[SCM] ffmpeg/master: Imported Upstream version 4:0.7~b1

siretart at users.alioth.debian.org siretart at users.alioth.debian.org
Tue Apr 19 11:36:50 UTC 2011


The following commit has been merged in the master branch:
commit 0ed2efd3a7a7a0aa314126f5c06d0757be3edb54
Author: Reinhard Tartler <siretart at tauware.de>
Date:   Tue Apr 19 12:45:53 2011 +0200

    Imported Upstream version 4:0.7~b1

diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..eac1758
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,45 @@
+.config
+.version
+*.o
+*.d
+*.exe
+*.ho
+*-example
+*-test
+*_g
+config.*
+doc/*.1
+doc/*.html
+doc/*.pod
+doxy
+ffmpeg
+ffplay
+ffprobe
+ffserver
+libavcodec/libavcodec*
+libavcore/libavcore*
+libavdevice/libavdevice*
+libavfilter/libavfilter*
+libavformat/libavformat*
+libavutil/avconfig.h
+libavutil/libavutil*
+libpostproc/libpostproc*
+libswscale/libswscale*
+tests/audiogen
+tests/base64
+tests/data
+tests/rotozoom
+tests/seek_test
+tests/tiny_psnr
+tests/videogen
+tests/vsynth1
+tests/vsynth2
+tools/cws2fws
+tools/graph2dot
+tools/lavfi-showfiltfmts
+tools/pktdumper
+tools/probetest
+tools/qt-faststart
+tools/trasher
+tools/trasher*.d
+version.h
diff --git a/CREDITS b/CREDITS
index 404cf38..4a53778 100644
--- a/CREDITS
+++ b/CREDITS
@@ -1,5 +1,7 @@
-This file contains the name of the people who have contributed to
-FFmpeg. The names are sorted alphabetically by last name.
+This file contains the names of some of the people who have contributed to
+Libav/FFmpeg. The names are sorted alphabetically by last name.  As this file is
+currently quite outdated and git serves as a much better tool for determining
+authorship, it remains here for historical reasons only.
 
 Dénes Balatoni
 Michel Bardiaux
diff --git a/Changelog b/Changelog
index 1ecc118..4bc6d31 100644
--- a/Changelog
+++ b/Changelog
@@ -1,6 +1,93 @@
 Entries are sorted chronologically from oldest to youngest within each release,
 releases are sorted from youngest to oldest.
 
+
+version <next>:
+
+- WebM support in Matroska de/muxer
+- low overhead Ogg muxing
+- MMS-TCP support
+- VP8 de/encoding via libvpx
+- Demuxer for On2's IVF format
+- Pictor/PC Paint decoder
+- HE-AAC v2 decoder
+- libfaad2 wrapper removed
+- DTS-ES extension (XCh) decoding support
+- native VP8 decoder
+- RTSP tunneling over HTTP
+- RTP depacketization of SVQ3
+- -strict inofficial replaced by -strict unofficial
+- ffplay -exitonkeydown and -exitonmousedown options added
+- native GSM / GSM MS decoder
+- RTP depacketization of QDM2
+- ANSI/ASCII art playback system
+- Lego Mindstorms RSO de/muxer
+- libavcore added
+- SubRip subtitle file muxer and demuxer
+- Chinese AVS encoding via libxavs
+- ffprobe -show_packets option added
+- RTP packetization of Theora and Vorbis
+- RTP depacketization of MP4A-LATM
+- RTP packetization and depacketization of VP8
+- hflip filter
+- Apple HTTP Live Streaming demuxer
+- a64 codec
+- MMS-HTTP support
+- G.722 ADPCM audio encoder/decoder
+- R10k video decoder
+- ocv_smooth filter
+- frei0r wrapper filter
+- change crop filter syntax to width:height:x:y
+- make the crop filter accept parametric expressions
+- make ffprobe accept AVFormatContext options
+- yadif filter
+- blackframe filter
+- Demuxer for Leitch/Harris' VR native stream format (LXF)
+- RTP depacketization of the X-QT QuickTime format
+- SAP (Session Announcement Protocol, RFC 2974) muxer and demuxer
+- cropdetect filter
+- ffmpeg -crop* options removed
+- transpose filter added
+- ffmpeg -force_key_frames option added
+- demuxer for receiving raw rtp:// URLs without an SDP description
+- single stream LATM/LOAS decoder
+- setpts filter added
+- Win64 support for optimized asm functions
+- MJPEG/AVI1 to JPEG/JFIF bitstream filter
+- ASS subtitle encoder and decoder
+- IEC 61937 encapsulation for E-AC3, TrueHD, DTS-HD (for HDMI passthrough)
+- overlay filter added
+- rename aspect filter to setdar, and pixelaspect to setsar
+- IEC 61937 demuxer
+- Mobotix .mxg demuxer
+- frei0r source added
+- hqdn3d filter added
+- RTP depacketization of QCELP
+- FLAC parser added
+- gradfun filter added
+- AMR-WB decoder
+- replace the ocv_smooth filter with a more generic ocv filter
+- Windows Televison (WTV) demuxer
+- FFmpeg metadata format muxer and demuxer
+- SubRip (srt) subtitle decoder
+- floating-point AC-3 encoder added
+- Lagarith decoder
+- ffmpeg -copytb option added
+- IVF muxer added
+- Wing Commander IV movies decoder added
+- movie source added
+- Bink version 'b' audio and video decoder
+- Bitmap Brothers JV playback system
+- Apple HTTP Live Streaming protocol handler
+- sndio support for playback and record
+- Linux framebuffer input device added
+- Chronomaster DFA decoder
+- Mobotix MxPEG decoder
+- AAC encoding via libvo-aacenc
+- AMR-WB encoding via libvo-amrwbenc
+- xWMA demuxer
+
+
 version 0.6:
 
 - PB-frame decoding for H.263
@@ -76,11 +163,7 @@ version 0.6:
 - 35% faster VP3/Theora decoding
 - faster AAC decoding
 - faster H.264 decoding
-- WebM support in Matroska de/muxer
-- low overhead Ogg muxing
-- VP8 de/encoding via libvpx
-- CODEC_CAP_EXPERIMENTAL added
-
+- RealAudio 1.0 (14.4K) encoder
 
 
 version 0.5:
@@ -245,7 +328,6 @@ version 0.5:
 - generic metadata API
 
 
-
 version 0.4.9-pre1:
 
 - DV encoder, DV muxer
@@ -330,7 +412,6 @@ version 0.4.9-pre1:
 - FunCom ISS audio file demuxer and according ADPCM decoding
 
 
-
 version 0.4.8:
 
 - MPEG-2 video encoding (Michael)
@@ -342,7 +423,6 @@ version 0.4.8:
 - Duck DK3 and DK4 ADPCM audio decoders (Mike Melanson)
 
 
-
 version 0.4.7:
 
 - RealAudio 1.0 (14_4) and 2.0 (28_8) native decoders. Author unknown, code from mplayerhq
@@ -384,7 +464,6 @@ version 0.4.7:
 .. And lots more new enhancements and fixes.
 
 
-
 version 0.4.6:
 
 - completely new integer only MPEG audio layer 1/2/3 decoder rewritten
@@ -422,7 +501,6 @@ version 0.4.6:
 - 16-bit and 15-bit RGB/BGR/GBR support (Bisqwit)
 
 
-
 version 0.4.5:
 
 - some header fixes (Zdenek Kabelac <kabi at informatics.muni.cz>)
@@ -454,7 +532,6 @@ version 0.4.5:
 - added JPEG image format support (input/output)
 
 
-
 version 0.4.4:
 
 - fixed some std header definitions (Bjorn Lindgren
@@ -480,7 +557,6 @@ version 0.4.4:
   segfault)
 
 
-
 version 0.4.3:
 
 - BGR24 patch (initial patch by Jeroen Vreeken <pe1rxq at amsat.org>)
@@ -502,7 +578,6 @@ version 0.4.3:
   instead of a protocol)
 
 
-
 version 0.4.2:
 
 - added H.263/MPEG-4/MSMPEG4 decoding support. MPEG-4 decoding support
@@ -533,7 +608,6 @@ version 0.4.1:
 - factorized some motion estimation code
 
 
-
 version 0.4.0:
 
 - removing grab code from ffserver and moved it to ffmpeg. Added
@@ -562,13 +636,11 @@ version 0.4.0:
   codecs
 
 
-
 version 0.3.4:
 
 - added stereo in MPEG audio encoder
 
 
-
 version 0.3.3:
 
 - added 'high quality' mode which use motion vectors. It can be used in
@@ -577,14 +649,12 @@ version 0.3.3:
   bitrates and large GOP size
 
 
-
 version 0.3.2: small fixes
 
 - ASF fixes
 - put_seek bug fix
 
 
-
 version 0.3.1: added avi/divx support
 
 - added AVI support
@@ -592,5 +662,4 @@ version 0.3.1: added avi/divx support
 - added sound for flash format (not tested)
 
 
-
 version 0.3: initial public release
diff --git a/Doxyfile b/Doxyfile
index ee233b9..5d80a2b 100644
--- a/Doxyfile
+++ b/Doxyfile
@@ -1,4 +1,4 @@
-# Doxyfile 1.3-rc1
+# Doxyfile 1.5.6
 
 # This file describes the settings to be used by the documentation system
 # doxygen (www.doxygen.org) for a project
@@ -11,13 +11,21 @@
 # Values that contain spaces should be placed between quotes (" ")
 
 #---------------------------------------------------------------------------
-# General configuration options
+# Project related configuration options
 #---------------------------------------------------------------------------
 
+# This tag specifies the encoding used for all characters in the config file
+# that follow. The default is UTF-8 which is also the encoding used for all
+# text before the first occurrence of this tag. Doxygen uses libiconv (or the
+# iconv built into libc) for the transcoding. See
+# http://www.gnu.org/software/libiconv for the list of possible encodings.
+
+DOXYFILE_ENCODING      = UTF-8
+
 # The PROJECT_NAME tag is a single word (or a sequence of words surrounded
 # by quotes) that should identify the project.
 
-PROJECT_NAME           = FFmpeg
+PROJECT_NAME           = Libav
 
 # The PROJECT_NUMBER tag can be used to enter a project or revision number.
 # This could be handy for archiving the generated documentation or
@@ -32,17 +40,238 @@ PROJECT_NUMBER         =
 
 OUTPUT_DIRECTORY       = doxy
 
+# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create
+# 4096 sub-directories (in 2 levels) under the output directory of each output
+# format and will distribute the generated files over these directories.
+# Enabling this option can be useful when feeding doxygen a huge amount of
+# source files, where putting all generated files in the same directory would
+# otherwise cause performance problems for the file system.
+
+CREATE_SUBDIRS         = NO
+
 # The OUTPUT_LANGUAGE tag is used to specify the language in which all
 # documentation generated by doxygen is written. Doxygen will use this
 # information to generate all constant output in the proper language.
 # The default language is English, other supported languages are:
-# Brazilian, Catalan, Chinese, Chinese-Traditional, Croatian, Czech, Danish, Dutch,
-# Finnish, French, German, Greek, Hungarian, Italian, Japanese, Japanese-en
-# (Japanese with english messages), Korean, Norwegian, Polish, Portuguese,
-# Romanian, Russian, Serbian, Slovak, Slovene, Spanish, Swedish and Ukrainian.
+# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional,
+# Croatian, Czech, Danish, Dutch, Farsi, Finnish, French, German, Greek,
+# Hungarian, Italian, Japanese, Japanese-en (Japanese with English messages),
+# Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian, Polish,
+# Portuguese, Romanian, Russian, Serbian, Slovak, Slovene, Spanish, Swedish,
+# and Ukrainian.
 
 OUTPUT_LANGUAGE        = English
 
+# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will
+# include brief member descriptions after the members that are listed in
+# the file and class documentation (similar to JavaDoc).
+# Set to NO to disable this.
+
+BRIEF_MEMBER_DESC      = YES
+
+# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend
+# the brief description of a member or function before the detailed description.
+# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the
+# brief descriptions will be completely suppressed.
+
+REPEAT_BRIEF           = YES
+
+# This tag implements a quasi-intelligent brief description abbreviator
+# that is used to form the text in various listings. Each string
+# in this list, if found as the leading text of the brief description, will be
+# stripped from the text and the result after processing the whole list, is
+# used as the annotated text. Otherwise, the brief description is used as-is.
+# If left blank, the following values are used ("$name" is automatically
+# replaced with the name of the entity): "The $name class" "The $name widget"
+# "The $name file" "is" "provides" "specifies" "contains"
+# "represents" "a" "an" "the"
+
+ABBREVIATE_BRIEF       =
+
+# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then
+# Doxygen will generate a detailed section even if there is only a brief
+# description.
+
+ALWAYS_DETAILED_SEC    = NO
+
+# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all
+# inherited members of a class in the documentation of that class as if those
+# members were ordinary class members. Constructors, destructors and assignment
+# operators of the base classes will not be shown.
+
+INLINE_INHERITED_MEMB  = NO
+
+# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full
+# path before files name in the file list and in the header files. If set
+# to NO the shortest path that makes the file name unique will be used.
+
+FULL_PATH_NAMES        = YES
+
+# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag
+# can be used to strip a user-defined part of the path. Stripping is
+# only done if one of the specified strings matches the left-hand part of
+# the path. The tag can be used to show relative paths in the file list.
+# If left blank the directory from which doxygen is run is used as the
+# path to strip.
+
+STRIP_FROM_PATH        = .
+
+# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of
+# the path mentioned in the documentation of a class, which tells
+# the reader which header file to include in order to use a class.
+# If left blank only the name of the header file containing the class
+# definition is used. Otherwise one should specify the include paths that
+# are normally passed to the compiler using the -I flag.
+
+STRIP_FROM_INC_PATH    =
+
+# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter
+# (but less readable) file names. This can be useful is your file systems
+# doesn't support long names like on DOS, Mac, or CD-ROM.
+
+SHORT_NAMES            = NO
+
+# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen
+# will interpret the first line (until the first dot) of a JavaDoc-style
+# comment as the brief description. If set to NO, the JavaDoc
+# comments will behave just like regular Qt-style comments
+# (thus requiring an explicit @brief command for a brief description.)
+
+JAVADOC_AUTOBRIEF      = YES
+
+# If the QT_AUTOBRIEF tag is set to YES then Doxygen will
+# interpret the first line (until the first dot) of a Qt-style
+# comment as the brief description. If set to NO, the comments
+# will behave just like regular Qt-style comments (thus requiring
+# an explicit \brief command for a brief description.)
+
+QT_AUTOBRIEF           = NO
+
+# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen
+# treat a multi-line C++ special comment block (i.e. a block of //! or ///
+# comments) as a brief description. This used to be the default behaviour.
+# The new default is to treat a multi-line C++ comment block as a detailed
+# description. Set this tag to YES if you prefer the old behaviour instead.
+
+MULTILINE_CPP_IS_BRIEF = NO
+
+# If the DETAILS_AT_TOP tag is set to YES then Doxygen
+# will output the detailed description near the top, like JavaDoc.
+# If set to NO, the detailed description appears after the member
+# documentation.
+
+DETAILS_AT_TOP         = NO
+
+# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented
+# member inherits the documentation from any documented member that it
+# re-implements.
+
+INHERIT_DOCS           = YES
+
+# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce
+# a new page for each member. If set to NO, the documentation of a member will
+# be part of the file/class/namespace that contains it.
+
+SEPARATE_MEMBER_PAGES  = NO
+
+# The TAB_SIZE tag can be used to set the number of spaces in a tab.
+# Doxygen uses this value to replace tabs by spaces in code fragments.
+
+TAB_SIZE               = 8
+
+# This tag can be used to specify a number of aliases that acts
+# as commands in the documentation. An alias has the form "name=value".
+# For example adding "sideeffect=\par Side Effects:\n" will allow you to
+# put the command \sideeffect (or @sideeffect) in the documentation, which
+# will result in a user-defined paragraph with heading "Side Effects:".
+# You can put \n's in the value part of an alias to insert newlines.
+
+ALIASES                =
+
+# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C
+# sources only. Doxygen will then generate output that is more tailored for C.
+# For instance, some of the names that are used will be different. The list
+# of all members will be omitted, etc.
+
+OPTIMIZE_OUTPUT_FOR_C  = YES
+
+# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java
+# sources only. Doxygen will then generate output that is more tailored for
+# Java. For instance, namespaces will be presented as packages, qualified
+# scopes will look different, etc.
+
+OPTIMIZE_OUTPUT_JAVA   = NO
+
+# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran
+# sources only. Doxygen will then generate output that is more tailored for
+# Fortran.
+
+OPTIMIZE_FOR_FORTRAN   = NO
+
+# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL
+# sources. Doxygen will then generate output that is tailored for
+# VHDL.
+
+OPTIMIZE_OUTPUT_VHDL   = NO
+
+# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want
+# to include (a tag file for) the STL sources as input, then you should
+# set this tag to YES in order to let doxygen match functions declarations and
+# definitions whose arguments contain STL classes (e.g. func(std::string); v.s.
+# func(std::string) {}). This also make the inheritance and collaboration
+# diagrams that involve STL classes more complete and accurate.
+
+BUILTIN_STL_SUPPORT    = NO
+
+# If you use Microsoft's C++/CLI language, you should set this option to YES to
+# enable parsing support.
+
+CPP_CLI_SUPPORT        = NO
+
+# Set the SIP_SUPPORT tag to YES if your project consists of sip sources only.
+# Doxygen will parse them like normal C++ but will assume all classes use public
+# instead of private inheritance when no explicit protection keyword is present.
+
+SIP_SUPPORT            = NO
+
+# For Microsoft's IDL there are propget and propput attributes to indicate getter
+# and setter methods for a property. Setting this option to YES (the default)
+# will make doxygen to replace the get and set methods by a property in the
+# documentation. This will only work if the methods are indeed getting or
+# setting a simple type. If this is not the case, or you want to show the
+# methods anyway, you should set this option to NO.
+
+IDL_PROPERTY_SUPPORT   = YES
+
+# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC
+# tag is set to YES, then doxygen will reuse the documentation of the first
+# member in the group (if any) for the other members of the group. By default
+# all members of a group must be documented explicitly.
+
+DISTRIBUTE_GROUP_DOC   = NO
+
+# Set the SUBGROUPING tag to YES (the default) to allow class member groups of
+# the same type (for instance a group of public functions) to be put as a
+# subgroup of that type (e.g. under the Public Functions section). Set it to
+# NO to prevent subgrouping. Alternatively, this can be done per class using
+# the \nosubgrouping command.
+
+SUBGROUPING            = YES
+
+# When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum
+# is documented as struct, union, or enum with the name of the typedef. So
+# typedef struct TypeS {} TypeT, will appear in the documentation as a struct
+# with name TypeT. When disabled the typedef will appear as a member of a file,
+# namespace, or class. And the struct will be named TypeS. This can typically
+# be useful for C code in case the coding convention dictates that all compound
+# types are typedef'ed and only the typedef is referenced, never the tag name.
+
+TYPEDEF_HIDES_STRUCT   = NO
+
+#---------------------------------------------------------------------------
+# Build related configuration options
+#---------------------------------------------------------------------------
+
 # If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in
 # documentation are documented, even if no documentation was available.
 # Private class members and static file members will be hidden unless
@@ -66,6 +295,21 @@ EXTRACT_STATIC         = YES
 
 EXTRACT_LOCAL_CLASSES  = YES
 
+# This flag is only useful for Objective-C code. When set to YES local
+# methods, which are defined in the implementation section but not in
+# the interface are included in the documentation.
+# If set to NO (the default) only methods in the interface are included.
+
+EXTRACT_LOCAL_METHODS  = NO
+
+# If this flag is set to YES, the members of anonymous namespaces will be
+# extracted and appear in the documentation as a namespace called
+# 'anonymous_namespace{file}', where file will be replaced with the base
+# name of the file that contains the anonymous namespace. By default
+# anonymous namespace are hidden.
+
+EXTRACT_ANON_NSPACES   = NO
+
 # If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all
 # undocumented members of documented classes, files or namespaces.
 # If set to NO (the default) these members will be included in the
@@ -76,7 +320,7 @@ HIDE_UNDOC_MEMBERS     = NO
 
 # If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all
 # undocumented classes that are normally visible in the class hierarchy.
-# If set to NO (the default) these class will be included in the various
+# If set to NO (the default) these classes will be included in the various
 # overviews. This option has no effect if EXTRACT_ALL is enabled.
 
 HIDE_UNDOC_CLASSES     = NO
@@ -95,46 +339,6 @@ HIDE_FRIEND_COMPOUNDS  = NO
 
 HIDE_IN_BODY_DOCS      = NO
 
-# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will
-# include brief member descriptions after the members that are listed in
-# the file and class documentation (similar to JavaDoc).
-# Set to NO to disable this.
-
-BRIEF_MEMBER_DESC      = YES
-
-# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend
-# the brief description of a member or function before the detailed description.
-# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the
-# brief descriptions will be completely suppressed.
-
-REPEAT_BRIEF           = YES
-
-# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then
-# Doxygen will generate a detailed section even if there is only a brief
-# description.
-
-ALWAYS_DETAILED_SEC    = NO
-
-# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all inherited
-# members of a class in the documentation of that class as if those members were
-# ordinary class members. Constructors, destructors and assignment operators of
-# the base classes will not be shown.
-
-INLINE_INHERITED_MEMB  = NO
-
-# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full
-# path before files name in the file list and in the header files. If set
-# to NO the shortest path that makes the file name unique will be used.
-
-FULL_PATH_NAMES        = YES
-
-# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag
-# can be used to strip a user defined part of the path. Stripping is
-# only done if one of the specified strings matches the left-hand part of
-# the path. It is allowed to use relative paths in the argument list.
-
-STRIP_FROM_PATH        = .
-
 # The INTERNAL_DOCS tag determines if documentation
 # that is typed after a \internal command is included. If the tag is set
 # to NO (the default) then the documentation will be excluded.
@@ -143,66 +347,25 @@ STRIP_FROM_PATH        = .
 INTERNAL_DOCS          = NO
 
 # If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate
-# file names in lower case letters. If set to YES upper case letters are also
+# file names in lower-case letters. If set to YES upper-case letters are also
 # allowed. This is useful if you have classes or files whose names only differ
 # in case and if your file system supports case sensitive file names. Windows
-# users are adviced to set this option to NO.
+# and Mac users are advised to set this option to NO.
 
 CASE_SENSE_NAMES       = YES
 
-# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter
-# (but less readable) file names. This can be useful is your file systems
-# doesn't support long names like on DOS, Mac, or CD-ROM.
-
-SHORT_NAMES            = NO
-
 # If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen
 # will show members with their full class and namespace scopes in the
 # documentation. If set to YES the scope will be hidden.
 
 HIDE_SCOPE_NAMES       = NO
 
-# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen
-# will generate a verbatim copy of the header file for each class for
-# which an include is specified. Set to NO to disable this.
-
-VERBATIM_HEADERS       = YES
-
 # If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen
-# will put list of the files that are included by a file in the documentation
+# will put a list of the files that are included by a file in the documentation
 # of that file.
 
 SHOW_INCLUDE_FILES     = YES
 
-# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen
-# will interpret the first line (until the first dot) of a JavaDoc-style
-# comment as the brief description. If set to NO, the JavaDoc
-# comments  will behave just like the Qt-style comments (thus requiring an
-# explict @brief command for a brief description.
-
-JAVADOC_AUTOBRIEF      = YES
-
-# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen
-# treat a multi-line C++ special comment block (i.e. a block of //! or ///
-# comments) as a brief description. This used to be the default behaviour.
-# The new default is to treat a multi-line C++ comment block as a detailed
-# description. Set this tag to YES if you prefer the old behaviour instead.
-
-MULTILINE_CPP_IS_BRIEF = NO
-
-# If the DETAILS_AT_TOP tag is set to YES then Doxygen
-# will output the detailed description near the top, like JavaDoc.
-# If set to NO, the detailed description appears after the member
-# documentation.
-
-DETAILS_AT_TOP         = NO
-
-# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented
-# member inherits the documentation from any documented member that it
-# reimplements.
-
-INHERIT_DOCS           = YES
-
 # If the INLINE_INFO tag is set to YES (the default) then a tag [inline]
 # is inserted in the documentation for inline members.
 
@@ -215,17 +378,28 @@ INLINE_INFO            = YES
 
 SORT_MEMBER_DOCS       = YES
 
-# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC
-# tag is set to YES, then doxygen will reuse the documentation of the first
-# member in the group (if any) for the other members of the group. By default
-# all members of a group must be documented explicitly.
+# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the
+# brief documentation of file, namespace and class members alphabetically
+# by member name. If set to NO (the default) the members will appear in
+# declaration order.
 
-DISTRIBUTE_GROUP_DOC   = NO
+SORT_BRIEF_DOCS        = NO
 
-# The TAB_SIZE tag can be used to set the number of spaces in a tab.
-# Doxygen uses this value to replace tabs by spaces in code fragments.
+# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the
+# hierarchy of group names into alphabetical order. If set to NO (the default)
+# the group names will appear in their defined order.
 
-TAB_SIZE               = 8
+SORT_GROUP_NAMES       = NO
+
+# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be
+# sorted by fully-qualified names, including namespaces. If set to
+# NO (the default), the class list will be sorted only by class name,
+# not including the namespace part.
+# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.
+# Note: This option applies only to the class list, not to the
+# alphabetical list.
+
+SORT_BY_SCOPE_NAME     = NO
 
 # The GENERATE_TODOLIST tag can be used to enable (YES) or
 # disable (NO) the todo list. This list is created by putting \todo
@@ -251,22 +425,13 @@ GENERATE_BUGLIST       = YES
 
 GENERATE_DEPRECATEDLIST= YES
 
-# This tag can be used to specify a number of aliases that acts
-# as commands in the documentation. An alias has the form "name=value".
-# For example adding "sideeffect=\par Side Effects:\n" will allow you to
-# put the command \sideeffect (or @sideeffect) in the documentation, which
-# will result in a user defined paragraph with heading "Side Effects:".
-# You can put \n's in the value part of an alias to insert newlines.
-
-ALIASES                =
-
 # The ENABLED_SECTIONS tag can be used to enable conditional
 # documentation sections, marked by \if sectionname ... \endif.
 
 ENABLED_SECTIONS       =
 
 # The MAX_INITIALIZER_LINES tag determines the maximum number of lines
-# the initial value of a variable or define consist of for it to appear in
+# the initial value of a variable or define consists of for it to appear in
 # the documentation. If the initializer consists of more lines than specified
 # here it will be hidden. Use a value of 0 to hide initializers completely.
 # The appearance of the initializer of individual variables and defines in the
@@ -275,26 +440,40 @@ ENABLED_SECTIONS       =
 
 MAX_INITIALIZER_LINES  = 30
 
-# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources
-# only. Doxygen will then generate output that is more tailored for C.
-# For instance some of the names that are used will be different. The list
-# of all members will be omitted, etc.
-
-OPTIMIZE_OUTPUT_FOR_C  = YES
-
-# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java sources
-# only. Doxygen will then generate output that is more tailored for Java.
-# For instance namespaces will be presented as packages, qualified scopes
-# will look different, etc.
-
-OPTIMIZE_OUTPUT_JAVA   = NO
-
 # Set the SHOW_USED_FILES tag to NO to disable the list of files generated
 # at the bottom of the documentation of classes and structs. If set to YES the
 # list will mention the files that were used to generate the documentation.
 
 SHOW_USED_FILES        = YES
 
+# If the sources in your project are distributed over multiple directories
+# then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy
+# in the documentation. The default is NO.
+
+SHOW_DIRECTORIES       = NO
+
+# Set the SHOW_FILES tag to NO to disable the generation of the Files page.
+# This will remove the Files entry from the Quick Index and from the
+# Folder Tree View (if specified). The default is YES.
+
+SHOW_FILES             = YES
+
+# Set the SHOW_NAMESPACES tag to NO to disable the generation of the
+# Namespaces page.  This will remove the Namespaces entry from the Quick Index
+# and from the Folder Tree View (if specified). The default is YES.
+
+SHOW_NAMESPACES        = YES
+
+# The FILE_VERSION_FILTER tag can be used to specify a program or script that
+# doxygen should invoke to get the current version for each file (typically from
+# the version control system). Doxygen will invoke the program by executing (via
+# popen()) the command <command> <input-file>, where <command> is the value of
+# the FILE_VERSION_FILTER tag, and <input-file> is the name of an input file
+# provided by doxygen. Whatever the program writes to standard output
+# is used as the file version. See the manual for examples.
+
+FILE_VERSION_FILTER    =
+
 #---------------------------------------------------------------------------
 # configuration options related to warning and progress messages
 #---------------------------------------------------------------------------
@@ -302,7 +481,7 @@ SHOW_USED_FILES        = YES
 # The QUIET tag can be used to turn on/off the messages that are generated
 # by doxygen. Possible values are YES and NO. If left blank NO is used.
 
-QUIET                  = NO
+QUIET                  = YES
 
 # The WARNINGS tag can be used to turn on/off the warning messages that are
 # generated by doxygen. Possible values are YES and NO. If left blank
@@ -316,10 +495,27 @@ WARNINGS               = YES
 
 WARN_IF_UNDOCUMENTED   = YES
 
+# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for
+# potential errors in the documentation, such as not documenting some
+# parameters in a documented function, or documenting parameters that
+# don't exist or using markup commands wrongly.
+
+WARN_IF_DOC_ERROR      = YES
+
+# This WARN_NO_PARAMDOC option can be abled to get warnings for
+# functions that are documented, but have no documentation for their parameters
+# or return value. If set to NO (the default) doxygen will only warn about
+# wrong or incomplete parameter documentation, but not about the absence of
+# documentation.
+
+WARN_NO_PARAMDOC       = NO
+
 # The WARN_FORMAT tag determines the format of the warning messages that
 # doxygen can produce. The string should contain the $file, $line, and $text
 # tags, which will be replaced by the file and line number from which the
-# warning originated and the warning text.
+# warning originated and the warning text. Optionally the format may contain
+# $version, which will be replaced by the version of the file (if it could
+# be obtained via FILE_VERSION_FILTER)
 
 WARN_FORMAT            = "$file:$line: $text"
 
@@ -340,12 +536,20 @@ WARN_LOGFILE           =
 
 INPUT                  =
 
+# This tag can be used to specify the character encoding of the source files
+# that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is
+# also the default input encoding. Doxygen uses libiconv (or the iconv built
+# into libc) for the transcoding. See http://www.gnu.org/software/libiconv for
+# the list of possible encodings.
+
+INPUT_ENCODING         = UTF-8
+
 # If the value of the INPUT tag contains directories, you can use the
 # FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp
 # and *.h) to filter out the source-files in the directories. If left
 # blank the following patterns are tested:
-# *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx *.hpp
-# *.h++ *.idl *.odl
+# *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx
+# *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.py *.f90
 
 FILE_PATTERNS          =
 
@@ -361,16 +565,27 @@ RECURSIVE              = YES
 
 EXCLUDE                =
 
-# The EXCLUDE_SYMLINKS tag can be used select whether or not files or directories
-# that are symbolic links (a Unix filesystem feature) are excluded from the input.
+# The EXCLUDE_SYMLINKS tag can be used select whether or not files or
+# directories that are symbolic links (a Unix filesystem feature) are excluded
+# from the input.
 
 EXCLUDE_SYMLINKS       = NO
 
 # If the value of the INPUT tag contains directories, you can use the
 # EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude
-# certain files from those directories.
+# certain files from those directories. Note that the wildcards are matched
+# against the file with absolute path, so to exclude all test directories
+# for example use the pattern */test/*
+
+EXCLUDE_PATTERNS       = *.git *.d
 
-EXCLUDE_PATTERNS       = *.svn *.git
+# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names
+# (namespaces, classes, functions, etc.) that should be excluded from the
+# output. The symbol name can be a fully qualified name, a word, or if the
+# wildcard * is used, a substring. Examples: ANamespace, AClass,
+# AClass::ANamespace, ANamespace::*Test
+
+EXCLUDE_SYMBOLS        =
 
 # The EXAMPLE_PATH tag can be used to specify one or more files or
 # directories that contain example code fragments that are included (see
@@ -403,10 +618,20 @@ IMAGE_PATH             =
 # by executing (via popen()) the command <filter> <input-file>, where <filter>
 # is the value of the INPUT_FILTER tag, and <input-file> is the name of an
 # input file. Doxygen will then use the output that the filter program writes
-# to standard output.
+# to standard output.  If FILTER_PATTERNS is specified, this tag will be
+# ignored.
 
 INPUT_FILTER           =
 
+# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern
+# basis.  Doxygen will compare the file name with each pattern and apply the
+# filter if there is a match.  The filters are a list of the form:
+# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further
+# info on how filters are used. If FILTER_PATTERNS is empty, INPUT_FILTER
+# is applied to all files.
+
+FILTER_PATTERNS        =
+
 # If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using
 # INPUT_FILTER) will be used to filter the input files when producing source
 # files to browse (i.e. when SOURCE_BROWSER is set to YES).
@@ -419,6 +644,8 @@ FILTER_SOURCE_FILES    = NO
 
 # If the SOURCE_BROWSER tag is set to YES then a list of source files will
 # be generated. Documented entities will be cross-referenced with these sources.
+# Note: To get rid of all source code in the generated output, make sure also
+# VERBATIM_HEADERS is set to NO.
 
 SOURCE_BROWSER         = YES
 
@@ -433,18 +660,39 @@ INLINE_SOURCES         = NO
 
 STRIP_CODE_COMMENTS    = YES
 
-# If the REFERENCED_BY_RELATION tag is set to YES (the default)
+# If the REFERENCED_BY_RELATION tag is set to YES
 # then for each documented function all documented
 # functions referencing it will be listed.
 
 REFERENCED_BY_RELATION = YES
 
-# If the REFERENCES_RELATION tag is set to YES (the default)
+# If the REFERENCES_RELATION tag is set to YES
 # then for each documented function all documented entities
 # called/used by that function will be listed.
 
 REFERENCES_RELATION    = NO
 
+# If the REFERENCES_LINK_SOURCE tag is set to YES (the default)
+# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from
+# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will
+# link to the source code.  Otherwise they will link to the documentstion.
+
+REFERENCES_LINK_SOURCE = YES
+
+# If the USE_HTAGS tag is set to YES then the references to source code
+# will point to the HTML generated by the htags(1) tool instead of doxygen
+# built-in source browser. The htags tool is part of GNU's global source
+# tagging system (see http://www.gnu.org/software/global/global.html). You
+# will need version 4.8.6 or higher.
+
+USE_HTAGS              = NO
+
+# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen
+# will generate a verbatim copy of the header file for each class for
+# which an include is specified. Set to NO to disable this.
+
+VERBATIM_HEADERS       = YES
+
 #---------------------------------------------------------------------------
 # configuration options related to the alphabetical class index
 #---------------------------------------------------------------------------
@@ -501,10 +749,12 @@ HTML_HEADER            =
 
 HTML_FOOTER            =
 
-# The HTML_STYLESHEET tag can be used to specify a user defined cascading
+# The HTML_STYLESHEET tag can be used to specify a user-defined cascading
 # style sheet that is used by each HTML page. It can be used to
 # fine-tune the look of the HTML output. If the tag is left blank doxygen
-# will generate a default style sheet
+# will generate a default style sheet. Note that doxygen will try to copy
+# the style sheet file to the HTML output directory, so don't put your own
+# stylesheet in the HTML output directory as well, or it will be erased!
 
 HTML_STYLESHEET        =
 
@@ -516,22 +766,55 @@ HTML_ALIGN_MEMBERS     = YES
 
 # If the GENERATE_HTMLHELP tag is set to YES, additional index files
 # will be generated that can be used as input for tools like the
-# Microsoft HTML help workshop to generate a compressed HTML help file (.chm)
+# Microsoft HTML help workshop to generate a compiled HTML help file (.chm)
 # of the generated HTML documentation.
 
 GENERATE_HTMLHELP      = NO
 
+# If the GENERATE_DOCSET tag is set to YES, additional index files
+# will be generated that can be used as input for Apple's Xcode 3
+# integrated development environment, introduced with OSX 10.5 (Leopard).
+# To create a documentation set, doxygen will generate a Makefile in the
+# HTML output directory. Running make will produce the docset in that
+# directory and running "make install" will install the docset in
+# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find
+# it at startup.
+
+GENERATE_DOCSET        = NO
+
+# When GENERATE_DOCSET tag is set to YES, this tag determines the name of the
+# feed. A documentation feed provides an umbrella under which multiple
+# documentation sets from a single provider (such as a company or product suite)
+# can be grouped.
+
+DOCSET_FEEDNAME        = "Doxygen generated docs"
+
+# When GENERATE_DOCSET tag is set to YES, this tag specifies a string that
+# should uniquely identify the documentation set bundle. This should be a
+# reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen
+# will append .docset to the name.
+
+DOCSET_BUNDLE_ID       = org.doxygen.Project
+
+# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML
+# documentation will contain sections that can be hidden and shown after the
+# page has loaded. For this to work a browser that supports
+# JavaScript and DHTML is required (for instance Mozilla 1.0+, Firefox
+# Netscape 6.0+, Internet explorer 5.0+, Konqueror, or Safari).
+
+HTML_DYNAMIC_SECTIONS  = NO
+
 # If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can
 # be used to specify the file name of the resulting .chm file. You
 # can add a path in front of the file if the result should not be
-# written to the html output dir.
+# written to the html output directory.
 
 CHM_FILE               =
 
 # If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can
 # be used to specify the location (absolute path including file name) of
-# the HTML help compiler (hhc.exe). If non empty doxygen will try to run
-# the html help compiler on the generated index.hhp.
+# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run
+# the HTML help compiler on the generated index.hhp.
 
 HHC_LOCATION           =
 
@@ -541,6 +824,12 @@ HHC_LOCATION           =
 
 GENERATE_CHI           = NO
 
+# If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING
+# is used to encode HtmlHelp index (hhk), content (hhc) and project file
+# content.
+
+CHM_INDEX_ENCODING     =
+
 # If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag
 # controls whether a binary table of contents is generated (YES) or a
 # normal table of contents (NO) in the .chm file.
@@ -548,7 +837,7 @@ GENERATE_CHI           = NO
 BINARY_TOC             = NO
 
 # The TOC_EXPAND flag can be set to YES to add extra items for group members
-# to the contents of the Html help documentation and to the tree view.
+# to the contents of the HTML help documentation and to the tree view.
 
 TOC_EXPAND             = NO
 
@@ -563,13 +852,20 @@ DISABLE_INDEX          = NO
 
 ENUM_VALUES_PER_LINE   = 4
 
-# If the GENERATE_TREEVIEW tag is set to YES, a side panel will be
-# generated containing a tree-like index structure (just like the one that
+# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index
+# structure should be generated to display hierarchical information.
+# If the tag value is set to FRAME, a side panel will be generated
+# containing a tree-like index structure (just like the one that
 # is generated for HTML Help). For this to work a browser that supports
-# JavaScript and frames is required (for instance Mozilla, Netscape 4.0+,
-# or Internet explorer 4.0+). Note that for large projects the tree generation
-# can take a very long time. In such cases it is better to disable this feature.
-# Windows users are probably better off using the HTML help feature.
+# JavaScript, DHTML, CSS and frames is required (for instance Mozilla 1.0+,
+# Netscape 6.0+, Internet explorer 5.0+, or Konqueror). Windows users are
+# probably better off using the HTML help feature. Other possible values
+# for this tag are: HIERARCHIES, which will generate the Groups, Directories,
+# and Class Hiererachy pages using a tree view instead of an ordered list;
+# ALL, which combines the behavior of FRAME and HIERARCHIES; and NONE, which
+# disables this behavior completely. For backwards compatibility with previous
+# releases of Doxygen, the values YES and NO are equivalent to FRAME and NONE
+# respectively.
 
 GENERATE_TREEVIEW      = NO
 
@@ -579,6 +875,14 @@ GENERATE_TREEVIEW      = NO
 
 TREEVIEW_WIDTH         = 250
 
+# Use this tag to change the font size of Latex formulas included
+# as images in the HTML documentation. The default is 10. Note that
+# when you change the font size after a successful doxygen run you need
+# to manually remove any form_*.png images from the HTML output directory
+# to force them to be regenerated.
+
+FORMULA_FONTSIZE       = 10
+
 #---------------------------------------------------------------------------
 # configuration options related to the LaTeX output
 #---------------------------------------------------------------------------
@@ -586,7 +890,7 @@ TREEVIEW_WIDTH         = 250
 # If the GENERATE_LATEX tag is set to YES (the default) Doxygen will
 # generate Latex output.
 
-GENERATE_LATEX         = YES
+GENERATE_LATEX         = NO
 
 # The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put.
 # If a relative path is entered the value of OUTPUT_DIRECTORY will be
@@ -649,6 +953,12 @@ USE_PDFLATEX           = NO
 
 LATEX_BATCHMODE        = NO
 
+# If LATEX_HIDE_INDICES is set to YES then doxygen will not
+# include the index chapters (such as File Index, Compound Index, etc.)
+# in the output.
+
+LATEX_HIDE_INDICES     = NO
+
 #---------------------------------------------------------------------------
 # configuration options related to the RTF output
 #---------------------------------------------------------------------------
@@ -681,7 +991,7 @@ COMPACT_RTF            = NO
 RTF_HYPERLINKS         = NO
 
 # Load stylesheet definitions from file. Syntax is similar to doxygen's
-# config file, i.e. a series of assigments. You only have to provide
+# config file, i.e. a series of assignments. You only have to provide
 # replacements, missing definitions are set to their default value.
 
 RTF_STYLESHEET_FILE    =
@@ -725,12 +1035,16 @@ MAN_LINKS              = NO
 
 # If the GENERATE_XML tag is set to YES Doxygen will
 # generate an XML file that captures the structure of
-# the code including all documentation. Note that this
-# feature is still experimental and incomplete at the
-# moment.
+# the code including all documentation.
 
 GENERATE_XML           = NO
 
+# The XML_OUTPUT tag is used to specify where the XML pages will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `xml' will be used as the default path.
+
+XML_OUTPUT             = xml
+
 # The XML_SCHEMA tag can be used to specify an XML schema,
 # which can be used by a validating XML parser to check the
 # syntax of the XML files.
@@ -743,6 +1057,13 @@ XML_SCHEMA             =
 
 XML_DTD                =
 
+# If the XML_PROGRAMLISTING tag is set to YES Doxygen will
+# dump the program listings (including syntax highlighting
+# and cross-referencing information) to the XML output. Note that
+# enabling this will significantly increase the size of the XML output.
+
+XML_PROGRAMLISTING     = YES
+
 #---------------------------------------------------------------------------
 # configuration options for the AutoGen Definitions output
 #---------------------------------------------------------------------------
@@ -807,7 +1128,7 @@ MACRO_EXPANSION        = YES
 
 # If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES
 # then the macro expansion is limited to the macros specified with the
-# PREDEFINED and EXPAND_AS_PREDEFINED tags.
+# PREDEFINED and EXPAND_AS_DEFINED tags.
 
 EXPAND_ONLY_PREDEF     = YES
 
@@ -833,7 +1154,9 @@ INCLUDE_FILE_PATTERNS  =
 # are defined before the preprocessor is started (similar to the -D option of
 # gcc). The argument of the tag is a list of macros of the form: name
 # or name=definition (no spaces). If the definition and the = are
-# omitted =1 is assumed.
+# omitted =1 is assumed. To prevent a macro definition from being
+# undefined via #undef or recursively expanded use the := operator
+# instead of the = operator.
 
 PREDEFINED             = __attribute__(x)="" "RENAME(x)=x ## _TMPL" "DEF(x)=x ## _TMPL" \
                          HAVE_AV_CONFIG_H HAVE_MMX HAVE_MMX2 HAVE_AMD3DNOW \
@@ -849,16 +1172,29 @@ EXPAND_AS_DEFINED      = declare_idct(idct, table, idct_row_head, idct_row, idct
 # If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then
 # doxygen's preprocessor will remove all function-like macros that are alone
 # on a line, have an all uppercase name, and do not end with a semicolon. Such
-# function macros are typically used for boiler-plate code, and will confuse the
-# parser if not removed.
+# function macros are typically used for boiler-plate code, and will confuse
+# the parser if not removed.
 
 SKIP_FUNCTION_MACROS   = YES
 
 #---------------------------------------------------------------------------
-# Configuration::addtions related to external references
+# Configuration::additions related to external references
 #---------------------------------------------------------------------------
 
-# The TAGFILES tag can be used to specify one or more tagfiles.
+# The TAGFILES option can be used to specify one or more tagfiles.
+# Optionally an initial location of the external documentation
+# can be added for each tagfile. The format of a tag file without
+# this location is as follows:
+#   TAGFILES = file1 file2 ...
+# Adding location for the tag files is done as follows:
+#   TAGFILES = file1=loc1 "file2 = loc2" ...
+# where "loc1" and "loc2" can be relative or absolute paths or
+# URLs. If a location is present for each tag, the installdox tool
+# does not have to be run to correct the links.
+# Note that each tag file must have a unique name
+# (where the name does NOT include the path)
+# If a tag file is not located in the directory in which doxygen
+# is run, you must also specify the path to the tagfile here.
 
 TAGFILES               =
 
@@ -889,13 +1225,23 @@ PERL_PATH              = /usr/bin/perl
 #---------------------------------------------------------------------------
 
 # If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will
-# generate a inheritance diagram (in Html, RTF and LaTeX) for classes with base or
-# super classes. Setting the tag to NO turns the diagrams off. Note that this
-# option is superceded by the HAVE_DOT option below. This is only a fallback. It is
-# recommended to install and use dot, since it yield more powerful graphs.
+# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base
+# or super classes. Setting the tag to NO turns the diagrams off. Note that
+# this option is superseded by the HAVE_DOT option below. This is only a
+# fallback. It is recommended to install and use dot, since it yields more
+# powerful graphs.
 
 CLASS_DIAGRAMS         = YES
 
+# You can define message sequence charts within doxygen comments using the \msc
+# command. Doxygen will then run the mscgen tool (see
+# http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the
+# documentation. The MSCGEN_PATH tag allows you to specify the directory where
+# the mscgen tool resides. If left empty the tool is assumed to be found in the
+# default search path.
+
+MSCGEN_PATH            =
+
 # If set to YES, the inheritance and collaboration graphs will hide
 # inheritance and usage relations if the target is undocumented
 # or is not a class.
@@ -909,6 +1255,24 @@ HIDE_UNDOC_RELATIONS   = YES
 
 HAVE_DOT               = NO
 
+# By default doxygen will write a font called FreeSans.ttf to the output
+# directory and reference it in all dot files that doxygen generates. This
+# font does not include all possible unicode characters however, so when you need
+# these (or just want a differently looking font) you can specify the font name
+# using DOT_FONTNAME. You need need to make sure dot is able to find the font,
+# which can be done by putting it in a standard location or by setting the
+# DOTFONTPATH environment variable or by setting DOT_FONTPATH to the directory
+# containing the font.
+
+DOT_FONTNAME           = FreeSans
+
+# By default doxygen will tell dot to use the output directory to look for the
+# FreeSans.ttf font (which doxygen will put there itself). If you specify a
+# different font using DOT_FONTNAME you can set the path where dot
+# can find it using this tag.
+
+DOT_FONTPATH           =
+
 # If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen
 # will generate a graph for each documented class showing the direct and
 # indirect inheritance relations. Setting this tag to YES will force the
@@ -923,6 +1287,17 @@ CLASS_GRAPH            = YES
 
 COLLABORATION_GRAPH    = YES
 
+# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen
+# will generate a graph for groups, showing the direct groups dependencies
+
+GROUP_GRAPHS           = YES
+
+# If the UML_LOOK tag is set to YES doxygen will generate inheritance and
+# collaboration diagrams in a style similar to the OMG's Unified Modeling
+# Language.
+
+UML_LOOK               = NO
+
 # If set to YES, the inheritance and collaboration graphs will show the
 # relations between templates and their instances.
 
@@ -942,11 +1317,34 @@ INCLUDE_GRAPH          = YES
 
 INCLUDED_BY_GRAPH      = YES
 
+# If the CALL_GRAPH and HAVE_DOT options are set to YES then
+# doxygen will generate a call dependency graph for every global function
+# or class method. Note that enabling this option will significantly increase
+# the time of a run. So in most cases it will be better to enable call graphs
+# for selected functions only using the \callgraph command.
+
+CALL_GRAPH             = NO
+
+# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then
+# doxygen will generate a caller dependency graph for every global function
+# or class method. Note that enabling this option will significantly increase
+# the time of a run. So in most cases it will be better to enable caller
+# graphs for selected functions only using the \callergraph command.
+
+CALLER_GRAPH           = NO
+
 # If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen
 # will graphical hierarchy of all classes instead of a textual one.
 
 GRAPHICAL_HIERARCHY    = YES
 
+# If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES
+# then doxygen will show the dependencies a directory has on other directories
+# in a graphical way. The dependency relations are determined by the #include
+# relations between the files in the directories.
+
+DIRECTORY_GRAPH        = YES
+
 # The DOT_IMAGE_FORMAT tag can be used to set the image format of the images
 # generated by dot. Possible values are png, jpg, or gif
 # If left blank png will be used.
@@ -954,7 +1352,7 @@ GRAPHICAL_HIERARCHY    = YES
 DOT_IMAGE_FORMAT       = png
 
 # The tag DOT_PATH can be used to specify the path where the dot tool can be
-# found. If left blank, it is assumed the dot tool can be found on the path.
+# found. If left blank, it is assumed the dot tool can be found in the path.
 
 DOT_PATH               =
 
@@ -964,21 +1362,40 @@ DOT_PATH               =
 
 DOTFILE_DIRS           =
 
-# The MAX_DOT_GRAPH_WIDTH tag can be used to set the maximum allowed width
-# (in pixels) of the graphs generated by dot. If a graph becomes larger than
-# this value, doxygen will try to truncate the graph, so that it fits within
-# the specified constraint. Beware that most browsers cannot cope with very
-# large images.
+# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of
+# nodes that will be shown in the graph. If the number of nodes in a graph
+# becomes larger than this value, doxygen will truncate the graph, which is
+# visualized by representing a node as a red box. Note that doxygen if the
+# number of direct children of the root node in a graph is already larger than
+# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note
+# that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.
+
+DOT_GRAPH_MAX_NODES    = 50
+
+# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the
+# graphs generated by dot. A depth value of 3 means that only nodes reachable
+# from the root by following a path via at most 3 edges will be shown. Nodes
+# that lay further from the root node will be omitted. Note that setting this
+# option to 1 or 2 may greatly reduce the computation time needed for large
+# code bases. Also note that the size of a graph can be further restricted by
+# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.
 
-MAX_DOT_GRAPH_WIDTH    = 1024
+MAX_DOT_GRAPH_DEPTH    = 0
 
-# The MAX_DOT_GRAPH_HEIGHT tag can be used to set the maximum allows height
-# (in pixels) of the graphs generated by dot. If a graph becomes larger than
-# this value, doxygen will try to truncate the graph, so that it fits within
-# the specified constraint. Beware that most browsers cannot cope with very
-# large images.
+# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent
+# background. This is enabled by default, which results in a transparent
+# background. Warning: Depending on the platform used, enabling this option
+# may lead to badly anti-aliased labels on the edges of a graph (i.e. they
+# become hard to read).
 
-MAX_DOT_GRAPH_HEIGHT   = 1024
+DOT_TRANSPARENT        = YES
+
+# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output
+# files in one run (i.e. multiple -o and -T options on the command line). This
+# makes dot run faster, but since only newer versions of dot (>1.8.10)
+# support this, this feature is disabled by default.
+
+DOT_MULTI_TARGETS      = NO
 
 # If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will
 # generate a legend page explaining the meaning of the various boxes and
@@ -987,51 +1404,16 @@ MAX_DOT_GRAPH_HEIGHT   = 1024
 GENERATE_LEGEND        = YES
 
 # If the DOT_CLEANUP tag is set to YES (the default) Doxygen will
-# remove the intermedate dot files that are used to generate
+# remove the intermediate dot files that are used to generate
 # the various graphs.
 
 DOT_CLEANUP            = YES
 
 #---------------------------------------------------------------------------
-# Configuration::addtions related to the search engine
+# Configuration::additions related to the search engine
 #---------------------------------------------------------------------------
 
 # The SEARCHENGINE tag specifies whether or not a search engine should be
 # used. If set to NO the values of all tags below this one will be ignored.
 
 SEARCHENGINE           = NO
-
-# The CGI_NAME tag should be the name of the CGI script that
-# starts the search engine (doxysearch) with the correct parameters.
-# A script with this name will be generated by doxygen.
-
-CGI_NAME               = search.cgi
-
-# The CGI_URL tag should be the absolute URL to the directory where the
-# cgi binaries are located. See the documentation of your http daemon for
-# details.
-
-CGI_URL                =
-
-# The DOC_URL tag should be the absolute URL to the directory where the
-# documentation is located. If left blank the absolute path to the
-# documentation, with file:// prepended to it, will be used.
-
-DOC_URL                =
-
-# The DOC_ABSPATH tag should be the absolute path to the directory where the
-# documentation is located. If left blank the directory on the local machine
-# will be used.
-
-DOC_ABSPATH            =
-
-# The BIN_ABSPATH tag must point to the directory where the doxysearch binary
-# is installed.
-
-BIN_ABSPATH            = /usr/local/bin/
-
-# The EXT_DOC_PATHS tag can be used to specify one or more paths to
-# documentation generated for other projects. This allows doxysearch to search
-# the documentation for these projects as well.
-
-EXT_DOC_PATHS          =
diff --git a/INSTALL b/INSTALL
index 8cd22bd..ac5dc5d 100644
--- a/INSTALL
+++ b/INSTALL
@@ -2,10 +2,17 @@
 1) Type './configure' to create the configuration. A list of configure
 options is printed by running 'configure --help'.
 
-'configure' can be launched from a directory different from the FFmpeg
+'configure' can be launched from a directory different from the Libav
 sources to build the objects out of tree. To do this, use an absolute
-path when launching 'configure', e.g. '/ffmpegdir/ffmpeg/configure'.
+path when launching 'configure', e.g. '/libavdir/libav/configure'.
 
-2) Then type 'make' to build FFmpeg. GNU Make 3.81 or later is required.
+2) Then type 'make' to build Libav. GNU Make 3.81 or later is required.
 
 3) Type 'make install' to install all binaries and libraries you built.
+
+NOTICE
+
+ - Non system dependencies (e.g. libx264, libvpx) are disabled by default.
+
+ - The default cflags include -g, if you want lean libraries you can either
+   pass --disable-debug or strip the debug symbols at a later time.
diff --git a/LICENSE b/LICENSE
index 668350b..725995d 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,24 +1,20 @@
-FFmpeg:
--------
+Libav:
+------
 
-Most files in FFmpeg are under the GNU Lesser General Public License version 2.1
+Most files in Libav are under the GNU Lesser General Public License version 2.1
 or later (LGPL v2.1+). Read the file COPYING.LGPLv2.1 for details. Some other
 files have MIT/X11/BSD-style licenses. In combination the LGPL v2.1+ applies to
-FFmpeg.
+Libav.
 
-Some optional parts of FFmpeg are licensed under the GNU General Public License
+Some optional parts of Libav are licensed under the GNU General Public License
 version 2 or later (GPL v2+). See the file COPYING.GPLv2 for details. None of
 these parts are used by default, you have to explicitly pass --enable-gpl to
-configure to activate them. In this case, FFmpeg's license changes to GPL v2+.
+configure to activate them. In this case, Libav's license changes to GPL v2+.
 
-Specifically, the GPL parts of FFmpeg are
+Specifically, the GPL parts of Libav are
 
 - libpostproc
-- optional MMX optimizations for YUV to RGB colorspace conversion in
-  libswscale/x86/yuv2rgb_template.c
 - optional x86 optimizations in the files
-  libavcodec/x86/h264_deblock_sse2.asm
-  libavcodec/x86/h264_idct_sse2.asm
   libavcodec/x86/idct_mmx.c
 - the X11 grabber in libavdevice/x11grab.c
 
@@ -37,14 +33,14 @@ external libraries:
 -------------------
 
 Some external libraries, e.g. libx264, are under GPL and can be used in
-conjunction with FFmpeg. They require --enable-gpl to be passed to configure
+conjunction with Libav. They require --enable-gpl to be passed to configure
 as well.
 
 The OpenCORE external libraries are under the Apache License 2.0. That license
 is incompatible with the LGPL v2.1 and the GPL v2, but not with version 3 of
-those licenses. So to combine the OpenCORE libraries with FFmpeg, the license
+those licenses. So to combine the OpenCORE libraries with Libav, the license
 version needs to be upgraded by passing --enable-version3 to configure.
 
-The nonfree external library libfaac can be hooked up in FFmpeg. You need to
+The nonfree external library libfaac can be hooked up in Libav. You need to
 pass --enable-nonfree to configure to enable it. Employ this option with care
-as FFmpeg then becomes nonfree and unredistributable.
+as Libav then becomes nonfree and unredistributable.
diff --git a/MAINTAINERS b/MAINTAINERS
deleted file mode 100644
index f9891fe..0000000
--- a/MAINTAINERS
+++ /dev/null
@@ -1,359 +0,0 @@
-FFmpeg maintainers
-==================
-
-Below is a list of the people maintaining different parts of the
-FFmpeg code.
-
-
-Project Leader
-==============
-
-Michael Niedermayer
-  final design decisions
-
-
-Applications
-============
-
-ffmpeg:
-  ffmpeg.c                              Michael Niedermayer
-
-ffplay:
-  ffplay.c                              Michael Niedermayer
-
-ffserver:
-  ffserver.c, ffserver.h                Baptiste Coudurier
-
-Commandline utility code:
-  cmdutils.c, cmdutils.h                Michael Niedermayer
-
-QuickTime faststart:
-  tools/qt-faststart.c                  Baptiste Coudurier
-
-
-Miscellaneous Areas
-===================
-
-documentation                           Mike Melanson, Diego Biurrun
-website                                 Robert Swain
-build system (configure,Makefiles)      Diego Biurrun, Mans Rullgard
-project server                          Diego Biurrun, Mans Rullgard
-mailinglists                            Michael Niedermayer, Baptiste Coudurier
-presets                                 Robert Swain
-metadata subsystem                      Aurelien Jacobs
-release management                      Diego Biurrun, Reinhard Tartler
-
-
-libavutil
-=========
-
-External Interfaces:
-  libavutil/avutil.h                    Michael Niedermayer
-Internal Interfaces:
-  libavutil/common.h                    Michael Niedermayer
-
-Other:
-  intfloat*                             Michael Niedermayer
-  rational.c, rational.h                Michael Niedermayer
-  mathematics.c, mathematics.h          Michael Niedermayer
-  integer.c, integer.h                  Michael Niedermayer
-  bswap.h
-
-
-libavcodec
-==========
-
-Generic Parts:
-  External Interfaces:
-    avcodec.h                           Michael Niedermayer
-  utility code:
-    utils.c                             Michael Niedermayer
-    mem.c                               Michael Niedermayer
-    opt.c, opt.h                        Michael Niedermayer
-  arithmetic expression evaluator:
-    eval.c                              Michael Niedermayer
-  audio and video frame extraction:
-    parser.c                            Michael Niedermayer
-  bitstream reading:
-    bitstream.c, bitstream.h            Michael Niedermayer
-  CABAC:
-    cabac.h, cabac.c                    Michael Niedermayer
-  DSP utilities:
-    dsputils.c, dsputils.h              Michael Niedermayer
-  entropy coding:
-    rangecoder.c, rangecoder.h          Michael Niedermayer
-    lzw.*                               Michael Niedermayer
-  floating point AAN DCT:
-    faandct.c, faandct.h                Michael Niedermayer
-  Golomb coding:
-    golomb.c, golomb.h                  Michael Niedermayer
-  LPC:
-    lpc.c, lpc.h                        Justin Ruggles
-  motion estimation:
-    motion*                             Michael Niedermayer
-  rate control:
-    ratecontrol.c                       Michael Niedermayer
-    libxvid_rc.c                        Michael Niedermayer
-  simple IDCT:
-    simple_idct.c, simple_idct.h        Michael Niedermayer
-  postprocessing:
-    libpostproc/*                       Michael Niedermayer
-
-Codecs:
-  4xm.c                                 Michael Niedermayer
-  8bps.c                                Roberto Togni
-  8svx.c                                Jaikrishnan Menon
-  aasc.c                                Kostya Shishkov
-  aac*, sbr.h                           Alex Converse
-  ac3*                                  Justin Ruggles
-  alacenc.c                             Jaikrishnan Menon
-  alsdec.c                              Thilo Borgmann
-  apedec.c                              Kostya Shishkov
-  asv*                                  Michael Niedermayer
-  atrac3*                               Benjamin Larsson
-  bgmc.c, bgmc.h                        Thilo Borgmann
-  bink.c                                Kostya Shishkov
-  binkaudio.c                           Peter Ross
-  bmp.c                                 Mans Rullgard, Kostya Shishkov
-  cavs*                                 Stefan Gehrer
-  celp_filters.*                        Vitor Sessak
-  cinepak.c                             Roberto Togni
-  cljr                                  Alex Beregszaszi
-  cook.c, cookdata.h                    Benjamin Larsson
-  cscd.c                                Reimar Doeffinger
-  dca.c                                 Kostya Shishkov, Benjamin Larsson
-  dnxhd*                                Baptiste Coudurier
-  dpcm.c                                Mike Melanson
-  dxa.c                                 Kostya Shishkov
-  dv.c                                  Roman Shaposhnik
-  eacmv*, eaidct*, eat*                 Peter Ross
-  ffv1.c                                Michael Niedermayer
-  flac*                                 Justin Ruggles
-  flashsv*                              Benjamin Larsson
-  flicvideo.c                           Mike Melanson
-  g726.c                                Roman Shaposhnik
-  gifdec.c                              Baptiste Coudurier
-  h264*                                 Loren Merritt, Michael Niedermayer
-  h261*                                 Michael Niedermayer
-  h263*                                 Michael Niedermayer
-  huffyuv.c                             Michael Niedermayer
-  idcinvideo.c                          Mike Melanson
-  imc*                                  Benjamin Larsson
-  indeo2*                               Kostya Shishkov
-  indeo5*                               Kostya Shishkov
-  interplayvideo.c                      Mike Melanson
-  ivi*                                  Kostya Shishkov
-  jpeg_ls.c                             Kostya Shishkov
-  kmvc.c                                Kostya Shishkov
-  lcl*.c                                Roberto Togni, Reimar Doeffinger
-  libgsm.c                              Michel Bardiaux
-  libdirac*                             David Conrad
-  libopenjpeg.c                         Jaikrishnan Menon
-  libschroedinger*                      David Conrad
-  libspeexdec.c                         Justin Ruggles
-  libtheoraenc.c                        David Conrad
-  libx264.c                             Mans Rullgard, Jason Garrett-Glaser
-  loco.c                                Kostya Shishkov
-  lzo.h, lzo.c                          Reimar Doeffinger
-  mdec.c                                Michael Niedermayer
-  mimic.c                               Ramiro Polla
-  mjpeg.c                               Michael Niedermayer
-  mlp*                                  Ramiro Polla
-  mmvideo.c                             Peter Ross
-  mpc*                                  Kostya Shishkov
-  mpeg12.c, mpeg12data.h                Michael Niedermayer
-  mpegvideo.c, mpegvideo.h              Michael Niedermayer
-  msmpeg4.c, msmpeg4data.h              Michael Niedermayer
-  msrle.c                               Mike Melanson
-  msvideo1.c                            Mike Melanson
-  nellymoserdec.c                       Benjamin Larsson
-  nuv.c                                 Reimar Doeffinger
-  pcx.c                                 Ivo van Poorten
-  ptx.c                                 Ivo van Poorten
-  qcelp*                                Reynaldo H. Verdejo Pinochet
-  qdm2.c, qdm2data.h                    Roberto Togni, Benjamin Larsson
-  qdrw.c                                Kostya Shishkov
-  qpeg.c                                Kostya Shishkov
-  qtrle.c                               Mike Melanson
-  ra144.c, ra144.h, ra288.c, ra288.h    Roberto Togni
-  resample2.c                           Michael Niedermayer
-  rl2.c                                 Sascha Sommer
-  rpza.c                                Roberto Togni
-  rtjpeg.c, rtjpeg.h                    Reimar Doeffinger
-  rv10.c                                Michael Niedermayer
-  rv3*                                  Kostya Shishkov
-  rv4*                                  Kostya Shishkov
-  s3tc*                                 Ivo van Poorten
-  smacker.c                             Kostya Shishkov
-  smc.c                                 Mike Melanson
-  snow.c                                Michael Niedermayer, Loren Merritt
-  sonic.c                               Alex Beregszaszi
-  sunrast.c                             Ivo van Poorten
-  svq3.c                                Michael Niedermayer
-  targa.c                               Kostya Shishkov
-  tiff.c                                Kostya Shishkov
-  truemotion1*                          Mike Melanson
-  truemotion2*                          Kostya Shishkov
-  truespeech.c                          Kostya Shishkov
-  tscc.c                                Kostya Shishkov
-  tta.c                                 Alex Beregszaszi, Jaikrishnan Menon
-  txd.c                                 Ivo van Poorten
-  ulti*                                 Kostya Shishkov
-  vb.c                                  Kostya Shishkov
-  vc1*                                  Kostya Shishkov
-  vcr1.c                                Michael Niedermayer
-  vmnc.c                                Kostya Shishkov
-  vorbis_enc.c                          Oded Shimon
-  vorbis_dec.c                          Denes Balatoni
-  vp3*                                  Mike Melanson
-  vp5                                   Aurelien Jacobs
-  vp6                                   Aurelien Jacobs
-  vqavideo.c                            Mike Melanson
-  wavpack.c                             Kostya Shishkov
-  wmaprodec.c                           Sascha Sommer
-  wmavoice.c                            Ronald S. Bultje
-  wmv2.c                                Michael Niedermayer
-  wnv1.c                                Kostya Shishkov
-  xan.c                                 Mike Melanson
-  xl.c                                  Kostya Shishkov
-  xvmc.c                                Ivan Kalvachev
-  zmbv*                                 Kostya Shishkov
-
-Hardware acceleration:
-  dxva2*                                Laurent Aimar
-  vaapi*                                Gwenole Beauchesne
-  vdpau*                                Carl Eugen Hoyos
-
-
-libavdevice
-===========
-  External Interface:
-    libavdevice/avdevice.h
-
-
-  libdc1394.c                           Roman Shaposhnik
-  v4l2.c                                Luca Abeni
-  vfwcap.c                              Ramiro Polla
-
-
-libavformat
-===========
-
-Generic parts:
-  External Interface:
-    libavformat/avformat.h              Michael Niedermayer
-  Utility Code:
-    libavformat/utils.c                 Michael Niedermayer
-
-
-Muxers/Demuxers:
-  4xm.c                                 Mike Melanson
-  adtsenc.c                             Robert Swain
-  aiff.c                                Baptiste Coudurier
-  ape.c                                 Kostya Shishkov
-  avi*                                  Michael Niedermayer
-  bink.c                                Peter Ross
-  crc.c                                 Michael Niedermayer
-  daud.c                                Reimar Doeffinger
-  dv.c                                  Roman Shaposhnik
-  dxa.c                                 Kostya Shishkov
-  electronicarts.c                      Peter Ross
-  ffm*                                  Baptiste Coudurier
-  flac*                                 Justin Ruggles
-  flic.c                                Mike Melanson
-  flvdec.c, flvenc.c                    Michael Niedermayer
-  gxf.c                                 Reimar Doeffinger
-  gxfenc.c                              Baptiste Coudurier
-  idcin.c                               Mike Melanson
-  idroq.c                               Mike Melanson
-  iff.c                                 Jaikrishnan Menon
-  ipmovie.c                             Mike Melanson
-  img2.c                                Michael Niedermayer
-  iss.c                                 Stefan Gehrer
-  libnut.c                              Oded Shimon
-  lmlm4.c                               Ivo van Poorten
-  matroska.c                            Aurelien Jacobs
-  matroskadec.c                         Aurelien Jacobs
-  matroskaenc.c                         David Conrad
-  metadata*                             Aurelien Jacobs
-  mm.c                                  Peter Ross
-  mov.c                                 Michael Niedermayer, Baptiste Coudurier
-  movenc.c                              Michael Niedermayer, Baptiste Coudurier
-  mpc.c                                 Kostya Shishkov
-  mpeg.c                                Michael Niedermayer
-  mpegenc.c                             Michael Niedermayer
-  mpegts*                               Baptiste Coudurier
-  msnwc_tcp.c                           Ramiro Polla
-  mtv.c                                 Reynaldo H. Verdejo Pinochet
-  mxf*                                  Baptiste Coudurier
-  nsvdec.c                              Francois Revol
-  nut.c                                 Michael Niedermayer
-  nuv.c                                 Reimar Doeffinger
-  oggdec.c, oggdec.h                    David Conrad
-  oggenc.c                              Baptiste Coudurier
-  oggparse*.c                           David Conrad
-  psxstr.c                              Mike Melanson
-  pva.c                                 Ivo van Poorten
-  r3d.c                                 Baptiste Coudurier
-  raw.c                                 Michael Niedermayer
-  rdt.c                                 Ronald S. Bultje
-  rl2.c                                 Sascha Sommer
-  rmdec.c, rmenc.c                      Ronald S. Bultje, Kostya Shishkov
-  rtmp*                                 Kostya Shishkov
-  rtp.c, rtpenc.c                       Luca Abeni
-  rtp_asf.*                             Ronald S. Bultje
-  rtp_mpv.*, rtp_aac.*                  Luca Abeni
-  rtsp.c                                Luca Barbato
-  sdp.c                                 Luca Abeni
-  segafilm.c                            Mike Melanson
-  siff.c                                Kostya Shishkov
-  smacker.c                             Kostya Shishkov
-  swf.c                                 Baptiste Coudurier
-  tta.c                                 Alex Beregszaszi
-  txd.c                                 Ivo van Poorten
-  voc.c                                 Aurelien Jacobs
-  wav.c                                 Michael Niedermayer
-  wc3movie.c                            Mike Melanson
-  westwood.c                            Mike Melanson
-  wv.c                                  Kostya Shishkov
-
-Protocols:
-  http.c                                Ronald S. Bultje
-  udp.c                                 Luca Abeni
-
-
-Operating systems / CPU architectures
-=====================================
-
-Alpha                                   Mans Rullgard, Falk Hueffner
-ARM                                     Mans Rullgard
-AVR32                                   Mans Rullgard
-MIPS                                    Mans Rullgard
-BeOS                                    Francois Revol
-Mac OS X / PowerPC                      Romain Dolbeau, Guillaume Poirier
-Amiga / PowerPC                         Colin Ward
-Linux / PowerPC                         Luca Barbato
-Windows MinGW                           Alex Beregszaszi, Ramiro Polla
-Windows Cygwin                          Victor Paesa
-ADI/Blackfin DSP                        Marc Hoffman
-Sparc                                   Roman Shaposhnik
-x86                                     Michael Niedermayer
-
-
-GnuPG Fingerprints of maintainers and others who have svn write access
-======================================================================
-
-Attila Kinali                 11F0 F9A6 A1D2 11F6 C745 D10C 6520 BCDD F2DF E765
-Baptiste Coudurier            8D77 134D 20CC 9220 201F C5DB 0AC9 325C 5C1A BAAA
-Benoit Fouet                  B22A 4F4F 43EF 636B BB66 FCDC 0023 AE1E 2985 49C8
-Daniel Verkamp                78A6 07ED 782C 653E C628 B8B9 F0EB 8DD8 2F0E 21C7
-Diego Biurrun                 8227 1E31 B6D9 4994 7427 E220 9CAE D6CC 4757 FCC5
-Jaikrishnan Menon             61A1 F09F 01C9 2D45 78E1 C862 25DC 8831 AF70 D368
-Loren Merritt                 ABD9 08F4 C920 3F65 D8BE 35D7 1540 DAA7 060F 56DE
-Michael Niedermayer           9FF2 128B 147E F673 0BAD F133 611E C787 040B 0FAB
-Panagiotis Issaris            515C E262 10A8 FDCE 5481 7B9C 3AD7 D9A5 071D B3A9
-Peter Ross                    A907 E02F A6E5 0CD2 34CD 20D2 6760 79C5 AC40 DD6B
-Reimar Döffinger              C61D 16E5 9E2C D10C 8958 38A4 0899 A2B9 06D4 D9C7
-Reinhard Tartler              9300 5DC2 7E87 6C37 ED7B CA9A 9808 3544 9453 48A4
-Reynaldo H. Verdejo Pinochet  6E27 CD34 170C C78E 4D4F 5F40 C18E 077F 3114 452A
-Sascha Sommer                 38A0 F88B 868E 9D3A 97D4 D6A0 E823 706F 1E07 0D3C
diff --git a/Makefile b/Makefile
index 18ab3a6..0bf04d1 100644
--- a/Makefile
+++ b/Makefile
@@ -9,17 +9,18 @@ PROGS-$(CONFIG_FFPLAY)   += ffplay
 PROGS-$(CONFIG_FFPROBE)  += ffprobe
 PROGS-$(CONFIG_FFSERVER) += ffserver
 
-PROGS      := $(addsuffix   $(EXESUF), $(PROGS-yes))
-PROGS_G     = $(addsuffix _g$(EXESUF), $(PROGS-yes))
-OBJS        = $(addsuffix .o,          $(PROGS-yes)) cmdutils.o
-MANPAGES    = $(addprefix doc/, $(addsuffix .1, $(PROGS-yes)))
-TOOLS       = $(addprefix tools/, $(addsuffix $(EXESUF), cws2fws pktdumper probetest qt-faststart trasher))
-HOSTPROGS   = $(addprefix tests/, audiogen videogen rotozoom tiny_psnr)
+PROGS      := $(PROGS-yes:%=%$(EXESUF))
+OBJS        = $(PROGS-yes:%=%.o) cmdutils.o
+MANPAGES    = $(PROGS-yes:%=doc/%.1)
+PODPAGES    = $(PROGS-yes:%=doc/%.pod)
+HTMLPAGES   = $(PROGS-yes:%=doc/%.html)
+TOOLS       = $(addprefix tools/, $(addsuffix $(EXESUF), cws2fws graph2dot lavfi-showfiltfmts pktdumper probetest qt-faststart trasher))
+TESTTOOLS   = audiogen videogen rotozoom tiny_psnr base64
+HOSTPROGS  := $(TESTTOOLS:%=tests/%)
 
 BASENAMES   = ffmpeg ffplay ffprobe ffserver
-ALLPROGS    = $(addsuffix   $(EXESUF), $(BASENAMES))
-ALLPROGS_G  = $(addsuffix _g$(EXESUF), $(BASENAMES))
-ALLMANPAGES = $(addsuffix .1, $(BASENAMES))
+ALLPROGS    = $(BASENAMES:%=%$(EXESUF))
+ALLMANPAGES = $(BASENAMES:%=%.1)
 
 FFLIBS-$(CONFIG_AVDEVICE) += avdevice
 FFLIBS-$(CONFIG_AVFILTER) += avfilter
@@ -50,13 +51,15 @@ INSTALL_PROGS_TARGETS-$(CONFIG_SHARED) = install-libs
 
 all: $(FF_DEP_LIBS) $(PROGS) $(ALL_TARGETS-yes)
 
-$(PROGS): %$(EXESUF): %_g$(EXESUF)
-	$(CP) $< $@
-	$(STRIP) $@
+config.h: .config
+.config: $(wildcard $(FFLIBS:%=$(SRC_DIR)/lib%/all*.c))
+	@-tput bold 2>/dev/null
+	@-printf '\nWARNING: $(?F) newer than config.h, rerun configure\n\n'
+	@-tput sgr0 2>/dev/null
 
 SUBDIR_VARS := OBJS FFLIBS CLEANFILES DIRS TESTPROGS EXAMPLES SKIPHEADERS \
                ALTIVEC-OBJS MMX-OBJS NEON-OBJS X86-OBJS YASM-OBJS-FFT YASM-OBJS \
-               HOSTPROGS BUILT_HEADERS TESTOBJS ARCH_HEADERS
+               HOSTPROGS BUILT_HEADERS TESTOBJS ARCH_HEADERS ARMV6-OBJS
 
 define RESET
 $(1) :=
@@ -71,25 +74,26 @@ endef
 
 $(foreach D,$(FFLIBS),$(eval $(call DOSUBDIR,lib$(D))))
 
-ffplay_g$(EXESUF): FF_EXTRALIBS += $(SDL_LIBS)
-ffserver_g$(EXESUF): FF_LDFLAGS += $(FFSERVERLDFLAGS)
+ffplay$(EXESUF): FF_EXTRALIBS += $(SDL_LIBS)
+ffserver$(EXESUF): FF_LDFLAGS += $(FFSERVERLDFLAGS)
 
-%_g$(EXESUF): %.o cmdutils.o $(FF_DEP_LIBS)
+%$(EXESUF): %.o cmdutils.o $(FF_DEP_LIBS)
 	$(LD) $(FF_LDFLAGS) -o $@ $< cmdutils.o $(FF_EXTRALIBS)
 
 tools/%$(EXESUF): tools/%.o
 	$(LD) $(FF_LDFLAGS) -o $@ $< $(FF_EXTRALIBS)
 
 tools/%.o: tools/%.c
-	$(CC) $(CPPFLAGS) $(CFLAGS) $(CC_O) $<
+	$(CC) $(CPPFLAGS) $(CFLAGS) -c $(CC_O) $<
 
-ffplay.o ffplay.d: CFLAGS += $(SDL_CFLAGS)
+-include $(wildcard tools/*.d)
+
+ffplay.o: CFLAGS += $(SDL_CFLAGS)
 
 VERSION_SH  = $(SRC_PATH_BARE)/version.sh
 GIT_LOG     = $(SRC_PATH_BARE)/.git/logs/HEAD
-SVN_ENTRIES = $(SRC_PATH_BARE)/.svn/entries
 
-.version: $(wildcard $(GIT_LOG) $(SVN_ENTRIES)) $(VERSION_SH) config.mak
+.version: $(wildcard $(GIT_LOG)) $(VERSION_SH) config.mak
 .version: M=@
 
 version.h .version:
@@ -101,16 +105,22 @@ version.h .version:
 
 alltools: $(TOOLS)
 
-documentation: $(addprefix doc/, developer.html faq.html ffmpeg-doc.html \
-                                 ffplay-doc.html ffprobe-doc.html ffserver-doc.html \
-                                 general.html libavfilter.html $(ALLMANPAGES))
+DOCS = $(addprefix doc/, developer.html faq.html general.html libavfilter.html) $(HTMLPAGES) $(MANPAGES) $(PODPAGES)
+
+documentation: $(DOCS)
+
+-include $(wildcard $(DOCS:%=%.d))
+
+TEXIDEP = awk '/^@include/ { printf "$@: $(@D)/%s\n", $$2 }' <$< >$(@:%=%.d)
 
 doc/%.html: TAG = HTML
-doc/%.html: doc/%.texi
-	$(M)cd doc && texi2html -monolithic -number $(<:doc/%=%)
+doc/%.html: doc/%.texi $(SRC_PATH_BARE)/doc/t2h.init
+	$(Q)$(TEXIDEP)
+	$(M)cd doc && texi2html -monolithic --init-file $(SRC_PATH_BARE)/doc/t2h.init $(<:doc/%=%)
 
 doc/%.pod: TAG = POD
-doc/%.pod: doc/%-doc.texi
+doc/%.pod: doc/%.texi
+	$(Q)$(TEXIDEP)
 	$(M)doc/texi2pod.pl $< $@
 
 doc/%.1: TAG = MAN
@@ -146,176 +156,48 @@ testclean:
 	$(RM) -r tests/vsynth1 tests/vsynth2 tests/data
 	$(RM) $(addprefix tests/,$(CLEANSUFFIXES))
 	$(RM) tests/seek_test$(EXESUF) tests/seek_test.o
-	$(RM) $(addprefix tests/,$(addsuffix $(HOSTEXESUF),audiogen videogen rotozoom tiny_psnr))
+	$(RM) $(TESTTOOLS:%=tests/%$(HOSTEXESUF))
 
 clean:: testclean
-	$(RM) $(ALLPROGS) $(ALLPROGS_G)
+	$(RM) $(ALLPROGS)
 	$(RM) $(CLEANSUFFIXES)
 	$(RM) doc/*.html doc/*.pod doc/*.1
 	$(RM) $(TOOLS)
+	$(RM) $(CLEANSUFFIXES:%=tools/%)
 
 distclean::
 	$(RM) $(DISTCLEANSUFFIXES)
 	$(RM) version.h config.* libavutil/avconfig.h
 
 config:
-	$(SRC_PATH)/configure $(value FFMPEG_CONFIGURATION)
+	$(SRC_PATH)/configure $(value LIBAV_CONFIGURATION)
 
 # regression tests
 
 check: test checkheaders
 
-fulltest test: codectest lavftest seektest
+fulltest test: codectest lavftest lavfitest seektest
 
 FFSERVER_REFFILE = $(SRC_PATH)/tests/ffserver.regression.ref
 SEEK_REFFILE     = $(SRC_PATH)/tests/seek.regression.ref
 
-ENCDEC = $(and $(CONFIG_$(1)_ENCODER),$(CONFIG_$(1)_DECODER))
-MUXDEM = $(and $(CONFIG_$(1)_MUXER),$(CONFIG_$(or $(2),$(1))_DEMUXER))
-
-VCODEC_TESTS =
-VCODEC_TESTS-$(call ENCDEC,ASV1)             += asv1
-VCODEC_TESTS-$(call ENCDEC,ASV2)             += asv2
-VCODEC_TESTS-$(call ENCDEC,DNXHD)            += dnxhd_1080i dnxhd_720p dnxhd_720p_rd
-VCODEC_TESTS-$(call ENCDEC,DVVIDEO)          += dv dv50
-VCODEC_TESTS-$(call ENCDEC,FFV1)             += ffv1
-VCODEC_TESTS-$(call ENCDEC,FLASHSV)          += flashsv
-VCODEC_TESTS-$(call ENCDEC,FLV)              += flv
-VCODEC_TESTS-$(call ENCDEC,H261)             += h261
-VCODEC_TESTS-$(call ENCDEC,H263)             += h263 h263p
-VCODEC_TESTS-$(call ENCDEC,HUFFYUV)          += huffyuv
-VCODEC_TESTS-$(call ENCDEC,JPEGLS)           += jpegls
-VCODEC_TESTS-$(call ENCDEC,MJPEG)            += mjpeg ljpeg
-VCODEC_TESTS-$(call ENCDEC,MPEG1VIDEO)       += mpeg mpeg1b
-VCODEC_TESTS-$(call ENCDEC,MPEG2VIDEO)       += mpeg2 mpeg2thread
-VCODEC_TESTS-$(call ENCDEC,MPEG4)            += mpeg4 mpeg4adv mpeg4nr mpeg4thread error rc
-VCODEC_TESTS-$(call ENCDEC,MSMPEG4V1)        += msmpeg4
-VCODEC_TESTS-$(call ENCDEC,MSMPEG4V2)        += msmpeg4v2
-VCODEC_TESTS-$(call ENCDEC,ROQ)              += roq
-VCODEC_TESTS-$(call ENCDEC,RV10)             += rv10
-VCODEC_TESTS-$(call ENCDEC,RV20)             += rv20
-VCODEC_TESTS-$(call ENCDEC,SNOW)             += snow snowll
-VCODEC_TESTS-$(call ENCDEC,SVQ1)             += svq1
-VCODEC_TESTS-$(call ENCDEC,WMV1)             += wmv1
-VCODEC_TESTS-$(call ENCDEC,WMV2)             += wmv2
-
-ACODEC_TESTS =
-ACODEC_TESTS-$(call ENCDEC,AC3)              += ac3
-ACODEC_TESTS-$(call ENCDEC,ADPCM_G726)       += g726
-ACODEC_TESTS-$(call ENCDEC,ADPCM_IMA_QT)     += adpcm_ima_qt
-ACODEC_TESTS-$(call ENCDEC,ADPCM_IMA_WAV)    += adpcm_ima_wav
-ACODEC_TESTS-$(call ENCDEC,ADPCM_MS)         += adpcm_ms
-ACODEC_TESTS-$(call ENCDEC,ADPCM_SWF)        += adpcm_swf
-ACODEC_TESTS-$(call ENCDEC,ADPCM_YAMAHA)     += adpcm_yam
-ACODEC_TESTS-$(call ENCDEC,ALAC)             += alac
-ACODEC_TESTS-$(call ENCDEC,FLAC)             += flac
-ACODEC_TESTS-$(call ENCDEC,MP2)              += mp2
-ACODEC_TESTS-$(call ENCDEC,PCM_S16LE)        += pcm         # fixme
-ACODEC_TESTS-$(call ENCDEC,WMAV1)            += wmav1
-ACODEC_TESTS-$(call ENCDEC,WMAV1)            += wmav2
-
-LAVF_TESTS =
-LAVF_TESTS-$(call MUXDEM,AIFF)               += aiff
-LAVF_TESTS-$(call MUXDEM,PCM_ALAW)           += alaw
-LAVF_TESTS-$(call MUXDEM,ASF)                += asf
-LAVF_TESTS-$(call MUXDEM,AU)                 += au
-LAVF_TESTS-$(call MUXDEM,AVI)                += avi
-LAVF_TESTS-$(call ENCDEC,BMP)                += bmp
-LAVF_TESTS-$(call MUXDEM,DV)                 += dv_fmt
-LAVF_TESTS-$(call MUXDEM,FFM)                += ffm
-LAVF_TESTS-$(call MUXDEM,FLV)                += flv_fmt
-LAVF_TESTS-$(call ENCDEC,GIF)                += gif
-LAVF_TESTS-$(call MUXDEM,GXF)                += gxf
-LAVF_TESTS-$(call ENCDEC,MJPEG)              += jpg
-LAVF_TESTS-$(call MUXDEM,MATROSKA)           += mkv
-LAVF_TESTS-$(call MUXDEM,MMF)                += mmf
-LAVF_TESTS-$(call MUXDEM,MOV)                += mov
-LAVF_TESTS-$(call MUXDEM,MPEG1SYSTEM,MPEGPS) += mpg
-LAVF_TESTS-$(call MUXDEM,PCM_MULAW)          += mulaw
-LAVF_TESTS-$(call MUXDEM,MXF)                += mxf
-LAVF_TESTS-$(call MUXDEM,NUT)                += nut
-LAVF_TESTS-$(call MUXDEM,OGG)                += ogg
-LAVF_TESTS-$(call ENCDEC,PBM)                += pbmpipe
-LAVF_TESTS-$(call ENCDEC,PCX)                += pcx
-LAVF_TESTS-$(call ENCDEC,PGM)                += pgm pgmpipe
-LAVF_TESTS-$(call MUXDEM,RAWVIDEO)           += pixfmt
-LAVF_TESTS-$(call ENCDEC,PPM)                += ppm ppmpipe
-LAVF_TESTS-$(call MUXDEM,RM)                 += rm
-LAVF_TESTS-$(call ENCDEC,SGI)                += sgi
-LAVF_TESTS-$(call MUXDEM,SWF)                += swf
-LAVF_TESTS-$(call ENCDEC,TARGA)              += tga
-LAVF_TESTS-$(call ENCDEC,TIFF)               += tiff
-LAVF_TESTS-$(call MUXDEM,MPEGTS)             += ts
-LAVF_TESTS-$(call MUXDEM,VOC)                += voc
-LAVF_TESTS-$(call MUXDEM,WAV)                += wav
-LAVF_TESTS-$(call MUXDEM,YUV4MPEGPIPE)       += yuv4mpeg
-
-LAVFI_TESTS =           \
-    crop                \
-    crop_scale          \
-    crop_scale_vflip    \
-    crop_vflip          \
-    null                \
-    scale200            \
-    scale500            \
-    vflip               \
-    vflip_crop          \
-    vflip_vflip         \
-
-ACODEC_TESTS := $(addprefix regtest-, $(ACODEC_TESTS) $(ACODEC_TESTS-yes))
-VCODEC_TESTS := $(addprefix regtest-, $(VCODEC_TESTS) $(VCODEC_TESTS-yes))
-LAVF_TESTS  := $(addprefix regtest-, $(LAVF_TESTS)  $(LAVF_TESTS-yes))
-LAVFI_TESTS := $(addprefix regtest-, $(LAVFI_TESTS) $(LAVFI_TESTS-yes))
-
-CODEC_TESTS = $(VCODEC_TESTS) $(ACODEC_TESTS)
-
-codectest: $(CODEC_TESTS)
-lavftest:  $(LAVF_TESTS)
-lavfitest: $(LAVFI_TESTS)
-
-$(ACODEC_TESTS): regtest-aref
-$(VCODEC_TESTS): regtest-vref
-$(LAVF_TESTS) $(LAVFI_TESTS): regtest-ref
-
-REFFILE = $(SRC_PATH)/tests/ref/$(1)/$(2:regtest-%=%)
-RESFILE = tests/data/$(2:regtest-%=%).$(1).regression
-
-define CODECTEST_CMD
-	$(SRC_PATH)/tests/codec-regression.sh $@ vsynth1 tests/vsynth1 "$(TARGET_EXEC)" "$(TARGET_PATH)"
-	$(SRC_PATH)/tests/codec-regression.sh $@ vsynth2 tests/vsynth2 "$(TARGET_EXEC)" "$(TARGET_PATH)"
-endef
-
-regtest-ref: regtest-aref regtest-vref
-
-regtest-vref: ffmpeg$(EXESUF) tests/vsynth1/00.pgm tests/vsynth2/00.pgm
-	$(CODECTEST_CMD)
-
-regtest-aref: ffmpeg$(EXESUF) tests/data/asynth1.sw
-	@$(SRC_PATH)/tests/codec-regression.sh $@ acodec tests/acodec "$(TARGET_EXEC)" "$(TARGET_PATH)"
+codectest: fate-codec
+lavftest:  fate-lavf
+lavfitest: fate-lavfi
+seektest:  fate-seek
 
-$(VCODEC_TESTS): tests/tiny_psnr$(HOSTEXESUF)
-	@echo "TEST VCODEC $(@:regtest-%=%)"
-	@$(CODECTEST_CMD)
-	@diff -u -w $(call REFFILE,vsynth1,$@) $(call RESFILE,vsynth1,$@)
-	@diff -u -w $(call REFFILE,vsynth2,$@) $(call RESFILE,vsynth2,$@)
+AREF = tests/data/acodec.ref.wav
+VREF = tests/data/vsynth1.ref.yuv
+REFS = $(AREF) $(VREF)
 
-$(ACODEC_TESTS): tests/tiny_psnr$(HOSTEXESUF)
-	@echo "TEST ACODEC $(@:regtest-%=%)"
-	@$(SRC_PATH)/tests/codec-regression.sh $@ acodec tests/acodec "$(TARGET_EXEC)" "$(TARGET_PATH)"
-	@diff -u -w $(call REFFILE,acodec,$@) $(call RESFILE,acodec,$@)
+$(REFS): TAG = GEN
 
-$(LAVF_TESTS):
-	@echo "TEST LAVF  $(@:regtest-%=%)"
-	@$(SRC_PATH)/tests/lavf-regression.sh $@ lavf tests/vsynth1 "$(TARGET_EXEC)" "$(TARGET_PATH)"
-	@diff -u -w $(call REFFILE,lavf,$@) $(call RESFILE,lavf,$@)
+$(VREF): ffmpeg$(EXESUF) tests/vsynth1/00.pgm tests/vsynth2/00.pgm
+	$(M)$(SRC_PATH)/tests/codec-regression.sh vref vsynth1 tests/vsynth1 "$(TARGET_EXEC)" "$(TARGET_PATH)"
+	$(Q)$(SRC_PATH)/tests/codec-regression.sh vref vsynth2 tests/vsynth2 "$(TARGET_EXEC)" "$(TARGET_PATH)"
 
-$(LAVFI_TESTS):
-	@echo "TEST LAVFI $(@:regtest-%=%)"
-	@$(SRC_PATH)/tests/lavfi-regression.sh $@ lavfi tests/vsynth1 "$(TARGET_EXEC)" "$(TARGET_PATH)"
-	@diff -u -w $(call REFFILE,lavfi,$@) $(call RESFILE,lavfi,$@)
-
-seektest: codectest lavftest tests/seek_test$(EXESUF)
-	$(SRC_PATH)/tests/seek-regression.sh $(SRC_PATH) "$(TARGET_EXEC)" "$(TARGET_PATH)"
+$(AREF): ffmpeg$(EXESUF) tests/data/asynth1.sw
+	$(M)$(SRC_PATH)/tests/codec-regression.sh aref acodec tests/acodec "$(TARGET_EXEC)" "$(TARGET_PATH)"
 
 ffservertest: ffserver$(EXESUF) tests/vsynth1/00.pgm tests/data/asynth1.sw
 	@echo
@@ -325,29 +207,86 @@ ffservertest: ffserver$(EXESUF) tests/vsynth1/00.pgm tests/data/asynth1.sw
 	$(SRC_PATH)/tests/ffserver-regression.sh $(FFSERVER_REFFILE) $(SRC_PATH)/tests/ffserver.conf
 
 tests/vsynth1/00.pgm: tests/videogen$(HOSTEXESUF)
-	mkdir -p tests/vsynth1
-	$(BUILD_ROOT)/$< 'tests/vsynth1/'
+	@mkdir -p tests/vsynth1
+	$(M)$(BUILD_ROOT)/$< 'tests/vsynth1/'
 
 tests/vsynth2/00.pgm: tests/rotozoom$(HOSTEXESUF)
-	mkdir -p tests/vsynth2
-	$(BUILD_ROOT)/$< 'tests/vsynth2/' $(SRC_PATH)/tests/lena.pnm
+	@mkdir -p tests/vsynth2
+	$(M)$(BUILD_ROOT)/$< 'tests/vsynth2/' $(SRC_PATH)/tests/lena.pnm
 
 tests/data/asynth1.sw: tests/audiogen$(HOSTEXESUF)
-	mkdir -p tests/data
-	$(BUILD_ROOT)/$< $@
+	@mkdir -p tests/data
+	$(M)$(BUILD_ROOT)/$< $@
+
+tests/data/asynth1.sw tests/vsynth%/00.pgm: TAG = GEN
 
 tests/seek_test$(EXESUF): tests/seek_test.o $(FF_DEP_LIBS)
 	$(LD) $(FF_LDFLAGS) -o $@ $< $(FF_EXTRALIBS)
 
-ifdef SAMPLES
+tools/lavfi-showfiltfmts$(EXESUF): tools/lavfi-showfiltfmts.o $(FF_DEP_LIBS)
+	$(LD) $(FF_LDFLAGS) -o $@ $< $(FF_EXTRALIBS)
+
 include $(SRC_PATH_BARE)/tests/fate.mak
-fate: $(FATE_TESTS)
-$(FATE_TESTS): ffmpeg$(EXESUF)
-	@echo "TEST FATE   $(@:fate-%=%)"
-	@$(SRC_PATH)/tests/fate-run.sh $@ "$(SAMPLES)" "$(TARGET_EXEC)" "$(TARGET_PATH)" '$(CMD)'
+include $(SRC_PATH_BARE)/tests/fate2.mak
+
+include $(SRC_PATH_BARE)/tests/fate/aac.mak
+include $(SRC_PATH_BARE)/tests/fate/als.mak
+include $(SRC_PATH_BARE)/tests/fate/fft.mak
+include $(SRC_PATH_BARE)/tests/fate/h264.mak
+include $(SRC_PATH_BARE)/tests/fate/mp3.mak
+include $(SRC_PATH_BARE)/tests/fate/vorbis.mak
+include $(SRC_PATH_BARE)/tests/fate/vp8.mak
+
+FATE_ACODEC  = $(ACODEC_TESTS:%=fate-acodec-%)
+FATE_VSYNTH1 = $(VCODEC_TESTS:%=fate-vsynth1-%)
+FATE_VSYNTH2 = $(VCODEC_TESTS:%=fate-vsynth2-%)
+FATE_VCODEC  = $(FATE_VSYNTH1) $(FATE_VSYNTH2)
+FATE_LAVF    = $(LAVF_TESTS:%=fate-lavf-%)
+FATE_LAVFI   = $(LAVFI_TESTS:%=fate-lavfi-%)
+FATE_SEEK    = $(SEEK_TESTS:seek_%=fate-seek-%)
+
+FATE = $(FATE_ACODEC)                                                   \
+       $(FATE_VCODEC)                                                   \
+       $(FATE_LAVF)                                                     \
+       $(FATE_LAVFI)                                                    \
+       $(FATE_SEEK)                                                     \
+
+$(FATE_ACODEC): $(AREF)
+$(FATE_VCODEC): $(VREF)
+$(FATE_LAVF):   $(REFS)
+$(FATE_LAVFI):  $(REFS) tools/lavfi-showfiltfmts$(EXESUF)
+$(FATE_SEEK):   fate-codec fate-lavf tests/seek_test$(EXESUF)
+
+$(FATE_ACODEC):  CMD = codectest acodec
+$(FATE_VSYNTH1): CMD = codectest vsynth1
+$(FATE_VSYNTH2): CMD = codectest vsynth2
+$(FATE_LAVF):    CMD = lavftest
+$(FATE_LAVFI):   CMD = lavfitest
+$(FATE_SEEK):    CMD = seektest
+
+fate-codec:  fate-acodec fate-vcodec
+fate-acodec: $(FATE_ACODEC)
+fate-vcodec: $(FATE_VCODEC)
+fate-lavf:   $(FATE_LAVF)
+fate-lavfi:  $(FATE_LAVFI)
+fate-seek:   $(FATE_SEEK)
+
+ifdef SAMPLES
+FATE += $(FATE_TESTS)
 else
-fate:
+$(FATE_TESTS):
 	@echo "SAMPLES not specified, cannot run FATE"
 endif
 
-.PHONY: documentation *test regtest-* zlib-error alltools check config
+FATE_UTILS = base64 tiny_psnr
+
+fate: $(FATE)
+
+$(FATE): ffmpeg$(EXESUF) $(FATE_UTILS:%=tests/%$(HOSTEXESUF))
+	@echo "TEST    $(@:fate-%=%)"
+	$(Q)$(SRC_PATH)/tests/fate-run.sh $@ "$(SAMPLES)" "$(TARGET_EXEC)" "$(TARGET_PATH)" '$(CMD)' '$(CMP)' '$(REF)' '$(FUZZ)' '$(THREADS)'
+
+fate-list:
+	@printf '%s\n' $(sort $(FATE))
+
+.PHONY: documentation *test regtest-* alltools check config
diff --git a/README b/README
index e907e90..afef671 100644
--- a/README
+++ b/README
@@ -1,5 +1,5 @@
-FFmpeg README
--------------
+Libav README
+------------
 
 1) Documentation
 ----------------
diff --git a/RELEASE b/RELEASE
deleted file mode 100644
index c68e42a..0000000
--- a/RELEASE
+++ /dev/null
@@ -1,96 +0,0 @@
-Release Notes
-=============
-
-* 0.6 "Works with HTML5" June, 2010
-
-General notes
--------------
-
-This release features a lot of improvements that are relevant for HTML5 video.
-The H.264 and Theora decoders are now significantly faster, the vorbis decoder
-has seen important updates and this release supports Google's newly released
-libvpx library for the VP8 codec and WEBM container.
-
-Other important changes are additions of decoders including, but not limited to,
-Intel Indeo 5, WMA Pro, WMA Voice and HE-AAC.
-
-See the Changelog file for a list of significant changes.
-
-Please note that our policy on bug reports has not changed. We still only accept
-bug reports against HEAD of the FFmpeg trunk repository. If you are experiencing
-any issues with any formally released version of FFmpeg, please try a current
-version of the development code to check if the issue still exists. If it does,
-make your report against the development code following the usual bug reporting
-guidelines.
-
-
-API and other notable Changes
------------------------------
-
-Please see the file doc/APIchanges for programmer-centric information.
-
-Notable changes:
-- deprecated vhook subsystem removed
-- deprecated old scaler removed
-- nonfree libamr support for AMR-NB/WB decoding/encoding removed
-- RTMP support in libavformat
-- -formats option split into -formats, -codecs, -bsfs, and -protocols
-- ffprobe tool
-- RTMP/RTMPT/RTMPS/RTMPE/RTMPTE protocol support via librtmp
-- CODEC_CAP_EXPERIMENTAL added
-
-
-Added Codecs:
--------------
-
-- VQF demuxer
-- PCX encoder
-- CorePNG decoding support
-- 8088flex TMV demuxer and decoder
-- enable symbol versioning by default for linkers that support it
-- V210 decoder and encoder
-- QCP demuxer
-- SoX native format muxer and demuxer
-- AMR-NB decoding/encoding, AMR-WB decoding via OpenCORE libraries
-- DPX image decoder
-- Electronic Arts Madcow decoder
-- DivX (XSUB) subtitle encoder
-- experimental AAC encoder
-- Wave64 demuxer
-- IEC-61937 compatible Muxer
-- TwinVQ decoder
-- Bluray (PGS) subtitle decoder
-- LPCM support in MPEG-TS (HDMV RID as found on Blu-ray disks)
-- WMA Pro decoder
-- Core Audio Format demuxer
-- Atrac1 decoder
-- MD STUDIO audio demuxer
-- RF64 support in WAV demuxer
-- MPEG-4 Audio Lossless Coding (ALS) decoder
-- IV8 demuxer
-- CDG demuxer and decoder
-- R210 decoder
-- Auravision Aura 1 and 2 decoders
-- Deluxe Paint Animation playback system
-- SIPR decoder
-- Adobe Filmstrip muxer and demuxer
-- RTP packetization and depacketization of H.263 and AMR
-- Bink demuxer and audio/video decoders
-- IFF PBM/ILBM bitmap decoder
-- Indeo 5 decoder
-- WMA Voice decoder
-- AMR-NB decoder
-- RTSP muxer
-- HE-AAC v1 decoder
-- Kega Game Video (KGV1) decoder
-- Psygnosis YOP demuxer and video decoder
-- RTP hinting in the mov/3gp/mp4 muxer
-- VP8 decoding via libvpx
-
-
-Notable license related changes
--------------------------------
-
-- remaining GPL parts in AC-3 decoder converted to LGPL
-- libswscale can now be compiled in LGPL mode
-- libvpx is considered (L)GPL incompatible
diff --git a/VERSION b/VERSION
index 5a2a580..59aef28 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.6
+0.7b1
diff --git a/cmdutils.c b/cmdutils.c
index 2349b70..cc10b48 100644
--- a/cmdutils.c
+++ b/cmdutils.c
@@ -2,20 +2,20 @@
  * Various utilities for command line tools
  * Copyright (c) 2000-2003 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -35,7 +35,9 @@
 #include "libswscale/swscale.h"
 #include "libpostproc/postprocess.h"
 #include "libavutil/avstring.h"
+#include "libavutil/parseutils.h"
 #include "libavutil/pixdesc.h"
+#include "libavutil/eval.h"
 #include "libavcodec/opt.h"
 #include "cmdutils.h"
 #include "version.h"
@@ -47,18 +49,57 @@
 #endif
 
 const char **opt_names;
+const char **opt_values;
 static int opt_name_count;
 AVCodecContext *avcodec_opts[AVMEDIA_TYPE_NB];
 AVFormatContext *avformat_opts;
 struct SwsContext *sws_opts;
 
-const int this_year = 2010;
+static const int this_year = 2011;
+
+void init_opts(void)
+{
+    int i;
+    for (i = 0; i < AVMEDIA_TYPE_NB; i++)
+        avcodec_opts[i] = avcodec_alloc_context2(i);
+    avformat_opts = avformat_alloc_context();
+#if CONFIG_SWSCALE
+    sws_opts = sws_getContext(16, 16, 0, 16, 16, 0, SWS_BICUBIC, NULL, NULL, NULL);
+#endif
+}
+
+void uninit_opts(void)
+{
+    int i;
+    for (i = 0; i < AVMEDIA_TYPE_NB; i++)
+        av_freep(&avcodec_opts[i]);
+    av_freep(&avformat_opts->key);
+    av_freep(&avformat_opts);
+#if CONFIG_SWSCALE
+    av_freep(&sws_opts);
+#endif
+    for (i = 0; i < opt_name_count; i++) {
+        //opt_values are only stored for codec-specific options in which case
+        //both the name and value are dup'd
+        if (opt_values[i]) {
+            av_freep(&opt_names[i]);
+            av_freep(&opt_values[i]);
+        }
+    }
+    av_freep(&opt_names);
+    av_freep(&opt_values);
+}
+
+void log_callback_help(void* ptr, int level, const char* fmt, va_list vl)
+{
+    vfprintf(stdout, fmt, vl);
+}
 
 double parse_number_or_die(const char *context, const char *numstr, int type, double min, double max)
 {
     char *tail;
     const char *error;
-    double d = strtod(numstr, &tail);
+    double d = av_strtod(numstr, &tail);
     if (*tail)
         error= "Expected number for %s but found: %s\n";
     else if (d < min || d > max)
@@ -73,8 +114,8 @@ double parse_number_or_die(const char *context, const char *numstr, int type, do
 
 int64_t parse_time_or_die(const char *context, const char *timestr, int is_duration)
 {
-    int64_t us = parse_date(timestr, is_duration);
-    if (us == INT64_MIN) {
+    int64_t us;
+    if (av_parse_time(&us, timestr, is_duration) < 0) {
         fprintf(stderr, "Invalid %s specification for %s: %s\n",
                 is_duration ? "duration" : "date", context, timestr);
         exit(1);
@@ -167,7 +208,7 @@ unknown_opt:
             } else if (po->flags & OPT_INT64) {
                 *po->u.int64_arg = parse_number_or_die(opt, arg, OPT_INT64, INT64_MIN, INT64_MAX);
             } else if (po->flags & OPT_FLOAT) {
-                *po->u.float_arg = parse_number_or_die(opt, arg, OPT_FLOAT, -1.0/0.0, 1.0/0.0);
+                *po->u.float_arg = parse_number_or_die(opt, arg, OPT_FLOAT, -INFINITY, INFINITY);
             } else if (po->flags & OPT_FUNC2) {
                 if (po->u.func2_arg(opt, arg) < 0) {
                     fprintf(stderr, "%s: failed to set value '%s' for option '%s'\n", argv[0], arg, opt);
@@ -191,21 +232,21 @@ int opt_default(const char *opt, const char *arg){
     const AVOption *o= NULL;
     int opt_types[]={AV_OPT_FLAG_VIDEO_PARAM, AV_OPT_FLAG_AUDIO_PARAM, 0, AV_OPT_FLAG_SUBTITLE_PARAM, 0};
 
-    for(type=0; type<AVMEDIA_TYPE_NB && ret>= 0; type++){
+    for(type=0; *avcodec_opts && type<AVMEDIA_TYPE_NB && ret>= 0; type++){
         const AVOption *o2 = av_find_opt(avcodec_opts[0], opt, NULL, opt_types[type], opt_types[type]);
         if(o2)
             ret = av_set_string3(avcodec_opts[type], opt, arg, 1, &o);
     }
-    if(!o)
+    if(!o && avformat_opts)
         ret = av_set_string3(avformat_opts, opt, arg, 1, &o);
     if(!o && sws_opts)
         ret = av_set_string3(sws_opts, opt, arg, 1, &o);
     if(!o){
-        if(opt[0] == 'a')
+        if (opt[0] == 'a' && avcodec_opts[AVMEDIA_TYPE_AUDIO])
             ret = av_set_string3(avcodec_opts[AVMEDIA_TYPE_AUDIO], opt+1, arg, 1, &o);
-        else if(opt[0] == 'v')
+        else if(opt[0] == 'v' && avcodec_opts[AVMEDIA_TYPE_VIDEO])
             ret = av_set_string3(avcodec_opts[AVMEDIA_TYPE_VIDEO], opt+1, arg, 1, &o);
-        else if(opt[0] == 's')
+        else if(opt[0] == 's' && avcodec_opts[AVMEDIA_TYPE_SUBTITLE])
             ret = av_set_string3(avcodec_opts[AVMEDIA_TYPE_SUBTITLE], opt+1, arg, 1, &o);
     }
     if (o && ret < 0) {
@@ -213,17 +254,35 @@ int opt_default(const char *opt, const char *arg){
         exit(1);
     }
     if (!o) {
-        fprintf(stderr, "Unrecognized option '%s'\n", opt);
-        exit(1);
+        AVCodec *p = NULL;
+        AVOutputFormat *oformat = NULL;
+        while ((p=av_codec_next(p))){
+            AVClass *c= p->priv_class;
+            if(c && av_find_opt(&c, opt, NULL, 0, 0))
+                break;
+        }
+        if (!p) {
+            while ((oformat = av_oformat_next(oformat))) {
+                const AVClass *c = oformat->priv_class;
+                if (c && av_find_opt(&c, opt, NULL, 0, 0))
+                    break;
+            }
+        }
+        if(!p && !oformat){
+            fprintf(stderr, "Unrecognized option '%s'\n", opt);
+            exit(1);
+        }
     }
 
 //    av_log(NULL, AV_LOG_ERROR, "%s:%s: %f 0x%0X\n", opt, arg, av_get_double(avcodec_opts, opt, NULL), (int)av_get_int(avcodec_opts, opt, NULL));
 
     //FIXME we should always use avcodec_opts, ... for storing options so there will not be any need to keep track of what i set over this
+    opt_values= av_realloc(opt_values, sizeof(void*)*(opt_name_count+1));
+    opt_values[opt_name_count]= o ? NULL : av_strdup(arg);
     opt_names= av_realloc(opt_names, sizeof(void*)*(opt_name_count+1));
-    opt_names[opt_name_count++]= o->name;
+    opt_names[opt_name_count++]= o ? o->name : av_strdup(opt);
 
-    if(avcodec_opts[0]->debug || avformat_opts->debug)
+    if ((*avcodec_opts && avcodec_opts[0]->debug) || (avformat_opts && avformat_opts->debug))
         av_log_set_level(AV_LOG_DEBUG);
     return 0;
 }
@@ -276,9 +335,22 @@ int opt_timelimit(const char *opt, const char *arg)
     return 0;
 }
 
-void set_context_opts(void *ctx, void *opts_ctx, int flags)
+void set_context_opts(void *ctx, void *opts_ctx, int flags, AVCodec *codec)
 {
     int i;
+    void *priv_ctx=NULL;
+    if(!strcmp("AVCodecContext", (*(AVClass**)ctx)->class_name)){
+        AVCodecContext *avctx= ctx;
+        if(codec && codec->priv_class && avctx->priv_data){
+            priv_ctx= avctx->priv_data;
+        }
+    } else if (!strcmp("AVFormatContext", (*(AVClass**)ctx)->class_name)) {
+        AVFormatContext *avctx = ctx;
+        if (avctx->oformat && avctx->oformat->priv_class) {
+            priv_ctx = avctx->priv_data;
+        }
+    }
+
     for(i=0; i<opt_name_count; i++){
         char buf[256];
         const AVOption *opt;
@@ -286,6 +358,12 @@ void set_context_opts(void *ctx, void *opts_ctx, int flags)
         /* if an option with name opt_names[i] is present in opts_ctx then str is non-NULL */
         if(str && ((opt->flags & flags) == flags))
             av_set_string3(ctx, opt_names[i], str, 1, NULL);
+        /* We need to use a differnt system to pass options to the private context because
+           it is not known which codec and thus context kind that will be when parsing options
+           we thus use opt_values directly instead of opts_ctx */
+        if(!str && priv_ctx && av_get_string(priv_ctx, opt_names[i], &opt, buf, sizeof(buf))){
+            av_set_string3(priv_ctx, opt_names[i], opt_values[i], 1, NULL);
+        }
     }
 }
 
@@ -299,66 +377,64 @@ void print_error(const char *filename, int err)
     fprintf(stderr, "%s: %s\n", filename, errbuf_ptr);
 }
 
-#define PRINT_LIB_VERSION(outstream,libname,LIBNAME,indent)             \
-    if (CONFIG_##LIBNAME) {                                             \
-        unsigned int version = libname##_version();                     \
-        fprintf(outstream, "%slib%-10s %2d.%2d.%2d / %2d.%2d.%2d\n",    \
-                indent? "  " : "", #libname,                            \
-                LIB##LIBNAME##_VERSION_MAJOR,                           \
-                LIB##LIBNAME##_VERSION_MINOR,                           \
-                LIB##LIBNAME##_VERSION_MICRO,                           \
-                version >> 16, version >> 8 & 0xff, version & 0xff);    \
-    }
+static int warned_cfg = 0;
 
-static void print_all_lib_versions(FILE* outstream, int indent)
-{
-    PRINT_LIB_VERSION(outstream, avutil,   AVUTIL,   indent);
-    PRINT_LIB_VERSION(outstream, avcodec,  AVCODEC,  indent);
-    PRINT_LIB_VERSION(outstream, avformat, AVFORMAT, indent);
-    PRINT_LIB_VERSION(outstream, avdevice, AVDEVICE, indent);
-    PRINT_LIB_VERSION(outstream, avfilter, AVFILTER, indent);
-    PRINT_LIB_VERSION(outstream, swscale,  SWSCALE,  indent);
-    PRINT_LIB_VERSION(outstream, postproc, POSTPROC, indent);
-}
+#define INDENT        1
+#define SHOW_VERSION  2
+#define SHOW_CONFIG   4
 
-static void maybe_print_config(const char *lib, const char *cfg)
+#define PRINT_LIB_INFO(outstream,libname,LIBNAME,flags)                 \
+    if (CONFIG_##LIBNAME) {                                             \
+        const char *indent = flags & INDENT? "  " : "";                 \
+        if (flags & SHOW_VERSION) {                                     \
+            unsigned int version = libname##_version();                 \
+            fprintf(outstream, "%slib%-9s %2d.%3d.%2d / %2d.%3d.%2d\n", \
+                    indent, #libname,                                   \
+                    LIB##LIBNAME##_VERSION_MAJOR,                       \
+                    LIB##LIBNAME##_VERSION_MINOR,                       \
+                    LIB##LIBNAME##_VERSION_MICRO,                       \
+                    version >> 16, version >> 8 & 0xff, version & 0xff); \
+        }                                                               \
+        if (flags & SHOW_CONFIG) {                                      \
+            const char *cfg = libname##_configuration();                \
+            if (strcmp(LIBAV_CONFIGURATION, cfg)) {                     \
+                if (!warned_cfg) {                                      \
+                    fprintf(outstream,                                  \
+                            "%sWARNING: library configuration mismatch\n", \
+                            indent);                                    \
+                    warned_cfg = 1;                                     \
+                }                                                       \
+                fprintf(stderr, "%s%-11s configuration: %s\n",          \
+                        indent, #libname, cfg);                         \
+            }                                                           \
+        }                                                               \
+    }                                                                   \
+
+static void print_all_libs_info(FILE* outstream, int flags)
 {
-    static int warned_cfg;
-
-    if (strcmp(FFMPEG_CONFIGURATION, cfg)) {
-        if (!warned_cfg) {
-            fprintf(stderr, "  WARNING: library configuration mismatch\n");
-            warned_cfg = 1;
-        }
-        fprintf(stderr, "  %-11s configuration: %s\n", lib, cfg);
-    }
+    PRINT_LIB_INFO(outstream, avutil,   AVUTIL,   flags);
+    PRINT_LIB_INFO(outstream, avcodec,  AVCODEC,  flags);
+    PRINT_LIB_INFO(outstream, avformat, AVFORMAT, flags);
+    PRINT_LIB_INFO(outstream, avdevice, AVDEVICE, flags);
+    PRINT_LIB_INFO(outstream, avfilter, AVFILTER, flags);
+    PRINT_LIB_INFO(outstream, swscale,  SWSCALE,  flags);
+    PRINT_LIB_INFO(outstream, postproc, POSTPROC, flags);
 }
 
-#define PRINT_LIB_CONFIG(lib, tag, cfg) do {    \
-        if (CONFIG_##lib)                       \
-            maybe_print_config(tag, cfg);       \
-    } while (0)
-
 void show_banner(void)
 {
-    fprintf(stderr, "%s version " FFMPEG_VERSION ", Copyright (c) %d-%d the FFmpeg developers\n",
+    fprintf(stderr, "%s version " LIBAV_VERSION ", Copyright (c) %d-%d the Libav developers\n",
             program_name, program_birth_year, this_year);
     fprintf(stderr, "  built on %s %s with %s %s\n",
             __DATE__, __TIME__, CC_TYPE, CC_VERSION);
-    fprintf(stderr, "  configuration: " FFMPEG_CONFIGURATION "\n");
-    PRINT_LIB_CONFIG(AVUTIL,   "libavutil",   avutil_configuration());
-    PRINT_LIB_CONFIG(AVCODEC,  "libavcodec",  avcodec_configuration());
-    PRINT_LIB_CONFIG(AVFORMAT, "libavformat", avformat_configuration());
-    PRINT_LIB_CONFIG(AVDEVICE, "libavdevice", avdevice_configuration());
-    PRINT_LIB_CONFIG(AVFILTER, "libavfilter", avfilter_configuration());
-    PRINT_LIB_CONFIG(SWSCALE,  "libswscale",  swscale_configuration());
-    PRINT_LIB_CONFIG(POSTPROC, "libpostproc", postproc_configuration());
-    print_all_lib_versions(stderr, 1);
+    fprintf(stderr, "  configuration: " LIBAV_CONFIGURATION "\n");
+    print_all_libs_info(stderr, INDENT|SHOW_CONFIG);
+    print_all_libs_info(stderr, INDENT|SHOW_VERSION);
 }
 
 void show_version(void) {
-    printf("%s " FFMPEG_VERSION "\n", program_name);
-    print_all_lib_versions(stdout, 0);
+    printf("%s " LIBAV_VERSION "\n", program_name);
+    print_all_libs_info(stdout, SHOW_VERSION);
 }
 
 void show_license(void)
@@ -577,11 +653,16 @@ void show_bsfs(void)
 
 void show_protocols(void)
 {
-    URLProtocol *up=NULL;
-
-    printf("Supported file protocols:\n");
-    while((up = av_protocol_next(up)))
-        printf("%s\n", up->name);
+    void *opaque = NULL;
+    const char *name;
+
+    printf("Supported file protocols:\n"
+           "Input:\n");
+    while ((name = avio_enum_protocols(&opaque, 0)))
+        printf("%s\n", name);
+    printf("Output:\n");
+    while ((name = avio_enum_protocols(&opaque, 1)))
+        printf("%s\n", name);
 }
 
 void show_filters(void)
@@ -662,3 +743,123 @@ int read_file(const char *filename, char **bufptr, size_t *size)
     fclose(f);
     return 0;
 }
+
+void init_pts_correction(PtsCorrectionContext *ctx)
+{
+    ctx->num_faulty_pts = ctx->num_faulty_dts = 0;
+    ctx->last_pts = ctx->last_dts = INT64_MIN;
+}
+
+int64_t guess_correct_pts(PtsCorrectionContext *ctx, int64_t reordered_pts, int64_t dts)
+{
+    int64_t pts = AV_NOPTS_VALUE;
+
+    if (dts != AV_NOPTS_VALUE) {
+        ctx->num_faulty_dts += dts <= ctx->last_dts;
+        ctx->last_dts = dts;
+    }
+    if (reordered_pts != AV_NOPTS_VALUE) {
+        ctx->num_faulty_pts += reordered_pts <= ctx->last_pts;
+        ctx->last_pts = reordered_pts;
+    }
+    if ((ctx->num_faulty_pts<=ctx->num_faulty_dts || dts == AV_NOPTS_VALUE)
+       && reordered_pts != AV_NOPTS_VALUE)
+        pts = reordered_pts;
+    else
+        pts = dts;
+
+    return pts;
+}
+
+FILE *get_preset_file(char *filename, size_t filename_size,
+                      const char *preset_name, int is_path, const char *codec_name)
+{
+    FILE *f = NULL;
+    int i;
+    const char *base[3]= { getenv("FFMPEG_DATADIR"),
+                           getenv("HOME"),
+                           FFMPEG_DATADIR,
+                         };
+
+    if (is_path) {
+        av_strlcpy(filename, preset_name, filename_size);
+        f = fopen(filename, "r");
+    } else {
+        for (i = 0; i < 3 && !f; i++) {
+            if (!base[i])
+                continue;
+            snprintf(filename, filename_size, "%s%s/%s.ffpreset", base[i], i != 1 ? "" : "/.ffmpeg", preset_name);
+            f = fopen(filename, "r");
+            if (!f && codec_name) {
+                snprintf(filename, filename_size,
+                         "%s%s/%s-%s.ffpreset", base[i],  i != 1 ? "" : "/.ffmpeg", codec_name, preset_name);
+                f = fopen(filename, "r");
+            }
+        }
+    }
+
+    return f;
+}
+
+#if CONFIG_AVFILTER
+
+static int ffsink_init(AVFilterContext *ctx, const char *args, void *opaque)
+{
+    FFSinkContext *priv = ctx->priv;
+
+    if (!opaque)
+        return AVERROR(EINVAL);
+    *priv = *(FFSinkContext *)opaque;
+
+    return 0;
+}
+
+static void null_end_frame(AVFilterLink *inlink) { }
+
+static int ffsink_query_formats(AVFilterContext *ctx)
+{
+    FFSinkContext *priv = ctx->priv;
+    enum PixelFormat pix_fmts[] = { priv->pix_fmt, PIX_FMT_NONE };
+
+    avfilter_set_common_formats(ctx, avfilter_make_format_list(pix_fmts));
+    return 0;
+}
+
+AVFilter ffsink = {
+    .name      = "ffsink",
+    .priv_size = sizeof(FFSinkContext),
+    .init      = ffsink_init,
+
+    .query_formats = ffsink_query_formats,
+
+    .inputs    = (AVFilterPad[]) {{ .name          = "default",
+                                    .type          = AVMEDIA_TYPE_VIDEO,
+                                    .end_frame     = null_end_frame,
+                                    .min_perms     = AV_PERM_READ, },
+                                  { .name = NULL }},
+    .outputs   = (AVFilterPad[]) {{ .name = NULL }},
+};
+
+int get_filtered_video_frame(AVFilterContext *ctx, AVFrame *frame,
+                             AVFilterBufferRef **picref_ptr, AVRational *tb)
+{
+    int ret;
+    AVFilterBufferRef *picref;
+
+    if ((ret = avfilter_request_frame(ctx->inputs[0])) < 0)
+        return ret;
+    if (!(picref = ctx->inputs[0]->cur_buf))
+        return AVERROR(ENOENT);
+    *picref_ptr = picref;
+    ctx->inputs[0]->cur_buf = NULL;
+    *tb = ctx->inputs[0]->time_base;
+
+    memcpy(frame->data,     picref->data,     sizeof(frame->data));
+    memcpy(frame->linesize, picref->linesize, sizeof(frame->linesize));
+    frame->interlaced_frame = picref->video->interlaced;
+    frame->top_field_first  = picref->video->top_field_first;
+
+    return 1;
+}
+
+#endif /* CONFIG_AVFILTER */
diff --git a/cmdutils.h b/cmdutils.h
index 5656370..0067295 100644
--- a/cmdutils.h
+++ b/cmdutils.h
@@ -2,20 +2,20 @@
  * Various utilities for command line tools
  * copyright (c) 2003 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -37,21 +37,36 @@ extern const char program_name[];
  */
 extern const int program_birth_year;
 
-extern const int this_year;
-
 extern const char **opt_names;
 extern AVCodecContext *avcodec_opts[AVMEDIA_TYPE_NB];
 extern AVFormatContext *avformat_opts;
 extern struct SwsContext *sws_opts;
 
 /**
+ * Initialize the cmdutils option system, in particular
+ * allocate the *_opts contexts.
+ */
+void init_opts(void);
+/**
+ * Uninitialize the cmdutils option system, in particular
+ * free the *_opts contexts and their contents.
+ */
+void uninit_opts(void);
+
+/**
+ * Trivial log callback.
+ * Only suitable for show_help and similar since it lacks prefix handling.
+ */
+void log_callback_help(void* ptr, int level, const char* fmt, va_list vl);
+
+/**
  * Fallback for options that are not explicitly handled, these will be
  * parsed through AVOptions.
  */
 int opt_default(const char *opt, const char *arg);
 
 /**
- * Sets the libav* libraries log level.
+ * Set the libav* libraries log level.
  */
 int opt_loglevel(const char *opt, const char *arg);
 
@@ -61,8 +76,8 @@ int opt_loglevel(const char *opt, const char *arg);
 int opt_timelimit(const char *opt, const char *arg);
 
 /**
- * Parses a string and returns its corresponding value as a double.
- * Exits from the application if the string cannot be correctly
+ * Parse a string and return its corresponding value as a double.
+ * Exit from the application if the string cannot be correctly
  * parsed or the corresponding value is invalid.
  *
  * @param context the context of the value to be set (e.g. the
@@ -76,8 +91,8 @@ int opt_timelimit(const char *opt, const char *arg);
 double parse_number_or_die(const char *context, const char *numstr, int type, double min, double max);
 
 /**
- * Parses a string specifying a time and returns its corresponding
- * value as a number of microseconds. Exits from the application if
+ * Parse a string specifying a time and return its corresponding
+ * value as a number of microseconds. Exit from the application if
  * the string cannot be correctly parsed.
  *
  * @param context the context of the value to be set (e.g. the
@@ -122,9 +137,9 @@ typedef struct {
 void show_help_options(const OptionDef *options, const char *msg, int mask, int value);
 
 /**
- * Parses the command line arguments.
+ * Parse the command line arguments.
  * @param options Array with the definitions required to interpret every
- * option of the form: -<option_name> [<argument>]
+ * option of the form: -option_name [argument]
  * @param parse_arg_function Name of the function called to process every
  * argument without a leading option name flag. NULL if such arguments do
  * not have to be processed.
@@ -132,10 +147,10 @@ void show_help_options(const OptionDef *options, const char *msg, int mask, int
 void parse_options(int argc, char **argv, const OptionDef *options,
                    void (* parse_arg_function)(const char*));
 
-void set_context_opts(void *ctx, void *opts_ctx, int flags);
+void set_context_opts(void *ctx, void *opts_ctx, int flags, AVCodec *codec);
 
 /**
- * Prints an error message to stderr, indicating filename and a human
+ * Print an error message to stderr, indicating filename and a human
  * readable description of the error code err.
  *
  * If strerror_r() is not available the use of this function in a
@@ -148,76 +163,140 @@ void print_error(const char *filename, int err);
 void list_fmts(void (*get_fmt_string)(char *buf, int buf_size, int fmt), int nb_fmts);
 
 /**
- * Prints the program banner to stderr. The banner contents depend on the
+ * Print the program banner to stderr. The banner contents depend on the
  * current version of the repository and of the libav* libraries used by
  * the program.
  */
 void show_banner(void);
 
 /**
- * Prints the version of the program to stdout. The version message
+ * Print the version of the program to stdout. The version message
  * depends on the current versions of the repository and of the libav*
  * libraries.
  */
 void show_version(void);
 
 /**
- * Prints the license of the program to stdout. The license depends on
+ * Print the license of the program to stdout. The license depends on
  * the license of the libraries compiled into the program.
  */
 void show_license(void);
 
 /**
- * Prints a listing containing all the formats supported by the
+ * Print a listing containing all the formats supported by the
  * program.
  */
 void show_formats(void);
 
 /**
- * Prints a listing containing all the codecs supported by the
+ * Print a listing containing all the codecs supported by the
  * program.
  */
 void show_codecs(void);
 
 /**
- * Prints a listing containing all the filters supported by the
+ * Print a listing containing all the filters supported by the
  * program.
  */
 void show_filters(void);
 
 /**
- * Prints a listing containing all the bit stream filters supported by the
+ * Print a listing containing all the bit stream filters supported by the
  * program.
  */
 void show_bsfs(void);
 
 /**
- * Prints a listing containing all the protocols supported by the
+ * Print a listing containing all the protocols supported by the
  * program.
  */
 void show_protocols(void);
 
 /**
- * Prints a listing containing all the pixel formats supported by the
+ * Print a listing containing all the pixel formats supported by the
  * program.
  */
 void show_pix_fmts(void);
 
 /**
- * Returns a positive value if reads from standard input a line
- * starting with [yY], otherwise returns 0.
+ * Return a positive value if a line read from standard input
+ * starts with [yY], otherwise return 0.
  */
 int read_yesno(void);
 
 /**
- * Reads the file with name filename, and puts its content in a newly
+ * Read the file with name filename, and put its content in a newly
  * allocated 0-terminated buffer.
  *
- * @param bufptr puts here the pointer to the newly allocated buffer
- * @param size puts here the size of the newly allocated buffer
+ * @param bufptr location where pointer to buffer is returned
+ * @param size   location where size of buffer is returned
  * @return 0 in case of success, a negative value corresponding to an
  * AVERROR error code in case of failure.
  */
 int read_file(const char *filename, char **bufptr, size_t *size);
 
+typedef struct {
+    int64_t num_faulty_pts; /// Number of incorrect PTS values so far
+    int64_t num_faulty_dts; /// Number of incorrect DTS values so far
+    int64_t last_pts;       /// PTS of the last frame
+    int64_t last_dts;       /// DTS of the last frame
+} PtsCorrectionContext;
+
+/**
+ * Reset the state of the PtsCorrectionContext.
+ */
+void init_pts_correction(PtsCorrectionContext *ctx);
+
+/**
+ * Attempt to guess proper monotonic timestamps for decoded video frames
+ * which might have incorrect times. Input timestamps may wrap around, in
+ * which case the output will as well.
+ *
+ * @param pts the pts field of the decoded AVPacket, as passed through
+ * AVCodecContext.reordered_opaque
+ * @param dts the dts field of the decoded AVPacket
+ * @return one of the input values, may be AV_NOPTS_VALUE
+ */
+int64_t guess_correct_pts(PtsCorrectionContext *ctx, int64_t pts, int64_t dts);
+
+/**
+ * Get a file corresponding to a preset file.
+ *
+ * If is_path is non-zero, look for the file in the path preset_name.
+ * Otherwise search for a file named arg.ffpreset in the directories
+ * $FFMPEG_DATADIR (if set), $HOME/.ffmpeg, and in the datadir defined
+ * at configuration time, in that order. If no such file is found and
+ * codec_name is defined, then search for a file named
+ * codec_name-preset_name.ffpreset in the above-mentioned directories.
+ *
+ * @param filename buffer where the name of the found filename is written
+ * @param filename_size size in bytes of the filename buffer
+ * @param preset_name name of the preset to search
+ * @param is_path tell if preset_name is a filename path
+ * @param codec_name name of the codec for which to look for the
+ * preset, may be NULL
+ */
+FILE *get_preset_file(char *filename, size_t filename_size,
+                      const char *preset_name, int is_path, const char *codec_name);
+
+#if CONFIG_AVFILTER
+#include "libavfilter/avfilter.h"
+
+typedef struct {
+    enum PixelFormat pix_fmt;
+} FFSinkContext;
+
+extern AVFilter ffsink;
+
+/**
+ * Extract a frame from sink.
+ *
+ * @return a negative error in case of failure, 1 if one frame has
+ * been extracted successfully.
+ */
+int get_filtered_video_frame(AVFilterContext *sink, AVFrame *frame,
+                             AVFilterBufferRef **picref, AVRational *pts_tb);
+
+#endif /* CONFIG_AVFILTER */
+
 #endif /* FFMPEG_CMDUTILS_H */
diff --git a/common.mak b/common.mak
index 25a5d81..03fae6f 100644
--- a/common.mak
+++ b/common.mak
@@ -21,20 +21,24 @@ endif
 ifndef V
 Q      = @
 ECHO   = printf "$(1)\t%s\n" $(2)
-BRIEF  = CC AS YASM AR LD HOSTCC STRIP CP
+BRIEF  = CC AS YASM AR LD HOSTCC
 SILENT = DEPCC YASMDEP RM RANLIB
 MSG    = $@
 M      = @$(call ECHO,$(TAG),$@);
 $(foreach VAR,$(BRIEF), \
-    $(eval $(VAR) = @$$(call ECHO,$(VAR),$$(MSG)); $($(VAR))))
-$(foreach VAR,$(SILENT),$(eval $(VAR) = @$($(VAR))))
+    $(eval override $(VAR) = @$$(call ECHO,$(VAR),$$(MSG)); $($(VAR))))
+$(foreach VAR,$(SILENT),$(eval override $(VAR) = @$($(VAR))))
 $(eval INSTALL = @$(call ECHO,INSTALL,$$(^:$(SRC_DIR)/%=%)); $(INSTALL))
 endif
 
 ALLFFLIBS = avcodec avdevice avfilter avformat avutil postproc swscale
 
-CPPFLAGS := -I$(BUILD_ROOT_REL) -I$(SRC_PATH) $(CPPFLAGS)
+IFLAGS   := -I$(BUILD_ROOT_REL) -I$(SRC_PATH)
+CPPFLAGS := $(IFLAGS) $(CPPFLAGS)
 CFLAGS   += $(ECFLAGS)
+YASMFLAGS += $(IFLAGS) -Pconfig.asm
+
+HOSTCFLAGS += $(IFLAGS)
 
 %.o: %.c
 	$(CCDEP)
@@ -54,6 +58,10 @@ CFLAGS   += $(ECFLAGS)
 
 %.c %.h: TAG = GEN
 
+# Dummy rule to stop make trying to rebuild removed or renamed headers
+%.h:
+	@:
+
 install: install-libs install-headers
 install-libs: install-libs-yes
 
@@ -81,7 +89,7 @@ FFLDFLAGS   := $(addprefix -L$(BUILD_ROOT)/lib,$(ALLFFLIBS)) $(LDFLAGS)
 
 EXAMPLES  := $(addprefix $(SUBDIR),$(addsuffix -example$(EXESUF),$(EXAMPLES)))
 OBJS      := $(addprefix $(SUBDIR),$(sort $(OBJS)))
-TESTOBJS  := $(addprefix $(SUBDIR),$(TESTOBJS))
+TESTOBJS  := $(addprefix $(SUBDIR),$(TESTOBJS) $(TESTPROGS:%=%-test.o))
 TESTPROGS := $(addprefix $(SUBDIR),$(addsuffix -test$(EXESUF),$(TESTPROGS)))
 HOSTOBJS  := $(addprefix $(SUBDIR),$(addsuffix .o,$(HOSTPROGS)))
 HOSTPROGS := $(addprefix $(SUBDIR),$(addsuffix $(HOSTEXESUF),$(HOSTPROGS)))
@@ -99,11 +107,8 @@ $(HOSTOBJS): %.o: %.c
 $(HOSTPROGS): %$(HOSTEXESUF): %.o
 	$(HOSTCC) $(HOSTLDFLAGS) -o $@ $< $(HOSTLIBS)
 
-DEPS := $(OBJS:.o=.d)
-depend dep: $(DEPS)
-
 CLEANSUFFIXES     = *.d *.o *~ *.ho *.map *.ver
 DISTCLEANSUFFIXES = *.pc
 LIBSUFFIXES       = *.a *.lib *.so *.so.* *.dylib *.dll *.def *.dll.a *.exp
 
--include $(wildcard $(DEPS))
+-include $(wildcard $(OBJS:.o=.d) $(TESTOBJS:.o=.d))
diff --git a/configure b/configure
index 0166829..32c3544 100755
--- a/configure
+++ b/configure
@@ -1,6 +1,6 @@
 #!/bin/sh
 #
-# FFmpeg configure script
+# Libav configure script
 #
 # Copyright (c) 2000-2002 Fabrice Bellard
 # Copyright (c) 2005-2008 Diego Biurrun
@@ -44,9 +44,9 @@ if test "$E1" != 0 || test "$E2" = 0; then
     echo "No compatible shell script interpreter found."
     echo "This configure script requires a POSIX-compatible shell"
     echo "such as bash or ksh."
-    echo "THIS IS NOT A BUG IN FFMPEG, DO NOT REPORT IT AS SUCH."
+    echo "THIS IS NOT A BUG IN LIBAV, DO NOT REPORT IT AS SUCH."
     echo "Instead, install a working POSIX-compatible shell."
-    echo "Disabling this configure test will create a broken FFmpeg."
+    echo "Disabling this configure test will create a broken Libav."
     if test "$BASH_VERSION" = '2.04.0(1)-release'; then
         echo "This bash version ($BASH_VERSION) is broken on your platform."
         echo "Upgrade to a later version if available."
@@ -61,7 +61,7 @@ Options: [defaults in brackets after descriptions]
 
 Standard options:
   --help                   print this message
-  --logfile=FILE           log tests and output to FILE [config.err]
+  --logfile=FILE           log tests and output to FILE [config.log]
   --disable-logging        do not log configure debug information
   --prefix=PREFIX          install in PREFIX [$prefix]
   --bindir=DIR             install binaries in DIR [PREFIX/bin]
@@ -89,11 +89,8 @@ Configuration options:
   --disable-avformat       disable libavformat build
   --disable-swscale        disable libswscale build
   --enable-postproc        enable GPLed postprocessing support [no]
-  --enable-avfilter        video filter support [no]
-  --enable-avfilter-lavf   video filters dependent on avformat [no]
-  --enable-beosthreads     use BeOS threads [no]
-  --enable-os2threads      use OS/2 threads [no]
-  --enable-pthreads        use pthreads [no]
+  --disable-avfilter       disable video filter support [no]
+  --disable-pthreads       disable pthreads [auto]
   --enable-w32threads      use Win32 threads [no]
   --enable-x11grab         enable X11 grabbing [no]
   --disable-network        disable network support [no]
@@ -106,6 +103,7 @@ Configuration options:
   --disable-dct            disable DCT code
   --disable-fft            disable FFT code
   --disable-golomb         disable Golomb code
+  --disable-huffman        disable Huffman code
   --disable-lpc            disable LPC code
   --disable-mdct           disable MDCT code
   --disable-rdft           disable RDFT code
@@ -115,7 +113,6 @@ Configuration options:
   --enable-runtime-cpudetect detect cpu capabilities at runtime (bigger binary)
   --enable-hardcoded-tables use hardcoded tables instead of runtime generation
   --enable-memalign-hack   emulate memalign, interferes with memory debuggers
-  --enable-beos-netserver  enable BeOS netserver
   --disable-everything     disable all components listed below
   --disable-encoder=NAME   disable encoder NAME
   --enable-encoder=NAME    enable encoder NAME
@@ -164,14 +161,14 @@ Configuration options:
 External library support:
   --enable-avisynth        enable reading of AVISynth script files [no]
   --enable-bzlib           enable bzlib [autodetect]
+  --enable-frei0r          enable frei0r video filtering
   --enable-libopencore-amrnb enable AMR-NB de/encoding via libopencore-amrnb [no]
   --enable-libopencore-amrwb enable AMR-WB decoding via libopencore-amrwb [no]
+  --enable-libopencv       enable video filtering via libopencv [no]
   --enable-libdc1394       enable IIDC-1394 grabbing using libdc1394
                            and libraw1394 [no]
   --enable-libdirac        enable Dirac support via libdirac [no]
   --enable-libfaac         enable FAAC support via libfaac [no]
-  --enable-libfaad         enable FAAD support via libfaad [no]
-  --enable-libfaadbin      open libfaad.so.0 at runtime [no]
   --enable-libgsm          enable GSM support via libgsm [no]
   --enable-libmp3lame      enable MP3 encoding via libmp3lame [no]
   --enable-libnut          enable NUT (de)muxing via libnut,
@@ -181,10 +178,13 @@ External library support:
   --enable-libschroedinger enable Dirac support via libschroedinger [no]
   --enable-libspeex        enable Speex decoding via libspeex [no]
   --enable-libtheora       enable Theora encoding via libtheora [no]
+  --enable-libvo-aacenc    enable AAC encoding via libvo-aacenc [no]
+  --enable-libvo-amrwbenc  enable AMR-WB encoding via libvo-amrwbenc [no]
   --enable-libvorbis       enable Vorbis encoding via libvorbis,
                            native implementation exists [no]
   --enable-libvpx          enable VP8 support via libvpx [no]
   --enable-libx264         enable H.264 encoding via x264 [no]
+  --enable-libxavs         enable AVS encoding via xavs [no]
   --enable-libxvid         enable Xvid encoding via xvidcore,
                            native MPEG-4/Xvid encoder exists [no]
   --enable-mlib            enable Sun medialib [no]
@@ -216,8 +216,6 @@ Advanced options (experts only):
   --arch=ARCH              select architecture [$arch]
   --cpu=CPU                select the minimum required CPU (affects
                            instruction selection, may crash on older CPUs)
-  --enable-powerpc-perf    enable performance report on PPC
-                           (requires enabling PMC)
   --disable-asm            disable all assembler optimizations
   --disable-altivec        disable AltiVec optimizations
   --disable-amd3dnow       disable 3DNow! optimizations
@@ -226,6 +224,7 @@ Advanced options (experts only):
   --disable-mmx2           disable MMX2 optimizations
   --disable-sse            disable SSE optimizations
   --disable-ssse3          disable SSSE3 optimizations
+  --disable-avx            disable AVX optimizations
   --disable-armv5te        disable armv5te optimizations
   --disable-armv6          disable armv6 optimizations
   --disable-armv6t2        disable armv6t2 optimizations
@@ -238,15 +237,15 @@ Advanced options (experts only):
   --enable-pic             build position-independent code
   --malloc-prefix=PFX      prefix malloc and related names with PFX
   --enable-sram            allow use of on-chip SRAM
+  --disable-symver         disable symbol versioning
 
-Developer options (useful when working on FFmpeg itself):
+Developer options (useful when working on Libav itself):
   --disable-debug          disable debugging symbols
   --enable-debug=LEVEL     set the debug level [$debuglevel]
-  --enable-gprof           enable profiling with gprof [$gprof]
   --disable-optimizations  disable compiler optimizations
   --enable-extra-warnings  enable more compiler warnings
-  --disable-stripping      disable stripping of executables and shared libraries
-  --samples=PATH           location of test samples for FATE
+  --samples=PATH           location of test samples for FATE, if not set use
+                           \$FATE_SAMPLES at make invocation time.
 
 NOTE: Object files are built at the place where configure is launched.
 EOF
@@ -270,13 +269,18 @@ echolog(){
     echo "$@"
 }
 
+warn(){
+    log "WARNING: $*"
+    WARNINGS="${WARNINGS}WARNING: $*\n"
+}
+
 die(){
     echolog "$@"
     cat <<EOF
 
 If you think configure made a mistake, make sure you are using the latest
-version from SVN.  If the latest version fails, report the problem to the
-ffmpeg-user at mplayerhq.hu mailing list or IRC #ffmpeg on irc.freenode.net.
+version from Git.  If the latest version fails, report the problem to the
+libav-user at libav.org mailing list or IRC #libav on irc.freenode.net.
 EOF
     if disabled logging; then
         cat <<EOF
@@ -307,10 +311,14 @@ c_escape(){
 
 sh_quote(){
     v=$(echo "$1" | sed "s/'/'\\\\''/g")
-    test "$v" = "${v#*[ |&;<>()$\`\\\"\'*?\[\]#~=%]}" || v="'$v'"
+    test "x$v" = "x${v#*[!A-Za-z0-9_/.+-]}" || v="'$v'"
     echo "$v"
 }
 
+cleanws(){
+    echo "$@" | sed 's/^ *//;s/  */ /g;s/ *$//'
+}
+
 filter(){
     pat=$1
     shift
@@ -319,6 +327,14 @@ filter(){
     done
 }
 
+filter_out(){
+    pat=$1
+    shift
+    for v; do
+        eval "case $v in $pat) ;; *) echo $v ;; esac"
+    done
+}
+
 map(){
     m=$1
     shift
@@ -341,6 +357,16 @@ set_weak(){
     done
 }
 
+set_safe(){
+    var=$1
+    shift
+    eval $(echo "$var" | sed 's/[^A-Za-z0-9_]/_/g')='$*'
+}
+
+get_safe(){
+    eval echo \$$(echo "$1" | sed 's/[^A-Za-z0-9_]/_/g')
+}
+
 pushvar(){
     for var in $*; do
         eval level=\${${var}_level:=0}
@@ -496,66 +522,53 @@ check_deps(){
     done
 }
 
-print_config(){
-    pfx=$1
-    header=$2
-    makefile=$3
-    shift 3
-    for cfg; do
-        ucname="$(toupper $cfg)"
-        if enabled $cfg; then
-            echo "#define ${pfx}${ucname} 1" >> $header
-            echo "${pfx}${ucname}=yes" >> $makefile
-        else
-            echo "#define ${pfx}${ucname} 0" >> $header
-            echo "!${pfx}${ucname}=yes" >> $makefile
-        fi
-    done
-}
-
-flags_saved(){
-    (: ${SAVE_CFLAGS?}) 2> /dev/null
+print_config_h(){
+    enabled $1 && v=1 || v=0
+    echo "#define $2 $v"
 }
 
-save_flags(){
-    flags_saved && return
-    SAVE_CFLAGS="$CFLAGS"
-    SAVE_LDFLAGS="$LDFLAGS"
-    SAVE_extralibs="$extralibs"
+print_config_mak(){
+    enabled $1 && v= || v=!
+    echo "$v$2=yes"
 }
 
-restore_flags(){
-    flags_saved || return
-    CFLAGS="$SAVE_CFLAGS"
-    LDFLAGS="$SAVE_LDFLAGS"
-    extralibs="$SAVE_extralibs"
-    unset SAVE_CFLAGS
-    unset SAVE_LDFLAGS
-    unset SAVE_extralibs
+print_config_asm(){
+    enabled $1 && echo "%define $2"
 }
 
-temp_cflags(){
-    save_flags
-    CFLAGS="$CFLAGS $*"
-}
-
-temp_ldflags(){
-    save_flags
-    LDFLAGS="$LDFLAGS $*"
+print_config(){
+    pfx=$1
+    files=$2
+    shift 2
+    for cfg; do
+        ucname="$(toupper $cfg)"
+        for f in $files; do
+            "print_config_${f##*.}" $cfg ${pfx}${ucname} >>$f
+        done
+    done
 }
 
-temp_extralibs(){
-    save_flags
-    extralibs="$extralibs $*"
+print_enabled(){
+    test "$1" = -n && end=" " && shift || end="\n"
+    suf=$1
+    shift
+    for v; do
+        enabled $v && printf "%s$end" ${v%$suf};
+    done
 }
 
 append(){
     var=$1
     shift
-    flags_saved && eval "SAVE_$var=\"\$SAVE_$var $*\""
     eval "$var=\"\$$var $*\""
 }
 
+prepend(){
+    var=$1
+    shift
+    eval "$var=\"$* \$$var\""
+}
+
 add_cppflags(){
     append CPPFLAGS $($filter_cppflags "$@")
 }
@@ -573,7 +586,7 @@ add_ldflags(){
 }
 
 add_extralibs(){
-    append extralibs "$@"
+    prepend extralibs "$@"
 }
 
 check_cmd(){
@@ -629,7 +642,7 @@ check_ld(){
         test "${f}" = "${f#-l}" && flags="$flags $f" || libs="$libs $f"
     done
     check_cc $($filter_cflags $flags) || return
-    check_cmd $ld $LDFLAGS $flags -o $TMPE $TMPO $extralibs $libs
+    check_cmd $ld $LDFLAGS $flags -o $TMPE $TMPO $libs $extralibs
 }
 
 check_cppflags(){
@@ -697,20 +710,17 @@ EOF
 check_func_headers(){
     log check_func_headers "$@"
     headers=$1
-    func=$2
+    funcs=$2
     shift 2
-    disable $func
-    incs=""
-    for hdr in $headers; do
-        incs="$incs
-#include <$hdr>"
-    done
-    check_ld "$@" <<EOF && enable $func && enable_safe $headers
-$incs
-int main(int argc, char **argv){
-    return (long) $func;
-}
-EOF
+    {
+        for hdr in $headers; do
+            echo "#include <$hdr>"
+        done
+        for func in $funcs; do
+            echo "long check_$func(void) { return (long) $func; }"
+        done
+        echo "int main(void) { return 0; }"
+    } | check_ld "$@" && enable $funcs && enable_safe $headers
 }
 
 check_cpp_condition(){
@@ -731,19 +741,29 @@ check_lib(){
     header="$1"
     func="$2"
     shift 2
-    temp_extralibs "$@"
-    check_header $header && check_func $func && add_extralibs "$@"
-    err=$?
-    restore_flags
-    return $err
+    check_header $header && check_func $func "$@" && add_extralibs "$@"
 }
 
 check_lib2(){
     log check_lib2 "$@"
     headers="$1"
-    func="$2"
+    funcs="$2"
     shift 2
-    check_func_headers "$headers" $func "$@" && add_extralibs "$@"
+    check_func_headers "$headers" "$funcs" "$@" && add_extralibs "$@"
+}
+
+check_pkg_config(){
+    log check_pkg_config "$@"
+    pkg="$1"
+    headers="$2"
+    funcs="$3"
+    shift 3
+    $pkg_config --exists $pkg || return
+    pkg_cflags=$($pkg_config --cflags $pkg)
+    pkg_libs=$($pkg_config --libs $pkg)
+    check_func_headers "$headers" "$funcs" $pkg_cflags $pkg_libs "$@" &&
+        set_safe ${pkg}_cflags $pkg_cflags   &&
+        set_safe ${pkg}_libs   $pkg_libs
 }
 
 check_exec(){
@@ -827,21 +847,11 @@ require2(){
     check_lib2 "$headers" $func "$@" || die "ERROR: $name not found"
 }
 
-check_foo_config(){
-    cfg=$1
-    pkg=$2
-    header=$3
-    func=$4
-    shift 4
-    disable $cfg
-    check_cmd ${pkg}-config --version
-    err=$?
-    if test "$err" = 0; then
-        temp_cflags $(${pkg}-config --cflags)
-        temp_extralibs $(${pkg}-config --libs)
-        check_lib "$@" $header $func && enable $cfg
-    fi
-    return $err
+require_pkg_config(){
+    pkg="$1"
+    check_pkg_config "$@" || die "ERROR: $pkg not found"
+    add_cflags    $(get_safe ${pkg}_cflags)
+    add_extralibs $(get_safe ${pkg}_libs)
 }
 
 check_host_cc(){
@@ -890,13 +900,12 @@ COMPONENT_LIST="
 CONFIG_LIST="
     $COMPONENT_LIST
     aandct
+    ac3dsp
     avcodec
     avdevice
     avfilter
-    avfilter_lavf
     avformat
     avisynth
-    beos_netserver
     bzlib
     dct
     doc
@@ -908,30 +917,34 @@ CONFIG_LIST="
     ffprobe
     ffserver
     fft
+    frei0r
     golomb
     gpl
-    gprof
     gray
     h264dsp
+    h264pred
     hardcoded_tables
+    huffman
     libdc1394
     libdirac
     libfaac
-    libfaad
-    libfaadbin
     libgsm
     libmp3lame
     libnut
     libopencore_amrnb
     libopencore_amrwb
+    libopencv
     libopenjpeg
     librtmp
     libschroedinger
     libspeex
     libtheora
+    libvo_aacenc
+    libvo_amrwbenc
     libvorbis
     libvpx
     libx264
+    libxavs
     libxvid
     lpc
     lsp
@@ -943,10 +956,11 @@ CONFIG_LIST="
     nonfree
     pic
     postproc
-    powerpc_perf
     rdft
+    rtpdec
     runtime_cpudetect
     shared
+    sinewin
     small
     sram
     static
@@ -960,8 +974,6 @@ CONFIG_LIST="
 "
 
 THREADS_LIST='
-    beosthreads
-    os2threads
     pthreads
     w32threads
 '
@@ -998,6 +1010,7 @@ ARCH_EXT_LIST='
     armv6
     armv6t2
     armvfp
+    avx
     iwmmxt
     mmi
     mmx
@@ -1011,12 +1024,14 @@ ARCH_EXT_LIST='
 
 HAVE_LIST_PUB='
     bigendian
+    fast_unaligned
 '
 
 HAVE_LIST="
     $ARCH_EXT_LIST
     $HAVE_LIST_PUB
     $THREADS_LIST
+    aligned_stack
     alsa_asoundlib_h
     altivec_h
     arpa_inet_h
@@ -1025,7 +1040,6 @@ HAVE_LIST="
     bswap
     closesocket
     cmov
-    conio_h
     dcbzl
     dev_bktr_ioctl_bt848_h
     dev_bktr_ioctl_meteor_h
@@ -1042,17 +1056,20 @@ HAVE_LIST="
     fast_64bit
     fast_clz
     fast_cmov
-    fast_unaligned
+    fcntl
     fork
     getaddrinfo
     gethrtime
     GetProcessMemoryInfo
     GetProcessTimes
     getrusage
+    gnu_as
     struct_rusage_ru_maxrss
+    ibm_asm
     inet_aton
     inline_asm
     isatty
+    kbhit
     ldbrx
     libdc1394_1
     libdc1394_2
@@ -1069,8 +1086,10 @@ HAVE_LIST="
     machine_ioctl_bt848_h
     machine_ioctl_meteor_h
     malloc_h
+    MapViewOfFile
     memalign
     mkstemp
+    mmap
     pld
     posix_memalign
     round
@@ -1078,11 +1097,13 @@ HAVE_LIST="
     sdl
     sdl_video_size
     setmode
+    sndio_h
     socklen_t
     soundcard_h
     poll_h
     setrlimit
     strerror_r
+    strtok_r
     struct_addrinfo
     struct_ipv6_mreq
     struct_sockaddr_in6
@@ -1097,13 +1118,13 @@ HAVE_LIST="
     sys_soundcard_h
     sys_videoio_h
     ten_operands
-    termios_h
     threads
     truncf
     vfp_args
     VirtualAlloc
     winsock2_h
     xform_asm
+    xmm_clobbers
     yasm
 "
 
@@ -1124,7 +1145,7 @@ CMDLINE_SELECT="
     extra_warnings
     logging
     optimizations
-    stripping
+    symver
     yasm
 "
 
@@ -1158,9 +1179,9 @@ CMDLINE_SET="
     logfile
     malloc_prefix
     nm
+    pkg_config
     samples
     source_path
-    strip
     sysinclude
     sysroot
     target_exec
@@ -1197,7 +1218,9 @@ mmx_deps="x86"
 mmx2_deps="mmx"
 sse_deps="mmx"
 ssse3_deps="sse"
+avx_deps="ssse3"
 
+aligned_stack_if_any="ppc x86"
 fast_64bit_if_any="alpha ia64 mips64 parisc64 ppc64 sparc64 x86_64"
 fast_clz_if_any="alpha armv5te avr32 mips ppc x86"
 fast_unaligned_if_any="armv6 ppc x86"
@@ -1208,21 +1231,26 @@ inline_asm_deps="!tms470"
 symver_if_any="symver_asm_label symver_gnu_asm"
 
 # subsystems
+dct_select="rdft"
 mdct_select="fft"
 rdft_select="fft"
 
 # decoders / encoders / hardware accelerators
-aac_decoder_select="mdct rdft aac_parser"
-aac_encoder_select="mdct"
-ac3_decoder_select="mdct ac3_parser"
+aac_decoder_select="mdct rdft sinewin"
+aac_encoder_select="mdct sinewin"
+aac_latm_decoder_select="aac_decoder aac_latm_parser"
+ac3_decoder_select="mdct ac3dsp ac3_parser"
+ac3_encoder_select="mdct ac3dsp"
+ac3_fixed_encoder_select="ac3dsp"
 alac_encoder_select="lpc"
 amrnb_decoder_select="lsp"
-atrac1_decoder_select="mdct"
+amrwb_decoder_select="lsp"
+atrac1_decoder_select="mdct sinewin"
 atrac3_decoder_select="mdct"
 binkaudio_dct_decoder_select="mdct rdft dct"
 binkaudio_rdft_decoder_select="mdct rdft"
 cavs_decoder_select="golomb"
-cook_decoder_select="mdct"
+cook_decoder_select="mdct sinewin"
 cscd_decoder_suggest="zlib"
 dca_decoder_select="mdct"
 dnxhd_encoder_select="aandct"
@@ -1238,13 +1266,14 @@ flashsv_decoder_select="zlib"
 flashsv_encoder_select="zlib"
 flv_decoder_select="h263_decoder"
 flv_encoder_select="h263_encoder"
+fraps_decoder_select="huffman"
 h261_encoder_select="aandct"
 h263_decoder_select="h263_parser"
 h263_encoder_select="aandct"
 h263_vaapi_hwaccel_select="vaapi h263_decoder"
 h263i_decoder_select="h263_decoder"
 h263p_encoder_select="h263_encoder"
-h264_decoder_select="golomb h264dsp"
+h264_decoder_select="golomb h264dsp h264pred"
 h264_dxva2_hwaccel_deps="dxva2api_h"
 h264_dxva2_hwaccel_select="dxva2 h264_decoder"
 h264_vaapi_hwaccel_select="vaapi"
@@ -1256,12 +1285,19 @@ ljpeg_encoder_select="aandct"
 loco_decoder_select="golomb"
 mjpeg_encoder_select="aandct"
 mlp_decoder_select="mlp_parser"
+mp1float_decoder_select="dct"
+mp2float_decoder_select="dct"
+mp3adufloat_decoder_select="dct"
+mp3float_decoder_select="dct"
+mp3on4float_decoder_select="dct"
 mpeg1video_encoder_select="aandct"
 mpeg2video_encoder_select="aandct"
 mpeg4_decoder_select="h263_decoder mpeg4video_parser"
 mpeg4_encoder_select="h263_encoder"
 mpeg_vdpau_decoder_select="vdpau mpegvideo_decoder"
 mpeg1_vdpau_decoder_select="vdpau mpeg1video_decoder"
+mpeg2_dxva2_hwaccel_deps="dxva2api_h"
+mpeg2_dxva2_hwaccel_select="dxva2 mpeg2video_decoder"
 mpeg2_vaapi_hwaccel_select="vaapi mpeg2video_decoder"
 mpeg4_vaapi_hwaccel_select="vaapi mpeg4_decoder"
 mpeg4_vdpau_decoder_select="vdpau mpeg4_decoder"
@@ -1273,34 +1309,32 @@ msmpeg4v2_decoder_select="h263_decoder"
 msmpeg4v2_encoder_select="h263_encoder"
 msmpeg4v3_decoder_select="h263_decoder"
 msmpeg4v3_encoder_select="h263_encoder"
-nellymoser_decoder_select="mdct"
-nellymoser_encoder_select="mdct"
+nellymoser_decoder_select="mdct sinewin"
+nellymoser_encoder_select="mdct sinewin"
 png_decoder_select="zlib"
 png_encoder_select="zlib"
 qcelp_decoder_select="lsp"
 qdm2_decoder_select="mdct rdft"
+ra_144_encoder_select="lpc"
 rv10_decoder_select="h263_decoder"
 rv10_encoder_select="h263_encoder"
 rv20_decoder_select="h263_decoder"
 rv20_encoder_select="h263_encoder"
-rv30_decoder_select="golomb h264dsp"
-rv40_decoder_select="golomb h264dsp"
+rv30_decoder_select="golomb h264pred"
+rv40_decoder_select="golomb h264pred"
 shorten_decoder_select="golomb"
 sipr_decoder_select="lsp"
 snow_decoder_select="dwt"
 snow_encoder_select="aandct dwt"
-sonic_decoder_select="golomb"
-sonic_encoder_select="golomb"
-sonic_ls_encoder_select="golomb"
 svq1_encoder_select="aandct"
-svq3_decoder_select="golomb h264dsp"
+svq3_decoder_select="golomb h264dsp h264pred"
 svq3_decoder_suggest="zlib"
 theora_decoder_select="vp3_decoder"
 tiff_decoder_suggest="zlib"
 tiff_encoder_suggest="zlib"
 truehd_decoder_select="mlp_decoder"
 tscc_decoder_select="zlib"
-twinvq_decoder_select="mdct lsp"
+twinvq_decoder_select="mdct lsp sinewin"
 vc1_decoder_select="h263_decoder"
 vc1_dxva2_hwaccel_deps="dxva2api_h DXVA_PictureParameters_wDecodedPictureIndex"
 vc1_dxva2_hwaccel_select="dxva2 vc1_decoder"
@@ -1308,14 +1342,16 @@ vc1_vaapi_hwaccel_select="vaapi vc1_decoder"
 vc1_vdpau_decoder_select="vdpau vc1_decoder"
 vorbis_decoder_select="mdct"
 vorbis_encoder_select="mdct"
+vp6_decoder_select="huffman"
 vp6a_decoder_select="vp6_decoder"
 vp6f_decoder_select="vp6_decoder"
-wmapro_decoder_select="mdct"
-wmav1_decoder_select="mdct"
-wmav1_encoder_select="mdct"
-wmav2_decoder_select="mdct"
-wmav2_encoder_select="mdct"
-wmavoice_decoder_select="lsp rdft dct"
+vp8_decoder_select="h264pred"
+wmapro_decoder_select="mdct sinewin"
+wmav1_decoder_select="mdct sinewin"
+wmav1_encoder_select="mdct sinewin"
+wmav2_decoder_select="mdct sinewin"
+wmav2_encoder_select="mdct sinewin"
+wmavoice_decoder_select="lsp rdft dct mdct sinewin"
 wmv1_decoder_select="h263_decoder"
 wmv1_encoder_select="h263_encoder"
 wmv2_decoder_select="h263_decoder"
@@ -1333,17 +1369,12 @@ vaapi_deps="va_va_h"
 vdpau_deps="vdpau_vdpau_h vdpau_vdpau_x11_h"
 
 # parsers
-h264_parser_select="golomb h264dsp"
-
-# bitstream_filters
-aac_adtstoasc_bsf_select="aac_parser"
+h264_parser_select="golomb h264dsp h264pred"
 
 # external libraries
 libdirac_decoder_deps="libdirac !libschroedinger"
 libdirac_encoder_deps="libdirac"
 libfaac_encoder_deps="libfaac"
-libfaad_decoder_deps="libfaad"
-libfaadbin_extralibs='$ldl'
 libgsm_decoder_deps="libgsm"
 libgsm_encoder_deps="libgsm"
 libgsm_ms_decoder_deps="libgsm"
@@ -1357,35 +1388,41 @@ libschroedinger_decoder_deps="libschroedinger"
 libschroedinger_encoder_deps="libschroedinger"
 libspeex_decoder_deps="libspeex"
 libtheora_encoder_deps="libtheora"
+libvo_aacenc_encoder_deps="libvo_aacenc"
+libvo_amrwbenc_encoder_deps="libvo_amrwbenc"
 libvorbis_encoder_deps="libvorbis"
 libvpx_decoder_deps="libvpx"
 libvpx_encoder_deps="libvpx"
 libx264_encoder_deps="libx264"
+libxavs_encoder_deps="libxavs"
 libxvid_encoder_deps="libxvid"
 
 # demuxers / muxers
-ac3_demuxer_deps="ac3_parser"
+ac3_demuxer_select="ac3_parser"
 asf_stream_muxer_select="asf_muxer"
 avisynth_demuxer_deps="avisynth"
-dirac_demuxer_deps="dirac_parser"
+dirac_demuxer_select="dirac_parser"
 eac3_demuxer_select="ac3_parser"
+flac_demuxer_select="flac_parser"
 ipod_muxer_select="mov_muxer"
 libnut_demuxer_deps="libnut"
 libnut_muxer_deps="libnut"
 matroska_audio_muxer_select="matroska_muxer"
 matroska_demuxer_suggest="zlib bzlib"
 mov_demuxer_suggest="zlib"
-mp3_demuxer_deps="mpegaudio_parser"
+mp3_demuxer_select="mpegaudio_parser"
 mp4_muxer_select="mov_muxer"
 mpegtsraw_demuxer_select="mpegts_demuxer"
 mxf_d10_muxer_select="mxf_muxer"
 ogg_demuxer_select="golomb"
 psp_muxer_select="mov_muxer"
-rtsp_demuxer_deps="sdp_demuxer"
-rtsp_muxer_deps="sdp_demuxer"
-rtsp_muxer_select="rtp_muxer"
-sdp_demuxer_deps="rtp_protocol mpegts_demuxer"
-sdp_demuxer_select="asf_demuxer rm_demuxer"
+rtp_demuxer_select="sdp_demuxer"
+rtpdec_select="asf_demuxer rm_demuxer rtp_protocol mpegts_demuxer mov_demuxer"
+rtsp_demuxer_select="http_protocol rtpdec"
+rtsp_muxer_select="rtp_muxer http_protocol rtp_protocol"
+sap_demuxer_select="sdp_demuxer"
+sap_muxer_select="rtp_muxer rtp_protocol"
+sdp_demuxer_select="rtpdec"
 spdif_muxer_select="aac_parser"
 tg2_muxer_select="mov_muxer"
 tgp_muxer_select="mov_muxer"
@@ -1393,23 +1430,19 @@ w64_demuxer_deps="wav_demuxer"
 
 # indevs / outdevs
 alsa_indev_deps="alsa_asoundlib_h snd_pcm_htimestamp"
-alsa_indev_extralibs="-lasound"
 alsa_outdev_deps="alsa_asoundlib_h"
-alsa_outdev_extralibs="-lasound"
-audio_beos_indev_deps="audio_beos"
-audio_beos_indev_extralibs="-lmedia -lbe"
-audio_beos_outdev_deps="audio_beos"
-audio_beos_outdev_extralibs="-lmedia -lbe"
 bktr_indev_deps_any="dev_bktr_ioctl_bt848_h machine_ioctl_bt848_h dev_video_bktr_ioctl_bt848_h dev_ic_bt8xx_h"
 dv1394_indev_deps="dv1394 dv_demuxer"
+fbdev_indev_deps="linux_fb_h"
 jack_indev_deps="jack_jack_h"
-jack_indev_extralibs="-ljack"
 libdc1394_indev_deps="libdc1394"
 oss_indev_deps_any="soundcard_h sys_soundcard_h"
 oss_outdev_deps_any="soundcard_h sys_soundcard_h"
+sndio_indev_deps="sndio_h"
+sndio_outdev_deps="sndio_h"
 v4l_indev_deps="linux_videodev_h"
 v4l2_indev_deps_any="linux_videodev2_h sys_videoio_h"
-vfwcap_indev_deps="capCreateCaptureWindow"
+vfwcap_indev_deps="capCreateCaptureWindow vfwcap_defines"
 vfwcap_indev_extralibs="-lavicap32"
 x11_grab_device_indev_deps="x11grab XShmCreateImage"
 x11_grab_device_indev_extralibs="-lX11 -lXext -lXfixes"
@@ -1418,14 +1451,22 @@ x11_grab_device_indev_extralibs="-lX11 -lXext -lXfixes"
 gopher_protocol_deps="network"
 http_protocol_deps="network"
 http_protocol_select="tcp_protocol"
-rtmp_protocol_deps="tcp_protocol"
-rtp_protocol_deps="udp_protocol"
+mmsh_protocol_select="http_protocol"
+mmst_protocol_deps="network"
+rtmp_protocol_select="tcp_protocol"
+rtp_protocol_select="udp_protocol"
 tcp_protocol_deps="network"
 udp_protocol_deps="network"
 
 # filters
-movie_filter_deps="avfilter_lavf"
-avfilter_lavf_deps="avformat"
+blackframe_filter_deps="gpl"
+cropdetect_filter_deps="gpl"
+frei0r_filter_deps="frei0r dlopen strtok_r"
+frei0r_src_filter_deps="frei0r dlopen strtok_r"
+hqdn3d_filter_deps="gpl"
+scale_filter_deps="swscale"
+ocv_filter_deps="libopencv"
+yadif_filter_deps="gpl"
 
 # libraries
 avdevice_deps="avcodec avformat"
@@ -1433,17 +1474,123 @@ avformat_deps="avcodec"
 
 # programs
 ffmpeg_deps="avcodec avformat swscale"
+ffmpeg_select="buffer_filter"
 ffplay_deps="avcodec avformat swscale sdl"
 ffplay_select="rdft"
 ffprobe_deps="avcodec avformat"
-ffserver_deps="avformat ffm_muxer rtp_protocol rtsp_demuxer"
+ffserver_deps="avformat ffm_muxer fork rtp_protocol rtsp_demuxer"
 ffserver_extralibs='$ldl'
 
 doc_deps="texi2html"
 
+# tests
+
+test_deps(){
+    suf1=$1
+    suf2=$2
+    shift 2
+    for v; do
+        dep=${v%=*}
+        tests=${v#*=}
+        for name in ${tests}; do
+            eval ${name}_test_deps="'${dep}$suf1 ${dep}$suf2'"
+        done
+    done
+}
+
+set_ne_test_deps(){
+    eval ${1}_be_test_deps="bigendian"
+    eval ${1}_le_test_deps="!bigendian"
+}
+
+test_deps _encoder _decoder                                             \
+    adpcm_g726=g726                                                     \
+    adpcm_ima_qt                                                        \
+    adpcm_ima_wav                                                       \
+    adpcm_ms                                                            \
+    adpcm_swf                                                           \
+    adpcm_yamaha=adpcm_yam                                              \
+    alac                                                                \
+    asv1                                                                \
+    asv2                                                                \
+    bmp                                                                 \
+    dnxhd="dnxhd_1080i dnxhd_720p dnxhd_720p_rd"                        \
+    dvvideo="dv dv50"                                                   \
+    ffv1                                                                \
+    flac                                                                \
+    flashsv                                                             \
+    flv                                                                 \
+    gif                                                                 \
+    h261                                                                \
+    h263="h263 h263p"                                                   \
+    huffyuv                                                             \
+    jpegls                                                              \
+    mjpeg="jpg mjpeg ljpeg"                                             \
+    mp2                                                                 \
+    mpeg1video="mpeg mpeg1b"                                            \
+    mpeg2video="mpeg2 mpeg2thread"                                      \
+    mpeg4="mpeg4 mpeg4adv mpeg4nr mpeg4thread error rc"                 \
+    msmpeg4v3=msmpeg4                                                   \
+    msmpeg4v2                                                           \
+    pbm=pbmpipe                                                         \
+    pcx                                                                 \
+    pgm="pgm pgmpipe"                                                   \
+    png                                                                 \
+    ppm="ppm ppmpipe"                                                   \
+    rawvideo="rgb yuv"                                                  \
+    roq                                                                 \
+    rv10                                                                \
+    rv20                                                                \
+    sgi                                                                 \
+    snow="snow snowll"                                                  \
+    svq1                                                                \
+    targa=tga                                                           \
+    tiff                                                                \
+    wmav1                                                               \
+    wmav2                                                               \
+    wmv1                                                                \
+    wmv2                                                                \
+
+test_deps _muxer _demuxer                                               \
+    aiff                                                                \
+    pcm_alaw=alaw                                                       \
+    asf                                                                 \
+    au                                                                  \
+    avi                                                                 \
+    dv=dv_fmt                                                           \
+    ffm                                                                 \
+    flv=flv_fmt                                                         \
+    gxf                                                                 \
+    matroska=mkv                                                        \
+    mmf                                                                 \
+    mov                                                                 \
+    pcm_mulaw=mulaw                                                     \
+    mxf                                                                 \
+    nut                                                                 \
+    ogg                                                                 \
+    rawvideo=pixfmt                                                     \
+    rm                                                                  \
+    swf                                                                 \
+    mpegts=ts                                                           \
+    voc                                                                 \
+    wav                                                                 \
+    yuv4mpegpipe=yuv4mpeg                                               \
+
+ac3_fixed_test_deps="ac3_fixed_encoder ac3_decoder rm_muxer rm_demuxer"
+mpg_test_deps="mpeg1system_muxer mpegps_demuxer"
+
+set_ne_test_deps pixdesc
+set_ne_test_deps pixfmts_copy
+set_ne_test_deps pixfmts_crop
+set_ne_test_deps pixfmts_hflip
+set_ne_test_deps pixfmts_null
+set_ne_test_deps pixfmts_pad
+set_ne_test_deps pixfmts_scale
+set_ne_test_deps pixfmts_vflip
+
 # default parameters
 
-logfile="config.err"
+logfile="config.log"
 
 # installation paths
 prefix_default="/usr/local"
@@ -1462,9 +1609,10 @@ host_cc_default="gcc"
 ln_s="ln -sf"
 nm_default="nm"
 objformat="elf"
+pkg_config_default=pkg-config
 ranlib="ranlib"
-strip_default="strip"
 yasmexe="yasm"
+nogas=":"
 
 nm_opts='-g'
 
@@ -1479,6 +1627,7 @@ host_os=$target_os_default
 # configurable options
 enable avcodec
 enable avdevice
+enable avfilter
 enable avformat
 enable avutil
 enable asm
@@ -1494,7 +1643,6 @@ enable network
 enable optimizations
 enable protocols
 enable static
-enable stripping
 enable swscale
 enable swscale_alpha
 
@@ -1519,8 +1667,8 @@ host_libs='-lm'
 
 target_path='$(CURDIR)'
 
-# gcc stupidly only outputs the basename of targets with -MM, but we need the
-# full relative path for objects in subdirectories for non-recursive Make.
+# since the object filename is not given with the -MM flag, the compiler
+# is only able to print the basename, and we must add the path ourselves
 DEPEND_CMD='$(DEPCC) $(DEPFLAGS) $< | sed -e "/^\#.*/d" -e "s,^[[:space:]]*$(*F)\\.o,$(@D)/$(*F).o," > $(@:.o=.d)'
 DEPFLAGS='$(CPPFLAGS) $(CFLAGS) -MM'
 
@@ -1542,7 +1690,7 @@ for v in "$@"; do
     r=${v#*=}
     l=${v%"$r"}
     r=$(sh_quote "$r")
-    FFMPEG_CONFIGURATION="${FFMPEG_CONFIGURATION# } ${l}${r}"
+    LIBAV_CONFIGURATION="${LIBAV_CONFIGURATION# } ${l}${r}"
 done
 
 find_things(){
@@ -1564,13 +1712,25 @@ INDEV_LIST=$(find_things    indev    _IN      libavdevice/alldevices.c)
 PROTOCOL_LIST=$(find_things protocol PROTOCOL libavformat/allformats.c)
 FILTER_LIST=$(find_things   filter   FILTER   libavfilter/allfilters.c)
 
+find_tests(){
+    map "echo ${2}\${v}_test" $(ls "$source_path"/tests/ref/$1 | grep -v '[^-a-z0-9_]')
+}
+
+ACODEC_TESTS=$(find_tests acodec)
+VCODEC_TESTS=$(find_tests vsynth1)
+LAVF_TESTS=$(find_tests lavf)
+LAVFI_TESTS=$(find_tests lavfi)
+SEEK_TESTS=$(find_tests seek seek_)
+
+pcm_test_deps=$(map 'echo ${v%_*}_decoder $v' $(filter pcm_* $ENCODER_LIST))
+
 for n in $COMPONENT_LIST; do
     v=$(toupper ${n%s})_LIST
     eval enable \$$v
     eval ${n}_if_any="\$$v"
 done
 
-enable $ARCH_EXT_LIST
+enable $ARCH_EXT_LIST $ACODEC_TESTS $VCODEC_TESTS $LAVF_TESTS $LAVFI_TESTS $SEEK_TESTS
 
 die_unknown(){
     echo "Unknown option \"$1\"."
@@ -1597,7 +1757,7 @@ for opt do
     --enable-debug=*) debuglevel="$optval"
     ;;
     --disable-everything)
-    map 'eval disable \${$(toupper ${v%s})_LIST}' $COMPONENT_LIST
+    map 'eval unset \${$(toupper ${v%s})_LIST}' $COMPONENT_LIST
     ;;
     --enable-*=*|--disable-*=*)
     eval $(echo "${opt%%=*}" | sed 's/--/action=/;s/-/ thing=/')
@@ -1642,7 +1802,7 @@ done
 
 disabled logging && logfile=/dev/null
 
-echo "# $0 $FFMPEG_CONFIGURATION" > $logfile
+echo "# $0 $LIBAV_CONFIGURATION" > $logfile
 set >> $logfile
 
 test -n "$cross_prefix" && enable cross_compile
@@ -1657,18 +1817,18 @@ set_default arch target_os
 ar_default="${cross_prefix}${ar_default}"
 cc_default="${cross_prefix}${cc_default}"
 nm_default="${cross_prefix}${nm_default}"
+pkg_config_default="${cross_prefix}${pkg_config_default}"
 ranlib="${cross_prefix}${ranlib}"
-strip_default="${cross_prefix}${strip_default}"
 
 sysinclude_default="${sysroot}/usr/include"
 
-set_default cc nm strip sysinclude
+set_default cc nm pkg_config sysinclude
 enabled cross_compile || host_cc_default=$cc
 set_default host_cc
 
 exesuf() {
     case $1 in
-        mingw32*|cygwin*|*-dos|freedos|opendos|os/2*) echo .exe ;;
+        mingw32*|cygwin*|*-dos|freedos|opendos|os/2*|symbian) echo .exe ;;
     esac
 }
 
@@ -1680,11 +1840,11 @@ HOSTEXESUF=$(exesuf $host_os)
 : ${TMPDIR:=$TMP}
 : ${TMPDIR:=/tmp}
 
-if ! check_cmd type mktemp; then
+if ! check_cmd mktemp -u XXXXXX; then
     # simple replacement for missing mktemp
     # NOT SAFE FOR GENERAL USE
     mktemp(){
-        echo "${2%XXX*}.${HOSTNAME}.${UID}.$$"
+        echo "${2%%XXX*}.${HOSTNAME}.${UID}.$$"
     }
 fi
 
@@ -1697,7 +1857,6 @@ tmpfile(){
 }
 
 trap 'rm -f -- $TMPFILES' EXIT
-trap exit HUP INT TERM
 
 tmpfile TMPC  .c
 tmpfile TMPE  $EXESUF
@@ -1706,9 +1865,12 @@ tmpfile TMPO  .o
 tmpfile TMPS  .S
 tmpfile TMPV  .ver
 tmpfile TMPSH .sh
+tmpfile TMPASM .asm
 
 unset -f mktemp
 
+chmod +x $TMPE
+
 # make sure we can execute files in $TMPDIR
 cat > $TMPSH 2>> $logfile <<EOF
 #! /bin/sh
@@ -1726,9 +1888,23 @@ filter_cflags=echo
 filter_cppflags=echo
 filter_asflags=echo
 
-if   $cc -v 2>&1 | grep -qi ^gcc; then
+if   $cc -v 2>&1 | grep -q '^gcc.*LLVM'; then
+    cc_type=llvm_gcc
+    cc_version=__VERSION__
+    gcc_extra_ver=$(expr "$($cc --version | head -n1)" : '.*\((.*)\)')
+    cc_ident="llvm-gcc $($cc -dumpversion) $gcc_extra_ver"
+    CC_DEPFLAGS='-MMD -MF $(@:.o=.d) -MT $@'
+    AS_DEPFLAGS='-MMD -MF $(@:.o=.d) -MT $@'
+    speed_cflags='-O3'
+    size_cflags='-Os'
+elif $cc -v 2>&1 | grep -qi ^gcc; then
     cc_type=gcc
     cc_version=__VERSION__
+    gcc_version=$($cc --version | head -n1)
+    gcc_basever=$($cc -dumpversion)
+    gcc_pkg_ver=$(expr "$gcc_version" : '[^ ]* \(([^)]*)\)')
+    gcc_ext_ver=$(expr "$gcc_version" : ".*$gcc_pkg_ver $gcc_basever \\(.*\\)")
+    cc_ident=$(cleanws "gcc $gcc_basever $gcc_pkg_ver $gcc_ext_ver")
     if ! $cc -dumpversion | grep -q '^2\.'; then
         CC_DEPFLAGS='-MMD -MF $(@:.o=.d) -MT $@'
         AS_DEPFLAGS='-MMD -MF $(@:.o=.d) -MT $@'
@@ -1738,6 +1914,8 @@ if   $cc -v 2>&1 | grep -qi ^gcc; then
 elif $cc --version 2>/dev/null | grep -q Intel; then
     cc_type=icc
     cc_version="AV_STRINGIFY(__INTEL_COMPILER)"
+    cc_ident=$($cc --version | head -n1)
+    icc_version=$($cc -dumpversion)
     CC_DEPFLAGS='-MMD'
     AS_DEPFLAGS='-MMD'
     speed_cflags='-O3'
@@ -1746,11 +1924,13 @@ elif $cc --version 2>/dev/null | grep -q Intel; then
 elif $cc -v 2>&1 | grep -q xlc; then
     cc_type=xlc
     cc_version="AV_STRINGIFY(__IBMC__)"
+    cc_ident=$($cc -qversion 2>/dev/null | head -n1)
     speed_cflags='-O5'
     size_cflags='-O5 -qcompact'
 elif $cc -V 2>/dev/null | grep -q Compaq; then
     cc_type=ccc
     cc_version="AV_STRINGIFY(__DECC_VER)"
+    cc_ident=$($cc -V | head -n1 | cut -d' ' -f1-3)
     DEPFLAGS='$(CPPFLAGS) $(CFLAGS) -M'
     debuglevel=3
     add_ldflags -Wl,-z,now # calls to libots crash without this
@@ -1760,21 +1940,25 @@ elif $cc --vsn 2>/dev/null | grep -q "ARM C/C++ Compiler"; then
     test -d "$sysroot" || die "No valid sysroot specified."
     cc_type=armcc
     cc_version="AV_STRINGIFY(__ARMCC_VERSION)"
+    cc_ident=$($cc --vsn | head -n1)
     armcc_conf="$PWD/armcc.conf"
     $cc --arm_linux_configure                 \
         --arm_linux_config_file="$armcc_conf" \
         --configure_sysroot="$sysroot"        \
         --configure_cpp_headers="$sysinclude" >>$logfile 2>&1 ||
         die "Error creating armcc configuration file."
+    $cc --vsn | grep -q RVCT && armcc_opt=rvct || armcc_opt=armcc
     cc="$cc --arm_linux_config_file=$armcc_conf --translate_gcc"
     as_default="${cross_prefix}gcc"
     CC_DEPFLAGS='-MMD'
     AS_DEPFLAGS='-MMD'
     speed_cflags='-O3'
     size_cflags='-Os'
+    filter_asflags="filter_out -W${armcc_opt}*"
 elif $cc -version 2>/dev/null | grep -q TMS470; then
     cc_type=tms470
     cc_version="AV_STRINGIFY(__TI_COMPILER_VERSION__)"
+    cc_ident=$($cc -version | head -n1 | tr -s ' ')
     cc="$cc --gcc --abi=eabi -eo=.o -mc -me"
     CC_O='-fr=$(@D)'
     as_default="${cross_prefix}gcc"
@@ -1813,7 +1997,9 @@ elif $cc -version 2>/dev/null | grep -q TMS470; then
     }
 elif $cc -v 2>&1 | grep -q clang; then
     cc_type=clang
-    cc_version=__VERSION__
+    $cc -dM -E $TMPC | grep -q __clang_version__ &&
+        cc_version=__clang_version__ || cc_version=__VERSION__
+    cc_ident=$($cc --version | head -n1)
     CC_DEPFLAGS='-MMD'
     AS_DEPFLAGS='-MMD'
     speed_cflags='-O3'
@@ -1821,6 +2007,7 @@ elif $cc -v 2>&1 | grep -q clang; then
 elif $cc -V 2>&1 | grep -q Sun; then
     cc_type=suncc
     cc_version="AV_STRINGIFY(__SUNPRO_C)"
+    cc_ident=$($cc -V 2>&1 | head -n1 | cut -d' ' -f 2-)
     DEPEND_CMD='$(DEPCC) $(DEPFLAGS) $< | sed -e "1s,^.*: ,$@: ," -e "\$$!s,\$$, \\\," -e "1!s,^.*: , ," > $(@:.o=.d)'
     DEPFLAGS='$(CPPFLAGS) $(CFLAGS) -xM1'
     speed_cflags='-O5'
@@ -1832,9 +2019,9 @@ elif $cc -V 2>&1 | grep -q Sun; then
                 -march=*|-mcpu=*)
                     case "${flag#*=}" in
                         native)                   echo -xtarget=native       ;;
-                        v9)                       echo -xarch=sparc          ;;
+                        v9|niagara)               echo -xarch=sparc          ;;
                         ultrasparc)               echo -xarch=sparcvis       ;;
-                        ultrasparc3|niagara*)     echo -xarch=sparcvis2      ;;
+                        ultrasparc3|niagara2)     echo -xarch=sparcvis2      ;;
                         i586|pentium)             echo -xchip=pentium        ;;
                         i686|pentiumpro|pentium2) echo -xtarget=pentium_pro  ;;
                         pentium3*|c3-2)           echo -xtarget=pentium3     ;;
@@ -1859,9 +2046,26 @@ elif $cc -V 2>&1 | grep -q Sun; then
             esac
         done
     }
+elif $cc -v 2>&1 | grep -q 'PathScale\|Path64'; then
+    cc_type=pathscale
+    cc_version=__PATHSCALE__
+    cc_ident=$($cc -v 2>&1 | head -n1 | tr -d :)
+    CC_DEPFLAGS='-MMD -MF $(@:.o=.d) -MT $@'
+    AS_DEPFLAGS='-MMD -MF $(@:.o=.d) -MT $@'
+    speed_cflags='-O2'
+    size_cflags='-Os'
+elif $cc -v 2>&1 | grep -q Open64; then
+    cc_type=open64
+    cc_version=__OPEN64__
+    cc_ident=$($cc -v 2>&1 | head -n1 | tr -d :)
+    CC_DEPFLAGS='-MMD -MF $(@:.o=.d) -MT $@'
+    AS_DEPFLAGS='-MMD -MF $(@:.o=.d) -MT $@'
+    speed_cflags='-O2'
+    size_cflags='-Os'
 fi
 
-test -n "$cc_type" && enable $cc_type || echolog "Unknown C compiler $cc"
+test -n "$cc_type" && enable $cc_type ||
+    warn "Unknown C compiler $cc, unable to select optimal CFLAGS"
 
 : ${as_default:=$cc}
 : ${dep_cc_default:=$cc}
@@ -1876,7 +2080,7 @@ add_asflags $extra_cflags
 
 if test -n "$sysroot"; then
     case "$cc_type" in
-        gcc)
+        gcc|llvm_gcc|clang)
             add_cppflags --sysroot="$sysroot"
             add_ldflags --sysroot="$sysroot"
         ;;
@@ -1884,10 +2088,6 @@ if test -n "$sysroot"; then
             add_cppflags -I"$sysinclude"
             add_ldflags  --sysroot="$sysroot"
         ;;
-        clang)
-            add_cppflags -isysroot "$sysroot"
-            add_ldflags -isysroot "$sysroot"
-        ;;
     esac
 fi
 
@@ -1895,7 +2095,7 @@ if test "$cpu" = host; then
     enabled cross_compile && die "--cpu=host makes no sense when cross-compiling."
 
     case "$cc_type" in
-        gcc)
+        gcc|llvm_gcc)
             check_native(){
                 $cc $1=native -v -c -o $TMPO $TMPC >$TMPE 2>&1 || return
                 sed -n "/$1=/{
@@ -1947,12 +2147,12 @@ case "$arch" in
         arch="sparc"
         subarch="sparc64"
     ;;
-    i[3-6]86|i86pc|BePC|x86_64|amd64)
+    i[3-6]86|i86pc|BePC|x86pc|x86_64|amd64)
         arch="x86"
     ;;
 esac
 
-is_in $arch $ARCH_LIST || echo "WARNING: unknown arch $arch"
+is_in $arch $ARCH_LIST || warn "unknown architecture $arch"
 enable $arch
 
 # Add processor-specific flags
@@ -2013,7 +2213,7 @@ elif enabled x86; then
             disable cmov
         ;;
         # targets that do support conditional mov (cmov)
-        i686|pentiumpro|pentium[23]|pentium-m|athlon|athlon-tbird|athlon-4|athlon-[mx]p|athlon64|k8|opteron|athlon-fx|core2|amdfam10)
+        i686|pentiumpro|pentium[23]|pentium-m|athlon|athlon-tbird|athlon-4|athlon-[mx]p|athlon64|k8|opteron|athlon-fx|core2|amdfam10|barcelona|atom)
             cpuflags="-march=$cpu"
             enable cmov
             enable fast_cmov
@@ -2029,6 +2229,10 @@ elif enabled x86; then
 elif enabled sparc; then
 
     case $cpu in
+        niagara)
+            cpuflags="-mcpu=$cpu"
+            disable vis
+        ;;
         sparc64)
             cpuflags="-mcpu=v9"
         ;;
@@ -2039,9 +2243,18 @@ elif enabled arm; then
     case $cpu in
         armv*)
             cpuflags="-march=$cpu"
+            subarch=$(echo $cpu | sed 's/[^a-z0-9]//g')
         ;;
         *)
             cpuflags="-mcpu=$cpu"
+            case $cpu in
+                cortex-a*)                               subarch=armv7a  ;;
+                cortex-r*)                               subarch=armv7r  ;;
+                cortex-m*)                               subarch=armv7m  ;;
+                arm11*)                                  subarch=armv6   ;;
+                arm[79]*e*|arm9[24]6*|arm96*|arm102[26]) subarch=armv5te ;;
+                armv4*|arm7*|arm9[24]*)                  subarch=armv4   ;;
+            esac
         ;;
     esac
 
@@ -2127,30 +2340,11 @@ enabled spic && enable pic
 
 # OS specific
 case $target_os in
-    beos|haiku|zeta)
-        prefix_default="$HOME/config"
-        # 3 gcc releases known for BeOS, each with ugly bugs
-        gcc_version="$($cc -v 2>&1 | grep version | cut -d ' ' -f3-)"
-        case "$gcc_version" in
-          2.9-beos-991026*|2.9-beos-000224*) echo "R5/GG gcc"
-            disable mmx
-            ;;
-          *20010315*) echo "BeBits gcc"
-            add_cflags -fno-expensive-optimizations
-            ;;
-        esac
-        SHFLAGS=-nostart
-        # enable BeOS things
-        enable audio_beos
-        # no need for libm, but the inet stuff
-        # Check for BONE
-        # XXX: actually should check for NOT net_server
-        if echo $BEINCLUDES | grep -q 'headers/be/bone'; then
-            network_extralibs="-lbind -lsocket"
-        else
-            enable beos_netserver
-            network_extralibs="-lnet"
-        fi ;;
+    haiku)
+        prefix_default="/boot/common"
+        network_extralibs="-lnetwork"
+        host_libs=
+        ;;
     sunos)
         FFSERVERLDFLAGS=""
         SHFLAGS='-shared -Wl,-h,$$(@F)'
@@ -2160,6 +2354,7 @@ case $target_os in
         nm_opts='-P -g'
         ;;
     netbsd)
+        disable symver
         oss_indev_extralibs="-lossaudio"
         oss_outdev_extralibs="-lossaudio"
         add_cppflags -D_XOPEN_SOURCE=600
@@ -2167,27 +2362,33 @@ case $target_os in
     openbsd)
         enable malloc_aligned
         # On OpenBSD 4.5. the compiler does not use PIC unless
-        # explicitly using -fPIC. FFmpeg builds fine without PIC,
+        # explicitly using -fPIC. Libav builds fine without PIC,
         # however the generated executable will not do anything
         # (simply quits with exit-code 1, no crash, no output).
         # Thus explicitly enable PIC here.
         enable pic
+        disable symver
         SHFLAGS='-shared'
         oss_indev_extralibs="-lossaudio"
         oss_outdev_extralibs="-lossaudio"
         ;;
-    freebsd|dragonfly)
+    dragonfly)
+        enable malloc_aligned
+        disable symver
+        ;;
+    freebsd)
         enable malloc_aligned
         ;;
     bsd/os)
-        osextralibs="-lpoll -lgnugetopt"
-        strip="strip -d"
+        add_extralibs -lpoll -lgnugetopt
         ;;
     darwin)
         enable malloc_aligned
-        SHFLAGS='-dynamiclib -Wl,-single_module -Wl,-install_name,$(SHLIBDIR)/$(SLIBNAME),-current_version,$(LIBVERSION),-compatibility_version,$(LIBMAJOR) -Wl,-read_only_relocs,suppress'
-        strip="strip -x"
-        FFLDFLAGS="-Wl,-dynamic,-search_paths_first"
+        gas="gas-preprocessor.pl $cc"
+        enabled ppc && add_asflags -force_cpusubtype_ALL
+        SHFLAGS='-dynamiclib -Wl,-single_module -Wl,-install_name,$(SHLIBDIR)/$(SLIBNAME),-current_version,$(LIBVERSION),-compatibility_version,$(LIBMAJOR)'
+        enabled x86_32 && append SHFLAGS -Wl,-read_only_relocs,suppress
+        add_ldflags -Wl,-dynamic,-search_paths_first
         SLIBSUF=".dylib"
         SLIBNAME_WITH_VERSION='$(SLIBPREF)$(FULLNAME).$(LIBVERSION)$(SLIBSUF)'
         SLIBNAME_WITH_MAJOR='$(SLIBPREF)$(FULLNAME).$(LIBMAJOR)$(SLIBSUF)'
@@ -2206,17 +2407,16 @@ case $target_os in
         LIBTARGET=i386
         if enabled x86_64; then
             enable malloc_aligned
-            LIBTARGET=x64
+            LIBTARGET="i386:x86-64"
         elif enabled arm; then
-            LIBTARGET=arm
+            LIBTARGET=arm-wince
         fi
         shlibdir_default="$bindir_default"
-        disable ffserver
         SLIBPREF=""
         SLIBSUF=".dll"
         SLIBNAME_WITH_VERSION='$(SLIBPREF)$(FULLNAME)-$(LIBVERSION)$(SLIBSUF)'
         SLIBNAME_WITH_MAJOR='$(SLIBPREF)$(FULLNAME)-$(LIBMAJOR)$(SLIBSUF)'
-        SLIB_EXTRA_CMD='-lib.exe /machine:$(LIBTARGET) /def:$$(@:$(SLIBSUF)=.def) /out:$(SUBDIR)$(SLIBNAME_WITH_MAJOR:$(SLIBSUF)=.lib)'
+        SLIB_EXTRA_CMD=-'$(DLLTOOL) -m $(LIBTARGET) -d $$(@:$(SLIBSUF)=.def) -l $(SUBDIR)$(SLIBNAME_WITH_MAJOR:$(SLIBSUF)=.lib) -D $(SLIBNAME_WITH_MAJOR)'
         SLIB_INSTALL_EXTRA_CMD='-install -m 644 $(SUBDIR)$(SLIBNAME_WITH_MAJOR:$(SLIBSUF)=.lib) "$(SHLIBDIR)/$(SLIBNAME:$(SLIBSUF)=.lib)"; \
             install -m 644 $(SUBDIR)$(SLIBNAME_WITH_MAJOR:$(SLIBSUF)=.lib) "$(SHLIBDIR)/$(SLIBNAME_WITH_MAJOR:$(SLIBSUF)=.lib)"; \
             install -d "$(LIBDIR)"; \
@@ -2224,15 +2424,13 @@ case $target_os in
         SLIB_UNINSTALL_EXTRA_CMD='rm -f "$(SHLIBDIR)/$(SLIBNAME:$(SLIBSUF)=.lib)"'
         SHFLAGS='-shared -Wl,--output-def,$$(@:$(SLIBSUF)=.def) -Wl,--out-implib,$(SUBDIR)lib$(SLIBNAME:$(SLIBSUF)=.dll.a) -Wl,--enable-runtime-pseudo-reloc -Wl,--enable-auto-image-base'
         objformat="win32"
+        dlltool="${cross_prefix}dlltool"
         enable dos_paths
         check_cflags -fno-common
-        if ! enabled x86_64; then
-            check_cpp_condition _mingw.h "(__MINGW32_MAJOR_VERSION > 3) || (__MINGW32_MAJOR_VERSION == 3 && __MINGW32_MINOR_VERSION >= 15)" ||
+        check_cpp_condition _mingw.h "defined (__MINGW64_VERSION_MAJOR) || (__MINGW32_MAJOR_VERSION > 3) \
+                                      || (__MINGW32_MAJOR_VERSION == 3 && __MINGW32_MINOR_VERSION >= 15)" ||
                 die "ERROR: MinGW runtime version must be >= 3.15."
-            enabled_any avisynth vfwcap_indev &&
-                { check_cpp_condition w32api.h "(__W32API_MAJOR_VERSION > 3) || (__W32API_MAJOR_VERSION == 3 && __W32API_MINOR_VERSION >= 13)" ||
-                  die "ERROR: avisynth and vfwcap_indev require w32api version 3.13 or later."; }
-        fi
+        add_cppflags -U__STRICT_ANSI__
         ;;
     cygwin*)
         target_os=cygwin
@@ -2247,8 +2445,6 @@ case $target_os in
         check_cflags -fno-common
         ;;
     *-dos|freedos|opendos)
-        disable ffplay ffserver
-        disable $INDEV_LIST $OUTDEV_LIST
         network_extralibs="-lsocket"
         objformat="coff"
         enable dos_paths
@@ -2261,9 +2457,8 @@ case $target_os in
         ranlib="echo ignoring ranlib"
         ;;
     os/2*)
-        strip="lxlite"
         ln_s="cp -f"
-        FFLDFLAGS="-Zomf -Zbin-files -Zargs-wild -Zmap"
+        add_ldflags -Zomf -Zbin-files -Zargs-wild -Zmap
         SHFLAGS='$(SUBDIR)$(NAME).def -Zdll -Zomf'
         FFSERVERLDFLAGS=""
         LIBSUF="_s.a"
@@ -2287,6 +2482,15 @@ case $target_os in
         ;;
     gnu)
         ;;
+    qnx)
+        add_cppflags -D_QNX_SOURCE
+        network_extralibs="-lsocket"
+        ;;
+    symbian)
+        SLIBSUF=".dll"
+        enable dos_paths
+        add_cflags --include=$sysinclude/gcce/gcce.h
+        ;;
     none)
         ;;
     *)
@@ -2294,15 +2498,12 @@ case $target_os in
         ;;
 esac
 
+echo "config:$arch:$subarch:$cpu:$target_os:$cc_ident:$LIBAV_CONFIGURATION" >config.fate
+
 check_cpp_condition stdlib.h "defined(__PIC__) || defined(__pic__) || defined(PIC)" && enable pic
 
 set_default $PATHS_LIST
 
-add_extralibs $osextralibs
-
-# Combine FFLDFLAGS and the LDFLAGS environment variable.
-LDFLAGS="$FFLDFLAGS $LDFLAGS"
-
 # we need to build at least one lib type
 if ! enabled_any static shared; then
     cat <<EOF
@@ -2316,28 +2517,12 @@ fi
 
 disabled static && LIBNAME=""
 
-if enabled_any libfaad libfaadbin ; then
-    if check_header faad.h; then
-        check_cc <<EOF
-#include <faad.h>
-#ifndef FAAD2_VERSION
-ok faad1
-#endif
-int main(void) { return 0; }
-EOF
-        test $? = 0 && enable libfaad2
-    else
-        die "FAAD test failed."
-    fi
-fi
-
-
 die_license_disabled() {
     enabled $1 || { enabled $2 && die "$2 is $1 and --enable-$1 is not specified."; }
 }
 
-die_license_disabled gpl libfaad2
 die_license_disabled gpl libx264
+die_license_disabled gpl libxavs
 die_license_disabled gpl libxvid
 die_license_disabled gpl postproc
 die_license_disabled gpl x11grab
@@ -2346,11 +2531,11 @@ die_license_disabled nonfree libfaac
 
 die_license_disabled version3 libopencore_amrnb
 die_license_disabled version3 libopencore_amrwb
+die_license_disabled version3 libvo_aacenc
+die_license_disabled version3 libvo_amrwbenc
 
 enabled version3 && { enabled gpl && enable gplv3 || enable lgplv3; }
 
-check_deps $ARCH_EXT_LIST
-
 disabled optimizations || check_cflags -fomit-frame-pointer
 
 enable_pic() {
@@ -2399,11 +2584,20 @@ if enabled alpha; then
 elif enabled arm; then
 
     check_cflags -marm
-
-    check_ld <<EOF && enable vfp_args
+    nogas=die
+
+    if     check_cpp_condition stddef.h "defined __ARM_PCS_VFP"; then
+        enable vfp_args
+    elif ! check_cpp_condition stddef.h "defined __ARM_PCS || defined __SOFTFP__"; then
+        case "${cross_prefix:-$cc}" in
+            *hardfloat*)         enable vfp_args;   fpabi=vfp ;;
+            *) check_ld <<EOF && enable vfp_args && fpabi=vfp || fpabi=soft ;;
 __asm__ (".eabi_attribute 28, 1");
 int main(void) { return 0; }
 EOF
+        esac
+        warn "Compiler does not indicate floating-point ABI, guessing $fpabi."
+    fi
 
     # We have to check if pld is a nop and disable it.
     check_asm pld '"pld [r0]"'
@@ -2426,12 +2620,14 @@ elif enabled ppc; then
 
     enable local_aligned_8 local_aligned_16
 
-    check_asm dcbzl     '"dcbzl 0, 1"'
+    check_asm dcbzl     '"dcbzl 0, %0" :: "r"(0)'
+    check_asm ibm_asm   '"add 0, 0, 0"'
     check_asm ppc4xx    '"maclhw r10, r11, r12"'
     check_asm xform_asm '"lwzx %1, %y0" :: "Z"(*(int*)0), "r"(0)'
 
     # AltiVec flags: The FSF version of GCC differs from the Apple version
     if enabled altivec; then
+        nogas=warn
         check_cflags -maltivec -mabi=altivec &&
         { check_header altivec.h && inc_altivec_h="#include <altivec.h>" ; } ||
         check_cflags -faltivec
@@ -2478,6 +2674,9 @@ EOF
     check_asm ebx_available '""::"b"(0)' &&
         check_asm ebx_available '"":::"%ebx"'
 
+    # check whether xmm clobbers are supported
+    check_asm xmm_clobbers '"":::"%xmm0"'
+
     # check whether more than 10 operands are supported
     check_cc <<EOF && enable ten_operands
 int main(void) {
@@ -2496,14 +2695,27 @@ EOF
 
     check_asm bswap '"bswap %%eax" ::: "%eax"'
 
-    YASMFLAGS="-f $objformat -DARCH_$(toupper $subarch)"
-    enabled     x86_64        && append YASMFLAGS "-m amd64"
-    enabled     pic           && append YASMFLAGS "-DPIC"
-    test -n "$extern_prefix"  && append YASMFLAGS "-DPREFIX"
-    case "$objformat" in
-        elf) enabled debug && append YASMFLAGS "-g dwarf2" ;;
-    esac
-    disabled yasm || { check_yasm "pabsw xmm0, xmm0" && enable yasm; }
+    if ! disabled_any asm mmx yasm; then
+        if check_cmd $yasmexe --version; then
+            enabled x86_64 && yasm_extra="-m amd64"
+            yasm_debug="-g dwarf2"
+        elif check_cmd nasm -v; then
+            yasmexe=nasm
+            yasm_debug="-g -F dwarf"
+            enabled x86_64 && test "$objformat" = elf && objformat=elf64
+        fi
+
+        YASMFLAGS="-f $objformat $yasm_extra"
+        enabled pic               && append YASMFLAGS "-DPIC"
+        test -n "$extern_prefix"  && append YASMFLAGS "-DPREFIX"
+        case "$objformat" in
+            elf*) enabled debug && append YASMFLAGS $yasm_debug ;;
+        esac
+
+        check_yasm "pextrd [eax], xmm0, 1" && enable yasm ||
+            die "yasm not found, use --disable-yasm for a crippled build"
+        check_yasm "vpaddw xmm0, xmm0, xmm0" || disable avx
+    fi
 
     case "$cpu" in
         athlon*|opteron*|k8*|pentium|pentium-mmx|prescott|nocona|atom|geode)
@@ -2513,15 +2725,50 @@ EOF
 
 fi
 
+if enabled asm; then
+    as=${gas:=$as}
+    check_asm gnu_as '".macro m n\n\\n:.int 0\n.endm\nm x"' ||
+        $nogas "GNU assembler not found, install gas-preprocessor"
+fi
+
+check_ldflags -Wl,--as-needed
+
 if check_func dlopen; then
     ldl=
 elif check_func dlopen -ldl; then
     ldl=-ldl
 fi
 
+if enabled network; then
+    check_type "sys/types.h sys/socket.h" socklen_t
+    check_type netdb.h "struct addrinfo"
+    check_type netinet/in.h "struct ipv6_mreq" -D_DARWIN_C_SOURCE
+    check_type netinet/in.h "struct sockaddr_in6"
+    check_type "sys/types.h sys/socket.h" "struct sockaddr_storage"
+    check_struct "sys/types.h sys/socket.h" "struct sockaddr" sa_len
+    # Prefer arpa/inet.h over winsock2
+    if check_header arpa/inet.h ; then
+        check_func closesocket
+    elif check_header winsock2.h ; then
+        check_func_headers winsock2.h closesocket -lws2 && \
+            network_extralibs="-lws2" || \
+        { check_func_headers winsock2.h closesocket -lws2_32 && \
+            network_extralibs="-lws2_32"; }
+        check_type ws2tcpip.h socklen_t
+        check_type ws2tcpip.h "struct addrinfo"
+        check_type ws2tcpip.h "struct ipv6_mreq"
+        check_type ws2tcpip.h "struct sockaddr_in6"
+        check_type ws2tcpip.h "struct sockaddr_storage"
+        check_struct winsock2.h "struct sockaddr" sa_len
+    else
+        disable network
+    fi
+fi
+
 # Solaris has nanosleep in -lrt, OpenSolaris no longer needs that
 check_func nanosleep || { check_func nanosleep -lrt && add_extralibs -lrt; }
 
+check_func  fcntl
 check_func  fork
 check_func  getaddrinfo $network_extralibs
 check_func  gethrtime
@@ -2531,16 +2778,19 @@ check_func  inet_aton $network_extralibs
 check_func  isatty
 check_func  ${malloc_prefix}memalign            && enable memalign
 check_func  mkstemp
+check_func  mmap
 check_func  ${malloc_prefix}posix_memalign      && enable posix_memalign
 check_func  setrlimit
 check_func  strerror_r
+check_func  strtok_r
+check_func_headers conio.h kbhit
 check_func_headers io.h setmode
 check_func_headers lzo/lzo1x.h lzo1x_999_compress
 check_lib2 "windows.h psapi.h" GetProcessMemoryInfo -lpsapi
 check_func_headers windows.h GetProcessTimes
+check_func_headers windows.h MapViewOfFile
 check_func_headers windows.h VirtualAlloc
 
-check_header conio.h
 check_header dlfcn.h
 check_header dxva2api.h
 check_header malloc.h
@@ -2548,7 +2798,6 @@ check_header poll.h
 check_header sys/mman.h
 check_header sys/resource.h
 check_header sys/select.h
-check_header termios.h
 check_header vdpau/vdpau.h
 check_header vdpau/vdpau_x11.h
 check_header X11/extensions/XvMClib.h
@@ -2565,7 +2814,8 @@ disabled bzlib || check_lib2 bzlib.h BZ2_bzlibVersion -lbz2 || disable bzlib
 
 # check for some common methods of building with pthread support
 # do this before the optional library checks as some of them require pthreads
-if enabled pthreads; then
+if ! disabled pthreads && ! enabled w32threads; then
+    enable pthreads
     if check_func pthread_create; then
         :
     elif check_func pthread_create -pthread; then
@@ -2577,7 +2827,7 @@ if enabled pthreads; then
     elif check_func pthread_create -lpthreadGC2; then
         add_extralibs -lpthreadGC2
     elif ! check_lib pthread.h pthread_create -lpthread; then
-        die "ERROR: can't find pthreads library"
+        disable pthreads
     fi
 fi
 
@@ -2590,7 +2840,7 @@ for thread in $THREADS_LIST; do
 done
 
 check_lib math.h sin -lm
-check_lib va/va.h vaInitialize -lva
+enabled vaapi && require vaapi va/va.h vaInitialize -lva
 
 check_mathfunc exp2
 check_mathfunc exp2f
@@ -2606,28 +2856,34 @@ check_mathfunc truncf
 
 # these are off by default, so fail if requested and not available
 enabled avisynth   && require2 vfw32 "windows.h vfw.h" AVIFileInit -lavifil32
-enabled libdirac   && add_cflags $(pkg-config --cflags dirac) &&
-                      require  libdirac libdirac_decoder/dirac_parser.h dirac_decoder_init $(pkg-config --libs dirac) &&
-                      require  libdirac libdirac_encoder/dirac_encoder.h dirac_encoder_init $(pkg-config --libs dirac)
+enabled frei0r     && { check_header frei0r.h || die "ERROR: frei0r.h header not found"; }
+enabled libdirac   && require_pkg_config dirac                          \
+    "libdirac_decoder/dirac_parser.h libdirac_encoder/dirac_encoder.h"  \
+    "dirac_decoder_init dirac_encoder_init"
 enabled libfaac    && require2 libfaac "stdint.h faac.h" faacEncGetVersion -lfaac
-enabled libfaad    && require2 libfaad faad.h faacDecOpen -lfaad
 enabled libgsm     && require  libgsm gsm/gsm.h gsm_create -lgsm
-enabled libmp3lame && require  libmp3lame lame/lame.h lame_init -lmp3lame -lm
+enabled libmp3lame && require  "libmp3lame >= 3.98.3" lame/lame.h lame_set_VBR_quality -lmp3lame
 enabled libnut     && require  libnut libnut.h nut_demuxer_init -lnut
-enabled libopencore_amrnb  && require libopencore_amrnb opencore-amrnb/interf_dec.h Decoder_Interface_init -lopencore-amrnb -lm
-enabled libopencore_amrwb  && require libopencore_amrwb opencore-amrwb/dec_if.h D_IF_init -lopencore-amrwb -lm
+enabled libopencore_amrnb  && require libopencore_amrnb opencore-amrnb/interf_dec.h Decoder_Interface_init -lopencore-amrnb
+enabled libopencore_amrwb  && require libopencore_amrwb opencore-amrwb/dec_if.h D_IF_init -lopencore-amrwb
+enabled libopencv  && require_pkg_config opencv opencv/cv.h cvCreateImageHeader
 enabled libopenjpeg && require libopenjpeg openjpeg.h opj_version -lopenjpeg
-enabled librtmp    && require  librtmp librtmp/rtmp.h RTMP_Init $(pkg-config --libs librtmp)
-enabled libschroedinger && add_cflags $(pkg-config --cflags schroedinger-1.0) &&
-                           require libschroedinger schroedinger/schro.h schro_init $(pkg-config --libs schroedinger-1.0)
+enabled librtmp    && require_pkg_config librtmp librtmp/rtmp.h RTMP_Socket
+enabled libschroedinger && require_pkg_config schroedinger-1.0 schroedinger/schro.h schro_init
 enabled libspeex   && require  libspeex speex/speex.h speex_decoder_init -lspeex
 enabled libtheora  && require  libtheora theora/theoraenc.h th_info_init -ltheoraenc -ltheoradec -logg
+enabled libvo_aacenc && require libvo_aacenc vo-aacenc/voAAC.h voGetAACEncAPI -lvo-aacenc
+enabled libvo_amrwbenc && require libvo_amrwbenc vo-amrwbenc/enc_if.h E_IF_init -lvo-amrwbenc
 enabled libvorbis  && require  libvorbis vorbis/vorbisenc.h vorbis_info_init -lvorbisenc -lvorbis -logg
-enabled libvpx     && require2 libvpx "vpx/vpx_decoder.h vpx/vp8dx.h" "vpx_codec_dec_init_ver" -lvpx &&
-                      require2 libvpx "vpx/vpx_encoder.h vpx/vp8cx.h" "vpx_codec_enc_init_ver" -lvpx
-enabled libx264    && require  libx264 x264.h x264_encoder_encode -lx264 -lm &&
-                      { check_cpp_condition x264.h "X264_BUILD >= 83" ||
-                        die "ERROR: libx264 version must be >= 0.83."; }
+enabled libvpx     && {
+    enabled libvpx_decoder && { check_lib2 "vpx/vpx_decoder.h vpx/vp8dx.h" vpx_codec_dec_init_ver -lvpx ||
+                                die "ERROR: libvpx decoder version must be >=0.9.1"; }
+    enabled libvpx_encoder && { check_lib2 "vpx/vpx_encoder.h vpx/vp8cx.h" vpx_codec_enc_init_ver -lvpx ||
+                                die "ERROR: libvpx encoder version must be >=0.9.1"; } }
+enabled libx264    && require  libx264 x264.h x264_encoder_encode -lx264 &&
+                      { check_cpp_condition x264.h "X264_BUILD >= 99" ||
+                        die "ERROR: libx264 version must be >= 0.99."; }
+enabled libxavs    && require  libxavs xavs.h xavs_encoder_encode -lxavs
 enabled libxvid    && require  libxvid xvid.h xvid_global -lxvidcore
 enabled mlib       && require  mediaLib mlib_types.h mlib_VectorSub_S16_U8_Mod -lmlib
 
@@ -2640,11 +2896,7 @@ if enabled libdc1394; then
     die "ERROR: No version of libdc1394 found "
 fi
 
-SDL_CONFIG="${cross_prefix}sdl-config"
-if "${SDL_CONFIG}" --version > /dev/null 2>&1; then
-    sdl_cflags=$("${SDL_CONFIG}" --cflags)
-    sdl_libs=$("${SDL_CONFIG}" --libs)
-    check_func_headers SDL.h SDL_Init $sdl_cflags $sdl_libs &&
+if check_pkg_config sdl SDL_version.h SDL_Linked_Version; then
     check_cpp_condition SDL.h "(SDL_MAJOR_VERSION<<16 | SDL_MINOR_VERSION<<8 | SDL_PATCHLEVEL) >= 0x010201" $sdl_cflags &&
     enable sdl &&
     check_struct SDL.h SDL_VideoInfo current_w $sdl_cflags && enable sdl_video_size
@@ -2652,37 +2904,15 @@ fi
 
 texi2html -version > /dev/null 2>&1 && enable texi2html || disable texi2html
 
-if enabled network; then
-    check_type "sys/types.h sys/socket.h" socklen_t
-    check_type netdb.h "struct addrinfo"
-    check_type netinet/in.h "struct ipv6_mreq"
-    check_type netinet/in.h "struct sockaddr_in6"
-    check_type "sys/types.h sys/socket.h" "struct sockaddr_storage"
-    check_struct "sys/types.h sys/socket.h" "struct sockaddr" sa_len
-    # Prefer arpa/inet.h over winsock2
-    if check_header arpa/inet.h ; then
-        check_func closesocket
-    elif check_header winsock2.h ; then
-        check_func_headers winsock2.h closesocket -lws2 && \
-            network_extralibs="-lws2" || \
-        { check_func_headers winsock2.h closesocket -lws2_32 && \
-            network_extralibs="-lws2_32"; }
-        check_type ws2tcpip.h socklen_t
-        check_type ws2tcpip.h "struct addrinfo"
-        check_type ws2tcpip.h "struct ipv6_mreq"
-        check_type ws2tcpip.h "struct sockaddr_in6"
-        check_type ws2tcpip.h "struct sockaddr_storage"
-        check_struct winsock2.h "struct sockaddr" sa_len
-    else
-        disable network
-    fi
-fi
-
+check_header linux/fb.h
 check_header linux/videodev.h
 check_header linux/videodev2.h
 check_header sys/videoio.h
 
 check_func_headers "windows.h vfw.h" capCreateCaptureWindow "$vfwcap_indev_extralibs"
+# check that WM_CAP_DRIVER_CONNECT is defined to the proper value
+# w32api 3.12 had it defined wrong
+check_cpp_condition vfw.h "WM_CAP_DRIVER_CONNECT > WM_USER" && enable vfwcap_defines
 
 # check for ioctl_meteor.h, ioctl_bt848.h and alternatives
 { check_header dev/bktr/ioctl_meteor.h &&
@@ -2693,6 +2923,7 @@ check_func_headers "windows.h vfw.h" capCreateCaptureWindow "$vfwcap_indev_extra
   check_header dev/video/bktr/ioctl_bt848.h; } ||
 check_header dev/ic/bt8xx.h
 
+check_header sndio.h
 check_header sys/soundcard.h
 check_header soundcard.h
 
@@ -2700,6 +2931,8 @@ enabled_any alsa_indev alsa_outdev && check_lib2 alsa/asoundlib.h snd_pcm_htimes
 
 enabled jack_indev && check_lib2 jack/jack.h jack_client_open -ljack
 
+enabled_any sndio_indev sndio_outdev && check_lib2 sndio.h sio_open -lsndio
+
 enabled x11grab                         &&
 check_header X11/Xlib.h                 &&
 check_header X11/extensions/XShm.h      &&
@@ -2720,6 +2953,7 @@ enabled debug && add_cflags -g"$debuglevel" && add_asflags -g"$debuglevel"
 # add some useful compiler flags if supported
 check_cflags -Wdeclaration-after-statement
 check_cflags -Wall
+check_cflags -Wno-parentheses
 check_cflags -Wno-switch
 check_cflags -Wdisabled-optimization
 check_cflags -Wpointer-arith
@@ -2734,9 +2968,8 @@ enabled extra_warnings && check_cflags -Winline
 
 # add some linker flags
 check_ldflags -Wl,--warn-common
-check_ldflags -Wl,--as-needed
 check_ldflags '-Wl,-rpath-link,\$(BUILD_ROOT)/libpostproc -Wl,-rpath-link,\$(BUILD_ROOT)/libswscale -Wl,-rpath-link,\$(BUILD_ROOT)/libavfilter -Wl,-rpath-link,\$(BUILD_ROOT)/libavdevice -Wl,-rpath-link,\$(BUILD_ROOT)/libavformat -Wl,-rpath-link,\$(BUILD_ROOT)/libavcodec -Wl,-rpath-link,\$(BUILD_ROOT)/libavutil'
-check_ldflags -Wl,-Bsymbolic
+test_ldflags -Wl,-Bsymbolic && append SHFLAGS -Wl,-Bsymbolic
 
 echo "X{};" > $TMPV
 if test_ldflags -Wl,--version-script,$TMPV; then
@@ -2767,9 +3000,11 @@ if enabled icc; then
     check_cflags -w1
     # -wd: Disable following warnings
     # 144, 167, 556: -Wno-pointer-sign
+    # 1292: attribute "foo" ignored
     # 10006: ignoring unknown option -fno-signed-zeros
+    # 10148: ignoring unknown option -Wno-parentheses
     # 10156: ignoring option '-W'; no argument required
-    check_cflags -wd144,167,556,10006,10156
+    check_cflags -wd144,167,556,1292,10006,10148,10156
     # 11030: Warning unknown option --as-needed
     # 10156: ignoring option '-export'; no argument required
     check_ldflags -wd10156,11030
@@ -2777,6 +3012,11 @@ if enabled icc; then
     check_ldflags -march=$cpu
     # icc 11.0 and 11.1 work with ebp_available, but don't pass the test
     enable ebp_available
+    if enabled x86_32; then
+        test ${icc_version%%.*} -ge 11 && \
+            check_cflags -falign-stack=maintain-16-byte || \
+            disable aligned_stack
+    fi
 elif enabled ccc; then
     # disable some annoying warnings
     add_cflags -msg_disable cvtu32to64
@@ -2787,26 +3027,25 @@ elif enabled ccc; then
     add_cflags -msg_disable unreachcode
 elif enabled gcc; then
     check_cflags -fno-tree-vectorize
-    check_cflags -Werror=implicit
+    check_cflags -Werror=implicit-function-declaration
     check_cflags -Werror=missing-prototypes
+elif enabled llvm_gcc; then
+    check_cflags -mllvm -stack-alignment=16
 elif enabled clang; then
+    check_cflags -mllvm -stack-alignment=16
     check_cflags -Qunused-arguments
 elif enabled armcc; then
     # 2523: use of inline assembler is deprecated
-    add_cflags -Wrvct,--diag_suppress=2523
-    add_cflags -Wrvct,--diag_suppress=1207
+    add_cflags -W${armcc_opt},--diag_suppress=2523
+    add_cflags -W${armcc_opt},--diag_suppress=1207
+    add_cflags -W${armcc_opt},--diag_suppress=1293 # assignment in condition
+    add_cflags -W${armcc_opt},--diag_suppress=3343 # hardfp compat
 elif enabled tms470; then
     add_cflags -pds=824 -pds=837
+elif enabled pathscale; then
+    add_cflags -fstrict-overflow -OPT:wrap_around_unsafe_opt=OFF
 fi
 
-if enabled gprof; then
-    add_cflags  -p
-    add_ldflags -p
-fi
-
-# Find out if the .align argument is a power of two or not.
-check_asm asmalign_pot '".align 3"'
-
 enabled_any $THREADS_LIST      && enable threads
 
 check_deps $CONFIG_LIST       \
@@ -2823,13 +3062,17 @@ check_deps $CONFIG_LIST       \
            $INDEV_LIST        \
            $OUTDEV_LIST       \
            $PROTOCOL_LIST     \
+           $ACODEC_TESTS      \
+           $VCODEC_TESTS      \
+           $LAVF_TESTS        \
+           $LAVFI_TESTS       \
+           $SEEK_TESTS        \
 
 enabled asm || { arch=c; disable $ARCH_LIST $ARCH_EXT_LIST; }
 
 echo "install prefix            $prefix"
 echo "source path               $source_path"
 echo "C compiler                $cc"
-echo ".align is power-of-two    $asmalign_pot"
 echo "ARCH                      $arch ($cpu)"
 if test "$build_suffix" != ""; then
     echo "build suffix              $build_suffix"
@@ -2868,43 +3111,43 @@ if enabled ppc; then
     echo "AltiVec enabled           ${altivec-no}"
     echo "PPC 4xx optimizations     ${ppc4xx-no}"
     echo "dcbzl available           ${dcbzl-no}"
-    echo "performance report        ${powerpc_perf-no}"
 fi
 if enabled sparc; then
     echo "VIS enabled               ${vis-no}"
 fi
-echo "gprof enabled             ${gprof-no}"
 echo "debug symbols             ${debug-no}"
-echo "strip symbols             ${stripping-no}"
 echo "optimizations             ${optimizations-no}"
 echo "static                    ${static-no}"
 echo "shared                    ${shared-no}"
 echo "postprocessing support    ${postproc-no}"
 echo "new filter support        ${avfilter-no}"
-echo "filters using lavformat   ${avfilter_lavf-no}"
 echo "network support           ${network-no}"
 echo "threading support         ${thread_type-no}"
 echo "SDL support               ${sdl-no}"
 echo "Sun medialib support      ${mlib-no}"
 echo "AVISynth enabled          ${avisynth-no}"
+echo "frei0r enabled            ${frei0r-no}"
 echo "libdc1394 support         ${libdc1394-no}"
 echo "libdirac enabled          ${libdirac-no}"
 echo "libfaac enabled           ${libfaac-no}"
-echo "libfaad enabled           ${libfaad-no}"
-echo "libfaad dlopened          ${libfaadbin-no}"
 echo "libgsm enabled            ${libgsm-no}"
 echo "libmp3lame enabled        ${libmp3lame-no}"
 echo "libnut enabled            ${libnut-no}"
 echo "libopencore-amrnb support ${libopencore_amrnb-no}"
 echo "libopencore-amrwb support ${libopencore_amrwb-no}"
+echo "libopencv support         ${libopencv-no}"
 echo "libopenjpeg enabled       ${libopenjpeg-no}"
 echo "librtmp enabled           ${librtmp-no}"
 echo "libschroedinger enabled   ${libschroedinger-no}"
 echo "libspeex enabled          ${libspeex-no}"
 echo "libtheora enabled         ${libtheora-no}"
+echo "libva enabled             ${vaapi-no}"
+echo "libvo-aacenc support      ${libvo_aacenc-no}"
+echo "libvo-amrwbenc support    ${libvo_amrwbenc-no}"
 echo "libvorbis enabled         ${libvorbis-no}"
 echo "libvpx enabled            ${libvpx-no}"
 echo "libx264 enabled           ${libx264-no}"
+echo "libxavs enabled           ${libxavs-no}"
 echo "libxvid enabled           ${libxvid-no}"
 echo "zlib enabled              ${zlib-no}"
 echo "bzlib enabled             ${bzlib-no}"
@@ -2913,9 +3156,7 @@ echo
 for type in decoder encoder hwaccel parser demuxer muxer protocol filter bsf indev outdev; do
     echo "Enabled ${type}s:"
     eval list=\$$(toupper $type)_LIST
-    for part in $list; do
-        enabled $part && echo ${part%_*}
-    done | sort | pr -3 -t
+    print_enabled '_*' $list | sort | pr -r -3 -t
     echo
 done
 
@@ -2942,6 +3183,7 @@ if enabled source_path_used; then
         libavcodec/$arch
         libavdevice
         libavfilter
+        libavfilter/$arch
         libavformat
         libavutil
         libavutil/$arch
@@ -2960,6 +3202,7 @@ if enabled source_path_used; then
         libavcodec/${arch}/Makefile
         libavdevice/Makefile
         libavfilter/Makefile
+        libavfilter/${arch}/Makefile
         libavformat/Makefile
         libavutil/Makefile
         libpostproc/Makefile
@@ -2969,13 +3212,13 @@ if enabled source_path_used; then
     map 'test -f "$source_path/$v" && $ln_s "$source_path/$v" $v' $FILES
 fi
 
-enabled stripping || strip="echo skipping strip"
+config_files="$TMPH config.mak"
 
 cat > config.mak <<EOF
 # Automatically generated by configure - do not modify!
-ifndef FFMPEG_CONFIG_MAK
-FFMPEG_CONFIG_MAK=1
-FFMPEG_CONFIGURATION=$FFMPEG_CONFIGURATION
+ifndef LIBAV_CONFIG_MAK
+LIBAV_CONFIG_MAK=1
+LIBAV_CONFIGURATION=$LIBAV_CONFIGURATION
 prefix=$prefix
 LIBDIR=\$(DESTDIR)$libdir
 SHLIBDIR=\$(DESTDIR)$shlibdir
@@ -2986,6 +3229,7 @@ MANDIR=\$(DESTDIR)$mandir
 SRC_PATH="$source_path"
 SRC_PATH_BARE=$source_path
 BUILD_ROOT="$PWD"
+CC_IDENT=$cc_ident
 ARCH=$arch
 CC=$cc
 AS=$as
@@ -2995,13 +3239,12 @@ YASM=$yasmexe
 YASMDEP=$yasmexe
 AR=$ar
 RANLIB=$ranlib
-CP=cp -p
 LN_S=$ln_s
-STRIP=$strip
 CPPFLAGS=$CPPFLAGS
 CFLAGS=$CFLAGS
 ASFLAGS=$ASFLAGS
 CC_O=$CC_O
+DLLTOOL=$dlltool
 LDFLAGS=$LDFLAGS
 FFSERVERLDFLAGS=$FFSERVERLDFLAGS
 SHFLAGS=$SHFLAGS
@@ -3040,7 +3283,7 @@ SLIB_CREATE_DEF_CMD=${SLIB_CREATE_DEF_CMD}
 SLIB_EXTRA_CMD=${SLIB_EXTRA_CMD}
 SLIB_INSTALL_EXTRA_CMD=${SLIB_INSTALL_EXTRA_CMD}
 SLIB_UNINSTALL_EXTRA_CMD=${SLIB_UNINSTALL_EXTRA_CMD}
-SAMPLES=$samples
+SAMPLES:=${samples:-\$(FATE_SAMPLES)}
 EOF
 
 get_version(){
@@ -3055,27 +3298,25 @@ get_version(){
 
 get_version LIBSWSCALE  libswscale/swscale.h
 get_version LIBPOSTPROC libpostproc/postprocess.h
-get_version LIBAVCODEC  libavcodec/avcodec.h
+get_version LIBAVCODEC  libavcodec/version.h
 get_version LIBAVDEVICE libavdevice/avdevice.h
-get_version LIBAVFORMAT libavformat/avformat.h
+get_version LIBAVFORMAT libavformat/version.h
 get_version LIBAVUTIL   libavutil/avutil.h
 get_version LIBAVFILTER libavfilter/avfilter.h
 
-enabled asmalign_pot || align_shift="1 <<"
-
 cat > $TMPH <<EOF
 /* Automatically generated by configure - do not modify! */
-#ifndef FFMPEG_CONFIG_H
-#define FFMPEG_CONFIG_H
-#define FFMPEG_CONFIGURATION "$(c_escape $FFMPEG_CONFIGURATION)"
-#define FFMPEG_LICENSE "$(c_escape $license)"
+#ifndef LIBAV_CONFIG_H
+#define LIBAV_CONFIG_H
+#define LIBAV_CONFIGURATION "$(c_escape $LIBAV_CONFIGURATION)"
+#define LIBAV_LICENSE "$(c_escape $license)"
 #define FFMPEG_DATADIR "$(eval c_escape $datadir)"
 #define CC_TYPE "$cc_type"
 #define CC_VERSION $cc_version
 #define restrict $_restrict
-#define ASMALIGN(ZEROBITS) ".align $align_shift " #ZEROBITS "\\n\\t"
 #define EXTERN_PREFIX "${extern_prefix}"
 #define EXTERN_ASM ${extern_prefix}
+#define SLIBSUF "$SLIBSUF"
 EOF
 
 test -n "$malloc_prefix" &&
@@ -3083,30 +3324,50 @@ test -n "$malloc_prefix" &&
 
 if enabled small || disabled optimizations; then
     echo "#undef  av_always_inline"  >> $TMPH
-    echo "#define av_always_inline"  >> $TMPH
+    if enabled small; then
+        echo "#define av_always_inline inline"  >> $TMPH
+    else
+        echo "#define av_always_inline av_unused"  >> $TMPH
+    fi
 fi
 
-print_config ARCH_   $TMPH config.mak $ARCH_LIST
-print_config HAVE_   $TMPH config.mak $HAVE_LIST
-print_config CONFIG_ $TMPH config.mak $CONFIG_LIST       \
-                                      $CONFIG_EXTRA      \
-                                      $DECODER_LIST      \
-                                      $ENCODER_LIST      \
-                                      $HWACCEL_LIST      \
-                                      $PARSER_LIST       \
-                                      $BSF_LIST          \
-                                      $DEMUXER_LIST      \
-                                      $MUXER_LIST        \
-                                      $FILTER_LIST       \
-                                      $PROTOCOL_LIST     \
-                                      $INDEV_LIST        \
-                                      $OUTDEV_LIST       \
-
-echo "#endif /* FFMPEG_CONFIG_H */" >> $TMPH
-echo "endif # FFMPEG_CONFIG_MAK" >> config.mak
+if enabled yasm; then
+    append config_files $TMPASM
+    printf '' >$TMPASM
+fi
+
+print_config ARCH_   "$config_files" $ARCH_LIST
+print_config HAVE_   "$config_files" $HAVE_LIST
+print_config CONFIG_ "$config_files" $CONFIG_LIST       \
+                                     $CONFIG_EXTRA      \
+                                     $DECODER_LIST      \
+                                     $ENCODER_LIST      \
+                                     $HWACCEL_LIST      \
+                                     $PARSER_LIST       \
+                                     $BSF_LIST          \
+                                     $DEMUXER_LIST      \
+                                     $MUXER_LIST        \
+                                     $FILTER_LIST       \
+                                     $PROTOCOL_LIST     \
+                                     $INDEV_LIST        \
+                                     $OUTDEV_LIST       \
+
+cat >>config.mak <<EOF
+ACODEC_TESTS=$(print_enabled -n _test $ACODEC_TESTS)
+VCODEC_TESTS=$(print_enabled -n _test $VCODEC_TESTS)
+LAVF_TESTS=$(print_enabled   -n _test $LAVF_TESTS)
+LAVFI_TESTS=$(print_enabled  -n _test $LAVFI_TESTS)
+SEEK_TESTS=$(print_enabled   -n _test $SEEK_TESTS)
+EOF
+
+echo "#endif /* LIBAV_CONFIG_H */" >> $TMPH
+echo "endif # LIBAV_CONFIG_MAK" >> config.mak
 
 # Do not overwrite an unchanged config.h to avoid superfluous rebuilds.
 cp_if_changed $TMPH config.h
+touch .config
+
+enabled yasm && cp_if_changed $TMPASM config.asm
 
 cat > $TMPH <<EOF
 /* Generated by ffconf */
@@ -3114,12 +3375,14 @@ cat > $TMPH <<EOF
 #define AVUTIL_AVCONFIG_H
 EOF
 
-print_config AV_HAVE_ $TMPH /dev/null $HAVE_LIST_PUB
+print_config AV_HAVE_ $TMPH $HAVE_LIST_PUB
 
 echo "#endif /* AVUTIL_AVCONFIG_H */" >> $TMPH
 
 cp_if_changed $TMPH libavutil/avconfig.h
 
+test -n "$WARNINGS" && printf "\n$WARNINGS"
+
 # build pkg-config files
 
 pkgconfig_generate(){
@@ -3129,6 +3392,7 @@ comment=$2
 version=$3
 libs=$4
 requires=$5
+enabled ${name#lib} || return 0
 cat <<EOF > $name/$name.pc
 prefix=$prefix
 exec_prefix=\${prefix}
@@ -3161,12 +3425,10 @@ Cflags: -I\${includedir}
 EOF
 }
 
-pkgconfig_generate libavutil "FFmpeg utility library" "$LIBAVUTIL_VERSION"
-pkgconfig_generate libavcodec "FFmpeg codec library" "$LIBAVCODEC_VERSION" "$extralibs" "libavutil = $LIBAVUTIL_VERSION"
-pkgconfig_generate libavformat "FFmpeg container format library" "$LIBAVFORMAT_VERSION" "$extralibs" "libavcodec = $LIBAVCODEC_VERSION"
-pkgconfig_generate libavdevice "FFmpeg device handling library" "$LIBAVDEVICE_VERSION" "$extralibs" "libavformat = $LIBAVFORMAT_VERSION"
-enabled avfilter &&
-    pkgconfig_generate libavfilter "FFmpeg video filtering library" "$LIBAVFILTER_VERSION" "$extralibs" "libavutil = $LIBAVUTIL_VERSION"
-enabled postproc &&
-    pkgconfig_generate libpostproc "FFmpeg post processing library" "$LIBPOSTPROC_VERSION"
-pkgconfig_generate libswscale "FFmpeg image rescaling library" "$LIBSWSCALE_VERSION" "" "libavutil = $LIBAVUTIL_VERSION"
+pkgconfig_generate libavutil "Libav utility library" "$LIBAVUTIL_VERSION"
+pkgconfig_generate libavcodec "Libav codec library" "$LIBAVCODEC_VERSION" "$extralibs"
+pkgconfig_generate libavformat "Libav container format library" "$LIBAVFORMAT_VERSION" "$extralibs" "libavcodec = $LIBAVCODEC_VERSION"
+pkgconfig_generate libavdevice "Libav device handling library" "$LIBAVDEVICE_VERSION" "$extralibs" "libavformat = $LIBAVFORMAT_VERSION"
+pkgconfig_generate libavfilter "Libav video filtering library" "$LIBAVFILTER_VERSION" "$extralibs"
+pkgconfig_generate libpostproc "Libav post processing library" "$LIBPOSTPROC_VERSION"
+pkgconfig_generate libswscale "Libav image rescaling library" "$LIBSWSCALE_VERSION" "" "libavutil = $LIBAVUTIL_VERSION"
diff --git a/doc/APIchanges b/doc/APIchanges
index db69658..11a8b51 100644
--- a/doc/APIchanges
+++ b/doc/APIchanges
@@ -12,14 +12,542 @@ libavutil:   2009-03-08
 
 API changes, most recent first:
 
+2011-04-12 - lavf 52.107.0 - avio.h
+  Avio cleanup, part II - deprecate the entire URLContext API:
+    175389c add avio_check as a replacement for url_exist
+    ff1ec0c add avio_pause and avio_seek_time as replacements
+            for _av_url_read_fseek/fpause
+    cdc6a87 deprecate av_protocol_next(), avio_enum_protocols
+            should be used instead.
+    80c6e23 rename url_set_interrupt_cb->avio_set_interrupt_cb.
+    f87b1b3 rename open flags: URL_* -> AVIO_*
+    f8270bb add avio_enum_protocols.
+    5593f03 deprecate URLProtocol.
+    c486dad deprecate URLContext.
+    026e175 deprecate the typedef for URLInterruptCB
+    8e76a19 deprecate av_register_protocol2.
+    b840484 deprecate URL_PROTOCOL_FLAG_NESTED_SCHEME
+    1305d93 deprecate av_url_read_seek
+    fa104e1 deprecate av_url_read_pause
+    727c7aa deprecate url_get_filename().
+    5958df3 deprecate url_max_packet_size().
+    1869ea0 deprecate url_get_file_handle().
+    32a97d4 deprecate url_filesize().
+    e52a914 deprecate url_close().
+    58a48c6 deprecate url_seek().
+    925e908 deprecate url_write().
+    dce3756 deprecate url_read_complete().
+    bc371ac deprecate url_read().
+    0589da0 deprecate url_open().
+    62eaaea deprecate url_connect.
+    5652bb9 deprecate url_alloc.
+    333e894 deprecate url_open_protocol
+    e230705 deprecate url_poll and URLPollEntry
+
+2011-04-10 - lavu  50.40.0 - pixfmt.h
+  Add PIX_FMT_BGR48LE and PIX_FMT_BGR48BE pixel formats
+
+2011-04-08 - lavf 52.106.0 - avformat.h
+  Minor avformat.h cleanup:
+    a9bf9d8 deprecate av_guess_image2_codec
+    c3675df rename avf_sdp_create->av_sdp_create
+
+2011-04-03 - lavf 52.105.0 - avio.h
+  Large-scale renaming/deprecating of AVIOContext-related functions:
+    724f6a0 deprecate url_fdopen
+    403ee83 deprecate url_open_dyn_packet_buf
+    6dc7d80 rename url_close_dyn_buf       -> avio_close_dyn_buf
+    b92c545 rename url_open_dyn_buf        -> avio_open_dyn_buf
+    8978fed introduce an AVIOContext.seekable field as a replacement for
+            AVIOContext.is_streamed and url_is_streamed()
+    b64030f deprecate get_checksum()
+    4c4427a deprecate init_checksum()
+    4ec153b deprecate udp_set_remote_url/get_local_port
+    933e90a deprecate av_url_read_fseek/fpause
+    8d9769a deprecate url_fileno
+    b7f2fdd rename put_flush_packet -> avio_flush
+    35f1023 deprecate url_close_buf
+    83fddae deprecate url_open_buf
+    d9d86e0 rename url_fprintf -> avio_printf
+    59f65d9 deprecate url_setbufsize
+    3e68b3b deprecate url_ferror
+    66e5b1d deprecate url_feof
+    e8bb2e2 deprecate url_fget_max_packet_size
+    76aa876 rename url_fsize -> avio_size
+    e519753 deprecate url_fgetc
+    655e45e deprecate url_fgets
+    a2704c9 rename url_ftell -> avio_tell
+    e16ead0 deprecate get_strz() in favor of avio_get_str
+    0300db8,2af07d3 rename url_fskip -> avio_skip
+    6b4aa5d rename url_fseek -> avio_seek
+    61840b4 deprecate put_tag
+    22a3212 rename url_fopen/fclose -> avio_open/close.
+    0ac8e2b deprecate put_nbyte
+    77eb550 rename put_byte          -> avio_w8
+                   put_[b/l]e<type>  -> avio_w[b/l]<type>
+                   put_buffer        -> avio_write
+    b7effd4 rename get_byte          -> avio_r8,
+                   get_[b/l]e<type>  -> avio_r[b/l]<type>
+                   get_buffer        -> avio_read
+    b3db9ce deprecate get_partial_buffer
+    8d9ac96 rename av_alloc_put_byte -> avio_alloc_context
+
+2011-03-25 - 34b47d7 - lavc 52.115.0 - AVCodecContext.audio_service_type
+  Add audio_service_type field to AVCodecContext.
+
+2011-03-02 - 863c471 - lavf  52.103.0 - av_pkt_dump2, av_pkt_dump_log2
+  Add new functions av_pkt_dump2, av_pkt_dump_log2 that uses the
+  source stream timebase for outputting timestamps. Deprecate
+  av_pkt_dump and av_pkt_dump_log.
+
+2011-02-20 - e731b8d - lavf  52.102.0 - avio.h
+  * e731b8d - rename init_put_byte() to ffio_init_context(), deprecating the
+              original, and move it to a private header so it is no longer
+              part of our public API. Instead, use av_alloc_put_byte().
+  * ae628ec - rename ByteIOContext to AVIOContext.
+
+2011-02-16 - 09d171b - lavf  52.101.0 - avformat.h
+                       lavu  52.39.0  - parseutils.h
+  * 610219a - Add av_ prefix to dump_format().
+  * f6c7375 - Replace parse_date() in lavf with av_parse_time() in lavu.
+  * ab0287f - Move find_info_tag from lavf to lavu and add av_prefix to it.
+
+2011-02-15 - lavu 52.38.0 - merge libavcore
+  libavcore is merged back completely into libavutil
+
+2011-02-10 - 55bad0c - lavc 52.113.0 - vbv_delay
+  Add vbv_delay field to AVCodecContext
+
+2011-02-14 - 24a83bd - lavf 52.100.0 - AV_DISPOSITION_CLEAN_EFFECTS
+  Add AV_DISPOSITION_CLEAN_EFFECTS disposition flag.
+
+2011-02-14 - 910b5b8 - lavfi 1.76.0 - AVFilterLink sample_aspect_ratio
+  Add sample_aspect_ratio field to AVFilterLink.
+
+2011-02-10 - 12c14cd - lavf 52.99.0 - AVStream.disposition
+  Add AV_DISPOSITION_HEARING_IMPAIRED and AV_DISPOSITION_VISUAL_IMPAIRED.
+
+2011-02-09 - 5592734 - lavc 52.112.0 - avcodec_thread_init()
+  Deprecate avcodec_thread_init()/avcodec_thread_free() use; instead
+  set thread_count before calling avcodec_open.
+
+2011-02-09 - 778b08a - lavc 52.111.0 - threading API
+  Add CODEC_CAP_FRAME_THREADS with new restrictions on get_buffer()/
+  release_buffer()/draw_horiz_band() callbacks for appropriate codecs.
+  Add thread_type and active_thread_type fields to AVCodecContext.
+
+2011-02-08 - 3940caa - lavf 52.98.0 - av_probe_input_buffer
+  Add av_probe_input_buffer() to avformat.h for probing format from a
+  ByteIOContext.
+
+2011-02-06 - fe174fc - lavf 52.97.0 - avio.h
+  Add flag for non-blocking protocols: URL_FLAG_NONBLOCK
+
+2011-02-04 - f124b08 - lavf 52.96.0 - avformat_free_context()
+  Add avformat_free_context() in avformat.h.
+
+2011-02-03 - f5b82f4 - lavc 52.109.0 - add CODEC_ID_PRORES
+  Add CODEC_ID_PRORES to avcodec.h.
+
+2011-02-03 - fe9a3fb - lavc 52.109.0 - H.264 profile defines
+  Add defines for H.264 * Constrained Baseline and Intra profiles
+
+2011-02-02 - lavf 52.95.0
+  * 50196a9 - add a new installed header version.h.
+  * 4efd5cf, dccbd97, 93b78d1 - add several variants of public
+    avio_{put,get}_str* functions.  Deprecate corresponding semi-public
+    {put,get}_str*.
+
+2011-02-02 - dfd2a00 - lavu 50.37.0 - log.h
+  Make av_dlog public.
+
+2011-01-15 - r26374 - lavfi 1.74.0 - AVFilterBufferRefAudioProps
+  Rename AVFilterBufferRefAudioProps.samples_nb to nb_samples.
+
+2011-01-14 - r26330 - lavf 52.93.0 - av_metadata_copy()
+  Add av_metadata_copy() in avformat.h.
+
+2011-01-07 - r26262 - lavc 52.107.0 - deprecate reordered_opaque
+  Deprecate reordered_opaque in favor of pkt_pts/dts.
+
+2011-01-07 - r26261 - lavc 52.106.0 - pkt_dts
+  Add pkt_dts to AVFrame, this will in the future allow multithreading decoders
+  to not mess up dts.
+
+2011-01-07 - r26260 - lavc 52.105.0 - pkt_pts
+  Add pkt_pts to AVFrame.
+
+2011-01-07 - r26259 - lavc 52.104.0 - av_get_profile_name()
+  Add av_get_profile_name to libavcodec/avcodec.h.
+
+2010-12-27 - r26108 - lavfi 1.71.0 - AV_PERM_NEG_LINESIZES
+  Add AV_PERM_NEG_LINESIZES in avfilter.h.
+
+2010-12-27 - r26104 - lavf 52.91.0 - av_find_best_stream()
+  Add av_find_best_stream to libavformat/avformat.h.
+
+2010-12-27 - r26103 - lavf 52.90.0
+  Add AVFMT_NOSTREAMS flag for formats with no streams,
+  like e.g. text metadata.
+
+2010-12-22 - r26073 - lavu 50.36.0 - file.h
+  Add functions av_file_map() and av_file_unmap() in file.h.
+
+2010-12-19 - r26056 - lavu 50.35.0 - error.h
+  Add "not found" error codes:
+  AVERROR_DEMUXER_NOT_FOUND
+  AVERROR_MUXER_NOT_FOUND
+  AVERROR_DECODER_NOT_FOUND
+  AVERROR_ENCODER_NOT_FOUND
+  AVERROR_PROTOCOL_NOT_FOUND
+  AVERROR_FILTER_NOT_FOUND
+  AVERROR_BSF_NOT_FOUND
+  AVERROR_STREAM_NOT_FOUND
+
+2010-12-09 - r25923 - lavcore 0.16.0 - avcore.h
+  Move AV_NOPTS_VALUE, AV_TIME_BASE, AV_TIME_BASE_Q symbols from
+  avcodec.h to avcore.h.
+
+2010-12-04 - r25886 - lavc 52.98.0 - CODEC_CAP_NEG_LINESIZES
+  Add CODEC_CAP_NEG_LINESIZES codec capability flag in avcodec.h.
+
+2010-12-04 - r25879 - lavu 50.34.0 - av_get_pix_fmt_string()
+  Deprecate avcodec_pix_fmt_string() in favor of
+  pixdesc.h/av_get_pix_fmt_string().
+
+2010-12-04 - r25878 - lavcore 0.15.0 - av_image_alloc()
+  Add av_image_alloc() to libavcore/imgutils.h.
+
+2010-12-02 - r25862 - lavfi 1.67.0 - avfilter_graph_create_filter()
+  Add function avfilter_graph_create_filter() in avfiltergraph.h.
+
+2010-11-25 - r25826 - lavfi 1.65.0 - avfilter_get_video_buffer_ref_from_arrays()
+  Add function avfilter_get_video_buffer_ref_from_arrays() in
+  avfilter.h.
+
+2010-11-21 - r25787 - lavcore 0.14.0 - audioconvert.h
+  Add a public audio channel API in audioconvert.h, and deprecate the
+  corresponding functions in libavcodec:
+  avcodec_get_channel_name()
+  avcodec_get_channel_layout()
+  avcodec_get_channel_layout_string()
+  avcodec_channel_layout_num_channels()
+  and the CH_* macros defined in libavcodec/avcodec.h.
+
+2010-11-21 - r25777 - lavf 52.85.0 - avformat.h
+  Add av_append_packet().
+
+2010-11-21 - r25776 - lavc 52.97.0 - avcodec.h
+  Add av_grow_packet().
+
+2010-11-17 - r25761 - lavcore 0.13.0 - parseutils.h
+  Add av_parse_color() declared in libavcore/parseutils.h.
+
+2010-11-13 - r25745 - lavc 52.95.0 - AVCodecContext
+  Add AVCodecContext.subtitle_header and AVCodecContext.subtitle_header_size
+  fields.
+
+2010-11-13 - r25740 - lavfi 1.62.0 - avfiltergraph.h
+  Make avfiltergraph.h public.
+
+2010-11-13 - r25737 - lavfi 1.61.0 - avfiltergraph.h
+  Remove declarations from avfiltergraph.h for the functions:
+  avfilter_graph_check_validity()
+  avfilter_graph_config_links()
+  avfilter_graph_config_formats()
+  which are now internal.
+  Use avfilter_graph_config() instead.
+
+2010-11-08 - r25708 - lavu 50.33.0 - eval.h
+  Deprecate functions:
+  av_parse_and_eval_expr(),
+  av_parse_expr(),
+  av_eval_expr(),
+  av_free_expr(),
+  in favor of the functions:
+  av_expr_parse_and_eval(),
+  av_expr_parse(),
+  av_expr_eval(),
+  av_expr_free().
+
+2010-11-08 - r25707 - lavfi 1.59.0 - avfilter_free()
+  Rename avfilter_destroy() to avfilter_free().
+  This change breaks libavfilter API/ABI.
+
+2010-11-07 - r25705 - lavfi 1.58.0 - avfiltergraph.h
+  Remove graphparser.h header, move AVFilterInOut and
+  avfilter_graph_parse() declarations to libavfilter/avfiltergraph.h.
+
+2010-11-07 - r25700 - lavfi 1.57.0 - AVFilterInOut
+  Rename field AVFilterInOut.filter to AVFilterInOut.filter_ctx.
+  This change breaks libavfilter API.
+
+2010-11-04 - r25674 - lavfi 1.56.0 - avfilter_graph_free()
+  Rename avfilter_graph_destroy() to avfilter_graph_free().
+  This change breaks libavfilter API/ABI.
+
+2010-11-04 - r25673 - lavfi 1.55.0 - avfilter_graph_alloc()
+  Add avfilter_graph_alloc() to libavfilter/avfiltergraph.h.
+
+2010-11-02 - r25654 - lavcore 0.12.0 - av_get_bits_per_sample_fmt()
+  Add av_get_bits_per_sample_fmt() to libavcore/samplefmt.h and
+  deprecate av_get_bits_per_sample_format().
+
+2010-11-02 - r25653 - lavcore 0.11.0 - samplefmt.h
+  Add sample format functions in libavcore/samplefmt.h:
+  av_get_sample_fmt_name(),
+  av_get_sample_fmt(),
+  av_get_sample_fmt_string(),
+  and deprecate the corresponding libavcodec/audioconvert.h functions:
+  avcodec_get_sample_fmt_name(),
+  avcodec_get_sample_fmt(),
+  avcodec_sample_fmt_string().
+
+2010-11-02 - r25652 - lavcore 0.10.0 - samplefmt.h
+  Define enum AVSampleFormat in libavcore/samplefmt.h, deprecate enum
+  SampleFormat.
+
+2010-10-16 - r25502 - lavfi 1.52.0 - avfilter_graph_config()
+  Add the function avfilter_graph_config() in avfiltergraph.h.
+
+2010-10-15 - r25493 - lavf 52.83.0 - metadata API
+  Change demuxers to export metadata in generic format and
+  muxers to accept generic format. Deprecate the public
+  conversion API.
+
+2010-10-10 - r25441 - lavfi 1.49.0 - AVFilterLink.time_base
+  Add time_base field to AVFilterLink.
+
+2010-09-27 - r25236 - lavu 50.31.0 - av_set_options_string()
+  Move av_set_options_string() from libavfilter/parseutils.h to
+  libavutil/opt.h.
+
+2010-09-27 - r25227 - lavfi 1.47.0 - AVFilterLink
+  Make the AVFilterLink fields srcpad and dstpad store the pointers to
+  the source and destination pads, rather than their indexes.
+
+2010-09-27 - r25225 - lavu 50.30.0 - av_get_token()
+  Move av_get_token() from libavfilter/parseutils.h to
+  libavutil/avstring.h.
+
+2010-09-26 - r32368 - lsws 0.12.0 - swscale.h
+  Add the functions sws_alloc_context() and sws_init_context().
+
+2010-09-26 - r25210 - lavu 50.29.0 - opt.h
+  Move libavcodec/opt.h to libavutil/opt.h.
+
+2010-09-24 - r25174 - lavu 50.28.0 - av_log_set_flags()
+  Default of av_log() changed due to many problems to the old no repeat
+  detection. Read the docs of AV_LOG_SKIP_REPEATED in log.h before
+  enabling it for your app!.
+
+2010-09-24 - r25167 - lavc 52.90.0 - av_opt_show2()
+  Deprecate av_opt_show() in favor or av_opt_show2().
+
+2010-09-14 - r25120 - lavu 50.27.0 - av_popcount()
+  Add av_popcount() to libavutil/common.h.
+
+2010-09-08 - r25076 - lavu 50.26.0 - av_get_cpu_flags()
+  Add av_get_cpu_flags().
+
+2010-09-07 - r25067 - lavcore 0.9.0 - av_image_copy()
+  Add av_image_copy().
+
+2010-09-07 - r25064 - lavcore 0.8.0 - av_image_copy_plane()
+  Add av_image_copy_plane().
+
+2010-09-07 - r25057 - lavcore 0.7.0 - imgutils.h
+  Adopt hierarchical scheme for the imgutils.h function names,
+  deprecate the old names.
+
+2010-09-04 - r25040 - lavu 50.25.0 - AV_CPU_FLAG_*
+  Deprecate the FF_MM_* flags defined in libavcodec/avcodec.h in favor
+  of the AV_CPU_FLAG_* flags defined in libavutil/cpu.h.
+
+2010-08-26 - r24936 - lavc 52.87.0 - avcodec_get_channel_layout()
+  Add avcodec_get_channel_layout() in audioconvert.h.
+
+2010-08-20 - r24851 - lavcore 0.6.0 - av_fill_image_max_pixsteps()
+  Rename av_fill_image_max_pixstep() to av_fill_image_max_pixsteps().
+
+2010-08-18 - r24827 - lavcore 0.5.0 - av_fill_image_max_pixstep()
+  Add av_fill_image_max_pixstep() in imgutils.h.
+
+2010-08-17 - r24814 - lavu 50.24.0 - AV_NE()
+  Add the AV_NE macro.
+
+2010-08-17 - r24811 - lavfi 1.36.0 - audio framework
+  Implement AVFilterBufferRefAudioProps struct for audio properties,
+  get_audio_buffer(), filter_samples() functions and related changes.
+
+2010-08-12 - r24787 - lavcore 0.4.0 - av_get_image_linesize()
+  Add av_get_image_linesize() in imgutils.h.
+
+2010-08-11 - r24773 - lavfi 1.34.0 - AVFilterBufferRef
+  Resize data and linesize arrays in AVFilterBufferRef to 8.
+
+  This change breaks libavfilter API/ABI.
+
+2010-08-11 - r24768 - lavc 52.85.0 - av_picture_data_copy()
+  Add av_picture_data_copy in avcodec.h.
+
+2010-08-11 - r24765 - lavfi 1.33.0 - avfilter_open()
+  Change avfilter_open() signature:
+  AVFilterContext *avfilter_open(AVFilter *filter, const char *inst_name) ->
+  int avfilter_open(AVFilterContext **filter_ctx, AVFilter *filter, const char *inst_name);
+
+  This change breaks libavfilter API/ABI.
+
+2010-08-11 - r24763 - lavfi 1.32.0 - AVFilterBufferRef
+  Add a type field to AVFilterBufferRef, and move video specific
+  properties to AVFilterBufferRefVideoProps.
+
+  This change breaks libavfilter API/ABI.
+
+2010-08-07 - r24732 - lavfi 1.31.0 - AVFilterLink
+  Rename AVFilterLink fields:
+  AVFilterLink.srcpic    ->  AVFilterLink.src_buf
+  AVFilterLink.cur_pic   ->  AVFilterLink.cur_buf
+  AVFilterLink.outpic    ->  AVFilterLink.out_buf
+
+2010-08-07 - r24731 - lavfi 1.30.0
+  Rename functions and fields:
+  avfilter_(un)ref_pic       -> avfilter_(un)ref_buffer
+  avfilter_copy_picref_props -> avfilter_copy_buffer_ref_props
+  AVFilterBufferRef.pic      -> AVFilterBufferRef.buffer
+
+2010-08-07 - r24730 - lavfi 1.29.0 - AVFilterBufferRef
+  Rename AVFilterPicRef to AVFilterBufferRef.
+
+2010-08-07 - r24728 - lavfi 1.28.0 - AVFilterBuffer
+  Move format field from AVFilterBuffer to AVFilterPicRef.
+
+2010-08-06 - r24709 - lavcore 0.3.0 - av_check_image_size()
+  Deprecate avcodec_check_dimensions() in favor of the function
+  av_check_image_size() defined in libavcore/imgutils.h.
+
+2010-07-30 - r24592 - lavfi 1.27.0 - AVFilterBuffer
+  Increase size of the arrays AVFilterBuffer.data and
+  AVFilterBuffer.linesize from 4 to 8.
+
+  This change breaks libavfilter ABI.
+
+2010-07-29 - r24583 - lavcore 0.2.0 - imgutils.h
+  Add functions av_fill_image_linesizes() and
+  av_fill_image_pointers(), declared in libavcore/imgutils.h.
+
+2010-07-27 - r24518 - lavcore 0.1.0 - parseutils.h
+  Deprecate av_parse_video_frame_size() and av_parse_video_frame_rate()
+  defined in libavcodec in favor of the newly added functions
+  av_parse_video_size() and av_parse_video_rate() declared in
+  libavcore/parseutils.h.
+
+2010-07-23 - r24439 - lavu 50.23.0 - mathematics.h
+  Add the M_PHI constant definition.
+
+2010-07-22 - r24424 - lavfi 1.26.0 - media format generalization
+  Add a type field to AVFilterLink.
+
+  Change the field types:
+  enum PixelFormat format   -> int format   in AVFilterBuffer
+  enum PixelFormat *formats -> int *formats in AVFilterFormats
+  enum PixelFormat *format  -> int format   in AVFilterLink
+
+  Change the function signatures:
+  AVFilterFormats *avfilter_make_format_list(const enum PixelFormat *pix_fmts); ->
+  AVFilterFormats *avfilter_make_format_list(const int *fmts);
+
+  int avfilter_add_colorspace(AVFilterFormats **avff, enum PixelFormat pix_fmt); ->
+  int avfilter_add_format    (AVFilterFormats **avff, int fmt);
+
+  AVFilterFormats *avfilter_all_colorspaces(void); ->
+  AVFilterFormats *avfilter_all_formats    (enum AVMediaType type);
+
+  This change breaks libavfilter API/ABI.
+
+2010-07-21 - r24393 - lavcore 0.0.0
+  Add libavcore.
+
+2010-07-17 - r24291 - lavfi 1.25.0 - AVFilterBuffer
+  Remove w and h fields from AVFilterBuffer.
+
+2010-07-17 - r24284 - lavfi 1.24.0 - AVFilterBuffer
+  Rename AVFilterPic to AVFilterBuffer.
+
+2010-07-17 - r24278 - lavf 52.74.0 - url_fskip()
+  Make url_fskip() return an int error code instead of void.
+
+2010-07-11 - r24199 - lavc 52.83.0
+  Add AVCodecContext.lpc_type and AVCodecContext.lpc_passes fields.
+  Add AVLPCType enum.
+  Deprecate AVCodecContext.use_lpc.
+
+2010-07-11 - r24185 - lavc 52.82.0 - avsubtitle_free()
+  Add a function for free the contents of a AVSubtitle generated by
+  avcodec_decode_subtitle.
+
+2010-07-11 - r24174 - lavu 50.22.0 - bswap.h and intreadwrite.h
+  Make the bswap.h and intreadwrite.h API public.
+
+2010-07-08 - r24101 - lavu 50.21.0 - pixdesc.h
+  Rename read/write_line() to av_read/write_image_line().
+
+2010-07-07 - r24091 - lavfi 1.21.0 - avfilter_copy_picref_props()
+  Add avfilter_copy_picref_props().
+
+2010-07-03 - r24021 - lavc 52.79.0
+  Add FF_COMPLIANCE_UNOFFICIAL and change all instances of
+  FF_COMPLIANCE_INOFFICIAL to use FF_COMPLIANCE_UNOFFICIAL.
+
+2010-07-02 - r23985 - lavu 50.20.0 - lfg.h
+  Export av_lfg_init(), av_lfg_get(), av_mlfg_get(), and av_bmg_get() through
+  lfg.h.
+
+2010-06-28 - r23835 - lavfi 1.20.1 - av_parse_color()
+  Extend av_parse_color() syntax, make it accept an alpha value specifier and
+  set the alpha value to 255 by default.
+
+2010-06-22 - r23706 - lavf 52.71.0 - URLProtocol.priv_data_size, priv_data_class
+  Add priv_data_size and priv_data_class to URLProtocol.
+
+2010-06-22 - r23704 - lavf 52.70.0 - url_alloc(), url_connect()
+  Add url_alloc() and url_connect().
+
+2010-06-22 - r23702 - lavf 52.69.0 - av_register_protocol2()
+  Add av_register_protocol2(), deprecating av_register_protocol().
+
+2010-06-09 - r23551 - lavu 50.19.0 - av_compare_mod()
+  Add av_compare_mod() to libavutil/mathematics.h.
+
+2010-06-05 - r23485 - lavu 50.18.0 - eval API
+  Make the eval API public.
+
+2010-06-04 - r23461 - lavu 50.17.0 - AV_BASE64_SIZE
+  Add AV_BASE64_SIZE() macro.
+
+2010-06-02 - r23421 - lavc 52.73.0 - av_get_codec_tag_string()
+  Add av_get_codec_tag_string().
+
 2010-06-01 - r31301 - lsws 0.11.0 - convertPalette API
-  Add sws_convertPalette8ToPacked32 and sws_convertPalette8ToPacked24
+  Add sws_convertPalette8ToPacked32() and sws_convertPalette8ToPacked24().
 
 2010-05-26 - r23334 - lavc 52.72.0 - CODEC_CAP_EXPERIMENTAL
   Add CODEC_CAP_EXPERIMENTAL flag.
+  NOTE: this was backported to 0.6
+
+2010-05-23 - r23255 - lavu 50.16.0 - av_get_random_seed()
+  Add av_get_random_seed().
 
 2010-05-18 - r23161 - lavf 52.63.0 - AVFMT_FLAG_RTP_HINT
-  Add AVFMT_FLAG_RTP_HINT as possible value for AVFormatContext.flags
+  Add AVFMT_FLAG_RTP_HINT as possible value for AVFormatContext.flags.
+  NOTE: this was backported to 0.6
+
+2010-05-09 - r23066 - lavfi 1.20.0 - AVFilterPicRef
+  Add interlaced and top_field_first fields to AVFilterPicRef.
+
+------------------------------8<-------------------------------------
+                   0.6 branch was cut here
+----------------------------->8--------------------------------------
 
 2010-05-01 - r23002 - lavf 52.62.0 - probe function
   Add av_probe_input_format2 to API, it allows ignoring probe
@@ -30,7 +558,7 @@ API changes, most recent first:
   existing tags.
 
 2010-04-01 - r22753 - lavc 52.66.0
-  Add avcodec_get_edge_width()
+  Add avcodec_get_edge_width().
 
 2010-03-31 - r22750 - lavc 52.65.0
   Add avcodec_copy_context().
@@ -49,7 +577,7 @@ API changes, most recent first:
   Implement av_strerror().
 
 2010-03-23 - r22649 - lavc 52.60.0 - av_dct_init()
-  Support DCT-I and DST-I
+  Support DCT-I and DST-I.
 
 2010-03-15 - r22540 - lavf 52.56.0 - AVFormatContext.start_time_realtime
   Add AVFormatContext.start_time_realtime field.
@@ -83,13 +611,13 @@ API changes, most recent first:
 2010-01-30 - r21545 - lavu 50.8.0 - av_get_pix_fmt()
   Add av_get_pix_fmt().
 
-2010-01-21 - r30381 - lsws 0.9.0 - sws_scale
+2010-01-21 - r30381 - lsws 0.9.0 - sws_scale()
   Change constness attributes of sws_scale() parameters.
 
 2010-01-10 - r21121 - lavfi 1.15.0 - avfilter_graph_config_links()
   Add a log_ctx parameter to avfilter_graph_config_links().
 
-2010-01-07 - r30236 - lsws 0.8.0 - sws_isSupported{In,Out}put
+2010-01-07 - r30236 - lsws 0.8.0 - sws_isSupported{In,Out}put()
   Add sws_isSupportedInput() and sws_isSupportedOutput() functions.
 
 2010-01-06 - r21035 - lavfi 1.14.0 - avfilter_add_colorspace()
@@ -106,7 +634,8 @@ API changes, most recent first:
   Add av_guess_format(), it should be used in place of guess_format().
 
 2009-12-13 - r20834 - lavf 52.43.0 - metadata API
-  Add av_metadata_set2(), AV_METADATA_DONT_STRDUP_KEY and AV_METADATA_DONT_STRDUP_VAL.
+  Add av_metadata_set2(), AV_METADATA_DONT_STRDUP_KEY and
+  AV_METADATA_DONT_STRDUP_VAL.
 
 2009-12-13 - r20829 - lavu 50.7.0 - avstring.h API
   Add av_d2str().
@@ -172,10 +701,10 @@ API changes, most recent first:
   When the lock manager is registered, FFmpeg is guaranteed to behave
   correctly in a multi-threaded application.
 
-2009-04-30 - r18719 - lavc 52.28.0 - av_free_packet
+2009-04-30 - r18719 - lavc 52.28.0 - av_free_packet()
   av_free_packet() is no longer an inline function. It is now exported.
 
-2009-04-11 - r18431 - lavc 52.25.0 - deprecate av_destruct_packet_nofree
+2009-04-11 - r18431 - lavc 52.25.0 - deprecate av_destruct_packet_nofree()
   Please use NULL instead. This has been supported since r16506
   (lavf > 52.23.1, lavc > 52.10.0).
 
@@ -185,7 +714,7 @@ API changes, most recent first:
   avcodec_decode_subtitle2(). These new functions take an AVPacket *pkt
   argument instead of a const uint8_t *buf / int buf_size pair.
 
-2009-04-03 - r18321 - lavu 50.3.0 - av_fifo_space
+2009-04-03 - r18321 - lavu 50.3.0 - av_fifo_space()
   Introduce the av_fifo_space() function.
 
 2009-04-02 - r18317 - lavc 52.23.0 - AVPacket
diff --git a/doc/TODO b/doc/TODO
index f03270e..8ff8a6b 100644
--- a/doc/TODO
+++ b/doc/TODO
@@ -29,14 +29,6 @@ Michael's TODO list: (unordered) (if anyone wanna help with sth, just ask)
 - more optimizations
 - simper rate control
 
-Francois' TODO list: (unordered, without any timeframe)
--------------------
-- test MACE decoder against the openquicktime one as suggested by A'rpi
-- BeOS audio input grabbing backend
-- BeOS video input grabbing backend
-- publish my BeOS libposix on BeBits so I can officially support ffserver :)
-- check the whole code for thread-safety (global and init stuff)
-
 Philip'a TODO list: (alphabetically ordered) (please help)
 ------------------
 - Add a multi-ffm filetype so that feeds can be recorded into multiple files rather
@@ -77,7 +69,7 @@ unassigned TODO: (unordered)
 - JPEG2000 decoder & encoder
 - MPEG4 GMC encoding support
 - macroblock based pixel format (better cache locality, somewhat complex, one paper claimed it faster for high res)
-- regression tests for codecs which do not have an encoder (I+P-frame bitstream in svn)
+- regression tests for codecs which do not have an encoder (I+P-frame bitstream in the 'master' branch)
 - add support for using mplayers video filters to ffmpeg
 - H264 encoder
 - per MB ratecontrol (so VCD and such do work better)
diff --git a/doc/bitstream_filters.texi b/doc/bitstream_filters.texi
new file mode 100644
index 0000000..c33fca6
--- /dev/null
+++ b/doc/bitstream_filters.texi
@@ -0,0 +1,77 @@
+ at chapter Bitstream Filters
+ at c man begin BITSTREAM FILTERS
+
+When you configure your Libav build, all the supported bitstream
+filters are enabled by default. You can list all available ones using
+the configure option @code{--list-bsfs}.
+
+You can disable all the bitstream filters using the configure option
+ at code{--disable-bsfs}, and selectively enable any bitstream filter using
+the option @code{--enable-bsf=BSF}, or you can disable a particular
+bitstream filter using the option @code{--disable-bsf=BSF}.
+
+The option @code{-bsfs} of the ff* tools will display the list of
+all the supported bitstream filters included in your build.
+
+Below is a description of the currently available bitstream filters.
+
+ at section aac_adtstoasc
+
+ at section chomp
+
+ at section dump_extradata
+
+ at section h264_mp4toannexb
+
+ at section imx_dump_header
+
+ at section mjpeg2jpeg
+
+Convert MJPEG/AVI1 packets to full JPEG/JFIF packets.
+
+MJPEG is a video codec wherein each video frame is essentially a
+JPEG image. The individual frames can be extracted without loss,
+e.g. by
+
+ at example
+ffmpeg -i ../some_mjpeg.avi -vcodec copy frames_%d.jpg
+ at end example
+
+Unfortunately, these chunks are incomplete JPEG images, because
+they lack the DHT segment required for decoding. Quoting from
+ at url{http://www.digitalpreservation.gov/formats/fdd/fdd000063.shtml}:
+
+Avery Lee, writing in the rec.video.desktop newsgroup in 2001,
+commented that "MJPEG, or at least the MJPEG in AVIs having the
+MJPG fourcc, is restricted JPEG with a fixed -- and *omitted* --
+Huffman table. The JPEG must be YCbCr colorspace, it must be 4:2:2,
+and it must use basic Huffman encoding, not arithmetic or
+progressive. . . . You can indeed extract the MJPEG frames and
+decode them with a regular JPEG decoder, but you have to prepend
+the DHT segment to them, or else the decoder won't have any idea
+how to decompress the data. The exact table necessary is given in
+the OpenDML spec."
+
+This bitstream filter patches the header of frames extracted from an MJPEG
+stream (carrying the AVI1 header ID and lacking a DHT segment) to
+produce fully qualified JPEG images.
+
+ at example
+ffmpeg -i mjpeg-movie.avi -vcodec copy -vbsf mjpeg2jpeg frame_%d.jpg
+exiftran -i -9 frame*.jpg
+ffmpeg -i frame_%d.jpg -vcodec copy rotated.avi
+ at end example
+
+ at section mjpega_dump_header
+
+ at section movsub
+
+ at section mp3_header_compress
+
+ at section mp3_header_decompress
+
+ at section noise
+
+ at section remove_extradata
+
+ at c man end BITSTREAM FILTERS
diff --git a/doc/build_system.txt b/doc/build_system.txt
new file mode 100644
index 0000000..1011f57
--- /dev/null
+++ b/doc/build_system.txt
@@ -0,0 +1,30 @@
+Libav currently uses a custom build system, this text attempts to document
+some of its obscure features and options.
+
+Makefile variables:
+
+V
+    Disable the default terse mode, the full command issued by make and its
+    output will be shown on the screen.
+
+DESTDIR
+    Destination directory for the install targets, useful to prepare packages
+    or install Libav in cross-environments.
+
+Makefile targets:
+
+all
+    Default target, builds all the libraries and the executables.
+
+install
+    Install headers, libraries and programs.
+
+libavformat/output-example
+    Build the libavformat basic example.
+
+libavcodec/api-example
+    Build the libavcodec basic example.
+
+libswscale/swscale-test
+    Build the swscale self-test (useful also as example).
+
diff --git a/doc/demuxers.texi b/doc/demuxers.texi
new file mode 100644
index 0000000..bbdde9c
--- /dev/null
+++ b/doc/demuxers.texi
@@ -0,0 +1,67 @@
+ at chapter Demuxers
+ at c man begin DEMUXERS
+
+Demuxers are configured elements in Libav which allow to read the
+multimedia streams from a particular type of file.
+
+When you configure your Libav build, all the supported demuxers
+are enabled by default. You can list all available ones using the
+configure option "--list-demuxers".
+
+You can disable all the demuxers using the configure option
+"--disable-demuxers", and selectively enable a single demuxer with
+the option "--enable-demuxer=@var{DEMUXER}", or disable it
+with the option "--disable-demuxer=@var{DEMUXER}".
+
+The option "-formats" of the ff* tools will display the list of
+enabled demuxers.
+
+The description of some of the currently available demuxers follows.
+
+ at section image2
+
+Image file demuxer.
+
+This demuxer reads from a list of image files specified by a pattern.
+
+The pattern may contain the string "%d" or "%0 at var{N}d", which
+specifies the position of the characters representing a sequential
+number in each filename matched by the pattern. If the form
+"%d0 at var{N}d" is used, the string representing the number in each
+filename is 0-padded and @var{N} is the total number of 0-padded
+digits representing the number. The literal character '%' can be
+specified in the pattern with the string "%%".
+
+If the pattern contains "%d" or "%0 at var{N}d", the first filename of
+the file list specified by the pattern must contain a number
+inclusively contained between 0 and 4, all the following numbers must
+be sequential. This limitation may be hopefully fixed.
+
+The pattern may contain a suffix which is used to automatically
+determine the format of the images contained in the files.
+
+For example the pattern "img-%03d.bmp" will match a sequence of
+filenames of the form @file{img-001.bmp}, @file{img-002.bmp}, ...,
+ at file{img-010.bmp}, etc.; the pattern "i%%m%%g-%d.jpg" will match a
+sequence of filenames of the form @file{i%m%g-1.jpg},
+ at file{i%m%g-2.jpg}, ..., @file{i%m%g-10.jpg}, etc.
+
+The size, the pixel format, and the format of each image must be the
+same for all the files in the sequence.
+
+The following example shows how to use @file{ffmpeg} for creating a
+video from the images in the file sequence @file{img-001.jpeg},
+ at file{img-002.jpeg}, ..., assuming an input framerate of 10 frames per
+second:
+ at example
+ffmpeg -r 10 -f image2 -i 'img-%03d.jpeg' out.avi
+ at end example
+
+Note that the pattern must not necessarily contain "%d" or
+"%0 at var{N}d", for example to convert a single image file
+ at file{img.jpeg} you can employ the command:
+ at example
+ffmpeg -f image2 -i img.jpeg img.png
+ at end example
+
+ at c man end INPUT DEVICES
diff --git a/doc/developer.texi b/doc/developer.texi
index edce7ea..ab736d7 100644
--- a/doc/developer.texi
+++ b/doc/developer.texi
@@ -2,11 +2,12 @@
 
 @settitle Developer Documentation
 @titlepage
- at sp 7
 @center @titlefont{Developer Documentation}
- at sp 3
 @end titlepage
 
+ at top
+
+ at contents
 
 @chapter Developers Guide
 
@@ -22,21 +23,27 @@ audio or video streams.
 
 @end itemize
 
- at section Integrating libavcodec or libavformat in your program
+ at section Integrating libav in your program
 
-You can integrate all the source code of the libraries to link them
-statically to avoid any version problem. All you need is to provide a
-'config.mak' and a 'config.h' in the parent directory. See the defines
-generated by ./configure to understand what is needed.
+Shared libraries should be used whenever is possible in order to reduce
+the effort distributors have to pour to support programs and to ensure
+only the public api is used.
 
-You can use libavcodec or libavformat in your commercial program, but
- at emph{any patch you make must be published}. The best way to proceed is
-to send your patches to the FFmpeg mailing list.
+You can use Libav in your commercial program, but you must abide to the
+license, LGPL or GPL depending on the specific features used, please refer
+to @url{http://libav.org/legal.html} for a quick checklist and to
+ at url{http://git.libav.org/?p=libav.git;a=blob;f=COPYING.GPLv2},
+ at url{http://git.libav.org/?p=libav.git;a=blob;f=COPYING.GPLv3},
+ at url{http://git.libav.org/?p=libav.git;a=blob;f=COPYING.LGPLv2.1},
+ at url{http://git.libav.org/?p=libav.git;a=blob;f=COPYING.LGPLv3} for the
+exact text of the licenses.
+Any modification to the source code can be suggested for inclusion.
+The best way to proceed is to send your patches to the Libav mailing list.
 
 @anchor{Coding Rules}
 @section Coding Rules
 
-FFmpeg is programmed in the ISO C90 language with a few additional
+Libav is programmed in the ISO C90 language with a few additional
 features from ISO C99, namely:
 @itemize @bullet
 @item
@@ -53,7 +60,7 @@ These features are supported by all compilers we care about, so we will not
 accept patches to remove their use unless they absolutely do not impair
 clarity and performance.
 
-All code must compile with GCC 2.95 and GCC 3.3. Currently, FFmpeg also
+All code must compile with GCC 2.95 and GCC 3.3. Currently, Libav also
 compiles with several other compilers, such as the Compaq ccc compiler
 or Sun Studio 9, and we would like to keep it that way unless it would
 be exceedingly involved. To ensure compatibility, please do not use any
@@ -73,9 +80,9 @@ Indent size is 4.
 The presentation is one inspired by 'indent -i4 -kr -nut'.
 The TAB character is forbidden outside of Makefiles as is any
 form of trailing whitespace. Commits containing either will be
-rejected by the Subversion repository.
+rejected by the git repository.
 
-The main priority in FFmpeg is simplicity and small code size in order to
+The main priority in Libav is simplicity and small code size in order to
 minimize the bug count.
 
 Comments: Use the JavaDoc/Doxygen
@@ -128,17 +135,33 @@ should also be avoided if they don't make the code easier to understand.
    an "or any later version" clause is also acceptable, but LGPL is
    preferred.
 @item
-   You must not commit code which breaks FFmpeg! (Meaning unfinished but
-   enabled code which breaks compilation or compiles but does not work or
-   breaks the regression tests)
-   You can commit unfinished stuff (for testing etc), but it must be disabled
-   (#ifdef etc) by default so it does not interfere with other developers'
-   work.
+   All the patches MUST be reviewed in the mailing list before they are
+   committed.
+ at item
+   The Libav coding style should remain consistent. Changes to
+   conform will be suggested during the review or implemented on commit.
+ at item
+   Patches should be generated using @code{git format-patch} or directly sent
+   using @code{git send-email}.
+   Please make sure you give the proper credit by setting the correct author
+   in the commit.
+ at item
+   The commit message should have a short first line in the form of
+   @samp{topic: short description} as header, separated by a newline
+   from the body consting in few lines explaining the reason of the patch.
+   Referring to the issue on the bug tracker does not exempt to report an
+   excerpt of the bug.
 @item
-   You do not have to over-test things. If it works for you, and you think it
-   should work for others, then commit. If your code has problems
-   (portability, triggers compiler bugs, unusual environment etc) they will be
-   reported and eventually fixed.
+   Work in progress patches should be sent to the mailing list with the [WIP]
+   or the [RFC] tag.
+ at item
+   Branches in public personal repos are advised as way to
+   work on issues collaboratively.
+ at item
+   You do not have to over-test things. If it works for you and you think it
+   should work for others, send it to the mailing list for review.
+   If you have doubt about portability please state it in the submission so
+   people with specific hardware could test it.
 @item
    Do not commit unrelated changes together, split them into self-contained
    pieces. Also do not forget that if part B depends on part A, but A does not
@@ -146,70 +169,32 @@ should also be avoided if they don't make the code easier to understand.
    Keeping changes well split into self-contained parts makes reviewing and
    understanding them on the commit log mailing list easier. This also helps
    in case of debugging later on.
-   Also if you have doubts about splitting or not splitting, do not hesitate to
-   ask/discuss it on the developer mailing list.
- at item
-   Do not change behavior of the program (renaming options etc) without
-   first discussing it on the ffmpeg-devel mailing list. Do not remove
-   functionality from the code. Just improve!
-
-   Note: Redundant code can be removed.
- at item
-   Do not commit changes to the build system (Makefiles, configure script)
-   which change behavior, defaults etc, without asking first. The same
-   applies to compiler warning fixes, trivial looking fixes and to code
-   maintained by other developers. We usually have a reason for doing things
-   the way we do. Send your changes as patches to the ffmpeg-devel mailing
-   list, and if the code maintainers say OK, you may commit. This does not
-   apply to files you wrote and/or maintain.
- at item
-   We refuse source indentation and other cosmetic changes if they are mixed
-   with functional changes, such commits will be rejected and removed. Every
-   developer has his own indentation style, you should not change it. Of course
-   if you (re)write something, you can use your own style, even though we would
-   prefer if the indentation throughout FFmpeg was consistent (Many projects
-   force a given indentation style - we do not.). If you really need to make
-   indentation changes (try to avoid this), separate them strictly from real
-   changes.
-
-   NOTE: If you had to put if()@{ .. @} over a large (> 5 lines) chunk of code,
-   then either do NOT change the indentation of the inner part within (do not
-   move it to the right)! or do so in a separate commit
- at item
-   Always fill out the commit log message. Describe in a few lines what you
-   changed and why. You can refer to mailing list postings if you fix a
-   particular bug. Comments such as "fixed!" or "Changed it." are unacceptable.
- at item
-   If you apply a patch by someone else, include the name and email address in
-   the log message. Since the ffmpeg-cvslog mailing list is publicly
-   archived you should add some SPAM protection to the email address. Send an
-   answer to ffmpeg-devel (or wherever you got the patch from) saying that
-   you applied the patch.
+ at item
+   Patches that change behavior of the programs (renaming options etc) or
+   public API or ABI should be discussed in depth and possible few days should
+   pass between discussion and commit.
+   Changes to the build system (Makefiles, configure script) which alter
+   the expected behavior should be considered in the same regard.
 @item
    When applying patches that have been discussed (at length) on the mailing
    list, reference the thread in the log message.
 @item
-    Do NOT commit to code actively maintained by others without permission.
-    Send a patch to ffmpeg-devel instead. If no one answers within a reasonable
-    timeframe (12h for build failures and security fixes, 3 days small changes,
-    1 week for big patches) then commit your patch if you think it is OK.
-    Also note, the maintainer can simply ask for more time to review!
- at item
-    Subscribe to the ffmpeg-cvslog mailing list. The diffs of all commits
-    are sent there and reviewed by all the other developers. Bugs and possible
-    improvements or general questions regarding commits are discussed there. We
-    expect you to react if problems with your code are uncovered.
+    Subscribe to the libav-devel and libav-commits mailing list.
+    Bugs and possible improvements or general questions regarding commits
+    are discussed on libav-devel. We expect you to react if problems with
+    your code are uncovered.
 @item
     Update the documentation if you change behavior or add features. If you are
-    unsure how best to do this, send a patch to ffmpeg-devel, the documentation
-    maintainer(s) will review and commit your stuff.
+    unsure how best to do this, send an [RFC] patch to libav-devel.
 @item
-    Try to keep important discussions and requests (also) on the public
-    developer mailing list, so that all developers can benefit from them.
+    All discussions and decisions should be reported on the public developer
+    mailing list, so that there is a reference to them.
+    Other media (e.g. IRC) should be used for coordination and immediate
+    collaboration.
 @item
     Never write to unallocated memory, never write over the end of arrays,
     always check values read from some untrusted source before using them
-    as array index or other risky things.
+    as array index or other risky things. Always use valgrind to doublecheck.
 @item
     Remember to check if you need to bump versions for the specific libav
     parts (libavutil, libavcodec, libavformat) you are changing. You need
@@ -222,13 +207,12 @@ should also be avoided if they don't make the code easier to understand.
     Incrementing the third component means a noteworthy binary compatible
     change (e.g. encoder bug fix that matters for the decoder).
 @item
-    Compiler warnings indicate potential bugs or code with bad style. If a type of
-    warning always points to correct and clean code, that warning should
-    be disabled, not the code changed.
-    Thus the remaining warnings can either be bugs or correct code.
+    Compiler warnings indicate potential bugs or code with bad style.
     If it is a bug, the bug has to be fixed. If it is not, the code should
     be changed to not generate a warning unless that causes a slowdown
     or obfuscates the code.
+    If a type of warning leads to too many false positives, that warning
+    should be disabled, not the code changed.
 @item
     If you add a new file, give it a proper license header. Do not copy and
     paste it from a random place, use an existing file as template.
@@ -236,45 +220,48 @@ should also be avoided if they don't make the code easier to understand.
 
 We think our rules are not too hard. If you have comments, contact us.
 
-Note, these rules are mostly borrowed from the MPlayer project.
+Note, some rules were borrowed from the MPlayer project.
 
 @section Submitting patches
 
-First, (@pxref{Coding Rules}) above if you did not yet.
+First, read the (@pxref{Coding Rules}) above if you did not yet, in particular
+the rules regarding patch submission.
 
-When you submit your patch, try to send a unified diff (diff '-up'
-option). We cannot read other diffs :-)
-
-Also please do not submit a patch which contains several unrelated changes.
+As stated already, please do not submit a patch which contains several
+unrelated changes.
 Split it into separate, self-contained pieces. This does not mean splitting
 file by file. Instead, make the patch as small as possible while still
 keeping it as a logical unit that contains an individual change, even
 if it spans multiple files. This makes reviewing your patches much easier
 for us and greatly increases your chances of getting your patch applied.
 
-Use the patcheck tool of FFmpeg to check your patch.
+Use the patcheck tool of Libav to check your patch.
 The tool is located in the tools directory.
 
-Run the regression tests before submitting a patch so that you can
-verify that there are no big problems.
+Run the @pxref{Regression Tests} before submitting a patch in order to verify
+it does not cause unexpected problems.
 
 Patches should be posted as base64 encoded attachments (or any other
 encoding which ensures that the patch will not be trashed during
-transmission) to the ffmpeg-devel mailing list, see
- at url{http://lists.mplayerhq.hu/mailman/listinfo/ffmpeg-devel}
+transmission) to the libav-devel mailing list, see
+ at url{https://lists.libav.org/mailman/listinfo/libav-devel}
 
 It also helps quite a bit if you tell us what the patch does (for example
 'replaces lrint by lrintf'), and why (for example '*BSD isn't C99 compliant
-and has no lrint()')
+and has no lrint()'). This kind of explanation should be the body of the
+commit message.
 
 Also please if you send several patches, send each patch as a separate mail,
 do not attach several unrelated patches to the same mail.
 
+Use @code{git send-email} when possible since it will properly send patches
+without requiring extra care.
+
 Your patch will be reviewed on the mailing list. You will likely be asked
 to make some changes and are expected to send in an improved version that
 incorporates the requests from the review. This process may go through
-several iterations. Once your patch is deemed good enough, some developer
-will pick it up and commit it to the official FFmpeg tree.
+several iterations. Once your patch is deemed good enough, it will be
+committed to the official Libav tree.
 
 Give us a few days to react. But if some time passes without reaction,
 send a reminder by email. Your patch should eventually be dealt with.
@@ -289,8 +276,8 @@ send a reminder by email. Your patch should eventually be dealt with.
     Did you add a long_name under NULL_IF_CONFIG_SMALL to the AVCodec or
     AVInputFormat/AVOutputFormat struct?
 @item
-    Did you bump the minor version number in @file{avcodec.h} or
-    @file{avformat.h}?
+    Did you bump the minor version number (and reset the micro version
+    number) in @file{avcodec.h} or @file{avformat.h}?
 @item
     Did you register it in @file{allcodecs.c} or @file{allformats.c}?
 @item
@@ -300,8 +287,8 @@ send a reminder by email. Your patch should eventually be dealt with.
     even if it is only a decoder?
 @item
     Did you add a rule to compile the appropriate files in the Makefile?
-    Remember to do this even if you're just adding a format to a file that is
-    already being compiled by some other rule, like a raw demuxer.
+    Remember to do this even if you are just adding a format to a file that
+    is already being compiled by some other rule, like a raw demuxer.
 @item
     Did you add an entry to the table of supported formats or codecs in
     @file{doc/general.texi}?
@@ -311,7 +298,7 @@ send a reminder by email. Your patch should eventually be dealt with.
     If it depends on a parser or a library, did you add that dependency in
     configure?
 @item
-    Did you "svn add" the appropriate files before commiting?
+    Did you @code{git add} the appropriate files before committing?
 @end enumerate
 
 @section patch submission checklist
@@ -322,12 +309,11 @@ send a reminder by email. Your patch should eventually be dealt with.
 @item
     Does @code{make checkheaders} pass with the patch applied?
 @item
-    Is the patch a unified diff?
+    Is the patch against latest Libav git master branch?
 @item
-    Is the patch against latest FFmpeg SVN?
- at item
-    Are you subscribed to ffmpeg-dev?
-    (the list is subscribers only due to spam)
+    Are you subscribed to libav-devel?
+    (@url{https://lists.libav.org/mailman/listinfo/libav-devel}
+     the list is subscribers)
 @item
     Have you checked that the changes are minimal, so that the same cannot be
     achieved with a smaller patch and/or simpler final code?
@@ -343,9 +329,6 @@ send a reminder by email. Your patch should eventually be dealt with.
     tools/trasher and the noise bitstream filter. Your decoder or demuxer
     should not crash or end in a (near) infinite loop when fed damaged data.
 @item
-    Is the patch created from the root of the source tree, so it can be
-    applied with @code{patch -p0}?
- at item
     Does the patch not mix functional and cosmetic changes?
 @item
     Did you add tabs or trailing whitespace to the code? Both are forbidden.
@@ -360,7 +343,7 @@ send a reminder by email. Your patch should eventually be dealt with.
     If the patch fixes a bug, did you provide enough information, including
     a sample, so the bug can be reproduced and the fix can be verified?
     Note please do not attach samples >100k to mails but rather provide a
-    URL, you can upload to ftp://upload.ffmpeg.org
+    URL, you can upload to ftp://upload.libav.org
 @item
     Did you provide a verbose summary about what the patch does change?
 @item
@@ -373,21 +356,19 @@ send a reminder by email. Your patch should eventually be dealt with.
     patch easily?
 @item
     If you added a new file, did you insert a license header? It should be
-    taken from FFmpeg, not randomly copied and pasted from somewhere else.
+    taken from Libav, not randomly copied and pasted from somewhere else.
 @item
     You should maintain alphabetical order in alphabetically ordered lists as
     long as doing so does not break API/ABI compatibility.
 @item
     Lines with similar content should be aligned vertically when doing so
     improves readability.
- at item
-    Did you provide a suggestion for a clear commit log message?
 @end enumerate
 
 @section Patch review process
 
-All patches posted to ffmpeg-devel will be reviewed, unless they contain a
-clear note that the patch is not for SVN.
+All patches posted to libav-devel will be reviewed, unless they contain a
+clear note that the patch is not for the git master branch.
 Reviews and comments will be posted as replies to the patch on the
 mailing list. The patch submitter then has to take care of every comment,
 that can be by resubmitting a changed patch or by discussion. Resubmitted
@@ -400,37 +381,22 @@ After a patch is approved it will be committed to the repository.
 We will review all submitted patches, but sometimes we are quite busy so
 especially for large patches this can take several weeks.
 
-When resubmitting patches, please do not make any significant changes
-not related to the comments received during review. Such patches will
-be rejected. Instead, submit  significant changes or new features as
-separate patches.
-
- at section Regression tests
-
-Before submitting a patch (or committing to the repository), you should at least
-test that you did not break anything.
+When resubmitting patches, if their size grew or during the review different
+issues arisen please split the patch so each issue has a specific patch.
 
-The regression tests build a synthetic video stream and a synthetic
-audio stream. These are then encoded and decoded with all codecs or
-formats. The CRC (or MD5) of each generated file is recorded in a
-result file. A 'diff' is launched to compare the reference results and
-the result file. The output is checked immediately after each test
-has run.
+ at anchor{Regression Tests}
+ at section Regression Tests
 
-The regression tests then go on to test the FFserver code with a
-limited set of streams. It is important that this step runs correctly
-as well.
+Before submitting a patch (or committing to the repository), you should at
+least make sure that it does not break anything.
 
-Run 'make test' to test all the codecs and formats. Commands like
-'make regtest-mpeg2' can be used to run a single test. By default,
-make will abort if any test fails. To run all tests regardless,
-use make -k. To get a more verbose output, use 'make V=1 test' or
-'make V=2 test'.
+If the code changed has already a test present in FATE you should run it,
+otherwise it is advised to add it.
 
-Run 'make fulltest' to test all the codecs, formats and FFserver.
+Improvements to codec or demuxer might change the FATE results. Make sure
+to commit the update reference with the change and to explain in the comment
+why the expected result changed.
 
-[Of course, some patches may change the results of the regression tests. In
-this case, the reference results of the regression tests shall be modified
-accordingly].
+Please refer to @file{doc/fate.txt}.
 
 @bye
diff --git a/doc/encoders.texi b/doc/encoders.texi
new file mode 100644
index 0000000..59337e2
--- /dev/null
+++ b/doc/encoders.texi
@@ -0,0 +1,356 @@
+ at chapter Encoders
+ at c man begin ENCODERS
+
+Encoders are configured elements in Libav which allow the encoding of
+multimedia streams.
+
+When you configure your Libav build, all the supported native encoders
+are enabled by default. Encoders requiring an external library must be enabled
+manually via the corresponding @code{--enable-lib} option. You can list all
+available encoders using the configure option @code{--list-encoders}.
+
+You can disable all the encoders with the configure option
+ at code{--disable-encoders} and selectively enable / disable single encoders
+with the options @code{--enable-encoder=@var{ENCODER}} /
+ at code{--disable-encoder=@var{ENCODER}}.
+
+The option @code{-codecs} of the ff* tools will display the list of
+enabled encoders.
+
+A description of some of the currently available encoders follows.
+
+ at section Audio Encoders
+
+ at subsection ac3 and ac3_fixed
+
+AC-3 audio encoders.
+
+These encoders implement part of ATSC A/52:2010 and ETSI TS 102 366, as well as
+the undocumented RealAudio 3 (a.k.a. dnet).
+
+The @var{ac3} encoder uses floating-point math, while the @var{ac3_fixed}
+encoder only uses fixed-point integer math. This does not mean that one is
+always faster, just that one or the other may be better suited to a
+particular system. The floating-point encoder will generally produce better
+quality audio for a given bitrate. The @var{ac3_fixed} encoder is not the
+default codec for any of the output formats, so it must be specified explicitly
+using the option @code{-acodec ac3_fixed} in order to use it.
+
+ at subheading AC-3 Metadata
+
+The AC-3 metadata options are used to set parameters that describe the audio,
+but in most cases do not affect the audio encoding itself. Some of the options
+do directly affect or influence the decoding and playback of the resulting
+bitstream, while others are just for informational purposes. A few of the
+options will add bits to the output stream that could otherwise be used for
+audio data, and will thus affect the quality of the output. Those will be
+indicated accordingly with a note in the option list below.
+
+These parameters are described in detail in several publicly-available
+documents.
+ at itemize
+ at item @uref{http://www.atsc.org/cms/standards/a_52-2010.pdf,A/52:2010 - Digital Audio Compression (AC-3) (E-AC-3) Standard}
+ at item @uref{http://www.atsc.org/cms/standards/a_54a_with_corr_1.pdf,A/54 - Guide to the Use of the ATSC Digital Television Standard}
+ at item @uref{http://www.dolby.com/uploadedFiles/zz-_Shared_Assets/English_PDFs/Professional/18_Metadata.Guide.pdf,Dolby Metadata Guide}
+ at item @uref{http://www.dolby.com/uploadedFiles/zz-_Shared_Assets/English_PDFs/Professional/46_DDEncodingGuidelines.pdf,Dolby Digital Professional Encoding Guidelines}
+ at end itemize
+
+ at subsubheading Metadata Control Options
+
+ at table @option
+
+ at item -per_frame_metadata @var{boolean}
+Allow Per-Frame Metadata. Specifies if the encoder should check for changing
+metadata for each frame.
+ at table @option
+ at item 0
+The metadata values set at initialization will be used for every frame in the
+stream. (default)
+ at item 1
+Metadata values can be changed before encoding each frame.
+ at end table
+
+ at end table
+
+ at subsubheading Downmix Levels
+
+ at table @option
+
+ at item -center_mixlev @var{level}
+Center Mix Level. The amount of gain the decoder should apply to the center
+channel when downmixing to stereo. This field will only be written to the
+bitstream if a center channel is present. The value is specified as a scale
+factor. There are 3 valid values:
+ at table @option
+ at item 0.707
+Apply -3dB gain
+ at item 0.595
+Apply -4.5dB gain (default)
+ at item 0.500
+Apply -6dB gain
+ at end table
+
+ at item -surround_mixlev @var{level}
+Surround Mix Level. The amount of gain the decoder should apply to the surround
+channel(s) when downmixing to stereo. This field will only be written to the
+bitstream if one or more surround channels are present. The value is specified
+as a scale factor.  There are 3 valid values:
+ at table @option
+ at item 0.707
+Apply -3dB gain
+ at item 0.500
+Apply -6dB gain (default)
+ at item 0.000
+Silence Surround Channel(s)
+ at end table
+
+ at end table
+
+ at subsubheading Audio Production Information
+Audio Production Information is optional information describing the mixing
+environment.  Either none or both of the fields are written to the bitstream.
+
+ at table @option
+
+ at item -mixing_level @var{number}
+Mixing Level. Specifies peak sound pressure level (SPL) in the production
+environment when the mix was mastered. Valid values are 80 to 111, or -1 for
+unknown or not indicated. The default value is -1, but that value cannot be
+used if the Audio Production Information is written to the bitstream. Therefore,
+if the @code{room_type} option is not the default value, the @code{mixing_level}
+option must not be -1.
+
+ at item -room_type @var{type}
+Room Type. Describes the equalization used during the final mixing session at
+the studio or on the dubbing stage. A large room is a dubbing stage with the
+industry standard X-curve equalization; a small room has flat equalization.
+This field will not be written to the bitstream if both the @code{mixing_level}
+option and the @code{room_type} option have the default values.
+ at table @option
+ at item 0
+ at itemx notindicated
+Not Indicated (default)
+ at item 1
+ at itemx large
+Large Room
+ at item 2
+ at itemx small
+Small Room
+ at end table
+
+ at end table
+
+ at subsubheading Other Metadata Options
+
+ at table @option
+
+ at item -copyright @var{boolean}
+Copyright Indicator. Specifies whether a copyright exists for this audio.
+ at table @option
+ at item 0
+ at itemx off
+No Copyright Exists (default)
+ at item 1
+ at itemx on
+Copyright Exists
+ at end table
+
+ at item -dialnorm @var{value}
+Dialogue Normalization. Indicates how far the average dialogue level of the
+program is below digital 100% full scale (0 dBFS). This parameter determines a
+level shift during audio reproduction that sets the average volume of the
+dialogue to a preset level. The goal is to match volume level between program
+sources. A value of -31dB will result in no volume level change, relative to
+the source volume, during audio reproduction. Valid values are whole numbers in
+the range -31 to -1, with -31 being the default.
+
+ at item -dsur_mode @var{mode}
+Dolby Surround Mode. Specifies whether the stereo signal uses Dolby Surround
+(Pro Logic). This field will only be written to the bitstream if the audio
+stream is stereo. Using this option does @b{NOT} mean the encoder will actually
+apply Dolby Surround processing.
+ at table @option
+ at item 0
+ at itemx notindicated
+Not Indicated (default)
+ at item 1
+ at itemx off
+Not Dolby Surround Encoded
+ at item 2
+ at itemx on
+Dolby Surround Encoded
+ at end table
+
+ at item -original @var{boolean}
+Original Bit Stream Indicator. Specifies whether this audio is from the
+original source and not a copy.
+ at table @option
+ at item 0
+ at itemx off
+Not Original Source
+ at item 1
+ at itemx on
+Original Source (default)
+ at end table
+
+ at end table
+
+ at subsubheading Extended Bitstream Information
+The extended bitstream options are part of the Alternate Bit Stream Syntax as
+specified in Annex D of the A/52:2010 standard. It is grouped into 2 parts.
+If any one parameter in a group is specified, all values in that group will be
+written to the bitstream.  Default values are used for those that are written
+but have not been specified.  If the mixing levels are written, the decoder
+will use these values instead of the ones specified in the @code{center_mixlev}
+and @code{surround_mixlev} options if it supports the Alternate Bit Stream
+Syntax.
+
+ at subsubheading Extended Bitstream Information - Part 1
+
+ at table @option
+
+ at item -dmix_mode @var{mode}
+Preferred Stereo Downmix Mode. Allows the user to select either Lt/Rt
+(Dolby Surround) or Lo/Ro (normal stereo) as the preferred stereo downmix mode.
+ at table @option
+ at item 0
+ at itemx notindicated
+Not Indicated (default)
+ at item 1
+ at itemx ltrt
+Lt/Rt Downmix Preferred
+ at item 2
+ at itemx loro
+Lo/Ro Downmix Preferred
+ at end table
+
+ at item -ltrt_cmixlev @var{level}
+Lt/Rt Center Mix Level. The amount of gain the decoder should apply to the
+center channel when downmixing to stereo in Lt/Rt mode.
+ at table @option
+ at item 1.414
+Apply +3dB gain
+ at item 1.189
+Apply +1.5dB gain
+ at item 1.000
+Apply 0dB gain
+ at item 0.841
+Apply -1.5dB gain
+ at item 0.707
+Apply -3.0dB gain
+ at item 0.595
+Apply -4.5dB gain (default)
+ at item 0.500
+Apply -6.0dB gain
+ at item 0.000
+Silence Center Channel
+ at end table
+
+ at item -ltrt_surmixlev @var{level}
+Lt/Rt Surround Mix Level. The amount of gain the decoder should apply to the
+surround channel(s) when downmixing to stereo in Lt/Rt mode.
+ at table @option
+ at item 0.841
+Apply -1.5dB gain
+ at item 0.707
+Apply -3.0dB gain
+ at item 0.595
+Apply -4.5dB gain
+ at item 0.500
+Apply -6.0dB gain (default)
+ at item 0.000
+Silence Surround Channel(s)
+ at end table
+
+ at item -loro_cmixlev @var{level}
+Lo/Ro Center Mix Level. The amount of gain the decoder should apply to the
+center channel when downmixing to stereo in Lo/Ro mode.
+ at table @option
+ at item 1.414
+Apply +3dB gain
+ at item 1.189
+Apply +1.5dB gain
+ at item 1.000
+Apply 0dB gain
+ at item 0.841
+Apply -1.5dB gain
+ at item 0.707
+Apply -3.0dB gain
+ at item 0.595
+Apply -4.5dB gain (default)
+ at item 0.500
+Apply -6.0dB gain
+ at item 0.000
+Silence Center Channel
+ at end table
+
+ at item -loro_surmixlev @var{level}
+Lo/Ro Surround Mix Level. The amount of gain the decoder should apply to the
+surround channel(s) when downmixing to stereo in Lo/Ro mode.
+ at table @option
+ at item 0.841
+Apply -1.5dB gain
+ at item 0.707
+Apply -3.0dB gain
+ at item 0.595
+Apply -4.5dB gain
+ at item 0.500
+Apply -6.0dB gain (default)
+ at item 0.000
+Silence Surround Channel(s)
+ at end table
+
+ at end table
+
+ at subsubheading Extended Bitstream Information - Part 2
+
+ at table @option
+
+ at item -dsurex_mode @var{mode}
+Dolby Surround EX Mode. Indicates whether the stream uses Dolby Surround EX
+(7.1 matrixed to 5.1). Using this option does @b{NOT} mean the encoder will actually
+apply Dolby Surround EX processing.
+ at table @option
+ at item 0
+ at itemx notindicated
+Not Indicated (default)
+ at item 1
+ at itemx on
+Dolby Surround EX On
+ at item 2
+ at itemx off
+Dolby Surround EX Off
+ at end table
+
+ at item -dheadphone_mode @var{mode}
+Dolby Headphone Mode. Indicates whether the stream uses Dolby Headphone
+encoding (multi-channel matrixed to 2.0 for use with headphones). Using this
+option does @b{NOT} mean the encoder will actually apply Dolby Headphone
+processing.
+ at table @option
+ at item 0
+ at itemx notindicated
+Not Indicated (default)
+ at item 1
+ at itemx on
+Dolby Headphone On
+ at item 2
+ at itemx off
+Dolby Headphone Off
+ at end table
+
+ at item -ad_conv_type @var{type}
+A/D Converter Type. Indicates whether the audio has passed through HDCD A/D
+conversion.
+ at table @option
+ at item 0
+ at itemx standard
+Standard A/D Converter (default)
+ at item 1
+ at itemx hdcd
+HDCD A/D Converter
+ at end table
+
+ at end table
+
+ at c man end ENCODERS
diff --git a/doc/eval.texi b/doc/eval.texi
new file mode 100644
index 0000000..d8c693f
--- /dev/null
+++ b/doc/eval.texi
@@ -0,0 +1,152 @@
+ at chapter Expression Evaluation
+ at c man begin EXPRESSION EVALUATION
+
+When evaluating an arithemetic expression, Libav uses an internal
+formula evaluator, implemented through the @file{libavutil/eval.h}
+interface.
+
+An expression may contain unary, binary operators, constants, and
+functions.
+
+Two expressions @var{expr1} and @var{expr2} can be combined to form
+another expression "@var{expr1};@var{expr2}".
+ at var{expr1} and @var{expr2} are evaluated in turn, and the new
+expression evaluates to the value of @var{expr2}.
+
+The following binary operators are available: @code{+}, @code{-},
+ at code{*}, @code{/}, @code{^}.
+
+The following unary operators are available: @code{+}, @code{-}.
+
+The following functions are available:
+ at table @option
+ at item sinh(x)
+ at item cosh(x)
+ at item tanh(x)
+ at item sin(x)
+ at item cos(x)
+ at item tan(x)
+ at item atan(x)
+ at item asin(x)
+ at item acos(x)
+ at item exp(x)
+ at item log(x)
+ at item abs(x)
+ at item squish(x)
+ at item gauss(x)
+ at item isnan(x)
+Return 1.0 if @var{x} is NAN, 0.0 otherwise.
+
+ at item mod(x, y)
+ at item max(x, y)
+ at item min(x, y)
+ at item eq(x, y)
+ at item gte(x, y)
+ at item gt(x, y)
+ at item lte(x, y)
+ at item lt(x, y)
+ at item st(var, expr)
+Allow to store the value of the expression @var{expr} in an internal
+variable. @var{var} specifies the number of the variable where to
+store the value, and it is a value ranging from 0 to 9. The function
+returns the value stored in the internal variable.
+
+ at item ld(var)
+Allow to load the value of the internal variable with number
+ at var{var}, which was previosly stored with st(@var{var}, @var{expr}).
+The function returns the loaded value.
+
+ at item while(cond, expr)
+Evaluate expression @var{expr} while the expression @var{cond} is
+non-zero, and returns the value of the last @var{expr} evaluation, or
+NAN if @var{cond} was always false.
+
+ at item ceil(expr)
+Round the value of expression @var{expr} upwards to the nearest
+integer. For example, "ceil(1.5)" is "2.0".
+
+ at item floor(expr)
+Round the value of expression @var{expr} downwards to the nearest
+integer. For example, "floor(-1.5)" is "-2.0".
+
+ at item trunc(expr)
+Round the value of expression @var{expr} towards zero to the nearest
+integer. For example, "trunc(-1.5)" is "-1.0".
+ at end table
+
+Note that:
+
+ at code{*} works like AND
+
+ at code{+} works like OR
+
+thus
+ at example
+if A then B else C
+ at end example
+is equivalent to
+ at example
+A*B + not(A)*C
+ at end example
+
+When A evaluates to either 1 or 0, that is the same as
+ at example
+A*B + eq(A,0)*C
+ at end example
+
+In your C code, you can extend the list of unary and binary functions,
+and define recognized constants, so that they are available for your
+expressions.
+
+The evaluator also recognizes the International System number
+postfixes. If 'i' is appended after the postfix, powers of 2 are used
+instead of powers of 10. The 'B' postfix multiplies the value for 8,
+and can be appended after another postfix or used alone. This allows
+using for example 'KB', 'MiB', 'G' and 'B' as postfix.
+
+Follows the list of available International System postfixes, with
+indication of the corresponding powers of 10 and of 2.
+ at table @option
+ at item y
+-24 / -80
+ at item z
+-21 / -70
+ at item a
+-18 / -60
+ at item f
+-15 / -50
+ at item p
+-12 / -40
+ at item n
+-9 / -30
+ at item u
+-6 / -20
+ at item m
+-3 / -10
+ at item c
+-2
+ at item d
+-1
+ at item h
+2
+ at item k
+3 / 10
+ at item K
+3 / 10
+ at item M
+6 / 20
+ at item G
+9 / 30
+ at item T
+12 / 40
+ at item P
+15 / 40
+ at item E
+18 / 50
+ at item Z
+21 / 60
+ at item Y
+24 / 70
+ at end table
+
+ at c man end
diff --git a/doc/faq.texi b/doc/faq.texi
index ec01b9e..a29af1e 100644
--- a/doc/faq.texi
+++ b/doc/faq.texi
@@ -1,51 +1,53 @@
 \input texinfo @c -*- texinfo -*-
 
- at settitle FFmpeg FAQ
+ at settitle Libav FAQ
 @titlepage
- at sp 7
- at center @titlefont{FFmpeg FAQ}
- at sp 3
+ at center @titlefont{Libav FAQ}
 @end titlepage
 
+ at top
+
+ at contents
 
 @chapter General Questions
 
- at section When will the next FFmpeg version be released? / Why are FFmpeg releases so few and far between?
+ at section When will the next Libav version be released? / Why are Libav releases so few and far between?
 
-Like most open source projects FFmpeg suffers from a certain lack of
+Like most open source projects Libav suffers from a certain lack of
 manpower. For this reason the developers have to prioritize the work
 they do and putting out releases is not at the top of the list, fixing
 bugs and reviewing patches takes precedence. Please don't complain or
 request more timely and/or frequent releases unless you are willing to
 help out creating them.
 
- at section I have a problem with an old version of FFmpeg; where should I report it?
-Nowhere. Upgrade to the latest release or if there is no recent release upgrade
-to Subversion HEAD. You could also try to report it. Maybe you will get lucky and
-become the first person in history to get an answer different from "upgrade
-to Subversion HEAD".
+ at section I have a problem with an old version of Libav; where should I report it?
+Nowhere. We do not support old Libav versions in any way, we simply lack
+the time, motivation and manpower to do so. If you have a problem with an
+old version of Libav, upgrade to the latest git snapshot. If you
+still experience the problem, then you can report it according to the
+guidelines in @url{http://libav.org/bugreports.html}.
 
- at section Why doesn't FFmpeg support feature [xyz]?
+ at section Why doesn't Libav support feature [xyz]?
 
-Because no one has taken on that task yet. FFmpeg development is
+Because no one has taken on that task yet. Libav development is
 driven by the tasks that are important to the individual developers.
 If there is a feature that is important to you, the best way to get
 it implemented is to undertake the task yourself or sponsor a developer.
 
- at section FFmpeg does not support codec XXX. Can you include a Windows DLL loader to support it?
+ at section Libav does not support codec XXX. Can you include a Windows DLL loader to support it?
 
 No. Windows DLLs are not portable, bloated and often slow.
-Moreover FFmpeg strives to support all codecs natively.
+Moreover Libav strives to support all codecs natively.
 A DLL loader is not conducive to that goal.
 
- at section My bug report/mail to ffmpeg-devel/user has not received any replies.
+ at section My bug report/mail to libav-devel/user has not received any replies.
 
 Likely reasons
 @itemize
 @item We are busy and haven't had time yet to read your report or
 investigate the issue.
- at item You didn't follow bugreports.html.
- at item You didn't use Subversion HEAD.
+ at item You didn't follow @url{http://libav.org/bugreports.html}.
+ at item You didn't use git master.
 @item You reported a segmentation fault without gdb output.
 @item You describe a problem but not how to reproduce it.
 @item It's unclear if you use ffmpeg as command line tool or use
@@ -53,10 +55,10 @@ libav* from another application.
 @item You speak about a video having problems on playback but
 not what you use to play it.
 @item We have no faint clue what you are talking about besides
-that it is related to FFmpeg.
+that it is related to Libav.
 @end itemize
 
- at section Is there a forum for FFmpeg? I do not like mailing lists.
+ at section Is there a forum for Libav? I do not like mailing lists.
 
 You may view our mailing lists with a more forum-alike look here:
 @url{http://dir.gmane.org/gmane.comp.video.ffmpeg.user},
@@ -85,7 +87,7 @@ The following list of video codecs should work on most Windows systems:
 .asf only
 @item mpeg4
 Only if you have some MPEG-4 codec like ffdshow or Xvid installed.
- at item mpeg1
+ at item mpeg1video
 .mpg only
 @end table
 Note, ASF files often have .wmv or .wma extensions in Windows. It should also
@@ -97,9 +99,9 @@ The following list of audio codecs should work on most Windows systems:
 @table @option
 @item adpcm_ima_wav
 @item adpcm_ms
- at item pcm
+ at item pcm_s16le
 always
- at item mp3
+ at item libmp3lame
 If some MP3 codec like LAME is installed.
 @end table
 
@@ -122,7 +124,7 @@ problem and an NP-hard problem...
 @section ffmpeg does not work; what is wrong?
 
 Try a @code{make distclean} in the ffmpeg source directory before the build. If this does not help see
-(@url{http://ffmpeg.org/bugreports.html}).
+(@url{http://libav.org/bugreports.html}).
 
 @section How do I encode single pictures into movies?
 
@@ -145,7 +147,7 @@ that match @code{*jpg} to the @file{/tmp} directory in the sequence of
 @file{img001.jpg}, @file{img002.jpg} and so on.
 
 @example
-  x=1; for i in *jpg; do counter=$(printf %03d $x); ln "$i" /tmp/img"$counter".jpg; x=$(($x+1)); done
+  x=1; for i in *jpg; do counter=$(printf %03d $x); ln -s "$i" /tmp/img"$counter".jpg; x=$(($x+1)); done
 @end example
 
 If you want to sequence them by oldest modified first, substitute
@@ -195,19 +197,6 @@ quite logical that there is a small reduction of quality. This is not a bug.
 
 Use @file{-} as file name.
 
- at section Why does the chrominance data seem to be sampled at a different time from the luminance data on bt8x8 captures on Linux?
-
-This is a well-known bug in the bt8x8 driver. For 2.4.26 there is a patch at
-(@url{http://svn.ffmpeg.org/michael/trunk/patches/bttv-420-2.4.26.patch?view=co}). This may also
-apply cleanly to other 2.4-series kernels.
-
- at section How do I avoid the ugly aliasing artifacts in bt8x8 captures on Linux?
-
-Pass 'combfilter=1 lumafilter=1' to the bttv driver. Note though that 'combfilter=1'
-will cause somewhat too strong filtering. A fix is to apply (@url{http://svn.ffmpeg.org/michael/trunk/patches/bttv-comb-2.4.26.patch?view=co})
-or (@url{http://svn.ffmpeg.org/michael/trunk/patches/bttv-comb-2.6.6.patch?view=co})
-and pass 'combfilter=2'.
-
 @section -f jpeg doesn't work.
 
 Try '-f image2 test%d.jpg'.
@@ -233,11 +222,11 @@ default.
 @item needed stuff
 -acodec libfaac -vcodec mpeg4 width<=320 height<=240
 @item working stuff
-4mv, title
+mv4, title
 @item non-working stuff
 B-frames
 @item example command line
-ffmpeg -i input -acodec libfaac -ab 128kb -vcodec mpeg4 -b 1200kb -mbd 2 -flags +4mv -trellis 2 -aic 2 -cmp 2 -subcmp 2 -s 320x180 -metadata title=X output.mp4
+ffmpeg -i input -acodec libfaac -ab 128k -vcodec mpeg4 -b 1200k -mbd 2 -flags +mv4+aic -trellis 2 -cmp 2 -subcmp 2 -s 320x180 -metadata title=X output.mp4
 @end table
 
 @section How do I encode videos which play on the PSP?
@@ -246,11 +235,11 @@ ffmpeg -i input -acodec libfaac -ab 128kb -vcodec mpeg4 -b 1200kb -mbd 2 -flags
 @item needed stuff
 -acodec libfaac -vcodec mpeg4 width*height<=76800 width%16=0 height%16=0 -ar 24000 -r 30000/1001 or 15000/1001 -f psp
 @item working stuff
-4mv, title
+mv4, title
 @item non-working stuff
 B-frames
 @item example command line
-ffmpeg -i input -acodec libfaac -ab 128kb -vcodec mpeg4 -b 1200kb -ar 24000 -mbd 2 -flags +4mv -trellis 2 -aic 2 -cmp 2 -subcmp 2 -s 368x192 -r 30000/1001 -metadata title=X -f psp output.mp4
+ffmpeg -i input -acodec libfaac -ab 128k -vcodec mpeg4 -b 1200k -ar 24000 -mbd 2 -flags +mv4+aic -trellis 2 -cmp 2 -subcmp 2 -s 368x192 -r 30000/1001 -metadata title=X -f psp output.mp4
 @item needed stuff for H.264
 -acodec libfaac -vcodec libx264 width*height<=76800 width%16=0? height%16=0? -ar 48000 -coder 1 -r 30000/1001 or 15000/1001 -f psp
 @item working stuff for H.264
@@ -258,16 +247,16 @@ title, loop filter
 @item non-working stuff for H.264
 CAVLC
 @item example command line
-ffmpeg -i input -acodec libfaac -ab 128kb -vcodec libx264 -b 1200kb -ar 48000 -mbd 2 -coder 1 -cmp 2 -subcmp 2 -s 368x192 -r 30000/1001 -metadata title=X -f psp -flags loop -trellis 2 -partitions parti4x4+parti8x8+partp4x4+partp8x8+partb8x8 output.mp4
+ffmpeg -i input -acodec libfaac -ab 128k -vcodec libx264 -b 1200k -ar 48000 -mbd 2 -coder 1 -cmp 2 -subcmp 2 -s 368x192 -r 30000/1001 -metadata title=X -f psp -flags loop -trellis 2 -partitions parti4x4+parti8x8+partp4x4+partp8x8+partb8x8 output.mp4
 @item higher resolution for newer PSP firmwares, width<=480, height<=272
 -vcodec libx264 -level 21 -coder 1 -f psp
 @item example command line
-ffmpeg -i input -acodec libfaac -ab 128kb -ac 2 -ar 48000 -vcodec libx264 -level 21 -b 640kb -coder 1 -f psp -flags +loop -trellis 2 -partitions +parti4x4+parti8x8+partp4x4+partp8x8+partb8x8 -g 250 -s 480x272 output.mp4
+ffmpeg -i input -acodec libfaac -ab 128k -ac 2 -ar 48000 -vcodec libx264 -level 21 -b 640k -coder 1 -f psp -flags +loop -trellis 2 -partitions +parti4x4+parti8x8+partp4x4+partp8x8+partb8x8 -g 250 -s 480x272 output.mp4
 @end table
 
 @section Which are good parameters for encoding high quality MPEG-4?
 
-'-mbd rd -flags +4mv+aic -trellis 2 -cmp 2 -subcmp 2 -g 300 -pass 1/2',
+'-mbd rd -flags +mv4+aic -trellis 2 -cmp 2 -subcmp 2 -g 300 -pass 1/2',
 things to try: '-bf 2', '-flags qprd', '-flags mv0', '-flags skiprd'.
 
 @section Which are good parameters for encoding high quality MPEG-1/MPEG-2?
@@ -283,11 +272,9 @@ material, and try '-top 0/1' if the result looks really messed-up.
 
 @section How can I read DirectShow files?
 
-If you have built FFmpeg with @code{./configure --enable-avisynth}
+If you have built Libav with @code{./configure --enable-avisynth}
 (only possible on MinGW/Cygwin platforms),
 then you may use any file that DirectShow can read as input.
-(Be aware that this feature has been recently added,
-so you will need to help yourself in case of problems.)
 
 Just create an "input.avs" text file with this single line ...
 @example
@@ -381,11 +368,11 @@ examining all of the vbv_delay values and making complicated computations."
 
 @chapter Development
 
- at section Are there examples illustrating how to use the FFmpeg libraries, particularly libavcodec and libavformat?
+ at section Are there examples illustrating how to use the Libav libraries, particularly libavcodec and libavformat?
 
-Yes. Read the Developers Guide of the FFmpeg documentation. Alternatively,
+Yes. Read the Developers Guide of the Libav documentation. Alternatively,
 examine the source code for one of the many open source projects that
-already incorporate FFmpeg at (@url{projects.html}).
+already incorporate Libav at (@url{projects.html}).
 
 @section Can you support my C compiler XXX?
 
@@ -396,14 +383,14 @@ with @code{#ifdef}s related to the compiler.
 @section Is Microsoft Visual C++ supported?
 
 No. Microsoft Visual C++ is not compliant to the C99 standard and does
-not - among other things - support the inline assembly used in FFmpeg.
+not - among other things - support the inline assembly used in Libav.
 If you wish to use MSVC++ for your
 project then you can link the MSVC++ code with libav* as long as
 you compile the latter with a working C compiler. For more information, see
-the @emph{Microsoft Visual C++ compatibility} section in the FFmpeg
+the @emph{Microsoft Visual C++ compatibility} section in the Libav
 documentation.
 
-There have been efforts to make FFmpeg compatible with MSVC++ in the
+There have been efforts to make Libav compatible with MSVC++ in the
 past. However, they have all been rejected as too intrusive, especially
 since MinGW does the job adequately. None of the core developers
 work with MSVC++ and thus this item is low priority. Should you find
@@ -411,33 +398,23 @@ the silver bullet that solves this problem, feel free to shoot it at us.
 
 We strongly recommend you to move over from MSVC++ to MinGW tools.
 
- at section Can I use FFmpeg or libavcodec under Windows?
+ at section Can I use Libav or libavcodec under Windows?
 
-Yes, but the Cygwin or MinGW tools @emph{must} be used to compile FFmpeg.
-Read the @emph{Windows} section in the FFmpeg documentation to find more
+Yes, but the Cygwin or MinGW tools @emph{must} be used to compile Libav.
+Read the @emph{Windows} section in the Libav documentation to find more
 information.
 
-To get help and instructions for building FFmpeg under Windows, check out
-the FFmpeg Windows Help Forum at
- at url{http://ffmpeg.arrozcru.org/}.
-
 @section Can you add automake, libtool or autoconf support?
 
 No. These tools are too bloated and they complicate the build.
 
 @section Why not rewrite ffmpeg in object-oriented C++?
 
-FFmpeg is already organized in a highly modular manner and does not need to
+Libav is already organized in a highly modular manner and does not need to
 be rewritten in a formal object language. Further, many of the developers
 favor straight C; it works for them. For more arguments on this matter,
 read "Programming Religion" at (@url{http://www.tux.org/lkml/#s15}).
 
- at section Why are the ffmpeg programs devoid of debugging symbols?
-
-The build process creates ffmpeg_g, ffplay_g, etc. which contain full debug
-information. Those binaries are stripped to create ffmpeg, ffplay, etc. If
-you need the debug information, used the *_g versions.
-
 @section I do not like the LGPL, can I contribute code under the GPL instead?
 
 Yes, as long as the code is optional and can easily and cleanly be placed
@@ -454,16 +431,16 @@ the compilation failure then you are probably not qualified for this.
 
 @section I'm using libavcodec from within my C++ application but the linker complains about missing symbols which seem to be available.
 
-FFmpeg is a pure C project, so to use the libraries within your C++ application
+Libav is a pure C project, so to use the libraries within your C++ application
 you need to explicitly state that you are using a C library. You can do this by
-encompassing your FFmpeg includes using @code{extern "C"}.
+encompassing your Libav includes using @code{extern "C"}.
 
 See @url{http://www.parashift.com/c++-faq-lite/mixing-c-and-cpp.html#faq-32.3}
 
 @section I have a file in memory / a API different from *open/*read/ libc how do I use it with libavformat?
 
-You have to implement a URLProtocol, see libavformat/file.c in FFmpeg
-and libmpdemux/demux_lavf.c in MPlayer sources.
+You have to implement a URLProtocol, see @file{libavformat/file.c} in
+Libav and @file{libmpdemux/demux_lavf.c} in MPlayer sources.
 
 @section I get "No compatible shell script interpreter found." in MSys.
 
@@ -473,18 +450,13 @@ The standard MSys bash (2.04) is broken. You need to install 2.05 or later.
 
 The standard MSys install doesn't come with pr. You need to get it from the coreutils package.
 
- at section I tried to pass RTP packets into a decoder, but it doesn't work.
-
-RTP is a container format like any other, you must first depacketize the
-codec frames/samples stored in RTP and then feed to the decoder.
-
 @section Where can I find libav* headers for Pascal/Delphi?
 
 see @url{http://www.iversenit.dk/dev/ffmpeg-headers/}
 
 @section Where is the documentation about ffv1, msmpeg4, asv1, 4xm?
 
-see @url{http://svn.ffmpeg.org/michael/trunk/docs/}
+see @url{http://www.ffmpeg.org/~michael/}
 
 @section How do I feed H.263-RTP (and other codecs in RTP) to libavcodec?
 
diff --git a/doc/fate.txt b/doc/fate.txt
new file mode 100644
index 0000000..f5f3759
--- /dev/null
+++ b/doc/fate.txt
@@ -0,0 +1,45 @@
+FATE Automated Testing Environment
+
+FATE provides a regression testsuite that can be run locally or configured
+to send reports to fate.libav.org.
+In order to run, it needs a large amount of data (samples and references)
+that is provided separately from the actual source distribution.
+
+Use the following command to get the fate test samples
+
+# rsync -aL rsync://samples.libav.org:/samples/fate-suite/ fate-suite
+
+To inform the build system about the testsuite location, pass
+`--samples=<path to the samples>` to configure or set the SAMPLES Make
+variable or the FATE_SAMPLES environment variable to a suitable value.
+
+For information on how to set up FATE to send results to the official Libav
+testing framework, please refer to the following wiki page:
+http://wiki.multimedia.cx/index.php?title=FATE
+
+FATE Makefile targets:
+
+fate-list
+    Will list all fate/regression test targets.
+
+fate
+    Run the FATE test suite (requires the fate-suite dataset).
+
+Fate Makefile variables:
+
+V
+    Verbosity level, can be set to 0, 1 or 2.
+    * 0: show just the test arguments
+    * 1: show just the command used in the test
+    * 2: show everything
+
+SAMPLES
+    Specify or override the path to the FATE samples at make time, it has a
+    meaning only while running the regression tests.
+
+THREADS
+    Specify how many threads to use while running regression tests, it is
+    quite useful to detect thread-related regressions.
+
+Example:
+    make V=1 SAMPLES=/var/fate/samples THREADS=2 fate
diff --git a/doc/ffmpeg-doc.texi b/doc/ffmpeg-doc.texi
deleted file mode 100644
index 7be11d2..0000000
--- a/doc/ffmpeg-doc.texi
+++ /dev/null
@@ -1,956 +0,0 @@
-\input texinfo @c -*- texinfo -*-
-
- at settitle FFmpeg Documentation
- at titlepage
- at sp 7
- at center @titlefont{FFmpeg Documentation}
- at sp 3
- at end titlepage
-
-
- at chapter Introduction
-
-FFmpeg is a very fast video and audio converter. It can also grab from
-a live audio/video source.
-
-The command line interface is designed to be intuitive, in the sense
-that FFmpeg tries to figure out all parameters that can possibly be
-derived automatically. You usually only have to specify the target
-bitrate you want.
-
-FFmpeg can also convert from any sample rate to any other, and resize
-video on the fly with a high quality polyphase filter.
-
- at chapter Quick Start
-
- at c man begin EXAMPLES
- at section Video and Audio grabbing
-
-FFmpeg can grab video and audio from devices given that you specify the input
-format and device.
-
- at example
-ffmpeg -f oss -i /dev/dsp -f video4linux2 -i /dev/video0 /tmp/out.mpg
- at end example
-
-Note that you must activate the right video source and channel before
-launching FFmpeg with any TV viewer such as xawtv
-(@url{http://linux.bytesex.org/xawtv/}) by Gerd Knorr. You also
-have to set the audio recording levels correctly with a
-standard mixer.
-
- at section X11 grabbing
-
-FFmpeg can grab the X11 display.
-
- at example
-ffmpeg -f x11grab -s cif -i :0.0 /tmp/out.mpg
- at end example
-
-0.0 is display.screen number of your X11 server, same as
-the DISPLAY environment variable.
-
- at example
-ffmpeg -f x11grab -s cif -i :0.0+10,20 /tmp/out.mpg
- at end example
-
-0.0 is display.screen number of your X11 server, same as the DISPLAY environment
-variable. 10 is the x-offset and 20 the y-offset for the grabbing.
-
- at section Video and Audio file format conversion
-
-* FFmpeg can use any supported file format and protocol as input:
-
-Examples:
-
-* You can use YUV files as input:
-
- at example
-ffmpeg -i /tmp/test%d.Y /tmp/out.mpg
- at end example
-
-It will use the files:
- at example
-/tmp/test0.Y, /tmp/test0.U, /tmp/test0.V,
-/tmp/test1.Y, /tmp/test1.U, /tmp/test1.V, etc...
- at end example
-
-The Y files use twice the resolution of the U and V files. They are
-raw files, without header. They can be generated by all decent video
-decoders. You must specify the size of the image with the @option{-s} option
-if FFmpeg cannot guess it.
-
-* You can input from a raw YUV420P file:
-
- at example
-ffmpeg -i /tmp/test.yuv /tmp/out.avi
- at end example
-
-test.yuv is a file containing raw YUV planar data. Each frame is composed
-of the Y plane followed by the U and V planes at half vertical and
-horizontal resolution.
-
-* You can output to a raw YUV420P file:
-
- at example
-ffmpeg -i mydivx.avi hugefile.yuv
- at end example
-
-* You can set several input files and output files:
-
- at example
-ffmpeg -i /tmp/a.wav -s 640x480 -i /tmp/a.yuv /tmp/a.mpg
- at end example
-
-Converts the audio file a.wav and the raw YUV video file a.yuv
-to MPEG file a.mpg.
-
-* You can also do audio and video conversions at the same time:
-
- at example
-ffmpeg -i /tmp/a.wav -ar 22050 /tmp/a.mp2
- at end example
-
-Converts a.wav to MPEG audio at 22050 Hz sample rate.
-
-* You can encode to several formats at the same time and define a
-mapping from input stream to output streams:
-
- at example
-ffmpeg -i /tmp/a.wav -ab 64k /tmp/a.mp2 -ab 128k /tmp/b.mp2 -map 0:0 -map 0:0
- at end example
-
-Converts a.wav to a.mp2 at 64 kbits and to b.mp2 at 128 kbits. '-map
-file:index' specifies which input stream is used for each output
-stream, in the order of the definition of output streams.
-
-* You can transcode decrypted VOBs:
-
- at example
-ffmpeg -i snatch_1.vob -f avi -vcodec mpeg4 -b 800k -g 300 -bf 2 -acodec libmp3lame -ab 128k snatch.avi
- at end example
-
-This is a typical DVD ripping example; the input is a VOB file, the
-output an AVI file with MPEG-4 video and MP3 audio. Note that in this
-command we use B-frames so the MPEG-4 stream is DivX5 compatible, and
-GOP size is 300 which means one intra frame every 10 seconds for 29.97fps
-input video. Furthermore, the audio stream is MP3-encoded so you need
-to enable LAME support by passing @code{--enable-libmp3lame} to configure.
-The mapping is particularly useful for DVD transcoding
-to get the desired audio language.
-
-NOTE: To see the supported input formats, use @code{ffmpeg -formats}.
-
-* You can extract images from a video, or create a video from many images:
-
-For extracting images from a video:
- at example
-ffmpeg -i foo.avi -r 1 -s WxH -f image2 foo-%03d.jpeg
- at end example
-
-This will extract one video frame per second from the video and will
-output them in files named @file{foo-001.jpeg}, @file{foo-002.jpeg},
-etc. Images will be rescaled to fit the new WxH values.
-
-If you want to extract just a limited number of frames, you can use the
-above command in combination with the -vframes or -t option, or in
-combination with -ss to start extracting from a certain point in time.
-
-For creating a video from many images:
- at example
-ffmpeg -f image2 -i foo-%03d.jpeg -r 12 -s WxH foo.avi
- at end example
-
-The syntax @code{foo-%03d.jpeg} specifies to use a decimal number
-composed of three digits padded with zeroes to express the sequence
-number. It is the same syntax supported by the C printf function, but
-only formats accepting a normal integer are suitable.
-
-* You can put many streams of the same type in the output:
-
- at example
-ffmpeg -i test1.avi -i test2.avi -vcodec copy -acodec copy -vcodec copy -acodec copy test12.avi -newvideo -newaudio
- at end example
-
-In addition to the first video and audio streams, the resulting
-output file @file{test12.avi} will contain the second video
-and the second audio stream found in the input streams list.
-
-The @code{-newvideo}, @code{-newaudio} and @code{-newsubtitle}
-options have to be specified immediately after the name of the output
-file to which you want to add them.
- at c man end
-
- at chapter Invocation
-
- at section Syntax
-
-The generic syntax is:
-
- at example
- at c man begin SYNOPSIS
-ffmpeg [[infile options][@option{-i} @var{infile}]]... @{[outfile options] @var{outfile}@}...
- at c man end
- at end example
- at c man begin DESCRIPTION
-As a general rule, options are applied to the next specified
-file. Therefore, order is important, and you can have the same
-option on the command line multiple times. Each occurrence is
-then applied to the next input or output file.
-
-* To set the video bitrate of the output file to 64kbit/s:
- at example
-ffmpeg -i input.avi -b 64k output.avi
- at end example
-
-* To force the frame rate of the output file to 24 fps:
- at example
-ffmpeg -i input.avi -r 24 output.avi
- at end example
-
-* To force the frame rate of the input file (valid for raw formats only)
-to 1 fps and the frame rate of the output file to 24 fps:
- at example
-ffmpeg -r 1 -i input.m2v -r 24 output.avi
- at end example
-
-The format option may be needed for raw input files.
-
-By default, FFmpeg tries to convert as losslessly as possible: It
-uses the same audio and video parameters for the outputs as the one
-specified for the inputs.
- at c man end
-
- at c man begin OPTIONS
-
- at include fftools-common-opts.texi
-
- at section Main options
-
- at table @option
-
- at item -f @var{fmt}
-Force format.
-
- at item -i @var{filename}
-input file name
-
- at item -y
-Overwrite output files.
-
- at item -t @var{duration}
-Restrict the transcoded/captured video sequence
-to the duration specified in seconds.
- at code{hh:mm:ss[.xxx]} syntax is also supported.
-
- at item -fs @var{limit_size}
-Set the file size limit.
-
- at item -ss @var{position}
-Seek to given time position in seconds.
- at code{hh:mm:ss[.xxx]} syntax is also supported.
-
- at item -itsoffset @var{offset}
-Set the input time offset in seconds.
- at code{[-]hh:mm:ss[.xxx]} syntax is also supported.
-This option affects all the input files that follow it.
-The offset is added to the timestamps of the input files.
-Specifying a positive offset means that the corresponding
-streams are delayed by 'offset' seconds.
-
- at item -timestamp @var{time}
-Set the timestamp.
-
- at item -metadata @var{key}=@var{value}
-Set a metadata key/value pair.
-
-For example, for setting the title in the output file:
- at example
-ffmpeg -i in.avi -metadata title="my title" out.flv
- at end example
-
- at item -v @var{number}
-Set the logging verbosity level.
-
- at item -target @var{type}
-Specify target file type ("vcd", "svcd", "dvd", "dv", "dv50", "pal-vcd",
-"ntsc-svcd", ... ). All the format options (bitrate, codecs,
-buffer sizes) are then set automatically. You can just type:
-
- at example
-ffmpeg -i myfile.avi -target vcd /tmp/vcd.mpg
- at end example
-
-Nevertheless you can specify additional options as long as you know
-they do not conflict with the standard, as in:
-
- at example
-ffmpeg -i myfile.avi -target vcd -bf 2 /tmp/vcd.mpg
- at end example
-
- at item -dframes @var{number}
-Set the number of data frames to record.
-
- at item -scodec @var{codec}
-Force subtitle codec ('copy' to copy stream).
-
- at item -newsubtitle
-Add a new subtitle stream to the current output stream.
-
- at item -slang @var{code}
-Set the ISO 639 language code (3 letters) of the current subtitle stream.
-
- at end table
-
- at section Video Options
-
- at table @option
- at item -b @var{bitrate}
-Set the video bitrate in bit/s (default = 200 kb/s).
- at item -vframes @var{number}
-Set the number of video frames to record.
- at item -r @var{fps}
-Set frame rate (Hz value, fraction or abbreviation), (default = 25).
- at item -s @var{size}
-Set frame size. The format is @samp{wxh} (ffserver default = 160x128, ffmpeg default = same as source).
-The following abbreviations are recognized:
- at table @samp
- at item sqcif
-128x96
- at item qcif
-176x144
- at item cif
-352x288
- at item 4cif
-704x576
- at item 16cif
-1408x1152
- at item qqvga
-160x120
- at item qvga
-320x240
- at item vga
-640x480
- at item svga
-800x600
- at item xga
-1024x768
- at item uxga
-1600x1200
- at item qxga
-2048x1536
- at item sxga
-1280x1024
- at item qsxga
-2560x2048
- at item hsxga
-5120x4096
- at item wvga
-852x480
- at item wxga
-1366x768
- at item wsxga
-1600x1024
- at item wuxga
-1920x1200
- at item woxga
-2560x1600
- at item wqsxga
-3200x2048
- at item wquxga
-3840x2400
- at item whsxga
-6400x4096
- at item whuxga
-7680x4800
- at item cga
-320x200
- at item ega
-640x350
- at item hd480
-852x480
- at item hd720
-1280x720
- at item hd1080
-1920x1080
- at end table
-
- at item -aspect @var{aspect}
-Set aspect ratio (4:3, 16:9 or 1.3333, 1.7777).
- at item -croptop @var{size}
-Set top crop band size (in pixels).
- at item -cropbottom @var{size}
-Set bottom crop band size (in pixels).
- at item -cropleft @var{size}
-Set left crop band size (in pixels).
- at item -cropright @var{size}
-Set right crop band size (in pixels).
- at item -padtop @var{size}
-Set top pad band size (in pixels).
- at item -padbottom @var{size}
-Set bottom pad band size (in pixels).
- at item -padleft @var{size}
-Set left pad band size (in pixels).
- at item -padright @var{size}
-Set right pad band size (in pixels).
- at item -padcolor @var{hex_color}
-Set color of padded bands. The value for padcolor is expressed
-as a six digit hexadecimal number where the first two digits
-represent red, the middle two digits green and last two digits
-blue (default = 000000 (black)).
- at item -vn
-Disable video recording.
- at item -bt @var{tolerance}
-Set video bitrate tolerance (in bits, default 4000k).
-Has a minimum value of: (target_bitrate/target_framerate).
-In 1-pass mode, bitrate tolerance specifies how far ratecontrol is
-willing to deviate from the target average bitrate value. This is
-not related to min/max bitrate. Lowering tolerance too much has
-an adverse effect on quality.
- at item -maxrate @var{bitrate}
-Set max video bitrate (in bit/s).
-Requires -bufsize to be set.
- at item -minrate @var{bitrate}
-Set min video bitrate (in bit/s).
-Most useful in setting up a CBR encode:
- at example
-ffmpeg -i myfile.avi -b 4000k -minrate 4000k -maxrate 4000k -bufsize 1835k out.m2v
- at end example
-It is of little use elsewise.
- at item -bufsize @var{size}
-Set video buffer verifier buffer size (in bits).
- at item -vcodec @var{codec}
-Force video codec to @var{codec}. Use the @code{copy} special value to
-tell that the raw codec data must be copied as is.
- at item -sameq
-Use same video quality as source (implies VBR).
-
- at item -pass @var{n}
-Select the pass number (1 or 2). It is used to do two-pass
-video encoding. The statistics of the video are recorded in the first
-pass into a log file (see also the option -passlogfile),
-and in the second pass that log file is used to generate the video
-at the exact requested bitrate.
-On pass 1, you may just deactivate audio and set output to null,
-examples for Windows and Unix:
- at example
-ffmpeg -i foo.mov -vcodec libxvid -pass 1 -an -f rawvideo -y NUL
-ffmpeg -i foo.mov -vcodec libxvid -pass 1 -an -f rawvideo -y /dev/null
- at end example
-
- at item -passlogfile @var{prefix}
-Set two-pass log file name prefix to @var{prefix}, the default file name
-prefix is ``ffmpeg2pass''. The complete file name will be
- at file{PREFIX-N.log}, where N is a number specific to the output
-stream.
-
- at item -newvideo
-Add a new video stream to the current output stream.
-
- at item -vlang @var{code}
-Set the ISO 639 language code (3 letters) of the current video stream.
-
- at end table
-
- at section Advanced Video Options
-
- at table @option
- at item -pix_fmt @var{format}
-Set pixel format. Use 'list' as parameter to show all the supported
-pixel formats.
- at item -sws_flags @var{flags}
-Set SwScaler flags.
- at item -g @var{gop_size}
-Set the group of pictures size.
- at item -intra
-Use only intra frames.
- at item -vdt @var{n}
-Discard threshold.
- at item -qscale @var{q}
-Use fixed video quantizer scale (VBR).
- at item -qmin @var{q}
-minimum video quantizer scale (VBR)
- at item -qmax @var{q}
-maximum video quantizer scale (VBR)
- at item -qdiff @var{q}
-maximum difference between the quantizer scales (VBR)
- at item -qblur @var{blur}
-video quantizer scale blur (VBR) (range 0.0 - 1.0)
- at item -qcomp @var{compression}
-video quantizer scale compression (VBR) (default 0.5).
-Constant of ratecontrol equation. Recommended range for default rc_eq: 0.0-1.0
-
- at item -lmin @var{lambda}
-minimum video lagrange factor (VBR)
- at item -lmax @var{lambda}
-max video lagrange factor (VBR)
- at item -mblmin @var{lambda}
-minimum macroblock quantizer scale (VBR)
- at item -mblmax @var{lambda}
-maximum macroblock quantizer scale (VBR)
-
-These four options (lmin, lmax, mblmin, mblmax) use 'lambda' units,
-but you may use the QP2LAMBDA constant to easily convert from 'q' units:
- at example
-ffmpeg -i src.ext -lmax 21*QP2LAMBDA dst.ext
- at end example
-
- at item -rc_init_cplx @var{complexity}
-initial complexity for single pass encoding
- at item -b_qfactor @var{factor}
-qp factor between P- and B-frames
- at item -i_qfactor @var{factor}
-qp factor between P- and I-frames
- at item -b_qoffset @var{offset}
-qp offset between P- and B-frames
- at item -i_qoffset @var{offset}
-qp offset between P- and I-frames
- at item -rc_eq @var{equation}
-Set rate control equation (@pxref{FFmpeg formula
-evaluator}) (default = @code{tex^qComp}).
- at item -rc_override @var{override}
-rate control override for specific intervals
- at item -me_method @var{method}
-Set motion estimation method to @var{method}.
-Available methods are (from lowest to best quality):
- at table @samp
- at item zero
-Try just the (0, 0) vector.
- at item phods
- at item log
- at item x1
- at item hex
- at item umh
- at item epzs
-(default method)
- at item full
-exhaustive search (slow and marginally better than epzs)
- at end table
-
- at item -dct_algo @var{algo}
-Set DCT algorithm to @var{algo}. Available values are:
- at table @samp
- at item 0
-FF_DCT_AUTO (default)
- at item 1
-FF_DCT_FASTINT
- at item 2
-FF_DCT_INT
- at item 3
-FF_DCT_MMX
- at item 4
-FF_DCT_MLIB
- at item 5
-FF_DCT_ALTIVEC
- at end table
-
- at item -idct_algo @var{algo}
-Set IDCT algorithm to @var{algo}. Available values are:
- at table @samp
- at item 0
-FF_IDCT_AUTO (default)
- at item 1
-FF_IDCT_INT
- at item 2
-FF_IDCT_SIMPLE
- at item 3
-FF_IDCT_SIMPLEMMX
- at item 4
-FF_IDCT_LIBMPEG2MMX
- at item 5
-FF_IDCT_PS2
- at item 6
-FF_IDCT_MLIB
- at item 7
-FF_IDCT_ARM
- at item 8
-FF_IDCT_ALTIVEC
- at item 9
-FF_IDCT_SH4
- at item 10
-FF_IDCT_SIMPLEARM
- at end table
-
- at item -er @var{n}
-Set error resilience to @var{n}.
- at table @samp
- at item 1
-FF_ER_CAREFUL (default)
- at item 2
-FF_ER_COMPLIANT
- at item 3
-FF_ER_AGGRESSIVE
- at item 4
-FF_ER_VERY_AGGRESSIVE
- at end table
-
- at item -ec @var{bit_mask}
-Set error concealment to @var{bit_mask}. @var{bit_mask} is a bit mask of
-the following values:
- at table @samp
- at item 1
-FF_EC_GUESS_MVS (default = enabled)
- at item 2
-FF_EC_DEBLOCK (default = enabled)
- at end table
-
- at item -bf @var{frames}
-Use 'frames' B-frames (supported for MPEG-1, MPEG-2 and MPEG-4).
- at item -mbd @var{mode}
-macroblock decision
- at table @samp
- at item 0
-FF_MB_DECISION_SIMPLE: Use mb_cmp (cannot change it yet in FFmpeg).
- at item 1
-FF_MB_DECISION_BITS: Choose the one which needs the fewest bits.
- at item 2
-FF_MB_DECISION_RD: rate distortion
- at end table
-
- at item -4mv
-Use four motion vector by macroblock (MPEG-4 only).
- at item -part
-Use data partitioning (MPEG-4 only).
- at item -bug @var{param}
-Work around encoder bugs that are not auto-detected.
- at item -strict @var{strictness}
-How strictly to follow the standards.
- at item -aic
-Enable Advanced intra coding (h263+).
- at item -umv
-Enable Unlimited Motion Vector (h263+)
-
- at item -deinterlace
-Deinterlace pictures.
- at item -ilme
-Force interlacing support in encoder (MPEG-2 and MPEG-4 only).
-Use this option if your input file is interlaced and you want
-to keep the interlaced format for minimum losses.
-The alternative is to deinterlace the input stream with
- at option{-deinterlace}, but deinterlacing introduces losses.
- at item -psnr
-Calculate PSNR of compressed frames.
- at item -vstats
-Dump video coding statistics to @file{vstats_HHMMSS.log}.
- at item -vstats_file @var{file}
-Dump video coding statistics to @var{file}.
- at item -top @var{n}
-top=1/bottom=0/auto=-1 field first
- at item -dc @var{precision}
-Intra_dc_precision.
- at item -vtag @var{fourcc/tag}
-Force video tag/fourcc.
- at item -qphist
-Show QP histogram.
- at item -vbsf @var{bitstream_filter}
-Bitstream filters available are "dump_extra", "remove_extra", "noise", "h264_mp4toannexb", "imxdump", "mjpegadump".
- at example
-ffmpeg -i h264.mp4 -vcodec copy -vbsf h264_mp4toannexb -an out.h264
- at end example
- at end table
-
- at section Audio Options
-
- at table @option
- at item -aframes @var{number}
-Set the number of audio frames to record.
- at item -ar @var{freq}
-Set the audio sampling frequency (default = 44100 Hz).
- at item -ab @var{bitrate}
-Set the audio bitrate in bit/s (default = 64k).
- at item -aq @var{q}
-Set the audio quality (codec-specific, VBR).
- at item -ac @var{channels}
-Set the number of audio channels (default = 1).
- at item -an
-Disable audio recording.
- at item -acodec @var{codec}
-Force audio codec to @var{codec}. Use the @code{copy} special value to
-specify that the raw codec data must be copied as is.
- at item -newaudio
-Add a new audio track to the output file. If you want to specify parameters,
-do so before @code{-newaudio} (@code{-acodec}, @code{-ab}, etc..).
-
-Mapping will be done automatically, if the number of output streams is equal to
-the number of input streams, else it will pick the first one that matches. You
-can override the mapping using @code{-map} as usual.
-
-Example:
- at example
-ffmpeg -i file.mpg -vcodec copy -acodec ac3 -ab 384k test.mpg -acodec mp2 -ab 192k -newaudio
- at end example
- at item -alang @var{code}
-Set the ISO 639 language code (3 letters) of the current audio stream.
- at end table
-
- at section Advanced Audio options:
-
- at table @option
- at item -atag @var{fourcc/tag}
-Force audio tag/fourcc.
- at item -absf @var{bitstream_filter}
-Bitstream filters available are "dump_extra", "remove_extra", "noise", "mp3comp", "mp3decomp".
- at end table
-
- at section Subtitle options:
-
- at table @option
- at item -scodec @var{codec}
-Force subtitle codec ('copy' to copy stream).
- at item -newsubtitle
-Add a new subtitle stream to the current output stream.
- at item -slang @var{code}
-Set the ISO 639 language code (3 letters) of the current subtitle stream.
- at item -sn
-Disable subtitle recording.
- at item -sbsf @var{bitstream_filter}
-Bitstream filters available are "mov2textsub", "text2movsub".
- at example
-ffmpeg -i file.mov -an -vn -sbsf mov2textsub -scodec copy -f rawvideo sub.txt
- at end example
- at end table
-
- at section Audio/Video grab options
-
- at table @option
- at item -vc @var{channel}
-Set video grab channel (DV1394 only).
- at item -tvstd @var{standard}
-Set television standard (NTSC, PAL (SECAM)).
- at item -isync
-Synchronize read on input.
- at end table
-
- at section Advanced options
-
- at table @option
- at item -map @var{input_stream_id}[:@var{sync_stream_id}]
-Set stream mapping from input streams to output streams.
-Just enumerate the input streams in the order you want them in the output.
- at var{sync_stream_id} if specified sets the input stream to sync
-against.
- at item -map_meta_data @var{outfile}:@var{infile}
-Set meta data information of @var{outfile} from @var{infile}.
- at item -debug
-Print specific debug info.
- at item -benchmark
-Show benchmarking information at the end of an encode.
-Shows CPU time used and maximum memory consumption.
-Maximum memory consumption is not supported on all systems,
-it will usually display as 0 if not supported.
- at item -dump
-Dump each input packet.
- at item -hex
-When dumping packets, also dump the payload.
- at item -bitexact
-Only use bit exact algorithms (for codec testing).
- at item -ps @var{size}
-Set RTP payload size in bytes.
- at item -re
-Read input at native frame rate. Mainly used to simulate a grab device.
- at item -loop_input
-Loop over the input stream. Currently it works only for image
-streams. This option is used for automatic FFserver testing.
- at item -loop_output @var{number_of_times}
-Repeatedly loop output for formats that support looping such as animated GIF
-(0 will loop the output infinitely).
- at item -threads @var{count}
-Thread count.
- at item -vsync @var{parameter}
-Video sync method.
-0   Each frame is passed with its timestamp from the demuxer to the muxer
-1   Frames will be duplicated and dropped to achieve exactly the requested
-    constant framerate.
-2   Frames are passed through with their timestamp or dropped so as to prevent
-    2 frames from having the same timestamp
--1  Chooses between 1 and 2 depending on muxer capabilities. This is the default method.
-
-With -map you can select from
-which stream the timestamps should be taken. You can leave either video or
-audio unchanged and sync the remaining stream(s) to the unchanged one.
- at item -async @var{samples_per_second}
-Audio sync method. "Stretches/squeezes" the audio stream to match the timestamps,
-the parameter is the maximum samples per second by which the audio is changed.
--async 1 is a special case where only the start of the audio stream is corrected
-without any later correction.
- at item -copyts
-Copy timestamps from input to output.
- at item -shortest
-Finish encoding when the shortest input stream ends.
- at item -dts_delta_threshold
-Timestamp discontinuity delta threshold.
- at item -muxdelay @var{seconds}
-Set the maximum demux-decode delay.
- at item -muxpreload @var{seconds}
-Set the initial demux-decode delay.
- at end table
-
- at section Preset files
-
-A preset file contains a sequence of @var{option}=@var{value} pairs,
-one for each line, specifying a sequence of options which would be
-awkward to specify on the command line. Lines starting with the hash
-('#') character are ignored and are used to provide comments. Check
-the @file{ffpresets} directory in the FFmpeg source tree for examples.
-
-Preset files are specified with the @code{vpre}, @code{apre},
- at code{spre}, and @code{fpre} options. The @code{fpre} option takes the
-filename of the preset instead of a preset name as input and can be
-used for any kind of codec. For the @code{vpre}, @code{apre}, and
- at code{spre} options, the options specified in a preset file are
-applied to the currently selected codec of the same type as the preset
-option.
-
-The argument passed to the @code{vpre}, @code{apre}, and @code{spre}
-preset options identifies the preset file to use according to the
-following rules:
-
-First ffmpeg searches for a file named @var{arg}.ffpreset in the
-directories @file{$FFMPEG_DATADIR} (if set), and @file{$HOME/.ffmpeg}, and in
-the datadir defined at configuration time (usually @file{PREFIX/share/ffmpeg})
-in that order. For example, if the argument is @code{libx264-max}, it will
-search for the file @file{libx264-max.ffpreset}.
-
-If no such file is found, then ffmpeg will search for a file named
- at var{codec_name}- at var{arg}.ffpreset in the above-mentioned
-directories, where @var{codec_name} is the name of the codec to which
-the preset file options will be applied. For example, if you select
-the video codec with @code{-vcodec libx264} and use @code{-vpre max},
-then it will search for the file @file{libx264-max.ffpreset}.
-
- at anchor{FFmpeg formula evaluator}
- at section FFmpeg formula evaluator
-
-When evaluating a rate control string, FFmpeg uses an internal formula
-evaluator.
-
-The following binary operators are available: @code{+}, @code{-},
- at code{*}, @code{/}, @code{^}.
-
-The following unary operators are available: @code{+}, @code{-},
- at code{(...)}.
-
-The following statements are available: @code{ld}, @code{st},
- at code{while}.
-
-The following functions are available:
- at table @var
- at item sinh(x)
- at item cosh(x)
- at item tanh(x)
- at item sin(x)
- at item cos(x)
- at item tan(x)
- at item atan(x)
- at item asin(x)
- at item acos(x)
- at item exp(x)
- at item log(x)
- at item abs(x)
- at item squish(x)
- at item gauss(x)
- at item mod(x, y)
- at item max(x, y)
- at item min(x, y)
- at item eq(x, y)
- at item gte(x, y)
- at item gt(x, y)
- at item lte(x, y)
- at item lt(x, y)
- at item bits2qp(bits)
- at item qp2bits(qp)
- at end table
-
-The following constants are available:
- at table @var
- at item PI
- at item E
- at item iTex
- at item pTex
- at item tex
- at item mv
- at item fCode
- at item iCount
- at item mcVar
- at item var
- at item isI
- at item isP
- at item isB
- at item avgQP
- at item qComp
- at item avgIITex
- at item avgPITex
- at item avgPPTex
- at item avgBPTex
- at item avgTex
- at end table
-
- at c man end
-
- at ignore
-
- at setfilename ffmpeg
- at settitle FFmpeg video converter
-
- at c man begin SEEALSO
-ffserver(1), ffplay(1) and the HTML documentation of @file{ffmpeg}.
- at c man end
-
- at c man begin AUTHOR
-Fabrice Bellard
- at c man end
-
- at end ignore
-
- at section Protocols
-
-The file name can be @file{-} to read from standard input or to write
-to standard output.
-
-FFmpeg also handles many protocols specified with an URL syntax.
-
-Use 'ffmpeg -protocols' to see a list of the supported protocols.
-
-The protocol @code{http:} is currently used only to communicate with
-FFserver (see the FFserver documentation). When FFmpeg will be a
-video player it will also be used for streaming :-)
-
- at chapter Tips
-
- at itemize
- at item For streaming at very low bitrate application, use a low frame rate
-and a small GOP size. This is especially true for RealVideo where
-the Linux player does not seem to be very fast, so it can miss
-frames. An example is:
-
- at example
-ffmpeg -g 3 -r 3 -t 10 -b 50k -s qcif -f rv10 /tmp/b.rm
- at end example
-
- at item  The parameter 'q' which is displayed while encoding is the current
-quantizer. The value 1 indicates that a very good quality could
-be achieved. The value 31 indicates the worst quality. If q=31 appears
-too often, it means that the encoder cannot compress enough to meet
-your bitrate. You must either increase the bitrate, decrease the
-frame rate or decrease the frame size.
-
- at item If your computer is not fast enough, you can speed up the
-compression at the expense of the compression ratio. You can use
-'-me zero' to speed up motion estimation, and '-intra' to disable
-motion estimation completely (you have only I-frames, which means it
-is about as good as JPEG compression).
-
- at item To have very low audio bitrates, reduce the sampling frequency
-(down to 22050 Hz for MPEG audio, 22050 or 11025 for AC-3).
-
- at item To have a constant quality (but a variable bitrate), use the option
-'-qscale n' when 'n' is between 1 (excellent quality) and 31 (worst
-quality).
-
- at item When converting video files, you can use the '-sameq' option which
-uses the same quality factor in the encoder as in the decoder.
-It allows almost lossless encoding.
-
- at end itemize
-
- at bye
diff --git a/doc/ffmpeg.texi b/doc/ffmpeg.texi
new file mode 100644
index 0000000..38da918
--- /dev/null
+++ b/doc/ffmpeg.texi
@@ -0,0 +1,1063 @@
+\input texinfo @c -*- texinfo -*-
+
+ at settitle FFmpeg Documentation
+ at titlepage
+ at center @titlefont{FFmpeg Documentation}
+ at end titlepage
+
+ at top
+
+ at contents
+
+ at chapter Synopsis
+
+The generic syntax is:
+
+ at example
+ at c man begin SYNOPSIS
+ffmpeg [[infile options][@option{-i} @var{infile}]]... @{[outfile options] @var{outfile}@}...
+ at c man end
+ at end example
+
+ at chapter Description
+ at c man begin DESCRIPTION
+
+FFmpeg is a very fast video and audio converter. It can also grab from
+a live audio/video source.
+
+The command line interface is designed to be intuitive, in the sense
+that FFmpeg tries to figure out all parameters that can possibly be
+derived automatically. You usually only have to specify the target
+bitrate you want.
+
+FFmpeg can also convert from any sample rate to any other, and resize
+video on the fly with a high quality polyphase filter.
+
+As a general rule, options are applied to the next specified
+file. Therefore, order is important, and you can have the same
+option on the command line multiple times. Each occurrence is
+then applied to the next input or output file.
+
+ at itemize
+ at item
+To set the video bitrate of the output file to 64kbit/s:
+ at example
+ffmpeg -i input.avi -b 64k output.avi
+ at end example
+
+ at item
+To force the frame rate of the output file to 24 fps:
+ at example
+ffmpeg -i input.avi -r 24 output.avi
+ at end example
+
+ at item
+To force the frame rate of the input file (valid for raw formats only)
+to 1 fps and the frame rate of the output file to 24 fps:
+ at example
+ffmpeg -r 1 -i input.m2v -r 24 output.avi
+ at end example
+ at end itemize
+
+The format option may be needed for raw input files.
+
+By default, FFmpeg tries to convert as losslessly as possible: It
+uses the same audio and video parameters for the outputs as the one
+specified for the inputs.
+
+ at c man end DESCRIPTION
+
+ at chapter Options
+ at c man begin OPTIONS
+
+ at include fftools-common-opts.texi
+
+ at section Main options
+
+ at table @option
+
+ at item -f @var{fmt}
+Force format.
+
+ at item -i @var{filename}
+input file name
+
+ at item -y
+Overwrite output files.
+
+ at item -t @var{duration}
+Restrict the transcoded/captured video sequence
+to the duration specified in seconds.
+ at code{hh:mm:ss[.xxx]} syntax is also supported.
+
+ at item -fs @var{limit_size}
+Set the file size limit.
+
+ at item -ss @var{position}
+Seek to given time position in seconds.
+ at code{hh:mm:ss[.xxx]} syntax is also supported.
+
+ at item -itsoffset @var{offset}
+Set the input time offset in seconds.
+ at code{[-]hh:mm:ss[.xxx]} syntax is also supported.
+This option affects all the input files that follow it.
+The offset is added to the timestamps of the input files.
+Specifying a positive offset means that the corresponding
+streams are delayed by 'offset' seconds.
+
+ at item -timestamp @var{time}
+Set the recording timestamp in the container.
+The syntax for @var{time} is:
+ at example
+now|([(YYYY-MM-DD|YYYYMMDD)[T|t| ]]((HH[:MM[:SS[.m...]]])|(HH[MM[SS[.m...]]]))[Z|z])
+ at end example
+If the value is "now" it takes the current time.
+Time is local time unless 'Z' or 'z' is appended, in which case it is
+interpreted as UTC.
+If the year-month-day part is not specified it takes the current
+year-month-day.
+
+ at item -metadata @var{key}=@var{value}
+Set a metadata key/value pair.
+
+For example, for setting the title in the output file:
+ at example
+ffmpeg -i in.avi -metadata title="my title" out.flv
+ at end example
+
+ at item -v @var{number}
+Set the logging verbosity level.
+
+ at item -target @var{type}
+Specify target file type ("vcd", "svcd", "dvd", "dv", "dv50", "pal-vcd",
+"ntsc-svcd", ... ). All the format options (bitrate, codecs,
+buffer sizes) are then set automatically. You can just type:
+
+ at example
+ffmpeg -i myfile.avi -target vcd /tmp/vcd.mpg
+ at end example
+
+Nevertheless you can specify additional options as long as you know
+they do not conflict with the standard, as in:
+
+ at example
+ffmpeg -i myfile.avi -target vcd -bf 2 /tmp/vcd.mpg
+ at end example
+
+ at item -dframes @var{number}
+Set the number of data frames to record.
+
+ at item -scodec @var{codec}
+Force subtitle codec ('copy' to copy stream).
+
+ at item -newsubtitle
+Add a new subtitle stream to the current output stream.
+
+ at item -slang @var{code}
+Set the ISO 639 language code (3 letters) of the current subtitle stream.
+
+ at end table
+
+ at section Video Options
+
+ at table @option
+ at item -b @var{bitrate}
+Set the video bitrate in bit/s (default = 200 kb/s).
+ at item -vframes @var{number}
+Set the number of video frames to record.
+ at item -r @var{fps}
+Set frame rate (Hz value, fraction or abbreviation), (default = 25).
+ at item -s @var{size}
+Set frame size. The format is @samp{wxh} (ffserver default = 160x128, ffmpeg default = same as source).
+The following abbreviations are recognized:
+ at table @samp
+ at item sqcif
+128x96
+ at item qcif
+176x144
+ at item cif
+352x288
+ at item 4cif
+704x576
+ at item 16cif
+1408x1152
+ at item qqvga
+160x120
+ at item qvga
+320x240
+ at item vga
+640x480
+ at item svga
+800x600
+ at item xga
+1024x768
+ at item uxga
+1600x1200
+ at item qxga
+2048x1536
+ at item sxga
+1280x1024
+ at item qsxga
+2560x2048
+ at item hsxga
+5120x4096
+ at item wvga
+852x480
+ at item wxga
+1366x768
+ at item wsxga
+1600x1024
+ at item wuxga
+1920x1200
+ at item woxga
+2560x1600
+ at item wqsxga
+3200x2048
+ at item wquxga
+3840x2400
+ at item whsxga
+6400x4096
+ at item whuxga
+7680x4800
+ at item cga
+320x200
+ at item ega
+640x350
+ at item hd480
+852x480
+ at item hd720
+1280x720
+ at item hd1080
+1920x1080
+ at end table
+
+ at item -aspect @var{aspect}
+Set aspect ratio (4:3, 16:9 or 1.3333, 1.7777).
+ at item -croptop @var{size}
+ at item -cropbottom @var{size}
+ at item -cropleft @var{size}
+ at item -cropright @var{size}
+All the crop options have been removed. Use -vf
+crop=width:height:x:y instead.
+
+ at item -padtop @var{size}
+ at item -padbottom @var{size}
+ at item -padleft @var{size}
+ at item -padright @var{size}
+ at item -padcolor @var{hex_color}
+All the pad options have been removed. Use -vf
+pad=width:height:x:y:color instead.
+ at item -vn
+Disable video recording.
+ at item -bt @var{tolerance}
+Set video bitrate tolerance (in bits, default 4000k).
+Has a minimum value of: (target_bitrate/target_framerate).
+In 1-pass mode, bitrate tolerance specifies how far ratecontrol is
+willing to deviate from the target average bitrate value. This is
+not related to min/max bitrate. Lowering tolerance too much has
+an adverse effect on quality.
+ at item -maxrate @var{bitrate}
+Set max video bitrate (in bit/s).
+Requires -bufsize to be set.
+ at item -minrate @var{bitrate}
+Set min video bitrate (in bit/s).
+Most useful in setting up a CBR encode:
+ at example
+ffmpeg -i myfile.avi -b 4000k -minrate 4000k -maxrate 4000k -bufsize 1835k out.m2v
+ at end example
+It is of little use elsewise.
+ at item -bufsize @var{size}
+Set video buffer verifier buffer size (in bits).
+ at item -vcodec @var{codec}
+Force video codec to @var{codec}. Use the @code{copy} special value to
+tell that the raw codec data must be copied as is.
+ at item -sameq
+Use same quantizer as source (implies VBR).
+
+ at item -pass @var{n}
+Select the pass number (1 or 2). It is used to do two-pass
+video encoding. The statistics of the video are recorded in the first
+pass into a log file (see also the option -passlogfile),
+and in the second pass that log file is used to generate the video
+at the exact requested bitrate.
+On pass 1, you may just deactivate audio and set output to null,
+examples for Windows and Unix:
+ at example
+ffmpeg -i foo.mov -vcodec libxvid -pass 1 -an -f rawvideo -y NUL
+ffmpeg -i foo.mov -vcodec libxvid -pass 1 -an -f rawvideo -y /dev/null
+ at end example
+
+ at item -passlogfile @var{prefix}
+Set two-pass log file name prefix to @var{prefix}, the default file name
+prefix is ``ffmpeg2pass''. The complete file name will be
+ at file{PREFIX-N.log}, where N is a number specific to the output
+stream.
+
+ at item -newvideo
+Add a new video stream to the current output stream.
+
+ at item -vlang @var{code}
+Set the ISO 639 language code (3 letters) of the current video stream.
+
+ at item -vf @var{filter_graph}
+ at var{filter_graph} is a description of the filter graph to apply to
+the input video.
+Use the option "-filters" to show all the available filters (including
+also sources and sinks).
+
+ at end table
+
+ at section Advanced Video Options
+
+ at table @option
+ at item -pix_fmt @var{format}
+Set pixel format. Use 'list' as parameter to show all the supported
+pixel formats.
+ at item -sws_flags @var{flags}
+Set SwScaler flags.
+ at item -g @var{gop_size}
+Set the group of pictures size.
+ at item -intra
+Use only intra frames.
+ at item -vdt @var{n}
+Discard threshold.
+ at item -qscale @var{q}
+Use fixed video quantizer scale (VBR).
+ at item -qmin @var{q}
+minimum video quantizer scale (VBR)
+ at item -qmax @var{q}
+maximum video quantizer scale (VBR)
+ at item -qdiff @var{q}
+maximum difference between the quantizer scales (VBR)
+ at item -qblur @var{blur}
+video quantizer scale blur (VBR) (range 0.0 - 1.0)
+ at item -qcomp @var{compression}
+video quantizer scale compression (VBR) (default 0.5).
+Constant of ratecontrol equation. Recommended range for default rc_eq: 0.0-1.0
+
+ at item -lmin @var{lambda}
+minimum video lagrange factor (VBR)
+ at item -lmax @var{lambda}
+max video lagrange factor (VBR)
+ at item -mblmin @var{lambda}
+minimum macroblock quantizer scale (VBR)
+ at item -mblmax @var{lambda}
+maximum macroblock quantizer scale (VBR)
+
+These four options (lmin, lmax, mblmin, mblmax) use 'lambda' units,
+but you may use the QP2LAMBDA constant to easily convert from 'q' units:
+ at example
+ffmpeg -i src.ext -lmax 21*QP2LAMBDA dst.ext
+ at end example
+
+ at item -rc_init_cplx @var{complexity}
+initial complexity for single pass encoding
+ at item -b_qfactor @var{factor}
+qp factor between P- and B-frames
+ at item -i_qfactor @var{factor}
+qp factor between P- and I-frames
+ at item -b_qoffset @var{offset}
+qp offset between P- and B-frames
+ at item -i_qoffset @var{offset}
+qp offset between P- and I-frames
+ at item -rc_eq @var{equation}
+Set rate control equation (see section "Expression Evaluation")
+(default = @code{tex^qComp}).
+
+When computing the rate control equation expression, besides the
+standard functions defined in the section "Expression Evaluation", the
+following functions are available:
+ at table @var
+ at item bits2qp(bits)
+ at item qp2bits(qp)
+ at end table
+
+and the following constants are available:
+ at table @var
+ at item iTex
+ at item pTex
+ at item tex
+ at item mv
+ at item fCode
+ at item iCount
+ at item mcVar
+ at item var
+ at item isI
+ at item isP
+ at item isB
+ at item avgQP
+ at item qComp
+ at item avgIITex
+ at item avgPITex
+ at item avgPPTex
+ at item avgBPTex
+ at item avgTex
+ at end table
+
+ at item -rc_override @var{override}
+rate control override for specific intervals
+ at item -me_method @var{method}
+Set motion estimation method to @var{method}.
+Available methods are (from lowest to best quality):
+ at table @samp
+ at item zero
+Try just the (0, 0) vector.
+ at item phods
+ at item log
+ at item x1
+ at item hex
+ at item umh
+ at item epzs
+(default method)
+ at item full
+exhaustive search (slow and marginally better than epzs)
+ at end table
+
+ at item -dct_algo @var{algo}
+Set DCT algorithm to @var{algo}. Available values are:
+ at table @samp
+ at item 0
+FF_DCT_AUTO (default)
+ at item 1
+FF_DCT_FASTINT
+ at item 2
+FF_DCT_INT
+ at item 3
+FF_DCT_MMX
+ at item 4
+FF_DCT_MLIB
+ at item 5
+FF_DCT_ALTIVEC
+ at end table
+
+ at item -idct_algo @var{algo}
+Set IDCT algorithm to @var{algo}. Available values are:
+ at table @samp
+ at item 0
+FF_IDCT_AUTO (default)
+ at item 1
+FF_IDCT_INT
+ at item 2
+FF_IDCT_SIMPLE
+ at item 3
+FF_IDCT_SIMPLEMMX
+ at item 4
+FF_IDCT_LIBMPEG2MMX
+ at item 5
+FF_IDCT_PS2
+ at item 6
+FF_IDCT_MLIB
+ at item 7
+FF_IDCT_ARM
+ at item 8
+FF_IDCT_ALTIVEC
+ at item 9
+FF_IDCT_SH4
+ at item 10
+FF_IDCT_SIMPLEARM
+ at end table
+
+ at item -er @var{n}
+Set error resilience to @var{n}.
+ at table @samp
+ at item 1
+FF_ER_CAREFUL (default)
+ at item 2
+FF_ER_COMPLIANT
+ at item 3
+FF_ER_AGGRESSIVE
+ at item 4
+FF_ER_VERY_AGGRESSIVE
+ at end table
+
+ at item -ec @var{bit_mask}
+Set error concealment to @var{bit_mask}. @var{bit_mask} is a bit mask of
+the following values:
+ at table @samp
+ at item 1
+FF_EC_GUESS_MVS (default = enabled)
+ at item 2
+FF_EC_DEBLOCK (default = enabled)
+ at end table
+
+ at item -bf @var{frames}
+Use 'frames' B-frames (supported for MPEG-1, MPEG-2 and MPEG-4).
+ at item -mbd @var{mode}
+macroblock decision
+ at table @samp
+ at item 0
+FF_MB_DECISION_SIMPLE: Use mb_cmp (cannot change it yet in FFmpeg).
+ at item 1
+FF_MB_DECISION_BITS: Choose the one which needs the fewest bits.
+ at item 2
+FF_MB_DECISION_RD: rate distortion
+ at end table
+
+ at item -4mv
+Use four motion vector by macroblock (MPEG-4 only).
+ at item -part
+Use data partitioning (MPEG-4 only).
+ at item -bug @var{param}
+Work around encoder bugs that are not auto-detected.
+ at item -strict @var{strictness}
+How strictly to follow the standards.
+ at item -aic
+Enable Advanced intra coding (h263+).
+ at item -umv
+Enable Unlimited Motion Vector (h263+)
+
+ at item -deinterlace
+Deinterlace pictures.
+ at item -ilme
+Force interlacing support in encoder (MPEG-2 and MPEG-4 only).
+Use this option if your input file is interlaced and you want
+to keep the interlaced format for minimum losses.
+The alternative is to deinterlace the input stream with
+ at option{-deinterlace}, but deinterlacing introduces losses.
+ at item -psnr
+Calculate PSNR of compressed frames.
+ at item -vstats
+Dump video coding statistics to @file{vstats_HHMMSS.log}.
+ at item -vstats_file @var{file}
+Dump video coding statistics to @var{file}.
+ at item -top @var{n}
+top=1/bottom=0/auto=-1 field first
+ at item -dc @var{precision}
+Intra_dc_precision.
+ at item -vtag @var{fourcc/tag}
+Force video tag/fourcc.
+ at item -qphist
+Show QP histogram.
+ at item -vbsf @var{bitstream_filter}
+Bitstream filters available are "dump_extra", "remove_extra", "noise", "h264_mp4toannexb", "imxdump", "mjpegadump", "mjpeg2jpeg".
+ at example
+ffmpeg -i h264.mp4 -vcodec copy -vbsf h264_mp4toannexb -an out.h264
+ at end example
+ at item -force_key_frames @var{time}[, at var{time}...]
+Force key frames at the specified timestamps, more precisely at the first
+frames after each specified time.
+This option can be useful to ensure that a seek point is present at a
+chapter mark or any other designated place in the output file.
+The timestamps must be specified in ascending order.
+ at end table
+
+ at section Audio Options
+
+ at table @option
+ at item -aframes @var{number}
+Set the number of audio frames to record.
+ at item -ar @var{freq}
+Set the audio sampling frequency. For input streams it is set by
+default to 44100 Hz, for output streams it is set by default to the
+frequency of the input stream. If the input file has audio streams
+with different frequencies, the behaviour is undefined.
+ at item -ab @var{bitrate}
+Set the audio bitrate in bit/s (default = 64k).
+ at item -aq @var{q}
+Set the audio quality (codec-specific, VBR).
+ at item -ac @var{channels}
+Set the number of audio channels. For input streams it is set by
+default to 1, for output streams it is set by default to the same
+number of audio channels in input. If the input file has audio streams
+with different channel count, the behaviour is undefined.
+ at item -an
+Disable audio recording.
+ at item -acodec @var{codec}
+Force audio codec to @var{codec}. Use the @code{copy} special value to
+specify that the raw codec data must be copied as is.
+ at item -newaudio
+Add a new audio track to the output file. If you want to specify parameters,
+do so before @code{-newaudio} (@code{-acodec}, @code{-ab}, etc..).
+
+Mapping will be done automatically, if the number of output streams is equal to
+the number of input streams, else it will pick the first one that matches. You
+can override the mapping using @code{-map} as usual.
+
+Example:
+ at example
+ffmpeg -i file.mpg -vcodec copy -acodec ac3 -ab 384k test.mpg -acodec mp2 -ab 192k -newaudio
+ at end example
+ at item -alang @var{code}
+Set the ISO 639 language code (3 letters) of the current audio stream.
+ at end table
+
+ at section Advanced Audio options:
+
+ at table @option
+ at item -atag @var{fourcc/tag}
+Force audio tag/fourcc.
+ at item -audio_service_type @var{type}
+Set the type of service that the audio stream contains.
+ at table @option
+ at item ma
+Main Audio Service (default)
+ at item ef
+Effects
+ at item vi
+Visually Impaired
+ at item hi
+Hearing Impaired
+ at item di
+Dialogue
+ at item co
+Commentary
+ at item em
+Emergency
+ at item vo
+Voice Over
+ at item ka
+Karaoke
+ at end table
+ at item -absf @var{bitstream_filter}
+Bitstream filters available are "dump_extra", "remove_extra", "noise", "mp3comp", "mp3decomp".
+ at end table
+
+ at section Subtitle options:
+
+ at table @option
+ at item -scodec @var{codec}
+Force subtitle codec ('copy' to copy stream).
+ at item -newsubtitle
+Add a new subtitle stream to the current output stream.
+ at item -slang @var{code}
+Set the ISO 639 language code (3 letters) of the current subtitle stream.
+ at item -sn
+Disable subtitle recording.
+ at item -sbsf @var{bitstream_filter}
+Bitstream filters available are "mov2textsub", "text2movsub".
+ at example
+ffmpeg -i file.mov -an -vn -sbsf mov2textsub -scodec copy -f rawvideo sub.txt
+ at end example
+ at end table
+
+ at section Audio/Video grab options
+
+ at table @option
+ at item -vc @var{channel}
+Set video grab channel (DV1394 only).
+ at item -tvstd @var{standard}
+Set television standard (NTSC, PAL (SECAM)).
+ at item -isync
+Synchronize read on input.
+ at end table
+
+ at section Advanced options
+
+ at table @option
+ at item -map @var{input_file_id}. at var{input_stream_id}[:@var{sync_file_id}. at var{sync_stream_id}]
+
+Designate an input stream as a source for the output file. Each input
+stream is identified by the input file index @var{input_file_id} and
+the input stream index @var{input_stream_id} within the input
+file. Both indexes start at 0. If specified,
+ at var{sync_file_id}. at var{sync_stream_id} sets which input stream
+is used as a presentation sync reference.
+
+The @code{-map} options must be specified just after the output file.
+If any @code{-map} options are used, the number of @code{-map} options
+on the command line must match the number of streams in the output
+file. The first @code{-map} option on the command line specifies the
+source for output stream 0, the second @code{-map} option specifies
+the source for output stream 1, etc.
+
+For example, if you have two audio streams in the first input file,
+these streams are identified by "0.0" and "0.1". You can use
+ at code{-map} to select which stream to place in an output file. For
+example:
+ at example
+ffmpeg -i INPUT out.wav -map 0.1
+ at end example
+will map the input stream in @file{INPUT} identified by "0.1" to
+the (single) output stream in @file{out.wav}.
+
+For example, to select the stream with index 2 from input file
+ at file{a.mov} (specified by the identifier "0.2"), and stream with
+index 6 from input @file{b.mov} (specified by the identifier "1.6"),
+and copy them to the output file @file{out.mov}:
+ at example
+ffmpeg -i a.mov -i b.mov -vcodec copy -acodec copy out.mov -map 0.2 -map 1.6
+ at end example
+
+To add more streams to the output file, you can use the
+ at code{-newaudio}, @code{-newvideo}, @code{-newsubtitle} options.
+
+ at item -map_meta_data @var{outfile}[, at var{metadata}]:@var{infile}[, at var{metadata}]
+Deprecated, use @var{-map_metadata} instead.
+
+ at item -map_metadata @var{outfile}[, at var{metadata}]:@var{infile}[, at var{metadata}]
+Set metadata information of @var{outfile} from @var{infile}. Note that those
+are file indices (zero-based), not filenames.
+Optional @var{metadata} parameters specify, which metadata to copy - (g)lobal
+(i.e. metadata that applies to the whole file), per-(s)tream, per-(c)hapter or
+per-(p)rogram. All metadata specifiers other than global must be followed by the
+stream/chapter/program number. If metadata specifier is omitted, it defaults to
+global.
+
+By default, global metadata is copied from the first input file to all output files,
+per-stream and per-chapter metadata is copied along with streams/chapters. These
+default mappings are disabled by creating any mapping of the relevant type. A negative
+file index can be used to create a dummy mapping that just disables automatic copying.
+
+For example to copy metadata from the first stream of the input file to global metadata
+of the output file:
+ at example
+ffmpeg -i in.ogg -map_metadata 0:0,s0 out.mp3
+ at end example
+ at item -map_chapters @var{outfile}:@var{infile}
+Copy chapters from @var{infile} to @var{outfile}. If no chapter mapping is specified,
+then chapters are copied from the first input file with at least one chapter to all
+output files. Use a negative file index to disable any chapter copying.
+ at item -debug
+Print specific debug info.
+ at item -benchmark
+Show benchmarking information at the end of an encode.
+Shows CPU time used and maximum memory consumption.
+Maximum memory consumption is not supported on all systems,
+it will usually display as 0 if not supported.
+ at item -dump
+Dump each input packet.
+ at item -hex
+When dumping packets, also dump the payload.
+ at item -bitexact
+Only use bit exact algorithms (for codec testing).
+ at item -ps @var{size}
+Set RTP payload size in bytes.
+ at item -re
+Read input at native frame rate. Mainly used to simulate a grab device.
+ at item -loop_input
+Loop over the input stream. Currently it works only for image
+streams. This option is used for automatic FFserver testing.
+ at item -loop_output @var{number_of_times}
+Repeatedly loop output for formats that support looping such as animated GIF
+(0 will loop the output infinitely).
+ at item -threads @var{count}
+Thread count.
+ at item -vsync @var{parameter}
+Video sync method.
+
+ at table @option
+ at item 0
+Each frame is passed with its timestamp from the demuxer to the muxer.
+ at item 1
+Frames will be duplicated and dropped to achieve exactly the requested
+constant framerate.
+ at item 2
+Frames are passed through with their timestamp or dropped so as to
+prevent 2 frames from having the same timestamp.
+ at item -1
+Chooses between 1 and 2 depending on muxer capabilities. This is the
+default method.
+ at end table
+
+With -map you can select from which stream the timestamps should be
+taken. You can leave either video or audio unchanged and sync the
+remaining stream(s) to the unchanged one.
+
+ at item -async @var{samples_per_second}
+Audio sync method. "Stretches/squeezes" the audio stream to match the timestamps,
+the parameter is the maximum samples per second by which the audio is changed.
+-async 1 is a special case where only the start of the audio stream is corrected
+without any later correction.
+ at item -copyts
+Copy timestamps from input to output.
+ at item -copytb
+Copy input stream time base from input to output when stream copying.
+ at item -shortest
+Finish encoding when the shortest input stream ends.
+ at item -dts_delta_threshold
+Timestamp discontinuity delta threshold.
+ at item -muxdelay @var{seconds}
+Set the maximum demux-decode delay.
+ at item -muxpreload @var{seconds}
+Set the initial demux-decode delay.
+ at item -streamid @var{output-stream-index}:@var{new-value}
+Assign a new stream-id value to an output stream. This option should be
+specified prior to the output filename to which it applies.
+For the situation where multiple output files exist, a streamid
+may be reassigned to a different value.
+
+For example, to set the stream 0 PID to 33 and the stream 1 PID to 36 for
+an output mpegts file:
+ at example
+ffmpeg -i infile -streamid 0:33 -streamid 1:36 out.ts
+ at end example
+ at end table
+
+ at section Preset files
+
+A preset file contains a sequence of @var{option}=@var{value} pairs,
+one for each line, specifying a sequence of options which would be
+awkward to specify on the command line. Lines starting with the hash
+('#') character are ignored and are used to provide comments. Check
+the @file{ffpresets} directory in the Libav source tree for examples.
+
+Preset files are specified with the @code{vpre}, @code{apre},
+ at code{spre}, and @code{fpre} options. The @code{fpre} option takes the
+filename of the preset instead of a preset name as input and can be
+used for any kind of codec. For the @code{vpre}, @code{apre}, and
+ at code{spre} options, the options specified in a preset file are
+applied to the currently selected codec of the same type as the preset
+option.
+
+The argument passed to the @code{vpre}, @code{apre}, and @code{spre}
+preset options identifies the preset file to use according to the
+following rules:
+
+First ffmpeg searches for a file named @var{arg}.ffpreset in the
+directories @file{$FFMPEG_DATADIR} (if set), and @file{$HOME/.ffmpeg}, and in
+the datadir defined at configuration time (usually @file{PREFIX/share/ffmpeg})
+in that order. For example, if the argument is @code{libx264-max}, it will
+search for the file @file{libx264-max.ffpreset}.
+
+If no such file is found, then ffmpeg will search for a file named
+ at var{codec_name}- at var{arg}.ffpreset in the above-mentioned
+directories, where @var{codec_name} is the name of the codec to which
+the preset file options will be applied. For example, if you select
+the video codec with @code{-vcodec libx264} and use @code{-vpre max},
+then it will search for the file @file{libx264-max.ffpreset}.
+ at c man end
+
+ at chapter Tips
+ at c man begin TIPS
+
+ at itemize
+ at item
+For streaming at very low bitrate application, use a low frame rate
+and a small GOP size. This is especially true for RealVideo where
+the Linux player does not seem to be very fast, so it can miss
+frames. An example is:
+
+ at example
+ffmpeg -g 3 -r 3 -t 10 -b 50k -s qcif -f rv10 /tmp/b.rm
+ at end example
+
+ at item
+The parameter 'q' which is displayed while encoding is the current
+quantizer. The value 1 indicates that a very good quality could
+be achieved. The value 31 indicates the worst quality. If q=31 appears
+too often, it means that the encoder cannot compress enough to meet
+your bitrate. You must either increase the bitrate, decrease the
+frame rate or decrease the frame size.
+
+ at item
+If your computer is not fast enough, you can speed up the
+compression at the expense of the compression ratio. You can use
+'-me zero' to speed up motion estimation, and '-intra' to disable
+motion estimation completely (you have only I-frames, which means it
+is about as good as JPEG compression).
+
+ at item
+To have very low audio bitrates, reduce the sampling frequency
+(down to 22050 Hz for MPEG audio, 22050 or 11025 for AC-3).
+
+ at item
+To have a constant quality (but a variable bitrate), use the option
+'-qscale n' when 'n' is between 1 (excellent quality) and 31 (worst
+quality).
+
+ at item
+When converting video files, you can use the '-sameq' option which
+uses the same quality factor in the encoder as in the decoder.
+It allows almost lossless encoding.
+
+ at end itemize
+ at c man end TIPS
+
+ at chapter Examples
+ at c man begin EXAMPLES
+
+ at section Video and Audio grabbing
+
+FFmpeg can grab video and audio from devices given that you specify the input
+format and device.
+
+ at example
+ffmpeg -f oss -i /dev/dsp -f video4linux2 -i /dev/video0 /tmp/out.mpg
+ at end example
+
+Note that you must activate the right video source and channel before
+launching FFmpeg with any TV viewer such as xawtv
+(@url{http://linux.bytesex.org/xawtv/}) by Gerd Knorr. You also
+have to set the audio recording levels correctly with a
+standard mixer.
+
+ at section X11 grabbing
+
+FFmpeg can grab the X11 display.
+
+ at example
+ffmpeg -f x11grab -s cif -r 25 -i :0.0 /tmp/out.mpg
+ at end example
+
+0.0 is display.screen number of your X11 server, same as
+the DISPLAY environment variable.
+
+ at example
+ffmpeg -f x11grab -s cif -r 25 -i :0.0+10,20 /tmp/out.mpg
+ at end example
+
+0.0 is display.screen number of your X11 server, same as the DISPLAY environment
+variable. 10 is the x-offset and 20 the y-offset for the grabbing.
+
+ at section Video and Audio file format conversion
+
+FFmpeg can use any supported file format and protocol as input:
+
+Examples:
+ at itemize
+ at item
+You can use YUV files as input:
+
+ at example
+ffmpeg -i /tmp/test%d.Y /tmp/out.mpg
+ at end example
+
+It will use the files:
+ at example
+/tmp/test0.Y, /tmp/test0.U, /tmp/test0.V,
+/tmp/test1.Y, /tmp/test1.U, /tmp/test1.V, etc...
+ at end example
+
+The Y files use twice the resolution of the U and V files. They are
+raw files, without header. They can be generated by all decent video
+decoders. You must specify the size of the image with the @option{-s} option
+if FFmpeg cannot guess it.
+
+ at item
+You can input from a raw YUV420P file:
+
+ at example
+ffmpeg -i /tmp/test.yuv /tmp/out.avi
+ at end example
+
+test.yuv is a file containing raw YUV planar data. Each frame is composed
+of the Y plane followed by the U and V planes at half vertical and
+horizontal resolution.
+
+ at item
+You can output to a raw YUV420P file:
+
+ at example
+ffmpeg -i mydivx.avi hugefile.yuv
+ at end example
+
+ at item
+You can set several input files and output files:
+
+ at example
+ffmpeg -i /tmp/a.wav -s 640x480 -i /tmp/a.yuv /tmp/a.mpg
+ at end example
+
+Converts the audio file a.wav and the raw YUV video file a.yuv
+to MPEG file a.mpg.
+
+ at item
+You can also do audio and video conversions at the same time:
+
+ at example
+ffmpeg -i /tmp/a.wav -ar 22050 /tmp/a.mp2
+ at end example
+
+Converts a.wav to MPEG audio at 22050 Hz sample rate.
+
+ at item
+You can encode to several formats at the same time and define a
+mapping from input stream to output streams:
+
+ at example
+ffmpeg -i /tmp/a.wav -ab 64k /tmp/a.mp2 -ab 128k /tmp/b.mp2 -map 0:0 -map 0:0
+ at end example
+
+Converts a.wav to a.mp2 at 64 kbits and to b.mp2 at 128 kbits. '-map
+file:index' specifies which input stream is used for each output
+stream, in the order of the definition of output streams.
+
+ at item
+You can transcode decrypted VOBs:
+
+ at example
+ffmpeg -i snatch_1.vob -f avi -vcodec mpeg4 -b 800k -g 300 -bf 2 -acodec libmp3lame -ab 128k snatch.avi
+ at end example
+
+This is a typical DVD ripping example; the input is a VOB file, the
+output an AVI file with MPEG-4 video and MP3 audio. Note that in this
+command we use B-frames so the MPEG-4 stream is DivX5 compatible, and
+GOP size is 300 which means one intra frame every 10 seconds for 29.97fps
+input video. Furthermore, the audio stream is MP3-encoded so you need
+to enable LAME support by passing @code{--enable-libmp3lame} to configure.
+The mapping is particularly useful for DVD transcoding
+to get the desired audio language.
+
+NOTE: To see the supported input formats, use @code{ffmpeg -formats}.
+
+ at item
+You can extract images from a video, or create a video from many images:
+
+For extracting images from a video:
+ at example
+ffmpeg -i foo.avi -r 1 -s WxH -f image2 foo-%03d.jpeg
+ at end example
+
+This will extract one video frame per second from the video and will
+output them in files named @file{foo-001.jpeg}, @file{foo-002.jpeg},
+etc. Images will be rescaled to fit the new WxH values.
+
+If you want to extract just a limited number of frames, you can use the
+above command in combination with the -vframes or -t option, or in
+combination with -ss to start extracting from a certain point in time.
+
+For creating a video from many images:
+ at example
+ffmpeg -f image2 -i foo-%03d.jpeg -r 12 -s WxH foo.avi
+ at end example
+
+The syntax @code{foo-%03d.jpeg} specifies to use a decimal number
+composed of three digits padded with zeroes to express the sequence
+number. It is the same syntax supported by the C printf function, but
+only formats accepting a normal integer are suitable.
+
+ at item
+You can put many streams of the same type in the output:
+
+ at example
+ffmpeg -i test1.avi -i test2.avi -vcodec copy -acodec copy -vcodec copy -acodec copy test12.avi -newvideo -newaudio
+ at end example
+
+In addition to the first video and audio streams, the resulting
+output file @file{test12.avi} will contain the second video
+and the second audio stream found in the input streams list.
+
+The @code{-newvideo}, @code{-newaudio} and @code{-newsubtitle}
+options have to be specified immediately after the name of the output
+file to which you want to add them.
+
+ at end itemize
+ at c man end EXAMPLES
+
+ at include eval.texi
+ at include encoders.texi
+ at include demuxers.texi
+ at include muxers.texi
+ at include indevs.texi
+ at include outdevs.texi
+ at include protocols.texi
+ at include bitstream_filters.texi
+ at include filters.texi
+ at include metadata.texi
+
+ at ignore
+
+ at setfilename ffmpeg
+ at settitle FFmpeg video converter
+
+ at c man begin SEEALSO
+ffplay(1), ffprobe(1), ffserver(1) and the Libav HTML documentation
+ at c man end
+
+ at c man begin AUTHORS
+The Libav developers
+ at c man end
+
+ at end ignore
+
+ at bye
diff --git a/doc/ffmpeg_powerpc_performance_evaluation_howto.txt b/doc/ffmpeg_powerpc_performance_evaluation_howto.txt
deleted file mode 100644
index 2eb4ee7..0000000
--- a/doc/ffmpeg_powerpc_performance_evaluation_howto.txt
+++ /dev/null
@@ -1,172 +0,0 @@
-FFmpeg & evaluating performance on the PowerPC Architecture HOWTO
-
-(c) 2003-2004 Romain Dolbeau <romain at dolbeau.org>
-
-
-
-I - Introduction
-
-The PowerPC architecture and its SIMD extension AltiVec offer some
-interesting tools to evaluate performance and improve the code.
-This document tries to explain how to use those tools with FFmpeg.
-
-The architecture itself offers two ways to evaluate the performance of
-a given piece of code:
-
-1) The Time Base Registers (TBL)
-2) The Performance Monitor Counter Registers (PMC)
-
-The first ones are always available, always active, but they're not very
-accurate: the registers increment by one every four *bus* cycles. On
-my 667 Mhz tiBook (ppc7450), this means once every twenty *processor*
-cycles. So we won't use that.
-
-The PMC are much more useful: not only can they report cycle-accurate
-timing, but they can also be used to monitor many other parameters,
-such as the number of AltiVec stalls for every kind of instruction,
-or instruction cache misses. The downside is that not all processors
-support the PMC (all G3, all G4 and the 970 do support them), and
-they're inactive by default - you need to activate them with a
-dedicated tool. Also, the number of available PMC depends on the
-procesor: the various 604 have 2, the various 75x (aka. G3) have 4,
-and the various 74xx (aka G4) have 6.
-
-*WARNING*: The PowerPC 970 is not very well documented, and its PMC
-registers are 64 bits wide. To properly notify the code, you *must*
-tune for the 970 (using --tune=970), or the code will assume 32 bit
-registers.
-
-
-II - Enabling FFmpeg PowerPC performance support
-
-This needs to be done by hand. First, you need to configure FFmpeg as
-usual, but add the "--powerpc-perf-enable" option. For instance:
-
-#####
-./configure --prefix=/usr/local/ffmpeg-svn --cc=gcc-3.3 --tune=7450 --powerpc-perf-enable
-#####
-
-This will configure FFmpeg to install inside /usr/local/ffmpeg-svn,
-compiling with gcc-3.3 (you should try to use this one or a newer
-gcc), and tuning for the PowerPC 7450 (i.e. the newer G4; as a rule of
-thumb, those at 550Mhz and more). It will also enable the PMC.
-
-You may also edit the file "config.h" to enable the following line:
-
-#####
-// #define ALTIVEC_USE_REFERENCE_C_CODE 1
-#####
-
-If you enable this line, then the code will not make use of AltiVec,
-but will use the reference C code instead. This is useful to compare
-performance between two versions of the code.
-
-Also, the number of enabled PMC is defined in "libavcodec/ppc/dsputil_ppc.h":
-
-#####
-#define POWERPC_NUM_PMC_ENABLED 4
-#####
-
-If you have a G4 CPU, you can enable all 6 PMC. DO NOT enable more
-PMC than available on your CPU!
-
-Then, simply compile FFmpeg as usual (make && make install).
-
-
-
-III - Using FFmpeg PowerPC performance support
-
-This FFmeg can be used exactly as usual. But before exiting, FFmpeg
-will dump a per-function report that looks like this:
-
-#####
-PowerPC performance report
- Values are from the PMC registers, and represent whatever the
- registers are set to record.
- Function "gmc1_altivec" (pmc1):
-        min: 231
-        max: 1339867
-        avg: 558.25 (255302)
- Function "gmc1_altivec" (pmc2):
-        min: 93
-        max: 2164
-        avg: 267.31 (255302)
- Function "gmc1_altivec" (pmc3):
-        min: 72
-        max: 1987
-        avg: 276.20 (255302)
-(...)
-#####
-
-In this example, PMC1 was set to record CPU cycles, PMC2 was set to
-record AltiVec Permute Stall Cycles, and PMC3 was set to record AltiVec
-Issue Stalls.
-
-The function "gmc1_altivec" was monitored 255302 times, and the
-minimum execution time was 231 processor cycles. The max and average
-aren't much use, as it's very likely the OS interrupted execution for
-reasons of its own :-(
-
-With the exact same settings and source file, but using the reference C
-code we get:
-
-#####
-PowerPC performance report
- Values are from the PMC registers, and represent whatever the
- registers are set to record.
- Function "gmc1_altivec" (pmc1):
-        min: 592
-        max: 2532235
-        avg: 962.88 (255302)
- Function "gmc1_altivec" (pmc2):
-        min: 0
-        max: 33
-        avg: 0.00 (255302)
- Function "gmc1_altivec" (pmc3):
-        min: 0
-        max: 350
-        avg: 0.03 (255302)
-(...)
-#####
-
-592 cycles, so the fastest AltiVec execution is about 2.5x faster than
-the fastest C execution in this example. It's not perfect but it's not
-bad (well I wrote this function so I can't say otherwise :-).
-
-Once you have that kind of report, you can try to improve things by
-finding what goes wrong and fixing it; in the example above, one
-should try to diminish the number of AltiVec stalls, as this *may*
-improve performance.
-
-
-
-IV) Enabling the PMC in Mac OS X
-
-This is easy. Use "Monster" and "monster". Those tools come from
-Apple's CHUD package, and can be found hidden in the developer web
-site & FTP site. "MONster" is the graphical application, use it to
-generate a config file specifying what each register should
-monitor. Then use the command-line application "monster" to use that
-config file, and enjoy the results.
-
-Note that "MONster" can be used for many other things, but it's
-documented by Apple, it's not my subject.
-
-If you are using CHUD 4.4.2 or later, you'll notice that MONster is
-no longer available. It's been superseeded by Shark, where
-configuration of PMCs is available as a plugin.
-
-
-
-V) Enabling the PMC on Linux
-
-On linux you may use oprofile from http://oprofile.sf.net, depending on the
-version and the cpu you may need to apply a patch[1] to access a set of the
-possibile counters from the userspace application. You can always define them
-using the kernel interface /dev/oprofile/* .
-
-[1] http://dev.gentoo.org/~lu_zero/development/oprofile-g4-20060423.patch
-
---
-Romain Dolbeau <romain at dolbeau.org>
-Luca Barbato <lu_zero at gentoo.org>
diff --git a/doc/ffplay-doc.texi b/doc/ffplay-doc.texi
deleted file mode 100644
index e0ca79d..0000000
--- a/doc/ffplay-doc.texi
+++ /dev/null
@@ -1,160 +0,0 @@
-\input texinfo @c -*- texinfo -*-
-
- at settitle FFplay Documentation
- at titlepage
- at sp 7
- at center @titlefont{FFplay Documentation}
- at sp 3
- at end titlepage
-
-
- at chapter Introduction
-
- at c man begin DESCRIPTION
-FFplay is a very simple and portable media player using the FFmpeg
-libraries and the SDL library. It is mostly used as a testbed for the
-various FFmpeg APIs.
- at c man end
-
- at chapter Invocation
-
- at section Syntax
- at example
- at c man begin SYNOPSIS
-ffplay [options] @file{input_file}
- at c man end
- at end example
-
- at c man begin OPTIONS
-
- at include fftools-common-opts.texi
-
- at section Main options
-
- at table @option
- at item -x @var{width}
-Force displayed width.
- at item -y @var{height}
-Force displayed height.
- at item -s @var{size}
-Set frame size (WxH or abbreviation), needed for videos which don't
-contain a header with the frame size like raw YUV.
- at item -an
-Disable audio.
- at item -vn
-Disable video.
- at item -ss @var{pos}
-Seek to a given position in seconds.
- at item -t @var{duration}
-play <duration> seconds of audio/video
- at item -bytes
-Seek by bytes.
- at item -nodisp
-Disable graphical display.
- at item -f @var{fmt}
-Force format.
- at item -window_title @var{title}
-Set window title (default is the input filename).
- at item -loop @var{number}
-Loops movie playback <number> times. 0 means forever.
- at end table
-
- at section Advanced options
- at table @option
- at item -pix_fmt @var{format}
-Set pixel format.
- at item -stats
-Show the stream duration, the codec parameters, the current position in
-the stream and the audio/video synchronisation drift.
- at item -debug
-Print specific debug info.
- at item -bug
-Work around bugs.
- at item -vismv
-Visualize motion vectors.
- at item -fast
-Non-spec-compliant optimizations.
- at item -genpts
-Generate pts.
- at item -rtp_tcp
-Force RTP/TCP protocol usage instead of RTP/UDP. It is only meaningful
-if you are streaming with the RTSP protocol.
- at item -sync @var{type}
-Set the master clock to audio (@code{type=audio}), video
-(@code{type=video}) or external (@code{type=ext}). Default is audio. The
-master clock is used to control audio-video synchronization. Most media
-players use audio as master clock, but in some cases (streaming or high
-quality broadcast) it is necessary to change that. This option is mainly
-used for debugging purposes.
- at item -threads @var{count}
-Set the thread count.
- at item -ast @var{audio_stream_number}
-Select the desired audio stream number, counting from 0. The number
-refers to the list of all the input audio streams. If it is greater
-than the number of audio streams minus one, then the last one is
-selected, if it is negative the audio playback is disabled.
- at item -vst @var{video_stream_number}
-Select the desired video stream number, counting from 0. The number
-refers to the list of all the input video streams. If it is greater
-than the number of video streams minus one, then the last one is
-selected, if it is negative the video playback is disabled.
- at item -sst @var{subtitle_stream_number}
-Select the desired subtitle stream number, counting from 0. The number
-refers to the list of all the input subtitle streams. If it is greater
-than the number of subtitle streams minus one, then the last one is
-selected, if it is negative the subtitle rendering is disabled.
- at end table
-
- at section While playing
-
- at table @key
- at item q, ESC
-Quit.
-
- at item f
-Toggle full screen.
-
- at item p, SPC
-Pause.
-
- at item a
-Cycle audio channel.
-
- at item v
-Cycle video channel.
-
- at item t
-Cycle subtitle channel.
-
- at item w
-Show audio waves.
-
- at item left/right
-Seek backward/forward 10 seconds.
-
- at item down/up
-Seek backward/forward 1 minute.
-
- at item mouse click
-Seek to percentage in file corresponding to fraction of width.
-
- at end table
-
- at c man end
-
- at ignore
-
- at setfilename ffplay
- at settitle FFplay media player
-
- at c man begin SEEALSO
-ffmpeg(1), ffserver(1) and the HTML documentation of @file{ffmpeg}.
- at c man end
-
- at c man begin AUTHOR
-Fabrice Bellard
- at c man end
-
- at end ignore
-
- at bye
diff --git a/doc/ffplay.texi b/doc/ffplay.texi
new file mode 100644
index 0000000..6199e6d
--- /dev/null
+++ b/doc/ffplay.texi
@@ -0,0 +1,181 @@
+\input texinfo @c -*- texinfo -*-
+
+ at settitle FFplay Documentation
+ at titlepage
+ at center @titlefont{FFplay Documentation}
+ at end titlepage
+
+ at top
+
+ at contents
+
+ at chapter Synopsis
+
+ at example
+ at c man begin SYNOPSIS
+ffplay [options] @file{input_file}
+ at c man end
+ at end example
+
+ at chapter Description
+ at c man begin DESCRIPTION
+
+FFplay is a very simple and portable media player using the Libav
+libraries and the SDL library. It is mostly used as a testbed for the
+various Libav APIs.
+ at c man end
+
+ at chapter Options
+ at c man begin OPTIONS
+
+ at include fftools-common-opts.texi
+
+ at section Main options
+
+ at table @option
+ at item -x @var{width}
+Force displayed width.
+ at item -y @var{height}
+Force displayed height.
+ at item -s @var{size}
+Set frame size (WxH or abbreviation), needed for videos which don't
+contain a header with the frame size like raw YUV.
+ at item -an
+Disable audio.
+ at item -vn
+Disable video.
+ at item -ss @var{pos}
+Seek to a given position in seconds.
+ at item -t @var{duration}
+play <duration> seconds of audio/video
+ at item -bytes
+Seek by bytes.
+ at item -nodisp
+Disable graphical display.
+ at item -f @var{fmt}
+Force format.
+ at item -window_title @var{title}
+Set window title (default is the input filename).
+ at item -loop @var{number}
+Loops movie playback <number> times. 0 means forever.
+ at item -vf @var{filter_graph}
+ at var{filter_graph} is a description of the filter graph to apply to
+the input video.
+Use the option "-filters" to show all the available filters (including
+also sources and sinks).
+
+ at end table
+
+ at section Advanced options
+ at table @option
+ at item -pix_fmt @var{format}
+Set pixel format.
+ at item -stats
+Show the stream duration, the codec parameters, the current position in
+the stream and the audio/video synchronisation drift.
+ at item -debug
+Print specific debug info.
+ at item -bug
+Work around bugs.
+ at item -vismv
+Visualize motion vectors.
+ at item -fast
+Non-spec-compliant optimizations.
+ at item -genpts
+Generate pts.
+ at item -rtp_tcp
+Force RTP/TCP protocol usage instead of RTP/UDP. It is only meaningful
+if you are streaming with the RTSP protocol.
+ at item -sync @var{type}
+Set the master clock to audio (@code{type=audio}), video
+(@code{type=video}) or external (@code{type=ext}). Default is audio. The
+master clock is used to control audio-video synchronization. Most media
+players use audio as master clock, but in some cases (streaming or high
+quality broadcast) it is necessary to change that. This option is mainly
+used for debugging purposes.
+ at item -threads @var{count}
+Set the thread count.
+ at item -ast @var{audio_stream_number}
+Select the desired audio stream number, counting from 0. The number
+refers to the list of all the input audio streams. If it is greater
+than the number of audio streams minus one, then the last one is
+selected, if it is negative the audio playback is disabled.
+ at item -vst @var{video_stream_number}
+Select the desired video stream number, counting from 0. The number
+refers to the list of all the input video streams. If it is greater
+than the number of video streams minus one, then the last one is
+selected, if it is negative the video playback is disabled.
+ at item -sst @var{subtitle_stream_number}
+Select the desired subtitle stream number, counting from 0. The number
+refers to the list of all the input subtitle streams. If it is greater
+than the number of subtitle streams minus one, then the last one is
+selected, if it is negative the subtitle rendering is disabled.
+ at item -autoexit
+Exit when video is done playing.
+ at item -exitonkeydown
+Exit if any key is pressed.
+ at item -exitonmousedown
+Exit if any mouse button is pressed.
+ at end table
+
+ at section While playing
+
+ at table @key
+ at item q, ESC
+Quit.
+
+ at item f
+Toggle full screen.
+
+ at item p, SPC
+Pause.
+
+ at item a
+Cycle audio channel.
+
+ at item v
+Cycle video channel.
+
+ at item t
+Cycle subtitle channel.
+
+ at item w
+Show audio waves.
+
+ at item left/right
+Seek backward/forward 10 seconds.
+
+ at item down/up
+Seek backward/forward 1 minute.
+
+ at item mouse click
+Seek to percentage in file corresponding to fraction of width.
+
+ at end table
+
+ at c man end
+
+ at include eval.texi
+ at include demuxers.texi
+ at include muxers.texi
+ at include indevs.texi
+ at include outdevs.texi
+ at include protocols.texi
+ at include filters.texi
+
+ at ignore
+
+ at setfilename ffplay
+ at settitle FFplay media player
+
+ at c man begin SEEALSO
+ffmpeg(1), ffprobe(1), ffserver(1) and the Libav HTML documentation
+ at c man end
+
+ at c man begin AUTHORS
+The Libav developers
+ at c man end
+
+ at end ignore
+
+ at bye
diff --git a/doc/ffprobe-doc.texi b/doc/ffprobe-doc.texi
deleted file mode 100644
index 8eb3ed9..0000000
--- a/doc/ffprobe-doc.texi
+++ /dev/null
@@ -1,121 +0,0 @@
-\input texinfo @c -*- texinfo -*-
-
- at settitle FFprobe Documentation
- at titlepage
- at sp 7
- at center @titlefont{FFprobe Documentation}
- at sp 3
- at end titlepage
-
- at chapter Introduction
-
- at c man begin DESCRIPTION
-
-FFprobe gathers information from multimedia streams and prints it in
-human- and machine-readable fashion.
-
-For example it can be used to check the format of the container used
-by a multimedia stream and the format and type of each media stream
-contained in it.
-
-If a filename is specified in input, ffprobe will try to open and
-probe the file content. If the file cannot be opened or recognized as
-a multimedia file, a positive exit code is returned.
-
-FFprobe may be employed both as a standalone application or in
-combination with a textual filter, which may perform more
-sophisticated processing, e.g. statistical processing or plotting.
-
-Options are used to list some of the formats supported by ffprobe or
-for specifying which information to display, and for setting how
-ffprobe will show it.
-
-FFprobe output is designed to be easily parsable by a textual filter,
-and consists of one or more sections of the form:
- at example
-[SECTION]
-key1=val1
-...
-keyN=valN
-[/SECTION]
- at end example
-
-Metadata tags stored in the container or in the streams are recognized
-and printed in the corresponding ``FORMAT'' or ``STREAM'' section, and
-are prefixed by the string ``TAG:''.
-
- at c man end
-
- at chapter Invocation
-
- at section Syntax
-
-The generic syntax is:
-
- at example
- at c man begin SYNOPSIS
-ffprobe [options] [@file{input_file}]
- at c man end
- at end example
-
- at c man begin OPTIONS
-
- at include fftools-common-opts.texi
-
- at section Main options
-
- at table @option
-
- at item -convert_tags
-Convert the tag names in the format container to the generic FFmpeg tag names.
-
- at item -f @var{format}
-Force format to use.
-
- at item -unit
-Show the unit of the displayed values.
-
- at item -prefix
-Show a SI prefixes of the displayed values.
-Unless ``-byte_binary_prefix'' option is used all the prefix
-are decimal.
-
- at item -byte_binary_prefix
-Force the use of binary prefixes for byte values.
-
- at item -sexagesimal
-Use sexagesimal format HH:MM:SS.MICROSECONDS for time values.
-
- at item -pretty
-Prettify the format of the displayed values, it corresponds to the
-options ``-unit -prefix -byte_binary_prefix -sexagesimal''.
-
- at item -show_format
-Show information about the container format of the input multimedia
-stream.
-
-All the container format information is printed within a section with
-name ``FORMAT''.
-
- at item -show_streams
-Show information about each media stream contained in the input
-multimedia stream.
-
-Each media stream information is printed within a dedicated section
-with name ``STREAM''.
-
- at end table
- at c man end
-
- at ignore
-
- at setfilename ffprobe
- at settitle FFprobe media prober
-
- at c man begin SEEALSO
-ffmpeg(1), ffplay(1), ffserver(1)
- at c man end
-
- at end ignore
-
- at bye
diff --git a/doc/ffprobe.texi b/doc/ffprobe.texi
new file mode 100644
index 0000000..b775f55
--- /dev/null
+++ b/doc/ffprobe.texi
@@ -0,0 +1,134 @@
+\input texinfo @c -*- texinfo -*-
+
+ at settitle FFprobe Documentation
+ at titlepage
+ at center @titlefont{FFprobe Documentation}
+ at end titlepage
+
+ at top
+
+ at contents
+
+ at chapter Synopsis
+
+The generic syntax is:
+
+ at example
+ at c man begin SYNOPSIS
+ffprobe [options] [@file{input_file}]
+ at c man end
+ at end example
+
+ at chapter Description
+ at c man begin DESCRIPTION
+
+FFprobe gathers information from multimedia streams and prints it in
+human- and machine-readable fashion.
+
+For example it can be used to check the format of the container used
+by a multimedia stream and the format and type of each media stream
+contained in it.
+
+If a filename is specified in input, ffprobe will try to open and
+probe the file content. If the file cannot be opened or recognized as
+a multimedia file, a positive exit code is returned.
+
+FFprobe may be employed both as a standalone application or in
+combination with a textual filter, which may perform more
+sophisticated processing, e.g. statistical processing or plotting.
+
+Options are used to list some of the formats supported by ffprobe or
+for specifying which information to display, and for setting how
+ffprobe will show it.
+
+FFprobe output is designed to be easily parsable by a textual filter,
+and consists of one or more sections of the form:
+ at example
+[SECTION]
+key1=val1
+...
+keyN=valN
+[/SECTION]
+ at end example
+
+Metadata tags stored in the container or in the streams are recognized
+and printed in the corresponding "FORMAT" or "STREAM" section, and
+are prefixed by the string "TAG:".
+
+ at c man end
+
+ at chapter Options
+ at c man begin OPTIONS
+
+ at include fftools-common-opts.texi
+
+ at section Main options
+
+ at table @option
+
+ at item -f @var{format}
+Force format to use.
+
+ at item -unit
+Show the unit of the displayed values.
+
+ at item -prefix
+Use SI prefixes for the displayed values.
+Unless the "-byte_binary_prefix" option is used all the prefixes
+are decimal.
+
+ at item -byte_binary_prefix
+Force the use of binary prefixes for byte values.
+
+ at item -sexagesimal
+Use sexagesimal format HH:MM:SS.MICROSECONDS for time values.
+
+ at item -pretty
+Prettify the format of the displayed values, it corresponds to the
+options "-unit -prefix -byte_binary_prefix -sexagesimal".
+
+ at item -show_format
+Show information about the container format of the input multimedia
+stream.
+
+All the container format information is printed within a section with
+name "FORMAT".
+
+ at item -show_packets
+Show information about each packet contained in the input multimedia
+stream.
+
+The information for each single packet is printed within a dedicated
+section with name "PACKET".
+
+ at item -show_streams
+Show information about each media stream contained in the input
+multimedia stream.
+
+Each media stream information is printed within a dedicated section
+with name "STREAM".
+
+ at end table
+ at c man end
+
+ at include demuxers.texi
+ at include muxers.texi
+ at include protocols.texi
+ at include indevs.texi
+
+ at ignore
+
+ at setfilename ffprobe
+ at settitle FFprobe media prober
+
+ at c man begin SEEALSO
+ffmpeg(1), ffplay(1), ffserver(1) and the Libav HTML documentation
+ at c man end
+
+ at c man begin AUTHORS
+The Libav developers
+ at c man end
+
+ at end ignore
+
+ at bye
diff --git a/doc/ffserver-doc.texi b/doc/ffserver-doc.texi
deleted file mode 100644
index 0a2440a..0000000
--- a/doc/ffserver-doc.texi
+++ /dev/null
@@ -1,274 +0,0 @@
-\input texinfo @c -*- texinfo -*-
-
- at settitle FFserver Documentation
- at titlepage
- at sp 7
- at center @titlefont{FFserver Documentation}
- at sp 3
- at end titlepage
-
-
- at chapter Introduction
-
- at c man begin DESCRIPTION
-FFserver is a streaming server for both audio and video. It supports
-several live feeds, streaming from files and time shifting on live feeds
-(you can seek to positions in the past on each live feed, provided you
-specify a big enough feed storage in ffserver.conf).
-
-FFserver runs in daemon mode by default; that is, it puts itself in
-the background and detaches from its TTY, unless it is launched in
-debug mode or a NoDaemon option is specified in the configuration
-file.
-
-This documentation covers only the streaming aspects of ffserver /
-ffmpeg. All questions about parameters for ffmpeg, codec questions,
-etc. are not covered here. Read @file{ffmpeg-doc.html} for more
-information.
-
- at section How does it work?
-
-FFserver receives prerecorded files or FFM streams from some ffmpeg
-instance as input, then streams them over RTP/RTSP/HTTP.
-
-An ffserver instance will listen on some port as specified in the
-configuration file. You can launch one or more instances of ffmpeg and
-send one or more FFM streams to the port where ffserver is expecting
-to receive them. Alternately, you can make ffserver launch such ffmpeg
-instances at startup.
-
-Input streams are called feeds, and each one is specified by a <Feed>
-section in the configuration file.
-
-For each feed you can have different output streams in various
-formats, each one specified by a <Stream> section in the configuration
-file.
-
- at section Status stream
-
-FFserver supports an HTTP interface which exposes the current status
-of the server.
-
-Simply point your browser to the address of the special status stream
-specified in the configuration file.
-
-For example if you have:
- at example
-<Stream status.html>
-Format status
-
-# Only allow local people to get the status
-ACL allow localhost
-ACL allow 192.168.0.0 192.168.255.255
-</Stream>
- at end example
-
-then the server will post a page with the status information when
-the special stream @file{status.html} is requested.
-
- at section What can this do?
-
-When properly configured and running, you can capture video and audio in real
-time from a suitable capture card, and stream it out over the Internet to
-either Windows Media Player or RealAudio player (with some restrictions).
-
-It can also stream from files, though that is currently broken. Very often, a
-web server can be used to serve up the files just as well.
-
-It can stream prerecorded video from .ffm files, though it is somewhat tricky
-to make it work correctly.
-
- at section What do I need?
-
-I use Linux on a 900 MHz Duron with a cheapo Bt848 based TV capture card. I'm
-using stock Linux 2.4.17 with the stock drivers. [Actually that isn't true,
-I needed some special drivers for my motherboard-based sound card.]
-
-I understand that FreeBSD systems work just fine as well.
-
- at section How do I make it work?
-
-First, build the kit. It *really* helps to have installed LAME first. Then when
-you run the ffserver ./configure, make sure that you have the
- at code{--enable-libmp3lame} flag turned on.
-
-LAME is important as it allows for streaming audio to Windows Media Player.
-Don't ask why the other audio types do not work.
-
-As a simple test, just run the following two command lines where INPUTFILE
-is some file which you can decode with ffmpeg:
-
- at example
-./ffserver -f doc/ffserver.conf &
-./ffmpeg -i INPUTFILE http://localhost:8090/feed1.ffm
- at end example
-
-At this point you should be able to go to your Windows machine and fire up
-Windows Media Player (WMP). Go to Open URL and enter
-
- at example
-    http://<linuxbox>:8090/test.asf
- at end example
-
-You should (after a short delay) see video and hear audio.
-
-WARNING: trying to stream test1.mpg doesn't work with WMP as it tries to
-transfer the entire file before starting to play.
-The same is true of AVI files.
-
- at section What happens next?
-
-You should edit the ffserver.conf file to suit your needs (in terms of
-frame rates etc). Then install ffserver and ffmpeg, write a script to start
-them up, and off you go.
-
- at section Troubleshooting
-
- at subsection I don't hear any audio, but video is fine.
-
-Maybe you didn't install LAME, or got your ./configure statement wrong. Check
-the ffmpeg output to see if a line referring to MP3 is present. If not, then
-your configuration was incorrect. If it is, then maybe your wiring is not
-set up correctly. Maybe the sound card is not getting data from the right
-input source. Maybe you have a really awful audio interface (like I do)
-that only captures in stereo and also requires that one channel be flipped.
-If you are one of these people, then export 'AUDIO_FLIP_LEFT=1' before
-starting ffmpeg.
-
- at subsection The audio and video loose sync after a while.
-
-Yes, they do.
-
- at subsection After a long while, the video update rate goes way down in WMP.
-
-Yes, it does. Who knows why?
-
- at subsection WMP 6.4 behaves differently to WMP 7.
-
-Yes, it does. Any thoughts on this would be gratefully received. These
-differences extend to embedding WMP into a web page. [There are two
-object IDs that you can use: The old one, which does not play well, and
-the new one, which does (both tested on the same system). However,
-I suspect that the new one is not available unless you have installed WMP 7].
-
- at section What else can it do?
-
-You can replay video from .ffm files that was recorded earlier.
-However, there are a number of caveats, including the fact that the
-ffserver parameters must match the original parameters used to record the
-file. If they do not, then ffserver deletes the file before recording into it.
-(Now that I write this, it seems broken).
-
-You can fiddle with many of the codec choices and encoding parameters, and
-there are a bunch more parameters that you cannot control. Post a message
-to the mailing list if there are some 'must have' parameters. Look in
-ffserver.conf for a list of the currently available controls.
-
-It will automatically generate the ASX or RAM files that are often used
-in browsers. These files are actually redirections to the underlying ASF
-or RM file. The reason for this is that the browser often fetches the
-entire file before starting up the external viewer. The redirection files
-are very small and can be transferred quickly. [The stream itself is
-often 'infinite' and thus the browser tries to download it and never
-finishes.]
-
- at section Tips
-
-* When you connect to a live stream, most players (WMP, RA, etc) want to
-buffer a certain number of seconds of material so that they can display the
-signal continuously. However, ffserver (by default) starts sending data
-in realtime. This means that there is a pause of a few seconds while the
-buffering is being done by the player. The good news is that this can be
-cured by adding a '?buffer=5' to the end of the URL. This means that the
-stream should start 5 seconds in the past -- and so the first 5 seconds
-of the stream are sent as fast as the network will allow. It will then
-slow down to real time. This noticeably improves the startup experience.
-
-You can also add a 'Preroll 15' statement into the ffserver.conf that will
-add the 15 second prebuffering on all requests that do not otherwise
-specify a time. In addition, ffserver will skip frames until a key_frame
-is found. This further reduces the startup delay by not transferring data
-that will be discarded.
-
-* You may want to adjust the MaxBandwidth in the ffserver.conf to limit
-the amount of bandwidth consumed by live streams.
-
- at section Why does the ?buffer / Preroll stop working after a time?
-
-It turns out that (on my machine at least) the number of frames successfully
-grabbed is marginally less than the number that ought to be grabbed. This
-means that the timestamp in the encoded data stream gets behind realtime.
-This means that if you say 'Preroll 10', then when the stream gets 10
-or more seconds behind, there is no Preroll left.
-
-Fixing this requires a change in the internals of how timestamps are
-handled.
-
- at section Does the @code{?date=} stuff work.
-
-Yes (subject to the limitation outlined above). Also note that whenever you
-start ffserver, it deletes the ffm file (if any parameters have changed),
-thus wiping out what you had recorded before.
-
-The format of the @code{?date=xxxxxx} is fairly flexible. You should use one
-of the following formats (the 'T' is literal):
-
- at example
-* YYYY-MM-DDTHH:MM:SS     (localtime)
-* YYYY-MM-DDTHH:MM:SSZ    (UTC)
- at end example
-
-You can omit the YYYY-MM-DD, and then it refers to the current day. However
-note that @samp{?date=16:00:00} refers to 16:00 on the current day -- this
-may be in the future and so is unlikely to be useful.
-
-You use this by adding the ?date= to the end of the URL for the stream.
-For example:   @samp{http://localhost:8080/test.asf?date=2002-07-26T23:05:00}.
- at c man end
-
- at chapter Invocation
- at section Syntax
- at example
- at c man begin SYNOPSIS
-ffserver [options]
- at c man end
- at end example
-
- at section Options
- at c man begin OPTIONS
-
- at include fftools-common-opts.texi
-
- at section Main options
-
- at table @option
- at item -f @var{configfile}
-Use @file{configfile} instead of @file{/etc/ffserver.conf}.
- at item -n
-Enable no-launch mode. This option disables all the Launch directives
-within the various <Stream> sections. FFserver will not launch any
-ffmpeg instance, so you will have to launch them manually.
- at item -d
-Enable debug mode. This option increases log verbosity, directs log
-messages to stdout and causes ffserver to run in the foreground
-rather than as a daemon.
- at end table
- at c man end
-
- at ignore
-
- at setfilename ffserver
- at settitle FFserver video server
-
- at c man begin SEEALSO
-ffmpeg(1), ffplay(1), the @file{ffmpeg/doc/ffserver.conf} example and
-the HTML documentation of @file{ffmpeg}.
- at c man end
-
- at c man begin AUTHOR
-Fabrice Bellard
- at c man end
-
- at end ignore
-
- at bye
diff --git a/doc/ffserver.conf b/doc/ffserver.conf
index 2fbfecd..62728b0 100644
--- a/doc/ffserver.conf
+++ b/doc/ffserver.conf
@@ -306,6 +306,27 @@ StartSendOnKey
 #</Stream>
 
 
+# Transcode an incoming live feed to another live feed,
+# using libx264 and video presets
+
+#<Stream live.h264>
+#Format rtp
+#Feed feed1.ffm
+#VideoCodec libx264
+#VideoFrameRate 24
+#VideoBitRate 100
+#VideoSize 480x272
+#AVPresetVideo default
+#AVPresetVideo baseline
+#AVOptionVideo flags +global_header
+#
+#AudioCodec libfaac
+#AudioBitRate 32
+#AudioChannels 2
+#AudioSampleRate 22050
+#AVOptionAudio flags +global_header
+#</Stream>
+
 ##################################################################
 # SDP/multicast examples
 #
@@ -350,7 +371,7 @@ ACL allow 192.168.0.0 192.168.255.255
 # Redirect index.html to the appropriate site
 
 <Redirect index.html>
-URL http://www.ffmpeg.org/
+URL http://www.libav.org/
 </Redirect>
 
 
diff --git a/doc/ffserver.texi b/doc/ffserver.texi
new file mode 100644
index 0000000..021b237
--- /dev/null
+++ b/doc/ffserver.texi
@@ -0,0 +1,278 @@
+\input texinfo @c -*- texinfo -*-
+
+ at settitle FFserver Documentation
+ at titlepage
+ at center @titlefont{FFserver Documentation}
+ at end titlepage
+
+ at top
+
+ at contents
+
+ at chapter Synopsys
+
+The generic syntax is:
+
+ at example
+ at c man begin SYNOPSIS
+ffserver [options]
+ at c man end
+ at end example
+
+ at chapter Description
+ at c man begin DESCRIPTION
+
+FFserver is a streaming server for both audio and video. It supports
+several live feeds, streaming from files and time shifting on live feeds
+(you can seek to positions in the past on each live feed, provided you
+specify a big enough feed storage in ffserver.conf).
+
+FFserver runs in daemon mode by default; that is, it puts itself in
+the background and detaches from its TTY, unless it is launched in
+debug mode or a NoDaemon option is specified in the configuration
+file.
+
+This documentation covers only the streaming aspects of ffserver /
+ffmpeg. All questions about parameters for ffmpeg, codec questions,
+etc. are not covered here. Read @file{ffmpeg-doc.html} for more
+information.
+
+ at section How does it work?
+
+FFserver receives prerecorded files or FFM streams from some ffmpeg
+instance as input, then streams them over RTP/RTSP/HTTP.
+
+An ffserver instance will listen on some port as specified in the
+configuration file. You can launch one or more instances of ffmpeg and
+send one or more FFM streams to the port where ffserver is expecting
+to receive them. Alternately, you can make ffserver launch such ffmpeg
+instances at startup.
+
+Input streams are called feeds, and each one is specified by a <Feed>
+section in the configuration file.
+
+For each feed you can have different output streams in various
+formats, each one specified by a <Stream> section in the configuration
+file.
+
+ at section Status stream
+
+FFserver supports an HTTP interface which exposes the current status
+of the server.
+
+Simply point your browser to the address of the special status stream
+specified in the configuration file.
+
+For example if you have:
+ at example
+<Stream status.html>
+Format status
+
+# Only allow local people to get the status
+ACL allow localhost
+ACL allow 192.168.0.0 192.168.255.255
+</Stream>
+ at end example
+
+then the server will post a page with the status information when
+the special stream @file{status.html} is requested.
+
+ at section What can this do?
+
+When properly configured and running, you can capture video and audio in real
+time from a suitable capture card, and stream it out over the Internet to
+either Windows Media Player or RealAudio player (with some restrictions).
+
+It can also stream from files, though that is currently broken. Very often, a
+web server can be used to serve up the files just as well.
+
+It can stream prerecorded video from .ffm files, though it is somewhat tricky
+to make it work correctly.
+
+ at section What do I need?
+
+I use Linux on a 900 MHz Duron with a cheapo Bt848 based TV capture card. I'm
+using stock Linux 2.4.17 with the stock drivers. [Actually that isn't true,
+I needed some special drivers for my motherboard-based sound card.]
+
+I understand that FreeBSD systems work just fine as well.
+
+ at section How do I make it work?
+
+First, build the kit. It *really* helps to have installed LAME first. Then when
+you run the ffserver ./configure, make sure that you have the
+ at code{--enable-libmp3lame} flag turned on.
+
+LAME is important as it allows for streaming audio to Windows Media Player.
+Don't ask why the other audio types do not work.
+
+As a simple test, just run the following two command lines where INPUTFILE
+is some file which you can decode with ffmpeg:
+
+ at example
+./ffserver -f doc/ffserver.conf &
+./ffmpeg -i INPUTFILE http://localhost:8090/feed1.ffm
+ at end example
+
+At this point you should be able to go to your Windows machine and fire up
+Windows Media Player (WMP). Go to Open URL and enter
+
+ at example
+    http://<linuxbox>:8090/test.asf
+ at end example
+
+You should (after a short delay) see video and hear audio.
+
+WARNING: trying to stream test1.mpg doesn't work with WMP as it tries to
+transfer the entire file before starting to play.
+The same is true of AVI files.
+
+ at section What happens next?
+
+You should edit the ffserver.conf file to suit your needs (in terms of
+frame rates etc). Then install ffserver and ffmpeg, write a script to start
+them up, and off you go.
+
+ at section Troubleshooting
+
+ at subsection I don't hear any audio, but video is fine.
+
+Maybe you didn't install LAME, or got your ./configure statement wrong. Check
+the ffmpeg output to see if a line referring to MP3 is present. If not, then
+your configuration was incorrect. If it is, then maybe your wiring is not
+set up correctly. Maybe the sound card is not getting data from the right
+input source. Maybe you have a really awful audio interface (like I do)
+that only captures in stereo and also requires that one channel be flipped.
+If you are one of these people, then export 'AUDIO_FLIP_LEFT=1' before
+starting ffmpeg.
+
+ at subsection The audio and video loose sync after a while.
+
+Yes, they do.
+
+ at subsection After a long while, the video update rate goes way down in WMP.
+
+Yes, it does. Who knows why?
+
+ at subsection WMP 6.4 behaves differently to WMP 7.
+
+Yes, it does. Any thoughts on this would be gratefully received. These
+differences extend to embedding WMP into a web page. [There are two
+object IDs that you can use: The old one, which does not play well, and
+the new one, which does (both tested on the same system). However,
+I suspect that the new one is not available unless you have installed WMP 7].
+
+ at section What else can it do?
+
+You can replay video from .ffm files that was recorded earlier.
+However, there are a number of caveats, including the fact that the
+ffserver parameters must match the original parameters used to record the
+file. If they do not, then ffserver deletes the file before recording into it.
+(Now that I write this, it seems broken).
+
+You can fiddle with many of the codec choices and encoding parameters, and
+there are a bunch more parameters that you cannot control. Post a message
+to the mailing list if there are some 'must have' parameters. Look in
+ffserver.conf for a list of the currently available controls.
+
+It will automatically generate the ASX or RAM files that are often used
+in browsers. These files are actually redirections to the underlying ASF
+or RM file. The reason for this is that the browser often fetches the
+entire file before starting up the external viewer. The redirection files
+are very small and can be transferred quickly. [The stream itself is
+often 'infinite' and thus the browser tries to download it and never
+finishes.]
+
+ at section Tips
+
+* When you connect to a live stream, most players (WMP, RA, etc) want to
+buffer a certain number of seconds of material so that they can display the
+signal continuously. However, ffserver (by default) starts sending data
+in realtime. This means that there is a pause of a few seconds while the
+buffering is being done by the player. The good news is that this can be
+cured by adding a '?buffer=5' to the end of the URL. This means that the
+stream should start 5 seconds in the past -- and so the first 5 seconds
+of the stream are sent as fast as the network will allow. It will then
+slow down to real time. This noticeably improves the startup experience.
+
+You can also add a 'Preroll 15' statement into the ffserver.conf that will
+add the 15 second prebuffering on all requests that do not otherwise
+specify a time. In addition, ffserver will skip frames until a key_frame
+is found. This further reduces the startup delay by not transferring data
+that will be discarded.
+
+* You may want to adjust the MaxBandwidth in the ffserver.conf to limit
+the amount of bandwidth consumed by live streams.
+
+ at section Why does the ?buffer / Preroll stop working after a time?
+
+It turns out that (on my machine at least) the number of frames successfully
+grabbed is marginally less than the number that ought to be grabbed. This
+means that the timestamp in the encoded data stream gets behind realtime.
+This means that if you say 'Preroll 10', then when the stream gets 10
+or more seconds behind, there is no Preroll left.
+
+Fixing this requires a change in the internals of how timestamps are
+handled.
+
+ at section Does the @code{?date=} stuff work.
+
+Yes (subject to the limitation outlined above). Also note that whenever you
+start ffserver, it deletes the ffm file (if any parameters have changed),
+thus wiping out what you had recorded before.
+
+The format of the @code{?date=xxxxxx} is fairly flexible. You should use one
+of the following formats (the 'T' is literal):
+
+ at example
+* YYYY-MM-DDTHH:MM:SS     (localtime)
+* YYYY-MM-DDTHH:MM:SSZ    (UTC)
+ at end example
+
+You can omit the YYYY-MM-DD, and then it refers to the current day. However
+note that @samp{?date=16:00:00} refers to 16:00 on the current day -- this
+may be in the future and so is unlikely to be useful.
+
+You use this by adding the ?date= to the end of the URL for the stream.
+For example:   @samp{http://localhost:8080/test.asf?date=2002-07-26T23:05:00}.
+ at c man end
+
+ at chapter Options
+ at c man begin OPTIONS
+
+ at include fftools-common-opts.texi
+
+ at section Main options
+
+ at table @option
+ at item -f @var{configfile}
+Use @file{configfile} instead of @file{/etc/ffserver.conf}.
+ at item -n
+Enable no-launch mode. This option disables all the Launch directives
+within the various <Stream> sections. FFserver will not launch any
+ffmpeg instance, so you will have to launch them manually.
+ at item -d
+Enable debug mode. This option increases log verbosity, directs log
+messages to stdout and causes ffserver to run in the foreground
+rather than as a daemon.
+ at end table
+ at c man end
+
+ at ignore
+
+ at setfilename ffserver
+ at settitle FFserver video server
+
+ at c man begin SEEALSO
+
+ffmpeg(1), ffplay(1), ffprobe(1), the @file{ffmpeg/doc/ffserver.conf}
+example and the Libav HTML documentation
+ at c man end
+
+ at c man begin AUTHORS
+The Libav developers
+ at c man end
+
+ at end ignore
+
+ at bye
diff --git a/doc/fftools-common-opts.texi b/doc/fftools-common-opts.texi
index 4fc271d..3a1cb3b 100644
--- a/doc/fftools-common-opts.texi
+++ b/doc/fftools-common-opts.texi
@@ -1,3 +1,16 @@
+All the numerical options, if not specified otherwise, accept in input
+a string representing a number, which may contain one of the
+International System number postfixes, for example 'K', 'M', 'G'.
+If 'i' is appended after the postfix, powers of 2 are used instead of
+powers of 10. The 'B' postfix multiplies the value for 8, and can be
+appended after another postfix or used alone. This allows using for
+example 'KB', 'MiB', 'G' and 'B' as postfix.
+
+Options which do not take arguments are boolean options, and set the
+corresponding value to true. They can be set to false by prefixing
+with "no" the option name, for example using "-nofoo" in the
+commandline will set to false the boolean option with name "foo".
+
 @section Generic options
 
 These options are shared amongst the ff* tools.
@@ -69,4 +82,12 @@ Set the logging level used by the library.
 @item debug
 @end table
 
+By default the program logs to stderr, if coloring is supported by the
+terminal, colors are used to mark errors and warnings. Log coloring
+can be disabled setting the environment variable
+ at env{FFMPEG_FORCE_NOCOLOR} or @env{NO_COLOR}, or can be forced setting
+the environment variable @env{FFMPEG_FORCE_COLOR}.
+The use of the environment variable @env{NO_COLOR} is deprecated and
+will be dropped in a following Libav version.
+
 @end table
diff --git a/doc/filters.texi b/doc/filters.texi
new file mode 100644
index 0000000..1a26f10
--- /dev/null
+++ b/doc/filters.texi
@@ -0,0 +1,1297 @@
+ at chapter Filtergraph description
+ at c man begin FILTERGRAPH DESCRIPTION
+
+A filtergraph is a directed graph of connected filters. It can contain
+cycles, and there can be multiple links between a pair of
+filters. Each link has one input pad on one side connecting it to one
+filter from which it takes its input, and one output pad on the other
+side connecting it to the one filter accepting its output.
+
+Each filter in a filtergraph is an instance of a filter class
+registered in the application, which defines the features and the
+number of input and output pads of the filter.
+
+A filter with no input pads is called a "source", a filter with no
+output pads is called a "sink".
+
+ at section Filtergraph syntax
+
+A filtergraph can be represented using a textual representation, which
+is recognized by the @code{-vf} and @code{-af} options of the ff*
+tools, and by the @code{av_parse_graph()} function defined in
+ at file{libavfilter/avfiltergraph}.
+
+A filterchain consists of a sequence of connected filters, each one
+connected to the previous one in the sequence. A filterchain is
+represented by a list of ","-separated filter descriptions.
+
+A filtergraph consists of a sequence of filterchains. A sequence of
+filterchains is represented by a list of ";"-separated filterchain
+descriptions.
+
+A filter is represented by a string of the form:
+[@var{in_link_1}]...[@var{in_link_N}]@var{filter_name}=@var{arguments}[@var{out_link_1}]...[@var{out_link_M}]
+
+ at var{filter_name} is the name of the filter class of which the
+described filter is an instance of, and has to be the name of one of
+the filter classes registered in the program.
+The name of the filter class is optionally followed by a string
+"=@var{arguments}".
+
+ at var{arguments} is a string which contains the parameters used to
+initialize the filter instance, and are described in the filter
+descriptions below.
+
+The list of arguments can be quoted using the character "'" as initial
+and ending mark, and the character '\' for escaping the characters
+within the quoted text; otherwise the argument string is considered
+terminated when the next special character (belonging to the set
+"[]=;,") is encountered.
+
+The name and arguments of the filter are optionally preceded and
+followed by a list of link labels.
+A link label allows to name a link and associate it to a filter output
+or input pad. The preceding labels @var{in_link_1}
+... @var{in_link_N}, are associated to the filter input pads,
+the following labels @var{out_link_1} ... @var{out_link_M}, are
+associated to the output pads.
+
+When two link labels with the same name are found in the
+filtergraph, a link between the corresponding input and output pad is
+created.
+
+If an output pad is not labelled, it is linked by default to the first
+unlabelled input pad of the next filter in the filterchain.
+For example in the filterchain:
+ at example
+nullsrc, split[L1], [L2]overlay, nullsink
+ at end example
+the split filter instance has two output pads, and the overlay filter
+instance two input pads. The first output pad of split is labelled
+"L1", the first input pad of overlay is labelled "L2", and the second
+output pad of split is linked to the second input pad of overlay,
+which are both unlabelled.
+
+In a complete filterchain all the unlabelled filter input and output
+pads must be connected. A filtergraph is considered valid if all the
+filter input and output pads of all the filterchains are connected.
+
+Follows a BNF description for the filtergraph syntax:
+ at example
+ at var{NAME}             ::= sequence of alphanumeric characters and '_'
+ at var{LINKLABEL}        ::= "[" @var{NAME} "]"
+ at var{LINKLABELS}       ::= @var{LINKLABEL} [@var{LINKLABELS}]
+ at var{FILTER_ARGUMENTS} ::= sequence of chars (eventually quoted)
+ at var{FILTER}           ::= [@var{LINKNAMES}] @var{NAME} ["=" @var{ARGUMENTS}] [@var{LINKNAMES}]
+ at var{FILTERCHAIN}      ::= @var{FILTER} [, at var{FILTERCHAIN}]
+ at var{FILTERGRAPH}      ::= @var{FILTERCHAIN} [;@var{FILTERGRAPH}]
+ at end example
+
+ at c man end FILTERGRAPH DESCRIPTION
+
+ at chapter Audio Filters
+ at c man begin AUDIO FILTERS
+
+When you configure your Libav build, you can disable any of the
+existing filters using --disable-filters.
+The configure output will show the audio filters included in your
+build.
+
+Below is a description of the currently available audio filters.
+
+ at section anull
+
+Pass the audio source unchanged to the output.
+
+ at c man end AUDIO FILTERS
+
+ at chapter Audio Sources
+ at c man begin AUDIO SOURCES
+
+Below is a description of the currently available audio sources.
+
+ at section anullsrc
+
+Null audio source, never return audio frames. It is mainly useful as a
+template and to be employed in analysis / debugging tools.
+
+It accepts as optional parameter a string of the form
+ at var{sample_rate}:@var{channel_layout}.
+
+ at var{sample_rate} specify the sample rate, and defaults to 44100.
+
+ at var{channel_layout} specify the channel layout, and can be either an
+integer or a string representing a channel layout. The default value
+of @var{channel_layout} is 3, which corresponds to CH_LAYOUT_STEREO.
+
+Check the channel_layout_map definition in
+ at file{libavcodec/audioconvert.c} for the mapping between strings and
+channel layout values.
+
+Follow some examples:
+ at example
+#  set the sample rate to 48000 Hz and the channel layout to CH_LAYOUT_MONO.
+anullsrc=48000:4
+
+# same as
+anullsrc=48000:mono
+ at end example
+
+ at c man end AUDIO SOURCES
+
+ at chapter Audio Sinks
+ at c man begin AUDIO SINKS
+
+Below is a description of the currently available audio sinks.
+
+ at section anullsink
+
+Null audio sink, do absolutely nothing with the input audio. It is
+mainly useful as a template and to be employed in analysis / debugging
+tools.
+
+ at c man end AUDIO SINKS
+
+ at chapter Video Filters
+ at c man begin VIDEO FILTERS
+
+When you configure your Libav build, you can disable any of the
+existing filters using --disable-filters.
+The configure output will show the video filters included in your
+build.
+
+Below is a description of the currently available video filters.
+
+ at section blackframe
+
+Detect frames that are (almost) completely black. Can be useful to
+detect chapter transitions or commercials. Output lines consist of
+the frame number of the detected frame, the percentage of blackness,
+the position in the file if known or -1 and the timestamp in seconds.
+
+In order to display the output lines, you need to set the loglevel at
+least to the AV_LOG_INFO value.
+
+The filter accepts the syntax:
+ at example
+blackframe[=@var{amount}:[@var{threshold}]]
+ at end example
+
+ at var{amount} is the percentage of the pixels that have to be below the
+threshold, and defaults to 98.
+
+ at var{threshold} is the threshold below which a pixel value is
+considered black, and defaults to 32.
+
+ at section copy
+
+Copy the input source unchanged to the output. Mainly useful for
+testing purposes.
+
+ at section crop
+
+Crop the input video to @var{out_w}:@var{out_h}:@var{x}:@var{y}.
+
+The parameters are expressions containing the following constants:
+
+ at table @option
+ at item E, PI, PHI
+the corresponding mathematical approximated values for e
+(euler number), pi (greek PI), PHI (golden ratio)
+
+ at item x, y
+the computed values for @var{x} and @var{y}. They are evaluated for
+each new frame.
+
+ at item in_w, in_h
+the input width and heigth
+
+ at item iw, ih
+same as @var{in_w} and @var{in_h}
+
+ at item out_w, out_h
+the output (cropped) width and heigth
+
+ at item ow, oh
+same as @var{out_w} and @var{out_h}
+
+ at item n
+the number of input frame, starting from 0
+
+ at item pos
+the position in the file of the input frame, NAN if unknown
+
+ at item t
+timestamp expressed in seconds, NAN if the input timestamp is unknown
+
+ at end table
+
+The @var{out_w} and @var{out_h} parameters specify the expressions for
+the width and height of the output (cropped) video. They are
+evaluated just at the configuration of the filter.
+
+The default value of @var{out_w} is "in_w", and the default value of
+ at var{out_h} is "in_h".
+
+The expression for @var{out_w} may depend on the value of @var{out_h},
+and the expression for @var{out_h} may depend on @var{out_w}, but they
+cannot depend on @var{x} and @var{y}, as @var{x} and @var{y} are
+evaluated after @var{out_w} and @var{out_h}.
+
+The @var{x} and @var{y} parameters specify the expressions for the
+position of the top-left corner of the output (non-cropped) area. They
+are evaluated for each frame. If the evaluated value is not valid, it
+is approximated to the nearest valid value.
+
+The default value of @var{x} is "(in_w-out_w)/2", and the default
+value for @var{y} is "(in_h-out_h)/2", which set the cropped area at
+the center of the input image.
+
+The expression for @var{x} may depend on @var{y}, and the expression
+for @var{y} may depend on @var{x}.
+
+Follow some examples:
+ at example
+# crop the central input area with size 100x100
+crop=100:100
+
+# crop the central input area with size 2/3 of the input video
+"crop=2/3*in_w:2/3*in_h"
+
+# crop the input video central square
+crop=in_h
+
+# delimit the rectangle with the top-left corner placed at position
+# 100:100 and the right-bottom corner corresponding to the right-bottom
+# corner of the input image.
+crop=in_w-100:in_h-100:100:100
+
+# crop 10 pixels from the left and right borders, and 20 pixels from
+# the top and bottom borders
+"crop=in_w-2*10:in_h-2*20"
+
+# keep only the bottom right quarter of the input image
+"crop=in_w/2:in_h/2:in_w/2:in_h/2"
+
+# crop height for getting Greek harmony
+"crop=in_w:1/PHI*in_w"
+
+# trembling effect
+"crop=in_w/2:in_h/2:(in_w-out_w)/2+((in_w-out_w)/2)*sin(n/10):(in_h-out_h)/2 +((in_h-out_h)/2)*sin(n/7)"
+
+# erratic camera effect depending on timestamp
+"crop=in_w/2:in_h/2:(in_w-out_w)/2+((in_w-out_w)/2)*sin(t*10):(in_h-out_h)/2 +((in_h-out_h)/2)*sin(t*13)"
+
+# set x depending on the value of y
+"crop=in_w/2:in_h/2:y:10+10*sin(n/10)"
+ at end example
+
+ at section cropdetect
+
+Auto-detect crop size.
+
+Calculate necessary cropping parameters and prints the recommended
+parameters through the logging system. The detected dimensions
+correspond to the non-black area of the input video.
+
+It accepts the syntax:
+ at example
+cropdetect[=@var{limit}[:@var{round}[:@var{reset}]]]
+ at end example
+
+ at table @option
+
+ at item limit
+Threshold, which can be optionally specified from nothing (0) to
+everything (255), defaults to 24.
+
+ at item round
+Value which the width/height should be divisible by, defaults to
+16. The offset is automatically adjusted to center the video. Use 2 to
+get only even dimensions (needed for 4:2:2 video). 16 is best when
+encoding to most video codecs.
+
+ at item reset
+Counter that determines after how many frames cropdetect will reset
+the previously detected largest video area and start over to detect
+the current optimal crop area. Defaults to 0.
+
+This can be useful when channel logos distort the video area. 0
+indicates never reset and return the largest area encountered during
+playback.
+ at end table
+
+ at section drawbox
+
+Draw a colored box on the input image.
+
+It accepts the syntax:
+ at example
+drawbox=@var{x}:@var{y}:@var{width}:@var{height}:@var{color}
+ at end example
+
+ at table @option
+
+ at item x, y
+Specify the top left corner coordinates of the box. Default to 0.
+
+ at item width, height
+Specify the width and height of the box, if 0 they are interpreted as
+the input width and height. Default to 0.
+
+ at item color
+Specify the color of the box to write, it can be the name of a color
+(case insensitive match) or a 0xRRGGBB[AA] sequence.
+ at end table
+
+Follow some examples:
+ at example
+# draw a black box around the edge of the input image
+drawbox
+
+# draw a box with color red and an opacity of 50%
+drawbox=10:20:200:60:red@@0.5"
+ at end example
+
+ at section fade
+
+Apply fade-in/out effect to input video.
+
+It accepts the parameters:
+ at var{type}:@var{start_frame}:@var{nb_frames}
+
+ at var{type} specifies if the effect type, can be either "in" for
+fade-in, or "out" for a fade-out effect.
+
+ at var{start_frame} specifies the number of the start frame for starting
+to apply the fade effect.
+
+ at var{nb_frames} specifies the number of frames for which the fade
+effect has to last. At the end of the fade-in effect the output video
+will have the same intensity as the input video, at the end of the
+fade-out transition the output video will be completely black.
+
+A few usage examples follow, usable too as test scenarios.
+ at example
+# fade in first 30 frames of video
+fade=in:0:30
+
+# fade out last 45 frames of a 200-frame video
+fade=out:155:45
+
+# fade in first 25 frames and fade out last 25 frames of a 1000-frame video
+fade=in:0:25, fade=out:975:25
+
+# make first 5 frames black, then fade in from frame 5-24
+fade=in:5:20
+ at end example
+
+ at section fifo
+
+Buffer input images and send them when they are requested.
+
+This filter is mainly useful when auto-inserted by the libavfilter
+framework.
+
+The filter does not take parameters.
+
+ at section format
+
+Convert the input video to one of the specified pixel formats.
+Libavfilter will try to pick one that is supported for the input to
+the next filter.
+
+The filter accepts a list of pixel format names, separated by ":",
+for example "yuv420p:monow:rgb24".
+
+Some examples follow:
+ at example
+# convert the input video to the format "yuv420p"
+format=yuv420p
+
+# convert the input video to any of the formats in the list
+format=yuv420p:yuv444p:yuv410p
+ at end example
+
+ at anchor{frei0r}
+ at section frei0r
+
+Apply a frei0r effect to the input video.
+
+To enable compilation of this filter you need to install the frei0r
+header and configure Libav with --enable-frei0r.
+
+The filter supports the syntax:
+ at example
+ at var{filter_name}[@{:|=@}@var{param1}:@var{param2}:...:@var{paramN}]
+ at end example
+
+ at var{filter_name} is the name to the frei0r effect to load. If the
+environment variable @env{FREI0R_PATH} is defined, the frei0r effect
+is searched in each one of the directories specified by the colon
+separated list in @env{FREIOR_PATH}, otherwise in the standard frei0r
+paths, which are in this order: @file{HOME/.frei0r-1/lib/},
+ at file{/usr/local/lib/frei0r-1/}, @file{/usr/lib/frei0r-1/}.
+
+ at var{param1}, @var{param2}, ... , @var{paramN} specify the parameters
+for the frei0r effect.
+
+A frei0r effect parameter can be a boolean (whose values are specified
+with "y" and "n"), a double, a color (specified by the syntax
+ at var{R}/@var{G}/@var{B}, @var{R}, @var{G}, and @var{B} being float
+numbers from 0.0 to 1.0) or by an @code{av_parse_color()} color
+description), a position (specified by the syntax @var{X}/@var{Y},
+ at var{X} and @var{Y} being float numbers) and a string.
+
+The number and kind of parameters depend on the loaded effect. If an
+effect parameter is not specified the default value is set.
+
+Some examples follow:
+ at example
+# apply the distort0r effect, set the first two double parameters
+frei0r=distort0r:0.5:0.01
+
+# apply the colordistance effect, takes a color as first parameter
+frei0r=colordistance:0.2/0.3/0.4
+frei0r=colordistance:violet
+frei0r=colordistance:0x112233
+
+# apply the perspective effect, specify the top left and top right
+# image positions
+frei0r=perspective:0.2/0.2:0.8/0.2
+ at end example
+
+For more information see:
+ at url{http://piksel.org/frei0r}
+
+ at section gradfun
+
+Fix the banding artifacts that are sometimes introduced into nearly flat
+regions by truncation to 8bit colordepth.
+Interpolate the gradients that should go where the bands are, and
+dither them.
+
+This filter is designed for playback only.  Do not use it prior to
+lossy compression, because compression tends to lose the dither and
+bring back the bands.
+
+The filter takes two optional parameters, separated by ':':
+ at var{strength}:@var{radius}
+
+ at var{strength} is the maximum amount by which the filter will change
+any one pixel. Also the threshold for detecting nearly flat
+regions. Acceptable values range from .51 to 255, default value is
+1.2, out-of-range values will be clipped to the valid range.
+
+ at var{radius} is the neighborhood to fit the gradient to. A larger
+radius makes for smoother gradients, but also prevents the filter from
+modifying the pixels near detailed regions. Acceptable values are
+8-32, default value is 16, out-of-range values will be clipped to the
+valid range.
+
+ at example
+# default parameters
+gradfun=1.2:16
+
+# omitting radius
+gradfun=1.2
+ at end example
+
+ at section hflip
+
+Flip the input video horizontally.
+
+For example to horizontally flip the video in input with
+ at file{ffmpeg}:
+ at example
+ffmpeg -i in.avi -vf "hflip" out.avi
+ at end example
+
+ at section hqdn3d
+
+High precision/quality 3d denoise filter. This filter aims to reduce
+image noise producing smooth images and making still images really
+still. It should enhance compressibility.
+
+It accepts the following optional parameters:
+ at var{luma_spatial}:@var{chroma_spatial}:@var{luma_tmp}:@var{chroma_tmp}
+
+ at table @option
+ at item luma_spatial
+a non-negative float number which specifies spatial luma strength,
+defaults to 4.0
+
+ at item chroma_spatial
+a non-negative float number which specifies spatial chroma strength,
+defaults to 3.0*@var{luma_spatial}/4.0
+
+ at item luma_tmp
+a float number which specifies luma temporal strength, defaults to
+6.0*@var{luma_spatial}/4.0
+
+ at item chroma_tmp
+a float number which specifies chroma temporal strength, defaults to
+ at var{luma_tmp}*@var{chroma_spatial}/@var{luma_spatial}
+ at end table
+
+ at section noformat
+
+Force libavfilter not to use any of the specified pixel formats for the
+input to the next filter.
+
+The filter accepts a list of pixel format names, separated by ":",
+for example "yuv420p:monow:rgb24".
+
+Some examples follow:
+ at example
+# force libavfilter to use a format different from "yuv420p" for the
+# input to the vflip filter
+noformat=yuv420p,vflip
+
+# convert the input video to any of the formats not contained in the list
+noformat=yuv420p:yuv444p:yuv410p
+ at end example
+
+ at section null
+
+Pass the video source unchanged to the output.
+
+ at section ocv
+
+Apply video transform using libopencv.
+
+To enable this filter install libopencv library and headers and
+configure Libav with --enable-libopencv.
+
+The filter takes the parameters: @var{filter_name}@{:=@}@var{filter_params}.
+
+ at var{filter_name} is the name of the libopencv filter to apply.
+
+ at var{filter_params} specifies the parameters to pass to the libopencv
+filter. If not specified the default values are assumed.
+
+Refer to the official libopencv documentation for more precise
+informations:
+ at url{http://opencv.willowgarage.com/documentation/c/image_filtering.html}
+
+Follows the list of supported libopencv filters.
+
+ at anchor{dilate}
+ at subsection dilate
+
+Dilate an image by using a specific structuring element.
+This filter corresponds to the libopencv function @code{cvDilate}.
+
+It accepts the parameters: @var{struct_el}:@var{nb_iterations}.
+
+ at var{struct_el} represents a structuring element, and has the syntax:
+ at var{cols}x at var{rows}+ at var{anchor_x}x at var{anchor_y}/@var{shape}
+
+ at var{cols} and @var{rows} represent the number of colums and rows of
+the structuring element, @var{anchor_x} and @var{anchor_y} the anchor
+point, and @var{shape} the shape for the structuring element, and
+can be one of the values "rect", "cross", "ellipse", "custom".
+
+If the value for @var{shape} is "custom", it must be followed by a
+string of the form "=@var{filename}". The file with name
+ at var{filename} is assumed to represent a binary image, with each
+printable character corresponding to a bright pixel. When a custom
+ at var{shape} is used, @var{cols} and @var{rows} are ignored, the number
+or columns and rows of the read file are assumed instead.
+
+The default value for @var{struct_el} is "3x3+0x0/rect".
+
+ at var{nb_iterations} specifies the number of times the transform is
+applied to the image, and defaults to 1.
+
+Follow some example:
+ at example
+# use the default values
+ocv=dilate
+
+# dilate using a structuring element with a 5x5 cross, iterate two times
+ocv=dilate=5x5+2x2/cross:2
+
+# read the shape from the file diamond.shape, iterate two times
+# the file diamond.shape may contain a pattern of characters like this:
+#   *
+#  ***
+# *****
+#  ***
+#   *
+# the specified cols and rows are ignored (but not the anchor point coordinates)
+ocv=0x0+2x2/custom=diamond.shape:2
+ at end example
+
+ at subsection erode
+
+Erode an image by using a specific structuring element.
+This filter corresponds to the libopencv function @code{cvErode}.
+
+The filter accepts the parameters: @var{struct_el}:@var{nb_iterations},
+with the same meaning and use of those of the dilate filter
+(@pxref{dilate}).
+
+ at subsection smooth
+
+Smooth the input video.
+
+The filter takes the following parameters:
+ at var{type}:@var{param1}:@var{param2}:@var{param3}:@var{param4}.
+
+ at var{type} is the type of smooth filter to apply, and can be one of
+the following values: "blur", "blur_no_scale", "median", "gaussian",
+"bilateral". The default value is "gaussian".
+
+ at var{param1}, @var{param2}, @var{param3}, and @var{param4} are
+parameters whose meanings depend on smooth type. @var{param1} and
+ at var{param2} accept integer positive values or 0, @var{param3} and
+ at var{param4} accept float values.
+
+The default value for @var{param1} is 3, the default value for the
+other parameters is 0.
+
+These parameters correspond to the parameters assigned to the
+libopencv function @code{cvSmooth}.
+
+ at section overlay
+
+Overlay one video on top of another.
+
+It takes two inputs and one output, the first input is the "main"
+video on which the second input is overlayed.
+
+It accepts the parameters: @var{x}:@var{y}.
+
+ at var{x} is the x coordinate of the overlayed video on the main video,
+ at var{y} is the y coordinate. The parameters are expressions containing
+the following parameters:
+
+ at table @option
+ at item main_w, main_h
+main input width and height
+
+ at item W, H
+same as @var{main_w} and @var{main_h}
+
+ at item overlay_w, overlay_h
+overlay input width and height
+
+ at item w, h
+same as @var{overlay_w} and @var{overlay_h}
+ at end table
+
+Be aware that frames are taken from each input video in timestamp
+order, hence, if their initial timestamps differ, it is a a good idea
+to pass the two inputs through a @var{setpts=PTS-STARTPTS} filter to
+have them begin in the same zero timestamp, as it does the example for
+the @var{movie} filter.
+
+Follow some examples:
+ at example
+# draw the overlay at 10 pixels from the bottom right
+# corner of the main video.
+overlay=main_w-overlay_w-10:main_h-overlay_h-10
+
+# insert a transparent PNG logo in the bottom left corner of the input
+movie=logo.png [logo];
+[in][logo] overlay=10:main_h-overlay_h-10 [out]
+
+# insert 2 different transparent PNG logos (second logo on bottom
+# right corner):
+movie=logo1.png [logo1];
+movie=logo2.png [logo2];
+[in][logo1]       overlay=10:H-h-10 [in+logo1];
+[in+logo1][logo2] overlay=W-w-10:H-h-10 [out]
+
+# add a transparent color layer on top of the main video,
+# WxH specifies the size of the main input to the overlay filter
+color=red at .3:WxH [over]; [in][over] overlay [out]
+ at end example
+
+You can chain togheter more overlays but the efficiency of such
+approach is yet to be tested.
+
+ at section pad
+
+Add paddings to the input image, and places the original input at the
+given coordinates @var{x}, @var{y}.
+
+It accepts the following parameters:
+ at var{width}:@var{height}:@var{x}:@var{y}:@var{color}.
+
+Follows the description of the accepted parameters.
+
+ at table @option
+ at item width, height
+
+Specify the size of the output image with the paddings added. If the
+value for @var{width} or @var{height} is 0, the corresponding input size
+is used for the output.
+
+The default value of @var{width} and @var{height} is 0.
+
+ at item x, y
+
+Specify the offsets where to place the input image in the padded area
+with respect to the top/left border of the output image.
+
+The default value of @var{x} and @var{y} is 0.
+
+ at item color
+
+Specify the color of the padded area, it can be the name of a color
+(case insensitive match) or a 0xRRGGBB[AA] sequence.
+
+The default value of @var{color} is "black".
+
+ at end table
+
+For example:
+
+ at example
+# Add paddings with color "violet" to the input video. Output video
+# size is 640x480, the top-left corner of the input video is placed at
+# column 0, row 40.
+pad=640:480:0:40:violet
+ at end example
+
+ at section pixdesctest
+
+Pixel format descriptor test filter, mainly useful for internal
+testing. The output video should be equal to the input video.
+
+For example:
+ at example
+format=monow, pixdesctest
+ at end example
+
+can be used to test the monowhite pixel format descriptor definition.
+
+ at section scale
+
+Scale the input video to @var{width}:@var{height} and/or convert the image format.
+
+For example the command:
+
+ at example
+./ffmpeg -i in.avi -vf "scale=200:100" out.avi
+ at end example
+
+will scale the input video to a size of 200x100.
+
+If the input image format is different from the format requested by
+the next filter, the scale filter will convert the input to the
+requested format.
+
+If the value for @var{width} or @var{height} is 0, the respective input
+size is used for the output.
+
+If the value for @var{width} or @var{height} is -1, the scale filter will
+use, for the respective output size, a value that maintains the aspect
+ratio of the input image.
+
+The default value of @var{width} and @var{height} is 0.
+
+ at anchor{setdar}
+ at section setdar
+
+Set the Display Aspect Ratio for the filter output video.
+
+This is done by changing the specified Sample (aka Pixel) Aspect
+Ratio, according to the following equation:
+ at math{DAR = HORIZONTAL_RESOLUTION / VERTICAL_RESOLUTION * SAR}
+
+Keep in mind that this filter does not modify the pixel dimensions of
+the video frame. Also the display aspect ratio set by this filter may
+be changed by later filters in the filterchain, e.g. in case of
+scaling or if another "setdar" or a "setsar" filter is applied.
+
+The filter accepts a parameter string which represents the wanted
+display aspect ratio.
+The parameter can be a floating point number string, or an expression
+of the form @var{num}:@var{den}, where @var{num} and @var{den} are the
+numerator and denominator of the aspect ratio.
+If the parameter is not specified, it is assumed the value "0:1".
+
+For example to change the display aspect ratio to 16:9, specify:
+ at example
+setdar=16:9
+# the above is equivalent to
+setdar=1.77777
+ at end example
+
+See also the "setsar" filter documentation (@pxref{setsar}).
+
+ at section setpts
+
+Change the PTS (presentation timestamp) of the input video frames.
+
+Accept in input an expression evaluated through the eval API, which
+can contain the following constants:
+
+ at table @option
+ at item PTS
+the presentation timestamp in input
+
+ at item PI
+Greek PI
+
+ at item PHI
+golden ratio
+
+ at item E
+Euler number
+
+ at item N
+the count of the input frame, starting from 0.
+
+ at item STARTPTS
+the PTS of the first video frame
+
+ at item INTERLACED
+tell if the current frame is interlaced
+
+ at item POS
+original position in the file of the frame, or undefined if undefined
+for the current frame
+
+ at item PREV_INPTS
+previous input PTS
+
+ at item PREV_OUTPTS
+previous output PTS
+
+ at end table
+
+Some examples follow:
+
+ at example
+# start counting PTS from zero
+setpts=PTS-STARTPTS
+
+# fast motion
+setpts=0.5*PTS
+
+# slow motion
+setpts=2.0*PTS
+
+# fixed rate 25 fps
+setpts=N/(25*TB)
+
+# fixed rate 25 fps with some jitter
+setpts='1/(25*TB) * (N + 0.05 * sin(N*2*PI/25))'
+ at end example
+
+ at anchor{setsar}
+ at section setsar
+
+Set the Sample (aka Pixel) Aspect Ratio for the filter output video.
+
+Note that as a consequence of the application of this filter, the
+output display aspect ratio will change according to the following
+equation:
+ at math{DAR = HORIZONTAL_RESOLUTION / VERTICAL_RESOLUTION * SAR}
+
+Keep in mind that the sample aspect ratio set by this filter may be
+changed by later filters in the filterchain, e.g. if another "setsar"
+or a "setdar" filter is applied.
+
+The filter accepts a parameter string which represents the wanted
+sample aspect ratio.
+The parameter can be a floating point number string, or an expression
+of the form @var{num}:@var{den}, where @var{num} and @var{den} are the
+numerator and denominator of the aspect ratio.
+If the parameter is not specified, it is assumed the value "0:1".
+
+For example to change the sample aspect ratio to 10:11, specify:
+ at example
+setsar=10:11
+ at end example
+
+ at section settb
+
+Set the timebase to use for the output frames timestamps.
+It is mainly useful for testing timebase configuration.
+
+It accepts in input an arithmetic expression representing a rational.
+The expression can contain the constants "PI", "E", "PHI", "AVTB" (the
+default timebase), and "intb" (the input timebase).
+
+The default value for the input is "intb".
+
+Follow some examples.
+
+ at example
+# set the timebase to 1/25
+settb=1/25
+
+# set the timebase to 1/10
+settb=0.1
+
+#set the timebase to 1001/1000
+settb=1+0.001
+
+#set the timebase to 2*intb
+settb=2*intb
+
+#set the default timebase value
+settb=AVTB
+ at end example
+
+ at section slicify
+
+Pass the images of input video on to next video filter as multiple
+slices.
+
+ at example
+./ffmpeg -i in.avi -vf "slicify=32" out.avi
+ at end example
+
+The filter accepts the slice height as parameter. If the parameter is
+not specified it will use the default value of 16.
+
+Adding this in the beginning of filter chains should make filtering
+faster due to better use of the memory cache.
+
+ at section transpose
+
+Transpose rows with columns in the input video and optionally flip it.
+
+It accepts a parameter representing an integer, which can assume the
+values:
+
+ at table @samp
+ at item 0
+Rotate by 90 degrees counterclockwise and vertically flip (default), that is:
+ at example
+L.R     L.l
+. . ->  . .
+l.r     R.r
+ at end example
+
+ at item 1
+Rotate by 90 degrees clockwise, that is:
+ at example
+L.R     l.L
+. . ->  . .
+l.r     r.R
+ at end example
+
+ at item 2
+Rotate by 90 degrees counterclockwise, that is:
+ at example
+L.R     R.r
+. . ->  . .
+l.r     L.l
+ at end example
+
+ at item 3
+Rotate by 90 degrees clockwise and vertically flip, that is:
+ at example
+L.R     r.R
+. . ->  . .
+l.r     l.L
+ at end example
+ at end table
+
+ at section unsharp
+
+Sharpen or blur the input video.
+
+It accepts the following parameters:
+ at var{luma_msize_x}:@var{luma_msize_y}:@var{luma_amount}:@var{chroma_msize_x}:@var{chroma_msize_y}:@var{chroma_amount}
+
+Negative values for the amount will blur the input video, while positive
+values will sharpen. All parameters are optional and default to the
+equivalent of the string '5:5:1.0:0:0:0.0'.
+
+ at table @option
+
+ at item luma_msize_x
+Set the luma matrix horizontal size. It can be an integer between 3
+and 13, default value is 5.
+
+ at item luma_msize_y
+Set the luma matrix vertical size. It can be an integer between 3
+and 13, default value is 5.
+
+ at item luma_amount
+Set the luma effect strength. It can be a float number between -2.0
+and 5.0, default value is 1.0.
+
+ at item chroma_msize_x
+Set the chroma matrix horizontal size. It can be an integer between 3
+and 13, default value is 0.
+
+ at item chroma_msize_y
+Set the chroma matrix vertical size. It can be an integer between 3
+and 13, default value is 0.
+
+ at item luma_amount
+Set the chroma effect strength. It can be a float number between -2.0
+and 5.0, default value is 0.0.
+
+ at end table
+
+ at example
+# Strong luma sharpen effect parameters
+unsharp=7:7:2.5
+
+# Strong blur of both luma and chroma parameters
+unsharp=7:7:-2:7:7:-2
+
+# Use the default values with @command{ffmpeg}
+./ffmpeg -i in.avi -vf "unsharp" out.mp4
+ at end example
+
+ at section vflip
+
+Flip the input video vertically.
+
+ at example
+./ffmpeg -i in.avi -vf "vflip" out.avi
+ at end example
+
+ at section yadif
+
+Deinterlace the input video ("yadif" means "yet another deinterlacing
+filter").
+
+It accepts the optional parameters: @var{mode}:@var{parity}.
+
+ at var{mode} specifies the interlacing mode to adopt, accepts one of the
+following values:
+
+ at table @option
+ at item 0
+output 1 frame for each frame
+ at item 1
+output 1 frame for each field
+ at item 2
+like 0 but skips spatial interlacing check
+ at item 3
+like 1 but skips spatial interlacing check
+ at end table
+
+Default value is 0.
+
+ at var{parity} specifies the picture field parity assumed for the input
+interlaced video, accepts one of the following values:
+
+ at table @option
+ at item 0
+assume bottom field first
+ at item 1
+assume top field first
+ at item -1
+enable automatic detection
+ at end table
+
+Default value is -1.
+If interlacing is unknown or decoder does not export this information,
+top field first will be assumed.
+
+ at c man end VIDEO FILTERS
+
+ at chapter Video Sources
+ at c man begin VIDEO SOURCES
+
+Below is a description of the currently available video sources.
+
+ at section buffer
+
+Buffer video frames, and make them available to the filter chain.
+
+This source is mainly intended for a programmatic use, in particular
+through the interface defined in @file{libavfilter/vsrc_buffer.h}.
+
+It accepts the following parameters:
+ at var{width}:@var{height}:@var{pix_fmt_string}:@var{timebase_num}:@var{timebase_den}
+
+All the parameters need to be explicitely defined.
+
+Follows the list of the accepted parameters.
+
+ at table @option
+
+ at item width, height
+Specify the width and height of the buffered video frames.
+
+ at item pix_fmt_string
+A string representing the pixel format of the buffered video frames.
+It may be a number corresponding to a pixel format, or a pixel format
+name.
+
+ at item timebase_num, timebase_den
+Specify numerator and denomitor of the timebase assumed by the
+timestamps of the buffered frames.
+ at end table
+
+For example:
+ at example
+buffer=320:240:yuv410p:1:24
+ at end example
+
+will instruct the source to accept video frames with size 320x240 and
+with format "yuv410p" and assuming 1/24 as the timestamps timebase.
+Since the pixel format with name "yuv410p" corresponds to the number 6
+(check the enum PixelFormat definition in @file{libavutil/pixfmt.h}),
+this example corresponds to:
+ at example
+buffer=320:240:6:1:24
+ at end example
+
+ at section color
+
+Provide an uniformly colored input.
+
+It accepts the following parameters:
+ at var{color}:@var{frame_size}:@var{frame_rate}
+
+Follows the description of the accepted parameters.
+
+ at table @option
+
+ at item color
+Specify the color of the source. It can be the name of a color (case
+insensitive match) or a 0xRRGGBB[AA] sequence, possibly followed by an
+alpha specifier. The default value is "black".
+
+ at item frame_size
+Specify the size of the sourced video, it may be a string of the form
+ at var{width}x at var{heigth}, or the name of a size abbreviation. The
+default value is "320x240".
+
+ at item frame_rate
+Specify the frame rate of the sourced video, as the number of frames
+generated per second. It has to be a string in the format
+ at var{frame_rate_num}/@var{frame_rate_den}, an integer number, a float
+number or a valid video frame rate abbreviation. The default value is
+"25".
+
+ at end table
+
+For example the following graph description will generate a red source
+with an opacity of 0.2, with size "qcif" and a frame rate of 10
+frames per second, which will be overlayed over the source connected
+to the pad with identifier "in".
+
+ at example
+"color=red@@0.2:qcif:10 [color]; [in][color] overlay [out]"
+ at end example
+
+ at section movie
+
+Read a video stream from a movie container.
+
+It accepts the syntax: @var{movie_name}[:@var{options}] where
+ at var{movie_name} is the name of the resource to read (not necessarily
+a file but also a device or a stream accessed through some protocol),
+and @var{options} is an optional sequence of @var{key}=@var{value}
+pairs, separated by ":".
+
+The description of the accepted options follows.
+
+ at table @option
+
+ at item format_name, f
+Specifies the format assumed for the movie to read, and can be either
+the name of a container or an input device. If not specified the
+format is guessed from @var{movie_name} or by probing.
+
+ at item seek_point, sp
+Specifies the seek point in seconds, the frames will be output
+starting from this seek point, the parameter is evaluated with
+ at code{av_strtod} so the numerical value may be suffixed by an IS
+postfix. Default value is "0".
+
+ at item stream_index, si
+Specifies the index of the video stream to read. If the value is -1,
+the best suited video stream will be automatically selected. Default
+value is "-1".
+
+ at end table
+
+This filter allows to overlay a second video on top of main input of
+a filtergraph as shown in this graph:
+ at example
+input -----------> deltapts0 --> overlay --> output
+                                    ^
+                                    |
+movie --> scale--> deltapts1 -------+
+ at end example
+
+Some examples follow:
+ at example
+# skip 3.2 seconds from the start of the avi file in.avi, and overlay it
+# on top of the input labelled as "in".
+movie=in.avi:seek_point=3.2, scale=180:-1, setpts=PTS-STARTPTS [movie];
+[in] setpts=PTS-STARTPTS, [movie] overlay=16:16 [out]
+
+# read from a video4linux2 device, and overlay it on top of the input
+# labelled as "in"
+movie=/dev/video0:f=video4linux2, scale=180:-1, setpts=PTS-STARTPTS [movie];
+[in] setpts=PTS-STARTPTS, [movie] overlay=16:16 [out]
+
+ at end example
+
+ at section nullsrc
+
+Null video source, never return images. It is mainly useful as a
+template and to be employed in analysis / debugging tools.
+
+It accepts as optional parameter a string of the form
+ at var{width}:@var{height}:@var{timebase}.
+
+ at var{width} and @var{height} specify the size of the configured
+source. The default values of @var{width} and @var{height} are
+respectively 352 and 288 (corresponding to the CIF size format).
+
+ at var{timebase} specifies an arithmetic expression representing a
+timebase. The expression can contain the constants "PI", "E", "PHI",
+"AVTB" (the default timebase), and defaults to the value "AVTB".
+
+ at section frei0r_src
+
+Provide a frei0r source.
+
+To enable compilation of this filter you need to install the frei0r
+header and configure Libav with --enable-frei0r.
+
+The source supports the syntax:
+ at example
+ at var{size}:@var{rate}:@var{src_name}[@{=|:@}@var{param1}:@var{param2}:...:@var{paramN}]
+ at end example
+
+ at var{size} is the size of the video to generate, may be a string of the
+form @var{width}x at var{height} or a frame size abbreviation.
+ at var{rate} is the rate of the video to generate, may be a string of
+the form @var{num}/@var{den} or a frame rate abbreviation.
+ at var{src_name} is the name to the frei0r source to load. For more
+information regarding frei0r and how to set the parameters read the
+section "frei0r" (@pxref{frei0r}) in the description of the video
+filters.
+
+Some examples follow:
+ at example
+# generate a frei0r partik0l source with size 200x200 and framerate 10
+# which is overlayed on the overlay filter main input
+frei0r_src=200x200:10:partik0l=1234 [overlay]; [in][overlay] overlay
+ at end example
+
+ at c man end VIDEO SOURCES
+
+ at chapter Video Sinks
+ at c man begin VIDEO SINKS
+
+Below is a description of the currently available video sinks.
+
+ at section nullsink
+
+Null video sink, do absolutely nothing with the input video. It is
+mainly useful as a template and to be employed in analysis / debugging
+tools.
+
+ at c man end VIDEO SINKS
+
diff --git a/doc/general.texi b/doc/general.texi
index dfa5b07..423402c 100644
--- a/doc/general.texi
+++ b/doc/general.texi
@@ -2,21 +2,22 @@
 
 @settitle General Documentation
 @titlepage
- at sp 7
 @center @titlefont{General Documentation}
- at sp 3
 @end titlepage
 
+ at top
+
+ at contents
 
 @chapter external libraries
 
-FFmpeg can be hooked up with a number of external libraries to add support
+Libav can be hooked up with a number of external libraries to add support
 for more formats. None of them are used by default, their use has to be
 explicitly requested by passing the appropriate flags to @file{./configure}.
 
 @section OpenCORE AMR
 
-FFmpeg can make use of the OpenCORE libraries for AMR-NB
+Libav can make use of the OpenCORE libraries for AMR-NB
 decoding/encoding and AMR-WB decoding.
 
 Go to @url{http://sourceforge.net/projects/opencore-amr/} and follow the instructions for
@@ -26,7 +27,7 @@ installing the libraries. Then pass @code{--enable-libopencore-amrnb} and/or
 Note that OpenCORE is under the Apache License 2.0 (see
 @url{http://www.apache.org/licenses/LICENSE-2.0} for details), which is
 incompatible with the LGPL version 2.1 and GPL version 2. You have to
-upgrade FFmpeg's license to LGPL version 3 (or if you have enabled
+upgrade Libav's license to LGPL version 3 (or if you have enabled
 GPL components, GPL version 3) to use it.
 
 
@@ -36,7 +37,7 @@ You can use the @code{-formats} and @code{-codecs} options to have an exhaustive
 
 @section File Formats
 
-FFmpeg supports the following file formats through the @code{libavformat}
+Libav supports the following file formats through the @code{libavformat}
 library:
 
 @multitable @columnfractions .4 .1 .1 .4
@@ -49,6 +50,7 @@ library:
 @item American Laser Games MM   @tab   @tab X
     @tab Multimedia format used in games like Mad Dog McCree.
 @item 3GPP AMR                  @tab X @tab X
+ at item Apple HTTP Live Streaming @tab   @tab X
 @item ASF                       @tab X @tab X
 @item AVI                       @tab X @tab X
 @item AVISynth                  @tab   @tab X
@@ -60,6 +62,8 @@ library:
     @tab Used in some games from Bethesda Softworks.
 @item Bink                      @tab   @tab X
     @tab Multimedia format used by many games.
+ at item Bitmap Brothers JV        @tab   @tab X
+    @tab Used in Z and Z95 games.
 @item Brute Force & Ignorance   @tab   @tab X
     @tab Used in the game Flash Traffic: City of Angels.
 @item Interplay C93             @tab   @tab X
@@ -77,6 +81,8 @@ library:
     @tab Audio format used in some games by CRYO Interactive Entertainment.
 @item D-Cinema audio            @tab X @tab X
 @item Deluxe Paint Animation    @tab   @tab X
+ at item DFA                       @tab   @tab X
+    @tab This format is used in Chronomaster game
 @item DV video                  @tab X @tab X
 @item DXA                       @tab   @tab X
     @tab This format is used in the non-Windows version of the Feeble Files
@@ -102,20 +108,27 @@ library:
 @item id Quake II CIN video     @tab   @tab X
 @item id RoQ                    @tab X @tab X
     @tab Used in Quake III, Jedi Knight 2, other computer games.
- at item IEC61937 encapsulation @tab X @tab
+ at item IEC61937 encapsulation @tab X @tab X
 @item IFF                       @tab   @tab X
     @tab Interchange File Format
 @item Interplay MVE             @tab   @tab X
     @tab Format used in various Interplay computer games.
 @item IV8                       @tab   @tab X
     @tab A format generated by IndigoVision 8000 video server.
+ at item IVF (On2)                 @tab X @tab X
+    @tab A format used by libvpx
 @item LMLM4                     @tab   @tab X
     @tab Used by Linux Media Labs MPEG-4 PCI boards
+ at item LXF                       @tab   @tab X
+    @tab VR native stream format, used by Leitch/Harris' video servers.
 @item Matroska                  @tab X @tab X
 @item Matroska audio            @tab X @tab
+ at item FFmpeg metadata           @tab X @tab X
+    @tab Metadata in text format.
 @item MAXIS XA                  @tab   @tab X
     @tab Used in Sim City 3000; file extension .xa.
 @item MD Studio                 @tab   @tab X
+ at item Mobotix .mxg              @tab   @tab X
 @item Monkey's Audio            @tab   @tab X
 @item Motion Pixels MVI         @tab   @tab X
 @item MOV/QuickTime/MP4         @tab X @tab X
@@ -154,7 +167,7 @@ library:
 @item QCP                       @tab   @tab X
 @item raw ADTS (AAC)            @tab X @tab X
 @item raw AC-3                  @tab X @tab X
- at item raw Chinese AVS video     @tab   @tab X
+ at item raw Chinese AVS video     @tab X @tab X
 @item raw CRI ADX               @tab X @tab X
 @item raw Dirac                 @tab X @tab X
 @item raw DNxHD                 @tab X @tab X
@@ -207,10 +220,12 @@ library:
 @item RL2                       @tab   @tab X
     @tab Audio and video format used in some games by Entertainment Software Partners.
 @item RPL/ARMovie               @tab   @tab X
+ at item Lego Mindstorms RSO       @tab X @tab X
 @item RTMP                      @tab X @tab X
     @tab Output is performed by publishing stream to RTMP server
- at item RTP                       @tab   @tab X
+ at item RTP                       @tab X @tab X
 @item RTSP                      @tab X @tab X
+ at item SAP                       @tab X @tab X
 @item SDP                       @tab   @tab X
 @item Sega FILM/CPK             @tab   @tab X
     @tab Used in many Sega Saturn console games.
@@ -226,6 +241,7 @@ library:
 @item Sony Wave64 (W64)         @tab   @tab X
 @item SoX native format         @tab X @tab X
 @item SUN AU format             @tab X @tab X
+ at item Text files                @tab   @tab X
 @item THP                       @tab   @tab X
     @tab Used on the Nintendo GameCube.
 @item Tiertex Limited SEQ       @tab   @tab X
@@ -235,12 +251,15 @@ library:
 @item WAV                       @tab X @tab X
 @item WavPack                   @tab   @tab X
 @item WebM                      @tab X @tab X
+ at item Windows Televison (WTV)   @tab   @tab X
 @item Wing Commander III movie  @tab   @tab X
     @tab Multimedia format used in Origin's Wing Commander III computer game.
 @item Westwood Studios audio    @tab   @tab X
     @tab Multimedia format used in Westwood Studios games.
 @item Westwood Studios VQA      @tab   @tab X
     @tab Multimedia format used in Westwood Studios games.
+ at item xWMA                      @tab   @tab X
+    @tab Microsoft audio container used by XAudio 2.
 @item YUV4MPEG pipe             @tab X @tab X
 @item Psygnosis YOP             @tab   @tab X
 @end multitable
@@ -279,6 +298,8 @@ following image formats are supported:
     @tab Portable GrayMap image
 @item PGMYUV       @tab X @tab X
     @tab PGM with U and V components in YUV 4:2:0
+ at item PIC          @tab @tab X
+    @tab Pictor/PC Paint
 @item PNG          @tab X @tab X
     @tab 2/4 bpp not supported yet
 @item PPM          @tab X @tab X
@@ -308,10 +329,13 @@ following image formats are supported:
 @item 8088flex TMV           @tab     @tab  X
 @item 8SVX exponential       @tab     @tab  X
 @item 8SVX fibonacci         @tab     @tab  X
+ at item A64 multicolor         @tab  X  @tab
+    @tab Creates video suitable to be played on a commodore 64 (multicolor mode).
 @item American Laser Games MM  @tab    @tab X
     @tab Used in games like Mad Dog McCree.
 @item AMV Video              @tab     @tab  X
     @tab Used in Chinese MP3 players.
+ at item ANSI/ASCII art         @tab     @tab  X
 @item Apple MJPEG-B          @tab     @tab  X
 @item Apple QuickDraw        @tab     @tab  X
     @tab fourcc: qdrw
@@ -334,7 +358,7 @@ following image formats are supported:
 @item Bethesda VID video     @tab     @tab  X
     @tab Used in some games from Bethesda Softworks.
 @item Bink Video             @tab     @tab  X
-    @tab Support for version 'b' is missing.
+ at item Bitmap Brothers JV video  @tab   @tab X
 @item Brute Force & Ignorance   @tab   @tab X
     @tab Used in the game Flash Traffic: City of Angels.
 @item C93 video              @tab     @tab  X
@@ -343,14 +367,16 @@ following image formats are supported:
     @tab fourcc: CSCD
 @item CD+G                   @tab     @tab  X
     @tab Video codec for CD+G karaoke disks
- at item Chinese AVS video      @tab     @tab  X
-    @tab AVS1-P2, JiZhun profile
+ at item Chinese AVS video      @tab  E  @tab  X
+    @tab AVS1-P2, JiZhun profile, encoding through external library libxavs
 @item Delphine Software International CIN video  @tab     @tab  X
     @tab Codec used in Delphine Software International games.
 @item Cinepak                @tab     @tab  X
 @item Cirrus Logic AccuPak   @tab     @tab  X
     @tab fourcc: CLJR
 @item Creative YUV (CYUV)    @tab     @tab  X
+ at item DFA                    @tab     @tab  X
+    @tab Codec used in Chronomaster game.
 @item Dirac                  @tab  E  @tab  E
     @tab supported through external libdirac/libschroedinger libraries
 @item Deluxe Paint Animation @tab     @tab  X
@@ -407,6 +433,7 @@ following image formats are supported:
     @tab Codec used in Worms games.
 @item Kega Game Video (KGV1) @tab      @tab  X
     @tab Kega emulator screen capture codec.
+ at item Lagarith               @tab     @tab  X
 @item LCL (LossLess Codec Library) MSZH  @tab     @tab  X
 @item LCL (LossLess Codec Library) ZLIB  @tab  E  @tab  E
 @item LOCO                   @tab     @tab  X
@@ -418,6 +445,7 @@ following image formats are supported:
 @item Miro VideoXL           @tab     @tab  X
     @tab fourcc: VIXL
 @item MJPEG (Motion JPEG)    @tab  X  @tab  X
+ at item Mobotix MxPEG video    @tab     @tab  X
 @item Motion Pixels video    @tab     @tab  X
 @item MPEG-1 video           @tab  X  @tab  X
 @item MPEG-1/2 video XvMC (X-Video Motion Compensation)  @tab     @tab  X
@@ -425,7 +453,7 @@ following image formats are supported:
 @item MPEG-2 video           @tab  X  @tab  X
 @item MPEG-4 part 2          @tab  X  @tab  X
     @ libxvidcore can be used alternatively for encoding.
- at item MPEG-4 part 2 Microsoft variant version 1  @tab  X  @tab  X
+ at item MPEG-4 part 2 Microsoft variant version 1  @tab     @tab  X
 @item MPEG-4 part 2 Microsoft variant version 2  @tab  X  @tab  X
 @item MPEG-4 part 2 Microsoft variant version 3  @tab  X  @tab  X
 @item Nintendo Gamecube THP video  @tab     @tab  X
@@ -437,8 +465,8 @@ following image formats are supported:
     @tab fourcc: VP50
 @item On2 VP6                @tab     @tab  X
     @tab fourcc: VP60,VP61,VP62
- at item VP8                    @tab  X  @tab  X
-    @tab fourcc: VP80, de/encoding supported through external library libvpx
+ at item VP8                    @tab  E  @tab  X
+    @tab fourcc: VP80, encoding supported through external library libvpx
 @item planar RGB             @tab     @tab  X
     @tab fourcc: 8BPS
 @item Q-team QPEG            @tab     @tab  X
@@ -450,6 +478,7 @@ following image formats are supported:
     @tab fourcc: 'smc '
 @item QuickTime video (RPZA) @tab     @tab  X
     @tab fourcc: rpza
+ at item R10K AJA Kona 10-bit RGB Codec     @tab     @tab  X
 @item R210 Quicktime Uncompressed RGB 10-bit     @tab     @tab  X
 @item Raw Video              @tab  X  @tab  X
 @item RealVideo 1.0          @tab  X  @tab  X
@@ -491,6 +520,8 @@ following image formats are supported:
     @tab not completely working
 @item Wing Commander III / Xan  @tab     @tab  X
     @tab Used in Wing Commander III .MVE files.
+ at item Wing Commander IV / Xan  @tab     @tab  X
+    @tab Used in Wing Commander IV.
 @item Winnov WNV1            @tab     @tab  X
 @item WMV7                   @tab  X  @tab  X
 @item YAMAHA SMAF            @tab  X  @tab  X
@@ -511,7 +542,7 @@ following image formats are supported:
 @item Name @tab Encoding @tab Decoding @tab Comments
 @item 8SVX audio             @tab     @tab  X
 @item AAC                    @tab  E  @tab  X
-    @tab encoding supported through external library libfaac
+    @tab encoding supported through external library libfaac and libvo-aacenc
 @item AC-3                   @tab IX  @tab  X
 @item ADPCM 4X Movie         @tab     @tab  X
 @item ADPCM CDROM XA         @tab     @tab  X
@@ -525,6 +556,7 @@ following image formats are supported:
 @item ADPCM Electronic Arts R2  @tab     @tab  X
 @item ADPCM Electronic Arts R3  @tab     @tab  X
 @item ADPCM Electronic Arts XAS @tab     @tab  X
+ at item ADPCM G.722            @tab  X  @tab  X
 @item ADPCM G.726            @tab  X  @tab  X
 @item ADPCM IMA AMV          @tab     @tab  X
     @tab Used in AMV files
@@ -558,8 +590,8 @@ following image formats are supported:
 @item ADPCM Yamaha           @tab  X  @tab  X
 @item AMR-NB                 @tab  E  @tab  X
     @tab encoding supported through external library libopencore-amrnb
- at item AMR-WB                 @tab     @tab  E
-    @tab decoding supported through external library libopencore-amrwb
+ at item AMR-WB                 @tab  E  @tab  X
+    @tab encoding supported through external library libvo-amrwbenc
 @item Apple lossless audio   @tab  X  @tab  X
     @tab QuickTime fourcc 'alac'
 @item Atrac 1                @tab     @tab  X
@@ -584,11 +616,10 @@ following image formats are supported:
 @item DV audio               @tab     @tab  X
 @item Enhanced AC-3          @tab     @tab  X
 @item FLAC (Free Lossless Audio Codec)  @tab  X  @tab  IX
- at item G.729                  @tab     @tab  X
- at item GSM                    @tab  E  @tab  E
-    @tab supported through external library libgsm
- at item GSM Microsoft variant  @tab  E  @tab  E
-    @tab supported through external library libgsm
+ at item GSM                    @tab  E  @tab  X
+    @tab encoding supported through external library libgsm
+ at item GSM Microsoft variant  @tab  E  @tab  X
+    @tab encoding supported through external library libgsm
 @item IMC (Intel Music Coder)  @tab     @tab  X
 @item MACE (Macintosh Audio Compression/Expansion) 3:1  @tab     @tab  X
 @item MACE (Macintosh Audio Compression/Expansion) 6:1  @tab     @tab  X
@@ -631,7 +662,7 @@ following image formats are supported:
 @item QCELP / PureVoice      @tab     @tab  X
 @item QDesign Music Codec 2  @tab     @tab  X
     @tab There are still some distortions.
- at item RealAudio 1.0 (14.4K)  @tab     @tab  X
+ at item RealAudio 1.0 (14.4K)  @tab  X  @tab  X
     @tab Real 14400 bit/s codec
 @item RealAudio 2.0 (28.8K)  @tab     @tab  X
     @tab Real 28800 bit/s codec
@@ -642,10 +673,6 @@ following image formats are supported:
 @item Sierra VMD audio       @tab     @tab  X
     @tab Used in Sierra VMD files.
 @item Smacker audio          @tab     @tab  X
- at item Sonic                  @tab  X  @tab  X
-    @tab experimental codec
- at item Sonic lossless         @tab  X  @tab  X
-    @tab experimental codec
 @item Speex                  @tab     @tab  E
     @tab supported through external library libspeex
 @item True Audio (TTA)       @tab     @tab  X
@@ -673,10 +700,11 @@ performance on systems without hardware floating point support).
 
 @multitable @columnfractions .4 .1 .1 .1 .1
 @item Name @tab Muxing @tab Demuxing @tab Encoding @tab Decoding
- at item SSA/ASS      @tab X @tab X
+ at item SSA/ASS      @tab X @tab X @tab X @tab X
 @item DVB          @tab X @tab X @tab X @tab X
 @item DVD          @tab X @tab X @tab X @tab X
 @item PGS          @tab   @tab   @tab   @tab X
+ at item SubRip (SRT) @tab X @tab X @tab   @tab X
 @item XSUB         @tab   @tab   @tab X @tab X
 @end multitable
 
@@ -686,9 +714,11 @@ performance on systems without hardware floating point support).
 
 @multitable @columnfractions .4 .1
 @item Name         @tab Support
+ at item Apple HTTP Live Streaming @tab X
 @item file         @tab X
 @item Gopher       @tab X
 @item HTTP         @tab X
+ at item MMS          @tab X
 @item pipe         @tab X
 @item RTP          @tab X
 @item TCP          @tab X
@@ -703,7 +733,6 @@ performance on systems without hardware floating point support).
 @multitable @columnfractions .4 .1 .1
 @item Name              @tab Input  @tab Output
 @item ALSA              @tab X      @tab X
- at item BEOS audio        @tab X      @tab X
 @item BKTR              @tab X      @tab
 @item DV1394            @tab X      @tab
 @item JACK              @tab X      @tab
@@ -720,28 +749,24 @@ performance on systems without hardware floating point support).
 
 @chapter Platform Specific information
 
- at section BeOS
-
-BeOS support is broken in mysterious ways.
-
 @section DOS
 
 Using a cross-compiler is preferred for various reasons.
 
 @subsection DJGPP
 
-FFmpeg cannot be compiled because of broken system headers, add
+Libav cannot be compiled because of broken system headers, add
 @code{--extra-cflags=-U__STRICT_ANSI__} to the configure options as a
 workaround.
 
 @section OS/2
 
-For information about compiling FFmpeg on OS/2 see
+For information about compiling Libav on OS/2 see
 @url{http://www.edm2.com/index.php/FFmpeg}.
 
 @section Unix-like
 
-Some parts of FFmpeg cannot be built with version 2.15 of the GNU
+Some parts of Libav cannot be built with version 2.15 of the GNU
 assembler which is still provided by a few AMD64 distributions. To
 make sure your compiler really uses the required version of gas
 after a binutils upgrade, run:
@@ -756,7 +781,7 @@ to configure.
 
 @subsection BSD
 
-BSD make will not build FFmpeg, you need to install and use GNU Make
+BSD make will not build Libav, you need to install and use GNU Make
 (@file{gmake}).
 
 @subsubsection FreeBSD
@@ -769,7 +794,7 @@ getting the system headers fixed.
 
 @subsection (Open)Solaris
 
-GNU Make is required to build FFmpeg, so you have to invoke (@file{gmake}),
+GNU Make is required to build Libav, so you have to invoke (@file{gmake}),
 standard Solaris Make will not work. When building with a non-c99 front-end
 (gcc, generic suncc) add either @code{--extra-libs=/usr/lib/values-xpg6.o}
 or @code{--extra-libs=/usr/lib/64/values-xpg6.o} to the configure options
@@ -782,20 +807,23 @@ bash directly to work around this:
 bash ./configure
 @end example
 
- at section Windows
+ at subsection Darwin (MacOS X, iPhone)
+
+MacOS X on PowerPC or ARM (iPhone) requires a preprocessor from
+ at url{http://github.com/yuvi/gas-preprocessor} to build the optimized
+assembler functions. Just download the Perl script and put it somewhere
+in your PATH, Libav's configure will pick it up automatically.
 
-To get help and instructions for building FFmpeg under Windows, check out
-the FFmpeg Windows Help Forum at
- at url{http://ffmpeg.arrozcru.org/}.
+ at section Windows
 
 @subsection Native Windows compilation
 
-FFmpeg can be built to run natively on Windows using the MinGW tools. Install
+Libav can be built to run natively on Windows using the MinGW tools. Install
 the latest versions of MSYS and MinGW from @url{http://www.mingw.org/}.
 You can find detailed installation
 instructions in the download section and the FAQ.
 
-FFmpeg does not build out-of-the-box with the packages the automated MinGW
+Libav does not build out-of-the-box with the packages the automated MinGW
 installer provides. It also requires coreutils to be installed and many other
 packages updated to the latest version. The minimum version for some packages
 are listed below:
@@ -807,7 +835,7 @@ are listed below:
 @item mingw-runtime 3.15
 @end itemize
 
-FFmpeg automatically passes @code{-fno-common} to the compiler to work around
+Libav automatically passes @code{-fno-common} to the compiler to work around
 a GCC bug (see @url{http://gcc.gnu.org/bugzilla/show_bug.cgi?id=37216}).
 
 Within the MSYS shell, configure and make with:
@@ -838,14 +866,14 @@ Edit the @file{bin/sdl-config} script so that it points to the correct prefix
 where SDL was installed. Verify that @file{sdl-config} can be launched from
 the MSYS command line.
 
- at item By using @code{./configure --enable-shared} when configuring FFmpeg,
+ at item By using @code{./configure --enable-shared} when configuring Libav,
 you can build libavutil, libavcodec and libavformat as DLLs.
 
 @end itemize
 
 @subsection Microsoft Visual C++ compatibility
 
-As stated in the FAQ, FFmpeg will not compile under MSVC++. However, if you
+As stated in the FAQ, Libav will not compile under MSVC++. However, if you
 want to use the libav* libraries in your own applications, you can still
 compile those applications using MSVC++. But the libav* libraries you link
 to @emph{must} be built with MinGW. However, you will not be able to debug
@@ -853,13 +881,13 @@ inside the libav* libraries, since MSVC++ does not recognize the debug
 symbols generated by GCC.
 We strongly recommend you to move over from MSVC++ to MinGW tools.
 
-This description of how to use the FFmpeg libraries with MSVC++ is based on
+This description of how to use the Libav libraries with MSVC++ is based on
 Microsoft Visual C++ 2005 Express Edition. If you have a different version,
 you might have to modify the procedures slightly.
 
 @subsubsection Using static libraries
 
-Assuming you have just built and installed FFmpeg in @file{/usr/local}.
+Assuming you have just built and installed Libav in @file{/usr/local}.
 
 @enumerate
 
@@ -870,13 +898,13 @@ Application Wizard, uncheck the "Precompiled headers" option.
 @item Write the source code for your application, or, for testing, just
 copy the code from an existing sample application into the source file
 that MSVC++ has already created for you. For example, you can copy
- at file{libavformat/output-example.c} from the FFmpeg distribution.
+ at file{libavformat/output-example.c} from the Libav distribution.
 
 @item Open the "Project / Properties" dialog box. In the "Configuration"
 combo box, select "All Configurations" so that the changes you make will
 affect both debug and release builds. In the tree view on the left hand
 side, select "C/C++ / General", then edit the "Additional Include
-Directories" setting to contain the path where the FFmpeg includes were
+Directories" setting to contain the path where the Libav includes were
 installed (i.e. @file{c:\msys\1.0\local\include}).
 Do not add MinGW's include directory here, or the include files will
 conflict with MSVC's.
@@ -884,7 +912,7 @@ conflict with MSVC's.
 @item Still in the "Project / Properties" dialog box, select
 "Linker / General" from the tree view and edit the
 "Additional Library Directories" setting to contain the @file{lib}
-directory where FFmpeg was installed (i.e. @file{c:\msys\1.0\local\lib}),
+directory where Libav was installed (i.e. @file{c:\msys\1.0\local\lib}),
 the directory where MinGW libs are installed (i.e. @file{c:\mingw\lib}),
 and the directory where MinGW's GCC libs are installed
 (i.e. @file{C:\mingw\lib\gcc\mingw32\4.2.1-sjlj}). Then select
@@ -901,13 +929,13 @@ set to "Multi-threaded DLL".
 
 @item Click "OK" to close the "Project / Properties" dialog box.
 
- at item MSVC++ lacks some C99 header files that are fundamental for FFmpeg.
+ at item MSVC++ lacks some C99 header files that are fundamental for Libav.
 Get msinttypes from @url{http://code.google.com/p/msinttypes/downloads/list}
 and install it in MSVC++'s include directory
 (i.e. @file{C:\Program Files\Microsoft Visual Studio 8\VC\include}).
 
 @item MSVC++ also does not understand the @code{inline} keyword used by
-FFmpeg, so you must add this line before @code{#include}ing libav*:
+Libav, so you must add this line before @code{#include}ing libav*:
 @example
 #define inline _inline
 @end example
@@ -940,10 +968,10 @@ and run @file{c:\msys\1.0\msys.bat} from there.
 @item Within the MSYS shell, run @code{lib.exe}. If you get a help message
 from @file{Microsoft (R) Library Manager}, this means your environment
 variables are set up correctly, the @file{Microsoft (R) Library Manager}
-is on the path and will be used by FFmpeg to create
+is on the path and will be used by Libav to create
 MSVC++-compatible import libraries.
 
- at item Build FFmpeg with
+ at item Build Libav with
 
 @example
 ./configure --enable-shared --enable-memalign-hack
@@ -960,28 +988,46 @@ To use those files with MSVC++, do the same as you would do with
 the static libraries, as described above. But in Step 4,
 you should only need to add the directory where the LIB files are installed
 (i.e. @file{c:\msys\usr\local\bin}). This is not a typo, the LIB files are
-installed in the @file{bin} directory. And instead of adding @file{libxx.a}
-files, you should add @file{avcodec.lib}, @file{avformat.lib}, and
- at file{avutil.lib}. There should be no need for @file{libmingwex.a},
+installed in the @file{bin} directory. And instead of adding the static
+libraries (@file{libxxx.a} files) you should add the MSVC import libraries
+(@file{avcodec.lib}, @file{avformat.lib}, and
+ at file{avutil.lib}). Note that you should not use the GCC import
+libraries (@file{libxxx.dll.a} files), as these will give you undefined
+reference errors. There should be no need for @file{libmingwex.a},
 @file{libgcc.a}, and @file{wsock32.lib}, nor any other external library
 statically linked into the DLLs. The @file{bin} directory contains a bunch
 of DLL files, but the ones that are actually used to run your application
 are the ones with a major version number in their filenames
 (i.e. @file{avcodec-51.dll}).
 
+Libav headers do not declare global data for Windows DLLs through the usual
+dllexport/dllimport interface. Such data will be exported properly while
+building, but to use them in your MSVC++ code you will have to edit the
+appropriate headers and mark the data as dllimport. For example, in
+libavutil/pixdesc.h you should have:
+ at example
+extern __declspec(dllimport) const AVPixFmtDescriptor av_pix_fmt_descriptors[];
+ at end example
+
+Note that using import libraries created by dlltool requires
+the linker optimization option to be set to
+"References: Keep Unreferenced Data (/OPT:NOREF)", otherwise
+the resulting binaries will fail during runtime. This isn't
+required when using import libraries generated by lib.exe.
+
 @subsection Cross compilation for Windows with Linux
 
 You must use the MinGW cross compilation tools available at
 @url{http://www.mingw.org/}.
 
-Then configure FFmpeg with the following options:
+Then configure Libav with the following options:
 @example
 ./configure --target-os=mingw32 --cross-prefix=i386-mingw32msvc-
 @end example
 (you can change the cross-prefix according to the prefix chosen for the
 MinGW tools).
 
-Then you can easily test FFmpeg with Wine
+Then you can easily test Libav with Wine
 (@url{http://www.winehq.com/}).
 
 @subsection Compilation under Cygwin
@@ -992,7 +1038,7 @@ llrint() in its C library.
 Install your Cygwin with all the "Base" packages, plus the
 following "Devel" ones:
 @example
-binutils, gcc4-core, make, subversion, mingw-runtime, texi2html
+binutils, gcc4-core, make, git, mingw-runtime, texi2html
 @end example
 
 And the following "Utils" one:
@@ -1015,7 +1061,7 @@ shared libraries:
 ./configure --enable-shared --disable-static --extra-cflags=-fno-reorder-functions
 @end example
 
-If you want to build FFmpeg with additional libraries, download Cygwin
+If you want to build Libav with additional libraries, download Cygwin
 "Devel" packages for Ogg and Vorbis from any Cygwin packages repository:
 @example
 libogg-devel, libvorbis-devel
@@ -1025,7 +1071,7 @@ These library packages are only available from Cygwin Ports
 (@url{http://sourceware.org/cygwinports/}) :
 
 @example
-yasm, libSDL-devel, libdirac-devel, libfaac-devel, libfaad-devel, libgsm-devel,
+yasm, libSDL-devel, libdirac-devel, libfaac-devel, libgsm-devel,
 libmp3lame-devel, libschroedinger1.0-devel, speex-devel, libtheora-devel,
 libxvidcore-devel
 @end example
diff --git a/doc/git-howto.txt b/doc/git-howto.txt
new file mode 100644
index 0000000..ba377c9
--- /dev/null
+++ b/doc/git-howto.txt
@@ -0,0 +1,259 @@
+
+About Git write access:
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Before everything else, you should know how to use GIT properly.
+Luckily Git comes with excellent documentation.
+
+  git --help
+  man git
+
+shows you the available subcommands,
+
+  git <command> --help
+  man git-<command>
+
+shows information about the subcommand <command>.
+
+The most comprehensive manual is the website Git Reference
+
+http://gitref.org/
+
+For more information about the Git project, visit
+
+http://git-scm.com/
+
+Consult these resources whenever you have problems, they are quite exhaustive.
+
+You do not need a special username or password.
+All you need is to provide a ssh public key to the Git server admin.
+
+What follows now is a basic introduction to Git and some Libav-specific
+guidelines. Read it at least once, if you are granted commit privileges to the
+Libav project you are expected to be familiar with these rules.
+
+
+
+I. BASICS:
+==========
+
+0. Get GIT:
+
+  You can get git from http://git-scm.com/
+
+
+1. Cloning the source tree:
+
+    git clone git://git.libav.org/libav.git <target>
+
+  This will put the Libav sources into the directory <target>.
+
+    git clone git at git.libav.org:libav.git <target>
+
+  This will put the Libav sources into the directory <target> and let
+  you push back your changes to the remote repository.
+
+
+2. Updating the source tree to the latest revision:
+
+    git pull (--ff-only)
+
+  pulls in the latest changes from the tracked branch. The tracked branch
+  can be remote. By default the master branch tracks the branch master in
+  the remote origin.
+  Caveat: Since merge commits are forbidden at least for the initial
+          months of git --ff-only or --rebase (see below) are recommended.
+          --ff-only will fail and not create merge commits if your branch
+          has diverged (has a different history) from the tracked branch.
+
+2.a Rebasing your local branches:
+
+    git pull --rebase
+
+  fetches the changes from the main repository and replays your local commits
+  over it. This is required to keep all your local changes at the top of
+  Libav's master tree. The master tree will reject pushes with merge commits.
+
+
+3. Adding/removing files/directories:
+
+    git add [-A] <filename/dirname>
+    git rm [-r] <filename/dirname>
+
+  GIT needs to get notified of all changes you make to your working
+  directory that makes files appear or disappear.
+  Line moves across files are automatically tracked.
+
+
+4. Showing modifications:
+
+    git diff <filename(s)>
+
+  will show all local modifications in your working directory as unified diff.
+
+
+5. Inspecting the changelog:
+
+    git log <filename(s)>
+
+  You may also use the graphical tools like gitview or gitk or the web
+  interface available at http://git.libav.org/
+
+6. Checking source tree status:
+
+    git status
+
+  detects all the changes you made and lists what actions will be taken in case
+  of a commit (additions, modifications, deletions, etc.).
+
+
+7. Committing:
+
+    git diff --check
+
+  to double check your changes before committing them to avoid trouble later
+  on. All experienced developers do this on each and every commit, no matter
+  how small.
+  Every one of them has been saved from looking like a fool by this many times.
+  It's very easy for stray debug output or cosmetic modifications to slip in,
+  please avoid problems through this extra level of scrutiny.
+
+  For cosmetics-only commits you should get (almost) empty output from
+
+    git diff -w -b <filename(s)>
+
+  Also check the output of
+
+    git status
+
+  to make sure you don't have untracked files or deletions.
+
+    git add [-i|-p|-A] <filenames/dirnames>
+
+  Make sure you have told git your name and email address, e.g. by running
+    git config --global user.name "My Name"
+    git config --global user.email my at email.invalid
+  (--global to set the global configuration for all your git checkouts).
+
+  Git will select the changes to the files for commit. Optionally you can use
+  the interactive or the patch mode to select hunk by hunk what should be
+  added to the commit.
+
+    git commit
+
+  Git will commit the selected changes to your current local branch.
+
+  You will be prompted for a log message in an editor, which is either
+  set in your personal configuration file through
+
+    git config core.editor
+
+  or set by one of the following environment variables:
+  GIT_EDITOR, VISUAL or EDITOR.
+
+  Log messages should be concise but descriptive. Explain why you made a change,
+  what you did will be obvious from the changes themselves most of the time.
+  Saying just "bug fix" or "10l" is bad. Remember that people of varying skill
+  levels look at and educate themselves while reading through your code. Don't
+  include filenames in log messages, Git provides that information.
+
+  Possibly make the commit message have a terse, descriptive first line, an
+  empty line and then a full description. The first line will be used to name
+  the patch by git format-patch.
+
+
+8. Renaming/moving/copying files or contents of files:
+
+  Git automatically tracks such changes, making those normal commits.
+
+    mv/cp path/file otherpath/otherfile
+
+    git add [-A] .
+
+    git commit
+
+  Do not move, rename or copy files of which you are not the maintainer without
+  discussing it on the mailing list first!
+
+9. Reverting broken commits
+
+    git revert <commit>
+
+  git revert will generate a revert commit. This will not make the faulty
+  commit disappear from the history.
+
+    git reset <commit>
+
+  git reset will uncommit the changes till <commit> rewriting the current
+  branch history.
+
+    git commit --amend
+
+  allows to amend the last commit details quickly.
+
+    git rebase -i origin/master
+
+  will replay local commits over the main repository allowing to edit,
+  merge or remove some of them in the process.
+
+  Note that the reset, commit --amend and rebase rewrite history, so you
+  should use them ONLY on your local or topic branches.
+
+  The main repository will reject those changes.
+
+10. Preparing a patchset.
+
+    git format-patch <commit> [-o directory]
+
+  will generate a set of patches out of the current branch starting from
+  commit. By default the patches are created in the current directory.
+
+11. Sending patches for review
+
+    git send-email <commit list|directory>
+
+  will send the patches created by git format-patch or directly generates
+  them. All the email fields can be configured in the global/local
+  configuration or overridden by command line.
+
+12. Pushing changes to remote trees
+
+    git push
+
+  Will push the changes to the default remote (origin).
+  Git will prevent you from pushing changes if the local and remote trees are
+  out of sync. Refer to 2 and 2.a to sync the local tree.
+
+    git remote add <name> <url>
+
+  Will add additional remote with a name reference, it is useful if you want
+  to push your local branch for review on a remote host.
+
+    git push <remote> <refspec>
+
+  Will push the changes to the remote repository. Omitting refspec makes git
+  push update all the remote branches matching the local ones.
+
+13. Finding a specific svn revision
+
+  Since version 1.7.1 git supports ':/foo' syntax for specifying commits
+  based on a regular expression. see man gitrevisions
+
+    git show :/'as revision 23456'
+
+  will show the svn changeset r23456. With older git versions searching in
+  the git log output is the easiest option (especially if a pager with
+  search capabilities is used).
+  This commit can be checked out with
+
+    git checkout -b svn_23456 :/'as revision 23456'
+
+  or for git < 1.7.1 with
+
+    git checkout -b svn_23456 $SHA1
+
+  where $SHA1 is the commit SHA1 from the 'git log' output.
+
+
+Contact the project admins <git at libav dot org> if you have technical
+problems with the GIT server.
diff --git a/doc/indevs.texi b/doc/indevs.texi
new file mode 100644
index 0000000..c5e04b0
--- /dev/null
+++ b/doc/indevs.texi
@@ -0,0 +1,254 @@
+ at chapter Input Devices
+ at c man begin INPUT DEVICES
+
+Input devices are configured elements in Libav which allow to access
+the data coming from a multimedia device attached to your system.
+
+When you configure your Libav build, all the supported input devices
+are enabled by default. You can list all available ones using the
+configure option "--list-indevs".
+
+You can disable all the input devices using the configure option
+"--disable-indevs", and selectively enable an input device using the
+option "--enable-indev=@var{INDEV}", or you can disable a particular
+input device using the option "--disable-indev=@var{INDEV}".
+
+The option "-formats" of the ff* tools will display the list of
+supported input devices (amongst the demuxers).
+
+A description of the currently available input devices follows.
+
+ at section alsa
+
+ALSA (Advanced Linux Sound Architecture) input device.
+
+To enable this input device during configuration you need libasound
+installed on your system.
+
+This device allows capturing from an ALSA device. The name of the
+device to capture has to be an ALSA card identifier.
+
+An ALSA identifier has the syntax:
+ at example
+hw:@var{CARD}[, at var{DEV}[, at var{SUBDEV}]]
+ at end example
+
+where the @var{DEV} and @var{SUBDEV} components are optional.
+
+The three arguments (in order: @var{CARD}, at var{DEV}, at var{SUBDEV})
+specify card number or identifier, device number and subdevice number
+(-1 means any).
+
+To see the list of cards currently recognized by your system check the
+files @file{/proc/asound/cards} and @file{/proc/asound/devices}.
+
+For example to capture with @file{ffmpeg} from an ALSA device with
+card id 0, you may run the command:
+ at example
+ffmpeg -f alsa -i hw:0 alsaout.wav
+ at end example
+
+For more information see:
+ at url{http://www.alsa-project.org/alsa-doc/alsa-lib/pcm.html}
+
+ at section bktr
+
+BSD video input device.
+
+ at section dv1394
+
+Linux DV 1394 input device.
+
+ at section fbdev
+
+Linux framebuffer input device.
+
+The Linux framebuffer is a graphic hardware-independent abstraction
+layer to show graphics on a computer monitor, typically on the
+console. It is accessed through a file device node, usually
+ at file{/dev/fb0}.
+
+For more detailed information read the file
+Documentation/fb/framebuffer.txt included in the Linux source tree.
+
+To record from the framebuffer device @file{/dev/fb0} with
+ at file{ffmpeg}:
+ at example
+ffmpeg -f fbdev -r 10 -i /dev/fb0 out.avi
+ at end example
+
+You can take a single screenshot image with the command:
+ at example
+ffmpeg -f fbdev -vframes 1 -r 1 -i /dev/fb0 screenshot.jpeg
+ at end example
+
+See also @url{http://linux-fbdev.sourceforge.net/}, and fbset(1).
+
+ at section jack
+
+JACK input device.
+
+To enable this input device during configuration you need libjack
+installed on your system.
+
+A JACK input device creates one or more JACK writable clients, one for
+each audio channel, with name @var{client_name}:input_ at var{N}, where
+ at var{client_name} is the name provided by the application, and @var{N}
+is a number which identifies the channel.
+Each writable client will send the acquired data to the Libav input
+device.
+
+Once you have created one or more JACK readable clients, you need to
+connect them to one or more JACK writable clients.
+
+To connect or disconnect JACK clients you can use the
+ at file{jack_connect} and @file{jack_disconnect} programs, or do it
+through a graphical interface, for example with @file{qjackctl}.
+
+To list the JACK clients and their properties you can invoke the command
+ at file{jack_lsp}.
+
+Follows an example which shows how to capture a JACK readable client
+with @file{ffmpeg}.
+ at example
+# Create a JACK writable client with name "ffmpeg".
+$ ffmpeg -f jack -i ffmpeg -y out.wav
+
+# Start the sample jack_metro readable client.
+$ jack_metro -b 120 -d 0.2 -f 4000
+
+# List the current JACK clients.
+$ jack_lsp -c
+system:capture_1
+system:capture_2
+system:playback_1
+system:playback_2
+ffmpeg:input_1
+metro:120_bpm
+
+# Connect metro to the ffmpeg writable client.
+$ jack_connect metro:120_bpm ffmpeg:input_1
+ at end example
+
+For more information read:
+ at url{http://jackaudio.org/}
+
+ at section libdc1394
+
+IIDC1394 input device, based on libdc1394 and libraw1394.
+
+ at section oss
+
+Open Sound System input device.
+
+The filename to provide to the input device is the device node
+representing the OSS input device, and is usually set to
+ at file{/dev/dsp}.
+
+For example to grab from @file{/dev/dsp} using @file{ffmpeg} use the
+command:
+ at example
+ffmpeg -f oss -i /dev/dsp /tmp/oss.wav
+ at end example
+
+For more information about OSS see:
+ at url{http://manuals.opensound.com/usersguide/dsp.html}
+
+ at section sndio
+
+sndio input device.
+
+To enable this input device during configuration you need libsndio
+installed on your system.
+
+The filename to provide to the input device is the device node
+representing the sndio input device, and is usually set to
+ at file{/dev/audio0}.
+
+For example to grab from @file{/dev/audio0} using @file{ffmpeg} use the
+command:
+ at example
+ffmpeg -f sndio -i /dev/audio0 /tmp/oss.wav
+ at end example
+
+ at section video4linux and video4linux2
+
+Video4Linux and Video4Linux2 input video devices.
+
+The name of the device to grab is a file device node, usually Linux
+systems tend to automatically create such nodes when the device
+(e.g. an USB webcam) is plugged into the system, and has a name of the
+kind @file{/dev/video at var{N}}, where @var{N} is a number associated to
+the device.
+
+Video4Linux and Video4Linux2 devices only support a limited set of
+ at var{width}x at var{height} sizes and framerates. You can check which are
+supported for example with the command @file{dov4l} for Video4Linux
+devices and the command @file{v4l-info} for Video4Linux2 devices.
+
+If the size for the device is set to 0x0, the input device will
+try to autodetect the size to use.
+Only for the video4linux2 device, if the frame rate is set to 0/0 the
+input device will use the frame rate value already set in the driver.
+
+Video4Linux support is deprecated since Linux 2.6.30, and will be
+dropped in later versions.
+
+Follow some usage examples of the video4linux devices with the ff*
+tools.
+ at example
+# Grab and show the input of a video4linux device, frame rate is set
+# to the default of 25/1.
+ffplay -s 320x240 -f video4linux /dev/video0
+
+# Grab and show the input of a video4linux2 device, autoadjust size.
+ffplay -f video4linux2 /dev/video0
+
+# Grab and record the input of a video4linux2 device, autoadjust size,
+# frame rate value defaults to 0/0 so it is read from the video4linux2
+# driver.
+ffmpeg -f video4linux2 -i /dev/video0 out.mpeg
+ at end example
+
+ at section vfwcap
+
+VfW (Video for Windows) capture input device.
+
+The filename passed as input is the capture driver number, ranging from
+0 to 9. You may use "list" as filename to print a list of drivers. Any
+other filename will be interpreted as device number 0.
+
+ at section x11grab
+
+X11 video input device.
+
+This device allows to capture a region of an X11 display.
+
+The filename passed as input has the syntax:
+ at example
+[@var{hostname}]:@var{display_number}. at var{screen_number}[+ at var{x_offset}, at var{y_offset}]
+ at end example
+
+ at var{hostname}:@var{display_number}. at var{screen_number} specifies the
+X11 display name of the screen to grab from. @var{hostname} can be
+ommitted, and defaults to "localhost". The environment variable
+ at env{DISPLAY} contains the default display name.
+
+ at var{x_offset} and @var{y_offset} specify the offsets of the grabbed
+area with respect to the top-left border of the X11 screen. They
+default to 0.
+
+Check the X11 documentation (e.g. man X) for more detailed information.
+
+Use the @file{dpyinfo} program for getting basic information about the
+properties of your X11 display (e.g. grep for "name" or "dimensions").
+
+For example to grab from @file{:0.0} using @file{ffmpeg}:
+ at example
+ffmpeg -f x11grab -r 25 -s cif -i :0.0 out.mpg
+
+# Grab at position 10,20.
+ffmpeg -f x11grab -25 -s cif -i :0.0+10,20 out.mpg
+ at end example
+
+ at c man end INPUT DEVICES
diff --git a/doc/issue_tracker.txt b/doc/issue_tracker.txt
index e5a74db..5a15a9b 100644
--- a/doc/issue_tracker.txt
+++ b/doc/issue_tracker.txt
@@ -1,11 +1,11 @@
-FFmpeg's bug/patch/feature request tracker manual
-=================================================
+Libav's bug/patch/feature request tracker manual
+================================================
 
 NOTE: This is a draft.
 
 Overview:
 ---------
-FFmpeg uses Roundup for tracking issues, new issues and changes to
+Libav uses Roundup for tracking issues, new issues and changes to
 existing issues can be done through a web interface and through email.
 It is possible to subscribe to individual issues by adding yourself to the
 nosy list or to subscribe to the ffmpeg-issues mailing list which receives
@@ -15,7 +15,7 @@ be properly added to the respective issue.
 The subscription URL for the ffmpeg-issues list is:
 http://live.polito/mailman/listinfo/ffmpeg-issues
 The URL of the webinterface of the tracker is:
-http(s)://roundup.ffmpeg/roundup/ffmpeg/
+http(s)://roundup.libav.org/
 Note the URLs in this document are obfuscated, you must append the top level
 domain for non-profit organizations to the tracker, and of Italy to the
 mailing list.
@@ -60,7 +60,7 @@ critical
     No feature request can be critical.
 
 important
-    Bugs which make FFmpeg unusable for a significant number of users, and
+    Bugs which make Libav unusable for a significant number of users, and
     patches fixing them.
     Examples here might be completely broken MPEG-4 decoding or a build issue
     on Linux.
@@ -81,7 +81,7 @@ minor
 wish
     Something that is desirable to have but that there is no urgency at
     all to implement, e.g. something completely cosmetic like a website
-    restyle or a personalized doxy template or the FFmpeg logo.
+    restyle or a personalized doxy template or the Libav logo.
     This priority is not valid for bugs.
 
 
@@ -187,7 +187,7 @@ feature_request/closed/wont_implement
     be legal, philosophical or others.
 
 Note, please do not use type-status-substatus combinations other than the
-above without asking on ffmpeg-dev first!
+above without asking on libav-devel first!
 
 Note2, if you provide the requested info do not forget to remove the
 needs_more_info substate.
diff --git a/doc/libavfilter.texi b/doc/libavfilter.texi
index 20ef445..1c12205 100644
--- a/doc/libavfilter.texi
+++ b/doc/libavfilter.texi
@@ -2,24 +2,25 @@
 
 @settitle Libavfilter Documentation
 @titlepage
- at sp 7
 @center @titlefont{Libavfilter Documentation}
- at sp 3
 @end titlepage
 
+ at top
+
+ at contents
 
 @chapter Introduction
 
-Libavfilter is the filtering API of FFmpeg. It is the substitute of the
+Libavfilter is the filtering API of Libav. It is the substitute of the
 now deprecated 'vhooks' and started as a Google Summer of Code project.
 
-Integrating libavfilter into the main FFmpeg repository is a work in
+Integrating libavfilter into the main Libav repository is a work in
 progress. If you wish to try the unfinished development code of
 libavfilter then check it out from the libavfilter repository into
 some directory of your choice by:
 
 @example
-   svn checkout svn://svn.ffmpeg.org/soc/libavfilter
+   svn checkout svn://svn.libav.org/soc/libavfilter
 @end example
 
 And then read the README file in the top directory to learn how to
@@ -47,14 +48,14 @@ and the vflip filter before merging it back with the other stream by
 overlaying it on top. You can use the following command to achieve this:
 
 @example
-./ffmpeg -i in.avi -s 240x320 -vfilters "[in] split [T1], fifo, [T2] overlay= 0:240 [out]; [T1] fifo, crop=0:0:-1:240, vflip [T2]
+./ffmpeg -i in.avi -s 240x320 -vf "[in] split [T1], fifo, [T2] overlay= 0:240 [out]; [T1] fifo, crop=0:0:-1:240, vflip [T2]
 @end example
 
 where input_video.avi has a vertical resolution of 480 pixels. The
 result will be that in output the top half of the video is mirrored
 onto the bottom half.
 
-Video filters are loaded using the @var{-vfilters} option passed to
+Video filters are loaded using the @var{-vf} option passed to
 ffmpeg or to ffplay. Filters in the same linear chain are separated by
 commas. In our example, @var{split, fifo, overlay} are in one linear
 chain, and @var{fifo, crop, vflip} are in another. The points where
@@ -73,7 +74,7 @@ not have video output.
 
 @chapter graph2dot
 
-The @file{graph2dot} program included in the FFmpeg @file{tools}
+The @file{graph2dot} program included in the Libav @file{tools}
 directory can be used to parse a filter graph description and issue a
 corresponding textual representation in the dot language.
 
@@ -99,209 +100,6 @@ display graph.png
 can be used to create and display an image representing the graph
 described by the @var{GRAPH_DESCRIPTION} string.
 
- at chapter Available video filters
-
-When you configure your FFmpeg build, you can disable any of the
-existing video filters.
-The configure output will show the video filters included in your
-build.
-
-Below is a description of the currently available video filters.
-
- at section crop
-
-Crop the input video to @var{x}:@var{y}:@var{width}:@var{height}.
-
- at example
-./ffmpeg -i in.avi -vfilters "crop=0:0:0:240" out.avi
- at end example
-
- at var{x} and @var{y} specify the position of the top-left corner of the
-output (non-cropped) area.
-
-The default value of @var{x} and @var{y} is 0.
-
-The @var{width} and @var{height} parameters specify the width and height
-of the output (non-cropped) area.
-
-A value of 0 is interpreted as the maximum possible size contained in
-the area delimited by the top-left corner at position x:y.
-
-For example the parameters:
-
- at example
-"crop=100:100:0:0"
- at end example
-
-will delimit the rectangle with the top-left corner placed at position
-100:100 and the right-bottom corner corresponding to the right-bottom
-corner of the input image.
-
-The default value of @var{width} and @var{height} is 0.
-
- at section format
-
-Convert the input video to one of the specified pixel formats.
-Libavfilter will try to pick one that is supported for the input to
-the next filter.
-
-The filter accepts a list of pixel format names, separated by ``:'',
-for example ``yuv420p:monow:rgb24''.
-
-The following command:
-
- at example
-./ffmpeg -i in.avi -vfilters "format=yuv420p" out.avi
- at end example
-
-will convert the input video to the format ``yuv420p''.
-
- at section noformat
-
-Force libavfilter not to use any of the specified pixel formats for the
-input to the next filter.
-
-The filter accepts a list of pixel format names, separated by ``:'',
-for example ``yuv420p:monow:rgb24''.
-
-The following command:
-
- at example
-./ffmpeg -i in.avi -vfilters "noformat=yuv420p, vflip" out.avi
- at end example
-
-will make libavfilter use a format different from ``yuv420p'' for the
-input to the vflip filter.
-
- at section null
-
-Pass the source unchanged to the output.
-
- at section scale
-
-Scale the input video to @var{width}:@var{height} and/or convert the image format.
-
-For example the command:
-
- at example
-./ffmpeg -i in.avi -vfilters "scale=200:100" out.avi
- at end example
-
-will scale the input video to a size of 200x100.
-
-If the input image format is different from the format requested by
-the next filter, the scale filter will convert the input to the
-requested format.
-
-If the value for @var{width} or @var{height} is 0, the respective input
-size is used for the output.
-
-If the value for @var{width} or @var{height} is -1, the scale filter will
-use, for the respective output size, a value that maintains the aspect
-ratio of the input image.
-
-The default value of @var{width} and @var{height} is 0.
-
- at section slicify
-
-Pass the images of input video on to next video filter as multiple
-slices.
-
- at example
-./ffmpeg -i in.avi -vfilters "slicify=32" out.avi
- at end example
-
-The filter accepts the slice height as parameter. If the parameter is
-not specified it will use the default value of 16.
-
-Adding this in the beginning of filter chains should make filtering
-faster due to better use of the memory cache.
-
- at section unsharp
-
-Sharpen or blur the input video. It accepts the following parameters:
-
- at multitable @columnfractions .2 .5 .1 .1 .1
- at headitem Name @tab Description @tab Min @tab Max @tab Default
- at item @var{luma_msize_x}
- at tab Luma matrix horizontal size
- at tab 3
- at tab 13
- at tab 5
- at item @var{luma_msize_y}
- at tab Luma matrix vertical size
- at tab 3
- at tab 13
- at tab 5
- at item @var{luma_amount}
- at tab Luma effect strength
- at tab -2.0
- at tab 5.0
- at tab 1.0
- at item @var{chroma_msize_x}
- at tab Chroma matrix horizontal size
- at tab 3
- at tab 13
- at tab 0
- at item @var{chroma_msize_y}
- at tab Chroma matrix vertical size
- at tab 3
- at tab 13
- at tab 0
- at item @var{chroma_amount}
- at tab Chroma effect strength
- at tab -2.0
- at tab 5.0
- at tab 0.0
- at end multitable
-
-Negative values for the amount will blur the input video, while positive
-values will sharpen. All parameters are optional and default to the
-equivalent of the string '5:5:1.0:0:0:0.0'.
-
- at example
-# Strong luma sharpen effect parameters
-unsharp=7:7:2.5
-
-# Strong blur of both luma and chroma parameters
-unsharp=7:7:-2:7:7:-2
-
-# Use the default values with @command{ffmpeg}
-./ffmpeg -i in.avi -vfilters "unsharp" out.mp4
- at end example
-
- at section vflip
-
-Flip the input video vertically.
-
- at example
-./ffmpeg -i in.avi -vfilters "vflip" out.avi
- at end example
-
- at chapter Available video sources
-
-Below is a description of the currently available video sources.
-
- at section nullsrc
-
-Null video source, never return images. It is mainly useful as a
-template and to be employed in analysis / debugging tools.
-
-It accepts as optional parameter a string of the form
- at var{width}:@var{height}, where @var{width} and @var{height} specify the size of
-the configured source.
-
-The default values of @var{width} and @var{height} are respectively 352
-and 288 (corresponding to the CIF size format).
-
- at chapter Available video sinks
-
-Below is a description of the currently available video sinks.
-
- at section nullsink
-
-Null video sink, do absolutely nothing with the input video. It is
-mainly useful as a template and to be employed in analysis / debugging
-tools.
+ at include filters.texi
 
 @bye
diff --git a/doc/metadata.texi b/doc/metadata.texi
new file mode 100644
index 0000000..cfaf491
--- /dev/null
+++ b/doc/metadata.texi
@@ -0,0 +1,68 @@
+ at chapter Metadata
+ at c man begin METADATA
+
+Libav is able to dump metadata from media files into a simple UTF-8-encoded
+INI-like text file and then load it back using the metadata muxer/demuxer.
+
+The file format is as follows:
+ at enumerate
+
+ at item
+A file consists of a header and a number of metadata tags divided into sections,
+each on its own line.
+
+ at item
+The header is a ';FFMETADATA' string, followed by a version number (now 1).
+
+ at item
+Metadata tags are of the form 'key=value'
+
+ at item
+Immediately after header follows global metadata
+
+ at item
+After global metadata there may be sections with per-stream/per-chapter
+metadata.
+
+ at item
+A section starts with the section name in uppercase (i.e. STREAM or CHAPTER) in
+brackets ('[', ']') and ends with next section or end of file.
+
+ at item
+At the beginning of a chapter section there may be an optional timebase to be
+used for start/end values. It must be in form 'TIMEBASE=num/den', where num and
+den are integers. If the timebase is missing then start/end times are assumed to
+be in milliseconds.
+Next a chapter section must contain chapter start and end times in form
+'START=num', 'END=num', where num is a positive integer.
+
+ at item
+Empty lines and lines starting with ';' or '#' are ignored.
+
+ at item
+Metadata keys or values containing special characters ('=', ';', '#', '\' and a
+newline) must be escaped with a backslash '\'.
+
+ at item
+Note that whitespace in metadata (e.g. foo = bar) is considered to be a part of
+the tag (in the example above key is 'foo ', value is ' bar').
+ at end enumerate
+
+A ffmetadata file might look like this:
+ at example
+;FFMETADATA1
+title=bike\\shed
+;this is a comment
+artist=Libav troll team
+
+[CHAPTER]
+TIMEBASE=1/1000
+START=0
+#chapter ends at 0:01:00
+END=60000
+title=chapter \#1
+[STREAM]
+title=multi\
+line
+ at end example
+ at c man end METADATA
diff --git a/doc/multithreading.txt b/doc/multithreading.txt
new file mode 100644
index 0000000..b72bc16
--- /dev/null
+++ b/doc/multithreading.txt
@@ -0,0 +1,65 @@
+Libav multithreading methods
+==============================================
+
+Libav provides two methods for multithreading codecs.
+
+Slice threading decodes multiple parts of a frame at the same time, using
+AVCodecContext execute() and execute2().
+
+Frame threading decodes multiple frames at the same time.
+It accepts N future frames and delays decoded pictures by N-1 frames.
+The later frames are decoded in separate threads while the user is
+displaying the current one.
+
+Restrictions on clients
+==============================================
+
+Slice threading -
+* The client's draw_horiz_band() must be thread-safe according to the comment
+  in avcodec.h.
+
+Frame threading -
+* Restrictions with slice threading also apply.
+* For best performance, the client should set thread_safe_callbacks if it
+  provides a thread-safe get_buffer() callback.
+* There is one frame of delay added for every thread beyond the first one.
+  Clients must be able to handle this; the pkt_dts and pkt_pts fields in
+  AVFrame will work as usual.
+
+Restrictions on codec implementations
+==============================================
+
+Slice threading -
+ None except that there must be something worth executing in parallel.
+
+Frame threading -
+* Codecs can only accept entire pictures per packet.
+* Codecs similar to ffv1, whose streams don't reset across frames,
+  will not work because their bitstreams cannot be decoded in parallel.
+
+* The contents of buffers must not be read before ff_thread_await_progress()
+  has been called on them. reget_buffer() and buffer age optimizations no longer work.
+* The contents of buffers must not be written to after ff_thread_report_progress()
+  has been called on them. This includes draw_edges().
+
+Porting codecs to frame threading
+==============================================
+
+Find all context variables that are needed by the next frame. Move all
+code changing them, as well as code calling get_buffer(), up to before
+the decode process starts. Call ff_thread_finish_setup() afterwards. If
+some code can't be moved, have update_thread_context() run it in the next
+thread.
+
+If the codec allocates writable tables in its init(), add an init_thread_copy()
+which re-allocates them for other threads.
+
+Add CODEC_CAP_FRAME_THREADS to the codec capabilities. There will be very little
+speed gain at this point but it should work.
+
+Call ff_thread_report_progress() after some part of the current picture has decoded.
+A good place to put this is where draw_horiz_band() is called - add this if it isn't
+called anywhere, as it's useful too and the implementation is trivial when you're
+doing this. Note that draw_edges() needs to be called before reporting progress.
+
+Before accessing a reference frame or its MVs, call ff_thread_await_progress().
diff --git a/doc/muxers.texi b/doc/muxers.texi
new file mode 100644
index 0000000..82f17ba
--- /dev/null
+++ b/doc/muxers.texi
@@ -0,0 +1,207 @@
+ at chapter Muxers
+ at c man begin MUXERS
+
+Muxers are configured elements in Libav which allow writing
+multimedia streams to a particular type of file.
+
+When you configure your Libav build, all the supported muxers
+are enabled by default. You can list all available muxers using the
+configure option @code{--list-muxers}.
+
+You can disable all the muxers with the configure option
+ at code{--disable-muxers} and selectively enable / disable single muxers
+with the options @code{--enable-muxer=@var{MUXER}} /
+ at code{--disable-muxer=@var{MUXER}}.
+
+The option @code{-formats} of the ff* tools will display the list of
+enabled muxers.
+
+A description of some of the currently available muxers follows.
+
+ at anchor{crc}
+ at section crc
+
+CRC (Cyclic Redundancy Check) testing format.
+
+This muxer computes and prints the Adler-32 CRC of all the input audio
+and video frames. By default audio frames are converted to signed
+16-bit raw audio and video frames to raw video before computing the
+CRC.
+
+The output of the muxer consists of a single line of the form:
+CRC=0x at var{CRC}, where @var{CRC} is a hexadecimal number 0-padded to
+8 digits containing the CRC for all the decoded input frames.
+
+For example to compute the CRC of the input, and store it in the file
+ at file{out.crc}:
+ at example
+ffmpeg -i INPUT -f crc out.crc
+ at end example
+
+You can print the CRC to stdout with the command:
+ at example
+ffmpeg -i INPUT -f crc -
+ at end example
+
+You can select the output format of each frame with @file{ffmpeg} by
+specifying the audio and video codec and format. For example to
+compute the CRC of the input audio converted to PCM unsigned 8-bit
+and the input video converted to MPEG-2 video, use the command:
+ at example
+ffmpeg -i INPUT -acodec pcm_u8 -vcodec mpeg2video -f crc -
+ at end example
+
+See also the @code{framecrc} muxer (@pxref{framecrc}).
+
+ at anchor{framecrc}
+ at section framecrc
+
+Per-frame CRC (Cyclic Redundancy Check) testing format.
+
+This muxer computes and prints the Adler-32 CRC for each decoded audio
+and video frame. By default audio frames are converted to signed
+16-bit raw audio and video frames to raw video before computing the
+CRC.
+
+The output of the muxer consists of a line for each audio and video
+frame of the form: @var{stream_index}, @var{frame_dts},
+ at var{frame_size}, 0x at var{CRC}, where @var{CRC} is a hexadecimal
+number 0-padded to 8 digits containing the CRC of the decoded frame.
+
+For example to compute the CRC of each decoded frame in the input, and
+store it in the file @file{out.crc}:
+ at example
+ffmpeg -i INPUT -f framecrc out.crc
+ at end example
+
+You can print the CRC of each decoded frame to stdout with the command:
+ at example
+ffmpeg -i INPUT -f framecrc -
+ at end example
+
+You can select the output format of each frame with @file{ffmpeg} by
+specifying the audio and video codec and format. For example, to
+compute the CRC of each decoded input audio frame converted to PCM
+unsigned 8-bit and of each decoded input video frame converted to
+MPEG-2 video, use the command:
+ at example
+ffmpeg -i INPUT -acodec pcm_u8 -vcodec mpeg2video -f framecrc -
+ at end example
+
+See also the @code{crc} muxer (@pxref{crc}).
+
+ at section image2
+
+Image file muxer.
+
+The image file muxer writes video frames to image files.
+
+The output filenames are specified by a pattern, which can be used to
+produce sequentially numbered series of files.
+The pattern may contain the string "%d" or "%0 at var{N}d", this string
+specifies the position of the characters representing a numbering in
+the filenames. If the form "%0 at var{N}d" is used, the string
+representing the number in each filename is 0-padded to @var{N}
+digits. The literal character '%' can be specified in the pattern with
+the string "%%".
+
+If the pattern contains "%d" or "%0 at var{N}d", the first filename of
+the file list specified will contain the number 1, all the following
+numbers will be sequential.
+
+The pattern may contain a suffix which is used to automatically
+determine the format of the image files to write.
+
+For example the pattern "img-%03d.bmp" will specify a sequence of
+filenames of the form @file{img-001.bmp}, @file{img-002.bmp}, ...,
+ at file{img-010.bmp}, etc.
+The pattern "img%%-%d.jpg" will specify a sequence of filenames of the
+form @file{img%-1.jpg}, @file{img%-2.jpg}, ..., @file{img%-10.jpg},
+etc.
+
+The following example shows how to use @file{ffmpeg} for creating a
+sequence of files @file{img-001.jpeg}, @file{img-002.jpeg}, ...,
+taking one image every second from the input video:
+ at example
+ffmpeg -i in.avi -r 1 -f image2 'img-%03d.jpeg'
+ at end example
+
+Note that with @file{ffmpeg}, if the format is not specified with the
+ at code{-f} option and the output filename specifies an image file
+format, the image2 muxer is automatically selected, so the previous
+command can be written as:
+ at example
+ffmpeg -i in.avi -r 1 'img-%03d.jpeg'
+ at end example
+
+Note also that the pattern must not necessarily contain "%d" or
+"%0 at var{N}d", for example to create a single image file
+ at file{img.jpeg} from the input video you can employ the command:
+ at example
+ffmpeg -i in.avi -f image2 -vframes 1 img.jpeg
+ at end example
+
+ at section mpegts
+
+MPEG transport stream muxer.
+
+This muxer implements ISO 13818-1 and part of ETSI EN 300 468.
+
+The muxer options are:
+
+ at table @option
+ at item -mpegts_original_network_id @var{number}
+Set the original_network_id (default 0x0001). This is unique identifier
+of a network in DVB. Its main use is in the unique identification of a
+service through the path Original_Network_ID, Transport_Stream_ID.
+ at item -mpegts_transport_stream_id @var{number}
+Set the transport_stream_id (default 0x0001). This identifies a
+transponder in DVB.
+ at item -mpegts_service_id @var{number}
+Set the service_id (default 0x0001) also known as program in DVB.
+ at item -mpegts_pmt_start_pid @var{number}
+Set the first PID for PMT (default 0x1000, max 0x1f00).
+ at item -mpegts_start_pid @var{number}
+Set the first PID for data packets (default 0x0100, max 0x0f00).
+ at end table
+
+The recognized metadata settings in mpegts muxer are @code{service_provider}
+and @code{service_name}. If they are not set the default for
+ at code{service_provider} is "Libav" and the default for
+ at code{service_name} is "Service01".
+
+ at example
+ffmpeg -i file.mpg -acodec copy -vcodec copy \
+     -mpegts_original_network_id 0x1122 \
+     -mpegts_transport_stream_id 0x3344 \
+     -mpegts_service_id 0x5566 \
+     -mpegts_pmt_start_pid 0x1500 \
+     -mpegts_start_pid 0x150 \
+     -metadata service_provider="Some provider" \
+     -metadata service_name="Some Channel" \
+     -y out.ts
+ at end example
+
+ at section null
+
+Null muxer.
+
+This muxer does not generate any output file, it is mainly useful for
+testing or benchmarking purposes.
+
+For example to benchmark decoding with @file{ffmpeg} you can use the
+command:
+ at example
+ffmpeg -benchmark -i INPUT -f null out.null
+ at end example
+
+Note that the above command does not read or write the @file{out.null}
+file, but specifying the output file is required by the @file{ffmpeg}
+syntax.
+
+Alternatively you can write the command as:
+ at example
+ffmpeg -benchmark -i INPUT -f null -
+ at end example
+
+ at c man end MUXERS
diff --git a/doc/optimization.txt b/doc/optimization.txt
index 5469adc..78e0077 100644
--- a/doc/optimization.txt
+++ b/doc/optimization.txt
@@ -17,15 +17,15 @@ Understanding these overoptimized functions:
 As many functions tend to be a bit difficult to understand because
 of optimizations, it can be hard to optimize them further, or write
 architecture-specific versions. It is recommended to look at older
-revisions of the interesting files (for a web frontend try ViewVC at
-http://svn.ffmpeg.org/ffmpeg/trunk/).
+revisions of the interesting files (web frontends for the various Libav
+branches are listed at http://libav.org/download.html).
 Alternatively, look into the other architecture-specific versions in
 the x86/, ppc/, alpha/ subdirectories. Even if you don't exactly
 comprehend the instructions, it could help understanding the functions
 and how they can be optimized.
 
 NOTE: If you still don't understand some function, ask at our mailing list!!!
-(http://lists.mplayerhq.hu/mailman/listinfo/ffmpeg-devel)
+(https://lists.libav.org/mailman/listinfo/libav-devel)
 
 
 When is an optimization justified?
@@ -157,15 +157,68 @@ Use asm loops like:
 __asm__(
     "1: ....
     ...
-    "jump_instruciton ....
+    "jump_instruction ....
 Do not use C loops:
 do{
     __asm__(
         ...
 }while()
 
-Use __asm__() instead of intrinsics. The latter requires a good optimizing compiler
-which gcc is not.
+For x86, mark registers that are clobbered in your asm. This means both
+general x86 registers (e.g. eax) as well as XMM registers. This last one is
+particularly important on Win64, where xmm6-15 are callee-save, and not
+restoring their contents leads to undefined results. In external asm (e.g.
+yasm), you do this by using:
+cglobal functon_name, num_args, num_regs, num_xmm_regs
+In inline asm, you specify clobbered registers at the end of your asm:
+__asm__(".." ::: "%eax").
+If gcc is not set to support sse (-msse) it will not accept xmm registers
+in the clobber list. For that we use two macros to declare the clobbers.
+XMM_CLOBBERS should be used when there are other clobbers, for example:
+__asm__(".." ::: XMM_CLOBBERS("xmm0",) "eax");
+and XMM_CLOBBERS_ONLY should be used when the only clobbers are xmm registers:
+__asm__(".." :: XMM_CLOBBERS_ONLY("xmm0"));
+
+Do not expect a compiler to maintain values in your registers between separate
+(inline) asm code blocks. It is not required to. For example, this is bad:
+__asm__("movdqa %0, %%xmm7" : src);
+/* do something */
+__asm__("movdqa %%xmm7, %1" : dst);
+- first of all, you're assuming that the compiler will not use xmm7 in
+   between the two asm blocks.  It probably won't when you test it, but it's
+   a poor assumption that will break at some point for some --cpu compiler flag
+- secondly, you didn't mark xmm7 as clobbered. If you did, the compiler would
+   have restored the original value of xmm7 after the first asm block, thus
+   rendering the combination of the two blocks of code invalid
+Code that depends on data in registries being untouched, should be written as
+a single __asm__() statement. Ideally, a single function contains only one
+__asm__() block.
+
+Use external asm (nasm/yasm) or inline asm (__asm__()), do not use intrinsics.
+The latter requires a good optimizing compiler which gcc is not.
+
+Inline asm vs. external asm
+---------------------------
+Both inline asm (__asm__("..") in a .c file, handled by a compiler such as gcc)
+and external asm (.s or .asm files, handled by an assembler such as yasm/nasm)
+are accepted in Libav. Which one to use differs per specific case.
+
+- if your code is intended to be inlined in a C function, inline asm is always
+   better, because external asm cannot be inlined
+- if your code calls external functions, yasm is always better
+- if your code takes huge and complex structs as function arguments (e.g.
+   MpegEncContext; note that this is not ideal and is discouraged if there
+   are alternatives), then inline asm is always better, because predicting
+   member offsets in complex structs is almost impossible. It's safest to let
+   the compiler take care of that
+- in many cases, both can be used and it just depends on the preference of the
+   person writing the asm. For new asm, the choice is up to you. For existing
+   asm, you'll likely want to maintain whatever form it is currently in unless
+   there is a good reason to change it.
+- if, for some reason, you believe that a particular chunk of existing external
+   asm could be improved upon further if written in inline asm (or the other
+   way around), then please make the move from external asm <-> inline asm a
+   separate patch before your patches that actually improve the asm.
 
 
 Links:
diff --git a/doc/outdevs.texi b/doc/outdevs.texi
new file mode 100644
index 0000000..938909c
--- /dev/null
+++ b/doc/outdevs.texi
@@ -0,0 +1,33 @@
+ at chapter Output Devices
+ at c man begin OUTPUT DEVICES
+
+Output devices are configured elements in Libav which allow to write
+multimedia data to an output device attached to your system.
+
+When you configure your Libav build, all the supported output devices
+are enabled by default. You can list all available ones using the
+configure option "--list-outdevs".
+
+You can disable all the output devices using the configure option
+"--disable-outdevs", and selectively enable an output device using the
+option "--enable-outdev=@var{OUTDEV}", or you can disable a particular
+input device using the option "--disable-outdev=@var{OUTDEV}".
+
+The option "-formats" of the ff* tools will display the list of
+enabled output devices (amongst the muxers).
+
+A description of the currently available output devices follows.
+
+ at section alsa
+
+ALSA (Advanced Linux Sound Architecture) output device.
+
+ at section oss
+
+OSS (Open Sound System) output device.
+
+ at section sndio
+
+sndio audio output device.
+
+ at c man end OUTPUT DEVICES
diff --git a/doc/protocols.texi b/doc/protocols.texi
new file mode 100644
index 0000000..18749ef
--- /dev/null
+++ b/doc/protocols.texi
@@ -0,0 +1,480 @@
+ at chapter Protocols
+ at c man begin PROTOCOLS
+
+Protocols are configured elements in Libav which allow to access
+resources which require the use of a particular protocol.
+
+When you configure your Libav build, all the supported protocols are
+enabled by default. You can list all available ones using the
+configure option "--list-protocols".
+
+You can disable all the protocols using the configure option
+"--disable-protocols", and selectively enable a protocol using the
+option "--enable-protocol=@var{PROTOCOL}", or you can disable a
+particular protocol using the option
+"--disable-protocol=@var{PROTOCOL}".
+
+The option "-protocols" of the ff* tools will display the list of
+supported protocols.
+
+A description of the currently available protocols follows.
+
+ at section applehttp
+
+Read Apple HTTP Live Streaming compliant segmented stream as
+a uniform one. The M3U8 playlists describing the segments can be
+remote HTTP resources or local files, accessed using the standard
+file protocol.
+HTTP is default, specific protocol can be declared by specifying
+"+ at var{proto}" after the applehttp URI scheme name, where @var{proto}
+is either "file" or "http".
+
+ at example
+applehttp://host/path/to/remote/resource.m3u8
+applehttp+http://host/path/to/remote/resource.m3u8
+applehttp+file://path/to/local/resource.m3u8
+ at end example
+
+ at section concat
+
+Physical concatenation protocol.
+
+Allow to read and seek from many resource in sequence as if they were
+a unique resource.
+
+A URL accepted by this protocol has the syntax:
+ at example
+concat:@var{URL1}|@var{URL2}|...|@var{URLN}
+ at end example
+
+where @var{URL1}, @var{URL2}, ..., @var{URLN} are the urls of the
+resource to be concatenated, each one possibly specifying a distinct
+protocol.
+
+For example to read a sequence of files @file{split1.mpeg},
+ at file{split2.mpeg}, @file{split3.mpeg} with @file{ffplay} use the
+command:
+ at example
+ffplay concat:split1.mpeg\|split2.mpeg\|split3.mpeg
+ at end example
+
+Note that you may need to escape the character "|" which is special for
+many shells.
+
+ at section file
+
+File access protocol.
+
+Allow to read from or read to a file.
+
+For example to read from a file @file{input.mpeg} with @file{ffmpeg}
+use the command:
+ at example
+ffmpeg -i file:input.mpeg output.mpeg
+ at end example
+
+The ff* tools default to the file protocol, that is a resource
+specified with the name "FILE.mpeg" is interpreted as the URL
+"file:FILE.mpeg".
+
+ at section gopher
+
+Gopher protocol.
+
+ at section http
+
+HTTP (Hyper Text Transfer Protocol).
+
+ at section mmst
+
+MMS (Microsoft Media Server) protocol over TCP.
+
+ at section mmsh
+
+MMS (Microsoft Media Server) protocol over HTTP.
+
+The required syntax is:
+ at example
+mmsh://@var{server}[:@var{port}][/@var{app}][/@var{playpath}]
+ at end example
+
+ at section md5
+
+MD5 output protocol.
+
+Computes the MD5 hash of the data to be written, and on close writes
+this to the designated output or stdout if none is specified. It can
+be used to test muxers without writing an actual file.
+
+Some examples follow.
+ at example
+# Write the MD5 hash of the encoded AVI file to the file output.avi.md5.
+ffmpeg -i input.flv -f avi -y md5:output.avi.md5
+
+# Write the MD5 hash of the encoded AVI file to stdout.
+ffmpeg -i input.flv -f avi -y md5:
+ at end example
+
+Note that some formats (typically MOV) require the output protocol to
+be seekable, so they will fail with the MD5 output protocol.
+
+ at section pipe
+
+UNIX pipe access protocol.
+
+Allow to read and write from UNIX pipes.
+
+The accepted syntax is:
+ at example
+pipe:[@var{number}]
+ at end example
+
+ at var{number} is the number corresponding to the file descriptor of the
+pipe (e.g. 0 for stdin, 1 for stdout, 2 for stderr).  If @var{number}
+is not specified, by default the stdout file descriptor will be used
+for writing, stdin for reading.
+
+For example to read from stdin with @file{ffmpeg}:
+ at example
+cat test.wav | ffmpeg -i pipe:0
+# ...this is the same as...
+cat test.wav | ffmpeg -i pipe:
+ at end example
+
+For writing to stdout with @file{ffmpeg}:
+ at example
+ffmpeg -i test.wav -f avi pipe:1 | cat > test.avi
+# ...this is the same as...
+ffmpeg -i test.wav -f avi pipe: | cat > test.avi
+ at end example
+
+Note that some formats (typically MOV), require the output protocol to
+be seekable, so they will fail with the pipe output protocol.
+
+ at section rtmp
+
+Real-Time Messaging Protocol.
+
+The Real-Time Messaging Protocol (RTMP) is used for streaming multime‐
+dia content across a TCP/IP network.
+
+The required syntax is:
+ at example
+rtmp://@var{server}[:@var{port}][/@var{app}][/@var{playpath}]
+ at end example
+
+The accepted parameters are:
+ at table @option
+
+ at item server
+The address of the RTMP server.
+
+ at item port
+The number of the TCP port to use (by default is 1935).
+
+ at item app
+It is the name of the application to access. It usually corresponds to
+the path where the application is installed on the RTMP server
+(e.g. @file{/ondemand/}, @file{/flash/live/}, etc.).
+
+ at item playpath
+It is the path or name of the resource to play with reference to the
+application specified in @var{app}, may be prefixed by "mp4:".
+
+ at end table
+
+For example to read with @file{ffplay} a multimedia resource named
+"sample" from the application "vod" from an RTMP server "myserver":
+ at example
+ffplay rtmp://myserver/vod/sample
+ at end example
+
+ at section rtmp, rtmpe, rtmps, rtmpt, rtmpte
+
+Real-Time Messaging Protocol and its variants supported through
+librtmp.
+
+Requires the presence of the librtmp headers and library during
+configuration. You need to explicitely configure the build with
+"--enable-librtmp". If enabled this will replace the native RTMP
+protocol.
+
+This protocol provides most client functions and a few server
+functions needed to support RTMP, RTMP tunneled in HTTP (RTMPT),
+encrypted RTMP (RTMPE), RTMP over SSL/TLS (RTMPS) and tunneled
+variants of these encrypted types (RTMPTE, RTMPTS).
+
+The required syntax is:
+ at example
+ at var{rtmp_proto}://@var{server}[:@var{port}][/@var{app}][/@var{playpath}] @var{options}
+ at end example
+
+where @var{rtmp_proto} is one of the strings "rtmp", "rtmpt", "rtmpe",
+"rtmps", "rtmpte", "rtmpts" corresponding to each RTMP variant, and
+ at var{server}, @var{port}, @var{app} and @var{playpath} have the same
+meaning as specified for the RTMP native protocol.
+ at var{options} contains a list of space-separated options of the form
+ at var{key}=@var{val}.
+
+See the librtmp manual page (man 3 librtmp) for more information.
+
+For example, to stream a file in real-time to an RTMP server using
+ at file{ffmpeg}:
+ at example
+ffmpeg -re -i myfile -f flv rtmp://myserver/live/mystream
+ at end example
+
+To play the same stream using @file{ffplay}:
+ at example
+ffplay "rtmp://myserver/live/mystream live=1"
+ at end example
+
+ at section rtp
+
+Real-Time Protocol.
+
+ at section rtsp
+
+RTSP is not technically a protocol handler in libavformat, it is a demuxer
+and muxer. The demuxer supports both normal RTSP (with data transferred
+over RTP; this is used by e.g. Apple and Microsoft) and Real-RTSP (with
+data transferred over RDT).
+
+The muxer can be used to send a stream using RTSP ANNOUNCE to a server
+supporting it (currently Darwin Streaming Server and Mischa Spiegelmock's
+RTSP server, @url{http://github.com/revmischa/rtsp-server}).
+
+The required syntax for a RTSP url is:
+ at example
+rtsp://@var{hostname}[:@var{port}]/@var{path}[?@var{options}]
+ at end example
+
+ at var{options} is a @code{&}-separated list. The following options
+are supported:
+
+ at table @option
+
+ at item udp
+Use UDP as lower transport protocol.
+
+ at item tcp
+Use TCP (interleaving within the RTSP control channel) as lower
+transport protocol.
+
+ at item multicast
+Use UDP multicast as lower transport protocol.
+
+ at item http
+Use HTTP tunneling as lower transport protocol, which is useful for
+passing proxies.
+
+ at item filter_src
+Accept packets only from negotiated peer address and port.
+ at end table
+
+Multiple lower transport protocols may be specified, in that case they are
+tried one at a time (if the setup of one fails, the next one is tried).
+For the muxer, only the @code{tcp} and @code{udp} options are supported.
+
+When receiving data over UDP, the demuxer tries to reorder received packets
+(since they may arrive out of order, or packets may get lost totally). In
+order for this to be enabled, a maximum delay must be specified in the
+ at code{max_delay} field of AVFormatContext.
+
+When watching multi-bitrate Real-RTSP streams with @file{ffplay}, the
+streams to display can be chosen with @code{-vst} @var{n} and
+ at code{-ast} @var{n} for video and audio respectively, and can be switched
+on the fly by pressing @code{v} and @code{a}.
+
+Example command lines:
+
+To watch a stream over UDP, with a max reordering delay of 0.5 seconds:
+
+ at example
+ffplay -max_delay 500000 rtsp://server/video.mp4?udp
+ at end example
+
+To watch a stream tunneled over HTTP:
+
+ at example
+ffplay rtsp://server/video.mp4?http
+ at end example
+
+To send a stream in realtime to a RTSP server, for others to watch:
+
+ at example
+ffmpeg -re -i @var{input} -f rtsp -muxdelay 0.1 rtsp://server/live.sdp
+ at end example
+
+ at section sap
+
+Session Announcement Protocol (RFC 2974). This is not technically a
+protocol handler in libavformat, it is a muxer and demuxer.
+It is used for signalling of RTP streams, by announcing the SDP for the
+streams regularly on a separate port.
+
+ at subsection Muxer
+
+The syntax for a SAP url given to the muxer is:
+ at example
+sap://@var{destination}[:@var{port}][?@var{options}]
+ at end example
+
+The RTP packets are sent to @var{destination} on port @var{port},
+or to port 5004 if no port is specified.
+ at var{options} is a @code{&}-separated list. The following options
+are supported:
+
+ at table @option
+
+ at item announce_addr=@var{address}
+Specify the destination IP address for sending the announcements to.
+If omitted, the announcements are sent to the commonly used SAP
+announcement multicast address 224.2.127.254 (sap.mcast.net), or
+ff0e::2:7ffe if @var{destination} is an IPv6 address.
+
+ at item announce_port=@var{port}
+Specify the port to send the announcements on, defaults to
+9875 if not specified.
+
+ at item ttl=@var{ttl}
+Specify the time to live value for the announcements and RTP packets,
+defaults to 255.
+
+ at item same_port=@var{0|1}
+If set to 1, send all RTP streams on the same port pair. If zero (the
+default), all streams are sent on unique ports, with each stream on a
+port 2 numbers higher than the previous.
+VLC/Live555 requires this to be set to 1, to be able to receive the stream.
+The RTP stack in libavformat for receiving requires all streams to be sent
+on unique ports.
+ at end table
+
+Example command lines follow.
+
+To broadcast a stream on the local subnet, for watching in VLC:
+
+ at example
+ffmpeg -re -i @var{input} -f sap sap://224.0.0.255?same_port=1
+ at end example
+
+Similarly, for watching in ffplay:
+
+ at example
+ffmpeg -re -i @var{input} -f sap sap://224.0.0.255
+ at end example
+
+And for watching in ffplay, over IPv6:
+
+ at example
+ffmpeg -re -i @var{input} -f sap sap://[ff0e::1:2:3:4]
+ at end example
+
+ at subsection Demuxer
+
+The syntax for a SAP url given to the demuxer is:
+ at example
+sap://[@var{address}][:@var{port}]
+ at end example
+
+ at var{address} is the multicast address to listen for announcements on,
+if omitted, the default 224.2.127.254 (sap.mcast.net) is used. @var{port}
+is the port that is listened on, 9875 if omitted.
+
+The demuxers listens for announcements on the given address and port.
+Once an announcement is received, it tries to receive that particular stream.
+
+Example command lines follow.
+
+To play back the first stream announced on the normal SAP multicast address:
+
+ at example
+ffplay sap://
+ at end example
+
+To play back the first stream announced on one the default IPv6 SAP multicast address:
+
+ at example
+ffplay sap://[ff0e::2:7ffe]
+ at end example
+
+ at section tcp
+
+Trasmission Control Protocol.
+
+The required syntax for a TCP url is:
+ at example
+tcp://@var{hostname}:@var{port}[?@var{options}]
+ at end example
+
+ at table @option
+
+ at item listen
+Listen for an incoming connection
+
+ at example
+ffmpeg -i @var{input} -f @var{format} tcp://@var{hostname}:@var{port}?listen
+ffplay tcp://@var{hostname}:@var{port}
+ at end example
+
+ at end table
+
+ at section udp
+
+User Datagram Protocol.
+
+The required syntax for a UDP url is:
+ at example
+udp://@var{hostname}:@var{port}[?@var{options}]
+ at end example
+
+ at var{options} contains a list of &-seperated options of the form @var{key}=@var{val}.
+Follow the list of supported options.
+
+ at table @option
+
+ at item buffer_size=@var{size}
+set the UDP buffer size in bytes
+
+ at item localport=@var{port}
+override the local UDP port to bind with
+
+ at item pkt_size=@var{size}
+set the size in bytes of UDP packets
+
+ at item reuse=@var{1|0}
+explicitly allow or disallow reusing UDP sockets
+
+ at item ttl=@var{ttl}
+set the time to live value (for multicast only)
+
+ at item connect=@var{1|0}
+Initialize the UDP socket with @code{connect()}. In this case, the
+destination address can't be changed with ff_udp_set_remote_url later.
+If the destination address isn't known at the start, this option can
+be specified in ff_udp_set_remote_url, too.
+This allows finding out the source address for the packets with getsockname,
+and makes writes return with AVERROR(ECONNREFUSED) if "destination
+unreachable" is received.
+For receiving, this gives the benefit of only receiving packets from
+the specified peer address/port.
+ at end table
+
+Some usage examples of the udp protocol with @file{ffmpeg} follow.
+
+To stream over UDP to a remote endpoint:
+ at example
+ffmpeg -i @var{input} -f @var{format} udp://@var{hostname}:@var{port}
+ at end example
+
+To stream in mpegts format over UDP using 188 sized UDP packets, using a large input buffer:
+ at example
+ffmpeg -i @var{input} -f mpegts udp://@var{hostname}:@var{port}?pkt_size=188&buffer_size=65535
+ at end example
+
+To receive over UDP from a remote endpoint:
+ at example
+ffmpeg -i udp://[@var{multicast-address}]:@var{port}
+ at end example
+
+ at c man end PROTOCOLS
diff --git a/doc/soc.txt b/doc/soc.txt
index 8b4a86d..e45bd6c 100644
--- a/doc/soc.txt
+++ b/doc/soc.txt
@@ -8,17 +8,17 @@ it's a little late for this year's soc (2006).
 
 The Goal:
 Our goal in respect to soc is and must be of course exactly one thing and
-that is to improve FFmpeg, to reach this goal, code must
-* conform to the svn policy and patch submission guidelines
-* must improve FFmpeg somehow (faster, smaller, "better",
+that is to improve Libav, to reach this goal, code must
+* conform to the development policy and patch submission guidelines
+* must improve Libav somehow (faster, smaller, "better",
   more codecs supported, fewer bugs, cleaner, ...)
 
 for mentors and other developers to help students to reach that goal it is
 essential that changes to their codebase are publicly visible, clean and
 easy reviewable that again leads us to:
-* use of a revision control system like svn
+* use of a revision control system like git
 * separation of cosmetic from non-cosmetic changes (this is almost entirely
   ignored by mentors and students in soc 2006 which might lead to a suprise
   when the code will be reviewed at the end before a possible inclusion in
-  FFmpeg, individual changes were generally not reviewable due to cosmetics).
+  Libav, individual changes were generally not reviewable due to cosmetics).
 * frequent commits, so that comments can be provided early
diff --git a/doc/t2h.init b/doc/t2h.init
new file mode 100644
index 0000000..cd38a3e
--- /dev/null
+++ b/doc/t2h.init
@@ -0,0 +1,24 @@
+# no horiz rules between sections
+$end_section = \&FFMPEG_end_section;
+sub FFMPEG_end_section($$)
+{
+}
+
+$print_page_foot = \&FFMPEG_print_page_foot;
+sub FFMPEG_print_page_foot($$)
+{
+    my $fh = shift;
+    print $fh "$SMALL_RULE\n";
+    T2H_DEFAULT_print_page_foot($fh);
+}
+
+# no navigation elements
+$SECTION_NAVIGATION = 0;
+# the same for texi2html 5.0
+$HEADERS = 0;
+
+# TOC and Chapter headings link
+$TOC_LINKS = 1;
+
+# print the TOC where @contents is used
+$INLINE_CONTENTS = 1;
diff --git a/doc/tablegen.txt b/doc/tablegen.txt
index 8dfcd7d..4c4f036 100644
--- a/doc/tablegen.txt
+++ b/doc/tablegen.txt
@@ -12,6 +12,7 @@ the tables as a header file using the tableprint.h helpers.
 Both of these files will be compiled for the host system, so to avoid
 breakage with cross-compilation neither of them may include, directly
 or indirectly, config.h or avconfig.h.
+This means that e.g. libavutil/mathematics.h is ok but libavutil/libm.h is not.
 Due to this, the .c file or Makefile may have to provide additional defines
 or stubs, though if possible this should be avoided.
 In particular, CONFIG_HARDCODED_TABLES should always be defined to 0.
@@ -27,9 +28,14 @@ them.
 The printing code typically looks like this:
     write_fileheader();
     printf("static const uint8_t my_array[100] = {\n");
-    write_uint8_array(my_array, 100);
+    write_uint8_t_array(my_array, 100);
     printf("};\n");
 
+This is the more generic form, in case you need to do something special.
+Usually you should instead use the short form:
+    write_fileheader();
+    WRITE_ARRAY("static const", uint8_t, my_array);
+
 write_fileheader() adds some minor things like a "this is a generated file"
 comment and some standard includes.
 tablegen.h defines some write functions for one- and two-dimensional arrays
diff --git a/doc/texi2pod.pl b/doc/texi2pod.pl
index c414ffc..84c36ff 100755
--- a/doc/texi2pod.pl
+++ b/doc/texi2pod.pl
@@ -26,6 +26,7 @@
 $output = 0;
 $skipping = 0;
 %sects = ();
+ at sects_sequence = ();
 $section = "";
 @icstack = ();
 @endwstack = ();
@@ -99,15 +100,21 @@ while(<$inf>) {
         next;
     };
 
+    /^\@include\s+(.+)$/ and do {
+        push @instack, $inf;
+        $inf = gensym();
+
+        # Try cwd and $ibase.
+        open($inf, "<" . $1)
+            or open($inf, "<" . $ibase . "/" . $1)
+                or die "cannot open $1 or $ibase/$1: $!\n";
+        next;
+    };
+
     # Look for blocks surrounded by @c man begin SECTION ... @c man end.
     # This really oughta be @ifman ... @end ifman and the like, but such
     # would require rev'ing all other Texinfo translators.
-    /^\@c\s+man\s+begin\s+([A-Z]+)\s+([A-Za-z0-9-]+)/ and do {
-        $output = 1 if exists $defs{$2};
-        $sect = $1;
-        next;
-    };
-    /^\@c\s+man\s+begin\s+([A-Z]+)/ and $sect = $1, $output = 1, next;
+    /^\@c\s+man\s+begin\s+([A-Za-z ]+)/ and $sect = $1, push (@sects_sequence, $sect), $output = 1, next;
     /^\@c\s+man\s+end/ and do {
         $sects{$sect} = "" unless exists $sects{$sect};
         $sects{$sect} .= postprocess($section);
@@ -224,27 +231,18 @@ while(<$inf>) {
 
     # Single line command handlers.
 
-    /^\@include\s+(.+)$/ and do {
-        push @instack, $inf;
-        $inf = gensym();
-
-        # Try cwd and $ibase.
-        open($inf, "<" . $1)
-            or open($inf, "<" . $ibase . "/" . $1)
-                or die "cannot open $1 or $ibase/$1: $!\n";
-        next;
-    };
-
-    /^\@(?:section|unnumbered|unnumberedsec|center)\s+(.+)$/
+    /^\@(?:section|unnumbered|unnumberedsec|center|heading)\s+(.+)$/
         and $_ = "\n=head2 $1\n";
-    /^\@subsection\s+(.+)$/
+    /^\@(?:subsection|subheading)\s+(.+)$/
         and $_ = "\n=head3 $1\n";
+    /^\@(?:subsubsection|subsubheading)\s+(.+)$/
+        and $_ = "\n=head4 $1\n";
 
     # Block command handlers:
-    /^\@itemize\s+(\@[a-z]+|\*|-)/ and do {
+    /^\@itemize\s*(\@[a-z]+|\*|-)?/ and do {
         push @endwstack, $endw;
         push @icstack, $ic;
-        $ic = $1;
+        $ic = $1 ? $1 : "*";
         $_ = "\n=over 4\n";
         $endw = "itemize";
     };
@@ -303,8 +301,8 @@ die "No filename or title\n" unless defined $fn && defined $tl;
 $sects{NAME} = "$fn \- $tl\n";
 $sects{FOOTNOTES} .= "=back\n" if exists $sects{FOOTNOTES};
 
-for $sect (qw(NAME SYNOPSIS DESCRIPTION OPTIONS EXAMPLES ENVIRONMENT FILES
-              BUGS NOTES FOOTNOTES SEEALSO AUTHOR COPYRIGHT)) {
+unshift @sects_sequence, "NAME";
+for $sect (@sects_sequence) {
     if(exists $sects{$sect}) {
         $head = $sect;
         $head =~ s/SEEALSO/SEE ALSO/;
@@ -350,6 +348,7 @@ sub postprocess
     # @* is also impossible in .pod; we discard it and any newline that
     # follows it.  Similarly, our macro @gol must be discarded.
 
+    s/\@anchor{(?:[^\}]*)\}//g;
     s/\(?\@xref\{(?:[^\}]*)\}(?:[^.<]|(?:<[^<>]*>))*\.\)?//g;
     s/\s+\(\@pxref\{(?:[^\}]*)\}\)//g;
     s/;\s+\@pxref\{(?:[^\}]*)\}//g;
diff --git a/ffmpeg.c b/ffmpeg.c
index 6b9380f..80d2cca 100644
--- a/ffmpeg.c
+++ b/ffmpeg.c
@@ -2,20 +2,20 @@
  * FFmpeg main
  * Copyright (c) 2000-2003 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -36,13 +36,23 @@
 #include "libswscale/swscale.h"
 #include "libavcodec/opt.h"
 #include "libavcodec/audioconvert.h"
-#include "libavcodec/colorspace.h"
+#include "libavutil/audioconvert.h"
+#include "libavutil/parseutils.h"
+#include "libavutil/samplefmt.h"
+#include "libavutil/colorspace.h"
 #include "libavutil/fifo.h"
+#include "libavutil/intreadwrite.h"
 #include "libavutil/pixdesc.h"
 #include "libavutil/avstring.h"
 #include "libavutil/libm.h"
 #include "libavformat/os_support.h"
 
+#if CONFIG_AVFILTER
+# include "libavfilter/avfilter.h"
+# include "libavfilter/avfiltergraph.h"
+# include "libavfilter/vsrc_buffer.h"
+#endif
+
 #if HAVE_SYS_RESOURCE_H
 #include <sys/types.h>
 #include <sys/time.h>
@@ -59,20 +69,14 @@
 #include <sys/select.h>
 #endif
 
-#if HAVE_TERMIOS_H
-#include <fcntl.h>
-#include <sys/ioctl.h>
-#include <sys/time.h>
-#include <termios.h>
-#elif HAVE_CONIO_H
+#if HAVE_KBHIT
 #include <conio.h>
 #endif
 #include <time.h>
 
 #include "cmdutils.h"
 
-#undef NDEBUG
-#include <assert.h>
+#include "libavutil/avassert.h"
 
 const char program_name[] = "FFmpeg";
 const int program_birth_year = 2000;
@@ -85,49 +89,65 @@ typedef struct AVStreamMap {
     int sync_stream_index;
 } AVStreamMap;
 
-/** select an input file for an output file */
+/**
+ * select an input file for an output file
+ */
 typedef struct AVMetaDataMap {
-    int out_file;
-    int in_file;
+    int  file;      //< file index
+    char type;      //< type of metadata to copy -- (g)lobal, (s)tream, (c)hapter or (p)rogram
+    int  index;     //< stream/chapter/program number
 } AVMetaDataMap;
 
+typedef struct AVChapterMap {
+    int in_file;
+    int out_file;
+} AVChapterMap;
+
 static const OptionDef options[];
 
 #define MAX_FILES 100
+#if !FF_API_MAX_STREAMS
+#define MAX_STREAMS 1024    /* arbitrary sanity check value */
+#endif
+
+#define FFM_PACKET_SIZE 4096 //XXX a duplicate of the line in ffm.h
 
 static const char *last_asked_format = NULL;
 static AVFormatContext *input_files[MAX_FILES];
 static int64_t input_files_ts_offset[MAX_FILES];
-static double input_files_ts_scale[MAX_FILES][MAX_STREAMS];
-static AVCodec *input_codecs[MAX_FILES*MAX_STREAMS];
+static double *input_files_ts_scale[MAX_FILES] = {NULL};
+static AVCodec **input_codecs = NULL;
 static int nb_input_files = 0;
-static int nb_icodecs;
+static int nb_input_codecs = 0;
+static int nb_input_files_ts_scale[MAX_FILES] = {0};
 
 static AVFormatContext *output_files[MAX_FILES];
-static AVCodec *output_codecs[MAX_FILES*MAX_STREAMS];
+static AVCodec **output_codecs = NULL;
 static int nb_output_files = 0;
-static int nb_ocodecs;
+static int nb_output_codecs = 0;
 
-static AVStreamMap stream_maps[MAX_FILES*MAX_STREAMS];
+static AVStreamMap *stream_maps = NULL;
 static int nb_stream_maps;
 
-static AVMetaDataMap meta_data_maps[MAX_FILES];
+/* first item specifies output metadata, second is input */
+static AVMetaDataMap (*meta_data_maps)[2] = NULL;
 static int nb_meta_data_maps;
+static int metadata_global_autocopy   = 1;
+static int metadata_streams_autocopy  = 1;
+static int metadata_chapters_autocopy = 1;
+
+static AVChapterMap *chapter_maps = NULL;
+static int nb_chapter_maps;
+
+/* indexed by output file stream index */
+static int *streamid_map = NULL;
+static int nb_streamid_map = 0;
 
 static int frame_width  = 0;
 static int frame_height = 0;
 static float frame_aspect_ratio = 0;
 static enum PixelFormat frame_pix_fmt = PIX_FMT_NONE;
-static enum SampleFormat audio_sample_fmt = SAMPLE_FMT_NONE;
-static int frame_padtop  = 0;
-static int frame_padbottom = 0;
-static int frame_padleft  = 0;
-static int frame_padright = 0;
-static int padcolor[3] = {16,128,128}; /* default to black */
-static int frame_topBand  = 0;
-static int frame_bottomBand = 0;
-static int frame_leftBand  = 0;
-static int frame_rightBand = 0;
+static enum AVSampleFormat audio_sample_fmt = AV_SAMPLE_FMT_NONE;
 static int max_frames[4] = {INT_MAX, INT_MAX, INT_MAX, INT_MAX};
 static AVRational frame_rate;
 static float video_qscale = 0;
@@ -137,7 +157,7 @@ static const char *video_rc_override_string=NULL;
 static int video_disable = 0;
 static int video_discard = 0;
 static char *video_codec_name = NULL;
-static int video_codec_tag = 0;
+static unsigned int video_codec_tag = 0;
 static char *video_language = NULL;
 static int same_quality = 0;
 static int do_deinterlace = 0;
@@ -147,6 +167,10 @@ static int intra_dc_precision = 8;
 static int loop_input = 0;
 static int loop_output = AVFMT_NOOUTPUTLOOP;
 static int qp_hist = 0;
+#if CONFIG_AVFILTER
+static char *vfilters = NULL;
+static AVFilterGraph *graph = NULL;
+#endif
 
 static int intra_only = 0;
 static int audio_sample_rate = 44100;
@@ -156,24 +180,23 @@ static float audio_qscale = QSCALE_NONE;
 static int audio_disable = 0;
 static int audio_channels = 1;
 static char  *audio_codec_name = NULL;
-static int audio_codec_tag = 0;
+static unsigned int audio_codec_tag = 0;
 static char *audio_language = NULL;
 
 static int subtitle_disable = 0;
 static char *subtitle_codec_name = NULL;
 static char *subtitle_language = NULL;
-static int subtitle_codec_tag = 0;
+static unsigned int subtitle_codec_tag = 0;
 
 static float mux_preload= 0.5;
 static float mux_max_delay= 0.7;
 
 static int64_t recording_time = INT64_MAX;
 static int64_t start_time = 0;
-static int64_t rec_timestamp = 0;
+static int64_t recording_timestamp = 0;
 static int64_t input_ts_offset = 0;
 static int file_overwrite = 0;
-static int metadata_count;
-static AVMetadataTag *metadata;
+static AVMetadata *metadata;
 static int do_benchmark = 0;
 static int do_hex_dump = 0;
 static int do_pkt_dump = 0;
@@ -187,6 +210,7 @@ static int video_sync_method= -1;
 static int audio_sync_method= 0;
 static float audio_drift_threshold= 0.1;
 static int copy_ts= 0;
+static int copy_tb;
 static int opt_shortest = 0;
 static int video_global_header = 0;
 static char *vstats_filename;
@@ -214,8 +238,8 @@ static int nb_frames_drop = 0;
 static int input_sync;
 static uint64_t limit_filesize = 0;
 static int force_fps = 0;
+static char *forced_key_frames = NULL;
 
-static int pgmyuv_compatibility_hack=0;
 static float dts_delta_threshold = 10;
 
 static unsigned int sws_flags = SWS_BICUBIC;
@@ -224,14 +248,13 @@ static int64_t timer_start;
 
 static uint8_t *audio_buf;
 static uint8_t *audio_out;
-unsigned int allocated_audio_out_size, allocated_audio_buf_size;
+static unsigned int allocated_audio_out_size, allocated_audio_buf_size;
 
 static short *samples;
 
 static AVBitStreamFilterContext *video_bitstream_filters=NULL;
 static AVBitStreamFilterContext *audio_bitstream_filters=NULL;
 static AVBitStreamFilterContext *subtitle_bitstream_filters=NULL;
-static AVBitStreamFilterContext *bitstream_filters[MAX_FILES][MAX_STREAMS];
 
 #define DEFAULT_PASS_LOGFILENAME_PREFIX "ffmpeg2pass"
 
@@ -249,6 +272,7 @@ typedef struct AVOutputStream {
     //double sync_ipts;        /* dts from the AVPacket of the demuxer in second units */
     struct AVInputStream *sync_ist; /* input stream to sync against */
     int64_t sync_opts;       /* output frame counter, could be changed to some true timestamp */ //FIXME look at frame_number
+    AVBitStreamFilterContext *bitstream_filters;
     /* video only */
     int video_resample;
     AVFrame pict_tmp;      /* temporary image for resampling */
@@ -261,35 +285,26 @@ typedef struct AVOutputStream {
     int original_height;
     int original_width;
 
-    /* cropping area sizes */
-    int video_crop;
-    int topBand;
-    int bottomBand;
-    int leftBand;
-    int rightBand;
-
-    /* cropping area of first frame */
-    int original_topBand;
-    int original_bottomBand;
-    int original_leftBand;
-    int original_rightBand;
-
-    /* padding area sizes */
-    int video_pad;
-    int padtop;
-    int padbottom;
-    int padleft;
-    int padright;
+    /* forced key frames */
+    int64_t *forced_kf_pts;
+    int forced_kf_count;
+    int forced_kf_index;
 
     /* audio only */
     int audio_resample;
     ReSampleContext *resample; /* for audio resampling */
+    int resample_sample_fmt;
+    int resample_channels;
+    int resample_sample_rate;
     int reformat_pair;
     AVAudioConvert *reformat_ctx;
     AVFifoBuffer *fifo;     /* for compression: one audio fifo per codec */
     FILE *logfile;
 } AVOutputStream;
 
+static AVOutputStream **output_streams_for_file[MAX_FILES] = { NULL };
+static int nb_output_streams_for_file[MAX_FILES] = { 0 };
+
 typedef struct AVInputStream {
     int file_index;
     int index;
@@ -302,9 +317,17 @@ typedef struct AVInputStream {
     int64_t       next_pts;  /* synthetic pts for cases where pkt.pts
                                 is not defined */
     int64_t       pts;       /* current pts */
+    PtsCorrectionContext pts_ctx;
     int is_start;            /* is 1 at the start and after a discontinuity */
     int showed_multi_packet_warning;
     int is_past_recording_time;
+#if CONFIG_AVFILTER
+    AVFilterContext *output_video_filter;
+    AVFilterContext *input_video_filter;
+    AVFrame *filter_frame;
+    int has_filter_frame;
+    AVFilterBufferRef *picref;
+#endif
 } AVInputStream;
 
 typedef struct AVInputFile {
@@ -314,17 +337,83 @@ typedef struct AVInputFile {
     int nb_streams;       /* nb streams we are aware of */
 } AVInputFile;
 
-#if HAVE_TERMIOS_H
+#if CONFIG_AVFILTER
 
-/* init terminal so that we can grab keys */
-static struct termios oldtty;
-#endif
+static int configure_filters(AVInputStream *ist, AVOutputStream *ost)
+{
+    AVFilterContext *last_filter, *filter;
+    /** filter graph containing all filters including input & output */
+    AVCodecContext *codec = ost->st->codec;
+    AVCodecContext *icodec = ist->st->codec;
+    FFSinkContext ffsink_ctx = { .pix_fmt = codec->pix_fmt };
+    char args[255];
+    int ret;
+
+    graph = avfilter_graph_alloc();
+
+    snprintf(args, 255, "%d:%d:%d:%d:%d", ist->st->codec->width,
+             ist->st->codec->height, ist->st->codec->pix_fmt, 1, AV_TIME_BASE);
+    ret = avfilter_graph_create_filter(&ist->input_video_filter, avfilter_get_by_name("buffer"),
+                                       "src", args, NULL, graph);
+    if (ret < 0)
+        return ret;
+    ret = avfilter_graph_create_filter(&ist->output_video_filter, &ffsink,
+                                       "out", NULL, &ffsink_ctx, graph);
+    if (ret < 0)
+        return ret;
+    last_filter = ist->input_video_filter;
+
+    if (codec->width  != icodec->width || codec->height != icodec->height) {
+        snprintf(args, 255, "%d:%d:flags=0x%X",
+                 codec->width,
+                 codec->height,
+                 (int)av_get_int(sws_opts, "sws_flags", NULL));
+        if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
+                                                NULL, args, NULL, graph)) < 0)
+            return ret;
+        if ((ret = avfilter_link(last_filter, 0, filter, 0)) < 0)
+            return ret;
+        last_filter = filter;
+    }
+
+    snprintf(args, sizeof(args), "flags=0x%X", (int)av_get_int(sws_opts, "sws_flags", NULL));
+    graph->scale_sws_opts = av_strdup(args);
+
+    if (vfilters) {
+        AVFilterInOut *outputs = av_malloc(sizeof(AVFilterInOut));
+        AVFilterInOut *inputs  = av_malloc(sizeof(AVFilterInOut));
+
+        outputs->name    = av_strdup("in");
+        outputs->filter_ctx = last_filter;
+        outputs->pad_idx = 0;
+        outputs->next    = NULL;
+
+        inputs->name    = av_strdup("out");
+        inputs->filter_ctx = ist->output_video_filter;
+        inputs->pad_idx = 0;
+        inputs->next    = NULL;
+
+        if ((ret = avfilter_graph_parse(graph, vfilters, inputs, outputs, NULL)) < 0)
+            return ret;
+        av_freep(&vfilters);
+    } else {
+        if ((ret = avfilter_link(last_filter, 0, ist->output_video_filter, 0)) < 0)
+            return ret;
+    }
+
+    if ((ret = avfilter_graph_config(graph, NULL)) < 0)
+        return ret;
+
+    codec->width  = ist->output_video_filter->inputs[0]->w;
+    codec->height = ist->output_video_filter->inputs[0]->h;
+
+    return 0;
+}
+#endif /* CONFIG_AVFILTER */
 
 static void term_exit(void)
 {
-#if HAVE_TERMIOS_H
-    tcsetattr (0, TCSANOW, &oldtty);
-#endif
+    av_log(NULL, AV_LOG_QUIET, "");
 }
 
 static volatile int received_sigterm = 0;
@@ -338,61 +427,17 @@ sigterm_handler(int sig)
 
 static void term_init(void)
 {
-#if HAVE_TERMIOS_H
-    struct termios tty;
-
-    tcgetattr (0, &tty);
-    oldtty = tty;
-    atexit(term_exit);
-
-    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
-                          |INLCR|IGNCR|ICRNL|IXON);
-    tty.c_oflag |= OPOST;
-    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
-    tty.c_cflag &= ~(CSIZE|PARENB);
-    tty.c_cflag |= CS8;
-    tty.c_cc[VMIN] = 1;
-    tty.c_cc[VTIME] = 0;
-
-    tcsetattr (0, TCSANOW, &tty);
-    signal(SIGQUIT, sigterm_handler); /* Quit (POSIX).  */
-#endif
-
     signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).  */
     signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
 #ifdef SIGXCPU
     signal(SIGXCPU, sigterm_handler);
 #endif
-
-#if CONFIG_BEOS_NETSERVER
-    fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
-#endif
 }
 
 /* read a key without blocking */
 static int read_key(void)
 {
-#if HAVE_TERMIOS_H
-    int n = 1;
-    unsigned char ch;
-#if !CONFIG_BEOS_NETSERVER
-    struct timeval tv;
-    fd_set rfds;
-
-    FD_ZERO(&rfds);
-    FD_SET(0, &rfds);
-    tv.tv_sec = 0;
-    tv.tv_usec = 0;
-    n = select(1, &rfds, NULL, NULL, &tv);
-#endif
-    if (n > 0) {
-        n = read(0, &ch, 1);
-        if (n == 1)
-            return ch;
-
-        return n;
-    }
-#elif HAVE_CONIO_H
+#if HAVE_KBHIT
     if(kbhit())
         return(getch());
 #endif
@@ -404,33 +449,22 @@ static int decode_interrupt_cb(void)
     return q_pressed || (q_pressed = read_key() == 'q');
 }
 
-static int av_exit(int ret)
+static int ffmpeg_exit(int ret)
 {
     int i;
 
     /* close files */
     for(i=0;i<nb_output_files;i++) {
-        /* maybe av_close_output_file ??? */
         AVFormatContext *s = output_files[i];
-        int j;
         if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
-            url_fclose(s->pb);
-        for(j=0;j<s->nb_streams;j++) {
-            av_metadata_free(&s->streams[j]->metadata);
-            av_free(s->streams[j]->codec);
-            av_free(s->streams[j]);
-        }
-        for(j=0;j<s->nb_programs;j++) {
-            av_metadata_free(&s->programs[j]->metadata);
-        }
-        for(j=0;j<s->nb_chapters;j++) {
-            av_metadata_free(&s->chapters[j]->metadata);
-        }
-        av_metadata_free(&s->metadata);
-        av_free(s);
+            avio_close(s->pb);
+        avformat_free_context(s);
+        av_free(output_streams_for_file[i]);
     }
-    for(i=0;i<nb_input_files;i++)
+    for(i=0;i<nb_input_files;i++) {
         av_close_input_file(input_files[i]);
+        av_free(input_files_ts_scale[i]);
+    }
 
     av_free(intra_matrix);
     av_free(inter_matrix);
@@ -439,7 +473,11 @@ static int av_exit(int ret)
         fclose(vstats_file);
     av_free(vstats_filename);
 
-    av_free(opt_names);
+    av_free(streamid_map);
+    av_free(input_codecs);
+    av_free(output_codecs);
+    av_free(stream_maps);
+    av_free(meta_data_maps);
 
     av_free(video_codec_name);
     av_free(audio_codec_name);
@@ -447,20 +485,16 @@ static int av_exit(int ret)
 
     av_free(video_standard);
 
-#if CONFIG_POWERPC_PERF
-    void powerpc_display_perf_report(void);
-    powerpc_display_perf_report();
-#endif /* CONFIG_POWERPC_PERF */
-
-    for (i=0;i<AVMEDIA_TYPE_NB;i++)
-        av_free(avcodec_opts[i]);
-    av_free(avformat_opts);
-    av_free(sws_opts);
+    uninit_opts();
     av_free(audio_buf);
     av_free(audio_out);
     allocated_audio_buf_size= allocated_audio_out_size= 0;
     av_free(samples);
 
+#if CONFIG_AVFILTER
+    avfilter_uninit();
+#endif
+
     if (received_sigterm) {
         fprintf(stderr,
             "Received signal %d: terminating.\n",
@@ -472,16 +506,42 @@ static int av_exit(int ret)
     return ret;
 }
 
+/* similar to ff_dynarray_add() and av_fast_realloc() */
+static void *grow_array(void *array, int elem_size, int *size, int new_size)
+{
+    if (new_size >= INT_MAX / elem_size) {
+        fprintf(stderr, "Array too big.\n");
+        ffmpeg_exit(1);
+    }
+    if (*size < new_size) {
+        uint8_t *tmp = av_realloc(array, new_size*elem_size);
+        if (!tmp) {
+            fprintf(stderr, "Could not alloc buffer.\n");
+            ffmpeg_exit(1);
+        }
+        memset(tmp + *size*elem_size, 0, (new_size-*size) * elem_size);
+        *size = new_size;
+        return tmp;
+    }
+    return array;
+}
+
 static void choose_sample_fmt(AVStream *st, AVCodec *codec)
 {
     if(codec && codec->sample_fmts){
-        const enum SampleFormat *p= codec->sample_fmts;
+        const enum AVSampleFormat *p= codec->sample_fmts;
         for(; *p!=-1; p++){
             if(*p == st->codec->sample_fmt)
                 break;
         }
-        if(*p == -1)
+        if (*p == -1) {
+            av_log(NULL, AV_LOG_WARNING,
+                   "Incompatible sample format '%s' for codec '%s', auto-selecting format '%s'\n",
+                   av_get_sample_fmt_name(st->codec->sample_fmt),
+                   codec->name,
+                   av_get_sample_fmt_name(codec->sample_fmts[0]));
             st->codec->sample_fmt = codec->sample_fmts[0];
+        }
     }
 }
 
@@ -489,7 +549,7 @@ static void choose_sample_rate(AVStream *st, AVCodec *codec)
 {
     if(codec && codec->supported_samplerates){
         const int *p= codec->supported_samplerates;
-        int best;
+        int best=0;
         int best_dist=INT_MAX;
         for(; *p; p++){
             int dist= abs(st->codec->sample_rate - *p);
@@ -509,19 +569,43 @@ static void choose_pixel_fmt(AVStream *st, AVCodec *codec)
 {
     if(codec && codec->pix_fmts){
         const enum PixelFormat *p= codec->pix_fmts;
+        if(st->codec->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL){
+            if(st->codec->codec_id==CODEC_ID_MJPEG){
+                p= (const enum PixelFormat[]){PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_NONE};
+            }else if(st->codec->codec_id==CODEC_ID_LJPEG){
+                p= (const enum PixelFormat[]){PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUVJ444P, PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_YUV444P, PIX_FMT_BGRA, PIX_FMT_NONE};
+            }
+        }
         for(; *p!=-1; p++){
             if(*p == st->codec->pix_fmt)
                 break;
         }
-        if(*p == -1
-           && !(   st->codec->codec_id==CODEC_ID_MJPEG
-                && st->codec->strict_std_compliance <= FF_COMPLIANCE_INOFFICIAL
-                && (   st->codec->pix_fmt == PIX_FMT_YUV420P
-                    || st->codec->pix_fmt == PIX_FMT_YUV422P)))
+        if(*p == -1)
             st->codec->pix_fmt = codec->pix_fmts[0];
     }
 }
 
+static AVOutputStream *new_output_stream(AVFormatContext *oc, int file_idx)
+{
+    int idx = oc->nb_streams - 1;
+    AVOutputStream *ost;
+
+    output_streams_for_file[file_idx] =
+        grow_array(output_streams_for_file[file_idx],
+                   sizeof(*output_streams_for_file[file_idx]),
+                   &nb_output_streams_for_file[file_idx],
+                   oc->nb_streams);
+    ost = output_streams_for_file[file_idx][idx] =
+        av_mallocz(sizeof(AVOutputStream));
+    if (!ost) {
+        fprintf(stderr, "Could not alloc output stream\n");
+        ffmpeg_exit(1);
+    }
+    ost->file_index = file_idx;
+    ost->index = idx;
+    return ost;
+}
+
 static int read_ffserver_streams(AVFormatContext *s, const char *filename)
 {
     int i, err;
@@ -532,18 +616,20 @@ static int read_ffserver_streams(AVFormatContext *s, const char *filename)
     if (err < 0)
         return err;
     /* copy stream format */
-    s->nb_streams = ic->nb_streams;
+    s->nb_streams = 0;
     for(i=0;i<ic->nb_streams;i++) {
         AVStream *st;
         AVCodec *codec;
 
+        s->nb_streams++;
+
         // FIXME: a more elegant solution is needed
         st = av_mallocz(sizeof(AVStream));
         memcpy(st, ic->streams[i], sizeof(AVStream));
         st->codec = avcodec_alloc_context();
         if (!st->codec) {
             print_error(filename, AVERROR(ENOMEM));
-            av_exit(1);
+            ffmpeg_exit(1);
         }
         avcodec_copy_context(st->codec, ic->streams[i]->codec);
         s->streams[i] = st;
@@ -561,13 +647,10 @@ static int read_ffserver_streams(AVFormatContext *s, const char *filename)
                 choose_pixel_fmt(st, codec);
         }
 
-        if(!st->codec->thread_count)
-            st->codec->thread_count = 1;
-        if(st->codec->thread_count>1)
-            avcodec_thread_init(st->codec, st->codec->thread_count);
-
         if(st->codec->flags & CODEC_FLAG_BITEXACT)
             nopts = 1;
+
+        new_output_stream(s, nb_output_files);
     }
 
     if (!nopts)
@@ -602,7 +685,7 @@ static void write_frame(AVFormatContext *s, AVPacket *pkt, AVCodecContext *avctx
                     avctx->codec ? avctx->codec->name : "copy");
             print_error("", a);
             if (exit_on_error)
-                av_exit(1);
+                ffmpeg_exit(1);
         }
         *pkt= new_pkt;
 
@@ -612,7 +695,7 @@ static void write_frame(AVFormatContext *s, AVPacket *pkt, AVCodecContext *avctx
     ret= av_interleaved_write_frame(s, pkt);
     if(ret < 0){
         print_error("av_interleaved_write_frame()", ret);
-        av_exit(1);
+        ffmpeg_exit(1);
     }
 }
 
@@ -627,17 +710,18 @@ static void do_audio_out(AVFormatContext *s,
     int64_t audio_out_size, audio_buf_size;
     int64_t allocated_for_size= size;
 
-    int size_out, frame_bytes, ret;
+    int size_out, frame_bytes, ret, resample_changed;
     AVCodecContext *enc= ost->st->codec;
     AVCodecContext *dec= ist->st->codec;
-    int osize= av_get_bits_per_sample_format(enc->sample_fmt)/8;
-    int isize= av_get_bits_per_sample_format(dec->sample_fmt)/8;
+    int osize= av_get_bits_per_sample_fmt(enc->sample_fmt)/8;
+    int isize= av_get_bits_per_sample_fmt(dec->sample_fmt)/8;
     const int coded_bps = av_get_bits_per_sample(enc->codec->id);
 
 need_realloc:
     audio_buf_size= (allocated_for_size + isize*dec->channels - 1) / (isize*dec->channels);
     audio_buf_size= (audio_buf_size*enc->sample_rate + dec->sample_rate) / dec->sample_rate;
     audio_buf_size= audio_buf_size*2 + 10000; //safety factors for the deprecated resampling API
+    audio_buf_size= FFMAX(audio_buf_size, enc->frame_size);
     audio_buf_size*= osize*enc->channels;
 
     audio_out_size= FFMAX(audio_buf_size, enc->frame_size * osize * enc->channels);
@@ -647,35 +731,59 @@ need_realloc:
 
     if(audio_out_size > INT_MAX || audio_buf_size > INT_MAX){
         fprintf(stderr, "Buffer sizes too large\n");
-        av_exit(1);
+        ffmpeg_exit(1);
     }
 
     av_fast_malloc(&audio_buf, &allocated_audio_buf_size, audio_buf_size);
     av_fast_malloc(&audio_out, &allocated_audio_out_size, audio_out_size);
     if (!audio_buf || !audio_out){
         fprintf(stderr, "Out of memory in do_audio_out\n");
-        av_exit(1);
+        ffmpeg_exit(1);
     }
 
     if (enc->channels != dec->channels)
         ost->audio_resample = 1;
 
-    if (ost->audio_resample && !ost->resample) {
-        if (dec->sample_fmt != SAMPLE_FMT_S16)
-            fprintf(stderr, "Warning, using s16 intermediate sample format for resampling\n");
-        ost->resample = av_audio_resample_init(enc->channels,    dec->channels,
-                                               enc->sample_rate, dec->sample_rate,
-                                               enc->sample_fmt,  dec->sample_fmt,
-                                               16, 10, 0, 0.8);
-        if (!ost->resample) {
-            fprintf(stderr, "Can not resample %d channels @ %d Hz to %d channels @ %d Hz\n",
-                    dec->channels, dec->sample_rate,
-                    enc->channels, enc->sample_rate);
-            av_exit(1);
+    resample_changed = ost->resample_sample_fmt  != dec->sample_fmt ||
+                       ost->resample_channels    != dec->channels   ||
+                       ost->resample_sample_rate != dec->sample_rate;
+
+    if ((ost->audio_resample && !ost->resample) || resample_changed) {
+        if (resample_changed) {
+            av_log(NULL, AV_LOG_INFO, "Input stream #%d.%d frame changed from rate:%d fmt:%s ch:%d to rate:%d fmt:%s ch:%d\n",
+                   ist->file_index, ist->index,
+                   ost->resample_sample_rate, av_get_sample_fmt_name(ost->resample_sample_fmt), ost->resample_channels,
+                   dec->sample_rate, av_get_sample_fmt_name(dec->sample_fmt), dec->channels);
+            ost->resample_sample_fmt  = dec->sample_fmt;
+            ost->resample_channels    = dec->channels;
+            ost->resample_sample_rate = dec->sample_rate;
+            if (ost->resample)
+                audio_resample_close(ost->resample);
+        }
+        /* if audio_sync_method is >1 the resampler is needed for audio drift compensation */
+        if (audio_sync_method <= 1 &&
+            ost->resample_sample_fmt  == enc->sample_fmt &&
+            ost->resample_channels    == enc->channels   &&
+            ost->resample_sample_rate == enc->sample_rate) {
+            ost->resample = NULL;
+            ost->audio_resample = 0;
+        } else {
+            if (dec->sample_fmt != AV_SAMPLE_FMT_S16)
+                fprintf(stderr, "Warning, using s16 intermediate sample format for resampling\n");
+            ost->resample = av_audio_resample_init(enc->channels,    dec->channels,
+                                                   enc->sample_rate, dec->sample_rate,
+                                                   enc->sample_fmt,  dec->sample_fmt,
+                                                   16, 10, 0, 0.8);
+            if (!ost->resample) {
+                fprintf(stderr, "Can not resample %d channels @ %d Hz to %d channels @ %d Hz\n",
+                        dec->channels, dec->sample_rate,
+                        enc->channels, enc->sample_rate);
+                ffmpeg_exit(1);
+            }
         }
     }
 
-#define MAKE_SFMT_PAIR(a,b) ((a)+SAMPLE_FMT_NB*(b))
+#define MAKE_SFMT_PAIR(a,b) ((a)+AV_SAMPLE_FMT_NB*(b))
     if (!ost->audio_resample && dec->sample_fmt!=enc->sample_fmt &&
         MAKE_SFMT_PAIR(enc->sample_fmt,dec->sample_fmt)!=ost->reformat_pair) {
         if (ost->reformat_ctx)
@@ -684,18 +792,18 @@ need_realloc:
                                                    dec->sample_fmt, 1, NULL, 0);
         if (!ost->reformat_ctx) {
             fprintf(stderr, "Cannot convert %s sample format to %s sample format\n",
-                avcodec_get_sample_fmt_name(dec->sample_fmt),
-                avcodec_get_sample_fmt_name(enc->sample_fmt));
-            av_exit(1);
+                av_get_sample_fmt_name(dec->sample_fmt),
+                av_get_sample_fmt_name(enc->sample_fmt));
+            ffmpeg_exit(1);
         }
         ost->reformat_pair=MAKE_SFMT_PAIR(enc->sample_fmt,dec->sample_fmt);
     }
 
     if(audio_sync_method){
         double delta = get_sync_ipts(ost) * enc->sample_rate - ost->sync_opts
-                - av_fifo_size(ost->fifo)/(ost->st->codec->channels * 2);
-        double idelta= delta*ist->st->codec->sample_rate / enc->sample_rate;
-        int byte_delta= ((int)idelta)*2*ist->st->codec->channels;
+                - av_fifo_size(ost->fifo)/(enc->channels * 2);
+        double idelta= delta*dec->sample_rate / enc->sample_rate;
+        int byte_delta= ((int)idelta)*2*dec->channels;
 
         //FIXME resample delay
         if(fabs(delta) > 50){
@@ -728,7 +836,7 @@ need_realloc:
                 }
             }else if(audio_sync_method>1){
                 int comp= av_clip(delta, -audio_sync_method, audio_sync_method);
-                assert(ost->audio_resample);
+                av_assert0(ost->audio_resample);
                 if(verbose > 2)
                     fprintf(stderr, "compensating audio timestamp drift:%f compensation:%d in:%d\n", delta, comp, enc->sample_rate);
 //                fprintf(stderr, "drift:%f len:%d opts:%"PRId64" ipts:%"PRId64" fifo:%d\n", delta, -1, ost->sync_opts, (int64_t)(get_sync_ipts(ost) * enc->sample_rate), av_fifo_size(ost->fifo)/(ost->st->codec->channels * 2));
@@ -737,13 +845,13 @@ need_realloc:
         }
     }else
         ost->sync_opts= lrintf(get_sync_ipts(ost) * enc->sample_rate)
-                        - av_fifo_size(ost->fifo)/(ost->st->codec->channels * 2); //FIXME wrong
+                        - av_fifo_size(ost->fifo)/(enc->channels * 2); //FIXME wrong
 
     if (ost->audio_resample) {
         buftmp = audio_buf;
         size_out = audio_resample(ost->resample,
                                   (short *)buftmp, (short *)buf,
-                                  size / (ist->st->codec->channels * isize));
+                                  size / (dec->channels * isize));
         size_out = size_out * enc->channels * osize;
     } else {
         buftmp = buf;
@@ -759,7 +867,7 @@ need_realloc:
         if (av_audio_convert(ost->reformat_ctx, obuf, ostride, ibuf, istride, len)<0) {
             printf("av_audio_convert() failed\n");
             if (exit_on_error)
-                av_exit(1);
+                ffmpeg_exit(1);
             return;
         }
         buftmp = audio_buf;
@@ -771,7 +879,7 @@ need_realloc:
         /* output resampled raw samples */
         if (av_fifo_realloc2(ost->fifo, av_fifo_size(ost->fifo) + size_out) < 0) {
             fprintf(stderr, "av_fifo_realloc2() failed\n");
-            av_exit(1);
+            ffmpeg_exit(1);
         }
         av_fifo_generic_write(ost->fifo, buftmp, size_out, NULL);
 
@@ -789,7 +897,7 @@ need_realloc:
                                        (short *)audio_buf);
             if (ret < 0) {
                 fprintf(stderr, "Audio encoding failed\n");
-                av_exit(1);
+                ffmpeg_exit(1);
             }
             audio_size += ret;
             pkt.stream_index= ost->index;
@@ -798,7 +906,7 @@ need_realloc:
             if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
                 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
             pkt.flags |= AV_PKT_FLAG_KEY;
-            write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
+            write_frame(s, &pkt, enc, ost->bitstream_filters);
 
             ost->sync_opts += enc->frame_size;
         }
@@ -816,7 +924,7 @@ need_realloc:
 
         if(size_out > audio_out_size){
             fprintf(stderr, "Internal error, buffer size too small\n");
-            av_exit(1);
+            ffmpeg_exit(1);
         }
 
         //FIXME pass ost->sync_opts as AVFrame.pts in avcodec_encode_audio()
@@ -824,7 +932,7 @@ need_realloc:
                                    (short *)buftmp);
         if (ret < 0) {
             fprintf(stderr, "Audio encoding failed\n");
-            av_exit(1);
+            ffmpeg_exit(1);
         }
         audio_size += ret;
         pkt.stream_index= ost->index;
@@ -833,7 +941,7 @@ need_realloc:
         if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
             pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
         pkt.flags |= AV_PKT_FLAG_KEY;
-        write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
+        write_frame(s, &pkt, enc, ost->bitstream_filters);
     }
 }
 
@@ -894,7 +1002,7 @@ static void do_subtitle_out(AVFormatContext *s,
     if (pts == AV_NOPTS_VALUE) {
         fprintf(stderr, "Subtitle packets must have a pts\n");
         if (exit_on_error)
-            av_exit(1);
+            ffmpeg_exit(1);
         return;
     }
 
@@ -922,7 +1030,7 @@ static void do_subtitle_out(AVFormatContext *s,
                                                     subtitle_out_max_size, sub);
         if (subtitle_out_size < 0) {
             fprintf(stderr, "Subtitle encoding failed\n");
-            av_exit(1);
+            ffmpeg_exit(1);
         }
 
         av_init_packet(&pkt);
@@ -938,7 +1046,7 @@ static void do_subtitle_out(AVFormatContext *s,
             else
                 pkt.pts += 90 * sub->end_display_time;
         }
-        write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
+        write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
     }
 }
 
@@ -952,15 +1060,10 @@ static void do_video_out(AVFormatContext *s,
                          int *frame_size)
 {
     int nb_frames, i, ret;
-    int64_t topBand, bottomBand, leftBand, rightBand;
     AVFrame *final_picture, *formatted_picture, *resampling_dst, *padding_src;
-    AVFrame picture_crop_temp, picture_pad_temp;
     AVCodecContext *enc, *dec;
     double sync_ipts;
 
-    avcodec_get_frame_defaults(&picture_crop_temp);
-    avcodec_get_frame_defaults(&picture_pad_temp);
-
     enc = ost->st->codec;
     dec = ist->st->codec;
 
@@ -980,7 +1083,7 @@ static void do_video_out(AVFormatContext *s,
             if(vdelta<=-0.6){
                 nb_frames=0;
             }else if(vdelta>0.6)
-            ost->sync_opts= lrintf(sync_ipts);
+                ost->sync_opts= lrintf(sync_ipts);
         }else if (vdelta > 1.1)
             nb_frames = lrintf(vdelta);
 //fprintf(stderr, "vdelta:%f, ost->sync_opts:%"PRId64", ost->sync_ipts:%f nb_frames:%d\n", vdelta, ost->sync_opts, get_sync_ipts(ost), nb_frames);
@@ -1000,96 +1103,48 @@ static void do_video_out(AVFormatContext *s,
     if (nb_frames <= 0)
         return;
 
-    if (ost->video_crop) {
-        if (av_picture_crop((AVPicture *)&picture_crop_temp, (AVPicture *)in_picture, dec->pix_fmt, ost->topBand, ost->leftBand) < 0) {
-            fprintf(stderr, "error cropping picture\n");
-            if (exit_on_error)
-                av_exit(1);
-            return;
-        }
-        formatted_picture = &picture_crop_temp;
-    } else {
-        formatted_picture = in_picture;
-    }
-
+    formatted_picture = in_picture;
     final_picture = formatted_picture;
     padding_src = formatted_picture;
     resampling_dst = &ost->pict_tmp;
-    if (ost->video_pad) {
-        final_picture = &ost->pict_tmp;
-        if (ost->video_resample) {
-            if (av_picture_crop((AVPicture *)&picture_pad_temp, (AVPicture *)final_picture, enc->pix_fmt, ost->padtop, ost->padleft) < 0) {
-                fprintf(stderr, "error padding picture\n");
-                if (exit_on_error)
-                    av_exit(1);
-                return;
-            }
-            resampling_dst = &picture_pad_temp;
-        }
-    }
 
-    if(    (ost->resample_height != (ist->st->codec->height - (ost->topBand  + ost->bottomBand)))
-        || (ost->resample_width  != (ist->st->codec->width  - (ost->leftBand + ost->rightBand)))
+    if (   ost->resample_height != ist->st->codec->height
+        || ost->resample_width  != ist->st->codec->width
         || (ost->resample_pix_fmt!= ist->st->codec->pix_fmt) ) {
 
         fprintf(stderr,"Input Stream #%d.%d frame size changed to %dx%d, %s\n", ist->file_index, ist->index, ist->st->codec->width,     ist->st->codec->height,avcodec_get_pix_fmt_name(ist->st->codec->pix_fmt));
         if(!ost->video_resample)
-            av_exit(1);
+            ffmpeg_exit(1);
     }
 
+#if !CONFIG_AVFILTER
     if (ost->video_resample) {
         padding_src = NULL;
         final_picture = &ost->pict_tmp;
-        if(  (ost->resample_height != (ist->st->codec->height - (ost->topBand  + ost->bottomBand)))
-          || (ost->resample_width  != (ist->st->codec->width  - (ost->leftBand + ost->rightBand)))
+        if(  ost->resample_height != ist->st->codec->height
+          || ost->resample_width  != ist->st->codec->width
           || (ost->resample_pix_fmt!= ist->st->codec->pix_fmt) ) {
 
-            /* keep bands proportional to the frame size */
-            topBand    = ((int64_t)ist->st->codec->height * ost->original_topBand    / ost->original_height) & ~1;
-            bottomBand = ((int64_t)ist->st->codec->height * ost->original_bottomBand / ost->original_height) & ~1;
-            leftBand   = ((int64_t)ist->st->codec->width  * ost->original_leftBand   / ost->original_width)  & ~1;
-            rightBand  = ((int64_t)ist->st->codec->width  * ost->original_rightBand  / ost->original_width)  & ~1;
-
-            /* sanity check to ensure no bad band sizes sneak in */
-            assert(topBand    <= INT_MAX && topBand    >= 0);
-            assert(bottomBand <= INT_MAX && bottomBand >= 0);
-            assert(leftBand   <= INT_MAX && leftBand   >= 0);
-            assert(rightBand  <= INT_MAX && rightBand  >= 0);
-
-            ost->topBand    = topBand;
-            ost->bottomBand = bottomBand;
-            ost->leftBand   = leftBand;
-            ost->rightBand  = rightBand;
-
-            ost->resample_height = ist->st->codec->height - (ost->topBand  + ost->bottomBand);
-            ost->resample_width  = ist->st->codec->width  - (ost->leftBand + ost->rightBand);
-            ost->resample_pix_fmt= ist->st->codec->pix_fmt;
-
             /* initialize a new scaler context */
             sws_freeContext(ost->img_resample_ctx);
             sws_flags = av_get_int(sws_opts, "sws_flags", NULL);
             ost->img_resample_ctx = sws_getContext(
-                ist->st->codec->width  - (ost->leftBand + ost->rightBand),
-                ist->st->codec->height - (ost->topBand  + ost->bottomBand),
+                ist->st->codec->width,
+                ist->st->codec->height,
                 ist->st->codec->pix_fmt,
-                ost->st->codec->width  - (ost->padleft  + ost->padright),
-                ost->st->codec->height - (ost->padtop   + ost->padbottom),
+                ost->st->codec->width,
+                ost->st->codec->height,
                 ost->st->codec->pix_fmt,
                 sws_flags, NULL, NULL, NULL);
             if (ost->img_resample_ctx == NULL) {
                 fprintf(stderr, "Cannot get resampling context\n");
-                av_exit(1);
+                ffmpeg_exit(1);
             }
         }
         sws_scale(ost->img_resample_ctx, formatted_picture->data, formatted_picture->linesize,
               0, ost->resample_height, resampling_dst->data, resampling_dst->linesize);
     }
-
-    if (ost->video_pad) {
-        av_picture_pad((AVPicture*)final_picture, (AVPicture *)padding_src,
-                enc->height, enc->width, enc->pix_fmt,
-                ost->padtop, ost->padbottom, ost->padleft, ost->padright, padcolor);
-    }
+#endif
 
     /* duplicates frame if needed */
     for(i=0;i<nb_frames;i++) {
@@ -1108,7 +1163,7 @@ static void do_video_out(AVFormatContext *s,
             pkt.pts= av_rescale_q(ost->sync_opts, enc->time_base, ost->st->time_base);
             pkt.flags |= AV_PKT_FLAG_KEY;
 
-            write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
+            write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
             enc->coded_frame = old_frame;
         } else {
             AVFrame big_picture;
@@ -1126,22 +1181,24 @@ static void do_video_out(AVFormatContext *s,
 
             /* handles sameq here. This is not correct because it may
                not be a global option */
-            if (same_quality) {
-                big_picture.quality = ist->st->quality;
-            }else
-                big_picture.quality = ost->st->quality;
+            big_picture.quality = same_quality ? ist->st->quality : ost->st->quality;
             if(!me_threshold)
                 big_picture.pict_type = 0;
 //            big_picture.pts = AV_NOPTS_VALUE;
             big_picture.pts= ost->sync_opts;
 //            big_picture.pts= av_rescale(ost->sync_opts, AV_TIME_BASE*(int64_t)enc->time_base.num, enc->time_base.den);
 //av_log(NULL, AV_LOG_DEBUG, "%"PRId64" -> encoder\n", ost->sync_opts);
+            if (ost->forced_kf_index < ost->forced_kf_count &&
+                big_picture.pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
+                big_picture.pict_type = FF_I_TYPE;
+                ost->forced_kf_index++;
+            }
             ret = avcodec_encode_video(enc,
                                        bit_buffer, bit_buffer_size,
                                        &big_picture);
             if (ret < 0) {
                 fprintf(stderr, "Video encoding failed\n");
-                av_exit(1);
+                ffmpeg_exit(1);
             }
 
             if(ret>0){
@@ -1155,7 +1212,7 @@ static void do_video_out(AVFormatContext *s,
 
                 if(enc->coded_frame->key_frame)
                     pkt.flags |= AV_PKT_FLAG_KEY;
-                write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
+                write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
                 *frame_size = ret;
                 video_size += ret;
                 //fprintf(stderr,"\nFrame: %3d size: %5d type: %d",
@@ -1187,7 +1244,7 @@ static void do_video_stats(AVFormatContext *os, AVOutputStream *ost,
         vstats_file = fopen(vstats_filename, "w");
         if (!vstats_file) {
             perror("fopen");
-            av_exit(1);
+            ffmpeg_exit(1);
         }
     }
 
@@ -1242,9 +1299,9 @@ static void print_report(AVFormatContext **output_files,
 
     oc = output_files[0];
 
-    total_size = url_fsize(oc->pb);
-    if(total_size<0) // FIXME improve url_fsize() so it works with non seekable output too
-        total_size= url_ftell(oc->pb);
+    total_size = avio_size(oc->pb);
+    if(total_size<0) // FIXME improve avio_size() so it works with non seekable output too
+        total_size= avio_tell(oc->pb);
 
     buf[0] = '\0';
     ti1 = 1e10;
@@ -1335,6 +1392,14 @@ static void print_report(AVFormatContext **output_files,
     }
 }
 
+static void generate_silence(uint8_t* buf, enum AVSampleFormat sample_fmt, size_t size)
+{
+    int fill_char = 0x00;
+    if (sample_fmt == AV_SAMPLE_FMT_U8)
+        fill_char = 0x80;
+    memset(buf, fill_char, size);
+}
+
 /* pkt = NULL means EOF (needed to flush decoder buffers) */
 static int output_packet(AVInputStream *ist, int ist_index,
                          AVOutputStream **ost_table, int nb_ostreams,
@@ -1348,9 +1413,13 @@ static int output_packet(AVInputStream *ist, int ist_index,
     void *buffer_to_free;
     static unsigned int samples_size= 0;
     AVSubtitle subtitle, *subtitle_to_free;
-    int got_subtitle;
+    int64_t pkt_pts = AV_NOPTS_VALUE;
+#if CONFIG_AVFILTER
+    int frame_available;
+#endif
+
     AVPacket avpkt;
-    int bps = av_get_bits_per_sample_format(ist->st->codec->sample_fmt)>>3;
+    int bps = av_get_bits_per_sample_fmt(ist->st->codec->sample_fmt)>>3;
 
     if(ist->next_pts == AV_NOPTS_VALUE)
         ist->next_pts= ist->pts;
@@ -1367,6 +1436,8 @@ static int output_packet(AVInputStream *ist, int ist_index,
 
     if(pkt->dts != AV_NOPTS_VALUE)
         ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
+    if(pkt->pts != AV_NOPTS_VALUE)
+        pkt_pts = av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
 
     //while we have more to decode or while the decoder did output something on EOF
     while (avpkt.size > 0 || (!pkt && ist->next_pts != ist->pts)) {
@@ -1419,6 +1490,9 @@ static int output_packet(AVInputStream *ist, int ist_index,
                     decoded_data_size = (ist->st->codec->width * ist->st->codec->height * 3) / 2;
                     /* XXX: allocate picture correctly */
                     avcodec_get_frame_defaults(&picture);
+                    avpkt.pts = pkt_pts;
+                    avpkt.dts = ist->pts;
+                    pkt_pts = AV_NOPTS_VALUE;
 
                     ret = avcodec_decode_video2(ist->st->codec,
                                                 &picture, &got_picture, &avpkt);
@@ -1429,6 +1503,7 @@ static int output_packet(AVInputStream *ist, int ist_index,
                         /* no picture yet */
                         goto discard_packet;
                     }
+                    ist->next_pts = ist->pts = guess_correct_pts(&ist->pts_ctx, picture.pkt_pts, picture.pkt_dts);
                     if (ist->st->codec->time_base.num != 0) {
                         int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;
                         ist->next_pts += ((int64_t)AV_TIME_BASE *
@@ -1439,10 +1514,10 @@ static int output_packet(AVInputStream *ist, int ist_index,
                     break;
             case AVMEDIA_TYPE_SUBTITLE:
                 ret = avcodec_decode_subtitle2(ist->st->codec,
-                                               &subtitle, &got_subtitle, &avpkt);
+                                               &subtitle, &got_picture, &avpkt);
                 if (ret < 0)
                     goto fail_decode;
-                if (!got_subtitle) {
+                if (!got_picture) {
                     goto discard_packet;
                 }
                 subtitle_to_free = &subtitle;
@@ -1476,6 +1551,18 @@ static int output_packet(AVInputStream *ist, int ist_index,
                                     &buffer_to_free);
         }
 
+#if CONFIG_AVFILTER
+        if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && ist->input_video_filter) {
+            AVRational sar;
+            if (ist->st->sample_aspect_ratio.num) sar = ist->st->sample_aspect_ratio;
+            else                                  sar = ist->st->codec->sample_aspect_ratio;
+            // add it to be filtered
+            av_vsrc_buffer_add_frame(ist->input_video_filter, &picture,
+                                     ist->pts,
+                                     sar);
+        }
+#endif
+
         // preprocess audio (volume)
         if (ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
             if (audio_volume != 256) {
@@ -1497,10 +1584,21 @@ static int output_packet(AVInputStream *ist, int ist_index,
             if (pts > now)
                 usleep(pts - now);
         }
-
+#if CONFIG_AVFILTER
+        frame_available = ist->st->codec->codec_type != AVMEDIA_TYPE_VIDEO ||
+            !ist->output_video_filter || avfilter_poll_frame(ist->output_video_filter->inputs[0]);
+#endif
         /* if output time reached then transcode raw format,
            encode packets and output them */
         if (start_time == 0 || ist->pts >= start_time)
+#if CONFIG_AVFILTER
+        while (frame_available) {
+            AVRational ist_pts_tb;
+            if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && ist->output_video_filter)
+                get_filtered_video_frame(ist->output_video_filter, &picture, &ist->picref, &ist_pts_tb);
+            if (ist->picref)
+                ist->pts = av_rescale_q(ist->picref->pts, ist_pts_tb, AV_TIME_BASE_Q);
+#endif
             for(i=0;i<nb_ostreams;i++) {
                 int frame_size;
 
@@ -1512,12 +1610,16 @@ static int output_packet(AVInputStream *ist, int ist_index,
                     //ost->sync_ipts = (double)(ist->pts + input_files_ts_offset[ist->file_index] - start_time)/ AV_TIME_BASE;
 
                     if (ost->encoding_needed) {
-                        assert(ist->decoding_needed);
+                        av_assert0(ist->decoding_needed);
                         switch(ost->st->codec->codec_type) {
                         case AVMEDIA_TYPE_AUDIO:
                             do_audio_out(os, ost, ist, decoded_data_buf, decoded_data_size);
                             break;
                         case AVMEDIA_TYPE_VIDEO:
+#if CONFIG_AVFILTER
+                            if (ist->picref->video)
+                                ost->st->codec->sample_aspect_ratio = ist->picref->video->pixel_aspect;
+#endif
                             do_video_out(os, ost, ist, &picture, &frame_size);
                             if (vstats_filename && frame_size)
                                 do_video_stats(os, ost, frame_size);
@@ -1580,25 +1682,25 @@ static int output_packet(AVInputStream *ist, int ist_index,
                             opkt.size = data_size;
                         }
 
-                        write_frame(os, &opkt, ost->st->codec, bitstream_filters[ost->file_index][opkt.stream_index]);
+                        write_frame(os, &opkt, ost->st->codec, ost->bitstream_filters);
                         ost->st->codec->frame_number++;
                         ost->frame_number++;
                         av_free_packet(&opkt);
                     }
                 }
             }
+
+#if CONFIG_AVFILTER
+            frame_available = (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) &&
+                              ist->output_video_filter && avfilter_poll_frame(ist->output_video_filter->inputs[0]);
+            if(ist->picref)
+                avfilter_unref_buffer(ist->picref);
+        }
+#endif
         av_free(buffer_to_free);
         /* XXX: allocate the subtitles in the codec ? */
         if (subtitle_to_free) {
-            if (subtitle_to_free->rects != NULL) {
-                for (i = 0; i < subtitle_to_free->num_rects; i++) {
-                    av_freep(&subtitle_to_free->rects[i]->pict.data[0]);
-                    av_freep(&subtitle_to_free->rects[i]->pict.data[1]);
-                    av_freep(&subtitle_to_free->rects[i]);
-                }
-                av_freep(&subtitle_to_free->rects);
-            }
-            subtitle_to_free->num_rects = 0;
+            avsubtitle_free(subtitle_to_free);
             subtitle_to_free = NULL;
         }
     }
@@ -1630,20 +1732,20 @@ static int output_packet(AVInputStream *ist, int ist_index,
                             ret = 0;
                             /* encode any samples remaining in fifo */
                             if (fifo_bytes > 0) {
-                                int osize = av_get_bits_per_sample_format(enc->sample_fmt) >> 3;
+                                int osize = av_get_bits_per_sample_fmt(enc->sample_fmt) >> 3;
                                 int fs_tmp = enc->frame_size;
 
-                                av_fifo_generic_read(ost->fifo, samples, fifo_bytes, NULL);
+                                av_fifo_generic_read(ost->fifo, audio_buf, fifo_bytes, NULL);
                                 if (enc->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
                                     enc->frame_size = fifo_bytes / (osize * enc->channels);
                                 } else { /* pad */
                                     int frame_bytes = enc->frame_size*osize*enc->channels;
-                                    if (samples_size < frame_bytes)
-                                        av_exit(1);
-                                    memset((uint8_t*)samples+fifo_bytes, 0, frame_bytes - fifo_bytes);
+                                    if (allocated_audio_buf_size < frame_bytes)
+                                        ffmpeg_exit(1);
+                                    generate_silence(audio_buf+fifo_bytes, enc->sample_fmt, frame_bytes - fifo_bytes);
                                 }
 
-                                ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, samples);
+                                ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, (short *)audio_buf);
                                 pkt.duration = av_rescale((int64_t)enc->frame_size*ost->st->time_base.den,
                                                           ost->st->time_base.num, enc->sample_rate);
                                 enc->frame_size = fs_tmp;
@@ -1653,7 +1755,7 @@ static int output_packet(AVInputStream *ist, int ist_index,
                             }
                             if (ret < 0) {
                                 fprintf(stderr, "Audio encoding failed\n");
-                                av_exit(1);
+                                ffmpeg_exit(1);
                             }
                             audio_size += ret;
                             pkt.flags |= AV_PKT_FLAG_KEY;
@@ -1662,7 +1764,7 @@ static int output_packet(AVInputStream *ist, int ist_index,
                             ret = avcodec_encode_video(enc, bit_buffer, bit_buffer_size, NULL);
                             if (ret < 0) {
                                 fprintf(stderr, "Video encoding failed\n");
-                                av_exit(1);
+                                ffmpeg_exit(1);
                             }
                             video_size += ret;
                             if(enc->coded_frame && enc->coded_frame->key_frame)
@@ -1681,7 +1783,7 @@ static int output_packet(AVInputStream *ist, int ist_index,
                         pkt.size= ret;
                         if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
                             pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
-                        write_frame(os, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
+                        write_frame(os, &pkt, ost->st->codec, ost->bitstream_filters);
                     }
                 }
             }
@@ -1697,7 +1799,7 @@ static void print_sdp(AVFormatContext **avc, int n)
 {
     char sdp[2048];
 
-    avf_sdp_create(avc, n, sdp, sizeof(sdp));
+    av_sdp_create(avc, n, sdp, sizeof(sdp));
     printf("SDP:\n%s\n", sdp);
     fflush(stdout);
 }
@@ -1710,7 +1812,6 @@ static int copy_chapters(int infile, int outfile)
 
     for (i = 0; i < is->nb_chapters; i++) {
         AVChapter *in_ch = is->chapters[i], *out_ch;
-        AVMetadataTag *t = NULL;
         int64_t ts_off   = av_rescale_q(start_time - input_files_ts_offset[infile],
                                       AV_TIME_BASE_Q, in_ch->time_base);
         int64_t rt       = (recording_time == INT64_MAX) ? INT64_MAX :
@@ -1731,8 +1832,8 @@ static int copy_chapters(int infile, int outfile)
         out_ch->start     = FFMAX(0,  in_ch->start - ts_off);
         out_ch->end       = FFMIN(rt, in_ch->end   - ts_off);
 
-        while ((t = av_metadata_get(in_ch->metadata, "", t, AV_METADATA_IGNORE_SUFFIX)))
-            av_metadata_set2(&out_ch->metadata, t->key, t->value, 0);
+        if (metadata_chapters_autocopy)
+            av_metadata_copy(&out_ch->metadata, in_ch->metadata, 0);
 
         os->nb_chapters++;
         os->chapters = av_realloc(os->chapters, sizeof(AVChapter)*os->nb_chapters);
@@ -1743,14 +1844,37 @@ static int copy_chapters(int infile, int outfile)
     return 0;
 }
 
+static void parse_forced_key_frames(char *kf, AVOutputStream *ost,
+                                    AVCodecContext *avctx)
+{
+    char *p;
+    int n = 1, i;
+    int64_t t;
+
+    for (p = kf; *p; p++)
+        if (*p == ',')
+            n++;
+    ost->forced_kf_count = n;
+    ost->forced_kf_pts = av_malloc(sizeof(*ost->forced_kf_pts) * n);
+    if (!ost->forced_kf_pts) {
+        av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
+        ffmpeg_exit(1);
+    }
+    for (i = 0; i < n; i++) {
+        p = i ? strchr(p, ',') + 1 : kf;
+        t = parse_time_or_die("force_key_frames", p, 1);
+        ost->forced_kf_pts[i] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
+    }
+}
+
 /*
  * The following code is the main loop of the file converter
  */
-static int av_transcode(AVFormatContext **output_files,
-                        int nb_output_files,
-                        AVFormatContext **input_files,
-                        int nb_input_files,
-                        AVStreamMap *stream_maps, int nb_stream_maps)
+static int transcode(AVFormatContext **output_files,
+                     int nb_output_files,
+                     AVFormatContext **input_files,
+                     int nb_input_files,
+                     AVStreamMap *stream_maps, int nb_stream_maps)
 {
     int ret = 0, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
     AVFormatContext *is, *os;
@@ -1809,16 +1933,18 @@ static int av_transcode(AVFormatContext **output_files,
     nb_ostreams = 0;
     for(i=0;i<nb_output_files;i++) {
         os = output_files[i];
-        if (!os->nb_streams) {
-            dump_format(output_files[i], i, output_files[i]->filename, 1);
+        if (!os->nb_streams && !(os->oformat->flags & AVFMT_NOSTREAMS)) {
+            av_dump_format(output_files[i], i, output_files[i]->filename, 1);
             fprintf(stderr, "Output file #%d does not contain any stream\n", i);
-            av_exit(1);
+            ret = AVERROR(EINVAL);
+            goto fail;
         }
         nb_ostreams += os->nb_streams;
     }
     if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
         fprintf(stderr, "Number of stream maps must match number of output streams\n");
-        av_exit(1);
+        ret = AVERROR(EINVAL);
+        goto fail;
     }
 
     /* Sanity check the mapping args -- do the input files & streams exist? */
@@ -1829,35 +1955,28 @@ static int av_transcode(AVFormatContext **output_files,
         if (fi < 0 || fi > nb_input_files - 1 ||
             si < 0 || si > file_table[fi].nb_streams - 1) {
             fprintf(stderr,"Could not find input stream #%d.%d\n", fi, si);
-            av_exit(1);
+            ret = AVERROR(EINVAL);
+            goto fail;
         }
         fi = stream_maps[i].sync_file_index;
         si = stream_maps[i].sync_stream_index;
         if (fi < 0 || fi > nb_input_files - 1 ||
             si < 0 || si > file_table[fi].nb_streams - 1) {
             fprintf(stderr,"Could not find sync stream #%d.%d\n", fi, si);
-            av_exit(1);
+            ret = AVERROR(EINVAL);
+            goto fail;
         }
     }
 
     ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
     if (!ost_table)
         goto fail;
-    for(i=0;i<nb_ostreams;i++) {
-        ost = av_mallocz(sizeof(AVOutputStream));
-        if (!ost)
-            goto fail;
-        ost_table[i] = ost;
-    }
-
     n = 0;
     for(k=0;k<nb_output_files;k++) {
         os = output_files[k];
         for(i=0;i<os->nb_streams;i++,n++) {
             int found;
-            ost = ost_table[n];
-            ost->file_index = k;
-            ost->index = i;
+            ost = ost_table[n] = output_streams_for_file[k][i];
             ost->st = os->streams[i];
             if (nb_stream_maps > 0) {
                 ost->source_index = file_table[stream_maps[n].file_index].ist_index +
@@ -1866,42 +1985,42 @@ static int av_transcode(AVFormatContext **output_files,
                 /* Sanity check that the stream types match */
                 if (ist_table[ost->source_index]->st->codec->codec_type != ost->st->codec->codec_type) {
                     int i= ost->file_index;
-                    dump_format(output_files[i], i, output_files[i]->filename, 1);
+                    av_dump_format(output_files[i], i, output_files[i]->filename, 1);
                     fprintf(stderr, "Codec type mismatch for mapping #%d.%d -> #%d.%d\n",
                         stream_maps[n].file_index, stream_maps[n].stream_index,
                         ost->file_index, ost->index);
-                    av_exit(1);
+                    ffmpeg_exit(1);
                 }
 
             } else {
                 int best_nb_frames=-1;
-                    /* get corresponding input stream index : we select the first one with the right type */
-                    found = 0;
-                    for(j=0;j<nb_istreams;j++) {
-                        int skip=0;
-                        ist = ist_table[j];
-                        if(opt_programid){
-                            int pi,si;
-                            AVFormatContext *f= input_files[ ist->file_index ];
-                            skip=1;
-                            for(pi=0; pi<f->nb_programs; pi++){
-                                AVProgram *p= f->programs[pi];
-                                if(p->id == opt_programid)
-                                    for(si=0; si<p->nb_stream_indexes; si++){
-                                        if(f->streams[ p->stream_index[si] ] == ist->st)
-                                            skip=0;
-                                    }
-                            }
+                /* get corresponding input stream index : we select the first one with the right type */
+                found = 0;
+                for(j=0;j<nb_istreams;j++) {
+                    int skip=0;
+                    ist = ist_table[j];
+                    if(opt_programid){
+                        int pi,si;
+                        AVFormatContext *f= input_files[ ist->file_index ];
+                        skip=1;
+                        for(pi=0; pi<f->nb_programs; pi++){
+                            AVProgram *p= f->programs[pi];
+                            if(p->id == opt_programid)
+                                for(si=0; si<p->nb_stream_indexes; si++){
+                                    if(f->streams[ p->stream_index[si] ] == ist->st)
+                                        skip=0;
+                                }
                         }
-                        if (ist->discard && ist->st->discard != AVDISCARD_ALL && !skip &&
-                            ist->st->codec->codec_type == ost->st->codec->codec_type) {
-                            if(best_nb_frames < ist->st->codec_info_nb_frames){
-                                best_nb_frames= ist->st->codec_info_nb_frames;
-                                ost->source_index = j;
-                                found = 1;
-                            }
+                    }
+                    if (ist->discard && ist->st->discard != AVDISCARD_ALL && !skip &&
+                        ist->st->codec->codec_type == ost->st->codec->codec_type) {
+                        if(best_nb_frames < ist->st->codec_info_nb_frames){
+                            best_nb_frames= ist->st->codec_info_nb_frames;
+                            ost->source_index = j;
+                            found = 1;
                         }
                     }
+                }
 
                 if (!found) {
                     if(! opt_programid) {
@@ -1917,10 +2036,10 @@ static int av_transcode(AVFormatContext **output_files,
                     }
                     if (!found) {
                         int i= ost->file_index;
-                        dump_format(output_files[i], i, output_files[i]->filename, 1);
+                        av_dump_format(output_files[i], i, output_files[i]->filename, 1);
                         fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
                                 ost->file_index, ost->index);
-                        av_exit(1);
+                        ffmpeg_exit(1);
                     }
                 }
             }
@@ -1934,7 +2053,6 @@ static int av_transcode(AVFormatContext **output_files,
 
     /* for each output stream, we compute the right encoding parameters */
     for(i=0;i<nb_ostreams;i++) {
-        AVMetadataTag *t = NULL;
         ost = ost_table[i];
         os = output_files[ost->file_index];
         ist = ist_table[ost->source_index];
@@ -1942,15 +2060,20 @@ static int av_transcode(AVFormatContext **output_files,
         codec = ost->st->codec;
         icodec = ist->st->codec;
 
-        while ((t = av_metadata_get(ist->st->metadata, "", t, AV_METADATA_IGNORE_SUFFIX))) {
-            av_metadata_set2(&ost->st->metadata, t->key, t->value, AV_METADATA_DONT_OVERWRITE);
-        }
+        if (metadata_streams_autocopy)
+            av_metadata_copy(&ost->st->metadata, ist->st->metadata,
+                             AV_METADATA_DONT_OVERWRITE);
 
         ost->st->disposition = ist->st->disposition;
         codec->bits_per_raw_sample= icodec->bits_per_raw_sample;
         codec->chroma_sample_location = icodec->chroma_sample_location;
 
         if (ost->st->stream_copy) {
+            uint64_t extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
+
+            if (extra_size > INT_MAX)
+                goto fail;
+
             /* if stream_copy is selected, no need to decode or encode */
             codec->codec_id = icodec->codec_id;
             codec->codec_type = icodec->codec_type;
@@ -1963,23 +2086,31 @@ static int av_transcode(AVFormatContext **output_files,
             }
 
             codec->bit_rate = icodec->bit_rate;
-            codec->extradata= icodec->extradata;
+            codec->rc_max_rate    = icodec->rc_max_rate;
+            codec->rc_buffer_size = icodec->rc_buffer_size;
+            codec->extradata= av_mallocz(extra_size);
+            if (!codec->extradata)
+                goto fail;
+            memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
             codec->extradata_size= icodec->extradata_size;
-            if(av_q2d(icodec->time_base)*icodec->ticks_per_frame > av_q2d(ist->st->time_base) && av_q2d(ist->st->time_base) < 1.0/1000){
+            if(!copy_tb && av_q2d(icodec->time_base)*icodec->ticks_per_frame > av_q2d(ist->st->time_base) && av_q2d(ist->st->time_base) < 1.0/500){
                 codec->time_base = icodec->time_base;
                 codec->time_base.num *= icodec->ticks_per_frame;
+                av_reduce(&codec->time_base.num, &codec->time_base.den,
+                          codec->time_base.num, codec->time_base.den, INT_MAX);
             }else
                 codec->time_base = ist->st->time_base;
             switch(codec->codec_type) {
             case AVMEDIA_TYPE_AUDIO:
                 if(audio_volume != 256) {
                     fprintf(stderr,"-acodec copy and -vol are incompatible (frames are not decoded)\n");
-                    av_exit(1);
+                    ffmpeg_exit(1);
                 }
                 codec->channel_layout = icodec->channel_layout;
                 codec->sample_rate = icodec->sample_rate;
                 codec->channels = icodec->channels;
                 codec->frame_size = icodec->frame_size;
+                codec->audio_service_type = icodec->audio_service_type;
                 codec->block_align= icodec->block_align;
                 if(codec->block_align == 1 && codec->codec_id == CODEC_ID_MP3)
                     codec->block_align= 0;
@@ -2005,75 +2136,62 @@ static int av_transcode(AVFormatContext **output_files,
                 ost->fifo= av_fifo_alloc(1024);
                 if(!ost->fifo)
                     goto fail;
-                ost->reformat_pair = MAKE_SFMT_PAIR(SAMPLE_FMT_NONE,SAMPLE_FMT_NONE);
+                ost->reformat_pair = MAKE_SFMT_PAIR(AV_SAMPLE_FMT_NONE,AV_SAMPLE_FMT_NONE);
                 ost->audio_resample = codec->sample_rate != icodec->sample_rate || audio_sync_method > 1;
                 icodec->request_channels = codec->channels;
                 ist->decoding_needed = 1;
                 ost->encoding_needed = 1;
+                ost->resample_sample_fmt  = icodec->sample_fmt;
+                ost->resample_sample_rate = icodec->sample_rate;
+                ost->resample_channels    = icodec->channels;
                 break;
             case AVMEDIA_TYPE_VIDEO:
                 if (ost->st->codec->pix_fmt == PIX_FMT_NONE) {
                     fprintf(stderr, "Video pixel format is unknown, stream cannot be encoded\n");
-                    av_exit(1);
+                    ffmpeg_exit(1);
                 }
-                ost->video_crop = ((frame_leftBand + frame_rightBand + frame_topBand + frame_bottomBand) != 0);
-                ost->video_pad = ((frame_padleft + frame_padright + frame_padtop + frame_padbottom) != 0);
-                ost->video_resample = ((codec->width != icodec->width -
-                                (frame_leftBand + frame_rightBand) +
-                                (frame_padleft + frame_padright)) ||
-                        (codec->height != icodec->height -
-                                (frame_topBand  + frame_bottomBand) +
-                                (frame_padtop + frame_padbottom)) ||
+                ost->video_resample = (codec->width != icodec->width   ||
+                                       codec->height != icodec->height ||
                         (codec->pix_fmt != icodec->pix_fmt));
-                if (ost->video_crop) {
-                    ost->topBand    = ost->original_topBand    = frame_topBand;
-                    ost->bottomBand = ost->original_bottomBand = frame_bottomBand;
-                    ost->leftBand   = ost->original_leftBand   = frame_leftBand;
-                    ost->rightBand  = ost->original_rightBand  = frame_rightBand;
-                }
-                if (ost->video_pad) {
-                    ost->padtop = frame_padtop;
-                    ost->padleft = frame_padleft;
-                    ost->padbottom = frame_padbottom;
-                    ost->padright = frame_padright;
-                    if (!ost->video_resample) {
-                        avcodec_get_frame_defaults(&ost->pict_tmp);
-                        if(avpicture_alloc((AVPicture*)&ost->pict_tmp, codec->pix_fmt,
-                                         codec->width, codec->height))
-                            goto fail;
-                    }
-                }
                 if (ost->video_resample) {
+#if !CONFIG_AVFILTER
                     avcodec_get_frame_defaults(&ost->pict_tmp);
                     if(avpicture_alloc((AVPicture*)&ost->pict_tmp, codec->pix_fmt,
                                          codec->width, codec->height)) {
                         fprintf(stderr, "Cannot allocate temp picture, check pix fmt\n");
-                        av_exit(1);
+                        ffmpeg_exit(1);
                     }
                     sws_flags = av_get_int(sws_opts, "sws_flags", NULL);
                     ost->img_resample_ctx = sws_getContext(
-                            icodec->width - (frame_leftBand + frame_rightBand),
-                            icodec->height - (frame_topBand + frame_bottomBand),
+                        icodec->width,
+                        icodec->height,
                             icodec->pix_fmt,
-                            codec->width - (frame_padleft + frame_padright),
-                            codec->height - (frame_padtop + frame_padbottom),
+                            codec->width,
+                            codec->height,
                             codec->pix_fmt,
                             sws_flags, NULL, NULL, NULL);
                     if (ost->img_resample_ctx == NULL) {
                         fprintf(stderr, "Cannot get resampling context\n");
-                        av_exit(1);
+                        ffmpeg_exit(1);
                     }
 
                     ost->original_height = icodec->height;
                     ost->original_width  = icodec->width;
-
+#endif
                     codec->bits_per_raw_sample= 0;
                 }
-                ost->resample_height = icodec->height - (frame_topBand  + frame_bottomBand);
-                ost->resample_width  = icodec->width  - (frame_leftBand + frame_rightBand);
+                ost->resample_height = icodec->height;
+                ost->resample_width  = icodec->width;
                 ost->resample_pix_fmt= icodec->pix_fmt;
                 ost->encoding_needed = 1;
                 ist->decoding_needed = 1;
+
+#if CONFIG_AVFILTER
+                if (configure_filters(ist, ost)) {
+                    fprintf(stderr, "Error opening filters!\n");
+                    exit(1);
+                }
+#endif
                 break;
             case AVMEDIA_TYPE_SUBTITLE:
                 ost->encoding_needed = 1;
@@ -2096,7 +2214,7 @@ static int av_transcode(AVFormatContext **output_files,
                     f = fopen(logfilename, "wb");
                     if (!f) {
                         fprintf(stderr, "Cannot write log file '%s' for pass-1 encoding: %s\n", logfilename, strerror(errno));
-                        av_exit(1);
+                        ffmpeg_exit(1);
                     }
                     ost->logfile = f;
                 } else {
@@ -2104,7 +2222,7 @@ static int av_transcode(AVFormatContext **output_files,
                     size_t logbuffer_size;
                     if (read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
                         fprintf(stderr, "Error reading log file '%s' for pass-2 encoding\n", logfilename);
-                        av_exit(1);
+                        ffmpeg_exit(1);
                     }
                     codec->stats_in = logbuffer;
                 }
@@ -2129,7 +2247,8 @@ static int av_transcode(AVFormatContext **output_files,
     for(i=0;i<nb_ostreams;i++) {
         ost = ost_table[i];
         if (ost->encoding_needed) {
-            AVCodec *codec = output_codecs[i];
+            AVCodec *codec = i < nb_output_codecs ? output_codecs[i] : NULL;
+            AVCodecContext *dec = ist_table[ost->source_index]->st->codec;
             if (!codec)
                 codec = avcodec_find_encoder(ost->st->codec->codec_id);
             if (!codec) {
@@ -2138,6 +2257,15 @@ static int av_transcode(AVFormatContext **output_files,
                 ret = AVERROR(EINVAL);
                 goto dump_format;
             }
+            if (dec->subtitle_header) {
+                ost->st->codec->subtitle_header = av_malloc(dec->subtitle_header_size);
+                if (!ost->st->codec->subtitle_header) {
+                    ret = AVERROR(ENOMEM);
+                    goto dump_format;
+                }
+                memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
+                ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
+            }
             if (avcodec_open(ost->st->codec, codec) < 0) {
                 snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height",
                         ost->file_index, ost->index);
@@ -2152,7 +2280,7 @@ static int av_transcode(AVFormatContext **output_files,
     for(i=0;i<nb_istreams;i++) {
         ist = ist_table[i];
         if (ist->decoding_needed) {
-            AVCodec *codec = input_codecs[i];
+            AVCodec *codec = i < nb_input_codecs ? input_codecs[i] : NULL;
             if (!codec)
                 codec = avcodec_find_decoder(ist->st->codec->codec_id);
             if (!codec) {
@@ -2179,50 +2307,98 @@ static int av_transcode(AVFormatContext **output_files,
         st= ist->st;
         ist->pts = st->avg_frame_rate.num ? - st->codec->has_b_frames*AV_TIME_BASE / av_q2d(st->avg_frame_rate) : 0;
         ist->next_pts = AV_NOPTS_VALUE;
+        init_pts_correction(&ist->pts_ctx);
         ist->is_start = 1;
     }
 
     /* set meta data information from input file if required */
     for (i=0;i<nb_meta_data_maps;i++) {
-        AVFormatContext *out_file;
-        AVFormatContext *in_file;
-        AVMetadataTag *mtag;
-
-        int out_file_index = meta_data_maps[i].out_file;
-        int in_file_index = meta_data_maps[i].in_file;
-        if (out_file_index < 0 || out_file_index >= nb_output_files) {
-            snprintf(error, sizeof(error), "Invalid output file index %d map_meta_data(%d,%d)",
-                     out_file_index, out_file_index, in_file_index);
+        AVFormatContext *files[2];
+        AVMetadata      **meta[2];
+        int j;
+
+#define METADATA_CHECK_INDEX(index, nb_elems, desc)\
+        if ((index) < 0 || (index) >= (nb_elems)) {\
+            snprintf(error, sizeof(error), "Invalid %s index %d while processing metadata maps\n",\
+                     (desc), (index));\
+            ret = AVERROR(EINVAL);\
+            goto dump_format;\
+        }
+
+        int out_file_index = meta_data_maps[i][0].file;
+        int in_file_index = meta_data_maps[i][1].file;
+        if (in_file_index < 0 || out_file_index < 0)
+            continue;
+        METADATA_CHECK_INDEX(out_file_index, nb_output_files, "output file")
+        METADATA_CHECK_INDEX(in_file_index, nb_input_files, "input file")
+
+        files[0] = output_files[out_file_index];
+        files[1] = input_files[in_file_index];
+
+        for (j = 0; j < 2; j++) {
+            AVMetaDataMap *map = &meta_data_maps[i][j];
+
+            switch (map->type) {
+            case 'g':
+                meta[j] = &files[j]->metadata;
+                break;
+            case 's':
+                METADATA_CHECK_INDEX(map->index, files[j]->nb_streams, "stream")
+                meta[j] = &files[j]->streams[map->index]->metadata;
+                break;
+            case 'c':
+                METADATA_CHECK_INDEX(map->index, files[j]->nb_chapters, "chapter")
+                meta[j] = &files[j]->chapters[map->index]->metadata;
+                break;
+            case 'p':
+                METADATA_CHECK_INDEX(map->index, files[j]->nb_programs, "program")
+                meta[j] = &files[j]->programs[map->index]->metadata;
+                break;
+            }
+        }
+
+        av_metadata_copy(meta[0], *meta[1], AV_METADATA_DONT_OVERWRITE);
+    }
+
+    /* copy global metadata by default */
+    if (metadata_global_autocopy) {
+
+        for (i = 0; i < nb_output_files; i++)
+            av_metadata_copy(&output_files[i]->metadata, input_files[0]->metadata,
+                             AV_METADATA_DONT_OVERWRITE);
+    }
+
+    /* copy chapters according to chapter maps */
+    for (i = 0; i < nb_chapter_maps; i++) {
+        int infile  = chapter_maps[i].in_file;
+        int outfile = chapter_maps[i].out_file;
+
+        if (infile < 0 || outfile < 0)
+            continue;
+        if (infile >= nb_input_files) {
+            snprintf(error, sizeof(error), "Invalid input file index %d in chapter mapping.\n", infile);
             ret = AVERROR(EINVAL);
             goto dump_format;
         }
-        if (in_file_index < 0 || in_file_index >= nb_input_files) {
-            snprintf(error, sizeof(error), "Invalid input file index %d map_meta_data(%d,%d)",
-                     in_file_index, out_file_index, in_file_index);
+        if (outfile >= nb_output_files) {
+            snprintf(error, sizeof(error), "Invalid output file index %d in chapter mapping.\n",outfile);
             ret = AVERROR(EINVAL);
             goto dump_format;
         }
-
-        out_file = output_files[out_file_index];
-        in_file = input_files[in_file_index];
-
-
-        mtag=NULL;
-        while((mtag=av_metadata_get(in_file->metadata, "", mtag, AV_METADATA_IGNORE_SUFFIX)))
-            av_metadata_set2(&out_file->metadata, mtag->key, mtag->value, AV_METADATA_DONT_OVERWRITE);
-        av_metadata_conv(out_file, out_file->oformat->metadata_conv,
-                                    in_file->iformat->metadata_conv);
+        copy_chapters(infile, outfile);
     }
 
     /* copy chapters from the first input file that has them*/
-    for (i = 0; i < nb_input_files; i++) {
-        if (!input_files[i]->nb_chapters)
-            continue;
+    if (!nb_chapter_maps)
+        for (i = 0; i < nb_input_files; i++) {
+            if (!input_files[i]->nb_chapters)
+                continue;
 
-        for (j = 0; j < nb_output_files; j++)
-            if ((ret = copy_chapters(i, j)) < 0)
-                goto dump_format;
-    }
+            for (j = 0; j < nb_output_files; j++)
+                if ((ret = copy_chapters(i, j)) < 0)
+                    goto dump_format;
+            break;
+        }
 
     /* open files and write file headers */
     for(i=0;i<nb_output_files;i++) {
@@ -2241,7 +2417,7 @@ static int av_transcode(AVFormatContext **output_files,
     /* dump the file output parameters - cannot be done before in case
        of stream copy */
     for(i=0;i<nb_output_files;i++) {
-        dump_format(output_files[i], i, output_files[i]->filename, 1);
+        av_dump_format(output_files[i], i, output_files[i]->filename, 1);
     }
 
     /* dump the stream mapping */
@@ -2272,8 +2448,12 @@ static int av_transcode(AVFormatContext **output_files,
     }
 
     if (!using_stdin && verbose >= 0) {
+#if HAVE_KBHIT
         fprintf(stderr, "Press [q] to stop encoding\n");
-        url_set_interrupt_cb(decode_interrupt_cb);
+#else
+        fprintf(stderr, "Press ctrl-c to stop encoding\n");
+#endif
+        avio_set_interrupt_cb(decode_interrupt_cb);
     }
     term_init();
 
@@ -2337,7 +2517,7 @@ static int av_transcode(AVFormatContext **output_files,
         }
 
         /* finish if limit size exhausted */
-        if (limit_filesize != 0 && limit_filesize < url_ftell(output_files[0]->pb))
+        if (limit_filesize != 0 && limit_filesize <= avio_tell(output_files[0]->pb))
             break;
 
         /* read a frame from it and output it in the fifo */
@@ -2360,7 +2540,8 @@ static int av_transcode(AVFormatContext **output_files,
         memset(no_packet, 0, sizeof(no_packet));
 
         if (do_pkt_dump) {
-            av_pkt_dump_log(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump);
+            av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
+                             is->streams[pkt.stream_index]);
         }
         /* the following test is needed in case new streams appear
            dynamically in stream : we ignore them */
@@ -2376,7 +2557,8 @@ static int av_transcode(AVFormatContext **output_files,
         if (pkt.pts != AV_NOPTS_VALUE)
             pkt.pts += av_rescale_q(input_files_ts_offset[ist->file_index], AV_TIME_BASE_Q, ist->st->time_base);
 
-        if(input_files_ts_scale[file_index][pkt.stream_index]){
+        if (pkt.stream_index < nb_input_files_ts_scale[file_index]
+            && input_files_ts_scale[file_index][pkt.stream_index]){
             if(pkt.pts != AV_NOPTS_VALUE)
                 pkt.pts *= input_files_ts_scale[file_index][pkt.stream_index];
             if(pkt.dts != AV_NOPTS_VALUE)
@@ -2412,7 +2594,7 @@ static int av_transcode(AVFormatContext **output_files,
                 fprintf(stderr, "Error while decoding stream #%d.%d\n",
                         ist->file_index, ist->index);
             if (exit_on_error)
-                av_exit(1);
+                ffmpeg_exit(1);
             av_free_packet(&pkt);
             goto redo;
         }
@@ -2459,6 +2641,9 @@ static int av_transcode(AVFormatContext **output_files,
             avcodec_close(ist->st->codec);
         }
     }
+#if CONFIG_AVFILTER
+    avfilter_graph_free(&graph);
+#endif
 
     /* finished ! */
     ret = 0;
@@ -2478,13 +2663,17 @@ static int av_transcode(AVFormatContext **output_files,
         for(i=0;i<nb_ostreams;i++) {
             ost = ost_table[i];
             if (ost) {
+                if (ost->st->stream_copy)
+                    av_freep(&ost->st->codec->extradata);
                 if (ost->logfile) {
                     fclose(ost->logfile);
                     ost->logfile = NULL;
                 }
                 av_fifo_free(ost->fifo); /* works even if fifo is not
                                              initialized but set to zero */
+                av_freep(&ost->st->codec->subtitle_header);
                 av_free(ost->pict_tmp.data[0]);
+                av_free(ost->forced_kf_pts);
                 if (ost->video_resample)
                     sws_freeContext(ost->img_resample_ctx);
                 if (ost->resample)
@@ -2501,14 +2690,6 @@ static int av_transcode(AVFormatContext **output_files,
 
 static void opt_format(const char *arg)
 {
-    /* compatibility stuff for pgmyuv */
-    if (!strcmp(arg, "pgmyuv")) {
-        pgmyuv_compatibility_hack=1;
-//        opt_image_format(arg);
-        arg = "image2";
-        fprintf(stderr, "pgmyuv format is deprecated, use image2\n");
-    }
-
     last_asked_format = arg;
 }
 
@@ -2531,9 +2712,9 @@ static int opt_verbose(const char *opt, const char *arg)
 
 static int opt_frame_rate(const char *opt, const char *arg)
 {
-    if (av_parse_video_frame_rate(&frame_rate, arg) < 0) {
+    if (av_parse_video_rate(&frame_rate, arg) < 0) {
         fprintf(stderr, "Incorrect value for %s: %s\n", opt, arg);
-        av_exit(1);
+        ffmpeg_exit(1);
     }
     return 0;
 }
@@ -2550,121 +2731,23 @@ static int opt_bitrate(const char *opt, const char *arg)
     return 0;
 }
 
-static void opt_frame_crop_top(const char *arg)
-{
-    frame_topBand = atoi(arg);
-    if (frame_topBand < 0) {
-        fprintf(stderr, "Incorrect top crop size\n");
-        av_exit(1);
-    }
-    if ((frame_topBand) >= frame_height){
-        fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
-        av_exit(1);
-    }
-    frame_height -= frame_topBand;
-}
-
-static void opt_frame_crop_bottom(const char *arg)
-{
-    frame_bottomBand = atoi(arg);
-    if (frame_bottomBand < 0) {
-        fprintf(stderr, "Incorrect bottom crop size\n");
-        av_exit(1);
-    }
-    if ((frame_bottomBand) >= frame_height){
-        fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
-        av_exit(1);
-    }
-    frame_height -= frame_bottomBand;
-}
-
-static void opt_frame_crop_left(const char *arg)
+static int opt_frame_crop(const char *opt, const char *arg)
 {
-    frame_leftBand = atoi(arg);
-    if (frame_leftBand < 0) {
-        fprintf(stderr, "Incorrect left crop size\n");
-        av_exit(1);
-    }
-    if ((frame_leftBand) >= frame_width){
-        fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
-        av_exit(1);
-    }
-    frame_width -= frame_leftBand;
-}
-
-static void opt_frame_crop_right(const char *arg)
-{
-    frame_rightBand = atoi(arg);
-    if (frame_rightBand < 0) {
-        fprintf(stderr, "Incorrect right crop size\n");
-        av_exit(1);
-    }
-    if ((frame_rightBand) >= frame_width){
-        fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
-        av_exit(1);
-    }
-    frame_width -= frame_rightBand;
+    fprintf(stderr, "Option '%s' has been removed, use the crop filter instead\n", opt);
+    return AVERROR(EINVAL);
 }
 
 static void opt_frame_size(const char *arg)
 {
-    if (av_parse_video_frame_size(&frame_width, &frame_height, arg) < 0) {
+    if (av_parse_video_size(&frame_width, &frame_height, arg) < 0) {
         fprintf(stderr, "Incorrect frame size\n");
-        av_exit(1);
-    }
-}
-
-static void opt_pad_color(const char *arg) {
-    /* Input is expected to be six hex digits similar to
-       how colors are expressed in html tags (but without the #) */
-    int rgb = strtol(arg, NULL, 16);
-    int r,g,b;
-
-    r = (rgb >> 16);
-    g = ((rgb >> 8) & 255);
-    b = (rgb & 255);
-
-    padcolor[0] = RGB_TO_Y(r,g,b);
-    padcolor[1] = RGB_TO_U(r,g,b,0);
-    padcolor[2] = RGB_TO_V(r,g,b,0);
-}
-
-static void opt_frame_pad_top(const char *arg)
-{
-    frame_padtop = atoi(arg);
-    if (frame_padtop < 0) {
-        fprintf(stderr, "Incorrect top pad size\n");
-        av_exit(1);
+        ffmpeg_exit(1);
     }
 }
 
-static void opt_frame_pad_bottom(const char *arg)
-{
-    frame_padbottom = atoi(arg);
-    if (frame_padbottom < 0) {
-        fprintf(stderr, "Incorrect bottom pad size\n");
-        av_exit(1);
-    }
-}
-
-
-static void opt_frame_pad_left(const char *arg)
-{
-    frame_padleft = atoi(arg);
-    if (frame_padleft < 0) {
-        fprintf(stderr, "Incorrect left pad size\n");
-        av_exit(1);
-    }
-}
-
-
-static void opt_frame_pad_right(const char *arg)
-{
-    frame_padright = atoi(arg);
-    if (frame_padright < 0) {
-        fprintf(stderr, "Incorrect right pad size\n");
-        av_exit(1);
-    }
+static int opt_pad(const char *opt, const char *arg) {
+    fprintf(stderr, "Option '%s' has been removed, use the pad filter instead\n", opt);
+    return -1;
 }
 
 static void opt_frame_pix_fmt(const char *arg)
@@ -2673,11 +2756,11 @@ static void opt_frame_pix_fmt(const char *arg)
         frame_pix_fmt = av_get_pix_fmt(arg);
         if (frame_pix_fmt == PIX_FMT_NONE) {
             fprintf(stderr, "Unknown pixel format requested: %s\n", arg);
-            av_exit(1);
+            ffmpeg_exit(1);
         }
     } else {
         show_pix_fmts();
-        av_exit(0);
+        ffmpeg_exit(0);
     }
 }
 
@@ -2700,7 +2783,7 @@ static void opt_frame_aspect_ratio(const char *arg)
 
     if (!ar) {
         fprintf(stderr, "Incorrect aspect ratio specification.\n");
-        av_exit(1);
+        ffmpeg_exit(1);
     }
     frame_aspect_ratio = ar;
 }
@@ -2711,14 +2794,11 @@ static int opt_metadata(const char *opt, const char *arg)
 
     if(!mid){
         fprintf(stderr, "Missing =\n");
-        av_exit(1);
+        ffmpeg_exit(1);
     }
     *mid++= 0;
 
-    metadata_count++;
-    metadata= av_realloc(metadata, sizeof(*metadata)*metadata_count);
-    metadata[metadata_count-1].key  = av_strdup(arg);
-    metadata[metadata_count-1].value= av_strdup(mid);
+    av_metadata_set2(&metadata, arg, mid, 0);
 
     return 0;
 }
@@ -2729,7 +2809,7 @@ static void opt_qscale(const char *arg)
     if (video_qscale <= 0 ||
         video_qscale > 255) {
         fprintf(stderr, "qscale must be > 0.0 and <= 255\n");
-        av_exit(1);
+        ffmpeg_exit(1);
     }
 }
 
@@ -2750,11 +2830,15 @@ static int opt_thread_count(const char *opt, const char *arg)
 
 static void opt_audio_sample_fmt(const char *arg)
 {
-    if (strcmp(arg, "list"))
-        audio_sample_fmt = avcodec_get_sample_fmt(arg);
-    else {
-        list_fmts(avcodec_sample_fmt_string, SAMPLE_FMT_NB);
-        av_exit(0);
+    if (strcmp(arg, "list")) {
+        audio_sample_fmt = av_get_sample_fmt(arg);
+        if (audio_sample_fmt == AV_SAMPLE_FMT_NONE) {
+            av_log(NULL, AV_LOG_ERROR, "Invalid sample format '%s'\n", arg);
+            ffmpeg_exit(1);
+        }
+    } else {
+        list_fmts(av_get_sample_fmt_string, AV_SAMPLE_FMT_NB);
+        ffmpeg_exit(0);
     }
 }
 
@@ -2796,24 +2880,6 @@ static void opt_audio_codec(const char *arg)
     opt_codec(&audio_stream_copy, &audio_codec_name, AVMEDIA_TYPE_AUDIO, arg);
 }
 
-static void opt_audio_tag(const char *arg)
-{
-    char *tail;
-    audio_codec_tag= strtol(arg, &tail, 0);
-
-    if(!tail || *tail)
-        audio_codec_tag= arg[0] + (arg[1]<<8) + (arg[2]<<16) + (arg[3]<<24);
-}
-
-static void opt_video_tag(const char *arg)
-{
-    char *tail;
-    video_codec_tag= strtol(arg, &tail, 0);
-
-    if(!tail || *tail)
-        video_codec_tag= arg[0] + (arg[1]<<8) + (arg[2]<<16) + (arg[3]<<24);
-}
-
 static void opt_video_codec(const char *arg)
 {
     opt_codec(&video_stream_copy, &video_codec_name, AVMEDIA_TYPE_VIDEO, arg);
@@ -2824,13 +2890,22 @@ static void opt_subtitle_codec(const char *arg)
     opt_codec(&subtitle_stream_copy, &subtitle_codec_name, AVMEDIA_TYPE_SUBTITLE, arg);
 }
 
-static void opt_subtitle_tag(const char *arg)
+static int opt_codec_tag(const char *opt, const char *arg)
 {
     char *tail;
-    subtitle_codec_tag= strtol(arg, &tail, 0);
+    uint32_t *codec_tag;
+
+    codec_tag = !strcmp(opt, "atag") ? &audio_codec_tag :
+                !strcmp(opt, "vtag") ? &video_codec_tag :
+                !strcmp(opt, "stag") ? &subtitle_codec_tag : NULL;
+    if (!codec_tag)
+        return -1;
+
+    *codec_tag = strtol(arg, &tail, 0);
+    if (!tail || *tail)
+        *codec_tag = AV_RL32(arg);
 
-    if(!tail || *tail)
-        subtitle_codec_tag= arg[0] + (arg[1]<<8) + (arg[2]<<16) + (arg[3]<<24);
+    return 0;
 }
 
 static void opt_map(const char *arg)
@@ -2838,7 +2913,8 @@ static void opt_map(const char *arg)
     AVStreamMap *m;
     char *p;
 
-    m = &stream_maps[nb_stream_maps++];
+    stream_maps = grow_array(stream_maps, sizeof(*stream_maps), &nb_stream_maps, nb_stream_maps + 1);
+    m = &stream_maps[nb_stream_maps-1];
 
     m->file_index = strtol(arg, &p, 0);
     if (*p)
@@ -2857,18 +2933,73 @@ static void opt_map(const char *arg)
     }
 }
 
-static void opt_map_meta_data(const char *arg)
+static void parse_meta_type(char *arg, char *type, int *index, char **endptr)
+{
+    *endptr = arg;
+    if (*arg == ',') {
+        *type = *(++arg);
+        switch (*arg) {
+        case 'g':
+            break;
+        case 's':
+        case 'c':
+        case 'p':
+            *index = strtol(++arg, endptr, 0);
+            break;
+        default:
+            fprintf(stderr, "Invalid metadata type %c.\n", *arg);
+            ffmpeg_exit(1);
+        }
+    } else
+        *type = 'g';
+}
+
+static void opt_map_metadata(const char *arg)
 {
-    AVMetaDataMap *m;
+    AVMetaDataMap *m, *m1;
     char *p;
 
-    m = &meta_data_maps[nb_meta_data_maps++];
+    meta_data_maps = grow_array(meta_data_maps, sizeof(*meta_data_maps),
+                                &nb_meta_data_maps, nb_meta_data_maps + 1);
+
+    m = &meta_data_maps[nb_meta_data_maps - 1][0];
+    m->file = strtol(arg, &p, 0);
+    parse_meta_type(p, &m->type, &m->index, &p);
+    if (*p)
+        p++;
+
+    m1 = &meta_data_maps[nb_meta_data_maps - 1][1];
+    m1->file = strtol(p, &p, 0);
+    parse_meta_type(p, &m1->type, &m1->index, &p);
+
+    if (m->type == 'g' || m1->type == 'g')
+        metadata_global_autocopy = 0;
+    if (m->type == 's' || m1->type == 's')
+        metadata_streams_autocopy = 0;
+    if (m->type == 'c' || m1->type == 'c')
+        metadata_chapters_autocopy = 0;
+}
+
+static void opt_map_meta_data(const char *arg)
+{
+    fprintf(stderr, "-map_meta_data is deprecated and will be removed soon. "
+                    "Use -map_metadata instead.\n");
+    opt_map_metadata(arg);
+}
 
-    m->out_file = strtol(arg, &p, 0);
+static void opt_map_chapters(const char *arg)
+{
+    AVChapterMap *c;
+    char *p;
+
+    chapter_maps = grow_array(chapter_maps, sizeof(*chapter_maps), &nb_chapter_maps,
+                              nb_chapter_maps + 1);
+    c = &chapter_maps[nb_chapter_maps - 1];
+    c->out_file = strtol(arg, &p, 0);
     if (*p)
         p++;
 
-    m->in_file = strtol(p, &p, 0);
+    c->in_file = strtol(p, &p, 0);
 }
 
 static void opt_input_ts_scale(const char *arg)
@@ -2883,8 +3014,9 @@ static void opt_input_ts_scale(const char *arg)
     scale= strtod(p, &p);
 
     if(stream >= MAX_STREAMS)
-        av_exit(1);
+        ffmpeg_exit(1);
 
+    input_files_ts_scale[nb_input_files] = grow_array(input_files_ts_scale[nb_input_files], sizeof(*input_files_ts_scale[nb_input_files]), &nb_input_files_ts_scale[nb_input_files], stream + 1);
     input_files_ts_scale[nb_input_files][stream]= scale;
 }
 
@@ -2900,9 +3032,9 @@ static int opt_start_time(const char *opt, const char *arg)
     return 0;
 }
 
-static int opt_rec_timestamp(const char *opt, const char *arg)
+static int opt_recording_timestamp(const char *opt, const char *arg)
 {
-    rec_timestamp = parse_time_or_die(opt, arg, 0) / 1000000;
+    recording_timestamp = parse_time_or_die(opt, arg, 0) / 1000000;
     return 0;
 }
 
@@ -2924,11 +3056,11 @@ static enum CodecID find_codec_or_die(const char *name, int type, int encoder, i
         avcodec_find_decoder_by_name(name);
     if(!codec) {
         fprintf(stderr, "Unknown %s '%s'\n", codec_string, name);
-        av_exit(1);
+        ffmpeg_exit(1);
     }
     if(codec->type != type) {
         fprintf(stderr, "Invalid %s type '%s'\n", codec_string, name);
-        av_exit(1);
+        ffmpeg_exit(1);
     }
     if(codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
        strict > FF_COMPLIANCE_EXPERIMENTAL) {
@@ -2941,7 +3073,7 @@ static enum CodecID find_codec_or_die(const char *name, int type, int encoder, i
         if (!(codec->capabilities & CODEC_CAP_EXPERIMENTAL))
             fprintf(stderr, "Or use the non experimental %s '%s'.\n",
                     codec_string, codec->name);
-        av_exit(1);
+        ffmpeg_exit(1);
     }
     return codec->id;
 }
@@ -2957,7 +3089,7 @@ static void opt_input_file(const char *filename)
     if (last_asked_format) {
         if (!(file_iformat = av_find_input_format(last_asked_format))) {
             fprintf(stderr, "Unknown input format: '%s'\n", last_asked_format);
-            av_exit(1);
+            ffmpeg_exit(1);
         }
         last_asked_format = NULL;
     }
@@ -2972,7 +3104,7 @@ static void opt_input_file(const char *filename)
     ic = avformat_alloc_context();
     if (!ic) {
         print_error(filename, AVERROR(ENOMEM));
-        av_exit(1);
+        ffmpeg_exit(1);
     }
 
     memset(ap, 0, sizeof(*ap));
@@ -2981,14 +3113,14 @@ static void opt_input_file(const char *filename)
     ap->channels = audio_channels;
     ap->time_base.den = frame_rate.num;
     ap->time_base.num = frame_rate.den;
-    ap->width = frame_width + frame_padleft + frame_padright;
-    ap->height = frame_height + frame_padtop + frame_padbottom;
+    ap->width = frame_width;
+    ap->height = frame_height;
     ap->pix_fmt = frame_pix_fmt;
    // ap->sample_fmt = audio_sample_fmt; //FIXME:not implemented in libavformat
     ap->channel = video_channel;
     ap->standard = video_standard;
 
-    set_context_opts(ic, avformat_opts, AV_OPT_FLAG_DECODING_PARAM);
+    set_context_opts(ic, avformat_opts, AV_OPT_FLAG_DECODING_PARAM, NULL);
 
     ic->video_codec_id   =
         find_codec_or_die(video_codec_name   , AVMEDIA_TYPE_VIDEO   , 0,
@@ -3001,14 +3133,11 @@ static void opt_input_file(const char *filename)
                           avcodec_opts[AVMEDIA_TYPE_SUBTITLE]->strict_std_compliance);
     ic->flags |= AVFMT_FLAG_NONBLOCK;
 
-    if(pgmyuv_compatibility_hack)
-        ic->video_codec_id= CODEC_ID_PGMYUV;
-
     /* open the input file with generic libav function */
     err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
     if (err < 0) {
         print_error(filename, err);
-        av_exit(1);
+        ffmpeg_exit(1);
     }
     if(opt_programid) {
         int i, j;
@@ -3029,7 +3158,7 @@ static void opt_input_file(const char *filename)
         }
         if(!found){
             fprintf(stderr, "Specified program id not found\n");
-            av_exit(1);
+            ffmpeg_exit(1);
         }
         opt_programid=0;
     }
@@ -3041,7 +3170,8 @@ static void opt_input_file(const char *filename)
     ret = av_find_stream_info(ic);
     if (ret < 0 && verbose >= 0) {
         fprintf(stderr, "%s: could not find codec parameters\n", filename);
-        av_exit(1);
+        av_close_input_file(ic);
+        ffmpeg_exit(1);
     }
 
     timestamp = start_time;
@@ -3063,45 +3193,54 @@ static void opt_input_file(const char *filename)
     /* update the current parameters so that they match the one of the input stream */
     for(i=0;i<ic->nb_streams;i++) {
         AVStream *st = ic->streams[i];
-        AVCodecContext *enc = st->codec;
-        avcodec_thread_init(enc, thread_count);
-        switch(enc->codec_type) {
+        AVCodecContext *dec = st->codec;
+        dec->thread_count = thread_count;
+        input_codecs = grow_array(input_codecs, sizeof(*input_codecs), &nb_input_codecs, nb_input_codecs + 1);
+        switch (dec->codec_type) {
         case AVMEDIA_TYPE_AUDIO:
-            set_context_opts(enc, avcodec_opts[AVMEDIA_TYPE_AUDIO], AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM);
-            //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
-            channel_layout = enc->channel_layout;
-            audio_channels = enc->channels;
-            audio_sample_rate = enc->sample_rate;
-            audio_sample_fmt = enc->sample_fmt;
-            input_codecs[nb_icodecs++] = avcodec_find_decoder_by_name(audio_codec_name);
+            input_codecs[nb_input_codecs-1] = avcodec_find_decoder_by_name(audio_codec_name);
+            set_context_opts(dec, avcodec_opts[AVMEDIA_TYPE_AUDIO], AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM, input_codecs[nb_input_codecs-1]);
+            //fprintf(stderr, "\nInput Audio channels: %d", dec->channels);
+            channel_layout    = dec->channel_layout;
+            audio_channels    = dec->channels;
+            audio_sample_rate = dec->sample_rate;
+            audio_sample_fmt  = dec->sample_fmt;
             if(audio_disable)
                 st->discard= AVDISCARD_ALL;
+            /* Note that av_find_stream_info can add more streams, and we
+             * currently have no chance of setting up lowres decoding
+             * early enough for them. */
+            if (dec->lowres)
+                audio_sample_rate >>= dec->lowres;
             break;
         case AVMEDIA_TYPE_VIDEO:
-            set_context_opts(enc, avcodec_opts[AVMEDIA_TYPE_VIDEO], AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM);
-            frame_height = enc->height;
-            frame_width = enc->width;
+            input_codecs[nb_input_codecs-1] = avcodec_find_decoder_by_name(video_codec_name);
+            set_context_opts(dec, avcodec_opts[AVMEDIA_TYPE_VIDEO], AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM, input_codecs[nb_input_codecs-1]);
+            frame_height = dec->height;
+            frame_width  = dec->width;
             if(ic->streams[i]->sample_aspect_ratio.num)
                 frame_aspect_ratio=av_q2d(ic->streams[i]->sample_aspect_ratio);
             else
-                frame_aspect_ratio=av_q2d(enc->sample_aspect_ratio);
-            frame_aspect_ratio *= (float) enc->width / enc->height;
-            frame_pix_fmt = enc->pix_fmt;
+                frame_aspect_ratio=av_q2d(dec->sample_aspect_ratio);
+            frame_aspect_ratio *= (float) dec->width / dec->height;
+            frame_pix_fmt = dec->pix_fmt;
             rfps      = ic->streams[i]->r_frame_rate.num;
             rfps_base = ic->streams[i]->r_frame_rate.den;
-            if(enc->lowres) {
-                enc->flags |= CODEC_FLAG_EMU_EDGE;
-                frame_height >>= enc->lowres;
-                frame_width  >>= enc->lowres;
+            if (dec->lowres) {
+                dec->flags |= CODEC_FLAG_EMU_EDGE;
+                frame_height >>= dec->lowres;
+                frame_width  >>= dec->lowres;
+                dec->height = frame_height;
+                dec->width  = frame_width;
             }
             if(me_threshold)
-                enc->debug |= FF_DEBUG_MV;
+                dec->debug |= FF_DEBUG_MV;
 
-            if (enc->time_base.den != rfps*enc->ticks_per_frame || enc->time_base.num != rfps_base) {
+            if (dec->time_base.den != rfps*dec->ticks_per_frame || dec->time_base.num != rfps_base) {
 
                 if (verbose >= 0)
                     fprintf(stderr,"\nSeems stream %d codec frame rate differs from container frame rate: %2.2f (%d/%d) -> %2.2f (%d/%d)\n",
-                            i, (float)enc->time_base.den / enc->time_base.num, enc->time_base.den, enc->time_base.num,
+                            i, (float)dec->time_base.den / dec->time_base.num, dec->time_base.den, dec->time_base.num,
 
                     (float)rfps / rfps_base, rfps, rfps_base);
             }
@@ -3109,7 +3248,6 @@ static void opt_input_file(const char *filename)
             frame_rate.num = rfps;
             frame_rate.den = rfps_base;
 
-            input_codecs[nb_icodecs++] = avcodec_find_decoder_by_name(video_codec_name);
             if(video_disable)
                 st->discard= AVDISCARD_ALL;
             else if(video_discard)
@@ -3118,13 +3256,12 @@ static void opt_input_file(const char *filename)
         case AVMEDIA_TYPE_DATA:
             break;
         case AVMEDIA_TYPE_SUBTITLE:
-            input_codecs[nb_icodecs++] = avcodec_find_decoder_by_name(subtitle_codec_name);
+            input_codecs[nb_input_codecs-1] = avcodec_find_decoder_by_name(subtitle_codec_name);
             if(subtitle_disable)
                 st->discard = AVDISCARD_ALL;
             break;
         case AVMEDIA_TYPE_ATTACHMENT:
         case AVMEDIA_TYPE_UNKNOWN:
-            nb_icodecs++;
             break;
         default:
             abort();
@@ -3135,7 +3272,7 @@ static void opt_input_file(const char *filename)
     input_files_ts_offset[nb_input_files] = input_ts_offset - (copy_ts ? 0 : timestamp);
     /* dump the file content */
     if (verbose >= 0)
-        dump_format(ic, nb_input_files, filename, 0);
+        av_dump_format(ic, nb_input_files, filename, 0);
 
     nb_input_files++;
 
@@ -3183,22 +3320,39 @@ static void check_audio_video_sub_inputs(int *has_video_ptr, int *has_audio_ptr,
     *has_subtitle_ptr = has_subtitle;
 }
 
-static void new_video_stream(AVFormatContext *oc)
+static void new_video_stream(AVFormatContext *oc, int file_idx)
 {
     AVStream *st;
+    AVOutputStream *ost;
     AVCodecContext *video_enc;
-    enum CodecID codec_id;
+    enum CodecID codec_id = CODEC_ID_NONE;
+    AVCodec *codec= NULL;
 
-    st = av_new_stream(oc, oc->nb_streams);
+    st = av_new_stream(oc, oc->nb_streams < nb_streamid_map ? streamid_map[oc->nb_streams] : 0);
     if (!st) {
         fprintf(stderr, "Could not alloc stream\n");
-        av_exit(1);
+        ffmpeg_exit(1);
+    }
+    ost = new_output_stream(oc, file_idx);
+
+    output_codecs = grow_array(output_codecs, sizeof(*output_codecs), &nb_output_codecs, nb_output_codecs + 1);
+    if(!video_stream_copy){
+        if (video_codec_name) {
+            codec_id = find_codec_or_die(video_codec_name, AVMEDIA_TYPE_VIDEO, 1,
+                                         avcodec_opts[AVMEDIA_TYPE_VIDEO]->strict_std_compliance);
+            codec = avcodec_find_encoder_by_name(video_codec_name);
+            output_codecs[nb_output_codecs-1] = codec;
+        } else {
+            codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, AVMEDIA_TYPE_VIDEO);
+            codec = avcodec_find_encoder(codec_id);
+        }
     }
-    avcodec_get_context_defaults2(st->codec, AVMEDIA_TYPE_VIDEO);
-    bitstream_filters[nb_output_files][oc->nb_streams - 1]= video_bitstream_filters;
+
+    avcodec_get_context_defaults3(st->codec, codec);
+    ost->bitstream_filters = video_bitstream_filters;
     video_bitstream_filters= NULL;
 
-    avcodec_thread_init(st->codec, thread_count);
+    st->codec->thread_count= thread_count;
 
     video_enc = st->codec;
 
@@ -3223,30 +3377,18 @@ static void new_video_stream(AVFormatContext *oc)
     } else {
         const char *p;
         int i;
-        AVCodec *codec;
         AVRational fps= frame_rate.num ? frame_rate : (AVRational){25,1};
 
-        if (video_codec_name) {
-            codec_id = find_codec_or_die(video_codec_name, AVMEDIA_TYPE_VIDEO, 1,
-                                         video_enc->strict_std_compliance);
-            codec = avcodec_find_encoder_by_name(video_codec_name);
-            output_codecs[nb_ocodecs] = codec;
-        } else {
-            codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, AVMEDIA_TYPE_VIDEO);
-            codec = avcodec_find_encoder(codec_id);
-        }
-
         video_enc->codec_id = codec_id;
-
-        set_context_opts(video_enc, avcodec_opts[AVMEDIA_TYPE_VIDEO], AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM);
+        set_context_opts(video_enc, avcodec_opts[AVMEDIA_TYPE_VIDEO], AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, codec);
 
         if (codec && codec->supported_framerates && !force_fps)
             fps = codec->supported_framerates[av_find_nearest_q_idx(fps, codec->supported_framerates)];
         video_enc->time_base.den = fps.num;
         video_enc->time_base.num = fps.den;
 
-        video_enc->width = frame_width + frame_padright + frame_padleft;
-        video_enc->height = frame_height + frame_padtop + frame_padbottom;
+        video_enc->width = frame_width;
+        video_enc->height = frame_height;
         video_enc->sample_aspect_ratio = av_d2q(frame_aspect_ratio*video_enc->height/video_enc->width, 255);
         video_enc->pix_fmt = frame_pix_fmt;
         st->sample_aspect_ratio = video_enc->sample_aspect_ratio;
@@ -3272,7 +3414,7 @@ static void new_video_stream(AVFormatContext *oc)
             int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
             if(e!=3){
                 fprintf(stderr, "error parsing rc_override\n");
-                av_exit(1);
+                ffmpeg_exit(1);
             }
             video_enc->rc_override=
                 av_realloc(video_enc->rc_override,
@@ -3307,8 +3449,10 @@ static void new_video_stream(AVFormatContext *oc)
                 video_enc->flags |= CODEC_FLAG_PASS2;
             }
         }
+
+        if (forced_key_frames)
+            parse_forced_key_frames(forced_key_frames, ost, video_enc);
     }
-    nb_ocodecs++;
     if (video_language) {
         av_metadata_set2(&st->metadata, "language", video_language, 0);
         av_freep(&video_language);
@@ -3317,27 +3461,45 @@ static void new_video_stream(AVFormatContext *oc)
     /* reset some key parameters */
     video_disable = 0;
     av_freep(&video_codec_name);
+    av_freep(&forced_key_frames);
     video_stream_copy = 0;
     frame_pix_fmt = PIX_FMT_NONE;
 }
 
-static void new_audio_stream(AVFormatContext *oc)
+static void new_audio_stream(AVFormatContext *oc, int file_idx)
 {
     AVStream *st;
+    AVOutputStream *ost;
+    AVCodec *codec= NULL;
     AVCodecContext *audio_enc;
-    enum CodecID codec_id;
+    enum CodecID codec_id = CODEC_ID_NONE;
 
-    st = av_new_stream(oc, oc->nb_streams);
+    st = av_new_stream(oc, oc->nb_streams < nb_streamid_map ? streamid_map[oc->nb_streams] : 0);
     if (!st) {
         fprintf(stderr, "Could not alloc stream\n");
-        av_exit(1);
+        ffmpeg_exit(1);
+    }
+    ost = new_output_stream(oc, file_idx);
+
+    output_codecs = grow_array(output_codecs, sizeof(*output_codecs), &nb_output_codecs, nb_output_codecs + 1);
+    if(!audio_stream_copy){
+        if (audio_codec_name) {
+            codec_id = find_codec_or_die(audio_codec_name, AVMEDIA_TYPE_AUDIO, 1,
+                                         avcodec_opts[AVMEDIA_TYPE_AUDIO]->strict_std_compliance);
+            codec = avcodec_find_encoder_by_name(audio_codec_name);
+            output_codecs[nb_output_codecs-1] = codec;
+        } else {
+            codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, AVMEDIA_TYPE_AUDIO);
+            codec = avcodec_find_encoder(codec_id);
+        }
     }
-    avcodec_get_context_defaults2(st->codec, AVMEDIA_TYPE_AUDIO);
 
-    bitstream_filters[nb_output_files][oc->nb_streams - 1]= audio_bitstream_filters;
+    avcodec_get_context_defaults3(st->codec, codec);
+
+    ost->bitstream_filters = audio_bitstream_filters;
     audio_bitstream_filters= NULL;
 
-    avcodec_thread_init(st->codec, thread_count);
+    st->codec->thread_count= thread_count;
 
     audio_enc = st->codec;
     audio_enc->codec_type = AVMEDIA_TYPE_AUDIO;
@@ -3354,20 +3516,8 @@ static void new_audio_stream(AVFormatContext *oc)
         audio_enc->channels = audio_channels;
         audio_enc->sample_rate = audio_sample_rate;
     } else {
-        AVCodec *codec;
-
-        set_context_opts(audio_enc, avcodec_opts[AVMEDIA_TYPE_AUDIO], AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM);
-
-        if (audio_codec_name) {
-            codec_id = find_codec_or_die(audio_codec_name, AVMEDIA_TYPE_AUDIO, 1,
-                                         audio_enc->strict_std_compliance);
-            codec = avcodec_find_encoder_by_name(audio_codec_name);
-            output_codecs[nb_ocodecs] = codec;
-        } else {
-            codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, AVMEDIA_TYPE_AUDIO);
-            codec = avcodec_find_encoder(codec_id);
-        }
         audio_enc->codec_id = codec_id;
+        set_context_opts(audio_enc, avcodec_opts[AVMEDIA_TYPE_AUDIO], AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, codec);
 
         if (audio_qscale > QSCALE_NONE) {
             audio_enc->flags |= CODEC_FLAG_QSCALE;
@@ -3377,12 +3527,11 @@ static void new_audio_stream(AVFormatContext *oc)
         audio_enc->sample_fmt = audio_sample_fmt;
         audio_enc->sample_rate = audio_sample_rate;
         audio_enc->channel_layout = channel_layout;
-        if (avcodec_channel_layout_num_channels(channel_layout) != audio_channels)
+        if (av_get_channel_layout_nb_channels(channel_layout) != audio_channels)
             audio_enc->channel_layout = 0;
         choose_sample_fmt(st, codec);
         choose_sample_rate(st, codec);
     }
-    nb_ocodecs++;
     audio_enc->time_base= (AVRational){1, audio_sample_rate};
     if (audio_language) {
         av_metadata_set2(&st->metadata, "language", audio_language, 0);
@@ -3395,36 +3544,52 @@ static void new_audio_stream(AVFormatContext *oc)
     audio_stream_copy = 0;
 }
 
-static void new_subtitle_stream(AVFormatContext *oc)
+static void new_subtitle_stream(AVFormatContext *oc, int file_idx)
 {
     AVStream *st;
+    AVOutputStream *ost;
+    AVCodec *codec=NULL;
     AVCodecContext *subtitle_enc;
+    enum CodecID codec_id = CODEC_ID_NONE;
 
-    st = av_new_stream(oc, oc->nb_streams);
+    st = av_new_stream(oc, oc->nb_streams < nb_streamid_map ? streamid_map[oc->nb_streams] : 0);
     if (!st) {
         fprintf(stderr, "Could not alloc stream\n");
-        av_exit(1);
+        ffmpeg_exit(1);
+    }
+    ost = new_output_stream(oc, file_idx);
+    subtitle_enc = st->codec;
+    output_codecs = grow_array(output_codecs, sizeof(*output_codecs), &nb_output_codecs, nb_output_codecs + 1);
+    if(!subtitle_stream_copy){
+        if (subtitle_codec_name) {
+            codec_id = find_codec_or_die(subtitle_codec_name, AVMEDIA_TYPE_SUBTITLE, 1,
+                                         avcodec_opts[AVMEDIA_TYPE_SUBTITLE]->strict_std_compliance);
+            codec= output_codecs[nb_output_codecs-1] = avcodec_find_encoder_by_name(subtitle_codec_name);
+        } else {
+            codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, AVMEDIA_TYPE_SUBTITLE);
+            codec = avcodec_find_encoder(codec_id);
+        }
     }
-    avcodec_get_context_defaults2(st->codec, AVMEDIA_TYPE_SUBTITLE);
+    avcodec_get_context_defaults3(st->codec, codec);
 
-    bitstream_filters[nb_output_files][oc->nb_streams - 1]= subtitle_bitstream_filters;
+    ost->bitstream_filters = subtitle_bitstream_filters;
     subtitle_bitstream_filters= NULL;
 
-    subtitle_enc = st->codec;
     subtitle_enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
 
     if(subtitle_codec_tag)
         subtitle_enc->codec_tag= subtitle_codec_tag;
 
+    if (oc->oformat->flags & AVFMT_GLOBALHEADER) {
+        subtitle_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
+        avcodec_opts[AVMEDIA_TYPE_SUBTITLE]->flags |= CODEC_FLAG_GLOBAL_HEADER;
+    }
     if (subtitle_stream_copy) {
         st->stream_copy = 1;
     } else {
-        set_context_opts(avcodec_opts[AVMEDIA_TYPE_SUBTITLE], subtitle_enc, AV_OPT_FLAG_SUBTITLE_PARAM | AV_OPT_FLAG_ENCODING_PARAM);
-        subtitle_enc->codec_id = find_codec_or_die(subtitle_codec_name, AVMEDIA_TYPE_SUBTITLE, 1,
-                                                   subtitle_enc->strict_std_compliance);
-        output_codecs[nb_ocodecs] = avcodec_find_encoder_by_name(subtitle_codec_name);
+        subtitle_enc->codec_id = codec_id;
+        set_context_opts(avcodec_opts[AVMEDIA_TYPE_SUBTITLE], subtitle_enc, AV_OPT_FLAG_SUBTITLE_PARAM | AV_OPT_FLAG_ENCODING_PARAM, codec);
     }
-    nb_ocodecs++;
 
     if (subtitle_language) {
         av_metadata_set2(&st->metadata, "language", subtitle_language, 0);
@@ -3436,37 +3601,44 @@ static void new_subtitle_stream(AVFormatContext *oc)
     subtitle_stream_copy = 0;
 }
 
-static void opt_new_audio_stream(void)
+static int opt_new_stream(const char *opt, const char *arg)
 {
     AVFormatContext *oc;
+    int file_idx = nb_output_files - 1;
     if (nb_output_files <= 0) {
         fprintf(stderr, "At least one output file must be specified\n");
-        av_exit(1);
+        ffmpeg_exit(1);
     }
-    oc = output_files[nb_output_files - 1];
-    new_audio_stream(oc);
-}
+    oc = output_files[file_idx];
 
-static void opt_new_video_stream(void)
-{
-    AVFormatContext *oc;
-    if (nb_output_files <= 0) {
-        fprintf(stderr, "At least one output file must be specified\n");
-        av_exit(1);
-    }
-    oc = output_files[nb_output_files - 1];
-    new_video_stream(oc);
+    if      (!strcmp(opt, "newvideo"   )) new_video_stream   (oc, file_idx);
+    else if (!strcmp(opt, "newaudio"   )) new_audio_stream   (oc, file_idx);
+    else if (!strcmp(opt, "newsubtitle")) new_subtitle_stream(oc, file_idx);
+    else av_assert0(0);
+    return 0;
 }
 
-static void opt_new_subtitle_stream(void)
+/* arg format is "output-stream-index:streamid-value". */
+static int opt_streamid(const char *opt, const char *arg)
 {
-    AVFormatContext *oc;
-    if (nb_output_files <= 0) {
-        fprintf(stderr, "At least one output file must be specified\n");
-        av_exit(1);
-    }
-    oc = output_files[nb_output_files - 1];
-    new_subtitle_stream(oc);
+    int idx;
+    char *p;
+    char idx_str[16];
+
+    strncpy(idx_str, arg, sizeof(idx_str));
+    idx_str[sizeof(idx_str)-1] = '\0';
+    p = strchr(idx_str, ':');
+    if (!p) {
+        fprintf(stderr,
+                "Invalid value '%s' for option '%s', required syntax is 'index:value'\n",
+                arg, opt);
+        ffmpeg_exit(1);
+    }
+    *p++ = '\0';
+    idx = parse_number_or_die(opt, idx_str, OPT_INT, 0, MAX_STREAMS-1);
+    streamid_map = grow_array(streamid_map, sizeof(*streamid_map), &nb_streamid_map, idx+1);
+    streamid_map[idx] = parse_number_or_die(opt, p, OPT_INT, 0, INT_MAX);
+    return 0;
 }
 
 static void opt_output_file(const char *filename)
@@ -3483,14 +3655,14 @@ static void opt_output_file(const char *filename)
     oc = avformat_alloc_context();
     if (!oc) {
         print_error(filename, AVERROR(ENOMEM));
-        av_exit(1);
+        ffmpeg_exit(1);
     }
 
     if (last_asked_format) {
         file_oformat = av_guess_format(last_asked_format, NULL, NULL);
         if (!file_oformat) {
             fprintf(stderr, "Requested output format '%s' is not a suitable output format\n", last_asked_format);
-            av_exit(1);
+            ffmpeg_exit(1);
         }
         last_asked_format = NULL;
     } else {
@@ -3498,7 +3670,7 @@ static void opt_output_file(const char *filename)
         if (!file_oformat) {
             fprintf(stderr, "Unable to find a suitable output format for '%s'\n",
                     filename);
-            av_exit(1);
+            ffmpeg_exit(1);
         }
     }
 
@@ -3512,7 +3684,7 @@ static void opt_output_file(const char *filename)
         int err = read_ffserver_streams(oc, filename);
         if (err < 0) {
             print_error(filename, err);
-            av_exit(1);
+            ffmpeg_exit(1);
         }
     } else {
         use_video = file_oformat->video_codec != CODEC_ID_NONE || video_stream_copy || video_codec_name;
@@ -3533,35 +3705,18 @@ static void opt_output_file(const char *filename)
         }
 
         /* manual disable */
-        if (audio_disable) {
-            use_audio = 0;
-        }
-        if (video_disable) {
-            use_video = 0;
-        }
-        if (subtitle_disable) {
-            use_subtitle = 0;
-        }
-
-        if (use_video) {
-            new_video_stream(oc);
-        }
+        if (audio_disable)    use_audio    = 0;
+        if (video_disable)    use_video    = 0;
+        if (subtitle_disable) use_subtitle = 0;
 
-        if (use_audio) {
-            new_audio_stream(oc);
-        }
-
-        if (use_subtitle) {
-            new_subtitle_stream(oc);
-        }
+        if (use_video)    new_video_stream(oc, nb_output_files);
+        if (use_audio)    new_audio_stream(oc, nb_output_files);
+        if (use_subtitle) new_subtitle_stream(oc, nb_output_files);
 
-        oc->timestamp = rec_timestamp;
+        oc->timestamp = recording_timestamp;
 
-        for(; metadata_count>0; metadata_count--){
-            av_metadata_set2(&oc->metadata, metadata[metadata_count-1].key,
-                                            metadata[metadata_count-1].value, 0);
-        }
-        av_metadata_conv(oc, oc->oformat->metadata_conv, NULL);
+        av_metadata_copy(&oc->metadata, metadata, 0);
+        av_metadata_free(&metadata);
     }
 
     output_files[nb_output_files++] = oc;
@@ -3570,7 +3725,7 @@ static void opt_output_file(const char *filename)
     if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
         if (!av_filename_number_test(oc->filename)) {
             print_error(oc->filename, AVERROR_NUMEXPECTED);
-            av_exit(1);
+            ffmpeg_exit(1);
         }
     }
 
@@ -3586,20 +3741,20 @@ static void opt_output_file(const char *filename)
                     fflush(stderr);
                     if (!read_yesno()) {
                         fprintf(stderr, "Not overwriting - exiting\n");
-                        av_exit(1);
+                        ffmpeg_exit(1);
                     }
                 }
                 else {
                     fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
-                    av_exit(1);
+                    ffmpeg_exit(1);
                 }
             }
         }
 
         /* open the file */
-        if ((err = url_fopen(&oc->pb, filename, URL_WRONLY)) < 0) {
+        if ((err = avio_open(&oc->pb, filename, AVIO_WRONLY)) < 0) {
             print_error(filename, err);
-            av_exit(1);
+            ffmpeg_exit(1);
         }
     }
 
@@ -3607,7 +3762,7 @@ static void opt_output_file(const char *filename)
     if (av_set_parameters(oc, ap) < 0) {
         fprintf(stderr, "%s: Invalid encoding parameters\n",
                 oc->filename);
-        av_exit(1);
+        ffmpeg_exit(1);
     }
 
     oc->preload= (int)(mux_preload*AV_TIME_BASE);
@@ -3615,7 +3770,9 @@ static void opt_output_file(const char *filename)
     oc->loop_output = loop_output;
     oc->flags |= AVFMT_FLAG_NONBLOCK;
 
-    set_context_opts(oc, avformat_opts, AV_OPT_FLAG_ENCODING_PARAM);
+    set_context_opts(oc, avformat_opts, AV_OPT_FLAG_ENCODING_PARAM, NULL);
+
+    av_freep(&forced_key_frames);
 }
 
 /* same option as mencoder */
@@ -3625,7 +3782,7 @@ static void opt_pass(const char *pass_str)
     pass = atoi(pass_str);
     if (pass != 1 && pass != 2) {
         fprintf(stderr, "pass number can be only 1 or 2\n");
-        av_exit(1);
+        ffmpeg_exit(1);
     }
     do_pass = pass;
 }
@@ -3677,7 +3834,7 @@ static void parse_matrix_coeffs(uint16_t *dest, const char *str)
         p = strchr(p, ',');
         if(!p) {
             fprintf(stderr, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
-            av_exit(1);
+            ffmpeg_exit(1);
         }
         p++;
     }
@@ -3695,15 +3852,6 @@ static void opt_intra_matrix(const char *arg)
     parse_matrix_coeffs(intra_matrix, arg);
 }
 
-/**
- * Trivial log callback.
- * Only suitable for show_help and similar since it lacks prefix handling.
- */
-static void log_callback_help(void* ptr, int level, const char* fmt, va_list vl)
-{
-    vfprintf(stdout, fmt, vl);
-}
-
 static void show_usage(void)
 {
     printf("Hyper fast Audio and Video encoder\n");
@@ -3713,6 +3861,9 @@ static void show_usage(void)
 
 static void show_help(void)
 {
+    AVCodec *c;
+    AVOutputFormat *oformat = NULL;
+
     av_log_set_callback(log_callback_help);
     show_usage();
     show_help_options(options, "Main options:\n",
@@ -3739,11 +3890,30 @@ static void show_help(void)
                       OPT_GRAB,
                       OPT_GRAB);
     printf("\n");
-    av_opt_show(avcodec_opts[0], NULL);
+    av_opt_show2(avcodec_opts[0], NULL, AV_OPT_FLAG_ENCODING_PARAM|AV_OPT_FLAG_DECODING_PARAM, 0);
     printf("\n");
-    av_opt_show(avformat_opts, NULL);
+
+    /* individual codec options */
+    c = NULL;
+    while ((c = av_codec_next(c))) {
+        if (c->priv_class) {
+            av_opt_show2(&c->priv_class, NULL, AV_OPT_FLAG_ENCODING_PARAM|AV_OPT_FLAG_DECODING_PARAM, 0);
+            printf("\n");
+        }
+    }
+
+    av_opt_show2(avformat_opts, NULL, AV_OPT_FLAG_ENCODING_PARAM|AV_OPT_FLAG_DECODING_PARAM, 0);
     printf("\n");
-    av_opt_show(sws_opts, NULL);
+
+    /* individual muxer options */
+    while ((oformat = av_oformat_next(oformat))) {
+        if (oformat->priv_class) {
+            av_opt_show2(&oformat->priv_class, NULL, AV_OPT_FLAG_ENCODING_PARAM, 0);
+            printf("\n");
+        }
+    }
+
+    av_opt_show2(sws_opts, NULL, AV_OPT_FLAG_ENCODING_PARAM|AV_OPT_FLAG_DECODING_PARAM, 0);
 }
 
 static void opt_target(const char *arg)
@@ -3799,7 +3969,7 @@ static void opt_target(const char *arg)
         fprintf(stderr, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
         fprintf(stderr, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
         fprintf(stderr, "or set a framerate with \"-r xxx\".\n");
-        av_exit(1);
+        ffmpeg_exit(1);
     }
 
     if(!strcmp(arg, "vcd")) {
@@ -3887,7 +4057,7 @@ static void opt_target(const char *arg)
 
     } else {
         fprintf(stderr, "Unknown target: %s\n", arg);
-        av_exit(1);
+        ffmpeg_exit(1);
     }
 }
 
@@ -3915,7 +4085,7 @@ static int opt_bsf(const char *opt, const char *arg)
 
     if(!bsfc){
         fprintf(stderr, "Unknown bitstream filter %s\n", arg);
-        av_exit(1);
+        ffmpeg_exit(1);
     }
 
     bsfp= *opt == 'v' ? &video_bitstream_filters :
@@ -3933,34 +4103,13 @@ static int opt_preset(const char *opt, const char *arg)
 {
     FILE *f=NULL;
     char filename[1000], tmp[1000], tmp2[1000], line[1000];
-    int i;
-    const char *base[3]= { getenv("FFMPEG_DATADIR"),
-                           getenv("HOME"),
-                           FFMPEG_DATADIR,
-                         };
-
-    if (*opt != 'f') {
-        for(i=0; i<3 && !f; i++){
-            if(!base[i])
-                continue;
-            snprintf(filename, sizeof(filename), "%s%s/%s.ffpreset", base[i], i != 1 ? "" : "/.ffmpeg", arg);
-            f= fopen(filename, "r");
-            if(!f){
-                char *codec_name= *opt == 'v' ? video_codec_name :
-                                  *opt == 'a' ? audio_codec_name :
-                                                subtitle_codec_name;
-                snprintf(filename, sizeof(filename), "%s%s/%s-%s.ffpreset", base[i],  i != 1 ? "" : "/.ffmpeg", codec_name, arg);
-                f= fopen(filename, "r");
-            }
-        }
-    } else {
-        av_strlcpy(filename, arg, sizeof(filename));
-        f= fopen(filename, "r");
-    }
+    char *codec_name = *opt == 'v' ? video_codec_name :
+                       *opt == 'a' ? audio_codec_name :
+                                     subtitle_codec_name;
 
-    if(!f){
+    if (!(f = get_preset_file(filename, sizeof(filename), arg, *opt == 'f', codec_name))) {
         fprintf(stderr, "File for preset '%s' not found\n", arg);
-        av_exit(1);
+        ffmpeg_exit(1);
     }
 
     while(!feof(f)){
@@ -3970,7 +4119,7 @@ static int opt_preset(const char *opt, const char *arg)
         e|= sscanf(line, "%999[^=]=%999[^\n]\n", tmp, tmp2) - 2;
         if(e){
             fprintf(stderr, "%s: Invalid syntax: '%s'\n", filename, line);
-            av_exit(1);
+            ffmpeg_exit(1);
         }
         if(!strcmp(tmp, "acodec")){
             opt_audio_codec(tmp2);
@@ -3980,7 +4129,7 @@ static int opt_preset(const char *opt, const char *arg)
             opt_subtitle_codec(tmp2);
         }else if(opt_default(tmp, tmp2) < 0){
             fprintf(stderr, "%s: Invalid option or argument: '%s', parsed as '%s' = '%s'\n", filename, line, tmp, tmp2);
-            av_exit(1);
+            ffmpeg_exit(1);
         }
     }
 
@@ -3995,14 +4144,18 @@ static const OptionDef options[] = {
     { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
     { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
     { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
-    { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream[:syncfile:syncstream]" },
-    { "map_meta_data", HAS_ARG | OPT_EXPERT, {(void*)opt_map_meta_data}, "set meta data information of outfile from infile", "outfile:infile" },
+    { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file.stream[:syncfile.syncstream]" },
+    { "map_meta_data", HAS_ARG | OPT_EXPERT, {(void*)opt_map_meta_data}, "DEPRECATED set meta data information of outfile from infile",
+      "outfile[,metadata]:infile[,metadata]" },
+    { "map_metadata", HAS_ARG | OPT_EXPERT, {(void*)opt_map_metadata}, "set metadata information of outfile from infile",
+      "outfile[,metadata]:infile[,metadata]" },
+    { "map_chapters",  HAS_ARG | OPT_EXPERT, {(void*)opt_map_chapters},  "set chapters mapping", "outfile:infile" },
     { "t", OPT_FUNC2 | HAS_ARG, {(void*)opt_recording_time}, "record or transcode \"duration\" seconds of audio/video", "duration" },
     { "fs", HAS_ARG | OPT_INT64, {(void*)&limit_filesize}, "set the limit file size in bytes", "limit_size" }, //
     { "ss", OPT_FUNC2 | HAS_ARG, {(void*)opt_start_time}, "set the start time offset", "time_off" },
     { "itsoffset", OPT_FUNC2 | HAS_ARG, {(void*)opt_input_ts_offset}, "set the input ts offset", "time_off" },
     { "itsscale", HAS_ARG, {(void*)opt_input_ts_scale}, "set the input ts scale", "stream:scale" },
-    { "timestamp", OPT_FUNC2 | HAS_ARG, {(void*)opt_rec_timestamp}, "set the timestamp ('now' to set the current time)", "time" },
+    { "timestamp", OPT_FUNC2 | HAS_ARG, {(void*)opt_recording_timestamp}, "set the recording timestamp ('now' to set the current time)", "time" },
     { "metadata", OPT_FUNC2 | HAS_ARG, {(void*)opt_metadata}, "add metadata", "string=string" },
     { "dframes", OPT_INT | HAS_ARG, {(void*)&max_frames[AVMEDIA_TYPE_DATA]}, "set the number of data frames to record", "number" },
     { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
@@ -4023,6 +4176,7 @@ static const OptionDef options[] = {
     { "adrift_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&audio_drift_threshold}, "audio drift threshold", "threshold" },
     { "vglobal", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&video_global_header}, "video global header storage type", "" },
     { "copyts", OPT_BOOL | OPT_EXPERT, {(void*)&copy_ts}, "copy timestamps" },
+    { "copytb", OPT_BOOL | OPT_EXPERT, {(void*)&copy_tb}, "copy input stream time base when stream copying" },
     { "shortest", OPT_BOOL | OPT_EXPERT, {(void*)&opt_shortest}, "finish encoding within shortest input" }, //
     { "dts_delta_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&dts_delta_threshold}, "timestamp discontinuity delta threshold", "threshold" },
     { "programid", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&opt_programid}, "desired program number", "" },
@@ -4037,15 +4191,15 @@ static const OptionDef options[] = {
     { "s", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
     { "aspect", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_aspect_ratio}, "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
     { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_frame_pix_fmt}, "set pixel format, 'list' as argument shows all the pixel formats supported", "format" },
-    { "croptop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_top}, "set top crop band size (in pixels)", "size" },
-    { "cropbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_bottom}, "set bottom crop band size (in pixels)", "size" },
-    { "cropleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_left}, "set left crop band size (in pixels)", "size" },
-    { "cropright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_right}, "set right crop band size (in pixels)", "size" },
-    { "padtop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_top}, "set top pad band size (in pixels)", "size" },
-    { "padbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_bottom}, "set bottom pad band size (in pixels)", "size" },
-    { "padleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_left}, "set left pad band size (in pixels)", "size" },
-    { "padright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_right}, "set right pad band size (in pixels)", "size" },
-    { "padcolor", HAS_ARG | OPT_VIDEO, {(void*)opt_pad_color}, "set color of pad bands (Hex 000000 thru FFFFFF)", "color" },
+    { "croptop", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
+    { "cropbottom", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
+    { "cropleft", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
+    { "cropright", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
+    { "padtop", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
+    { "padbottom", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
+    { "padleft", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
+    { "padright", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
+    { "padcolor", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "color" },
     { "intra", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_only}, "use only intra frames"},
     { "vn", OPT_BOOL | OPT_VIDEO, {(void*)&video_disable}, "disable video" },
     { "vdt", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&video_discard}, "discard threshold", "n" },
@@ -4054,7 +4208,7 @@ static const OptionDef options[] = {
     { "vcodec", HAS_ARG | OPT_VIDEO, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
     { "me_threshold", HAS_ARG | OPT_FUNC2 | OPT_EXPERT | OPT_VIDEO, {(void*)opt_me_threshold}, "motion estimaton threshold",  "threshold" },
     { "sameq", OPT_BOOL | OPT_VIDEO, {(void*)&same_quality},
-      "use same video quality as source (implies VBR)" },
+      "use same quantizer as source (implies VBR)" },
     { "pass", HAS_ARG | OPT_VIDEO, {(void*)&opt_pass}, "select the pass number (1 or 2)", "n" },
     { "passlogfile", HAS_ARG | OPT_STRING | OPT_VIDEO, {(void*)&pass_logfilename_prefix}, "select two pass log file name prefix", "prefix" },
     { "deinterlace", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_deinterlace},
@@ -4062,15 +4216,20 @@ static const OptionDef options[] = {
     { "psnr", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
     { "vstats", OPT_EXPERT | OPT_VIDEO, {(void*)&opt_vstats}, "dump video coding statistics to file" },
     { "vstats_file", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_vstats_file}, "dump video coding statistics to file", "file" },
+#if CONFIG_AVFILTER
+    { "vf", OPT_STRING | HAS_ARG, {(void*)&vfilters}, "video filters", "filter list" },
+#endif
     { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_intra_matrix}, "specify intra matrix coeffs", "matrix" },
     { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_inter_matrix}, "specify inter matrix coeffs", "matrix" },
     { "top", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_top_field_first}, "top=1/bottom=0/auto=-1 field first", "" },
     { "dc", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_dc_precision}, "intra_dc_precision", "precision" },
-    { "vtag", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_tag}, "force video tag/fourcc", "fourcc/tag" },
-    { "newvideo", OPT_VIDEO, {(void*)opt_new_video_stream}, "add a new video stream to the current output stream" },
+    { "vtag", OPT_FUNC2 | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_codec_tag}, "force video tag/fourcc", "fourcc/tag" },
+    { "newvideo", OPT_VIDEO | OPT_FUNC2, {(void*)opt_new_stream}, "add a new video stream to the current output stream" },
     { "vlang", HAS_ARG | OPT_STRING | OPT_VIDEO, {(void *)&video_language}, "set the ISO 639 language code (3 letters) of the current video stream" , "code" },
     { "qphist", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, { (void *)&qp_hist }, "show QP histogram" },
     { "force_fps", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&force_fps}, "force the selected framerate, disable the best supported framerate selection" },
+    { "streamid", OPT_FUNC2 | HAS_ARG | OPT_EXPERT, {(void*)opt_streamid}, "set the value of an outfile streamid", "streamIndex:value" },
+    { "force_key_frames", OPT_STRING | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void *)&forced_key_frames}, "force key frames at specified timestamps", "timestamps" },
 
     /* audio options */
     { "ab", OPT_FUNC2 | HAS_ARG | OPT_AUDIO, {(void*)opt_bitrate}, "set bitrate (in bits/s)", "bitrate" },
@@ -4080,18 +4239,18 @@ static const OptionDef options[] = {
     { "ac", HAS_ARG | OPT_FUNC2 | OPT_AUDIO, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
     { "an", OPT_BOOL | OPT_AUDIO, {(void*)&audio_disable}, "disable audio" },
     { "acodec", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
-    { "atag", HAS_ARG | OPT_EXPERT | OPT_AUDIO, {(void*)opt_audio_tag}, "force audio tag/fourcc", "fourcc/tag" },
+    { "atag", OPT_FUNC2 | HAS_ARG | OPT_EXPERT | OPT_AUDIO, {(void*)opt_codec_tag}, "force audio tag/fourcc", "fourcc/tag" },
     { "vol", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&audio_volume}, "change audio volume (256=normal)" , "volume" }, //
-    { "newaudio", OPT_AUDIO, {(void*)opt_new_audio_stream}, "add a new audio stream to the current output stream" },
+    { "newaudio", OPT_AUDIO | OPT_FUNC2, {(void*)opt_new_stream}, "add a new audio stream to the current output stream" },
     { "alang", HAS_ARG | OPT_STRING | OPT_AUDIO, {(void *)&audio_language}, "set the ISO 639 language code (3 letters) of the current audio stream" , "code" },
     { "sample_fmt", HAS_ARG | OPT_EXPERT | OPT_AUDIO, {(void*)opt_audio_sample_fmt}, "set sample format, 'list' as argument shows all the sample formats supported", "format" },
 
     /* subtitle options */
     { "sn", OPT_BOOL | OPT_SUBTITLE, {(void*)&subtitle_disable}, "disable subtitle" },
     { "scodec", HAS_ARG | OPT_SUBTITLE, {(void*)opt_subtitle_codec}, "force subtitle codec ('copy' to copy stream)", "codec" },
-    { "newsubtitle", OPT_SUBTITLE, {(void*)opt_new_subtitle_stream}, "add a new subtitle stream to the current output stream" },
+    { "newsubtitle", OPT_SUBTITLE | OPT_FUNC2, {(void*)opt_new_stream}, "add a new subtitle stream to the current output stream" },
     { "slang", HAS_ARG | OPT_STRING | OPT_SUBTITLE, {(void *)&subtitle_language}, "set the ISO 639 language code (3 letters) of the current subtitle stream" , "code" },
-    { "stag", HAS_ARG | OPT_EXPERT | OPT_SUBTITLE, {(void*)opt_subtitle_tag}, "force subtitle tag/fourcc", "fourcc/tag" },
+    { "stag", OPT_FUNC2 | HAS_ARG | OPT_EXPERT | OPT_SUBTITLE, {(void*)opt_codec_tag}, "force subtitle tag/fourcc", "fourcc/tag" },
 
     /* grab options */
     { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "set video grab channel (DV1394 only)", "channel" },
@@ -4117,25 +4276,25 @@ static const OptionDef options[] = {
 
 int main(int argc, char **argv)
 {
-    int i;
     int64_t ti;
 
+    av_log_set_flags(AV_LOG_SKIP_REPEATED);
+
     avcodec_register_all();
 #if CONFIG_AVDEVICE
     avdevice_register_all();
 #endif
+#if CONFIG_AVFILTER
+    avfilter_register_all();
+#endif
     av_register_all();
 
 #if HAVE_ISATTY
     if(isatty(STDIN_FILENO))
-        url_set_interrupt_cb(decode_interrupt_cb);
+        avio_set_interrupt_cb(decode_interrupt_cb);
 #endif
 
-    for(i=0; i<AVMEDIA_TYPE_NB; i++){
-        avcodec_opts[i]= avcodec_alloc_context2(i);
-    }
-    avformat_opts = avformat_alloc_context();
-    sws_opts = sws_getContext(16,16,0, 16,16,0, sws_flags, NULL,NULL,NULL);
+    init_opts();
 
     show_banner();
 
@@ -4145,29 +4304,29 @@ int main(int argc, char **argv)
     if(nb_output_files <= 0 && nb_input_files == 0) {
         show_usage();
         fprintf(stderr, "Use -h to get full help or, even better, run 'man ffmpeg'\n");
-        av_exit(1);
+        ffmpeg_exit(1);
     }
 
     /* file converter / grab */
     if (nb_output_files <= 0) {
         fprintf(stderr, "At least one output file must be specified\n");
-        av_exit(1);
+        ffmpeg_exit(1);
     }
 
     if (nb_input_files == 0) {
         fprintf(stderr, "At least one input file must be specified\n");
-        av_exit(1);
+        ffmpeg_exit(1);
     }
 
     ti = getutime();
-    if (av_transcode(output_files, nb_output_files, input_files, nb_input_files,
-                     stream_maps, nb_stream_maps) < 0)
-        av_exit(1);
+    if (transcode(output_files, nb_output_files, input_files, nb_input_files,
+                  stream_maps, nb_stream_maps) < 0)
+        ffmpeg_exit(1);
     ti = getutime() - ti;
     if (do_benchmark) {
         int maxrss = getmaxrss() / 1024;
         printf("bench: utime=%0.3fs maxrss=%ikB\n", ti / 1000000.0, maxrss);
     }
 
-    return av_exit(0);
+    return ffmpeg_exit(0);
 }
diff --git a/ffplay.c b/ffplay.c
index e79e17b..bd8a985 100644
--- a/ffplay.c
+++ b/ffplay.c
@@ -1,42 +1,46 @@
 /*
- * FFplay : Simple Media Player based on the FFmpeg libraries
+ * FFplay : Simple Media Player based on the Libav libraries
  * Copyright (c) 2003 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#define _XOPEN_SOURCE 600
+
 #include "config.h"
 #include <inttypes.h>
 #include <math.h>
 #include <limits.h>
 #include "libavutil/avstring.h"
+#include "libavutil/colorspace.h"
 #include "libavutil/pixdesc.h"
+#include "libavutil/imgutils.h"
+#include "libavutil/parseutils.h"
+#include "libavutil/samplefmt.h"
 #include "libavformat/avformat.h"
 #include "libavdevice/avdevice.h"
 #include "libswscale/swscale.h"
 #include "libavcodec/audioconvert.h"
-#include "libavcodec/colorspace.h"
 #include "libavcodec/opt.h"
 #include "libavcodec/avfft.h"
 
 #if CONFIG_AVFILTER
 # include "libavfilter/avfilter.h"
 # include "libavfilter/avfiltergraph.h"
-# include "libavfilter/graphparser.h"
 #endif
 
 #include "cmdutils.h"
@@ -54,6 +58,7 @@
 const char program_name[] = "FFplay";
 const int program_birth_year = 2003;
 
+//#define DEBUG
 //#define DEBUG_SYNC
 
 #define MAX_QUEUE_SIZE (15 * 1024 * 1024)
@@ -80,9 +85,7 @@ const int program_birth_year = 2003;
 /* NOTE: the size must be big enough to compensate the hardware audio buffersize size */
 #define SAMPLE_ARRAY_SIZE (2*65536)
 
-#if !CONFIG_AVFILTER
 static int sws_flags = SWS_BICUBIC;
-#endif
 
 typedef struct PacketQueue {
     AVPacketList *first_pkt, *last_pkt;
@@ -106,7 +109,7 @@ typedef struct VideoPicture {
     enum PixelFormat pix_fmt;
 
 #if CONFIG_AVFILTER
-    AVFilterPicRef *picref;
+    AVFilterBufferRef *picref;
 #endif
 } VideoPicture;
 
@@ -161,7 +164,7 @@ typedef struct VideoState {
     int audio_buf_index; /* in bytes */
     AVPacket audio_pkt_temp;
     AVPacket audio_pkt;
-    enum SampleFormat audio_src_fmt;
+    enum AVSampleFormat audio_src_fmt;
     AVAudioConvert *reformat_ctx;
 
     int show_audio; /* if true, display audio samples */
@@ -170,6 +173,7 @@ typedef struct VideoState {
     int last_i_start;
     RDFTContext *rdft;
     int rdft_bits;
+    FFTSample *rdft_data;
     int xpos;
 
     SDL_Thread *subtitle_tid;
@@ -204,10 +208,7 @@ typedef struct VideoState {
     char filename[1024];
     int width, height, xleft, ytop;
 
-    int64_t faulty_pts;
-    int64_t faulty_dts;
-    int64_t last_dts_for_fault_detection;
-    int64_t last_pts_for_fault_detection;
+    PtsCorrectionContext pts_ctx;
 
 #if CONFIG_AVFILTER
     AVFilterContext *out_video_filter;          ///<the last filter in the video chain
@@ -261,6 +262,8 @@ static int error_recognition = FF_ER_CAREFUL;
 static int error_concealment = 3;
 static int decoder_reorder_pts= -1;
 static int autoexit;
+static int exit_on_keydown;
+static int exit_on_mousedown;
 static int loop=1;
 static int framedrop=1;
 
@@ -676,18 +679,7 @@ static void blend_subrect(AVPicture *dst, const AVSubtitleRect *rect, int imgw,
 
 static void free_subpicture(SubPicture *sp)
 {
-    int i;
-
-    for (i = 0; i < sp->sub.num_rects; i++)
-    {
-        av_freep(&sp->sub.rects[i]->pict.data[0]);
-        av_freep(&sp->sub.rects[i]->pict.data[1]);
-        av_freep(&sp->sub.rects[i]);
-    }
-
-    av_free(sp->sub.rects);
-
-    memset(&sp->sub, 0, sizeof(AVSubtitle));
+    avsubtitle_free(&sp->sub);
 }
 
 static void video_image_display(VideoState *is)
@@ -703,10 +695,10 @@ static void video_image_display(VideoState *is)
     vp = &is->pictq[is->pictq_rindex];
     if (vp->bmp) {
 #if CONFIG_AVFILTER
-         if (vp->picref->pixel_aspect.num == 0)
+         if (vp->picref->video->pixel_aspect.num == 0)
              aspect_ratio = 0;
          else
-             aspect_ratio = av_q2d(vp->picref->pixel_aspect);
+             aspect_ratio = av_q2d(vp->picref->video->pixel_aspect);
 #else
 
         /* XXX: use variable in the frame */
@@ -720,40 +712,6 @@ static void video_image_display(VideoState *is)
         if (aspect_ratio <= 0.0)
             aspect_ratio = 1.0;
         aspect_ratio *= (float)vp->width / (float)vp->height;
-        /* if an active format is indicated, then it overrides the
-           mpeg format */
-#if 0
-        if (is->video_st->codec->dtg_active_format != is->dtg_active_format) {
-            is->dtg_active_format = is->video_st->codec->dtg_active_format;
-            printf("dtg_active_format=%d\n", is->dtg_active_format);
-        }
-#endif
-#if 0
-        switch(is->video_st->codec->dtg_active_format) {
-        case FF_DTG_AFD_SAME:
-        default:
-            /* nothing to do */
-            break;
-        case FF_DTG_AFD_4_3:
-            aspect_ratio = 4.0 / 3.0;
-            break;
-        case FF_DTG_AFD_16_9:
-            aspect_ratio = 16.0 / 9.0;
-            break;
-        case FF_DTG_AFD_14_9:
-            aspect_ratio = 14.0 / 9.0;
-            break;
-        case FF_DTG_AFD_4_3_SP_14_9:
-            aspect_ratio = 14.0 / 9.0;
-            break;
-        case FF_DTG_AFD_16_9_SP_14_9:
-            aspect_ratio = 14.0 / 9.0;
-            break;
-        case FF_DTG_AFD_SP_4_3:
-            aspect_ratio = 4.0 / 3.0;
-            break;
-        }
-#endif
 
         if (is->subtitle_st)
         {
@@ -919,12 +877,15 @@ static void video_audio_display(VideoState *s)
         nb_display_channels= FFMIN(nb_display_channels, 2);
         if(rdft_bits != s->rdft_bits){
             av_rdft_end(s->rdft);
+            av_free(s->rdft_data);
             s->rdft = av_rdft_init(rdft_bits, DFT_R2C);
             s->rdft_bits= rdft_bits;
+            s->rdft_data= av_malloc(4*nb_freq*sizeof(*s->rdft_data));
         }
         {
-            FFTSample data[2][2*nb_freq];
+            FFTSample *data[2];
             for(ch = 0;ch < nb_display_channels; ch++) {
+                data[ch] = s->rdft_data + 2*nb_freq*ch;
                 i = i_start + ch;
                 for(x = 0; x < 2*nb_freq; x++) {
                     double w= (x-nb_freq)*(1.0/nb_freq);
@@ -939,7 +900,8 @@ static void video_audio_display(VideoState *s)
             for(y=0; y<s->height; y++){
                 double w= 1/sqrt(nb_freq);
                 int a= sqrt(w*sqrt(data[0][2*y+0]*data[0][2*y+0] + data[0][2*y+1]*data[0][2*y+1]));
-                int b= sqrt(w*sqrt(data[1][2*y+0]*data[1][2*y+0] + data[1][2*y+1]*data[1][2*y+1]));
+                int b= (nb_display_channels == 2 ) ? sqrt(w*sqrt(data[1][2*y+0]*data[1][2*y+0]
+                       + data[1][2*y+1]*data[1][2*y+1])) : a;
                 a= FFMIN(a,255);
                 b= FFMIN(b,255);
                 fgcolor = SDL_MapRGB(screen->format, a, b, (a+b)/2);
@@ -1021,12 +983,12 @@ static int refresh_thread(void *opaque)
 {
     VideoState *is= opaque;
     while(!is->abort_request){
-    SDL_Event event;
-    event.type = FF_REFRESH_EVENT;
-    event.user.data1 = opaque;
+        SDL_Event event;
+        event.type = FF_REFRESH_EVENT;
+        event.user.data1 = opaque;
         if(!is->refresh){
             is->refresh=1;
-    SDL_PushEvent(&event);
+            SDL_PushEvent(&event);
         }
         usleep(is->audio_st && is->show_audio ? rdftspeed*1000 : 5000); //FIXME ideally we should wait the correct time but SDLs event passing is so slow it would be silly
     }
@@ -1247,7 +1209,8 @@ retry:
             }
 
             /* display picture */
-            video_display(is);
+            if (!display_disable)
+                video_display(is);
 
             /* update queue size and signal for next picture */
             if (++is->pictq_rindex == VIDEO_PICTURE_QUEUE_SIZE)
@@ -1265,7 +1228,8 @@ retry:
            than nothing, just to test the implementation */
 
         /* display picture */
-        video_display(is);
+        if (!display_disable)
+            video_display(is);
     }
     if (show_status) {
         static int64_t last_time;
@@ -1288,13 +1252,64 @@ retry:
             if (is->audio_st && is->video_st)
                 av_diff = get_audio_clock(is) - get_video_clock(is);
             printf("%7.2f A-V:%7.3f s:%3.1f aq=%5dKB vq=%5dKB sq=%5dB f=%"PRId64"/%"PRId64"   \r",
-                   get_master_clock(is), av_diff, FFMAX(is->skip_frames-1, 0), aqsize / 1024, vqsize / 1024, sqsize, is->faulty_dts, is->faulty_pts);
+                   get_master_clock(is), av_diff, FFMAX(is->skip_frames-1, 0), aqsize / 1024, vqsize / 1024, sqsize, is->pts_ctx.num_faulty_dts, is->pts_ctx.num_faulty_pts);
             fflush(stdout);
             last_time = cur_time;
         }
     }
 }
 
+static void stream_close(VideoState *is)
+{
+    VideoPicture *vp;
+    int i;
+    /* XXX: use a special url_shutdown call to abort parse cleanly */
+    is->abort_request = 1;
+    SDL_WaitThread(is->parse_tid, NULL);
+    SDL_WaitThread(is->refresh_tid, NULL);
+
+    /* free all pictures */
+    for(i=0;i<VIDEO_PICTURE_QUEUE_SIZE; i++) {
+        vp = &is->pictq[i];
+#if CONFIG_AVFILTER
+        if (vp->picref) {
+            avfilter_unref_buffer(vp->picref);
+            vp->picref = NULL;
+        }
+#endif
+        if (vp->bmp) {
+            SDL_FreeYUVOverlay(vp->bmp);
+            vp->bmp = NULL;
+        }
+    }
+    SDL_DestroyMutex(is->pictq_mutex);
+    SDL_DestroyCond(is->pictq_cond);
+    SDL_DestroyMutex(is->subpq_mutex);
+    SDL_DestroyCond(is->subpq_cond);
+#if !CONFIG_AVFILTER
+    if (is->img_convert_ctx)
+        sws_freeContext(is->img_convert_ctx);
+#endif
+    av_free(is);
+}
+
+static void do_exit(void)
+{
+    if (cur_stream) {
+        stream_close(cur_stream);
+        cur_stream = NULL;
+    }
+    uninit_opts();
+#if CONFIG_AVFILTER
+    avfilter_uninit();
+#endif
+    if (show_status)
+        printf("\n");
+    SDL_Quit();
+    av_log(NULL, AV_LOG_QUIET, "");
+    exit(0);
+}
+
 /* allocate a picture (needs to do that in main thread to avoid
    potential locking problems */
 static void alloc_picture(void *opaque)
@@ -1309,7 +1324,7 @@ static void alloc_picture(void *opaque)
 
 #if CONFIG_AVFILTER
     if (vp->picref)
-        avfilter_unref_pic(vp->picref);
+        avfilter_unref_buffer(vp->picref);
     vp->picref = NULL;
 
     vp->width   = is->out_video_filter->inputs[0]->w;
@@ -1324,6 +1339,14 @@ static void alloc_picture(void *opaque)
     vp->bmp = SDL_CreateYUVOverlay(vp->width, vp->height,
                                    SDL_YV12_OVERLAY,
                                    screen);
+    if (!vp->bmp || vp->bmp->pitches[0] < vp->width) {
+        /* SDL allocates a buffer smaller than requested if the video
+         * overlay hardware is unable to support the requested size. */
+        fprintf(stderr, "Error: the video system does not support an image\n"
+                        "size of %dx%d pixels. Try using -lowres or -vf \"scale=w:h\"\n"
+                        "to reduce the image size.\n", vp->width, vp->height );
+        do_exit();
+    }
 
     SDL_LockMutex(is->pictq_mutex);
     vp->allocated = 1;
@@ -1394,7 +1417,7 @@ static int queue_picture(VideoState *is, AVFrame *src_frame, double pts, int64_t
         AVPicture pict;
 #if CONFIG_AVFILTER
         if(vp->picref)
-            avfilter_unref_pic(vp->picref);
+            avfilter_unref_buffer(vp->picref);
         vp->picref = src_frame->opaque;
 #endif
 
@@ -1487,64 +1510,49 @@ static int get_video_frame(VideoState *is, AVFrame *frame, int64_t *pts, AVPacke
 {
     int len1, got_picture, i;
 
-        if (packet_queue_get(&is->videoq, pkt, 1) < 0)
-            return -1;
-
-        if(pkt->data == flush_pkt.data){
-            avcodec_flush_buffers(is->video_st->codec);
+    if (packet_queue_get(&is->videoq, pkt, 1) < 0)
+        return -1;
 
-            SDL_LockMutex(is->pictq_mutex);
-            //Make sure there are no long delay timers (ideally we should just flush the que but thats harder)
-            for(i=0; i<VIDEO_PICTURE_QUEUE_SIZE; i++){
-                is->pictq[i].target_clock= 0;
-            }
-            while (is->pictq_size && !is->videoq.abort_request) {
-                SDL_CondWait(is->pictq_cond, is->pictq_mutex);
-            }
-            is->video_current_pos= -1;
-            SDL_UnlockMutex(is->pictq_mutex);
+    if (pkt->data == flush_pkt.data) {
+        avcodec_flush_buffers(is->video_st->codec);
 
-            is->last_dts_for_fault_detection=
-            is->last_pts_for_fault_detection= INT64_MIN;
-            is->frame_last_pts= AV_NOPTS_VALUE;
-            is->frame_last_delay = 0;
-            is->frame_timer = (double)av_gettime() / 1000000.0;
-            is->skip_frames= 1;
-            is->skip_frames_index= 0;
-            return 0;
+        SDL_LockMutex(is->pictq_mutex);
+        //Make sure there are no long delay timers (ideally we should just flush the que but thats harder)
+        for (i = 0; i < VIDEO_PICTURE_QUEUE_SIZE; i++) {
+            is->pictq[i].target_clock= 0;
+        }
+        while (is->pictq_size && !is->videoq.abort_request) {
+            SDL_CondWait(is->pictq_cond, is->pictq_mutex);
         }
+        is->video_current_pos = -1;
+        SDL_UnlockMutex(is->pictq_mutex);
 
-        /* NOTE: ipts is the PTS of the _first_ picture beginning in
-           this packet, if any */
-        is->video_st->codec->reordered_opaque= pkt->pts;
-        len1 = avcodec_decode_video2(is->video_st->codec,
-                                    frame, &got_picture,
-                                    pkt);
+        init_pts_correction(&is->pts_ctx);
+        is->frame_last_pts = AV_NOPTS_VALUE;
+        is->frame_last_delay = 0;
+        is->frame_timer = (double)av_gettime() / 1000000.0;
+        is->skip_frames = 1;
+        is->skip_frames_index = 0;
+        return 0;
+    }
 
-        if (got_picture) {
-            if(pkt->dts != AV_NOPTS_VALUE){
-                is->faulty_dts += pkt->dts <= is->last_dts_for_fault_detection;
-                is->last_dts_for_fault_detection= pkt->dts;
-            }
-            if(frame->reordered_opaque != AV_NOPTS_VALUE){
-                is->faulty_pts += frame->reordered_opaque <= is->last_pts_for_fault_detection;
-                is->last_pts_for_fault_detection= frame->reordered_opaque;
-            }
+    len1 = avcodec_decode_video2(is->video_st->codec,
+                                 frame, &got_picture,
+                                 pkt);
+
+    if (got_picture) {
+        if (decoder_reorder_pts == -1) {
+            *pts = guess_correct_pts(&is->pts_ctx, frame->pkt_pts, frame->pkt_dts);
+        } else if (decoder_reorder_pts) {
+            *pts = frame->pkt_pts;
+        } else {
+            *pts = frame->pkt_dts;
         }
 
-        if(   (   decoder_reorder_pts==1
-               || (decoder_reorder_pts && is->faulty_pts<is->faulty_dts)
-               || pkt->dts == AV_NOPTS_VALUE)
-           && frame->reordered_opaque != AV_NOPTS_VALUE)
-            *pts= frame->reordered_opaque;
-        else if(pkt->dts != AV_NOPTS_VALUE)
-            *pts= pkt->dts;
-        else
-            *pts= 0;
+        if (*pts == AV_NOPTS_VALUE) {
+            *pts = 0;
+        }
 
-//            if (len1 < 0)
-//                break;
-    if (got_picture){
         is->skip_frames_index += 1;
         if(is->skip_frames_index >= is->skip_frames){
             is->skip_frames_index -= FFMAX(is->skip_frames, 1.0);
@@ -1565,11 +1573,14 @@ typedef struct {
 static int input_get_buffer(AVCodecContext *codec, AVFrame *pic)
 {
     AVFilterContext *ctx = codec->opaque;
-    AVFilterPicRef  *ref;
+    AVFilterBufferRef  *ref;
     int perms = AV_PERM_WRITE;
-    int w, h, stride[4];
+    int i, w, h, stride[4];
     unsigned edge;
 
+    if (codec->codec->capabilities & CODEC_CAP_NEG_LINESIZES)
+        perms |= AV_PERM_NEG_LINESIZES;
+
     if(pic->buffer_hints & FF_BUFFER_HINTS_VALID) {
         if(pic->buffer_hints & FF_BUFFER_HINTS_READABLE) perms |= AV_PERM_READ;
         if(pic->buffer_hints & FF_BUFFER_HINTS_PRESERVE) perms |= AV_PERM_PRESERVE;
@@ -1587,11 +1598,11 @@ static int input_get_buffer(AVCodecContext *codec, AVFrame *pic)
     if(!(ref = avfilter_get_video_buffer(ctx->outputs[0], perms, w, h)))
         return -1;
 
-    ref->w = codec->width;
-    ref->h = codec->height;
-    for(int i = 0; i < 3; i ++) {
-        unsigned hshift = i == 0 ? 0 : av_pix_fmt_descriptors[ref->pic->format].log2_chroma_w;
-        unsigned vshift = i == 0 ? 0 : av_pix_fmt_descriptors[ref->pic->format].log2_chroma_h;
+    ref->video->w = codec->width;
+    ref->video->h = codec->height;
+    for(i = 0; i < 4; i ++) {
+        unsigned hshift = (i == 1 || i == 2) ? av_pix_fmt_descriptors[ref->format].log2_chroma_w : 0;
+        unsigned vshift = (i == 1 || i == 2) ? av_pix_fmt_descriptors[ref->format].log2_chroma_h : 0;
 
         if (ref->data[i]) {
             ref->data[i]    += (edge >> hshift) + ((edge * ref->linesize[i]) >> vshift);
@@ -1602,13 +1613,37 @@ static int input_get_buffer(AVCodecContext *codec, AVFrame *pic)
     pic->opaque = ref;
     pic->age    = INT_MAX;
     pic->type   = FF_BUFFER_TYPE_USER;
+    pic->reordered_opaque = codec->reordered_opaque;
+    if(codec->pkt) pic->pkt_pts = codec->pkt->pts;
+    else           pic->pkt_pts = AV_NOPTS_VALUE;
     return 0;
 }
 
 static void input_release_buffer(AVCodecContext *codec, AVFrame *pic)
 {
     memset(pic->data, 0, sizeof(pic->data));
-    avfilter_unref_pic(pic->opaque);
+    avfilter_unref_buffer(pic->opaque);
+}
+
+static int input_reget_buffer(AVCodecContext *codec, AVFrame *pic)
+{
+    AVFilterBufferRef *ref = pic->opaque;
+
+    if (pic->data[0] == NULL) {
+        pic->buffer_hints |= FF_BUFFER_HINTS_READABLE;
+        return codec->get_buffer(codec, pic);
+    }
+
+    if ((codec->width != ref->video->w) || (codec->height != ref->video->h) ||
+        (codec->pix_fmt != ref->format)) {
+        av_log(codec, AV_LOG_ERROR, "Picture properties changed.\n");
+        return -1;
+    }
+
+    pic->reordered_opaque = codec->reordered_opaque;
+    if(codec->pkt) pic->pkt_pts = codec->pkt->pts;
+    else           pic->pkt_pts = AV_NOPTS_VALUE;
+    return 0;
 }
 
 static int input_init(AVFilterContext *ctx, const char *args, void *opaque)
@@ -1624,6 +1659,8 @@ static int input_init(AVFilterContext *ctx, const char *args, void *opaque)
         priv->use_dr1 = 1;
         codec->get_buffer     = input_get_buffer;
         codec->release_buffer = input_release_buffer;
+        codec->reget_buffer   = input_reget_buffer;
+        codec->thread_safe_callbacks = 1;
     }
 
     priv->frame = avcodec_alloc_frame();
@@ -1640,7 +1677,7 @@ static void input_uninit(AVFilterContext *ctx)
 static int input_request_frame(AVFilterLink *link)
 {
     FilterPriv *priv = link->src->priv;
-    AVFilterPicRef *picref;
+    AVFilterBufferRef *picref;
     int64_t pts = 0;
     AVPacket pkt;
     int ret;
@@ -1651,17 +1688,18 @@ static int input_request_frame(AVFilterLink *link)
         return -1;
 
     if(priv->use_dr1) {
-        picref = avfilter_ref_pic(priv->frame->opaque, ~0);
+        picref = avfilter_ref_buffer(priv->frame->opaque, ~0);
     } else {
         picref = avfilter_get_video_buffer(link, AV_PERM_WRITE, link->w, link->h);
-        av_picture_copy((AVPicture *)&picref->data, (AVPicture *)priv->frame,
-                        picref->pic->format, link->w, link->h);
+        av_image_copy(picref->data, picref->linesize,
+                      priv->frame->data, priv->frame->linesize,
+                      picref->format, link->w, link->h);
     }
     av_free_packet(&pkt);
 
     picref->pts = pts;
     picref->pos = pkt.pos;
-    picref->pixel_aspect = priv->is->video_st->codec->sample_aspect_ratio;
+    picref->video->pixel_aspect = priv->is->video_st->codec->sample_aspect_ratio;
     avfilter_start_frame(link, picref);
     avfilter_draw_slice(link, 0, link->h, 1);
     avfilter_end_frame(link);
@@ -1687,6 +1725,7 @@ static int input_config_props(AVFilterLink *link)
 
     link->w = c->width;
     link->h = c->height;
+    link->time_base = priv->is->video_st->time_base;
 
     return 0;
 }
@@ -1710,113 +1749,97 @@ static AVFilter input_filter =
                                   { .name = NULL }},
 };
 
-static void output_end_frame(AVFilterLink *link)
-{
-}
-
-static int output_query_formats(AVFilterContext *ctx)
-{
-    enum PixelFormat pix_fmts[] = { PIX_FMT_YUV420P, PIX_FMT_NONE };
-
-    avfilter_set_common_formats(ctx, avfilter_make_format_list(pix_fmts));
-    return 0;
-}
-
-static int get_filtered_video_frame(AVFilterContext *ctx, AVFrame *frame,
-                                    int64_t *pts, int64_t *pos)
-{
-    AVFilterPicRef *pic;
-
-    if(avfilter_request_frame(ctx->inputs[0]))
-        return -1;
-    if(!(pic = ctx->inputs[0]->cur_pic))
-        return -1;
-    ctx->inputs[0]->cur_pic = NULL;
-
-    frame->opaque = pic;
-    *pts          = pic->pts;
-    *pos          = pic->pos;
-
-    memcpy(frame->data,     pic->data,     sizeof(frame->data));
-    memcpy(frame->linesize, pic->linesize, sizeof(frame->linesize));
-
-    return 1;
-}
-
-static AVFilter output_filter =
-{
-    .name      = "ffplay_output",
-
-    .query_formats = output_query_formats,
-
-    .inputs    = (AVFilterPad[]) {{ .name          = "default",
-                                    .type          = AVMEDIA_TYPE_VIDEO,
-                                    .end_frame     = output_end_frame,
-                                    .min_perms     = AV_PERM_READ, },
-                                  { .name = NULL }},
-    .outputs   = (AVFilterPad[]) {{ .name = NULL }},
-};
-#endif  /* CONFIG_AVFILTER */
-
-static int video_thread(void *arg)
+static int configure_video_filters(AVFilterGraph *graph, VideoState *is, const char *vfilters)
 {
-    VideoState *is = arg;
-    AVFrame *frame= avcodec_alloc_frame();
-    int64_t pts_int;
-    double pts;
+    char sws_flags_str[128];
     int ret;
-
-#if CONFIG_AVFILTER
-    int64_t pos;
+    FFSinkContext ffsink_ctx = { .pix_fmt = PIX_FMT_YUV420P };
     AVFilterContext *filt_src = NULL, *filt_out = NULL;
-    AVFilterGraph *graph = av_mallocz(sizeof(AVFilterGraph));
-    graph->scale_sws_opts = av_strdup("sws_flags=bilinear");
-
-    if(!(filt_src = avfilter_open(&input_filter,  "src")))   goto the_end;
-    if(!(filt_out = avfilter_open(&output_filter, "out")))   goto the_end;
-
-    if(avfilter_init_filter(filt_src, NULL, is))             goto the_end;
-    if(avfilter_init_filter(filt_out, NULL, frame))          goto the_end;
+    snprintf(sws_flags_str, sizeof(sws_flags_str), "flags=%d", sws_flags);
+    graph->scale_sws_opts = av_strdup(sws_flags_str);
 
+    if ((ret = avfilter_graph_create_filter(&filt_src, &input_filter, "src",
+                                            NULL, is, graph)) < 0)
+        goto the_end;
+    if ((ret = avfilter_graph_create_filter(&filt_out, &ffsink, "out",
+                                            NULL, &ffsink_ctx, graph)) < 0)
+        goto the_end;
 
     if(vfilters) {
         AVFilterInOut *outputs = av_malloc(sizeof(AVFilterInOut));
         AVFilterInOut *inputs  = av_malloc(sizeof(AVFilterInOut));
 
         outputs->name    = av_strdup("in");
-        outputs->filter  = filt_src;
+        outputs->filter_ctx = filt_src;
         outputs->pad_idx = 0;
         outputs->next    = NULL;
 
         inputs->name    = av_strdup("out");
-        inputs->filter  = filt_out;
+        inputs->filter_ctx = filt_out;
         inputs->pad_idx = 0;
         inputs->next    = NULL;
 
-        if (avfilter_graph_parse(graph, vfilters, inputs, outputs, NULL) < 0)
+        if ((ret = avfilter_graph_parse(graph, vfilters, inputs, outputs, NULL)) < 0)
             goto the_end;
         av_freep(&vfilters);
     } else {
-        if(avfilter_link(filt_src, 0, filt_out, 0) < 0)          goto the_end;
+        if ((ret = avfilter_link(filt_src, 0, filt_out, 0)) < 0)
+            goto the_end;
     }
-    avfilter_graph_add_filter(graph, filt_src);
-    avfilter_graph_add_filter(graph, filt_out);
 
-    if(avfilter_graph_check_validity(graph, NULL))           goto the_end;
-    if(avfilter_graph_config_formats(graph, NULL))           goto the_end;
-    if(avfilter_graph_config_links(graph, NULL))             goto the_end;
+    if ((ret = avfilter_graph_config(graph, NULL)) < 0)
+        goto the_end;
 
     is->out_video_filter = filt_out;
+the_end:
+    return ret;
+}
+
+#endif  /* CONFIG_AVFILTER */
+
+static int video_thread(void *arg)
+{
+    VideoState *is = arg;
+    AVFrame *frame= avcodec_alloc_frame();
+    int64_t pts_int;
+    double pts;
+    int ret;
+
+#if CONFIG_AVFILTER
+    AVFilterGraph *graph = avfilter_graph_alloc();
+    AVFilterContext *filt_out = NULL;
+    int64_t pos;
+
+    if ((ret = configure_video_filters(graph, is, vfilters)) < 0)
+        goto the_end;
+    filt_out = is->out_video_filter;
 #endif
 
     for(;;) {
 #if !CONFIG_AVFILTER
         AVPacket pkt;
+#else
+        AVFilterBufferRef *picref;
+        AVRational tb;
 #endif
         while (is->paused && !is->videoq.abort_request)
             SDL_Delay(10);
 #if CONFIG_AVFILTER
-        ret = get_filtered_video_frame(filt_out, frame, &pts_int, &pos);
+        ret = get_filtered_video_frame(filt_out, frame, &picref, &tb);
+        if (picref) {
+            pts_int = picref->pts;
+            pos     = picref->pos;
+            frame->opaque = picref;
+        }
+
+        if (av_cmp_q(tb, is->video_st->time_base)) {
+            av_unused int64_t pts1 = pts_int;
+            pts_int = av_rescale_q(pts_int, tb, is->video_st->time_base);
+            av_dlog(NULL, "video_thread(): "
+                    "tb:%d/%d pts:%"PRId64" -> tb:%d/%d pts:%"PRId64"\n",
+                    tb.num, tb.den, pts1,
+                    is->video_st->time_base.num, is->video_st->time_base.den, pts_int);
+        }
 #else
         ret = get_video_frame(is, frame, &pts_int, &pkt);
 #endif
@@ -1843,8 +1866,7 @@ static int video_thread(void *arg)
     }
  the_end:
 #if CONFIG_AVFILTER
-    avfilter_graph_destroy(graph);
-    av_freep(&graph);
+    avfilter_graph_free(&graph);
 #endif
     av_free(frame);
     return 0;
@@ -2053,12 +2075,12 @@ static int audio_decode_frame(VideoState *is, double *pts_ptr)
             if (dec->sample_fmt != is->audio_src_fmt) {
                 if (is->reformat_ctx)
                     av_audio_convert_free(is->reformat_ctx);
-                is->reformat_ctx= av_audio_convert_alloc(SAMPLE_FMT_S16, 1,
+                is->reformat_ctx= av_audio_convert_alloc(AV_SAMPLE_FMT_S16, 1,
                                                          dec->sample_fmt, 1, NULL, 0);
                 if (!is->reformat_ctx) {
                     fprintf(stderr, "Cannot convert %s sample format to %s sample format\n",
-                        avcodec_get_sample_fmt_name(dec->sample_fmt),
-                        avcodec_get_sample_fmt_name(SAMPLE_FMT_S16));
+                        av_get_sample_fmt_name(dec->sample_fmt),
+                        av_get_sample_fmt_name(AV_SAMPLE_FMT_S16));
                         break;
                 }
                 is->audio_src_fmt= dec->sample_fmt;
@@ -2067,7 +2089,7 @@ static int audio_decode_frame(VideoState *is, double *pts_ptr)
             if (is->reformat_ctx) {
                 const void *ibuf[6]= {is->audio_buf1};
                 void *obuf[6]= {is->audio_buf2};
-                int istride[6]= {av_get_bits_per_sample_format(dec->sample_fmt)/8};
+                int istride[6]= {av_get_bits_per_sample_fmt(dec->sample_fmt)/8};
                 int ostride[6]= {2};
                 int len= data_size/istride[0];
                 if (av_audio_convert(is->reformat_ctx, obuf, ostride, ibuf, istride, len)<0) {
@@ -2204,9 +2226,9 @@ static int stream_component_open(VideoState *is, int stream_index)
     avctx->skip_loop_filter= skip_loop_filter;
     avctx->error_recognition= error_recognition;
     avctx->error_concealment= error_concealment;
-    avcodec_thread_init(avctx, thread_count);
+    avctx->thread_count= thread_count;
 
-    set_context_opts(avctx, avcodec_opts[avctx->codec_type], 0);
+    set_context_opts(avctx, avcodec_opts[avctx->codec_type], 0, codec);
 
     if (!codec ||
         avcodec_open(avctx, codec) < 0)
@@ -2226,7 +2248,7 @@ static int stream_component_open(VideoState *is, int stream_index)
             return -1;
         }
         is->audio_hw_buf_size = spec.size;
-        is->audio_src_fmt= SAMPLE_FMT_S16;
+        is->audio_src_fmt= AV_SAMPLE_FMT_S16;
     }
 
     ic->streams[stream_index]->discard = AVDISCARD_DEFAULT;
@@ -2358,8 +2380,6 @@ static int decode_thread(void *arg)
     AVFormatContext *ic;
     int err, i, ret;
     int st_index[AVMEDIA_TYPE_NB];
-    int st_count[AVMEDIA_TYPE_NB]={0};
-    int st_best_packet_count[AVMEDIA_TYPE_NB];
     AVPacket pkt1, *pkt = &pkt1;
     AVFormatParameters params, *ap = &params;
     int eof=0;
@@ -2368,13 +2388,12 @@ static int decode_thread(void *arg)
     ic = avformat_alloc_context();
 
     memset(st_index, -1, sizeof(st_index));
-    memset(st_best_packet_count, -1, sizeof(st_best_packet_count));
     is->video_stream = -1;
     is->audio_stream = -1;
     is->subtitle_stream = -1;
 
     global_video_state = is;
-    url_set_interrupt_cb(decode_interrupt_cb);
+    avio_set_interrupt_cb(decode_interrupt_cb);
 
     memset(ap, 0, sizeof(*ap));
 
@@ -2384,7 +2403,7 @@ static int decode_thread(void *arg)
     ap->time_base= (AVRational){1, 25};
     ap->pix_fmt = frame_pix_fmt;
 
-    set_context_opts(ic, avformat_opts, AV_OPT_FLAG_DECODING_PARAM);
+    set_context_opts(ic, avformat_opts, AV_OPT_FLAG_DECODING_PARAM, NULL);
 
     err = av_open_input_file(&ic, is->filename, is->iformat, 0, ap);
     if (err < 0) {
@@ -2424,35 +2443,28 @@ static int decode_thread(void *arg)
         }
     }
 
-    for(i = 0; i < ic->nb_streams; i++) {
-        AVStream *st= ic->streams[i];
-        AVCodecContext *avctx = st->codec;
+    for (i = 0; i < ic->nb_streams; i++)
         ic->streams[i]->discard = AVDISCARD_ALL;
-        if(avctx->codec_type >= (unsigned)AVMEDIA_TYPE_NB)
-            continue;
-        if(st_count[avctx->codec_type]++ != wanted_stream[avctx->codec_type] && wanted_stream[avctx->codec_type] >= 0)
-            continue;
-
-        if(st_best_packet_count[avctx->codec_type] >= st->codec_info_nb_frames)
-            continue;
-        st_best_packet_count[avctx->codec_type]= st->codec_info_nb_frames;
-
-        switch(avctx->codec_type) {
-        case AVMEDIA_TYPE_AUDIO:
-            if (!audio_disable)
-                st_index[AVMEDIA_TYPE_AUDIO] = i;
-            break;
-        case AVMEDIA_TYPE_VIDEO:
-        case AVMEDIA_TYPE_SUBTITLE:
-            if (!video_disable)
-                st_index[avctx->codec_type] = i;
-            break;
-        default:
-            break;
-        }
-    }
+    if (!video_disable)
+        st_index[AVMEDIA_TYPE_VIDEO] =
+            av_find_best_stream(ic, AVMEDIA_TYPE_VIDEO,
+                                wanted_stream[AVMEDIA_TYPE_VIDEO], -1, NULL, 0);
+    if (!audio_disable)
+        st_index[AVMEDIA_TYPE_AUDIO] =
+            av_find_best_stream(ic, AVMEDIA_TYPE_AUDIO,
+                                wanted_stream[AVMEDIA_TYPE_AUDIO],
+                                st_index[AVMEDIA_TYPE_VIDEO],
+                                NULL, 0);
+    if (!video_disable)
+        st_index[AVMEDIA_TYPE_SUBTITLE] =
+            av_find_best_stream(ic, AVMEDIA_TYPE_SUBTITLE,
+                                wanted_stream[AVMEDIA_TYPE_SUBTITLE],
+                                (st_index[AVMEDIA_TYPE_AUDIO] >= 0 ?
+                                 st_index[AVMEDIA_TYPE_AUDIO] :
+                                 st_index[AVMEDIA_TYPE_VIDEO]),
+                                NULL, 0);
     if (show_status) {
-        dump_format(ic, 0, is->filename, 0);
+        av_dump_format(ic, 0, is->filename, 0);
     }
 
     /* open the streams */
@@ -2535,7 +2547,7 @@ static int decode_thread(void *arg)
             SDL_Delay(10);
             continue;
         }
-        if(url_feof(ic->pb) || eof) {
+        if(eof) {
             if(is->video_stream >= 0){
                 av_init_packet(pkt);
                 pkt->data=NULL;
@@ -2556,9 +2568,9 @@ static int decode_thread(void *arg)
         }
         ret = av_read_frame(ic, pkt);
         if (ret < 0) {
-            if (ret == AVERROR_EOF)
+            if (ret == AVERROR_EOF || (ic->pb && ic->pb->eof_reached))
                 eof=1;
-            if (url_ferror(ic->pb))
+            if (ic->pb && ic->pb->error)
                 break;
             SDL_Delay(100); /* wait for user event */
             continue;
@@ -2600,7 +2612,7 @@ static int decode_thread(void *arg)
         av_close_input_file(is->ic);
         is->ic = NULL; /* safety */
     }
-    url_set_interrupt_cb(NULL);
+    avio_set_interrupt_cb(NULL);
 
     if (ret != 0) {
         SDL_Event event;
@@ -2640,40 +2652,6 @@ static VideoState *stream_open(const char *filename, AVInputFormat *iformat)
     return is;
 }
 
-static void stream_close(VideoState *is)
-{
-    VideoPicture *vp;
-    int i;
-    /* XXX: use a special url_shutdown call to abort parse cleanly */
-    is->abort_request = 1;
-    SDL_WaitThread(is->parse_tid, NULL);
-    SDL_WaitThread(is->refresh_tid, NULL);
-
-    /* free all pictures */
-    for(i=0;i<VIDEO_PICTURE_QUEUE_SIZE; i++) {
-        vp = &is->pictq[i];
-#if CONFIG_AVFILTER
-        if (vp->picref) {
-            avfilter_unref_pic(vp->picref);
-            vp->picref = NULL;
-        }
-#endif
-        if (vp->bmp) {
-            SDL_FreeYUVOverlay(vp->bmp);
-            vp->bmp = NULL;
-        }
-    }
-    SDL_DestroyMutex(is->pictq_mutex);
-    SDL_DestroyCond(is->pictq_cond);
-    SDL_DestroyMutex(is->subpq_mutex);
-    SDL_DestroyCond(is->subpq_cond);
-#if !CONFIG_AVFILTER
-    if (is->img_convert_ctx)
-        sws_freeContext(is->img_convert_ctx);
-#endif
-    av_free(is);
-}
-
 static void stream_cycle_channel(VideoState *is, int codec_type)
 {
     AVFormatContext *ic = is->ic;
@@ -2751,26 +2729,6 @@ static void step_to_next_frame(void)
     step = 1;
 }
 
-static void do_exit(void)
-{
-    int i;
-    if (cur_stream) {
-        stream_close(cur_stream);
-        cur_stream = NULL;
-    }
-    for (i = 0; i < AVMEDIA_TYPE_NB; i++)
-        av_free(avcodec_opts[i]);
-    av_free(avformat_opts);
-    av_free(sws_opts);
-#if CONFIG_AVFILTER
-    avfilter_uninit();
-#endif
-    if (show_status)
-        printf("\n");
-    SDL_Quit();
-    exit(0);
-}
-
 static void toggle_audio_display(void)
 {
     if (cur_stream) {
@@ -2794,6 +2752,10 @@ static void event_loop(void)
         SDL_WaitEvent(&event);
         switch(event.type) {
         case SDL_KEYDOWN:
+            if (exit_on_keydown) {
+                do_exit();
+                break;
+            }
             switch(event.key.keysym.sym) {
             case SDLK_ESCAPE:
             case SDLK_q:
@@ -2843,7 +2805,7 @@ static void event_loop(void)
                         }else if(cur_stream->audio_stream >= 0 && cur_stream->audio_pkt.pos>=0){
                             pos= cur_stream->audio_pkt.pos;
                         }else
-                            pos = url_ftell(cur_stream->ic->pb);
+                            pos = avio_tell(cur_stream->ic->pb);
                         if (cur_stream->ic->bit_rate)
                             incr *= cur_stream->ic->bit_rate / 8.0;
                         else
@@ -2862,6 +2824,10 @@ static void event_loop(void)
             }
             break;
         case SDL_MOUSEBUTTONDOWN:
+            if (exit_on_mousedown) {
+                do_exit();
+                break;
+            }
         case SDL_MOUSEMOTION:
             if(event.type ==SDL_MOUSEBUTTONDOWN){
                 x= event.button.x;
@@ -2872,7 +2838,7 @@ static void event_loop(void)
             }
             if (cur_stream) {
                 if(seek_by_bytes || cur_stream->ic->duration<=0){
-                    uint64_t size=  url_fsize(cur_stream->ic->pb);
+                    uint64_t size=  avio_size(cur_stream->ic->pb);
                     stream_seek(cur_stream, size*x/cur_stream->width, 0, 1);
                 }else{
                     int64_t ts;
@@ -2924,7 +2890,7 @@ static void event_loop(void)
 
 static void opt_frame_size(const char *arg)
 {
-    if (av_parse_video_frame_size(&frame_width, &frame_height, arg) < 0) {
+    if (av_parse_video_size(&frame_width, &frame_height, arg) < 0) {
         fprintf(stderr, "Incorrect frame size\n");
         exit(1);
     }
@@ -3043,11 +3009,13 @@ static const OptionDef options[] = {
     { "sync", HAS_ARG | OPT_FUNC2 | OPT_EXPERT, {(void*)opt_sync}, "set audio-video sync. type (type=audio/video/ext)", "type" },
     { "threads", HAS_ARG | OPT_FUNC2 | OPT_EXPERT, {(void*)opt_thread_count}, "thread count", "count" },
     { "autoexit", OPT_BOOL | OPT_EXPERT, {(void*)&autoexit}, "exit at the end", "" },
+    { "exitonkeydown", OPT_BOOL | OPT_EXPERT, {(void*)&exit_on_keydown}, "exit on key down", "" },
+    { "exitonmousedown", OPT_BOOL | OPT_EXPERT, {(void*)&exit_on_mousedown}, "exit on mouse down", "" },
     { "loop", OPT_INT | HAS_ARG | OPT_EXPERT, {(void*)&loop}, "set number of times the playback shall be looped", "loop count" },
     { "framedrop", OPT_BOOL | OPT_EXPERT, {(void*)&framedrop}, "drop frames when cpu is too slow", "" },
     { "window_title", OPT_STRING | HAS_ARG, {(void*)&window_title}, "set window title", "window title" },
 #if CONFIG_AVFILTER
-    { "vfilters", OPT_STRING | HAS_ARG, {(void*)&vfilters}, "video filters", "filter list" },
+    { "vf", OPT_STRING | HAS_ARG, {(void*)&vfilters}, "video filters", "filter list" },
 #endif
     { "rdftspeed", OPT_INT | HAS_ARG| OPT_AUDIO | OPT_EXPERT, {(void*)&rdftspeed}, "rdft speed", "msecs" },
     { "default", OPT_FUNC2 | HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
@@ -3063,11 +3031,23 @@ static void show_usage(void)
 
 static void show_help(void)
 {
+    av_log_set_callback(log_callback_help);
     show_usage();
     show_help_options(options, "Main options:\n",
                       OPT_EXPERT, 0);
     show_help_options(options, "\nAdvanced options:\n",
                       OPT_EXPERT, OPT_EXPERT);
+    printf("\n");
+    av_opt_show2(avcodec_opts[0], NULL,
+                 AV_OPT_FLAG_DECODING_PARAM, 0);
+    printf("\n");
+    av_opt_show2(avformat_opts, NULL,
+                 AV_OPT_FLAG_DECODING_PARAM, 0);
+#if !CONFIG_AVFILTER
+    printf("\n");
+    av_opt_show2(sws_opts, NULL,
+                 AV_OPT_FLAG_ENCODING_PARAM, 0);
+#endif
     printf("\nWhile playing:\n"
            "q, ESC              quit\n"
            "f                   toggle full screen\n"
@@ -3098,7 +3078,9 @@ static void opt_input_file(const char *filename)
 /* Called from the main */
 int main(int argc, char **argv)
 {
-    int flags, i;
+    int flags;
+
+    av_log_set_flags(AV_LOG_SKIP_REPEATED);
 
     /* register all codecs, demux and protocols */
     avcodec_register_all();
@@ -3110,13 +3092,7 @@ int main(int argc, char **argv)
 #endif
     av_register_all();
 
-    for(i=0; i<AVMEDIA_TYPE_NB; i++){
-        avcodec_opts[i]= avcodec_alloc_context2(i);
-    }
-    avformat_opts = avformat_alloc_context();
-#if !CONFIG_AVFILTER
-    sws_opts = sws_getContext(16,16,0, 16,16,0, sws_flags, NULL,NULL,NULL);
-#endif
+    init_opts();
 
     show_banner();
 
diff --git a/ffpresets/libx264-default.ffpreset b/ffpresets/libx264-default.ffpreset
deleted file mode 100644
index 75191e2..0000000
--- a/ffpresets/libx264-default.ffpreset
+++ /dev/null
@@ -1,22 +0,0 @@
-coder=1
-flags=+loop
-cmp=+chroma
-partitions=+parti8x8+parti4x4+partp8x8+partb8x8
-me_method=hex
-subq=7
-me_range=16
-g=250
-keyint_min=25
-sc_threshold=40
-i_qfactor=0.71
-b_strategy=1
-qcomp=0.6
-qmin=10
-qmax=51
-qdiff=4
-bf=3
-refs=3
-directpred=1
-trellis=1
-flags2=+mixed_refs+wpred+dct8x8+fastpskip
-wpredp=2
diff --git a/ffpresets/libx264-fast.ffpreset b/ffpresets/libx264-fast.ffpreset
index cac6534..0fc1f22 100644
--- a/ffpresets/libx264-fast.ffpreset
+++ b/ffpresets/libx264-fast.ffpreset
@@ -11,8 +11,8 @@ sc_threshold=40
 i_qfactor=0.71
 b_strategy=1
 qcomp=0.6
-qmin=10
-qmax=51
+qmin=0
+qmax=69
 qdiff=4
 bf=3
 refs=2
diff --git a/ffpresets/libx264-fast_firstpass.ffpreset b/ffpresets/libx264-fast_firstpass.ffpreset
index 65ec011..cdcbbbf 100644
--- a/ffpresets/libx264-fast_firstpass.ffpreset
+++ b/ffpresets/libx264-fast_firstpass.ffpreset
@@ -11,8 +11,8 @@ sc_threshold=40
 i_qfactor=0.71
 b_strategy=1
 qcomp=0.6
-qmin=10
-qmax=51
+qmin=0
+qmax=69
 qdiff=4
 bf=3
 refs=1
diff --git a/ffpresets/libx264-faster.ffpreset b/ffpresets/libx264-faster.ffpreset
index a32eed3..3156cd8 100644
--- a/ffpresets/libx264-faster.ffpreset
+++ b/ffpresets/libx264-faster.ffpreset
@@ -11,8 +11,8 @@ sc_threshold=40
 i_qfactor=0.71
 b_strategy=1
 qcomp=0.6
-qmin=10
-qmax=51
+qmin=0
+qmax=69
 qdiff=4
 bf=3
 refs=2
diff --git a/ffpresets/libx264-faster_firstpass.ffpreset b/ffpresets/libx264-faster_firstpass.ffpreset
index c777eb4..9bcf18a 100644
--- a/ffpresets/libx264-faster_firstpass.ffpreset
+++ b/ffpresets/libx264-faster_firstpass.ffpreset
@@ -11,8 +11,8 @@ sc_threshold=40
 i_qfactor=0.71
 b_strategy=1
 qcomp=0.6
-qmin=10
-qmax=51
+qmin=0
+qmax=69
 qdiff=4
 bf=3
 refs=1
diff --git a/ffpresets/libx264-fastfirstpass.ffpreset b/ffpresets/libx264-fastfirstpass.ffpreset
deleted file mode 100644
index 7278f77..0000000
--- a/ffpresets/libx264-fastfirstpass.ffpreset
+++ /dev/null
@@ -1,22 +0,0 @@
-coder=1
-flags=+loop
-cmp=+chroma
-partitions=-parti8x8-parti4x4-partp8x8-partp4x4-partb8x8
-me_method=dia
-subq=2
-me_range=16
-g=250
-keyint_min=25
-sc_threshold=40
-i_qfactor=0.71
-b_strategy=1
-qcomp=0.6
-qmin=10
-qmax=51
-qdiff=4
-bf=3
-refs=1
-directpred=3
-trellis=0
-flags2=-bpyramid-wpred-mixed_refs-dct8x8+fastpskip
-wpredp=2
diff --git a/ffpresets/libx264-hq.ffpreset b/ffpresets/libx264-hq.ffpreset
deleted file mode 100644
index 9c14d8f..0000000
--- a/ffpresets/libx264-hq.ffpreset
+++ /dev/null
@@ -1,22 +0,0 @@
-coder=1
-flags=+loop
-cmp=+chroma
-partitions=+parti8x8+parti4x4+partp8x8+partb8x8
-me_method=umh
-subq=8
-me_range=16
-g=250
-keyint_min=25
-sc_threshold=40
-i_qfactor=0.71
-b_strategy=2
-qcomp=0.6
-qmin=10
-qmax=51
-qdiff=4
-bf=3
-refs=4
-directpred=3
-trellis=1
-flags2=+wpred+mixed_refs+dct8x8+fastpskip
-wpredp=2
diff --git a/ffpresets/libx264-lossless_fast.ffpreset b/ffpresets/libx264-lossless_fast.ffpreset
index ea08d3c..b7696b5 100644
--- a/ffpresets/libx264-lossless_fast.ffpreset
+++ b/ffpresets/libx264-lossless_fast.ffpreset
@@ -11,8 +11,8 @@ sc_threshold=40
 i_qfactor=0.71
 b_strategy=1
 qcomp=0.6
-qmin=10
-qmax=51
+qmin=0
+qmax=69
 qdiff=4
 directpred=1
 flags2=+fastpskip
diff --git a/ffpresets/libx264-lossless_max.ffpreset b/ffpresets/libx264-lossless_max.ffpreset
index 8c049c9..75c387f 100644
--- a/ffpresets/libx264-lossless_max.ffpreset
+++ b/ffpresets/libx264-lossless_max.ffpreset
@@ -11,8 +11,8 @@ sc_threshold=40
 i_qfactor=0.71
 b_strategy=1
 qcomp=0.6
-qmin=10
-qmax=51
+qmin=0
+qmax=69
 qdiff=4
 refs=16
 directpred=1
diff --git a/ffpresets/libx264-lossless_medium.ffpreset b/ffpresets/libx264-lossless_medium.ffpreset
index 558be6c..116e334 100644
--- a/ffpresets/libx264-lossless_medium.ffpreset
+++ b/ffpresets/libx264-lossless_medium.ffpreset
@@ -11,8 +11,8 @@ sc_threshold=40
 i_qfactor=0.71
 b_strategy=1
 qcomp=0.6
-qmin=10
-qmax=51
+qmin=0
+qmax=69
 qdiff=4
 directpred=1
 flags2=+fastpskip
diff --git a/ffpresets/libx264-lossless_slow.ffpreset b/ffpresets/libx264-lossless_slow.ffpreset
index ff641cf..0d496f6 100644
--- a/ffpresets/libx264-lossless_slow.ffpreset
+++ b/ffpresets/libx264-lossless_slow.ffpreset
@@ -11,8 +11,8 @@ sc_threshold=40
 i_qfactor=0.71
 b_strategy=1
 qcomp=0.6
-qmin=10
-qmax=51
+qmin=0
+qmax=69
 qdiff=4
 refs=2
 directpred=1
diff --git a/ffpresets/libx264-lossless_slower.ffpreset b/ffpresets/libx264-lossless_slower.ffpreset
index 854f74b..672e0cd 100644
--- a/ffpresets/libx264-lossless_slower.ffpreset
+++ b/ffpresets/libx264-lossless_slower.ffpreset
@@ -11,8 +11,8 @@ sc_threshold=40
 i_qfactor=0.71
 b_strategy=1
 qcomp=0.6
-qmin=10
-qmax=51
+qmin=0
+qmax=69
 qdiff=4
 refs=4
 directpred=1
diff --git a/ffpresets/libx264-lossless_ultrafast.ffpreset b/ffpresets/libx264-lossless_ultrafast.ffpreset
index 1c429f2..a2eda65 100644
--- a/ffpresets/libx264-lossless_ultrafast.ffpreset
+++ b/ffpresets/libx264-lossless_ultrafast.ffpreset
@@ -11,8 +11,8 @@ sc_threshold=40
 i_qfactor=0.71
 b_strategy=1
 qcomp=0.6
-qmin=10
-qmax=51
+qmin=0
+qmax=69
 qdiff=4
 directpred=1
 flags2=+fastpskip
diff --git a/ffpresets/libx264-max.ffpreset b/ffpresets/libx264-max.ffpreset
deleted file mode 100644
index 667ba85..0000000
--- a/ffpresets/libx264-max.ffpreset
+++ /dev/null
@@ -1,22 +0,0 @@
-coder=1
-flags=+loop
-cmp=+chroma
-partitions=+parti8x8+parti4x4+partp8x8+partp4x4+partb8x8
-me_method=tesa
-subq=10
-me_range=24
-g=250
-keyint_min=25
-sc_threshold=40
-i_qfactor=0.71
-b_strategy=2
-qcomp=0.6
-qmin=10
-qmax=51
-qdiff=4
-bf=3
-refs=16
-directpred=3
-trellis=2
-flags2=+wpred+mixed_refs+dct8x8-fastpskip
-wpredp=2
diff --git a/ffpresets/libx264-medium.ffpreset b/ffpresets/libx264-medium.ffpreset
index 039f1d6..3c90ec5 100644
--- a/ffpresets/libx264-medium.ffpreset
+++ b/ffpresets/libx264-medium.ffpreset
@@ -11,8 +11,8 @@ sc_threshold=40
 i_qfactor=0.71
 b_strategy=1
 qcomp=0.6
-qmin=10
-qmax=51
+qmin=0
+qmax=69
 qdiff=4
 bf=3
 refs=3
diff --git a/ffpresets/libx264-medium_firstpass.ffpreset b/ffpresets/libx264-medium_firstpass.ffpreset
index e415989..2ad0a9c 100644
--- a/ffpresets/libx264-medium_firstpass.ffpreset
+++ b/ffpresets/libx264-medium_firstpass.ffpreset
@@ -11,8 +11,8 @@ sc_threshold=40
 i_qfactor=0.71
 b_strategy=1
 qcomp=0.6
-qmin=10
-qmax=51
+qmin=0
+qmax=69
 qdiff=4
 bf=3
 refs=1
diff --git a/ffpresets/libx264-normal.ffpreset b/ffpresets/libx264-normal.ffpreset
deleted file mode 100644
index ee790b6..0000000
--- a/ffpresets/libx264-normal.ffpreset
+++ /dev/null
@@ -1,22 +0,0 @@
-coder=1
-flags=+loop
-cmp=+chroma
-partitions=+parti8x8+parti4x4+partp8x8+partb8x8
-me_method=hex
-subq=6
-me_range=16
-g=250
-keyint_min=25
-sc_threshold=40
-i_qfactor=0.71
-b_strategy=1
-qcomp=0.6
-qmin=10
-qmax=51
-qdiff=4
-bf=3
-refs=2
-directpred=3
-trellis=0
-flags2=+wpred+dct8x8+fastpskip
-wpredp=2
diff --git a/ffpresets/libx264-placebo.ffpreset b/ffpresets/libx264-placebo.ffpreset
index fae2222..9f4719f 100644
--- a/ffpresets/libx264-placebo.ffpreset
+++ b/ffpresets/libx264-placebo.ffpreset
@@ -11,8 +11,8 @@ sc_threshold=40
 i_qfactor=0.71
 b_strategy=2
 qcomp=0.6
-qmin=10
-qmax=51
+qmin=0
+qmax=69
 qdiff=4
 bf=16
 refs=16
diff --git a/ffpresets/libx264-placebo_firstpass.ffpreset b/ffpresets/libx264-placebo_firstpass.ffpreset
index fae2222..9f4719f 100644
--- a/ffpresets/libx264-placebo_firstpass.ffpreset
+++ b/ffpresets/libx264-placebo_firstpass.ffpreset
@@ -11,8 +11,8 @@ sc_threshold=40
 i_qfactor=0.71
 b_strategy=2
 qcomp=0.6
-qmin=10
-qmax=51
+qmin=0
+qmax=69
 qdiff=4
 bf=16
 refs=16
diff --git a/ffpresets/libx264-slow.ffpreset b/ffpresets/libx264-slow.ffpreset
index 0f3f4d4..dabe0ae 100644
--- a/ffpresets/libx264-slow.ffpreset
+++ b/ffpresets/libx264-slow.ffpreset
@@ -11,8 +11,8 @@ sc_threshold=40
 i_qfactor=0.71
 b_strategy=2
 qcomp=0.6
-qmin=10
-qmax=51
+qmin=0
+qmax=69
 qdiff=4
 bf=3
 refs=5
diff --git a/ffpresets/libx264-slow_firstpass.ffpreset b/ffpresets/libx264-slow_firstpass.ffpreset
index 89e74e4..4af64db 100644
--- a/ffpresets/libx264-slow_firstpass.ffpreset
+++ b/ffpresets/libx264-slow_firstpass.ffpreset
@@ -11,8 +11,8 @@ sc_threshold=40
 i_qfactor=0.71
 b_strategy=2
 qcomp=0.6
-qmin=10
-qmax=51
+qmin=0
+qmax=69
 qdiff=4
 bf=3
 refs=1
diff --git a/ffpresets/libx264-slower.ffpreset b/ffpresets/libx264-slower.ffpreset
index f3a412c..239ee68 100644
--- a/ffpresets/libx264-slower.ffpreset
+++ b/ffpresets/libx264-slower.ffpreset
@@ -11,8 +11,8 @@ sc_threshold=40
 i_qfactor=0.71
 b_strategy=2
 qcomp=0.6
-qmin=10
-qmax=51
+qmin=0
+qmax=69
 qdiff=4
 bf=3
 refs=8
diff --git a/ffpresets/libx264-slower_firstpass.ffpreset b/ffpresets/libx264-slower_firstpass.ffpreset
index aa1eb1e..4b5b420 100644
--- a/ffpresets/libx264-slower_firstpass.ffpreset
+++ b/ffpresets/libx264-slower_firstpass.ffpreset
@@ -11,8 +11,8 @@ sc_threshold=40
 i_qfactor=0.71
 b_strategy=2
 qcomp=0.6
-qmin=10
-qmax=51
+qmin=0
+qmax=69
 qdiff=4
 bf=3
 refs=1
diff --git a/ffpresets/libx264-slowfirstpass.ffpreset b/ffpresets/libx264-slowfirstpass.ffpreset
deleted file mode 100644
index fe07331..0000000
--- a/ffpresets/libx264-slowfirstpass.ffpreset
+++ /dev/null
@@ -1,22 +0,0 @@
-coder=1
-flags=+loop
-cmp=+chroma
-partitions=+parti8x8+parti4x4+partp8x8+partb8x8
-me_method=hex
-subq=6
-me_range=16
-g=250
-keyint_min=25
-sc_threshold=40
-i_qfactor=0.71
-b_strategy=2
-qcomp=0.6
-qmin=10
-qmax=51
-qdiff=4
-bf=3
-refs=1
-directpred=3
-trellis=0
-flags2=+wpred+dct8x8+fastpskip
-wpredp=2
diff --git a/ffpresets/libx264-superfast.ffpreset b/ffpresets/libx264-superfast.ffpreset
index e2cb959..fb2ab8c 100644
--- a/ffpresets/libx264-superfast.ffpreset
+++ b/ffpresets/libx264-superfast.ffpreset
@@ -11,8 +11,8 @@ sc_threshold=40
 i_qfactor=0.71
 b_strategy=1
 qcomp=0.6
-qmin=10
-qmax=51
+qmin=0
+qmax=69
 qdiff=4
 bf=3
 refs=1
@@ -20,3 +20,4 @@ directpred=1
 trellis=0
 flags2=+bpyramid-mixed_refs+wpred+dct8x8+fastpskip-mbtree
 wpredp=0
+rc_lookahead=0
diff --git a/ffpresets/libx264-superfast_firstpass.ffpreset b/ffpresets/libx264-superfast_firstpass.ffpreset
index 5f44bea..55ff9a2 100644
--- a/ffpresets/libx264-superfast_firstpass.ffpreset
+++ b/ffpresets/libx264-superfast_firstpass.ffpreset
@@ -11,8 +11,8 @@ sc_threshold=40
 i_qfactor=0.71
 b_strategy=1
 qcomp=0.6
-qmin=10
-qmax=51
+qmin=0
+qmax=69
 qdiff=4
 bf=3
 refs=1
@@ -20,3 +20,4 @@ directpred=1
 trellis=0
 flags2=+bpyramid-mixed_refs+wpred-dct8x8+fastpskip-mbtree
 wpredp=0
+rc_lookahead=0
diff --git a/ffpresets/libx264-ultrafast.ffpreset b/ffpresets/libx264-ultrafast.ffpreset
index 70acb00..28dc0eb 100644
--- a/ffpresets/libx264-ultrafast.ffpreset
+++ b/ffpresets/libx264-ultrafast.ffpreset
@@ -11,8 +11,8 @@ sc_threshold=0
 i_qfactor=0.71
 b_strategy=0
 qcomp=0.6
-qmin=10
-qmax=51
+qmin=0
+qmax=69
 qdiff=4
 bf=0
 refs=1
@@ -21,3 +21,4 @@ trellis=0
 flags2=-bpyramid-mixed_refs-wpred-dct8x8+fastpskip-mbtree
 wpredp=0
 aq_mode=0
+rc_lookahead=0
diff --git a/ffpresets/libx264-ultrafast_firstpass.ffpreset b/ffpresets/libx264-ultrafast_firstpass.ffpreset
index 70acb00..28dc0eb 100644
--- a/ffpresets/libx264-ultrafast_firstpass.ffpreset
+++ b/ffpresets/libx264-ultrafast_firstpass.ffpreset
@@ -11,8 +11,8 @@ sc_threshold=0
 i_qfactor=0.71
 b_strategy=0
 qcomp=0.6
-qmin=10
-qmax=51
+qmin=0
+qmax=69
 qdiff=4
 bf=0
 refs=1
@@ -21,3 +21,4 @@ trellis=0
 flags2=-bpyramid-mixed_refs-wpred-dct8x8+fastpskip-mbtree
 wpredp=0
 aq_mode=0
+rc_lookahead=0
diff --git a/ffpresets/libx264-veryfast.ffpreset b/ffpresets/libx264-veryfast.ffpreset
index a29b115..bfa3d8f 100644
--- a/ffpresets/libx264-veryfast.ffpreset
+++ b/ffpresets/libx264-veryfast.ffpreset
@@ -11,12 +11,13 @@ sc_threshold=40
 i_qfactor=0.71
 b_strategy=1
 qcomp=0.6
-qmin=10
-qmax=51
+qmin=0
+qmax=69
 qdiff=4
 bf=3
 refs=1
 directpred=1
 trellis=0
-flags2=+bpyramid-mixed_refs+wpred+dct8x8+fastpskip-mbtree
+flags2=+bpyramid-mixed_refs+wpred+dct8x8+fastpskip
 wpredp=0
+rc_lookahead=10
diff --git a/ffpresets/libx264-veryfast_firstpass.ffpreset b/ffpresets/libx264-veryfast_firstpass.ffpreset
index bab5d9b..ac2332d 100644
--- a/ffpresets/libx264-veryfast_firstpass.ffpreset
+++ b/ffpresets/libx264-veryfast_firstpass.ffpreset
@@ -11,12 +11,13 @@ sc_threshold=40
 i_qfactor=0.71
 b_strategy=1
 qcomp=0.6
-qmin=10
-qmax=51
+qmin=0
+qmax=69
 qdiff=4
 bf=3
 refs=1
 directpred=1
 trellis=0
-flags2=+bpyramid-mixed_refs+wpred-dct8x8+fastpskip-mbtree
+flags2=+bpyramid-mixed_refs+wpred-dct8x8+fastpskip
 wpredp=0
+rc_lookahead=10
diff --git a/ffpresets/libx264-veryslow.ffpreset b/ffpresets/libx264-veryslow.ffpreset
index a060625..e07aeb8 100644
--- a/ffpresets/libx264-veryslow.ffpreset
+++ b/ffpresets/libx264-veryslow.ffpreset
@@ -11,8 +11,8 @@ sc_threshold=40
 i_qfactor=0.71
 b_strategy=2
 qcomp=0.6
-qmin=10
-qmax=51
+qmin=0
+qmax=69
 qdiff=4
 bf=8
 refs=16
diff --git a/ffpresets/libx264-veryslow_firstpass.ffpreset b/ffpresets/libx264-veryslow_firstpass.ffpreset
index 6e7079b..e17c04b 100644
--- a/ffpresets/libx264-veryslow_firstpass.ffpreset
+++ b/ffpresets/libx264-veryslow_firstpass.ffpreset
@@ -11,8 +11,8 @@ sc_threshold=40
 i_qfactor=0.71
 b_strategy=2
 qcomp=0.6
-qmin=10
-qmax=51
+qmin=0
+qmax=69
 qdiff=4
 bf=8
 refs=1
diff --git a/ffprobe.c b/ffprobe.c
index 7cb6167..6c672e7 100644
--- a/ffprobe.c
+++ b/ffprobe.c
@@ -1,21 +1,21 @@
 /*
- * FFprobe : Simple Media Prober based on the FFmpeg libraries
+ * FFprobe : Simple Media Prober based on the Libav libraries
  * Copyright (c) 2007-2010 Stefano Sabatini
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -32,9 +32,9 @@ const char program_name[] = "FFprobe";
 const int program_birth_year = 2007;
 
 static int do_show_format  = 0;
+static int do_show_packets = 0;
 static int do_show_streams = 0;
 
-static int convert_tags                 = 0;
 static int show_value_unit              = 0;
 static int use_value_prefix             = 0;
 static int use_byte_value_binary_prefix = 0;
@@ -101,6 +101,17 @@ static char *time_value_string(char *buf, int buf_size, int64_t val, const AVRat
     return buf;
 }
 
+static char *ts_value_string (char *buf, int buf_size, int64_t ts)
+{
+    if (ts == AV_NOPTS_VALUE) {
+        snprintf(buf, buf_size, "N/A");
+    } else {
+        snprintf(buf, buf_size, "%"PRId64, ts);
+    }
+
+    return buf;
+}
+
 static const char *media_type_string(enum AVMediaType media_type)
 {
     switch (media_type) {
@@ -113,6 +124,36 @@ static const char *media_type_string(enum AVMediaType media_type)
     }
 }
 
+static void show_packet(AVFormatContext *fmt_ctx, AVPacket *pkt)
+{
+    char val_str[128];
+    AVStream *st = fmt_ctx->streams[pkt->stream_index];
+
+    printf("[PACKET]\n");
+    printf("codec_type=%s\n"   , media_type_string(st->codec->codec_type));
+    printf("stream_index=%d\n" , pkt->stream_index);
+    printf("pts=%s\n"          , ts_value_string  (val_str, sizeof(val_str), pkt->pts));
+    printf("pts_time=%s\n"     , time_value_string(val_str, sizeof(val_str), pkt->pts, &st->time_base));
+    printf("dts=%s\n"          , ts_value_string  (val_str, sizeof(val_str), pkt->dts));
+    printf("dts_time=%s\n"     , time_value_string(val_str, sizeof(val_str), pkt->dts, &st->time_base));
+    printf("duration=%s\n"     , ts_value_string  (val_str, sizeof(val_str), pkt->duration));
+    printf("duration_time=%s\n", time_value_string(val_str, sizeof(val_str), pkt->duration, &st->time_base));
+    printf("size=%s\n"         , value_string     (val_str, sizeof(val_str), pkt->size, unit_byte_str));
+    printf("pos=%"PRId64"\n"   , pkt->pos);
+    printf("flags=%c\n"        , pkt->flags & AV_PKT_FLAG_KEY ? 'K' : '_');
+    printf("[/PACKET]\n");
+}
+
+static void show_packets(AVFormatContext *fmt_ctx)
+{
+    AVPacket pkt;
+
+    av_init_packet(&pkt);
+
+    while (!av_read_frame(fmt_ctx, &pkt))
+        show_packet(fmt_ctx, &pkt);
+}
+
 static void show_stream(AVFormatContext *fmt_ctx, int stream_idx)
 {
     AVStream *stream = fmt_ctx->streams[stream_idx];
@@ -120,7 +161,6 @@ static void show_stream(AVFormatContext *fmt_ctx, int stream_idx)
     AVCodec *dec;
     char val_str[128];
     AVMetadataTag *tag = NULL;
-    char a, b, c, d;
     AVRational display_aspect_ratio;
 
     printf("[STREAM]\n");
@@ -139,16 +179,9 @@ static void show_stream(AVFormatContext *fmt_ctx, int stream_idx)
         printf("codec_time_base=%d/%d\n", dec_ctx->time_base.num, dec_ctx->time_base.den);
 
         /* print AVI/FourCC tag */
-        a = dec_ctx->codec_tag     & 0xff;
-        b = dec_ctx->codec_tag>>8  & 0xff;
-        c = dec_ctx->codec_tag>>16 & 0xff;
-        d = dec_ctx->codec_tag>>24 & 0xff;
-        printf("codec_tag_string=");
-        if (isprint(a)) printf("%c", a); else printf("[%d]", a);
-        if (isprint(b)) printf("%c", b); else printf("[%d]", b);
-        if (isprint(c)) printf("%c", c); else printf("[%d]", c);
-        if (isprint(d)) printf("%c", d); else printf("[%d]", d);
-        printf("\ncodec_tag=0x%04x\n", dec_ctx->codec_tag);
+        av_get_codec_tag_string(val_str, sizeof(val_str), dec_ctx->codec_tag);
+        printf("codec_tag_string=%s\n", val_str);
+        printf("codec_tag=0x%04x\n", dec_ctx->codec_tag);
 
         switch (dec_ctx->codec_type) {
         case AVMEDIA_TYPE_VIDEO:
@@ -186,8 +219,6 @@ static void show_stream(AVFormatContext *fmt_ctx, int stream_idx)
     printf("r_frame_rate=%d/%d\n",         stream->r_frame_rate.num,   stream->r_frame_rate.den);
     printf("avg_frame_rate=%d/%d\n",       stream->avg_frame_rate.num, stream->avg_frame_rate.den);
     printf("time_base=%d/%d\n",            stream->time_base.num,      stream->time_base.den);
-    if (stream->language[0])
-        printf("language=%s\n",            stream->language);
     printf("start_time=%s\n",   time_value_string(val_str, sizeof(val_str), stream->start_time,
                                                   &stream->time_base));
     printf("duration=%s\n",     time_value_string(val_str, sizeof(val_str), stream->duration,
@@ -221,8 +252,6 @@ static void show_format(AVFormatContext *fmt_ctx)
     printf("bit_rate=%s\n",         value_string(val_str, sizeof(val_str), fmt_ctx->bit_rate,
                                                  unit_bit_per_second_str));
 
-    if (convert_tags)
-        av_metadata_conv(fmt_ctx, NULL, fmt_ctx->iformat->metadata_conv);
     while ((tag = av_metadata_get(fmt_ctx->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX)))
         printf("TAG:%s=%s\n", tag->key, tag->value);
 
@@ -235,6 +264,7 @@ static int open_input_file(AVFormatContext **fmt_ctx_ptr, const char *filename)
     AVFormatContext *fmt_ctx;
 
     fmt_ctx = avformat_alloc_context();
+    set_context_opts(fmt_ctx, avformat_opts, AV_OPT_FLAG_DECODING_PARAM, NULL);
 
     if ((err = av_open_input_file(&fmt_ctx, filename, iformat, 0, NULL)) < 0) {
         print_error(filename, err);
@@ -247,7 +277,7 @@ static int open_input_file(AVFormatContext **fmt_ctx_ptr, const char *filename)
         return err;
     }
 
-    dump_format(fmt_ctx, 0, filename, 0);
+    av_dump_format(fmt_ctx, 0, filename, 0);
 
     /* bind a decoder to each input stream */
     for (i = 0; i < fmt_ctx->nb_streams; i++) {
@@ -275,6 +305,9 @@ static int probe_file(const char *filename)
     if ((ret = open_input_file(&fmt_ctx, filename)))
         return ret;
 
+    if (do_show_packets)
+        show_packets(fmt_ctx);
+
     if (do_show_streams)
         for (i = 0; i < fmt_ctx->nb_streams; i++)
             show_stream(fmt_ctx, i);
@@ -316,9 +349,12 @@ static void opt_input_file(const char *arg)
 
 static void show_help(void)
 {
+    av_log_set_callback(log_callback_help);
     show_usage();
     show_help_options(options, "Main options:\n", 0, 0);
     printf("\n");
+    av_opt_show2(avformat_opts, NULL,
+                 AV_OPT_FLAG_DECODING_PARAM, 0);
 }
 
 static void opt_pretty(void)
@@ -331,7 +367,6 @@ static void opt_pretty(void)
 
 static const OptionDef options[] = {
 #include "cmdutils_common_opts.h"
-    { "convert_tags", OPT_BOOL, {(void*)&convert_tags}, "convert tag names to the FFmpeg generic tag names" },
     { "f", HAS_ARG, {(void*)opt_format}, "force format", "format" },
     { "unit", OPT_BOOL, {(void*)&show_value_unit}, "show unit of the displayed values" },
     { "prefix", OPT_BOOL, {(void*)&use_value_prefix}, "use SI prefixes for the displayed values" },
@@ -342,17 +377,23 @@ static const OptionDef options[] = {
     { "pretty", 0, {(void*)&opt_pretty},
       "prettify the format of displayed values, make it more human readable" },
     { "show_format",  OPT_BOOL, {(void*)&do_show_format} , "show format/container info" },
+    { "show_packets", OPT_BOOL, {(void*)&do_show_packets}, "show packets info" },
     { "show_streams", OPT_BOOL, {(void*)&do_show_streams}, "show streams info" },
+    { "default", OPT_FUNC2 | HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
     { NULL, },
 };
 
 int main(int argc, char **argv)
 {
+    int ret;
+
     av_register_all();
 #if CONFIG_AVDEVICE
     avdevice_register_all();
 #endif
 
+    avformat_opts = avformat_alloc_context();
+
     show_banner();
     parse_options(argc, argv, options, opt_input_file);
 
@@ -363,5 +404,9 @@ int main(int argc, char **argv)
         exit(1);
     }
 
-    return probe_file(input_filename);
+    ret = probe_file(input_filename);
+
+    av_free(avformat_opts);
+
+    return ret;
 }
diff --git a/ffserver.c b/ffserver.c
index a1bd526..36cd9ce 100644
--- a/ffserver.c
+++ b/ffserver.c
@@ -2,20 +2,20 @@
  * Multiple format streaming server
  * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -29,13 +29,17 @@
 #include <strings.h>
 #include <stdlib.h>
 #include "libavformat/avformat.h"
+#include "libavformat/ffm.h"
 #include "libavformat/network.h"
 #include "libavformat/os_support.h"
 #include "libavformat/rtpdec.h"
 #include "libavformat/rtsp.h"
+// XXX for ffio_open_dyn_packet_buffer, to be removed
+#include "libavformat/avio_internal.h"
 #include "libavutil/avstring.h"
 #include "libavutil/lfg.h"
 #include "libavutil/random_seed.h"
+#include "libavutil/parseutils.h"
 #include "libavcodec/opt.h"
 #include <stdarg.h>
 #include <unistd.h>
@@ -91,6 +95,10 @@ static const char *http_state[] = {
     "RTSP_SEND_PACKET",
 };
 
+#if !FF_API_MAX_STREAMS
+#define MAX_STREAMS 20
+#endif
+
 #define IOBUFFER_INIT_SIZE 8192
 
 /* timeouts are in ms */
@@ -158,7 +166,7 @@ typedef struct HTTPContext {
 
     /* RTSP state specific */
     uint8_t *pb_buffer; /* XXX: use that in all the code */
-    ByteIOContext *pb;
+    AVIOContext *pb;
     int seq; /* RTSP sequence number */
 
     /* RTP state specific */
@@ -379,7 +387,10 @@ static void http_vlog(const char *fmt, va_list vargs)
     }
 }
 
-static void __attribute__ ((format (printf, 1, 2))) http_log(const char *fmt, ...)
+#ifdef __GNUC__
+__attribute__ ((format (printf, 1, 2)))
+#endif
+static void http_log(const char *fmt, ...)
 {
     va_list vargs;
     va_start(vargs, fmt);
@@ -684,8 +695,8 @@ static int http_server(void)
            second to handle timeouts */
         do {
             ret = poll(poll_table, poll_entry - poll_table, delay);
-            if (ret < 0 && ff_neterrno() != FF_NETERROR(EAGAIN) &&
-                ff_neterrno() != FF_NETERROR(EINTR))
+            if (ret < 0 && ff_neterrno() != AVERROR(EAGAIN) &&
+                ff_neterrno() != AVERROR(EINTR))
                 return -1;
         } while (ret < 0);
 
@@ -740,7 +751,7 @@ static void http_send_too_busy_reply(int fd)
 {
     char buffer[300];
     int len = snprintf(buffer, sizeof(buffer),
-                       "HTTP/1.0 200 Server too busy\r\n"
+                       "HTTP/1.0 503 Server too busy\r\n"
                        "Content-type: text/html\r\n"
                        "\r\n"
                        "<html><head><title>Too busy</title></head><body>\r\n"
@@ -861,10 +872,10 @@ static void close_connection(HTTPContext *c)
     if (!c->last_packet_sent && c->state == HTTPSTATE_SEND_DATA_TRAILER) {
         if (ctx->oformat) {
             /* prepare header */
-            if (url_open_dyn_buf(&ctx->pb) >= 0) {
+            if (avio_open_dyn_buf(&ctx->pb) >= 0) {
                 av_write_trailer(ctx);
                 av_freep(&c->pb_buffer);
-                url_close_dyn_buf(ctx->pb, &c->pb_buffer);
+                avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
             }
         }
     }
@@ -908,8 +919,8 @@ static int handle_connection(HTTPContext *c)
     read_loop:
         len = recv(c->fd, c->buffer_ptr, 1, 0);
         if (len < 0) {
-            if (ff_neterrno() != FF_NETERROR(EAGAIN) &&
-                ff_neterrno() != FF_NETERROR(EINTR))
+            if (ff_neterrno() != AVERROR(EAGAIN) &&
+                ff_neterrno() != AVERROR(EINTR))
                 return -1;
         } else if (len == 0) {
             return -1;
@@ -944,8 +955,8 @@ static int handle_connection(HTTPContext *c)
             return 0;
         len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
         if (len < 0) {
-            if (ff_neterrno() != FF_NETERROR(EAGAIN) &&
-                ff_neterrno() != FF_NETERROR(EINTR)) {
+            if (ff_neterrno() != AVERROR(EAGAIN) &&
+                ff_neterrno() != AVERROR(EINTR)) {
                 /* error : close connection */
                 av_freep(&c->pb_buffer);
                 return -1;
@@ -1014,8 +1025,8 @@ static int handle_connection(HTTPContext *c)
             return 0;
         len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
         if (len < 0) {
-            if (ff_neterrno() != FF_NETERROR(EAGAIN) &&
-                ff_neterrno() != FF_NETERROR(EINTR)) {
+            if (ff_neterrno() != AVERROR(EAGAIN) &&
+                ff_neterrno() != AVERROR(EINTR)) {
                 /* error : close connection */
                 av_freep(&c->pb_buffer);
                 return -1;
@@ -1041,8 +1052,8 @@ static int handle_connection(HTTPContext *c)
         len = send(c->fd, c->packet_buffer_ptr,
                     c->packet_buffer_end - c->packet_buffer_ptr, 0);
         if (len < 0) {
-            if (ff_neterrno() != FF_NETERROR(EAGAIN) &&
-                ff_neterrno() != FF_NETERROR(EINTR)) {
+            if (ff_neterrno() != AVERROR(EAGAIN) &&
+                ff_neterrno() != AVERROR(EINTR)) {
                 /* error : close connection */
                 av_freep(&c->packet_buffer);
                 return -1;
@@ -1187,19 +1198,6 @@ static int modify_current_stream(HTTPContext *c, char *rates)
     return action_required;
 }
 
-
-static void do_switch_stream(HTTPContext *c, int i)
-{
-    if (c->switch_feed_streams[i] >= 0) {
-#ifdef PHILIP
-        c->feed_streams[i] = c->switch_feed_streams[i];
-#endif
-
-        /* Now update the stream */
-    }
-    c->switch_feed_streams[i] = -1;
-}
-
 /* XXX: factorize in utils.c ? */
 /* XXX: take care with different space meaning */
 static void skip_spaces(const char **pp)
@@ -1573,7 +1571,7 @@ static int http_parse_request(HTTPContext *c)
         if (modify_current_stream(c, ratebuf)) {
             for (i = 0; i < FF_ARRAY_ELEMS(c->feed_streams); i++) {
                 if (c->switch_feed_streams[i] >= 0)
-                    do_switch_stream(c, i);
+                    c->switch_feed_streams[i] = -1;
             }
         }
     }
@@ -1589,10 +1587,10 @@ static int http_parse_request(HTTPContext *c)
     }
 
     if (c->post == 0 && max_bandwidth < current_bandwidth) {
-        c->http_error = 200;
+        c->http_error = 503;
         q = c->buffer;
         q += snprintf(q, c->buffer_size,
-                      "HTTP/1.0 200 Server too busy\r\n"
+                      "HTTP/1.0 503 Server too busy\r\n"
                       "Content-type: text/html\r\n"
                       "\r\n"
                       "<html><head><title>Too busy</title></head><body>\r\n"
@@ -1859,14 +1857,14 @@ static int http_parse_request(HTTPContext *c)
     return 0;
 }
 
-static void fmt_bytecount(ByteIOContext *pb, int64_t count)
+static void fmt_bytecount(AVIOContext *pb, int64_t count)
 {
     static const char *suffix = " kMGTP";
     const char *s;
 
     for (s = suffix; count >= 100000 && s[1]; count /= 1000, s++);
 
-    url_fprintf(pb, "%"PRId64"%c", count, *s);
+    avio_printf(pb, "%"PRId64"%c", count, *s);
 }
 
 static void compute_status(HTTPContext *c)
@@ -1876,29 +1874,29 @@ static void compute_status(HTTPContext *c)
     char *p;
     time_t ti;
     int i, len;
-    ByteIOContext *pb;
+    AVIOContext *pb;
 
-    if (url_open_dyn_buf(&pb) < 0) {
+    if (avio_open_dyn_buf(&pb) < 0) {
         /* XXX: return an error ? */
         c->buffer_ptr = c->buffer;
         c->buffer_end = c->buffer;
         return;
     }
 
-    url_fprintf(pb, "HTTP/1.0 200 OK\r\n");
-    url_fprintf(pb, "Content-type: %s\r\n", "text/html");
-    url_fprintf(pb, "Pragma: no-cache\r\n");
-    url_fprintf(pb, "\r\n");
+    avio_printf(pb, "HTTP/1.0 200 OK\r\n");
+    avio_printf(pb, "Content-type: %s\r\n", "text/html");
+    avio_printf(pb, "Pragma: no-cache\r\n");
+    avio_printf(pb, "\r\n");
 
-    url_fprintf(pb, "<html><head><title>%s Status</title>\n", program_name);
+    avio_printf(pb, "<html><head><title>%s Status</title>\n", program_name);
     if (c->stream->feed_filename[0])
-        url_fprintf(pb, "<link rel=\"shortcut icon\" href=\"%s\">\n", c->stream->feed_filename);
-    url_fprintf(pb, "</head>\n<body>");
-    url_fprintf(pb, "<h1>%s Status</h1>\n", program_name);
+        avio_printf(pb, "<link rel=\"shortcut icon\" href=\"%s\">\n", c->stream->feed_filename);
+    avio_printf(pb, "</head>\n<body>");
+    avio_printf(pb, "<h1>%s Status</h1>\n", program_name);
     /* format status */
-    url_fprintf(pb, "<h2>Available Streams</h2>\n");
-    url_fprintf(pb, "<table cellspacing=0 cellpadding=4>\n");
-    url_fprintf(pb, "<tr><th valign=top>Path<th align=left>Served<br>Conns<th><br>bytes<th valign=top>Format<th>Bit rate<br>kbits/s<th align=left>Video<br>kbits/s<th><br>Codec<th align=left>Audio<br>kbits/s<th><br>Codec<th align=left valign=top>Feed\n");
+    avio_printf(pb, "<h2>Available Streams</h2>\n");
+    avio_printf(pb, "<table cellspacing=0 cellpadding=4>\n");
+    avio_printf(pb, "<tr><th valign=top>Path<th align=left>Served<br>Conns<th><br>bytes<th valign=top>Format<th>Bit rate<br>kbits/s<th align=left>Video<br>kbits/s<th><br>Codec<th align=left>Audio<br>kbits/s<th><br>Codec<th align=left valign=top>Feed\n");
     stream = first_stream;
     while (stream != NULL) {
         char sfilename[1024];
@@ -1926,9 +1924,9 @@ static void compute_status(HTTPContext *c)
                 }
             }
 
-            url_fprintf(pb, "<tr><td><a href=\"/%s\">%s</a> ",
+            avio_printf(pb, "<tr><td><a href=\"/%s\">%s</a> ",
                          sfilename, stream->filename);
-            url_fprintf(pb, "<td align=right> %d <td align=right> ",
+            avio_printf(pb, "<td align=right> %d <td align=right> ",
                         stream->conns_served);
             fmt_bytecount(pb, stream->bytes_served);
             switch(stream->stream_type) {
@@ -1967,33 +1965,33 @@ static void compute_status(HTTPContext *c)
                             abort();
                         }
                     }
-                    url_fprintf(pb, "<td align=center> %s <td align=right> %d <td align=right> %d <td> %s %s <td align=right> %d <td> %s %s",
+                    avio_printf(pb, "<td align=center> %s <td align=right> %d <td align=right> %d <td> %s %s <td align=right> %d <td> %s %s",
                                  stream->fmt->name,
                                  stream->bandwidth,
                                  video_bit_rate / 1000, video_codec_name, video_codec_name_extra,
                                  audio_bit_rate / 1000, audio_codec_name, audio_codec_name_extra);
                     if (stream->feed)
-                        url_fprintf(pb, "<td>%s", stream->feed->filename);
+                        avio_printf(pb, "<td>%s", stream->feed->filename);
                     else
-                        url_fprintf(pb, "<td>%s", stream->feed_filename);
-                    url_fprintf(pb, "\n");
+                        avio_printf(pb, "<td>%s", stream->feed_filename);
+                    avio_printf(pb, "\n");
                 }
                 break;
             default:
-                url_fprintf(pb, "<td align=center> - <td align=right> - <td align=right> - <td><td align=right> - <td>\n");
+                avio_printf(pb, "<td align=center> - <td align=right> - <td align=right> - <td><td align=right> - <td>\n");
                 break;
             }
         }
         stream = stream->next;
     }
-    url_fprintf(pb, "</table>\n");
+    avio_printf(pb, "</table>\n");
 
     stream = first_stream;
     while (stream != NULL) {
         if (stream->feed == stream) {
-            url_fprintf(pb, "<h2>Feed %s</h2>", stream->filename);
+            avio_printf(pb, "<h2>Feed %s</h2>", stream->filename);
             if (stream->pid) {
-                url_fprintf(pb, "Running as pid %d.\n", stream->pid);
+                avio_printf(pb, "Running as pid %d.\n", stream->pid);
 
 #if defined(linux) && !defined(CONFIG_NOCUTILS)
                 {
@@ -2012,7 +2010,7 @@ static void compute_status(HTTPContext *c)
 
                         if (fscanf(pid_stat, "%10s %64s", cpuperc,
                                    cpuused) == 2) {
-                            url_fprintf(pb, "Currently using %s%% of the cpu. Total time used %s.\n",
+                            avio_printf(pb, "Currently using %s%% of the cpu. Total time used %s.\n",
                                          cpuperc, cpuused);
                         }
                         fclose(pid_stat);
@@ -2020,9 +2018,9 @@ static void compute_status(HTTPContext *c)
                 }
 #endif
 
-                url_fprintf(pb, "<p>");
+                avio_printf(pb, "<p>");
             }
-            url_fprintf(pb, "<table cellspacing=0 cellpadding=4><tr><th>Stream<th>type<th>kbits/s<th align=left>codec<th align=left>Parameters\n");
+            avio_printf(pb, "<table cellspacing=0 cellpadding=4><tr><th>Stream<th>type<th>kbits/s<th align=left>codec<th align=left>Parameters\n");
 
             for (i = 0; i < stream->nb_streams; i++) {
                 AVStream *st = stream->streams[i];
@@ -2045,26 +2043,26 @@ static void compute_status(HTTPContext *c)
                 default:
                     abort();
                 }
-                url_fprintf(pb, "<tr><td align=right>%d<td>%s<td align=right>%d<td>%s<td>%s\n",
+                avio_printf(pb, "<tr><td align=right>%d<td>%s<td align=right>%d<td>%s<td>%s\n",
                         i, type, st->codec->bit_rate/1000, codec ? codec->name : "", parameters);
             }
-            url_fprintf(pb, "</table>\n");
+            avio_printf(pb, "</table>\n");
 
         }
         stream = stream->next;
     }
 
     /* connection status */
-    url_fprintf(pb, "<h2>Connection Status</h2>\n");
+    avio_printf(pb, "<h2>Connection Status</h2>\n");
 
-    url_fprintf(pb, "Number of connections: %d / %d<br>\n",
+    avio_printf(pb, "Number of connections: %d / %d<br>\n",
                  nb_connections, nb_max_connections);
 
-    url_fprintf(pb, "Bandwidth in use: %"PRIu64"k / %"PRIu64"k<br>\n",
+    avio_printf(pb, "Bandwidth in use: %"PRIu64"k / %"PRIu64"k<br>\n",
                  current_bandwidth, max_bandwidth);
 
-    url_fprintf(pb, "<table>\n");
-    url_fprintf(pb, "<tr><th>#<th>File<th>IP<th>Proto<th>State<th>Target bits/sec<th>Actual bits/sec<th>Bytes transferred\n");
+    avio_printf(pb, "<table>\n");
+    avio_printf(pb, "<tr><th>#<th>File<th>IP<th>Proto<th>State<th>Target bits/sec<th>Actual bits/sec<th>Bytes transferred\n");
     c1 = first_http_ctx;
     i = 0;
     while (c1 != NULL) {
@@ -2083,7 +2081,7 @@ static void compute_status(HTTPContext *c)
 
         i++;
         p = inet_ntoa(c1->from_addr.sin_addr);
-        url_fprintf(pb, "<tr><td><b>%d</b><td>%s%s<td>%s<td>%s<td>%s<td align=right>",
+        avio_printf(pb, "<tr><td><b>%d</b><td>%s%s<td>%s<td>%s<td>%s<td align=right>",
                     i,
                     c1->stream ? c1->stream->filename : "",
                     c1->state == HTTPSTATE_RECEIVE_DATA ? "(input)" : "",
@@ -2091,22 +2089,22 @@ static void compute_status(HTTPContext *c)
                     c1->protocol,
                     http_state[c1->state]);
         fmt_bytecount(pb, bitrate);
-        url_fprintf(pb, "<td align=right>");
+        avio_printf(pb, "<td align=right>");
         fmt_bytecount(pb, compute_datarate(&c1->datarate, c1->data_count) * 8);
-        url_fprintf(pb, "<td align=right>");
+        avio_printf(pb, "<td align=right>");
         fmt_bytecount(pb, c1->data_count);
-        url_fprintf(pb, "\n");
+        avio_printf(pb, "\n");
         c1 = c1->next;
     }
-    url_fprintf(pb, "</table>\n");
+    avio_printf(pb, "</table>\n");
 
     /* date */
     ti = time(NULL);
     p = ctime(&ti);
-    url_fprintf(pb, "<hr size=1 noshade>Generated at %s", p);
-    url_fprintf(pb, "</body>\n</html>\n");
+    avio_printf(pb, "<hr size=1 noshade>Generated at %s", p);
+    avio_printf(pb, "</body>\n</html>\n");
 
-    len = url_close_dyn_buf(pb, &c->pb_buffer);
+    len = avio_close_dyn_buf(pb, &c->pb_buffer);
     c->buffer_ptr = c->pb_buffer;
     c->buffer_end = c->pb_buffer + len;
 }
@@ -2140,11 +2138,10 @@ static int open_input_stream(HTTPContext *c, const char *info)
         strcpy(input_filename, c->stream->feed->feed_filename);
         buf_size = FFM_PACKET_SIZE;
         /* compute position (absolute time) */
-        if (find_info_tag(buf, sizeof(buf), "date", info)) {
-            stream_pos = parse_date(buf, 0);
-            if (stream_pos == INT64_MIN)
-                return -1;
-        } else if (find_info_tag(buf, sizeof(buf), "buffer", info)) {
+        if (av_find_info_tag(buf, sizeof(buf), "date", info)) {
+            if ((ret = av_parse_time(&stream_pos, buf, 0)) < 0)
+                return ret;
+        } else if (av_find_info_tag(buf, sizeof(buf), "buffer", info)) {
             int prebuffer = strtol(buf, 0, 10);
             stream_pos = av_gettime() - prebuffer * (int64_t)1000000;
         } else
@@ -2153,10 +2150,9 @@ static int open_input_stream(HTTPContext *c, const char *info)
         strcpy(input_filename, c->stream->feed_filename);
         buf_size = 0;
         /* compute position (relative time) */
-        if (find_info_tag(buf, sizeof(buf), "date", info)) {
-            stream_pos = parse_date(buf, 1);
-            if (stream_pos == INT64_MIN)
-                return -1;
+        if (av_find_info_tag(buf, sizeof(buf), "date", info)) {
+            if ((ret = av_parse_time(&stream_pos, buf, 1)) < 0)
+                return ret;
         } else
             stream_pos = 0;
     }
@@ -2263,11 +2259,11 @@ static int http_prepare_data(HTTPContext *c)
         c->got_key_frame = 0;
 
         /* prepare header and save header data in a stream */
-        if (url_open_dyn_buf(&c->fmt_ctx.pb) < 0) {
+        if (avio_open_dyn_buf(&c->fmt_ctx.pb) < 0) {
             /* XXX: potential leak */
             return -1;
         }
-        c->fmt_ctx.pb->is_streamed = 1;
+        c->fmt_ctx.pb->seekable = 0;
 
         /*
          * HACK to avoid mpeg ps muxer to spit many underflow errors
@@ -2284,7 +2280,7 @@ static int http_prepare_data(HTTPContext *c)
         }
         av_metadata_free(&c->fmt_ctx.metadata);
 
-        len = url_close_dyn_buf(c->fmt_ctx.pb, &c->pb_buffer);
+        len = avio_close_dyn_buf(c->fmt_ctx.pb, &c->pb_buffer);
         c->buffer_ptr = c->pb_buffer;
         c->buffer_end = c->pb_buffer + len;
 
@@ -2306,12 +2302,16 @@ static int http_prepare_data(HTTPContext *c)
         else {
             AVPacket pkt;
         redo:
-            if (av_read_frame(c->fmt_in, &pkt) < 0) {
-                if (c->stream->feed && c->stream->feed->feed_opened) {
+            ret = av_read_frame(c->fmt_in, &pkt);
+            if (ret < 0) {
+                if (c->stream->feed) {
                     /* if coming from feed, it means we reached the end of the
                        ffm file, so must wait for more data */
                     c->state = HTTPSTATE_WAIT_FEED;
                     return 1; /* state changed */
+                } else if (ret == AVERROR(EAGAIN)) {
+                    /* input not ready, come back later */
+                    return 0;
                 } else {
                     if (c->stream->loop) {
                         av_close_input_file(c->fmt_in);
@@ -2340,7 +2340,7 @@ static int http_prepare_data(HTTPContext *c)
                         for(i=0;i<c->stream->nb_streams;i++) {
                             if (c->switch_feed_streams[i] == pkt.stream_index)
                                 if (pkt.flags & AV_PKT_FLAG_KEY)
-                                    do_switch_stream(c, i);
+                                    c->switch_feed_streams[i] = -1;
                             if (c->switch_feed_streams[i] >= 0)
                                 c->switch_pending = 1;
                         }
@@ -2368,8 +2368,7 @@ static int http_prepare_data(HTTPContext *c)
                     if (c->is_packetized) {
                         /* compute send time and duration */
                         c->cur_pts = av_rescale_q(pkt.dts, ist->time_base, AV_TIME_BASE_Q);
-                        if (ist->start_time != AV_NOPTS_VALUE)
-                            c->cur_pts -= av_rescale_q(ist->start_time, ist->time_base, AV_TIME_BASE_Q);
+                        c->cur_pts -= c->first_pts;
                         c->cur_frame_duration = av_rescale_q(pkt.duration, ist->time_base, AV_TIME_BASE_Q);
                         /* find RTP context */
                         c->packet_stream_index = pkt.stream_index;
@@ -2393,9 +2392,9 @@ static int http_prepare_data(HTTPContext *c)
                             max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
                         else
                             max_packet_size = url_get_max_packet_size(c->rtp_handles[c->packet_stream_index]);
-                        ret = url_open_dyn_packet_buf(&ctx->pb, max_packet_size);
+                        ret = ffio_open_dyn_packet_buf(&ctx->pb, max_packet_size);
                     } else {
-                        ret = url_open_dyn_buf(&ctx->pb);
+                        ret = avio_open_dyn_buf(&ctx->pb);
                     }
                     if (ret < 0) {
                         /* XXX: potential leak */
@@ -2403,7 +2402,7 @@ static int http_prepare_data(HTTPContext *c)
                     }
                     ost = ctx->streams[pkt.stream_index];
 
-                    ctx->pb->is_streamed = 1;
+                    ctx->pb->seekable = 0;
                     if (pkt.dts != AV_NOPTS_VALUE)
                         pkt.dts = av_rescale_q(pkt.dts, ist->time_base, ost->time_base);
                     if (pkt.pts != AV_NOPTS_VALUE)
@@ -2414,7 +2413,7 @@ static int http_prepare_data(HTTPContext *c)
                         c->state = HTTPSTATE_SEND_DATA_TRAILER;
                     }
 
-                    len = url_close_dyn_buf(ctx->pb, &c->pb_buffer);
+                    len = avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
                     c->cur_frame_bytes = len;
                     c->buffer_ptr = c->pb_buffer;
                     c->buffer_end = c->pb_buffer + len;
@@ -2436,13 +2435,13 @@ static int http_prepare_data(HTTPContext *c)
             return -1;
         ctx = &c->fmt_ctx;
         /* prepare header */
-        if (url_open_dyn_buf(&ctx->pb) < 0) {
+        if (avio_open_dyn_buf(&ctx->pb) < 0) {
             /* XXX: potential leak */
             return -1;
         }
-        c->fmt_ctx.pb->is_streamed = 1;
+        c->fmt_ctx.pb->seekable = 0;
         av_write_trailer(ctx);
-        len = url_close_dyn_buf(ctx->pb, &c->pb_buffer);
+        len = avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
         c->buffer_ptr = c->pb_buffer;
         c->buffer_end = c->pb_buffer + len;
 
@@ -2495,7 +2494,7 @@ static int http_send_data(HTTPContext *c)
 
                 if (c->rtp_protocol == RTSP_LOWER_TRANSPORT_TCP) {
                     /* RTP packets are sent inside the RTSP TCP connection */
-                    ByteIOContext *pb;
+                    AVIOContext *pb;
                     int interleaved_index, size;
                     uint8_t header[4];
                     HTTPContext *rtsp_c;
@@ -2507,7 +2506,7 @@ static int http_send_data(HTTPContext *c)
                     /* if already sending something, then wait. */
                     if (rtsp_c->state != RTSPSTATE_WAIT_REQUEST)
                         break;
-                    if (url_open_dyn_buf(&pb) < 0)
+                    if (avio_open_dyn_buf(&pb) < 0)
                         goto fail1;
                     interleaved_index = c->packet_stream_index * 2;
                     /* RTCP packets are sent at odd indexes */
@@ -2518,11 +2517,11 @@ static int http_send_data(HTTPContext *c)
                     header[1] = interleaved_index;
                     header[2] = len >> 8;
                     header[3] = len;
-                    put_buffer(pb, header, 4);
+                    avio_write(pb, header, 4);
                     /* write RTP packet data */
                     c->buffer_ptr += 4;
-                    put_buffer(pb, c->buffer_ptr, len);
-                    size = url_close_dyn_buf(pb, &c->packet_buffer);
+                    avio_write(pb, c->buffer_ptr, len);
+                    size = avio_close_dyn_buf(pb, &c->packet_buffer);
                     /* prepare asynchronous TCP sending */
                     rtsp_c->packet_buffer_ptr = c->packet_buffer;
                     rtsp_c->packet_buffer_end = c->packet_buffer + size;
@@ -2554,8 +2553,8 @@ static int http_send_data(HTTPContext *c)
                 /* TCP data output */
                 len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
                 if (len < 0) {
-                    if (ff_neterrno() != FF_NETERROR(EAGAIN) &&
-                        ff_neterrno() != FF_NETERROR(EINTR))
+                    if (ff_neterrno() != AVERROR(EAGAIN) &&
+                        ff_neterrno() != AVERROR(EINTR))
                         /* error : close connection */
                         return -1;
                     else
@@ -2628,10 +2627,11 @@ static int http_receive_data(HTTPContext *c)
         len = recv(c->fd, c->buffer_ptr, 1, 0);
 
         if (len < 0) {
-            if (ff_neterrno() != FF_NETERROR(EAGAIN) &&
-                ff_neterrno() != FF_NETERROR(EINTR))
+            if (ff_neterrno() != AVERROR(EAGAIN) &&
+                ff_neterrno() != AVERROR(EINTR))
                 /* error : close connection */
                 goto fail;
+            return 0;
         } else if (len == 0) {
             /* end of connection : close it */
             goto fail;
@@ -2654,8 +2654,8 @@ static int http_receive_data(HTTPContext *c)
         len = recv(c->fd, c->buffer_ptr,
                    FFMIN(c->chunk_size, c->buffer_end - c->buffer_ptr), 0);
         if (len < 0) {
-            if (ff_neterrno() != FF_NETERROR(EAGAIN) &&
-                ff_neterrno() != FF_NETERROR(EINTR))
+            if (ff_neterrno() != AVERROR(EAGAIN) &&
+                ff_neterrno() != AVERROR(EINTR))
                 /* error : close connection */
                 goto fail;
         } else if (len == 0)
@@ -2715,7 +2715,7 @@ static int http_receive_data(HTTPContext *c)
         } else {
             /* We have a header in our hands that contains useful data */
             AVFormatContext *s = NULL;
-            ByteIOContext *pb;
+            AVIOContext *pb;
             AVInputFormat *fmt_in;
             int i;
 
@@ -2724,8 +2724,9 @@ static int http_receive_data(HTTPContext *c)
             if (!fmt_in)
                 goto fail;
 
-            url_open_buf(&pb, c->buffer, c->buffer_end - c->buffer, URL_RDONLY);
-            pb->is_streamed = 1;
+            pb = avio_alloc_context(c->buffer, c->buffer_end - c->buffer,
+                                    0, NULL, NULL, NULL, NULL);
+            pb->seekable = 0;
 
             if (av_open_input_stream(&s, pb, c->stream->feed_filename, fmt_in, NULL) < 0) {
                 av_free(pb);
@@ -2744,14 +2745,7 @@ static int http_receive_data(HTTPContext *c)
             for (i = 0; i < s->nb_streams; i++) {
                 AVStream *fst = feed->streams[i];
                 AVStream *st = s->streams[i];
-                memcpy(fst->codec, st->codec, sizeof(AVCodecContext));
-                if (fst->codec->extradata_size) {
-                    fst->codec->extradata = av_malloc(fst->codec->extradata_size);
-                    if (!fst->codec->extradata)
-                        goto fail;
-                    memcpy(fst->codec->extradata, st->codec->extradata,
-                           fst->codec->extradata_size);
-                }
+                avcodec_copy_context(fst->codec, st->codec);
             }
 
             av_close_input_stream(s);
@@ -2780,7 +2774,7 @@ static void rtsp_reply_header(HTTPContext *c, enum RTSPStatusCode error_number)
 {
     const char *str;
     time_t ti;
-    char *p;
+    struct tm *tm;
     char buf2[32];
 
     switch(error_number) {
@@ -2822,23 +2816,20 @@ static void rtsp_reply_header(HTTPContext *c, enum RTSPStatusCode error_number)
         break;
     }
 
-    url_fprintf(c->pb, "RTSP/1.0 %d %s\r\n", error_number, str);
-    url_fprintf(c->pb, "CSeq: %d\r\n", c->seq);
+    avio_printf(c->pb, "RTSP/1.0 %d %s\r\n", error_number, str);
+    avio_printf(c->pb, "CSeq: %d\r\n", c->seq);
 
     /* output GMT time */
     ti = time(NULL);
-    p = ctime(&ti);
-    strcpy(buf2, p);
-    p = buf2 + strlen(p) - 1;
-    if (*p == '\n')
-        *p = '\0';
-    url_fprintf(c->pb, "Date: %s GMT\r\n", buf2);
+    tm = gmtime(&ti);
+    strftime(buf2, sizeof(buf2), "%a, %d %b %Y %H:%M:%S", tm);
+    avio_printf(c->pb, "Date: %s GMT\r\n", buf2);
 }
 
 static void rtsp_reply_error(HTTPContext *c, enum RTSPStatusCode error_number)
 {
     rtsp_reply_header(c, error_number);
-    url_fprintf(c->pb, "\r\n");
+    avio_printf(c->pb, "\r\n");
 }
 
 static int rtsp_parse_request(HTTPContext *c)
@@ -2862,7 +2853,7 @@ static int rtsp_parse_request(HTTPContext *c)
     av_strlcpy(c->url, url, sizeof(c->url));
     av_strlcpy(c->protocol, protocol, sizeof(c->protocol));
 
-    if (url_open_dyn_buf(&c->pb) < 0) {
+    if (avio_open_dyn_buf(&c->pb) < 0) {
         /* XXX: cannot do more */
         c->pb = NULL; /* safety */
         return -1;
@@ -2896,7 +2887,7 @@ static int rtsp_parse_request(HTTPContext *c)
             len = sizeof(line) - 1;
         memcpy(line, p, len);
         line[len] = '\0';
-        ff_rtsp_parse_line(header, line, NULL);
+        ff_rtsp_parse_line(header, line, NULL, NULL);
         p = p1 + 1;
     }
 
@@ -2919,7 +2910,7 @@ static int rtsp_parse_request(HTTPContext *c)
         rtsp_reply_error(c, RTSP_STATUS_METHOD);
 
  the_end:
-    len = url_close_dyn_buf(c->pb, &c->pb_buffer);
+    len = avio_close_dyn_buf(c->pb, &c->pb_buffer);
     c->pb = NULL; /* safety */
     if (len < 0) {
         /* XXX: cannot do more */
@@ -2935,7 +2926,7 @@ static int prepare_sdp_description(FFStream *stream, uint8_t **pbuffer,
                                    struct in_addr my_ip)
 {
     AVFormatContext *avc;
-    AVStream avs[MAX_STREAMS];
+    AVStream *avs = NULL;
     int i;
 
     avc =  avformat_alloc_context();
@@ -2953,14 +2944,29 @@ static int prepare_sdp_description(FFStream *stream, uint8_t **pbuffer,
         snprintf(avc->filename, 1024, "rtp://0.0.0.0");
     }
 
+#if !FF_API_MAX_STREAMS
+    if (avc->nb_streams >= INT_MAX/sizeof(*avc->streams) ||
+        !(avc->streams = av_malloc(avc->nb_streams * sizeof(*avc->streams))))
+        goto sdp_done;
+#endif
+    if (avc->nb_streams >= INT_MAX/sizeof(*avs) ||
+        !(avs = av_malloc(avc->nb_streams * sizeof(*avs))))
+        goto sdp_done;
+
     for(i = 0; i < stream->nb_streams; i++) {
         avc->streams[i] = &avs[i];
         avc->streams[i]->codec = stream->streams[i]->codec;
     }
     *pbuffer = av_mallocz(2048);
-    avf_sdp_create(&avc, 1, *pbuffer, 2048);
+    av_sdp_create(&avc, 1, *pbuffer, 2048);
+
+ sdp_done:
+#if !FF_API_MAX_STREAMS
+    av_free(avc->streams);
+#endif
     av_metadata_free(&avc->metadata);
     av_free(avc);
+    av_free(avs);
 
     return strlen(*pbuffer);
 }
@@ -2968,10 +2974,10 @@ static int prepare_sdp_description(FFStream *stream, uint8_t **pbuffer,
 static void rtsp_cmd_options(HTTPContext *c, const char *url)
 {
 //    rtsp_reply_header(c, RTSP_STATUS_OK);
-    url_fprintf(c->pb, "RTSP/1.0 %d %s\r\n", RTSP_STATUS_OK, "OK");
-    url_fprintf(c->pb, "CSeq: %d\r\n", c->seq);
-    url_fprintf(c->pb, "Public: %s\r\n", "OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE");
-    url_fprintf(c->pb, "\r\n");
+    avio_printf(c->pb, "RTSP/1.0 %d %s\r\n", RTSP_STATUS_OK, "OK");
+    avio_printf(c->pb, "CSeq: %d\r\n", c->seq);
+    avio_printf(c->pb, "Public: %s\r\n", "OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE");
+    avio_printf(c->pb, "\r\n");
 }
 
 static void rtsp_cmd_describe(HTTPContext *c, const char *url)
@@ -2984,7 +2990,7 @@ static void rtsp_cmd_describe(HTTPContext *c, const char *url)
     struct sockaddr_in my_addr;
 
     /* find which url is asked */
-    ff_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
+    av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
     path = path1;
     if (*path == '/')
         path++;
@@ -3012,11 +3018,11 @@ static void rtsp_cmd_describe(HTTPContext *c, const char *url)
         return;
     }
     rtsp_reply_header(c, RTSP_STATUS_OK);
-    url_fprintf(c->pb, "Content-Base: %s/\r\n", url);
-    url_fprintf(c->pb, "Content-Type: application/sdp\r\n");
-    url_fprintf(c->pb, "Content-Length: %d\r\n", content_length);
-    url_fprintf(c->pb, "\r\n");
-    put_buffer(c->pb, content, content_length);
+    avio_printf(c->pb, "Content-Base: %s/\r\n", url);
+    avio_printf(c->pb, "Content-Type: application/sdp\r\n");
+    avio_printf(c->pb, "Content-Length: %d\r\n", content_length);
+    avio_printf(c->pb, "\r\n");
+    avio_write(c->pb, content, content_length);
     av_free(content);
 }
 
@@ -3061,7 +3067,7 @@ static void rtsp_cmd_setup(HTTPContext *c, const char *url,
     RTSPActionServerSetup setup;
 
     /* find which url is asked */
-    ff_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
+    av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
     path = path1;
     if (*path == '/')
         path++;
@@ -3161,30 +3167,30 @@ static void rtsp_cmd_setup(HTTPContext *c, const char *url,
     /* now everything is OK, so we can send the connection parameters */
     rtsp_reply_header(c, RTSP_STATUS_OK);
     /* session ID */
-    url_fprintf(c->pb, "Session: %s\r\n", rtp_c->session_id);
+    avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
 
     switch(rtp_c->rtp_protocol) {
     case RTSP_LOWER_TRANSPORT_UDP:
         rtp_port = rtp_get_local_rtp_port(rtp_c->rtp_handles[stream_index]);
         rtcp_port = rtp_get_local_rtcp_port(rtp_c->rtp_handles[stream_index]);
-        url_fprintf(c->pb, "Transport: RTP/AVP/UDP;unicast;"
+        avio_printf(c->pb, "Transport: RTP/AVP/UDP;unicast;"
                     "client_port=%d-%d;server_port=%d-%d",
                     th->client_port_min, th->client_port_max,
                     rtp_port, rtcp_port);
         break;
     case RTSP_LOWER_TRANSPORT_TCP:
-        url_fprintf(c->pb, "Transport: RTP/AVP/TCP;interleaved=%d-%d",
+        avio_printf(c->pb, "Transport: RTP/AVP/TCP;interleaved=%d-%d",
                     stream_index * 2, stream_index * 2 + 1);
         break;
     default:
         break;
     }
     if (setup.transport_option[0] != '\0')
-        url_fprintf(c->pb, ";%s", setup.transport_option);
-    url_fprintf(c->pb, "\r\n");
+        avio_printf(c->pb, ";%s", setup.transport_option);
+    avio_printf(c->pb, "\r\n");
 
 
-    url_fprintf(c->pb, "\r\n");
+    avio_printf(c->pb, "\r\n");
 }
 
 
@@ -3197,14 +3203,14 @@ static HTTPContext *find_rtp_session_with_url(const char *url,
     char path1[1024];
     const char *path;
     char buf[1024];
-    int s;
+    int s, len;
 
     rtp_c = find_rtp_session(session_id);
     if (!rtp_c)
         return NULL;
 
     /* find which url is asked */
-    ff_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
+    av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
     path = path1;
     if (*path == '/')
         path++;
@@ -3217,6 +3223,10 @@ static HTTPContext *find_rtp_session_with_url(const char *url,
         return rtp_c;
       }
     }
+    len = strlen(path);
+    if (len > 0 && path[len - 1] == '/' &&
+        !strncmp(path, rtp_c->stream->filename, len - 1))
+        return rtp_c;
     return NULL;
 }
 
@@ -3242,8 +3252,8 @@ static void rtsp_cmd_play(HTTPContext *c, const char *url, RTSPMessageHeader *h)
     /* now everything is OK, so we can send the connection parameters */
     rtsp_reply_header(c, RTSP_STATUS_OK);
     /* session ID */
-    url_fprintf(c->pb, "Session: %s\r\n", rtp_c->session_id);
-    url_fprintf(c->pb, "\r\n");
+    avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
+    avio_printf(c->pb, "\r\n");
 }
 
 static void rtsp_cmd_pause(HTTPContext *c, const char *url, RTSPMessageHeader *h)
@@ -3267,8 +3277,8 @@ static void rtsp_cmd_pause(HTTPContext *c, const char *url, RTSPMessageHeader *h
     /* now everything is OK, so we can send the connection parameters */
     rtsp_reply_header(c, RTSP_STATUS_OK);
     /* session ID */
-    url_fprintf(c->pb, "Session: %s\r\n", rtp_c->session_id);
-    url_fprintf(c->pb, "\r\n");
+    avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
+    avio_printf(c->pb, "\r\n");
 }
 
 static void rtsp_cmd_teardown(HTTPContext *c, const char *url, RTSPMessageHeader *h)
@@ -3290,8 +3300,8 @@ static void rtsp_cmd_teardown(HTTPContext *c, const char *url, RTSPMessageHeader
     /* now everything is OK, so we can send the connection parameters */
     rtsp_reply_header(c, RTSP_STATUS_OK);
     /* session ID */
-    url_fprintf(c->pb, "Session: %s\r\n", session_id);
-    url_fprintf(c->pb, "\r\n");
+    avio_printf(c->pb, "Session: %s\r\n", session_id);
+    avio_printf(c->pb, "\r\n");
 }
 
 
@@ -3418,7 +3428,7 @@ static int rtp_new_av_stream(HTTPContext *c,
                      "rtp://%s:%d", ipaddr, ntohs(dest_addr->sin_port));
         }
 
-        if (url_open(&h, ctx->filename, URL_WRONLY) < 0)
+        if (url_open(&h, ctx->filename, AVIO_WRONLY) < 0)
             goto fail;
         c->rtp_handles[stream_index] = h;
         max_packet_size = url_get_max_packet_size(h);
@@ -3437,7 +3447,7 @@ static int rtp_new_av_stream(HTTPContext *c,
              c->stream->filename, stream_index, c->protocol);
 
     /* normally, no packets should be output here, but the packet size may be checked */
-    if (url_open_dyn_packet_buf(&ctx->pb, max_packet_size) < 0) {
+    if (ffio_open_dyn_packet_buf(&ctx->pb, max_packet_size) < 0) {
         /* XXX: close stream */
         goto fail;
     }
@@ -3449,7 +3459,7 @@ static int rtp_new_av_stream(HTTPContext *c,
         av_free(ctx);
         return -1;
     }
-    url_close_dyn_buf(ctx->pb, &dummy_buf);
+    avio_close_dyn_buf(ctx->pb, &dummy_buf);
     av_free(dummy_buf);
 
     c->rtp_ctx[stream_index] = ctx;
@@ -3483,6 +3493,7 @@ static AVStream *add_av_stream1(FFStream *stream, AVCodecContext *codec, int cop
     fst->priv_data = av_mallocz(sizeof(FeedData));
     fst->index = stream->nb_streams;
     av_set_pts_info(fst, 33, 1, 90000);
+    fst->sample_aspect_ratio = codec->sample_aspect_ratio;
     stream->streams[stream->nb_streams++] = fst;
     return fst;
 }
@@ -3757,7 +3768,7 @@ static void build_feed_streams(void)
             }
 
             /* only write the header of the ffm file */
-            if (url_fopen(&s->pb, feed->feed_filename, URL_WRONLY) < 0) {
+            if (avio_open(&s->pb, feed->feed_filename, AVIO_WRONLY) < 0) {
                 http_log("Could not open output feed file '%s'\n",
                          feed->feed_filename);
                 exit(1);
@@ -3776,7 +3787,7 @@ static void build_feed_streams(void)
             }
             /* XXX: need better api */
             av_freep(&s->priv_data);
-            url_fclose(s->pb);
+            avio_close(s->pb);
         }
         /* get feed size and write index */
         fd = open(feed->feed_filename, O_RDONLY);
@@ -3863,7 +3874,8 @@ static void add_codec(FFStream *stream, AVCodecContext *av)
             av->nsse_weight = 8;
 
         av->frame_skip_cmp = FF_CMP_DCTMAX;
-        av->me_method = ME_EPZS;
+        if (!av->me_method)
+            av->me_method = ME_EPZS;
         av->rc_buffer_aggressivity = 1.0;
 
         if (!av->rc_eq)
@@ -3951,6 +3963,49 @@ static int ffserver_opt_default(const char *opt, const char *arg,
     return ret;
 }
 
+static int ffserver_opt_preset(const char *arg,
+                       AVCodecContext *avctx, int type,
+                       enum CodecID *audio_id, enum CodecID *video_id)
+{
+    FILE *f=NULL;
+    char filename[1000], tmp[1000], tmp2[1000], line[1000];
+    int ret = 0;
+    AVCodec *codec = avcodec_find_encoder(avctx->codec_id);
+
+    if (!(f = get_preset_file(filename, sizeof(filename), arg, 0,
+                              codec ? codec->name : NULL))) {
+        fprintf(stderr, "File for preset '%s' not found\n", arg);
+        return 1;
+    }
+
+    while(!feof(f)){
+        int e= fscanf(f, "%999[^\n]\n", line) - 1;
+        if(line[0] == '#' && !e)
+            continue;
+        e|= sscanf(line, "%999[^=]=%999[^\n]\n", tmp, tmp2) - 2;
+        if(e){
+            fprintf(stderr, "%s: Invalid syntax: '%s'\n", filename, line);
+            ret = 1;
+            break;
+        }
+        if(!strcmp(tmp, "acodec")){
+            *audio_id = opt_audio_codec(tmp2);
+        }else if(!strcmp(tmp, "vcodec")){
+            *video_id = opt_video_codec(tmp2);
+        }else if(!strcmp(tmp, "scodec")){
+            /* opt_subtitle_codec(tmp2); */
+        }else if(ffserver_opt_default(tmp, tmp2, avctx, type) < 0){
+            fprintf(stderr, "%s: Invalid option or argument: '%s', parsed as '%s' = '%s'\n", filename, line, tmp, tmp2);
+            ret = 1;
+            break;
+        }
+    }
+
+    fclose(f);
+
+    return ret;
+}
+
 static AVOutputFormat *ffserver_guess_format(const char *short_name, const char *filename,
                                              const char *mime_type)
 {
@@ -4301,7 +4356,7 @@ static int parse_ffconfig(const char *filename)
         } else if (!strcasecmp(cmd, "AudioBitRate")) {
             get_arg(arg, sizeof(arg), &p);
             if (stream)
-                audio_enc.bit_rate = atoi(arg) * 1000;
+                audio_enc.bit_rate = lrintf(atof(arg) * 1000);
         } else if (!strcasecmp(cmd, "AudioChannels")) {
             get_arg(arg, sizeof(arg), &p);
             if (stream)
@@ -4356,7 +4411,7 @@ static int parse_ffconfig(const char *filename)
         } else if (!strcasecmp(cmd, "VideoSize")) {
             get_arg(arg, sizeof(arg), &p);
             if (stream) {
-                av_parse_video_frame_size(&video_enc.width, &video_enc.height, arg);
+                av_parse_video_size(&video_enc.width, &video_enc.height, arg);
                 if ((video_enc.width % 16) != 0 ||
                     (video_enc.height % 16) != 0) {
                     ERROR("Image size must be a multiple of 16\n");
@@ -4366,7 +4421,7 @@ static int parse_ffconfig(const char *filename)
             get_arg(arg, sizeof(arg), &p);
             if (stream) {
                 AVRational frame_rate;
-                if (av_parse_video_frame_rate(&frame_rate, arg) < 0) {
+                if (av_parse_video_rate(&frame_rate, arg) < 0) {
                     ERROR("Incorrect frame rate: %s\n", arg);
                 } else {
                     video_enc.time_base.num = frame_rate.den;
@@ -4405,6 +4460,23 @@ static int parse_ffconfig(const char *filename)
             if (ffserver_opt_default(arg, arg2, avctx, type|AV_OPT_FLAG_ENCODING_PARAM)) {
                 ERROR("AVOption error: %s %s\n", arg, arg2);
             }
+        } else if (!strcasecmp(cmd, "AVPresetVideo") ||
+                   !strcasecmp(cmd, "AVPresetAudio")) {
+            AVCodecContext *avctx;
+            int type;
+            get_arg(arg, sizeof(arg), &p);
+            if (!strcasecmp(cmd, "AVPresetVideo")) {
+                avctx = &video_enc;
+                video_enc.codec_id = video_id;
+                type = AV_OPT_FLAG_VIDEO_PARAM;
+            } else {
+                avctx = &audio_enc;
+                audio_enc.codec_id = audio_id;
+                type = AV_OPT_FLAG_AUDIO_PARAM;
+            }
+            if (ffserver_opt_preset(arg, avctx, type|AV_OPT_FLAG_ENCODING_PARAM, &audio_id, &video_id)) {
+                ERROR("AVPreset error: %s\n", arg);
+            }
         } else if (!strcasecmp(cmd, "VideoTag")) {
             get_arg(arg, sizeof(arg), &p);
             if ((strlen(arg) == 4) && stream)
@@ -4630,7 +4702,7 @@ int main(int argc, char **argv)
 
     unsetenv("http_proxy");             /* Kill the http_proxy */
 
-    av_lfg_init(&random_state, ff_random_get_seed());
+    av_lfg_init(&random_state, av_get_random_seed());
 
     memset(&sigact, 0, sizeof(sigact));
     sigact.sa_handler = handle_child_exit;
diff --git a/ffserver.h b/ffserver.h
index c76752f..868b83b 100644
--- a/ffserver.h
+++ b/ffserver.h
@@ -2,20 +2,20 @@
  * Multiple format streaming server
  * copyright (c) 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #ifndef FFMPEG_FFSERVER_H
diff --git a/libavcodec/4xm.c b/libavcodec/4xm.c
index 2198503..dc6f8bd 100644
--- a/libavcodec/4xm.c
+++ b/libavcodec/4xm.c
@@ -2,20 +2,20 @@
  * 4XM codec
  * Copyright (c) 2003 Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -260,6 +260,23 @@ static void init_mv(FourXContext *f){
     }
 }
 
+#if HAVE_BIGENDIAN
+#define LE_CENTRIC_MUL(dst, src, scale, dc) \
+    { \
+        unsigned tmpval = AV_RN32(src);                 \
+        tmpval = (tmpval <<  16) | (tmpval >>  16);     \
+        tmpval = tmpval * (scale) + (dc);               \
+        tmpval = (tmpval <<  16) | (tmpval >>  16);     \
+        AV_WN32A(dst, tmpval);                          \
+    }
+#else
+#define LE_CENTRIC_MUL(dst, src, scale, dc) \
+    { \
+        unsigned tmpval = AV_RN32(src) * (scale) + (dc); \
+        AV_WN32A(dst, tmpval);                           \
+    }
+#endif
+
 static inline void mcdc(uint16_t *dst, uint16_t *src, int log2w, int h, int stride, int scale, int dc){
    int i;
    dc*= 0x10001;
@@ -274,25 +291,25 @@ static inline void mcdc(uint16_t *dst, uint16_t *src, int log2w, int h, int stri
         break;
     case 1:
         for(i=0; i<h; i++){
-            ((uint32_t*)dst)[0] = scale*((uint32_t*)src)[0] + dc;
+            LE_CENTRIC_MUL(dst, src, scale, dc);
             if(scale) src += stride;
             dst += stride;
         }
         break;
     case 2:
         for(i=0; i<h; i++){
-            ((uint32_t*)dst)[0] = scale*((uint32_t*)src)[0] + dc;
-            ((uint32_t*)dst)[1] = scale*((uint32_t*)src)[1] + dc;
+            LE_CENTRIC_MUL(dst,     src,     scale, dc);
+            LE_CENTRIC_MUL(dst + 2, src + 2, scale, dc);
             if(scale) src += stride;
             dst += stride;
         }
         break;
     case 3:
         for(i=0; i<h; i++){
-            ((uint32_t*)dst)[0] = scale*((uint32_t*)src)[0] + dc;
-            ((uint32_t*)dst)[1] = scale*((uint32_t*)src)[1] + dc;
-            ((uint32_t*)dst)[2] = scale*((uint32_t*)src)[2] + dc;
-            ((uint32_t*)dst)[3] = scale*((uint32_t*)src)[3] + dc;
+            LE_CENTRIC_MUL(dst,     src,     scale, dc);
+            LE_CENTRIC_MUL(dst + 2, src + 2, scale, dc);
+            LE_CENTRIC_MUL(dst + 4, src + 4, scale, dc);
+            LE_CENTRIC_MUL(dst + 6, src + 6, scale, dc);
             if(scale) src += stride;
             dst += stride;
         }
@@ -333,16 +350,16 @@ static void decode_p_block(FourXContext *f, uint16_t *dst, uint16_t *src, int lo
             av_log(f->avctx, AV_LOG_ERROR, "mv out of pic\n");
             return;
         }
-        mcdc(dst, src, log2w, h, stride, 1, le2me_16(*f->wordstream++));
+        mcdc(dst, src, log2w, h, stride, 1, av_le2ne16(*f->wordstream++));
     }else if(code == 5){
-        mcdc(dst, src, log2w, h, stride, 0, le2me_16(*f->wordstream++));
+        mcdc(dst, src, log2w, h, stride, 0, av_le2ne16(*f->wordstream++));
     }else if(code == 6){
         if(log2w){
-            dst[0] = le2me_16(*f->wordstream++);
-            dst[1] = le2me_16(*f->wordstream++);
+            dst[0] = av_le2ne16(*f->wordstream++);
+            dst[1] = av_le2ne16(*f->wordstream++);
         }else{
-            dst[0     ] = le2me_16(*f->wordstream++);
-            dst[stride] = le2me_16(*f->wordstream++);
+            dst[0     ] = av_le2ne16(*f->wordstream++);
+            dst[stride] = av_le2ne16(*f->wordstream++);
         }
     }
 }
@@ -774,6 +791,14 @@ static int decode_frame(AVCodecContext *avctx,
         if(decode_i_frame(f, buf, frame_size) < 0)
             return -1;
     }else if(frame_4cc == AV_RL32("pfrm") || frame_4cc == AV_RL32("pfr2")){
+        if(!f->last_picture.data[0]){
+            f->last_picture.reference= 1;
+            if(avctx->get_buffer(avctx, &f->last_picture) < 0){
+                av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
+                return -1;
+            }
+        }
+
         p->pict_type= FF_P_TYPE;
         if(decode_p_frame(f, buf, frame_size) < 0)
             return -1;
@@ -840,7 +865,7 @@ static av_cold int decode_end(AVCodecContext *avctx){
     return 0;
 }
 
-AVCodec fourxm_decoder = {
+AVCodec ff_fourxm_decoder = {
     "4xm",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_4XM,
diff --git a/libavcodec/8bps.c b/libavcodec/8bps.c
index ff57955..055715f 100644
--- a/libavcodec/8bps.c
+++ b/libavcodec/8bps.c
@@ -2,20 +2,20 @@
  * Quicktime Planar RGB (8BPS) Video Decoder
  * Copyright (C) 2003 Roberto Togni
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -50,6 +50,8 @@ typedef struct EightBpsContext {
 
         unsigned char planes;
         unsigned char planemap[4];
+
+        uint32_t pal[256];
 } EightBpsContext;
 
 
@@ -100,7 +102,7 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPac
                 for(row = 0; row < height; row++) {
                         pixptr = c->pic.data[0] + row * c->pic.linesize[0] + planemap[p];
                         pixptr_end = pixptr + c->pic.linesize[0];
-                        dlen = be2me_16(*(const unsigned short *)(lp+row*2));
+                        dlen = av_be2ne16(*(const unsigned short *)(lp+row*2));
                         /* Decode a row of this plane */
                         while(dlen > 0) {
                                 if(dp + 1 >= buf+buf_size) return -1;
@@ -129,13 +131,16 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPac
                 }
         }
 
-        if (avctx->palctrl) {
-                memcpy (c->pic.data[1], avctx->palctrl->palette, AVPALETTE_SIZE);
-                if (avctx->palctrl->palette_changed) {
+        if (avctx->bits_per_coded_sample <= 8) {
+                const uint8_t *pal = av_packet_get_side_data(avpkt,
+                                                             AV_PKT_DATA_PALETTE,
+                                                             NULL);
+                if (pal) {
                         c->pic.palette_has_changed = 1;
-                        avctx->palctrl->palette_changed = 0;
-                } else
-                        c->pic.palette_has_changed = 0;
+                        memcpy(c->pal, pal, AVPALETTE_SIZE);
+                }
+
+                memcpy (c->pic.data[1], c->pal, AVPALETTE_SIZE);
         }
 
         *data_size = sizeof(AVFrame);
@@ -164,10 +169,6 @@ static av_cold int decode_init(AVCodecContext *avctx)
                         avctx->pix_fmt = PIX_FMT_PAL8;
                         c->planes = 1;
                         c->planemap[0] = 0; // 1st plane is palette indexes
-                        if (avctx->palctrl == NULL) {
-                                av_log(avctx, AV_LOG_ERROR, "Error: PAL8 format but no palette from demuxer.\n");
-                                return -1;
-                        }
                         break;
                 case 24:
                         avctx->pix_fmt = avctx->get_format(avctx, pixfmt_rgb24);
@@ -219,7 +220,7 @@ static av_cold int decode_end(AVCodecContext *avctx)
 
 
 
-AVCodec eightbps_decoder = {
+AVCodec ff_eightbps_decoder = {
         "8bps",
         AVMEDIA_TYPE_VIDEO,
         CODEC_ID_8BPS,
diff --git a/libavcodec/8svx.c b/libavcodec/8svx.c
index 6e09b11..5fdea91 100644
--- a/libavcodec/8svx.c
+++ b/libavcodec/8svx.c
@@ -2,20 +2,20 @@
  * 8SVX audio decoder
  * Copyright (C) 2008 Jaikrishnan Menon
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -88,11 +88,11 @@ static av_cold int eightsvx_decode_init(AVCodecContext *avctx)
         default:
           return -1;
     }
-    avctx->sample_fmt = SAMPLE_FMT_S16;
+    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
     return 0;
 }
 
-AVCodec eightsvx_fib_decoder = {
+AVCodec ff_eightsvx_fib_decoder = {
   .name           = "8svx_fib",
   .type           = AVMEDIA_TYPE_AUDIO,
   .id             = CODEC_ID_8SVX_FIB,
@@ -102,7 +102,7 @@ AVCodec eightsvx_fib_decoder = {
   .long_name      = NULL_IF_CONFIG_SMALL("8SVX fibonacci"),
 };
 
-AVCodec eightsvx_exp_decoder = {
+AVCodec ff_eightsvx_exp_decoder = {
   .name           = "8svx_exp",
   .type           = AVMEDIA_TYPE_AUDIO,
   .id             = CODEC_ID_8SVX_EXP,
diff --git a/libavcodec/Makefile b/libavcodec/Makefile
index 00e6b57..1cdae2c 100644
--- a/libavcodec/Makefile
+++ b/libavcodec/Makefile
@@ -3,7 +3,7 @@ include $(SUBDIR)../config.mak
 NAME = avcodec
 FFLIBS = avutil
 
-HEADERS = avcodec.h avfft.h dxva2.h opt.h vaapi.h vdpau.h xvmc.h
+HEADERS = avcodec.h avfft.h dxva2.h opt.h vaapi.h vdpau.h version.h xvmc.h
 
 OBJS = allcodecs.o                                                      \
        audioconvert.o                                                   \
@@ -11,8 +11,8 @@ OBJS = allcodecs.o                                                      \
        bitstream.o                                                      \
        bitstream_filter.o                                               \
        dsputil.o                                                        \
-       eval.o                                                           \
        faanidct.o                                                       \
+       fmtconvert.o                                                     \
        imgconvert.o                                                     \
        jrevdct.o                                                        \
        opt.o                                                            \
@@ -26,31 +26,40 @@ OBJS = allcodecs.o                                                      \
 
 # parts needed for many different codecs
 OBJS-$(CONFIG_AANDCT)                  += aandcttab.o
+OBJS-$(CONFIG_AC3DSP)                  += ac3dsp.o
 OBJS-$(CONFIG_ENCODERS)                += faandct.o jfdctfst.o jfdctint.o
 OBJS-$(CONFIG_DCT)                     += dct.o
 OBJS-$(CONFIG_DWT)                     += dwt.o
 OBJS-$(CONFIG_DXVA2)                   += dxva2.o
-FFT-OBJS-$(CONFIG_HARDCODED_TABLES)    += cos_tables.o
-OBJS-$(CONFIG_FFT)                     += avfft.o fft.o $(FFT-OBJS-yes)
+FFT-OBJS-$(CONFIG_HARDCODED_TABLES)    += cos_tables.o cos_fixed_tables.o
+OBJS-$(CONFIG_FFT)                     += avfft.o fft_fixed.o fft_float.o \
+                                          $(FFT-OBJS-yes)
 OBJS-$(CONFIG_GOLOMB)                  += golomb.o
-OBJS-$(CONFIG_H264DSP)                 += h264dsp.o h264idct.o h264pred.o
+OBJS-$(CONFIG_H264DSP)                 += h264dsp.o h264idct.o
+OBJS-$(CONFIG_H264PRED)                += h264pred.o
+OBJS-$(CONFIG_HUFFMAN)                 += huffman.o
 OBJS-$(CONFIG_LPC)                     += lpc.o
 OBJS-$(CONFIG_LSP)                     += lsp.o
-OBJS-$(CONFIG_MDCT)                    += mdct.o
+OBJS-$(CONFIG_MDCT)                    += mdct_fixed.o mdct_float.o
 RDFT-OBJS-$(CONFIG_HARDCODED_TABLES)   += sin_tables.o
 OBJS-$(CONFIG_RDFT)                    += rdft.o $(RDFT-OBJS-yes)
+OBJS-$(CONFIG_SINEWIN)                 += sinewin.o
 OBJS-$(CONFIG_VAAPI)                   += vaapi.o
 OBJS-$(CONFIG_VDPAU)                   += vdpau.o
 
 # decoders/encoders/hardware accelerators
-OBJS-$(CONFIG_AAC_DECODER)             += aac.o aactab.o aacsbr.o
+OBJS-$(CONFIG_A64MULTI_ENCODER)        += a64multienc.o elbg.o
+OBJS-$(CONFIG_A64MULTI5_ENCODER)       += a64multienc.o elbg.o
+OBJS-$(CONFIG_AAC_DECODER)             += aacdec.o aactab.o aacsbr.o aacps.o \
+                                          aacadtsdec.o mpeg4audio.o kbdwin.o
 OBJS-$(CONFIG_AAC_ENCODER)             += aacenc.o aaccoder.o    \
                                           aacpsy.o aactab.o      \
                                           psymodel.o iirfilter.o \
-                                          mpeg4audio.o
+                                          mpeg4audio.o kbdwin.o
 OBJS-$(CONFIG_AASC_DECODER)            += aasc.o msrledec.o
-OBJS-$(CONFIG_AC3_DECODER)             += ac3dec.o ac3dec_data.o ac3.o
-OBJS-$(CONFIG_AC3_ENCODER)             += ac3enc.o ac3tab.o ac3.o
+OBJS-$(CONFIG_AC3_DECODER)             += ac3dec.o ac3dec_data.o ac3.o kbdwin.o
+OBJS-$(CONFIG_AC3_ENCODER)             += ac3enc_float.o ac3tab.o ac3.o kbdwin.o
+OBJS-$(CONFIG_AC3_FIXED_ENCODER)       += ac3enc_fixed.o ac3tab.o ac3.o
 OBJS-$(CONFIG_ALAC_DECODER)            += alac.o
 OBJS-$(CONFIG_ALAC_ENCODER)            += alacenc.o
 OBJS-$(CONFIG_ALS_DECODER)             += alsdec.o bgmc.o mpeg4audio.o
@@ -58,9 +67,16 @@ OBJS-$(CONFIG_AMRNB_DECODER)           += amrnbdec.o celp_filters.o   \
                                           celp_math.o acelp_filters.o \
                                           acelp_vectors.o             \
                                           acelp_pitch_delay.o
+OBJS-$(CONFIG_AMRWB_DECODER)           += amrwbdec.o celp_filters.o   \
+                                          celp_math.o acelp_filters.o \
+                                          acelp_vectors.o             \
+                                          acelp_pitch_delay.o lsp.o
 OBJS-$(CONFIG_AMV_DECODER)             += sp5xdec.o mjpegdec.o mjpeg.o
 OBJS-$(CONFIG_ANM_DECODER)             += anm.o
+OBJS-$(CONFIG_ANSI_DECODER)            += ansi.o cga_data.o
 OBJS-$(CONFIG_APE_DECODER)             += apedec.o
+OBJS-$(CONFIG_ASS_DECODER)             += assdec.o ass.o
+OBJS-$(CONFIG_ASS_ENCODER)             += assenc.o ass.o
 OBJS-$(CONFIG_ASV1_DECODER)            += asv1.o mpeg12data.o
 OBJS-$(CONFIG_ASV1_ENCODER)            += asv1.o mpeg12data.o
 OBJS-$(CONFIG_ASV2_DECODER)            += asv1.o mpeg12data.o
@@ -88,6 +104,7 @@ OBJS-$(CONFIG_COOK_DECODER)            += cook.o
 OBJS-$(CONFIG_CSCD_DECODER)            += cscd.o
 OBJS-$(CONFIG_CYUV_DECODER)            += cyuv.o
 OBJS-$(CONFIG_DCA_DECODER)             += dca.o synth_filter.o dcadsp.o
+OBJS-$(CONFIG_DFA_DECODER)             += dfa.o
 OBJS-$(CONFIG_DNXHD_DECODER)           += dnxhddec.o dnxhddata.o
 OBJS-$(CONFIG_DNXHD_ENCODER)           += dnxhdenc.o dnxhddata.o       \
                                           mpegvideo_enc.o motion_est.o \
@@ -127,10 +144,12 @@ OBJS-$(CONFIG_FLASHSV_DECODER)         += flashsv.o
 OBJS-$(CONFIG_FLASHSV_ENCODER)         += flashsvenc.o
 OBJS-$(CONFIG_FLIC_DECODER)            += flicvideo.o
 OBJS-$(CONFIG_FOURXM_DECODER)          += 4xm.o
-OBJS-$(CONFIG_FRAPS_DECODER)           += fraps.o huffman.o
+OBJS-$(CONFIG_FRAPS_DECODER)           += fraps.o
 OBJS-$(CONFIG_FRWU_DECODER)            += frwu.o
 OBJS-$(CONFIG_GIF_DECODER)             += gifdec.o lzw.o
 OBJS-$(CONFIG_GIF_ENCODER)             += gif.o lzwenc.o
+OBJS-$(CONFIG_GSM_DECODER)             += gsmdec.o gsmdec_data.o msgsmdec.o
+OBJS-$(CONFIG_GSM_MS_DECODER)          += gsmdec.o gsmdec_data.o msgsmdec.o
 OBJS-$(CONFIG_H261_DECODER)            += h261dec.o h261.o \
                                           mpegvideo.o error_resilience.o
 OBJS-$(CONFIG_H261_ENCODER)            += h261enc.o h261.o             \
@@ -153,7 +172,6 @@ OBJS-$(CONFIG_H264_DECODER)            += h264.o                               \
                                           h264_refs.o h264_cavlc.o h264_cabac.o\
                                           mpegvideo.o error_resilience.o
 OBJS-$(CONFIG_H264_DXVA2_HWACCEL)      += dxva2_h264.o
-OBJS-$(CONFIG_H264_ENCODER)            += h264enc.o h264dspenc.o
 OBJS-$(CONFIG_H264_VAAPI_HWACCEL)      += vaapi_h264.o
 OBJS-$(CONFIG_HUFFYUV_DECODER)         += huffyuv.o
 OBJS-$(CONFIG_HUFFYUV_ENCODER)         += huffyuv.o
@@ -169,8 +187,10 @@ OBJS-$(CONFIG_INTERPLAY_VIDEO_DECODER) += interplayvideo.o
 OBJS-$(CONFIG_JPEGLS_DECODER)          += jpeglsdec.o jpegls.o \
                                           mjpegdec.o mjpeg.o
 OBJS-$(CONFIG_JPEGLS_ENCODER)          += jpeglsenc.o jpegls.o
+OBJS-$(CONFIG_JV_DECODER)              += jvdec.o
 OBJS-$(CONFIG_KGV1_DECODER)            += kgv1dec.o
 OBJS-$(CONFIG_KMVC_DECODER)            += kmvc.o
+OBJS-$(CONFIG_LAGARITH_DECODER)        += lagarith.o lagarithrac.o
 OBJS-$(CONFIG_LJPEG_ENCODER)           += ljpegenc.o mjpegenc.o mjpeg.o \
                                           mpegvideo_enc.o motion_est.o  \
                                           ratecontrol.o mpeg12data.o    \
@@ -192,17 +212,28 @@ OBJS-$(CONFIG_MMVIDEO_DECODER)         += mmvideo.o
 OBJS-$(CONFIG_MOTIONPIXELS_DECODER)    += motionpixels.o
 OBJS-$(CONFIG_MP1_DECODER)             += mpegaudiodec.o mpegaudiodecheader.o \
                                           mpegaudio.o mpegaudiodata.o
+OBJS-$(CONFIG_MP1FLOAT_DECODER)        += mpegaudiodec_float.o mpegaudiodecheader.o \
+                                          mpegaudio.o mpegaudiodata.o
 OBJS-$(CONFIG_MP2_DECODER)             += mpegaudiodec.o mpegaudiodecheader.o \
                                           mpegaudio.o mpegaudiodata.o
 OBJS-$(CONFIG_MP2_ENCODER)             += mpegaudioenc.o mpegaudio.o \
                                           mpegaudiodata.o
+OBJS-$(CONFIG_MP2FLOAT_DECODER)        += mpegaudiodec_float.o mpegaudiodecheader.o \
+                                          mpegaudio.o mpegaudiodata.o
 OBJS-$(CONFIG_MP3ADU_DECODER)          += mpegaudiodec.o mpegaudiodecheader.o \
                                           mpegaudio.o mpegaudiodata.o
+OBJS-$(CONFIG_MP3ADUFLOAT_DECODER)     += mpegaudiodec_float.o mpegaudiodecheader.o \
+                                          mpegaudio.o mpegaudiodata.o
 OBJS-$(CONFIG_MP3ON4_DECODER)          += mpegaudiodec.o mpegaudiodecheader.o \
                                           mpegaudio.o mpegaudiodata.o         \
                                           mpeg4audio.o
+OBJS-$(CONFIG_MP3ON4FLOAT_DECODER)     += mpegaudiodec_float.o mpegaudiodecheader.o \
+                                          mpegaudio.o mpegaudiodata.o         \
+                                          mpeg4audio.o
 OBJS-$(CONFIG_MP3_DECODER)             += mpegaudiodec.o mpegaudiodecheader.o \
                                           mpegaudio.o mpegaudiodata.o
+OBJS-$(CONFIG_MP3FLOAT_DECODER)        += mpegaudiodec_float.o mpegaudiodecheader.o \
+                                          mpegaudio.o mpegaudiodata.o
 OBJS-$(CONFIG_MPC7_DECODER)            += mpc7.o mpc.o mpegaudiodec.o      \
                                           mpegaudiodecheader.o mpegaudio.o \
                                           mpegaudiodata.o
@@ -218,6 +249,7 @@ OBJS-$(CONFIG_MPEG1VIDEO_ENCODER)      += mpeg12enc.o mpegvideo_enc.o \
                                           motion_est.o ratecontrol.o  \
                                           mpeg12.o mpeg12data.o       \
                                           mpegvideo.o error_resilience.o
+OBJS-$(CONFIG_MPEG2_DXVA2_HWACCEL)     += dxva2_mpeg2.o
 OBJS-$(CONFIG_MPEG2_VAAPI_HWACCEL)     += vaapi_mpeg2.o
 OBJS-$(CONFIG_MPEG2VIDEO_DECODER)      += mpeg12.o mpeg12data.o \
                                           mpegvideo.o error_resilience.o
@@ -240,6 +272,7 @@ OBJS-$(CONFIG_MSMPEG4V3_ENCODER)       += msmpeg4.o msmpeg4data.o h263dec.o \
 OBJS-$(CONFIG_MSRLE_DECODER)           += msrle.o msrledec.o
 OBJS-$(CONFIG_MSVIDEO1_DECODER)        += msvideo1.o
 OBJS-$(CONFIG_MSZH_DECODER)            += lcldec.o
+OBJS-$(CONFIG_MXPEG_DECODER)           += mxpegdec.o
 OBJS-$(CONFIG_NELLYMOSER_DECODER)      += nellymoserdec.o nellymoser.o
 OBJS-$(CONFIG_NELLYMOSER_ENCODER)      += nellymoserenc.o nellymoser.o
 OBJS-$(CONFIG_NUV_DECODER)             += nuv.o rtjpeg.o
@@ -254,6 +287,7 @@ OBJS-$(CONFIG_PGM_ENCODER)             += pnmenc.o pnm.o
 OBJS-$(CONFIG_PGMYUV_DECODER)          += pnmdec.o pnm.o
 OBJS-$(CONFIG_PGMYUV_ENCODER)          += pnmenc.o pnm.o
 OBJS-$(CONFIG_PGSSUB_DECODER)          += pgssubdec.o
+OBJS-$(CONFIG_PICTOR_DECODER)          += pictordec.o cga_data.o
 OBJS-$(CONFIG_PNG_DECODER)             += png.o pngdec.o
 OBJS-$(CONFIG_PNG_ENCODER)             += png.o pngenc.o
 OBJS-$(CONFIG_PPM_DECODER)             += pnmdec.o pnm.o
@@ -269,8 +303,10 @@ OBJS-$(CONFIG_QDRAW_DECODER)           += qdrw.o
 OBJS-$(CONFIG_QPEG_DECODER)            += qpeg.o
 OBJS-$(CONFIG_QTRLE_DECODER)           += qtrle.o
 OBJS-$(CONFIG_QTRLE_ENCODER)           += qtrleenc.o
+OBJS-$(CONFIG_R10K_DECODER)            += r210dec.o
 OBJS-$(CONFIG_R210_DECODER)            += r210dec.o
-OBJS-$(CONFIG_RA_144_DECODER)          += ra144.o celp_filters.o
+OBJS-$(CONFIG_RA_144_DECODER)          += ra144dec.o ra144.o celp_filters.o
+OBJS-$(CONFIG_RA_144_ENCODER)          += ra144enc.o ra144.o celp_filters.o
 OBJS-$(CONFIG_RA_288_DECODER)          += ra288.o celp_math.o celp_filters.o
 OBJS-$(CONFIG_RAWVIDEO_DECODER)        += rawdec.o
 OBJS-$(CONFIG_RAWVIDEO_ENCODER)        += rawenc.o
@@ -305,10 +341,8 @@ OBJS-$(CONFIG_SNOW_ENCODER)            += snow.o rangecoder.o motion_est.o \
                                           ituh263enc.o mpegvideo_enc.o     \
                                           mpeg12data.o
 OBJS-$(CONFIG_SOL_DPCM_DECODER)        += dpcm.o
-OBJS-$(CONFIG_SONIC_DECODER)           += sonic.o
-OBJS-$(CONFIG_SONIC_ENCODER)           += sonic.o
-OBJS-$(CONFIG_SONIC_LS_ENCODER)        += sonic.o
 OBJS-$(CONFIG_SP5X_DECODER)            += sp5xdec.o mjpegdec.o mjpeg.o
+OBJS-$(CONFIG_SRT_DECODER)             += srtdec.o ass.o
 OBJS-$(CONFIG_SUNRAST_DECODER)         += sunrast.o
 OBJS-$(CONFIG_SVQ1_DECODER)            += svq1dec.o svq1.o h263.o \
                                           mpegvideo.o error_resilience.o
@@ -359,9 +393,10 @@ OBJS-$(CONFIG_VORBIS_ENCODER)          += vorbis_enc.o vorbis.o \
                                           vorbis_data.o
 OBJS-$(CONFIG_VP3_DECODER)             += vp3.o vp3dsp.o
 OBJS-$(CONFIG_VP5_DECODER)             += vp5.o vp56.o vp56data.o vp56dsp.o \
-                                          vp3dsp.o
+                                          vp3dsp.o vp56rac.o
 OBJS-$(CONFIG_VP6_DECODER)             += vp6.o vp56.o vp56data.o vp56dsp.o \
-                                          vp3dsp.o vp6dsp.o huffman.o
+                                          vp3dsp.o vp6dsp.o vp56rac.o
+OBJS-$(CONFIG_VP8_DECODER)             += vp8.o vp8dsp.o vp56rac.o
 OBJS-$(CONFIG_VQA_DECODER)             += vqavideo.o
 OBJS-$(CONFIG_WAVPACK_DECODER)         += wavpack.o
 OBJS-$(CONFIG_WMAPRO_DECODER)          += wmaprodec.o wma.o
@@ -383,7 +418,7 @@ OBJS-$(CONFIG_WNV1_DECODER)            += wnv1.o
 OBJS-$(CONFIG_WS_SND1_DECODER)         += ws-snd1.o
 OBJS-$(CONFIG_XAN_DPCM_DECODER)        += dpcm.o
 OBJS-$(CONFIG_XAN_WC3_DECODER)         += xan.o
-OBJS-$(CONFIG_XAN_WC4_DECODER)         += xan.o
+OBJS-$(CONFIG_XAN_WC4_DECODER)         += xxan.o
 OBJS-$(CONFIG_XL_DECODER)              += xl.o
 OBJS-$(CONFIG_XSUB_DECODER)            += xsubdec.o
 OBJS-$(CONFIG_XSUB_ENCODER)            += xsubenc.o
@@ -407,6 +442,7 @@ OBJS-$(CONFIG_PCM_F64BE_DECODER)          += pcm.o
 OBJS-$(CONFIG_PCM_F64BE_ENCODER)          += pcm.o
 OBJS-$(CONFIG_PCM_F64LE_DECODER)          += pcm.o
 OBJS-$(CONFIG_PCM_F64LE_ENCODER)          += pcm.o
+OBJS-$(CONFIG_PCM_LXF_DECODER)            += pcm.o
 OBJS-$(CONFIG_PCM_MULAW_DECODER)          += pcm.o
 OBJS-$(CONFIG_PCM_MULAW_ENCODER)          += pcm.o
 OBJS-$(CONFIG_PCM_S8_DECODER)             += pcm.o
@@ -453,6 +489,8 @@ OBJS-$(CONFIG_ADPCM_EA_R1_DECODER)        += adpcm.o
 OBJS-$(CONFIG_ADPCM_EA_R2_DECODER)        += adpcm.o
 OBJS-$(CONFIG_ADPCM_EA_R3_DECODER)        += adpcm.o
 OBJS-$(CONFIG_ADPCM_EA_XAS_DECODER)       += adpcm.o
+OBJS-$(CONFIG_ADPCM_G722_DECODER)         += g722.o
+OBJS-$(CONFIG_ADPCM_G722_ENCODER)         += g722.o
 OBJS-$(CONFIG_ADPCM_G726_DECODER)         += g726.o
 OBJS-$(CONFIG_ADPCM_G726_ENCODER)         += g726.o
 OBJS-$(CONFIG_ADPCM_IMA_AMV_DECODER)      += adpcm.o
@@ -491,24 +529,28 @@ OBJS-$(CONFIG_GXF_DEMUXER)             += mpeg12data.o
 OBJS-$(CONFIG_IFF_DEMUXER)             += iff.o
 OBJS-$(CONFIG_MATROSKA_AUDIO_MUXER)    += xiph.o mpeg4audio.o \
                                           flacdec.o flacdata.o flac.o
-OBJS-$(CONFIG_MATROSKA_DEMUXER)        += mpeg4audio.o
+OBJS-$(CONFIG_MATROSKA_DEMUXER)        += mpeg4audio.o mpegaudiodata.o
 OBJS-$(CONFIG_MATROSKA_MUXER)          += xiph.o mpeg4audio.o \
-                                          flacdec.o flacdata.o flac.o
+                                          flacdec.o flacdata.o flac.o \
+                                          mpegaudiodata.o
 OBJS-$(CONFIG_MOV_DEMUXER)             += mpeg4audio.o mpegaudiodata.o
+OBJS-$(CONFIG_MOV_MUXER)               += mpeg4audio.o mpegaudiodata.o
 OBJS-$(CONFIG_MPEGTS_MUXER)            += mpegvideo.o mpeg4audio.o
+OBJS-$(CONFIG_MPEGTS_DEMUXER)          += mpeg4audio.o mpegaudiodata.o
 OBJS-$(CONFIG_NUT_MUXER)               += mpegaudiodata.o
 OBJS-$(CONFIG_OGG_DEMUXER)             += flacdec.o flacdata.o flac.o \
                                           dirac.o mpeg12data.o
 OBJS-$(CONFIG_OGG_MUXER)               += xiph.o flacdec.o flacdata.o flac.o
-OBJS-$(CONFIG_RTP_MUXER)               += mpegvideo.o
+OBJS-$(CONFIG_RTP_MUXER)               += mpegvideo.o xiph.o
+OBJS-$(CONFIG_SPDIF_DEMUXER)           += aacadtsdec.o mpeg4audio.o
 OBJS-$(CONFIG_WEBM_MUXER)              += xiph.o mpeg4audio.o \
-                                          flacdec.o flacdata.o flac.o
+                                          flacdec.o flacdata.o flac.o \
+                                          mpegaudiodata.o
 
 # external codec libraries
 OBJS-$(CONFIG_LIBDIRAC_DECODER)           += libdiracdec.o
 OBJS-$(CONFIG_LIBDIRAC_ENCODER)           += libdiracenc.o libdirac_libschro.o
 OBJS-$(CONFIG_LIBFAAC_ENCODER)            += libfaac.o
-OBJS-$(CONFIG_LIBFAAD_DECODER)            += libfaad.o
 OBJS-$(CONFIG_LIBGSM_DECODER)             += libgsm.o
 OBJS-$(CONFIG_LIBGSM_ENCODER)             += libgsm.o
 OBJS-$(CONFIG_LIBGSM_MS_DECODER)          += libgsm.o
@@ -526,15 +568,18 @@ OBJS-$(CONFIG_LIBSCHROEDINGER_ENCODER)    += libschroedingerenc.o \
                                              libdirac_libschro.o
 OBJS-$(CONFIG_LIBSPEEX_DECODER)           += libspeexdec.o
 OBJS-$(CONFIG_LIBTHEORA_ENCODER)          += libtheoraenc.o
-OBJS-$(CONFIG_LIBVORBIS_ENCODER)          += libvorbis.o
+OBJS-$(CONFIG_LIBVO_AACENC_ENCODER)       += libvo-aacenc.o mpeg4audio.o
+OBJS-$(CONFIG_LIBVO_AMRWBENC_ENCODER)     += libvo-amrwbenc.o
+OBJS-$(CONFIG_LIBVORBIS_ENCODER)          += libvorbis.o vorbis_data.o
 OBJS-$(CONFIG_LIBVPX_DECODER)             += libvpxdec.o
 OBJS-$(CONFIG_LIBVPX_ENCODER)             += libvpxenc.o
 OBJS-$(CONFIG_LIBX264_ENCODER)            += libx264.o
-OBJS-$(CONFIG_LIBXVID_ENCODER)            += libxvidff.o libxvid_rc.o
+OBJS-$(CONFIG_LIBXAVS_ENCODER)            += libxavs.o
+OBJS-$(CONFIG_LIBXVID)                    += libxvidff.o libxvid_rc.o
 
 # parsers
 OBJS-$(CONFIG_AAC_PARSER)              += aac_parser.o aac_ac3_parser.o \
-                                          mpeg4audio.o
+                                          aacadtsdec.o mpeg4audio.o
 OBJS-$(CONFIG_AC3_PARSER)              += ac3_parser.o ac3tab.o \
                                           aac_ac3_parser.o
 OBJS-$(CONFIG_CAVSVIDEO_PARSER)        += cavs_parser.o
@@ -543,6 +588,7 @@ OBJS-$(CONFIG_DIRAC_PARSER)            += dirac_parser.o
 OBJS-$(CONFIG_DNXHD_PARSER)            += dnxhd_parser.o
 OBJS-$(CONFIG_DVBSUB_PARSER)           += dvbsub_parser.o
 OBJS-$(CONFIG_DVDSUB_PARSER)           += dvdsub_parser.o
+OBJS-$(CONFIG_FLAC_PARSER)             += flac_parser.o flacdata.o flac.o
 OBJS-$(CONFIG_H261_PARSER)             += h261_parser.o
 OBJS-$(CONFIG_H263_PARSER)             += h263_parser.o
 OBJS-$(CONFIG_H264_PARSER)             += h264_parser.o h264.o            \
@@ -551,6 +597,7 @@ OBJS-$(CONFIG_H264_PARSER)             += h264_parser.o h264.o            \
                                           h264_loopfilter.o h264_cabac.o \
                                           h264_cavlc.o h264_ps.o \
                                           mpegvideo.o error_resilience.o
+OBJS-$(CONFIG_AAC_LATM_PARSER)         += latm_parser.o
 OBJS-$(CONFIG_MJPEG_PARSER)            += mjpeg_parser.o
 OBJS-$(CONFIG_MLP_PARSER)              += mlp_parser.o mlp.o
 OBJS-$(CONFIG_MPEG4VIDEO_PARSER)       += mpeg4video_parser.o h263.o \
@@ -567,12 +614,16 @@ OBJS-$(CONFIG_VC1_PARSER)              += vc1_parser.o vc1.o vc1data.o \
                                           msmpeg4.o msmpeg4data.o mpeg4video.o \
                                           h263.o mpegvideo.o error_resilience.o
 OBJS-$(CONFIG_VP3_PARSER)              += vp3_parser.o
+OBJS-$(CONFIG_VP8_PARSER)              += vp8_parser.o
 
 # bitstream filters
-OBJS-$(CONFIG_AAC_ADTSTOASC_BSF)          += aac_adtstoasc_bsf.o
+OBJS-$(CONFIG_AAC_ADTSTOASC_BSF)          += aac_adtstoasc_bsf.o aacadtsdec.o \
+                                             mpeg4audio.o
+OBJS-$(CONFIG_CHOMP_BSF)                  += chomp_bsf.o
 OBJS-$(CONFIG_DUMP_EXTRADATA_BSF)         += dump_extradata_bsf.o
 OBJS-$(CONFIG_H264_MP4TOANNEXB_BSF)       += h264_mp4toannexb_bsf.o
 OBJS-$(CONFIG_IMX_DUMP_HEADER_BSF)        += imx_dump_header_bsf.o
+OBJS-$(CONFIG_MJPEG2JPEG_BSF)             += mjpeg2jpeg_bsf.o mjpeg.o
 OBJS-$(CONFIG_MJPEGA_DUMP_HEADER_BSF)     += mjpega_dump_header_bsf.o
 OBJS-$(CONFIG_MOV2TEXTSUB_BSF)            += movsub_bsf.o
 OBJS-$(CONFIG_MP3_HEADER_COMPRESS_BSF)    += mp3_header_compress_bsf.o
@@ -583,13 +634,17 @@ OBJS-$(CONFIG_REMOVE_EXTRADATA_BSF)       += remove_extradata_bsf.o
 OBJS-$(CONFIG_TEXT2MOVSUB_BSF)            += movsub_bsf.o
 
 # thread libraries
-OBJS-$(HAVE_BEOSTHREADS)               += beosthread.o
-OBJS-$(HAVE_OS2THREADS)                += os2thread.o
 OBJS-$(HAVE_PTHREADS)                  += pthread.o
 OBJS-$(HAVE_W32THREADS)                += w32thread.o
 
 OBJS-$(CONFIG_MLIB)                    += mlib/dsputil_mlib.o           \
 
+# inverse.o contains the ff_inverse table definition, which is used by
+# the FASTDIV macro (from libavutil); since referencing the external
+# table has a negative effect on performance, copy it in libavcodec as
+# well.
+OBJS-$(!CONFIG_SMALL)                  += inverse.o
+
 -include $(SUBDIR)$(ARCH)/Makefile
 
 SKIPHEADERS                             = %_tablegen.h
@@ -603,8 +658,7 @@ SKIPHEADERS                            += mpegaudio3.h
 
 EXAMPLES = api
 
-TESTPROGS = cabac dct eval fft h264 iirfilter rangecoder snow
-TESTPROGS-$(ARCH_X86) += x86/cpuid
+TESTPROGS = cabac dct eval fft fft-fixed h264 iirfilter rangecoder snow
 TESTPROGS-$(HAVE_MMX) += motion
 TESTOBJS = dctref.o
 
@@ -621,6 +675,9 @@ $(SUBDIR)dct-test$(EXESUF): $(SUBDIR)dctref.o
 $(SUBDIR)cos_tables.c: $(SUBDIR)costablegen$(HOSTEXESUF)
 	$(M)./$< > $@
 
+$(SUBDIR)cos_fixed_tables.c: $(SUBDIR)costablegen$(HOSTEXESUF)
+	$(M)./$< cos fixed > $@
+
 $(SUBDIR)sin_tables.c: $(SUBDIR)costablegen$(HOSTEXESUF)
 	$(M)./$< sin > $@
 
@@ -638,17 +695,25 @@ else
 $(SUBDIR)%_tablegen$(HOSTEXESUF): HOSTCFLAGS += -DCONFIG_SMALL=0
 endif
 
-$(SUBDIR)%_tablegen$(HOSTEXESUF): $(SUBDIR)%_tablegen.c $(SUBDIR)tableprint.c
-	$(HOSTCC) $(HOSTCFLAGS) $(HOSTLDFLAGS) -o $@ $^ $(HOSTLIBS)
+$(SUBDIR)%_tablegen$(HOSTEXESUF): $(SUBDIR)%_tablegen.c $(SUBDIR)%_tablegen.h $(SUBDIR)tableprint.c
+	$(HOSTCC) $(HOSTCFLAGS) $(HOSTLDFLAGS) -o $@ $(filter %.c,$^) $(HOSTLIBS)
+
+GEN_HEADERS = cbrt_tables.h aacps_tables.h aac_tables.h dv_tables.h     \
+              sinewin_tables.h mpegaudio_tables.h motionpixels_tables.h \
+              pcm_tables.h qdm2_tables.h
+GEN_HEADERS := $(addprefix $(SUBDIR), $(GEN_HEADERS))
 
-$(SUBDIR)%_tables.h: $(SUBDIR)%_tablegen$(HOSTEXESUF)
+$(GEN_HEADERS): $(SUBDIR)%_tables.h: $(SUBDIR)%_tablegen$(HOSTEXESUF)
 	$(M)./$< > $@
 
 ifdef CONFIG_HARDCODED_TABLES
-$(SUBDIR)aac.o: $(SUBDIR)cbrt_tables.h
+$(SUBDIR)aacdec.o: $(SUBDIR)cbrt_tables.h
+$(SUBDIR)aacps.o: $(SUBDIR)aacps_tables.h
+$(SUBDIR)aactab.o: $(SUBDIR)aac_tables.h
 $(SUBDIR)dv.o: $(SUBDIR)dv_tables.h
-$(SUBDIR)mdct.o: $(SUBDIR)mdct_tables.h
+$(SUBDIR)sinewin.o: $(SUBDIR)sinewin_tables.h
 $(SUBDIR)mpegaudiodec.o: $(SUBDIR)mpegaudio_tables.h
+$(SUBDIR)mpegaudiodec_float.o: $(SUBDIR)mpegaudio_tables.h
 $(SUBDIR)motionpixels.o: $(SUBDIR)motionpixels_tables.h
 $(SUBDIR)pcm.o: $(SUBDIR)pcm_tables.h
 $(SUBDIR)qdm2.o: $(SUBDIR)qdm2_tables.h
diff --git a/libavcodec/a64colors.h b/libavcodec/a64colors.h
new file mode 100644
index 0000000..d977426
--- /dev/null
+++ b/libavcodec/a64colors.h
@@ -0,0 +1,52 @@
+/*
+ * a64 video encoder - c64 colors in rgb (Pepto)
+ * Copyright (c) 2009 Tobias Bindhammer
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * a64 video encoder - c64 colors in rgb
+ */
+
+#ifndef AVCODEC_A64COLORS_H
+#define AVCODEC_A64COLORS_H
+
+#include <stdint.h>
+
+/* c64 palette in RGB */
+static const uint8_t a64_palette[16][3] = {
+    {0x00, 0x00, 0x00},
+    {0xff, 0xff, 0xff},
+    {0x68, 0x37, 0x2b},
+    {0x70, 0xa4, 0xb2},
+    {0x6f, 0x3d, 0x86},
+    {0x58, 0x8d, 0x43},
+    {0x35, 0x28, 0x79},
+    {0xb8, 0xc7, 0x6f},
+    {0x6f, 0x4f, 0x25},
+    {0x43, 0x39, 0x00},
+    {0x9a, 0x67, 0x59},
+    {0x44, 0x44, 0x44},
+    {0x6c, 0x6c, 0x6c},
+    {0x9a, 0xd2, 0x84},
+    {0x6c, 0x5e, 0xb5},
+    {0x95, 0x95, 0x95},
+};
+
+#endif /* AVCODEC_A64COLORS_H */
diff --git a/libavcodec/a64enc.h b/libavcodec/a64enc.h
new file mode 100644
index 0000000..b64b952
--- /dev/null
+++ b/libavcodec/a64enc.h
@@ -0,0 +1,55 @@
+/*
+ * a64 video encoder - basic headers
+ * Copyright (c) 2009 Tobias Bindhammer
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * a64 video encoder - basic headers
+ */
+
+#ifndef AVCODEC_A64ENC_H
+#define AVCODEC_A64ENC_H
+
+#include "libavutil/lfg.h"
+#include "avcodec.h"
+
+#define C64XRES 320
+#define C64YRES 200
+
+typedef struct A64Context {
+    /* general variables */
+    AVFrame picture;
+
+    /* variables for multicolor modes */
+    AVLFG randctx;
+    int mc_lifetime;
+    int mc_use_5col;
+    int mc_frame_counter;
+    int *mc_meta_charset;
+    int *mc_charmap;
+    int *mc_best_cb;
+    int mc_luma_vals[5];
+    uint8_t *mc_charset;
+    uint8_t *mc_colram;
+    uint8_t *mc_palette;
+    int mc_pal_size;
+} A64Context;
+
+#endif /* AVCODEC_A64ENC_H */
diff --git a/libavcodec/a64multienc.c b/libavcodec/a64multienc.c
new file mode 100644
index 0000000..3b45e5a
--- /dev/null
+++ b/libavcodec/a64multienc.c
@@ -0,0 +1,389 @@
+/*
+ * a64 video encoder - multicolor modes
+ * Copyright (c) 2009 Tobias Bindhammer
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * a64 video encoder - multicolor modes
+ */
+
+#include "a64enc.h"
+#include "a64colors.h"
+#include "a64tables.h"
+#include "elbg.h"
+#include "libavutil/intreadwrite.h"
+
+#define DITHERSTEPS   8
+#define CHARSET_CHARS 256
+#define INTERLACED    1
+#define CROP_SCREENS  1
+
+/* gray gradient */
+static const int mc_colors[5]={0x0,0xb,0xc,0xf,0x1};
+
+/* other possible gradients - to be tested */
+//static const int mc_colors[5]={0x0,0x8,0xa,0xf,0x7};
+//static const int mc_colors[5]={0x0,0x9,0x8,0xa,0x3};
+
+static void to_meta_with_crop(AVCodecContext *avctx, AVFrame *p, int *dest)
+{
+    int blockx, blocky, x, y;
+    int luma = 0;
+    int height = FFMIN(avctx->height, C64YRES);
+    int width  = FFMIN(avctx->width , C64XRES);
+    uint8_t *src = p->data[0];
+
+    for (blocky = 0; blocky < C64YRES; blocky += 8) {
+        for (blockx = 0; blockx < C64XRES; blockx += 8) {
+            for (y = blocky; y < blocky + 8 && y < C64YRES; y++) {
+                for (x = blockx; x < blockx + 8 && x < C64XRES; x += 2) {
+                    if(x < width && y < height) {
+                        /* build average over 2 pixels */
+                        luma = (src[(x + 0 + y * p->linesize[0])] +
+                                src[(x + 1 + y * p->linesize[0])]) / 2;
+                        /* write blocks as linear data now so they are suitable for elbg */
+                        dest[0] = luma;
+                    }
+                    dest++;
+                }
+            }
+        }
+    }
+}
+
+static void render_charset(AVCodecContext *avctx, uint8_t *charset,
+                           uint8_t *colrammap)
+{
+    A64Context *c = avctx->priv_data;
+    uint8_t row1, row2;
+    int charpos, x, y;
+    int a, b;
+    uint8_t pix;
+    int lowdiff, highdiff;
+    int *best_cb = c->mc_best_cb;
+    static uint8_t index1[256];
+    static uint8_t index2[256];
+    static uint8_t dither[256];
+    int i;
+    int distance;
+
+    /* generate lookup-tables for dither and index before looping */
+    i = 0;
+    for (a=0; a < 256; a++) {
+        if(i < c->mc_pal_size -1 && a == c->mc_luma_vals[i + 1]) {
+            distance = c->mc_luma_vals[i + 1] - c->mc_luma_vals[i];
+            for(b = 0; b <= distance; b++) {
+                  dither[c->mc_luma_vals[i] + b] = b * (DITHERSTEPS - 1) / distance;
+            }
+            i++;
+        }
+        if(i >= c->mc_pal_size - 1) dither[a] = 0;
+        index1[a] = i;
+        index2[a] = FFMIN(i + 1, c->mc_pal_size - 1);
+    }
+
+    /* and render charset */
+    for (charpos = 0; charpos < CHARSET_CHARS; charpos++) {
+        lowdiff  = 0;
+        highdiff = 0;
+        for (y = 0; y < 8; y++) {
+            row1 = 0; row2 = 0;
+            for (x = 0; x < 4; x++) {
+                pix = best_cb[y * 4 + x];
+
+                /* accumulate error for brightest/darkest color */
+                if (index1[pix] >= 3)
+                    highdiff += pix - c->mc_luma_vals[3];
+                if (index1[pix] < 1)
+                    lowdiff += c->mc_luma_vals[1] - pix;
+
+                row1 <<= 2;
+
+                if (INTERLACED) {
+                    row2 <<= 2;
+                    if (interlaced_dither_patterns[dither[pix]][(y & 3) * 2 + 0][x & 3])
+                        row1 |= 3-(index2[pix] & 3);
+                    else
+                        row1 |= 3-(index1[pix] & 3);
+
+                    if (interlaced_dither_patterns[dither[pix]][(y & 3) * 2 + 1][x & 3])
+                        row2 |= 3-(index2[pix] & 3);
+                    else
+                        row2 |= 3-(index1[pix] & 3);
+                }
+                else {
+                    if (multi_dither_patterns[dither[pix]][(y & 3)][x & 3])
+                        row1 |= 3-(index2[pix] & 3);
+                    else
+                        row1 |= 3-(index1[pix] & 3);
+                }
+            }
+            charset[y+0x000] = row1;
+            if (INTERLACED) charset[y+0x800] = row2;
+        }
+        /* do we need to adjust pixels? */
+        if (highdiff > 0 && lowdiff > 0 && c->mc_use_5col) {
+            if (lowdiff > highdiff) {
+                for (x = 0; x < 32; x++)
+                    best_cb[x] = FFMIN(c->mc_luma_vals[3], best_cb[x]);
+            } else {
+                for (x = 0; x < 32; x++)
+                    best_cb[x] = FFMAX(c->mc_luma_vals[1], best_cb[x]);
+            }
+            charpos--;          /* redo now adjusted char */
+        /* no adjustment needed, all fine */
+        } else {
+            /* advance pointers */
+            best_cb += 32;
+            charset += 8;
+
+            /* remember colorram value */
+            colrammap[charpos] = (highdiff > 0);
+        }
+    }
+}
+
+static av_cold int a64multi_close_encoder(AVCodecContext *avctx)
+{
+    A64Context *c = avctx->priv_data;
+    av_free(c->mc_meta_charset);
+    av_free(c->mc_best_cb);
+    av_free(c->mc_charset);
+    av_free(c->mc_charmap);
+    av_free(c->mc_colram);
+    return 0;
+}
+
+static av_cold int a64multi_init_encoder(AVCodecContext *avctx)
+{
+    A64Context *c = avctx->priv_data;
+    int a;
+    av_lfg_init(&c->randctx, 1);
+
+    if (avctx->global_quality < 1) {
+        c->mc_lifetime = 4;
+    } else {
+        c->mc_lifetime = avctx->global_quality /= FF_QP2LAMBDA;
+    }
+
+    av_log(avctx, AV_LOG_INFO, "charset lifetime set to %d frame(s)\n", c->mc_lifetime);
+
+    c->mc_frame_counter = 0;
+    c->mc_use_5col      = avctx->codec->id == CODEC_ID_A64_MULTI5;
+    c->mc_pal_size      = 4 + c->mc_use_5col;
+
+    /* precalc luma values for later use */
+    for (a = 0; a < c->mc_pal_size; a++) {
+        c->mc_luma_vals[a]=a64_palette[mc_colors[a]][0] * 0.30 +
+                           a64_palette[mc_colors[a]][1] * 0.59 +
+                           a64_palette[mc_colors[a]][2] * 0.11;
+    }
+
+    if (!(c->mc_meta_charset = av_malloc(32000 * c->mc_lifetime * sizeof(int))) ||
+       !(c->mc_best_cb       = av_malloc(CHARSET_CHARS * 32 * sizeof(int)))     ||
+       !(c->mc_charmap       = av_mallocz(1000 * c->mc_lifetime * sizeof(int))) ||
+       !(c->mc_colram        = av_mallocz(CHARSET_CHARS * sizeof(uint8_t)))     ||
+       !(c->mc_charset       = av_malloc(0x800 * (INTERLACED+1) * sizeof(uint8_t)))) {
+        av_log(avctx, AV_LOG_ERROR, "Failed to allocate buffer memory.\n");
+        return AVERROR(ENOMEM);
+    }
+
+    /* set up extradata */
+    if (!(avctx->extradata = av_mallocz(8 * 4 + FF_INPUT_BUFFER_PADDING_SIZE))) {
+        av_log(avctx, AV_LOG_ERROR, "Failed to allocate memory for extradata.\n");
+        return AVERROR(ENOMEM);
+    }
+    avctx->extradata_size = 8 * 4;
+    AV_WB32(avctx->extradata, c->mc_lifetime);
+    AV_WB32(avctx->extradata + 16, INTERLACED);
+
+    avcodec_get_frame_defaults(&c->picture);
+    avctx->coded_frame            = &c->picture;
+    avctx->coded_frame->pict_type = FF_I_TYPE;
+    avctx->coded_frame->key_frame = 1;
+    if (!avctx->codec_tag)
+         avctx->codec_tag = AV_RL32("a64m");
+
+    return 0;
+}
+
+static void a64_compress_colram(unsigned char *buf, int *charmap, uint8_t *colram)
+{
+    int a;
+    uint8_t temp;
+    /* only needs to be done in 5col mode */
+    /* XXX could be squeezed to 0x80 bytes */
+    for (a = 0; a < 256; a++) {
+        temp  = colram[charmap[a + 0x000]] << 0;
+        temp |= colram[charmap[a + 0x100]] << 1;
+        temp |= colram[charmap[a + 0x200]] << 2;
+        if (a < 0xe8) temp |= colram[charmap[a + 0x300]] << 3;
+        buf[a] = temp << 2;
+    }
+}
+
+static int a64multi_encode_frame(AVCodecContext *avctx, unsigned char *buf,
+                                 int buf_size, void *data)
+{
+    A64Context *c = avctx->priv_data;
+    AVFrame *pict = data;
+    AVFrame *const p = (AVFrame *) & c->picture;
+
+    int frame;
+    int x, y;
+    int b_height;
+    int b_width;
+
+    int req_size;
+    int num_frames   = c->mc_lifetime;
+
+    int *charmap     = c->mc_charmap;
+    uint8_t *colram  = c->mc_colram;
+    uint8_t *charset = c->mc_charset;
+    int *meta        = c->mc_meta_charset;
+    int *best_cb     = c->mc_best_cb;
+
+    int charset_size = 0x800 * (INTERLACED + 1);
+    int colram_size  = 0x100 * c->mc_use_5col;
+    int screen_size;
+
+    if(CROP_SCREENS) {
+        b_height = FFMIN(avctx->height,C64YRES) >> 3;
+        b_width  = FFMIN(avctx->width ,C64XRES) >> 3;
+        screen_size = b_width * b_height;
+    } else {
+        b_height = C64YRES >> 3;
+        b_width  = C64XRES >> 3;
+        screen_size = 0x400;
+    }
+
+    /* no data, means end encoding asap */
+    if (!data) {
+        /* all done, end encoding */
+        if (!c->mc_lifetime) return 0;
+        /* no more frames in queue, prepare to flush remaining frames */
+        if (!c->mc_frame_counter) {
+            num_frames = c->mc_lifetime;
+            c->mc_lifetime = 0;
+        }
+        /* still frames in queue so limit lifetime to remaining frames */
+        else c->mc_lifetime = c->mc_frame_counter;
+    /* still new data available */
+    } else {
+        /* fill up mc_meta_charset with data until lifetime exceeds */
+        if (c->mc_frame_counter < c->mc_lifetime) {
+            *p = *pict;
+            p->pict_type = FF_I_TYPE;
+            p->key_frame = 1;
+            to_meta_with_crop(avctx, p, meta + 32000 * c->mc_frame_counter);
+            c->mc_frame_counter++;
+            /* lifetime is not reached so wait for next frame first */
+            return 0;
+        }
+    }
+
+    /* lifetime reached so now convert X frames at once */
+    if (c->mc_frame_counter == c->mc_lifetime) {
+        req_size = 0;
+        /* any frames to encode? */
+        if (c->mc_lifetime) {
+            /* calc optimal new charset + charmaps */
+            ff_init_elbg(meta, 32, 1000 * c->mc_lifetime, best_cb, CHARSET_CHARS, 50, charmap, &c->randctx);
+            ff_do_elbg  (meta, 32, 1000 * c->mc_lifetime, best_cb, CHARSET_CHARS, 50, charmap, &c->randctx);
+
+            /* create colorram map and a c64 readable charset */
+            render_charset(avctx, charset, colram);
+
+            /* copy charset to buf */
+            memcpy(buf,charset, charset_size);
+
+            /* advance pointers */
+            buf      += charset_size;
+            charset  += charset_size;
+            req_size += charset_size;
+        }
+        /* no charset so clean buf */
+        else memset(buf, 0, charset_size);
+
+        /* write x frames to buf */
+        for (frame = 0; frame < c->mc_lifetime; frame++) {
+            /* copy charmap to buf. buf is uchar*, charmap is int*, so no memcpy here, sorry */
+            for (y = 0; y < b_height; y++) {
+                for (x = 0; x < b_width; x++) {
+                    buf[y * b_width + x] = charmap[y * b_width + x];
+                }
+            }
+            /* advance pointers */
+            buf += screen_size;
+            req_size += screen_size;
+
+            /* compress and copy colram to buf */
+            if (c->mc_use_5col) {
+                a64_compress_colram(buf, charmap, colram);
+                /* advance pointers */
+                buf += colram_size;
+                req_size += colram_size;
+            }
+
+            /* advance to next charmap */
+            charmap += 1000;
+        }
+
+        AV_WB32(avctx->extradata + 4,  c->mc_frame_counter);
+        AV_WB32(avctx->extradata + 8,  charset_size);
+        AV_WB32(avctx->extradata + 12, screen_size + colram_size);
+
+        /* reset counter */
+        c->mc_frame_counter = 0;
+
+        if (req_size > buf_size) {
+            av_log(avctx, AV_LOG_ERROR, "buf size too small (need %d, got %d)\n", req_size, buf_size);
+            return -1;
+        }
+        return req_size;
+    }
+    return 0;
+}
+
+AVCodec ff_a64multi_encoder = {
+    .name           = "a64multi",
+    .type           = AVMEDIA_TYPE_VIDEO,
+    .id             = CODEC_ID_A64_MULTI,
+    .priv_data_size = sizeof(A64Context),
+    .init           = a64multi_init_encoder,
+    .encode         = a64multi_encode_frame,
+    .close          = a64multi_close_encoder,
+    .pix_fmts       = (const enum PixelFormat[]) {PIX_FMT_GRAY8, PIX_FMT_NONE},
+    .long_name      = NULL_IF_CONFIG_SMALL("Multicolor charset for Commodore 64"),
+    .capabilities   = CODEC_CAP_DELAY,
+};
+
+AVCodec ff_a64multi5_encoder = {
+    .name           = "a64multi5",
+    .type           = AVMEDIA_TYPE_VIDEO,
+    .id             = CODEC_ID_A64_MULTI5,
+    .priv_data_size = sizeof(A64Context),
+    .init           = a64multi_init_encoder,
+    .encode         = a64multi_encode_frame,
+    .close          = a64multi_close_encoder,
+    .pix_fmts       = (const enum PixelFormat[]) {PIX_FMT_GRAY8, PIX_FMT_NONE},
+    .long_name      = NULL_IF_CONFIG_SMALL("Multicolor charset for Commodore 64, extended with 5th color (colram)"),
+    .capabilities   = CODEC_CAP_DELAY,
+};
diff --git a/libavcodec/a64tables.h b/libavcodec/a64tables.h
new file mode 100644
index 0000000..b95c5ce
--- /dev/null
+++ b/libavcodec/a64tables.h
@@ -0,0 +1,150 @@
+/*
+ * a64 video encoder - tables used by a64 encoders
+ * Copyright (c) 2009 Tobias Bindhammer
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * a64 video encoder - tables used by a64 encoders
+ */
+
+#ifndef AVCODEC_A64TABLES_H
+#define AVCODEC_A64TABLES_H
+
+#include <stdint.h>
+
+/**
+ * dither patterns used vor rendering the multicolor charset
+ */
+
+static const uint8_t multi_dither_patterns[9][4][4] = {
+    {
+     {0, 0, 0, 0},
+     {0, 0, 0, 0},
+     {0, 0, 0, 0},
+     {0, 0, 0, 0}
+     },
+    {
+     {1, 0, 0, 0},
+     {0, 0, 0, 0},
+     {0, 0, 1, 0},
+     {0, 0, 0, 0}
+     },
+    {
+     {1, 0, 0, 0},
+     {0, 0, 1, 0},
+     {0, 1, 0, 0},
+     {0, 0, 0, 1}
+     },
+    {
+     {1, 0, 0, 0},
+     {0, 1, 0, 1},
+     {0, 0, 1, 0},
+     {0, 1, 0, 1}
+     },
+    {
+     {1, 0, 1, 0},
+     {0, 1, 0, 1},
+     {1, 0, 1, 0},
+     {0, 1, 0, 1}
+     },
+    {
+     {1, 1, 1, 0},
+     {0, 1, 0, 1},
+     {1, 0, 1, 1},
+     {0, 1, 0, 1}
+     },
+    {
+     {0, 1, 1, 1},
+     {1, 1, 0, 1},
+     {1, 0, 1, 1},
+     {1, 1, 1, 0}
+     },
+    {
+     {0, 1, 1, 1},
+     {1, 1, 1, 1},
+     {1, 1, 0, 1},
+     {1, 1, 1, 1}
+     },
+    {
+     {1, 1, 1, 1},
+     {1, 1, 1, 1},
+     {1, 1, 1, 1},
+     {1, 1, 1, 1}
+     },
+};
+
+static const uint8_t interlaced_dither_patterns[9][8][4] = {
+    {
+     {0, 0, 0, 0}, {0, 0, 0, 0},
+     {0, 0, 0, 0}, {0, 0, 0, 0},
+     {0, 0, 0, 0}, {0, 0, 0, 0},
+     {0, 0, 0, 0}, {0, 0, 0, 0},
+     },
+    {
+     {1, 0, 1, 0}, {0, 0, 0, 0},
+     {0, 0, 0, 0}, {0, 0, 0, 0},
+     {1, 0, 1, 0}, {0, 0, 0, 0},
+     {0, 0, 0, 0}, {0, 0, 0, 0},
+     },
+    {
+     {1, 0, 1, 0}, {0, 0, 0, 0},
+     {0, 0, 0, 0}, {0, 1, 0, 1},
+     {1, 0, 1, 0}, {0, 0, 0, 0},
+     {0, 0, 0, 0}, {0, 1, 0, 1},
+     },
+    {
+     {1, 0, 1, 0}, {0, 1, 0, 1},
+     {0, 1, 0, 1}, {0, 0, 0, 0},
+     {1, 0, 1, 0}, {0, 1, 0, 1},
+     {0, 1, 0, 1}, {0, 0, 0, 0},
+     },
+    {
+     {1, 0, 1, 0}, {0, 1, 0, 1},
+     {0, 1, 0, 1}, {1, 0, 1, 0},
+     {1, 0, 1, 0}, {0, 1, 0, 1},
+     {0, 1, 0, 1}, {1, 0, 1, 0},
+     },
+    {
+     {1, 0, 1, 0}, {0, 1, 0, 1},
+     {1, 1, 1, 1}, {1, 0, 1, 0},
+     {1, 0, 1, 0}, {0, 1, 0, 1},
+     {1, 1, 1, 1}, {1, 0, 1, 0},
+     },
+    {
+     {1, 0, 1, 0}, {1, 1, 1, 1},
+     {1, 1, 1, 1}, {0, 1, 0, 1},
+     {1, 0, 1, 0}, {1, 1, 1, 1},
+     {1, 1, 1, 1}, {0, 1, 0, 1},
+     },
+    {
+     {1, 1, 1, 1}, {1, 1, 1, 1},
+     {1, 1, 1, 1}, {0, 1, 0, 1},
+     {1, 1, 1, 1}, {1, 1, 1, 1},
+     {1, 1, 1, 1}, {0, 1, 0, 1},
+     },
+    {
+     {1, 1, 1, 1}, {1, 1, 1, 1},
+     {1, 1, 1, 1}, {1, 1, 1, 1},
+     {1, 1, 1, 1}, {1, 1, 1, 1},
+     {1, 1, 1, 1}, {1, 1, 1, 1},
+     }
+};
+
+#endif /* AVCODEC_A64TABLES_H */
diff --git a/libavcodec/aac.c b/libavcodec/aac.c
deleted file mode 100644
index 3330e1c..0000000
--- a/libavcodec/aac.c
+++ /dev/null
@@ -1,2108 +0,0 @@
-/*
- * AAC decoder
- * Copyright (c) 2005-2006 Oded Shimon ( ods15 ods15 dyndns org )
- * Copyright (c) 2006-2007 Maxim Gavrilov ( maxim.gavrilov gmail com )
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-/**
- * @file
- * AAC decoder
- * @author Oded Shimon  ( ods15 ods15 dyndns org )
- * @author Maxim Gavrilov ( maxim.gavrilov gmail com )
- */
-
-/*
- * supported tools
- *
- * Support?             Name
- * N (code in SoC repo) gain control
- * Y                    block switching
- * Y                    window shapes - standard
- * N                    window shapes - Low Delay
- * Y                    filterbank - standard
- * N (code in SoC repo) filterbank - Scalable Sample Rate
- * Y                    Temporal Noise Shaping
- * N (code in SoC repo) Long Term Prediction
- * Y                    intensity stereo
- * Y                    channel coupling
- * Y                    frequency domain prediction
- * Y                    Perceptual Noise Substitution
- * Y                    Mid/Side stereo
- * N                    Scalable Inverse AAC Quantization
- * N                    Frequency Selective Switch
- * N                    upsampling filter
- * Y                    quantization & coding - AAC
- * N                    quantization & coding - TwinVQ
- * N                    quantization & coding - BSAC
- * N                    AAC Error Resilience tools
- * N                    Error Resilience payload syntax
- * N                    Error Protection tool
- * N                    CELP
- * N                    Silence Compression
- * N                    HVXC
- * N                    HVXC 4kbits/s VR
- * N                    Structured Audio tools
- * N                    Structured Audio Sample Bank Format
- * N                    MIDI
- * N                    Harmonic and Individual Lines plus Noise
- * N                    Text-To-Speech Interface
- * Y                    Spectral Band Replication
- * Y (not in this code) Layer-1
- * Y (not in this code) Layer-2
- * Y (not in this code) Layer-3
- * N                    SinuSoidal Coding (Transient, Sinusoid, Noise)
- * N (planned)          Parametric Stereo
- * N                    Direct Stream Transfer
- *
- * Note: - HE AAC v1 comprises LC AAC with Spectral Band Replication.
- *       - HE AAC v2 comprises LC AAC with Spectral Band Replication and
-           Parametric Stereo.
- */
-
-
-#include "avcodec.h"
-#include "internal.h"
-#include "get_bits.h"
-#include "dsputil.h"
-#include "fft.h"
-#include "lpc.h"
-
-#include "aac.h"
-#include "aactab.h"
-#include "aacdectab.h"
-#include "cbrt_tablegen.h"
-#include "sbr.h"
-#include "aacsbr.h"
-#include "mpeg4audio.h"
-#include "aac_parser.h"
-
-#include <assert.h>
-#include <errno.h>
-#include <math.h>
-#include <string.h>
-
-#if ARCH_ARM
-#   include "arm/aac.h"
-#endif
-
-union float754 {
-    float f;
-    uint32_t i;
-};
-
-static VLC vlc_scalefactors;
-static VLC vlc_spectral[11];
-
-static const char overread_err[] = "Input buffer exhausted before END element found\n";
-
-static ChannelElement *get_che(AACContext *ac, int type, int elem_id)
-{
-    if (ac->tag_che_map[type][elem_id]) {
-        return ac->tag_che_map[type][elem_id];
-    }
-    if (ac->tags_mapped >= tags_per_config[ac->m4ac.chan_config]) {
-        return NULL;
-    }
-    switch (ac->m4ac.chan_config) {
-    case 7:
-        if (ac->tags_mapped == 3 && type == TYPE_CPE) {
-            ac->tags_mapped++;
-            return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][2];
-        }
-    case 6:
-        /* Some streams incorrectly code 5.1 audio as SCE[0] CPE[0] CPE[1] SCE[1]
-           instead of SCE[0] CPE[0] CPE[0] LFE[0]. If we seem to have
-           encountered such a stream, transfer the LFE[0] element to SCE[1] */
-        if (ac->tags_mapped == tags_per_config[ac->m4ac.chan_config] - 1 && (type == TYPE_LFE || type == TYPE_SCE)) {
-            ac->tags_mapped++;
-            return ac->tag_che_map[type][elem_id] = ac->che[TYPE_LFE][0];
-        }
-    case 5:
-        if (ac->tags_mapped == 2 && type == TYPE_CPE) {
-            ac->tags_mapped++;
-            return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][1];
-        }
-    case 4:
-        if (ac->tags_mapped == 2 && ac->m4ac.chan_config == 4 && type == TYPE_SCE) {
-            ac->tags_mapped++;
-            return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
-        }
-    case 3:
-    case 2:
-        if (ac->tags_mapped == (ac->m4ac.chan_config != 2) && type == TYPE_CPE) {
-            ac->tags_mapped++;
-            return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][0];
-        } else if (ac->m4ac.chan_config == 2) {
-            return NULL;
-        }
-    case 1:
-        if (!ac->tags_mapped && type == TYPE_SCE) {
-            ac->tags_mapped++;
-            return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][0];
-        }
-    default:
-        return NULL;
-    }
-}
-
-/**
- * Check for the channel element in the current channel position configuration.
- * If it exists, make sure the appropriate element is allocated and map the
- * channel order to match the internal FFmpeg channel layout.
- *
- * @param   che_pos current channel position configuration
- * @param   type channel element type
- * @param   id channel element id
- * @param   channels count of the number of channels in the configuration
- *
- * @return  Returns error status. 0 - OK, !0 - error
- */
-static av_cold int che_configure(AACContext *ac,
-                         enum ChannelPosition che_pos[4][MAX_ELEM_ID],
-                         int type, int id,
-                         int *channels)
-{
-    if (che_pos[type][id]) {
-        if (!ac->che[type][id] && !(ac->che[type][id] = av_mallocz(sizeof(ChannelElement))))
-            return AVERROR(ENOMEM);
-        ff_aac_sbr_ctx_init(&ac->che[type][id]->sbr);
-        if (type != TYPE_CCE) {
-            ac->output_data[(*channels)++] = ac->che[type][id]->ch[0].ret;
-            if (type == TYPE_CPE) {
-                ac->output_data[(*channels)++] = ac->che[type][id]->ch[1].ret;
-            }
-        }
-    } else {
-        if (ac->che[type][id])
-            ff_aac_sbr_ctx_close(&ac->che[type][id]->sbr);
-        av_freep(&ac->che[type][id]);
-    }
-    return 0;
-}
-
-/**
- * Configure output channel order based on the current program configuration element.
- *
- * @param   che_pos current channel position configuration
- * @param   new_che_pos New channel position configuration - we only do something if it differs from the current one.
- *
- * @return  Returns error status. 0 - OK, !0 - error
- */
-static av_cold int output_configure(AACContext *ac,
-                            enum ChannelPosition che_pos[4][MAX_ELEM_ID],
-                            enum ChannelPosition new_che_pos[4][MAX_ELEM_ID],
-                            int channel_config, enum OCStatus oc_type)
-{
-    AVCodecContext *avctx = ac->avccontext;
-    int i, type, channels = 0, ret;
-
-    memcpy(che_pos, new_che_pos, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
-
-    if (channel_config) {
-        for (i = 0; i < tags_per_config[channel_config]; i++) {
-            if ((ret = che_configure(ac, che_pos,
-                                     aac_channel_layout_map[channel_config - 1][i][0],
-                                     aac_channel_layout_map[channel_config - 1][i][1],
-                                     &channels)))
-                return ret;
-        }
-
-        memset(ac->tag_che_map, 0,       4 * MAX_ELEM_ID * sizeof(ac->che[0][0]));
-        ac->tags_mapped = 0;
-
-        avctx->channel_layout = aac_channel_layout[channel_config - 1];
-    } else {
-        /* Allocate or free elements depending on if they are in the
-         * current program configuration.
-         *
-         * Set up default 1:1 output mapping.
-         *
-         * For a 5.1 stream the output order will be:
-         *    [ Center ] [ Front Left ] [ Front Right ] [ LFE ] [ Surround Left ] [ Surround Right ]
-         */
-
-        for (i = 0; i < MAX_ELEM_ID; i++) {
-            for (type = 0; type < 4; type++) {
-                if ((ret = che_configure(ac, che_pos, type, i, &channels)))
-                    return ret;
-            }
-        }
-
-        memcpy(ac->tag_che_map, ac->che, 4 * MAX_ELEM_ID * sizeof(ac->che[0][0]));
-        ac->tags_mapped = 4 * MAX_ELEM_ID;
-
-        avctx->channel_layout = 0;
-    }
-
-    avctx->channels = channels;
-
-    ac->output_configured = oc_type;
-
-    return 0;
-}
-
-/**
- * Decode an array of 4 bit element IDs, optionally interleaved with a stereo/mono switching bit.
- *
- * @param cpe_map Stereo (Channel Pair Element) map, NULL if stereo bit is not present.
- * @param sce_map mono (Single Channel Element) map
- * @param type speaker type/position for these channels
- */
-static void decode_channel_map(enum ChannelPosition *cpe_map,
-                               enum ChannelPosition *sce_map,
-                               enum ChannelPosition type,
-                               GetBitContext *gb, int n)
-{
-    while (n--) {
-        enum ChannelPosition *map = cpe_map && get_bits1(gb) ? cpe_map : sce_map; // stereo or mono map
-        map[get_bits(gb, 4)] = type;
-    }
-}
-
-/**
- * Decode program configuration element; reference: table 4.2.
- *
- * @param   new_che_pos New channel position configuration - we only do something if it differs from the current one.
- *
- * @return  Returns error status. 0 - OK, !0 - error
- */
-static int decode_pce(AACContext *ac, enum ChannelPosition new_che_pos[4][MAX_ELEM_ID],
-                      GetBitContext *gb)
-{
-    int num_front, num_side, num_back, num_lfe, num_assoc_data, num_cc, sampling_index;
-    int comment_len;
-
-    skip_bits(gb, 2);  // object_type
-
-    sampling_index = get_bits(gb, 4);
-    if (ac->m4ac.sampling_index != sampling_index)
-        av_log(ac->avccontext, AV_LOG_WARNING, "Sample rate index in program config element does not match the sample rate index configured by the container.\n");
-
-    num_front       = get_bits(gb, 4);
-    num_side        = get_bits(gb, 4);
-    num_back        = get_bits(gb, 4);
-    num_lfe         = get_bits(gb, 2);
-    num_assoc_data  = get_bits(gb, 3);
-    num_cc          = get_bits(gb, 4);
-
-    if (get_bits1(gb))
-        skip_bits(gb, 4); // mono_mixdown_tag
-    if (get_bits1(gb))
-        skip_bits(gb, 4); // stereo_mixdown_tag
-
-    if (get_bits1(gb))
-        skip_bits(gb, 3); // mixdown_coeff_index and pseudo_surround
-
-    decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_FRONT, gb, num_front);
-    decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_SIDE,  gb, num_side );
-    decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_BACK,  gb, num_back );
-    decode_channel_map(NULL,                  new_che_pos[TYPE_LFE], AAC_CHANNEL_LFE,   gb, num_lfe  );
-
-    skip_bits_long(gb, 4 * num_assoc_data);
-
-    decode_channel_map(new_che_pos[TYPE_CCE], new_che_pos[TYPE_CCE], AAC_CHANNEL_CC,    gb, num_cc   );
-
-    align_get_bits(gb);
-
-    /* comment field, first byte is length */
-    comment_len = get_bits(gb, 8) * 8;
-    if (get_bits_left(gb) < comment_len) {
-        av_log(ac->avccontext, AV_LOG_ERROR, overread_err);
-        return -1;
-    }
-    skip_bits_long(gb, comment_len);
-    return 0;
-}
-
-/**
- * Set up channel positions based on a default channel configuration
- * as specified in table 1.17.
- *
- * @param   new_che_pos New channel position configuration - we only do something if it differs from the current one.
- *
- * @return  Returns error status. 0 - OK, !0 - error
- */
-static av_cold int set_default_channel_config(AACContext *ac,
-                                      enum ChannelPosition new_che_pos[4][MAX_ELEM_ID],
-                                      int channel_config)
-{
-    if (channel_config < 1 || channel_config > 7) {
-        av_log(ac->avccontext, AV_LOG_ERROR, "invalid default channel configuration (%d)\n",
-               channel_config);
-        return -1;
-    }
-
-    /* default channel configurations:
-     *
-     * 1ch : front center (mono)
-     * 2ch : L + R (stereo)
-     * 3ch : front center + L + R
-     * 4ch : front center + L + R + back center
-     * 5ch : front center + L + R + back stereo
-     * 6ch : front center + L + R + back stereo + LFE
-     * 7ch : front center + L + R + outer front left + outer front right + back stereo + LFE
-     */
-
-    if (channel_config != 2)
-        new_che_pos[TYPE_SCE][0] = AAC_CHANNEL_FRONT; // front center (or mono)
-    if (channel_config > 1)
-        new_che_pos[TYPE_CPE][0] = AAC_CHANNEL_FRONT; // L + R (or stereo)
-    if (channel_config == 4)
-        new_che_pos[TYPE_SCE][1] = AAC_CHANNEL_BACK;  // back center
-    if (channel_config > 4)
-        new_che_pos[TYPE_CPE][(channel_config == 7) + 1]
-        = AAC_CHANNEL_BACK;  // back stereo
-    if (channel_config > 5)
-        new_che_pos[TYPE_LFE][0] = AAC_CHANNEL_LFE;   // LFE
-    if (channel_config == 7)
-        new_che_pos[TYPE_CPE][1] = AAC_CHANNEL_FRONT; // outer front left + outer front right
-
-    return 0;
-}
-
-/**
- * Decode GA "General Audio" specific configuration; reference: table 4.1.
- *
- * @return  Returns error status. 0 - OK, !0 - error
- */
-static int decode_ga_specific_config(AACContext *ac, GetBitContext *gb,
-                                     int channel_config)
-{
-    enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
-    int extension_flag, ret;
-
-    if (get_bits1(gb)) { // frameLengthFlag
-        av_log_missing_feature(ac->avccontext, "960/120 MDCT window is", 1);
-        return -1;
-    }
-
-    if (get_bits1(gb))       // dependsOnCoreCoder
-        skip_bits(gb, 14);   // coreCoderDelay
-    extension_flag = get_bits1(gb);
-
-    if (ac->m4ac.object_type == AOT_AAC_SCALABLE ||
-        ac->m4ac.object_type == AOT_ER_AAC_SCALABLE)
-        skip_bits(gb, 3);     // layerNr
-
-    memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
-    if (channel_config == 0) {
-        skip_bits(gb, 4);  // element_instance_tag
-        if ((ret = decode_pce(ac, new_che_pos, gb)))
-            return ret;
-    } else {
-        if ((ret = set_default_channel_config(ac, new_che_pos, channel_config)))
-            return ret;
-    }
-    if ((ret = output_configure(ac, ac->che_pos, new_che_pos, channel_config, OC_GLOBAL_HDR)))
-        return ret;
-
-    if (extension_flag) {
-        switch (ac->m4ac.object_type) {
-        case AOT_ER_BSAC:
-            skip_bits(gb, 5);    // numOfSubFrame
-            skip_bits(gb, 11);   // layer_length
-            break;
-        case AOT_ER_AAC_LC:
-        case AOT_ER_AAC_LTP:
-        case AOT_ER_AAC_SCALABLE:
-        case AOT_ER_AAC_LD:
-            skip_bits(gb, 3);  /* aacSectionDataResilienceFlag
-                                    * aacScalefactorDataResilienceFlag
-                                    * aacSpectralDataResilienceFlag
-                                    */
-            break;
-        }
-        skip_bits1(gb);    // extensionFlag3 (TBD in version 3)
-    }
-    return 0;
-}
-
-/**
- * Decode audio specific configuration; reference: table 1.13.
- *
- * @param   data        pointer to AVCodecContext extradata
- * @param   data_size   size of AVCCodecContext extradata
- *
- * @return  Returns error status. 0 - OK, !0 - error
- */
-static int decode_audio_specific_config(AACContext *ac, void *data,
-                                        int data_size)
-{
-    GetBitContext gb;
-    int i;
-
-    init_get_bits(&gb, data, data_size * 8);
-
-    if ((i = ff_mpeg4audio_get_config(&ac->m4ac, data, data_size)) < 0)
-        return -1;
-    if (ac->m4ac.sampling_index > 12) {
-        av_log(ac->avccontext, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->m4ac.sampling_index);
-        return -1;
-    }
-
-    skip_bits_long(&gb, i);
-
-    switch (ac->m4ac.object_type) {
-    case AOT_AAC_MAIN:
-    case AOT_AAC_LC:
-        if (decode_ga_specific_config(ac, &gb, ac->m4ac.chan_config))
-            return -1;
-        break;
-    default:
-        av_log(ac->avccontext, AV_LOG_ERROR, "Audio object type %s%d is not supported.\n",
-               ac->m4ac.sbr == 1? "SBR+" : "", ac->m4ac.object_type);
-        return -1;
-    }
-    return 0;
-}
-
-/**
- * linear congruential pseudorandom number generator
- *
- * @param   previous_val    pointer to the current state of the generator
- *
- * @return  Returns a 32-bit pseudorandom integer
- */
-static av_always_inline int lcg_random(int previous_val)
-{
-    return previous_val * 1664525 + 1013904223;
-}
-
-static av_always_inline void reset_predict_state(PredictorState *ps)
-{
-    ps->r0   = 0.0f;
-    ps->r1   = 0.0f;
-    ps->cor0 = 0.0f;
-    ps->cor1 = 0.0f;
-    ps->var0 = 1.0f;
-    ps->var1 = 1.0f;
-}
-
-static void reset_all_predictors(PredictorState *ps)
-{
-    int i;
-    for (i = 0; i < MAX_PREDICTORS; i++)
-        reset_predict_state(&ps[i]);
-}
-
-static void reset_predictor_group(PredictorState *ps, int group_num)
-{
-    int i;
-    for (i = group_num - 1; i < MAX_PREDICTORS; i += 30)
-        reset_predict_state(&ps[i]);
-}
-
-static av_cold int aac_decode_init(AVCodecContext *avccontext)
-{
-    AACContext *ac = avccontext->priv_data;
-    int i;
-
-    ac->avccontext = avccontext;
-    ac->m4ac.sample_rate = avccontext->sample_rate;
-
-    if (avccontext->extradata_size > 0) {
-        if (decode_audio_specific_config(ac, avccontext->extradata, avccontext->extradata_size))
-            return -1;
-    }
-
-    avccontext->sample_fmt = SAMPLE_FMT_S16;
-
-    AAC_INIT_VLC_STATIC( 0, 304);
-    AAC_INIT_VLC_STATIC( 1, 270);
-    AAC_INIT_VLC_STATIC( 2, 550);
-    AAC_INIT_VLC_STATIC( 3, 300);
-    AAC_INIT_VLC_STATIC( 4, 328);
-    AAC_INIT_VLC_STATIC( 5, 294);
-    AAC_INIT_VLC_STATIC( 6, 306);
-    AAC_INIT_VLC_STATIC( 7, 268);
-    AAC_INIT_VLC_STATIC( 8, 510);
-    AAC_INIT_VLC_STATIC( 9, 366);
-    AAC_INIT_VLC_STATIC(10, 462);
-
-    ff_aac_sbr_init();
-
-    dsputil_init(&ac->dsp, avccontext);
-
-    ac->random_state = 0x1f2e3d4c;
-
-    // -1024 - Compensate wrong IMDCT method.
-    // 32768 - Required to scale values to the correct range for the bias method
-    //         for float to int16 conversion.
-
-    if (ac->dsp.float_to_int16_interleave == ff_float_to_int16_interleave_c) {
-        ac->add_bias  = 385.0f;
-        ac->sf_scale  = 1. / (-1024. * 32768.);
-        ac->sf_offset = 0;
-    } else {
-        ac->add_bias  = 0.0f;
-        ac->sf_scale  = 1. / -1024.;
-        ac->sf_offset = 60;
-    }
-
-#if !CONFIG_HARDCODED_TABLES
-    for (i = 0; i < 428; i++)
-        ff_aac_pow2sf_tab[i] = pow(2, (i - 200) / 4.);
-#endif /* CONFIG_HARDCODED_TABLES */
-
-    INIT_VLC_STATIC(&vlc_scalefactors,7,FF_ARRAY_ELEMS(ff_aac_scalefactor_code),
-                    ff_aac_scalefactor_bits, sizeof(ff_aac_scalefactor_bits[0]), sizeof(ff_aac_scalefactor_bits[0]),
-                    ff_aac_scalefactor_code, sizeof(ff_aac_scalefactor_code[0]), sizeof(ff_aac_scalefactor_code[0]),
-                    352);
-
-    ff_mdct_init(&ac->mdct, 11, 1, 1.0);
-    ff_mdct_init(&ac->mdct_small, 8, 1, 1.0);
-    // window initialization
-    ff_kbd_window_init(ff_aac_kbd_long_1024, 4.0, 1024);
-    ff_kbd_window_init(ff_aac_kbd_short_128, 6.0, 128);
-    ff_init_ff_sine_windows(10);
-    ff_init_ff_sine_windows( 7);
-
-    cbrt_tableinit();
-
-    return 0;
-}
-
-/**
- * Skip data_stream_element; reference: table 4.10.
- */
-static int skip_data_stream_element(AACContext *ac, GetBitContext *gb)
-{
-    int byte_align = get_bits1(gb);
-    int count = get_bits(gb, 8);
-    if (count == 255)
-        count += get_bits(gb, 8);
-    if (byte_align)
-        align_get_bits(gb);
-
-    if (get_bits_left(gb) < 8 * count) {
-        av_log(ac->avccontext, AV_LOG_ERROR, overread_err);
-        return -1;
-    }
-    skip_bits_long(gb, 8 * count);
-    return 0;
-}
-
-static int decode_prediction(AACContext *ac, IndividualChannelStream *ics,
-                             GetBitContext *gb)
-{
-    int sfb;
-    if (get_bits1(gb)) {
-        ics->predictor_reset_group = get_bits(gb, 5);
-        if (ics->predictor_reset_group == 0 || ics->predictor_reset_group > 30) {
-            av_log(ac->avccontext, AV_LOG_ERROR, "Invalid Predictor Reset Group.\n");
-            return -1;
-        }
-    }
-    for (sfb = 0; sfb < FFMIN(ics->max_sfb, ff_aac_pred_sfb_max[ac->m4ac.sampling_index]); sfb++) {
-        ics->prediction_used[sfb] = get_bits1(gb);
-    }
-    return 0;
-}
-
-/**
- * Decode Individual Channel Stream info; reference: table 4.6.
- *
- * @param   common_window   Channels have independent [0], or shared [1], Individual Channel Stream information.
- */
-static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,
-                           GetBitContext *gb, int common_window)
-{
-    if (get_bits1(gb)) {
-        av_log(ac->avccontext, AV_LOG_ERROR, "Reserved bit set.\n");
-        memset(ics, 0, sizeof(IndividualChannelStream));
-        return -1;
-    }
-    ics->window_sequence[1] = ics->window_sequence[0];
-    ics->window_sequence[0] = get_bits(gb, 2);
-    ics->use_kb_window[1]   = ics->use_kb_window[0];
-    ics->use_kb_window[0]   = get_bits1(gb);
-    ics->num_window_groups  = 1;
-    ics->group_len[0]       = 1;
-    if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
-        int i;
-        ics->max_sfb = get_bits(gb, 4);
-        for (i = 0; i < 7; i++) {
-            if (get_bits1(gb)) {
-                ics->group_len[ics->num_window_groups - 1]++;
-            } else {
-                ics->num_window_groups++;
-                ics->group_len[ics->num_window_groups - 1] = 1;
-            }
-        }
-        ics->num_windows       = 8;
-        ics->swb_offset        =    ff_swb_offset_128[ac->m4ac.sampling_index];
-        ics->num_swb           =   ff_aac_num_swb_128[ac->m4ac.sampling_index];
-        ics->tns_max_bands     = ff_tns_max_bands_128[ac->m4ac.sampling_index];
-        ics->predictor_present = 0;
-    } else {
-        ics->max_sfb               = get_bits(gb, 6);
-        ics->num_windows           = 1;
-        ics->swb_offset            =    ff_swb_offset_1024[ac->m4ac.sampling_index];
-        ics->num_swb               =   ff_aac_num_swb_1024[ac->m4ac.sampling_index];
-        ics->tns_max_bands         = ff_tns_max_bands_1024[ac->m4ac.sampling_index];
-        ics->predictor_present     = get_bits1(gb);
-        ics->predictor_reset_group = 0;
-        if (ics->predictor_present) {
-            if (ac->m4ac.object_type == AOT_AAC_MAIN) {
-                if (decode_prediction(ac, ics, gb)) {
-                    memset(ics, 0, sizeof(IndividualChannelStream));
-                    return -1;
-                }
-            } else if (ac->m4ac.object_type == AOT_AAC_LC) {
-                av_log(ac->avccontext, AV_LOG_ERROR, "Prediction is not allowed in AAC-LC.\n");
-                memset(ics, 0, sizeof(IndividualChannelStream));
-                return -1;
-            } else {
-                av_log_missing_feature(ac->avccontext, "Predictor bit set but LTP is", 1);
-                memset(ics, 0, sizeof(IndividualChannelStream));
-                return -1;
-            }
-        }
-    }
-
-    if (ics->max_sfb > ics->num_swb) {
-        av_log(ac->avccontext, AV_LOG_ERROR,
-               "Number of scalefactor bands in group (%d) exceeds limit (%d).\n",
-               ics->max_sfb, ics->num_swb);
-        memset(ics, 0, sizeof(IndividualChannelStream));
-        return -1;
-    }
-
-    return 0;
-}
-
-/**
- * Decode band types (section_data payload); reference: table 4.46.
- *
- * @param   band_type           array of the used band type
- * @param   band_type_run_end   array of the last scalefactor band of a band type run
- *
- * @return  Returns error status. 0 - OK, !0 - error
- */
-static int decode_band_types(AACContext *ac, enum BandType band_type[120],
-                             int band_type_run_end[120], GetBitContext *gb,
-                             IndividualChannelStream *ics)
-{
-    int g, idx = 0;
-    const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
-    for (g = 0; g < ics->num_window_groups; g++) {
-        int k = 0;
-        while (k < ics->max_sfb) {
-            uint8_t sect_end = k;
-            int sect_len_incr;
-            int sect_band_type = get_bits(gb, 4);
-            if (sect_band_type == 12) {
-                av_log(ac->avccontext, AV_LOG_ERROR, "invalid band type\n");
-                return -1;
-            }
-            while ((sect_len_incr = get_bits(gb, bits)) == (1 << bits) - 1)
-                sect_end += sect_len_incr;
-            sect_end += sect_len_incr;
-            if (get_bits_left(gb) < 0) {
-                av_log(ac->avccontext, AV_LOG_ERROR, overread_err);
-                return -1;
-            }
-            if (sect_end > ics->max_sfb) {
-                av_log(ac->avccontext, AV_LOG_ERROR,
-                       "Number of bands (%d) exceeds limit (%d).\n",
-                       sect_end, ics->max_sfb);
-                return -1;
-            }
-            for (; k < sect_end; k++) {
-                band_type        [idx]   = sect_band_type;
-                band_type_run_end[idx++] = sect_end;
-            }
-        }
-    }
-    return 0;
-}
-
-/**
- * Decode scalefactors; reference: table 4.47.
- *
- * @param   global_gain         first scalefactor value as scalefactors are differentially coded
- * @param   band_type           array of the used band type
- * @param   band_type_run_end   array of the last scalefactor band of a band type run
- * @param   sf                  array of scalefactors or intensity stereo positions
- *
- * @return  Returns error status. 0 - OK, !0 - error
- */
-static int decode_scalefactors(AACContext *ac, float sf[120], GetBitContext *gb,
-                               unsigned int global_gain,
-                               IndividualChannelStream *ics,
-                               enum BandType band_type[120],
-                               int band_type_run_end[120])
-{
-    const int sf_offset = ac->sf_offset + (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE ? 12 : 0);
-    int g, i, idx = 0;
-    int offset[3] = { global_gain, global_gain - 90, 100 };
-    int noise_flag = 1;
-    static const char *sf_str[3] = { "Global gain", "Noise gain", "Intensity stereo position" };
-    for (g = 0; g < ics->num_window_groups; g++) {
-        for (i = 0; i < ics->max_sfb;) {
-            int run_end = band_type_run_end[idx];
-            if (band_type[idx] == ZERO_BT) {
-                for (; i < run_end; i++, idx++)
-                    sf[idx] = 0.;
-            } else if ((band_type[idx] == INTENSITY_BT) || (band_type[idx] == INTENSITY_BT2)) {
-                for (; i < run_end; i++, idx++) {
-                    offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
-                    if (offset[2] > 255U) {
-                        av_log(ac->avccontext, AV_LOG_ERROR,
-                               "%s (%d) out of range.\n", sf_str[2], offset[2]);
-                        return -1;
-                    }
-                    sf[idx] = ff_aac_pow2sf_tab[-offset[2] + 300];
-                }
-            } else if (band_type[idx] == NOISE_BT) {
-                for (; i < run_end; i++, idx++) {
-                    if (noise_flag-- > 0)
-                        offset[1] += get_bits(gb, 9) - 256;
-                    else
-                        offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
-                    if (offset[1] > 255U) {
-                        av_log(ac->avccontext, AV_LOG_ERROR,
-                               "%s (%d) out of range.\n", sf_str[1], offset[1]);
-                        return -1;
-                    }
-                    sf[idx] = -ff_aac_pow2sf_tab[offset[1] + sf_offset + 100];
-                }
-            } else {
-                for (; i < run_end; i++, idx++) {
-                    offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
-                    if (offset[0] > 255U) {
-                        av_log(ac->avccontext, AV_LOG_ERROR,
-                               "%s (%d) out of range.\n", sf_str[0], offset[0]);
-                        return -1;
-                    }
-                    sf[idx] = -ff_aac_pow2sf_tab[ offset[0] + sf_offset];
-                }
-            }
-        }
-    }
-    return 0;
-}
-
-/**
- * Decode pulse data; reference: table 4.7.
- */
-static int decode_pulses(Pulse *pulse, GetBitContext *gb,
-                         const uint16_t *swb_offset, int num_swb)
-{
-    int i, pulse_swb;
-    pulse->num_pulse = get_bits(gb, 2) + 1;
-    pulse_swb        = get_bits(gb, 6);
-    if (pulse_swb >= num_swb)
-        return -1;
-    pulse->pos[0]    = swb_offset[pulse_swb];
-    pulse->pos[0]   += get_bits(gb, 5);
-    if (pulse->pos[0] > 1023)
-        return -1;
-    pulse->amp[0]    = get_bits(gb, 4);
-    for (i = 1; i < pulse->num_pulse; i++) {
-        pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];
-        if (pulse->pos[i] > 1023)
-            return -1;
-        pulse->amp[i] = get_bits(gb, 4);
-    }
-    return 0;
-}
-
-/**
- * Decode Temporal Noise Shaping data; reference: table 4.48.
- *
- * @return  Returns error status. 0 - OK, !0 - error
- */
-static int decode_tns(AACContext *ac, TemporalNoiseShaping *tns,
-                      GetBitContext *gb, const IndividualChannelStream *ics)
-{
-    int w, filt, i, coef_len, coef_res, coef_compress;
-    const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
-    const int tns_max_order = is8 ? 7 : ac->m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
-    for (w = 0; w < ics->num_windows; w++) {
-        if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
-            coef_res = get_bits1(gb);
-
-            for (filt = 0; filt < tns->n_filt[w]; filt++) {
-                int tmp2_idx;
-                tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
-
-                if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
-                    av_log(ac->avccontext, AV_LOG_ERROR, "TNS filter order %d is greater than maximum %d.\n",
-                           tns->order[w][filt], tns_max_order);
-                    tns->order[w][filt] = 0;
-                    return -1;
-                }
-                if (tns->order[w][filt]) {
-                    tns->direction[w][filt] = get_bits1(gb);
-                    coef_compress = get_bits1(gb);
-                    coef_len = coef_res + 3 - coef_compress;
-                    tmp2_idx = 2 * coef_compress + coef_res;
-
-                    for (i = 0; i < tns->order[w][filt]; i++)
-                        tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
-                }
-            }
-        }
-    }
-    return 0;
-}
-
-/**
- * Decode Mid/Side data; reference: table 4.54.
- *
- * @param   ms_present  Indicates mid/side stereo presence. [0] mask is all 0s;
- *                      [1] mask is decoded from bitstream; [2] mask is all 1s;
- *                      [3] reserved for scalable AAC
- */
-static void decode_mid_side_stereo(ChannelElement *cpe, GetBitContext *gb,
-                                   int ms_present)
-{
-    int idx;
-    if (ms_present == 1) {
-        for (idx = 0; idx < cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb; idx++)
-            cpe->ms_mask[idx] = get_bits1(gb);
-    } else if (ms_present == 2) {
-        memset(cpe->ms_mask, 1, cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb * sizeof(cpe->ms_mask[0]));
-    }
-}
-
-#ifndef VMUL2
-static inline float *VMUL2(float *dst, const float *v, unsigned idx,
-                           const float *scale)
-{
-    float s = *scale;
-    *dst++ = v[idx    & 15] * s;
-    *dst++ = v[idx>>4 & 15] * s;
-    return dst;
-}
-#endif
-
-#ifndef VMUL4
-static inline float *VMUL4(float *dst, const float *v, unsigned idx,
-                           const float *scale)
-{
-    float s = *scale;
-    *dst++ = v[idx    & 3] * s;
-    *dst++ = v[idx>>2 & 3] * s;
-    *dst++ = v[idx>>4 & 3] * s;
-    *dst++ = v[idx>>6 & 3] * s;
-    return dst;
-}
-#endif
-
-#ifndef VMUL2S
-static inline float *VMUL2S(float *dst, const float *v, unsigned idx,
-                            unsigned sign, const float *scale)
-{
-    union float754 s0, s1;
-
-    s0.f = s1.f = *scale;
-    s0.i ^= sign >> 1 << 31;
-    s1.i ^= sign      << 31;
-
-    *dst++ = v[idx    & 15] * s0.f;
-    *dst++ = v[idx>>4 & 15] * s1.f;
-
-    return dst;
-}
-#endif
-
-#ifndef VMUL4S
-static inline float *VMUL4S(float *dst, const float *v, unsigned idx,
-                            unsigned sign, const float *scale)
-{
-    unsigned nz = idx >> 12;
-    union float754 s = { .f = *scale };
-    union float754 t;
-
-    t.i = s.i ^ (sign & 1<<31);
-    *dst++ = v[idx    & 3] * t.f;
-
-    sign <<= nz & 1; nz >>= 1;
-    t.i = s.i ^ (sign & 1<<31);
-    *dst++ = v[idx>>2 & 3] * t.f;
-
-    sign <<= nz & 1; nz >>= 1;
-    t.i = s.i ^ (sign & 1<<31);
-    *dst++ = v[idx>>4 & 3] * t.f;
-
-    sign <<= nz & 1; nz >>= 1;
-    t.i = s.i ^ (sign & 1<<31);
-    *dst++ = v[idx>>6 & 3] * t.f;
-
-    return dst;
-}
-#endif
-
-/**
- * Decode spectral data; reference: table 4.50.
- * Dequantize and scale spectral data; reference: 4.6.3.3.
- *
- * @param   coef            array of dequantized, scaled spectral data
- * @param   sf              array of scalefactors or intensity stereo positions
- * @param   pulse_present   set if pulses are present
- * @param   pulse           pointer to pulse data struct
- * @param   band_type       array of the used band type
- *
- * @return  Returns error status. 0 - OK, !0 - error
- */
-static int decode_spectrum_and_dequant(AACContext *ac, float coef[1024],
-                                       GetBitContext *gb, const float sf[120],
-                                       int pulse_present, const Pulse *pulse,
-                                       const IndividualChannelStream *ics,
-                                       enum BandType band_type[120])
-{
-    int i, k, g, idx = 0;
-    const int c = 1024 / ics->num_windows;
-    const uint16_t *offsets = ics->swb_offset;
-    float *coef_base = coef;
-    int err_idx;
-
-    for (g = 0; g < ics->num_windows; g++)
-        memset(coef + g * 128 + offsets[ics->max_sfb], 0, sizeof(float) * (c - offsets[ics->max_sfb]));
-
-    for (g = 0; g < ics->num_window_groups; g++) {
-        unsigned g_len = ics->group_len[g];
-
-        for (i = 0; i < ics->max_sfb; i++, idx++) {
-            const unsigned cbt_m1 = band_type[idx] - 1;
-            float *cfo = coef + offsets[i];
-            int off_len = offsets[i + 1] - offsets[i];
-            int group;
-
-            if (cbt_m1 >= INTENSITY_BT2 - 1) {
-                for (group = 0; group < g_len; group++, cfo+=128) {
-                    memset(cfo, 0, off_len * sizeof(float));
-                }
-            } else if (cbt_m1 == NOISE_BT - 1) {
-                for (group = 0; group < g_len; group++, cfo+=128) {
-                    float scale;
-                    float band_energy;
-
-                    for (k = 0; k < off_len; k++) {
-                        ac->random_state  = lcg_random(ac->random_state);
-                        cfo[k] = ac->random_state;
-                    }
-
-                    band_energy = ac->dsp.scalarproduct_float(cfo, cfo, off_len);
-                    scale = sf[idx] / sqrtf(band_energy);
-                    ac->dsp.vector_fmul_scalar(cfo, cfo, scale, off_len);
-                }
-            } else {
-                const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
-                const uint16_t *cb_vector_idx = ff_aac_codebook_vector_idx[cbt_m1];
-                VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
-                const int cb_size = ff_aac_spectral_sizes[cbt_m1];
-                OPEN_READER(re, gb);
-
-                switch (cbt_m1 >> 1) {
-                case 0:
-                    for (group = 0; group < g_len; group++, cfo+=128) {
-                        float *cf = cfo;
-                        int len = off_len;
-
-                        do {
-                            int code;
-                            unsigned cb_idx;
-
-                            UPDATE_CACHE(re, gb);
-                            GET_VLC(code, re, gb, vlc_tab, 8, 2);
-
-                            if (code >= cb_size) {
-                                err_idx = code;
-                                goto err_cb_overflow;
-                            }
-
-                            cb_idx = cb_vector_idx[code];
-                            cf = VMUL4(cf, vq, cb_idx, sf + idx);
-                        } while (len -= 4);
-                    }
-                    break;
-
-                case 1:
-                    for (group = 0; group < g_len; group++, cfo+=128) {
-                        float *cf = cfo;
-                        int len = off_len;
-
-                        do {
-                            int code;
-                            unsigned nnz;
-                            unsigned cb_idx;
-                            uint32_t bits;
-
-                            UPDATE_CACHE(re, gb);
-                            GET_VLC(code, re, gb, vlc_tab, 8, 2);
-
-                            if (code >= cb_size) {
-                                err_idx = code;
-                                goto err_cb_overflow;
-                            }
-
-#if MIN_CACHE_BITS < 20
-                            UPDATE_CACHE(re, gb);
-#endif
-                            cb_idx = cb_vector_idx[code];
-                            nnz = cb_idx >> 8 & 15;
-                            bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
-                            LAST_SKIP_BITS(re, gb, nnz);
-                            cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
-                        } while (len -= 4);
-                    }
-                    break;
-
-                case 2:
-                    for (group = 0; group < g_len; group++, cfo+=128) {
-                        float *cf = cfo;
-                        int len = off_len;
-
-                        do {
-                            int code;
-                            unsigned cb_idx;
-
-                            UPDATE_CACHE(re, gb);
-                            GET_VLC(code, re, gb, vlc_tab, 8, 2);
-
-                            if (code >= cb_size) {
-                                err_idx = code;
-                                goto err_cb_overflow;
-                            }
-
-                            cb_idx = cb_vector_idx[code];
-                            cf = VMUL2(cf, vq, cb_idx, sf + idx);
-                        } while (len -= 2);
-                    }
-                    break;
-
-                case 3:
-                case 4:
-                    for (group = 0; group < g_len; group++, cfo+=128) {
-                        float *cf = cfo;
-                        int len = off_len;
-
-                        do {
-                            int code;
-                            unsigned nnz;
-                            unsigned cb_idx;
-                            unsigned sign;
-
-                            UPDATE_CACHE(re, gb);
-                            GET_VLC(code, re, gb, vlc_tab, 8, 2);
-
-                            if (code >= cb_size) {
-                                err_idx = code;
-                                goto err_cb_overflow;
-                            }
-
-                            cb_idx = cb_vector_idx[code];
-                            nnz = cb_idx >> 8 & 15;
-                            sign = SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12);
-                            LAST_SKIP_BITS(re, gb, nnz);
-                            cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
-                        } while (len -= 2);
-                    }
-                    break;
-
-                default:
-                    for (group = 0; group < g_len; group++, cfo+=128) {
-                        float *cf = cfo;
-                        uint32_t *icf = (uint32_t *) cf;
-                        int len = off_len;
-
-                        do {
-                            int code;
-                            unsigned nzt, nnz;
-                            unsigned cb_idx;
-                            uint32_t bits;
-                            int j;
-
-                            UPDATE_CACHE(re, gb);
-                            GET_VLC(code, re, gb, vlc_tab, 8, 2);
-
-                            if (!code) {
-                                *icf++ = 0;
-                                *icf++ = 0;
-                                continue;
-                            }
-
-                            if (code >= cb_size) {
-                                err_idx = code;
-                                goto err_cb_overflow;
-                            }
-
-                            cb_idx = cb_vector_idx[code];
-                            nnz = cb_idx >> 12;
-                            nzt = cb_idx >> 8;
-                            bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
-                            LAST_SKIP_BITS(re, gb, nnz);
-
-                            for (j = 0; j < 2; j++) {
-                                if (nzt & 1<<j) {
-                                    uint32_t b;
-                                    int n;
-                                    /* The total length of escape_sequence must be < 22 bits according
-                                       to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
-                                    UPDATE_CACHE(re, gb);
-                                    b = GET_CACHE(re, gb);
-                                    b = 31 - av_log2(~b);
-
-                                    if (b > 8) {
-                                        av_log(ac->avccontext, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
-                                        return -1;
-                                    }
-
-#if MIN_CACHE_BITS < 21
-                                    LAST_SKIP_BITS(re, gb, b + 1);
-                                    UPDATE_CACHE(re, gb);
-#else
-                                    SKIP_BITS(re, gb, b + 1);
-#endif
-                                    b += 4;
-                                    n = (1 << b) + SHOW_UBITS(re, gb, b);
-                                    LAST_SKIP_BITS(re, gb, b);
-                                    *icf++ = cbrt_tab[n] | (bits & 1<<31);
-                                    bits <<= 1;
-                                } else {
-                                    unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
-                                    *icf++ = (bits & 1<<31) | v;
-                                    bits <<= !!v;
-                                }
-                                cb_idx >>= 4;
-                            }
-                        } while (len -= 2);
-
-                        ac->dsp.vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
-                    }
-                }
-
-                CLOSE_READER(re, gb);
-            }
-        }
-        coef += g_len << 7;
-    }
-
-    if (pulse_present) {
-        idx = 0;
-        for (i = 0; i < pulse->num_pulse; i++) {
-            float co = coef_base[ pulse->pos[i] ];
-            while (offsets[idx + 1] <= pulse->pos[i])
-                idx++;
-            if (band_type[idx] != NOISE_BT && sf[idx]) {
-                float ico = -pulse->amp[i];
-                if (co) {
-                    co /= sf[idx];
-                    ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
-                }
-                coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
-            }
-        }
-    }
-    return 0;
-
-err_cb_overflow:
-    av_log(ac->avccontext, AV_LOG_ERROR,
-           "Read beyond end of ff_aac_codebook_vectors[%d][]. index %d >= %d\n",
-           band_type[idx], err_idx, ff_aac_spectral_sizes[band_type[idx]]);
-    return -1;
-}
-
-static av_always_inline float flt16_round(float pf)
-{
-    union float754 tmp;
-    tmp.f = pf;
-    tmp.i = (tmp.i + 0x00008000U) & 0xFFFF0000U;
-    return tmp.f;
-}
-
-static av_always_inline float flt16_even(float pf)
-{
-    union float754 tmp;
-    tmp.f = pf;
-    tmp.i = (tmp.i + 0x00007FFFU + (tmp.i & 0x00010000U >> 16)) & 0xFFFF0000U;
-    return tmp.f;
-}
-
-static av_always_inline float flt16_trunc(float pf)
-{
-    union float754 pun;
-    pun.f = pf;
-    pun.i &= 0xFFFF0000U;
-    return pun.f;
-}
-
-static av_always_inline void predict(AACContext *ac, PredictorState *ps, float *coef,
-                    int output_enable)
-{
-    const float a     = 0.953125; // 61.0 / 64
-    const float alpha = 0.90625;  // 29.0 / 32
-    float e0, e1;
-    float pv;
-    float k1, k2;
-
-    k1 = ps->var0 > 1 ? ps->cor0 * flt16_even(a / ps->var0) : 0;
-    k2 = ps->var1 > 1 ? ps->cor1 * flt16_even(a / ps->var1) : 0;
-
-    pv = flt16_round(k1 * ps->r0 + k2 * ps->r1);
-    if (output_enable)
-        *coef += pv * ac->sf_scale;
-
-    e0 = *coef / ac->sf_scale;
-    e1 = e0 - k1 * ps->r0;
-
-    ps->cor1 = flt16_trunc(alpha * ps->cor1 + ps->r1 * e1);
-    ps->var1 = flt16_trunc(alpha * ps->var1 + 0.5 * (ps->r1 * ps->r1 + e1 * e1));
-    ps->cor0 = flt16_trunc(alpha * ps->cor0 + ps->r0 * e0);
-    ps->var0 = flt16_trunc(alpha * ps->var0 + 0.5 * (ps->r0 * ps->r0 + e0 * e0));
-
-    ps->r1 = flt16_trunc(a * (ps->r0 - k1 * e0));
-    ps->r0 = flt16_trunc(a * e0);
-}
-
-/**
- * Apply AAC-Main style frequency domain prediction.
- */
-static void apply_prediction(AACContext *ac, SingleChannelElement *sce)
-{
-    int sfb, k;
-
-    if (!sce->ics.predictor_initialized) {
-        reset_all_predictors(sce->predictor_state);
-        sce->ics.predictor_initialized = 1;
-    }
-
-    if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
-        for (sfb = 0; sfb < ff_aac_pred_sfb_max[ac->m4ac.sampling_index]; sfb++) {
-            for (k = sce->ics.swb_offset[sfb]; k < sce->ics.swb_offset[sfb + 1]; k++) {
-                predict(ac, &sce->predictor_state[k], &sce->coeffs[k],
-                        sce->ics.predictor_present && sce->ics.prediction_used[sfb]);
-            }
-        }
-        if (sce->ics.predictor_reset_group)
-            reset_predictor_group(sce->predictor_state, sce->ics.predictor_reset_group);
-    } else
-        reset_all_predictors(sce->predictor_state);
-}
-
-/**
- * Decode an individual_channel_stream payload; reference: table 4.44.
- *
- * @param   common_window   Channels have independent [0], or shared [1], Individual Channel Stream information.
- * @param   scale_flag      scalable [1] or non-scalable [0] AAC (Unused until scalable AAC is implemented.)
- *
- * @return  Returns error status. 0 - OK, !0 - error
- */
-static int decode_ics(AACContext *ac, SingleChannelElement *sce,
-                      GetBitContext *gb, int common_window, int scale_flag)
-{
-    Pulse pulse;
-    TemporalNoiseShaping    *tns = &sce->tns;
-    IndividualChannelStream *ics = &sce->ics;
-    float *out = sce->coeffs;
-    int global_gain, pulse_present = 0;
-
-    /* This assignment is to silence a GCC warning about the variable being used
-     * uninitialized when in fact it always is.
-     */
-    pulse.num_pulse = 0;
-
-    global_gain = get_bits(gb, 8);
-
-    if (!common_window && !scale_flag) {
-        if (decode_ics_info(ac, ics, gb, 0) < 0)
-            return -1;
-    }
-
-    if (decode_band_types(ac, sce->band_type, sce->band_type_run_end, gb, ics) < 0)
-        return -1;
-    if (decode_scalefactors(ac, sce->sf, gb, global_gain, ics, sce->band_type, sce->band_type_run_end) < 0)
-        return -1;
-
-    pulse_present = 0;
-    if (!scale_flag) {
-        if ((pulse_present = get_bits1(gb))) {
-            if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
-                av_log(ac->avccontext, AV_LOG_ERROR, "Pulse tool not allowed in eight short sequence.\n");
-                return -1;
-            }
-            if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
-                av_log(ac->avccontext, AV_LOG_ERROR, "Pulse data corrupt or invalid.\n");
-                return -1;
-            }
-        }
-        if ((tns->present = get_bits1(gb)) && decode_tns(ac, tns, gb, ics))
-            return -1;
-        if (get_bits1(gb)) {
-            av_log_missing_feature(ac->avccontext, "SSR", 1);
-            return -1;
-        }
-    }
-
-    if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present, &pulse, ics, sce->band_type) < 0)
-        return -1;
-
-    if (ac->m4ac.object_type == AOT_AAC_MAIN && !common_window)
-        apply_prediction(ac, sce);
-
-    return 0;
-}
-
-/**
- * Mid/Side stereo decoding; reference: 4.6.8.1.3.
- */
-static void apply_mid_side_stereo(AACContext *ac, ChannelElement *cpe)
-{
-    const IndividualChannelStream *ics = &cpe->ch[0].ics;
-    float *ch0 = cpe->ch[0].coeffs;
-    float *ch1 = cpe->ch[1].coeffs;
-    int g, i, group, idx = 0;
-    const uint16_t *offsets = ics->swb_offset;
-    for (g = 0; g < ics->num_window_groups; g++) {
-        for (i = 0; i < ics->max_sfb; i++, idx++) {
-            if (cpe->ms_mask[idx] &&
-                    cpe->ch[0].band_type[idx] < NOISE_BT && cpe->ch[1].band_type[idx] < NOISE_BT) {
-                for (group = 0; group < ics->group_len[g]; group++) {
-                    ac->dsp.butterflies_float(ch0 + group * 128 + offsets[i],
-                                              ch1 + group * 128 + offsets[i],
-                                              offsets[i+1] - offsets[i]);
-                }
-            }
-        }
-        ch0 += ics->group_len[g] * 128;
-        ch1 += ics->group_len[g] * 128;
-    }
-}
-
-/**
- * intensity stereo decoding; reference: 4.6.8.2.3
- *
- * @param   ms_present  Indicates mid/side stereo presence. [0] mask is all 0s;
- *                      [1] mask is decoded from bitstream; [2] mask is all 1s;
- *                      [3] reserved for scalable AAC
- */
-static void apply_intensity_stereo(ChannelElement *cpe, int ms_present)
-{
-    const IndividualChannelStream *ics = &cpe->ch[1].ics;
-    SingleChannelElement         *sce1 = &cpe->ch[1];
-    float *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
-    const uint16_t *offsets = ics->swb_offset;
-    int g, group, i, k, idx = 0;
-    int c;
-    float scale;
-    for (g = 0; g < ics->num_window_groups; g++) {
-        for (i = 0; i < ics->max_sfb;) {
-            if (sce1->band_type[idx] == INTENSITY_BT || sce1->band_type[idx] == INTENSITY_BT2) {
-                const int bt_run_end = sce1->band_type_run_end[idx];
-                for (; i < bt_run_end; i++, idx++) {
-                    c = -1 + 2 * (sce1->band_type[idx] - 14);
-                    if (ms_present)
-                        c *= 1 - 2 * cpe->ms_mask[idx];
-                    scale = c * sce1->sf[idx];
-                    for (group = 0; group < ics->group_len[g]; group++)
-                        for (k = offsets[i]; k < offsets[i + 1]; k++)
-                            coef1[group * 128 + k] = scale * coef0[group * 128 + k];
-                }
-            } else {
-                int bt_run_end = sce1->band_type_run_end[idx];
-                idx += bt_run_end - i;
-                i    = bt_run_end;
-            }
-        }
-        coef0 += ics->group_len[g] * 128;
-        coef1 += ics->group_len[g] * 128;
-    }
-}
-
-/**
- * Decode a channel_pair_element; reference: table 4.4.
- *
- * @param   elem_id Identifies the instance of a syntax element.
- *
- * @return  Returns error status. 0 - OK, !0 - error
- */
-static int decode_cpe(AACContext *ac, GetBitContext *gb, ChannelElement *cpe)
-{
-    int i, ret, common_window, ms_present = 0;
-
-    common_window = get_bits1(gb);
-    if (common_window) {
-        if (decode_ics_info(ac, &cpe->ch[0].ics, gb, 1))
-            return -1;
-        i = cpe->ch[1].ics.use_kb_window[0];
-        cpe->ch[1].ics = cpe->ch[0].ics;
-        cpe->ch[1].ics.use_kb_window[1] = i;
-        ms_present = get_bits(gb, 2);
-        if (ms_present == 3) {
-            av_log(ac->avccontext, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
-            return -1;
-        } else if (ms_present)
-            decode_mid_side_stereo(cpe, gb, ms_present);
-    }
-    if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
-        return ret;
-    if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
-        return ret;
-
-    if (common_window) {
-        if (ms_present)
-            apply_mid_side_stereo(ac, cpe);
-        if (ac->m4ac.object_type == AOT_AAC_MAIN) {
-            apply_prediction(ac, &cpe->ch[0]);
-            apply_prediction(ac, &cpe->ch[1]);
-        }
-    }
-
-    apply_intensity_stereo(cpe, ms_present);
-    return 0;
-}
-
-/**
- * Decode coupling_channel_element; reference: table 4.8.
- *
- * @param   elem_id Identifies the instance of a syntax element.
- *
- * @return  Returns error status. 0 - OK, !0 - error
- */
-static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
-{
-    int num_gain = 0;
-    int c, g, sfb, ret;
-    int sign;
-    float scale;
-    SingleChannelElement *sce = &che->ch[0];
-    ChannelCoupling     *coup = &che->coup;
-
-    coup->coupling_point = 2 * get_bits1(gb);
-    coup->num_coupled = get_bits(gb, 3);
-    for (c = 0; c <= coup->num_coupled; c++) {
-        num_gain++;
-        coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
-        coup->id_select[c] = get_bits(gb, 4);
-        if (coup->type[c] == TYPE_CPE) {
-            coup->ch_select[c] = get_bits(gb, 2);
-            if (coup->ch_select[c] == 3)
-                num_gain++;
-        } else
-            coup->ch_select[c] = 2;
-    }
-    coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
-
-    sign  = get_bits(gb, 1);
-    scale = pow(2., pow(2., (int)get_bits(gb, 2) - 3));
-
-    if ((ret = decode_ics(ac, sce, gb, 0, 0)))
-        return ret;
-
-    for (c = 0; c < num_gain; c++) {
-        int idx  = 0;
-        int cge  = 1;
-        int gain = 0;
-        float gain_cache = 1.;
-        if (c) {
-            cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
-            gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
-            gain_cache = pow(scale, -gain);
-        }
-        if (coup->coupling_point == AFTER_IMDCT) {
-            coup->gain[c][0] = gain_cache;
-        } else {
-            for (g = 0; g < sce->ics.num_window_groups; g++) {
-                for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
-                    if (sce->band_type[idx] != ZERO_BT) {
-                        if (!cge) {
-                            int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
-                            if (t) {
-                                int s = 1;
-                                t = gain += t;
-                                if (sign) {
-                                    s  -= 2 * (t & 0x1);
-                                    t >>= 1;
-                                }
-                                gain_cache = pow(scale, -t) * s;
-                            }
-                        }
-                        coup->gain[c][idx] = gain_cache;
-                    }
-                }
-            }
-        }
-    }
-    return 0;
-}
-
-/**
- * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
- *
- * @return  Returns number of bytes consumed.
- */
-static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc,
-                                         GetBitContext *gb)
-{
-    int i;
-    int num_excl_chan = 0;
-
-    do {
-        for (i = 0; i < 7; i++)
-            che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
-    } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
-
-    return num_excl_chan / 7;
-}
-
-/**
- * Decode dynamic range information; reference: table 4.52.
- *
- * @param   cnt length of TYPE_FIL syntactic element in bytes
- *
- * @return  Returns number of bytes consumed.
- */
-static int decode_dynamic_range(DynamicRangeControl *che_drc,
-                                GetBitContext *gb, int cnt)
-{
-    int n             = 1;
-    int drc_num_bands = 1;
-    int i;
-
-    /* pce_tag_present? */
-    if (get_bits1(gb)) {
-        che_drc->pce_instance_tag  = get_bits(gb, 4);
-        skip_bits(gb, 4); // tag_reserved_bits
-        n++;
-    }
-
-    /* excluded_chns_present? */
-    if (get_bits1(gb)) {
-        n += decode_drc_channel_exclusions(che_drc, gb);
-    }
-
-    /* drc_bands_present? */
-    if (get_bits1(gb)) {
-        che_drc->band_incr            = get_bits(gb, 4);
-        che_drc->interpolation_scheme = get_bits(gb, 4);
-        n++;
-        drc_num_bands += che_drc->band_incr;
-        for (i = 0; i < drc_num_bands; i++) {
-            che_drc->band_top[i] = get_bits(gb, 8);
-            n++;
-        }
-    }
-
-    /* prog_ref_level_present? */
-    if (get_bits1(gb)) {
-        che_drc->prog_ref_level = get_bits(gb, 7);
-        skip_bits1(gb); // prog_ref_level_reserved_bits
-        n++;
-    }
-
-    for (i = 0; i < drc_num_bands; i++) {
-        che_drc->dyn_rng_sgn[i] = get_bits1(gb);
-        che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
-        n++;
-    }
-
-    return n;
-}
-
-/**
- * Decode extension data (incomplete); reference: table 4.51.
- *
- * @param   cnt length of TYPE_FIL syntactic element in bytes
- *
- * @return Returns number of bytes consumed
- */
-static int decode_extension_payload(AACContext *ac, GetBitContext *gb, int cnt,
-                                    ChannelElement *che, enum RawDataBlockType elem_type)
-{
-    int crc_flag = 0;
-    int res = cnt;
-    switch (get_bits(gb, 4)) { // extension type
-    case EXT_SBR_DATA_CRC:
-        crc_flag++;
-    case EXT_SBR_DATA:
-        if (!che) {
-            av_log(ac->avccontext, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
-            return res;
-        } else if (!ac->m4ac.sbr) {
-            av_log(ac->avccontext, AV_LOG_ERROR, "SBR signaled to be not-present but was found in the bitstream.\n");
-            skip_bits_long(gb, 8 * cnt - 4);
-            return res;
-        } else if (ac->m4ac.sbr == -1 && ac->output_configured == OC_LOCKED) {
-            av_log(ac->avccontext, AV_LOG_ERROR, "Implicit SBR was found with a first occurrence after the first frame.\n");
-            skip_bits_long(gb, 8 * cnt - 4);
-            return res;
-        } else {
-            ac->m4ac.sbr = 1;
-        }
-        res = ff_decode_sbr_extension(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
-        break;
-    case EXT_DYNAMIC_RANGE:
-        res = decode_dynamic_range(&ac->che_drc, gb, cnt);
-        break;
-    case EXT_FILL:
-    case EXT_FILL_DATA:
-    case EXT_DATA_ELEMENT:
-    default:
-        skip_bits_long(gb, 8 * cnt - 4);
-        break;
-    };
-    return res;
-}
-
-/**
- * Decode Temporal Noise Shaping filter coefficients and apply all-pole filters; reference: 4.6.9.3.
- *
- * @param   decode  1 if tool is used normally, 0 if tool is used in LTP.
- * @param   coef    spectral coefficients
- */
-static void apply_tns(float coef[1024], TemporalNoiseShaping *tns,
-                      IndividualChannelStream *ics, int decode)
-{
-    const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
-    int w, filt, m, i;
-    int bottom, top, order, start, end, size, inc;
-    float lpc[TNS_MAX_ORDER];
-
-    for (w = 0; w < ics->num_windows; w++) {
-        bottom = ics->num_swb;
-        for (filt = 0; filt < tns->n_filt[w]; filt++) {
-            top    = bottom;
-            bottom = FFMAX(0, top - tns->length[w][filt]);
-            order  = tns->order[w][filt];
-            if (order == 0)
-                continue;
-
-            // tns_decode_coef
-            compute_lpc_coefs(tns->coef[w][filt], order, lpc, 0, 0, 0);
-
-            start = ics->swb_offset[FFMIN(bottom, mmm)];
-            end   = ics->swb_offset[FFMIN(   top, mmm)];
-            if ((size = end - start) <= 0)
-                continue;
-            if (tns->direction[w][filt]) {
-                inc = -1;
-                start = end - 1;
-            } else {
-                inc = 1;
-            }
-            start += w * 128;
-
-            // ar filter
-            for (m = 0; m < size; m++, start += inc)
-                for (i = 1; i <= FFMIN(m, order); i++)
-                    coef[start] -= coef[start - i * inc] * lpc[i - 1];
-        }
-    }
-}
-
-/**
- * Conduct IMDCT and windowing.
- */
-static void imdct_and_windowing(AACContext *ac, SingleChannelElement *sce, float bias)
-{
-    IndividualChannelStream *ics = &sce->ics;
-    float *in    = sce->coeffs;
-    float *out   = sce->ret;
-    float *saved = sce->saved;
-    const float *swindow      = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
-    const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
-    const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
-    float *buf  = ac->buf_mdct;
-    float *temp = ac->temp;
-    int i;
-
-    // imdct
-    if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
-        if (ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE)
-            av_log(ac->avccontext, AV_LOG_WARNING,
-                   "Transition from an ONLY_LONG or LONG_STOP to an EIGHT_SHORT sequence detected. "
-                   "If you heard an audible artifact, please submit the sample to the FFmpeg developers.\n");
-        for (i = 0; i < 1024; i += 128)
-            ff_imdct_half(&ac->mdct_small, buf + i, in + i);
-    } else
-        ff_imdct_half(&ac->mdct, buf, in);
-
-    /* window overlapping
-     * NOTE: To simplify the overlapping code, all 'meaningless' short to long
-     * and long to short transitions are considered to be short to short
-     * transitions. This leaves just two cases (long to long and short to short)
-     * with a little special sauce for EIGHT_SHORT_SEQUENCE.
-     */
-    if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
-            (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
-        ac->dsp.vector_fmul_window(    out,               saved,            buf,         lwindow_prev, bias, 512);
-    } else {
-        for (i = 0; i < 448; i++)
-            out[i] = saved[i] + bias;
-
-        if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
-            ac->dsp.vector_fmul_window(out + 448 + 0*128, saved + 448,      buf + 0*128, swindow_prev, bias, 64);
-            ac->dsp.vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow,      bias, 64);
-            ac->dsp.vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow,      bias, 64);
-            ac->dsp.vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow,      bias, 64);
-            ac->dsp.vector_fmul_window(temp,              buf + 3*128 + 64, buf + 4*128, swindow,      bias, 64);
-            memcpy(                    out + 448 + 4*128, temp, 64 * sizeof(float));
-        } else {
-            ac->dsp.vector_fmul_window(out + 448,         saved + 448,      buf,         swindow_prev, bias, 64);
-            for (i = 576; i < 1024; i++)
-                out[i] = buf[i-512] + bias;
-        }
-    }
-
-    // buffer update
-    if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
-        for (i = 0; i < 64; i++)
-            saved[i] = temp[64 + i] - bias;
-        ac->dsp.vector_fmul_window(saved + 64,  buf + 4*128 + 64, buf + 5*128, swindow, 0, 64);
-        ac->dsp.vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 0, 64);
-        ac->dsp.vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 0, 64);
-        memcpy(                    saved + 448, buf + 7*128 + 64,  64 * sizeof(float));
-    } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
-        memcpy(                    saved,       buf + 512,        448 * sizeof(float));
-        memcpy(                    saved + 448, buf + 7*128 + 64,  64 * sizeof(float));
-    } else { // LONG_STOP or ONLY_LONG
-        memcpy(                    saved,       buf + 512,        512 * sizeof(float));
-    }
-}
-
-/**
- * Apply dependent channel coupling (applied before IMDCT).
- *
- * @param   index   index into coupling gain array
- */
-static void apply_dependent_coupling(AACContext *ac,
-                                     SingleChannelElement *target,
-                                     ChannelElement *cce, int index)
-{
-    IndividualChannelStream *ics = &cce->ch[0].ics;
-    const uint16_t *offsets = ics->swb_offset;
-    float *dest = target->coeffs;
-    const float *src = cce->ch[0].coeffs;
-    int g, i, group, k, idx = 0;
-    if (ac->m4ac.object_type == AOT_AAC_LTP) {
-        av_log(ac->avccontext, AV_LOG_ERROR,
-               "Dependent coupling is not supported together with LTP\n");
-        return;
-    }
-    for (g = 0; g < ics->num_window_groups; g++) {
-        for (i = 0; i < ics->max_sfb; i++, idx++) {
-            if (cce->ch[0].band_type[idx] != ZERO_BT) {
-                const float gain = cce->coup.gain[index][idx];
-                for (group = 0; group < ics->group_len[g]; group++) {
-                    for (k = offsets[i]; k < offsets[i + 1]; k++) {
-                        // XXX dsputil-ize
-                        dest[group * 128 + k] += gain * src[group * 128 + k];
-                    }
-                }
-            }
-        }
-        dest += ics->group_len[g] * 128;
-        src  += ics->group_len[g] * 128;
-    }
-}
-
-/**
- * Apply independent channel coupling (applied after IMDCT).
- *
- * @param   index   index into coupling gain array
- */
-static void apply_independent_coupling(AACContext *ac,
-                                       SingleChannelElement *target,
-                                       ChannelElement *cce, int index)
-{
-    int i;
-    const float gain = cce->coup.gain[index][0];
-    const float bias = ac->add_bias;
-    const float *src = cce->ch[0].ret;
-    float *dest = target->ret;
-    const int len = 1024 << (ac->m4ac.sbr == 1);
-
-    for (i = 0; i < len; i++)
-        dest[i] += gain * (src[i] - bias);
-}
-
-/**
- * channel coupling transformation interface
- *
- * @param   index   index into coupling gain array
- * @param   apply_coupling_method   pointer to (in)dependent coupling function
- */
-static void apply_channel_coupling(AACContext *ac, ChannelElement *cc,
-                                   enum RawDataBlockType type, int elem_id,
-                                   enum CouplingPoint coupling_point,
-                                   void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
-{
-    int i, c;
-
-    for (i = 0; i < MAX_ELEM_ID; i++) {
-        ChannelElement *cce = ac->che[TYPE_CCE][i];
-        int index = 0;
-
-        if (cce && cce->coup.coupling_point == coupling_point) {
-            ChannelCoupling *coup = &cce->coup;
-
-            for (c = 0; c <= coup->num_coupled; c++) {
-                if (coup->type[c] == type && coup->id_select[c] == elem_id) {
-                    if (coup->ch_select[c] != 1) {
-                        apply_coupling_method(ac, &cc->ch[0], cce, index);
-                        if (coup->ch_select[c] != 0)
-                            index++;
-                    }
-                    if (coup->ch_select[c] != 2)
-                        apply_coupling_method(ac, &cc->ch[1], cce, index++);
-                } else
-                    index += 1 + (coup->ch_select[c] == 3);
-            }
-        }
-    }
-}
-
-/**
- * Convert spectral data to float samples, applying all supported tools as appropriate.
- */
-static void spectral_to_sample(AACContext *ac)
-{
-    int i, type;
-    float imdct_bias = (ac->m4ac.sbr <= 0) ? ac->add_bias : 0.0f;
-    for (type = 3; type >= 0; type--) {
-        for (i = 0; i < MAX_ELEM_ID; i++) {
-            ChannelElement *che = ac->che[type][i];
-            if (che) {
-                if (type <= TYPE_CPE)
-                    apply_channel_coupling(ac, che, type, i, BEFORE_TNS, apply_dependent_coupling);
-                if (che->ch[0].tns.present)
-                    apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
-                if (che->ch[1].tns.present)
-                    apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
-                if (type <= TYPE_CPE)
-                    apply_channel_coupling(ac, che, type, i, BETWEEN_TNS_AND_IMDCT, apply_dependent_coupling);
-                if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
-                    imdct_and_windowing(ac, &che->ch[0], imdct_bias);
-                    if (type == TYPE_CPE) {
-                        imdct_and_windowing(ac, &che->ch[1], imdct_bias);
-                    }
-                    if (ac->m4ac.sbr > 0) {
-                        ff_sbr_apply(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
-                    }
-                }
-                if (type <= TYPE_CCE)
-                    apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, apply_independent_coupling);
-            }
-        }
-    }
-}
-
-static int parse_adts_frame_header(AACContext *ac, GetBitContext *gb)
-{
-    int size;
-    AACADTSHeaderInfo hdr_info;
-
-    size = ff_aac_parse_header(gb, &hdr_info);
-    if (size > 0) {
-        if (ac->output_configured != OC_LOCKED && hdr_info.chan_config) {
-            enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
-            memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
-            ac->m4ac.chan_config = hdr_info.chan_config;
-            if (set_default_channel_config(ac, new_che_pos, hdr_info.chan_config))
-                return -7;
-            if (output_configure(ac, ac->che_pos, new_che_pos, hdr_info.chan_config, OC_TRIAL_FRAME))
-                return -7;
-        } else if (ac->output_configured != OC_LOCKED) {
-            ac->output_configured = OC_NONE;
-        }
-        if (ac->output_configured != OC_LOCKED)
-            ac->m4ac.sbr = -1;
-        ac->m4ac.sample_rate     = hdr_info.sample_rate;
-        ac->m4ac.sampling_index  = hdr_info.sampling_index;
-        ac->m4ac.object_type     = hdr_info.object_type;
-        if (!ac->avccontext->sample_rate)
-            ac->avccontext->sample_rate = hdr_info.sample_rate;
-        if (hdr_info.num_aac_frames == 1) {
-            if (!hdr_info.crc_absent)
-                skip_bits(gb, 16);
-        } else {
-            av_log_missing_feature(ac->avccontext, "More than one AAC RDB per ADTS frame is", 0);
-            return -1;
-        }
-    }
-    return size;
-}
-
-static int aac_decode_frame(AVCodecContext *avccontext, void *data,
-                            int *data_size, AVPacket *avpkt)
-{
-    const uint8_t *buf = avpkt->data;
-    int buf_size = avpkt->size;
-    AACContext *ac = avccontext->priv_data;
-    ChannelElement *che = NULL, *che_prev = NULL;
-    GetBitContext gb;
-    enum RawDataBlockType elem_type, elem_type_prev = TYPE_END;
-    int err, elem_id, data_size_tmp;
-    int buf_consumed;
-    int samples = 1024, multiplier;
-    int buf_offset;
-
-    init_get_bits(&gb, buf, buf_size * 8);
-
-    if (show_bits(&gb, 12) == 0xfff) {
-        if (parse_adts_frame_header(ac, &gb) < 0) {
-            av_log(avccontext, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
-            return -1;
-        }
-        if (ac->m4ac.sampling_index > 12) {
-            av_log(ac->avccontext, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->m4ac.sampling_index);
-            return -1;
-        }
-    }
-
-    // parse
-    while ((elem_type = get_bits(&gb, 3)) != TYPE_END) {
-        elem_id = get_bits(&gb, 4);
-
-        if (elem_type < TYPE_DSE && !(che=get_che(ac, elem_type, elem_id))) {
-            av_log(ac->avccontext, AV_LOG_ERROR, "channel element %d.%d is not allocated\n", elem_type, elem_id);
-            return -1;
-        }
-
-        switch (elem_type) {
-
-        case TYPE_SCE:
-            err = decode_ics(ac, &che->ch[0], &gb, 0, 0);
-            break;
-
-        case TYPE_CPE:
-            err = decode_cpe(ac, &gb, che);
-            break;
-
-        case TYPE_CCE:
-            err = decode_cce(ac, &gb, che);
-            break;
-
-        case TYPE_LFE:
-            err = decode_ics(ac, &che->ch[0], &gb, 0, 0);
-            break;
-
-        case TYPE_DSE:
-            err = skip_data_stream_element(ac, &gb);
-            break;
-
-        case TYPE_PCE: {
-            enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
-            memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
-            if ((err = decode_pce(ac, new_che_pos, &gb)))
-                break;
-            if (ac->output_configured > OC_TRIAL_PCE)
-                av_log(avccontext, AV_LOG_ERROR,
-                       "Not evaluating a further program_config_element as this construct is dubious at best.\n");
-            else
-                err = output_configure(ac, ac->che_pos, new_che_pos, 0, OC_TRIAL_PCE);
-            break;
-        }
-
-        case TYPE_FIL:
-            if (elem_id == 15)
-                elem_id += get_bits(&gb, 8) - 1;
-            if (get_bits_left(&gb) < 8 * elem_id) {
-                    av_log(avccontext, AV_LOG_ERROR, overread_err);
-                    return -1;
-            }
-            while (elem_id > 0)
-                elem_id -= decode_extension_payload(ac, &gb, elem_id, che_prev, elem_type_prev);
-            err = 0; /* FIXME */
-            break;
-
-        default:
-            err = -1; /* should not happen, but keeps compiler happy */
-            break;
-        }
-
-        che_prev       = che;
-        elem_type_prev = elem_type;
-
-        if (err)
-            return err;
-
-        if (get_bits_left(&gb) < 3) {
-            av_log(avccontext, AV_LOG_ERROR, overread_err);
-            return -1;
-        }
-    }
-
-    spectral_to_sample(ac);
-
-    multiplier = (ac->m4ac.sbr == 1) ? ac->m4ac.ext_sample_rate > ac->m4ac.sample_rate : 0;
-    samples <<= multiplier;
-    if (ac->output_configured < OC_LOCKED) {
-        avccontext->sample_rate = ac->m4ac.sample_rate << multiplier;
-        avccontext->frame_size = samples;
-    }
-
-    data_size_tmp = samples * avccontext->channels * sizeof(int16_t);
-    if (*data_size < data_size_tmp) {
-        av_log(avccontext, AV_LOG_ERROR,
-               "Output buffer too small (%d) or trying to output too many samples (%d) for this frame.\n",
-               *data_size, data_size_tmp);
-        return -1;
-    }
-    *data_size = data_size_tmp;
-
-    ac->dsp.float_to_int16_interleave(data, (const float **)ac->output_data, samples, avccontext->channels);
-
-    if (ac->output_configured)
-        ac->output_configured = OC_LOCKED;
-
-    buf_consumed = (get_bits_count(&gb) + 7) >> 3;
-    for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
-        if (buf[buf_offset])
-            break;
-
-    return buf_size > buf_offset ? buf_consumed : buf_size;
-}
-
-static av_cold int aac_decode_close(AVCodecContext *avccontext)
-{
-    AACContext *ac = avccontext->priv_data;
-    int i, type;
-
-    for (i = 0; i < MAX_ELEM_ID; i++) {
-        for (type = 0; type < 4; type++) {
-            if (ac->che[type][i])
-                ff_aac_sbr_ctx_close(&ac->che[type][i]->sbr);
-            av_freep(&ac->che[type][i]);
-        }
-    }
-
-    ff_mdct_end(&ac->mdct);
-    ff_mdct_end(&ac->mdct_small);
-    return 0;
-}
-
-AVCodec aac_decoder = {
-    "aac",
-    AVMEDIA_TYPE_AUDIO,
-    CODEC_ID_AAC,
-    sizeof(AACContext),
-    aac_decode_init,
-    NULL,
-    aac_decode_close,
-    aac_decode_frame,
-    .long_name = NULL_IF_CONFIG_SMALL("Advanced Audio Coding"),
-    .sample_fmts = (const enum SampleFormat[]) {
-        SAMPLE_FMT_S16,SAMPLE_FMT_NONE
-    },
-    .channel_layouts = aac_channel_layout,
-};
diff --git a/libavcodec/aac.h b/libavcodec/aac.h
index 1a8aa6c..e3385e2 100644
--- a/libavcodec/aac.h
+++ b/libavcodec/aac.h
@@ -3,20 +3,20 @@
  * Copyright (c) 2005-2006 Oded Shimon ( ods15 ods15 dyndns org )
  * Copyright (c) 2006-2007 Maxim Gavrilov ( maxim.gavrilov gmail com )
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -35,19 +35,15 @@
 #include "fft.h"
 #include "mpeg4audio.h"
 #include "sbr.h"
+#include "fmtconvert.h"
 
 #include <stdint.h>
 
-#define AAC_INIT_VLC_STATIC(num, size) \
-    INIT_VLC_STATIC(&vlc_spectral[num], 8, ff_aac_spectral_sizes[num], \
-         ff_aac_spectral_bits[num], sizeof( ff_aac_spectral_bits[num][0]), sizeof( ff_aac_spectral_bits[num][0]), \
-        ff_aac_spectral_codes[num], sizeof(ff_aac_spectral_codes[num][0]), sizeof(ff_aac_spectral_codes[num][0]), \
-        size);
-
 #define MAX_CHANNELS 64
 #define MAX_ELEM_ID 16
 
 #define TNS_MAX_ORDER 20
+#define MAX_LTP_LONG_SFB 40
 
 enum RawDataBlockType {
     TYPE_SCE,
@@ -136,6 +132,16 @@ typedef struct {
 #define SCALE_DIFF_ZERO  60    ///< codebook index corresponding to zero scalefactor indices difference
 
 /**
+ * Long Term Prediction
+ */
+typedef struct {
+    int8_t present;
+    int16_t lag;
+    float coef;
+    int8_t used[MAX_LTP_LONG_SFB];
+} LongTermPrediction;
+
+/**
  * Individual Channel Stream
  */
 typedef struct {
@@ -144,6 +150,7 @@ typedef struct {
     uint8_t use_kb_window[2];   ///< If set, use Kaiser-Bessel window, otherwise use a sinus window.
     int num_window_groups;
     uint8_t group_len[8];
+    LongTermPrediction ltp;
     const uint16_t *swb_offset; ///< table of offsets to the lowest spectral coefficient of a scalefactor band, sfb, for a particular window
     const uint8_t *swb_sizes;   ///< table of scalefactor band sizes for a particular window
     int num_swb;                ///< number of scalefactor window bands
@@ -211,14 +218,15 @@ typedef struct {
     IndividualChannelStream ics;
     TemporalNoiseShaping tns;
     Pulse pulse;
-    enum BandType band_type[128];             ///< band types
-    int band_type_run_end[120];               ///< band type run end points
-    float sf[120];                            ///< scalefactors
-    int sf_idx[128];                          ///< scalefactor indices (used by encoder)
-    uint8_t zeroes[128];                      ///< band is not coded (used by encoder)
-    DECLARE_ALIGNED(16, float, coeffs)[1024]; ///< coefficients for IMDCT
-    DECLARE_ALIGNED(16, float, saved)[1024];  ///< overlap
-    DECLARE_ALIGNED(16, float, ret)[2048];    ///< PCM output
+    enum BandType band_type[128];                   ///< band types
+    int band_type_run_end[120];                     ///< band type run end points
+    float sf[120];                                  ///< scalefactors
+    int sf_idx[128];                                ///< scalefactor indices (used by encoder)
+    uint8_t zeroes[128];                            ///< band is not coded (used by encoder)
+    DECLARE_ALIGNED(16, float,   coeffs)[1024];     ///< coefficients for IMDCT
+    DECLARE_ALIGNED(16, float,   saved)[1024];      ///< overlap
+    DECLARE_ALIGNED(16, float,   ret)[2048];        ///< PCM output
+    DECLARE_ALIGNED(16, int16_t, ltp_state)[3072];  ///< time signal for LTP
     PredictorState predictor_state[MAX_PREDICTORS];
 } SingleChannelElement;
 
@@ -241,7 +249,7 @@ typedef struct {
  * main AAC context
  */
 typedef struct {
-    AVCodecContext * avccontext;
+    AVCodecContext *avctx;
 
     MPEG4AudioConfig m4ac;
 
@@ -255,8 +263,8 @@ typedef struct {
     enum ChannelPosition che_pos[4][MAX_ELEM_ID]; /**< channel element channel mapping with the
                                                    *   first index as the first 4 raw data block types
                                                    */
-    ChannelElement * che[4][MAX_ELEM_ID];
-    ChannelElement * tag_che_map[4][MAX_ELEM_ID];
+    ChannelElement          *che[4][MAX_ELEM_ID];
+    ChannelElement  *tag_che_map[4][MAX_ELEM_ID];
     int tags_mapped;
     /** @} */
 
@@ -273,7 +281,9 @@ typedef struct {
      */
     FFTContext mdct;
     FFTContext mdct_small;
+    FFTContext mdct_ltp;
     DSPContext dsp;
+    FmtConvertContext fmt_conv;
     int random_state;
     /** @} */
 
@@ -282,7 +292,6 @@ typedef struct {
      * @{
      */
     float *output_data[MAX_CHANNELS];                 ///< Points to each element's 'ret' buffer (PCM output).
-    float add_bias;                                   ///< offset for dsp.float_to_int16
     float sf_scale;                                   ///< Pre-scale for correct IMDCT and dsp.float_to_int16.
     int sf_offset;                                    ///< offset into pow2sf_tab as appropriate for dsp.float_to_int16
     /** @} */
diff --git a/libavcodec/aac_ac3_parser.c b/libavcodec/aac_ac3_parser.c
index 8791161..58f30a4 100644
--- a/libavcodec/aac_ac3_parser.c
+++ b/libavcodec/aac_ac3_parser.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2003 Fabrice Bellard
  * Copyright (c) 2003 Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -94,6 +94,7 @@ get_next:
             avctx->channel_layout = s->channel_layout;
         }
         avctx->frame_size = s->samples;
+        avctx->audio_service_type = s->service_type;
     }
 
     avctx->bit_rate = s->bit_rate;
diff --git a/libavcodec/aac_ac3_parser.h b/libavcodec/aac_ac3_parser.h
index 75f6d4b..c4ed816 100644
--- a/libavcodec/aac_ac3_parser.h
+++ b/libavcodec/aac_ac3_parser.h
@@ -3,20 +3,20 @@
  * Copyright (c) 2003 Fabrice Bellard
  * Copyright (c) 2003 Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -49,6 +49,7 @@ typedef struct AACAC3ParseContext {
     int bit_rate;
     int samples;
     int64_t channel_layout;
+    int service_type;
 
     int remaining_size;
     uint64_t state;
diff --git a/libavcodec/aac_adtstoasc_bsf.c b/libavcodec/aac_adtstoasc_bsf.c
index 9d53a01..fbb86f8 100644
--- a/libavcodec/aac_adtstoasc_bsf.c
+++ b/libavcodec/aac_adtstoasc_bsf.c
@@ -2,25 +2,25 @@
  * MPEG-2/4 AAC ADTS to MPEG-4 Audio Specific Configuration bitstream filter
  * Copyright (c) 2009 Alex Converse <alex.converse at gmail.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "avcodec.h"
-#include "aac_parser.h"
+#include "aacadtsdec.h"
 #include "put_bits.h"
 #include "get_bits.h"
 #include "mpeg4audio.h"
@@ -107,7 +107,7 @@ static int aac_adtstoasc_filter(AVBitStreamFilterContext *bsfc,
     return 0;
 }
 
-AVBitStreamFilter aac_adtstoasc_bsf = {
+AVBitStreamFilter ff_aac_adtstoasc_bsf = {
     "aac_adtstoasc",
     sizeof(AACBSFContext),
     aac_adtstoasc_filter,
diff --git a/libavcodec/aac_parser.c b/libavcodec/aac_parser.c
index 30ce04d..1c5546e 100644
--- a/libavcodec/aac_parser.c
+++ b/libavcodec/aac_parser.c
@@ -3,72 +3,29 @@
  * Copyright (c) 2003 Fabrice Bellard
  * Copyright (c) 2003 Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "parser.h"
 #include "aac_ac3_parser.h"
-#include "aac_parser.h"
+#include "aacadtsdec.h"
 #include "get_bits.h"
 #include "mpeg4audio.h"
 
-int ff_aac_parse_header(GetBitContext *gbc, AACADTSHeaderInfo *hdr)
-{
-    int size, rdb, ch, sr;
-    int aot, crc_abs;
-
-    if(get_bits(gbc, 12) != 0xfff)
-        return AAC_AC3_PARSE_ERROR_SYNC;
-
-    skip_bits1(gbc);             /* id */
-    skip_bits(gbc, 2);           /* layer */
-    crc_abs = get_bits1(gbc);    /* protection_absent */
-    aot     = get_bits(gbc, 2);  /* profile_objecttype */
-    sr      = get_bits(gbc, 4);  /* sample_frequency_index */
-    if(!ff_mpeg4audio_sample_rates[sr])
-        return AAC_AC3_PARSE_ERROR_SAMPLE_RATE;
-    skip_bits1(gbc);             /* private_bit */
-    ch      = get_bits(gbc, 3);  /* channel_configuration */
-
-    skip_bits1(gbc);             /* original/copy */
-    skip_bits1(gbc);             /* home */
-
-    /* adts_variable_header */
-    skip_bits1(gbc);             /* copyright_identification_bit */
-    skip_bits1(gbc);             /* copyright_identification_start */
-    size    = get_bits(gbc, 13); /* aac_frame_length */
-    if(size < AAC_ADTS_HEADER_SIZE)
-        return AAC_AC3_PARSE_ERROR_FRAME_SIZE;
-
-    skip_bits(gbc, 11);          /* adts_buffer_fullness */
-    rdb = get_bits(gbc, 2);      /* number_of_raw_data_blocks_in_frame */
-
-    hdr->object_type    = aot + 1;
-    hdr->chan_config    = ch;
-    hdr->crc_absent     = crc_abs;
-    hdr->num_aac_frames = rdb + 1;
-    hdr->sampling_index = sr;
-    hdr->sample_rate    = ff_mpeg4audio_sample_rates[sr];
-    hdr->samples        = (rdb + 1) * 1024;
-    hdr->bit_rate       = size * 8 * hdr->sample_rate / hdr->samples;
-
-    return size;
-}
-
 static int aac_sync(uint64_t state, AACAC3ParseContext *hdr_info,
         int *need_next_header, int *new_frame_start)
 {
@@ -80,7 +37,7 @@ static int aac_sync(uint64_t state, AACAC3ParseContext *hdr_info,
         uint8_t  u8[8];
     } tmp;
 
-    tmp.u64 = be2me_64(state);
+    tmp.u64 = av_be2ne64(state);
     init_get_bits(&bits, tmp.u8+8-AAC_ADTS_HEADER_SIZE, AAC_ADTS_HEADER_SIZE * 8);
 
     if ((size = ff_aac_parse_header(&bits, &hdr)) < 0)
@@ -103,7 +60,7 @@ static av_cold int aac_parse_init(AVCodecParserContext *s1)
 }
 
 
-AVCodecParser aac_parser = {
+AVCodecParser ff_aac_parser = {
     { CODEC_ID_AAC },
     sizeof(AACAC3ParseContext),
     aac_parse_init,
diff --git a/libavcodec/aac_parser.h b/libavcodec/aac_parser.h
deleted file mode 100644
index 8dd575b..0000000
--- a/libavcodec/aac_parser.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * AAC parser prototypes
- * Copyright (c) 2003 Fabrice Bellard
- * Copyright (c) 2003 Michael Niedermayer
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-#ifndef AVCODEC_AAC_PARSER_H
-#define AVCODEC_AAC_PARSER_H
-
-#include <stdint.h>
-#include "aac_ac3_parser.h"
-#include "get_bits.h"
-
-#define AAC_ADTS_HEADER_SIZE 7
-
-typedef struct {
-    uint32_t sample_rate;
-    uint32_t samples;
-    uint32_t bit_rate;
-    uint8_t  crc_absent;
-    uint8_t  object_type;
-    uint8_t  sampling_index;
-    uint8_t  chan_config;
-    uint8_t  num_aac_frames;
-} AACADTSHeaderInfo;
-
-/**
- * Parses AAC frame header.
- * Parses the ADTS frame header to the end of the variable header, which is
- * the first 54 bits.
- * @param gbc[in] BitContext containing the first 54 bits of the frame.
- * @param hdr[out] Pointer to struct where header info is written.
- * @return Returns 0 on success, -1 if there is a sync word mismatch,
- * -2 if the version element is invalid, -3 if the sample rate
- * element is invalid, or -4 if the bit rate element is invalid.
- */
-int ff_aac_parse_header(GetBitContext *gbc, AACADTSHeaderInfo *hdr);
-
-#endif /* AVCODEC_AAC_PARSER_H */
diff --git a/libavcodec/aac_tablegen.c b/libavcodec/aac_tablegen.c
new file mode 100644
index 0000000..b2c6c95
--- /dev/null
+++ b/libavcodec/aac_tablegen.c
@@ -0,0 +1,37 @@
+/*
+ * Generate a header file for hardcoded AAC tables
+ *
+ * Copyright (c) 2010 Alex Converse <alex.converse at gmail.com>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <stdlib.h>
+#define CONFIG_HARDCODED_TABLES 0
+#include "aac_tablegen.h"
+#include "tableprint.h"
+
+int main(void)
+{
+    ff_aac_tableinit();
+
+    write_fileheader();
+
+    WRITE_ARRAY("const", float, ff_aac_pow2sf_tab);
+
+    return 0;
+}
diff --git a/libavcodec/aac_tablegen.h b/libavcodec/aac_tablegen.h
new file mode 100644
index 0000000..c7be492
--- /dev/null
+++ b/libavcodec/aac_tablegen.h
@@ -0,0 +1,42 @@
+/*
+ * Header file for hardcoded AAC tables
+ *
+ * Copyright (c) 2010 Alex Converse <alex.converse at gmail.com>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AAC_TABLEGEN_H
+#define AAC_TABLEGEN_H
+
+#include "aac_tablegen_decl.h"
+
+#if CONFIG_HARDCODED_TABLES
+#include "libavcodec/aac_tables.h"
+#else
+#include "libavutil/mathematics.h"
+float ff_aac_pow2sf_tab[428];
+
+void ff_aac_tableinit(void)
+{
+    int i;
+    for (i = 0; i < 428; i++)
+        ff_aac_pow2sf_tab[i] = pow(2, (i - 200) / 4.);
+}
+#endif /* CONFIG_HARDCODED_TABLES */
+
+#endif /* AAC_TABLEGEN_H */
diff --git a/libavcodec/aac_tablegen_decl.h b/libavcodec/aac_tablegen_decl.h
new file mode 100644
index 0000000..ce4ecb5
--- /dev/null
+++ b/libavcodec/aac_tablegen_decl.h
@@ -0,0 +1,34 @@
+/*
+ * Header file for hardcoded AAC tables
+ *
+ * Copyright (c) 2010 Alex Converse <alex.converse at gmail.com>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AAC_TABLEGEN_DECL_H
+#define AAC_TABLEGEN_DECL_H
+
+#if CONFIG_HARDCODED_TABLES
+#define ff_aac_tableinit()
+extern const float ff_aac_pow2sf_tab[428];
+#else
+void ff_aac_tableinit(void);
+extern       float ff_aac_pow2sf_tab[428];
+#endif /* CONFIG_HARDCODED_TABLES */
+
+#endif /* AAC_TABLEGEN_DECL_H */
diff --git a/libavcodec/aacadtsdec.c b/libavcodec/aacadtsdec.c
new file mode 100644
index 0000000..a9ff8ef
--- /dev/null
+++ b/libavcodec/aacadtsdec.c
@@ -0,0 +1,70 @@
+/*
+ * Audio and Video frame extraction
+ * Copyright (c) 2003 Fabrice Bellard
+ * Copyright (c) 2003 Michael Niedermayer
+ * Copyright (c) 2009 Alex Converse
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "aac_ac3_parser.h"
+#include "aacadtsdec.h"
+#include "get_bits.h"
+#include "mpeg4audio.h"
+
+int ff_aac_parse_header(GetBitContext *gbc, AACADTSHeaderInfo *hdr)
+{
+    int size, rdb, ch, sr;
+    int aot, crc_abs;
+
+    if(get_bits(gbc, 12) != 0xfff)
+        return AAC_AC3_PARSE_ERROR_SYNC;
+
+    skip_bits1(gbc);             /* id */
+    skip_bits(gbc, 2);           /* layer */
+    crc_abs = get_bits1(gbc);    /* protection_absent */
+    aot     = get_bits(gbc, 2);  /* profile_objecttype */
+    sr      = get_bits(gbc, 4);  /* sample_frequency_index */
+    if(!ff_mpeg4audio_sample_rates[sr])
+        return AAC_AC3_PARSE_ERROR_SAMPLE_RATE;
+    skip_bits1(gbc);             /* private_bit */
+    ch      = get_bits(gbc, 3);  /* channel_configuration */
+
+    skip_bits1(gbc);             /* original/copy */
+    skip_bits1(gbc);             /* home */
+
+    /* adts_variable_header */
+    skip_bits1(gbc);             /* copyright_identification_bit */
+    skip_bits1(gbc);             /* copyright_identification_start */
+    size    = get_bits(gbc, 13); /* aac_frame_length */
+    if(size < AAC_ADTS_HEADER_SIZE)
+        return AAC_AC3_PARSE_ERROR_FRAME_SIZE;
+
+    skip_bits(gbc, 11);          /* adts_buffer_fullness */
+    rdb = get_bits(gbc, 2);      /* number_of_raw_data_blocks_in_frame */
+
+    hdr->object_type    = aot + 1;
+    hdr->chan_config    = ch;
+    hdr->crc_absent     = crc_abs;
+    hdr->num_aac_frames = rdb + 1;
+    hdr->sampling_index = sr;
+    hdr->sample_rate    = ff_mpeg4audio_sample_rates[sr];
+    hdr->samples        = (rdb + 1) * 1024;
+    hdr->bit_rate       = size * 8 * hdr->sample_rate / hdr->samples;
+
+    return size;
+}
diff --git a/libavcodec/aacadtsdec.h b/libavcodec/aacadtsdec.h
new file mode 100644
index 0000000..2fa1b4b
--- /dev/null
+++ b/libavcodec/aacadtsdec.h
@@ -0,0 +1,54 @@
+/*
+ * AAC ADTS header decoding prototypes and structures
+ * Copyright (c) 2003 Fabrice Bellard
+ * Copyright (c) 2003 Michael Niedermayer
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_AACADTSDEC_H
+#define AVCODEC_AACADTSDEC_H
+
+#include <stdint.h>
+#include "get_bits.h"
+
+#define AAC_ADTS_HEADER_SIZE 7
+
+typedef struct {
+    uint32_t sample_rate;
+    uint32_t samples;
+    uint32_t bit_rate;
+    uint8_t  crc_absent;
+    uint8_t  object_type;
+    uint8_t  sampling_index;
+    uint8_t  chan_config;
+    uint8_t  num_aac_frames;
+} AACADTSHeaderInfo;
+
+/**
+ * Parse AAC frame header.
+ * Parse the ADTS frame header to the end of the variable header, which is
+ * the first 54 bits.
+ * @param[in]  gbc BitContext containing the first 54 bits of the frame.
+ * @param[out] hdr Pointer to struct where header info is written.
+ * @return Returns 0 on success, -1 if there is a sync word mismatch,
+ * -2 if the version element is invalid, -3 if the sample rate
+ * element is invalid, or -4 if the bit rate element is invalid.
+ */
+int ff_aac_parse_header(GetBitContext *gbc, AACADTSHeaderInfo *hdr);
+
+#endif /* AVCODEC_AACADTSDEC_H */
diff --git a/libavcodec/aaccoder.c b/libavcodec/aaccoder.c
index 0957469..e7f8cb0 100644
--- a/libavcodec/aaccoder.c
+++ b/libavcodec/aaccoder.c
@@ -2,20 +2,20 @@
  * AAC coefficients encoder
  * Copyright (C) 2008-2009 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -30,6 +30,7 @@
  * add sane pulse detection
  ***********************************/
 
+#include <float.h>
 #include "avcodec.h"
 #include "put_bits.h"
 #include "aac.h"
@@ -65,18 +66,16 @@ static av_always_inline int quant(float coef, const float Q)
     return sqrtf(a * sqrtf(a)) + 0.4054;
 }
 
-static void quantize_bands(int (*out)[2], const float *in, const float *scaled,
+static void quantize_bands(int *out, const float *in, const float *scaled,
                            int size, float Q34, int is_signed, int maxval)
 {
     int i;
     double qc;
     for (i = 0; i < size; i++) {
         qc = scaled[i] * Q34;
-        out[i][0] = (int)FFMIN(qc,          (double)maxval);
-        out[i][1] = (int)FFMIN(qc + 0.4054, (double)maxval);
+        out[i] = (int)FFMIN(qc + 0.4054, (double)maxval);
         if (is_signed && in[i] < 0.0f) {
-            out[i][0] = -out[i][0];
-            out[i][1] = -out[i][1];
+            out[i] = -out[i];
         }
     }
 }
@@ -100,147 +99,157 @@ static const uint8_t aac_cb_maxval[12] = {0, 1, 1, 2, 2, 4, 4, 7, 7, 12, 12, 16}
  *
  * @return quantization distortion
  */
-static float quantize_and_encode_band_cost(struct AACEncContext *s,
+static av_always_inline float quantize_and_encode_band_cost_template(
+                                struct AACEncContext *s,
                                 PutBitContext *pb, const float *in,
                                 const float *scaled, int size, int scale_idx,
                                 int cb, const float lambda, const float uplim,
-                                int *bits)
+                                int *bits, int BT_ZERO, int BT_UNSIGNED,
+                                int BT_PAIR, int BT_ESC)
 {
     const float IQ = ff_aac_pow2sf_tab[200 + scale_idx - SCALE_ONE_POS + SCALE_DIV_512];
     const float  Q = ff_aac_pow2sf_tab[200 - scale_idx + SCALE_ONE_POS - SCALE_DIV_512];
     const float CLIPPED_ESCAPE = 165140.0f*IQ;
-    int i, j, k;
+    int i, j;
     float cost = 0;
-    const int dim = cb < FIRST_PAIR_BT ? 4 : 2;
+    const int dim = BT_PAIR ? 2 : 4;
     int resbits = 0;
-#ifndef USE_REALLY_FULL_SEARCH
     const float  Q34 = sqrtf(Q * sqrtf(Q));
     const int range  = aac_cb_range[cb];
     const int maxval = aac_cb_maxval[cb];
-    int offs[4];
-#endif /* USE_REALLY_FULL_SEARCH */
+    int off;
 
-    if (!cb) {
+    if (BT_ZERO) {
         for (i = 0; i < size; i++)
             cost += in[i]*in[i];
         if (bits)
             *bits = 0;
         return cost * lambda;
     }
-#ifndef USE_REALLY_FULL_SEARCH
-    offs[0] = 1;
-    for (i = 1; i < dim; i++)
-        offs[i] = offs[i-1]*range;
     if (!scaled) {
         abs_pow34_v(s->scoefs, in, size);
         scaled = s->scoefs;
     }
-    quantize_bands(s->qcoefs, in, scaled, size, Q34, !IS_CODEBOOK_UNSIGNED(cb), maxval);
-#endif /* USE_REALLY_FULL_SEARCH */
+    quantize_bands(s->qcoefs, in, scaled, size, Q34, !BT_UNSIGNED, maxval);
+    if (BT_UNSIGNED) {
+        off = 0;
+    } else {
+        off = maxval;
+    }
     for (i = 0; i < size; i += dim) {
-        float mincost;
-        int minidx  = 0;
-        int minbits = 0;
         const float *vec;
-#ifndef USE_REALLY_FULL_SEARCH
-        int (*quants)[2] = &s->qcoefs[i];
-        mincost = 0.0f;
-        for (j = 0; j < dim; j++)
-            mincost += in[i+j]*in[i+j];
-        minidx = IS_CODEBOOK_UNSIGNED(cb) ? 0 : 40;
-        minbits = ff_aac_spectral_bits[cb-1][minidx];
-        mincost = mincost * lambda + minbits;
-        for (j = 0; j < (1<<dim); j++) {
-            float rd = 0.0f;
-            int curbits;
-            int curidx = IS_CODEBOOK_UNSIGNED(cb) ? 0 : 40;
-            int same   = 0;
-            for (k = 0; k < dim; k++) {
-                if ((j & (1 << k)) && quants[k][0] == quants[k][1]) {
-                    same = 1;
-                    break;
-                }
-            }
-            if (same)
-                continue;
-            for (k = 0; k < dim; k++)
-                curidx += quants[k][!!(j & (1 << k))] * offs[dim - 1 - k];
-            curbits =  ff_aac_spectral_bits[cb-1][curidx];
-            vec     = &ff_aac_codebook_vectors[cb-1][curidx*dim];
-#else
-        mincost = INFINITY;
-        vec = ff_aac_codebook_vectors[cb-1];
-        for (j = 0; j < ff_aac_spectral_sizes[cb-1]; j++, vec += dim) {
-            float rd = 0.0f;
-            int curbits = ff_aac_spectral_bits[cb-1][j];
-            int curidx = j;
-#endif /* USE_REALLY_FULL_SEARCH */
-            if (IS_CODEBOOK_UNSIGNED(cb)) {
-                for (k = 0; k < dim; k++) {
-                    float t = fabsf(in[i+k]);
-                    float di;
-                    if (vec[k] == 64.0f) { //FIXME: slow
-                        //do not code with escape sequence small values
-                        if (t < 39.0f*IQ) {
-                            rd = INFINITY;
-                            break;
-                        }
-                        if (t >= CLIPPED_ESCAPE) {
-                            di = t - CLIPPED_ESCAPE;
-                            curbits += 21;
-                        } else {
-                            int c = av_clip(quant(t, Q), 0, 8191);
-                            di = t - c*cbrtf(c)*IQ;
-                            curbits += av_log2(c)*2 - 4 + 1;
-                        }
+        int *quants = s->qcoefs + i;
+        int curidx = 0;
+        int curbits;
+        float rd = 0.0f;
+        for (j = 0; j < dim; j++) {
+            curidx *= range;
+            curidx += quants[j] + off;
+        }
+        curbits =  ff_aac_spectral_bits[cb-1][curidx];
+        vec     = &ff_aac_codebook_vectors[cb-1][curidx*dim];
+        if (BT_UNSIGNED) {
+            for (j = 0; j < dim; j++) {
+                float t = fabsf(in[i+j]);
+                float di;
+                if (BT_ESC && vec[j] == 64.0f) { //FIXME: slow
+                    if (t >= CLIPPED_ESCAPE) {
+                        di = t - CLIPPED_ESCAPE;
+                        curbits += 21;
                     } else {
-                        di = t - vec[k]*IQ;
+                        int c = av_clip(quant(t, Q), 0, 8191);
+                        di = t - c*cbrtf(c)*IQ;
+                        curbits += av_log2(c)*2 - 4 + 1;
                     }
-                    if (vec[k] != 0.0f)
-                        curbits++;
-                    rd += di*di;
-                }
-            } else {
-                for (k = 0; k < dim; k++) {
-                    float di = in[i+k] - vec[k]*IQ;
-                    rd += di*di;
+                } else {
+                    di = t - vec[j]*IQ;
                 }
+                if (vec[j] != 0.0f)
+                    curbits++;
+                rd += di*di;
             }
-            rd = rd * lambda + curbits;
-            if (rd < mincost) {
-                mincost = rd;
-                minidx  = curidx;
-                minbits = curbits;
+        } else {
+            for (j = 0; j < dim; j++) {
+                float di = in[i+j] - vec[j]*IQ;
+                rd += di*di;
             }
         }
-        cost    += mincost;
-        resbits += minbits;
+        cost    += rd * lambda + curbits;
+        resbits += curbits;
         if (cost >= uplim)
             return uplim;
         if (pb) {
-        put_bits(pb, ff_aac_spectral_bits[cb-1][minidx], ff_aac_spectral_codes[cb-1][minidx]);
-        if (IS_CODEBOOK_UNSIGNED(cb))
-            for (j = 0; j < dim; j++)
-                if (ff_aac_codebook_vectors[cb-1][minidx*dim+j] != 0.0f)
-                    put_bits(pb, 1, in[i+j] < 0.0f);
-        if (cb == ESC_BT) {
-            for (j = 0; j < 2; j++) {
-                if (ff_aac_codebook_vectors[cb-1][minidx*2+j] == 64.0f) {
-                    int coef = av_clip(quant(fabsf(in[i+j]), Q), 0, 8191);
-                    int len = av_log2(coef);
-
-                    put_bits(pb, len - 4 + 1, (1 << (len - 4 + 1)) - 2);
-                    put_bits(pb, len, coef & ((1 << len) - 1));
+            put_bits(pb, ff_aac_spectral_bits[cb-1][curidx], ff_aac_spectral_codes[cb-1][curidx]);
+            if (BT_UNSIGNED)
+                for (j = 0; j < dim; j++)
+                    if (ff_aac_codebook_vectors[cb-1][curidx*dim+j] != 0.0f)
+                        put_bits(pb, 1, in[i+j] < 0.0f);
+            if (BT_ESC) {
+                for (j = 0; j < 2; j++) {
+                    if (ff_aac_codebook_vectors[cb-1][curidx*2+j] == 64.0f) {
+                        int coef = av_clip(quant(fabsf(in[i+j]), Q), 0, 8191);
+                        int len = av_log2(coef);
+
+                        put_bits(pb, len - 4 + 1, (1 << (len - 4 + 1)) - 2);
+                        put_bits(pb, len, coef & ((1 << len) - 1));
+                    }
                 }
             }
         }
-        }
     }
 
     if (bits)
         *bits = resbits;
     return cost;
 }
+
+#define QUANTIZE_AND_ENCODE_BAND_COST_FUNC(NAME, BT_ZERO, BT_UNSIGNED, BT_PAIR, BT_ESC) \
+static float quantize_and_encode_band_cost_ ## NAME(                                        \
+                                struct AACEncContext *s,                                \
+                                PutBitContext *pb, const float *in,                     \
+                                const float *scaled, int size, int scale_idx,           \
+                                int cb, const float lambda, const float uplim,          \
+                                int *bits) {                                            \
+    return quantize_and_encode_band_cost_template(                                      \
+                                s, pb, in, scaled, size, scale_idx,                     \
+                                BT_ESC ? ESC_BT : cb, lambda, uplim, bits,              \
+                                BT_ZERO, BT_UNSIGNED, BT_PAIR, BT_ESC);                 \
+}
+
+QUANTIZE_AND_ENCODE_BAND_COST_FUNC(ZERO,  1, 0, 0, 0)
+QUANTIZE_AND_ENCODE_BAND_COST_FUNC(SQUAD, 0, 0, 0, 0)
+QUANTIZE_AND_ENCODE_BAND_COST_FUNC(UQUAD, 0, 1, 0, 0)
+QUANTIZE_AND_ENCODE_BAND_COST_FUNC(SPAIR, 0, 0, 1, 0)
+QUANTIZE_AND_ENCODE_BAND_COST_FUNC(UPAIR, 0, 1, 1, 0)
+QUANTIZE_AND_ENCODE_BAND_COST_FUNC(ESC,   0, 1, 1, 1)
+
+static float (*const quantize_and_encode_band_cost_arr[])(
+                                struct AACEncContext *s,
+                                PutBitContext *pb, const float *in,
+                                const float *scaled, int size, int scale_idx,
+                                int cb, const float lambda, const float uplim,
+                                int *bits) = {
+    quantize_and_encode_band_cost_ZERO,
+    quantize_and_encode_band_cost_SQUAD,
+    quantize_and_encode_band_cost_SQUAD,
+    quantize_and_encode_band_cost_UQUAD,
+    quantize_and_encode_band_cost_UQUAD,
+    quantize_and_encode_band_cost_SPAIR,
+    quantize_and_encode_band_cost_SPAIR,
+    quantize_and_encode_band_cost_UPAIR,
+    quantize_and_encode_band_cost_UPAIR,
+    quantize_and_encode_band_cost_UPAIR,
+    quantize_and_encode_band_cost_UPAIR,
+    quantize_and_encode_band_cost_ESC,
+};
+
+#define quantize_and_encode_band_cost(                                  \
+                                s, pb, in, scaled, size, scale_idx, cb, \
+                                lambda, uplim, bits)                    \
+    quantize_and_encode_band_cost_arr[cb](                              \
+                                s, pb, in, scaled, size, scale_idx, cb, \
+                                lambda, uplim, bits)
+
 static float quantize_band_cost(struct AACEncContext *s, const float *in,
                                 const float *scaled, int size, int scale_idx,
                                 int cb, const float lambda, const float uplim,
@@ -258,6 +267,32 @@ static void quantize_and_encode_band(struct AACEncContext *s, PutBitContext *pb,
                                   INFINITY, NULL);
 }
 
+static float find_max_val(int group_len, int swb_size, const float *scaled) {
+    float maxval = 0.0f;
+    int w2, i;
+    for (w2 = 0; w2 < group_len; w2++) {
+        for (i = 0; i < swb_size; i++) {
+            maxval = FFMAX(maxval, scaled[w2*128+i]);
+        }
+    }
+    return maxval;
+}
+
+static int find_min_book(float maxval, int sf) {
+    float Q = ff_aac_pow2sf_tab[200 - sf + SCALE_ONE_POS - SCALE_DIV_512];
+    float Q34 = sqrtf(Q * sqrtf(Q));
+    int qmaxval, cb;
+    qmaxval = maxval * Q34 + 0.4054f;
+    if      (qmaxval ==  0) cb = 0;
+    else if (qmaxval ==  1) cb = 1;
+    else if (qmaxval ==  2) cb = 3;
+    else if (qmaxval <=  4) cb = 5;
+    else if (qmaxval <=  7) cb = 7;
+    else if (qmaxval <= 12) cb = 9;
+    else                    cb = 11;
+    return cb;
+}
+
 /**
  * structure used in optimal codebook search
  */
@@ -372,15 +407,131 @@ static void encode_window_bands_info(AACEncContext *s, SingleChannelElement *sce
     }
 }
 
+static void codebook_trellis_rate(AACEncContext *s, SingleChannelElement *sce,
+                                  int win, int group_len, const float lambda)
+{
+    BandCodingPath path[120][12];
+    int w, swb, cb, start, start2, size;
+    int i, j;
+    const int max_sfb  = sce->ics.max_sfb;
+    const int run_bits = sce->ics.num_windows == 1 ? 5 : 3;
+    const int run_esc  = (1 << run_bits) - 1;
+    int idx, ppos, count;
+    int stackrun[120], stackcb[120], stack_len;
+    float next_minrd = INFINITY;
+    int next_mincb = 0;
+
+    abs_pow34_v(s->scoefs, sce->coeffs, 1024);
+    start = win*128;
+    for (cb = 0; cb < 12; cb++) {
+        path[0][cb].cost     = run_bits+4;
+        path[0][cb].prev_idx = -1;
+        path[0][cb].run      = 0;
+    }
+    for (swb = 0; swb < max_sfb; swb++) {
+        start2 = start;
+        size = sce->ics.swb_sizes[swb];
+        if (sce->zeroes[win*16 + swb]) {
+            for (cb = 0; cb < 12; cb++) {
+                path[swb+1][cb].prev_idx = cb;
+                path[swb+1][cb].cost     = path[swb][cb].cost;
+                path[swb+1][cb].run      = path[swb][cb].run + 1;
+            }
+        } else {
+            float minrd = next_minrd;
+            int mincb = next_mincb;
+            int startcb = sce->band_type[win*16+swb];
+            next_minrd = INFINITY;
+            next_mincb = 0;
+            for (cb = 0; cb < startcb; cb++) {
+                path[swb+1][cb].cost = 61450;
+                path[swb+1][cb].prev_idx = -1;
+                path[swb+1][cb].run = 0;
+            }
+            for (cb = startcb; cb < 12; cb++) {
+                float cost_stay_here, cost_get_here;
+                float rd = 0.0f;
+                for (w = 0; w < group_len; w++) {
+                    rd += quantize_band_cost(s, sce->coeffs + start + w*128,
+                                             s->scoefs + start + w*128, size,
+                                             sce->sf_idx[(win+w)*16+swb], cb,
+                                             0, INFINITY, NULL);
+                }
+                cost_stay_here = path[swb][cb].cost + rd;
+                cost_get_here  = minrd              + rd + run_bits + 4;
+                if (   run_value_bits[sce->ics.num_windows == 8][path[swb][cb].run]
+                    != run_value_bits[sce->ics.num_windows == 8][path[swb][cb].run+1])
+                    cost_stay_here += run_bits;
+                if (cost_get_here < cost_stay_here) {
+                    path[swb+1][cb].prev_idx = mincb;
+                    path[swb+1][cb].cost     = cost_get_here;
+                    path[swb+1][cb].run      = 1;
+                } else {
+                    path[swb+1][cb].prev_idx = cb;
+                    path[swb+1][cb].cost     = cost_stay_here;
+                    path[swb+1][cb].run      = path[swb][cb].run + 1;
+                }
+                if (path[swb+1][cb].cost < next_minrd) {
+                    next_minrd = path[swb+1][cb].cost;
+                    next_mincb = cb;
+                }
+            }
+        }
+        start += sce->ics.swb_sizes[swb];
+    }
+
+    //convert resulting path from backward-linked list
+    stack_len = 0;
+    idx       = 0;
+    for (cb = 1; cb < 12; cb++)
+        if (path[max_sfb][cb].cost < path[max_sfb][idx].cost)
+            idx = cb;
+    ppos = max_sfb;
+    while (ppos > 0) {
+        assert(idx >= 0);
+        cb = idx;
+        stackrun[stack_len] = path[ppos][cb].run;
+        stackcb [stack_len] = cb;
+        idx = path[ppos-path[ppos][cb].run+1][cb].prev_idx;
+        ppos -= path[ppos][cb].run;
+        stack_len++;
+    }
+    //perform actual band info encoding
+    start = 0;
+    for (i = stack_len - 1; i >= 0; i--) {
+        put_bits(&s->pb, 4, stackcb[i]);
+        count = stackrun[i];
+        memset(sce->zeroes + win*16 + start, !stackcb[i], count);
+        //XXX: memset when band_type is also uint8_t
+        for (j = 0; j < count; j++) {
+            sce->band_type[win*16 + start] =  stackcb[i];
+            start++;
+        }
+        while (count >= run_esc) {
+            put_bits(&s->pb, run_bits, run_esc);
+            count -= run_esc;
+        }
+        put_bits(&s->pb, run_bits, count);
+    }
+}
+
+/** Return the minimum scalefactor where the quantized coef does not clip. */
+static av_always_inline uint8_t coef2minsf(float coef) {
+    return av_clip_uint8(log2f(coef)*4 - 69 + SCALE_ONE_POS - SCALE_DIV_512);
+}
+
+/** Return the maximum scalefactor where the quantized coef is not zero. */
+static av_always_inline uint8_t coef2maxsf(float coef) {
+    return av_clip_uint8(log2f(coef)*4 +  6 + SCALE_ONE_POS - SCALE_DIV_512);
+}
+
 typedef struct TrellisPath {
     float cost;
     int prev;
-    int min_val;
-    int max_val;
 } TrellisPath;
 
 #define TRELLIS_STAGES 121
-#define TRELLIS_STATES 256
+#define TRELLIS_STATES (SCALE_MAX_DIFF+1)
 
 static void search_for_quantizers_anmr(AVCodecContext *avctx, AACEncContext *s,
                                        SingleChannelElement *sce,
@@ -393,19 +544,56 @@ static void search_for_quantizers_anmr(AVCodecContext *avctx, AACEncContext *s,
     int bandaddr[TRELLIS_STAGES];
     int minq;
     float mincost;
+    float q0f = FLT_MAX, q1f = 0.0f, qnrgf = 0.0f;
+    int q0, q1, qcnt = 0;
+
+    for (i = 0; i < 1024; i++) {
+        float t = fabsf(sce->coeffs[i]);
+        if (t > 0.0f) {
+            q0f = FFMIN(q0f, t);
+            q1f = FFMAX(q1f, t);
+            qnrgf += t*t;
+            qcnt++;
+        }
+    }
+
+    if (!qcnt) {
+        memset(sce->sf_idx, 0, sizeof(sce->sf_idx));
+        memset(sce->zeroes, 1, sizeof(sce->zeroes));
+        return;
+    }
+
+    //minimum scalefactor index is when minimum nonzero coefficient after quantizing is not clipped
+    q0 = coef2minsf(q0f);
+    //maximum scalefactor index is when maximum coefficient after quantizing is still not zero
+    q1 = coef2maxsf(q1f);
+    //av_log(NULL, AV_LOG_ERROR, "q0 %d, q1 %d\n", q0, q1);
+    if (q1 - q0 > 60) {
+        int q0low  = q0;
+        int q1high = q1;
+        //minimum scalefactor index is when maximum nonzero coefficient after quantizing is not clipped
+        int qnrg = av_clip_uint8(log2f(sqrtf(qnrgf/qcnt))*4 - 31 + SCALE_ONE_POS - SCALE_DIV_512);
+        q1 = qnrg + 30;
+        q0 = qnrg - 30;
+        //av_log(NULL, AV_LOG_ERROR, "q0 %d, q1 %d\n", q0, q1);
+        if (q0 < q0low) {
+            q1 += q0low - q0;
+            q0  = q0low;
+        } else if (q1 > q1high) {
+            q0 -= q1 - q1high;
+            q1  = q1high;
+        }
+    }
+    //av_log(NULL, AV_LOG_ERROR, "q0 %d, q1 %d\n", q0, q1);
 
     for (i = 0; i < TRELLIS_STATES; i++) {
         paths[0][i].cost    = 0.0f;
         paths[0][i].prev    = -1;
-        paths[0][i].min_val = i;
-        paths[0][i].max_val = i;
     }
     for (j = 1; j < TRELLIS_STAGES; j++) {
         for (i = 0; i < TRELLIS_STATES; i++) {
             paths[j][i].cost    = INFINITY;
             paths[j][i].prev    = -2;
-            paths[j][i].min_val = INT_MAX;
-            paths[j][i].max_val = 0;
         }
     }
     idx = 1;
@@ -438,66 +626,38 @@ static void search_for_quantizers_anmr(AVCodecContext *avctx, AACEncContext *s,
             if (nz) {
                 int minscale, maxscale;
                 float minrd = INFINITY;
+                float maxval;
                 //minimum scalefactor index is when minimum nonzero coefficient after quantizing is not clipped
-                minscale = av_clip_uint8(log2(qmin)*4 - 69 + SCALE_ONE_POS - SCALE_DIV_512);
+                minscale = coef2minsf(qmin);
                 //maximum scalefactor index is when maximum coefficient after quantizing is still not zero
-                maxscale = av_clip_uint8(log2(qmax)*4 +  6 + SCALE_ONE_POS - SCALE_DIV_512);
+                maxscale = coef2maxsf(qmax);
+                minscale = av_clip(minscale - q0, 0, TRELLIS_STATES - 1);
+                maxscale = av_clip(maxscale - q0, 0, TRELLIS_STATES);
+                maxval = find_max_val(sce->ics.group_len[w], sce->ics.swb_sizes[g], s->scoefs+start);
                 for (q = minscale; q < maxscale; q++) {
-                    float dists[12], dist;
-                    memset(dists, 0, sizeof(dists));
+                    float dist = 0;
+                    int cb = find_min_book(maxval, sce->sf_idx[w*16+g]);
                     for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
                         FFPsyBand *band = &s->psy.psy_bands[s->cur_channel*PSY_MAX_BANDS+(w+w2)*16+g];
-                        int cb;
-                        for (cb = 0; cb <= ESC_BT; cb++)
-                            dists[cb] += quantize_band_cost(s, coefs + w2*128, s->scoefs + start + w2*128, sce->ics.swb_sizes[g],
-                                                            q, cb, lambda / band->threshold, INFINITY, NULL);
+                        dist += quantize_band_cost(s, coefs + w2*128, s->scoefs + start + w2*128, sce->ics.swb_sizes[g],
+                                                   q + q0, cb, lambda / band->threshold, INFINITY, NULL);
                     }
-                    dist = dists[0];
-                    for (i = 1; i <= ESC_BT; i++)
-                        dist = FFMIN(dist, dists[i]);
                     minrd = FFMIN(minrd, dist);
 
-                    for (i = FFMAX(q - SCALE_MAX_DIFF, 0); i < FFMIN(q + SCALE_MAX_DIFF, TRELLIS_STATES); i++) {
+                    for (i = 0; i < q1 - q0; i++) {
                         float cost;
-                        int minv, maxv;
-                        if (isinf(paths[idx - 1][i].cost))
-                            continue;
                         cost = paths[idx - 1][i].cost + dist
                                + ff_aac_scalefactor_bits[q - i + SCALE_DIFF_ZERO];
-                        minv = FFMIN(paths[idx - 1][i].min_val, q);
-                        maxv = FFMAX(paths[idx - 1][i].max_val, q);
-                        if (cost < paths[idx][q].cost && maxv-minv < SCALE_MAX_DIFF) {
+                        if (cost < paths[idx][q].cost) {
                             paths[idx][q].cost    = cost;
                             paths[idx][q].prev    = i;
-                            paths[idx][q].min_val = minv;
-                            paths[idx][q].max_val = maxv;
                         }
                     }
                 }
             } else {
-                for (q = 0; q < TRELLIS_STATES; q++) {
-                    if (!isinf(paths[idx - 1][q].cost)) {
-                        paths[idx][q].cost = paths[idx - 1][q].cost + 1;
-                        paths[idx][q].prev = q;
-                        paths[idx][q].min_val = FFMIN(paths[idx - 1][q].min_val, q);
-                        paths[idx][q].max_val = FFMAX(paths[idx - 1][q].max_val, q);
-                        continue;
-                    }
-                    for (i = FFMAX(q - SCALE_MAX_DIFF, 0); i < FFMIN(q + SCALE_MAX_DIFF, TRELLIS_STATES); i++) {
-                        float cost;
-                        int minv, maxv;
-                        if (isinf(paths[idx - 1][i].cost))
-                            continue;
-                        cost = paths[idx - 1][i].cost + ff_aac_scalefactor_bits[q - i + SCALE_DIFF_ZERO];
-                        minv = FFMIN(paths[idx - 1][i].min_val, q);
-                        maxv = FFMAX(paths[idx - 1][i].max_val, q);
-                        if (cost < paths[idx][q].cost && maxv-minv < SCALE_MAX_DIFF) {
-                            paths[idx][q].cost    = cost;
-                            paths[idx][q].prev    = i;
-                            paths[idx][q].min_val = minv;
-                            paths[idx][q].max_val = maxv;
-                        }
-                    }
+                for (q = 0; q < q1 - q0; q++) {
+                    paths[idx][q].cost = paths[idx - 1][q].cost + 1;
+                    paths[idx][q].prev = q;
                 }
             }
             sce->zeroes[w*16+g] = !nz;
@@ -515,7 +675,7 @@ static void search_for_quantizers_anmr(AVCodecContext *avctx, AACEncContext *s,
         }
     }
     while (idx) {
-        sce->sf_idx[bandaddr[idx]] = minq;
+        sce->sf_idx[bandaddr[idx]] = minq + q0;
         minq = paths[idx][minq].prev;
         idx--;
     }
@@ -537,6 +697,7 @@ static void search_for_quantizers_twoloop(AVCodecContext *avctx,
     int start = 0, i, w, w2, g;
     int destbits = avctx->bit_rate * 1024.0 / avctx->sample_rate / avctx->channels;
     float dists[128], uplims[128];
+    float maxvals[128];
     int fflag, minscaler;
     int its  = 0;
     int allz = 0;
@@ -562,7 +723,7 @@ static void search_for_quantizers_twoloop(AVCodecContext *avctx,
             sce->zeroes[w*16+g] = !nz;
             if (nz)
                 minthr = FFMIN(minthr, uplim);
-            allz = FFMAX(allz, nz);
+            allz |= nz;
         }
     }
     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
@@ -571,13 +732,23 @@ static void search_for_quantizers_twoloop(AVCodecContext *avctx,
                 sce->sf_idx[w*16+g] = SCALE_ONE_POS;
                 continue;
             }
-            sce->sf_idx[w*16+g] = SCALE_ONE_POS + FFMIN(log2(uplims[w*16+g]/minthr)*4,59);
+            sce->sf_idx[w*16+g] = SCALE_ONE_POS + FFMIN(log2f(uplims[w*16+g]/minthr)*4,59);
         }
     }
 
     if (!allz)
         return;
     abs_pow34_v(s->scoefs, sce->coeffs, 1024);
+
+    for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
+        start = w*128;
+        for (g = 0;  g < sce->ics.num_swb; g++) {
+            const float *scaled = s->scoefs + start;
+            maxvals[w*16+g] = find_max_val(sce->ics.group_len[w], sce->ics.swb_sizes[g], scaled);
+            start += sce->ics.swb_sizes[g];
+        }
+    }
+
     //perform two-loop search
     //outer loop - improve quality
     do {
@@ -596,36 +767,27 @@ static void search_for_quantizers_twoloop(AVCodecContext *avctx,
                     const float *scaled = s->scoefs + start;
                     int bits = 0;
                     int cb;
-                    float mindist = INFINITY;
-                    int minbits = 0;
+                    float dist = 0.0f;
 
                     if (sce->zeroes[w*16+g] || sce->sf_idx[w*16+g] >= 218) {
                         start += sce->ics.swb_sizes[g];
                         continue;
                     }
                     minscaler = FFMIN(minscaler, sce->sf_idx[w*16+g]);
-                    for (cb = 0; cb <= ESC_BT; cb++) {
-                        float dist = 0.0f;
-                        int bb = 0;
-                        for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
-                            int b;
-                            dist += quantize_band_cost(s, coefs + w2*128,
-                                                       scaled + w2*128,
-                                                       sce->ics.swb_sizes[g],
-                                                       sce->sf_idx[w*16+g],
-                                                       cb,
-                                                       lambda,
-                                                       INFINITY,
-                                                       &b);
-                            bb += b;
-                        }
-                        if (dist < mindist) {
-                            mindist = dist;
-                            minbits = bb;
-                        }
+                    cb = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]);
+                    for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
+                        int b;
+                        dist += quantize_band_cost(s, coefs + w2*128,
+                                                   scaled + w2*128,
+                                                   sce->ics.swb_sizes[g],
+                                                   sce->sf_idx[w*16+g],
+                                                   cb,
+                                                   1.0f,
+                                                   INFINITY,
+                                                   &b);
+                        bits += b;
                     }
-                    dists[w*16+g] = (mindist - minbits) / lambda;
-                    bits = minbits;
+                    dists[w*16+g] = dist - bits;
                     if (prev != -1) {
                         bits += ff_aac_scalefactor_bits[sce->sf_idx[w*16+g] - prev + SCALE_DIFF_ZERO];
                     }
@@ -644,24 +806,26 @@ static void search_for_quantizers_twoloop(AVCodecContext *avctx,
                         sce->sf_idx[i] -= qstep;
             }
             qstep >>= 1;
-            if (!qstep && tbits > destbits*1.02)
+            if (!qstep && tbits > destbits*1.02 && sce->sf_idx[0] < 217)
                 qstep = 1;
-            if (sce->sf_idx[0] >= 217)
-                break;
         } while (qstep);
 
         fflag = 0;
         minscaler = av_clip(minscaler, 60, 255 - SCALE_MAX_DIFF);
         for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
-            start = w*128;
             for (g = 0; g < sce->ics.num_swb; g++) {
                 int prevsc = sce->sf_idx[w*16+g];
-                if (dists[w*16+g] > uplims[w*16+g] && sce->sf_idx[w*16+g] > 60)
-                    sce->sf_idx[w*16+g]--;
+                if (dists[w*16+g] > uplims[w*16+g] && sce->sf_idx[w*16+g] > 60) {
+                    if (find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]-1))
+                        sce->sf_idx[w*16+g]--;
+                    else //Try to make sure there is some energy in every band
+                        sce->sf_idx[w*16+g]-=2;
+                }
                 sce->sf_idx[w*16+g] = av_clip(sce->sf_idx[w*16+g], minscaler, minscaler + SCALE_MAX_DIFF);
                 sce->sf_idx[w*16+g] = FFMIN(sce->sf_idx[w*16+g], 219);
                 if (sce->sf_idx[w*16+g] != prevsc)
                     fflag = 1;
+                sce->band_type[w*16+g] = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]);
             }
         }
         its++;
@@ -771,7 +935,7 @@ static void search_for_quantizers_faac(AVCodecContext *avctx, AACEncContext *s,
                 continue;
             }
             sce->zeroes[w*16+g] = 0;
-            scf  = prev_scf = av_clip(SCALE_ONE_POS - SCALE_DIV_512 - log2(1/maxq[w*16+g])*16/3, 60, 218);
+            scf  = prev_scf = av_clip(SCALE_ONE_POS - SCALE_DIV_512 - log2f(1/maxq[w*16+g])*16/3, 60, 218);
             step = 16;
             for (;;) {
                 float dist = 0.0f;
@@ -800,7 +964,7 @@ static void search_for_quantizers_faac(AVCodecContext *avctx, AACEncContext *s,
                 if (curdiff <= 1.0f)
                     step = 0;
                 else
-                    step = log2(curdiff);
+                    step = log2f(curdiff);
                 if (dist > uplim[w*16+g])
                     step = -step;
                 scf += step;
@@ -853,7 +1017,7 @@ static void search_for_quantizers_fast(AVCodecContext *avctx, AACEncContext *s,
                     sce->sf_idx[(w+w2)*16+g] = 218;
                     sce->zeroes[(w+w2)*16+g] = 1;
                 } else {
-                    sce->sf_idx[(w+w2)*16+g] = av_clip(SCALE_ONE_POS - SCALE_DIV_512 + log2(band->threshold), 80, 218);
+                    sce->sf_idx[(w+w2)*16+g] = av_clip(SCALE_ONE_POS - SCALE_DIV_512 + log2f(band->threshold), 80, 218);
                     sce->zeroes[(w+w2)*16+g] = 0;
                 }
                 minq = FFMIN(minq, sce->sf_idx[(w+w2)*16+g]);
@@ -893,7 +1057,7 @@ static void search_for_ms(AACEncContext *s, ChannelElement *cpe,
                     for (i = 0; i < sce0->ics.swb_sizes[g]; i++) {
                         M[i] = (sce0->coeffs[start+w2*128+i]
                               + sce1->coeffs[start+w2*128+i]) * 0.5;
-                        S[i] =  sce0->coeffs[start+w2*128+i]
+                        S[i] =  M[i]
                               - sce1->coeffs[start+w2*128+i];
                     }
                     abs_pow34_v(L34, sce0->coeffs+start+w2*128, sce0->ics.swb_sizes[g]);
@@ -947,7 +1111,7 @@ AACCoefficientsEncoder ff_aac_coders[] = {
     },
     {
         search_for_quantizers_twoloop,
-        encode_window_bands_info,
+        codebook_trellis_rate,
         quantize_and_encode_band,
         search_for_ms,
     },
diff --git a/libavcodec/aacdec.c b/libavcodec/aacdec.c
new file mode 100644
index 0000000..c9761a1
--- /dev/null
+++ b/libavcodec/aacdec.c
@@ -0,0 +1,2520 @@
+/*
+ * AAC decoder
+ * Copyright (c) 2005-2006 Oded Shimon ( ods15 ods15 dyndns org )
+ * Copyright (c) 2006-2007 Maxim Gavrilov ( maxim.gavrilov gmail com )
+ *
+ * AAC LATM decoder
+ * Copyright (c) 2008-2010 Paul Kendall <paul at kcbbs.gen.nz>
+ * Copyright (c) 2010      Janne Grunau <janne-ffmpeg at jannau.net>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * AAC decoder
+ * @author Oded Shimon  ( ods15 ods15 dyndns org )
+ * @author Maxim Gavrilov ( maxim.gavrilov gmail com )
+ */
+
+/*
+ * supported tools
+ *
+ * Support?             Name
+ * N (code in SoC repo) gain control
+ * Y                    block switching
+ * Y                    window shapes - standard
+ * N                    window shapes - Low Delay
+ * Y                    filterbank - standard
+ * N (code in SoC repo) filterbank - Scalable Sample Rate
+ * Y                    Temporal Noise Shaping
+ * Y                    Long Term Prediction
+ * Y                    intensity stereo
+ * Y                    channel coupling
+ * Y                    frequency domain prediction
+ * Y                    Perceptual Noise Substitution
+ * Y                    Mid/Side stereo
+ * N                    Scalable Inverse AAC Quantization
+ * N                    Frequency Selective Switch
+ * N                    upsampling filter
+ * Y                    quantization & coding - AAC
+ * N                    quantization & coding - TwinVQ
+ * N                    quantization & coding - BSAC
+ * N                    AAC Error Resilience tools
+ * N                    Error Resilience payload syntax
+ * N                    Error Protection tool
+ * N                    CELP
+ * N                    Silence Compression
+ * N                    HVXC
+ * N                    HVXC 4kbits/s VR
+ * N                    Structured Audio tools
+ * N                    Structured Audio Sample Bank Format
+ * N                    MIDI
+ * N                    Harmonic and Individual Lines plus Noise
+ * N                    Text-To-Speech Interface
+ * Y                    Spectral Band Replication
+ * Y (not in this code) Layer-1
+ * Y (not in this code) Layer-2
+ * Y (not in this code) Layer-3
+ * N                    SinuSoidal Coding (Transient, Sinusoid, Noise)
+ * Y                    Parametric Stereo
+ * N                    Direct Stream Transfer
+ *
+ * Note: - HE AAC v1 comprises LC AAC with Spectral Band Replication.
+ *       - HE AAC v2 comprises LC AAC with Spectral Band Replication and
+           Parametric Stereo.
+ */
+
+
+#include "avcodec.h"
+#include "internal.h"
+#include "get_bits.h"
+#include "dsputil.h"
+#include "fft.h"
+#include "fmtconvert.h"
+#include "lpc.h"
+#include "kbdwin.h"
+#include "sinewin.h"
+
+#include "aac.h"
+#include "aactab.h"
+#include "aacdectab.h"
+#include "cbrt_tablegen.h"
+#include "sbr.h"
+#include "aacsbr.h"
+#include "mpeg4audio.h"
+#include "aacadtsdec.h"
+
+#include <assert.h>
+#include <errno.h>
+#include <math.h>
+#include <string.h>
+
+#if ARCH_ARM
+#   include "arm/aac.h"
+#endif
+
+union float754 {
+    float f;
+    uint32_t i;
+};
+
+static VLC vlc_scalefactors;
+static VLC vlc_spectral[11];
+
+static const char overread_err[] = "Input buffer exhausted before END element found\n";
+
+static ChannelElement *get_che(AACContext *ac, int type, int elem_id)
+{
+    // For PCE based channel configurations map the channels solely based on tags.
+    if (!ac->m4ac.chan_config) {
+        return ac->tag_che_map[type][elem_id];
+    }
+    // For indexed channel configurations map the channels solely based on position.
+    switch (ac->m4ac.chan_config) {
+    case 7:
+        if (ac->tags_mapped == 3 && type == TYPE_CPE) {
+            ac->tags_mapped++;
+            return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][2];
+        }
+    case 6:
+        /* Some streams incorrectly code 5.1 audio as SCE[0] CPE[0] CPE[1] SCE[1]
+           instead of SCE[0] CPE[0] CPE[1] LFE[0]. If we seem to have
+           encountered such a stream, transfer the LFE[0] element to the SCE[1]'s mapping */
+        if (ac->tags_mapped == tags_per_config[ac->m4ac.chan_config] - 1 && (type == TYPE_LFE || type == TYPE_SCE)) {
+            ac->tags_mapped++;
+            return ac->tag_che_map[type][elem_id] = ac->che[TYPE_LFE][0];
+        }
+    case 5:
+        if (ac->tags_mapped == 2 && type == TYPE_CPE) {
+            ac->tags_mapped++;
+            return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][1];
+        }
+    case 4:
+        if (ac->tags_mapped == 2 && ac->m4ac.chan_config == 4 && type == TYPE_SCE) {
+            ac->tags_mapped++;
+            return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
+        }
+    case 3:
+    case 2:
+        if (ac->tags_mapped == (ac->m4ac.chan_config != 2) && type == TYPE_CPE) {
+            ac->tags_mapped++;
+            return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][0];
+        } else if (ac->m4ac.chan_config == 2) {
+            return NULL;
+        }
+    case 1:
+        if (!ac->tags_mapped && type == TYPE_SCE) {
+            ac->tags_mapped++;
+            return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][0];
+        }
+    default:
+        return NULL;
+    }
+}
+
+/**
+ * Check for the channel element in the current channel position configuration.
+ * If it exists, make sure the appropriate element is allocated and map the
+ * channel order to match the internal Libav channel layout.
+ *
+ * @param   che_pos current channel position configuration
+ * @param   type channel element type
+ * @param   id channel element id
+ * @param   channels count of the number of channels in the configuration
+ *
+ * @return  Returns error status. 0 - OK, !0 - error
+ */
+static av_cold int che_configure(AACContext *ac,
+                         enum ChannelPosition che_pos[4][MAX_ELEM_ID],
+                         int type, int id,
+                         int *channels)
+{
+    if (che_pos[type][id]) {
+        if (!ac->che[type][id] && !(ac->che[type][id] = av_mallocz(sizeof(ChannelElement))))
+            return AVERROR(ENOMEM);
+        ff_aac_sbr_ctx_init(&ac->che[type][id]->sbr);
+        if (type != TYPE_CCE) {
+            ac->output_data[(*channels)++] = ac->che[type][id]->ch[0].ret;
+            if (type == TYPE_CPE ||
+                (type == TYPE_SCE && ac->m4ac.ps == 1)) {
+                ac->output_data[(*channels)++] = ac->che[type][id]->ch[1].ret;
+            }
+        }
+    } else {
+        if (ac->che[type][id])
+            ff_aac_sbr_ctx_close(&ac->che[type][id]->sbr);
+        av_freep(&ac->che[type][id]);
+    }
+    return 0;
+}
+
+/**
+ * Configure output channel order based on the current program configuration element.
+ *
+ * @param   che_pos current channel position configuration
+ * @param   new_che_pos New channel position configuration - we only do something if it differs from the current one.
+ *
+ * @return  Returns error status. 0 - OK, !0 - error
+ */
+static av_cold int output_configure(AACContext *ac,
+                            enum ChannelPosition che_pos[4][MAX_ELEM_ID],
+                            enum ChannelPosition new_che_pos[4][MAX_ELEM_ID],
+                            int channel_config, enum OCStatus oc_type)
+{
+    AVCodecContext *avctx = ac->avctx;
+    int i, type, channels = 0, ret;
+
+    if (new_che_pos != che_pos)
+    memcpy(che_pos, new_che_pos, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
+
+    if (channel_config) {
+        for (i = 0; i < tags_per_config[channel_config]; i++) {
+            if ((ret = che_configure(ac, che_pos,
+                                     aac_channel_layout_map[channel_config - 1][i][0],
+                                     aac_channel_layout_map[channel_config - 1][i][1],
+                                     &channels)))
+                return ret;
+        }
+
+        memset(ac->tag_che_map, 0,       4 * MAX_ELEM_ID * sizeof(ac->che[0][0]));
+
+        avctx->channel_layout = aac_channel_layout[channel_config - 1];
+    } else {
+        /* Allocate or free elements depending on if they are in the
+         * current program configuration.
+         *
+         * Set up default 1:1 output mapping.
+         *
+         * For a 5.1 stream the output order will be:
+         *    [ Center ] [ Front Left ] [ Front Right ] [ LFE ] [ Surround Left ] [ Surround Right ]
+         */
+
+        for (i = 0; i < MAX_ELEM_ID; i++) {
+            for (type = 0; type < 4; type++) {
+                if ((ret = che_configure(ac, che_pos, type, i, &channels)))
+                    return ret;
+            }
+        }
+
+        memcpy(ac->tag_che_map, ac->che, 4 * MAX_ELEM_ID * sizeof(ac->che[0][0]));
+
+        avctx->channel_layout = 0;
+    }
+
+    avctx->channels = channels;
+
+    ac->output_configured = oc_type;
+
+    return 0;
+}
+
+/**
+ * Decode an array of 4 bit element IDs, optionally interleaved with a stereo/mono switching bit.
+ *
+ * @param cpe_map Stereo (Channel Pair Element) map, NULL if stereo bit is not present.
+ * @param sce_map mono (Single Channel Element) map
+ * @param type speaker type/position for these channels
+ */
+static void decode_channel_map(enum ChannelPosition *cpe_map,
+                               enum ChannelPosition *sce_map,
+                               enum ChannelPosition type,
+                               GetBitContext *gb, int n)
+{
+    while (n--) {
+        enum ChannelPosition *map = cpe_map && get_bits1(gb) ? cpe_map : sce_map; // stereo or mono map
+        map[get_bits(gb, 4)] = type;
+    }
+}
+
+/**
+ * Decode program configuration element; reference: table 4.2.
+ *
+ * @param   new_che_pos New channel position configuration - we only do something if it differs from the current one.
+ *
+ * @return  Returns error status. 0 - OK, !0 - error
+ */
+static int decode_pce(AVCodecContext *avctx, MPEG4AudioConfig *m4ac,
+                      enum ChannelPosition new_che_pos[4][MAX_ELEM_ID],
+                      GetBitContext *gb)
+{
+    int num_front, num_side, num_back, num_lfe, num_assoc_data, num_cc, sampling_index;
+    int comment_len;
+
+    skip_bits(gb, 2);  // object_type
+
+    sampling_index = get_bits(gb, 4);
+    if (m4ac->sampling_index != sampling_index)
+        av_log(avctx, AV_LOG_WARNING, "Sample rate index in program config element does not match the sample rate index configured by the container.\n");
+
+    num_front       = get_bits(gb, 4);
+    num_side        = get_bits(gb, 4);
+    num_back        = get_bits(gb, 4);
+    num_lfe         = get_bits(gb, 2);
+    num_assoc_data  = get_bits(gb, 3);
+    num_cc          = get_bits(gb, 4);
+
+    if (get_bits1(gb))
+        skip_bits(gb, 4); // mono_mixdown_tag
+    if (get_bits1(gb))
+        skip_bits(gb, 4); // stereo_mixdown_tag
+
+    if (get_bits1(gb))
+        skip_bits(gb, 3); // mixdown_coeff_index and pseudo_surround
+
+    decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_FRONT, gb, num_front);
+    decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_SIDE,  gb, num_side );
+    decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_BACK,  gb, num_back );
+    decode_channel_map(NULL,                  new_che_pos[TYPE_LFE], AAC_CHANNEL_LFE,   gb, num_lfe  );
+
+    skip_bits_long(gb, 4 * num_assoc_data);
+
+    decode_channel_map(new_che_pos[TYPE_CCE], new_che_pos[TYPE_CCE], AAC_CHANNEL_CC,    gb, num_cc   );
+
+    align_get_bits(gb);
+
+    /* comment field, first byte is length */
+    comment_len = get_bits(gb, 8) * 8;
+    if (get_bits_left(gb) < comment_len) {
+        av_log(avctx, AV_LOG_ERROR, overread_err);
+        return -1;
+    }
+    skip_bits_long(gb, comment_len);
+    return 0;
+}
+
+/**
+ * Set up channel positions based on a default channel configuration
+ * as specified in table 1.17.
+ *
+ * @param   new_che_pos New channel position configuration - we only do something if it differs from the current one.
+ *
+ * @return  Returns error status. 0 - OK, !0 - error
+ */
+static av_cold int set_default_channel_config(AVCodecContext *avctx,
+                                      enum ChannelPosition new_che_pos[4][MAX_ELEM_ID],
+                                      int channel_config)
+{
+    if (channel_config < 1 || channel_config > 7) {
+        av_log(avctx, AV_LOG_ERROR, "invalid default channel configuration (%d)\n",
+               channel_config);
+        return -1;
+    }
+
+    /* default channel configurations:
+     *
+     * 1ch : front center (mono)
+     * 2ch : L + R (stereo)
+     * 3ch : front center + L + R
+     * 4ch : front center + L + R + back center
+     * 5ch : front center + L + R + back stereo
+     * 6ch : front center + L + R + back stereo + LFE
+     * 7ch : front center + L + R + outer front left + outer front right + back stereo + LFE
+     */
+
+    if (channel_config != 2)
+        new_che_pos[TYPE_SCE][0] = AAC_CHANNEL_FRONT; // front center (or mono)
+    if (channel_config > 1)
+        new_che_pos[TYPE_CPE][0] = AAC_CHANNEL_FRONT; // L + R (or stereo)
+    if (channel_config == 4)
+        new_che_pos[TYPE_SCE][1] = AAC_CHANNEL_BACK;  // back center
+    if (channel_config > 4)
+        new_che_pos[TYPE_CPE][(channel_config == 7) + 1]
+        = AAC_CHANNEL_BACK;  // back stereo
+    if (channel_config > 5)
+        new_che_pos[TYPE_LFE][0] = AAC_CHANNEL_LFE;   // LFE
+    if (channel_config == 7)
+        new_che_pos[TYPE_CPE][1] = AAC_CHANNEL_FRONT; // outer front left + outer front right
+
+    return 0;
+}
+
+/**
+ * Decode GA "General Audio" specific configuration; reference: table 4.1.
+ *
+ * @param   ac          pointer to AACContext, may be null
+ * @param   avctx       pointer to AVCCodecContext, used for logging
+ *
+ * @return  Returns error status. 0 - OK, !0 - error
+ */
+static int decode_ga_specific_config(AACContext *ac, AVCodecContext *avctx,
+                                     GetBitContext *gb,
+                                     MPEG4AudioConfig *m4ac,
+                                     int channel_config)
+{
+    enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
+    int extension_flag, ret;
+
+    if (get_bits1(gb)) { // frameLengthFlag
+        av_log_missing_feature(avctx, "960/120 MDCT window is", 1);
+        return -1;
+    }
+
+    if (get_bits1(gb))       // dependsOnCoreCoder
+        skip_bits(gb, 14);   // coreCoderDelay
+    extension_flag = get_bits1(gb);
+
+    if (m4ac->object_type == AOT_AAC_SCALABLE ||
+        m4ac->object_type == AOT_ER_AAC_SCALABLE)
+        skip_bits(gb, 3);     // layerNr
+
+    memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
+    if (channel_config == 0) {
+        skip_bits(gb, 4);  // element_instance_tag
+        if ((ret = decode_pce(avctx, m4ac, new_che_pos, gb)))
+            return ret;
+    } else {
+        if ((ret = set_default_channel_config(avctx, new_che_pos, channel_config)))
+            return ret;
+    }
+    if (ac && (ret = output_configure(ac, ac->che_pos, new_che_pos, channel_config, OC_GLOBAL_HDR)))
+        return ret;
+
+    if (extension_flag) {
+        switch (m4ac->object_type) {
+        case AOT_ER_BSAC:
+            skip_bits(gb, 5);    // numOfSubFrame
+            skip_bits(gb, 11);   // layer_length
+            break;
+        case AOT_ER_AAC_LC:
+        case AOT_ER_AAC_LTP:
+        case AOT_ER_AAC_SCALABLE:
+        case AOT_ER_AAC_LD:
+            skip_bits(gb, 3);  /* aacSectionDataResilienceFlag
+                                    * aacScalefactorDataResilienceFlag
+                                    * aacSpectralDataResilienceFlag
+                                    */
+            break;
+        }
+        skip_bits1(gb);    // extensionFlag3 (TBD in version 3)
+    }
+    return 0;
+}
+
+/**
+ * Decode audio specific configuration; reference: table 1.13.
+ *
+ * @param   ac          pointer to AACContext, may be null
+ * @param   avctx       pointer to AVCCodecContext, used for logging
+ * @param   m4ac        pointer to MPEG4AudioConfig, used for parsing
+ * @param   data        pointer to AVCodecContext extradata
+ * @param   data_size   size of AVCCodecContext extradata
+ *
+ * @return  Returns error status or number of consumed bits. <0 - error
+ */
+static int decode_audio_specific_config(AACContext *ac,
+                                        AVCodecContext *avctx,
+                                        MPEG4AudioConfig *m4ac,
+                                        const uint8_t *data, int data_size)
+{
+    GetBitContext gb;
+    int i;
+
+    init_get_bits(&gb, data, data_size * 8);
+
+    if ((i = ff_mpeg4audio_get_config(m4ac, data, data_size)) < 0)
+        return -1;
+    if (m4ac->sampling_index > 12) {
+        av_log(avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", m4ac->sampling_index);
+        return -1;
+    }
+    if (m4ac->sbr == 1 && m4ac->ps == -1)
+        m4ac->ps = 1;
+
+    skip_bits_long(&gb, i);
+
+    switch (m4ac->object_type) {
+    case AOT_AAC_MAIN:
+    case AOT_AAC_LC:
+    case AOT_AAC_LTP:
+        if (decode_ga_specific_config(ac, avctx, &gb, m4ac, m4ac->chan_config))
+            return -1;
+        break;
+    default:
+        av_log(avctx, AV_LOG_ERROR, "Audio object type %s%d is not supported.\n",
+               m4ac->sbr == 1? "SBR+" : "", m4ac->object_type);
+        return -1;
+    }
+
+    return get_bits_count(&gb);
+}
+
+/**
+ * linear congruential pseudorandom number generator
+ *
+ * @param   previous_val    pointer to the current state of the generator
+ *
+ * @return  Returns a 32-bit pseudorandom integer
+ */
+static av_always_inline int lcg_random(int previous_val)
+{
+    return previous_val * 1664525 + 1013904223;
+}
+
+static av_always_inline void reset_predict_state(PredictorState *ps)
+{
+    ps->r0   = 0.0f;
+    ps->r1   = 0.0f;
+    ps->cor0 = 0.0f;
+    ps->cor1 = 0.0f;
+    ps->var0 = 1.0f;
+    ps->var1 = 1.0f;
+}
+
+static void reset_all_predictors(PredictorState *ps)
+{
+    int i;
+    for (i = 0; i < MAX_PREDICTORS; i++)
+        reset_predict_state(&ps[i]);
+}
+
+static void reset_predictor_group(PredictorState *ps, int group_num)
+{
+    int i;
+    for (i = group_num - 1; i < MAX_PREDICTORS; i += 30)
+        reset_predict_state(&ps[i]);
+}
+
+#define AAC_INIT_VLC_STATIC(num, size) \
+    INIT_VLC_STATIC(&vlc_spectral[num], 8, ff_aac_spectral_sizes[num], \
+         ff_aac_spectral_bits[num], sizeof( ff_aac_spectral_bits[num][0]), sizeof( ff_aac_spectral_bits[num][0]), \
+        ff_aac_spectral_codes[num], sizeof(ff_aac_spectral_codes[num][0]), sizeof(ff_aac_spectral_codes[num][0]), \
+        size);
+
+static av_cold int aac_decode_init(AVCodecContext *avctx)
+{
+    AACContext *ac = avctx->priv_data;
+
+    ac->avctx = avctx;
+    ac->m4ac.sample_rate = avctx->sample_rate;
+
+    if (avctx->extradata_size > 0) {
+        if (decode_audio_specific_config(ac, ac->avctx, &ac->m4ac,
+                                         avctx->extradata,
+                                         avctx->extradata_size) < 0)
+            return -1;
+    }
+
+    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
+
+    AAC_INIT_VLC_STATIC( 0, 304);
+    AAC_INIT_VLC_STATIC( 1, 270);
+    AAC_INIT_VLC_STATIC( 2, 550);
+    AAC_INIT_VLC_STATIC( 3, 300);
+    AAC_INIT_VLC_STATIC( 4, 328);
+    AAC_INIT_VLC_STATIC( 5, 294);
+    AAC_INIT_VLC_STATIC( 6, 306);
+    AAC_INIT_VLC_STATIC( 7, 268);
+    AAC_INIT_VLC_STATIC( 8, 510);
+    AAC_INIT_VLC_STATIC( 9, 366);
+    AAC_INIT_VLC_STATIC(10, 462);
+
+    ff_aac_sbr_init();
+
+    dsputil_init(&ac->dsp, avctx);
+    ff_fmt_convert_init(&ac->fmt_conv, avctx);
+
+    ac->random_state = 0x1f2e3d4c;
+
+    // -1024 - Compensate wrong IMDCT method.
+    // 60    - Required to scale values to the correct range [-32768,32767]
+    //         for float to int16 conversion. (1 << (60 / 4)) == 32768
+    ac->sf_scale  = 1. / -1024.;
+    ac->sf_offset = 60;
+
+    ff_aac_tableinit();
+
+    INIT_VLC_STATIC(&vlc_scalefactors,7,FF_ARRAY_ELEMS(ff_aac_scalefactor_code),
+                    ff_aac_scalefactor_bits, sizeof(ff_aac_scalefactor_bits[0]), sizeof(ff_aac_scalefactor_bits[0]),
+                    ff_aac_scalefactor_code, sizeof(ff_aac_scalefactor_code[0]), sizeof(ff_aac_scalefactor_code[0]),
+                    352);
+
+    ff_mdct_init(&ac->mdct,       11, 1, 1.0);
+    ff_mdct_init(&ac->mdct_small,  8, 1, 1.0);
+    ff_mdct_init(&ac->mdct_ltp,   11, 0, 1.0);
+    // window initialization
+    ff_kbd_window_init(ff_aac_kbd_long_1024, 4.0, 1024);
+    ff_kbd_window_init(ff_aac_kbd_short_128, 6.0, 128);
+    ff_init_ff_sine_windows(10);
+    ff_init_ff_sine_windows( 7);
+
+    cbrt_tableinit();
+
+    return 0;
+}
+
+/**
+ * Skip data_stream_element; reference: table 4.10.
+ */
+static int skip_data_stream_element(AACContext *ac, GetBitContext *gb)
+{
+    int byte_align = get_bits1(gb);
+    int count = get_bits(gb, 8);
+    if (count == 255)
+        count += get_bits(gb, 8);
+    if (byte_align)
+        align_get_bits(gb);
+
+    if (get_bits_left(gb) < 8 * count) {
+        av_log(ac->avctx, AV_LOG_ERROR, overread_err);
+        return -1;
+    }
+    skip_bits_long(gb, 8 * count);
+    return 0;
+}
+
+static int decode_prediction(AACContext *ac, IndividualChannelStream *ics,
+                             GetBitContext *gb)
+{
+    int sfb;
+    if (get_bits1(gb)) {
+        ics->predictor_reset_group = get_bits(gb, 5);
+        if (ics->predictor_reset_group == 0 || ics->predictor_reset_group > 30) {
+            av_log(ac->avctx, AV_LOG_ERROR, "Invalid Predictor Reset Group.\n");
+            return -1;
+        }
+    }
+    for (sfb = 0; sfb < FFMIN(ics->max_sfb, ff_aac_pred_sfb_max[ac->m4ac.sampling_index]); sfb++) {
+        ics->prediction_used[sfb] = get_bits1(gb);
+    }
+    return 0;
+}
+
+/**
+ * Decode Long Term Prediction data; reference: table 4.xx.
+ */
+static void decode_ltp(AACContext *ac, LongTermPrediction *ltp,
+                       GetBitContext *gb, uint8_t max_sfb)
+{
+    int sfb;
+
+    ltp->lag  = get_bits(gb, 11);
+    ltp->coef = ltp_coef[get_bits(gb, 3)] * ac->sf_scale;
+    for (sfb = 0; sfb < FFMIN(max_sfb, MAX_LTP_LONG_SFB); sfb++)
+        ltp->used[sfb] = get_bits1(gb);
+}
+
+/**
+ * Decode Individual Channel Stream info; reference: table 4.6.
+ *
+ * @param   common_window   Channels have independent [0], or shared [1], Individual Channel Stream information.
+ */
+static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,
+                           GetBitContext *gb, int common_window)
+{
+    if (get_bits1(gb)) {
+        av_log(ac->avctx, AV_LOG_ERROR, "Reserved bit set.\n");
+        memset(ics, 0, sizeof(IndividualChannelStream));
+        return -1;
+    }
+    ics->window_sequence[1] = ics->window_sequence[0];
+    ics->window_sequence[0] = get_bits(gb, 2);
+    ics->use_kb_window[1]   = ics->use_kb_window[0];
+    ics->use_kb_window[0]   = get_bits1(gb);
+    ics->num_window_groups  = 1;
+    ics->group_len[0]       = 1;
+    if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
+        int i;
+        ics->max_sfb = get_bits(gb, 4);
+        for (i = 0; i < 7; i++) {
+            if (get_bits1(gb)) {
+                ics->group_len[ics->num_window_groups - 1]++;
+            } else {
+                ics->num_window_groups++;
+                ics->group_len[ics->num_window_groups - 1] = 1;
+            }
+        }
+        ics->num_windows       = 8;
+        ics->swb_offset        =    ff_swb_offset_128[ac->m4ac.sampling_index];
+        ics->num_swb           =   ff_aac_num_swb_128[ac->m4ac.sampling_index];
+        ics->tns_max_bands     = ff_tns_max_bands_128[ac->m4ac.sampling_index];
+        ics->predictor_present = 0;
+    } else {
+        ics->max_sfb               = get_bits(gb, 6);
+        ics->num_windows           = 1;
+        ics->swb_offset            =    ff_swb_offset_1024[ac->m4ac.sampling_index];
+        ics->num_swb               =   ff_aac_num_swb_1024[ac->m4ac.sampling_index];
+        ics->tns_max_bands         = ff_tns_max_bands_1024[ac->m4ac.sampling_index];
+        ics->predictor_present     = get_bits1(gb);
+        ics->predictor_reset_group = 0;
+        if (ics->predictor_present) {
+            if (ac->m4ac.object_type == AOT_AAC_MAIN) {
+                if (decode_prediction(ac, ics, gb)) {
+                    memset(ics, 0, sizeof(IndividualChannelStream));
+                    return -1;
+                }
+            } else if (ac->m4ac.object_type == AOT_AAC_LC) {
+                av_log(ac->avctx, AV_LOG_ERROR, "Prediction is not allowed in AAC-LC.\n");
+                memset(ics, 0, sizeof(IndividualChannelStream));
+                return -1;
+            } else {
+                if ((ics->ltp.present = get_bits(gb, 1)))
+                    decode_ltp(ac, &ics->ltp, gb, ics->max_sfb);
+            }
+        }
+    }
+
+    if (ics->max_sfb > ics->num_swb) {
+        av_log(ac->avctx, AV_LOG_ERROR,
+               "Number of scalefactor bands in group (%d) exceeds limit (%d).\n",
+               ics->max_sfb, ics->num_swb);
+        memset(ics, 0, sizeof(IndividualChannelStream));
+        return -1;
+    }
+
+    return 0;
+}
+
+/**
+ * Decode band types (section_data payload); reference: table 4.46.
+ *
+ * @param   band_type           array of the used band type
+ * @param   band_type_run_end   array of the last scalefactor band of a band type run
+ *
+ * @return  Returns error status. 0 - OK, !0 - error
+ */
+static int decode_band_types(AACContext *ac, enum BandType band_type[120],
+                             int band_type_run_end[120], GetBitContext *gb,
+                             IndividualChannelStream *ics)
+{
+    int g, idx = 0;
+    const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
+    for (g = 0; g < ics->num_window_groups; g++) {
+        int k = 0;
+        while (k < ics->max_sfb) {
+            uint8_t sect_end = k;
+            int sect_len_incr;
+            int sect_band_type = get_bits(gb, 4);
+            if (sect_band_type == 12) {
+                av_log(ac->avctx, AV_LOG_ERROR, "invalid band type\n");
+                return -1;
+            }
+            while ((sect_len_incr = get_bits(gb, bits)) == (1 << bits) - 1)
+                sect_end += sect_len_incr;
+            sect_end += sect_len_incr;
+            if (get_bits_left(gb) < 0) {
+                av_log(ac->avctx, AV_LOG_ERROR, overread_err);
+                return -1;
+            }
+            if (sect_end > ics->max_sfb) {
+                av_log(ac->avctx, AV_LOG_ERROR,
+                       "Number of bands (%d) exceeds limit (%d).\n",
+                       sect_end, ics->max_sfb);
+                return -1;
+            }
+            for (; k < sect_end; k++) {
+                band_type        [idx]   = sect_band_type;
+                band_type_run_end[idx++] = sect_end;
+            }
+        }
+    }
+    return 0;
+}
+
+/**
+ * Decode scalefactors; reference: table 4.47.
+ *
+ * @param   global_gain         first scalefactor value as scalefactors are differentially coded
+ * @param   band_type           array of the used band type
+ * @param   band_type_run_end   array of the last scalefactor band of a band type run
+ * @param   sf                  array of scalefactors or intensity stereo positions
+ *
+ * @return  Returns error status. 0 - OK, !0 - error
+ */
+static int decode_scalefactors(AACContext *ac, float sf[120], GetBitContext *gb,
+                               unsigned int global_gain,
+                               IndividualChannelStream *ics,
+                               enum BandType band_type[120],
+                               int band_type_run_end[120])
+{
+    const int sf_offset = ac->sf_offset + (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE ? 12 : 0);
+    int g, i, idx = 0;
+    int offset[3] = { global_gain, global_gain - 90, 100 };
+    int noise_flag = 1;
+    static const char *sf_str[3] = { "Global gain", "Noise gain", "Intensity stereo position" };
+    for (g = 0; g < ics->num_window_groups; g++) {
+        for (i = 0; i < ics->max_sfb;) {
+            int run_end = band_type_run_end[idx];
+            if (band_type[idx] == ZERO_BT) {
+                for (; i < run_end; i++, idx++)
+                    sf[idx] = 0.;
+            } else if ((band_type[idx] == INTENSITY_BT) || (band_type[idx] == INTENSITY_BT2)) {
+                for (; i < run_end; i++, idx++) {
+                    offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
+                    if (offset[2] > 255U) {
+                        av_log(ac->avctx, AV_LOG_ERROR,
+                               "%s (%d) out of range.\n", sf_str[2], offset[2]);
+                        return -1;
+                    }
+                    sf[idx] = ff_aac_pow2sf_tab[-offset[2] + 300];
+                }
+            } else if (band_type[idx] == NOISE_BT) {
+                for (; i < run_end; i++, idx++) {
+                    if (noise_flag-- > 0)
+                        offset[1] += get_bits(gb, 9) - 256;
+                    else
+                        offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
+                    if (offset[1] > 255U) {
+                        av_log(ac->avctx, AV_LOG_ERROR,
+                               "%s (%d) out of range.\n", sf_str[1], offset[1]);
+                        return -1;
+                    }
+                    sf[idx] = -ff_aac_pow2sf_tab[offset[1] + sf_offset + 100];
+                }
+            } else {
+                for (; i < run_end; i++, idx++) {
+                    offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
+                    if (offset[0] > 255U) {
+                        av_log(ac->avctx, AV_LOG_ERROR,
+                               "%s (%d) out of range.\n", sf_str[0], offset[0]);
+                        return -1;
+                    }
+                    sf[idx] = -ff_aac_pow2sf_tab[ offset[0] + sf_offset];
+                }
+            }
+        }
+    }
+    return 0;
+}
+
+/**
+ * Decode pulse data; reference: table 4.7.
+ */
+static int decode_pulses(Pulse *pulse, GetBitContext *gb,
+                         const uint16_t *swb_offset, int num_swb)
+{
+    int i, pulse_swb;
+    pulse->num_pulse = get_bits(gb, 2) + 1;
+    pulse_swb        = get_bits(gb, 6);
+    if (pulse_swb >= num_swb)
+        return -1;
+    pulse->pos[0]    = swb_offset[pulse_swb];
+    pulse->pos[0]   += get_bits(gb, 5);
+    if (pulse->pos[0] > 1023)
+        return -1;
+    pulse->amp[0]    = get_bits(gb, 4);
+    for (i = 1; i < pulse->num_pulse; i++) {
+        pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];
+        if (pulse->pos[i] > 1023)
+            return -1;
+        pulse->amp[i] = get_bits(gb, 4);
+    }
+    return 0;
+}
+
+/**
+ * Decode Temporal Noise Shaping data; reference: table 4.48.
+ *
+ * @return  Returns error status. 0 - OK, !0 - error
+ */
+static int decode_tns(AACContext *ac, TemporalNoiseShaping *tns,
+                      GetBitContext *gb, const IndividualChannelStream *ics)
+{
+    int w, filt, i, coef_len, coef_res, coef_compress;
+    const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
+    const int tns_max_order = is8 ? 7 : ac->m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
+    for (w = 0; w < ics->num_windows; w++) {
+        if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
+            coef_res = get_bits1(gb);
+
+            for (filt = 0; filt < tns->n_filt[w]; filt++) {
+                int tmp2_idx;
+                tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
+
+                if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
+                    av_log(ac->avctx, AV_LOG_ERROR, "TNS filter order %d is greater than maximum %d.\n",
+                           tns->order[w][filt], tns_max_order);
+                    tns->order[w][filt] = 0;
+                    return -1;
+                }
+                if (tns->order[w][filt]) {
+                    tns->direction[w][filt] = get_bits1(gb);
+                    coef_compress = get_bits1(gb);
+                    coef_len = coef_res + 3 - coef_compress;
+                    tmp2_idx = 2 * coef_compress + coef_res;
+
+                    for (i = 0; i < tns->order[w][filt]; i++)
+                        tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
+                }
+            }
+        }
+    }
+    return 0;
+}
+
+/**
+ * Decode Mid/Side data; reference: table 4.54.
+ *
+ * @param   ms_present  Indicates mid/side stereo presence. [0] mask is all 0s;
+ *                      [1] mask is decoded from bitstream; [2] mask is all 1s;
+ *                      [3] reserved for scalable AAC
+ */
+static void decode_mid_side_stereo(ChannelElement *cpe, GetBitContext *gb,
+                                   int ms_present)
+{
+    int idx;
+    if (ms_present == 1) {
+        for (idx = 0; idx < cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb; idx++)
+            cpe->ms_mask[idx] = get_bits1(gb);
+    } else if (ms_present == 2) {
+        memset(cpe->ms_mask, 1, cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb * sizeof(cpe->ms_mask[0]));
+    }
+}
+
+#ifndef VMUL2
+static inline float *VMUL2(float *dst, const float *v, unsigned idx,
+                           const float *scale)
+{
+    float s = *scale;
+    *dst++ = v[idx    & 15] * s;
+    *dst++ = v[idx>>4 & 15] * s;
+    return dst;
+}
+#endif
+
+#ifndef VMUL4
+static inline float *VMUL4(float *dst, const float *v, unsigned idx,
+                           const float *scale)
+{
+    float s = *scale;
+    *dst++ = v[idx    & 3] * s;
+    *dst++ = v[idx>>2 & 3] * s;
+    *dst++ = v[idx>>4 & 3] * s;
+    *dst++ = v[idx>>6 & 3] * s;
+    return dst;
+}
+#endif
+
+#ifndef VMUL2S
+static inline float *VMUL2S(float *dst, const float *v, unsigned idx,
+                            unsigned sign, const float *scale)
+{
+    union float754 s0, s1;
+
+    s0.f = s1.f = *scale;
+    s0.i ^= sign >> 1 << 31;
+    s1.i ^= sign      << 31;
+
+    *dst++ = v[idx    & 15] * s0.f;
+    *dst++ = v[idx>>4 & 15] * s1.f;
+
+    return dst;
+}
+#endif
+
+#ifndef VMUL4S
+static inline float *VMUL4S(float *dst, const float *v, unsigned idx,
+                            unsigned sign, const float *scale)
+{
+    unsigned nz = idx >> 12;
+    union float754 s = { .f = *scale };
+    union float754 t;
+
+    t.i = s.i ^ (sign & 1U<<31);
+    *dst++ = v[idx    & 3] * t.f;
+
+    sign <<= nz & 1; nz >>= 1;
+    t.i = s.i ^ (sign & 1U<<31);
+    *dst++ = v[idx>>2 & 3] * t.f;
+
+    sign <<= nz & 1; nz >>= 1;
+    t.i = s.i ^ (sign & 1U<<31);
+    *dst++ = v[idx>>4 & 3] * t.f;
+
+    sign <<= nz & 1; nz >>= 1;
+    t.i = s.i ^ (sign & 1U<<31);
+    *dst++ = v[idx>>6 & 3] * t.f;
+
+    return dst;
+}
+#endif
+
+/**
+ * Decode spectral data; reference: table 4.50.
+ * Dequantize and scale spectral data; reference: 4.6.3.3.
+ *
+ * @param   coef            array of dequantized, scaled spectral data
+ * @param   sf              array of scalefactors or intensity stereo positions
+ * @param   pulse_present   set if pulses are present
+ * @param   pulse           pointer to pulse data struct
+ * @param   band_type       array of the used band type
+ *
+ * @return  Returns error status. 0 - OK, !0 - error
+ */
+static int decode_spectrum_and_dequant(AACContext *ac, float coef[1024],
+                                       GetBitContext *gb, const float sf[120],
+                                       int pulse_present, const Pulse *pulse,
+                                       const IndividualChannelStream *ics,
+                                       enum BandType band_type[120])
+{
+    int i, k, g, idx = 0;
+    const int c = 1024 / ics->num_windows;
+    const uint16_t *offsets = ics->swb_offset;
+    float *coef_base = coef;
+
+    for (g = 0; g < ics->num_windows; g++)
+        memset(coef + g * 128 + offsets[ics->max_sfb], 0, sizeof(float) * (c - offsets[ics->max_sfb]));
+
+    for (g = 0; g < ics->num_window_groups; g++) {
+        unsigned g_len = ics->group_len[g];
+
+        for (i = 0; i < ics->max_sfb; i++, idx++) {
+            const unsigned cbt_m1 = band_type[idx] - 1;
+            float *cfo = coef + offsets[i];
+            int off_len = offsets[i + 1] - offsets[i];
+            int group;
+
+            if (cbt_m1 >= INTENSITY_BT2 - 1) {
+                for (group = 0; group < g_len; group++, cfo+=128) {
+                    memset(cfo, 0, off_len * sizeof(float));
+                }
+            } else if (cbt_m1 == NOISE_BT - 1) {
+                for (group = 0; group < g_len; group++, cfo+=128) {
+                    float scale;
+                    float band_energy;
+
+                    for (k = 0; k < off_len; k++) {
+                        ac->random_state  = lcg_random(ac->random_state);
+                        cfo[k] = ac->random_state;
+                    }
+
+                    band_energy = ac->dsp.scalarproduct_float(cfo, cfo, off_len);
+                    scale = sf[idx] / sqrtf(band_energy);
+                    ac->dsp.vector_fmul_scalar(cfo, cfo, scale, off_len);
+                }
+            } else {
+                const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
+                const uint16_t *cb_vector_idx = ff_aac_codebook_vector_idx[cbt_m1];
+                VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
+                OPEN_READER(re, gb);
+
+                switch (cbt_m1 >> 1) {
+                case 0:
+                    for (group = 0; group < g_len; group++, cfo+=128) {
+                        float *cf = cfo;
+                        int len = off_len;
+
+                        do {
+                            int code;
+                            unsigned cb_idx;
+
+                            UPDATE_CACHE(re, gb);
+                            GET_VLC(code, re, gb, vlc_tab, 8, 2);
+                            cb_idx = cb_vector_idx[code];
+                            cf = VMUL4(cf, vq, cb_idx, sf + idx);
+                        } while (len -= 4);
+                    }
+                    break;
+
+                case 1:
+                    for (group = 0; group < g_len; group++, cfo+=128) {
+                        float *cf = cfo;
+                        int len = off_len;
+
+                        do {
+                            int code;
+                            unsigned nnz;
+                            unsigned cb_idx;
+                            uint32_t bits;
+
+                            UPDATE_CACHE(re, gb);
+                            GET_VLC(code, re, gb, vlc_tab, 8, 2);
+                            cb_idx = cb_vector_idx[code];
+                            nnz = cb_idx >> 8 & 15;
+                            bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
+                            LAST_SKIP_BITS(re, gb, nnz);
+                            cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
+                        } while (len -= 4);
+                    }
+                    break;
+
+                case 2:
+                    for (group = 0; group < g_len; group++, cfo+=128) {
+                        float *cf = cfo;
+                        int len = off_len;
+
+                        do {
+                            int code;
+                            unsigned cb_idx;
+
+                            UPDATE_CACHE(re, gb);
+                            GET_VLC(code, re, gb, vlc_tab, 8, 2);
+                            cb_idx = cb_vector_idx[code];
+                            cf = VMUL2(cf, vq, cb_idx, sf + idx);
+                        } while (len -= 2);
+                    }
+                    break;
+
+                case 3:
+                case 4:
+                    for (group = 0; group < g_len; group++, cfo+=128) {
+                        float *cf = cfo;
+                        int len = off_len;
+
+                        do {
+                            int code;
+                            unsigned nnz;
+                            unsigned cb_idx;
+                            unsigned sign;
+
+                            UPDATE_CACHE(re, gb);
+                            GET_VLC(code, re, gb, vlc_tab, 8, 2);
+                            cb_idx = cb_vector_idx[code];
+                            nnz = cb_idx >> 8 & 15;
+                            sign = SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12);
+                            LAST_SKIP_BITS(re, gb, nnz);
+                            cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
+                        } while (len -= 2);
+                    }
+                    break;
+
+                default:
+                    for (group = 0; group < g_len; group++, cfo+=128) {
+                        float *cf = cfo;
+                        uint32_t *icf = (uint32_t *) cf;
+                        int len = off_len;
+
+                        do {
+                            int code;
+                            unsigned nzt, nnz;
+                            unsigned cb_idx;
+                            uint32_t bits;
+                            int j;
+
+                            UPDATE_CACHE(re, gb);
+                            GET_VLC(code, re, gb, vlc_tab, 8, 2);
+
+                            if (!code) {
+                                *icf++ = 0;
+                                *icf++ = 0;
+                                continue;
+                            }
+
+                            cb_idx = cb_vector_idx[code];
+                            nnz = cb_idx >> 12;
+                            nzt = cb_idx >> 8;
+                            bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
+                            LAST_SKIP_BITS(re, gb, nnz);
+
+                            for (j = 0; j < 2; j++) {
+                                if (nzt & 1<<j) {
+                                    uint32_t b;
+                                    int n;
+                                    /* The total length of escape_sequence must be < 22 bits according
+                                       to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
+                                    UPDATE_CACHE(re, gb);
+                                    b = GET_CACHE(re, gb);
+                                    b = 31 - av_log2(~b);
+
+                                    if (b > 8) {
+                                        av_log(ac->avctx, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
+                                        return -1;
+                                    }
+
+                                    SKIP_BITS(re, gb, b + 1);
+                                    b += 4;
+                                    n = (1 << b) + SHOW_UBITS(re, gb, b);
+                                    LAST_SKIP_BITS(re, gb, b);
+                                    *icf++ = cbrt_tab[n] | (bits & 1U<<31);
+                                    bits <<= 1;
+                                } else {
+                                    unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
+                                    *icf++ = (bits & 1U<<31) | v;
+                                    bits <<= !!v;
+                                }
+                                cb_idx >>= 4;
+                            }
+                        } while (len -= 2);
+
+                        ac->dsp.vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
+                    }
+                }
+
+                CLOSE_READER(re, gb);
+            }
+        }
+        coef += g_len << 7;
+    }
+
+    if (pulse_present) {
+        idx = 0;
+        for (i = 0; i < pulse->num_pulse; i++) {
+            float co = coef_base[ pulse->pos[i] ];
+            while (offsets[idx + 1] <= pulse->pos[i])
+                idx++;
+            if (band_type[idx] != NOISE_BT && sf[idx]) {
+                float ico = -pulse->amp[i];
+                if (co) {
+                    co /= sf[idx];
+                    ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
+                }
+                coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
+            }
+        }
+    }
+    return 0;
+}
+
+static av_always_inline float flt16_round(float pf)
+{
+    union float754 tmp;
+    tmp.f = pf;
+    tmp.i = (tmp.i + 0x00008000U) & 0xFFFF0000U;
+    return tmp.f;
+}
+
+static av_always_inline float flt16_even(float pf)
+{
+    union float754 tmp;
+    tmp.f = pf;
+    tmp.i = (tmp.i + 0x00007FFFU + (tmp.i & 0x00010000U >> 16)) & 0xFFFF0000U;
+    return tmp.f;
+}
+
+static av_always_inline float flt16_trunc(float pf)
+{
+    union float754 pun;
+    pun.f = pf;
+    pun.i &= 0xFFFF0000U;
+    return pun.f;
+}
+
+static av_always_inline void predict(PredictorState *ps, float *coef,
+                                     float sf_scale, float inv_sf_scale,
+                    int output_enable)
+{
+    const float a     = 0.953125; // 61.0 / 64
+    const float alpha = 0.90625;  // 29.0 / 32
+    float e0, e1;
+    float pv;
+    float k1, k2;
+    float   r0 = ps->r0,     r1 = ps->r1;
+    float cor0 = ps->cor0, cor1 = ps->cor1;
+    float var0 = ps->var0, var1 = ps->var1;
+
+    k1 = var0 > 1 ? cor0 * flt16_even(a / var0) : 0;
+    k2 = var1 > 1 ? cor1 * flt16_even(a / var1) : 0;
+
+    pv = flt16_round(k1 * r0 + k2 * r1);
+    if (output_enable)
+        *coef += pv * sf_scale;
+
+    e0 = *coef * inv_sf_scale;
+    e1 = e0 - k1 * r0;
+
+    ps->cor1 = flt16_trunc(alpha * cor1 + r1 * e1);
+    ps->var1 = flt16_trunc(alpha * var1 + 0.5f * (r1 * r1 + e1 * e1));
+    ps->cor0 = flt16_trunc(alpha * cor0 + r0 * e0);
+    ps->var0 = flt16_trunc(alpha * var0 + 0.5f * (r0 * r0 + e0 * e0));
+
+    ps->r1 = flt16_trunc(a * (r0 - k1 * e0));
+    ps->r0 = flt16_trunc(a * e0);
+}
+
+/**
+ * Apply AAC-Main style frequency domain prediction.
+ */
+static void apply_prediction(AACContext *ac, SingleChannelElement *sce)
+{
+    int sfb, k;
+    float sf_scale = ac->sf_scale, inv_sf_scale = 1 / ac->sf_scale;
+
+    if (!sce->ics.predictor_initialized) {
+        reset_all_predictors(sce->predictor_state);
+        sce->ics.predictor_initialized = 1;
+    }
+
+    if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
+        for (sfb = 0; sfb < ff_aac_pred_sfb_max[ac->m4ac.sampling_index]; sfb++) {
+            for (k = sce->ics.swb_offset[sfb]; k < sce->ics.swb_offset[sfb + 1]; k++) {
+                predict(&sce->predictor_state[k], &sce->coeffs[k],
+                        sf_scale, inv_sf_scale,
+                        sce->ics.predictor_present && sce->ics.prediction_used[sfb]);
+            }
+        }
+        if (sce->ics.predictor_reset_group)
+            reset_predictor_group(sce->predictor_state, sce->ics.predictor_reset_group);
+    } else
+        reset_all_predictors(sce->predictor_state);
+}
+
+/**
+ * Decode an individual_channel_stream payload; reference: table 4.44.
+ *
+ * @param   common_window   Channels have independent [0], or shared [1], Individual Channel Stream information.
+ * @param   scale_flag      scalable [1] or non-scalable [0] AAC (Unused until scalable AAC is implemented.)
+ *
+ * @return  Returns error status. 0 - OK, !0 - error
+ */
+static int decode_ics(AACContext *ac, SingleChannelElement *sce,
+                      GetBitContext *gb, int common_window, int scale_flag)
+{
+    Pulse pulse;
+    TemporalNoiseShaping    *tns = &sce->tns;
+    IndividualChannelStream *ics = &sce->ics;
+    float *out = sce->coeffs;
+    int global_gain, pulse_present = 0;
+
+    /* This assignment is to silence a GCC warning about the variable being used
+     * uninitialized when in fact it always is.
+     */
+    pulse.num_pulse = 0;
+
+    global_gain = get_bits(gb, 8);
+
+    if (!common_window && !scale_flag) {
+        if (decode_ics_info(ac, ics, gb, 0) < 0)
+            return -1;
+    }
+
+    if (decode_band_types(ac, sce->band_type, sce->band_type_run_end, gb, ics) < 0)
+        return -1;
+    if (decode_scalefactors(ac, sce->sf, gb, global_gain, ics, sce->band_type, sce->band_type_run_end) < 0)
+        return -1;
+
+    pulse_present = 0;
+    if (!scale_flag) {
+        if ((pulse_present = get_bits1(gb))) {
+            if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
+                av_log(ac->avctx, AV_LOG_ERROR, "Pulse tool not allowed in eight short sequence.\n");
+                return -1;
+            }
+            if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
+                av_log(ac->avctx, AV_LOG_ERROR, "Pulse data corrupt or invalid.\n");
+                return -1;
+            }
+        }
+        if ((tns->present = get_bits1(gb)) && decode_tns(ac, tns, gb, ics))
+            return -1;
+        if (get_bits1(gb)) {
+            av_log_missing_feature(ac->avctx, "SSR", 1);
+            return -1;
+        }
+    }
+
+    if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present, &pulse, ics, sce->band_type) < 0)
+        return -1;
+
+    if (ac->m4ac.object_type == AOT_AAC_MAIN && !common_window)
+        apply_prediction(ac, sce);
+
+    return 0;
+}
+
+/**
+ * Mid/Side stereo decoding; reference: 4.6.8.1.3.
+ */
+static void apply_mid_side_stereo(AACContext *ac, ChannelElement *cpe)
+{
+    const IndividualChannelStream *ics = &cpe->ch[0].ics;
+    float *ch0 = cpe->ch[0].coeffs;
+    float *ch1 = cpe->ch[1].coeffs;
+    int g, i, group, idx = 0;
+    const uint16_t *offsets = ics->swb_offset;
+    for (g = 0; g < ics->num_window_groups; g++) {
+        for (i = 0; i < ics->max_sfb; i++, idx++) {
+            if (cpe->ms_mask[idx] &&
+                    cpe->ch[0].band_type[idx] < NOISE_BT && cpe->ch[1].band_type[idx] < NOISE_BT) {
+                for (group = 0; group < ics->group_len[g]; group++) {
+                    ac->dsp.butterflies_float(ch0 + group * 128 + offsets[i],
+                                              ch1 + group * 128 + offsets[i],
+                                              offsets[i+1] - offsets[i]);
+                }
+            }
+        }
+        ch0 += ics->group_len[g] * 128;
+        ch1 += ics->group_len[g] * 128;
+    }
+}
+
+/**
+ * intensity stereo decoding; reference: 4.6.8.2.3
+ *
+ * @param   ms_present  Indicates mid/side stereo presence. [0] mask is all 0s;
+ *                      [1] mask is decoded from bitstream; [2] mask is all 1s;
+ *                      [3] reserved for scalable AAC
+ */
+static void apply_intensity_stereo(AACContext *ac, ChannelElement *cpe, int ms_present)
+{
+    const IndividualChannelStream *ics = &cpe->ch[1].ics;
+    SingleChannelElement         *sce1 = &cpe->ch[1];
+    float *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
+    const uint16_t *offsets = ics->swb_offset;
+    int g, group, i, idx = 0;
+    int c;
+    float scale;
+    for (g = 0; g < ics->num_window_groups; g++) {
+        for (i = 0; i < ics->max_sfb;) {
+            if (sce1->band_type[idx] == INTENSITY_BT || sce1->band_type[idx] == INTENSITY_BT2) {
+                const int bt_run_end = sce1->band_type_run_end[idx];
+                for (; i < bt_run_end; i++, idx++) {
+                    c = -1 + 2 * (sce1->band_type[idx] - 14);
+                    if (ms_present)
+                        c *= 1 - 2 * cpe->ms_mask[idx];
+                    scale = c * sce1->sf[idx];
+                    for (group = 0; group < ics->group_len[g]; group++)
+                        ac->dsp.vector_fmul_scalar(coef1 + group * 128 + offsets[i],
+                                                   coef0 + group * 128 + offsets[i],
+                                                   scale,
+                                                   offsets[i + 1] - offsets[i]);
+                }
+            } else {
+                int bt_run_end = sce1->band_type_run_end[idx];
+                idx += bt_run_end - i;
+                i    = bt_run_end;
+            }
+        }
+        coef0 += ics->group_len[g] * 128;
+        coef1 += ics->group_len[g] * 128;
+    }
+}
+
+/**
+ * Decode a channel_pair_element; reference: table 4.4.
+ *
+ * @return  Returns error status. 0 - OK, !0 - error
+ */
+static int decode_cpe(AACContext *ac, GetBitContext *gb, ChannelElement *cpe)
+{
+    int i, ret, common_window, ms_present = 0;
+
+    common_window = get_bits1(gb);
+    if (common_window) {
+        if (decode_ics_info(ac, &cpe->ch[0].ics, gb, 1))
+            return -1;
+        i = cpe->ch[1].ics.use_kb_window[0];
+        cpe->ch[1].ics = cpe->ch[0].ics;
+        cpe->ch[1].ics.use_kb_window[1] = i;
+        if (cpe->ch[1].ics.predictor_present && (ac->m4ac.object_type != AOT_AAC_MAIN))
+            if ((cpe->ch[1].ics.ltp.present = get_bits(gb, 1)))
+                decode_ltp(ac, &cpe->ch[1].ics.ltp, gb, cpe->ch[1].ics.max_sfb);
+        ms_present = get_bits(gb, 2);
+        if (ms_present == 3) {
+            av_log(ac->avctx, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
+            return -1;
+        } else if (ms_present)
+            decode_mid_side_stereo(cpe, gb, ms_present);
+    }
+    if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
+        return ret;
+    if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
+        return ret;
+
+    if (common_window) {
+        if (ms_present)
+            apply_mid_side_stereo(ac, cpe);
+        if (ac->m4ac.object_type == AOT_AAC_MAIN) {
+            apply_prediction(ac, &cpe->ch[0]);
+            apply_prediction(ac, &cpe->ch[1]);
+        }
+    }
+
+    apply_intensity_stereo(ac, cpe, ms_present);
+    return 0;
+}
+
+static const float cce_scale[] = {
+    1.09050773266525765921, //2^(1/8)
+    1.18920711500272106672, //2^(1/4)
+    M_SQRT2,
+    2,
+};
+
+/**
+ * Decode coupling_channel_element; reference: table 4.8.
+ *
+ * @return  Returns error status. 0 - OK, !0 - error
+ */
+static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
+{
+    int num_gain = 0;
+    int c, g, sfb, ret;
+    int sign;
+    float scale;
+    SingleChannelElement *sce = &che->ch[0];
+    ChannelCoupling     *coup = &che->coup;
+
+    coup->coupling_point = 2 * get_bits1(gb);
+    coup->num_coupled = get_bits(gb, 3);
+    for (c = 0; c <= coup->num_coupled; c++) {
+        num_gain++;
+        coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
+        coup->id_select[c] = get_bits(gb, 4);
+        if (coup->type[c] == TYPE_CPE) {
+            coup->ch_select[c] = get_bits(gb, 2);
+            if (coup->ch_select[c] == 3)
+                num_gain++;
+        } else
+            coup->ch_select[c] = 2;
+    }
+    coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
+
+    sign  = get_bits(gb, 1);
+    scale = cce_scale[get_bits(gb, 2)];
+
+    if ((ret = decode_ics(ac, sce, gb, 0, 0)))
+        return ret;
+
+    for (c = 0; c < num_gain; c++) {
+        int idx  = 0;
+        int cge  = 1;
+        int gain = 0;
+        float gain_cache = 1.;
+        if (c) {
+            cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
+            gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
+            gain_cache = powf(scale, -gain);
+        }
+        if (coup->coupling_point == AFTER_IMDCT) {
+            coup->gain[c][0] = gain_cache;
+        } else {
+            for (g = 0; g < sce->ics.num_window_groups; g++) {
+                for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
+                    if (sce->band_type[idx] != ZERO_BT) {
+                        if (!cge) {
+                            int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
+                            if (t) {
+                                int s = 1;
+                                t = gain += t;
+                                if (sign) {
+                                    s  -= 2 * (t & 0x1);
+                                    t >>= 1;
+                                }
+                                gain_cache = powf(scale, -t) * s;
+                            }
+                        }
+                        coup->gain[c][idx] = gain_cache;
+                    }
+                }
+            }
+        }
+    }
+    return 0;
+}
+
+/**
+ * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
+ *
+ * @return  Returns number of bytes consumed.
+ */
+static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc,
+                                         GetBitContext *gb)
+{
+    int i;
+    int num_excl_chan = 0;
+
+    do {
+        for (i = 0; i < 7; i++)
+            che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
+    } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
+
+    return num_excl_chan / 7;
+}
+
+/**
+ * Decode dynamic range information; reference: table 4.52.
+ *
+ * @param   cnt length of TYPE_FIL syntactic element in bytes
+ *
+ * @return  Returns number of bytes consumed.
+ */
+static int decode_dynamic_range(DynamicRangeControl *che_drc,
+                                GetBitContext *gb, int cnt)
+{
+    int n             = 1;
+    int drc_num_bands = 1;
+    int i;
+
+    /* pce_tag_present? */
+    if (get_bits1(gb)) {
+        che_drc->pce_instance_tag  = get_bits(gb, 4);
+        skip_bits(gb, 4); // tag_reserved_bits
+        n++;
+    }
+
+    /* excluded_chns_present? */
+    if (get_bits1(gb)) {
+        n += decode_drc_channel_exclusions(che_drc, gb);
+    }
+
+    /* drc_bands_present? */
+    if (get_bits1(gb)) {
+        che_drc->band_incr            = get_bits(gb, 4);
+        che_drc->interpolation_scheme = get_bits(gb, 4);
+        n++;
+        drc_num_bands += che_drc->band_incr;
+        for (i = 0; i < drc_num_bands; i++) {
+            che_drc->band_top[i] = get_bits(gb, 8);
+            n++;
+        }
+    }
+
+    /* prog_ref_level_present? */
+    if (get_bits1(gb)) {
+        che_drc->prog_ref_level = get_bits(gb, 7);
+        skip_bits1(gb); // prog_ref_level_reserved_bits
+        n++;
+    }
+
+    for (i = 0; i < drc_num_bands; i++) {
+        che_drc->dyn_rng_sgn[i] = get_bits1(gb);
+        che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
+        n++;
+    }
+
+    return n;
+}
+
+/**
+ * Decode extension data (incomplete); reference: table 4.51.
+ *
+ * @param   cnt length of TYPE_FIL syntactic element in bytes
+ *
+ * @return Returns number of bytes consumed
+ */
+static int decode_extension_payload(AACContext *ac, GetBitContext *gb, int cnt,
+                                    ChannelElement *che, enum RawDataBlockType elem_type)
+{
+    int crc_flag = 0;
+    int res = cnt;
+    switch (get_bits(gb, 4)) { // extension type
+    case EXT_SBR_DATA_CRC:
+        crc_flag++;
+    case EXT_SBR_DATA:
+        if (!che) {
+            av_log(ac->avctx, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
+            return res;
+        } else if (!ac->m4ac.sbr) {
+            av_log(ac->avctx, AV_LOG_ERROR, "SBR signaled to be not-present but was found in the bitstream.\n");
+            skip_bits_long(gb, 8 * cnt - 4);
+            return res;
+        } else if (ac->m4ac.sbr == -1 && ac->output_configured == OC_LOCKED) {
+            av_log(ac->avctx, AV_LOG_ERROR, "Implicit SBR was found with a first occurrence after the first frame.\n");
+            skip_bits_long(gb, 8 * cnt - 4);
+            return res;
+        } else if (ac->m4ac.ps == -1 && ac->output_configured < OC_LOCKED && ac->avctx->channels == 1) {
+            ac->m4ac.sbr = 1;
+            ac->m4ac.ps = 1;
+            output_configure(ac, ac->che_pos, ac->che_pos, ac->m4ac.chan_config, ac->output_configured);
+        } else {
+            ac->m4ac.sbr = 1;
+        }
+        res = ff_decode_sbr_extension(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
+        break;
+    case EXT_DYNAMIC_RANGE:
+        res = decode_dynamic_range(&ac->che_drc, gb, cnt);
+        break;
+    case EXT_FILL:
+    case EXT_FILL_DATA:
+    case EXT_DATA_ELEMENT:
+    default:
+        skip_bits_long(gb, 8 * cnt - 4);
+        break;
+    };
+    return res;
+}
+
+/**
+ * Decode Temporal Noise Shaping filter coefficients and apply all-pole filters; reference: 4.6.9.3.
+ *
+ * @param   decode  1 if tool is used normally, 0 if tool is used in LTP.
+ * @param   coef    spectral coefficients
+ */
+static void apply_tns(float coef[1024], TemporalNoiseShaping *tns,
+                      IndividualChannelStream *ics, int decode)
+{
+    const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
+    int w, filt, m, i;
+    int bottom, top, order, start, end, size, inc;
+    float lpc[TNS_MAX_ORDER];
+    float tmp[TNS_MAX_ORDER];
+
+    for (w = 0; w < ics->num_windows; w++) {
+        bottom = ics->num_swb;
+        for (filt = 0; filt < tns->n_filt[w]; filt++) {
+            top    = bottom;
+            bottom = FFMAX(0, top - tns->length[w][filt]);
+            order  = tns->order[w][filt];
+            if (order == 0)
+                continue;
+
+            // tns_decode_coef
+            compute_lpc_coefs(tns->coef[w][filt], order, lpc, 0, 0, 0);
+
+            start = ics->swb_offset[FFMIN(bottom, mmm)];
+            end   = ics->swb_offset[FFMIN(   top, mmm)];
+            if ((size = end - start) <= 0)
+                continue;
+            if (tns->direction[w][filt]) {
+                inc = -1;
+                start = end - 1;
+            } else {
+                inc = 1;
+            }
+            start += w * 128;
+
+            if (decode) {
+                // ar filter
+                for (m = 0; m < size; m++, start += inc)
+                    for (i = 1; i <= FFMIN(m, order); i++)
+                        coef[start] -= coef[start - i * inc] * lpc[i - 1];
+            } else {
+                // ma filter
+                for (m = 0; m < size; m++, start += inc) {
+                    tmp[0] = coef[start];
+                    for (i = 1; i <= FFMIN(m, order); i++)
+                        coef[start] += tmp[i] * lpc[i - 1];
+                    for (i = order; i > 0; i--)
+                        tmp[i] = tmp[i - 1];
+                }
+            }
+        }
+    }
+}
+
+/**
+ *  Apply windowing and MDCT to obtain the spectral
+ *  coefficient from the predicted sample by LTP.
+ */
+static void windowing_and_mdct_ltp(AACContext *ac, float *out,
+                                   float *in, IndividualChannelStream *ics)
+{
+    const float *lwindow      = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
+    const float *swindow      = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
+    const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
+    const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
+
+    if (ics->window_sequence[0] != LONG_STOP_SEQUENCE) {
+        ac->dsp.vector_fmul(in, in, lwindow_prev, 1024);
+    } else {
+        memset(in, 0, 448 * sizeof(float));
+        ac->dsp.vector_fmul(in + 448, in + 448, swindow_prev, 128);
+        memcpy(in + 576, in + 576, 448 * sizeof(float));
+    }
+    if (ics->window_sequence[0] != LONG_START_SEQUENCE) {
+        ac->dsp.vector_fmul_reverse(in + 1024, in + 1024, lwindow, 1024);
+    } else {
+        memcpy(in + 1024, in + 1024, 448 * sizeof(float));
+        ac->dsp.vector_fmul_reverse(in + 1024 + 448, in + 1024 + 448, swindow, 128);
+        memset(in + 1024 + 576, 0, 448 * sizeof(float));
+    }
+    ac->mdct_ltp.mdct_calc(&ac->mdct_ltp, out, in);
+}
+
+/**
+ * Apply the long term prediction
+ */
+static void apply_ltp(AACContext *ac, SingleChannelElement *sce)
+{
+    const LongTermPrediction *ltp = &sce->ics.ltp;
+    const uint16_t *offsets = sce->ics.swb_offset;
+    int i, sfb;
+
+    if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
+        float *predTime = sce->ret;
+        float *predFreq = ac->buf_mdct;
+        int16_t num_samples = 2048;
+
+        if (ltp->lag < 1024)
+            num_samples = ltp->lag + 1024;
+        for (i = 0; i < num_samples; i++)
+            predTime[i] = sce->ltp_state[i + 2048 - ltp->lag] * ltp->coef;
+        memset(&predTime[i], 0, (2048 - i) * sizeof(float));
+
+        windowing_and_mdct_ltp(ac, predFreq, predTime, &sce->ics);
+
+        if (sce->tns.present)
+            apply_tns(predFreq, &sce->tns, &sce->ics, 0);
+
+        for (sfb = 0; sfb < FFMIN(sce->ics.max_sfb, MAX_LTP_LONG_SFB); sfb++)
+            if (ltp->used[sfb])
+                for (i = offsets[sfb]; i < offsets[sfb + 1]; i++)
+                    sce->coeffs[i] += predFreq[i];
+    }
+}
+
+/**
+ * Update the LTP buffer for next frame
+ */
+static void update_ltp(AACContext *ac, SingleChannelElement *sce)
+{
+    IndividualChannelStream *ics = &sce->ics;
+    float *saved     = sce->saved;
+    float *saved_ltp = sce->coeffs;
+    const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
+    const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
+    int i;
+
+    if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
+        memcpy(saved_ltp,       saved, 512 * sizeof(float));
+        memset(saved_ltp + 576, 0,     448 * sizeof(float));
+        ac->dsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960,     &swindow[64],      64);
+        for (i = 0; i < 64; i++)
+            saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
+    } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
+        memcpy(saved_ltp,       ac->buf_mdct + 512, 448 * sizeof(float));
+        memset(saved_ltp + 576, 0,                  448 * sizeof(float));
+        ac->dsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960,     &swindow[64],      64);
+        for (i = 0; i < 64; i++)
+            saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
+    } else { // LONG_STOP or ONLY_LONG
+        ac->dsp.vector_fmul_reverse(saved_ltp,       ac->buf_mdct + 512,     &lwindow[512],     512);
+        for (i = 0; i < 512; i++)
+            saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * lwindow[511 - i];
+    }
+
+    memcpy(sce->ltp_state, &sce->ltp_state[1024], 1024 * sizeof(int16_t));
+    ac->fmt_conv.float_to_int16(&(sce->ltp_state[1024]), sce->ret,  1024);
+    ac->fmt_conv.float_to_int16(&(sce->ltp_state[2048]), saved_ltp, 1024);
+}
+
+/**
+ * Conduct IMDCT and windowing.
+ */
+static void imdct_and_windowing(AACContext *ac, SingleChannelElement *sce)
+{
+    IndividualChannelStream *ics = &sce->ics;
+    float *in    = sce->coeffs;
+    float *out   = sce->ret;
+    float *saved = sce->saved;
+    const float *swindow      = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
+    const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
+    const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
+    float *buf  = ac->buf_mdct;
+    float *temp = ac->temp;
+    int i;
+
+    // imdct
+    if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
+        for (i = 0; i < 1024; i += 128)
+            ac->mdct_small.imdct_half(&ac->mdct_small, buf + i, in + i);
+    } else
+        ac->mdct.imdct_half(&ac->mdct, buf, in);
+
+    /* window overlapping
+     * NOTE: To simplify the overlapping code, all 'meaningless' short to long
+     * and long to short transitions are considered to be short to short
+     * transitions. This leaves just two cases (long to long and short to short)
+     * with a little special sauce for EIGHT_SHORT_SEQUENCE.
+     */
+    if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
+            (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
+        ac->dsp.vector_fmul_window(    out,               saved,            buf,         lwindow_prev, 512);
+    } else {
+        memcpy(                        out,               saved,            448 * sizeof(float));
+
+        if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
+            ac->dsp.vector_fmul_window(out + 448 + 0*128, saved + 448,      buf + 0*128, swindow_prev, 64);
+            ac->dsp.vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow,      64);
+            ac->dsp.vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow,      64);
+            ac->dsp.vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow,      64);
+            ac->dsp.vector_fmul_window(temp,              buf + 3*128 + 64, buf + 4*128, swindow,      64);
+            memcpy(                    out + 448 + 4*128, temp, 64 * sizeof(float));
+        } else {
+            ac->dsp.vector_fmul_window(out + 448,         saved + 448,      buf,         swindow_prev, 64);
+            memcpy(                    out + 576,         buf + 64,         448 * sizeof(float));
+        }
+    }
+
+    // buffer update
+    if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
+        memcpy(                    saved,       temp + 64,         64 * sizeof(float));
+        ac->dsp.vector_fmul_window(saved + 64,  buf + 4*128 + 64, buf + 5*128, swindow, 64);
+        ac->dsp.vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 64);
+        ac->dsp.vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 64);
+        memcpy(                    saved + 448, buf + 7*128 + 64,  64 * sizeof(float));
+    } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
+        memcpy(                    saved,       buf + 512,        448 * sizeof(float));
+        memcpy(                    saved + 448, buf + 7*128 + 64,  64 * sizeof(float));
+    } else { // LONG_STOP or ONLY_LONG
+        memcpy(                    saved,       buf + 512,        512 * sizeof(float));
+    }
+}
+
+/**
+ * Apply dependent channel coupling (applied before IMDCT).
+ *
+ * @param   index   index into coupling gain array
+ */
+static void apply_dependent_coupling(AACContext *ac,
+                                     SingleChannelElement *target,
+                                     ChannelElement *cce, int index)
+{
+    IndividualChannelStream *ics = &cce->ch[0].ics;
+    const uint16_t *offsets = ics->swb_offset;
+    float *dest = target->coeffs;
+    const float *src = cce->ch[0].coeffs;
+    int g, i, group, k, idx = 0;
+    if (ac->m4ac.object_type == AOT_AAC_LTP) {
+        av_log(ac->avctx, AV_LOG_ERROR,
+               "Dependent coupling is not supported together with LTP\n");
+        return;
+    }
+    for (g = 0; g < ics->num_window_groups; g++) {
+        for (i = 0; i < ics->max_sfb; i++, idx++) {
+            if (cce->ch[0].band_type[idx] != ZERO_BT) {
+                const float gain = cce->coup.gain[index][idx];
+                for (group = 0; group < ics->group_len[g]; group++) {
+                    for (k = offsets[i]; k < offsets[i + 1]; k++) {
+                        // XXX dsputil-ize
+                        dest[group * 128 + k] += gain * src[group * 128 + k];
+                    }
+                }
+            }
+        }
+        dest += ics->group_len[g] * 128;
+        src  += ics->group_len[g] * 128;
+    }
+}
+
+/**
+ * Apply independent channel coupling (applied after IMDCT).
+ *
+ * @param   index   index into coupling gain array
+ */
+static void apply_independent_coupling(AACContext *ac,
+                                       SingleChannelElement *target,
+                                       ChannelElement *cce, int index)
+{
+    int i;
+    const float gain = cce->coup.gain[index][0];
+    const float *src = cce->ch[0].ret;
+    float *dest = target->ret;
+    const int len = 1024 << (ac->m4ac.sbr == 1);
+
+    for (i = 0; i < len; i++)
+        dest[i] += gain * src[i];
+}
+
+/**
+ * channel coupling transformation interface
+ *
+ * @param   apply_coupling_method   pointer to (in)dependent coupling function
+ */
+static void apply_channel_coupling(AACContext *ac, ChannelElement *cc,
+                                   enum RawDataBlockType type, int elem_id,
+                                   enum CouplingPoint coupling_point,
+                                   void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
+{
+    int i, c;
+
+    for (i = 0; i < MAX_ELEM_ID; i++) {
+        ChannelElement *cce = ac->che[TYPE_CCE][i];
+        int index = 0;
+
+        if (cce && cce->coup.coupling_point == coupling_point) {
+            ChannelCoupling *coup = &cce->coup;
+
+            for (c = 0; c <= coup->num_coupled; c++) {
+                if (coup->type[c] == type && coup->id_select[c] == elem_id) {
+                    if (coup->ch_select[c] != 1) {
+                        apply_coupling_method(ac, &cc->ch[0], cce, index);
+                        if (coup->ch_select[c] != 0)
+                            index++;
+                    }
+                    if (coup->ch_select[c] != 2)
+                        apply_coupling_method(ac, &cc->ch[1], cce, index++);
+                } else
+                    index += 1 + (coup->ch_select[c] == 3);
+            }
+        }
+    }
+}
+
+/**
+ * Convert spectral data to float samples, applying all supported tools as appropriate.
+ */
+static void spectral_to_sample(AACContext *ac)
+{
+    int i, type;
+    for (type = 3; type >= 0; type--) {
+        for (i = 0; i < MAX_ELEM_ID; i++) {
+            ChannelElement *che = ac->che[type][i];
+            if (che) {
+                if (type <= TYPE_CPE)
+                    apply_channel_coupling(ac, che, type, i, BEFORE_TNS, apply_dependent_coupling);
+                if (ac->m4ac.object_type == AOT_AAC_LTP) {
+                    if (che->ch[0].ics.predictor_present) {
+                        if (che->ch[0].ics.ltp.present)
+                            apply_ltp(ac, &che->ch[0]);
+                        if (che->ch[1].ics.ltp.present && type == TYPE_CPE)
+                            apply_ltp(ac, &che->ch[1]);
+                    }
+                }
+                if (che->ch[0].tns.present)
+                    apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
+                if (che->ch[1].tns.present)
+                    apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
+                if (type <= TYPE_CPE)
+                    apply_channel_coupling(ac, che, type, i, BETWEEN_TNS_AND_IMDCT, apply_dependent_coupling);
+                if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
+                    imdct_and_windowing(ac, &che->ch[0]);
+                    if (ac->m4ac.object_type == AOT_AAC_LTP)
+                        update_ltp(ac, &che->ch[0]);
+                    if (type == TYPE_CPE) {
+                        imdct_and_windowing(ac, &che->ch[1]);
+                        if (ac->m4ac.object_type == AOT_AAC_LTP)
+                            update_ltp(ac, &che->ch[1]);
+                    }
+                    if (ac->m4ac.sbr > 0) {
+                        ff_sbr_apply(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
+                    }
+                }
+                if (type <= TYPE_CCE)
+                    apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, apply_independent_coupling);
+            }
+        }
+    }
+}
+
+static int parse_adts_frame_header(AACContext *ac, GetBitContext *gb)
+{
+    int size;
+    AACADTSHeaderInfo hdr_info;
+
+    size = ff_aac_parse_header(gb, &hdr_info);
+    if (size > 0) {
+        if (ac->output_configured != OC_LOCKED && hdr_info.chan_config) {
+            enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
+            memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
+            ac->m4ac.chan_config = hdr_info.chan_config;
+            if (set_default_channel_config(ac->avctx, new_che_pos, hdr_info.chan_config))
+                return -7;
+            if (output_configure(ac, ac->che_pos, new_che_pos, hdr_info.chan_config, OC_TRIAL_FRAME))
+                return -7;
+        } else if (ac->output_configured != OC_LOCKED) {
+            ac->output_configured = OC_NONE;
+        }
+        if (ac->output_configured != OC_LOCKED) {
+            ac->m4ac.sbr = -1;
+            ac->m4ac.ps  = -1;
+        }
+        ac->m4ac.sample_rate     = hdr_info.sample_rate;
+        ac->m4ac.sampling_index  = hdr_info.sampling_index;
+        ac->m4ac.object_type     = hdr_info.object_type;
+        if (!ac->avctx->sample_rate)
+            ac->avctx->sample_rate = hdr_info.sample_rate;
+        if (hdr_info.num_aac_frames == 1) {
+            if (!hdr_info.crc_absent)
+                skip_bits(gb, 16);
+        } else {
+            av_log_missing_feature(ac->avctx, "More than one AAC RDB per ADTS frame is", 0);
+            return -1;
+        }
+    }
+    return size;
+}
+
+static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
+                                int *data_size, GetBitContext *gb)
+{
+    AACContext *ac = avctx->priv_data;
+    ChannelElement *che = NULL, *che_prev = NULL;
+    enum RawDataBlockType elem_type, elem_type_prev = TYPE_END;
+    int err, elem_id, data_size_tmp;
+    int samples = 0, multiplier;
+
+    if (show_bits(gb, 12) == 0xfff) {
+        if (parse_adts_frame_header(ac, gb) < 0) {
+            av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
+            return -1;
+        }
+        if (ac->m4ac.sampling_index > 12) {
+            av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->m4ac.sampling_index);
+            return -1;
+        }
+    }
+
+    ac->tags_mapped = 0;
+    // parse
+    while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
+        elem_id = get_bits(gb, 4);
+
+        if (elem_type < TYPE_DSE) {
+            if (!(che=get_che(ac, elem_type, elem_id))) {
+                av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",
+                       elem_type, elem_id);
+                return -1;
+            }
+            samples = 1024;
+        }
+
+        switch (elem_type) {
+
+        case TYPE_SCE:
+            err = decode_ics(ac, &che->ch[0], gb, 0, 0);
+            break;
+
+        case TYPE_CPE:
+            err = decode_cpe(ac, gb, che);
+            break;
+
+        case TYPE_CCE:
+            err = decode_cce(ac, gb, che);
+            break;
+
+        case TYPE_LFE:
+            err = decode_ics(ac, &che->ch[0], gb, 0, 0);
+            break;
+
+        case TYPE_DSE:
+            err = skip_data_stream_element(ac, gb);
+            break;
+
+        case TYPE_PCE: {
+            enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
+            memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
+            if ((err = decode_pce(avctx, &ac->m4ac, new_che_pos, gb)))
+                break;
+            if (ac->output_configured > OC_TRIAL_PCE)
+                av_log(avctx, AV_LOG_ERROR,
+                       "Not evaluating a further program_config_element as this construct is dubious at best.\n");
+            else
+                err = output_configure(ac, ac->che_pos, new_che_pos, 0, OC_TRIAL_PCE);
+            break;
+        }
+
+        case TYPE_FIL:
+            if (elem_id == 15)
+                elem_id += get_bits(gb, 8) - 1;
+            if (get_bits_left(gb) < 8 * elem_id) {
+                    av_log(avctx, AV_LOG_ERROR, overread_err);
+                    return -1;
+            }
+            while (elem_id > 0)
+                elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, elem_type_prev);
+            err = 0; /* FIXME */
+            break;
+
+        default:
+            err = -1; /* should not happen, but keeps compiler happy */
+            break;
+        }
+
+        che_prev       = che;
+        elem_type_prev = elem_type;
+
+        if (err)
+            return err;
+
+        if (get_bits_left(gb) < 3) {
+            av_log(avctx, AV_LOG_ERROR, overread_err);
+            return -1;
+        }
+    }
+
+    spectral_to_sample(ac);
+
+    multiplier = (ac->m4ac.sbr == 1) ? ac->m4ac.ext_sample_rate > ac->m4ac.sample_rate : 0;
+    samples <<= multiplier;
+    if (ac->output_configured < OC_LOCKED) {
+        avctx->sample_rate = ac->m4ac.sample_rate << multiplier;
+        avctx->frame_size = samples;
+    }
+
+    data_size_tmp = samples * avctx->channels * sizeof(int16_t);
+    if (*data_size < data_size_tmp) {
+        av_log(avctx, AV_LOG_ERROR,
+               "Output buffer too small (%d) or trying to output too many samples (%d) for this frame.\n",
+               *data_size, data_size_tmp);
+        return -1;
+    }
+    *data_size = data_size_tmp;
+
+    if (samples)
+        ac->fmt_conv.float_to_int16_interleave(data, (const float **)ac->output_data, samples, avctx->channels);
+
+    if (ac->output_configured)
+        ac->output_configured = OC_LOCKED;
+
+    return 0;
+}
+
+static int aac_decode_frame(AVCodecContext *avctx, void *data,
+                            int *data_size, AVPacket *avpkt)
+{
+    const uint8_t *buf = avpkt->data;
+    int buf_size = avpkt->size;
+    GetBitContext gb;
+    int buf_consumed;
+    int buf_offset;
+    int err;
+
+    init_get_bits(&gb, buf, buf_size * 8);
+
+    if ((err = aac_decode_frame_int(avctx, data, data_size, &gb)) < 0)
+        return err;
+
+    buf_consumed = (get_bits_count(&gb) + 7) >> 3;
+    for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
+        if (buf[buf_offset])
+            break;
+
+    return buf_size > buf_offset ? buf_consumed : buf_size;
+}
+
+static av_cold int aac_decode_close(AVCodecContext *avctx)
+{
+    AACContext *ac = avctx->priv_data;
+    int i, type;
+
+    for (i = 0; i < MAX_ELEM_ID; i++) {
+        for (type = 0; type < 4; type++) {
+            if (ac->che[type][i])
+                ff_aac_sbr_ctx_close(&ac->che[type][i]->sbr);
+            av_freep(&ac->che[type][i]);
+        }
+    }
+
+    ff_mdct_end(&ac->mdct);
+    ff_mdct_end(&ac->mdct_small);
+    ff_mdct_end(&ac->mdct_ltp);
+    return 0;
+}
+
+
+#define LOAS_SYNC_WORD   0x2b7       ///< 11 bits LOAS sync word
+
+struct LATMContext {
+    AACContext      aac_ctx;             ///< containing AACContext
+    int             initialized;         ///< initilized after a valid extradata was seen
+
+    // parser data
+    int             audio_mux_version_A; ///< LATM syntax version
+    int             frame_length_type;   ///< 0/1 variable/fixed frame length
+    int             frame_length;        ///< frame length for fixed frame length
+};
+
+static inline uint32_t latm_get_value(GetBitContext *b)
+{
+    int length = get_bits(b, 2);
+
+    return get_bits_long(b, (length+1)*8);
+}
+
+static int latm_decode_audio_specific_config(struct LATMContext *latmctx,
+                                             GetBitContext *gb)
+{
+    AVCodecContext *avctx = latmctx->aac_ctx.avctx;
+    MPEG4AudioConfig m4ac;
+    int  config_start_bit = get_bits_count(gb);
+    int     bits_consumed, esize;
+
+    if (config_start_bit % 8) {
+        av_log_missing_feature(latmctx->aac_ctx.avctx, "audio specific "
+                               "config not byte aligned.\n", 1);
+        return AVERROR_INVALIDDATA;
+    } else {
+        bits_consumed =
+            decode_audio_specific_config(NULL, avctx, &m4ac,
+                                         gb->buffer + (config_start_bit / 8),
+                                         get_bits_left(gb) / 8);
+
+        if (bits_consumed < 0)
+            return AVERROR_INVALIDDATA;
+
+        esize = (bits_consumed+7) / 8;
+
+        if (avctx->extradata_size <= esize) {
+            av_free(avctx->extradata);
+            avctx->extradata = av_malloc(esize + FF_INPUT_BUFFER_PADDING_SIZE);
+            if (!avctx->extradata)
+                return AVERROR(ENOMEM);
+        }
+
+        avctx->extradata_size = esize;
+        memcpy(avctx->extradata, gb->buffer + (config_start_bit/8), esize);
+        memset(avctx->extradata+esize, 0, FF_INPUT_BUFFER_PADDING_SIZE);
+
+        skip_bits_long(gb, bits_consumed);
+    }
+
+    return bits_consumed;
+}
+
+static int read_stream_mux_config(struct LATMContext *latmctx,
+                                  GetBitContext *gb)
+{
+    int ret, audio_mux_version = get_bits(gb, 1);
+
+    latmctx->audio_mux_version_A = 0;
+    if (audio_mux_version)
+        latmctx->audio_mux_version_A = get_bits(gb, 1);
+
+    if (!latmctx->audio_mux_version_A) {
+
+        if (audio_mux_version)
+            latm_get_value(gb);                 // taraFullness
+
+        skip_bits(gb, 1);                       // allStreamSameTimeFraming
+        skip_bits(gb, 6);                       // numSubFrames
+        // numPrograms
+        if (get_bits(gb, 4)) {                  // numPrograms
+            av_log_missing_feature(latmctx->aac_ctx.avctx,
+                                   "multiple programs are not supported\n", 1);
+            return AVERROR_PATCHWELCOME;
+        }
+
+        // for each program (which there is only on in DVB)
+
+        // for each layer (which there is only on in DVB)
+        if (get_bits(gb, 3)) {                   // numLayer
+            av_log_missing_feature(latmctx->aac_ctx.avctx,
+                                   "multiple layers are not supported\n", 1);
+            return AVERROR_PATCHWELCOME;
+        }
+
+        // for all but first stream: use_same_config = get_bits(gb, 1);
+        if (!audio_mux_version) {
+            if ((ret = latm_decode_audio_specific_config(latmctx, gb)) < 0)
+                return ret;
+        } else {
+            int ascLen = latm_get_value(gb);
+            if ((ret = latm_decode_audio_specific_config(latmctx, gb)) < 0)
+                return ret;
+            ascLen -= ret;
+            skip_bits_long(gb, ascLen);
+        }
+
+        latmctx->frame_length_type = get_bits(gb, 3);
+        switch (latmctx->frame_length_type) {
+        case 0:
+            skip_bits(gb, 8);       // latmBufferFullness
+            break;
+        case 1:
+            latmctx->frame_length = get_bits(gb, 9);
+            break;
+        case 3:
+        case 4:
+        case 5:
+            skip_bits(gb, 6);       // CELP frame length table index
+            break;
+        case 6:
+        case 7:
+            skip_bits(gb, 1);       // HVXC frame length table index
+            break;
+        }
+
+        if (get_bits(gb, 1)) {                  // other data
+            if (audio_mux_version) {
+                latm_get_value(gb);             // other_data_bits
+            } else {
+                int esc;
+                do {
+                    esc = get_bits(gb, 1);
+                    skip_bits(gb, 8);
+                } while (esc);
+            }
+        }
+
+        if (get_bits(gb, 1))                     // crc present
+            skip_bits(gb, 8);                    // config_crc
+    }
+
+    return 0;
+}
+
+static int read_payload_length_info(struct LATMContext *ctx, GetBitContext *gb)
+{
+    uint8_t tmp;
+
+    if (ctx->frame_length_type == 0) {
+        int mux_slot_length = 0;
+        do {
+            tmp = get_bits(gb, 8);
+            mux_slot_length += tmp;
+        } while (tmp == 255);
+        return mux_slot_length;
+    } else if (ctx->frame_length_type == 1) {
+        return ctx->frame_length;
+    } else if (ctx->frame_length_type == 3 ||
+               ctx->frame_length_type == 5 ||
+               ctx->frame_length_type == 7) {
+        skip_bits(gb, 2);          // mux_slot_length_coded
+    }
+    return 0;
+}
+
+static int read_audio_mux_element(struct LATMContext *latmctx,
+                                  GetBitContext *gb)
+{
+    int err;
+    uint8_t use_same_mux = get_bits(gb, 1);
+    if (!use_same_mux) {
+        if ((err = read_stream_mux_config(latmctx, gb)) < 0)
+            return err;
+    } else if (!latmctx->aac_ctx.avctx->extradata) {
+        av_log(latmctx->aac_ctx.avctx, AV_LOG_DEBUG,
+               "no decoder config found\n");
+        return AVERROR(EAGAIN);
+    }
+    if (latmctx->audio_mux_version_A == 0) {
+        int mux_slot_length_bytes = read_payload_length_info(latmctx, gb);
+        if (mux_slot_length_bytes * 8 > get_bits_left(gb)) {
+            av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR, "incomplete frame\n");
+            return AVERROR_INVALIDDATA;
+        } else if (mux_slot_length_bytes * 8 + 256 < get_bits_left(gb)) {
+            av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
+                   "frame length mismatch %d << %d\n",
+                   mux_slot_length_bytes * 8, get_bits_left(gb));
+            return AVERROR_INVALIDDATA;
+        }
+    }
+    return 0;
+}
+
+
+static int latm_decode_frame(AVCodecContext *avctx, void *out, int *out_size,
+                             AVPacket *avpkt)
+{
+    struct LATMContext *latmctx = avctx->priv_data;
+    int                 muxlength, err;
+    GetBitContext       gb;
+
+    if (avpkt->size == 0)
+        return 0;
+
+    init_get_bits(&gb, avpkt->data, avpkt->size * 8);
+
+    // check for LOAS sync word
+    if (get_bits(&gb, 11) != LOAS_SYNC_WORD)
+        return AVERROR_INVALIDDATA;
+
+    muxlength = get_bits(&gb, 13) + 3;
+    // not enough data, the parser should have sorted this
+    if (muxlength > avpkt->size)
+        return AVERROR_INVALIDDATA;
+
+    if ((err = read_audio_mux_element(latmctx, &gb)) < 0)
+        return err;
+
+    if (!latmctx->initialized) {
+        if (!avctx->extradata) {
+            *out_size = 0;
+            return avpkt->size;
+        } else {
+            if ((err = aac_decode_init(avctx)) < 0)
+                return err;
+            latmctx->initialized = 1;
+        }
+    }
+
+    if (show_bits(&gb, 12) == 0xfff) {
+        av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
+               "ADTS header detected, probably as result of configuration "
+               "misparsing\n");
+        return AVERROR_INVALIDDATA;
+    }
+
+    if ((err = aac_decode_frame_int(avctx, out, out_size, &gb)) < 0)
+        return err;
+
+    return muxlength;
+}
+
+av_cold static int latm_decode_init(AVCodecContext *avctx)
+{
+    struct LATMContext *latmctx = avctx->priv_data;
+    int ret;
+
+    ret = aac_decode_init(avctx);
+
+    if (avctx->extradata_size > 0) {
+        latmctx->initialized = !ret;
+    } else {
+        latmctx->initialized = 0;
+    }
+
+    return ret;
+}
+
+
+AVCodec ff_aac_decoder = {
+    "aac",
+    AVMEDIA_TYPE_AUDIO,
+    CODEC_ID_AAC,
+    sizeof(AACContext),
+    aac_decode_init,
+    NULL,
+    aac_decode_close,
+    aac_decode_frame,
+    .long_name = NULL_IF_CONFIG_SMALL("Advanced Audio Coding"),
+    .sample_fmts = (const enum AVSampleFormat[]) {
+        AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE
+    },
+    .channel_layouts = aac_channel_layout,
+};
+
+/*
+    Note: This decoder filter is intended to decode LATM streams transferred
+    in MPEG transport streams which only contain one program.
+    To do a more complex LATM demuxing a separate LATM demuxer should be used.
+*/
+AVCodec ff_aac_latm_decoder = {
+    .name = "aac_latm",
+    .type = AVMEDIA_TYPE_AUDIO,
+    .id   = CODEC_ID_AAC_LATM,
+    .priv_data_size = sizeof(struct LATMContext),
+    .init   = latm_decode_init,
+    .close  = aac_decode_close,
+    .decode = latm_decode_frame,
+    .long_name = NULL_IF_CONFIG_SMALL("AAC LATM (Advanced Audio Codec LATM syntax)"),
+    .sample_fmts = (const enum AVSampleFormat[]) {
+        AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE
+    },
+    .channel_layouts = aac_channel_layout,
+};
diff --git a/libavcodec/aacdectab.h b/libavcodec/aacdectab.h
index b74f100..64c2a1c 100644
--- a/libavcodec/aacdectab.h
+++ b/libavcodec/aacdectab.h
@@ -3,20 +3,20 @@
  * Copyright (c) 2005-2006 Oded Shimon ( ods15 ods15 dyndns org )
  * Copyright (c) 2006-2007 Maxim Gavrilov ( maxim.gavrilov gmail com )
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -30,10 +30,19 @@
 #ifndef AVCODEC_AACDECTAB_H
 #define AVCODEC_AACDECTAB_H
 
+#include "libavutil/audioconvert.h"
 #include "aac.h"
 
 #include <stdint.h>
 
+/* @name ltp_coef
+ * Table of the LTP coefficient (multiplied by 2)
+ */
+static const float ltp_coef[8] = {
+     1.141658,    1.393232,    1.626008,    1.822608,
+     1.969800,    2.135788,    2.2389202,   2.739066,
+};
+
 /* @name tns_tmp2_map
  * Tables of the tmp2[] arrays of LPC coefficients used for TNS.
  * The suffix _M_N[] indicate the values of coef_compress and coef_res
@@ -82,13 +91,13 @@ static const uint8_t aac_channel_layout_map[7][5][2] = {
 };
 
 static const int64_t aac_channel_layout[8] = {
-    CH_LAYOUT_MONO,
-    CH_LAYOUT_STEREO,
-    CH_LAYOUT_SURROUND,
-    CH_LAYOUT_4POINT0,
-    CH_LAYOUT_5POINT0_BACK,
-    CH_LAYOUT_5POINT1_BACK,
-    CH_LAYOUT_7POINT1_WIDE,
+    AV_CH_LAYOUT_MONO,
+    AV_CH_LAYOUT_STEREO,
+    AV_CH_LAYOUT_SURROUND,
+    AV_CH_LAYOUT_4POINT0,
+    AV_CH_LAYOUT_5POINT0_BACK,
+    AV_CH_LAYOUT_5POINT1_BACK,
+    AV_CH_LAYOUT_7POINT1_WIDE,
     0,
 };
 
diff --git a/libavcodec/aacenc.c b/libavcodec/aacenc.c
index 90dff15..d4b6112 100644
--- a/libavcodec/aacenc.c
+++ b/libavcodec/aacenc.c
@@ -2,20 +2,20 @@
  * AAC encoder
  * Copyright (C) 2008 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -34,6 +34,8 @@
 #include "put_bits.h"
 #include "dsputil.h"
 #include "mpeg4audio.h"
+#include "kbdwin.h"
+#include "sinewin.h"
 
 #include "aac.h"
 #include "aactab.h"
@@ -41,6 +43,8 @@
 
 #include "psymodel.h"
 
+#define AAC_MAX_CHANNELS 6
+
 static const uint8_t swb_size_1024_96[] = {
     4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 8, 8, 8, 8, 8,
     12, 12, 12, 12, 12, 16, 16, 24, 28, 36, 44,
@@ -147,6 +151,11 @@ static void put_audio_specific_config(AVCodecContext *avctx)
     put_bits(&pb, 1, 0); //frame length - 1024 samples
     put_bits(&pb, 1, 0); //does not depend on core coder
     put_bits(&pb, 1, 0); //is not extension
+
+    //Explicitly Mark SBR absent
+    put_bits(&pb, 11, 0x2b7); //sync extension
+    put_bits(&pb, 5,  AOT_SBR);
+    put_bits(&pb, 1,  0);
     flush_put_bits(&pb);
 }
 
@@ -166,7 +175,7 @@ static av_cold int aac_encode_init(AVCodecContext *avctx)
         av_log(avctx, AV_LOG_ERROR, "Unsupported sample rate %d\n", avctx->sample_rate);
         return -1;
     }
-    if (avctx->channels > 6) {
+    if (avctx->channels > AAC_MAX_CHANNELS) {
         av_log(avctx, AV_LOG_ERROR, "Unsupported number of channels: %d\n", avctx->channels);
         return -1;
     }
@@ -191,8 +200,8 @@ static av_cold int aac_encode_init(AVCodecContext *avctx)
 
     s->samples            = av_malloc(2 * 1024 * avctx->channels * sizeof(s->samples[0]));
     s->cpe                = av_mallocz(sizeof(ChannelElement) * aac_chan_configs[avctx->channels-1][0]);
-    avctx->extradata      = av_malloc(2);
-    avctx->extradata_size = 2;
+    avctx->extradata      = av_mallocz(5 + FF_INPUT_BUFFER_PADDING_SIZE);
+    avctx->extradata_size = 5;
     put_audio_specific_config(avctx);
 
     sizes[0]   = swb_size_1024[i];
@@ -201,70 +210,61 @@ static av_cold int aac_encode_init(AVCodecContext *avctx)
     lengths[1] = ff_aac_num_swb_128[i];
     ff_psy_init(&s->psy, avctx, 2, sizes, lengths);
     s->psypp = ff_psy_preprocess_init(avctx);
-    s->coder = &ff_aac_coders[0];
+    s->coder = &ff_aac_coders[2];
 
     s->lambda = avctx->global_quality ? avctx->global_quality : 120;
-#if !CONFIG_HARDCODED_TABLES
-    for (i = 0; i < 428; i++)
-        ff_aac_pow2sf_tab[i] = pow(2, (i - 200)/4.);
-#endif /* CONFIG_HARDCODED_TABLES */
 
-    if (avctx->channels > 5)
-        av_log(avctx, AV_LOG_ERROR, "This encoder does not yet enforce the restrictions on LFEs. "
-               "The output will most likely be an illegal bitstream.\n");
+    ff_aac_tableinit();
 
     return 0;
 }
 
 static void apply_window_and_mdct(AVCodecContext *avctx, AACEncContext *s,
-                                  SingleChannelElement *sce, short *audio, int channel)
+                                  SingleChannelElement *sce, short *audio)
 {
-    int i, j, k;
+    int i, k;
+    const int chans = avctx->channels;
     const float * lwindow = sce->ics.use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
     const float * swindow = sce->ics.use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
     const float * pwindow = sce->ics.use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
+    float *output = sce->ret;
 
     if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
-        memcpy(s->output, sce->saved, sizeof(float)*1024);
+        memcpy(output, sce->saved, sizeof(float)*1024);
         if (sce->ics.window_sequence[0] == LONG_STOP_SEQUENCE) {
-            memset(s->output, 0, sizeof(s->output[0]) * 448);
+            memset(output, 0, sizeof(output[0]) * 448);
             for (i = 448; i < 576; i++)
-                s->output[i] = sce->saved[i] * pwindow[i - 448];
+                output[i] = sce->saved[i] * pwindow[i - 448];
             for (i = 576; i < 704; i++)
-                s->output[i] = sce->saved[i];
+                output[i] = sce->saved[i];
         }
         if (sce->ics.window_sequence[0] != LONG_START_SEQUENCE) {
-            j = channel;
-            for (i = 0; i < 1024; i++, j += avctx->channels) {
-                s->output[i+1024]         = audio[j] * lwindow[1024 - i - 1];
-                sce->saved[i] = audio[j] * lwindow[i];
+            for (i = 0; i < 1024; i++) {
+                output[i+1024]         = audio[i * chans] * lwindow[1024 - i - 1];
+                sce->saved[i] = audio[i * chans] * lwindow[i];
             }
         } else {
-            j = channel;
-            for (i = 0; i < 448; i++, j += avctx->channels)
-                s->output[i+1024]         = audio[j];
-            for (i = 448; i < 576; i++, j += avctx->channels)
-                s->output[i+1024]         = audio[j] * swindow[576 - i - 1];
-            memset(s->output+1024+576, 0, sizeof(s->output[0]) * 448);
-            j = channel;
-            for (i = 0; i < 1024; i++, j += avctx->channels)
-                sce->saved[i] = audio[j];
+            for (i = 0; i < 448; i++)
+                output[i+1024]         = audio[i * chans];
+            for (; i < 576; i++)
+                output[i+1024]         = audio[i * chans] * swindow[576 - i - 1];
+            memset(output+1024+576, 0, sizeof(output[0]) * 448);
+            for (i = 0; i < 1024; i++)
+                sce->saved[i] = audio[i * chans];
         }
-        ff_mdct_calc(&s->mdct1024, sce->coeffs, s->output);
+        s->mdct1024.mdct_calc(&s->mdct1024, sce->coeffs, output);
     } else {
-        j = channel;
         for (k = 0; k < 1024; k += 128) {
             for (i = 448 + k; i < 448 + k + 256; i++)
-                s->output[i - 448 - k] = (i < 1024)
+                output[i - 448 - k] = (i < 1024)
                                          ? sce->saved[i]
-                                         : audio[channel + (i-1024)*avctx->channels];
-            s->dsp.vector_fmul        (s->output,     k ?  swindow : pwindow, 128);
-            s->dsp.vector_fmul_reverse(s->output+128, s->output+128, swindow, 128);
-            ff_mdct_calc(&s->mdct128, sce->coeffs + k, s->output);
+                                         : audio[(i-1024)*chans];
+            s->dsp.vector_fmul        (output,     output, k ?  swindow : pwindow, 128);
+            s->dsp.vector_fmul_reverse(output+128, output+128, swindow, 128);
+            s->mdct128.mdct_calc(&s->mdct128, sce->coeffs + k, output);
         }
-        j = channel;
-        for (i = 0; i < 1024; i++, j += avctx->channels)
-            sce->saved[i] = audio[j];
+        for (i = 0; i < 1024; i++)
+            sce->saved[i] = audio[i * chans];
     }
 }
 
@@ -310,7 +310,7 @@ static void encode_ms_info(PutBitContext *pb, ChannelElement *cpe)
 static void adjust_frame_information(AACEncContext *apc, ChannelElement *cpe, int chans)
 {
     int i, w, w2, g, ch;
-    int start, sum, maxsfb, cmaxsfb;
+    int start, maxsfb, cmaxsfb;
 
     for (ch = 0; ch < chans; ch++) {
         IndividualChannelStream *ics = &cpe->ch[ch].ics;
@@ -319,9 +319,8 @@ static void adjust_frame_information(AACEncContext *apc, ChannelElement *cpe, in
         cpe->ch[ch].pulse.num_pulse = 0;
         for (w = 0; w < ics->num_windows*16; w += 16) {
             for (g = 0; g < ics->num_swb; g++) {
-                sum = 0;
                 //apply M/S
-                if (!ch && cpe->ms_mask[w + g]) {
+                if (cpe->common_window && !ch && cpe->ms_mask[w + g]) {
                     for (i = 0; i < ics->swb_sizes[g]; i++) {
                         cpe->ch[0].coeffs[start+i] = (cpe->ch[0].coeffs[start+i] + cpe->ch[1].coeffs[start+i]) / 2.0;
                         cpe->ch[1].coeffs[start+i] =  cpe->ch[0].coeffs[start+i] - cpe->ch[1].coeffs[start+i];
@@ -493,7 +492,7 @@ static int aac_encode_frame(AVCodecContext *avctx,
     int i, j, chans, tag, start_ch;
     const uint8_t *chan_map = aac_chan_configs[avctx->channels-1];
     int chan_el_counter[4];
-    FFPsyWindowInfo windows[avctx->channels];
+    FFPsyWindowInfo windows[AAC_MAX_CHANNELS];
 
     if (s->last_frame)
         return 0;
@@ -525,26 +524,34 @@ static int aac_encode_frame(AVCodecContext *avctx,
         tag      = chan_map[i+1];
         chans    = tag == TYPE_CPE ? 2 : 1;
         cpe      = &s->cpe[i];
-        samples2 = samples + start_ch;
-        la       = samples2 + 1024 * avctx->channels + start_ch;
-        if (!data)
-            la = NULL;
         for (j = 0; j < chans; j++) {
             IndividualChannelStream *ics = &cpe->ch[j].ics;
             int k;
-            wi[j] = ff_psy_suggest_window(&s->psy, samples2, la, start_ch + j, ics->window_sequence[0]);
+            int cur_channel = start_ch + j;
+            samples2 = samples + cur_channel;
+            la       = samples2 + (448+64) * avctx->channels;
+            if (!data)
+                la = NULL;
+            if (tag == TYPE_LFE) {
+                wi[j].window_type[0] = ONLY_LONG_SEQUENCE;
+                wi[j].window_shape   = 0;
+                wi[j].num_windows    = 1;
+                wi[j].grouping[0]    = 1;
+            } else {
+                wi[j] = ff_psy_suggest_window(&s->psy, samples2, la, cur_channel,
+                                              ics->window_sequence[0]);
+            }
             ics->window_sequence[1] = ics->window_sequence[0];
             ics->window_sequence[0] = wi[j].window_type[0];
             ics->use_kb_window[1]   = ics->use_kb_window[0];
             ics->use_kb_window[0]   = wi[j].window_shape;
             ics->num_windows        = wi[j].num_windows;
             ics->swb_sizes          = s->psy.bands    [ics->num_windows == 8];
-            ics->num_swb            = s->psy.num_bands[ics->num_windows == 8];
+            ics->num_swb            = tag == TYPE_LFE ? 12 : s->psy.num_bands[ics->num_windows == 8];
             for (k = 0; k < ics->num_windows; k++)
                 ics->group_len[k] = wi[j].grouping[k];
 
-            s->cur_channel = start_ch + j;
-            apply_window_and_mdct(avctx, s, &cpe->ch[j], samples2, j);
+            apply_window_and_mdct(avctx, s, &cpe->ch[j], samples2);
         }
         start_ch += chans;
     }
@@ -560,8 +567,11 @@ static int aac_encode_frame(AVCodecContext *avctx,
             tag      = chan_map[i+1];
             chans    = tag == TYPE_CPE ? 2 : 1;
             cpe      = &s->cpe[i];
+            put_bits(&s->pb, 3, tag);
+            put_bits(&s->pb, 4, chan_el_counter[tag]++);
             for (j = 0; j < chans; j++) {
                 s->cur_channel = start_ch + j;
+                ff_psy_set_band_info(&s->psy, s->cur_channel, cpe->ch[j].coeffs, &wi[j]);
                 s->coder->search_for_quantizers(avctx, s, &cpe->ch[j], s->lambda);
             }
             cpe->common_window = 0;
@@ -581,8 +591,6 @@ static int aac_encode_frame(AVCodecContext *avctx,
             if (cpe->common_window && s->coder->search_for_ms)
                 s->coder->search_for_ms(s, cpe, s->lambda);
             adjust_frame_information(s, cpe, chans);
-            put_bits(&s->pb, 3, tag);
-            put_bits(&s->pb, 4, chan_el_counter[tag]++);
             if (chans == 2) {
                 put_bits(&s->pb, 1, cpe->common_window);
                 if (cpe->common_window) {
@@ -592,7 +600,6 @@ static int aac_encode_frame(AVCodecContext *avctx,
             }
             for (j = 0; j < chans; j++) {
                 s->cur_channel = start_ch + j;
-                ff_psy_set_band_info(&s->psy, s->cur_channel, cpe->ch[j].coeffs, &wi[j]);
                 encode_individual_channel(avctx, s, &cpe->ch[j], cpe->common_window);
             }
             start_ch += chans;
@@ -637,7 +644,7 @@ static av_cold int aac_encode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec aac_encoder = {
+AVCodec ff_aac_encoder = {
     "aac",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_AAC,
@@ -646,6 +653,6 @@ AVCodec aac_encoder = {
     aac_encode_frame,
     aac_encode_end,
     .capabilities = CODEC_CAP_SMALL_LAST_FRAME | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
-    .sample_fmts = (const enum SampleFormat[]){SAMPLE_FMT_S16,SAMPLE_FMT_NONE},
+    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
     .long_name = NULL_IF_CONFIG_SMALL("Advanced Audio Coding"),
 };
diff --git a/libavcodec/aacenc.h b/libavcodec/aacenc.h
index e99be98..3d584d2 100644
--- a/libavcodec/aacenc.h
+++ b/libavcodec/aacenc.h
@@ -2,20 +2,20 @@
  * AAC encoder
  * Copyright (C) 2008 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -52,8 +52,7 @@ typedef struct AACEncContext {
     FFTContext mdct1024;                         ///< long (1024 samples) frame transform context
     FFTContext mdct128;                          ///< short (128 samples) frame transform context
     DSPContext  dsp;
-    DECLARE_ALIGNED(16, FFTSample, output)[2048]; ///< temporary buffer for MDCT input coefficients
-    int16_t* samples;                            ///< saved preprocessed input
+    int16_t *samples;                            ///< saved preprocessed input
 
     int samplerate_index;                        ///< MPEG-4 samplerate index
 
@@ -64,7 +63,7 @@ typedef struct AACEncContext {
     int cur_channel;
     int last_frame;
     float lambda;
-    DECLARE_ALIGNED(16, int,   qcoefs)[96][2];   ///< quantized coefficients
+    DECLARE_ALIGNED(16, int,   qcoefs)[96];      ///< quantized coefficients
     DECLARE_ALIGNED(16, float, scoefs)[1024];    ///< scaled coefficients
 } AACEncContext;
 
diff --git a/libavcodec/aacps.c b/libavcodec/aacps.c
new file mode 100644
index 0000000..724c132
--- /dev/null
+++ b/libavcodec/aacps.c
@@ -0,0 +1,1037 @@
+/*
+ * MPEG-4 Parametric Stereo decoding functions
+ * Copyright (c) 2010 Alex Converse <alex.converse at gmail.com>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <stdint.h>
+#include "libavutil/common.h"
+#include "libavutil/mathematics.h"
+#include "avcodec.h"
+#include "get_bits.h"
+#include "aacps.h"
+#include "aacps_tablegen.h"
+#include "aacpsdata.c"
+
+#define PS_BASELINE 0  //< Operate in Baseline PS mode
+                       //< Baseline implies 10 or 20 stereo bands,
+                       //< mixing mode A, and no ipd/opd
+
+#define numQMFSlots 32 //numTimeSlots * RATE
+
+static const int8_t num_env_tab[2][4] = {
+    { 0, 1, 2, 4, },
+    { 1, 2, 3, 4, },
+};
+
+static const int8_t nr_iidicc_par_tab[] = {
+    10, 20, 34, 10, 20, 34,
+};
+
+static const int8_t nr_iidopd_par_tab[] = {
+     5, 11, 17,  5, 11, 17,
+};
+
+enum {
+    huff_iid_df1,
+    huff_iid_dt1,
+    huff_iid_df0,
+    huff_iid_dt0,
+    huff_icc_df,
+    huff_icc_dt,
+    huff_ipd_df,
+    huff_ipd_dt,
+    huff_opd_df,
+    huff_opd_dt,
+};
+
+static const int huff_iid[] = {
+    huff_iid_df0,
+    huff_iid_df1,
+    huff_iid_dt0,
+    huff_iid_dt1,
+};
+
+static VLC vlc_ps[10];
+
+/**
+ * Read Inter-channel Intensity Difference/Inter-Channel Coherence/
+ * Inter-channel Phase Difference/Overall Phase Difference parameters from the
+ * bitstream.
+ *
+ * @param avctx contains the current codec context
+ * @param gb    pointer to the input bitstream
+ * @param ps    pointer to the Parametric Stereo context
+ * @param par   pointer to the parameter to be read
+ * @param e     envelope to decode
+ * @param dt    1: time delta-coded, 0: frequency delta-coded
+ */
+#define READ_PAR_DATA(PAR, OFFSET, MASK, ERR_CONDITION) \
+static int read_ ## PAR ## _data(AVCodecContext *avctx, GetBitContext *gb, PSContext *ps, \
+                        int8_t (*PAR)[PS_MAX_NR_IIDICC], int table_idx, int e, int dt) \
+{ \
+    int b, num = ps->nr_ ## PAR ## _par; \
+    VLC_TYPE (*vlc_table)[2] = vlc_ps[table_idx].table; \
+    if (dt) { \
+        int e_prev = e ? e - 1 : ps->num_env_old - 1; \
+        e_prev = FFMAX(e_prev, 0); \
+        for (b = 0; b < num; b++) { \
+            int val = PAR[e_prev][b] + get_vlc2(gb, vlc_table, 9, 3) - OFFSET; \
+            if (MASK) val &= MASK; \
+            PAR[e][b] = val; \
+            if (ERR_CONDITION) \
+                goto err; \
+        } \
+    } else { \
+        int val = 0; \
+        for (b = 0; b < num; b++) { \
+            val += get_vlc2(gb, vlc_table, 9, 3) - OFFSET; \
+            if (MASK) val &= MASK; \
+            PAR[e][b] = val; \
+            if (ERR_CONDITION) \
+                goto err; \
+        } \
+    } \
+    return 0; \
+err: \
+    av_log(avctx, AV_LOG_ERROR, "illegal "#PAR"\n"); \
+    return -1; \
+}
+
+READ_PAR_DATA(iid,    huff_offset[table_idx],    0, FFABS(ps->iid_par[e][b]) > 7 + 8 * ps->iid_quant)
+READ_PAR_DATA(icc,    huff_offset[table_idx],    0, ps->icc_par[e][b] > 7U)
+READ_PAR_DATA(ipdopd,                      0, 0x07, 0)
+
+static int ps_read_extension_data(GetBitContext *gb, PSContext *ps, int ps_extension_id)
+{
+    int e;
+    int count = get_bits_count(gb);
+
+    if (ps_extension_id)
+        return 0;
+
+    ps->enable_ipdopd = get_bits1(gb);
+    if (ps->enable_ipdopd) {
+        for (e = 0; e < ps->num_env; e++) {
+            int dt = get_bits1(gb);
+            read_ipdopd_data(NULL, gb, ps, ps->ipd_par, dt ? huff_ipd_dt : huff_ipd_df, e, dt);
+            dt = get_bits1(gb);
+            read_ipdopd_data(NULL, gb, ps, ps->opd_par, dt ? huff_opd_dt : huff_opd_df, e, dt);
+        }
+    }
+    skip_bits1(gb);      //reserved_ps
+    return get_bits_count(gb) - count;
+}
+
+static void ipdopd_reset(int8_t *opd_hist, int8_t *ipd_hist)
+{
+    int i;
+    for (i = 0; i < PS_MAX_NR_IPDOPD; i++) {
+        opd_hist[i] = 0;
+        ipd_hist[i] = 0;
+    }
+}
+
+int ff_ps_read_data(AVCodecContext *avctx, GetBitContext *gb_host, PSContext *ps, int bits_left)
+{
+    int e;
+    int bit_count_start = get_bits_count(gb_host);
+    int header;
+    int bits_consumed;
+    GetBitContext gbc = *gb_host, *gb = &gbc;
+
+    header = get_bits1(gb);
+    if (header) {     //enable_ps_header
+        ps->enable_iid = get_bits1(gb);
+        if (ps->enable_iid) {
+            int iid_mode = get_bits(gb, 3);
+            if (iid_mode > 5) {
+                av_log(avctx, AV_LOG_ERROR, "iid_mode %d is reserved.\n",
+                       iid_mode);
+                goto err;
+            }
+            ps->nr_iid_par    = nr_iidicc_par_tab[iid_mode];
+            ps->iid_quant     = iid_mode > 2;
+            ps->nr_ipdopd_par = nr_iidopd_par_tab[iid_mode];
+        }
+        ps->enable_icc = get_bits1(gb);
+        if (ps->enable_icc) {
+            ps->icc_mode = get_bits(gb, 3);
+            if (ps->icc_mode > 5) {
+                av_log(avctx, AV_LOG_ERROR, "icc_mode %d is reserved.\n",
+                       ps->icc_mode);
+                goto err;
+            }
+            ps->nr_icc_par = nr_iidicc_par_tab[ps->icc_mode];
+        }
+        ps->enable_ext = get_bits1(gb);
+    }
+
+    ps->frame_class = get_bits1(gb);
+    ps->num_env_old = ps->num_env;
+    ps->num_env     = num_env_tab[ps->frame_class][get_bits(gb, 2)];
+
+    ps->border_position[0] = -1;
+    if (ps->frame_class) {
+        for (e = 1; e <= ps->num_env; e++)
+            ps->border_position[e] = get_bits(gb, 5);
+    } else
+        for (e = 1; e <= ps->num_env; e++)
+            ps->border_position[e] = (e * numQMFSlots >> ff_log2_tab[ps->num_env]) - 1;
+
+    if (ps->enable_iid) {
+        for (e = 0; e < ps->num_env; e++) {
+            int dt = get_bits1(gb);
+            if (read_iid_data(avctx, gb, ps, ps->iid_par, huff_iid[2*dt+ps->iid_quant], e, dt))
+                goto err;
+        }
+    } else
+        memset(ps->iid_par, 0, sizeof(ps->iid_par));
+
+    if (ps->enable_icc)
+        for (e = 0; e < ps->num_env; e++) {
+            int dt = get_bits1(gb);
+            if (read_icc_data(avctx, gb, ps, ps->icc_par, dt ? huff_icc_dt : huff_icc_df, e, dt))
+                goto err;
+        }
+    else
+        memset(ps->icc_par, 0, sizeof(ps->icc_par));
+
+    if (ps->enable_ext) {
+        int cnt = get_bits(gb, 4);
+        if (cnt == 15) {
+            cnt += get_bits(gb, 8);
+        }
+        cnt *= 8;
+        while (cnt > 7) {
+            int ps_extension_id = get_bits(gb, 2);
+            cnt -= 2 + ps_read_extension_data(gb, ps, ps_extension_id);
+        }
+        if (cnt < 0) {
+            av_log(avctx, AV_LOG_ERROR, "ps extension overflow %d", cnt);
+            goto err;
+        }
+        skip_bits(gb, cnt);
+    }
+
+    ps->enable_ipdopd &= !PS_BASELINE;
+
+    //Fix up envelopes
+    if (!ps->num_env || ps->border_position[ps->num_env] < numQMFSlots - 1) {
+        //Create a fake envelope
+        int source = ps->num_env ? ps->num_env - 1 : ps->num_env_old - 1;
+        if (source >= 0 && source != ps->num_env) {
+            if (ps->enable_iid) {
+                memcpy(ps->iid_par+ps->num_env, ps->iid_par+source, sizeof(ps->iid_par[0]));
+            }
+            if (ps->enable_icc) {
+                memcpy(ps->icc_par+ps->num_env, ps->icc_par+source, sizeof(ps->icc_par[0]));
+            }
+            if (ps->enable_ipdopd) {
+                memcpy(ps->ipd_par+ps->num_env, ps->ipd_par+source, sizeof(ps->ipd_par[0]));
+                memcpy(ps->opd_par+ps->num_env, ps->opd_par+source, sizeof(ps->opd_par[0]));
+            }
+        }
+        ps->num_env++;
+        ps->border_position[ps->num_env] = numQMFSlots - 1;
+    }
+
+
+    ps->is34bands_old = ps->is34bands;
+    if (!PS_BASELINE && (ps->enable_iid || ps->enable_icc))
+        ps->is34bands = (ps->enable_iid && ps->nr_iid_par == 34) ||
+                        (ps->enable_icc && ps->nr_icc_par == 34);
+
+    //Baseline
+    if (!ps->enable_ipdopd) {
+        memset(ps->ipd_par, 0, sizeof(ps->ipd_par));
+        memset(ps->opd_par, 0, sizeof(ps->opd_par));
+    }
+
+    if (header)
+        ps->start = 1;
+
+    bits_consumed = get_bits_count(gb) - bit_count_start;
+    if (bits_consumed <= bits_left) {
+        skip_bits_long(gb_host, bits_consumed);
+        return bits_consumed;
+    }
+    av_log(avctx, AV_LOG_ERROR, "Expected to read %d PS bits actually read %d.\n", bits_left, bits_consumed);
+err:
+    ps->start = 0;
+    skip_bits_long(gb_host, bits_left);
+    return bits_left;
+}
+
+/** Split one subband into 2 subsubbands with a symmetric real filter.
+ * The filter must have its non-center even coefficients equal to zero. */
+static void hybrid2_re(float (*in)[2], float (*out)[32][2], const float filter[7], int len, int reverse)
+{
+    int i, j;
+    for (i = 0; i < len; i++, in++) {
+        float re_in = filter[6] * in[6][0];          //real inphase
+        float re_op = 0.0f;                          //real out of phase
+        float im_in = filter[6] * in[6][1];          //imag inphase
+        float im_op = 0.0f;                          //imag out of phase
+        for (j = 0; j < 6; j += 2) {
+            re_op += filter[j+1] * (in[j+1][0] + in[12-j-1][0]);
+            im_op += filter[j+1] * (in[j+1][1] + in[12-j-1][1]);
+        }
+        out[ reverse][i][0] = re_in + re_op;
+        out[ reverse][i][1] = im_in + im_op;
+        out[!reverse][i][0] = re_in - re_op;
+        out[!reverse][i][1] = im_in - im_op;
+    }
+}
+
+/** Split one subband into 6 subsubbands with a complex filter */
+static void hybrid6_cx(float (*in)[2], float (*out)[32][2], const float (*filter)[7][2], int len)
+{
+    int i, j, ssb;
+    int N = 8;
+    float temp[8][2];
+
+    for (i = 0; i < len; i++, in++) {
+        for (ssb = 0; ssb < N; ssb++) {
+            float sum_re = filter[ssb][6][0] * in[6][0], sum_im = filter[ssb][6][0] * in[6][1];
+            for (j = 0; j < 6; j++) {
+                float in0_re = in[j][0];
+                float in0_im = in[j][1];
+                float in1_re = in[12-j][0];
+                float in1_im = in[12-j][1];
+                sum_re += filter[ssb][j][0] * (in0_re + in1_re) - filter[ssb][j][1] * (in0_im - in1_im);
+                sum_im += filter[ssb][j][0] * (in0_im + in1_im) + filter[ssb][j][1] * (in0_re - in1_re);
+            }
+            temp[ssb][0] = sum_re;
+            temp[ssb][1] = sum_im;
+        }
+        out[0][i][0] = temp[6][0];
+        out[0][i][1] = temp[6][1];
+        out[1][i][0] = temp[7][0];
+        out[1][i][1] = temp[7][1];
+        out[2][i][0] = temp[0][0];
+        out[2][i][1] = temp[0][1];
+        out[3][i][0] = temp[1][0];
+        out[3][i][1] = temp[1][1];
+        out[4][i][0] = temp[2][0] + temp[5][0];
+        out[4][i][1] = temp[2][1] + temp[5][1];
+        out[5][i][0] = temp[3][0] + temp[4][0];
+        out[5][i][1] = temp[3][1] + temp[4][1];
+    }
+}
+
+static void hybrid4_8_12_cx(float (*in)[2], float (*out)[32][2], const float (*filter)[7][2], int N, int len)
+{
+    int i, j, ssb;
+
+    for (i = 0; i < len; i++, in++) {
+        for (ssb = 0; ssb < N; ssb++) {
+            float sum_re = filter[ssb][6][0] * in[6][0], sum_im = filter[ssb][6][0] * in[6][1];
+            for (j = 0; j < 6; j++) {
+                float in0_re = in[j][0];
+                float in0_im = in[j][1];
+                float in1_re = in[12-j][0];
+                float in1_im = in[12-j][1];
+                sum_re += filter[ssb][j][0] * (in0_re + in1_re) - filter[ssb][j][1] * (in0_im - in1_im);
+                sum_im += filter[ssb][j][0] * (in0_im + in1_im) + filter[ssb][j][1] * (in0_re - in1_re);
+            }
+            out[ssb][i][0] = sum_re;
+            out[ssb][i][1] = sum_im;
+        }
+    }
+}
+
+static void hybrid_analysis(float out[91][32][2], float in[5][44][2], float L[2][38][64], int is34, int len)
+{
+    int i, j;
+    for (i = 0; i < 5; i++) {
+        for (j = 0; j < 38; j++) {
+            in[i][j+6][0] = L[0][j][i];
+            in[i][j+6][1] = L[1][j][i];
+        }
+    }
+    if (is34) {
+        hybrid4_8_12_cx(in[0], out,    f34_0_12, 12, len);
+        hybrid4_8_12_cx(in[1], out+12, f34_1_8,   8, len);
+        hybrid4_8_12_cx(in[2], out+20, f34_2_4,   4, len);
+        hybrid4_8_12_cx(in[3], out+24, f34_2_4,   4, len);
+        hybrid4_8_12_cx(in[4], out+28, f34_2_4,   4, len);
+        for (i = 0; i < 59; i++) {
+            for (j = 0; j < len; j++) {
+                out[i+32][j][0] = L[0][j][i+5];
+                out[i+32][j][1] = L[1][j][i+5];
+            }
+        }
+    } else {
+        hybrid6_cx(in[0], out, f20_0_8, len);
+        hybrid2_re(in[1], out+6, g1_Q2, len, 1);
+        hybrid2_re(in[2], out+8, g1_Q2, len, 0);
+        for (i = 0; i < 61; i++) {
+            for (j = 0; j < len; j++) {
+                out[i+10][j][0] = L[0][j][i+3];
+                out[i+10][j][1] = L[1][j][i+3];
+            }
+        }
+    }
+    //update in_buf
+    for (i = 0; i < 5; i++) {
+        memcpy(in[i], in[i]+32, 6 * sizeof(in[i][0]));
+    }
+}
+
+static void hybrid_synthesis(float out[2][38][64], float in[91][32][2], int is34, int len)
+{
+    int i, n;
+    if (is34) {
+        for (n = 0; n < len; n++) {
+            memset(out[0][n], 0, 5*sizeof(out[0][n][0]));
+            memset(out[1][n], 0, 5*sizeof(out[1][n][0]));
+            for (i = 0; i < 12; i++) {
+                out[0][n][0] += in[   i][n][0];
+                out[1][n][0] += in[   i][n][1];
+            }
+            for (i = 0; i < 8; i++) {
+                out[0][n][1] += in[12+i][n][0];
+                out[1][n][1] += in[12+i][n][1];
+            }
+            for (i = 0; i < 4; i++) {
+                out[0][n][2] += in[20+i][n][0];
+                out[1][n][2] += in[20+i][n][1];
+                out[0][n][3] += in[24+i][n][0];
+                out[1][n][3] += in[24+i][n][1];
+                out[0][n][4] += in[28+i][n][0];
+                out[1][n][4] += in[28+i][n][1];
+            }
+        }
+        for (i = 0; i < 59; i++) {
+            for (n = 0; n < len; n++) {
+                out[0][n][i+5] = in[i+32][n][0];
+                out[1][n][i+5] = in[i+32][n][1];
+            }
+        }
+    } else {
+        for (n = 0; n < len; n++) {
+            out[0][n][0] = in[0][n][0] + in[1][n][0] + in[2][n][0] +
+                           in[3][n][0] + in[4][n][0] + in[5][n][0];
+            out[1][n][0] = in[0][n][1] + in[1][n][1] + in[2][n][1] +
+                           in[3][n][1] + in[4][n][1] + in[5][n][1];
+            out[0][n][1] = in[6][n][0] + in[7][n][0];
+            out[1][n][1] = in[6][n][1] + in[7][n][1];
+            out[0][n][2] = in[8][n][0] + in[9][n][0];
+            out[1][n][2] = in[8][n][1] + in[9][n][1];
+        }
+        for (i = 0; i < 61; i++) {
+            for (n = 0; n < len; n++) {
+                out[0][n][i+3] = in[i+10][n][0];
+                out[1][n][i+3] = in[i+10][n][1];
+            }
+        }
+    }
+}
+
+/// All-pass filter decay slope
+#define DECAY_SLOPE      0.05f
+/// Number of frequency bands that can be addressed by the parameter index, b(k)
+static const int   NR_PAR_BANDS[]      = { 20, 34 };
+/// Number of frequency bands that can be addressed by the sub subband index, k
+static const int   NR_BANDS[]          = { 71, 91 };
+/// Start frequency band for the all-pass filter decay slope
+static const int   DECAY_CUTOFF[]      = { 10, 32 };
+/// Number of all-pass filer bands
+static const int   NR_ALLPASS_BANDS[]  = { 30, 50 };
+/// First stereo band using the short one sample delay
+static const int   SHORT_DELAY_BAND[]  = { 42, 62 };
+
+/** Table 8.46 */
+static void map_idx_10_to_20(int8_t *par_mapped, const int8_t *par, int full)
+{
+    int b;
+    if (full)
+        b = 9;
+    else {
+        b = 4;
+        par_mapped[10] = 0;
+    }
+    for (; b >= 0; b--) {
+        par_mapped[2*b+1] = par_mapped[2*b] = par[b];
+    }
+}
+
+static void map_idx_34_to_20(int8_t *par_mapped, const int8_t *par, int full)
+{
+    par_mapped[ 0] = (2*par[ 0] +   par[ 1]) / 3;
+    par_mapped[ 1] = (  par[ 1] + 2*par[ 2]) / 3;
+    par_mapped[ 2] = (2*par[ 3] +   par[ 4]) / 3;
+    par_mapped[ 3] = (  par[ 4] + 2*par[ 5]) / 3;
+    par_mapped[ 4] = (  par[ 6] +   par[ 7]) / 2;
+    par_mapped[ 5] = (  par[ 8] +   par[ 9]) / 2;
+    par_mapped[ 6] =    par[10];
+    par_mapped[ 7] =    par[11];
+    par_mapped[ 8] = (  par[12] +   par[13]) / 2;
+    par_mapped[ 9] = (  par[14] +   par[15]) / 2;
+    par_mapped[10] =    par[16];
+    if (full) {
+        par_mapped[11] =    par[17];
+        par_mapped[12] =    par[18];
+        par_mapped[13] =    par[19];
+        par_mapped[14] = (  par[20] +   par[21]) / 2;
+        par_mapped[15] = (  par[22] +   par[23]) / 2;
+        par_mapped[16] = (  par[24] +   par[25]) / 2;
+        par_mapped[17] = (  par[26] +   par[27]) / 2;
+        par_mapped[18] = (  par[28] +   par[29] +   par[30] +   par[31]) / 4;
+        par_mapped[19] = (  par[32] +   par[33]) / 2;
+    }
+}
+
+static void map_val_34_to_20(float par[PS_MAX_NR_IIDICC])
+{
+    par[ 0] = (2*par[ 0] +   par[ 1]) * 0.33333333f;
+    par[ 1] = (  par[ 1] + 2*par[ 2]) * 0.33333333f;
+    par[ 2] = (2*par[ 3] +   par[ 4]) * 0.33333333f;
+    par[ 3] = (  par[ 4] + 2*par[ 5]) * 0.33333333f;
+    par[ 4] = (  par[ 6] +   par[ 7]) * 0.5f;
+    par[ 5] = (  par[ 8] +   par[ 9]) * 0.5f;
+    par[ 6] =    par[10];
+    par[ 7] =    par[11];
+    par[ 8] = (  par[12] +   par[13]) * 0.5f;
+    par[ 9] = (  par[14] +   par[15]) * 0.5f;
+    par[10] =    par[16];
+    par[11] =    par[17];
+    par[12] =    par[18];
+    par[13] =    par[19];
+    par[14] = (  par[20] +   par[21]) * 0.5f;
+    par[15] = (  par[22] +   par[23]) * 0.5f;
+    par[16] = (  par[24] +   par[25]) * 0.5f;
+    par[17] = (  par[26] +   par[27]) * 0.5f;
+    par[18] = (  par[28] +   par[29] +   par[30] +   par[31]) * 0.25f;
+    par[19] = (  par[32] +   par[33]) * 0.5f;
+}
+
+static void map_idx_10_to_34(int8_t *par_mapped, const int8_t *par, int full)
+{
+    if (full) {
+        par_mapped[33] = par[9];
+        par_mapped[32] = par[9];
+        par_mapped[31] = par[9];
+        par_mapped[30] = par[9];
+        par_mapped[29] = par[9];
+        par_mapped[28] = par[9];
+        par_mapped[27] = par[8];
+        par_mapped[26] = par[8];
+        par_mapped[25] = par[8];
+        par_mapped[24] = par[8];
+        par_mapped[23] = par[7];
+        par_mapped[22] = par[7];
+        par_mapped[21] = par[7];
+        par_mapped[20] = par[7];
+        par_mapped[19] = par[6];
+        par_mapped[18] = par[6];
+        par_mapped[17] = par[5];
+        par_mapped[16] = par[5];
+    } else {
+        par_mapped[16] =      0;
+    }
+    par_mapped[15] = par[4];
+    par_mapped[14] = par[4];
+    par_mapped[13] = par[4];
+    par_mapped[12] = par[4];
+    par_mapped[11] = par[3];
+    par_mapped[10] = par[3];
+    par_mapped[ 9] = par[2];
+    par_mapped[ 8] = par[2];
+    par_mapped[ 7] = par[2];
+    par_mapped[ 6] = par[2];
+    par_mapped[ 5] = par[1];
+    par_mapped[ 4] = par[1];
+    par_mapped[ 3] = par[1];
+    par_mapped[ 2] = par[0];
+    par_mapped[ 1] = par[0];
+    par_mapped[ 0] = par[0];
+}
+
+static void map_idx_20_to_34(int8_t *par_mapped, const int8_t *par, int full)
+{
+    if (full) {
+        par_mapped[33] =  par[19];
+        par_mapped[32] =  par[19];
+        par_mapped[31] =  par[18];
+        par_mapped[30] =  par[18];
+        par_mapped[29] =  par[18];
+        par_mapped[28] =  par[18];
+        par_mapped[27] =  par[17];
+        par_mapped[26] =  par[17];
+        par_mapped[25] =  par[16];
+        par_mapped[24] =  par[16];
+        par_mapped[23] =  par[15];
+        par_mapped[22] =  par[15];
+        par_mapped[21] =  par[14];
+        par_mapped[20] =  par[14];
+        par_mapped[19] =  par[13];
+        par_mapped[18] =  par[12];
+        par_mapped[17] =  par[11];
+    }
+    par_mapped[16] =  par[10];
+    par_mapped[15] =  par[ 9];
+    par_mapped[14] =  par[ 9];
+    par_mapped[13] =  par[ 8];
+    par_mapped[12] =  par[ 8];
+    par_mapped[11] =  par[ 7];
+    par_mapped[10] =  par[ 6];
+    par_mapped[ 9] =  par[ 5];
+    par_mapped[ 8] =  par[ 5];
+    par_mapped[ 7] =  par[ 4];
+    par_mapped[ 6] =  par[ 4];
+    par_mapped[ 5] =  par[ 3];
+    par_mapped[ 4] = (par[ 2] + par[ 3]) / 2;
+    par_mapped[ 3] =  par[ 2];
+    par_mapped[ 2] =  par[ 1];
+    par_mapped[ 1] = (par[ 0] + par[ 1]) / 2;
+    par_mapped[ 0] =  par[ 0];
+}
+
+static void map_val_20_to_34(float par[PS_MAX_NR_IIDICC])
+{
+    par[33] =  par[19];
+    par[32] =  par[19];
+    par[31] =  par[18];
+    par[30] =  par[18];
+    par[29] =  par[18];
+    par[28] =  par[18];
+    par[27] =  par[17];
+    par[26] =  par[17];
+    par[25] =  par[16];
+    par[24] =  par[16];
+    par[23] =  par[15];
+    par[22] =  par[15];
+    par[21] =  par[14];
+    par[20] =  par[14];
+    par[19] =  par[13];
+    par[18] =  par[12];
+    par[17] =  par[11];
+    par[16] =  par[10];
+    par[15] =  par[ 9];
+    par[14] =  par[ 9];
+    par[13] =  par[ 8];
+    par[12] =  par[ 8];
+    par[11] =  par[ 7];
+    par[10] =  par[ 6];
+    par[ 9] =  par[ 5];
+    par[ 8] =  par[ 5];
+    par[ 7] =  par[ 4];
+    par[ 6] =  par[ 4];
+    par[ 5] =  par[ 3];
+    par[ 4] = (par[ 2] + par[ 3]) * 0.5f;
+    par[ 3] =  par[ 2];
+    par[ 2] =  par[ 1];
+    par[ 1] = (par[ 0] + par[ 1]) * 0.5f;
+    par[ 0] =  par[ 0];
+}
+
+static void decorrelation(PSContext *ps, float (*out)[32][2], const float (*s)[32][2], int is34)
+{
+    float power[34][PS_QMF_TIME_SLOTS] = {{0}};
+    float transient_gain[34][PS_QMF_TIME_SLOTS];
+    float *peak_decay_nrg = ps->peak_decay_nrg;
+    float *power_smooth = ps->power_smooth;
+    float *peak_decay_diff_smooth = ps->peak_decay_diff_smooth;
+    float (*delay)[PS_QMF_TIME_SLOTS + PS_MAX_DELAY][2] = ps->delay;
+    float (*ap_delay)[PS_AP_LINKS][PS_QMF_TIME_SLOTS + PS_MAX_AP_DELAY][2] = ps->ap_delay;
+    const int8_t *k_to_i = is34 ? k_to_i_34 : k_to_i_20;
+    const float peak_decay_factor = 0.76592833836465f;
+    const float transient_impact  = 1.5f;
+    const float a_smooth          = 0.25f; //< Smoothing coefficient
+    int i, k, m, n;
+    int n0 = 0, nL = 32;
+    static const int link_delay[] = { 3, 4, 5 };
+    static const float a[] = { 0.65143905753106f,
+                               0.56471812200776f,
+                               0.48954165955695f };
+
+    if (is34 != ps->is34bands_old) {
+        memset(ps->peak_decay_nrg,         0, sizeof(ps->peak_decay_nrg));
+        memset(ps->power_smooth,           0, sizeof(ps->power_smooth));
+        memset(ps->peak_decay_diff_smooth, 0, sizeof(ps->peak_decay_diff_smooth));
+        memset(ps->delay,                  0, sizeof(ps->delay));
+        memset(ps->ap_delay,               0, sizeof(ps->ap_delay));
+    }
+
+    for (n = n0; n < nL; n++) {
+        for (k = 0; k < NR_BANDS[is34]; k++) {
+            int i = k_to_i[k];
+            power[i][n] += s[k][n][0] * s[k][n][0] + s[k][n][1] * s[k][n][1];
+        }
+    }
+
+    //Transient detection
+    for (i = 0; i < NR_PAR_BANDS[is34]; i++) {
+        for (n = n0; n < nL; n++) {
+            float decayed_peak = peak_decay_factor * peak_decay_nrg[i];
+            float denom;
+            peak_decay_nrg[i] = FFMAX(decayed_peak, power[i][n]);
+            power_smooth[i] += a_smooth * (power[i][n] - power_smooth[i]);
+            peak_decay_diff_smooth[i] += a_smooth * (peak_decay_nrg[i] - power[i][n] - peak_decay_diff_smooth[i]);
+            denom = transient_impact * peak_decay_diff_smooth[i];
+            transient_gain[i][n]   = (denom > power_smooth[i]) ?
+                                         power_smooth[i] / denom : 1.0f;
+        }
+    }
+
+    //Decorrelation and transient reduction
+    //                         PS_AP_LINKS - 1
+    //                               -----
+    //                                | |  Q_fract_allpass[k][m]*z^-link_delay[m] - a[m]*g_decay_slope[k]
+    //H[k][z] = z^-2 * phi_fract[k] * | | ----------------------------------------------------------------
+    //                                | | 1 - a[m]*g_decay_slope[k]*Q_fract_allpass[k][m]*z^-link_delay[m]
+    //                               m = 0
+    //d[k][z] (out) = transient_gain_mapped[k][z] * H[k][z] * s[k][z]
+    for (k = 0; k < NR_ALLPASS_BANDS[is34]; k++) {
+        int b = k_to_i[k];
+        float g_decay_slope = 1.f - DECAY_SLOPE * (k - DECAY_CUTOFF[is34]);
+        float ag[PS_AP_LINKS];
+        g_decay_slope = av_clipf(g_decay_slope, 0.f, 1.f);
+        memcpy(delay[k], delay[k]+nL, PS_MAX_DELAY*sizeof(delay[k][0]));
+        memcpy(delay[k]+PS_MAX_DELAY, s[k], numQMFSlots*sizeof(delay[k][0]));
+        for (m = 0; m < PS_AP_LINKS; m++) {
+            memcpy(ap_delay[k][m],   ap_delay[k][m]+numQMFSlots,           5*sizeof(ap_delay[k][m][0]));
+            ag[m] = a[m] * g_decay_slope;
+        }
+        for (n = n0; n < nL; n++) {
+            float in_re = delay[k][n+PS_MAX_DELAY-2][0] * phi_fract[is34][k][0] -
+                          delay[k][n+PS_MAX_DELAY-2][1] * phi_fract[is34][k][1];
+            float in_im = delay[k][n+PS_MAX_DELAY-2][0] * phi_fract[is34][k][1] +
+                          delay[k][n+PS_MAX_DELAY-2][1] * phi_fract[is34][k][0];
+            for (m = 0; m < PS_AP_LINKS; m++) {
+                float a_re                = ag[m] * in_re;
+                float a_im                = ag[m] * in_im;
+                float link_delay_re       = ap_delay[k][m][n+5-link_delay[m]][0];
+                float link_delay_im       = ap_delay[k][m][n+5-link_delay[m]][1];
+                float fractional_delay_re = Q_fract_allpass[is34][k][m][0];
+                float fractional_delay_im = Q_fract_allpass[is34][k][m][1];
+                ap_delay[k][m][n+5][0] = in_re;
+                ap_delay[k][m][n+5][1] = in_im;
+                in_re = link_delay_re * fractional_delay_re - link_delay_im * fractional_delay_im - a_re;
+                in_im = link_delay_re * fractional_delay_im + link_delay_im * fractional_delay_re - a_im;
+                ap_delay[k][m][n+5][0] += ag[m] * in_re;
+                ap_delay[k][m][n+5][1] += ag[m] * in_im;
+            }
+            out[k][n][0] = transient_gain[b][n] * in_re;
+            out[k][n][1] = transient_gain[b][n] * in_im;
+        }
+    }
+    for (; k < SHORT_DELAY_BAND[is34]; k++) {
+        memcpy(delay[k], delay[k]+nL, PS_MAX_DELAY*sizeof(delay[k][0]));
+        memcpy(delay[k]+PS_MAX_DELAY, s[k], numQMFSlots*sizeof(delay[k][0]));
+        for (n = n0; n < nL; n++) {
+            //H = delay 14
+            out[k][n][0] = transient_gain[k_to_i[k]][n] * delay[k][n+PS_MAX_DELAY-14][0];
+            out[k][n][1] = transient_gain[k_to_i[k]][n] * delay[k][n+PS_MAX_DELAY-14][1];
+        }
+    }
+    for (; k < NR_BANDS[is34]; k++) {
+        memcpy(delay[k], delay[k]+nL, PS_MAX_DELAY*sizeof(delay[k][0]));
+        memcpy(delay[k]+PS_MAX_DELAY, s[k], numQMFSlots*sizeof(delay[k][0]));
+        for (n = n0; n < nL; n++) {
+            //H = delay 1
+            out[k][n][0] = transient_gain[k_to_i[k]][n] * delay[k][n+PS_MAX_DELAY-1][0];
+            out[k][n][1] = transient_gain[k_to_i[k]][n] * delay[k][n+PS_MAX_DELAY-1][1];
+        }
+    }
+}
+
+static void remap34(int8_t (**p_par_mapped)[PS_MAX_NR_IIDICC],
+                    int8_t           (*par)[PS_MAX_NR_IIDICC],
+                    int num_par, int num_env, int full)
+{
+    int8_t (*par_mapped)[PS_MAX_NR_IIDICC] = *p_par_mapped;
+    int e;
+    if (num_par == 20 || num_par == 11) {
+        for (e = 0; e < num_env; e++) {
+            map_idx_20_to_34(par_mapped[e], par[e], full);
+        }
+    } else if (num_par == 10 || num_par == 5) {
+        for (e = 0; e < num_env; e++) {
+            map_idx_10_to_34(par_mapped[e], par[e], full);
+        }
+    } else {
+        *p_par_mapped = par;
+    }
+}
+
+static void remap20(int8_t (**p_par_mapped)[PS_MAX_NR_IIDICC],
+                    int8_t           (*par)[PS_MAX_NR_IIDICC],
+                    int num_par, int num_env, int full)
+{
+    int8_t (*par_mapped)[PS_MAX_NR_IIDICC] = *p_par_mapped;
+    int e;
+    if (num_par == 34 || num_par == 17) {
+        for (e = 0; e < num_env; e++) {
+            map_idx_34_to_20(par_mapped[e], par[e], full);
+        }
+    } else if (num_par == 10 || num_par == 5) {
+        for (e = 0; e < num_env; e++) {
+            map_idx_10_to_20(par_mapped[e], par[e], full);
+        }
+    } else {
+        *p_par_mapped = par;
+    }
+}
+
+static void stereo_processing(PSContext *ps, float (*l)[32][2], float (*r)[32][2], int is34)
+{
+    int e, b, k, n;
+
+    float (*H11)[PS_MAX_NUM_ENV+1][PS_MAX_NR_IIDICC] = ps->H11;
+    float (*H12)[PS_MAX_NUM_ENV+1][PS_MAX_NR_IIDICC] = ps->H12;
+    float (*H21)[PS_MAX_NUM_ENV+1][PS_MAX_NR_IIDICC] = ps->H21;
+    float (*H22)[PS_MAX_NUM_ENV+1][PS_MAX_NR_IIDICC] = ps->H22;
+    int8_t *opd_hist = ps->opd_hist;
+    int8_t *ipd_hist = ps->ipd_hist;
+    int8_t iid_mapped_buf[PS_MAX_NUM_ENV][PS_MAX_NR_IIDICC];
+    int8_t icc_mapped_buf[PS_MAX_NUM_ENV][PS_MAX_NR_IIDICC];
+    int8_t ipd_mapped_buf[PS_MAX_NUM_ENV][PS_MAX_NR_IIDICC];
+    int8_t opd_mapped_buf[PS_MAX_NUM_ENV][PS_MAX_NR_IIDICC];
+    int8_t (*iid_mapped)[PS_MAX_NR_IIDICC] = iid_mapped_buf;
+    int8_t (*icc_mapped)[PS_MAX_NR_IIDICC] = icc_mapped_buf;
+    int8_t (*ipd_mapped)[PS_MAX_NR_IIDICC] = ipd_mapped_buf;
+    int8_t (*opd_mapped)[PS_MAX_NR_IIDICC] = opd_mapped_buf;
+    const int8_t *k_to_i = is34 ? k_to_i_34 : k_to_i_20;
+    const float (*H_LUT)[8][4] = (PS_BASELINE || ps->icc_mode < 3) ? HA : HB;
+
+    //Remapping
+    memcpy(H11[0][0], H11[0][ps->num_env_old], PS_MAX_NR_IIDICC*sizeof(H11[0][0][0]));
+    memcpy(H11[1][0], H11[1][ps->num_env_old], PS_MAX_NR_IIDICC*sizeof(H11[1][0][0]));
+    memcpy(H12[0][0], H12[0][ps->num_env_old], PS_MAX_NR_IIDICC*sizeof(H12[0][0][0]));
+    memcpy(H12[1][0], H12[1][ps->num_env_old], PS_MAX_NR_IIDICC*sizeof(H12[1][0][0]));
+    memcpy(H21[0][0], H21[0][ps->num_env_old], PS_MAX_NR_IIDICC*sizeof(H21[0][0][0]));
+    memcpy(H21[1][0], H21[1][ps->num_env_old], PS_MAX_NR_IIDICC*sizeof(H21[1][0][0]));
+    memcpy(H22[0][0], H22[0][ps->num_env_old], PS_MAX_NR_IIDICC*sizeof(H22[0][0][0]));
+    memcpy(H22[1][0], H22[1][ps->num_env_old], PS_MAX_NR_IIDICC*sizeof(H22[1][0][0]));
+    if (is34) {
+        remap34(&iid_mapped, ps->iid_par, ps->nr_iid_par, ps->num_env, 1);
+        remap34(&icc_mapped, ps->icc_par, ps->nr_icc_par, ps->num_env, 1);
+        if (ps->enable_ipdopd) {
+            remap34(&ipd_mapped, ps->ipd_par, ps->nr_ipdopd_par, ps->num_env, 0);
+            remap34(&opd_mapped, ps->opd_par, ps->nr_ipdopd_par, ps->num_env, 0);
+        }
+        if (!ps->is34bands_old) {
+            map_val_20_to_34(H11[0][0]);
+            map_val_20_to_34(H11[1][0]);
+            map_val_20_to_34(H12[0][0]);
+            map_val_20_to_34(H12[1][0]);
+            map_val_20_to_34(H21[0][0]);
+            map_val_20_to_34(H21[1][0]);
+            map_val_20_to_34(H22[0][0]);
+            map_val_20_to_34(H22[1][0]);
+            ipdopd_reset(ipd_hist, opd_hist);
+        }
+    } else {
+        remap20(&iid_mapped, ps->iid_par, ps->nr_iid_par, ps->num_env, 1);
+        remap20(&icc_mapped, ps->icc_par, ps->nr_icc_par, ps->num_env, 1);
+        if (ps->enable_ipdopd) {
+            remap20(&ipd_mapped, ps->ipd_par, ps->nr_ipdopd_par, ps->num_env, 0);
+            remap20(&opd_mapped, ps->opd_par, ps->nr_ipdopd_par, ps->num_env, 0);
+        }
+        if (ps->is34bands_old) {
+            map_val_34_to_20(H11[0][0]);
+            map_val_34_to_20(H11[1][0]);
+            map_val_34_to_20(H12[0][0]);
+            map_val_34_to_20(H12[1][0]);
+            map_val_34_to_20(H21[0][0]);
+            map_val_34_to_20(H21[1][0]);
+            map_val_34_to_20(H22[0][0]);
+            map_val_34_to_20(H22[1][0]);
+            ipdopd_reset(ipd_hist, opd_hist);
+        }
+    }
+
+    //Mixing
+    for (e = 0; e < ps->num_env; e++) {
+        for (b = 0; b < NR_PAR_BANDS[is34]; b++) {
+            float h11, h12, h21, h22;
+            h11 = H_LUT[iid_mapped[e][b] + 7 + 23 * ps->iid_quant][icc_mapped[e][b]][0];
+            h12 = H_LUT[iid_mapped[e][b] + 7 + 23 * ps->iid_quant][icc_mapped[e][b]][1];
+            h21 = H_LUT[iid_mapped[e][b] + 7 + 23 * ps->iid_quant][icc_mapped[e][b]][2];
+            h22 = H_LUT[iid_mapped[e][b] + 7 + 23 * ps->iid_quant][icc_mapped[e][b]][3];
+            if (!PS_BASELINE && ps->enable_ipdopd && b < ps->nr_ipdopd_par) {
+                //The spec say says to only run this smoother when enable_ipdopd
+                //is set but the reference decoder appears to run it constantly
+                float h11i, h12i, h21i, h22i;
+                float ipd_adj_re, ipd_adj_im;
+                int opd_idx = opd_hist[b] * 8 + opd_mapped[e][b];
+                int ipd_idx = ipd_hist[b] * 8 + ipd_mapped[e][b];
+                float opd_re = pd_re_smooth[opd_idx];
+                float opd_im = pd_im_smooth[opd_idx];
+                float ipd_re = pd_re_smooth[ipd_idx];
+                float ipd_im = pd_im_smooth[ipd_idx];
+                opd_hist[b] = opd_idx & 0x3F;
+                ipd_hist[b] = ipd_idx & 0x3F;
+
+                ipd_adj_re = opd_re*ipd_re + opd_im*ipd_im;
+                ipd_adj_im = opd_im*ipd_re - opd_re*ipd_im;
+                h11i = h11 * opd_im;
+                h11  = h11 * opd_re;
+                h12i = h12 * ipd_adj_im;
+                h12  = h12 * ipd_adj_re;
+                h21i = h21 * opd_im;
+                h21  = h21 * opd_re;
+                h22i = h22 * ipd_adj_im;
+                h22  = h22 * ipd_adj_re;
+                H11[1][e+1][b] = h11i;
+                H12[1][e+1][b] = h12i;
+                H21[1][e+1][b] = h21i;
+                H22[1][e+1][b] = h22i;
+            }
+            H11[0][e+1][b] = h11;
+            H12[0][e+1][b] = h12;
+            H21[0][e+1][b] = h21;
+            H22[0][e+1][b] = h22;
+        }
+        for (k = 0; k < NR_BANDS[is34]; k++) {
+            float h11r, h12r, h21r, h22r;
+            float h11i, h12i, h21i, h22i;
+            float h11r_step, h12r_step, h21r_step, h22r_step;
+            float h11i_step, h12i_step, h21i_step, h22i_step;
+            int start = ps->border_position[e];
+            int stop  = ps->border_position[e+1];
+            float width = 1.f / (stop - start);
+            b = k_to_i[k];
+            h11r = H11[0][e][b];
+            h12r = H12[0][e][b];
+            h21r = H21[0][e][b];
+            h22r = H22[0][e][b];
+            if (!PS_BASELINE && ps->enable_ipdopd) {
+            //Is this necessary? ps_04_new seems unchanged
+            if ((is34 && k <= 13 && k >= 9) || (!is34 && k <= 1)) {
+                h11i = -H11[1][e][b];
+                h12i = -H12[1][e][b];
+                h21i = -H21[1][e][b];
+                h22i = -H22[1][e][b];
+            } else {
+                h11i = H11[1][e][b];
+                h12i = H12[1][e][b];
+                h21i = H21[1][e][b];
+                h22i = H22[1][e][b];
+            }
+            }
+            //Interpolation
+            h11r_step = (H11[0][e+1][b] - h11r) * width;
+            h12r_step = (H12[0][e+1][b] - h12r) * width;
+            h21r_step = (H21[0][e+1][b] - h21r) * width;
+            h22r_step = (H22[0][e+1][b] - h22r) * width;
+            if (!PS_BASELINE && ps->enable_ipdopd) {
+                h11i_step = (H11[1][e+1][b] - h11i) * width;
+                h12i_step = (H12[1][e+1][b] - h12i) * width;
+                h21i_step = (H21[1][e+1][b] - h21i) * width;
+                h22i_step = (H22[1][e+1][b] - h22i) * width;
+            }
+            for (n = start + 1; n <= stop; n++) {
+                //l is s, r is d
+                float l_re = l[k][n][0];
+                float l_im = l[k][n][1];
+                float r_re = r[k][n][0];
+                float r_im = r[k][n][1];
+                h11r += h11r_step;
+                h12r += h12r_step;
+                h21r += h21r_step;
+                h22r += h22r_step;
+                if (!PS_BASELINE && ps->enable_ipdopd) {
+                    h11i += h11i_step;
+                    h12i += h12i_step;
+                    h21i += h21i_step;
+                    h22i += h22i_step;
+
+                    l[k][n][0] = h11r*l_re + h21r*r_re - h11i*l_im - h21i*r_im;
+                    l[k][n][1] = h11r*l_im + h21r*r_im + h11i*l_re + h21i*r_re;
+                    r[k][n][0] = h12r*l_re + h22r*r_re - h12i*l_im - h22i*r_im;
+                    r[k][n][1] = h12r*l_im + h22r*r_im + h12i*l_re + h22i*r_re;
+                } else {
+                    l[k][n][0] = h11r*l_re + h21r*r_re;
+                    l[k][n][1] = h11r*l_im + h21r*r_im;
+                    r[k][n][0] = h12r*l_re + h22r*r_re;
+                    r[k][n][1] = h12r*l_im + h22r*r_im;
+                }
+            }
+        }
+    }
+}
+
+int ff_ps_apply(AVCodecContext *avctx, PSContext *ps, float L[2][38][64], float R[2][38][64], int top)
+{
+    float Lbuf[91][32][2];
+    float Rbuf[91][32][2];
+    const int len = 32;
+    int is34 = ps->is34bands;
+
+    top += NR_BANDS[is34] - 64;
+    memset(ps->delay+top, 0, (NR_BANDS[is34] - top)*sizeof(ps->delay[0]));
+    if (top < NR_ALLPASS_BANDS[is34])
+        memset(ps->ap_delay + top, 0, (NR_ALLPASS_BANDS[is34] - top)*sizeof(ps->ap_delay[0]));
+
+    hybrid_analysis(Lbuf, ps->in_buf, L, is34, len);
+    decorrelation(ps, Rbuf, Lbuf, is34);
+    stereo_processing(ps, Lbuf, Rbuf, is34);
+    hybrid_synthesis(L, Lbuf, is34, len);
+    hybrid_synthesis(R, Rbuf, is34, len);
+
+    return 0;
+}
+
+#define PS_INIT_VLC_STATIC(num, size) \
+    INIT_VLC_STATIC(&vlc_ps[num], 9, ps_tmp[num].table_size / ps_tmp[num].elem_size,    \
+                    ps_tmp[num].ps_bits, 1, 1,                                          \
+                    ps_tmp[num].ps_codes, ps_tmp[num].elem_size, ps_tmp[num].elem_size, \
+                    size);
+
+#define PS_VLC_ROW(name) \
+    { name ## _codes, name ## _bits, sizeof(name ## _codes), sizeof(name ## _codes[0]) }
+
+av_cold void ff_ps_init(void) {
+    // Syntax initialization
+    static const struct {
+        const void *ps_codes, *ps_bits;
+        const unsigned int table_size, elem_size;
+    } ps_tmp[] = {
+        PS_VLC_ROW(huff_iid_df1),
+        PS_VLC_ROW(huff_iid_dt1),
+        PS_VLC_ROW(huff_iid_df0),
+        PS_VLC_ROW(huff_iid_dt0),
+        PS_VLC_ROW(huff_icc_df),
+        PS_VLC_ROW(huff_icc_dt),
+        PS_VLC_ROW(huff_ipd_df),
+        PS_VLC_ROW(huff_ipd_dt),
+        PS_VLC_ROW(huff_opd_df),
+        PS_VLC_ROW(huff_opd_dt),
+    };
+
+    PS_INIT_VLC_STATIC(0, 1544);
+    PS_INIT_VLC_STATIC(1,  832);
+    PS_INIT_VLC_STATIC(2, 1024);
+    PS_INIT_VLC_STATIC(3, 1036);
+    PS_INIT_VLC_STATIC(4,  544);
+    PS_INIT_VLC_STATIC(5,  544);
+    PS_INIT_VLC_STATIC(6,  512);
+    PS_INIT_VLC_STATIC(7,  512);
+    PS_INIT_VLC_STATIC(8,  512);
+    PS_INIT_VLC_STATIC(9,  512);
+
+    ps_tableinit();
+}
+
+av_cold void ff_ps_ctx_init(PSContext *ps)
+{
+}
diff --git a/libavcodec/aacps.h b/libavcodec/aacps.h
new file mode 100644
index 0000000..59a9bff
--- /dev/null
+++ b/libavcodec/aacps.h
@@ -0,0 +1,82 @@
+/*
+ * MPEG-4 Parametric Stereo definitions and declarations
+ * Copyright (c) 2010 Alex Converse <alex.converse at gmail.com>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_PS_H
+#define AVCODEC_PS_H
+
+#include <stdint.h>
+
+#include "avcodec.h"
+#include "get_bits.h"
+
+#define PS_MAX_NUM_ENV 5
+#define PS_MAX_NR_IIDICC 34
+#define PS_MAX_NR_IPDOPD 17
+#define PS_MAX_SSB 91
+#define PS_MAX_AP_BANDS 50
+#define PS_QMF_TIME_SLOTS 32
+#define PS_MAX_DELAY 14
+#define PS_AP_LINKS 3
+#define PS_MAX_AP_DELAY 5
+
+typedef struct {
+    int    start;
+    int    enable_iid;
+    int    iid_quant;
+    int    nr_iid_par;
+    int    nr_ipdopd_par;
+    int    enable_icc;
+    int    icc_mode;
+    int    nr_icc_par;
+    int    enable_ext;
+    int    frame_class;
+    int    num_env_old;
+    int    num_env;
+    int    enable_ipdopd;
+    int    border_position[PS_MAX_NUM_ENV+1];
+    int8_t iid_par[PS_MAX_NUM_ENV][PS_MAX_NR_IIDICC]; //<Inter-channel Intensity Difference Parameters
+    int8_t icc_par[PS_MAX_NUM_ENV][PS_MAX_NR_IIDICC]; //<Inter-Channel Coherence Parameters
+    /* ipd/opd is iid/icc sized so that the same functions can handle both */
+    int8_t ipd_par[PS_MAX_NUM_ENV][PS_MAX_NR_IIDICC]; //<Inter-channel Phase Difference Parameters
+    int8_t opd_par[PS_MAX_NUM_ENV][PS_MAX_NR_IIDICC]; //<Overall Phase Difference Parameters
+    int    is34bands;
+    int    is34bands_old;
+
+    float  in_buf[5][44][2];
+    float  delay[PS_MAX_SSB][PS_QMF_TIME_SLOTS + PS_MAX_DELAY][2];
+    float  ap_delay[PS_MAX_AP_BANDS][PS_AP_LINKS][PS_QMF_TIME_SLOTS + PS_MAX_AP_DELAY][2];
+    float  peak_decay_nrg[34];
+    float  power_smooth[34];
+    float  peak_decay_diff_smooth[34];
+    float  H11[2][PS_MAX_NUM_ENV+1][PS_MAX_NR_IIDICC];
+    float  H12[2][PS_MAX_NUM_ENV+1][PS_MAX_NR_IIDICC];
+    float  H21[2][PS_MAX_NUM_ENV+1][PS_MAX_NR_IIDICC];
+    float  H22[2][PS_MAX_NUM_ENV+1][PS_MAX_NR_IIDICC];
+    int8_t opd_hist[PS_MAX_NR_IIDICC];
+    int8_t ipd_hist[PS_MAX_NR_IIDICC];
+} PSContext;
+
+void ff_ps_init(void);
+void ff_ps_ctx_init(PSContext *ps);
+int ff_ps_read_data(AVCodecContext *avctx, GetBitContext *gb, PSContext *ps, int bits_left);
+int ff_ps_apply(AVCodecContext *avctx, PSContext *ps, float L[2][38][64], float R[2][38][64], int top);
+
+#endif /* AVCODEC_PS_H */
diff --git a/libavcodec/aacps_tablegen.c b/libavcodec/aacps_tablegen.c
new file mode 100644
index 0000000..8650226
--- /dev/null
+++ b/libavcodec/aacps_tablegen.c
@@ -0,0 +1,93 @@
+/*
+ * Generate a header file for hardcoded Parametric Stereo tables
+ *
+ * Copyright (c) 2010 Alex Converse <alex.converse at gmail.com>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <stdlib.h>
+#define CONFIG_HARDCODED_TABLES 0
+#include "aacps_tablegen.h"
+#include "tableprint.h"
+
+void write_float_3d_array (const void *p, int b, int c, int d)
+{
+    int i;
+    const float *f = p;
+    for (i = 0; i < b; i++) {
+        printf("{\n");
+        write_float_2d_array(f, c, d);
+        printf("},\n");
+        f += c * d;
+    }
+}
+
+void write_float_4d_array (const void *p, int a, int b, int c, int d)
+{
+    int i;
+    const float *f = p;
+    for (i = 0; i < a; i++) {
+        printf("{\n");
+        write_float_3d_array(f, b, c, d);
+        printf("},\n");
+        f += b * c * d;
+    }
+}
+
+int main(void)
+{
+    ps_tableinit();
+
+    write_fileheader();
+
+    printf("static const float pd_re_smooth[8*8*8] = {\n");
+    write_float_array(pd_re_smooth, 8*8*8);
+    printf("};\n");
+    printf("static const float pd_im_smooth[8*8*8] = {\n");
+    write_float_array(pd_im_smooth, 8*8*8);
+    printf("};\n");
+
+    printf("static const float HA[46][8][4] = {\n");
+    write_float_3d_array(HA, 46, 8, 4);
+    printf("};\n");
+    printf("static const float HB[46][8][4] = {\n");
+    write_float_3d_array(HB, 46, 8, 4);
+    printf("};\n");
+
+    printf("static const float f20_0_8[8][7][2] = {\n");
+    write_float_3d_array(f20_0_8, 8, 7, 2);
+    printf("};\n");
+    printf("static const float f34_0_12[12][7][2] = {\n");
+    write_float_3d_array(f34_0_12, 12, 7, 2);
+    printf("};\n");
+    printf("static const float f34_1_8[8][7][2] = {\n");
+    write_float_3d_array(f34_1_8, 8, 7, 2);
+    printf("};\n");
+    printf("static const float f34_2_4[4][7][2] = {\n");
+    write_float_3d_array(f34_2_4, 4, 7, 2);
+    printf("};\n");
+
+    printf("static const float Q_fract_allpass[2][50][3][2] = {\n");
+    write_float_4d_array(Q_fract_allpass, 2, 50, 3, 2);
+    printf("};\n");
+    printf("static const float phi_fract[2][50][2] = {\n");
+    write_float_3d_array(phi_fract, 2, 50, 2);
+    printf("};\n");
+
+    return 0;
+}
diff --git a/libavcodec/aacps_tablegen.h b/libavcodec/aacps_tablegen.h
new file mode 100644
index 0000000..492cb0c
--- /dev/null
+++ b/libavcodec/aacps_tablegen.h
@@ -0,0 +1,212 @@
+/*
+ * Header file for hardcoded Parametric Stereo tables
+ *
+ * Copyright (c) 2010 Alex Converse <alex.converse at gmail.com>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AACPS_TABLEGEN_H
+#define AACPS_TABLEGEN_H
+
+#include <stdint.h>
+
+#if CONFIG_HARDCODED_TABLES
+#define ps_tableinit()
+#include "libavcodec/aacps_tables.h"
+#else
+#include "libavutil/common.h"
+#include "libavutil/mathematics.h"
+#define NR_ALLPASS_BANDS20 30
+#define NR_ALLPASS_BANDS34 50
+#define PS_AP_LINKS 3
+static float pd_re_smooth[8*8*8];
+static float pd_im_smooth[8*8*8];
+static float HA[46][8][4];
+static float HB[46][8][4];
+static float f20_0_8 [ 8][7][2];
+static float f34_0_12[12][7][2];
+static float f34_1_8 [ 8][7][2];
+static float f34_2_4 [ 4][7][2];
+static float Q_fract_allpass[2][50][3][2];
+static float phi_fract[2][50][2];
+
+static const float g0_Q8[] = {
+    0.00746082949812f, 0.02270420949825f, 0.04546865930473f, 0.07266113929591f,
+    0.09885108575264f, 0.11793710567217f, 0.125f
+};
+
+static const float g0_Q12[] = {
+    0.04081179924692f, 0.03812810994926f, 0.05144908135699f, 0.06399831151592f,
+    0.07428313801106f, 0.08100347892914f, 0.08333333333333f
+};
+
+static const float g1_Q8[] = {
+    0.01565675600122f, 0.03752716391991f, 0.05417891378782f, 0.08417044116767f,
+    0.10307344158036f, 0.12222452249753f, 0.125f
+};
+
+static const float g2_Q4[] = {
+    -0.05908211155639f, -0.04871498374946f, 0.0f,   0.07778723915851f,
+     0.16486303567403f,  0.23279856662996f, 0.25f
+};
+
+static void make_filters_from_proto(float (*filter)[7][2], const float *proto, int bands)
+{
+    int q, n;
+    for (q = 0; q < bands; q++) {
+        for (n = 0; n < 7; n++) {
+            double theta = 2 * M_PI * (q + 0.5) * (n - 6) / bands;
+            filter[q][n][0] = proto[n] *  cos(theta);
+            filter[q][n][1] = proto[n] * -sin(theta);
+        }
+    }
+}
+
+static void ps_tableinit(void)
+{
+    static const float ipdopd_sin[] = { 0, M_SQRT1_2, 1,  M_SQRT1_2,  0, -M_SQRT1_2, -1, -M_SQRT1_2 };
+    static const float ipdopd_cos[] = { 1, M_SQRT1_2, 0, -M_SQRT1_2, -1, -M_SQRT1_2,  0,  M_SQRT1_2 };
+    int pd0, pd1, pd2;
+
+    static const float iid_par_dequant[] = {
+        //iid_par_dequant_default
+        0.05623413251903, 0.12589254117942, 0.19952623149689, 0.31622776601684,
+        0.44668359215096, 0.63095734448019, 0.79432823472428, 1,
+        1.25892541179417, 1.58489319246111, 2.23872113856834, 3.16227766016838,
+        5.01187233627272, 7.94328234724282, 17.7827941003892,
+        //iid_par_dequant_fine
+        0.00316227766017, 0.00562341325190, 0.01,             0.01778279410039,
+        0.03162277660168, 0.05623413251903, 0.07943282347243, 0.11220184543020,
+        0.15848931924611, 0.22387211385683, 0.31622776601684, 0.39810717055350,
+        0.50118723362727, 0.63095734448019, 0.79432823472428, 1,
+        1.25892541179417, 1.58489319246111, 1.99526231496888, 2.51188643150958,
+        3.16227766016838, 4.46683592150963, 6.30957344480193, 8.91250938133745,
+        12.5892541179417, 17.7827941003892, 31.6227766016838, 56.2341325190349,
+        100,              177.827941003892, 316.227766016837,
+    };
+    static const float icc_invq[] = {
+        1, 0.937,      0.84118,    0.60092,    0.36764,   0,      -0.589,    -1
+    };
+    static const float acos_icc_invq[] = {
+        0, 0.35685527, 0.57133466, 0.92614472, 1.1943263, M_PI/2, 2.2006171, M_PI
+    };
+    int iid, icc;
+
+    int k, m;
+    static const int8_t f_center_20[] = {
+        -3, -1, 1, 3, 5, 7, 10, 14, 18, 22,
+    };
+    static const int8_t f_center_34[] = {
+         2,  6, 10, 14, 18, 22, 26, 30,
+        34,-10, -6, -2, 51, 57, 15, 21,
+        27, 33, 39, 45, 54, 66, 78, 42,
+       102, 66, 78, 90,102,114,126, 90,
+    };
+    static const float fractional_delay_links[] = { 0.43f, 0.75f, 0.347f };
+    const float fractional_delay_gain = 0.39f;
+
+    for (pd0 = 0; pd0 < 8; pd0++) {
+        float pd0_re = ipdopd_cos[pd0];
+        float pd0_im = ipdopd_sin[pd0];
+        for (pd1 = 0; pd1 < 8; pd1++) {
+            float pd1_re = ipdopd_cos[pd1];
+            float pd1_im = ipdopd_sin[pd1];
+            for (pd2 = 0; pd2 < 8; pd2++) {
+                float pd2_re = ipdopd_cos[pd2];
+                float pd2_im = ipdopd_sin[pd2];
+                float re_smooth = 0.25f * pd0_re + 0.5f * pd1_re + pd2_re;
+                float im_smooth = 0.25f * pd0_im + 0.5f * pd1_im + pd2_im;
+                float pd_mag = 1 / sqrt(im_smooth * im_smooth + re_smooth * re_smooth);
+                pd_re_smooth[pd0*64+pd1*8+pd2] = re_smooth * pd_mag;
+                pd_im_smooth[pd0*64+pd1*8+pd2] = im_smooth * pd_mag;
+            }
+        }
+    }
+
+    for (iid = 0; iid < 46; iid++) {
+        float c = iid_par_dequant[iid]; //<Linear Inter-channel Intensity Difference
+        float c1 = (float)M_SQRT2 / sqrtf(1.0f + c*c);
+        float c2 = c * c1;
+        for (icc = 0; icc < 8; icc++) {
+            /*if (PS_BASELINE || ps->icc_mode < 3)*/ {
+                float alpha = 0.5f * acos_icc_invq[icc];
+                float beta  = alpha * (c1 - c2) * (float)M_SQRT1_2;
+                HA[iid][icc][0] = c2 * cosf(beta + alpha);
+                HA[iid][icc][1] = c1 * cosf(beta - alpha);
+                HA[iid][icc][2] = c2 * sinf(beta + alpha);
+                HA[iid][icc][3] = c1 * sinf(beta - alpha);
+            } /* else */ {
+                float alpha, gamma, mu, rho;
+                float alpha_c, alpha_s, gamma_c, gamma_s;
+                rho = FFMAX(icc_invq[icc], 0.05f);
+                alpha = 0.5f * atan2f(2.0f * c * rho, c*c - 1.0f);
+                mu = c + 1.0f / c;
+                mu = sqrtf(1 + (4 * rho * rho - 4)/(mu * mu));
+                gamma = atanf(sqrtf((1.0f - mu)/(1.0f + mu)));
+                if (alpha < 0) alpha += M_PI/2;
+                alpha_c = cosf(alpha);
+                alpha_s = sinf(alpha);
+                gamma_c = cosf(gamma);
+                gamma_s = sinf(gamma);
+                HB[iid][icc][0] =  M_SQRT2 * alpha_c * gamma_c;
+                HB[iid][icc][1] =  M_SQRT2 * alpha_s * gamma_c;
+                HB[iid][icc][2] = -M_SQRT2 * alpha_s * gamma_s;
+                HB[iid][icc][3] =  M_SQRT2 * alpha_c * gamma_s;
+            }
+        }
+    }
+
+    for (k = 0; k < NR_ALLPASS_BANDS20; k++) {
+        double f_center, theta;
+        if (k < FF_ARRAY_ELEMS(f_center_20))
+            f_center = f_center_20[k] * 0.125;
+        else
+            f_center = k - 6.5f;
+        for (m = 0; m < PS_AP_LINKS; m++) {
+            theta = -M_PI * fractional_delay_links[m] * f_center;
+            Q_fract_allpass[0][k][m][0] = cos(theta);
+            Q_fract_allpass[0][k][m][1] = sin(theta);
+        }
+        theta = -M_PI*fractional_delay_gain*f_center;
+        phi_fract[0][k][0] = cos(theta);
+        phi_fract[0][k][1] = sin(theta);
+    }
+    for (k = 0; k < NR_ALLPASS_BANDS34; k++) {
+        double f_center, theta;
+        if (k < FF_ARRAY_ELEMS(f_center_34))
+            f_center = f_center_34[k] / 24.;
+        else
+            f_center = k - 26.5f;
+        for (m = 0; m < PS_AP_LINKS; m++) {
+            theta = -M_PI * fractional_delay_links[m] * f_center;
+            Q_fract_allpass[1][k][m][0] = cos(theta);
+            Q_fract_allpass[1][k][m][1] = sin(theta);
+        }
+        theta = -M_PI*fractional_delay_gain*f_center;
+        phi_fract[1][k][0] = cos(theta);
+        phi_fract[1][k][1] = sin(theta);
+    }
+
+    make_filters_from_proto(f20_0_8,  g0_Q8,   8);
+    make_filters_from_proto(f34_0_12, g0_Q12, 12);
+    make_filters_from_proto(f34_1_8,  g1_Q8,   8);
+    make_filters_from_proto(f34_2_4,  g2_Q4,   4);
+}
+#endif /* CONFIG_HARDCODED_TABLES */
+
+#endif /* AACPS_TABLEGEN_H */
diff --git a/libavcodec/aacpsdata.c b/libavcodec/aacpsdata.c
new file mode 100644
index 0000000..675bd8e
--- /dev/null
+++ b/libavcodec/aacpsdata.c
@@ -0,0 +1,163 @@
+/*
+ * MPEG-4 Parametric Stereo data tables
+ * Copyright (c) 2010 Alex Converse <alex.converse at gmail.com>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+static const uint8_t huff_iid_df1_bits[] = {
+    18, 18, 18, 18, 18, 18, 18, 18, 18, 17, 18, 17, 17, 16, 16, 15, 14, 14,
+    13, 12, 12, 11, 10, 10,  8,  7,  6,  5,  4,  3,  1,  3,  4,  5,  6,  7,
+     8,  9, 10, 11, 11, 12, 13, 14, 14, 15, 16, 16, 17, 17, 18, 17, 18, 18,
+    18, 18, 18, 18, 18, 18, 18,
+};
+
+static const uint32_t huff_iid_df1_codes[] = {
+    0x01FEB4, 0x01FEB5, 0x01FD76, 0x01FD77, 0x01FD74, 0x01FD75, 0x01FE8A,
+    0x01FE8B, 0x01FE88, 0x00FE80, 0x01FEB6, 0x00FE82, 0x00FEB8, 0x007F42,
+    0x007FAE, 0x003FAF, 0x001FD1, 0x001FE9, 0x000FE9, 0x0007EA, 0x0007FB,
+    0x0003FB, 0x0001FB, 0x0001FF, 0x00007C, 0x00003C, 0x00001C, 0x00000C,
+    0x000000, 0x000001, 0x000001, 0x000002, 0x000001, 0x00000D, 0x00001D,
+    0x00003D, 0x00007D, 0x0000FC, 0x0001FC, 0x0003FC, 0x0003F4, 0x0007EB,
+    0x000FEA, 0x001FEA, 0x001FD6, 0x003FD0, 0x007FAF, 0x007F43, 0x00FEB9,
+    0x00FE83, 0x01FEB7, 0x00FE81, 0x01FE89, 0x01FE8E, 0x01FE8F, 0x01FE8C,
+    0x01FE8D, 0x01FEB2, 0x01FEB3, 0x01FEB0, 0x01FEB1,
+};
+
+static const uint8_t huff_iid_dt1_bits[] = {
+    16, 16, 16, 16, 16, 16, 16, 16, 16, 15, 15, 15, 15, 15, 15, 14, 14, 13,
+    13, 13, 12, 12, 11, 10,  9,  9,  7,  6,  5,  3,  1,  2,  5,  6,  7,  8,
+     9, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16,
+    16, 16, 16, 16, 16, 16, 16,
+};
+
+static const uint16_t huff_iid_dt1_codes[] = {
+    0x004ED4, 0x004ED5, 0x004ECE, 0x004ECF, 0x004ECC, 0x004ED6, 0x004ED8,
+    0x004F46, 0x004F60, 0x002718, 0x002719, 0x002764, 0x002765, 0x00276D,
+    0x0027B1, 0x0013B7, 0x0013D6, 0x0009C7, 0x0009E9, 0x0009ED, 0x0004EE,
+    0x0004F7, 0x000278, 0x000139, 0x00009A, 0x00009F, 0x000020, 0x000011,
+    0x00000A, 0x000003, 0x000001, 0x000000, 0x00000B, 0x000012, 0x000021,
+    0x00004C, 0x00009B, 0x00013A, 0x000279, 0x000270, 0x0004EF, 0x0004E2,
+    0x0009EA, 0x0009D8, 0x0013D7, 0x0013D0, 0x0027B2, 0x0027A2, 0x00271A,
+    0x00271B, 0x004F66, 0x004F67, 0x004F61, 0x004F47, 0x004ED9, 0x004ED7,
+    0x004ECD, 0x004ED2, 0x004ED3, 0x004ED0, 0x004ED1,
+};
+
+static const uint8_t huff_iid_df0_bits[] = {
+    17, 17, 17, 17, 16, 15, 13, 10,  9,  7,  6,  5,  4,  3,  1,  3,  4,  5,
+     6,  6,  8, 11, 13, 14, 14, 15, 17, 18, 18,
+};
+
+static const uint32_t huff_iid_df0_codes[] = {
+    0x01FFFB, 0x01FFFC, 0x01FFFD, 0x01FFFA, 0x00FFFC, 0x007FFC, 0x001FFD,
+    0x0003FE, 0x0001FE, 0x00007E, 0x00003C, 0x00001D, 0x00000D, 0x000005,
+    0x000000, 0x000004, 0x00000C, 0x00001C, 0x00003D, 0x00003E, 0x0000FE,
+    0x0007FE, 0x001FFC, 0x003FFC, 0x003FFD, 0x007FFD, 0x01FFFE, 0x03FFFE,
+    0x03FFFF,
+};
+
+static const uint8_t huff_iid_dt0_bits[] = {
+    19, 19, 19, 20, 20, 20, 17, 15, 12, 10,  8,  6,  4,  2,  1,  3,  5,  7,
+     9, 11, 13, 14, 17, 19, 20, 20, 20, 20, 20,
+};
+
+static const uint32_t huff_iid_dt0_codes[] = {
+    0x07FFF9, 0x07FFFA, 0x07FFFB, 0x0FFFF8, 0x0FFFF9, 0x0FFFFA, 0x01FFFD,
+    0x007FFE, 0x000FFE, 0x0003FE, 0x0000FE, 0x00003E, 0x00000E, 0x000002,
+    0x000000, 0x000006, 0x00001E, 0x00007E, 0x0001FE, 0x0007FE, 0x001FFE,
+    0x003FFE, 0x01FFFC, 0x07FFF8, 0x0FFFFB, 0x0FFFFC, 0x0FFFFD, 0x0FFFFE,
+    0x0FFFFF,
+};
+
+static const uint8_t huff_icc_df_bits[] = {
+    14, 14, 12, 10, 7, 5, 3, 1, 2, 4, 6, 8, 9, 11, 13,
+};
+
+static const uint16_t huff_icc_df_codes[] = {
+    0x3FFF, 0x3FFE, 0x0FFE, 0x03FE, 0x007E, 0x001E, 0x0006, 0x0000,
+    0x0002, 0x000E, 0x003E, 0x00FE, 0x01FE, 0x07FE, 0x1FFE,
+};
+
+static const uint8_t huff_icc_dt_bits[] = {
+    14, 13, 11, 9, 7, 5, 3, 1, 2, 4, 6, 8, 10, 12, 14,
+};
+
+static const uint16_t huff_icc_dt_codes[] = {
+    0x3FFE, 0x1FFE, 0x07FE, 0x01FE, 0x007E, 0x001E, 0x0006, 0x0000,
+    0x0002, 0x000E, 0x003E, 0x00FE, 0x03FE, 0x0FFE, 0x3FFF,
+};
+
+static const uint8_t huff_ipd_df_bits[] = {
+    1, 3, 4, 4, 4, 4, 4, 4,
+};
+
+static const uint8_t huff_ipd_df_codes[] = {
+    0x01, 0x00, 0x06, 0x04, 0x02, 0x03, 0x05, 0x07,
+};
+
+static const uint8_t huff_ipd_dt_bits[] = {
+    1, 3, 4, 5, 5, 4, 4, 3,
+};
+
+static const uint8_t huff_ipd_dt_codes[] = {
+    0x01, 0x02, 0x02, 0x03, 0x02, 0x00, 0x03, 0x03,
+};
+
+static const uint8_t huff_opd_df_bits[] = {
+    1, 3, 4, 4, 5, 5, 4, 3,
+};
+
+static const uint8_t huff_opd_df_codes[] = {
+    0x01, 0x01, 0x06, 0x04, 0x0F, 0x0E, 0x05, 0x00,
+};
+
+static const uint8_t huff_opd_dt_bits[] = {
+    1, 3, 4, 5, 5, 4, 4, 3,
+};
+
+static const uint8_t huff_opd_dt_codes[] = {
+    0x01, 0x02, 0x01, 0x07, 0x06, 0x00, 0x02, 0x03,
+};
+
+static const int8_t huff_offset[] = {
+    30, 30,
+    14, 14,
+    7, 7,
+    0, 0,
+    0, 0,
+};
+
+///Table 8.48
+static const int8_t k_to_i_20[] = {
+     1,  0,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 14, 15,
+    15, 15, 16, 16, 16, 16, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18,
+    18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+    19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19
+};
+///Table 8.49
+static const int8_t k_to_i_34[] = {
+     0,  1,  2,  3,  4,  5,  6,  6,  7,  2,  1,  0, 10, 10,  4,  5,  6,  7,  8,
+     9, 10, 11, 12,  9, 14, 11, 12, 13, 14, 15, 16, 13, 16, 17, 18, 19, 20, 21,
+    22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 27, 28, 28, 28, 29, 29, 29,
+    30, 30, 30, 31, 31, 31, 31, 32, 32, 32, 32, 33, 33, 33, 33, 33, 33, 33, 33,
+    33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33
+};
+
+static const float g1_Q2[] = {
+    0.0f,  0.01899487526049f, 0.0f, -0.07293139167538f,
+    0.0f,  0.30596630545168f, 0.5f
+};
diff --git a/libavcodec/aacpsy.c b/libavcodec/aacpsy.c
index 53dac3d..4250a5d 100644
--- a/libavcodec/aacpsy.c
+++ b/libavcodec/aacpsy.c
@@ -2,20 +2,20 @@
  * AAC encoder psychoacoustic model
  * Copyright (C) 2008 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -39,11 +39,19 @@
  * constants for 3GPP AAC psychoacoustic model
  * @{
  */
-#define PSY_3GPP_SPREAD_LOW  1.5f // spreading factor for ascending threshold spreading  (15 dB/Bark)
-#define PSY_3GPP_SPREAD_HI   3.0f // spreading factor for descending threshold spreading (30 dB/Bark)
+#define PSY_3GPP_THR_SPREAD_HI   1.5f // spreading factor for low-to-hi threshold spreading  (15 dB/Bark)
+#define PSY_3GPP_THR_SPREAD_LOW  3.0f // spreading factor for hi-to-low threshold spreading  (30 dB/Bark)
 
 #define PSY_3GPP_RPEMIN      0.01f
 #define PSY_3GPP_RPELEV      2.0f
+
+/* LAME psy model constants */
+#define PSY_LAME_FIR_LEN 21         ///< LAME psy model FIR order
+#define AAC_BLOCK_SIZE_LONG 1024    ///< long block size
+#define AAC_BLOCK_SIZE_SHORT 128    ///< short block size
+#define AAC_NUM_BLOCKS_SHORT 8      ///< number of blocks in a short sequence
+#define PSY_LAME_NUM_SUBBLOCKS 3    ///< Number of sub-blocks in each short block
+
 /**
  * @}
  */
@@ -51,44 +59,155 @@
 /**
  * information for single band used by 3GPP TS26.403-inspired psychoacoustic model
  */
-typedef struct Psy3gppBand{
+typedef struct AacPsyBand{
     float energy;    ///< band energy
-    float ffac;      ///< form factor
     float thr;       ///< energy threshold
-    float min_snr;   ///< minimal SNR
     float thr_quiet; ///< threshold in quiet
-}Psy3gppBand;
+}AacPsyBand;
 
 /**
  * single/pair channel context for psychoacoustic model
  */
-typedef struct Psy3gppChannel{
-    Psy3gppBand band[128];               ///< bands information
-    Psy3gppBand prev_band[128];          ///< bands information from the previous frame
+typedef struct AacPsyChannel{
+    AacPsyBand band[128];               ///< bands information
+    AacPsyBand prev_band[128];          ///< bands information from the previous frame
 
     float       win_energy;              ///< sliding average of channel energy
     float       iir_state[2];            ///< hi-pass IIR filter state
     uint8_t     next_grouping;           ///< stored grouping scheme for the next frame (in case of 8 short window sequence)
     enum WindowSequence next_window_seq; ///< window sequence to be used in the next frame
-}Psy3gppChannel;
+    /* LAME psy model specific members */
+    float attack_threshold;              ///< attack threshold for this channel
+    float prev_energy_subshort[AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS];
+    int   prev_attack;                   ///< attack value for the last short block in the previous sequence
+}AacPsyChannel;
 
 /**
  * psychoacoustic model frame type-dependent coefficients
  */
-typedef struct Psy3gppCoeffs{
-    float ath       [64]; ///< absolute threshold of hearing per bands
-    float barks     [64]; ///< Bark value for each spectral band in long frame
-    float spread_low[64]; ///< spreading factor for low-to-high threshold spreading in long frame
-    float spread_hi [64]; ///< spreading factor for high-to-low threshold spreading in long frame
-}Psy3gppCoeffs;
+typedef struct AacPsyCoeffs{
+    float ath;           ///< absolute threshold of hearing per bands
+    float barks;         ///< Bark value for each spectral band in long frame
+    float spread_low[2]; ///< spreading factor for low-to-high threshold spreading in long frame
+    float spread_hi [2]; ///< spreading factor for high-to-low threshold spreading in long frame
+    float min_snr;       ///< minimal SNR
+}AacPsyCoeffs;
 
 /**
  * 3GPP TS26.403-inspired psychoacoustic model specific data
  */
-typedef struct Psy3gppContext{
-    Psy3gppCoeffs psy_coef[2];
-    Psy3gppChannel *ch;
-}Psy3gppContext;
+typedef struct AacPsyContext{
+    AacPsyCoeffs psy_coef[2][64];
+    AacPsyChannel *ch;
+}AacPsyContext;
+
+/**
+ * LAME psy model preset struct
+ */
+typedef struct {
+    int   quality;  ///< Quality to map the rest of the vaules to.
+     /* This is overloaded to be both kbps per channel in ABR mode, and
+      * requested quality in constant quality mode.
+      */
+    float st_lrm;   ///< short threshold for L, R, and M channels
+} PsyLamePreset;
+
+/**
+ * LAME psy model preset table for ABR
+ */
+static const PsyLamePreset psy_abr_map[] = {
+/* TODO: Tuning. These were taken from LAME. */
+/* kbps/ch st_lrm   */
+    {  8,  6.60},
+    { 16,  6.60},
+    { 24,  6.60},
+    { 32,  6.60},
+    { 40,  6.60},
+    { 48,  6.60},
+    { 56,  6.60},
+    { 64,  6.40},
+    { 80,  6.00},
+    { 96,  5.60},
+    {112,  5.20},
+    {128,  5.20},
+    {160,  5.20}
+};
+
+/**
+* LAME psy model preset table for constant quality
+*/
+static const PsyLamePreset psy_vbr_map[] = {
+/* vbr_q  st_lrm    */
+    { 0,  4.20},
+    { 1,  4.20},
+    { 2,  4.20},
+    { 3,  4.20},
+    { 4,  4.20},
+    { 5,  4.20},
+    { 6,  4.20},
+    { 7,  4.20},
+    { 8,  4.20},
+    { 9,  4.20},
+    {10,  4.20}
+};
+
+/**
+ * LAME psy model FIR coefficient table
+ */
+static const float psy_fir_coeffs[] = {
+    -8.65163e-18 * 2, -0.00851586 * 2, -6.74764e-18 * 2, 0.0209036 * 2,
+    -3.36639e-17 * 2, -0.0438162 * 2,  -1.54175e-17 * 2, 0.0931738 * 2,
+    -5.52212e-17 * 2, -0.313819 * 2
+};
+
+/**
+ * calculates the attack threshold for ABR from the above table for the LAME psy model
+ */
+static float lame_calc_attack_threshold(int bitrate)
+{
+    /* Assume max bitrate to start with */
+    int lower_range = 12, upper_range = 12;
+    int lower_range_kbps = psy_abr_map[12].quality;
+    int upper_range_kbps = psy_abr_map[12].quality;
+    int i;
+
+    /* Determine which bitrates the value specified falls between.
+     * If the loop ends without breaking our above assumption of 320kbps was correct.
+     */
+    for (i = 1; i < 13; i++) {
+        if (FFMAX(bitrate, psy_abr_map[i].quality) != bitrate) {
+            upper_range = i;
+            upper_range_kbps = psy_abr_map[i    ].quality;
+            lower_range = i - 1;
+            lower_range_kbps = psy_abr_map[i - 1].quality;
+            break; /* Upper range found */
+        }
+    }
+
+    /* Determine which range the value specified is closer to */
+    if ((upper_range_kbps - bitrate) > (bitrate - lower_range_kbps))
+        return psy_abr_map[lower_range].st_lrm;
+    return psy_abr_map[upper_range].st_lrm;
+}
+
+/**
+ * LAME psy model specific initialization
+ */
+static void lame_window_init(AacPsyContext *ctx, AVCodecContext *avctx) {
+    int i, j;
+
+    for (i = 0; i < avctx->channels; i++) {
+        AacPsyChannel *pch = &ctx->ch[i];
+
+        if (avctx->flags & CODEC_FLAG_QSCALE)
+            pch->attack_threshold = psy_vbr_map[avctx->global_quality / FF_QP2LAMBDA].st_lrm;
+        else
+            pch->attack_threshold = lame_calc_attack_threshold(avctx->bit_rate / avctx->channels / 1000);
+
+        for (j = 0; j < AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS; j++)
+            pch->prev_energy_subshort[j] = 10.0f;
+    }
+}
 
 /**
  * Calculate Bark value for given line.
@@ -113,41 +232,47 @@ static av_cold float ath(float f, float add)
 }
 
 static av_cold int psy_3gpp_init(FFPsyContext *ctx) {
-    Psy3gppContext *pctx;
-    float barks[1024];
+    AacPsyContext *pctx;
+    float bark;
     int i, j, g, start;
     float prev, minscale, minath;
 
-    ctx->model_priv_data = av_mallocz(sizeof(Psy3gppContext));
-    pctx = (Psy3gppContext*) ctx->model_priv_data;
+    ctx->model_priv_data = av_mallocz(sizeof(AacPsyContext));
+    pctx = (AacPsyContext*) ctx->model_priv_data;
 
-    for (i = 0; i < 1024; i++)
-        barks[i] = calc_bark(i * ctx->avctx->sample_rate / 2048.0);
     minath = ath(3410, ATH_ADD);
     for (j = 0; j < 2; j++) {
-        Psy3gppCoeffs *coeffs = &pctx->psy_coef[j];
+        AacPsyCoeffs *coeffs = pctx->psy_coef[j];
+        const uint8_t *band_sizes = ctx->bands[j];
+        float line_to_frequency = ctx->avctx->sample_rate / (j ? 256.f : 2048.0f);
         i = 0;
         prev = 0.0;
         for (g = 0; g < ctx->num_bands[j]; g++) {
-            i += ctx->bands[j][g];
-            coeffs->barks[g] = (barks[i - 1] + prev) / 2.0;
-            prev = barks[i - 1];
+            i += band_sizes[g];
+            bark = calc_bark((i-1) * line_to_frequency);
+            coeffs[g].barks = (bark + prev) / 2.0;
+            prev = bark;
         }
         for (g = 0; g < ctx->num_bands[j] - 1; g++) {
-            coeffs->spread_low[g] = pow(10.0, -(coeffs->barks[g+1] - coeffs->barks[g]) * PSY_3GPP_SPREAD_LOW);
-            coeffs->spread_hi [g] = pow(10.0, -(coeffs->barks[g+1] - coeffs->barks[g]) * PSY_3GPP_SPREAD_HI);
+            AacPsyCoeffs *coeff = &coeffs[g];
+            float bark_width = coeffs[g+1].barks - coeffs->barks;
+            coeff->spread_low[0] = pow(10.0, -bark_width * PSY_3GPP_THR_SPREAD_LOW);
+            coeff->spread_hi [0] = pow(10.0, -bark_width * PSY_3GPP_THR_SPREAD_HI);
         }
         start = 0;
         for (g = 0; g < ctx->num_bands[j]; g++) {
-            minscale = ath(ctx->avctx->sample_rate * start / 1024.0, ATH_ADD);
-            for (i = 1; i < ctx->bands[j][g]; i++)
-                minscale = FFMIN(minscale, ath(ctx->avctx->sample_rate * (start + i) / 1024.0 / 2.0, ATH_ADD));
-            coeffs->ath[g] = minscale - minath;
-            start += ctx->bands[j][g];
+            minscale = ath(start * line_to_frequency, ATH_ADD);
+            for (i = 1; i < band_sizes[g]; i++)
+                minscale = FFMIN(minscale, ath((start + i) * line_to_frequency, ATH_ADD));
+            coeffs[g].ath = minscale - minath;
+            start += band_sizes[g];
         }
     }
 
-    pctx->ch = av_mallocz(sizeof(Psy3gppChannel) * ctx->avctx->channels);
+    pctx->ch = av_mallocz(sizeof(AacPsyChannel) * ctx->avctx->channels);
+
+    lame_window_init(pctx, ctx->avctx);
+
     return 0;
 }
 
@@ -182,9 +307,10 @@ static FFPsyWindowInfo psy_3gpp_window(FFPsyContext *ctx,
     int i, j;
     int br               = ctx->avctx->bit_rate / ctx->avctx->channels;
     int attack_ratio     = br <= 16000 ? 18 : 10;
-    Psy3gppContext *pctx = (Psy3gppContext*) ctx->model_priv_data;
-    Psy3gppChannel *pch  = &pctx->ch[channel];
+    AacPsyContext *pctx = (AacPsyContext*) ctx->model_priv_data;
+    AacPsyChannel *pch  = &pctx->ch[channel];
     uint8_t grouping     = 0;
+    int next_type        = pch->next_window_seq;
     FFPsyWindowInfo wi;
 
     memset(&wi, 0, sizeof(wi));
@@ -193,9 +319,10 @@ static FFPsyWindowInfo psy_3gpp_window(FFPsyContext *ctx,
         int switch_to_eight = 0;
         float sum = 0.0, sum2 = 0.0;
         int attack_n = 0;
+        int stay_short = 0;
         for (i = 0; i < 8; i++) {
             for (j = 0; j < 128; j++) {
-                v = iir_filter(audio[(i*128+j)*ctx->avctx->channels], pch->iir_state);
+                v = iir_filter(la[(i*128+j)*ctx->avctx->channels], pch->iir_state);
                 sum += v*v;
             }
             s[i]  = sum;
@@ -214,20 +341,27 @@ static FFPsyWindowInfo psy_3gpp_window(FFPsyContext *ctx,
         switch (prev_type) {
         case ONLY_LONG_SEQUENCE:
             wi.window_type[0] = switch_to_eight ? LONG_START_SEQUENCE : ONLY_LONG_SEQUENCE;
+            next_type = switch_to_eight ? EIGHT_SHORT_SEQUENCE : ONLY_LONG_SEQUENCE;
             break;
         case LONG_START_SEQUENCE:
             wi.window_type[0] = EIGHT_SHORT_SEQUENCE;
             grouping = pch->next_grouping;
+            next_type = switch_to_eight ? EIGHT_SHORT_SEQUENCE : LONG_STOP_SEQUENCE;
             break;
         case LONG_STOP_SEQUENCE:
-            wi.window_type[0] = ONLY_LONG_SEQUENCE;
+            wi.window_type[0] = switch_to_eight ? LONG_START_SEQUENCE : ONLY_LONG_SEQUENCE;
+            next_type = switch_to_eight ? EIGHT_SHORT_SEQUENCE : ONLY_LONG_SEQUENCE;
             break;
         case EIGHT_SHORT_SEQUENCE:
-            wi.window_type[0] = switch_to_eight ? EIGHT_SHORT_SEQUENCE : LONG_STOP_SEQUENCE;
-            grouping = switch_to_eight ? pch->next_grouping : 0;
+            stay_short = next_type == EIGHT_SHORT_SEQUENCE || switch_to_eight;
+            wi.window_type[0] = stay_short ? EIGHT_SHORT_SEQUENCE : LONG_STOP_SEQUENCE;
+            grouping = next_type == EIGHT_SHORT_SEQUENCE ? pch->next_grouping : 0;
+            next_type = switch_to_eight ? EIGHT_SHORT_SEQUENCE : LONG_STOP_SEQUENCE;
             break;
         }
+
         pch->next_grouping = window_grouping[attack_n];
+        pch->next_window_seq = next_type;
     } else {
         for (i = 0; i < 3; i++)
             wi.window_type[i] = prev_type;
@@ -255,64 +389,238 @@ static FFPsyWindowInfo psy_3gpp_window(FFPsyContext *ctx,
  * Calculate band thresholds as suggested in 3GPP TS26.403
  */
 static void psy_3gpp_analyze(FFPsyContext *ctx, int channel,
-                             const float *coefs, FFPsyWindowInfo *wi)
+                             const float *coefs, const FFPsyWindowInfo *wi)
 {
-    Psy3gppContext *pctx = (Psy3gppContext*) ctx->model_priv_data;
-    Psy3gppChannel *pch  = &pctx->ch[channel];
+    AacPsyContext *pctx = (AacPsyContext*) ctx->model_priv_data;
+    AacPsyChannel *pch  = &pctx->ch[channel];
     int start = 0;
     int i, w, g;
-    const int num_bands       = ctx->num_bands[wi->num_windows == 8];
-    const uint8_t* band_sizes = ctx->bands[wi->num_windows == 8];
-    Psy3gppCoeffs *coeffs     = &pctx->psy_coef[wi->num_windows == 8];
+    const int      num_bands  = ctx->num_bands[wi->num_windows == 8];
+    const uint8_t *band_sizes = ctx->bands[wi->num_windows == 8];
+    AacPsyCoeffs  *coeffs     = pctx->psy_coef[wi->num_windows == 8];
 
     //calculate energies, initial thresholds and related values - 5.4.2 "Threshold Calculation"
     for (w = 0; w < wi->num_windows*16; w += 16) {
         for (g = 0; g < num_bands; g++) {
-            Psy3gppBand *band = &pch->band[w+g];
+            AacPsyBand *band = &pch->band[w+g];
             band->energy = 0.0f;
             for (i = 0; i < band_sizes[g]; i++)
                 band->energy += coefs[start+i] * coefs[start+i];
-            band->energy *= 1.0f / (512*512);
             band->thr     = band->energy * 0.001258925f;
             start        += band_sizes[g];
-
-            ctx->psy_bands[channel*PSY_MAX_BANDS+w+g].energy = band->energy;
         }
     }
-    //modify thresholds - spread, threshold in quiet - 5.4.3 "Spreaded Energy Calculation"
+    //modify thresholds and energies - spread, threshold in quiet, pre-echo control
     for (w = 0; w < wi->num_windows*16; w += 16) {
-        Psy3gppBand *band = &pch->band[w];
+        AacPsyBand *bands = &pch->band[w];
+        //5.4.2.3 "Spreading" & 5.4.3 "Spreaded Energy Calculation"
         for (g = 1; g < num_bands; g++)
-            band[g].thr = FFMAX(band[g].thr, band[g-1].thr * coeffs->spread_low[g-1]);
+            bands[g].thr = FFMAX(bands[g].thr, bands[g-1].thr * coeffs[g].spread_hi[0]);
         for (g = num_bands - 2; g >= 0; g--)
-            band[g].thr = FFMAX(band[g].thr, band[g+1].thr * coeffs->spread_hi [g]);
+            bands[g].thr = FFMAX(bands[g].thr, bands[g+1].thr * coeffs[g].spread_low[0]);
+        //5.4.2.4 "Threshold in quiet"
+        for (g = 0; g < num_bands; g++) {
+            AacPsyBand *band = &bands[g];
+            band->thr_quiet = band->thr = FFMAX(band->thr, coeffs[g].ath);
+            //5.4.2.5 "Pre-echo control"
+            if (!(wi->window_type[0] == LONG_STOP_SEQUENCE || (wi->window_type[1] == LONG_START_SEQUENCE && !w)))
+                band->thr = FFMAX(PSY_3GPP_RPEMIN*band->thr, FFMIN(band->thr,
+                                  PSY_3GPP_RPELEV*pch->prev_band[w+g].thr_quiet));
+        }
+    }
+
+    for (w = 0; w < wi->num_windows*16; w += 16) {
         for (g = 0; g < num_bands; g++) {
-            band[g].thr_quiet = FFMAX(band[g].thr, coeffs->ath[g]);
-            if (wi->num_windows != 8 && wi->window_type[1] != EIGHT_SHORT_SEQUENCE)
-                band[g].thr_quiet = FFMAX(PSY_3GPP_RPEMIN*band[g].thr_quiet,
-                                          FFMIN(band[g].thr_quiet,
-                                          PSY_3GPP_RPELEV*pch->prev_band[w+g].thr_quiet));
-            band[g].thr = FFMAX(band[g].thr, band[g].thr_quiet * 0.25);
-
-            ctx->psy_bands[channel*PSY_MAX_BANDS+w+g].threshold = band[g].thr;
+            AacPsyBand *band     = &pch->band[w+g];
+            FFPsyBand  *psy_band = &ctx->psy_bands[channel*PSY_MAX_BANDS+w+g];
+
+            psy_band->threshold = band->thr;
+            psy_band->energy    = band->energy;
         }
     }
+
     memcpy(pch->prev_band, pch->band, sizeof(pch->band));
 }
 
 static av_cold void psy_3gpp_end(FFPsyContext *apc)
 {
-    Psy3gppContext *pctx = (Psy3gppContext*) apc->model_priv_data;
+    AacPsyContext *pctx = (AacPsyContext*) apc->model_priv_data;
     av_freep(&pctx->ch);
     av_freep(&apc->model_priv_data);
 }
 
+static void lame_apply_block_type(AacPsyChannel *ctx, FFPsyWindowInfo *wi, int uselongblock)
+{
+    int blocktype = ONLY_LONG_SEQUENCE;
+    if (uselongblock) {
+        if (ctx->next_window_seq == EIGHT_SHORT_SEQUENCE)
+            blocktype = LONG_STOP_SEQUENCE;
+    } else {
+        blocktype = EIGHT_SHORT_SEQUENCE;
+        if (ctx->next_window_seq == ONLY_LONG_SEQUENCE)
+            ctx->next_window_seq = LONG_START_SEQUENCE;
+        if (ctx->next_window_seq == LONG_STOP_SEQUENCE)
+            ctx->next_window_seq = EIGHT_SHORT_SEQUENCE;
+    }
+
+    wi->window_type[0] = ctx->next_window_seq;
+    ctx->next_window_seq = blocktype;
+}
+
+static FFPsyWindowInfo psy_lame_window(FFPsyContext *ctx,
+                                       const int16_t *audio, const int16_t *la,
+                                       int channel, int prev_type)
+{
+    AacPsyContext *pctx = (AacPsyContext*) ctx->model_priv_data;
+    AacPsyChannel *pch  = &pctx->ch[channel];
+    int grouping     = 0;
+    int uselongblock = 1;
+    int attacks[AAC_NUM_BLOCKS_SHORT + 1] = { 0 };
+    int i;
+    FFPsyWindowInfo wi;
+
+    memset(&wi, 0, sizeof(wi));
+    if (la) {
+        float hpfsmpl[AAC_BLOCK_SIZE_LONG];
+        float const *pf = hpfsmpl;
+        float attack_intensity[(AAC_NUM_BLOCKS_SHORT + 1) * PSY_LAME_NUM_SUBBLOCKS];
+        float energy_subshort[(AAC_NUM_BLOCKS_SHORT + 1) * PSY_LAME_NUM_SUBBLOCKS];
+        float energy_short[AAC_NUM_BLOCKS_SHORT + 1] = { 0 };
+        int chans = ctx->avctx->channels;
+        const int16_t *firbuf = la + (AAC_BLOCK_SIZE_SHORT/4 - PSY_LAME_FIR_LEN) * chans;
+        int j, att_sum = 0;
+
+        /* LAME comment: apply high pass filter of fs/4 */
+        for (i = 0; i < AAC_BLOCK_SIZE_LONG; i++) {
+            float sum1, sum2;
+            sum1 = firbuf[(i + ((PSY_LAME_FIR_LEN - 1) / 2)) * chans];
+            sum2 = 0.0;
+            for (j = 0; j < ((PSY_LAME_FIR_LEN - 1) / 2) - 1; j += 2) {
+                sum1 += psy_fir_coeffs[j] * (firbuf[(i + j) * chans] + firbuf[(i + PSY_LAME_FIR_LEN - j) * chans]);
+                sum2 += psy_fir_coeffs[j + 1] * (firbuf[(i + j + 1) * chans] + firbuf[(i + PSY_LAME_FIR_LEN - j - 1) * chans]);
+            }
+            hpfsmpl[i] = sum1 + sum2;
+        }
+
+        /* Calculate the energies of each sub-shortblock */
+        for (i = 0; i < PSY_LAME_NUM_SUBBLOCKS; i++) {
+            energy_subshort[i] = pch->prev_energy_subshort[i + ((AAC_NUM_BLOCKS_SHORT - 1) * PSY_LAME_NUM_SUBBLOCKS)];
+            assert(pch->prev_energy_subshort[i + ((AAC_NUM_BLOCKS_SHORT - 2) * PSY_LAME_NUM_SUBBLOCKS + 1)] > 0);
+            attack_intensity[i] = energy_subshort[i] / pch->prev_energy_subshort[i + ((AAC_NUM_BLOCKS_SHORT - 2) * PSY_LAME_NUM_SUBBLOCKS + 1)];
+            energy_short[0] += energy_subshort[i];
+        }
+
+        for (i = 0; i < AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS; i++) {
+            float const *const pfe = pf + AAC_BLOCK_SIZE_LONG / (AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS);
+            float p = 1.0f;
+            for (; pf < pfe; pf++)
+                if (p < fabsf(*pf))
+                    p = fabsf(*pf);
+            pch->prev_energy_subshort[i] = energy_subshort[i + PSY_LAME_NUM_SUBBLOCKS] = p;
+            energy_short[1 + i / PSY_LAME_NUM_SUBBLOCKS] += p;
+            /* FIXME: The indexes below are [i + 3 - 2] in the LAME source.
+             *          Obviously the 3 and 2 have some significance, or this would be just [i + 1]
+             *          (which is what we use here). What the 3 stands for is ambigious, as it is both
+             *          number of short blocks, and the number of sub-short blocks.
+             *          It seems that LAME is comparing each sub-block to sub-block + 1 in the
+             *          previous block.
+             */
+            if (p > energy_subshort[i + 1])
+                p = p / energy_subshort[i + 1];
+            else if (energy_subshort[i + 1] > p * 10.0f)
+                p = energy_subshort[i + 1] / (p * 10.0f);
+            else
+                p = 0.0;
+            attack_intensity[i + PSY_LAME_NUM_SUBBLOCKS] = p;
+        }
+
+        /* compare energy between sub-short blocks */
+        for (i = 0; i < (AAC_NUM_BLOCKS_SHORT + 1) * PSY_LAME_NUM_SUBBLOCKS; i++)
+            if (!attacks[i / PSY_LAME_NUM_SUBBLOCKS])
+                if (attack_intensity[i] > pch->attack_threshold)
+                    attacks[i / PSY_LAME_NUM_SUBBLOCKS] = (i % PSY_LAME_NUM_SUBBLOCKS) + 1;
+
+        /* should have energy change between short blocks, in order to avoid periodic signals */
+        /* Good samples to show the effect are Trumpet test songs */
+        /* GB: tuned (1) to avoid too many short blocks for test sample TRUMPET */
+        /* RH: tuned (2) to let enough short blocks through for test sample FSOL and SNAPS */
+        for (i = 1; i < AAC_NUM_BLOCKS_SHORT + 1; i++) {
+            float const u = energy_short[i - 1];
+            float const v = energy_short[i];
+            float const m = FFMAX(u, v);
+            if (m < 40000) {                          /* (2) */
+                if (u < 1.7f * v && v < 1.7f * u) {   /* (1) */
+                    if (i == 1 && attacks[0] < attacks[i])
+                        attacks[0] = 0;
+                    attacks[i] = 0;
+                }
+            }
+            att_sum += attacks[i];
+        }
+
+        if (attacks[0] <= pch->prev_attack)
+            attacks[0] = 0;
+
+        att_sum += attacks[0];
+        /* 3 below indicates the previous attack happened in the last sub-block of the previous sequence */
+        if (pch->prev_attack == 3 || att_sum) {
+            uselongblock = 0;
+
+            for (i = 1; i < AAC_NUM_BLOCKS_SHORT + 1; i++)
+                if (attacks[i] && attacks[i-1])
+                    attacks[i] = 0;
+        }
+    } else {
+        /* We have no lookahead info, so just use same type as the previous sequence. */
+        uselongblock = !(prev_type == EIGHT_SHORT_SEQUENCE);
+    }
+
+    lame_apply_block_type(pch, &wi, uselongblock);
+
+    wi.window_type[1] = prev_type;
+    if (wi.window_type[0] != EIGHT_SHORT_SEQUENCE) {
+        wi.num_windows  = 1;
+        wi.grouping[0]  = 1;
+        if (wi.window_type[0] == LONG_START_SEQUENCE)
+            wi.window_shape = 0;
+        else
+            wi.window_shape = 1;
+    } else {
+        int lastgrp = 0;
+
+        wi.num_windows = 8;
+        wi.window_shape = 0;
+        for (i = 0; i < 8; i++) {
+            if (!((pch->next_grouping >> i) & 1))
+                lastgrp = i;
+            wi.grouping[lastgrp]++;
+        }
+    }
+
+    /* Determine grouping, based on the location of the first attack, and save for
+     * the next frame.
+     * FIXME: Move this to analysis.
+     * TODO: Tune groupings depending on attack location
+     * TODO: Handle more than one attack in a group
+     */
+    for (i = 0; i < 9; i++) {
+        if (attacks[i]) {
+            grouping = i;
+            break;
+        }
+    }
+    pch->next_grouping = window_grouping[grouping];
+
+    pch->prev_attack = attacks[8];
+
+    return wi;
+}
 
 const FFPsyModel ff_aac_psy_model =
 {
     .name    = "3GPP TS 26.403-inspired model",
     .init    = psy_3gpp_init,
-    .window  = psy_3gpp_window,
+    .window  = psy_lame_window,
     .analyze = psy_3gpp_analyze,
     .end     = psy_3gpp_end,
 };
diff --git a/libavcodec/aacpsy.h b/libavcodec/aacpsy.h
index 05c93cd..5d1e142 100644
--- a/libavcodec/aacpsy.h
+++ b/libavcodec/aacpsy.h
@@ -2,20 +2,20 @@
  * AAC encoder psychoacoustic model
  * Copyright (C) 2008 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/aacsbr.c b/libavcodec/aacsbr.c
index 0de81a5..0df5249 100644
--- a/libavcodec/aacsbr.c
+++ b/libavcodec/aacsbr.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2008-2009 Robert Swain ( rob opendot cl )
  * Copyright (c) 2009-2010 Alex Converse <alex.converse at gmail.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -31,6 +31,7 @@
 #include "aacsbr.h"
 #include "aacsbrdata.h"
 #include "fft.h"
+#include "aacps.h"
 
 #include <stdint.h>
 #include <float.h>
@@ -71,9 +72,6 @@ enum {
 static VLC vlc_sbr[10];
 static const int8_t vlc_sbr_lav[10] =
     { 60, 60, 24, 24, 31, 31, 12, 12, 31, 12 };
-static DECLARE_ALIGNED(16, float, analysis_cos_pre)[64];
-static DECLARE_ALIGNED(16, float, analysis_sin_pre)[64];
-static DECLARE_ALIGNED(16, float, analysis_cossin_post)[32][2];
 static const DECLARE_ALIGNED(16, float, zero64)[64];
 
 #define SBR_INIT_VLC_STATIC(num, size) \
@@ -87,7 +85,7 @@ static const DECLARE_ALIGNED(16, float, zero64)[64];
 
 av_cold void ff_aac_sbr_init(void)
 {
-    int n, k;
+    int n;
     static const struct {
         const void *sbr_codes, *sbr_bits;
         const unsigned int table_size, elem_size;
@@ -116,16 +114,6 @@ av_cold void ff_aac_sbr_init(void)
     SBR_INIT_VLC_STATIC(8, 592);
     SBR_INIT_VLC_STATIC(9, 512);
 
-    for (n = 0; n < 64; n++) {
-        float pre = M_PI * n / 64;
-        analysis_cos_pre[n] = cosf(pre);
-        analysis_sin_pre[n] = sinf(pre);
-    }
-    for (k = 0; k < 32; k++) {
-        float post = M_PI * (k + 0.5) / 128;
-        analysis_cossin_post[k][0] =  4.0 * cosf(post);
-        analysis_cossin_post[k][1] = -4.0 * sinf(post);
-    }
     for (n = 1; n < 320; n++)
         sbr_qmf_window_us[320 + n] = sbr_qmf_window_us[320 - n];
     sbr_qmf_window_us[384] = -sbr_qmf_window_us[384];
@@ -133,6 +121,8 @@ av_cold void ff_aac_sbr_init(void)
 
     for (n = 0; n < 320; n++)
         sbr_qmf_window_ds[n] = sbr_qmf_window_us[2*n];
+
+    ff_ps_init();
 }
 
 av_cold void ff_aac_sbr_ctx_init(SpectralBandReplication *sbr)
@@ -142,13 +132,14 @@ av_cold void ff_aac_sbr_ctx_init(SpectralBandReplication *sbr)
     sbr->data[0].synthesis_filterbank_samples_offset = SBR_SYNTHESIS_BUF_SIZE - (1280 - 128);
     sbr->data[1].synthesis_filterbank_samples_offset = SBR_SYNTHESIS_BUF_SIZE - (1280 - 128);
     ff_mdct_init(&sbr->mdct, 7, 1, 1.0/64);
-    ff_rdft_init(&sbr->rdft, 6, IDFT_R2C);
+    ff_mdct_init(&sbr->mdct_ana, 7, 1, -2.0);
+    ff_ps_ctx_init(&sbr->ps);
 }
 
 av_cold void ff_aac_sbr_ctx_close(SpectralBandReplication *sbr)
 {
     ff_mdct_end(&sbr->mdct);
-    ff_rdft_end(&sbr->rdft);
+    ff_mdct_end(&sbr->mdct_ana);
 }
 
 static int qsort_comparison_function_int16(const void *a, const void *b)
@@ -293,15 +284,15 @@ static void make_bands(int16_t* bands, int start, int stop, int num_bands)
     bands[num_bands-1] = stop - previous;
 }
 
-static int check_n_master(AVCodecContext *avccontext, int n_master, int bs_xover_band)
+static int check_n_master(AVCodecContext *avctx, int n_master, int bs_xover_band)
 {
     // Requirements (14496-3 sp04 p205)
     if (n_master <= 0) {
-        av_log(avccontext, AV_LOG_ERROR, "Invalid n_master: %d\n", n_master);
+        av_log(avctx, AV_LOG_ERROR, "Invalid n_master: %d\n", n_master);
         return -1;
     }
     if (bs_xover_band >= n_master) {
-        av_log(avccontext, AV_LOG_ERROR,
+        av_log(avctx, AV_LOG_ERROR,
                "Invalid bitstream, crossover band index beyond array bounds: %d\n",
                bs_xover_band);
         return -1;
@@ -349,7 +340,7 @@ static int sbr_make_f_master(AACContext *ac, SpectralBandReplication *sbr,
         sbr_offset_ptr = sbr_offset[5];
         break;
     default:
-        av_log(ac->avccontext, AV_LOG_ERROR,
+        av_log(ac->avctx, AV_LOG_ERROR,
                "Unsupported sample rate for SBR: %d\n", sbr->sample_rate);
         return -1;
     }
@@ -367,7 +358,7 @@ static int sbr_make_f_master(AACContext *ac, SpectralBandReplication *sbr,
     } else if (spectrum->bs_stop_freq == 15) {
         sbr->k[2] = 3*sbr->k[0];
     } else {
-        av_log(ac->avccontext, AV_LOG_ERROR,
+        av_log(ac->avctx, AV_LOG_ERROR,
                "Invalid bs_stop_freq: %d\n", spectrum->bs_stop_freq);
         return -1;
     }
@@ -382,18 +373,17 @@ static int sbr_make_f_master(AACContext *ac, SpectralBandReplication *sbr,
         max_qmf_subbands = 32;
 
     if (sbr->k[2] - sbr->k[0] > max_qmf_subbands) {
-        av_log(ac->avccontext, AV_LOG_ERROR,
+        av_log(ac->avctx, AV_LOG_ERROR,
                "Invalid bitstream, too many QMF subbands: %d\n", sbr->k[2] - sbr->k[0]);
         return -1;
     }
 
     if (!spectrum->bs_freq_scale) {
-        unsigned int dk;
-        int k2diff;
+        int dk, k2diff;
 
         dk = spectrum->bs_alter_scale + 1;
         sbr->n_master = ((sbr->k[2] - sbr->k[0] + (dk&2)) >> dk) << 1;
-        if (check_n_master(ac->avccontext, sbr->n_master, sbr->spectrum_params.bs_xover_band))
+        if (check_n_master(ac->avctx, sbr->n_master, sbr->spectrum_params.bs_xover_band))
             return -1;
 
         for (k = 1; k <= sbr->n_master; k++)
@@ -402,7 +392,7 @@ static int sbr_make_f_master(AACContext *ac, SpectralBandReplication *sbr,
         k2diff = sbr->k[2] - sbr->k[0] - sbr->n_master * dk;
         if (k2diff < 0) {
             sbr->f_master[1]--;
-            sbr->f_master[2]-= (k2diff < 1);
+            sbr->f_master[2]-= (k2diff < -1);
         } else if (k2diff) {
             sbr->f_master[sbr->n_master]++;
         }
@@ -428,7 +418,7 @@ static int sbr_make_f_master(AACContext *ac, SpectralBandReplication *sbr,
         num_bands_0 = lrintf(half_bands * log2f(sbr->k[1] / (float)sbr->k[0])) * 2;
 
         if (num_bands_0 <= 0) { // Requirements (14496-3 sp04 p205)
-            av_log(ac->avccontext, AV_LOG_ERROR, "Invalid num_bands_0: %d\n", num_bands_0);
+            av_log(ac->avctx, AV_LOG_ERROR, "Invalid num_bands_0: %d\n", num_bands_0);
             return -1;
         }
 
@@ -442,7 +432,7 @@ static int sbr_make_f_master(AACContext *ac, SpectralBandReplication *sbr,
         vk0[0] = sbr->k[0];
         for (k = 1; k <= num_bands_0; k++) {
             if (vk0[k] <= 0) { // Requirements (14496-3 sp04 p205)
-                av_log(ac->avccontext, AV_LOG_ERROR, "Invalid vDk0[%d]: %d\n", k, vk0[k]);
+                av_log(ac->avctx, AV_LOG_ERROR, "Invalid vDk0[%d]: %d\n", k, vk0[k]);
                 return -1;
             }
             vk0[k] += vk0[k-1];
@@ -472,14 +462,14 @@ static int sbr_make_f_master(AACContext *ac, SpectralBandReplication *sbr,
             vk1[0] = sbr->k[1];
             for (k = 1; k <= num_bands_1; k++) {
                 if (vk1[k] <= 0) { // Requirements (14496-3 sp04 p205)
-                    av_log(ac->avccontext, AV_LOG_ERROR, "Invalid vDk1[%d]: %d\n", k, vk1[k]);
+                    av_log(ac->avctx, AV_LOG_ERROR, "Invalid vDk1[%d]: %d\n", k, vk1[k]);
                     return -1;
                 }
                 vk1[k] += vk1[k-1];
             }
 
             sbr->n_master = num_bands_0 + num_bands_1;
-            if (check_n_master(ac->avccontext, sbr->n_master, sbr->spectrum_params.bs_xover_band))
+            if (check_n_master(ac->avctx, sbr->n_master, sbr->spectrum_params.bs_xover_band))
                 return -1;
             memcpy(&sbr->f_master[0],               vk0,
                    (num_bands_0 + 1) * sizeof(sbr->f_master[0]));
@@ -488,7 +478,7 @@ static int sbr_make_f_master(AACContext *ac, SpectralBandReplication *sbr,
 
         } else {
             sbr->n_master = num_bands_0;
-            if (check_n_master(ac->avccontext, sbr->n_master, sbr->spectrum_params.bs_xover_band))
+            if (check_n_master(ac->avctx, sbr->n_master, sbr->spectrum_params.bs_xover_band))
                 return -1;
             memcpy(sbr->f_master, vk0, (num_bands_0 + 1) * sizeof(sbr->f_master[0]));
         }
@@ -524,7 +514,7 @@ static int sbr_hf_calc_npatches(AACContext *ac, SpectralBandReplication *sbr)
         // illegal however the Coding Technologies decoder check stream has a final
         // count of 6 patches
         if (sbr->num_patches > 5) {
-            av_log(ac->avccontext, AV_LOG_ERROR, "Too many patches: %d\n", sbr->num_patches);
+            av_log(ac->avctx, AV_LOG_ERROR, "Too many patches: %d\n", sbr->num_patches);
             return -1;
         }
 
@@ -563,12 +553,12 @@ static int sbr_make_f_derived(AACContext *ac, SpectralBandReplication *sbr)
 
     // Requirements (14496-3 sp04 p205)
     if (sbr->kx[1] + sbr->m[1] > 64) {
-        av_log(ac->avccontext, AV_LOG_ERROR,
+        av_log(ac->avctx, AV_LOG_ERROR,
                "Stop frequency border too high: %d\n", sbr->kx[1] + sbr->m[1]);
         return -1;
     }
     if (sbr->kx[1] > 32) {
-        av_log(ac->avccontext, AV_LOG_ERROR, "Start frequency border too high: %d\n", sbr->kx[1]);
+        av_log(ac->avctx, AV_LOG_ERROR, "Start frequency border too high: %d\n", sbr->kx[1]);
         return -1;
     }
 
@@ -580,7 +570,7 @@ static int sbr_make_f_derived(AACContext *ac, SpectralBandReplication *sbr)
     sbr->n_q = FFMAX(1, lrintf(sbr->spectrum_params.bs_noise_bands *
                                log2f(sbr->k[2] / (float)sbr->kx[1]))); // 0 <= bs_noise_bands <= 3
     if (sbr->n_q > 5) {
-        av_log(ac->avccontext, AV_LOG_ERROR, "Too many noise floor scale factors: %d\n", sbr->n_q);
+        av_log(ac->avctx, AV_LOG_ERROR, "Too many noise floor scale factors: %d\n", sbr->n_q);
         return -1;
     }
 
@@ -638,7 +628,7 @@ static int read_sbr_grid(AACContext *ac, SpectralBandReplication *sbr,
             ch_data->bs_amp_res = 0;
 
         if (ch_data->bs_num_env > 4) {
-            av_log(ac->avccontext, AV_LOG_ERROR,
+            av_log(ac->avctx, AV_LOG_ERROR,
                    "Invalid bitstream, too many SBR envelopes in FIXFIX type SBR frame: %d\n",
                    ch_data->bs_num_env);
             return -1;
@@ -693,7 +683,7 @@ static int read_sbr_grid(AACContext *ac, SpectralBandReplication *sbr,
         ch_data->bs_num_env                 = num_rel_lead + num_rel_trail + 1;
 
         if (ch_data->bs_num_env > 5) {
-            av_log(ac->avccontext, AV_LOG_ERROR,
+            av_log(ac->avctx, AV_LOG_ERROR,
                    "Invalid bitstream, too many SBR envelopes in VARVAR type SBR frame: %d\n",
                    ch_data->bs_num_env);
             return -1;
@@ -714,7 +704,7 @@ static int read_sbr_grid(AACContext *ac, SpectralBandReplication *sbr,
     }
 
     if (bs_pointer > ch_data->bs_num_env + 1) {
-        av_log(ac->avccontext, AV_LOG_ERROR,
+        av_log(ac->avctx, AV_LOG_ERROR,
                "Invalid bitstream, bs_pointer points to a middle noise border outside the time borders table: %d\n",
                bs_pointer);
         return -1;
@@ -722,7 +712,7 @@ static int read_sbr_grid(AACContext *ac, SpectralBandReplication *sbr,
 
     for (i = 1; i <= ch_data->bs_num_env; i++) {
         if (ch_data->t_env[i-1] > ch_data->t_env[i]) {
-            av_log(ac->avccontext, AV_LOG_ERROR, "Non monotone time borders\n");
+            av_log(ac->avctx, AV_LOG_ERROR, "Non monotone time borders\n");
             return -1;
         }
     }
@@ -903,25 +893,24 @@ static void read_sbr_extension(AACContext *ac, SpectralBandReplication *sbr,
                                GetBitContext *gb,
                                int bs_extension_id, int *num_bits_left)
 {
-//TODO - implement ps_data for parametric stereo parsing
     switch (bs_extension_id) {
     case EXTENSION_ID_PS:
         if (!ac->m4ac.ps) {
-            av_log(ac->avccontext, AV_LOG_ERROR, "Parametric Stereo signaled to be not-present but was found in the bitstream.\n");
+            av_log(ac->avctx, AV_LOG_ERROR, "Parametric Stereo signaled to be not-present but was found in the bitstream.\n");
             skip_bits_long(gb, *num_bits_left); // bs_fill_bits
             *num_bits_left = 0;
         } else {
-#if 0
-            *num_bits_left -= ff_ps_data(gb, ps);
+#if 1
+            *num_bits_left -= ff_ps_read_data(ac->avctx, gb, &sbr->ps, *num_bits_left);
 #else
-            av_log_missing_feature(ac->avccontext, "Parametric Stereo is", 0);
+            av_log_missing_feature(ac->avctx, "Parametric Stereo is", 0);
             skip_bits_long(gb, *num_bits_left); // bs_fill_bits
             *num_bits_left = 0;
 #endif
         }
         break;
     default:
-        av_log_missing_feature(ac->avccontext, "Reserved SBR extensions are", 1);
+        av_log_missing_feature(ac->avctx, "Reserved SBR extensions are", 1);
         skip_bits_long(gb, *num_bits_left); // bs_fill_bits
         *num_bits_left = 0;
         break;
@@ -1006,7 +995,7 @@ static unsigned int read_sbr_data(AACContext *ac, SpectralBandReplication *sbr,
             return get_bits_count(gb) - cnt;
         }
     } else {
-        av_log(ac->avccontext, AV_LOG_ERROR,
+        av_log(ac->avctx, AV_LOG_ERROR,
             "Invalid bitstream - cannot apply SBR to element type %d\n", id_aac);
         sbr->start = 0;
         return get_bits_count(gb) - cnt;
@@ -1021,6 +1010,11 @@ static unsigned int read_sbr_data(AACContext *ac, SpectralBandReplication *sbr,
             num_bits_left -= 2;
             read_sbr_extension(ac, sbr, gb, get_bits(gb, 2), &num_bits_left); // bs_extension_id
         }
+        if (num_bits_left < 0) {
+            av_log(ac->avctx, AV_LOG_ERROR, "SBR Extension over read.\n");
+        }
+        if (num_bits_left > 0)
+            skip_bits(gb, num_bits_left);
     }
 
     return get_bits_count(gb) - cnt;
@@ -1033,7 +1027,7 @@ static void sbr_reset(AACContext *ac, SpectralBandReplication *sbr)
     if (err >= 0)
         err = sbr_make_f_derived(ac, sbr);
     if (err < 0) {
-        av_log(ac->avccontext, AV_LOG_ERROR,
+        av_log(ac->avctx, AV_LOG_ERROR,
                "SBR reset failed. Switching SBR to pure upsampling mode.\n");
         sbr->start = 0;
     }
@@ -1085,7 +1079,7 @@ int ff_decode_sbr_extension(AACContext *ac, SpectralBandReplication *sbr,
     bytes_read = ((num_sbr_bits + num_align_bits + 4) >> 3);
 
     if (bytes_read > cnt) {
-        av_log(ac->avccontext, AV_LOG_ERROR,
+        av_log(ac->avctx, AV_LOG_ERROR,
                "Expected to read %d SBR bytes actually read %d.\n", cnt, bytes_read);
     }
     return cnt;
@@ -1139,36 +1133,32 @@ static void sbr_dequant(SpectralBandReplication *sbr, int id_aac)
  * @param   x       pointer to the beginning of the first sample window
  * @param   W       array of complex-valued samples split into subbands
  */
-static void sbr_qmf_analysis(DSPContext *dsp, RDFTContext *rdft, const float *in, float *x,
-                             float z[320], float W[2][32][32][2],
-                             float scale)
+static void sbr_qmf_analysis(DSPContext *dsp, FFTContext *mdct, const float *in, float *x,
+                             float z[320], float W[2][32][32][2])
 {
     int i, k;
     memcpy(W[0], W[1], sizeof(W[0]));
     memcpy(x    , x+1024, (320-32)*sizeof(x[0]));
-    if (scale != 1.0f)
-        dsp->vector_fmul_scalar(x+288, in, scale, 1024);
-    else
-        memcpy(x+288, in, 1024*sizeof(*x));
+    memcpy(x+288, in,         1024*sizeof(x[0]));
     for (i = 0; i < 32; i++) { // numTimeSlots*RATE = 16*2 as 960 sample frames
                                // are not supported
-        float re, im;
         dsp->vector_fmul_reverse(z, sbr_qmf_window_ds, x, 320);
         for (k = 0; k < 64; k++) {
             float f = z[k] + z[k + 64] + z[k + 128] + z[k + 192] + z[k + 256];
-            z[k] = f * analysis_cos_pre[k];
-            z[k+64] = f;
+            z[k] = f;
         }
-        ff_rdft_calc(rdft, z);
-        re = z[0] * 0.5f;
-        im = 0.5f * dsp->scalarproduct_float(z+64, analysis_sin_pre, 64);
-        W[1][i][0][0] = re * analysis_cossin_post[0][0] - im * analysis_cossin_post[0][1];
-        W[1][i][0][1] = re * analysis_cossin_post[0][1] + im * analysis_cossin_post[0][0];
+        //Shuffle to IMDCT
+        z[64] = z[0];
         for (k = 1; k < 32; k++) {
-            re = z[2*k  ] - re;
-            im = z[2*k+1] - im;
-            W[1][i][k][0] = re * analysis_cossin_post[k][0] - im * analysis_cossin_post[k][1];
-            W[1][i][k][1] = re * analysis_cossin_post[k][1] + im * analysis_cossin_post[k][0];
+            z[64+2*k-1] =  z[   k];
+            z[64+2*k  ] = -z[64-k];
+        }
+        z[64+63] = z[32];
+
+        mdct->imdct_half(mdct, z, z+64);
+        for (k = 0; k < 32; k++) {
+            W[1][i][k][0] = -z[63-k];
+            W[1][i][k][1] = z[k];
         }
         x += 32;
     }
@@ -1179,14 +1169,12 @@ static void sbr_qmf_analysis(DSPContext *dsp, RDFTContext *rdft, const float *in
  * (14496-3 sp04 p206)
  */
 static void sbr_qmf_synthesis(DSPContext *dsp, FFTContext *mdct,
-                              float *out, float X[2][32][64],
+                              float *out, float X[2][38][64],
                               float mdct_buf[2][64],
-                              float *v0, int *v_off, const unsigned int div,
-                              float bias, float scale)
+                              float *v0, int *v_off, const unsigned int div)
 {
     int i, n;
     const float *sbr_qmf_window = div ? sbr_qmf_window_ds : sbr_qmf_window_us;
-    int scale_and_bias = scale != 1.0f || bias != 0.0f;
     float *v;
     for (i = 0; i < 32; i++) {
         if (*v_off == 0) {
@@ -1197,21 +1185,22 @@ static void sbr_qmf_synthesis(DSPContext *dsp, FFTContext *mdct,
             *v_off -= 128 >> div;
         }
         v = v0 + *v_off;
-        for (n = 1; n < 64 >> div; n+=2) {
-            X[1][i][n] = -X[1][i][n];
-        }
-        if (div) {
-            memset(X[0][i]+32, 0, 32*sizeof(float));
-            memset(X[1][i]+32, 0, 32*sizeof(float));
-        }
-        ff_imdct_half(mdct, mdct_buf[0], X[0][i]);
-        ff_imdct_half(mdct, mdct_buf[1], X[1][i]);
         if (div) {
             for (n = 0; n < 32; n++) {
-                v[      n] = -mdct_buf[0][63 - 2*n] + mdct_buf[1][2*n    ];
-                v[ 63 - n] =  mdct_buf[0][62 - 2*n] + mdct_buf[1][2*n + 1];
+                X[0][i][   n] = -X[0][i][n];
+                X[0][i][32+n] =  X[1][i][31-n];
+            }
+            mdct->imdct_half(mdct, mdct_buf[0], X[0][i]);
+            for (n = 0; n < 32; n++) {
+                v[     n] =  mdct_buf[0][63 - 2*n];
+                v[63 - n] = -mdct_buf[0][62 - 2*n];
             }
         } else {
+            for (n = 1; n < 64; n+=2) {
+                X[1][i][n] = -X[1][i][n];
+            }
+            mdct->imdct_half(mdct, mdct_buf[0], X[0][i]);
+            mdct->imdct_half(mdct, mdct_buf[1], X[1][i]);
             for (n = 0; n < 64; n++) {
                 v[      n] = -mdct_buf[0][63 -   n] + mdct_buf[1][  n    ];
                 v[127 - n] =  mdct_buf[0][63 -   n] + mdct_buf[1][  n    ];
@@ -1227,9 +1216,6 @@ static void sbr_qmf_synthesis(DSPContext *dsp, FFTContext *mdct,
         dsp->vector_fmul_add(out, v + ( 960 >> div), sbr_qmf_window + (448 >> div), out   , 64 >> div);
         dsp->vector_fmul_add(out, v + (1024 >> div), sbr_qmf_window + (512 >> div), out   , 64 >> div);
         dsp->vector_fmul_add(out, v + (1216 >> div), sbr_qmf_window + (576 >> div), out   , 64 >> div);
-        if (scale_and_bias)
-            for (n = 0; n < 64 >> div; n++)
-                out[n] = out[n] * scale + bias;
         out += 64 >> div;
     }
 }
@@ -1380,7 +1366,7 @@ static int sbr_hf_gen(AACContext *ac, SpectralBandReplication *sbr,
             g--;
 
             if (g < 0) {
-                av_log(ac->avccontext, AV_LOG_ERROR,
+                av_log(ac->avctx, AV_LOG_ERROR,
                        "ERROR : no subband found for frequency %d\n", k);
                 return -1;
             }
@@ -1414,7 +1400,7 @@ static int sbr_hf_gen(AACContext *ac, SpectralBandReplication *sbr,
 }
 
 /// Generate the subband filtered lowband
-static int sbr_x_gen(SpectralBandReplication *sbr, float X[2][32][64],
+static int sbr_x_gen(SpectralBandReplication *sbr, float X[2][38][64],
                      const float X_low[32][40][2], const float Y[2][38][64][2],
                      int ch)
 {
@@ -1436,7 +1422,7 @@ static int sbr_x_gen(SpectralBandReplication *sbr, float X[2][32][64],
     }
 
     for (k = 0; k < sbr->kx[1]; k++) {
-        for (i = i_Temp; i < i_f; i++) {
+        for (i = i_Temp; i < 38; i++) {
             X[0][i][k] = X_low[k][i + ENVELOPE_ADJUSTMENT_OFFSET][0];
             X[1][i][k] = X_low[k][i + ENVELOPE_ADJUSTMENT_OFFSET][1];
         }
@@ -1585,7 +1571,7 @@ static void sbr_gain_calc(AACContext *ac, SpectralBandReplication *sbr,
                 sum[1] += sbr->e_curr[e][m];
             }
             gain_max = limgain[sbr->bs_limiter_gains] * sqrtf((FLT_EPSILON + sum[0]) / (FLT_EPSILON + sum[1]));
-            gain_max = FFMIN(100000, gain_max);
+            gain_max = FFMIN(100000.f, gain_max);
             for (m = sbr->f_tablelim[k] - sbr->kx[1]; m < sbr->f_tablelim[k + 1] - sbr->kx[1]; m++) {
                 float q_m_max   = sbr->q_m[e][m] * gain_max / sbr->gain[e][m];
                 sbr->q_m[e][m]  = FFMIN(sbr->q_m[e][m], q_m_max);
@@ -1599,7 +1585,7 @@ static void sbr_gain_calc(AACContext *ac, SpectralBandReplication *sbr,
                           + (delta && !sbr->s_m[e][m]) * sbr->q_m[e][m] * sbr->q_m[e][m];
             }
             gain_boost = sqrtf((FLT_EPSILON + sum[0]) / (FLT_EPSILON + sum[1]));
-            gain_boost = FFMIN(1.584893192, gain_boost);
+            gain_boost = FFMIN(1.584893192f, gain_boost);
             for (m = sbr->f_tablelim[k] - sbr->kx[1]; m < sbr->f_tablelim[k + 1] - sbr->kx[1]; m++) {
                 sbr->gain[e][m] *= gain_boost;
                 sbr->q_m[e][m]  *= gain_boost;
@@ -1730,9 +1716,9 @@ void ff_sbr_apply(AACContext *ac, SpectralBandReplication *sbr, int id_aac,
     }
     for (ch = 0; ch < nch; ch++) {
         /* decode channel */
-        sbr_qmf_analysis(&ac->dsp, &sbr->rdft, ch ? R : L, sbr->data[ch].analysis_filterbank_samples,
+        sbr_qmf_analysis(&ac->dsp, &sbr->mdct_ana, ch ? R : L, sbr->data[ch].analysis_filterbank_samples,
                          (float*)sbr->qmf_filter_scratch,
-                         sbr->data[ch].W, 1/(-1024 * ac->sf_scale));
+                         sbr->data[ch].W);
         sbr_lf_gen(ac, sbr, sbr->X_low, sbr->data[ch].W);
         if (sbr->start) {
             sbr_hf_inverse_filter(sbr->alpha0, sbr->alpha1, sbr->X_low, sbr->k[0]);
@@ -1752,15 +1738,23 @@ void ff_sbr_apply(AACContext *ac, SpectralBandReplication *sbr, int id_aac,
         /* synthesis */
         sbr_x_gen(sbr, sbr->X[ch], sbr->X_low, sbr->data[ch].Y, ch);
     }
+
+    if (ac->m4ac.ps == 1) {
+        if (sbr->ps.start) {
+            ff_ps_apply(ac->avctx, &sbr->ps, sbr->X[0], sbr->X[1], sbr->kx[1] + sbr->m[1]);
+        } else {
+            memcpy(sbr->X[1], sbr->X[0], sizeof(sbr->X[0]));
+        }
+        nch = 2;
+    }
+
     sbr_qmf_synthesis(&ac->dsp, &sbr->mdct, L, sbr->X[0], sbr->qmf_filter_scratch,
                       sbr->data[0].synthesis_filterbank_samples,
                       &sbr->data[0].synthesis_filterbank_samples_offset,
-                      downsampled,
-                      ac->add_bias, -1024 * ac->sf_scale);
+                      downsampled);
     if (nch == 2)
         sbr_qmf_synthesis(&ac->dsp, &sbr->mdct, R, sbr->X[1], sbr->qmf_filter_scratch,
                           sbr->data[1].synthesis_filterbank_samples,
                           &sbr->data[1].synthesis_filterbank_samples_offset,
-                          downsampled,
-                          ac->add_bias, -1024 * ac->sf_scale);
+                          downsampled);
 }
diff --git a/libavcodec/aacsbr.h b/libavcodec/aacsbr.h
index 6b10ed4..dca8330 100644
--- a/libavcodec/aacsbr.h
+++ b/libavcodec/aacsbr.h
@@ -3,20 +3,20 @@
  * Copyright (c) 2008-2009 Robert Swain ( rob opendot cl )
  * Copyright (c) 2010      Alex Converse <alex.converse at gmail.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/aacsbrdata.h b/libavcodec/aacsbrdata.h
index 5d33a60..44d578f 100644
--- a/libavcodec/aacsbrdata.h
+++ b/libavcodec/aacsbrdata.h
@@ -2,20 +2,20 @@
  * AAC Spectral Band Replication decoding data
  * Copyright (c) 2008-2009 Robert Swain ( rob opendot cl )
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/aactab.c b/libavcodec/aactab.c
index eaa5486..46886b1 100644
--- a/libavcodec/aactab.c
+++ b/libavcodec/aactab.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2005-2006 Oded Shimon ( ods15 ods15 dyndns org )
  * Copyright (c) 2006-2007 Maxim Gavrilov ( maxim.gavrilov gmail com )
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -29,6 +29,7 @@
 
 #include "libavutil/mem.h"
 #include "aac.h"
+#include "aac_tablegen.h"
 
 #include <stdint.h>
 
@@ -1204,129 +1205,3 @@ const uint8_t ff_tns_max_bands_128[] = {
     9, 9, 10, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14
 };
 // @}
-
-
-#if CONFIG_HARDCODED_TABLES
-
-/**
- * Table of pow(2, (i - 200)/4.) used for different purposes depending on the
- * range of indices to the table:
- * [ 0, 255] scale factor decoding when using C dsp.float_to_int16
- * [60, 315] scale factor decoding when using SIMD dsp.float_to_int16
- * [45, 300] intensity stereo position decoding mapped in reverse order i.e. 0->300, 1->299, ..., 254->46, 255->45
- */
-const float ff_aac_pow2sf_tab[428] = {
-    8.88178420e-16, 1.05622810e-15, 1.25607397e-15, 1.49373210e-15,
-    1.77635684e-15, 2.11245619e-15, 2.51214793e-15, 2.98746420e-15,
-    3.55271368e-15, 4.22491238e-15, 5.02429587e-15, 5.97492839e-15,
-    7.10542736e-15, 8.44982477e-15, 1.00485917e-14, 1.19498568e-14,
-    1.42108547e-14, 1.68996495e-14, 2.00971835e-14, 2.38997136e-14,
-    2.84217094e-14, 3.37992991e-14, 4.01943669e-14, 4.77994272e-14,
-    5.68434189e-14, 6.75985982e-14, 8.03887339e-14, 9.55988543e-14,
-    1.13686838e-13, 1.35197196e-13, 1.60777468e-13, 1.91197709e-13,
-    2.27373675e-13, 2.70394393e-13, 3.21554936e-13, 3.82395417e-13,
-    4.54747351e-13, 5.40788785e-13, 6.43109871e-13, 7.64790834e-13,
-    9.09494702e-13, 1.08157757e-12, 1.28621974e-12, 1.52958167e-12,
-    1.81898940e-12, 2.16315514e-12, 2.57243948e-12, 3.05916334e-12,
-    3.63797881e-12, 4.32631028e-12, 5.14487897e-12, 6.11832668e-12,
-    7.27595761e-12, 8.65262056e-12, 1.02897579e-11, 1.22366534e-11,
-    1.45519152e-11, 1.73052411e-11, 2.05795159e-11, 2.44733067e-11,
-    2.91038305e-11, 3.46104823e-11, 4.11590317e-11, 4.89466134e-11,
-    5.82076609e-11, 6.92209645e-11, 8.23180635e-11, 9.78932268e-11,
-    1.16415322e-10, 1.38441929e-10, 1.64636127e-10, 1.95786454e-10,
-    2.32830644e-10, 2.76883858e-10, 3.29272254e-10, 3.91572907e-10,
-    4.65661287e-10, 5.53767716e-10, 6.58544508e-10, 7.83145814e-10,
-    9.31322575e-10, 1.10753543e-09, 1.31708902e-09, 1.56629163e-09,
-    1.86264515e-09, 2.21507086e-09, 2.63417803e-09, 3.13258326e-09,
-    3.72529030e-09, 4.43014173e-09, 5.26835606e-09, 6.26516652e-09,
-    7.45058060e-09, 8.86028346e-09, 1.05367121e-08, 1.25303330e-08,
-    1.49011612e-08, 1.77205669e-08, 2.10734243e-08, 2.50606661e-08,
-    2.98023224e-08, 3.54411338e-08, 4.21468485e-08, 5.01213321e-08,
-    5.96046448e-08, 7.08822677e-08, 8.42936970e-08, 1.00242664e-07,
-    1.19209290e-07, 1.41764535e-07, 1.68587394e-07, 2.00485328e-07,
-    2.38418579e-07, 2.83529071e-07, 3.37174788e-07, 4.00970657e-07,
-    4.76837158e-07, 5.67058141e-07, 6.74349576e-07, 8.01941314e-07,
-    9.53674316e-07, 1.13411628e-06, 1.34869915e-06, 1.60388263e-06,
-    1.90734863e-06, 2.26823256e-06, 2.69739830e-06, 3.20776526e-06,
-    3.81469727e-06, 4.53646513e-06, 5.39479661e-06, 6.41553051e-06,
-    7.62939453e-06, 9.07293026e-06, 1.07895932e-05, 1.28310610e-05,
-    1.52587891e-05, 1.81458605e-05, 2.15791864e-05, 2.56621220e-05,
-    3.05175781e-05, 3.62917210e-05, 4.31583729e-05, 5.13242441e-05,
-    6.10351562e-05, 7.25834421e-05, 8.63167458e-05, 1.02648488e-04,
-    1.22070312e-04, 1.45166884e-04, 1.72633492e-04, 2.05296976e-04,
-    2.44140625e-04, 2.90333768e-04, 3.45266983e-04, 4.10593953e-04,
-    4.88281250e-04, 5.80667537e-04, 6.90533966e-04, 8.21187906e-04,
-    9.76562500e-04, 1.16133507e-03, 1.38106793e-03, 1.64237581e-03,
-    1.95312500e-03, 2.32267015e-03, 2.76213586e-03, 3.28475162e-03,
-    3.90625000e-03, 4.64534029e-03, 5.52427173e-03, 6.56950324e-03,
-    7.81250000e-03, 9.29068059e-03, 1.10485435e-02, 1.31390065e-02,
-    1.56250000e-02, 1.85813612e-02, 2.20970869e-02, 2.62780130e-02,
-    3.12500000e-02, 3.71627223e-02, 4.41941738e-02, 5.25560260e-02,
-    6.25000000e-02, 7.43254447e-02, 8.83883476e-02, 1.05112052e-01,
-    1.25000000e-01, 1.48650889e-01, 1.76776695e-01, 2.10224104e-01,
-    2.50000000e-01, 2.97301779e-01, 3.53553391e-01, 4.20448208e-01,
-    5.00000000e-01, 5.94603558e-01, 7.07106781e-01, 8.40896415e-01,
-    1.00000000e+00, 1.18920712e+00, 1.41421356e+00, 1.68179283e+00,
-    2.00000000e+00, 2.37841423e+00, 2.82842712e+00, 3.36358566e+00,
-    4.00000000e+00, 4.75682846e+00, 5.65685425e+00, 6.72717132e+00,
-    8.00000000e+00, 9.51365692e+00, 1.13137085e+01, 1.34543426e+01,
-    1.60000000e+01, 1.90273138e+01, 2.26274170e+01, 2.69086853e+01,
-    3.20000000e+01, 3.80546277e+01, 4.52548340e+01, 5.38173706e+01,
-    6.40000000e+01, 7.61092554e+01, 9.05096680e+01, 1.07634741e+02,
-    1.28000000e+02, 1.52218511e+02, 1.81019336e+02, 2.15269482e+02,
-    2.56000000e+02, 3.04437021e+02, 3.62038672e+02, 4.30538965e+02,
-    5.12000000e+02, 6.08874043e+02, 7.24077344e+02, 8.61077929e+02,
-    1.02400000e+03, 1.21774809e+03, 1.44815469e+03, 1.72215586e+03,
-    2.04800000e+03, 2.43549617e+03, 2.89630938e+03, 3.44431172e+03,
-    4.09600000e+03, 4.87099234e+03, 5.79261875e+03, 6.88862343e+03,
-    8.19200000e+03, 9.74198469e+03, 1.15852375e+04, 1.37772469e+04,
-    1.63840000e+04, 1.94839694e+04, 2.31704750e+04, 2.75544937e+04,
-    3.27680000e+04, 3.89679387e+04, 4.63409500e+04, 5.51089875e+04,
-    6.55360000e+04, 7.79358775e+04, 9.26819000e+04, 1.10217975e+05,
-    1.31072000e+05, 1.55871755e+05, 1.85363800e+05, 2.20435950e+05,
-    2.62144000e+05, 3.11743510e+05, 3.70727600e+05, 4.40871900e+05,
-    5.24288000e+05, 6.23487020e+05, 7.41455200e+05, 8.81743800e+05,
-    1.04857600e+06, 1.24697404e+06, 1.48291040e+06, 1.76348760e+06,
-    2.09715200e+06, 2.49394808e+06, 2.96582080e+06, 3.52697520e+06,
-    4.19430400e+06, 4.98789616e+06, 5.93164160e+06, 7.05395040e+06,
-    8.38860800e+06, 9.97579232e+06, 1.18632832e+07, 1.41079008e+07,
-    1.67772160e+07, 1.99515846e+07, 2.37265664e+07, 2.82158016e+07,
-    3.35544320e+07, 3.99031693e+07, 4.74531328e+07, 5.64316032e+07,
-    6.71088640e+07, 7.98063385e+07, 9.49062656e+07, 1.12863206e+08,
-    1.34217728e+08, 1.59612677e+08, 1.89812531e+08, 2.25726413e+08,
-    2.68435456e+08, 3.19225354e+08, 3.79625062e+08, 4.51452825e+08,
-    5.36870912e+08, 6.38450708e+08, 7.59250125e+08, 9.02905651e+08,
-    1.07374182e+09, 1.27690142e+09, 1.51850025e+09, 1.80581130e+09,
-    2.14748365e+09, 2.55380283e+09, 3.03700050e+09, 3.61162260e+09,
-    4.29496730e+09, 5.10760567e+09, 6.07400100e+09, 7.22324521e+09,
-    8.58993459e+09, 1.02152113e+10, 1.21480020e+10, 1.44464904e+10,
-    1.71798692e+10, 2.04304227e+10, 2.42960040e+10, 2.88929808e+10,
-    3.43597384e+10, 4.08608453e+10, 4.85920080e+10, 5.77859616e+10,
-    6.87194767e+10, 8.17216907e+10, 9.71840160e+10, 1.15571923e+11,
-    1.37438953e+11, 1.63443381e+11, 1.94368032e+11, 2.31143847e+11,
-    2.74877907e+11, 3.26886763e+11, 3.88736064e+11, 4.62287693e+11,
-    5.49755814e+11, 6.53773525e+11, 7.77472128e+11, 9.24575386e+11,
-    1.09951163e+12, 1.30754705e+12, 1.55494426e+12, 1.84915077e+12,
-    2.19902326e+12, 2.61509410e+12, 3.10988851e+12, 3.69830155e+12,
-    4.39804651e+12, 5.23018820e+12, 6.21977702e+12, 7.39660309e+12,
-    8.79609302e+12, 1.04603764e+13, 1.24395540e+13, 1.47932062e+13,
-    1.75921860e+13, 2.09207528e+13, 2.48791081e+13, 2.95864124e+13,
-    3.51843721e+13, 4.18415056e+13, 4.97582162e+13, 5.91728247e+13,
-    7.03687442e+13, 8.36830112e+13, 9.95164324e+13, 1.18345649e+14,
-    1.40737488e+14, 1.67366022e+14, 1.99032865e+14, 2.36691299e+14,
-    2.81474977e+14, 3.34732045e+14, 3.98065730e+14, 4.73382598e+14,
-    5.62949953e+14, 6.69464090e+14, 7.96131459e+14, 9.46765196e+14,
-    1.12589991e+15, 1.33892818e+15, 1.59226292e+15, 1.89353039e+15,
-    2.25179981e+15, 2.67785636e+15, 3.18452584e+15, 3.78706078e+15,
-    4.50359963e+15, 5.35571272e+15, 6.36905167e+15, 7.57412156e+15,
-    9.00719925e+15, 1.07114254e+16, 1.27381033e+16, 1.51482431e+16,
-    1.80143985e+16, 2.14228509e+16, 2.54762067e+16, 3.02964863e+16,
-    3.60287970e+16, 4.28457018e+16, 5.09524134e+16, 6.05929725e+16,
-    7.20575940e+16, 8.56914035e+16, 1.01904827e+17, 1.21185945e+17,
-};
-
-#else
-
-float ff_aac_pow2sf_tab[428];
-
-#endif /* CONFIG_HARDCODED_TABLES */
diff --git a/libavcodec/aactab.h b/libavcodec/aactab.h
index 283d6c3..c76d65d 100644
--- a/libavcodec/aactab.h
+++ b/libavcodec/aactab.h
@@ -3,20 +3,20 @@
  * Copyright (c) 2005-2006 Oded Shimon ( ods15 ods15 dyndns org )
  * Copyright (c) 2006-2007 Maxim Gavrilov ( maxim.gavrilov gmail com )
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -32,6 +32,7 @@
 
 #include "libavutil/mem.h"
 #include "aac.h"
+#include "aac_tablegen_decl.h"
 
 #include <stdint.h>
 
@@ -73,10 +74,4 @@ extern const uint16_t * const ff_swb_offset_128 [13];
 extern const uint8_t ff_tns_max_bands_1024[13];
 extern const uint8_t ff_tns_max_bands_128 [13];
 
-#if CONFIG_HARDCODED_TABLES
-extern const float ff_aac_pow2sf_tab[428];
-#else
-extern       float ff_aac_pow2sf_tab[428];
-#endif /* CONFIG_HARDCODED_TABLES */
-
 #endif /* AVCODEC_AACTAB_H */
diff --git a/libavcodec/aandcttab.c b/libavcodec/aandcttab.c
index 87c50b3..0c5b573 100644
--- a/libavcodec/aandcttab.c
+++ b/libavcodec/aandcttab.c
@@ -1,18 +1,18 @@
 /*
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/aandcttab.h b/libavcodec/aandcttab.h
index d774828..daccb7b 100644
--- a/libavcodec/aandcttab.h
+++ b/libavcodec/aandcttab.h
@@ -1,18 +1,18 @@
 /*
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/aasc.c b/libavcodec/aasc.c
index 82bd2bf..e80e094 100644
--- a/libavcodec/aasc.c
+++ b/libavcodec/aasc.c
@@ -2,20 +2,20 @@
  * Autodesk RLE Decoder
  * Copyright (C) 2005 the ffmpeg project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -109,7 +109,7 @@ static av_cold int aasc_decode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec aasc_decoder = {
+AVCodec ff_aasc_decoder = {
     "aasc",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_AASC,
diff --git a/libavcodec/ac3.c b/libavcodec/ac3.c
index 3fce5bc..99e5b50 100644
--- a/libavcodec/ac3.c
+++ b/libavcodec/ac3.c
@@ -2,20 +2,20 @@
  * Common code between the AC-3 encoder and decoder
  * Copyright (c) 2000 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -28,12 +28,10 @@
 #include "ac3.h"
 #include "get_bits.h"
 
-#if CONFIG_HARDCODED_TABLES
-
 /**
  * Starting frequency coefficient bin for each critical band.
  */
-static const uint8_t band_start_tab[51] = {
+const uint8_t ff_ac3_band_start_tab[AC3_CRITICAL_BANDS+1] = {
       0,  1,   2,   3,   4,   5,   6,   7,   8,   9,
      10,  11, 12,  13,  14,  15,  16,  17,  18,  19,
      20,  21, 22,  23,  24,  25,  26,  27,  28,  31,
@@ -41,10 +39,12 @@ static const uint8_t band_start_tab[51] = {
      79,  85, 97, 109, 121, 133, 157, 181, 205, 229, 253
 };
 
+#if CONFIG_HARDCODED_TABLES
+
 /**
- * Maps each frequency coefficient bin to the critical band that contains it.
+ * Map each frequency coefficient bin to the critical band that contains it.
  */
-static const uint8_t bin_to_band_tab[253] = {
+const uint8_t ff_ac3_bin_to_band_tab[253] = {
      0,
      1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12,
     13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
@@ -70,8 +70,7 @@ static const uint8_t bin_to_band_tab[253] = {
 };
 
 #else /* CONFIG_HARDCODED_TABLES */
-static uint8_t band_start_tab[51];
-static uint8_t bin_to_band_tab[253];
+uint8_t ff_ac3_bin_to_band_tab[253];
 #endif
 
 static inline int calc_lowcomp1(int a, int b0, int b1, int c)
@@ -107,10 +106,10 @@ void ff_ac3_bit_alloc_calc_psd(int8_t *exp, int start, int end, int16_t *psd,
 
     /* PSD integration */
     bin  = start;
-    band = bin_to_band_tab[start];
+    band = ff_ac3_bin_to_band_tab[start];
     do {
         int v = psd[bin++];
-        int band_end = FFMIN(band_start_tab[band+1], end);
+        int band_end = FFMIN(ff_ac3_band_start_tab[band+1], end);
         for (; bin < band_end; bin++) {
             int max = FFMAX(v, psd[bin]);
             /* logadd */
@@ -118,7 +117,7 @@ void ff_ac3_bit_alloc_calc_psd(int8_t *exp, int start, int end, int16_t *psd,
             v = max + ff_ac3_log_add_tab[adr];
         }
         band_psd[band++] = v;
-    } while (end > band_start_tab[band]);
+    } while (end > ff_ac3_band_start_tab[band]);
 }
 
 int ff_ac3_bit_alloc_calc_mask(AC3BitAllocParameters *s, int16_t *band_psd,
@@ -127,14 +126,14 @@ int ff_ac3_bit_alloc_calc_mask(AC3BitAllocParameters *s, int16_t *band_psd,
                                uint8_t *dba_lengths, uint8_t *dba_values,
                                int16_t *mask)
 {
-    int16_t excite[50]; /* excitation */
+    int16_t excite[AC3_CRITICAL_BANDS]; /* excitation */
     int band;
     int band_start, band_end, begin, end1;
     int lowcomp, fastleak, slowleak;
 
     /* excitation function */
-    band_start = bin_to_band_tab[start];
-    band_end   = bin_to_band_tab[end-1] + 1;
+    band_start = ff_ac3_bin_to_band_tab[start];
+    band_end   = ff_ac3_bin_to_band_tab[end-1] + 1;
 
     if (band_start == 0) {
         lowcomp = 0;
@@ -193,12 +192,12 @@ int ff_ac3_bit_alloc_calc_mask(AC3BitAllocParameters *s, int16_t *band_psd,
 
     if (dba_mode == DBA_REUSE || dba_mode == DBA_NEW) {
         int i, seg, delta;
-        if (dba_nsegs >= 8)
+        if (dba_nsegs > 8)
             return -1;
-        band = 0;
+        band = band_start;
         for (seg = 0; seg < dba_nsegs; seg++) {
             band += dba_offsets[seg];
-            if (band >= 50 || dba_lengths[seg] > 50-band)
+            if (band >= AC3_CRITICAL_BANDS || dba_lengths[seg] > AC3_CRITICAL_BANDS-band)
                 return -1;
             if (dba_values[seg] >= 4) {
                 delta = (dba_values[seg] - 3) << 7;
@@ -213,69 +212,20 @@ int ff_ac3_bit_alloc_calc_mask(AC3BitAllocParameters *s, int16_t *band_psd,
     return 0;
 }
 
-void ff_ac3_bit_alloc_calc_bap(int16_t *mask, int16_t *psd, int start, int end,
-                               int snr_offset, int floor,
-                               const uint8_t *bap_tab, uint8_t *bap)
-{
-    int bin, band;
-
-    /* special case, if snr offset is -960, set all bap's to zero */
-    if (snr_offset == -960) {
-        memset(bap, 0, 256);
-        return;
-    }
-
-    bin  = start;
-    band = bin_to_band_tab[start];
-    do {
-        int m = (FFMAX(mask[band] - snr_offset - floor, 0) & 0x1FE0) + floor;
-        int band_end = FFMIN(band_start_tab[band+1], end);
-        for (; bin < band_end; bin++) {
-            int address = av_clip((psd[bin] - m) >> 5, 0, 63);
-            bap[bin] = bap_tab[address];
-        }
-    } while (end > band_start_tab[band++]);
-}
-
-/* AC-3 bit allocation. The algorithm is the one described in the AC-3
-   spec. */
-void ac3_parametric_bit_allocation(AC3BitAllocParameters *s, uint8_t *bap,
-                                   int8_t *exp, int start, int end,
-                                   int snr_offset, int fast_gain, int is_lfe,
-                                   int dba_mode, int dba_nsegs,
-                                   uint8_t *dba_offsets, uint8_t *dba_lengths,
-                                   uint8_t *dba_values)
-{
-    int16_t psd[256];   /* scaled exponents */
-    int16_t band_psd[50]; /* interpolated exponents */
-    int16_t mask[50];   /* masking value */
-
-    ff_ac3_bit_alloc_calc_psd(exp, start, end, psd, band_psd);
-
-    ff_ac3_bit_alloc_calc_mask(s, band_psd, start, end, fast_gain, is_lfe,
-                               dba_mode, dba_nsegs, dba_offsets, dba_lengths,
-                               dba_values, mask);
-
-    ff_ac3_bit_alloc_calc_bap(mask, psd, start, end, snr_offset, s->floor,
-                              ff_ac3_bap_tab, bap);
-}
-
 /**
- * Initializes some tables.
+ * Initialize some tables.
  * note: This function must remain thread safe because it is called by the
  *       AVParser init code.
  */
-av_cold void ac3_common_init(void)
+av_cold void ff_ac3_common_init(void)
 {
 #if !CONFIG_HARDCODED_TABLES
-    /* compute bndtab and masktab from bandsz */
+    /* compute ff_ac3_bin_to_band_tab from ff_ac3_band_start_tab */
     int bin = 0, band;
-    for (band = 0; band < 50; band++) {
-        int band_end = bin + ff_ac3_critical_band_size_tab[band];
-        band_start_tab[band] = bin;
+    for (band = 0; band < AC3_CRITICAL_BANDS; band++) {
+        int band_end = ff_ac3_band_start_tab[band+1];
         while (bin < band_end)
-            bin_to_band_tab[bin++] = band;
+            ff_ac3_bin_to_band_tab[bin++] = band;
     }
-    band_start_tab[50] = bin;
 #endif /* !CONFIG_HARDCODED_TABLES */
 }
diff --git a/libavcodec/ac3.h b/libavcodec/ac3.h
index 0def3b0..4ed8c25 100644
--- a/libavcodec/ac3.h
+++ b/libavcodec/ac3.h
@@ -2,20 +2,20 @@
  * Common code between the AC-3 encoder and decoder
  * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -27,13 +27,18 @@
 #ifndef AVCODEC_AC3_H
 #define AVCODEC_AC3_H
 
-#include "ac3tab.h"
-
 #define AC3_MAX_CODED_FRAME_SIZE 3840 /* in bytes */
 #define AC3_MAX_CHANNELS 6 /* including LFE channel */
 
-#define NB_BLOCKS 6 /* number of PCM blocks inside an AC-3 frame */
-#define AC3_FRAME_SIZE (NB_BLOCKS * 256)
+#define AC3_MAX_COEFS   256
+#define AC3_BLOCK_SIZE  256
+#define AC3_MAX_BLOCKS    6
+#define AC3_FRAME_SIZE (AC3_MAX_BLOCKS * 256)
+#define AC3_WINDOW_SIZE (AC3_BLOCK_SIZE * 2)
+#define AC3_CRITICAL_BANDS 50
+#define AC3_MAX_CPL_BANDS  18
+
+#include "ac3tab.h"
 
 /* exponent encoding strategy */
 #define EXP_REUSE 0
@@ -43,6 +48,17 @@
 #define EXP_D25   2
 #define EXP_D45   3
 
+/* pre-defined gain values */
+#define LEVEL_PLUS_3DB          1.4142135623730950
+#define LEVEL_PLUS_1POINT5DB    1.1892071150027209
+#define LEVEL_MINUS_1POINT5DB   0.8408964152537145
+#define LEVEL_MINUS_3DB         0.7071067811865476
+#define LEVEL_MINUS_4POINT5DB   0.5946035575013605
+#define LEVEL_MINUS_6DB         0.5000000000000000
+#define LEVEL_MINUS_9DB         0.3535533905932738
+#define LEVEL_ZERO              0.0000000000000000
+#define LEVEL_ONE               1.0000000000000000
+
 /** Delta bit allocation strategy */
 typedef enum {
     DBA_REUSE = 0,
@@ -82,6 +98,7 @@ typedef struct {
     uint16_t crc1;
     uint8_t sr_code;
     uint8_t bitstream_id;
+    uint8_t bitstream_mode;
     uint8_t channel_mode;
     uint8_t lfe_on;
     uint8_t frame_type;
@@ -111,10 +128,10 @@ typedef enum {
     EAC3_FRAME_TYPE_RESERVED
 } EAC3FrameType;
 
-void ac3_common_init(void);
+void ff_ac3_common_init(void);
 
 /**
- * Calculates the log power-spectral density of the input signal.
+ * Calculate the log power-spectral density of the input signal.
  * This gives a rough estimate of signal power in the frequency domain by using
  * the spectral envelope (exponents).  The psd is also separately grouped
  * into critical bands for use in the calculating the masking curve.
@@ -131,7 +148,7 @@ void ff_ac3_bit_alloc_calc_psd(int8_t *exp, int start, int end, int16_t *psd,
                                int16_t *band_psd);
 
 /**
- * Calculates the masking curve.
+ * Calculate the masking curve.
  * First, the excitation is calculated using parameters in s and the signal
  * power in each critical band.  The excitation is compared with a predefined
  * hearing threshold table to produce the masking curve.  If delta bit
@@ -158,30 +175,4 @@ int ff_ac3_bit_alloc_calc_mask(AC3BitAllocParameters *s, int16_t *band_psd,
                                uint8_t *dba_lengths, uint8_t *dba_values,
                                int16_t *mask);
 
-/**
- * Calculates bit allocation pointers.
- * The SNR is the difference between the masking curve and the signal.  AC-3
- * uses this value for each frequency bin to allocate bits.  The snroffset
- * parameter is a global adjustment to the SNR for all bins.
- *
- * @param[in]  mask       masking curve
- * @param[in]  psd        signal power for each frequency bin
- * @param[in]  start      starting bin location
- * @param[in]  end        ending bin location
- * @param[in]  snr_offset SNR adjustment
- * @param[in]  floor      noise floor
- * @param[in]  bap_tab    look-up table for bit allocation pointers
- * @param[out] bap        bit allocation pointers
- */
-void ff_ac3_bit_alloc_calc_bap(int16_t *mask, int16_t *psd, int start, int end,
-                               int snr_offset, int floor,
-                               const uint8_t *bap_tab, uint8_t *bap);
-
-void ac3_parametric_bit_allocation(AC3BitAllocParameters *s, uint8_t *bap,
-                                   int8_t *exp, int start, int end,
-                                   int snr_offset, int fast_gain, int is_lfe,
-                                   int dba_mode, int dba_nsegs,
-                                   uint8_t *dba_offsets, uint8_t *dba_lengths,
-                                   uint8_t *dba_values);
-
 #endif /* AVCODEC_AC3_H */
diff --git a/libavcodec/ac3_parser.c b/libavcodec/ac3_parser.c
index 856f97a..82eeda3 100644
--- a/libavcodec/ac3_parser.c
+++ b/libavcodec/ac3_parser.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2003 Fabrice Bellard
  * Copyright (c) 2003 Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -24,6 +24,7 @@
 #include "ac3_parser.h"
 #include "aac_ac3_parser.h"
 #include "get_bits.h"
+#include "libavutil/audioconvert.h"
 
 
 #define AC3_HEADER_SIZE 7
@@ -68,7 +69,7 @@ int ff_ac3_parse_header(GetBitContext *gbc, AC3HeaderInfo *hdr)
 
         skip_bits(gbc, 5); // skip bsid, already got it
 
-        skip_bits(gbc, 3); // skip bitstream mode
+        hdr->bitstream_mode = get_bits(gbc, 3);
         hdr->channel_mode = get_bits(gbc, 3);
 
         if(hdr->channel_mode == AC3_CHMODE_STEREO) {
@@ -123,40 +124,11 @@ int ff_ac3_parse_header(GetBitContext *gbc, AC3HeaderInfo *hdr)
     }
     hdr->channel_layout = ff_ac3_channel_layout_tab[hdr->channel_mode];
     if (hdr->lfe_on)
-        hdr->channel_layout |= CH_LOW_FREQUENCY;
+        hdr->channel_layout |= AV_CH_LOW_FREQUENCY;
 
     return 0;
 }
 
-int ff_ac3_parse_header_full(GetBitContext *gbc, AC3HeaderInfo *hdr){
-    int ret, i;
-    ret = ff_ac3_parse_header(gbc, hdr);
-    if(!ret){
-        if(hdr->bitstream_id>10){
-            /* Enhanced AC-3 */
-            skip_bits(gbc, 5); // skip bitstream id
-
-            /* skip dialog normalization and compression gain */
-            for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) {
-                skip_bits(gbc, 5); // skip dialog normalization
-                if (get_bits1(gbc)) {
-                    skip_bits(gbc, 8); //skip Compression gain word
-                }
-            }
-            /* dependent stream channel map */
-            if (hdr->frame_type == EAC3_FRAME_TYPE_DEPENDENT && get_bits1(gbc)) {
-                    hdr->channel_map = get_bits(gbc, 16); //custom channel map
-                    return 0;
-            }
-        }
-        //default channel map based on acmod and lfeon
-        hdr->channel_map = ff_eac3_default_chmap[hdr->channel_mode];
-        if(hdr->lfe_on)
-            hdr->channel_map |= AC3_CHMAP_LFE;
-    }
-    return ret;
-}
-
 static int ac3_sync(uint64_t state, AACAC3ParseContext *hdr_info,
         int *need_next_header, int *new_frame_start)
 {
@@ -164,7 +136,7 @@ static int ac3_sync(uint64_t state, AACAC3ParseContext *hdr_info,
     union {
         uint64_t u64;
         uint8_t  u8[8];
-    } tmp = { be2me_64(state) };
+    } tmp = { av_be2ne64(state) };
     AC3HeaderInfo hdr;
     GetBitContext gbc;
 
@@ -179,9 +151,12 @@ static int ac3_sync(uint64_t state, AACAC3ParseContext *hdr_info,
     hdr_info->channels = hdr.channels;
     hdr_info->channel_layout = hdr.channel_layout;
     hdr_info->samples = hdr.num_blocks * 256;
+    hdr_info->service_type = hdr.bitstream_mode;
+    if (hdr.bitstream_mode == 0x7 && hdr.channels > 1)
+        hdr_info->service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
     if(hdr.bitstream_id>10)
         hdr_info->codec_id = CODEC_ID_EAC3;
-    else
+    else if (hdr_info->codec_id == CODEC_ID_NONE)
         hdr_info->codec_id = CODEC_ID_AC3;
 
     *need_next_header = (hdr.frame_type != EAC3_FRAME_TYPE_AC3_CONVERT);
@@ -198,7 +173,7 @@ static av_cold int ac3_parse_init(AVCodecParserContext *s1)
 }
 
 
-AVCodecParser ac3_parser = {
+AVCodecParser ff_ac3_parser = {
     { CODEC_ID_AC3, CODEC_ID_EAC3 },
     sizeof(AACAC3ParseContext),
     ac3_parse_init,
diff --git a/libavcodec/ac3_parser.h b/libavcodec/ac3_parser.h
index 766c68b..d62490b 100644
--- a/libavcodec/ac3_parser.h
+++ b/libavcodec/ac3_parser.h
@@ -3,20 +3,20 @@
  * Copyright (c) 2003 Fabrice Bellard
  * Copyright (c) 2003 Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -27,26 +27,15 @@
 #include "get_bits.h"
 
 /**
- * Parses AC-3 frame header.
- * Parses the header up to the lfeon element, which is the first 52 or 54 bits
+ * Parse AC-3 frame header.
+ * Parse the header up to the lfeon element, which is the first 52 or 54 bits
  * depending on the audio coding mode.
- * @param gbc[in] BitContext containing the first 54 bits of the frame.
- * @param hdr[out] Pointer to struct where header info is written.
+ * @param[in]  gbc BitContext containing the first 54 bits of the frame.
+ * @param[out] hdr Pointer to struct where header info is written.
  * @return Returns 0 on success, -1 if there is a sync word mismatch,
  * -2 if the bsid (version) element is invalid, -3 if the fscod (sample rate)
  * element is invalid, or -4 if the frmsizecod (bit rate) element is invalid.
  */
 int ff_ac3_parse_header(GetBitContext *gbc, AC3HeaderInfo *hdr);
 
-/**
- * Parses AC-3 frame header and sets channel_map
- * Parses the header up to the lfeon (channel_map in E-AC-3)
- * element, which is the first 52, 54 or 104 bits depending
- * on the audio coding mode.
- * @param gbc[in] BitContext containing the first 54 bits of the frame.
- * @param hdr[out] Pointer to struct where header info is written.
- * @return value returned by ff_ac3_parse_header
- */
-int ff_ac3_parse_header_full(GetBitContext *gbc, AC3HeaderInfo *hdr);
-
 #endif /* AVCODEC_AC3_PARSER_H */
diff --git a/libavcodec/ac3dec.c b/libavcodec/ac3dec.c
index f2f6e5c..015ebae 100644
--- a/libavcodec/ac3dec.c
+++ b/libavcodec/ac3dec.c
@@ -7,20 +7,20 @@
  * Copyright (c) 2007-2008 Bartlomiej Wolowiec <bartek.wolowiec at gmail.com>
  * Copyright (c) 2007 Justin Ruggles <justin.ruggles at gmail.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -35,6 +35,7 @@
 #include "ac3_parser.h"
 #include "ac3dec.h"
 #include "ac3dec_data.h"
+#include "kbdwin.h"
 
 /** Large enough for maximum possible frame size when the specification limit is ignored */
 #define AC3_FRAME_BUFFER_SIZE 32768
@@ -66,16 +67,6 @@ static const uint8_t quantization_tab[16] = {
 static float dynamic_range_tab[256];
 
 /** Adjustments in dB gain */
-#define LEVEL_PLUS_3DB          1.4142135623730950
-#define LEVEL_PLUS_1POINT5DB    1.1892071150027209
-#define LEVEL_MINUS_1POINT5DB   0.8408964152537145
-#define LEVEL_MINUS_3DB         0.7071067811865476
-#define LEVEL_MINUS_4POINT5DB   0.5946035575013605
-#define LEVEL_MINUS_6DB         0.5000000000000000
-#define LEVEL_MINUS_9DB         0.3535533905932738
-#define LEVEL_ZERO              0.0000000000000000
-#define LEVEL_ONE               1.0000000000000000
-
 static const float gain_levels[9] = {
     LEVEL_PLUS_3DB,
     LEVEL_PLUS_1POINT5DB,
@@ -187,22 +178,18 @@ static av_cold int ac3_decode_init(AVCodecContext *avctx)
     AC3DecodeContext *s = avctx->priv_data;
     s->avctx = avctx;
 
-    ac3_common_init();
+    ff_ac3_common_init();
     ac3_tables_init();
     ff_mdct_init(&s->imdct_256, 8, 1, 1.0);
     ff_mdct_init(&s->imdct_512, 9, 1, 1.0);
     ff_kbd_window_init(s->window, 5.0, 256);
     dsputil_init(&s->dsp, avctx);
+    ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
+    ff_fmt_convert_init(&s->fmt_conv, avctx);
     av_lfg_init(&s->dith_state, 0);
 
-    /* set bias values for float to int16 conversion */
-    if(s->dsp.float_to_int16_interleave == ff_float_to_int16_interleave_c) {
-        s->add_bias = 385.0f;
-        s->mul_bias = 1.0f;
-    } else {
-        s->add_bias = 0.0f;
-        s->mul_bias = 32767.0f;
-    }
+    /* set scale value for float to int16 conversion */
+    s->mul_bias = 32767.0f;
 
     /* allow downmixing to stereo or mono */
     if (avctx->channels > 0 && avctx->request_channels > 0 &&
@@ -213,13 +200,11 @@ static av_cold int ac3_decode_init(AVCodecContext *avctx)
     s->downmixed = 1;
 
     /* allocate context input buffer */
-    if (avctx->error_recognition >= FF_ER_CAREFUL) {
         s->input_buffer = av_mallocz(AC3_FRAME_BUFFER_SIZE + FF_INPUT_BUFFER_PADDING_SIZE);
         if (!s->input_buffer)
             return AVERROR(ENOMEM);
-    }
 
-    avctx->sample_fmt = SAMPLE_FMT_S16;
+    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
     return 0;
 }
 
@@ -279,6 +264,7 @@ static int parse_frame_header(AC3DecodeContext *s)
 
     /* get decoding parameters from header info */
     s->bit_alloc_params.sr_code     = hdr.sr_code;
+    s->bitstream_mode               = hdr.bitstream_mode;
     s->channel_mode                 = hdr.channel_mode;
     s->channel_layout               = hdr.channel_layout;
     s->lfe_on                       = hdr.lfe_on;
@@ -626,9 +612,6 @@ static void do_rematrixing(AC3DecodeContext *s)
 static inline void do_imdct(AC3DecodeContext *s, int channels)
 {
     int ch;
-    float add_bias = s->add_bias;
-    if(s->out_channels==1 && channels>1)
-        add_bias *= LEVEL_MINUS_3DB; // compensate for the gain in downmix
 
     for (ch=1; ch<=channels; ch++) {
         if (s->block_switch[ch]) {
@@ -636,14 +619,14 @@ static inline void do_imdct(AC3DecodeContext *s, int channels)
             float *x = s->tmp_output+128;
             for(i=0; i<128; i++)
                 x[i] = s->transform_coeffs[ch][2*i];
-            ff_imdct_half(&s->imdct_256, s->tmp_output, x);
-            s->dsp.vector_fmul_window(s->output[ch-1], s->delay[ch-1], s->tmp_output, s->window, add_bias, 128);
+            s->imdct_256.imdct_half(&s->imdct_256, s->tmp_output, x);
+            s->dsp.vector_fmul_window(s->output[ch-1], s->delay[ch-1], s->tmp_output, s->window, 128);
             for(i=0; i<128; i++)
                 x[i] = s->transform_coeffs[ch][2*i+1];
-            ff_imdct_half(&s->imdct_256, s->delay[ch-1], x);
+            s->imdct_256.imdct_half(&s->imdct_256, s->delay[ch-1], x);
         } else {
-            ff_imdct_half(&s->imdct_512, s->tmp_output, s->transform_coeffs[ch]);
-            s->dsp.vector_fmul_window(s->output[ch-1], s->delay[ch-1], s->tmp_output, s->window, add_bias, 128);
+            s->imdct_512.imdct_half(&s->imdct_512, s->tmp_output, s->transform_coeffs[ch]);
+            s->dsp.vector_fmul_window(s->output[ch-1], s->delay[ch-1], s->tmp_output, s->window, 128);
             memcpy(s->delay[ch-1], s->tmp_output+128, 128*sizeof(float));
         }
     }
@@ -1190,8 +1173,8 @@ static int decode_audio_block(AC3DecodeContext *s, int blk)
         /* channel delta offset, len and bit allocation */
         for (ch = !cpl_in_use; ch <= fbw_channels; ch++) {
             if (s->dba_mode[ch] == DBA_NEW) {
-                s->dba_nsegs[ch] = get_bits(gbc, 3);
-                for (seg = 0; seg <= s->dba_nsegs[ch]; seg++) {
+                s->dba_nsegs[ch] = get_bits(gbc, 3) + 1;
+                for (seg = 0; seg < s->dba_nsegs[ch]; seg++) {
                     s->dba_offsets[ch][seg] = get_bits(gbc, 5);
                     s->dba_lengths[ch][seg] = get_bits(gbc, 4);
                     s->dba_values[ch][seg] = get_bits(gbc, 3);
@@ -1231,7 +1214,7 @@ static int decode_audio_block(AC3DecodeContext *s, int blk)
             /* Compute bit allocation */
             const uint8_t *bap_tab = s->channel_uses_aht[ch] ?
                                      ff_eac3_hebap_tab : ff_ac3_bap_tab;
-            ff_ac3_bit_alloc_calc_bap(s->mask[ch], s->psd[ch],
+            s->ac3dsp.bit_alloc_calc_bap(s->mask[ch], s->psd[ch],
                                       s->start_freq[ch], s->end_freq[ch],
                                       s->snr_offset[ch],
                                       s->bit_alloc_params.floor,
@@ -1264,7 +1247,7 @@ static int decode_audio_block(AC3DecodeContext *s, int blk)
         } else {
             gain *= s->dynamic_range[0];
         }
-        s->dsp.int32_to_float_fmul_scalar(s->transform_coeffs[ch], s->fixed_coeffs[ch], gain, 256);
+        s->fmt_conv.int32_to_float_fmul_scalar(s->transform_coeffs[ch], s->fixed_coeffs[ch], gain, 256);
     }
 
     /* apply spectral extension to high frequency bins */
@@ -1321,15 +1304,17 @@ static int ac3_decode_frame(AVCodecContext * avctx, void *data, int *data_size,
     const uint8_t *channel_map;
     const float *output[AC3_MAX_CHANNELS];
 
-    /* initialize the GetBitContext with the start of valid AC-3 Frame */
-    if (s->input_buffer) {
-        /* copy input buffer to decoder context to avoid reading past the end
-           of the buffer, which can be caused by a damaged input stream. */
+    /* copy input buffer to decoder context to avoid reading past the end
+       of the buffer, which can be caused by a damaged input stream. */
+    if (buf_size >= 2 && AV_RB16(buf) == 0x770B) {
+        // seems to be byte-swapped AC-3
+        int cnt = FFMIN(buf_size, AC3_FRAME_BUFFER_SIZE) >> 1;
+        s->dsp.bswap16_buf((uint16_t *)s->input_buffer, (const uint16_t *)buf, cnt);
+    } else
         memcpy(s->input_buffer, buf, FFMIN(buf_size, AC3_FRAME_BUFFER_SIZE));
-        init_get_bits(&s->gbc, s->input_buffer, buf_size * 8);
-    } else {
-        init_get_bits(&s->gbc, buf, buf_size * 8);
-    }
+    buf = s->input_buffer;
+    /* initialize the GetBitContext with the start of valid AC-3 Frame */
+    init_get_bits(&s->gbc, buf, buf_size * 8);
 
     /* parse the syncinfo */
     *data_size = 0;
@@ -1406,6 +1391,10 @@ static int ac3_decode_frame(AVCodecContext * avctx, void *data, int *data_size,
         if(s->out_channels < s->channels)
             s->output_mode  = s->out_channels == 1 ? AC3_CHMODE_MONO : AC3_CHMODE_STEREO;
     }
+    /* set audio service type based on bitstream mode for AC-3 */
+    avctx->audio_service_type = s->bitstream_mode;
+    if (s->bitstream_mode == 0x7 && s->channels > 1)
+        avctx->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
 
     /* decode the audio blocks */
     channel_map = ff_ac3_dec_channel_map[s->output_mode & ~AC3_OUTPUT_LFEON][s->lfe_on];
@@ -1416,7 +1405,7 @@ static int ac3_decode_frame(AVCodecContext * avctx, void *data, int *data_size,
             av_log(avctx, AV_LOG_ERROR, "error decoding the audio block\n");
             err = 1;
         }
-        s->dsp.float_to_int16_interleave(out_samples, output, 256, s->out_channels);
+        s->fmt_conv.float_to_int16_interleave(out_samples, output, 256, s->out_channels);
         out_samples += 256 * s->out_channels;
     }
     *data_size = s->num_blocks * 256 * avctx->channels * sizeof (int16_t);
@@ -1437,7 +1426,7 @@ static av_cold int ac3_decode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec ac3_decoder = {
+AVCodec ff_ac3_decoder = {
     .name = "ac3",
     .type = AVMEDIA_TYPE_AUDIO,
     .id = CODEC_ID_AC3,
@@ -1449,7 +1438,7 @@ AVCodec ac3_decoder = {
 };
 
 #if CONFIG_EAC3_DECODER
-AVCodec eac3_decoder = {
+AVCodec ff_eac3_decoder = {
     .name = "eac3",
     .type = AVMEDIA_TYPE_AUDIO,
     .id = CODEC_ID_EAC3,
diff --git a/libavcodec/ac3dec.h b/libavcodec/ac3dec.h
index 8c0d442..3459441 100644
--- a/libavcodec/ac3dec.h
+++ b/libavcodec/ac3dec.h
@@ -2,20 +2,20 @@
  * Common code between the AC-3 and E-AC-3 decoders
  * Copyright (c) 2007 Bartlomiej Wolowiec <bartek.wolowiec at gmail.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -52,9 +52,11 @@
 
 #include "libavutil/lfg.h"
 #include "ac3.h"
+#include "ac3dsp.h"
 #include "get_bits.h"
 #include "dsputil.h"
 #include "fft.h"
+#include "fmtconvert.h"
 
 /* override ac3.h to include coupling channel */
 #undef AC3_MAX_CHANNELS
@@ -63,9 +65,6 @@
 
 #define AC3_OUTPUT_LFEON  8
 
-#define AC3_MAX_COEFS   256
-#define AC3_BLOCK_SIZE  256
-#define MAX_BLOCKS        6
 #define SPX_MAX_BANDS    17
 
 typedef struct {
@@ -81,6 +80,7 @@ typedef struct {
     int bit_rate;                           ///< stream bit rate, in bits-per-second
     int sample_rate;                        ///< sample frequency, in Hz
     int num_blocks;                         ///< number of audio blocks
+    int bitstream_mode;                     ///< bitstream mode                         (bsmod)
     int channel_mode;                       ///< channel mode                           (acmod)
     int channel_layout;                     ///< channel layout
     int lfe_on;                             ///< lfe channel in use
@@ -101,16 +101,16 @@ typedef struct {
  ///@}
 
 ///@defgroup cpl standard coupling
-    int cpl_in_use[MAX_BLOCKS];             ///< coupling in use                        (cplinu)
-    int cpl_strategy_exists[MAX_BLOCKS];    ///< coupling strategy exists               (cplstre)
+    int cpl_in_use[AC3_MAX_BLOCKS];         ///< coupling in use                        (cplinu)
+    int cpl_strategy_exists[AC3_MAX_BLOCKS];///< coupling strategy exists               (cplstre)
     int channel_in_cpl[AC3_MAX_CHANNELS];   ///< channel in coupling                    (chincpl)
     int phase_flags_in_use;                 ///< phase flags in use                     (phsflginu)
-    int phase_flags[18];                    ///< phase flags                            (phsflg)
+    int phase_flags[AC3_MAX_CPL_BANDS];     ///< phase flags                            (phsflg)
     int num_cpl_bands;                      ///< number of coupling bands               (ncplbnd)
-    uint8_t cpl_band_sizes[18];             ///< number of coeffs in each coupling band
+    uint8_t cpl_band_sizes[AC3_MAX_CPL_BANDS]; ///< number of coeffs in each coupling band
     int firstchincpl;                       ///< first channel in coupling
     int first_cpl_coords[AC3_MAX_CHANNELS]; ///< first coupling coordinates states      (firstcplcos)
-    int cpl_coords[AC3_MAX_CHANNELS][18];   ///< coupling coordinates                   (cplco)
+    int cpl_coords[AC3_MAX_CHANNELS][AC3_MAX_CPL_BANDS]; ///< coupling coordinates      (cplco)
 ///@}
 
 ///@defgroup spx spectral extension
@@ -131,7 +131,7 @@ typedef struct {
 
 ///@defgroup aht adaptive hybrid transform
     int channel_uses_aht[AC3_MAX_CHANNELS];                         ///< channel AHT in use (chahtinu)
-    int pre_mantissa[AC3_MAX_CHANNELS][AC3_MAX_COEFS][MAX_BLOCKS];  ///< pre-IDCT mantissas
+    int pre_mantissa[AC3_MAX_CHANNELS][AC3_MAX_COEFS][AC3_MAX_BLOCKS];  ///< pre-IDCT mantissas
 ///@}
 
 ///@defgroup channel channel
@@ -161,7 +161,7 @@ typedef struct {
 ///@defgroup exponents exponents
     int num_exp_groups[AC3_MAX_CHANNELS];           ///< Number of exponent groups      (nexpgrp)
     int8_t dexps[AC3_MAX_CHANNELS][AC3_MAX_COEFS];  ///< decoded exponents
-    int exp_strategy[MAX_BLOCKS][AC3_MAX_CHANNELS]; ///< exponent strategies            (expstr)
+    int exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS]; ///< exponent strategies        (expstr)
 ///@}
 
 ///@defgroup bitalloc bit allocation
@@ -171,8 +171,8 @@ typedef struct {
     int fast_gain[AC3_MAX_CHANNELS];                ///< fast gain values/SMR's         (fgain)
     uint8_t bap[AC3_MAX_CHANNELS][AC3_MAX_COEFS];   ///< bit allocation pointers
     int16_t psd[AC3_MAX_CHANNELS][AC3_MAX_COEFS];   ///< scaled exponents
-    int16_t band_psd[AC3_MAX_CHANNELS][50];         ///< interpolated exponents
-    int16_t mask[AC3_MAX_CHANNELS][50];             ///< masking curve values
+    int16_t band_psd[AC3_MAX_CHANNELS][AC3_CRITICAL_BANDS]; ///< interpolated exponents
+    int16_t mask[AC3_MAX_CHANNELS][AC3_CRITICAL_BANDS];     ///< masking curve values
     int dba_mode[AC3_MAX_CHANNELS];                 ///< delta bit allocation mode
     int dba_nsegs[AC3_MAX_CHANNELS];                ///< number of delta segments
     uint8_t dba_offsets[AC3_MAX_CHANNELS][8];       ///< delta segment offsets
@@ -193,7 +193,8 @@ typedef struct {
 
 ///@defgroup opt optimization
     DSPContext dsp;                         ///< for optimization
-    float add_bias;                         ///< offset for float_to_int16 conversion
+    AC3DSPContext ac3dsp;
+    FmtConvertContext fmt_conv;             ///< optimized conversion functions
     float mul_bias;                         ///< scaling for float_to_int16 conversion
 ///@}
 
diff --git a/libavcodec/ac3dec_data.c b/libavcodec/ac3dec_data.c
index ea13d3d..ba3cbd3 100644
--- a/libavcodec/ac3dec_data.c
+++ b/libavcodec/ac3dec_data.c
@@ -2,20 +2,20 @@
  * AC-3 and E-AC-3 decoder tables
  * Copyright (c) 2007 Bartlomiej Wolowiec <bartek.wolowiec at gmail.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -43,12 +43,6 @@ const uint8_t ff_ac3_ungroup_3_in_5_bits_tab[32][3] = {
     { 3, 0, 1 }, { 3, 0, 2 }, { 3, 1, 0 }, { 3, 1, 1 }
 };
 
-/**
- * Table of bin locations for rematrixing bands
- * reference: Section 7.5.2 Rematrixing : Frequency Band Definitions
- */
-const uint8_t ff_ac3_rematrix_band_tab[5] = { 13, 25, 37, 61, 253 };
-
 const uint8_t ff_eac3_hebap_tab[64] = {
     0, 1, 2, 3, 4, 5, 6, 7, 8, 8,
     8, 8, 9, 9, 9, 10, 10, 10, 10, 11,
diff --git a/libavcodec/ac3dec_data.h b/libavcodec/ac3dec_data.h
index 9ed7c73..a758f8b 100644
--- a/libavcodec/ac3dec_data.h
+++ b/libavcodec/ac3dec_data.h
@@ -2,20 +2,20 @@
  * AC-3 and E-AC-3 decoder tables
  * Copyright (c) 2007 Bartlomiej Wolowiec <bartek.wolowiec at gmail.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,7 +25,6 @@
 #include <stdint.h>
 
 extern const uint8_t ff_ac3_ungroup_3_in_5_bits_tab[32][3];
-extern const uint8_t ff_ac3_rematrix_band_tab[5];
 
 extern const uint8_t ff_eac3_hebap_tab[64];
 extern const uint8_t ff_eac3_default_cpl_band_struct[18];
diff --git a/libavcodec/ac3dsp.c b/libavcodec/ac3dsp.c
new file mode 100644
index 0000000..dccad3b
--- /dev/null
+++ b/libavcodec/ac3dsp.c
@@ -0,0 +1,189 @@
+/*
+ * AC-3 DSP utils
+ * Copyright (c) 2011 Justin Ruggles
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "libavutil/avassert.h"
+#include "avcodec.h"
+#include "ac3.h"
+#include "ac3dsp.h"
+
+static void ac3_exponent_min_c(uint8_t *exp, int num_reuse_blocks, int nb_coefs)
+{
+    int blk, i;
+
+    if (!num_reuse_blocks)
+        return;
+
+    for (i = 0; i < nb_coefs; i++) {
+        uint8_t min_exp = *exp;
+        uint8_t *exp1 = exp + 256;
+        for (blk = 0; blk < num_reuse_blocks; blk++) {
+            uint8_t next_exp = *exp1;
+            if (next_exp < min_exp)
+                min_exp = next_exp;
+            exp1 += 256;
+        }
+        *exp++ = min_exp;
+    }
+}
+
+static int ac3_max_msb_abs_int16_c(const int16_t *src, int len)
+{
+    int i, v = 0;
+    for (i = 0; i < len; i++)
+        v |= abs(src[i]);
+    return v;
+}
+
+static void ac3_lshift_int16_c(int16_t *src, unsigned int len,
+                               unsigned int shift)
+{
+    uint32_t *src32 = (uint32_t *)src;
+    const uint32_t mask = ~(((1 << shift) - 1) << 16);
+    int i;
+    len >>= 1;
+    for (i = 0; i < len; i += 8) {
+        src32[i  ] = (src32[i  ] << shift) & mask;
+        src32[i+1] = (src32[i+1] << shift) & mask;
+        src32[i+2] = (src32[i+2] << shift) & mask;
+        src32[i+3] = (src32[i+3] << shift) & mask;
+        src32[i+4] = (src32[i+4] << shift) & mask;
+        src32[i+5] = (src32[i+5] << shift) & mask;
+        src32[i+6] = (src32[i+6] << shift) & mask;
+        src32[i+7] = (src32[i+7] << shift) & mask;
+    }
+}
+
+static void ac3_rshift_int32_c(int32_t *src, unsigned int len,
+                               unsigned int shift)
+{
+    do {
+        *src++ >>= shift;
+        *src++ >>= shift;
+        *src++ >>= shift;
+        *src++ >>= shift;
+        *src++ >>= shift;
+        *src++ >>= shift;
+        *src++ >>= shift;
+        *src++ >>= shift;
+        len -= 8;
+    } while (len > 0);
+}
+
+static void float_to_fixed24_c(int32_t *dst, const float *src, unsigned int len)
+{
+    const float scale = 1 << 24;
+    do {
+        *dst++ = lrintf(*src++ * scale);
+        *dst++ = lrintf(*src++ * scale);
+        *dst++ = lrintf(*src++ * scale);
+        *dst++ = lrintf(*src++ * scale);
+        *dst++ = lrintf(*src++ * scale);
+        *dst++ = lrintf(*src++ * scale);
+        *dst++ = lrintf(*src++ * scale);
+        *dst++ = lrintf(*src++ * scale);
+        len -= 8;
+    } while (len > 0);
+}
+
+static void ac3_bit_alloc_calc_bap_c(int16_t *mask, int16_t *psd,
+                                     int start, int end,
+                                     int snr_offset, int floor,
+                                     const uint8_t *bap_tab, uint8_t *bap)
+{
+    int bin, band;
+
+    /* special case, if snr offset is -960, set all bap's to zero */
+    if (snr_offset == -960) {
+        memset(bap, 0, AC3_MAX_COEFS);
+        return;
+    }
+
+    bin  = start;
+    band = ff_ac3_bin_to_band_tab[start];
+    do {
+        int m = (FFMAX(mask[band] - snr_offset - floor, 0) & 0x1FE0) + floor;
+        int band_end = FFMIN(ff_ac3_band_start_tab[band+1], end);
+        for (; bin < band_end; bin++) {
+            int address = av_clip((psd[bin] - m) >> 5, 0, 63);
+            bap[bin] = bap_tab[address];
+        }
+    } while (end > ff_ac3_band_start_tab[band++]);
+}
+
+static int ac3_compute_mantissa_size_c(int mant_cnt[5], uint8_t *bap,
+                                       int nb_coefs)
+{
+    int bits, b, i;
+
+    bits = 0;
+    for (i = 0; i < nb_coefs; i++) {
+        b = bap[i];
+        if (b <= 4) {
+            // bap=1 to bap=4 will be counted in compute_mantissa_size_final
+            mant_cnt[b]++;
+        } else if (b <= 13) {
+            // bap=5 to bap=13 use (bap-1) bits
+            bits += b - 1;
+        } else {
+            // bap=14 uses 14 bits and bap=15 uses 16 bits
+            bits += (b == 14) ? 14 : 16;
+        }
+    }
+    return bits;
+}
+
+static void ac3_extract_exponents_c(uint8_t *exp, int32_t *coef, int nb_coefs)
+{
+    int i;
+
+    for (i = 0; i < nb_coefs; i++) {
+        int e;
+        int v = abs(coef[i]);
+        if (v == 0)
+            e = 24;
+        else {
+            e = 23 - av_log2(v);
+            if (e >= 24) {
+                e = 24;
+                coef[i] = 0;
+            }
+            av_assert2(e >= 0);
+        }
+        exp[i] = e;
+    }
+}
+
+av_cold void ff_ac3dsp_init(AC3DSPContext *c, int bit_exact)
+{
+    c->ac3_exponent_min = ac3_exponent_min_c;
+    c->ac3_max_msb_abs_int16 = ac3_max_msb_abs_int16_c;
+    c->ac3_lshift_int16 = ac3_lshift_int16_c;
+    c->ac3_rshift_int32 = ac3_rshift_int32_c;
+    c->float_to_fixed24 = float_to_fixed24_c;
+    c->bit_alloc_calc_bap = ac3_bit_alloc_calc_bap_c;
+    c->compute_mantissa_size = ac3_compute_mantissa_size_c;
+    c->extract_exponents = ac3_extract_exponents_c;
+
+    if (ARCH_ARM)
+        ff_ac3dsp_init_arm(c, bit_exact);
+    if (HAVE_MMX)
+        ff_ac3dsp_init_x86(c, bit_exact);
+}
diff --git a/libavcodec/ac3dsp.h b/libavcodec/ac3dsp.h
new file mode 100644
index 0000000..b750767
--- /dev/null
+++ b/libavcodec/ac3dsp.h
@@ -0,0 +1,116 @@
+/*
+ * AC-3 DSP utils
+ * Copyright (c) 2011 Justin Ruggles
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_AC3DSP_H
+#define AVCODEC_AC3DSP_H
+
+#include <stdint.h>
+
+typedef struct AC3DSPContext {
+    /**
+     * Set each encoded exponent in a block to the minimum of itself and the
+     * exponents in the same frequency bin of up to 5 following blocks.
+     * @param exp   pointer to the start of the current block of exponents.
+     *              constraints: align 16
+     * @param num_reuse_blocks  number of blocks that will reuse exponents from the current block.
+     *                          constraints: range 0 to 5
+     * @param nb_coefs  number of frequency coefficients.
+     */
+    void (*ac3_exponent_min)(uint8_t *exp, int num_reuse_blocks, int nb_coefs);
+
+    /**
+     * Calculate the maximum MSB of the absolute value of each element in an
+     * array of int16_t.
+     * @param src input array
+     *            constraints: align 16. values must be in range [-32767,32767]
+     * @param len number of values in the array
+     *            constraints: multiple of 16 greater than 0
+     * @return    a value with the same MSB as max(abs(src[]))
+     */
+    int (*ac3_max_msb_abs_int16)(const int16_t *src, int len);
+
+    /**
+     * Left-shift each value in an array of int16_t by a specified amount.
+     * @param src    input array
+     *               constraints: align 16
+     * @param len    number of values in the array
+     *               constraints: multiple of 32 greater than 0
+     * @param shift  left shift amount
+     *               constraints: range [0,15]
+     */
+    void (*ac3_lshift_int16)(int16_t *src, unsigned int len, unsigned int shift);
+
+    /**
+     * Right-shift each value in an array of int32_t by a specified amount.
+     * @param src    input array
+     *               constraints: align 16
+     * @param len    number of values in the array
+     *               constraints: multiple of 16 greater than 0
+     * @param shift  right shift amount
+     *               constraints: range [0,31]
+     */
+    void (*ac3_rshift_int32)(int32_t *src, unsigned int len, unsigned int shift);
+
+    /**
+     * Convert an array of float in range [-1.0,1.0] to int32_t with range
+     * [-(1<<24),(1<<24)]
+     *
+     * @param dst destination array of int32_t.
+     *            constraints: 16-byte aligned
+     * @param src source array of float.
+     *            constraints: 16-byte aligned
+     * @param len number of elements to convert.
+     *            constraints: multiple of 32 greater than zero
+     */
+    void (*float_to_fixed24)(int32_t *dst, const float *src, unsigned int len);
+
+    /**
+     * Calculate bit allocation pointers.
+     * The SNR is the difference between the masking curve and the signal.  AC-3
+     * uses this value for each frequency bin to allocate bits.  The snroffset
+     * parameter is a global adjustment to the SNR for all bins.
+     *
+     * @param[in]  mask       masking curve
+     * @param[in]  psd        signal power for each frequency bin
+     * @param[in]  start      starting bin location
+     * @param[in]  end        ending bin location
+     * @param[in]  snr_offset SNR adjustment
+     * @param[in]  floor      noise floor
+     * @param[in]  bap_tab    look-up table for bit allocation pointers
+     * @param[out] bap        bit allocation pointers
+     */
+    void (*bit_alloc_calc_bap)(int16_t *mask, int16_t *psd, int start, int end,
+                               int snr_offset, int floor,
+                               const uint8_t *bap_tab, uint8_t *bap);
+
+    /**
+     * Calculate the number of bits needed to encode a set of mantissas.
+     */
+    int (*compute_mantissa_size)(int mant_cnt[5], uint8_t *bap, int nb_coefs);
+
+    void (*extract_exponents)(uint8_t *exp, int32_t *coef, int nb_coefs);
+} AC3DSPContext;
+
+void ff_ac3dsp_init    (AC3DSPContext *c, int bit_exact);
+void ff_ac3dsp_init_arm(AC3DSPContext *c, int bit_exact);
+void ff_ac3dsp_init_x86(AC3DSPContext *c, int bit_exact);
+
+#endif /* AVCODEC_AC3DSP_H */
diff --git a/libavcodec/ac3enc.c b/libavcodec/ac3enc.c
index e30e1bd..04e8b4f 100644
--- a/libavcodec/ac3enc.c
+++ b/libavcodec/ac3enc.c
@@ -1,21 +1,23 @@
 /*
  * The simplest AC-3 encoder
  * Copyright (c) 2000 Fabrice Bellard
+ * Copyright (c) 2006-2010 Justin Ruggles <justin.ruggles at gmail.com>
+ * Copyright (c) 2006-2010 Prakash Punnoor <prakash at punnoor.de>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -23,512 +25,841 @@
  * @file
  * The simplest AC-3 encoder.
  */
+
 //#define DEBUG
-//#define DEBUG_BITALLOC
+//#define ASSERT_LEVEL 2
+
+#include <stdint.h>
+
+#include "libavutil/audioconvert.h"
+#include "libavutil/avassert.h"
 #include "libavutil/crc.h"
+#include "libavutil/opt.h"
 #include "avcodec.h"
-#include "libavutil/common.h" /* for av_reverse */
 #include "put_bits.h"
+#include "dsputil.h"
+#include "ac3dsp.h"
 #include "ac3.h"
 #include "audioconvert.h"
+#include "fft.h"
+
+
+#ifndef CONFIG_AC3ENC_FLOAT
+#define CONFIG_AC3ENC_FLOAT 0
+#endif
+
+
+/** Maximum number of exponent groups. +1 for separate DC exponent. */
+#define AC3_MAX_EXP_GROUPS 85
+
+/* stereo rematrixing algorithms */
+#define AC3_REMATRIXING_IS_STATIC 0x1
+#define AC3_REMATRIXING_SUMS    0
+#define AC3_REMATRIXING_NONE    1
+#define AC3_REMATRIXING_ALWAYS  3
+
+#if CONFIG_AC3ENC_FLOAT
+#define MAC_COEF(d,a,b) ((d)+=(a)*(b))
+typedef float SampleType;
+typedef float CoefType;
+typedef float CoefSumType;
+#else
+#define MAC_COEF(d,a,b) MAC64(d,a,b)
+typedef int16_t SampleType;
+typedef int32_t CoefType;
+typedef int64_t CoefSumType;
+#endif
+
+typedef struct AC3MDCTContext {
+    const SampleType *window;           ///< MDCT window function
+    FFTContext fft;                     ///< FFT context for MDCT calculation
+} AC3MDCTContext;
+
+/**
+ * Encoding Options used by AVOption.
+ */
+typedef struct AC3EncOptions {
+    /* AC-3 metadata options*/
+    int dialogue_level;
+    int bitstream_mode;
+    float center_mix_level;
+    float surround_mix_level;
+    int dolby_surround_mode;
+    int audio_production_info;
+    int mixing_level;
+    int room_type;
+    int copyright;
+    int original;
+    int extended_bsi_1;
+    int preferred_stereo_downmix;
+    float ltrt_center_mix_level;
+    float ltrt_surround_mix_level;
+    float loro_center_mix_level;
+    float loro_surround_mix_level;
+    int extended_bsi_2;
+    int dolby_surround_ex_mode;
+    int dolby_headphone_mode;
+    int ad_converter_type;
+
+    /* other encoding options */
+    int allow_per_frame_metadata;
+} AC3EncOptions;
+
+/**
+ * Data for a single audio block.
+ */
+typedef struct AC3Block {
+    uint8_t  **bap;                             ///< bit allocation pointers (bap)
+    CoefType **mdct_coef;                       ///< MDCT coefficients
+    int32_t  **fixed_coef;                      ///< fixed-point MDCT coefficients
+    uint8_t  **exp;                             ///< original exponents
+    uint8_t  **grouped_exp;                     ///< grouped exponents
+    int16_t  **psd;                             ///< psd per frequency bin
+    int16_t  **band_psd;                        ///< psd per critical band
+    int16_t  **mask;                            ///< masking curve
+    uint16_t **qmant;                           ///< quantized mantissas
+    uint8_t  coeff_shift[AC3_MAX_CHANNELS];     ///< fixed-point coefficient shift values
+    uint8_t  new_rematrixing_strategy;          ///< send new rematrixing flags in this block
+    uint8_t  rematrixing_flags[4];              ///< rematrixing flags
+    struct AC3Block *exp_ref_block[AC3_MAX_CHANNELS]; ///< reference blocks for EXP_REUSE
+} AC3Block;
 
+/**
+ * AC-3 encoder private context.
+ */
 typedef struct AC3EncodeContext {
-    PutBitContext pb;
-    int nb_channels;
-    int nb_all_channels;
-    int lfe_channel;
-    const uint8_t *channel_map;
-    int bit_rate;
-    unsigned int sample_rate;
-    unsigned int bitstream_id;
-    unsigned int frame_size_min; /* minimum frame size in case rounding is necessary */
-    unsigned int frame_size; /* current frame size in words */
-    unsigned int bits_written;
-    unsigned int samples_written;
-    int sr_shift;
-    unsigned int frame_size_code;
-    unsigned int sr_code; /* frequency */
-    unsigned int channel_mode;
-    int lfe;
-    unsigned int bitstream_mode;
-    short last_samples[AC3_MAX_CHANNELS][256];
-    unsigned int chbwcod[AC3_MAX_CHANNELS];
+    AVClass *av_class;                      ///< AVClass used for AVOption
+    AC3EncOptions options;                  ///< encoding options
+    PutBitContext pb;                       ///< bitstream writer context
+    DSPContext dsp;
+    AC3DSPContext ac3dsp;                   ///< AC-3 optimized functions
+    AC3MDCTContext mdct;                    ///< MDCT context
+
+    AC3Block blocks[AC3_MAX_BLOCKS];        ///< per-block info
+
+    int bitstream_id;                       ///< bitstream id                           (bsid)
+    int bitstream_mode;                     ///< bitstream mode                         (bsmod)
+
+    int bit_rate;                           ///< target bit rate, in bits-per-second
+    int sample_rate;                        ///< sampling frequency, in Hz
+
+    int frame_size_min;                     ///< minimum frame size in case rounding is necessary
+    int frame_size;                         ///< current frame size in bytes
+    int frame_size_code;                    ///< frame size code                        (frmsizecod)
+    uint16_t crc_inv[2];
+    int bits_written;                       ///< bit count    (used to avg. bitrate)
+    int samples_written;                    ///< sample count (used to avg. bitrate)
+
+    int fbw_channels;                       ///< number of full-bandwidth channels      (nfchans)
+    int channels;                           ///< total number of channels               (nchans)
+    int lfe_on;                             ///< indicates if there is an LFE channel   (lfeon)
+    int lfe_channel;                        ///< channel index of the LFE channel
+    int has_center;                         ///< indicates if there is a center channel
+    int has_surround;                       ///< indicates if there are one or more surround channels
+    int channel_mode;                       ///< channel mode                           (acmod)
+    const uint8_t *channel_map;             ///< channel map used to reorder channels
+
+    int center_mix_level;                   ///< center mix level code
+    int surround_mix_level;                 ///< surround mix level code
+    int ltrt_center_mix_level;              ///< Lt/Rt center mix level code
+    int ltrt_surround_mix_level;            ///< Lt/Rt surround mix level code
+    int loro_center_mix_level;              ///< Lo/Ro center mix level code
+    int loro_surround_mix_level;            ///< Lo/Ro surround mix level code
+
+    int cutoff;                             ///< user-specified cutoff frequency, in Hz
+    int bandwidth_code[AC3_MAX_CHANNELS];   ///< bandwidth code (0 to 60)               (chbwcod)
     int nb_coefs[AC3_MAX_CHANNELS];
 
+    int rematrixing;                        ///< determines how rematrixing strategy is calculated
+    int num_rematrixing_bands;              ///< number of rematrixing bands
+
     /* bitrate allocation control */
-    int slow_gain_code, slow_decay_code, fast_decay_code, db_per_bit_code, floor_code;
-    AC3BitAllocParameters bit_alloc;
-    int coarse_snr_offset;
-    int fast_gain_code[AC3_MAX_CHANNELS];
-    int fine_snr_offset[AC3_MAX_CHANNELS];
-    /* mantissa encoding */
-    int mant1_cnt, mant2_cnt, mant4_cnt;
+    int slow_gain_code;                     ///< slow gain code                         (sgaincod)
+    int slow_decay_code;                    ///< slow decay code                        (sdcycod)
+    int fast_decay_code;                    ///< fast decay code                        (fdcycod)
+    int db_per_bit_code;                    ///< dB/bit code                            (dbpbcod)
+    int floor_code;                         ///< floor code                             (floorcod)
+    AC3BitAllocParameters bit_alloc;        ///< bit allocation parameters
+    int coarse_snr_offset;                  ///< coarse SNR offsets                     (csnroffst)
+    int fast_gain_code[AC3_MAX_CHANNELS];   ///< fast gain codes (signal-to-mask ratio) (fgaincod)
+    int fine_snr_offset[AC3_MAX_CHANNELS];  ///< fine SNR offsets                       (fsnroffst)
+    int frame_bits_fixed;                   ///< number of non-coefficient bits for fixed parameters
+    int frame_bits;                         ///< all frame bits except exponents and mantissas
+    int exponent_bits;                      ///< number of bits used for exponents
+
+    SampleType **planar_samples;
+    uint8_t *bap_buffer;
+    uint8_t *bap1_buffer;
+    CoefType *mdct_coef_buffer;
+    int32_t *fixed_coef_buffer;
+    uint8_t *exp_buffer;
+    uint8_t *grouped_exp_buffer;
+    int16_t *psd_buffer;
+    int16_t *band_psd_buffer;
+    int16_t *mask_buffer;
+    uint16_t *qmant_buffer;
+
+    uint8_t exp_strategy[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS]; ///< exponent strategies
+
+    DECLARE_ALIGNED(16, SampleType, windowed_samples)[AC3_WINDOW_SIZE];
 } AC3EncodeContext;
 
-static int16_t costab[64];
-static int16_t sintab[64];
-static int16_t xcos1[128];
-static int16_t xsin1[128];
+typedef struct AC3Mant {
+    uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4
+    int mant1_cnt, mant2_cnt, mant4_cnt;    ///< mantissa counts for bap=1,2,4
+} AC3Mant;
+
+#define CMIXLEV_NUM_OPTIONS 3
+static const float cmixlev_options[CMIXLEV_NUM_OPTIONS] = {
+    LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB
+};
+
+#define SURMIXLEV_NUM_OPTIONS 3
+static const float surmixlev_options[SURMIXLEV_NUM_OPTIONS] = {
+    LEVEL_MINUS_3DB, LEVEL_MINUS_6DB, LEVEL_ZERO
+};
+
+#define EXTMIXLEV_NUM_OPTIONS 8
+static const float extmixlev_options[EXTMIXLEV_NUM_OPTIONS] = {
+    LEVEL_PLUS_3DB,  LEVEL_PLUS_1POINT5DB,  LEVEL_ONE,       LEVEL_MINUS_4POINT5DB,
+    LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB, LEVEL_ZERO
+};
+
+
+#define OFFSET(param) offsetof(AC3EncodeContext, options.param)
+#define AC3ENC_PARAM (AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
+
+static const AVOption options[] = {
+/* Metadata Options */
+{"per_frame_metadata", "Allow Changing Metadata Per-Frame", OFFSET(allow_per_frame_metadata), FF_OPT_TYPE_INT, 0, 0, 1, AC3ENC_PARAM},
+/* downmix levels */
+{"center_mixlev", "Center Mix Level", OFFSET(center_mix_level), FF_OPT_TYPE_FLOAT, LEVEL_MINUS_4POINT5DB, 0.0, 1.0, AC3ENC_PARAM},
+{"surround_mixlev", "Surround Mix Level", OFFSET(surround_mix_level), FF_OPT_TYPE_FLOAT, LEVEL_MINUS_6DB, 0.0, 1.0, AC3ENC_PARAM},
+/* audio production information */
+{"mixing_level", "Mixing Level", OFFSET(mixing_level), FF_OPT_TYPE_INT, -1, -1, 111, AC3ENC_PARAM},
+{"room_type", "Room Type", OFFSET(room_type), FF_OPT_TYPE_INT, -1, -1, 2, AC3ENC_PARAM, "room_type"},
+    {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, 0, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
+    {"large",        "Large Room",              0, FF_OPT_TYPE_CONST, 1, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
+    {"small",        "Small Room",              0, FF_OPT_TYPE_CONST, 2, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
+/* other metadata options */
+{"copyright", "Copyright Bit", OFFSET(copyright), FF_OPT_TYPE_INT, 0, 0, 1, AC3ENC_PARAM},
+{"dialnorm", "Dialogue Level (dB)", OFFSET(dialogue_level), FF_OPT_TYPE_INT, -31, -31, -1, AC3ENC_PARAM},
+{"dsur_mode", "Dolby Surround Mode", OFFSET(dolby_surround_mode), FF_OPT_TYPE_INT, 0, 0, 2, AC3ENC_PARAM, "dsur_mode"},
+    {"notindicated", "Not Indicated (default)",    0, FF_OPT_TYPE_CONST, 0, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
+    {"on",           "Dolby Surround Encoded",     0, FF_OPT_TYPE_CONST, 1, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
+    {"off",          "Not Dolby Surround Encoded", 0, FF_OPT_TYPE_CONST, 2, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
+{"original", "Original Bit Stream", OFFSET(original), FF_OPT_TYPE_INT, 1, 0, 1, AC3ENC_PARAM},
+/* extended bitstream information */
+{"dmix_mode", "Preferred Stereo Downmix Mode", OFFSET(preferred_stereo_downmix), FF_OPT_TYPE_INT, -1, -1, 2, AC3ENC_PARAM, "dmix_mode"},
+    {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, 0, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
+    {"ltrt", "Lt/Rt Downmix Preferred",         0, FF_OPT_TYPE_CONST, 1, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
+    {"loro", "Lo/Ro Downmix Preferred",         0, FF_OPT_TYPE_CONST, 2, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
+{"ltrt_cmixlev", "Lt/Rt Center Mix Level", OFFSET(ltrt_center_mix_level), FF_OPT_TYPE_FLOAT, -1.0, -1.0, 2.0, AC3ENC_PARAM},
+{"ltrt_surmixlev", "Lt/Rt Surround Mix Level", OFFSET(ltrt_surround_mix_level), FF_OPT_TYPE_FLOAT, -1.0, -1.0, 2.0, AC3ENC_PARAM},
+{"loro_cmixlev", "Lo/Ro Center Mix Level", OFFSET(loro_center_mix_level), FF_OPT_TYPE_FLOAT, -1.0, -1.0, 2.0, AC3ENC_PARAM},
+{"loro_surmixlev", "Lo/Ro Surround Mix Level", OFFSET(loro_surround_mix_level), FF_OPT_TYPE_FLOAT, -1.0, -1.0, 2.0, AC3ENC_PARAM},
+{"dsurex_mode", "Dolby Surround EX Mode", OFFSET(dolby_surround_ex_mode), FF_OPT_TYPE_INT, -1, -1, 2, AC3ENC_PARAM, "dsurex_mode"},
+    {"notindicated", "Not Indicated (default)",       0, FF_OPT_TYPE_CONST, 0, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
+    {"on",           "Dolby Surround EX Encoded",     0, FF_OPT_TYPE_CONST, 1, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
+    {"off",          "Not Dolby Surround EX Encoded", 0, FF_OPT_TYPE_CONST, 2, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
+{"dheadphone_mode", "Dolby Headphone Mode", OFFSET(dolby_headphone_mode), FF_OPT_TYPE_INT, -1, -1, 2, AC3ENC_PARAM, "dheadphone_mode"},
+    {"notindicated", "Not Indicated (default)",     0, FF_OPT_TYPE_CONST, 0, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
+    {"on",           "Dolby Headphone Encoded",     0, FF_OPT_TYPE_CONST, 1, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
+    {"off",          "Not Dolby Headphone Encoded", 0, FF_OPT_TYPE_CONST, 2, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
+{"ad_conv_type", "A/D Converter Type", OFFSET(ad_converter_type), FF_OPT_TYPE_INT, -1, -1, 1, AC3ENC_PARAM, "ad_conv_type"},
+    {"standard", "Standard (default)", 0, FF_OPT_TYPE_CONST, 0, INT_MIN, INT_MAX, AC3ENC_PARAM, "ad_conv_type"},
+    {"hdcd",     "HDCD",               0, FF_OPT_TYPE_CONST, 1, INT_MIN, INT_MAX, AC3ENC_PARAM, "ad_conv_type"},
+{NULL}
+};
+
+#if CONFIG_AC3ENC_FLOAT
+static AVClass ac3enc_class = { "AC-3 Encoder", av_default_item_name,
+                                options, LIBAVUTIL_VERSION_INT };
+#else
+static AVClass ac3enc_class = { "Fixed-Point AC-3 Encoder", av_default_item_name,
+                                options, LIBAVUTIL_VERSION_INT };
+#endif
+
+
+/* prototypes for functions in ac3enc_fixed.c and ac3enc_float.c */
+
+static av_cold void mdct_end(AC3MDCTContext *mdct);
+
+static av_cold int mdct_init(AVCodecContext *avctx, AC3MDCTContext *mdct,
+                             int nbits);
+
+static void apply_window(DSPContext *dsp, SampleType *output, const SampleType *input,
+                         const SampleType *window, unsigned int len);
+
+static int normalize_samples(AC3EncodeContext *s);
+
+static void scale_coefficients(AC3EncodeContext *s);
+
+
+/**
+ * LUT for number of exponent groups.
+ * exponent_group_tab[exponent strategy-1][number of coefficients]
+ */
+static uint8_t exponent_group_tab[3][256];
+
+
+/**
+ * List of supported channel layouts.
+ */
+static const int64_t ac3_channel_layouts[] = {
+     AV_CH_LAYOUT_MONO,
+     AV_CH_LAYOUT_STEREO,
+     AV_CH_LAYOUT_2_1,
+     AV_CH_LAYOUT_SURROUND,
+     AV_CH_LAYOUT_2_2,
+     AV_CH_LAYOUT_QUAD,
+     AV_CH_LAYOUT_4POINT0,
+     AV_CH_LAYOUT_5POINT0,
+     AV_CH_LAYOUT_5POINT0_BACK,
+    (AV_CH_LAYOUT_MONO     | AV_CH_LOW_FREQUENCY),
+    (AV_CH_LAYOUT_STEREO   | AV_CH_LOW_FREQUENCY),
+    (AV_CH_LAYOUT_2_1      | AV_CH_LOW_FREQUENCY),
+    (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
+    (AV_CH_LAYOUT_2_2      | AV_CH_LOW_FREQUENCY),
+    (AV_CH_LAYOUT_QUAD     | AV_CH_LOW_FREQUENCY),
+    (AV_CH_LAYOUT_4POINT0  | AV_CH_LOW_FREQUENCY),
+     AV_CH_LAYOUT_5POINT1,
+     AV_CH_LAYOUT_5POINT1_BACK,
+     0
+};
+
+
+/**
+ * LUT to select the bandwidth code based on the bit rate, sample rate, and
+ * number of full-bandwidth channels.
+ * bandwidth_tab[fbw_channels-1][sample rate code][bit rate code]
+ */
+static const uint8_t ac3_bandwidth_tab[5][3][19] = {
+//      32  40  48  56  64  80  96 112 128 160 192 224 256 320 384 448 512 576 640
 
-#define MDCT_NBITS 9
-#define N         (1 << MDCT_NBITS)
+    { {  0,  0,  0, 12, 16, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
+      {  0,  0,  0, 16, 20, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
+      {  0,  0,  0, 32, 40, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
+
+    { {  0,  0,  0,  0,  0,  0,  0, 20, 24, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
+      {  0,  0,  0,  0,  0,  0,  4, 24, 28, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
+      {  0,  0,  0,  0,  0,  0, 20, 44, 52, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
+
+    { {  0,  0,  0,  0,  0,  0,  0,  0,  0, 16, 24, 32, 40, 48, 48, 48, 48, 48, 48 },
+      {  0,  0,  0,  0,  0,  0,  0,  0,  4, 20, 28, 36, 44, 56, 56, 56, 56, 56, 56 },
+      {  0,  0,  0,  0,  0,  0,  0,  0, 20, 40, 48, 60, 60, 60, 60, 60, 60, 60, 60 } },
+
+    { {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 12, 24, 32, 48, 48, 48, 48, 48, 48 },
+      {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 16, 28, 36, 56, 56, 56, 56, 56, 56 },
+      {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 32, 48, 60, 60, 60, 60, 60, 60, 60 } },
+
+    { {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  8, 20, 32, 40, 48, 48, 48, 48 },
+      {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 12, 24, 36, 44, 56, 56, 56, 56 },
+      {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 28, 44, 60, 60, 60, 60, 60, 60 } }
+};
 
-/* new exponents are sent if their Norm 1 exceed this number */
-#define EXP_DIFF_THRESHOLD 1000
 
-static inline int16_t fix15(float a)
+/**
+ * Adjust the frame size to make the average bit rate match the target bit rate.
+ * This is only needed for 11025, 22050, and 44100 sample rates.
+ */
+static void adjust_frame_size(AC3EncodeContext *s)
 {
-    int v;
-    v = (int)(a * (float)(1 << 15));
-    if (v < -32767)
-        v = -32767;
-    else if (v > 32767)
-        v = 32767;
-    return v;
+    while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
+        s->bits_written    -= s->bit_rate;
+        s->samples_written -= s->sample_rate;
+    }
+    s->frame_size = s->frame_size_min +
+                    2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
+    s->bits_written    += s->frame_size * 8;
+    s->samples_written += AC3_FRAME_SIZE;
+}
+
+
+/**
+ * Deinterleave input samples.
+ * Channels are reordered from Libav's default order to AC-3 order.
+ */
+static void deinterleave_input_samples(AC3EncodeContext *s,
+                                       const SampleType *samples)
+{
+    int ch, i;
+
+    /* deinterleave and remap input samples */
+    for (ch = 0; ch < s->channels; ch++) {
+        const SampleType *sptr;
+        int sinc;
+
+        /* copy last 256 samples of previous frame to the start of the current frame */
+        memcpy(&s->planar_samples[ch][0], &s->planar_samples[ch][AC3_FRAME_SIZE],
+               AC3_BLOCK_SIZE * sizeof(s->planar_samples[0][0]));
+
+        /* deinterleave */
+        sinc = s->channels;
+        sptr = samples + s->channel_map[ch];
+        for (i = AC3_BLOCK_SIZE; i < AC3_FRAME_SIZE+AC3_BLOCK_SIZE; i++) {
+            s->planar_samples[ch][i] = *sptr;
+            sptr += sinc;
+        }
+    }
 }
 
-typedef struct IComplex {
-    short re,im;
-} IComplex;
 
-static av_cold void fft_init(int ln)
+/**
+ * Apply the MDCT to input samples to generate frequency coefficients.
+ * This applies the KBD window and normalizes the input to reduce precision
+ * loss due to fixed-point calculations.
+ */
+static void apply_mdct(AC3EncodeContext *s)
 {
-    int i, n;
-    float alpha;
+    int blk, ch;
 
-    n = 1 << ln;
+    for (ch = 0; ch < s->channels; ch++) {
+        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
+            AC3Block *block = &s->blocks[blk];
+            const SampleType *input_samples = &s->planar_samples[ch][blk * AC3_BLOCK_SIZE];
 
-    for(i=0;i<(n/2);i++) {
-        alpha = 2 * M_PI * (float)i / (float)n;
-        costab[i] = fix15(cos(alpha));
-        sintab[i] = fix15(sin(alpha));
+            apply_window(&s->dsp, s->windowed_samples, input_samples, s->mdct.window, AC3_WINDOW_SIZE);
+
+            block->coeff_shift[ch] = normalize_samples(s);
+
+            s->mdct.fft.mdct_calcw(&s->mdct.fft, block->mdct_coef[ch],
+                                   s->windowed_samples);
+        }
     }
 }
 
-/* butter fly op */
-#define BF(pre, pim, qre, qim, pre1, pim1, qre1, qim1) \
-{\
-  int ax, ay, bx, by;\
-  bx=pre1;\
-  by=pim1;\
-  ax=qre1;\
-  ay=qim1;\
-  pre = (bx + ax) >> 1;\
-  pim = (by + ay) >> 1;\
-  qre = (bx - ax) >> 1;\
-  qim = (by - ay) >> 1;\
-}
 
-#define CMUL(pre, pim, are, aim, bre, bim) \
-{\
-   pre = (MUL16(are, bre) - MUL16(aim, bim)) >> 15;\
-   pim = (MUL16(are, bim) + MUL16(bre, aim)) >> 15;\
+/**
+ * Initialize stereo rematrixing.
+ * If the strategy does not change for each frame, set the rematrixing flags.
+ */
+static void rematrixing_init(AC3EncodeContext *s)
+{
+    if (s->channel_mode == AC3_CHMODE_STEREO)
+        s->rematrixing = AC3_REMATRIXING_SUMS;
+    else
+        s->rematrixing = AC3_REMATRIXING_NONE;
+    /* NOTE: AC3_REMATRIXING_ALWAYS might be used in
+             the future in conjunction with channel coupling. */
+
+    if (s->rematrixing & AC3_REMATRIXING_IS_STATIC) {
+        int flag = (s->rematrixing == AC3_REMATRIXING_ALWAYS);
+        s->blocks[0].new_rematrixing_strategy = 1;
+        memset(s->blocks[0].rematrixing_flags, flag,
+               sizeof(s->blocks[0].rematrixing_flags));
+    }
 }
 
 
-/* do a 2^n point complex fft on 2^ln points. */
-static void fft(IComplex *z, int ln)
+/**
+ * Determine rematrixing flags for each block and band.
+ */
+static void compute_rematrixing_strategy(AC3EncodeContext *s)
 {
-    int        j, l, np, np2;
-    int        nblocks, nloops;
-    register IComplex *p,*q;
-    int tmp_re, tmp_im;
-
-    np = 1 << ln;
-
-    /* reverse */
-    for(j=0;j<np;j++) {
-        int k = av_reverse[j] >> (8 - ln);
-        if (k < j)
-            FFSWAP(IComplex, z[k], z[j]);
-    }
-
-    /* pass 0 */
-
-    p=&z[0];
-    j=(np >> 1);
-    do {
-        BF(p[0].re, p[0].im, p[1].re, p[1].im,
-           p[0].re, p[0].im, p[1].re, p[1].im);
-        p+=2;
-    } while (--j != 0);
-
-    /* pass 1 */
-
-    p=&z[0];
-    j=np >> 2;
-    do {
-        BF(p[0].re, p[0].im, p[2].re, p[2].im,
-           p[0].re, p[0].im, p[2].re, p[2].im);
-        BF(p[1].re, p[1].im, p[3].re, p[3].im,
-           p[1].re, p[1].im, p[3].im, -p[3].re);
-        p+=4;
-    } while (--j != 0);
-
-    /* pass 2 .. ln-1 */
-
-    nblocks = np >> 3;
-    nloops = 1 << 2;
-    np2 = np >> 1;
-    do {
-        p = z;
-        q = z + nloops;
-        for (j = 0; j < nblocks; ++j) {
-
-            BF(p->re, p->im, q->re, q->im,
-               p->re, p->im, q->re, q->im);
-
-            p++;
-            q++;
-            for(l = nblocks; l < np2; l += nblocks) {
-                CMUL(tmp_re, tmp_im, costab[l], -sintab[l], q->re, q->im);
-                BF(p->re, p->im, q->re, q->im,
-                   p->re, p->im, tmp_re, tmp_im);
-                p++;
-                q++;
+    int nb_coefs;
+    int blk, bnd, i;
+    AC3Block *block, *block0;
+
+    s->num_rematrixing_bands = 4;
+
+    if (s->rematrixing & AC3_REMATRIXING_IS_STATIC)
+        return;
+
+    nb_coefs = FFMIN(s->nb_coefs[0], s->nb_coefs[1]);
+
+    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
+        block = &s->blocks[blk];
+        block->new_rematrixing_strategy = !blk;
+        for (bnd = 0; bnd < s->num_rematrixing_bands; bnd++) {
+            /* calculate calculate sum of squared coeffs for one band in one block */
+            int start = ff_ac3_rematrix_band_tab[bnd];
+            int end   = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
+            CoefSumType sum[4] = {0,};
+            for (i = start; i < end; i++) {
+                CoefType lt = block->mdct_coef[0][i];
+                CoefType rt = block->mdct_coef[1][i];
+                CoefType md = lt + rt;
+                CoefType sd = lt - rt;
+                MAC_COEF(sum[0], lt, lt);
+                MAC_COEF(sum[1], rt, rt);
+                MAC_COEF(sum[2], md, md);
+                MAC_COEF(sum[3], sd, sd);
+            }
+
+            /* compare sums to determine if rematrixing will be used for this band */
+            if (FFMIN(sum[2], sum[3]) < FFMIN(sum[0], sum[1]))
+                block->rematrixing_flags[bnd] = 1;
+            else
+                block->rematrixing_flags[bnd] = 0;
+
+            /* determine if new rematrixing flags will be sent */
+            if (blk &&
+                block->rematrixing_flags[bnd] != block0->rematrixing_flags[bnd]) {
+                block->new_rematrixing_strategy = 1;
             }
-            p += nloops;
-            q += nloops;
         }
-        nblocks = nblocks >> 1;
-        nloops = nloops << 1;
-    } while (nblocks != 0);
+        block0 = block;
+    }
 }
 
-/* do a 512 point mdct */
-static void mdct512(int32_t *out, int16_t *in)
+
+/**
+ * Apply stereo rematrixing to coefficients based on rematrixing flags.
+ */
+static void apply_rematrixing(AC3EncodeContext *s)
 {
-    int i, re, im, re1, im1;
-    int16_t rot[N];
-    IComplex x[N/4];
+    int nb_coefs;
+    int blk, bnd, i;
+    int start, end;
+    uint8_t *flags;
 
-    /* shift to simplify computations */
-    for(i=0;i<N/4;i++)
-        rot[i] = -in[i + 3*N/4];
-    for(i=N/4;i<N;i++)
-        rot[i] = in[i - N/4];
+    if (s->rematrixing == AC3_REMATRIXING_NONE)
+        return;
 
-    /* pre rotation */
-    for(i=0;i<N/4;i++) {
-        re = ((int)rot[2*i] - (int)rot[N-1-2*i]) >> 1;
-        im = -((int)rot[N/2+2*i] - (int)rot[N/2-1-2*i]) >> 1;
-        CMUL(x[i].re, x[i].im, re, im, -xcos1[i], xsin1[i]);
+    nb_coefs = FFMIN(s->nb_coefs[0], s->nb_coefs[1]);
+
+    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
+        AC3Block *block = &s->blocks[blk];
+        if (block->new_rematrixing_strategy)
+            flags = block->rematrixing_flags;
+        for (bnd = 0; bnd < s->num_rematrixing_bands; bnd++) {
+            if (flags[bnd]) {
+                start = ff_ac3_rematrix_band_tab[bnd];
+                end   = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
+                for (i = start; i < end; i++) {
+                    int32_t lt = block->fixed_coef[0][i];
+                    int32_t rt = block->fixed_coef[1][i];
+                    block->fixed_coef[0][i] = (lt + rt) >> 1;
+                    block->fixed_coef[1][i] = (lt - rt) >> 1;
+                }
+            }
+        }
     }
+}
 
-    fft(x, MDCT_NBITS - 2);
 
-    /* post rotation */
-    for(i=0;i<N/4;i++) {
-        re = x[i].re;
-        im = x[i].im;
-        CMUL(re1, im1, re, im, xsin1[i], xcos1[i]);
-        out[2*i] = im1;
-        out[N/2-1-2*i] = re1;
+/**
+ * Initialize exponent tables.
+ */
+static av_cold void exponent_init(AC3EncodeContext *s)
+{
+    int i;
+    for (i = 73; i < 256; i++) {
+        exponent_group_tab[0][i] = (i - 1) /  3;
+        exponent_group_tab[1][i] = (i + 2) /  6;
+        exponent_group_tab[2][i] = (i + 8) / 12;
     }
+    /* LFE */
+    exponent_group_tab[0][7] = 2;
 }
 
-/* XXX: use another norm ? */
-static int calc_exp_diff(uint8_t *exp1, uint8_t *exp2, int n)
+
+/**
+ * Extract exponents from the MDCT coefficients.
+ * This takes into account the normalization that was done to the input samples
+ * by adjusting the exponents by the exponent shift values.
+ */
+static void extract_exponents(AC3EncodeContext *s)
 {
-    int sum, i;
-    sum = 0;
-    for(i=0;i<n;i++) {
-        sum += abs(exp1[i] - exp2[i]);
+    int blk, ch;
+
+    for (ch = 0; ch < s->channels; ch++) {
+        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
+            AC3Block *block = &s->blocks[blk];
+            s->ac3dsp.extract_exponents(block->exp[ch], block->fixed_coef[ch],
+                                        AC3_MAX_COEFS);
+        }
     }
-    return sum;
 }
 
-static void compute_exp_strategy(uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
-                                 uint8_t exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
-                                 int ch, int is_lfe)
+
+/**
+ * Exponent Difference Threshold.
+ * New exponents are sent if their SAD exceed this number.
+ */
+#define EXP_DIFF_THRESHOLD 500
+
+
+/**
+ * Calculate exponent strategies for all blocks in a single channel.
+ */
+static void compute_exp_strategy_ch(AC3EncodeContext *s, uint8_t *exp_strategy,
+                                    uint8_t *exp)
 {
-    int i, j;
+    int blk, blk1;
     int exp_diff;
 
     /* estimate if the exponent variation & decide if they should be
        reused in the next frame */
-    exp_strategy[0][ch] = EXP_NEW;
-    for(i=1;i<NB_BLOCKS;i++) {
-        exp_diff = calc_exp_diff(exp[i][ch], exp[i-1][ch], N/2);
-        dprintf(NULL, "exp_diff=%d\n", exp_diff);
+    exp_strategy[0] = EXP_NEW;
+    exp += AC3_MAX_COEFS;
+    for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
+        exp_diff = s->dsp.sad[0](NULL, exp, exp - AC3_MAX_COEFS, 16, 16);
         if (exp_diff > EXP_DIFF_THRESHOLD)
-            exp_strategy[i][ch] = EXP_NEW;
+            exp_strategy[blk] = EXP_NEW;
         else
-            exp_strategy[i][ch] = EXP_REUSE;
+            exp_strategy[blk] = EXP_REUSE;
+        exp += AC3_MAX_COEFS;
     }
-    if (is_lfe)
-        return;
 
     /* now select the encoding strategy type : if exponents are often
        recoded, we use a coarse encoding */
-    i = 0;
-    while (i < NB_BLOCKS) {
-        j = i + 1;
-        while (j < NB_BLOCKS && exp_strategy[j][ch] == EXP_REUSE)
-            j++;
-        switch(j - i) {
-        case 1:
-            exp_strategy[i][ch] = EXP_D45;
-            break;
+    blk = 0;
+    while (blk < AC3_MAX_BLOCKS) {
+        blk1 = blk + 1;
+        while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
+            blk1++;
+        switch (blk1 - blk) {
+        case 1:  exp_strategy[blk] = EXP_D45; break;
         case 2:
-        case 3:
-            exp_strategy[i][ch] = EXP_D25;
-            break;
-        default:
-            exp_strategy[i][ch] = EXP_D15;
-            break;
+        case 3:  exp_strategy[blk] = EXP_D25; break;
+        default: exp_strategy[blk] = EXP_D15; break;
         }
-        i = j;
+        blk = blk1;
     }
 }
 
-/* set exp[i] to min(exp[i], exp1[i]) */
-static void exponent_min(uint8_t exp[N/2], uint8_t exp1[N/2], int n)
+
+/**
+ * Calculate exponent strategies for all channels.
+ * Array arrangement is reversed to simplify the per-channel calculation.
+ */
+static void compute_exp_strategy(AC3EncodeContext *s)
 {
-    int i;
+    int ch, blk;
 
-    for(i=0;i<n;i++) {
-        if (exp1[i] < exp[i])
-            exp[i] = exp1[i];
+    for (ch = 0; ch < s->fbw_channels; ch++) {
+        compute_exp_strategy_ch(s, s->exp_strategy[ch], s->blocks[0].exp[ch]);
+    }
+    if (s->lfe_on) {
+        ch = s->lfe_channel;
+        s->exp_strategy[ch][0] = EXP_D15;
+        for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
+            s->exp_strategy[ch][blk] = EXP_REUSE;
     }
 }
 
-/* update the exponents so that they are the ones the decoder will
-   decode. Return the number of bits used to code the exponents */
-static int encode_exp(uint8_t encoded_exp[N/2],
-                      uint8_t exp[N/2],
-                      int nb_exps,
-                      int exp_strategy)
+
+/**
+ * Update the exponents so that they are the ones the decoder will decode.
+ */
+static void encode_exponents_blk_ch(uint8_t *exp, int nb_exps, int exp_strategy)
 {
-    int group_size, nb_groups, i, j, k, exp_min;
-    uint8_t exp1[N/2];
+    int nb_groups, i, k;
 
+    nb_groups = exponent_group_tab[exp_strategy-1][nb_exps] * 3;
+
+    /* for each group, compute the minimum exponent */
     switch(exp_strategy) {
-    case EXP_D15:
-        group_size = 1;
-        break;
     case EXP_D25:
-        group_size = 2;
+        for (i = 1, k = 1; i <= nb_groups; i++) {
+            uint8_t exp_min = exp[k];
+            if (exp[k+1] < exp_min)
+                exp_min = exp[k+1];
+            exp[i] = exp_min;
+            k += 2;
+        }
         break;
-    default:
     case EXP_D45:
-        group_size = 4;
-        break;
-    }
-    nb_groups = ((nb_exps + (group_size * 3) - 4) / (3 * group_size)) * 3;
-
-    /* for each group, compute the minimum exponent */
-    exp1[0] = exp[0]; /* DC exponent is handled separately */
-    k = 1;
-    for(i=1;i<=nb_groups;i++) {
-        exp_min = exp[k];
-        assert(exp_min >= 0 && exp_min <= 24);
-        for(j=1;j<group_size;j++) {
-            if (exp[k+j] < exp_min)
-                exp_min = exp[k+j];
+        for (i = 1, k = 1; i <= nb_groups; i++) {
+            uint8_t exp_min = exp[k];
+            if (exp[k+1] < exp_min)
+                exp_min = exp[k+1];
+            if (exp[k+2] < exp_min)
+                exp_min = exp[k+2];
+            if (exp[k+3] < exp_min)
+                exp_min = exp[k+3];
+            exp[i] = exp_min;
+            k += 4;
         }
-        exp1[i] = exp_min;
-        k += group_size;
+        break;
     }
 
     /* constraint for DC exponent */
-    if (exp1[0] > 15)
-        exp1[0] = 15;
+    if (exp[0] > 15)
+        exp[0] = 15;
 
-    /* Decrease the delta between each groups to within 2
-     * so that they can be differentially encoded */
-    for (i=1;i<=nb_groups;i++)
-        exp1[i] = FFMIN(exp1[i], exp1[i-1] + 2);
-    for (i=nb_groups-1;i>=0;i--)
-        exp1[i] = FFMIN(exp1[i], exp1[i+1] + 2);
+    /* decrease the delta between each groups to within 2 so that they can be
+       differentially encoded */
+    for (i = 1; i <= nb_groups; i++)
+        exp[i] = FFMIN(exp[i], exp[i-1] + 2);
+    i--;
+    while (--i >= 0)
+        exp[i] = FFMIN(exp[i], exp[i+1] + 2);
 
     /* now we have the exponent values the decoder will see */
-    encoded_exp[0] = exp1[0];
-    k = 1;
-    for(i=1;i<=nb_groups;i++) {
-        for(j=0;j<group_size;j++) {
-            encoded_exp[k+j] = exp1[i];
+    switch (exp_strategy) {
+    case EXP_D25:
+        for (i = nb_groups, k = nb_groups * 2; i > 0; i--) {
+            uint8_t exp1 = exp[i];
+            exp[k--] = exp1;
+            exp[k--] = exp1;
         }
-        k += group_size;
-    }
-
-#if defined(DEBUG)
-    av_log(NULL, AV_LOG_DEBUG, "exponents: strategy=%d\n", exp_strategy);
-    for(i=0;i<=nb_groups * group_size;i++) {
-        av_log(NULL, AV_LOG_DEBUG, "%d ", encoded_exp[i]);
+        break;
+    case EXP_D45:
+        for (i = nb_groups, k = nb_groups * 4; i > 0; i--) {
+            exp[k] = exp[k-1] = exp[k-2] = exp[k-3] = exp[i];
+            k -= 4;
+        }
+        break;
     }
-    av_log(NULL, AV_LOG_DEBUG, "\n");
-#endif
-
-    return 4 + (nb_groups / 3) * 7;
 }
 
-/* return the size in bits taken by the mantissa */
-static int compute_mantissa_size(AC3EncodeContext *s, uint8_t *m, int nb_coefs)
+
+/**
+ * Encode exponents from original extracted form to what the decoder will see.
+ * This copies and groups exponents based on exponent strategy and reduces
+ * deltas between adjacent exponent groups so that they can be differentially
+ * encoded.
+ */
+static void encode_exponents(AC3EncodeContext *s)
 {
-    int bits, mant, i;
+    int blk, blk1, ch;
+    uint8_t *exp, *exp_strategy;
+    int nb_coefs, num_reuse_blocks;
+
+    for (ch = 0; ch < s->channels; ch++) {
+        exp          = s->blocks[0].exp[ch];
+        exp_strategy = s->exp_strategy[ch];
+        nb_coefs     = s->nb_coefs[ch];
+
+        blk = 0;
+        while (blk < AC3_MAX_BLOCKS) {
+            blk1 = blk + 1;
+
+            /* count the number of EXP_REUSE blocks after the current block
+               and set exponent reference block pointers */
+            s->blocks[blk].exp_ref_block[ch] = &s->blocks[blk];
+            while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE) {
+                s->blocks[blk1].exp_ref_block[ch] = &s->blocks[blk];
+                blk1++;
+            }
+            num_reuse_blocks = blk1 - blk - 1;
 
-    bits = 0;
-    for(i=0;i<nb_coefs;i++) {
-        mant = m[i];
-        switch(mant) {
-        case 0:
-            /* nothing */
-            break;
-        case 1:
-            /* 3 mantissa in 5 bits */
-            if (s->mant1_cnt == 0)
-                bits += 5;
-            if (++s->mant1_cnt == 3)
-                s->mant1_cnt = 0;
-            break;
-        case 2:
-            /* 3 mantissa in 7 bits */
-            if (s->mant2_cnt == 0)
-                bits += 7;
-            if (++s->mant2_cnt == 3)
-                s->mant2_cnt = 0;
-            break;
-        case 3:
-            bits += 3;
-            break;
-        case 4:
-            /* 2 mantissa in 7 bits */
-            if (s->mant4_cnt == 0)
-                bits += 7;
-            if (++s->mant4_cnt == 2)
-                s->mant4_cnt = 0;
-            break;
-        case 14:
-            bits += 14;
-            break;
-        case 15:
-            bits += 16;
-            break;
-        default:
-            bits += mant - 1;
-            break;
+            /* for the EXP_REUSE case we select the min of the exponents */
+            s->ac3dsp.ac3_exponent_min(exp, num_reuse_blocks, nb_coefs);
+
+            encode_exponents_blk_ch(exp, nb_coefs, exp_strategy[blk]);
+
+            exp += AC3_MAX_COEFS * (num_reuse_blocks + 1);
+            blk = blk1;
         }
     }
-    return bits;
 }
 
 
-static void bit_alloc_masking(AC3EncodeContext *s,
-                              uint8_t encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
-                              uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
-                              int16_t psd[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
-                              int16_t mask[NB_BLOCKS][AC3_MAX_CHANNELS][50])
+/**
+ * Group exponents.
+ * 3 delta-encoded exponents are in each 7-bit group. The number of groups
+ * varies depending on exponent strategy and bandwidth.
+ */
+static void group_exponents(AC3EncodeContext *s)
 {
-    int blk, ch;
-    int16_t band_psd[NB_BLOCKS][AC3_MAX_CHANNELS][50];
-
-    for(blk=0; blk<NB_BLOCKS; blk++) {
-        for(ch=0;ch<s->nb_all_channels;ch++) {
-            if(exp_strategy[blk][ch] == EXP_REUSE) {
-                memcpy(psd[blk][ch], psd[blk-1][ch], (N/2)*sizeof(int16_t));
-                memcpy(mask[blk][ch], mask[blk-1][ch], 50*sizeof(int16_t));
-            } else {
-                ff_ac3_bit_alloc_calc_psd(encoded_exp[blk][ch], 0,
-                                          s->nb_coefs[ch],
-                                          psd[blk][ch], band_psd[blk][ch]);
-                ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, band_psd[blk][ch],
-                                           0, s->nb_coefs[ch],
-                                           ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
-                                           ch == s->lfe_channel,
-                                           DBA_NONE, 0, NULL, NULL, NULL,
-                                           mask[blk][ch]);
+    int blk, ch, i;
+    int group_size, nb_groups, bit_count;
+    uint8_t *p;
+    int delta0, delta1, delta2;
+    int exp0, exp1;
+
+    bit_count = 0;
+    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
+        AC3Block *block = &s->blocks[blk];
+        for (ch = 0; ch < s->channels; ch++) {
+            int exp_strategy = s->exp_strategy[ch][blk];
+            if (exp_strategy == EXP_REUSE)
+                continue;
+            group_size = exp_strategy + (exp_strategy == EXP_D45);
+            nb_groups = exponent_group_tab[exp_strategy-1][s->nb_coefs[ch]];
+            bit_count += 4 + (nb_groups * 7);
+            p = block->exp[ch];
+
+            /* DC exponent */
+            exp1 = *p++;
+            block->grouped_exp[ch][0] = exp1;
+
+            /* remaining exponents are delta encoded */
+            for (i = 1; i <= nb_groups; i++) {
+                /* merge three delta in one code */
+                exp0   = exp1;
+                exp1   = p[0];
+                p     += group_size;
+                delta0 = exp1 - exp0 + 2;
+                av_assert2(delta0 >= 0 && delta0 <= 4);
+
+                exp0   = exp1;
+                exp1   = p[0];
+                p     += group_size;
+                delta1 = exp1 - exp0 + 2;
+                av_assert2(delta1 >= 0 && delta1 <= 4);
+
+                exp0   = exp1;
+                exp1   = p[0];
+                p     += group_size;
+                delta2 = exp1 - exp0 + 2;
+                av_assert2(delta2 >= 0 && delta2 <= 4);
+
+                block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
             }
         }
     }
+
+    s->exponent_bits = bit_count;
 }
 
-static int bit_alloc(AC3EncodeContext *s,
-                     int16_t mask[NB_BLOCKS][AC3_MAX_CHANNELS][50],
-                     int16_t psd[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
-                     uint8_t bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
-                     int frame_bits, int coarse_snr_offset, int fine_snr_offset)
+
+/**
+ * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
+ * Extract exponents from MDCT coefficients, calculate exponent strategies,
+ * and encode final exponents.
+ */
+static void process_exponents(AC3EncodeContext *s)
 {
-    int i, ch;
-    int snr_offset;
-
-    snr_offset = (((coarse_snr_offset - 15) << 4) + fine_snr_offset) << 2;
-
-    /* compute size */
-    for(i=0;i<NB_BLOCKS;i++) {
-        s->mant1_cnt = 0;
-        s->mant2_cnt = 0;
-        s->mant4_cnt = 0;
-        for(ch=0;ch<s->nb_all_channels;ch++) {
-            ff_ac3_bit_alloc_calc_bap(mask[i][ch], psd[i][ch], 0,
-                                      s->nb_coefs[ch], snr_offset,
-                                      s->bit_alloc.floor, ff_ac3_bap_tab,
-                                      bap[i][ch]);
-            frame_bits += compute_mantissa_size(s, bap[i][ch],
-                                                 s->nb_coefs[ch]);
-        }
-    }
-#if 0
-    printf("csnr=%d fsnr=%d frame_bits=%d diff=%d\n",
-           coarse_snr_offset, fine_snr_offset, frame_bits,
-           16 * s->frame_size - ((frame_bits + 7) & ~7));
-#endif
-    return 16 * s->frame_size - frame_bits;
+    extract_exponents(s);
+
+    compute_exp_strategy(s);
+
+    encode_exponents(s);
+
+    group_exponents(s);
+
+    emms_c();
 }
 
-#define SNR_INC1 4
 
-static int compute_bit_allocation(AC3EncodeContext *s,
-                                  uint8_t bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
-                                  uint8_t encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
-                                  uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
-                                  int frame_bits)
+/**
+ * Count frame bits that are based solely on fixed parameters.
+ * This only has to be run once when the encoder is initialized.
+ */
+static void count_frame_bits_fixed(AC3EncodeContext *s)
 {
-    int i, ch;
-    int coarse_snr_offset, fine_snr_offset;
-    uint8_t bap1[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
-    int16_t psd[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
-    int16_t mask[NB_BLOCKS][AC3_MAX_CHANNELS][50];
     static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
+    int blk;
+    int frame_bits;
 
-    /* init default parameters */
-    s->slow_decay_code = 2;
-    s->fast_decay_code = 1;
-    s->slow_gain_code = 1;
-    s->db_per_bit_code = 2;
-    s->floor_code = 4;
-    for(ch=0;ch<s->nb_all_channels;ch++)
-        s->fast_gain_code[ch] = 4;
-
-    /* compute real values */
-    s->bit_alloc.sr_code = s->sr_code;
-    s->bit_alloc.sr_shift = s->sr_shift;
-    s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->sr_shift;
-    s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->sr_shift;
-    s->bit_alloc.slow_gain = ff_ac3_slow_gain_tab[s->slow_gain_code];
-    s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
-    s->bit_alloc.floor = ff_ac3_floor_tab[s->floor_code];
+    /* assumptions:
+     *   no dynamic range codes
+     *   no channel coupling
+     *   bit allocation parameters do not change between blocks
+     *   SNR offsets do not change between blocks
+     *   no delta bit allocation
+     *   no skipped data
+     *   no auxilliary data
+     */
 
     /* header size */
-    frame_bits += 65;
-    // if (s->channel_mode == 2)
-    //    frame_bits += 2;
+    frame_bits = 65;
     frame_bits += frame_bits_inc[s->channel_mode];
 
     /* audio blocks */
-    for(i=0;i<NB_BLOCKS;i++) {
-        frame_bits += s->nb_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
+    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
+        frame_bits += s->fbw_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
         if (s->channel_mode == AC3_CHMODE_STEREO) {
             frame_bits++; /* rematstr */
-            if(i==0) frame_bits += 4;
         }
-        frame_bits += 2 * s->nb_channels; /* chexpstr[2] * c */
-        if (s->lfe)
+        frame_bits += 2 * s->fbw_channels; /* chexpstr[2] * c */
+        if (s->lfe_on)
             frame_bits++; /* lfeexpstr */
-        for(ch=0;ch<s->nb_channels;ch++) {
-            if (exp_strategy[i][ch] != EXP_REUSE)
-                frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
-        }
         frame_bits++; /* baie */
         frame_bits++; /* snr */
         frame_bits += 2; /* delta / skip */
@@ -538,7 +869,7 @@ static int compute_bit_allocation(AC3EncodeContext *s,
     /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
     /* csnroffset[6] */
     /* (fsnoffset[4] + fgaincod[4]) * c */
-    frame_bits += 2*4 + 3 + 6 + s->nb_all_channels * (4 + 3);
+    frame_bits += 2*4 + 3 + 6 + s->channels * (4 + 3);
 
     /* auxdatae, crcrsv */
     frame_bits += 2;
@@ -546,249 +877,353 @@ static int compute_bit_allocation(AC3EncodeContext *s,
     /* CRC */
     frame_bits += 16;
 
-    /* calculate psd and masking curve before doing bit allocation */
-    bit_alloc_masking(s, encoded_exp, exp_strategy, psd, mask);
+    s->frame_bits_fixed = frame_bits;
+}
 
-    /* now the big work begins : do the bit allocation. Modify the snr
-       offset until we can pack everything in the requested frame size */
 
-    coarse_snr_offset = s->coarse_snr_offset;
-    while (coarse_snr_offset >= 0 &&
-           bit_alloc(s, mask, psd, bap, frame_bits, coarse_snr_offset, 0) < 0)
-        coarse_snr_offset -= SNR_INC1;
-    if (coarse_snr_offset < 0) {
-        av_log(NULL, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
-        return -1;
+/**
+ * Initialize bit allocation.
+ * Set default parameter codes and calculate parameter values.
+ */
+static void bit_alloc_init(AC3EncodeContext *s)
+{
+    int ch;
+
+    /* init default parameters */
+    s->slow_decay_code = 2;
+    s->fast_decay_code = 1;
+    s->slow_gain_code  = 1;
+    s->db_per_bit_code = 3;
+    s->floor_code      = 7;
+    for (ch = 0; ch < s->channels; ch++)
+        s->fast_gain_code[ch] = 4;
+
+    /* initial snr offset */
+    s->coarse_snr_offset = 40;
+
+    /* compute real values */
+    /* currently none of these values change during encoding, so we can just
+       set them once at initialization */
+    s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
+    s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
+    s->bit_alloc.slow_gain  = ff_ac3_slow_gain_tab[s->slow_gain_code];
+    s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
+    s->bit_alloc.floor      = ff_ac3_floor_tab[s->floor_code];
+
+    count_frame_bits_fixed(s);
+}
+
+
+/**
+ * Count the bits used to encode the frame, minus exponents and mantissas.
+ * Bits based on fixed parameters have already been counted, so now we just
+ * have to add the bits based on parameters that change during encoding.
+ */
+static void count_frame_bits(AC3EncodeContext *s)
+{
+    AC3EncOptions *opt = &s->options;
+    int blk, ch;
+    int frame_bits = 0;
+
+    if (opt->audio_production_info)
+        frame_bits += 7;
+    if (s->bitstream_id == 6) {
+        if (opt->extended_bsi_1)
+            frame_bits += 14;
+        if (opt->extended_bsi_2)
+            frame_bits += 14;
     }
-    while ((coarse_snr_offset + SNR_INC1) <= 63 &&
-           bit_alloc(s, mask, psd, bap1, frame_bits,
-                     coarse_snr_offset + SNR_INC1, 0) >= 0) {
-        coarse_snr_offset += SNR_INC1;
-        memcpy(bap, bap1, sizeof(bap1));
-    }
-    while ((coarse_snr_offset + 1) <= 63 &&
-           bit_alloc(s, mask, psd, bap1, frame_bits, coarse_snr_offset + 1, 0) >= 0) {
-        coarse_snr_offset++;
-        memcpy(bap, bap1, sizeof(bap1));
-    }
-
-    fine_snr_offset = 0;
-    while ((fine_snr_offset + SNR_INC1) <= 15 &&
-           bit_alloc(s, mask, psd, bap1, frame_bits,
-                     coarse_snr_offset, fine_snr_offset + SNR_INC1) >= 0) {
-        fine_snr_offset += SNR_INC1;
-        memcpy(bap, bap1, sizeof(bap1));
-    }
-    while ((fine_snr_offset + 1) <= 15 &&
-           bit_alloc(s, mask, psd, bap1, frame_bits,
-                     coarse_snr_offset, fine_snr_offset + 1) >= 0) {
-        fine_snr_offset++;
-        memcpy(bap, bap1, sizeof(bap1));
-    }
-
-    s->coarse_snr_offset = coarse_snr_offset;
-    for(ch=0;ch<s->nb_all_channels;ch++)
-        s->fine_snr_offset[ch] = fine_snr_offset;
-#if defined(DEBUG_BITALLOC)
-    {
-        int j;
-
-        for(i=0;i<6;i++) {
-            for(ch=0;ch<s->nb_all_channels;ch++) {
-                printf("Block #%d Ch%d:\n", i, ch);
-                printf("bap=");
-                for(j=0;j<s->nb_coefs[ch];j++) {
-                    printf("%d ",bap[i][ch][j]);
-                }
-                printf("\n");
-            }
+
+    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
+        /* stereo rematrixing */
+        if (s->channel_mode == AC3_CHMODE_STEREO &&
+            s->blocks[blk].new_rematrixing_strategy) {
+            frame_bits += s->num_rematrixing_bands;
+        }
+
+        for (ch = 0; ch < s->fbw_channels; ch++) {
+            if (s->exp_strategy[ch][blk] != EXP_REUSE)
+                frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
         }
     }
-#endif
-    return 0;
+    s->frame_bits = s->frame_bits_fixed + frame_bits;
 }
 
-static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
-                                    int64_t *channel_layout)
+
+/**
+ * Finalize the mantissa bit count by adding in the grouped mantissas.
+ */
+static int compute_mantissa_size_final(int mant_cnt[5])
 {
-    int ch_layout;
+    // bap=1 : 3 mantissas in 5 bits
+    int bits = (mant_cnt[1] / 3) * 5;
+    // bap=2 : 3 mantissas in 7 bits
+    // bap=4 : 2 mantissas in 7 bits
+    bits += ((mant_cnt[2] / 3) + (mant_cnt[4] >> 1)) * 7;
+    // bap=3 : each mantissa is 3 bits
+    bits += mant_cnt[3] * 3;
+    return bits;
+}
 
-    if (channels < 1 || channels > AC3_MAX_CHANNELS)
-        return -1;
-    if ((uint64_t)*channel_layout > 0x7FF)
-        return -1;
-    ch_layout = *channel_layout;
-    if (!ch_layout)
-        ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
-    if (avcodec_channel_layout_num_channels(ch_layout) != channels)
-        return -1;
 
-    s->lfe = !!(ch_layout & CH_LOW_FREQUENCY);
-    s->nb_all_channels = channels;
-    s->nb_channels = channels - s->lfe;
-    s->lfe_channel = s->lfe ? s->nb_channels : -1;
-    if (s->lfe)
-        ch_layout -= CH_LOW_FREQUENCY;
+/**
+ * Calculate masking curve based on the final exponents.
+ * Also calculate the power spectral densities to use in future calculations.
+ */
+static void bit_alloc_masking(AC3EncodeContext *s)
+{
+    int blk, ch;
+
+    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
+        AC3Block *block = &s->blocks[blk];
+        for (ch = 0; ch < s->channels; ch++) {
+            /* We only need psd and mask for calculating bap.
+               Since we currently do not calculate bap when exponent
+               strategy is EXP_REUSE we do not need to calculate psd or mask. */
+            if (s->exp_strategy[ch][blk] != EXP_REUSE) {
+                ff_ac3_bit_alloc_calc_psd(block->exp[ch], 0,
+                                          s->nb_coefs[ch],
+                                          block->psd[ch], block->band_psd[ch]);
+                ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
+                                           0, s->nb_coefs[ch],
+                                           ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
+                                           ch == s->lfe_channel,
+                                           DBA_NONE, 0, NULL, NULL, NULL,
+                                           block->mask[ch]);
+            }
+        }
+    }
+}
 
-    switch (ch_layout) {
-    case CH_LAYOUT_MONO:           s->channel_mode = AC3_CHMODE_MONO;   break;
-    case CH_LAYOUT_STEREO:         s->channel_mode = AC3_CHMODE_STEREO; break;
-    case CH_LAYOUT_SURROUND:       s->channel_mode = AC3_CHMODE_3F;     break;
-    case CH_LAYOUT_2_1:            s->channel_mode = AC3_CHMODE_2F1R;   break;
-    case CH_LAYOUT_4POINT0:        s->channel_mode = AC3_CHMODE_3F1R;   break;
-    case CH_LAYOUT_QUAD:
-    case CH_LAYOUT_2_2:            s->channel_mode = AC3_CHMODE_2F2R;   break;
-    case CH_LAYOUT_5POINT0:
-    case CH_LAYOUT_5POINT0_BACK:   s->channel_mode = AC3_CHMODE_3F2R;   break;
-    default:
-        return -1;
+
+/**
+ * Ensure that bap for each block and channel point to the current bap_buffer.
+ * They may have been switched during the bit allocation search.
+ */
+static void reset_block_bap(AC3EncodeContext *s)
+{
+    int blk, ch;
+    if (s->blocks[0].bap[0] == s->bap_buffer)
+        return;
+    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
+        for (ch = 0; ch < s->channels; ch++) {
+            s->blocks[blk].bap[ch] = &s->bap_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
+        }
     }
+}
 
-    s->channel_map = ff_ac3_enc_channel_map[s->channel_mode][s->lfe];
-    *channel_layout = ch_layout;
-    if (s->lfe)
-        *channel_layout |= CH_LOW_FREQUENCY;
 
-    return 0;
+/**
+ * Run the bit allocation with a given SNR offset.
+ * This calculates the bit allocation pointers that will be used to determine
+ * the quantization of each mantissa.
+ * @return the number of bits needed for mantissas if the given SNR offset is
+ *         is used.
+ */
+static int bit_alloc(AC3EncodeContext *s, int snr_offset)
+{
+    int blk, ch;
+    int mantissa_bits;
+    int mant_cnt[5];
+
+    snr_offset = (snr_offset - 240) << 2;
+
+    reset_block_bap(s);
+    mantissa_bits = 0;
+    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
+        AC3Block *block;
+        // initialize grouped mantissa counts. these are set so that they are
+        // padded to the next whole group size when bits are counted in
+        // compute_mantissa_size_final
+        mant_cnt[0] = mant_cnt[3] = 0;
+        mant_cnt[1] = mant_cnt[2] = 2;
+        mant_cnt[4] = 1;
+        for (ch = 0; ch < s->channels; ch++) {
+            /* Currently the only bit allocation parameters which vary across
+               blocks within a frame are the exponent values.  We can take
+               advantage of that by reusing the bit allocation pointers
+               whenever we reuse exponents. */
+            block = s->blocks[blk].exp_ref_block[ch];
+            if (s->exp_strategy[ch][blk] != EXP_REUSE) {
+                s->ac3dsp.bit_alloc_calc_bap(block->mask[ch], block->psd[ch], 0,
+                                          s->nb_coefs[ch], snr_offset,
+                                          s->bit_alloc.floor, ff_ac3_bap_tab,
+                                          block->bap[ch]);
+            }
+            mantissa_bits += s->ac3dsp.compute_mantissa_size(mant_cnt, block->bap[ch], s->nb_coefs[ch]);
+        }
+        mantissa_bits += compute_mantissa_size_final(mant_cnt);
+    }
+    return mantissa_bits;
 }
 
-static av_cold int AC3_encode_init(AVCodecContext *avctx)
+
+/**
+ * Constant bitrate bit allocation search.
+ * Find the largest SNR offset that will allow data to fit in the frame.
+ */
+static int cbr_bit_allocation(AC3EncodeContext *s)
 {
-    int freq = avctx->sample_rate;
-    int bitrate = avctx->bit_rate;
-    AC3EncodeContext *s = avctx->priv_data;
-    int i, j, ch;
-    float alpha;
-    int bw_code;
+    int ch;
+    int bits_left;
+    int snr_offset, snr_incr;
 
-    avctx->frame_size = AC3_FRAME_SIZE;
+    bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
+    av_assert2(bits_left >= 0);
 
-    ac3_common_init();
+    snr_offset = s->coarse_snr_offset << 4;
 
-    if (!avctx->channel_layout) {
-        av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
-                                      "encoder will guess the layout, but it "
-                                      "might be incorrect.\n");
-    }
-    if (set_channel_info(s, avctx->channels, &avctx->channel_layout)) {
-        av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
-        return -1;
+    /* if previous frame SNR offset was 1023, check if current frame can also
+       use SNR offset of 1023. if so, skip the search. */
+    if ((snr_offset | s->fine_snr_offset[0]) == 1023) {
+        if (bit_alloc(s, 1023) <= bits_left)
+            return 0;
     }
 
-    /* frequency */
-    for(i=0;i<3;i++) {
-        for(j=0;j<3;j++)
-            if ((ff_ac3_sample_rate_tab[j] >> i) == freq)
-                goto found;
+    while (snr_offset >= 0 &&
+           bit_alloc(s, snr_offset) > bits_left) {
+        snr_offset -= 64;
     }
-    return -1;
- found:
-    s->sample_rate = freq;
-    s->sr_shift = i;
-    s->sr_code = j;
-    s->bitstream_id = 8 + s->sr_shift;
-    s->bitstream_mode = 0; /* complete main audio service */
-
-    /* bitrate & frame size */
-    for(i=0;i<19;i++) {
-        if ((ff_ac3_bitrate_tab[i] >> s->sr_shift)*1000 == bitrate)
-            break;
+    if (snr_offset < 0)
+        return AVERROR(EINVAL);
+
+    FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
+    for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
+        while (snr_offset + snr_incr <= 1023 &&
+               bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
+            snr_offset += snr_incr;
+            FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
+        }
     }
-    if (i == 19)
-        return -1;
-    s->bit_rate = bitrate;
-    s->frame_size_code = i << 1;
-    s->frame_size_min = ff_ac3_frame_size_tab[s->frame_size_code][s->sr_code];
-    s->bits_written = 0;
-    s->samples_written = 0;
-    s->frame_size = s->frame_size_min;
+    FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
+    reset_block_bap(s);
 
-    /* bit allocation init */
-    if(avctx->cutoff) {
-        /* calculate bandwidth based on user-specified cutoff frequency */
-        int cutoff = av_clip(avctx->cutoff, 1, s->sample_rate >> 1);
-        int fbw_coeffs = cutoff * 512 / s->sample_rate;
-        bw_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
-    } else {
-        /* use default bandwidth setting */
-        /* XXX: should compute the bandwidth according to the frame
-           size, so that we avoid annoying high frequency artifacts */
-        bw_code = 50;
+    s->coarse_snr_offset = snr_offset >> 4;
+    for (ch = 0; ch < s->channels; ch++)
+        s->fine_snr_offset[ch] = snr_offset & 0xF;
+
+    return 0;
+}
+
+
+/**
+ * Downgrade exponent strategies to reduce the bits used by the exponents.
+ * This is a fallback for when bit allocation fails with the normal exponent
+ * strategies.  Each time this function is run it only downgrades the
+ * strategy in 1 channel of 1 block.
+ * @return non-zero if downgrade was unsuccessful
+ */
+static int downgrade_exponents(AC3EncodeContext *s)
+{
+    int ch, blk;
+
+    for (ch = 0; ch < s->fbw_channels; ch++) {
+        for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
+            if (s->exp_strategy[ch][blk] == EXP_D15) {
+                s->exp_strategy[ch][blk] = EXP_D25;
+                return 0;
+            }
+        }
     }
-    for(ch=0;ch<s->nb_channels;ch++) {
-        /* bandwidth for each channel */
-        s->chbwcod[ch] = bw_code;
-        s->nb_coefs[ch] = bw_code * 3 + 73;
+    for (ch = 0; ch < s->fbw_channels; ch++) {
+        for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
+            if (s->exp_strategy[ch][blk] == EXP_D25) {
+                s->exp_strategy[ch][blk] = EXP_D45;
+                return 0;
+            }
+        }
     }
-    if (s->lfe) {
-        s->nb_coefs[s->lfe_channel] = 7; /* fixed */
+    for (ch = 0; ch < s->fbw_channels; ch++) {
+        /* block 0 cannot reuse exponents, so only downgrade D45 to REUSE if
+           the block number > 0 */
+        for (blk = AC3_MAX_BLOCKS-1; blk > 0; blk--) {
+            if (s->exp_strategy[ch][blk] > EXP_REUSE) {
+                s->exp_strategy[ch][blk] = EXP_REUSE;
+                return 0;
+            }
+        }
     }
-    /* initial snr offset */
-    s->coarse_snr_offset = 40;
+    return -1;
+}
 
-    /* mdct init */
-    fft_init(MDCT_NBITS - 2);
-    for(i=0;i<N/4;i++) {
-        alpha = 2 * M_PI * (i + 1.0 / 8.0) / (float)N;
-        xcos1[i] = fix15(-cos(alpha));
-        xsin1[i] = fix15(-sin(alpha));
-    }
 
-    avctx->coded_frame= avcodec_alloc_frame();
-    avctx->coded_frame->key_frame= 1;
+/**
+ * Reduce the bandwidth to reduce the number of bits used for a given SNR offset.
+ * This is a second fallback for when bit allocation still fails after exponents
+ * have been downgraded.
+ * @return non-zero if bandwidth reduction was unsuccessful
+ */
+static int reduce_bandwidth(AC3EncodeContext *s, int min_bw_code)
+{
+    int ch;
 
-    return 0;
+    if (s->bandwidth_code[0] > min_bw_code) {
+        for (ch = 0; ch < s->fbw_channels; ch++) {
+            s->bandwidth_code[ch]--;
+            s->nb_coefs[ch] = s->bandwidth_code[ch] * 3 + 73;
+        }
+        return 0;
+    }
+    return -1;
 }
 
-/* output the AC-3 frame header */
-static void output_frame_header(AC3EncodeContext *s, unsigned char *frame)
+
+/**
+ * Perform bit allocation search.
+ * Finds the SNR offset value that maximizes quality and fits in the specified
+ * frame size.  Output is the SNR offset and a set of bit allocation pointers
+ * used to quantize the mantissas.
+ */
+static int compute_bit_allocation(AC3EncodeContext *s)
 {
-    init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
+    int ret;
 
-    put_bits(&s->pb, 16, 0x0b77); /* frame header */
-    put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
-    put_bits(&s->pb, 2, s->sr_code);
-    put_bits(&s->pb, 6, s->frame_size_code + (s->frame_size - s->frame_size_min));
-    put_bits(&s->pb, 5, s->bitstream_id);
-    put_bits(&s->pb, 3, s->bitstream_mode);
-    put_bits(&s->pb, 3, s->channel_mode);
-    if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
-        put_bits(&s->pb, 2, 1); /* XXX -4.5 dB */
-    if (s->channel_mode & 0x04)
-        put_bits(&s->pb, 2, 1); /* XXX -6 dB */
-    if (s->channel_mode == AC3_CHMODE_STEREO)
-        put_bits(&s->pb, 2, 0); /* surround not indicated */
-    put_bits(&s->pb, 1, s->lfe); /* LFE */
-    put_bits(&s->pb, 5, 31); /* dialog norm: -31 db */
-    put_bits(&s->pb, 1, 0); /* no compression control word */
-    put_bits(&s->pb, 1, 0); /* no lang code */
-    put_bits(&s->pb, 1, 0); /* no audio production info */
-    put_bits(&s->pb, 1, 0); /* no copyright */
-    put_bits(&s->pb, 1, 1); /* original bitstream */
-    put_bits(&s->pb, 1, 0); /* no time code 1 */
-    put_bits(&s->pb, 1, 0); /* no time code 2 */
-    put_bits(&s->pb, 1, 0); /* no additional bit stream info */
+    count_frame_bits(s);
+
+    bit_alloc_masking(s);
+
+    ret = cbr_bit_allocation(s);
+    while (ret) {
+        /* fallback 1: downgrade exponents */
+        if (!downgrade_exponents(s)) {
+            extract_exponents(s);
+            encode_exponents(s);
+            group_exponents(s);
+            ret = compute_bit_allocation(s);
+            continue;
+        }
+
+        /* fallback 2: reduce bandwidth */
+        /* only do this if the user has not specified a specific cutoff
+           frequency */
+        if (!s->cutoff && !reduce_bandwidth(s, 0)) {
+            process_exponents(s);
+            ret = compute_bit_allocation(s);
+            continue;
+        }
+
+        /* fallbacks were not enough... */
+        break;
+    }
+
+    return ret;
 }
 
-/* symetric quantization on 'levels' levels */
+
+/**
+ * Symmetric quantization on 'levels' levels.
+ */
 static inline int sym_quant(int c, int e, int levels)
 {
-    int v;
-
-    if (c >= 0) {
-        v = (levels * (c << e)) >> 24;
-        v = (v + 1) >> 1;
-        v = (levels >> 1) + v;
-    } else {
-        v = (levels * ((-c) << e)) >> 24;
-        v = (v + 1) >> 1;
-        v = (levels >> 1) - v;
-    }
-    assert (v >= 0 && v < levels);
+    int v = (((levels * c) >> (24 - e)) + levels) >> 1;
+    av_assert2(v >= 0 && v < levels);
     return v;
 }
 
-/* asymetric quantization on 2^qbits levels */
+
+/**
+ * Asymmetric quantization on 2^qbits levels.
+ */
 static inline int asym_quant(int c, int e, int qbits)
 {
     int lshift, m, v;
@@ -803,130 +1238,255 @@ static inline int asym_quant(int c, int e, int qbits)
     m = (1 << (qbits-1));
     if (v >= m)
         v = m - 1;
-    assert(v >= -m);
+    av_assert2(v >= -m);
     return v & ((1 << qbits)-1);
 }
 
-/* Output one audio block. There are NB_BLOCKS audio blocks in one AC-3
-   frame */
-static void output_audio_block(AC3EncodeContext *s,
-                               uint8_t exp_strategy[AC3_MAX_CHANNELS],
-                               uint8_t encoded_exp[AC3_MAX_CHANNELS][N/2],
-                               uint8_t bap[AC3_MAX_CHANNELS][N/2],
-                               int32_t mdct_coefs[AC3_MAX_CHANNELS][N/2],
-                               int8_t global_exp[AC3_MAX_CHANNELS],
-                               int block_num)
+
+/**
+ * Quantize a set of mantissas for a single channel in a single block.
+ */
+static void quantize_mantissas_blk_ch(AC3Mant *s, int32_t *fixed_coef,
+                                      uint8_t *exp,
+                                      uint8_t *bap, uint16_t *qmant, int n)
 {
-    int ch, nb_groups, group_size, i, baie, rbnd;
-    uint8_t *p;
-    uint16_t qmant[AC3_MAX_CHANNELS][N/2];
-    int exp0, exp1;
-    int mant1_cnt, mant2_cnt, mant4_cnt;
-    uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr;
-    int delta0, delta1, delta2;
+    int i;
 
-    for(ch=0;ch<s->nb_channels;ch++)
-        put_bits(&s->pb, 1, 0); /* 512 point MDCT */
-    for(ch=0;ch<s->nb_channels;ch++)
-        put_bits(&s->pb, 1, 1); /* no dither */
-    put_bits(&s->pb, 1, 0); /* no dynamic range */
-    if (block_num == 0) {
-        /* for block 0, even if no coupling, we must say it. This is a
-           waste of bit :-) */
-        put_bits(&s->pb, 1, 1); /* coupling strategy present */
-        put_bits(&s->pb, 1, 0); /* no coupling strategy */
-    } else {
-        put_bits(&s->pb, 1, 0); /* no new coupling strategy */
+    for (i = 0; i < n; i++) {
+        int v;
+        int c = fixed_coef[i];
+        int e = exp[i];
+        int b = bap[i];
+        switch (b) {
+        case 0:
+            v = 0;
+            break;
+        case 1:
+            v = sym_quant(c, e, 3);
+            switch (s->mant1_cnt) {
+            case 0:
+                s->qmant1_ptr = &qmant[i];
+                v = 9 * v;
+                s->mant1_cnt = 1;
+                break;
+            case 1:
+                *s->qmant1_ptr += 3 * v;
+                s->mant1_cnt = 2;
+                v = 128;
+                break;
+            default:
+                *s->qmant1_ptr += v;
+                s->mant1_cnt = 0;
+                v = 128;
+                break;
+            }
+            break;
+        case 2:
+            v = sym_quant(c, e, 5);
+            switch (s->mant2_cnt) {
+            case 0:
+                s->qmant2_ptr = &qmant[i];
+                v = 25 * v;
+                s->mant2_cnt = 1;
+                break;
+            case 1:
+                *s->qmant2_ptr += 5 * v;
+                s->mant2_cnt = 2;
+                v = 128;
+                break;
+            default:
+                *s->qmant2_ptr += v;
+                s->mant2_cnt = 0;
+                v = 128;
+                break;
+            }
+            break;
+        case 3:
+            v = sym_quant(c, e, 7);
+            break;
+        case 4:
+            v = sym_quant(c, e, 11);
+            switch (s->mant4_cnt) {
+            case 0:
+                s->qmant4_ptr = &qmant[i];
+                v = 11 * v;
+                s->mant4_cnt = 1;
+                break;
+            default:
+                *s->qmant4_ptr += v;
+                s->mant4_cnt = 0;
+                v = 128;
+                break;
+            }
+            break;
+        case 5:
+            v = sym_quant(c, e, 15);
+            break;
+        case 14:
+            v = asym_quant(c, e, 14);
+            break;
+        case 15:
+            v = asym_quant(c, e, 16);
+            break;
+        default:
+            v = asym_quant(c, e, b - 1);
+            break;
+        }
+        qmant[i] = v;
     }
+}
 
-    if (s->channel_mode == AC3_CHMODE_STEREO)
-      {
-        if(block_num==0)
-          {
-            /* first block must define rematrixing (rematstr)  */
-            put_bits(&s->pb, 1, 1);
-
-            /* dummy rematrixing rematflg(1:4)=0 */
-            for (rbnd=0;rbnd<4;rbnd++)
-              put_bits(&s->pb, 1, 0);
-          }
-        else
-          {
-            /* no matrixing (but should be used in the future) */
-            put_bits(&s->pb, 1, 0);
-          }
-      }
 
-#if defined(DEBUG)
-    {
-      static int count = 0;
-      av_log(NULL, AV_LOG_DEBUG, "Block #%d (%d)\n", block_num, count++);
+/**
+ * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
+ */
+static void quantize_mantissas(AC3EncodeContext *s)
+{
+    int blk, ch;
+
+
+    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
+        AC3Block *block = &s->blocks[blk];
+        AC3Block *ref_block;
+        AC3Mant m = { 0 };
+
+        for (ch = 0; ch < s->channels; ch++) {
+            ref_block = block->exp_ref_block[ch];
+            quantize_mantissas_blk_ch(&m, block->fixed_coef[ch],
+                                      ref_block->exp[ch], ref_block->bap[ch],
+                                      block->qmant[ch], s->nb_coefs[ch]);
+        }
     }
-#endif
-    /* exponent strategy */
-    for(ch=0;ch<s->nb_channels;ch++) {
-        put_bits(&s->pb, 2, exp_strategy[ch]);
+}
+
+
+/**
+ * Write the AC-3 frame header to the output bitstream.
+ */
+static void output_frame_header(AC3EncodeContext *s)
+{
+    AC3EncOptions *opt = &s->options;
+
+    put_bits(&s->pb, 16, 0x0b77);   /* frame header */
+    put_bits(&s->pb, 16, 0);        /* crc1: will be filled later */
+    put_bits(&s->pb, 2,  s->bit_alloc.sr_code);
+    put_bits(&s->pb, 6,  s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
+    put_bits(&s->pb, 5,  s->bitstream_id);
+    put_bits(&s->pb, 3,  s->bitstream_mode);
+    put_bits(&s->pb, 3,  s->channel_mode);
+    if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
+        put_bits(&s->pb, 2, s->center_mix_level);
+    if (s->channel_mode & 0x04)
+        put_bits(&s->pb, 2, s->surround_mix_level);
+    if (s->channel_mode == AC3_CHMODE_STEREO)
+        put_bits(&s->pb, 2, opt->dolby_surround_mode);
+    put_bits(&s->pb, 1, s->lfe_on); /* LFE */
+    put_bits(&s->pb, 5, -opt->dialogue_level);
+    put_bits(&s->pb, 1, 0);         /* no compression control word */
+    put_bits(&s->pb, 1, 0);         /* no lang code */
+    put_bits(&s->pb, 1, opt->audio_production_info);
+    if (opt->audio_production_info) {
+        put_bits(&s->pb, 5, opt->mixing_level - 80);
+        put_bits(&s->pb, 2, opt->room_type);
+    }
+    put_bits(&s->pb, 1, opt->copyright);
+    put_bits(&s->pb, 1, opt->original);
+    if (s->bitstream_id == 6) {
+        /* alternate bit stream syntax */
+        put_bits(&s->pb, 1, opt->extended_bsi_1);
+        if (opt->extended_bsi_1) {
+            put_bits(&s->pb, 2, opt->preferred_stereo_downmix);
+            put_bits(&s->pb, 3, s->ltrt_center_mix_level);
+            put_bits(&s->pb, 3, s->ltrt_surround_mix_level);
+            put_bits(&s->pb, 3, s->loro_center_mix_level);
+            put_bits(&s->pb, 3, s->loro_surround_mix_level);
+        }
+        put_bits(&s->pb, 1, opt->extended_bsi_2);
+        if (opt->extended_bsi_2) {
+            put_bits(&s->pb, 2, opt->dolby_surround_ex_mode);
+            put_bits(&s->pb, 2, opt->dolby_headphone_mode);
+            put_bits(&s->pb, 1, opt->ad_converter_type);
+            put_bits(&s->pb, 9, 0);     /* xbsi2 and encinfo : reserved */
+        }
+    } else {
+    put_bits(&s->pb, 1, 0);         /* no time code 1 */
+    put_bits(&s->pb, 1, 0);         /* no time code 2 */
+    }
+    put_bits(&s->pb, 1, 0);         /* no additional bit stream info */
+}
+
+
+/**
+ * Write one audio block to the output bitstream.
+ */
+static void output_audio_block(AC3EncodeContext *s, int blk)
+{
+    int ch, i, baie, rbnd;
+    AC3Block *block = &s->blocks[blk];
+
+    /* block switching */
+    for (ch = 0; ch < s->fbw_channels; ch++)
+        put_bits(&s->pb, 1, 0);
+
+    /* dither flags */
+    for (ch = 0; ch < s->fbw_channels; ch++)
+        put_bits(&s->pb, 1, 1);
+
+    /* dynamic range codes */
+    put_bits(&s->pb, 1, 0);
+
+    /* channel coupling */
+    if (!blk) {
+        put_bits(&s->pb, 1, 1); /* coupling strategy present */
+        put_bits(&s->pb, 1, 0); /* no coupling strategy */
+    } else {
+        put_bits(&s->pb, 1, 0); /* no new coupling strategy */
     }
 
-    if (s->lfe) {
-        put_bits(&s->pb, 1, exp_strategy[s->lfe_channel]);
+    /* stereo rematrixing */
+    if (s->channel_mode == AC3_CHMODE_STEREO) {
+        put_bits(&s->pb, 1, block->new_rematrixing_strategy);
+        if (block->new_rematrixing_strategy) {
+            /* rematrixing flags */
+            for (rbnd = 0; rbnd < s->num_rematrixing_bands; rbnd++)
+                put_bits(&s->pb, 1, block->rematrixing_flags[rbnd]);
+        }
     }
 
-    for(ch=0;ch<s->nb_channels;ch++) {
-        if (exp_strategy[ch] != EXP_REUSE)
-            put_bits(&s->pb, 6, s->chbwcod[ch]);
+    /* exponent strategy */
+    for (ch = 0; ch < s->fbw_channels; ch++)
+        put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
+    if (s->lfe_on)
+        put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
+
+    /* bandwidth */
+    for (ch = 0; ch < s->fbw_channels; ch++) {
+        if (s->exp_strategy[ch][blk] != EXP_REUSE)
+            put_bits(&s->pb, 6, s->bandwidth_code[ch]);
     }
 
     /* exponents */
-    for (ch = 0; ch < s->nb_all_channels; ch++) {
-        switch(exp_strategy[ch]) {
-        case EXP_REUSE:
+    for (ch = 0; ch < s->channels; ch++) {
+        int nb_groups;
+
+        if (s->exp_strategy[ch][blk] == EXP_REUSE)
             continue;
-        case EXP_D15:
-            group_size = 1;
-            break;
-        case EXP_D25:
-            group_size = 2;
-            break;
-        default:
-        case EXP_D45:
-            group_size = 4;
-            break;
-        }
-        nb_groups = (s->nb_coefs[ch] + (group_size * 3) - 4) / (3 * group_size);
-        p = encoded_exp[ch];
-
-        /* first exponent */
-        exp1 = *p++;
-        put_bits(&s->pb, 4, exp1);
-
-        /* next ones are delta encoded */
-        for(i=0;i<nb_groups;i++) {
-            /* merge three delta in one code */
-            exp0 = exp1;
-            exp1 = p[0];
-            p += group_size;
-            delta0 = exp1 - exp0 + 2;
-
-            exp0 = exp1;
-            exp1 = p[0];
-            p += group_size;
-            delta1 = exp1 - exp0 + 2;
-
-            exp0 = exp1;
-            exp1 = p[0];
-            p += group_size;
-            delta2 = exp1 - exp0 + 2;
-
-            put_bits(&s->pb, 7, ((delta0 * 5 + delta1) * 5) + delta2);
-        }
 
+        /* DC exponent */
+        put_bits(&s->pb, 4, block->grouped_exp[ch][0]);
+
+        /* exponent groups */
+        nb_groups = exponent_group_tab[s->exp_strategy[ch][blk]-1][s->nb_coefs[ch]];
+        for (i = 1; i <= nb_groups; i++)
+            put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
+
+        /* gain range info */
         if (ch != s->lfe_channel)
-            put_bits(&s->pb, 2, 0); /* no gain range info */
+            put_bits(&s->pb, 2, 0);
     }
 
     /* bit allocation info */
-    baie = (block_num == 0);
+    baie = (blk == 0);
     put_bits(&s->pb, 1, baie);
     if (baie) {
         put_bits(&s->pb, 2, s->slow_decay_code);
@@ -937,10 +1497,10 @@ static void output_audio_block(AC3EncodeContext *s,
     }
 
     /* snr offset */
-    put_bits(&s->pb, 1, baie); /* always present with bai */
+    put_bits(&s->pb, 1, baie);
     if (baie) {
         put_bits(&s->pb, 6, s->coarse_snr_offset);
-        for(ch=0;ch<s->nb_all_channels;ch++) {
+        for (ch = 0; ch < s->channels; ch++) {
             put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
             put_bits(&s->pb, 3, s->fast_gain_code[ch]);
         }
@@ -949,141 +1509,32 @@ static void output_audio_block(AC3EncodeContext *s,
     put_bits(&s->pb, 1, 0); /* no delta bit allocation */
     put_bits(&s->pb, 1, 0); /* no data to skip */
 
-    /* mantissa encoding : we use two passes to handle the grouping. A
-       one pass method may be faster, but it would necessitate to
-       modify the output stream. */
-
-    /* first pass: quantize */
-    mant1_cnt = mant2_cnt = mant4_cnt = 0;
-    qmant1_ptr = qmant2_ptr = qmant4_ptr = NULL;
-
-    for (ch = 0; ch < s->nb_all_channels; ch++) {
-        int b, c, e, v;
-
-        for(i=0;i<s->nb_coefs[ch];i++) {
-            c = mdct_coefs[ch][i];
-            e = encoded_exp[ch][i] - global_exp[ch];
-            b = bap[ch][i];
-            switch(b) {
-            case 0:
-                v = 0;
-                break;
-            case 1:
-                v = sym_quant(c, e, 3);
-                switch(mant1_cnt) {
-                case 0:
-                    qmant1_ptr = &qmant[ch][i];
-                    v = 9 * v;
-                    mant1_cnt = 1;
-                    break;
-                case 1:
-                    *qmant1_ptr += 3 * v;
-                    mant1_cnt = 2;
-                    v = 128;
-                    break;
-                default:
-                    *qmant1_ptr += v;
-                    mant1_cnt = 0;
-                    v = 128;
-                    break;
-                }
-                break;
-            case 2:
-                v = sym_quant(c, e, 5);
-                switch(mant2_cnt) {
-                case 0:
-                    qmant2_ptr = &qmant[ch][i];
-                    v = 25 * v;
-                    mant2_cnt = 1;
-                    break;
-                case 1:
-                    *qmant2_ptr += 5 * v;
-                    mant2_cnt = 2;
-                    v = 128;
-                    break;
-                default:
-                    *qmant2_ptr += v;
-                    mant2_cnt = 0;
-                    v = 128;
-                    break;
-                }
-                break;
-            case 3:
-                v = sym_quant(c, e, 7);
-                break;
-            case 4:
-                v = sym_quant(c, e, 11);
-                switch(mant4_cnt) {
-                case 0:
-                    qmant4_ptr = &qmant[ch][i];
-                    v = 11 * v;
-                    mant4_cnt = 1;
-                    break;
-                default:
-                    *qmant4_ptr += v;
-                    mant4_cnt = 0;
-                    v = 128;
-                    break;
-                }
-                break;
-            case 5:
-                v = sym_quant(c, e, 15);
-                break;
-            case 14:
-                v = asym_quant(c, e, 14);
-                break;
-            case 15:
-                v = asym_quant(c, e, 16);
-                break;
-            default:
-                v = asym_quant(c, e, b - 1);
-                break;
-            }
-            qmant[ch][i] = v;
-        }
-    }
-
-    /* second pass : output the values */
-    for (ch = 0; ch < s->nb_all_channels; ch++) {
+    /* mantissas */
+    for (ch = 0; ch < s->channels; ch++) {
         int b, q;
-
-        for(i=0;i<s->nb_coefs[ch];i++) {
-            q = qmant[ch][i];
-            b = bap[ch][i];
-            switch(b) {
-            case 0:
-                break;
-            case 1:
-                if (q != 128)
-                    put_bits(&s->pb, 5, q);
-                break;
-            case 2:
-                if (q != 128)
-                    put_bits(&s->pb, 7, q);
-                break;
-            case 3:
-                put_bits(&s->pb, 3, q);
-                break;
-            case 4:
-                if (q != 128)
-                    put_bits(&s->pb, 7, q);
-                break;
-            case 14:
-                put_bits(&s->pb, 14, q);
-                break;
-            case 15:
-                put_bits(&s->pb, 16, q);
-                break;
-            default:
-                put_bits(&s->pb, b - 1, q);
-                break;
+        AC3Block *ref_block = block->exp_ref_block[ch];
+        for (i = 0; i < s->nb_coefs[ch]; i++) {
+            q = block->qmant[ch][i];
+            b = ref_block->bap[ch][i];
+            switch (b) {
+            case 0:                                         break;
+            case 1: if (q != 128) put_bits(&s->pb,   5, q); break;
+            case 2: if (q != 128) put_bits(&s->pb,   7, q); break;
+            case 3:               put_bits(&s->pb,   3, q); break;
+            case 4: if (q != 128) put_bits(&s->pb,   7, q); break;
+            case 14:              put_bits(&s->pb,  14, q); break;
+            case 15:              put_bits(&s->pb,  16, q); break;
+            default:              put_bits(&s->pb, b-1, q); break;
             }
         }
     }
 }
 
+
+/** CRC-16 Polynomial */
 #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
 
+
 static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
 {
     unsigned int c;
@@ -1100,6 +1551,7 @@ static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
     return c;
 }
 
+
 static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
 {
     unsigned int r;
@@ -1114,312 +1566,711 @@ static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
 }
 
 
-/* compute log2(max(abs(tab[]))) */
-static int log2_tab(int16_t *tab, int n)
+/**
+ * Fill the end of the frame with 0's and compute the two CRCs.
+ */
+static void output_frame_end(AC3EncodeContext *s)
 {
-    int i, v;
+    const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
+    int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
+    uint8_t *frame;
+
+    frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
 
-    v = 0;
-    for(i=0;i<n;i++) {
-        v |= abs(tab[i]);
+    /* pad the remainder of the frame with zeros */
+    av_assert2(s->frame_size * 8 - put_bits_count(&s->pb) >= 18);
+    flush_put_bits(&s->pb);
+    frame = s->pb.buf;
+    pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
+    av_assert2(pad_bytes >= 0);
+    if (pad_bytes > 0)
+        memset(put_bits_ptr(&s->pb), 0, pad_bytes);
+
+    /* compute crc1 */
+    /* this is not so easy because it is at the beginning of the data... */
+    crc1    = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
+    crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
+    crc1    = mul_poly(crc_inv, crc1, CRC16_POLY);
+    AV_WB16(frame + 2, crc1);
+
+    /* compute crc2 */
+    crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
+                          s->frame_size - frame_size_58 - 3);
+    crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
+    /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
+    if (crc2 == 0x770B) {
+        frame[s->frame_size - 3] ^= 0x1;
+        crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
     }
-    return av_log2(v);
+    crc2 = av_bswap16(crc2);
+    AV_WB16(frame + s->frame_size - 2, crc2);
 }
 
-static void lshift_tab(int16_t *tab, int n, int lshift)
+
+/**
+ * Write the frame to the output bitstream.
+ */
+static void output_frame(AC3EncodeContext *s, unsigned char *frame)
 {
-    int i;
+    int blk;
+
+    init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
+
+    output_frame_header(s);
+
+    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
+        output_audio_block(s, blk);
+
+    output_frame_end(s);
+}
+
 
-    if (lshift > 0) {
-        for(i=0;i<n;i++) {
-            tab[i] <<= lshift;
+static void dprint_options(AVCodecContext *avctx)
+{
+#ifdef DEBUG
+    AC3EncodeContext *s = avctx->priv_data;
+    AC3EncOptions *opt = &s->options;
+    char strbuf[32];
+
+    switch (s->bitstream_id) {
+    case  6:  strncpy(strbuf, "AC-3 (alt syntax)", 32);      break;
+    case  8:  strncpy(strbuf, "AC-3 (standard)", 32);        break;
+    case  9:  strncpy(strbuf, "AC-3 (dnet half-rate)", 32);  break;
+    case 10:  strncpy(strbuf, "AC-3 (dnet quater-rate", 32); break;
+    default: snprintf(strbuf, 32, "ERROR");
+    }
+    av_dlog(avctx, "bitstream_id: %s (%d)\n", strbuf, s->bitstream_id);
+    av_dlog(avctx, "sample_fmt: %s\n", av_get_sample_fmt_name(avctx->sample_fmt));
+    av_get_channel_layout_string(strbuf, 32, s->channels, avctx->channel_layout);
+    av_dlog(avctx, "channel_layout: %s\n", strbuf);
+    av_dlog(avctx, "sample_rate: %d\n", s->sample_rate);
+    av_dlog(avctx, "bit_rate: %d\n", s->bit_rate);
+    if (s->cutoff)
+        av_dlog(avctx, "cutoff: %d\n", s->cutoff);
+
+    av_dlog(avctx, "per_frame_metadata: %s\n",
+            opt->allow_per_frame_metadata?"on":"off");
+    if (s->has_center)
+        av_dlog(avctx, "center_mixlev: %0.3f (%d)\n", opt->center_mix_level,
+                s->center_mix_level);
+    else
+        av_dlog(avctx, "center_mixlev: {not written}\n");
+    if (s->has_surround)
+        av_dlog(avctx, "surround_mixlev: %0.3f (%d)\n", opt->surround_mix_level,
+                s->surround_mix_level);
+    else
+        av_dlog(avctx, "surround_mixlev: {not written}\n");
+    if (opt->audio_production_info) {
+        av_dlog(avctx, "mixing_level: %ddB\n", opt->mixing_level);
+        switch (opt->room_type) {
+        case 0:  strncpy(strbuf, "notindicated", 32); break;
+        case 1:  strncpy(strbuf, "large", 32);        break;
+        case 2:  strncpy(strbuf, "small", 32);        break;
+        default: snprintf(strbuf, 32, "ERROR (%d)", opt->room_type);
+        }
+        av_dlog(avctx, "room_type: %s\n", strbuf);
+    } else {
+        av_dlog(avctx, "mixing_level: {not written}\n");
+        av_dlog(avctx, "room_type: {not written}\n");
+    }
+    av_dlog(avctx, "copyright: %s\n", opt->copyright?"on":"off");
+    av_dlog(avctx, "dialnorm: %ddB\n", opt->dialogue_level);
+    if (s->channel_mode == AC3_CHMODE_STEREO) {
+        switch (opt->dolby_surround_mode) {
+        case 0:  strncpy(strbuf, "notindicated", 32); break;
+        case 1:  strncpy(strbuf, "on", 32);           break;
+        case 2:  strncpy(strbuf, "off", 32);          break;
+        default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_mode);
+        }
+        av_dlog(avctx, "dsur_mode: %s\n", strbuf);
+    } else {
+        av_dlog(avctx, "dsur_mode: {not written}\n");
+    }
+    av_dlog(avctx, "original: %s\n", opt->original?"on":"off");
+
+    if (s->bitstream_id == 6) {
+        if (opt->extended_bsi_1) {
+            switch (opt->preferred_stereo_downmix) {
+            case 0:  strncpy(strbuf, "notindicated", 32); break;
+            case 1:  strncpy(strbuf, "ltrt", 32);         break;
+            case 2:  strncpy(strbuf, "loro", 32);         break;
+            default: snprintf(strbuf, 32, "ERROR (%d)", opt->preferred_stereo_downmix);
+            }
+            av_dlog(avctx, "dmix_mode: %s\n", strbuf);
+            av_dlog(avctx, "ltrt_cmixlev: %0.3f (%d)\n",
+                    opt->ltrt_center_mix_level, s->ltrt_center_mix_level);
+            av_dlog(avctx, "ltrt_surmixlev: %0.3f (%d)\n",
+                    opt->ltrt_surround_mix_level, s->ltrt_surround_mix_level);
+            av_dlog(avctx, "loro_cmixlev: %0.3f (%d)\n",
+                    opt->loro_center_mix_level, s->loro_center_mix_level);
+            av_dlog(avctx, "loro_surmixlev: %0.3f (%d)\n",
+                    opt->loro_surround_mix_level, s->loro_surround_mix_level);
+        } else {
+            av_dlog(avctx, "extended bitstream info 1: {not written}\n");
         }
-    } else if (lshift < 0) {
-        lshift = -lshift;
-        for(i=0;i<n;i++) {
-            tab[i] >>= lshift;
+        if (opt->extended_bsi_2) {
+            switch (opt->dolby_surround_ex_mode) {
+            case 0:  strncpy(strbuf, "notindicated", 32); break;
+            case 1:  strncpy(strbuf, "on", 32);           break;
+            case 2:  strncpy(strbuf, "off", 32);          break;
+            default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_ex_mode);
+            }
+            av_dlog(avctx, "dsurex_mode: %s\n", strbuf);
+            switch (opt->dolby_headphone_mode) {
+            case 0:  strncpy(strbuf, "notindicated", 32); break;
+            case 1:  strncpy(strbuf, "on", 32);           break;
+            case 2:  strncpy(strbuf, "off", 32);          break;
+            default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_headphone_mode);
+            }
+            av_dlog(avctx, "dheadphone_mode: %s\n", strbuf);
+
+            switch (opt->ad_converter_type) {
+            case 0:  strncpy(strbuf, "standard", 32); break;
+            case 1:  strncpy(strbuf, "hdcd", 32);     break;
+            default: snprintf(strbuf, 32, "ERROR (%d)", opt->ad_converter_type);
+            }
+            av_dlog(avctx, "ad_conv_type: %s\n", strbuf);
+        } else {
+            av_dlog(avctx, "extended bitstream info 2: {not written}\n");
         }
     }
+#endif
 }
 
-/* fill the end of the frame and compute the two crcs */
-static int output_frame_end(AC3EncodeContext *s)
+
+#define FLT_OPTION_THRESHOLD 0.01
+
+static int validate_float_option(float v, const float *v_list, int v_list_size)
 {
-    int frame_size, frame_size_58, n, crc1, crc2, crc_inv;
-    uint8_t *frame;
+    int i;
 
-    frame_size = s->frame_size; /* frame size in words */
-    /* align to 8 bits */
-    flush_put_bits(&s->pb);
-    /* add zero bytes to reach the frame size */
-    frame = s->pb.buf;
-    n = 2 * s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
-    assert(n >= 0);
-    if(n>0)
-      memset(put_bits_ptr(&s->pb), 0, n);
-
-    /* Now we must compute both crcs : this is not so easy for crc1
-       because it is at the beginning of the data... */
-    frame_size_58 = (frame_size >> 1) + (frame_size >> 3);
-    crc1 = bswap_16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
-                           frame + 4, 2 * frame_size_58 - 4));
-    /* XXX: could precompute crc_inv */
-    crc_inv = pow_poly((CRC16_POLY >> 1), (16 * frame_size_58) - 16, CRC16_POLY);
-    crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
-    AV_WB16(frame+2,crc1);
-
-    crc2 = bswap_16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
-                           frame + 2 * frame_size_58,
-                           (frame_size - frame_size_58) * 2 - 2));
-    AV_WB16(frame+2*frame_size-2,crc2);
-
-    //    printf("n=%d frame_size=%d\n", n, frame_size);
-    return frame_size * 2;
+    for (i = 0; i < v_list_size; i++) {
+        if (v < (v_list[i] + FLT_OPTION_THRESHOLD) &&
+            v > (v_list[i] - FLT_OPTION_THRESHOLD))
+            break;
+    }
+    if (i == v_list_size)
+        return -1;
+
+    return i;
 }
 
-static int AC3_encode_frame(AVCodecContext *avctx,
-                            unsigned char *frame, int buf_size, void *data)
+
+static void validate_mix_level(void *log_ctx, const char *opt_name,
+                               float *opt_param, const float *list,
+                               int list_size, int default_value, int min_value,
+                               int *ctx_param)
 {
-    AC3EncodeContext *s = avctx->priv_data;
-    int16_t *samples = data;
-    int i, j, k, v, ch;
-    int16_t input_samples[N];
-    int32_t mdct_coef[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
-    uint8_t exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
-    uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS];
-    uint8_t encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
-    uint8_t bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
-    int8_t exp_samples[NB_BLOCKS][AC3_MAX_CHANNELS];
-    int frame_bits;
+    int mixlev = validate_float_option(*opt_param, list, list_size);
+    if (mixlev < min_value) {
+        mixlev = default_value;
+        if (*opt_param >= 0.0) {
+            av_log(log_ctx, AV_LOG_WARNING, "requested %s is not valid. using "
+                   "default value: %0.3f\n", opt_name, list[mixlev]);
+        }
+    }
+    *opt_param = list[mixlev];
+    *ctx_param = mixlev;
+}
 
-    frame_bits = 0;
-    for(ch=0;ch<s->nb_all_channels;ch++) {
-        int ich = s->channel_map[ch];
-        /* fixed mdct to the six sub blocks & exponent computation */
-        for(i=0;i<NB_BLOCKS;i++) {
-            int16_t *sptr;
-            int sinc;
-
-            /* compute input samples */
-            memcpy(input_samples, s->last_samples[ich], N/2 * sizeof(int16_t));
-            sinc = s->nb_all_channels;
-            sptr = samples + (sinc * (N/2) * i) + ich;
-            for(j=0;j<N/2;j++) {
-                v = *sptr;
-                input_samples[j + N/2] = v;
-                s->last_samples[ich][j] = v;
-                sptr += sinc;
-            }
 
-            /* apply the MDCT window */
-            for(j=0;j<N/2;j++) {
-                input_samples[j] = MUL16(input_samples[j],
-                                         ff_ac3_window[j]) >> 15;
-                input_samples[N-j-1] = MUL16(input_samples[N-j-1],
-                                             ff_ac3_window[j]) >> 15;
-            }
+/**
+ * Validate metadata options as set by AVOption system.
+ * These values can optionally be changed per-frame.
+ */
+static int validate_metadata(AVCodecContext *avctx)
+{
+    AC3EncodeContext *s = avctx->priv_data;
+    AC3EncOptions *opt = &s->options;
 
-            /* Normalize the samples to use the maximum available
-               precision */
-            v = 14 - log2_tab(input_samples, N);
-            if (v < 0)
-                v = 0;
-            exp_samples[i][ch] = v - 9;
-            lshift_tab(input_samples, N, v);
-
-            /* do the MDCT */
-            mdct512(mdct_coef[i][ch], input_samples);
-
-            /* compute "exponents". We take into account the
-               normalization there */
-            for(j=0;j<N/2;j++) {
-                int e;
-                v = abs(mdct_coef[i][ch][j]);
-                if (v == 0)
-                    e = 24;
-                else {
-                    e = 23 - av_log2(v) + exp_samples[i][ch];
-                    if (e >= 24) {
-                        e = 24;
-                        mdct_coef[i][ch][j] = 0;
-                    }
-                }
-                exp[i][ch][j] = e;
-            }
+    /* validate mixing levels */
+    if (s->has_center) {
+        validate_mix_level(avctx, "center_mix_level", &opt->center_mix_level,
+                           cmixlev_options, CMIXLEV_NUM_OPTIONS, 1, 0,
+                           &s->center_mix_level);
+    }
+    if (s->has_surround) {
+        validate_mix_level(avctx, "surround_mix_level", &opt->surround_mix_level,
+                           surmixlev_options, SURMIXLEV_NUM_OPTIONS, 1, 0,
+                           &s->surround_mix_level);
+    }
+
+    /* set audio production info flag */
+    if (opt->mixing_level >= 0 || opt->room_type >= 0) {
+        if (opt->mixing_level < 0) {
+            av_log(avctx, AV_LOG_ERROR, "mixing_level must be set if "
+                   "room_type is set\n");
+            return AVERROR(EINVAL);
         }
+        if (opt->mixing_level < 80) {
+            av_log(avctx, AV_LOG_ERROR, "invalid mixing level. must be between "
+                   "80dB and 111dB\n");
+            return AVERROR(EINVAL);
+        }
+        /* default room type */
+        if (opt->room_type < 0)
+            opt->room_type = 0;
+        opt->audio_production_info = 1;
+    } else {
+        opt->audio_production_info = 0;
+    }
 
-        compute_exp_strategy(exp_strategy, exp, ch, ch == s->lfe_channel);
-
-        /* compute the exponents as the decoder will see them. The
-           EXP_REUSE case must be handled carefully : we select the
-           min of the exponents */
-        i = 0;
-        while (i < NB_BLOCKS) {
-            j = i + 1;
-            while (j < NB_BLOCKS && exp_strategy[j][ch] == EXP_REUSE) {
-                exponent_min(exp[i][ch], exp[j][ch], s->nb_coefs[ch]);
-                j++;
-            }
-            frame_bits += encode_exp(encoded_exp[i][ch],
-                                     exp[i][ch], s->nb_coefs[ch],
-                                     exp_strategy[i][ch]);
-            /* copy encoded exponents for reuse case */
-            for(k=i+1;k<j;k++) {
-                memcpy(encoded_exp[k][ch], encoded_exp[i][ch],
-                       s->nb_coefs[ch] * sizeof(uint8_t));
+    /* set extended bsi 1 flag */
+    if ((s->has_center || s->has_surround) &&
+        (opt->preferred_stereo_downmix >= 0 ||
+         opt->ltrt_center_mix_level   >= 0 ||
+         opt->ltrt_surround_mix_level >= 0 ||
+         opt->loro_center_mix_level   >= 0 ||
+         opt->loro_surround_mix_level >= 0)) {
+        /* default preferred stereo downmix */
+        if (opt->preferred_stereo_downmix < 0)
+            opt->preferred_stereo_downmix = 0;
+        /* validate Lt/Rt center mix level */
+        validate_mix_level(avctx, "ltrt_center_mix_level",
+                           &opt->ltrt_center_mix_level, extmixlev_options,
+                           EXTMIXLEV_NUM_OPTIONS, 5, 0,
+                           &s->ltrt_center_mix_level);
+        /* validate Lt/Rt surround mix level */
+        validate_mix_level(avctx, "ltrt_surround_mix_level",
+                           &opt->ltrt_surround_mix_level, extmixlev_options,
+                           EXTMIXLEV_NUM_OPTIONS, 6, 3,
+                           &s->ltrt_surround_mix_level);
+        /* validate Lo/Ro center mix level */
+        validate_mix_level(avctx, "loro_center_mix_level",
+                           &opt->loro_center_mix_level, extmixlev_options,
+                           EXTMIXLEV_NUM_OPTIONS, 5, 0,
+                           &s->loro_center_mix_level);
+        /* validate Lo/Ro surround mix level */
+        validate_mix_level(avctx, "loro_surround_mix_level",
+                           &opt->loro_surround_mix_level, extmixlev_options,
+                           EXTMIXLEV_NUM_OPTIONS, 6, 3,
+                           &s->loro_surround_mix_level);
+        opt->extended_bsi_1 = 1;
+    } else {
+        opt->extended_bsi_1 = 0;
+    }
+
+    /* set extended bsi 2 flag */
+    if (opt->dolby_surround_ex_mode >= 0 ||
+        opt->dolby_headphone_mode   >= 0 ||
+        opt->ad_converter_type      >= 0) {
+        /* default dolby surround ex mode */
+        if (opt->dolby_surround_ex_mode < 0)
+            opt->dolby_surround_ex_mode = 0;
+        /* default dolby headphone mode */
+        if (opt->dolby_headphone_mode < 0)
+            opt->dolby_headphone_mode = 0;
+        /* default A/D converter type */
+        if (opt->ad_converter_type < 0)
+            opt->ad_converter_type = 0;
+        opt->extended_bsi_2 = 1;
+    } else {
+        opt->extended_bsi_2 = 0;
+    }
+
+    /* set bitstream id for alternate bitstream syntax */
+    if (opt->extended_bsi_1 || opt->extended_bsi_2) {
+        if (s->bitstream_id > 8 && s->bitstream_id < 11) {
+            static int warn_once = 1;
+            if (warn_once) {
+                av_log(avctx, AV_LOG_WARNING, "alternate bitstream syntax is "
+                       "not compatible with reduced samplerates. writing of "
+                       "extended bitstream information will be disabled.\n");
+                warn_once = 0;
             }
-            i = j;
+        } else {
+            s->bitstream_id = 6;
         }
     }
 
-    /* adjust for fractional frame sizes */
-    while(s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
-        s->bits_written -= s->bit_rate;
-        s->samples_written -= s->sample_rate;
+    return 0;
+}
+
+
+/**
+ * Encode a single AC-3 frame.
+ */
+static int ac3_encode_frame(AVCodecContext *avctx, unsigned char *frame,
+                            int buf_size, void *data)
+{
+    AC3EncodeContext *s = avctx->priv_data;
+    const SampleType *samples = data;
+    int ret;
+
+    if (s->options.allow_per_frame_metadata) {
+        ret = validate_metadata(avctx);
+        if (ret)
+            return ret;
     }
-    s->frame_size = s->frame_size_min + (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
-    s->bits_written += s->frame_size * 16;
-    s->samples_written += AC3_FRAME_SIZE;
 
-    compute_bit_allocation(s, bap, encoded_exp, exp_strategy, frame_bits);
-    /* everything is known... let's output the frame */
-    output_frame_header(s, frame);
+    if (s->bit_alloc.sr_code == 1)
+        adjust_frame_size(s);
+
+    deinterleave_input_samples(s, samples);
 
-    for(i=0;i<NB_BLOCKS;i++) {
-        output_audio_block(s, exp_strategy[i], encoded_exp[i],
-                           bap[i], mdct_coef[i], exp_samples[i], i);
+    apply_mdct(s);
+
+    scale_coefficients(s);
+
+    compute_rematrixing_strategy(s);
+
+    apply_rematrixing(s);
+
+    process_exponents(s);
+
+    ret = compute_bit_allocation(s);
+    if (ret) {
+        av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
+        return ret;
     }
-    return output_frame_end(s);
+
+    quantize_mantissas(s);
+
+    output_frame(s, frame);
+
+    return s->frame_size;
 }
 
-static av_cold int AC3_encode_close(AVCodecContext *avctx)
+
+/**
+ * Finalize encoding and free any memory allocated by the encoder.
+ */
+static av_cold int ac3_encode_close(AVCodecContext *avctx)
 {
+    int blk, ch;
+    AC3EncodeContext *s = avctx->priv_data;
+
+    for (ch = 0; ch < s->channels; ch++)
+        av_freep(&s->planar_samples[ch]);
+    av_freep(&s->planar_samples);
+    av_freep(&s->bap_buffer);
+    av_freep(&s->bap1_buffer);
+    av_freep(&s->mdct_coef_buffer);
+    av_freep(&s->fixed_coef_buffer);
+    av_freep(&s->exp_buffer);
+    av_freep(&s->grouped_exp_buffer);
+    av_freep(&s->psd_buffer);
+    av_freep(&s->band_psd_buffer);
+    av_freep(&s->mask_buffer);
+    av_freep(&s->qmant_buffer);
+    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
+        AC3Block *block = &s->blocks[blk];
+        av_freep(&block->bap);
+        av_freep(&block->mdct_coef);
+        av_freep(&block->fixed_coef);
+        av_freep(&block->exp);
+        av_freep(&block->grouped_exp);
+        av_freep(&block->psd);
+        av_freep(&block->band_psd);
+        av_freep(&block->mask);
+        av_freep(&block->qmant);
+    }
+
+    mdct_end(&s->mdct);
+
     av_freep(&avctx->coded_frame);
     return 0;
 }
 
-#if 0
-/*************************************************************************/
-/* TEST */
 
-#undef random
-#define FN (N/4)
+/**
+ * Set channel information during initialization.
+ */
+static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
+                                    int64_t *channel_layout)
+{
+    int ch_layout;
+
+    if (channels < 1 || channels > AC3_MAX_CHANNELS)
+        return AVERROR(EINVAL);
+    if ((uint64_t)*channel_layout > 0x7FF)
+        return AVERROR(EINVAL);
+    ch_layout = *channel_layout;
+    if (!ch_layout)
+        ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
+    if (av_get_channel_layout_nb_channels(ch_layout) != channels)
+        return AVERROR(EINVAL);
+
+    s->lfe_on       = !!(ch_layout & AV_CH_LOW_FREQUENCY);
+    s->channels     = channels;
+    s->fbw_channels = channels - s->lfe_on;
+    s->lfe_channel  = s->lfe_on ? s->fbw_channels : -1;
+    if (s->lfe_on)
+        ch_layout -= AV_CH_LOW_FREQUENCY;
+
+    switch (ch_layout) {
+    case AV_CH_LAYOUT_MONO:           s->channel_mode = AC3_CHMODE_MONO;   break;
+    case AV_CH_LAYOUT_STEREO:         s->channel_mode = AC3_CHMODE_STEREO; break;
+    case AV_CH_LAYOUT_SURROUND:       s->channel_mode = AC3_CHMODE_3F;     break;
+    case AV_CH_LAYOUT_2_1:            s->channel_mode = AC3_CHMODE_2F1R;   break;
+    case AV_CH_LAYOUT_4POINT0:        s->channel_mode = AC3_CHMODE_3F1R;   break;
+    case AV_CH_LAYOUT_QUAD:
+    case AV_CH_LAYOUT_2_2:            s->channel_mode = AC3_CHMODE_2F2R;   break;
+    case AV_CH_LAYOUT_5POINT0:
+    case AV_CH_LAYOUT_5POINT0_BACK:   s->channel_mode = AC3_CHMODE_3F2R;   break;
+    default:
+        return AVERROR(EINVAL);
+    }
+    s->has_center   = (s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO;
+    s->has_surround =  s->channel_mode & 0x04;
+
+    s->channel_map  = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
+    *channel_layout = ch_layout;
+    if (s->lfe_on)
+        *channel_layout |= AV_CH_LOW_FREQUENCY;
+
+    return 0;
+}
 
-void fft_test(void)
+
+static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
 {
-    IComplex in[FN], in1[FN];
-    int k, n, i;
-    float sum_re, sum_im, a;
-
-    /* FFT test */
-
-    for(i=0;i<FN;i++) {
-        in[i].re = random() % 65535 - 32767;
-        in[i].im = random() % 65535 - 32767;
-        in1[i] = in[i];
-    }
-    fft(in, 7);
-
-    /* do it by hand */
-    for(k=0;k<FN;k++) {
-        sum_re = 0;
-        sum_im = 0;
-        for(n=0;n<FN;n++) {
-            a = -2 * M_PI * (n * k) / FN;
-            sum_re += in1[n].re * cos(a) - in1[n].im * sin(a);
-            sum_im += in1[n].re * sin(a) + in1[n].im * cos(a);
-        }
-        printf("%3d: %6d,%6d %6.0f,%6.0f\n",
-               k, in[k].re, in[k].im, sum_re / FN, sum_im / FN);
+    int i, ret;
+
+    /* validate channel layout */
+    if (!avctx->channel_layout) {
+        av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
+                                      "encoder will guess the layout, but it "
+                                      "might be incorrect.\n");
+    }
+    ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
+    if (ret) {
+        av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
+        return ret;
+    }
+
+    /* validate sample rate */
+    for (i = 0; i < 9; i++) {
+        if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
+            break;
+    }
+    if (i == 9) {
+        av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
+        return AVERROR(EINVAL);
+    }
+    s->sample_rate        = avctx->sample_rate;
+    s->bit_alloc.sr_shift = i % 3;
+    s->bit_alloc.sr_code  = i / 3;
+    s->bitstream_id       = 8 + s->bit_alloc.sr_shift;
+
+    /* validate bit rate */
+    for (i = 0; i < 19; i++) {
+        if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
+            break;
+    }
+    if (i == 19) {
+        av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
+        return AVERROR(EINVAL);
     }
+    s->bit_rate        = avctx->bit_rate;
+    s->frame_size_code = i << 1;
+
+    /* validate cutoff */
+    if (avctx->cutoff < 0) {
+        av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
+        return AVERROR(EINVAL);
+    }
+    s->cutoff = avctx->cutoff;
+    if (s->cutoff > (s->sample_rate >> 1))
+        s->cutoff = s->sample_rate >> 1;
+
+    /* validate audio service type / channels combination */
+    if ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_KARAOKE &&
+         avctx->channels == 1) ||
+        ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_COMMENTARY ||
+          avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_EMERGENCY  ||
+          avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_VOICE_OVER)
+         && avctx->channels > 1)) {
+        av_log(avctx, AV_LOG_ERROR, "invalid audio service type for the "
+                                    "specified number of channels\n");
+        return AVERROR(EINVAL);
+    }
+
+    ret = validate_metadata(avctx);
+    if (ret)
+        return ret;
+
+    return 0;
 }
 
-void mdct_test(void)
+
+/**
+ * Set bandwidth for all channels.
+ * The user can optionally supply a cutoff frequency. Otherwise an appropriate
+ * default value will be used.
+ */
+static av_cold void set_bandwidth(AC3EncodeContext *s)
 {
-    int16_t input[N];
-    int32_t output[N/2];
-    float input1[N];
-    float output1[N/2];
-    float s, a, err, e, emax;
-    int i, k, n;
-
-    for(i=0;i<N;i++) {
-        input[i] = (random() % 65535 - 32767) * 9 / 10;
-        input1[i] = input[i];
-    }
-
-    mdct512(output, input);
-
-    /* do it by hand */
-    for(k=0;k<N/2;k++) {
-        s = 0;
-        for(n=0;n<N;n++) {
-            a = (2*M_PI*(2*n+1+N/2)*(2*k+1) / (4 * N));
-            s += input1[n] * cos(a);
-        }
-        output1[k] = -2 * s / N;
+    int ch, bw_code;
+
+    if (s->cutoff) {
+        /* calculate bandwidth based on user-specified cutoff frequency */
+        int fbw_coeffs;
+        fbw_coeffs     = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
+        bw_code        = av_clip((fbw_coeffs - 73) / 3, 0, 60);
+    } else {
+        /* use default bandwidth setting */
+        bw_code = ac3_bandwidth_tab[s->fbw_channels-1][s->bit_alloc.sr_code][s->frame_size_code/2];
     }
 
-    err = 0;
-    emax = 0;
-    for(i=0;i<N/2;i++) {
-        printf("%3d: %7d %7.0f\n", i, output[i], output1[i]);
-        e = output[i] - output1[i];
-        if (e > emax)
-            emax = e;
-        err += e * e;
+    /* set number of coefficients for each channel */
+    for (ch = 0; ch < s->fbw_channels; ch++) {
+        s->bandwidth_code[ch] = bw_code;
+        s->nb_coefs[ch]       = bw_code * 3 + 73;
     }
-    printf("err2=%f emax=%f\n", err / (N/2), emax);
+    if (s->lfe_on)
+        s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
 }
 
-void test_ac3(void)
+
+static av_cold int allocate_buffers(AVCodecContext *avctx)
 {
-    AC3EncodeContext ctx;
-    unsigned char frame[AC3_MAX_CODED_FRAME_SIZE];
-    short samples[AC3_FRAME_SIZE];
-    int ret, i;
+    int blk, ch;
+    AC3EncodeContext *s = avctx->priv_data;
 
-    AC3_encode_init(&ctx, 44100, 64000, 1);
+    FF_ALLOC_OR_GOTO(avctx, s->planar_samples, s->channels * sizeof(*s->planar_samples),
+                     alloc_fail);
+    for (ch = 0; ch < s->channels; ch++) {
+        FF_ALLOCZ_OR_GOTO(avctx, s->planar_samples[ch],
+                          (AC3_FRAME_SIZE+AC3_BLOCK_SIZE) * sizeof(**s->planar_samples),
+                          alloc_fail);
+    }
+    FF_ALLOC_OR_GOTO(avctx, s->bap_buffer,  AC3_MAX_BLOCKS * s->channels *
+                     AC3_MAX_COEFS * sizeof(*s->bap_buffer),  alloc_fail);
+    FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * s->channels *
+                     AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
+    FF_ALLOC_OR_GOTO(avctx, s->mdct_coef_buffer, AC3_MAX_BLOCKS * s->channels *
+                     AC3_MAX_COEFS * sizeof(*s->mdct_coef_buffer), alloc_fail);
+    FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, AC3_MAX_BLOCKS * s->channels *
+                     AC3_MAX_COEFS * sizeof(*s->exp_buffer), alloc_fail);
+    FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, AC3_MAX_BLOCKS * s->channels *
+                     128 * sizeof(*s->grouped_exp_buffer), alloc_fail);
+    FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, AC3_MAX_BLOCKS * s->channels *
+                     AC3_MAX_COEFS * sizeof(*s->psd_buffer), alloc_fail);
+    FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, AC3_MAX_BLOCKS * s->channels *
+                     64 * sizeof(*s->band_psd_buffer), alloc_fail);
+    FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, AC3_MAX_BLOCKS * s->channels *
+                     64 * sizeof(*s->mask_buffer), alloc_fail);
+    FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, AC3_MAX_BLOCKS * s->channels *
+                     AC3_MAX_COEFS * sizeof(*s->qmant_buffer), alloc_fail);
+    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
+        AC3Block *block = &s->blocks[blk];
+        FF_ALLOC_OR_GOTO(avctx, block->bap, s->channels * sizeof(*block->bap),
+                         alloc_fail);
+        FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, s->channels * sizeof(*block->mdct_coef),
+                          alloc_fail);
+        FF_ALLOCZ_OR_GOTO(avctx, block->exp, s->channels * sizeof(*block->exp),
+                          alloc_fail);
+        FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, s->channels * sizeof(*block->grouped_exp),
+                          alloc_fail);
+        FF_ALLOCZ_OR_GOTO(avctx, block->psd, s->channels * sizeof(*block->psd),
+                          alloc_fail);
+        FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, s->channels * sizeof(*block->band_psd),
+                          alloc_fail);
+        FF_ALLOCZ_OR_GOTO(avctx, block->mask, s->channels * sizeof(*block->mask),
+                          alloc_fail);
+        FF_ALLOCZ_OR_GOTO(avctx, block->qmant, s->channels * sizeof(*block->qmant),
+                          alloc_fail);
+
+        for (ch = 0; ch < s->channels; ch++) {
+            /* arrangement: block, channel, coeff */
+            block->bap[ch]         = &s->bap_buffer        [AC3_MAX_COEFS * (blk * s->channels + ch)];
+            block->mdct_coef[ch]   = &s->mdct_coef_buffer  [AC3_MAX_COEFS * (blk * s->channels + ch)];
+            block->grouped_exp[ch] = &s->grouped_exp_buffer[128           * (blk * s->channels + ch)];
+            block->psd[ch]         = &s->psd_buffer        [AC3_MAX_COEFS * (blk * s->channels + ch)];
+            block->band_psd[ch]    = &s->band_psd_buffer   [64            * (blk * s->channels + ch)];
+            block->mask[ch]        = &s->mask_buffer       [64            * (blk * s->channels + ch)];
+            block->qmant[ch]       = &s->qmant_buffer      [AC3_MAX_COEFS * (blk * s->channels + ch)];
+
+            /* arrangement: channel, block, coeff */
+            block->exp[ch]         = &s->exp_buffer        [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
+        }
+    }
 
-    fft_test();
-    mdct_test();
+    if (CONFIG_AC3ENC_FLOAT) {
+        FF_ALLOC_OR_GOTO(avctx, s->fixed_coef_buffer, AC3_MAX_BLOCKS * s->channels *
+                         AC3_MAX_COEFS * sizeof(*s->fixed_coef_buffer), alloc_fail);
+        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
+            AC3Block *block = &s->blocks[blk];
+            FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, s->channels *
+                              sizeof(*block->fixed_coef), alloc_fail);
+            for (ch = 0; ch < s->channels; ch++)
+                block->fixed_coef[ch] = &s->fixed_coef_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
+        }
+    } else {
+        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
+            AC3Block *block = &s->blocks[blk];
+            FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, s->channels *
+                              sizeof(*block->fixed_coef), alloc_fail);
+            for (ch = 0; ch < s->channels; ch++)
+                block->fixed_coef[ch] = (int32_t *)block->mdct_coef[ch];
+        }
+    }
 
-    for(i=0;i<AC3_FRAME_SIZE;i++)
-        samples[i] = (int)(sin(2*M_PI*i*1000.0/44100) * 10000);
-    ret = AC3_encode_frame(&ctx, frame, samples);
-    printf("ret=%d\n", ret);
+    return 0;
+alloc_fail:
+    return AVERROR(ENOMEM);
 }
-#endif
 
-AVCodec ac3_encoder = {
-    "ac3",
-    AVMEDIA_TYPE_AUDIO,
-    CODEC_ID_AC3,
-    sizeof(AC3EncodeContext),
-    AC3_encode_init,
-    AC3_encode_frame,
-    AC3_encode_close,
-    NULL,
-    .sample_fmts = (const enum SampleFormat[]){SAMPLE_FMT_S16,SAMPLE_FMT_NONE},
-    .long_name = NULL_IF_CONFIG_SMALL("ATSC A/52A (AC-3)"),
-    .channel_layouts = (const int64_t[]){
-        CH_LAYOUT_MONO,
-        CH_LAYOUT_STEREO,
-        CH_LAYOUT_2_1,
-        CH_LAYOUT_SURROUND,
-        CH_LAYOUT_2_2,
-        CH_LAYOUT_QUAD,
-        CH_LAYOUT_4POINT0,
-        CH_LAYOUT_5POINT0,
-        CH_LAYOUT_5POINT0_BACK,
-       (CH_LAYOUT_MONO     | CH_LOW_FREQUENCY),
-       (CH_LAYOUT_STEREO   | CH_LOW_FREQUENCY),
-       (CH_LAYOUT_2_1      | CH_LOW_FREQUENCY),
-       (CH_LAYOUT_SURROUND | CH_LOW_FREQUENCY),
-       (CH_LAYOUT_2_2      | CH_LOW_FREQUENCY),
-       (CH_LAYOUT_QUAD     | CH_LOW_FREQUENCY),
-       (CH_LAYOUT_4POINT0  | CH_LOW_FREQUENCY),
-        CH_LAYOUT_5POINT1,
-        CH_LAYOUT_5POINT1_BACK,
-        0 },
-};
+
+/**
+ * Initialize the encoder.
+ */
+static av_cold int ac3_encode_init(AVCodecContext *avctx)
+{
+    AC3EncodeContext *s = avctx->priv_data;
+    int ret, frame_size_58;
+
+    avctx->frame_size = AC3_FRAME_SIZE;
+
+    ff_ac3_common_init();
+
+    ret = validate_options(avctx, s);
+    if (ret)
+        return ret;
+
+    s->bitstream_mode = avctx->audio_service_type;
+    if (s->bitstream_mode == AV_AUDIO_SERVICE_TYPE_KARAOKE)
+        s->bitstream_mode = 0x7;
+
+    s->frame_size_min  = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
+    s->bits_written    = 0;
+    s->samples_written = 0;
+    s->frame_size      = s->frame_size_min;
+
+    /* calculate crc_inv for both possible frame sizes */
+    frame_size_58 = (( s->frame_size    >> 2) + ( s->frame_size    >> 4)) << 1;
+    s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
+    if (s->bit_alloc.sr_code == 1) {
+        frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
+        s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
+    }
+
+    set_bandwidth(s);
+
+    rematrixing_init(s);
+
+    exponent_init(s);
+
+    bit_alloc_init(s);
+
+    ret = mdct_init(avctx, &s->mdct, 9);
+    if (ret)
+        goto init_fail;
+
+    ret = allocate_buffers(avctx);
+    if (ret)
+        goto init_fail;
+
+    avctx->coded_frame= avcodec_alloc_frame();
+
+    dsputil_init(&s->dsp, avctx);
+    ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
+
+    dprint_options(avctx);
+
+    return 0;
+init_fail:
+    ac3_encode_close(avctx);
+    return ret;
+}
diff --git a/libavcodec/ac3enc_fixed.c b/libavcodec/ac3enc_fixed.c
new file mode 100644
index 0000000..720d87d
--- /dev/null
+++ b/libavcodec/ac3enc_fixed.c
@@ -0,0 +1,125 @@
+/*
+ * The simplest AC-3 encoder
+ * Copyright (c) 2000 Fabrice Bellard
+ * Copyright (c) 2006-2010 Justin Ruggles <justin.ruggles at gmail.com>
+ * Copyright (c) 2006-2010 Prakash Punnoor <prakash at punnoor.de>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * fixed-point AC-3 encoder.
+ */
+
+#define CONFIG_FFT_FLOAT 0
+#undef CONFIG_AC3ENC_FLOAT
+#include "ac3enc.c"
+
+
+/**
+ * Finalize MDCT and free allocated memory.
+ */
+static av_cold void mdct_end(AC3MDCTContext *mdct)
+{
+    ff_fft_end(&mdct->fft);
+}
+
+
+/**
+ * Initialize MDCT tables.
+ * @param nbits log2(MDCT size)
+ */
+static av_cold int mdct_init(AVCodecContext *avctx, AC3MDCTContext *mdct,
+                             int nbits)
+{
+    int ret = ff_mdct_init(&mdct->fft, nbits, 0, 1.0);
+    mdct->window = ff_ac3_window;
+    return ret;
+}
+
+
+/**
+ * Apply KBD window to input samples prior to MDCT.
+ */
+static void apply_window(DSPContext *dsp, int16_t *output, const int16_t *input,
+                         const int16_t *window, unsigned int len)
+{
+    dsp->apply_window_int16(output, input, window, len);
+}
+
+
+/**
+ * Calculate the log2() of the maximum absolute value in an array.
+ * @param tab input array
+ * @param n   number of values in the array
+ * @return    log2(max(abs(tab[])))
+ */
+static int log2_tab(AC3EncodeContext *s, int16_t *src, int len)
+{
+    int v = s->ac3dsp.ac3_max_msb_abs_int16(src, len);
+    return av_log2(v);
+}
+
+
+/**
+ * Normalize the input samples to use the maximum available precision.
+ * This assumes signed 16-bit input samples.
+ *
+ * @return exponent shift
+ */
+static int normalize_samples(AC3EncodeContext *s)
+{
+    int v = 14 - log2_tab(s, s->windowed_samples, AC3_WINDOW_SIZE);
+    if (v > 0)
+        s->ac3dsp.ac3_lshift_int16(s->windowed_samples, AC3_WINDOW_SIZE, v);
+    /* +6 to right-shift from 31-bit to 25-bit */
+    return v + 6;
+}
+
+
+/**
+ * Scale MDCT coefficients to 25-bit signed fixed-point.
+ */
+static void scale_coefficients(AC3EncodeContext *s)
+{
+    int blk, ch;
+
+    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
+        AC3Block *block = &s->blocks[blk];
+        for (ch = 0; ch < s->channels; ch++) {
+            s->ac3dsp.ac3_rshift_int32(block->mdct_coef[ch], AC3_MAX_COEFS,
+                                       block->coeff_shift[ch]);
+        }
+    }
+}
+
+
+AVCodec ff_ac3_fixed_encoder = {
+    "ac3_fixed",
+    AVMEDIA_TYPE_AUDIO,
+    CODEC_ID_AC3,
+    sizeof(AC3EncodeContext),
+    ac3_encode_init,
+    ac3_encode_frame,
+    ac3_encode_close,
+    NULL,
+    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
+    .long_name = NULL_IF_CONFIG_SMALL("ATSC A/52A (AC-3)"),
+    .priv_class = &ac3enc_class,
+    .channel_layouts = ac3_channel_layouts,
+};
diff --git a/libavcodec/ac3enc_float.c b/libavcodec/ac3enc_float.c
new file mode 100644
index 0000000..d2435de
--- /dev/null
+++ b/libavcodec/ac3enc_float.c
@@ -0,0 +1,114 @@
+/*
+ * The simplest AC-3 encoder
+ * Copyright (c) 2000 Fabrice Bellard
+ * Copyright (c) 2006-2010 Justin Ruggles <justin.ruggles at gmail.com>
+ * Copyright (c) 2006-2010 Prakash Punnoor <prakash at punnoor.de>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * floating-point AC-3 encoder.
+ */
+
+#define CONFIG_AC3ENC_FLOAT 1
+#include "ac3enc.c"
+#include "kbdwin.h"
+
+
+/**
+ * Finalize MDCT and free allocated memory.
+ */
+static av_cold void mdct_end(AC3MDCTContext *mdct)
+{
+    ff_mdct_end(&mdct->fft);
+    av_freep(&mdct->window);
+}
+
+
+/**
+ * Initialize MDCT tables.
+ * @param nbits log2(MDCT size)
+ */
+static av_cold int mdct_init(AVCodecContext *avctx, AC3MDCTContext *mdct,
+                             int nbits)
+{
+    float *window;
+    int i, n, n2;
+
+    n  = 1 << nbits;
+    n2 = n >> 1;
+
+    window = av_malloc(n * sizeof(*window));
+    if (!window) {
+        av_log(avctx, AV_LOG_ERROR, "Cannot allocate memory.\n");
+        return AVERROR(ENOMEM);
+    }
+    ff_kbd_window_init(window, 5.0, n2);
+    for (i = 0; i < n2; i++)
+        window[n-1-i] = window[i];
+    mdct->window = window;
+
+    return ff_mdct_init(&mdct->fft, nbits, 0, -2.0 / n);
+}
+
+
+/**
+ * Apply KBD window to input samples prior to MDCT.
+ */
+static void apply_window(DSPContext *dsp, float *output, const float *input,
+                         const float *window, unsigned int len)
+{
+    dsp->vector_fmul(output, input, window, len);
+}
+
+
+/**
+ * Normalize the input samples to use the maximum available precision.
+ */
+static int normalize_samples(AC3EncodeContext *s)
+{
+    /* Normalization is not needed for floating-point samples, so just return 0 */
+    return 0;
+}
+
+
+/**
+ * Scale MDCT coefficients from float to 24-bit fixed-point.
+ */
+static void scale_coefficients(AC3EncodeContext *s)
+{
+    s->ac3dsp.float_to_fixed24(s->fixed_coef_buffer, s->mdct_coef_buffer,
+                               AC3_MAX_COEFS * AC3_MAX_BLOCKS * s->channels);
+}
+
+
+AVCodec ff_ac3_encoder = {
+    "ac3",
+    AVMEDIA_TYPE_AUDIO,
+    CODEC_ID_AC3,
+    sizeof(AC3EncodeContext),
+    ac3_encode_init,
+    ac3_encode_frame,
+    ac3_encode_close,
+    NULL,
+    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_FLT,AV_SAMPLE_FMT_NONE},
+    .long_name = NULL_IF_CONFIG_SMALL("ATSC A/52A (AC-3)"),
+    .priv_class = &ac3enc_class,
+    .channel_layouts = ac3_channel_layouts,
+};
diff --git a/libavcodec/ac3tab.c b/libavcodec/ac3tab.c
index 4f28fb3..6a4d8cd 100644
--- a/libavcodec/ac3tab.c
+++ b/libavcodec/ac3tab.c
@@ -2,20 +2,20 @@
  * AC-3 tables
  * copyright (c) 2001 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -24,6 +24,7 @@
  * tables taken directly from the AC-3 spec.
  */
 
+#include "libavutil/audioconvert.h"
 #include "avcodec.h"
 #include "ac3tab.h"
 
@@ -73,7 +74,7 @@ const uint16_t ff_ac3_frame_size_tab[38][3] = {
 };
 
 /**
- * Maps audio coding mode (acmod) to number of full-bandwidth channels.
+ * Map audio coding mode (acmod) to number of full-bandwidth channels.
  * from ATSC A/52 Table 5.8 Audio Coding Mode
  */
 const uint8_t ff_ac3_channels_tab[8] = {
@@ -81,17 +82,17 @@ const uint8_t ff_ac3_channels_tab[8] = {
 };
 
 /**
- * Maps audio coding mode (acmod) to channel layout mask.
+ * Map audio coding mode (acmod) to channel layout mask.
  */
 const uint16_t ff_ac3_channel_layout_tab[8] = {
-    CH_LAYOUT_STEREO,
-    CH_LAYOUT_MONO,
-    CH_LAYOUT_STEREO,
-    CH_LAYOUT_SURROUND,
-    CH_LAYOUT_2_1,
-    CH_LAYOUT_4POINT0,
-    CH_LAYOUT_2_2,
-    CH_LAYOUT_5POINT0
+    AV_CH_LAYOUT_STEREO,
+    AV_CH_LAYOUT_MONO,
+    AV_CH_LAYOUT_STEREO,
+    AV_CH_LAYOUT_SURROUND,
+    AV_CH_LAYOUT_2_1,
+    AV_CH_LAYOUT_4POINT0,
+    AV_CH_LAYOUT_2_2,
+    AV_CH_LAYOUT_5POINT0
 };
 
 #define COMMON_CHANNEL_MAP \
@@ -131,10 +132,16 @@ const uint16_t ff_ac3_bitrate_tab[19] = {
     160, 192, 224, 256, 320, 384, 448, 512, 576, 640
 };
 
+/**
+ * Table of bin locations for rematrixing bands
+ * reference: Section 7.5.2 Rematrixing : Frequency Band Definitions
+ */
+const uint8_t ff_ac3_rematrix_band_tab[5] = { 13, 25, 37, 61, 253 };
+
 /* AC-3 MDCT window */
 
 /* MDCT window */
-const int16_t ff_ac3_window[256] = {
+DECLARE_ALIGNED(16, const int16_t, ff_ac3_window)[AC3_WINDOW_SIZE/2] = {
     4,    7,   12,   16,   21,   28,   34,   42,
    51,   61,   72,   84,   97,  111,  127,  145,
   164,  184,  207,  231,  257,  285,  315,  347,
@@ -198,7 +205,7 @@ const uint8_t ff_ac3_log_add_tab[260]= {
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 };
 
-const uint16_t ff_ac3_hearing_threshold_tab[50][3]= {
+const uint16_t ff_ac3_hearing_threshold_tab[AC3_CRITICAL_BANDS][3]= {
 { 0x04d0,0x04f0,0x0580 },
 { 0x04d0,0x04f0,0x0580 },
 { 0x0440,0x0460,0x04b0 },
@@ -285,11 +292,6 @@ const uint16_t ff_ac3_fast_gain_tab[8]= {
     0x080, 0x100, 0x180, 0x200, 0x280, 0x300, 0x380, 0x400,
 };
 
-const uint8_t ff_ac3_critical_band_size_tab[50]={
-    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
-    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3,
-    3, 6, 6, 6, 6, 6, 6, 12, 12, 12, 12, 24, 24, 24, 24, 24
-};
 /**
  * Default channel map for a dependent substream defined by acmod
  */
diff --git a/libavcodec/ac3tab.h b/libavcodec/ac3tab.h
index b5c2b77..292ce0d 100644
--- a/libavcodec/ac3tab.h
+++ b/libavcodec/ac3tab.h
@@ -2,20 +2,20 @@
  * AC-3 tables
  * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -23,6 +23,13 @@
 #define AVCODEC_AC3TAB_H
 
 #include "libavutil/common.h"
+#include "ac3.h"
+
+#if CONFIG_HARDCODED_TABLES
+#   define HCONST const
+#else
+#   define HCONST
+#endif
 
 extern const uint16_t ff_ac3_frame_size_tab[38][3];
 extern const uint8_t  ff_ac3_channels_tab[8];
@@ -31,9 +38,10 @@ extern const uint8_t  ff_ac3_enc_channel_map[8][2][6];
 extern const uint8_t  ff_ac3_dec_channel_map[8][2][6];
 extern const uint16_t ff_ac3_sample_rate_tab[3];
 extern const uint16_t ff_ac3_bitrate_tab[19];
-extern const int16_t  ff_ac3_window[256];
+extern const uint8_t  ff_ac3_rematrix_band_tab[5];
+extern const int16_t  ff_ac3_window[AC3_WINDOW_SIZE/2];
 extern const uint8_t  ff_ac3_log_add_tab[260];
-extern const uint16_t ff_ac3_hearing_threshold_tab[50][3];
+extern const uint16_t ff_ac3_hearing_threshold_tab[AC3_CRITICAL_BANDS][3];
 extern const uint8_t  ff_ac3_bap_tab[64];
 extern const uint8_t  ff_ac3_slow_decay_tab[4];
 extern const uint8_t  ff_ac3_fast_decay_tab[4];
@@ -41,8 +49,9 @@ extern const uint16_t ff_ac3_slow_gain_tab[4];
 extern const uint16_t ff_ac3_db_per_bit_tab[4];
 extern const int16_t  ff_ac3_floor_tab[8];
 extern const uint16_t ff_ac3_fast_gain_tab[8];
-extern const uint8_t  ff_ac3_critical_band_size_tab[50];
 extern const uint16_t ff_eac3_default_chmap[8];
+extern const uint8_t  ff_ac3_band_start_tab[AC3_CRITICAL_BANDS+1];
+extern HCONST uint8_t ff_ac3_bin_to_band_tab[253];
 
 /** Custom channel map locations bitmask
  *  Other channels described in documentation:
diff --git a/libavcodec/acelp_filters.c b/libavcodec/acelp_filters.c
index 31f0e86..04f6d4a 100644
--- a/libavcodec/acelp_filters.c
+++ b/libavcodec/acelp_filters.c
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2008 Vladimir Voroshilov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/acelp_filters.h b/libavcodec/acelp_filters.h
index 09b5da4..b8715d2 100644
--- a/libavcodec/acelp_filters.h
+++ b/libavcodec/acelp_filters.h
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2008 Vladimir Voroshilov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -38,7 +38,7 @@ extern const int16_t ff_acelp_interp_filter[61];
 
 /**
  * Generic FIR interpolation routine.
- * @param out [out] buffer for interpolated data
+ * @param[out] out buffer for interpolated data
  * @param in input data
  * @param filter_coeffs interpolation filter coefficients (0.15)
  * @param precision sub sample factor, that is the precision of the position
@@ -65,8 +65,8 @@ void ff_acelp_interpolatef(float *out, const float *in,
 
 /**
  * high-pass filtering and upscaling (4.2.5 of G.729).
- * @param out [out] output buffer for filtered speech data
- * @param hpf_f [in/out] past filtered data from previous (2 items long)
+ * @param[out]     out   output buffer for filtered speech data
+ * @param[in,out]  hpf_f past filtered data from previous (2 items long)
  *                       frames (-0x20000000 <= (14.13) < 0x20000000)
  * @param in speech data to process
  * @param length input data size
diff --git a/libavcodec/acelp_pitch_delay.c b/libavcodec/acelp_pitch_delay.c
index cddf726..4e44bc9 100644
--- a/libavcodec/acelp_pitch_delay.c
+++ b/libavcodec/acelp_pitch_delay.c
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2008 Vladimir Voroshilov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/acelp_pitch_delay.h b/libavcodec/acelp_pitch_delay.h
index 2413145..6d182bb 100644
--- a/libavcodec/acelp_pitch_delay.h
+++ b/libavcodec/acelp_pitch_delay.h
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2008 Vladimir Voroshilov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -54,8 +54,8 @@ int ff_acelp_decode_8bit_to_1st_delay3(int ac_index);
  * Pitch delay is coded:
  *    with 1/3 resolution, -6 < pitch_delay - int(prev_pitch_delay) < 5
  *
- * \remark The routine is used in G.729 @8k, AMR @10.2k, AMR @7.95k,
- *         AMR @7.4k for the second subframe.
+ * \remark The routine is used in G.729 @@8k, AMR @@10.2k, AMR @@7.95k,
+ *         AMR @@7.4k for the second subframe.
  */
 int ff_acelp_decode_5_6_bit_to_2nd_delay3(
         int ac_index,
@@ -74,8 +74,8 @@ int ff_acelp_decode_5_6_bit_to_2nd_delay3(
  *    with 1/3 resolution,    -2  < pitch_delay - int(prev_pitch_delay) <  1
  *    integers only,           1 <= pitch_delay - int(prev_pitch_delay) <  5
  *
- * \remark The routine is used in G.729 @6.4k, AMR @6.7k, AMR @5.9k,
- *         AMR @5.15k, AMR @4.75k for the second subframe.
+ * \remark The routine is used in G.729 @@6.4k, AMR @@6.7k, AMR @@5.9k,
+ *         AMR @@5.15k, AMR @@4.75k for the second subframe.
  */
 int ff_acelp_decode_4bit_to_2nd_delay3(
         int ac_index,
@@ -85,8 +85,6 @@ int ff_acelp_decode_4bit_to_2nd_delay3(
  * \brief Decode pitch delay of the first subframe encoded by 9 bits
  *        with 1/6 precision.
  * \param ac_index adaptive codebook index (9 bits)
- * \param pitch_delay_min lower bound (integer) of pitch delay interval for
- *                      second subframe
  *
  * \return pitch delay in 1/6 units
  *
@@ -94,7 +92,7 @@ int ff_acelp_decode_4bit_to_2nd_delay3(
  *    with 1/6 resolution,  17  < pitch_delay <  95
  *    integers only,        95 <= pitch_delay <= 143
  *
- * \remark The routine is used in AMR @12.2k for the first and third subframes.
+ * \remark The routine is used in AMR @@12.2k for the first and third subframes.
  */
 int ff_acelp_decode_9bit_to_1st_delay6(int ac_index);
 
@@ -110,7 +108,7 @@ int ff_acelp_decode_9bit_to_1st_delay6(int ac_index);
  * Pitch delay is coded:
  *    with 1/6 resolution, -6 < pitch_delay - int(prev_pitch_delay) < 5
  *
- * \remark The routine is used in AMR @12.2k for the second and fourth subframes.
+ * \remark The routine is used in AMR @@12.2k for the second and fourth subframes.
  */
 int ff_acelp_decode_6bit_to_2nd_delay6(
         int ac_index,
@@ -118,7 +116,7 @@ int ff_acelp_decode_6bit_to_2nd_delay6(
 
 /**
  * \brief Update past quantized energies
- * \param quant_energy [in/out] past quantized energies (5.10)
+ * \param[in,out]  quant_energy  past quantized energies (5.10)
  * \param gain_corr_factor gain correction factor
  * \param log2_ma_pred_order log2() of MA prediction order
  * \param erasure frame erasure flag
@@ -145,9 +143,8 @@ void ff_acelp_update_past_gain(
  * \param gain_corr_factor gain correction factor (2.13)
  * \param fc_v fixed-codebook vector (2.13)
  * \param mr_energy mean innovation energy and fixed-point correction (7.13)
- * \param quant_energy [in/out] past quantized energies (5.10)
+ * \param[in,out]  quant_energy  past quantized energies (5.10)
  * \param subframe_size length of subframe
- * \param ma_pred_order MA prediction order
  *
  * \return quantized fixed-codebook gain (14.1)
  *
@@ -224,7 +221,7 @@ int16_t ff_acelp_decode_gain_code(
  * Calculate fixed gain (part of section 6.1.3 of AMR spec)
  *
  * @param fixed_gain_factor gain correction factor
- * @param fixed_energy decoded algebraic codebook vector energy
+ * @param fixed_mean_energy mean decoded algebraic codebook vector energy
  * @param prediction_error vector of the quantified predictor errors of
  *        the four previous subframes. It is updated by this function.
  * @param energy_mean desired mean innovation energy
diff --git a/libavcodec/acelp_vectors.c b/libavcodec/acelp_vectors.c
index e41e5fa..8e59e4b 100644
--- a/libavcodec/acelp_vectors.c
+++ b/libavcodec/acelp_vectors.c
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2008 Vladimir Voroshilov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/acelp_vectors.h b/libavcodec/acelp_vectors.h
index ba3437f..07d1000 100644
--- a/libavcodec/acelp_vectors.h
+++ b/libavcodec/acelp_vectors.h
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2008 Vladimir Voroshilov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -47,7 +47,7 @@ typedef struct {
  *
  * Table contains only first the pulse indexes.
  *
- * Used in G.729 @8k, G.729 @4.4k, AMR @7.95k, AMR @7.40k
+ * Used in G.729 @@8k, G.729 @@4.4k, AMR @@7.95k, AMR @@7.40k
  */
 extern const uint8_t ff_fc_4pulses_8bits_tracks_13[16];
 
@@ -60,7 +60,7 @@ extern const uint8_t ff_fc_4pulses_8bits_tracks_13[16];
  *
  * @remark Track in the table should be read top-to-bottom, left-to-right.
  *
- * Used in G.729 @8k, G.729 @4.4k, AMR @7.95k, AMR @7.40k
+ * Used in G.729 @@8k, G.729 @@4.4k, AMR @@7.95k, AMR @@7.40k
  */
 extern const uint8_t ff_fc_4pulses_8bits_track_4[32];
 
@@ -76,7 +76,7 @@ extern const uint8_t ff_fc_4pulses_8bits_track_4[32];
  * @note (EE) Reference G.729D code also uses gray decoding for each
  *            pulse index before looking up the value in the table.
  *
- * Used in G.729 @6.4k (with gray coding), AMR @5.9k (without gray coding)
+ * Used in G.729 @@6.4k (with gray coding), AMR @@5.9k (without gray coding)
  */
 extern const uint8_t ff_fc_2pulses_9bits_track1[16];
 extern const uint8_t ff_fc_2pulses_9bits_track1_gray[16];
@@ -108,7 +108,7 @@ extern const uint8_t ff_fc_2pulses_9bits_track1_gray[16];
  * @note (EE.2) Reference G.729D code also uses gray decoding for each
  *              pulse index before looking up the value in the table.
  *
- * Used in G.729 @6.4k (with gray coding)
+ * Used in G.729 @@6.4k (with gray coding)
  */
 extern const uint8_t ff_fc_2pulses_9bits_track2_gray[32];
 
@@ -134,7 +134,7 @@ extern const float ff_pow_0_55[10];
 
 /**
  * Decode fixed-codebook vector (3.8 and D.5.8 of G.729, 5.7.1 of AMR).
- * @param fc_v [out] decoded fixed codebook vector (2.13)
+ * @param[out] fc_v decoded fixed codebook vector (2.13)
  * @param tab1 table used for first pulse_count pulses
  * @param tab2 table used for last pulse
  * @param pulse_indexes fixed codebook indexes
@@ -144,7 +144,7 @@ extern const float ff_pow_0_55[10];
  * @param pulse_count number of pulses decoded using first table
  * @param bits length of one pulse index in bits
  *
- * Used in G.729 @8k, G.729 @4.4k, G.729 @6.4k, AMR @7.95k, AMR @7.40k
+ * Used in G.729 @@8k, G.729 @@4.4k, G.729 @@6.4k, AMR @@7.95k, AMR @@7.40k
  */
 void ff_acelp_fc_pulse_per_track(int16_t* fc_v,
                                  const uint8_t *tab1,
@@ -174,7 +174,7 @@ void ff_decode_10_pulses_35bits(const int16_t *fixed_index,
 
 /**
  * weighted sum of two vectors with rounding.
- * @param out [out] result of addition
+ * @param[out] out result of addition
  * @param in_a first vector
  * @param in_b second vector
  * @param weight_coeff_a first vector weight coefficient
@@ -198,7 +198,7 @@ void ff_acelp_weighted_vector_sum(int16_t* out,
 
 /**
  * float implementation of weighted sum of two vectors.
- * @param out [out] result of addition
+ * @param[out] out result of addition
  * @param in_a first vector
  * @param in_b second vector
  * @param weight_coeff_a first vector weight coefficient
diff --git a/libavcodec/adpcm.c b/libavcodec/adpcm.c
index 68bd656..70a5360 100644
--- a/libavcodec/adpcm.c
+++ b/libavcodec/adpcm.c
@@ -2,20 +2,20 @@
  * ADPCM codecs
  * Copyright (c) 2001-2003 The ffmpeg Project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #include "avcodec.h"
@@ -145,15 +145,35 @@ typedef struct ADPCMChannelStatus {
     int idelta;
 } ADPCMChannelStatus;
 
+typedef struct TrellisPath {
+    int nibble;
+    int prev;
+} TrellisPath;
+
+typedef struct TrellisNode {
+    uint32_t ssd;
+    int path;
+    int sample1;
+    int sample2;
+    int step;
+} TrellisNode;
+
 typedef struct ADPCMContext {
     ADPCMChannelStatus status[6];
+    TrellisPath *paths;
+    TrellisNode *node_buf;
+    TrellisNode **nodep_buf;
+    uint8_t *trellis_hash;
 } ADPCMContext;
 
+#define FREEZE_INTERVAL 128
+
 /* XXX: implement encoding */
 
 #if CONFIG_ENCODERS
 static av_cold int adpcm_encode_init(AVCodecContext *avctx)
 {
+    ADPCMContext *s = avctx->priv_data;
     uint8_t *extradata;
     int i;
     if (avctx->channels > 2)
@@ -164,6 +184,15 @@ static av_cold int adpcm_encode_init(AVCodecContext *avctx)
         return -1;
     }
 
+    if (avctx->trellis) {
+        int frontier = 1 << avctx->trellis;
+        int max_paths =  frontier * FREEZE_INTERVAL;
+        FF_ALLOC_OR_GOTO(avctx, s->paths,     max_paths * sizeof(*s->paths), error);
+        FF_ALLOC_OR_GOTO(avctx, s->node_buf,  2 * frontier * sizeof(*s->node_buf), error);
+        FF_ALLOC_OR_GOTO(avctx, s->nodep_buf, 2 * frontier * sizeof(*s->nodep_buf), error);
+        FF_ALLOC_OR_GOTO(avctx, s->trellis_hash, 65536 * sizeof(*s->trellis_hash), error);
+    }
+
     switch(avctx->codec->id) {
     case CODEC_ID_ADPCM_IMA_WAV:
         avctx->frame_size = (BLKSIZE - 4 * avctx->channels) * 8 / (4 * avctx->channels) + 1; /* each 16 bits sample gives one nibble */
@@ -199,23 +228,34 @@ static av_cold int adpcm_encode_init(AVCodecContext *avctx)
             avctx->sample_rate != 22050 &&
             avctx->sample_rate != 44100) {
             av_log(avctx, AV_LOG_ERROR, "Sample rate must be 11025, 22050 or 44100\n");
-            return -1;
+            goto error;
         }
         avctx->frame_size = 512 * (avctx->sample_rate / 11025);
         break;
     default:
-        return -1;
+        goto error;
     }
 
     avctx->coded_frame= avcodec_alloc_frame();
     avctx->coded_frame->key_frame= 1;
 
     return 0;
+error:
+    av_freep(&s->paths);
+    av_freep(&s->node_buf);
+    av_freep(&s->nodep_buf);
+    av_freep(&s->trellis_hash);
+    return -1;
 }
 
 static av_cold int adpcm_encode_close(AVCodecContext *avctx)
 {
+    ADPCMContext *s = avctx->priv_data;
     av_freep(&avctx->coded_frame);
+    av_freep(&s->paths);
+    av_freep(&s->node_buf);
+    av_freep(&s->nodep_buf);
+    av_freep(&s->trellis_hash);
 
     return 0;
 }
@@ -276,39 +316,25 @@ static inline unsigned char adpcm_yamaha_compress_sample(ADPCMChannelStatus *c,
     return nibble;
 }
 
-typedef struct TrellisPath {
-    int nibble;
-    int prev;
-} TrellisPath;
-
-typedef struct TrellisNode {
-    uint32_t ssd;
-    int path;
-    int sample1;
-    int sample2;
-    int step;
-} TrellisNode;
-
 static void adpcm_compress_trellis(AVCodecContext *avctx, const short *samples,
                                    uint8_t *dst, ADPCMChannelStatus *c, int n)
 {
-#define FREEZE_INTERVAL 128
     //FIXME 6% faster if frontier is a compile-time constant
+    ADPCMContext *s = avctx->priv_data;
     const int frontier = 1 << avctx->trellis;
     const int stride = avctx->channels;
     const int version = avctx->codec->id;
-    const int max_paths = frontier*FREEZE_INTERVAL;
-    TrellisPath paths[max_paths], *p;
-    TrellisNode node_buf[2][frontier];
-    TrellisNode *nodep_buf[2][frontier];
-    TrellisNode **nodes = nodep_buf[0]; // nodes[] is always sorted by .ssd
-    TrellisNode **nodes_next = nodep_buf[1];
-    int pathn = 0, froze = -1, i, j, k;
-
-    assert(!(max_paths&(max_paths-1)));
-
-    memset(nodep_buf, 0, sizeof(nodep_buf));
-    nodes[0] = &node_buf[1][0];
+    TrellisPath *paths = s->paths, *p;
+    TrellisNode *node_buf = s->node_buf;
+    TrellisNode **nodep_buf = s->nodep_buf;
+    TrellisNode **nodes = nodep_buf; // nodes[] is always sorted by .ssd
+    TrellisNode **nodes_next = nodep_buf + frontier;
+    int pathn = 0, froze = -1, i, j, k, generation = 0;
+    uint8_t *hash = s->trellis_hash;
+    memset(hash, 0xff, 65536 * sizeof(*hash));
+
+    memset(nodep_buf, 0, 2 * frontier * sizeof(*nodep_buf));
+    nodes[0] = node_buf + frontier;
     nodes[0]->ssd = 0;
     nodes[0]->path = 0;
     nodes[0]->step = c->step_index;
@@ -329,12 +355,13 @@ static void adpcm_compress_trellis(AVCodecContext *avctx, const short *samples,
     }
 
     for(i=0; i<n; i++) {
-        TrellisNode *t = node_buf[i&1];
+        TrellisNode *t = node_buf + frontier*(i&1);
         TrellisNode **u;
         int sample = samples[i*stride];
+        int heap_pos = 0;
         memset(nodes_next, 0, frontier*sizeof(TrellisNode*));
         for(j=0; j<frontier && nodes[j]; j++) {
-            // higher j have higher ssd already, so they're unlikely to use a suboptimal next sample too
+            // higher j have higher ssd already, so they're likely to yield a suboptimal next sample too
             const int range = (j < frontier/2) ? 1 : 0;
             const int step = nodes[j]->step;
             int nidx;
@@ -349,38 +376,64 @@ static void adpcm_compress_trellis(AVCodecContext *avctx, const short *samples,
 #define STORE_NODE(NAME, STEP_INDEX)\
                     int d;\
                     uint32_t ssd;\
+                    int pos;\
+                    TrellisNode *u;\
+                    uint8_t *h;\
                     dec_sample = av_clip_int16(dec_sample);\
                     d = sample - dec_sample;\
                     ssd = nodes[j]->ssd + d*d;\
-                    if(nodes_next[frontier-1] && ssd >= nodes_next[frontier-1]->ssd)\
-                        continue;\
+                    /* Check for wraparound, skip such samples completely. \
+                     * Note, changing ssd to a 64 bit variable would be \
+                     * simpler, avoiding this check, but it's slower on \
+                     * x86 32 bit at the moment. */\
+                    if (ssd < nodes[j]->ssd)\
+                        goto next_##NAME;\
                     /* Collapse any two states with the same previous sample value. \
                      * One could also distinguish states by step and by 2nd to last
-                     * sample, but the effects of that are negligible. */\
-                    for(k=0; k<frontier && nodes_next[k]; k++) {\
-                        if(dec_sample == nodes_next[k]->sample1) {\
-                            assert(ssd >= nodes_next[k]->ssd);\
+                     * sample, but the effects of that are negligible.
+                     * Since nodes in the previous generation are iterated
+                     * through a heap, they're roughly ordered from better to
+                     * worse, but not strictly ordered. Therefore, an earlier
+                     * node with the same sample value is better in most cases
+                     * (and thus the current is skipped), but not strictly
+                     * in all cases. Only skipping samples where ssd >=
+                     * ssd of the earlier node with the same sample gives
+                     * slightly worse quality, though, for some reason. */ \
+                    h = &hash[(uint16_t) dec_sample];\
+                    if (*h == generation)\
+                        goto next_##NAME;\
+                    if (heap_pos < frontier) {\
+                        pos = heap_pos++;\
+                    } else {\
+                        /* Try to replace one of the leaf nodes with the new \
+                         * one, but try a different slot each time. */\
+                        pos = (frontier >> 1) + (heap_pos & ((frontier >> 1) - 1));\
+                        if (ssd > nodes_next[pos]->ssd)\
                             goto next_##NAME;\
-                        }\
+                        heap_pos++;\
+                    }\
+                    *h = generation;\
+                    u = nodes_next[pos];\
+                    if(!u) {\
+                        assert(pathn < FREEZE_INTERVAL<<avctx->trellis);\
+                        u = t++;\
+                        nodes_next[pos] = u;\
+                        u->path = pathn++;\
                     }\
-                    for(k=0; k<frontier; k++) {\
-                        if(!nodes_next[k] || ssd < nodes_next[k]->ssd) {\
-                            TrellisNode *u = nodes_next[frontier-1];\
-                            if(!u) {\
-                                assert(pathn < max_paths);\
-                                u = t++;\
-                                u->path = pathn++;\
-                            }\
-                            u->ssd = ssd;\
-                            u->step = STEP_INDEX;\
-                            u->sample2 = nodes[j]->sample1;\
-                            u->sample1 = dec_sample;\
-                            paths[u->path].nibble = nibble;\
-                            paths[u->path].prev = nodes[j]->path;\
-                            memmove(&nodes_next[k+1], &nodes_next[k], (frontier-k-1)*sizeof(TrellisNode*));\
-                            nodes_next[k] = u;\
+                    u->ssd = ssd;\
+                    u->step = STEP_INDEX;\
+                    u->sample2 = nodes[j]->sample1;\
+                    u->sample1 = dec_sample;\
+                    paths[u->path].nibble = nibble;\
+                    paths[u->path].prev = nodes[j]->path;\
+                    /* Sift the newly inserted node up in the heap to \
+                     * restore the heap property. */\
+                    while (pos > 0) {\
+                        int parent = (pos - 1) >> 1;\
+                        if (nodes_next[parent]->ssd <= ssd)\
                             break;\
-                        }\
+                        FFSWAP(TrellisNode*, nodes_next[parent], nodes_next[pos]);\
+                        pos = parent;\
                     }\
                     next_##NAME:;
                     STORE_NODE(ms, FFMAX(16, (AdaptationTable[nibble] * step) >> 8));
@@ -410,6 +463,12 @@ static void adpcm_compress_trellis(AVCodecContext *avctx, const short *samples,
         nodes = nodes_next;
         nodes_next = u;
 
+        generation++;
+        if (generation == 255) {
+            memset(hash, 0xff, 65536 * sizeof(*hash));
+            generation = 0;
+        }
+
         // prevent overflow
         if(nodes[0]->ssd > (1<<28)) {
             for(j=1; j<frontier && nodes[j]; j++)
@@ -454,6 +513,7 @@ static int adpcm_encode_frame(AVCodecContext *avctx,
     short *samples;
     unsigned char *dst;
     ADPCMContext *c = avctx->priv_data;
+    uint8_t *buf;
 
     dst = frame;
     samples = (short *)data;
@@ -480,22 +540,24 @@ static int adpcm_encode_frame(AVCodecContext *avctx,
 
             /* stereo: 4 bytes (8 samples) for left, 4 bytes for right, 4 bytes left, ... */
             if(avctx->trellis > 0) {
-                uint8_t buf[2][n*8];
-                adpcm_compress_trellis(avctx, samples, buf[0], &c->status[0], n*8);
+                FF_ALLOC_OR_GOTO(avctx, buf, 2*n*8, error);
+                adpcm_compress_trellis(avctx, samples, buf, &c->status[0], n*8);
                 if(avctx->channels == 2)
-                    adpcm_compress_trellis(avctx, samples+1, buf[1], &c->status[1], n*8);
+                    adpcm_compress_trellis(avctx, samples+1, buf + n*8, &c->status[1], n*8);
                 for(i=0; i<n; i++) {
-                    *dst++ = buf[0][8*i+0] | (buf[0][8*i+1] << 4);
-                    *dst++ = buf[0][8*i+2] | (buf[0][8*i+3] << 4);
-                    *dst++ = buf[0][8*i+4] | (buf[0][8*i+5] << 4);
-                    *dst++ = buf[0][8*i+6] | (buf[0][8*i+7] << 4);
+                    *dst++ = buf[8*i+0] | (buf[8*i+1] << 4);
+                    *dst++ = buf[8*i+2] | (buf[8*i+3] << 4);
+                    *dst++ = buf[8*i+4] | (buf[8*i+5] << 4);
+                    *dst++ = buf[8*i+6] | (buf[8*i+7] << 4);
                     if (avctx->channels == 2) {
-                        *dst++ = buf[1][8*i+0] | (buf[1][8*i+1] << 4);
-                        *dst++ = buf[1][8*i+2] | (buf[1][8*i+3] << 4);
-                        *dst++ = buf[1][8*i+4] | (buf[1][8*i+5] << 4);
-                        *dst++ = buf[1][8*i+6] | (buf[1][8*i+7] << 4);
+                        uint8_t *buf1 = buf + n*8;
+                        *dst++ = buf1[8*i+0] | (buf1[8*i+1] << 4);
+                        *dst++ = buf1[8*i+2] | (buf1[8*i+3] << 4);
+                        *dst++ = buf1[8*i+4] | (buf1[8*i+5] << 4);
+                        *dst++ = buf1[8*i+6] | (buf1[8*i+7] << 4);
                     }
                 }
+                av_free(buf);
             } else
             for (; n>0; n--) {
                 *dst = adpcm_ima_compress_sample(&c->status[0], samples[0]);
@@ -555,6 +617,7 @@ static int adpcm_encode_frame(AVCodecContext *avctx,
             }
         }
 
+        flush_put_bits(&pb);
         dst += put_bits_count(&pb)>>3;
         break;
     }
@@ -578,15 +641,16 @@ static int adpcm_encode_frame(AVCodecContext *avctx,
         }
 
         if(avctx->trellis > 0) {
-            uint8_t buf[2][n];
-            adpcm_compress_trellis(avctx, samples+2, buf[0], &c->status[0], n);
+            FF_ALLOC_OR_GOTO(avctx, buf, 2*n, error);
+            adpcm_compress_trellis(avctx, samples+2, buf, &c->status[0], n);
             if (avctx->channels == 2)
-                adpcm_compress_trellis(avctx, samples+3, buf[1], &c->status[1], n);
+                adpcm_compress_trellis(avctx, samples+3, buf+n, &c->status[1], n);
             for(i=0; i<n; i++) {
-                put_bits(&pb, 4, buf[0][i]);
+                put_bits(&pb, 4, buf[i]);
                 if (avctx->channels == 2)
-                    put_bits(&pb, 4, buf[1][i]);
+                    put_bits(&pb, 4, buf[n+i]);
             }
+            av_free(buf);
         } else {
             for (i=1; i<avctx->frame_size; i++) {
                 put_bits(&pb, 4, adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels*i]));
@@ -625,18 +689,18 @@ static int adpcm_encode_frame(AVCodecContext *avctx,
 
         if(avctx->trellis > 0) {
             int n = avctx->block_align - 7*avctx->channels;
-            uint8_t buf[2][n];
+            FF_ALLOC_OR_GOTO(avctx, buf, 2*n, error);
             if(avctx->channels == 1) {
-                n *= 2;
-                adpcm_compress_trellis(avctx, samples, buf[0], &c->status[0], n);
+                adpcm_compress_trellis(avctx, samples, buf, &c->status[0], n);
                 for(i=0; i<n; i+=2)
-                    *dst++ = (buf[0][i] << 4) | buf[0][i+1];
+                    *dst++ = (buf[i] << 4) | buf[i+1];
             } else {
-                adpcm_compress_trellis(avctx, samples, buf[0], &c->status[0], n);
-                adpcm_compress_trellis(avctx, samples+1, buf[1], &c->status[1], n);
+                adpcm_compress_trellis(avctx, samples, buf, &c->status[0], n);
+                adpcm_compress_trellis(avctx, samples+1, buf+n, &c->status[1], n);
                 for(i=0; i<n; i++)
-                    *dst++ = (buf[0][i] << 4) | buf[1][i];
+                    *dst++ = (buf[i] << 4) | buf[n+i];
             }
+            av_free(buf);
         } else
         for(i=7*avctx->channels; i<avctx->block_align; i++) {
             int nibble;
@@ -648,18 +712,19 @@ static int adpcm_encode_frame(AVCodecContext *avctx,
     case CODEC_ID_ADPCM_YAMAHA:
         n = avctx->frame_size / 2;
         if(avctx->trellis > 0) {
-            uint8_t buf[2][n*2];
+            FF_ALLOC_OR_GOTO(avctx, buf, 2*n*2, error);
             n *= 2;
             if(avctx->channels == 1) {
-                adpcm_compress_trellis(avctx, samples, buf[0], &c->status[0], n);
+                adpcm_compress_trellis(avctx, samples, buf, &c->status[0], n);
                 for(i=0; i<n; i+=2)
-                    *dst++ = buf[0][i] | (buf[0][i+1] << 4);
+                    *dst++ = buf[i] | (buf[i+1] << 4);
             } else {
-                adpcm_compress_trellis(avctx, samples, buf[0], &c->status[0], n);
-                adpcm_compress_trellis(avctx, samples+1, buf[1], &c->status[1], n);
+                adpcm_compress_trellis(avctx, samples, buf, &c->status[0], n);
+                adpcm_compress_trellis(avctx, samples+1, buf+n, &c->status[1], n);
                 for(i=0; i<n; i++)
-                    *dst++ = buf[0][i] | (buf[1][i] << 4);
+                    *dst++ = buf[i] | (buf[n+i] << 4);
             }
+            av_free(buf);
         } else
             for (n *= avctx->channels; n>0; n--) {
                 int nibble;
@@ -669,6 +734,7 @@ static int adpcm_encode_frame(AVCodecContext *avctx,
             }
         break;
     default:
+    error:
         return -1;
     }
     return dst - frame;
@@ -695,6 +761,12 @@ static av_cold int adpcm_decode_init(AVCodecContext * avctx)
     case CODEC_ID_ADPCM_CT:
         c->status[0].step = c->status[1].step = 511;
         break;
+    case CODEC_ID_ADPCM_IMA_WAV:
+        if (avctx->bits_per_coded_sample != 4) {
+            av_log(avctx, AV_LOG_ERROR, "Only 4-bit ADPCM IMA WAV files are supported\n");
+            return -1;
+        }
+        break;
     case CODEC_ID_ADPCM_IMA_WS:
         if (avctx->extradata && avctx->extradata_size == 2 * 4) {
             c->status[0].predictor = AV_RL32(avctx->extradata);
@@ -704,7 +776,7 @@ static av_cold int adpcm_decode_init(AVCodecContext * avctx)
     default:
         break;
     }
-    avctx->sample_fmt = SAMPLE_FMT_S16;
+    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
     return 0;
 }
 
@@ -1636,7 +1708,7 @@ static int adpcm_decode_frame(AVCodecContext *avctx,
 
 #if CONFIG_ENCODERS
 #define ADPCM_ENCODER(id,name,long_name_)       \
-AVCodec name ## _encoder = {                    \
+AVCodec ff_ ## name ## _encoder = {             \
     #name,                                      \
     AVMEDIA_TYPE_AUDIO,                         \
     id,                                         \
@@ -1645,16 +1717,16 @@ AVCodec name ## _encoder = {                    \
     adpcm_encode_frame,                         \
     adpcm_encode_close,                         \
     NULL,                                       \
-    .sample_fmts = (const enum SampleFormat[]){SAMPLE_FMT_S16,SAMPLE_FMT_NONE}, \
+    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE}, \
     .long_name = NULL_IF_CONFIG_SMALL(long_name_), \
-};
+}
 #else
 #define ADPCM_ENCODER(id,name,long_name_)
 #endif
 
 #if CONFIG_DECODERS
 #define ADPCM_DECODER(id,name,long_name_)       \
-AVCodec name ## _decoder = {                    \
+AVCodec ff_ ## name ## _decoder = {             \
     #name,                                      \
     AVMEDIA_TYPE_AUDIO,                         \
     id,                                         \
@@ -1664,13 +1736,13 @@ AVCodec name ## _decoder = {                    \
     NULL,                                       \
     adpcm_decode_frame,                         \
     .long_name = NULL_IF_CONFIG_SMALL(long_name_), \
-};
+}
 #else
 #define ADPCM_DECODER(id,name,long_name_)
 #endif
 
 #define ADPCM_CODEC(id,name,long_name_)         \
-    ADPCM_ENCODER(id,name,long_name_) ADPCM_DECODER(id,name,long_name_)
+    ADPCM_ENCODER(id,name,long_name_); ADPCM_DECODER(id,name,long_name_)
 
 /* Note: Do not forget to add new entries to the Makefile as well. */
 ADPCM_DECODER(CODEC_ID_ADPCM_4XM, adpcm_4xm, "ADPCM 4X Movie");
diff --git a/libavcodec/adx.h b/libavcodec/adx.h
index 0fa1003..c420696 100644
--- a/libavcodec/adx.h
+++ b/libavcodec/adx.h
@@ -2,20 +2,20 @@
  * ADX ADPCM codecs
  * Copyright (c) 2001,2003 BERO
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/adxdec.c b/libavcodec/adxdec.c
index adb22fc..48acc65 100644
--- a/libavcodec/adxdec.c
+++ b/libavcodec/adxdec.c
@@ -2,20 +2,20 @@
  * ADX ADPCM codecs
  * Copyright (c) 2001,2003 BERO
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -34,7 +34,7 @@
 
 static av_cold int adx_decode_init(AVCodecContext *avctx)
 {
-    avctx->sample_fmt = SAMPLE_FMT_S16;
+    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
     return 0;
 }
 
@@ -166,7 +166,7 @@ static int adx_decode_frame(AVCodecContext *avctx,
     return buf-buf0;
 }
 
-AVCodec adpcm_adx_decoder = {
+AVCodec ff_adpcm_adx_decoder = {
     "adpcm_adx",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_ADPCM_ADX,
diff --git a/libavcodec/adxenc.c b/libavcodec/adxenc.c
index 116b746..b0847f4 100644
--- a/libavcodec/adxenc.c
+++ b/libavcodec/adxenc.c
@@ -2,20 +2,20 @@
  * ADX ADPCM codecs
  * Copyright (c) 2001,2003 BERO
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -183,7 +183,7 @@ static int adx_encode_frame(AVCodecContext *avctx,
     return dst-frame;
 }
 
-AVCodec adpcm_adx_encoder = {
+AVCodec ff_adpcm_adx_encoder = {
     "adpcm_adx",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_ADPCM_ADX,
@@ -192,6 +192,6 @@ AVCodec adpcm_adx_encoder = {
     adx_encode_frame,
     adx_encode_close,
     NULL,
-    .sample_fmts = (const enum SampleFormat[]){SAMPLE_FMT_S16,SAMPLE_FMT_NONE},
+    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
     .long_name = NULL_IF_CONFIG_SMALL("SEGA CRI ADX ADPCM"),
 };
diff --git a/libavcodec/alac.c b/libavcodec/alac.c
index 50fc7a1..4ea3f7e 100644
--- a/libavcodec/alac.c
+++ b/libavcodec/alac.c
@@ -2,20 +2,20 @@
  * ALAC (Apple Lossless Audio Codec) decoder
  * Copyright (c) 2005 David Hammerton
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -65,9 +65,6 @@ typedef struct {
 
     AVCodecContext *avctx;
     GetBitContext gb;
-    /* init to 0; first frame decode should initialize from extradata and
-     * set this to 1 */
-    int context_initialized;
 
     int numchannels;
     int bytespersample;
@@ -471,21 +468,7 @@ static int alac_decode_frame(AVCodecContext *avctx,
 
     /* short-circuit null buffers */
     if (!inbuffer || !input_buffer_size)
-        return input_buffer_size;
-
-    /* initialize from the extradata */
-    if (!alac->context_initialized) {
-        if (alac->avctx->extradata_size != ALAC_EXTRADATA_SIZE) {
-            av_log(avctx, AV_LOG_ERROR, "alac: expected %d extradata bytes\n",
-                ALAC_EXTRADATA_SIZE);
-            return input_buffer_size;
-        }
-        if (alac_set_info(alac)) {
-            av_log(avctx, AV_LOG_ERROR, "alac: set_info failed\n");
-            return input_buffer_size;
-        }
-        alac->context_initialized = 1;
-    }
+        return -1;
 
     init_get_bits(&alac->gb, inbuffer, input_buffer_size * 8);
 
@@ -493,7 +476,7 @@ static int alac_decode_frame(AVCodecContext *avctx,
     if (channels > MAX_CHANNELS) {
         av_log(avctx, AV_LOG_ERROR, "channels > %d not supported\n",
                MAX_CHANNELS);
-        return input_buffer_size;
+        return -1;
     }
 
     /* 2^result = something to do with output waiting.
@@ -522,10 +505,10 @@ static int alac_decode_frame(AVCodecContext *avctx,
         outputsamples = alac->setinfo_max_samples_per_frame;
 
     switch (alac->setinfo_sample_size) {
-    case 16: avctx->sample_fmt    = SAMPLE_FMT_S16;
+    case 16: avctx->sample_fmt    = AV_SAMPLE_FMT_S16;
              alac->bytespersample = channels << 1;
              break;
-    case 24: avctx->sample_fmt    = SAMPLE_FMT_S32;
+    case 24: avctx->sample_fmt    = AV_SAMPLE_FMT_S32;
              alac->bytespersample = channels << 2;
              break;
     default: av_log(avctx, AV_LOG_ERROR, "Sample depth %d is not supported.\n",
@@ -547,11 +530,11 @@ static int alac_decode_frame(AVCodecContext *avctx,
 
     if (!isnotcompressed) {
         /* so it is compressed */
-        int16_t predictor_coef_table[channels][32];
-        int predictor_coef_num[channels];
-        int prediction_type[channels];
-        int prediction_quantitization[channels];
-        int ricemodifier[channels];
+        int16_t predictor_coef_table[MAX_CHANNELS][32];
+        int predictor_coef_num[MAX_CHANNELS];
+        int prediction_type[MAX_CHANNELS];
+        int prediction_quantitization[MAX_CHANNELS];
+        int ricemodifier[MAX_CHANNELS];
         int i, chan;
 
         interlacing_shift = get_bits(&alac->gb, 8);
@@ -678,10 +661,19 @@ static av_cold int alac_decode_init(AVCodecContext * avctx)
 {
     ALACContext *alac = avctx->priv_data;
     alac->avctx = avctx;
-    alac->context_initialized = 0;
-
     alac->numchannels = alac->avctx->channels;
 
+    /* initialize from the extradata */
+    if (alac->avctx->extradata_size != ALAC_EXTRADATA_SIZE) {
+        av_log(avctx, AV_LOG_ERROR, "alac: expected %d extradata bytes\n",
+            ALAC_EXTRADATA_SIZE);
+        return -1;
+    }
+    if (alac_set_info(alac)) {
+        av_log(avctx, AV_LOG_ERROR, "alac: set_info failed\n");
+        return -1;
+    }
+
     return 0;
 }
 
@@ -699,7 +691,7 @@ static av_cold int alac_decode_close(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec alac_decoder = {
+AVCodec ff_alac_decoder = {
     "alac",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_ALAC,
diff --git a/libavcodec/alacenc.c b/libavcodec/alacenc.c
index 0876633..2e20a60 100644
--- a/libavcodec/alacenc.c
+++ b/libavcodec/alacenc.c
@@ -2,20 +2,20 @@
  * ALAC audio encoder
  * Copyright (c) 2008  Jaikrishnan Menon <realityman at gmx.net>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -51,11 +51,11 @@ typedef struct RiceContext {
     int rice_modifier;
 } RiceContext;
 
-typedef struct LPCContext {
+typedef struct AlacLPCContext {
     int lpc_order;
     int lpc_coeff[ALAC_MAX_LPC_ORDER+1];
     int lpc_quant;
-} LPCContext;
+} AlacLPCContext;
 
 typedef struct AlacEncodeContext {
     int compression_level;
@@ -69,18 +69,18 @@ typedef struct AlacEncodeContext {
     int interlacing_leftweight;
     PutBitContext pbctx;
     RiceContext rc;
-    LPCContext lpc[MAX_CHANNELS];
-    DSPContext dspctx;
+    AlacLPCContext lpc[MAX_CHANNELS];
+    LPCContext lpc_ctx;
     AVCodecContext *avctx;
 } AlacEncodeContext;
 
 
-static void init_sample_buffers(AlacEncodeContext *s, int16_t *input_samples)
+static void init_sample_buffers(AlacEncodeContext *s, const int16_t *input_samples)
 {
     int ch, i;
 
     for(ch=0;ch<s->avctx->channels;ch++) {
-        int16_t *sptr = input_samples + ch;
+        const int16_t *sptr = input_samples + ch;
         for(i=0;i<s->avctx->frame_size;i++) {
             s->sample_buf[ch][i] = *sptr;
             sptr += s->avctx->channels;
@@ -141,11 +141,12 @@ static void calc_predictor_params(AlacEncodeContext *s, int ch)
         s->lpc[ch].lpc_coeff[4] =   80;
         s->lpc[ch].lpc_coeff[5] =  -25;
     } else {
-        opt_order = ff_lpc_calc_coefs(&s->dspctx, s->sample_buf[ch],
+        opt_order = ff_lpc_calc_coefs(&s->lpc_ctx, s->sample_buf[ch],
                                       s->avctx->frame_size,
                                       s->min_prediction_order,
                                       s->max_prediction_order,
-                                      ALAC_MAX_LPC_PRECISION, coefs, shift, 1,
+                                      ALAC_MAX_LPC_PRECISION, coefs, shift,
+                                      AV_LPC_TYPE_LEVINSON, 0,
                                       ORDER_METHOD_EST, ALAC_MAX_LPC_SHIFT, 1);
 
         s->lpc[ch].lpc_order = opt_order;
@@ -236,7 +237,7 @@ static void alac_stereo_decorrelation(AlacEncodeContext *s)
 static void alac_linear_predictor(AlacEncodeContext *s, int ch)
 {
     int i;
-    LPCContext lpc = s->lpc[ch];
+    AlacLPCContext lpc = s->lpc[ch];
 
     if(lpc.lpc_order == 31) {
         s->predictor_buf[0] = s->sample_buf[ch][0];
@@ -377,12 +378,13 @@ static void write_compressed_frame(AlacEncodeContext *s)
 static av_cold int alac_encode_init(AVCodecContext *avctx)
 {
     AlacEncodeContext *s    = avctx->priv_data;
+    int ret;
     uint8_t *alac_extradata = av_mallocz(ALAC_EXTRADATA_SIZE+1);
 
     avctx->frame_size      = DEFAULT_FRAME_SIZE;
     avctx->bits_per_coded_sample = DEFAULT_SAMPLE_SIZE;
 
-    if(avctx->sample_fmt != SAMPLE_FMT_S16) {
+    if(avctx->sample_fmt != AV_SAMPLE_FMT_S16) {
         av_log(avctx, AV_LOG_ERROR, "only pcm_s16 input samples are supported\n");
         return -1;
     }
@@ -454,9 +456,10 @@ static av_cold int alac_encode_init(AVCodecContext *avctx)
     avctx->coded_frame->key_frame = 1;
 
     s->avctx = avctx;
-    dsputil_init(&s->dspctx, avctx);
+    ret = ff_lpc_init(&s->lpc_ctx, avctx->frame_size, s->max_prediction_order,
+                      AV_LPC_TYPE_LEVINSON);
 
-    return 0;
+    return ret;
 }
 
 static int alac_encode_frame(AVCodecContext *avctx, uint8_t *frame,
@@ -481,7 +484,7 @@ verbatim:
 
     if((s->compression_level == 0) || verbatim_flag) {
         // Verbatim mode
-        int16_t *samples = data;
+        const int16_t *samples = data;
         write_frame_header(s, 1);
         for(i=0; i<avctx->frame_size*avctx->channels; i++) {
             put_sbits(pb, 16, *samples++);
@@ -512,13 +515,15 @@ verbatim:
 
 static av_cold int alac_encode_close(AVCodecContext *avctx)
 {
+    AlacEncodeContext *s = avctx->priv_data;
+    ff_lpc_end(&s->lpc_ctx);
     av_freep(&avctx->extradata);
     avctx->extradata_size = 0;
     av_freep(&avctx->coded_frame);
     return 0;
 }
 
-AVCodec alac_encoder = {
+AVCodec ff_alac_encoder = {
     "alac",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_ALAC,
@@ -527,6 +532,6 @@ AVCodec alac_encoder = {
     alac_encode_frame,
     alac_encode_close,
     .capabilities = CODEC_CAP_SMALL_LAST_FRAME,
-    .sample_fmts = (const enum SampleFormat[]){ SAMPLE_FMT_S16, SAMPLE_FMT_NONE},
+    .sample_fmts = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE},
     .long_name = NULL_IF_CONFIG_SMALL("ALAC (Apple Lossless Audio Codec)"),
 };
diff --git a/libavcodec/allcodecs.c b/libavcodec/allcodecs.c
index aa3001c..40a7e23 100644
--- a/libavcodec/allcodecs.c
+++ b/libavcodec/allcodecs.c
@@ -1,49 +1,49 @@
 /*
- * Provides registration of all codecs, parsers and bitstream filters for libavcodec.
+ * Provide registration of all codecs, parsers and bitstream filters for libavcodec.
  * Copyright (c) 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 /**
  * @file
- * Provides registration of all codecs, parsers and bitstream filters for libavcodec.
+ * Provide registration of all codecs, parsers and bitstream filters for libavcodec.
  */
 
 #include "avcodec.h"
 
 #define REGISTER_HWACCEL(X,x) { \
-          extern AVHWAccel x##_hwaccel; \
-          if(CONFIG_##X##_HWACCEL) av_register_hwaccel(&x##_hwaccel); }
+          extern AVHWAccel ff_##x##_hwaccel; \
+          if(CONFIG_##X##_HWACCEL) av_register_hwaccel(&ff_##x##_hwaccel); }
 
 #define REGISTER_ENCODER(X,x) { \
-          extern AVCodec x##_encoder; \
-          if(CONFIG_##X##_ENCODER)  avcodec_register(&x##_encoder); }
+          extern AVCodec ff_##x##_encoder; \
+          if(CONFIG_##X##_ENCODER)  avcodec_register(&ff_##x##_encoder); }
 #define REGISTER_DECODER(X,x) { \
-          extern AVCodec x##_decoder; \
-          if(CONFIG_##X##_DECODER)  avcodec_register(&x##_decoder); }
+          extern AVCodec ff_##x##_decoder; \
+          if(CONFIG_##X##_DECODER)  avcodec_register(&ff_##x##_decoder); }
 #define REGISTER_ENCDEC(X,x)  REGISTER_ENCODER(X,x); REGISTER_DECODER(X,x)
 
 #define REGISTER_PARSER(X,x) { \
-          extern AVCodecParser x##_parser; \
-          if(CONFIG_##X##_PARSER)  av_register_codec_parser(&x##_parser); }
+          extern AVCodecParser ff_##x##_parser; \
+          if(CONFIG_##X##_PARSER)  av_register_codec_parser(&ff_##x##_parser); }
 #define REGISTER_BSF(X,x) { \
-          extern AVBitStreamFilter x##_bsf; \
-          if(CONFIG_##X##_BSF)     av_register_bitstream_filter(&x##_bsf); }
+          extern AVBitStreamFilter ff_##x##_bsf; \
+          if(CONFIG_##X##_BSF)     av_register_bitstream_filter(&ff_##x##_bsf); }
 
 void avcodec_register_all(void)
 {
@@ -57,6 +57,7 @@ void avcodec_register_all(void)
     REGISTER_HWACCEL (H263_VAAPI, h263_vaapi);
     REGISTER_HWACCEL (H264_DXVA2, h264_dxva2);
     REGISTER_HWACCEL (H264_VAAPI, h264_vaapi);
+    REGISTER_HWACCEL (MPEG2_DXVA2, mpeg2_dxva2);
     REGISTER_HWACCEL (MPEG2_VAAPI, mpeg2_vaapi);
     REGISTER_HWACCEL (MPEG4_VAAPI, mpeg4_vaapi);
     REGISTER_HWACCEL (VC1_DXVA2, vc1_dxva2);
@@ -65,9 +66,12 @@ void avcodec_register_all(void)
     REGISTER_HWACCEL (WMV3_VAAPI, wmv3_vaapi);
 
     /* video codecs */
+    REGISTER_ENCODER (A64MULTI, a64multi);
+    REGISTER_ENCODER (A64MULTI5, a64multi5);
     REGISTER_DECODER (AASC, aasc);
     REGISTER_DECODER (AMV, amv);
     REGISTER_DECODER (ANM, anm);
+    REGISTER_DECODER (ANSI, ansi);
     REGISTER_ENCDEC  (ASV1, asv1);
     REGISTER_ENCDEC  (ASV2, asv2);
     REGISTER_DECODER (AURA, aura);
@@ -84,6 +88,7 @@ void avcodec_register_all(void)
     REGISTER_DECODER (CLJR, cljr);
     REGISTER_DECODER (CSCD, cscd);
     REGISTER_DECODER (CYUV, cyuv);
+    REGISTER_DECODER (DFA, dfa);
     REGISTER_ENCDEC  (DNXHD, dnxhd);
     REGISTER_DECODER (DPX, dpx);
     REGISTER_DECODER (DSICINVIDEO, dsicinvideo);
@@ -122,8 +127,10 @@ void avcodec_register_all(void)
     REGISTER_DECODER (INDEO5, indeo5);
     REGISTER_DECODER (INTERPLAY_VIDEO, interplay_video);
     REGISTER_ENCDEC  (JPEGLS, jpegls);
+    REGISTER_DECODER (JV, jv);
     REGISTER_DECODER (KGV1, kgv1);
     REGISTER_DECODER (KMVC, kmvc);
+    REGISTER_DECODER (LAGARITH, lagarith);
     REGISTER_ENCODER (LJPEG, ljpeg);
     REGISTER_DECODER (LOCO, loco);
     REGISTER_DECODER (MDEC, mdec);
@@ -146,18 +153,21 @@ void avcodec_register_all(void)
     REGISTER_DECODER (MSRLE, msrle);
     REGISTER_DECODER (MSVIDEO1, msvideo1);
     REGISTER_DECODER (MSZH, mszh);
+    REGISTER_DECODER (MXPEG, mxpeg);
     REGISTER_DECODER (NUV, nuv);
     REGISTER_ENCDEC  (PAM, pam);
     REGISTER_ENCDEC  (PBM, pbm);
     REGISTER_ENCDEC  (PCX, pcx);
     REGISTER_ENCDEC  (PGM, pgm);
     REGISTER_ENCDEC  (PGMYUV, pgmyuv);
+    REGISTER_DECODER (PICTOR, pictor);
     REGISTER_ENCDEC  (PNG, png);
     REGISTER_ENCDEC  (PPM, ppm);
     REGISTER_DECODER (PTX, ptx);
     REGISTER_DECODER (QDRAW, qdraw);
     REGISTER_DECODER (QPEG, qpeg);
     REGISTER_ENCDEC  (QTRLE, qtrle);
+    REGISTER_DECODER (R10K,  r10k);
     REGISTER_DECODER (R210,  r210);
     REGISTER_ENCDEC  (RAWVIDEO, rawvideo);
     REGISTER_DECODER (RL2, rl2);
@@ -199,6 +209,7 @@ void avcodec_register_all(void)
     REGISTER_DECODER (VP6, vp6);
     REGISTER_DECODER (VP6A, vp6a);
     REGISTER_DECODER (VP6F, vp6f);
+    REGISTER_DECODER (VP8, vp8);
     REGISTER_DECODER (VQA, vqa);
     REGISTER_ENCDEC  (WMV1, wmv1);
     REGISTER_ENCDEC  (WMV2, wmv2);
@@ -206,6 +217,7 @@ void avcodec_register_all(void)
     REGISTER_DECODER (WMV3_VDPAU, wmv3_vdpau);
     REGISTER_DECODER (WNV1, wnv1);
     REGISTER_DECODER (XAN_WC3, xan_wc3);
+    REGISTER_DECODER (XAN_WC4, xan_wc4);
     REGISTER_DECODER (XL, xl);
     REGISTER_DECODER (YOP, yop);
     REGISTER_ENCDEC  (ZLIB, zlib);
@@ -213,10 +225,13 @@ void avcodec_register_all(void)
 
     /* audio codecs */
     REGISTER_ENCDEC  (AAC, aac);
+    REGISTER_DECODER (AAC_LATM, aac_latm);
     REGISTER_ENCDEC  (AC3, ac3);
+    REGISTER_ENCODER (AC3_FIXED, ac3_fixed);
     REGISTER_ENCDEC  (ALAC, alac);
     REGISTER_DECODER (ALS, als);
     REGISTER_DECODER (AMRNB, amrnb);
+    REGISTER_DECODER (AMRWB, amrwb);
     REGISTER_DECODER (APE, ape);
     REGISTER_DECODER (ATRAC1, atrac1);
     REGISTER_DECODER (ATRAC3, atrac3);
@@ -227,33 +242,38 @@ void avcodec_register_all(void)
     REGISTER_DECODER (DSICINAUDIO, dsicinaudio);
     REGISTER_DECODER (EAC3, eac3);
     REGISTER_ENCDEC  (FLAC, flac);
+    REGISTER_DECODER (GSM, gsm);
+    REGISTER_DECODER (GSM_MS, gsm_ms);
     REGISTER_DECODER (IMC, imc);
     REGISTER_DECODER (MACE3, mace3);
     REGISTER_DECODER (MACE6, mace6);
     REGISTER_DECODER (MLP, mlp);
     REGISTER_DECODER (MP1, mp1);
+    REGISTER_DECODER (MP1FLOAT, mp1float);
     REGISTER_ENCDEC  (MP2, mp2);
+    REGISTER_DECODER (MP2FLOAT, mp2float);
     REGISTER_DECODER (MP3, mp3);
+    REGISTER_DECODER (MP3FLOAT, mp3float);
     REGISTER_DECODER (MP3ADU, mp3adu);
+    REGISTER_DECODER (MP3ADUFLOAT, mp3adufloat);
     REGISTER_DECODER (MP3ON4, mp3on4);
+    REGISTER_DECODER (MP3ON4FLOAT, mp3on4float);
     REGISTER_DECODER (MPC7, mpc7);
     REGISTER_DECODER (MPC8, mpc8);
     REGISTER_ENCDEC  (NELLYMOSER, nellymoser);
     REGISTER_DECODER (QCELP, qcelp);
     REGISTER_DECODER (QDM2, qdm2);
-    REGISTER_DECODER (RA_144, ra_144);
+    REGISTER_ENCDEC  (RA_144, ra_144);
     REGISTER_DECODER (RA_288, ra_288);
     REGISTER_DECODER (SHORTEN, shorten);
     REGISTER_DECODER (SIPR, sipr);
     REGISTER_DECODER (SMACKAUD, smackaud);
-    REGISTER_ENCDEC  (SONIC, sonic);
-    REGISTER_ENCODER (SONIC_LS, sonic_ls);
     REGISTER_DECODER (TRUEHD, truehd);
     REGISTER_DECODER (TRUESPEECH, truespeech);
     REGISTER_DECODER (TTA, tta);
     REGISTER_DECODER (TWINVQ, twinvq);
     REGISTER_DECODER (VMDAUDIO, vmdaudio);
-    REGISTER_DECODER  (VORBIS, vorbis);
+    REGISTER_ENCDEC  (VORBIS, vorbis);
     REGISTER_DECODER (WAVPACK, wavpack);
     REGISTER_DECODER (WMAPRO, wmapro);
     REGISTER_ENCDEC  (WMAV1, wmav1);
@@ -269,6 +289,7 @@ void avcodec_register_all(void)
     REGISTER_ENCDEC  (PCM_F32LE, pcm_f32le);
     REGISTER_ENCDEC  (PCM_F64BE, pcm_f64be);
     REGISTER_ENCDEC  (PCM_F64LE, pcm_f64le);
+    REGISTER_DECODER (PCM_LXF, pcm_lxf);
     REGISTER_ENCDEC  (PCM_MULAW, pcm_mulaw);
     REGISTER_ENCDEC  (PCM_S8, pcm_s8);
     REGISTER_ENCDEC  (PCM_S16BE, pcm_s16be);
@@ -304,6 +325,7 @@ void avcodec_register_all(void)
     REGISTER_DECODER (ADPCM_EA_R2, adpcm_ea_r2);
     REGISTER_DECODER (ADPCM_EA_R3, adpcm_ea_r3);
     REGISTER_DECODER (ADPCM_EA_XAS, adpcm_ea_xas);
+    REGISTER_ENCDEC  (ADPCM_G722, adpcm_g722);
     REGISTER_ENCDEC  (ADPCM_G726, adpcm_g726);
     REGISTER_DECODER (ADPCM_IMA_AMV, adpcm_ima_amv);
     REGISTER_DECODER (ADPCM_IMA_DK3, adpcm_ima_dk3);
@@ -325,15 +347,16 @@ void avcodec_register_all(void)
     REGISTER_ENCDEC  (ADPCM_YAMAHA, adpcm_yamaha);
 
     /* subtitles */
+    REGISTER_ENCDEC  (ASS, ass);
     REGISTER_ENCDEC  (DVBSUB, dvbsub);
     REGISTER_ENCDEC  (DVDSUB, dvdsub);
     REGISTER_DECODER (PGSSUB, pgssub);
+    REGISTER_DECODER (SRT, srt);
     REGISTER_ENCDEC  (XSUB, xsub);
 
     /* external libraries */
     REGISTER_ENCDEC  (LIBDIRAC, libdirac);
     REGISTER_ENCODER (LIBFAAC, libfaac);
-    REGISTER_DECODER (LIBFAAD, libfaad);
     REGISTER_ENCDEC  (LIBGSM, libgsm);
     REGISTER_ENCDEC  (LIBGSM_MS, libgsm_ms);
     REGISTER_ENCODER (LIBMP3LAME, libmp3lame);
@@ -343,13 +366,17 @@ void avcodec_register_all(void)
     REGISTER_ENCDEC  (LIBSCHROEDINGER, libschroedinger);
     REGISTER_DECODER (LIBSPEEX, libspeex);
     REGISTER_ENCODER (LIBTHEORA, libtheora);
+    REGISTER_ENCODER (LIBVO_AACENC, libvo_aacenc);
+    REGISTER_ENCODER (LIBVO_AMRWBENC, libvo_amrwbenc);
     REGISTER_ENCODER (LIBVORBIS, libvorbis);
     REGISTER_ENCDEC  (LIBVPX, libvpx);
     REGISTER_ENCODER (LIBX264, libx264);
+    REGISTER_ENCODER (LIBXAVS, libxavs);
     REGISTER_ENCODER (LIBXVID, libxvid);
 
     /* parsers */
     REGISTER_PARSER  (AAC, aac);
+    REGISTER_PARSER  (AAC_LATM, aac_latm);
     REGISTER_PARSER  (AC3, ac3);
     REGISTER_PARSER  (CAVSVIDEO, cavsvideo);
     REGISTER_PARSER  (DCA, dca);
@@ -357,6 +384,7 @@ void avcodec_register_all(void)
     REGISTER_PARSER  (DNXHD, dnxhd);
     REGISTER_PARSER  (DVBSUB, dvbsub);
     REGISTER_PARSER  (DVDSUB, dvdsub);
+    REGISTER_PARSER  (FLAC, flac);
     REGISTER_PARSER  (H261, h261);
     REGISTER_PARSER  (H263, h263);
     REGISTER_PARSER  (H264, h264);
@@ -368,12 +396,15 @@ void avcodec_register_all(void)
     REGISTER_PARSER  (PNM, pnm);
     REGISTER_PARSER  (VC1, vc1);
     REGISTER_PARSER  (VP3, vp3);
+    REGISTER_PARSER  (VP8, vp8);
 
     /* bitstream filters */
     REGISTER_BSF     (AAC_ADTSTOASC, aac_adtstoasc);
+    REGISTER_BSF     (CHOMP, chomp);
     REGISTER_BSF     (DUMP_EXTRADATA, dump_extradata);
     REGISTER_BSF     (H264_MP4TOANNEXB, h264_mp4toannexb);
     REGISTER_BSF     (IMX_DUMP_HEADER, imx_dump_header);
+    REGISTER_BSF     (MJPEG2JPEG, mjpeg2jpeg);
     REGISTER_BSF     (MJPEGA_DUMP_HEADER, mjpega_dump_header);
     REGISTER_BSF     (MP3_HEADER_COMPRESS, mp3_header_compress);
     REGISTER_BSF     (MP3_HEADER_DECOMPRESS, mp3_header_decompress);
diff --git a/libavcodec/alpha/asm.h b/libavcodec/alpha/asm.h
index 827721e..ab4cfcc 100644
--- a/libavcodec/alpha/asm.h
+++ b/libavcodec/alpha/asm.h
@@ -2,20 +2,20 @@
  * Alpha optimized DSP utils
  * Copyright (c) 2002 Falk Hueffner <falk at debian.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/alpha/dsputil_alpha.c b/libavcodec/alpha/dsputil_alpha.c
index b87367f..610f92a 100644
--- a/libavcodec/alpha/dsputil_alpha.c
+++ b/libavcodec/alpha/dsputil_alpha.c
@@ -2,20 +2,20 @@
  * Alpha optimized DSP utils
  * Copyright (c) 2002 Falk Hueffner <falk at debian.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/alpha/dsputil_alpha.h b/libavcodec/alpha/dsputil_alpha.h
index a3fa3dd..0dcacab 100644
--- a/libavcodec/alpha/dsputil_alpha.h
+++ b/libavcodec/alpha/dsputil_alpha.h
@@ -1,18 +1,18 @@
 /*
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/alpha/dsputil_alpha_asm.S b/libavcodec/alpha/dsputil_alpha_asm.S
index 57b21fc..ca857ac 100644
--- a/libavcodec/alpha/dsputil_alpha_asm.S
+++ b/libavcodec/alpha/dsputil_alpha_asm.S
@@ -2,20 +2,20 @@
  * Alpha optimized DSP utils
  * Copyright (c) 2002 Falk Hueffner <falk at debian.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -53,11 +53,6 @@ put_pixels_axp_asm:
         .frame sp, 0, ra
         .prologue 0
 
-#if CONFIG_GPROF
-        lda     AT, _mcount
-        jsr     AT, (AT), _mcount
-#endif
-
         and     a1, 7, t0
         beq     t0, $aligned
 
@@ -150,11 +145,6 @@ put_pixels_clamped_mvi_asm:
         .frame sp, 0, ra
         .prologue 0
 
-#if CONFIG_GPROF
-        lda     AT, _mcount
-        jsr     AT, (AT), _mcount
-#endif
-
         lda     t8, -1
         lda     t9, 8           # loop counter
         zap     t8, 0xaa, t8    # 00ff00ff00ff00ff
@@ -205,11 +195,6 @@ add_pixels_clamped_mvi_asm:
         .frame sp, 0, ra
         .prologue 0
 
-#if CONFIG_GPROF
-        lda     AT, _mcount
-        jsr     AT, (AT), _mcount
-#endif
-
         lda     t1, -1
         lda     th, 8
         zap     t1, 0x33, tg
diff --git a/libavcodec/alpha/motion_est_alpha.c b/libavcodec/alpha/motion_est_alpha.c
index 863dd23..bb9ab13 100644
--- a/libavcodec/alpha/motion_est_alpha.c
+++ b/libavcodec/alpha/motion_est_alpha.c
@@ -2,20 +2,20 @@
  * Alpha optimized DSP utils
  * Copyright (c) 2002 Falk Hueffner <falk at debian.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/alpha/motion_est_mvi_asm.S b/libavcodec/alpha/motion_est_mvi_asm.S
index 2a08b07..7fe4e16 100644
--- a/libavcodec/alpha/motion_est_mvi_asm.S
+++ b/libavcodec/alpha/motion_est_mvi_asm.S
@@ -2,20 +2,20 @@
  * Alpha optimized DSP utils
  * Copyright (c) 2002 Falk Hueffner <falk at debian.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -55,11 +55,6 @@ pix_abs16x16_mvi_asm:
         .frame sp, 0, ra, 0
         .prologue 0
 
-#if CONFIG_GPROF
-        lda     AT, _mcount
-        jsr     AT, (AT), _mcount
-#endif
-
         and     a2, 7, t0
         clr     v0
         beq     t0, $aligned
diff --git a/libavcodec/alpha/mpegvideo_alpha.c b/libavcodec/alpha/mpegvideo_alpha.c
index de32545..add5736 100644
--- a/libavcodec/alpha/mpegvideo_alpha.c
+++ b/libavcodec/alpha/mpegvideo_alpha.c
@@ -2,20 +2,20 @@
  * Alpha optimized DSP utils
  * Copyright (c) 2002 Falk Hueffner <falk at debian.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/alpha/regdef.h b/libavcodec/alpha/regdef.h
index aa1959f..fa9ad98 100644
--- a/libavcodec/alpha/regdef.h
+++ b/libavcodec/alpha/regdef.h
@@ -2,20 +2,20 @@
  * Alpha optimized DSP utils
  * copyright (c) 2002 Falk Hueffner <falk at debian.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/alpha/simple_idct_alpha.c b/libavcodec/alpha/simple_idct_alpha.c
index 0c0689a..8f5c134 100644
--- a/libavcodec/alpha/simple_idct_alpha.c
+++ b/libavcodec/alpha/simple_idct_alpha.c
@@ -9,20 +9,20 @@
  * Alpha optimizations by Måns Rullgård <mans at mansr.com>
  *                     and Falk Hueffner <falk at debian.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/alsdec.c b/libavcodec/alsdec.c
index 2058a85..17c5490 100644
--- a/libavcodec/alsdec.c
+++ b/libavcodec/alsdec.c
@@ -2,20 +2,20 @@
  * MPEG-4 ALS decoder
  * Copyright (c) 2009 Thilo Borgmann <thilo.borgmann _at_ googlemail.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -35,11 +35,14 @@
 #include "mpeg4audio.h"
 #include "bytestream.h"
 #include "bgmc.h"
+#include "dsputil.h"
+#include "libavutil/samplefmt.h"
+#include "libavutil/crc.h"
 
 #include <stdint.h>
 
 /** Rice parameters and corresponding index offsets for decoding the
- *  indices of scaled PARCOR values. The table choosen is set globally
+ *  indices of scaled PARCOR values. The table chosen is set globally
  *  by the encoder and stored in ALSSpecificConfig.
  */
 static const int8_t parcor_rice_table[3][20][2] = {
@@ -154,6 +157,7 @@ typedef struct {
     uint32_t samples;         ///< number of samples, 0xFFFFFFFF if unknown
     int resolution;           ///< 000 = 8-bit; 001 = 16-bit; 010 = 24-bit; 011 = 32-bit
     int floating;             ///< 1 = IEEE 32-bit floating-point, 0 = integer
+    int msb_first;            ///< 1 = original CRC calculated on big-endian system, 0 = little-endian
     int frame_length;         ///< frame length for each frame (last frame may differ)
     int ra_distance;          ///< distance between RA frames (in frames, 0...255)
     enum RA_Flag ra_flag;     ///< indicates where the size of ra units is stored
@@ -171,6 +175,7 @@ typedef struct {
     int rlslms;               ///< use "Recursive Least Square-Least Mean Square" predictor: 1 = on, 0 = off
     int chan_config_info;     ///< mapping of channels to loudspeaker locations. Unused until setting channel configuration is implemented.
     int *chan_pos;            ///< original channel positions
+    int crc_enabled;          ///< enable Cyclic Redundancy Checksum
 } ALSSpecificConfig;
 
 
@@ -188,14 +193,22 @@ typedef struct {
     AVCodecContext *avctx;
     ALSSpecificConfig sconf;
     GetBitContext gb;
+    DSPContext dsp;
+    const AVCRC *crc_table;
+    uint32_t crc_org;               ///< CRC value of the original input data
+    uint32_t crc;                   ///< CRC value calculated from decoded data
     unsigned int cur_frame_length;  ///< length of the current frame to decode
     unsigned int frame_id;          ///< the frame ID / number of the current frame
     unsigned int js_switch;         ///< if true, joint-stereo decoding is enforced
     unsigned int num_blocks;        ///< number of blocks used in the current frame
     unsigned int s_max;             ///< maximum Rice parameter allowed in entropy coding
     uint8_t *bgmc_lut;              ///< pointer at lookup tables used for BGMC
-    unsigned int *bgmc_lut_status;  ///< pointer at lookup table status flags used for BGMC
+    int *bgmc_lut_status;           ///< pointer at lookup table status flags used for BGMC
     int ltp_lag_length;             ///< number of bits used for ltp lag value
+    int *const_block;               ///< contains const_block flags for all channels
+    unsigned int *shift_lsbs;       ///< contains shift_lsbs flags for all channels
+    unsigned int *opt_order;        ///< contains opt_order flags for all channels
+    int *store_prev_samples;        ///< contains store_prev_samples flags for all channels
     int *use_ltp;                   ///< contains use_ltp flags for all channels
     int *ltp_lag;                   ///< contains ltp lag values for all channels
     int **ltp_gain;                 ///< gain values for ltp 5-tap filter for a channel
@@ -211,18 +224,18 @@ typedef struct {
     int32_t *prev_raw_samples;      ///< contains unshifted raw samples from the previous block
     int32_t **raw_samples;          ///< decoded raw samples for each channel
     int32_t *raw_buffer;            ///< contains all decoded raw samples including carryover samples
+    uint8_t *crc_buffer;            ///< buffer of byte order corrected samples used for CRC check
 } ALSDecContext;
 
 
 typedef struct {
     unsigned int block_length;      ///< number of samples within the block
     unsigned int ra_block;          ///< if true, this is a random access block
-    int          const_block;       ///< if true, this is a constant value block
-    int32_t      const_val;         ///< the sample value of a constant block
+    int          *const_block;      ///< if true, this is a constant value block
     int          js_blocks;         ///< true if this block contains a difference signal
-    unsigned int shift_lsbs;        ///< shift of values for this block
-    unsigned int opt_order;         ///< prediction order of this block
-    int          store_prev_samples;///< if true, carryover samples have to be stored
+    unsigned int *shift_lsbs;       ///< shift of values for this block
+    unsigned int *opt_order;        ///< prediction order of this block
+    int          *store_prev_samples;///< if true, carryover samples have to be stored
     int          *use_ltp;          ///< if true, long-term prediction is used
     int          *ltp_lag;          ///< lag value for long-term prediction
     int          *ltp_gain;         ///< gain values for ltp 5-tap filter
@@ -240,35 +253,35 @@ static av_cold void dprint_specific_config(ALSDecContext *ctx)
     AVCodecContext *avctx    = ctx->avctx;
     ALSSpecificConfig *sconf = &ctx->sconf;
 
-    dprintf(avctx, "resolution = %i\n",           sconf->resolution);
-    dprintf(avctx, "floating = %i\n",             sconf->floating);
-    dprintf(avctx, "frame_length = %i\n",         sconf->frame_length);
-    dprintf(avctx, "ra_distance = %i\n",          sconf->ra_distance);
-    dprintf(avctx, "ra_flag = %i\n",              sconf->ra_flag);
-    dprintf(avctx, "adapt_order = %i\n",          sconf->adapt_order);
-    dprintf(avctx, "coef_table = %i\n",           sconf->coef_table);
-    dprintf(avctx, "long_term_prediction = %i\n", sconf->long_term_prediction);
-    dprintf(avctx, "max_order = %i\n",            sconf->max_order);
-    dprintf(avctx, "block_switching = %i\n",      sconf->block_switching);
-    dprintf(avctx, "bgmc = %i\n",                 sconf->bgmc);
-    dprintf(avctx, "sb_part = %i\n",              sconf->sb_part);
-    dprintf(avctx, "joint_stereo = %i\n",         sconf->joint_stereo);
-    dprintf(avctx, "mc_coding = %i\n",            sconf->mc_coding);
-    dprintf(avctx, "chan_config = %i\n",          sconf->chan_config);
-    dprintf(avctx, "chan_sort = %i\n",            sconf->chan_sort);
-    dprintf(avctx, "RLSLMS = %i\n",               sconf->rlslms);
-    dprintf(avctx, "chan_config_info = %i\n",     sconf->chan_config_info);
+    av_dlog(avctx, "resolution = %i\n",           sconf->resolution);
+    av_dlog(avctx, "floating = %i\n",             sconf->floating);
+    av_dlog(avctx, "frame_length = %i\n",         sconf->frame_length);
+    av_dlog(avctx, "ra_distance = %i\n",          sconf->ra_distance);
+    av_dlog(avctx, "ra_flag = %i\n",              sconf->ra_flag);
+    av_dlog(avctx, "adapt_order = %i\n",          sconf->adapt_order);
+    av_dlog(avctx, "coef_table = %i\n",           sconf->coef_table);
+    av_dlog(avctx, "long_term_prediction = %i\n", sconf->long_term_prediction);
+    av_dlog(avctx, "max_order = %i\n",            sconf->max_order);
+    av_dlog(avctx, "block_switching = %i\n",      sconf->block_switching);
+    av_dlog(avctx, "bgmc = %i\n",                 sconf->bgmc);
+    av_dlog(avctx, "sb_part = %i\n",              sconf->sb_part);
+    av_dlog(avctx, "joint_stereo = %i\n",         sconf->joint_stereo);
+    av_dlog(avctx, "mc_coding = %i\n",            sconf->mc_coding);
+    av_dlog(avctx, "chan_config = %i\n",          sconf->chan_config);
+    av_dlog(avctx, "chan_sort = %i\n",            sconf->chan_sort);
+    av_dlog(avctx, "RLSLMS = %i\n",               sconf->rlslms);
+    av_dlog(avctx, "chan_config_info = %i\n",     sconf->chan_config_info);
 #endif
 }
 
 
-/** Reads an ALSSpecificConfig from a buffer into the output struct.
+/** Read an ALSSpecificConfig from a buffer into the output struct.
  */
 static av_cold int read_specific_config(ALSDecContext *ctx)
 {
     GetBitContext gb;
     uint64_t ht_size;
-    int i, config_offset, crc_enabled;
+    int i, config_offset;
     MPEG4AudioConfig m4ac;
     ALSSpecificConfig *sconf = &ctx->sconf;
     AVCodecContext *avctx    = ctx->avctx;
@@ -297,7 +310,7 @@ static av_cold int read_specific_config(ALSDecContext *ctx)
     skip_bits(&gb, 3);       // skip file_type
     sconf->resolution           = get_bits(&gb, 3);
     sconf->floating             = get_bits1(&gb);
-    skip_bits1(&gb);         // skip msb_first
+    sconf->msb_first            = get_bits1(&gb);
     sconf->frame_length         = get_bits(&gb, 16) + 1;
     sconf->ra_distance          = get_bits(&gb, 8);
     sconf->ra_flag              = get_bits(&gb, 2);
@@ -312,7 +325,7 @@ static av_cold int read_specific_config(ALSDecContext *ctx)
     sconf->mc_coding            = get_bits1(&gb);
     sconf->chan_config          = get_bits1(&gb);
     sconf->chan_sort            = get_bits1(&gb);
-    crc_enabled                 = get_bits1(&gb);
+    sconf->crc_enabled          = get_bits1(&gb);
     sconf->rlslms               = get_bits1(&gb);
     skip_bits(&gb, 5);       // skip 5 reserved bits
     skip_bits1(&gb);         // skip aux_data_enabled
@@ -375,12 +388,17 @@ static av_cold int read_specific_config(ALSDecContext *ctx)
     skip_bits_long(&gb, ht_size);
 
 
-    // skip the crc data
-    if (crc_enabled) {
+    // initialize CRC calculation
+    if (sconf->crc_enabled) {
         if (get_bits_left(&gb) < 32)
             return -1;
 
-        skip_bits_long(&gb, 32);
+        if (avctx->error_recognition >= FF_ER_CAREFUL) {
+            ctx->crc_table = av_crc_get_table(AV_CRC_32_IEEE_LE);
+            ctx->crc       = 0xFFFFFFFF;
+            ctx->crc_org   = ~get_bits_long(&gb, 32);
+        } else
+            skip_bits_long(&gb, 32);
     }
 
 
@@ -392,7 +410,7 @@ static av_cold int read_specific_config(ALSDecContext *ctx)
 }
 
 
-/** Checks the ALSSpecificConfig for unsupported features.
+/** Check the ALSSpecificConfig for unsupported features.
  */
 static int check_specific_config(ALSDecContext *ctx)
 {
@@ -416,7 +434,7 @@ static int check_specific_config(ALSDecContext *ctx)
 }
 
 
-/** Parses the bs_info field to extract the block partitioning used in
+/** Parse the bs_info field to extract the block partitioning used in
  *  block switching mode, refer to ISO/IEC 14496-3, section 11.6.2.
  */
 static void parse_bs_info(const uint32_t bs_info, unsigned int n,
@@ -440,7 +458,7 @@ static void parse_bs_info(const uint32_t bs_info, unsigned int n,
 }
 
 
-/** Reads and decodes a Rice codeword.
+/** Read and decode a Rice codeword.
  */
 static int32_t decode_rice(GetBitContext *gb, unsigned int k)
 {
@@ -458,7 +476,7 @@ static int32_t decode_rice(GetBitContext *gb, unsigned int k)
 }
 
 
-/** Converts PARCOR coefficient k to direct filter coefficient.
+/** Convert PARCOR coefficient k to direct filter coefficient.
  */
 static void parcor_to_lpc(unsigned int k, const int32_t *par, int32_t *cof)
 {
@@ -476,8 +494,8 @@ static void parcor_to_lpc(unsigned int k, const int32_t *par, int32_t *cof)
 }
 
 
-/** Reads block switching field if necessary and sets actual block sizes.
- *  Also assures that the block sizes of the last frame correspond to the
+/** Read block switching field if necessary and set actual block sizes.
+ *  Also assure that the block sizes of the last frame correspond to the
  *  actual number of samples.
  */
 static void get_block_sizes(ALSDecContext *ctx, unsigned int *div_blocks,
@@ -531,7 +549,7 @@ static void get_block_sizes(ALSDecContext *ctx, unsigned int *div_blocks,
 }
 
 
-/** Reads the block data for a constant block
+/** Read the block data for a constant block
  */
 static void read_const_block_data(ALSDecContext *ctx, ALSBlockData *bd)
 {
@@ -539,30 +557,30 @@ static void read_const_block_data(ALSDecContext *ctx, ALSBlockData *bd)
     AVCodecContext *avctx    = ctx->avctx;
     GetBitContext *gb        = &ctx->gb;
 
-    bd->const_val    = 0;
-    bd->const_block  = get_bits1(gb);    // 1 = constant value, 0 = zero block (silence)
+    *bd->raw_samples = 0;
+    *bd->const_block = get_bits1(gb);    // 1 = constant value, 0 = zero block (silence)
     bd->js_blocks    = get_bits1(gb);
 
     // skip 5 reserved bits
     skip_bits(gb, 5);
 
-    if (bd->const_block) {
+    if (*bd->const_block) {
         unsigned int const_val_bits = sconf->floating ? 24 : avctx->bits_per_raw_sample;
-        bd->const_val = get_sbits_long(gb, const_val_bits);
+        *bd->raw_samples = get_sbits_long(gb, const_val_bits);
     }
 
     // ensure constant block decoding by reusing this field
-    bd->const_block = 1;
+    *bd->const_block = 1;
 }
 
 
-/** Decodes the block data for a constant block
+/** Decode the block data for a constant block
  */
 static void decode_const_block_data(ALSDecContext *ctx, ALSBlockData *bd)
 {
-    int      smp = bd->block_length;
-    int32_t  val = bd->const_val;
-    int32_t *dst = bd->raw_samples;
+    int      smp = bd->block_length - 1;
+    int32_t  val = *bd->raw_samples;
+    int32_t *dst = bd->raw_samples + 1;
 
     // write raw samples into buffer
     for (; smp; smp--)
@@ -570,7 +588,7 @@ static void decode_const_block_data(ALSDecContext *ctx, ALSBlockData *bd)
 }
 
 
-/** Reads the block data for a non-constant block
+/** Read the block data for a non-constant block
  */
 static int read_var_block_data(ALSDecContext *ctx, ALSBlockData *bd)
 {
@@ -589,12 +607,12 @@ static int read_var_block_data(ALSDecContext *ctx, ALSBlockData *bd)
 
 
     // ensure variable block decoding by reusing this field
-    bd->const_block = 0;
+    *bd->const_block = 0;
 
-    bd->opt_order   = 1;
+    *bd->opt_order  = 1;
     bd->js_blocks   = get_bits1(gb);
 
-    opt_order       = bd->opt_order;
+    opt_order       = *bd->opt_order;
 
     // determine the number of subblocks for entropy decoding
     if (!sconf->bgmc && !sconf->sb_part) {
@@ -634,21 +652,21 @@ static int read_var_block_data(ALSDecContext *ctx, ALSBlockData *bd)
     }
 
     if (get_bits1(gb))
-        bd->shift_lsbs = get_bits(gb, 4) + 1;
+        *bd->shift_lsbs = get_bits(gb, 4) + 1;
 
-    bd->store_prev_samples = (bd->js_blocks && bd->raw_other) || bd->shift_lsbs;
+    *bd->store_prev_samples = (bd->js_blocks && bd->raw_other) || *bd->shift_lsbs;
 
 
     if (!sconf->rlslms) {
         if (sconf->adapt_order) {
             int opt_order_length = av_ceil_log2(av_clip((bd->block_length >> 3) - 1,
                                                 2, sconf->max_order + 1));
-            bd->opt_order        = get_bits(gb, opt_order_length);
+            *bd->opt_order       = get_bits(gb, opt_order_length);
         } else {
-            bd->opt_order = sconf->max_order;
+            *bd->opt_order = sconf->max_order;
         }
 
-        opt_order = bd->opt_order;
+        opt_order = *bd->opt_order;
 
         if (opt_order) {
             int add_base;
@@ -734,8 +752,8 @@ static int read_var_block_data(ALSDecContext *ctx, ALSBlockData *bd)
 
     // read all residuals
     if (sconf->bgmc) {
-        unsigned int delta[sub_blocks];
-        unsigned int k    [sub_blocks];
+        int          delta[8];
+        unsigned int k    [8];
         unsigned int b = av_clip((av_ceil_log2(bd->block_length) - 3) >> 1, 0, 5);
         unsigned int i = start;
 
@@ -817,7 +835,7 @@ static int read_var_block_data(ALSDecContext *ctx, ALSBlockData *bd)
 }
 
 
-/** Decodes the block data for a non-constant block
+/** Decode the block data for a non-constant block
  */
 static int decode_var_block_data(ALSDecContext *ctx, ALSBlockData *bd)
 {
@@ -825,7 +843,7 @@ static int decode_var_block_data(ALSDecContext *ctx, ALSBlockData *bd)
     unsigned int block_length = bd->block_length;
     unsigned int smp = 0;
     unsigned int k;
-    int opt_order             = bd->opt_order;
+    int opt_order             = *bd->opt_order;
     int sb;
     int64_t y;
     int32_t *quant_cof        = bd->quant_cof;
@@ -870,7 +888,7 @@ static int decode_var_block_data(ALSDecContext *ctx, ALSBlockData *bd)
             parcor_to_lpc(k, quant_cof, lpc_cof);
 
         // store previous samples in case that they have to be altered
-        if (bd->store_prev_samples)
+        if (*bd->store_prev_samples)
             memcpy(bd->prev_raw_samples, raw_samples - sconf->max_order,
                    sizeof(*bd->prev_raw_samples) * sconf->max_order);
 
@@ -891,9 +909,9 @@ static int decode_var_block_data(ALSDecContext *ctx, ALSBlockData *bd)
         }
 
         // reconstruct shifted signal
-        if (bd->shift_lsbs)
+        if (*bd->shift_lsbs)
             for (sb = -1; sb >= -sconf->max_order; sb--)
-                raw_samples[sb] >>= bd->shift_lsbs;
+                raw_samples[sb] >>= *bd->shift_lsbs;
     }
 
     // reverse linear prediction coefficients for efficiency
@@ -918,7 +936,7 @@ static int decode_var_block_data(ALSDecContext *ctx, ALSBlockData *bd)
     raw_samples = bd->raw_samples;
 
     // restore previous samples in case that they have been altered
-    if (bd->store_prev_samples)
+    if (*bd->store_prev_samples)
         memcpy(raw_samples - sconf->max_order, bd->prev_raw_samples,
                sizeof(*raw_samples) * sconf->max_order);
 
@@ -926,12 +944,13 @@ static int decode_var_block_data(ALSDecContext *ctx, ALSBlockData *bd)
 }
 
 
-/** Reads the block data.
+/** Read the block data.
  */
 static int read_block(ALSDecContext *ctx, ALSBlockData *bd)
 {
     GetBitContext *gb        = &ctx->gb;
 
+    *bd->shift_lsbs = 0;
     // read block type flag and read the samples accordingly
     if (get_bits1(gb)) {
         if (read_var_block_data(ctx, bd))
@@ -944,29 +963,29 @@ static int read_block(ALSDecContext *ctx, ALSBlockData *bd)
 }
 
 
-/** Decodes the block data.
+/** Decode the block data.
  */
 static int decode_block(ALSDecContext *ctx, ALSBlockData *bd)
 {
     unsigned int smp;
 
     // read block type flag and read the samples accordingly
-    if (bd->const_block)
+    if (*bd->const_block)
         decode_const_block_data(ctx, bd);
     else if (decode_var_block_data(ctx, bd))
         return -1;
 
     // TODO: read RLSLMS extension data
 
-    if (bd->shift_lsbs)
+    if (*bd->shift_lsbs)
         for (smp = 0; smp < bd->block_length; smp++)
-            bd->raw_samples[smp] <<= bd->shift_lsbs;
+            bd->raw_samples[smp] <<= *bd->shift_lsbs;
 
     return 0;
 }
 
 
-/** Reads and decodes block data successively.
+/** Read and decode block data successively.
  */
 static int read_decode_block(ALSDecContext *ctx, ALSBlockData *bd)
 {
@@ -983,7 +1002,7 @@ static int read_decode_block(ALSDecContext *ctx, ALSBlockData *bd)
 }
 
 
-/** Computes the number of samples left to decode for the current frame and
+/** Compute the number of samples left to decode for the current frame and
  *  sets these samples to zero.
  */
 static void zero_remaining(unsigned int b, unsigned int b_max,
@@ -999,7 +1018,7 @@ static void zero_remaining(unsigned int b, unsigned int b_max,
 }
 
 
-/** Decodes blocks independently.
+/** Decode blocks independently.
  */
 static int decode_blocks_ind(ALSDecContext *ctx, unsigned int ra_frame,
                              unsigned int c, const unsigned int *div_blocks,
@@ -1011,6 +1030,10 @@ static int decode_blocks_ind(ALSDecContext *ctx, unsigned int ra_frame,
     memset(&bd, 0, sizeof(ALSBlockData));
 
     bd.ra_block         = ra_frame;
+    bd.const_block      = ctx->const_block;
+    bd.shift_lsbs       = ctx->shift_lsbs;
+    bd.opt_order        = ctx->opt_order;
+    bd.store_prev_samples = ctx->store_prev_samples;
     bd.use_ltp          = ctx->use_ltp;
     bd.ltp_lag          = ctx->ltp_lag;
     bd.ltp_gain         = ctx->ltp_gain[0];
@@ -1021,7 +1044,6 @@ static int decode_blocks_ind(ALSDecContext *ctx, unsigned int ra_frame,
 
 
     for (b = 0; b < ctx->num_blocks; b++) {
-        bd.shift_lsbs       = 0;
         bd.block_length     = div_blocks[b];
 
         if (read_decode_block(ctx, &bd)) {
@@ -1037,7 +1059,7 @@ static int decode_blocks_ind(ALSDecContext *ctx, unsigned int ra_frame,
 }
 
 
-/** Decodes blocks dependently.
+/** Decode blocks dependently.
  */
 static int decode_blocks(ALSDecContext *ctx, unsigned int ra_frame,
                          unsigned int c, const unsigned int *div_blocks,
@@ -1051,6 +1073,10 @@ static int decode_blocks(ALSDecContext *ctx, unsigned int ra_frame,
     memset(bd, 0, 2 * sizeof(ALSBlockData));
 
     bd[0].ra_block         = ra_frame;
+    bd[0].const_block      = ctx->const_block;
+    bd[0].shift_lsbs       = ctx->shift_lsbs;
+    bd[0].opt_order        = ctx->opt_order;
+    bd[0].store_prev_samples = ctx->store_prev_samples;
     bd[0].use_ltp          = ctx->use_ltp;
     bd[0].ltp_lag          = ctx->ltp_lag;
     bd[0].ltp_gain         = ctx->ltp_gain[0];
@@ -1060,6 +1086,10 @@ static int decode_blocks(ALSDecContext *ctx, unsigned int ra_frame,
     bd[0].js_blocks        = *js_blocks;
 
     bd[1].ra_block         = ra_frame;
+    bd[1].const_block      = ctx->const_block;
+    bd[1].shift_lsbs       = ctx->shift_lsbs;
+    bd[1].opt_order        = ctx->opt_order;
+    bd[1].store_prev_samples = ctx->store_prev_samples;
     bd[1].use_ltp          = ctx->use_ltp;
     bd[1].ltp_lag          = ctx->ltp_lag;
     bd[1].ltp_gain         = ctx->ltp_gain[0];
@@ -1072,9 +1102,6 @@ static int decode_blocks(ALSDecContext *ctx, unsigned int ra_frame,
     for (b = 0; b < ctx->num_blocks; b++) {
         unsigned int s;
 
-        bd[0].shift_lsbs   = 0;
-        bd[1].shift_lsbs   = 0;
-
         bd[0].block_length = div_blocks[b];
         bd[1].block_length = div_blocks[b];
 
@@ -1118,7 +1145,7 @@ static int decode_blocks(ALSDecContext *ctx, unsigned int ra_frame,
 }
 
 
-/** Reads the channel data.
+/** Read the channel data.
   */
 static int read_channel_data(ALSDecContext *ctx, ALSChannelData *cd, int c)
 {
@@ -1192,6 +1219,10 @@ static int revert_channel_correlation(ALSDecContext *ctx, ALSBlockData *bd,
         return -1;
     }
 
+    bd->const_block = ctx->const_block + c;
+    bd->shift_lsbs  = ctx->shift_lsbs + c;
+    bd->opt_order   = ctx->opt_order + c;
+    bd->store_prev_samples = ctx->store_prev_samples + c;
     bd->use_ltp     = ctx->use_ltp + c;
     bd->ltp_lag     = ctx->ltp_lag + c;
     bd->ltp_gain    = ctx->ltp_gain[c];
@@ -1246,7 +1277,7 @@ static int revert_channel_correlation(ALSDecContext *ctx, ALSBlockData *bd,
 }
 
 
-/** Reads the frame data.
+/** Read the frame data.
  */
 static int read_frame_data(ALSDecContext *ctx, unsigned int ra_frame)
 {
@@ -1325,10 +1356,13 @@ static int read_frame_data(ALSDecContext *ctx, unsigned int ra_frame)
         get_block_sizes(ctx, div_blocks, &bs_info);
 
         for (b = 0; b < ctx->num_blocks; b++) {
-            bd.shift_lsbs   = 0;
             bd.block_length = div_blocks[b];
 
             for (c = 0; c < avctx->channels; c++) {
+                bd.const_block = ctx->const_block + c;
+                bd.shift_lsbs  = ctx->shift_lsbs + c;
+                bd.opt_order   = ctx->opt_order + c;
+                bd.store_prev_samples = ctx->store_prev_samples + c;
                 bd.use_ltp     = ctx->use_ltp + c;
                 bd.ltp_lag     = ctx->ltp_lag + c;
                 bd.ltp_gain    = ctx->ltp_gain[c];
@@ -1348,6 +1382,10 @@ static int read_frame_data(ALSDecContext *ctx, unsigned int ra_frame)
                     return -1;
 
             for (c = 0; c < avctx->channels; c++) {
+                bd.const_block = ctx->const_block + c;
+                bd.shift_lsbs  = ctx->shift_lsbs + c;
+                bd.opt_order   = ctx->opt_order + c;
+                bd.store_prev_samples = ctx->store_prev_samples + c;
                 bd.use_ltp     = ctx->use_ltp + c;
                 bd.ltp_lag     = ctx->ltp_lag + c;
                 bd.ltp_gain    = ctx->ltp_gain[c];
@@ -1375,7 +1413,7 @@ static int read_frame_data(ALSDecContext *ctx, unsigned int ra_frame)
 }
 
 
-/** Decodes an ALS frame.
+/** Decode an ALS frame.
  */
 static int decode_frame(AVCodecContext *avctx,
                         void *data, int *data_size,
@@ -1412,7 +1450,7 @@ static int decode_frame(AVCodecContext *avctx,
 
     // check for size of decoded data
     size = ctx->cur_frame_length * avctx->channels *
-           (av_get_bits_per_sample_format(avctx->sample_fmt) >> 3);
+           (av_get_bits_per_sample_fmt(avctx->sample_fmt) >> 3);
 
     if (size > *data_size) {
         av_log(avctx, AV_LOG_ERROR, "Decoded data exceeds buffer size.\n");
@@ -1437,6 +1475,59 @@ static int decode_frame(AVCodecContext *avctx,
         INTERLEAVE_OUTPUT(32)
     }
 
+    // update CRC
+    if (sconf->crc_enabled && avctx->error_recognition >= FF_ER_CAREFUL) {
+        int swap = HAVE_BIGENDIAN != sconf->msb_first;
+
+        if (ctx->avctx->bits_per_raw_sample == 24) {
+            int32_t *src = data;
+
+            for (sample = 0;
+                 sample < ctx->cur_frame_length * avctx->channels;
+                 sample++) {
+                int32_t v;
+
+                if (swap)
+                    v = av_bswap32(src[sample]);
+                else
+                    v = src[sample];
+                if (!HAVE_BIGENDIAN)
+                    v >>= 8;
+
+                ctx->crc = av_crc(ctx->crc_table, ctx->crc, (uint8_t*)(&v), 3);
+            }
+        } else {
+            uint8_t *crc_source;
+
+            if (swap) {
+                if (ctx->avctx->bits_per_raw_sample <= 16) {
+                    int16_t *src  = (int16_t*) data;
+                    int16_t *dest = (int16_t*) ctx->crc_buffer;
+                    for (sample = 0;
+                         sample < ctx->cur_frame_length * avctx->channels;
+                         sample++)
+                        *dest++ = av_bswap16(src[sample]);
+                } else {
+                    ctx->dsp.bswap_buf((uint32_t*)ctx->crc_buffer, data,
+                                       ctx->cur_frame_length * avctx->channels);
+                }
+                crc_source = ctx->crc_buffer;
+            } else {
+                crc_source = data;
+            }
+
+            ctx->crc = av_crc(ctx->crc_table, ctx->crc, crc_source, size);
+        }
+
+
+        // check CRC sums if this is the last frame
+        if (ctx->cur_frame_length != sconf->frame_length &&
+            ctx->crc_org != ctx->crc) {
+            av_log(avctx, AV_LOG_ERROR, "CRC error.\n");
+        }
+    }
+
+
     bytes_read = invalid_frame ? buffer_size :
                                  (get_bits_count(&ctx->gb) + 7) >> 3;
 
@@ -1444,7 +1535,7 @@ static int decode_frame(AVCodecContext *avctx,
 }
 
 
-/** Uninitializes the ALS decoder.
+/** Uninitialize the ALS decoder.
  */
 static av_cold int decode_end(AVCodecContext *avctx)
 {
@@ -1454,6 +1545,10 @@ static av_cold int decode_end(AVCodecContext *avctx)
 
     ff_bgmc_end(&ctx->bgmc_lut, &ctx->bgmc_lut_status);
 
+    av_freep(&ctx->const_block);
+    av_freep(&ctx->shift_lsbs);
+    av_freep(&ctx->opt_order);
+    av_freep(&ctx->store_prev_samples);
     av_freep(&ctx->use_ltp);
     av_freep(&ctx->ltp_lag);
     av_freep(&ctx->ltp_gain);
@@ -1469,12 +1564,13 @@ static av_cold int decode_end(AVCodecContext *avctx)
     av_freep(&ctx->chan_data);
     av_freep(&ctx->chan_data_buffer);
     av_freep(&ctx->reverted_channels);
+    av_freep(&ctx->crc_buffer);
 
     return 0;
 }
 
 
-/** Initializes the ALS decoder.
+/** Initialize the ALS decoder.
  */
 static av_cold int decode_init(AVCodecContext *avctx)
 {
@@ -1505,11 +1601,11 @@ static av_cold int decode_init(AVCodecContext *avctx)
         ff_bgmc_init(avctx, &ctx->bgmc_lut, &ctx->bgmc_lut_status);
 
     if (sconf->floating) {
-        avctx->sample_fmt          = SAMPLE_FMT_FLT;
+        avctx->sample_fmt          = AV_SAMPLE_FMT_FLT;
         avctx->bits_per_raw_sample = 32;
     } else {
         avctx->sample_fmt          = sconf->resolution > 1
-                                     ? SAMPLE_FMT_S32 : SAMPLE_FMT_S16;
+                                     ? AV_SAMPLE_FMT_S32 : AV_SAMPLE_FMT_S16;
         avctx->bits_per_raw_sample = (sconf->resolution + 1) * 8;
     }
 
@@ -1548,13 +1644,19 @@ static av_cold int decode_init(AVCodecContext *avctx)
     }
 
     // allocate and assign lag and gain data buffer for ltp mode
+    ctx->const_block     = av_malloc (sizeof(*ctx->const_block) * num_buffers);
+    ctx->shift_lsbs      = av_malloc (sizeof(*ctx->shift_lsbs)  * num_buffers);
+    ctx->opt_order       = av_malloc (sizeof(*ctx->opt_order)   * num_buffers);
+    ctx->store_prev_samples = av_malloc(sizeof(*ctx->store_prev_samples) * num_buffers);
     ctx->use_ltp         = av_mallocz(sizeof(*ctx->use_ltp)  * num_buffers);
     ctx->ltp_lag         = av_malloc (sizeof(*ctx->ltp_lag)  * num_buffers);
     ctx->ltp_gain        = av_malloc (sizeof(*ctx->ltp_gain) * num_buffers);
     ctx->ltp_gain_buffer = av_malloc (sizeof(*ctx->ltp_gain_buffer) *
                                       num_buffers * 5);
 
-    if (!ctx->use_ltp  || !ctx->ltp_lag ||
+    if (!ctx->const_block || !ctx->shift_lsbs ||
+        !ctx->opt_order || !ctx->store_prev_samples ||
+        !ctx->use_ltp  || !ctx->ltp_lag ||
         !ctx->ltp_gain || !ctx->ltp_gain_buffer) {
         av_log(avctx, AV_LOG_ERROR, "Allocating buffer memory failed.\n");
         decode_end(avctx);
@@ -1606,11 +1708,27 @@ static av_cold int decode_init(AVCodecContext *avctx)
     for (c = 1; c < avctx->channels; c++)
         ctx->raw_samples[c] = ctx->raw_samples[c - 1] + channel_size;
 
+    // allocate crc buffer
+    if (HAVE_BIGENDIAN != sconf->msb_first && sconf->crc_enabled &&
+        avctx->error_recognition >= FF_ER_CAREFUL) {
+        ctx->crc_buffer = av_malloc(sizeof(*ctx->crc_buffer) *
+                                    ctx->cur_frame_length *
+                                    avctx->channels *
+                                    (av_get_bits_per_sample_fmt(avctx->sample_fmt) >> 3));
+        if (!ctx->crc_buffer) {
+            av_log(avctx, AV_LOG_ERROR, "Allocating buffer memory failed.\n");
+            decode_end(avctx);
+            return AVERROR(ENOMEM);
+        }
+    }
+
+    dsputil_init(&ctx->dsp, avctx);
+
     return 0;
 }
 
 
-/** Flushes (resets) the frame ID after seeking.
+/** Flush (reset) the frame ID after seeking.
  */
 static av_cold void flush(AVCodecContext *avctx)
 {
@@ -1620,7 +1738,7 @@ static av_cold void flush(AVCodecContext *avctx)
 }
 
 
-AVCodec als_decoder = {
+AVCodec ff_als_decoder = {
     "als",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_MP4ALS,
diff --git a/libavcodec/amr.h b/libavcodec/amr.h
new file mode 100644
index 0000000..ae6e4d1
--- /dev/null
+++ b/libavcodec/amr.h
@@ -0,0 +1,68 @@
+/*
+ * Shared functions between AMR codecs
+ *
+ * Copyright (c) 2010 Marcelo Galvao Povoa
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_AMR_H
+#define AVCODEC_AMR_H
+
+#include "avcodec.h"
+
+#ifdef AMR_USE_16BIT_TABLES
+#define R_TABLE_TYPE uint16_t
+#else
+#define R_TABLE_TYPE uint8_t
+#endif
+
+/**
+ * Fill the frame structure variables from bitstream by parsing the
+ * given reordering table that uses the following format:
+ *
+ * Each field (16 bits) in the AMR Frame is stored as:
+ * - one byte for the number of bits in the field
+ * - one byte for the field index
+ * - then, one byte for each bit of the field (from most-significant to least)
+ *         of the position of that bit in the AMR frame.
+ *
+ * @param out pointer to the frame struct
+ * @param size the size in bytes of the frame struct
+ * @param data input bitstream after the frame header
+ * @param ord_table the reordering table as above
+ */
+static inline void ff_amr_bit_reorder(uint16_t *out, int size,
+                                      const uint8_t *data,
+                                      const R_TABLE_TYPE *ord_table)
+{
+    int field_size;
+
+    memset(out, 0, size);
+    while ((field_size = *ord_table++)) {
+        int field = 0;
+        int field_offset = *ord_table++;
+        while (field_size--) {
+           int bit = *ord_table++;
+           field <<= 1;
+           field |= data[bit >> 3] >> (bit & 7) & 1;
+        }
+        out[field_offset] = field;
+    }
+}
+
+#endif /* AVCODEC_AMR_H */
diff --git a/libavcodec/amrnbdata.h b/libavcodec/amrnbdata.h
index 2f21439..d6d1f34 100644
--- a/libavcodec/amrnbdata.h
+++ b/libavcodec/amrnbdata.h
@@ -3,20 +3,20 @@
  * Copyright (c) 2006-2007 Robert Swain
  * Copyright (c) 2009 Colin McQuillan
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/amrnbdec.c b/libavcodec/amrnbdec.c
index d3fa765..4e24e26 100644
--- a/libavcodec/amrnbdec.c
+++ b/libavcodec/amrnbdec.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2006-2007 Robert Swain
  * Copyright (c) 2009 Colin McQuillan
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -52,6 +52,7 @@
 #include "acelp_vectors.h"
 #include "acelp_pitch_delay.h"
 #include "lsp.h"
+#include "amr.h"
 
 #include "amrnbdata.h"
 
@@ -153,7 +154,7 @@ static av_cold int amrnb_decode_init(AVCodecContext *avctx)
     AMRContext *p = avctx->priv_data;
     int i;
 
-    avctx->sample_fmt = SAMPLE_FMT_FLT;
+    avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
 
     // p->excitation always points to the same position in p->excitation_buf
     p->excitation = &p->excitation_buf[PITCH_DELAY_MAX + LP_FILTER_ORDER + 1];
@@ -195,24 +196,9 @@ static enum Mode unpack_bitstream(AMRContext *p, const uint8_t *buf,
     p->bad_frame_indicator = !get_bits1(&gb); // quality bit
     skip_bits(&gb, 2);                        // two padding bits
 
-    if (mode < MODE_DTX) {
-        uint16_t *data = (uint16_t *)&p->frame;
-        const uint8_t *order = amr_unpacking_bitmaps_per_mode[mode];
-        int field_size;
-
-        memset(&p->frame, 0, sizeof(AMRNBFrame));
-        buf++;
-        while ((field_size = *order++)) {
-            int field = 0;
-            int field_offset = *order++;
-            while (field_size--) {
-               int bit = *order++;
-               field <<= 1;
-               field |= buf[bit >> 3] >> (bit & 7) & 1;
-            }
-            data[field_offset] = field;
-        }
-    }
+    if (mode < MODE_DTX)
+        ff_amr_bit_reorder((uint16_t *) &p->frame, sizeof(AMRNBFrame), buf + 1,
+                           amr_unpacking_bitmaps_per_mode[mode]);
 
     return mode;
 }
@@ -222,20 +208,6 @@ static enum Mode unpack_bitstream(AMRContext *p, const uint8_t *buf,
 /// @{
 
 /**
- * Convert an lsf vector into an lsp vector.
- *
- * @param lsf               input lsf vector
- * @param lsp               output lsp vector
- */
-static void lsf2lsp(const float *lsf, double *lsp)
-{
-    int i;
-
-    for (i = 0; i < LP_FILTER_ORDER; i++)
-        lsp[i] = cos(2.0 * M_PI * lsf[i]);
-}
-
-/**
  * Interpolate the LSF vector (used for fixed gain smoothing).
  * The interpolation is done over all four subframes even in MODE_12k2.
  *
@@ -283,7 +255,7 @@ static void lsf2lsp_for_mode12k2(AMRContext *p, double lsp[LP_FILTER_ORDER],
     }
 
     if (update)
-        memcpy(p->prev_lsf_r, lsf_r, LP_FILTER_ORDER * sizeof(float));
+        memcpy(p->prev_lsf_r, lsf_r, LP_FILTER_ORDER * sizeof(*lsf_r));
 
     for (i = 0; i < LP_FILTER_ORDER; i++)
         lsf_q[i] = lsf_r[i] * (LSF_R_FAC / 8000.0) + lsf_no_r[i] * (1.0 / 8000.0);
@@ -293,7 +265,7 @@ static void lsf2lsp_for_mode12k2(AMRContext *p, double lsp[LP_FILTER_ORDER],
     if (update)
         interpolate_lsf(p->lsf_q, lsf_q);
 
-    lsf2lsp(lsf_q, lsp);
+    ff_acelp_lsf2lspd(lsp, lsf_q, LP_FILTER_ORDER);
 }
 
 /**
@@ -357,7 +329,7 @@ static void lsf2lsp_3(AMRContext *p)
     interpolate_lsf(p->lsf_q, lsf_q);
     memcpy(p->prev_lsf_r, lsf_r, LP_FILTER_ORDER * sizeof(*lsf_r));
 
-    lsf2lsp(lsf_q, p->lsp[3]);
+    ff_acelp_lsf2lspd(p->lsp[3], lsf_q, LP_FILTER_ORDER);
 
     // interpolate LSP vectors at subframes 1, 2 and 3
     for (i = 1; i <= 3; i++)
@@ -1064,7 +1036,7 @@ static int amrnb_decode_frame(AVCodecContext *avctx, void *data, int *data_size,
 }
 
 
-AVCodec amrnb_decoder = {
+AVCodec ff_amrnb_decoder = {
     .name           = "amrnb",
     .type           = AVMEDIA_TYPE_AUDIO,
     .id             = CODEC_ID_AMR_NB,
@@ -1072,5 +1044,5 @@ AVCodec amrnb_decoder = {
     .init           = amrnb_decode_init,
     .decode         = amrnb_decode_frame,
     .long_name      = NULL_IF_CONFIG_SMALL("Adaptive Multi-Rate NarrowBand"),
-    .sample_fmts    = (enum SampleFormat[]){SAMPLE_FMT_FLT,SAMPLE_FMT_NONE},
+    .sample_fmts    = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_FLT,AV_SAMPLE_FMT_NONE},
 };
diff --git a/libavcodec/amrwbdata.h b/libavcodec/amrwbdata.h
new file mode 100644
index 0000000..f4db99e
--- /dev/null
+++ b/libavcodec/amrwbdata.h
@@ -0,0 +1,1890 @@
+/*
+ * AMR wideband data and definitions
+ * Copyright (c) 2010 Marcelo Galvao Povoa
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * AMR wideband data and definitions
+ */
+
+#ifndef AVCODEC_AMRWBDATA_H
+#define AVCODEC_AMRWBDATA_H
+
+#include <stdint.h>
+#include <stddef.h>
+
+#define LP_ORDER            16                ///< linear predictive coding filter order
+#define LP_ORDER_16k        20                ///< lpc filter order at 16kHz
+#define HB_FIR_SIZE         30                ///< amount of past data needed by HB filters
+#define UPS_FIR_SIZE        12                ///< upsampling filter size
+#define UPS_MEM_SIZE        (2 * UPS_FIR_SIZE)
+
+#define MIN_ISF_SPACING     (128.0 / 32768.0) ///< minimum isf gap
+#define PRED_FACTOR         (1.0 / 3.0)
+#define MIN_ENERGY         -14.0              ///< initial innnovation energy (dB)
+#define ENERGY_MEAN         30.0              ///< mean innovation energy (dB) in all modes
+#define PREEMPH_FAC         0.68              ///< factor used to de-emphasize synthesis
+
+#define AMRWB_SFR_SIZE      64                ///< samples per subframe at 12.8 kHz
+#define AMRWB_SFR_SIZE_16k  80                ///< samples per subframe at 16 kHz
+#define AMRWB_P_DELAY_MAX   231               ///< maximum pitch delay value
+#define AMRWB_P_DELAY_MIN   34
+
+/* Relative mode ordering is sensitive */
+enum Mode {
+    MODE_6k60 = 0,                         ///< 6.60 kbit/s
+    MODE_8k85,                             ///< 8.85 kbit/s
+    MODE_12k65,                            ///< 12.65 kbit/s
+    MODE_14k25,                            ///< 14.25 kbit/s
+    MODE_15k85,                            ///< 15.85 kbit/s
+    MODE_18k25,                            ///< 18.25 kbit/s
+    MODE_19k85,                            ///< 19.85 kbit/s
+    MODE_23k05,                            ///< 23.05 kbit/s
+    MODE_23k85,                            ///< 23.85 kbit/s
+    MODE_SID,                              ///< comfort noise frame
+    /* 10-13:  Future use */
+    SP_LOST = 14,                          ///< speech lost
+    NO_DATA                                ///< no transmission
+};
+
+/* All decoded parameters in these structs must be 2 bytes long
+ * because of the direct indexing at the frame parsing */
+typedef struct {
+    uint16_t adap;                         ///< adaptive codebook index
+    uint16_t ltp;                          ///< ltp-filtering flag
+    uint16_t vq_gain;                      ///< VQ adaptive and innovative gains
+    uint16_t hb_gain;                      ///< high-band energy index (mode 23k85 only)
+    uint16_t pul_ih[4];                    ///< MSBs part of codebook index (high modes only)
+    uint16_t pul_il[4];                    ///< LSBs part of codebook index
+} AMRWBSubFrame;
+
+typedef struct {
+    uint16_t vad;                          ///< voice activity detection flag
+    uint16_t isp_id[7];                    ///< index of ISP subvectors
+    AMRWBSubFrame subframe[4];             ///< data for subframes
+} AMRWBFrame;
+
+/** The index of a frame parameter */
+#define AMR_BIT(field)                  (offsetof(AMRWBFrame, field) >> 1)
+/** The index of a subframe-specific parameter */
+#define AMR_OF(frame_num, variable)     AMR_BIT(subframe[frame_num].variable)
+
+//As defined in 3GPP TS 26.201 V9.0.0
+//Tables for bit parsing in Core Frame speech frames
+//The reordered bits are in order of decreasing importance and
+//may be contiguously separated in Class A, B and C bits.
+
+// Each field in AMRWBFrame is stored as:
+// * one byte for the number of bits in the field
+// * one byte for the field index
+// * then, one byte for each bit of the field (from most-significant to least)
+//         of the position of that bit in the AMR frame.
+static const uint16_t order_MODE_6k60[] = {
+     1,         AMR_BIT(vad),   7,
+     8,   AMR_BIT(isp_id[0]),  24,  33,  39,  12,   6,   5,   4,  13,
+     8,   AMR_BIT(isp_id[1]),  65,  79,  64,  78,  51,  61,  71,  70,
+     7,   AMR_BIT(isp_id[2]),  52,  55,  44,  54,  53,  43,  42,
+     7,   AMR_BIT(isp_id[3]),  60,  59,  58,  57,  56,  75,  74,
+     6,   AMR_BIT(isp_id[4]),  73,  72,  86,  87,  85,  84,
+     8,      AMR_OF(0, adap),  11,  10,   9,   8,  28,  27,  49,  69,
+     6, AMR_OF(0, pul_il[0]),  83,  91,  99, 107, 115, 123,
+     6, AMR_OF(0, pul_il[1]),  82, 103, 111, 119, 127, 135,
+     6,   AMR_OF(0, vq_gain),  38,  23,  34,  19,   3,  15,
+     5,      AMR_OF(1, adap),  32,  41,  63,  67,  77,
+     6, AMR_OF(1, pul_il[0]),  81,  90,  98, 106, 114, 122,
+     6, AMR_OF(1, pul_il[1]),  80, 102, 110, 118, 126, 134,
+     6,   AMR_OF(1, vq_gain),  26,  22,  36,  18,   2,  14,
+     5,      AMR_OF(2, adap),  45,  40,  50,  48,  68,
+     6, AMR_OF(2, pul_il[0]),  95,  89,  97, 105, 113, 121,
+     6, AMR_OF(2, pul_il[1]),  94, 101, 109, 117, 125, 133,
+     6,   AMR_OF(2, vq_gain),  37,  21,  35,  17,   1,  31,
+     5,      AMR_OF(3, adap),  47,  46,  62,  66,  76,
+     6, AMR_OF(3, pul_il[0]),  93,  88,  96, 104, 112, 120,
+     6, AMR_OF(3, pul_il[1]),  92, 100, 108, 116, 124, 132,
+     6,   AMR_OF(3, vq_gain),  25,  20,  29,  16,   0,  30,
+     0
+};
+
+static const uint16_t order_MODE_8k85[] = {
+     1,         AMR_BIT(vad),   7,
+     8,   AMR_BIT(isp_id[0]),  47,  32,   2,   6,   3,   5,   4,  60,
+     8,   AMR_BIT(isp_id[1]),  69,  50,  67,  41,  51,  49,  59,  53,
+     6,   AMR_BIT(isp_id[2]),  40,  55,  43,  54,  42,  62,
+     7,   AMR_BIT(isp_id[3]),  63,  48,  52,  61,  77,  78,  72,
+     7,   AMR_BIT(isp_id[4]),  85,  56,  86,  68,  74,  73,  81,
+     5,   AMR_BIT(isp_id[5]),  82,  95,  80,  94,  91,
+     5,   AMR_BIT(isp_id[6]),  90,  89,  88, 103,  87,
+     8,      AMR_OF(0, adap),   1,   0,  15,  35,  33,  58,  64,  84,
+     5, AMR_OF(0, pul_il[0]), 102, 118, 134, 150, 166,
+     5, AMR_OF(0, pul_il[1]), 101, 114, 130, 146, 162,
+     5, AMR_OF(0, pul_il[2]), 100, 126, 142, 158, 174,
+     5, AMR_OF(0, pul_il[3]),  99, 122, 138, 154, 170,
+     6,   AMR_OF(0, vq_gain),  11,  39,  19,  31,  27,  23,
+     5,      AMR_OF(1, adap),  46,  71,  66,  76,  93,
+     5, AMR_OF(1, pul_il[0]),  98, 117, 133, 149, 165,
+     5, AMR_OF(1, pul_il[1]),  97, 113, 129, 145, 161,
+     5, AMR_OF(1, pul_il[2]),  96, 125, 141, 157, 173,
+     5, AMR_OF(1, pul_il[3]), 111, 121, 137, 153, 169,
+     6,   AMR_OF(1, vq_gain),  10,  38,  18,  30,  26,  22,
+     8,      AMR_OF(2, adap),  14,  13,  12,  34,  45,  57,  79,  83,
+     5, AMR_OF(2, pul_il[0]), 110, 116, 132, 148, 164,
+     5, AMR_OF(2, pul_il[1]), 109, 112, 128, 144, 160,
+     5, AMR_OF(2, pul_il[2]), 108, 124, 140, 156, 172,
+     5, AMR_OF(2, pul_il[3]), 107, 120, 136, 152, 168,
+     6,   AMR_OF(2, vq_gain),   9,  37,  17,  29,  25,  21,
+     5,      AMR_OF(3, adap),  44,  70,  65,  75,  92,
+     5, AMR_OF(3, pul_il[0]), 106, 115, 131, 147, 163,
+     5, AMR_OF(3, pul_il[1]), 105, 127, 143, 159, 175,
+     5, AMR_OF(3, pul_il[2]), 104, 123, 139, 155, 171,
+     5, AMR_OF(3, pul_il[3]), 119, 135, 151, 167, 183,
+     6,   AMR_OF(3, vq_gain),   8,  36,  16,  28,  24,  20,
+     0
+};
+
+static const uint16_t order_MODE_12k65[] = {
+     1,         AMR_BIT(vad),   7,
+     8,   AMR_BIT(isp_id[0]),  55,  40,  14,   6,  15,   5,   0,  68,
+     8,   AMR_BIT(isp_id[1]),  77,  58,  75,  49,  59,  57,  67,  61,
+     6,   AMR_BIT(isp_id[2]),  48,  63,  51,  62,  50,  70,
+     7,   AMR_BIT(isp_id[3]),  71,  56,  60,  69,  85,  86,  80,
+     7,   AMR_BIT(isp_id[4]),  93,  64,  94,  76,  82,  81,  89,
+     5,   AMR_BIT(isp_id[5]),  90, 103,  88, 102,  99,
+     5,   AMR_BIT(isp_id[6]),  98,  97,  96, 111,  95,
+     9,      AMR_OF(0, adap),  13,  12,  11,  10,   9,  41,  66,  72,
+                               92,
+     1,       AMR_OF(0, ltp), 110,
+     9, AMR_OF(0, pul_il[0]), 106, 122, 154, 186, 218, 134, 166, 198,
+                              230,
+     9, AMR_OF(0, pul_il[1]), 105, 130, 162, 194, 226, 142, 174, 206,
+                              238,
+     9, AMR_OF(0, pul_il[2]), 104, 138, 170, 202, 234, 150, 182, 214,
+                              246,
+     9, AMR_OF(0, pul_il[3]), 119, 146, 178, 210, 242, 158, 190, 222,
+                              254,
+     7,   AMR_OF(0, vq_gain),   4,  19,  45,  27,  39,  33,  31,
+     6,      AMR_OF(1, adap),  35,  54,  79,  74,  84, 101,
+     1,       AMR_OF(1, ltp), 109,
+     9, AMR_OF(1, pul_il[0]), 118, 121, 153, 185, 217, 133, 165, 197,
+                              229,
+     9, AMR_OF(1, pul_il[1]), 117, 129, 161, 193, 225, 141, 173, 205,
+                              237,
+     9, AMR_OF(1, pul_il[2]), 116, 137, 169, 201, 233, 149, 181, 213,
+                              245,
+     9, AMR_OF(1, pul_il[3]), 115, 145, 177, 209, 241, 157, 189, 221,
+                              253,
+     7,   AMR_OF(1, vq_gain),   3,  18,  44,  26,  38,  32,  30,
+     9,      AMR_OF(2, adap),   8,  23,  22,  21,  20,  52,  65,  87,
+                               91,
+     1,       AMR_OF(2, ltp), 108,
+     9, AMR_OF(2, pul_il[0]), 114, 120, 152, 184, 216, 132, 164, 196,
+                              228,
+     9, AMR_OF(2, pul_il[1]), 113, 128, 160, 192, 224, 140, 172, 204,
+                              236,
+     9, AMR_OF(2, pul_il[2]), 112, 136, 168, 200, 232, 148, 180, 212,
+                              244,
+     9, AMR_OF(2, pul_il[3]), 127, 144, 176, 208, 240, 156, 188, 220,
+                              252,
+     7,   AMR_OF(2, vq_gain),   2,  17,  43,  25,  37,  47,  29,
+     6,      AMR_OF(3, adap),  34,  53,  78,  73,  83, 100,
+     1,       AMR_OF(3, ltp), 107,
+     9, AMR_OF(3, pul_il[0]), 126, 135, 167, 199, 231, 131, 163, 195,
+                              227,
+     9, AMR_OF(3, pul_il[1]), 125, 143, 175, 207, 239, 139, 171, 203,
+                              235,
+     9, AMR_OF(3, pul_il[2]), 124, 151, 183, 215, 247, 147, 179, 211,
+                              243,
+     9, AMR_OF(3, pul_il[3]), 123, 159, 191, 223, 255, 155, 187, 219,
+                              251,
+     7,   AMR_OF(3, vq_gain),   1,  16,  42,  24,  36,  46,  28,
+     0
+};
+
+static const uint16_t order_MODE_14k25[] = {
+     1,         AMR_BIT(vad),   7,
+     8,   AMR_BIT(isp_id[0]),  55,  40,  14,   6,  15,   5,   0,  68,
+     8,   AMR_BIT(isp_id[1]),  77,  58,  75,  49,  59,  57,  67,  61,
+     6,   AMR_BIT(isp_id[2]),  48,  63,  51,  62,  50,  70,
+     7,   AMR_BIT(isp_id[3]),  71,  56,  60,  69,  85,  86,  80,
+     7,   AMR_BIT(isp_id[4]),  93,  64,  94,  76,  82,  81,  89,
+     5,   AMR_BIT(isp_id[5]),  90, 103,  88, 102,  99,
+     5,   AMR_BIT(isp_id[6]),  98,  97,  96, 111,  95,
+     9,      AMR_OF(0, adap),  13,  12,  11,  10,   9,  41,  66,  72,
+                               92,
+     1,       AMR_OF(0, ltp), 110,
+    13, AMR_OF(0, pul_il[0]), 114, 186, 210, 234, 258, 106, 126, 162,
+                              170, 198, 222, 246, 270,
+    13, AMR_OF(0, pul_il[1]), 122, 194, 218, 242, 266, 118, 134, 174,
+                              182, 206, 230, 254, 278,
+     9, AMR_OF(0, pul_il[2]), 130, 138, 146, 154, 178, 202, 226, 250,
+                              274,
+     9, AMR_OF(0, pul_il[3]), 142, 150, 158, 166, 190, 214, 238, 262,
+                              286,
+     7,   AMR_OF(0, vq_gain),   4,  19,  45,  27,  39,  33,  31,
+     6,      AMR_OF(1, adap),  35,  54,  79,  74,  84, 101,
+     1,       AMR_OF(1, ltp), 109,
+    13, AMR_OF(1, pul_il[0]), 113, 185, 209, 233, 257, 105, 125, 161,
+                              169, 197, 221, 245, 269,
+    13, AMR_OF(1, pul_il[1]), 121, 193, 217, 241, 265, 117, 133, 173,
+                              181, 205, 229, 253, 277,
+     9, AMR_OF(1, pul_il[2]), 129, 137, 145, 153, 177, 201, 225, 249,
+                              273,
+     9, AMR_OF(1, pul_il[3]), 141, 149, 157, 165, 189, 213, 237, 261,
+                              285,
+     7,   AMR_OF(1, vq_gain),   3,  18,  44,  26,  38,  32,  30,
+     9,      AMR_OF(2, adap),   8,  23,  22,  21,  20,  52,  65,  87,
+                               91,
+     1,       AMR_OF(2, ltp), 108,
+    13, AMR_OF(2, pul_il[0]), 112, 184, 208, 232, 256, 104, 124, 160,
+                              168, 196, 220, 244, 268,
+    13, AMR_OF(2, pul_il[1]), 120, 192, 216, 240, 264, 116, 132, 172,
+                              180, 204, 228, 252, 276,
+     9, AMR_OF(2, pul_il[2]), 128, 136, 144, 152, 176, 200, 224, 248,
+                              272,
+     9, AMR_OF(2, pul_il[3]), 140, 148, 156, 164, 188, 212, 236, 260,
+                              284,
+     7,   AMR_OF(2, vq_gain),   2,  17,  43,  25,  37,  47,  29,
+     6,      AMR_OF(3, adap),  34,  53,  78,  73,  83, 100,
+     1,       AMR_OF(3, ltp), 107,
+    13, AMR_OF(3, pul_il[0]), 127, 199, 223, 247, 271, 119, 123, 175,
+                              183, 195, 219, 243, 267,
+    13, AMR_OF(3, pul_il[1]), 135, 207, 231, 255, 279, 115, 131, 171,
+                              179, 203, 227, 251, 275,
+     9, AMR_OF(3, pul_il[2]), 143, 151, 159, 167, 191, 215, 239, 263,
+                              287,
+     9, AMR_OF(3, pul_il[3]), 139, 147, 155, 163, 187, 211, 235, 259,
+                              283,
+     7,   AMR_OF(3, vq_gain),   1,  16,  42,  24,  36,  46,  28,
+     0
+};
+
+static const uint16_t order_MODE_15k85[] = {
+     1,         AMR_BIT(vad),   7,
+     8,   AMR_BIT(isp_id[0]),  55,  40,  14,   6,  15,   5,   0,  68,
+     8,   AMR_BIT(isp_id[1]),  77,  58,  75,  49,  59,  57,  67,  61,
+     6,   AMR_BIT(isp_id[2]),  48,  63,  51,  62,  50,  70,
+     7,   AMR_BIT(isp_id[3]),  71,  56,  60,  69,  85,  86,  80,
+     7,   AMR_BIT(isp_id[4]),  93,  64,  94,  76,  82,  81,  89,
+     5,   AMR_BIT(isp_id[5]),  90, 103,  88, 102,  99,
+     5,   AMR_BIT(isp_id[6]),  98,  97,  96, 111,  95,
+     9,      AMR_OF(0, adap),  13,  12,  11,  10,   9,  41,  66,  72,
+                               92,
+     1,       AMR_OF(0, ltp), 110,
+    13, AMR_OF(0, pul_il[0]), 122, 154, 170, 218, 266, 138, 106, 182,
+                              230, 278, 178, 226, 274,
+    13, AMR_OF(0, pul_il[1]), 134, 166, 190, 238, 286, 150, 118, 186,
+                              234, 282, 198, 246, 294,
+    13, AMR_OF(0, pul_il[2]), 130, 162, 194, 242, 290, 146, 114, 206,
+                              254, 302, 202, 250, 298,
+    13, AMR_OF(0, pul_il[3]), 142, 174, 214, 262, 310, 158, 126, 210,
+                              258, 306, 222, 270, 318,
+     7,   AMR_OF(0, vq_gain),   4,  19,  45,  27,  39,  33,  31,
+     6,      AMR_OF(1, adap),  35,  54,  79,  74,  84, 101,
+     1,       AMR_OF(1, ltp), 109,
+    13, AMR_OF(1, pul_il[0]), 121, 153, 169, 217, 265, 137, 105, 181,
+                              229, 277, 177, 225, 273,
+    13, AMR_OF(1, pul_il[1]), 133, 165, 189, 237, 285, 149, 117, 185,
+                              233, 281, 197, 245, 293,
+    13, AMR_OF(1, pul_il[2]), 129, 161, 193, 241, 289, 145, 113, 205,
+                              253, 301, 201, 249, 297,
+    13, AMR_OF(1, pul_il[3]), 141, 173, 213, 261, 309, 157, 125, 209,
+                              257, 305, 221, 269, 317,
+     7,   AMR_OF(1, vq_gain),   3,  18,  44,  26,  38,  32,  30,
+     9,      AMR_OF(2, adap),   8,  23,  22,  21,  20,  52,  65,  87,
+                               91,
+     1,       AMR_OF(2, ltp), 108,
+    13, AMR_OF(2, pul_il[0]), 120, 152, 168, 216, 264, 136, 104, 180,
+                              228, 276, 176, 224, 272,
+    13, AMR_OF(2, pul_il[1]), 132, 164, 188, 236, 284, 148, 116, 184,
+                              232, 280, 196, 244, 292,
+    13, AMR_OF(2, pul_il[2]), 128, 160, 192, 240, 288, 144, 112, 204,
+                              252, 300, 200, 248, 296,
+    13, AMR_OF(2, pul_il[3]), 140, 172, 212, 260, 308, 156, 124, 208,
+                              256, 304, 220, 268, 316,
+     7,   AMR_OF(2, vq_gain),   2,  17,  43,  25,  37,  47,  29,
+     6,      AMR_OF(3, adap),  34,  53,  78,  73,  83, 100,
+     1,       AMR_OF(3, ltp), 107,
+    13, AMR_OF(3, pul_il[0]), 135, 167, 183, 231, 279, 151, 119, 179,
+                              227, 275, 191, 239, 287,
+    13, AMR_OF(3, pul_il[1]), 131, 163, 187, 235, 283, 147, 115, 199,
+                              247, 295, 195, 243, 291,
+    13, AMR_OF(3, pul_il[2]), 143, 175, 207, 255, 303, 159, 127, 203,
+                              251, 299, 215, 263, 311,
+    13, AMR_OF(3, pul_il[3]), 139, 171, 211, 259, 307, 155, 123, 223,
+                              271, 319, 219, 267, 315,
+     7,   AMR_OF(3, vq_gain),   1,  16,  42,  24,  36,  46,  28,
+     0
+};
+
+static const uint16_t order_MODE_18k25[] = {
+     1,         AMR_BIT(vad),   7,
+     8,   AMR_BIT(isp_id[0]),  55,  40,  14,   6,  15,   5,   0,  68,
+     8,   AMR_BIT(isp_id[1]),  77,  58,  75,  49,  59,  57,  67,  61,
+     6,   AMR_BIT(isp_id[2]),  48,  63,  51,  62,  50,  70,
+     7,   AMR_BIT(isp_id[3]),  71,  56,  60,  69,  85,  86,  80,
+     7,   AMR_BIT(isp_id[4]),  93,  64,  94,  76,  82,  81,  89,
+     5,   AMR_BIT(isp_id[5]),  90, 103,  88, 102,  99,
+     5,   AMR_BIT(isp_id[6]),  98,  97,  96, 111,  95,
+     9,      AMR_OF(0, adap),  13,  12,  11,  10,   9,  41,  66,  72,
+                               92,
+     1,       AMR_OF(0, ltp), 110,
+     2, AMR_OF(0, pul_ih[0]), 124, 115,
+     2, AMR_OF(0, pul_ih[1]), 150, 117,
+     2, AMR_OF(0, pul_ih[2]), 129, 114,
+     2, AMR_OF(0, pul_ih[3]), 121, 131,
+    14, AMR_OF(0, pul_il[0]), 161, 257, 343, 199, 177, 303, 204, 173,
+                              168, 260, 277, 307, 338, 128,
+    14, AMR_OF(0, pul_il[1]), 194, 286, 347, 222, 214, 316, 236, 152,
+                              166, 242, 284, 308, 344, 142,
+    14, AMR_OF(0, pul_il[2]), 169, 273, 353, 202, 189, 311, 240, 200,
+                              171, 261, 309, 296, 345, 130,
+    14, AMR_OF(0, pul_il[3]), 198, 275, 349, 187, 163, 282, 193, 195,
+                              175, 234, 265, 289, 328, 119,
+     7,   AMR_OF(0, vq_gain),   4,  19,  45,  27,  39,  33,  31,
+     6,      AMR_OF(1, adap),  35,  54,  79,  74,  84, 101,
+     1,       AMR_OF(1, ltp), 109,
+     2, AMR_OF(1, pul_ih[0]), 139, 104,
+     2, AMR_OF(1, pul_ih[1]), 135, 118,
+     2, AMR_OF(1, pul_ih[2]), 112, 127,
+     2, AMR_OF(1, pul_ih[3]), 140, 141,
+    14, AMR_OF(1, pul_il[0]), 179, 276, 340, 225, 223, 321, 235, 190,
+                              182, 271, 310, 315, 352, 125,
+    14, AMR_OF(1, pul_il[1]), 153, 264, 329, 232, 209, 323, 231, 165,
+                              191, 279, 290, 312, 367, 134,
+    14, AMR_OF(1, pul_il[2]), 167, 269, 341, 205, 197, 298, 224, 160,
+                              170, 259, 280, 317, 357, 148,
+    14, AMR_OF(1, pul_il[3]), 203, 272, 342, 227, 192, 299, 233, 172,
+                              183, 256, 283, 326, 355, 106,
+     7,   AMR_OF(1, vq_gain),   3,  18,  44,  26,  38,  32,  30,
+     9,      AMR_OF(2, adap),   8,  23,  22,  21,  20,  52,  65,  87,
+                               91,
+     1,       AMR_OF(2, ltp), 108,
+     2, AMR_OF(2, pul_ih[0]), 144, 120,
+     2, AMR_OF(2, pul_ih[1]), 157, 123,
+     2, AMR_OF(2, pul_ih[2]), 145, 138,
+     2, AMR_OF(2, pul_ih[3]), 132, 154,
+    14, AMR_OF(2, pul_il[0]), 241, 319, 365, 252, 253, 331, 254, 230,
+                              220, 263, 285, 314, 364, 156,
+    14, AMR_OF(2, pul_il[1]), 247, 291, 339, 249, 250, 332, 267, 196,
+                              207, 268, 304, 324, 356, 158,
+    14, AMR_OF(2, pul_il[2]), 210, 300, 348, 243, 237, 333, 246, 206,
+                              219, 266, 318, 335, 363, 159,
+    14, AMR_OF(2, pul_il[3]), 239, 306, 366, 221, 226, 297, 251, 184,
+                              178, 258, 292, 305, 346, 116,
+     7,   AMR_OF(2, vq_gain),   2,  17,  43,  25,  37,  47,  29,
+     6,      AMR_OF(3, adap),  34,  53,  78,  73,  83, 100,
+     1,       AMR_OF(3, ltp), 107,
+     2, AMR_OF(3, pul_ih[0]), 143, 126,
+     2, AMR_OF(3, pul_ih[1]), 137, 122,
+     2, AMR_OF(3, pul_ih[2]), 149, 105,
+     2, AMR_OF(3, pul_ih[3]), 133, 136,
+    14, AMR_OF(3, pul_il[0]), 162, 287, 337, 244, 229, 322, 218, 180,
+                              186, 262, 274, 288, 351, 146,
+    14, AMR_OF(3, pul_il[1]), 212, 294, 358, 248, 228, 334, 215, 174,
+                              176, 270, 293, 301, 354, 147,
+    14, AMR_OF(3, pul_il[2]), 185, 327, 336, 211, 213, 313, 245, 181,
+                              188, 255, 281, 325, 350, 151,
+    14, AMR_OF(3, pul_il[3]), 201, 295, 359, 216, 208, 320, 238, 164,
+                              155, 217, 278, 302, 330, 113,
+     7,   AMR_OF(3, vq_gain),   1,  16,  42,  24,  36,  46,  28,
+     0
+};
+
+static const uint16_t order_MODE_19k85[] = {
+     1,         AMR_BIT(vad),   7,
+     8,   AMR_BIT(isp_id[0]),  55,  40,  14,   6,  15,   5,   0,  68,
+     8,   AMR_BIT(isp_id[1]),  77,  58,  75,  49,  59,  57,  67,  61,
+     6,   AMR_BIT(isp_id[2]),  48,  63,  51,  62,  50,  70,
+     7,   AMR_BIT(isp_id[3]),  71,  56,  60,  69,  85,  86,  80,
+     7,   AMR_BIT(isp_id[4]),  93,  64,  94,  76,  82,  81,  89,
+     5,   AMR_BIT(isp_id[5]),  90, 103,  88, 102,  99,
+     5,   AMR_BIT(isp_id[6]),  98,  97,  96, 111,  95,
+     9,      AMR_OF(0, adap),  13,  12,  11,  10,   9,  41,  66,  72,
+                               92,
+     1,       AMR_OF(0, ltp), 110,
+    10, AMR_OF(0, pul_ih[0]), 134, 153, 263, 342, 399, 154, 106, 177,
+                              317, 265,
+    10, AMR_OF(0, pul_ih[1]), 128, 167, 270, 351, 385, 160, 105, 213,
+                              329, 259,
+     2, AMR_OF(0, pul_ih[2]), 123, 147,
+     2, AMR_OF(0, pul_ih[3]), 131, 143,
+    10, AMR_OF(0, pul_il[0]), 346, 118, 170, 201, 296, 368, 250, 284,
+                              341, 391,
+    10, AMR_OF(0, pul_il[1]), 345, 104, 166, 196, 281, 374, 242, 269,
+                              327, 390,
+    14, AMR_OF(0, pul_il[2]), 141, 171, 291, 364, 229, 210, 308, 228,
+                              206, 200, 258, 295, 313, 361,
+    14, AMR_OF(0, pul_il[3]), 144, 188, 282, 366, 217, 216, 309, 218,
+                              193, 182, 245, 287, 300, 367,
+     7,   AMR_OF(0, vq_gain),   4,  19,  45,  27,  39,  33,  31,
+     6,      AMR_OF(1, adap),  35,  54,  79,  74,  84, 101,
+     1,       AMR_OF(1, ltp), 109,
+    10, AMR_OF(1, pul_ih[0]), 139, 169, 267, 348, 389, 163, 116, 189,
+                              343, 268,
+    10, AMR_OF(1, pul_ih[1]), 120, 161, 249, 339, 397, 152, 114, 230,
+                              334, 303,
+     2, AMR_OF(1, pul_ih[2]), 125, 138,
+     2, AMR_OF(1, pul_ih[3]), 112, 129,
+    10, AMR_OF(1, pul_il[0]), 349, 122, 162, 203, 288, 372, 278, 274,
+                              312, 377,
+    10, AMR_OF(1, pul_il[1]), 357, 126, 165, 214, 298, 362, 252, 260,
+                              321, 378,
+    14, AMR_OF(1, pul_il[2]), 150, 199, 266, 355, 211, 180, 285, 241,
+                              195, 198, 243, 275, 323, 375,
+    14, AMR_OF(1, pul_il[3]), 142, 191, 256, 353, 208, 220, 314, 237,
+                              190, 212, 255, 304, 318, 371,
+     7,   AMR_OF(1, vq_gain),   3,  18,  44,  26,  38,  32,  30,
+     9,      AMR_OF(2, adap),   8,  23,  22,  21,  20,  52,  65,  87,
+                               91,
+     1,       AMR_OF(2, ltp), 108,
+    10, AMR_OF(2, pul_ih[0]), 159, 168, 302, 356, 395, 178, 132, 185,
+                              330, 286,
+    10, AMR_OF(2, pul_ih[1]), 158, 181, 292, 358, 396, 176, 133, 235,
+                              331, 276,
+     2, AMR_OF(2, pul_ih[2]), 130, 157,
+     2, AMR_OF(2, pul_ih[3]), 124, 136,
+    10, AMR_OF(2, pul_il[0]), 354, 121, 194, 246, 322, 379, 272, 273,
+                              332, 398,
+    10, AMR_OF(2, pul_il[1]), 359, 140, 186, 236, 333, 376, 290, 301,
+                              338, 387,
+    14, AMR_OF(2, pul_il[2]), 155, 227, 319, 369, 253, 254, 350, 248,
+                              224, 239, 240, 293, 315, 383,
+    14, AMR_OF(2, pul_il[3]), 156, 209, 297, 373, 225, 215, 326, 247,
+                              197, 184, 232, 289, 310, 365,
+     7,   AMR_OF(2, vq_gain),   2,  17,  43,  25,  37,  47,  29,
+     6,      AMR_OF(3, adap),  34,  53,  78,  73,  83, 100,
+     1,       AMR_OF(3, ltp), 107,
+    10, AMR_OF(3, pul_ih[0]), 148, 164, 264, 340, 388, 183, 117, 205,
+                              336, 261,
+    10, AMR_OF(3, pul_ih[1]), 146, 174, 257, 335, 384, 173, 113, 187,
+                              320, 279,
+     2, AMR_OF(3, pul_ih[2]), 127, 151,
+     2, AMR_OF(3, pul_ih[3]), 119, 137,
+    10, AMR_OF(3, pul_il[0]), 352, 135, 172, 238, 306, 381, 262, 271,
+                              328, 382,
+    10, AMR_OF(3, pul_il[1]), 347, 115, 179, 219, 305, 380, 277, 294,
+                              337, 386,
+    14, AMR_OF(3, pul_il[2]), 145, 192, 307, 370, 234, 223, 324, 244,
+                              202, 204, 251, 299, 325, 360,
+    14, AMR_OF(3, pul_il[3]), 149, 221, 311, 363, 226, 222, 316, 231,
+                              207, 175, 233, 280, 283, 344,
+     7,   AMR_OF(3, vq_gain),   1,  16,  42,  24,  36,  46,  28,
+     0
+};
+
+static const uint16_t order_MODE_23k05[] = {
+     1,         AMR_BIT(vad),   7,
+     8,   AMR_BIT(isp_id[0]),  55,  40,  14,   6,  15,   5,   0,  68,
+     8,   AMR_BIT(isp_id[1]),  77,  58,  75,  49,  59,  57,  67,  61,
+     6,   AMR_BIT(isp_id[2]),  48,  63,  51,  62,  50,  70,
+     7,   AMR_BIT(isp_id[3]),  71,  56,  60,  69,  85,  86,  80,
+     7,   AMR_BIT(isp_id[4]),  93,  64,  94,  76,  82,  81,  89,
+     5,   AMR_BIT(isp_id[5]),  90, 103,  88, 102,  99,
+     5,   AMR_BIT(isp_id[6]),  98,  97,  96, 111,  95,
+     9,      AMR_OF(0, adap),  13,  12,  11,  10,   9,  41,  66,  72,
+                               92,
+     1,       AMR_OF(0, ltp), 110,
+    11, AMR_OF(0, pul_ih[0]), 118, 129, 131, 153, 170, 282, 298, 210,
+                              191, 357, 317,
+    11, AMR_OF(0, pul_ih[1]), 126, 146, 135, 165, 187, 273, 345, 295,
+                              172, 338, 340,
+    11, AMR_OF(0, pul_ih[2]), 119, 137, 141, 167, 208, 304, 366, 256,
+                              177, 339, 328,
+    11, AMR_OF(0, pul_ih[3]), 116, 130, 120, 166, 190, 252, 311, 239,
+                              173, 343, 318,
+    11, AMR_OF(0, pul_il[0]), 245, 180, 342, 424, 259, 277, 266, 380,
+                              398, 423, 440,
+    11, AMR_OF(0, pul_il[1]), 218, 207, 367, 434, 201, 240, 275, 363,
+                              399, 419, 452,
+    11, AMR_OF(0, pul_il[2]), 274, 188, 348, 425, 242, 204, 262, 365,
+                              402, 431, 463,
+    11, AMR_OF(0, pul_il[3]), 221, 183, 337, 439, 243, 216, 251, 354,
+                              390, 411, 462,
+     7,   AMR_OF(0, vq_gain),   4,  19,  45,  27,  39,  33,  31,
+     6,      AMR_OF(1, adap),  35,  54,  79,  74,  84, 101,
+     1,       AMR_OF(1, ltp), 109,
+    11, AMR_OF(1, pul_ih[0]), 115, 140, 142, 161, 230, 291, 351, 235,
+                              181, 293, 310,
+    11, AMR_OF(1, pul_ih[1]), 104, 138, 132, 162, 211, 315, 347, 233,
+                              176, 320, 329,
+    11, AMR_OF(1, pul_ih[2]), 106, 134, 125, 154, 205, 267, 306, 220,
+                              185, 330, 297,
+    11, AMR_OF(1, pul_ih[3]), 105, 148, 122, 152, 215, 302, 350, 254,
+                              178, 319, 313,
+    11, AMR_OF(1, pul_il[0]), 269, 189, 382, 432, 272, 228, 263, 383,
+                              406, 422, 453,
+    11, AMR_OF(1, pul_il[1]), 286, 206, 377, 446, 226, 222, 265, 368,
+                              404, 416, 454,
+    11, AMR_OF(1, pul_il[2]), 247, 195, 358, 445, 224, 236, 309, 341,
+                              375, 408, 449,
+    11, AMR_OF(1, pul_il[3]), 225, 192, 359, 436, 250, 258, 290, 389,
+                              400, 420, 448,
+     7,   AMR_OF(1, vq_gain),   3,  18,  44,  26,  38,  32,  30,
+     9,      AMR_OF(2, adap),   8,  23,  22,  21,  20,  52,  65,  87,
+                               91,
+     1,       AMR_OF(2, ltp), 108,
+    11, AMR_OF(2, pul_ih[0]), 139, 144, 145, 169, 234, 327, 395, 299,
+                              244, 356, 379,
+    11, AMR_OF(2, pul_ih[1]), 127, 156, 158, 171, 231, 308, 397, 355,
+                              261, 371, 335,
+    11, AMR_OF(2, pul_ih[2]), 123, 155, 157, 193, 241, 362, 384, 323,
+                              238, 392, 361,
+    11, AMR_OF(2, pul_ih[3]), 114, 147, 121, 175, 196, 333, 373, 303,
+                              184, 353, 322,
+    11, AMR_OF(2, pul_il[0]), 271, 203, 385, 442, 307, 276, 334, 405,
+                              412, 427, 459,
+    11, AMR_OF(2, pul_il[1]), 278, 200, 388, 447, 292, 288, 296, 403,
+                              415, 429, 460,
+    11, AMR_OF(2, pul_il[2]), 312, 214, 393, 433, 279, 301, 314, 391,
+                              410, 426, 450,
+    11, AMR_OF(2, pul_il[3]), 280, 186, 376, 437, 268, 260, 255, 364,
+                              414, 417, 441,
+     7,   AMR_OF(2, vq_gain),   2,  17,  43,  25,  37,  47,  29,
+     6,      AMR_OF(3, adap),  34,  53,  78,  73,  83, 100,
+     1,       AMR_OF(3, ltp), 107,
+    11, AMR_OF(3, pul_ih[0]), 112, 159, 143, 164, 213, 281, 332, 284,
+                              168, 344, 325,
+    11, AMR_OF(3, pul_ih[1]), 113, 150, 149, 179, 199, 316, 324, 285,
+                              237, 360, 336,
+    11, AMR_OF(3, pul_ih[2]), 124, 136, 151, 174, 209, 326, 349, 248,
+                              198, 374, 331,
+    11, AMR_OF(3, pul_ih[3]), 117, 128, 133, 163, 202, 300, 372, 305,
+                              194, 387, 321,
+    11, AMR_OF(3, pul_il[0]), 249, 182, 352, 428, 253, 264, 289, 413,
+                              407, 418, 461,
+    11, AMR_OF(3, pul_il[1]), 287, 212, 369, 444, 223, 246, 217, 346,
+                              394, 401, 451,
+    11, AMR_OF(3, pul_il[2]), 219, 197, 378, 435, 229, 257, 283, 396,
+                              409, 430, 455,
+    11, AMR_OF(3, pul_il[3]), 232, 160, 370, 438, 227, 270, 294, 381,
+                              386, 421, 443,
+     7,   AMR_OF(3, vq_gain),   1,  16,  42,  24,  36,  46,  28,
+     0
+};
+
+static const uint16_t order_MODE_23k85[] = {
+     1,         AMR_BIT(vad),   7,
+     8,   AMR_BIT(isp_id[0]),  55,  40,  14,   6,  15,   5,   0,  68,
+     8,   AMR_BIT(isp_id[1]),  93,  58,  91,  49,  59,  57,  67,  61,
+     6,   AMR_BIT(isp_id[2]),  48,  63,  51,  62,  50,  70,
+     7,   AMR_BIT(isp_id[3]),  71,  56,  60,  69, 101, 102,  96,
+     7,   AMR_BIT(isp_id[4]), 109,  64, 110,  92,  98,  97, 105,
+     5,   AMR_BIT(isp_id[5]), 106, 119, 104, 118, 115,
+     5,   AMR_BIT(isp_id[6]), 114, 113, 112, 127, 111,
+     9,      AMR_OF(0, adap),  13,  12,  11,  10,   9,  41,  66,  88,
+                              108,
+     1,       AMR_OF(0, ltp), 126,
+    11, AMR_OF(0, pul_ih[0]), 134, 145, 147, 169, 186, 298, 314, 226,
+                              207, 373, 333,
+    11, AMR_OF(0, pul_ih[1]), 142, 162, 151, 181, 203, 289, 361, 311,
+                              188, 354, 356,
+    11, AMR_OF(0, pul_ih[2]), 135, 153, 157, 183, 224, 320, 382, 272,
+                              193, 355, 344,
+    11, AMR_OF(0, pul_ih[3]), 132, 146, 136, 182, 206, 268, 327, 255,
+                              189, 359, 334,
+    11, AMR_OF(0, pul_il[0]), 261, 196, 358, 440, 275, 293, 282, 396,
+                              414, 439, 456,
+    11, AMR_OF(0, pul_il[1]), 234, 223, 383, 450, 217, 256, 291, 379,
+                              415, 435, 468,
+    11, AMR_OF(0, pul_il[2]), 290, 204, 364, 441, 258, 220, 278, 381,
+                              418, 447, 479,
+    11, AMR_OF(0, pul_il[3]), 237, 199, 353, 455, 259, 232, 267, 370,
+                              406, 427, 478,
+     7,   AMR_OF(0, vq_gain),   4,  19,  45,  27,  39,  33,  31,
+     4,   AMR_OF(0, hb_gain),  79,  78,  77,  76,
+     6,      AMR_OF(1, adap),  35,  54,  95,  90, 100, 117,
+     1,       AMR_OF(1, ltp), 125,
+    11, AMR_OF(1, pul_ih[0]), 131, 156, 158, 177, 246, 307, 367, 251,
+                              197, 309, 326,
+    11, AMR_OF(1, pul_ih[1]), 120, 154, 148, 178, 227, 331, 363, 249,
+                              192, 336, 345,
+    11, AMR_OF(1, pul_ih[2]), 122, 150, 141, 170, 221, 283, 322, 236,
+                              201, 346, 313,
+    11, AMR_OF(1, pul_ih[3]), 121, 164, 138, 168, 231, 318, 366, 270,
+                              194, 335, 329,
+    11, AMR_OF(1, pul_il[0]), 285, 205, 398, 448, 288, 244, 279, 399,
+                              422, 438, 469,
+    11, AMR_OF(1, pul_il[1]), 302, 222, 393, 462, 242, 238, 281, 384,
+                              420, 432, 470,
+    11, AMR_OF(1, pul_il[2]), 263, 211, 374, 461, 240, 252, 325, 357,
+                              391, 424, 465,
+    11, AMR_OF(1, pul_il[3]), 241, 208, 375, 452, 266, 274, 306, 405,
+                              416, 436, 464,
+     7,   AMR_OF(1, vq_gain),   3,  18,  44,  26,  38,  32,  30,
+     4,   AMR_OF(1, hb_gain),  75,  74,  73,  72,
+     9,      AMR_OF(2, adap),   8,  23,  22,  21,  20,  52,  65, 103,
+                              107,
+     1,       AMR_OF(2, ltp), 124,
+    11, AMR_OF(2, pul_ih[0]), 155, 160, 161, 185, 250, 343, 411, 315,
+                              260, 372, 395,
+    11, AMR_OF(2, pul_ih[1]), 143, 172, 174, 187, 247, 324, 413, 371,
+                              277, 387, 351,
+    11, AMR_OF(2, pul_ih[2]), 139, 171, 173, 209, 257, 378, 400, 339,
+                              254, 408, 377,
+    11, AMR_OF(2, pul_ih[3]), 130, 163, 137, 191, 212, 349, 389, 319,
+                              200, 369, 338,
+    11, AMR_OF(2, pul_il[0]), 287, 219, 401, 458, 323, 292, 350, 421,
+                              428, 443, 475,
+    11, AMR_OF(2, pul_il[1]), 294, 216, 404, 463, 308, 304, 312, 419,
+                              431, 445, 476,
+    11, AMR_OF(2, pul_il[2]), 328, 230, 409, 449, 295, 317, 330, 407,
+                              426, 442, 466,
+    11, AMR_OF(2, pul_il[3]), 296, 202, 392, 453, 284, 276, 271, 380,
+                              430, 433, 457,
+     7,   AMR_OF(2, vq_gain),   2,  17,  43,  25,  37,  47,  29,
+     4,   AMR_OF(2, hb_gain),  87,  86,  85,  84,
+     6,      AMR_OF(3, adap),  34,  53,  94,  89,  99, 116,
+     1,       AMR_OF(3, ltp), 123,
+    11, AMR_OF(3, pul_ih[0]), 128, 175, 159, 180, 229, 297, 348, 300,
+                              184, 360, 341,
+    11, AMR_OF(3, pul_ih[1]), 129, 166, 165, 195, 215, 332, 340, 301,
+                              253, 376, 352,
+    11, AMR_OF(3, pul_ih[2]), 140, 152, 167, 190, 225, 342, 365, 264,
+                              214, 390, 347,
+    11, AMR_OF(3, pul_ih[3]), 133, 144, 149, 179, 218, 316, 388, 321,
+                              210, 403, 337,
+    11, AMR_OF(3, pul_il[0]), 265, 198, 368, 444, 269, 280, 305, 429,
+                              423, 434, 477,
+    11, AMR_OF(3, pul_il[1]), 303, 228, 385, 460, 239, 262, 233, 362,
+                              410, 417, 467,
+    11, AMR_OF(3, pul_il[2]), 235, 213, 394, 451, 245, 273, 299, 412,
+                              425, 446, 471,
+    11, AMR_OF(3, pul_il[3]), 248, 176, 386, 454, 243, 286, 310, 397,
+                              402, 437, 459,
+     7,   AMR_OF(3, vq_gain),   1,  16,  42,  24,  36,  46,  28,
+     4,   AMR_OF(3, hb_gain),  83,  82,  81,  80,
+     0
+};
+
+/** Reordering array addresses for each mode */
+static const uint16_t* amr_bit_orderings_by_mode[] = {
+    order_MODE_6k60,
+    order_MODE_8k85,
+    order_MODE_12k65,
+    order_MODE_14k25,
+    order_MODE_15k85,
+    order_MODE_18k25,
+    order_MODE_19k85,
+    order_MODE_23k05,
+    order_MODE_23k85
+};
+
+// Extracted from 3GPP TS 26.173 V9.0.0 (qpisf_2s.tab)
+// The *_36b tables are used in 6k60 mode
+// Stored in fixed-point to save some space
+/** Indexed tables for retrieval of quantized ISF vectors in Q15 */
+static const int16_t dico1_isf[256][9] = {
+ {  579,  1081,  1035,   390,     3,  -263,  -198,   -82,    38},
+ {   18,   -68,   -12,   313,   761,   405,   249,   111,   -76},
+ {  740,  1263,  1292,  1006,   997,  1019,  1017,   976,   923},
+ {  -91,   827,   948,   648,   613,   535,   522,   490,   421},
+ {   41,   -44,  -281,  -472,   652,   534,   193,   135,   -90},
+ {   41,  -121,  -356,   -60,   663,   307,    61,   -48,  -344},
+ {  557,   946,  1049,   867,   846,   990,  1112,  1262,  1241},
+ { -118,  -204,   328,   512,   870,   793,   610,   402,   186},
+ {  156,   293,    74,  -338,  -475,  -897,  -594,  -161,  -497},
+ {  226,   131,  -138,   307,   169,  -271,  -164,  -387,  -624},
+ {   62,   -32,   -61,  -252,  -541,  -828, -1027,  -523,  -662},
+ {  102,   -61,   141,   112,  -270,  -251,  -541,    25,  -150},
+ {    6,  -132,  -356,  -686,   -96,  -322,  -522,   -31,  -326},
+ {  -36,  -209,  -521,  -229,   307,  -132,    -5,   -99,  -384},
+ {   60,   -51,  -237,  -668,  -973,  -407,  -708,   -75,  -172},
+ {   26,  -138,  -266,   111,  -302,    43,  -278,  -356,  -359},
+ {  570,   822,   496,  -154,  -312,   -92,   137,   279,   371},
+ { -146,   368,   409,    68,     6,    77,   167,   202,   162},
+ {  633,   898,   996,   756,   662,   683,   783,   909,   996},
+ { -103,   294,   607,   415,   483,   462,   480,   431,   408},
+ { -120,  -338,  -612,  -524,   584,   331,    92,   433,   276},
+ { -178,  -293,  -154,   -41,   269,   100,    -9,   213,   160},
+ {  830,   736,   278,   820,  1254,   686,   712,  1039,   473},
+ { -218,  -304,   463,   454,   397,   273,   202,   286,   273},
+ { -232,     7,     6,  -388,  -472,  -427,  -378,  -167,  -100},
+ { -294,  -183,   134,   -47,   101,   -88,   -84,  -117,    -3},
+ {   57,    17,  -202,  -634,  -989, -1119,  -533,   176,   -36},
+ {  120,   -28,    23,   111,  -319,   318,   -22,   -77,   266},
+ { -271,  -464,  -434,  -658,  -640,  -385,  -385,   -99,   -69},
+ { -198,  -259,  -266,   -44,   -39,  -139,  -137,   171,    66},
+ {    9,  -145,  -377,  -846, -1000,  -111,  -325,   342,   135},
+ {  -81,  -286,  -380,   192,   -57,   307,    76,   -24,  -140},
+ {  677,   702,   247,    56,   249,   141,  -105,  -236,   -99},
+ {   36,   -39,   -69,   348,   198,   -93,   322,    91,   -72},
+ {  503,   885,  1508,  1307,  1282,  1172,  1119,  1209,  1061},
+ {  416,   719,   989,  1227,  1001,  1052,   954,   741,  1044},
+ { -127,  -376,  -657,   139,   623,   223,   501,   306,   220},
+ { -113,  -384,  -796,   504,   438,    85,   213,   -83,  -194},
+ {  585,  1132,  1233,  1091,  1247,  1433,  1512,  1448,  1314},
+ { -174,  -422,     7,  1155,  1089,  1182,  1003,   945,   806},
+ {    8,  -126,  -317,  -103,  -351,  -695,   -98,  -268,  -537},
+ {   33,  -103,  -290,   167,   -39,  -407,    44,  -208,  -375},
+ {  104,   -23,   -64,  -291,  -637,  -851, -1084,   -61,  -112},
+ {  -75,  -306,  -434,   218,  -148,  -354,  -680,  -133,  -216},
+ { -121,  -377,  -718,   -97,  -130,  -361,  -156,  -379,  -599},
+ {  -56,  -254,  -586,   235,   157,  -214,    11,  -260,  -149},
+ { -124,  -267,  -397,  -580,  -593,  -527,  -805,  -385,   346},
+ { -193,  -440,  -708,  -351,  -141,  -255,  -499,  -147,  -185},
+ {  448,   660,   494,   208,   509,   461,   338,   291,   149},
+ { -223,    88,   335,   159,   212,   191,   286,   308,   205},
+ {  -31,   469,   803,   659,   619,   658,   843,   987,  1113},
+ { -171,  -242,   514,   362,   295,   524,   552,   694,   585},
+ {  -64,  -308,  -448,   -21,   284,   786,   446,   289,    92},
+ { -218,  -390,    -7,   169,   206,   330,   352,   408,   358},
+ {  -36,   702,   959,   859,   861,  1115,  1269,  1357,  1305},
+ { -133,  -341,   -65,   678,   417,   440,   486,   518,   780},
+ {   33,   -44,  -191,  -344,  -461,  -755,  -201,   217,   -31},
+ { -353,  -547,   -44,   123,   -61,   -68,   -79,    29,    60},
+ {   73,   -57,  -406,  -766, -1243, -1203,   240,   400,   165},
+ {  -73,  -282,  -601,  -213,  -171,  -375,   332,    35,  -103},
+ {  -29,  -207,  -553,  -476,  -638,  -908,   172,   -22,  -135},
+ { -192,  -239,  -164,  -103,  -111,   -47,   153,   125,   110},
+ {   -1,  -203,  -570, -1030, -1424,  -535,   155,     1,   147},
+ { -333,  -653,  -865,  -197,  -158,   -21,   -44,    95,   108},
+ {  389,   588,   490,    33,  -237,  -524,  -628,  -136,  -260},
+ {   40,  -177,  -462,   453,   862,   380,   131,  -130,  -405},
+ {  842,  1678,  1841,  1549,  1474,  1256,  1082,   905,   742},
+ {  370,  1216,  1768,  1633,  1212,   636,    22,  -330,    71},
+ {  -76,  -281,  -741,  -742,   898,   619,   277,    71,  -222},
+ {  -32,  -265,  -556,   -25,   994,   682,   305,   126,  -165},
+ {   73,   738,   893,   968,   993,  1768,  2273,  1840,  1391},
+ {  -69,  -349,  -585,   234,  1158,   903,   626,   510,   251},
+ {   -1,   -99,  -272,  -210,  -603,  -351,  -540,  -811,  -383},
+ {  -16,  -230,  -504,   410,   149,  -205,  -343,  -651,  -639},
+ {  103,    -9,  -227,  -205,  -562,  -781, -1079, -1208,  -156},
+ {  143,    63,  -135,   -67,  -317,  -602,  -784, -1154,  -640},
+ { -144,  -391,  -674,  -622,  -200,  -254,  -660,  -947,  -395},
+ {  -40,  -250,  -625,    27,   543,    94,  -131,  -386,  -673},
+ { -123,  -371,  -757,  -451,  -564,  -614,  -415,  -711,   -35},
+ { -116,  -309,  -593,  -268,   239,   -33,  -338,  -650,  -135},
+ {   94,   251,   554,    57,  -312,  -423,  -154,   -57,   235},
+ { -268,   -71,   381,   114,   -44,   -87,   125,   173,   133},
+ { 1513,  1714,  1238,   534,   276,   315,   461,   459,   508},
+ { -131,   -19,  1149,   670,   486,   356,   309,   369,   296},
+ { -223,  -501,  -899,  -722,   -70,     6,   131,   310,   394},
+ {  -99,  -303,  -517,   249,    64,   -53,   135,   -11,   453},
+ { -147,  -399,  -730,  -401,   817,   738,   802,   749,   575},
+ { -154,  -435,  -739,   800,   593,   366,   529,   318,   326},
+ { -224,    45,   -39,  -387,  -515,  -518,  -608,  -384,  -321},
+ { -315,  -377,   143,  -101,  -113,  -377,  -177,  -144,   -12},
+ {  117,    40,  -239,  -651, -1051,  -581,  -737,  -990,  -328},
+ {   26,   -50,  -157,   -23,  -453,  -283,  -531,  -546,   192},
+ { -252,  -501,  -743,  -589,  -627,  -499,  -328,  -118,   -72},
+ { -324,  -494,  -244,  -306,  -144,  -177,  -262,  -135,   -78},
+ {  -36,  -234,  -519,  -961, -1290,  -314,  -479,  -371,   -45},
+ {  -95,  -292,  -535,    -8,  -300,   112,  -164,  -277,   198},
+ {  -99,  -128,   880,   836,   579,   351,    23,   -95,  -217},
+ {  -27,  -258,   124,  1011,   597,   425,   144,     7,   -73},
+ {  421,  1293,  1640,  1623,  1742,  1617,  1499,  1284,  1006},
+ {  -95,   752,  1680,  1569,  1618,  1436,  1200,   980,   712},
+ {  -69,  -300,  -683,  -435,  1132,   899,   504,   332,   109},
+ {  -74,  -323,  -637,   563,  1074,   608,   371,   105,   -49},
+ {  -78,   831,  1194,  1110,  1378,  1481,  1492,  1365,  1217},
+ { -259,  -121,  1440,  1334,  1628,  1490,  1438,  1223,   933},
+ {  -82,  -306,  -613,  -222,  -378,  -675,  -545,  -671,  -845},
+ {   53,  -124,  -347,   422,    52,  -125,  -270,  -529,     9},
+ {   79,   -89,  -320,  -662,  -999, -1199, -1243,  -676,  -297},
+ {  -68,  -273,  -611,   137,  -146,  -397,  -627,  -845,  -220},
+ { -112,  -346,  -797,  -826,   234,  -132,  -188,  -278,  -522},
+ { -159,  -405,  -734,  -419,   293,    74,  -167,  -167,   184},
+ { -153,  -437,  -833, -1080,  -336,  -472,  -561,  -340,  -253},
+ { -169,  -423,  -820,  -904,  -131,   -19,  -346,  -604,    31},
+ {   33,   -31,   312,    62,  -148,    49,   -59,   564,   486},
+ { -306,  -333,   194,   -44,    67,    72,   147,   205,   243},
+ { -207,   -49,  1360,   983,   969,   991,  1014,  1110,   973},
+ { -211,  -172,   883,   627,   711,   674,   705,   798,   746},
+ {  -88,  -325,  -763,  -974,   687,   908,   514,   382,   172},
+ { -292,  -612,  -805,    63,   131,   270,   259,   352,   348},
+ { -235,   -84,   955,   818,  1120,  1289,  1559,  1480,  1285},
+ { -180,  -461,  -614,   657,   691,   745,   854,   783,   713},
+ {  -97,  -309,  -477,  -614,  -777,  -734,  -768,  -526,  -472},
+ { -344,  -476,   -35,  -169,    49,   -77,  -150,  -240,  -141},
+ {  -52,  -268,  -639,  -919, -1278, -1113,  -342,  -333,  -151},
+ {  -68,  -242,  -585,   -73,  -209,  -478,  -159,  -429,   133},
+ { -197,  -499, -1005, -1268,  -272,  -224,  -105,   -67,    17},
+ { -363,  -618,  -414,  -116,   -62,    20,    10,   116,   108},
+ { -195,  -475,  -906, -1260,  -891,  -441,  -277,  -142,   -28},
+ { -226,  -519,  -950,  -700,  -275,  -266,  -116,  -105,    82},
+ {  404,   511,   520,   327,    17,  -194,  -333,  -536,  -586},
+ { -114,  -130,   276,   237,   204,   342,   135,   -16,  -111},
+ {  670,  1208,  1168,   860,   742,   601,   528,   403,   309},
+ {  397,   621,   966,   752,   579,   398,   400,   329,   252},
+ {  191,   180,  -137,  -467,   272,   106,   -95,    17,  -192},
+ {  -80,  -290,  -626,   194,   598,   196,    21,  -281,    77},
+ {  510,   864,  1108,   807,   939,   902,   925,   717,   481},
+ {  137,   367,   534,   764,   670,   382,   296,   153,    84},
+ {  303,   497,   144,   -85,  -125,  -539,  -482,  -464,  -764},
+ {  233,   347,    68,  -147,   169,  -210,  -242,  -226,  -482},
+ {  307,   422,   154,  -175,  -386,  -722,  -724,  -904, -1015},
+ {  309,   308,   160,   -60,  -470,  -420,  -598,  -791,  -219},
+ {   68,   121,  -137,  -560,  -146,  -446,  -515,  -494,  -729},
+ {  130,    53,  -227,    46,   474,    32,  -161,  -192,  -490},
+ {  213,   164,   -71,  -465,  -876,  -161,  -456,  -587,   -48},
+ {  218,   117,    39,   177,  -194,   -88,  -226,  -418,    50},
+ {  210,   547,   569,   279,   121,   -44,   -50,    10,   -84},
+ {   58,   140,   182,    -5,   267,   117,   106,   211,   198},
+ {  539,   835,   913,   719,   617,   544,   591,   565,   642},
+ {  153,   559,   872,   460,   222,   108,   188,   180,   183},
+ {  158,   119,   284,  -153,  -271,   229,    87,   110,   -57},
+ { -183,    82,   118,    21,    13,    40,   118,   191,   185},
+ {  162,   889,   654,   108,   -34,   244,   488,   561,   532},
+ {  163,    56,   609,   341,    50,   329,    68,   266,   218},
+ {  100,   206,    18,  -304,  -107,  -436,  -487,   -65,  -306},
+ {  -86,   154,   134,   -30,   -45,   -73,  -104,   -80,   -96},
+ {  245,   330,    10,  -440,  -849, -1082,    79,    40,  -265},
+ {  196,   372,   272,  -181,  -493,  -389,   275,    80,   -59},
+ {    2,   -12,  -246,  -505,  -100,  -436,    21,  -187,  -431},
+ { -221,   -48,    36,  -271,  -186,  -147,  -109,    26,    71},
+ {  213,   140,    72,  -351,  -620,   -84,  -363,    69,    46},
+ {   91,   167,    -3,   -95,   -99,  -105,   -48,   114,   147},
+ {  259,   249,   172,   607,   406,    52,    59,  -189,  -320},
+ {  115,   -85,   -54,   574,   128,   226,   -59,  -253,   130},
+ {  -62,  1033,  1308,  1035,  1127,  1098,  1029,   961,   823},
+ {   39,   364,   757,   940,   728,   660,   659,   583,   770},
+ { -115,  -338,  -760,  -471,   394,    37,   441,   178,     6},
+ {  -57,  -305,  -525,   796,   453,   188,    -4,  -114,   248},
+ {   71,   444,   797,   731,  1096,  1157,  1222,  1029,   811},
+ {  135,   359,   551,   425,   749,   815,   874,   704,   502},
+ {  132,   247,     0,  -206,  -449,  -750,  -258,  -514,  -633},
+ {  248,   249,    91,   121,  -195,  -499,   -90,  -282,  -435},
+ {   78,    20,  -277,  -623,  -983, -1224,  -415,  -458,  -639},
+ {  347,   509,   208,  -179,  -464,  -728,   -76,  -237,  -486},
+ { -103,  -343,  -756,  -713,  -265,  -609,  -191,  -398,  -636},
+ { -121,  -383,  -749,   567,   252,   -36,  -354,  -417,   -50},
+ {  204,   100,  -149,  -650, -1081,   -47,    -7,  -263,   111},
+ {  -46,  -180,  -267,  -324,  -562,  -394,  -692,   398,   292},
+ {  482,   670,   683,   624,   442,   165,   116,    36,  -149},
+ {  108,   247,   291,   247,   355,   122,   109,   224,   296},
+ {  -14,   945,   990,   801,   755,   815,   847,   913,   892},
+ {  292,   349,   725,   482,   388,   329,   429,   620,   667},
+ {  -34,   197,   213,  -127,    84,   494,   620,   575,   375},
+ {  126,   207,   172,   167,   362,   202,   296,   395,   455},
+ {   -6,   250,   539,   467,   636,   801,  1149,  1287,  1118},
+ {   27,   240,   369,   280,   440,   411,   634,   892,   953},
+ {  159,   170,   -58,  -395,  -797,  -690,    77,  -211,  -334},
+ {   -5,   -28,   -13,   -74,  -335,  -603,   300,    88,  -205},
+ {   82,   -33,  -364,  -698, -1203, -1153,   110,  -146,  -289},
+ {  113,     1,  -243,  -588,  -994,  -496,   414,   160,    42},
+ {  -56,  -247,  -440,  -693,  -996,  -479,    11,  -178,  -357},
+ { -151,  -353,  -327,  -211,  -340,   141,    65,   425,   453},
+ {   34,  -169,  -455,  -932, -1215,   138,   499,   256,   324},
+ {   68,   139,   -15,  -547,  -478,    17,   306,   502,   481},
+ {  -32,  -134,   445,   129,  -143,  -244,  -503,  -507,  -599},
+ {   61,  -140,  -345,   496,   458,    -2,    20,  -227,  -514},
+ {  394,  1765,  1666,  1339,  1117,   806,   642,   479,   380},
+ {  215,   519,   920,  1053,  1090,   791,   528,   290,   155},
+ {  -54,  -233,  -647,  -602,   639,   294,    -2,  -167,  -442},
+ {  -78,  -315,  -791,  -113,   820,   403,   158,  -116,  -356},
+ {  529,  1851,  2003,  1228,   622,   -41,  -416,   344,   819},
+ { -105,  -379,  -236,  1224,   893,   749,   568,   356,   214},
+ {  -17,  -199,  -144,    50,  -283,  -247,  -578,  -846, -1087},
+ {   69,   -11,  -381,  -206,   209,  -284,  -387,  -416,  -716},
+ {   39,    -5,  -145,  -374,  -682,  -909, -1074, -1169, -1066},
+ {  287,   226,    67,  -221,  -662,  -171,  -421,  -642,  -707},
+ { -132,  -348,  -538,  -448,   -20,    -4,  -354,  -748,  -933},
+ {    4,   -75,  -289,  -598,   317,    52,  -208,  -297,  -559},
+ {  -88,  -264,  -358,  -589,  -631,  -248,  -523,  -822, -1071},
+ {   70,    -8,    54,  -314,  -515,    92,  -146,  -274,  -493},
+ {  199,    62,   391,   158,  -141,    71,  -219,  -203,  -207},
+ {  152,    40,   329,   162,   -29,    48,  -149,   108,   127},
+ {  635,  1058,   883,   492,   372,   312,   317,   274,   241},
+ {  267,   722,  1256,   882,   625,   248,     8,   -81,   -60},
+ {  -58,  -138,  -291,  -600,   -12,    -2,   -39,   147,   117},
+ { -107,  -345,  -513,   459,    76,    92,  -272,   388,   262},
+ {  362,   516,   203,  -409,  -716,  -831,  -331,   185,   209},
+ { -117,  -391,  -298,   671,   292,   538,   257,   166,   -38},
+ { -102,  -319,  -194,  -283,  -573,  -262,  -579,  -219,  -444},
+ { -235,    78,    11,  -168,  -101,  -229,  -263,  -321,  -123},
+ {   70,    50,  -170,  -599,  -996,  -588,  -263,  -516,  -455},
+ {  394,   363,   229,  -136,  -538,    21,  -183,  -348,  -201},
+ { -124,  -368,  -640,  -879,  -847,  -209,  -409,  -494,  -515},
+ { -127,  -341,  -541,  -425,  -510,   -10,  -252,  -473,  -291},
+ {   84,   -69,  -201,  -676,  -868,   103,  -311,  -132,  -320},
+ {    5,  -173,  -188,  -297,  -628,   197,   -57,     7,   -11},
+ {   49,  -160,    56,   558,   111,    33,  -311,  -440,  -463},
+ {   -1,  -246,  -307,   862,   453,   139,  -170,  -355,  -232},
+ {  279,   966,  1642,  1478,  1463,  1123,   795,   525,   339},
+ { -197,   -38,  1702,  1331,  1252,   950,   692,   504,   426},
+ { -108,  -344,  -861, -1172,   444,   354,    88,   -46,  -220},
+ {  -53,  -321,  -494,  1113,   744,   364,   198,   -34,   -75},
+ {  457,   955,  1177,  1214,  1427,  1457,  1345,   917,   539},
+ {  -69,   199,   897,  1140,  1343,  1183,   977,   742,   522},
+ {  122,    44,  -269,    27,  -155,  -562,  -307,  -590,  -773},
+ {  154,    42,  -160,   252,  -129,  -305,  -471,  -733,  -371},
+ {  135,   185,   -82,  -416,  -722,  -913,  -504,  -743,  -880},
+ {  149,   214,   -84,  -329,  -680,  -835,  -426,  -661,   -81},
+ { -128,  -380,  -735,  -998,  -337,    17,  -182,  -467,  -697},
+ {  -84,  -290,  -510,  -592,    13,   440,   154,   -38,  -279},
+ {   70,   -61,  -246,  -727, -1047,   -80,  -381,  -535,  -704},
+ {  178,    -2,  -146,  -670,  -938,   482,   138,    63,    65},
+ {  -11,    15,   772,   443,   142,   -20,  -209,  -126,  -161},
+ {  -32,  -249,    95,   552,   124,    30,  -343,    82,   -86},
+ {  148,   751,  1515,  1105,   867,   606,   474,   448,   399},
+ { -163,  -257,   899,  1097,   906,   751,   502,   390,   294},
+ {  -51,  -258,  -447,  -806,  -368,   763,   464,   364,   183},
+ { -166,  -374,  -367,    87,    35,   399,   418,   856,   833},
+ { -205,  -310,   588,   778,   785,  1065,  1118,  1245,  1157},
+ { -173,  -312,   107,   345,   400,   790,   870,  1113,  1001},
+ {   -7,  -120,  -387,  -410,  -614,  -943,  -226,  -384,  -491},
+ { -203,  -288,   -51,  -331,   -90,  -178,  -408,  -573,  -338},
+ {   56,   -29,  -273,  -627, -1041,  -798,  -247,  -467,   148},
+ {   66,    -2,  -205,  -205,  -575,  -349,   -57,  -352,   -58},
+ {  -45,  -225,  -471,  -924,  -497,    77,   -32,    44,  -135},
+ { -277,  -491,  -497,  -502,  -424,  -202,  -137,    77,    96},
+ {   26,  -179,  -469, -1008, -1260,   262,   -35,  -132,  -259},
+ {  -66,  -232,  -447,  -533,  -789,  -191,  -100,  -267,   364}
+};
+
+static const int16_t dico2_isf[256][7] = {
+ {  1357,  1313,  1136,   784,   438,   181,   145},
+ {   636,   648,   667,   568,   442,   217,   362},
+ {   427,   440,   674,   524,   332,   117,  -417},
+ {   121,   295,   468,   465,   230,    44,  -221},
+ {  -147,  -240,   149,    80,   390,   278,   106},
+ {  -418,  -556,   552,   511,   235,   144,   -95},
+ {    43,   193,   274,   150,    67,    34,  -273},
+ {   -43,  -126,   171,   416,   282,    63,  -354},
+ {  -372,   -86,  -344,  -108,   -94,  -182,   -89},
+ {  -600,  -840,  -200,   465,   258,   -11,  -253},
+ {   -48,   329,    97,  -290,  -543,  -795,  -354},
+ {  -570,  -117,   187,    10,  -133,  -416,   -76},
+ {  -618,  -129,  -247,  -371,    45,   -76,   277},
+ { -1022, -1079,   126,   474,   254,   127,    52},
+ {  -281,    76,  -167,  -361,  -283,  -551,  -283},
+ {  -119,   -52,    -1,   134,   -32,  -204,  -415},
+ {  1064,   827,   637,   684,   464,   209,    12},
+ {   482,   416,   449,   371,   335,   294,   194},
+ {   719,   576,   365,   135,   113,    91,  -199},
+ {   298,   176,   493,   366,   194,   163,    36},
+ {   -35,  -236,  -259,   -36,    -4,    99,   152},
+ {   -98,  -306,   -27,   228,    90,   111,   -86},
+ {    91,    13,  -211,  -258,  -106,    86,   -64},
+ {    73,   -35,   -57,   -31,   162,    35,  -192},
+ {  -109,  -335,  -629,   -66,   -61,  -128,   322},
+ {  -495,  -669,  -728,   193,    31,  -220,   122},
+ {   324,    95,   -89,   -91,  -409,  -710,  -154},
+ {     0,  -234,    92,    33,  -343,  -609,  -220},
+ {  -343,  -408,  -476,  -655,  -153,    82,   222},
+ {  -490,  -745,  -255,    49,   -48,   135,  -127},
+ {   119,   -67,  -328,  -390,  -272,  -545,   -56},
+ {   -57,  -130,   -10,    -7,  -164,   -47,   -22},
+ {   984,  1064,   961,   568,   210,   -27,    16},
+ {   811,   691,   754,   514,   224,   -35,   166},
+ {   662,   704,   618,   386,    57,  -211,  -257},
+ {   510,   359,   418,   393,    91,  -144,   -18},
+ {  -193,   -31,   -27,   223,    89,  -143,    24},
+ {  -112,   -98,   471,   319,   185,     3,   175},
+ {   252,   146,   -47,   272,    48,  -211,  -234},
+ {   146,    69,   203,   364,    68,   -52,    51},
+ {  -259,  -478,  -697,  -349,  -758,  -501,    63},
+ {  -501,  -769,  -289,    79,  -311,  -497,  -106},
+ {   251,    53,  -235,  -469,  -895,  -884,   145},
+ {  -416,  -551,   140,  -133,  -523,  -775,    44},
+ {  -326,  -423,  -713,  -497,   -86,  -431,    99},
+ {  -757,  -772,  -160,   -76,   -46,   -32,   379},
+ {    85,   -35,  -200,  -401,  -663, -1040,  -247},
+ {  -180,  -330,   -92,  -376,    27,  -183,  -110},
+ {  1279,  1086,   781,   502,   324,   164,   157},
+ {   682,   466,   449,   277,   146,    28,   409},
+ {   635,   472,   390,   107,  -232,  -538,  -139},
+ {   196,   396,   332,   213,   209,   -29,   -81},
+ {   150,   -95,  -312,    76,   -77,  -320,   -50},
+ {    46,     9,    47,   175,   139,    30,   384},
+ {   218,   206,   -24,  -250,   -96,  -276,  -183},
+ {    26,   119,    38,    14,    -4,  -133,   -52},
+ {  -477,  -614,  -987,  -715,  -631,  -813,   200},
+ {  -744, -1009, -1065,  -745,  -631,  -171,    18},
+ {  -137,  -251,  -483,  -613,  -980, -1203,    12},
+ {  -605,  -767,  -562,  -686, -1088,  -515,    58},
+ {  -202,  -428,  -782, -1072,   -96,  -234,  -179},
+ {  -480,  -709, -1070,  -897,  -131,   -92,   321},
+ {  -145,  -193,  -512,  -729,  -572,  -765,  -210},
+ {  -331,  -585,  -525,  -631,  -281,  -208,  -303},
+ {  1165,  1104,   939,   828,   716,   426,   155},
+ {     6,  -109,   820,   778,   415,   113,   -27},
+ {   381,   339,   314,   265,   121,    -9,  -474},
+ {  -373,    47,   584,   442,    99,  -231,  -113},
+ {  -496,   -38,  -285,   262,   305,   170,     4},
+ {  -587,  -556,    69,    66,   471,   354,    13},
+ {  -138,    70,   -18,   106,    67,   167,  -302},
+ {  -445,  -141,   185,   191,   151,    83,  -133},
+ {  -257,  -521,  -720,  -198,   134,   -46,  -182},
+ {  -819, -1168,  -777,   512,   359,    95,  -113},
+ {   137,    -2,   -74,  -138,  -401,  -114,  -371},
+ {  -242,  -466,   204,   223,   -31,  -212,  -192},
+ {  -532,  -637,  -466,  -686,   256,   277,  -139},
+ { -1141, -1244,  -381,   -75,   -54,    14,    88},
+ {  -311,   115,  -143,  -499,  -343,   124,  -416},
+ {  -616,  -147,  -135,    43,    -4,   121,  -369},
+ {   835,   783,   641,   390,   355,   350,    64},
+ {    72,   194,   443,   467,   436,   219,   372},
+ {   464,   369,   192,     4,  -156,   -72,  -226},
+ {    57,   206,   303,   205,   188,   101,   265},
+ {   -40,  -205,  -488,  -184,   276,    64,   -26},
+ {  -217,  -433,  -297,   137,   328,   308,  -289},
+ {   378,    81,  -308,  -465,    57,   -37,   227},
+ {  -100,    24,   -36,  -151,   199,     8,   143},
+ {  -426,  -697, -1059,  -133,   388,   161,   321},
+ {  -644, -1023, -1271,    39,    66,  -123,    70},
+ {   372,   177,  -173,  -556,  -553,  -304,  -189},
+ {  -117,  -369,  -425,  -122,  -462,  -152,   -73},
+ {  -649,  -850, -1189,  -767,   497,   360,   222},
+ {  -798, -1139, -1455,  -190,   430,   234,   179},
+ {    42,   -94,  -405,  -692,    38,  -202,  -246},
+ {  -169,  -366,  -290,   -88,   -64,    32,  -292},
+ {  1010,   923,   938,   710,   465,   230,   342},
+ {   217,   300,  1054,   675,    68,  -458,  -179},
+ {    78,   453,   316,    18,  -237,  -496,  -243},
+ {   167,    21,   424,   215,   -91,  -303,  -170},
+ {  -290,   -81,   -70,   -67,    40,    54,   -59},
+ {  -353,  -427,   -90,    53,    94,     9,    54},
+ {   -28,   318,   283,    15,  -240,   -58,    79},
+ {   -75,  -121,   229,    35,    58,     6,  -133},
+ {  -351,  -514,  -744,  -834,  -705,  -137,   164},
+ { -1124, -1388, -1055,  -230,   -73,    40,    36},
+ {  -163,  -233,  -532,  -785, -1170,  -697,    96},
+ {  -788,  -959,  -246,  -430,  -624,  -165,    -8},
+ {  -856,  -540,  -630,  -907,  -337,   -70,    76},
+ {  -937, -1042,  -659,  -733,  -208,   199,   -26},
+ {  -523,    78,   -98,  -501,  -869,  -890,   -81},
+ {  -624,  -703,   -45,  -348,   -25,    87,  -186},
+ {  1005,   823,   546,   249,    90,   -22,   207},
+ {   298,   397,   381,   319,   200,    62,   303},
+ {   473,   379,   133,  -247,  -632,  -441,    75},
+ {   284,   208,   391,   115,   -25,    44,    95},
+ {   -72,    79,   -95,   -63,  -129,  -293,   203},
+ {  -164,  -349,   115,   122,    69,    -1,   378},
+ {   348,   170,    99,    58,  -179,  -302,   188},
+ {  -190,    -2,   150,    23,   -51,   -11,   216},
+ {  -615,  -863, -1090, -1427,  -802,   -48,    -6},
+ {  -961, -1276, -1548,  -727,   -58,    56,   223},
+ {  -124,  -255,  -561,  -988, -1277,  -148,   -82},
+ {  -480,  -660,  -891, -1191, -1339,  -325,    20},
+ {  -621,  -917, -1296, -1350,   264,   289,    50},
+ {  -844, -1022, -1345, -1329,  -293,    46,   278},
+ {  -260,  -468,  -829, -1176,  -533,  -560,   -78},
+ {  -215,  -484,  -822, -1233,  -791,    15,  -138},
+ {  1301,  1317,  1262,  1048,   716,   357,   -64},
+ {   578,   824,   925,   802,   630,   362,   102},
+ {   470,   925,   767,   514,   327,   190,  -112},
+ {   225,   492,   495,   437,   598,   384,   -45},
+ {    43,    82,   -42,   175,   519,   342,   -64},
+ {  -304,  -154,   159,   576,   403,   221,   327},
+ {   214,   244,   122,   -62,   312,    92,  -160},
+ {   218,   208,   310,   268,   306,   323,  -199},
+ {  -285,  -269,   -79,  -124,  -143,  -153,   236},
+ {  -205,  -384,  -426,   344,    59,  -185,  -184},
+ {  -272,   247,   126,  -210,  -518,  -468,    78},
+ {   -99,  -120,   502,   160,  -280,  -557,   304},
+ {  -423,   -17,  -283,  -443,   215,   212,  -140},
+ {  -564,  -684,  -228,   510,   361,   130,   323},
+ {  -428,   335,    98,   -65,    36,  -215,  -246},
+ {  -362,    51,   364,   -16,  -234,   150,  -165},
+ {   914,   883,   751,   653,   676,   464,  -153},
+ {   631,   545,   535,   720,   596,   360,   -81},
+ {   783,   712,   512,   439,   341,   251,  -391},
+ {   497,   417,   249,   372,   295,   173,  -193},
+ {   128,  -110,  -385,    93,    39,   173,  -231},
+ {   216,   -59,  -253,   462,   389,   154,    69},
+ {   455,   270,    -4,  -337,   -49,   233,  -322},
+ {   307,   143,    53,   218,   128,   236,  -156},
+ {   -37,  -186,  -240,  -411,  -110,     9,   399},
+ {  -140,  -365,  -628,   258,   380,   214,   277},
+ {   131,   454,   177,  -285,  -520,   108,  -214},
+ {    77,  -141,   201,  -123,  -490,  -131,    60},
+ {   -14,  -194,  -521,  -741,   273,   362,   -33},
+ {  -362,  -566,  -287,  -228,   161,   237,   317},
+ {  -269,   195,   -75,  -375,  -204,    11,    77},
+ {  -128,  -264,  -156,  -223,  -475,   265,    27},
+ {  1238,  1147,   916,   689,   432,   210,  -280},
+ {   800,   664,   879,   726,   411,   160,  -164},
+ {   454,   686,   536,   275,   147,    46,   111},
+ {   303,   486,   512,   355,   241,   181,   -69},
+ {    79,    92,    29,   147,   233,    52,    17},
+ {  -171,   289,   131,   439,   271,     3,   -10},
+ {   413,   241,   144,   174,   155,    -2,    14},
+ {    58,   217,   247,   219,   149,   175,   -18},
+ {   228,    -8,  -240,  -206,  -513,  -191,   202},
+ {   -96,  -272,  -454,    33,  -300,  -575,    46},
+ {   -10,  -108,  -246,  -347,  -770,  -535,     9},
+ {  -326,  -430,   -61,  -321,  -704,  -299,   201},
+ {    -1,  -280,  -603,  -419,  -185,    18,   -36},
+ {  -516,  -522,  -379,  -291,  -181,   -97,    27},
+ {  -159,  -313,  -525,  -224,  -510,  -831,  -197},
+ {  -292,  -459,   -59,  -310,  -562,  -143,  -351},
+ {  1066,   912,   631,   389,   207,    86,  -224},
+ {   596,   512,   596,   505,   314,   122,   -48},
+ {   787,   861,   441,   -93,  -303,    33,  -190},
+ {   257,   469,   337,    51,    15,   298,   -93},
+ {   295,    73,  -119,    25,    36,    23,   108},
+ {   -28,    -3,   -32,   114,    21,   185,   107},
+ {   482,   305,    15,  -279,  -319,    52,    96},
+ {   226,    46,   115,    72,  -136,   133,  -125},
+ {    18,  -207,  -559,  -590,  -503,  -482,   321},
+ {  -571,  -789,  -951,  -172,  -441,  -538,   113},
+ {   181,    14,  -310,  -641, -1001,  -202,   159},
+ {  -136,  -393,  -433,  -513,  -911,  -144,   -22},
+ {    72,  -265,  -706,  -954,  -159,    53,   332},
+ {  -338,  -591,  -852,  -383,  -395,    56,    44},
+ {    43,  -158,  -464,  -897,  -631,  -157,  -294},
+ {  -161,  -128,  -328,  -573,  -483,  -125,    11},
+ {  1017,   906,  1051,  1005,   679,   341,  -102},
+ {   359,   334,  1567,  1314,   723,   105,    10},
+ {   -65,   726,   529,   301,   220,    43,  -273},
+ {  -510,   436,   719,   566,   358,   179,   114},
+ {  -560,   298,   133,  -120,   342,   225,    14},
+ {  -899,  -101,   217,   617,   400,   146,   -58},
+ {   -41,   352,    82,  -196,    39,   121,  -167},
+ {  -212,    59,   447,   284,   423,   250,  -169},
+ {  -371,  -484,  -596,    30,   -41,   249,    22},
+ {  -372,  -650,  -794,   477,   445,   216,   -79},
+ {  -352,   275,    17,  -443,  -929,    92,    19},
+ {  -699,  -696,   431,   264,   -49,  -310,   182},
+ {  -978,  -217,  -430,  -400,   101,   261,    72},
+ {  -929,  -889,  -357,   -13,   463,   378,   236},
+ {  -826,    56,    30,  -299,  -360,  -128,   -51},
+ {  -878,  -299,  -111,    75,    65,    36,     3},
+ {   817,   368,   -25,   354,   697,   591,  -173},
+ {   309,   212,   222,   751,   484,   140,   -56},
+ {   593,   379,    70,    -8,   258,   180,   110},
+ {   165,   -46,   255,   297,   219,   273,   105},
+ {   160,   -70,  -358,  -181,   379,   330,   319},
+ {  -238,  -369,  -198,   740,   580,   319,  -143},
+ {   201,   109,  -202,  -456,   328,   276,  -141},
+ {   203,   170,   111,    42,   207,   360,   188},
+ {  -345,  -399,  -513,  -233,   650,   422,    81},
+ {  -635,  -961, -1220,   463,   539,   204,   209},
+ {   202,   -25,  -194,  -498,  -787,   193,  -143},
+ {  -449,  -538,   195,  -106,  -331,    68,    62},
+ {  -228,  -477,  -840,  -576,   317,   128,   283},
+ {  -671,  -937,  -807,  -114,   391,   335,   -62},
+ {   246,     2,  -314,  -679,  -303,   180,   -88},
+ {  -107,  -272,    90,  -198,   -28,   290,  -112},
+ {   885,  1149,  1021,   712,   496,   281,   -83},
+ {   269,   492,   787,   643,   347,    70,   124},
+ {   336,   636,   499,    92,  -229,  -179,   191},
+ {    26,   402,   564,   340,   149,   -11,   135},
+ {  -440,   561,   470,   204,   -72,  -186,   140},
+ {  -720,    14,   355,   229,    68,  -133,   465},
+ {   110,   310,   103,    12,   106,    29,   158},
+ {  -178,   113,   161,   142,   121,   115,    27},
+ {  -651,  -414,  -645,  -152,  -164,   -13,  -429},
+ {  -639,  -944,  -681,  -104,   -81,    52,  -189},
+ {  -663,  -164,  -316,  -683,  -954,  -205,   -83},
+ {  -609,  -669,  -172,  -517,  -694,   283,   -80},
+ {  -646,  -152,  -383,  -678,  -246,   -40,  -143},
+ {  -747,  -796,  -745,  -390,   -98,    43,   275},
+ {  -599,  -199,  -398,  -433,  -436,  -538,    31},
+ { -1107,  -568,  -376,  -265,  -126,   -21,     1},
+ {   847,   573,   308,   392,   305,   101,    55},
+ {   273,   293,   201,   267,   346,   201,   123},
+ {   727,   480,   226,     2,   -65,  -138,   164},
+ {   273,   208,   173,   292,    12,   253,   174},
+ {   340,   207,   180,    88,   116,    46,   475},
+ {  -460,  -166,   -30,    13,   110,   173,   396},
+ {   137,    88,    43,  -137,   -94,    34,   284},
+ {    96,   -14,   226,    40,    63,    70,   130},
+ {  -467,  -735, -1012, -1174,  -307,   305,   -67},
+ {  -612,  -920, -1146,  -567,    -8,    92,   -25},
+ {  -182,  -271,  -492,  -754,  -857,   287,   -75},
+ {  -494,  -787,  -689,  -683,  -709,   137,  -326},
+ {  -288,  -550,  -903, -1105,   334,   321,   -62},
+ {  -354,  -653,  -834,  -445,     1,   377,  -152},
+ {  -162,  -306,  -608,  -937,  -297,   247,  -192},
+ {  -234,  -477,  -244,  -488,  -266,   342,  -332}
+};
+
+static const int16_t dico21_isf[64][3] = {
+ {   329,   409,   249}, {   -33,   505,   160},
+ {   -29,   -14,   582}, {  -262,   127,   354},
+ {   145,   237,   175}, {  -152,   245,   122},
+ {    27,    42,   340}, {   -84,   -93,   311},
+ {   285,   222,  -156}, {    47,   -43,  -504},
+ {   234,   121,   385}, {   104,  -317,    45},
+ {   176,   195,     8}, {   104,   -59,   -94},
+ {   177,    53,   192}, {   -34,  -127,   152},
+ {   570,   277,   -34}, {   -67,  -329,  -639},
+ {  -157,  -272,   462}, {  -177,  -462,   198},
+ {   322,   179,   115}, {  -386,   171,    19},
+ {    19,   -12,   195}, {  -120,  -252,   201},
+ {   304,    36,  -336}, {  -128,  -221,  -380},
+ {   171,  -185,   296}, {  -242,  -312,    23},
+ {   198,    39,    16}, {    -3,  -177,  -111},
+ {   111,   -93,    76}, {   -92,  -223,     4},
+ {   177,   406,   -44}, {  -168,   380,  -149},
+ {    -4,   273,   331}, {  -420,   513,   277},
+ {    21,   247,    47}, {   -58,   131,    -2},
+ {    -3,   134,   180}, {  -145,    40,   175},
+ {   189,    74,  -145}, {   -27,   -45,  -325},
+ {   370,  -114,   -21}, {   -83,  -415,  -173},
+ {    77,    95,   -51}, {   -40,   -30,   -67},
+ {    71,    88,    86}, {   -35,   -98,    14},
+ {    69,   197,  -334}, {  -196,    79,  -231},
+ {  -348,  -137,   218}, {  -352,   -89,   -85},
+ {    47,   201,  -130}, {  -165,    37,   -15},
+ {   -43,     3,    86}, {  -161,  -108,    79},
+ {    83,    21,  -237}, {   -81,  -149,  -238},
+ {   150,  -186,  -251}, {  -186,  -249,  -162},
+ {   -19,    66,  -139}, {   -26,   -50,  -181},
+ {    24,    11,     0}, {  -130,  -105,   -98}
+};
+
+static const int16_t dico22_isf[128][3] = {
+ {  -127,   310,    42}, {  -242,   197,     5},
+ {  -151,    84,   -17}, {  -214,   127,  -149},
+ {  -247,  -131,   159}, {  -268,  -267,   -95},
+ {  -217,     1,   -79}, {  -271,   -80,  -185},
+ {   -45,   436,   159}, {   165,   199,   391},
+ {   -33,    81,   187}, {   -66,   -42,   355},
+ {  -298,   -57,   343}, {  -108,  -537,   226},
+ {  -144,   -23,   193}, {   176,  -402,    87},
+ {    53,   296,    25}, {   -84,   253,  -104},
+ {   -58,   105,  -126}, {  -169,   174,  -314},
+ {   -48,    44,  -294}, {  -164,  -417,  -242},
+ {  -139,     3,  -194}, {  -155,  -207,  -211},
+ {   119,   322,   213}, {   333,    50,   380},
+ {   237,   247,    -2}, {   466,   -16,   201},
+ {   238,  -255,  -107}, {    67,  -440,  -149},
+ {   122,   -88,  -139}, {    88,  -247,   -73},
+ {   -41,   231,   167}, {   -62,   155,    16},
+ {   -65,    16,    77}, {   -68,    -2,   -63},
+ {  -151,  -300,   160}, {   -18,  -333,    54},
+ {   -56,   -94,     5}, {     2,  -190,    14},
+ {    92,   148,   209}, {   108,     9,   272},
+ {   108,    35,   110}, {   142,   -85,   145},
+ {    47,  -157,   279}, {     3,  -320,   246},
+ {    43,   -72,    68}, {    86,  -217,   135},
+ {    36,   140,    79}, {    56,   175,   -49},
+ {    26,    45,     3}, {    73,    55,  -101},
+ {   109,  -183,  -242}, {    -4,  -283,  -242},
+ {    48,   -68,   -48}, {    -6,  -153,  -122},
+ {   161,   196,    96}, {   232,    80,   190},
+ {   165,    97,    11}, {   258,   -31,    71},
+ {   267,   -77,   -91}, {   311,  -209,    87},
+ {   152,   -14,   -22}, {   150,  -149,     9},
+ {  -324,   557,   187}, {  -384,   307,    46},
+ {  -251,    27,    77}, {  -365,    77,   -52},
+ {  -482,   -84,   160}, {  -424,  -515,   -64},
+ {  -294,  -120,    -4}, {  -476,  -116,  -109},
+ {   -97,   318,   365}, {   106,   627,   445},
+ {  -190,   120,   287}, {  -146,    65,   619},
+ {  -427,   242,   363}, {  -361,  -371,   432},
+ {  -347,   102,   168}, {  -629,   195,   -14},
+ {   -65,   476,   -47}, {  -297,   320,  -168},
+ {   -55,   356,  -264}, {  -391,    82,  -286},
+ {   -51,   -31,  -556}, {  -178,  -399,  -586},
+ {  -205,   -49,  -360}, {  -343,  -238,  -337},
+ {   220,   457,    58}, {   561,   467,   259},
+ {   340,   270,  -168}, {   450,    77,  -280},
+ {    60,   167,  -413}, {   133,  -252,  -492},
+ {   216,   157,  -290}, {   282,     0,  -495},
+ {  -226,   293,   183}, {  -157,   135,   122},
+ {  -158,   -59,    39}, {  -133,  -118,   -97},
+ {  -332,  -309,   113}, {  -160,  -425,    -6},
+ {  -149,  -211,    24}, {   -80,  -277,   -90},
+ {   -11,   125,   338}, {   130,   -71,   465},
+ {     5,   -45,   184}, {   237,   -95,   253},
+ {  -139,  -197,   297}, {   -19,  -300,   511},
+ {   -63,  -152,   139}, {   250,  -289,   336},
+ {   124,   339,  -150}, {    34,   176,  -208},
+ {   171,   166,  -116}, {    94,    38,  -229},
+ {    75,   -65,  -339}, {   -78,  -205,  -385},
+ {     0,   -30,  -163}, {   -56,  -110,  -242},
+ {   321,   244,   194}, {   505,   238,    -1},
+ {   317,   116,    65}, {   309,    88,   -74},
+ {   452,   -51,   -50}, {   334,  -217,  -290},
+ {   211,    41,  -152}, {   238,   -55,  -260}
+};
+
+static const int16_t dico23_isf[128][3] = {
+ {   -10,   151,   359}, {   136,   298,   223},
+ {   255,  -104,   290}, {   423,     6,   183},
+ {  -270,  -269,   -98}, {   -52,   -82,    13},
+ {   -82,  -274,   -97}, {    90,  -246,   -72},
+ {  -299,   -70,   421}, {   -88,   365,   430},
+ {   187,  -318,   381}, {   380,    37,   488},
+ {  -373,  -316,    79}, {  -308,  -101,     5},
+ {  -135,  -451,     8}, {    72,  -421,  -154},
+ {   180,   170,  -121}, {    62,   177,   -40},
+ {   326,    80,  -105}, {   248,   263,    -5},
+ {  -168,  -181,  -221}, {    -2,   -23,  -158},
+ {   -14,  -149,  -121}, {   119,   -91,  -147},
+ {   119,   332,  -153}, {    49,   303,    34},
+ {   442,   -55,   -69}, {   217,   454,    58},
+ {  -359,  -187,  -375}, {   -42,    50,  -274},
+ {    -8,  -267,  -249}, {    85,   -86,  -346},
+ {   -77,   -40,   345}, {    89,   134,   219},
+ {   156,   -80,   160}, {   108,    40,   116},
+ {  -158,  -206,    29}, {     5,   -32,   175},
+ {   -65,  -158,   146}, {    55,   -78,    73},
+ {  -114,  -222,   353}, {   -47,    81,   211},
+ {    49,  -151,   268}, {   105,     4,   302},
+ {  -263,  -132,   183}, {  -151,   -28,   201},
+ {  -177,  -307,   166}, {   101,  -221,   130},
+ {    74,    58,   -98}, {    32,    44,    13},
+ {   194,    30,  -142}, {   170,    96,     8},
+ {  -136,  -119,   -91}, {   -65,     8,   -55},
+ {     3,  -188,    12}, {    45,   -63,   -49},
+ {   149,   -21,   -19}, {    24,   144,    95},
+ {   254,   -22,    60}, {   161,   196,    96},
+ {  -158,   -61,    48}, {   -70,    33,    82},
+ {   -23,  -321,    58}, {   155,  -147,     5},
+ {  -364,   328,    77}, {   -21,   453,   173},
+ {  -108,    82,   630}, {   367,   263,   208},
+ {  -300,   -62,  -176}, {  -205,   143,  -158},
+ {  -169,  -410,  -264}, {   257,  -269,  -100},
+ {  -636,   289,    -2}, {  -292,   627,   173},
+ {  -382,  -363,   387}, {   248,   524,   447},
+ {  -521,  -111,  -107}, {  -395,   118,  -274},
+ {  -343,  -680,  -125}, {  -172,  -447,  -663},
+ {    75,   148,  -367}, {   -79,   263,   -94},
+ {   249,   148,  -286}, {   380,   271,  -162},
+ {  -142,    -4,  -186}, {   -57,   111,  -125},
+ {   -35,  -108,  -254}, {   100,    29,  -242},
+ {   -80,   303,  -264}, {   -78,   464,   -57},
+ {   248,   -22,  -494}, {   661,   662,    44},
+ {  -193,   -40,  -330}, {  -178,   145,  -337},
+ {   -90,  -199,  -400}, {   -40,   -23,  -498},
+ {  -192,   114,   315}, {   -41,   244,   190},
+ {    88,   -97,   485}, {   241,    80,   212},
+ {  -246,    40,    87}, {  -156,   147,   134},
+ {    -2,  -334,   239}, {   308,  -203,   110},
+ {  -459,   251,   422}, {  -218,   310,   228},
+ {   -86,  -346,   654}, {   184,   175,   425},
+ {  -481,   -63,   169}, {  -349,   117,   188},
+ {  -125,  -560,   310}, {   158,  -416,    94},
+ {    46,   171,  -192}, {   -63,   157,    14},
+ {   256,   -35,  -271}, {   322,   123,    53},
+ {  -214,     4,   -76}, {  -156,    86,   -18},
+ {   128,  -197,  -232}, {   265,   -90,   -98},
+ {  -308,   332,  -145}, {  -131,   308,    58},
+ {   509,    59,  -339}, {   562,   196,   -14},
+ {  -378,   100,   -47}, {  -234,   202,     1},
+ {   104,  -270,  -493}, {   319,  -210,  -325}
+};
+
+static const int16_t dico24_isf[32][3] = {
+ {   -79,   -89,    -4}, {  -171,    77,  -211},
+ {   160,  -193,    98}, {   120,  -103,   323},
+ {    32,   -22,  -129}, {    72,    78,  -268},
+ {   182,   -76,   -66}, {   309,    99,  -145},
+ {  -229,  -157,   -84}, {  -383,    98,   -71},
+ {   -90,  -352,    12}, {  -284,  -178,   178},
+ {   -65,  -125,  -166}, {   -87,  -175,  -351},
+ {    42,  -198,   -48}, {   154,  -140,  -243},
+ {   -77,    18,   108}, {   -39,   355,    91},
+ {    87,     8,   155}, {    -4,   158,   239},
+ {   128,    95,   -54}, {     7,   246,  -124},
+ {   258,    15,    89}, {   206,   216,    98},
+ {  -201,     9,    18}, {  -312,   233,   204},
+ {   -39,  -174,   155}, {  -144,    -9,   284},
+ {   -57,    70,   -69}, {  -157,   187,    18},
+ {    54,   -30,    23}, {    24,   135,    55}
+};
+
+static const int16_t dico25_isf[32][4] = {
+ {   169,   142,  -119,   115}, {   206,   -20,    94,   226},
+ {  -106,   313,   -21,    16}, {   -62,   161,    71,   255},
+ {   -89,   101,  -185,   125}, {    72,   -30,  -201,   344},
+ {  -258,    33,    -8,    81}, {  -104,  -154,    72,   296},
+ {   144,   -68,  -268,   -25}, {    81,   -78,   -87,   106},
+ {    22,   155,  -186,  -119}, {   -46,   -28,    27,    91},
+ {  -114,   -37,  -175,   -33}, {   -94,  -222,  -189,   122},
+ {  -132,  -119,  -191,  -270}, {  -172,  -173,    18,   -43},
+ {   279,   135,   -42,  -128}, {   187,   -86,   229,  -138},
+ {   159,   240,   140,    46}, {    69,    25,   227,    77},
+ {    21,   115,    13,     8}, {    68,  -248,   126,    81},
+ {  -150,   137,   207,    -9}, {  -154,  -133,   289,    67},
+ {   143,   -37,   -86,  -326}, {   180,   -32,    19,   -23},
+ {    26,   168,   116,  -233}, {   -32,   -26,   118,   -78},
+ {     3,    -8,   -45,  -115}, {    57,  -215,   -54,   -83},
+ {  -209,   112,   -22,  -167}, {   -91,  -151,   168,  -262}
+};
+
+static const int16_t dico21_isf_36b[128][5] = {
+ {   -52,   -96,   212,   315,   -73}, {    82,  -204,   363,   136,  -197},
+ {  -126,  -331,   183,   218,   143}, {   -49,   -41,   557,   230,    72},
+ {     2,   -73,   163,   377,   221}, {   133,   111,   278,   215,  -110},
+ {  -102,   -20,   284,   113,   273}, {    84,   319,   290,    18,    85},
+ {   -25,    -5,   125,   132,  -204}, {   -38,    -5,   286,    -9,  -356},
+ {  -140,  -256,    92,   117,  -189}, {  -144,   191,   313,    51,   -98},
+ {   167,   -10,    44,   247,    36}, {   381,   197,   238,    74,     6},
+ {    38,  -408,    29,    -3,   -85}, {    92,   266,   157,   -25,  -200},
+ {   161,  -121,    70,    84,  -140}, {   -16,   -86,   112,   -94,  -189},
+ {  -269,  -270,   351,   107,   -24}, {   -68,   -67,   492,  -103,  -155},
+ {   -53,  -131,    62,   122,    10}, {   135,    84,   283,   -55,  -120},
+ {   -12,  -219,   331,   -81,   167}, {   220,  -136,   147,  -172,   -42},
+ {   140,   -95,  -109,   -88,  -194}, {     0,    -2,    -4,   -33,  -381},
+ {   -66,  -217,   152,  -186,  -402}, {   244,   108,   156,  -140,  -395},
+ {   113,  -136,  -196,   110,   -24}, {   214,   118,    11,   -64,  -131},
+ {  -110,  -286,    -6,  -332,    16}, {    94,    97,    79,  -291,  -205},
+ {    -5,   -39,   -20,   252,   -96}, {    76,   174,   101,   163,    61},
+ {   -69,  -239,   -55,   399,     6}, {  -115,   319,   164,   275,   196},
+ {   -15,    36,   -47,   331,   121}, {   226,   209,   271,   325,   184},
+ {    13,   -80,  -218,   471,   353}, {   288,   378,    16,   -51,   251},
+ {   174,   116,    52,   149,  -279}, {   235,   276,    39,   120,   -48},
+ {     0,  -108,  -108,   241,  -339}, {   -93,   534,    45,    33,   -87},
+ {   194,   149,   -71,   405,   -44}, {   409,   370,    81,  -186,  -154},
+ {    25,  -102,  -448,   124,  -173}, {    22,   408,  -110,  -310,  -214},
+ {   -26,    23,   -83,   114,    14}, {  -110,   164,    52,   223,   -82},
+ {    37,   -25,  -263,   306,   -15}, {  -466,   415,   292,   165,   -18},
+ {    29,   -19,  -171,   155,   182}, {   179,   144,   -27,   231,   258},
+ {  -103,  -247,  -396,   238,   113}, {   375,  -154,  -109,    -4,   156},
+ {    98,    85,  -292,    -5,  -124}, {   116,   139,  -116,   -98,  -294},
+ {   -14,   -83,  -278,  -117,  -378}, {   106,    33,  -106,  -344,  -484},
+ {   119,    17,  -412,   138,   166}, {   384,   101,  -204,    88,  -156},
+ {  -121,  -284,  -300,    -1,  -166}, {   280,    33,  -152,  -313,   -81},
+ {   -37,    22,   229,   153,    37}, {   -60,   -83,   236,    -8,   -41},
+ {  -169,  -228,   126,   -20,   363}, {  -235,    17,   364,  -156,   156},
+ {   -25,   -30,    72,   144,   156}, {   153,   -26,   256,    97,   144},
+ {   -21,   -37,    48,   -65,   250}, {    63,    77,   273,  -128,   124},
+ {  -129,   -26,    40,     9,  -115}, {    -6,    82,    38,   -90,  -182},
+ {  -336,   -13,    28,   158,    91}, {   -30,   241,   137,  -170,   -17},
+ {   146,    14,   -11,    33,    61}, {   192,   197,    54,   -84,    85},
+ {    23,  -200,   -78,   -29,   140}, {   122,   237,   106,  -341,   136},
+ {   -57,  -142,   -85,   -16,   -74}, {   -59,   -90,    -8,  -187,   -20},
+ {  -211,  -267,   216,  -179,  -110}, {   -50,    -7,   220,  -267,   -70},
+ {   -57,   -42,   -17,   -15,    71}, {    32,    21,    63,  -137,    33},
+ {  -137,  -175,   104,   -68,    97}, {   -67,   -43,   133,  -301,   221},
+ {  -116,  -200,   -81,   -92,  -272}, {   -64,   -41,   -54,  -244,  -220},
+ {  -287,  -242,   -50,   -87,   -89}, {  -245,   236,   102,  -166,  -295},
+ {    66,    24,  -162,   -71,    95}, {    66,   136,   -90,  -220,   -36},
+ {   -98,  -161,  -222,  -188,    29}, {   -18,    18,   -19,  -415,     9},
+ {    49,    61,   100,    39,   -56}, {  -111,    82,   135,   -31,    52},
+ {   -90,  -153,   -93,   189,   182}, {  -214,   295,   119,   -74,   284},
+ {     2,   137,    37,    47,   182}, {    92,   117,   184,   -53,   373},
+ {   -21,   -14,   -35,   136,   391}, {   146,   129,  -164,   -28,   333},
+ {    92,    80,   -84,   100,  -134}, {    -8,   217,   -32,     3,   -47},
+ {  -151,   251,  -215,   142,    92}, {  -224,   310,  -172,  -275,    98},
+ {   159,   155,  -177,   112,    53}, {   205,    27,     8,  -240,   192},
+ {   169,   120,  -319,  -201,   106}, {    11,    36,   -86,  -237,   455},
+ {  -109,  -154,  -163,   174,   -55}, {   -38,    32,  -101,   -78,   -59},
+ {  -205,  -321,   -97,    69,    79}, {  -310,    44,    18,  -185,    34},
+ {  -115,   -20,  -148,   -39,   203}, {   -29,   154,   -30,  -158,   166},
+ {   -45,  -131,  -317,   -24,   363}, {  -165,  -205,  -112,  -222,   265},
+ {   -32,   -44,  -150,    54,  -193}, {    -6,   -38,  -255,  -169,  -115},
+ {  -266,    87,  -189,   -36,  -169}, {   -60,   -87,  -266,  -436,  -170},
+ {   -68,   -81,  -278,    24,    38}, {   -23,   -19,  -155,  -256,   141},
+ {   -61,  -226,  -565,  -175,    71}, {     9,   -29,  -237,  -515,   263}
+};
+
+static const int16_t dico22_isf_36b[128][4] = {
+ {  -298,    -6,    95,    31}, {  -213,   -87,  -122,   261},
+ {     4,   -49,   208,    14}, {  -129,  -110,    30,   118},
+ {  -214,   258,   110,  -235}, {   -41,   -18,  -126,   120},
+ {   103,    65,   127,   -37}, {   126,   -36,   -24,    25},
+ {  -138,   -67,  -278,  -186}, {  -164,  -194,  -201,    78},
+ {  -211,   -87,   -51,  -221}, {  -174,   -79,   -94,   -39},
+ {    23,    -6,  -157,  -240}, {    22,  -110,  -153,   -68},
+ {   148,    -5,    -2,  -149}, {    -1,  -135,   -39,  -179},
+ {    68,   360,  -117,   -15}, {   137,    47,  -278,   146},
+ {   136,   260,   135,    65}, {    61,   116,   -45,    97},
+ {   231,   379,    87,  -120}, {   338,   177,  -272,     3},
+ {   266,   156,    28,   -69}, {   260,    84,   -85,    86},
+ {  -266,   154,  -256,  -182}, {   -17,   -65,  -304,    -6},
+ {   -40,   175,  -151,  -180}, {   -27,    27,   -87,   -63},
+ {   121,   114,  -166,  -469}, {   159,   -66,  -323,  -231},
+ {   214,   152,  -141,  -212}, {   137,    36,  -184,   -51},
+ {  -282,  -237,    40,    10}, {   -48,  -235,   -37,   251},
+ {   -54,  -323,   136,    29}, {   -88,  -174,   213,   198},
+ {  -390,    99,   -63,  -375}, {   107,  -169,  -164,   424},
+ {    69,  -111,   141,  -167}, {    74,  -129,    65,   144},
+ {  -353,  -207,  -205,  -109}, {  -160,  -386,  -355,    98},
+ {  -176,  -493,   -20,  -143}, {  -252,  -432,    -2,   216},
+ {   -90,  -174,  -168,  -411}, {    13,  -284,  -229,  -160},
+ {   -87,  -279,    34,  -251}, {   -75,  -263,   -58,   -42},
+ {   420,    53,  -211,  -358}, {   384,   -35,  -374,   396},
+ {    68,  -228,   323,    -2}, {   167,  -307,   192,   194},
+ {   459,   329,    -5,  -332}, {   375,    79,    -7,   313},
+ {   282,  -124,   200,   -92}, {   271,  -162,   -70,   180},
+ {  -157,  -298,  -514,  -309}, {    58,  -163,  -546,    18},
+ {   124,  -364,   167,  -238}, {    83,  -411,  -117,    96},
+ {   140,  -112,  -388,  -624}, {   259,  -133,  -317,    41},
+ {   163,  -130,   -64,  -334}, {   226,  -165,  -124,  -110},
+ {  -466,   -61,     6,   229}, {  -153,   205,  -145,   242},
+ {  -159,    48,   195,   148}, {   -58,    28,    31,   279},
+ {  -303,   185,   279,    -4}, {   -61,   197,    59,    86},
+ {  -114,   123,   168,   -52}, {    35,    36,   100,   126},
+ {  -407,   102,   -77,   -40}, {  -338,    -1,  -342,   156},
+ {  -179,   105,   -34,   -97}, {  -185,    84,   -35,   108},
+ {  -133,   107,   -91,  -357}, {  -180,    54,  -229,    24},
+ {   -44,    47,    47,  -182}, {   -66,    13,    45,     4},
+ {  -339,   251,    64,   226}, {   -42,   101,  -350,   275},
+ {   -99,   398,   142,   121}, {   111,    12,  -102,   260},
+ {     0,   505,   260,   -94}, {   161,   285,   -96,   224},
+ {    -4,   206,   314,    33}, {   167,   139,    88,   204},
+ {  -235,   316,   -60,   -25}, {    -8,  -150,  -312,   201},
+ {   -36,   292,    61,  -104}, {   -40,   174,  -162,    42},
+ {   -21,   402,   -29,  -351}, {    21,   152,  -360,   -93},
+ {    57,   191,   212,  -196}, {    76,   158,   -21,   -69},
+ {  -328,  -185,   331,   119}, {   -53,   285,    56,   337},
+ {  -107,   -24,   405,    29}, {   -18,   137,   272,   277},
+ {  -255,    22,   173,  -191}, {   295,   322,   325,   302},
+ {    21,   -27,   332,  -178}, {   119,    13,   271,   129},
+ {  -455,  -180,   116,  -191}, {  -227,    62,  -148,   524},
+ {  -176,  -287,   282,  -157}, {  -243,    13,   199,   430},
+ {   -59,   -49,   115,  -365}, {    72,  -172,  -137,    93},
+ {  -138,  -126,   141,   -84}, {     5,  -124,    38,   -20},
+ {  -258,   311,   601,   213}, {    94,   130,   -61,   502},
+ {    -1,  -157,   485,   313}, {   146,   -74,   158,   345},
+ {   276,   135,   280,   -57}, {   490,   252,    99,    43},
+ {   267,   -74,   429,   105}, {   278,   -23,   119,    94},
+ {  -542,   488,   257,  -115}, {   -84,  -244,  -438,   478},
+ {  -113,  -545,   387,   101}, {   -95,  -306,   111,   498},
+ {    95,   166,    22,  -301}, {   420,   -15,   -58,   -78},
+ {   270,    29,   122,  -282}, {   160,  -240,    50,   -38}
+};
+
+static const int16_t dico23_isf_36b[64][7] = {
+ {    81,   -18,    68,   -27,  -122,  -280,    -4},
+ {    45,  -177,   209,   -30,  -136,   -74,   131},
+ {   -44,   101,   -75,   -88,   -48,  -137,   -54},
+ {  -245,   -28,    63,   -18,  -112,  -103,    58},
+ {   -79,    -6,   220,   -65,   114,   -35,   -50},
+ {   109,   -65,   143,  -114,   129,    76,   125},
+ {   166,    90,   -61,  -242,   186,   -74,   -43},
+ {   -46,   -92,    49,  -227,    24,  -155,    39},
+ {    67,    85,    99,   -42,    53,  -184,  -281},
+ {   142,  -122,     0,    21,  -142,   -15,   -17},
+ {   223,    92,   -21,   -48,   -82,   -14,  -167},
+ {    51,   -37,  -243,   -30,   -90,    18,   -56},
+ {    54,   105,    74,    86,    69,    13,  -101},
+ {   196,    72,   -89,    43,    65,    19,    39},
+ {   121,    34,   131,   -82,    25,   213,  -156},
+ {   101,  -102,  -136,   -21,    57,   214,    22},
+ {    36,  -124,   205,   204,    58,  -156,   -83},
+ {    83,  -117,   137,   137,    85,   116,    44},
+ {   -92,  -148,   -68,    11,  -102,  -197,  -220},
+ {   -76,  -185,   -58,   132,   -26,  -183,    85},
+ {    -7,   -31,    -2,    23,   205,  -151,    10},
+ {   -27,   -37,    -5,   -18,   292,   131,     1},
+ {   117,  -168,     9,   -93,    80,   -59,  -125},
+ {  -182,  -244,    98,   -24,   135,   -22,    94},
+ {   221,    97,   106,    42,    43,  -160,    83},
+ {    25,   -64,   -21,     6,    14,   -15,   154},
+ {   126,    15,  -140,   150,   -10,  -207,  -114},
+ {    79,   -63,  -211,   -70,   -28,  -217,   165},
+ {    46,    38,   -22,   281,   132,   -62,   109},
+ {   112,    54,  -112,   -93,   208,    27,   296},
+ {   115,    10,  -147,    41,   216,    42,  -276},
+ {    50,  -115,  -254,   167,   117,    -2,    61},
+ {    17,   144,    34,   -72,  -186,  -150,   272},
+ {   -29,   -66,   -89,   -95,  -149,   129,   251},
+ {   122,     0,   -50,  -234,   -91,    36,    26},
+ {  -105,  -102,   -88,  -121,  -236,    -7,   -11},
+ {  -204,   109,     5,  -191,   105,   -15,   163},
+ {   -80,    32,   -24,  -209,    41,   294,    70},
+ {  -106,   -94,  -204,  -118,   120,   -50,   -37},
+ {   -82,  -241,    46,  -131,   -29,   150,   -55},
+ {    33,   155,   120,   -89,    -8,     7,    62},
+ {   213,    82,    61,    18,  -161,   144,   152},
+ {    30,   131,    65,   -87,  -255,   -17,  -107},
+ {    -8,    85,   -64,    51,  -162,   223,   -53},
+ {  -134,   261,    69,   -56,   218,    72,  -111},
+ {     2,   155,  -113,   -87,    49,    85,   -28},
+ {  -163,    42,    -1,  -196,     7,    39,  -245},
+ {    14,  -137,   -79,    11,  -160,   202,  -293},
+ {   -94,    33,   208,   100,    56,   -44,   326},
+ {   -78,   -41,   232,    13,  -142,   227,    80},
+ {   -16,   -87,   201,    33,  -133,    15,  -183},
+ {   -58,  -192,   -47,   184,  -128,   133,    99},
+ {  -205,    11,  -155,    78,    52,    72,   141},
+ {  -246,    26,    99,   151,    59,   115,   -64},
+ {   -79,   -47,   -16,   -14,     6,    47,   -43},
+ {   -72,  -178,   -27,   162,   112,    43,  -174},
+ {  -175,   238,   186,    71,   -54,  -188,   -76},
+ {  -225,   233,    39,   -39,  -158,   122,    44},
+ {   -26,    43,    84,   130,   -93,   -51,    22},
+ {     3,    92,  -150,   136,  -182,   -57,    97},
+ {  -131,   179,   -78,    80,    91,  -165,    90},
+ {    -2,   148,    15,   130,    65,   175,   117},
+ {  -138,   114,  -137,   132,     3,   -10,  -186},
+ {   140,    -4,   -37,   254,   -62,    92,  -109}
+};
+
+/** Means of ISF vectors in Q15 */
+static const int16_t isf_mean[LP_ORDER] = {
+   738,  1326,  2336,  3578,  4596,  5662,  6711,  7730,
+  8750,  9753, 10705, 11728, 12833, 13971, 15043,  4037
+};
+
+/** Initialization tables for the processed ISF vector in Q15 */
+static const int16_t isf_init[LP_ORDER] = {
+  1024,  2048,  3072,  4096,  5120,  6144,  7168, 8192,
+  9216, 10240, 11264, 12288, 13312, 14336, 15360, 3840
+};
+
+/** ISF/ISP interpolation coefficients for each subframe */
+static const float isfp_inter[4] = { 0.45, 0.8, 0.96, 1.0 };
+
+/** Coefficients for FIR interpolation of excitation vector
+ * at pitch lag resulting the adaptive codebook vector */
+static const float ac_inter[65] = {
+     9.400024e-01,
+     8.563843e-01,  6.322632e-01,  3.375854e-01,  5.908203e-02,
+    -1.310425e-01, -1.994019e-01, -1.585693e-01, -5.633545e-02,
+     4.760742e-02,  1.067505e-01,  1.036987e-01,  5.206299e-02,
+    -1.519775e-02, -6.372070e-02, -7.366943e-02, -4.650879e-02,
+    -9.765625e-04,  3.820801e-02,  5.316162e-02,  4.003906e-02,
+     9.338379e-03, -2.166748e-02, -3.778076e-02, -3.320312e-02,
+    -1.300049e-02,  1.068115e-02,  2.587891e-02,  2.630615e-02,
+     1.379395e-02, -3.662109e-03, -1.678467e-02, -1.983643e-02,
+    -1.275635e-02, -5.493164e-04,  1.007080e-02,  1.409912e-02,
+     1.068115e-02,  2.624512e-03, -5.371094e-03, -9.338379e-03,
+    -8.117676e-03, -3.173828e-03,  2.319336e-03,  5.615234e-03,
+     5.554199e-03,  2.868652e-03, -6.103516e-04, -2.990723e-03,
+    -3.356934e-03, -2.014160e-03, -1.220703e-04,  1.342773e-03,
+     1.708984e-03,  1.159668e-03,  2.441406e-04, -4.272461e-04,
+    -6.103516e-04, -4.272461e-04, -1.220703e-04,  6.103516e-05,
+     1.220703e-04,  6.103516e-05,  0.000000e+00,  0.000000e+00
+};
+
+/** [i][j] is the number of pulses present in track j at mode i */
+static const uint8_t pulses_nb_per_mode_tr[][4] = {
+    {1, 1, 0, 0}, {1, 1, 1, 1}, {2, 2, 2, 2},
+    {3, 3, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4},
+    {5, 5, 4, 4}, {6, 6, 6, 6}, {6, 6, 6, 6}
+};
+
+/** Tables for decoding quantized gains { pitch (Q14), fixed factor (Q11) } */
+static const int16_t qua_gain_6b[64][2] = {
+    {  1566,  1332},    {  1577,  3557},
+    {  3071,  6490},    {  4193, 10163},
+    {  4496,  2534},    {  5019,  4488},
+    {  5586, 15614},    {  5725,  1422},
+    {  6453,   580},    {  6724,  6831},
+    {  7657,  3527},    {  8072,  2099},
+    {  8232,  5319},    {  8827,  8775},
+    {  9740,  2868},    {  9856,  1465},
+    { 10087, 12488},    { 10241,  4453},
+    { 10859,  6618},    { 11321,  3587},
+    { 11417,  1800},    { 11643,  2428},
+    { 11718,   988},    { 12312,  5093},
+    { 12523,  8413},    { 12574, 26214},
+    { 12601,  3396},    { 13172,  1623},
+    { 13285,  2423},    { 13418,  6087},
+    { 13459, 12810},    { 13656,  3607},
+    { 14111,  4521},    { 14144,  1229},
+    { 14425,  1871},    { 14431,  7234},
+    { 14445,  2834},    { 14628, 10036},
+    { 14860, 17496},    { 15161,  3629},
+    { 15209,  5819},    { 15299,  2256},
+    { 15518,  4722},    { 15663,  1060},
+    { 15759,  7972},    { 15939, 11964},
+    { 16020,  2996},    { 16086,  1707},
+    { 16521,  4254},    { 16576,  6224},
+    { 16894,  2380},    { 16906,   681},
+    { 17213,  8406},    { 17610,  3418},
+    { 17895,  5269},    { 18168, 11748},
+    { 18230,  1575},    { 18607, 32767},
+    { 18728, 21684},    { 19137,  2543},
+    { 19422,  6577},    { 19446,  4097},
+    { 19450,  9056},    { 20371, 14885}
+};
+
+static const int16_t qua_gain_7b[128][2] = {
+    {   204,   441},    {   464,  1977},
+    {   869,  1077},    {  1072,  3062},
+    {  1281,  4759},    {  1647,  1539},
+    {  1845,  7020},    {  1853,   634},
+    {  1995,  2336},    {  2351, 15400},
+    {  2661,  1165},    {  2702,  3900},
+    {  2710, 10133},    {  3195,  1752},
+    {  3498,  2624},    {  3663,   849},
+    {  3984,  5697},    {  4214,  3399},
+    {  4415,  1304},    {  4695,  2056},
+    {  5376,  4558},    {  5386,   676},
+    {  5518, 23554},    {  5567,  7794},
+    {  5644,  3061},    {  5672,  1513},
+    {  5957,  2338},    {  6533,  1060},
+    {  6804,  5998},    {  6820,  1767},
+    {  6937,  3837},    {  7277,   414},
+    {  7305,  2665},    {  7466, 11304},
+    {  7942,   794},    {  8007,  1982},
+    {  8007,  1366},    {  8326,  3105},
+    {  8336,  4810},    {  8708,  7954},
+    {  8989,  2279},    {  9031,  1055},
+    {  9247,  3568},    {  9283,  1631},
+    {  9654,  6311},    {  9811,  2605},
+    { 10120,   683},    { 10143,  4179},
+    { 10245,  1946},    { 10335,  1218},
+    { 10468,  9960},    { 10651,  3000},
+    { 10951,  1530},    { 10969,  5290},
+    { 11203,  2305},    { 11325,  3562},
+    { 11771,  6754},    { 11839,  1849},
+    { 11941,  4495},    { 11954,  1298},
+    { 11975, 15223},    { 11977,   883},
+    { 11986,  2842},    { 12438,  2141},
+    { 12593,  3665},    { 12636,  8367},
+    { 12658,  1594},    { 12886,  2628},
+    { 12984,  4942},    { 13146,  1115},
+    { 13224,   524},    { 13341,  3163},
+    { 13399,  1923},    { 13549,  5961},
+    { 13606,  1401},    { 13655,  2399},
+    { 13782,  3909},    { 13868, 10923},
+    { 14226,  1723},    { 14232,  2939},
+    { 14278,  7528},    { 14439,  4598},
+    { 14451,   984},    { 14458,  2265},
+    { 14792,  1403},    { 14818,  3445},
+    { 14899,  5709},    { 15017, 15362},
+    { 15048,  1946},    { 15069,  2655},
+    { 15405,  9591},    { 15405,  4079},
+    { 15570,  7183},    { 15687,  2286},
+    { 15691,  1624},    { 15699,  3068},
+    { 15772,  5149},    { 15868,  1205},
+    { 15970,   696},    { 16249,  3584},
+    { 16338,  1917},    { 16424,  2560},
+    { 16483,  4438},    { 16529,  6410},
+    { 16620, 11966},    { 16839,  8780},
+    { 17030,  3050},    { 17033, 18325},
+    { 17092,  1568},    { 17123,  5197},
+    { 17351,  2113},    { 17374,   980},
+    { 17566, 26214},    { 17609,  3912},
+    { 17639, 32767},    { 18151,  7871},
+    { 18197,  2516},    { 18202,  5649},
+    { 18679,  3283},    { 18930,  1370},
+    { 19271, 13757},    { 19317,  4120},
+    { 19460,  1973},    { 19654, 10018},
+    { 19764,  6792},    { 19912,  5135},
+    { 20040,  2841},    { 21234, 19833}
+};
+
+/** 4-tap moving average prediction coefficients in reverse order */
+static const float energy_pred_fac[4] = { 0.2, 0.3, 0.4, 0.5 };
+
+/** impulse response filter tables converted to float from Q15
+ * used for anti-sparseness processing */
+static const float ir_filter_str[64] = {
+     6.159058e-01,  2.958069e-01,  9.979248e-02, -1.048889e-01,
+     8.740234e-02, -1.599121e-01,  4.849243e-02, -4.141235e-02,
+     1.831055e-02,  1.188049e-01, -4.568481e-02, -2.130127e-02,
+     3.671265e-02, -1.601868e-01,  3.659058e-02,  1.639099e-01,
+    -4.541016e-02, -2.151489e-02, -8.810425e-02,  6.030273e-02,
+     2.740479e-02,  2.200317e-02, -1.182861e-01,  1.289978e-01,
+    -1.560059e-01,  1.953125e-01, -3.149414e-02, -1.441956e-01,
+     1.249084e-01, -1.328125e-01,  9.780884e-02,  6.500244e-02,
+    -6.091309e-02, -5.599976e-02,  8.081055e-02, -5.450439e-02,
+    -1.239014e-02,  1.748657e-02,  7.580566e-02, -1.101074e-01,
+     9.579468e-02, -4.159546e-02, -7.830811e-02,  1.162109e-01,
+    -1.950073e-02, -6.259155e-02, -1.651001e-02,  7.250977e-02,
+     1.199951e-01, -1.911011e-01,  4.370117e-02, -1.098938e-01,
+     1.492004e-01,  1.129150e-02,  1.730347e-02, -3.549194e-02,
+    -8.709717e-02,  5.841064e-02,  1.190186e-03, -7.379150e-02,
+     1.054077e-01,  9.078979e-02, -1.227112e-01,  1.047058e-01
+};
+
+static const float ir_filter_mid[64] = {
+     7.354126e-01,  3.192139e-01, -1.606140e-01, -2.328491e-02,
+     6.250000e-02, -2.828979e-02,  5.349731e-02, -1.014099e-01,
+     6.750488e-02,  1.989746e-02, -6.549072e-02,  7.589722e-02,
+    -1.080017e-01,  1.253967e-01, -6.430054e-02, -1.141357e-02,
+    -1.910400e-02,  1.303101e-01, -1.673889e-01,  6.820679e-02,
+     5.670166e-02, -8.450317e-02,  2.270508e-02,  3.479004e-02,
+    -2.328491e-02, -4.928589e-02,  1.239014e-01, -1.395874e-01,
+     9.100342e-02, -3.549194e-02,  2.230835e-02, -3.350830e-02,
+     2.450562e-02,  5.096436e-03, -2.178955e-02,  1.849365e-02,
+    -1.708984e-02,  1.950073e-02,  1.312256e-03, -5.389404e-02,
+     9.851074e-02, -8.489990e-02,  2.029419e-02,  2.328491e-02,
+     7.110596e-03, -6.109619e-02,  3.939819e-02,  5.709839e-02,
+    -1.058960e-01,  3.149414e-02,  8.270264e-02, -1.232910e-01,
+     1.105957e-01, -1.286011e-01,  1.614990e-01, -1.303101e-01,
+     4.769897e-02,  3.295898e-03, -1.770020e-02,  5.010986e-02,
+    -7.501221e-02,  2.920532e-02,  1.660156e-02,  7.751465e-02
+};
+
+static const float *ir_filters_lookup[2] = {
+    ir_filter_str, ir_filter_mid
+};
+
+/** High-pass filters coefficients for 31 Hz and 400 Hz cutoff */
+static const float hpf_zeros[2]     = { -2.0, 1.0 };
+static const float hpf_31_poles[2]  = { -1.978881836, 0.979125977 };
+static const float hpf_31_gain      = 0.989501953;
+
+static const float hpf_400_poles[2] = { -1.787109375, 0.864257812 };
+static const float hpf_400_gain     = 0.893554687;
+
+/** Interpolation coefficients for 5/4 signal upsampling
+ * Table from the reference source was reordered for efficiency */
+static const float upsample_fir[4][24] = {
+    { -6.103516e-05,  7.324219e-04, -2.014160e-03,  4.150391e-03,
+      -7.263184e-03,  1.165771e-02, -1.776123e-02,  2.624512e-02,
+      -3.869629e-02,  5.877686e-02, -9.863281e-02,  2.314453e-01,
+       9.348755e-01, -1.523438e-01,  7.861328e-02, -4.937744e-02,
+       3.308105e-02, -2.252197e-02,  1.507568e-02, -9.765625e-03,
+       5.859375e-03, -3.173828e-03,  1.403809e-03, -3.662109e-04  },
+    { -2.441406e-04,  1.464844e-03, -3.784180e-03,  7.568359e-03,
+      -1.300049e-02,  2.062988e-02, -3.112793e-02,  4.589844e-02,
+      -6.781006e-02,  1.042480e-01, -1.815186e-01,  5.016479e-01,
+       7.548828e-01, -2.094727e-01,  1.148071e-01, -7.348633e-02,
+       4.956055e-02, -3.369141e-02,  2.246094e-02, -1.434326e-02,
+       8.483887e-03, -4.455566e-03,  1.831055e-03, -4.272461e-04  },
+    { -4.272461e-04,  1.831055e-03, -4.455566e-03,  8.483887e-03,
+      -1.434326e-02,  2.246094e-02, -3.369141e-02,  4.956055e-02,
+      -7.348633e-02,  1.148071e-01, -2.094727e-01,  7.548828e-01,
+       5.016479e-01, -1.815186e-01,  1.042480e-01, -6.781006e-02,
+       4.589844e-02, -3.112793e-02,  2.062988e-02, -1.300049e-02,
+       7.568359e-03, -3.784180e-03,  1.464844e-03, -2.441406e-04  },
+    { -3.662109e-04,  1.403809e-03, -3.173828e-03,  5.859375e-03,
+      -9.765625e-03,  1.507568e-02, -2.252197e-02,  3.308105e-02,
+      -4.937744e-02,  7.861328e-02, -1.523438e-01,  9.348755e-01,
+       2.314453e-01, -9.863281e-02,  5.877686e-02, -3.869629e-02,
+       2.624512e-02, -1.776123e-02,  1.165771e-02, -7.263184e-03,
+       4.150391e-03, -2.014160e-03,  7.324219e-04, -6.103516e-05  }
+};
+
+/** High band quantized gains for 23k85 in Q14 */
+static const uint16_t qua_hb_gain[16] = {
+   3624, 4673, 5597, 6479, 7425, 8378, 9324, 10264,
+   11210, 12206, 13391, 14844, 16770, 19655, 24289, 32728
+};
+
+/** High-band post-processing FIR filters coefficients from Q15 */
+static const float bpf_6_7_coef[31] = { // band pass, 6kHz and 7kHz cutoffs
+    -2.441406e-04,  3.585815e-04,  2.441406e-04,
+    -2.059937e-04, -2.815248e-03,  8.560180e-03,
+    -1.084137e-02,  0.000000e+00,  2.897645e-02,
+    -6.774902e-02,  9.421540e-02, -8.380128e-02,
+     2.706910e-02,  5.924987e-02, -1.373367e-01,
+     1.687469e-01,
+    -1.373367e-01,  5.924987e-02,  2.706910e-02,
+    -8.380128e-02,  9.421540e-02, -6.774902e-02,
+     2.897645e-02,  0.000000e+00, -1.084137e-02,
+     8.560180e-03, -2.815248e-03, -2.059937e-04,
+     2.441406e-04,  3.585815e-04, -2.441406e-04
+};
+
+static const float lpf_7_coef[31] = { // low pass, 7kHz cutoff
+    -6.408691e-04,  1.434326e-03, -2.716064e-03,
+     4.455566e-03, -6.195068e-03,  6.988525e-03,
+    -5.401611e-03,  0.000000e+00,  1.022339e-02,
+    -2.560425e-02,  4.531860e-02, -6.747437e-02,
+     8.944702e-02, -1.080933e-01,  1.206360e-01,
+     8.753052e-01,
+     1.206360e-01, -1.080933e-01,  8.944702e-02,
+    -6.747437e-02,  4.531860e-02, -2.560425e-02,
+     1.022339e-02,  0.000000e+00, -5.401611e-03,
+     6.988525e-03, -6.195068e-03,  4.455566e-03,
+    -2.716064e-03,  1.434326e-03, -6.408691e-04
+};
+
+/** Core frame sizes in each mode */
+static const uint16_t cf_sizes_wb[] = {
+    132, 177, 253, 285, 317, 365, 397, 461, 477,
+    40 /// SID/comfort noise frame
+};
+
+#endif
diff --git a/libavcodec/amrwbdec.c b/libavcodec/amrwbdec.c
new file mode 100644
index 0000000..d4bb776
--- /dev/null
+++ b/libavcodec/amrwbdec.c
@@ -0,0 +1,1237 @@
+/*
+ * AMR wideband decoder
+ * Copyright (c) 2010 Marcelo Galvao Povoa
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A particular PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * AMR wideband decoder
+ */
+
+#include "libavutil/lfg.h"
+
+#include "avcodec.h"
+#include "get_bits.h"
+#include "lsp.h"
+#include "celp_math.h"
+#include "celp_filters.h"
+#include "acelp_filters.h"
+#include "acelp_vectors.h"
+#include "acelp_pitch_delay.h"
+
+#define AMR_USE_16BIT_TABLES
+#include "amr.h"
+
+#include "amrwbdata.h"
+
+typedef struct {
+    AMRWBFrame                             frame; ///< AMRWB parameters decoded from bitstream
+    enum Mode                        fr_cur_mode; ///< mode index of current frame
+    uint8_t                           fr_quality; ///< frame quality index (FQI)
+    float                      isf_cur[LP_ORDER]; ///< working ISF vector from current frame
+    float                   isf_q_past[LP_ORDER]; ///< quantized ISF vector of the previous frame
+    float               isf_past_final[LP_ORDER]; ///< final processed ISF vector of the previous frame
+    double                      isp[4][LP_ORDER]; ///< ISP vectors from current frame
+    double               isp_sub4_past[LP_ORDER]; ///< ISP vector for the 4th subframe of the previous frame
+
+    float                   lp_coef[4][LP_ORDER]; ///< Linear Prediction Coefficients from ISP vector
+
+    uint8_t                       base_pitch_lag; ///< integer part of pitch lag for the next relative subframe
+    uint8_t                        pitch_lag_int; ///< integer part of pitch lag of the previous subframe
+
+    float excitation_buf[AMRWB_P_DELAY_MAX + LP_ORDER + 2 + AMRWB_SFR_SIZE]; ///< current excitation and all necessary excitation history
+    float                            *excitation; ///< points to current excitation in excitation_buf[]
+
+    float           pitch_vector[AMRWB_SFR_SIZE]; ///< adaptive codebook (pitch) vector for current subframe
+    float           fixed_vector[AMRWB_SFR_SIZE]; ///< algebraic codebook (fixed) vector for current subframe
+
+    float                    prediction_error[4]; ///< quantified prediction errors {20log10(^gamma_gc)} for previous four subframes
+    float                          pitch_gain[6]; ///< quantified pitch gains for the current and previous five subframes
+    float                          fixed_gain[2]; ///< quantified fixed gains for the current and previous subframes
+
+    float                              tilt_coef; ///< {beta_1} related to the voicing of the previous subframe
+
+    float                 prev_sparse_fixed_gain; ///< previous fixed gain; used by anti-sparseness to determine "onset"
+    uint8_t                    prev_ir_filter_nr; ///< previous impulse response filter "impNr": 0 - strong, 1 - medium, 2 - none
+    float                           prev_tr_gain; ///< previous initial gain used by noise enhancer for threshold
+
+    float samples_az[LP_ORDER + AMRWB_SFR_SIZE];         ///< low-band samples and memory from synthesis at 12.8kHz
+    float samples_up[UPS_MEM_SIZE + AMRWB_SFR_SIZE];     ///< low-band samples and memory processed for upsampling
+    float samples_hb[LP_ORDER_16k + AMRWB_SFR_SIZE_16k]; ///< high-band samples and memory from synthesis at 16kHz
+
+    float          hpf_31_mem[2], hpf_400_mem[2]; ///< previous values in the high pass filters
+    float                           demph_mem[1]; ///< previous value in the de-emphasis filter
+    float               bpf_6_7_mem[HB_FIR_SIZE]; ///< previous values in the high-band band pass filter
+    float                 lpf_7_mem[HB_FIR_SIZE]; ///< previous values in the high-band low pass filter
+
+    AVLFG                                   prng; ///< random number generator for white noise excitation
+    uint8_t                          first_frame; ///< flag active during decoding of the first frame
+} AMRWBContext;
+
+static av_cold int amrwb_decode_init(AVCodecContext *avctx)
+{
+    AMRWBContext *ctx = avctx->priv_data;
+    int i;
+
+    avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
+
+    av_lfg_init(&ctx->prng, 1);
+
+    ctx->excitation  = &ctx->excitation_buf[AMRWB_P_DELAY_MAX + LP_ORDER + 1];
+    ctx->first_frame = 1;
+
+    for (i = 0; i < LP_ORDER; i++)
+        ctx->isf_past_final[i] = isf_init[i] * (1.0f / (1 << 15));
+
+    for (i = 0; i < 4; i++)
+        ctx->prediction_error[i] = MIN_ENERGY;
+
+    return 0;
+}
+
+/**
+ * Decode the frame header in the "MIME/storage" format. This format
+ * is simpler and does not carry the auxiliary information of the frame
+ *
+ * @param[in] ctx                  The Context
+ * @param[in] buf                  Pointer to the input buffer
+ *
+ * @return The decoded header length in bytes
+ */
+static int decode_mime_header(AMRWBContext *ctx, const uint8_t *buf)
+{
+    GetBitContext gb;
+    init_get_bits(&gb, buf, 8);
+
+    /* Decode frame header (1st octet) */
+    skip_bits(&gb, 1);  // padding bit
+    ctx->fr_cur_mode  = get_bits(&gb, 4);
+    ctx->fr_quality   = get_bits1(&gb);
+    skip_bits(&gb, 2);  // padding bits
+
+    return 1;
+}
+
+/**
+ * Decodes quantized ISF vectors using 36-bit indexes (6K60 mode only)
+ *
+ * @param[in]  ind                 Array of 5 indexes
+ * @param[out] isf_q               Buffer for isf_q[LP_ORDER]
+ *
+ */
+static void decode_isf_indices_36b(uint16_t *ind, float *isf_q)
+{
+    int i;
+
+    for (i = 0; i < 9; i++)
+        isf_q[i]      = dico1_isf[ind[0]][i]      * (1.0f / (1 << 15));
+
+    for (i = 0; i < 7; i++)
+        isf_q[i + 9]  = dico2_isf[ind[1]][i]      * (1.0f / (1 << 15));
+
+    for (i = 0; i < 5; i++)
+        isf_q[i]     += dico21_isf_36b[ind[2]][i] * (1.0f / (1 << 15));
+
+    for (i = 0; i < 4; i++)
+        isf_q[i + 5] += dico22_isf_36b[ind[3]][i] * (1.0f / (1 << 15));
+
+    for (i = 0; i < 7; i++)
+        isf_q[i + 9] += dico23_isf_36b[ind[4]][i] * (1.0f / (1 << 15));
+}
+
+/**
+ * Decodes quantized ISF vectors using 46-bit indexes (except 6K60 mode)
+ *
+ * @param[in]  ind                 Array of 7 indexes
+ * @param[out] isf_q               Buffer for isf_q[LP_ORDER]
+ *
+ */
+static void decode_isf_indices_46b(uint16_t *ind, float *isf_q)
+{
+    int i;
+
+    for (i = 0; i < 9; i++)
+        isf_q[i]       = dico1_isf[ind[0]][i]  * (1.0f / (1 << 15));
+
+    for (i = 0; i < 7; i++)
+        isf_q[i + 9]   = dico2_isf[ind[1]][i]  * (1.0f / (1 << 15));
+
+    for (i = 0; i < 3; i++)
+        isf_q[i]      += dico21_isf[ind[2]][i] * (1.0f / (1 << 15));
+
+    for (i = 0; i < 3; i++)
+        isf_q[i + 3]  += dico22_isf[ind[3]][i] * (1.0f / (1 << 15));
+
+    for (i = 0; i < 3; i++)
+        isf_q[i + 6]  += dico23_isf[ind[4]][i] * (1.0f / (1 << 15));
+
+    for (i = 0; i < 3; i++)
+        isf_q[i + 9]  += dico24_isf[ind[5]][i] * (1.0f / (1 << 15));
+
+    for (i = 0; i < 4; i++)
+        isf_q[i + 12] += dico25_isf[ind[6]][i] * (1.0f / (1 << 15));
+}
+
+/**
+ * Apply mean and past ISF values using the prediction factor
+ * Updates past ISF vector
+ *
+ * @param[in,out] isf_q            Current quantized ISF
+ * @param[in,out] isf_past         Past quantized ISF
+ *
+ */
+static void isf_add_mean_and_past(float *isf_q, float *isf_past)
+{
+    int i;
+    float tmp;
+
+    for (i = 0; i < LP_ORDER; i++) {
+        tmp = isf_q[i];
+        isf_q[i] += isf_mean[i] * (1.0f / (1 << 15));
+        isf_q[i] += PRED_FACTOR * isf_past[i];
+        isf_past[i] = tmp;
+    }
+}
+
+/**
+ * Interpolate the fourth ISP vector from current and past frames
+ * to obtain a ISP vector for each subframe
+ *
+ * @param[in,out] isp_q            ISPs for each subframe
+ * @param[in]     isp4_past        Past ISP for subframe 4
+ */
+static void interpolate_isp(double isp_q[4][LP_ORDER], const double *isp4_past)
+{
+    int i, k;
+
+    for (k = 0; k < 3; k++) {
+        float c = isfp_inter[k];
+        for (i = 0; i < LP_ORDER; i++)
+            isp_q[k][i] = (1.0 - c) * isp4_past[i] + c * isp_q[3][i];
+    }
+}
+
+/**
+ * Decode an adaptive codebook index into pitch lag (except 6k60, 8k85 modes)
+ * Calculate integer lag and fractional lag always using 1/4 resolution
+ * In 1st and 3rd subframes the index is relative to last subframe integer lag
+ *
+ * @param[out]    lag_int          Decoded integer pitch lag
+ * @param[out]    lag_frac         Decoded fractional pitch lag
+ * @param[in]     pitch_index      Adaptive codebook pitch index
+ * @param[in,out] base_lag_int     Base integer lag used in relative subframes
+ * @param[in]     subframe         Current subframe index (0 to 3)
+ */
+static void decode_pitch_lag_high(int *lag_int, int *lag_frac, int pitch_index,
+                                  uint8_t *base_lag_int, int subframe)
+{
+    if (subframe == 0 || subframe == 2) {
+        if (pitch_index < 376) {
+            *lag_int  = (pitch_index + 137) >> 2;
+            *lag_frac = pitch_index - (*lag_int << 2) + 136;
+        } else if (pitch_index < 440) {
+            *lag_int  = (pitch_index + 257 - 376) >> 1;
+            *lag_frac = (pitch_index - (*lag_int << 1) + 256 - 376) << 1;
+            /* the actual resolution is 1/2 but expressed as 1/4 */
+        } else {
+            *lag_int  = pitch_index - 280;
+            *lag_frac = 0;
+        }
+        /* minimum lag for next subframe */
+        *base_lag_int = av_clip(*lag_int - 8 - (*lag_frac < 0),
+                                AMRWB_P_DELAY_MIN, AMRWB_P_DELAY_MAX - 15);
+        // XXX: the spec states clearly that *base_lag_int should be
+        // the nearest integer to *lag_int (minus 8), but the ref code
+        // actually always uses its floor, I'm following the latter
+    } else {
+        *lag_int  = (pitch_index + 1) >> 2;
+        *lag_frac = pitch_index - (*lag_int << 2);
+        *lag_int += *base_lag_int;
+    }
+}
+
+/**
+ * Decode a adaptive codebook index into pitch lag for 8k85 and 6k60 modes
+ * Description is analogous to decode_pitch_lag_high, but in 6k60 relative
+ * index is used for all subframes except the first
+ */
+static void decode_pitch_lag_low(int *lag_int, int *lag_frac, int pitch_index,
+                                 uint8_t *base_lag_int, int subframe, enum Mode mode)
+{
+    if (subframe == 0 || (subframe == 2 && mode != MODE_6k60)) {
+        if (pitch_index < 116) {
+            *lag_int  = (pitch_index + 69) >> 1;
+            *lag_frac = (pitch_index - (*lag_int << 1) + 68) << 1;
+        } else {
+            *lag_int  = pitch_index - 24;
+            *lag_frac = 0;
+        }
+        // XXX: same problem as before
+        *base_lag_int = av_clip(*lag_int - 8 - (*lag_frac < 0),
+                                AMRWB_P_DELAY_MIN, AMRWB_P_DELAY_MAX - 15);
+    } else {
+        *lag_int  = (pitch_index + 1) >> 1;
+        *lag_frac = (pitch_index - (*lag_int << 1)) << 1;
+        *lag_int += *base_lag_int;
+    }
+}
+
+/**
+ * Find the pitch vector by interpolating the past excitation at the
+ * pitch delay, which is obtained in this function
+ *
+ * @param[in,out] ctx              The context
+ * @param[in]     amr_subframe     Current subframe data
+ * @param[in]     subframe         Current subframe index (0 to 3)
+ */
+static void decode_pitch_vector(AMRWBContext *ctx,
+                                const AMRWBSubFrame *amr_subframe,
+                                const int subframe)
+{
+    int pitch_lag_int, pitch_lag_frac;
+    int i;
+    float *exc     = ctx->excitation;
+    enum Mode mode = ctx->fr_cur_mode;
+
+    if (mode <= MODE_8k85) {
+        decode_pitch_lag_low(&pitch_lag_int, &pitch_lag_frac, amr_subframe->adap,
+                              &ctx->base_pitch_lag, subframe, mode);
+    } else
+        decode_pitch_lag_high(&pitch_lag_int, &pitch_lag_frac, amr_subframe->adap,
+                              &ctx->base_pitch_lag, subframe);
+
+    ctx->pitch_lag_int = pitch_lag_int;
+    pitch_lag_int += pitch_lag_frac > 0;
+
+    /* Calculate the pitch vector by interpolating the past excitation at the
+       pitch lag using a hamming windowed sinc function */
+    ff_acelp_interpolatef(exc, exc + 1 - pitch_lag_int,
+                          ac_inter, 4,
+                          pitch_lag_frac + (pitch_lag_frac > 0 ? 0 : 4),
+                          LP_ORDER, AMRWB_SFR_SIZE + 1);
+
+    /* Check which pitch signal path should be used
+     * 6k60 and 8k85 modes have the ltp flag set to 0 */
+    if (amr_subframe->ltp) {
+        memcpy(ctx->pitch_vector, exc, AMRWB_SFR_SIZE * sizeof(float));
+    } else {
+        for (i = 0; i < AMRWB_SFR_SIZE; i++)
+            ctx->pitch_vector[i] = 0.18 * exc[i - 1] + 0.64 * exc[i] +
+                                   0.18 * exc[i + 1];
+        memcpy(exc, ctx->pitch_vector, AMRWB_SFR_SIZE * sizeof(float));
+    }
+}
+
+/** Get x bits in the index interval [lsb,lsb+len-1] inclusive */
+#define BIT_STR(x,lsb,len) (((x) >> (lsb)) & ((1 << (len)) - 1))
+
+/** Get the bit at specified position */
+#define BIT_POS(x, p) (((x) >> (p)) & 1)
+
+/**
+ * The next six functions decode_[i]p_track decode exactly i pulses
+ * positions and amplitudes (-1 or 1) in a subframe track using
+ * an encoded pulse indexing (TS 26.190 section 5.8.2)
+ *
+ * The results are given in out[], in which a negative number means
+ * amplitude -1 and vice versa (i.e., ampl(x) = x / abs(x) )
+ *
+ * @param[out] out                 Output buffer (writes i elements)
+ * @param[in]  code                Pulse index (no. of bits varies, see below)
+ * @param[in]  m                   (log2) Number of potential positions
+ * @param[in]  off                 Offset for decoded positions
+ */
+static inline void decode_1p_track(int *out, int code, int m, int off)
+{
+    int pos = BIT_STR(code, 0, m) + off; ///code: m+1 bits
+
+    out[0] = BIT_POS(code, m) ? -pos : pos;
+}
+
+static inline void decode_2p_track(int *out, int code, int m, int off) ///code: 2m+1 bits
+{
+    int pos0 = BIT_STR(code, m, m) + off;
+    int pos1 = BIT_STR(code, 0, m) + off;
+
+    out[0] = BIT_POS(code, 2*m) ? -pos0 : pos0;
+    out[1] = BIT_POS(code, 2*m) ? -pos1 : pos1;
+    out[1] = pos0 > pos1 ? -out[1] : out[1];
+}
+
+static void decode_3p_track(int *out, int code, int m, int off) ///code: 3m+1 bits
+{
+    int half_2p = BIT_POS(code, 2*m - 1) << (m - 1);
+
+    decode_2p_track(out, BIT_STR(code, 0, 2*m - 1),
+                    m - 1, off + half_2p);
+    decode_1p_track(out + 2, BIT_STR(code, 2*m, m + 1), m, off);
+}
+
+static void decode_4p_track(int *out, int code, int m, int off) ///code: 4m bits
+{
+    int half_4p, subhalf_2p;
+    int b_offset = 1 << (m - 1);
+
+    switch (BIT_STR(code, 4*m - 2, 2)) { /* case ID (2 bits) */
+    case 0: /* 0 pulses in A, 4 pulses in B or vice versa */
+        half_4p = BIT_POS(code, 4*m - 3) << (m - 1); // which has 4 pulses
+        subhalf_2p = BIT_POS(code, 2*m - 3) << (m - 2);
+
+        decode_2p_track(out, BIT_STR(code, 0, 2*m - 3),
+                        m - 2, off + half_4p + subhalf_2p);
+        decode_2p_track(out + 2, BIT_STR(code, 2*m - 2, 2*m - 1),
+                        m - 1, off + half_4p);
+        break;
+    case 1: /* 1 pulse in A, 3 pulses in B */
+        decode_1p_track(out, BIT_STR(code,  3*m - 2, m),
+                        m - 1, off);
+        decode_3p_track(out + 1, BIT_STR(code, 0, 3*m - 2),
+                        m - 1, off + b_offset);
+        break;
+    case 2: /* 2 pulses in each half */
+        decode_2p_track(out, BIT_STR(code, 2*m - 1, 2*m - 1),
+                        m - 1, off);
+        decode_2p_track(out + 2, BIT_STR(code, 0, 2*m - 1),
+                        m - 1, off + b_offset);
+        break;
+    case 3: /* 3 pulses in A, 1 pulse in B */
+        decode_3p_track(out, BIT_STR(code, m, 3*m - 2),
+                        m - 1, off);
+        decode_1p_track(out + 3, BIT_STR(code, 0, m),
+                        m - 1, off + b_offset);
+        break;
+    }
+}
+
+static void decode_5p_track(int *out, int code, int m, int off) ///code: 5m bits
+{
+    int half_3p = BIT_POS(code, 5*m - 1) << (m - 1);
+
+    decode_3p_track(out, BIT_STR(code, 2*m + 1, 3*m - 2),
+                    m - 1, off + half_3p);
+
+    decode_2p_track(out + 3, BIT_STR(code, 0, 2*m + 1), m, off);
+}
+
+static void decode_6p_track(int *out, int code, int m, int off) ///code: 6m-2 bits
+{
+    int b_offset = 1 << (m - 1);
+    /* which half has more pulses in cases 0 to 2 */
+    int half_more  = BIT_POS(code, 6*m - 5) << (m - 1);
+    int half_other = b_offset - half_more;
+
+    switch (BIT_STR(code, 6*m - 4, 2)) { /* case ID (2 bits) */
+    case 0: /* 0 pulses in A, 6 pulses in B or vice versa */
+        decode_1p_track(out, BIT_STR(code, 0, m),
+                        m - 1, off + half_more);
+        decode_5p_track(out + 1, BIT_STR(code, m, 5*m - 5),
+                        m - 1, off + half_more);
+        break;
+    case 1: /* 1 pulse in A, 5 pulses in B or vice versa */
+        decode_1p_track(out, BIT_STR(code, 0, m),
+                        m - 1, off + half_other);
+        decode_5p_track(out + 1, BIT_STR(code, m, 5*m - 5),
+                        m - 1, off + half_more);
+        break;
+    case 2: /* 2 pulses in A, 4 pulses in B or vice versa */
+        decode_2p_track(out, BIT_STR(code, 0, 2*m - 1),
+                        m - 1, off + half_other);
+        decode_4p_track(out + 2, BIT_STR(code, 2*m - 1, 4*m - 4),
+                        m - 1, off + half_more);
+        break;
+    case 3: /* 3 pulses in A, 3 pulses in B */
+        decode_3p_track(out, BIT_STR(code, 3*m - 2, 3*m - 2),
+                        m - 1, off);
+        decode_3p_track(out + 3, BIT_STR(code, 0, 3*m - 2),
+                        m - 1, off + b_offset);
+        break;
+    }
+}
+
+/**
+ * Decode the algebraic codebook index to pulse positions and signs,
+ * then construct the algebraic codebook vector
+ *
+ * @param[out] fixed_vector        Buffer for the fixed codebook excitation
+ * @param[in]  pulse_hi            MSBs part of the pulse index array (higher modes only)
+ * @param[in]  pulse_lo            LSBs part of the pulse index array
+ * @param[in]  mode                Mode of the current frame
+ */
+static void decode_fixed_vector(float *fixed_vector, const uint16_t *pulse_hi,
+                                const uint16_t *pulse_lo, const enum Mode mode)
+{
+    /* sig_pos stores for each track the decoded pulse position indexes
+     * (1-based) multiplied by its corresponding amplitude (+1 or -1) */
+    int sig_pos[4][6];
+    int spacing = (mode == MODE_6k60) ? 2 : 4;
+    int i, j;
+
+    switch (mode) {
+    case MODE_6k60:
+        for (i = 0; i < 2; i++)
+            decode_1p_track(sig_pos[i], pulse_lo[i], 5, 1);
+        break;
+    case MODE_8k85:
+        for (i = 0; i < 4; i++)
+            decode_1p_track(sig_pos[i], pulse_lo[i], 4, 1);
+        break;
+    case MODE_12k65:
+        for (i = 0; i < 4; i++)
+            decode_2p_track(sig_pos[i], pulse_lo[i], 4, 1);
+        break;
+    case MODE_14k25:
+        for (i = 0; i < 2; i++)
+            decode_3p_track(sig_pos[i], pulse_lo[i], 4, 1);
+        for (i = 2; i < 4; i++)
+            decode_2p_track(sig_pos[i], pulse_lo[i], 4, 1);
+        break;
+    case MODE_15k85:
+        for (i = 0; i < 4; i++)
+            decode_3p_track(sig_pos[i], pulse_lo[i], 4, 1);
+        break;
+    case MODE_18k25:
+        for (i = 0; i < 4; i++)
+            decode_4p_track(sig_pos[i], (int) pulse_lo[i] +
+                           ((int) pulse_hi[i] << 14), 4, 1);
+        break;
+    case MODE_19k85:
+        for (i = 0; i < 2; i++)
+            decode_5p_track(sig_pos[i], (int) pulse_lo[i] +
+                           ((int) pulse_hi[i] << 10), 4, 1);
+        for (i = 2; i < 4; i++)
+            decode_4p_track(sig_pos[i], (int) pulse_lo[i] +
+                           ((int) pulse_hi[i] << 14), 4, 1);
+        break;
+    case MODE_23k05:
+    case MODE_23k85:
+        for (i = 0; i < 4; i++)
+            decode_6p_track(sig_pos[i], (int) pulse_lo[i] +
+                           ((int) pulse_hi[i] << 11), 4, 1);
+        break;
+    }
+
+    memset(fixed_vector, 0, sizeof(float) * AMRWB_SFR_SIZE);
+
+    for (i = 0; i < 4; i++)
+        for (j = 0; j < pulses_nb_per_mode_tr[mode][i]; j++) {
+            int pos = (FFABS(sig_pos[i][j]) - 1) * spacing + i;
+
+            fixed_vector[pos] += sig_pos[i][j] < 0 ? -1.0 : 1.0;
+        }
+}
+
+/**
+ * Decode pitch gain and fixed gain correction factor
+ *
+ * @param[in]  vq_gain             Vector-quantized index for gains
+ * @param[in]  mode                Mode of the current frame
+ * @param[out] fixed_gain_factor   Decoded fixed gain correction factor
+ * @param[out] pitch_gain          Decoded pitch gain
+ */
+static void decode_gains(const uint8_t vq_gain, const enum Mode mode,
+                         float *fixed_gain_factor, float *pitch_gain)
+{
+    const int16_t *gains = (mode <= MODE_8k85 ? qua_gain_6b[vq_gain] :
+                                                qua_gain_7b[vq_gain]);
+
+    *pitch_gain        = gains[0] * (1.0f / (1 << 14));
+    *fixed_gain_factor = gains[1] * (1.0f / (1 << 11));
+}
+
+/**
+ * Apply pitch sharpening filters to the fixed codebook vector
+ *
+ * @param[in]     ctx              The context
+ * @param[in,out] fixed_vector     Fixed codebook excitation
+ */
+// XXX: Spec states this procedure should be applied when the pitch
+// lag is less than 64, but this checking seems absent in reference and AMR-NB
+static void pitch_sharpening(AMRWBContext *ctx, float *fixed_vector)
+{
+    int i;
+
+    /* Tilt part */
+    for (i = AMRWB_SFR_SIZE - 1; i != 0; i--)
+        fixed_vector[i] -= fixed_vector[i - 1] * ctx->tilt_coef;
+
+    /* Periodicity enhancement part */
+    for (i = ctx->pitch_lag_int; i < AMRWB_SFR_SIZE; i++)
+        fixed_vector[i] += fixed_vector[i - ctx->pitch_lag_int] * 0.85;
+}
+
+/**
+ * Calculate the voicing factor (-1.0 = unvoiced to 1.0 = voiced)
+ *
+ * @param[in] p_vector, f_vector   Pitch and fixed excitation vectors
+ * @param[in] p_gain, f_gain       Pitch and fixed gains
+ */
+// XXX: There is something wrong with the precision here! The magnitudes
+// of the energies are not correct. Please check the reference code carefully
+static float voice_factor(float *p_vector, float p_gain,
+                          float *f_vector, float f_gain)
+{
+    double p_ener = (double) ff_dot_productf(p_vector, p_vector,
+                                             AMRWB_SFR_SIZE) * p_gain * p_gain;
+    double f_ener = (double) ff_dot_productf(f_vector, f_vector,
+                                             AMRWB_SFR_SIZE) * f_gain * f_gain;
+
+    return (p_ener - f_ener) / (p_ener + f_ener);
+}
+
+/**
+ * Reduce fixed vector sparseness by smoothing with one of three IR filters
+ * Also known as "adaptive phase dispersion"
+ *
+ * @param[in]     ctx              The context
+ * @param[in,out] fixed_vector     Unfiltered fixed vector
+ * @param[out]    buf              Space for modified vector if necessary
+ *
+ * @return The potentially overwritten filtered fixed vector address
+ */
+static float *anti_sparseness(AMRWBContext *ctx,
+                              float *fixed_vector, float *buf)
+{
+    int ir_filter_nr;
+
+    if (ctx->fr_cur_mode > MODE_8k85) // no filtering in higher modes
+        return fixed_vector;
+
+    if (ctx->pitch_gain[0] < 0.6) {
+        ir_filter_nr = 0;      // strong filtering
+    } else if (ctx->pitch_gain[0] < 0.9) {
+        ir_filter_nr = 1;      // medium filtering
+    } else
+        ir_filter_nr = 2;      // no filtering
+
+    /* detect 'onset' */
+    if (ctx->fixed_gain[0] > 3.0 * ctx->fixed_gain[1]) {
+        if (ir_filter_nr < 2)
+            ir_filter_nr++;
+    } else {
+        int i, count = 0;
+
+        for (i = 0; i < 6; i++)
+            if (ctx->pitch_gain[i] < 0.6)
+                count++;
+
+        if (count > 2)
+            ir_filter_nr = 0;
+
+        if (ir_filter_nr > ctx->prev_ir_filter_nr + 1)
+            ir_filter_nr--;
+    }
+
+    /* update ir filter strength history */
+    ctx->prev_ir_filter_nr = ir_filter_nr;
+
+    ir_filter_nr += (ctx->fr_cur_mode == MODE_8k85);
+
+    if (ir_filter_nr < 2) {
+        int i;
+        const float *coef = ir_filters_lookup[ir_filter_nr];
+
+        /* Circular convolution code in the reference
+         * decoder was modified to avoid using one
+         * extra array. The filtered vector is given by:
+         *
+         * c2(n) = sum(i,0,len-1){ c(i) * coef( (n - i + len) % len ) }
+         */
+
+        memset(buf, 0, sizeof(float) * AMRWB_SFR_SIZE);
+        for (i = 0; i < AMRWB_SFR_SIZE; i++)
+            if (fixed_vector[i])
+                ff_celp_circ_addf(buf, buf, coef, i, fixed_vector[i],
+                                  AMRWB_SFR_SIZE);
+        fixed_vector = buf;
+    }
+
+    return fixed_vector;
+}
+
+/**
+ * Calculate a stability factor {teta} based on distance between
+ * current and past isf. A value of 1 shows maximum signal stability
+ */
+static float stability_factor(const float *isf, const float *isf_past)
+{
+    int i;
+    float acc = 0.0;
+
+    for (i = 0; i < LP_ORDER - 1; i++)
+        acc += (isf[i] - isf_past[i]) * (isf[i] - isf_past[i]);
+
+    // XXX: This part is not so clear from the reference code
+    // the result is more accurate changing the "/ 256" to "* 512"
+    return FFMAX(0.0, 1.25 - acc * 0.8 * 512);
+}
+
+/**
+ * Apply a non-linear fixed gain smoothing in order to reduce
+ * fluctuation in the energy of excitation
+ *
+ * @param[in]     fixed_gain       Unsmoothed fixed gain
+ * @param[in,out] prev_tr_gain     Previous threshold gain (updated)
+ * @param[in]     voice_fac        Frame voicing factor
+ * @param[in]     stab_fac         Frame stability factor
+ *
+ * @return The smoothed gain
+ */
+static float noise_enhancer(float fixed_gain, float *prev_tr_gain,
+                            float voice_fac,  float stab_fac)
+{
+    float sm_fac = 0.5 * (1 - voice_fac) * stab_fac;
+    float g0;
+
+    // XXX: the following fixed-point constants used to in(de)crement
+    // gain by 1.5dB were taken from the reference code, maybe it could
+    // be simpler
+    if (fixed_gain < *prev_tr_gain) {
+        g0 = FFMIN(*prev_tr_gain, fixed_gain + fixed_gain *
+                     (6226 * (1.0f / (1 << 15)))); // +1.5 dB
+    } else
+        g0 = FFMAX(*prev_tr_gain, fixed_gain *
+                    (27536 * (1.0f / (1 << 15)))); // -1.5 dB
+
+    *prev_tr_gain = g0; // update next frame threshold
+
+    return sm_fac * g0 + (1 - sm_fac) * fixed_gain;
+}
+
+/**
+ * Filter the fixed_vector to emphasize the higher frequencies
+ *
+ * @param[in,out] fixed_vector     Fixed codebook vector
+ * @param[in]     voice_fac        Frame voicing factor
+ */
+static void pitch_enhancer(float *fixed_vector, float voice_fac)
+{
+    int i;
+    float cpe  = 0.125 * (1 + voice_fac);
+    float last = fixed_vector[0]; // holds c(i - 1)
+
+    fixed_vector[0] -= cpe * fixed_vector[1];
+
+    for (i = 1; i < AMRWB_SFR_SIZE - 1; i++) {
+        float cur = fixed_vector[i];
+
+        fixed_vector[i] -= cpe * (last + fixed_vector[i + 1]);
+        last = cur;
+    }
+
+    fixed_vector[AMRWB_SFR_SIZE - 1] -= cpe * last;
+}
+
+/**
+ * Conduct 16th order linear predictive coding synthesis from excitation
+ *
+ * @param[in]     ctx              Pointer to the AMRWBContext
+ * @param[in]     lpc              Pointer to the LPC coefficients
+ * @param[out]    excitation       Buffer for synthesis final excitation
+ * @param[in]     fixed_gain       Fixed codebook gain for synthesis
+ * @param[in]     fixed_vector     Algebraic codebook vector
+ * @param[in,out] samples          Pointer to the output samples and memory
+ */
+static void synthesis(AMRWBContext *ctx, float *lpc, float *excitation,
+                      float fixed_gain, const float *fixed_vector,
+                      float *samples)
+{
+    ff_weighted_vector_sumf(excitation, ctx->pitch_vector, fixed_vector,
+                            ctx->pitch_gain[0], fixed_gain, AMRWB_SFR_SIZE);
+
+    /* emphasize pitch vector contribution in low bitrate modes */
+    if (ctx->pitch_gain[0] > 0.5 && ctx->fr_cur_mode <= MODE_8k85) {
+        int i;
+        float energy = ff_dot_productf(excitation, excitation,
+                                       AMRWB_SFR_SIZE);
+
+        // XXX: Weird part in both ref code and spec. A unknown parameter
+        // {beta} seems to be identical to the current pitch gain
+        float pitch_factor = 0.25 * ctx->pitch_gain[0] * ctx->pitch_gain[0];
+
+        for (i = 0; i < AMRWB_SFR_SIZE; i++)
+            excitation[i] += pitch_factor * ctx->pitch_vector[i];
+
+        ff_scale_vector_to_given_sum_of_squares(excitation, excitation,
+                                                energy, AMRWB_SFR_SIZE);
+    }
+
+    ff_celp_lp_synthesis_filterf(samples, lpc, excitation,
+                                 AMRWB_SFR_SIZE, LP_ORDER);
+}
+
+/**
+ * Apply to synthesis a de-emphasis filter of the form:
+ * H(z) = 1 / (1 - m * z^-1)
+ *
+ * @param[out]    out              Output buffer
+ * @param[in]     in               Input samples array with in[-1]
+ * @param[in]     m                Filter coefficient
+ * @param[in,out] mem              State from last filtering
+ */
+static void de_emphasis(float *out, float *in, float m, float mem[1])
+{
+    int i;
+
+    out[0] = in[0] + m * mem[0];
+
+    for (i = 1; i < AMRWB_SFR_SIZE; i++)
+         out[i] = in[i] + out[i - 1] * m;
+
+    mem[0] = out[AMRWB_SFR_SIZE - 1];
+}
+
+/**
+ * Upsample a signal by 5/4 ratio (from 12.8kHz to 16kHz) using
+ * a FIR interpolation filter. Uses past data from before *in address
+ *
+ * @param[out] out                 Buffer for interpolated signal
+ * @param[in]  in                  Current signal data (length 0.8*o_size)
+ * @param[in]  o_size              Output signal length
+ */
+static void upsample_5_4(float *out, const float *in, int o_size)
+{
+    const float *in0 = in - UPS_FIR_SIZE + 1;
+    int i, j, k;
+    int int_part = 0, frac_part;
+
+    i = 0;
+    for (j = 0; j < o_size / 5; j++) {
+        out[i] = in[int_part];
+        frac_part = 4;
+        i++;
+
+        for (k = 1; k < 5; k++) {
+            out[i] = ff_dot_productf(in0 + int_part, upsample_fir[4 - frac_part],
+                                     UPS_MEM_SIZE);
+            int_part++;
+            frac_part--;
+            i++;
+        }
+    }
+}
+
+/**
+ * Calculate the high-band gain based on encoded index (23k85 mode) or
+ * on the low-band speech signal and the Voice Activity Detection flag
+ *
+ * @param[in] ctx                  The context
+ * @param[in] synth                LB speech synthesis at 12.8k
+ * @param[in] hb_idx               Gain index for mode 23k85 only
+ * @param[in] vad                  VAD flag for the frame
+ */
+static float find_hb_gain(AMRWBContext *ctx, const float *synth,
+                          uint16_t hb_idx, uint8_t vad)
+{
+    int wsp = (vad > 0);
+    float tilt;
+
+    if (ctx->fr_cur_mode == MODE_23k85)
+        return qua_hb_gain[hb_idx] * (1.0f / (1 << 14));
+
+    tilt = ff_dot_productf(synth, synth + 1, AMRWB_SFR_SIZE - 1) /
+           ff_dot_productf(synth, synth, AMRWB_SFR_SIZE);
+
+    /* return gain bounded by [0.1, 1.0] */
+    return av_clipf((1.0 - FFMAX(0.0, tilt)) * (1.25 - 0.25 * wsp), 0.1, 1.0);
+}
+
+/**
+ * Generate the high-band excitation with the same energy from the lower
+ * one and scaled by the given gain
+ *
+ * @param[in]  ctx                 The context
+ * @param[out] hb_exc              Buffer for the excitation
+ * @param[in]  synth_exc           Low-band excitation used for synthesis
+ * @param[in]  hb_gain             Wanted excitation gain
+ */
+static void scaled_hb_excitation(AMRWBContext *ctx, float *hb_exc,
+                                 const float *synth_exc, float hb_gain)
+{
+    int i;
+    float energy = ff_dot_productf(synth_exc, synth_exc, AMRWB_SFR_SIZE);
+
+    /* Generate a white-noise excitation */
+    for (i = 0; i < AMRWB_SFR_SIZE_16k; i++)
+        hb_exc[i] = 32768.0 - (uint16_t) av_lfg_get(&ctx->prng);
+
+    ff_scale_vector_to_given_sum_of_squares(hb_exc, hb_exc,
+                                            energy * hb_gain * hb_gain,
+                                            AMRWB_SFR_SIZE_16k);
+}
+
+/**
+ * Calculate the auto-correlation for the ISF difference vector
+ */
+static float auto_correlation(float *diff_isf, float mean, int lag)
+{
+    int i;
+    float sum = 0.0;
+
+    for (i = 7; i < LP_ORDER - 2; i++) {
+        float prod = (diff_isf[i] - mean) * (diff_isf[i - lag] - mean);
+        sum += prod * prod;
+    }
+    return sum;
+}
+
+/**
+ * Extrapolate a ISF vector to the 16kHz range (20th order LP)
+ * used at mode 6k60 LP filter for the high frequency band
+ *
+ * @param[out] out                 Buffer for extrapolated isf
+ * @param[in]  isf                 Input isf vector
+ */
+static void extrapolate_isf(float out[LP_ORDER_16k], float isf[LP_ORDER])
+{
+    float diff_isf[LP_ORDER - 2], diff_mean;
+    float *diff_hi = diff_isf - LP_ORDER + 1; // diff array for extrapolated indexes
+    float corr_lag[3];
+    float est, scale;
+    int i, i_max_corr;
+
+    memcpy(out, isf, (LP_ORDER - 1) * sizeof(float));
+    out[LP_ORDER_16k - 1] = isf[LP_ORDER - 1];
+
+    /* Calculate the difference vector */
+    for (i = 0; i < LP_ORDER - 2; i++)
+        diff_isf[i] = isf[i + 1] - isf[i];
+
+    diff_mean = 0.0;
+    for (i = 2; i < LP_ORDER - 2; i++)
+        diff_mean += diff_isf[i] * (1.0f / (LP_ORDER - 4));
+
+    /* Find which is the maximum autocorrelation */
+    i_max_corr = 0;
+    for (i = 0; i < 3; i++) {
+        corr_lag[i] = auto_correlation(diff_isf, diff_mean, i + 2);
+
+        if (corr_lag[i] > corr_lag[i_max_corr])
+            i_max_corr = i;
+    }
+    i_max_corr++;
+
+    for (i = LP_ORDER - 1; i < LP_ORDER_16k - 1; i++)
+        out[i] = isf[i - 1] + isf[i - 1 - i_max_corr]
+                            - isf[i - 2 - i_max_corr];
+
+    /* Calculate an estimate for ISF(18) and scale ISF based on the error */
+    est   = 7965 + (out[2] - out[3] - out[4]) / 6.0;
+    scale = 0.5 * (FFMIN(est, 7600) - out[LP_ORDER - 2]) /
+            (out[LP_ORDER_16k - 2] - out[LP_ORDER - 2]);
+
+    for (i = LP_ORDER - 1; i < LP_ORDER_16k - 1; i++)
+        diff_hi[i] = scale * (out[i] - out[i - 1]);
+
+    /* Stability insurance */
+    for (i = LP_ORDER; i < LP_ORDER_16k - 1; i++)
+        if (diff_hi[i] + diff_hi[i - 1] < 5.0) {
+            if (diff_hi[i] > diff_hi[i - 1]) {
+                diff_hi[i - 1] = 5.0 - diff_hi[i];
+            } else
+                diff_hi[i] = 5.0 - diff_hi[i - 1];
+        }
+
+    for (i = LP_ORDER - 1; i < LP_ORDER_16k - 1; i++)
+        out[i] = out[i - 1] + diff_hi[i] * (1.0f / (1 << 15));
+
+    /* Scale the ISF vector for 16000 Hz */
+    for (i = 0; i < LP_ORDER_16k - 1; i++)
+        out[i] *= 0.8;
+}
+
+/**
+ * Spectral expand the LP coefficients using the equation:
+ *   y[i] = x[i] * (gamma ** i)
+ *
+ * @param[out] out                 Output buffer (may use input array)
+ * @param[in]  lpc                 LP coefficients array
+ * @param[in]  gamma               Weighting factor
+ * @param[in]  size                LP array size
+ */
+static void lpc_weighting(float *out, const float *lpc, float gamma, int size)
+{
+    int i;
+    float fac = gamma;
+
+    for (i = 0; i < size; i++) {
+        out[i] = lpc[i] * fac;
+        fac   *= gamma;
+    }
+}
+
+/**
+ * Conduct 20th order linear predictive coding synthesis for the high
+ * frequency band excitation at 16kHz
+ *
+ * @param[in]     ctx              The context
+ * @param[in]     subframe         Current subframe index (0 to 3)
+ * @param[in,out] samples          Pointer to the output speech samples
+ * @param[in]     exc              Generated white-noise scaled excitation
+ * @param[in]     isf              Current frame isf vector
+ * @param[in]     isf_past         Past frame final isf vector
+ */
+static void hb_synthesis(AMRWBContext *ctx, int subframe, float *samples,
+                         const float *exc, const float *isf, const float *isf_past)
+{
+    float hb_lpc[LP_ORDER_16k];
+    enum Mode mode = ctx->fr_cur_mode;
+
+    if (mode == MODE_6k60) {
+        float e_isf[LP_ORDER_16k]; // ISF vector for extrapolation
+        double e_isp[LP_ORDER_16k];
+
+        ff_weighted_vector_sumf(e_isf, isf_past, isf, isfp_inter[subframe],
+                                1.0 - isfp_inter[subframe], LP_ORDER);
+
+        extrapolate_isf(e_isf, e_isf);
+
+        e_isf[LP_ORDER_16k - 1] *= 2.0;
+        ff_acelp_lsf2lspd(e_isp, e_isf, LP_ORDER_16k);
+        ff_amrwb_lsp2lpc(e_isp, hb_lpc, LP_ORDER_16k);
+
+        lpc_weighting(hb_lpc, hb_lpc, 0.9, LP_ORDER_16k);
+    } else {
+        lpc_weighting(hb_lpc, ctx->lp_coef[subframe], 0.6, LP_ORDER);
+    }
+
+    ff_celp_lp_synthesis_filterf(samples, hb_lpc, exc, AMRWB_SFR_SIZE_16k,
+                                 (mode == MODE_6k60) ? LP_ORDER_16k : LP_ORDER);
+}
+
+/**
+ * Apply to high-band samples a 15th order filter
+ * The filter characteristic depends on the given coefficients
+ *
+ * @param[out]    out              Buffer for filtered output
+ * @param[in]     fir_coef         Filter coefficients
+ * @param[in,out] mem              State from last filtering (updated)
+ * @param[in]     in               Input speech data (high-band)
+ *
+ * @remark It is safe to pass the same array in in and out parameters
+ */
+static void hb_fir_filter(float *out, const float fir_coef[HB_FIR_SIZE + 1],
+                          float mem[HB_FIR_SIZE], const float *in)
+{
+    int i, j;
+    float data[AMRWB_SFR_SIZE_16k + HB_FIR_SIZE]; // past and current samples
+
+    memcpy(data, mem, HB_FIR_SIZE * sizeof(float));
+    memcpy(data + HB_FIR_SIZE, in, AMRWB_SFR_SIZE_16k * sizeof(float));
+
+    for (i = 0; i < AMRWB_SFR_SIZE_16k; i++) {
+        out[i] = 0.0;
+        for (j = 0; j <= HB_FIR_SIZE; j++)
+            out[i] += data[i + j] * fir_coef[j];
+    }
+
+    memcpy(mem, data + AMRWB_SFR_SIZE_16k, HB_FIR_SIZE * sizeof(float));
+}
+
+/**
+ * Update context state before the next subframe
+ */
+static void update_sub_state(AMRWBContext *ctx)
+{
+    memmove(&ctx->excitation_buf[0], &ctx->excitation_buf[AMRWB_SFR_SIZE],
+            (AMRWB_P_DELAY_MAX + LP_ORDER + 1) * sizeof(float));
+
+    memmove(&ctx->pitch_gain[1], &ctx->pitch_gain[0], 5 * sizeof(float));
+    memmove(&ctx->fixed_gain[1], &ctx->fixed_gain[0], 1 * sizeof(float));
+
+    memmove(&ctx->samples_az[0], &ctx->samples_az[AMRWB_SFR_SIZE],
+            LP_ORDER * sizeof(float));
+    memmove(&ctx->samples_up[0], &ctx->samples_up[AMRWB_SFR_SIZE],
+            UPS_MEM_SIZE * sizeof(float));
+    memmove(&ctx->samples_hb[0], &ctx->samples_hb[AMRWB_SFR_SIZE_16k],
+            LP_ORDER_16k * sizeof(float));
+}
+
+static int amrwb_decode_frame(AVCodecContext *avctx, void *data, int *data_size,
+                              AVPacket *avpkt)
+{
+    AMRWBContext *ctx  = avctx->priv_data;
+    AMRWBFrame   *cf   = &ctx->frame;
+    const uint8_t *buf = avpkt->data;
+    int buf_size       = avpkt->size;
+    int expected_fr_size, header_size;
+    float *buf_out = data;
+    float spare_vector[AMRWB_SFR_SIZE];      // extra stack space to hold result from anti-sparseness processing
+    float fixed_gain_factor;                 // fixed gain correction factor (gamma)
+    float *synth_fixed_vector;               // pointer to the fixed vector that synthesis should use
+    float synth_fixed_gain;                  // the fixed gain that synthesis should use
+    float voice_fac, stab_fac;               // parameters used for gain smoothing
+    float synth_exc[AMRWB_SFR_SIZE];         // post-processed excitation for synthesis
+    float hb_exc[AMRWB_SFR_SIZE_16k];        // excitation for the high frequency band
+    float hb_samples[AMRWB_SFR_SIZE_16k];    // filtered high-band samples from synthesis
+    float hb_gain;
+    int sub, i;
+
+    header_size      = decode_mime_header(ctx, buf);
+    expected_fr_size = ((cf_sizes_wb[ctx->fr_cur_mode] + 7) >> 3) + 1;
+
+    if (buf_size < expected_fr_size) {
+        av_log(avctx, AV_LOG_ERROR,
+            "Frame too small (%d bytes). Truncated file?\n", buf_size);
+        *data_size = 0;
+        return buf_size;
+    }
+
+    if (!ctx->fr_quality || ctx->fr_cur_mode > MODE_SID)
+        av_log(avctx, AV_LOG_ERROR, "Encountered a bad or corrupted frame\n");
+
+    if (ctx->fr_cur_mode == MODE_SID) /* Comfort noise frame */
+        av_log_missing_feature(avctx, "SID mode", 1);
+
+    if (ctx->fr_cur_mode >= MODE_SID)
+        return -1;
+
+    ff_amr_bit_reorder((uint16_t *) &ctx->frame, sizeof(AMRWBFrame),
+        buf + header_size, amr_bit_orderings_by_mode[ctx->fr_cur_mode]);
+
+    /* Decode the quantized ISF vector */
+    if (ctx->fr_cur_mode == MODE_6k60) {
+        decode_isf_indices_36b(cf->isp_id, ctx->isf_cur);
+    } else {
+        decode_isf_indices_46b(cf->isp_id, ctx->isf_cur);
+    }
+
+    isf_add_mean_and_past(ctx->isf_cur, ctx->isf_q_past);
+    ff_set_min_dist_lsf(ctx->isf_cur, MIN_ISF_SPACING, LP_ORDER - 1);
+
+    stab_fac = stability_factor(ctx->isf_cur, ctx->isf_past_final);
+
+    ctx->isf_cur[LP_ORDER - 1] *= 2.0;
+    ff_acelp_lsf2lspd(ctx->isp[3], ctx->isf_cur, LP_ORDER);
+
+    /* Generate a ISP vector for each subframe */
+    if (ctx->first_frame) {
+        ctx->first_frame = 0;
+        memcpy(ctx->isp_sub4_past, ctx->isp[3], LP_ORDER * sizeof(double));
+    }
+    interpolate_isp(ctx->isp, ctx->isp_sub4_past);
+
+    for (sub = 0; sub < 4; sub++)
+        ff_amrwb_lsp2lpc(ctx->isp[sub], ctx->lp_coef[sub], LP_ORDER);
+
+    for (sub = 0; sub < 4; sub++) {
+        const AMRWBSubFrame *cur_subframe = &cf->subframe[sub];
+        float *sub_buf = buf_out + sub * AMRWB_SFR_SIZE_16k;
+
+        /* Decode adaptive codebook (pitch vector) */
+        decode_pitch_vector(ctx, cur_subframe, sub);
+        /* Decode innovative codebook (fixed vector) */
+        decode_fixed_vector(ctx->fixed_vector, cur_subframe->pul_ih,
+                            cur_subframe->pul_il, ctx->fr_cur_mode);
+
+        pitch_sharpening(ctx, ctx->fixed_vector);
+
+        decode_gains(cur_subframe->vq_gain, ctx->fr_cur_mode,
+                     &fixed_gain_factor, &ctx->pitch_gain[0]);
+
+        ctx->fixed_gain[0] =
+            ff_amr_set_fixed_gain(fixed_gain_factor,
+                       ff_dot_productf(ctx->fixed_vector, ctx->fixed_vector,
+                                       AMRWB_SFR_SIZE) / AMRWB_SFR_SIZE,
+                       ctx->prediction_error,
+                       ENERGY_MEAN, energy_pred_fac);
+
+        /* Calculate voice factor and store tilt for next subframe */
+        voice_fac      = voice_factor(ctx->pitch_vector, ctx->pitch_gain[0],
+                                      ctx->fixed_vector, ctx->fixed_gain[0]);
+        ctx->tilt_coef = voice_fac * 0.25 + 0.25;
+
+        /* Construct current excitation */
+        for (i = 0; i < AMRWB_SFR_SIZE; i++) {
+            ctx->excitation[i] *= ctx->pitch_gain[0];
+            ctx->excitation[i] += ctx->fixed_gain[0] * ctx->fixed_vector[i];
+            ctx->excitation[i] = truncf(ctx->excitation[i]);
+        }
+
+        /* Post-processing of excitation elements */
+        synth_fixed_gain = noise_enhancer(ctx->fixed_gain[0], &ctx->prev_tr_gain,
+                                          voice_fac, stab_fac);
+
+        synth_fixed_vector = anti_sparseness(ctx, ctx->fixed_vector,
+                                             spare_vector);
+
+        pitch_enhancer(synth_fixed_vector, voice_fac);
+
+        synthesis(ctx, ctx->lp_coef[sub], synth_exc, synth_fixed_gain,
+                  synth_fixed_vector, &ctx->samples_az[LP_ORDER]);
+
+        /* Synthesis speech post-processing */
+        de_emphasis(&ctx->samples_up[UPS_MEM_SIZE],
+                    &ctx->samples_az[LP_ORDER], PREEMPH_FAC, ctx->demph_mem);
+
+        ff_acelp_apply_order_2_transfer_function(&ctx->samples_up[UPS_MEM_SIZE],
+            &ctx->samples_up[UPS_MEM_SIZE], hpf_zeros, hpf_31_poles,
+            hpf_31_gain, ctx->hpf_31_mem, AMRWB_SFR_SIZE);
+
+        upsample_5_4(sub_buf, &ctx->samples_up[UPS_FIR_SIZE],
+                     AMRWB_SFR_SIZE_16k);
+
+        /* High frequency band (6.4 - 7.0 kHz) generation part */
+        ff_acelp_apply_order_2_transfer_function(hb_samples,
+            &ctx->samples_up[UPS_MEM_SIZE], hpf_zeros, hpf_400_poles,
+            hpf_400_gain, ctx->hpf_400_mem, AMRWB_SFR_SIZE);
+
+        hb_gain = find_hb_gain(ctx, hb_samples,
+                               cur_subframe->hb_gain, cf->vad);
+
+        scaled_hb_excitation(ctx, hb_exc, synth_exc, hb_gain);
+
+        hb_synthesis(ctx, sub, &ctx->samples_hb[LP_ORDER_16k],
+                     hb_exc, ctx->isf_cur, ctx->isf_past_final);
+
+        /* High-band post-processing filters */
+        hb_fir_filter(hb_samples, bpf_6_7_coef, ctx->bpf_6_7_mem,
+                      &ctx->samples_hb[LP_ORDER_16k]);
+
+        if (ctx->fr_cur_mode == MODE_23k85)
+            hb_fir_filter(hb_samples, lpf_7_coef, ctx->lpf_7_mem,
+                          hb_samples);
+
+        /* Add the low and high frequency bands */
+        for (i = 0; i < AMRWB_SFR_SIZE_16k; i++)
+            sub_buf[i] = (sub_buf[i] + hb_samples[i]) * (1.0f / (1 << 15));
+
+        /* Update buffers and history */
+        update_sub_state(ctx);
+    }
+
+    /* update state for next frame */
+    memcpy(ctx->isp_sub4_past, ctx->isp[3], LP_ORDER * sizeof(ctx->isp[3][0]));
+    memcpy(ctx->isf_past_final, ctx->isf_cur, LP_ORDER * sizeof(float));
+
+    /* report how many samples we got */
+    *data_size = 4 * AMRWB_SFR_SIZE_16k * sizeof(float);
+
+    return expected_fr_size;
+}
+
+AVCodec ff_amrwb_decoder = {
+    .name           = "amrwb",
+    .type           = AVMEDIA_TYPE_AUDIO,
+    .id             = CODEC_ID_AMR_WB,
+    .priv_data_size = sizeof(AMRWBContext),
+    .init           = amrwb_decode_init,
+    .decode         = amrwb_decode_frame,
+    .long_name      = NULL_IF_CONFIG_SMALL("Adaptive Multi-Rate WideBand"),
+    .sample_fmts    = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_FLT,AV_SAMPLE_FMT_NONE},
+};
diff --git a/libavcodec/anm.c b/libavcodec/anm.c
index f384861..ef037f2 100644
--- a/libavcodec/anm.c
+++ b/libavcodec/anm.c
@@ -2,20 +2,20 @@
  * Deluxe Paint Animation decoder
  * Copyright (c) 2009 Peter Ross
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -183,7 +183,7 @@ static av_cold int decode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec anm_decoder = {
+AVCodec ff_anm_decoder = {
     "anm",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_ANM,
diff --git a/libavcodec/ansi.c b/libavcodec/ansi.c
new file mode 100644
index 0000000..892cc34
--- /dev/null
+++ b/libavcodec/ansi.c
@@ -0,0 +1,435 @@
+/*
+ * ASCII/ANSI art decoder
+ * Copyright (c) 2010 Peter Ross <pross at xvid.org>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * ASCII/ANSI art decoder
+ */
+
+#include "libavutil/lfg.h"
+#include "avcodec.h"
+#include "cga_data.h"
+
+#define ATTR_BOLD         0x01  /**< Bold/Bright-foreground (mode 1) */
+#define ATTR_FAINT        0x02  /**< Faint (mode 2) */
+#define ATTR_UNDERLINE    0x08  /**< Underline (mode 4) */
+#define ATTR_BLINK        0x10  /**< Blink/Bright-background (mode 5) */
+#define ATTR_REVERSE      0x40  /**< Reverse (mode 7) */
+#define ATTR_CONCEALED    0x80  /**< Concealed (mode 8) */
+
+#define DEFAULT_FG_COLOR     7  /**< CGA color index */
+#define DEFAULT_BG_COLOR     0
+#define DEFAULT_SCREEN_MODE  3  /**< 80x25 */
+
+#define FONT_WIDTH           8  /**< Font width */
+
+/** map ansi color index to cga palette index */
+static const uint8_t ansi_to_cga[16] = {
+    0,  4,  2,  6,  1,  5,  3, 7, 8, 12, 10, 14,  9, 13, 11, 15
+};
+
+typedef struct {
+    AVFrame frame;
+    int x;                /**< x cursor position (pixels) */
+    int y;                /**< y cursor position (pixels) */
+    int sx;               /**< saved x cursor position (pixels) */
+    int sy;               /**< saved y cursor position (pixels) */
+    const uint8_t* font;  /**< font */
+    int font_height;      /**< font height */
+    int attributes;       /**< attribute flags */
+    int fg;               /**< foreground color */
+    int bg;               /**< background color */
+
+    /* ansi parser state machine */
+    enum {
+        STATE_NORMAL = 0,
+        STATE_ESCAPE,
+        STATE_CODE,
+        STATE_MUSIC_PREAMBLE
+    } state;
+#define MAX_NB_ARGS 4
+    int args[MAX_NB_ARGS];
+    int nb_args;          /**< number of arguments (may exceed MAX_NB_ARGS) */
+} AnsiContext;
+
+static av_cold int decode_init(AVCodecContext *avctx)
+{
+    AnsiContext *s = avctx->priv_data;
+    avctx->pix_fmt = PIX_FMT_PAL8;
+
+    /* defaults */
+    s->font        = ff_vga16_font;
+    s->font_height = 16;
+    s->fg          = DEFAULT_FG_COLOR;
+    s->bg          = DEFAULT_BG_COLOR;
+
+    if (!avctx->width || !avctx->height)
+        avcodec_set_dimensions(avctx, 80<<3, 25<<4);
+
+    return 0;
+}
+
+static void hscroll(AVCodecContext *avctx)
+{
+    AnsiContext *s = avctx->priv_data;
+    int i;
+
+    if (s->y < avctx->height - s->font_height) {
+        s->y += s->font_height;
+        return;
+    }
+
+    i = 0;
+    for (; i < avctx->height - s->font_height; i++)
+        memcpy(s->frame.data[0] + i * s->frame.linesize[0],
+               s->frame.data[0] + (i + s->font_height) * s->frame.linesize[0],
+               avctx->width);
+    for (; i < avctx->height; i++)
+        memset(s->frame.data[0] + i * s->frame.linesize[0],
+            DEFAULT_BG_COLOR, avctx->width);
+}
+
+static void erase_line(AVCodecContext * avctx, int xoffset, int xlength)
+{
+    AnsiContext *s = avctx->priv_data;
+    int i;
+    for (i = 0; i < s->font_height; i++)
+        memset(s->frame.data[0] + (s->y + i)*s->frame.linesize[0] + xoffset,
+            DEFAULT_BG_COLOR, xlength);
+}
+
+static void erase_screen(AVCodecContext *avctx)
+{
+    AnsiContext *s = avctx->priv_data;
+    int i;
+    for (i = 0; i < avctx->height; i++)
+        memset(s->frame.data[0] + i * s->frame.linesize[0], DEFAULT_BG_COLOR, avctx->width);
+    s->x = s->y = 0;
+}
+
+/**
+ * Draw character to screen
+ */
+static void draw_char(AVCodecContext *avctx, int c)
+{
+    AnsiContext *s = avctx->priv_data;
+    int fg = s->fg;
+    int bg = s->bg;
+
+    if ((s->attributes & ATTR_BOLD))
+        fg += 8;
+    if ((s->attributes & ATTR_BLINK))
+        bg += 8;
+    if ((s->attributes & ATTR_REVERSE))
+        FFSWAP(int, fg, bg);
+    if ((s->attributes & ATTR_CONCEALED))
+        fg = bg;
+    ff_draw_pc_font(s->frame.data[0] + s->y * s->frame.linesize[0] + s->x,
+                    s->frame.linesize[0], s->font, s->font_height, c, fg, bg);
+    s->x += FONT_WIDTH;
+    if (s->x >= avctx->width) {
+        s->x = 0;
+        hscroll(avctx);
+    }
+}
+
+/**
+ * Execute ANSI escape code
+ * @param <0 error
+ */
+static int execute_code(AVCodecContext * avctx, int c)
+{
+    AnsiContext *s = avctx->priv_data;
+    int ret, i, width, height;
+    switch(c) {
+    case 'A': //Cursor Up
+        s->y = FFMAX(s->y - (s->nb_args > 0 ? s->args[0]*s->font_height : s->font_height), 0);
+        break;
+    case 'B': //Cursor Down
+        s->y = FFMIN(s->y + (s->nb_args > 0 ? s->args[0]*s->font_height : s->font_height), avctx->height - s->font_height);
+        break;
+    case 'C': //Cursor Right
+        s->x = FFMIN(s->x + (s->nb_args > 0 ? s->args[0]*FONT_WIDTH : FONT_WIDTH), avctx->width  - FONT_WIDTH);
+        break;
+    case 'D': //Cursor Left
+        s->x = FFMAX(s->x - (s->nb_args > 0 ? s->args[0]*FONT_WIDTH : FONT_WIDTH), 0);
+        break;
+    case 'H': //Cursor Position
+    case 'f': //Horizontal and Vertical Position
+        s->y = s->nb_args > 0 ? av_clip((s->args[0] - 1)*s->font_height, 0, avctx->height - s->font_height) : 0;
+        s->x = s->nb_args > 1 ? av_clip((s->args[1] - 1)*FONT_WIDTH,     0, avctx->width  - FONT_WIDTH) : 0;
+        break;
+    case 'h': //set creen mode
+    case 'l': //reset screen mode
+        if (s->nb_args < 2)
+            s->args[0] = DEFAULT_SCREEN_MODE;
+        switch(s->args[0]) {
+        case 0: case 1: case 4: case 5: case 13: case 19: //320x200 (25 rows)
+            s->font = ff_cga_font;
+            s->font_height = 8;
+            width  = 40<<3;
+            height = 25<<3;
+            break;
+        case 2: case 3: //640x400 (25 rows)
+            s->font = ff_vga16_font;
+            s->font_height = 16;
+            width  = 80<<3;
+            height = 25<<4;
+            break;
+        case 6: case 14: //640x200 (25 rows)
+            s->font = ff_cga_font;
+            s->font_height = 8;
+            width  = 80<<3;
+            height = 25<<3;
+            break;
+        case 7: //set line wrapping
+            break;
+        case 15: case 16: //640x350 (43 rows)
+            s->font = ff_cga_font;
+            s->font_height = 8;
+            width  = 80<<3;
+            height = 43<<3;
+            break;
+        case 17: case 18: //640x480 (60 rows)
+            s->font = ff_cga_font;
+            s->font_height = 8;
+            width  = 80<<3;
+            height = 60<<4;
+            break;
+        default:
+            av_log_ask_for_sample(avctx, "unsupported screen mode\n");
+        }
+        if (width != avctx->width || height != avctx->height) {
+            if (s->frame.data[0])
+                avctx->release_buffer(avctx, &s->frame);
+            avcodec_set_dimensions(avctx, width, height);
+            ret = avctx->get_buffer(avctx, &s->frame);
+            if (ret < 0) {
+                av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
+                return ret;
+            }
+            s->frame.pict_type           = FF_I_TYPE;
+            s->frame.palette_has_changed = 1;
+            memcpy(s->frame.data[1], ff_cga_palette, 16 * 4);
+            erase_screen(avctx);
+        } else if (c == 'l') {
+            erase_screen(avctx);
+        }
+        break;
+    case 'J': //Erase in Page
+        switch (s->args[0]) {
+        case 0:
+            erase_line(avctx, s->x, avctx->width - s->x);
+            if (s->y < avctx->height - s->font_height)
+                memset(s->frame.data[0] + (s->y + s->font_height)*s->frame.linesize[0],
+                    DEFAULT_BG_COLOR, (avctx->height - s->y - s->font_height)*s->frame.linesize[0]);
+            break;
+        case 1:
+            erase_line(avctx, 0, s->x);
+            if (s->y > 0)
+                memset(s->frame.data[0], DEFAULT_BG_COLOR, s->y * s->frame.linesize[0]);
+            break;
+        case 2:
+            erase_screen(avctx);
+        }
+        break;
+    case 'K': //Erase in Line
+        switch(s->args[0]) {
+        case 0:
+            erase_line(avctx, s->x, avctx->width - s->x);
+            break;
+        case 1:
+            erase_line(avctx, 0, s->x);
+            break;
+        case 2:
+            erase_line(avctx, 0, avctx->width);
+        }
+        break;
+    case 'm': //Select Graphics Rendition
+        if (s->nb_args == 0) {
+            s->nb_args = 1;
+            s->args[0] = 0;
+        }
+        for (i = 0; i < FFMIN(s->nb_args, MAX_NB_ARGS); i++) {
+            int m = s->args[i];
+            if (m == 0) {
+                s->attributes = 0;
+                s->fg = DEFAULT_FG_COLOR;
+                s->bg = DEFAULT_BG_COLOR;
+            } else if (m == 1 || m == 2 || m == 4 || m == 5 || m == 7 || m == 8) {
+                s->attributes |= 1 << (m - 1);
+            } else if (m >= 30 && m <= 38) {
+                s->fg = ansi_to_cga[m - 30];
+            } else if (m == 39) {
+                s->fg = ansi_to_cga[DEFAULT_FG_COLOR];
+            } else if (m >= 40 && m <= 47) {
+                s->bg = ansi_to_cga[m - 40];
+            } else if (m == 49) {
+                s->fg = ansi_to_cga[DEFAULT_BG_COLOR];
+            } else {
+                av_log_ask_for_sample(avctx, "unsupported rendition parameter\n");
+            }
+        }
+        break;
+    case 'n': //Device Status Report
+    case 'R': //report current line and column
+        /* ignore */
+        break;
+    case 's': //Save Cursor Position
+        s->sx = s->x;
+        s->sy = s->y;
+        break;
+    case 'u': //Restore Cursor Position
+        s->x = av_clip(s->sx, 0, avctx->width  - FONT_WIDTH);
+        s->y = av_clip(s->sy, 0, avctx->height - s->font_height);
+        break;
+    default:
+        av_log_ask_for_sample(avctx, "unsupported escape code\n");
+        break;
+    }
+    return 0;
+}
+
+static int decode_frame(AVCodecContext *avctx,
+                            void *data, int *data_size,
+                            AVPacket *avpkt)
+{
+    AnsiContext *s = avctx->priv_data;
+    uint8_t *buf = avpkt->data;
+    int buf_size = avpkt->size;
+    const uint8_t *buf_end   = buf+buf_size;
+    int ret, i, count;
+
+    ret = avctx->reget_buffer(avctx, &s->frame);
+    if (ret < 0){
+        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
+        return ret;
+    }
+    s->frame.pict_type           = FF_I_TYPE;
+    s->frame.palette_has_changed = 1;
+    memcpy(s->frame.data[1], ff_cga_palette, 16 * 4);
+
+    while(buf < buf_end) {
+        switch(s->state) {
+        case STATE_NORMAL:
+            switch (buf[0]) {
+            case 0x00: //NUL
+            case 0x07: //BEL
+            case 0x1A: //SUB
+                /* ignore */
+                break;
+            case 0x08: //BS
+                s->x = FFMAX(s->x - 1, 0);
+                break;
+            case 0x09: //HT
+                i = s->x / FONT_WIDTH;
+                count = ((i + 8) & ~7) - i;
+                for (i = 0; i < count; i++)
+                    draw_char(avctx, ' ');
+                break;
+            case 0x0A: //LF
+                hscroll(avctx);
+            case 0x0D: //CR
+                s->x = 0;
+                break;
+            case 0x0C: //FF
+                erase_screen(avctx);
+                break;
+            case 0x1B: //ESC
+                s->state = STATE_ESCAPE;
+                break;
+            default:
+                draw_char(avctx, buf[0]);
+            }
+            break;
+        case STATE_ESCAPE:
+            if (buf[0] == '[') {
+                s->state   = STATE_CODE;
+                s->nb_args = 0;
+                s->args[0] = 0;
+            } else {
+                s->state = STATE_NORMAL;
+                draw_char(avctx, 0x1B);
+                    return -1;
+                continue;
+            }
+            break;
+        case STATE_CODE:
+            switch(buf[0]) {
+            case '0': case '1': case '2': case '3': case '4':
+            case '5': case '6': case '7': case '8': case '9':
+                if (s->nb_args < MAX_NB_ARGS)
+                    s->args[s->nb_args] = s->args[s->nb_args] * 10 + buf[0] - '0';
+                break;
+            case ';':
+                s->nb_args++;
+                if (s->nb_args < MAX_NB_ARGS)
+                    s->args[s->nb_args] = 0;
+                break;
+            case 'M':
+                s->state = STATE_MUSIC_PREAMBLE;
+                break;
+            case '=': case '?':
+                /* ignore */
+                break;
+            default:
+                if (s->nb_args > MAX_NB_ARGS)
+                    av_log(avctx, AV_LOG_WARNING, "args overflow (%i)\n", s->nb_args);
+                if (s->nb_args < MAX_NB_ARGS && s->args[s->nb_args])
+                    s->nb_args++;
+                if (execute_code(avctx, buf[0]) < 0)
+                    return -1;
+                s->state = STATE_NORMAL;
+            }
+            break;
+        case STATE_MUSIC_PREAMBLE:
+            if (buf[0] == 0x0E || buf[0] == 0x1B)
+                s->state = STATE_NORMAL;
+            /* ignore music data */
+            break;
+        }
+        buf++;
+    }
+
+    *data_size = sizeof(AVFrame);
+    *(AVFrame*)data = s->frame;
+    return buf_size;
+}
+
+static av_cold int decode_close(AVCodecContext *avctx)
+{
+    AnsiContext *s = avctx->priv_data;
+    if (s->frame.data[0])
+        avctx->release_buffer(avctx, &s->frame);
+    return 0;
+}
+
+AVCodec ff_ansi_decoder = {
+    .name           = "ansi",
+    .type           = AVMEDIA_TYPE_VIDEO,
+    .id             = CODEC_ID_ANSI,
+    .priv_data_size = sizeof(AnsiContext),
+    .init           = decode_init,
+    .close          = decode_close,
+    .decode         = decode_frame,
+    .capabilities   = CODEC_CAP_DR1,
+    .long_name      = NULL_IF_CONFIG_SMALL("ASCII/ANSI art"),
+};
diff --git a/libavcodec/apedec.c b/libavcodec/apedec.c
index a90a07f..d5a7efd 100644
--- a/libavcodec/apedec.c
+++ b/libavcodec/apedec.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2007 Benjamin Zores <ben at geexbox.org>
  *  based upon libdemac from Dave Chapman.
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,6 +25,7 @@
 #include "dsputil.h"
 #include "get_bits.h"
 #include "bytestream.h"
+#include "libavutil/audioconvert.h"
 
 /**
  * @file
@@ -198,8 +199,8 @@ static av_cold int ape_decode_init(AVCodecContext * avctx)
     }
 
     dsputil_init(&s->dsp, avctx);
-    avctx->sample_fmt = SAMPLE_FMT_S16;
-    avctx->channel_layout = (avctx->channels==2) ? CH_LAYOUT_STEREO : CH_LAYOUT_MONO;
+    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
+    avctx->channel_layout = (avctx->channels==2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;
     return 0;
 }
 
@@ -877,7 +878,13 @@ static int ape_decode_frame(AVCodecContext * avctx,
     return bytes_used;
 }
 
-AVCodec ape_decoder = {
+static void ape_flush(AVCodecContext *avctx)
+{
+    APEContext *s = avctx->priv_data;
+    s->samples= 0;
+}
+
+AVCodec ff_ape_decoder = {
     "ape",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_APE,
@@ -887,5 +894,6 @@ AVCodec ape_decoder = {
     ape_decode_close,
     ape_decode_frame,
     .capabilities = CODEC_CAP_SUBFRAMES,
+    .flush = ape_flush,
     .long_name = NULL_IF_CONFIG_SMALL("Monkey's Audio"),
 };
diff --git a/libavcodec/api-example.c b/libavcodec/api-example.c
index f34075e..0221a30 100644
--- a/libavcodec/api-example.c
+++ b/libavcodec/api-example.c
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2001 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/arm/Makefile b/libavcodec/arm/Makefile
index 46bfc75..a5abfdd 100644
--- a/libavcodec/arm/Makefile
+++ b/libavcodec/arm/Makefile
@@ -1,14 +1,23 @@
+OBJS-$(CONFIG_AC3DSP)                  += arm/ac3dsp_init_arm.o         \
+                                          arm/ac3dsp_arm.o
+
 OBJS-$(CONFIG_DCA_DECODER)             += arm/dcadsp_init_arm.o         \
 
+ARMV6-OBJS-$(CONFIG_AC3DSP)            += arm/ac3dsp_armv6.o
+
 OBJS-$(CONFIG_VP5_DECODER)             += arm/vp56dsp_init_arm.o
 OBJS-$(CONFIG_VP6_DECODER)             += arm/vp56dsp_init_arm.o
+OBJS-$(CONFIG_VP8_DECODER)             += arm/vp8dsp_init_arm.o
+ARMV6-OBJS-$(CONFIG_VP8_DECODER)       += arm/vp8_armv6.o
 
-OBJS-$(CONFIG_H264DSP)                 += arm/h264dsp_init_arm.o        \
-                                          arm/h264pred_init_arm.o       \
+OBJS-$(CONFIG_H264DSP)                 += arm/h264dsp_init_arm.o
+OBJS-$(CONFIG_H264PRED)                += arm/h264pred_init_arm.o
 
 OBJS                                   += arm/dsputil_init_arm.o        \
                                           arm/dsputil_arm.o             \
                                           arm/fft_init_arm.o            \
+                                          arm/fft_fixed_init_arm.o      \
+                                          arm/fmtconvert_init_arm.o     \
                                           arm/jrevdct_arm.o             \
                                           arm/mpegvideo_arm.o           \
                                           arm/simple_idct_arm.o         \
@@ -21,33 +30,49 @@ OBJS-$(HAVE_ARMV5TE)                   += arm/dsputil_init_armv5te.o    \
 OBJS-$(HAVE_ARMV6)                     += arm/dsputil_init_armv6.o      \
                                           arm/dsputil_armv6.o           \
                                           arm/simple_idct_armv6.o       \
+                                          $(ARMV6-OBJS-yes)
+
+VFP-OBJS-$(HAVE_ARMV6)                 += arm/fmtconvert_vfp.o          \
 
 OBJS-$(HAVE_ARMVFP)                    += arm/dsputil_vfp.o             \
                                           arm/dsputil_init_vfp.o        \
+                                          $(VFP-OBJS-yes)
 
 OBJS-$(HAVE_IWMMXT)                    += arm/dsputil_iwmmxt.o          \
                                           arm/mpegvideo_iwmmxt.o        \
 
 NEON-OBJS-$(CONFIG_FFT)                += arm/fft_neon.o                \
+                                          arm/fft_fixed_neon.o          \
 
 NEON-OBJS-$(CONFIG_MDCT)               += arm/mdct_neon.o               \
+                                          arm/mdct_fixed_neon.o         \
 
 NEON-OBJS-$(CONFIG_RDFT)               += arm/rdft_neon.o               \
 
 NEON-OBJS-$(CONFIG_H264DSP)            += arm/h264dsp_neon.o            \
                                           arm/h264idct_neon.o           \
-                                          arm/h264pred_neon.o           \
+
+NEON-OBJS-$(CONFIG_H264PRED)           += arm/h264pred_neon.o           \
+
+NEON-OBJS-$(CONFIG_AC3DSP)             += arm/ac3dsp_neon.o
 
 NEON-OBJS-$(CONFIG_DCA_DECODER)        += arm/dcadsp_neon.o             \
                                           arm/synth_filter_neon.o       \
 
 NEON-OBJS-$(CONFIG_VP3_DECODER)        += arm/vp3dsp_neon.o
 
-NEON-OBJS-$(CONFIG_VP5_DECODER)        += arm/vp56dsp_neon.o
-NEON-OBJS-$(CONFIG_VP6_DECODER)        += arm/vp56dsp_neon.o
+NEON-OBJS-$(CONFIG_VP5_DECODER)        += arm/vp56dsp_neon.o            \
+                                          arm/vp3dsp_neon.o             \
+
+NEON-OBJS-$(CONFIG_VP6_DECODER)        += arm/vp56dsp_neon.o            \
+                                          arm/vp3dsp_neon.o             \
+
+NEON-OBJS-$(CONFIG_VP8_DECODER)        += arm/vp8dsp_neon.o
 
 OBJS-$(HAVE_NEON)                      += arm/dsputil_init_neon.o       \
                                           arm/dsputil_neon.o            \
+                                          arm/fmtconvert_neon.o         \
                                           arm/int_neon.o                \
+                                          arm/mpegvideo_neon.o          \
                                           arm/simple_idct_neon.o        \
                                           $(NEON-OBJS-yes)
diff --git a/libavcodec/arm/aac.h b/libavcodec/arm/aac.h
index 390cdbf..e907c9e 100644
--- a/libavcodec/arm/aac.h
+++ b/libavcodec/arm/aac.h
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2010 Mans Rullgard <mans at mansr.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/arm/ac3dsp_arm.S b/libavcodec/arm/ac3dsp_arm.S
new file mode 100644
index 0000000..d7d498e
--- /dev/null
+++ b/libavcodec/arm/ac3dsp_arm.S
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 2011 Mans Rullgard <mans at mansr.com>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "asm.S"
+
+function ff_ac3_compute_mantissa_size_arm, export=1
+        push            {r4-r8,lr}
+        ldm             r0,  {r4-r8}
+        mov             r3,  r0
+        mov             r0,  #0
+1:
+        ldrb            lr,  [r1], #1
+        subs            r2,  r2,  #1
+        blt             2f
+        cmp             lr,  #4
+        bgt             3f
+        subs            lr,  lr,  #1
+        addlt           r4,  r4,  #1
+        addeq           r5,  r5,  #1
+        ble             1b
+        subs            lr,  lr,  #2
+        addlt           r6,  r6,  #1
+        addeq           r7,  r7,  #1
+        addgt           r8,  r8,  #1
+        b               1b
+3:
+        cmp             lr,  #14
+        sublt           lr,  lr,  #1
+        addgt           r0,  r0,  #16
+        addle           r0,  r0,  lr
+        b               1b
+2:
+        stm             r3,  {r4-r8}
+        pop             {r4-r8,pc}
+endfunc
diff --git a/libavcodec/arm/ac3dsp_armv6.S b/libavcodec/arm/ac3dsp_armv6.S
new file mode 100644
index 0000000..7f01add
--- /dev/null
+++ b/libavcodec/arm/ac3dsp_armv6.S
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2011 Mans Rullgard <mans at mansr.com>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "asm.S"
+
+function ff_ac3_bit_alloc_calc_bap_armv6, export=1
+        ldr             r12, [sp]
+        cmp             r12, #-960
+        beq             4f
+        push            {r4-r11,lr}
+        add             r5,  sp,  #40
+        movrel          r4,  X(ff_ac3_bin_to_band_tab)
+        movrel          lr,  X(ff_ac3_band_start_tab)
+        ldm             r5,  {r5-r7}
+        ldrb            r4,  [r4, r2]
+        add             r1,  r1,  r2,  lsl #1           @ psd + start
+        add             r0,  r0,  r4,  lsl #1           @ mask + band
+        add             r4,  lr,  r4
+        add             r7,  r7,  r2                    @ bap + start
+        ldrb            r10, [r4], #1
+1:
+        ldrsh           r9,  [r0], #2                   @ mask[band]
+        movw            r8,  #0x1fe0
+        sub             r9,  r9,  r12                   @   - snr_offset
+        mov             r11, r10
+        ldrb            r10, [r4], #1                   @ band_start_tab[band++]
+        subs            r9,  r9,  r5                    @   - floor
+        movlt           r9,  #0
+        cmp             r10, r3                         @   - end
+        and             r9,  r9,  r8                    @   & 0x1fe0
+        subgt           r8,  r3,  r11
+        suble           r8,  r10, r11
+        add             r9,  r9,  r5                    @   + floor => m
+        tst             r8,  #1
+        add             r2,  r7,  r8
+        bne             3f
+        b               5f
+2:
+        ldrsh           r8,  [r1], #2
+        ldrsh           lr,  [r1], #2
+        sub             r8,  r8,  r9
+        sub             lr,  lr,  r9
+        usat            r8,  #6,  r8,  asr #5           @ address
+        usat            lr,  #6,  lr,  asr #5
+        ldrb            r8,  [r6, r8]                   @ bap_tab[address]
+        ldrb            lr,  [r6, lr]
+        strb            r8,  [r7], #1                   @ bap[bin]
+        strb            lr,  [r7], #1
+5:      cmp             r7,  r2
+        blo             2b
+        cmp             r3,  r11
+        bgt             1b
+        pop             {r4-r11,pc}
+3:
+        ldrsh           r8,  [r1], #2                   @ psd[bin]
+        sub             r8,  r8,  r9                    @   - m
+        usat            r8,  #6,  r8,  asr #5           @ address
+        ldrb            r8,  [r6, r8]                   @ bap_tab[address]
+        strb            r8,  [r7], #1                   @ bap[bin]
+        b               5b
+4:
+        ldr             r0,  [sp, #12]
+        mov             r1,  #0
+        mov             r2,  #256
+        b               memset
+endfunc
diff --git a/libavcodec/arm/ac3dsp_init_arm.c b/libavcodec/arm/ac3dsp_init_arm.c
new file mode 100644
index 0000000..fd78e1e
--- /dev/null
+++ b/libavcodec/arm/ac3dsp_init_arm.c
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2011 Mans Rullgard <mans at mansr.com>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <stdint.h>
+#include "libavutil/attributes.h"
+#include "libavcodec/ac3dsp.h"
+#include "config.h"
+
+void ff_ac3_exponent_min_neon(uint8_t *exp, int num_reuse_blocks, int nb_coefs);
+int ff_ac3_max_msb_abs_int16_neon(const int16_t *src, int len);
+void ff_ac3_lshift_int16_neon(int16_t *src, unsigned len, unsigned shift);
+void ff_ac3_rshift_int32_neon(int32_t *src, unsigned len, unsigned shift);
+void ff_float_to_fixed24_neon(int32_t *dst, const float *src, unsigned int len);
+void ff_ac3_extract_exponents_neon(uint8_t *exp, int32_t *coef, int nb_coefs);
+
+void ff_ac3_bit_alloc_calc_bap_armv6(int16_t *mask, int16_t *psd,
+                                     int start, int end,
+                                     int snr_offset, int floor,
+                                     const uint8_t *bap_tab, uint8_t *bap);
+
+int ff_ac3_compute_mantissa_size_arm(int cnt[5], uint8_t *bap, int nb_coefs);
+
+av_cold void ff_ac3dsp_init_arm(AC3DSPContext *c, int bit_exact)
+{
+    c->compute_mantissa_size     = ff_ac3_compute_mantissa_size_arm;
+
+    if (HAVE_ARMV6) {
+        c->bit_alloc_calc_bap    = ff_ac3_bit_alloc_calc_bap_armv6;
+    }
+
+    if (HAVE_NEON) {
+        c->ac3_exponent_min      = ff_ac3_exponent_min_neon;
+        c->ac3_max_msb_abs_int16 = ff_ac3_max_msb_abs_int16_neon;
+        c->ac3_lshift_int16      = ff_ac3_lshift_int16_neon;
+        c->ac3_rshift_int32      = ff_ac3_rshift_int32_neon;
+        c->float_to_fixed24      = ff_float_to_fixed24_neon;
+        c->extract_exponents     = ff_ac3_extract_exponents_neon;
+    }
+}
diff --git a/libavcodec/arm/ac3dsp_neon.S b/libavcodec/arm/ac3dsp_neon.S
new file mode 100644
index 0000000..946b39f
--- /dev/null
+++ b/libavcodec/arm/ac3dsp_neon.S
@@ -0,0 +1,114 @@
+/*
+ * Copyright (c) 2011 Mans Rullgard <mans at mansr.com>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "asm.S"
+
+function ff_ac3_max_msb_abs_int16_neon, export=1
+        vmov.i16        q0,  #0
+        vmov.i16        q2,  #0
+1:      vld1.16         {q1},     [r0,:128]!
+        vabs.s16        q1,  q1
+        vld1.16         {q3},     [r0,:128]!
+        vabs.s16        q3,  q3
+        vorr            q0,  q0,  q1
+        vorr            q2,  q2,  q3
+        subs            r1,  r1,  #16
+        bgt             1b
+        vorr            q0,  q0,  q2
+        vorr            d0,  d0,  d1
+        vpmax.u16       d0,  d0,  d0
+        vpmax.u16       d0,  d0,  d0
+        vmov.u16        r0,  d0[0]
+        bx              lr
+endfunc
+
+function ff_ac3_exponent_min_neon, export=1
+        cmp             r1,  #0
+        bxeq            lr
+        push            {lr}
+        mov             r12, #256
+1:
+        vld1.8          {q0},     [r0,:128]
+        mov             lr,  r1
+        add             r3,  r0,  #256
+2:      vld1.8          {q1},     [r3,:128], r12
+        subs            lr,  lr,  #1
+        vmin.u8         q0,  q0,  q1
+        bgt             2b
+        subs            r2,  r2,  #16
+        vst1.8          {q0},     [r0,:128]!
+        bgt             1b
+        pop             {pc}
+endfunc
+
+function ff_ac3_lshift_int16_neon, export=1
+        vdup.16         q0,  r2
+1:      vld1.16         {q1},     [r0,:128]
+        vshl.s16        q1,  q1,  q0
+        vst1.16         {q1},     [r0,:128]!
+        subs            r1,  r1,  #8
+        bgt             1b
+        bx              lr
+endfunc
+
+function ff_ac3_rshift_int32_neon, export=1
+        rsb             r2,  r2,  #0
+        vdup.32         q0,  r2
+1:      vld1.32         {q1},     [r0,:128]
+        vshl.s32        q1,  q1,  q0
+        vst1.32         {q1},     [r0,:128]!
+        subs            r1,  r1,  #4
+        bgt             1b
+        bx              lr
+endfunc
+
+function ff_float_to_fixed24_neon, export=1
+1:      vld1.32         {q0-q1},  [r1,:128]!
+        vcvt.s32.f32    q0,  q0,  #24
+        vld1.32         {q2-q3},  [r1,:128]!
+        vcvt.s32.f32    q1,  q1,  #24
+        vcvt.s32.f32    q2,  q2,  #24
+        vst1.32         {q0-q1},  [r0,:128]!
+        vcvt.s32.f32    q3,  q3,  #24
+        vst1.32         {q2-q3},  [r0,:128]!
+        subs            r2,  r2,  #16
+        bgt             1b
+        bx              lr
+endfunc
+
+function ff_ac3_extract_exponents_neon, export=1
+        vmov.i32        q14, #24
+        vmov.i32        q15, #8
+1:
+        vld1.32         {q0},     [r1,:128]
+        vabs.s32        q1,  q0
+        vclz.i32        q3,  q1
+        vsub.i32        q3,  q3,  q15
+        vcge.s32        q2,  q3,  q14
+        vbit            q3,  q14, q2
+        vbic            q0,  q0,  q2
+        vmovn.i32       d6,  q3
+        vmovn.i16       d6,  q3
+        vst1.32         {q0},     [r1,:128]!
+        vst1.32         {d6[0]},  [r0,:32]!
+        subs            r2,  r2,  #4
+        bgt             1b
+        bx              lr
+endfunc
diff --git a/libavcodec/arm/asm-offsets.h b/libavcodec/arm/asm-offsets.h
new file mode 100644
index 0000000..43c1630
--- /dev/null
+++ b/libavcodec/arm/asm-offsets.h
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2010 Mans Rullgard
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_ARM_ASM_OFFSETS_H
+#define AVCODEC_ARM_ASM_OFFSETS_H
+
+#ifndef __ASSEMBLER__
+#include <stddef.h>
+#define CHK_OFFS(s, m, o) struct check_##o {    \
+        int x_##o[offsetof(s, m) == o? 1: -1];  \
+    }
+#endif
+
+/* MpegEncContext */
+#define Y_DC_SCALE               0xb4
+#define C_DC_SCALE               0xb8
+#define AC_PRED                  0xbc
+#define BLOCK_LAST_INDEX         0xc0
+#define H263_AIC                 0xf0
+#define INTER_SCANTAB_RASTER_END 0x138
+
+#endif
diff --git a/libavcodec/arm/asm.S b/libavcodec/arm/asm.S
index 17139b4..6e3d788 100644
--- a/libavcodec/arm/asm.S
+++ b/libavcodec/arm/asm.S
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2008 Mans Rullgard <mans at mansr.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -26,37 +26,59 @@
 #   define ELF @
 #endif
 
-        .macro require8, val=1
+.macro  require8 val=1
 ELF     .eabi_attribute 24, \val
-        .endm
+.endm
 
-        .macro preserve8, val=1
+.macro  preserve8 val=1
 ELF     .eabi_attribute 25, \val
-        .endm
+.endm
 
-        .macro function name, export=0
-        .macro endfunc
+.macro  function name, export=0
+    .macro endfunc
 ELF     .size   \name, . - \name
         .endfunc
         .purgem endfunc
-        .endm
-.if \export
+    .endm
+        .text
+    .if \export
         .global EXTERN_ASM\name
 EXTERN_ASM\name:
-.endif
+    .endif
 ELF     .type   \name, %function
         .func   \name
 \name:
-        .endm
+.endm
 
-        .macro movrel rd, val
-#if HAVE_ARMV6T2 && !CONFIG_PIC
+.macro  const   name, align=2
+    .macro endconst
+ELF     .size   \name, . - \name
+        .purgem endconst
+    .endm
+        .section        .rodata
+        .align          \align
+\name:
+.endm
+
+.macro  mov32   rd, val
+#if HAVE_ARMV6T2
+        movw            \rd, #(\val) & 0xffff
+    .if (\val) >> 16
+        movt            \rd, #(\val) >> 16
+    .endif
+#else
+        ldr             \rd, =\val
+#endif
+.endm
+
+.macro  movrel rd, val
+#if HAVE_ARMV6T2 && !CONFIG_PIC && !defined(__APPLE__)
         movw            \rd, #:lower16:\val
         movt            \rd, #:upper16:\val
 #else
         ldr             \rd, =\val
 #endif
-        .endm
+.endm
 
 #if HAVE_VFP_ARGS
         .eabi_attribute 28, 1
diff --git a/libavcodec/arm/dcadsp_init_arm.c b/libavcodec/arm/dcadsp_init_arm.c
index 816718d..b5ac206 100644
--- a/libavcodec/arm/dcadsp_init_arm.c
+++ b/libavcodec/arm/dcadsp_init_arm.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2010 Mans Rullgard <mans at mansr.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -23,7 +23,7 @@
 #include "libavcodec/dcadsp.h"
 
 void ff_dca_lfe_fir_neon(float *out, const float *in, const float *coefs,
-                         int decifactor, float scale, float bias);
+                         int decifactor, float scale);
 
 void av_cold ff_dcadsp_init_arm(DCADSPContext *s)
 {
diff --git a/libavcodec/arm/dcadsp_neon.S b/libavcodec/arm/dcadsp_neon.S
index 19960ab..6120836 100644
--- a/libavcodec/arm/dcadsp_neon.S
+++ b/libavcodec/arm/dcadsp_neon.S
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2010 Mans Rullgard <mans at mansr.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -29,7 +29,7 @@ function ff_dca_lfe_fir_neon, export=1
         cmp             r3,  #32
         moveq           r6,  #256/32
         movne           r6,  #256/64
-NOVFP   vldr            d0,  [sp, #16]          @ scale, bias
+NOVFP   vldr            s0,  [sp, #16]          @ scale
         mov             lr,  #-16
 1:
         vmov.f32        q2,  #0.0               @ v0
@@ -51,8 +51,7 @@ NOVFP   vldr            d0,  [sp, #16]          @ scale, bias
         vadd.f32        d4,  d4,  d5
         vadd.f32        d6,  d6,  d7
         vpadd.f32       d4,  d4,  d6
-        vdup.32         d5,  d0[1]
-        vmla.f32        d5,  d4,  d0[0]
+        vmul.f32        d5,  d4,  d0[0]
         vst1.32         {d5[0]},  [r0,:32]!
         vst1.32         {d5[1]},  [r4,:32]!
         bne             1b
diff --git a/libavcodec/arm/dsputil_arm.S b/libavcodec/arm/dsputil_arm.S
index 7ee85e8..2117628 100644
--- a/libavcodec/arm/dsputil_arm.S
+++ b/libavcodec/arm/dsputil_arm.S
@@ -2,20 +2,20 @@
 @ ARMv4 optimized DSP utils
 @ Copyright (c) 2004 AGAWA Koji <i (AT) atty (DOT) jp>
 @
-@ This file is part of FFmpeg.
+@ This file is part of Libav.
 @
-@ FFmpeg is free software; you can redistribute it and/or
+@ Libav is free software; you can redistribute it and/or
 @ modify it under the terms of the GNU Lesser General Public
 @ License as published by the Free Software Foundation; either
 @ version 2.1 of the License, or (at your option) any later version.
 @
-@ FFmpeg is distributed in the hope that it will be useful,
+@ Libav is distributed in the hope that it will be useful,
 @ but WITHOUT ANY WARRANTY; without even the implied warranty of
 @ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 @ Lesser General Public License for more details.
 @
 @ You should have received a copy of the GNU Lesser General Public
-@ License along with FFmpeg; if not, write to the Free Software
+@ License along with Libav; if not, write to the Free Software
 @ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 @
 
diff --git a/libavcodec/arm/dsputil_arm.h b/libavcodec/arm/dsputil_arm.h
index 7f8579d..14d9836 100644
--- a/libavcodec/arm/dsputil_arm.h
+++ b/libavcodec/arm/dsputil_arm.h
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2009 Mans Rullgard <mans at mansr.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/arm/dsputil_armv6.S b/libavcodec/arm/dsputil_armv6.S
index 214d947..8acb96d 100644
--- a/libavcodec/arm/dsputil_armv6.S
+++ b/libavcodec/arm/dsputil_armv6.S
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2009 Mans Rullgard <mans at mansr.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/arm/dsputil_init_arm.c b/libavcodec/arm/dsputil_init_arm.c
index c9c3351..92796c3 100644
--- a/libavcodec/arm/dsputil_init_arm.c
+++ b/libavcodec/arm/dsputil_init_arm.c
@@ -2,20 +2,20 @@
  * ARM optimized DSP utils
  * Copyright (c) 2001 Lionel Ulmer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -73,11 +73,6 @@ static void simple_idct_arm_add(uint8_t *dest, int line_size, DCTELEM *block)
     ff_add_pixels_clamped(block, dest, line_size);
 }
 
-int mm_support(void)
-{
-    return HAVE_IWMMXT * FF_MM_IWMMXT;
-}
-
 void dsputil_init_arm(DSPContext* c, AVCodecContext *avctx)
 {
     ff_put_pixels_clamped = c->put_pixels_clamped;
diff --git a/libavcodec/arm/dsputil_init_armv5te.c b/libavcodec/arm/dsputil_init_armv5te.c
index 750e514..572e06c 100644
--- a/libavcodec/arm/dsputil_init_armv5te.c
+++ b/libavcodec/arm/dsputil_init_armv5te.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2009 Mans Rullgard <mans at mansr.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/arm/dsputil_init_armv6.c b/libavcodec/arm/dsputil_init_armv6.c
index 3209062..362050c 100644
--- a/libavcodec/arm/dsputil_init_armv6.c
+++ b/libavcodec/arm/dsputil_init_armv6.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2009 Mans Rullgard <mans at mansr.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/arm/dsputil_init_neon.c b/libavcodec/arm/dsputil_init_neon.c
index 0e44160..cd58011 100644
--- a/libavcodec/arm/dsputil_init_neon.c
+++ b/libavcodec/arm/dsputil_init_neon.c
@@ -2,20 +2,20 @@
  * ARM NEON optimised DSP functions
  * Copyright (c) 2008 Mans Rullgard <mans at mansr.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -34,6 +34,9 @@ void ff_vp3_idct_put_neon(uint8_t *dest, int line_size, DCTELEM *data);
 void ff_vp3_idct_add_neon(uint8_t *dest, int line_size, DCTELEM *data);
 void ff_vp3_idct_dc_add_neon(uint8_t *dest, int line_size, const DCTELEM *data);
 
+void ff_clear_block_neon(DCTELEM *block);
+void ff_clear_blocks_neon(DCTELEM *blocks);
+
 void ff_put_pixels16_neon(uint8_t *, const uint8_t *, int, int);
 void ff_put_pixels16_x2_neon(uint8_t *, const uint8_t *, int, int);
 void ff_put_pixels16_y2_neon(uint8_t *, const uint8_t *, int, int);
@@ -135,10 +138,9 @@ void ff_avg_h264_chroma_mc2_neon(uint8_t *, uint8_t *, int, int, int, int);
 void ff_vp3_v_loop_filter_neon(uint8_t *, int, int *);
 void ff_vp3_h_loop_filter_neon(uint8_t *, int, int *);
 
-void ff_vector_fmul_neon(float *dst, const float *src, int len);
+void ff_vector_fmul_neon(float *dst, const float *src0, const float *src1, int len);
 void ff_vector_fmul_window_neon(float *dst, const float *src0,
-                                const float *src1, const float *win,
-                                float add_bias, int len);
+                                const float *src1, const float *win, int len);
 void ff_vector_fmul_scalar_neon(float *dst, const float *src, float mul,
                                 int len);
 void ff_vector_fmul_sv_scalar_2_neon(float *dst, const float *src,
@@ -151,8 +153,6 @@ void ff_sv_fmul_scalar_4_neon(float *dst, const float **vp, float mul,
                               int len);
 void ff_butterflies_float_neon(float *v1, float *v2, int len);
 float ff_scalarproduct_float_neon(const float *v1, const float *v2, int len);
-void ff_int32_to_float_fmul_scalar_neon(float *dst, const int *src,
-                                        float mul, int len);
 void ff_vector_fmul_reverse_neon(float *dst, const float *src0,
                                  const float *src1, int len);
 void ff_vector_fmul_add_neon(float *dst, const float *src0, const float *src1,
@@ -160,15 +160,16 @@ void ff_vector_fmul_add_neon(float *dst, const float *src0, const float *src1,
 
 void ff_vector_clipf_neon(float *dst, const float *src, float min, float max,
                           int len);
-void ff_float_to_int16_neon(int16_t *, const float *, long);
-void ff_float_to_int16_interleave_neon(int16_t *, const float **, long, int);
 
 void ff_vorbis_inverse_coupling_neon(float *mag, float *ang, int blocksize);
 
-int32_t ff_scalarproduct_int16_neon(int16_t *v1, int16_t *v2, int len,
+int32_t ff_scalarproduct_int16_neon(const int16_t *v1, const int16_t *v2, int len,
                                     int shift);
-int32_t ff_scalarproduct_and_madd_int16_neon(int16_t *v1, int16_t *v2,
-                                             int16_t *v3, int len, int mul);
+int32_t ff_scalarproduct_and_madd_int16_neon(int16_t *v1, const int16_t *v2,
+                                             const int16_t *v3, int len, int mul);
+
+void ff_apply_window_int16_neon(int16_t *dst, const int16_t *src,
+                                const int16_t *window, unsigned n);
 
 void ff_dsputil_init_neon(DSPContext *c, AVCodecContext *avctx)
 {
@@ -189,6 +190,9 @@ void ff_dsputil_init_neon(DSPContext *c, AVCodecContext *avctx)
         }
     }
 
+    c->clear_block  = ff_clear_block_neon;
+    c->clear_blocks = ff_clear_blocks_neon;
+
     c->put_pixels_tab[0][0] = ff_put_pixels16_neon;
     c->put_pixels_tab[0][1] = ff_put_pixels16_x2_neon;
     c->put_pixels_tab[0][2] = ff_put_pixels16_y2_neon;
@@ -303,7 +307,6 @@ void ff_dsputil_init_neon(DSPContext *c, AVCodecContext *avctx)
     c->vector_fmul_scalar         = ff_vector_fmul_scalar_neon;
     c->butterflies_float          = ff_butterflies_float_neon;
     c->scalarproduct_float        = ff_scalarproduct_float_neon;
-    c->int32_to_float_fmul_scalar = ff_int32_to_float_fmul_scalar_neon;
     c->vector_fmul_reverse        = ff_vector_fmul_reverse_neon;
     c->vector_fmul_add            = ff_vector_fmul_add_neon;
     c->vector_clipf               = ff_vector_clipf_neon;
@@ -314,14 +317,11 @@ void ff_dsputil_init_neon(DSPContext *c, AVCodecContext *avctx)
     c->sv_fmul_scalar[0] = ff_sv_fmul_scalar_2_neon;
     c->sv_fmul_scalar[1] = ff_sv_fmul_scalar_4_neon;
 
-    if (!(avctx->flags & CODEC_FLAG_BITEXACT)) {
-        c->float_to_int16            = ff_float_to_int16_neon;
-        c->float_to_int16_interleave = ff_float_to_int16_interleave_neon;
-    }
-
     if (CONFIG_VORBIS_DECODER)
         c->vorbis_inverse_coupling = ff_vorbis_inverse_coupling_neon;
 
     c->scalarproduct_int16 = ff_scalarproduct_int16_neon;
     c->scalarproduct_and_madd_int16 = ff_scalarproduct_and_madd_int16_neon;
+
+    c->apply_window_int16 = ff_apply_window_int16_neon;
 }
diff --git a/libavcodec/arm/dsputil_init_vfp.c b/libavcodec/arm/dsputil_init_vfp.c
index 9f8c1b7..3928911 100644
--- a/libavcodec/arm/dsputil_init_vfp.c
+++ b/libavcodec/arm/dsputil_init_vfp.c
@@ -1,36 +1,33 @@
 /*
  * Copyright (c) 2008 Siarhei Siamashka <ssvb at users.sourceforge.net>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "libavcodec/dsputil.h"
 #include "dsputil_arm.h"
 
-void ff_vector_fmul_vfp(float *dst, const float *src, int len);
+void ff_vector_fmul_vfp(float *dst, const float *src0,
+                        const float *src1, int len);
 void ff_vector_fmul_reverse_vfp(float *dst, const float *src0,
                                 const float *src1, int len);
-void ff_float_to_int16_vfp(int16_t *dst, const float *src, long len);
 
 void ff_dsputil_init_vfp(DSPContext* c, AVCodecContext *avctx)
 {
     c->vector_fmul = ff_vector_fmul_vfp;
     c->vector_fmul_reverse = ff_vector_fmul_reverse_vfp;
-#if HAVE_ARMV6
-    c->float_to_int16 = ff_float_to_int16_vfp;
-#endif
 }
diff --git a/libavcodec/arm/dsputil_iwmmxt.c b/libavcodec/arm/dsputil_iwmmxt.c
index 6a23732..e83edb5 100644
--- a/libavcodec/arm/dsputil_iwmmxt.c
+++ b/libavcodec/arm/dsputil_iwmmxt.c
@@ -2,23 +2,24 @@
  * iWMMXt optimized DSP utils
  * Copyright (c) 2004 AGAWA Koji
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/cpu.h"
 #include "libavcodec/dsputil.h"
 
 #define DEF(x, y) x ## _no_rnd_ ## y ##_iwmmxt
@@ -150,18 +151,19 @@ static void nop(uint8_t *block, const uint8_t *pixels, int line_size, int h)
 /* A run time test is not simple. If this file is compiled in
  * then we should install the functions
  */
-int mm_flags = FF_MM_IWMMXT; /* multimedia extension flags */
 
 void ff_dsputil_init_iwmmxt(DSPContext* c, AVCodecContext *avctx)
 {
+    int mm_flags = AV_CPU_FLAG_IWMMXT; /* multimedia extension flags */
+
     if (avctx->dsp_mask) {
-        if (avctx->dsp_mask & FF_MM_FORCE)
+        if (avctx->dsp_mask & AV_CPU_FLAG_FORCE)
             mm_flags |= (avctx->dsp_mask & 0xffff);
         else
             mm_flags &= ~(avctx->dsp_mask & 0xffff);
     }
 
-    if (!(mm_flags & FF_MM_IWMMXT)) return;
+    if (!(mm_flags & AV_CPU_FLAG_IWMMXT)) return;
 
     c->add_pixels_clamped = add_pixels_clamped_iwmmxt;
 
diff --git a/libavcodec/arm/dsputil_iwmmxt_rnd_template.c b/libavcodec/arm/dsputil_iwmmxt_rnd_template.c
index 35a5a9b..df0ead6 100644
--- a/libavcodec/arm/dsputil_iwmmxt_rnd_template.c
+++ b/libavcodec/arm/dsputil_iwmmxt_rnd_template.c
@@ -2,20 +2,20 @@
  * iWMMXt optimized DSP utils
  * copyright (c) 2004 AGAWA Koji
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/arm/dsputil_neon.S b/libavcodec/arm/dsputil_neon.S
index 722ed78..5b80e40 100644
--- a/libavcodec/arm/dsputil_neon.S
+++ b/libavcodec/arm/dsputil_neon.S
@@ -2,20 +2,20 @@
  * ARM NEON optimised DSP functions
  * Copyright (c) 2008 Mans Rullgard <mans at mansr.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,6 +25,22 @@
         preserve8
         .text
 
+function ff_clear_block_neon, export=1
+        vmov.i16        q0,  #0
+        .rept           8
+        vst1.16         {q0}, [r0,:128]!
+        .endr
+        bx              lr
+endfunc
+
+function ff_clear_blocks_neon, export=1
+        vmov.i16        q0,  #0
+        .rept           8*6
+        vst1.16         {q0}, [r0,:128]!
+        .endr
+        bx              lr
+endfunc
+
         .macro pixels16 avg=0
 .if \avg
         mov             ip,  r0
@@ -384,389 +400,48 @@ function ff_add_pixels_clamped_neon, export=1
         bx              lr
 endfunc
 
-function ff_float_to_int16_neon, export=1
-        subs            r2,  r2,  #8
-        vld1.64         {d0-d1},  [r1,:128]!
-        vcvt.s32.f32    q8,  q0,  #16
-        vld1.64         {d2-d3},  [r1,:128]!
-        vcvt.s32.f32    q9,  q1,  #16
-        beq             3f
-        bics            ip,  r2,  #15
-        beq             2f
-1:      subs            ip,  ip,  #16
-        vshrn.s32       d4,  q8,  #16
-        vld1.64         {d0-d1},  [r1,:128]!
-        vcvt.s32.f32    q0,  q0,  #16
-        vshrn.s32       d5,  q9,  #16
-        vld1.64         {d2-d3},  [r1,:128]!
-        vcvt.s32.f32    q1,  q1,  #16
-        vshrn.s32       d6,  q0,  #16
-        vst1.64         {d4-d5},  [r0,:128]!
-        vshrn.s32       d7,  q1,  #16
-        vld1.64         {d16-d17},[r1,:128]!
-        vcvt.s32.f32    q8,  q8,  #16
-        vld1.64         {d18-d19},[r1,:128]!
-        vcvt.s32.f32    q9,  q9,  #16
-        vst1.64         {d6-d7},  [r0,:128]!
-        bne             1b
-        ands            r2,  r2,  #15
-        beq             3f
-2:      vld1.64         {d0-d1},  [r1,:128]!
-        vshrn.s32       d4,  q8,  #16
-        vcvt.s32.f32    q0,  q0,  #16
-        vld1.64         {d2-d3},  [r1,:128]!
-        vshrn.s32       d5,  q9,  #16
-        vcvt.s32.f32    q1,  q1,  #16
-        vshrn.s32       d6,  q0,  #16
-        vst1.64         {d4-d5},  [r0,:128]!
-        vshrn.s32       d7,  q1,  #16
-        vst1.64         {d6-d7},  [r0,:128]!
-        bx              lr
-3:      vshrn.s32       d4,  q8,  #16
-        vshrn.s32       d5,  q9,  #16
-        vst1.64         {d4-d5},  [r0,:128]!
-        bx              lr
-endfunc
-
-function ff_float_to_int16_interleave_neon, export=1
-        cmp             r3, #2
-        ldrlt           r1, [r1]
-        blt             ff_float_to_int16_neon
-        bne             4f
-
-        ldr             r3, [r1]
-        ldr             r1, [r1, #4]
-
-        subs            r2,  r2,  #8
-        vld1.64         {d0-d1},  [r3,:128]!
-        vcvt.s32.f32    q8,  q0,  #16
-        vld1.64         {d2-d3},  [r3,:128]!
-        vcvt.s32.f32    q9,  q1,  #16
-        vld1.64         {d20-d21},[r1,:128]!
-        vcvt.s32.f32    q10, q10, #16
-        vld1.64         {d22-d23},[r1,:128]!
-        vcvt.s32.f32    q11, q11, #16
-        beq             3f
-        bics            ip,  r2,  #15
-        beq             2f
-1:      subs            ip,  ip,  #16
-        vld1.64         {d0-d1},  [r3,:128]!
-        vcvt.s32.f32    q0,  q0,  #16
-        vsri.32         q10, q8,  #16
-        vld1.64         {d2-d3},  [r3,:128]!
-        vcvt.s32.f32    q1,  q1,  #16
-        vld1.64         {d24-d25},[r1,:128]!
-        vcvt.s32.f32    q12, q12, #16
-        vld1.64         {d26-d27},[r1,:128]!
-        vsri.32         q11, q9,  #16
-        vst1.64         {d20-d21},[r0,:128]!
-        vcvt.s32.f32    q13, q13, #16
-        vst1.64         {d22-d23},[r0,:128]!
-        vsri.32         q12, q0,  #16
-        vld1.64         {d16-d17},[r3,:128]!
-        vsri.32         q13, q1,  #16
-        vst1.64         {d24-d25},[r0,:128]!
-        vcvt.s32.f32    q8,  q8,  #16
-        vld1.64         {d18-d19},[r3,:128]!
-        vcvt.s32.f32    q9,  q9,  #16
-        vld1.64         {d20-d21},[r1,:128]!
-        vcvt.s32.f32    q10, q10, #16
-        vld1.64         {d22-d23},[r1,:128]!
-        vcvt.s32.f32    q11, q11, #16
-        vst1.64         {d26-d27},[r0,:128]!
-        bne             1b
-        ands            r2,  r2,  #15
-        beq             3f
-2:      vsri.32         q10, q8,  #16
-        vld1.64         {d0-d1},  [r3,:128]!
-        vcvt.s32.f32    q0,  q0,  #16
-        vld1.64         {d2-d3},  [r3,:128]!
-        vcvt.s32.f32    q1,  q1,  #16
-        vld1.64         {d24-d25},[r1,:128]!
-        vcvt.s32.f32    q12, q12, #16
-        vsri.32         q11, q9,  #16
-        vld1.64         {d26-d27},[r1,:128]!
-        vcvt.s32.f32    q13, q13, #16
-        vst1.64         {d20-d21},[r0,:128]!
-        vsri.32         q12, q0,  #16
-        vst1.64         {d22-d23},[r0,:128]!
-        vsri.32         q13, q1,  #16
-        vst1.64         {d24-d27},[r0,:128]!
-        bx              lr
-3:      vsri.32         q10, q8,  #16
-        vsri.32         q11, q9,  #16
-        vst1.64         {d20-d23},[r0,:128]!
-        bx              lr
-
-4:      push            {r4-r8,lr}
-        cmp             r3,  #4
-        lsl             ip,  r3,  #1
-        blt             4f
-
-        @ 4 channels
-5:      ldmia           r1!, {r4-r7}
-        mov             lr,  r2
-        mov             r8,  r0
-        vld1.64         {d16-d17},[r4,:128]!
-        vcvt.s32.f32    q8,  q8,  #16
-        vld1.64         {d18-d19},[r5,:128]!
-        vcvt.s32.f32    q9,  q9,  #16
-        vld1.64         {d20-d21},[r6,:128]!
-        vcvt.s32.f32    q10, q10, #16
-        vld1.64         {d22-d23},[r7,:128]!
-        vcvt.s32.f32    q11, q11, #16
-6:      subs            lr,  lr,  #8
-        vld1.64         {d0-d1},  [r4,:128]!
-        vcvt.s32.f32    q0,  q0,  #16
-        vsri.32         q9,  q8,  #16
-        vld1.64         {d2-d3},  [r5,:128]!
-        vcvt.s32.f32    q1,  q1,  #16
-        vsri.32         q11, q10, #16
-        vld1.64         {d4-d5},  [r6,:128]!
-        vcvt.s32.f32    q2,  q2,  #16
-        vzip.32         d18, d22
-        vld1.64         {d6-d7},  [r7,:128]!
-        vcvt.s32.f32    q3,  q3,  #16
-        vzip.32         d19, d23
-        vst1.64         {d18},    [r8], ip
-        vsri.32         q1,  q0,  #16
-        vst1.64         {d22},    [r8], ip
-        vsri.32         q3,  q2,  #16
-        vst1.64         {d19},    [r8], ip
-        vzip.32         d2,  d6
-        vst1.64         {d23},    [r8], ip
-        vzip.32         d3,  d7
-        beq             7f
-        vld1.64         {d16-d17},[r4,:128]!
-        vcvt.s32.f32    q8,  q8,  #16
-        vst1.64         {d2},     [r8], ip
-        vld1.64         {d18-d19},[r5,:128]!
-        vcvt.s32.f32    q9,  q9,  #16
-        vst1.64         {d6},     [r8], ip
-        vld1.64         {d20-d21},[r6,:128]!
-        vcvt.s32.f32    q10, q10, #16
-        vst1.64         {d3},     [r8], ip
-        vld1.64         {d22-d23},[r7,:128]!
-        vcvt.s32.f32    q11, q11, #16
-        vst1.64         {d7},     [r8], ip
-        b               6b
-7:      vst1.64         {d2},     [r8], ip
-        vst1.64         {d6},     [r8], ip
-        vst1.64         {d3},     [r8], ip
-        vst1.64         {d7},     [r8], ip
-        subs            r3,  r3,  #4
-        popeq           {r4-r8,pc}
-        cmp             r3,  #4
-        add             r0,  r0,  #8
-        bge             5b
-
-        @ 2 channels
-4:      cmp             r3,  #2
-        blt             4f
-        ldmia           r1!, {r4-r5}
-        mov             lr,  r2
-        mov             r8,  r0
-        tst             lr,  #8
-        vld1.64         {d16-d17},[r4,:128]!
-        vcvt.s32.f32    q8,  q8,  #16
-        vld1.64         {d18-d19},[r5,:128]!
-        vcvt.s32.f32    q9,  q9,  #16
-        vld1.64         {d20-d21},[r4,:128]!
-        vcvt.s32.f32    q10, q10, #16
-        vld1.64         {d22-d23},[r5,:128]!
-        vcvt.s32.f32    q11, q11, #16
-        beq             6f
-        subs            lr,  lr,  #8
-        beq             7f
-        vsri.32         d18, d16, #16
-        vsri.32         d19, d17, #16
-        vld1.64         {d16-d17},[r4,:128]!
-        vcvt.s32.f32    q8,  q8,  #16
-        vst1.32         {d18[0]}, [r8], ip
-        vsri.32         d22, d20, #16
-        vst1.32         {d18[1]}, [r8], ip
-        vsri.32         d23, d21, #16
-        vst1.32         {d19[0]}, [r8], ip
-        vst1.32         {d19[1]}, [r8], ip
-        vld1.64         {d18-d19},[r5,:128]!
-        vcvt.s32.f32    q9,  q9,  #16
-        vst1.32         {d22[0]}, [r8], ip
-        vst1.32         {d22[1]}, [r8], ip
-        vld1.64         {d20-d21},[r4,:128]!
-        vcvt.s32.f32    q10, q10, #16
-        vst1.32         {d23[0]}, [r8], ip
-        vst1.32         {d23[1]}, [r8], ip
-        vld1.64         {d22-d23},[r5,:128]!
-        vcvt.s32.f32    q11, q11, #16
-6:      subs            lr,  lr,  #16
-        vld1.64         {d0-d1},  [r4,:128]!
-        vcvt.s32.f32    q0,  q0,  #16
-        vsri.32         d18, d16, #16
-        vld1.64         {d2-d3},  [r5,:128]!
-        vcvt.s32.f32    q1,  q1,  #16
-        vsri.32         d19, d17, #16
-        vld1.64         {d4-d5},  [r4,:128]!
-        vcvt.s32.f32    q2,  q2,  #16
-        vld1.64         {d6-d7},  [r5,:128]!
-        vcvt.s32.f32    q3,  q3,  #16
-        vst1.32         {d18[0]}, [r8], ip
-        vsri.32         d22, d20, #16
-        vst1.32         {d18[1]}, [r8], ip
-        vsri.32         d23, d21, #16
-        vst1.32         {d19[0]}, [r8], ip
-        vsri.32         d2,  d0,  #16
-        vst1.32         {d19[1]}, [r8], ip
-        vsri.32         d3,  d1,  #16
-        vst1.32         {d22[0]}, [r8], ip
-        vsri.32         d6,  d4,  #16
-        vst1.32         {d22[1]}, [r8], ip
-        vsri.32         d7,  d5,  #16
-        vst1.32         {d23[0]}, [r8], ip
-        vst1.32         {d23[1]}, [r8], ip
-        beq             6f
-        vld1.64         {d16-d17},[r4,:128]!
-        vcvt.s32.f32    q8,  q8,  #16
-        vst1.32         {d2[0]},  [r8], ip
-        vst1.32         {d2[1]},  [r8], ip
-        vld1.64         {d18-d19},[r5,:128]!
-        vcvt.s32.f32    q9,  q9,  #16
-        vst1.32         {d3[0]},  [r8], ip
-        vst1.32         {d3[1]},  [r8], ip
-        vld1.64         {d20-d21},[r4,:128]!
-        vcvt.s32.f32    q10, q10, #16
-        vst1.32         {d6[0]},  [r8], ip
-        vst1.32         {d6[1]},  [r8], ip
-        vld1.64         {d22-d23},[r5,:128]!
-        vcvt.s32.f32    q11, q11, #16
-        vst1.32         {d7[0]},  [r8], ip
-        vst1.32         {d7[1]},  [r8], ip
-        bgt             6b
-6:      vst1.32         {d2[0]},  [r8], ip
-        vst1.32         {d2[1]},  [r8], ip
-        vst1.32         {d3[0]},  [r8], ip
-        vst1.32         {d3[1]},  [r8], ip
-        vst1.32         {d6[0]},  [r8], ip
-        vst1.32         {d6[1]},  [r8], ip
-        vst1.32         {d7[0]},  [r8], ip
-        vst1.32         {d7[1]},  [r8], ip
-        b               8f
-7:      vsri.32         d18, d16, #16
-        vsri.32         d19, d17, #16
-        vst1.32         {d18[0]}, [r8], ip
-        vsri.32         d22, d20, #16
-        vst1.32         {d18[1]}, [r8], ip
-        vsri.32         d23, d21, #16
-        vst1.32         {d19[0]}, [r8], ip
-        vst1.32         {d19[1]}, [r8], ip
-        vst1.32         {d22[0]}, [r8], ip
-        vst1.32         {d22[1]}, [r8], ip
-        vst1.32         {d23[0]}, [r8], ip
-        vst1.32         {d23[1]}, [r8], ip
-8:      subs            r3,  r3,  #2
-        add             r0,  r0,  #4
-        popeq           {r4-r8,pc}
-
-        @ 1 channel
-4:      ldr             r4,  [r1],#4
-        tst             r2,  #8
-        mov             lr,  r2
-        mov             r5,  r0
-        vld1.64         {d0-d1},  [r4,:128]!
-        vcvt.s32.f32    q0,  q0,  #16
-        vld1.64         {d2-d3},  [r4,:128]!
-        vcvt.s32.f32    q1,  q1,  #16
-        bne             8f
-6:      subs            lr,  lr,  #16
-        vld1.64         {d4-d5},  [r4,:128]!
-        vcvt.s32.f32    q2,  q2,  #16
-        vld1.64         {d6-d7},  [r4,:128]!
-        vcvt.s32.f32    q3,  q3,  #16
-        vst1.16         {d0[1]},  [r5,:16], ip
-        vst1.16         {d0[3]},  [r5,:16], ip
-        vst1.16         {d1[1]},  [r5,:16], ip
-        vst1.16         {d1[3]},  [r5,:16], ip
-        vst1.16         {d2[1]},  [r5,:16], ip
-        vst1.16         {d2[3]},  [r5,:16], ip
-        vst1.16         {d3[1]},  [r5,:16], ip
-        vst1.16         {d3[3]},  [r5,:16], ip
-        beq             7f
-        vld1.64         {d0-d1},  [r4,:128]!
-        vcvt.s32.f32    q0,  q0,  #16
-        vld1.64         {d2-d3},  [r4,:128]!
-        vcvt.s32.f32    q1,  q1,  #16
-7:      vst1.16         {d4[1]},  [r5,:16], ip
-        vst1.16         {d4[3]},  [r5,:16], ip
-        vst1.16         {d5[1]},  [r5,:16], ip
-        vst1.16         {d5[3]},  [r5,:16], ip
-        vst1.16         {d6[1]},  [r5,:16], ip
-        vst1.16         {d6[3]},  [r5,:16], ip
-        vst1.16         {d7[1]},  [r5,:16], ip
-        vst1.16         {d7[3]},  [r5,:16], ip
-        bgt             6b
-        pop             {r4-r8,pc}
-8:      subs            lr,  lr,  #8
-        vst1.16         {d0[1]},  [r5,:16], ip
-        vst1.16         {d0[3]},  [r5,:16], ip
-        vst1.16         {d1[1]},  [r5,:16], ip
-        vst1.16         {d1[3]},  [r5,:16], ip
-        vst1.16         {d2[1]},  [r5,:16], ip
-        vst1.16         {d2[3]},  [r5,:16], ip
-        vst1.16         {d3[1]},  [r5,:16], ip
-        vst1.16         {d3[3]},  [r5,:16], ip
-        popeq           {r4-r8,pc}
-        vld1.64         {d0-d1},  [r4,:128]!
-        vcvt.s32.f32    q0,  q0,  #16
-        vld1.64         {d2-d3},  [r4,:128]!
-        vcvt.s32.f32    q1,  q1,  #16
-        b               6b
-endfunc
-
 function ff_vector_fmul_neon, export=1
-        mov             r3,  r0
-        subs            r2,  r2,  #8
-        vld1.64         {d0-d3},  [r0,:128]!
-        vld1.64         {d4-d7},  [r1,:128]!
+        subs            r3,  r3,  #8
+        vld1.64         {d0-d3},  [r1,:128]!
+        vld1.64         {d4-d7},  [r2,:128]!
         vmul.f32        q8,  q0,  q2
         vmul.f32        q9,  q1,  q3
         beq             3f
-        bics            ip,  r2,  #15
+        bics            ip,  r3,  #15
         beq             2f
 1:      subs            ip,  ip,  #16
-        vld1.64         {d0-d1},  [r0,:128]!
-        vld1.64         {d4-d5},  [r1,:128]!
+        vld1.64         {d0-d1},  [r1,:128]!
+        vld1.64         {d4-d5},  [r2,:128]!
         vmul.f32        q10, q0,  q2
-        vld1.64         {d2-d3},  [r0,:128]!
-        vld1.64         {d6-d7},  [r1,:128]!
+        vld1.64         {d2-d3},  [r1,:128]!
+        vld1.64         {d6-d7},  [r2,:128]!
         vmul.f32        q11, q1,  q3
-        vst1.64         {d16-d19},[r3,:128]!
-        vld1.64         {d0-d1},  [r0,:128]!
-        vld1.64         {d4-d5},  [r1,:128]!
+        vst1.64         {d16-d19},[r0,:128]!
+        vld1.64         {d0-d1},  [r1,:128]!
+        vld1.64         {d4-d5},  [r2,:128]!
         vmul.f32        q8,  q0,  q2
-        vld1.64         {d2-d3},  [r0,:128]!
-        vld1.64         {d6-d7},  [r1,:128]!
+        vld1.64         {d2-d3},  [r1,:128]!
+        vld1.64         {d6-d7},  [r2,:128]!
         vmul.f32        q9,  q1,  q3
-        vst1.64         {d20-d23},[r3,:128]!
+        vst1.64         {d20-d23},[r0,:128]!
         bne             1b
-        ands            r2,  r2,  #15
+        ands            r3,  r3,  #15
         beq             3f
-2:      vld1.64         {d0-d1},  [r0,:128]!
-        vld1.64         {d4-d5},  [r1,:128]!
-        vst1.64         {d16-d17},[r3,:128]!
+2:      vld1.64         {d0-d1},  [r1,:128]!
+        vld1.64         {d4-d5},  [r2,:128]!
+        vst1.64         {d16-d17},[r0,:128]!
         vmul.f32        q8,  q0,  q2
-        vld1.64         {d2-d3},  [r0,:128]!
-        vld1.64         {d6-d7},  [r1,:128]!
-        vst1.64         {d18-d19},[r3,:128]!
+        vld1.64         {d2-d3},  [r1,:128]!
+        vld1.64         {d6-d7},  [r2,:128]!
+        vst1.64         {d18-d19},[r0,:128]!
         vmul.f32        q9,  q1,  q3
-3:      vst1.64         {d16-d19},[r3,:128]!
+3:      vst1.64         {d16-d19},[r0,:128]!
         bx              lr
 endfunc
 
 function ff_vector_fmul_window_neon, export=1
-VFP     vdup.32         q8,  d0[0]
-NOVFP   vld1.32         {d16[],d17[]}, [sp,:32]
         push            {r4,r5,lr}
-VFP     ldr             lr,  [sp, #12]
-NOVFP   ldr             lr,  [sp, #16]
+        ldr             lr,  [sp, #12]
         sub             r2,  r2,  #8
         sub             r5,  lr,  #2
         add             r2,  r2,  r5, lsl #2
@@ -778,14 +453,12 @@ NOVFP   ldr             lr,  [sp, #16]
         vld1.64         {d4,d5},  [r3,:128]!
         vld1.64         {d6,d7},  [r4,:128], r5
 1:      subs            lr,  lr,  #4
-        vmov            q11, q8
-        vmla.f32        d22, d0,  d4
-        vmov            q10, q8
-        vmla.f32        d23, d1,  d5
+        vmul.f32        d22, d0,  d4
         vrev64.32       q3,  q3
-        vmla.f32        d20, d0,  d7
+        vmul.f32        d23, d1,  d5
         vrev64.32       q1,  q1
-        vmla.f32        d21, d1,  d6
+        vmul.f32        d20, d0,  d7
+        vmul.f32        d21, d1,  d6
         beq             2f
         vmla.f32        d22, d3,  d7
         vld1.64         {d0,d1},  [r1,:128]!
@@ -1040,34 +713,6 @@ NOVFP   vmov.32         r0,  d0[0]
         bx              lr
 endfunc
 
-function ff_int32_to_float_fmul_scalar_neon, export=1
-VFP     vdup.32         q0,  d0[0]
-VFP     len     .req    r2
-NOVFP   vdup.32         q0,  r2
-NOVFP   len     .req    r3
-
-        vld1.32         {q1},[r1,:128]!
-        vcvt.f32.s32    q3,  q1
-        vld1.32         {q2},[r1,:128]!
-        vcvt.f32.s32    q8,  q2
-1:      subs            len, len, #8
-        pld             [r1, #16]
-        vmul.f32        q9,  q3,  q0
-        vmul.f32        q10, q8,  q0
-        beq             2f
-        vld1.32         {q1},[r1,:128]!
-        vcvt.f32.s32    q3,  q1
-        vld1.32         {q2},[r1,:128]!
-        vcvt.f32.s32    q8,  q2
-        vst1.32         {q9}, [r0,:128]!
-        vst1.32         {q10},[r0,:128]!
-        b               1b
-2:      vst1.32         {q9}, [r0,:128]!
-        vst1.32         {q10},[r0,:128]!
-        bx              lr
-        .unreq  len
-endfunc
-
 function ff_vector_fmul_reverse_neon, export=1
         add             r2,  r2,  r3,  lsl #2
         sub             r2,  r2,  #32
@@ -1144,3 +789,26 @@ NOVFP   ldr             r2,  [sp]
         vst1.f32        {q9},[r0,:128]!
         bx              lr
 endfunc
+
+function ff_apply_window_int16_neon, export=1
+        push            {r4,lr}
+        add             r4,  r1,  r3,  lsl #1
+        add             lr,  r0,  r3,  lsl #1
+        sub             r4,  r4,  #16
+        sub             lr,  lr,  #16
+        mov             r12, #-16
+1:
+        vld1.16         {q0},     [r1,:128]!
+        vld1.16         {q2},     [r2,:128]!
+        vld1.16         {q1},     [r4,:128], r12
+        vrev64.16       q3,  q2
+        vqrdmulh.s16    q0,  q0,  q2
+        vqrdmulh.s16    d2,  d2,  d7
+        vqrdmulh.s16    d3,  d3,  d6
+        vst1.16         {q0},     [r0,:128]!
+        vst1.16         {q1},     [lr,:128], r12
+        subs            r3,  r3,  #16
+        bgt             1b
+
+        pop             {r4,pc}
+endfunc
diff --git a/libavcodec/arm/dsputil_vfp.S b/libavcodec/arm/dsputil_vfp.S
index b704ba9..b41db03 100644
--- a/libavcodec/arm/dsputil_vfp.S
+++ b/libavcodec/arm/dsputil_vfp.S
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2008 Siarhei Siamashka <ssvb at users.sourceforge.net>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -41,34 +41,33 @@
  * ARM VFP optimized implementation of 'vector_fmul_c' function.
  * Assume that len is a positive number and is multiple of 8
  */
-@ void ff_vector_fmul_vfp(float *dst, const float *src, int len)
+@ void ff_vector_fmul_vfp(float *dst, const float *src0, const float *src1, int len)
 function ff_vector_fmul_vfp, export=1
         vpush           {d8-d15}
-        mov             r3,  r0
         fmrx            r12, fpscr
         orr             r12, r12, #(3 << 16) /* set vector size to 4 */
         fmxr            fpscr, r12
 
-        vldmia          r3!, {s0-s3}
-        vldmia          r1!, {s8-s11}
-        vldmia          r3!, {s4-s7}
-        vldmia          r1!, {s12-s15}
+        vldmia          r1!, {s0-s3}
+        vldmia          r2!, {s8-s11}
+        vldmia          r1!, {s4-s7}
+        vldmia          r2!, {s12-s15}
         vmul.f32        s8,  s0,  s8
 1:
-        subs            r2,  r2,  #16
+        subs            r3,  r3,  #16
         vmul.f32        s12, s4,  s12
-        vldmiage        r3!, {s16-s19}
-        vldmiage        r1!, {s24-s27}
-        vldmiage        r3!, {s20-s23}
-        vldmiage        r1!, {s28-s31}
+        vldmiage        r1!, {s16-s19}
+        vldmiage        r2!, {s24-s27}
+        vldmiage        r1!, {s20-s23}
+        vldmiage        r2!, {s28-s31}
         vmulge.f32      s24, s16, s24
         vstmia          r0!, {s8-s11}
         vstmia          r0!, {s12-s15}
         vmulge.f32      s28, s20, s28
-        vldmiagt        r3!, {s0-s3}
-        vldmiagt        r1!, {s8-s11}
-        vldmiagt        r3!, {s4-s7}
-        vldmiagt        r1!, {s12-s15}
+        vldmiagt        r1!, {s0-s3}
+        vldmiagt        r2!, {s8-s11}
+        vldmiagt        r1!, {s4-s7}
+        vldmiagt        r2!, {s12-s15}
         vmulge.f32      s8,  s0,  s8
         vstmiage        r0!, {s24-s27}
         vstmiage        r0!, {s28-s31}
@@ -132,58 +131,3 @@ function ff_vector_fmul_reverse_vfp, export=1
         vpop            {d8-d15}
         bx              lr
 endfunc
-
-#if HAVE_ARMV6
-/**
- * ARM VFP optimized float to int16 conversion.
- * Assume that len is a positive number and is multiple of 8, destination
- * buffer is at least 4 bytes aligned (8 bytes alignment is better for
- * performance), little endian byte sex
- */
-@ void ff_float_to_int16_vfp(int16_t *dst, const float *src, int len)
-function ff_float_to_int16_vfp, export=1
-        push            {r4-r8,lr}
-        vpush           {d8-d11}
-        vldmia          r1!, {s16-s23}
-        vcvt.s32.f32    s0,  s16
-        vcvt.s32.f32    s1,  s17
-        vcvt.s32.f32    s2,  s18
-        vcvt.s32.f32    s3,  s19
-        vcvt.s32.f32    s4,  s20
-        vcvt.s32.f32    s5,  s21
-        vcvt.s32.f32    s6,  s22
-        vcvt.s32.f32    s7,  s23
-1:
-        subs            r2,  r2,  #8
-        vmov            r3,  r4,  s0, s1
-        vmov            r5,  r6,  s2, s3
-        vmov            r7,  r8,  s4, s5
-        vmov            ip,  lr,  s6, s7
-        vldmiagt        r1!, {s16-s23}
-        ssat            r4,  #16, r4
-        ssat            r3,  #16, r3
-        ssat            r6,  #16, r6
-        ssat            r5,  #16, r5
-        pkhbt           r3,  r3,  r4, lsl #16
-        pkhbt           r4,  r5,  r6, lsl #16
-        vcvtgt.s32.f32  s0,  s16
-        vcvtgt.s32.f32  s1,  s17
-        vcvtgt.s32.f32  s2,  s18
-        vcvtgt.s32.f32  s3,  s19
-        vcvtgt.s32.f32  s4,  s20
-        vcvtgt.s32.f32  s5,  s21
-        vcvtgt.s32.f32  s6,  s22
-        vcvtgt.s32.f32  s7,  s23
-        ssat            r8,  #16, r8
-        ssat            r7,  #16, r7
-        ssat            lr,  #16, lr
-        ssat            ip,  #16, ip
-        pkhbt           r5,  r7,  r8, lsl #16
-        pkhbt           r6,  ip,  lr, lsl #16
-        stmia           r0!, {r3-r6}
-        bgt             1b
-
-        vpop            {d8-d11}
-        pop             {r4-r8,pc}
-endfunc
-#endif
diff --git a/libavcodec/arm/fft_fixed_init_arm.c b/libavcodec/arm/fft_fixed_init_arm.c
new file mode 100644
index 0000000..be412cd
--- /dev/null
+++ b/libavcodec/arm/fft_fixed_init_arm.c
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2009 Mans Rullgard <mans at mansr.com>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#define CONFIG_FFT_FLOAT 0
+#include "libavcodec/fft.h"
+
+void ff_fft_fixed_calc_neon(FFTContext *s, FFTComplex *z);
+void ff_mdct_fixed_calc_neon(FFTContext *s, FFTSample *o, const FFTSample *i);
+void ff_mdct_fixed_calcw_neon(FFTContext *s, FFTDouble *o, const FFTSample *i);
+
+av_cold void ff_fft_fixed_init_arm(FFTContext *s)
+{
+    if (HAVE_NEON) {
+        s->fft_permutation = FF_FFT_PERM_SWAP_LSBS;
+        s->fft_calc        = ff_fft_fixed_calc_neon;
+
+#if CONFIG_MDCT
+        if (!s->inverse && s->mdct_bits >= 5) {
+            s->mdct_permutation = FF_MDCT_PERM_INTERLEAVE;
+            s->mdct_calc        = ff_mdct_fixed_calc_neon;
+            s->mdct_calcw       = ff_mdct_fixed_calcw_neon;
+        }
+#endif
+    }
+}
diff --git a/libavcodec/arm/fft_fixed_neon.S b/libavcodec/arm/fft_fixed_neon.S
new file mode 100644
index 0000000..14884d3
--- /dev/null
+++ b/libavcodec/arm/fft_fixed_neon.S
@@ -0,0 +1,261 @@
+/*
+ * Copyright (c) 2011 Mans Rullgard <mans at mansr.com>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "asm.S"
+
+.macro  bflies          d0,  d1,  r0,  r1
+        vrev64.32       \r0, \d1                @ t5, t6, t1, t2
+        vhsub.s16       \r1, \d1, \r0           @ t1-t5, t2-t6, t5-t1, t6-t2
+        vhadd.s16       \r0, \d1, \r0           @ t1+t5, t2+t6, t5+t1, t6+t2
+        vext.16         \r1, \r1, \r1, #1       @ t2-t6, t5-t1, t6-t2, t1-t5
+        vtrn.32         \r0, \r1                @ t1+t5, t2+t6, t2-t6, t5-t1
+                                                @ t5,    t6,    t4,    t3
+        vhsub.s16       \d1, \d0, \r0
+        vhadd.s16       \d0, \d0, \r0
+.endm
+
+.macro  transform01     q0,  q1,  d3,  c0,  c1,  r0,  w0,  w1
+        vrev32.16       \r0, \d3
+        vmull.s16       \w0, \d3, \c0
+        vmlal.s16       \w0, \r0, \c1
+        vshrn.s32       \d3, \w0, #15
+        bflies          \q0, \q1, \w0, \w1
+.endm
+
+.macro  transform2      d0,  d1,  d2,  d3,  q0,  q1,  c0,  c1,  c2,  c3, \
+                        r0,  r1,  w0,  w1
+        vrev32.16       \r0, \d1
+        vrev32.16       \r1, \d3
+        vmull.s16       \w0, \d1, \c0
+        vmlal.s16       \w0, \r0, \c1
+        vmull.s16       \w1, \d3, \c2
+        vmlal.s16       \w1, \r1, \c3
+        vshrn.s32       \d1, \w0, #15
+        vshrn.s32       \d3, \w1, #15
+        bflies          \q0, \q1, \w0, \w1
+.endm
+
+.macro  fft4            d0,  d1,  r0,  r1
+        vhsub.s16       \r0, \d0, \d1           @ t3, t4, t8, t7
+        vhsub.s16       \r1, \d1, \d0
+        vhadd.s16       \d0, \d0, \d1           @ t1, t2, t6, t5
+        vmov.i64        \d1, #0xffff<<32
+        vbit            \r0, \r1, \d1
+        vrev64.16       \r1, \r0                @ t7, t8, t4, t3
+        vtrn.32         \r0, \r1                @ t3, t4, t7, t8
+        vtrn.32         \d0, \r0                @ t1, t2, t3, t4, t6, t5, t8, t7
+        vhsub.s16       \d1, \d0, \r0           @ r2, i2, r3, i1
+        vhadd.s16       \d0, \d0, \r0           @ r0, i0, r1, i3
+.endm
+
+.macro  fft8            d0,  d1,  d2,  d3,  q0,  q1,  c0,  c1,  r0,  r1, w0, w1
+        fft4            \d0, \d1, \r0, \r1
+        vtrn.32         \d0, \d1                @ z0, z2, z1, z3
+        vhadd.s16       \r0, \d2, \d3           @ t1, t2, t3, t4
+        vhsub.s16       \d3, \d2, \d3           @ z5, z7
+        vmov            \d2, \r0
+        transform01     \q0, \q1, \d3, \c0, \c1, \r0, \w0, \w1
+.endm
+
+function fft4_neon
+        vld1.16         {d0-d1},  [r0,:128]
+        fft4            d0,  d1,  d2,  d3
+        vst1.16         {d0-d1},  [r0,:128]
+        bx              lr
+endfunc
+
+function fft8_neon
+        vld1.16         {d0-d3},  [r0,:128]
+        movrel          r1,  coefs
+        vld1.16         {d30},    [r1,:64]
+        vdup.16         d31, d30[0]
+        fft8            d0,  d1,  d2,  d3,  q0,  q1,  d31, d30, d20, d21, q8, q9
+        vtrn.32         d0,  d1
+        vtrn.32         d2,  d3
+        vst1.16         {d0-d3},  [r0,:128]
+        bx              lr
+endfunc
+
+function fft16_neon
+        vld1.16         {d0-d3},  [r0,:128]!
+        vld1.16         {d4-d7},  [r0,:128]
+        movrel          r1,  coefs
+        sub             r0,  r0,  #32
+        vld1.16         {d28-d31},[r1,:128]
+        vdup.16         d31, d28[0]
+        fft8            d0,  d1,  d2,  d3,  q0,  q1,  d31, d28, d20, d21, q8, q9
+        vswp            d5,  d6
+        fft4            q2,  q3,  q8,  q9
+        vswp            d5,  d6
+        vtrn.32         q0,  q1             @ z0, z4, z2, z6, z1, z5, z3, z7
+        vtrn.32         q2,  q3             @ z8, z12,z10,z14,z9, z13,z11,z15
+        vswp            d1,  d2
+        vdup.16         d31, d28[0]
+        transform01     q0,  q2,  d5,  d31, d28, d20, q8, q9
+        vdup.16         d26, d29[0]
+        vdup.16         d27, d30[0]
+        transform2      d2,  d6,  d3,  d7,  q1,  q3,  d26, d30, d27, d29, \
+                        d20, d21, q8,  q9
+        vtrn.32         q0,  q1
+        vtrn.32         q2,  q3
+        vst1.16         {d0-d3},  [r0,:128]!
+        vst1.16         {d4-d7},  [r0,:128]
+        bx              lr
+endfunc
+
+function fft_pass_neon
+        push            {r4,lr}
+        movrel          lr,  coefs + 24
+        vld1.16         {d30},    [lr,:64]
+        lsl             r12, r2,  #3
+        vmov            d31, d30
+        add             r3,  r1,  r2,  lsl #2
+        mov             lr,  #-8
+        sub             r3,  r3,  #2
+        mov             r4,  r0
+        vld1.16         {d27[]},  [r3,:16]
+        sub             r3,  r3,  #6
+        vld1.16         {q0},     [r4,:128], r12
+        vld1.16         {q1},     [r4,:128], r12
+        vld1.16         {q2},     [r4,:128], r12
+        vld1.16         {q3},     [r4,:128], r12
+        vld1.16         {d28},    [r1,:64]!
+        vld1.16         {d29},    [r3,:64], lr
+        vswp            d1,  d2
+        vswp            d5,  d6
+        vtrn.32         d0,  d1
+        vtrn.32         d4,  d5
+        vdup.16         d25, d28[1]
+        vmul.s16        d27, d27, d31
+        transform01     q0,  q2,  d5,  d25, d27, d20, q8,  q9
+        b               2f
+1:
+        mov             r4,  r0
+        vdup.16         d26, d29[0]
+        vld1.16         {q0},     [r4,:128], r12
+        vld1.16         {q1},     [r4,:128], r12
+        vld1.16         {q2},     [r4,:128], r12
+        vld1.16         {q3},     [r4,:128], r12
+        vld1.16         {d28},    [r1,:64]!
+        vld1.16         {d29},    [r3,:64], lr
+        vswp            d1,  d2
+        vswp            d5,  d6
+        vtrn.32         d0,  d1
+        vtrn.32         d4,  d5
+        vdup.16         d24, d28[0]
+        vdup.16         d25, d28[1]
+        vdup.16         d27, d29[3]
+        vmul.s16        q13, q13, q15
+        transform2      d0,  d4,  d1,  d5,  q0,  q2,  d24, d26, d25, d27, \
+                        d16, d17, q9,  q10
+2:
+        vtrn.32         d2,  d3
+        vtrn.32         d6,  d7
+        vdup.16         d24, d28[2]
+        vdup.16         d26, d29[2]
+        vdup.16         d25, d28[3]
+        vdup.16         d27, d29[1]
+        vmul.s16        q13, q13, q15
+        transform2      d2,  d6,  d3,  d7,  q1,  q3,  d24, d26, d25, d27, \
+                        d16, d17, q9,  q10
+        vtrn.32         d0,  d1
+        vtrn.32         d2,  d3
+        vtrn.32         d4,  d5
+        vtrn.32         d6,  d7
+        vswp            d1,  d2
+        vswp            d5,  d6
+        mov             r4,  r0
+        vst1.16         {q0},     [r4,:128], r12
+        vst1.16         {q1},     [r4,:128], r12
+        vst1.16         {q2},     [r4,:128], r12
+        vst1.16         {q3},     [r4,:128], r12
+        add             r0,  r0,  #16
+        subs            r2,  r2,  #2
+        bgt             1b
+        pop             {r4,pc}
+endfunc
+
+#define F_SQRT1_2   23170
+#define F_COS_16_1  30274
+#define F_COS_16_3  12540
+
+const   coefs, align=4
+        .short          F_SQRT1_2, -F_SQRT1_2, -F_SQRT1_2,  F_SQRT1_2
+        .short          F_COS_16_1,-F_COS_16_1,-F_COS_16_1, F_COS_16_1
+        .short          F_COS_16_3,-F_COS_16_3,-F_COS_16_3, F_COS_16_3
+        .short          1,         -1,         -1,          1
+endconst
+
+.macro  def_fft n, n2, n4
+function fft\n\()_neon
+        push            {r4, lr}
+        mov             r4,  r0
+        bl              fft\n2\()_neon
+        add             r0,  r4,  #\n4*2*4
+        bl              fft\n4\()_neon
+        add             r0,  r4,  #\n4*3*4
+        bl              fft\n4\()_neon
+        mov             r0,  r4
+        pop             {r4, lr}
+        movrel          r1,  X(ff_cos_\n\()_fixed)
+        mov             r2,  #\n4/2
+        b               fft_pass_neon
+endfunc
+.endm
+
+        def_fft    32,    16,     8
+        def_fft    64,    32,    16
+        def_fft   128,    64,    32
+        def_fft   256,   128,    64
+        def_fft   512,   256,   128
+        def_fft  1024,   512,   256
+        def_fft  2048,  1024,   512
+        def_fft  4096,  2048,  1024
+        def_fft  8192,  4096,  2048
+        def_fft 16384,  8192,  4096
+        def_fft 32768, 16384,  8192
+        def_fft 65536, 32768, 16384
+
+function ff_fft_fixed_calc_neon, export=1
+        ldr             r2,  [r0]
+        sub             r2,  r2,  #2
+        movrel          r3,  fft_fixed_tab_neon
+        ldr             r3,  [r3, r2, lsl #2]
+        mov             r0,  r1
+        bx              r3
+endfunc
+
+const   fft_fixed_tab_neon
+        .word fft4_neon
+        .word fft8_neon
+        .word fft16_neon
+        .word fft32_neon
+        .word fft64_neon
+        .word fft128_neon
+        .word fft256_neon
+        .word fft512_neon
+        .word fft1024_neon
+        .word fft2048_neon
+        .word fft4096_neon
+        .word fft8192_neon
+        .word fft16384_neon
+        .word fft32768_neon
+        .word fft65536_neon
+endconst
diff --git a/libavcodec/arm/fft_init_arm.c b/libavcodec/arm/fft_init_arm.c
index bde1240..4ee4909 100644
--- a/libavcodec/arm/fft_init_arm.c
+++ b/libavcodec/arm/fft_init_arm.c
@@ -1,24 +1,25 @@
 /*
  * Copyright (c) 2009 Mans Rullgard <mans at mansr.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "libavcodec/fft.h"
+#include "libavcodec/rdft.h"
 #include "libavcodec/synth_filter.h"
 
 void ff_fft_permute_neon(FFTContext *s, FFTComplex *z);
@@ -34,7 +35,7 @@ void ff_synth_filter_float_neon(FFTContext *imdct,
                                 float *synth_buf_ptr, int *synth_buf_offset,
                                 float synth_buf2[32], const float window[512],
                                 float out[32], const float in[32],
-                                float scale, float bias);
+                                float scale);
 
 av_cold void ff_fft_init_arm(FFTContext *s)
 {
@@ -44,7 +45,7 @@ av_cold void ff_fft_init_arm(FFTContext *s)
         s->imdct_calc   = ff_imdct_calc_neon;
         s->imdct_half   = ff_imdct_half_neon;
         s->mdct_calc    = ff_mdct_calc_neon;
-        s->permutation  = FF_MDCT_PERM_INTERLEAVE;
+        s->mdct_permutation = FF_MDCT_PERM_INTERLEAVE;
     }
 }
 
diff --git a/libavcodec/arm/fft_neon.S b/libavcodec/arm/fft_neon.S
index 08589db..8876218 100644
--- a/libavcodec/arm/fft_neon.S
+++ b/libavcodec/arm/fft_neon.S
@@ -4,20 +4,23 @@
  * Copyright (c) 2009 Mans Rullgard <mans at mansr.com>
  * Copyright (c) 2009 Naotoshi Nojiri
  *
- * This file is part of FFmpeg.
+ * This algorithm (though not any of the implementation details) is
+ * based on libdjbfft by D. J. Bernstein.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -320,7 +323,7 @@ function ff_fft_permute_neon, export=1
         push            {r4,lr}
         mov             r12, #1
         ldr             r2,  [r0]       @ nbits
-        ldr             r3,  [r0, #20]  @ tmp_buf
+        ldr             r3,  [r0, #12]  @ tmp_buf
         ldr             r0,  [r0, #8]   @ revtab
         lsl             r12, r12, r2
         mov             r2,  r12
@@ -364,7 +367,7 @@ fft_tab_neon:
         .word fft16384_neon
         .word fft32768_neon
         .word fft65536_neon
-        .size fft_tab_neon, . - fft_tab_neon
+ELF     .size fft_tab_neon, . - fft_tab_neon
 
         .align 4
 pmmp:   .float  +1.0, -1.0, -1.0, +1.0
diff --git a/libavcodec/arm/fmtconvert_init_arm.c b/libavcodec/arm/fmtconvert_init_arm.c
new file mode 100644
index 0000000..92e07f1
--- /dev/null
+++ b/libavcodec/arm/fmtconvert_init_arm.c
@@ -0,0 +1,48 @@
+/*
+ * ARM optimized Format Conversion Utils
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <stdint.h>
+
+#include "libavcodec/avcodec.h"
+#include "libavcodec/fmtconvert.h"
+
+void ff_int32_to_float_fmul_scalar_neon(float *dst, const int *src,
+                                        float mul, int len);
+
+void ff_float_to_int16_neon(int16_t *dst, const float *src, long len);
+void ff_float_to_int16_interleave_neon(int16_t *, const float **, long, int);
+
+void ff_float_to_int16_vfp(int16_t *dst, const float *src, long len);
+
+void ff_fmt_convert_init_arm(FmtConvertContext *c, AVCodecContext *avctx)
+{
+    if (HAVE_ARMVFP && HAVE_ARMV6) {
+        c->float_to_int16 = ff_float_to_int16_vfp;
+    }
+
+    if (HAVE_NEON) {
+        c->int32_to_float_fmul_scalar = ff_int32_to_float_fmul_scalar_neon;
+
+        if (!(avctx->flags & CODEC_FLAG_BITEXACT)) {
+            c->float_to_int16            = ff_float_to_int16_neon;
+            c->float_to_int16_interleave = ff_float_to_int16_interleave_neon;
+        }
+    }
+}
diff --git a/libavcodec/arm/fmtconvert_neon.S b/libavcodec/arm/fmtconvert_neon.S
new file mode 100644
index 0000000..4b0e9a2
--- /dev/null
+++ b/libavcodec/arm/fmtconvert_neon.S
@@ -0,0 +1,391 @@
+/*
+ * ARM NEON optimised Format Conversion Utils
+ * Copyright (c) 2008 Mans Rullgard <mans at mansr.com>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "config.h"
+#include "asm.S"
+
+        preserve8
+        .text
+
+function ff_float_to_int16_neon, export=1
+        subs            r2,  r2,  #8
+        vld1.64         {d0-d1},  [r1,:128]!
+        vcvt.s32.f32    q8,  q0,  #16
+        vld1.64         {d2-d3},  [r1,:128]!
+        vcvt.s32.f32    q9,  q1,  #16
+        beq             3f
+        bics            ip,  r2,  #15
+        beq             2f
+1:      subs            ip,  ip,  #16
+        vshrn.s32       d4,  q8,  #16
+        vld1.64         {d0-d1},  [r1,:128]!
+        vcvt.s32.f32    q0,  q0,  #16
+        vshrn.s32       d5,  q9,  #16
+        vld1.64         {d2-d3},  [r1,:128]!
+        vcvt.s32.f32    q1,  q1,  #16
+        vshrn.s32       d6,  q0,  #16
+        vst1.64         {d4-d5},  [r0,:128]!
+        vshrn.s32       d7,  q1,  #16
+        vld1.64         {d16-d17},[r1,:128]!
+        vcvt.s32.f32    q8,  q8,  #16
+        vld1.64         {d18-d19},[r1,:128]!
+        vcvt.s32.f32    q9,  q9,  #16
+        vst1.64         {d6-d7},  [r0,:128]!
+        bne             1b
+        ands            r2,  r2,  #15
+        beq             3f
+2:      vld1.64         {d0-d1},  [r1,:128]!
+        vshrn.s32       d4,  q8,  #16
+        vcvt.s32.f32    q0,  q0,  #16
+        vld1.64         {d2-d3},  [r1,:128]!
+        vshrn.s32       d5,  q9,  #16
+        vcvt.s32.f32    q1,  q1,  #16
+        vshrn.s32       d6,  q0,  #16
+        vst1.64         {d4-d5},  [r0,:128]!
+        vshrn.s32       d7,  q1,  #16
+        vst1.64         {d6-d7},  [r0,:128]!
+        bx              lr
+3:      vshrn.s32       d4,  q8,  #16
+        vshrn.s32       d5,  q9,  #16
+        vst1.64         {d4-d5},  [r0,:128]!
+        bx              lr
+endfunc
+
+function ff_float_to_int16_interleave_neon, export=1
+        cmp             r3, #2
+        ldrlt           r1, [r1]
+        blt             ff_float_to_int16_neon
+        bne             4f
+
+        ldr             r3, [r1]
+        ldr             r1, [r1, #4]
+
+        subs            r2,  r2,  #8
+        vld1.64         {d0-d1},  [r3,:128]!
+        vcvt.s32.f32    q8,  q0,  #16
+        vld1.64         {d2-d3},  [r3,:128]!
+        vcvt.s32.f32    q9,  q1,  #16
+        vld1.64         {d20-d21},[r1,:128]!
+        vcvt.s32.f32    q10, q10, #16
+        vld1.64         {d22-d23},[r1,:128]!
+        vcvt.s32.f32    q11, q11, #16
+        beq             3f
+        bics            ip,  r2,  #15
+        beq             2f
+1:      subs            ip,  ip,  #16
+        vld1.64         {d0-d1},  [r3,:128]!
+        vcvt.s32.f32    q0,  q0,  #16
+        vsri.32         q10, q8,  #16
+        vld1.64         {d2-d3},  [r3,:128]!
+        vcvt.s32.f32    q1,  q1,  #16
+        vld1.64         {d24-d25},[r1,:128]!
+        vcvt.s32.f32    q12, q12, #16
+        vld1.64         {d26-d27},[r1,:128]!
+        vsri.32         q11, q9,  #16
+        vst1.64         {d20-d21},[r0,:128]!
+        vcvt.s32.f32    q13, q13, #16
+        vst1.64         {d22-d23},[r0,:128]!
+        vsri.32         q12, q0,  #16
+        vld1.64         {d16-d17},[r3,:128]!
+        vsri.32         q13, q1,  #16
+        vst1.64         {d24-d25},[r0,:128]!
+        vcvt.s32.f32    q8,  q8,  #16
+        vld1.64         {d18-d19},[r3,:128]!
+        vcvt.s32.f32    q9,  q9,  #16
+        vld1.64         {d20-d21},[r1,:128]!
+        vcvt.s32.f32    q10, q10, #16
+        vld1.64         {d22-d23},[r1,:128]!
+        vcvt.s32.f32    q11, q11, #16
+        vst1.64         {d26-d27},[r0,:128]!
+        bne             1b
+        ands            r2,  r2,  #15
+        beq             3f
+2:      vsri.32         q10, q8,  #16
+        vld1.64         {d0-d1},  [r3,:128]!
+        vcvt.s32.f32    q0,  q0,  #16
+        vld1.64         {d2-d3},  [r3,:128]!
+        vcvt.s32.f32    q1,  q1,  #16
+        vld1.64         {d24-d25},[r1,:128]!
+        vcvt.s32.f32    q12, q12, #16
+        vsri.32         q11, q9,  #16
+        vld1.64         {d26-d27},[r1,:128]!
+        vcvt.s32.f32    q13, q13, #16
+        vst1.64         {d20-d21},[r0,:128]!
+        vsri.32         q12, q0,  #16
+        vst1.64         {d22-d23},[r0,:128]!
+        vsri.32         q13, q1,  #16
+        vst1.64         {d24-d27},[r0,:128]!
+        bx              lr
+3:      vsri.32         q10, q8,  #16
+        vsri.32         q11, q9,  #16
+        vst1.64         {d20-d23},[r0,:128]!
+        bx              lr
+
+4:      push            {r4-r8,lr}
+        cmp             r3,  #4
+        lsl             ip,  r3,  #1
+        blt             4f
+
+        @ 4 channels
+5:      ldmia           r1!, {r4-r7}
+        mov             lr,  r2
+        mov             r8,  r0
+        vld1.64         {d16-d17},[r4,:128]!
+        vcvt.s32.f32    q8,  q8,  #16
+        vld1.64         {d18-d19},[r5,:128]!
+        vcvt.s32.f32    q9,  q9,  #16
+        vld1.64         {d20-d21},[r6,:128]!
+        vcvt.s32.f32    q10, q10, #16
+        vld1.64         {d22-d23},[r7,:128]!
+        vcvt.s32.f32    q11, q11, #16
+6:      subs            lr,  lr,  #8
+        vld1.64         {d0-d1},  [r4,:128]!
+        vcvt.s32.f32    q0,  q0,  #16
+        vsri.32         q9,  q8,  #16
+        vld1.64         {d2-d3},  [r5,:128]!
+        vcvt.s32.f32    q1,  q1,  #16
+        vsri.32         q11, q10, #16
+        vld1.64         {d4-d5},  [r6,:128]!
+        vcvt.s32.f32    q2,  q2,  #16
+        vzip.32         d18, d22
+        vld1.64         {d6-d7},  [r7,:128]!
+        vcvt.s32.f32    q3,  q3,  #16
+        vzip.32         d19, d23
+        vst1.64         {d18},    [r8], ip
+        vsri.32         q1,  q0,  #16
+        vst1.64         {d22},    [r8], ip
+        vsri.32         q3,  q2,  #16
+        vst1.64         {d19},    [r8], ip
+        vzip.32         d2,  d6
+        vst1.64         {d23},    [r8], ip
+        vzip.32         d3,  d7
+        beq             7f
+        vld1.64         {d16-d17},[r4,:128]!
+        vcvt.s32.f32    q8,  q8,  #16
+        vst1.64         {d2},     [r8], ip
+        vld1.64         {d18-d19},[r5,:128]!
+        vcvt.s32.f32    q9,  q9,  #16
+        vst1.64         {d6},     [r8], ip
+        vld1.64         {d20-d21},[r6,:128]!
+        vcvt.s32.f32    q10, q10, #16
+        vst1.64         {d3},     [r8], ip
+        vld1.64         {d22-d23},[r7,:128]!
+        vcvt.s32.f32    q11, q11, #16
+        vst1.64         {d7},     [r8], ip
+        b               6b
+7:      vst1.64         {d2},     [r8], ip
+        vst1.64         {d6},     [r8], ip
+        vst1.64         {d3},     [r8], ip
+        vst1.64         {d7},     [r8], ip
+        subs            r3,  r3,  #4
+        popeq           {r4-r8,pc}
+        cmp             r3,  #4
+        add             r0,  r0,  #8
+        bge             5b
+
+        @ 2 channels
+4:      cmp             r3,  #2
+        blt             4f
+        ldmia           r1!, {r4-r5}
+        mov             lr,  r2
+        mov             r8,  r0
+        tst             lr,  #8
+        vld1.64         {d16-d17},[r4,:128]!
+        vcvt.s32.f32    q8,  q8,  #16
+        vld1.64         {d18-d19},[r5,:128]!
+        vcvt.s32.f32    q9,  q9,  #16
+        vld1.64         {d20-d21},[r4,:128]!
+        vcvt.s32.f32    q10, q10, #16
+        vld1.64         {d22-d23},[r5,:128]!
+        vcvt.s32.f32    q11, q11, #16
+        beq             6f
+        subs            lr,  lr,  #8
+        beq             7f
+        vsri.32         d18, d16, #16
+        vsri.32         d19, d17, #16
+        vld1.64         {d16-d17},[r4,:128]!
+        vcvt.s32.f32    q8,  q8,  #16
+        vst1.32         {d18[0]}, [r8], ip
+        vsri.32         d22, d20, #16
+        vst1.32         {d18[1]}, [r8], ip
+        vsri.32         d23, d21, #16
+        vst1.32         {d19[0]}, [r8], ip
+        vst1.32         {d19[1]}, [r8], ip
+        vld1.64         {d18-d19},[r5,:128]!
+        vcvt.s32.f32    q9,  q9,  #16
+        vst1.32         {d22[0]}, [r8], ip
+        vst1.32         {d22[1]}, [r8], ip
+        vld1.64         {d20-d21},[r4,:128]!
+        vcvt.s32.f32    q10, q10, #16
+        vst1.32         {d23[0]}, [r8], ip
+        vst1.32         {d23[1]}, [r8], ip
+        vld1.64         {d22-d23},[r5,:128]!
+        vcvt.s32.f32    q11, q11, #16
+6:      subs            lr,  lr,  #16
+        vld1.64         {d0-d1},  [r4,:128]!
+        vcvt.s32.f32    q0,  q0,  #16
+        vsri.32         d18, d16, #16
+        vld1.64         {d2-d3},  [r5,:128]!
+        vcvt.s32.f32    q1,  q1,  #16
+        vsri.32         d19, d17, #16
+        vld1.64         {d4-d5},  [r4,:128]!
+        vcvt.s32.f32    q2,  q2,  #16
+        vld1.64         {d6-d7},  [r5,:128]!
+        vcvt.s32.f32    q3,  q3,  #16
+        vst1.32         {d18[0]}, [r8], ip
+        vsri.32         d22, d20, #16
+        vst1.32         {d18[1]}, [r8], ip
+        vsri.32         d23, d21, #16
+        vst1.32         {d19[0]}, [r8], ip
+        vsri.32         d2,  d0,  #16
+        vst1.32         {d19[1]}, [r8], ip
+        vsri.32         d3,  d1,  #16
+        vst1.32         {d22[0]}, [r8], ip
+        vsri.32         d6,  d4,  #16
+        vst1.32         {d22[1]}, [r8], ip
+        vsri.32         d7,  d5,  #16
+        vst1.32         {d23[0]}, [r8], ip
+        vst1.32         {d23[1]}, [r8], ip
+        beq             6f
+        vld1.64         {d16-d17},[r4,:128]!
+        vcvt.s32.f32    q8,  q8,  #16
+        vst1.32         {d2[0]},  [r8], ip
+        vst1.32         {d2[1]},  [r8], ip
+        vld1.64         {d18-d19},[r5,:128]!
+        vcvt.s32.f32    q9,  q9,  #16
+        vst1.32         {d3[0]},  [r8], ip
+        vst1.32         {d3[1]},  [r8], ip
+        vld1.64         {d20-d21},[r4,:128]!
+        vcvt.s32.f32    q10, q10, #16
+        vst1.32         {d6[0]},  [r8], ip
+        vst1.32         {d6[1]},  [r8], ip
+        vld1.64         {d22-d23},[r5,:128]!
+        vcvt.s32.f32    q11, q11, #16
+        vst1.32         {d7[0]},  [r8], ip
+        vst1.32         {d7[1]},  [r8], ip
+        bgt             6b
+6:      vst1.32         {d2[0]},  [r8], ip
+        vst1.32         {d2[1]},  [r8], ip
+        vst1.32         {d3[0]},  [r8], ip
+        vst1.32         {d3[1]},  [r8], ip
+        vst1.32         {d6[0]},  [r8], ip
+        vst1.32         {d6[1]},  [r8], ip
+        vst1.32         {d7[0]},  [r8], ip
+        vst1.32         {d7[1]},  [r8], ip
+        b               8f
+7:      vsri.32         d18, d16, #16
+        vsri.32         d19, d17, #16
+        vst1.32         {d18[0]}, [r8], ip
+        vsri.32         d22, d20, #16
+        vst1.32         {d18[1]}, [r8], ip
+        vsri.32         d23, d21, #16
+        vst1.32         {d19[0]}, [r8], ip
+        vst1.32         {d19[1]}, [r8], ip
+        vst1.32         {d22[0]}, [r8], ip
+        vst1.32         {d22[1]}, [r8], ip
+        vst1.32         {d23[0]}, [r8], ip
+        vst1.32         {d23[1]}, [r8], ip
+8:      subs            r3,  r3,  #2
+        add             r0,  r0,  #4
+        popeq           {r4-r8,pc}
+
+        @ 1 channel
+4:      ldr             r4,  [r1],#4
+        tst             r2,  #8
+        mov             lr,  r2
+        mov             r5,  r0
+        vld1.64         {d0-d1},  [r4,:128]!
+        vcvt.s32.f32    q0,  q0,  #16
+        vld1.64         {d2-d3},  [r4,:128]!
+        vcvt.s32.f32    q1,  q1,  #16
+        bne             8f
+6:      subs            lr,  lr,  #16
+        vld1.64         {d4-d5},  [r4,:128]!
+        vcvt.s32.f32    q2,  q2,  #16
+        vld1.64         {d6-d7},  [r4,:128]!
+        vcvt.s32.f32    q3,  q3,  #16
+        vst1.16         {d0[1]},  [r5,:16], ip
+        vst1.16         {d0[3]},  [r5,:16], ip
+        vst1.16         {d1[1]},  [r5,:16], ip
+        vst1.16         {d1[3]},  [r5,:16], ip
+        vst1.16         {d2[1]},  [r5,:16], ip
+        vst1.16         {d2[3]},  [r5,:16], ip
+        vst1.16         {d3[1]},  [r5,:16], ip
+        vst1.16         {d3[3]},  [r5,:16], ip
+        beq             7f
+        vld1.64         {d0-d1},  [r4,:128]!
+        vcvt.s32.f32    q0,  q0,  #16
+        vld1.64         {d2-d3},  [r4,:128]!
+        vcvt.s32.f32    q1,  q1,  #16
+7:      vst1.16         {d4[1]},  [r5,:16], ip
+        vst1.16         {d4[3]},  [r5,:16], ip
+        vst1.16         {d5[1]},  [r5,:16], ip
+        vst1.16         {d5[3]},  [r5,:16], ip
+        vst1.16         {d6[1]},  [r5,:16], ip
+        vst1.16         {d6[3]},  [r5,:16], ip
+        vst1.16         {d7[1]},  [r5,:16], ip
+        vst1.16         {d7[3]},  [r5,:16], ip
+        bgt             6b
+        pop             {r4-r8,pc}
+8:      subs            lr,  lr,  #8
+        vst1.16         {d0[1]},  [r5,:16], ip
+        vst1.16         {d0[3]},  [r5,:16], ip
+        vst1.16         {d1[1]},  [r5,:16], ip
+        vst1.16         {d1[3]},  [r5,:16], ip
+        vst1.16         {d2[1]},  [r5,:16], ip
+        vst1.16         {d2[3]},  [r5,:16], ip
+        vst1.16         {d3[1]},  [r5,:16], ip
+        vst1.16         {d3[3]},  [r5,:16], ip
+        popeq           {r4-r8,pc}
+        vld1.64         {d0-d1},  [r4,:128]!
+        vcvt.s32.f32    q0,  q0,  #16
+        vld1.64         {d2-d3},  [r4,:128]!
+        vcvt.s32.f32    q1,  q1,  #16
+        b               6b
+endfunc
+
+function ff_int32_to_float_fmul_scalar_neon, export=1
+VFP     vdup.32         q0,  d0[0]
+VFP     len     .req    r2
+NOVFP   vdup.32         q0,  r2
+NOVFP   len     .req    r3
+
+        vld1.32         {q1},[r1,:128]!
+        vcvt.f32.s32    q3,  q1
+        vld1.32         {q2},[r1,:128]!
+        vcvt.f32.s32    q8,  q2
+1:      subs            len, len, #8
+        pld             [r1, #16]
+        vmul.f32        q9,  q3,  q0
+        vmul.f32        q10, q8,  q0
+        beq             2f
+        vld1.32         {q1},[r1,:128]!
+        vcvt.f32.s32    q3,  q1
+        vld1.32         {q2},[r1,:128]!
+        vcvt.f32.s32    q8,  q2
+        vst1.32         {q9}, [r0,:128]!
+        vst1.32         {q10},[r0,:128]!
+        b               1b
+2:      vst1.32         {q9}, [r0,:128]!
+        vst1.32         {q10},[r0,:128]!
+        bx              lr
+        .unreq  len
+endfunc
diff --git a/libavcodec/arm/fmtconvert_vfp.S b/libavcodec/arm/fmtconvert_vfp.S
new file mode 100644
index 0000000..e01627b
--- /dev/null
+++ b/libavcodec/arm/fmtconvert_vfp.S
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) 2008 Siarhei Siamashka <ssvb at users.sourceforge.net>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "config.h"
+#include "asm.S"
+
+        .syntax unified
+
+/**
+ * ARM VFP optimized float to int16 conversion.
+ * Assume that len is a positive number and is multiple of 8, destination
+ * buffer is at least 4 bytes aligned (8 bytes alignment is better for
+ * performance), little endian byte sex
+ */
+@ void ff_float_to_int16_vfp(int16_t *dst, const float *src, int len)
+function ff_float_to_int16_vfp, export=1
+        push            {r4-r8,lr}
+        vpush           {d8-d11}
+        vldmia          r1!, {s16-s23}
+        vcvt.s32.f32    s0,  s16
+        vcvt.s32.f32    s1,  s17
+        vcvt.s32.f32    s2,  s18
+        vcvt.s32.f32    s3,  s19
+        vcvt.s32.f32    s4,  s20
+        vcvt.s32.f32    s5,  s21
+        vcvt.s32.f32    s6,  s22
+        vcvt.s32.f32    s7,  s23
+1:
+        subs            r2,  r2,  #8
+        vmov            r3,  r4,  s0, s1
+        vmov            r5,  r6,  s2, s3
+        vmov            r7,  r8,  s4, s5
+        vmov            ip,  lr,  s6, s7
+        vldmiagt        r1!, {s16-s23}
+        ssat            r4,  #16, r4
+        ssat            r3,  #16, r3
+        ssat            r6,  #16, r6
+        ssat            r5,  #16, r5
+        pkhbt           r3,  r3,  r4, lsl #16
+        pkhbt           r4,  r5,  r6, lsl #16
+        vcvtgt.s32.f32  s0,  s16
+        vcvtgt.s32.f32  s1,  s17
+        vcvtgt.s32.f32  s2,  s18
+        vcvtgt.s32.f32  s3,  s19
+        vcvtgt.s32.f32  s4,  s20
+        vcvtgt.s32.f32  s5,  s21
+        vcvtgt.s32.f32  s6,  s22
+        vcvtgt.s32.f32  s7,  s23
+        ssat            r8,  #16, r8
+        ssat            r7,  #16, r7
+        ssat            lr,  #16, lr
+        ssat            ip,  #16, ip
+        pkhbt           r5,  r7,  r8, lsl #16
+        pkhbt           r6,  ip,  lr, lsl #16
+        stmia           r0!, {r3-r6}
+        bgt             1b
+
+        vpop            {d8-d11}
+        pop             {r4-r8,pc}
+endfunc
diff --git a/libavcodec/arm/h264dsp_init_arm.c b/libavcodec/arm/h264dsp_init_arm.c
index c06c3d0..20f5ac2 100644
--- a/libavcodec/arm/h264dsp_init_arm.c
+++ b/libavcodec/arm/h264dsp_init_arm.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2010 Mans Rullgard <mans at mansr.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -86,7 +86,12 @@ void ff_h264_idct_add8_neon(uint8_t **dest, const int *block_offset,
                             DCTELEM *block, int stride,
                             const uint8_t nnzc[6*8]);
 
-#if HAVE_NEON
+void ff_h264_idct8_add_neon(uint8_t *dst, DCTELEM *block, int stride);
+void ff_h264_idct8_dc_add_neon(uint8_t *dst, DCTELEM *block, int stride);
+void ff_h264_idct8_add4_neon(uint8_t *dst, const int *block_offset,
+                             DCTELEM *block, int stride,
+                             const uint8_t nnzc[6*8]);
+
 static void ff_h264dsp_init_neon(H264DSPContext *c)
 {
     c->h264_v_loop_filter_luma   = ff_h264_v_loop_filter_luma_neon;
@@ -117,8 +122,10 @@ static void ff_h264dsp_init_neon(H264DSPContext *c)
     c->h264_idct_add16      = ff_h264_idct_add16_neon;
     c->h264_idct_add16intra = ff_h264_idct_add16intra_neon;
     c->h264_idct_add8       = ff_h264_idct_add8_neon;
+    c->h264_idct8_add       = ff_h264_idct8_add_neon;
+    c->h264_idct8_dc_add    = ff_h264_idct8_dc_add_neon;
+    c->h264_idct8_add4      = ff_h264_idct8_add4_neon;
 }
-#endif
 
 void ff_h264dsp_init_arm(H264DSPContext *c)
 {
diff --git a/libavcodec/arm/h264dsp_neon.S b/libavcodec/arm/h264dsp_neon.S
index d9cdad8..b76e447 100644
--- a/libavcodec/arm/h264dsp_neon.S
+++ b/libavcodec/arm/h264dsp_neon.S
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2008 Mans Rullgard <mans at mansr.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -586,19 +586,17 @@ endfunc
         vclt.u8         d26, d26, d22   @ < alpha
         vsubw.u8        q2,  q2,  d2
         vdup.8          d22, r3         @ beta
-        vclt.s8         d25, d24, #0
         vrshrn.i16      d4,  q2,  #3
         vclt.u8         d28, d28, d22   @ < beta
-        vbic            d26, d26, d25
         vclt.u8         d30, d30, d22   @ < beta
-        vand            d26, d26, d28
-        vneg.s8         d25, d24
-        vand            d26, d26, d30
         vmin.s8         d4,  d4,  d24
-        vmovl.u8        q14, d16
-        vand            d4,  d4,  d26
+        vneg.s8         d25, d24
+        vand            d26, d26, d28
         vmax.s8         d4,  d4,  d25
+        vand            d26, d26, d30
         vmovl.u8        q11, d0
+        vand            d4,  d4,  d26
+        vmovl.u8        q14, d16
         vaddw.s8        q14, q14, d4
         vsubw.s8        q11, q11, d4
         vqmovun.s16     d16, q14
diff --git a/libavcodec/arm/h264idct_neon.S b/libavcodec/arm/h264idct_neon.S
index 0ba4880..b725354 100644
--- a/libavcodec/arm/h264idct_neon.S
+++ b/libavcodec/arm/h264idct_neon.S
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2008 Mans Rullgard <mans at mansr.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -150,13 +150,13 @@ function ff_h264_idct_add8_neon, export=1
         mov             r2,  r3
         ldr             r6,  [sp, #32]
         movrel          r7,  scan8+16
-        mov             ip,  #8
+        mov             ip,  #7
 1:      ldrb            r8,  [r7], #1
         ldr             r0,  [r5], #4
         ldrb            r8,  [r6, r8]
         tst             ip,  #4
-        addeq           r0,  r0,  r4
-        addne           r0,  r0,  r9
+        addne           r0,  r0,  r4
+        addeq           r0,  r0,  r9
         cmp             r8,  #0
         ldrsh           r8,  [r1]
         adrne           lr,  ff_h264_idct_add_neon
@@ -165,10 +165,214 @@ function ff_h264_idct_add8_neon, export=1
         blxne           lr
         subs            ip,  ip,  #1
         add             r1,  r1,  #32
-        bne             1b
+        bge             1b
         pop             {r4-r10,pc}
 endfunc
 
+.macro  idct8x8_cols    pass
+  .if \pass == 0
+        qa      .req    q2
+        qb      .req    q14
+        vshr.s16        q2,  q10, #1
+        vadd.i16        q0,  q8,  q12
+        vld1.16         {q14-q15},[r1,:128]!
+        vsub.i16        q1,  q8,  q12
+        vshr.s16        q3,  q14, #1
+        vsub.i16        q2,  q2,  q14
+        vadd.i16        q3,  q3,  q10
+  .else
+        qa      .req    q14
+        qb      .req    q2
+        vtrn.32         q8,  q10
+        vtrn.16         q12, q13
+        vtrn.32         q9,  q11
+        vtrn.32         q12, q2
+        vtrn.32         q13, q15
+        vswp            d21, d4
+        vshr.s16        q14, q10, #1
+        vswp            d17, d24
+        vshr.s16        q3,  q2,  #1
+        vswp            d19, d26
+        vadd.i16        q0,  q8,  q12
+        vswp            d23, d30
+        vsub.i16        q1,  q8,  q12
+        vsub.i16        q14, q14, q2
+        vadd.i16        q3,  q3,  q10
+  .endif
+        vadd.i16        q10, q1,  qa
+        vsub.i16        q12, q1,  qa
+        vadd.i16        q8,  q0,  q3
+        vsub.i16        qb,  q0,  q3
+        vsub.i16        q0,  q13, q11
+        vadd.i16        q1,  q15, q9
+        vsub.i16        qa,  q15, q9
+        vadd.i16        q3,  q13, q11
+        vsub.i16        q0,  q0,  q15
+        vsub.i16        q1,  q1,  q11
+        vadd.i16        qa,  qa,  q13
+        vadd.i16        q3,  q3,  q9
+        vshr.s16        q9,  q9,  #1
+        vshr.s16        q11, q11, #1
+        vshr.s16        q13, q13, #1
+        vshr.s16        q15, q15, #1
+        vsub.i16        q0,  q0,  q15
+        vsub.i16        q1,  q1,  q11
+        vadd.i16        qa,  qa,  q13
+        vadd.i16        q3,  q3,  q9
+        vshr.s16        q9,  q0,  #2
+        vshr.s16        q11, q1,  #2
+        vshr.s16        q13, qa,  #2
+        vshr.s16        q15, q3,  #2
+        vsub.i16        q3,  q3,  q9
+        vsub.i16        qa,  q11, qa
+        vadd.i16        q1,  q1,  q13
+        vadd.i16        q0,  q0,  q15
+  .if \pass == 0
+        vsub.i16        q15, q8,  q3
+        vadd.i16        q8,  q8,  q3
+        vadd.i16        q9,  q10, q2
+        vsub.i16        q2,  q10, q2
+        vtrn.16         q8,  q9
+        vadd.i16        q10, q12, q1
+        vtrn.16         q2,  q15
+        vadd.i16        q11, q14, q0
+        vsub.i16        q13, q12, q1
+        vtrn.16         q10, q11
+        vsub.i16        q12, q14, q0
+  .else
+        vsub.i16        q15, q8,  q3
+        vadd.i16        q8,  q8,  q3
+        vadd.i16        q9,  q10, q14
+        vsub.i16        q14, q10, q14
+        vadd.i16        q10, q12, q1
+        vsub.i16        q13, q12, q1
+        vadd.i16        q11, q2, q0
+        vsub.i16        q12, q2, q0
+  .endif
+        .unreq          qa
+        .unreq          qb
+.endm
+
+function ff_h264_idct8_add_neon, export=1
+        vld1.16         {q8-q9},  [r1,:128]!
+        vld1.16         {q10-q11},[r1,:128]!
+        vld1.16         {q12-q13},[r1,:128]!
+
+        idct8x8_cols    0
+        idct8x8_cols    1
+
+        mov             r3,  r0
+        vrshr.s16       q8,  q8,  #6
+        vld1.8          {d0},     [r0,:64], r2
+        vrshr.s16       q9,  q9,  #6
+        vld1.8          {d1},     [r0,:64], r2
+        vrshr.s16       q10, q10, #6
+        vld1.8          {d2},     [r0,:64], r2
+        vrshr.s16       q11, q11, #6
+        vld1.8          {d3},     [r0,:64], r2
+        vrshr.s16       q12, q12, #6
+        vld1.8          {d4},     [r0,:64], r2
+        vrshr.s16       q13, q13, #6
+        vld1.8          {d5},     [r0,:64], r2
+        vrshr.s16       q14, q14, #6
+        vld1.8          {d6},     [r0,:64], r2
+        vrshr.s16       q15, q15, #6
+        vld1.8          {d7},     [r0,:64], r2
+        vaddw.u8        q8,  q8,  d0
+        vaddw.u8        q9,  q9,  d1
+        vaddw.u8        q10, q10, d2
+        vqmovun.s16     d0,  q8
+        vaddw.u8        q11, q11, d3
+        vqmovun.s16     d1,  q9
+        vaddw.u8        q12, q12, d4
+        vqmovun.s16     d2,  q10
+        vst1.8          {d0},     [r3,:64], r2
+        vaddw.u8        q13, q13, d5
+        vqmovun.s16     d3,  q11
+        vst1.8          {d1},     [r3,:64], r2
+        vaddw.u8        q14, q14, d6
+        vqmovun.s16     d4,  q12
+        vst1.8          {d2},     [r3,:64], r2
+        vaddw.u8        q15, q15, d7
+        vqmovun.s16     d5,  q13
+        vst1.8          {d3},     [r3,:64], r2
+        vqmovun.s16     d6,  q14
+        vqmovun.s16     d7,  q15
+        vst1.8          {d4},     [r3,:64], r2
+        vst1.8          {d5},     [r3,:64], r2
+        vst1.8          {d6},     [r3,:64], r2
+        vst1.8          {d7},     [r3,:64], r2
+
+        sub             r1,  r1,  #128
+        bx              lr
+endfunc
+
+function ff_h264_idct8_dc_add_neon, export=1
+        vld1.16         {d30[],d31[]},[r1,:16]
+        vld1.32         {d0},     [r0,:64], r2
+        vrshr.s16       q15, q15, #6
+        vld1.32         {d1},     [r0,:64], r2
+        vld1.32         {d2},     [r0,:64], r2
+        vaddw.u8        q8,  q15, d0
+        vld1.32         {d3},     [r0,:64], r2
+        vaddw.u8        q9,  q15, d1
+        vld1.32         {d4},     [r0,:64], r2
+        vaddw.u8        q10, q15, d2
+        vld1.32         {d5},     [r0,:64], r2
+        vaddw.u8        q11, q15, d3
+        vld1.32         {d6},     [r0,:64], r2
+        vaddw.u8        q12, q15, d4
+        vld1.32         {d7},     [r0,:64], r2
+        vaddw.u8        q13, q15, d5
+        vaddw.u8        q14, q15, d6
+        vaddw.u8        q15, q15, d7
+        vqmovun.s16     d0,  q8
+        vqmovun.s16     d1,  q9
+        vqmovun.s16     d2,  q10
+        vqmovun.s16     d3,  q11
+        sub             r0,  r0,  r2, lsl #3
+        vst1.32         {d0},     [r0,:64], r2
+        vqmovun.s16     d4,  q12
+        vst1.32         {d1},     [r0,:64], r2
+        vqmovun.s16     d5,  q13
+        vst1.32         {d2},     [r0,:64], r2
+        vqmovun.s16     d6,  q14
+        vst1.32         {d3},     [r0,:64], r2
+        vqmovun.s16     d7,  q15
+        vst1.32         {d4},     [r0,:64], r2
+        vst1.32         {d5},     [r0,:64], r2
+        vst1.32         {d6},     [r0,:64], r2
+        vst1.32         {d7},     [r0,:64], r2
+        bx              lr
+endfunc
+
+function ff_h264_idct8_add4_neon, export=1
+        push            {r4-r8,lr}
+        mov             r4,  r0
+        mov             r5,  r1
+        mov             r1,  r2
+        mov             r2,  r3
+        ldr             r6,  [sp, #24]
+        movrel          r7,  scan8
+        mov             r12, #16
+1:      ldrb            r8,  [r7], #4
+        ldr             r0,  [r5], #16
+        ldrb            r8,  [r6, r8]
+        subs            r8,  r8,  #1
+        blt             2f
+        ldrsh           lr,  [r1]
+        add             r0,  r0,  r4
+        movne           lr,  #0
+        cmp             lr,  #0
+        adrne           lr,  ff_h264_idct8_dc_add_neon
+        adreq           lr,  ff_h264_idct8_add_neon
+        blx             lr
+2:      subs            r12, r12, #4
+        add             r1,  r1,  #128
+        bne             1b
+        pop             {r4-r8,pc}
+endfunc
+
         .section .rodata
 scan8:  .byte           4+1*8, 5+1*8, 4+2*8, 5+2*8
         .byte           6+1*8, 7+1*8, 6+2*8, 7+2*8
diff --git a/libavcodec/arm/h264pred_init_arm.c b/libavcodec/arm/h264pred_init_arm.c
index a7d9960..3f1c5c6 100644
--- a/libavcodec/arm/h264pred_init_arm.c
+++ b/libavcodec/arm/h264pred_init_arm.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2009 Mans Rullgard <mans at mansr.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -42,14 +42,14 @@ void ff_pred8x8_0lt_dc_neon(uint8_t *src, int stride);
 void ff_pred8x8_l00_dc_neon(uint8_t *src, int stride);
 void ff_pred8x8_0l0_dc_neon(uint8_t *src, int stride);
 
-#if HAVE_NEON
 static void ff_h264_pred_init_neon(H264PredContext *h, int codec_id)
 {
     h->pred8x8[VERT_PRED8x8     ] = ff_pred8x8_vert_neon;
     h->pred8x8[HOR_PRED8x8      ] = ff_pred8x8_hor_neon;
-    h->pred8x8[PLANE_PRED8x8    ] = ff_pred8x8_plane_neon;
+    if (codec_id != CODEC_ID_VP8)
+        h->pred8x8[PLANE_PRED8x8] = ff_pred8x8_plane_neon;
     h->pred8x8[DC_128_PRED8x8   ] = ff_pred8x8_128_dc_neon;
-    if (codec_id != CODEC_ID_RV40) {
+    if (codec_id != CODEC_ID_RV40 && codec_id != CODEC_ID_VP8) {
         h->pred8x8[DC_PRED8x8     ] = ff_pred8x8_dc_neon;
         h->pred8x8[LEFT_DC_PRED8x8] = ff_pred8x8_left_dc_neon;
         h->pred8x8[TOP_DC_PRED8x8 ] = ff_pred8x8_top_dc_neon;
@@ -65,10 +65,9 @@ static void ff_h264_pred_init_neon(H264PredContext *h, int codec_id)
     h->pred16x16[LEFT_DC_PRED8x8] = ff_pred16x16_left_dc_neon;
     h->pred16x16[TOP_DC_PRED8x8 ] = ff_pred16x16_top_dc_neon;
     h->pred16x16[DC_128_PRED8x8 ] = ff_pred16x16_128_dc_neon;
-    if (codec_id != CODEC_ID_SVQ3 && codec_id != CODEC_ID_RV40)
+    if (codec_id != CODEC_ID_SVQ3 && codec_id != CODEC_ID_RV40 && codec_id != CODEC_ID_VP8)
         h->pred16x16[PLANE_PRED8x8  ] = ff_pred16x16_plane_neon;
 }
-#endif
 
 void ff_h264_pred_init_arm(H264PredContext *h, int codec_id)
 {
diff --git a/libavcodec/arm/h264pred_neon.S b/libavcodec/arm/h264pred_neon.S
index e2c69e1..fe8a369 100644
--- a/libavcodec/arm/h264pred_neon.S
+++ b/libavcodec/arm/h264pred_neon.S
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2009 Mans Rullgard <mans at mansr.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -131,8 +131,8 @@ function ff_pred16x16_plane_neon, export=1
         vadd.i16        d5,  d6,  d7
         vpadd.i16       d4,  d4,  d5
         vpadd.i16       d4,  d4,  d4
-        vshl.i16        d5,  d4,  #2
-        vaddl.s16       q2,  d4,  d5
+        vshll.s16       q3,  d4,  #2
+        vaddw.s16       q2,  q3,  d4
         vrshrn.s32      d4,  q2,  #6
         mov             r3,  #0
         vtrn.16         d4,  d5
diff --git a/libavcodec/arm/int_neon.S b/libavcodec/arm/int_neon.S
index e8023e0..5a14991 100644
--- a/libavcodec/arm/int_neon.S
+++ b/libavcodec/arm/int_neon.S
@@ -2,20 +2,20 @@
  * ARM NEON optimised integer operations
  * Copyright (c) 2009 Kostya Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/arm/mathops.h b/libavcodec/arm/mathops.h
index 2244fa1..1fce8e3 100644
--- a/libavcodec/arm/mathops.h
+++ b/libavcodec/arm/mathops.h
@@ -2,20 +2,20 @@
  * simple math operations
  * Copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at> et al
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/arm/mdct_fixed_neon.S b/libavcodec/arm/mdct_fixed_neon.S
new file mode 100644
index 0000000..d219216
--- /dev/null
+++ b/libavcodec/arm/mdct_fixed_neon.S
@@ -0,0 +1,195 @@
+/*
+ * Copyright (c) 2011 Mans Rullgard <mans at mansr.com>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "asm.S"
+
+        preserve8
+
+.macro  prerot          dst, rt
+        lsr             r3,  r6,  #2            @ n4
+        add             \rt, r4,  r6,  lsr #1   @ revtab + n4
+        add             r9,  r3,  r3,  lsl #1   @ n3
+        add             r8,  r7,  r6            @ tcos + n4
+        add             r3,  r2,  r6,  lsr #1   @ in + n4
+        add             r9,  r2,  r9,  lsl #1   @ in + n3
+        sub             r8,  r8,  #16
+        sub             r10, r3,  #16
+        sub             r11, r9,  #16
+        mov             r12, #-16
+1:
+        vld2.16         {d0,d1},  [r9, :128]!
+        vld2.16         {d2,d3},  [r11,:128], r12
+        vld2.16         {d4,d5},  [r3, :128]!
+        vld2.16         {d6,d7},  [r10,:128], r12
+        vld2.16         {d16,d17},[r7, :128]!   @ cos, sin
+        vld2.16         {d18,d19},[r8, :128], r12
+        vrev64.16       q1,  q1
+        vrev64.16       q3,  q3
+        vrev64.16       q9,  q9
+        vneg.s16        d0,  d0
+        vneg.s16        d2,  d2
+        vneg.s16        d16, d16
+        vneg.s16        d18, d18
+        vhsub.s16       d0,  d0,  d3            @ re
+        vhsub.s16       d4,  d7,  d4            @ im
+        vhsub.s16       d6,  d6,  d5
+        vhsub.s16       d2,  d2,  d1
+        vmull.s16       q10, d0,  d16
+        vmlsl.s16       q10, d4,  d17
+        vmull.s16       q11, d0,  d17
+        vmlal.s16       q11, d4,  d16
+        vmull.s16       q12, d6,  d18
+        vmlsl.s16       q12, d2,  d19
+        vmull.s16       q13, d6,  d19
+        vmlal.s16       q13, d2,  d18
+        vshrn.s32       d0,  q10, #15
+        vshrn.s32       d1,  q11, #15
+        vshrn.s32       d2,  q12, #15
+        vshrn.s32       d3,  q13, #15
+        vzip.16         d0,  d1
+        vzip.16         d2,  d3
+        ldrh            lr,  [r4], #2
+        ldrh            r2,  [\rt, #-2]!
+        add             lr,  \dst, lr,  lsl #2
+        add             r2,  \dst, r2,  lsl #2
+        vst1.32         {d0[0]},  [lr,:32]
+        vst1.32         {d2[0]},  [r2,:32]
+        ldrh            lr,  [r4], #2
+        ldrh            r2,  [\rt, #-2]!
+        add             lr,  \dst, lr,  lsl #2
+        add             r2,  \dst, r2,  lsl #2
+        vst1.32         {d0[1]},  [lr,:32]
+        vst1.32         {d2[1]},  [r2,:32]
+        ldrh            lr,  [r4], #2
+        ldrh            r2,  [\rt, #-2]!
+        add             lr,  \dst, lr,  lsl #2
+        add             r2,  \dst, r2,  lsl #2
+        vst1.32         {d1[0]},  [lr,:32]
+        vst1.32         {d3[0]},  [r2,:32]
+        ldrh            lr,  [r4], #2
+        ldrh            r2,  [\rt, #-2]!
+        add             lr,  \dst, lr,  lsl #2
+        add             r2,  \dst, r2,  lsl #2
+        vst1.32         {d1[1]},  [lr,:32]
+        vst1.32         {d3[1]},  [r2,:32]
+        subs            r6,  r6,  #32
+        bgt             1b
+.endm
+
+function ff_mdct_fixed_calc_neon, export=1
+        push            {r1,r4-r11,lr}
+
+        ldr             r4,  [r0, #8]           @ revtab
+        ldr             r6,  [r0, #16]          @ mdct_size; n
+        ldr             r7,  [r0, #24]          @ tcos
+
+        prerot          r1,  r5
+
+        mov             r4,  r0
+        bl              X(ff_fft_fixed_calc_neon)
+
+        pop             {r5}
+        mov             r12, #-16
+        ldr             r6,  [r4, #16]          @ mdct_size; n
+        ldr             r7,  [r4, #24]          @ tcos
+        add             r5,  r5,  r6,  lsr #1
+        add             r7,  r7,  r6,  lsr #1
+        sub             r1,  r5,  #16
+        sub             r2,  r7,  #16
+1:
+        vld2.16         {d4,d5},  [r7,:128]!
+        vld2.16         {d6,d7},  [r2,:128], r12
+        vld2.16         {d0,d1},  [r5,:128]
+        vld2.16         {d2,d3},  [r1,:128]
+        vrev64.16       q3,  q3
+        vrev64.16       q1,  q1
+        vneg.s16        q3,  q3
+        vneg.s16        q2,  q2
+        vmull.s16       q11, d2,  d6
+        vmlal.s16       q11, d3,  d7
+        vmull.s16       q8,  d0,  d5
+        vmlsl.s16       q8,  d1,  d4
+        vmull.s16       q9,  d0,  d4
+        vmlal.s16       q9,  d1,  d5
+        vmull.s16       q10, d2,  d7
+        vmlsl.s16       q10, d3,  d6
+        vshrn.s32       d0,  q11, #15
+        vshrn.s32       d1,  q8,  #15
+        vshrn.s32       d2,  q9,  #15
+        vshrn.s32       d3,  q10, #15
+        vrev64.16       q0,  q0
+        vst2.16         {d2,d3},  [r5,:128]!
+        vst2.16         {d0,d1},  [r1,:128], r12
+        subs            r6,  r6,  #32
+        bgt             1b
+
+        pop             {r4-r11,pc}
+endfunc
+
+function ff_mdct_fixed_calcw_neon, export=1
+        push            {r1,r4-r11,lr}
+
+        ldrd            r4,  r5,  [r0, #8]      @ revtab, tmp_buf
+        ldr             r6,  [r0, #16]          @ mdct_size; n
+        ldr             r7,  [r0, #24]          @ tcos
+
+        prerot          r5,  r1
+
+        mov             r4,  r0
+        mov             r1,  r5
+        bl              X(ff_fft_fixed_calc_neon)
+
+        pop             {r7}
+        mov             r12, #-16
+        ldr             r6,  [r4, #16]          @ mdct_size; n
+        ldr             r9,  [r4, #24]          @ tcos
+        add             r5,  r5,  r6,  lsr #1
+        add             r7,  r7,  r6
+        add             r9,  r9,  r6,  lsr #1
+        sub             r3,  r5,  #16
+        sub             r1,  r7,  #16
+        sub             r2,  r9,  #16
+1:
+        vld2.16         {d4,d5},  [r9,:128]!
+        vld2.16         {d6,d7},  [r2,:128], r12
+        vld2.16         {d0,d1},  [r5,:128]!
+        vld2.16         {d2,d3},  [r3,:128], r12
+        vrev64.16       q3,  q3
+        vrev64.16       q1,  q1
+        vneg.s16        q3,  q3
+        vneg.s16        q2,  q2
+        vmull.s16       q8,  d2,  d6
+        vmlal.s16       q8,  d3,  d7
+        vmull.s16       q9,  d0,  d5
+        vmlsl.s16       q9,  d1,  d4
+        vmull.s16       q10, d0,  d4
+        vmlal.s16       q10, d1,  d5
+        vmull.s16       q11, d2,  d7
+        vmlsl.s16       q11, d3,  d6
+        vrev64.32       q8,  q8
+        vrev64.32       q9,  q9
+        vst2.32         {q10,q11},[r7,:128]!
+        vst2.32         {d16,d18},[r1,:128], r12
+        vst2.32         {d17,d19},[r1,:128], r12
+        subs            r6,  r6,  #32
+        bgt             1b
+
+        pop             {r4-r11,pc}
+endfunc
diff --git a/libavcodec/arm/mdct_neon.S b/libavcodec/arm/mdct_neon.S
index fac75be..c375f4c 100644
--- a/libavcodec/arm/mdct_neon.S
+++ b/libavcodec/arm/mdct_neon.S
@@ -2,20 +2,20 @@
  * ARM NEON optimised MDCT
  * Copyright (c) 2009 Mans Rullgard <mans at mansr.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -31,8 +31,8 @@ function ff_imdct_half_neon, export=1
         push            {r4-r8,lr}
 
         mov             r12, #1
-        ldr             lr,  [r0, #28]          @ mdct_bits
-        ldr             r4,  [r0, #32]          @ tcos
+        ldr             lr,  [r0, #20]          @ mdct_bits
+        ldr             r4,  [r0, #24]          @ tcos
         ldr             r3,  [r0, #8]           @ revtab
         lsl             r12, r12, lr            @ n  = 1 << nbits
         lsr             lr,  r12, #2            @ n4 = n >> 2
@@ -76,8 +76,8 @@ function ff_imdct_half_neon, export=1
         bl              ff_fft_calc_neon
 
         mov             r12, #1
-        ldr             lr,  [r4, #28]          @ mdct_bits
-        ldr             r4,  [r4, #32]          @ tcos
+        ldr             lr,  [r4, #20]          @ mdct_bits
+        ldr             r4,  [r4, #24]          @ tcos
         lsl             r12, r12, lr            @ n  = 1 << nbits
         lsr             lr,  r12, #3            @ n8 = n >> 3
 
@@ -127,7 +127,7 @@ endfunc
 function ff_imdct_calc_neon, export=1
         push            {r4-r6,lr}
 
-        ldr             r3,  [r0, #28]
+        ldr             r3,  [r0, #20]
         mov             r4,  #1
         mov             r5,  r1
         lsl             r4,  r4,  r3
@@ -164,8 +164,8 @@ function ff_mdct_calc_neon, export=1
         push            {r4-r10,lr}
 
         mov             r12, #1
-        ldr             lr,  [r0, #28]          @ mdct_bits
-        ldr             r4,  [r0, #32]          @ tcos
+        ldr             lr,  [r0, #20]          @ mdct_bits
+        ldr             r4,  [r0, #24]          @ tcos
         ldr             r3,  [r0, #8]           @ revtab
         lsl             lr,  r12, lr            @ n  = 1 << nbits
         add             r7,  r2,  lr            @ in4u
@@ -253,8 +253,8 @@ function ff_mdct_calc_neon, export=1
         bl              ff_fft_calc_neon
 
         mov             r12, #1
-        ldr             lr,  [r4, #28]          @ mdct_bits
-        ldr             r4,  [r4, #32]          @ tcos
+        ldr             lr,  [r4, #20]          @ mdct_bits
+        ldr             r4,  [r4, #24]          @ tcos
         lsl             r12, r12, lr            @ n  = 1 << nbits
         lsr             lr,  r12, #3            @ n8 = n >> 3
 
diff --git a/libavcodec/arm/mpegvideo_arm.c b/libavcodec/arm/mpegvideo_arm.c
index 06eacdf..b1d1312 100644
--- a/libavcodec/arm/mpegvideo_arm.c
+++ b/libavcodec/arm/mpegvideo_arm.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2002 Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -22,6 +22,21 @@
 #include "libavcodec/dsputil.h"
 #include "libavcodec/mpegvideo.h"
 #include "mpegvideo_arm.h"
+#include "asm-offsets.h"
+
+#if HAVE_NEON
+CHK_OFFS(MpegEncContext, y_dc_scale,       Y_DC_SCALE);
+CHK_OFFS(MpegEncContext, c_dc_scale,       C_DC_SCALE);
+CHK_OFFS(MpegEncContext, ac_pred,          AC_PRED);
+CHK_OFFS(MpegEncContext, block_last_index, BLOCK_LAST_INDEX);
+CHK_OFFS(MpegEncContext, inter_scantable.raster_end, INTER_SCANTAB_RASTER_END);
+CHK_OFFS(MpegEncContext, h263_aic,         H263_AIC);
+#endif
+
+void ff_dct_unquantize_h263_inter_neon(MpegEncContext *s, DCTELEM *block,
+                                       int n, int qscale);
+void ff_dct_unquantize_h263_intra_neon(MpegEncContext *s, DCTELEM *block,
+                                       int n, int qscale);
 
 void MPV_common_init_arm(MpegEncContext *s)
 {
@@ -35,4 +50,9 @@ void MPV_common_init_arm(MpegEncContext *s)
 #if HAVE_IWMMXT
     MPV_common_init_iwmmxt(s);
 #endif
+
+    if (HAVE_NEON) {
+        s->dct_unquantize_h263_intra = ff_dct_unquantize_h263_intra_neon;
+        s->dct_unquantize_h263_inter = ff_dct_unquantize_h263_inter_neon;
+    }
 }
diff --git a/libavcodec/arm/mpegvideo_arm.h b/libavcodec/arm/mpegvideo_arm.h
index 4cc25fd..0812ca1 100644
--- a/libavcodec/arm/mpegvideo_arm.h
+++ b/libavcodec/arm/mpegvideo_arm.h
@@ -1,18 +1,18 @@
 /*
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/arm/mpegvideo_armv5te.c b/libavcodec/arm/mpegvideo_armv5te.c
index 1d383ca..30197d8 100644
--- a/libavcodec/arm/mpegvideo_armv5te.c
+++ b/libavcodec/arm/mpegvideo_armv5te.c
@@ -2,20 +2,20 @@
  * Optimization of some functions from mpegvideo.c for armv5te
  * Copyright (c) 2007 Siarhei Siamashka <ssvb at users.sourceforge.net>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/arm/mpegvideo_armv5te_s.S b/libavcodec/arm/mpegvideo_armv5te_s.S
index c8cb2c6..6473926 100644
--- a/libavcodec/arm/mpegvideo_armv5te_s.S
+++ b/libavcodec/arm/mpegvideo_armv5te_s.S
@@ -2,20 +2,20 @@
  * Optimization of some functions from mpegvideo.c for armv5te
  * Copyright (c) 2007 Siarhei Siamashka <ssvb at users.sourceforge.net>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/arm/mpegvideo_iwmmxt.c b/libavcodec/arm/mpegvideo_iwmmxt.c
index 9e3878f..4d5edd8 100644
--- a/libavcodec/arm/mpegvideo_iwmmxt.c
+++ b/libavcodec/arm/mpegvideo_iwmmxt.c
@@ -1,23 +1,24 @@
 /*
  * copyright (c) 2004 AGAWA Koji
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/cpu.h"
 #include "libavcodec/avcodec.h"
 #include "libavcodec/dsputil.h"
 #include "libavcodec/mpegvideo.h"
@@ -111,7 +112,7 @@ static void dct_unquantize_h263_inter_iwmmxt(MpegEncContext *s,
 
 void MPV_common_init_iwmmxt(MpegEncContext *s)
 {
-    if (!(mm_flags & FF_MM_IWMMXT)) return;
+    if (!(mm_flags & AV_CPU_FLAG_IWMMXT)) return;
 
     s->dct_unquantize_h263_intra = dct_unquantize_h263_intra_iwmmxt;
 #if 0
diff --git a/libavcodec/arm/mpegvideo_neon.S b/libavcodec/arm/mpegvideo_neon.S
new file mode 100644
index 0000000..365dcf6
--- /dev/null
+++ b/libavcodec/arm/mpegvideo_neon.S
@@ -0,0 +1,103 @@
+/*
+ * Copyright (c) 2010 Mans Rullgard
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "asm.S"
+#include "asm-offsets.h"
+
+function ff_dct_unquantize_h263_inter_neon, export=1
+        add             r12, r0,  #BLOCK_LAST_INDEX
+        ldr             r12, [r12, r2, lsl #2]
+        add             r0,  r0,  #INTER_SCANTAB_RASTER_END
+        ldrb            r12, [r0, r12]
+        sub             r2,  r3,  #1
+        lsl             r0,  r3,  #1
+        orr             r2,  r2,  #1
+        add             r3,  r12, #1
+endfunc
+
+function ff_dct_unquantize_h263_neon, export=1
+        vdup.16         q15, r0                 @ qmul
+        vdup.16         q14, r2                 @ qadd
+        vneg.s16        q13, q14
+        cmp             r3,  #4
+        mov             r0,  r1
+        ble             2f
+1:
+        vld1.16         {q0},     [r0,:128]!
+        vclt.s16        q3,  q0,  #0
+        vld1.16         {q8},     [r0,:128]!
+        vceq.s16        q1,  q0,  #0
+        vmul.s16        q2,  q0,  q15
+        vclt.s16        q11, q8,  #0
+        vmul.s16        q10, q8,  q15
+        vbsl            q3,  q13, q14
+        vbsl            q11, q13, q14
+        vadd.s16        q2,  q2,  q3
+        vceq.s16        q9,  q8,  #0
+        vadd.s16        q10, q10, q11
+        vbif            q0,  q2,  q1
+        vbif            q8,  q10, q9
+        subs            r3,  r3,  #16
+        vst1.16         {q0},     [r1,:128]!
+        vst1.16         {q8},     [r1,:128]!
+        bxle            lr
+        cmp             r3,  #8
+        bgt             1b
+2:
+        vld1.16         {d0},     [r0,:64]
+        vclt.s16        d3,  d0,  #0
+        vceq.s16        d1,  d0,  #0
+        vmul.s16        d2,  d0,  d30
+        vbsl            d3,  d26, d28
+        vadd.s16        d2,  d2,  d3
+        vbif            d0,  d2,  d1
+        vst1.16         {d0},     [r1,:64]
+        bx              lr
+endfunc
+
+function ff_dct_unquantize_h263_intra_neon, export=1
+        push            {r4-r6,lr}
+        add             r12, r0,  #BLOCK_LAST_INDEX
+        ldr             r6,  [r0, #AC_PRED]
+        add             lr,  r0,  #INTER_SCANTAB_RASTER_END
+        cmp             r6,  #0
+        movne           r12, #63
+        bne             1f
+        ldr             r12, [r12, r2, lsl #2]
+        ldrb            r12, [lr, r12]
+1:      ldr             r5,  [r0, #H263_AIC]
+        ldrsh           r4,  [r1]
+        cmp             r5,  #0
+        mov             r5,  r1
+        movne           r2,  #0
+        bne             2f
+        cmp             r2,  #4
+        addge           r0,  r0,  #4
+        sub             r2,  r3,  #1
+        ldr             r6,  [r0, #Y_DC_SCALE]
+        orr             r2,  r2,  #1
+        smulbb          r4,  r4,  r6
+2:      lsl             r0,  r3,  #1
+        add             r3,  r12, #1
+        bl              ff_dct_unquantize_h263_neon
+        vmov.16         d0[0], r4
+        vst1.16         {d0[0]},  [r5]
+        pop             {r4-r6,pc}
+endfunc
diff --git a/libavcodec/arm/rdft_neon.S b/libavcodec/arm/rdft_neon.S
index 4f8a103..8aafdc9 100644
--- a/libavcodec/arm/rdft_neon.S
+++ b/libavcodec/arm/rdft_neon.S
@@ -2,20 +2,20 @@
  * ARM NEON optimised RDFT
  * Copyright (c) 2009 Mans Rullgard <mans at mansr.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/arm/simple_idct_arm.S b/libavcodec/arm/simple_idct_arm.S
index ecb83d2..4e6dfa4 100644
--- a/libavcodec/arm/simple_idct_arm.S
+++ b/libavcodec/arm/simple_idct_arm.S
@@ -5,22 +5,22 @@
  * Author: Frederic Boulay <dilb at handhelds.org>
  *
  * The function defined in this file is derived from the simple_idct function
- * from the libavcodec library part of the FFmpeg project.
+ * from the libavcodec library part of the Libav project.
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/arm/simple_idct_armv5te.S b/libavcodec/arm/simple_idct_armv5te.S
index 27aeca4..5d03c0c 100644
--- a/libavcodec/arm/simple_idct_armv5te.S
+++ b/libavcodec/arm/simple_idct_armv5te.S
@@ -4,20 +4,20 @@
  * Copyright (c) 2001 Michael Niedermayer <michaelni at gmx.at>
  * Copyright (c) 2006 Mans Rullgard <mans at mansr.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/arm/simple_idct_armv6.S b/libavcodec/arm/simple_idct_armv6.S
index d61c1fd..b2eb525 100644
--- a/libavcodec/arm/simple_idct_armv6.S
+++ b/libavcodec/arm/simple_idct_armv6.S
@@ -4,20 +4,20 @@
  * Copyright (c) 2001 Michael Niedermayer <michaelni at gmx.at>
  * Copyright (c) 2007 Mans Rullgard <mans at mansr.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/arm/simple_idct_neon.S b/libavcodec/arm/simple_idct_neon.S
index f27208e..0628b96 100644
--- a/libavcodec/arm/simple_idct_neon.S
+++ b/libavcodec/arm/simple_idct_neon.S
@@ -6,20 +6,20 @@
  * Based on Simple IDCT
  * Copyright (c) 2001 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -243,7 +243,6 @@ endfunc
         .align 4
 idct_coeff_neon:
         .short W1, W2, W3, W4, W5, W6, W7, W4c
-        .previous
 
         .macro idct_start data
         push            {r4-r7, lr}
diff --git a/libavcodec/arm/synth_filter_neon.S b/libavcodec/arm/synth_filter_neon.S
index c168d73..d4f67b7 100644
--- a/libavcodec/arm/synth_filter_neon.S
+++ b/libavcodec/arm/synth_filter_neon.S
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2010 Mans Rullgard <mans at mansr.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -36,13 +36,13 @@ function ff_synth_filter_float_neon, export=1
         mov             r9,  r1                 @ synth_buf
 
 VFP     vpush           {d0}
-        bl              ff_imdct_half_neon
+        bl              X(ff_imdct_half_neon)
 VFP     vpop            {d0}
         pop             {r3}
 
         ldr             r5,  [sp, #9*4]         @ window
         ldr             r2,  [sp, #10*4]        @ out
-NOVFP   vldr            d0,  [sp, #12*4]        @ scale, bias
+NOVFP   vldr            s0,  [sp, #12*4]        @ scale
         add             r8,  r9,  #12*4
 
         mov             lr,  #64*4
@@ -90,10 +90,8 @@ NOVFP   vldr            d0,  [sp, #12*4]        @ scale, bias
         sub             r11, r11, #512*4
         b               2b
 3:
-        vdup.32         q8,  d0[1]
-        vdup.32         q9,  d0[1]
-        vmla.f32        q8,  q10, d0[0]
-        vmla.f32        q9,  q1,  d0[0]
+        vmul.f32        q8,  q10, d0[0]
+        vmul.f32        q9,  q1,  d0[0]
         vst1.32         {q3},     [r3,:128]
         sub             r3,  r3,  #16*4
         vst1.32         {q2},     [r3,:128]
diff --git a/libavcodec/arm/vp3dsp_neon.S b/libavcodec/arm/vp3dsp_neon.S
index ade1998..c1a55ca 100644
--- a/libavcodec/arm/vp3dsp_neon.S
+++ b/libavcodec/arm/vp3dsp_neon.S
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2009 David Conrad
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -377,12 +377,10 @@ endfunc
 
 function ff_vp3_idct_dc_add_neon, export=1
     ldrsh           r2,  [r2]
-    movw            r3,  #46341
-    mul             r2,  r3,  r2
-    smulwt          r2,  r3,  r2
     mov             r3,  r0
+    add             r2,  r2,  #15
     vdup.16         q15, r2
-    vrshr.s16       q15, q15, #4
+    vshr.s16        q15, q15, #5
 
     vld1.8          {d0}, [r0,:64], r1
     vld1.8          {d1}, [r0,:64], r1
diff --git a/libavcodec/arm/vp56_arith.h b/libavcodec/arm/vp56_arith.h
new file mode 100644
index 0000000..f5dbd1d
--- /dev/null
+++ b/libavcodec/arm/vp56_arith.h
@@ -0,0 +1,92 @@
+/*
+ * Copyright (C) 2010 Mans Rullgard <mans at mansr.com>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_ARM_VP56_ARITH_H
+#define AVCODEC_ARM_VP56_ARITH_H
+
+#if HAVE_ARMV6 && HAVE_INLINE_ASM
+
+#define vp56_rac_get_prob vp56_rac_get_prob_armv6
+static inline int vp56_rac_get_prob_armv6(VP56RangeCoder *c, int pr)
+{
+    unsigned shift     = ff_vp56_norm_shift[c->high];
+    unsigned code_word = c->code_word << shift;
+    unsigned high      = c->high << shift;
+    unsigned bit;
+
+    __asm__ volatile ("adds    %3,  %3,  %0           \n"
+                      "cmpcs   %7,  %4                \n"
+                      "ldrcsh  %2,  [%4], #2          \n"
+                      "rsb     %0,  %6,  #256         \n"
+                      "smlabb  %0,  %5,  %6,  %0      \n"
+                      "rev16cs %2,  %2                \n"
+                      "orrcs   %1,  %1,  %2,  lsl %3  \n"
+                      "subcs   %3,  %3,  #16          \n"
+                      "lsr     %0,  %0,  #8           \n"
+                      "cmp     %1,  %0,  lsl #16      \n"
+                      "subge   %1,  %1,  %0,  lsl #16 \n"
+                      "subge   %0,  %5,  %0           \n"
+                      "movge   %2,  #1                \n"
+                      "movlt   %2,  #0                \n"
+                      : "=&r"(c->high), "=&r"(c->code_word), "=&r"(bit),
+                        "+&r"(c->bits), "+&r"(c->buffer)
+                      : "r"(high), "r"(pr), "r"(c->end - 1),
+                        "0"(shift), "1"(code_word));
+
+    return bit;
+}
+
+#define vp56_rac_get_prob_branchy vp56_rac_get_prob_branchy_armv6
+static inline int vp56_rac_get_prob_branchy_armv6(VP56RangeCoder *c, int pr)
+{
+    unsigned shift     = ff_vp56_norm_shift[c->high];
+    unsigned code_word = c->code_word << shift;
+    unsigned high      = c->high << shift;
+    unsigned low;
+    unsigned tmp;
+
+    __asm__ volatile ("adds    %3,  %3,  %0           \n"
+                      "cmpcs   %7,  %4                \n"
+                      "ldrcsh  %2,  [%4], #2          \n"
+                      "rsb     %0,  %6,  #256         \n"
+                      "smlabb  %0,  %5,  %6,  %0      \n"
+                      "rev16cs %2,  %2                \n"
+                      "orrcs   %1,  %1,  %2,  lsl %3  \n"
+                      "subcs   %3,  %3,  #16          \n"
+                      "lsr     %0,  %0,  #8           \n"
+                      "lsl     %2,  %0,  #16          \n"
+                      : "=&r"(low), "+&r"(code_word), "=&r"(tmp),
+                        "+&r"(c->bits), "+&r"(c->buffer)
+                      : "r"(high), "r"(pr), "r"(c->end - 1), "0"(shift));
+
+    if (code_word >= tmp) {
+        c->high      = high - low;
+        c->code_word = code_word - tmp;
+        return 1;
+    }
+
+    c->high      = low;
+    c->code_word = code_word;
+    return 0;
+}
+
+#endif
+
+#endif
diff --git a/libavcodec/arm/vp56dsp_init_arm.c b/libavcodec/arm/vp56dsp_init_arm.c
index ceab9a8..5989602 100644
--- a/libavcodec/arm/vp56dsp_init_arm.c
+++ b/libavcodec/arm/vp56dsp_init_arm.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2010 Mans Rullgard <mans at mansr.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/arm/vp56dsp_neon.S b/libavcodec/arm/vp56dsp_neon.S
index 0353661..b95d8ab 100644
--- a/libavcodec/arm/vp56dsp_neon.S
+++ b/libavcodec/arm/vp56dsp_neon.S
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2010 Mans Rullgard <mans at mansr.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/arm/vp8.h b/libavcodec/arm/vp8.h
new file mode 100644
index 0000000..35cdd8b
--- /dev/null
+++ b/libavcodec/arm/vp8.h
@@ -0,0 +1,29 @@
+/**
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_ARM_VP8_H
+#define AVCODEC_ARM_VP8_H
+
+#if HAVE_ARMV6
+#define decode_block_coeffs_internal ff_decode_block_coeffs_armv6
+int ff_decode_block_coeffs_armv6(VP56RangeCoder *rc, DCTELEM block[16],
+                                 uint8_t probs[8][3][NUM_DCT_TOKENS-1],
+                                 int i, uint8_t *token_prob, int16_t qmul[2]);
+#endif
+
+#endif
diff --git a/libavcodec/arm/vp8_armv6.S b/libavcodec/arm/vp8_armv6.S
new file mode 100644
index 0000000..88fa398
--- /dev/null
+++ b/libavcodec/arm/vp8_armv6.S
@@ -0,0 +1,220 @@
+/**
+ * Copyright (C) 2010 Mans Rullgard
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "asm.S"
+
+        .syntax         unified
+
+.macro rac_get_prob     h, bs, buf, cw, pr, t0, t1
+        adds            \bs, \bs, \t0
+        lsl             \cw, \cw, \t0
+        lsl             \t0, \h,  \t0
+        rsb             \h,  \pr, #256
+        ldrhcs          \t1, [\buf], #2
+        smlabb          \h,  \t0, \pr, \h
+        rev16cs         \t1, \t1
+        orrcs           \cw, \cw, \t1, lsl \bs
+        subcs           \bs, \bs, #16
+        lsr             \h,  \h,  #8
+        cmp             \cw, \h,  lsl #16
+        subge           \cw, \cw, \h,  lsl #16
+        subge           \h,  \t0, \h
+.endm
+
+.macro rac_get_128      h, bs, buf, cw, t0, t1
+        adds            \bs, \bs, \t0
+        lsl             \cw, \cw, \t0
+        lsl             \t0, \h,  \t0
+        ldrhcs          \t1, [\buf], #2
+        mov             \h,  #128
+        rev16cs         \t1, \t1
+        add             \h,  \h,  \t0, lsl #7
+        orrcs           \cw, \cw, \t1, lsl \bs
+        subcs           \bs, \bs, #16
+        lsr             \h,  \h,  #8
+        cmp             \cw, \h,  lsl #16
+        subge           \cw, \cw, \h,  lsl #16
+        subge           \h,  \t0, \h
+.endm
+
+function ff_decode_block_coeffs_armv6, export=1
+        push            {r0,r1,r4-r11,lr}
+        movrel          lr,  X(ff_vp56_norm_shift)
+        ldrd            r4,  r5,  [sp, #44]             @ token_prob, qmul
+        cmp             r3,  #0
+        ldr             r11, [r5]
+        ldm             r0,  {r5-r7}                    @ high, bits, buf
+        pkhtbne         r11, r11, r11, asr #16
+        ldr             r8,  [r0, #16]                  @ code_word
+0:
+        ldrb            r9,  [lr, r5]
+        add             r3,  r3,  #1
+        ldrb            r0,  [r4, #1]
+        rac_get_prob    r5,  r6,  r7,  r8,  r0,  r9,  r10
+        blt             2f
+
+        ldrb            r9,  [lr, r5]
+        ldrb            r0,  [r4, #2]
+        rac_get_prob    r5,  r6,  r7,  r8,  r0,  r9,  r10
+        ldrb            r9,  [lr, r5]
+        bge             3f
+
+        add             r4,  r3,  r3,  lsl #5
+        sxth            r12, r11
+        add             r4,  r2,  r4
+        adds            r6,  r6,  r9
+        add             r4,  r4,  #11
+        lsl             r8,  r8,  r9
+        ldrhcs          r10, [r7], #2
+        lsl             r9,  r5,  r9
+        mov             r5,  #128
+        rev16cs         r10, r10
+        add             r5,  r5,  r9,  lsl #7
+        orrcs           r8,  r8,  r10, lsl r6
+        subcs           r6,  r6,  #16
+        lsr             r5,  r5,  #8
+        cmp             r8,  r5,  lsl #16
+        movrel          r10, zigzag_scan-1
+        subge           r8,  r8,  r5,  lsl #16
+        subge           r5,  r9,  r5
+        ldrb            r10, [r10, r3]
+        rsbge           r12, r12, #0
+        cmp             r3,  #16
+        strh            r12, [r1, r10]
+        bge             6f
+5:
+        ldrb            r9,  [lr, r5]
+        ldrb            r0,  [r4]
+        rac_get_prob    r5,  r6,  r7,  r8,  r0,  r9,  r10
+        pkhtb           r11, r11, r11, asr #16
+        bge             0b
+
+6:
+        ldr             r0,  [sp]
+        ldr             r9,  [r0, #12]
+        cmp             r7,  r9
+        movhi           r7,  r9
+        stm             r0,  {r5-r7}                    @ high, bits, buf
+        str             r8,  [r0, #16]                  @ code_word
+
+        add             sp,  sp,  #8
+        mov             r0,  r3
+        pop             {r4-r11,pc}
+2:
+        add             r4,  r3,  r3,  lsl #5
+        cmp             r3,  #16
+        add             r4,  r2,  r4
+        pkhtb           r11, r11, r11, asr #16
+        bne             0b
+        b               6b
+3:
+        ldrb            r0,  [r4, #3]
+        rac_get_prob    r5,  r6,  r7,  r8,  r0,  r9,  r10
+        ldrb            r9,  [lr, r5]
+        bge             1f
+
+        mov             r12, #2
+        ldrb            r0,  [r4, #4]
+        rac_get_prob    r5,  r6,  r7,  r8,  r0,  r9,  r10
+        addge           r12, #1
+        ldrb            r9,  [lr, r5]
+        blt             4f
+        ldrb            r0,  [r4, #5]
+        rac_get_prob    r5,  r6,  r7,  r8,  r0,  r9,  r10
+        addge           r12, #1
+        ldrb            r9,  [lr, r5]
+        b               4f
+1:
+        ldrb            r0,  [r4, #6]
+        rac_get_prob    r5,  r6,  r7,  r8,  r0,  r9,  r10
+        ldrb            r9,  [lr, r5]
+        bge             3f
+
+        ldrb            r0,  [r4, #7]
+        rac_get_prob    r5,  r6,  r7,  r8,  r0,  r9,  r10
+        ldrb            r9,  [lr, r5]
+        bge             2f
+
+        mov             r12, #5
+        mov             r0,  #159
+        rac_get_prob    r5,  r6,  r7,  r8,  r0,  r9,  r10
+        addge           r12, r12, #1
+        ldrb            r9,  [lr, r5]
+        b               4f
+2:
+        mov             r12, #7
+        mov             r0,  #165
+        rac_get_prob    r5,  r6,  r7,  r8,  r0,  r9,  r10
+        addge           r12, r12, #2
+        ldrb            r9,  [lr, r5]
+        mov             r0,  #145
+        rac_get_prob    r5,  r6,  r7,  r8,  r0,  r9,  r10
+        addge           r12, r12, #1
+        ldrb            r9,  [lr, r5]
+        b               4f
+3:
+        ldrb            r0,  [r4, #8]
+        rac_get_prob    r5,  r6,  r7,  r8,  r0,  r9,  r10
+        addge           r4,  r4,  #1
+        ldrb            r9,  [lr, r5]
+        movge           r12, #2
+        movlt           r12, #0
+        ldrb            r0,  [r4, #9]
+        rac_get_prob    r5,  r6,  r7,  r8,  r0,  r9,  r10
+        mov             r9,  #8
+        addge           r12, r12, #1
+        movrel          r4,  ff_vp8_dct_cat_prob
+        lsl             r9,  r9,  r12
+        ldr             r4,  [r4, r12, lsl #2]
+        add             r12, r9,  #3
+        mov             r1,  #0
+        ldrb            r0,  [r4], #1
+1:
+        ldrb            r9,  [lr, r5]
+        lsl             r1,  r1,  #1
+        rac_get_prob    r5,  r6,  r7,  r8,  r0,  r9,  r10
+        ldrb            r0,  [r4], #1
+        addge           r1,  r1,  #1
+        cmp             r0,  #0
+        bne             1b
+        ldrb            r9,  [lr, r5]
+        add             r12, r12, r1
+        ldr             r1,  [sp, #4]
+4:
+        add             r4,  r3,  r3,  lsl #5
+        add             r4,  r2,  r4
+        add             r4,  r4,  #22
+        rac_get_128     r5,  r6,  r7,  r8,  r9,  r10
+        rsbge           r12, r12, #0
+        smulbb          r12, r12, r11
+        movrel          r9,  zigzag_scan-1
+        ldrb            r9,  [r9, r3]
+        cmp             r3,  #16
+        strh            r12, [r1, r9]
+        bge             6b
+        b               5b
+endfunc
+
+        .section        .rodata
+zigzag_scan:
+        .byte            0,  2,  8, 16
+        .byte           10,  4,  6, 12
+        .byte           18, 24, 26, 20
+        .byte           14, 22, 28, 30
diff --git a/libavcodec/arm/vp8dsp_init_arm.c b/libavcodec/arm/vp8dsp_init_arm.c
new file mode 100644
index 0000000..269c6e3
--- /dev/null
+++ b/libavcodec/arm/vp8dsp_init_arm.c
@@ -0,0 +1,163 @@
+/**
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <stdint.h>
+#include "libavcodec/vp8dsp.h"
+
+void ff_vp8_luma_dc_wht_neon(DCTELEM block[4][4][16], DCTELEM dc[16]);
+void ff_vp8_luma_dc_wht_dc_neon(DCTELEM block[4][4][16], DCTELEM dc[16]);
+
+void ff_vp8_idct_add_neon(uint8_t *dst, DCTELEM block[16], int stride);
+void ff_vp8_idct_dc_add_neon(uint8_t *dst, DCTELEM block[16], int stride);
+void ff_vp8_idct_dc_add4y_neon(uint8_t *dst, DCTELEM block[4][16], int stride);
+void ff_vp8_idct_dc_add4uv_neon(uint8_t *dst, DCTELEM block[4][16], int stride);
+
+void ff_vp8_v_loop_filter16_neon(uint8_t *dst, int stride,
+                                 int flim_E, int flim_I, int hev_thresh);
+void ff_vp8_h_loop_filter16_neon(uint8_t *dst, int stride,
+                                 int flim_E, int flim_I, int hev_thresh);
+void ff_vp8_v_loop_filter8uv_neon(uint8_t *dstU, uint8_t *dstV, int stride,
+                                  int flim_E, int flim_I, int hev_thresh);
+void ff_vp8_h_loop_filter8uv_neon(uint8_t *dstU, uint8_t *dstV, int stride,
+                                  int flim_E, int flim_I, int hev_thresh);
+
+void ff_vp8_v_loop_filter16_inner_neon(uint8_t *dst, int stride,
+                                       int flim_E, int flim_I, int hev_thresh);
+void ff_vp8_h_loop_filter16_inner_neon(uint8_t *dst, int stride,
+                                       int flim_E, int flim_I, int hev_thresh);
+void ff_vp8_v_loop_filter8uv_inner_neon(uint8_t *dstU, uint8_t *dstV,
+                                        int stride, int flim_E, int flim_I,
+                                        int hev_thresh);
+void ff_vp8_h_loop_filter8uv_inner_neon(uint8_t *dstU, uint8_t *dstV,
+                                        int stride, int flim_E, int flim_I,
+                                        int hev_thresh);
+
+void ff_vp8_v_loop_filter16_simple_neon(uint8_t *dst, int stride, int flim);
+void ff_vp8_h_loop_filter16_simple_neon(uint8_t *dst, int stride, int flim);
+
+
+#define VP8_MC(n)                                                       \
+    void ff_put_vp8_##n##_neon(uint8_t *dst, int dststride,             \
+                               uint8_t *src, int srcstride,             \
+                               int h, int x, int y)
+
+#define VP8_EPEL(w)                             \
+    VP8_MC(pixels ## w);                        \
+    VP8_MC(epel ## w ## _h4);                   \
+    VP8_MC(epel ## w ## _h6);                   \
+    VP8_MC(epel ## w ## _v4);                   \
+    VP8_MC(epel ## w ## _h4v4);                 \
+    VP8_MC(epel ## w ## _h6v4);                 \
+    VP8_MC(epel ## w ## _v6);                   \
+    VP8_MC(epel ## w ## _h4v6);                 \
+    VP8_MC(epel ## w ## _h6v6)
+
+VP8_EPEL(16);
+VP8_EPEL(8);
+VP8_EPEL(4);
+
+VP8_MC(bilin16_h);
+VP8_MC(bilin16_v);
+VP8_MC(bilin16_hv);
+VP8_MC(bilin8_h);
+VP8_MC(bilin8_v);
+VP8_MC(bilin8_hv);
+VP8_MC(bilin4_h);
+VP8_MC(bilin4_v);
+VP8_MC(bilin4_hv);
+
+av_cold void ff_vp8dsp_init_arm(VP8DSPContext *dsp)
+{
+    if (HAVE_NEON) {
+        dsp->vp8_luma_dc_wht    = ff_vp8_luma_dc_wht_neon;
+        dsp->vp8_luma_dc_wht_dc = ff_vp8_luma_dc_wht_dc_neon;
+
+        dsp->vp8_idct_add       = ff_vp8_idct_add_neon;
+        dsp->vp8_idct_dc_add    = ff_vp8_idct_dc_add_neon;
+        dsp->vp8_idct_dc_add4y  = ff_vp8_idct_dc_add4y_neon;
+        dsp->vp8_idct_dc_add4uv = ff_vp8_idct_dc_add4uv_neon;
+
+        dsp->vp8_v_loop_filter16y = ff_vp8_v_loop_filter16_neon;
+        dsp->vp8_h_loop_filter16y = ff_vp8_h_loop_filter16_neon;
+        dsp->vp8_v_loop_filter8uv = ff_vp8_v_loop_filter8uv_neon;
+        dsp->vp8_h_loop_filter8uv = ff_vp8_h_loop_filter8uv_neon;
+
+        dsp->vp8_v_loop_filter16y_inner = ff_vp8_v_loop_filter16_inner_neon;
+        dsp->vp8_h_loop_filter16y_inner = ff_vp8_h_loop_filter16_inner_neon;
+        dsp->vp8_v_loop_filter8uv_inner = ff_vp8_v_loop_filter8uv_inner_neon;
+        dsp->vp8_h_loop_filter8uv_inner = ff_vp8_h_loop_filter8uv_inner_neon;
+
+        dsp->vp8_v_loop_filter_simple = ff_vp8_v_loop_filter16_simple_neon;
+        dsp->vp8_h_loop_filter_simple = ff_vp8_h_loop_filter16_simple_neon;
+
+        dsp->put_vp8_epel_pixels_tab[0][0][0] = ff_put_vp8_pixels16_neon;
+        dsp->put_vp8_epel_pixels_tab[0][0][2] = ff_put_vp8_epel16_h6_neon;
+        dsp->put_vp8_epel_pixels_tab[0][2][0] = ff_put_vp8_epel16_v6_neon;
+        dsp->put_vp8_epel_pixels_tab[0][2][2] = ff_put_vp8_epel16_h6v6_neon;
+
+        dsp->put_vp8_epel_pixels_tab[1][0][0] = ff_put_vp8_pixels8_neon;
+        dsp->put_vp8_epel_pixels_tab[1][0][1] = ff_put_vp8_epel8_h4_neon;
+        dsp->put_vp8_epel_pixels_tab[1][0][2] = ff_put_vp8_epel8_h6_neon;
+        dsp->put_vp8_epel_pixels_tab[1][1][0] = ff_put_vp8_epel8_v4_neon;
+        dsp->put_vp8_epel_pixels_tab[1][1][1] = ff_put_vp8_epel8_h4v4_neon;
+        dsp->put_vp8_epel_pixels_tab[1][1][2] = ff_put_vp8_epel8_h6v4_neon;
+        dsp->put_vp8_epel_pixels_tab[1][2][0] = ff_put_vp8_epel8_v6_neon;
+        dsp->put_vp8_epel_pixels_tab[1][2][1] = ff_put_vp8_epel8_h4v6_neon;
+        dsp->put_vp8_epel_pixels_tab[1][2][2] = ff_put_vp8_epel8_h6v6_neon;
+
+        dsp->put_vp8_epel_pixels_tab[2][0][0] = ff_put_vp8_pixels4_neon;
+        dsp->put_vp8_epel_pixels_tab[2][0][1] = ff_put_vp8_epel4_h4_neon;
+        dsp->put_vp8_epel_pixels_tab[2][0][2] = ff_put_vp8_epel4_h6_neon;
+        dsp->put_vp8_epel_pixels_tab[2][1][0] = ff_put_vp8_epel4_v4_neon;
+        dsp->put_vp8_epel_pixels_tab[2][1][1] = ff_put_vp8_epel4_h4v4_neon;
+        dsp->put_vp8_epel_pixels_tab[2][1][2] = ff_put_vp8_epel4_h6v4_neon;
+        dsp->put_vp8_epel_pixels_tab[2][2][0] = ff_put_vp8_epel4_v6_neon;
+        dsp->put_vp8_epel_pixels_tab[2][2][1] = ff_put_vp8_epel4_h4v6_neon;
+        dsp->put_vp8_epel_pixels_tab[2][2][2] = ff_put_vp8_epel4_h6v6_neon;
+
+        dsp->put_vp8_bilinear_pixels_tab[0][0][0] = ff_put_vp8_pixels16_neon;
+        dsp->put_vp8_bilinear_pixels_tab[0][0][1] = ff_put_vp8_bilin16_h_neon;
+        dsp->put_vp8_bilinear_pixels_tab[0][0][2] = ff_put_vp8_bilin16_h_neon;
+        dsp->put_vp8_bilinear_pixels_tab[0][1][0] = ff_put_vp8_bilin16_v_neon;
+        dsp->put_vp8_bilinear_pixels_tab[0][1][1] = ff_put_vp8_bilin16_hv_neon;
+        dsp->put_vp8_bilinear_pixels_tab[0][1][2] = ff_put_vp8_bilin16_hv_neon;
+        dsp->put_vp8_bilinear_pixels_tab[0][2][0] = ff_put_vp8_bilin16_v_neon;
+        dsp->put_vp8_bilinear_pixels_tab[0][2][1] = ff_put_vp8_bilin16_hv_neon;
+        dsp->put_vp8_bilinear_pixels_tab[0][2][2] = ff_put_vp8_bilin16_hv_neon;
+
+        dsp->put_vp8_bilinear_pixels_tab[1][0][0] = ff_put_vp8_pixels8_neon;
+        dsp->put_vp8_bilinear_pixels_tab[1][0][1] = ff_put_vp8_bilin8_h_neon;
+        dsp->put_vp8_bilinear_pixels_tab[1][0][2] = ff_put_vp8_bilin8_h_neon;
+        dsp->put_vp8_bilinear_pixels_tab[1][1][0] = ff_put_vp8_bilin8_v_neon;
+        dsp->put_vp8_bilinear_pixels_tab[1][1][1] = ff_put_vp8_bilin8_hv_neon;
+        dsp->put_vp8_bilinear_pixels_tab[1][1][2] = ff_put_vp8_bilin8_hv_neon;
+        dsp->put_vp8_bilinear_pixels_tab[1][2][0] = ff_put_vp8_bilin8_v_neon;
+        dsp->put_vp8_bilinear_pixels_tab[1][2][1] = ff_put_vp8_bilin8_hv_neon;
+        dsp->put_vp8_bilinear_pixels_tab[1][2][2] = ff_put_vp8_bilin8_hv_neon;
+
+        dsp->put_vp8_bilinear_pixels_tab[2][0][0] = ff_put_vp8_pixels4_neon;
+        dsp->put_vp8_bilinear_pixels_tab[2][0][1] = ff_put_vp8_bilin4_h_neon;
+        dsp->put_vp8_bilinear_pixels_tab[2][0][2] = ff_put_vp8_bilin4_h_neon;
+        dsp->put_vp8_bilinear_pixels_tab[2][1][0] = ff_put_vp8_bilin4_v_neon;
+        dsp->put_vp8_bilinear_pixels_tab[2][1][1] = ff_put_vp8_bilin4_hv_neon;
+        dsp->put_vp8_bilinear_pixels_tab[2][1][2] = ff_put_vp8_bilin4_hv_neon;
+        dsp->put_vp8_bilinear_pixels_tab[2][2][0] = ff_put_vp8_bilin4_v_neon;
+        dsp->put_vp8_bilinear_pixels_tab[2][2][1] = ff_put_vp8_bilin4_hv_neon;
+        dsp->put_vp8_bilinear_pixels_tab[2][2][2] = ff_put_vp8_bilin4_hv_neon;
+    }
+}
diff --git a/libavcodec/arm/vp8dsp_neon.S b/libavcodec/arm/vp8dsp_neon.S
new file mode 100644
index 0000000..92b1ef4
--- /dev/null
+++ b/libavcodec/arm/vp8dsp_neon.S
@@ -0,0 +1,1912 @@
+/**
+ * VP8 NEON optimisations
+ *
+ * Copyright (c) 2010 Rob Clark <rob at ti.com>
+ * Copyright (c) 2011 Mans Rullgard <mans at mansr.com>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "asm.S"
+
+function ff_vp8_luma_dc_wht_neon, export=1
+        vld1.16         {q0-q1},  [r1,:128]
+        vmov.i16        q15, #0
+
+        vadd.i16        d4,  d0,  d3
+        vadd.i16        d6,  d1,  d2
+        vst1.16         {q15},    [r1,:128]!
+        vsub.i16        d7,  d1,  d2
+        vsub.i16        d5,  d0,  d3
+        vst1.16         {q15},    [r1,:128]
+        vadd.i16        q0,  q2,  q3
+        vsub.i16        q1,  q2,  q3
+
+        vmov.i16        q8, #3
+
+        vtrn.32         d0,  d2
+        vtrn.32         d1,  d3
+        vtrn.16         d0,  d1
+        vtrn.16         d2,  d3
+
+        vadd.i16        d0,  d0,  d16
+
+        vadd.i16        d4,  d0,  d3
+        vadd.i16        d6,  d1,  d2
+        vsub.i16        d7,  d1,  d2
+        vsub.i16        d5,  d0,  d3
+        vadd.i16        q0,  q2,  q3
+        vsub.i16        q1,  q2,  q3
+
+        vshr.s16        q0,  q0,  #3
+        vshr.s16        q1,  q1,  #3
+
+        mov             r3,  #32
+        vst1.16         {d0[0]},  [r0,:16], r3
+        vst1.16         {d1[0]},  [r0,:16], r3
+        vst1.16         {d2[0]},  [r0,:16], r3
+        vst1.16         {d3[0]},  [r0,:16], r3
+        vst1.16         {d0[1]},  [r0,:16], r3
+        vst1.16         {d1[1]},  [r0,:16], r3
+        vst1.16         {d2[1]},  [r0,:16], r3
+        vst1.16         {d3[1]},  [r0,:16], r3
+        vst1.16         {d0[2]},  [r0,:16], r3
+        vst1.16         {d1[2]},  [r0,:16], r3
+        vst1.16         {d2[2]},  [r0,:16], r3
+        vst1.16         {d3[2]},  [r0,:16], r3
+        vst1.16         {d0[3]},  [r0,:16], r3
+        vst1.16         {d1[3]},  [r0,:16], r3
+        vst1.16         {d2[3]},  [r0,:16], r3
+        vst1.16         {d3[3]},  [r0,:16], r3
+
+        bx              lr
+endfunc
+
+function ff_vp8_luma_dc_wht_dc_neon, export=1
+        ldrsh           r2,  [r1]
+        mov             r3,  #0
+        add             r2,  r2,  #3
+        strh            r3,  [r1]
+        asr             r2,  r2,  #3
+    .rept 16
+        strh            r2,  [r0], #32
+    .endr
+        bx              lr
+endfunc
+
+function ff_vp8_idct_add_neon, export=1
+        vld1.16         {q0-q1},  [r1,:128]
+        movw            r3,  #20091
+        movt            r3,  #35468/2
+        vdup.32         d4,  r3
+
+        vmull.s16       q12, d1,  d4[0]
+        vmull.s16       q13, d3,  d4[0]
+        vqdmulh.s16     d20, d1,  d4[1]
+        vqdmulh.s16     d23, d3,  d4[1]
+        vshrn.s32       d21, q12, #16
+        vshrn.s32       d22, q13, #16
+        vadd.s16        d21, d21, d1
+        vadd.s16        d22, d22, d3
+
+        vadd.s16        d16, d0,  d2
+        vsub.s16        d17, d0,  d2
+        vadd.s16        d18, d21, d23
+        vsub.s16        d19, d20, d22
+        vadd.s16        q0,  q8,  q9
+        vsub.s16        q1,  q8,  q9
+
+        vtrn.32         d0,  d3
+        vtrn.32         d1,  d2
+        vtrn.16         d0,  d1
+        vtrn.16         d3,  d2
+
+        vmov.i16        q15, #0
+        vmull.s16       q12, d1,  d4[0]
+        vst1.16         {q15},    [r1,:128]!
+        vmull.s16       q13, d2,  d4[0]
+        vst1.16         {q15},    [r1,:128]
+        vqdmulh.s16     d21, d1,  d4[1]
+        vqdmulh.s16     d23, d2,  d4[1]
+        vshrn.s32       d20, q12, #16
+        vshrn.s32       d22, q13, #16
+        vadd.i16        d20, d20, d1
+        vadd.i16        d22, d22, d2
+
+        vadd.i16        d16, d0,  d3
+        vsub.i16        d17, d0,  d3
+        vadd.i16        d18, d20, d23
+        vld1.32         {d20[]},  [r0,:32], r2
+        vsub.i16        d19, d21, d22
+        vld1.32         {d22[]},  [r0,:32], r2
+        vadd.s16        q0,  q8,  q9
+        vld1.32         {d23[]},  [r0,:32], r2
+        vsub.s16        q1,  q8,  q9
+        vld1.32         {d21[]},  [r0,:32], r2
+        vrshr.s16       q0,  q0,  #3
+        vtrn.32         q10, q11
+        vrshr.s16       q1,  q1,  #3
+
+        sub             r0,  r0,  r2,  lsl #2
+
+        vtrn.32         d0,  d3
+        vtrn.32         d1,  d2
+        vtrn.16         d0,  d1
+        vtrn.16         d3,  d2
+
+        vaddw.u8        q0,  q0,  d20
+        vaddw.u8        q1,  q1,  d21
+        vqmovun.s16     d0,  q0
+        vqmovun.s16     d1,  q1
+
+        vst1.32         {d0[0]},  [r0,:32], r2
+        vst1.32         {d0[1]},  [r0,:32], r2
+        vst1.32         {d1[1]},  [r0,:32], r2
+        vst1.32         {d1[0]},  [r0,:32], r2
+
+        bx              lr
+endfunc
+
+function ff_vp8_idct_dc_add_neon, export=1
+        mov             r3,  #0
+        ldrsh           r12, [r1]
+        strh            r3,  [r1]
+        vdup.16         q1,  r12
+        vrshr.s16       q1,  q1,  #3
+        vld1.32         {d0[]},   [r0,:32], r2
+        vld1.32         {d1[]},   [r0,:32], r2
+        vld1.32         {d0[1]},  [r0,:32], r2
+        vld1.32         {d1[1]},  [r0,:32], r2
+        vaddw.u8        q2,  q1,  d0
+        vaddw.u8        q3,  q1,  d1
+        sub             r0,  r0,  r2, lsl #2
+        vqmovun.s16     d0,  q2
+        vqmovun.s16     d1,  q3
+        vst1.32         {d0[0]},  [r0,:32], r2
+        vst1.32         {d1[0]},  [r0,:32], r2
+        vst1.32         {d0[1]},  [r0,:32], r2
+        vst1.32         {d1[1]},  [r0,:32], r2
+        bx              lr
+endfunc
+
+function ff_vp8_idct_dc_add4uv_neon, export=1
+        vmov.i16        d0,  #0
+        mov             r3,  #32
+        vld1.16         {d16[]},  [r1,:16]
+        vst1.16         {d0[0]},  [r1,:16], r3
+        vld1.16         {d17[]},  [r1,:16]
+        vst1.16         {d0[0]},  [r1,:16], r3
+        vld1.16         {d18[]},  [r1,:16]
+        vst1.16         {d0[0]},  [r1,:16], r3
+        vld1.16         {d19[]},  [r1,:16]
+        vst1.16         {d0[0]},  [r1,:16], r3
+        mov             r3,  r0
+        vrshr.s16       q8,  q8,  #3            @ dc >>= 3
+        vld1.8          {d0},     [r0,:64], r2
+        vrshr.s16       q9,  q9,  #3
+        vld1.8          {d1},     [r0,:64], r2
+        vaddw.u8        q10, q8,  d0
+        vld1.8          {d2},     [r0,:64], r2
+        vaddw.u8        q0,  q8,  d1
+        vld1.8          {d3},     [r0,:64], r2
+        vaddw.u8        q11, q8,  d2
+        vld1.8          {d4},     [r0,:64], r2
+        vaddw.u8        q1,  q8,  d3
+        vld1.8          {d5},     [r0,:64], r2
+        vaddw.u8        q12, q9,  d4
+        vld1.8          {d6},     [r0,:64], r2
+        vaddw.u8        q2,  q9,  d5
+        vld1.8          {d7},     [r0,:64], r2
+        vaddw.u8        q13, q9,  d6
+        vqmovun.s16     d20, q10
+        vaddw.u8        q3,  q9,  d7
+        vqmovun.s16     d21, q0
+        vqmovun.s16     d22, q11
+        vst1.8          {d20},    [r3,:64], r2
+        vqmovun.s16     d23, q1
+        vst1.8          {d21},    [r3,:64], r2
+        vqmovun.s16     d24, q12
+        vst1.8          {d22},    [r3,:64], r2
+        vqmovun.s16     d25, q2
+        vst1.8          {d23},    [r3,:64], r2
+        vqmovun.s16     d26, q13
+        vst1.8          {d24},    [r3,:64], r2
+        vqmovun.s16     d27, q3
+        vst1.8          {d25},    [r3,:64], r2
+        vst1.8          {d26},    [r3,:64], r2
+        vst1.8          {d27},    [r3,:64], r2
+
+        bx              lr
+endfunc
+
+function ff_vp8_idct_dc_add4y_neon, export=1
+        vmov.i16        d0,  #0
+        mov             r3,  #32
+        vld1.16         {d16[]},  [r1,:16]
+        vst1.16         {d0[0]},  [r1,:16], r3
+        vld1.16         {d17[]},  [r1,:16]
+        vst1.16         {d0[0]},  [r1,:16], r3
+        vld1.16         {d18[]},  [r1,:16]
+        vst1.16         {d0[0]},  [r1,:16], r3
+        vld1.16         {d19[]},  [r1,:16]
+        vst1.16         {d0[0]},  [r1,:16], r3
+        vrshr.s16       q8,  q8,  #3            @ dc >>= 3
+        vld1.8          {q0},     [r0,:128], r2
+        vrshr.s16       q9,  q9,  #3
+        vld1.8          {q1},     [r0,:128], r2
+        vaddw.u8        q10, q8,  d0
+        vld1.8          {q2},     [r0,:128], r2
+        vaddw.u8        q0,  q9,  d1
+        vld1.8          {q3},     [r0,:128], r2
+        vaddw.u8        q11, q8,  d2
+        vaddw.u8        q1,  q9,  d3
+        vaddw.u8        q12, q8,  d4
+        vaddw.u8        q2,  q9,  d5
+        vaddw.u8        q13, q8,  d6
+        vaddw.u8        q3,  q9,  d7
+        sub             r0,  r0,  r2,  lsl #2
+        vqmovun.s16     d20, q10
+        vqmovun.s16     d21, q0
+        vqmovun.s16     d22, q11
+        vqmovun.s16     d23, q1
+        vqmovun.s16     d24, q12
+        vst1.8          {q10},    [r0,:128], r2
+        vqmovun.s16     d25, q2
+        vst1.8          {q11},    [r0,:128], r2
+        vqmovun.s16     d26, q13
+        vst1.8          {q12},    [r0,:128], r2
+        vqmovun.s16     d27, q3
+        vst1.8          {q13},    [r0,:128], r2
+
+        bx              lr
+endfunc
+
+@ Register layout:
+@   P3..Q3 -> q0..q7
+@   flim_E -> q14
+@   flim_I -> q15
+@   hev_thresh -> r12
+@
+.macro  vp8_loop_filter, inner=0, simple=0
+    .if \simple
+        vabd.u8         q9,  q3,  q4            @ abs(P0-Q0)
+        vabd.u8         q15, q2,  q5            @ abs(P1-Q1)
+        vqadd.u8        q9,  q9,  q9            @ abs(P0-Q0) * 2
+        vshr.u8         q10, q15, #1            @ abs(P1-Q1) / 2
+        vqadd.u8        q11, q9,  q10           @ (abs(P0-Q0)*2) + (abs(P1-Q1)/2)
+        vmov.i8         q13, #0x80
+        vcle.u8         q8,  q11, q14           @ (abs(P0-Q0)*2) + (abs(P1-Q1)/2) <= flim
+    .else
+        @ calculate hev and normal_limit:
+        vabd.u8         q12, q2,  q3            @ abs(P1-P0)
+        vabd.u8         q13, q5,  q4            @ abs(Q1-Q0)
+        vabd.u8         q10, q0,  q1            @ abs(P3-P2)
+        vabd.u8         q11, q1,  q2            @ abs(P2-P1)
+        vcle.u8         q8,  q12, q15           @ abs(P1-P0) <= flim_I
+        vcle.u8         q9,  q13, q15           @ abs(Q1-Q0) <= flim_I
+        vcle.u8         q10, q10, q15           @ abs(P3-P2) <= flim_I
+        vcle.u8         q11, q11, q15           @ abs(P2-P1) <= flim_I
+        vand            q8,  q8,  q9
+        vabd.u8         q9,  q7,  q6            @ abs(Q3-Q2)
+        vand            q8,  q8,  q11
+        vabd.u8         q11, q6,  q5            @ abs(Q2-Q1)
+        vand            q8,  q8,  q10
+        vcle.u8         q10, q9,  q15           @ abs(Q3-Q2) <= flim_I
+        vcle.u8         q11, q11, q15           @ abs(Q2-Q1) <= flim_I
+        vabd.u8         q9,  q3,  q4            @ abs(P0-Q0)
+        vabd.u8         q15, q2,  q5            @ abs(P1-Q1)
+        vand            q8,  q8,  q10
+        vqadd.u8        q9,  q9,  q9            @ abs(P0-Q0) * 2
+        vand            q8,  q8,  q11
+        vshr.u8         q10, q15, #1            @ abs(P1-Q1) / 2
+        vdup.8          q15, r12                @ hev_thresh
+        vqadd.u8        q11, q9,  q10           @ (abs(P0-Q0)*2) + (abs(P1-Q1)/2)
+        vcgt.u8         q12, q12, q15           @ abs(P1-P0) > hev_thresh
+        vcle.u8         q11, q11, q14           @ (abs(P0-Q0)*2) + (abs(P1-Q1)/2) <= flim_E
+        vcgt.u8         q14, q13, q15           @ abs(Q1-Q0) > hev_thresh
+        vand            q8,  q8,  q11
+        vmov.i8         q13, #0x80
+        vorr            q9,  q12, q14
+    .endif
+
+        @ at this point:
+        @   q8: normal_limit
+        @   q9: hev
+
+        @ convert to signed value:
+        veor            q3,  q3,  q13           @ PS0 = P0 ^ 0x80
+        veor            q4,  q4,  q13           @ QS0 = Q0 ^ 0x80
+
+        vmov.i16        q12, #3
+        vsubl.s8        q10, d8,  d6            @ QS0 - PS0
+        vsubl.s8        q11, d9,  d7            @   (widened to 16bit)
+        veor            q2,  q2,  q13           @ PS1 = P1 ^ 0x80
+        veor            q5,  q5,  q13           @ QS1 = Q1 ^ 0x80
+        vmul.i16        q10, q10, q12           @ w = 3 * (QS0 - PS0)
+        vmul.i16        q11, q11, q12
+
+        vqsub.s8        q12, q2,  q5            @ clamp(PS1-QS1)
+        vmov.i8         q14, #4
+        vmov.i8         q15, #3
+    .if \inner
+        vand            q12, q12, q9            @ if(hev) w += clamp(PS1-QS1)
+    .endif
+        vaddw.s8        q10, q10, d24           @ w += clamp(PS1-QS1)
+        vaddw.s8        q11, q11, d25
+        vqmovn.s16      d20, q10                @ narrow result back into q10
+        vqmovn.s16      d21, q11
+    .if !\inner && !\simple
+        veor            q1,  q1,  q13           @ PS2 = P2 ^ 0x80
+        veor            q6,  q6,  q13           @ QS2 = Q2 ^ 0x80
+    .endif
+        vand            q10, q10, q8            @ w &= normal_limit
+
+        @ registers used at this point..
+        @   q0 -> P3  (don't corrupt)
+        @   q1-q6 -> PS2-QS2
+        @   q7 -> Q3  (don't corrupt)
+        @   q9 -> hev
+        @   q10 -> w
+        @   q13 -> #0x80
+        @   q14 -> #4
+        @   q15 -> #3
+        @   q8, q11, q12 -> unused
+
+        @ filter_common:   is4tap==1
+        @   c1 = clamp(w + 4) >> 3;
+        @   c2 = clamp(w + 3) >> 3;
+        @   Q0 = s2u(QS0 - c1);
+        @   P0 = s2u(PS0 + c2);
+
+    .if \simple
+        vqadd.s8        q11, q10, q14           @ c1 = clamp((w&hev)+4)
+        vqadd.s8        q12, q10, q15           @ c2 = clamp((w&hev)+3)
+        vshr.s8         q11, q11, #3            @ c1 >>= 3
+        vshr.s8         q12, q12, #3            @ c2 >>= 3
+        vqsub.s8        q4,  q4,  q11           @ QS0 = clamp(QS0-c1)
+        vqadd.s8        q3,  q3,  q12           @ PS0 = clamp(PS0+c2)
+        veor            q4,  q4,  q13           @ Q0 = QS0 ^ 0x80
+        veor            q3,  q3,  q13           @ P0 = PS0 ^ 0x80
+        veor            q5,  q5,  q13           @ Q1 = QS1 ^ 0x80
+        veor            q2,  q2,  q13           @ P1 = PS1 ^ 0x80
+    .elseif \inner
+        @ the !is4tap case of filter_common, only used for inner blocks
+        @   c3 = ((c1&~hev) + 1) >> 1;
+        @   Q1 = s2u(QS1 - c3);
+        @   P1 = s2u(PS1 + c3);
+        vqadd.s8        q11, q10, q14           @ c1 = clamp((w&hev)+4)
+        vqadd.s8        q12, q10, q15           @ c2 = clamp((w&hev)+3)
+        vshr.s8         q11, q11, #3            @ c1 >>= 3
+        vshr.s8         q12, q12, #3            @ c2 >>= 3
+        vqsub.s8        q4,  q4,  q11           @ QS0 = clamp(QS0-c1)
+        vqadd.s8        q3,  q3,  q12           @ PS0 = clamp(PS0+c2)
+        vbic            q11, q11, q9            @ c1 & ~hev
+        veor            q4,  q4,  q13           @ Q0 = QS0 ^ 0x80
+        vrshr.s8        q11, q11, #1            @ c3 >>= 1
+        veor            q3,  q3,  q13           @ P0 = PS0 ^ 0x80
+        vqsub.s8        q5,  q5,  q11           @ QS1 = clamp(QS1-c3)
+        vqadd.s8        q2,  q2,  q11           @ PS1 = clamp(PS1+c3)
+        veor            q5,  q5,  q13           @ Q1 = QS1 ^ 0x80
+        veor            q2,  q2,  q13           @ P1 = PS1 ^ 0x80
+    .else
+        vand            q12, q10, q9            @ w & hev
+        vqadd.s8        q11, q12, q14           @ c1 = clamp((w&hev)+4)
+        vqadd.s8        q12, q12, q15           @ c2 = clamp((w&hev)+3)
+        vshr.s8         q11, q11, #3            @ c1 >>= 3
+        vshr.s8         q12, q12, #3            @ c2 >>= 3
+        vbic            q10, q10, q9            @ w &= ~hev
+        vqsub.s8        q4,  q4,  q11           @ QS0 = clamp(QS0-c1)
+        vqadd.s8        q3,  q3,  q12           @ PS0 = clamp(PS0+c2)
+
+        @ filter_mbedge:
+        @   a = clamp((27*w + 63) >> 7);
+        @   Q0 = s2u(QS0 - a);
+        @   P0 = s2u(PS0 + a);
+        @   a = clamp((18*w + 63) >> 7);
+        @   Q1 = s2u(QS1 - a);
+        @   P1 = s2u(PS1 + a);
+        @   a = clamp((9*w + 63) >> 7);
+        @   Q2 = s2u(QS2 - a);
+        @   P2 = s2u(PS2 + a);
+        vmov.i16        q9,  #63
+        vshll.s8        q14, d20, #3
+        vshll.s8        q15, d21, #3
+        vaddw.s8        q14, q14, d20
+        vaddw.s8        q15, q15, d21
+        vadd.s16        q8,  q9,  q14
+        vadd.s16        q9,  q9,  q15           @  9*w + 63
+        vadd.s16        q11, q8,  q14
+        vadd.s16        q12, q9,  q15           @ 18*w + 63
+        vadd.s16        q14, q11, q14
+        vadd.s16        q15, q12, q15           @ 27*w + 63
+        vqshrn.s16      d16, q8,  #7
+        vqshrn.s16      d17, q9,  #7            @ clamp(( 9*w + 63)>>7)
+        vqshrn.s16      d22, q11, #7
+        vqshrn.s16      d23, q12, #7            @ clamp((18*w + 63)>>7)
+        vqshrn.s16      d28, q14, #7
+        vqshrn.s16      d29, q15, #7            @ clamp((27*w + 63)>>7)
+        vqadd.s8        q1,  q1,  q8            @ PS2 = clamp(PS2+a)
+        vqsub.s8        q6,  q6,  q8            @ QS2 = clamp(QS2-a)
+        vqadd.s8        q2,  q2,  q11           @ PS1 = clamp(PS1+a)
+        vqsub.s8        q5,  q5,  q11           @ QS1 = clamp(QS1-a)
+        vqadd.s8        q3,  q3,  q14           @ PS0 = clamp(PS0+a)
+        vqsub.s8        q4,  q4,  q14           @ QS0 = clamp(QS0-a)
+        veor            q3,  q3,  q13           @ P0 = PS0 ^ 0x80
+        veor            q4,  q4,  q13           @ Q0 = QS0 ^ 0x80
+        veor            q2,  q2,  q13           @ P1 = PS1 ^ 0x80
+        veor            q5,  q5,  q13           @ Q1 = QS1 ^ 0x80
+        veor            q1,  q1,  q13           @ P2 = PS2 ^ 0x80
+        veor            q6,  q6,  q13           @ Q2 = QS2 ^ 0x80
+    .endif
+.endm
+
+.macro transpose8x16matrix
+        vtrn.32         q0,   q4
+        vtrn.32         q1,   q5
+        vtrn.32         q2,   q6
+        vtrn.32         q3,   q7
+
+        vtrn.16         q0,   q2
+        vtrn.16         q1,   q3
+        vtrn.16         q4,   q6
+        vtrn.16         q5,   q7
+
+        vtrn.8          q0,   q1
+        vtrn.8          q2,   q3
+        vtrn.8          q4,   q5
+        vtrn.8          q6,   q7
+.endm
+
+.macro  vp8_v_loop_filter16 name, inner=0, simple=0
+function ff_vp8_v_loop_filter16\name\()_neon, export=1
+        vpush           {q4-q7}
+        sub             r0,  r0,  r1,  lsl #1+!\simple
+
+        @ Load pixels:
+    .if !\simple
+        ldr             r12, [sp, #64]          @ hev_thresh
+        vld1.8          {q0},     [r0,:128], r1 @ P3
+        vld1.8          {q1},     [r0,:128], r1 @ P2
+    .endif
+        vld1.8          {q2},     [r0,:128], r1 @ P1
+        vld1.8          {q3},     [r0,:128], r1 @ P0
+        vld1.8          {q4},     [r0,:128], r1 @ Q0
+        vld1.8          {q5},     [r0,:128], r1 @ Q1
+    .if !\simple
+        vld1.8          {q6},     [r0,:128], r1 @ Q2
+        vld1.8          {q7},     [r0,:128]     @ Q3
+        vdup.8          q15, r3                 @ flim_I
+    .endif
+        vdup.8          q14, r2                 @ flim_E
+
+        vp8_loop_filter inner=\inner, simple=\simple
+
+        @ back up to P2:  dst -= stride * 6
+        sub             r0,  r0,  r1,  lsl #2
+    .if !\simple
+        sub             r0,  r0,  r1,  lsl #1
+
+        @ Store pixels:
+        vst1.8          {q1},     [r0,:128], r1 @ P2
+    .endif
+        vst1.8          {q2},     [r0,:128], r1 @ P1
+        vst1.8          {q3},     [r0,:128], r1 @ P0
+        vst1.8          {q4},     [r0,:128], r1 @ Q0
+        vst1.8          {q5},     [r0,:128], r1 @ Q1
+    .if !\simple
+        vst1.8          {q6},     [r0,:128]     @ Q2
+    .endif
+
+        vpop            {q4-q7}
+        bx              lr
+endfunc
+.endm
+
+vp8_v_loop_filter16
+vp8_v_loop_filter16 _inner,  inner=1
+vp8_v_loop_filter16 _simple, simple=1
+
+.macro  vp8_v_loop_filter8uv name, inner=0
+function ff_vp8_v_loop_filter8uv\name\()_neon, export=1
+        vpush           {q4-q7}
+        sub             r0,  r0,  r2,  lsl #2
+        sub             r1,  r1,  r2,  lsl #2
+        ldr             r12, [sp, #64]          @ flim_I
+
+        @ Load pixels:
+        vld1.8          {d0},     [r0,:64], r2  @ P3
+        vld1.8          {d1},     [r1,:64], r2  @ P3
+        vld1.8          {d2},     [r0,:64], r2  @ P2
+        vld1.8          {d3},     [r1,:64], r2  @ P2
+        vld1.8          {d4},     [r0,:64], r2  @ P1
+        vld1.8          {d5},     [r1,:64], r2  @ P1
+        vld1.8          {d6},     [r0,:64], r2  @ P0
+        vld1.8          {d7},     [r1,:64], r2  @ P0
+        vld1.8          {d8},     [r0,:64], r2  @ Q0
+        vld1.8          {d9},     [r1,:64], r2  @ Q0
+        vld1.8          {d10},    [r0,:64], r2  @ Q1
+        vld1.8          {d11},    [r1,:64], r2  @ Q1
+        vld1.8          {d12},    [r0,:64], r2  @ Q2
+        vld1.8          {d13},    [r1,:64], r2  @ Q2
+        vld1.8          {d14},    [r0,:64]      @ Q3
+        vld1.8          {d15},    [r1,:64]      @ Q3
+
+        vdup.8          q14, r3                 @ flim_E
+        vdup.8          q15, r12                @ flim_I
+        ldr             r12, [sp, #68]          @ hev_thresh
+
+        vp8_loop_filter inner=\inner
+
+        @ back up to P2:  u,v -= stride * 6
+        sub             r0,  r0,  r2,  lsl #2
+        sub             r1,  r1,  r2,  lsl #2
+        sub             r0,  r0,  r2,  lsl #1
+        sub             r1,  r1,  r2,  lsl #1
+
+        @ Store pixels:
+        vst1.8          {d2},     [r0,:64], r2  @ P2
+        vst1.8          {d3},     [r1,:64], r2  @ P2
+        vst1.8          {d4},     [r0,:64], r2  @ P1
+        vst1.8          {d5},     [r1,:64], r2  @ P1
+        vst1.8          {d6},     [r0,:64], r2  @ P0
+        vst1.8          {d7},     [r1,:64], r2  @ P0
+        vst1.8          {d8},     [r0,:64], r2  @ Q0
+        vst1.8          {d9},     [r1,:64], r2  @ Q0
+        vst1.8          {d10},    [r0,:64], r2  @ Q1
+        vst1.8          {d11},    [r1,:64], r2  @ Q1
+        vst1.8          {d12},    [r0,:64]      @ Q2
+        vst1.8          {d13},    [r1,:64]      @ Q2
+
+        vpop            {q4-q7}
+        bx              lr
+endfunc
+.endm
+
+vp8_v_loop_filter8uv
+vp8_v_loop_filter8uv _inner, inner=1
+
+.macro  vp8_h_loop_filter16 name, inner=0, simple=0
+function ff_vp8_h_loop_filter16\name\()_neon, export=1
+        vpush           {q4-q7}
+        sub             r0,  r0,  #4
+    .if !\simple
+        ldr             r12, [sp, #64]          @ hev_thresh
+    .endif
+
+        @ Load pixels:
+        vld1.8          {d0},     [r0], r1      @ load first 8-line src data
+        vld1.8          {d2},     [r0], r1
+        vld1.8          {d4},     [r0], r1
+        vld1.8          {d6},     [r0], r1
+        vld1.8          {d8},     [r0], r1
+        vld1.8          {d10},    [r0], r1
+        vld1.8          {d12},    [r0], r1
+        vld1.8          {d14},    [r0], r1
+        vld1.8          {d1},     [r0], r1      @ load second 8-line src data
+        vld1.8          {d3},     [r0], r1
+        vld1.8          {d5},     [r0], r1
+        vld1.8          {d7},     [r0], r1
+        vld1.8          {d9},     [r0], r1
+        vld1.8          {d11},    [r0], r1
+        vld1.8          {d13},    [r0], r1
+        vld1.8          {d15},    [r0], r1
+
+        transpose8x16matrix
+
+        vdup.8          q14, r2                 @ flim_E
+    .if !\simple
+        vdup.8          q15, r3                 @ flim_I
+    .endif
+
+        vp8_loop_filter inner=\inner, simple=\simple
+
+        sub             r0,  r0,  r1, lsl #4    @ backup 16 rows
+
+        transpose8x16matrix
+
+        @ Store pixels:
+        vst1.8          {d0},     [r0],     r1
+        vst1.8          {d2},     [r0],     r1
+        vst1.8          {d4},     [r0],     r1
+        vst1.8          {d6},     [r0],     r1
+        vst1.8          {d8},     [r0],     r1
+        vst1.8          {d10},    [r0],     r1
+        vst1.8          {d12},    [r0],     r1
+        vst1.8          {d14},    [r0],     r1
+        vst1.8          {d1},     [r0],     r1
+        vst1.8          {d3},     [r0],     r1
+        vst1.8          {d5},     [r0],     r1
+        vst1.8          {d7},     [r0],     r1
+        vst1.8          {d9},     [r0],     r1
+        vst1.8          {d11},    [r0],     r1
+        vst1.8          {d13},    [r0],     r1
+        vst1.8          {d15},    [r0]
+
+        vpop            {q4-q7}
+        bx              lr
+endfunc
+.endm
+
+vp8_h_loop_filter16
+vp8_h_loop_filter16 _inner,  inner=1
+vp8_h_loop_filter16 _simple, simple=1
+
+.macro  vp8_h_loop_filter8uv name, inner=0
+function ff_vp8_h_loop_filter8uv\name\()_neon, export=1
+        vpush           {q4-q7}
+        sub             r0,  r0,  #4
+        sub             r1,  r1,  #4
+        ldr             r12, [sp, #64]          @ flim_I
+
+        @ Load pixels:
+        vld1.8          {d0},     [r0], r2      @ load u
+        vld1.8          {d1},     [r1], r2      @ load v
+        vld1.8          {d2},     [r0], r2
+        vld1.8          {d3},     [r1], r2
+        vld1.8          {d4},     [r0], r2
+        vld1.8          {d5},     [r1], r2
+        vld1.8          {d6},     [r0], r2
+        vld1.8          {d7},     [r1], r2
+        vld1.8          {d8},     [r0], r2
+        vld1.8          {d9},     [r1], r2
+        vld1.8          {d10},    [r0], r2
+        vld1.8          {d11},    [r1], r2
+        vld1.8          {d12},    [r0], r2
+        vld1.8          {d13},    [r1], r2
+        vld1.8          {d14},    [r0], r2
+        vld1.8          {d15},    [r1], r2
+
+        transpose8x16matrix
+
+        vdup.8          q14, r3                 @ flim_E
+        vdup.8          q15, r12                @ flim_I
+        ldr             r12, [sp, #68]          @ hev_thresh
+
+        vp8_loop_filter inner=\inner
+
+        sub             r0,  r0,  r2, lsl #3    @ backup u 8 rows
+        sub             r1,  r1,  r2, lsl #3    @ backup v 8 rows
+
+        transpose8x16matrix
+
+        @ Store pixels:
+        vst1.8          {d0},     [r0], r2
+        vst1.8          {d1},     [r1], r2
+        vst1.8          {d2},     [r0], r2
+        vst1.8          {d3},     [r1], r2
+        vst1.8          {d4},     [r0], r2
+        vst1.8          {d5},     [r1], r2
+        vst1.8          {d6},     [r0], r2
+        vst1.8          {d7},     [r1], r2
+        vst1.8          {d8},     [r0], r2
+        vst1.8          {d9},     [r1], r2
+        vst1.8          {d10},    [r0], r2
+        vst1.8          {d11},    [r1], r2
+        vst1.8          {d12},    [r0], r2
+        vst1.8          {d13},    [r1], r2
+        vst1.8          {d14},    [r0]
+        vst1.8          {d15},    [r1]
+
+        vpop            {q4-q7}
+        bx              lr
+endfunc
+.endm
+
+vp8_h_loop_filter8uv
+vp8_h_loop_filter8uv _inner, inner=1
+
+function ff_put_vp8_pixels16_neon, export=1
+        ldr             r12, [sp, #0]           @ h
+1:
+        subs            r12, r12, #4
+        vld1.8          {q0},     [r2], r3
+        vld1.8          {q1},     [r2], r3
+        vld1.8          {q2},     [r2], r3
+        vld1.8          {q3},     [r2], r3
+        vst1.8          {q0},     [r0,:128], r1
+        vst1.8          {q1},     [r0,:128], r1
+        vst1.8          {q2},     [r0,:128], r1
+        vst1.8          {q3},     [r0,:128], r1
+        bgt             1b
+        bx              lr
+endfunc
+
+function ff_put_vp8_pixels8_neon, export=1
+        ldr             r12, [sp, #0]           @ h
+1:
+        subs            r12, r12, #4
+        vld1.8          {d0},     [r2], r3
+        vld1.8          {d1},     [r2], r3
+        vld1.8          {d2},     [r2], r3
+        vld1.8          {d3},     [r2], r3
+        vst1.8          {d0},     [r0,:64], r1
+        vst1.8          {d1},     [r0,:64], r1
+        vst1.8          {d2},     [r0,:64], r1
+        vst1.8          {d3},     [r0,:64], r1
+        bgt             1b
+        bx              lr
+endfunc
+
+function ff_put_vp8_pixels4_neon, export=1
+        ldr             r12, [sp, #0]           @ h
+        push            {r4-r6,lr}
+1:
+        subs            r12, r12, #4
+        ldr             r4,       [r2], r3
+        ldr             r5,       [r2], r3
+        ldr             r6,       [r2], r3
+        ldr             lr,       [r2], r3
+        str             r4,       [r0], r1
+        str             r5,       [r0], r1
+        str             r6,       [r0], r1
+        str             lr,       [r0], r1
+        bgt             1b
+        pop             {r4-r6,pc}
+endfunc
+
+/* 4/6-tap 8th-pel MC */
+
+.macro  vp8_epel8_h6    d,   a,   b
+        vext.8          d27, \a,  \b,  #1
+        vmovl.u8        q8,  \a
+        vext.8          d28, \a,  \b,  #2
+        vmovl.u8        q9,  d27
+        vext.8          d29, \a,  \b,  #3
+        vmovl.u8        q10, d28
+        vext.8          d30, \a,  \b,  #4
+        vmovl.u8        q11, d29
+        vext.8          d31, \a,  \b,  #5
+        vmovl.u8        q12, d30
+        vmul.u16        q10, q10, d0[2]
+        vmovl.u8        q13, d31
+        vmul.u16        q11, q11, d0[3]
+        vmls.u16        q10, q9,  d0[1]
+        vmls.u16        q11, q12, d1[0]
+        vmla.u16        q10, q8,  d0[0]
+        vmla.u16        q11, q13, d1[1]
+        vqadd.s16       q11, q10, q11
+        vqrshrun.s16    \d,  q11, #7
+.endm
+
+.macro  vp8_epel16_h6   d0,  d1,  s0,  s1,  s2,  q0,  q1
+        vext.8          q14, \q0, \q1, #3
+        vext.8          q15, \q0, \q1, #4
+        vmovl.u8        q11, d28
+        vmovl.u8        q14, d29
+        vext.8          q3,  \q0, \q1, #2
+        vmovl.u8        q12, d30
+        vmovl.u8        q15, d31
+        vext.8          q8,  \q0, \q1, #1
+        vmovl.u8        q10, d6
+        vmovl.u8        q3,  d7
+        vext.8          q2,  \q0, \q1, #5
+        vmovl.u8        q13, d4
+        vmovl.u8        q2,  d5
+        vmovl.u8        q9,  d16
+        vmovl.u8        q8,  d17
+        vmul.u16        q11, q11, d0[3]
+        vmul.u16        q10, q10, d0[2]
+        vmul.u16        q3,  q3,  d0[2]
+        vmul.u16        q14, q14, d0[3]
+        vmls.u16        q11, q12, d1[0]
+        vmovl.u8        q12, \s0
+        vmovl.u8        q1,  \s1
+        vmls.u16        q10, q9,  d0[1]
+        vmls.u16        q3,  q8,  d0[1]
+        vmls.u16        q14, q15, d1[0]
+        vmla.u16        q10, q12, d0[0]
+        vmla.u16        q11, q13, d1[1]
+        vmla.u16        q3,  q1,  d0[0]
+        vmla.u16        q14, q2,  d1[1]
+        vqadd.s16       q11, q10, q11
+        vqadd.s16       q14, q3,  q14
+        vqrshrun.s16    \d0, q11, #7
+        vqrshrun.s16    \d1, q14, #7
+.endm
+
+.macro  vp8_epel8_v6    d0,  s0,  s1,  s2,  s3,  s4,  s5
+        vmovl.u8        q10, \s2
+        vmovl.u8        q11, \s3
+        vmovl.u8        q9,  \s1
+        vmovl.u8        q12, \s4
+        vmovl.u8        q8,  \s0
+        vmovl.u8        q13, \s5
+        vmul.u16        q10, q10, d0[2]
+        vmul.u16        q11, q11, d0[3]
+        vmls.u16        q10, q9,  d0[1]
+        vmls.u16        q11, q12, d1[0]
+        vmla.u16        q10, q8,  d0[0]
+        vmla.u16        q11, q13, d1[1]
+        vqadd.s16       q11, q10, q11
+        vqrshrun.s16    \d0, q11, #7
+.endm
+
+.macro  vp8_epel8_v6_y2 d0, d1, s0, s1, s2, s3, s4, s5, s6
+        vmovl.u8        q10, \s0
+        vmovl.u8        q11, \s3
+        vmovl.u8        q14, \s6
+        vmovl.u8        q9,  \s1
+        vmovl.u8        q12, \s4
+        vmovl.u8        q8,  \s2
+        vmovl.u8        q13, \s5
+        vmul.u16        q10, q10, d0[0]
+        vmul.u16        q15, q11, d0[3]
+        vmul.u16        q11, q11, d0[2]
+        vmul.u16        q14, q14, d1[1]
+        vmls.u16        q10, q9,  d0[1]
+        vmls.u16        q15, q12, d1[0]
+        vmls.u16        q11, q8,  d0[1]
+        vmls.u16        q14, q13, d1[0]
+        vmla.u16        q10, q8,  d0[2]
+        vmla.u16        q15, q13, d1[1]
+        vmla.u16        q11, q9,  d0[0]
+        vmla.u16        q14, q12, d0[3]
+        vqadd.s16       q15, q10, q15
+        vqadd.s16       q14, q11, q14
+        vqrshrun.s16    \d0, q15, #7
+        vqrshrun.s16    \d1, q14, #7
+.endm
+
+.macro  vp8_epel8_h4    d,   a,   b
+        vext.8          d28, \a,  \b,  #1
+        vmovl.u8        q9,  \a
+        vext.8          d29, \a,  \b,  #2
+        vmovl.u8        q10, d28
+        vext.8          d30, \a,  \b,  #3
+        vmovl.u8        q11, d29
+        vmovl.u8        q12, d30
+        vmul.u16        q10, q10, d0[2]
+        vmul.u16        q11, q11, d0[3]
+        vmls.u16        q10, q9,  d0[1]
+        vmls.u16        q11, q12, d1[0]
+        vqadd.s16       q11, q10, q11
+        vqrshrun.s16    \d,  q11, #7
+.endm
+
+.macro  vp8_epel8_v4_y2 d0,  d1,  s0,  s1,  s2,  s3,  s4
+        vmovl.u8        q9,  \s0
+        vmovl.u8        q10, \s1
+        vmovl.u8        q11, \s2
+        vmovl.u8        q12, \s3
+        vmovl.u8        q13, \s4
+        vmul.u16        q8,  q10, d0[2]
+        vmul.u16        q14, q11, d0[3]
+        vmul.u16        q11, q11, d0[2]
+        vmul.u16        q15, q12, d0[3]
+        vmls.u16        q8,  q9,  d0[1]
+        vmls.u16        q14, q12, d1[0]
+        vmls.u16        q11, q10, d0[1]
+        vmls.u16        q15, q13, d1[0]
+        vqadd.s16       q8,  q8,  q14
+        vqadd.s16       q11, q11, q15
+        vqrshrun.s16    \d0, q8,  #7
+        vqrshrun.s16    \d1, q11, #7
+.endm
+
+function ff_put_vp8_epel16_v6_neon, export=1
+        sub             r2,  r2,  r3,  lsl #1
+        push            {r4,lr}
+        vpush           {d8-d15}
+
+        ldr             r4,  [sp, #80]          @ my
+        movrel          lr,  subpel_filters-16
+        ldr             r12, [sp, #72]          @ h
+        add             r4,  lr,  r4, lsl #4
+        vld1.16         {q0},     [r4,:128]
+1:
+        vld1.8          {d2-d3},  [r2], r3
+        vld1.8          {d4-d5},  [r2], r3
+        vld1.8          {d6-d7},  [r2], r3
+        vld1.8          {d8-d9},  [r2], r3
+        vld1.8          {d10-d11},[r2], r3
+        vld1.8          {d12-d13},[r2], r3
+        vld1.8          {d14-d15},[r2]
+        sub             r2,  r2,  r3,  lsl #2
+
+        vp8_epel8_v6_y2 d2,  d4,  d2,  d4,  d6,  d8,  d10, d12, d14
+        vp8_epel8_v6_y2 d3,  d5,  d3,  d5,  d7,  d9,  d11, d13, d15
+
+        vst1.8          {d2-d3},  [r0,:128], r1
+        vst1.8          {d4-d5},  [r0,:128], r1
+        subs            r12, r12, #2
+        bne             1b
+
+        vpop            {d8-d15}
+        pop             {r4,pc}
+endfunc
+
+function ff_put_vp8_epel16_h6_neon, export=1
+        sub             r2,  r2,  #2
+        push            {r4,lr}
+
+        ldr             r4,  [sp, #12]          @ mx
+        movrel          lr,  subpel_filters-16
+        ldr             r12, [sp, #8]           @ h
+        add             r4,  lr,  r4, lsl #4
+        vld1.16         {q0},     [r4,:128]
+1:
+        vld1.8          {d2-d4},  [r2], r3
+
+        vp8_epel16_h6   d2,  d3,  d2,  d3,  d4,  q1,  q2
+
+        vst1.8          {d2-d3}, [r0,:128], r1
+        subs            r12, r12, #1
+        bne             1b
+
+        pop             {r4,pc}
+endfunc
+
+function ff_put_vp8_epel16_h6v6_neon, export=1
+        sub             r2,  r2,  r3,  lsl #1
+        sub             r2,  r2,  #2
+        push            {r4,lr}
+        vpush           {d8-d9}
+
+        @ first pass (horizontal):
+        ldr             r4,  [sp, #28]          @ mx
+        movrel          lr,  subpel_filters-16
+        ldr             r12, [sp, #24]          @ h
+        add             r4,  lr,  r4, lsl #4
+        sub             sp,  sp,  #336+16
+        vld1.16         {q0},     [r4,:128]
+        add             lr,  sp,  #15
+        add             r12, r12, #5
+        bic             lr,  lr,  #15
+1:
+        vld1.8          {d2,d3,d4}, [r2], r3
+
+        vp8_epel16_h6   d2,  d3,  d2,  d3,  d4,  q1,  q2
+
+        vst1.8          {d2-d3}, [lr,:128]!
+        subs            r12, r12, #1
+        bne             1b
+
+        @ second pass (vertical):
+        ldr             r4,  [sp, #336+16+32]   @ my
+        movrel          lr,  subpel_filters-16
+        ldr             r12, [sp, #336+16+24]   @ h
+        add             r4,  lr,  r4, lsl #4
+        add             lr,  sp,  #15
+        vld1.16         {q0},     [r4,:128]
+        bic             lr,  lr,  #15
+2:
+        vld1.8          {d2-d5},  [lr,:128]!
+        vld1.8          {d6-d9},  [lr,:128]!
+        vld1.8          {d28-d31},[lr,:128]
+        sub             lr,  lr,  #48
+
+        vp8_epel8_v6    d2, d2, d4, d6, d8, d28, d30
+        vp8_epel8_v6    d3, d3, d5, d7, d9, d29, d31
+
+        vst1.8          {d2-d3}, [r0,:128], r1
+        subs            r12, r12, #1
+        bne             2b
+
+        add             sp,  sp,  #336+16
+        vpop            {d8-d9}
+        pop             {r4,pc}
+endfunc
+
+function ff_put_vp8_epel8_v6_neon, export=1
+        sub             r2,  r2,  r3,  lsl #1
+        push            {r4,lr}
+
+        ldr             r4,  [sp, #16]          @ my
+        movrel          lr,  subpel_filters-16
+        ldr             r12, [sp, #8]           @ h
+        add             r4,  lr,  r4, lsl #4
+        vld1.16         {q0},     [r4,:128]
+1:
+        vld1.8          {d2},  [r2], r3
+        vld1.8          {d3},  [r2], r3
+        vld1.8          {d4},  [r2], r3
+        vld1.8          {d5},  [r2], r3
+        vld1.8          {d6},  [r2], r3
+        vld1.8          {d7},  [r2], r3
+        vld1.8          {d28}, [r2]
+
+        sub             r2,  r2,  r3,  lsl #2
+
+        vp8_epel8_v6_y2 d2,  d3,  d2,  d3,  d4,  d5,  d6,  d7,  d28
+
+        vst1.8          {d2}, [r0,:64], r1
+        vst1.8          {d3}, [r0,:64], r1
+        subs            r12, r12, #2
+        bne             1b
+
+        pop             {r4,pc}
+endfunc
+
+function ff_put_vp8_epel8_h6_neon, export=1
+        sub             r2,  r2,  #2
+        push            {r4,lr}
+
+        ldr             r4,  [sp, #12]          @ mx
+        movrel          lr,  subpel_filters-16
+        ldr             r12, [sp, #8]           @ h
+        add             r4,  lr,  r4, lsl #4
+        vld1.16         {q0},     [r4,:128]
+1:
+        vld1.8          {d2,d3}, [r2], r3
+
+        vp8_epel8_h6    d2,  d2,  d3
+
+        vst1.8          {d2}, [r0,:64], r1
+        subs            r12, r12, #1
+        bne             1b
+
+        pop             {r4,pc}
+endfunc
+
+function ff_put_vp8_epel8_h6v6_neon, export=1
+        sub             r2,  r2,  r3,  lsl #1
+        sub             r2,  r2,  #2
+        push            {r4,lr}
+
+        @ first pass (horizontal):
+        ldr             r4,  [sp, #12]          @ mx
+        movrel          lr,  subpel_filters-16
+        ldr             r12, [sp, #8]           @ h
+        add             r4,  lr,  r4, lsl #4
+        sub             sp,  sp,  #168+16
+        vld1.16         {q0},     [r4,:128]
+        add             lr,  sp,  #15
+        add             r12, r12, #5
+        bic             lr,  lr,  #15
+1:
+        vld1.8          {d2,d3}, [r2], r3
+
+        vp8_epel8_h6    d2,  d2,  d3
+
+        vst1.8          {d2}, [lr,:64]!
+        subs            r12, r12, #1
+        bne             1b
+
+        @ second pass (vertical):
+        ldr             r4,  [sp, #168+16+16]   @ my
+        movrel          lr,  subpel_filters-16
+        ldr             r12, [sp, #168+16+8]    @ h
+        add             r4,  lr,  r4, lsl #4
+        add             lr,  sp,  #15
+        vld1.16         {q0},     [r4,:128]
+        bic             lr,  lr,  #15
+2:
+        vld1.8          {d2-d5},  [lr,:128]!
+        vld1.8          {d6-d7},  [lr,:128]!
+        vld1.8          {d30},    [lr,:64]
+        sub             lr,  lr,  #32
+
+        vp8_epel8_v6_y2 d2,  d3,  d2,  d3,  d4,  d5,  d6,  d7,  d30
+
+        vst1.8          {d2}, [r0,:64], r1
+        vst1.8          {d3}, [r0,:64], r1
+        subs            r12, r12, #2
+        bne             2b
+
+        add             sp,  sp,  #168+16
+        pop             {r4,pc}
+endfunc
+
+function ff_put_vp8_epel8_v4_neon, export=1
+        sub             r2,  r2,  r3
+        push            {r4,lr}
+
+        ldr             r4,  [sp, #16]          @ my
+        movrel          lr,  subpel_filters-16
+        ldr             r12, [sp, #8]           @ h
+        add             r4,  lr,  r4, lsl #4
+        vld1.16         {q0},     [r4,:128]
+1:
+        vld1.8          {d2},     [r2], r3
+        vld1.8          {d3},     [r2], r3
+        vld1.8          {d4},     [r2], r3
+        vld1.8          {d5},     [r2], r3
+        vld1.8          {d6},     [r2]
+        sub             r2,  r2,  r3,  lsl #1
+
+        vp8_epel8_v4_y2 d2,  d3,  d2,  d3,  d4,  d5,  d6
+
+        vst1.8          {d2}, [r0,:64], r1
+        vst1.8          {d3}, [r0,:64], r1
+        subs            r12, r12, #2
+        bne             1b
+
+        pop             {r4,pc}
+endfunc
+
+function ff_put_vp8_epel8_h4_neon, export=1
+        sub             r2,  r2,  #1
+        push            {r4,lr}
+
+        ldr             r4,  [sp, #12]          @ mx
+        movrel          lr,  subpel_filters-16
+        ldr             r12, [sp, #8]           @ h
+        add             r4,  lr,  r4, lsl #4
+        vld1.16         {q0},     [r4,:128]
+1:
+        vld1.8          {d2,d3}, [r2], r3
+
+        vp8_epel8_h4    d2,  d2,  d3
+
+        vst1.8          {d2}, [r0,:64], r1
+        subs            r12, r12, #1
+        bne             1b
+
+        pop             {r4,pc}
+endfunc
+
+function ff_put_vp8_epel8_h4v4_neon, export=1
+        sub             r2,  r2,  r3
+        sub             r2,  r2,  #1
+        push            {r4,lr}
+
+        @ first pass (horizontal):
+        ldr             r4,  [sp, #12]          @ mx
+        movrel          lr,  subpel_filters-16
+        ldr             r12, [sp, #8]           @ h
+        add             r4,  lr,  r4, lsl #4
+        sub             sp,  sp,  #168+16
+        vld1.16         {q0},     [r4,:128]
+        add             lr,  sp,  #15
+        add             r12, r12, #3
+        bic             lr,  lr,  #15
+1:
+        vld1.8          {d2,d3}, [r2], r3
+
+        vp8_epel8_h4    d2,  d2,  d3
+
+        vst1.8          {d2}, [lr,:64]!
+        subs            r12, r12, #1
+        bne             1b
+
+        @ second pass (vertical):
+        ldr             r4,  [sp, #168+16+16]   @ my
+        movrel          lr,  subpel_filters-16
+        ldr             r12, [sp, #168+16+8]    @ h
+        add             r4,  lr,  r4, lsl #4
+        add             lr,  sp,  #15
+        vld1.16         {q0},     [r4,:128]
+        bic             lr,  lr,  #15
+2:
+        vld1.8          {d2-d5},  [lr,:128]!
+        vld1.8          {d6},     [lr,:64]
+        sub             lr,  lr,  #16
+
+        vp8_epel8_v4_y2 d2,  d3,  d2,  d3,  d4,  d5,  d6
+
+        vst1.8          {d2},     [r0,:64], r1
+        vst1.8          {d3},     [r0,:64], r1
+        subs            r12, r12, #2
+        bne             2b
+
+        add             sp,  sp,  #168+16
+        pop             {r4,pc}
+endfunc
+
+function ff_put_vp8_epel8_h6v4_neon, export=1
+        sub             r2,  r2,  r3
+        sub             r2,  r2,  #2
+        push            {r4,lr}
+
+        @ first pass (horizontal):
+        ldr             r4,  [sp, #12]          @ mx
+        movrel          lr,  subpel_filters-16
+        ldr             r12, [sp, #8]           @ h
+        add             r4,  lr,  r4, lsl #4
+        sub             sp,  sp,  #168+16
+        vld1.16         {q0},     [r4,:128]
+        add             lr,  sp,  #15
+        add             r12, r12, #3
+        bic             lr,  lr,  #15
+1:
+        vld1.8          {d2,d3}, [r2], r3
+
+        vp8_epel8_h6    d2,  d2,  d3
+
+        vst1.8          {d2}, [lr,:64]!
+        subs            r12, r12, #1
+        bne             1b
+
+        @ second pass (vertical):
+        ldr             r4,  [sp, #168+16+16]   @ my
+        movrel          lr,  subpel_filters-16
+        ldr             r12, [sp, #168+16+8]    @ h
+        add             r4,  lr,  r4, lsl #4
+        add             lr,  sp,  #15
+        vld1.16         {q0},     [r4,:128]
+        bic             lr,  lr,  #15
+2:
+        vld1.8          {d2-d5},  [lr,:128]!
+        vld1.8          {d6},     [lr,:64]
+        sub             lr,  lr,  #16
+
+        vp8_epel8_v4_y2 d2,  d3,  d2,  d3,  d4,  d5,  d6
+
+        vst1.8          {d2},     [r0,:64], r1
+        vst1.8          {d3},     [r0,:64], r1
+        subs            r12, r12, #2
+        bne             2b
+
+        add             sp,  sp,  #168+16
+        pop             {r4,pc}
+endfunc
+
+function ff_put_vp8_epel8_h4v6_neon, export=1
+        sub             r2,  r2,  r3,  lsl #1
+        sub             r2,  r2,  #1
+        push            {r4,lr}
+
+        @ first pass (horizontal):
+        ldr             r4,  [sp, #12]          @ mx
+        movrel          lr,  subpel_filters-16
+        ldr             r12, [sp, #8]           @ h
+        add             r4,  lr,  r4, lsl #4
+        sub             sp,  sp,  #168+16
+        vld1.16         {q0},     [r4,:128]
+        add             lr,  sp,  #15
+        add             r12, r12, #5
+        bic             lr,  lr,  #15
+1:
+        vld1.8          {d2,d3}, [r2], r3
+
+        vp8_epel8_h4    d2,  d2,  d3
+
+        vst1.8          {d2}, [lr,:64]!
+        subs            r12, r12, #1
+        bne             1b
+
+        @ second pass (vertical):
+        ldr             r4,  [sp, #168+16+16]   @ my
+        movrel          lr,  subpel_filters-16
+        ldr             r12, [sp, #168+16+8]    @ h
+        add             r4,  lr,  r4, lsl #4
+        add             lr,  sp,  #15
+        vld1.16         {q0},     [r4,:128]
+        bic             lr,  lr,  #15
+2:
+        vld1.8          {d2-d5},  [lr,:128]!
+        vld1.8          {d6-d7},  [lr,:128]!
+        vld1.8          {d30},    [lr,:64]
+        sub             lr,  lr,  #32
+
+        vp8_epel8_v6_y2 d2,  d3,  d2,  d3,  d4,  d5,  d6,  d7,  d30
+
+        vst1.8          {d2}, [r0,:64], r1
+        vst1.8          {d3}, [r0,:64], r1
+        subs            r12, r12, #2
+        bne             2b
+
+        add             sp,  sp,  #168+16
+        pop             {r4,pc}
+endfunc
+
+.ltorg
+
+function ff_put_vp8_epel4_v6_neon, export=1
+        sub             r2,  r2,  r3,  lsl #1
+        push            {r4,lr}
+
+        ldr             r4,  [sp, #16]          @ my
+        movrel          lr,  subpel_filters-16
+        ldr             r12, [sp, #8]           @ h
+        add             r4,  lr,  r4, lsl #4
+        vld1.16         {q0},     [r4,:128]
+1:
+        vld1.32         {d2[]},   [r2], r3
+        vld1.32         {d3[]},   [r2], r3
+        vld1.32         {d4[]},   [r2], r3
+        vld1.32         {d5[]},   [r2], r3
+        vld1.32         {d6[]},   [r2], r3
+        vld1.32         {d7[]},   [r2], r3
+        vld1.32         {d28[]},  [r2]
+        sub             r2,  r2,  r3,  lsl #2
+        vld1.32         {d2[1]},  [r2], r3
+        vld1.32         {d3[1]},  [r2], r3
+        vld1.32         {d4[1]},  [r2], r3
+        vld1.32         {d5[1]},  [r2], r3
+        vld1.32         {d6[1]},  [r2], r3
+        vld1.32         {d7[1]},  [r2], r3
+        vld1.32         {d28[1]}, [r2]
+        sub             r2,  r2,  r3,  lsl #2
+
+        vp8_epel8_v6_y2 d2,  d3,  d2,  d3,  d4,  d5,  d6,  d7,  d28
+
+        vst1.32         {d2[0]},  [r0,:32], r1
+        vst1.32         {d3[0]},  [r0,:32], r1
+        vst1.32         {d2[1]},  [r0,:32], r1
+        vst1.32         {d3[1]},  [r0,:32], r1
+        subs            r12, r12, #4
+        bne             1b
+
+        pop             {r4,pc}
+endfunc
+
+function ff_put_vp8_epel4_h6_neon, export=1
+        sub             r2,  r2,  #2
+        push            {r4,lr}
+
+        ldr             r4,  [sp, #12]          @ mx
+        movrel          lr,  subpel_filters-16
+        ldr             r12, [sp, #8]           @ h
+        add             r4,  lr,  r4, lsl #4
+        vld1.16         {q0},     [r4,:128]
+1:
+        vld1.8          {q1},     [r2], r3
+        vp8_epel8_h6    d2,  d2,  d3
+        vst1.32         {d2[0]},  [r0,:32], r1
+        subs            r12, r12, #1
+        bne             1b
+
+        pop             {r4,pc}
+endfunc
+
+function ff_put_vp8_epel4_h6v6_neon, export=1
+        sub             r2,  r2,  r3,  lsl #1
+        sub             r2,  r2,  #2
+        push            {r4,lr}
+
+        ldr             r4,  [sp, #12]          @ mx
+        movrel          lr,  subpel_filters-16
+        ldr             r12, [sp, #8]           @ h
+        add             r4,  lr,  r4, lsl #4
+        sub             sp,  sp,  #52+16
+        vld1.16         {q0},     [r4,:128]
+        add             lr,  sp,  #15
+        add             r12, r12, #5
+        bic             lr,  lr,  #15
+1:
+        vld1.8          {q1},     [r2], r3
+        vp8_epel8_h6    d2,  d2,  d3
+        vst1.32         {d2[0]},  [lr,:32]!
+        subs            r12, r12, #1
+        bne             1b
+
+        ldr             r4,  [sp, #52+16+16]    @ my
+        movrel          lr,  subpel_filters-16
+        ldr             r12, [sp, #52+16+8]     @ h
+        add             r4,  lr,  r4, lsl #4
+        add             lr,  sp,  #15
+        vld1.16         {q0},     [r4,:128]
+        bic             lr,  lr,  #15
+2:
+        vld1.8          {d2-d3},  [lr,:128]!
+        vld1.8          {d6},     [lr,:64]!
+        vld1.32         {d28[]},  [lr,:32]
+        sub             lr,  lr,  #16
+        vld1.8          {d4-d5},  [lr]!
+        vld1.8          {d7},     [lr,:64]!
+        vld1.32         {d28[1]}, [lr,:32]
+        sub             lr,  lr,  #16
+        vtrn.32         q1,  q2
+        vtrn.32         d6,  d7
+        vp8_epel8_v6_y2 d2,  d3,  d2,  d4,  d3,  d5,  d6,  d7,  d28
+        vst1.32         {d2[0]},  [r0,:32], r1
+        vst1.32         {d3[0]},  [r0,:32], r1
+        vst1.32         {d2[1]},  [r0,:32], r1
+        vst1.32         {d3[1]},  [r0,:32], r1
+        subs            r12, r12, #4
+        bne             2b
+
+        add             sp,  sp,  #52+16
+        pop             {r4,pc}
+endfunc
+
+function ff_put_vp8_epel4_h4v6_neon, export=1
+        sub             r2,  r2,  r3,  lsl #1
+        sub             r2,  r2,  #1
+        push            {r4,lr}
+
+        ldr             r4,  [sp, #12]          @ mx
+        movrel          lr,  subpel_filters-16
+        ldr             r12, [sp, #8]           @ h
+        add             r4,  lr,  r4, lsl #4
+        sub             sp,  sp,  #52+16
+        vld1.16         {q0},     [r4,:128]
+        add             lr,  sp,  #15
+        add             r12, r12, #5
+        bic             lr,  lr,  #15
+1:
+        vld1.8          {d2},     [r2], r3
+        vp8_epel8_h4    d2,  d2,  d2
+        vst1.32         {d2[0]},  [lr,:32]!
+        subs            r12, r12, #1
+        bne             1b
+
+        ldr             r4,  [sp, #52+16+16]    @ my
+        movrel          lr,  subpel_filters-16
+        ldr             r12, [sp, #52+16+8]     @ h
+        add             r4,  lr,  r4, lsl #4
+        add             lr,  sp,  #15
+        vld1.16         {q0},     [r4,:128]
+        bic             lr,  lr,  #15
+2:
+        vld1.8          {d2-d3},  [lr,:128]!
+        vld1.8          {d6},     [lr,:64]!
+        vld1.32         {d28[]},  [lr,:32]
+        sub             lr,  lr,  #16
+        vld1.8          {d4-d5},  [lr]!
+        vld1.8          {d7},     [lr,:64]!
+        vld1.32         {d28[1]}, [lr,:32]
+        sub             lr,  lr,  #16
+        vtrn.32         q1,  q2
+        vtrn.32         d6,  d7
+        vp8_epel8_v6_y2 d2,  d3,  d2,  d4,  d3,  d5,  d6,  d7,  d28
+        vst1.32         {d2[0]},  [r0,:32], r1
+        vst1.32         {d3[0]},  [r0,:32], r1
+        vst1.32         {d2[1]},  [r0,:32], r1
+        vst1.32         {d3[1]},  [r0,:32], r1
+        subs            r12, r12, #4
+        bne             2b
+
+        add             sp,  sp,  #52+16
+        pop             {r4,pc}
+endfunc
+
+function ff_put_vp8_epel4_h6v4_neon, export=1
+        sub             r2,  r2,  r3
+        sub             r2,  r2,  #2
+        push            {r4,lr}
+
+        ldr             r4,  [sp, #12]          @ mx
+        movrel          lr,  subpel_filters-16
+        ldr             r12, [sp, #8]           @ h
+        add             r4,  lr,  r4, lsl #4
+        sub             sp,  sp,  #44+16
+        vld1.16         {q0},     [r4,:128]
+        add             lr,  sp,  #15
+        add             r12, r12, #3
+        bic             lr,  lr,  #15
+1:
+        vld1.8          {q1},     [r2], r3
+        vp8_epel8_h6    d2,  d2,  d3
+        vst1.32         {d2[0]},  [lr,:32]!
+        subs            r12, r12, #1
+        bne             1b
+
+        ldr             r4,  [sp, #44+16+16]    @ my
+        movrel          lr,  subpel_filters-16
+        ldr             r12, [sp, #44+16+8]     @ h
+        add             r4,  lr,  r4, lsl #4
+        add             lr,  sp,  #15
+        vld1.16         {q0},     [r4,:128]
+        bic             lr,  lr,  #15
+2:
+        vld1.8          {d2-d3},  [lr,:128]!
+        vld1.32         {d6[]},   [lr,:32]
+        sub             lr,  lr,  #8
+        vld1.8          {d4-d5},  [lr]!
+        vld1.32         {d6[1]},  [lr,:32]
+        sub             lr,  lr,  #8
+        vtrn.32         q1,  q2
+        vp8_epel8_v4_y2 d2,  d3,  d2,  d4,  d3,  d5,  d6
+        vst1.32         {d2[0]},  [r0,:32], r1
+        vst1.32         {d3[0]},  [r0,:32], r1
+        vst1.32         {d2[1]},  [r0,:32], r1
+        vst1.32         {d3[1]},  [r0,:32], r1
+        subs            r12, r12, #4
+        bne             2b
+
+        add             sp,  sp,  #44+16
+        pop             {r4,pc}
+endfunc
+
+function ff_put_vp8_epel4_h4_neon, export=1
+        sub             r2,  r2,  #1
+        push            {r4,lr}
+
+        ldr             r4,  [sp, #12]          @ mx
+        movrel          lr,  subpel_filters-16
+        ldr             r12, [sp, #8]           @ h
+        add             r4,  lr,  r4, lsl #4
+        vld1.16         {q0},     [r4,:128]
+1:
+        vld1.8          {d2},     [r2], r3
+        vp8_epel8_h4    d2,  d2,  d2
+        vst1.32         {d2[0]},  [r0,:32], r1
+        subs            r12, r12, #1
+        bne             1b
+
+        pop             {r4,pc}
+endfunc
+
+function ff_put_vp8_epel4_v4_neon, export=1
+        sub             r2,  r2,  r3
+        push            {r4,lr}
+
+        ldr             r4,  [sp, #16]          @ my
+        movrel          lr,  subpel_filters-16
+        ldr             r12, [sp, #8]           @ h
+        add             r4,  lr,  r4, lsl #4
+        vld1.16         {q0},     [r4,:128]
+1:
+        vld1.32         {d2[]},   [r2], r3
+        vld1.32         {d3[]},   [r2], r3
+        vld1.32         {d4[]},   [r2], r3
+        vld1.32         {d5[]},   [r2], r3
+        vld1.32         {d6[]},   [r2]
+        sub             r2,  r2,  r3,  lsl #1
+        vld1.32         {d2[1]},  [r2], r3
+        vld1.32         {d3[1]},  [r2], r3
+        vld1.32         {d4[1]},  [r2], r3
+        vld1.32         {d5[1]},  [r2], r3
+        vld1.32         {d6[1]},  [r2]
+        sub             r2,  r2,  r3,  lsl #1
+
+        vp8_epel8_v4_y2 d2,  d3,  d2,  d3,  d4,  d5,  d6
+
+        vst1.32         {d2[0]},  [r0,:32], r1
+        vst1.32         {d3[0]},  [r0,:32], r1
+        vst1.32         {d2[1]},  [r0,:32], r1
+        vst1.32         {d3[1]},  [r0,:32], r1
+        subs            r12, r12, #4
+        bne             1b
+
+        pop             {r4,pc}
+endfunc
+
+function ff_put_vp8_epel4_h4v4_neon, export=1
+        sub             r2,  r2,  r3
+        sub             r2,  r2,  #1
+        push            {r4,lr}
+
+        ldr             r4,  [sp, #12]          @ mx
+        movrel          lr,  subpel_filters-16
+        ldr             r12, [sp, #8]           @ h
+        add             r4,  lr,  r4, lsl #4
+        sub             sp,  sp,  #44+16
+        vld1.16         {q0},     [r4,:128]
+        add             lr,  sp,  #15
+        add             r12, r12, #3
+        bic             lr,  lr,  #15
+1:
+        vld1.8          {d2},     [r2], r3
+        vp8_epel8_h4    d2,  d2,  d3
+        vst1.32         {d2[0]},  [lr,:32]!
+        subs            r12, r12, #1
+        bne             1b
+
+        ldr             r4,  [sp, #44+16+16]    @ my
+        movrel          lr,  subpel_filters-16
+        ldr             r12, [sp, #44+16+8]     @ h
+        add             r4,  lr,  r4, lsl #4
+        add             lr,  sp,  #15
+        vld1.16         {q0},     [r4,:128]
+        bic             lr,  lr,  #15
+2:
+        vld1.8          {d2-d3},  [lr,:128]!
+        vld1.32         {d6[]},   [lr,:32]
+        sub             lr,  lr,  #8
+        vld1.8          {d4-d5},  [lr]!
+        vld1.32         {d6[1]},  [lr,:32]
+        sub             lr,  lr,  #8
+        vtrn.32         q1,  q2
+        vp8_epel8_v4_y2 d2,  d3,  d2,  d4,  d3,  d5,  d6
+        vst1.32         {d2[0]},  [r0,:32], r1
+        vst1.32         {d3[0]},  [r0,:32], r1
+        vst1.32         {d2[1]},  [r0,:32], r1
+        vst1.32         {d3[1]},  [r0,:32], r1
+        subs            r12, r12, #4
+        bne             2b
+
+        add             sp,  sp,  #44+16
+        pop             {r4,pc}
+endfunc
+
+@ note: worst case sum of all 6-tap filter values * 255 is 0x7f80 so 16 bit
+@ arithmatic can be used to apply filters
+const   subpel_filters, align=4
+        .short     0,   6, 123,  12,   1,   0,   0,   0
+        .short     2,  11, 108,  36,   8,   1,   0,   0
+        .short     0,   9,  93,  50,   6,   0,   0,   0
+        .short     3,  16,  77,  77,  16,   3,   0,   0
+        .short     0,   6,  50,  93,   9,   0,   0,   0
+        .short     1,   8,  36, 108,  11,   2,   0,   0
+        .short     0,   1,  12, 123,   6,   0,   0,   0
+endconst
+
+/* Bilinear MC */
+
+function ff_put_vp8_bilin16_h_neon, export=1
+        ldr             r3,  [sp, #4]           @ mx
+        rsb             r12, r3,  #8
+        vdup.8          d0,  r3
+        vdup.8          d1,  r12
+        ldr             r12, [sp]               @ h
+1:
+        subs            r12, r12, #2
+        vld1.8          {d2-d4},  [r2], r1
+        vext.8          q2,  q1,  q2,  #1
+        vmull.u8        q8,  d2,  d1
+        vmlal.u8        q8,  d4,  d0
+        vld1.8          {d18-d20},[r2], r1
+        vmull.u8        q3,  d3,  d1
+        vmlal.u8        q3,  d5,  d0
+        vext.8          q10, q9,  q10, #1
+        vmull.u8        q11, d18, d1
+        vmlal.u8        q11, d20, d0
+        vmull.u8        q12, d19, d1
+        vmlal.u8        q12, d21, d0
+        vrshrn.u16      d4,  q8,  #3
+        vrshrn.u16      d5,  q3,  #3
+        vrshrn.u16      d6,  q11, #3
+        vrshrn.u16      d7,  q12, #3
+        vst1.8          {q2},     [r0,:128], r1
+        vst1.8          {q3},     [r0,:128], r1
+        bgt             1b
+
+        bx              lr
+endfunc
+
+function ff_put_vp8_bilin16_v_neon, export=1
+        ldr             r3,  [sp, #8]           @ my
+        rsb             r12, r3,  #8
+        vdup.8          d0,  r3
+        vdup.8          d1,  r12
+        ldr             r12, [sp]               @ h
+        vld1.8          {q1},     [r2], r1
+1:
+        subs            r12, r12, #2
+        vld1.8          {q2},     [r2], r1
+        vmull.u8        q3,  d2,  d1
+        vmlal.u8        q3,  d4,  d0
+        vmull.u8        q8,  d3,  d1
+        vmlal.u8        q8,  d5,  d0
+        vld1.8          {q1},     [r2], r1
+        vmull.u8        q9,  d4,  d1
+        vmlal.u8        q9,  d2,  d0
+        vmull.u8        q10, d5,  d1
+        vmlal.u8        q10, d3,  d0
+        vrshrn.u16      d4,  q3,  #3
+        vrshrn.u16      d5,  q8,  #3
+        vrshrn.u16      d6,  q9,  #3
+        vrshrn.u16      d7,  q10, #3
+        vst1.8          {q2},     [r0,:128], r1
+        vst1.8          {q3},     [r0,:128], r1
+        bgt             1b
+
+        bx              lr
+endfunc
+
+function ff_put_vp8_bilin16_hv_neon, export=1
+        ldr             r3,  [sp, #4]           @ mx
+        rsb             r12, r3,  #8
+        vdup.8          d0,  r3
+        vdup.8          d1,  r12
+        ldr             r3,  [sp, #8]           @ my
+        rsb             r12, r3,  #8
+        vdup.8          d2,  r3
+        vdup.8          d3,  r12
+        ldr             r12, [sp]               @ h
+
+        vld1.8          {d4-d6},  [r2], r1
+        vext.8          q3,  q2,  q3,  #1
+        vmull.u8        q8,  d4,  d1
+        vmlal.u8        q8,  d6,  d0
+        vmull.u8        q9,  d5,  d1
+        vmlal.u8        q9,  d7,  d0
+        vrshrn.u16      d4,  q8,  #3
+        vrshrn.u16      d5,  q9,  #3
+1:
+        subs            r12, r12, #2
+        vld1.8          {d18-d20},[r2], r1
+        vext.8          q10, q9,  q10, #1
+        vmull.u8        q11, d18, d1
+        vmlal.u8        q11, d20, d0
+        vld1.8          {d26-d28},[r2], r1
+        vmull.u8        q12, d19, d1
+        vmlal.u8        q12, d21, d0
+        vext.8          q14, q13, q14, #1
+        vmull.u8        q8,  d26, d1
+        vmlal.u8        q8,  d28, d0
+        vmull.u8        q9,  d27, d1
+        vmlal.u8        q9,  d29, d0
+        vrshrn.u16      d6,  q11, #3
+        vrshrn.u16      d7,  q12, #3
+        vmull.u8        q12, d4,  d3
+        vmlal.u8        q12, d6,  d2
+        vmull.u8        q15, d5,  d3
+        vmlal.u8        q15, d7,  d2
+        vrshrn.u16      d4,  q8,  #3
+        vrshrn.u16      d5,  q9,  #3
+        vmull.u8        q10, d6,  d3
+        vmlal.u8        q10, d4,  d2
+        vmull.u8        q11, d7,  d3
+        vmlal.u8        q11, d5,  d2
+        vrshrn.u16      d24, q12, #3
+        vrshrn.u16      d25, q15, #3
+        vst1.8          {q12},    [r0,:128], r1
+        vrshrn.u16      d20, q10, #3
+        vrshrn.u16      d21, q11, #3
+        vst1.8          {q10},    [r0,:128], r1
+        bgt             1b
+
+        bx              lr
+endfunc
+
+function ff_put_vp8_bilin8_h_neon, export=1
+        ldr             r3,  [sp, #4]           @ mx
+        rsb             r12, r3,  #8
+        vdup.8          d0,  r3
+        vdup.8          d1,  r12
+        ldr             r12, [sp]               @ h
+1:
+        subs            r12, r12, #2
+        vld1.8          {q1},     [r2], r1
+        vext.8          d3,  d2,  d3,  #1
+        vmull.u8        q2,  d2,  d1
+        vmlal.u8        q2,  d3,  d0
+        vld1.8          {q3},     [r2], r1
+        vext.8          d7,  d6,  d7,  #1
+        vmull.u8        q8,  d6,  d1
+        vmlal.u8        q8,  d7,  d0
+        vrshrn.u16      d4,  q2,  #3
+        vrshrn.u16      d16, q8,  #3
+        vst1.8          {d4},     [r0,:64], r1
+        vst1.8          {d16},    [r0,:64], r1
+        bgt             1b
+
+        bx              lr
+endfunc
+
+function ff_put_vp8_bilin8_v_neon, export=1
+        ldr             r3,  [sp, #8]           @ my
+        rsb             r12, r3,  #8
+        vdup.8          d0,  r3
+        vdup.8          d1,  r12
+        ldr             r12, [sp]               @ h
+        vld1.8          {d2},     [r2], r1
+1:
+        subs            r12, r12, #2
+        vld1.8          {d3},     [r2], r1
+        vmull.u8        q2,  d2,  d1
+        vmlal.u8        q2,  d3,  d0
+        vld1.8          {d2},     [r2], r1
+        vmull.u8        q3,  d3,  d1
+        vmlal.u8        q3,  d2,  d0
+        vrshrn.u16      d4,  q2,  #3
+        vrshrn.u16      d6,  q3,  #3
+        vst1.8          {d4},     [r0,:64], r1
+        vst1.8          {d6},     [r0,:64], r1
+        bgt             1b
+
+        bx              lr
+endfunc
+
+function ff_put_vp8_bilin8_hv_neon, export=1
+        ldr             r3,  [sp, #4]           @ mx
+        rsb             r12, r3,  #8
+        vdup.8          d0,  r3
+        vdup.8          d1,  r12
+        ldr             r3,  [sp, #8]           @ my
+        rsb             r12, r3,  #8
+        vdup.8          d2,  r3
+        vdup.8          d3,  r12
+        ldr             r12, [sp]               @ h
+
+        vld1.8          {q2},     [r2], r1
+        vext.8          d5,  d4,  d5,  #1
+        vmull.u8        q9,  d4,  d1
+        vmlal.u8        q9,  d5,  d0
+        vrshrn.u16      d22, q9,  #3
+1:
+        subs            r12, r12, #2
+        vld1.8          {q3},     [r2], r1
+        vext.8          d7,  d6,  d7,  #1
+        vmull.u8        q8,  d6,  d1
+        vmlal.u8        q8,  d7,  d0
+        vld1.8          {q2},     [r2], r1
+        vext.8          d5,  d4,  d5,  #1
+        vmull.u8        q9,  d4,  d1
+        vmlal.u8        q9,  d5,  d0
+        vrshrn.u16      d16, q8,  #3
+        vmull.u8        q10, d22, d3
+        vmlal.u8        q10, d16, d2
+        vrshrn.u16      d22, q9,  #3
+        vmull.u8        q12, d16, d3
+        vmlal.u8        q12, d22, d2
+        vrshrn.u16      d20, q10, #3
+        vst1.8          {d20},    [r0,:64], r1
+        vrshrn.u16      d23, q12, #3
+        vst1.8          {d23},    [r0,:64], r1
+        bgt             1b
+
+        bx              lr
+endfunc
+
+function ff_put_vp8_bilin4_h_neon, export=1
+        ldr             r3,  [sp, #4]           @ mx
+        rsb             r12, r3,  #8
+        vdup.8          d0,  r3
+        vdup.8          d1,  r12
+        ldr             r12, [sp]               @ h
+1:
+        subs            r12, r12, #2
+        vld1.8          {d2},     [r2], r1
+        vext.8          d3,  d2,  d3,  #1
+        vld1.8          {d6},     [r2], r1
+        vext.8          d7,  d6,  d7,  #1
+        vtrn.32         q1,  q3
+        vmull.u8        q2,  d2,  d1
+        vmlal.u8        q2,  d3,  d0
+        vrshrn.u16      d4,  q2,  #3
+        vst1.32         {d4[0]},  [r0,:32], r1
+        vst1.32         {d4[1]}, [r0,:32], r1
+        bgt             1b
+
+        bx              lr
+endfunc
+
+function ff_put_vp8_bilin4_v_neon, export=1
+        ldr             r3,  [sp, #8]           @ my
+        rsb             r12, r3,  #8
+        vdup.8          d0,  r3
+        vdup.8          d1,  r12
+        ldr             r12, [sp]               @ h
+        vld1.32         {d2[]},   [r2], r1
+1:
+        vld1.32         {d3[]},   [r2]
+        vld1.32         {d2[1]},  [r2], r1
+        vld1.32         {d3[1]},  [r2], r1
+        vmull.u8        q2,  d2,  d1
+        vmlal.u8        q2,  d3,  d0
+        vtrn.32         d3,  d2
+        vrshrn.u16      d4,  q2,  #3
+        vst1.32         {d4[0]},  [r0,:32], r1
+        vst1.32         {d4[1]},  [r0,:32], r1
+        subs            r12, r12, #2
+        bgt             1b
+
+        bx              lr
+endfunc
+
+function ff_put_vp8_bilin4_hv_neon, export=1
+        ldr             r3,  [sp, #4]           @ mx
+        rsb             r12, r3,  #8
+        vdup.8          d0,  r3
+        vdup.8          d1,  r12
+        ldr             r3,  [sp, #8]           @ my
+        rsb             r12, r3,  #8
+        vdup.8          d2,  r3
+        vdup.8          d3,  r12
+        ldr             r12, [sp]               @ h
+
+        vld1.8          {d4},     [r2], r1
+        vext.8          d5,  d4,  d4,  #1
+        vmull.u8        q9,  d4,  d1
+        vmlal.u8        q9,  d5,  d0
+        vrshrn.u16      d22, q9,  #3
+1:
+        subs            r12, r12, #2
+        vld1.8          {d6},     [r2], r1
+        vext.8          d7,  d6,  d6,  #1
+        vld1.8          {d4},     [r2], r1
+        vext.8          d5,  d4,  d4,  #1
+        vtrn.32         q3,  q2
+        vmull.u8        q8,  d6,  d1
+        vmlal.u8        q8,  d7,  d0
+        vrshrn.u16      d16, q8,  #3
+        vmull.u8        q10, d16, d2
+        vtrn.32         d22, d16
+        vmlal.u8        q10, d22, d3
+        vrev64.32       d22, d16
+        vrshrn.u16      d20, q10, #3
+        vst1.32         {d20[0]}, [r0,:32], r1
+        vst1.32         {d20[1]}, [r0,:32], r1
+        bgt             1b
+
+        bx              lr
+endfunc
diff --git a/libavcodec/ass.c b/libavcodec/ass.c
new file mode 100644
index 0000000..beb1ba1
--- /dev/null
+++ b/libavcodec/ass.c
@@ -0,0 +1,124 @@
+/*
+ * SSA/ASS common funtions
+ * Copyright (c) 2010  Aurelien Jacobs <aurel at gnuage.org>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "avcodec.h"
+#include "ass.h"
+
+/**
+ * Generate a suitable AVCodecContext.subtitle_header for SUBTITLE_ASS.
+ *
+ * @param avctx pointer to the AVCodecContext
+ * @param font name of the default font face to use
+ * @param font_size default font size to use
+ * @param color default text color to use (ABGR)
+ * @param back_color default background color to use (ABGR)
+ * @param bold 1 for bold text, 0 for normal text
+ * @param italic 1 for italic text, 0 for normal text
+ * @param underline 1 for underline text, 0 for normal text
+ * @param alignment position of the text (left, center, top...), defined after
+ *                  the layout of the numpad (1-3 sub, 4-6 mid, 7-9 top)
+ * @return >= 0 on success otherwise an error code <0
+ */
+static int ff_ass_subtitle_header(AVCodecContext *avctx,
+                                  const char *font, int font_size,
+                                  int color, int back_color,
+                                  int bold, int italic, int underline,
+                                  int alignment)
+{
+    char header[512];
+
+    snprintf(header, sizeof(header),
+             "[Script Info]\r\n"
+             "ScriptType: v4.00+\r\n"
+             "\r\n"
+             "[V4+ Styles]\r\n"
+             "Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, AlphaLevel, Encoding\r\n"
+             "Style: Default,%s,%d,&H%x,&H%x,&H%x,&H%x,%d,%d,%d,1,1,0,%d,10,10,10,0,0\r\n"
+             "\r\n"
+             "[Events]\r\n"
+             "Format: Layer, Start, End, Text\r\n",
+             font, font_size, color, color, back_color, back_color,
+             -bold, -italic, -underline, alignment);
+
+    avctx->subtitle_header = av_strdup(header);
+    if (!avctx->subtitle_header)
+        return AVERROR(ENOMEM);
+    avctx->subtitle_header_size = strlen(avctx->subtitle_header);
+    return 0;
+}
+
+int ff_ass_subtitle_header_default(AVCodecContext *avctx)
+{
+    return ff_ass_subtitle_header(avctx, ASS_DEFAULT_FONT,
+                                         ASS_DEFAULT_FONT_SIZE,
+                                         ASS_DEFAULT_COLOR,
+                                         ASS_DEFAULT_BACK_COLOR,
+                                         ASS_DEFAULT_BOLD,
+                                         ASS_DEFAULT_ITALIC,
+                                         ASS_DEFAULT_UNDERLINE,
+                                         ASS_DEFAULT_ALIGNMENT);
+}
+
+void ff_ass_init(AVSubtitle *sub)
+{
+    memset(sub, 0, sizeof(*sub));
+}
+
+static int ts_to_string(char *str, int strlen, int ts)
+{
+    int h, m, s;
+    h = ts/360000;  ts -= 360000*h;
+    m = ts/  6000;  ts -=   6000*m;
+    s = ts/   100;  ts -=    100*s;
+    return snprintf(str, strlen, "%d:%02d:%02d.%02d", h, m, s, ts);
+}
+
+int ff_ass_add_rect(AVSubtitle *sub, const char *dialog,
+                    int ts_start, int ts_end, int raw)
+{
+    int len = 0, dlen, duration = ts_end - ts_start;
+    char s_start[16], s_end[16], header[48] = {0};
+    AVSubtitleRect **rects;
+
+    if (!raw) {
+        ts_to_string(s_start, sizeof(s_start), ts_start);
+        ts_to_string(s_end,   sizeof(s_end),   ts_end  );
+        len = snprintf(header, sizeof(header), "Dialogue: 0,%s,%s,",
+                       s_start, s_end);
+    }
+
+    dlen = strcspn(dialog, "\n");
+    dlen += dialog[dlen] == '\n';
+
+    rects = av_realloc(sub->rects, (sub->num_rects+1) * sizeof(*sub->rects));
+    if (!rects)
+        return AVERROR(ENOMEM);
+    sub->rects = rects;
+    sub->end_display_time = FFMAX(sub->end_display_time, 10 * duration);
+    rects[sub->num_rects]       = av_mallocz(sizeof(*rects[0]));
+    rects[sub->num_rects]->type = SUBTITLE_ASS;
+    rects[sub->num_rects]->ass  = av_malloc(len + dlen + 1);
+    strcpy (rects[sub->num_rects]->ass      , header);
+    strncpy(rects[sub->num_rects]->ass + len, dialog, dlen);
+    rects[sub->num_rects]->ass[len+dlen] = 0;
+    sub->num_rects++;
+    return dlen;
+}
diff --git a/libavcodec/ass.h b/libavcodec/ass.h
new file mode 100644
index 0000000..d350cf3
--- /dev/null
+++ b/libavcodec/ass.h
@@ -0,0 +1,77 @@
+/*
+ * SSA/ASS common funtions
+ * Copyright (c) 2010  Aurelien Jacobs <aurel at gnuage.org>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_ASS_H
+#define AVCODEC_ASS_H
+
+#include "avcodec.h"
+
+/**
+ * Default values for ASS style.
+ * @defgroup ass_default
+ * @{
+ */
+#define ASS_DEFAULT_FONT        "Arial"
+#define ASS_DEFAULT_FONT_SIZE   16
+#define ASS_DEFAULT_COLOR       0xffffff
+#define ASS_DEFAULT_BACK_COLOR  0
+#define ASS_DEFAULT_BOLD        0
+#define ASS_DEFAULT_ITALIC      0
+#define ASS_DEFAULT_UNDERLINE   0
+#define ASS_DEFAULT_ALIGNMENT   2
+/** @} */
+
+/**
+ * Generate a suitable AVCodecContext.subtitle_header for SUBTITLE_ASS
+ * with default style.
+ *
+ * @param avctx pointer to the AVCodecContext
+ * @return >= 0 on success otherwise an error code <0
+ */
+int ff_ass_subtitle_header_default(AVCodecContext *avctx);
+
+/**
+ * Initialize an AVSubtitle structure for use with ff_ass_add_rect().
+ *
+ * @param sub pointer to the AVSubtitle
+ */
+void ff_ass_init(AVSubtitle *sub);
+
+/**
+ * Add an ASS dialog line to an AVSubtitle as a new AVSubtitleRect.
+ *
+ * @param sub pointer to the AVSubtitle
+ * @param dialog ASS dialog to add to sub
+ * @param ts_start start timestamp for this dialog (in 1/100 second unit)
+ * @param ts_end end timestamp for this dialog (in 1/100 second unit)
+ * @param raw when set to 1, it indicates that dialog contains a whole ASS
+ *                           dialog line which should be copied as is.
+ *            when set to 0, it indicates that dialog contains only the Text
+ *                           part of the ASS dialog line, the rest of the line
+ *                           will be generated.
+ * @return number of characters read from dialog. It can be less than the whole
+ *         length of dialog, if dialog contains several lines of text.
+ *         A negative value indicates an error.
+ */
+int ff_ass_add_rect(AVSubtitle *sub, const char *dialog,
+                    int ts_start, int ts_end, int raw);
+
+#endif /* AVCODEC_ASS_H */
diff --git a/libavcodec/assdec.c b/libavcodec/assdec.c
new file mode 100644
index 0000000..98f7be3
--- /dev/null
+++ b/libavcodec/assdec.c
@@ -0,0 +1,62 @@
+/*
+ * SSA/ASS decoder
+ * Copyright (c) 2010  Aurelien Jacobs <aurel at gnuage.org>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "avcodec.h"
+#include "ass.h"
+
+static av_cold int ass_decode_init(AVCodecContext *avctx)
+{
+    avctx->subtitle_header = av_malloc(avctx->extradata_size);
+    if (!avctx->extradata)
+        return AVERROR(ENOMEM);
+    memcpy(avctx->subtitle_header, avctx->extradata, avctx->extradata_size);
+    avctx->subtitle_header_size = avctx->extradata_size;
+    return 0;
+}
+
+static int ass_decode_frame(AVCodecContext *avctx, void *data, int *got_sub_ptr,
+                            AVPacket *avpkt)
+{
+    const char *ptr = avpkt->data;
+    int len, size = avpkt->size;
+
+    ff_ass_init(data);
+
+    while (size > 0) {
+        len = ff_ass_add_rect(data, ptr, 0, 0/* FIXME: duration */, 1);
+        if (len < 0)
+            return len;
+        ptr  += len;
+        size -= len;
+    }
+
+    *got_sub_ptr = avpkt->size > 0;
+    return avpkt->size;
+}
+
+AVCodec ff_ass_decoder = {
+    .name         = "ass",
+    .long_name    = NULL_IF_CONFIG_SMALL("Advanced SubStation Alpha subtitle"),
+    .type         = AVMEDIA_TYPE_SUBTITLE,
+    .id           = CODEC_ID_SSA,
+    .init         = ass_decode_init,
+    .decode       = ass_decode_frame,
+};
diff --git a/libavcodec/assenc.c b/libavcodec/assenc.c
new file mode 100644
index 0000000..b7836ff
--- /dev/null
+++ b/libavcodec/assenc.c
@@ -0,0 +1,67 @@
+/*
+ * SSA/ASS encoder
+ * Copyright (c) 2010  Aurelien Jacobs <aurel at gnuage.org>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "avcodec.h"
+#include "libavutil/avstring.h"
+
+static av_cold int ass_encode_init(AVCodecContext *avctx)
+{
+    avctx->extradata = av_malloc(avctx->subtitle_header_size);
+    if (!avctx->extradata)
+        return AVERROR(ENOMEM);
+    memcpy(avctx->extradata, avctx->subtitle_header, avctx->subtitle_header_size);
+    avctx->extradata_size = avctx->subtitle_header_size;
+    return 0;
+}
+
+static int ass_encode_frame(AVCodecContext *avctx,
+                            unsigned char *buf, int bufsize, void *data)
+{
+    AVSubtitle *sub = data;
+    int i, len, total_len = 0;
+
+    for (i=0; i<sub->num_rects; i++) {
+        if (sub->rects[i]->type != SUBTITLE_ASS) {
+            av_log(avctx, AV_LOG_ERROR, "Only SUBTITLE_ASS type supported.\n");
+            return -1;
+        }
+
+        len = av_strlcpy(buf+total_len, sub->rects[i]->ass, bufsize-total_len);
+
+        if (len > bufsize-total_len-1) {
+            av_log(avctx, AV_LOG_ERROR, "Buffer too small for ASS event.\n");
+            return -1;
+        }
+
+        total_len += len;
+    }
+
+    return total_len;
+}
+
+AVCodec ff_ass_encoder = {
+    .name         = "ass",
+    .long_name    = NULL_IF_CONFIG_SMALL("Advanced SubStation Alpha subtitle"),
+    .type         = AVMEDIA_TYPE_SUBTITLE,
+    .id           = CODEC_ID_SSA,
+    .init         = ass_encode_init,
+    .encode       = ass_encode_frame,
+};
diff --git a/libavcodec/asv1.c b/libavcodec/asv1.c
index 211a13f..cb07771 100644
--- a/libavcodec/asv1.c
+++ b/libavcodec/asv1.c
@@ -2,20 +2,20 @@
  * ASUS V1/V2 codec
  * Copyright (c) 2003 Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -588,8 +588,8 @@ static av_cold int encode_init(AVCodecContext *avctx){
 
     avctx->extradata= av_mallocz(8);
     avctx->extradata_size=8;
-    ((uint32_t*)avctx->extradata)[0]= le2me_32(a->inv_qscale);
-    ((uint32_t*)avctx->extradata)[1]= le2me_32(AV_RL32("ASUS"));
+    ((uint32_t*)avctx->extradata)[0]= av_le2ne32(a->inv_qscale);
+    ((uint32_t*)avctx->extradata)[1]= av_le2ne32(AV_RL32("ASUS"));
 
     for(i=0; i<64; i++){
         int q= 32*scale*ff_mpeg1_default_intra_matrix[i];
@@ -613,7 +613,7 @@ static av_cold int decode_end(AVCodecContext *avctx){
     return 0;
 }
 
-AVCodec asv1_decoder = {
+AVCodec ff_asv1_decoder = {
     "asv1",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_ASV1,
@@ -626,7 +626,7 @@ AVCodec asv1_decoder = {
     .long_name= NULL_IF_CONFIG_SMALL("ASUS V1"),
 };
 
-AVCodec asv2_decoder = {
+AVCodec ff_asv2_decoder = {
     "asv2",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_ASV2,
@@ -640,7 +640,7 @@ AVCodec asv2_decoder = {
 };
 
 #if CONFIG_ASV1_ENCODER
-AVCodec asv1_encoder = {
+AVCodec ff_asv1_encoder = {
     "asv1",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_ASV1,
@@ -654,7 +654,7 @@ AVCodec asv1_encoder = {
 #endif
 
 #if CONFIG_ASV2_ENCODER
-AVCodec asv2_encoder = {
+AVCodec ff_asv2_encoder = {
     "asv2",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_ASV2,
diff --git a/libavcodec/atrac.c b/libavcodec/atrac.c
index e398cee..2c39aad 100644
--- a/libavcodec/atrac.c
+++ b/libavcodec/atrac.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2006-2008 Maxim Poliakovski
  * Copyright (c) 2006-2008 Benjamin Larsson
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -32,8 +32,8 @@
 #include "dsputil.h"
 #include "atrac.h"
 
-float sf_table[64];
-float qmf_window[48];
+float ff_atrac_sf_table[64];
+static float qmf_window[48];
 
 static const float qmf_48tap_half[24] = {
    -0.00001461907, -0.00009205479,-0.000056157569,0.00030117269,
@@ -54,9 +54,9 @@ void atrac_generate_tables(void)
     float s;
 
     /* Generate scale factors */
-    if (!sf_table[63])
+    if (!ff_atrac_sf_table[63])
         for (i=0 ; i<64 ; i++)
-            sf_table[i] = pow(2.0, (i - 15) / 3.0);
+            ff_atrac_sf_table[i] = pow(2.0, (i - 15) / 3.0);
 
     /* Generate the QMF window. */
     if (!qmf_window[47])
diff --git a/libavcodec/atrac.h b/libavcodec/atrac.h
index 0732da0..2223a5e 100644
--- a/libavcodec/atrac.h
+++ b/libavcodec/atrac.h
@@ -3,20 +3,20 @@
  * Copyright (c) 2009 Maxim Poliakovski
  * Copyright (c) 2009 Benjamin Larsson
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -28,9 +28,7 @@
 #ifndef AVCODEC_ATRAC_H
 #define AVCODEC_ATRAC_H
 
-
-extern float sf_table[64];
-extern float qmf_window[48];
+extern float ff_atrac_sf_table[64];
 
 void atrac_generate_tables(void);
 void atrac_iqmf (float *inlo, float *inhi, unsigned int nIn, float *pOut, float *delayBuf, float *temp);
diff --git a/libavcodec/atrac1.c b/libavcodec/atrac1.c
index 5ff8816..d6c7053 100644
--- a/libavcodec/atrac1.c
+++ b/libavcodec/atrac1.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2009 Maxim Poliakovski
  * Copyright (c) 2009 Benjamin Larsson
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -36,6 +36,7 @@
 #include "get_bits.h"
 #include "dsputil.h"
 #include "fft.h"
+#include "sinewin.h"
 
 #include "atrac.h"
 #include "atrac1data.h"
@@ -99,7 +100,7 @@ static void at1_imdct(AT1Ctx *q, float *spec, float *out, int nbits,
         for (i = 0; i < transf_size / 2; i++)
             FFSWAP(float, spec[i], spec[transf_size - 1 - i]);
     }
-    ff_imdct_half(mdct_context, out, spec);
+    mdct_context->imdct_half(mdct_context, out, spec);
 }
 
 
@@ -141,7 +142,7 @@ static int at1_imdct_block(AT1SUCtx* su, AT1Ctx *q)
 
             /* overlap and window */
             q->dsp.vector_fmul_window(&q->bands[band_num][start_pos], prev_buf,
-                                      &su->spectrum[0][ref_pos + start_pos], ff_sine_32, 0, 16);
+                                      &su->spectrum[0][ref_pos + start_pos], ff_sine_32, 16);
 
             prev_buf = &su->spectrum[0][ref_pos+start_pos + 16];
             start_pos += block_size;
@@ -223,7 +224,7 @@ static int at1_unpack_dequant(GetBitContext* gb, AT1SUCtx* su,
 
             int num_specs = specs_per_bfu[bfu_num];
             int word_len  = !!idwls[bfu_num] + idwls[bfu_num];
-            float scale_factor = sf_table[idsfs[bfu_num]];
+            float scale_factor = ff_atrac_sf_table[idsfs[bfu_num]];
             bits_used += word_len * num_specs; /* add number of bits consumed by current BFU */
 
             /* check for bitstream overflow */
@@ -326,7 +327,7 @@ static av_cold int atrac1_decode_init(AVCodecContext *avctx)
 {
     AT1Ctx *q = avctx->priv_data;
 
-    avctx->sample_fmt = SAMPLE_FMT_FLT;
+    avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
 
     q->channels = avctx->channels;
 
@@ -365,7 +366,7 @@ static av_cold int atrac1_decode_end(AVCodecContext * avctx) {
 }
 
 
-AVCodec atrac1_decoder = {
+AVCodec ff_atrac1_decoder = {
     .name = "atrac1",
     .type = AVMEDIA_TYPE_AUDIO,
     .id = CODEC_ID_ATRAC1,
diff --git a/libavcodec/atrac1data.h b/libavcodec/atrac1data.h
index ebebe4b..7d5dbeb 100644
--- a/libavcodec/atrac1data.h
+++ b/libavcodec/atrac1data.h
@@ -3,20 +3,20 @@
  * Copyright (c) 2009 Maxim Poliakovski
  * Copyright (c) 2009 Benjamin Larsson
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/atrac3.c b/libavcodec/atrac3.c
index 5179c34..5633520 100644
--- a/libavcodec/atrac3.c
+++ b/libavcodec/atrac3.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2006-2008 Maxim Poliakovski
  * Copyright (c) 2006-2008 Benjamin Larsson
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -118,13 +118,14 @@ typedef struct {
     int                 scrambled_stream;
     int                 frame_factor;
     //@}
+
+    FFTContext          mdct_ctx;
 } ATRAC3Context;
 
 static DECLARE_ALIGNED(16, float,mdct_window)[512];
 static VLC              spectral_coeff_tab[7];
 static float            gain_tab1[16];
 static float            gain_tab2[31];
-static FFTContext       mdct_ctx;
 static DSPContext       dsp;
 
 
@@ -137,7 +138,7 @@ static DSPContext       dsp;
  * @param odd_band  1 if the band is an odd band
  */
 
-static void IMLT(float *pInput, float *pOutput, int odd_band)
+static void IMLT(ATRAC3Context *q, float *pInput, float *pOutput, int odd_band)
 {
     int     i;
 
@@ -145,7 +146,7 @@ static void IMLT(float *pInput, float *pOutput, int odd_band)
         /**
         * Reverse the odd bands before IMDCT, this is an effect of the QMF transform
         * or it gives better compression to do it this way.
-        * FIXME: It should be possible to handle this in ff_imdct_calc
+        * FIXME: It should be possible to handle this in imdct_calc
         * for that to happen a modification of the prerotation step of
         * all SIMD code and C code is needed.
         * Or fix the functions before so they generate a pre reversed spectrum.
@@ -155,10 +156,10 @@ static void IMLT(float *pInput, float *pOutput, int odd_band)
             FFSWAP(float, pInput[i], pInput[255-i]);
     }
 
-    ff_imdct_calc(&mdct_ctx,pOutput,pInput);
+    q->mdct_ctx.imdct_calc(&q->mdct_ctx,pOutput,pInput);
 
     /* Perform windowing on the output. */
-    dsp.vector_fmul(pOutput,mdct_window,512);
+    dsp.vector_fmul(pOutput, pOutput, mdct_window, 512);
 
 }
 
@@ -166,9 +167,9 @@ static void IMLT(float *pInput, float *pOutput, int odd_band)
 /**
  * Atrac 3 indata descrambling, only used for data coming from the rm container
  *
- * @param in        pointer to 8 bit array of indata
- * @param bits      amount of bits
+ * @param inbuffer  pointer to 8 bit array of indata
  * @param out       pointer to 8 bit array of outdata
+ * @param bytes     amount of bytes
  */
 
 static int decode_bytes(const uint8_t* inbuffer, uint8_t* out, int bytes){
@@ -179,7 +180,7 @@ static int decode_bytes(const uint8_t* inbuffer, uint8_t* out, int bytes){
 
     off = (intptr_t)inbuffer & 3;
     buf = (const uint32_t*) (inbuffer - off);
-    c = be2me_32((0x537F6103 >> (off*8)) | (0x537F6103 << (32-(off*8))));
+    c = av_be2ne32((0x537F6103 >> (off*8)) | (0x537F6103 << (32-(off*8))));
     bytes += 3 + off;
     for (i = 0; i < bytes/4; i++)
         obuf[i] = c ^ buf[i];
@@ -207,7 +208,7 @@ static av_cold void init_atrac3_transforms(ATRAC3Context *q) {
         }
 
     /* Initialize the MDCT transform. */
-    ff_mdct_init(&mdct_ctx, 9, 1, 1.0);
+    ff_mdct_init(&q->mdct_ctx, 9, 1, 1.0);
 }
 
 /**
@@ -220,6 +221,7 @@ static av_cold int atrac3_decode_close(AVCodecContext *avctx)
 
     av_free(q->pUnits);
     av_free(q->decoded_bytes_buffer);
+    ff_mdct_end(&q->mdct_ctx);
 
     return 0;
 }
@@ -325,7 +327,7 @@ static int decodeSpectrum (GetBitContext *gb, float *pOut)
             readQuantSpectralCoeffs (gb, subband_vlc_index[cnt], codingMode, mantissas, subbWidth);
 
             /* Decode the scale factor for this subband. */
-            SF = sf_table[SF_idxs[cnt]] * iMaxQuant[subband_vlc_index[cnt]];
+            SF = ff_atrac_sf_table[SF_idxs[cnt]] * iMaxQuant[subband_vlc_index[cnt]];
 
             /* Inverse quantize the coefficients. */
             for (pIn=mantissas ; first<last; first++, pIn++)
@@ -398,7 +400,7 @@ static int decodeTonalComponents (GetBitContext *gb, tonal_component *pComponent
                 coded_values = coded_values_per_component + 1;
                 coded_values = FFMIN(max_coded_values,coded_values);
 
-                scalefactor = sf_table[sfIndx] * iMaxQuant[quant_step_index];
+                scalefactor = ff_atrac_sf_table[sfIndx] * iMaxQuant[quant_step_index];
 
                 readQuantSpectralCoeffs(gb, quant_step_index, coding_mode, mantissa, coded_values);
 
@@ -694,7 +696,7 @@ static int decodeChannelSoundUnit (ATRAC3Context *q, GetBitContext *gb, channel_
     for (band=0; band<4; band++) {
         /* Perform the IMDCT step without overlapping. */
         if (band <= numBands) {
-            IMLT(&(pSnd->spectrum[band*256]), pSnd->IMDCT_buf, band&1);
+            IMLT(q, &(pSnd->spectrum[band*256]), pSnd->IMDCT_buf, band&1);
         } else
             memset(pSnd->IMDCT_buf, 0, 512 * sizeof(float));
 
@@ -825,8 +827,12 @@ static int atrac3_decode_frame(AVCodecContext *avctx,
     const uint8_t* databuf;
     int16_t* samples = data;
 
-    if (buf_size < avctx->block_align)
+    if (buf_size < avctx->block_align) {
+        av_log(avctx, AV_LOG_ERROR,
+               "Frame too small (%d bytes). Truncated file?\n", buf_size);
+        *data_size = 0;
         return buf_size;
+    }
 
     /* Check if we need to descramble and what buffer to pass on. */
     if (q->scrambled_stream) {
@@ -1008,12 +1014,12 @@ static av_cold int atrac3_decode_init(AVCodecContext *avctx)
         return AVERROR(ENOMEM);
     }
 
-    avctx->sample_fmt = SAMPLE_FMT_S16;
+    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
     return 0;
 }
 
 
-AVCodec atrac3_decoder =
+AVCodec ff_atrac3_decoder =
 {
     .name = "atrac3",
     .type = AVMEDIA_TYPE_AUDIO,
diff --git a/libavcodec/atrac3data.h b/libavcodec/atrac3data.h
index b5aa71f..9076d3a 100644
--- a/libavcodec/atrac3data.h
+++ b/libavcodec/atrac3data.h
@@ -3,20 +3,20 @@
  * Copyright (c) 2006-2007 Maxim Poliakovski
  * Copyright (c) 2006-2007 Benjamin Larsson
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/audioconvert.c b/libavcodec/audioconvert.c
index d022bc9..4bea308 100644
--- a/libavcodec/audioconvert.c
+++ b/libavcodec/audioconvert.c
@@ -2,20 +2,20 @@
  * audio conversion
  * Copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -27,145 +27,65 @@
 
 #include "libavutil/avstring.h"
 #include "libavutil/libm.h"
+#include "libavutil/samplefmt.h"
 #include "avcodec.h"
 #include "audioconvert.h"
 
-typedef struct SampleFmtInfo {
-    const char *name;
-    int bits;
-} SampleFmtInfo;
-
-/** this table gives more information about formats */
-static const SampleFmtInfo sample_fmt_info[SAMPLE_FMT_NB] = {
-    [SAMPLE_FMT_U8]  = { .name = "u8",  .bits = 8 },
-    [SAMPLE_FMT_S16] = { .name = "s16", .bits = 16 },
-    [SAMPLE_FMT_S32] = { .name = "s32", .bits = 32 },
-    [SAMPLE_FMT_FLT] = { .name = "flt", .bits = 32 },
-    [SAMPLE_FMT_DBL] = { .name = "dbl", .bits = 64 },
-};
-
+#if FF_API_OLD_SAMPLE_FMT
 const char *avcodec_get_sample_fmt_name(int sample_fmt)
 {
-    if (sample_fmt < 0 || sample_fmt >= SAMPLE_FMT_NB)
-        return NULL;
-    return sample_fmt_info[sample_fmt].name;
+    return av_get_sample_fmt_name(sample_fmt);
 }
 
-enum SampleFormat avcodec_get_sample_fmt(const char* name)
+enum AVSampleFormat avcodec_get_sample_fmt(const char* name)
 {
-    int i;
-
-    for (i=0; i < SAMPLE_FMT_NB; i++)
-        if (!strcmp(sample_fmt_info[i].name, name))
-            return i;
-    return SAMPLE_FMT_NONE;
+    return av_get_sample_fmt(name);
 }
 
 void avcodec_sample_fmt_string (char *buf, int buf_size, int sample_fmt)
 {
-    /* print header */
-    if (sample_fmt < 0)
-        snprintf (buf, buf_size, "name  " " depth");
-    else if (sample_fmt < SAMPLE_FMT_NB) {
-        SampleFmtInfo info= sample_fmt_info[sample_fmt];
-        snprintf (buf, buf_size, "%-6s" "   %2d ", info.name, info.bits);
-    }
-}
-
-static const char* const channel_names[]={
-    "FL", "FR", "FC", "LFE", "BL",  "BR",  "FLC", "FRC",
-    "BC", "SL", "SR", "TC",  "TFL", "TFC", "TFR", "TBL",
-    "TBC", "TBR",
-    [29] = "DL",
-    [30] = "DR",
-};
-
-static const char *get_channel_name(int channel_id)
-{
-    if (channel_id<0 || channel_id>=FF_ARRAY_ELEMS(channel_names))
-        return NULL;
-    return channel_names[channel_id];
+    av_get_sample_fmt_string(buf, buf_size, sample_fmt);
 }
+#endif
 
 int64_t avcodec_guess_channel_layout(int nb_channels, enum CodecID codec_id, const char *fmt_name)
 {
     switch(nb_channels) {
-    case 1: return CH_LAYOUT_MONO;
-    case 2: return CH_LAYOUT_STEREO;
-    case 3: return CH_LAYOUT_SURROUND;
-    case 4: return CH_LAYOUT_QUAD;
-    case 5: return CH_LAYOUT_5POINT0;
-    case 6: return CH_LAYOUT_5POINT1;
-    case 8: return CH_LAYOUT_7POINT1;
+    case 1: return AV_CH_LAYOUT_MONO;
+    case 2: return AV_CH_LAYOUT_STEREO;
+    case 3: return AV_CH_LAYOUT_SURROUND;
+    case 4: return AV_CH_LAYOUT_QUAD;
+    case 5: return AV_CH_LAYOUT_5POINT0;
+    case 6: return AV_CH_LAYOUT_5POINT1;
+    case 8: return AV_CH_LAYOUT_7POINT1;
     default: return 0;
     }
 }
 
-static const struct {
-    const char *name;
-    int         nb_channels;
-    int64_t     layout;
-} channel_layout_map[] = {
-    { "mono",        1,  CH_LAYOUT_MONO },
-    { "stereo",      2,  CH_LAYOUT_STEREO },
-    { "4.0",         4,  CH_LAYOUT_4POINT0 },
-    { "quad",        4,  CH_LAYOUT_QUAD },
-    { "5.0",         5,  CH_LAYOUT_5POINT0 },
-    { "5.0",         5,  CH_LAYOUT_5POINT0_BACK },
-    { "5.1",         6,  CH_LAYOUT_5POINT1 },
-    { "5.1",         6,  CH_LAYOUT_5POINT1_BACK },
-    { "5.1+downmix", 8,  CH_LAYOUT_5POINT1|CH_LAYOUT_STEREO_DOWNMIX, },
-    { "7.1",         8,  CH_LAYOUT_7POINT1 },
-    { "7.1(wide)",   8,  CH_LAYOUT_7POINT1_WIDE },
-    { "7.1+downmix", 10, CH_LAYOUT_7POINT1|CH_LAYOUT_STEREO_DOWNMIX, },
-    { 0 }
-};
+#if FF_API_OLD_AUDIOCONVERT
+int64_t avcodec_get_channel_layout(const char *name)
+{
+    return av_get_channel_layout(name);
+}
 
 void avcodec_get_channel_layout_string(char *buf, int buf_size, int nb_channels, int64_t channel_layout)
 {
-    int i;
-
-    for (i=0; channel_layout_map[i].name; i++)
-        if (nb_channels    == channel_layout_map[i].nb_channels &&
-            channel_layout == channel_layout_map[i].layout) {
-            av_strlcpy(buf, channel_layout_map[i].name, buf_size);
-            return;
-        }
-
-    snprintf(buf, buf_size, "%d channels", nb_channels);
-    if (channel_layout) {
-        int i,ch;
-        av_strlcat(buf, " (", buf_size);
-        for(i=0,ch=0; i<64; i++) {
-            if ((channel_layout & (1L<<i))) {
-                const char *name = get_channel_name(i);
-                if (name) {
-                    if (ch>0) av_strlcat(buf, "|", buf_size);
-                    av_strlcat(buf, name, buf_size);
-                }
-                ch++;
-            }
-        }
-        av_strlcat(buf, ")", buf_size);
-    }
+    av_get_channel_layout_string(buf, buf_size, nb_channels, channel_layout);
 }
 
 int avcodec_channel_layout_num_channels(int64_t channel_layout)
 {
-    int count;
-    uint64_t x = channel_layout;
-    for (count = 0; x; count++)
-        x &= x-1; // unset lowest set bit
-    return count;
+    return av_get_channel_layout_nb_channels(channel_layout);
 }
+#endif
 
 struct AVAudioConvert {
     int in_channels, out_channels;
     int fmt_pair;
 };
 
-AVAudioConvert *av_audio_convert_alloc(enum SampleFormat out_fmt, int out_channels,
-                                       enum SampleFormat in_fmt, int in_channels,
+AVAudioConvert *av_audio_convert_alloc(enum AVSampleFormat out_fmt, int out_channels,
+                                       enum AVSampleFormat in_fmt, int in_channels,
                                        const float *matrix, int flags)
 {
     AVAudioConvert *ctx;
@@ -176,7 +96,7 @@ AVAudioConvert *av_audio_convert_alloc(enum SampleFormat out_fmt, int out_channe
         return NULL;
     ctx->in_channels = in_channels;
     ctx->out_channels = out_channels;
-    ctx->fmt_pair = out_fmt + SAMPLE_FMT_NB*in_fmt;
+    ctx->fmt_pair = out_fmt + AV_SAMPLE_FMT_NB*in_fmt;
     return ctx;
 }
 
@@ -203,7 +123,7 @@ int av_audio_convert(AVAudioConvert *ctx,
             continue;
 
 #define CONV(ofmt, otype, ifmt, expr)\
-if(ctx->fmt_pair == ofmt + SAMPLE_FMT_NB*ifmt){\
+if(ctx->fmt_pair == ofmt + AV_SAMPLE_FMT_NB*ifmt){\
     do{\
         *(otype*)po = expr; pi += is; po += os;\
     }while(po < end);\
@@ -212,31 +132,31 @@ if(ctx->fmt_pair == ofmt + SAMPLE_FMT_NB*ifmt){\
 //FIXME put things below under ifdefs so we do not waste space for cases no codec will need
 //FIXME rounding ?
 
-             CONV(SAMPLE_FMT_U8 , uint8_t, SAMPLE_FMT_U8 ,  *(const uint8_t*)pi)
-        else CONV(SAMPLE_FMT_S16, int16_t, SAMPLE_FMT_U8 , (*(const uint8_t*)pi - 0x80)<<8)
-        else CONV(SAMPLE_FMT_S32, int32_t, SAMPLE_FMT_U8 , (*(const uint8_t*)pi - 0x80)<<24)
-        else CONV(SAMPLE_FMT_FLT, float  , SAMPLE_FMT_U8 , (*(const uint8_t*)pi - 0x80)*(1.0 / (1<<7)))
-        else CONV(SAMPLE_FMT_DBL, double , SAMPLE_FMT_U8 , (*(const uint8_t*)pi - 0x80)*(1.0 / (1<<7)))
-        else CONV(SAMPLE_FMT_U8 , uint8_t, SAMPLE_FMT_S16, (*(const int16_t*)pi>>8) + 0x80)
-        else CONV(SAMPLE_FMT_S16, int16_t, SAMPLE_FMT_S16,  *(const int16_t*)pi)
-        else CONV(SAMPLE_FMT_S32, int32_t, SAMPLE_FMT_S16,  *(const int16_t*)pi<<16)
-        else CONV(SAMPLE_FMT_FLT, float  , SAMPLE_FMT_S16,  *(const int16_t*)pi*(1.0 / (1<<15)))
-        else CONV(SAMPLE_FMT_DBL, double , SAMPLE_FMT_S16,  *(const int16_t*)pi*(1.0 / (1<<15)))
-        else CONV(SAMPLE_FMT_U8 , uint8_t, SAMPLE_FMT_S32, (*(const int32_t*)pi>>24) + 0x80)
-        else CONV(SAMPLE_FMT_S16, int16_t, SAMPLE_FMT_S32,  *(const int32_t*)pi>>16)
-        else CONV(SAMPLE_FMT_S32, int32_t, SAMPLE_FMT_S32,  *(const int32_t*)pi)
-        else CONV(SAMPLE_FMT_FLT, float  , SAMPLE_FMT_S32,  *(const int32_t*)pi*(1.0 / (1<<31)))
-        else CONV(SAMPLE_FMT_DBL, double , SAMPLE_FMT_S32,  *(const int32_t*)pi*(1.0 / (1<<31)))
-        else CONV(SAMPLE_FMT_U8 , uint8_t, SAMPLE_FMT_FLT, av_clip_uint8(  lrintf(*(const float*)pi * (1<<7)) + 0x80))
-        else CONV(SAMPLE_FMT_S16, int16_t, SAMPLE_FMT_FLT, av_clip_int16(  lrintf(*(const float*)pi * (1<<15))))
-        else CONV(SAMPLE_FMT_S32, int32_t, SAMPLE_FMT_FLT, av_clipl_int32(llrintf(*(const float*)pi * (1U<<31))))
-        else CONV(SAMPLE_FMT_FLT, float  , SAMPLE_FMT_FLT, *(const float*)pi)
-        else CONV(SAMPLE_FMT_DBL, double , SAMPLE_FMT_FLT, *(const float*)pi)
-        else CONV(SAMPLE_FMT_U8 , uint8_t, SAMPLE_FMT_DBL, av_clip_uint8(  lrint(*(const double*)pi * (1<<7)) + 0x80))
-        else CONV(SAMPLE_FMT_S16, int16_t, SAMPLE_FMT_DBL, av_clip_int16(  lrint(*(const double*)pi * (1<<15))))
-        else CONV(SAMPLE_FMT_S32, int32_t, SAMPLE_FMT_DBL, av_clipl_int32(llrint(*(const double*)pi * (1U<<31))))
-        else CONV(SAMPLE_FMT_FLT, float  , SAMPLE_FMT_DBL, *(const double*)pi)
-        else CONV(SAMPLE_FMT_DBL, double , SAMPLE_FMT_DBL, *(const double*)pi)
+             CONV(AV_SAMPLE_FMT_U8 , uint8_t, AV_SAMPLE_FMT_U8 ,  *(const uint8_t*)pi)
+        else CONV(AV_SAMPLE_FMT_S16, int16_t, AV_SAMPLE_FMT_U8 , (*(const uint8_t*)pi - 0x80)<<8)
+        else CONV(AV_SAMPLE_FMT_S32, int32_t, AV_SAMPLE_FMT_U8 , (*(const uint8_t*)pi - 0x80)<<24)
+        else CONV(AV_SAMPLE_FMT_FLT, float  , AV_SAMPLE_FMT_U8 , (*(const uint8_t*)pi - 0x80)*(1.0 / (1<<7)))
+        else CONV(AV_SAMPLE_FMT_DBL, double , AV_SAMPLE_FMT_U8 , (*(const uint8_t*)pi - 0x80)*(1.0 / (1<<7)))
+        else CONV(AV_SAMPLE_FMT_U8 , uint8_t, AV_SAMPLE_FMT_S16, (*(const int16_t*)pi>>8) + 0x80)
+        else CONV(AV_SAMPLE_FMT_S16, int16_t, AV_SAMPLE_FMT_S16,  *(const int16_t*)pi)
+        else CONV(AV_SAMPLE_FMT_S32, int32_t, AV_SAMPLE_FMT_S16,  *(const int16_t*)pi<<16)
+        else CONV(AV_SAMPLE_FMT_FLT, float  , AV_SAMPLE_FMT_S16,  *(const int16_t*)pi*(1.0 / (1<<15)))
+        else CONV(AV_SAMPLE_FMT_DBL, double , AV_SAMPLE_FMT_S16,  *(const int16_t*)pi*(1.0 / (1<<15)))
+        else CONV(AV_SAMPLE_FMT_U8 , uint8_t, AV_SAMPLE_FMT_S32, (*(const int32_t*)pi>>24) + 0x80)
+        else CONV(AV_SAMPLE_FMT_S16, int16_t, AV_SAMPLE_FMT_S32,  *(const int32_t*)pi>>16)
+        else CONV(AV_SAMPLE_FMT_S32, int32_t, AV_SAMPLE_FMT_S32,  *(const int32_t*)pi)
+        else CONV(AV_SAMPLE_FMT_FLT, float  , AV_SAMPLE_FMT_S32,  *(const int32_t*)pi*(1.0 / (1U<<31)))
+        else CONV(AV_SAMPLE_FMT_DBL, double , AV_SAMPLE_FMT_S32,  *(const int32_t*)pi*(1.0 / (1U<<31)))
+        else CONV(AV_SAMPLE_FMT_U8 , uint8_t, AV_SAMPLE_FMT_FLT, av_clip_uint8(  lrintf(*(const float*)pi * (1<<7)) + 0x80))
+        else CONV(AV_SAMPLE_FMT_S16, int16_t, AV_SAMPLE_FMT_FLT, av_clip_int16(  lrintf(*(const float*)pi * (1<<15))))
+        else CONV(AV_SAMPLE_FMT_S32, int32_t, AV_SAMPLE_FMT_FLT, av_clipl_int32(llrintf(*(const float*)pi * (1U<<31))))
+        else CONV(AV_SAMPLE_FMT_FLT, float  , AV_SAMPLE_FMT_FLT, *(const float*)pi)
+        else CONV(AV_SAMPLE_FMT_DBL, double , AV_SAMPLE_FMT_FLT, *(const float*)pi)
+        else CONV(AV_SAMPLE_FMT_U8 , uint8_t, AV_SAMPLE_FMT_DBL, av_clip_uint8(  lrint(*(const double*)pi * (1<<7)) + 0x80))
+        else CONV(AV_SAMPLE_FMT_S16, int16_t, AV_SAMPLE_FMT_DBL, av_clip_int16(  lrint(*(const double*)pi * (1<<15))))
+        else CONV(AV_SAMPLE_FMT_S32, int32_t, AV_SAMPLE_FMT_DBL, av_clipl_int32(llrint(*(const double*)pi * (1U<<31))))
+        else CONV(AV_SAMPLE_FMT_FLT, float  , AV_SAMPLE_FMT_DBL, *(const double*)pi)
+        else CONV(AV_SAMPLE_FMT_DBL, double , AV_SAMPLE_FMT_DBL, *(const double*)pi)
         else return -1;
     }
     return 0;
diff --git a/libavcodec/audioconvert.h b/libavcodec/audioconvert.h
index 81b6cde..e9a78fe 100644
--- a/libavcodec/audioconvert.h
+++ b/libavcodec/audioconvert.h
@@ -3,20 +3,20 @@
  * Copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at>
  * Copyright (c) 2008 Peter Ross
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -29,42 +29,51 @@
  */
 
 
+#include "libavutil/cpu.h"
 #include "avcodec.h"
+#include "libavutil/audioconvert.h"
 
-
+#if FF_API_OLD_SAMPLE_FMT
 /**
- * Generate string corresponding to the sample format with
- * number sample_fmt, or a header if sample_fmt is negative.
- *
- * @param[in] buf the buffer where to write the string
- * @param[in] buf_size the size of buf
- * @param[in] sample_fmt the number of the sample format to print the corresponding info string, or
- * a negative value to print the corresponding header.
- * Meaningful values for obtaining a sample format info vary from 0 to SAMPLE_FMT_NB -1.
+ * @deprecated Use av_get_sample_fmt_string() instead.
  */
+attribute_deprecated
 void avcodec_sample_fmt_string(char *buf, int buf_size, int sample_fmt);
 
 /**
- * @return NULL on error
+ * @deprecated Use av_get_sample_fmt_name() instead.
  */
+attribute_deprecated
 const char *avcodec_get_sample_fmt_name(int sample_fmt);
 
 /**
- * @return SAMPLE_FMT_NONE on error
+ * @deprecated Use av_get_sample_fmt() instead.
  */
-enum SampleFormat avcodec_get_sample_fmt(const char* name);
+attribute_deprecated
+enum AVSampleFormat avcodec_get_sample_fmt(const char* name);
+#endif
 
+#if FF_API_OLD_AUDIOCONVERT
 /**
- * @return NULL on error
+ * @deprecated Use av_get_channel_layout() instead.
  */
-const char *avcodec_get_channel_name(int channel_id);
+attribute_deprecated
+int64_t avcodec_get_channel_layout(const char *name);
 
 /**
- * Return description of channel layout
+ * @deprecated Use av_get_channel_layout_string() instead.
  */
+attribute_deprecated
 void avcodec_get_channel_layout_string(char *buf, int buf_size, int nb_channels, int64_t channel_layout);
 
 /**
+ * @deprecated Use av_get_channel_layout_nb_channels() instead.
+ */
+attribute_deprecated
+int avcodec_channel_layout_num_channels(int64_t channel_layout);
+#endif
+
+/**
  * Guess the channel layout
  * @param nb_channels
  * @param codec_id Codec identifier, or CODEC_ID_NONE if unknown
@@ -73,11 +82,6 @@ void avcodec_get_channel_layout_string(char *buf, int buf_size, int nb_channels,
  */
 int64_t avcodec_guess_channel_layout(int nb_channels, enum CodecID codec_id, const char *fmt_name);
 
-/**
- * @return the number of channels in the channel layout.
- */
-int avcodec_channel_layout_num_channels(int64_t channel_layout);
-
 struct AVAudioConvert;
 typedef struct AVAudioConvert AVAudioConvert;
 
@@ -88,11 +92,11 @@ typedef struct AVAudioConvert AVAudioConvert;
  * @param in_fmt Input sample format
  * @param in_channels Number of input channels
  * @param[in] matrix Channel mixing matrix (of dimension in_channel*out_channels). Set to NULL to ignore.
- * @param flags See FF_MM_xx
+ * @param flags See AV_CPU_FLAG_xx
  * @return NULL on error
  */
-AVAudioConvert *av_audio_convert_alloc(enum SampleFormat out_fmt, int out_channels,
-                                       enum SampleFormat in_fmt, int in_channels,
+AVAudioConvert *av_audio_convert_alloc(enum AVSampleFormat out_fmt, int out_channels,
+                                       enum AVSampleFormat in_fmt, int in_channels,
                                        const float *matrix, int flags);
 
 /**
diff --git a/libavcodec/aura.c b/libavcodec/aura.c
index 8942cdd..e85e822 100644
--- a/libavcodec/aura.c
+++ b/libavcodec/aura.c
@@ -1,20 +1,20 @@
 /*
  * Aura 2 decoder
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -122,7 +122,7 @@ static av_cold int aura_decode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec aura2_decoder = {
+AVCodec ff_aura2_decoder = {
     "aura2",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_AURA2,
diff --git a/libavcodec/avcodec.h b/libavcodec/avcodec.h
index 974e87c..df4e617 100644
--- a/libavcodec/avcodec.h
+++ b/libavcodec/avcodec.h
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2001 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -27,28 +27,20 @@
  */
 
 #include <errno.h>
+#include "libavutil/samplefmt.h"
 #include "libavutil/avutil.h"
+#include "libavutil/cpu.h"
 
-#define LIBAVCODEC_VERSION_MAJOR 52
-#define LIBAVCODEC_VERSION_MINOR 72
-#define LIBAVCODEC_VERSION_MICRO  2
+#include "libavcodec/version.h"
 
-#define LIBAVCODEC_VERSION_INT  AV_VERSION_INT(LIBAVCODEC_VERSION_MAJOR, \
-                                               LIBAVCODEC_VERSION_MINOR, \
-                                               LIBAVCODEC_VERSION_MICRO)
-#define LIBAVCODEC_VERSION      AV_VERSION(LIBAVCODEC_VERSION_MAJOR,    \
-                                           LIBAVCODEC_VERSION_MINOR,    \
-                                           LIBAVCODEC_VERSION_MICRO)
-#define LIBAVCODEC_BUILD        LIBAVCODEC_VERSION_INT
-
-#define LIBAVCODEC_IDENT        "Lavc" AV_STRINGIFY(LIBAVCODEC_VERSION)
-
-#define AV_NOPTS_VALUE          INT64_C(0x8000000000000000)
-#define AV_TIME_BASE            1000000
-#define AV_TIME_BASE_Q          (AVRational){1, AV_TIME_BASE}
+#if LIBAVCODEC_VERSION_MAJOR < 53
+#   define FF_INTERNALC_MEM_TYPE unsigned int
+#else
+#   define FF_INTERNALC_MEM_TYPE size_t
+#endif
 
 /**
- * Identifies the syntax and semantics of the bitstream.
+ * Identify the syntax and semantics of the bitstream.
  * The principle is roughly:
  * Two decoders with the same ID can decode the same streams.
  * Two encoders with the same ID can encode compatible streams.
@@ -211,6 +203,16 @@ enum CodecID {
     CODEC_ID_KGV1,
     CODEC_ID_YOP,
     CODEC_ID_VP8,
+    CODEC_ID_PICTOR,
+    CODEC_ID_ANSI,
+    CODEC_ID_A64_MULTI,
+    CODEC_ID_A64_MULTI5,
+    CODEC_ID_R10K,
+    CODEC_ID_MXPEG,
+    CODEC_ID_LAGARITH,
+    CODEC_ID_PRORES,
+    CODEC_ID_JV,
+    CODEC_ID_DFA,
 
     /* various PCM "codecs" */
     CODEC_ID_PCM_S16LE= 0x10000,
@@ -238,6 +240,7 @@ enum CodecID {
     CODEC_ID_PCM_F64BE,
     CODEC_ID_PCM_F64LE,
     CODEC_ID_PCM_BLURAY,
+    CODEC_ID_PCM_LXF,
 
     /* various ADPCM codecs */
     CODEC_ID_ADPCM_IMA_QT= 0x11000,
@@ -268,6 +271,7 @@ enum CodecID {
     CODEC_ID_ADPCM_EA_XAS,
     CODEC_ID_ADPCM_EA_MAXIS_XA,
     CODEC_ID_ADPCM_IMA_ISS,
+    CODEC_ID_ADPCM_G722,
 
     /* AMR */
     CODEC_ID_AMR_NB= 0x12000,
@@ -336,6 +340,8 @@ enum CodecID {
     CODEC_ID_ATRAC1,
     CODEC_ID_BINKAUDIO_RDFT,
     CODEC_ID_BINKAUDIO_DCT,
+    CODEC_ID_AAC_LATM,
+    CODEC_ID_QDMC,
 
     /* subtitle codecs */
     CODEC_ID_DVD_SUBTITLE= 0x17000,
@@ -346,6 +352,7 @@ enum CodecID {
     CODEC_ID_MOV_TEXT,
     CODEC_ID_HDMV_PGS_SUBTITLE,
     CODEC_ID_DVB_TELETEXT,
+    CODEC_ID_SRT,
 
     /* other specific kind of codecs (generally used for attachments) */
     CODEC_ID_TTF= 0x18000,
@@ -354,6 +361,7 @@ enum CodecID {
 
     CODEC_ID_MPEG2TS= 0x20000, /**< _FAKE_ codec to indicate a raw MPEG-2 TS
                                 * stream (only used by libavformat) */
+    CODEC_ID_FFMETADATA=0x21000,   ///< Dummy codec for streams containing only metadata information.
 };
 
 #if LIBAVCODEC_VERSION_MAJOR < 53
@@ -368,63 +376,65 @@ enum CodecID {
 #define CODEC_TYPE_NB         AVMEDIA_TYPE_NB
 #endif
 
-/**
- * all in native-endian format
- */
-enum SampleFormat {
-    SAMPLE_FMT_NONE = -1,
-    SAMPLE_FMT_U8,              ///< unsigned 8 bits
-    SAMPLE_FMT_S16,             ///< signed 16 bits
-    SAMPLE_FMT_S32,             ///< signed 32 bits
-    SAMPLE_FMT_FLT,             ///< float
-    SAMPLE_FMT_DBL,             ///< double
-    SAMPLE_FMT_NB               ///< Number of sample formats. DO NOT USE if dynamically linking to libavcodec
-};
+#if FF_API_OLD_SAMPLE_FMT
+#define SampleFormat AVSampleFormat
+
+#define SAMPLE_FMT_NONE AV_SAMPLE_FMT_NONE
+#define SAMPLE_FMT_U8   AV_SAMPLE_FMT_U8
+#define SAMPLE_FMT_S16  AV_SAMPLE_FMT_S16
+#define SAMPLE_FMT_S32  AV_SAMPLE_FMT_S32
+#define SAMPLE_FMT_FLT  AV_SAMPLE_FMT_FLT
+#define SAMPLE_FMT_DBL  AV_SAMPLE_FMT_DBL
+#define SAMPLE_FMT_NB   AV_SAMPLE_FMT_NB
+#endif
+
+#if FF_API_OLD_AUDIOCONVERT
+#include "libavutil/audioconvert.h"
 
 /* Audio channel masks */
-#define CH_FRONT_LEFT             0x00000001
-#define CH_FRONT_RIGHT            0x00000002
-#define CH_FRONT_CENTER           0x00000004
-#define CH_LOW_FREQUENCY          0x00000008
-#define CH_BACK_LEFT              0x00000010
-#define CH_BACK_RIGHT             0x00000020
-#define CH_FRONT_LEFT_OF_CENTER   0x00000040
-#define CH_FRONT_RIGHT_OF_CENTER  0x00000080
-#define CH_BACK_CENTER            0x00000100
-#define CH_SIDE_LEFT              0x00000200
-#define CH_SIDE_RIGHT             0x00000400
-#define CH_TOP_CENTER             0x00000800
-#define CH_TOP_FRONT_LEFT         0x00001000
-#define CH_TOP_FRONT_CENTER       0x00002000
-#define CH_TOP_FRONT_RIGHT        0x00004000
-#define CH_TOP_BACK_LEFT          0x00008000
-#define CH_TOP_BACK_CENTER        0x00010000
-#define CH_TOP_BACK_RIGHT         0x00020000
-#define CH_STEREO_LEFT            0x20000000  ///< Stereo downmix.
-#define CH_STEREO_RIGHT           0x40000000  ///< See CH_STEREO_LEFT.
+#define CH_FRONT_LEFT            AV_CH_FRONT_LEFT
+#define CH_FRONT_RIGHT           AV_CH_FRONT_RIGHT
+#define CH_FRONT_CENTER          AV_CH_FRONT_CENTER
+#define CH_LOW_FREQUENCY         AV_CH_LOW_FREQUENCY
+#define CH_BACK_LEFT             AV_CH_BACK_LEFT
+#define CH_BACK_RIGHT            AV_CH_BACK_RIGHT
+#define CH_FRONT_LEFT_OF_CENTER  AV_CH_FRONT_LEFT_OF_CENTER
+#define CH_FRONT_RIGHT_OF_CENTER AV_CH_FRONT_RIGHT_OF_CENTER
+#define CH_BACK_CENTER           AV_CH_BACK_CENTER
+#define CH_SIDE_LEFT             AV_CH_SIDE_LEFT
+#define CH_SIDE_RIGHT            AV_CH_SIDE_RIGHT
+#define CH_TOP_CENTER            AV_CH_TOP_CENTER
+#define CH_TOP_FRONT_LEFT        AV_CH_TOP_FRONT_LEFT
+#define CH_TOP_FRONT_CENTER      AV_CH_TOP_FRONT_CENTER
+#define CH_TOP_FRONT_RIGHT       AV_CH_TOP_FRONT_RIGHT
+#define CH_TOP_BACK_LEFT         AV_CH_TOP_BACK_LEFT
+#define CH_TOP_BACK_CENTER       AV_CH_TOP_BACK_CENTER
+#define CH_TOP_BACK_RIGHT        AV_CH_TOP_BACK_RIGHT
+#define CH_STEREO_LEFT           AV_CH_STEREO_LEFT
+#define CH_STEREO_RIGHT          AV_CH_STEREO_RIGHT
 
 /** Channel mask value used for AVCodecContext.request_channel_layout
     to indicate that the user requests the channel order of the decoder output
     to be the native codec channel order. */
-#define CH_LAYOUT_NATIVE          0x8000000000000000LL
+#define CH_LAYOUT_NATIVE         AV_CH_LAYOUT_NATIVE
 
 /* Audio channel convenience macros */
-#define CH_LAYOUT_MONO              (CH_FRONT_CENTER)
-#define CH_LAYOUT_STEREO            (CH_FRONT_LEFT|CH_FRONT_RIGHT)
-#define CH_LAYOUT_2_1               (CH_LAYOUT_STEREO|CH_BACK_CENTER)
-#define CH_LAYOUT_SURROUND          (CH_LAYOUT_STEREO|CH_FRONT_CENTER)
-#define CH_LAYOUT_4POINT0           (CH_LAYOUT_SURROUND|CH_BACK_CENTER)
-#define CH_LAYOUT_2_2               (CH_LAYOUT_STEREO|CH_SIDE_LEFT|CH_SIDE_RIGHT)
-#define CH_LAYOUT_QUAD              (CH_LAYOUT_STEREO|CH_BACK_LEFT|CH_BACK_RIGHT)
-#define CH_LAYOUT_5POINT0           (CH_LAYOUT_SURROUND|CH_SIDE_LEFT|CH_SIDE_RIGHT)
-#define CH_LAYOUT_5POINT1           (CH_LAYOUT_5POINT0|CH_LOW_FREQUENCY)
-#define CH_LAYOUT_5POINT0_BACK      (CH_LAYOUT_SURROUND|CH_BACK_LEFT|CH_BACK_RIGHT)
-#define CH_LAYOUT_5POINT1_BACK      (CH_LAYOUT_5POINT0_BACK|CH_LOW_FREQUENCY)
-#define CH_LAYOUT_7POINT0           (CH_LAYOUT_5POINT0|CH_BACK_LEFT|CH_BACK_RIGHT)
-#define CH_LAYOUT_7POINT1           (CH_LAYOUT_5POINT1|CH_BACK_LEFT|CH_BACK_RIGHT)
-#define CH_LAYOUT_7POINT1_WIDE      (CH_LAYOUT_5POINT1_BACK|\
-                                          CH_FRONT_LEFT_OF_CENTER|CH_FRONT_RIGHT_OF_CENTER)
-#define CH_LAYOUT_STEREO_DOWNMIX    (CH_STEREO_LEFT|CH_STEREO_RIGHT)
+#define CH_LAYOUT_MONO           AV_CH_LAYOUT_MONO
+#define CH_LAYOUT_STEREO         AV_CH_LAYOUT_STEREO
+#define CH_LAYOUT_2_1            AV_CH_LAYOUT_2_1
+#define CH_LAYOUT_SURROUND       AV_CH_LAYOUT_SURROUND
+#define CH_LAYOUT_4POINT0        AV_CH_LAYOUT_4POINT0
+#define CH_LAYOUT_2_2            AV_CH_LAYOUT_2_2
+#define CH_LAYOUT_QUAD           AV_CH_LAYOUT_QUAD
+#define CH_LAYOUT_5POINT0        AV_CH_LAYOUT_5POINT0
+#define CH_LAYOUT_5POINT1        AV_CH_LAYOUT_5POINT1
+#define CH_LAYOUT_5POINT0_BACK   AV_CH_LAYOUT_5POINT0_BACK
+#define CH_LAYOUT_5POINT1_BACK   AV_CH_LAYOUT_5POINT1_BACK
+#define CH_LAYOUT_7POINT0        AV_CH_LAYOUT_7POINT0
+#define CH_LAYOUT_7POINT1        AV_CH_LAYOUT_7POINT1
+#define CH_LAYOUT_7POINT1_WIDE   AV_CH_LAYOUT_7POINT1_WIDE
+#define CH_LAYOUT_STEREO_DOWNMIX AV_CH_LAYOUT_STEREO_DOWNMIX
+#endif
 
 /* in bytes */
 #define AVCODEC_MAX_AUDIO_FRAME_SIZE 192000 // 1 second of 48khz 32bit audio
@@ -525,6 +535,31 @@ enum AVChromaLocation{
     AVCHROMA_LOC_NB           , ///< Not part of ABI
 };
 
+/**
+ * LPC analysis type
+ */
+enum AVLPCType {
+    AV_LPC_TYPE_DEFAULT     = -1, ///< use the codec default LPC type
+    AV_LPC_TYPE_NONE        =  0, ///< do not use LPC prediction or use all zero coefficients
+    AV_LPC_TYPE_FIXED       =  1, ///< fixed LPC coefficients
+    AV_LPC_TYPE_LEVINSON    =  2, ///< Levinson-Durbin recursion
+    AV_LPC_TYPE_CHOLESKY    =  3, ///< Cholesky factorization
+    AV_LPC_TYPE_NB              , ///< Not part of ABI
+};
+
+enum AVAudioServiceType {
+    AV_AUDIO_SERVICE_TYPE_MAIN              = 0,
+    AV_AUDIO_SERVICE_TYPE_EFFECTS           = 1,
+    AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED = 2,
+    AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED  = 3,
+    AV_AUDIO_SERVICE_TYPE_DIALOGUE          = 4,
+    AV_AUDIO_SERVICE_TYPE_COMMENTARY        = 5,
+    AV_AUDIO_SERVICE_TYPE_EMERGENCY         = 6,
+    AV_AUDIO_SERVICE_TYPE_VOICE_OVER        = 7,
+    AV_AUDIO_SERVICE_TYPE_KARAOKE           = 8,
+    AV_AUDIO_SERVICE_TYPE_NB                   , ///< Not part of ABI
+};
+
 typedef struct RcOverride{
     int start_frame;
     int end_frame;
@@ -598,6 +633,7 @@ typedef struct RcOverride{
 #define CODEC_FLAG2_MBTREE        0x00040000 ///< Use macroblock tree ratecontrol (x264 only)
 #define CODEC_FLAG2_PSY           0x00080000 ///< Use psycho visual optimizations.
 #define CODEC_FLAG2_SSIM          0x00100000 ///< Compute SSIM during encoding, error[] values are undefined.
+#define CODEC_FLAG2_INTRA_REFRESH 0x00200000 ///< Use periodic insertion of intra blocks instead of keyframes.
 
 /* Unsupported options :
  *              Syntax Arithmetic coding (SAC)
@@ -649,6 +685,18 @@ typedef struct RcOverride{
  * encoders
  */
 #define CODEC_CAP_EXPERIMENTAL     0x0200
+/**
+ * Codec should fill in channel configuration and samplerate instead of container
+ */
+#define CODEC_CAP_CHANNEL_CONF     0x0400
+/**
+ * Codec is able to deal with negative linesizes
+ */
+#define CODEC_CAP_NEG_LINESIZES    0x0800
+/**
+ * Codec supports frame-level multithreading.
+ */
+#define CODEC_CAP_FRAME_THREADS    0x1000
 
 //The following defines may change, don't expect compatibility if you use them.
 #define MB_TYPE_INTRA4x4   0x0001
@@ -916,8 +964,13 @@ typedef struct AVPanScan{
     int8_t *ref_index[2];\
 \
     /**\
-     * reordered opaque 64bit number (generally a PTS) from AVCodecContext.reordered_opaque\
-     * output in AVFrame.reordered_opaque\
+     * reordered opaque 64bit (generally an integer or a double precision float\
+     * PTS but can be anything). \
+     * The user sets AVCodecContext.reordered_opaque to represent the input at\
+     * that time,\
+     * the decoder reorders values as needed and sets AVFrame.reordered_opaque\
+     * to exactly one of the values provided by the user through AVCodecContext.reordered_opaque \
+     * @deprecated in favor of pkt_pts\
      * - encoding: unused\
      * - decoding: Read by user.\
      */\
@@ -929,7 +982,34 @@ typedef struct AVPanScan{
      * - decoding: Set by libavcodec\
      */\
     void *hwaccel_picture_private;\
-
+\
+    /**\
+     * reordered pts from the last AVPacket that has been input into the decoder\
+     * - encoding: unused\
+     * - decoding: Read by user.\
+     */\
+    int64_t pkt_pts;\
+\
+    /**\
+     * dts from the last AVPacket that has been input into the decoder\
+     * - encoding: unused\
+     * - decoding: Read by user.\
+     */\
+    int64_t pkt_dts;\
+\
+    /**\
+     * the AVCodecContext which ff_thread_get_buffer() was last called on\
+     * - encoding: Set by libavcodec.\
+     * - decoding: Set by libavcodec.\
+     */\
+    struct AVCodecContext *owner;\
+\
+    /**\
+     * used by multithreading to store frame-specific info\
+     * - encoding: Set by libavcodec.\
+     * - decoding: Set by libavcodec.\
+     */\
+    void *thread_opaque;\
 
 #define FF_QSCALE_TYPE_MPEG1 0
 #define FF_QSCALE_TYPE_MPEG2 1
@@ -955,6 +1035,10 @@ typedef struct AVPanScan{
 #define FF_BUFFER_HINTS_PRESERVE 0x04 // User must not alter buffer content.
 #define FF_BUFFER_HINTS_REUSABLE 0x08 // Codec will reuse the buffer (update).
 
+enum AVPacketSideDataType {
+    AV_PKT_DATA_PALETTE,
+};
+
 typedef struct AVPacket {
     /**
      * Presentation timestamp in AVStream->time_base units; the time at which
@@ -977,6 +1061,17 @@ typedef struct AVPacket {
     int   stream_index;
     int   flags;
     /**
+     * Additional packet data that can be provided by the container.
+     * Packet can contain several types of side information.
+     */
+    struct {
+        uint8_t *data;
+        int      size;
+        enum AVPacketSideDataType type;
+    } *side_data;
+    int side_data_elems;
+
+    /**
      * Duration of this packet in AVStream->time_base units, 0 if unknown.
      * Equals next_pts - this_pts in presentation order.
      */
@@ -993,6 +1088,8 @@ typedef struct AVPacket {
      * the very first frame or from this keyframe.
      * Is AV_NOPTS_VALUE if unknown.
      * This field is not the display duration of the current packet.
+     * This field has no meaning if the packet does not have AV_PKT_FLAG_KEY
+     * set.
      *
      * The purpose of this field is to allow seeking in streams that have no
      * keyframes in the conventional sense. It corresponds to the
@@ -1119,24 +1216,32 @@ typedef struct AVCodecContext {
 
     /**
      * Pixel format, see PIX_FMT_xxx.
+     * May be set by the demuxer if known from headers.
+     * May be overriden by the decoder if it knows better.
      * - encoding: Set by user.
-     * - decoding: Set by libavcodec.
+     * - decoding: Set by user if known, overridden by libavcodec if known
      */
     enum PixelFormat pix_fmt;
 
+#if FF_API_RATE_EMU
     /**
      * Frame rate emulation. If not zero, the lower layer (i.e. format handler)
      * has to read frames at native frame rate.
      * - encoding: Set by user.
      * - decoding: unused
      */
-    int rate_emu;
+    attribute_deprecated int rate_emu;
+#endif
 
     /**
      * If non NULL, 'draw_horiz_band' is called by the libavcodec
      * decoder to draw a horizontal band. It improves cache usage. Not
      * all codecs can do that. You must check the codec capabilities
      * beforehand.
+     * When multithreading is used, it may be called from multiple threads
+     * at the same time; threads might draw different parts of the same AVFrame,
+     * or multiple AVFrames, and there is no guarantee that slices will be drawn
+     * in order.
      * The function is also used by hardware acceleration APIs.
      * It is called at least once during frame decoding to pass
      * the data needed for hardware render.
@@ -1164,7 +1269,7 @@ typedef struct AVCodecContext {
      * - encoding: Set by user.
      * - decoding: Set by libavcodec.
      */
-    enum SampleFormat sample_fmt;  ///< sample format
+    enum AVSampleFormat sample_fmt;  ///< sample format
 
     /* The following data should not be initialized. */
     /**
@@ -1232,13 +1337,15 @@ typedef struct AVCodecContext {
 
     int b_frame_strategy;
 
+#if FF_API_HURRY_UP
     /**
      * hurry up amount
      * - encoding: unused
      * - decoding: Set by user. 1-> Skip B-frames, 2-> Skip IDCT/dequant too, 5-> Skip everything except header
      * @deprecated Deprecated in favor of skip_idct and skip_frame.
      */
-    int hurry_up;
+    attribute_deprecated int hurry_up;
+#endif
 
     struct AVCodec *codec;
 
@@ -1346,18 +1453,21 @@ typedef struct AVCodecContext {
      * - encoding: Set by user.
      * - decoding: Set by user.
      * Setting this to STRICT or higher means the encoder and decoder will
-     * generally do stupid things. While setting it to inofficial or lower
-     * will mean the encoder might use things that are not supported by all
-     * spec compliant decoders. Decoders make no difference between normal,
-     * inofficial and experimental, that is they always try to decode things
-     * when they can unless they are explicitly asked to behave stupid
+     * generally do stupid things, whereas setting it to unofficial or lower
+     * will mean the encoder might produce output that is not supported by all
+     * spec-compliant decoders. Decoders don't differentiate between normal,
+     * unofficial and experimental (that is, they always try to decode things
+     * when they can) unless they are explicitly asked to behave stupidly
      * (=strictly conform to the specs)
      */
     int strict_std_compliance;
-#define FF_COMPLIANCE_VERY_STRICT   2 ///< Strictly conform to a older more strict version of the spec or reference software.
+#define FF_COMPLIANCE_VERY_STRICT   2 ///< Strictly conform to an older more strict version of the spec or reference software.
 #define FF_COMPLIANCE_STRICT        1 ///< Strictly conform to all the things in the spec no matter what consequences.
 #define FF_COMPLIANCE_NORMAL        0
-#define FF_COMPLIANCE_INOFFICIAL   -1 ///< Allow inofficial extensions.
+#if FF_API_INOFFICIAL
+#define FF_COMPLIANCE_INOFFICIAL   -1 ///< Allow inofficial extensions (deprecated - use FF_COMPLIANCE_UNOFFICIAL instead).
+#endif
+#define FF_COMPLIANCE_UNOFFICIAL   -1 ///< Allow unofficial extensions
 #define FF_COMPLIANCE_EXPERIMENTAL -2 ///< Allow nonstandardized experimental things.
 
     /**
@@ -1387,8 +1497,11 @@ typedef struct AVCodecContext {
      * if CODEC_CAP_DR1 is not set then get_buffer() must call
      * avcodec_default_get_buffer() instead of providing buffers allocated by
      * some other means.
+     * If frame multithreading is used and thread_safe_callbacks is set,
+     * it may be called from a different thread, but not from more than one at once.
+     * Does not need to be reentrant.
      * - encoding: unused
-     * - decoding: Set by libavcodec., user can override.
+     * - decoding: Set by libavcodec, user can override.
      */
     int (*get_buffer)(struct AVCodecContext *c, AVFrame *pic);
 
@@ -1396,8 +1509,10 @@ typedef struct AVCodecContext {
      * Called to release buffers which were allocated with get_buffer.
      * A released buffer can be reused in get_buffer().
      * pic.data[*] must be set to NULL.
+     * May be called from a different thread if frame multithreading is used,
+     * but not by more than one thread at once, so does not need to be reentrant.
      * - encoding: unused
-     * - decoding: Set by libavcodec., user can override.
+     * - decoding: Set by libavcodec, user can override.
      */
     void (*release_buffer)(struct AVCodecContext *c, AVFrame *pic);
 
@@ -1624,23 +1739,25 @@ typedef struct AVCodecContext {
      * result into program crash.)
      */
     unsigned dsp_mask;
-#define FF_MM_FORCE    0x80000000 /* Force usage of selected flags (OR) */
-    /* lower 16 bits - CPU features */
-#define FF_MM_MMX      0x0001 ///< standard MMX
-#define FF_MM_3DNOW    0x0004 ///< AMD 3DNOW
-#if LIBAVCODEC_VERSION_MAJOR < 53
-#define FF_MM_MMXEXT   0x0002 ///< SSE integer functions or AMD MMX ext
+
+#if FF_API_MM_FLAGS
+#define FF_MM_FORCE      AV_CPU_FLAG_FORCE
+#define FF_MM_MMX        AV_CPU_FLAG_MMX
+#define FF_MM_3DNOW      AV_CPU_FLAG_3DNOW
+#define FF_MM_MMXEXT     AV_CPU_FLAG_MMX2
+#define FF_MM_MMX2       AV_CPU_FLAG_MMX2
+#define FF_MM_SSE        AV_CPU_FLAG_SSE
+#define FF_MM_SSE2       AV_CPU_FLAG_SSE2
+#define FF_MM_SSE2SLOW   AV_CPU_FLAG_SSE2SLOW
+#define FF_MM_3DNOWEXT   AV_CPU_FLAG_3DNOWEXT
+#define FF_MM_SSE3       AV_CPU_FLAG_SSE3
+#define FF_MM_SSE3SLOW   AV_CPU_FLAG_SSE3SLOW
+#define FF_MM_SSSE3      AV_CPU_FLAG_SSSE3
+#define FF_MM_SSE4       AV_CPU_FLAG_SSE4
+#define FF_MM_SSE42      AV_CPU_FLAG_SSE42
+#define FF_MM_IWMMXT     AV_CPU_FLAG_IWMMXT
+#define FF_MM_ALTIVEC    AV_CPU_FLAG_ALTIVEC
 #endif
-#define FF_MM_MMX2     0x0002 ///< SSE integer functions or AMD MMX ext
-#define FF_MM_SSE      0x0008 ///< SSE functions
-#define FF_MM_SSE2     0x0010 ///< PIV SSE2 functions
-#define FF_MM_3DNOWEXT 0x0020 ///< AMD 3DNowExt
-#define FF_MM_SSE3     0x0040 ///< Prescott SSE3 functions
-#define FF_MM_SSSE3    0x0080 ///< Conroe SSSE3 functions
-#define FF_MM_SSE4     0x0100 ///< Penryn SSE4.1 functions
-#define FF_MM_SSE42    0x0200 ///< Nehalem SSE4.2 functions
-#define FF_MM_IWMMXT   0x0100 ///< XScale IWMMXT
-#define FF_MM_ALTIVEC  0x0001 ///< standard AltiVec
 
     /**
      * bits per sample/pixel from the demuxer (needed for huffyuv).
@@ -1697,6 +1814,7 @@ typedef struct AVCodecContext {
 #define FF_DEBUG_VIS_QP      0x00002000
 #define FF_DEBUG_VIS_MB_TYPE 0x00004000
 #define FF_DEBUG_BUFFERS     0x00008000
+#define FF_DEBUG_THREADS     0x00010000
 
     /**
      * debug
@@ -1715,19 +1833,21 @@ typedef struct AVCodecContext {
      */
     uint64_t error[4];
 
+#if FF_API_MB_Q
     /**
      * minimum MB quantizer
      * - encoding: unused
      * - decoding: unused
      */
-    int mb_qmin;
+    attribute_deprecated int mb_qmin;
 
     /**
      * maximum MB quantizer
      * - encoding: unused
      * - decoding: unused
      */
-    int mb_qmax;
+    attribute_deprecated int mb_qmax;
+#endif
 
     /**
      * motion estimation comparison function
@@ -1884,12 +2004,6 @@ typedef struct AVCodecContext {
      */
     void *internal_buffer;
 
-#define FF_LAMBDA_SHIFT 7
-#define FF_LAMBDA_SCALE (1<<FF_LAMBDA_SHIFT)
-#define FF_QP2LAMBDA 118 ///< factor to convert from H.263 QP to lambda
-#define FF_LAMBDA_MAX (256*128-1)
-
-#define FF_QUALITY_SCALE FF_LAMBDA_SCALE //FIXME maybe remove
     /**
      * Global quality for codecs which cannot change it per frame.
      * This should be proportional to MPEG-1/2/4 qscale.
@@ -1996,12 +2110,14 @@ typedef struct AVCodecContext {
      */
     int lmax;
 
+#if FF_API_PALETTE_CONTROL
     /**
      * palette control structure
      * - encoding: ??? (no palette-enabled encoder yet)
      * - decoding: Set by user.
      */
     struct AVPaletteControl *palctrl;
+#endif
 
     /**
      * noise reduction strength
@@ -2020,7 +2136,7 @@ typedef struct AVCodecContext {
      * avcodec_default_reget_buffer() instead of providing buffers allocated by
      * some other means.
      * - encoding: unused
-     * - decoding: Set by libavcodec., user can override
+     * - decoding: Set by libavcodec, user can override.
      */
     int (*reget_buffer)(struct AVCodecContext *c, AVFrame *pic);
 
@@ -2052,16 +2168,19 @@ typedef struct AVCodecContext {
      */
     int error_rate;
 
+#if FF_API_ANTIALIAS_ALGO
     /**
      * MP3 antialias algorithm, see FF_AA_* below.
      * - encoding: unused
      * - decoding: Set by user.
      */
-    int antialias_algo;
+    attribute_deprecated int antialias_algo;
 #define FF_AA_AUTO    0
 #define FF_AA_FASTINT 1 //not implemented yet
 #define FF_AA_INT     2
 #define FF_AA_FLOAT   3
+#endif
+
     /**
      * quantizer noise shaping
      * - encoding: Set by user.
@@ -2147,20 +2266,47 @@ typedef struct AVCodecContext {
      */
      int profile;
 #define FF_PROFILE_UNKNOWN -99
+#define FF_PROFILE_RESERVED -100
 
 #define FF_PROFILE_AAC_MAIN 0
 #define FF_PROFILE_AAC_LOW  1
 #define FF_PROFILE_AAC_SSR  2
 #define FF_PROFILE_AAC_LTP  3
 
-#define FF_PROFILE_H264_BASELINE    66
-#define FF_PROFILE_H264_MAIN        77
-#define FF_PROFILE_H264_EXTENDED    88
-#define FF_PROFILE_H264_HIGH        100
-#define FF_PROFILE_H264_HIGH_10     110
-#define FF_PROFILE_H264_HIGH_422    122
-#define FF_PROFILE_H264_HIGH_444    244
-#define FF_PROFILE_H264_CAVLC_444   44
+#define FF_PROFILE_DTS         20
+#define FF_PROFILE_DTS_ES      30
+#define FF_PROFILE_DTS_96_24   40
+#define FF_PROFILE_DTS_HD_HRA  50
+#define FF_PROFILE_DTS_HD_MA   60
+
+#define FF_PROFILE_MPEG2_422    0
+#define FF_PROFILE_MPEG2_HIGH   1
+#define FF_PROFILE_MPEG2_SS     2
+#define FF_PROFILE_MPEG2_SNR_SCALABLE  3
+#define FF_PROFILE_MPEG2_MAIN   4
+#define FF_PROFILE_MPEG2_SIMPLE 5
+
+#define FF_PROFILE_H264_CONSTRAINED  (1<<9)  // 8+1; constraint_set1_flag
+#define FF_PROFILE_H264_INTRA        (1<<11) // 8+3; constraint_set3_flag
+
+#define FF_PROFILE_H264_BASELINE             66
+#define FF_PROFILE_H264_CONSTRAINED_BASELINE (66|FF_PROFILE_H264_CONSTRAINED)
+#define FF_PROFILE_H264_MAIN                 77
+#define FF_PROFILE_H264_EXTENDED             88
+#define FF_PROFILE_H264_HIGH                 100
+#define FF_PROFILE_H264_HIGH_10              110
+#define FF_PROFILE_H264_HIGH_10_INTRA        (110|FF_PROFILE_H264_INTRA)
+#define FF_PROFILE_H264_HIGH_422             122
+#define FF_PROFILE_H264_HIGH_422_INTRA       (122|FF_PROFILE_H264_INTRA)
+#define FF_PROFILE_H264_HIGH_444             144
+#define FF_PROFILE_H264_HIGH_444_PREDICTIVE  244
+#define FF_PROFILE_H264_HIGH_444_INTRA       (244|FF_PROFILE_H264_INTRA)
+#define FF_PROFILE_H264_CAVLC_444            44
+
+#define FF_PROFILE_VC1_SIMPLE   0
+#define FF_PROFILE_VC1_MAIN     1
+#define FF_PROFILE_VC1_COMPLEX  2
+#define FF_PROFILE_VC1_ADVANCED 3
 
     /**
      * level
@@ -2404,12 +2550,15 @@ typedef struct AVCodecContext {
     int compression_level;
 #define FF_COMPRESSION_DEFAULT -1
 
+#if FF_API_USE_LPC
     /**
      * Sets whether to use LPC mode - used by FLAC encoder.
      * - encoding: Set by user.
      * - decoding: unused
+     * @deprecated Deprecated in favor of lpc_type and lpc_passes.
      */
     int use_lpc;
+#endif
 
     /**
      * LPC coefficient precision - used by FLAC encoder
@@ -2456,7 +2605,7 @@ typedef struct AVCodecContext {
      */
     int64_t timecode_frame_start;
 
-#if LIBAVCODEC_VERSION_MAJOR < 53
+#if FF_API_REQUEST_CHANNELS
     /**
      * Decoder should decode to this many channels if it can (0 for default)
      * - encoding: unused
@@ -2477,6 +2626,7 @@ typedef struct AVCodecContext {
     /**
      * opaque 64bit number (generally a PTS) that will be reordered and
      * output in AVFrame.reordered_opaque
+     * @deprecated in favor of pkt_pts
      * - encoding: unused
      * - decoding: Set by user.
      */
@@ -2484,7 +2634,7 @@ typedef struct AVCodecContext {
 
     /**
      * Bits per sample/pixel of internal libavcodec pixel/sample format.
-     * This field is applicable only when sample_fmt is SAMPLE_FMT_S32.
+     * This field is applicable only when sample_fmt is AV_SAMPLE_FMT_S32.
      * - encoding: set by user.
      * - decoding: set by libavcodec.
      */
@@ -2652,9 +2802,124 @@ typedef struct AVCodecContext {
      * - decoding: unused
      */
     int rc_lookahead;
+
+    /**
+     * Constant rate factor maximum
+     * With CRF encoding mode and VBV restrictions enabled, prevents quality from being worse
+     * than crf_max, even if doing so would violate VBV restrictions.
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    float crf_max;
+
+    int log_level_offset;
+
+    /**
+     * Determines which LPC analysis algorithm to use.
+     * - encoding: Set by user
+     * - decoding: unused
+     */
+    enum AVLPCType lpc_type;
+
+    /**
+     * Number of passes to use for Cholesky factorization during LPC analysis
+     * - encoding: Set by user
+     * - decoding: unused
+     */
+    int lpc_passes;
+
+    /**
+     * Number of slices.
+     * Indicates number of picture subdivisions. Used for parallelized
+     * decoding.
+     * - encoding: Set by user
+     * - decoding: unused
+     */
+    int slices;
+
+    /**
+     * Header containing style information for text subtitles.
+     * For SUBTITLE_ASS subtitle type, it should contain the whole ASS
+     * [Script Info] and [V4+ Styles] section, plus the [Events] line and
+     * the Format line following. It shouldn't include any Dialogue line.
+     * - encoding: Set/allocated/freed by user (before avcodec_open())
+     * - decoding: Set/allocated/freed by libavcodec (by avcodec_open())
+     */
+    uint8_t *subtitle_header;
+    int subtitle_header_size;
+
+    /**
+     * Current packet as passed into the decoder, to avoid having
+     * to pass the packet into every function. Currently only valid
+     * inside lavc and get/release_buffer callbacks.
+     * - decoding: set by avcodec_decode_*, read by get_buffer() for setting pkt_pts
+     * - encoding: unused
+     */
+    AVPacket *pkt;
+
+    /**
+     * Whether this is a copy of the context which had init() called on it.
+     * This is used by multithreading - shared tables and picture pointers
+     * should be freed from the original context only.
+     * - encoding: Set by libavcodec.
+     * - decoding: Set by libavcodec.
+     */
+    int is_copy;
+
+    /**
+     * Which multithreading methods to use.
+     * Use of FF_THREAD_FRAME will increase decoding delay by one frame per thread,
+     * so clients which cannot provide future frames should not use it.
+     *
+     * - encoding: Set by user, otherwise the default is used.
+     * - decoding: Set by user, otherwise the default is used.
+     */
+    int thread_type;
+#define FF_THREAD_FRAME   1 //< Decode more than one frame at once
+#define FF_THREAD_SLICE   2 //< Decode more than one part of a single frame at once
+
+    /**
+     * Which multithreading methods are in use by the codec.
+     * - encoding: Set by libavcodec.
+     * - decoding: Set by libavcodec.
+     */
+    int active_thread_type;
+
+    /**
+     * Set by the client if its custom get_buffer() callback can be called
+     * from another thread, which allows faster multithreaded decoding.
+     * draw_horiz_band() will be called from other threads regardless of this setting.
+     * Ignored if the default get_buffer() is used.
+     * - encoding: Set by user.
+     * - decoding: Set by user.
+     */
+    int thread_safe_callbacks;
+
+    /**
+     * VBV delay coded in the last frame (in periods of a 27 MHz clock).
+     * Used for compliant TS muxing.
+     * - encoding: Set by libavcodec.
+     * - decoding: unused.
+     */
+    uint64_t vbv_delay;
+
+    /**
+     * Type of service that the audio stream conveys.
+     * - encoding: Set by user.
+     * - decoding: Set by libavcodec.
+     */
+    enum AVAudioServiceType audio_service_type;
 } AVCodecContext;
 
 /**
+ * AVProfile.
+ */
+typedef struct AVProfile {
+    int profile;
+    const char *name; ///< short name for the profile
+} AVProfile;
+
+/**
  * AVCodec.
  */
 typedef struct AVCodec {
@@ -2691,8 +2956,31 @@ typedef struct AVCodec {
      */
     const char *long_name;
     const int *supported_samplerates;       ///< array of supported audio samplerates, or NULL if unknown, array is terminated by 0
-    const enum SampleFormat *sample_fmts;   ///< array of supported sample formats, or NULL if unknown, array is terminated by -1
+    const enum AVSampleFormat *sample_fmts; ///< array of supported sample formats, or NULL if unknown, array is terminated by -1
     const int64_t *channel_layouts;         ///< array of support channel layouts, or NULL if unknown. array is terminated by 0
+    uint8_t max_lowres;                     ///< maximum value for lowres supported by the decoder
+    const AVClass *priv_class;              ///< AVClass for the private context
+    const AVProfile *profiles;              ///< array of recognized profiles, or NULL if unknown, array is terminated by {FF_PROFILE_UNKNOWN}
+
+    /**
+     * @defgroup framethreading Frame-level threading support functions.
+     * @{
+     */
+    /**
+     * If defined, called on thread contexts when they are created.
+     * If the codec allocates writable tables in init(), re-allocate them here.
+     * priv_data will be set to a copy of the original.
+     */
+    int (*init_thread_copy)(AVCodecContext *);
+    /**
+     * Copy necessary context variables from a previous thread context to the current one.
+     * If not defined, the next thread will start automatically; otherwise, the codec
+     * must call ff_thread_finish_setup().
+     *
+     * dst and src will (rarely) point to the same context, in which case memcpy should be skipped.
+     */
+    int (*update_thread_context)(AVCodecContext *dst, const AVCodecContext *src);
+    /** @} */
 } AVCodec;
 
 /**
@@ -2794,7 +3082,7 @@ typedef struct AVPicture {
     int linesize[4];       ///< number of bytes per line
 } AVPicture;
 
-#if LIBAVCODEC_VERSION_MAJOR < 53
+#if FF_API_PALETTE_CONTROL
 /**
  * AVPaletteControl
  * This structure defines a method for communicating palette changes
@@ -2909,6 +3197,14 @@ int av_new_packet(AVPacket *pkt, int size);
 void av_shrink_packet(AVPacket *pkt, int size);
 
 /**
+ * Increase packet size, correctly zeroing padding
+ *
+ * @param pkt packet
+ * @param grow_by number of bytes by which to increase the size of the packet
+ */
+int av_grow_packet(AVPacket *pkt, int grow_by);
+
+/**
  * @warning This is a hack - the packet memory allocation stuff is broken. The
  * packet is allocated if it was not really allocated.
  */
@@ -2921,6 +3217,28 @@ int av_dup_packet(AVPacket *pkt);
  */
 void av_free_packet(AVPacket *pkt);
 
+/**
+ * Allocate new information of a packet.
+ *
+ * @param pkt packet
+ * @param type side information type
+ * @param size side information size
+ * @return pointer to fresh allocated data or NULL otherwise
+ */
+uint8_t* av_packet_new_side_data(AVPacket *pkt, enum AVPacketSideDataType type,
+                                 int size);
+
+/**
+ * Get side information from packet.
+ *
+ * @param pkt packet
+ * @param type desired side information type
+ * @param size pointer for side information size to store (optional)
+ * @return pointer to data if present or NULL otherwise
+ */
+uint8_t* av_packet_get_side_data(AVPacket *pkt, enum AVPacketSideDataType type,
+                                 int *size);
+
 /* resample.c */
 
 struct ReSampleContext;
@@ -2928,15 +3246,16 @@ struct AVResampleContext;
 
 typedef struct ReSampleContext ReSampleContext;
 
-#if LIBAVCODEC_VERSION_MAJOR < 53
+#if FF_API_AUDIO_OLD
 /**
  * @deprecated Use av_audio_resample_init() instead.
  */
 attribute_deprecated ReSampleContext *audio_resample_init(int output_channels, int input_channels,
                                                           int output_rate, int input_rate);
 #endif
+
 /**
- *  Initializes audio resampling context
+ *  Initialize audio resampling context.
  *
  * @param output_channels  number of output channels
  * @param input_channels   number of input channels
@@ -2944,26 +3263,33 @@ attribute_deprecated ReSampleContext *audio_resample_init(int output_channels, i
  * @param input_rate       input sample rate
  * @param sample_fmt_out   requested output sample format
  * @param sample_fmt_in    input sample format
- * @param filter_length    length of each FIR filter in the filterbank relative to the cutoff freq
+ * @param filter_length    length of each FIR filter in the filterbank relative to the cutoff frequency
  * @param log2_phase_count log2 of the number of entries in the polyphase filterbank
- * @param linear           If 1 then the used FIR filter will be linearly interpolated
+ * @param linear           if 1 then the used FIR filter will be linearly interpolated
                            between the 2 closest, if 0 the closest will be used
  * @param cutoff           cutoff frequency, 1.0 corresponds to half the output sampling rate
  * @return allocated ReSampleContext, NULL if error occured
  */
 ReSampleContext *av_audio_resample_init(int output_channels, int input_channels,
                                         int output_rate, int input_rate,
-                                        enum SampleFormat sample_fmt_out,
-                                        enum SampleFormat sample_fmt_in,
+                                        enum AVSampleFormat sample_fmt_out,
+                                        enum AVSampleFormat sample_fmt_in,
                                         int filter_length, int log2_phase_count,
                                         int linear, double cutoff);
 
 int audio_resample(ReSampleContext *s, short *output, short *input, int nb_samples);
+
+/**
+ * Free resample context.
+ *
+ * @param s a non-NULL pointer to a resample context previously
+ *          created with av_audio_resample_init()
+ */
 void audio_resample_close(ReSampleContext *s);
 
 
 /**
- * Initializes an audio resampler.
+ * Initialize an audio resampler.
  * Note, if either rate is not an integer then simply scale both rates up so they are.
  * @param filter_length length of each FIR filter in the filterbank relative to the cutoff freq
  * @param log2_phase_count log2 of the number of entries in the polyphase filterbank
@@ -2974,7 +3300,7 @@ void audio_resample_close(ReSampleContext *s);
 struct AVResampleContext *av_resample_init(int out_rate, int in_rate, int filter_length, int log2_phase_count, int linear, double cutoff);
 
 /**
- * resamples.
+ * Resample an array of samples using a previously configured context.
  * @param src an array of unconsumed samples
  * @param consumed the number of samples of src which have been consumed are returned here
  * @param src_size the number of unconsumed samples available
@@ -2986,7 +3312,7 @@ int av_resample(struct AVResampleContext *c, short *dst, short *src, int *consum
 
 
 /**
- * Compensates samplerate/timestamp drift. The compensation is done by changing
+ * Compensate samplerate/timestamp drift. The compensation is done by changing
  * the resampler parameters, so no audible clicks or similar distortions occur
  * @param compensation_distance distance in output samples over which the compensation should be performed
  * @param sample_delta number of output samples which should be output less
@@ -3059,15 +3385,15 @@ void avcodec_set_dimensions(AVCodecContext *s, int width, int height);
 
 #if LIBAVCODEC_VERSION_MAJOR < 53
 /**
- * Returns the pixel format corresponding to the name name.
+ * Return the pixel format corresponding to the name name.
  *
- * If there is no pixel format with name name, then looks for a
+ * If there is no pixel format with name name, then look for a
  * pixel format with the name corresponding to the native endian
  * format of name.
- * For example in a little-endian system, first looks for "gray16",
+ * For example in a little-endian system, first look for "gray16",
  * then for "gray16le".
  *
- * Finally if no pixel format has been found, returns PIX_FMT_NONE.
+ * Finally if no pixel format has been found, return PIX_FMT_NONE.
  *
  * @deprecated Deprecated in favor of av_get_pix_fmt().
  */
@@ -3075,12 +3401,21 @@ attribute_deprecated enum PixelFormat avcodec_get_pix_fmt(const char* name);
 #endif
 
 /**
- * Returns a value representing the fourCC code associated to the
+ * Return a value representing the fourCC code associated to the
  * pixel format pix_fmt, or 0 if no associated fourCC code can be
  * found.
  */
 unsigned int avcodec_pix_fmt_to_codec_tag(enum PixelFormat pix_fmt);
 
+/**
+ * Put a string representing the codec tag codec_tag in buf.
+ *
+ * @param buf_size size in bytes of buf
+ * @return the length of the string that would have been generated if
+ * enough space had been available, excluding the trailing null
+ */
+size_t av_get_codec_tag_string(char *buf, size_t buf_size, unsigned int codec_tag);
+
 #define FF_LOSS_RESOLUTION  0x0001 /**< loss due to resolution change */
 #define FF_LOSS_DEPTH       0x0002 /**< loss due to color depth change */
 #define FF_LOSS_COLORSPACE  0x0004 /**< loss due to color space conversion */
@@ -3089,7 +3424,7 @@ unsigned int avcodec_pix_fmt_to_codec_tag(enum PixelFormat pix_fmt);
 #define FF_LOSS_CHROMA      0x0020 /**< loss of chroma (e.g. RGB to gray conversion) */
 
 /**
- * Computes what kind of losses will occur when converting from one specific
+ * Compute what kind of losses will occur when converting from one specific
  * pixel format to another.
  * When converting from one pixel format to another, information loss may occur.
  * For example, when converting from RGB24 to GRAY, the color information will
@@ -3109,7 +3444,7 @@ int avcodec_get_pix_fmt_loss(enum PixelFormat dst_pix_fmt, enum PixelFormat src_
                              int has_alpha);
 
 /**
- * Finds the best pixel format to convert to given a certain source pixel
+ * Find the best pixel format to convert to given a certain source pixel
  * format.  When converting from one pixel format to another, information loss
  * may occur.  For example, when converting from RGB24 to GRAY, the color
  * information will be lost. Similarly, other losses occur when converting from
@@ -3133,18 +3468,13 @@ int avcodec_get_pix_fmt_loss(enum PixelFormat dst_pix_fmt, enum PixelFormat src_
 enum PixelFormat avcodec_find_best_pix_fmt(int64_t pix_fmt_mask, enum PixelFormat src_pix_fmt,
                               int has_alpha, int *loss_ptr);
 
-
+#if LIBAVCODEC_VERSION_MAJOR < 53
 /**
- * Print in buf the string corresponding to the pixel format with
- * number pix_fmt, or an header if pix_fmt is negative.
- *
- * @param[in] buf the buffer where to write the string
- * @param[in] buf_size the size of buf
- * @param[in] pix_fmt the number of the pixel format to print the corresponding info string, or
- * a negative value to print the corresponding header.
- * Meaningful values for obtaining a pixel format info vary from 0 to PIX_FMT_NB -1.
+ * @deprecated Use av_get_pix_fmt_string() instead.
  */
+attribute_deprecated
 void avcodec_pix_fmt_string (char *buf, int buf_size, enum PixelFormat pix_fmt);
+#endif
 
 #define FF_ALPHA_TRANSP       0x0001 /* image has some totally transparent pixels */
 #define FF_ALPHA_SEMI_TRANSP  0x0002 /* image has some transparent pixels */
@@ -3171,22 +3501,22 @@ int avpicture_deinterlace(AVPicture *dst, const AVPicture *src,
 AVCodec *av_codec_next(AVCodec *c);
 
 /**
- * Returns the LIBAVCODEC_VERSION_INT constant.
+ * Return the LIBAVCODEC_VERSION_INT constant.
  */
 unsigned avcodec_version(void);
 
 /**
- * Returns the libavcodec build-time configuration.
+ * Return the libavcodec build-time configuration.
  */
 const char *avcodec_configuration(void);
 
 /**
- * Returns the libavcodec license.
+ * Return the libavcodec license.
  */
 const char *avcodec_license(void);
 
 /**
- * Initializes libavcodec.
+ * Initialize libavcodec.
  *
  * @warning This function must be called before any other libavcodec
  * function.
@@ -3208,7 +3538,7 @@ attribute_deprecated void register_avcodec(AVCodec *codec);
 void avcodec_register(AVCodec *codec);
 
 /**
- * Finds a registered encoder with a matching codec ID.
+ * Find a registered encoder with a matching codec ID.
  *
  * @param id CodecID of the requested encoder
  * @return An encoder if one was found, NULL otherwise.
@@ -3216,7 +3546,7 @@ void avcodec_register(AVCodec *codec);
 AVCodec *avcodec_find_encoder(enum CodecID id);
 
 /**
- * Finds a registered encoder with the specified name.
+ * Find a registered encoder with the specified name.
  *
  * @param name name of the requested encoder
  * @return An encoder if one was found, NULL otherwise.
@@ -3224,7 +3554,7 @@ AVCodec *avcodec_find_encoder(enum CodecID id);
 AVCodec *avcodec_find_encoder_by_name(const char *name);
 
 /**
- * Finds a registered decoder with a matching codec ID.
+ * Find a registered decoder with a matching codec ID.
  *
  * @param id CodecID of the requested decoder
  * @return A decoder if one was found, NULL otherwise.
@@ -3232,7 +3562,7 @@ AVCodec *avcodec_find_encoder_by_name(const char *name);
 AVCodec *avcodec_find_decoder(enum CodecID id);
 
 /**
- * Finds a registered decoder with the specified name.
+ * Find a registered decoder with the specified name.
  *
  * @param name name of the requested decoder
  * @return A decoder if one was found, NULL otherwise.
@@ -3241,7 +3571,16 @@ AVCodec *avcodec_find_decoder_by_name(const char *name);
 void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode);
 
 /**
- * Sets the fields of the given AVCodecContext to default values.
+ * Return a name for the specified profile, if available.
+ *
+ * @param codec the codec that is searched for the given profile
+ * @param profile the profile value for which a name is requested
+ * @return A name for the profile if found, NULL otherwise.
+ */
+const char *av_get_profile_name(const AVCodec *codec, int profile);
+
+/**
+ * Set the fields of the given AVCodecContext to default values.
  *
  * @param s The AVCodecContext of which the fields should be set to default values.
  */
@@ -3251,8 +3590,12 @@ void avcodec_get_context_defaults(AVCodecContext *s);
  *  we WILL change its arguments and name a few times! */
 void avcodec_get_context_defaults2(AVCodecContext *s, enum AVMediaType);
 
+/** THIS FUNCTION IS NOT YET PART OF THE PUBLIC API!
+ *  we WILL change its arguments and name a few times! */
+int avcodec_get_context_defaults3(AVCodecContext *s, AVCodec *codec);
+
 /**
- * Allocates an AVCodecContext and sets its fields to default values.  The
+ * Allocate an AVCodecContext and set its fields to default values.  The
  * resulting struct can be deallocated by simply calling av_free().
  *
  * @return An AVCodecContext filled with default values or NULL on failure.
@@ -3264,6 +3607,10 @@ AVCodecContext *avcodec_alloc_context(void);
  *  we WILL change its arguments and name a few times! */
 AVCodecContext *avcodec_alloc_context2(enum AVMediaType);
 
+/** THIS FUNCTION IS NOT YET PART OF THE PUBLIC API!
+ *  we WILL change its arguments and name a few times! */
+AVCodecContext *avcodec_alloc_context3(AVCodec *codec);
+
 /**
  * Copy the settings of the source AVCodecContext into the destination
  * AVCodecContext. The resulting destination codec context will be
@@ -3278,14 +3625,14 @@ AVCodecContext *avcodec_alloc_context2(enum AVMediaType);
 int avcodec_copy_context(AVCodecContext *dest, const AVCodecContext *src);
 
 /**
- * Sets the fields of the given AVFrame to default values.
+ * Set the fields of the given AVFrame to default values.
  *
  * @param pic The AVFrame of which the fields should be set to default values.
  */
 void avcodec_get_frame_defaults(AVFrame *pic);
 
 /**
- * Allocates an AVFrame and sets its fields to default values.  The resulting
+ * Allocate an AVFrame and set its fields to default values.  The resulting
  * struct can be deallocated by simply calling av_free().
  *
  * @return An AVFrame filled with default values or NULL on failure.
@@ -3298,7 +3645,7 @@ void avcodec_default_release_buffer(AVCodecContext *s, AVFrame *pic);
 int avcodec_default_reget_buffer(AVCodecContext *s, AVFrame *pic);
 
 /**
- * Returns the amount of padding in pixels which the get_buffer callback must
+ * Return the amount of padding in pixels which the get_buffer callback must
  * provide around the edge of the image for codecs which do not have the
  * CODEC_FLAG_EMU_EDGE flag.
  *
@@ -3306,7 +3653,7 @@ int avcodec_default_reget_buffer(AVCodecContext *s, AVFrame *pic);
  */
 unsigned avcodec_get_edge_width(void);
 /**
- * Modifies width and height values so that they will result in a memory
+ * Modify width and height values so that they will result in a memory
  * buffer that is acceptable for the codec if you do not use any horizontal
  * padding.
  *
@@ -3316,7 +3663,7 @@ unsigned avcodec_get_edge_width(void);
  */
 void avcodec_align_dimensions(AVCodecContext *s, int *width, int *height);
 /**
- * Modifies width and height values so that they will result in a memory
+ * Modify width and height values so that they will result in a memory
  * buffer that is acceptable for the codec if you also ensure that all
  * line sizes are a multiple of the respective linesize_align[i].
  *
@@ -3327,25 +3674,30 @@ void avcodec_align_dimensions(AVCodecContext *s, int *width, int *height);
 void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height,
                                int linesize_align[4]);
 
+#if LIBAVCODEC_VERSION_MAJOR < 53
 /**
- * Checks if the given dimension of a picture is valid, meaning that all
- * bytes of the picture can be addressed with a signed int.
- *
- * @param[in] w Width of the picture.
- * @param[in] h Height of the picture.
- * @return Zero if valid, a negative value if invalid.
+ * @deprecated Deprecated in favor of av_check_image_size().
  */
+attribute_deprecated
 int avcodec_check_dimensions(void *av_log_ctx, unsigned int w, unsigned int h);
+#endif
+
 enum PixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum PixelFormat * fmt);
 
+#if LIBAVCODEC_VERSION_MAJOR < 53
+/**
+ * @deprecated Set s->thread_count before calling avcodec_open() instead of calling this.
+ */
+attribute_deprecated
 int avcodec_thread_init(AVCodecContext *s, int thread_count);
 void avcodec_thread_free(AVCodecContext *s);
+#endif
 int avcodec_default_execute(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2),void *arg, int *ret, int count, int size);
 int avcodec_default_execute2(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2, int, int),void *arg, int *ret, int count);
 //FIXME func typedef
 
 /**
- * Initializes the AVCodecContext to use the given AVCodec. Prior to using this
+ * Initialize the AVCodecContext to use the given AVCodec. Prior to using this
  * function the context has to be allocated.
  *
  * The functions avcodec_find_decoder_by_name(), avcodec_find_encoder_by_name(),
@@ -3373,9 +3725,9 @@ int avcodec_default_execute2(AVCodecContext *c, int (*func)(AVCodecContext *c2,
  */
 int avcodec_open(AVCodecContext *avctx, AVCodec *codec);
 
-#if LIBAVCODEC_VERSION_MAJOR < 53
+#if FF_API_AUDIO_OLD
 /**
- * Decodes an audio frame from buf into samples.
+ * Decode an audio frame from buf into samples.
  * Wrapper function which calls avcodec_decode_audio3.
  *
  * @deprecated Use avcodec_decode_audio3 instead.
@@ -3393,7 +3745,7 @@ attribute_deprecated int avcodec_decode_audio2(AVCodecContext *avctx, int16_t *s
 #endif
 
 /**
- * Decodes the audio frame of size avpkt->size from avpkt->data into samples.
+ * Decode the audio frame of size avpkt->size from avpkt->data into samples.
  * Some decoders may support multiple frames in a single AVPacket, such
  * decoders would then just decode the first frame. In this case,
  * avcodec_decode_audio3 has to be called again with an AVPacket that contains
@@ -3435,9 +3787,9 @@ int avcodec_decode_audio3(AVCodecContext *avctx, int16_t *samples,
                          int *frame_size_ptr,
                          AVPacket *avpkt);
 
-#if LIBAVCODEC_VERSION_MAJOR < 53
+#if FF_API_VIDEO_OLD
 /**
- * Decodes a video frame from buf into picture.
+ * Decode a video frame from buf into picture.
  * Wrapper function which calls avcodec_decode_video2.
  *
  * @deprecated Use avcodec_decode_video2 instead.
@@ -3455,7 +3807,7 @@ attribute_deprecated int avcodec_decode_video(AVCodecContext *avctx, AVFrame *pi
 #endif
 
 /**
- * Decodes the video frame of size avpkt->size from avpkt->data into picture.
+ * Decode the video frame of size avpkt->size from avpkt->data into picture.
  * Some decoders may support multiple frames in a single AVPacket, such
  * decoders would then just decode the first frame.
  *
@@ -3480,6 +3832,11 @@ attribute_deprecated int avcodec_decode_video(AVCodecContext *avctx, AVFrame *pi
  * @param[out] picture The AVFrame in which the decoded video frame will be stored.
  *             Use avcodec_alloc_frame to get an AVFrame, the codec will
  *             allocate memory for the actual bitmap.
+ *             with default get/release_buffer(), the decoder frees/reuses the bitmap as it sees fit.
+ *             with overridden get/release_buffer() (needs CODEC_CAP_DR1) the user decides into what buffer the decoder
+ *                   decodes and the decoder tells the user once it does not need the data anymore,
+ *                   the user app can at this point free/reuse/keep the memory as it sees fit.
+ *
  * @param[in] avpkt The input AVpacket containing the input buffer.
  *            You can create such packet with av_init_packet() and by then setting
  *            data and size, some decoders might in addition need other fields like
@@ -3493,7 +3850,7 @@ int avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
                          int *got_picture_ptr,
                          AVPacket *avpkt);
 
-#if LIBAVCODEC_VERSION_MAJOR < 53
+#if FF_API_SUBTITLE_OLD
 /* Decode a subtitle message. Return -1 if error, otherwise return the
  * number of bytes used. If no subtitle could be decompressed,
  * got_sub_ptr is zero. Otherwise, the subtitle is stored in *sub. */
@@ -3503,25 +3860,38 @@ attribute_deprecated int avcodec_decode_subtitle(AVCodecContext *avctx, AVSubtit
 #endif
 
 /**
- * Decodes a subtitle message.
- * Returns a negative value on error, otherwise returns the number of bytes used.
+ * Decode a subtitle message.
+ * Return a negative value on error, otherwise return the number of bytes used.
  * If no subtitle could be decompressed, got_sub_ptr is zero.
  * Otherwise, the subtitle is stored in *sub.
+ * Note that CODEC_CAP_DR1 is not available for subtitle codecs. This is for
+ * simplicity, because the performance difference is expect to be negligible
+ * and reusing a get_buffer written for video codecs would probably perform badly
+ * due to a potentially very different allocation pattern.
  *
  * @param avctx the codec context
- * @param[out] sub The AVSubtitle in which the decoded subtitle will be stored.
+ * @param[out] sub The AVSubtitle in which the decoded subtitle will be stored, must be
+                   freed with avsubtitle_free if *got_sub_ptr is set.
  * @param[in,out] got_sub_ptr Zero if no subtitle could be decompressed, otherwise, it is nonzero.
  * @param[in] avpkt The input AVPacket containing the input buffer.
  */
 int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
                             int *got_sub_ptr,
                             AVPacket *avpkt);
+
+/**
+ * Frees all allocated data in the given subtitle struct.
+ *
+ * @param sub AVSubtitle to free.
+ */
+void avsubtitle_free(AVSubtitle *sub);
+
 int avcodec_parse_frame(AVCodecContext *avctx, uint8_t **pdata,
                         int *data_size_ptr,
                         uint8_t *buf, int buf_size);
 
 /**
- * Encodes an audio frame from samples into buf.
+ * Encode an audio frame from samples into buf.
  *
  * @note The output buffer should be at least FF_MIN_BUFFER_SIZE bytes large.
  * However, for PCM audio the user will know how much space is needed
@@ -3543,7 +3913,7 @@ int avcodec_encode_audio(AVCodecContext *avctx, uint8_t *buf, int buf_size,
                          const short *samples);
 
 /**
- * Encodes a video frame from pict into buf.
+ * Encode a video frame from pict into buf.
  * The input picture should be
  * stored using a specific format, namely avctx.pix_fmt.
  *
@@ -3583,7 +3953,7 @@ void avcodec_default_free_buffers(AVCodecContext *s);
 /* misc useful functions */
 
 /**
- * Returns a single letter to describe the given picture type pict_type.
+ * Return a single letter to describe the given picture type pict_type.
  *
  * @param[in] pict_type the picture type
  * @return A single character representing the picture type.
@@ -3591,20 +3961,20 @@ void avcodec_default_free_buffers(AVCodecContext *s);
 char av_get_pict_type_char(int pict_type);
 
 /**
- * Returns codec bits per sample.
+ * Return codec bits per sample.
  *
  * @param[in] codec_id the codec
  * @return Number of bits per sample or zero if unknown for the given codec.
  */
 int av_get_bits_per_sample(enum CodecID codec_id);
 
+#if FF_API_OLD_SAMPLE_FMT
 /**
- * Returns sample format bits per sample.
- *
- * @param[in] sample_fmt the sample format
- * @return Number of bits per sample or zero if unknown for the given sample format.
+ * @deprecated Use av_get_bits_per_sample_fmt() instead.
  */
-int av_get_bits_per_sample_format(enum SampleFormat sample_fmt);
+attribute_deprecated
+int av_get_bits_per_sample_format(enum AVSampleFormat sample_fmt);
+#endif
 
 /* frame parsing */
 typedef struct AVCodecParserContext {
@@ -3642,6 +4012,9 @@ typedef struct AVCodecParserContext {
 
     int flags;
 #define PARSER_FLAG_COMPLETE_FRAMES           0x0001
+#define PARSER_FLAG_ONCE                      0x0002
+/// Set if the parser has a valid file offset
+#define PARSER_FLAG_FETCHED_OFFSET            0x0004
 
     int64_t offset;      ///< byte offset from starting packet start
     int64_t cur_frame_end[AV_PARSER_PTS_NB];
@@ -3662,6 +4035,8 @@ typedef struct AVCodecParserContext {
      * the very first frame or from this keyframe.
      * Is AV_NOPTS_VALUE if unknown.
      * This field is not the display duration of the current frame.
+     * This field has no meaning if the packet does not have AV_PKT_FLAG_KEY
+     * set.
      *
      * The purpose of this field is to allow seeking in streams that have no
      * keyframes in the conventional sense. It corresponds to the
@@ -3831,15 +4206,14 @@ AVBitStreamFilter *av_bitstream_filter_next(AVBitStreamFilter *f);
 /* memory */
 
 /**
- * Reallocates the given block if it is not large enough, otherwise it
- * does nothing.
+ * Reallocate the given block if it is not large enough, otherwise do nothing.
  *
  * @see av_realloc
  */
-void *av_fast_realloc(void *ptr, unsigned int *size, unsigned int min_size);
+void *av_fast_realloc(void *ptr, unsigned int *size, FF_INTERNALC_MEM_TYPE min_size);
 
 /**
- * Allocates a buffer, reusing the given one if large enough.
+ * Allocate a buffer, reusing the given one if large enough.
  *
  * Contrary to av_fast_realloc the current buffer contents might not be
  * preserved and on error the old buffer is freed, thus no special
@@ -3850,10 +4224,20 @@ void *av_fast_realloc(void *ptr, unsigned int *size, unsigned int min_size);
  * @param min_size minimum size of *ptr buffer after returning, *ptr will be NULL and
  *                 *size 0 if an error occurred.
  */
-void av_fast_malloc(void *ptr, unsigned int *size, unsigned int min_size);
+void av_fast_malloc(void *ptr, unsigned int *size, FF_INTERNALC_MEM_TYPE min_size);
+
+#if LIBAVCODEC_VERSION_MAJOR < 53
+/**
+ * @deprecated Deprecated in favor of av_image_copy().
+ */
+attribute_deprecated
+void av_picture_data_copy(uint8_t *dst_data[4], int dst_linesize[4],
+                          uint8_t *src_data[4], int src_linesize[4],
+                          enum PixelFormat pix_fmt, int width, int height);
+#endif
 
 /**
- * Copy image 'src' to 'dst'.
+ * Copy image src to dst. Wraps av_picture_data_copy() above.
  */
 void av_picture_copy(AVPicture *dst, const AVPicture *src,
                      enum PixelFormat pix_fmt, int width, int height);
@@ -3871,7 +4255,7 @@ int av_picture_pad(AVPicture *dst, const AVPicture *src, int height, int width,
             int padtop, int padbottom, int padleft, int padright, int *color);
 
 /**
- * Encodes extradata length to a buffer. Used by xiph codecs.
+ * Encode extradata length to a buffer. Used by xiph codecs.
  *
  * @param s buffer to write to; must be at least (v/255+1) bytes long
  * @param v size of extradata in bytes
@@ -3879,33 +4263,25 @@ int av_picture_pad(AVPicture *dst, const AVPicture *src, int height, int width,
  */
 unsigned int av_xiphlacing(unsigned char *s, unsigned int v);
 
+#if LIBAVCODEC_VERSION_MAJOR < 53
 /**
- * Parses str and put in width_ptr and height_ptr the detected values.
+ * Parse str and put in width_ptr and height_ptr the detected values.
  *
- * @return 0 in case of a successful parsing, a negative value otherwise
- * @param[in] str the string to parse: it has to be a string in the format
- * <width>x<height> or a valid video frame size abbreviation.
- * @param[in,out] width_ptr pointer to the variable which will contain the detected
- * frame width value
- * @param[in,out] height_ptr pointer to the variable which will contain the detected
- * frame height value
+ * @deprecated Deprecated in favor of av_parse_video_size().
  */
-int av_parse_video_frame_size(int *width_ptr, int *height_ptr, const char *str);
+attribute_deprecated int av_parse_video_frame_size(int *width_ptr, int *height_ptr, const char *str);
 
 /**
- * Parses str and put in frame_rate the detected values.
+ * Parse str and store the detected values in *frame_rate.
  *
- * @return 0 in case of a successful parsing, a negative value otherwise
- * @param[in] str the string to parse: it has to be a string in the format
- * <frame_rate_num>/<frame_rate_den>, a float number or a valid video rate abbreviation
- * @param[in,out] frame_rate pointer to the AVRational which will contain the detected
- * frame rate
+ * @deprecated Deprecated in favor of av_parse_video_rate().
  */
-int av_parse_video_frame_rate(AVRational *frame_rate, const char *str);
+attribute_deprecated int av_parse_video_frame_rate(AVRational *frame_rate, const char *str);
+#endif
 
 /**
  * Logs a generic warning message about a missing feature. This function is
- * intended to be used internally by FFmpeg (libavcodec, libavformat, etc.)
+ * intended to be used internally by Libav (libavcodec, libavformat, etc.)
  * only, and would normally not be used by applications.
  * @param[in] avc a pointer to an arbitrary struct of which the first field is
  * a pointer to an AVClass struct
@@ -3918,8 +4294,8 @@ int av_parse_video_frame_rate(AVRational *frame_rate, const char *str);
 void av_log_missing_feature(void *avc, const char *feature, int want_sample);
 
 /**
- * Logs a generic warning message asking for a sample. This function is
- * intended to be used internally by FFmpeg (libavcodec, libavformat, etc.)
+ * Log a generic warning message asking for a sample. This function is
+ * intended to be used internally by Libav (libavcodec, libavformat, etc.)
  * only, and would normally not be used by applications.
  * @param[in] avc a pointer to an arbitrary struct of which the first field is
  * a pointer to an AVClass struct
@@ -3928,7 +4304,7 @@ void av_log_missing_feature(void *avc, const char *feature, int want_sample);
 void av_log_ask_for_sample(void *avc, const char *msg);
 
 /**
- * Registers the hardware accelerator hwaccel.
+ * Register the hardware accelerator hwaccel.
  */
 void av_register_hwaccel(AVHWAccel *hwaccel);
 
@@ -3956,7 +4332,7 @@ enum AVLockOp {
  * lockmgr should store/get a pointer to a user allocated mutex. It's
  * NULL upon AV_LOCK_CREATE and != NULL for all other ops.
  *
- * @param cb User defined callback. Note: FFmpeg may invoke calls to this
+ * @param cb User defined callback. Note: Libav may invoke calls to this
  *           callback during the call to av_lockmgr_register().
  *           Thus, the application must be prepared to handle that.
  *           If cb is set to NULL the lockmgr will be unregistered.
diff --git a/libavcodec/avfft.c b/libavcodec/avfft.c
index 25fc4e0..9ed06fb 100644
--- a/libavcodec/avfft.c
+++ b/libavcodec/avfft.c
@@ -1,24 +1,26 @@
 /*
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "libavutil/mem.h"
 #include "avfft.h"
 #include "fft.h"
+#include "rdft.h"
+#include "dct.h"
 
 /* FFT */
 
@@ -26,8 +28,8 @@ FFTContext *av_fft_init(int nbits, int inverse)
 {
     FFTContext *s = av_malloc(sizeof(*s));
 
-    if (s)
-        ff_fft_init(s, nbits, inverse);
+    if (s && ff_fft_init(s, nbits, inverse))
+        av_freep(&s);
 
     return s;
 }
@@ -56,8 +58,8 @@ FFTContext *av_mdct_init(int nbits, int inverse, double scale)
 {
     FFTContext *s = av_malloc(sizeof(*s));
 
-    if (s)
-        ff_mdct_init(s, nbits, inverse, scale);
+    if (s && ff_mdct_init(s, nbits, inverse, scale))
+        av_freep(&s);
 
     return s;
 }
@@ -93,15 +95,15 @@ RDFTContext *av_rdft_init(int nbits, enum RDFTransformType trans)
 {
     RDFTContext *s = av_malloc(sizeof(*s));
 
-    if (s)
-        ff_rdft_init(s, nbits, trans);
+    if (s && ff_rdft_init(s, nbits, trans))
+        av_freep(&s);
 
     return s;
 }
 
 void av_rdft_calc(RDFTContext *s, FFTSample *data)
 {
-    ff_rdft_calc(s, data);
+    s->rdft_calc(s, data);
 }
 
 void av_rdft_end(RDFTContext *s)
@@ -120,15 +122,15 @@ DCTContext *av_dct_init(int nbits, enum DCTTransformType inverse)
 {
     DCTContext *s = av_malloc(sizeof(*s));
 
-    if (s)
-        ff_dct_init(s, nbits, inverse);
+    if (s && ff_dct_init(s, nbits, inverse))
+        av_freep(&s);
 
     return s;
 }
 
 void av_dct_calc(DCTContext *s, FFTSample *data)
 {
-    ff_dct_calc(s, data);
+    s->dct_calc(s, data);
 }
 
 void av_dct_end(DCTContext *s)
diff --git a/libavcodec/avfft.h b/libavcodec/avfft.h
index 623f0a3..91fe2f4 100644
--- a/libavcodec/avfft.h
+++ b/libavcodec/avfft.h
@@ -1,18 +1,18 @@
 /*
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -85,7 +85,7 @@ enum DCTTransformType {
 };
 
 /**
- * Sets up DCT.
+ * Set up DCT.
  * @param nbits           size of the input array:
  *                        (1 << nbits)     for DCT-II, DCT-III and DST-I
  *                        (1 << nbits) + 1 for DCT-I
diff --git a/libavcodec/avpacket.c b/libavcodec/avpacket.c
index c51260f..e0e4df4 100644
--- a/libavcodec/avpacket.c
+++ b/libavcodec/avpacket.c
@@ -2,35 +2,45 @@
  * AVPacket functions for libavcodec
  * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "avcodec.h"
+#include "libavutil/avassert.h"
 
 
 void av_destruct_packet_nofree(AVPacket *pkt)
 {
     pkt->data = NULL; pkt->size = 0;
+    pkt->side_data       = NULL;
+    pkt->side_data_elems = 0;
 }
 
 void av_destruct_packet(AVPacket *pkt)
 {
+    int i;
+
     av_free(pkt->data);
     pkt->data = NULL; pkt->size = 0;
+
+    for (i = 0; i < pkt->side_data_elems; i++)
+        av_free(pkt->side_data[i].data);
+    av_freep(&pkt->side_data);
+    pkt->side_data_elems = 0;
 }
 
 void av_init_packet(AVPacket *pkt)
@@ -43,6 +53,8 @@ void av_init_packet(AVPacket *pkt)
     pkt->flags = 0;
     pkt->stream_index = 0;
     pkt->destruct= NULL;
+    pkt->side_data       = NULL;
+    pkt->side_data_elems = 0;
 }
 
 int av_new_packet(AVPacket *pkt, int size)
@@ -71,23 +83,69 @@ void av_shrink_packet(AVPacket *pkt, int size)
     memset(pkt->data + size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
 }
 
+int av_grow_packet(AVPacket *pkt, int grow_by)
+{
+    void *new_ptr;
+    av_assert0((unsigned)pkt->size <= INT_MAX - FF_INPUT_BUFFER_PADDING_SIZE);
+    if (!pkt->size)
+        return av_new_packet(pkt, grow_by);
+    if ((unsigned)grow_by > INT_MAX - (pkt->size + FF_INPUT_BUFFER_PADDING_SIZE))
+        return -1;
+    new_ptr = av_realloc(pkt->data, pkt->size + grow_by + FF_INPUT_BUFFER_PADDING_SIZE);
+    if (!new_ptr)
+        return AVERROR(ENOMEM);
+    pkt->data = new_ptr;
+    pkt->size += grow_by;
+    memset(pkt->data + pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
+    return 0;
+}
+
+#define DUP_DATA(dst, src, size, padding) \
+    do { \
+        void *data; \
+        if (padding) { \
+            if ((unsigned)(size) > (unsigned)(size) + FF_INPUT_BUFFER_PADDING_SIZE) \
+                goto failed_alloc; \
+            data = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE); \
+        } else { \
+            data = av_malloc(size); \
+        } \
+        if (!data) \
+            goto failed_alloc; \
+        memcpy(data, src, size); \
+        if (padding) \
+            memset((uint8_t*)data + size, 0, FF_INPUT_BUFFER_PADDING_SIZE); \
+        dst = data; \
+    } while(0)
+
 int av_dup_packet(AVPacket *pkt)
 {
+    AVPacket tmp_pkt;
+
     if (((pkt->destruct == av_destruct_packet_nofree) || (pkt->destruct == NULL)) && pkt->data) {
-        uint8_t *data;
-        /* We duplicate the packet and don't forget to add the padding again. */
-        if((unsigned)pkt->size > (unsigned)pkt->size + FF_INPUT_BUFFER_PADDING_SIZE)
-            return AVERROR(ENOMEM);
-        data = av_malloc(pkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
-        if (!data) {
-            return AVERROR(ENOMEM);
-        }
-        memcpy(data, pkt->data, pkt->size);
-        memset(data + pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
-        pkt->data = data;
+        tmp_pkt = *pkt;
+
+        pkt->data      = NULL;
+        pkt->side_data = NULL;
+        DUP_DATA(pkt->data, tmp_pkt.data, pkt->size, 1);
         pkt->destruct = av_destruct_packet;
+
+        if (pkt->side_data_elems) {
+            int i;
+
+            DUP_DATA(pkt->side_data, tmp_pkt.side_data,
+                     pkt->side_data_elems * sizeof(*pkt->side_data), 0);
+            memset(pkt->side_data, 0, pkt->side_data_elems * sizeof(*pkt->side_data));
+            for (i = 0; i < pkt->side_data_elems; i++) {
+                DUP_DATA(pkt->side_data[i].data, tmp_pkt.side_data[i].data,
+                         pkt->side_data[i].size, 1);
+            }
+        }
     }
     return 0;
+failed_alloc:
+    av_destruct_packet(pkt);
+    return AVERROR(ENOMEM);
 }
 
 void av_free_packet(AVPacket *pkt)
@@ -95,5 +153,46 @@ void av_free_packet(AVPacket *pkt)
     if (pkt) {
         if (pkt->destruct) pkt->destruct(pkt);
         pkt->data = NULL; pkt->size = 0;
+        pkt->side_data       = NULL;
+        pkt->side_data_elems = 0;
+    }
+}
+
+uint8_t* av_packet_new_side_data(AVPacket *pkt, enum AVPacketSideDataType type,
+                                 int size)
+{
+    int elems = pkt->side_data_elems;
+
+    if ((unsigned)elems + 1 > INT_MAX / sizeof(*pkt->side_data))
+        return NULL;
+    if ((unsigned)size > INT_MAX - FF_INPUT_BUFFER_PADDING_SIZE)
+        return NULL;
+
+    pkt->side_data = av_realloc(pkt->side_data, (elems + 1) * sizeof(*pkt->side_data));
+    if (!pkt->side_data)
+        return NULL;
+
+    pkt->side_data[elems].data = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
+    if (!pkt->side_data[elems].data)
+        return NULL;
+    pkt->side_data[elems].size = size;
+    pkt->side_data[elems].type = type;
+    pkt->side_data_elems++;
+
+    return pkt->side_data[elems].data;
+}
+
+uint8_t* av_packet_get_side_data(AVPacket *pkt, enum AVPacketSideDataType type,
+                                 int *size)
+{
+    int i;
+
+    for (i = 0; i < pkt->side_data_elems; i++) {
+        if (pkt->side_data[i].type == type) {
+            if (size)
+                *size = pkt->side_data[i].size;
+            return pkt->side_data[i].data;
+        }
     }
+    return NULL;
 }
diff --git a/libavcodec/avr32/mathops.h b/libavcodec/avr32/mathops.h
index 85f42b5..528b7ad 100644
--- a/libavcodec/avr32/mathops.h
+++ b/libavcodec/avr32/mathops.h
@@ -2,20 +2,20 @@
  * Simple math operations
  * Copyright (c) 2009 Mans Rullgard <mans at mansr.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/avs.c b/libavcodec/avs.c
index f65a25a..5520135 100644
--- a/libavcodec/avs.c
+++ b/libavcodec/avs.c
@@ -2,20 +2,20 @@
  * AVS video decoder.
  * Copyright (c) 2006  Aurelien Jacobs <aurel at gnuage.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -150,7 +150,7 @@ static av_cold int avs_decode_init(AVCodecContext * avctx)
     return 0;
 }
 
-AVCodec avs_decoder = {
+AVCodec ff_avs_decoder = {
     "avs",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_AVS,
diff --git a/libavcodec/beosthread.c b/libavcodec/beosthread.c
deleted file mode 100644
index 44fe492..0000000
--- a/libavcodec/beosthread.c
+++ /dev/null
@@ -1,183 +0,0 @@
-/*
- * Copyright (c) 2004 François Revol <revol at free.fr>
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-//#define DEBUG
-
-#include "avcodec.h"
-
-#include <OS.h>
-
-typedef struct ThreadContext{
-    AVCodecContext *avctx;
-    thread_id thread;
-    sem_id work_sem;
-    sem_id done_sem;
-    int (*func)(AVCodecContext *c, void *arg);
-    void *arg;
-    int ret;
-}ThreadContext;
-
-// it's odd Be never patented that :D
-struct benaphore {
-        vint32 atom;
-        sem_id sem;
-};
-static inline int lock_ben(struct benaphore *ben)
-{
-        if (atomic_add(&ben->atom, 1) > 0)
-                return acquire_sem(ben->sem);
-        return B_OK;
-}
-static inline int unlock_ben(struct benaphore *ben)
-{
-        if (atomic_add(&ben->atom, -1) > 1)
-                return release_sem(ben->sem);
-        return B_OK;
-}
-
-static struct benaphore av_thread_lib_ben;
-
-static int32 ff_thread_func(void *v){
-    ThreadContext *c= v;
-
-    for(;;){
-//printf("thread_func %X enter wait\n", (int)v); fflush(stdout);
-        acquire_sem(c->work_sem);
-//printf("thread_func %X after wait (func=%X)\n", (int)v, (int)c->func); fflush(stdout);
-        if(c->func)
-            c->ret= c->func(c->avctx, c->arg);
-        else
-            return 0;
-//printf("thread_func %X signal complete\n", (int)v); fflush(stdout);
-        release_sem(c->done_sem);
-    }
-
-    return B_OK;
-}
-
-/**
- * Free what has been allocated by avcodec_thread_init().
- * Must be called after decoding has finished, especially do not call while avcodec_thread_execute() is running.
- */
-void avcodec_thread_free(AVCodecContext *s){
-    ThreadContext *c= s->thread_opaque;
-    int i;
-    int32 ret;
-
-    for(i=0; i<s->thread_count; i++){
-
-        c[i].func= NULL;
-        release_sem(c[i].work_sem);
-        wait_for_thread(c[i].thread, &ret);
-        if(c[i].work_sem > B_OK) delete_sem(c[i].work_sem);
-        if(c[i].done_sem > B_OK) delete_sem(c[i].done_sem);
-    }
-
-    av_freep(&s->thread_opaque);
-}
-
-static int avcodec_thread_execute(AVCodecContext *s, int (*func)(AVCodecContext *c2, void *arg2),void *arg, int *ret, int count, int size){
-    ThreadContext *c= s->thread_opaque;
-    int i;
-
-    assert(s == c->avctx);
-    assert(count <= s->thread_count);
-
-    /* note, we can be certain that this is not called with the same AVCodecContext by different threads at the same time */
-
-    for(i=0; i<count; i++){
-        c[i].arg= (char*)arg + i*size;
-        c[i].func= func;
-        c[i].ret= 12345;
-
-        release_sem(c[i].work_sem);
-    }
-    for(i=0; i<count; i++){
-        acquire_sem(c[i].done_sem);
-
-        c[i].func= NULL;
-        if(ret) ret[i]= c[i].ret;
-    }
-    return 0;
-}
-
-int avcodec_thread_init(AVCodecContext *s, int thread_count){
-    int i;
-    ThreadContext *c;
-
-    s->thread_count= thread_count;
-
-    if (thread_count <= 1)
-        return 0;
-
-    assert(!s->thread_opaque);
-    c= av_mallocz(sizeof(ThreadContext)*thread_count);
-    s->thread_opaque= c;
-
-    for(i=0; i<thread_count; i++){
-//printf("init semaphors %d\n", i); fflush(stdout);
-        c[i].avctx= s;
-
-        if((c[i].work_sem = create_sem(0, "ff work sem")) < B_OK)
-            goto fail;
-        if((c[i].done_sem = create_sem(0, "ff done sem")) < B_OK)
-            goto fail;
-
-//printf("create thread %d\n", i); fflush(stdout);
-        c[i].thread = spawn_thread(ff_thread_func, "libavcodec thread", B_LOW_PRIORITY, &c[i] );
-        if( c[i].thread < B_OK ) goto fail;
-        resume_thread(c[i].thread );
-    }
-//printf("init done\n"); fflush(stdout);
-
-    s->execute= avcodec_thread_execute;
-
-    return 0;
-fail:
-    avcodec_thread_free(s);
-    return -1;
-}
-
-/* provide a mean to serialize calls to avcodec_*() for thread safety. */
-
-int avcodec_thread_lock_lib(void)
-{
-        return lock_ben(&av_thread_lib_ben);
-}
-
-int avcodec_thread_unlock_lib(void)
-{
-        return unlock_ben(&av_thread_lib_ben);
-}
-
-/* our versions of _init and _fini (which are called by those actually from crt.o) */
-
-void initialize_after(void)
-{
-        av_thread_lib_ben.atom = 0;
-        av_thread_lib_ben.sem = create_sem(0, "libavcodec benaphore");
-}
-
-void uninitialize_before(void)
-{
-        delete_sem(av_thread_lib_ben.sem);
-}
-
-
-
diff --git a/libavcodec/bethsoftvideo.c b/libavcodec/bethsoftvideo.c
index 0ba39e6..d294bbf 100644
--- a/libavcodec/bethsoftvideo.c
+++ b/libavcodec/bethsoftvideo.c
@@ -2,20 +2,20 @@
  * Bethesda VID video decoder
  * Copyright (C) 2007 Nicholas Tung
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -130,7 +130,7 @@ static av_cold int bethsoftvid_decode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec bethsoftvid_decoder = {
+AVCodec ff_bethsoftvid_decoder = {
     .name = "bethsoftvid",
     .type = AVMEDIA_TYPE_VIDEO,
     .id = CODEC_ID_BETHSOFTVID,
diff --git a/libavcodec/bethsoftvideo.h b/libavcodec/bethsoftvideo.h
index d5b5d0a..5cbbdfd 100644
--- a/libavcodec/bethsoftvideo.h
+++ b/libavcodec/bethsoftvideo.h
@@ -2,20 +2,20 @@
  * Bethesda VID video decoder
  * Copyright (C) 2007 Nicholas Tung
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/bfi.c b/libavcodec/bfi.c
index 91c8f6d..312921f 100644
--- a/libavcodec/bfi.c
+++ b/libavcodec/bfi.c
@@ -2,20 +2,20 @@
  * Brute Force & Ignorance (BFI) video decoder
  * Copyright (c) 2008 Sisir Koppaka
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -47,7 +47,7 @@ static av_cold int bfi_decode_init(AVCodecContext * avctx)
 static int bfi_decode_frame(AVCodecContext * avctx, void *data,
                             int *data_size, AVPacket *avpkt)
 {
-    const uint8_t *buf = avpkt->data;
+    const uint8_t *buf = avpkt->data, *buf_end = avpkt->data + avpkt->size;
     int buf_size = avpkt->size;
     BFIContext *bfi = avctx->priv_data;
     uint8_t *dst = bfi->dst;
@@ -99,6 +99,11 @@ static int bfi_decode_frame(AVCodecContext * avctx, void *data,
         unsigned int code = byte >> 6;
         unsigned int length = byte & ~0xC0;
 
+        if (buf >= buf_end) {
+            av_log(avctx, AV_LOG_ERROR, "Input resolution larger than actual frame.\n");
+            return -1;
+        }
+
         /* Get length and offset(if required) */
         if (length == 0) {
             if (code == 1) {
@@ -121,6 +126,10 @@ static int bfi_decode_frame(AVCodecContext * avctx, void *data,
         switch (code) {
 
         case 0:                //Normal Chain
+            if (length >= buf_end - buf) {
+                av_log(avctx, AV_LOG_ERROR, "Frame larger than buffer.\n");
+                return -1;
+            }
             bytestream_get_buffer(&buf, dst, length);
             dst += length;
             break;
@@ -171,7 +180,7 @@ static av_cold int bfi_decode_close(AVCodecContext * avctx)
     return 0;
 }
 
-AVCodec bfi_decoder = {
+AVCodec ff_bfi_decoder = {
     .name = "bfi",
     .type = AVMEDIA_TYPE_VIDEO,
     .id = CODEC_ID_BFI,
diff --git a/libavcodec/bfin/config_bfin.h b/libavcodec/bfin/config_bfin.h
index f3a2c6e..0fee494 100644
--- a/libavcodec/bfin/config_bfin.h
+++ b/libavcodec/bfin/config_bfin.h
@@ -1,20 +1,20 @@
 /*
  * Copyright (C) 2007 Marc Hoffman <marc.hoffman at analog.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 /*
diff --git a/libavcodec/bfin/dsputil_bfin.c b/libavcodec/bfin/dsputil_bfin.c
index 161d2da..65d0308 100644
--- a/libavcodec/bfin/dsputil_bfin.c
+++ b/libavcodec/bfin/dsputil_bfin.c
@@ -4,20 +4,20 @@
  * Copyright (C) 2007 Marc Hoffman <marc.hoffman at analog.com>
  * Copyright (c) 2006 Michael Benjamin <michael.benjamin at analog.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -228,18 +228,6 @@ void dsputil_init_bfin( DSPContext* c, AVCodecContext *avctx )
     c->sse[1] = ff_bfin_sse8;
     c->sse[2] = ff_bfin_sse4;
 
-
-    /**
-     * Halfpel motion compensation with rounding (a+b+1)>>1.
-     * This is an array[4][4] of motion compensation functions for 4
-     * horizontal blocksizes (8,16) and the 4 halfpel positions
-     * *pixels_tab[ 0->16xH 1->8xH ][ xhalfpel + 2*yhalfpel ]
-     * @param block destination where the result is stored
-     * @param pixels source
-     * @param line_size number of bytes in a horizontal line of block
-     * @param h height
-     */
-
     c->put_pixels_tab[0][0] = bfin_put_pixels16;
     c->put_pixels_tab[0][1] = bfin_put_pixels16_x2;
     c->put_pixels_tab[0][2] = bfin_put_pixels16_y2;
diff --git a/libavcodec/bfin/dsputil_bfin.h b/libavcodec/bfin/dsputil_bfin.h
index 7edcf97..f1a9b32 100644
--- a/libavcodec/bfin/dsputil_bfin.h
+++ b/libavcodec/bfin/dsputil_bfin.h
@@ -3,20 +3,20 @@
  *
  * Copyright (C) 2007 Marc Hoffman <mmh at pleasantst.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/bfin/fdct_bfin.S b/libavcodec/bfin/fdct_bfin.S
index 0eac7a3..4c32436 100644
--- a/libavcodec/bfin/fdct_bfin.S
+++ b/libavcodec/bfin/fdct_bfin.S
@@ -3,20 +3,20 @@
  *
  * Copyright (C) 2007 Marc Hoffman <marc.hoffman at analog.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 /*
diff --git a/libavcodec/bfin/idct_bfin.S b/libavcodec/bfin/idct_bfin.S
index 04f9159..b3dedd3 100644
--- a/libavcodec/bfin/idct_bfin.S
+++ b/libavcodec/bfin/idct_bfin.S
@@ -3,20 +3,20 @@
  *
  * Copyright (C) 2007 Marc Hoffman <marc.hoffman at analog.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 /*
diff --git a/libavcodec/bfin/mathops.h b/libavcodec/bfin/mathops.h
index a0e808c..db527bf 100644
--- a/libavcodec/bfin/mathops.h
+++ b/libavcodec/bfin/mathops.h
@@ -3,20 +3,20 @@
  *
  * Copyright (C) 2007 Marc Hoffman <mmhoffm at gmail.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #ifndef AVCODEC_BFIN_MATHOPS_H
diff --git a/libavcodec/bfin/mpegvideo_bfin.c b/libavcodec/bfin/mpegvideo_bfin.c
index 0373e22..ad68876 100644
--- a/libavcodec/bfin/mpegvideo_bfin.c
+++ b/libavcodec/bfin/mpegvideo_bfin.c
@@ -3,20 +3,20 @@
  *
  * Copyright (C) 2007 Marc Hoffman <mmh at pleasantst.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/bfin/pixels_bfin.S b/libavcodec/bfin/pixels_bfin.S
index 69b493b..085ff46 100644
--- a/libavcodec/bfin/pixels_bfin.S
+++ b/libavcodec/bfin/pixels_bfin.S
@@ -2,20 +2,20 @@
  * Blackfin Pixel Operations
  * Copyright (C) 2007 Marc Hoffman <marc.hoffman at analog.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #include "config_bfin.h"
diff --git a/libavcodec/bfin/vp3_bfin.c b/libavcodec/bfin/vp3_bfin.c
index b010178..4b08042 100644
--- a/libavcodec/bfin/vp3_bfin.c
+++ b/libavcodec/bfin/vp3_bfin.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (C) 2007 Marc Hoffman <marc.hoffman at analog.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,14 +25,14 @@
 /* Intra iDCT offset 128 */
 void ff_bfin_vp3_idct_put (uint8_t *dest, int line_size, DCTELEM *block)
 {
-    uint8_t *cm = ff_cropTbl + MAX_NEG_CROP;
+    uint8_t *cm = ff_cropTbl + MAX_NEG_CROP + 128;
     int i,j;
 
     ff_bfin_vp3_idct (block);
 
     for (i=0;i<8;i++)
         for (j=0;j<8;j++)
-            dest[line_size*i+j]=cm[128+block[i*8+j]];
+            dest[line_size*i+j]=cm[block[i*8+j]];
 }
 
 /* Inter iDCT */
diff --git a/libavcodec/bfin/vp3_idct_bfin.S b/libavcodec/bfin/vp3_idct_bfin.S
index 21f732c..4c678f1 100644
--- a/libavcodec/bfin/vp3_idct_bfin.S
+++ b/libavcodec/bfin/vp3_idct_bfin.S
@@ -3,20 +3,20 @@
  *
  * Copyright (C) 2007 Marc Hoffman <marc.hoffman at analog.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 /*
diff --git a/libavcodec/bgmc.c b/libavcodec/bgmc.c
index 86b807b..b8aaa8d 100644
--- a/libavcodec/bgmc.c
+++ b/libavcodec/bgmc.c
@@ -2,20 +2,20 @@
  * Block Gilbert-Moore decoder
  * Copyright (c) 2010 Thilo Borgmann <thilo.borgmann _at_ googlemail.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -424,10 +424,10 @@ static const uint16_t * const cf_table[16] = {
 };
 
 
-/** Initializes a given lookup table using a given delta
+/** Initialize a given lookup table using a given delta
  */
-static void bgmc_lut_fillp(uint8_t *lut, unsigned int *lut_status,
-                           unsigned int delta)
+static void bgmc_lut_fillp(uint8_t *lut, int *lut_status,
+                           int delta)
 {
     unsigned int sx, i;
 
@@ -446,10 +446,10 @@ static void bgmc_lut_fillp(uint8_t *lut, unsigned int *lut_status,
 }
 
 
-/** Retunes the index of a suitable lookup table for a given delta
+/** Retune the index of a suitable lookup table for a given delta
  */
-static uint8_t* bgmc_lut_getp(uint8_t *lut, unsigned int *lut_status,
-                              unsigned int delta)
+static uint8_t* bgmc_lut_getp(uint8_t *lut, int *lut_status,
+                              int delta)
 {
     unsigned int i = av_clip(delta, 0, LUT_BUFF - 1);
 
@@ -462,9 +462,9 @@ static uint8_t* bgmc_lut_getp(uint8_t *lut, unsigned int *lut_status,
 }
 
 
-/** Initializes the lookup table arrays
+/** Initialize the lookup table arrays
  */
-int ff_bgmc_init(AVCodecContext *avctx, uint8_t **cf_lut, unsigned int **cf_lut_status)
+int ff_bgmc_init(AVCodecContext *avctx, uint8_t **cf_lut, int **cf_lut_status)
 {
     *cf_lut        = av_malloc(sizeof(*cf_lut       ) * LUT_BUFF * 16 * LUT_SIZE);
     *cf_lut_status = av_malloc(sizeof(*cf_lut_status) * LUT_BUFF);
@@ -473,22 +473,25 @@ int ff_bgmc_init(AVCodecContext *avctx, uint8_t **cf_lut, unsigned int **cf_lut_
         ff_bgmc_end(cf_lut, cf_lut_status);
         av_log(avctx, AV_LOG_ERROR, "Allocating buffer memory failed.\n");
         return AVERROR(ENOMEM);
+    } else {
+        // initialize lut_status buffer to a value never used to compare against
+        memset(*cf_lut_status, -1, sizeof(*cf_lut_status) * LUT_BUFF);
     }
 
     return 0;
 }
 
 
-/** Releases the lookup table arrays
+/** Release the lookup table arrays
  */
-void ff_bgmc_end(uint8_t **cf_lut, unsigned int **cf_lut_status)
+void ff_bgmc_end(uint8_t **cf_lut, int **cf_lut_status)
 {
     av_freep(cf_lut);
     av_freep(cf_lut_status);
 }
 
 
-/** Initializes decoding and reads the first value
+/** Initialize decoding and reads the first value
  */
 void ff_bgmc_decode_init(GetBitContext *gb,
                       unsigned int *h, unsigned int *l, unsigned int *v)
@@ -507,12 +510,12 @@ void ff_bgmc_decode_end(GetBitContext *gb)
 }
 
 
-/** Reads and decodes a block Gilbert-Moore coded symbol
+/** Read and decode a block Gilbert-Moore coded symbol
  */
 void ff_bgmc_decode(GetBitContext *gb, unsigned int num, int32_t *dst,
-                 unsigned int delta, unsigned int sx,
+                 int delta, unsigned int sx,
                  unsigned int *h, unsigned int *l, unsigned int *v,
-                 uint8_t *cf_lut, unsigned int *cf_lut_status)
+                 uint8_t *cf_lut, int *cf_lut_status)
 {
     unsigned int i;
     uint8_t *lut = bgmc_lut_getp(cf_lut, cf_lut_status, delta);
diff --git a/libavcodec/bgmc.h b/libavcodec/bgmc.h
index eab413b..3d5b490 100644
--- a/libavcodec/bgmc.h
+++ b/libavcodec/bgmc.h
@@ -2,20 +2,20 @@
  * Block Gilbert-Moore decoder
  * Copyright (c) 2010 Thilo Borgmann <thilo.borgmann _at_ googlemail.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -34,10 +34,10 @@
 #include "get_bits.h"
 
 
-int ff_bgmc_init(AVCodecContext *avctx, uint8_t **cf_lut, unsigned int **cf_lut_status);
+int ff_bgmc_init(AVCodecContext *avctx, uint8_t **cf_lut, int **cf_lut_status);
 
 
-void ff_bgmc_end(uint8_t **cf_lut, unsigned int **cf_lut_status);
+void ff_bgmc_end(uint8_t **cf_lut, int **cf_lut_status);
 
 
 void ff_bgmc_decode_init(GetBitContext *gb,
@@ -48,9 +48,9 @@ void ff_bgmc_decode_end(GetBitContext *gb);
 
 
 void ff_bgmc_decode(GetBitContext *gb, unsigned int num, int32_t *dst,
-                 unsigned int delta, unsigned int sx,
+                 int delta, unsigned int sx,
                  unsigned int *h, unsigned int *l, unsigned int *v,
-                 uint8_t *cf_lut, unsigned int *cf_lut_status);
+                 uint8_t *cf_lut, int *cf_lut_status);
 
 
 #endif /* AVCODEC_BGMC_H */
diff --git a/libavcodec/bink.c b/libavcodec/bink.c
index a988a34..34d4d10 100644
--- a/libavcodec/bink.c
+++ b/libavcodec/bink.c
@@ -1,24 +1,26 @@
 /*
  * Bink video decoder
  * Copyright (c) 2009 Konstantin Shishkov
+ * Copyright (C) 2011 Peter Ross <pross at xvid.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/imgutils.h"
 #include "avcodec.h"
 #include "dsputil.h"
 #include "binkdata.h"
@@ -33,6 +35,35 @@
 static VLC bink_trees[16];
 
 /**
+ * IDs for different data types used in old version of Bink video codec
+ */
+enum OldSources {
+    BINKB_SRC_BLOCK_TYPES = 0, ///< 8x8 block types
+    BINKB_SRC_COLORS,          ///< pixel values used for different block types
+    BINKB_SRC_PATTERN,         ///< 8-bit values for 2-colour pattern fill
+    BINKB_SRC_X_OFF,           ///< X components of motion value
+    BINKB_SRC_Y_OFF,           ///< Y components of motion value
+    BINKB_SRC_INTRA_DC,        ///< DC values for intrablocks with DCT
+    BINKB_SRC_INTER_DC,        ///< DC values for interblocks with DCT
+    BINKB_SRC_INTRA_Q,         ///< quantizer values for intrablocks with DCT
+    BINKB_SRC_INTER_Q,         ///< quantizer values for interblocks with DCT
+    BINKB_SRC_INTER_COEFS,     ///< number of coefficients for residue blocks
+
+    BINKB_NB_SRC
+};
+
+static const int binkb_bundle_sizes[BINKB_NB_SRC] = {
+    4, 8, 8, 5, 5, 11, 11, 4, 4, 7
+};
+
+static const int binkb_bundle_signed[BINKB_NB_SRC] = {
+    0, 0, 0, 1, 1, 0, 1, 0, 0, 0
+};
+
+static uint32_t binkb_intra_quant[16][64];
+static uint32_t binkb_inter_quant[16][64];
+
+/**
  * IDs for different data types used in Bink video codec
  */
 enum Sources {
@@ -84,7 +115,7 @@ typedef struct BinkContext {
     int            swap_planes;
     ScanTable      scantable;            ///< permutated scantable for DCT coeffs decoding
 
-    Bundle         bundle[BINK_NB_SRC];  ///< bundles for decoding all data types
+    Bundle         bundle[BINKB_NB_SRC]; ///< bundles for decoding all data types
     Tree           col_high[16];         ///< trees for decoding high nibble in "colours" data type
     int            col_lastval;          ///< value of last decoded high nibble in "colours" data type
 } BinkContext;
@@ -106,7 +137,7 @@ enum BlockTypes {
 };
 
 /**
- * Initializes length length in all bundles.
+ * Initialize length length in all bundles.
  *
  * @param c     decoder context
  * @param width plane width
@@ -118,7 +149,7 @@ static void init_lengths(BinkContext *c, int width, int bw)
 
     c->bundle[BINK_SRC_SUB_BLOCK_TYPES].len = av_log2((width >> 4) + 511) + 1;
 
-    c->bundle[BINK_SRC_COLORS].len = av_log2((width >> 3)*64 + 511) + 1;
+    c->bundle[BINK_SRC_COLORS].len = av_log2(bw*64 + 511) + 1;
 
     c->bundle[BINK_SRC_INTRA_DC].len =
     c->bundle[BINK_SRC_INTER_DC].len =
@@ -127,11 +158,11 @@ static void init_lengths(BinkContext *c, int width, int bw)
 
     c->bundle[BINK_SRC_PATTERN].len = av_log2((bw << 3) + 511) + 1;
 
-    c->bundle[BINK_SRC_RUN].len = av_log2((width >> 3)*48 + 511) + 1;
+    c->bundle[BINK_SRC_RUN].len = av_log2(bw*48 + 511) + 1;
 }
 
 /**
- * Allocates memory for bundles.
+ * Allocate memory for bundles.
  *
  * @param c decoder context
  */
@@ -144,26 +175,26 @@ static av_cold void init_bundles(BinkContext *c)
     bh = (c->avctx->height + 7) >> 3;
     blocks = bw * bh;
 
-    for (i = 0; i < BINK_NB_SRC; i++) {
+    for (i = 0; i < BINKB_NB_SRC; i++) {
         c->bundle[i].data = av_malloc(blocks * 64);
         c->bundle[i].data_end = c->bundle[i].data + blocks * 64;
     }
 }
 
 /**
- * Frees memory used by bundles.
+ * Free memory used by bundles.
  *
  * @param c decoder context
  */
 static av_cold void free_bundles(BinkContext *c)
 {
     int i;
-    for (i = 0; i < BINK_NB_SRC; i++)
+    for (i = 0; i < BINKB_NB_SRC; i++)
         av_freep(&c->bundle[i].data);
 }
 
 /**
- * Merges two consequent lists of equal size depending on bits read.
+ * Merge two consequent lists of equal size depending on bits read.
  *
  * @param gb   context for reading bits
  * @param dst  buffer where merged list will be written to
@@ -192,7 +223,7 @@ static void merge(GetBitContext *gb, uint8_t *dst, uint8_t *src, int size)
 }
 
 /**
- * Reads information about Huffman tree used to decode data.
+ * Read information about Huffman tree used to decode data.
  *
  * @param gb   context for reading bits
  * @param tree pointer for storing tree data
@@ -233,7 +264,7 @@ static void read_tree(GetBitContext *gb, Tree *tree)
 }
 
 /**
- * Prepares bundle for decoding data.
+ * Prepare bundle for decoding data.
  *
  * @param gb          context for reading bits
  * @param c           decoder context
@@ -324,7 +355,7 @@ static int read_motion_values(AVCodecContext *avctx, GetBitContext *gb, Bundle *
     return 0;
 }
 
-const uint8_t bink_rlelens[4] = { 4, 8, 12, 32 };
+static const uint8_t bink_rlelens[4] = { 4, 8, 12, 32 };
 
 static int read_block_types(AVCodecContext *avctx, GetBitContext *gb, Bundle *b)
 {
@@ -462,14 +493,14 @@ static int read_dcs(AVCodecContext *avctx, GetBitContext *gb, Bundle *b,
 }
 
 /**
- * Retrieves next value from bundle.
+ * Retrieve next value from bundle.
  *
  * @param c      decoder context
  * @param bundle bundle number
  */
 static inline int get_value(BinkContext *c, int bundle)
 {
-    int16_t ret;
+    int ret;
 
     if (bundle < BINK_SRC_X_OFF || bundle == BINK_SRC_RUN)
         return *c->bundle[bundle].cur_ptr++;
@@ -480,17 +511,77 @@ static inline int get_value(BinkContext *c, int bundle)
     return ret;
 }
 
+static void binkb_init_bundle(BinkContext *c, int bundle_num)
+{
+    c->bundle[bundle_num].cur_dec =
+    c->bundle[bundle_num].cur_ptr = c->bundle[bundle_num].data;
+    c->bundle[bundle_num].len = 13;
+}
+
+static void binkb_init_bundles(BinkContext *c)
+{
+    int i;
+    for (i = 0; i < BINKB_NB_SRC; i++)
+        binkb_init_bundle(c, i);
+}
+
+static int binkb_read_bundle(BinkContext *c, GetBitContext *gb, int bundle_num)
+{
+    const int bits = binkb_bundle_sizes[bundle_num];
+    const int mask = 1 << (bits - 1);
+    const int issigned = binkb_bundle_signed[bundle_num];
+    Bundle *b = &c->bundle[bundle_num];
+    int i, len;
+
+    CHECK_READ_VAL(gb, b, len);
+    if (bits <= 8) {
+        if (!issigned) {
+            for (i = 0; i < len; i++)
+                *b->cur_dec++ = get_bits(gb, bits);
+        } else {
+            for (i = 0; i < len; i++)
+                *b->cur_dec++ = get_bits(gb, bits) - mask;
+        }
+    } else {
+        int16_t *dst = (int16_t*)b->cur_dec;
+
+        if (!issigned) {
+            for (i = 0; i < len; i++)
+                *dst++ = get_bits(gb, bits);
+        } else {
+            for (i = 0; i < len; i++)
+                *dst++ = get_bits(gb, bits) - mask;
+        }
+        b->cur_dec = (uint8_t*)dst;
+    }
+    return 0;
+}
+
+static inline int binkb_get_value(BinkContext *c, int bundle_num)
+{
+    int16_t ret;
+    const int bits = binkb_bundle_sizes[bundle_num];
+
+    if (bits <= 8) {
+        int val = *c->bundle[bundle_num].cur_ptr++;
+        return binkb_bundle_signed[bundle_num] ? (int8_t)val : val;
+    }
+    ret = *(int16_t*)c->bundle[bundle_num].cur_ptr;
+    c->bundle[bundle_num].cur_ptr += 2;
+    return ret;
+}
+
 /**
- * Reads 8x8 block of DCT coefficients.
+ * Read 8x8 block of DCT coefficients.
  *
  * @param gb       context for reading bits
  * @param block    place for storing coefficients
  * @param scan     scan order table
- * @param is_intra tells what set of quantizer matrices to use
+ * @param quant_matrices quantization matrices
  * @return 0 for success, negative value in other cases
  */
 static int read_dct_coeffs(GetBitContext *gb, DCTELEM block[64], const uint8_t *scan,
-                           int is_intra)
+                           const uint32_t quant_matrices[16][64], int q)
 {
     int coef_list[128];
     int mode_list[128];
@@ -570,9 +661,14 @@ static int read_dct_coeffs(GetBitContext *gb, DCTELEM block[64], const uint8_t *
         }
     }
 
-    quant_idx = get_bits(gb, 4);
-    quant = is_intra ? bink_intra_quant[quant_idx]
-                     : bink_inter_quant[quant_idx];
+    if (q == -1) {
+        quant_idx = get_bits(gb, 4);
+    } else {
+        quant_idx = q;
+    }
+
+    quant = quant_matrices[quant_idx];
+
     block[0] = (block[0] * quant[0]) >> 11;
     for (i = 0; i < coef_count; i++) {
         int idx = coef_idx[i];
@@ -583,7 +679,7 @@ static int read_dct_coeffs(GetBitContext *gb, DCTELEM block[64], const uint8_t *
 }
 
 /**
- * Reads 8x8 block with residue after motion compensation.
+ * Read 8x8 block with residue after motion compensation.
  *
  * @param gb          context for reading bits
  * @param block       place to store read data
@@ -672,6 +768,164 @@ static int read_residue(GetBitContext *gb, DCTELEM block[64], int masks_count)
     return 0;
 }
 
+/**
+ * Copy 8x8 block from source to destination, where src and dst may be overlapped
+ */
+static inline void put_pixels8x8_overlapped(uint8_t *dst, uint8_t *src, int stride)
+{
+    uint8_t tmp[64];
+    int i;
+    for (i = 0; i < 8; i++)
+        memcpy(tmp + i*8, src + i*stride, 8);
+    for (i = 0; i < 8; i++)
+        memcpy(dst + i*stride, tmp + i*8, 8);
+}
+
+static int binkb_decode_plane(BinkContext *c, GetBitContext *gb, int plane_idx,
+                              int is_key, int is_chroma)
+{
+    int blk;
+    int i, j, bx, by;
+    uint8_t *dst, *ref, *ref_start, *ref_end;
+    int v, col[2];
+    const uint8_t *scan;
+    int xoff, yoff;
+    LOCAL_ALIGNED_16(DCTELEM, block, [64]);
+    int coordmap[64];
+    int ybias = is_key ? -15 : 0;
+    int qp;
+
+    const int stride = c->pic.linesize[plane_idx];
+    int bw = is_chroma ? (c->avctx->width  + 15) >> 4 : (c->avctx->width  + 7) >> 3;
+    int bh = is_chroma ? (c->avctx->height + 15) >> 4 : (c->avctx->height + 7) >> 3;
+
+    binkb_init_bundles(c);
+    ref_start = c->pic.data[plane_idx];
+    ref_end   = c->pic.data[plane_idx] + (bh * c->pic.linesize[plane_idx] + bw) * 8;
+
+    for (i = 0; i < 64; i++)
+        coordmap[i] = (i & 7) + (i >> 3) * stride;
+
+    for (by = 0; by < bh; by++) {
+        for (i = 0; i < BINKB_NB_SRC; i++) {
+            if (binkb_read_bundle(c, gb, i) < 0)
+                return -1;
+        }
+
+        dst  = c->pic.data[plane_idx]  + 8*by*stride;
+        for (bx = 0; bx < bw; bx++, dst += 8) {
+            blk = binkb_get_value(c, BINKB_SRC_BLOCK_TYPES);
+            switch (blk) {
+            case 0:
+                break;
+            case 1:
+                scan = bink_patterns[get_bits(gb, 4)];
+                i = 0;
+                do {
+                    int mode, run;
+
+                    mode = get_bits1(gb);
+                    run = get_bits(gb, binkb_runbits[i]) + 1;
+
+                    i += run;
+                    if (i > 64) {
+                        av_log(c->avctx, AV_LOG_ERROR, "Run went out of bounds\n");
+                        return -1;
+                    }
+                    if (mode) {
+                        v = binkb_get_value(c, BINKB_SRC_COLORS);
+                        for (j = 0; j < run; j++)
+                            dst[coordmap[*scan++]] = v;
+                    } else {
+                        for (j = 0; j < run; j++)
+                            dst[coordmap[*scan++]] = binkb_get_value(c, BINKB_SRC_COLORS);
+                    }
+                } while (i < 63);
+                if (i == 63)
+                    dst[coordmap[*scan++]] = binkb_get_value(c, BINKB_SRC_COLORS);
+                break;
+            case 2:
+                c->dsp.clear_block(block);
+                block[0] = binkb_get_value(c, BINKB_SRC_INTRA_DC);
+                qp = binkb_get_value(c, BINKB_SRC_INTRA_Q);
+                read_dct_coeffs(gb, block, c->scantable.permutated, binkb_intra_quant, qp);
+                c->dsp.idct_put(dst, stride, block);
+                break;
+            case 3:
+                xoff = binkb_get_value(c, BINKB_SRC_X_OFF);
+                yoff = binkb_get_value(c, BINKB_SRC_Y_OFF) + ybias;
+                ref = dst + xoff + yoff * stride;
+                if (ref < ref_start || ref + 8*stride > ref_end) {
+                    av_log(c->avctx, AV_LOG_WARNING, "Reference block is out of bounds\n");
+                } else if (ref + 8*stride < dst || ref >= dst + 8*stride) {
+                    c->dsp.put_pixels_tab[1][0](dst, ref, stride, 8);
+                } else {
+                    put_pixels8x8_overlapped(dst, ref, stride);
+                }
+                c->dsp.clear_block(block);
+                v = binkb_get_value(c, BINKB_SRC_INTER_COEFS);
+                read_residue(gb, block, v);
+                c->dsp.add_pixels8(dst, block, stride);
+                break;
+            case 4:
+                xoff = binkb_get_value(c, BINKB_SRC_X_OFF);
+                yoff = binkb_get_value(c, BINKB_SRC_Y_OFF) + ybias;
+                ref = dst + xoff + yoff * stride;
+                if (ref < ref_start || ref + 8 * stride > ref_end) {
+                    av_log(c->avctx, AV_LOG_WARNING, "Reference block is out of bounds\n");
+                } else if (ref + 8*stride < dst || ref >= dst + 8*stride) {
+                    c->dsp.put_pixels_tab[1][0](dst, ref, stride, 8);
+                } else {
+                    put_pixels8x8_overlapped(dst, ref, stride);
+                }
+                c->dsp.clear_block(block);
+                block[0] = binkb_get_value(c, BINKB_SRC_INTER_DC);
+                qp = binkb_get_value(c, BINKB_SRC_INTER_Q);
+                read_dct_coeffs(gb, block, c->scantable.permutated, binkb_inter_quant, qp);
+                c->dsp.idct_add(dst, stride, block);
+                break;
+            case 5:
+                v = binkb_get_value(c, BINKB_SRC_COLORS);
+                c->dsp.fill_block_tab[1](dst, v, stride, 8);
+                break;
+            case 6:
+                for (i = 0; i < 2; i++)
+                    col[i] = binkb_get_value(c, BINKB_SRC_COLORS);
+                for (i = 0; i < 8; i++) {
+                    v = binkb_get_value(c, BINKB_SRC_PATTERN);
+                    for (j = 0; j < 8; j++, v >>= 1)
+                        dst[i*stride + j] = col[v & 1];
+                }
+                break;
+            case 7:
+                xoff = binkb_get_value(c, BINKB_SRC_X_OFF);
+                yoff = binkb_get_value(c, BINKB_SRC_Y_OFF) + ybias;
+                ref = dst + xoff + yoff * stride;
+                if (ref < ref_start || ref + 8 * stride > ref_end) {
+                    av_log(c->avctx, AV_LOG_WARNING, "Reference block is out of bounds\n");
+                } else if (ref + 8*stride < dst || ref >= dst + 8*stride) {
+                    c->dsp.put_pixels_tab[1][0](dst, ref, stride, 8);
+                } else {
+                    put_pixels8x8_overlapped(dst, ref, stride);
+                }
+                break;
+            case 8:
+                for (i = 0; i < 8; i++)
+                    memcpy(dst + i*stride, c->bundle[BINKB_SRC_COLORS].cur_ptr + i*8, 8);
+                c->bundle[BINKB_SRC_COLORS].cur_ptr += 64;
+                break;
+            default:
+                av_log(c->avctx, AV_LOG_ERROR, "Unknown block type %d\n", blk);
+                return -1;
+            }
+        }
+    }
+    if (get_bits_count(gb) & 0x1F) //next plane data starts at 32-bit boundary
+        skip_bits_long(gb, 32 - (get_bits_count(gb) & 0x1F));
+
+    return 0;
+}
+
 static int bink_decode_plane(BinkContext *c, GetBitContext *gb, int plane_idx,
                              int is_chroma)
 {
@@ -681,8 +935,8 @@ static int bink_decode_plane(BinkContext *c, GetBitContext *gb, int plane_idx,
     int v, col[2];
     const uint8_t *scan;
     int xoff, yoff;
-    DECLARE_ALIGNED(16, DCTELEM, block[64]);
-    DECLARE_ALIGNED(16, uint8_t, ublock[64]);
+    LOCAL_ALIGNED_16(DCTELEM, block, [64]);
+    LOCAL_ALIGNED_16(uint8_t, ublock, [64]);
     int coordmap[64];
 
     const int stride = c->pic.linesize[plane_idx];
@@ -767,7 +1021,7 @@ static int bink_decode_plane(BinkContext *c, GetBitContext *gb, int plane_idx,
                 case INTRA_BLOCK:
                     c->dsp.clear_block(block);
                     block[0] = get_value(c, BINK_SRC_INTRA_DC);
-                    read_dct_coeffs(gb, block, c->scantable.permutated, 1);
+                    read_dct_coeffs(gb, block, c->scantable.permutated, bink_intra_quant, -1);
                     c->dsp.idct(block);
                     c->dsp.put_pixels_nonclamped(block, ublock, 8);
                     break;
@@ -851,7 +1105,7 @@ static int bink_decode_plane(BinkContext *c, GetBitContext *gb, int plane_idx,
             case INTRA_BLOCK:
                 c->dsp.clear_block(block);
                 block[0] = get_value(c, BINK_SRC_INTRA_DC);
-                read_dct_coeffs(gb, block, c->scantable.permutated, 1);
+                read_dct_coeffs(gb, block, c->scantable.permutated, bink_intra_quant, -1);
                 c->dsp.idct_put(dst, stride, block);
                 break;
             case FILL_BLOCK:
@@ -865,7 +1119,7 @@ static int bink_decode_plane(BinkContext *c, GetBitContext *gb, int plane_idx,
                 c->dsp.put_pixels_tab[1][0](dst, ref, stride, 8);
                 c->dsp.clear_block(block);
                 block[0] = get_value(c, BINK_SRC_INTER_DC);
-                read_dct_coeffs(gb, block, c->scantable.permutated, 0);
+                read_dct_coeffs(gb, block, c->scantable.permutated, bink_inter_quant, -1);
                 c->dsp.idct_add(dst, stride, block);
                 break;
             case PATTERN_BLOCK:
@@ -901,12 +1155,19 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPac
     int plane, plane_idx;
     int bits_count = pkt->size << 3;
 
-    if(c->pic.data[0])
-        avctx->release_buffer(avctx, &c->pic);
+    if (c->version > 'b') {
+        if(c->pic.data[0])
+            avctx->release_buffer(avctx, &c->pic);
 
-    if(avctx->get_buffer(avctx, &c->pic) < 0){
-        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
-        return -1;
+        if(avctx->get_buffer(avctx, &c->pic) < 0){
+            av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
+            return -1;
+        }
+    } else {
+        if(avctx->reget_buffer(avctx, &c->pic) < 0){
+            av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
+            return -1;
+        }
     }
 
     init_get_bits(&gb, pkt->data, bits_count);
@@ -922,8 +1183,13 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPac
     for (plane = 0; plane < 3; plane++) {
         plane_idx = (!plane || !c->swap_planes) ? plane : (plane ^ 3);
 
-        if (bink_decode_plane(c, &gb, plane_idx, !!plane) < 0)
-            return -1;
+        if (c->version > 'b') {
+            if (bink_decode_plane(c, &gb, plane_idx, !!plane) < 0)
+                return -1;
+        } else {
+            if (binkb_decode_plane(c, &gb, plane_idx, !pkt->pts, !!plane) < 0)
+                return -1;
+        }
         if (get_bits_count(&gb) >= bits_count)
             break;
     }
@@ -932,24 +1198,67 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPac
     *data_size = sizeof(AVFrame);
     *(AVFrame*)data = c->pic;
 
-    FFSWAP(AVFrame, c->pic, c->last);
+    if (c->version > 'b')
+        FFSWAP(AVFrame, c->pic, c->last);
 
     /* always report that the buffer was completely consumed */
     return pkt->size;
 }
 
+/**
+ * Caclulate quantization tables for version b
+ */
+static av_cold void binkb_calc_quant()
+{
+    uint8_t inv_bink_scan[64];
+    double s[64];
+    int i, j;
+
+    for (j = 0; j < 8; j++) {
+        for (i = 0; i < 8; i++) {
+            if (j && j != 4)
+               if (i && i != 4)
+                   s[j*8 + i] = cos(j * M_PI/16.0) * cos(i * M_PI/16.0) * 2.0;
+               else
+                   s[j*8 + i] = cos(j * M_PI/16.0) * sqrt(2.0);
+            else
+               if (i && i != 4)
+                   s[j*8 + i] = cos(i * M_PI/16.0) * sqrt(2.0);
+               else
+                   s[j*8 + i] = 1.0;
+        }
+    }
+
+    for (i = 0; i < 64; i++)
+        inv_bink_scan[bink_scan[i]] = i;
+
+    for (j = 0; j < 16; j++) {
+        for (i = 0; i < 64; i++) {
+            int k = inv_bink_scan[i];
+            if (s[i] == 1.0) {
+                binkb_intra_quant[j][k] = (1L << 12) * binkb_intra_seed[i] *
+                                          binkb_num[j]/binkb_den[j];
+                binkb_inter_quant[j][k] = (1L << 12) * binkb_inter_seed[i] *
+                                          binkb_num[j]/binkb_den[j];
+            } else {
+                binkb_intra_quant[j][k] = (1L << 12) * binkb_intra_seed[i] * s[i] *
+                                          binkb_num[j]/(double)binkb_den[j];
+                binkb_inter_quant[j][k] = (1L << 12) * binkb_inter_seed[i] * s[i] *
+                                          binkb_num[j]/(double)binkb_den[j];
+            }
+        }
+    }
+}
+
 static av_cold int decode_init(AVCodecContext *avctx)
 {
     BinkContext * const c = avctx->priv_data;
     static VLC_TYPE table[16 * 128][2];
+    static int binkb_initialised = 0;
     int i;
     int flags;
 
     c->version = avctx->codec_tag >> 24;
-    if (c->version < 'c') {
-        av_log(avctx, AV_LOG_ERROR, "Too old version '%c'\n", c->version);
-        return -1;
-    }
     if (avctx->extradata_size < 4) {
         av_log(avctx, AV_LOG_ERROR, "Extradata missing or too short\n");
         return -1;
@@ -971,7 +1280,7 @@ static av_cold int decode_init(AVCodecContext *avctx)
 
     c->pic.data[0] = NULL;
 
-    if (avcodec_check_dimensions(avctx, avctx->width, avctx->height) < 0) {
+    if (av_image_check_size(avctx->width, avctx->height, 0, avctx) < 0) {
         return 1;
     }
 
@@ -983,6 +1292,13 @@ static av_cold int decode_init(AVCodecContext *avctx)
 
     init_bundles(c);
 
+    if (c->version == 'b') {
+        if (!binkb_initialised) {
+            binkb_calc_quant();
+            binkb_initialised = 1;
+        }
+    }
+
     return 0;
 }
 
@@ -999,7 +1315,7 @@ static av_cold int decode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec bink_decoder = {
+AVCodec ff_bink_decoder = {
     "binkvideo",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_BINKVIDEO,
diff --git a/libavcodec/binkaudio.c b/libavcodec/binkaudio.c
index 295b351..77ce6b9 100644
--- a/libavcodec/binkaudio.c
+++ b/libavcodec/binkaudio.c
@@ -1,22 +1,22 @@
 /*
  * Bink Audio decoder
- * Copyright (c) 2007-2010 Peter Ross (pross at xvid.org)
+ * Copyright (c) 2007-2011 Peter Ross (pross at xvid.org)
  * Copyright (c) 2009 Daniel Verkamp (daniel at drv.nu)
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -32,7 +32,10 @@
 #define ALT_BITSTREAM_READER_LE
 #include "get_bits.h"
 #include "dsputil.h"
-#include "fft.h"
+#include "dct.h"
+#include "rdft.h"
+#include "fmtconvert.h"
+#include "libavutil/intfloat_readwrite.h"
 
 extern const uint16_t ff_wma_critical_freqs[25];
 
@@ -40,9 +43,10 @@ extern const uint16_t ff_wma_critical_freqs[25];
 #define BINK_BLOCK_MAX_SIZE (MAX_CHANNELS << 11)
 
 typedef struct {
-    AVCodecContext *avctx;
     GetBitContext gb;
     DSPContext dsp;
+    FmtConvertContext fmt_conv;
+    int version_b;          ///< Bink version 'b'
     int first;
     int channels;
     int frame_len;          ///< transform size (samples)
@@ -69,8 +73,8 @@ static av_cold int decode_init(AVCodecContext *avctx)
     int i;
     int frame_len_bits;
 
-    s->avctx = avctx;
     dsputil_init(&s->dsp, avctx);
+    ff_fmt_convert_init(&s->fmt_conv, avctx);
 
     /* determine frame length */
     if (avctx->sample_rate < 22050) {
@@ -80,24 +84,25 @@ static av_cold int decode_init(AVCodecContext *avctx)
     } else {
         frame_len_bits = 11;
     }
-    s->frame_len = 1 << frame_len_bits;
 
-    if (s->channels > MAX_CHANNELS) {
-        av_log(s->avctx, AV_LOG_ERROR, "too many channels: %d\n", s->channels);
+    if (avctx->channels > MAX_CHANNELS) {
+        av_log(avctx, AV_LOG_ERROR, "too many channels: %d\n", avctx->channels);
         return -1;
     }
 
+    s->version_b = avctx->codec_tag == MKTAG('B','I','K','b');
+
     if (avctx->codec->id == CODEC_ID_BINKAUDIO_RDFT) {
         // audio is already interleaved for the RDFT format variant
         sample_rate  *= avctx->channels;
-        s->frame_len *= avctx->channels;
         s->channels = 1;
-        if (avctx->channels == 2)
-            frame_len_bits++;
+        if (!s->version_b)
+            frame_len_bits += av_log2(avctx->channels);
     } else {
         s->channels = avctx->channels;
     }
 
+    s->frame_len     = 1 << frame_len_bits;
     s->overlap_len   = s->frame_len / 16;
     s->block_size    = (s->frame_len - s->overlap_len) * s->channels;
     sample_rate_half = (sample_rate + 1) / 2;
@@ -113,13 +118,13 @@ static av_cold int decode_init(AVCodecContext *avctx)
         return AVERROR(ENOMEM);
 
     /* populate bands data */
-    s->bands[0] = 1;
+    s->bands[0] = 2;
     for (i = 1; i < s->num_bands; i++)
-        s->bands[i] = ff_wma_critical_freqs[i - 1] * (s->frame_len / 2) / sample_rate_half;
-    s->bands[s->num_bands] = s->frame_len / 2;
+        s->bands[i] = (ff_wma_critical_freqs[i - 1] * s->frame_len / sample_rate_half) & ~1;
+    s->bands[s->num_bands] = s->frame_len;
 
     s->first = 1;
-    avctx->sample_fmt = SAMPLE_FMT_S16;
+    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
 
     for (i = 0; i < s->channels; i++)
         s->coeffs_ptr[i] = s->coeffs + i * s->frame_len;
@@ -163,9 +168,13 @@ static void decode_block(BinkAudioContext *s, short *out, int use_dct)
 
     for (ch = 0; ch < s->channels; ch++) {
         FFTSample *coeffs = s->coeffs_ptr[ch];
-        q = 0.0f;
-        coeffs[0] = get_float(gb) * s->root;
-        coeffs[1] = get_float(gb) * s->root;
+        if (s->version_b) {
+            coeffs[0] = av_int2flt(get_bits(gb, 32)) * s->root;
+            coeffs[1] = av_int2flt(get_bits(gb, 32)) * s->root;
+        } else {
+            coeffs[0] = get_float(gb) * s->root;
+            coeffs[1] = get_float(gb) * s->root;
+        }
 
         for (i = 0; i < s->num_bands; i++) {
             /* constant is result of 0.066399999/log10(M_E) */
@@ -173,15 +182,15 @@ static void decode_block(BinkAudioContext *s, short *out, int use_dct)
             quant[i] = expf(FFMIN(value, 95) * 0.15289164787221953823f) * s->root;
         }
 
-        // find band (k)
-        for (k = 0; s->bands[k] < 1; k++) {
-            q = quant[k];
-        }
+        k = 0;
+        q = quant[0];
 
         // parse coefficients
         i = 2;
         while (i < s->frame_len) {
-            if (get_bits1(gb)) {
+            if (s->version_b) {
+                j = i + 16;
+            } else if (get_bits1(gb)) {
                 j = i + rle_length_tab[get_bits(gb, 4)] * 8;
             } else {
                 j = i + 8;
@@ -193,11 +202,11 @@ static void decode_block(BinkAudioContext *s, short *out, int use_dct)
             if (width == 0) {
                 memset(coeffs + i, 0, (j - i) * sizeof(*coeffs));
                 i = j;
-                while (s->bands[k] * 2 < i)
+                while (s->bands[k] < i)
                     q = quant[k++];
             } else {
                 while (i < j) {
-                    if (s->bands[k] * 2 == i)
+                    if (s->bands[k] == i)
                         q = quant[k++];
                     coeff = get_bits(gb, width);
                     if (coeff) {
@@ -215,19 +224,15 @@ static void decode_block(BinkAudioContext *s, short *out, int use_dct)
 
         if (CONFIG_BINKAUDIO_DCT_DECODER && use_dct) {
             coeffs[0] /= 0.5;
-            ff_dct_calc (&s->trans.dct,  coeffs);
+            s->trans.dct.dct_calc(&s->trans.dct,  coeffs);
             s->dsp.vector_fmul_scalar(coeffs, coeffs, s->frame_len / 2, s->frame_len);
         }
         else if (CONFIG_BINKAUDIO_RDFT_DECODER)
-            ff_rdft_calc(&s->trans.rdft, coeffs);
+            s->trans.rdft.rdft_calc(&s->trans.rdft, coeffs);
     }
 
-    if (s->dsp.float_to_int16_interleave == ff_float_to_int16_interleave_c) {
-        for (i = 0; i < s->channels; i++)
-            for (j = 0; j < s->frame_len; j++)
-                s->coeffs_ptr[i][j] = 385.0 + s->coeffs_ptr[i][j]*(1.0/32767.0);
-    }
-    s->dsp.float_to_int16_interleave(out, (const float **)s->coeffs_ptr, s->frame_len, s->channels);
+    s->fmt_conv.float_to_int16_interleave(out, (const float **)s->coeffs_ptr,
+                                          s->frame_len, s->channels);
 
     if (!s->first) {
         int count = s->overlap_len * s->channels;
@@ -286,7 +291,7 @@ static int decode_frame(AVCodecContext *avctx,
     return buf_size;
 }
 
-AVCodec binkaudio_rdft_decoder = {
+AVCodec ff_binkaudio_rdft_decoder = {
     "binkaudio_rdft",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_BINKAUDIO_RDFT,
@@ -298,7 +303,7 @@ AVCodec binkaudio_rdft_decoder = {
     .long_name = NULL_IF_CONFIG_SMALL("Bink Audio (RDFT)")
 };
 
-AVCodec binkaudio_dct_decoder = {
+AVCodec ff_binkaudio_dct_decoder = {
     "binkaudio_dct",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_BINKAUDIO_DCT,
diff --git a/libavcodec/binkdata.h b/libavcodec/binkdata.h
index 1ca34a6..db289ad 100644
--- a/libavcodec/binkdata.h
+++ b/libavcodec/binkdata.h
@@ -2,20 +2,20 @@
  * Bink video decoder
  * Copyright (C) 2009 Kostya Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -611,4 +611,45 @@ static const uint32_t bink_inter_quant[16][64] = {
 },
 };
 
+static const uint8_t binkb_runbits[64] = {
+    6, 6, 6, 6, 6, 6, 6, 6,
+    6, 6, 6, 6, 6, 6, 6, 6,
+    6, 6, 6, 6, 6, 6, 6, 6,
+    6, 6, 6, 6, 6, 6, 6, 6,
+    5, 5, 5, 5, 5, 5, 5, 5,
+    5, 5, 5, 5, 5, 5, 5, 5,
+    4, 4, 4, 4, 4, 4, 4, 4,
+    3, 3, 3, 3, 2, 2, 1, 0,
+};
+
+static const uint8_t binkb_intra_seed[64] = {
+    16, 16, 16, 19, 16, 19, 22, 22,
+    22, 22, 26, 24, 26, 22, 22, 27,
+    27, 27, 26, 26, 26, 29, 29, 29,
+    27, 27, 27, 26, 34, 34, 34, 29,
+    29, 29, 27, 27, 37, 34, 34, 32,
+    32, 29, 29, 38, 37, 35, 35, 34,
+    35, 40, 40, 40, 38, 38, 48, 48,
+    46, 46, 58, 56, 56, 69, 69, 83,
+};
+
+static const uint8_t binkb_inter_seed[64] = {
+    16, 17, 17, 18, 18, 18, 19, 19,
+    19, 19, 20, 20, 20, 20, 20, 21,
+    21, 21, 21, 21, 21, 22, 22, 22,
+    22, 22, 22, 22, 23, 23, 23, 23,
+    23, 23, 23, 23, 24, 24, 24, 25,
+    24, 24, 24, 25, 26, 26, 26, 26,
+    25, 27, 27, 27, 27, 27, 28, 28,
+    28, 28, 30, 30, 30, 31, 31, 33,
+};
+
+static const uint8_t binkb_num[16] = {
+    1, 4, 5, 2, 7, 8, 3, 7, 4, 9, 5, 6, 7, 8, 9, 10
+};
+
+static const uint8_t binkb_den[16] = {
+    1, 3, 3, 1, 3, 3, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1
+};
+
 #endif /* AVCODEC_BINKDATA_H */
diff --git a/libavcodec/binkidct.c b/libavcodec/binkidct.c
index 160926e..2326a61 100644
--- a/libavcodec/binkidct.c
+++ b/libavcodec/binkidct.c
@@ -2,20 +2,20 @@
  * Bink IDCT algorithm
  * Copyright (c) 2009 Kostya Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -62,7 +62,7 @@
 #define MUNGE_ROW(x) (((x) + 0x7F)>>8)
 #define IDCT_ROW(dest,src) IDCT_TRANSFORM(dest,0,1,2,3,4,5,6,7,0,1,2,3,4,5,6,7,MUNGE_ROW,src)
 
-static inline void bink_idct_col(DCTELEM *dest, const DCTELEM *src)
+static inline void bink_idct_col(int *dest, const DCTELEM *src)
 {
     if ((src[8]|src[16]|src[24]|src[32]|src[40]|src[48]|src[56])==0) {
         dest[0]  =
@@ -81,7 +81,7 @@ static inline void bink_idct_col(DCTELEM *dest, const DCTELEM *src)
 void ff_bink_idct_c(DCTELEM *block)
 {
     int i;
-    DCTELEM temp[64];
+    int temp[64];
 
     for (i = 0; i < 8; i++)
         bink_idct_col(&temp[i], &block[i]);
@@ -103,7 +103,7 @@ void ff_bink_idct_add_c(uint8_t *dest, int linesize, DCTELEM *block)
 void ff_bink_idct_put_c(uint8_t *dest, int linesize, DCTELEM *block)
 {
     int i;
-    DCTELEM temp[64];
+    int temp[64];
     for (i = 0; i < 8; i++)
         bink_idct_col(&temp[i], &block[i]);
     for (i = 0; i < 8; i++) {
diff --git a/libavcodec/bitstream.c b/libavcodec/bitstream.c
index 0d7a2db..329ec95 100644
--- a/libavcodec/bitstream.c
+++ b/libavcodec/bitstream.c
@@ -6,20 +6,20 @@
  *
  * alternative bitstream reader & writer by Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -275,8 +275,8 @@ int init_vlc_sparse(VLC *vlc, int nb_bits, int nb_codes,
              const void *symbols, int symbols_wrap, int symbols_size,
              int flags)
 {
-    VLCcode buf[nb_codes];
-    int i, j;
+    VLCcode *buf;
+    int i, j, ret;
 
     vlc->bits = nb_bits;
     if(flags & INIT_VLC_USE_NEW_STATIC){
@@ -295,6 +295,8 @@ int init_vlc_sparse(VLC *vlc, int nb_bits, int nb_codes,
     av_log(NULL,AV_LOG_DEBUG,"build table nb_codes=%d\n", nb_codes);
 #endif
 
+    buf = av_malloc((nb_codes+1)*sizeof(VLCcode));
+
     assert(symbols_size <= 2 || !symbols);
     j = 0;
 #define COPY(condition)\
@@ -319,7 +321,10 @@ int init_vlc_sparse(VLC *vlc, int nb_bits, int nb_codes,
     COPY(buf[j].bits && buf[j].bits <= nb_bits);
     nb_codes = j;
 
-    if (build_table(vlc, nb_bits, nb_codes, buf, flags) < 0) {
+    ret = build_table(vlc, nb_bits, nb_codes, buf, flags);
+
+    av_free(buf);
+    if (ret < 0) {
         av_freep(&vlc->table);
         return -1;
     }
diff --git a/libavcodec/bitstream_filter.c b/libavcodec/bitstream_filter.c
index 1a6ba39..b803ca4 100644
--- a/libavcodec/bitstream_filter.c
+++ b/libavcodec/bitstream_filter.c
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/bmp.c b/libavcodec/bmp.c
index da7bb78..fa4014c 100644
--- a/libavcodec/bmp.c
+++ b/libavcodec/bmp.c
@@ -2,20 +2,20 @@
  * BMP image format decoder
  * Copyright (c) 2005 Mans Rullgard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -290,7 +290,7 @@ static int bmp_decode_frame(AVCodecContext *avctx,
                 uint16_t *dst = (uint16_t *) ptr;
 
                 for(j = 0; j < avctx->width; j++)
-                    *dst++ = le2me_16(*src++);
+                    *dst++ = av_le2ne16(*src++);
 
                 buf += n;
                 ptr += linesize;
@@ -335,7 +335,7 @@ static av_cold int bmp_decode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec bmp_decoder = {
+AVCodec ff_bmp_decoder = {
     "bmp",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_BMP,
diff --git a/libavcodec/bmp.h b/libavcodec/bmp.h
index b24a1fa..ab11523 100644
--- a/libavcodec/bmp.h
+++ b/libavcodec/bmp.h
@@ -2,20 +2,20 @@
  * internals for BMP codecs
  * Copyright (c) 2005 Mans Rullgard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/bmpenc.c b/libavcodec/bmpenc.c
index ee85f3c..3d4597c 100644
--- a/libavcodec/bmpenc.c
+++ b/libavcodec/bmpenc.c
@@ -3,23 +3,24 @@
  * Copyright (c) 2006, 2007 Michel Bardiaux
  * Copyright (c) 2009 Daniel Verkamp <daniel at drv.nu>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/imgutils.h"
 #include "avcodec.h"
 #include "bytestream.h"
 #include "bmp.h"
@@ -33,6 +34,32 @@ static av_cold int bmp_encode_init(AVCodecContext *avctx){
     avcodec_get_frame_defaults((AVFrame*)&s->picture);
     avctx->coded_frame = (AVFrame*)&s->picture;
 
+    switch (avctx->pix_fmt) {
+    case PIX_FMT_BGR24:
+        avctx->bits_per_coded_sample = 24;
+        break;
+    case PIX_FMT_RGB555:
+        avctx->bits_per_coded_sample = 16;
+        break;
+    case PIX_FMT_RGB565:
+        avctx->bits_per_coded_sample = 16;
+        break;
+    case PIX_FMT_RGB8:
+    case PIX_FMT_BGR8:
+    case PIX_FMT_RGB4_BYTE:
+    case PIX_FMT_BGR4_BYTE:
+    case PIX_FMT_GRAY8:
+    case PIX_FMT_PAL8:
+        avctx->bits_per_coded_sample = 8;
+        break;
+    case PIX_FMT_MONOBLACK:
+        avctx->bits_per_coded_sample = 1;
+        break;
+    default:
+        av_log(avctx, AV_LOG_INFO, "unsupported pixel format\n");
+        return -1;
+    }
+
     return 0;
 }
 
@@ -42,21 +69,15 @@ static int bmp_encode_frame(AVCodecContext *avctx, unsigned char *buf, int buf_s
     AVFrame * const p= (AVFrame*)&s->picture;
     int n_bytes_image, n_bytes_per_row, n_bytes, i, n, hsize;
     const uint32_t *pal = NULL;
-    int pad_bytes_per_row, bit_count, pal_entries = 0, compression = BMP_RGB;
+    int pad_bytes_per_row, pal_entries = 0, compression = BMP_RGB;
+    int bit_count = avctx->bits_per_coded_sample;
     uint8_t *ptr;
     unsigned char* buf0 = buf;
     *p = *pict;
     p->pict_type= FF_I_TYPE;
     p->key_frame= 1;
     switch (avctx->pix_fmt) {
-    case PIX_FMT_BGR24:
-        bit_count = 24;
-        break;
-    case PIX_FMT_RGB555:
-        bit_count = 16;
-        break;
     case PIX_FMT_RGB565:
-        bit_count = 16;
         compression = BMP_BITFIELDS;
         pal = rgb565_masks; // abuse pal to hold color masks
         pal_entries = 3;
@@ -66,16 +87,13 @@ static int bmp_encode_frame(AVCodecContext *avctx, unsigned char *buf, int buf_s
     case PIX_FMT_RGB4_BYTE:
     case PIX_FMT_BGR4_BYTE:
     case PIX_FMT_GRAY8:
+        ff_set_systematic_pal2((uint32_t*)p->data[1], avctx->pix_fmt);
     case PIX_FMT_PAL8:
-        bit_count = 8;
         pal = (uint32_t *)p->data[1];
         break;
     case PIX_FMT_MONOBLACK:
-        bit_count = 1;
         pal = monoblack_pal;
         break;
-    default:
-        return -1;
     }
     if (pal && !pal_entries) pal_entries = 1 << bit_count;
     n_bytes_per_row = ((int64_t)avctx->width * (int64_t)bit_count + 7LL) >> 3LL;
@@ -131,7 +149,7 @@ static int bmp_encode_frame(AVCodecContext *avctx, unsigned char *buf, int buf_s
     return n_bytes;
 }
 
-AVCodec bmp_encoder = {
+AVCodec ff_bmp_encoder = {
     "bmp",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_BMP,
diff --git a/libavcodec/bytestream.h b/libavcodec/bytestream.h
index b56f6ce..98f0087 100644
--- a/libavcodec/bytestream.h
+++ b/libavcodec/bytestream.h
@@ -2,20 +2,20 @@
  * Bytestream functions
  * copyright (c) 2006 Baptiste Coudurier <baptiste.coudurier at free.fr>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/c93.c b/libavcodec/c93.c
index d713ff8..dc911b0 100644
--- a/libavcodec/c93.c
+++ b/libavcodec/c93.c
@@ -2,20 +2,20 @@
  * Interplay C93 video decoder
  * Copyright (c) 2007 Anssi Hannula <anssi.hannula at gmail.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -242,7 +242,7 @@ static int decode_frame(AVCodecContext *avctx, void *data,
     return buf_size;
 }
 
-AVCodec c93_decoder = {
+AVCodec ff_c93_decoder = {
     "c93",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_C93,
diff --git a/libavcodec/cabac.c b/libavcodec/cabac.c
index 7b5e5b1..098cd6f 100644
--- a/libavcodec/cabac.c
+++ b/libavcodec/cabac.c
@@ -2,20 +2,20 @@
  * H.26L/H.264/AVC/JVT/14496-10/... encoder/decoder
  * Copyright (c) 2003 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/cabac.h b/libavcodec/cabac.h
index 0af77e4..4708563 100644
--- a/libavcodec/cabac.h
+++ b/libavcodec/cabac.h
@@ -2,20 +2,20 @@
  * H.26L/H.264/AVC/JVT/14496-10/... encoder/decoder
  * Copyright (c) 2003 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/cavs.c b/libavcodec/cavs.c
index ff6c869..9a73e2a 100644
--- a/libavcodec/cavs.c
+++ b/libavcodec/cavs.c
@@ -2,20 +2,20 @@
  * Chinese AVS video (AVS1-P2, JiZhun profile) decoder.
  * Copyright (c) 2006  Stefan Gehrer <stefan.gehrer at gmx.de>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -113,22 +113,22 @@ void ff_cavs_filter(AVSContext *h, enum cavs_mb mb_type) {
             if(h->flags & A_AVAIL) {
                 qp_avg = (h->qp + h->left_qp + 1) >> 1;
                 SET_PARAMS;
-                h->s.dsp.cavs_filter_lv(h->cy,h->l_stride,alpha,beta,tc,bs[0],bs[1]);
-                h->s.dsp.cavs_filter_cv(h->cu,h->c_stride,alpha,beta,tc,bs[0],bs[1]);
-                h->s.dsp.cavs_filter_cv(h->cv,h->c_stride,alpha,beta,tc,bs[0],bs[1]);
+                h->cdsp.cavs_filter_lv(h->cy,h->l_stride,alpha,beta,tc,bs[0],bs[1]);
+                h->cdsp.cavs_filter_cv(h->cu,h->c_stride,alpha,beta,tc,bs[0],bs[1]);
+                h->cdsp.cavs_filter_cv(h->cv,h->c_stride,alpha,beta,tc,bs[0],bs[1]);
             }
             qp_avg = h->qp;
             SET_PARAMS;
-            h->s.dsp.cavs_filter_lv(h->cy + 8,h->l_stride,alpha,beta,tc,bs[2],bs[3]);
-            h->s.dsp.cavs_filter_lh(h->cy + 8*h->l_stride,h->l_stride,alpha,beta,tc,
+            h->cdsp.cavs_filter_lv(h->cy + 8,h->l_stride,alpha,beta,tc,bs[2],bs[3]);
+            h->cdsp.cavs_filter_lh(h->cy + 8*h->l_stride,h->l_stride,alpha,beta,tc,
                            bs[6],bs[7]);
 
             if(h->flags & B_AVAIL) {
                 qp_avg = (h->qp + h->top_qp[h->mbx] + 1) >> 1;
                 SET_PARAMS;
-                h->s.dsp.cavs_filter_lh(h->cy,h->l_stride,alpha,beta,tc,bs[4],bs[5]);
-                h->s.dsp.cavs_filter_ch(h->cu,h->c_stride,alpha,beta,tc,bs[4],bs[5]);
-                h->s.dsp.cavs_filter_ch(h->cv,h->c_stride,alpha,beta,tc,bs[4],bs[5]);
+                h->cdsp.cavs_filter_lh(h->cy,h->l_stride,alpha,beta,tc,bs[4],bs[5]);
+                h->cdsp.cavs_filter_ch(h->cu,h->c_stride,alpha,beta,tc,bs[4],bs[5]);
+                h->cdsp.cavs_filter_ch(h->cv,h->c_stride,alpha,beta,tc,bs[4],bs[5]);
             }
         }
     }
@@ -353,7 +353,7 @@ static inline void mc_dir_part(AVSContext *h,Picture *pic,int square,
           || full_my < 0-extra_height
           || full_mx + 16/*FIXME*/ > pic_width + extra_width
           || full_my + 16/*FIXME*/ > pic_height + extra_height){
-        ff_emulated_edge_mc(s->edge_emu_buffer, src_y - 2 - 2*h->l_stride, h->l_stride,
+        s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_y - 2 - 2*h->l_stride, h->l_stride,
                             16+5, 16+5/*FIXME*/, full_mx-2, full_my-2, pic_width, pic_height);
         src_y= s->edge_emu_buffer + 2 + 2*h->l_stride;
         emu=1;
@@ -365,14 +365,14 @@ static inline void mc_dir_part(AVSContext *h,Picture *pic,int square,
     }
 
     if(emu){
-        ff_emulated_edge_mc(s->edge_emu_buffer, src_cb, h->c_stride,
+        s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cb, h->c_stride,
                             9, 9/*FIXME*/, (mx>>3), (my>>3), pic_width>>1, pic_height>>1);
         src_cb= s->edge_emu_buffer;
     }
     chroma_op(dest_cb, src_cb, h->c_stride, chroma_height, mx&7, my&7);
 
     if(emu){
-        ff_emulated_edge_mc(s->edge_emu_buffer, src_cr, h->c_stride,
+        s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cr, h->c_stride,
                             9, 9/*FIXME*/, (mx>>3), (my>>3), pic_width>>1, pic_height>>1);
         src_cr= s->edge_emu_buffer;
     }
@@ -414,30 +414,30 @@ static inline void mc_part_std(AVSContext *h,int square,int chroma_height,int de
 void ff_cavs_inter(AVSContext *h, enum cavs_mb mb_type) {
     if(ff_cavs_partition_flags[mb_type] == 0){ // 16x16
         mc_part_std(h, 1, 8, 0, h->cy, h->cu, h->cv, 0, 0,
-                h->s.dsp.put_cavs_qpel_pixels_tab[0],
+                h->cdsp.put_cavs_qpel_pixels_tab[0],
                 h->s.dsp.put_h264_chroma_pixels_tab[0],
-                h->s.dsp.avg_cavs_qpel_pixels_tab[0],
+                h->cdsp.avg_cavs_qpel_pixels_tab[0],
                 h->s.dsp.avg_h264_chroma_pixels_tab[0],&h->mv[MV_FWD_X0]);
     }else{
         mc_part_std(h, 1, 4, 0, h->cy, h->cu, h->cv, 0, 0,
-                h->s.dsp.put_cavs_qpel_pixels_tab[1],
+                h->cdsp.put_cavs_qpel_pixels_tab[1],
                 h->s.dsp.put_h264_chroma_pixels_tab[1],
-                h->s.dsp.avg_cavs_qpel_pixels_tab[1],
+                h->cdsp.avg_cavs_qpel_pixels_tab[1],
                 h->s.dsp.avg_h264_chroma_pixels_tab[1],&h->mv[MV_FWD_X0]);
         mc_part_std(h, 1, 4, 0, h->cy, h->cu, h->cv, 4, 0,
-                h->s.dsp.put_cavs_qpel_pixels_tab[1],
+                h->cdsp.put_cavs_qpel_pixels_tab[1],
                 h->s.dsp.put_h264_chroma_pixels_tab[1],
-                h->s.dsp.avg_cavs_qpel_pixels_tab[1],
+                h->cdsp.avg_cavs_qpel_pixels_tab[1],
                 h->s.dsp.avg_h264_chroma_pixels_tab[1],&h->mv[MV_FWD_X1]);
         mc_part_std(h, 1, 4, 0, h->cy, h->cu, h->cv, 0, 4,
-                h->s.dsp.put_cavs_qpel_pixels_tab[1],
+                h->cdsp.put_cavs_qpel_pixels_tab[1],
                 h->s.dsp.put_h264_chroma_pixels_tab[1],
-                h->s.dsp.avg_cavs_qpel_pixels_tab[1],
+                h->cdsp.avg_cavs_qpel_pixels_tab[1],
                 h->s.dsp.avg_h264_chroma_pixels_tab[1],&h->mv[MV_FWD_X2]);
         mc_part_std(h, 1, 4, 0, h->cy, h->cu, h->cv, 4, 4,
-                h->s.dsp.put_cavs_qpel_pixels_tab[1],
+                h->cdsp.put_cavs_qpel_pixels_tab[1],
                 h->s.dsp.put_h264_chroma_pixels_tab[1],
-                h->s.dsp.avg_cavs_qpel_pixels_tab[1],
+                h->cdsp.avg_cavs_qpel_pixels_tab[1],
                 h->s.dsp.avg_h264_chroma_pixels_tab[1],&h->mv[MV_FWD_X3]);
     }
 }
@@ -672,6 +672,7 @@ av_cold int ff_cavs_init(AVCodecContext *avctx) {
     MpegEncContext * const s = &h->s;
 
     MPV_decode_defaults(s);
+    ff_cavsdsp_init(&h->cdsp, avctx);
     s->avctx = avctx;
 
     avctx->pix_fmt= PIX_FMT_YUV420P;
diff --git a/libavcodec/cavs.h b/libavcodec/cavs.h
index 729c83e..29ba4d4 100644
--- a/libavcodec/cavs.h
+++ b/libavcodec/cavs.h
@@ -2,20 +2,20 @@
  * Chinese AVS video (AVS1-P2, JiZhun profile) decoder.
  * Copyright (c) 2006  Stefan Gehrer <stefan.gehrer at gmx.de>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -24,6 +24,7 @@
 
 #include "dsputil.h"
 #include "mpegvideo.h"
+#include "cavsdsp.h"
 
 #define SLICE_MAX_START_CODE    0x000001af
 #define EXT_START_CODE          0x000001b5
@@ -153,6 +154,7 @@ struct dec_2dvlc {
 
 typedef struct {
     MpegEncContext s;
+    CAVSDSPContext cdsp;
     Picture picture; ///< currently decoded frame
     Picture DPB[2];  ///< reference frames
     int dist[2];     ///< temporal distances from current frame to ref frames
diff --git a/libavcodec/cavs_parser.c b/libavcodec/cavs_parser.c
index 8e9c35b..2cc6566 100644
--- a/libavcodec/cavs_parser.c
+++ b/libavcodec/cavs_parser.c
@@ -2,20 +2,20 @@
  * Chinese AVS video (AVS1-P2, JiZhun profile) parser.
  * Copyright (c) 2006  Stefan Gehrer <stefan.gehrer at gmx.de>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -97,7 +97,7 @@ static int cavsvideo_parse(AVCodecParserContext *s,
     return next;
 }
 
-AVCodecParser cavsvideo_parser = {
+AVCodecParser ff_cavsvideo_parser = {
     { CODEC_ID_CAVS },
     sizeof(ParseContext1),
     NULL,
diff --git a/libavcodec/cavsdata.h b/libavcodec/cavsdata.h
index b597da1..caed4e8 100644
--- a/libavcodec/cavsdata.h
+++ b/libavcodec/cavsdata.h
@@ -2,20 +2,20 @@
  * Chinese AVS video (AVS1-P2, JiZhun profile) decoder.
  * Copyright (c) 2006  Stefan Gehrer <stefan.gehrer at gmx.de>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -88,15 +88,15 @@ const uint16_t ff_cavs_dequant_mul[64] = {
   32771,35734,38965,42497,46341,50535,55109,60099
 };
 
-/** marks block as unavailable, i.e. out of picture
+/** mark block as unavailable, i.e. out of picture
     or not yet decoded */
 const cavs_vector ff_cavs_un_mv    = {0,0,1,NOT_AVAIL};
 
-/** marks block as "no prediction from this direction"
+/** mark block as "no prediction from this direction"
     e.g. forward motion vector in BWD partition */
 const cavs_vector ff_cavs_dir_mv   = {0,0,1,REF_DIR};
 
-/** marks block as using intra prediction */
+/** mark block as using intra prediction */
 const cavs_vector ff_cavs_intra_mv = {0,0,1,REF_INTRA};
 
 #define EOB 0,0,0
diff --git a/libavcodec/cavsdec.c b/libavcodec/cavsdec.c
index 9d6307c..fa12bc9 100644
--- a/libavcodec/cavsdec.c
+++ b/libavcodec/cavsdec.c
@@ -2,20 +2,20 @@
  * Chinese AVS video (AVS1-P2, JiZhun profile) decoder.
  * Copyright (c) 2006  Stefan Gehrer <stefan.gehrer at gmx.de>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -143,7 +143,7 @@ static int decode_residual_block(AVSContext *h, GetBitContext *gb,
     if(dequant(h,level_buf, run_buf, block, ff_cavs_dequant_mul[qp],
                ff_cavs_dequant_shift[qp], i))
         return -1;
-    h->s.dsp.cavs_idct8_add(dst,block,stride);
+    h->cdsp.cavs_idct8_add(dst,block,stride);
     h->s.dsp.clear_block(block);
     return 0;
 }
@@ -709,7 +709,7 @@ static int cavs_decode_frame(AVCodecContext * avctx,void *data, int *data_size,
     }
 }
 
-AVCodec cavs_decoder = {
+AVCodec ff_cavs_decoder = {
     "cavs",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_CAVS,
diff --git a/libavcodec/cavsdsp.c b/libavcodec/cavsdsp.c
index 808f62b..04e521b 100644
--- a/libavcodec/cavsdsp.c
+++ b/libavcodec/cavsdsp.c
@@ -5,25 +5,26 @@
  *
  * Copyright (c) 2006  Stefan Gehrer <stefan.gehrer at gmx.de>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include <stdio.h>
 #include "dsputil.h"
+#include "cavsdsp.h"
 
 /*****************************************************************************
  *
@@ -510,7 +511,12 @@ CAVS_MC(put_, 16)
 CAVS_MC(avg_, 8)
 CAVS_MC(avg_, 16)
 
-av_cold void ff_cavsdsp_init(DSPContext* c, AVCodecContext *avctx) {
+#define ff_put_cavs_qpel8_mc00_c  ff_put_pixels8x8_c
+#define ff_avg_cavs_qpel8_mc00_c  ff_avg_pixels8x8_c
+#define ff_put_cavs_qpel16_mc00_c ff_put_pixels16x16_c
+#define ff_avg_cavs_qpel16_mc00_c ff_avg_pixels16x16_c
+
+av_cold void ff_cavsdsp_init(CAVSDSPContext* c, AVCodecContext *avctx) {
 #define dspfunc(PFX, IDX, NUM) \
     c->PFX ## _pixels_tab[IDX][ 0] = ff_ ## PFX ## NUM ## _mc00_c; \
     c->PFX ## _pixels_tab[IDX][ 1] = ff_ ## PFX ## NUM ## _mc10_c; \
@@ -537,4 +543,6 @@ av_cold void ff_cavsdsp_init(DSPContext* c, AVCodecContext *avctx) {
     c->cavs_filter_cv = cavs_filter_cv_c;
     c->cavs_filter_ch = cavs_filter_ch_c;
     c->cavs_idct8_add = cavs_idct8_add_c;
+
+    if (HAVE_MMX) ff_cavsdsp_init_mmx(c, avctx);
 }
diff --git a/libavcodec/cavsdsp.h b/libavcodec/cavsdsp.h
new file mode 100644
index 0000000..de2f530
--- /dev/null
+++ b/libavcodec/cavsdsp.h
@@ -0,0 +1,41 @@
+/*
+ * Chinese AVS video (AVS1-P2, JiZhun profile) decoder.
+ * Copyright (c) 2006  Stefan Gehrer <stefan.gehrer at gmx.de>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_CAVSDSP_H
+#define AVCODEC_CAVSDSP_H
+
+#include <stdint.h>
+#include "dsputil.h"
+
+typedef struct CAVSDSPContext {
+    qpel_mc_func put_cavs_qpel_pixels_tab[2][16];
+    qpel_mc_func avg_cavs_qpel_pixels_tab[2][16];
+    void (*cavs_filter_lv)(uint8_t *pix, int stride, int alpha, int beta, int tc, int bs1, int bs2);
+    void (*cavs_filter_lh)(uint8_t *pix, int stride, int alpha, int beta, int tc, int bs1, int bs2);
+    void (*cavs_filter_cv)(uint8_t *pix, int stride, int alpha, int beta, int tc, int bs1, int bs2);
+    void (*cavs_filter_ch)(uint8_t *pix, int stride, int alpha, int beta, int tc, int bs1, int bs2);
+    void (*cavs_idct8_add)(uint8_t *dst, DCTELEM *block, int stride);
+} CAVSDSPContext;
+
+void ff_cavsdsp_init(CAVSDSPContext* c, AVCodecContext *avctx);
+void ff_cavsdsp_init_mmx(CAVSDSPContext* c, AVCodecContext *avctx);
+
+#endif
diff --git a/libavcodec/cbrt_tablegen.c b/libavcodec/cbrt_tablegen.c
index dbbd632..e92c0f1 100644
--- a/libavcodec/cbrt_tablegen.c
+++ b/libavcodec/cbrt_tablegen.c
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2010 Reimar Döffinger <Reimar.Doeffinger at gmx.de>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -31,9 +31,7 @@ int main(void)
 
     write_fileheader();
 
-    printf("static const uint32_t cbrt_tab[1<<13] = {\n");
-    write_uint32_array(cbrt_tab, 1 << 13);
-    printf("};\n");
+    WRITE_ARRAY("static const", uint32_t, cbrt_tab);
 
     return 0;
 }
diff --git a/libavcodec/cbrt_tablegen.h b/libavcodec/cbrt_tablegen.h
index 930e513..977450c 100644
--- a/libavcodec/cbrt_tablegen.h
+++ b/libavcodec/cbrt_tablegen.h
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2010 Reimar Döffinger <Reimar.Doeffinger at gmx.de>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/cdgraphics.c b/libavcodec/cdgraphics.c
index c174aa9..2f8e98c 100644
--- a/libavcodec/cdgraphics.c
+++ b/libavcodec/cdgraphics.c
@@ -2,20 +2,20 @@
  * CD Graphics Video Decoder
  * Copyright (c) 2009 Michael Tison
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -367,7 +367,7 @@ static av_cold int cdg_decode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec cdgraphics_decoder = {
+AVCodec ff_cdgraphics_decoder = {
     "cdgraphics",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_CDGRAPHICS,
@@ -377,5 +377,6 @@ AVCodec cdgraphics_decoder = {
     cdg_decode_end,
     cdg_decode_frame,
     CODEC_CAP_DR1,
+    .max_lowres = 5,
     .long_name = NULL_IF_CONFIG_SMALL("CD Graphics video"),
 };
diff --git a/libavcodec/celp_filters.c b/libavcodec/celp_filters.c
index 26a62ee..32eaff3 100644
--- a/libavcodec/celp_filters.c
+++ b/libavcodec/celp_filters.c
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2008 Vladimir Voroshilov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/celp_filters.h b/libavcodec/celp_filters.h
index 7b64fc0..03d481d 100644
--- a/libavcodec/celp_filters.h
+++ b/libavcodec/celp_filters.h
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2008 Vladimir Voroshilov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -56,7 +56,7 @@ void ff_celp_circ_addf(float *out, const float *in,
 
 /**
  * LP synthesis filter.
- * @param out [out] pointer to output buffer
+ * @param[out] out pointer to output buffer
  * @param filter_coeffs filter coefficients (-0x8000 <= (3.12) < 0x8000)
  * @param in input signal
  * @param buffer_length amount of data to process
@@ -79,7 +79,7 @@ int ff_celp_lp_synthesis_filter(int16_t *out, const int16_t *filter_coeffs,
 
 /**
  * LP synthesis filter.
- * @param out [out] pointer to output buffer
+ * @param[out] out pointer to output buffer
  *        - the array out[-filter_length, -1] must
  *        contain the previous result of this filter
  * @param filter_coeffs filter coefficients.
@@ -99,7 +99,7 @@ void ff_celp_lp_synthesis_filterf(float *out, const float *filter_coeffs,
 
 /**
  * LP zero synthesis filter.
- * @param out [out] pointer to output buffer
+ * @param[out] out pointer to output buffer
  * @param filter_coeffs filter coefficients.
  * @param in input signal
  *        - the array in[-filter_length, -1] must
diff --git a/libavcodec/celp_math.c b/libavcodec/celp_math.c
index 09111da..4ab20ad 100644
--- a/libavcodec/celp_math.c
+++ b/libavcodec/celp_math.c
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2008 Vladimir Voroshilov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/celp_math.h b/libavcodec/celp_math.h
index 7cf7861..9cd9ae2 100644
--- a/libavcodec/celp_math.h
+++ b/libavcodec/celp_math.h
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2008 Vladimir Voroshilov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -43,7 +43,7 @@ int16_t ff_cos(uint16_t arg);
 int ff_exp2(uint16_t power);
 
 /**
- * Calculates log2(x).
+ * Calculate log2(x).
  * @param value function argument, 0 < value <= 7fff ffff
  *
  * @return value of (1<<15) * log2(value)
diff --git a/libavcodec/cga_data.c b/libavcodec/cga_data.c
index 2d1f89c..2c63ff2 100644
--- a/libavcodec/cga_data.c
+++ b/libavcodec/cga_data.c
@@ -1,24 +1,30 @@
 /*
- * CGA ROM data
+ * CGA/EGA/VGA ROM data
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+/**
+ * @file
+ * CGA/EGA/VGA ROM data
+ */
+
 #include <stdint.h>
+#include "cga_data.h"
 
 const uint8_t ff_cga_font[2048] = {
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7e, 0x81, 0xa5, 0x81, 0xbd, 0x99, 0x81, 0x7e,
@@ -151,7 +157,288 @@ const uint8_t ff_cga_font[2048] = {
  0x00, 0x00, 0x3c, 0x3c, 0x3c, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
 };
 
+const uint8_t ff_vga16_font[4096] = {
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x7e, 0x81, 0xa5, 0x81, 0x81, 0xbd, 0x99, 0x81, 0x81, 0x7e, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x7e, 0xff, 0xdb, 0xff, 0xff, 0xc3, 0xe7, 0xff, 0xff, 0x7e, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x6c, 0xfe, 0xfe, 0xfe, 0xfe, 0x7c, 0x38, 0x10, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x7c, 0xfe, 0x7c, 0x38, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x18, 0x3c, 0x3c, 0xe7, 0xe7, 0xe7, 0x18, 0x18, 0x3c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x18, 0x3c, 0x7e, 0xff, 0xff, 0x7e, 0x18, 0x18, 0x3c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x3c, 0x3c, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe7, 0xc3, 0xc3, 0xe7, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x66, 0x42, 0x42, 0x66, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0xff, 0xff, 0xff, 0xff, 0xff, 0xc3, 0x99, 0xbd, 0xbd, 0x99, 0xc3, 0xff, 0xff, 0xff, 0xff, 0xff,
+ 0x00, 0x00, 0x1e, 0x0e, 0x1a, 0x32, 0x78, 0xcc, 0xcc, 0xcc, 0xcc, 0x78, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x3c, 0x66, 0x66, 0x66, 0x66, 0x3c, 0x18, 0x7e, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x3f, 0x33, 0x3f, 0x30, 0x30, 0x30, 0x30, 0x70, 0xf0, 0xe0, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x7f, 0x63, 0x7f, 0x63, 0x63, 0x63, 0x63, 0x67, 0xe7, 0xe6, 0xc0, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x18, 0x18, 0xdb, 0x3c, 0xe7, 0x3c, 0xdb, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfe, 0xf8, 0xf0, 0xe0, 0xc0, 0x80, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x02, 0x06, 0x0e, 0x1e, 0x3e, 0xfe, 0x3e, 0x1e, 0x0e, 0x06, 0x02, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x18, 0x3c, 0x7e, 0x18, 0x18, 0x18, 0x7e, 0x3c, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x00, 0x66, 0x66, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x7f, 0xdb, 0xdb, 0xdb, 0x7b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x7c, 0xc6, 0x60, 0x38, 0x6c, 0xc6, 0xc6, 0x6c, 0x38, 0x0c, 0xc6, 0x7c, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0xfe, 0xfe, 0xfe, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x18, 0x3c, 0x7e, 0x18, 0x18, 0x18, 0x7e, 0x3c, 0x18, 0x7e, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x18, 0x3c, 0x7e, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x7e, 0x3c, 0x18, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x0c, 0xfe, 0x0c, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x60, 0xfe, 0x60, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0xc0, 0xc0, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x24, 0x66, 0xff, 0x66, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x38, 0x7c, 0x7c, 0xfe, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0xfe, 0xfe, 0x7c, 0x7c, 0x38, 0x38, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x18, 0x3c, 0x3c, 0x3c, 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x66, 0x66, 0x66, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x6c, 0x6c, 0xfe, 0x6c, 0x6c, 0x6c, 0xfe, 0x6c, 0x6c, 0x00, 0x00, 0x00, 0x00,
+ 0x18, 0x18, 0x7c, 0xc6, 0xc2, 0xc0, 0x7c, 0x06, 0x06, 0x86, 0xc6, 0x7c, 0x18, 0x18, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0xc2, 0xc6, 0x0c, 0x18, 0x30, 0x60, 0xc6, 0x86, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x38, 0x6c, 0x6c, 0x38, 0x76, 0xdc, 0xcc, 0xcc, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x30, 0x30, 0x30, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x0c, 0x18, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x18, 0x0c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x30, 0x18, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x18, 0x30, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x66, 0x3c, 0xff, 0x3c, 0x66, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x7e, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x30, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x02, 0x06, 0x0c, 0x18, 0x30, 0x60, 0xc0, 0x80, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x3c, 0x66, 0xc3, 0xc3, 0xdb, 0xdb, 0xc3, 0xc3, 0x66, 0x3c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x18, 0x38, 0x78, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x7e, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x7c, 0xc6, 0x06, 0x0c, 0x18, 0x30, 0x60, 0xc0, 0xc6, 0xfe, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x7c, 0xc6, 0x06, 0x06, 0x3c, 0x06, 0x06, 0x06, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x0c, 0x1c, 0x3c, 0x6c, 0xcc, 0xfe, 0x0c, 0x0c, 0x0c, 0x1e, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0xfe, 0xc0, 0xc0, 0xc0, 0xfc, 0x06, 0x06, 0x06, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x38, 0x60, 0xc0, 0xc0, 0xfc, 0xc6, 0xc6, 0xc6, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0xfe, 0xc6, 0x06, 0x06, 0x0c, 0x18, 0x30, 0x30, 0x30, 0x30, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x7c, 0xc6, 0xc6, 0xc6, 0x7c, 0xc6, 0xc6, 0xc6, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x7c, 0xc6, 0xc6, 0xc6, 0x7e, 0x06, 0x06, 0x06, 0x0c, 0x78, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x18, 0x18, 0x30, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x06, 0x0c, 0x18, 0x30, 0x60, 0x30, 0x18, 0x0c, 0x06, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x7e, 0x00, 0x00, 0x7e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x60, 0x30, 0x18, 0x0c, 0x06, 0x0c, 0x18, 0x30, 0x60, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x7c, 0xc6, 0xc6, 0x0c, 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x7c, 0xc6, 0xc6, 0xde, 0xde, 0xde, 0xdc, 0xc0, 0x7c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x10, 0x38, 0x6c, 0xc6, 0xc6, 0xfe, 0xc6, 0xc6, 0xc6, 0xc6, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0xfc, 0x66, 0x66, 0x66, 0x7c, 0x66, 0x66, 0x66, 0x66, 0xfc, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x3c, 0x66, 0xc2, 0xc0, 0xc0, 0xc0, 0xc0, 0xc2, 0x66, 0x3c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0xf8, 0x6c, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x6c, 0xf8, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0xfe, 0x66, 0x62, 0x68, 0x78, 0x68, 0x60, 0x62, 0x66, 0xfe, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0xfe, 0x66, 0x62, 0x68, 0x78, 0x68, 0x60, 0x60, 0x60, 0xf0, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x3c, 0x66, 0xc2, 0xc0, 0xc0, 0xde, 0xc6, 0xc6, 0x66, 0x3a, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0xc6, 0xc6, 0xc6, 0xc6, 0xfe, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x3c, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x1e, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0xcc, 0xcc, 0xcc, 0x78, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0xe6, 0x66, 0x66, 0x6c, 0x78, 0x78, 0x6c, 0x66, 0x66, 0xe6, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0xf0, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x62, 0x66, 0xfe, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0xc3, 0xe7, 0xff, 0xff, 0xdb, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0xc6, 0xe6, 0xf6, 0xfe, 0xde, 0xce, 0xc6, 0xc6, 0xc6, 0xc6, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x7c, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0xfc, 0x66, 0x66, 0x66, 0x7c, 0x60, 0x60, 0x60, 0x60, 0xf0, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x7c, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xd6, 0xde, 0x7c, 0x0c, 0x0e, 0x00, 0x00,
+ 0x00, 0x00, 0xfc, 0x66, 0x66, 0x66, 0x7c, 0x6c, 0x66, 0x66, 0x66, 0xe6, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x7c, 0xc6, 0xc6, 0x60, 0x38, 0x0c, 0x06, 0xc6, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0xff, 0xdb, 0x99, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0x66, 0x3c, 0x18, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xdb, 0xdb, 0xff, 0x66, 0x66, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0xc3, 0xc3, 0x66, 0x3c, 0x18, 0x18, 0x3c, 0x66, 0xc3, 0xc3, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0xc3, 0xc3, 0xc3, 0x66, 0x3c, 0x18, 0x18, 0x18, 0x18, 0x3c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0xff, 0xc3, 0x86, 0x0c, 0x18, 0x30, 0x60, 0xc1, 0xc3, 0xff, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x3c, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x3c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x80, 0xc0, 0xe0, 0x70, 0x38, 0x1c, 0x0e, 0x06, 0x02, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x3c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x3c, 0x00, 0x00, 0x00, 0x00,
+ 0x10, 0x38, 0x6c, 0xc6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00,
+ 0x30, 0x30, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x0c, 0x7c, 0xcc, 0xcc, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0xe0, 0x60, 0x60, 0x78, 0x6c, 0x66, 0x66, 0x66, 0x66, 0x7c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0xc6, 0xc0, 0xc0, 0xc0, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x1c, 0x0c, 0x0c, 0x3c, 0x6c, 0xcc, 0xcc, 0xcc, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0xc6, 0xfe, 0xc0, 0xc0, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x38, 0x6c, 0x64, 0x60, 0xf0, 0x60, 0x60, 0x60, 0x60, 0xf0, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0x7c, 0x0c, 0xcc, 0x78, 0x00,
+ 0x00, 0x00, 0xe0, 0x60, 0x60, 0x6c, 0x76, 0x66, 0x66, 0x66, 0x66, 0xe6, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x18, 0x18, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x06, 0x06, 0x00, 0x0e, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x66, 0x66, 0x3c, 0x00,
+ 0x00, 0x00, 0xe0, 0x60, 0x60, 0x66, 0x6c, 0x78, 0x78, 0x6c, 0x66, 0xe6, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0xe6, 0xff, 0xdb, 0xdb, 0xdb, 0xdb, 0xdb, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0xdc, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0xdc, 0x66, 0x66, 0x66, 0x66, 0x66, 0x7c, 0x60, 0x60, 0xf0, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0x7c, 0x0c, 0x0c, 0x1e, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0xdc, 0x76, 0x66, 0x60, 0x60, 0x60, 0xf0, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0xc6, 0x60, 0x38, 0x0c, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x10, 0x30, 0x30, 0xfc, 0x30, 0x30, 0x30, 0x30, 0x36, 0x1c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0xc3, 0xc3, 0xc3, 0xc3, 0x66, 0x3c, 0x18, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0xc3, 0xc3, 0xc3, 0xdb, 0xdb, 0xff, 0x66, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0xc3, 0x66, 0x3c, 0x18, 0x3c, 0x66, 0xc3, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x7e, 0x06, 0x0c, 0xf8, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0xcc, 0x18, 0x30, 0x60, 0xc6, 0xfe, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x0e, 0x18, 0x18, 0x18, 0x70, 0x18, 0x18, 0x18, 0x18, 0x0e, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x70, 0x18, 0x18, 0x18, 0x0e, 0x18, 0x18, 0x18, 0x18, 0x70, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x76, 0xdc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x6c, 0xc6, 0xc6, 0xc6, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x3c, 0x66, 0xc2, 0xc0, 0xc0, 0xc0, 0xc2, 0x66, 0x3c, 0x0c, 0x06, 0x7c, 0x00, 0x00,
+ 0x00, 0x00, 0xcc, 0x00, 0x00, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x0c, 0x18, 0x30, 0x00, 0x7c, 0xc6, 0xfe, 0xc0, 0xc0, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x10, 0x38, 0x6c, 0x00, 0x78, 0x0c, 0x7c, 0xcc, 0xcc, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0xcc, 0x00, 0x00, 0x78, 0x0c, 0x7c, 0xcc, 0xcc, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x60, 0x30, 0x18, 0x00, 0x78, 0x0c, 0x7c, 0xcc, 0xcc, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x38, 0x6c, 0x38, 0x00, 0x78, 0x0c, 0x7c, 0xcc, 0xcc, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x3c, 0x66, 0x60, 0x60, 0x66, 0x3c, 0x0c, 0x06, 0x3c, 0x00, 0x00, 0x00,
+ 0x00, 0x10, 0x38, 0x6c, 0x00, 0x7c, 0xc6, 0xfe, 0xc0, 0xc0, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0xc6, 0x00, 0x00, 0x7c, 0xc6, 0xfe, 0xc0, 0xc0, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x60, 0x30, 0x18, 0x00, 0x7c, 0xc6, 0xfe, 0xc0, 0xc0, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x66, 0x00, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x18, 0x3c, 0x66, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x60, 0x30, 0x18, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0xc6, 0x00, 0x10, 0x38, 0x6c, 0xc6, 0xc6, 0xfe, 0xc6, 0xc6, 0xc6, 0x00, 0x00, 0x00, 0x00,
+ 0x38, 0x6c, 0x38, 0x00, 0x38, 0x6c, 0xc6, 0xc6, 0xfe, 0xc6, 0xc6, 0xc6, 0x00, 0x00, 0x00, 0x00,
+ 0x18, 0x30, 0x60, 0x00, 0xfe, 0x66, 0x60, 0x7c, 0x60, 0x60, 0x66, 0xfe, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x6e, 0x3b, 0x1b, 0x7e, 0xd8, 0xdc, 0x77, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x3e, 0x6c, 0xcc, 0xcc, 0xfe, 0xcc, 0xcc, 0xcc, 0xcc, 0xce, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x10, 0x38, 0x6c, 0x00, 0x7c, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0xc6, 0x00, 0x00, 0x7c, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x60, 0x30, 0x18, 0x00, 0x7c, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x30, 0x78, 0xcc, 0x00, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x60, 0x30, 0x18, 0x00, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0xc6, 0x00, 0x00, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x7e, 0x06, 0x0c, 0x78, 0x00,
+ 0x00, 0xc6, 0x00, 0x7c, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0xc6, 0x00, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x18, 0x18, 0x7e, 0xc3, 0xc0, 0xc0, 0xc0, 0xc3, 0x7e, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x38, 0x6c, 0x64, 0x60, 0xf0, 0x60, 0x60, 0x60, 0x60, 0xe6, 0xfc, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0xc3, 0x66, 0x3c, 0x18, 0xff, 0x18, 0xff, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0xfc, 0x66, 0x66, 0x7c, 0x62, 0x66, 0x6f, 0x66, 0x66, 0x66, 0xf3, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x0e, 0x1b, 0x18, 0x18, 0x18, 0x7e, 0x18, 0x18, 0x18, 0x18, 0x18, 0xd8, 0x70, 0x00, 0x00,
+ 0x00, 0x18, 0x30, 0x60, 0x00, 0x78, 0x0c, 0x7c, 0xcc, 0xcc, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x0c, 0x18, 0x30, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x18, 0x30, 0x60, 0x00, 0x7c, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x18, 0x30, 0x60, 0x00, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x76, 0xdc, 0x00, 0xdc, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x00, 0x00, 0x00, 0x00,
+ 0x76, 0xdc, 0x00, 0xc6, 0xe6, 0xf6, 0xfe, 0xde, 0xce, 0xc6, 0xc6, 0xc6, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x3c, 0x6c, 0x6c, 0x3e, 0x00, 0x7e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x38, 0x6c, 0x6c, 0x38, 0x00, 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x30, 0x30, 0x00, 0x30, 0x30, 0x60, 0xc0, 0xc6, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0xc0, 0xc0, 0xc0, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x06, 0x06, 0x06, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0xc0, 0xc0, 0xc2, 0xc6, 0xcc, 0x18, 0x30, 0x60, 0xce, 0x9b, 0x06, 0x0c, 0x1f, 0x00, 0x00,
+ 0x00, 0xc0, 0xc0, 0xc2, 0xc6, 0xcc, 0x18, 0x30, 0x66, 0xce, 0x96, 0x3e, 0x06, 0x06, 0x00, 0x00,
+ 0x00, 0x00, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x3c, 0x3c, 0x3c, 0x18, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x36, 0x6c, 0xd8, 0x6c, 0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0xd8, 0x6c, 0x36, 0x6c, 0xd8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44,
+ 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa,
+ 0xdd, 0x77, 0xdd, 0x77, 0xdd, 0x77, 0xdd, 0x77, 0xdd, 0x77, 0xdd, 0x77, 0xdd, 0x77, 0xdd, 0x77,
+ 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
+ 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xf8, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
+ 0x18, 0x18, 0x18, 0x18, 0x18, 0xf8, 0x18, 0xf8, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
+ 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xf6, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x18, 0xf8, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
+ 0x36, 0x36, 0x36, 0x36, 0x36, 0xf6, 0x06, 0xf6, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
+ 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x06, 0xf6, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
+ 0x36, 0x36, 0x36, 0x36, 0x36, 0xf6, 0x06, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x18, 0x18, 0x18, 0x18, 0x18, 0xf8, 0x18, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
+ 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
+ 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1f, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xff, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
+ 0x18, 0x18, 0x18, 0x18, 0x18, 0x1f, 0x18, 0x1f, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
+ 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x37, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
+ 0x36, 0x36, 0x36, 0x36, 0x36, 0x37, 0x30, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x30, 0x37, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
+ 0x36, 0x36, 0x36, 0x36, 0x36, 0xf7, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0xf7, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
+ 0x36, 0x36, 0x36, 0x36, 0x36, 0x37, 0x30, 0x37, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x36, 0x36, 0x36, 0x36, 0x36, 0xf7, 0x00, 0xf7, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
+ 0x18, 0x18, 0x18, 0x18, 0x18, 0xff, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0xff, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
+ 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x18, 0x18, 0x18, 0x18, 0x18, 0x1f, 0x18, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, 0x18, 0x1f, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
+ 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xff, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
+ 0x18, 0x18, 0x18, 0x18, 0x18, 0xff, 0x18, 0xff, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
+ 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
+ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+ 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0,
+ 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f,
+ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xdc, 0xd8, 0xd8, 0xd8, 0xdc, 0x76, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x78, 0xcc, 0xcc, 0xcc, 0xd8, 0xcc, 0xc6, 0xc6, 0xc6, 0xcc, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0xfe, 0xc6, 0xc6, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0xfe, 0x6c, 0x6c, 0x6c, 0x6c, 0x6c, 0x6c, 0x6c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0xfe, 0xc6, 0x60, 0x30, 0x18, 0x30, 0x60, 0xc6, 0xfe, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x7e, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0x70, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x7c, 0x60, 0x60, 0xc0, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x76, 0xdc, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x7e, 0x18, 0x3c, 0x66, 0x66, 0x66, 0x3c, 0x18, 0x7e, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x38, 0x6c, 0xc6, 0xc6, 0xfe, 0xc6, 0xc6, 0x6c, 0x38, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x38, 0x6c, 0xc6, 0xc6, 0xc6, 0x6c, 0x6c, 0x6c, 0x6c, 0xee, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x1e, 0x30, 0x18, 0x0c, 0x3e, 0x66, 0x66, 0x66, 0x66, 0x3c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x7e, 0xdb, 0xdb, 0xdb, 0x7e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x03, 0x06, 0x7e, 0xdb, 0xdb, 0xf3, 0x7e, 0x60, 0xc0, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x1c, 0x30, 0x60, 0x60, 0x7c, 0x60, 0x60, 0x60, 0x30, 0x1c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x7c, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0xfe, 0x00, 0x00, 0xfe, 0x00, 0x00, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x7e, 0x18, 0x18, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x30, 0x18, 0x0c, 0x06, 0x0c, 0x18, 0x30, 0x00, 0x7e, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x0c, 0x18, 0x30, 0x60, 0x30, 0x18, 0x0c, 0x00, 0x7e, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x0e, 0x1b, 0x1b, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
+ 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xd8, 0xd8, 0xd8, 0x70, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x7e, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xdc, 0x00, 0x76, 0xdc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x38, 0x6c, 0x6c, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x0f, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0xec, 0x6c, 0x6c, 0x3c, 0x1c, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0xd8, 0x6c, 0x6c, 0x6c, 0x6c, 0x6c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x70, 0xd8, 0x30, 0x60, 0xc8, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x7c, 0x7c, 0x7c, 0x7c, 0x7c, 0x7c, 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
+};
+
 const uint32_t ff_cga_palette[16] = {
     0x000000, 0x0000AA, 0x00AA00, 0x00AAAA, 0xAA0000, 0xAA00AA, 0xAA5500, 0xAAAAAA,
     0x555555, 0x5555FF, 0x55FF55, 0x55FFFF, 0xFF5555, 0xFF55FF, 0xFFFF55, 0xFFFFFF,
 };
+
+const uint32_t ff_ega_palette[64] = {
+    0x000000, 0x0000AA, 0x00AA00, 0x00AAAA, 0xAA0000, 0xAA00AA, 0xAAAA00, 0xAAAAAA,
+    0x000055, 0x0000FF, 0x00AA55, 0x00AAFF, 0xAA0055, 0xAA00FF, 0xAAAA55, 0xAAAAFF,
+    0x005500, 0x0055AA, 0x00FF00, 0x00FFAA, 0xAA5500, 0xAA55AA, 0xAAFF00, 0xAAFFAA,
+    0x005555, 0x0055FF, 0x00FF55, 0x00FFFF, 0xAA5555, 0xAA55FF, 0xAAFF55, 0xAAFFFF,
+    0x550000, 0x5500AA, 0x55AA00, 0x55AAAA, 0xFF0000, 0xFF00AA, 0xFFAA00, 0xFFAAAA,
+    0x550055, 0x5500FF, 0x55AA55, 0x55AAFF, 0xFF0055, 0xFF00FF, 0xFFAA55, 0xFFAAFF,
+    0x555500, 0x5555AA, 0x55FF00, 0x55FFAA, 0xFF5500, 0xFF55AA, 0xFFFF00, 0xFFFFAA,
+    0x555555, 0x5555FF, 0x55FF55, 0x55FFFF, 0xFF5555, 0xFF55FF, 0xFFFF55, 0xFFFFFF
+};
+
+void ff_draw_pc_font(uint8_t *dst, int linesize, const uint8_t *font, int font_height, int ch, int fg, int bg)
+{
+    int char_y, mask;
+    for (char_y = 0; char_y < font_height; char_y++) {
+        for (mask = 0x80; mask; mask >>= 1) {
+            *dst++ = font[ch * font_height + char_y] & mask ? fg : bg;
+        }
+        dst += linesize - 8;
+    }
+}
diff --git a/libavcodec/cga_data.h b/libavcodec/cga_data.h
index c3f69f1..60f572f 100644
--- a/libavcodec/cga_data.h
+++ b/libavcodec/cga_data.h
@@ -1,29 +1,48 @@
 /*
- * CGA ROM data
+ * CGA/EGA/VGA ROM data
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+/**
+ * @file
+ * CGA/EGA/VGA ROM data
+ */
+
 #ifndef AVCODEC_CGA_DATA_H
 #define AVCODEC_CGA_DATA_H
 
 #include <stdint.h>
 
 extern const uint8_t ff_cga_font[2048];
+extern const uint8_t ff_vga16_font[4096];
 extern const uint32_t ff_cga_palette[16];
+extern const uint32_t ff_ega_palette[64];
+
+/**
+ * Draw CGA/EGA/VGA font to 8-bit pixel buffer
+ *
+ * @param dst Destination pixel buffer
+ * @param linesize Linesize (pixels)
+ * @param font Font table. We assume font width is always 8 pixels wide.
+ * @param font_height Font height (pixels)
+ * @param fg,bg Foreground and background palette index
+ * @param ch Character to draw
+ */
+void ff_draw_pc_font(uint8_t *dst, int linesize, const uint8_t *font, int font_height, int ch, int fg, int bg);
 
 #endif
diff --git a/libavcodec/chomp_bsf.c b/libavcodec/chomp_bsf.c
new file mode 100644
index 0000000..9ed7496
--- /dev/null
+++ b/libavcodec/chomp_bsf.c
@@ -0,0 +1,47 @@
+/*
+ * Chomp bitstream filter
+ * Copyright (c) 2010 Alex Converse <alex.converse at gmail.com>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "avcodec.h"
+#include "internal.h"
+
+static int chomp_filter(AVBitStreamFilterContext *bsfc,
+                        AVCodecContext *avctx, const char *args,
+                        uint8_t  **poutbuf, int *poutbuf_size,
+                        const uint8_t *buf, int      buf_size,
+                        int keyframe)
+{
+    while (buf_size > 0 && !buf[buf_size-1])
+        buf_size--;
+
+    *poutbuf = (uint8_t*) buf;
+    *poutbuf_size = buf_size;
+
+    return 0;
+}
+
+/**
+ * This filter removes a string of NULL bytes from the end of a packet.
+ */
+AVBitStreamFilter ff_chomp_bsf = {
+    "chomp",
+    0,
+    chomp_filter,
+};
diff --git a/libavcodec/cinepak.c b/libavcodec/cinepak.c
index 8e7aa5a..4bda2a7 100644
--- a/libavcodec/cinepak.c
+++ b/libavcodec/cinepak.c
@@ -2,20 +2,20 @@
  * Cinepak Video Decoder
  * Copyright (C) 2003 the ffmpeg project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -67,6 +67,7 @@ typedef struct CinepakContext {
 
     int sega_film_skip_bytes;
 
+    uint32_t pal[256];
 } CinepakContext;
 
 static void cinepak_decode_codebook (cvid_codebook *codebook,
@@ -395,7 +396,7 @@ static av_cold int cinepak_decode_init(AVCodecContext *avctx)
     s->sega_film_skip_bytes = -1;  /* uninitialized state */
 
     // check for paletted data
-    if ((avctx->palctrl == NULL) || (avctx->bits_per_coded_sample == 40)) {
+    if (avctx->bits_per_coded_sample != 8) {
         s->palette_video = 0;
         avctx->pix_fmt = PIX_FMT_YUV420P;
     } else {
@@ -427,17 +428,19 @@ static int cinepak_decode_frame(AVCodecContext *avctx,
         return -1;
     }
 
-    cinepak_decode(s);
-
     if (s->palette_video) {
-        memcpy (s->frame.data[1], avctx->palctrl->palette, AVPALETTE_SIZE);
-        if (avctx->palctrl->palette_changed) {
+        const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, NULL);
+        if (pal) {
             s->frame.palette_has_changed = 1;
-            avctx->palctrl->palette_changed = 0;
-        } else
-            s->frame.palette_has_changed = 0;
+            memcpy(s->pal, pal, AVPALETTE_SIZE);
+        }
     }
 
+    cinepak_decode(s);
+
+    if (s->palette_video)
+        memcpy (s->frame.data[1], s->pal, AVPALETTE_SIZE);
+
     *data_size = sizeof(AVFrame);
     *(AVFrame*)data = s->frame;
 
@@ -455,7 +458,7 @@ static av_cold int cinepak_decode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec cinepak_decoder = {
+AVCodec ff_cinepak_decoder = {
     "cinepak",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_CINEPAK,
diff --git a/libavcodec/cljr.c b/libavcodec/cljr.c
index 47809c0..1da4d3b 100644
--- a/libavcodec/cljr.c
+++ b/libavcodec/cljr.c
@@ -2,20 +2,20 @@
  * Cirrus Logic AccuPak (CLJR) codec
  * Copyright (c) 2003 Alex Beregszaszi
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -54,6 +54,11 @@ static int decode_frame(AVCodecContext *avctx,
     if(p->data[0])
         avctx->release_buffer(avctx, p);
 
+    if(buf_size/avctx->height < avctx->width) {
+        av_log(avctx, AV_LOG_ERROR, "Resolution larger than buffer size. Invalid header?\n");
+        return -1;
+    }
+
     p->reference= 0;
     if(avctx->get_buffer(avctx, p) < 0){
         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
@@ -135,7 +140,7 @@ static av_cold int encode_init(AVCodecContext *avctx){
 }
 #endif
 
-AVCodec cljr_decoder = {
+AVCodec ff_cljr_decoder = {
     "cljr",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_CLJR,
@@ -149,7 +154,7 @@ AVCodec cljr_decoder = {
 };
 
 #if CONFIG_CLJR_ENCODER
-AVCodec cljr_encoder = {
+AVCodec ff_cljr_encoder = {
     "cljr",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_CLJR,
diff --git a/libavcodec/colorspace.h b/libavcodec/colorspace.h
deleted file mode 100644
index 4ec081e..0000000
--- a/libavcodec/colorspace.h
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * Colorspace conversion defines
- * Copyright (c) 2001, 2002, 2003 Fabrice Bellard
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-/**
- * @file
- * Various defines for YUV<->RGB conversion
- */
-
-#ifndef AVCODEC_COLORSPACE_H
-#define AVCODEC_COLORSPACE_H
-
-#define SCALEBITS 10
-#define ONE_HALF  (1 << (SCALEBITS - 1))
-#define FIX(x)    ((int) ((x) * (1<<SCALEBITS) + 0.5))
-
-#define YUV_TO_RGB1_CCIR(cb1, cr1)\
-{\
-    cb = (cb1) - 128;\
-    cr = (cr1) - 128;\
-    r_add = FIX(1.40200*255.0/224.0) * cr + ONE_HALF;\
-    g_add = - FIX(0.34414*255.0/224.0) * cb - FIX(0.71414*255.0/224.0) * cr + \
-            ONE_HALF;\
-    b_add = FIX(1.77200*255.0/224.0) * cb + ONE_HALF;\
-}
-
-#define YUV_TO_RGB2_CCIR(r, g, b, y1)\
-{\
-    y = ((y1) - 16) * FIX(255.0/219.0);\
-    r = cm[(y + r_add) >> SCALEBITS];\
-    g = cm[(y + g_add) >> SCALEBITS];\
-    b = cm[(y + b_add) >> SCALEBITS];\
-}
-
-#define YUV_TO_RGB1(cb1, cr1)\
-{\
-    cb = (cb1) - 128;\
-    cr = (cr1) - 128;\
-    r_add = FIX(1.40200) * cr + ONE_HALF;\
-    g_add = - FIX(0.34414) * cb - FIX(0.71414) * cr + ONE_HALF;\
-    b_add = FIX(1.77200) * cb + ONE_HALF;\
-}
-
-#define YUV_TO_RGB2(r, g, b, y1)\
-{\
-    y = (y1) << SCALEBITS;\
-    r = cm[(y + r_add) >> SCALEBITS];\
-    g = cm[(y + g_add) >> SCALEBITS];\
-    b = cm[(y + b_add) >> SCALEBITS];\
-}
-
-#define Y_CCIR_TO_JPEG(y)\
- cm[((y) * FIX(255.0/219.0) + (ONE_HALF - 16 * FIX(255.0/219.0))) >> SCALEBITS]
-
-#define Y_JPEG_TO_CCIR(y)\
- (((y) * FIX(219.0/255.0) + (ONE_HALF + (16 << SCALEBITS))) >> SCALEBITS)
-
-#define C_CCIR_TO_JPEG(y)\
- cm[(((y) - 128) * FIX(127.0/112.0) + (ONE_HALF + (128 << SCALEBITS))) >> SCALEBITS]
-
-/* NOTE: the clamp is really necessary! */
-static inline int C_JPEG_TO_CCIR(int y) {
-    y = (((y - 128) * FIX(112.0/127.0) + (ONE_HALF + (128 << SCALEBITS))) >> SCALEBITS);
-    if (y < 16)
-        y = 16;
-    return y;
-}
-
-
-#define RGB_TO_Y(r, g, b) \
-((FIX(0.29900) * (r) + FIX(0.58700) * (g) + \
-  FIX(0.11400) * (b) + ONE_HALF) >> SCALEBITS)
-
-#define RGB_TO_U(r1, g1, b1, shift)\
-(((- FIX(0.16874) * r1 - FIX(0.33126) * g1 +         \
-     FIX(0.50000) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
-
-#define RGB_TO_V(r1, g1, b1, shift)\
-(((FIX(0.50000) * r1 - FIX(0.41869) * g1 -           \
-   FIX(0.08131) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
-
-#define RGB_TO_Y_CCIR(r, g, b) \
-((FIX(0.29900*219.0/255.0) * (r) + FIX(0.58700*219.0/255.0) * (g) + \
-  FIX(0.11400*219.0/255.0) * (b) + (ONE_HALF + (16 << SCALEBITS))) >> SCALEBITS)
-
-#define RGB_TO_U_CCIR(r1, g1, b1, shift)\
-(((- FIX(0.16874*224.0/255.0) * r1 - FIX(0.33126*224.0/255.0) * g1 +         \
-     FIX(0.50000*224.0/255.0) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
-
-#define RGB_TO_V_CCIR(r1, g1, b1, shift)\
-(((FIX(0.50000*224.0/255.0) * r1 - FIX(0.41869*224.0/255.0) * g1 -           \
-   FIX(0.08131*224.0/255.0) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
-
-#endif /* AVCODEC_COLORSPACE_H */
diff --git a/libavcodec/cook.c b/libavcodec/cook.c
index e406e65..7717c4b 100644
--- a/libavcodec/cook.c
+++ b/libavcodec/cook.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2003 Sascha Sommer
  * Copyright (c) 2005 Benjamin Larsson
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -53,6 +53,8 @@
 #include "dsputil.h"
 #include "bytestream.h"
 #include "fft.h"
+#include "libavutil/audioconvert.h"
+#include "sinewin.h"
 
 #include "cookdata.h"
 
@@ -284,6 +286,9 @@ static av_cold void init_cplscales_table (COOKContext *q) {
 
 /*************** init functions end ***********/
 
+#define DECODE_BYTES_PAD1(bytes) (3 - ((bytes)+3) % 4)
+#define DECODE_BYTES_PAD2(bytes) ((bytes) % 4 + DECODE_BYTES_PAD1(2 * (bytes)))
+
 /**
  * Cook indata decoding, every 32 bits are XORed with 0x37c511f2.
  * Why? No idea, some checksum/error detection method maybe.
@@ -304,8 +309,6 @@ static av_cold void init_cplscales_table (COOKContext *q) {
  * @param out       pointer to byte array of outdata
  * @param bytes     number of bytes
  */
-#define DECODE_BYTES_PAD1(bytes) (3 - ((bytes)+3) % 4)
-#define DECODE_BYTES_PAD2(bytes) ((bytes) % 4 + DECODE_BYTES_PAD1(2 * (bytes)))
 
 static inline int decode_bytes(const uint8_t* inbuffer, uint8_t* out, int bytes){
     int i, off;
@@ -315,12 +318,12 @@ static inline int decode_bytes(const uint8_t* inbuffer, uint8_t* out, int bytes)
     /* FIXME: 64 bit platforms would be able to do 64 bits at a time.
      * I'm too lazy though, should be something like
      * for(i=0 ; i<bitamount/64 ; i++)
-     *     (int64_t)out[i] = 0x37c511f237c511f2^be2me_64(int64_t)in[i]);
+     *     (int64_t)out[i] = 0x37c511f237c511f2^av_be2ne64(int64_t)in[i]);
      * Buffer alignment needs to be checked. */
 
     off = (intptr_t)inbuffer & 3;
     buf = (const uint32_t*) (inbuffer - off);
-    c = be2me_32((0x37c511f2 >> (off*8)) | (0x37c511f2 << (32-(off*8))));
+    c = av_be2ne32((0x37c511f2 >> (off*8)) | (0x37c511f2 << (32-(off*8))));
     bytes += 3 + off;
     for (i = 0; i < bytes/4; i++)
         obuf[i] = c ^ buf[i];
@@ -364,8 +367,8 @@ static av_cold int cook_decode_close(AVCodecContext *avctx)
 /**
  * Fill the gain array for the timedomain quantization.
  *
- * @param q                 pointer to the COOKContext
- * @param gaininfo[9]       array of gain indexes
+ * @param gb          pointer to the GetBitContext
+ * @param gaininfo[9] array of gain indexes
  */
 
 static void decode_gain_info(GetBitContext *gb, int *gaininfo)
@@ -713,7 +716,7 @@ static void interpolate_float(COOKContext *q, float* buffer,
  * @param previous_buffer   pointer to the previous buffer to be used for overlapping
  */
 
-static void imlt_window_float (COOKContext *q, float *buffer1,
+static void imlt_window_float (COOKContext *q, float *inbuffer,
                                cook_gains *gains_ptr, float *previous_buffer)
 {
     const float fc = pow2tab[gains_ptr->previous[0] + 63];
@@ -726,7 +729,7 @@ static void imlt_window_float (COOKContext *q, float *buffer1,
 
     /* Apply window and overlap */
     for(i = 0; i < q->samples_per_channel; i++){
-        buffer1[i] = buffer1[i] * fc * q->mlt_window[i] -
+        inbuffer[i] = inbuffer[i] * fc * q->mlt_window[i] -
           previous_buffer[i] * q->mlt_window[q->samples_per_channel - 1 - i];
     }
 }
@@ -751,7 +754,7 @@ static void imlt_gain(COOKContext *q, float *inbuffer,
     int i;
 
     /* Inverse modified discrete cosine transform */
-    ff_imdct_calc(&q->mdct_ctx, q->mono_mdct_output, inbuffer);
+    q->mdct_ctx.imdct_calc(&q->mdct_ctx, q->mono_mdct_output, inbuffer);
 
     q->imlt_window (q, buffer1, gains_ptr, previous_buffer);
 
@@ -877,7 +880,7 @@ static void joint_decode(COOKContext *q, COOKSubpacket *p, float* mlt_buffer1,
  *
  * @param q                 pointer to the COOKContext
  * @param inbuffer          pointer to raw stream data
- * @param gain_ptr          array of current/prev gain pointers
+ * @param gains_ptr         array of current/prev gain pointers
  */
 
 static inline void
@@ -923,7 +926,7 @@ saturate_output_float (COOKContext *q, int chan, int16_t *out)
  *
  * @param q                 pointer to the COOKContext
  * @param decode_buffer     pointer to the mlt coefficients
- * @param gain_ptr          array of current/prev gain pointers
+ * @param gains_ptr         array of current/prev gain pointers
  * @param previous_buffer   pointer to the previous buffer to be used for overlapping
  * @param out               pointer to the output buffer
  * @param chan              0: left or single channel, 1: right channel
@@ -931,10 +934,10 @@ saturate_output_float (COOKContext *q, int chan, int16_t *out)
 
 static inline void
 mlt_compensate_output(COOKContext *q, float *decode_buffer,
-                      cook_gains *gains, float *previous_buffer,
+                      cook_gains *gains_ptr, float *previous_buffer,
                       int16_t *out, int chan)
 {
-    imlt_gain(q, decode_buffer, gains, previous_buffer);
+    imlt_gain(q, decode_buffer, gains_ptr, previous_buffer);
     q->saturate_output (q, chan, out);
 }
 
@@ -945,11 +948,8 @@ mlt_compensate_output(COOKContext *q, float *decode_buffer,
  *
  * @param q                 pointer to the COOKContext
  * @param inbuffer          pointer to the inbuffer
- * @param sub_packet_size   subpacket size
  * @param outbuffer         pointer to the outbuffer
  */
-
-
 static void decode_subpacket(COOKContext *q, COOKSubpacket* p, const uint8_t *inbuffer, int16_t *outbuffer) {
     int sub_packet_size = p->size;
     /* packet dump */
@@ -1272,11 +1272,11 @@ static av_cold int cook_decode_init(AVCodecContext *avctx)
         return -1;
     }
 
-    avctx->sample_fmt = SAMPLE_FMT_S16;
+    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
     if (channel_mask)
         avctx->channel_layout = channel_mask;
     else
-        avctx->channel_layout = (avctx->channels==2) ? CH_LAYOUT_STEREO : CH_LAYOUT_MONO;
+        avctx->channel_layout = (avctx->channels==2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;
 
 #ifdef COOKDEBUG
     dump_cook_context(q);
@@ -1285,7 +1285,7 @@ static av_cold int cook_decode_init(AVCodecContext *avctx)
 }
 
 
-AVCodec cook_decoder =
+AVCodec ff_cook_decoder =
 {
     .name = "cook",
     .type = AVMEDIA_TYPE_AUDIO,
diff --git a/libavcodec/cookdata.h b/libavcodec/cookdata.h
index 15e8e95..e8d6ebf 100644
--- a/libavcodec/cookdata.h
+++ b/libavcodec/cookdata.h
@@ -3,20 +3,20 @@
  * Copyright (c) 2003 Sascha Sommer
  * Copyright (c) 2005 Benjamin Larsson
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/costablegen.c b/libavcodec/costablegen.c
index bfcd635..65c4926 100644
--- a/libavcodec/costablegen.c
+++ b/libavcodec/costablegen.c
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2009 Reimar Döffinger <Reimar.Doeffinger at gmx.de>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -29,15 +29,34 @@
 #endif
 #define BITS 16
 #define FLOATFMT "%.18e"
+#define FIXEDFMT "%6d"
+
+static int clip_f15(int v)
+{
+    return v < -32767 ? -32767 :
+           v >  32767 ?  32767 :
+           v;
+}
+
+static void printval(double val, int fixed)
+{
+    if (fixed)
+        printf(" "FIXEDFMT",", clip_f15(lrint(val * (double)(1<<15))));
+    else
+        printf(" "FLOATFMT",", val);
+
+}
 
 int main(int argc, char *argv[])
 {
     int i, j;
-    int do_sin = argc == 2 && !strcmp(argv[1], "sin");
+    int do_sin = argc > 1 && !strcmp(argv[1], "sin");
+    int fixed  = argc > 2 && !strcmp(argv[2], "fixed");
     double (*func)(double) = do_sin ? sin : cos;
 
     printf("/* This file was generated by libavcodec/costablegen */\n");
-    printf("#include \"libavcodec/fft.h\"\n");
+    printf("#define CONFIG_FFT_FLOAT %d\n", !fixed);
+    printf("#include \"libavcodec/%s\"\n", do_sin ? "rdft.h" : "fft.h");
     for (i = 4; i <= BITS; i++) {
         int m = 1 << i;
         double freq = 2*M_PI/m;
@@ -46,11 +65,12 @@ int main(int argc, char *argv[])
             int idx = j > m/4 ? m/2 - j : j;
             if (do_sin && j >= m/4)
                 idx = m/4 - j;
-            printf(" "FLOATFMT",", func(idx*freq));
+            printval(func(idx*freq), fixed);
             if ((j & 3) == 3)
                 printf("\n   ");
         }
-        printf(" "FLOATFMT"\n};\n", func(do_sin ? -(m/4 - 1)*freq : freq));
+        printval(func(do_sin ? -(m/4 - 1)*freq : freq), fixed);
+        printf("\n};\n");
     }
     return 0;
 }
diff --git a/libavcodec/cscd.c b/libavcodec/cscd.c
index e4f4b8f..6e55c18 100644
--- a/libavcodec/cscd.c
+++ b/libavcodec/cscd.c
@@ -2,20 +2,20 @@
  * CamStudio decoder
  * Copyright (c) 2006 Reimar Doeffinger
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #include <stdio.h>
@@ -35,19 +35,19 @@ typedef struct {
     unsigned char* decomp_buf;
 } CamStudioContext;
 
-static void copy_frame_default(AVFrame *f, const uint8_t *src,
+static void copy_frame_default(AVFrame *f, const uint8_t *src, int src_stride,
                                int linelen, int height) {
     int i;
     uint8_t *dst = f->data[0];
     dst += (height - 1) * f->linesize[0];
     for (i = height; i; i--) {
         memcpy(dst, src, linelen);
-        src += linelen;
+        src += src_stride;
         dst -= f->linesize[0];
     }
 }
 
-static void add_frame_default(AVFrame *f, const uint8_t *src,
+static void add_frame_default(AVFrame *f, const uint8_t *src, int src_stride,
                               int linelen, int height) {
     int i, j;
     uint8_t *dst = f->data[0];
@@ -55,15 +55,16 @@ static void add_frame_default(AVFrame *f, const uint8_t *src,
     for (i = height; i; i--) {
         for (j = linelen; j; j--)
             *dst++ += *src++;
+        src += src_stride - linelen;
         dst -= f->linesize[0] + linelen;
     }
 }
 
 #if !HAVE_BIGENDIAN
-#define copy_frame_16 copy_frame_default
-#define copy_frame_32 copy_frame_default
-#define add_frame_16 add_frame_default
-#define add_frame_32 add_frame_default
+#define copy_frame_16(f, s, l, h) copy_frame_default(f, s, l, l, h)
+#define copy_frame_32(f, s, l, h) copy_frame_default(f, s, l, l, h)
+#define add_frame_16(f, s, l, h) add_frame_default(f, s, l, l, h)
+#define add_frame_32(f, s, l, h) add_frame_default(f, s, l, l, h)
 #else
 static void copy_frame_16(AVFrame *f, const uint8_t *src,
                           int linelen, int height) {
@@ -192,7 +193,8 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *data_size,
               copy_frame_32(&c->pic, c->decomp_buf, c->linelen, c->height);
               break;
           default:
-              copy_frame_default(&c->pic, c->decomp_buf, c->linelen, c->height);
+              copy_frame_default(&c->pic, c->decomp_buf, FFALIGN(c->linelen, 4),
+                                 c->linelen, c->height);
         }
     } else {
         c->pic.pict_type = FF_P_TYPE;
@@ -205,7 +207,8 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *data_size,
               add_frame_32(&c->pic, c->decomp_buf, c->linelen, c->height);
               break;
           default:
-              add_frame_default(&c->pic, c->decomp_buf, c->linelen, c->height);
+              add_frame_default(&c->pic, c->decomp_buf, FFALIGN(c->linelen, 4),
+                                c->linelen, c->height);
         }
     }
 
@@ -216,6 +219,7 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *data_size,
 
 static av_cold int decode_init(AVCodecContext *avctx) {
     CamStudioContext *c = avctx->priv_data;
+    int stride;
     switch (avctx->bits_per_coded_sample) {
         case 16: avctx->pix_fmt = PIX_FMT_RGB555; break;
         case 24: avctx->pix_fmt = PIX_FMT_BGR24; break;
@@ -224,13 +228,16 @@ static av_cold int decode_init(AVCodecContext *avctx) {
             av_log(avctx, AV_LOG_ERROR,
                    "CamStudio codec error: invalid depth %i bpp\n",
                    avctx->bits_per_coded_sample);
-             return 1;
+            return 1;
     }
     c->bpp = avctx->bits_per_coded_sample;
     c->pic.data[0] = NULL;
     c->linelen = avctx->width * avctx->bits_per_coded_sample / 8;
     c->height = avctx->height;
-    c->decomp_size = c->height * c->linelen;
+    stride = c->linelen;
+    if (avctx->bits_per_coded_sample == 24)
+        stride = FFALIGN(stride, 4);
+    c->decomp_size = c->height * stride;
     c->decomp_buf = av_malloc(c->decomp_size + AV_LZO_OUTPUT_PADDING);
     if (!c->decomp_buf) {
         av_log(avctx, AV_LOG_ERROR, "Can't allocate decompression buffer.\n");
@@ -247,7 +254,7 @@ static av_cold int decode_end(AVCodecContext *avctx) {
     return 0;
 }
 
-AVCodec cscd_decoder = {
+AVCodec ff_cscd_decoder = {
     "camstudio",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_CSCD,
diff --git a/libavcodec/cyuv.c b/libavcodec/cyuv.c
index db7e690..ecdec17 100644
--- a/libavcodec/cyuv.c
+++ b/libavcodec/cyuv.c
@@ -6,20 +6,20 @@
  *
  * Copyright (C) 2003 the ffmpeg project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -178,7 +178,7 @@ static av_cold int cyuv_decode_end(AVCodecContext *avctx)
 }
 
 #if CONFIG_AURA_DECODER
-AVCodec aura_decoder = {
+AVCodec ff_aura_decoder = {
     "aura",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_AURA,
@@ -194,7 +194,7 @@ AVCodec aura_decoder = {
 #endif
 
 #if CONFIG_CYUV_DECODER
-AVCodec cyuv_decoder = {
+AVCodec ff_cyuv_decoder = {
     "cyuv",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_CYUV,
diff --git a/libavcodec/dca.c b/libavcodec/dca.c
index 10bc956..e3c6466 100644
--- a/libavcodec/dca.c
+++ b/libavcodec/dca.c
@@ -5,20 +5,20 @@
  * Copyright (C) 2006 Benjamin Larsson
  * Copyright (C) 2007 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -26,8 +26,10 @@
 #include <stddef.h>
 #include <stdio.h>
 
+#include "libavutil/common.h"
 #include "libavutil/intmath.h"
 #include "libavutil/intreadwrite.h"
+#include "libavutil/audioconvert.h"
 #include "avcodec.h"
 #include "dsputil.h"
 #include "fft.h"
@@ -38,13 +40,16 @@
 #include "dca.h"
 #include "synth_filter.h"
 #include "dcadsp.h"
+#include "fmtconvert.h"
 
 //#define TRACE
 
-#define DCA_PRIM_CHANNELS_MAX (5)
+#define DCA_PRIM_CHANNELS_MAX (7)
 #define DCA_SUBBANDS (32)
 #define DCA_ABITS_MAX (32)      /* Should be 28 */
-#define DCA_SUBSUBFAMES_MAX (4)
+#define DCA_SUBSUBFRAMES_MAX (4)
+#define DCA_SUBFRAMES_MAX (16)
+#define DCA_BLOCKS_MAX (16)
 #define DCA_LFE_MAX (3)
 
 enum DCAMode {
@@ -61,6 +66,54 @@ enum DCAMode {
     DCA_4F2R
 };
 
+/* these are unconfirmed but should be mostly correct */
+enum DCAExSSSpeakerMask {
+    DCA_EXSS_FRONT_CENTER          = 0x0001,
+    DCA_EXSS_FRONT_LEFT_RIGHT      = 0x0002,
+    DCA_EXSS_SIDE_REAR_LEFT_RIGHT  = 0x0004,
+    DCA_EXSS_LFE                   = 0x0008,
+    DCA_EXSS_REAR_CENTER           = 0x0010,
+    DCA_EXSS_FRONT_HIGH_LEFT_RIGHT = 0x0020,
+    DCA_EXSS_REAR_LEFT_RIGHT       = 0x0040,
+    DCA_EXSS_FRONT_HIGH_CENTER     = 0x0080,
+    DCA_EXSS_OVERHEAD              = 0x0100,
+    DCA_EXSS_CENTER_LEFT_RIGHT     = 0x0200,
+    DCA_EXSS_WIDE_LEFT_RIGHT       = 0x0400,
+    DCA_EXSS_SIDE_LEFT_RIGHT       = 0x0800,
+    DCA_EXSS_LFE2                  = 0x1000,
+    DCA_EXSS_SIDE_HIGH_LEFT_RIGHT  = 0x2000,
+    DCA_EXSS_REAR_HIGH_CENTER      = 0x4000,
+    DCA_EXSS_REAR_HIGH_LEFT_RIGHT  = 0x8000,
+};
+
+enum DCAExtensionMask {
+    DCA_EXT_CORE       = 0x001, ///< core in core substream
+    DCA_EXT_XXCH       = 0x002, ///< XXCh channels extension in core substream
+    DCA_EXT_X96        = 0x004, ///< 96/24 extension in core substream
+    DCA_EXT_XCH        = 0x008, ///< XCh channel extension in core substream
+    DCA_EXT_EXSS_CORE  = 0x010, ///< core in ExSS (extension substream)
+    DCA_EXT_EXSS_XBR   = 0x020, ///< extended bitrate extension in ExSS
+    DCA_EXT_EXSS_XXCH  = 0x040, ///< XXCh channels extension in ExSS
+    DCA_EXT_EXSS_X96   = 0x080, ///< 96/24 extension in ExSS
+    DCA_EXT_EXSS_LBR   = 0x100, ///< low bitrate component in ExSS
+    DCA_EXT_EXSS_XLL   = 0x200, ///< lossless extension in ExSS
+};
+
+/* -1 are reserved or unknown */
+static const int dca_ext_audio_descr_mask[] = {
+    DCA_EXT_XCH,
+    -1,
+    DCA_EXT_X96,
+    DCA_EXT_XCH | DCA_EXT_X96,
+    -1,
+    -1,
+    DCA_EXT_XXCH,
+    -1,
+};
+
+/* extensions that reside in core substream */
+#define DCA_CORE_EXTS (DCA_EXT_XCH | DCA_EXT_XXCH | DCA_EXT_X96)
+
 /* Tables for mapping dts channel configurations to libavcodec multichannel api.
  * Some compromises have been made for special configurations. Most configurations
  * are never used so complete accuracy is not needed.
@@ -68,70 +121,107 @@ enum DCAMode {
  * L = left, R = right, C = center, S = surround, F = front, R = rear, T = total, OV = overhead.
  * S  -> side, when both rear and back are configured move one of them to the side channel
  * OV -> center back
- * All 2 channel configurations -> CH_LAYOUT_STEREO
+ * All 2 channel configurations -> AV_CH_LAYOUT_STEREO
  */
 
 static const int64_t dca_core_channel_layout[] = {
-    CH_FRONT_CENTER,                                               ///< 1, A
-    CH_LAYOUT_STEREO,                                              ///< 2, A + B (dual mono)
-    CH_LAYOUT_STEREO,                                              ///< 2, L + R (stereo)
-    CH_LAYOUT_STEREO,                                              ///< 2, (L+R) + (L-R) (sum-difference)
-    CH_LAYOUT_STEREO,                                              ///< 2, LT +RT (left and right total)
-    CH_LAYOUT_STEREO|CH_FRONT_CENTER,                              ///< 3, C+L+R
-    CH_LAYOUT_STEREO|CH_BACK_CENTER,                               ///< 3, L+R+S
-    CH_LAYOUT_STEREO|CH_FRONT_CENTER|CH_BACK_CENTER,               ///< 4, C + L + R+ S
-    CH_LAYOUT_STEREO|CH_SIDE_LEFT|CH_SIDE_RIGHT,                   ///< 4, L + R +SL+ SR
-    CH_LAYOUT_STEREO|CH_FRONT_CENTER|CH_SIDE_LEFT|CH_SIDE_RIGHT,   ///< 5, C + L + R+ SL+SR
-    CH_LAYOUT_STEREO|CH_SIDE_LEFT|CH_SIDE_RIGHT|CH_FRONT_LEFT_OF_CENTER|CH_FRONT_RIGHT_OF_CENTER,                 ///< 6, CL + CR + L + R + SL + SR
-    CH_LAYOUT_STEREO|CH_BACK_LEFT|CH_BACK_RIGHT|CH_FRONT_CENTER|CH_BACK_CENTER,                                   ///< 6, C + L + R+ LR + RR + OV
-    CH_FRONT_CENTER|CH_FRONT_RIGHT_OF_CENTER|CH_FRONT_LEFT_OF_CENTER|CH_BACK_CENTER|CH_BACK_LEFT|CH_BACK_RIGHT,   ///< 6, CF+ CR+LF+ RF+LR + RR
-    CH_FRONT_LEFT_OF_CENTER|CH_FRONT_CENTER|CH_FRONT_RIGHT_OF_CENTER|CH_LAYOUT_STEREO|CH_SIDE_LEFT|CH_SIDE_RIGHT, ///< 7, CL + C + CR + L + R + SL + SR
-    CH_FRONT_LEFT_OF_CENTER|CH_FRONT_RIGHT_OF_CENTER|CH_LAYOUT_STEREO|CH_SIDE_LEFT|CH_SIDE_RIGHT|CH_BACK_LEFT|CH_BACK_RIGHT, ///< 8, CL + CR + L + R + SL1 + SL2+ SR1 + SR2
-    CH_FRONT_LEFT_OF_CENTER|CH_FRONT_CENTER|CH_FRONT_RIGHT_OF_CENTER|CH_LAYOUT_STEREO|CH_SIDE_LEFT|CH_BACK_CENTER|CH_SIDE_RIGHT, ///< 8, CL + C+ CR + L + R + SL + S+ SR
+    AV_CH_FRONT_CENTER,                                                      ///< 1, A
+    AV_CH_LAYOUT_STEREO,                                                     ///< 2, A + B (dual mono)
+    AV_CH_LAYOUT_STEREO,                                                     ///< 2, L + R (stereo)
+    AV_CH_LAYOUT_STEREO,                                                     ///< 2, (L+R) + (L-R) (sum-difference)
+    AV_CH_LAYOUT_STEREO,                                                     ///< 2, LT +RT (left and right total)
+    AV_CH_LAYOUT_STEREO|AV_CH_FRONT_CENTER,                                  ///< 3, C+L+R
+    AV_CH_LAYOUT_STEREO|AV_CH_BACK_CENTER,                                   ///< 3, L+R+S
+    AV_CH_LAYOUT_STEREO|AV_CH_FRONT_CENTER|AV_CH_BACK_CENTER,                ///< 4, C + L + R+ S
+    AV_CH_LAYOUT_STEREO|AV_CH_SIDE_LEFT|AV_CH_SIDE_RIGHT,                    ///< 4, L + R +SL+ SR
+    AV_CH_LAYOUT_STEREO|AV_CH_FRONT_CENTER|AV_CH_SIDE_LEFT|AV_CH_SIDE_RIGHT, ///< 5, C + L + R+ SL+SR
+    AV_CH_LAYOUT_STEREO|AV_CH_SIDE_LEFT|AV_CH_SIDE_RIGHT|AV_CH_FRONT_LEFT_OF_CENTER|AV_CH_FRONT_RIGHT_OF_CENTER,                    ///< 6, CL + CR + L + R + SL + SR
+    AV_CH_LAYOUT_STEREO|AV_CH_BACK_LEFT|AV_CH_BACK_RIGHT|AV_CH_FRONT_CENTER|AV_CH_BACK_CENTER,                                      ///< 6, C + L + R+ LR + RR + OV
+    AV_CH_FRONT_CENTER|AV_CH_FRONT_RIGHT_OF_CENTER|AV_CH_FRONT_LEFT_OF_CENTER|AV_CH_BACK_CENTER|AV_CH_BACK_LEFT|AV_CH_BACK_RIGHT,   ///< 6, CF+ CR+LF+ RF+LR + RR
+    AV_CH_FRONT_LEFT_OF_CENTER|AV_CH_FRONT_CENTER|AV_CH_FRONT_RIGHT_OF_CENTER|AV_CH_LAYOUT_STEREO|AV_CH_SIDE_LEFT|AV_CH_SIDE_RIGHT, ///< 7, CL + C + CR + L + R + SL + SR
+    AV_CH_FRONT_LEFT_OF_CENTER|AV_CH_FRONT_RIGHT_OF_CENTER|AV_CH_LAYOUT_STEREO|AV_CH_SIDE_LEFT|AV_CH_SIDE_RIGHT|AV_CH_BACK_LEFT|AV_CH_BACK_RIGHT, ///< 8, CL + CR + L + R + SL1 + SL2+ SR1 + SR2
+    AV_CH_FRONT_LEFT_OF_CENTER|AV_CH_FRONT_CENTER|AV_CH_FRONT_RIGHT_OF_CENTER|AV_CH_LAYOUT_STEREO|AV_CH_SIDE_LEFT|AV_CH_BACK_CENTER|AV_CH_SIDE_RIGHT, ///< 8, CL + C+ CR + L + R + SL + S+ SR
 };
 
 static const int8_t dca_lfe_index[] = {
     1,2,2,2,2,3,2,3,2,3,2,3,1,3,2,3
 };
 
-static const int8_t dca_channel_reorder_lfe[][8] = {
-    { 0, -1, -1, -1, -1, -1, -1, -1},
-    { 0,  1, -1, -1, -1, -1, -1, -1},
-    { 0,  1, -1, -1, -1, -1, -1, -1},
-    { 0,  1, -1, -1, -1, -1, -1, -1},
-    { 0,  1, -1, -1, -1, -1, -1, -1},
-    { 2,  0,  1, -1, -1, -1, -1, -1},
-    { 0,  1,  3, -1, -1, -1, -1, -1},
-    { 2,  0,  1,  4, -1, -1, -1, -1},
-    { 0,  1,  3,  4, -1, -1, -1, -1},
-    { 2,  0,  1,  4,  5, -1, -1, -1},
-    { 3,  4,  0,  1,  5,  6, -1, -1},
-    { 2,  0,  1,  4,  5,  6, -1, -1},
-    { 0,  6,  4,  5,  2,  3, -1, -1},
-    { 4,  2,  5,  0,  1,  6,  7, -1},
-    { 5,  6,  0,  1,  7,  3,  8,  4},
-    { 4,  2,  5,  0,  1,  6,  8,  7},
+static const int8_t dca_channel_reorder_lfe[][9] = {
+    { 0, -1, -1, -1, -1, -1, -1, -1, -1},
+    { 0,  1, -1, -1, -1, -1, -1, -1, -1},
+    { 0,  1, -1, -1, -1, -1, -1, -1, -1},
+    { 0,  1, -1, -1, -1, -1, -1, -1, -1},
+    { 0,  1, -1, -1, -1, -1, -1, -1, -1},
+    { 2,  0,  1, -1, -1, -1, -1, -1, -1},
+    { 0,  1,  3, -1, -1, -1, -1, -1, -1},
+    { 2,  0,  1,  4, -1, -1, -1, -1, -1},
+    { 0,  1,  3,  4, -1, -1, -1, -1, -1},
+    { 2,  0,  1,  4,  5, -1, -1, -1, -1},
+    { 3,  4,  0,  1,  5,  6, -1, -1, -1},
+    { 2,  0,  1,  4,  5,  6, -1, -1, -1},
+    { 0,  6,  4,  5,  2,  3, -1, -1, -1},
+    { 4,  2,  5,  0,  1,  6,  7, -1, -1},
+    { 5,  6,  0,  1,  7,  3,  8,  4, -1},
+    { 4,  2,  5,  0,  1,  6,  8,  7, -1},
 };
 
-static const int8_t dca_channel_reorder_nolfe[][8] = {
-    { 0, -1, -1, -1, -1, -1, -1, -1},
-    { 0,  1, -1, -1, -1, -1, -1, -1},
-    { 0,  1, -1, -1, -1, -1, -1, -1},
-    { 0,  1, -1, -1, -1, -1, -1, -1},
-    { 0,  1, -1, -1, -1, -1, -1, -1},
-    { 2,  0,  1, -1, -1, -1, -1, -1},
-    { 0,  1,  2, -1, -1, -1, -1, -1},
-    { 2,  0,  1,  3, -1, -1, -1, -1},
-    { 0,  1,  2,  3, -1, -1, -1, -1},
-    { 2,  0,  1,  3,  4, -1, -1, -1},
-    { 2,  3,  0,  1,  4,  5, -1, -1},
-    { 2,  0,  1,  3,  4,  5, -1, -1},
-    { 0,  5,  3,  4,  1,  2, -1, -1},
-    { 3,  2,  4,  0,  1,  5,  6, -1},
-    { 4,  5,  0,  1,  6,  2,  7,  3},
-    { 3,  2,  4,  0,  1,  5,  7,  6},
+static const int8_t dca_channel_reorder_lfe_xch[][9] = {
+    { 0,  2, -1, -1, -1, -1, -1, -1, -1},
+    { 0,  1,  3, -1, -1, -1, -1, -1, -1},
+    { 0,  1,  3, -1, -1, -1, -1, -1, -1},
+    { 0,  1,  3, -1, -1, -1, -1, -1, -1},
+    { 0,  1,  3, -1, -1, -1, -1, -1, -1},
+    { 2,  0,  1,  4, -1, -1, -1, -1, -1},
+    { 0,  1,  3,  4, -1, -1, -1, -1, -1},
+    { 2,  0,  1,  4,  5, -1, -1, -1, -1},
+    { 0,  1,  4,  5,  3, -1, -1, -1, -1},
+    { 2,  0,  1,  5,  6,  4, -1, -1, -1},
+    { 3,  4,  0,  1,  6,  7,  5, -1, -1},
+    { 2,  0,  1,  4,  5,  6,  7, -1, -1},
+    { 0,  6,  4,  5,  2,  3,  7, -1, -1},
+    { 4,  2,  5,  0,  1,  7,  8,  6, -1},
+    { 5,  6,  0,  1,  8,  3,  9,  4,  7},
+    { 4,  2,  5,  0,  1,  6,  9,  8,  7},
 };
 
+static const int8_t dca_channel_reorder_nolfe[][9] = {
+    { 0, -1, -1, -1, -1, -1, -1, -1, -1},
+    { 0,  1, -1, -1, -1, -1, -1, -1, -1},
+    { 0,  1, -1, -1, -1, -1, -1, -1, -1},
+    { 0,  1, -1, -1, -1, -1, -1, -1, -1},
+    { 0,  1, -1, -1, -1, -1, -1, -1, -1},
+    { 2,  0,  1, -1, -1, -1, -1, -1, -1},
+    { 0,  1,  2, -1, -1, -1, -1, -1, -1},
+    { 2,  0,  1,  3, -1, -1, -1, -1, -1},
+    { 0,  1,  2,  3, -1, -1, -1, -1, -1},
+    { 2,  0,  1,  3,  4, -1, -1, -1, -1},
+    { 2,  3,  0,  1,  4,  5, -1, -1, -1},
+    { 2,  0,  1,  3,  4,  5, -1, -1, -1},
+    { 0,  5,  3,  4,  1,  2, -1, -1, -1},
+    { 3,  2,  4,  0,  1,  5,  6, -1, -1},
+    { 4,  5,  0,  1,  6,  2,  7,  3, -1},
+    { 3,  2,  4,  0,  1,  5,  7,  6, -1},
+};
+
+static const int8_t dca_channel_reorder_nolfe_xch[][9] = {
+    { 0,  1, -1, -1, -1, -1, -1, -1, -1},
+    { 0,  1,  2, -1, -1, -1, -1, -1, -1},
+    { 0,  1,  2, -1, -1, -1, -1, -1, -1},
+    { 0,  1,  2, -1, -1, -1, -1, -1, -1},
+    { 0,  1,  2, -1, -1, -1, -1, -1, -1},
+    { 2,  0,  1,  3, -1, -1, -1, -1, -1},
+    { 0,  1,  2,  3, -1, -1, -1, -1, -1},
+    { 2,  0,  1,  3,  4, -1, -1, -1, -1},
+    { 0,  1,  3,  4,  2, -1, -1, -1, -1},
+    { 2,  0,  1,  4,  5,  3, -1, -1, -1},
+    { 2,  3,  0,  1,  5,  6,  4, -1, -1},
+    { 2,  0,  1,  3,  4,  5,  6, -1, -1},
+    { 0,  5,  3,  4,  1,  2,  6, -1, -1},
+    { 3,  2,  4,  0,  1,  6,  7,  5, -1},
+    { 4,  5,  0,  1,  7,  2,  8,  3,  6},
+    { 3,  2,  4,  0,  1,  5,  8,  7,  6},
+};
 
 #define DCA_DOLBY 101           /* FIXME */
 
@@ -143,6 +233,9 @@ static const int8_t dca_channel_reorder_nolfe[][8] = {
 #define HEADER_SIZE 14
 
 #define DCA_MAX_FRAME_SIZE 16384
+#define DCA_MAX_EXSS_HEADER_SIZE 4096
+
+#define DCA_BUFFER_PADDING_SIZE 1024
 
 /** Bit allocation */
 typedef struct {
@@ -196,6 +289,7 @@ typedef struct {
 
     /* Primary audio coding header */
     int subframes;              ///< number of subframes
+    int is_channels_set;        ///< check for if the channel number is already set
     int total_channels;         ///< number of channels including extensions
     int prim_channels;          ///< number of primary audio channels
     int subband_activity[DCA_PRIM_CHANNELS_MAX];    ///< subband activity count
@@ -208,8 +302,8 @@ typedef struct {
     float scalefactor_adj[DCA_PRIM_CHANNELS_MAX][DCA_ABITS_MAX];   ///< scale factor adjustment
 
     /* Primary audio coding side information */
-    int subsubframes;           ///< number of subsubframes
-    int partial_samples;        ///< partial subsubframe samples count
+    int subsubframes[DCA_SUBFRAMES_MAX];           ///< number of subsubframes
+    int partial_samples[DCA_SUBFRAMES_MAX];        ///< partial subsubframe samples count
     int prediction_mode[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS];    ///< prediction mode (ADPCM used or not)
     int prediction_vq[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS];      ///< prediction VQ coefs
     int bitalloc[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS];           ///< bit allocation index
@@ -222,8 +316,7 @@ typedef struct {
 
     int high_freq_vq[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS];       ///< VQ encoded high frequency subbands
 
-    float lfe_data[2 * DCA_SUBSUBFAMES_MAX * DCA_LFE_MAX *
-                   2 /*history */ ];    ///< Low frequency effect data
+    float lfe_data[2 * DCA_LFE_MAX * (DCA_BLOCKS_MAX + 4)];      ///< Low frequency effect data
     int lfe_scale_factor;
 
     /* Subband samples history (for ADPCM) */
@@ -234,13 +327,13 @@ typedef struct {
     DECLARE_ALIGNED(16, float, raXin)[32];
 
     int output;                 ///< type of output
-    float add_bias;             ///< output bias
     float scale_bias;           ///< output scale
 
-    DECLARE_ALIGNED(16, float, samples)[1536];  /* 6 * 256 = 1536, might only need 5 */
-    const float *samples_chanptr[6];
+    DECLARE_ALIGNED(16, float, subband_samples)[DCA_BLOCKS_MAX][DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS][8];
+    DECLARE_ALIGNED(16, float, samples)[(DCA_PRIM_CHANNELS_MAX+1)*256];
+    const float *samples_chanptr[DCA_PRIM_CHANNELS_MAX+1];
 
-    uint8_t dca_buffer[DCA_MAX_FRAME_SIZE];
+    uint8_t dca_buffer[DCA_MAX_FRAME_SIZE + DCA_MAX_EXSS_HEADER_SIZE + DCA_BUFFER_PADDING_SIZE];
     int dca_buffer_size;        ///< how much data is in the dca_buffer
 
     const int8_t* channel_order_tab;                             ///< channel reordering table, lfe and non lfe
@@ -249,11 +342,26 @@ typedef struct {
     int current_subframe;
     int current_subsubframe;
 
+    int core_ext_mask;          ///< present extensions in the core substream
+
+    /* XCh extension information */
+    int xch_present;            ///< XCh extension present and valid
+    int xch_base_channel;       ///< index of first (only) channel containing XCH data
+
+    /* ExSS header parser */
+    int static_fields;          ///< static fields present
+    int mix_metadata;           ///< mixing metadata present
+    int num_mix_configs;        ///< number of mix out configurations
+    int mix_config_num_ch[4];   ///< number of channels in each mix out configuration
+
+    int profile;
+
     int debug_flag;             ///< used for suppressing repeated error messages output
     DSPContext dsp;
     FFTContext imdct;
     SynthFilterContext synth;
     DCADSPContext dcadsp;
+    FmtConvertContext fmt_conv;
 } DCAContext;
 
 static const uint16_t dca_vlc_offs[] = {
@@ -302,9 +410,9 @@ static av_cold void dca_init_vlcs(void)
                  tmode_codes[i], 2, 2, INIT_VLC_USE_NEW_STATIC);
     }
 
-    for(i = 0; i < 10; i++)
-        for(j = 0; j < 7; j++){
-            if(!bitalloc_codes[i][j]) break;
+    for (i = 0; i < 10; i++)
+        for (j = 0; j < 7; j++){
+            if (!bitalloc_codes[i][j]) break;
             dca_smpl_bitalloc[i+1].offset = bitalloc_offsets[i];
             dca_smpl_bitalloc[i+1].wrap = 1 + (j > 4);
             dca_smpl_bitalloc[i+1].vlc[j].table = &dca_table[dca_vlc_offs[c]];
@@ -324,13 +432,87 @@ static inline void get_array(GetBitContext *gb, int *dst, int len, int bits)
         *dst++ = get_bits(gb, bits);
 }
 
-static int dca_parse_frame_header(DCAContext * s)
+static int dca_parse_audio_coding_header(DCAContext * s, int base_channel)
 {
     int i, j;
     static const float adj_table[4] = { 1.0, 1.1250, 1.2500, 1.4375 };
     static const int bitlen[11] = { 0, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3 };
     static const int thr[11] = { 0, 1, 3, 3, 3, 3, 7, 7, 7, 7, 7 };
 
+    s->total_channels    = get_bits(&s->gb, 3) + 1 + base_channel;
+    s->prim_channels     = s->total_channels;
+
+    if (s->prim_channels > DCA_PRIM_CHANNELS_MAX)
+        s->prim_channels = DCA_PRIM_CHANNELS_MAX;
+
+
+    for (i = base_channel; i < s->prim_channels; i++) {
+        s->subband_activity[i] = get_bits(&s->gb, 5) + 2;
+        if (s->subband_activity[i] > DCA_SUBBANDS)
+            s->subband_activity[i] = DCA_SUBBANDS;
+    }
+    for (i = base_channel; i < s->prim_channels; i++) {
+        s->vq_start_subband[i] = get_bits(&s->gb, 5) + 1;
+        if (s->vq_start_subband[i] > DCA_SUBBANDS)
+            s->vq_start_subband[i] = DCA_SUBBANDS;
+    }
+    get_array(&s->gb, s->joint_intensity + base_channel,     s->prim_channels - base_channel, 3);
+    get_array(&s->gb, s->transient_huffman + base_channel,   s->prim_channels - base_channel, 2);
+    get_array(&s->gb, s->scalefactor_huffman + base_channel, s->prim_channels - base_channel, 3);
+    get_array(&s->gb, s->bitalloc_huffman + base_channel,    s->prim_channels - base_channel, 3);
+
+    /* Get codebooks quantization indexes */
+    if (!base_channel)
+        memset(s->quant_index_huffman, 0, sizeof(s->quant_index_huffman));
+    for (j = 1; j < 11; j++)
+        for (i = base_channel; i < s->prim_channels; i++)
+            s->quant_index_huffman[i][j] = get_bits(&s->gb, bitlen[j]);
+
+    /* Get scale factor adjustment */
+    for (j = 0; j < 11; j++)
+        for (i = base_channel; i < s->prim_channels; i++)
+            s->scalefactor_adj[i][j] = 1;
+
+    for (j = 1; j < 11; j++)
+        for (i = base_channel; i < s->prim_channels; i++)
+            if (s->quant_index_huffman[i][j] < thr[j])
+                s->scalefactor_adj[i][j] = adj_table[get_bits(&s->gb, 2)];
+
+    if (s->crc_present) {
+        /* Audio header CRC check */
+        get_bits(&s->gb, 16);
+    }
+
+    s->current_subframe = 0;
+    s->current_subsubframe = 0;
+
+#ifdef TRACE
+    av_log(s->avctx, AV_LOG_DEBUG, "subframes: %i\n", s->subframes);
+    av_log(s->avctx, AV_LOG_DEBUG, "prim channels: %i\n", s->prim_channels);
+    for (i = base_channel; i < s->prim_channels; i++){
+        av_log(s->avctx, AV_LOG_DEBUG, "subband activity: %i\n", s->subband_activity[i]);
+        av_log(s->avctx, AV_LOG_DEBUG, "vq start subband: %i\n", s->vq_start_subband[i]);
+        av_log(s->avctx, AV_LOG_DEBUG, "joint intensity: %i\n", s->joint_intensity[i]);
+        av_log(s->avctx, AV_LOG_DEBUG, "transient mode codebook: %i\n", s->transient_huffman[i]);
+        av_log(s->avctx, AV_LOG_DEBUG, "scale factor codebook: %i\n", s->scalefactor_huffman[i]);
+        av_log(s->avctx, AV_LOG_DEBUG, "bit allocation quantizer: %i\n", s->bitalloc_huffman[i]);
+        av_log(s->avctx, AV_LOG_DEBUG, "quant index huff:");
+        for (j = 0; j < 11; j++)
+            av_log(s->avctx, AV_LOG_DEBUG, " %i",
+                   s->quant_index_huffman[i][j]);
+        av_log(s->avctx, AV_LOG_DEBUG, "\n");
+        av_log(s->avctx, AV_LOG_DEBUG, "scalefac adj:");
+        for (j = 0; j < 11; j++)
+            av_log(s->avctx, AV_LOG_DEBUG, " %1.3f", s->scalefactor_adj[i][j]);
+        av_log(s->avctx, AV_LOG_DEBUG, "\n");
+    }
+#endif
+
+  return 0;
+}
+
+static int dca_parse_frame_header(DCAContext * s)
+{
     init_get_bits(&s->gb, s->dca_buffer, s->dca_buffer_size * 8);
 
     /* Sync code */
@@ -378,7 +560,7 @@ static int dca_parse_frame_header(DCAContext * s)
 
     /* FIXME: channels mixing levels */
     s->output = s->amode;
-    if(s->lfe) s->output |= DCA_LFE;
+    if (s->lfe) s->output |= DCA_LFE;
 
 #ifdef TRACE
     av_log(s->avctx, AV_LOG_DEBUG, "frame type: %i\n", s->frame_type);
@@ -420,74 +602,8 @@ static int dca_parse_frame_header(DCAContext * s)
 
     /* Primary audio coding header */
     s->subframes         = get_bits(&s->gb, 4) + 1;
-    s->total_channels    = get_bits(&s->gb, 3) + 1;
-    s->prim_channels     = s->total_channels;
-    if (s->prim_channels > DCA_PRIM_CHANNELS_MAX)
-        s->prim_channels = DCA_PRIM_CHANNELS_MAX;   /* We only support DTS core */
-
-
-    for (i = 0; i < s->prim_channels; i++) {
-        s->subband_activity[i] = get_bits(&s->gb, 5) + 2;
-        if (s->subband_activity[i] > DCA_SUBBANDS)
-            s->subband_activity[i] = DCA_SUBBANDS;
-    }
-    for (i = 0; i < s->prim_channels; i++) {
-        s->vq_start_subband[i] = get_bits(&s->gb, 5) + 1;
-        if (s->vq_start_subband[i] > DCA_SUBBANDS)
-            s->vq_start_subband[i] = DCA_SUBBANDS;
-    }
-    get_array(&s->gb, s->joint_intensity,     s->prim_channels, 3);
-    get_array(&s->gb, s->transient_huffman,   s->prim_channels, 2);
-    get_array(&s->gb, s->scalefactor_huffman, s->prim_channels, 3);
-    get_array(&s->gb, s->bitalloc_huffman,    s->prim_channels, 3);
-
-    /* Get codebooks quantization indexes */
-    memset(s->quant_index_huffman, 0, sizeof(s->quant_index_huffman));
-    for (j = 1; j < 11; j++)
-        for (i = 0; i < s->prim_channels; i++)
-            s->quant_index_huffman[i][j] = get_bits(&s->gb, bitlen[j]);
-
-    /* Get scale factor adjustment */
-    for (j = 0; j < 11; j++)
-        for (i = 0; i < s->prim_channels; i++)
-            s->scalefactor_adj[i][j] = 1;
-
-    for (j = 1; j < 11; j++)
-        for (i = 0; i < s->prim_channels; i++)
-            if (s->quant_index_huffman[i][j] < thr[j])
-                s->scalefactor_adj[i][j] = adj_table[get_bits(&s->gb, 2)];
-
-    if (s->crc_present) {
-        /* Audio header CRC check */
-        get_bits(&s->gb, 16);
-    }
-
-    s->current_subframe = 0;
-    s->current_subsubframe = 0;
-
-#ifdef TRACE
-    av_log(s->avctx, AV_LOG_DEBUG, "subframes: %i\n", s->subframes);
-    av_log(s->avctx, AV_LOG_DEBUG, "prim channels: %i\n", s->prim_channels);
-    for(i = 0; i < s->prim_channels; i++){
-        av_log(s->avctx, AV_LOG_DEBUG, "subband activity: %i\n", s->subband_activity[i]);
-        av_log(s->avctx, AV_LOG_DEBUG, "vq start subband: %i\n", s->vq_start_subband[i]);
-        av_log(s->avctx, AV_LOG_DEBUG, "joint intensity: %i\n", s->joint_intensity[i]);
-        av_log(s->avctx, AV_LOG_DEBUG, "transient mode codebook: %i\n", s->transient_huffman[i]);
-        av_log(s->avctx, AV_LOG_DEBUG, "scale factor codebook: %i\n", s->scalefactor_huffman[i]);
-        av_log(s->avctx, AV_LOG_DEBUG, "bit allocation quantizer: %i\n", s->bitalloc_huffman[i]);
-        av_log(s->avctx, AV_LOG_DEBUG, "quant index huff:");
-        for (j = 0; j < 11; j++)
-            av_log(s->avctx, AV_LOG_DEBUG, " %i",
-                   s->quant_index_huffman[i][j]);
-        av_log(s->avctx, AV_LOG_DEBUG, "\n");
-        av_log(s->avctx, AV_LOG_DEBUG, "scalefac adj:");
-        for (j = 0; j < 11; j++)
-            av_log(s->avctx, AV_LOG_DEBUG, " %1.3f", s->scalefactor_adj[i][j]);
-        av_log(s->avctx, AV_LOG_DEBUG, "\n");
-    }
-#endif
 
-    return 0;
+    return dca_parse_audio_coding_header(s, 0);
 }
 
 
@@ -496,25 +612,31 @@ static inline int get_scale(GetBitContext *gb, int level, int value)
    if (level < 5) {
        /* huffman encoded */
        value += get_bitalloc(gb, &dca_scalefactor, level);
-   } else if(level < 8)
+   } else if (level < 8)
        value = get_bits(gb, level + 1);
    return value;
 }
 
-static int dca_subframe_header(DCAContext * s)
+static int dca_subframe_header(DCAContext * s, int base_channel, int block_index)
 {
     /* Primary audio coding side information */
     int j, k;
 
-    s->subsubframes = get_bits(&s->gb, 2) + 1;
-    s->partial_samples = get_bits(&s->gb, 3);
-    for (j = 0; j < s->prim_channels; j++) {
+    if (get_bits_left(&s->gb) < 0)
+        return -1;
+
+    if (!base_channel) {
+        s->subsubframes[s->current_subframe] = get_bits(&s->gb, 2) + 1;
+        s->partial_samples[s->current_subframe] = get_bits(&s->gb, 3);
+    }
+
+    for (j = base_channel; j < s->prim_channels; j++) {
         for (k = 0; k < s->subband_activity[j]; k++)
             s->prediction_mode[j][k] = get_bits(&s->gb, 1);
     }
 
     /* Get prediction codebook */
-    for (j = 0; j < s->prim_channels; j++) {
+    for (j = base_channel; j < s->prim_channels; j++) {
         for (k = 0; k < s->subband_activity[j]; k++) {
             if (s->prediction_mode[j][k] > 0) {
                 /* (Prediction coefficient VQ address) */
@@ -524,7 +646,7 @@ static int dca_subframe_header(DCAContext * s)
     }
 
     /* Bit allocation index */
-    for (j = 0; j < s->prim_channels; j++) {
+    for (j = base_channel; j < s->prim_channels; j++) {
         for (k = 0; k < s->vq_start_subband[j]; k++) {
             if (s->bitalloc_huffman[j] == 6)
                 s->bitalloc[j][k] = get_bits(&s->gb, 5);
@@ -548,10 +670,10 @@ static int dca_subframe_header(DCAContext * s)
     }
 
     /* Transition mode */
-    for (j = 0; j < s->prim_channels; j++) {
+    for (j = base_channel; j < s->prim_channels; j++) {
         for (k = 0; k < s->subband_activity[j]; k++) {
             s->transition_mode[j][k] = 0;
-            if (s->subsubframes > 1 &&
+            if (s->subsubframes[s->current_subframe] > 1 &&
                 k < s->vq_start_subband[j] && s->bitalloc[j][k] > 0) {
                 s->transition_mode[j][k] =
                     get_bitalloc(&s->gb, &dca_tmode, s->transient_huffman[j]);
@@ -559,7 +681,10 @@ static int dca_subframe_header(DCAContext * s)
         }
     }
 
-    for (j = 0; j < s->prim_channels; j++) {
+    if (get_bits_left(&s->gb) < 0)
+        return -1;
+
+    for (j = base_channel; j < s->prim_channels; j++) {
         const uint32_t *scale_table;
         int scale_sum;
 
@@ -588,14 +713,17 @@ static int dca_subframe_header(DCAContext * s)
     }
 
     /* Joint subband scale factor codebook select */
-    for (j = 0; j < s->prim_channels; j++) {
+    for (j = base_channel; j < s->prim_channels; j++) {
         /* Transmitted only if joint subband coding enabled */
         if (s->joint_intensity[j] > 0)
             s->joint_huff[j] = get_bits(&s->gb, 3);
     }
 
+    if (get_bits_left(&s->gb) < 0)
+        return -1;
+
     /* Scale factors for joint subband coding */
-    for (j = 0; j < s->prim_channels; j++) {
+    for (j = base_channel; j < s->prim_channels; j++) {
         int source_channel;
 
         /* Transmitted only if joint subband coding enabled */
@@ -621,15 +749,15 @@ static int dca_subframe_header(DCAContext * s)
     }
 
     /* Stereo downmix coefficients */
-    if (s->prim_channels > 2) {
-        if(s->downmix) {
-            for (j = 0; j < s->prim_channels; j++) {
+    if (!base_channel && s->prim_channels > 2) {
+        if (s->downmix) {
+            for (j = base_channel; j < s->prim_channels; j++) {
                 s->downmix_coef[j][0] = get_bits(&s->gb, 7);
                 s->downmix_coef[j][1] = get_bits(&s->gb, 7);
             }
         } else {
             int am = s->amode & DCA_CHANNEL_MASK;
-            for (j = 0; j < s->prim_channels; j++) {
+            for (j = base_channel; j < s->prim_channels; j++) {
                 s->downmix_coef[j][0] = dca_default_coeffs[am][j][0];
                 s->downmix_coef[j][1] = dca_default_coeffs[am][j][1];
             }
@@ -637,7 +765,7 @@ static int dca_subframe_header(DCAContext * s)
     }
 
     /* Dynamic range coefficient */
-    if (s->dynrange)
+    if (!base_channel && s->dynrange)
         s->dynrange_coef = get_bits(&s->gb, 8);
 
     /* Side information CRC check word */
@@ -650,18 +778,19 @@ static int dca_subframe_header(DCAContext * s)
      */
 
     /* VQ encoded high frequency subbands */
-    for (j = 0; j < s->prim_channels; j++)
+    for (j = base_channel; j < s->prim_channels; j++)
         for (k = s->vq_start_subband[j]; k < s->subband_activity[j]; k++)
             /* 1 vector -> 32 samples */
             s->high_freq_vq[j][k] = get_bits(&s->gb, 10);
 
     /* Low frequency effect data */
-    if (s->lfe) {
+    if (!base_channel && s->lfe) {
         /* LFE samples */
-        int lfe_samples = 2 * s->lfe * s->subsubframes;
+        int lfe_samples = 2 * s->lfe * (4 + block_index);
+        int lfe_end_sample = 2 * s->lfe * (4 + block_index + s->subsubframes[s->current_subframe]);
         float lfe_scale;
 
-        for (j = lfe_samples; j < lfe_samples * 2; j++) {
+        for (j = lfe_samples; j < lfe_end_sample; j++) {
             /* Signed 8 bits int */
             s->lfe_data[j] = get_sbits(&s->gb, 8);
         }
@@ -672,21 +801,21 @@ static int dca_subframe_header(DCAContext * s)
         /* Quantization step size * scale factor */
         lfe_scale = 0.035 * s->lfe_scale_factor;
 
-        for (j = lfe_samples; j < lfe_samples * 2; j++)
+        for (j = lfe_samples; j < lfe_end_sample; j++)
             s->lfe_data[j] *= lfe_scale;
     }
 
 #ifdef TRACE
-    av_log(s->avctx, AV_LOG_DEBUG, "subsubframes: %i\n", s->subsubframes);
+    av_log(s->avctx, AV_LOG_DEBUG, "subsubframes: %i\n", s->subsubframes[s->current_subframe]);
     av_log(s->avctx, AV_LOG_DEBUG, "partial samples: %i\n",
-           s->partial_samples);
-    for (j = 0; j < s->prim_channels; j++) {
+           s->partial_samples[s->current_subframe]);
+    for (j = base_channel; j < s->prim_channels; j++) {
         av_log(s->avctx, AV_LOG_DEBUG, "prediction mode:");
         for (k = 0; k < s->subband_activity[j]; k++)
             av_log(s->avctx, AV_LOG_DEBUG, " %i", s->prediction_mode[j][k]);
         av_log(s->avctx, AV_LOG_DEBUG, "\n");
     }
-    for (j = 0; j < s->prim_channels; j++) {
+    for (j = base_channel; j < s->prim_channels; j++) {
         for (k = 0; k < s->subband_activity[j]; k++)
                 av_log(s->avctx, AV_LOG_DEBUG,
                        "prediction coefs: %f, %f, %f, %f\n",
@@ -695,19 +824,19 @@ static int dca_subframe_header(DCAContext * s)
                        (float) adpcm_vb[s->prediction_vq[j][k]][2] / 8192,
                        (float) adpcm_vb[s->prediction_vq[j][k]][3] / 8192);
     }
-    for (j = 0; j < s->prim_channels; j++) {
+    for (j = base_channel; j < s->prim_channels; j++) {
         av_log(s->avctx, AV_LOG_DEBUG, "bitalloc index: ");
         for (k = 0; k < s->vq_start_subband[j]; k++)
             av_log(s->avctx, AV_LOG_DEBUG, "%2.2i ", s->bitalloc[j][k]);
         av_log(s->avctx, AV_LOG_DEBUG, "\n");
     }
-    for (j = 0; j < s->prim_channels; j++) {
+    for (j = base_channel; j < s->prim_channels; j++) {
         av_log(s->avctx, AV_LOG_DEBUG, "Transition mode:");
         for (k = 0; k < s->subband_activity[j]; k++)
             av_log(s->avctx, AV_LOG_DEBUG, " %i", s->transition_mode[j][k]);
         av_log(s->avctx, AV_LOG_DEBUG, "\n");
     }
-    for (j = 0; j < s->prim_channels; j++) {
+    for (j = base_channel; j < s->prim_channels; j++) {
         av_log(s->avctx, AV_LOG_DEBUG, "Scale factor:");
         for (k = 0; k < s->subband_activity[j]; k++) {
             if (k >= s->vq_start_subband[j] || s->bitalloc[j][k] > 0)
@@ -717,7 +846,7 @@ static int dca_subframe_header(DCAContext * s)
         }
         av_log(s->avctx, AV_LOG_DEBUG, "\n");
     }
-    for (j = 0; j < s->prim_channels; j++) {
+    for (j = base_channel; j < s->prim_channels; j++) {
         if (s->joint_intensity[j] > 0) {
             int source_channel = s->joint_intensity[j] - 1;
             av_log(s->avctx, AV_LOG_DEBUG, "Joint scale factor index:\n");
@@ -726,7 +855,7 @@ static int dca_subframe_header(DCAContext * s)
             av_log(s->avctx, AV_LOG_DEBUG, "\n");
         }
     }
-    if (s->prim_channels > 2 && s->downmix) {
+    if (!base_channel && s->prim_channels > 2 && s->downmix) {
         av_log(s->avctx, AV_LOG_DEBUG, "Downmix coeffs:\n");
         for (j = 0; j < s->prim_channels; j++) {
             av_log(s->avctx, AV_LOG_DEBUG, "Channel 0,%d = %f\n", j, dca_downmix_coeffs[s->downmix_coef[j][0]]);
@@ -734,13 +863,15 @@ static int dca_subframe_header(DCAContext * s)
         }
         av_log(s->avctx, AV_LOG_DEBUG, "\n");
     }
-    for (j = 0; j < s->prim_channels; j++)
+    for (j = base_channel; j < s->prim_channels; j++)
         for (k = s->vq_start_subband[j]; k < s->subband_activity[j]; k++)
             av_log(s->avctx, AV_LOG_DEBUG, "VQ index: %i\n", s->high_freq_vq[j][k]);
-    if(s->lfe){
-        int lfe_samples = 2 * s->lfe * s->subsubframes;
+    if (!base_channel && s->lfe) {
+        int lfe_samples = 2 * s->lfe * (4 + block_index);
+        int lfe_end_sample = 2 * s->lfe * (4 + block_index + s->subsubframes[s->current_subframe]);
+
         av_log(s->avctx, AV_LOG_DEBUG, "LFE samples:\n");
-        for (j = lfe_samples; j < lfe_samples * 2; j++)
+        for (j = lfe_samples; j < lfe_end_sample; j++)
             av_log(s->avctx, AV_LOG_DEBUG, " %f", s->lfe_data[j]);
         av_log(s->avctx, AV_LOG_DEBUG, "\n");
     }
@@ -751,7 +882,7 @@ static int dca_subframe_header(DCAContext * s)
 
 static void qmf_32_subbands(DCAContext * s, int chans,
                             float samples_in[32][8], float *samples_out,
-                            float scale, float bias)
+                            float scale)
 {
     const float *prCoeff;
     int i;
@@ -780,7 +911,7 @@ static void qmf_32_subbands(DCAContext * s, int chans,
         s->synth.synth_filter_float(&s->imdct,
                               s->subband_fir_hist[chans], &s->hist_index[chans],
                               s->subband_fir_noidea[chans], prCoeff,
-                              samples_out, s->raXin, scale, bias);
+                              samples_out, s->raXin, scale);
         samples_out+= 32;
 
     }
@@ -788,8 +919,7 @@ static void qmf_32_subbands(DCAContext * s, int chans,
 
 static void lfe_interpolation_fir(DCAContext *s, int decimation_select,
                                   int num_deci_sample, float *samples_in,
-                                  float *samples_out, float scale,
-                                  float bias)
+                                  float *samples_out, float scale)
 {
     /* samples_in: An array holding decimated samples.
      *   Samples in current subframe starts from samples_in[0],
@@ -814,7 +944,7 @@ static void lfe_interpolation_fir(DCAContext *s, int decimation_select,
     /* Interpolation */
     for (deciindex = 0; deciindex < num_deci_sample; deciindex++) {
         s->dcadsp.lfe_fir(samples_out, samples_in, prCoeff, decifactor,
-                          scale, bias);
+                          scale);
         samples_in++;
         samples_out += 2 * decifactor;
     }
@@ -822,7 +952,7 @@ static void lfe_interpolation_fir(DCAContext *s, int decimation_select,
 
 /* downmixing routines */
 #define MIX_REAR1(samples, si1, rs, coef) \
-     samples[i]     += samples[si1] * coef[rs][0]; \
+     samples[i]     += samples[si1] * coef[rs][0];  \
      samples[i+256] += samples[si1] * coef[rs][1];
 
 #define MIX_REAR2(samples, si1, si2, rs, coef) \
@@ -830,24 +960,28 @@ static void lfe_interpolation_fir(DCAContext *s, int decimation_select,
      samples[i+256] += samples[si1] * coef[rs][1] + samples[si2] * coef[rs+1][1];
 
 #define MIX_FRONT3(samples, coef) \
-    t = samples[i]; \
-    samples[i]     = t * coef[0][0] + samples[i+256] * coef[1][0] + samples[i+512] * coef[2][0]; \
-    samples[i+256] = t * coef[0][1] + samples[i+256] * coef[1][1] + samples[i+512] * coef[2][1];
+    t = samples[i+c]; \
+    u = samples[i+l]; \
+    v = samples[i+r]; \
+    samples[i]     = t * coef[0][0] + u * coef[1][0] + v * coef[2][0]; \
+    samples[i+256] = t * coef[0][1] + u * coef[1][1] + v * coef[2][1];
 
 #define DOWNMIX_TO_STEREO(op1, op2) \
-    for(i = 0; i < 256; i++){ \
+    for (i = 0; i < 256; i++){ \
         op1 \
         op2 \
     }
 
 static void dca_downmix(float *samples, int srcfmt,
-                        int downmix_coef[DCA_PRIM_CHANNELS_MAX][2])
+                        int downmix_coef[DCA_PRIM_CHANNELS_MAX][2],
+                        const int8_t *channel_mapping)
 {
+    int c,l,r,sl,sr,s;
     int i;
-    float t;
+    float t, u, v;
     float coef[DCA_PRIM_CHANNELS_MAX][2];
 
-    for(i=0; i<DCA_PRIM_CHANNELS_MAX; i++) {
+    for (i=0; i<DCA_PRIM_CHANNELS_MAX; i++) {
         coef[i][0] = dca_downmix_coeffs[downmix_coef[i][0]];
         coef[i][1] = dca_downmix_coeffs[downmix_coef[i][1]];
     }
@@ -863,21 +997,36 @@ static void dca_downmix(float *samples, int srcfmt,
     case DCA_STEREO:
         break;
     case DCA_3F:
+        c = channel_mapping[0] * 256;
+        l = channel_mapping[1] * 256;
+        r = channel_mapping[2] * 256;
         DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef),);
         break;
     case DCA_2F1R:
-        DOWNMIX_TO_STEREO(MIX_REAR1(samples, i + 512, 2, coef),);
+        s = channel_mapping[2] * 256;
+        DOWNMIX_TO_STEREO(MIX_REAR1(samples, i + s, 2, coef),);
         break;
     case DCA_3F1R:
+        c = channel_mapping[0] * 256;
+        l = channel_mapping[1] * 256;
+        r = channel_mapping[2] * 256;
+        s = channel_mapping[3] * 256;
         DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef),
-                          MIX_REAR1(samples, i + 768, 3, coef));
+                          MIX_REAR1(samples, i + s, 3, coef));
         break;
     case DCA_2F2R:
-        DOWNMIX_TO_STEREO(MIX_REAR2(samples, i + 512, i + 768, 2, coef),);
+        sl = channel_mapping[2] * 256;
+        sr = channel_mapping[3] * 256;
+        DOWNMIX_TO_STEREO(MIX_REAR2(samples, i + sl, i + sr, 2, coef),);
         break;
     case DCA_3F2R:
+        c =  channel_mapping[0] * 256;
+        l =  channel_mapping[1] * 256;
+        r =  channel_mapping[2] * 256;
+        sl = channel_mapping[3] * 256;
+        sr = channel_mapping[4] * 256;
         DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef),
-                          MIX_REAR2(samples, i + 768, i + 1024, 3, coef));
+                          MIX_REAR2(samples, i + sl, i + sr, 3, coef));
         break;
     }
 }
@@ -907,7 +1056,7 @@ static int decode_blockcode(int code, int levels, int *values)
 static const uint8_t abits_sizes[7] = { 7, 10, 12, 13, 15, 17, 19 };
 static const uint8_t abits_levels[7] = { 3, 5, 7, 9, 13, 17, 25 };
 
-static int dca_subsubframe(DCAContext * s)
+static int dca_subsubframe(DCAContext * s, int base_channel, int block_index)
 {
     int k, l;
     int subsubframe = s->current_subsubframe;
@@ -915,7 +1064,7 @@ static int dca_subsubframe(DCAContext * s)
     const float *quant_step_table;
 
     /* FIXME */
-    LOCAL_ALIGNED_16(float, subband_samples, [DCA_PRIM_CHANNELS_MAX], [DCA_SUBBANDS][8]);
+    float (*subband_samples)[DCA_SUBBANDS][8] = s->subband_samples[block_index];
     LOCAL_ALIGNED_16(int, block, [8]);
 
     /*
@@ -928,7 +1077,10 @@ static int dca_subsubframe(DCAContext * s)
     else
         quant_step_table = lossy_quant_d;
 
-    for (k = 0; k < s->prim_channels; k++) {
+    for (k = base_channel; k < s->prim_channels; k++) {
+        if (get_bits_left(&s->gb) < 0)
+            return -1;
+
         for (l = 0; l < s->vq_start_subband[k]; l++) {
             int m;
 
@@ -947,15 +1099,15 @@ static int dca_subsubframe(DCAContext * s)
             /*
              * Extract bits from the bit stream
              */
-            if(!abits){
+            if (!abits){
                 memset(subband_samples[k][l], 0, 8 * sizeof(subband_samples[0][0][0]));
             } else {
                 /* Deal with transients */
                 int sfi = s->transition_mode[k][l] && subsubframe >= s->transition_mode[k][l];
                 float rscale = quant_step_size * s->scale_factor[k][l][sfi] * s->scalefactor_adj[k][sel];
 
-                if(abits >= 11 || !dca_smpl_bitalloc[abits].vlc[sel].table){
-                    if(abits <= 7){
+                if (abits >= 11 || !dca_smpl_bitalloc[abits].vlc[sel].table){
+                    if (abits <= 7){
                         /* Block code */
                         int block_code1, block_code2, size, levels;
 
@@ -978,7 +1130,7 @@ static int dca_subsubframe(DCAContext * s)
                         block[m] = get_bitalloc(&s->gb, &dca_smpl_bitalloc[abits], sel);
                 }
 
-                s->dsp.int32_to_float_fmul_scalar(subband_samples[k][l],
+                s->fmt_conv.int32_to_float_fmul_scalar(subband_samples[k][l],
                                                   block, rscale, 8);
             }
 
@@ -1025,7 +1177,7 @@ static int dca_subsubframe(DCAContext * s)
     }
 
     /* Check for DSYNC after subsubframe */
-    if (s->aspf || subsubframe == s->subsubframes - 1) {
+    if (s->aspf || subsubframe == s->subsubframes[s->current_subframe] - 1) {
         if (0xFFFF == get_bits(&s->gb, 16)) {   /* 0xFFFF */
 #ifdef TRACE
             av_log(s->avctx, AV_LOG_DEBUG, "Got subframe DSYNC\n");
@@ -1036,35 +1188,38 @@ static int dca_subsubframe(DCAContext * s)
     }
 
     /* Backup predictor history for adpcm */
-    for (k = 0; k < s->prim_channels; k++)
+    for (k = base_channel; k < s->prim_channels; k++)
         for (l = 0; l < s->vq_start_subband[k]; l++)
             memcpy(s->subband_samples_hist[k][l], &subband_samples[k][l][4],
                         4 * sizeof(subband_samples[0][0][0]));
 
+    return 0;
+}
+
+static int dca_filter_channels(DCAContext * s, int block_index)
+{
+    float (*subband_samples)[DCA_SUBBANDS][8] = s->subband_samples[block_index];
+    int k;
+
     /* 32 subbands QMF */
     for (k = 0; k < s->prim_channels; k++) {
 /*        static float pcm_to_double[8] =
             {32768.0, 32768.0, 524288.0, 524288.0, 0, 8388608.0, 8388608.0};*/
          qmf_32_subbands(s, k, subband_samples[k], &s->samples[256 * s->channel_order_tab[k]],
-                            M_SQRT1_2*s->scale_bias /*pcm_to_double[s->source_pcm_res] */ ,
-                            s->add_bias );
+                         M_SQRT1_2*s->scale_bias /*pcm_to_double[s->source_pcm_res] */ );
     }
 
     /* Down mixing */
-
-    if (s->prim_channels > dca_channels[s->output & DCA_CHANNEL_MASK]) {
-        dca_downmix(s->samples, s->amode, s->downmix_coef);
+    if (s->avctx->request_channels == 2 && s->prim_channels > 2) {
+        dca_downmix(s->samples, s->amode, s->downmix_coef, s->channel_order_tab);
     }
 
     /* Generate LFE samples for this subsubframe FIXME!!! */
     if (s->output & DCA_LFE) {
-        int lfe_samples = 2 * s->lfe * s->subsubframes;
-
         lfe_interpolation_fir(s, s->lfe, 2 * s->lfe,
-                              s->lfe_data + lfe_samples +
-                              2 * s->lfe * subsubframe,
+                              s->lfe_data + 2 * s->lfe * (block_index + 4),
                               &s->samples[256 * dca_lfe_index[s->amode]],
-                              (1.0/256.0)*s->scale_bias,  s->add_bias);
+                              (1.0/256.0)*s->scale_bias);
         /* Outputs 20bits pcm samples */
     }
 
@@ -1072,30 +1227,27 @@ static int dca_subsubframe(DCAContext * s)
 }
 
 
-static int dca_subframe_footer(DCAContext * s)
+static int dca_subframe_footer(DCAContext * s, int base_channel)
 {
     int aux_data_count = 0, i;
-    int lfe_samples;
 
     /*
      * Unpack optional information
      */
 
-    if (s->timestamp)
-        get_bits(&s->gb, 32);
-
-    if (s->aux_data)
-        aux_data_count = get_bits(&s->gb, 6);
+    /* presumably optional information only appears in the core? */
+    if (!base_channel) {
+        if (s->timestamp)
+            get_bits(&s->gb, 32);
 
-    for (i = 0; i < aux_data_count; i++)
-        get_bits(&s->gb, 8);
+        if (s->aux_data)
+            aux_data_count = get_bits(&s->gb, 6);
 
-    if (s->crc_present && (s->downmix || s->dynrange))
-        get_bits(&s->gb, 16);
+        for (i = 0; i < aux_data_count; i++)
+            get_bits(&s->gb, 8);
 
-    lfe_samples = 2 * s->lfe * s->subsubframes;
-    for (i = 0; i < lfe_samples; i++) {
-        s->lfe_data[i] = s->lfe_data[i + lfe_samples];
+        if (s->crc_present && (s->downmix || s->dynrange))
+            get_bits(&s->gb, 16);
     }
 
     return 0;
@@ -1107,7 +1259,7 @@ static int dca_subframe_footer(DCAContext * s)
  * @param s     pointer to the DCAContext
  */
 
-static int dca_decode_block(DCAContext * s)
+static int dca_decode_block(DCAContext * s, int base_channel, int block_index)
 {
 
     /* Sanity check */
@@ -1122,7 +1274,7 @@ static int dca_decode_block(DCAContext * s)
         av_log(s->avctx, AV_LOG_DEBUG, "DSYNC dca_subframe_header\n");
 #endif
         /* Read subframe header */
-        if (dca_subframe_header(s))
+        if (dca_subframe_header(s, base_channel, block_index))
             return -1;
     }
 
@@ -1130,12 +1282,12 @@ static int dca_decode_block(DCAContext * s)
 #ifdef TRACE
     av_log(s->avctx, AV_LOG_DEBUG, "DSYNC dca_subsubframe\n");
 #endif
-    if (dca_subsubframe(s))
+    if (dca_subsubframe(s, base_channel, block_index))
         return -1;
 
     /* Update state */
     s->current_subsubframe++;
-    if (s->current_subsubframe >= s->subsubframes) {
+    if (s->current_subsubframe >= s->subsubframes[s->current_subframe]) {
         s->current_subsubframe = 0;
         s->current_subframe++;
     }
@@ -1144,7 +1296,7 @@ static int dca_decode_block(DCAContext * s)
         av_log(s->avctx, AV_LOG_DEBUG, "DSYNC dca_subframe_footer\n");
 #endif
         /* Read subframe footer */
-        if (dca_subframe_footer(s))
+        if (dca_subframe_footer(s, base_channel))
             return -1;
     }
 
@@ -1163,7 +1315,7 @@ static int dca_convert_bitstream(const uint8_t * src, int src_size, uint8_t * ds
     uint16_t *sdst = (uint16_t *) dst;
     PutBitContext pb;
 
-    if((unsigned)src_size > (unsigned)max_size) {
+    if ((unsigned)src_size > (unsigned)max_size) {
 //        av_log(NULL, AV_LOG_ERROR, "Input frame size larger then DCA_MAX_FRAME_SIZE!\n");
 //        return -1;
         src_size = max_size;
@@ -1176,7 +1328,7 @@ static int dca_convert_bitstream(const uint8_t * src, int src_size, uint8_t * ds
         return src_size;
     case DCA_MARKER_RAW_LE:
         for (i = 0; i < (src_size + 1) >> 1; i++)
-            *sdst++ = bswap_16(*ssrc++);
+            *sdst++ = av_bswap16(*ssrc++);
         return src_size;
     case DCA_MARKER_14B_BE:
     case DCA_MARKER_14B_LE:
@@ -1193,6 +1345,274 @@ static int dca_convert_bitstream(const uint8_t * src, int src_size, uint8_t * ds
 }
 
 /**
+ * Return the number of channels in an ExSS speaker mask (HD)
+ */
+static int dca_exss_mask2count(int mask)
+{
+    /* count bits that mean speaker pairs twice */
+    return av_popcount(mask)
+        + av_popcount(mask & (
+            DCA_EXSS_CENTER_LEFT_RIGHT
+          | DCA_EXSS_FRONT_LEFT_RIGHT
+          | DCA_EXSS_FRONT_HIGH_LEFT_RIGHT
+          | DCA_EXSS_WIDE_LEFT_RIGHT
+          | DCA_EXSS_SIDE_LEFT_RIGHT
+          | DCA_EXSS_SIDE_HIGH_LEFT_RIGHT
+          | DCA_EXSS_SIDE_REAR_LEFT_RIGHT
+          | DCA_EXSS_REAR_LEFT_RIGHT
+          | DCA_EXSS_REAR_HIGH_LEFT_RIGHT
+          ));
+}
+
+/**
+ * Skip mixing coefficients of a single mix out configuration (HD)
+ */
+static void dca_exss_skip_mix_coeffs(GetBitContext *gb, int channels, int out_ch)
+{
+    int i;
+
+    for (i = 0; i < channels; i++) {
+        int mix_map_mask = get_bits(gb, out_ch);
+        int num_coeffs = av_popcount(mix_map_mask);
+        skip_bits_long(gb, num_coeffs * 6);
+    }
+}
+
+/**
+ * Parse extension substream asset header (HD)
+ */
+static int dca_exss_parse_asset_header(DCAContext *s)
+{
+    int header_pos = get_bits_count(&s->gb);
+    int header_size;
+    int channels;
+    int embedded_stereo = 0;
+    int embedded_6ch = 0;
+    int drc_code_present;
+    int extensions_mask;
+    int i, j;
+
+    if (get_bits_left(&s->gb) < 16)
+        return -1;
+
+    /* We will parse just enough to get to the extensions bitmask with which
+     * we can set the profile value. */
+
+    header_size = get_bits(&s->gb, 9) + 1;
+    skip_bits(&s->gb, 3); // asset index
+
+    if (s->static_fields) {
+        if (get_bits1(&s->gb))
+            skip_bits(&s->gb, 4); // asset type descriptor
+        if (get_bits1(&s->gb))
+            skip_bits_long(&s->gb, 24); // language descriptor
+
+        if (get_bits1(&s->gb)) {
+            /* How can one fit 1024 bytes of text here if the maximum value
+             * for the asset header size field above was 512 bytes? */
+            int text_length = get_bits(&s->gb, 10) + 1;
+            if (get_bits_left(&s->gb) < text_length * 8)
+                return -1;
+            skip_bits_long(&s->gb, text_length * 8); // info text
+        }
+
+        skip_bits(&s->gb, 5); // bit resolution - 1
+        skip_bits(&s->gb, 4); // max sample rate code
+        channels = get_bits(&s->gb, 8) + 1;
+
+        if (get_bits1(&s->gb)) { // 1-to-1 channels to speakers
+            int spkr_remap_sets;
+            int spkr_mask_size = 16;
+            int num_spkrs[7];
+
+            if (channels > 2)
+                embedded_stereo = get_bits1(&s->gb);
+            if (channels > 6)
+                embedded_6ch = get_bits1(&s->gb);
+
+            if (get_bits1(&s->gb)) {
+                spkr_mask_size = (get_bits(&s->gb, 2) + 1) << 2;
+                skip_bits(&s->gb, spkr_mask_size); // spkr activity mask
+            }
+
+            spkr_remap_sets = get_bits(&s->gb, 3);
+
+            for (i = 0; i < spkr_remap_sets; i++) {
+                /* std layout mask for each remap set */
+                num_spkrs[i] = dca_exss_mask2count(get_bits(&s->gb, spkr_mask_size));
+            }
+
+            for (i = 0; i < spkr_remap_sets; i++) {
+                int num_dec_ch_remaps = get_bits(&s->gb, 5) + 1;
+                if (get_bits_left(&s->gb) < 0)
+                    return -1;
+
+                for (j = 0; j < num_spkrs[i]; j++) {
+                    int remap_dec_ch_mask = get_bits_long(&s->gb, num_dec_ch_remaps);
+                    int num_dec_ch = av_popcount(remap_dec_ch_mask);
+                    skip_bits_long(&s->gb, num_dec_ch * 5); // remap codes
+                }
+            }
+
+        } else {
+            skip_bits(&s->gb, 3); // representation type
+        }
+    }
+
+    drc_code_present = get_bits1(&s->gb);
+    if (drc_code_present)
+        get_bits(&s->gb, 8); // drc code
+
+    if (get_bits1(&s->gb))
+        skip_bits(&s->gb, 5); // dialog normalization code
+
+    if (drc_code_present && embedded_stereo)
+        get_bits(&s->gb, 8); // drc stereo code
+
+    if (s->mix_metadata && get_bits1(&s->gb)) {
+        skip_bits(&s->gb, 1); // external mix
+        skip_bits(&s->gb, 6); // post mix gain code
+
+        if (get_bits(&s->gb, 2) != 3) // mixer drc code
+            skip_bits(&s->gb, 3); // drc limit
+        else
+            skip_bits(&s->gb, 8); // custom drc code
+
+        if (get_bits1(&s->gb)) // channel specific scaling
+            for (i = 0; i < s->num_mix_configs; i++)
+                skip_bits_long(&s->gb, s->mix_config_num_ch[i] * 6); // scale codes
+        else
+            skip_bits_long(&s->gb, s->num_mix_configs * 6); // scale codes
+
+        for (i = 0; i < s->num_mix_configs; i++) {
+            if (get_bits_left(&s->gb) < 0)
+                return -1;
+            dca_exss_skip_mix_coeffs(&s->gb, channels, s->mix_config_num_ch[i]);
+            if (embedded_6ch)
+                dca_exss_skip_mix_coeffs(&s->gb, 6, s->mix_config_num_ch[i]);
+            if (embedded_stereo)
+                dca_exss_skip_mix_coeffs(&s->gb, 2, s->mix_config_num_ch[i]);
+        }
+    }
+
+    switch (get_bits(&s->gb, 2)) {
+    case 0: extensions_mask = get_bits(&s->gb, 12); break;
+    case 1: extensions_mask = DCA_EXT_EXSS_XLL;     break;
+    case 2: extensions_mask = DCA_EXT_EXSS_LBR;     break;
+    case 3: extensions_mask = 0; /* aux coding */   break;
+    }
+
+    /* not parsed further, we were only interested in the extensions mask */
+
+    if (get_bits_left(&s->gb) < 0)
+        return -1;
+
+    if (get_bits_count(&s->gb) - header_pos > header_size * 8) {
+        av_log(s->avctx, AV_LOG_WARNING, "Asset header size mismatch.\n");
+        return -1;
+    }
+    skip_bits_long(&s->gb, header_pos + header_size * 8 - get_bits_count(&s->gb));
+
+    if (extensions_mask & DCA_EXT_EXSS_XLL)
+        s->profile = FF_PROFILE_DTS_HD_MA;
+    else if (extensions_mask & (DCA_EXT_EXSS_XBR | DCA_EXT_EXSS_X96 |
+                                DCA_EXT_EXSS_XXCH))
+        s->profile = FF_PROFILE_DTS_HD_HRA;
+
+    if (!(extensions_mask & DCA_EXT_CORE))
+        av_log(s->avctx, AV_LOG_WARNING, "DTS core detection mismatch.\n");
+    if ((extensions_mask & DCA_CORE_EXTS) != s->core_ext_mask)
+        av_log(s->avctx, AV_LOG_WARNING, "DTS extensions detection mismatch (%d, %d)\n",
+               extensions_mask & DCA_CORE_EXTS, s->core_ext_mask);
+
+    return 0;
+}
+
+/**
+ * Parse extension substream header (HD)
+ */
+static void dca_exss_parse_header(DCAContext *s)
+{
+    int ss_index;
+    int blownup;
+    int header_size;
+    int hd_size;
+    int num_audiop = 1;
+    int num_assets = 1;
+    int active_ss_mask[8];
+    int i, j;
+
+    if (get_bits_left(&s->gb) < 52)
+        return;
+
+    skip_bits(&s->gb, 8); // user data
+    ss_index = get_bits(&s->gb, 2);
+
+    blownup = get_bits1(&s->gb);
+    header_size = get_bits(&s->gb, 8 + 4 * blownup) + 1;
+    hd_size = get_bits_long(&s->gb, 16 + 4 * blownup) + 1;
+
+    s->static_fields = get_bits1(&s->gb);
+    if (s->static_fields) {
+        skip_bits(&s->gb, 2); // reference clock code
+        skip_bits(&s->gb, 3); // frame duration code
+
+        if (get_bits1(&s->gb))
+            skip_bits_long(&s->gb, 36); // timestamp
+
+        /* a single stream can contain multiple audio assets that can be
+         * combined to form multiple audio presentations */
+
+        num_audiop = get_bits(&s->gb, 3) + 1;
+        if (num_audiop > 1) {
+            av_log_ask_for_sample(s->avctx, "Multiple DTS-HD audio presentations.");
+            /* ignore such streams for now */
+            return;
+        }
+
+        num_assets = get_bits(&s->gb, 3) + 1;
+        if (num_assets > 1) {
+            av_log_ask_for_sample(s->avctx, "Multiple DTS-HD audio assets.");
+            /* ignore such streams for now */
+            return;
+        }
+
+        for (i = 0; i < num_audiop; i++)
+            active_ss_mask[i] = get_bits(&s->gb, ss_index + 1);
+
+        for (i = 0; i < num_audiop; i++)
+            for (j = 0; j <= ss_index; j++)
+                if (active_ss_mask[i] & (1 << j))
+                    skip_bits(&s->gb, 8); // active asset mask
+
+        s->mix_metadata = get_bits1(&s->gb);
+        if (s->mix_metadata) {
+            int mix_out_mask_size;
+
+            skip_bits(&s->gb, 2); // adjustment level
+            mix_out_mask_size = (get_bits(&s->gb, 2) + 1) << 2;
+            s->num_mix_configs = get_bits(&s->gb, 2) + 1;
+
+            for (i = 0; i < s->num_mix_configs; i++) {
+                int mix_out_mask = get_bits(&s->gb, mix_out_mask_size);
+                s->mix_config_num_ch[i] = dca_exss_mask2count(mix_out_mask);
+            }
+        }
+    }
+
+    for (i = 0; i < num_assets; i++)
+        skip_bits_long(&s->gb, 16 + 4 * blownup); // asset size
+
+    for (i = 0; i < num_assets; i++) {
+        if (dca_exss_parse_asset_header(s))
+            return;
+    }
+
+    /* not parsed further, we were only interested in the extensions mask
+     * from the asset header */
+}
+
+/**
  * Main frame decoding function
  * FIXME add arguments
  */
@@ -1203,13 +1623,19 @@ static int dca_decode_frame(AVCodecContext * avctx,
     const uint8_t *buf = avpkt->data;
     int buf_size = avpkt->size;
 
+    int lfe_samples;
+    int num_core_channels = 0;
     int i;
     int16_t *samples = data;
     DCAContext *s = avctx->priv_data;
     int channels;
+    int core_ss_end;
 
 
-    s->dca_buffer_size = dca_convert_bitstream(buf, buf_size, s->dca_buffer, DCA_MAX_FRAME_SIZE);
+    s->xch_present = 0;
+
+    s->dca_buffer_size = dca_convert_bitstream(buf, buf_size, s->dca_buffer,
+                                               DCA_MAX_FRAME_SIZE + DCA_MAX_EXSS_HEADER_SIZE);
     if (s->dca_buffer_size == -1) {
         av_log(avctx, AV_LOG_ERROR, "Not a valid DCA frame\n");
         return -1;
@@ -1225,25 +1651,145 @@ static int dca_decode_frame(AVCodecContext * avctx,
     avctx->sample_rate = s->sample_rate;
     avctx->bit_rate = s->bit_rate;
 
+    s->profile = FF_PROFILE_DTS;
+
+    for (i = 0; i < (s->sample_blocks / 8); i++) {
+        dca_decode_block(s, 0, i);
+    }
+
+    /* record number of core channels incase less than max channels are requested */
+    num_core_channels = s->prim_channels;
+
+    if (s->ext_coding)
+        s->core_ext_mask = dca_ext_audio_descr_mask[s->ext_descr];
+    else
+        s->core_ext_mask = 0;
+
+    core_ss_end = FFMIN(s->frame_size, s->dca_buffer_size) * 8;
+
+    /* only scan for extensions if ext_descr was unknown or indicated a
+     * supported XCh extension */
+    if (s->core_ext_mask < 0 || s->core_ext_mask & DCA_EXT_XCH) {
+
+        /* if ext_descr was unknown, clear s->core_ext_mask so that the
+         * extensions scan can fill it up */
+        s->core_ext_mask = FFMAX(s->core_ext_mask, 0);
+
+        /* extensions start at 32-bit boundaries into bitstream */
+        skip_bits_long(&s->gb, (-get_bits_count(&s->gb)) & 31);
+
+    while(core_ss_end - get_bits_count(&s->gb) >= 32) {
+        uint32_t bits = get_bits_long(&s->gb, 32);
+
+        switch(bits) {
+        case 0x5a5a5a5a: {
+            int ext_amode, xch_fsize;
+
+            s->xch_base_channel = s->prim_channels;
+
+            /* validate sync word using XCHFSIZE field */
+            xch_fsize = show_bits(&s->gb, 10);
+            if((s->frame_size != (get_bits_count(&s->gb) >> 3) - 4 + xch_fsize) &&
+               (s->frame_size != (get_bits_count(&s->gb) >> 3) - 4 + xch_fsize + 1))
+                continue;
+
+            /* skip length-to-end-of-frame field for the moment */
+            skip_bits(&s->gb, 10);
+
+            s->core_ext_mask |= DCA_EXT_XCH;
+
+            /* extension amode should == 1, number of channels in extension */
+            /* AFAIK XCh is not used for more channels */
+            if ((ext_amode = get_bits(&s->gb, 4)) != 1) {
+                av_log(avctx, AV_LOG_ERROR, "XCh extension amode %d not"
+                       " supported!\n",ext_amode);
+                continue;
+            }
+
+            /* much like core primary audio coding header */
+            dca_parse_audio_coding_header(s, s->xch_base_channel);
+
+            for (i = 0; i < (s->sample_blocks / 8); i++) {
+                dca_decode_block(s, s->xch_base_channel, i);
+            }
+
+            s->xch_present = 1;
+            break;
+        }
+        case 0x47004a03:
+            /* XXCh: extended channels */
+            /* usually found either in core or HD part in DTS-HD HRA streams,
+             * but not in DTS-ES which contains XCh extensions instead */
+            s->core_ext_mask |= DCA_EXT_XXCH;
+            break;
+
+        case 0x1d95f262: {
+            int fsize96 = show_bits(&s->gb, 12) + 1;
+            if (s->frame_size != (get_bits_count(&s->gb) >> 3) - 4 + fsize96)
+                continue;
+
+            av_log(avctx, AV_LOG_DEBUG, "X96 extension found at %d bits\n", get_bits_count(&s->gb));
+            skip_bits(&s->gb, 12);
+            av_log(avctx, AV_LOG_DEBUG, "FSIZE96 = %d bytes\n", fsize96);
+            av_log(avctx, AV_LOG_DEBUG, "REVNO = %d\n", get_bits(&s->gb, 4));
+
+            s->core_ext_mask |= DCA_EXT_X96;
+            break;
+        }
+        }
+
+        skip_bits_long(&s->gb, (-get_bits_count(&s->gb)) & 31);
+    }
+
+    } else {
+        /* no supported extensions, skip the rest of the core substream */
+        skip_bits_long(&s->gb, core_ss_end - get_bits_count(&s->gb));
+    }
+
+    if (s->core_ext_mask & DCA_EXT_X96)
+        s->profile = FF_PROFILE_DTS_96_24;
+    else if (s->core_ext_mask & (DCA_EXT_XCH | DCA_EXT_XXCH))
+        s->profile = FF_PROFILE_DTS_ES;
+
+    /* check for ExSS (HD part) */
+    if (s->dca_buffer_size - s->frame_size > 32
+        && get_bits_long(&s->gb, 32) == DCA_HD_MARKER)
+        dca_exss_parse_header(s);
+
+    avctx->profile = s->profile;
+
     channels = s->prim_channels + !!s->lfe;
 
     if (s->amode<16) {
         avctx->channel_layout = dca_core_channel_layout[s->amode];
 
-        if (s->lfe) {
-            avctx->channel_layout |= CH_LOW_FREQUENCY;
-            s->channel_order_tab = dca_channel_reorder_lfe[s->amode];
-        } else
-            s->channel_order_tab = dca_channel_reorder_nolfe[s->amode];
+        if (s->xch_present && (!avctx->request_channels ||
+                               avctx->request_channels > num_core_channels + !!s->lfe)) {
+            avctx->channel_layout |= AV_CH_BACK_CENTER;
+            if (s->lfe) {
+                avctx->channel_layout |= AV_CH_LOW_FREQUENCY;
+                s->channel_order_tab = dca_channel_reorder_lfe_xch[s->amode];
+            } else {
+                s->channel_order_tab = dca_channel_reorder_nolfe_xch[s->amode];
+            }
+        } else {
+            channels = num_core_channels + !!s->lfe;
+            s->xch_present = 0; /* disable further xch processing */
+            if (s->lfe) {
+                avctx->channel_layout |= AV_CH_LOW_FREQUENCY;
+                s->channel_order_tab = dca_channel_reorder_lfe[s->amode];
+            } else
+                s->channel_order_tab = dca_channel_reorder_nolfe[s->amode];
+        }
 
-        if (s->prim_channels > 0 &&
-            s->channel_order_tab[s->prim_channels - 1] < 0)
+        if (channels > !!s->lfe &&
+            s->channel_order_tab[channels - 1 - !!s->lfe] < 0)
             return -1;
 
-        if(avctx->request_channels == 2 && s->prim_channels > 2) {
+        if (avctx->request_channels == 2 && s->prim_channels > 2) {
             channels = 2;
             s->output = DCA_STEREO;
-            avctx->channel_layout = CH_LAYOUT_STEREO;
+            avctx->channel_layout = AV_CH_LAYOUT_STEREO;
         }
     } else {
         av_log(avctx, AV_LOG_ERROR, "Non standard configuration %d !\n",s->amode);
@@ -1256,18 +1802,47 @@ static int dca_decode_frame(AVCodecContext * avctx,
        unset. Ideally during the first probe for channels the crc should be checked
        and only set avctx->channels when the crc is ok. Right now the decoder could
        set the channels based on a broken first frame.*/
-    if (!avctx->channels)
+    if (s->is_channels_set == 0) {
+        s->is_channels_set = 1;
         avctx->channels = channels;
+    }
+    if (avctx->channels != channels) {
+        av_log(avctx, AV_LOG_ERROR, "DCA decoder does not support number of "
+               "channels changing in stream. Skipping frame.\n");
+        return -1;
+    }
 
-    if(*data_size < (s->sample_blocks / 8) * 256 * sizeof(int16_t) * channels)
+    if (*data_size < (s->sample_blocks / 8) * 256 * sizeof(int16_t) * channels)
         return -1;
     *data_size = 256 / 8 * s->sample_blocks * sizeof(int16_t) * channels;
+
+    /* filter to get final output */
     for (i = 0; i < (s->sample_blocks / 8); i++) {
-        dca_decode_block(s);
-        s->dsp.float_to_int16_interleave(samples, s->samples_chanptr, 256, channels);
+        dca_filter_channels(s, i);
+
+        /* If this was marked as a DTS-ES stream we need to subtract back- */
+        /* channel from SL & SR to remove matrixed back-channel signal */
+        if((s->source_pcm_res & 1) && s->xch_present) {
+            float* back_chan = s->samples + s->channel_order_tab[s->xch_base_channel] * 256;
+            float* lt_chan   = s->samples + s->channel_order_tab[s->xch_base_channel - 2] * 256;
+            float* rt_chan   = s->samples + s->channel_order_tab[s->xch_base_channel - 1] * 256;
+            int j;
+            for(j = 0; j < 256; ++j) {
+                lt_chan[j] -= back_chan[j] * M_SQRT1_2;
+                rt_chan[j] -= back_chan[j] * M_SQRT1_2;
+            }
+        }
+
+        s->fmt_conv.float_to_int16_interleave(samples, s->samples_chanptr, 256, channels);
         samples += 256 * channels;
     }
 
+    /* update lfe history */
+    lfe_samples = 2 * s->lfe * (s->sample_blocks / 8);
+    for (i = 0; i < 2 * s->lfe * 4; i++) {
+        s->lfe_data[i] = s->lfe_data[i + lfe_samples];
+    }
+
     return buf_size;
 }
 
@@ -1291,26 +1866,20 @@ static av_cold int dca_decode_init(AVCodecContext * avctx)
     ff_mdct_init(&s->imdct, 6, 1, 1.0);
     ff_synth_filter_init(&s->synth);
     ff_dcadsp_init(&s->dcadsp);
+    ff_fmt_convert_init(&s->fmt_conv, avctx);
 
-    for(i = 0; i < 6; i++)
+    for (i = 0; i < DCA_PRIM_CHANNELS_MAX+1; i++)
         s->samples_chanptr[i] = s->samples + i * 256;
-    avctx->sample_fmt = SAMPLE_FMT_S16;
+    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
 
-    if(s->dsp.float_to_int16_interleave == ff_float_to_int16_interleave_c) {
-        s->add_bias = 385.0f;
-        s->scale_bias = 1.0 / 32768.0;
-    } else {
-        s->add_bias = 0.0f;
-        s->scale_bias = 1.0;
+    s->scale_bias = 1.0;
 
-        /* allow downmixing to stereo */
-        if (avctx->channels > 0 && avctx->request_channels < avctx->channels &&
-                avctx->request_channels == 2) {
-            avctx->channels = avctx->request_channels;
-        }
+    /* allow downmixing to stereo */
+    if (avctx->channels > 0 && avctx->request_channels < avctx->channels &&
+        avctx->request_channels == 2) {
+        avctx->channels = avctx->request_channels;
     }
 
-
     return 0;
 }
 
@@ -1321,7 +1890,16 @@ static av_cold int dca_decode_end(AVCodecContext * avctx)
     return 0;
 }
 
-AVCodec dca_decoder = {
+static const AVProfile profiles[] = {
+    { FF_PROFILE_DTS,        "DTS"        },
+    { FF_PROFILE_DTS_ES,     "DTS-ES"     },
+    { FF_PROFILE_DTS_96_24,  "DTS 96/24"  },
+    { FF_PROFILE_DTS_HD_HRA, "DTS-HD HRA" },
+    { FF_PROFILE_DTS_HD_MA,  "DTS-HD MA"  },
+    { FF_PROFILE_UNKNOWN },
+};
+
+AVCodec ff_dca_decoder = {
     .name = "dca",
     .type = AVMEDIA_TYPE_AUDIO,
     .id = CODEC_ID_DTS,
@@ -1330,4 +1908,6 @@ AVCodec dca_decoder = {
     .decode = dca_decode_frame,
     .close = dca_decode_end,
     .long_name = NULL_IF_CONFIG_SMALL("DCA (DTS Coherent Acoustics)"),
+    .capabilities = CODEC_CAP_CHANNEL_CONF,
+    .profiles = NULL_IF_CONFIG_SMALL(profiles),
 };
diff --git a/libavcodec/dca.h b/libavcodec/dca.h
index 02c0a51..8ea6049 100644
--- a/libavcodec/dca.h
+++ b/libavcodec/dca.h
@@ -5,20 +5,20 @@
  * Copyright (C) 2006 Benjamin Larsson
  * Copyright (C) 2007 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/dca_parser.c b/libavcodec/dca_parser.c
index 01c5597..70a3e98 100644
--- a/libavcodec/dca_parser.c
+++ b/libavcodec/dca_parser.c
@@ -5,20 +5,20 @@
  * Copyright (C) 2006 Benjamin Larsson
  * Copyright (C) 2007 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -125,7 +125,7 @@ static int dca_parse(AVCodecParserContext * s,
     return next;
 }
 
-AVCodecParser dca_parser = {
+AVCodecParser ff_dca_parser = {
     {CODEC_ID_DTS},
     sizeof(DCAParseContext),
     dca_parse_init,
diff --git a/libavcodec/dcadata.h b/libavcodec/dcadata.h
index fbd22ab..ed3ec4e 100644
--- a/libavcodec/dcadata.h
+++ b/libavcodec/dcadata.h
@@ -3,20 +3,20 @@
  * Copyright (C) 2004 Gildas Bazin
  * Copyright (c) 2006 Benjamin Larsson
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -60,4102 +60,4102 @@ static const uint8_t dca_bits_per_sample[7] =
 /* 16bits signed fractional Q13 binary codes */
 static const int16_t adpcm_vb[4096][4] =
 {
-  { 9928, -2618, -1093, -1263 },
-  { 11077, -2876, -1747, -308 },
-  { 10503, -1082, -1426, -1167 },
-  { 9337, -2403, -1495, 274 },
-  { 10698, -2529, -532, -1122 },
-  { 10368, -3974, -1264, -750 },
-  { 10070, -3667, 346, 863 },
-  { 10278, -3093, 311, -576 },
-  { 9894, -1330, -1428, -860 },
-  { 10544, -1923, -1058, -971 },
-  { 10996, -1632, -841, -1404 },
-  { 11832, -3465, 1658, -1990 },
-  { 10852, -688, -2658, -499 },
-  { 10546, -1749, -147, -1733 },
-  { 10801, -1004, -708, -1453 },
-  { 10588, -441, -2113, -952 },
-  { 10141, -3331, -582, -1432 },
-  { 9608, -2590, 383, 258 },
-  { 11422, -3265, 229, -1544 },
-  { 10460, -1338, -713, -1568 },
-  { 10306, -1721, -1660, -603 },
-  { 9580, -1812, -1235, -1061 },
-  { 11471, -2285, -1617, -607 },
-  { 10081, -2225, -1408, -868 },
-  { 10715, -2624, -1367, -704 },
-  { 10616, -1871, -2770, -35 },
-  { 9352, -2340, -1024, -1566 },
-  { 11065, -1458, -1926, -735 },
-  { 11334, -2056, -1041, -1144 },
-  { 9825, -2048, -794, -1536 },
-  { 11850, -2695, -1123, -867 },
-  { 10654, -2226, -1891, -373 },
-  { 10024, -1557, -808, -1069 },
-  { 11142, -1266, -3238, 128 },
-  { 11729, -3282, -514, -1011 },
-  { 11402, -2094, -2335, -189 },
-  { 10195, -3658, 181, -1875 },
-  { 11431, -2626, -404, -1377 },
-  { 11001, -3868, -619, -1077 },
-  { 10894, -2559, 274, -1758 },
-  { 9633, -1482, -2253, -773 },
-  { 11245, -3321, 830, -1972 },
-  { 9768, -2701, -199, -1859 },
-  { 10500, -2042, 525, -2043 },
-  { 11669, -4069, 293, -1468 },
-  { 9192, -1991, -583, -61 },
-  { 10057, -3220, -2015, -473 },
-  { 9497, -2315, -2490, -467 },
-  { 10455, -3069, -1194, -1007 },
-  { 9994, -1936, -60, -1225 },
-  { 9295, -2156, -1761, -1134 },
-  { 10085, -3748, -1026, 197 },
-  { 9334, -2360, 804, -351 },
-  { 11561, -2553, 1352, -2313 },
-  { 12837, -3998, 1195, -1958 },
-  { 10114, -1100, -2414, -394 },
-  { 9341, -2530, 315, 755 },
-  { 10131, -3164, 1411, -674 },
-  { 9535, -905, -1551, 579 },
-  { 11717, -1519, -3051, 91 },
-  { 9824, -2911, -2775, 192 },
-  { 9662, -2934, -561, 1450 },
-  { 11085, -3392, -1298, -659 },
-  { 8955, -2102, -1899, 703 },
-  { 8607, -1742, -4348, 814 },
-  { 7640, -2063, -3617, 52 },
-  { 7074, -826, -4325, 4375 },
-  { 7714, 584, -4238, 1927 },
-  { 6355, -952, -4912, 3127 },
-  { 7069, -660, -6413, 4087 },
-  { 8313, -132, -2964, -876 },
-  { 6952, -1422, -3962, -24 },
-  { 9299, -734, -3088, -263 },
-  { 9484, -574, -4513, 466 },
-  { 7246, -91, -3735, -704 },
-  { 8325, -1417, -3090, -530 },
-  { 6469, -1226, -4757, 829 },
-  { 6652, -368, -5682, 1393 },
-  { 7971, -1278, -2284, 1205 },
-  { 7229, -699, -3556, 1840 },
-  { 7994, 1284, -2729, 732 },
-  { 9005, -698, -4522, 2189 },
-  { 6963, 197, -2727, 380 },
-  { 8527, 135, -3991, -213 },
-  { 8840, 934, -3014, -567 },
-  { 10125, 418, -3284, -371 },
-  { 6367, 361, -2318, 2554 },
-  { 7892, 172, -5247, 4673 },
-  { 6674, 387, -5424, 4398 },
-  { 6240, 684, -4047, 1219 },
-  { 11170, -794, -5081, 1195 },
-  { 11765, -648, -6265, 2052 },
-  { 10845, -775, -3837, 366 },
-  { 12496, -689, -8260, 3562 },
-  { 7893, -1166, -4972, 988 },
-  { 8592, 1052, -5986, 3087 },
-  { 7277, 1874, -5685, 3579 },
-  { 6900, 2016, -4809, 3491 },
-  { 8530, -2405, -3250, 1986 },
-  { 9426, 494, -7067, 5038 },
-  { 10285, 564, -8210, 5370 },
-  { 8749, -2207, -3980, 2852 },
-  { 9653, -2686, -4300, 1400 },
-  { 9770, -2286, -5663, 4233 },
-  { 8490, -4, -7048, 4496 },
-  { 7697, -1209, -5328, 3183 },
-  { 6451, 801, -4324, -554 },
-  { 7387, 1806, -5265, 545 },
-  { 7450, -2302, -4445, 1418 },
-  { 8817, -1370, -5827, 2168 },
-  { 10324, -2406, -5629, 2579 },
-  { 8863, -2578, -3537, 467 },
-  { 6901, -1624, -3169, 3392 },
-  { 7846, 156, -6948, 3381 },
-  { 7928, -1115, -5972, 4816 },
-  { 6089, -599, -4368, -320 },
-  { 7833, 1246, -3960, -621 },
-  { 8931, 2521, -6768, 2052 },
-  { 8900, 1944, -4126, 40 },
-  { 7661, -34, -2855, 2480 },
-  { 5873, 474, -3262, 3712 },
-  { 7535, -234, -4699, 216 },
-  { 5856, 143, -5142, 73 },
-  { 8944, -106, -5874, 3663 },
-  { 7134, 426, -5879, 2895 },
-  { 10199, 1011, -4762, 369 },
-  { 8454, 264, -5971, 1291 },
-  { 7822, -2449, -4333, 4540 },
-  { 6200, -2758, -2632, 1497 },
-  { 6070, -4315, -2699, 414 },
-  { 7047, -3739, -3210, 1060 },
-  { 5675, -3801, -2717, -407 },
-  { 4789, -4063, -2628, -744 },
-  { 4023, -3366, -3133, -726 },
-  { 4296, -2407, -3381, -513 },
-  { 4388, -2931, -2820, 1512 },
-  { 4559, -4233, -1941, 1976 },
-  { 6702, -3208, -1755, 1680 },
-  { 4416, -3521, -1052, 2984 },
-  { 7154, -4266, -1203, 3732 },
-  { 3625, -4242, -3244, 1395 },
-  { 6518, -2856, -1304, 2887 },
-  { 6170, -1949, -3014, 3973 },
-  { 5189, -2451, -4020, 3477 },
-  { 6218, -2988, -1921, 3844 },
-  { 4827, -3688, -1928, 3343 },
-  { 6668, -3991, -2805, 3095 },
-  { 5297, -3115, -3684, 2390 },
-  { 5354, -4614, -2662, 1504 },
-  { 4196, -3091, -4147, 1135 },
-  { 3540, -2893, -4007, 100 },
-  { 5569, -1602, -4007, 1909 },
-  { 4341, -2091, -4272, 252 },
-  { 5559, -2878, -3832, 498 },
-  { 4548, -4479, -2898, -27 },
-  { 5176, -2494, -4635, 1476 },
-  { 3294, -3485, -3738, 716 },
-  { 4920, -1229, -4195, -365 },
-  { 3257, -3518, -3349, 2862 },
-  { 5286, -1948, -3485, -778 },
-  { 6502, -3051, -152, 2854 },
-  { 5864, -4192, -1076, 3451 },
-  { 4656, -3122, -3448, 179 },
-  { 5907, -754, -1596, 3116 },
-  { 7229, -3680, -1590, 2892 },
-  { 5107, -3888, -3364, 806 },
-  { 6764, -2635, -3450, 134 },
-  { 5258, -2827, -2844, -1052 },
-  { 5798, -1725, -4305, 205 },
-  { 5404, -1213, -3362, 449 },
-  { 6224, -2738, -3046, -581 },
-  { 4223, -2438, -2725, 3745 },
-  { 4751, -3411, -2123, 116 },
-  { 3868, -3000, -3954, 2297 },
-  { 6819, -2899, -4277, 2825 },
-  { 4207, -4754, -2808, 865 },
-  { 4804, -1494, -1997, 4688 },
-  { 5282, -2213, -548, 3559 },
-  { 5580, -1912, -566, 4370 },
-  { 6168, -2857, -672, 4053 },
-  { 6583, -4515, -2850, 1670 },
-  { 6511, -3093, -3988, 1421 },
-  { 4646, -1790, -1443, 3650 },
-  { 5915, -924, -2020, 896 },
-  { 7814, -4181, -3152, 2007 },
-  { 6190, -2238, -4817, 2279 },
-  { 4737, -4034, -3288, 1835 },
-  { 8161, -3633, -3423, 3137 },
-  { 7415, -2351, -2088, 4290 },
-  { 4106, -2517, -62, 2905 },
-  { 4909, -3145, -614, 4112 },
-  { 4938, -3281, -397, 1100 },
-  { -173, 919, 1589, -5363 },
-  { -13, 796, -295, -6655 },
-  { -1860, -829, 1141, -4555 },
-  { 2298, -838, -664, -5005 },
-  { -884, -1097, 2074, -4613 },
-  { -101, 281, 2846, -4535 },
-  { 1166, 453, 2429, -5910 },
-  { 879, -664, 2370, -5452 },
-  { 1415, -370, -1699, -4727 },
-  { -1413, 1277, -669, -6649 },
-  { 2133, 304, -968, -4624 },
-  { 380, 586, -2087, -4892 },
-  { 1336, 275, -82, -5789 },
-  { -2459, 1057, -34, -5416 },
-  { 2278, -1758, 866, -5653 },
-  { 1945, -2295, -149, -5302 },
-  { 1287, -3525, 996, -5255 },
-  { 2297, 803, 1177, -6067 },
-  { 187, -180, -619, -6202 },
-  { -793, -2537, 1554, -5057 },
-  { -2703, -204, -629, -5853 },
-  { -1007, -146, 313, -5582 },
-  { 830, 357, 869, -6363 },
-  { -228, -575, -3177, -4433 },
-  { -1001, -1553, -142, -5708 },
-  { -1644, 1683, 1721, -4533 },
-  { 893, 1924, -15, -5791 },
-  { 2195, 2061, -262, -5471 },
-  { 3031, 270, 311, -5096 },
-  { 1912, 1638, -1523, -4677 },
-  { -3142, -55, 253, -4914 },
-  { 356, -1680, 343, -6123 },
-  { -2241, -1734, -976, -5939 },
-  { -2196, -2893, 547, -4938 },
-  { -1245, 126, -1916, -5419 },
-  { -249, -3755, -1422, -5594 },
-  { 575, -2683, -1926, -4566 },
-  { -762, 1885, 192, -5880 },
-  { -811, -2562, -1068, -6013 },
-  { -2264, -3086, -976, -4775 },
-  { 70, -1215, 2880, -4410 },
-  { 714, -3760, 2916, -4691 },
-  { -244, -3404, 1740, -4493 },
-  { 684, -5137, -328, -5608 },
-  { -529, -3825, -1786, -4535 },
-  { -713, -4743, -1118, -5546 },
-  { 2718, -3788, 1798, -5708 },
-  { -1639, -3679, -1564, -6095 },
-  { 1693, -2642, -1389, -4539 },
-  { 505, -1573, -1651, -4878 },
-  { -835, -2256, -1941, -5352 },
-  { 1464, -411, 1993, -6441 },
-  { 493, -3184, -145, -6148 },
-  { -1413, 499, -1617, -6479 },
-  { -294, 1722, -1419, -5725 },
-  { -2937, -1528, -175, -4624 },
-  { -594, -5911, -56, -6146 },
-  { -300, -4275, 1156, -5947 },
-  { 552, -2643, 2669, -3959 },
-  { 905, -4158, 1789, -5809 },
-  { 1336, -2009, 2108, -5903 },
-  { 1555, -3600, 1110, -6759 },
-  { -1294, -3464, 77, -6084 },
-  { -1139, -4006, -1270, -4181 },
-  { -5094, -3296, 1092, -2847 },
-  { -5503, -2883, 1984, -2067 },
-  { -4671, -4218, -1417, -4132 },
-  { -3763, -3818, 1262, -3082 },
-  { -5132, -3430, 2928, -728 },
-  { -5957, -2877, 1251, -2446 },
-  { -4425, -2319, -212, -4276 },
-  { -6201, -1993, 1774, -2182 },
-  { -5500, -3836, 2201, -1396 },
-  { -6934, -2334, 2366, -1293 },
-  { -6124, -4140, 1337, -1977 },
-  { -6553, -4186, 1756, -1325 },
-  { -5126, -1258, 744, -3656 },
-  { -5167, -1390, 1581, -2895 },
-  { -4525, -3398, 2429, -1865 },
-  { -4076, -3183, 2027, -2510 },
-  { -6191, -3274, 1838, -1814 },
-  { -4454, -2753, 2723, -1185 },
-  { -6655, -4797, 251, -2595 },
-  { -6332, -2232, 1832, 217 },
-  { -5869, -1698, 134, 340 },
-  { -6614, -1045, 2126, -1932 },
-  { -4859, -2107, 2010, -2435 },
-  { -6274, -1622, 2808, -1374 },
-  { -3119, -3209, 521, -3988 },
-  { -5676, -2082, -420, -2711 },
-  { -7073, -3623, 696, -2343 },
-  { -5986, -4224, 572, -2454 },
-  { -4340, -4521, 882, -2771 },
-  { -6178, -1933, 535, -1444 },
-  { -4923, -4163, 1744, -2066 },
-  { -6410, -1519, 1058, -2683 },
-  { -5077, -1185, 856, -2216 },
-  { -7091, -2444, 687, -2597 },
-  { -5284, -2165, 3239, -993 },
-  { -4763, -1497, 197, -3179 },
-  { -4128, -4958, -396, -3578 },
-  { -5054, -3878, -647, -2672 },
-  { -7005, -3348, 1679, -1579 },
-  { -5767, -1017, 2582, -1915 },
-  { -7069, -2787, 1331, -2070 },
-  { -5532, -2296, 706, -2950 },
-  { -5059, -3543, -821, -3637 },
-  { -6639, -1835, 1016, -696 },
-  { -5611, -5220, -694, -3371 },
-  { -5994, -2803, 2933, -729 },
-  { -5948, -619, 1596, -2676 },
-  { -5486, -4419, 153, -3265 },
-  { -4329, -3440, 1646, -1439 },
-  { -4083, -3978, 177, -3569 },
-  { -4289, -2599, 1224, -3075 },
-  { -5707, -3253, 1912, -759 },
-  { -6606, -3437, 2562, -571 },
-  { -5254, -2444, 769, -352 },
-  { -6545, -3154, 582, -1103 },
-  { -5328, -2241, 2566, -1775 },
-  { -7216, -1936, 1538, -1983 },
-  { -3730, -2451, 426, -3869 },
-  { -5110, -1385, 2031, -1169 },
-  { -6470, -2715, 269, -3123 },
-  { -5806, -2480, -97, -3832 },
-  { -3683, -4916, -490, -4330 },
-  { -6341, -2083, -669, -115 },
-  { -4913, -4079, -837, -4673 },
-  { -3274, -2497, 2334, -2652 },
-  { -1286, -1731, 2550, -3756 },
-  { -3375, -877, 926, -3977 },
-  { -2525, -2079, 2879, -2625 },
-  { -5308, -504, 3111, -1607 },
-  { -4904, 460, 4093, -1232 },
-  { -1993, 1616, 4656, -1913 },
-  { -3481, -1176, 3119, -2236 },
-  { -4132, -1502, 2339, -2545 },
-  { -2542, 1151, 3569, -2550 },
-  { -4381, 430, 3147, -2082 },
-  { -3888, 867, 3899, -1657 },
-  { -2861, 1290, 4202, -1979 },
-  { -3893, -253, 2363, -2764 },
-  { -1705, 688, 3827, -2923 },
-  { -2223, 2312, 3700, -3148 },
-  { -1986, -720, 5021, -795 },
-  { -3177, 242, 1952, -3352 },
-  { -1854, 1509, 2528, -3815 },
-  { -3173, 97, 5019, -706 },
-  { -2689, -145, 1375, -3915 },
-  { -4838, -385, 2488, -2427 },
-  { -4557, -355, 1603, -3060 },
-  { -3522, 1832, 3292, -2674 },
-  { -3769, 780, 2378, -2704 },
-  { -4323, -1932, 3414, -1169 },
-  { -2740, 1158, 2729, -3273 },
-  { -3647, 210, 1464, -2892 },
-  { -2342, -2097, 1513, -3727 },
-  { -4422, -1242, 3130, -1833 },
-  { -1308, -1039, 4290, -1875 },
-  { -1754, -2535, 3298, -2314 },
-  { -4102, -186, 4037, -1094 },
-  { -1008, 1570, 3290, 171 },
-  { -3322, -2621, 2791, -1536 },
-  { -2539, -2597, 3442, -1672 },
-  { -3411, -2015, 3670, -1174 },
-  { -2097, 730, 5581, -1399 },
-  { -1510, -74, 4820, -2004 },
-  { -4086, -868, 4425, -771 },
-  { -956, -986, 3640, -2925 },
-  { -2087, -1250, 3464, -2458 },
-  { -3308, -2411, 1334, -3667 },
-  { -2264, -389, 4004, -1854 },
-  { -680, 239, 4058, -3388 },
-  { -1357, 30, 2993, -3658 },
-  { -3601, -552, 1177, -1136 },
-  { -2641, 442, 4374, -1625 },
-  { -2525, 770, 1640, -3895 },
-  { -3172, -891, 3893, -1608 },
-  { -2996, 13, 3277, -2414 },
-  { -899, 1055, 4470, -2501 },
-  { -422, -584, 3475, -3787 },
-  { -1978, -593, 2566, -3415 },
-  { -3150, -1280, 2362, -3047 },
-  { -3592, 224, 1026, -3932 },
-  { -4840, -1189, 3633, -879 },
-  { -3952, -2255, 2916, -1826 },
-  { -1695, 28, 1810, -349 },
-  { -745, -2484, 3308, -3293 },
-  { -1016, 1563, 5365, -1823 },
-  { -2172, -1787, 4266, -1287 },
-  { -1241, -1951, 3982, -2413 },
-  { -2009, -2639, 2330, -3480 },
-  { 5105, -1618, -2588, -2015 },
-  { 6497, -1523, -3218, -910 },
-  { 6526, -2305, -2029, -1790 },
-  { 5289, -99, -3436, -400 },
-  { 5781, -1623, -1577, -2617 },
-  { 5259, -670, -3125, -1700 },
-  { 6343, -1256, -331, -3222 },
-  { 7967, -678, -2195, -1462 },
-  { 6119, -695, -2988, -1538 },
-  { 6108, 494, -3359, -1548 },
-  { 5067, 969, -2328, -2707 },
-  { 7595, -435, -1497, -2056 },
-  { 6929, -719, -2420, -1665 },
-  { 5190, 584, -2982, -2103 },
-  { 6106, -444, -1411, -2739 },
-  { 5584, 289, -1804, -2803 },
-  { 5276, 227, -1180, -3361 },
-  { 7544, -1525, -1834, -1725 },
-  { 5986, -1470, -2606, -1701 },
-  { 5096, -765, -1712, -3006 },
-  { 5423, -149, -3933, -1157 },
-  { 7651, 26, -2445, -1507 },
-  { 4745, -464, -1735, -2362 },
-  { 5352, -1011, -1094, -1999 },
-  { 6300, -672, -542, -1950 },
-  { 6675, -1020, -1318, -1059 },
-  { 7218, -2036, -603, -2462 },
-  { 7755, -1514, -2430, -1229 },
-  { 5041, 449, -1056, -2405 },
-  { 6710, -2277, -1344, -2284 },
-  { 6824, -1347, -2254, 251 },
-  { 6068, -1857, -983, -1316 },
-  { 5603, -2177, -2730, -1477 },
-  { 5838, -1059, -3604, -970 },
-  { 5076, -789, -335, -2413 },
-  { 6191, -1634, -2000, -2129 },
-  { 5092, -1292, -2543, -1034 },
-  { 5305, 435, -1710, -1850 },
-  { 6140, 561, -2176, -2380 },
-  { 6752, 348, -2496, -1890 },
-  { 6405, 273, -1098, -2778 },
-  { 6942, -1340, -496, -1381 },
-  { 5238, -687, -2454, -2349 },
-  { 6959, -882, -1833, -2061 },
-  { 6292, -253, -2125, -2199 },
-  { 5838, -574, -759, -3215 },
-  { 6954, -1484, -640, -2771 },
-  { 7498, -1706, -1210, -2154 },
-  { 6772, -1003, -1235, -2532 },
-  { 6014, 228, -2154, -1108 },
-  { 6943, -2178, -2644, -1122 },
-  { 7262, -763, -3056, -1090 },
-  { 6273, -1478, -1072, 177 },
-  { 4734, 425, -2912, 357 },
-  { 7129, 168, -1537, -2327 },
-  { 7204, -434, -746, -2660 },
-  { 6879, 57, -3087, -1310 },
-  { 4623, -610, -718, -3459 },
-  { 6565, -543, -1998, -339 },
-  { 4752, -277, -2066, -1405 },
-  { 7435, -1416, -1904, -505 },
-  { 4076, 150, -1222, -3556 },
-  { 7082, -28, -1456, -1174 },
-  { 5941, -446, -1326, -1158 },
-  { 3870, -1648, -2474, -2589 },
-  { 858, 37, -3387, -3721 },
-  { 3557, -1503, -1664, -3383 },
-  { 3336, -1972, -3079, -2216 },
-  { 3186, 60, -4185, -863 },
-  { 3456, -773, -3066, -2457 },
-  { 4131, -913, -2060, -2601 },
-  { 4431, -691, -4114, -972 },
-  { 3461, -334, -3680, -1751 },
-  { 2006, -459, -2214, -3827 },
-  { 1322, 32, -2816, -3203 },
-  { 4425, -1897, -2791, -1946 },
-  { 4504, 23, -3421, -1909 },
-  { 3090, -885, -2366, -3264 },
-  { 3209, -2363, -3730, -834 },
-  { 3312, -1471, -3641, -1579 },
-  { 4184, -1669, -3323, -1248 },
-  { 2190, -931, -3302, -2944 },
-  { 2947, -229, -4791, -1195 },
-  { 2020, -1626, -2700, -3125 },
-  { 2214, -326, -4352, -1683 },
-  { 3286, -2619, -2412, -2458 },
-  { 1000, -2571, -4129, -2158 },
-  { 2496, -2627, -3611, -1433 },
-  { 2043, -2191, -2167, -3827 },
-  { 2571, -2544, -1915, -3222 },
-  { 2022, -1501, -3856, -2165 },
-  { 2685, -1180, -1461, -4038 },
-  { 1610, -2313, -4391, -1173 },
-  { 2340, -2490, -4215, -516 },
-  { 1742, -2615, -3632, -2146 },
-  { 523, -1293, -4246, -2442 },
-  { 3725, -2723, -3014, -1576 },
-  { 3554, -1381, -4200, -824 },
-  { 1291, -1594, -4777, -1430 },
-  { 1452, 515, -2960, -3830 },
-  { 4264, -894, -3305, -1826 },
-  { 2606, -1452, -4522, -966 },
-  { 1196, -830, -4807, -1816 },
-  { 1054, -775, -2616, -4071 },
-  { 4206, 415, -4344, -1132 },
-  { 3044, 491, -4126, -1934 },
-  { 988, -901, -3353, -3443 },
-  { 1729, -3063, -2267, -3370 },
-  { 3915, 912, -2989, -2387 },
-  { 3781, 300, -2457, -3050 },
-  { 2712, 924, -1350, -1206 },
-  { 4230, 405, -2343, 665 },
-  { 1878, -873, -225, -29 },
-  { 3510, 56, -1334, -3420 },
-  { 2850, 1447, -2651, -3150 },
-  { 1510, -706, -4125, -2483 },
-  { 3115, 793, -1692, -3894 },
-  { 2667, 213, -2973, -2786 },
-  { 1184, -2384, -3051, -3173 },
-  { 2139, 796, -2079, -3697 },
-  { 1464, -1483, -3726, -2754 },
-  { 2407, -1148, -3915, -1569 },
-  { 2612, -1779, -3217, -2271 },
-  { 2406, -2870, -2937, -2496 },
-  { 2140, 126, -3646, -2758 },
-  { 2952, -1036, 268, -1423 },
-  { 93, -1931, -3841, -3535 },
-  { 389, -2953, -3383, -3343 },
-  { 8652, -5511, -1662, 565 },
-  { 7427, -2791, -2535, -842 },
-  { 8541, -4253, -1407, -988 },
-  { 8018, -3203, -2998, 105 },
-  { 7231, -3926, -958, 1308 },
-  { 7331, -3690, -363, 2586 },
-  { 6803, -3646, -2226, -903 },
-  { 8163, -2811, -477, -2235 },
-  { 9356, -3818, -1685, -684 },
-  { 8466, -2854, -302, -698 },
-  { 8458, -3224, 517, 279 },
-  { 8074, -2619, -1326, 2596 },
-  { 8779, -2761, -2527, -441 },
-  { 6533, -2887, -899, -696 },
-  { 7394, -2305, -1642, -120 },
-  { 8281, -3780, -22, 1305 },
-  { 9158, -4413, -779, 901 },
-  { 9031, -5240, -1109, 1678 },
-  { 8717, -3650, 410, -1075 },
-  { 7317, -3197, -818, -2264 },
-  { 7934, -2385, -1214, -1886 },
-  { 8256, -4441, -291, -587 },
-  { 7358, -3395, 1090, -270 },
-  { 9446, -4910, -1343, -473 },
-  { 8187, -4726, -808, 1166 },
-  { 7504, -3845, -47, 267 },
-  { 8029, -2146, -1283, -383 },
-  { 7461, -2705, -853, 783 },
-  { 9367, -3636, -645, -354 },
-  { 8955, -3473, -308, -1947 },
-  { 8676, -2683, -2099, 1485 },
-  { 7481, -3003, -871, -444 },
-  { 8015, -2839, -1673, 1175 },
-  { 6947, -4643, -1527, -1047 },
-  { 7622, -2575, -137, -960 },
-  { 9388, -4279, -707, -1322 },
-  { 8382, -5259, -1283, -565 },
-  { 6856, -4138, -1030, 630 },
-  { 8659, -2571, -1124, -1666 },
-  { 8763, -3807, -537, 2543 },
-  { 8049, -3578, -2186, -604 },
-  { 8272, -2351, -1985, -1214 },
-  { 6855, -3796, -1527, -1631 },
-  { 7178, -2896, -1600, -1756 },
-  { 7040, -2888, -89, -1586 },
-  { 6261, -3403, -264, 998 },
-  { 7756, -4699, -1543, -834 },
-  { 7682, -4622, -758, -1721 },
-  { 8839, -4232, -2932, 1959 },
-  { 9363, -4679, -1956, 39 },
-  { 7883, -3616, -1414, -1432 },
-  { 8828, -3188, -1356, -1312 },
-  { 7746, -3987, -121, -2424 },
-  { 9262, -3256, -693, 818 },
-  { 7670, -3420, -148, 3504 },
-  { 7344, -3183, 608, 1595 },
-  { 8976, -4139, -1848, 1304 },
-  { 6708, -4131, 33, -852 },
-  { 7840, -4429, -2275, 79 },
-  { 8980, -3858, -2838, 453 },
-  { 7815, -4604, -2563, 944 },
-  { 8372, -4422, -1783, 3071 },
-  { 8623, -5128, -1754, 2888 },
-  { 7462, -3281, 889, 920 },
-  { 8416, -59, -1320, -1825 },
-  { 7928, -1488, -414, -2499 },
-  { 8110, -977, -1047, -2042 },
-  { 8278, -687, -1597, -1550 },
-  { 7988, -174, -977, -2106 },
-  { 8609, -1547, -1628, -1527 },
-  { 9000, -1798, -946, -1761 },
-  { 8954, -872, -1404, -1594 },
-  { 8939, 466, -748, -1212 },
-  { 9549, -329, -177, -1360 },
-  { 9411, -18, -1126, -1568 },
-  { 8859, -782, -488, -1338 },
-  { 8955, -218, -43, -1209 },
-  { 9131, -69, -453, -1001 },
-  { 9069, -1519, -1091, -1199 },
-  { 9247, -1309, -566, -1146 },
-  { 8528, -1617, -287, -1313 },
-  { 7763, -745, -149, -2040 },
-  { 8294, -343, 257, -2633 },
-  { 10149, -893, -552, -1649 },
-  { 9398, -915, 218, -2042 },
-  { 9703, -1194, -675, -1592 },
-  { 9586, -700, -427, -1710 },
-  { 8930, 497, -1445, -1218 },
-  { 9285, -1323, -163, -1552 },
-  { 8431, -1289, -985, -1404 },
-  { 8965, -655, 653, -1483 },
-  { 9542, -1001, -951, -1128 },
-  { 9205, -647, -37, -882 },
-  { 8603, -56, 514, -1793 },
-  { 9300, -12, -1324, -567 },
-  { 8773, 238, -184, -1456 },
-  { 9941, -1306, -69, -1792 },
-  { 9360, 279, -376, -1919 },
-  { 9180, -285, 95, -2170 },
-  { 9922, -501, -970, -1570 },
-  { 8341, -1493, -856, -2092 },
-  { 8780, -981, -850, -1014 },
-  { 9721, -548, -1504, -1094 },
-  { 9973, -1493, 482, -2105 },
-  { 8707, -333, -1027, -1087 },
-  { 9098, -469, -315, -1723 },
-  { 8879, -1050, -661, -2020 },
-  { 8857, 602, -866, -1918 },
-  { 8945, -1025, -2154, -1071 },
-  { 8484, -1930, -468, -2179 },
-  { 9177, -1903, -224, -2112 },
-  { 8652, -137, -2097, -1214 },
-  { 9063, -973, -1405, -772 },
-  { 9328, -456, 662, -2469 },
-  { 10101, -697, 127, -2113 },
-  { 9685, 811, -2359, -1024 },
-  { 8586, -94, -460, -1982 },
-  { 7924, -141, -509, -2513 },
-  { 7773, -669, -107, -2835 },
-  { 8636, -1064, -46, -2409 },
-  { 9748, 596, -1815, -1349 },
-  { 8924, 304, 547, -2614 },
-  { 9442, 746, -1153, -1679 },
-  { 9454, -278, -529, -1976 },
-  { 8488, 561, -32, -2160 },
-  { 10083, -63, -1544, -1364 },
-  { 9390, -1278, 568, -1131 },
-  { 9740, -49, -2253, -910 },
-  { 3636, -2391, -1115, -3614 },
-  { 6014, -3204, -1902, -1808 },
-  { 5787, -3497, -1116, -2590 },
-  { 4365, -3046, -1632, -2668 },
-  { 4733, -2192, -2029, -2468 },
-  { 5412, -2753, -1633, -2464 },
-  { 4455, -3375, -767, -3399 },
-  { 4456, -1644, -983, -2841 },
-  { 4039, -2523, 38, -3967 },
-  { 3406, -2662, 72, -4757 },
-  { 4279, -2005, 1055, -4399 },
-  { 4321, -1377, -860, -3786 },
-  { 3743, -5739, -651, -3047 },
-  { 3528, -5510, 361, -4060 },
-  { 6496, -4886, -136, -2689 },
-  { 4513, -5254, 551, -4010 },
-  { 6557, -3413, -92, -3063 },
-  { 4186, -2059, 187, 47 },
-  { 6210, -4117, -1256, -1985 },
-  { 6038, -4343, 351, -2124 },
-  { 4305, -4780, -2077, -1897 },
-  { 4480, -3815, -2228, -1533 },
-  { 5582, -3689, 1221, -3429 },
-  { 5532, -4874, 1195, -2765 },
-  { 6518, -2853, -905, -2568 },
-  { 5467, -2192, 470, -4115 },
-  { 4139, -1577, 240, -3493 },
-  { 5281, -1926, -729, -3340 },
-  { 5214, -2870, 1359, -4289 },
-  { 3046, -3510, -1536, -3214 },
-  { 5433, -2881, -1230, -1184 },
-  { 4861, -3932, -1071, -2791 },
-  { 5693, -4234, -1906, -1502 },
-  { 4004, -3935, -1804, -2383 },
-  { 3728, -3792, 681, -4773 },
-  { 3621, -3030, -1951, -2598 },
-  { 5133, -3903, 44, -3700 },
-  { 3561, -3451, 1183, -5301 },
-  { 5026, -2762, -2341, -1780 },
-  { 5841, -2492, -467, -3210 },
-  { 5591, -1791, 497, -2472 },
-  { 5054, -3898, -1822, -2097 },
-  { 5813, -2792, 83, -1469 },
-  { 4432, -4497, 1670, -5193 },
-  { 5338, -4653, -1109, -2200 },
-  { 3239, -4401, -648, -3655 },
-  { 2147, -3598, -1200, -4242 },
-  { 4417, -2271, -1552, -3210 },
-  { 6494, -4360, 852, -3565 },
-  { 2393, -6358, -856, -4524 },
-  { 4959, -4196, -847, -1403 },
-  { 4924, -5438, -226, -3026 },
-  { 4254, -5303, -1306, -2424 },
-  { 4121, -3126, -2334, -1981 },
-  { 3437, -4443, -1464, -2953 },
-  { 3203, -3459, -529, -4339 },
-  { 5896, -5945, 543, -3246 },
-  { 1987, -4733, -220, -4863 },
-  { 4358, -4431, -514, -3081 },
-  { 4583, -2416, -492, -2287 },
-  { 2943, -5035, 419, -4927 },
-  { 5358, -5129, 987, -4309 },
-  { 4460, -3392, 1752, -5634 },
-  { 3415, -4633, 1507, -5945 },
-  { 811, -4692, -445, 2333 },
-  { 1009, -5613, -1857, 1360 },
-  { 1338, -2712, -2720, 3036 },
-  { 1002, -3754, -2582, 2344 },
-  { 750, -4608, -2334, 714 },
-  { 2043, -3207, -2822, 2173 },
-  { -140, -4654, -2953, 357 },
-  { -54, -4026, -2376, 2695 },
-  { 1858, -5022, -717, 2287 },
-  { 2064, -3894, -722, 3255 },
-  { 2727, -4558, -332, 2603 },
-  { 1810, -5378, 283, 1826 },
-  { 3935, -4326, 762, 3383 },
-  { -767, -4697, -2510, 1922 },
-  { 2146, -4312, -3090, 1641 },
-  { 54, -5881, -2114, 921 },
-  { 1992, -5766, -640, 1574 },
-  { 1200, -5371, -1114, 1828 },
-  { 2973, -5337, 34, 2266 },
-  { 1531, -5018, -2817, 1192 },
-  { 3078, -4570, 117, 1990 },
-  { 924, -4286, -1388, 2713 },
-  { 142, -5058, -2848, 1487 },
-  { -106, -6180, -881, 842 },
-  { 673, -5433, -229, 1596 },
-  { 783, -5710, -2784, 562 },
-  { 1935, -5729, -2009, 856 },
-  { -410, -3375, -3326, 2734 },
-  { 234, -3000, -2628, 3260 },
-  { 733, -3405, -3806, 1589 },
-  { 771, -4285, -3544, 1314 },
-  { 1192, -3563, -3960, 2178 },
-  { 206, -5555, -1250, 1546 },
-  { -130, -3815, -1210, 3041 },
-  { 646, -3940, -393, 2992 },
-  { -184, -4931, -1767, 1925 },
-  { 2746, -5120, -2275, 1464 },
-  { 2440, -3731, -3352, 2729 },
-  { -490, -4942, -3779, 997 },
-  { 68, -2636, -4167, 3778 },
-  { 48, -3986, -4118, 2106 },
-  { -978, -5486, -1336, 1390 },
-  { 1126, -5297, -855, 640 },
-  { -472, -3975, -3622, 1557 },
-  { 2456, -5344, -1523, 1648 },
-  { -774, -5652, -2417, 1147 },
-  { 995, -6122, -812, 1132 },
-  { 3282, -4571, -1763, 2175 },
-  { 3655, -3862, -676, 3568 },
-  { 3038, -3647, -1672, 3381 },
-  { 2595, -2964, -2772, 3263 },
-  { 4176, -3353, -1148, 4354 },
-  { 1603, -3442, -1500, 3444 },
-  { 828, -6226, -1783, 678 },
-  { 1421, -3333, -3080, 3403 },
-  { 1121, -4727, -1924, 1984 },
-  { -186, -5083, -682, 1796 },
-  { 819, -2778, -3488, 530 },
-  { 421, -2873, -3832, 2596 },
-  { 2164, -4263, -1605, 2282 },
-  { 585, -4437, -682, -491 },
-  { -644, -4452, -1157, 2325 },
-  { 1991, -4299, 210, 2834 },
-  { 2135, -3632, -2113, 665 },
-  { -7482, -2724, -2662, -1380 },
-  { -6983, -2166, -3756, -3509 },
-  { -7085, -1439, -2397, -3112 },
-  { -7760, -3049, -3319, -2822 },
-  { -8413, -2760, -4406, -3298 },
-  { -5995, -3943, -1260, -3750 },
-  { -7879, -1554, -3464, -2606 },
-  { -6314, -2034, -3878, -1681 },
-  { -8849, -2084, -1399, -1231 },
-  { -7153, -2602, -1384, -817 },
-  { -8041, -2571, -407, -2785 },
-  { -7246, -2233, -1578, 260 },
-  { -7336, -3883, -4061, -1342 },
-  { -7619, -3908, -2342, 382 },
-  { -8684, -3724, -1662, -727 },
-  { -7850, -2922, -1770, -3449 },
-  { -6766, -2034, -1293, -1988 },
-  { -6895, -2116, -968, -3744 },
-  { -7136, -5147, -2618, -2809 },
-  { -8224, -3724, -2519, -1589 },
-  { -6711, -2750, -3021, -219 },
-  { -8059, -1638, -1102, -3175 },
-  { -8710, -4839, -3963, -3143 },
-  { -9363, -4965, -3257, -1002 },
-  { -6099, -1751, -3157, -395 },
-  { -6453, -3216, -4597, -483 },
-  { -7879, -5477, -839, -2638 },
-  { -7202, -4038, -526, -2856 },
-  { -8022, -1228, -1910, -1646 },
-  { -9117, -1393, -1582, -2535 },
-  { -9095, -2693, -636, -2605 },
-  { -9076, -2580, -3481, -2519 },
-  { -8327, -4859, -2422, 83 },
-  { -8368, -2129, -2324, -2173 },
-  { -8554, -4563, -3842, -2007 },
-  { -10462, -4261, -1934, -2084 },
-  { -9717, -3187, -2294, -1896 },
-  { -9625, -3889, -3020, -3224 },
-  { -9857, -4955, -4239, -2184 },
-  { -9752, -2351, -2277, -3129 },
-  { -7219, -1302, -2639, -1603 },
-  { -7477, -4360, -3718, -559 },
-  { -5680, -2033, -2326, -3078 },
-  { -10190, -5548, -4643, -3601 },
-  { -9431, -4121, -879, -2479 },
-  { -8365, -5450, -2020, -1439 },
-  { -6289, -5178, -1605, -3845 },
-  { -8319, -3866, -687, -2792 },
-  { -8131, -1031, -3608, -3947 },
-  { -10510, -2560, -1199, -2082 },
-  { -11015, -3640, -2748, -3041 },
-  { -8762, -5022, -5231, -1162 },
-  { -10153, -2715, -4648, -4859 },
-  { -7930, -5205, -1900, -3600 },
-  { -9561, -3548, -4812, -3722 },
-  { -7663, -4709, -1180, -1475 },
-  { -9073, -5707, -1815, -2980 },
-  { -8602, -2363, -2675, -3770 },
-  { -9967, -5614, -3575, -3838 },
-  { -8324, -1005, -2131, -3254 },
-  { -10331, -5737, -2550, -2940 },
-  { -8234, -3354, -3361, -4479 },
-  { -8140, -1951, -4526, -4545 },
-  { -6679, -2662, -2284, -4182 },
-  { -1122, -1514, -6427, -212 },
-  { 54, -1660, -5424, -1404 },
-  { 254, -2778, -5222, 846 },
-  { -267, -1661, -6577, 814 },
-  { -305, -2021, -5759, 1484 },
-  { -1791, -2446, -6867, -86 },
-  { -2929, -3158, -6603, -1799 },
-  { -1391, -3189, -5557, -1053 },
-  { -1602, -884, -6767, -1213 },
-  { -361, -318, -6219, -44 },
-  { -4078, -2635, -5523, -433 },
-  { -956, 478, -4382, 1470 },
-  { -3300, -2462, -6021, -2721 },
-  { 708, -2434, -5085, -540 },
-  { -2435, -3607, -5647, -2110 },
-  { -491, -1134, -4681, -2886 },
-  { 87, -3435, -4641, -1194 },
-  { -586, -2927, -4784, 366 },
-  { -1394, -2326, -6021, 350 },
-  { 97, -2519, -4678, -2120 },
-  { -1547, -1907, -5069, -2993 },
-  { 268, -3724, -4719, 127 },
-  { -827, -1190, -5912, 1144 },
-  { -3959, -2322, -6898, -1974 },
-  { -2728, -2228, -6426, -562 },
-  { -456, -666, -5785, -1609 },
-  { 531, -1096, -5731, -656 },
-  { -3569, -688, -3915, 110 },
-  { -4752, -1725, -4393, -377 },
-  { -3210, -3315, -6960, -840 },
-  { -688, -3416, -4971, 1221 },
-  { -1833, 77, -6491, -2434 },
-  { -239, -255, -6850, -886 },
-  { -2112, -1490, -6291, -2689 },
-  { -1544, -4579, -5198, -1261 },
-  { -2771, -4014, -5520, 683 },
-  { -1635, -2829, -5512, 1214 },
-  { -958, -2582, -4823, 2360 },
-  { -2077, -4566, -4642, 365 },
-  { -3112, -4214, -5960, -823 },
-  { -2467, -2510, -4858, 1467 },
-  { -1561, -3399, -5822, 211 },
-  { -775, -1081, -4424, 2636 },
-  { -1263, 25, -6378, -1392 },
-  { -3476, -366, -5417, -1393 },
-  { -3176, -1476, -4149, 1466 },
-  { -2479, 518, -4448, -257 },
-  { -2992, 158, -4660, -1279 },
-  { -1320, -3872, -4479, 1147 },
-  { -1475, -312, -5318, 539 },
-  { -3527, -1679, -5860, -1681 },
-  { -3397, -3438, -5593, 1866 },
-  { -4089, -2439, -4763, 1275 },
-  { -748, -4513, -4687, -48 },
-  { -2166, -4531, -4691, -2856 },
-  { -2385, -853, -6035, -627 },
-  { -1194, -4091, -4472, -1963 },
-  { -682, -3234, -4084, -3033 },
-  { -3255, -5015, -5328, -12 },
-  { -2313, -3436, -4601, -155 },
-  { -2792, -1038, -6947, -2019 },
-  { -1244, -1526, -5771, -1882 },
-  { -4679, -3731, -5506, 283 },
-  { -3062, -66, -3558, -758 },
-  { -4895, -1187, 4751, 3728 },
-  { -7600, -2752, 3320, 4613 },
-  { -5703, -2975, 3944, 2659 },
-  { -4972, -1257, -246, 2952 },
-  { -4221, -2487, 1702, 4295 },
-  { -2900, -1529, 2458, 4935 },
-  { -5061, 407, 2416, 4050 },
-  { -6931, -3478, 2761, 2213 },
-  { -6037, -3921, 3192, 1866 },
-  { -6113, -811, 2407, 3782 },
-  { -5878, -1716, 1207, 3478 },
-  { -5953, -2853, 2207, 2712 },
-  { -6807, -3223, 2749, 3595 },
-  { -3272, -3157, 1389, 3788 },
-  { -5368, -1904, 1980, 5077 },
-  { -7235, -1398, 3075, 4548 },
-  { -4765, -3487, 2755, 2796 },
-  { -7658, -4435, 2694, 2582 },
-  { -6997, -4282, 456, 3832 },
-  { -5563, -3115, -63, 3713 },
-  { -4244, -4220, 1450, 2767 },
-  { -3801, -2194, 190, 4303 },
-  { -5458, -4119, 1958, 2274 },
-  { -7300, -3469, 3514, 3193 },
-  { -4594, -2067, 775, 4752 },
-  { -3389, -1654, 1464, 5412 },
-  { -4845, -3483, 964, 3437 },
-  { -6007, -2818, 1666, 4659 },
-  { -8709, -5007, 1757, 3287 },
-  { -5833, -4389, 1025, 3171 },
-  { -5788, -1780, 3944, 3661 },
-  { -4430, -920, 1938, 4753 },
-  { -7066, -1857, 4591, 4538 },
-  { -3549, -513, 1427, 5317 },
-  { -7517, -1220, 2883, 3049 },
-  { -7605, -2687, 1874, 2735 },
-  { -8718, -4035, 2676, 3730 },
-  { -7990, -3907, 1185, 2607 },
-  { -6058, -1744, 3349, 5157 },
-  { -5954, 565, 3161, 3250 },
-  { -6478, -612, 1930, 2271 },
-  { -6535, -1445, -2, 1618 },
-  { -8963, -4151, 1192, 4044 },
-  { -7227, -3570, 1600, 4234 },
-  { -4674, 79, 595, 3015 },
-  { -3974, 430, 2727, 5137 },
-  { -5299, 9, 3714, 4779 },
-  { -6779, -2699, -8, 2436 },
-  { -7016, -1145, 1293, 2310 },
-  { -6955, -3312, 1534, 1801 },
-  { -4025, 740, 1850, 4054 },
-  { -9589, -3460, 4154, 5270 },
-  { -4404, -1181, 4298, 5173 },
-  { -7356, -4583, -18, 2644 },
-  { -6516, -1235, 4439, 6234 },
-  { -3453, -301, 4344, 4464 },
-  { -4643, 1530, 3315, 4340 },
-  { -4575, -2557, 3754, 3682 },
-  { -3643, -3501, 2051, 2997 },
-  { -5412, -2475, 2301, 1579 },
-  { -5846, 259, 1360, 2348 },
-  { -5258, -1358, 1050, 838 },
-  { -5542, -219, 6377, 5750 },
-  { -5713, -2952, 922, 899 },
-  { -2049, -1135, 5206, 1033 },
-  { -1693, -1886, 4835, -106 },
-  { -2344, -3504, 4232, -13 },
-  { -2475, -2334, 5043, 1126 },
-  { -787, -2549, 3880, 2138 },
-  { -3159, -2341, 4830, 2887 },
-  { -1780, -1009, 6240, 2061 },
-  { -4327, -3363, 2818, 886 },
-  { -3376, -2743, 4104, 207 },
-  { -3250, -4640, 2718, 1498 },
-  { -382, -1075, 4382, 3460 },
-  { -2416, -4168, 3530, 816 },
-  { -1756, -2708, 4861, 622 },
-  { -1879, -2097, 5156, 2889 },
-  { -2496, -2418, 3722, 2671 },
-  { -2717, -3252, 3341, 1944 },
-  { -4063, -4091, 3306, 267 },
-  { -3549, -3808, 3747, 842 },
-  { -2635, 546, 5794, 1894 },
-  { -1857, -1121, 4383, 3964 },
-  { -2226, -2166, 3489, 3678 },
-  { -3492, -660, 5323, 1063 },
-  { -3033, -3130, 4382, 1828 },
-  { -2703, -625, 6369, 2851 },
-  { -1656, -2842, 4584, -528 },
-  { -4781, -2622, 4390, 2097 },
-  { -413, -2045, 5081, 3035 },
-  { -3810, -2662, 4532, 1095 },
-  { -3144, -1858, 5215, 1880 },
-  { -3562, -1795, 4928, 670 },
-  { -4800, -1509, 5189, 1859 },
-  { -1085, -3832, 4169, 900 },
-  { -1969, -3270, 2857, 2878 },
-  { -4267, -4140, 3176, 1805 },
-  { -5145, -3727, 3524, 1168 },
-  { -1346, -1876, 5501, 1748 },
-  { -4998, -2945, 3699, 338 },
-  { -3458, -3096, 3406, -635 },
-  { -1751, -3209, 3508, 395 },
-  { -2507, 170, 5987, 705 },
-  { -3756, -1072, 5647, 3536 },
-  { -2870, -1439, 5026, 3212 },
-  { -3913, -3225, 3669, 2144 },
-  { -3739, 226, 5747, 764 },
-  { -2052, -820, 5266, 3093 },
-  { -3214, -3820, 2409, 2391 },
-  { -4398, -2588, 3501, -218 },
-  { -4484, -1763, 4180, -198 },
-  { -3368, -1525, 4362, -134 },
-  { -2407, 224, 4905, 3533 },
-  { -1369, -2937, 4728, 1788 },
-  { -4848, -1707, 4159, 851 },
-  { -3454, -1749, 4281, 3230 },
-  { -1990, -3853, 3487, 1735 },
-  { -3117, 92, 6155, 4075 },
-  { -2676, -2472, 4078, -589 },
-  { -1547, -2012, 2626, 1835 },
-  { -4275, -588, 4824, 725 },
-  { -601, -2249, 3736, 3548 },
-  { -4060, -61, 5333, 3097 },
-  { -4303, 7, 6551, 3054 },
-  { -5003, -1029, 5786, 3319 },
-  { -2810, -728, 5392, 199 },
-  { -1232, -200, 5228, 3121 },
-  { 2621, 165, -6255, 298 },
-  { 3669, 537, -6844, 1564 },
-  { 1598, -1190, -6235, 2523 },
-  { 2164, -32, -6894, 1383 },
-  { 853, -1597, -6069, 1449 },
-  { 1377, -1661, -5266, 108 },
-  { 2660, 48, -5172, -517 },
-  { 1903, -391, -5677, 1010 },
-  { 3792, 206, -5274, -11 },
-  { 1239, 2776, -2929, 2721 },
-  { 4071, 149, -7259, 3125 },
-  { 1436, -480, -6156, -196 },
-  { 1373, -1960, -5005, 3122 },
-  { 3413, -1271, -5176, 3283 },
-  { 3060, -68, -6495, 2238 },
-  { 2700, -2075, -4681, 91 },
-  { 2928, -1728, -5168, 1858 },
-  { 4424, 828, -4471, 88 },
-  { 2672, -2604, -4038, 2753 },
-  { 5223, -123, -6749, 2295 },
-  { 4237, -420, -5538, 1353 },
-  { 4744, -1281, -4097, 4708 },
-  { 1103, -2764, -4751, 2024 },
-  { 3747, -1913, -3911, 3960 },
-  { 2470, -1416, -5542, 615 },
-  { 4847, -1354, -5334, 1733 },
-  { 5336, 88, -7593, 4007 },
-  { 2388, -2880, -4807, 1037 },
-  { 4495, 1391, -5685, -139 },
-  { 5253, 1637, -6450, 1533 },
-  { 1199, 795, -5515, 1261 },
-  { 1397, -1259, -4252, 3838 },
-  { 746, 70, -6640, 604 },
-  { 1584, 166, -4972, 3072 },
-  { 380, -999, -5397, 2267 },
-  { 2974, 1707, -3242, 5360 },
-  { 5202, -403, -5453, 2832 },
-  { 3718, -1731, -4760, 714 },
-  { 4150, -975, -4792, 61 },
-  { 2925, -818, -4841, 15 },
-  { 5301, 577, -4006, 3259 },
-  { 5265, 1986, -5679, 3028 },
-  { 3752, 1928, -4509, 3729 },
-  { 3278, 1925, -6370, 1247 },
-  { 5107, 1721, -4853, 3127 },
-  { 3279, 2982, -2515, 4005 },
-  { 4622, 668, -6204, 759 },
-  { 6034, 317, -5763, 4818 },
-  { -558, 57, -3785, 2817 },
-  { 4476, 1616, -3965, 4536 },
-  { 5953, 2056, -8215, 2715 },
-  { 4387, 2613, -7463, 868 },
-  { 5834, 1088, -4736, 4924 },
-  { 6473, -856, -6991, 4172 },
-  { 4959, -293, -5162, 76 },
-  { 2731, -843, -6119, 3847 },
-  { 3245, 1202, -6833, 616 },
-  { 2553, 1383, -3829, 3859 },
-  { 4332, 2099, -3480, 3622 },
-  { 2110, 2683, -2728, 3990 },
-  { 876, 1167, -3290, 3466 },
-  { 3991, 1709, -2410, 4077 },
-  { 5105, 939, -2584, 3256 },
-  { 4719, 688, -1566, 3040 },
-  { -3632, 4335, 1266, -3303 },
-  { -4956, 3207, 1312, -2806 },
-  { -4669, 2627, 2663, -2435 },
-  { -4282, 3708, 2303, -3038 },
-  { -4536, 2297, -175, -3350 },
-  { -5234, 2503, -139, -880 },
-  { -3978, 1512, 1092, -3619 },
-  { -4519, 4649, 1363, -2455 },
-  { -5118, 3132, 1961, -1577 },
-  { -5196, 3379, -182, -1378 },
-  { -6420, 4486, 2397, -1993 },
-  { -5030, 5046, 1292, -1118 },
-  { -4559, 2573, -927, -1406 },
-  { -3501, 3730, 691, -4930 },
-  { -4364, 2758, 1007, -3909 },
-  { -4026, 2839, -1559, -2340 },
-  { -5037, 4053, 836, -1571 },
-  { -4727, 5136, 1110, -3588 },
-  { -5245, 2799, -999, -2164 },
-  { -4954, 1501, 422, -3963 },
-  { -5994, 2726, 1462, -2833 },
-  { -5621, 5159, 2038, -2512 },
-  { -4991, 2291, 1917, -3151 },
-  { -5469, 4382, -148, -2978 },
-  { -5858, 1983, 807, -2720 },
-  { -4709, 3556, 952, -467 },
-  { -2489, 2362, 1714, -4230 },
-  { -4717, 5004, -1180, -3672 },
-  { -5914, 3653, 1359, -1317 },
-  { -5506, 2995, 780, -1059 },
-  { -5287, 3945, 2480, -2293 },
-  { -3849, 4358, 322, -1770 },
-  { -3911, 3570, 252, -3185 },
-  { -3660, 5128, 158, -3719 },
-  { -4599, 3277, -503, -2727 },
-  { -3673, 3760, -1252, -3339 },
-  { -5161, 2337, 388, -1943 },
-  { -3529, 2216, 2156, -3080 },
-  { -4309, 4331, 1808, -1460 },
-  { -4782, 3820, 480, -2504 },
-  { -4166, 3544, -378, -1567 },
-  { -5572, 2466, -418, -2909 },
-  { -6096, 2930, 119, -1878 },
-  { -5963, 3554, 1011, -2233 },
-  { -6433, 4335, 935, -2930 },
-  { -5004, 3314, -1352, -3430 },
-  { -6042, 3463, -1008, -3940 },
-  { -4671, 2214, -640, -5040 },
-  { -2795, 3759, 1412, -3803 },
-  { -3647, 4436, 729, -515 },
-  { -3594, 1033, 56, -4148 },
-  { -2908, 3027, 2889, -3485 },
-  { -3338, 2234, 313, -4285 },
-  { -3825, 4497, -561, -2634 },
-  { -6167, 3012, -48, -3149 },
-  { -4828, 3515, -969, -4475 },
-  { -5789, 2757, -539, -4173 },
-  { -2452, 3067, 564, -4249 },
-  { -4921, 1358, 1331, -2889 },
-  { -3127, 4239, -1045, -1523 },
-  { -4780, 2326, -1118, -3446 },
-  { -3908, 5546, 152, -2622 },
-  { -6972, 2976, 337, -2809 },
-  { -4839, 4613, -35, -4077 },
-  { -1408, 4822, -1149, -4997 },
-  { -981, 4979, -912, -6304 },
-  { -2098, 5689, -888, -2878 },
-  { -3343, 4814, -657, -4434 },
-  { -2461, 3601, -967, -4869 },
-  { -2652, 3944, 87, -5520 },
-  { -1104, 6076, 174, -6407 },
-  { 355, 5370, -1721, -5869 },
-  { 1242, 4497, -1107, -5091 },
-  { -89, 4002, -1491, -5182 },
-  { 1059, 5693, -1591, -4905 },
-  { 1323, 4682, -2078, -4768 },
-  { 818, 3996, -549, -5468 },
-  { -287, 4529, 929, -5543 },
-  { -919, 5519, -2791, -2844 },
-  { -1407, 5679, -3289, -3974 },
-  { -189, 6530, -3547, -4002 },
-  { -900, 7039, -3371, -4855 },
-  { -2983, 7211, -363, -4835 },
-  { -814, 6503, -104, -5106 },
-  { -2386, 6896, 809, -4919 },
-  { 845, 4492, 352, -6621 },
-  { -1998, 7237, -1646, -4231 },
-  { -3380, 6251, 471, -4577 },
-  { -1908, 7059, 84, -5726 },
-  { -340, 6346, -803, -6265 },
-  { -2279, 5834, -47, -4633 },
-  { -1532, 5286, -1748, -1901 },
-  { -2757, 6188, -453, -3415 },
-  { -1255, 6405, -2043, -6357 },
-  { 918, 5581, -121, -5667 },
-  { 1840, 5336, -821, -5034 },
-  { -2475, 4992, -1825, -3104 },
-  { -2413, 5606, -1789, -4298 },
-  { 132, 5128, -2389, -4442 },
-  { 223, 6400, -2653, -4742 },
-  { -673, 5012, 680, -4582 },
-  { -1657, 6624, -349, -3596 },
-  { -755, 6289, -1860, -3978 },
-  { -572, 6894, -1946, -5207 },
-  { -1141, 4756, -2665, -5586 },
-  { -1073, 4269, -431, -4030 },
-  { 186, 5761, 916, -5868 },
-  { -1907, 4836, 1017, -5106 },
-  { -963, 3363, -1248, -6348 },
-  { -3262, 4774, -1818, -5858 },
-  { 847, 3812, -2538, -4302 },
-  { -1223, 5903, 1360, -5479 },
-  { -1094, 6923, -1244, -2381 },
-  { 267, 6276, -709, -2846 },
-  { -157, 5840, 1124, -4266 },
-  { 889, 3206, -910, -5305 },
-  { -1736, 3344, 582, -4838 },
-  { -2357, 5676, -2695, -6277 },
-  { -1916, 6901, -986, -5397 },
-  { -3062, 6028, -695, -5687 },
-  { 1836, 3566, -1357, -5226 },
-  { -2176, 4938, 646, -3872 },
-  { -2199, 3055, -208, -6124 },
-  { -236, 3032, -821, -5325 },
-  { -3989, 7277, -565, -3899 },
-  { -595, 4362, 74, -5975 },
-  { 684, 5874, -841, -4424 },
-  { -2731, 6305, -2389, -5465 },
-  { -5775, 1325, -56, -2528 },
-  { -7029, -534, -1890, -3278 },
-  { -5798, -15, -2734, -2210 },
-  { -5504, -1198, -353, -3659 },
-  { -5079, 960, -894, -4336 },
-  { -6073, -36, -133, -3014 },
-  { -5782, -259, -1025, -3986 },
-  { -6843, 1262, -807, -1639 },
-  { -5263, -918, -3290, -579 },
-  { -4840, 461, -2158, -533 },
-  { -6014, -50, -620, 504 },
-  { -5843, 241, -1359, -282 },
-  { -5898, 577, 769, -3271 },
-  { -6833, -946, -466, -3347 },
-  { -6026, 1459, -512, -729 },
-  { -7361, 747, -388, -1110 },
-  { -6391, 2142, -1160, -2513 },
-  { -6995, 304, 498, -2673 },
-  { -6757, 679, -386, -433 },
-  { -5222, 1688, -1093, -1032 },
-  { -5019, 575, 184, -3627 },
-  { -4237, 628, -3507, -1243 },
-  { -7479, -456, -1722, -1486 },
-  { -6464, 713, -1273, -1153 },
-  { -6255, 1682, -606, -3607 },
-  { -7033, 1497, -71, -1955 },
-  { -6694, 1556, -1721, -3214 },
-  { -6114, -356, 813, -2575 },
-  { -5308, 632, -1851, -1636 },
-  { -5742, -911, -1733, 383 },
-  { -6083, -387, -2313, -879 },
-  { -6535, -530, -1505, -2083 },
-  { -4896, 1223, -2750, -1816 },
-  { -6392, -463, -3247, -2093 },
-  { -5373, 1264, -2706, -3042 },
-  { -3894, -1390, -1020, -891 },
-  { -6179, 1168, -1966, -1922 },
-  { -5162, 1668, -1617, -1916 },
-  { -6453, 920, -1169, -2432 },
-  { -6130, 2005, -536, -1519 },
-  { -6552, -98, -518, -1938 },
-  { -7528, 355, -1101, -1772 },
-  { -5745, 610, -247, -1360 },
-  { -7003, 177, -2064, -1958 },
-  { -6956, -570, -2220, -4225 },
-  { -7830, 791, -1394, -2774 },
-  { -7634, 480, -3171, -4224 },
-  { -7913, 1154, -350, -2381 },
-  { -5063, 1704, -1804, -2977 },
-  { -4887, -524, -2703, 188 },
-  { -5551, 406, -1620, -3063 },
-  { -7109, 1342, 381, -3021 },
-  { -6846, 631, -458, -3398 },
-  { -4606, -605, 11, -3930 },
-  { -8134, -225, -1738, -2648 },
-  { -7043, 402, -2734, -3059 },
-  { -7417, 1825, -2545, -4389 },
-  { -6971, -236, -1031, -665 },
-  { -5752, 2111, -1632, -3808 },
-  { -7660, -78, -624, -3135 },
-  { -6358, 619, -1951, -3911 },
-  { -8134, 408, -1935, -3695 },
-  { -6335, 1911, -2368, -4505 },
-  { -7116, 2163, -344, -2753 },
-  { 2357, 4488, 2220, -5682 },
-  { 1385, 3206, 2300, -5305 },
-  { 1419, 2557, 5203, -3516 },
-  { 262, 4315, 3920, -1847 },
-  { 3316, 3187, 1612, -5609 },
-  { 1729, 2350, 1673, -6068 },
-  { 1603, 6126, 1467, -2839 },
-  { -1339, 3316, 3691, -3530 },
-  { -563, 4618, 3180, -4548 },
-  { 463, 4624, 3111, -5614 },
-  { 1246, 5455, 3356, -5720 },
-  { 480, 2149, 5422, -2893 },
-  { 1768, 4827, 913, -5579 },
-  { -149, 5381, 4366, -3297 },
-  { 985, 3672, 2644, -92 },
-  { -258, 2911, 5817, -2213 },
-  { 3428, 3289, 3351, -3541 },
-  { -666, 3295, 4727, -2869 },
-  { 35, 6641, 4160, -4052 },
-  { 623, 6787, 3156, -4560 },
-  { 2654, 4360, 4676, -4632 },
-  { 1386, 5246, 4834, -4497 },
-  { 3488, 4574, 3856, -5946 },
-  { 383, 4481, 4168, -4110 },
-  { 1753, 3652, 4288, -3326 },
-  { 1344, 4905, 2508, -4660 },
-  { 1580, 4106, 3104, -2224 },
-  { 2027, 5038, 1683, -1554 },
-  { 446, 3699, 5872, -3013 },
-  { 4637, 4087, 3578, -5018 },
-  { 2629, 3560, 5331, -4900 },
-  { 1527, 6674, 2523, -4131 },
-  { -1437, 2804, 2528, -4464 },
-  { -229, 3355, 2016, -5537 },
-  { 3666, 3418, 4374, -4581 },
-  { 1192, 3799, 923, -6596 },
-  { 2040, 2956, 448, -5322 },
-  { 2468, 5768, 4029, -5869 },
-  { 3438, 6516, 3529, -6667 },
-  { 2737, 5495, 680, -5535 },
-  { 3896, 5727, 1801, -4958 },
-  { 4988, 4957, 3592, -6518 },
-  { -542, 4416, 5794, -2787 },
-  { 4136, 4354, 2064, -4696 },
-  { 3067, 5936, 1207, -3396 },
-  { 2789, 4966, 2405, -3854 },
-  { 1731, 3270, 3251, -1063 },
-  { 1767, 5537, 2084, -2349 },
-  { 465, 3116, 4532, -837 },
-  { 1499, 2627, 4610, -2212 },
-  { 122, 3095, 3642, -3552 },
-  { 2542, 2866, 2705, -6402 },
-  { 3134, 4323, 698, -4785 },
-  { 731, 1859, 3112, -5242 },
-  { 2553, 2980, 3241, -4846 },
-  { 1329, 5310, 1607, -6624 },
-  { 2468, 1858, 3476, -1034 },
-  { -172, 4996, 2000, -5562 },
-  { 2621, 4220, 1574, -3386 },
-  { -333, 1832, 3362, -4117 },
-  { 2169, 6762, 3065, -6225 },
-  { 2844, 5528, 3223, -4765 },
-  { 526, 5175, 1644, -4267 },
-  { 2922, 4426, 2414, -2610 },
-  { 452, 1399, -4516, -2636 },
-  { 2872, 1720, -4667, -1435 },
-  { 1279, 702, -5424, -1984 },
-  { 2187, 870, -5021, -1341 },
-  { 583, -144, -4628, -2464 },
-  { 3, 2237, -5284, -2827 },
-  { -19, 1005, -5460, -1819 },
-  { 2897, 2084, -5885, -515 },
-  { -400, 3370, -5527, -2947 },
-  { 1505, 2593, -5518, -1802 },
-  { 1341, 4534, -5094, -1899 },
-  { 3241, 3670, -5493, -1252 },
-  { -1287, 921, -5994, -1675 },
-  { 627, 408, -6652, -364 },
-  { -260, 1127, -4849, -3247 },
-  { 371, 3400, -5976, -2285 },
-  { 1533, 1566, -6373, -610 },
-  { 2462, 4274, -6184, -1254 },
-  { 1782, 3363, -6222, -1381 },
-  { 572, 4650, -5673, -2754 },
-  { 2674, 3414, -4460, -2154 },
-  { 3614, 3820, -6883, -398 },
-  { 1136, -1, -5511, -1112 },
-  { -1773, 1137, -5647, -2377 },
-  { -753, 2104, -6085, -2565 },
-  { -204, 3025, -4731, -1418 },
-  { -1486, 1438, -4380, -216 },
-  { 302, 858, -5786, -264 },
-  { 3486, 1495, -5234, -783 },
-  { 888, 2327, -3423, -3720 },
-  { -259, 772, -6596, -1311 },
-  { -1197, 2073, -5174, -1826 },
-  { 1500, 3470, -4462, -2645 },
-  { 3072, 1960, -3277, -2264 },
-  { 1841, 952, -4324, -2340 },
-  { 1994, 2200, -3940, -2923 },
-  { -1782, 1699, -4667, -1075 },
-  { -1464, 2906, -3468, -375 },
-  { 366, 2380, -3747, 1467 },
-  { -545, 1645, -4619, 376 },
-  { 1724, 2350, -2374, -3512 },
-  { 3184, 2628, -2996, -3275 },
-  { 734, 2010, -6239, -1479 },
-  { 524, 3756, -4496, -3263 },
-  { 1492, 3570, -3494, -3600 },
-  { -932, 618, -5389, -2894 },
-  { -133, 2161, -4083, -3267 },
-  { 786, 774, -3279, -3731 },
-  { 1078, 803, -3843, -3007 },
-  { -332, 3405, -3347, 40 },
-  { -17, 6, -4005, -3690 },
-  { -189, 4372, -4488, -2561 },
-  { -450, 3846, -3790, -1370 },
-  { 362, 2212, -5272, -15 },
-  { -1529, 791, -6802, -2296 },
-  { 2145, 4241, -4474, 376 },
-  { 1813, 2426, -2932, -2726 },
-  { -542, 4557, -3140, -1080 },
-  { 1192, 3784, -4371, -20 },
-  { 2784, 5188, -6399, -1394 },
-  { 431, 4561, -3673, -1398 },
-  { 1382, 3096, -4083, 1253 },
-  { 1209, 4224, -2930, 1500 },
-  { 2798, 2684, -6676, -606 },
-  { -2396, 1510, -5381, -2713 },
-  { -2625, 2542, -4032, -2880 },
-  { -1231, 3967, -4098, -2886 },
-  { -1393, 2374, -3862, -4525 },
-  { -2495, 1665, -1637, -5445 },
-  { -3854, 1759, -1750, -4944 },
-  { -2373, 1668, -2856, -6251 },
-  { -2668, 1981, -886, -4557 },
-  { -2927, 4427, -3451, -6172 },
-  { -1925, 2596, -4696, -2527 },
-  { -3202, 2847, -3928, -5896 },
-  { -3332, 1665, -5025, -3412 },
-  { -3212, 3115, -4155, -4062 },
-  { -1013, 3205, -5133, -3751 },
-  { -2022, 4595, -3947, -5611 },
-  { -3556, 1755, -3715, -2300 },
-  { -1784, 4114, -2723, -1773 },
-  { -3586, 4081, -2733, -4942 },
-  { -1608, 3685, -4154, -4573 },
-  { -3368, 4042, -4452, -6227 },
-  { -1407, 3881, -5729, -3719 },
-  { -2751, 3281, -5077, -4999 },
-  { -3791, 2410, -4906, -5288 },
-  { -730, 2303, -4217, -3755 },
-  { -1812, 2311, -5492, -3709 },
-  { -610, 4336, -3915, -3783 },
-  { -2841, 4337, -4278, -4430 },
-  { -1662, 4666, -4661, -3964 },
-  { -589, 5209, -4923, -3682 },
-  { -4155, 2234, -4076, -4218 },
-  { -3951, 2770, -2665, -2805 },
-  { -2302, 3228, -3717, -1908 },
-  { -3129, 4373, -2264, -2851 },
-  { -447, 1363, -3578, -4323 },
-  { -2648, 4237, -3159, -3071 },
-  { -4072, 3241, -3541, -4605 },
-  { -4507, 3458, -2339, -3838 },
-  { -1646, 997, -4926, -3970 },
-  { -3025, 1614, -3940, -1242 },
-  { -1337, 1756, -3163, -5529 },
-  { -3203, 1865, -3282, -4354 },
-  { -1646, 2118, -2203, -6018 },
-  { 174, 1871, -2707, -4639 },
-  { -2607, 1485, -4778, -4750 },
-  { -2199, 3991, -3134, -4879 },
-  { -2962, 3323, -2816, -2419 },
-  { -5286, 2495, -4548, -5395 },
-  { -2810, 3710, -2274, -4211 },
-  { -330, 3006, -2993, -4678 },
-  { -1187, 2411, -2743, -5196 },
-  { -664, 4033, -3101, -5641 },
-  { -1458, 3602, -2816, -5371 },
-  { -4116, 4923, -3321, -5630 },
-  { -4165, 2528, -2592, -4798 },
-  { -2759, 3080, -2333, -5719 },
-  { -5157, 3011, -5526, -6348 },
-  { -3095, 2126, -5881, -4234 },
-  { -4377, 3849, -3600, -6099 },
-  { -1994, 4947, -5235, -4753 },
-  { -1067, 600, -3258, -5133 },
-  { -4992, 3302, -2208, -5051 },
-  { -3377, 2981, -1655, -4815 },
-  { -3325, 2446, -1787, -6116 },
-  { -2341, 2737, -3240, -6347 },
-  { -2258, -3732, 3710, -1235 },
-  { -1558, -3849, 2694, -3012 },
-  { -599, -4837, 3050, -2951 },
-  { -2246, -5433, 2798, -1910 },
-  { -2255, -4989, 3260, 270 },
-  { -3026, -5353, 2693, -1036 },
-  { -1151, -6097, 1097, -3782 },
-  { -3391, -6012, 2130, -1303 },
-  { -2850, -4422, 3375, -480 },
-  { -1138, -3779, 1491, -4162 },
-  { -551, -3892, 3787, -2082 },
-  { -3221, -3676, 3144, -1202 },
-  { -3023, -5196, 2650, 605 },
-  { -1756, -5729, 2646, 321 },
-  { -2693, -4409, 494, -4797 },
-  { -1913, -4573, 3372, -1730 },
-  { -1277, -3604, 4061, -993 },
-  { -420, -4993, 1351, -4796 },
-  { -3052, -5333, 1435, -1242 },
-  { -602, -5034, 3869, -1141 },
-  { -2436, -4680, 1665, -3019 },
-  { -2657, -3658, 1459, -3391 },
-  { -1220, -6246, 2749, -525 },
-  { -3838, -4844, 2265, -1735 },
-  { -1247, -5679, 3356, -1417 },
-  { -917, -5448, 3342, 105 },
-  { -1756, -6839, 2276, -2350 },
-  { -412, -5206, 1764, -3539 },
-  { -1439, -6915, 1442, -3750 },
-  { -1381, -4439, 3863, -282 },
-  { -3482, -4953, 2726, -336 },
-  { -1376, -5931, 1714, -1987 },
-  { -1716, -4405, 2608, 105 },
-  { -1590, -5191, 2652, -2704 },
-  { -2149, -6442, 2453, -1263 },
-  { -3426, -3832, 2334, -1829 },
-  { -2747, -5948, 2362, -173 },
-  { -2435, -3267, 2966, -1710 },
-  { -3979, -4282, 2705, -775 },
-  { -356, -4238, 2544, -4343 },
-  { -1363, -6471, 2817, -1836 },
-  { -2878, -5117, 218, -3149 },
-  { -3539, -5196, 1710, -2356 },
-  { -2888, -4537, 2746, -1701 },
-  { -1870, -4439, 1496, -4121 },
-  { -1486, -3388, 3349, -2145 },
-  { -3333, -4138, 1467, -2876 },
-  { -345, -5340, 1012, -1190 },
-  { -1672, -4992, 2289, -1029 },
-  { -2146, -5528, 3038, -635 },
-  { -316, -3656, 3426, -3152 },
-  { -2695, -5812, 2336, -2050 },
-  { -2067, -6052, 737, -3258 },
-  { -2664, -4205, -350, -1266 },
-  { -617, -5406, 80, -4853 },
-  { -2418, -3825, 1853, -1326 },
-  { -1961, -4339, 583, -4315 },
-  { -1495, -5141, -133, -5205 },
-  { -3208, -6440, 1691, -2069 },
-  { -2632, -3633, 2325, -2761 },
-  { -2624, -5670, 1252, -3676 },
-  { -3687, -5608, 687, -2833 },
-  { -3320, -5707, 16, -3877 },
-  { -2738, -6112, 84, -5135 },
-  { 2277, -5661, 3076, 843 },
-  { 1555, -5769, 2821, -5236 },
-  { 536, -6381, 603, -4910 },
-  { 734, -4609, 3314, -4092 },
-  { 1836, -4547, 3267, -4322 },
-  { -13, -5976, 3752, -1607 },
-  { 1423, -6318, 2336, 398 },
-  { 365, -7779, 1498, -534 },
-  { 2104, -8366, 2946, -1345 },
-  { 143, -5545, 1898, -3756 },
-  { 655, -6852, 1430, 148 },
-  { 4, -6653, 2397, -59 },
-  { 2346, -5996, 4562, -934 },
-  { 1229, -7104, 2963, -598 },
-  { -528, -7048, 2887, -1790 },
-  { 1451, -6857, 3900, -1637 },
-  { 554, -6018, 3336, 9 },
-  { 3278, -5758, 4034, 129 },
-  { 3541, -7145, 4905, -1575 },
-  { 2339, -6907, 3464, -301 },
-  { 2775, -7301, 1667, -3894 },
-  { 539, -7887, 991, -4156 },
-  { 2115, -7421, 3131, -3075 },
-  { 2803, -8546, 2564, -5836 },
-  { 2869, -5833, 1620, -4561 },
-  { 2591, -7281, 3215, -4719 },
-  { -1228, -8477, 706, -4782 },
-  { 1967, -5243, 4813, -1940 },
-  { 701, -7010, 2273, -3893 },
-  { 915, -8470, 1918, -5620 },
-  { -94, -6715, 156, -3873 },
-  { 1074, -5607, 4389, -1017 },
-  { 2739, -6551, 1227, -3521 },
-  { 725, -7835, 2701, -1291 },
-  { -493, -7475, 2263, -1075 },
-  { -412, -6508, 2984, -744 },
-  { 665, -5451, 3725, -2692 },
-  { 1499, -8129, 3564, -2072 },
-  { 2870, -6333, 4487, -2108 },
-  { 706, -5007, 3911, -152 },
-  { -482, -8660, 1483, -2900 },
-  { 2481, -6596, 2518, -1715 },
-  { 1403, -6414, 1398, -5387 },
-  { 652, -6267, 583, -5942 },
-  { 694, -7540, 646, -6272 },
-  { 2275, -7614, 256, -5015 },
-  { 1416, -9727, 1900, -3153 },
-  { 2760, -6433, 3875, -3771 },
-  { 2325, -11196, 2182, -5155 },
-  { 1223, -11061, 1377, -5097 },
-  { 108, -10603, 307, -4952 },
-  { -118, -8268, 1650, -1572 },
-  { 1839, -7943, 1755, -612 },
-  { 2501, -9056, 981, -2969 },
-  { 2902, -8476, 1491, -5780 },
-  { 1995, -11175, 1585, -3643 },
-  { 696, -8212, 828, -2474 },
-  { 1526, -8649, 1380, -1210 },
-  { 461, -7253, 3222, -2229 },
-  { 2966, -8641, 4121, -3271 },
-  { 833, -6039, 2361, -1086 },
-  { 3565, -7312, 1980, -5427 },
-  { 2850, -8671, 3760, -1846 },
-  { 2643, -7281, 2163, -173 },
-  { 3463, -3706, -3132, -923 },
-  { 1315, -3825, -3443, 2 },
-  { 2594, -4083, -3815, 670 },
-  { 1826, -4291, -2741, -155 },
-  { 868, -3749, -4175, -298 },
-  { 2008, -4237, -3897, -517 },
-  { 1242, -3493, -4335, -1335 },
-  { -88, -4142, -3390, -1529 },
-  { 2176, -3488, -3822, -975 },
-  { 1706, -5188, -3415, -637 },
-  { 2717, -6159, -2333, -882 },
-  { 1276, -3978, -4361, 537 },
-  { 2471, -5556, -2866, -208 },
-  { 799, -4673, -4086, 56 },
-  { 1901, -4786, -3533, 270 },
-  { 3036, -3902, -3606, -333 },
-  { 2249, -3317, -4319, -144 },
-  { 2594, -4207, -2105, -2930 },
-  { 4008, -4774, -2626, -902 },
-  { 1038, -3659, -3496, -2454 },
-  { 2725, -3597, -3298, -1535 },
-  { 1662, -5803, -2813, 175 },
-  { 705, -3757, -3441, -1484 },
-  { 1860, -5987, -2821, -886 },
-  { 3786, -4918, -2199, -1929 },
-  { 3683, -4235, -2547, -1287 },
-  { 2531, -4896, -2956, -1593 },
-  { 1005, -5585, -3324, -180 },
-  { 1625, -5229, -1756, -3642 },
-  { 1494, -5041, -2989, -2685 },
-  { 2718, -4655, -3224, -867 },
-  { 2374, -6640, -1745, -2975 },
-  { 2133, -6436, -2477, -1499 },
-  { 1833, -4418, -3523, -1512 },
-  { 1128, -4910, -2658, -1106 },
-  { 689, -4777, -2831, -2085 },
-  { 3593, -5280, -2627, -315 },
-  { 3264, -3771, -2673, -1861 },
-  { 3202, -5602, -2409, 402 },
-  { 552, -4618, -2221, -3002 },
-  { 3095, -5356, -2666, -1083 },
-  { 3401, -4609, -3146, 45 },
-  { 3051, -4662, -2192, -2232 },
-  { 2798, -5552, -2462, -1941 },
-  { 2354, -5815, -2223, -2619 },
-  { 192, -3708, -2807, -2658 },
-  { 1886, -4226, -1862, -3529 },
-  { 2526, -3976, -2819, -2332 },
-  { 1577, -3870, -2711, -2806 },
-  { 1288, -5588, -3382, -1403 },
-  { 2711, -5399, -1564, -3253 },
-  { 1459, -5492, -2222, -322 },
-  { 2823, -5091, -2886, 776 },
-  { 3559, -5821, -2109, -1360 },
-  { 1587, -6331, -2760, -1909 },
-  { 2139, -5213, -2874, -2120 },
-  { 1318, -4337, -3695, -2098 },
-  { 821, -4471, -1849, -565 },
-  { 3329, -4782, -1725, -89 },
-  { 582, -4914, -4105, -1119 },
-  { 417, -4144, -4072, -2529 },
-  { -199, -3803, -2765, -4042 },
-  { 2731, -4283, -2143, 1 },
-  { 2911, -6187, -1951, -2116 },
-  { 1573, -6094, -493, -2838 },
-  { 2081, -6927, -864, -3211 },
-  { 1058, -7826, 79, -364 },
-  { 3147, -5570, -684, -978 },
-  { 3572, -5856, 1060, 1824 },
-  { 1143, -6702, -1478, 338 },
-  { 2341, -7220, -88, 260 },
-  { 3639, -6861, 668, 815 },
-  { 2227, -6268, -1706, 446 },
-  { 3390, -6082, -353, 1302 },
-  { 1123, -7556, -1237, -430 },
-  { 1729, -7742, 729, -218 },
-  { 1457, -6774, 587, 579 },
-  { 505, -6919, -569, 371 },
-  { 1106, -7245, 78, 158 },
-  { 2755, -6745, -1122, 338 },
-  { 3069, -6040, -1415, 986 },
-  { 2174, -7064, -1430, -283 },
-  { 1390, -8626, -446, -3031 },
-  { 3534, -6890, -431, 547 },
-  { 2267, -9618, 475, -2994 },
-  { 3672, -7673, 75, -115 },
-  { 2131, -7560, -1206, -750 },
-  { 2972, -7477, -685, -262 },
-  { 1604, -6637, -672, 699 },
-  { 1666, -7577, -577, -240 },
-  { 1591, -6554, -2158, -94 },
-  { 2348, -6286, -353, 1123 },
-  { 2017, -8810, -412, -1805 },
-  { 2892, -6713, -1765, -554 },
-  { 2500, -6828, -1995, -1197 },
-  { 3877, -6639, -224, -1655 },
-  { 2392, -7872, -91, -333 },
-  { 3562, -7370, -532, -2836 },
-  { 2552, -7614, 164, -1805 },
-  { 990, -6104, 218, 438 },
-  { 910, -7861, 312, -1195 },
-  { 1472, -6327, 372, -640 },
-  { 1576, -7143, -1983, -843 },
-  { 422, -7625, -457, -278 },
-  { 1797, -8532, 405, -1011 },
-  { 1088, -7396, -238, -2277 },
-  { 3209, -6753, -1431, -2072 },
-  { 2617, -6839, 100, -2573 },
-  { 2575, -8573, -387, -3188 },
-  { 3618, -6971, -1190, -321 },
-  { 2205, -7361, -1695, -2008 },
-  { 2985, -6297, 1464, 1179 },
-  { 2804, -7310, 1053, 338 },
-  { 1362, -6074, -1163, -840 },
-  { 3336, -6325, -1794, 21 },
-  { 2836, -8109, 818, -329 },
-  { 2791, -5879, 560, 1546 },
-  { 2392, -6064, 135, 100 },
-  { 1838, -6194, 596, 1085 },
-  { 1926, -7515, -414, -4901 },
-  { 3225, -7298, -1202, -1189 },
-  { 3960, -7558, -659, -719 },
-  { 3442, -6647, -1692, -1095 },
-  { 3381, -6441, 262, -886 },
-  { 1431, -8150, -1186, -1406 },
-  { 340, -8498, -150, -899 },
-  { 3004, -8149, -260, -953 },
-  { 2749, -6611, 563, 873 },
-  { -6647, -1325, -4517, -4691 },
-  { -6005, -1657, -4089, -3797 },
-  { -3157, 588, -5213, -3068 },
-  { -3311, -1425, -6329, -3726 },
-  { -5866, -819, -3857, -2744 },
-  { -5001, -1799, -1075, -4621 },
-  { -5330, -2650, -2672, -4664 },
-  { -4930, -539, -2363, -4010 },
-  { -2984, 10, -3863, -5749 },
-  { -1055, -2106, -3713, -4267 },
-  { -5476, -502, -4279, -6504 },
-  { -5231, -1543, -5018, -6425 },
-  { -5134, -363, -3165, -5109 },
-  { -3953, -771, -4107, -6393 },
-  { -2159, -563, -3652, -5342 },
-  { -3888, -2321, -919, -5057 },
-  { -1236, -597, -4235, -4193 },
-  { -4053, 675, -3083, -6174 },
-  { -2793, -1089, -5396, -3460 },
-  { -3000, -44, -2209, -6575 },
-  { -3336, -1531, -4313, -5160 },
-  { -2127, 128, -4851, -3692 },
-  { -3321, 136, -2067, -5660 },
-  { -5215, 1404, -4374, -4356 },
-  { -2747, 400, -6340, -3691 },
-  { -3926, -599, -5361, -5006 },
-  { -2875, -2592, -5143, -4092 },
-  { -4991, -1958, -5322, -4891 },
-  { -4965, -1318, -6652, -5333 },
-  { -4920, -1691, -3388, -5561 },
-  { -3644, -3354, -2688, -5982 },
-  { -5076, -919, -4563, -2984 },
-  { -6114, 250, -3884, -3915 },
-  { -4014, 744, -3973, -1924 },
-  { -5543, -1041, -5557, -3847 },
-  { -4711, -1352, -5649, -2603 },
-  { -3362, 775, -5305, -4879 },
-  { -5001, 107, -3554, -2888 },
-  { -6258, -1651, -6356, -6566 },
-  { -4529, 407, -5003, -3865 },
-  { -5154, 550, -5278, -5465 },
-  { -4195, -467, -1894, -3129 },
-  { -5022, 1127, -3349, -3314 },
-  { -6075, 1250, -4313, -5641 },
-  { -2677, -2283, -2312, -5903 },
-  { -4113, 193, -1195, -4833 },
-  { -3940, -1048, -1389, -5079 },
-  { -3703, 917, -4043, -4451 },
-  { -3366, -4231, -1534, -5488 },
-  { -3326, -3583, -2091, -4903 },
-  { -5144, 1254, -2532, -4949 },
-  { -5982, -870, -2545, -4555 },
-  { -3925, -157, -5367, -2281 },
-  { -6419, -746, -5668, -4371 },
-  { -5787, 518, -7096, -5805 },
-  { -4258, 954, -6453, -4321 },
-  { -4771, -695, -4158, -1639 },
-  { -7078, -760, -5195, -5877 },
-  { -7348, 83, -4101, -4586 },
-  { -2430, 184, -2874, -1679 },
-  { -2284, -3943, -2924, -5034 },
-  { -1804, -1785, -3002, -4710 },
-  { -4399, -2772, -1815, -4637 },
-  { -6340, -2626, -2824, -5191 },
-  { -4998, -5168, -3480, 1905 },
-  { -3958, -5492, -1599, 1579 },
-  { -2471, -3755, -276, 3182 },
-  { -3033, -5779, -1063, 1554 },
-  { -2936, -4829, -1290, 2386 },
-  { -1835, -5073, -3051, 1299 },
-  { -1724, -3771, -3935, 2324 },
-  { -5070, -2550, -3692, 768 },
-  { -4326, -5333, -297, 1878 },
-  { -3472, -5619, -3094, 992 },
-  { -3027, -4384, -3038, 2265 },
-  { -3201, -5332, 67, 2200 },
-  { -1681, -4373, -1947, 2461 },
-  { -3221, -3329, -4238, 2564 },
-  { -1262, -2968, -2915, 3227 },
-  { -3419, -1878, -3373, 2110 },
-  { -2244, -5583, -2012, 1288 },
-  { -1971, -5266, -990, 1812 },
-  { -2975, -2778, -452, 4063 },
-  { -2198, -1165, -3298, 2965 },
-  { -4782, -4894, -4767, 664 },
-  { -6002, -3950, -2806, 2025 },
-  { -3142, -3162, -2859, 3295 },
-  { -3262, -3340, -4123, 1596 },
-  { -4014, -3918, -1955, 3361 },
-  { -1700, -3463, -1346, 3449 },
-  { -4245, -4445, -4743, 1644 },
-  { -4180, -3969, -401, 3281 },
-  { -2782, -5240, -4117, 1156 },
-  { -5744, -4040, -1439, 3470 },
-  { -5063, -4663, -323, 3172 },
-  { -4531, -3319, -844, 3988 },
-  { -6226, -5125, -2064, 2976 },
-  { -3115, -3267, -1531, 3898 },
-  { -4628, -4421, -2864, 2808 },
-  { -4559, -2989, -3442, 2024 },
-  { -1775, -4487, -656, 2477 },
-  { -2664, -1865, -1884, 4081 },
-  { -1828, -2575, -3894, 3378 },
-  { -6441, -3677, -2025, 1677 },
-  { -4141, -2156, -1191, 3474 },
-  { -4802, -1623, -1727, 2160 },
-  { -5474, -2745, -1475, 2498 },
-  { -3664, -1056, -1975, 2491 },
-  { -4672, -3062, -2235, 2933 },
-  { -4205, -5960, -2849, 1517 },
-  { -4995, -5708, -1739, 1805 },
-  { -4892, -6080, -4793, 872 },
-  { -4270, -4172, -4263, 2185 },
-  { -4687, -1470, -2905, 1023 },
-  { -6446, -5017, -3919, 1000 },
-  { -6046, -5538, -3943, 2006 },
-  { -6028, -3750, -3953, 771 },
-  { -5959, -4582, -5024, 824 },
-  { -5818, -2576, -2249, 1326 },
-  { -5659, -5345, -1119, 2500 },
-  { -3346, -4155, 606, 2749 },
-  { -5680, -4827, -2501, 1838 },
-  { -6193, -2543, -1295, 840 },
-  { -6871, -4925, -3512, 1801 },
-  { -5605, -1788, -1895, 779 },
-  { -3922, -5712, -4644, 510 },
-  { -4745, -3869, -4533, 99 },
-  { -2984, -4907, -399, 1497 },
-  { 1847, -478, 3061, -5812 },
-  { 4450, -1116, 3609, -6570 },
-  { 3139, 99, 3007, -5532 },
-  { 2590, -3782, 3138, -4770 },
-  { 1881, 1204, 5778, -3404 },
-  { 3631, 2060, 5566, -5038 },
-  { 3461, 1961, 5167, -3800 },
-  { 2947, 273, 4536, -4389 },
-  { 4453, -1730, 5788, -4370 },
-  { 4032, 1805, 2666, -4534 },
-  { 3487, -944, 2313, -6028 },
-  { 1313, 34, 4210, -4067 },
-  { 5632, -1502, 5825, -5855 },
-  { 7736, -547, 4879, -5476 },
-  { 4906, -1512, 4760, -5760 },
-  { 3843, 447, 1091, -4958 },
-  { 2982, -1135, 5442, -4386 },
-  { 3579, 271, 3031, -6770 },
-  { 3932, -211, 4688, -5507 },
-  { 4411, 1720, 2387, -5584 },
-  { 5379, -479, 4575, -6280 },
-  { 3613, -362, 2012, -4885 },
-  { 3744, -2013, 4493, -5073 },
-  { 5693, 109, 4379, -3362 },
-  { 5475, -621, 5317, -3985 },
-  { 6411, -673, 5708, -4752 },
-  { 4933, -796, 7262, -4290 },
-  { 2804, 444, 6276, -3655 },
-  { 4120, -517, 6078, -4531 },
-  { 5119, 841, 3486, -3910 },
-  { 4738, 1539, 3525, -2970 },
-  { 5086, 370, 5895, -5640 },
-  { 4235, 2716, 4589, -5044 },
-  { 3691, 682, 6199, -4700 },
-  { 6111, -570, 6271, -6528 },
-  { 2611, 1277, 3756, -4802 },
-  { 4395, 970, 3807, -5879 },
-  { 5225, 2299, 3242, -4333 },
-  { 5144, 1778, 4946, -5545 },
-  { 2989, -3016, 3247, -5495 },
-  { 2983, 920, 2071, -6059 },
-  { 5270, -903, 4434, -2350 },
-  { 6415, -585, 3970, -3554 },
-  { 3866, -197, 5216, -2884 },
-  { 3767, -1298, 6702, -3315 },
-  { 6299, 2620, 5284, -6824 },
-  { 6654, 646, 3653, -4927 },
-  { 4770, 3047, 5160, -6287 },
-  { 5364, 434, 2919, -5207 },
-  { 2998, 1344, 4801, -2456 },
-  { 3896, 1013, 3773, -1864 },
-  { 2115, 655, 2999, -6344 },
-  { 5170, -981, 2849, -4464 },
-  { 2735, -2159, 2717, -5776 },
-  { 2430, -1952, 4392, -4559 },
-  { 6143, -1180, 3659, -4746 },
-  { 4978, -1483, 1726, -4875 },
-  { 3486, -2383, 3306, -4301 },
-  { 1434, -1372, 4171, -4770 },
-  { 3354, -2627, 1525, -5093 },
-  { 6790, 2386, 3995, -5909 },
-  { 1475, -2674, 3451, -4204 },
-  { 1999, -3494, 3693, -5556 },
-  { 4764, -2848, 2856, -5589 },
-  { -3677, 5131, 2827, -2934 },
-  { -2844, 7078, 2852, -3580 },
-  { -3902, 6434, 4118, -1911 },
-  { -1769, 7530, 3492, -3541 },
-  { -1937, 5679, -447, -1127 },
-  { -2456, 4680, 4196, -2407 },
-  { -2778, 8241, 1698, -4288 },
-  { -2876, 6104, 5182, -2387 },
-  { -2802, 7341, 4463, -2938 },
-  { -1025, 6267, 4752, -3201 },
-  { -2349, 5413, 2041, -3794 },
-  { -2252, 8225, 2856, -4269 },
-  { -1465, 4967, 4976, -2500 },
-  { -636, 7565, 3517, -4233 },
-  { -1905, 5618, 3904, -2942 },
-  { -302, 6816, 3343, -3316 },
-  { -2210, 4156, 2817, -3511 },
-  { -717, 6568, 1863, -2951 },
-  { -3873, 5682, 2164, -575 },
-  { -2878, 5835, 440, -2597 },
-  { -3228, 7701, 2610, -2514 },
-  { -3608, 8888, 3377, -2468 },
-  { -2582, 9717, 2519, -3126 },
-  { -5238, 6202, 2866, -2831 },
-  { -3428, 7370, 3056, -335 },
-  { -1681, 8836, 1210, -2010 },
-  { -3276, 6724, 1156, -3930 },
-  { -894, 8149, 827, -1258 },
-  { -2965, 8631, 2549, -1320 },
-  { -3961, 6902, 3581, 55 },
-  { -1894, 7745, 1750, -841 },
-  { -821, 6844, 850, -676 },
-  { -608, 6948, -4, -1376 },
-  { 615, 6524, 1089, -1147 },
-  { -2972, 5668, 1091, -489 },
-  { -157, 4649, 2904, -413 },
-  { 673, 5121, 1498, -66 },
-  { -390, 5902, 1611, -245 },
-  { -2349, 5478, 4772, -1320 },
-  { 88, 6798, 1972, -1859 },
-  { -1213, 5120, 2991, 200 },
-  { -2347, 6040, 2839, 376 },
-  { -578, 5976, 3364, -1796 },
-  { -1391, 5872, 3002, -965 },
-  { -564, 4496, 3946, -1186 },
-  { -2299, 6386, 3135, -2176 },
-  { -2131, 5641, 2011, 1223 },
-  { -772, 5807, 1124, 895 },
-  { -2837, 6758, 2297, -740 },
-  { -3091, 6298, 1415, -2126 },
-  { -4197, 6036, 1843, -3022 },
-  { -41, 6459, 92, 344 },
-  { -2241, 6860, 2095, -4396 },
-  { -1931, 7088, 2117, -2135 },
-  { -2375, 4422, 1688, -3169 },
-  { -1742, 6674, 1538, -119 },
-  { -4818, 7749, 4192, -1577 },
-  { -2004, 5672, 193, -430 },
-  { -3825, 6042, 2128, -1898 },
-  { -1108, 8033, 2119, -3013 },
-  { -2370, 5453, 1721, 266 },
-  { -1570, 7134, 614, -2638 },
-  { -1519, 8752, 3503, -4330 },
-  { -2050, 3845, 2907, -1126 },
-  { 5085, 4412, -335, -1923 },
-  { 3618, 1423, -613, -4012 },
-  { 4481, 3729, 589, -4631 },
-  { 4270, 3216, -1763, -3168 },
-  { 4241, 1796, -1701, -2796 },
-  { 4787, 2338, -487, -3639 },
-  { 2915, 3429, -621, -4753 },
-  { 5175, 1660, -1265, -3223 },
-  { 4280, 4057, -684, -4079 },
-  { 4980, 4419, -1455, -2719 },
-  { 5436, 2464, 387, -4197 },
-  { 4507, 4018, 1121, -3314 },
-  { 6020, 2401, -413, -3201 },
-  { 4200, 3789, -333, -2813 },
-  { 5229, 2493, -1194, -1878 },
-  { 5851, 2695, -492, -2292 },
-  { 5743, 3288, -697, -1221 },
-  { 5692, 2612, 979, -2227 },
-  { 5085, 2067, 1046, -1214 },
-  { 3163, 2240, -2098, -3435 },
-  { 5228, 1898, 145, -2397 },
-  { 5860, 3976, -418, -2872 },
-  { 6008, 3399, 1027, -3506 },
-  { 4126, 2035, 1865, -893 },
-  { 5375, 3596, 511, -2362 },
-  { 1937, 1493, -852, -122 },
-  { 3473, 4849, 547, -2603 },
-  { 4631, 2977, 1141, -1768 },
-  { 6149, 3050, -71, -1886 },
-  { 4069, 4353, -289, -1429 },
-  { 2884, 1225, -1388, 365 },
-  { 5485, 2518, -235, -571 },
-  { 1216, 4375, 1443, 398 },
-  { 4988, 3106, 107, -1435 },
-  { 4511, 2801, 307, -444 },
-  { 3235, 4386, 327, -676 },
-  { 2055, 3708, 1657, -305 },
-  { 5839, 2374, 290, -1385 },
-  { 5110, 3305, 1936, -4206 },
-  { 6416, 2920, 338, -2736 },
-  { 3350, 2824, -1269, -3881 },
-  { 4840, 1815, 464, 186 },
-  { 2399, 3332, 238, 1238 },
-  { 3516, 1363, 1582, 688 },
-  { 3582, 1874, 154, -4770 },
-  { 3261, 2878, 886, 283 },
-  { 3877, 2658, -327, 884 },
-  { 4151, 3436, 2173, -2923 },
-  { 3592, 3674, 1281, -1295 },
-  { 4561, 3730, -1114, -1747 },
-  { 4595, 3625, -558, -575 },
-  { 2577, 2348, 2267, 120 },
-  { 5242, 3299, 32, -3412 },
-  { 4264, 3637, 709, -2320 },
-  { 6556, 3570, -838, -2472 },
-  { 5745, 4014, -940, -1973 },
-  { 5629, 4475, 477, -3328 },
-  { 5269, 3199, 1682, -3085 },
-  { 4432, 2416, 1145, -3299 },
-  { 4465, 2505, 2162, -2186 },
-  { 4643, 4941, -88, -2885 },
-  { 4568, 5231, 552, -3915 },
-  { 5667, 3075, -1406, -2963 },
-  { 5418, 5259, -771, -2818 },
-  { -256, -7875, 511, -471 },
-  { -1813, -7971, -424, -396 },
-  { -306, -7006, 862, 282 },
-  { -2306, -6422, -1440, 508 },
-  { -245, -6787, 375, -100 },
-  { -1309, -6065, -20, 779 },
-  { -1656, -6047, -641, 1307 },
-  { -1496, -6522, 964, 726 },
-  { -2291, -6588, -202, 795 },
-  { -762, -7522, 1454, -558 },
-  { -2270, -7004, -834, -580 },
-  { -1139, -7078, 259, 362 },
-  { -2535, -7568, -1040, 49 },
-  { -3786, -7280, 934, -476 },
-  { -3336, -6368, 606, 1056 },
-  { -3602, -6924, 52, 714 },
-  { -2278, -6550, 1674, 204 },
-  { -2855, -5765, 930, 1530 },
-  { -2889, -7325, -215, 305 },
-  { -2749, -6080, -237, 1452 },
-  { -985, -6667, 1577, 400 },
-  { -2036, -6083, 380, 1267 },
-  { -2077, -7460, 380, -30 },
-  { -1775, -7175, 1540, -386 },
-  { -3065, -6927, 989, 168 },
-  { -2836, -7602, 117, -3392 },
-  { -1058, -6396, 593, -3078 },
-  { -844, -6062, 999, -236 },
-  { -3261, -6951, 1491, -720 },
-  { -2186, -8484, 75, -1287 },
-  { -2882, -7756, 456, -510 },
-  { -1800, -6879, 960, -1183 },
-  { -2554, -7241, 1614, -1474 },
-  { -2608, -5305, 392, 851 },
-  { -2973, -6562, -859, 858 },
-  { -2640, -5989, 1031, -416 },
-  { -977, -8366, 705, -1434 },
-  { -1213, -7409, -77, -1390 },
-  { -1335, -6657, 2125, -123 },
-  { -2544, -6862, 1852, -737 },
-  { -3235, -6422, 1752, -103 },
-  { -1300, -7557, 939, -348 },
-  { -3476, -7579, 202, -109 },
-  { -2482, -6572, 753, 619 },
-  { -2554, -8136, -648, -429 },
-  { -1012, -7870, -3, -421 },
-  { -3604, -6247, 32, -3102 },
-  { -1486, -7271, 2013, -1021 },
-  { -578, -6799, -523, 405 },
-  { -2841, -5948, 1644, 911 },
-  { -2411, -7473, 1084, -484 },
-  { -2238, -6033, 294, -1059 },
-  { -3459, -6470, -201, -790 },
-  { -2027, -6009, 1833, 805 },
-  { -1433, -8047, 1531, -1754 },
-  { -3258, -7884, 763, -1422 },
-  { -1544, -6928, -729, 478 },
-  { -2314, -8415, 74, -3757 },
-  { -3201, -5684, 95, -2214 },
-  { -2423, -8694, 725, -3631 },
-  { -3545, -7071, 1162, -1798 },
-  { -294, -9662, 403, -2274 },
-  { -2290, -5460, 1196, 402 },
-  { -1603, -6713, 903, -2363 },
-  { 4121, 2491, -3142, -2482 },
-  { 4500, 3305, -3671, -1567 },
-  { 5973, 3172, -1348, -534 },
-  { 4830, 3379, -1549, 643 },
-  { 5214, 3938, -2641, -2302 },
-  { 4639, 4826, -5532, -847 },
-  { 5639, 2731, -2170, -963 },
-  { 6084, 3487, -3525, -1346 },
-  { 5971, 3154, -2190, -2316 },
-  { 5618, 4865, -6927, 116 },
-  { 5345, 3568, -7391, 709 },
-  { 5429, 5078, -3811, -1524 },
-  { 6960, 2037, -3515, -1096 },
-  { 7092, 2531, -4557, -588 },
-  { 6061, 4247, -5651, -478 },
-  { 4595, 3684, -4907, -827 },
-  { 7497, 3213, -3048, -424 },
-  { 5996, 2137, -3098, -1745 },
-  { 6198, 5199, -2223, -2274 },
-  { 6888, 2851, -2768, -1675 },
-  { 6114, 4210, -2316, -954 },
-  { 7127, 4242, -3041, -1408 },
-  { 6126, 3668, -1517, -1427 },
-  { 6245, 6129, -4225, -1186 },
-  { 6816, 3213, -2101, -964 },
-  { 5345, 5276, -2643, -847 },
-  { 6592, 4665, -4338, 484 },
-  { 6746, 3751, -3443, 124 },
-  { 5453, 1980, -2738, 2606 },
-  { 4662, 2179, -4226, -1059 },
-  { 5571, 3208, -3554, 174 },
-  { 5256, 4447, -1815, -1481 },
-  { 5400, 2570, -1210, 235 },
-  { 7056, 2549, -2674, 318 },
-  { 4574, 4340, -2892, -130 },
-  { 6203, 4587, -3273, -305 },
-  { 5103, 1925, -2715, -2137 },
-  { 3905, 4296, -1700, 247 },
-  { 4421, 4605, -3299, 811 },
-  { 5671, 1273, -3870, -924 },
-  { 5486, 1805, -4901, 133 },
-  { 6437, 2578, -1828, -106 },
-  { 5530, 5253, -5058, 1223 },
-  { 4816, 2025, -1215, 1443 },
-  { 3457, 3525, -2456, 3217 },
-  { 3316, 2595, -1108, 2459 },
-  { 3068, 3810, -2207, 1926 },
-  { 6351, 5436, -6470, 600 },
-  { 6324, 4240, -5365, 2416 },
-  { 4851, 4774, -4075, 1878 },
-  { 4900, 3679, -5198, 1078 },
-  { 8347, 3633, -4565, -171 },
-  { 5244, 5718, -3853, 173 },
-  { 3960, 3492, -2939, 2105 },
-  { 6070, 3473, -2351, 161 },
-  { 8228, 3034, -3360, -901 },
-  { 7006, 3985, -1940, -1926 },
-  { 7123, 4681, -4301, -878 },
-  { 5122, 4097, -1851, -449 },
-  { 6200, 2060, -2251, 1049 },
-  { 7106, 3844, -7209, 2625 },
-  { 7108, 3370, -6734, 533 },
-  { 6859, 2849, -3992, 1360 },
-  { 5458, 2278, -3253, 1131 },
-  { -1072, -2109, 4783, -1073 },
-  { -319, -2604, 4257, -2418 },
-  { 2466, 1300, 3476, -314 },
-  { 2847, -1502, 5296, -141 },
-  { 1667, -1273, 5559, -2725 },
-  { 2877, -3402, 6434, 204 },
-  { 53, -2637, 5275, -1181 },
-  { 1091, -2215, 5803, -1549 },
-  { 2397, -922, 4327, 1182 },
-  { 219, -3747, 4647, -1564 },
-  { -29, -2705, 4812, 1277 },
-  { 1499, -2608, 5648, 1407 },
-  { 2139, -2399, 4202, 2791 },
-  { -426, -2064, 5528, 151 },
-  { 2560, -2803, 6179, -2806 },
-  { 4537, -2479, 3797, 1095 },
-  { 888, -3357, 5341, -415 },
-  { 4460, -1814, 5388, -1227 },
-  { 3920, -3268, 6364, -703 },
-  { 3343, -4698, 4410, 784 },
-  { 309, -1897, 6306, 1223 },
-  { 958, -3318, 4254, -3167 },
-  { -99, 1596, 6018, -1983 },
-  { -429, -853, 6407, 878 },
-  { 1170, -1322, 6290, -417 },
-  { 2288, -505, 6303, -1999 },
-  { 3312, -1674, 6749, -2494 },
-  { -415, -3401, 4721, -371 },
-  { -189, -1210, 4844, -2002 },
-  { 888, -4142, 4377, 130 },
-  { 2469, -4381, 5398, -2492 },
-  { 2879, -2912, 5094, -2598 },
-  { -717, -617, 5650, -685 },
-  { 1470, -3863, 5352, -1684 },
-  { 3935, -96, 3823, -730 },
-  { 3769, -430, 3168, 694 },
-  { 2556, 385, 3539, 512 },
-  { 77, -1415, 5111, 2655 },
-  { 2724, -2158, 6715, -822 },
-  { 1832, 1001, 5385, -1900 },
-  { 900, 2198, 4464, -559 },
-  { 441, 69, 5921, -1743 },
-  { -1161, 738, 6732, -308 },
-  { 257, 2035, 4091, 736 },
-  { 1607, 1288, 4355, -23 },
-  { -13, 1316, 4180, 1672 },
-  { 1511, 1336, 3057, 1435 },
-  { 2189, -3813, 4530, 939 },
-  { 3632, -706, 2646, 1375 },
-  { 4266, -3761, 4241, 1077 },
-  { 3101, -427, 5273, -1202 },
-  { 2293, 276, 4810, -313 },
-  { 3430, -1851, 3101, 2045 },
-  { 3453, -2979, 5142, 942 },
-  { 1683, -3281, 4802, 2002 },
-  { 3954, -4715, 5611, 578 },
-  { 1272, -155, 5085, 454 },
-  { 128, -194, 5095, 1409 },
-  { 820, 880, 5797, -2658 },
-  { -1095, 656, 5774, 1095 },
-  { 813, -1669, 4320, -3251 },
-  { -119, 518, 6372, -651 },
-  { 2922, -4299, 6115, -877 },
-  { 4205, -4273, 4004, 2642 },
-  { -1211, -3892, 224, 3127 },
-  { -34, -4371, 1321, 2318 },
-  { 77, -6326, 1201, 828 },
-  { 3995, -3775, 1958, 3233 },
-  { 178, -3301, 1985, 3318 },
-  { 2330, -3801, 1033, 3195 },
-  { 1413, -5536, 826, 1709 },
-  { 2468, -3499, 3653, 3631 },
-  { 741, -4617, 1723, 2008 },
-  { 1246, -3043, 2978, 3949 },
-  { -343, -4308, 2258, 2189 },
-  { -682, -4640, 454, 2272 },
-  { 1236, -4829, 2491, 1642 },
-  { -512, -3766, 1182, 3052 },
-  { 119, -3939, 3712, 971 },
-  { -1145, -4624, 1360, 2281 },
-  { 101, -4746, 2866, 1255 },
-  { -1500, -5455, 539, 1637 },
-  { -969, -5909, 1414, 1128 },
-  { -1261, -4939, -231, 2022 },
-  { -226, -5345, 1207, 705 },
-  { 2712, -5109, 3205, 1866 },
-  { -476, -5913, 273, 1208 },
-  { -2039, -4464, 624, 2545 },
-  { -2351, -3930, 2019, 2673 },
-  { -2675, -4849, 1522, 1990 },
-  { -1524, -3461, 1446, 3204 },
-  { 477, -5314, 1710, 1577 },
-  { 656, -3729, 2346, 2511 },
-  { 550, -5917, 1975, 1040 },
-  { 1728, -4704, 3067, 1058 },
-  { -9, -5247, 506, 1760 },
-  { -574, -5135, 1675, 1672 },
-  { 2129, -3781, 3444, 2313 },
-  { 1144, -4439, 2214, 2529 },
-  { 1292, -4160, 3185, 1833 },
-  { 2445, -3262, 2534, 3227 },
-  { 2266, -4401, 2023, 2400 },
-  { -587, -3602, 3408, 2067 },
-  { -885, -4951, 3228, 1174 },
-  { -728, -2711, 2807, 3552 },
-  { 1019, -3043, 3195, 2954 },
-  { 1888, -4615, 1140, 2454 },
-  { 660, -5616, 754, 800 },
-  { -1975, -5371, 1649, 1585 },
-  { -1544, -5436, 2422, 1081 },
-  { -422, -5882, 2390, 750 },
-  { 1336, -5557, 2441, 1230 },
-  { 136, -4001, 267, 2854 },
-  { -522, -3289, 2226, 2728 },
-  { -971, -4580, 2471, 708 },
-  { 704, -5306, 3300, 1001 },
-  { 325, -3464, 3555, 2398 },
-  { 794, -3686, 848, 3169 },
-  { 660, -3017, 4584, 3242 },
-  { -1486, -3978, 2170, 1644 },
-  { -1615, -4650, 2688, 1844 },
-  { 750, -4578, 538, 2239 },
-  { 1668, -5849, 1455, 1031 },
-  { 3486, -4681, 2030, 2183 },
-  { 2642, -5429, 1696, 1761 },
-  { 4491, -4502, 3538, 2767 },
-  { 3545, -4528, 3514, 2982 },
-  { 3269, -3676, 2758, 3966 },
-  { 5572, 1146, 209, -3379 },
-  { 7459, 1053, 593, -1896 },
-  { 4480, 200, -310, -4259 },
-  { 5577, -939, 242, -3992 },
-  { 8142, 442, 1257, -3083 },
-  { 5442, 1261, 1424, -3236 },
-  { 6260, -183, 3125, -2532 },
-  { 7179, 889, 1618, -2548 },
-  { 6416, 932, 2379, -2487 },
-  { 7094, 2560, 961, -3392 },
-  { 7322, 463, 2732, -3735 },
-  { 6632, 1577, 1912, -3272 },
-  { 6312, 1349, 3028, -3460 },
-  { 6105, 386, 1213, -977 },
-  { 5478, 1158, 1114, -486 },
-  { 6493, 410, 1686, -2180 },
-  { 6378, 1881, 1333, -2240 },
-  { 5711, 812, 1958, -1300 },
-  { 6844, 877, 730, -1189 },
-  { 6824, -245, 2249, -2000 },
-  { 7515, 1521, 1251, -3058 },
-  { 6697, 1051, 1300, -1749 },
-  { 6476, 1425, 811, -2773 },
-  { 7350, 465, -76, -2849 },
-  { 6975, 2095, 567, -2492 },
-  { 4691, 1736, 2660, -2289 },
-  { 7837, 1456, 340, -2767 },
-  { 7930, 507, 838, -2074 },
-  { 6106, 1502, 766, -1110 },
-  { 4891, -659, 835, -3954 },
-  { 7250, 141, 1369, -1523 },
-  { 7651, 67, 1651, -2298 },
-  { 7364, -305, 601, -3132 },
-  { 7179, 193, 2491, -2871 },
-  { 6504, -272, 2167, -1322 },
-  { 4456, 983, 2300, -421 },
-  { 4817, 457, 1695, 371 },
-  { 6914, 555, 850, -3159 },
-  { 5904, 1030, 202, -1959 },
-  { 6258, 880, 2233, -4503 },
-  { 6029, 10, 2130, -3600 },
-  { 6449, 985, 1129, -3963 },
-  { 6616, -18, -111, -3285 },
-  { 4496, 775, 817, -4276 },
-  { 6134, 2338, 1470, -2973 },
-  { 6911, 152, 430, -1946 },
-  { 4053, 991, 3218, -1193 },
-  { 5435, 1285, 3124, -2412 },
-  { 5507, 1836, 1935, -1988 },
-  { 5240, 689, 2189, -2670 },
-  { 6638, 1719, 606, -1799 },
-  { 5556, -180, 129, -2595 },
-  { 5644, 1918, 1281, -4316 },
-  { 6410, 1088, -282, -3117 },
-  { 6503, 1841, 312, -3514 },
-  { 6947, 20, 1358, -3886 },
-  { 5464, 2109, 2398, -3194 },
-  { 5616, -407, 2140, -498 },
-  { 6121, 2707, 2379, -4096 },
-  { 7303, 1846, 2266, -4095 },
-  { 5444, 470, 2718, -1553 },
-  { 5817, -645, 3285, -1349 },
-  { 5625, 1427, 1103, -1991 },
-  { 6041, -806, 1196, -2943 },
-  { 3050, -5722, 4070, -5460 },
-  { 3420, -4386, 4078, -5155 },
-  { 6020, -3982, 7268, -2689 },
-  { 7502, -4317, 7894, -3973 },
-  { 4156, -3558, 5247, -4316 },
-  { 4725, -4401, 7290, -1540 },
-  { 6688, -5122, 8216, -3210 },
-  { 9176, -6576, 9276, -4963 },
-  { 8706, -5708, 7987, -4621 },
-  { 7060, -3535, 6532, -3308 },
-  { 5600, -2719, 5363, -1568 },
-  { 4661, -2803, 6263, -4716 },
-  { 3673, -3636, 6147, -3433 },
-  { 5305, -2585, 6073, -2638 },
-  { 7614, -1962, 6079, -5266 },
-  { 6760, -3366, 7382, -4322 },
-  { 6385, -3883, 4797, -1353 },
-  { 8182, -5120, 4298, -4641 },
-  { 9130, -6198, 4975, -3063 },
-  { 7421, -5436, 5576, -3713 },
-  { 3483, -4898, 5443, -2745 },
-  { 4907, -5643, 6390, -4105 },
-  { 8119, -7008, 7992, -6764 },
-  { 6528, -6122, 6967, -5590 },
-  { 5890, -4190, 6624, -5688 },
-  { 6815, -7934, 7275, -5456 },
-  { 5434, -4306, 5169, -5378 },
-  { 4364, -6436, 5376, -2604 },
-  { 8152, -3404, 5913, -5048 },
-  { 7983, -4863, 4262, -2461 },
-  { 8023, -6188, 6238, -5062 },
-  { 6753, -3692, 3935, -3723 },
-  { 6826, -4760, 3284, -4051 },
-  { 7224, -7423, 4492, -3875 },
-  { 6904, -2590, 6587, -6248 },
-  { 6106, -1944, 7345, -5506 },
-  { 4956, -2990, 7808, -3146 },
-  { 6908, -6885, 5949, -1288 },
-  { 7162, -6058, 3419, -3401 },
-  { 7015, -7080, 6907, -3018 },
-  { 6971, -6832, 5646, -3273 },
-  { 8014, -5546, 5471, -1544 },
-  { 6792, -2220, 5105, -2879 },
-  { 8494, -3974, 4408, -3999 },
-  { 9591, -4866, 6027, -4558 },
-  { 5264, -5161, 6101, -738 },
-  { 5803, -6141, 5197, -5231 },
-  { 4657, -6822, 3232, -5189 },
-  { 4791, -5135, 3809, -4665 },
-  { 6108, -5103, 2379, -3873 },
-  { 4680, -3909, 3234, -5093 },
-  { 5802, -3853, 3795, -4984 },
-  { 4360, -7483, 4802, -3877 },
-  { 5429, -7517, 5911, -3717 },
-  { 6866, -2280, 4880, -4634 },
-  { 10131, -4628, 4414, -4092 },
-  { 10811, -5189, 7746, -5337 },
-  { 5663, -8941, 5287, -5680 },
-  { 8023, -5991, 7403, -2796 },
-  { 9669, -6919, 6525, -4932 },
-  { 7275, -3796, 4962, -2547 },
-  { 8848, -4806, 5677, -3080 },
-  { 8128, -4308, 7749, -6569 },
-  { 4032, -5196, 2282, -6239 },
-  { 6593, 700, -229, 304 },
-  { 8260, 539, -66, -1259 },
-  { 6605, 176, -814, -109 },
-  { 8057, 0, -1, -136 },
-  { 7382, -38, -484, -1129 },
-  { 8373, -929, 682, -454 },
-  { 7674, 690, -1278, 546 },
-  { 7326, -517, 406, -1283 },
-  { 7612, -1715, -1167, 1175 },
-  { 8590, 441, -782, -710 },
-  { 8572, -1202, -291, 260 },
-  { 7308, -147, -1785, 414 },
-  { 6787, -353, -672, 934 },
-  { 5177, -133, 179, 82 },
-  { 4161, -34, 447, 1497 },
-  { 5997, -902, 1533, -121 },
-  { 5727, -871, -1370, 945 },
-  { 8386, -252, 293, -823 },
-  { 6573, -1354, 682, 616 },
-  { 7650, -2096, 725, 457 },
-  { 8122, 78, 636, -1400 },
-  { 8421, 428, -1620, 131 },
-  { 7341, -1292, -717, 186 },
-  { 7998, -49, -720, 266 },
-  { 5987, -351, 669, 844 },
-  { 7314, -1620, 250, -603 },
-  { 7219, -1562, -572, 1994 },
-  { 8682, -358, -290, -388 },
-  { 5810, 155, -178, 1199 },
-  { 7246, -12, 1042, -786 },
-  { 7357, -923, 1468, -475 },
-  { 7801, 621, -212, -724 },
-  { 5346, -514, 1210, 1356 },
-  { 8459, 36, -127, -779 },
-  { 6878, -2429, 854, 1750 },
-  { 7280, -1401, -1353, 2845 },
-  { 7579, -2148, -1463, 2087 },
-  { 6637, 946, -872, 750 },
-  { 4807, -1100, 1289, 2602 },
-  { 4495, 219, 1551, 1128 },
-  { 7639, 506, 446, -1107 },
-  { 6359, 188, 1009, -115 },
-  { 6641, -1820, 1655, 723 },
-  { 5394, -2382, 1604, 2542 },
-  { 6021, -2644, 2396, 1407 },
-  { 4698, 882, 245, 1525 },
-  { 8103, 573, -798, -349 },
-  { 8045, -519, 997, -1092 },
-  { 7571, -122, 227, -338 },
-  { 5347, -1200, 630, 1718 },
-  { 7070, 790, 218, -544 },
-  { 7440, 728, -527, -20 },
-  { 6402, -355, 197, -736 },
-  { 4031, 771, 866, 1895 },
-  { 6009, 896, 445, -31 },
-  { 5160, 1098, -856, 1784 },
-  { 7980, -886, -1293, 1396 },
-  { 6318, -1361, 2423, 252 },
-  { 7547, -699, 133, 506 },
-  { 8562, -2344, 940, 264 },
-  { 5890, 1187, -1425, 2194 },
-  { 6558, -645, -1311, 2621 },
-  { 4634, -1671, 2075, 1623 },
-  { 5614, 105, -816, 2376 },
-  { 6646, 1558, -1365, 630 },
-  { 6998, 1150, -2117, -990 },
-  { 6555, 2311, -1093, -1783 },
-  { 6682, 1430, -2391, -1940 },
-  { 7861, 1555, -2977, -1188 },
-  { 6745, 1723, -459, -2085 },
-  { 7504, 1229, -1666, -2060 },
-  { 7937, 671, -2128, -1529 },
-  { 7139, 991, -735, -2632 },
-  { 6867, 1592, -1303, -2324 },
-  { 6401, 2230, -1732, -2508 },
-  { 7201, 2184, -2169, -1988 },
-  { 6636, 2190, -995, -2840 },
-  { 7620, 2306, -2089, -651 },
-  { 7584, 1875, -1438, -631 },
-  { 9214, 1561, -2464, -1139 },
-  { 6154, 1318, -1237, -2917 },
-  { 7917, 2847, -1797, -1599 },
-  { 8309, 2029, -2555, -465 },
-  { 8204, 1282, -584, -2405 },
-  { 8440, 1035, -1147, -1137 },
-  { 7107, 1858, -60, -1568 },
-  { 6781, 2912, -873, -1463 },
-  { 7603, 1316, -319, -1249 },
-  { 7833, 1335, -78, -1849 },
-  { 7930, 1141, -1016, -695 },
-  { 7883, 1610, -1017, -1314 },
-  { 8069, 1409, -1811, -196 },
-  { 8319, 1031, -582, -1590 },
-  { 5948, 1537, -2153, -2373 },
-  { 8684, 1171, -1871, -850 },
-  { 8357, 2484, -2411, -1292 },
-  { 6516, 2092, -193, -1167 },
-  { 6112, 1697, 22, -525 },
-  { 7161, 703, -602, -1879 },
-  { 6047, 2351, -807, -219 },
-  { 8072, 1854, -1817, -1553 },
-  { 6956, 1304, 76, -1011 },
-  { 6607, 1481, -544, -162 },
-  { 6958, 2541, -265, -1938 },
-  { 6416, 2514, -777, -850 },
-  { 7272, 2110, -899, -1171 },
-  { 7741, 2153, -283, -2614 },
-  { 6482, 2041, -1758, -1221 },
-  { 6762, 940, -1862, -2281 },
-  { 5610, 1194, -1691, -1561 },
-  { 7833, 2164, -823, -1952 },
-  { 5460, 1438, -848, 1189 },
-  { 6011, 1377, -771, -1557 },
-  { 7679, 544, -1134, -2214 },
-  { 7209, 1292, -2714, -1564 },
-  { 5567, 1200, -404, -169 },
-  { 5853, 1461, -1465, -518 },
-  { 6782, 689, -844, -860 },
-  { 7330, 1337, -1152, -71 },
-  { 7189, 1506, -653, -685 },
-  { 6860, 2116, -1403, -240 },
-  { 8804, 1516, -1391, -1760 },
-  { 7210, 2689, -1498, -989 },
-  { 7030, 3022, -1441, -2083 },
-  { 5649, 1836, -407, 525 },
-  { 7451, 3099, -717, -2464 },
-  { 7384, 1656, -2007, 398 },
-  { 6504, 707, -1919, -134 },
-  { -1851, 3639, -2279, -695 },
-  { -4037, 1644, -77, 1329 },
-  { -4025, 1960, -1565, -567 },
-  { -3430, 2495, -795, 368 },
-  { -4771, 2480, 993, 756 },
-  { -3431, 2058, -2539, -971 },
-  { -3802, 3418, 380, 217 },
-  { -3074, 3350, -1652, -1056 },
-  { -3705, 326, -1650, 1535 },
-  { -3122, 1281, -1192, 1607 },
-  { -4601, 1367, -968, 53 },
-  { -3808, 958, 44, 2560 },
-  { -2079, 2530, -1485, 1166 },
-  { -3707, 343, -2889, 180 },
-  { -5249, 1431, -31, 688 },
-  { -4990, 125, -704, 1270 },
-  { -2771, 1334, -2446, 746 },
-  { -2292, 994, -1527, 2630 },
-  { -1261, 3070, -2519, 268 },
-  { -2544, 3890, -1057, -552 },
-  { -4421, 255, -1980, 530 },
-  { -2951, 454, -13, 3643 },
-  { -2262, 1815, -370, 2880 },
-  { -2383, 3657, -649, 576 },
-  { -3541, -161, -1389, 2550 },
-  { -4241, 1575, 1325, 2561 },
-  { -2767, 4037, 1221, 1578 },
-  { -3748, 2697, 1148, 1801 },
-  { -4686, 2385, -220, 0 },
-  { -1531, 1645, -2751, 1327 },
-  { -45, 4032, -799, 2298 },
-  { -2915, 2280, 709, 2495 },
-  { -1199, 3278, -406, 2346 },
-  { -2471, 116, -2706, 2060 },
-  { -2440, 2173, -2894, -344 },
-  { -3375, 2287, 1781, 3226 },
-  { -2153, 3568, 1827, 2918 },
-  { -862, 2267, -1626, 2527 },
-  { -2698, 1135, 301, 4239 },
-  { -2364, 2123, 1010, 3710 },
-  { -2447, 3281, -81, 1408 },
-  { -2660, 4735, 472, 258 },
-  { -1053, 3097, 2682, 2398 },
-  { -3366, -1037, -1152, -868 },
-  { -643, 4242, 2212, 1259 },
-  { 971, 3991, 934, 643 },
-  { -1617, 2002, 2139, 2195 },
-  { -4897, 972, 784, 1719 },
-  { -1275, 2992, 1039, 3821 },
-  { -392, 4973, -209, 1821 },
-  { -1028, 4718, -1479, -137 },
-  { 50, 3914, 553, 2210 },
-  { 678, 4364, 359, 1303 },
-  { -582, 4911, 514, 1671 },
-  { 1276, 3914, -1252, 2934 },
-  { -1496, 3984, 857, 2330 },
-  { 772, 4744, -655, 2332 },
-  { -799, 5283, -439, 624 },
-  { 1341, 2937, 650, 2027 },
-  { -1739, 4892, 1275, 1702 },
-  { -892, 2596, -151, 3951 },
-  { -3532, 1090, 1292, 32 },
-  { 321, 3146, 2647, 1475 },
-  { 264, 4199, -1591, 1317 },
-  { -452, -2357, 2266, 4192 },
-  { 3022, -1033, -2389, 5678 },
-  { -1162, -1342, 3543, 4990 },
-  { -474, -1477, -1223, 5016 },
-  { -699, -2857, 900, 3835 },
-  { -461, -2255, -117, 4626 },
-  { 1204, -2062, -1211, 4403 },
-  { 2192, -3035, -337, 3966 },
-  { 108, -831, 279, 5643 },
-  { 1457, -620, -2908, 5276 },
-  { -2527, -78, 1085, 5460 },
-  { -1978, -1918, -949, 4733 },
-  { 32, 367, -1904, 5166 },
-  { 1890, -1665, 440, 4752 },
-  { -518, -348, 2816, 4891 },
-  { 3695, -2490, -1374, 4603 },
-  { 246, -1965, 3549, 3969 },
-  { 1100, -3111, 656, 3737 },
-  { -1379, 870, -414, 4575 },
-  { 628, -357, -1227, 6179 },
-  { -1129, -1318, -2457, 4576 },
-  { -425, -98, -73, 6336 },
-  { 367, -887, 2990, 4207 },
-  { 2091, -1251, 2444, 3557 },
-  { -1759, -1610, 2046, 5273 },
-  { 3210, 1414, -20, 2616 },
-  { 3303, -2636, 1005, 4237 },
-  { -327, -3107, -640, 3687 },
-  { -197, 764, 572, 5486 },
-  { 646, -767, 1388, 5464 },
-  { 104, 2742, -228, 3907 },
-  { -236, 1829, -579, 4585 },
-  { -2150, -474, -1525, 4006 },
-  { -23, -2632, -2400, 3892 },
-  { -12, -1739, -2910, 4867 },
-  { -2310, -368, -102, 4583 },
-  { -1991, -2061, 533, 4531 },
-  { 3884, -1446, -153, 4393 },
-  { 1568, 14, -289, 5268 },
-  { -1376, -253, -2797, 3417 },
-  { 3193, -2577, 2475, 3566 },
-  { 3418, 617, 1350, 1857 },
-  { 3792, -24, -272, 3370 },
-  { 153, 1159, 2906, 2877 },
-  { 511, 2162, 1548, 2741 },
-  { 262, 819, -2791, 3734 },
-  { 4232, -2015, 1486, 3477 },
-  { 2943, -1110, -1014, 5480 },
-  { 2842, 369, 703, 3476 },
-  { 3011, 1634, -933, 3553 },
-  { 4412, -1548, -942, 5021 },
-  { -1405, 593, 2372, 5267 },
-  { 2093, 2129, 896, 2365 },
-  { 4845, -1980, 0, 3823 },
-  { -2140, 81, 3278, 5637 },
-  { 1484, 2665, -324, 3653 },
-  { 10, 192, 1620, 5291 },
-  { 2152, 738, -2269, 5000 },
-  { 2102, 2748, -1652, 4707 },
-  { 2855, -2131, -387, 5188 },
-  { 1173, 676, 1338, 3277 },
-  { 2340, -2329, -2064, 4095 },
-  { 861, -2024, 1296, 5055 },
-  { 2189, 3225, -695, 2626 },
-  { 6196, -7079, 1943, -822 },
-  { 4547, -4813, 3261, 1856 },
-  { 4243, -6904, 3443, 448 },
-  { 4581, -7503, 946, 506 },
-  { 6626, -7754, 3427, 470 },
-  { 3407, -9088, 3269, -1496 },
-  { 4079, -6464, 2304, 777 },
-  { 5621, -9336, 2684, -768 },
-  { 5351, -6464, 5238, -214 },
-  { 5961, -8007, 1724, -3091 },
-  { 4213, -8067, 603, -246 },
-  { 7208, -7403, 3168, -1738 },
-  { 6098, -7700, 329, -1379 },
-  { 6525, -6735, 4248, -1072 },
-  { 6073, -6241, 2167, -2378 },
-  { 4609, -9218, 3051, -1033 },
-  { 6813, -7283, 1581, -1897 },
-  { 6126, -6275, 2789, 681 },
-  { 4423, -6538, 1621, -1692 },
-  { 6272, -8298, 3167, -1855 },
-  { 6172, -8558, 4498, -1169 },
-  { 4844, -8588, 1647, -366 },
-  { 6209, -8807, 1581, -369 },
-  { 5389, -8059, 550, -192 },
-  { 6654, -9775, 2504, -1063 },
-  { 7103, -7998, 806, 530 },
-  { 5662, -6736, 1565, -3620 },
-  { 4165, -9564, 4191, -2131 },
-  { 4526, -7181, 576, -2875 },
-  { 4633, -8623, 2807, -4742 },
-  { 3709, -7794, 1815, 34 },
-  { 3634, -8622, 2313, -826 },
-  { 6991, -8447, 2063, -3198 },
-  { 7757, -9486, 2255, -558 },
-  { 4149, -7778, 4728, -1696 },
-  { 5767, -7427, 1113, 707 },
-  { 4592, -6261, 2329, 1864 },
-  { 3159, -10498, 1677, -4273 },
-  { 3534, -9010, 2437, -3565 },
-  { 4479, -10821, 2715, -4942 },
-  { 3207, -9805, 3054, -3886 },
-  { 4627, -8189, 3018, -2354 },
-  { 5527, -10566, 3244, -2749 },
-  { 4346, -10127, 3335, -3084 },
-  { 6132, -10085, 3316, -1308 },
-  { 5629, -9704, 2178, -3058 },
-  { 3603, -8538, 1246, -624 },
-  { 3737, -8488, 395, -3167 },
-  { 5465, -11414, 2810, -4640 },
-  { 5306, -7745, 2721, -3988 },
-  { 7000, -9111, 1695, -1409 },
-  { 6663, -7741, 2466, -4079 },
-  { 4083, -7175, 1836, -4831 },
-  { 3613, -9926, 1342, -3455 },
-  { 6588, -8033, 457, -258 },
-  { 4720, -8102, 17, -1209 },
-  { 7414, -8709, 1294, -344 },
-  { 5437, -10030, 4043, -1704 },
-  { 4862, -9281, 1558, -1431 },
-  { 6800, -6403, 5113, 862 },
-  { 4623, -8242, 2667, -228 },
-  { 5919, -5083, 3348, 2135 },
-  { 5985, -8889, 2733, -5105 },
-  { 5029, -5767, 4407, 719 },
-  { 354, -6158, -838, -3001 },
-  { 351, -5943, -2104, -1534 },
-  { -633, -7190, -25, -4798 },
-  { -1595, -7235, -3812, -1400 },
-  { 103, -6197, -2933, -78 },
-  { -1722, -5020, -3441, -4333 },
-  { -1963, -5644, -4365, -270 },
-  { -846, -5743, -3477, 196 },
-  { -191, -5348, -4054, -469 },
-  { -2515, -7754, -3495, -818 },
-  { -2090, -6710, -2701, 117 },
-  { -546, -7036, -1398, 163 },
-  { -278, -7091, -2662, -536 },
-  { -622, -7962, -2731, -1464 },
-  { -1555, -8118, -3612, -2057 },
-  { -1094, -6280, -2314, 505 },
-  { -2556, -8538, -4024, -2247 },
-  { 109, -7134, -3107, -1823 },
-  { -900, -6954, -3340, -717 },
-  { -605, -7113, -3656, -2154 },
-  { 837, -6263, -3211, -2177 },
-  { -417, -5810, -3871, -1469 },
-  { -1318, -5649, -4207, -3198 },
-  { 413, -6765, -2082, -33 },
-  { -3101, -6450, -4362, -766 },
-  { 755, -6489, -2967, -846 },
-  { 1117, -7106, -2452, -1352 },
-  { -1202, -8387, -3072, -2897 },
-  { -365, -4894, -3561, -2937 },
-  { -2372, -8776, -265, -4441 },
-  { -1224, -8678, -896, -5074 },
-  { -755, -10096, -600, -6623 },
-  { 300, -8206, -225, -4568 },
-  { -1176, -6824, -2633, -3527 },
-  { -2006, -5443, -1526, -5849 },
-  { -1115, -5540, -2363, -4785 },
-  { 1059, -6812, -2543, -2654 },
-  { -1976, -6861, -3062, -5508 },
-  { -379, -5328, -2321, -3624 },
-  { -2108, -5860, -4518, -1915 },
-  { -379, -7885, -1329, -594 },
-  { 774, -5389, -581, -5213 },
-  { -2601, -5083, -1849, -4921 },
-  { -176, -5580, 74, -5075 },
-  { -204, -6780, -190, -6232 },
-  { 418, -7594, -1987, -820 },
-  { -1873, -8529, -2926, -1609 },
-  { 1340, -6362, -919, -4975 },
-  { 577, -7990, -2044, -1873 },
-  { -2572, -7413, -1745, -2224 },
-  { -2037, -7030, -1461, -7138 },
-  { -2559, -8756, -2039, -5836 },
-  { -2079, -6764, -1209, -5669 },
-  { -1613, -7801, -2006, -685 },
-  { -1865, -6583, -722, -3529 },
-  { -589, -6358, -1377, -1003 },
-  { -540, -7514, -1331, -3542 },
-  { 419, -6192, -1677, -4927 },
-  { -2786, -8763, -2966, -5065 },
-  { -2172, -8411, -1726, -4675 },
-  { -3382, -9833, -3497, -5722 },
-  { -2433, -10169, -2077, -5775 },
-  { -424, -9451, -1096, -3658 },
-  { -537, -8522, -910, -1897 },
-  { -5550, 2807, 1683, -693 },
-  { -6395, 635, 3573, -1246 },
-  { -7544, 2280, 2140, 44 },
-  { -8751, 1136, 2951, -794 },
-  { -5605, 2709, 2052, 916 },
-  { -7650, 654, 869, 135 },
-  { -6939, 967, 1409, 870 },
-  { -7834, 2123, 3310, 974 },
-  { -6935, 2818, 1274, -1678 },
-  { -5605, 2233, 1013, 471 },
-  { -7095, 1849, 1648, 198 },
-  { -6636, 1634, 712, -37 },
-  { -7279, 978, 296, -315 },
-  { -7664, 3504, 3292, -216 },
-  { -7836, 1209, 1221, -257 },
-  { -7913, 2201, 1765, -1529 },
-  { -7077, 3783, 2632, -1407 },
-  { -5565, 1645, 1410, -622 },
-  { -6494, 2879, 1181, -759 },
-  { -7073, 3137, 3010, 550 },
-  { -7249, 1839, 847, -805 },
-  { -6630, 2197, 282, -1096 },
-  { -8836, 1573, 1988, -1090 },
-  { -7809, 1274, 836, -1198 },
-  { -7895, 2970, 3511, -1097 },
-  { -6960, 1664, 1356, -2442 },
-  { -6582, 2866, 2273, 307 },
-  { -7221, 821, 2851, -1435 },
-  { -6015, 1703, 2001, -2367 },
-  { -8082, 1034, 2103, 239 },
-  { -5952, 1912, 301, -465 },
-  { -6099, 841, 379, 567 },
-  { -6343, 50, 494, 658 },
-  { -6586, 983, 591, -893 },
-  { -5500, 869, 2187, -2479 },
-  { -6482, 60, 1545, -979 },
-  { -6705, 515, 1974, -53 },
-  { -6460, 1755, 1325, -1275 },
-  { -6093, 2617, 2465, -623 },
-  { -7330, 2161, 594, -2115 },
-  { -7324, 762, 1593, -2004 },
-  { -6385, 679, 1510, -2514 },
-  { -6159, 241, 2976, -1631 },
-  { -8583, 3030, 4045, -162 },
-  { -6299, 66, 2209, -2103 },
-  { -5428, 1279, 3267, -1846 },
-  { -6438, 1335, 2728, -1631 },
-  { -8012, 1070, 2428, -1151 },
-  { -6201, 2781, 2349, -1918 },
-  { -5918, 1139, 3121, -148 },
-  { -6314, 2481, 3137, -1808 },
-  { -7180, 1722, 2435, -1602 },
-  { -6750, 1829, 3763, -1145 },
-  { -6713, 1777, 2221, 1212 },
-  { -7479, 1835, 3627, -479 },
-  { -7299, 10, 2406, -1593 },
-  { -8249, 3129, 996, -2870 },
-  { -8374, 1534, 1333, -1882 },
-  { -7507, 3353, 1598, -2299 },
-  { -7379, 2701, 2326, -1167 },
-  { -8440, 2276, 2796, -542 },
-  { -10348, 1527, 2649, -1165 },
-  { -8184, 3614, 2574, -1738 },
-  { -5539, 1574, 1733, 1138 },
-  { 9404, -7652, 67, 79 },
-  { 8654, -3972, 1358, -60 },
-  { 8617, -4794, 117, 2318 },
-  { 7886, -4505, 1784, 1200 },
-  { 8636, -6125, 3879, -1003 },
-  { 9654, -6836, 1816, 205 },
-  { 9374, -6553, 913, 1875 },
-  { 8020, -6150, 1134, 2390 },
-  { 7786, -4970, 2078, -1857 },
-  { 8691, -6119, 711, 708 },
-  { 9039, -5568, 2944, -1902 },
-  { 9955, -5048, 1433, -601 },
-  { 8089, -6927, 3093, -2846 },
-  { 8487, -7024, 2415, 19 },
-  { 9388, -5287, 3577, -2655 },
-  { 8591, -7371, 2300, -996 },
-  { 9104, -4763, 1453, -2558 },
-  { 7615, -5457, 596, 164 },
-  { 9860, -7047, 3433, -614 },
-  { 8756, -4404, 2235, -964 },
-  { 9462, -4660, 299, -1822 },
-  { 10119, -5550, 2689, -1273 },
-  { 10915, -7471, 2705, -1007 },
-  { 11433, -7090, 1410, -1198 },
-  { 9882, -7431, 2965, -1895 },
-  { 7628, -5219, 769, -2661 },
-  { 8169, -5318, 2262, 70 },
-  { 8846, -6320, 1939, -754 },
-  { 7147, -5593, 1248, -971 },
-  { 10652, -5485, 935, 137 },
-  { 7778, -6533, 2564, -1932 },
-  { 8878, -5173, 1214, -361 },
-  { 9828, -4943, 282, 510 },
-  { 10042, -6134, 3895, -1914 },
-  { 7965, -6630, 3566, -433 },
-  { 8573, -4502, 3574, -1209 },
-  { 8398, -4801, 1031, -1347 },
-  { 10136, -7772, 2612, 1547 },
-  { 9890, -7280, 1768, -1083 },
-  { 8407, -6585, -706, -58 },
-  { 7976, -7582, 229, -131 },
-  { 10481, -8866, 1166, -147 },
-  { 10914, -4342, 3189, -2412 },
-  { 10440, -5198, -104, -1109 },
-  { 11227, -6530, 2381, -2449 },
-  { 8487, -8064, 1086, 230 },
-  { 9975, -6123, -857, -134 },
-  { 8339, -6498, 1232, -2337 },
-  { 11042, -4506, 1119, -2098 },
-  { 12563, -5592, 1837, -2062 },
-  { 11801, -5590, 632, -1296 },
-  { 10152, -5617, 1511, -1917 },
-  { 7800, -6473, 51, -1337 },
-  { 7941, -5560, 2438, -3270 },
-  { 6554, -3834, 2100, 1476 },
-  { 9065, -5520, -226, -1120 },
-  { 10794, -7120, -243, 122 },
-  { 10429, -6968, 272, -806 },
-  { 8942, -8914, 1442, -392 },
-  { 9969, -5051, 2033, -2953 },
-  { 7275, -4152, 3058, -64 },
-  { 11127, -5488, 4589, -3227 },
-  { 9626, -6666, 2739, -2958 },
-  { 6943, -5362, 4470, 1008 },
-  { -7456, -967, 2936, -1002 },
-  { -8622, -333, 6962, 2606 },
-  { -7486, -3392, 3668, 1287 },
-  { -8053, -827, 5148, 1097 },
-  { -6610, 454, 4952, 96 },
-  { -7701, -1982, 3161, -468 },
-  { -7307, -1132, 4071, -36 },
-  { -8125, -271, 5199, 3862 },
-  { -9182, -1950, 2813, 1878 },
-  { -9855, -952, 4794, 3010 },
-  { -7241, 1431, 4202, 2468 },
-  { -9646, 157, 4766, 1046 },
-  { -9371, 1230, 6009, 2958 },
-  { -11514, -64, 8630, 5248 },
-  { -6766, 565, 2766, 2140 },
-  { -8426, -9, 2852, 1271 },
-  { -11291, -1113, 5087, 2937 },
-  { -8297, 2092, 4495, 1264 },
-  { -9983, 735, 3809, -51 },
-  { -9048, -1000, 3191, -308 },
-  { -7331, -1987, 2655, 1391 },
-  { -7144, -21, 4333, 2161 },
-  { -6032, -1540, 3543, 896 },
-  { -7987, -1036, 1985, 1529 },
-  { -9264, 2004, 5194, 290 },
-  { -11308, -840, 5754, 1654 },
-  { -9130, -2398, 4292, 2973 },
-  { -6248, 838, 3563, 1223 },
-  { -6819, -2760, 3511, 119 },
-  { -7213, -2006, 4364, 762 },
-  { -5431, -1047, 4533, 166 },
-  { -7098, -641, 2021, 639 },
-  { -8628, -2249, 3588, 399 },
-  { -6352, -1498, 3560, -648 },
-  { -7033, -2190, 4870, 2562 },
-  { -7405, -46, 3772, -581 },
-  { -6104, 796, 5143, 1965 },
-  { -5787, 943, 5784, 3030 },
-  { -8367, 1465, 7192, 4097 },
-  { -8259, 789, 5694, 1963 },
-  { -10614, -1899, 5748, 2645 },
-  { -8258, -805, 3698, 2275 },
-  { -6877, -972, 6431, 3160 },
-  { -6483, 363, 7018, 3129 },
-  { -6283, -1358, 5191, 1524 },
-  { -8853, -3157, 4119, 1741 },
-  { -6086, -267, 3883, -835 },
-  { -7254, 1032, 6613, 4017 },
-  { -11470, -3350, 4649, 3426 },
-  { -6743, 481, 6148, 1239 },
-  { -5394, -166, 5309, 3165 },
-  { -7958, 1068, 4268, -240 },
-  { -10520, 2256, 7916, 2828 },
-  { -5132, -4, 5739, 1176 },
-  { -8643, 120, 3255, -629 },
-  { -9631, 1974, 8870, 4362 },
-  { -10663, -1221, 3733, 589 },
-  { -8224, -1843, 5806, 2655 },
-  { -8282, 1255, 8647, 3478 },
-  { -12311, -1505, 9043, 6256 },
-  { -11312, -856, 7136, 4681 },
-  { -11944, -722, 7941, 3309 },
-  { -7868, -463, 6846, 4196 },
-  { -8679, -241, 7410, 5347 },
-  { 6759, -4680, -508, 1220 },
-  { 5176, -6111, 944, 121 },
-  { 6843, -5667, -1368, -533 },
-  { 5616, -5884, -1471, -695 },
-  { 6030, -5089, -1808, -940 },
-  { 7444, -5463, -52, 1881 },
-  { 4207, -6079, -506, 1571 },
-  { 6785, -4410, -649, 3084 },
-  { 4838, -5214, 2026, 2998 },
-  { 4201, -5790, 645, 1811 },
-  { 6930, -5129, -1940, 1698 },
-  { 6332, -4627, 692, 3027 },
-  { 6285, -4314, -106, 3644 },
-  { 6255, -5450, -1975, 742 },
-  { 4199, -4676, -459, 1796 },
-  { 5592, -5500, 1345, 1300 },
-  { 4358, -5556, -2236, 114 },
-  { 4620, -5875, -1563, 888 },
-  { 4892, -7550, -327, -419 },
-  { 4734, -7085, 7, 613 },
-  { 3883, -5562, -1969, 1080 },
-  { 5610, -4990, -204, 834 },
-  { 4117, -6482, -1271, 341 },
-  { 6585, -5107, 892, 1169 },
-  { 6632, -3683, 302, 3002 },
-  { 6326, -5351, -983, -1250 },
-  { 4382, -7192, -730, -158 },
-  { 5227, -6540, -451, 1123 },
-  { 5468, -6472, -870, -1471 },
-  { 5191, -6402, -1365, -127 },
-  { 7407, -6317, -973, -336 },
-  { 4611, -6530, -820, -1980 },
-  { 4963, -5159, -2050, -966 },
-  { 4414, -5691, -211, -998 },
-  { 5954, -5873, 750, -1749 },
-  { 4394, -4796, -1268, 254 },
-  { 7161, -6214, -1010, 689 },
-  { 4965, -3598, 2372, 1711 },
-  { 6248, -6180, 981, 864 },
-  { 6473, -5336, 525, -600 },
-  { 4591, -6864, -1131, -900 },
-  { 6314, -6440, -1021, -375 },
-  { 5838, -6209, -1199, 944 },
-  { 5308, -5283, -2100, 1267 },
-  { 4342, -5860, -1637, -1356 },
-  { 5680, -4388, -1227, -104 },
-  { 4900, -4098, 1449, 4046 },
-  { 4677, -4284, -106, 3190 },
-  { 7574, -6173, -848, 1859 },
-  { 6493, -7207, -131, 726 },
-  { 5513, -5261, -2117, 4 },
-  { 6191, -7352, -193, -505 },
-  { 5885, -4333, 324, -134 },
-  { 6162, -6081, -312, -2044 },
-  { 4216, -6200, -1810, -572 },
-  { 5652, -7035, -696, -197 },
-  { 7131, -7189, -366, -60 },
-  { 5032, -4803, -1514, 2832 },
-  { 7386, -4610, -606, 3489 },
-  { 4211, -5031, 1221, 3047 },
-  { 4050, -4653, 1584, 1469 },
-  { 6852, -5302, -1861, 206 },
-  { 7736, -4816, -1794, 3359 },
-  { 6290, -3439, 1522, 2454 },
-  { 1768, 5990, -5560, -2594 },
-  { 3903, 5326, -1530, -1501 },
-  { 2472, 3738, -2117, -4240 },
-  { 3260, 5448, -904, -4733 },
-  { 1435, 7297, -3676, -4102 },
-  { 4096, 5951, -656, -3312 },
-  { 2178, 6009, -3146, -3724 },
-  { 3787, 5493, -5473, -1633 },
-  { 2998, 7286, -3334, -3571 },
-  { 2894, 6576, -4708, -2804 },
-  { 830, 6163, -4286, -3348 },
-  { 4755, 5569, -1730, -2739 },
-  { 4604, 6065, -3562, -2605 },
-  { 2749, 5141, -3986, -2775 },
-  { 3942, 4875, -2143, -3340 },
-  { 2819, 8517, -2004, -2724 },
-  { 2146, 6298, -689, -3093 },
-  { 5196, 6504, -3393, -1475 },
-  { 1851, 8386, -1748, -1420 },
-  { 3474, 8572, -3534, -2688 },
-  { 4503, 7560, -3561, -2245 },
-  { 4433, 6219, -2393, -1575 },
-  { 3506, 7248, -2275, -1977 },
-  { 3490, 7409, -3147, -604 },
-  { 4214, 6447, -3520, 516 },
-  { 619, 7034, -829, -1705 },
-  { 1732, 7395, -356, -2208 },
-  { 1226, 5204, -3294, -3732 },
-  { 2027, 5619, -1813, -4146 },
-  { 3078, 5877, 47, -2651 },
-  { 1654, 5458, 424, -682 },
-  { 3163, 5464, -2026, -270 },
-  { 2884, 5375, -685, -530 },
-  { 2950, 7286, -35, -2967 },
-  { 1986, 5066, -597, 482 },
-  { 3459, 4308, -3845, -2333 },
-  { 3155, 7037, -1346, -4345 },
-  { 2193, 6696, -717, -1319 },
-  { 3677, 5089, -3892, -487 },
-  { 2186, 5136, -4186, -1492 },
-  { 773, 5796, -917, 817 },
-  { 2489, 6546, -3570, -2117 },
-  { 1223, 6469, -1362, -33 },
-  { 271, 6061, -1466, -1725 },
-  { 2540, 5171, -1847, 1032 },
-  { 2548, 5251, -2697, 1677 },
-  { 771, 7600, -768, -632 },
-  { 4710, 6647, -4736, -1275 },
-  { 1369, 5917, -2971, -1056 },
-  { 163, 5239, -3499, -2275 },
-  { 2104, 4285, -3211, -3286 },
-  { 1107, 7411, -1972, -1671 },
-  { 2196, 7262, -2310, -1926 },
-  { -244, 6439, -1745, -839 },
-  { 3293, 3832, -2890, -3000 },
-  { 419, 6443, -379, -407 },
-  { 3077, 4930, -1156, -2869 },
-  { 2131, 5874, -2330, 224 },
-  { 690, 6538, -2212, -2841 },
-  { 1602, 4421, -2515, 1542 },
-  { 3318, 9373, -3032, -3477 },
-  { 5646, 7462, -5153, -1463 },
-  { 4139, 7137, -1539, -3321 },
-  { 3481, 9077, -1645, -3653 },
-  { -7747, 375, -106, -543 },
-  { -8587, -1379, -586, -461 },
-  { -10146, -892, 2094, 694 },
-  { -8103, 382, 504, -325 },
-  { -8548, -92, 94, -656 },
-  { -7460, 38, 152, 388 },
-  { -8266, -271, -459, -883 },
-  { -7935, -664, -1026, -802 },
-  { -8341, -109, 853, 161 },
-  { -8802, -1355, 1099, 630 },
-  { -8957, -6, 1108, -669 },
-  { -7260, -1520, -43, -407 },
-  { -7555, -174, 668, -2562 },
-  { -9014, -126, 227, -1191 },
-  { -8184, 769, 290, -1375 },
-  { -9476, 55, 962, -1528 },
-  { -8679, 541, 755, -1030 },
-  { -9842, -1626, 838, -1588 },
-  { -8513, -702, 788, -1998 },
-  { -10101, -1558, -366, -1841 },
-  { -8135, 78, 1479, -1813 },
-  { -9128, -454, 313, -1786 },
-  { -7554, -1084, 831, -2442 },
-  { -7576, -701, 2068, -1665 },
-  { -7791, -1481, 1587, -1808 },
-  { -6701, -596, -97, 802 },
-  { -7418, -15, 684, -963 },
-  { -7127, -477, -139, -426 },
-  { -8097, -110, -36, -264 },
-  { -7620, -1922, -590, -101 },
-  { -7647, -1201, 279, 660 },
-  { -7856, -1974, 758, -2271 },
-  { -8496, -167, 2232, -1143 },
-  { -8506, -1359, 624, -740 },
-  { -7274, -1052, 1062, -139 },
-  { -7800, -217, 91, -1794 },
-  { -7030, -1694, -955, 615 },
-  { -9020, -1864, 101, -2182 },
-  { -9400, -740, 598, -667 },
-  { -8448, -1184, 2024, -1272 },
-  { -8812, -570, -897, -2384 },
-  { -10559, -1286, 538, -1536 },
-  { -8728, -888, -1089, -1397 },
-  { -7080, -1185, 636, -1252 },
-  { -9880, 233, 2344, -782 },
-  { -7952, -1326, -378, -1947 },
-  { -7207, -378, 1408, -2237 },
-  { -8467, -1545, 902, -1987 },
-  { -9163, -1474, 924, -1739 },
-  { -8159, -992, -77, -2744 },
-  { -8343, 148, -423, -1573 },
-  { -9105, -649, -254, -1214 },
-  { -8939, 456, 281, -1905 },
-  { -8837, 179, -394, -2634 },
-  { -9145, 757, 1547, -1319 },
-  { -9775, -723, 441, -1680 },
-  { -8910, -686, 1529, -1525 },
-  { -9492, -1134, 2064, -938 },
-  { -6111, -943, 677, -31 },
-  { -7411, -613, -814, 46 },
-  { -9479, -922, -430, -2061 },
-  { -11298, -1268, 1318, -1117 },
-  { -8190, 832, 671, -2214 },
-  { -10453, -550, 1672, -886 },
-  { 1044, 9353, -1651, -5423 },
-  { 1034, 8149, -455, -6166 },
-  { 761, 8293, -3214, -4838 },
-  { 938, 8077, 164, -5130 },
-  { 1295, 8673, 2582, -5490 },
-  { -314, 7973, -2395, -5231 },
-  { -507, 9012, -2497, -5775 },
-  { 2396, 8314, -1022, -4673 },
-  { -1516, 8501, 1950, -4969 },
-  { -308, 7401, 1549, -4866 },
-  { -112, 8340, 3003, -4920 },
-  { -50, 9315, 1371, -5666 },
-  { -659, 9449, 2496, -5547 },
-  { 2573, 9148, -2270, -4783 },
-  { 830, 7104, -438, -3907 },
-  { 522, 10672, -677, -6483 },
-  { -1190, 10108, -510, -6518 },
-  { -427, 8271, -579, -6315 },
-  { 1602, 8113, -1927, -4418 },
-  { -2266, 8180, 448, -5190 },
-  { -1633, 8816, -226, -5771 },
-  { 759, 9481, -105, -5813 },
-  { 2254, 6679, -466, -5662 },
-  { -88, 6946, 895, -5958 },
-  { -1705, 10009, 1394, -5574 },
-  { 748, 7943, 540, -6692 },
-  { 1411, 7009, 232, -6145 },
-  { 697, 7290, -1221, -5342 },
-  { -1764, 10580, 1944, -3981 },
-  { -1334, 9124, 1195, -3903 },
-  { -905, 10067, 635, -5039 },
-  { 664, 10680, 49, -4625 },
-  { 1374, 9536, -777, -3591 },
-  { 252, 9698, -597, -2931 },
-  { 824, 9164, -1014, -2144 },
-  { 2438, 10569, -2289, -4424 },
-  { 2101, 7102, 507, -3614 },
-  { 294, 8051, -432, -1518 },
-  { -665, 10337, 547, -2852 },
-  { 1168, 11989, -492, -5427 },
-  { 1344, 6416, 302, -5061 },
-  { -1727, 12264, 1507, -4543 },
-  { 674, 10889, -902, -3605 },
-  { -582, 9504, 300, -3618 },
-  { 641, 7654, 689, -2109 },
-  { 2065, 9243, 508, -4367 },
-  { 1055, 8373, 688, -3144 },
-  { -641, 8185, 986, -3307 },
-  { 1120, 7426, 1785, -3757 },
-  { 1660, 8070, -593, -3104 },
-  { 2002, 9467, -1722, -3475 },
-  { 2361, 8368, 100, -3709 },
-  { -772, 7845, -613, -4988 },
-  { 1485, 7430, 1896, -6127 },
-  { -432, 7823, -947, -2882 },
-  { 313, 11122, -760, -4871 },
-  { 412, 8412, -283, -4231 },
-  { 1585, 10402, -1884, -3267 },
-  { 321, 6952, 773, -3016 },
-  { -105, 9014, 121, -2249 },
-  { 1585, 10313, -977, -4812 },
-  { 1619, 11869, 1306, -6876 },
-  { -1168, 8886, -81, -2500 },
-  { -395, 10886, 733, -6490 },
-  { -4949, 4274, 3992, -1054 },
-  { -4241, 5299, 4262, -1584 },
-  { -2710, 3862, 4552, -1673 },
-  { -4608, 2472, 3672, -1715 },
-  { -2843, 2816, 4003, -2326 },
-  { -5229, 2964, 5636, 90 },
-  { -4924, 3442, 5015, -1096 },
-  { -1281, 3313, 5537, -2066 },
-  { -3808, 1939, 4351, -919 },
-  { -1915, 2585, 4939, -1614 },
-  { -3470, 1843, 5562, -682 },
-  { -3800, 870, 5827, 144 },
-  { -4985, 1452, 4728, -709 },
-  { -3745, 2750, 7220, 259 },
-  { -1875, 1900, 6514, -826 },
-  { -4329, 1574, 7192, 1304 },
-  { -5408, 1444, 6208, 631 },
-  { -3327, 5312, 5707, -1541 },
-  { -6966, 3334, 4034, 1028 },
-  { -7484, 4245, 4218, -212 },
-  { -6567, 5839, 4539, -512 },
-  { -5715, 5935, 3747, -1186 },
-  { -6410, 4881, 3356, -1610 },
-  { -5146, 2590, 2850, 2172 },
-  { -5196, 4095, 2569, -373 },
-  { -5043, 6025, 4318, 692 },
-  { -5525, 4884, 3513, 370 },
-  { -6804, 7533, 5812, -488 },
-  { -5657, 2480, 4061, 1234 },
-  { -3155, 1472, 6071, 1188 },
-  { -3427, 5217, 3442, 858 },
-  { -4698, 3013, 5517, 2586 },
-  { -4449, 2226, 5418, 3580 },
-  { -6395, 3547, 5487, 2028 },
-  { -3500, 5019, 4787, 1 },
-  { -4038, 2578, 3073, 3151 },
-  { -2750, 1955, 4469, 3856 },
-  { -5696, 1659, 6118, 2469 },
-  { -4350, 1241, 6840, 3126 },
-  { -5565, 5058, 5196, 1314 },
-  { -1642, 4190, 3948, 607 },
-  { -1233, 4108, 4850, -640 },
-  { -997, 3428, 3239, 1378 },
-  { -6488, 2741, 6926, 2792 },
-  { -4188, 3763, 4235, 2018 },
-  { -3210, 3224, 5646, 1427 },
-  { -5526, 6909, 5070, -627 },
-  { -2815, 3994, 3425, 1903 },
-  { -2163, 2734, 5423, 145 },
-  { -4149, 4247, 2355, 734 },
-  { -410, 2521, 4138, -16 },
-  { -2411, 2385, 4927, 2105 },
-  { -6077, 3591, 3114, 594 },
-  { -4186, 4834, 5926, -1004 },
-  { -7315, 3369, 5966, 448 },
-  { -7042, 5721, 5771, 238 },
-  { -4466, 3907, 3535, -1751 },
-  { -2116, 3970, 6163, -1392 },
-  { -7239, 2143, 8407, 3630 },
-  { -5431, 4486, 6486, -42 },
-  { -1874, 1617, 6333, 519 },
-  { -6478, 2629, 4634, -505 },
-  { -7784, 2342, 7216, 1365 },
-  { -1154, 1432, 4831, 1544 },
-  { -4964, -5801, 1797, 506 },
-  { -4436, -6905, 1059, -1237 },
-  { -5400, -6886, 884, -290 },
-  { -6259, -7103, 523, -227 },
-  { -4819, -6450, 1412, -450 },
-  { -4056, -6213, 1725, -943 },
-  { -5642, -6091, 1357, 605 },
-  { -4196, -5678, 2187, -173 },
-  { -4726, -5126, 2470, 321 },
-  { -6642, -5091, 1507, -1005 },
-  { -5304, -5250, 1944, 1579 },
-  { -7179, -5520, 1468, -425 },
-  { -6033, -4895, 1876, -955 },
-  { -6595, -5143, 2207, 1291 },
-  { -4224, -4943, 1846, 1792 },
-  { -7128, -6950, 539, 724 },
-  { -4369, -4901, 2590, 1103 },
-  { -7413, -5696, 1712, 1440 },
-  { -5885, -6821, 418, 871 },
-  { -6828, -5599, 710, -1563 },
-  { -6123, -5817, 1358, 1631 },
-  { -5291, -5622, 578, 2138 },
-  { -7171, -6004, 347, 2208 },
-  { -6083, -5251, 2132, 425 },
-  { -4329, -5721, 407, -2993 },
-  { -5326, -5056, 1119, -1837 },
-  { -5485, -5856, 185, -2389 },
-  { -6529, -5178, 403, -697 },
-  { -6719, -4412, 2726, 871 },
-  { -5126, -5629, 1835, -771 },
-  { -5622, -4361, 2973, 858 },
-  { -5282, -5895, 45, -335 },
-  { -4357, -5656, 1696, -1558 },
-  { -7139, -6659, 627, -409 },
-  { -4415, -6328, 35, 1306 },
-  { -7639, -6110, 1134, 197 },
-  { -3626, -5592, 2019, 901 },
-  { -3547, -5064, 1176, 1738 },
-  { -5075, -3899, 2087, 266 },
-  { -4086, -6311, 1479, 360 },
-  { -6210, -5220, -199, -1477 },
-  { -3910, -5063, 1356, -15 },
-  { -7616, -4977, 461, 2401 },
-  { -6118, -6131, 1258, -563 },
-  { -6127, -4968, 1286, -27 },
-  { -4121, -5852, 1113, 1476 },
-  { -5157, -4881, 1162, -662 },
-  { -4637, -5031, 1179, 709 },
-  { -5509, -5452, -397, 1224 },
-  { -4597, -6861, 646, 467 },
-  { -6247, -4043, 468, 278 },
-  { -5336, -6465, 874, -1472 },
-  { -6998, -6346, 78, -1798 },
-  { -4915, -4530, 2756, -203 },
-  { -6048, -4373, 1468, 1052 },
-  { -4273, -7100, 942, -323 },
-  { -6552, -4287, 2351, 69 },
-  { -6954, -4613, 722, 1521 },
-  { -4201, -5361, 763, -1562 },
-  { -6881, -5596, -748, 669 },
-  { -6695, -3547, -34, 1299 },
-  { -3981, -5728, 84, 111 },
-  { -4663, -4809, 2173, -1031 },
-  { -6599, -6077, 1303, 256 },
-  { -7596, -4265, -5791, -4140 },
-  { -6610, -2758, -5288, -3936 },
-  { -5880, -3865, -6563, -3088 },
-  { -7228, -5510, -7677, -3912 },
-  { -8854, -6553, -8318, -5361 },
-  { -9362, -5249, -6413, -4319 },
-  { -4418, -3110, -6368, -4358 },
-  { -5544, -4203, -6863, -5013 },
-  { -3056, -4316, -5567, -3181 },
-  { -3078, -5999, -5051, -2657 },
-  { -5884, -6292, -5756, -4013 },
-  { -4825, -4549, -5535, -4053 },
-  { -4443, -6126, -5316, -1368 },
-  { -3972, -6341, -6098, -2686 },
-  { -5751, -2781, -5398, -6230 },
-  { -4466, -6135, -5570, -3679 },
-  { -4291, -5992, -3564, -5189 },
-  { -7189, -4429, -7279, -6082 },
-  { -5076, -4433, -2748, -5366 },
-  { -6225, -2825, -6833, -5663 },
-  { -2989, -4792, -3960, -4492 },
-  { -7836, -7773, -7722, -5741 },
-  { -6559, -5703, -5844, -5589 },
-  { -7612, -5438, -4136, -3774 },
-  { -4218, -4176, -6591, -2333 },
-  { -4837, -5063, -6581, 322 },
-  { -6590, -5990, -2980, -3847 },
-  { -5558, -2971, -5489, -1932 },
-  { -7001, -5323, -4975, -1697 },
-  { -4694, -2688, -6904, -3044 },
-  { -8511, -5379, -5767, -2549 },
-  { -7548, -5412, -6522, -2572 },
-  { -6597, -4973, -6423, -1274 },
-  { -6415, -4022, -5168, -1072 },
-  { -5528, -5530, -7218, -2345 },
-  { -4845, -4805, -5943, -1227 },
-  { -6049, -7150, -6744, -2161 },
-  { -9061, -7299, -8542, -4375 },
-  { -5010, -5546, -5416, -82 },
-  { -4135, -4205, -5109, -3373 },
-  { -3311, -5869, -4007, -5061 },
-  { -5993, -6472, -3962, -4718 },
-  { -2966, -5832, -2821, -6305 },
-  { -4851, -5152, -2067, -3930 },
-  { -3620, -4441, -3362, -5836 },
-  { -4469, -5221, -4534, -5592 },
-  { -4022, -6335, -4321, -6107 },
-  { -4899, -4503, -3084, -3725 },
-  { -4490, -8276, -4620, -6236 },
-  { -6591, -4342, -7365, -4063 },
-  { -6498, -5057, -5553, 485 },
-  { -6060, -2714, -7093, -4144 },
-  { -6199, -7774, -7094, -4057 },
-  { -7536, -6424, -6415, -4265 },
-  { -7439, -2454, -6348, -4827 },
-  { -5333, -7565, -4417, -4639 },
-  { -4353, -7103, -4197, -2689 },
-  { -5229, -6549, -5129, -6804 },
-  { -6129, -7701, -5236, -4836 },
-  { -6797, -3983, -3884, -4406 },
-  { -6624, -4467, -4745, -5052 },
-  { -3324, -7596, -2720, -6553 },
-  { -5473, -6284, -1704, -4511 },
-  { -4131, -7263, -3180, -5196 },
-  { -7116, -5565, -3469, 685 },
-  { -6002, -6021, -3858, 576 },
-  { -3144, -8203, -1291, -434 },
-  { -6096, -7027, -4004, 1353 },
-  { -3943, -7709, -2344, -36 },
-  { -4510, -6767, -2642, 631 },
-  { -3657, -11541, -2570, -3984 },
-  { -5959, -8854, -1333, -867 },
-  { -6699, -8866, -1606, -344 },
-  { -3836, -7961, -2334, -2028 },
-  { -3430, -8045, -3037, -672 },
-  { -3868, -9184, -3635, -1819 },
-  { -4258, -9060, -2621, -1008 },
-  { -3595, -8693, -2022, -752 },
-  { -4573, -8048, -3166, -2622 },
-  { -4852, -7903, -1405, 256 },
-  { -4591, -7057, -1560, 965 },
-  { -6963, -7655, -980, 808 },
-  { -5179, -6641, -3356, 1196 },
-  { -7102, -6941, -2798, 2123 },
-  { -6867, -5834, -3320, -770 },
-  { -5977, -7369, -2500, -778 },
-  { -6160, -6400, -934, -2543 },
-  { -6741, -7608, -355, -1289 },
-  { -6856, -6466, -1433, -1643 },
-  { -4786, -6292, -4970, 376 },
-  { -5407, -8866, -2255, -400 },
-  { -3814, -6506, -1387, -3620 },
-  { -4998, -6137, -1200, -4092 },
-  { -5123, -9557, -2849, -1306 },
-  { -4259, -6444, -4395, -338 },
-  { -5221, -6810, -883, 1225 },
-  { -6137, -6215, -2165, 554 },
-  { -3895, -6557, -3176, -1829 },
-  { -3886, -8188, -87, -954 },
-  { -7243, -6707, -2216, -316 },
-  { -5592, -7606, 85, -432 },
-  { -3957, -7945, -504, -144 },
-  { -4617, -7624, 218, -312 },
-  { -4797, -8737, -844, -1051 },
-  { -4478, -8516, -1401, -454 },
-  { -4557, -7058, -302, -2332 },
-  { -6623, -7736, -271, -50 },
-  { -3157, -7532, -1111, -2207 },
-  { -3590, -7300, -1271, 517 },
-  { -4442, -7306, -507, 590 },
-  { -6458, -7524, -2807, 666 },
-  { -4991, -8466, -3363, -785 },
-  { -7474, -7541, -1056, -1839 },
-  { -7501, -8316, -938, -180 },
-  { -5329, -7739, -579, -2341 },
-  { -4549, -7063, -176, -3539 },
-  { -5191, -8612, -1504, -4250 },
-  { -3083, -7058, -2251, 32 },
-  { -4003, -7043, -1093, -791 },
-  { -5523, -8093, -678, -114 },
-  { -3022, -10265, -2070, -3109 },
-  { -3905, -6274, -182, -3652 },
-  { -3269, -9217, -551, -2650 },
-  { -3138, -9314, -1726, -1704 },
-  { -4420, -10339, -1744, -3459 },
-  { -4163, -8609, -2298, -4113 },
-  { -5566, -6505, -1241, -463 },
-  { -3130, -9746, -2352, -4884 },
-  { -7825, -3439, 1451, -1468 },
-  { -8451, -3318, 2360, -435 },
-  { -8462, -4130, 1438, -1024 },
-  { -9425, -4564, 1328, -689 },
-  { -11014, -3202, 2278, 2080 },
-  { -8269, -2761, -146, -440 },
-  { -7497, -2618, -166, 413 },
-  { -8250, -3060, 522, -2133 },
-  { -8365, -5366, 1347, -451 },
-  { -8589, -3979, 2943, 714 },
-  { -8111, -2572, 1272, -1748 },
-  { -7830, -5193, 605, -1484 },
-  { -8119, -4736, 2141, 256 },
-  { -7724, -4769, 1463, -812 },
-  { -7363, -3911, 2540, 4 },
-  { -7974, -3397, 2363, 1366 },
-  { -7359, -4204, 1752, -958 },
-  { -7622, -3505, 660, 916 },
-  { -9934, -3665, 3165, 828 },
-  { -8721, -4162, 62, 1718 },
-  { -9433, -4768, 2722, 1234 },
-  { -7960, -4496, 138, 1528 },
-  { -8198, -3454, -443, 631 },
-  { -7756, -2246, 655, 1137 },
-  { -8841, -3145, 1113, 829 },
-  { -7817, -3298, 1251, 230 },
-  { -9413, -2733, 323, -1862 },
-  { -9408, -4168, 1270, 1549 },
-  { -9037, -3892, -942, 283 },
-  { -8255, -3849, 1301, 1762 },
-  { -9057, -3987, -41, -682 },
-  { -9441, -4187, 2019, -111 },
-  { -9740, -3178, 1602, -871 },
-  { -8344, -2474, 1461, 1506 },
-  { -9752, -2925, 1996, 1243 },
-  { -9199, -3796, 180, 537 },
-  { -9060, -2405, 1140, -1562 },
-  { -9348, -2376, 309, -162 },
-  { -10786, -3182, -5, -1500 },
-  { -8142, -4540, -434, -826 },
-  { -7528, -2341, 1104, -73 },
-  { -9360, -2658, 3062, 56 },
-  { -8267, -2335, 2000, -1193 },
-  { -12169, -3154, 1287, -640 },
-  { -11398, -2120, 946, -1163 },
-  { -8940, -4559, 328, -1696 },
-  { -11025, -4213, 2813, 840 },
-  { -9224, -3581, 2224, 2039 },
-  { -8943, -3337, 1248, -1298 },
-  { -7900, -4042, 485, -2080 },
-  { -9221, -1947, 2191, -880 },
-  { -10762, -1800, 2516, -324 },
-  { -10095, -2238, 981, -1335 },
-  { -11908, -2808, 3255, 645 },
-  { -10640, -4105, 1283, -595 },
-  { -7663, -2863, 2467, -797 },
-  { -10712, -3854, 3710, 1538 },
-  { -10823, -2893, 1408, -801 },
-  { -9874, -3832, 256, -1638 },
-  { -10394, -3391, 2315, -94 },
-  { -11525, -4079, 4153, 2122 },
-  { -9546, -2088, 1541, 481 },
-  { -8731, -2433, 1042, 2160 },
-  { -7852, -3977, -1370, 1677 },
-  { 7072, -3420, 1398, -1741 },
-  { 6180, -1976, 1280, -3557 },
-  { 7692, -1793, 2844, -1700 },
-  { 8363, -1773, 3104, -2679 },
-  { 9213, -3266, 3756, -3542 },
-  { 9650, -2644, 1426, -1318 },
-  { 7712, -2796, 3686, -1975 },
-  { 7316, -3517, 2821, -622 },
-  { 7434, -2594, 2305, -2264 },
-  { 7237, -1797, 255, -3114 },
-  { 8663, -1983, 1338, -3056 },
-  { 6616, -952, 4059, -2652 },
-  { 8823, -1327, 1362, -1356 },
-  { 9938, -1722, 1287, -2362 },
-  { 7207, -1057, 1913, -1315 },
-  { 7508, -1585, 870, -1982 },
-  { 8217, -3680, 1417, -3170 },
-  { 8329, -2541, 1684, -585 },
-  { 8062, -2335, 252, -2800 },
-  { 8204, -4108, 3097, -2569 },
-  { 7701, -3367, 576, -3008 },
-  { 7350, -786, 2414, -2129 },
-  { 6948, -2568, 1607, -225 },
-  { 7684, -2387, 1308, -3449 },
-  { 8306, -3458, 2394, -1454 },
-  { 8438, -2781, 1043, -1362 },
-  { 9175, -2076, 2144, -1987 },
-  { 8347, -2709, 3489, -4301 },
-  { 5696, -2377, 2870, 851 },
-  { 8825, -1243, 2219, -2603 },
-  { 8801, -1614, 584, -2513 },
-  { 8413, -384, 1421, -2244 },
-  { 9228, -3050, 3279, -2164 },
-  { 6342, -2698, 3547, -107 },
-  { 10053, -2476, 2837, -3168 },
-  { 7439, -604, 3177, -3991 },
-  { 7749, -1064, 4329, -4855 },
-  { 8655, -2177, 2252, -3519 },
-  { 8490, -228, 1958, -3233 },
-  { 10513, -2968, 1911, -2340 },
-  { 8146, -862, 1884, -1723 },
-  { 7788, -666, 3004, -2891 },
-  { 7785, -1620, 4133, -3417 },
-  { 10262, -3731, 3455, -2971 },
-  { 8570, -905, 4519, -4649 },
-  { 9129, -2562, 463, -2465 },
-  { 9451, -3587, 1904, -3056 },
-  { 6549, -2236, 3010, -4523 },
-  { 7175, -2684, 2967, -3458 },
-  { 9872, -3278, 1054, -2472 },
-  { 9153, -931, 1217, -2565 },
-  { 8789, -3469, 753, -2568 },
-  { 6683, -3791, 1797, -3968 },
-  { 6801, -1977, 2311, -452 },
-  { 6336, -1572, 2612, -3264 },
-  { 7996, -1008, 730, -2964 },
-  { 7521, -1059, 1573, -3694 },
-  { 8148, -3973, 2600, -3572 },
-  { 7765, -1532, 2528, -3856 },
-  { 7404, -3918, 4472, -143 },
-  { 8894, -1398, 3299, -3685 },
-  { 5768, -2041, 1487, -637 },
-  { 5131, -2865, 2463, -811 },
-  { 6439, -1568, 3500, -1550 },
-  { -8878, -6798, -5319, -1452 },
-  { -6332, -9713, -3112, -990 },
-  { -8444, -6316, -3694, -687 },
-  { -6123, -10840, -3637, -4358 },
-  { -4784, -9580, -4577, -2581 },
-  { -6108, -10515, -4859, -2524 },
-  { -7605, -7518, -2327, -2797 },
-  { -9662, -8775, -2467, -2010 },
-  { -6494, -7523, -4715, -118 },
-  { -8290, -8982, -1672, -317 },
-  { -8798, -11051, -3888, -1426 },
-  { -6273, -6623, -6791, -142 },
-  { -8313, -7668, -2141, -1275 },
-  { -6453, -8412, -3589, -4102 },
-  { -6747, -7750, -5690, -2498 },
-  { -7814, -6693, -3174, -2446 },
-  { -10383, -10130, -3931, -2364 },
-  { -10606, -8467, -5539, -2772 },
-  { -9475, -6671, -3305, -2271 },
-  { -8982, -9457, -5635, -4005 },
-  { -10111, -7965, -6515, -4180 },
-  { -7301, -6479, -5364, 720 },
-  { -9543, -8999, -7921, -912 },
-  { -9534, -8562, -3469, -384 },
-  { -7601, -10344, -3205, -1127 },
-  { -8088, -8620, -4954, -2888 },
-  { -8202, -8406, -7038, -3775 },
-  { -7312, -8324, -3334, -1775 },
-  { -8566, -9262, -8071, -4174 },
-  { -7068, -11300, -5573, -2907 },
-  { -8295, -8952, -4366, -1544 },
-  { -11104, -10210, -2285, -384 },
-  { -5213, -7520, -5008, -1339 },
-  { -5889, -7940, -5987, -1385 },
-  { -10816, -8201, -4153, -1485 },
-  { -10277, -8919, -6315, -1652 },
-  { -5888, -10320, -3821, -1733 },
-  { -10497, -7181, -6083, -3032 },
-  { -7721, -9724, -6591, -5336 },
-  { -5688, -7894, -3486, -2552 },
-  { -10014, -10500, -3247, -820 },
-  { -6301, -8765, -4506, -2923 },
-  { -8261, -7847, -6213, -1552 },
-  { -10212, -7481, -8113, -3954 },
-  { -6938, -10874, -6074, -4703 },
-  { -7183, -10968, -4446, -1773 },
-  { -7120, -9193, -1966, -2509 },
-  { -6234, -9263, -2313, -4284 },
-  { -8503, -9857, -2429, -608 },
-  { -9372, -7844, -8391, -2120 },
-  { -7951, -7157, -6535, -11 },
-  { -7256, -9473, -2172, -660 },
-  { -10063, -9612, -2515, -15 },
-  { -6684, -9134, -6109, -4206 },
-  { -8204, -11932, -5220, -2306 },
-  { -9710, -6706, -4115, -3275 },
-  { -6855, -7078, -2409, -4447 },
-  { -7344, -7673, -4479, -4116 },
-  { -8851, -6842, -4927, -2948 },
-  { -8927, -10452, -5633, -2194 },
-  { -8627, -9002, -7176, -1575 },
-  { -8209, -9722, -7021, -3324 },
-  { -3770, -10249, -3623, -4816 },
-  { -8183, -7465, -4090, 646 },
-  { -8163, -7149, 200, 498 },
-  { -8289, -6266, 686, -206 },
-  { -10030, -6241, -1032, -1864 },
-  { -8793, -8327, -773, -169 },
-  { -9149, -6215, 969, -15 },
-  { -8303, -5859, -7, 2006 },
-  { -9682, -7283, 255, 1322 },
-  { -9293, -7227, 71, -231 },
-  { -8525, -6215, 287, -837 },
-  { -10477, -5379, 1159, 1449 },
-  { -10726, -7856, -130, 102 },
-  { -8694, -7461, -1210, 690 },
-  { -9367, -5324, 1103, 3170 },
-  { -10686, -8055, -831, 1633 },
-  { -9201, -6873, -2704, 2258 },
-  { -8421, -5358, -1405, 226 },
-  { -9066, -5830, -307, -1571 },
-  { -11150, -7381, -2746, -900 },
-  { -9978, -5925, -2006, -437 },
-  { -9464, -4741, -273, 1061 },
-  { -10543, -6684, -1113, 1660 },
-  { -10073, -5576, 1083, -269 },
-  { -8826, -5763, 1600, 1486 },
-  { -10445, -9071, -1253, -64 },
-  { -12085, -5799, 2, 769 },
-  { -12939, -6663, 1650, 1437 },
-  { -10932, -6434, -1252, -649 },
-  { -11650, -7826, -2053, 710 },
-  { -12122, -6733, -1889, -731 },
-  { -9093, -6095, -2463, -842 },
-  { -10977, -4364, 469, 420 },
-  { -11488, -6908, -521, 893 },
-  { -9669, -5478, -842, 337 },
-  { -10606, -5203, -632, -1361 },
-  { -10198, -6284, 1662, 1277 },
-  { -10135, -5292, 2435, 3493 },
-  { -11027, -6561, 655, 56 },
-  { -10977, -5030, 1127, -358 },
-  { -12766, -3986, 1348, -335 },
-  { -14244, -7731, 264, 317 },
-  { -15124, -10309, -508, 1447 },
-  { -12821, -8638, -608, 137 },
-  { -13076, -8693, -2852, -431 },
-  { -11156, -5546, -2252, -1600 },
-  { -8692, -7366, -819, -1223 },
-  { -12507, -9816, -1714, -121 },
-  { -10712, -6666, 544, 3349 },
-  { -12462, -5890, -2491, -2318 },
-  { -12468, -7226, 437, 232 },
-  { -11300, -5226, 2068, 687 },
-  { -11994, -8320, -626, 2728 },
-  { -12222, -5476, 1142, 18 },
-  { -10277, -8122, -2418, 2003 },
-  { -13418, -6115, -3563, -2802 },
-  { -14759, -9834, -1243, 21 },
-  { -13699, -5665, 1525, 507 },
-  { -16269, -9476, -701, 163 },
-  { -12677, -5437, -247, -1019 },
-  { -11827, -4295, -181, -1243 },
-  { -12847, -4496, 2984, 1123 },
-  { -13860, -7915, -1166, -547 },
-  { -12276, -8145, -2290, -1527 },
-  { -11417, -4830, 2983, 1854 },
-  { -11793, -6002, 1163, 1940 },
-  { 11443, -4920, -3235, 3151 },
-  { 11300, -6616, -1506, 1175 },
-  { 9198, -4628, -2060, 2390 },
-  { 10532, -4027, -643, 912 },
-  { 9902, -3573, -1606, 1327 },
-  { 9653, -3536, -2240, 1869 },
-  { 9948, -5171, -423, 2662 },
-  { 12316, -4004, -1989, 281 },
-  { 12125, -4800, -1265, -163 },
-  { 10650, -2617, -2337, 1462 },
-  { 9909, -4968, -2376, 916 },
-  { 12944, -4647, -1958, 460 },
-  { 12988, -5283, -1141, 41 },
-  { 12321, -2915, -3621, 1025 },
-  { 11449, -2894, -2728, 351 },
-  { 12087, -3041, -2002, -32 },
-  { 11558, -4031, -1343, -399 },
-  { 12983, -3740, -3516, 1245 },
-  { 12099, -2515, -2752, 225 },
-  { 12515, -3465, -2701, 550 },
-  { 14683, -5022, -5272, 2996 },
-  { 12260, -3383, -1215, -528 },
-  { 13810, -5422, -2443, 1166 },
-  { 13421, -5378, -1886, 721 },
-  { 12961, -4259, -2594, 796 },
-  { 12266, -2104, -4768, 1591 },
-  { 13523, -4710, -3045, 1342 },
-  { 12437, -2099, -5610, 2117 },
-  { 11850, -2183, -3497, 661 },
-  { 12275, -3936, -597, -697 },
-  { 12459, -5253, -517, -544 },
-  { 12835, -4094, -1322, -168 },
-  { 14360, -5677, -3305, 1859 },
-  { 13905, -4552, -4309, 2117 },
-  { 11559, -3412, -1847, -81 },
-  { 13379, -3167, -5764, 2746 },
-  { 11910, -1634, -4342, 1052 },
-  { 12662, -4742, 71, -974 },
-  { 13057, -3254, -4424, 1705 },
-  { 15046, -5706, -4851, 3019 },
-  { 14162, -4142, -5514, 2843 },
-  { 12764, -1845, -6684, 2888 },
-  { 13714, -2374, -7838, 3857 },
-  { 13295, -1663, -8293, 4073 },
-  { 10032, -4152, -3403, 1421 },
-  { 10942, -5386, -2222, 950 },
-  { 10532, -6385, -1750, 1925 },
-  { 10273, -5972, -1534, 643 },
-  { 10605, -4782, -1695, 27 },
-  { 10988, -5153, -1123, -341 },
-  { 11629, -5884, -1060, 48 },
-  { 10441, -4045, -2431, 311 },
-  { 10788, -3595, -4171, 1807 },
-  { 12110, -5686, -2127, 976 },
-  { 11746, -4773, -2639, 891 },
-  { 11541, -5299, -3031, 1732 },
-  { 11416, -2559, -5359, 2198 },
-  { 11583, -5376, -704, 677 },
-  { 10416, -3214, -3516, 872 },
-  { 9651, -5435, -1618, 3255 },
-  { 9973, -5133, -996, 3923 },
-  { 11707, -4643, -430, -796 },
-  { 10994, -2709, -3587, 2302 },
-  { 10716, -5118, -645, 270 },
-  { 14100, -10314, 1095, 1531 },
-  { 12944, -8049, 1105, -741 },
-  { 13276, -7035, -511, 274 },
-  { 14008, -7254, -283, 139 },
-  { 11594, -6536, -91, 1671 },
-  { 11732, -8645, 746, 15 },
-  { 14613, -7085, -1578, 1183 },
-  { 13083, -6224, -750, -4 },
-  { 13988, -6256, -1592, 820 },
-  { 14678, -8683, 441, 126 },
-  { 15571, -8872, -521, 1139 },
-  { 15642, -9533, 341, 697 },
-  { 15960, -9586, -168, 1121 },
-  { 15464, -10239, 1433, -1 },
-  { 14934, -7887, -1046, 1080 },
-  { 15252, -7630, -1899, 1628 },
-  { 15485, -8384, -1234, 1484 },
-  { 15962, -8638, -1815, 1931 },
-  { 16501, -10664, 398, 1167 },
-  { 16146, -10145, 411, 918 },
-  { 14573, -7475, -697, 601 },
-  { 14302, -7996, 28, 257 },
-  { 14769, -6792, -2286, 1574 },
-  { 14144, -6137, -2169, 1257 },
-  { 14770, -6271, -3111, 1933 },
-  { 14110, -8312, 1083, -531 },
-  { 15235, -6991, -2993, 2174 },
-  { 13222, -5805, 547, -891 },
-  { 14796, -8762, 1254, -246 },
-  { 16040, -9181, -1005, 1551 },
-  { 16487, -10086, -373, 1420 },
-  { 15077, -9479, 966, 51 },
-  { 13026, -6468, 932, -1080 },
-  { 12703, -6152, -33, -573 },
-  { 15641, -6810, -4128, 2874 },
-  { 13282, -7673, 1583, -1283 },
-  { 12373, -7150, 1512, -917 },
-  { 12992, -7751, -678, 783 },
-  { 10907, -6858, -313, 2597 },
-  { 13026, -8963, 125, 2152 },
-  { 12770, -9946, 1957, -505 },
-  { 12482, -6849, -1268, 833 },
-  { 13790, -6181, -138, -279 },
-  { 12709, -8382, 2044, 227 },
-  { 12244, -6630, 203, -457 },
-  { 14209, -6816, -1032, 632 },
-  { 15134, -8267, -288, 640 },
-  { 13619, -6157, -1090, 356 },
-  { 14044, -7413, 725, -484 },
-  { 12958, -7753, 2585, -1980 },
-  { 13188, -8396, 2306, -1558 },
-  { 14379, -9980, 2132, -688 },
-  { 14275, -9857, 1162, 179 },
-  { 13690, -8648, 1621, -889 },
-  { 11770, -6829, -746, 278 },
-  { 12732, -8202, 286, 90 },
-  { 13630, -10146, 1867, -207 },
-  { 12072, -8740, 1299, -645 },
-  { 12852, -9492, 1226, 62 },
-  { 11792, -7382, -54, -116 },
-  { 13779, -9014, 487, 351 },
-  { 11951, -7729, 121, 834 },
-  { 11970, -9781, 2276, -4 },
-  { 12680, -7984, 2787, -787 },
-  { 13300, -14488, 6408, -1927 },
-  { 13635, -15355, 9153, -3073 },
-  { 12804, -13566, 5517, -1625 },
-  { 16624, -10854, 1690, 28 },
-  { 20387, -18532, 6162, -261 },
-  { 16515, -12642, 3392, -519 },
-  { 15800, -11095, 2151, -202 },
-  { 16824, -11790, 1651, 599 },
-  { 17604, -13213, 2563, 538 },
-  { 17892, -14177, 3562, 147 },
-  { 16987, -11399, 869, 1052 },
-  { 17003, -12456, 2442, 265 },
-  { 21657, -21806, 9198, -1250 },
-  { 16825, -13341, 3980, -686 },
-  { 17525, -12714, 1887, 805 },
-  { 16419, -11034, 1216, 617 },
-  { 20931, -19939, 7469, -684 },
-  { 18452, -15390, 4573, -191 },
-  { 14778, -10077, 2841, -1209 },
-  { 17402, -13319, 3042, 160 },
-  { 19365, -17922, 7087, -1061 },
-  { 16298, -11941, 2810, -351 },
-  { 19087, -16176, 4775, -84 },
-  { 17666, -12289, 938, 1224 },
-  { 18581, -15894, 5132, -430 },
-  { 19823, -16717, 4142, 545 },
-  { 19960, -19423, 8400, -1492 },
-  { 18973, -16817, 5906, -594 },
-  { 19079, -15431, 3528, 503 },
-  { 16667, -12485, 4467, -1302 },
-  { 19791, -17797, 6196, -529 },
-  { 20005, -17606, 5354, -20 },
-  { 20123, -18599, 6886, -728 },
-  { 19068, -14805, 2394, 1105 },
-  { 14443, -13723, 5631, -2029 },
-  { 14730, -14231, 5631, -1450 },
-  { 16089, -15959, 7271, -2029 },
-  { 13473, -11200, 3236, -924 },
-  { 14413, -10902, 2347, -267 },
-  { 17666, -18662, 11381, -3496 },
-  { 14749, -11042, 3305, -275 },
-  { 15304, -10486, 1869, -240 },
-  { 14809, -12126, 3369, -616 },
-  { 16896, -16561, 7307, -1845 },
-  { 15782, -14336, 5380, -1264 },
-  { 16395, -15520, 6415, -1588 },
-  { 13681, -11114, 2584, -320 },
-  { 14244, -12326, 4480, -1632 },
-  { 15247, -13119, 4265, -898 },
-  { 13987, -12091, 3469, -597 },
-  { 13941, -12770, 4240, -839 },
-  { 13771, -13627, 5252, -1384 },
-  { 15010, -16074, 7592, -2249 },
-  { 15852, -17226, 8619, -2655 },
-  { 18921, -16916, 6875, -1501 },
-  { 14909, -11678, 2768, -295 },
-  { 18988, -18353, 8424, -2070 },
-  { 15457, -15080, 6218, -1513 },
-  { 14916, -15512, 6949, -1883 },
-  { 18108, -14702, 4681, -701 },
-  { 17600, -15733, 5616, -775 },
-  { 14070, -13683, 6472, -2626 },
-  { 13832, -11914, 5201, -2232 },
-  { 18846, -19009, 9192, -1961 },
-  { -11981, -10994, -6324, -2264 },
-  { -10976, -9047, -6546, -3828 },
-  { -11288, -10532, -7014, -4191 },
-  { -10139, -10189, -7799, -2688 },
-  { -10555, -9988, -9181, -2040 },
-  { -11596, -11339, -10022, -2707 },
-  { -13400, -13395, -11306, -4206 },
-  { -9774, -12281, -7466, -4133 },
-  { -10842, -13125, -8777, -4956 },
-  { -11964, -15082, -9779, -5095 },
-  { -9382, -10188, -9053, -4927 },
-  { -11562, -11296, -3651, -985 },
-  { -9287, -10083, -7918, -4069 },
-  { -12821, -16556, -11410, -6195 },
-  { -12628, -8959, -4521, -1113 },
-  { -13845, -11581, -3649, -681 },
-  { -12685, -10269, -5483, -1275 },
-  { -14988, -12874, -5107, -1189 },
-  { -13761, -11367, -6202, -1804 },
-  { -13225, -11249, -7820, -3354 },
-  { -14809, -11992, -3202, -312 },
-  { -15620, -15519, -10210, -3433 },
-  { -12954, -10200, -3139, -611 },
-  { -11536, -9981, -5284, -923 },
-  { -13034, -12417, -4612, -1098 },
-  { -16911, -15505, -6123, -1352 },
-  { -17396, -17685, -8330, -2171 },
-  { -14120, -10764, -2265, -99 },
-  { -12598, -7367, -5406, -3530 },
-  { -14143, -12793, -10909, -5226 },
-  { -14692, -16871, -11626, -5554 },
-  { -12581, -11197, -9194, -3837 },
-  { -16752, -16726, -9746, -2808 },
-  { -10600, -10358, -6560, -1227 },
-  { -14573, -13312, -8957, -3393 },
-  { -10172, -8463, -8579, -3387 },
-  { -11418, -12421, -5522, -1842 },
-  { -11855, -14204, -6669, -2625 },
-  { -13308, -8191, -3941, -2194 },
-  { -10007, -12266, -5022, -1811 },
-  { -13532, -15771, -9497, -3175 },
-  { -11760, -11148, -10339, -5529 },
-  { -12149, -12763, -11198, -3697 },
-  { -12029, -12119, -8555, -1792 },
-  { -16995, -19957, -11447, -3471 },
-  { -13144, -14504, -9988, -3191 },
-  { -9938, -11064, -6139, -3162 },
-  { -8873, -11550, -8294, -6550 },
-  { -9303, -13010, -6150, -2711 },
-  { -15463, -10469, -1766, -170 },
-  { -15985, -11693, -3007, -650 },
-  { -17142, -10671, -1434, 47 },
-  { -16063, -13858, -4817, -1058 },
-  { -19446, -19599, -9594, -2464 },
-  { -20076, -18744, -8313, -1889 },
-  { -15047, -16085, -7590, -2250 },
-  { -13481, -16195, -8552, -2998 },
-  { -13829, -14869, -6704, -1932 },
-  { -16357, -18484, -9802, -2959 },
-  { -10551, -8393, -9303, -5070 },
-  { -11345, -9156, -5641, -3107 },
-  { -13217, -13449, -9270, -4541 },
-  { -11988, -13732, -9995, -6374 },
-  { -11007, -9519, -5168, -4107 },
-  { 9930, -7858, 8061, -4375 },
-  { 8274, -7867, 5992, -2096 },
-  { 9692, -9675, 7621, -3670 },
-  { 9589, -8110, 6509, -3010 },
-  { 12617, -11976, 10122, -5360 },
-  { 11867, -8895, 7948, -5323 },
-  { 10388, -10482, 9234, -4324 },
-  { 8188, -8220, 7810, -2737 },
-  { 10407, -8787, 4806, -1930 },
-  { 10348, -8845, 9233, -6614 },
-  { 9422, -7091, 4820, -2878 },
-  { 9758, -9796, 5584, -2256 },
-  { 10188, -7994, 5347, -3343 },
-  { 11133, -7455, 4015, -2306 },
-  { 10676, -10744, 6093, -2629 },
-  { 11522, -12184, 7848, -3375 },
-  { 8805, -9883, 5317, -3071 },
-  { 9498, -9654, 6555, -3592 },
-  { 10488, -8008, 4066, -1252 },
-  { 11261, -8930, 6068, -2738 },
-  { 12180, -10397, 5027, -1531 },
-  { 9138, -8531, 3601, -1959 },
-  { 8107, -8380, 4970, -2061 },
-  { 9737, -13248, 6438, -2617 },
-  { 11178, -10423, 2622, -522 },
-  { 9572, -12372, 5199, -2019 },
-  { 12057, -12144, 4147, -1099 },
-  { 9047, -9925, 2516, -665 },
-  { 10790, -8030, 5882, -4386 },
-  { 7199, -8426, 6337, -2841 },
-  { 7778, -8285, 3529, -3442 },
-  { 7559, -10569, 3484, -1332 },
-  { 9404, -8115, 7484, -5541 },
-  { 7792, -11976, 5546, -2573 },
-  { 9313, -10264, 7661, -5195 },
-  { 6701, -10725, 4370, -1784 },
-  { 4918, -11361, 4507, -4527 },
-  { 5147, -12305, 3978, -5556 },
-  { 6525, -9899, 4481, -3129 },
-  { 7538, -12855, 6060, -4826 },
-  { 8659, -12111, 7159, -4430 },
-  { 8440, -11304, 4547, -1747 },
-  { 9216, -10918, 3507, -1195 },
-  { 6165, -9254, 4771, -4677 },
-  { 9163, -11019, 5637, -4935 },
-  { 13441, -11509, 6676, -2434 },
-  { 7912, -9398, 6663, -4048 },
-  { 11723, -13745, 8131, -4148 },
-  { 6065, -10257, 5005, -6327 },
-  { 11618, -12417, 5336, -1894 },
-  { 8891, -13924, 8407, -6131 },
-  { 9622, -12563, 7908, -5109 },
-  { 11479, -10315, 8349, -3991 },
-  { 11676, -14103, 6611, -2330 },
-  { 11951, -8953, 3829, -1550 },
-  { 10486, -8044, 10493, -5920 },
-  { 11801, -10769, 9763, -5305 },
-  { 6109, -8676, 5827, -1346 },
-  { 7030, -9611, 5624, -5761 },
-  { 12808, -12886, 8683, -4148 },
-  { 13213, -10464, 6381, -3189 },
-  { 11796, -13681, 10703, -6075 },
-  { 9639, -7949, 9625, -3944 },
-  { 8538, -6997, 5309, 453 }
+  {   9928,  -2618,  -1093,  -1263 },
+  {  11077,  -2876,  -1747,   -308 },
+  {  10503,  -1082,  -1426,  -1167 },
+  {   9337,  -2403,  -1495,    274 },
+  {  10698,  -2529,   -532,  -1122 },
+  {  10368,  -3974,  -1264,   -750 },
+  {  10070,  -3667,    346,    863 },
+  {  10278,  -3093,    311,   -576 },
+  {   9894,  -1330,  -1428,   -860 },
+  {  10544,  -1923,  -1058,   -971 },
+  {  10996,  -1632,   -841,  -1404 },
+  {  11832,  -3465,   1658,  -1990 },
+  {  10852,   -688,  -2658,   -499 },
+  {  10546,  -1749,   -147,  -1733 },
+  {  10801,  -1004,   -708,  -1453 },
+  {  10588,   -441,  -2113,   -952 },
+  {  10141,  -3331,   -582,  -1432 },
+  {   9608,  -2590,    383,    258 },
+  {  11422,  -3265,    229,  -1544 },
+  {  10460,  -1338,   -713,  -1568 },
+  {  10306,  -1721,  -1660,   -603 },
+  {   9580,  -1812,  -1235,  -1061 },
+  {  11471,  -2285,  -1617,   -607 },
+  {  10081,  -2225,  -1408,   -868 },
+  {  10715,  -2624,  -1367,   -704 },
+  {  10616,  -1871,  -2770,    -35 },
+  {   9352,  -2340,  -1024,  -1566 },
+  {  11065,  -1458,  -1926,   -735 },
+  {  11334,  -2056,  -1041,  -1144 },
+  {   9825,  -2048,   -794,  -1536 },
+  {  11850,  -2695,  -1123,   -867 },
+  {  10654,  -2226,  -1891,   -373 },
+  {  10024,  -1557,   -808,  -1069 },
+  {  11142,  -1266,  -3238,    128 },
+  {  11729,  -3282,   -514,  -1011 },
+  {  11402,  -2094,  -2335,   -189 },
+  {  10195,  -3658,    181,  -1875 },
+  {  11431,  -2626,   -404,  -1377 },
+  {  11001,  -3868,   -619,  -1077 },
+  {  10894,  -2559,    274,  -1758 },
+  {   9633,  -1482,  -2253,   -773 },
+  {  11245,  -3321,    830,  -1972 },
+  {   9768,  -2701,   -199,  -1859 },
+  {  10500,  -2042,    525,  -2043 },
+  {  11669,  -4069,    293,  -1468 },
+  {   9192,  -1991,   -583,    -61 },
+  {  10057,  -3220,  -2015,   -473 },
+  {   9497,  -2315,  -2490,   -467 },
+  {  10455,  -3069,  -1194,  -1007 },
+  {   9994,  -1936,    -60,  -1225 },
+  {   9295,  -2156,  -1761,  -1134 },
+  {  10085,  -3748,  -1026,    197 },
+  {   9334,  -2360,    804,   -351 },
+  {  11561,  -2553,   1352,  -2313 },
+  {  12837,  -3998,   1195,  -1958 },
+  {  10114,  -1100,  -2414,   -394 },
+  {   9341,  -2530,    315,    755 },
+  {  10131,  -3164,   1411,   -674 },
+  {   9535,   -905,  -1551,    579 },
+  {  11717,  -1519,  -3051,     91 },
+  {   9824,  -2911,  -2775,    192 },
+  {   9662,  -2934,   -561,   1450 },
+  {  11085,  -3392,  -1298,   -659 },
+  {   8955,  -2102,  -1899,    703 },
+  {   8607,  -1742,  -4348,    814 },
+  {   7640,  -2063,  -3617,     52 },
+  {   7074,   -826,  -4325,   4375 },
+  {   7714,    584,  -4238,   1927 },
+  {   6355,   -952,  -4912,   3127 },
+  {   7069,   -660,  -6413,   4087 },
+  {   8313,   -132,  -2964,   -876 },
+  {   6952,  -1422,  -3962,    -24 },
+  {   9299,   -734,  -3088,   -263 },
+  {   9484,   -574,  -4513,    466 },
+  {   7246,    -91,  -3735,   -704 },
+  {   8325,  -1417,  -3090,   -530 },
+  {   6469,  -1226,  -4757,    829 },
+  {   6652,   -368,  -5682,   1393 },
+  {   7971,  -1278,  -2284,   1205 },
+  {   7229,   -699,  -3556,   1840 },
+  {   7994,   1284,  -2729,    732 },
+  {   9005,   -698,  -4522,   2189 },
+  {   6963,    197,  -2727,    380 },
+  {   8527,    135,  -3991,   -213 },
+  {   8840,    934,  -3014,   -567 },
+  {  10125,    418,  -3284,   -371 },
+  {   6367,    361,  -2318,   2554 },
+  {   7892,    172,  -5247,   4673 },
+  {   6674,    387,  -5424,   4398 },
+  {   6240,    684,  -4047,   1219 },
+  {  11170,   -794,  -5081,   1195 },
+  {  11765,   -648,  -6265,   2052 },
+  {  10845,   -775,  -3837,    366 },
+  {  12496,   -689,  -8260,   3562 },
+  {   7893,  -1166,  -4972,    988 },
+  {   8592,   1052,  -5986,   3087 },
+  {   7277,   1874,  -5685,   3579 },
+  {   6900,   2016,  -4809,   3491 },
+  {   8530,  -2405,  -3250,   1986 },
+  {   9426,    494,  -7067,   5038 },
+  {  10285,    564,  -8210,   5370 },
+  {   8749,  -2207,  -3980,   2852 },
+  {   9653,  -2686,  -4300,   1400 },
+  {   9770,  -2286,  -5663,   4233 },
+  {   8490,     -4,  -7048,   4496 },
+  {   7697,  -1209,  -5328,   3183 },
+  {   6451,    801,  -4324,   -554 },
+  {   7387,   1806,  -5265,    545 },
+  {   7450,  -2302,  -4445,   1418 },
+  {   8817,  -1370,  -5827,   2168 },
+  {  10324,  -2406,  -5629,   2579 },
+  {   8863,  -2578,  -3537,    467 },
+  {   6901,  -1624,  -3169,   3392 },
+  {   7846,    156,  -6948,   3381 },
+  {   7928,  -1115,  -5972,   4816 },
+  {   6089,   -599,  -4368,   -320 },
+  {   7833,   1246,  -3960,   -621 },
+  {   8931,   2521,  -6768,   2052 },
+  {   8900,   1944,  -4126,     40 },
+  {   7661,    -34,  -2855,   2480 },
+  {   5873,    474,  -3262,   3712 },
+  {   7535,   -234,  -4699,    216 },
+  {   5856,    143,  -5142,     73 },
+  {   8944,   -106,  -5874,   3663 },
+  {   7134,    426,  -5879,   2895 },
+  {  10199,   1011,  -4762,    369 },
+  {   8454,    264,  -5971,   1291 },
+  {   7822,  -2449,  -4333,   4540 },
+  {   6200,  -2758,  -2632,   1497 },
+  {   6070,  -4315,  -2699,    414 },
+  {   7047,  -3739,  -3210,   1060 },
+  {   5675,  -3801,  -2717,   -407 },
+  {   4789,  -4063,  -2628,   -744 },
+  {   4023,  -3366,  -3133,   -726 },
+  {   4296,  -2407,  -3381,   -513 },
+  {   4388,  -2931,  -2820,   1512 },
+  {   4559,  -4233,  -1941,   1976 },
+  {   6702,  -3208,  -1755,   1680 },
+  {   4416,  -3521,  -1052,   2984 },
+  {   7154,  -4266,  -1203,   3732 },
+  {   3625,  -4242,  -3244,   1395 },
+  {   6518,  -2856,  -1304,   2887 },
+  {   6170,  -1949,  -3014,   3973 },
+  {   5189,  -2451,  -4020,   3477 },
+  {   6218,  -2988,  -1921,   3844 },
+  {   4827,  -3688,  -1928,   3343 },
+  {   6668,  -3991,  -2805,   3095 },
+  {   5297,  -3115,  -3684,   2390 },
+  {   5354,  -4614,  -2662,   1504 },
+  {   4196,  -3091,  -4147,   1135 },
+  {   3540,  -2893,  -4007,    100 },
+  {   5569,  -1602,  -4007,   1909 },
+  {   4341,  -2091,  -4272,    252 },
+  {   5559,  -2878,  -3832,    498 },
+  {   4548,  -4479,  -2898,    -27 },
+  {   5176,  -2494,  -4635,   1476 },
+  {   3294,  -3485,  -3738,    716 },
+  {   4920,  -1229,  -4195,   -365 },
+  {   3257,  -3518,  -3349,   2862 },
+  {   5286,  -1948,  -3485,   -778 },
+  {   6502,  -3051,   -152,   2854 },
+  {   5864,  -4192,  -1076,   3451 },
+  {   4656,  -3122,  -3448,    179 },
+  {   5907,   -754,  -1596,   3116 },
+  {   7229,  -3680,  -1590,   2892 },
+  {   5107,  -3888,  -3364,    806 },
+  {   6764,  -2635,  -3450,    134 },
+  {   5258,  -2827,  -2844,  -1052 },
+  {   5798,  -1725,  -4305,    205 },
+  {   5404,  -1213,  -3362,    449 },
+  {   6224,  -2738,  -3046,   -581 },
+  {   4223,  -2438,  -2725,   3745 },
+  {   4751,  -3411,  -2123,    116 },
+  {   3868,  -3000,  -3954,   2297 },
+  {   6819,  -2899,  -4277,   2825 },
+  {   4207,  -4754,  -2808,    865 },
+  {   4804,  -1494,  -1997,   4688 },
+  {   5282,  -2213,   -548,   3559 },
+  {   5580,  -1912,   -566,   4370 },
+  {   6168,  -2857,   -672,   4053 },
+  {   6583,  -4515,  -2850,   1670 },
+  {   6511,  -3093,  -3988,   1421 },
+  {   4646,  -1790,  -1443,   3650 },
+  {   5915,   -924,  -2020,    896 },
+  {   7814,  -4181,  -3152,   2007 },
+  {   6190,  -2238,  -4817,   2279 },
+  {   4737,  -4034,  -3288,   1835 },
+  {   8161,  -3633,  -3423,   3137 },
+  {   7415,  -2351,  -2088,   4290 },
+  {   4106,  -2517,    -62,   2905 },
+  {   4909,  -3145,   -614,   4112 },
+  {   4938,  -3281,   -397,   1100 },
+  {   -173,    919,   1589,  -5363 },
+  {    -13,    796,   -295,  -6655 },
+  {  -1860,   -829,   1141,  -4555 },
+  {   2298,   -838,   -664,  -5005 },
+  {   -884,  -1097,   2074,  -4613 },
+  {   -101,    281,   2846,  -4535 },
+  {   1166,    453,   2429,  -5910 },
+  {    879,   -664,   2370,  -5452 },
+  {   1415,   -370,  -1699,  -4727 },
+  {  -1413,   1277,   -669,  -6649 },
+  {   2133,    304,   -968,  -4624 },
+  {    380,    586,  -2087,  -4892 },
+  {   1336,    275,    -82,  -5789 },
+  {  -2459,   1057,    -34,  -5416 },
+  {   2278,  -1758,    866,  -5653 },
+  {   1945,  -2295,   -149,  -5302 },
+  {   1287,  -3525,    996,  -5255 },
+  {   2297,    803,   1177,  -6067 },
+  {    187,   -180,   -619,  -6202 },
+  {   -793,  -2537,   1554,  -5057 },
+  {  -2703,   -204,   -629,  -5853 },
+  {  -1007,   -146,    313,  -5582 },
+  {    830,    357,    869,  -6363 },
+  {   -228,   -575,  -3177,  -4433 },
+  {  -1001,  -1553,   -142,  -5708 },
+  {  -1644,   1683,   1721,  -4533 },
+  {    893,   1924,    -15,  -5791 },
+  {   2195,   2061,   -262,  -5471 },
+  {   3031,    270,    311,  -5096 },
+  {   1912,   1638,  -1523,  -4677 },
+  {  -3142,    -55,    253,  -4914 },
+  {    356,  -1680,    343,  -6123 },
+  {  -2241,  -1734,   -976,  -5939 },
+  {  -2196,  -2893,    547,  -4938 },
+  {  -1245,    126,  -1916,  -5419 },
+  {   -249,  -3755,  -1422,  -5594 },
+  {    575,  -2683,  -1926,  -4566 },
+  {   -762,   1885,    192,  -5880 },
+  {   -811,  -2562,  -1068,  -6013 },
+  {  -2264,  -3086,   -976,  -4775 },
+  {     70,  -1215,   2880,  -4410 },
+  {    714,  -3760,   2916,  -4691 },
+  {   -244,  -3404,   1740,  -4493 },
+  {    684,  -5137,   -328,  -5608 },
+  {   -529,  -3825,  -1786,  -4535 },
+  {   -713,  -4743,  -1118,  -5546 },
+  {   2718,  -3788,   1798,  -5708 },
+  {  -1639,  -3679,  -1564,  -6095 },
+  {   1693,  -2642,  -1389,  -4539 },
+  {    505,  -1573,  -1651,  -4878 },
+  {   -835,  -2256,  -1941,  -5352 },
+  {   1464,   -411,   1993,  -6441 },
+  {    493,  -3184,   -145,  -6148 },
+  {  -1413,    499,  -1617,  -6479 },
+  {   -294,   1722,  -1419,  -5725 },
+  {  -2937,  -1528,   -175,  -4624 },
+  {   -594,  -5911,    -56,  -6146 },
+  {   -300,  -4275,   1156,  -5947 },
+  {    552,  -2643,   2669,  -3959 },
+  {    905,  -4158,   1789,  -5809 },
+  {   1336,  -2009,   2108,  -5903 },
+  {   1555,  -3600,   1110,  -6759 },
+  {  -1294,  -3464,     77,  -6084 },
+  {  -1139,  -4006,  -1270,  -4181 },
+  {  -5094,  -3296,   1092,  -2847 },
+  {  -5503,  -2883,   1984,  -2067 },
+  {  -4671,  -4218,  -1417,  -4132 },
+  {  -3763,  -3818,   1262,  -3082 },
+  {  -5132,  -3430,   2928,   -728 },
+  {  -5957,  -2877,   1251,  -2446 },
+  {  -4425,  -2319,   -212,  -4276 },
+  {  -6201,  -1993,   1774,  -2182 },
+  {  -5500,  -3836,   2201,  -1396 },
+  {  -6934,  -2334,   2366,  -1293 },
+  {  -6124,  -4140,   1337,  -1977 },
+  {  -6553,  -4186,   1756,  -1325 },
+  {  -5126,  -1258,    744,  -3656 },
+  {  -5167,  -1390,   1581,  -2895 },
+  {  -4525,  -3398,   2429,  -1865 },
+  {  -4076,  -3183,   2027,  -2510 },
+  {  -6191,  -3274,   1838,  -1814 },
+  {  -4454,  -2753,   2723,  -1185 },
+  {  -6655,  -4797,    251,  -2595 },
+  {  -6332,  -2232,   1832,    217 },
+  {  -5869,  -1698,    134,    340 },
+  {  -6614,  -1045,   2126,  -1932 },
+  {  -4859,  -2107,   2010,  -2435 },
+  {  -6274,  -1622,   2808,  -1374 },
+  {  -3119,  -3209,    521,  -3988 },
+  {  -5676,  -2082,   -420,  -2711 },
+  {  -7073,  -3623,    696,  -2343 },
+  {  -5986,  -4224,    572,  -2454 },
+  {  -4340,  -4521,    882,  -2771 },
+  {  -6178,  -1933,    535,  -1444 },
+  {  -4923,  -4163,   1744,  -2066 },
+  {  -6410,  -1519,   1058,  -2683 },
+  {  -5077,  -1185,    856,  -2216 },
+  {  -7091,  -2444,    687,  -2597 },
+  {  -5284,  -2165,   3239,   -993 },
+  {  -4763,  -1497,    197,  -3179 },
+  {  -4128,  -4958,   -396,  -3578 },
+  {  -5054,  -3878,   -647,  -2672 },
+  {  -7005,  -3348,   1679,  -1579 },
+  {  -5767,  -1017,   2582,  -1915 },
+  {  -7069,  -2787,   1331,  -2070 },
+  {  -5532,  -2296,    706,  -2950 },
+  {  -5059,  -3543,   -821,  -3637 },
+  {  -6639,  -1835,   1016,   -696 },
+  {  -5611,  -5220,   -694,  -3371 },
+  {  -5994,  -2803,   2933,   -729 },
+  {  -5948,   -619,   1596,  -2676 },
+  {  -5486,  -4419,    153,  -3265 },
+  {  -4329,  -3440,   1646,  -1439 },
+  {  -4083,  -3978,    177,  -3569 },
+  {  -4289,  -2599,   1224,  -3075 },
+  {  -5707,  -3253,   1912,   -759 },
+  {  -6606,  -3437,   2562,   -571 },
+  {  -5254,  -2444,    769,   -352 },
+  {  -6545,  -3154,    582,  -1103 },
+  {  -5328,  -2241,   2566,  -1775 },
+  {  -7216,  -1936,   1538,  -1983 },
+  {  -3730,  -2451,    426,  -3869 },
+  {  -5110,  -1385,   2031,  -1169 },
+  {  -6470,  -2715,    269,  -3123 },
+  {  -5806,  -2480,    -97,  -3832 },
+  {  -3683,  -4916,   -490,  -4330 },
+  {  -6341,  -2083,   -669,   -115 },
+  {  -4913,  -4079,   -837,  -4673 },
+  {  -3274,  -2497,   2334,  -2652 },
+  {  -1286,  -1731,   2550,  -3756 },
+  {  -3375,   -877,    926,  -3977 },
+  {  -2525,  -2079,   2879,  -2625 },
+  {  -5308,   -504,   3111,  -1607 },
+  {  -4904,    460,   4093,  -1232 },
+  {  -1993,   1616,   4656,  -1913 },
+  {  -3481,  -1176,   3119,  -2236 },
+  {  -4132,  -1502,   2339,  -2545 },
+  {  -2542,   1151,   3569,  -2550 },
+  {  -4381,    430,   3147,  -2082 },
+  {  -3888,    867,   3899,  -1657 },
+  {  -2861,   1290,   4202,  -1979 },
+  {  -3893,   -253,   2363,  -2764 },
+  {  -1705,    688,   3827,  -2923 },
+  {  -2223,   2312,   3700,  -3148 },
+  {  -1986,   -720,   5021,   -795 },
+  {  -3177,    242,   1952,  -3352 },
+  {  -1854,   1509,   2528,  -3815 },
+  {  -3173,     97,   5019,   -706 },
+  {  -2689,   -145,   1375,  -3915 },
+  {  -4838,   -385,   2488,  -2427 },
+  {  -4557,   -355,   1603,  -3060 },
+  {  -3522,   1832,   3292,  -2674 },
+  {  -3769,    780,   2378,  -2704 },
+  {  -4323,  -1932,   3414,  -1169 },
+  {  -2740,   1158,   2729,  -3273 },
+  {  -3647,    210,   1464,  -2892 },
+  {  -2342,  -2097,   1513,  -3727 },
+  {  -4422,  -1242,   3130,  -1833 },
+  {  -1308,  -1039,   4290,  -1875 },
+  {  -1754,  -2535,   3298,  -2314 },
+  {  -4102,   -186,   4037,  -1094 },
+  {  -1008,   1570,   3290,    171 },
+  {  -3322,  -2621,   2791,  -1536 },
+  {  -2539,  -2597,   3442,  -1672 },
+  {  -3411,  -2015,   3670,  -1174 },
+  {  -2097,    730,   5581,  -1399 },
+  {  -1510,    -74,   4820,  -2004 },
+  {  -4086,   -868,   4425,   -771 },
+  {   -956,   -986,   3640,  -2925 },
+  {  -2087,  -1250,   3464,  -2458 },
+  {  -3308,  -2411,   1334,  -3667 },
+  {  -2264,   -389,   4004,  -1854 },
+  {   -680,    239,   4058,  -3388 },
+  {  -1357,     30,   2993,  -3658 },
+  {  -3601,   -552,   1177,  -1136 },
+  {  -2641,    442,   4374,  -1625 },
+  {  -2525,    770,   1640,  -3895 },
+  {  -3172,   -891,   3893,  -1608 },
+  {  -2996,     13,   3277,  -2414 },
+  {   -899,   1055,   4470,  -2501 },
+  {   -422,   -584,   3475,  -3787 },
+  {  -1978,   -593,   2566,  -3415 },
+  {  -3150,  -1280,   2362,  -3047 },
+  {  -3592,    224,   1026,  -3932 },
+  {  -4840,  -1189,   3633,   -879 },
+  {  -3952,  -2255,   2916,  -1826 },
+  {  -1695,     28,   1810,   -349 },
+  {   -745,  -2484,   3308,  -3293 },
+  {  -1016,   1563,   5365,  -1823 },
+  {  -2172,  -1787,   4266,  -1287 },
+  {  -1241,  -1951,   3982,  -2413 },
+  {  -2009,  -2639,   2330,  -3480 },
+  {   5105,  -1618,  -2588,  -2015 },
+  {   6497,  -1523,  -3218,   -910 },
+  {   6526,  -2305,  -2029,  -1790 },
+  {   5289,    -99,  -3436,   -400 },
+  {   5781,  -1623,  -1577,  -2617 },
+  {   5259,   -670,  -3125,  -1700 },
+  {   6343,  -1256,   -331,  -3222 },
+  {   7967,   -678,  -2195,  -1462 },
+  {   6119,   -695,  -2988,  -1538 },
+  {   6108,    494,  -3359,  -1548 },
+  {   5067,    969,  -2328,  -2707 },
+  {   7595,   -435,  -1497,  -2056 },
+  {   6929,   -719,  -2420,  -1665 },
+  {   5190,    584,  -2982,  -2103 },
+  {   6106,   -444,  -1411,  -2739 },
+  {   5584,    289,  -1804,  -2803 },
+  {   5276,    227,  -1180,  -3361 },
+  {   7544,  -1525,  -1834,  -1725 },
+  {   5986,  -1470,  -2606,  -1701 },
+  {   5096,   -765,  -1712,  -3006 },
+  {   5423,   -149,  -3933,  -1157 },
+  {   7651,     26,  -2445,  -1507 },
+  {   4745,   -464,  -1735,  -2362 },
+  {   5352,  -1011,  -1094,  -1999 },
+  {   6300,   -672,   -542,  -1950 },
+  {   6675,  -1020,  -1318,  -1059 },
+  {   7218,  -2036,   -603,  -2462 },
+  {   7755,  -1514,  -2430,  -1229 },
+  {   5041,    449,  -1056,  -2405 },
+  {   6710,  -2277,  -1344,  -2284 },
+  {   6824,  -1347,  -2254,    251 },
+  {   6068,  -1857,   -983,  -1316 },
+  {   5603,  -2177,  -2730,  -1477 },
+  {   5838,  -1059,  -3604,   -970 },
+  {   5076,   -789,   -335,  -2413 },
+  {   6191,  -1634,  -2000,  -2129 },
+  {   5092,  -1292,  -2543,  -1034 },
+  {   5305,    435,  -1710,  -1850 },
+  {   6140,    561,  -2176,  -2380 },
+  {   6752,    348,  -2496,  -1890 },
+  {   6405,    273,  -1098,  -2778 },
+  {   6942,  -1340,   -496,  -1381 },
+  {   5238,   -687,  -2454,  -2349 },
+  {   6959,   -882,  -1833,  -2061 },
+  {   6292,   -253,  -2125,  -2199 },
+  {   5838,   -574,   -759,  -3215 },
+  {   6954,  -1484,   -640,  -2771 },
+  {   7498,  -1706,  -1210,  -2154 },
+  {   6772,  -1003,  -1235,  -2532 },
+  {   6014,    228,  -2154,  -1108 },
+  {   6943,  -2178,  -2644,  -1122 },
+  {   7262,   -763,  -3056,  -1090 },
+  {   6273,  -1478,  -1072,    177 },
+  {   4734,    425,  -2912,    357 },
+  {   7129,    168,  -1537,  -2327 },
+  {   7204,   -434,   -746,  -2660 },
+  {   6879,     57,  -3087,  -1310 },
+  {   4623,   -610,   -718,  -3459 },
+  {   6565,   -543,  -1998,   -339 },
+  {   4752,   -277,  -2066,  -1405 },
+  {   7435,  -1416,  -1904,   -505 },
+  {   4076,    150,  -1222,  -3556 },
+  {   7082,    -28,  -1456,  -1174 },
+  {   5941,   -446,  -1326,  -1158 },
+  {   3870,  -1648,  -2474,  -2589 },
+  {    858,     37,  -3387,  -3721 },
+  {   3557,  -1503,  -1664,  -3383 },
+  {   3336,  -1972,  -3079,  -2216 },
+  {   3186,     60,  -4185,   -863 },
+  {   3456,   -773,  -3066,  -2457 },
+  {   4131,   -913,  -2060,  -2601 },
+  {   4431,   -691,  -4114,   -972 },
+  {   3461,   -334,  -3680,  -1751 },
+  {   2006,   -459,  -2214,  -3827 },
+  {   1322,     32,  -2816,  -3203 },
+  {   4425,  -1897,  -2791,  -1946 },
+  {   4504,     23,  -3421,  -1909 },
+  {   3090,   -885,  -2366,  -3264 },
+  {   3209,  -2363,  -3730,   -834 },
+  {   3312,  -1471,  -3641,  -1579 },
+  {   4184,  -1669,  -3323,  -1248 },
+  {   2190,   -931,  -3302,  -2944 },
+  {   2947,   -229,  -4791,  -1195 },
+  {   2020,  -1626,  -2700,  -3125 },
+  {   2214,   -326,  -4352,  -1683 },
+  {   3286,  -2619,  -2412,  -2458 },
+  {   1000,  -2571,  -4129,  -2158 },
+  {   2496,  -2627,  -3611,  -1433 },
+  {   2043,  -2191,  -2167,  -3827 },
+  {   2571,  -2544,  -1915,  -3222 },
+  {   2022,  -1501,  -3856,  -2165 },
+  {   2685,  -1180,  -1461,  -4038 },
+  {   1610,  -2313,  -4391,  -1173 },
+  {   2340,  -2490,  -4215,   -516 },
+  {   1742,  -2615,  -3632,  -2146 },
+  {    523,  -1293,  -4246,  -2442 },
+  {   3725,  -2723,  -3014,  -1576 },
+  {   3554,  -1381,  -4200,   -824 },
+  {   1291,  -1594,  -4777,  -1430 },
+  {   1452,    515,  -2960,  -3830 },
+  {   4264,   -894,  -3305,  -1826 },
+  {   2606,  -1452,  -4522,   -966 },
+  {   1196,   -830,  -4807,  -1816 },
+  {   1054,   -775,  -2616,  -4071 },
+  {   4206,    415,  -4344,  -1132 },
+  {   3044,    491,  -4126,  -1934 },
+  {    988,   -901,  -3353,  -3443 },
+  {   1729,  -3063,  -2267,  -3370 },
+  {   3915,    912,  -2989,  -2387 },
+  {   3781,    300,  -2457,  -3050 },
+  {   2712,    924,  -1350,  -1206 },
+  {   4230,    405,  -2343,    665 },
+  {   1878,   -873,   -225,    -29 },
+  {   3510,     56,  -1334,  -3420 },
+  {   2850,   1447,  -2651,  -3150 },
+  {   1510,   -706,  -4125,  -2483 },
+  {   3115,    793,  -1692,  -3894 },
+  {   2667,    213,  -2973,  -2786 },
+  {   1184,  -2384,  -3051,  -3173 },
+  {   2139,    796,  -2079,  -3697 },
+  {   1464,  -1483,  -3726,  -2754 },
+  {   2407,  -1148,  -3915,  -1569 },
+  {   2612,  -1779,  -3217,  -2271 },
+  {   2406,  -2870,  -2937,  -2496 },
+  {   2140,    126,  -3646,  -2758 },
+  {   2952,  -1036,    268,  -1423 },
+  {     93,  -1931,  -3841,  -3535 },
+  {    389,  -2953,  -3383,  -3343 },
+  {   8652,  -5511,  -1662,    565 },
+  {   7427,  -2791,  -2535,   -842 },
+  {   8541,  -4253,  -1407,   -988 },
+  {   8018,  -3203,  -2998,    105 },
+  {   7231,  -3926,   -958,   1308 },
+  {   7331,  -3690,   -363,   2586 },
+  {   6803,  -3646,  -2226,   -903 },
+  {   8163,  -2811,   -477,  -2235 },
+  {   9356,  -3818,  -1685,   -684 },
+  {   8466,  -2854,   -302,   -698 },
+  {   8458,  -3224,    517,    279 },
+  {   8074,  -2619,  -1326,   2596 },
+  {   8779,  -2761,  -2527,   -441 },
+  {   6533,  -2887,   -899,   -696 },
+  {   7394,  -2305,  -1642,   -120 },
+  {   8281,  -3780,    -22,   1305 },
+  {   9158,  -4413,   -779,    901 },
+  {   9031,  -5240,  -1109,   1678 },
+  {   8717,  -3650,    410,  -1075 },
+  {   7317,  -3197,   -818,  -2264 },
+  {   7934,  -2385,  -1214,  -1886 },
+  {   8256,  -4441,   -291,   -587 },
+  {   7358,  -3395,   1090,   -270 },
+  {   9446,  -4910,  -1343,   -473 },
+  {   8187,  -4726,   -808,   1166 },
+  {   7504,  -3845,    -47,    267 },
+  {   8029,  -2146,  -1283,   -383 },
+  {   7461,  -2705,   -853,    783 },
+  {   9367,  -3636,   -645,   -354 },
+  {   8955,  -3473,   -308,  -1947 },
+  {   8676,  -2683,  -2099,   1485 },
+  {   7481,  -3003,   -871,   -444 },
+  {   8015,  -2839,  -1673,   1175 },
+  {   6947,  -4643,  -1527,  -1047 },
+  {   7622,  -2575,   -137,   -960 },
+  {   9388,  -4279,   -707,  -1322 },
+  {   8382,  -5259,  -1283,   -565 },
+  {   6856,  -4138,  -1030,    630 },
+  {   8659,  -2571,  -1124,  -1666 },
+  {   8763,  -3807,   -537,   2543 },
+  {   8049,  -3578,  -2186,   -604 },
+  {   8272,  -2351,  -1985,  -1214 },
+  {   6855,  -3796,  -1527,  -1631 },
+  {   7178,  -2896,  -1600,  -1756 },
+  {   7040,  -2888,    -89,  -1586 },
+  {   6261,  -3403,   -264,    998 },
+  {   7756,  -4699,  -1543,   -834 },
+  {   7682,  -4622,   -758,  -1721 },
+  {   8839,  -4232,  -2932,   1959 },
+  {   9363,  -4679,  -1956,     39 },
+  {   7883,  -3616,  -1414,  -1432 },
+  {   8828,  -3188,  -1356,  -1312 },
+  {   7746,  -3987,   -121,  -2424 },
+  {   9262,  -3256,   -693,    818 },
+  {   7670,  -3420,   -148,   3504 },
+  {   7344,  -3183,    608,   1595 },
+  {   8976,  -4139,  -1848,   1304 },
+  {   6708,  -4131,     33,   -852 },
+  {   7840,  -4429,  -2275,     79 },
+  {   8980,  -3858,  -2838,    453 },
+  {   7815,  -4604,  -2563,    944 },
+  {   8372,  -4422,  -1783,   3071 },
+  {   8623,  -5128,  -1754,   2888 },
+  {   7462,  -3281,    889,    920 },
+  {   8416,    -59,  -1320,  -1825 },
+  {   7928,  -1488,   -414,  -2499 },
+  {   8110,   -977,  -1047,  -2042 },
+  {   8278,   -687,  -1597,  -1550 },
+  {   7988,   -174,   -977,  -2106 },
+  {   8609,  -1547,  -1628,  -1527 },
+  {   9000,  -1798,   -946,  -1761 },
+  {   8954,   -872,  -1404,  -1594 },
+  {   8939,    466,   -748,  -1212 },
+  {   9549,   -329,   -177,  -1360 },
+  {   9411,    -18,  -1126,  -1568 },
+  {   8859,   -782,   -488,  -1338 },
+  {   8955,   -218,    -43,  -1209 },
+  {   9131,    -69,   -453,  -1001 },
+  {   9069,  -1519,  -1091,  -1199 },
+  {   9247,  -1309,   -566,  -1146 },
+  {   8528,  -1617,   -287,  -1313 },
+  {   7763,   -745,   -149,  -2040 },
+  {   8294,   -343,    257,  -2633 },
+  {  10149,   -893,   -552,  -1649 },
+  {   9398,   -915,    218,  -2042 },
+  {   9703,  -1194,   -675,  -1592 },
+  {   9586,   -700,   -427,  -1710 },
+  {   8930,    497,  -1445,  -1218 },
+  {   9285,  -1323,   -163,  -1552 },
+  {   8431,  -1289,   -985,  -1404 },
+  {   8965,   -655,    653,  -1483 },
+  {   9542,  -1001,   -951,  -1128 },
+  {   9205,   -647,    -37,   -882 },
+  {   8603,    -56,    514,  -1793 },
+  {   9300,    -12,  -1324,   -567 },
+  {   8773,    238,   -184,  -1456 },
+  {   9941,  -1306,    -69,  -1792 },
+  {   9360,    279,   -376,  -1919 },
+  {   9180,   -285,     95,  -2170 },
+  {   9922,   -501,   -970,  -1570 },
+  {   8341,  -1493,   -856,  -2092 },
+  {   8780,   -981,   -850,  -1014 },
+  {   9721,   -548,  -1504,  -1094 },
+  {   9973,  -1493,    482,  -2105 },
+  {   8707,   -333,  -1027,  -1087 },
+  {   9098,   -469,   -315,  -1723 },
+  {   8879,  -1050,   -661,  -2020 },
+  {   8857,    602,   -866,  -1918 },
+  {   8945,  -1025,  -2154,  -1071 },
+  {   8484,  -1930,   -468,  -2179 },
+  {   9177,  -1903,   -224,  -2112 },
+  {   8652,   -137,  -2097,  -1214 },
+  {   9063,   -973,  -1405,   -772 },
+  {   9328,   -456,    662,  -2469 },
+  {  10101,   -697,    127,  -2113 },
+  {   9685,    811,  -2359,  -1024 },
+  {   8586,    -94,   -460,  -1982 },
+  {   7924,   -141,   -509,  -2513 },
+  {   7773,   -669,   -107,  -2835 },
+  {   8636,  -1064,    -46,  -2409 },
+  {   9748,    596,  -1815,  -1349 },
+  {   8924,    304,    547,  -2614 },
+  {   9442,    746,  -1153,  -1679 },
+  {   9454,   -278,   -529,  -1976 },
+  {   8488,    561,    -32,  -2160 },
+  {  10083,    -63,  -1544,  -1364 },
+  {   9390,  -1278,    568,  -1131 },
+  {   9740,    -49,  -2253,   -910 },
+  {   3636,  -2391,  -1115,  -3614 },
+  {   6014,  -3204,  -1902,  -1808 },
+  {   5787,  -3497,  -1116,  -2590 },
+  {   4365,  -3046,  -1632,  -2668 },
+  {   4733,  -2192,  -2029,  -2468 },
+  {   5412,  -2753,  -1633,  -2464 },
+  {   4455,  -3375,   -767,  -3399 },
+  {   4456,  -1644,   -983,  -2841 },
+  {   4039,  -2523,     38,  -3967 },
+  {   3406,  -2662,     72,  -4757 },
+  {   4279,  -2005,   1055,  -4399 },
+  {   4321,  -1377,   -860,  -3786 },
+  {   3743,  -5739,   -651,  -3047 },
+  {   3528,  -5510,    361,  -4060 },
+  {   6496,  -4886,   -136,  -2689 },
+  {   4513,  -5254,    551,  -4010 },
+  {   6557,  -3413,    -92,  -3063 },
+  {   4186,  -2059,    187,     47 },
+  {   6210,  -4117,  -1256,  -1985 },
+  {   6038,  -4343,    351,  -2124 },
+  {   4305,  -4780,  -2077,  -1897 },
+  {   4480,  -3815,  -2228,  -1533 },
+  {   5582,  -3689,   1221,  -3429 },
+  {   5532,  -4874,   1195,  -2765 },
+  {   6518,  -2853,   -905,  -2568 },
+  {   5467,  -2192,    470,  -4115 },
+  {   4139,  -1577,    240,  -3493 },
+  {   5281,  -1926,   -729,  -3340 },
+  {   5214,  -2870,   1359,  -4289 },
+  {   3046,  -3510,  -1536,  -3214 },
+  {   5433,  -2881,  -1230,  -1184 },
+  {   4861,  -3932,  -1071,  -2791 },
+  {   5693,  -4234,  -1906,  -1502 },
+  {   4004,  -3935,  -1804,  -2383 },
+  {   3728,  -3792,    681,  -4773 },
+  {   3621,  -3030,  -1951,  -2598 },
+  {   5133,  -3903,     44,  -3700 },
+  {   3561,  -3451,   1183,  -5301 },
+  {   5026,  -2762,  -2341,  -1780 },
+  {   5841,  -2492,   -467,  -3210 },
+  {   5591,  -1791,    497,  -2472 },
+  {   5054,  -3898,  -1822,  -2097 },
+  {   5813,  -2792,     83,  -1469 },
+  {   4432,  -4497,   1670,  -5193 },
+  {   5338,  -4653,  -1109,  -2200 },
+  {   3239,  -4401,   -648,  -3655 },
+  {   2147,  -3598,  -1200,  -4242 },
+  {   4417,  -2271,  -1552,  -3210 },
+  {   6494,  -4360,    852,  -3565 },
+  {   2393,  -6358,   -856,  -4524 },
+  {   4959,  -4196,   -847,  -1403 },
+  {   4924,  -5438,   -226,  -3026 },
+  {   4254,  -5303,  -1306,  -2424 },
+  {   4121,  -3126,  -2334,  -1981 },
+  {   3437,  -4443,  -1464,  -2953 },
+  {   3203,  -3459,   -529,  -4339 },
+  {   5896,  -5945,    543,  -3246 },
+  {   1987,  -4733,   -220,  -4863 },
+  {   4358,  -4431,   -514,  -3081 },
+  {   4583,  -2416,   -492,  -2287 },
+  {   2943,  -5035,    419,  -4927 },
+  {   5358,  -5129,    987,  -4309 },
+  {   4460,  -3392,   1752,  -5634 },
+  {   3415,  -4633,   1507,  -5945 },
+  {    811,  -4692,   -445,   2333 },
+  {   1009,  -5613,  -1857,   1360 },
+  {   1338,  -2712,  -2720,   3036 },
+  {   1002,  -3754,  -2582,   2344 },
+  {    750,  -4608,  -2334,    714 },
+  {   2043,  -3207,  -2822,   2173 },
+  {   -140,  -4654,  -2953,    357 },
+  {    -54,  -4026,  -2376,   2695 },
+  {   1858,  -5022,   -717,   2287 },
+  {   2064,  -3894,   -722,   3255 },
+  {   2727,  -4558,   -332,   2603 },
+  {   1810,  -5378,    283,   1826 },
+  {   3935,  -4326,    762,   3383 },
+  {   -767,  -4697,  -2510,   1922 },
+  {   2146,  -4312,  -3090,   1641 },
+  {     54,  -5881,  -2114,    921 },
+  {   1992,  -5766,   -640,   1574 },
+  {   1200,  -5371,  -1114,   1828 },
+  {   2973,  -5337,     34,   2266 },
+  {   1531,  -5018,  -2817,   1192 },
+  {   3078,  -4570,    117,   1990 },
+  {    924,  -4286,  -1388,   2713 },
+  {    142,  -5058,  -2848,   1487 },
+  {   -106,  -6180,   -881,    842 },
+  {    673,  -5433,   -229,   1596 },
+  {    783,  -5710,  -2784,    562 },
+  {   1935,  -5729,  -2009,    856 },
+  {   -410,  -3375,  -3326,   2734 },
+  {    234,  -3000,  -2628,   3260 },
+  {    733,  -3405,  -3806,   1589 },
+  {    771,  -4285,  -3544,   1314 },
+  {   1192,  -3563,  -3960,   2178 },
+  {    206,  -5555,  -1250,   1546 },
+  {   -130,  -3815,  -1210,   3041 },
+  {    646,  -3940,   -393,   2992 },
+  {   -184,  -4931,  -1767,   1925 },
+  {   2746,  -5120,  -2275,   1464 },
+  {   2440,  -3731,  -3352,   2729 },
+  {   -490,  -4942,  -3779,    997 },
+  {     68,  -2636,  -4167,   3778 },
+  {     48,  -3986,  -4118,   2106 },
+  {   -978,  -5486,  -1336,   1390 },
+  {   1126,  -5297,   -855,    640 },
+  {   -472,  -3975,  -3622,   1557 },
+  {   2456,  -5344,  -1523,   1648 },
+  {   -774,  -5652,  -2417,   1147 },
+  {    995,  -6122,   -812,   1132 },
+  {   3282,  -4571,  -1763,   2175 },
+  {   3655,  -3862,   -676,   3568 },
+  {   3038,  -3647,  -1672,   3381 },
+  {   2595,  -2964,  -2772,   3263 },
+  {   4176,  -3353,  -1148,   4354 },
+  {   1603,  -3442,  -1500,   3444 },
+  {    828,  -6226,  -1783,    678 },
+  {   1421,  -3333,  -3080,   3403 },
+  {   1121,  -4727,  -1924,   1984 },
+  {   -186,  -5083,   -682,   1796 },
+  {    819,  -2778,  -3488,    530 },
+  {    421,  -2873,  -3832,   2596 },
+  {   2164,  -4263,  -1605,   2282 },
+  {    585,  -4437,   -682,   -491 },
+  {   -644,  -4452,  -1157,   2325 },
+  {   1991,  -4299,    210,   2834 },
+  {   2135,  -3632,  -2113,    665 },
+  {  -7482,  -2724,  -2662,  -1380 },
+  {  -6983,  -2166,  -3756,  -3509 },
+  {  -7085,  -1439,  -2397,  -3112 },
+  {  -7760,  -3049,  -3319,  -2822 },
+  {  -8413,  -2760,  -4406,  -3298 },
+  {  -5995,  -3943,  -1260,  -3750 },
+  {  -7879,  -1554,  -3464,  -2606 },
+  {  -6314,  -2034,  -3878,  -1681 },
+  {  -8849,  -2084,  -1399,  -1231 },
+  {  -7153,  -2602,  -1384,   -817 },
+  {  -8041,  -2571,   -407,  -2785 },
+  {  -7246,  -2233,  -1578,    260 },
+  {  -7336,  -3883,  -4061,  -1342 },
+  {  -7619,  -3908,  -2342,    382 },
+  {  -8684,  -3724,  -1662,   -727 },
+  {  -7850,  -2922,  -1770,  -3449 },
+  {  -6766,  -2034,  -1293,  -1988 },
+  {  -6895,  -2116,   -968,  -3744 },
+  {  -7136,  -5147,  -2618,  -2809 },
+  {  -8224,  -3724,  -2519,  -1589 },
+  {  -6711,  -2750,  -3021,   -219 },
+  {  -8059,  -1638,  -1102,  -3175 },
+  {  -8710,  -4839,  -3963,  -3143 },
+  {  -9363,  -4965,  -3257,  -1002 },
+  {  -6099,  -1751,  -3157,   -395 },
+  {  -6453,  -3216,  -4597,   -483 },
+  {  -7879,  -5477,   -839,  -2638 },
+  {  -7202,  -4038,   -526,  -2856 },
+  {  -8022,  -1228,  -1910,  -1646 },
+  {  -9117,  -1393,  -1582,  -2535 },
+  {  -9095,  -2693,   -636,  -2605 },
+  {  -9076,  -2580,  -3481,  -2519 },
+  {  -8327,  -4859,  -2422,     83 },
+  {  -8368,  -2129,  -2324,  -2173 },
+  {  -8554,  -4563,  -3842,  -2007 },
+  { -10462,  -4261,  -1934,  -2084 },
+  {  -9717,  -3187,  -2294,  -1896 },
+  {  -9625,  -3889,  -3020,  -3224 },
+  {  -9857,  -4955,  -4239,  -2184 },
+  {  -9752,  -2351,  -2277,  -3129 },
+  {  -7219,  -1302,  -2639,  -1603 },
+  {  -7477,  -4360,  -3718,   -559 },
+  {  -5680,  -2033,  -2326,  -3078 },
+  { -10190,  -5548,  -4643,  -3601 },
+  {  -9431,  -4121,   -879,  -2479 },
+  {  -8365,  -5450,  -2020,  -1439 },
+  {  -6289,  -5178,  -1605,  -3845 },
+  {  -8319,  -3866,   -687,  -2792 },
+  {  -8131,  -1031,  -3608,  -3947 },
+  { -10510,  -2560,  -1199,  -2082 },
+  { -11015,  -3640,  -2748,  -3041 },
+  {  -8762,  -5022,  -5231,  -1162 },
+  { -10153,  -2715,  -4648,  -4859 },
+  {  -7930,  -5205,  -1900,  -3600 },
+  {  -9561,  -3548,  -4812,  -3722 },
+  {  -7663,  -4709,  -1180,  -1475 },
+  {  -9073,  -5707,  -1815,  -2980 },
+  {  -8602,  -2363,  -2675,  -3770 },
+  {  -9967,  -5614,  -3575,  -3838 },
+  {  -8324,  -1005,  -2131,  -3254 },
+  { -10331,  -5737,  -2550,  -2940 },
+  {  -8234,  -3354,  -3361,  -4479 },
+  {  -8140,  -1951,  -4526,  -4545 },
+  {  -6679,  -2662,  -2284,  -4182 },
+  {  -1122,  -1514,  -6427,   -212 },
+  {     54,  -1660,  -5424,  -1404 },
+  {    254,  -2778,  -5222,    846 },
+  {   -267,  -1661,  -6577,    814 },
+  {   -305,  -2021,  -5759,   1484 },
+  {  -1791,  -2446,  -6867,    -86 },
+  {  -2929,  -3158,  -6603,  -1799 },
+  {  -1391,  -3189,  -5557,  -1053 },
+  {  -1602,   -884,  -6767,  -1213 },
+  {   -361,   -318,  -6219,    -44 },
+  {  -4078,  -2635,  -5523,   -433 },
+  {   -956,    478,  -4382,   1470 },
+  {  -3300,  -2462,  -6021,  -2721 },
+  {    708,  -2434,  -5085,   -540 },
+  {  -2435,  -3607,  -5647,  -2110 },
+  {   -491,  -1134,  -4681,  -2886 },
+  {     87,  -3435,  -4641,  -1194 },
+  {   -586,  -2927,  -4784,    366 },
+  {  -1394,  -2326,  -6021,    350 },
+  {     97,  -2519,  -4678,  -2120 },
+  {  -1547,  -1907,  -5069,  -2993 },
+  {    268,  -3724,  -4719,    127 },
+  {   -827,  -1190,  -5912,   1144 },
+  {  -3959,  -2322,  -6898,  -1974 },
+  {  -2728,  -2228,  -6426,   -562 },
+  {   -456,   -666,  -5785,  -1609 },
+  {    531,  -1096,  -5731,   -656 },
+  {  -3569,   -688,  -3915,    110 },
+  {  -4752,  -1725,  -4393,   -377 },
+  {  -3210,  -3315,  -6960,   -840 },
+  {   -688,  -3416,  -4971,   1221 },
+  {  -1833,     77,  -6491,  -2434 },
+  {   -239,   -255,  -6850,   -886 },
+  {  -2112,  -1490,  -6291,  -2689 },
+  {  -1544,  -4579,  -5198,  -1261 },
+  {  -2771,  -4014,  -5520,    683 },
+  {  -1635,  -2829,  -5512,   1214 },
+  {   -958,  -2582,  -4823,   2360 },
+  {  -2077,  -4566,  -4642,    365 },
+  {  -3112,  -4214,  -5960,   -823 },
+  {  -2467,  -2510,  -4858,   1467 },
+  {  -1561,  -3399,  -5822,    211 },
+  {   -775,  -1081,  -4424,   2636 },
+  {  -1263,     25,  -6378,  -1392 },
+  {  -3476,   -366,  -5417,  -1393 },
+  {  -3176,  -1476,  -4149,   1466 },
+  {  -2479,    518,  -4448,   -257 },
+  {  -2992,    158,  -4660,  -1279 },
+  {  -1320,  -3872,  -4479,   1147 },
+  {  -1475,   -312,  -5318,    539 },
+  {  -3527,  -1679,  -5860,  -1681 },
+  {  -3397,  -3438,  -5593,   1866 },
+  {  -4089,  -2439,  -4763,   1275 },
+  {   -748,  -4513,  -4687,    -48 },
+  {  -2166,  -4531,  -4691,  -2856 },
+  {  -2385,   -853,  -6035,   -627 },
+  {  -1194,  -4091,  -4472,  -1963 },
+  {   -682,  -3234,  -4084,  -3033 },
+  {  -3255,  -5015,  -5328,    -12 },
+  {  -2313,  -3436,  -4601,   -155 },
+  {  -2792,  -1038,  -6947,  -2019 },
+  {  -1244,  -1526,  -5771,  -1882 },
+  {  -4679,  -3731,  -5506,    283 },
+  {  -3062,    -66,  -3558,   -758 },
+  {  -4895,  -1187,   4751,   3728 },
+  {  -7600,  -2752,   3320,   4613 },
+  {  -5703,  -2975,   3944,   2659 },
+  {  -4972,  -1257,   -246,   2952 },
+  {  -4221,  -2487,   1702,   4295 },
+  {  -2900,  -1529,   2458,   4935 },
+  {  -5061,    407,   2416,   4050 },
+  {  -6931,  -3478,   2761,   2213 },
+  {  -6037,  -3921,   3192,   1866 },
+  {  -6113,   -811,   2407,   3782 },
+  {  -5878,  -1716,   1207,   3478 },
+  {  -5953,  -2853,   2207,   2712 },
+  {  -6807,  -3223,   2749,   3595 },
+  {  -3272,  -3157,   1389,   3788 },
+  {  -5368,  -1904,   1980,   5077 },
+  {  -7235,  -1398,   3075,   4548 },
+  {  -4765,  -3487,   2755,   2796 },
+  {  -7658,  -4435,   2694,   2582 },
+  {  -6997,  -4282,    456,   3832 },
+  {  -5563,  -3115,    -63,   3713 },
+  {  -4244,  -4220,   1450,   2767 },
+  {  -3801,  -2194,    190,   4303 },
+  {  -5458,  -4119,   1958,   2274 },
+  {  -7300,  -3469,   3514,   3193 },
+  {  -4594,  -2067,    775,   4752 },
+  {  -3389,  -1654,   1464,   5412 },
+  {  -4845,  -3483,    964,   3437 },
+  {  -6007,  -2818,   1666,   4659 },
+  {  -8709,  -5007,   1757,   3287 },
+  {  -5833,  -4389,   1025,   3171 },
+  {  -5788,  -1780,   3944,   3661 },
+  {  -4430,   -920,   1938,   4753 },
+  {  -7066,  -1857,   4591,   4538 },
+  {  -3549,   -513,   1427,   5317 },
+  {  -7517,  -1220,   2883,   3049 },
+  {  -7605,  -2687,   1874,   2735 },
+  {  -8718,  -4035,   2676,   3730 },
+  {  -7990,  -3907,   1185,   2607 },
+  {  -6058,  -1744,   3349,   5157 },
+  {  -5954,    565,   3161,   3250 },
+  {  -6478,   -612,   1930,   2271 },
+  {  -6535,  -1445,     -2,   1618 },
+  {  -8963,  -4151,   1192,   4044 },
+  {  -7227,  -3570,   1600,   4234 },
+  {  -4674,     79,    595,   3015 },
+  {  -3974,    430,   2727,   5137 },
+  {  -5299,      9,   3714,   4779 },
+  {  -6779,  -2699,     -8,   2436 },
+  {  -7016,  -1145,   1293,   2310 },
+  {  -6955,  -3312,   1534,   1801 },
+  {  -4025,    740,   1850,   4054 },
+  {  -9589,  -3460,   4154,   5270 },
+  {  -4404,  -1181,   4298,   5173 },
+  {  -7356,  -4583,    -18,   2644 },
+  {  -6516,  -1235,   4439,   6234 },
+  {  -3453,   -301,   4344,   4464 },
+  {  -4643,   1530,   3315,   4340 },
+  {  -4575,  -2557,   3754,   3682 },
+  {  -3643,  -3501,   2051,   2997 },
+  {  -5412,  -2475,   2301,   1579 },
+  {  -5846,    259,   1360,   2348 },
+  {  -5258,  -1358,   1050,    838 },
+  {  -5542,   -219,   6377,   5750 },
+  {  -5713,  -2952,    922,    899 },
+  {  -2049,  -1135,   5206,   1033 },
+  {  -1693,  -1886,   4835,   -106 },
+  {  -2344,  -3504,   4232,    -13 },
+  {  -2475,  -2334,   5043,   1126 },
+  {   -787,  -2549,   3880,   2138 },
+  {  -3159,  -2341,   4830,   2887 },
+  {  -1780,  -1009,   6240,   2061 },
+  {  -4327,  -3363,   2818,    886 },
+  {  -3376,  -2743,   4104,    207 },
+  {  -3250,  -4640,   2718,   1498 },
+  {   -382,  -1075,   4382,   3460 },
+  {  -2416,  -4168,   3530,    816 },
+  {  -1756,  -2708,   4861,    622 },
+  {  -1879,  -2097,   5156,   2889 },
+  {  -2496,  -2418,   3722,   2671 },
+  {  -2717,  -3252,   3341,   1944 },
+  {  -4063,  -4091,   3306,    267 },
+  {  -3549,  -3808,   3747,    842 },
+  {  -2635,    546,   5794,   1894 },
+  {  -1857,  -1121,   4383,   3964 },
+  {  -2226,  -2166,   3489,   3678 },
+  {  -3492,   -660,   5323,   1063 },
+  {  -3033,  -3130,   4382,   1828 },
+  {  -2703,   -625,   6369,   2851 },
+  {  -1656,  -2842,   4584,   -528 },
+  {  -4781,  -2622,   4390,   2097 },
+  {   -413,  -2045,   5081,   3035 },
+  {  -3810,  -2662,   4532,   1095 },
+  {  -3144,  -1858,   5215,   1880 },
+  {  -3562,  -1795,   4928,    670 },
+  {  -4800,  -1509,   5189,   1859 },
+  {  -1085,  -3832,   4169,    900 },
+  {  -1969,  -3270,   2857,   2878 },
+  {  -4267,  -4140,   3176,   1805 },
+  {  -5145,  -3727,   3524,   1168 },
+  {  -1346,  -1876,   5501,   1748 },
+  {  -4998,  -2945,   3699,    338 },
+  {  -3458,  -3096,   3406,   -635 },
+  {  -1751,  -3209,   3508,    395 },
+  {  -2507,    170,   5987,    705 },
+  {  -3756,  -1072,   5647,   3536 },
+  {  -2870,  -1439,   5026,   3212 },
+  {  -3913,  -3225,   3669,   2144 },
+  {  -3739,    226,   5747,    764 },
+  {  -2052,   -820,   5266,   3093 },
+  {  -3214,  -3820,   2409,   2391 },
+  {  -4398,  -2588,   3501,   -218 },
+  {  -4484,  -1763,   4180,   -198 },
+  {  -3368,  -1525,   4362,   -134 },
+  {  -2407,    224,   4905,   3533 },
+  {  -1369,  -2937,   4728,   1788 },
+  {  -4848,  -1707,   4159,    851 },
+  {  -3454,  -1749,   4281,   3230 },
+  {  -1990,  -3853,   3487,   1735 },
+  {  -3117,     92,   6155,   4075 },
+  {  -2676,  -2472,   4078,   -589 },
+  {  -1547,  -2012,   2626,   1835 },
+  {  -4275,   -588,   4824,    725 },
+  {   -601,  -2249,   3736,   3548 },
+  {  -4060,    -61,   5333,   3097 },
+  {  -4303,      7,   6551,   3054 },
+  {  -5003,  -1029,   5786,   3319 },
+  {  -2810,   -728,   5392,    199 },
+  {  -1232,   -200,   5228,   3121 },
+  {   2621,    165,  -6255,    298 },
+  {   3669,    537,  -6844,   1564 },
+  {   1598,  -1190,  -6235,   2523 },
+  {   2164,    -32,  -6894,   1383 },
+  {    853,  -1597,  -6069,   1449 },
+  {   1377,  -1661,  -5266,    108 },
+  {   2660,     48,  -5172,   -517 },
+  {   1903,   -391,  -5677,   1010 },
+  {   3792,    206,  -5274,    -11 },
+  {   1239,   2776,  -2929,   2721 },
+  {   4071,    149,  -7259,   3125 },
+  {   1436,   -480,  -6156,   -196 },
+  {   1373,  -1960,  -5005,   3122 },
+  {   3413,  -1271,  -5176,   3283 },
+  {   3060,    -68,  -6495,   2238 },
+  {   2700,  -2075,  -4681,     91 },
+  {   2928,  -1728,  -5168,   1858 },
+  {   4424,    828,  -4471,     88 },
+  {   2672,  -2604,  -4038,   2753 },
+  {   5223,   -123,  -6749,   2295 },
+  {   4237,   -420,  -5538,   1353 },
+  {   4744,  -1281,  -4097,   4708 },
+  {   1103,  -2764,  -4751,   2024 },
+  {   3747,  -1913,  -3911,   3960 },
+  {   2470,  -1416,  -5542,    615 },
+  {   4847,  -1354,  -5334,   1733 },
+  {   5336,     88,  -7593,   4007 },
+  {   2388,  -2880,  -4807,   1037 },
+  {   4495,   1391,  -5685,   -139 },
+  {   5253,   1637,  -6450,   1533 },
+  {   1199,    795,  -5515,   1261 },
+  {   1397,  -1259,  -4252,   3838 },
+  {    746,     70,  -6640,    604 },
+  {   1584,    166,  -4972,   3072 },
+  {    380,   -999,  -5397,   2267 },
+  {   2974,   1707,  -3242,   5360 },
+  {   5202,   -403,  -5453,   2832 },
+  {   3718,  -1731,  -4760,    714 },
+  {   4150,   -975,  -4792,     61 },
+  {   2925,   -818,  -4841,     15 },
+  {   5301,    577,  -4006,   3259 },
+  {   5265,   1986,  -5679,   3028 },
+  {   3752,   1928,  -4509,   3729 },
+  {   3278,   1925,  -6370,   1247 },
+  {   5107,   1721,  -4853,   3127 },
+  {   3279,   2982,  -2515,   4005 },
+  {   4622,    668,  -6204,    759 },
+  {   6034,    317,  -5763,   4818 },
+  {   -558,     57,  -3785,   2817 },
+  {   4476,   1616,  -3965,   4536 },
+  {   5953,   2056,  -8215,   2715 },
+  {   4387,   2613,  -7463,    868 },
+  {   5834,   1088,  -4736,   4924 },
+  {   6473,   -856,  -6991,   4172 },
+  {   4959,   -293,  -5162,     76 },
+  {   2731,   -843,  -6119,   3847 },
+  {   3245,   1202,  -6833,    616 },
+  {   2553,   1383,  -3829,   3859 },
+  {   4332,   2099,  -3480,   3622 },
+  {   2110,   2683,  -2728,   3990 },
+  {    876,   1167,  -3290,   3466 },
+  {   3991,   1709,  -2410,   4077 },
+  {   5105,    939,  -2584,   3256 },
+  {   4719,    688,  -1566,   3040 },
+  {  -3632,   4335,   1266,  -3303 },
+  {  -4956,   3207,   1312,  -2806 },
+  {  -4669,   2627,   2663,  -2435 },
+  {  -4282,   3708,   2303,  -3038 },
+  {  -4536,   2297,   -175,  -3350 },
+  {  -5234,   2503,   -139,   -880 },
+  {  -3978,   1512,   1092,  -3619 },
+  {  -4519,   4649,   1363,  -2455 },
+  {  -5118,   3132,   1961,  -1577 },
+  {  -5196,   3379,   -182,  -1378 },
+  {  -6420,   4486,   2397,  -1993 },
+  {  -5030,   5046,   1292,  -1118 },
+  {  -4559,   2573,   -927,  -1406 },
+  {  -3501,   3730,    691,  -4930 },
+  {  -4364,   2758,   1007,  -3909 },
+  {  -4026,   2839,  -1559,  -2340 },
+  {  -5037,   4053,    836,  -1571 },
+  {  -4727,   5136,   1110,  -3588 },
+  {  -5245,   2799,   -999,  -2164 },
+  {  -4954,   1501,    422,  -3963 },
+  {  -5994,   2726,   1462,  -2833 },
+  {  -5621,   5159,   2038,  -2512 },
+  {  -4991,   2291,   1917,  -3151 },
+  {  -5469,   4382,   -148,  -2978 },
+  {  -5858,   1983,    807,  -2720 },
+  {  -4709,   3556,    952,   -467 },
+  {  -2489,   2362,   1714,  -4230 },
+  {  -4717,   5004,  -1180,  -3672 },
+  {  -5914,   3653,   1359,  -1317 },
+  {  -5506,   2995,    780,  -1059 },
+  {  -5287,   3945,   2480,  -2293 },
+  {  -3849,   4358,    322,  -1770 },
+  {  -3911,   3570,    252,  -3185 },
+  {  -3660,   5128,    158,  -3719 },
+  {  -4599,   3277,   -503,  -2727 },
+  {  -3673,   3760,  -1252,  -3339 },
+  {  -5161,   2337,    388,  -1943 },
+  {  -3529,   2216,   2156,  -3080 },
+  {  -4309,   4331,   1808,  -1460 },
+  {  -4782,   3820,    480,  -2504 },
+  {  -4166,   3544,   -378,  -1567 },
+  {  -5572,   2466,   -418,  -2909 },
+  {  -6096,   2930,    119,  -1878 },
+  {  -5963,   3554,   1011,  -2233 },
+  {  -6433,   4335,    935,  -2930 },
+  {  -5004,   3314,  -1352,  -3430 },
+  {  -6042,   3463,  -1008,  -3940 },
+  {  -4671,   2214,   -640,  -5040 },
+  {  -2795,   3759,   1412,  -3803 },
+  {  -3647,   4436,    729,   -515 },
+  {  -3594,   1033,     56,  -4148 },
+  {  -2908,   3027,   2889,  -3485 },
+  {  -3338,   2234,    313,  -4285 },
+  {  -3825,   4497,   -561,  -2634 },
+  {  -6167,   3012,    -48,  -3149 },
+  {  -4828,   3515,   -969,  -4475 },
+  {  -5789,   2757,   -539,  -4173 },
+  {  -2452,   3067,    564,  -4249 },
+  {  -4921,   1358,   1331,  -2889 },
+  {  -3127,   4239,  -1045,  -1523 },
+  {  -4780,   2326,  -1118,  -3446 },
+  {  -3908,   5546,    152,  -2622 },
+  {  -6972,   2976,    337,  -2809 },
+  {  -4839,   4613,    -35,  -4077 },
+  {  -1408,   4822,  -1149,  -4997 },
+  {   -981,   4979,   -912,  -6304 },
+  {  -2098,   5689,   -888,  -2878 },
+  {  -3343,   4814,   -657,  -4434 },
+  {  -2461,   3601,   -967,  -4869 },
+  {  -2652,   3944,     87,  -5520 },
+  {  -1104,   6076,    174,  -6407 },
+  {    355,   5370,  -1721,  -5869 },
+  {   1242,   4497,  -1107,  -5091 },
+  {    -89,   4002,  -1491,  -5182 },
+  {   1059,   5693,  -1591,  -4905 },
+  {   1323,   4682,  -2078,  -4768 },
+  {    818,   3996,   -549,  -5468 },
+  {   -287,   4529,    929,  -5543 },
+  {   -919,   5519,  -2791,  -2844 },
+  {  -1407,   5679,  -3289,  -3974 },
+  {   -189,   6530,  -3547,  -4002 },
+  {   -900,   7039,  -3371,  -4855 },
+  {  -2983,   7211,   -363,  -4835 },
+  {   -814,   6503,   -104,  -5106 },
+  {  -2386,   6896,    809,  -4919 },
+  {    845,   4492,    352,  -6621 },
+  {  -1998,   7237,  -1646,  -4231 },
+  {  -3380,   6251,    471,  -4577 },
+  {  -1908,   7059,     84,  -5726 },
+  {   -340,   6346,   -803,  -6265 },
+  {  -2279,   5834,    -47,  -4633 },
+  {  -1532,   5286,  -1748,  -1901 },
+  {  -2757,   6188,   -453,  -3415 },
+  {  -1255,   6405,  -2043,  -6357 },
+  {    918,   5581,   -121,  -5667 },
+  {   1840,   5336,   -821,  -5034 },
+  {  -2475,   4992,  -1825,  -3104 },
+  {  -2413,   5606,  -1789,  -4298 },
+  {    132,   5128,  -2389,  -4442 },
+  {    223,   6400,  -2653,  -4742 },
+  {   -673,   5012,    680,  -4582 },
+  {  -1657,   6624,   -349,  -3596 },
+  {   -755,   6289,  -1860,  -3978 },
+  {   -572,   6894,  -1946,  -5207 },
+  {  -1141,   4756,  -2665,  -5586 },
+  {  -1073,   4269,   -431,  -4030 },
+  {    186,   5761,    916,  -5868 },
+  {  -1907,   4836,   1017,  -5106 },
+  {   -963,   3363,  -1248,  -6348 },
+  {  -3262,   4774,  -1818,  -5858 },
+  {    847,   3812,  -2538,  -4302 },
+  {  -1223,   5903,   1360,  -5479 },
+  {  -1094,   6923,  -1244,  -2381 },
+  {    267,   6276,   -709,  -2846 },
+  {   -157,   5840,   1124,  -4266 },
+  {    889,   3206,   -910,  -5305 },
+  {  -1736,   3344,    582,  -4838 },
+  {  -2357,   5676,  -2695,  -6277 },
+  {  -1916,   6901,   -986,  -5397 },
+  {  -3062,   6028,   -695,  -5687 },
+  {   1836,   3566,  -1357,  -5226 },
+  {  -2176,   4938,    646,  -3872 },
+  {  -2199,   3055,   -208,  -6124 },
+  {   -236,   3032,   -821,  -5325 },
+  {  -3989,   7277,   -565,  -3899 },
+  {   -595,   4362,     74,  -5975 },
+  {    684,   5874,   -841,  -4424 },
+  {  -2731,   6305,  -2389,  -5465 },
+  {  -5775,   1325,    -56,  -2528 },
+  {  -7029,   -534,  -1890,  -3278 },
+  {  -5798,    -15,  -2734,  -2210 },
+  {  -5504,  -1198,   -353,  -3659 },
+  {  -5079,    960,   -894,  -4336 },
+  {  -6073,    -36,   -133,  -3014 },
+  {  -5782,   -259,  -1025,  -3986 },
+  {  -6843,   1262,   -807,  -1639 },
+  {  -5263,   -918,  -3290,   -579 },
+  {  -4840,    461,  -2158,   -533 },
+  {  -6014,    -50,   -620,    504 },
+  {  -5843,    241,  -1359,   -282 },
+  {  -5898,    577,    769,  -3271 },
+  {  -6833,   -946,   -466,  -3347 },
+  {  -6026,   1459,   -512,   -729 },
+  {  -7361,    747,   -388,  -1110 },
+  {  -6391,   2142,  -1160,  -2513 },
+  {  -6995,    304,    498,  -2673 },
+  {  -6757,    679,   -386,   -433 },
+  {  -5222,   1688,  -1093,  -1032 },
+  {  -5019,    575,    184,  -3627 },
+  {  -4237,    628,  -3507,  -1243 },
+  {  -7479,   -456,  -1722,  -1486 },
+  {  -6464,    713,  -1273,  -1153 },
+  {  -6255,   1682,   -606,  -3607 },
+  {  -7033,   1497,    -71,  -1955 },
+  {  -6694,   1556,  -1721,  -3214 },
+  {  -6114,   -356,    813,  -2575 },
+  {  -5308,    632,  -1851,  -1636 },
+  {  -5742,   -911,  -1733,    383 },
+  {  -6083,   -387,  -2313,   -879 },
+  {  -6535,   -530,  -1505,  -2083 },
+  {  -4896,   1223,  -2750,  -1816 },
+  {  -6392,   -463,  -3247,  -2093 },
+  {  -5373,   1264,  -2706,  -3042 },
+  {  -3894,  -1390,  -1020,   -891 },
+  {  -6179,   1168,  -1966,  -1922 },
+  {  -5162,   1668,  -1617,  -1916 },
+  {  -6453,    920,  -1169,  -2432 },
+  {  -6130,   2005,   -536,  -1519 },
+  {  -6552,    -98,   -518,  -1938 },
+  {  -7528,    355,  -1101,  -1772 },
+  {  -5745,    610,   -247,  -1360 },
+  {  -7003,    177,  -2064,  -1958 },
+  {  -6956,   -570,  -2220,  -4225 },
+  {  -7830,    791,  -1394,  -2774 },
+  {  -7634,    480,  -3171,  -4224 },
+  {  -7913,   1154,   -350,  -2381 },
+  {  -5063,   1704,  -1804,  -2977 },
+  {  -4887,   -524,  -2703,    188 },
+  {  -5551,    406,  -1620,  -3063 },
+  {  -7109,   1342,    381,  -3021 },
+  {  -6846,    631,   -458,  -3398 },
+  {  -4606,   -605,     11,  -3930 },
+  {  -8134,   -225,  -1738,  -2648 },
+  {  -7043,    402,  -2734,  -3059 },
+  {  -7417,   1825,  -2545,  -4389 },
+  {  -6971,   -236,  -1031,   -665 },
+  {  -5752,   2111,  -1632,  -3808 },
+  {  -7660,    -78,   -624,  -3135 },
+  {  -6358,    619,  -1951,  -3911 },
+  {  -8134,    408,  -1935,  -3695 },
+  {  -6335,   1911,  -2368,  -4505 },
+  {  -7116,   2163,   -344,  -2753 },
+  {   2357,   4488,   2220,  -5682 },
+  {   1385,   3206,   2300,  -5305 },
+  {   1419,   2557,   5203,  -3516 },
+  {    262,   4315,   3920,  -1847 },
+  {   3316,   3187,   1612,  -5609 },
+  {   1729,   2350,   1673,  -6068 },
+  {   1603,   6126,   1467,  -2839 },
+  {  -1339,   3316,   3691,  -3530 },
+  {   -563,   4618,   3180,  -4548 },
+  {    463,   4624,   3111,  -5614 },
+  {   1246,   5455,   3356,  -5720 },
+  {    480,   2149,   5422,  -2893 },
+  {   1768,   4827,    913,  -5579 },
+  {   -149,   5381,   4366,  -3297 },
+  {    985,   3672,   2644,    -92 },
+  {   -258,   2911,   5817,  -2213 },
+  {   3428,   3289,   3351,  -3541 },
+  {   -666,   3295,   4727,  -2869 },
+  {     35,   6641,   4160,  -4052 },
+  {    623,   6787,   3156,  -4560 },
+  {   2654,   4360,   4676,  -4632 },
+  {   1386,   5246,   4834,  -4497 },
+  {   3488,   4574,   3856,  -5946 },
+  {    383,   4481,   4168,  -4110 },
+  {   1753,   3652,   4288,  -3326 },
+  {   1344,   4905,   2508,  -4660 },
+  {   1580,   4106,   3104,  -2224 },
+  {   2027,   5038,   1683,  -1554 },
+  {    446,   3699,   5872,  -3013 },
+  {   4637,   4087,   3578,  -5018 },
+  {   2629,   3560,   5331,  -4900 },
+  {   1527,   6674,   2523,  -4131 },
+  {  -1437,   2804,   2528,  -4464 },
+  {   -229,   3355,   2016,  -5537 },
+  {   3666,   3418,   4374,  -4581 },
+  {   1192,   3799,    923,  -6596 },
+  {   2040,   2956,    448,  -5322 },
+  {   2468,   5768,   4029,  -5869 },
+  {   3438,   6516,   3529,  -6667 },
+  {   2737,   5495,    680,  -5535 },
+  {   3896,   5727,   1801,  -4958 },
+  {   4988,   4957,   3592,  -6518 },
+  {   -542,   4416,   5794,  -2787 },
+  {   4136,   4354,   2064,  -4696 },
+  {   3067,   5936,   1207,  -3396 },
+  {   2789,   4966,   2405,  -3854 },
+  {   1731,   3270,   3251,  -1063 },
+  {   1767,   5537,   2084,  -2349 },
+  {    465,   3116,   4532,   -837 },
+  {   1499,   2627,   4610,  -2212 },
+  {    122,   3095,   3642,  -3552 },
+  {   2542,   2866,   2705,  -6402 },
+  {   3134,   4323,    698,  -4785 },
+  {    731,   1859,   3112,  -5242 },
+  {   2553,   2980,   3241,  -4846 },
+  {   1329,   5310,   1607,  -6624 },
+  {   2468,   1858,   3476,  -1034 },
+  {   -172,   4996,   2000,  -5562 },
+  {   2621,   4220,   1574,  -3386 },
+  {   -333,   1832,   3362,  -4117 },
+  {   2169,   6762,   3065,  -6225 },
+  {   2844,   5528,   3223,  -4765 },
+  {    526,   5175,   1644,  -4267 },
+  {   2922,   4426,   2414,  -2610 },
+  {    452,   1399,  -4516,  -2636 },
+  {   2872,   1720,  -4667,  -1435 },
+  {   1279,    702,  -5424,  -1984 },
+  {   2187,    870,  -5021,  -1341 },
+  {    583,   -144,  -4628,  -2464 },
+  {      3,   2237,  -5284,  -2827 },
+  {    -19,   1005,  -5460,  -1819 },
+  {   2897,   2084,  -5885,   -515 },
+  {   -400,   3370,  -5527,  -2947 },
+  {   1505,   2593,  -5518,  -1802 },
+  {   1341,   4534,  -5094,  -1899 },
+  {   3241,   3670,  -5493,  -1252 },
+  {  -1287,    921,  -5994,  -1675 },
+  {    627,    408,  -6652,   -364 },
+  {   -260,   1127,  -4849,  -3247 },
+  {    371,   3400,  -5976,  -2285 },
+  {   1533,   1566,  -6373,   -610 },
+  {   2462,   4274,  -6184,  -1254 },
+  {   1782,   3363,  -6222,  -1381 },
+  {    572,   4650,  -5673,  -2754 },
+  {   2674,   3414,  -4460,  -2154 },
+  {   3614,   3820,  -6883,   -398 },
+  {   1136,     -1,  -5511,  -1112 },
+  {  -1773,   1137,  -5647,  -2377 },
+  {   -753,   2104,  -6085,  -2565 },
+  {   -204,   3025,  -4731,  -1418 },
+  {  -1486,   1438,  -4380,   -216 },
+  {    302,    858,  -5786,   -264 },
+  {   3486,   1495,  -5234,   -783 },
+  {    888,   2327,  -3423,  -3720 },
+  {   -259,    772,  -6596,  -1311 },
+  {  -1197,   2073,  -5174,  -1826 },
+  {   1500,   3470,  -4462,  -2645 },
+  {   3072,   1960,  -3277,  -2264 },
+  {   1841,    952,  -4324,  -2340 },
+  {   1994,   2200,  -3940,  -2923 },
+  {  -1782,   1699,  -4667,  -1075 },
+  {  -1464,   2906,  -3468,   -375 },
+  {    366,   2380,  -3747,   1467 },
+  {   -545,   1645,  -4619,    376 },
+  {   1724,   2350,  -2374,  -3512 },
+  {   3184,   2628,  -2996,  -3275 },
+  {    734,   2010,  -6239,  -1479 },
+  {    524,   3756,  -4496,  -3263 },
+  {   1492,   3570,  -3494,  -3600 },
+  {   -932,    618,  -5389,  -2894 },
+  {   -133,   2161,  -4083,  -3267 },
+  {    786,    774,  -3279,  -3731 },
+  {   1078,    803,  -3843,  -3007 },
+  {   -332,   3405,  -3347,     40 },
+  {    -17,      6,  -4005,  -3690 },
+  {   -189,   4372,  -4488,  -2561 },
+  {   -450,   3846,  -3790,  -1370 },
+  {    362,   2212,  -5272,    -15 },
+  {  -1529,    791,  -6802,  -2296 },
+  {   2145,   4241,  -4474,    376 },
+  {   1813,   2426,  -2932,  -2726 },
+  {   -542,   4557,  -3140,  -1080 },
+  {   1192,   3784,  -4371,    -20 },
+  {   2784,   5188,  -6399,  -1394 },
+  {    431,   4561,  -3673,  -1398 },
+  {   1382,   3096,  -4083,   1253 },
+  {   1209,   4224,  -2930,   1500 },
+  {   2798,   2684,  -6676,   -606 },
+  {  -2396,   1510,  -5381,  -2713 },
+  {  -2625,   2542,  -4032,  -2880 },
+  {  -1231,   3967,  -4098,  -2886 },
+  {  -1393,   2374,  -3862,  -4525 },
+  {  -2495,   1665,  -1637,  -5445 },
+  {  -3854,   1759,  -1750,  -4944 },
+  {  -2373,   1668,  -2856,  -6251 },
+  {  -2668,   1981,   -886,  -4557 },
+  {  -2927,   4427,  -3451,  -6172 },
+  {  -1925,   2596,  -4696,  -2527 },
+  {  -3202,   2847,  -3928,  -5896 },
+  {  -3332,   1665,  -5025,  -3412 },
+  {  -3212,   3115,  -4155,  -4062 },
+  {  -1013,   3205,  -5133,  -3751 },
+  {  -2022,   4595,  -3947,  -5611 },
+  {  -3556,   1755,  -3715,  -2300 },
+  {  -1784,   4114,  -2723,  -1773 },
+  {  -3586,   4081,  -2733,  -4942 },
+  {  -1608,   3685,  -4154,  -4573 },
+  {  -3368,   4042,  -4452,  -6227 },
+  {  -1407,   3881,  -5729,  -3719 },
+  {  -2751,   3281,  -5077,  -4999 },
+  {  -3791,   2410,  -4906,  -5288 },
+  {   -730,   2303,  -4217,  -3755 },
+  {  -1812,   2311,  -5492,  -3709 },
+  {   -610,   4336,  -3915,  -3783 },
+  {  -2841,   4337,  -4278,  -4430 },
+  {  -1662,   4666,  -4661,  -3964 },
+  {   -589,   5209,  -4923,  -3682 },
+  {  -4155,   2234,  -4076,  -4218 },
+  {  -3951,   2770,  -2665,  -2805 },
+  {  -2302,   3228,  -3717,  -1908 },
+  {  -3129,   4373,  -2264,  -2851 },
+  {   -447,   1363,  -3578,  -4323 },
+  {  -2648,   4237,  -3159,  -3071 },
+  {  -4072,   3241,  -3541,  -4605 },
+  {  -4507,   3458,  -2339,  -3838 },
+  {  -1646,    997,  -4926,  -3970 },
+  {  -3025,   1614,  -3940,  -1242 },
+  {  -1337,   1756,  -3163,  -5529 },
+  {  -3203,   1865,  -3282,  -4354 },
+  {  -1646,   2118,  -2203,  -6018 },
+  {    174,   1871,  -2707,  -4639 },
+  {  -2607,   1485,  -4778,  -4750 },
+  {  -2199,   3991,  -3134,  -4879 },
+  {  -2962,   3323,  -2816,  -2419 },
+  {  -5286,   2495,  -4548,  -5395 },
+  {  -2810,   3710,  -2274,  -4211 },
+  {   -330,   3006,  -2993,  -4678 },
+  {  -1187,   2411,  -2743,  -5196 },
+  {   -664,   4033,  -3101,  -5641 },
+  {  -1458,   3602,  -2816,  -5371 },
+  {  -4116,   4923,  -3321,  -5630 },
+  {  -4165,   2528,  -2592,  -4798 },
+  {  -2759,   3080,  -2333,  -5719 },
+  {  -5157,   3011,  -5526,  -6348 },
+  {  -3095,   2126,  -5881,  -4234 },
+  {  -4377,   3849,  -3600,  -6099 },
+  {  -1994,   4947,  -5235,  -4753 },
+  {  -1067,    600,  -3258,  -5133 },
+  {  -4992,   3302,  -2208,  -5051 },
+  {  -3377,   2981,  -1655,  -4815 },
+  {  -3325,   2446,  -1787,  -6116 },
+  {  -2341,   2737,  -3240,  -6347 },
+  {  -2258,  -3732,   3710,  -1235 },
+  {  -1558,  -3849,   2694,  -3012 },
+  {   -599,  -4837,   3050,  -2951 },
+  {  -2246,  -5433,   2798,  -1910 },
+  {  -2255,  -4989,   3260,    270 },
+  {  -3026,  -5353,   2693,  -1036 },
+  {  -1151,  -6097,   1097,  -3782 },
+  {  -3391,  -6012,   2130,  -1303 },
+  {  -2850,  -4422,   3375,   -480 },
+  {  -1138,  -3779,   1491,  -4162 },
+  {   -551,  -3892,   3787,  -2082 },
+  {  -3221,  -3676,   3144,  -1202 },
+  {  -3023,  -5196,   2650,    605 },
+  {  -1756,  -5729,   2646,    321 },
+  {  -2693,  -4409,    494,  -4797 },
+  {  -1913,  -4573,   3372,  -1730 },
+  {  -1277,  -3604,   4061,   -993 },
+  {   -420,  -4993,   1351,  -4796 },
+  {  -3052,  -5333,   1435,  -1242 },
+  {   -602,  -5034,   3869,  -1141 },
+  {  -2436,  -4680,   1665,  -3019 },
+  {  -2657,  -3658,   1459,  -3391 },
+  {  -1220,  -6246,   2749,   -525 },
+  {  -3838,  -4844,   2265,  -1735 },
+  {  -1247,  -5679,   3356,  -1417 },
+  {   -917,  -5448,   3342,    105 },
+  {  -1756,  -6839,   2276,  -2350 },
+  {   -412,  -5206,   1764,  -3539 },
+  {  -1439,  -6915,   1442,  -3750 },
+  {  -1381,  -4439,   3863,   -282 },
+  {  -3482,  -4953,   2726,   -336 },
+  {  -1376,  -5931,   1714,  -1987 },
+  {  -1716,  -4405,   2608,    105 },
+  {  -1590,  -5191,   2652,  -2704 },
+  {  -2149,  -6442,   2453,  -1263 },
+  {  -3426,  -3832,   2334,  -1829 },
+  {  -2747,  -5948,   2362,   -173 },
+  {  -2435,  -3267,   2966,  -1710 },
+  {  -3979,  -4282,   2705,   -775 },
+  {   -356,  -4238,   2544,  -4343 },
+  {  -1363,  -6471,   2817,  -1836 },
+  {  -2878,  -5117,    218,  -3149 },
+  {  -3539,  -5196,   1710,  -2356 },
+  {  -2888,  -4537,   2746,  -1701 },
+  {  -1870,  -4439,   1496,  -4121 },
+  {  -1486,  -3388,   3349,  -2145 },
+  {  -3333,  -4138,   1467,  -2876 },
+  {   -345,  -5340,   1012,  -1190 },
+  {  -1672,  -4992,   2289,  -1029 },
+  {  -2146,  -5528,   3038,   -635 },
+  {   -316,  -3656,   3426,  -3152 },
+  {  -2695,  -5812,   2336,  -2050 },
+  {  -2067,  -6052,    737,  -3258 },
+  {  -2664,  -4205,   -350,  -1266 },
+  {   -617,  -5406,     80,  -4853 },
+  {  -2418,  -3825,   1853,  -1326 },
+  {  -1961,  -4339,    583,  -4315 },
+  {  -1495,  -5141,   -133,  -5205 },
+  {  -3208,  -6440,   1691,  -2069 },
+  {  -2632,  -3633,   2325,  -2761 },
+  {  -2624,  -5670,   1252,  -3676 },
+  {  -3687,  -5608,    687,  -2833 },
+  {  -3320,  -5707,     16,  -3877 },
+  {  -2738,  -6112,     84,  -5135 },
+  {   2277,  -5661,   3076,    843 },
+  {   1555,  -5769,   2821,  -5236 },
+  {    536,  -6381,    603,  -4910 },
+  {    734,  -4609,   3314,  -4092 },
+  {   1836,  -4547,   3267,  -4322 },
+  {    -13,  -5976,   3752,  -1607 },
+  {   1423,  -6318,   2336,    398 },
+  {    365,  -7779,   1498,   -534 },
+  {   2104,  -8366,   2946,  -1345 },
+  {    143,  -5545,   1898,  -3756 },
+  {    655,  -6852,   1430,    148 },
+  {      4,  -6653,   2397,    -59 },
+  {   2346,  -5996,   4562,   -934 },
+  {   1229,  -7104,   2963,   -598 },
+  {   -528,  -7048,   2887,  -1790 },
+  {   1451,  -6857,   3900,  -1637 },
+  {    554,  -6018,   3336,      9 },
+  {   3278,  -5758,   4034,    129 },
+  {   3541,  -7145,   4905,  -1575 },
+  {   2339,  -6907,   3464,   -301 },
+  {   2775,  -7301,   1667,  -3894 },
+  {    539,  -7887,    991,  -4156 },
+  {   2115,  -7421,   3131,  -3075 },
+  {   2803,  -8546,   2564,  -5836 },
+  {   2869,  -5833,   1620,  -4561 },
+  {   2591,  -7281,   3215,  -4719 },
+  {  -1228,  -8477,    706,  -4782 },
+  {   1967,  -5243,   4813,  -1940 },
+  {    701,  -7010,   2273,  -3893 },
+  {    915,  -8470,   1918,  -5620 },
+  {    -94,  -6715,    156,  -3873 },
+  {   1074,  -5607,   4389,  -1017 },
+  {   2739,  -6551,   1227,  -3521 },
+  {    725,  -7835,   2701,  -1291 },
+  {   -493,  -7475,   2263,  -1075 },
+  {   -412,  -6508,   2984,   -744 },
+  {    665,  -5451,   3725,  -2692 },
+  {   1499,  -8129,   3564,  -2072 },
+  {   2870,  -6333,   4487,  -2108 },
+  {    706,  -5007,   3911,   -152 },
+  {   -482,  -8660,   1483,  -2900 },
+  {   2481,  -6596,   2518,  -1715 },
+  {   1403,  -6414,   1398,  -5387 },
+  {    652,  -6267,    583,  -5942 },
+  {    694,  -7540,    646,  -6272 },
+  {   2275,  -7614,    256,  -5015 },
+  {   1416,  -9727,   1900,  -3153 },
+  {   2760,  -6433,   3875,  -3771 },
+  {   2325, -11196,   2182,  -5155 },
+  {   1223, -11061,   1377,  -5097 },
+  {    108, -10603,    307,  -4952 },
+  {   -118,  -8268,   1650,  -1572 },
+  {   1839,  -7943,   1755,   -612 },
+  {   2501,  -9056,    981,  -2969 },
+  {   2902,  -8476,   1491,  -5780 },
+  {   1995, -11175,   1585,  -3643 },
+  {    696,  -8212,    828,  -2474 },
+  {   1526,  -8649,   1380,  -1210 },
+  {    461,  -7253,   3222,  -2229 },
+  {   2966,  -8641,   4121,  -3271 },
+  {    833,  -6039,   2361,  -1086 },
+  {   3565,  -7312,   1980,  -5427 },
+  {   2850,  -8671,   3760,  -1846 },
+  {   2643,  -7281,   2163,   -173 },
+  {   3463,  -3706,  -3132,   -923 },
+  {   1315,  -3825,  -3443,      2 },
+  {   2594,  -4083,  -3815,    670 },
+  {   1826,  -4291,  -2741,   -155 },
+  {    868,  -3749,  -4175,   -298 },
+  {   2008,  -4237,  -3897,   -517 },
+  {   1242,  -3493,  -4335,  -1335 },
+  {    -88,  -4142,  -3390,  -1529 },
+  {   2176,  -3488,  -3822,   -975 },
+  {   1706,  -5188,  -3415,   -637 },
+  {   2717,  -6159,  -2333,   -882 },
+  {   1276,  -3978,  -4361,    537 },
+  {   2471,  -5556,  -2866,   -208 },
+  {    799,  -4673,  -4086,     56 },
+  {   1901,  -4786,  -3533,    270 },
+  {   3036,  -3902,  -3606,   -333 },
+  {   2249,  -3317,  -4319,   -144 },
+  {   2594,  -4207,  -2105,  -2930 },
+  {   4008,  -4774,  -2626,   -902 },
+  {   1038,  -3659,  -3496,  -2454 },
+  {   2725,  -3597,  -3298,  -1535 },
+  {   1662,  -5803,  -2813,    175 },
+  {    705,  -3757,  -3441,  -1484 },
+  {   1860,  -5987,  -2821,   -886 },
+  {   3786,  -4918,  -2199,  -1929 },
+  {   3683,  -4235,  -2547,  -1287 },
+  {   2531,  -4896,  -2956,  -1593 },
+  {   1005,  -5585,  -3324,   -180 },
+  {   1625,  -5229,  -1756,  -3642 },
+  {   1494,  -5041,  -2989,  -2685 },
+  {   2718,  -4655,  -3224,   -867 },
+  {   2374,  -6640,  -1745,  -2975 },
+  {   2133,  -6436,  -2477,  -1499 },
+  {   1833,  -4418,  -3523,  -1512 },
+  {   1128,  -4910,  -2658,  -1106 },
+  {    689,  -4777,  -2831,  -2085 },
+  {   3593,  -5280,  -2627,   -315 },
+  {   3264,  -3771,  -2673,  -1861 },
+  {   3202,  -5602,  -2409,    402 },
+  {    552,  -4618,  -2221,  -3002 },
+  {   3095,  -5356,  -2666,  -1083 },
+  {   3401,  -4609,  -3146,     45 },
+  {   3051,  -4662,  -2192,  -2232 },
+  {   2798,  -5552,  -2462,  -1941 },
+  {   2354,  -5815,  -2223,  -2619 },
+  {    192,  -3708,  -2807,  -2658 },
+  {   1886,  -4226,  -1862,  -3529 },
+  {   2526,  -3976,  -2819,  -2332 },
+  {   1577,  -3870,  -2711,  -2806 },
+  {   1288,  -5588,  -3382,  -1403 },
+  {   2711,  -5399,  -1564,  -3253 },
+  {   1459,  -5492,  -2222,   -322 },
+  {   2823,  -5091,  -2886,    776 },
+  {   3559,  -5821,  -2109,  -1360 },
+  {   1587,  -6331,  -2760,  -1909 },
+  {   2139,  -5213,  -2874,  -2120 },
+  {   1318,  -4337,  -3695,  -2098 },
+  {    821,  -4471,  -1849,   -565 },
+  {   3329,  -4782,  -1725,    -89 },
+  {    582,  -4914,  -4105,  -1119 },
+  {    417,  -4144,  -4072,  -2529 },
+  {   -199,  -3803,  -2765,  -4042 },
+  {   2731,  -4283,  -2143,      1 },
+  {   2911,  -6187,  -1951,  -2116 },
+  {   1573,  -6094,   -493,  -2838 },
+  {   2081,  -6927,   -864,  -3211 },
+  {   1058,  -7826,     79,   -364 },
+  {   3147,  -5570,   -684,   -978 },
+  {   3572,  -5856,   1060,   1824 },
+  {   1143,  -6702,  -1478,    338 },
+  {   2341,  -7220,    -88,    260 },
+  {   3639,  -6861,    668,    815 },
+  {   2227,  -6268,  -1706,    446 },
+  {   3390,  -6082,   -353,   1302 },
+  {   1123,  -7556,  -1237,   -430 },
+  {   1729,  -7742,    729,   -218 },
+  {   1457,  -6774,    587,    579 },
+  {    505,  -6919,   -569,    371 },
+  {   1106,  -7245,     78,    158 },
+  {   2755,  -6745,  -1122,    338 },
+  {   3069,  -6040,  -1415,    986 },
+  {   2174,  -7064,  -1430,   -283 },
+  {   1390,  -8626,   -446,  -3031 },
+  {   3534,  -6890,   -431,    547 },
+  {   2267,  -9618,    475,  -2994 },
+  {   3672,  -7673,     75,   -115 },
+  {   2131,  -7560,  -1206,   -750 },
+  {   2972,  -7477,   -685,   -262 },
+  {   1604,  -6637,   -672,    699 },
+  {   1666,  -7577,   -577,   -240 },
+  {   1591,  -6554,  -2158,    -94 },
+  {   2348,  -6286,   -353,   1123 },
+  {   2017,  -8810,   -412,  -1805 },
+  {   2892,  -6713,  -1765,   -554 },
+  {   2500,  -6828,  -1995,  -1197 },
+  {   3877,  -6639,   -224,  -1655 },
+  {   2392,  -7872,    -91,   -333 },
+  {   3562,  -7370,   -532,  -2836 },
+  {   2552,  -7614,    164,  -1805 },
+  {    990,  -6104,    218,    438 },
+  {    910,  -7861,    312,  -1195 },
+  {   1472,  -6327,    372,   -640 },
+  {   1576,  -7143,  -1983,   -843 },
+  {    422,  -7625,   -457,   -278 },
+  {   1797,  -8532,    405,  -1011 },
+  {   1088,  -7396,   -238,  -2277 },
+  {   3209,  -6753,  -1431,  -2072 },
+  {   2617,  -6839,    100,  -2573 },
+  {   2575,  -8573,   -387,  -3188 },
+  {   3618,  -6971,  -1190,   -321 },
+  {   2205,  -7361,  -1695,  -2008 },
+  {   2985,  -6297,   1464,   1179 },
+  {   2804,  -7310,   1053,    338 },
+  {   1362,  -6074,  -1163,   -840 },
+  {   3336,  -6325,  -1794,     21 },
+  {   2836,  -8109,    818,   -329 },
+  {   2791,  -5879,    560,   1546 },
+  {   2392,  -6064,    135,    100 },
+  {   1838,  -6194,    596,   1085 },
+  {   1926,  -7515,   -414,  -4901 },
+  {   3225,  -7298,  -1202,  -1189 },
+  {   3960,  -7558,   -659,   -719 },
+  {   3442,  -6647,  -1692,  -1095 },
+  {   3381,  -6441,    262,   -886 },
+  {   1431,  -8150,  -1186,  -1406 },
+  {    340,  -8498,   -150,   -899 },
+  {   3004,  -8149,   -260,   -953 },
+  {   2749,  -6611,    563,    873 },
+  {  -6647,  -1325,  -4517,  -4691 },
+  {  -6005,  -1657,  -4089,  -3797 },
+  {  -3157,    588,  -5213,  -3068 },
+  {  -3311,  -1425,  -6329,  -3726 },
+  {  -5866,   -819,  -3857,  -2744 },
+  {  -5001,  -1799,  -1075,  -4621 },
+  {  -5330,  -2650,  -2672,  -4664 },
+  {  -4930,   -539,  -2363,  -4010 },
+  {  -2984,     10,  -3863,  -5749 },
+  {  -1055,  -2106,  -3713,  -4267 },
+  {  -5476,   -502,  -4279,  -6504 },
+  {  -5231,  -1543,  -5018,  -6425 },
+  {  -5134,   -363,  -3165,  -5109 },
+  {  -3953,   -771,  -4107,  -6393 },
+  {  -2159,   -563,  -3652,  -5342 },
+  {  -3888,  -2321,   -919,  -5057 },
+  {  -1236,   -597,  -4235,  -4193 },
+  {  -4053,    675,  -3083,  -6174 },
+  {  -2793,  -1089,  -5396,  -3460 },
+  {  -3000,    -44,  -2209,  -6575 },
+  {  -3336,  -1531,  -4313,  -5160 },
+  {  -2127,    128,  -4851,  -3692 },
+  {  -3321,    136,  -2067,  -5660 },
+  {  -5215,   1404,  -4374,  -4356 },
+  {  -2747,    400,  -6340,  -3691 },
+  {  -3926,   -599,  -5361,  -5006 },
+  {  -2875,  -2592,  -5143,  -4092 },
+  {  -4991,  -1958,  -5322,  -4891 },
+  {  -4965,  -1318,  -6652,  -5333 },
+  {  -4920,  -1691,  -3388,  -5561 },
+  {  -3644,  -3354,  -2688,  -5982 },
+  {  -5076,   -919,  -4563,  -2984 },
+  {  -6114,    250,  -3884,  -3915 },
+  {  -4014,    744,  -3973,  -1924 },
+  {  -5543,  -1041,  -5557,  -3847 },
+  {  -4711,  -1352,  -5649,  -2603 },
+  {  -3362,    775,  -5305,  -4879 },
+  {  -5001,    107,  -3554,  -2888 },
+  {  -6258,  -1651,  -6356,  -6566 },
+  {  -4529,    407,  -5003,  -3865 },
+  {  -5154,    550,  -5278,  -5465 },
+  {  -4195,   -467,  -1894,  -3129 },
+  {  -5022,   1127,  -3349,  -3314 },
+  {  -6075,   1250,  -4313,  -5641 },
+  {  -2677,  -2283,  -2312,  -5903 },
+  {  -4113,    193,  -1195,  -4833 },
+  {  -3940,  -1048,  -1389,  -5079 },
+  {  -3703,    917,  -4043,  -4451 },
+  {  -3366,  -4231,  -1534,  -5488 },
+  {  -3326,  -3583,  -2091,  -4903 },
+  {  -5144,   1254,  -2532,  -4949 },
+  {  -5982,   -870,  -2545,  -4555 },
+  {  -3925,   -157,  -5367,  -2281 },
+  {  -6419,   -746,  -5668,  -4371 },
+  {  -5787,    518,  -7096,  -5805 },
+  {  -4258,    954,  -6453,  -4321 },
+  {  -4771,   -695,  -4158,  -1639 },
+  {  -7078,   -760,  -5195,  -5877 },
+  {  -7348,     83,  -4101,  -4586 },
+  {  -2430,    184,  -2874,  -1679 },
+  {  -2284,  -3943,  -2924,  -5034 },
+  {  -1804,  -1785,  -3002,  -4710 },
+  {  -4399,  -2772,  -1815,  -4637 },
+  {  -6340,  -2626,  -2824,  -5191 },
+  {  -4998,  -5168,  -3480,   1905 },
+  {  -3958,  -5492,  -1599,   1579 },
+  {  -2471,  -3755,   -276,   3182 },
+  {  -3033,  -5779,  -1063,   1554 },
+  {  -2936,  -4829,  -1290,   2386 },
+  {  -1835,  -5073,  -3051,   1299 },
+  {  -1724,  -3771,  -3935,   2324 },
+  {  -5070,  -2550,  -3692,    768 },
+  {  -4326,  -5333,   -297,   1878 },
+  {  -3472,  -5619,  -3094,    992 },
+  {  -3027,  -4384,  -3038,   2265 },
+  {  -3201,  -5332,     67,   2200 },
+  {  -1681,  -4373,  -1947,   2461 },
+  {  -3221,  -3329,  -4238,   2564 },
+  {  -1262,  -2968,  -2915,   3227 },
+  {  -3419,  -1878,  -3373,   2110 },
+  {  -2244,  -5583,  -2012,   1288 },
+  {  -1971,  -5266,   -990,   1812 },
+  {  -2975,  -2778,   -452,   4063 },
+  {  -2198,  -1165,  -3298,   2965 },
+  {  -4782,  -4894,  -4767,    664 },
+  {  -6002,  -3950,  -2806,   2025 },
+  {  -3142,  -3162,  -2859,   3295 },
+  {  -3262,  -3340,  -4123,   1596 },
+  {  -4014,  -3918,  -1955,   3361 },
+  {  -1700,  -3463,  -1346,   3449 },
+  {  -4245,  -4445,  -4743,   1644 },
+  {  -4180,  -3969,   -401,   3281 },
+  {  -2782,  -5240,  -4117,   1156 },
+  {  -5744,  -4040,  -1439,   3470 },
+  {  -5063,  -4663,   -323,   3172 },
+  {  -4531,  -3319,   -844,   3988 },
+  {  -6226,  -5125,  -2064,   2976 },
+  {  -3115,  -3267,  -1531,   3898 },
+  {  -4628,  -4421,  -2864,   2808 },
+  {  -4559,  -2989,  -3442,   2024 },
+  {  -1775,  -4487,   -656,   2477 },
+  {  -2664,  -1865,  -1884,   4081 },
+  {  -1828,  -2575,  -3894,   3378 },
+  {  -6441,  -3677,  -2025,   1677 },
+  {  -4141,  -2156,  -1191,   3474 },
+  {  -4802,  -1623,  -1727,   2160 },
+  {  -5474,  -2745,  -1475,   2498 },
+  {  -3664,  -1056,  -1975,   2491 },
+  {  -4672,  -3062,  -2235,   2933 },
+  {  -4205,  -5960,  -2849,   1517 },
+  {  -4995,  -5708,  -1739,   1805 },
+  {  -4892,  -6080,  -4793,    872 },
+  {  -4270,  -4172,  -4263,   2185 },
+  {  -4687,  -1470,  -2905,   1023 },
+  {  -6446,  -5017,  -3919,   1000 },
+  {  -6046,  -5538,  -3943,   2006 },
+  {  -6028,  -3750,  -3953,    771 },
+  {  -5959,  -4582,  -5024,    824 },
+  {  -5818,  -2576,  -2249,   1326 },
+  {  -5659,  -5345,  -1119,   2500 },
+  {  -3346,  -4155,    606,   2749 },
+  {  -5680,  -4827,  -2501,   1838 },
+  {  -6193,  -2543,  -1295,    840 },
+  {  -6871,  -4925,  -3512,   1801 },
+  {  -5605,  -1788,  -1895,    779 },
+  {  -3922,  -5712,  -4644,    510 },
+  {  -4745,  -3869,  -4533,     99 },
+  {  -2984,  -4907,   -399,   1497 },
+  {   1847,   -478,   3061,  -5812 },
+  {   4450,  -1116,   3609,  -6570 },
+  {   3139,     99,   3007,  -5532 },
+  {   2590,  -3782,   3138,  -4770 },
+  {   1881,   1204,   5778,  -3404 },
+  {   3631,   2060,   5566,  -5038 },
+  {   3461,   1961,   5167,  -3800 },
+  {   2947,    273,   4536,  -4389 },
+  {   4453,  -1730,   5788,  -4370 },
+  {   4032,   1805,   2666,  -4534 },
+  {   3487,   -944,   2313,  -6028 },
+  {   1313,     34,   4210,  -4067 },
+  {   5632,  -1502,   5825,  -5855 },
+  {   7736,   -547,   4879,  -5476 },
+  {   4906,  -1512,   4760,  -5760 },
+  {   3843,    447,   1091,  -4958 },
+  {   2982,  -1135,   5442,  -4386 },
+  {   3579,    271,   3031,  -6770 },
+  {   3932,   -211,   4688,  -5507 },
+  {   4411,   1720,   2387,  -5584 },
+  {   5379,   -479,   4575,  -6280 },
+  {   3613,   -362,   2012,  -4885 },
+  {   3744,  -2013,   4493,  -5073 },
+  {   5693,    109,   4379,  -3362 },
+  {   5475,   -621,   5317,  -3985 },
+  {   6411,   -673,   5708,  -4752 },
+  {   4933,   -796,   7262,  -4290 },
+  {   2804,    444,   6276,  -3655 },
+  {   4120,   -517,   6078,  -4531 },
+  {   5119,    841,   3486,  -3910 },
+  {   4738,   1539,   3525,  -2970 },
+  {   5086,    370,   5895,  -5640 },
+  {   4235,   2716,   4589,  -5044 },
+  {   3691,    682,   6199,  -4700 },
+  {   6111,   -570,   6271,  -6528 },
+  {   2611,   1277,   3756,  -4802 },
+  {   4395,    970,   3807,  -5879 },
+  {   5225,   2299,   3242,  -4333 },
+  {   5144,   1778,   4946,  -5545 },
+  {   2989,  -3016,   3247,  -5495 },
+  {   2983,    920,   2071,  -6059 },
+  {   5270,   -903,   4434,  -2350 },
+  {   6415,   -585,   3970,  -3554 },
+  {   3866,   -197,   5216,  -2884 },
+  {   3767,  -1298,   6702,  -3315 },
+  {   6299,   2620,   5284,  -6824 },
+  {   6654,    646,   3653,  -4927 },
+  {   4770,   3047,   5160,  -6287 },
+  {   5364,    434,   2919,  -5207 },
+  {   2998,   1344,   4801,  -2456 },
+  {   3896,   1013,   3773,  -1864 },
+  {   2115,    655,   2999,  -6344 },
+  {   5170,   -981,   2849,  -4464 },
+  {   2735,  -2159,   2717,  -5776 },
+  {   2430,  -1952,   4392,  -4559 },
+  {   6143,  -1180,   3659,  -4746 },
+  {   4978,  -1483,   1726,  -4875 },
+  {   3486,  -2383,   3306,  -4301 },
+  {   1434,  -1372,   4171,  -4770 },
+  {   3354,  -2627,   1525,  -5093 },
+  {   6790,   2386,   3995,  -5909 },
+  {   1475,  -2674,   3451,  -4204 },
+  {   1999,  -3494,   3693,  -5556 },
+  {   4764,  -2848,   2856,  -5589 },
+  {  -3677,   5131,   2827,  -2934 },
+  {  -2844,   7078,   2852,  -3580 },
+  {  -3902,   6434,   4118,  -1911 },
+  {  -1769,   7530,   3492,  -3541 },
+  {  -1937,   5679,   -447,  -1127 },
+  {  -2456,   4680,   4196,  -2407 },
+  {  -2778,   8241,   1698,  -4288 },
+  {  -2876,   6104,   5182,  -2387 },
+  {  -2802,   7341,   4463,  -2938 },
+  {  -1025,   6267,   4752,  -3201 },
+  {  -2349,   5413,   2041,  -3794 },
+  {  -2252,   8225,   2856,  -4269 },
+  {  -1465,   4967,   4976,  -2500 },
+  {   -636,   7565,   3517,  -4233 },
+  {  -1905,   5618,   3904,  -2942 },
+  {   -302,   6816,   3343,  -3316 },
+  {  -2210,   4156,   2817,  -3511 },
+  {   -717,   6568,   1863,  -2951 },
+  {  -3873,   5682,   2164,   -575 },
+  {  -2878,   5835,    440,  -2597 },
+  {  -3228,   7701,   2610,  -2514 },
+  {  -3608,   8888,   3377,  -2468 },
+  {  -2582,   9717,   2519,  -3126 },
+  {  -5238,   6202,   2866,  -2831 },
+  {  -3428,   7370,   3056,   -335 },
+  {  -1681,   8836,   1210,  -2010 },
+  {  -3276,   6724,   1156,  -3930 },
+  {   -894,   8149,    827,  -1258 },
+  {  -2965,   8631,   2549,  -1320 },
+  {  -3961,   6902,   3581,     55 },
+  {  -1894,   7745,   1750,   -841 },
+  {   -821,   6844,    850,   -676 },
+  {   -608,   6948,     -4,  -1376 },
+  {    615,   6524,   1089,  -1147 },
+  {  -2972,   5668,   1091,   -489 },
+  {   -157,   4649,   2904,   -413 },
+  {    673,   5121,   1498,    -66 },
+  {   -390,   5902,   1611,   -245 },
+  {  -2349,   5478,   4772,  -1320 },
+  {     88,   6798,   1972,  -1859 },
+  {  -1213,   5120,   2991,    200 },
+  {  -2347,   6040,   2839,    376 },
+  {   -578,   5976,   3364,  -1796 },
+  {  -1391,   5872,   3002,   -965 },
+  {   -564,   4496,   3946,  -1186 },
+  {  -2299,   6386,   3135,  -2176 },
+  {  -2131,   5641,   2011,   1223 },
+  {   -772,   5807,   1124,    895 },
+  {  -2837,   6758,   2297,   -740 },
+  {  -3091,   6298,   1415,  -2126 },
+  {  -4197,   6036,   1843,  -3022 },
+  {    -41,   6459,     92,    344 },
+  {  -2241,   6860,   2095,  -4396 },
+  {  -1931,   7088,   2117,  -2135 },
+  {  -2375,   4422,   1688,  -3169 },
+  {  -1742,   6674,   1538,   -119 },
+  {  -4818,   7749,   4192,  -1577 },
+  {  -2004,   5672,    193,   -430 },
+  {  -3825,   6042,   2128,  -1898 },
+  {  -1108,   8033,   2119,  -3013 },
+  {  -2370,   5453,   1721,    266 },
+  {  -1570,   7134,    614,  -2638 },
+  {  -1519,   8752,   3503,  -4330 },
+  {  -2050,   3845,   2907,  -1126 },
+  {   5085,   4412,   -335,  -1923 },
+  {   3618,   1423,   -613,  -4012 },
+  {   4481,   3729,    589,  -4631 },
+  {   4270,   3216,  -1763,  -3168 },
+  {   4241,   1796,  -1701,  -2796 },
+  {   4787,   2338,   -487,  -3639 },
+  {   2915,   3429,   -621,  -4753 },
+  {   5175,   1660,  -1265,  -3223 },
+  {   4280,   4057,   -684,  -4079 },
+  {   4980,   4419,  -1455,  -2719 },
+  {   5436,   2464,    387,  -4197 },
+  {   4507,   4018,   1121,  -3314 },
+  {   6020,   2401,   -413,  -3201 },
+  {   4200,   3789,   -333,  -2813 },
+  {   5229,   2493,  -1194,  -1878 },
+  {   5851,   2695,   -492,  -2292 },
+  {   5743,   3288,   -697,  -1221 },
+  {   5692,   2612,    979,  -2227 },
+  {   5085,   2067,   1046,  -1214 },
+  {   3163,   2240,  -2098,  -3435 },
+  {   5228,   1898,    145,  -2397 },
+  {   5860,   3976,   -418,  -2872 },
+  {   6008,   3399,   1027,  -3506 },
+  {   4126,   2035,   1865,   -893 },
+  {   5375,   3596,    511,  -2362 },
+  {   1937,   1493,   -852,   -122 },
+  {   3473,   4849,    547,  -2603 },
+  {   4631,   2977,   1141,  -1768 },
+  {   6149,   3050,    -71,  -1886 },
+  {   4069,   4353,   -289,  -1429 },
+  {   2884,   1225,  -1388,    365 },
+  {   5485,   2518,   -235,   -571 },
+  {   1216,   4375,   1443,    398 },
+  {   4988,   3106,    107,  -1435 },
+  {   4511,   2801,    307,   -444 },
+  {   3235,   4386,    327,   -676 },
+  {   2055,   3708,   1657,   -305 },
+  {   5839,   2374,    290,  -1385 },
+  {   5110,   3305,   1936,  -4206 },
+  {   6416,   2920,    338,  -2736 },
+  {   3350,   2824,  -1269,  -3881 },
+  {   4840,   1815,    464,    186 },
+  {   2399,   3332,    238,   1238 },
+  {   3516,   1363,   1582,    688 },
+  {   3582,   1874,    154,  -4770 },
+  {   3261,   2878,    886,    283 },
+  {   3877,   2658,   -327,    884 },
+  {   4151,   3436,   2173,  -2923 },
+  {   3592,   3674,   1281,  -1295 },
+  {   4561,   3730,  -1114,  -1747 },
+  {   4595,   3625,   -558,   -575 },
+  {   2577,   2348,   2267,    120 },
+  {   5242,   3299,     32,  -3412 },
+  {   4264,   3637,    709,  -2320 },
+  {   6556,   3570,   -838,  -2472 },
+  {   5745,   4014,   -940,  -1973 },
+  {   5629,   4475,    477,  -3328 },
+  {   5269,   3199,   1682,  -3085 },
+  {   4432,   2416,   1145,  -3299 },
+  {   4465,   2505,   2162,  -2186 },
+  {   4643,   4941,    -88,  -2885 },
+  {   4568,   5231,    552,  -3915 },
+  {   5667,   3075,  -1406,  -2963 },
+  {   5418,   5259,   -771,  -2818 },
+  {   -256,  -7875,    511,   -471 },
+  {  -1813,  -7971,   -424,   -396 },
+  {   -306,  -7006,    862,    282 },
+  {  -2306,  -6422,  -1440,    508 },
+  {   -245,  -6787,    375,   -100 },
+  {  -1309,  -6065,    -20,    779 },
+  {  -1656,  -6047,   -641,   1307 },
+  {  -1496,  -6522,    964,    726 },
+  {  -2291,  -6588,   -202,    795 },
+  {   -762,  -7522,   1454,   -558 },
+  {  -2270,  -7004,   -834,   -580 },
+  {  -1139,  -7078,    259,    362 },
+  {  -2535,  -7568,  -1040,     49 },
+  {  -3786,  -7280,    934,   -476 },
+  {  -3336,  -6368,    606,   1056 },
+  {  -3602,  -6924,     52,    714 },
+  {  -2278,  -6550,   1674,    204 },
+  {  -2855,  -5765,    930,   1530 },
+  {  -2889,  -7325,   -215,    305 },
+  {  -2749,  -6080,   -237,   1452 },
+  {   -985,  -6667,   1577,    400 },
+  {  -2036,  -6083,    380,   1267 },
+  {  -2077,  -7460,    380,    -30 },
+  {  -1775,  -7175,   1540,   -386 },
+  {  -3065,  -6927,    989,    168 },
+  {  -2836,  -7602,    117,  -3392 },
+  {  -1058,  -6396,    593,  -3078 },
+  {   -844,  -6062,    999,   -236 },
+  {  -3261,  -6951,   1491,   -720 },
+  {  -2186,  -8484,     75,  -1287 },
+  {  -2882,  -7756,    456,   -510 },
+  {  -1800,  -6879,    960,  -1183 },
+  {  -2554,  -7241,   1614,  -1474 },
+  {  -2608,  -5305,    392,    851 },
+  {  -2973,  -6562,   -859,    858 },
+  {  -2640,  -5989,   1031,   -416 },
+  {   -977,  -8366,    705,  -1434 },
+  {  -1213,  -7409,    -77,  -1390 },
+  {  -1335,  -6657,   2125,   -123 },
+  {  -2544,  -6862,   1852,   -737 },
+  {  -3235,  -6422,   1752,   -103 },
+  {  -1300,  -7557,    939,   -348 },
+  {  -3476,  -7579,    202,   -109 },
+  {  -2482,  -6572,    753,    619 },
+  {  -2554,  -8136,   -648,   -429 },
+  {  -1012,  -7870,     -3,   -421 },
+  {  -3604,  -6247,     32,  -3102 },
+  {  -1486,  -7271,   2013,  -1021 },
+  {   -578,  -6799,   -523,    405 },
+  {  -2841,  -5948,   1644,    911 },
+  {  -2411,  -7473,   1084,   -484 },
+  {  -2238,  -6033,    294,  -1059 },
+  {  -3459,  -6470,   -201,   -790 },
+  {  -2027,  -6009,   1833,    805 },
+  {  -1433,  -8047,   1531,  -1754 },
+  {  -3258,  -7884,    763,  -1422 },
+  {  -1544,  -6928,   -729,    478 },
+  {  -2314,  -8415,     74,  -3757 },
+  {  -3201,  -5684,     95,  -2214 },
+  {  -2423,  -8694,    725,  -3631 },
+  {  -3545,  -7071,   1162,  -1798 },
+  {   -294,  -9662,    403,  -2274 },
+  {  -2290,  -5460,   1196,    402 },
+  {  -1603,  -6713,    903,  -2363 },
+  {   4121,   2491,  -3142,  -2482 },
+  {   4500,   3305,  -3671,  -1567 },
+  {   5973,   3172,  -1348,   -534 },
+  {   4830,   3379,  -1549,    643 },
+  {   5214,   3938,  -2641,  -2302 },
+  {   4639,   4826,  -5532,   -847 },
+  {   5639,   2731,  -2170,   -963 },
+  {   6084,   3487,  -3525,  -1346 },
+  {   5971,   3154,  -2190,  -2316 },
+  {   5618,   4865,  -6927,    116 },
+  {   5345,   3568,  -7391,    709 },
+  {   5429,   5078,  -3811,  -1524 },
+  {   6960,   2037,  -3515,  -1096 },
+  {   7092,   2531,  -4557,   -588 },
+  {   6061,   4247,  -5651,   -478 },
+  {   4595,   3684,  -4907,   -827 },
+  {   7497,   3213,  -3048,   -424 },
+  {   5996,   2137,  -3098,  -1745 },
+  {   6198,   5199,  -2223,  -2274 },
+  {   6888,   2851,  -2768,  -1675 },
+  {   6114,   4210,  -2316,   -954 },
+  {   7127,   4242,  -3041,  -1408 },
+  {   6126,   3668,  -1517,  -1427 },
+  {   6245,   6129,  -4225,  -1186 },
+  {   6816,   3213,  -2101,   -964 },
+  {   5345,   5276,  -2643,   -847 },
+  {   6592,   4665,  -4338,    484 },
+  {   6746,   3751,  -3443,    124 },
+  {   5453,   1980,  -2738,   2606 },
+  {   4662,   2179,  -4226,  -1059 },
+  {   5571,   3208,  -3554,    174 },
+  {   5256,   4447,  -1815,  -1481 },
+  {   5400,   2570,  -1210,    235 },
+  {   7056,   2549,  -2674,    318 },
+  {   4574,   4340,  -2892,   -130 },
+  {   6203,   4587,  -3273,   -305 },
+  {   5103,   1925,  -2715,  -2137 },
+  {   3905,   4296,  -1700,    247 },
+  {   4421,   4605,  -3299,    811 },
+  {   5671,   1273,  -3870,   -924 },
+  {   5486,   1805,  -4901,    133 },
+  {   6437,   2578,  -1828,   -106 },
+  {   5530,   5253,  -5058,   1223 },
+  {   4816,   2025,  -1215,   1443 },
+  {   3457,   3525,  -2456,   3217 },
+  {   3316,   2595,  -1108,   2459 },
+  {   3068,   3810,  -2207,   1926 },
+  {   6351,   5436,  -6470,    600 },
+  {   6324,   4240,  -5365,   2416 },
+  {   4851,   4774,  -4075,   1878 },
+  {   4900,   3679,  -5198,   1078 },
+  {   8347,   3633,  -4565,   -171 },
+  {   5244,   5718,  -3853,    173 },
+  {   3960,   3492,  -2939,   2105 },
+  {   6070,   3473,  -2351,    161 },
+  {   8228,   3034,  -3360,   -901 },
+  {   7006,   3985,  -1940,  -1926 },
+  {   7123,   4681,  -4301,   -878 },
+  {   5122,   4097,  -1851,   -449 },
+  {   6200,   2060,  -2251,   1049 },
+  {   7106,   3844,  -7209,   2625 },
+  {   7108,   3370,  -6734,    533 },
+  {   6859,   2849,  -3992,   1360 },
+  {   5458,   2278,  -3253,   1131 },
+  {  -1072,  -2109,   4783,  -1073 },
+  {   -319,  -2604,   4257,  -2418 },
+  {   2466,   1300,   3476,   -314 },
+  {   2847,  -1502,   5296,   -141 },
+  {   1667,  -1273,   5559,  -2725 },
+  {   2877,  -3402,   6434,    204 },
+  {     53,  -2637,   5275,  -1181 },
+  {   1091,  -2215,   5803,  -1549 },
+  {   2397,   -922,   4327,   1182 },
+  {    219,  -3747,   4647,  -1564 },
+  {    -29,  -2705,   4812,   1277 },
+  {   1499,  -2608,   5648,   1407 },
+  {   2139,  -2399,   4202,   2791 },
+  {   -426,  -2064,   5528,    151 },
+  {   2560,  -2803,   6179,  -2806 },
+  {   4537,  -2479,   3797,   1095 },
+  {    888,  -3357,   5341,   -415 },
+  {   4460,  -1814,   5388,  -1227 },
+  {   3920,  -3268,   6364,   -703 },
+  {   3343,  -4698,   4410,    784 },
+  {    309,  -1897,   6306,   1223 },
+  {    958,  -3318,   4254,  -3167 },
+  {    -99,   1596,   6018,  -1983 },
+  {   -429,   -853,   6407,    878 },
+  {   1170,  -1322,   6290,   -417 },
+  {   2288,   -505,   6303,  -1999 },
+  {   3312,  -1674,   6749,  -2494 },
+  {   -415,  -3401,   4721,   -371 },
+  {   -189,  -1210,   4844,  -2002 },
+  {    888,  -4142,   4377,    130 },
+  {   2469,  -4381,   5398,  -2492 },
+  {   2879,  -2912,   5094,  -2598 },
+  {   -717,   -617,   5650,   -685 },
+  {   1470,  -3863,   5352,  -1684 },
+  {   3935,    -96,   3823,   -730 },
+  {   3769,   -430,   3168,    694 },
+  {   2556,    385,   3539,    512 },
+  {     77,  -1415,   5111,   2655 },
+  {   2724,  -2158,   6715,   -822 },
+  {   1832,   1001,   5385,  -1900 },
+  {    900,   2198,   4464,   -559 },
+  {    441,     69,   5921,  -1743 },
+  {  -1161,    738,   6732,   -308 },
+  {    257,   2035,   4091,    736 },
+  {   1607,   1288,   4355,    -23 },
+  {    -13,   1316,   4180,   1672 },
+  {   1511,   1336,   3057,   1435 },
+  {   2189,  -3813,   4530,    939 },
+  {   3632,   -706,   2646,   1375 },
+  {   4266,  -3761,   4241,   1077 },
+  {   3101,   -427,   5273,  -1202 },
+  {   2293,    276,   4810,   -313 },
+  {   3430,  -1851,   3101,   2045 },
+  {   3453,  -2979,   5142,    942 },
+  {   1683,  -3281,   4802,   2002 },
+  {   3954,  -4715,   5611,    578 },
+  {   1272,   -155,   5085,    454 },
+  {    128,   -194,   5095,   1409 },
+  {    820,    880,   5797,  -2658 },
+  {  -1095,    656,   5774,   1095 },
+  {    813,  -1669,   4320,  -3251 },
+  {   -119,    518,   6372,   -651 },
+  {   2922,  -4299,   6115,   -877 },
+  {   4205,  -4273,   4004,   2642 },
+  {  -1211,  -3892,    224,   3127 },
+  {    -34,  -4371,   1321,   2318 },
+  {     77,  -6326,   1201,    828 },
+  {   3995,  -3775,   1958,   3233 },
+  {    178,  -3301,   1985,   3318 },
+  {   2330,  -3801,   1033,   3195 },
+  {   1413,  -5536,    826,   1709 },
+  {   2468,  -3499,   3653,   3631 },
+  {    741,  -4617,   1723,   2008 },
+  {   1246,  -3043,   2978,   3949 },
+  {   -343,  -4308,   2258,   2189 },
+  {   -682,  -4640,    454,   2272 },
+  {   1236,  -4829,   2491,   1642 },
+  {   -512,  -3766,   1182,   3052 },
+  {    119,  -3939,   3712,    971 },
+  {  -1145,  -4624,   1360,   2281 },
+  {    101,  -4746,   2866,   1255 },
+  {  -1500,  -5455,    539,   1637 },
+  {   -969,  -5909,   1414,   1128 },
+  {  -1261,  -4939,   -231,   2022 },
+  {   -226,  -5345,   1207,    705 },
+  {   2712,  -5109,   3205,   1866 },
+  {   -476,  -5913,    273,   1208 },
+  {  -2039,  -4464,    624,   2545 },
+  {  -2351,  -3930,   2019,   2673 },
+  {  -2675,  -4849,   1522,   1990 },
+  {  -1524,  -3461,   1446,   3204 },
+  {    477,  -5314,   1710,   1577 },
+  {    656,  -3729,   2346,   2511 },
+  {    550,  -5917,   1975,   1040 },
+  {   1728,  -4704,   3067,   1058 },
+  {     -9,  -5247,    506,   1760 },
+  {   -574,  -5135,   1675,   1672 },
+  {   2129,  -3781,   3444,   2313 },
+  {   1144,  -4439,   2214,   2529 },
+  {   1292,  -4160,   3185,   1833 },
+  {   2445,  -3262,   2534,   3227 },
+  {   2266,  -4401,   2023,   2400 },
+  {   -587,  -3602,   3408,   2067 },
+  {   -885,  -4951,   3228,   1174 },
+  {   -728,  -2711,   2807,   3552 },
+  {   1019,  -3043,   3195,   2954 },
+  {   1888,  -4615,   1140,   2454 },
+  {    660,  -5616,    754,    800 },
+  {  -1975,  -5371,   1649,   1585 },
+  {  -1544,  -5436,   2422,   1081 },
+  {   -422,  -5882,   2390,    750 },
+  {   1336,  -5557,   2441,   1230 },
+  {    136,  -4001,    267,   2854 },
+  {   -522,  -3289,   2226,   2728 },
+  {   -971,  -4580,   2471,    708 },
+  {    704,  -5306,   3300,   1001 },
+  {    325,  -3464,   3555,   2398 },
+  {    794,  -3686,    848,   3169 },
+  {    660,  -3017,   4584,   3242 },
+  {  -1486,  -3978,   2170,   1644 },
+  {  -1615,  -4650,   2688,   1844 },
+  {    750,  -4578,    538,   2239 },
+  {   1668,  -5849,   1455,   1031 },
+  {   3486,  -4681,   2030,   2183 },
+  {   2642,  -5429,   1696,   1761 },
+  {   4491,  -4502,   3538,   2767 },
+  {   3545,  -4528,   3514,   2982 },
+  {   3269,  -3676,   2758,   3966 },
+  {   5572,   1146,    209,  -3379 },
+  {   7459,   1053,    593,  -1896 },
+  {   4480,    200,   -310,  -4259 },
+  {   5577,   -939,    242,  -3992 },
+  {   8142,    442,   1257,  -3083 },
+  {   5442,   1261,   1424,  -3236 },
+  {   6260,   -183,   3125,  -2532 },
+  {   7179,    889,   1618,  -2548 },
+  {   6416,    932,   2379,  -2487 },
+  {   7094,   2560,    961,  -3392 },
+  {   7322,    463,   2732,  -3735 },
+  {   6632,   1577,   1912,  -3272 },
+  {   6312,   1349,   3028,  -3460 },
+  {   6105,    386,   1213,   -977 },
+  {   5478,   1158,   1114,   -486 },
+  {   6493,    410,   1686,  -2180 },
+  {   6378,   1881,   1333,  -2240 },
+  {   5711,    812,   1958,  -1300 },
+  {   6844,    877,    730,  -1189 },
+  {   6824,   -245,   2249,  -2000 },
+  {   7515,   1521,   1251,  -3058 },
+  {   6697,   1051,   1300,  -1749 },
+  {   6476,   1425,    811,  -2773 },
+  {   7350,    465,    -76,  -2849 },
+  {   6975,   2095,    567,  -2492 },
+  {   4691,   1736,   2660,  -2289 },
+  {   7837,   1456,    340,  -2767 },
+  {   7930,    507,    838,  -2074 },
+  {   6106,   1502,    766,  -1110 },
+  {   4891,   -659,    835,  -3954 },
+  {   7250,    141,   1369,  -1523 },
+  {   7651,     67,   1651,  -2298 },
+  {   7364,   -305,    601,  -3132 },
+  {   7179,    193,   2491,  -2871 },
+  {   6504,   -272,   2167,  -1322 },
+  {   4456,    983,   2300,   -421 },
+  {   4817,    457,   1695,    371 },
+  {   6914,    555,    850,  -3159 },
+  {   5904,   1030,    202,  -1959 },
+  {   6258,    880,   2233,  -4503 },
+  {   6029,     10,   2130,  -3600 },
+  {   6449,    985,   1129,  -3963 },
+  {   6616,    -18,   -111,  -3285 },
+  {   4496,    775,    817,  -4276 },
+  {   6134,   2338,   1470,  -2973 },
+  {   6911,    152,    430,  -1946 },
+  {   4053,    991,   3218,  -1193 },
+  {   5435,   1285,   3124,  -2412 },
+  {   5507,   1836,   1935,  -1988 },
+  {   5240,    689,   2189,  -2670 },
+  {   6638,   1719,    606,  -1799 },
+  {   5556,   -180,    129,  -2595 },
+  {   5644,   1918,   1281,  -4316 },
+  {   6410,   1088,   -282,  -3117 },
+  {   6503,   1841,    312,  -3514 },
+  {   6947,     20,   1358,  -3886 },
+  {   5464,   2109,   2398,  -3194 },
+  {   5616,   -407,   2140,   -498 },
+  {   6121,   2707,   2379,  -4096 },
+  {   7303,   1846,   2266,  -4095 },
+  {   5444,    470,   2718,  -1553 },
+  {   5817,   -645,   3285,  -1349 },
+  {   5625,   1427,   1103,  -1991 },
+  {   6041,   -806,   1196,  -2943 },
+  {   3050,  -5722,   4070,  -5460 },
+  {   3420,  -4386,   4078,  -5155 },
+  {   6020,  -3982,   7268,  -2689 },
+  {   7502,  -4317,   7894,  -3973 },
+  {   4156,  -3558,   5247,  -4316 },
+  {   4725,  -4401,   7290,  -1540 },
+  {   6688,  -5122,   8216,  -3210 },
+  {   9176,  -6576,   9276,  -4963 },
+  {   8706,  -5708,   7987,  -4621 },
+  {   7060,  -3535,   6532,  -3308 },
+  {   5600,  -2719,   5363,  -1568 },
+  {   4661,  -2803,   6263,  -4716 },
+  {   3673,  -3636,   6147,  -3433 },
+  {   5305,  -2585,   6073,  -2638 },
+  {   7614,  -1962,   6079,  -5266 },
+  {   6760,  -3366,   7382,  -4322 },
+  {   6385,  -3883,   4797,  -1353 },
+  {   8182,  -5120,   4298,  -4641 },
+  {   9130,  -6198,   4975,  -3063 },
+  {   7421,  -5436,   5576,  -3713 },
+  {   3483,  -4898,   5443,  -2745 },
+  {   4907,  -5643,   6390,  -4105 },
+  {   8119,  -7008,   7992,  -6764 },
+  {   6528,  -6122,   6967,  -5590 },
+  {   5890,  -4190,   6624,  -5688 },
+  {   6815,  -7934,   7275,  -5456 },
+  {   5434,  -4306,   5169,  -5378 },
+  {   4364,  -6436,   5376,  -2604 },
+  {   8152,  -3404,   5913,  -5048 },
+  {   7983,  -4863,   4262,  -2461 },
+  {   8023,  -6188,   6238,  -5062 },
+  {   6753,  -3692,   3935,  -3723 },
+  {   6826,  -4760,   3284,  -4051 },
+  {   7224,  -7423,   4492,  -3875 },
+  {   6904,  -2590,   6587,  -6248 },
+  {   6106,  -1944,   7345,  -5506 },
+  {   4956,  -2990,   7808,  -3146 },
+  {   6908,  -6885,   5949,  -1288 },
+  {   7162,  -6058,   3419,  -3401 },
+  {   7015,  -7080,   6907,  -3018 },
+  {   6971,  -6832,   5646,  -3273 },
+  {   8014,  -5546,   5471,  -1544 },
+  {   6792,  -2220,   5105,  -2879 },
+  {   8494,  -3974,   4408,  -3999 },
+  {   9591,  -4866,   6027,  -4558 },
+  {   5264,  -5161,   6101,   -738 },
+  {   5803,  -6141,   5197,  -5231 },
+  {   4657,  -6822,   3232,  -5189 },
+  {   4791,  -5135,   3809,  -4665 },
+  {   6108,  -5103,   2379,  -3873 },
+  {   4680,  -3909,   3234,  -5093 },
+  {   5802,  -3853,   3795,  -4984 },
+  {   4360,  -7483,   4802,  -3877 },
+  {   5429,  -7517,   5911,  -3717 },
+  {   6866,  -2280,   4880,  -4634 },
+  {  10131,  -4628,   4414,  -4092 },
+  {  10811,  -5189,   7746,  -5337 },
+  {   5663,  -8941,   5287,  -5680 },
+  {   8023,  -5991,   7403,  -2796 },
+  {   9669,  -6919,   6525,  -4932 },
+  {   7275,  -3796,   4962,  -2547 },
+  {   8848,  -4806,   5677,  -3080 },
+  {   8128,  -4308,   7749,  -6569 },
+  {   4032,  -5196,   2282,  -6239 },
+  {   6593,    700,   -229,    304 },
+  {   8260,    539,    -66,  -1259 },
+  {   6605,    176,   -814,   -109 },
+  {   8057,      0,     -1,   -136 },
+  {   7382,    -38,   -484,  -1129 },
+  {   8373,   -929,    682,   -454 },
+  {   7674,    690,  -1278,    546 },
+  {   7326,   -517,    406,  -1283 },
+  {   7612,  -1715,  -1167,   1175 },
+  {   8590,    441,   -782,   -710 },
+  {   8572,  -1202,   -291,    260 },
+  {   7308,   -147,  -1785,    414 },
+  {   6787,   -353,   -672,    934 },
+  {   5177,   -133,    179,     82 },
+  {   4161,    -34,    447,   1497 },
+  {   5997,   -902,   1533,   -121 },
+  {   5727,   -871,  -1370,    945 },
+  {   8386,   -252,    293,   -823 },
+  {   6573,  -1354,    682,    616 },
+  {   7650,  -2096,    725,    457 },
+  {   8122,     78,    636,  -1400 },
+  {   8421,    428,  -1620,    131 },
+  {   7341,  -1292,   -717,    186 },
+  {   7998,    -49,   -720,    266 },
+  {   5987,   -351,    669,    844 },
+  {   7314,  -1620,    250,   -603 },
+  {   7219,  -1562,   -572,   1994 },
+  {   8682,   -358,   -290,   -388 },
+  {   5810,    155,   -178,   1199 },
+  {   7246,    -12,   1042,   -786 },
+  {   7357,   -923,   1468,   -475 },
+  {   7801,    621,   -212,   -724 },
+  {   5346,   -514,   1210,   1356 },
+  {   8459,     36,   -127,   -779 },
+  {   6878,  -2429,    854,   1750 },
+  {   7280,  -1401,  -1353,   2845 },
+  {   7579,  -2148,  -1463,   2087 },
+  {   6637,    946,   -872,    750 },
+  {   4807,  -1100,   1289,   2602 },
+  {   4495,    219,   1551,   1128 },
+  {   7639,    506,    446,  -1107 },
+  {   6359,    188,   1009,   -115 },
+  {   6641,  -1820,   1655,    723 },
+  {   5394,  -2382,   1604,   2542 },
+  {   6021,  -2644,   2396,   1407 },
+  {   4698,    882,    245,   1525 },
+  {   8103,    573,   -798,   -349 },
+  {   8045,   -519,    997,  -1092 },
+  {   7571,   -122,    227,   -338 },
+  {   5347,  -1200,    630,   1718 },
+  {   7070,    790,    218,   -544 },
+  {   7440,    728,   -527,    -20 },
+  {   6402,   -355,    197,   -736 },
+  {   4031,    771,    866,   1895 },
+  {   6009,    896,    445,    -31 },
+  {   5160,   1098,   -856,   1784 },
+  {   7980,   -886,  -1293,   1396 },
+  {   6318,  -1361,   2423,    252 },
+  {   7547,   -699,    133,    506 },
+  {   8562,  -2344,    940,    264 },
+  {   5890,   1187,  -1425,   2194 },
+  {   6558,   -645,  -1311,   2621 },
+  {   4634,  -1671,   2075,   1623 },
+  {   5614,    105,   -816,   2376 },
+  {   6646,   1558,  -1365,    630 },
+  {   6998,   1150,  -2117,   -990 },
+  {   6555,   2311,  -1093,  -1783 },
+  {   6682,   1430,  -2391,  -1940 },
+  {   7861,   1555,  -2977,  -1188 },
+  {   6745,   1723,   -459,  -2085 },
+  {   7504,   1229,  -1666,  -2060 },
+  {   7937,    671,  -2128,  -1529 },
+  {   7139,    991,   -735,  -2632 },
+  {   6867,   1592,  -1303,  -2324 },
+  {   6401,   2230,  -1732,  -2508 },
+  {   7201,   2184,  -2169,  -1988 },
+  {   6636,   2190,   -995,  -2840 },
+  {   7620,   2306,  -2089,   -651 },
+  {   7584,   1875,  -1438,   -631 },
+  {   9214,   1561,  -2464,  -1139 },
+  {   6154,   1318,  -1237,  -2917 },
+  {   7917,   2847,  -1797,  -1599 },
+  {   8309,   2029,  -2555,   -465 },
+  {   8204,   1282,   -584,  -2405 },
+  {   8440,   1035,  -1147,  -1137 },
+  {   7107,   1858,    -60,  -1568 },
+  {   6781,   2912,   -873,  -1463 },
+  {   7603,   1316,   -319,  -1249 },
+  {   7833,   1335,    -78,  -1849 },
+  {   7930,   1141,  -1016,   -695 },
+  {   7883,   1610,  -1017,  -1314 },
+  {   8069,   1409,  -1811,   -196 },
+  {   8319,   1031,   -582,  -1590 },
+  {   5948,   1537,  -2153,  -2373 },
+  {   8684,   1171,  -1871,   -850 },
+  {   8357,   2484,  -2411,  -1292 },
+  {   6516,   2092,   -193,  -1167 },
+  {   6112,   1697,     22,   -525 },
+  {   7161,    703,   -602,  -1879 },
+  {   6047,   2351,   -807,   -219 },
+  {   8072,   1854,  -1817,  -1553 },
+  {   6956,   1304,     76,  -1011 },
+  {   6607,   1481,   -544,   -162 },
+  {   6958,   2541,   -265,  -1938 },
+  {   6416,   2514,   -777,   -850 },
+  {   7272,   2110,   -899,  -1171 },
+  {   7741,   2153,   -283,  -2614 },
+  {   6482,   2041,  -1758,  -1221 },
+  {   6762,    940,  -1862,  -2281 },
+  {   5610,   1194,  -1691,  -1561 },
+  {   7833,   2164,   -823,  -1952 },
+  {   5460,   1438,   -848,   1189 },
+  {   6011,   1377,   -771,  -1557 },
+  {   7679,    544,  -1134,  -2214 },
+  {   7209,   1292,  -2714,  -1564 },
+  {   5567,   1200,   -404,   -169 },
+  {   5853,   1461,  -1465,   -518 },
+  {   6782,    689,   -844,   -860 },
+  {   7330,   1337,  -1152,    -71 },
+  {   7189,   1506,   -653,   -685 },
+  {   6860,   2116,  -1403,   -240 },
+  {   8804,   1516,  -1391,  -1760 },
+  {   7210,   2689,  -1498,   -989 },
+  {   7030,   3022,  -1441,  -2083 },
+  {   5649,   1836,   -407,    525 },
+  {   7451,   3099,   -717,  -2464 },
+  {   7384,   1656,  -2007,    398 },
+  {   6504,    707,  -1919,   -134 },
+  {  -1851,   3639,  -2279,   -695 },
+  {  -4037,   1644,    -77,   1329 },
+  {  -4025,   1960,  -1565,   -567 },
+  {  -3430,   2495,   -795,    368 },
+  {  -4771,   2480,    993,    756 },
+  {  -3431,   2058,  -2539,   -971 },
+  {  -3802,   3418,    380,    217 },
+  {  -3074,   3350,  -1652,  -1056 },
+  {  -3705,    326,  -1650,   1535 },
+  {  -3122,   1281,  -1192,   1607 },
+  {  -4601,   1367,   -968,     53 },
+  {  -3808,    958,     44,   2560 },
+  {  -2079,   2530,  -1485,   1166 },
+  {  -3707,    343,  -2889,    180 },
+  {  -5249,   1431,    -31,    688 },
+  {  -4990,    125,   -704,   1270 },
+  {  -2771,   1334,  -2446,    746 },
+  {  -2292,    994,  -1527,   2630 },
+  {  -1261,   3070,  -2519,    268 },
+  {  -2544,   3890,  -1057,   -552 },
+  {  -4421,    255,  -1980,    530 },
+  {  -2951,    454,    -13,   3643 },
+  {  -2262,   1815,   -370,   2880 },
+  {  -2383,   3657,   -649,    576 },
+  {  -3541,   -161,  -1389,   2550 },
+  {  -4241,   1575,   1325,   2561 },
+  {  -2767,   4037,   1221,   1578 },
+  {  -3748,   2697,   1148,   1801 },
+  {  -4686,   2385,   -220,      0 },
+  {  -1531,   1645,  -2751,   1327 },
+  {    -45,   4032,   -799,   2298 },
+  {  -2915,   2280,    709,   2495 },
+  {  -1199,   3278,   -406,   2346 },
+  {  -2471,    116,  -2706,   2060 },
+  {  -2440,   2173,  -2894,   -344 },
+  {  -3375,   2287,   1781,   3226 },
+  {  -2153,   3568,   1827,   2918 },
+  {   -862,   2267,  -1626,   2527 },
+  {  -2698,   1135,    301,   4239 },
+  {  -2364,   2123,   1010,   3710 },
+  {  -2447,   3281,    -81,   1408 },
+  {  -2660,   4735,    472,    258 },
+  {  -1053,   3097,   2682,   2398 },
+  {  -3366,  -1037,  -1152,   -868 },
+  {   -643,   4242,   2212,   1259 },
+  {    971,   3991,    934,    643 },
+  {  -1617,   2002,   2139,   2195 },
+  {  -4897,    972,    784,   1719 },
+  {  -1275,   2992,   1039,   3821 },
+  {   -392,   4973,   -209,   1821 },
+  {  -1028,   4718,  -1479,   -137 },
+  {     50,   3914,    553,   2210 },
+  {    678,   4364,    359,   1303 },
+  {   -582,   4911,    514,   1671 },
+  {   1276,   3914,  -1252,   2934 },
+  {  -1496,   3984,    857,   2330 },
+  {    772,   4744,   -655,   2332 },
+  {   -799,   5283,   -439,    624 },
+  {   1341,   2937,    650,   2027 },
+  {  -1739,   4892,   1275,   1702 },
+  {   -892,   2596,   -151,   3951 },
+  {  -3532,   1090,   1292,     32 },
+  {    321,   3146,   2647,   1475 },
+  {    264,   4199,  -1591,   1317 },
+  {   -452,  -2357,   2266,   4192 },
+  {   3022,  -1033,  -2389,   5678 },
+  {  -1162,  -1342,   3543,   4990 },
+  {   -474,  -1477,  -1223,   5016 },
+  {   -699,  -2857,    900,   3835 },
+  {   -461,  -2255,   -117,   4626 },
+  {   1204,  -2062,  -1211,   4403 },
+  {   2192,  -3035,   -337,   3966 },
+  {    108,   -831,    279,   5643 },
+  {   1457,   -620,  -2908,   5276 },
+  {  -2527,    -78,   1085,   5460 },
+  {  -1978,  -1918,   -949,   4733 },
+  {     32,    367,  -1904,   5166 },
+  {   1890,  -1665,    440,   4752 },
+  {   -518,   -348,   2816,   4891 },
+  {   3695,  -2490,  -1374,   4603 },
+  {    246,  -1965,   3549,   3969 },
+  {   1100,  -3111,    656,   3737 },
+  {  -1379,    870,   -414,   4575 },
+  {    628,   -357,  -1227,   6179 },
+  {  -1129,  -1318,  -2457,   4576 },
+  {   -425,    -98,    -73,   6336 },
+  {    367,   -887,   2990,   4207 },
+  {   2091,  -1251,   2444,   3557 },
+  {  -1759,  -1610,   2046,   5273 },
+  {   3210,   1414,    -20,   2616 },
+  {   3303,  -2636,   1005,   4237 },
+  {   -327,  -3107,   -640,   3687 },
+  {   -197,    764,    572,   5486 },
+  {    646,   -767,   1388,   5464 },
+  {    104,   2742,   -228,   3907 },
+  {   -236,   1829,   -579,   4585 },
+  {  -2150,   -474,  -1525,   4006 },
+  {    -23,  -2632,  -2400,   3892 },
+  {    -12,  -1739,  -2910,   4867 },
+  {  -2310,   -368,   -102,   4583 },
+  {  -1991,  -2061,    533,   4531 },
+  {   3884,  -1446,   -153,   4393 },
+  {   1568,     14,   -289,   5268 },
+  {  -1376,   -253,  -2797,   3417 },
+  {   3193,  -2577,   2475,   3566 },
+  {   3418,    617,   1350,   1857 },
+  {   3792,    -24,   -272,   3370 },
+  {    153,   1159,   2906,   2877 },
+  {    511,   2162,   1548,   2741 },
+  {    262,    819,  -2791,   3734 },
+  {   4232,  -2015,   1486,   3477 },
+  {   2943,  -1110,  -1014,   5480 },
+  {   2842,    369,    703,   3476 },
+  {   3011,   1634,   -933,   3553 },
+  {   4412,  -1548,   -942,   5021 },
+  {  -1405,    593,   2372,   5267 },
+  {   2093,   2129,    896,   2365 },
+  {   4845,  -1980,      0,   3823 },
+  {  -2140,     81,   3278,   5637 },
+  {   1484,   2665,   -324,   3653 },
+  {     10,    192,   1620,   5291 },
+  {   2152,    738,  -2269,   5000 },
+  {   2102,   2748,  -1652,   4707 },
+  {   2855,  -2131,   -387,   5188 },
+  {   1173,    676,   1338,   3277 },
+  {   2340,  -2329,  -2064,   4095 },
+  {    861,  -2024,   1296,   5055 },
+  {   2189,   3225,   -695,   2626 },
+  {   6196,  -7079,   1943,   -822 },
+  {   4547,  -4813,   3261,   1856 },
+  {   4243,  -6904,   3443,    448 },
+  {   4581,  -7503,    946,    506 },
+  {   6626,  -7754,   3427,    470 },
+  {   3407,  -9088,   3269,  -1496 },
+  {   4079,  -6464,   2304,    777 },
+  {   5621,  -9336,   2684,   -768 },
+  {   5351,  -6464,   5238,   -214 },
+  {   5961,  -8007,   1724,  -3091 },
+  {   4213,  -8067,    603,   -246 },
+  {   7208,  -7403,   3168,  -1738 },
+  {   6098,  -7700,    329,  -1379 },
+  {   6525,  -6735,   4248,  -1072 },
+  {   6073,  -6241,   2167,  -2378 },
+  {   4609,  -9218,   3051,  -1033 },
+  {   6813,  -7283,   1581,  -1897 },
+  {   6126,  -6275,   2789,    681 },
+  {   4423,  -6538,   1621,  -1692 },
+  {   6272,  -8298,   3167,  -1855 },
+  {   6172,  -8558,   4498,  -1169 },
+  {   4844,  -8588,   1647,   -366 },
+  {   6209,  -8807,   1581,   -369 },
+  {   5389,  -8059,    550,   -192 },
+  {   6654,  -9775,   2504,  -1063 },
+  {   7103,  -7998,    806,    530 },
+  {   5662,  -6736,   1565,  -3620 },
+  {   4165,  -9564,   4191,  -2131 },
+  {   4526,  -7181,    576,  -2875 },
+  {   4633,  -8623,   2807,  -4742 },
+  {   3709,  -7794,   1815,     34 },
+  {   3634,  -8622,   2313,   -826 },
+  {   6991,  -8447,   2063,  -3198 },
+  {   7757,  -9486,   2255,   -558 },
+  {   4149,  -7778,   4728,  -1696 },
+  {   5767,  -7427,   1113,    707 },
+  {   4592,  -6261,   2329,   1864 },
+  {   3159, -10498,   1677,  -4273 },
+  {   3534,  -9010,   2437,  -3565 },
+  {   4479, -10821,   2715,  -4942 },
+  {   3207,  -9805,   3054,  -3886 },
+  {   4627,  -8189,   3018,  -2354 },
+  {   5527, -10566,   3244,  -2749 },
+  {   4346, -10127,   3335,  -3084 },
+  {   6132, -10085,   3316,  -1308 },
+  {   5629,  -9704,   2178,  -3058 },
+  {   3603,  -8538,   1246,   -624 },
+  {   3737,  -8488,    395,  -3167 },
+  {   5465, -11414,   2810,  -4640 },
+  {   5306,  -7745,   2721,  -3988 },
+  {   7000,  -9111,   1695,  -1409 },
+  {   6663,  -7741,   2466,  -4079 },
+  {   4083,  -7175,   1836,  -4831 },
+  {   3613,  -9926,   1342,  -3455 },
+  {   6588,  -8033,    457,   -258 },
+  {   4720,  -8102,     17,  -1209 },
+  {   7414,  -8709,   1294,   -344 },
+  {   5437, -10030,   4043,  -1704 },
+  {   4862,  -9281,   1558,  -1431 },
+  {   6800,  -6403,   5113,    862 },
+  {   4623,  -8242,   2667,   -228 },
+  {   5919,  -5083,   3348,   2135 },
+  {   5985,  -8889,   2733,  -5105 },
+  {   5029,  -5767,   4407,    719 },
+  {    354,  -6158,   -838,  -3001 },
+  {    351,  -5943,  -2104,  -1534 },
+  {   -633,  -7190,    -25,  -4798 },
+  {  -1595,  -7235,  -3812,  -1400 },
+  {    103,  -6197,  -2933,    -78 },
+  {  -1722,  -5020,  -3441,  -4333 },
+  {  -1963,  -5644,  -4365,   -270 },
+  {   -846,  -5743,  -3477,    196 },
+  {   -191,  -5348,  -4054,   -469 },
+  {  -2515,  -7754,  -3495,   -818 },
+  {  -2090,  -6710,  -2701,    117 },
+  {   -546,  -7036,  -1398,    163 },
+  {   -278,  -7091,  -2662,   -536 },
+  {   -622,  -7962,  -2731,  -1464 },
+  {  -1555,  -8118,  -3612,  -2057 },
+  {  -1094,  -6280,  -2314,    505 },
+  {  -2556,  -8538,  -4024,  -2247 },
+  {    109,  -7134,  -3107,  -1823 },
+  {   -900,  -6954,  -3340,   -717 },
+  {   -605,  -7113,  -3656,  -2154 },
+  {    837,  -6263,  -3211,  -2177 },
+  {   -417,  -5810,  -3871,  -1469 },
+  {  -1318,  -5649,  -4207,  -3198 },
+  {    413,  -6765,  -2082,    -33 },
+  {  -3101,  -6450,  -4362,   -766 },
+  {    755,  -6489,  -2967,   -846 },
+  {   1117,  -7106,  -2452,  -1352 },
+  {  -1202,  -8387,  -3072,  -2897 },
+  {   -365,  -4894,  -3561,  -2937 },
+  {  -2372,  -8776,   -265,  -4441 },
+  {  -1224,  -8678,   -896,  -5074 },
+  {   -755, -10096,   -600,  -6623 },
+  {    300,  -8206,   -225,  -4568 },
+  {  -1176,  -6824,  -2633,  -3527 },
+  {  -2006,  -5443,  -1526,  -5849 },
+  {  -1115,  -5540,  -2363,  -4785 },
+  {   1059,  -6812,  -2543,  -2654 },
+  {  -1976,  -6861,  -3062,  -5508 },
+  {   -379,  -5328,  -2321,  -3624 },
+  {  -2108,  -5860,  -4518,  -1915 },
+  {   -379,  -7885,  -1329,   -594 },
+  {    774,  -5389,   -581,  -5213 },
+  {  -2601,  -5083,  -1849,  -4921 },
+  {   -176,  -5580,     74,  -5075 },
+  {   -204,  -6780,   -190,  -6232 },
+  {    418,  -7594,  -1987,   -820 },
+  {  -1873,  -8529,  -2926,  -1609 },
+  {   1340,  -6362,   -919,  -4975 },
+  {    577,  -7990,  -2044,  -1873 },
+  {  -2572,  -7413,  -1745,  -2224 },
+  {  -2037,  -7030,  -1461,  -7138 },
+  {  -2559,  -8756,  -2039,  -5836 },
+  {  -2079,  -6764,  -1209,  -5669 },
+  {  -1613,  -7801,  -2006,   -685 },
+  {  -1865,  -6583,   -722,  -3529 },
+  {   -589,  -6358,  -1377,  -1003 },
+  {   -540,  -7514,  -1331,  -3542 },
+  {    419,  -6192,  -1677,  -4927 },
+  {  -2786,  -8763,  -2966,  -5065 },
+  {  -2172,  -8411,  -1726,  -4675 },
+  {  -3382,  -9833,  -3497,  -5722 },
+  {  -2433, -10169,  -2077,  -5775 },
+  {   -424,  -9451,  -1096,  -3658 },
+  {   -537,  -8522,   -910,  -1897 },
+  {  -5550,   2807,   1683,   -693 },
+  {  -6395,    635,   3573,  -1246 },
+  {  -7544,   2280,   2140,     44 },
+  {  -8751,   1136,   2951,   -794 },
+  {  -5605,   2709,   2052,    916 },
+  {  -7650,    654,    869,    135 },
+  {  -6939,    967,   1409,    870 },
+  {  -7834,   2123,   3310,    974 },
+  {  -6935,   2818,   1274,  -1678 },
+  {  -5605,   2233,   1013,    471 },
+  {  -7095,   1849,   1648,    198 },
+  {  -6636,   1634,    712,    -37 },
+  {  -7279,    978,    296,   -315 },
+  {  -7664,   3504,   3292,   -216 },
+  {  -7836,   1209,   1221,   -257 },
+  {  -7913,   2201,   1765,  -1529 },
+  {  -7077,   3783,   2632,  -1407 },
+  {  -5565,   1645,   1410,   -622 },
+  {  -6494,   2879,   1181,   -759 },
+  {  -7073,   3137,   3010,    550 },
+  {  -7249,   1839,    847,   -805 },
+  {  -6630,   2197,    282,  -1096 },
+  {  -8836,   1573,   1988,  -1090 },
+  {  -7809,   1274,    836,  -1198 },
+  {  -7895,   2970,   3511,  -1097 },
+  {  -6960,   1664,   1356,  -2442 },
+  {  -6582,   2866,   2273,    307 },
+  {  -7221,    821,   2851,  -1435 },
+  {  -6015,   1703,   2001,  -2367 },
+  {  -8082,   1034,   2103,    239 },
+  {  -5952,   1912,    301,   -465 },
+  {  -6099,    841,    379,    567 },
+  {  -6343,     50,    494,    658 },
+  {  -6586,    983,    591,   -893 },
+  {  -5500,    869,   2187,  -2479 },
+  {  -6482,     60,   1545,   -979 },
+  {  -6705,    515,   1974,    -53 },
+  {  -6460,   1755,   1325,  -1275 },
+  {  -6093,   2617,   2465,   -623 },
+  {  -7330,   2161,    594,  -2115 },
+  {  -7324,    762,   1593,  -2004 },
+  {  -6385,    679,   1510,  -2514 },
+  {  -6159,    241,   2976,  -1631 },
+  {  -8583,   3030,   4045,   -162 },
+  {  -6299,     66,   2209,  -2103 },
+  {  -5428,   1279,   3267,  -1846 },
+  {  -6438,   1335,   2728,  -1631 },
+  {  -8012,   1070,   2428,  -1151 },
+  {  -6201,   2781,   2349,  -1918 },
+  {  -5918,   1139,   3121,   -148 },
+  {  -6314,   2481,   3137,  -1808 },
+  {  -7180,   1722,   2435,  -1602 },
+  {  -6750,   1829,   3763,  -1145 },
+  {  -6713,   1777,   2221,   1212 },
+  {  -7479,   1835,   3627,   -479 },
+  {  -7299,     10,   2406,  -1593 },
+  {  -8249,   3129,    996,  -2870 },
+  {  -8374,   1534,   1333,  -1882 },
+  {  -7507,   3353,   1598,  -2299 },
+  {  -7379,   2701,   2326,  -1167 },
+  {  -8440,   2276,   2796,   -542 },
+  { -10348,   1527,   2649,  -1165 },
+  {  -8184,   3614,   2574,  -1738 },
+  {  -5539,   1574,   1733,   1138 },
+  {   9404,  -7652,     67,     79 },
+  {   8654,  -3972,   1358,    -60 },
+  {   8617,  -4794,    117,   2318 },
+  {   7886,  -4505,   1784,   1200 },
+  {   8636,  -6125,   3879,  -1003 },
+  {   9654,  -6836,   1816,    205 },
+  {   9374,  -6553,    913,   1875 },
+  {   8020,  -6150,   1134,   2390 },
+  {   7786,  -4970,   2078,  -1857 },
+  {   8691,  -6119,    711,    708 },
+  {   9039,  -5568,   2944,  -1902 },
+  {   9955,  -5048,   1433,   -601 },
+  {   8089,  -6927,   3093,  -2846 },
+  {   8487,  -7024,   2415,     19 },
+  {   9388,  -5287,   3577,  -2655 },
+  {   8591,  -7371,   2300,   -996 },
+  {   9104,  -4763,   1453,  -2558 },
+  {   7615,  -5457,    596,    164 },
+  {   9860,  -7047,   3433,   -614 },
+  {   8756,  -4404,   2235,   -964 },
+  {   9462,  -4660,    299,  -1822 },
+  {  10119,  -5550,   2689,  -1273 },
+  {  10915,  -7471,   2705,  -1007 },
+  {  11433,  -7090,   1410,  -1198 },
+  {   9882,  -7431,   2965,  -1895 },
+  {   7628,  -5219,    769,  -2661 },
+  {   8169,  -5318,   2262,     70 },
+  {   8846,  -6320,   1939,   -754 },
+  {   7147,  -5593,   1248,   -971 },
+  {  10652,  -5485,    935,    137 },
+  {   7778,  -6533,   2564,  -1932 },
+  {   8878,  -5173,   1214,   -361 },
+  {   9828,  -4943,    282,    510 },
+  {  10042,  -6134,   3895,  -1914 },
+  {   7965,  -6630,   3566,   -433 },
+  {   8573,  -4502,   3574,  -1209 },
+  {   8398,  -4801,   1031,  -1347 },
+  {  10136,  -7772,   2612,   1547 },
+  {   9890,  -7280,   1768,  -1083 },
+  {   8407,  -6585,   -706,    -58 },
+  {   7976,  -7582,    229,   -131 },
+  {  10481,  -8866,   1166,   -147 },
+  {  10914,  -4342,   3189,  -2412 },
+  {  10440,  -5198,   -104,  -1109 },
+  {  11227,  -6530,   2381,  -2449 },
+  {   8487,  -8064,   1086,    230 },
+  {   9975,  -6123,   -857,   -134 },
+  {   8339,  -6498,   1232,  -2337 },
+  {  11042,  -4506,   1119,  -2098 },
+  {  12563,  -5592,   1837,  -2062 },
+  {  11801,  -5590,    632,  -1296 },
+  {  10152,  -5617,   1511,  -1917 },
+  {   7800,  -6473,     51,  -1337 },
+  {   7941,  -5560,   2438,  -3270 },
+  {   6554,  -3834,   2100,   1476 },
+  {   9065,  -5520,   -226,  -1120 },
+  {  10794,  -7120,   -243,    122 },
+  {  10429,  -6968,    272,   -806 },
+  {   8942,  -8914,   1442,   -392 },
+  {   9969,  -5051,   2033,  -2953 },
+  {   7275,  -4152,   3058,    -64 },
+  {  11127,  -5488,   4589,  -3227 },
+  {   9626,  -6666,   2739,  -2958 },
+  {   6943,  -5362,   4470,   1008 },
+  {  -7456,   -967,   2936,  -1002 },
+  {  -8622,   -333,   6962,   2606 },
+  {  -7486,  -3392,   3668,   1287 },
+  {  -8053,   -827,   5148,   1097 },
+  {  -6610,    454,   4952,     96 },
+  {  -7701,  -1982,   3161,   -468 },
+  {  -7307,  -1132,   4071,    -36 },
+  {  -8125,   -271,   5199,   3862 },
+  {  -9182,  -1950,   2813,   1878 },
+  {  -9855,   -952,   4794,   3010 },
+  {  -7241,   1431,   4202,   2468 },
+  {  -9646,    157,   4766,   1046 },
+  {  -9371,   1230,   6009,   2958 },
+  { -11514,    -64,   8630,   5248 },
+  {  -6766,    565,   2766,   2140 },
+  {  -8426,     -9,   2852,   1271 },
+  { -11291,  -1113,   5087,   2937 },
+  {  -8297,   2092,   4495,   1264 },
+  {  -9983,    735,   3809,    -51 },
+  {  -9048,  -1000,   3191,   -308 },
+  {  -7331,  -1987,   2655,   1391 },
+  {  -7144,    -21,   4333,   2161 },
+  {  -6032,  -1540,   3543,    896 },
+  {  -7987,  -1036,   1985,   1529 },
+  {  -9264,   2004,   5194,    290 },
+  { -11308,   -840,   5754,   1654 },
+  {  -9130,  -2398,   4292,   2973 },
+  {  -6248,    838,   3563,   1223 },
+  {  -6819,  -2760,   3511,    119 },
+  {  -7213,  -2006,   4364,    762 },
+  {  -5431,  -1047,   4533,    166 },
+  {  -7098,   -641,   2021,    639 },
+  {  -8628,  -2249,   3588,    399 },
+  {  -6352,  -1498,   3560,   -648 },
+  {  -7033,  -2190,   4870,   2562 },
+  {  -7405,    -46,   3772,   -581 },
+  {  -6104,    796,   5143,   1965 },
+  {  -5787,    943,   5784,   3030 },
+  {  -8367,   1465,   7192,   4097 },
+  {  -8259,    789,   5694,   1963 },
+  { -10614,  -1899,   5748,   2645 },
+  {  -8258,   -805,   3698,   2275 },
+  {  -6877,   -972,   6431,   3160 },
+  {  -6483,    363,   7018,   3129 },
+  {  -6283,  -1358,   5191,   1524 },
+  {  -8853,  -3157,   4119,   1741 },
+  {  -6086,   -267,   3883,   -835 },
+  {  -7254,   1032,   6613,   4017 },
+  { -11470,  -3350,   4649,   3426 },
+  {  -6743,    481,   6148,   1239 },
+  {  -5394,   -166,   5309,   3165 },
+  {  -7958,   1068,   4268,   -240 },
+  { -10520,   2256,   7916,   2828 },
+  {  -5132,     -4,   5739,   1176 },
+  {  -8643,    120,   3255,   -629 },
+  {  -9631,   1974,   8870,   4362 },
+  { -10663,  -1221,   3733,    589 },
+  {  -8224,  -1843,   5806,   2655 },
+  {  -8282,   1255,   8647,   3478 },
+  { -12311,  -1505,   9043,   6256 },
+  { -11312,   -856,   7136,   4681 },
+  { -11944,   -722,   7941,   3309 },
+  {  -7868,   -463,   6846,   4196 },
+  {  -8679,   -241,   7410,   5347 },
+  {   6759,  -4680,   -508,   1220 },
+  {   5176,  -6111,    944,    121 },
+  {   6843,  -5667,  -1368,   -533 },
+  {   5616,  -5884,  -1471,   -695 },
+  {   6030,  -5089,  -1808,   -940 },
+  {   7444,  -5463,    -52,   1881 },
+  {   4207,  -6079,   -506,   1571 },
+  {   6785,  -4410,   -649,   3084 },
+  {   4838,  -5214,   2026,   2998 },
+  {   4201,  -5790,    645,   1811 },
+  {   6930,  -5129,  -1940,   1698 },
+  {   6332,  -4627,    692,   3027 },
+  {   6285,  -4314,   -106,   3644 },
+  {   6255,  -5450,  -1975,    742 },
+  {   4199,  -4676,   -459,   1796 },
+  {   5592,  -5500,   1345,   1300 },
+  {   4358,  -5556,  -2236,    114 },
+  {   4620,  -5875,  -1563,    888 },
+  {   4892,  -7550,   -327,   -419 },
+  {   4734,  -7085,      7,    613 },
+  {   3883,  -5562,  -1969,   1080 },
+  {   5610,  -4990,   -204,    834 },
+  {   4117,  -6482,  -1271,    341 },
+  {   6585,  -5107,    892,   1169 },
+  {   6632,  -3683,    302,   3002 },
+  {   6326,  -5351,   -983,  -1250 },
+  {   4382,  -7192,   -730,   -158 },
+  {   5227,  -6540,   -451,   1123 },
+  {   5468,  -6472,   -870,  -1471 },
+  {   5191,  -6402,  -1365,   -127 },
+  {   7407,  -6317,   -973,   -336 },
+  {   4611,  -6530,   -820,  -1980 },
+  {   4963,  -5159,  -2050,   -966 },
+  {   4414,  -5691,   -211,   -998 },
+  {   5954,  -5873,    750,  -1749 },
+  {   4394,  -4796,  -1268,    254 },
+  {   7161,  -6214,  -1010,    689 },
+  {   4965,  -3598,   2372,   1711 },
+  {   6248,  -6180,    981,    864 },
+  {   6473,  -5336,    525,   -600 },
+  {   4591,  -6864,  -1131,   -900 },
+  {   6314,  -6440,  -1021,   -375 },
+  {   5838,  -6209,  -1199,    944 },
+  {   5308,  -5283,  -2100,   1267 },
+  {   4342,  -5860,  -1637,  -1356 },
+  {   5680,  -4388,  -1227,   -104 },
+  {   4900,  -4098,   1449,   4046 },
+  {   4677,  -4284,   -106,   3190 },
+  {   7574,  -6173,   -848,   1859 },
+  {   6493,  -7207,   -131,    726 },
+  {   5513,  -5261,  -2117,      4 },
+  {   6191,  -7352,   -193,   -505 },
+  {   5885,  -4333,    324,   -134 },
+  {   6162,  -6081,   -312,  -2044 },
+  {   4216,  -6200,  -1810,   -572 },
+  {   5652,  -7035,   -696,   -197 },
+  {   7131,  -7189,   -366,    -60 },
+  {   5032,  -4803,  -1514,   2832 },
+  {   7386,  -4610,   -606,   3489 },
+  {   4211,  -5031,   1221,   3047 },
+  {   4050,  -4653,   1584,   1469 },
+  {   6852,  -5302,  -1861,    206 },
+  {   7736,  -4816,  -1794,   3359 },
+  {   6290,  -3439,   1522,   2454 },
+  {   1768,   5990,  -5560,  -2594 },
+  {   3903,   5326,  -1530,  -1501 },
+  {   2472,   3738,  -2117,  -4240 },
+  {   3260,   5448,   -904,  -4733 },
+  {   1435,   7297,  -3676,  -4102 },
+  {   4096,   5951,   -656,  -3312 },
+  {   2178,   6009,  -3146,  -3724 },
+  {   3787,   5493,  -5473,  -1633 },
+  {   2998,   7286,  -3334,  -3571 },
+  {   2894,   6576,  -4708,  -2804 },
+  {    830,   6163,  -4286,  -3348 },
+  {   4755,   5569,  -1730,  -2739 },
+  {   4604,   6065,  -3562,  -2605 },
+  {   2749,   5141,  -3986,  -2775 },
+  {   3942,   4875,  -2143,  -3340 },
+  {   2819,   8517,  -2004,  -2724 },
+  {   2146,   6298,   -689,  -3093 },
+  {   5196,   6504,  -3393,  -1475 },
+  {   1851,   8386,  -1748,  -1420 },
+  {   3474,   8572,  -3534,  -2688 },
+  {   4503,   7560,  -3561,  -2245 },
+  {   4433,   6219,  -2393,  -1575 },
+  {   3506,   7248,  -2275,  -1977 },
+  {   3490,   7409,  -3147,   -604 },
+  {   4214,   6447,  -3520,    516 },
+  {    619,   7034,   -829,  -1705 },
+  {   1732,   7395,   -356,  -2208 },
+  {   1226,   5204,  -3294,  -3732 },
+  {   2027,   5619,  -1813,  -4146 },
+  {   3078,   5877,     47,  -2651 },
+  {   1654,   5458,    424,   -682 },
+  {   3163,   5464,  -2026,   -270 },
+  {   2884,   5375,   -685,   -530 },
+  {   2950,   7286,    -35,  -2967 },
+  {   1986,   5066,   -597,    482 },
+  {   3459,   4308,  -3845,  -2333 },
+  {   3155,   7037,  -1346,  -4345 },
+  {   2193,   6696,   -717,  -1319 },
+  {   3677,   5089,  -3892,   -487 },
+  {   2186,   5136,  -4186,  -1492 },
+  {    773,   5796,   -917,    817 },
+  {   2489,   6546,  -3570,  -2117 },
+  {   1223,   6469,  -1362,    -33 },
+  {    271,   6061,  -1466,  -1725 },
+  {   2540,   5171,  -1847,   1032 },
+  {   2548,   5251,  -2697,   1677 },
+  {    771,   7600,   -768,   -632 },
+  {   4710,   6647,  -4736,  -1275 },
+  {   1369,   5917,  -2971,  -1056 },
+  {    163,   5239,  -3499,  -2275 },
+  {   2104,   4285,  -3211,  -3286 },
+  {   1107,   7411,  -1972,  -1671 },
+  {   2196,   7262,  -2310,  -1926 },
+  {   -244,   6439,  -1745,   -839 },
+  {   3293,   3832,  -2890,  -3000 },
+  {    419,   6443,   -379,   -407 },
+  {   3077,   4930,  -1156,  -2869 },
+  {   2131,   5874,  -2330,    224 },
+  {    690,   6538,  -2212,  -2841 },
+  {   1602,   4421,  -2515,   1542 },
+  {   3318,   9373,  -3032,  -3477 },
+  {   5646,   7462,  -5153,  -1463 },
+  {   4139,   7137,  -1539,  -3321 },
+  {   3481,   9077,  -1645,  -3653 },
+  {  -7747,    375,   -106,   -543 },
+  {  -8587,  -1379,   -586,   -461 },
+  { -10146,   -892,   2094,    694 },
+  {  -8103,    382,    504,   -325 },
+  {  -8548,    -92,     94,   -656 },
+  {  -7460,     38,    152,    388 },
+  {  -8266,   -271,   -459,   -883 },
+  {  -7935,   -664,  -1026,   -802 },
+  {  -8341,   -109,    853,    161 },
+  {  -8802,  -1355,   1099,    630 },
+  {  -8957,     -6,   1108,   -669 },
+  {  -7260,  -1520,    -43,   -407 },
+  {  -7555,   -174,    668,  -2562 },
+  {  -9014,   -126,    227,  -1191 },
+  {  -8184,    769,    290,  -1375 },
+  {  -9476,     55,    962,  -1528 },
+  {  -8679,    541,    755,  -1030 },
+  {  -9842,  -1626,    838,  -1588 },
+  {  -8513,   -702,    788,  -1998 },
+  { -10101,  -1558,   -366,  -1841 },
+  {  -8135,     78,   1479,  -1813 },
+  {  -9128,   -454,    313,  -1786 },
+  {  -7554,  -1084,    831,  -2442 },
+  {  -7576,   -701,   2068,  -1665 },
+  {  -7791,  -1481,   1587,  -1808 },
+  {  -6701,   -596,    -97,    802 },
+  {  -7418,    -15,    684,   -963 },
+  {  -7127,   -477,   -139,   -426 },
+  {  -8097,   -110,    -36,   -264 },
+  {  -7620,  -1922,   -590,   -101 },
+  {  -7647,  -1201,    279,    660 },
+  {  -7856,  -1974,    758,  -2271 },
+  {  -8496,   -167,   2232,  -1143 },
+  {  -8506,  -1359,    624,   -740 },
+  {  -7274,  -1052,   1062,   -139 },
+  {  -7800,   -217,     91,  -1794 },
+  {  -7030,  -1694,   -955,    615 },
+  {  -9020,  -1864,    101,  -2182 },
+  {  -9400,   -740,    598,   -667 },
+  {  -8448,  -1184,   2024,  -1272 },
+  {  -8812,   -570,   -897,  -2384 },
+  { -10559,  -1286,    538,  -1536 },
+  {  -8728,   -888,  -1089,  -1397 },
+  {  -7080,  -1185,    636,  -1252 },
+  {  -9880,    233,   2344,   -782 },
+  {  -7952,  -1326,   -378,  -1947 },
+  {  -7207,   -378,   1408,  -2237 },
+  {  -8467,  -1545,    902,  -1987 },
+  {  -9163,  -1474,    924,  -1739 },
+  {  -8159,   -992,    -77,  -2744 },
+  {  -8343,    148,   -423,  -1573 },
+  {  -9105,   -649,   -254,  -1214 },
+  {  -8939,    456,    281,  -1905 },
+  {  -8837,    179,   -394,  -2634 },
+  {  -9145,    757,   1547,  -1319 },
+  {  -9775,   -723,    441,  -1680 },
+  {  -8910,   -686,   1529,  -1525 },
+  {  -9492,  -1134,   2064,   -938 },
+  {  -6111,   -943,    677,    -31 },
+  {  -7411,   -613,   -814,     46 },
+  {  -9479,   -922,   -430,  -2061 },
+  { -11298,  -1268,   1318,  -1117 },
+  {  -8190,    832,    671,  -2214 },
+  { -10453,   -550,   1672,   -886 },
+  {   1044,   9353,  -1651,  -5423 },
+  {   1034,   8149,   -455,  -6166 },
+  {    761,   8293,  -3214,  -4838 },
+  {    938,   8077,    164,  -5130 },
+  {   1295,   8673,   2582,  -5490 },
+  {   -314,   7973,  -2395,  -5231 },
+  {   -507,   9012,  -2497,  -5775 },
+  {   2396,   8314,  -1022,  -4673 },
+  {  -1516,   8501,   1950,  -4969 },
+  {   -308,   7401,   1549,  -4866 },
+  {   -112,   8340,   3003,  -4920 },
+  {    -50,   9315,   1371,  -5666 },
+  {   -659,   9449,   2496,  -5547 },
+  {   2573,   9148,  -2270,  -4783 },
+  {    830,   7104,   -438,  -3907 },
+  {    522,  10672,   -677,  -6483 },
+  {  -1190,  10108,   -510,  -6518 },
+  {   -427,   8271,   -579,  -6315 },
+  {   1602,   8113,  -1927,  -4418 },
+  {  -2266,   8180,    448,  -5190 },
+  {  -1633,   8816,   -226,  -5771 },
+  {    759,   9481,   -105,  -5813 },
+  {   2254,   6679,   -466,  -5662 },
+  {    -88,   6946,    895,  -5958 },
+  {  -1705,  10009,   1394,  -5574 },
+  {    748,   7943,    540,  -6692 },
+  {   1411,   7009,    232,  -6145 },
+  {    697,   7290,  -1221,  -5342 },
+  {  -1764,  10580,   1944,  -3981 },
+  {  -1334,   9124,   1195,  -3903 },
+  {   -905,  10067,    635,  -5039 },
+  {    664,  10680,     49,  -4625 },
+  {   1374,   9536,   -777,  -3591 },
+  {    252,   9698,   -597,  -2931 },
+  {    824,   9164,  -1014,  -2144 },
+  {   2438,  10569,  -2289,  -4424 },
+  {   2101,   7102,    507,  -3614 },
+  {    294,   8051,   -432,  -1518 },
+  {   -665,  10337,    547,  -2852 },
+  {   1168,  11989,   -492,  -5427 },
+  {   1344,   6416,    302,  -5061 },
+  {  -1727,  12264,   1507,  -4543 },
+  {    674,  10889,   -902,  -3605 },
+  {   -582,   9504,    300,  -3618 },
+  {    641,   7654,    689,  -2109 },
+  {   2065,   9243,    508,  -4367 },
+  {   1055,   8373,    688,  -3144 },
+  {   -641,   8185,    986,  -3307 },
+  {   1120,   7426,   1785,  -3757 },
+  {   1660,   8070,   -593,  -3104 },
+  {   2002,   9467,  -1722,  -3475 },
+  {   2361,   8368,    100,  -3709 },
+  {   -772,   7845,   -613,  -4988 },
+  {   1485,   7430,   1896,  -6127 },
+  {   -432,   7823,   -947,  -2882 },
+  {    313,  11122,   -760,  -4871 },
+  {    412,   8412,   -283,  -4231 },
+  {   1585,  10402,  -1884,  -3267 },
+  {    321,   6952,    773,  -3016 },
+  {   -105,   9014,    121,  -2249 },
+  {   1585,  10313,   -977,  -4812 },
+  {   1619,  11869,   1306,  -6876 },
+  {  -1168,   8886,    -81,  -2500 },
+  {   -395,  10886,    733,  -6490 },
+  {  -4949,   4274,   3992,  -1054 },
+  {  -4241,   5299,   4262,  -1584 },
+  {  -2710,   3862,   4552,  -1673 },
+  {  -4608,   2472,   3672,  -1715 },
+  {  -2843,   2816,   4003,  -2326 },
+  {  -5229,   2964,   5636,     90 },
+  {  -4924,   3442,   5015,  -1096 },
+  {  -1281,   3313,   5537,  -2066 },
+  {  -3808,   1939,   4351,   -919 },
+  {  -1915,   2585,   4939,  -1614 },
+  {  -3470,   1843,   5562,   -682 },
+  {  -3800,    870,   5827,    144 },
+  {  -4985,   1452,   4728,   -709 },
+  {  -3745,   2750,   7220,    259 },
+  {  -1875,   1900,   6514,   -826 },
+  {  -4329,   1574,   7192,   1304 },
+  {  -5408,   1444,   6208,    631 },
+  {  -3327,   5312,   5707,  -1541 },
+  {  -6966,   3334,   4034,   1028 },
+  {  -7484,   4245,   4218,   -212 },
+  {  -6567,   5839,   4539,   -512 },
+  {  -5715,   5935,   3747,  -1186 },
+  {  -6410,   4881,   3356,  -1610 },
+  {  -5146,   2590,   2850,   2172 },
+  {  -5196,   4095,   2569,   -373 },
+  {  -5043,   6025,   4318,    692 },
+  {  -5525,   4884,   3513,    370 },
+  {  -6804,   7533,   5812,   -488 },
+  {  -5657,   2480,   4061,   1234 },
+  {  -3155,   1472,   6071,   1188 },
+  {  -3427,   5217,   3442,    858 },
+  {  -4698,   3013,   5517,   2586 },
+  {  -4449,   2226,   5418,   3580 },
+  {  -6395,   3547,   5487,   2028 },
+  {  -3500,   5019,   4787,      1 },
+  {  -4038,   2578,   3073,   3151 },
+  {  -2750,   1955,   4469,   3856 },
+  {  -5696,   1659,   6118,   2469 },
+  {  -4350,   1241,   6840,   3126 },
+  {  -5565,   5058,   5196,   1314 },
+  {  -1642,   4190,   3948,    607 },
+  {  -1233,   4108,   4850,   -640 },
+  {   -997,   3428,   3239,   1378 },
+  {  -6488,   2741,   6926,   2792 },
+  {  -4188,   3763,   4235,   2018 },
+  {  -3210,   3224,   5646,   1427 },
+  {  -5526,   6909,   5070,   -627 },
+  {  -2815,   3994,   3425,   1903 },
+  {  -2163,   2734,   5423,    145 },
+  {  -4149,   4247,   2355,    734 },
+  {   -410,   2521,   4138,    -16 },
+  {  -2411,   2385,   4927,   2105 },
+  {  -6077,   3591,   3114,    594 },
+  {  -4186,   4834,   5926,  -1004 },
+  {  -7315,   3369,   5966,    448 },
+  {  -7042,   5721,   5771,    238 },
+  {  -4466,   3907,   3535,  -1751 },
+  {  -2116,   3970,   6163,  -1392 },
+  {  -7239,   2143,   8407,   3630 },
+  {  -5431,   4486,   6486,    -42 },
+  {  -1874,   1617,   6333,    519 },
+  {  -6478,   2629,   4634,   -505 },
+  {  -7784,   2342,   7216,   1365 },
+  {  -1154,   1432,   4831,   1544 },
+  {  -4964,  -5801,   1797,    506 },
+  {  -4436,  -6905,   1059,  -1237 },
+  {  -5400,  -6886,    884,   -290 },
+  {  -6259,  -7103,    523,   -227 },
+  {  -4819,  -6450,   1412,   -450 },
+  {  -4056,  -6213,   1725,   -943 },
+  {  -5642,  -6091,   1357,    605 },
+  {  -4196,  -5678,   2187,   -173 },
+  {  -4726,  -5126,   2470,    321 },
+  {  -6642,  -5091,   1507,  -1005 },
+  {  -5304,  -5250,   1944,   1579 },
+  {  -7179,  -5520,   1468,   -425 },
+  {  -6033,  -4895,   1876,   -955 },
+  {  -6595,  -5143,   2207,   1291 },
+  {  -4224,  -4943,   1846,   1792 },
+  {  -7128,  -6950,    539,    724 },
+  {  -4369,  -4901,   2590,   1103 },
+  {  -7413,  -5696,   1712,   1440 },
+  {  -5885,  -6821,    418,    871 },
+  {  -6828,  -5599,    710,  -1563 },
+  {  -6123,  -5817,   1358,   1631 },
+  {  -5291,  -5622,    578,   2138 },
+  {  -7171,  -6004,    347,   2208 },
+  {  -6083,  -5251,   2132,    425 },
+  {  -4329,  -5721,    407,  -2993 },
+  {  -5326,  -5056,   1119,  -1837 },
+  {  -5485,  -5856,    185,  -2389 },
+  {  -6529,  -5178,    403,   -697 },
+  {  -6719,  -4412,   2726,    871 },
+  {  -5126,  -5629,   1835,   -771 },
+  {  -5622,  -4361,   2973,    858 },
+  {  -5282,  -5895,     45,   -335 },
+  {  -4357,  -5656,   1696,  -1558 },
+  {  -7139,  -6659,    627,   -409 },
+  {  -4415,  -6328,     35,   1306 },
+  {  -7639,  -6110,   1134,    197 },
+  {  -3626,  -5592,   2019,    901 },
+  {  -3547,  -5064,   1176,   1738 },
+  {  -5075,  -3899,   2087,    266 },
+  {  -4086,  -6311,   1479,    360 },
+  {  -6210,  -5220,   -199,  -1477 },
+  {  -3910,  -5063,   1356,    -15 },
+  {  -7616,  -4977,    461,   2401 },
+  {  -6118,  -6131,   1258,   -563 },
+  {  -6127,  -4968,   1286,    -27 },
+  {  -4121,  -5852,   1113,   1476 },
+  {  -5157,  -4881,   1162,   -662 },
+  {  -4637,  -5031,   1179,    709 },
+  {  -5509,  -5452,   -397,   1224 },
+  {  -4597,  -6861,    646,    467 },
+  {  -6247,  -4043,    468,    278 },
+  {  -5336,  -6465,    874,  -1472 },
+  {  -6998,  -6346,     78,  -1798 },
+  {  -4915,  -4530,   2756,   -203 },
+  {  -6048,  -4373,   1468,   1052 },
+  {  -4273,  -7100,    942,   -323 },
+  {  -6552,  -4287,   2351,     69 },
+  {  -6954,  -4613,    722,   1521 },
+  {  -4201,  -5361,    763,  -1562 },
+  {  -6881,  -5596,   -748,    669 },
+  {  -6695,  -3547,    -34,   1299 },
+  {  -3981,  -5728,     84,    111 },
+  {  -4663,  -4809,   2173,  -1031 },
+  {  -6599,  -6077,   1303,    256 },
+  {  -7596,  -4265,  -5791,  -4140 },
+  {  -6610,  -2758,  -5288,  -3936 },
+  {  -5880,  -3865,  -6563,  -3088 },
+  {  -7228,  -5510,  -7677,  -3912 },
+  {  -8854,  -6553,  -8318,  -5361 },
+  {  -9362,  -5249,  -6413,  -4319 },
+  {  -4418,  -3110,  -6368,  -4358 },
+  {  -5544,  -4203,  -6863,  -5013 },
+  {  -3056,  -4316,  -5567,  -3181 },
+  {  -3078,  -5999,  -5051,  -2657 },
+  {  -5884,  -6292,  -5756,  -4013 },
+  {  -4825,  -4549,  -5535,  -4053 },
+  {  -4443,  -6126,  -5316,  -1368 },
+  {  -3972,  -6341,  -6098,  -2686 },
+  {  -5751,  -2781,  -5398,  -6230 },
+  {  -4466,  -6135,  -5570,  -3679 },
+  {  -4291,  -5992,  -3564,  -5189 },
+  {  -7189,  -4429,  -7279,  -6082 },
+  {  -5076,  -4433,  -2748,  -5366 },
+  {  -6225,  -2825,  -6833,  -5663 },
+  {  -2989,  -4792,  -3960,  -4492 },
+  {  -7836,  -7773,  -7722,  -5741 },
+  {  -6559,  -5703,  -5844,  -5589 },
+  {  -7612,  -5438,  -4136,  -3774 },
+  {  -4218,  -4176,  -6591,  -2333 },
+  {  -4837,  -5063,  -6581,    322 },
+  {  -6590,  -5990,  -2980,  -3847 },
+  {  -5558,  -2971,  -5489,  -1932 },
+  {  -7001,  -5323,  -4975,  -1697 },
+  {  -4694,  -2688,  -6904,  -3044 },
+  {  -8511,  -5379,  -5767,  -2549 },
+  {  -7548,  -5412,  -6522,  -2572 },
+  {  -6597,  -4973,  -6423,  -1274 },
+  {  -6415,  -4022,  -5168,  -1072 },
+  {  -5528,  -5530,  -7218,  -2345 },
+  {  -4845,  -4805,  -5943,  -1227 },
+  {  -6049,  -7150,  -6744,  -2161 },
+  {  -9061,  -7299,  -8542,  -4375 },
+  {  -5010,  -5546,  -5416,    -82 },
+  {  -4135,  -4205,  -5109,  -3373 },
+  {  -3311,  -5869,  -4007,  -5061 },
+  {  -5993,  -6472,  -3962,  -4718 },
+  {  -2966,  -5832,  -2821,  -6305 },
+  {  -4851,  -5152,  -2067,  -3930 },
+  {  -3620,  -4441,  -3362,  -5836 },
+  {  -4469,  -5221,  -4534,  -5592 },
+  {  -4022,  -6335,  -4321,  -6107 },
+  {  -4899,  -4503,  -3084,  -3725 },
+  {  -4490,  -8276,  -4620,  -6236 },
+  {  -6591,  -4342,  -7365,  -4063 },
+  {  -6498,  -5057,  -5553,    485 },
+  {  -6060,  -2714,  -7093,  -4144 },
+  {  -6199,  -7774,  -7094,  -4057 },
+  {  -7536,  -6424,  -6415,  -4265 },
+  {  -7439,  -2454,  -6348,  -4827 },
+  {  -5333,  -7565,  -4417,  -4639 },
+  {  -4353,  -7103,  -4197,  -2689 },
+  {  -5229,  -6549,  -5129,  -6804 },
+  {  -6129,  -7701,  -5236,  -4836 },
+  {  -6797,  -3983,  -3884,  -4406 },
+  {  -6624,  -4467,  -4745,  -5052 },
+  {  -3324,  -7596,  -2720,  -6553 },
+  {  -5473,  -6284,  -1704,  -4511 },
+  {  -4131,  -7263,  -3180,  -5196 },
+  {  -7116,  -5565,  -3469,    685 },
+  {  -6002,  -6021,  -3858,    576 },
+  {  -3144,  -8203,  -1291,   -434 },
+  {  -6096,  -7027,  -4004,   1353 },
+  {  -3943,  -7709,  -2344,    -36 },
+  {  -4510,  -6767,  -2642,    631 },
+  {  -3657, -11541,  -2570,  -3984 },
+  {  -5959,  -8854,  -1333,   -867 },
+  {  -6699,  -8866,  -1606,   -344 },
+  {  -3836,  -7961,  -2334,  -2028 },
+  {  -3430,  -8045,  -3037,   -672 },
+  {  -3868,  -9184,  -3635,  -1819 },
+  {  -4258,  -9060,  -2621,  -1008 },
+  {  -3595,  -8693,  -2022,   -752 },
+  {  -4573,  -8048,  -3166,  -2622 },
+  {  -4852,  -7903,  -1405,    256 },
+  {  -4591,  -7057,  -1560,    965 },
+  {  -6963,  -7655,   -980,    808 },
+  {  -5179,  -6641,  -3356,   1196 },
+  {  -7102,  -6941,  -2798,   2123 },
+  {  -6867,  -5834,  -3320,   -770 },
+  {  -5977,  -7369,  -2500,   -778 },
+  {  -6160,  -6400,   -934,  -2543 },
+  {  -6741,  -7608,   -355,  -1289 },
+  {  -6856,  -6466,  -1433,  -1643 },
+  {  -4786,  -6292,  -4970,    376 },
+  {  -5407,  -8866,  -2255,   -400 },
+  {  -3814,  -6506,  -1387,  -3620 },
+  {  -4998,  -6137,  -1200,  -4092 },
+  {  -5123,  -9557,  -2849,  -1306 },
+  {  -4259,  -6444,  -4395,   -338 },
+  {  -5221,  -6810,   -883,   1225 },
+  {  -6137,  -6215,  -2165,    554 },
+  {  -3895,  -6557,  -3176,  -1829 },
+  {  -3886,  -8188,    -87,   -954 },
+  {  -7243,  -6707,  -2216,   -316 },
+  {  -5592,  -7606,     85,   -432 },
+  {  -3957,  -7945,   -504,   -144 },
+  {  -4617,  -7624,    218,   -312 },
+  {  -4797,  -8737,   -844,  -1051 },
+  {  -4478,  -8516,  -1401,   -454 },
+  {  -4557,  -7058,   -302,  -2332 },
+  {  -6623,  -7736,   -271,    -50 },
+  {  -3157,  -7532,  -1111,  -2207 },
+  {  -3590,  -7300,  -1271,    517 },
+  {  -4442,  -7306,   -507,    590 },
+  {  -6458,  -7524,  -2807,    666 },
+  {  -4991,  -8466,  -3363,   -785 },
+  {  -7474,  -7541,  -1056,  -1839 },
+  {  -7501,  -8316,   -938,   -180 },
+  {  -5329,  -7739,   -579,  -2341 },
+  {  -4549,  -7063,   -176,  -3539 },
+  {  -5191,  -8612,  -1504,  -4250 },
+  {  -3083,  -7058,  -2251,     32 },
+  {  -4003,  -7043,  -1093,   -791 },
+  {  -5523,  -8093,   -678,   -114 },
+  {  -3022, -10265,  -2070,  -3109 },
+  {  -3905,  -6274,   -182,  -3652 },
+  {  -3269,  -9217,   -551,  -2650 },
+  {  -3138,  -9314,  -1726,  -1704 },
+  {  -4420, -10339,  -1744,  -3459 },
+  {  -4163,  -8609,  -2298,  -4113 },
+  {  -5566,  -6505,  -1241,   -463 },
+  {  -3130,  -9746,  -2352,  -4884 },
+  {  -7825,  -3439,   1451,  -1468 },
+  {  -8451,  -3318,   2360,   -435 },
+  {  -8462,  -4130,   1438,  -1024 },
+  {  -9425,  -4564,   1328,   -689 },
+  { -11014,  -3202,   2278,   2080 },
+  {  -8269,  -2761,   -146,   -440 },
+  {  -7497,  -2618,   -166,    413 },
+  {  -8250,  -3060,    522,  -2133 },
+  {  -8365,  -5366,   1347,   -451 },
+  {  -8589,  -3979,   2943,    714 },
+  {  -8111,  -2572,   1272,  -1748 },
+  {  -7830,  -5193,    605,  -1484 },
+  {  -8119,  -4736,   2141,    256 },
+  {  -7724,  -4769,   1463,   -812 },
+  {  -7363,  -3911,   2540,      4 },
+  {  -7974,  -3397,   2363,   1366 },
+  {  -7359,  -4204,   1752,   -958 },
+  {  -7622,  -3505,    660,    916 },
+  {  -9934,  -3665,   3165,    828 },
+  {  -8721,  -4162,     62,   1718 },
+  {  -9433,  -4768,   2722,   1234 },
+  {  -7960,  -4496,    138,   1528 },
+  {  -8198,  -3454,   -443,    631 },
+  {  -7756,  -2246,    655,   1137 },
+  {  -8841,  -3145,   1113,    829 },
+  {  -7817,  -3298,   1251,    230 },
+  {  -9413,  -2733,    323,  -1862 },
+  {  -9408,  -4168,   1270,   1549 },
+  {  -9037,  -3892,   -942,    283 },
+  {  -8255,  -3849,   1301,   1762 },
+  {  -9057,  -3987,    -41,   -682 },
+  {  -9441,  -4187,   2019,   -111 },
+  {  -9740,  -3178,   1602,   -871 },
+  {  -8344,  -2474,   1461,   1506 },
+  {  -9752,  -2925,   1996,   1243 },
+  {  -9199,  -3796,    180,    537 },
+  {  -9060,  -2405,   1140,  -1562 },
+  {  -9348,  -2376,    309,   -162 },
+  { -10786,  -3182,     -5,  -1500 },
+  {  -8142,  -4540,   -434,   -826 },
+  {  -7528,  -2341,   1104,    -73 },
+  {  -9360,  -2658,   3062,     56 },
+  {  -8267,  -2335,   2000,  -1193 },
+  { -12169,  -3154,   1287,   -640 },
+  { -11398,  -2120,    946,  -1163 },
+  {  -8940,  -4559,    328,  -1696 },
+  { -11025,  -4213,   2813,    840 },
+  {  -9224,  -3581,   2224,   2039 },
+  {  -8943,  -3337,   1248,  -1298 },
+  {  -7900,  -4042,    485,  -2080 },
+  {  -9221,  -1947,   2191,   -880 },
+  { -10762,  -1800,   2516,   -324 },
+  { -10095,  -2238,    981,  -1335 },
+  { -11908,  -2808,   3255,    645 },
+  { -10640,  -4105,   1283,   -595 },
+  {  -7663,  -2863,   2467,   -797 },
+  { -10712,  -3854,   3710,   1538 },
+  { -10823,  -2893,   1408,   -801 },
+  {  -9874,  -3832,    256,  -1638 },
+  { -10394,  -3391,   2315,    -94 },
+  { -11525,  -4079,   4153,   2122 },
+  {  -9546,  -2088,   1541,    481 },
+  {  -8731,  -2433,   1042,   2160 },
+  {  -7852,  -3977,  -1370,   1677 },
+  {   7072,  -3420,   1398,  -1741 },
+  {   6180,  -1976,   1280,  -3557 },
+  {   7692,  -1793,   2844,  -1700 },
+  {   8363,  -1773,   3104,  -2679 },
+  {   9213,  -3266,   3756,  -3542 },
+  {   9650,  -2644,   1426,  -1318 },
+  {   7712,  -2796,   3686,  -1975 },
+  {   7316,  -3517,   2821,   -622 },
+  {   7434,  -2594,   2305,  -2264 },
+  {   7237,  -1797,    255,  -3114 },
+  {   8663,  -1983,   1338,  -3056 },
+  {   6616,   -952,   4059,  -2652 },
+  {   8823,  -1327,   1362,  -1356 },
+  {   9938,  -1722,   1287,  -2362 },
+  {   7207,  -1057,   1913,  -1315 },
+  {   7508,  -1585,    870,  -1982 },
+  {   8217,  -3680,   1417,  -3170 },
+  {   8329,  -2541,   1684,   -585 },
+  {   8062,  -2335,    252,  -2800 },
+  {   8204,  -4108,   3097,  -2569 },
+  {   7701,  -3367,    576,  -3008 },
+  {   7350,   -786,   2414,  -2129 },
+  {   6948,  -2568,   1607,   -225 },
+  {   7684,  -2387,   1308,  -3449 },
+  {   8306,  -3458,   2394,  -1454 },
+  {   8438,  -2781,   1043,  -1362 },
+  {   9175,  -2076,   2144,  -1987 },
+  {   8347,  -2709,   3489,  -4301 },
+  {   5696,  -2377,   2870,    851 },
+  {   8825,  -1243,   2219,  -2603 },
+  {   8801,  -1614,    584,  -2513 },
+  {   8413,   -384,   1421,  -2244 },
+  {   9228,  -3050,   3279,  -2164 },
+  {   6342,  -2698,   3547,   -107 },
+  {  10053,  -2476,   2837,  -3168 },
+  {   7439,   -604,   3177,  -3991 },
+  {   7749,  -1064,   4329,  -4855 },
+  {   8655,  -2177,   2252,  -3519 },
+  {   8490,   -228,   1958,  -3233 },
+  {  10513,  -2968,   1911,  -2340 },
+  {   8146,   -862,   1884,  -1723 },
+  {   7788,   -666,   3004,  -2891 },
+  {   7785,  -1620,   4133,  -3417 },
+  {  10262,  -3731,   3455,  -2971 },
+  {   8570,   -905,   4519,  -4649 },
+  {   9129,  -2562,    463,  -2465 },
+  {   9451,  -3587,   1904,  -3056 },
+  {   6549,  -2236,   3010,  -4523 },
+  {   7175,  -2684,   2967,  -3458 },
+  {   9872,  -3278,   1054,  -2472 },
+  {   9153,   -931,   1217,  -2565 },
+  {   8789,  -3469,    753,  -2568 },
+  {   6683,  -3791,   1797,  -3968 },
+  {   6801,  -1977,   2311,   -452 },
+  {   6336,  -1572,   2612,  -3264 },
+  {   7996,  -1008,    730,  -2964 },
+  {   7521,  -1059,   1573,  -3694 },
+  {   8148,  -3973,   2600,  -3572 },
+  {   7765,  -1532,   2528,  -3856 },
+  {   7404,  -3918,   4472,   -143 },
+  {   8894,  -1398,   3299,  -3685 },
+  {   5768,  -2041,   1487,   -637 },
+  {   5131,  -2865,   2463,   -811 },
+  {   6439,  -1568,   3500,  -1550 },
+  {  -8878,  -6798,  -5319,  -1452 },
+  {  -6332,  -9713,  -3112,   -990 },
+  {  -8444,  -6316,  -3694,   -687 },
+  {  -6123, -10840,  -3637,  -4358 },
+  {  -4784,  -9580,  -4577,  -2581 },
+  {  -6108, -10515,  -4859,  -2524 },
+  {  -7605,  -7518,  -2327,  -2797 },
+  {  -9662,  -8775,  -2467,  -2010 },
+  {  -6494,  -7523,  -4715,   -118 },
+  {  -8290,  -8982,  -1672,   -317 },
+  {  -8798, -11051,  -3888,  -1426 },
+  {  -6273,  -6623,  -6791,   -142 },
+  {  -8313,  -7668,  -2141,  -1275 },
+  {  -6453,  -8412,  -3589,  -4102 },
+  {  -6747,  -7750,  -5690,  -2498 },
+  {  -7814,  -6693,  -3174,  -2446 },
+  { -10383, -10130,  -3931,  -2364 },
+  { -10606,  -8467,  -5539,  -2772 },
+  {  -9475,  -6671,  -3305,  -2271 },
+  {  -8982,  -9457,  -5635,  -4005 },
+  { -10111,  -7965,  -6515,  -4180 },
+  {  -7301,  -6479,  -5364,    720 },
+  {  -9543,  -8999,  -7921,   -912 },
+  {  -9534,  -8562,  -3469,   -384 },
+  {  -7601, -10344,  -3205,  -1127 },
+  {  -8088,  -8620,  -4954,  -2888 },
+  {  -8202,  -8406,  -7038,  -3775 },
+  {  -7312,  -8324,  -3334,  -1775 },
+  {  -8566,  -9262,  -8071,  -4174 },
+  {  -7068, -11300,  -5573,  -2907 },
+  {  -8295,  -8952,  -4366,  -1544 },
+  { -11104, -10210,  -2285,   -384 },
+  {  -5213,  -7520,  -5008,  -1339 },
+  {  -5889,  -7940,  -5987,  -1385 },
+  { -10816,  -8201,  -4153,  -1485 },
+  { -10277,  -8919,  -6315,  -1652 },
+  {  -5888, -10320,  -3821,  -1733 },
+  { -10497,  -7181,  -6083,  -3032 },
+  {  -7721,  -9724,  -6591,  -5336 },
+  {  -5688,  -7894,  -3486,  -2552 },
+  { -10014, -10500,  -3247,   -820 },
+  {  -6301,  -8765,  -4506,  -2923 },
+  {  -8261,  -7847,  -6213,  -1552 },
+  { -10212,  -7481,  -8113,  -3954 },
+  {  -6938, -10874,  -6074,  -4703 },
+  {  -7183, -10968,  -4446,  -1773 },
+  {  -7120,  -9193,  -1966,  -2509 },
+  {  -6234,  -9263,  -2313,  -4284 },
+  {  -8503,  -9857,  -2429,   -608 },
+  {  -9372,  -7844,  -8391,  -2120 },
+  {  -7951,  -7157,  -6535,    -11 },
+  {  -7256,  -9473,  -2172,   -660 },
+  { -10063,  -9612,  -2515,    -15 },
+  {  -6684,  -9134,  -6109,  -4206 },
+  {  -8204, -11932,  -5220,  -2306 },
+  {  -9710,  -6706,  -4115,  -3275 },
+  {  -6855,  -7078,  -2409,  -4447 },
+  {  -7344,  -7673,  -4479,  -4116 },
+  {  -8851,  -6842,  -4927,  -2948 },
+  {  -8927, -10452,  -5633,  -2194 },
+  {  -8627,  -9002,  -7176,  -1575 },
+  {  -8209,  -9722,  -7021,  -3324 },
+  {  -3770, -10249,  -3623,  -4816 },
+  {  -8183,  -7465,  -4090,    646 },
+  {  -8163,  -7149,    200,    498 },
+  {  -8289,  -6266,    686,   -206 },
+  { -10030,  -6241,  -1032,  -1864 },
+  {  -8793,  -8327,   -773,   -169 },
+  {  -9149,  -6215,    969,    -15 },
+  {  -8303,  -5859,     -7,   2006 },
+  {  -9682,  -7283,    255,   1322 },
+  {  -9293,  -7227,     71,   -231 },
+  {  -8525,  -6215,    287,   -837 },
+  { -10477,  -5379,   1159,   1449 },
+  { -10726,  -7856,   -130,    102 },
+  {  -8694,  -7461,  -1210,    690 },
+  {  -9367,  -5324,   1103,   3170 },
+  { -10686,  -8055,   -831,   1633 },
+  {  -9201,  -6873,  -2704,   2258 },
+  {  -8421,  -5358,  -1405,    226 },
+  {  -9066,  -5830,   -307,  -1571 },
+  { -11150,  -7381,  -2746,   -900 },
+  {  -9978,  -5925,  -2006,   -437 },
+  {  -9464,  -4741,   -273,   1061 },
+  { -10543,  -6684,  -1113,   1660 },
+  { -10073,  -5576,   1083,   -269 },
+  {  -8826,  -5763,   1600,   1486 },
+  { -10445,  -9071,  -1253,    -64 },
+  { -12085,  -5799,      2,    769 },
+  { -12939,  -6663,   1650,   1437 },
+  { -10932,  -6434,  -1252,   -649 },
+  { -11650,  -7826,  -2053,    710 },
+  { -12122,  -6733,  -1889,   -731 },
+  {  -9093,  -6095,  -2463,   -842 },
+  { -10977,  -4364,    469,    420 },
+  { -11488,  -6908,   -521,    893 },
+  {  -9669,  -5478,   -842,    337 },
+  { -10606,  -5203,   -632,  -1361 },
+  { -10198,  -6284,   1662,   1277 },
+  { -10135,  -5292,   2435,   3493 },
+  { -11027,  -6561,    655,     56 },
+  { -10977,  -5030,   1127,   -358 },
+  { -12766,  -3986,   1348,   -335 },
+  { -14244,  -7731,    264,    317 },
+  { -15124, -10309,   -508,   1447 },
+  { -12821,  -8638,   -608,    137 },
+  { -13076,  -8693,  -2852,   -431 },
+  { -11156,  -5546,  -2252,  -1600 },
+  {  -8692,  -7366,   -819,  -1223 },
+  { -12507,  -9816,  -1714,   -121 },
+  { -10712,  -6666,    544,   3349 },
+  { -12462,  -5890,  -2491,  -2318 },
+  { -12468,  -7226,    437,    232 },
+  { -11300,  -5226,   2068,    687 },
+  { -11994,  -8320,   -626,   2728 },
+  { -12222,  -5476,   1142,     18 },
+  { -10277,  -8122,  -2418,   2003 },
+  { -13418,  -6115,  -3563,  -2802 },
+  { -14759,  -9834,  -1243,     21 },
+  { -13699,  -5665,   1525,    507 },
+  { -16269,  -9476,   -701,    163 },
+  { -12677,  -5437,   -247,  -1019 },
+  { -11827,  -4295,   -181,  -1243 },
+  { -12847,  -4496,   2984,   1123 },
+  { -13860,  -7915,  -1166,   -547 },
+  { -12276,  -8145,  -2290,  -1527 },
+  { -11417,  -4830,   2983,   1854 },
+  { -11793,  -6002,   1163,   1940 },
+  {  11443,  -4920,  -3235,   3151 },
+  {  11300,  -6616,  -1506,   1175 },
+  {   9198,  -4628,  -2060,   2390 },
+  {  10532,  -4027,   -643,    912 },
+  {   9902,  -3573,  -1606,   1327 },
+  {   9653,  -3536,  -2240,   1869 },
+  {   9948,  -5171,   -423,   2662 },
+  {  12316,  -4004,  -1989,    281 },
+  {  12125,  -4800,  -1265,   -163 },
+  {  10650,  -2617,  -2337,   1462 },
+  {   9909,  -4968,  -2376,    916 },
+  {  12944,  -4647,  -1958,    460 },
+  {  12988,  -5283,  -1141,     41 },
+  {  12321,  -2915,  -3621,   1025 },
+  {  11449,  -2894,  -2728,    351 },
+  {  12087,  -3041,  -2002,    -32 },
+  {  11558,  -4031,  -1343,   -399 },
+  {  12983,  -3740,  -3516,   1245 },
+  {  12099,  -2515,  -2752,    225 },
+  {  12515,  -3465,  -2701,    550 },
+  {  14683,  -5022,  -5272,   2996 },
+  {  12260,  -3383,  -1215,   -528 },
+  {  13810,  -5422,  -2443,   1166 },
+  {  13421,  -5378,  -1886,    721 },
+  {  12961,  -4259,  -2594,    796 },
+  {  12266,  -2104,  -4768,   1591 },
+  {  13523,  -4710,  -3045,   1342 },
+  {  12437,  -2099,  -5610,   2117 },
+  {  11850,  -2183,  -3497,    661 },
+  {  12275,  -3936,   -597,   -697 },
+  {  12459,  -5253,   -517,   -544 },
+  {  12835,  -4094,  -1322,   -168 },
+  {  14360,  -5677,  -3305,   1859 },
+  {  13905,  -4552,  -4309,   2117 },
+  {  11559,  -3412,  -1847,    -81 },
+  {  13379,  -3167,  -5764,   2746 },
+  {  11910,  -1634,  -4342,   1052 },
+  {  12662,  -4742,     71,   -974 },
+  {  13057,  -3254,  -4424,   1705 },
+  {  15046,  -5706,  -4851,   3019 },
+  {  14162,  -4142,  -5514,   2843 },
+  {  12764,  -1845,  -6684,   2888 },
+  {  13714,  -2374,  -7838,   3857 },
+  {  13295,  -1663,  -8293,   4073 },
+  {  10032,  -4152,  -3403,   1421 },
+  {  10942,  -5386,  -2222,    950 },
+  {  10532,  -6385,  -1750,   1925 },
+  {  10273,  -5972,  -1534,    643 },
+  {  10605,  -4782,  -1695,     27 },
+  {  10988,  -5153,  -1123,   -341 },
+  {  11629,  -5884,  -1060,     48 },
+  {  10441,  -4045,  -2431,    311 },
+  {  10788,  -3595,  -4171,   1807 },
+  {  12110,  -5686,  -2127,    976 },
+  {  11746,  -4773,  -2639,    891 },
+  {  11541,  -5299,  -3031,   1732 },
+  {  11416,  -2559,  -5359,   2198 },
+  {  11583,  -5376,   -704,    677 },
+  {  10416,  -3214,  -3516,    872 },
+  {   9651,  -5435,  -1618,   3255 },
+  {   9973,  -5133,   -996,   3923 },
+  {  11707,  -4643,   -430,   -796 },
+  {  10994,  -2709,  -3587,   2302 },
+  {  10716,  -5118,   -645,    270 },
+  {  14100, -10314,   1095,   1531 },
+  {  12944,  -8049,   1105,   -741 },
+  {  13276,  -7035,   -511,    274 },
+  {  14008,  -7254,   -283,    139 },
+  {  11594,  -6536,    -91,   1671 },
+  {  11732,  -8645,    746,     15 },
+  {  14613,  -7085,  -1578,   1183 },
+  {  13083,  -6224,   -750,     -4 },
+  {  13988,  -6256,  -1592,    820 },
+  {  14678,  -8683,    441,    126 },
+  {  15571,  -8872,   -521,   1139 },
+  {  15642,  -9533,    341,    697 },
+  {  15960,  -9586,   -168,   1121 },
+  {  15464, -10239,   1433,     -1 },
+  {  14934,  -7887,  -1046,   1080 },
+  {  15252,  -7630,  -1899,   1628 },
+  {  15485,  -8384,  -1234,   1484 },
+  {  15962,  -8638,  -1815,   1931 },
+  {  16501, -10664,    398,   1167 },
+  {  16146, -10145,    411,    918 },
+  {  14573,  -7475,   -697,    601 },
+  {  14302,  -7996,     28,    257 },
+  {  14769,  -6792,  -2286,   1574 },
+  {  14144,  -6137,  -2169,   1257 },
+  {  14770,  -6271,  -3111,   1933 },
+  {  14110,  -8312,   1083,   -531 },
+  {  15235,  -6991,  -2993,   2174 },
+  {  13222,  -5805,    547,   -891 },
+  {  14796,  -8762,   1254,   -246 },
+  {  16040,  -9181,  -1005,   1551 },
+  {  16487, -10086,   -373,   1420 },
+  {  15077,  -9479,    966,     51 },
+  {  13026,  -6468,    932,  -1080 },
+  {  12703,  -6152,    -33,   -573 },
+  {  15641,  -6810,  -4128,   2874 },
+  {  13282,  -7673,   1583,  -1283 },
+  {  12373,  -7150,   1512,   -917 },
+  {  12992,  -7751,   -678,    783 },
+  {  10907,  -6858,   -313,   2597 },
+  {  13026,  -8963,    125,   2152 },
+  {  12770,  -9946,   1957,   -505 },
+  {  12482,  -6849,  -1268,    833 },
+  {  13790,  -6181,   -138,   -279 },
+  {  12709,  -8382,   2044,    227 },
+  {  12244,  -6630,    203,   -457 },
+  {  14209,  -6816,  -1032,    632 },
+  {  15134,  -8267,   -288,    640 },
+  {  13619,  -6157,  -1090,    356 },
+  {  14044,  -7413,    725,   -484 },
+  {  12958,  -7753,   2585,  -1980 },
+  {  13188,  -8396,   2306,  -1558 },
+  {  14379,  -9980,   2132,   -688 },
+  {  14275,  -9857,   1162,    179 },
+  {  13690,  -8648,   1621,   -889 },
+  {  11770,  -6829,   -746,    278 },
+  {  12732,  -8202,    286,     90 },
+  {  13630, -10146,   1867,   -207 },
+  {  12072,  -8740,   1299,   -645 },
+  {  12852,  -9492,   1226,     62 },
+  {  11792,  -7382,    -54,   -116 },
+  {  13779,  -9014,    487,    351 },
+  {  11951,  -7729,    121,    834 },
+  {  11970,  -9781,   2276,     -4 },
+  {  12680,  -7984,   2787,   -787 },
+  {  13300, -14488,   6408,  -1927 },
+  {  13635, -15355,   9153,  -3073 },
+  {  12804, -13566,   5517,  -1625 },
+  {  16624, -10854,   1690,     28 },
+  {  20387, -18532,   6162,   -261 },
+  {  16515, -12642,   3392,   -519 },
+  {  15800, -11095,   2151,   -202 },
+  {  16824, -11790,   1651,    599 },
+  {  17604, -13213,   2563,    538 },
+  {  17892, -14177,   3562,    147 },
+  {  16987, -11399,    869,   1052 },
+  {  17003, -12456,   2442,    265 },
+  {  21657, -21806,   9198,  -1250 },
+  {  16825, -13341,   3980,   -686 },
+  {  17525, -12714,   1887,    805 },
+  {  16419, -11034,   1216,    617 },
+  {  20931, -19939,   7469,   -684 },
+  {  18452, -15390,   4573,   -191 },
+  {  14778, -10077,   2841,  -1209 },
+  {  17402, -13319,   3042,    160 },
+  {  19365, -17922,   7087,  -1061 },
+  {  16298, -11941,   2810,   -351 },
+  {  19087, -16176,   4775,    -84 },
+  {  17666, -12289,    938,   1224 },
+  {  18581, -15894,   5132,   -430 },
+  {  19823, -16717,   4142,    545 },
+  {  19960, -19423,   8400,  -1492 },
+  {  18973, -16817,   5906,   -594 },
+  {  19079, -15431,   3528,    503 },
+  {  16667, -12485,   4467,  -1302 },
+  {  19791, -17797,   6196,   -529 },
+  {  20005, -17606,   5354,    -20 },
+  {  20123, -18599,   6886,   -728 },
+  {  19068, -14805,   2394,   1105 },
+  {  14443, -13723,   5631,  -2029 },
+  {  14730, -14231,   5631,  -1450 },
+  {  16089, -15959,   7271,  -2029 },
+  {  13473, -11200,   3236,   -924 },
+  {  14413, -10902,   2347,   -267 },
+  {  17666, -18662,  11381,  -3496 },
+  {  14749, -11042,   3305,   -275 },
+  {  15304, -10486,   1869,   -240 },
+  {  14809, -12126,   3369,   -616 },
+  {  16896, -16561,   7307,  -1845 },
+  {  15782, -14336,   5380,  -1264 },
+  {  16395, -15520,   6415,  -1588 },
+  {  13681, -11114,   2584,   -320 },
+  {  14244, -12326,   4480,  -1632 },
+  {  15247, -13119,   4265,   -898 },
+  {  13987, -12091,   3469,   -597 },
+  {  13941, -12770,   4240,   -839 },
+  {  13771, -13627,   5252,  -1384 },
+  {  15010, -16074,   7592,  -2249 },
+  {  15852, -17226,   8619,  -2655 },
+  {  18921, -16916,   6875,  -1501 },
+  {  14909, -11678,   2768,   -295 },
+  {  18988, -18353,   8424,  -2070 },
+  {  15457, -15080,   6218,  -1513 },
+  {  14916, -15512,   6949,  -1883 },
+  {  18108, -14702,   4681,   -701 },
+  {  17600, -15733,   5616,   -775 },
+  {  14070, -13683,   6472,  -2626 },
+  {  13832, -11914,   5201,  -2232 },
+  {  18846, -19009,   9192,  -1961 },
+  { -11981, -10994,  -6324,  -2264 },
+  { -10976,  -9047,  -6546,  -3828 },
+  { -11288, -10532,  -7014,  -4191 },
+  { -10139, -10189,  -7799,  -2688 },
+  { -10555,  -9988,  -9181,  -2040 },
+  { -11596, -11339, -10022,  -2707 },
+  { -13400, -13395, -11306,  -4206 },
+  {  -9774, -12281,  -7466,  -4133 },
+  { -10842, -13125,  -8777,  -4956 },
+  { -11964, -15082,  -9779,  -5095 },
+  {  -9382, -10188,  -9053,  -4927 },
+  { -11562, -11296,  -3651,   -985 },
+  {  -9287, -10083,  -7918,  -4069 },
+  { -12821, -16556, -11410,  -6195 },
+  { -12628,  -8959,  -4521,  -1113 },
+  { -13845, -11581,  -3649,   -681 },
+  { -12685, -10269,  -5483,  -1275 },
+  { -14988, -12874,  -5107,  -1189 },
+  { -13761, -11367,  -6202,  -1804 },
+  { -13225, -11249,  -7820,  -3354 },
+  { -14809, -11992,  -3202,   -312 },
+  { -15620, -15519, -10210,  -3433 },
+  { -12954, -10200,  -3139,   -611 },
+  { -11536,  -9981,  -5284,   -923 },
+  { -13034, -12417,  -4612,  -1098 },
+  { -16911, -15505,  -6123,  -1352 },
+  { -17396, -17685,  -8330,  -2171 },
+  { -14120, -10764,  -2265,    -99 },
+  { -12598,  -7367,  -5406,  -3530 },
+  { -14143, -12793, -10909,  -5226 },
+  { -14692, -16871, -11626,  -5554 },
+  { -12581, -11197,  -9194,  -3837 },
+  { -16752, -16726,  -9746,  -2808 },
+  { -10600, -10358,  -6560,  -1227 },
+  { -14573, -13312,  -8957,  -3393 },
+  { -10172,  -8463,  -8579,  -3387 },
+  { -11418, -12421,  -5522,  -1842 },
+  { -11855, -14204,  -6669,  -2625 },
+  { -13308,  -8191,  -3941,  -2194 },
+  { -10007, -12266,  -5022,  -1811 },
+  { -13532, -15771,  -9497,  -3175 },
+  { -11760, -11148, -10339,  -5529 },
+  { -12149, -12763, -11198,  -3697 },
+  { -12029, -12119,  -8555,  -1792 },
+  { -16995, -19957, -11447,  -3471 },
+  { -13144, -14504,  -9988,  -3191 },
+  {  -9938, -11064,  -6139,  -3162 },
+  {  -8873, -11550,  -8294,  -6550 },
+  {  -9303, -13010,  -6150,  -2711 },
+  { -15463, -10469,  -1766,   -170 },
+  { -15985, -11693,  -3007,   -650 },
+  { -17142, -10671,  -1434,     47 },
+  { -16063, -13858,  -4817,  -1058 },
+  { -19446, -19599,  -9594,  -2464 },
+  { -20076, -18744,  -8313,  -1889 },
+  { -15047, -16085,  -7590,  -2250 },
+  { -13481, -16195,  -8552,  -2998 },
+  { -13829, -14869,  -6704,  -1932 },
+  { -16357, -18484,  -9802,  -2959 },
+  { -10551,  -8393,  -9303,  -5070 },
+  { -11345,  -9156,  -5641,  -3107 },
+  { -13217, -13449,  -9270,  -4541 },
+  { -11988, -13732,  -9995,  -6374 },
+  { -11007,  -9519,  -5168,  -4107 },
+  {   9930,  -7858,   8061,  -4375 },
+  {   8274,  -7867,   5992,  -2096 },
+  {   9692,  -9675,   7621,  -3670 },
+  {   9589,  -8110,   6509,  -3010 },
+  {  12617, -11976,  10122,  -5360 },
+  {  11867,  -8895,   7948,  -5323 },
+  {  10388, -10482,   9234,  -4324 },
+  {   8188,  -8220,   7810,  -2737 },
+  {  10407,  -8787,   4806,  -1930 },
+  {  10348,  -8845,   9233,  -6614 },
+  {   9422,  -7091,   4820,  -2878 },
+  {   9758,  -9796,   5584,  -2256 },
+  {  10188,  -7994,   5347,  -3343 },
+  {  11133,  -7455,   4015,  -2306 },
+  {  10676, -10744,   6093,  -2629 },
+  {  11522, -12184,   7848,  -3375 },
+  {   8805,  -9883,   5317,  -3071 },
+  {   9498,  -9654,   6555,  -3592 },
+  {  10488,  -8008,   4066,  -1252 },
+  {  11261,  -8930,   6068,  -2738 },
+  {  12180, -10397,   5027,  -1531 },
+  {   9138,  -8531,   3601,  -1959 },
+  {   8107,  -8380,   4970,  -2061 },
+  {   9737, -13248,   6438,  -2617 },
+  {  11178, -10423,   2622,   -522 },
+  {   9572, -12372,   5199,  -2019 },
+  {  12057, -12144,   4147,  -1099 },
+  {   9047,  -9925,   2516,   -665 },
+  {  10790,  -8030,   5882,  -4386 },
+  {   7199,  -8426,   6337,  -2841 },
+  {   7778,  -8285,   3529,  -3442 },
+  {   7559, -10569,   3484,  -1332 },
+  {   9404,  -8115,   7484,  -5541 },
+  {   7792, -11976,   5546,  -2573 },
+  {   9313, -10264,   7661,  -5195 },
+  {   6701, -10725,   4370,  -1784 },
+  {   4918, -11361,   4507,  -4527 },
+  {   5147, -12305,   3978,  -5556 },
+  {   6525,  -9899,   4481,  -3129 },
+  {   7538, -12855,   6060,  -4826 },
+  {   8659, -12111,   7159,  -4430 },
+  {   8440, -11304,   4547,  -1747 },
+  {   9216, -10918,   3507,  -1195 },
+  {   6165,  -9254,   4771,  -4677 },
+  {   9163, -11019,   5637,  -4935 },
+  {  13441, -11509,   6676,  -2434 },
+  {   7912,  -9398,   6663,  -4048 },
+  {  11723, -13745,   8131,  -4148 },
+  {   6065, -10257,   5005,  -6327 },
+  {  11618, -12417,   5336,  -1894 },
+  {   8891, -13924,   8407,  -6131 },
+  {   9622, -12563,   7908,  -5109 },
+  {  11479, -10315,   8349,  -3991 },
+  {  11676, -14103,   6611,  -2330 },
+  {  11951,  -8953,   3829,  -1550 },
+  {  10486,  -8044,  10493,  -5920 },
+  {  11801, -10769,   9763,  -5305 },
+  {   6109,  -8676,   5827,  -1346 },
+  {   7030,  -9611,   5624,  -5761 },
+  {  12808, -12886,   8683,  -4148 },
+  {  13213, -10464,   6381,  -3189 },
+  {  11796, -13681,  10703,  -6075 },
+  {   9639,  -7949,   9625,  -3944 },
+  {   8538,  -6997,   5309,    453 }
 };
 
 /* quantization tables */
@@ -4226,2054 +4226,2054 @@ static const float lossless_quant_d[32] = {
 
 static const int8_t high_freq_vq[1024][32] =
 {
-  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
-  { -4, -2, 2, 1, -16, -10, 1, 3, 1, 0, 6, 1, -3, 7, 1, -22,
-    2, -4, -3, 11, 14, 6, -1, 1, -13, 29, -28, 10, 10, -8, 0, -9 },
-  { -8, 8, -7, 10, -3, -12, -5, -8, 1, -2, 9, -2, -5, -18, 1, 9,
-    -8, -8, 3, 41, 7, -9, -9, 22, -42, -29, 14, -18, -14, -32, 1, -15 },
-  { -16, 8, 15, 16, -16, 5, 2, 7, -6, -16, -7, 1, 1, -3, -2, 0,
-    8, 20, -26, -11, 2, -17, 0, -3, -34, -37, 10, 44, -2, 22, 2, -4 },
-  { 7, 14, 5, 6, 15, -1, 3, -3, -9, -23, -5, -14, 8, -1, -14, -6,
-    -5, -8, 54, 31, -6, 18, 2, -19, -2, -11, -30, -6, -19, 2, -2, -14 },
-  { 1, 2, -2, -1, -3, -3, 1, -5, 1, -3, -4, -8, 5, -4, 0, 1,
-    3, 7, -5, -4, -3, -12, 3, -2, -3, 12, -53, -51, 6, -1, 6, 8 },
-  { 0, -1, 5, 1, -6, -8, 7, 5, -18, -4, -1, 1, 0, -3, -3, -14,
-    -1, -6, 0, -14, -1, -1, 5, -3, -11, 1, -20, 10, 2, 19, -2, -2 },
-  { 2, 4, 3, 0, 5, 0, 3, 1, -2, 0, -6, -3, -4, -5, -3, -3,
-    -7, 0, -34, 4, -43, 17, 0, -53, -13, -7, 24, 14, 5, -18, 9, -20 },
-  { 1, 0, -3, 2, 3, -5, -2, 7, -21, 5, -25, 23, 11, -28, 2, 1,
-    -11, 9, 13, -6, -12, 5, 7, 2, 4, -11, -6, -1, 8, 0, 1, -2 },
-  { 2, -4, -6, -4, 0, -5, -29, 13, -6, -22, -3, -43, 12, -41, 5, 24,
-    18, -9, -36, -6, 4, -7, -4, 13, 4, -15, -1, -5, 1, 2, -5, 4 },
-  { 0, -1, 13, -6, -5, 1, 0, -3, 1, -5, 19, -22, 31, -27, 4, -15,
-    -6, 15, 9, -13, 1, -9, 10, -17, 4, -1, -1, 4, 2, 0, -3, -5 },
-  { -7, 3, -8, 13, 19, -12, 8, -19, -3, -2, -24, 31, 14, 0, 7, -13,
-    -18, 0, 3, 6, 13, -2, 1, -12, -21, 9, -2, 30, 21, -14, 2, -14 },
-  { -3, -7, 8, -1, -2, -9, 6, 1, -7, 7, 13, 3, -1, -10, 30, 4,
-    -10, 12, 5, 6, -13, -7, -4, -2, -2, 7, -3, -6, 3, 4, 1, 2 },
-  { -8, 9, 2, -3, -5, 2, 0, 9, 3, 7, -4, -16, -13, 3, 23, -27,
-    18, 46, -38, 6, 4, 43, -1, 0, 8, -7, -4, -1, 11, -7, 6, -3 },
-  { 1, 1, 18, -8, -6, 0, 3, 4, 22, -3, -4, -2, -4, -11, 40, -7,
-    -3, -13, -14, -7, -10, 14, 7, 5, -14, 11, -5, 7, 21, -2, 9, -3 },
-  { 0, 0, -2, 4, -2, 0, 2, 0, -1, 2, -1, 0, 0, 2, 2, 2,
-    -1, 1, -3, -1, -15, -2, -63, -27, -21, -47, -14, 1, -14, 10, 0, 2 },
-  { 1, 0, -4, 0, -3, -9, 4, 2, 6, -6, 0, -5, 11, -7, -15, 6,
-    -7, -6, 3, 7, -15, -5, 23, -13, -6, 12, -8, 9, 2, -3, 3, 4 },
-  { 6, 0, 3, 0, -2, -4, 2, 1, 1, -1, 1, -2, -1, -4, -22, -15,
-    -46, -66, 10, 20, 2, -17, 12, -6, 1, -2, -2, 0, 1, -5, 1, 2 },
-  { -1, 0, 0, 1, 0, -4, 0, 1, -10, -3, -8, 5, 7, -11, 2, -11,
-    29, -25, 11, 10, 0, -1, 5, -7, -2, -5, -2, 4, 4, -3, 5, -2 },
-  { 1, -1, -1, -3, -2, 1, -8, -3, 2, -2, 4, -5, -1, -7, -2, 1,
-    -14, -7, 3, -30, -15, -14, 3, -4, -1, 3, -13, -1, -3, 1, 2, 3 },
-  { -1, -2, -3, 2, 2, -3, 3, 1, -3, 2, 0, -4, 6, 5, -5, 10,
-    -57, 3, 22, -50, 1, -2, -5, -6, -1, 5, 1, 2, 2, 1, -2, 2 },
-  { 2, 0, -1, -7, 2, 1, 3, 2, 0, 4, 3, -2, 3, -3, 4, -4,
-    24, -35, -3, 38, -6, -5, 15, 20, 3, 16, -7, -5, 0, -4, -5, 0 },
-  { 0, 1, 0, 0, 0, -1, -1, 1, 1, -1, 1, -2, 0, 0, 0, 0,
-    0, -1, -2, -1, -5, -2, -43, -3, 46, -52, -10, 7, -8, 11, -2, -1 },
-  { 0, 0, -1, 0, -1, 2, -41, 33, -44, -48, -15, -26, -9, 6, 3, 3,
-    -3, 2, 2, 2, 2, -1, -1, -2, 1, 3, 0, 0, 5, 2, 3, 1 },
-  { -4, 1, 6, 1, -6, -1, -2, 1, -14, -4, 0, -5, -2, 2, -2, 0,
-    -6, 1, 0, 8, -21, 32, -3, -36, -6, -2, -1, -7, 3, 0, 1, -6 },
-  { -3, -2, 3, 0, 2, 2, 8, -4, -4, 6, 2, 1, 3, -6, 4, 3,
-    13, 0, -12, -1, 25, -20, -2, -23, -15, 7, -3, -11, -3, 6, -1, 0 },
-  { 0, 0, -3, -1, 0, 0, -2, -1, -2, -2, 1, -1, 0, 0, 10, 3,
-    -2, 3, 3, -7, -6, -5, 0, -4, -60, -16, -6, 38, 5, 6, -5, 0 },
-  { 0, 1, 0, 0, 0, 0, 0, 0, 1, -1, -1, 0, 1, 0, 0, 1,
-    0, 0, -1, 0, -8, 2, -9, 10, 40, 31, -56, -21, 4, 20, -4, 7 },
-  { -2, -2, 0, 4, -3, -1, 7, 3, 1, 3, -8, 0, 3, 1, 2, 5,
-    1, -2, 14, 5, 4, 5, 5, 5, -5, 9, -66, 0, -20, -2, -8, 4 },
-  { -2, -1, 4, -1, -8, -2, -4, -1, -3, -3, 2, -7, -3, 5, 7, -2,
-    45, 31, -17, -16, -2, -2, -1, -22, 1, -1, -3, 3, 5, -3, 5, -1 },
-  { -4, 0, 7, 5, 8, 7, 2, 9, -9, -9, -7, -11, -3, -8, 17, -4,
-    34, 32, 18, 22, 1, 2, 1, -7, -5, 6, -1, 6, 4, 10, -2, -7 },
-  { 6, 0, 14, 9, 6, -1, -2, -3, 4, -6, -8, 4, 7, -1, 28, 38,
-    15, -1, 16, -11, 5, 8, 4, -10, 3, -10, -17, 5, 3, 3, 3, 1 },
-  { 1, 1, 2, -1, 2, 1, 0, 0, -1, 0, 0, -2, 1, -3, 0, 1,
-    2, -2, -4, -2, 0, -1, 1, -3, 1, 1, 1, -1, 8, 8, 66, 33 },
-  { -5, 2, -3, -7, 2, -8, -4, 10, 17, -18, -7, 4, -4, -7, -6, -6,
-    -5, 5, -12, 2, 0, 6, 8, -2, 1, 4, -11, 2, 1, 8, 31, 19 },
-  { 6, 9, 16, -6, -6, -1, -2, -3, -11, -2, 7, 7, 17, 3, 4, 10,
-    2, 5, -13, 8, 7, 1, 4, 5, 7, 6, 7, -8, 9, -8, 33, 6 },
-  { 3, -1, 1, 0, -7, -5, 0, 14, -7, 1, -7, 1, 2, -4, 7, 10,
-    -16, 12, 1, -6, 3, 8, -1, 10, -13, -6, -12, -23, 12, -3, 30, 14 },
-  { -2, -15, 0, 8, 3, -19, 5, -3, 2, 3, 13, 7, 14, -3, -10, 0,
-    8, 5, -6, -16, -8, -8, 14, 2, -1, 1, -9, -11, 11, -5, 27, 9 },
-  { -8, 6, -4, 4, -4, -1, 5, 4, 1, -7, -5, -4, -15, 1, 9, 0,
-    8, 4, 1, -17, 11, -2, -19, -1, -6, -8, 3, -12, 3, -17, 33, -10 },
-  { -3, -1, 2, 7, 7, -2, 9, 8, -18, -1, -13, -10, -3, -3, 11, 8,
-    -2, -12, -8, 1, 4, 9, 14, 10, -3, 0, 2, 1, -2, 3, 31, 10 },
-  { -3, -10, 8, -1, -5, -11, 7, -5, 3, 6, 1, 4, -16, 10, 5, -4,
-    -2, -10, -1, 13, 6, -5, -7, 12, 7, -3, -17, 1, 12, -4, 29, 8 },
-  { 1, 2, 5, 2, -6, -7, 0, -1, 6, -1, 10, 6, -4, 5, 2, 2,
-    -2, -8, -6, -11, 14, -13, 27, 3, -2, -12, 5, -16, 2, -26, 20, 15 },
-  { -1, -3, -5, -3, -3, 6, -1, 3, -5, 1, 7, 2, 1, 0, -1, -1,
-    0, -1, 9, 7, -6, -3, 4, -5, -4, 8, -8, -25, -8, -4, 34, 23 },
-  { -1, -2, 1, 1, -1, -2, -1, 1, -1, 0, 0, 0, 0, -2, -1, 1,
-    0, 2, 1, -1, 4, 0, 0, 1, -1, 0, 5, 3, 12, -9, 68, -16 },
-  { 10, 0, -8, 14, -6, 1, -12, 0, 0, -3, -5, -11, -6, 12, 9, -10,
-    -3, 5, 0, 7, 11, 2, 4, -3, -8, -3, 7, 4, 3, -3, 34, 4 },
-  { -12, 13, -5, 7, -11, -2, -1, 1, -4, -14, -21, 3, -3, -3, -4, -7,
-    -9, -4, 3, -17, -2, -13, 10, -2, 12, -4, 0, -9, 1, -5, 31, 10 },
-  { -10, 6, 5, 6, 4, -7, 10, 0, -28, -3, 0, -11, -1, -5, 16, -10,
-    -16, 7, 20, 2, -4, 2, -5, 0, 15, 6, 5, -10, 7, -9, 20, 4 },
-  { 1, -7, -2, -7, 4, -3, -2, -7, -1, -14, 6, -16, 4, -5, -4, -6,
-    -5, 0, -2, 2, -6, 9, -5, 4, -18, 8, -10, 8, 15, 0, 32, 1 },
-  { -5, 7, -3, 7, 15, -4, 0, -16, 9, 5, -5, 5, 4, -3, -12, -9,
-    -18, 10, 2, 2, -3, 7, 3, -1, 6, -9, -10, 3, 15, -4, 35, -7 },
-  { -1, -10, 2, 2, -4, -2, 10, 2, -1, 2, -2, 1, -1, -14, -11, 3,
-    -8, 5, -8, -2, 6, -1, -7, 1, 7, 5, 7, 8, 30, -4, 30, 14 },
-  { 2, -2, 1, 2, 3, -8, 3, 0, -2, 0, -9, 2, 1, 4, -6, -1,
-    -2, 5, 0, 1, -2, 12, 6, -3, 9, -3, 4, -12, 21, -39, 24, -2 },
-  { 3, 5, 1, -2, -2, -2, -3, 6, -8, -2, -11, -8, -1, 4, 2, 2,
-    -4, -10, 12, -5, -11, 1, -15, -34, -11, -7, -11, -1, 7, -14, 38, -1 },
-  { -4, 4, 8, 9, 8, 1, -5, -9, 4, -2, 15, -4, 11, -15, 20, -1,
-    -1, -3, 4, -9, -2, -2, -2, 8, 6, 12, -5, 0, 11, -12, 27, -4 },
-  { 0, 8, -4, 3, -11, 6, -11, 2, 3, 0, 5, -8, -7, -6, -9, -21,
-    4, -11, -1, -16, -7, 16, -3, 7, -7, 4, -5, 0, 11, -7, 31, 3 },
-  { 1, 3, 4, 11, -11, -2, -3, -6, 6, 5, 0, 3, -9, -6, 4, -4,
-    0, 4, -8, 13, -6, -13, -1, -5, -1, 4, 0, 0, 9, -22, 24, 18 },
-  { -7, 3, 10, -13, -6, 6, -6, 6, 22, 1, 0, -14, 2, 3, 7, -1,
-    8, 20, -1, 5, -4, 13, 9, -9, -9, 6, 0, -4, 0, -8, 31, -4 },
-  { -3, -4, 0, 1, 7, 3, -7, 0, 5, -2, 1, 3, 3, 1, -5, -2,
-    5, 2, -11, 4, 0, -1, 12, 0, -3, -13, 15, 8, -6, -27, 34, 0 },
-  { -3, -3, 10, -4, 2, -1, -3, 0, -1, -1, -4, 2, 6, -2, 12, 1,
-    3, -6, -7, -6, -5, 4, -19, -6, -8, -34, -4, -8, 10, -7, 23, 10 },
-  { -7, 0, -1, -6, 8, 4, -4, 2, -5, -8, -7, -9, -8, 5, 9, 7,
-    -6, 1, -12, -12, -1, -16, 5, 0, 16, 3, -7, -8, 27, -4, 23, 15 },
-  { -8, 4, 8, 5, 6, 11, -3, 5, 3, -1, -11, 6, -5, 0, 2, -6,
-    -3, -6, 4, -1, 5, -5, -12, -6, 7, -5, 9, 3, 6, -7, 29, 1 },
-  { 1, 3, -2, -2, -6, -2, 1, 6, -6, -3, 1, 2, 3, 4, 1, 5,
-    -1, 0, 4, 2, 11, 6, 2, -3, 13, -9, -19, 18, -15, -10, 36, 21 },
-  { -3, -3, 2, -1, -7, 6, -4, 1, -3, -1, -2, 2, 3, -7, -3, 0,
-    -2, 0, -2, 6, -19, 3, -8, 2, -6, 7, -1, 0, 29, -6, 28, -10 },
-  { -5, 1, -3, -7, -12, -4, 1, 1, -1, 13, -10, -1, -9, -5, -13, 6,
-    13, 3, -4, 2, 3, 11, 2, 6, -25, -16, -6, 0, 14, -1, 27, 16 },
-  { -6, -1, -7, -5, -2, -5, -5, -1, 9, 1, 0, 3, -8, -12, -6, 5,
-    -6, 5, 3, -9, 1, 4, -7, -10, -9, -7, -17, -5, -15, -23, 25, 3 },
-  { -8, -2, 9, -3, -4, 3, -1, 8, -7, -7, -5, -4, -2, 9, 4, -1,
-    -7, -4, -5, -16, 3, -6, 18, -13, -9, 16, -15, 8, 15, -10, 24, 5 },
-  { 1, -38, 2, 34, 9, 10, 11, 2, 2, -6, 3, 2, -2, 5, 4, -7,
-    -1, 1, 4, 0, 3, 1, -8, -1, -6, 5, 4, 2, -4, 5, 2, -1 },
-  { 1, -22, 15, 18, -2, 10, -16, -9, -8, -11, 8, 4, 0, 7, -14, -5,
-    -1, -7, 12, 17, 9, 5, -7, -4, -12, -6, 7, 0, 7, 2, -2, 1 },
-  { -11, -29, 7, 10, 19, -1, -8, -9, 7, 1, 9, 6, 8, -7, -14, 8,
-    -3, -11, -13, 0, -7, -23, -2, -8, 12, 9, 2, 14, 19, 1, -1, 5 },
-  { -24, -27, -11, 36, 2, 6, -3, 4, -6, 8, 0, 12, -1, -4, -6, 3,
-    4, -1, 2, -3, -2, 3, 2, -1, -2, -4, 0, -1, -2, 7, 2, 3 },
-  { -9, -24, 11, 13, -10, -12, 12, -2, 7, 4, 8, 13, -3, -3, 2, 9,
-    -3, -4, 4, 13, 5, 13, -6, -3, 1, 15, 7, -3, 0, 19, -2, -9 },
-  { -8, -15, 7, 14, -4, -5, 2, -18, -19, -2, 2, 17, 16, 6, -10, 10,
-    -9, 14, -1, -5, -1, -6, -7, 2, 9, 11, 13, 6, -5, -12, 3, 2 },
-  { -10, -37, 13, 1, 3, -14, 0, -20, 4, -3, 8, 2, -2, -3, -9, -5,
-    -3, -17, -1, 13, -11, 2, -6, 4, 4, 0, 3, 1, -9, -4, -5, -4 },
-  { -2, -22, -5, 46, -8, 5, 9, -11, 8, 7, 7, -1, -1, -2, -7, 2,
-    -3, 3, -1, -2, 7, 0, 2, -1, 1, -2, -2, -3, 6, 0, -4, -6 },
-  { -16, -27, 15, 16, -4, 14, -7, -26, 2, -2, 6, 5, -3, 11, 0, 2,
-    3, 9, -7, -1, 2, -4, -4, -1, 6, 10, 1, 1, -3, -2, 3, 0 },
-  { -3, -22, 10, 26, 1, 2, -3, 3, 17, -3, -7, 9, 1, -21, -4, 5,
-    3, 0, -7, -6, 3, 3, -8, -7, -9, 3, 7, 1, -8, 12, 6, -7 },
-  { -9, -25, 3, 18, 9, -6, -11, 0, -5, -12, 9, -8, -7, -6, -6, 22,
-    2, -6, -3, 15, 3, 2, -2, 9, 14, -10, -7, 15, 13, 6, -2, 11 },
-  { 5, -20, -5, 28, 11, 10, -4, -4, 0, -7, 3, 5, 2, -5, -8, 2,
-    6, 10, 9, -9, -18, 3, 14, 1, 3, -3, -1, -6, 7, 7, 2, -1 },
-  { -8, -30, 7, 12, 10, 8, 7, -13, -16, 0, 1, -1, -6, -11, -15, 4,
-    1, -2, 10, -15, 1, 11, -2, 8, 9, -7, -7, 9, -5, 2, 7, -18 },
-  { -10, -32, 10, 11, 3, -1, 3, -5, 5, 2, 14, -6, 3, 1, 5, -15,
-    -11, 6, 20, 4, 0, -12, -7, 3, 1, -1, 10, 6, -1, -9, -4, -1 },
-  { 1, -25, -14, 12, -11, 9, 9, -16, -24, -17, 22, -9, 11, -30, -3, -4,
-    6, -7, 9, 2, -1, -5, -6, 2, -1, -1, 10, 1, -3, 3, 4, 8 },
-  { -14, -26, -6, 9, 8, 17, -11, -24, -7, -4, -8, -2, 10, 2, 2, -1,
-    2, 13, 12, -7, 4, -6, -10, 6, 6, -13, -11, -7, -16, 0, -2, 5 },
-  { -4, -30, -13, 12, 16, -6, 12, -16, -13, 5, 15, -2, -2, -10, -7, 7,
-    11, -1, -4, -2, -4, 7, 4, -8, 1, 3, 0, 11, 3, -2, -5, 4 },
-  { -4, -21, 20, 22, 2, 20, -8, 1, -12, -5, -9, 4, -10, -17, -3, -8,
-    -3, 3, -12, 1, -3, 0, 7, 4, 7, 7, -3, 7, 5, 3, 1, -5 },
-  { -12, -20, 2, 29, 11, -6, 9, -7, -6, -4, 0, 6, 17, -13, -2, -10,
-    -17, -1, -18, 2, 0, 14, -6, 1, 0, 3, 2, -10, 1, -5, -2, 5 },
-  { 16, -37, -1, 26, -2, -14, 1, -5, -14, 2, 2, 3, 6, 1, 1, 4,
-    0, -1, 0, -2, -2, 4, 9, -6, 0, -2, 10, -7, -2, 4, 1, 0 },
-  { -9, -24, -12, 5, 5, 3, -17, -14, 4, 3, 2, -4, 10, -22, -8, -3,
-    6, 1, 12, -8, 4, 1, 9, -1, 18, -3, 6, 5, 3, -5, 9, -5 },
-  { -14, -33, -2, 20, -13, -10, 2, -7, -1, 11, -9, -8, 18, -3, 1, 8,
-    0, -2, 10, 7, -2, -13, 9, -3, -4, 5, -2, -2, -1, -5, 1, -7 },
-  { -10, -23, 8, 14, 1, 7, 1, -3, -7, 4, 1, 1, 8, -7, 15, -14,
-    13, 14, 2, 5, -13, -5, -8, -1, 6, 3, 6, 9, 6, 15, 14, 5 },
-  { -13, -25, -10, 13, -17, -24, -7, -13, -6, -10, -8, 2, 0, -13, -10, -4,
-    -8, 4, -9, 9, -4, 4, -3, -3, 3, 3, -5, -9, 1, -2, 11, 2 },
-  { -12, -23, 1, 18, -11, -2, 5, 9, -5, 5, 14, -9, -3, -2, -6, 2,
-    -2, 11, -13, 1, -3, 11, -9, -4, -2, -6, 8, 10, 1, 4, 2, 1 },
-  { -5, -18, 16, 22, 2, 0, 8, -6, -9, -7, 10, -16, 23, 10, -11, -1,
-    7, 2, 7, 2, 1, -5, 6, 1, 0, -4, 9, 2, -3, 1, 0, -4 },
-  { -3, -26, 14, 11, 2, -9, 17, -2, -1, -5, -16, -9, -5, 10, -13, 1,
-    6, 12, 10, 11, 0, 0, -3, -14, 6, -2, 0, 4, -5, -1, -7, -1 },
-  { -10, -33, 1, 8, 11, -5, 1, -6, 7, 4, 5, 6, 1, -2, -10, -5,
-    -6, 12, -11, 5, -10, 4, 12, -1, -1, -3, 4, -1, 9, 0, 16, -17 },
-  { -14, -37, 7, 7, -2, 5, -8, -11, 2, -13, 4, -19, 1, 8, 8, 4,
-    -9, 2, -4, 3, 12, 2, 4, -4, -8, 8, 1, 4, 8, -1, 6, -2 },
-  { -6, -30, 18, 17, 1, -22, -3, 4, -7, -10, 7, 0, -8, 8, -1, 4,
-    2, 8, 6, -2, 2, 7, 4, 4, 3, -6, 2, 1, -3, 1, -1, -5 },
-  { -17, -18, -3, 22, -8, 1, 9, -2, -17, 20, -5, -5, -12, -5, 4, -5,
-    -9, 8, -2, 16, -3, 0, 19, -8, 8, 1, 2, -4, 0, 11, 0, -3 },
-  { -9, -23, 3, 10, 4, 4, -3, -2, -2, -2, 1, -22, 11, 0, -2, 5,
-    -2, 14, -9, -11, -4, 7, 5, 32, 1, -3, -7, 0, 21, -9, 7, -6 },
-  { 0, 0, 0, 2, -1, 1, 0, 1, 3, 0, 0, 1, 0, 1, 0, 1,
-    -3, 0, -1, -2, 0, -1, -1, -3, -1, 1, -4, 1, -1, -5, -69, -19 },
-  { -3, -5, -8, -12, 4, -3, -19, -11, -5, 0, -14, 7, 18, -6, 7, 22,
-    8, 14, 15, 10, 3, -1, -3, 5, -1, 7, -7, 1, -6, 3, -26, -11 },
-  { -1, -6, 4, -4, -5, -16, 0, -6, -3, 11, 1, 0, 9, 5, 16, 3,
-    -4, -33, -4, 4, -7, 0, 1, 6, -11, -2, -13, -2, -18, 20, -25, -16 },
-  { 4, 0, -1, 0, -5, 1, 0, 2, 0, 11, -10, 4, -10, 7, 16, 2,
-    16, 15, 2, -1, 2, 9, 2, 8, -3, -5, -2, 0, -3, 0, -33, -2 },
-  { -3, -15, 10, 10, -9, -1, 7, 3, 5, -5, -8, -8, -3, 15, -9, 4,
-    12, 13, -13, -14, 10, -6, 9, 22, -27, 23, -1, 5, -24, 2, -30, 5 },
-  { 0, -2, 7, -5, -5, 3, 5, 3, -3, -5, 2, 1, -4, 3, -3, -1,
-    1, -2, 10, 22, -3, -4, -2, -2, -7, 3, 8, 1, 14, 4, -37, 9 },
-  { -3, -4, -1, 1, -4, 0, 6, 2, 6, -7, -10, -10, -1, -4, 11, -3,
-    7, -6, 4, -12, -1, 5, 1, -7, 10, -6, 17, -4, 8, 3, -40, 13 },
-  { 2, 12, 4, -7, 14, -3, 16, -2, 18, 2, 13, 5, 5, 1, 11, -1,
-    0, 9, 2, -6, -1, 2, -6, 2, -5, 3, 5, 1, -1, 1, -32, -7 },
-  { -16, 11, 7, -4, 2, -5, -9, 9, 11, 11, 15, -13, -11, 11, 9, 4,
-    3, -8, -10, 12, 12, 0, 0, -16, -9, 13, 2, 9, 4, -13, -33, 3 },
-  { 6, 4, 5, 4, 3, -1, 5, 6, 4, 2, -11, -1, -15, -11, -1, 1,
-    11, -3, -2, 24, -4, -6, -25, -10, -15, -8, 0, 0, -5, 4, -30, 2 },
-  { 10, -3, -6, 1, -9, -5, 6, 9, -10, -3, 8, -1, 4, -1, 11, -11,
-    3, 9, 11, -3, 6, -17, 5, -8, -33, 9, -13, 19, -2, 9, -25, 2 },
-  { 0, 0, -1, -3, 0, -2, 1, 0, 0, 2, 1, 0, -2, 0, -1, 2,
-    0, -1, 4, -1, 2, -3, 4, -2, 3, 3, 1, 0, -15, 12, -63, 27 },
-  { -2, 14, 9, -1, 3, 0, 1, 1, -19, 15, 3, 4, 0, -10, 1, -5,
-    3, 0, -5, -10, 2, -16, -4, 8, -12, -6, 7, -5, -10, -1, -33, -4 },
-  { 0, 3, 1, 3, 1, 2, 4, 4, 9, -6, -8, -5, 1, -12, 3, 8,
-    -10, 6, -1, 1, 13, -5, -5, 2, -4, 13, -18, -10, -7, -9, -33, 10 },
-  { -6, -3, -12, 5, -1, 11, -6, 0, -2, 1, 2, -7, 3, 1, 3, -2,
-    1, 8, -10, 7, -1, -3, 3, 0, 13, 1, 6, 7, -16, -7, -39, 8 },
-  { -6, -1, 11, 6, -3, 8, 3, -5, 3, 0, -5, -2, -6, -3, -4, 2,
-    -3, 13, -11, 1, 7, 5, 19, -5, -3, -15, -1, 7, -1, 6, -33, 8 },
-  { -7, 3, -4, -3, -4, 1, 6, -5, -5, 6, -8, -1, -7, 4, -1, -6,
-    -2, 1, 7, 0, 1, 1, -5, 2, -2, 0, -13, -2, -31, -14, -39, -12 },
-  { -10, 9, 0, -3, 1, -1, -1, 0, 1, -5, -1, -4, -2, 5, 2, -7,
-    18, -8, -2, -19, -7, -7, -12, -14, -11, -1, -9, -13, -7, -12, -31, -9 },
-  { -3, -16, 10, 9, 1, -10, -12, 2, -2, 2, 7, -3, -3, 1, -4, -5,
-    -9, 5, 7, 3, -1, 4, -11, -8, 4, 13, -10, 13, 10, -4, -36, 1 },
-  { -7, -12, 4, -20, -7, -7, 2, 11, -1, -2, 3, -12, 1, 0, -6, -7,
-    6, 4, 13, 3, -3, 4, 3, -6, -12, 5, -5, -22, -13, -8, -37, -6 },
-  { -7, 5, 3, 5, 7, 9, -14, -3, 10, 17, -1, 1, -12, 5, -6, 0,
-    -4, -9, 0, -11, -14, 3, 13, 6, -25, -8, -12, 4, -10, 18, -30, -1 },
-  { -10, 6, -10, 6, 6, 1, -10, 0, -7, 5, -2, 17, -18, -4, 0, -3,
-    -16, -6, -3, -8, 5, 1, -4, 6, -7, 16, 6, 10, -1, 0, -32, -11 },
-  { -1, 9, 9, -5, 4, 9, 6, 9, -4, -2, 7, 11, 4, 2, -5, -4,
-    -6, 0, 2, -3, -1, 5, 10, 0, 12, -10, -18, -3, -1, 14, -33, 2 },
-  { 4, -8, -18, -4, -5, -11, 4, -10, -4, 9, 13, -12, 1, -6, 1, 2,
-    4, -9, 8, 3, -6, 21, 13, -1, -2, 1, -2, 6, -7, 0, -30, 1 },
-  { 6, -1, 2, -3, -1, -4, 6, -4, 0, 4, 2, 2, -9, 2, 6, 3,
-    -2, 4, -1, 9, -6, 0, 7, -8, 5, 19, -2, 9, -5, 2, -33, -8 },
-  { 2, 1, 12, -5, -8, 8, 3, -2, -4, 1, -2, 5, -4, -9, -8, -8,
-    7, -11, -4, 6, -10, 7, -1, -1, -2, -1, 16, 32, -7, 20, -33, -6 },
-  { -18, 2, 6, 13, 9, 9, -1, 3, -17, 24, -2, -6, 28, 8, -2, 6,
-    3, -10, -34, -16, -13, -4, -15, -11, -12, -3, -10, 4, -8, 4, -31, -4 },
-  { -11, 0, 18, 2, -16, -9, -13, -2, -2, -12, -3, -22, 30, 0, 8, 3,
-    9, -4, -16, 1, 0, -11, 15, -2, -4, 6, -5, 6, 1, 2, -25, -12 },
-  { 14, -1, 5, 7, 3, -15, -8, 1, 5, -2, 12, 13, 11, -25, 3, 1,
-    0, -2, -4, -16, -23, 0, -5, -17, 7, 5, -9, 6, -5, 2, -32, -7 },
-  { 3, -1, 6, 14, 2, -12, -9, -9, 4, 7, 4, 6, 5, -8, 4, 2,
-    4, 5, -2, 8, 8, -6, 0, 10, -20, -1, 3, -1, 8, 23, -33, -5 },
-  { -3, 11, -6, 3, -4, 5, 7, 3, 4, 5, -2, 3, -1, 30, 6, 1,
-    8, -6, 0, 0, -9, 6, -9, 4, 2, 9, -6, 1, -12, 0, -34, 18 },
-  { -17, 13, 0, 1, 9, -4, -11, 0, 7, 0, -10, -4, -1, 6, -6, 4,
-    1, 6, -9, 3, -5, -6, -11, 2, -4, 14, 23, -3, 2, 5, -30, 12 },
-  { -14, 5, -27, 2, 0, 7, 1, 4, 30, 8, 7, 5, 1, -1, 0, 5,
-    8, -10, 48, -11, 12, 33, 6, 8, -15, 20, -2, -5, 32, 5, -19, 10 },
-  { -16, -4, -12, -7, -2, 0, 8, -6, -20, -18, 16, -3, 0, 31, -2, 11,
-    2, -9, 49, -19, -12, -23, 10, 26, 16, -2, 4, -21, -14, 13, -11, -9 },
-  { -5, -9, -1, 3, -5, -21, 2, 10, 0, 0, 10, -21, -7, 7, -26, -9,
-    22, 32, 58, 11, -3, 11, -5, -8, -13, 6, -5, -9, 1, 10, 14, -8 },
-  { 7, 7, 10, 3, -2, -1, -11, -11, -6, -43, -3, 14, -19, -18, 19, 18,
-    -32, 10, 45, -6, 6, 21, -20, -12, 2, 4, 6, 6, -4, 3, 3, 1 },
-  { 21, 22, -3, -2, -11, -6, -1, -2, 8, 8, 32, -21, 7, 28, -4, -6,
-    -3, -2, 50, 2, 2, 27, -5, -8, 12, 7, -5, -1, -4, -17, 27, 6 },
-  { 13, 7, 2, -6, -12, 2, -10, -5, -17, 11, 4, 17, -12, -2, 5, -17,
-    37, -16, 48, -14, -18, 29, 8, 24, 11, -5, -9, 11, -1, 1, -13, -3 },
-  { 1, 1, -1, 2, 0, 0, 0, -1, 1, -1, 7, 2, -3, 3, 0, 6,
-    2, 10, 54, -25, 7, 54, -5, -6, -1, -15, 9, 13, -24, -15, -12, 3 },
-  { 21, 5, 8, 3, -3, -4, -2, -4, 3, -11, -5, -8, 9, 16, 8, -9,
-    -10, -3, 46, -46, 2, 1, -10, 10, 17, 11, -20, -36, 10, 14, 0, -5 },
-  { 7, -13, -6, -9, -24, 45, 2, 8, 8, 0, 17, 20, 12, -24, 1, -7,
-    -15, -3, 46, -13, -2, 20, 1, -13, -11, -13, 2, 15, 1, 10, -1, 3 },
-  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, -2, -1,
-    -16, -9, 31, -69, -34, 26, 7, 17, -1, -6, -1, 0, 0, 0, 0, 0 },
-  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -4,
-    -5, -20, 18, -82, 22, 3, -7, 9, 4, 6, 2, -4, -1, 0, -2, 2 },
-  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 4, -1,
-    15, -5, 62, -36, 4, 52, -7, 5, 0, 6, 1, 2, 1, 1, -1, 0 },
-  { 3, -19, 19, -20, 13, -4, -11, 8, 8, -16, 10, 1, -14, 30, 1, -33,
-    10, -11, 45, -30, 3, -4, -3, -13, 7, 12, 3, -22, 3, -2, -4, -2 },
-  { -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 2, 1,
-    11, 8, 70, 48, -10, 21, 4, 9, -9, -9, -4, -6, 0, -1, 0, 0 },
-  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0,
-    2, -1, 80, 2, -15, -36, -10, -5, -2, 8, -2, 2, 0, 0, 0, 0 },
-  { 10, 8, -8, -8, -24, 12, -1, 0, 20, 9, -1, -2, 2, -2, 12, -10,
-    -2, -13, 35, -43, 44, 15, -10, -25, 4, 10, -3, -5, -5, 7, -1, 3 },
-  { 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, -2, -1,
-    -18, 9, 49, -72, 7, -8, 7, -5, 2, 3, 2, -2, 1, -2, -3, 1 },
-  { -1, 4, -3, 10, 19, 4, 3, 20, 6, -24, 6, 9, 8, 15, 18, 18,
-    -36, 19, 57, -11, 4, -3, 8, 7, 2, -3, -2, -9, -15, -2, 12, -4 },
-  { 20, 3, 11, -9, -4, 22, 42, -25, 1, 5, -10, -19, 0, 9, -16, 5,
-    2, 10, 44, -29, 17, -3, -9, -2, -1, 8, 14, -7, -1, 16, -5, 1 },
-  { -7, 16, -11, 12, 6, 33, -15, 14, -23, 2, -26, 8, 2, 10, 0, -5,
-    8, -8, 38, -38, -4, 5, 5, 5, 1, 22, -15, 7, 6, 0, 4, 28 },
-  { -1, -12, 2, 10, -2, 0, 7, 17, 12, 22, -4, 10, 25, 29, 5, 18,
-    4, 1, 27, -39, 31, 17, 2, 2, 22, -23, 13, 16, 1, -7, -4, -5 },
-  { 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, -2, 0, -14, 0,
-    -7, -11, 49, -22, -4, 19, 17, -39, 4, -29, 10, 2, 36, -4, 23, -1 },
-  { -2, -2, -2, -2, 1, 15, -5, -7, -16, -8, -19, 16, -3, -20, 36, -9,
-    -3, 20, 39, -20, 0, 2, 27, -16, 10, 10, -14, -22, -16, -3, 13, -8 },
-  { 5, -9, 6, -25, 7, 37, 13, -10, -5, 3, -5, 7, 18, -22, -7, 9,
-    -5, -4, 50, -11, -4, -5, -5, 8, -4, -2, -4, -27, 14, 20, 7, -9 },
-  { 0, -14, -10, -27, -14, -17, -6, 26, 10, 2, 14, -12, -5, 0, 8, 9,
-    0, -28, 55, -7, -12, -7, 4, -10, 10, 7, -12, 11, 3, 5, 9, -8 },
-  { 2, 23, 4, -2, -1, -20, -2, 14, 10, -9, -9, -24, 10, 0, 11, -12,
-    12, 11, 49, -25, -2, 29, 7, -13, 21, -10, 11, -17, 3, 1, -8, 5 },
-  { 3, 0, -14, -6, 18, -2, 17, -9, -19, 9, -5, 9, 14, 6, 19, -3,
-    27, 1, 41, -21, 20, -15, 33, 0, 26, 14, 7, 10, 3, 20, -3, -12 },
-  { -1, 16, 15, -8, 3, -8, -8, 21, -5, -16, -29, 4, 1, -6, -4, -28,
-    2, 31, 37, -26, -2, 13, 24, 8, -9, -6, -29, 10, 7, 2, 7, 8 },
-  { -10, -10, 11, 13, -32, 2, 16, 9, 14, 23, -15, -13, 24, 13, 4, -27,
-    14, 12, 31, -18, 17, 23, -2, -7, -14, 9, -17, -6, -10, 20, 9, 6 },
-  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0,
-    5, 1, 89, 8, 10, -6, 2, -1, 0, 0, 0, 0, 0, 0, 0, 0 },
-  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, -1,
-    4, -7, 64, -50, 7, 37, 2, 5, 0, 0, 0, 0, 0, 0, 0, 0 },
-  { -2, 5, 3, -4, -4, -3, 2, -3, 3, -3, 5, 4, 1, -6, -1, 1,
-    6, -2, 50, -35, -7, 43, 7, -7, -5, -26, 24, 21, 3, -15, 5, 6 },
-  { -8, 21, -19, 33, -8, 22, -11, 17, 3, 0, 0, -2, 1, -3, 6, -1,
-    10, -8, 4, -11, -4, -5, 0, 8, -4, 3, 1, -4, 4, 2, 8, 4 },
-  { -7, 5, -20, 9, -22, 3, -14, 1, 6, 13, 23, -2, -4, -7, 2, 0,
-    11, 4, 6, 3, -7, -11, -7, 4, 5, 5, -12, 8, 2, 4, 7, -3 },
-  { -7, 6, -4, 20, -20, 16, -2, 7, 6, 16, 11, 12, -7, -7, 5, 3,
-    -9, -4, 1, 2, 5, 2, 1, -9, -2, -17, -4, 6, -10, 7, -7, -6 },
-  { -9, 18, -17, 12, -24, 1, -1, 4, 14, 9, 4, 3, 2, 8, -12, -14,
-    4, -8, -4, 7, 7, 6, -1, 13, -9, -4, -1, 1, 0, -4, 15, 8 },
-  { -25, 2, -11, 6, -5, 24, -28, -5, 8, 12, -2, 6, 8, -3, 8, -9,
-    -1, -5, -1, -5, 6, -1, -1, -1, -4, 8, -12, -2, -13, 7, 2, 1 },
-  { -14, 14, -18, 20, -10, 12, -2, 9, 1, 0, 12, -2, 15, -10, 26, -17,
-    16, -11, 10, -10, 9, -2, 4, -8, 2, -3, 4, 4, 2, -3, -5, 1 },
-  { -18, 12, -18, 21, -6, 12, -6, 13, -25, 18, 1, 11, -9, -5, 0, 10,
-    -5, 3, -3, 8, -9, 7, 4, 2, -9, 0, 5, 0, 2, -3, 9, -8 },
-  { -4, 16, 1, 18, -30, 9, 1, 6, -8, 13, 13, -12, -6, -1, 13, 7,
-    6, 2, -15, -3, 5, 5, 1, -6, 1, -5, 0, 2, -16, 0, 3, -4 },
-  { -21, 1, -2, 6, -43, 18, -1, 5, -1, 4, 6, -2, -1, -3, -1, -3,
-    0, 1, 2, -9, 0, -1, 0, -2, 0, -1, -1, -2, 6, 0, 1, -2 },
-  { -23, 10, 4, 7, -32, -11, -18, 2, -2, -7, -6, -3, -3, -12, 19, 3,
-    -5, -6, 16, -6, 16, 2, 16, 16, 8, -2, 13, 8, -15, -11, 2, 10 },
-  { -8, 2, -13, 2, -29, 24, -20, 19, 1, 10, -4, 10, 1, 2, -9, 11,
-    -1, -2, 9, -5, 19, -7, 16, -9, -2, -18, 11, 1, 1, 0, 7, -3 },
-  { -6, 3, 4, 13, -26, 10, -10, 28, -7, 28, 1, 7, 0, -14, 5, 7,
-    4, -4, 3, -2, 3, 3, -11, 7, 6, 4, 0, -1, 2, -1, -3, 2 },
-  { -6, 16, -31, 13, -10, 17, -6, 4, -14, 4, 4, -1, -10, 12, -5, 1,
-    -14, 15, 0, -8, 1, -5, 3, 3, 9, -5, 7, -20, 7, 4, 11, -5 },
-  { -19, 3, -17, 14, -12, 16, -22, 18, 14, 8, -2, 4, 10, 12, -14, 4,
-    -3, 2, 3, 7, -7, 7, -6, 2, -2, -4, -5, 0, -5, -2, 2, 1 },
-  { -9, -7, -11, 24, -36, -9, -11, 5, 7, -12, -13, 18, -2, 20, 1, -4,
-    -1, -10, 15, -6, 14, 1, 0, 2, 1, 2, -9, -16, -11, 7, 13, 0 },
-  { -24, 24, -18, 18, -22, 14, -11, 13, -12, 11, -10, 11, -7, 11, -5, -4,
-    -1, 1, 5, 2, 3, -1, 1, -5, 7, -4, 5, -6, 8, -7, 8, -6 },
-  { -6, 18, -22, 22, 5, 11, -1, 6, 19, 22, 8, 4, -8, 20, -2, 15,
-    -6, -18, 0, -33, -9, -12, -1, 6, 5, 2, 5, 5, -5, -17, -3, -3 },
-  { 1, 11, -16, 9, -18, 11, -4, 18, 20, 26, -10, 8, 1, -11, 8, -4,
-    0, 7, 3, 5, 2, 2, 10, -2, -4, 4, -4, -2, 1, -4, -5, -1 },
-  { -10, 6, -1, 18, -17, 27, -3, 10, -2, 12, -7, -9, 1, 1, -1, 7,
-    -12, -1, -7, -6, -1, 8, 3, -15, 8, 9, 3, -7, 4, -1, 1, -1 },
-  { -14, 6, -16, 22, 2, 5, 0, 5, -18, 11, 6, -3, 22, -20, -9, -3,
-    6, -6, -7, -15, 1, 15, -8, 11, 8, -3, -8, 1, -8, 2, 6, -2 },
-  { -21, 5, -19, 19, -7, 4, -7, 0, -8, 6, 12, 5, -3, -22, -13, -6,
-    -1, -3, -2, -14, 6, -3, 1, -8, -7, -5, -6, 11, -3, -10, -5, 2 },
-  { -1, 9, -12, 15, -6, 6, -19, 14, -9, 11, 3, 12, -17, -3, 8, -4,
-    -3, -4, 1, -5, 4, 5, -7, -15, -7, 15, -6, -5, 1, -5, -3, 1 },
-  { -12, 20, -15, 20, -14, 3, -14, 9, -6, 33, -13, 6, -2, 8, -6, 7,
-    -5, -6, -3, -3, 0, 8, -3, -3, 1, -2, 2, 2, 6, -5, -5, -2 },
-  { -7, 12, -18, 12, -18, 10, -4, 8, 2, 4, 8, 9, 0, 3, -8, 3,
-    6, -12, -4, 1, 25, -5, -9, 6, -7, 0, -9, -7, 3, -5, -4, -4 },
-  { -18, 12, -10, 11, -22, 0, -15, 5, -2, 2, -3, 6, -4, -4, -3, -15,
-    -2, -3, 21, 6, -12, -11, 19, 3, 3, -14, 7, 0, -11, -22, -10, 0 },
-  { -15, 2, -30, 15, -17, 13, -16, 8, -7, 10, -8, 2, 11, 3, 10, -7,
-    7, -22, 12, -10, 3, -12, 6, -10, 12, -10, 7, -8, 5, 2, 9, 1 },
-  { -9, 11, -14, 6, -10, 21, 5, 12, -5, 5, 7, 21, 6, 2, -2, -1,
-    -1, 4, 2, -20, -18, -1, -14, 3, -1, 4, -7, 10, 1, 11, 4, -4 },
-  { -22, 8, -30, 13, -21, -4, 4, -1, 12, 9, -2, -3, 2, -6, 4, -13,
-    -2, 8, 8, 1, -7, 3, -4, -5, -1, -7, -2, 8, 8, 7, 8, 0 },
-  { -6, -4, -35, 16, -13, 15, -11, 14, -7, 9, -1, 11, 7, 0, 13, 10,
-    -1, 8, 1, 1, -2, 8, -1, 2, 2, 3, -10, -1, 7, -13, -3, -7 },
-  { -15, 7, -16, 14, -18, 17, -6, 14, 3, 4, 7, -3, 10, -22, 5, -15,
-    4, -4, -11, 15, -15, 11, -11, 20, 1, 0, 2, 1, 11, -3, 11, -7 },
-  { -12, 3, 5, 16, -37, -1, 15, 15, -15, 10, 3, -10, 1, 15, 7, -15,
-    -13, 8, 9, -3, 2, 12, -8, 2, -5, 0, -3, 4, 5, -9, -4, 5 },
-  { -16, 26, -4, 14, -22, 26, 6, -3, -8, 4, 21, 6, 16, -4, -11, 7,
-    -10, 3, 3, 7, -4, 2, -9, 8, -2, 2, 5, -2, -4, -2, 7, -1 },
-  { -7, -10, 4, 3, 2, -4, -12, -10, -4, -5, 16, 19, -16, 1, 2, -9,
-    -10, 0, 9, 7, -8, 3, 12, 8, -6, -11, -13, -1, -3, -20, 6, -5 },
-  { -14, -17, 3, -5, 14, -12, -12, 8, -6, -25, 21, 21, 10, -8, -12, 4,
-    10, -4, 3, -9, 11, 9, 0, 4, 2, -15, 1, -14, 4, 1, 0, -4 },
-  { -4, -9, -3, -1, 6, 3, -6, 6, -10, -4, 14, 8, 2, -3, -12, -19,
-    0, 11, -20, 1, 6, -2, -27, -6, 10, -17, -14, -17, -9, 8, -8, 3 },
-  { -12, -13, 16, -4, -2, 12, -7, -11, 2, -13, 3, 7, -16, -18, -1, -12,
-    -2, 1, -12, -9, -2, -6, 2, 9, -22, -3, -4, -14, -7, 7, -1, 2 },
-  { -7, -8, -8, 15, 15, 18, 15, 16, -4, -37, 11, 15, -12, -1, -3, 3,
-    6, 6, 0, -5, -3, -5, 9, 1, 1, -11, -1, -8, -6, 2, 3, 0 },
-  { -6, 7, -5, -12, 13, 10, -18, -4, -3, -21, 6, 16, -15, -7, -12, -9,
-    1, -12, -1, 10, -2, -1, -3, 4, -4, 1, -16, -1, 12, -9, 5, 9 },
-  { -14, -5, 9, 3, 4, 26, -28, 3, -6, -24, 4, 5, 3, 13, 5, -1,
-    3, -1, 3, 1, 1, -5, 3, 0, -7, -8, -7, -3, 3, -5, 4, 0 },
-  { -4, 2, -10, -6, 25, 26, -6, 10, -6, -8, 15, 11, -6, -3, 2, -7,
-    5, 14, 9, -1, 0, -12, 4, -4, -10, 1, -3, 3, -2, -2, -6, -1 },
-  { -10, 8, -15, -10, 19, 17, -8, 0, -3, -7, 7, 5, -13, -1, 7, -7,
-    1, 13, -12, -13, 17, -12, 1, 26, -18, -3, -5, -6, 4, 5, 8, 1 },
-  { 2, -5, 3, 0, 0, 0, 2, -3, -2, -5, 7, 13, -4, 9, 0, -5,
-    4, -1, -11, -8, -4, 0, -13, 2, -47, -23, -8, -11, -4, 4, -2, -3 },
-  { -18, -4, 4, 5, -1, 17, -12, -8, 1, -12, 7, 20, -12, 3, -2, -11,
-    16, 12, -6, 1, -13, -16, -6, -3, -3, -5, 4, -12, -5, -9, 10, 1 },
-  { -11, 0, 4, 7, 7, 8, 3, -1, 3, -19, 32, 8, -19, -8, 2, 4,
-    -12, 15, -16, 3, 1, 9, -2, 1, -2, 8, 5, 6, -4, -1, 11, -8 },
-  { 3, -1, 4, -2, 14, 32, -9, -23, -10, -12, 22, 15, -1, -2, 10, 0,
-    4, 6, -8, 4, -15, -2, -1, -4, 0, -8, 4, 1, -8, 3, 4, 1 },
-  { -17, -12, 6, -8, 16, 13, -20, -8, -1, -16, 10, 21, -19, 11, -9, -5,
-    7, 18, -6, 7, -7, -18, 13, 2, -2, 8, -12, -9, 2, 4, -5, 16 },
-  { 4, 0, 17, -11, 12, 7, -12, 5, -1, -25, 30, -8, -7, -6, -4, -7,
-    9, 8, 7, 3, 3, -16, 8, 0, -2, -2, -18, -3, -4, -5, 1, 4 },
-  { -3, -6, 6, -16, 17, 6, -3, 2, -9, -17, 12, 11, 11, 2, -20, 8,
-    1, 1, 0, 2, -2, -6, -21, -13, -9, -15, -1, -8, -6, -8, 0, -2 },
-  { -11, -7, 6, -9, 3, 6, 8, 16, 4, -5, 23, 26, -10, -3, 4, 0,
-    2, 2, -4, 4, -2, -12, 12, 10, -11, 0, -10, -16, 3, 0, 0, -10 },
-  { -5, -16, 10, -6, 27, 13, -3, 4, -2, -13, 15, 5, 2, 5, 3, -4,
-    13, 12, -11, -7, 0, 1, 11, 12, 2, 13, -15, -8, 9, -2, 3, 8 },
-  { -5, -8, 4, 3, 9, 3, -11, 10, 14, -25, 14, 8, -2, 5, -12, -21,
-    2, 10, -7, 2, -3, 2, 0, 2, -1, -3, -5, -6, -1, -16, 2, 8 },
-  { -1, 5, 1, -11, 5, 9, -7, 8, -13, -12, 4, 12, -4, 1, -1, -1,
-    27, 29, 10, 15, 2, -6, -3, 4, -21, 10, -9, -11, -6, -1, -9, -3 },
-  { -6, -3, -1, -6, 11, -5, 0, -2, -5, -31, 11, 3, -1, 5, -3, 4,
-    5, 7, -10, 5, -10, -13, 4, 12, -15, -2, 2, -7, 1, -9, -3, -10 },
-  { -3, -7, 17, -8, -5, 36, 8, -7, -8, -20, 12, 8, 1, -1, 3, 0,
-    1, 4, -10, 3, 1, 4, -2, -3, -2, -3, -10, 4, -1, -7, 3, 2 },
-  { -13, -3, -5, 9, 22, 6, -23, 3, -10, -7, 17, 17, 18, -14, -8, -8,
-    2, 4, -8, 2, -3, -8, 6, 4, -1, 7, 0, 0, -3, 0, -12, -3 },
-  { -3, -10, -15, -3, 9, 3, -23, -9, -13, -18, 12, 13, -2, 0, 1, 8,
-    -1, 2, -7, -12, -5, 14, 2, 1, -22, 6, -10, -8, -9, 28, -7, -14 },
-  { -3, 1, 2, -1, 13, 7, -2, -7, 1, -3, 6, 9, -3, -2, 4, -2,
-    2, 1, -10, -2, -2, -22, -2, -7, -10, -5, -11, -27, -12, -16, 4, -7 },
-  { 2, -6, -3, 1, 8, 0, -2, 12, -3, -4, 58, 15, -10, -4, -2, 2,
-    -2, 0, -2, -6, 2, 4, -1, 1, -4, 1, -1, -5, -4, -3, 3, 1 },
-  { 10, -1, 0, 5, 21, 7, -14, 6, -3, -16, 15, 17, -16, 13, 3, -6,
-    -4, 6, -12, -5, 1, -4, -7, -8, 2, 3, -6, 6, -1, -8, 5, 4 },
-  { -6, -2, -8, -11, 15, 10, 0, 8, -6, -15, 33, 8, -2, 18, -15, -11,
-    5, -1, 0, 15, -15, -4, -4, -1, 10, 7, -13, 4, -4, 0, 8, 3 },
-  { -7, -2, 0, -2, 0, -2, -4, -5, -14, -16, 12, 38, 7, 12, 6, -4,
-    0, -1, 0, 3, -2, -6, 0, 2, -9, 1, 0, -1, 0, -2, 4, 1 },
-  { -8, -4, 18, 1, 14, 5, -12, -3, 20, -17, 5, 19, -11, -8, 11, -3,
-    3, 9, -7, -8, 9, -17, 2, 15, -10, -11, 5, -5, 7, 15, -6, -2 },
-  { -7, 2, 38, 5, 19, 16, -5, 4, -13, -20, 0, 4, -4, 6, 4, 2,
-    -7, 6, -8, -2, -5, -7, 6, 3, -4, -3, -2, -3, 7, -6, -4, 0 },
-  { -11, -12, 8, -15, -3, 14, -7, -22, -11, 2, 22, 14, -19, 2, -19, -6,
-    1, 3, -18, 14, 2, -6, -2, -8, -3, -6, 5, -7, -8, -4, 1, 1 },
-  { 8, 7, 25, -21, 12, -6, -5, -4, -10, 6, 0, 10, 1, -12, 18, -5,
-    -15, 4, 1, 14, -1, 5, 8, -7, 1, -7, -3, 9, 10, 1, -1, 0 },
-  { 9, 10, 32, -15, 8, 2, 11, -7, -18, -8, 2, -6, -9, -16, -3, 3,
-    -1, 3, 1, -5, 4, -2, 1, -8, 0, -6, -3, -11, 1, 5, 0, 0 },
-  { 14, 0, 23, -25, 22, 3, 7, 10, 0, -2, 7, 8, 0, 10, 0, 0,
-    3, 2, 3, -10, 0, 10, 0, -7, 0, 10, -1, -5, -7, 1, -1, 2 },
-  { 12, 0, 25, -18, -5, -4, 13, -10, 3, -6, 7, 21, 0, -16, 3, -10,
-    -6, 5, -7, -3, 2, 5, 3, -6, 4, 9, -8, 12, -2, 3, 2, 4 },
-  { 31, 15, 27, -20, 10, -7, 15, -10, 9, -8, 4, -5, 3, -3, 5, 6,
-    11, -2, -12, -2, 6, -2, 1, 2, -1, -1, 1, 1, 3, 1, 1, 2 },
-  { 12, -4, 13, -23, 12, -6, 2, 4, -3, 13, 6, -7, 5, -19, -7, 18,
-    1, -7, 7, 1, 16, -7, 3, 0, 3, 0, -12, 8, -11, 9, 4, 7 },
-  { 29, 1, 3, -22, -5, 6, 0, 12, -14, 11, 1, 6, -3, 4, 6, -2,
-    4, -13, 12, 1, 1, 3, -11, 9, -10, -1, -7, 16, -11, -1, 3, 9 },
-  { 4, 4, 36, -23, -5, -8, -15, 1, -6, 3, 13, -1, -5, -7, 4, 9,
-    2, -11, -3, 5, 1, 3, -6, -1, -4, -4, -2, 2, 3, -1, -5, -2 },
-  { 19, 10, 6, -17, 2, -4, -2, -4, -3, 13, 2, 2, -13, -7, -3, -11,
-    9, -6, 1, -9, -5, 4, -5, -9, -18, -7, -11, 9, 4, -11, 8, 4 },
-  { 16, -3, 9, -16, 18, -2, -12, -16, -11, 11, -18, 16, -13, 6, 2, 8,
-    3, 8, -4, -16, 10, -11, -1, -3, -8, 5, -9, -4, 9, -4, 0, -3 },
-  { 14, 15, 3, -23, -5, 7, -8, -6, 2, 17, 2, 12, -8, -12, 13, -1,
-    -9, 3, 1, 1, 19, 15, 4, -1, 1, 2, -3, 2, -3, 1, 5, 3 },
-  { 32, 5, -10, -47, -5, -1, 4, 11, -7, 0, 2, -2, 1, -7, 6, -4,
-    6, 2, -4, -2, 2, -2, 0, -4, 1, -6, -5, 2, -2, -1, -3, -4 },
-  { 20, 8, 10, -21, -7, -9, -16, 12, 1, 4, 6, -5, 9, -11, -7, 4,
-    -11, 28, -3, 2, 4, -6, 10, -8, -5, -5, -9, 9, -2, -1, 6, -5 },
-  { 38, 3, 23, -25, -6, -18, 3, -10, -8, 6, -10, 1, -10, 2, 2, 0,
-    -7, 2, -4, 5, -1, 8, -3, 0, 3, 3, -1, 1, 0, -4, -4, 0 },
-  { 20, 5, 16, -22, 24, -18, 2, -12, -14, -7, -3, 10, 2, 7, -10, 2,
-    -8, 1, 8, -1, 4, 1, 4, -2, 5, -9, -18, -8, -13, 5, -11, 10 },
-  { 14, 8, -12, -16, 9, -11, -3, -6, -25, -7, 6, 5, -7, -16, 10, 2,
-    -7, -1, -9, -3, 16, 4, 3, 3, -3, -3, -15, 13, -3, 4, 13, -7 },
-  { 16, -9, 19, -23, 7, -19, -3, -5, -15, 11, -21, 21, -16, 18, -1, 6,
-    10, -10, 18, -14, 16, -15, 6, -5, -9, 5, -17, 13, -10, 13, 0, 10 },
-  { 8, -4, 4, -24, 8, -21, -18, 9, -11, 4, -6, 17, 5, -9, -2, -2,
-    2, 15, -2, -3, -2, 1, 7, -13, 15, -10, -8, -11, 3, 3, -1, -1 },
-  { 14, 17, 6, -32, 5, -17, -2, 0, 15, -1, -5, 16, 1, -5, -2, 9,
-    -3, 8, 4, -2, -2, -4, -3, 1, 0, 7, -3, 4, -5, 0, -7, 2 },
-  { 24, 6, 22, -12, 8, 3, -14, 4, -7, 8, 6, 5, 6, 1, 6, -12,
-    15, 10, 4, 11, 9, 6, -7, -4, 10, -9, 2, -1, -5, 11, 15, 3 },
-  { 17, 12, 3, -23, 5, -1, -2, 1, -9, -1, -3, 1, 8, 1, -5, 17,
-    11, 0, -2, -11, 7, 4, 0, -27, -7, 1, 2, -8, 9, 7, 5, 3 },
-  { 12, 10, 12, -10, -4, 5, -1, 2, -24, 5, -8, 2, 6, -17, 19, 5,
-    12, -2, 16, -7, -6, -14, 4, 1, -3, 13, -16, 5, -1, 4, 1, 1 },
-  { 31, 9, 11, -17, 10, -3, -7, 7, 1, 2, 2, 4, -3, -1, 11, 4,
-    -5, -8, 1, 4, 15, -6, -28, 1, 8, 3, -6, 5, 17, -2, 2, -4 },
-  { 11, 19, 16, -26, 0, -7, -7, 2, -13, -15, -12, 9, -3, 27, 8, 4,
-    -6, 1, 4, -6, 11, -1, -6, -7, -3, 0, -6, 4, -6, -7, -3, -1 },
-  { 10, 18, 16, -32, 19, -9, -4, -3, -7, 8, 8, -3, -11, -2, -6, -16,
-    13, 13, -6, -1, 10, -2, -2, -9, 0, -3, 9, 4, 11, -2, -6, 6 },
-  { 9, 4, 19, -33, 4, 7, -12, 36, -3, -1, 8, -2, 2, -8, -9, -4,
-    -8, 0, 1, -1, 0, -4, -4, 3, 0, 3, 6, 0, -6, 2, 0, -2 },
-  { 25, 7, 15, -12, 2, -24, -1, 24, -4, 4, 9, 0, -2, -9, 4, 6,
-    3, 13, -3, 1, 5, -1, -3, -5, -1, 7, -2, 3, 4, 4, 1, 0 },
-  { 19, 6, 8, -20, 9, -9, 5, -4, -13, 7, 11, -3, 5, -13, -9, 6,
-    -11, -1, 0, 4, 11, 26, 3, 6, -7, 12, 6, -3, 1, -9, 7, 1 },
-  { 15, 6, 19, -23, -3, -9, 3, 16, -6, -4, 6, -5, -10, 1, 16, -14,
-    2, 0, 2, -13, -3, 8, -6, 3, 1, 1, 2, -5, 12, -4, -8, -3 },
-  { 14, 4, 16, -20, 1, 12, 0, 6, -3, 9, 4, 16, 10, -16, 5, 7,
-    5, -4, -4, -18, -3, -11, -4, 4, -7, 3, 13, 7, 3, 3, 2, -7 },
-  { 22, 3, -1, -30, 18, -3, -9, 9, -2, 11, -16, -2, -14, 12, 0, 4,
-    -5, 4, -1, 3, -20, 12, 4, -10, -2, -2, -12, -12, 10, 6, 11, -3 },
-  { 15, 7, 2, -21, 5, 4, 9, -9, -33, 7, 7, 3, -6, -14, -8, 10,
-    12, 0, 2, -1, 5, 4, -2, 0, -7, 0, 2, 4, 0, 1, -3, 8 },
-  { -7, 0, 12, 3, 0, -6, 8, -4, 0, 2, 14, -15, 2, -7, -31, -3,
-    14, 0, 14, -15, -1, -4, -15, 10, 1, -3, 1, 2, 5, 2, -8, 1 },
-  { -2, 5, 1, 0, -3, 3, 3, -6, -1, 2, -4, 1, -19, 0, -11, 18,
-    11, 10, 21, 5, 6, 2, 10, 3, -6, 0, -2, 13, 5, -1, -2, 9 },
-  { -9, 1, -5, 0, 0, -15, 8, 4, 8, 3, 8, 12, -13, -2, -39, -2,
-    4, -4, 5, -3, -4, 3, -3, 3, 10, 5, 3, 2, -3, 5, -2, 8 },
-  { -9, 6, 6, -8, 12, -12, 23, -18, 4, -15, -5, 2, -20, 13, -7, 7,
-    7, -12, 14, -12, 6, 1, 1, -3, -8, 9, 0, 1, -7, 3, 7, -6 },
-  { -18, 13, 4, 3, -10, -30, -10, -6, -14, 1, -7, -4, -35, 5, -25, 11,
-    9, 8, 19, -4, -7, -3, -18, -8, 1, 5, 10, -4, -14, -9, 3, -4 },
-  { -6, -1, 4, -9, -9, 4, 20, 0, 0, 3, 11, 7, -16, -17, -20, 11,
-    -6, -14, 1, 4, 19, 2, -8, 6, -15, 3, 6, -5, -14, 3, 7, 2 },
-  { 1, 6, -2, -8, -5, -3, 3, -8, 21, 1, 3, 16, -14, -2, -9, -4,
-    13, -2, 18, 14, 14, 19, -13, 5, -10, 2, -3, 3, 5, 5, 1, -1 },
-  { -1, -5, -6, -2, -11, -7, 5, -4, 5, -1, 0, 3, -3, 2, -19, 18,
-    16, 4, 14, -22, -2, -11, -22, 1, -1, 11, 1, 2, 11, -10, 7, -12 },
-  { 1, 4, 5, -1, -9, -5, 1, 12, 5, 6, 12, 9, -24, 23, 1, 20,
-    14, -11, 13, 5, -2, -2, 5, 6, 2, 1, -9, 6, 10, 5, -4, 11 },
-  { -1, -1, 1, 7, -3, -4, 8, -16, 15, -1, -7, 9, -22, -11, -11, 10,
-    16, 9, -2, 4, 13, 10, 6, 16, 4, 7, 1, -8, -7, -14, -7, 4 },
-  { 1, 3, -6, 0, 15, -9, -4, 0, 4, 6, 12, 9, -6, -5, -22, 17,
-    7, -11, 15, -5, 1, 3, -19, 0, -15, -3, 16, 5, 5, -7, -11, 12 },
-  { -2, -1, 13, 2, 4, -24, 37, -5, -2, -6, 12, 7, -2, -23, -4, 9,
-    2, -3, 3, 2, 3, 3, -14, 11, 0, -4, -2, -2, 3, 10, -10, 4 },
-  { 2, 9, 8, -6, -28, 14, 28, -11, 18, -11, 0, 2, -2, 4, -12, 3,
-    6, 0, 7, -7, -6, 2, 5, -1, -1, -1, 5, 2, 3, 0, -3, 9 },
-  { -7, 14, 5, -10, -3, 7, 4, -5, 7, -8, -7, 4, -12, 14, -16, 25,
-    3, 0, 1, -5, 12, -10, 0, -10, 0, 12, 12, 17, 12, 10, -1, 0 },
-  { -4, -2, 5, -2, -17, -3, 5, -5, 7, -17, 1, 5, -4, 4, -20, 0,
-    11, -15, 13, -8, 10, 1, 1, 5, -12, 9, -8, 0, 6, -1, -11, 4 },
-  { -3, 12, 13, -15, -7, -7, 0, 5, 33, 3, 3, -6, -13, -7, -15, 10,
-    3, 3, 3, -5, 2, 7, -1, 0, -12, 2, 11, -6, -9, 0, 5, 11 },
-  { -8, 5, 10, -7, -14, -4, 13, 0, 18, -3, -6, 7, 1, -6, 0, 21,
-    8, -7, 10, -8, -3, 17, -9, 0, -5, 1, 4, 8, -3, 11, -5, 0 },
-  { -8, 8, -3, -8, 8, -11, 16, -16, 17, 0, 8, 16, -17, 10, -16, 10,
-    -8, 6, 11, 0, 10, 7, 4, 5, 7, -5, -5, -6, -7, -5, -1, 16 },
-  { -6, 0, 6, 1, -8, -8, 8, -7, -5, -10, -11, 8, -19, 6, -7, 13,
-    5, -3, 4, -8, 7, -1, -18, 9, 0, -5, 6, 26, 3, 8, 2, 4 },
-  { -2, -2, 23, -2, -20, 2, 7, -7, -6, -15, 3, 9, -19, -2, -10, 7,
-    -2, 7, 9, 11, 0, 4, -4, 6, 9, -2, 4, -3, 4, 3, 2, 8 },
-  { -6, 12, 10, -10, -7, 4, 17, 11, -6, 1, 12, 11, -18, 8, -12, 4,
-    1, 13, 6, -13, 23, 9, -5, 8, -2, -5, 1, 3, 0, -2, -4, 4 },
-  { 7, 1, 7, -17, -8, 8, -1, -7, 5, -6, 4, -3, -16, 9, -24, 18,
-    -3, 10, 13, -11, -6, -11, -4, 10, 0, 11, 8, 2, 6, -5, -11, 4 },
-  { -4, 1, -5, -10, 0, -3, 9, -2, 4, -1, 1, 5, -41, -10, -7, 4,
-    -3, 3, 1, 0, -12, 4, -3, 0, 2, -1, -2, -5, 3, 2, -7, 5 },
-  { -2, 1, 4, 4, -3, -6, 1, 0, 12, -5, 11, 0, -17, -3, -1, 11,
-    4, 1, 27, -12, 0, -14, 2, -15, -3, -9, 0, -7, -3, 15, -8, 6 },
-  { -6, 4, 9, 2, 4, 3, 7, -10, 28, 1, -2, 48, 7, 0, -10, 10,
-    1, -9, 2, -1, 0, 3, -5, 5, -4, -2, 7, 7, 1, 3, 2, 5 },
-  { -3, 3, -1, 3, -9, 0, -1, 3, 2, -6, 39, -14, -12, 5, -19, 21,
-    7, -6, 4, -1, -4, 0, -4, 1, 0, -9, 1, 10, 0, -2, 0, 7 },
-  { 4, 2, -29, 12, 5, -3, 16, -6, 15, -13, -4, -1, -13, 22, -16, 17,
-    16, 4, 9, -4, 4, -6, -4, 11, -8, 7, 8, 4, 3, -3, -7, -13 },
-  { 0, 3, 3, -6, -4, 0, 9, 0, 5, 0, 10, 10, 4, -13, -12, 16,
-    23, -4, -12, -6, -4, 20, 2, 0, -4, 23, 1, 8, 11, -4, -5, 15 },
-  { -6, 4, -15, -9, -1, -19, 12, -30, -17, -4, 1, -13, -13, 4, -3, 26,
-    5, -25, 11, -14, -6, -13, 0, -7, 9, 2, 8, -1, -8, 1, -8, 13 },
-  { 1, 6, 1, -4, -4, 1, 2, 0, -3, 2, 10, 6, -6, -2, -11, 4,
-    32, 15, 15, -47, -8, 3, -12, 4, -5, 4, -1, 0, -5, 5, 1, -7 },
-  { 2, -1, 0, 0, -1, -6, 0, -6, 4, -4, 5, 9, -5, 1, -3, 51,
-    4, -5, 4, -14, -1, -4, -3, 1, -4, -1, 0, 2, -8, 0, 1, 2 },
-  { 0, 4, -2, -7, -2, -9, 6, -8, 11, -3, -6, 3, -11, -8, -12, 8,
-    11, 5, 19, 3, -24, 19, -14, 11, -5, -18, -8, -12, -5, -4, -1, 4 },
-  { 16, 9, 10, 14, -18, -2, -18, -27, 10, -5, 12, 14, 4, 0, -2, -6,
-    -12, -7, -1, 3, 4, 7, 11, 10, 5, -5, -7, -16, -3, -6, 6, 9 },
-  { 7, 15, -9, 10, -19, 4, -5, -37, -2, -4, 8, 2, 4, -1, 1, 9,
-    -5, -5, -12, 1, -1, -8, 3, -3, 4, 6, 9, 3, 3, -1, 2, 4 },
-  { 13, 17, 3, 9, -7, -7, -15, -17, -8, -13, -4, -8, 19, 2, 16, 25,
-    7, 15, 2, 16, -5, -6, -10, -9, -7, -6, -2, -7, 7, 2, 4, 5 },
-  { 24, 7, 9, 8, -13, -2, 0, -4, 1, -13, 3, 6, 7, 10, -4, 15,
-    5, 7, -4, 5, -5, 3, 13, -7, 5, 15, -11, -2, 7, 5, 8, 6 },
-  { 17, 6, -15, 23, -2, -1, -6, -2, 0, -4, 11, -3, 12, 15, 6, -8,
-    -15, 10, -9, 7, -1, -11, 2, -8, -4, 3, 4, -10, 4, 4, 11, 1 },
-  { 21, 12, -3, 6, -8, 8, -11, -8, -5, -5, 3, 7, -1, -5, 12, 15,
-    -10, -11, 3, 15, 8, 4, 2, -15, 0, 14, 1, -8, -1, 3, 10, -7 },
-  { 16, 12, 5, 13, -6, 15, -23, 0, -17, -9, 0, 4, -9, 13, 6, 18,
-    0, 0, -4, -1, 0, 14, 5, -1, 8, -4, -8, -6, 5, -2, -2, 0 },
-  { 14, 16, -1, 12, -15, -9, -6, -20, 4, 6, 8, 9, 3, 1, -9, -4,
-    -1, -11, 9, 11, -12, 1, -14, -7, 2, -8, 11, 9, -4, 10, 4, -16 },
-  { 13, 10, 3, 7, 0, -8, -33, -6, 4, -4, 19, -2, 14, 6, 5, 7,
-    6, -3, -1, -10, -10, -9, 4, -3, 5, 9, 2, 2, 10, 9, -2, -3 },
-  { 11, 10, 25, 18, -1, -6, -21, -21, -11, -16, 6, 5, 14, 4, 8, 7,
-    0, -10, -7, -9, -5, -4, 3, -1, 1, 6, -1, 6, -2, 2, -3, -9 },
-  { 15, 9, 5, 22, -17, 15, -9, 7, 7, -9, 13, 9, 10, -1, 8, -3,
-    -2, 6, 1, 17, 8, -14, 7, -3, 12, 9, 1, 0, 1, -5, 17, -18 },
-  { 25, 19, -17, 12, -4, -10, 1, -13, -19, -7, -3, 9, 6, -2, 3, 1,
-    4, -2, -11, -14, -1, -7, -5, -9, 7, -1, -3, 4, -5, 1, 0, -1 },
-  { 20, 8, -3, -10, -24, 3, -6, -2, 0, -12, 14, 6, 7, 11, 4, 7,
-    -12, -5, -8, -10, 5, -1, -4, 4, 16, 7, -14, 6, -1, -2, -7, -11 },
-  { 16, 18, 17, 1, -15, -6, -5, -3, -1, -19, 8, -2, 2, 8, 12, -19,
-    -12, 8, 0, -3, -1, -1, 4, -14, 9, -1, -12, -1, -7, 10, -3, 5 },
-  { 18, 12, -7, 7, 0, -3, -13, 0, -1, -4, 9, -2, 6, -1, 0, 1,
-    15, -21, 1, -8, 25, -19, 13, -9, 2, 12, 5, -7, -3, -1, -3, 1 },
-  { 13, 16, -4, 9, -2, 2, -1, -19, -7, -4, 18, -6, 14, 18, -5, 4,
-    -6, -3, -19, -14, -1, -12, 10, 6, 7, 17, -12, -13, -10, -4, 5, 4 },
-  { 27, 17, 4, 14, -9, -2, -4, -8, 0, -6, 14, -11, -7, 2, -3, -3,
-    -2, -3, -13, 12, 16, 1, -5, -9, -10, -11, -2, 3, -7, 5, 11, -7 },
-  { 7, 17, -16, -2, -14, -28, -7, -8, 15, -10, 7, 15, 8, 17, 13, -1,
-    4, -7, -12, -11, 0, 0, 2, 3, -3, 7, -6, 6, 1, -16, 1, -2 },
-  { 23, 11, -9, 15, -23, -4, -6, -4, 2, -9, -7, 9, -8, 3, -13, -4,
-    8, 18, -6, -2, 1, -5, 6, -14, -5, -2, -6, -5, -3, -2, 4, -5 },
-  { 12, 13, 18, 18, -35, 2, 7, -17, 3, -11, 6, 9, -3, -2, 10, -4,
-    3, 3, -2, -7, 0, 2, -4, 0, -4, 0, -6, 5, 10, 4, -3, -1 },
-  { 19, 11, 1, 20, -14, 4, -9, -13, -2, 11, 0, 17, -1, -1, -1, -1,
-    -5, -8, 0, 5, -1, -8, 5, -1, 3, 2, -12, 21, -2, -24, 5, 7 },
-  { 15, 15, -15, 17, -14, -22, 3, -4, -11, -3, -7, 1, 18, 10, 1, 10,
-    -6, -3, 8, 2, -7, 0, -2, 1, 1, 2, -9, -2, 1, 2, -3, 4 },
-  { 45, 13, 8, 17, -5, 2, -16, 2, 8, -2, 8, -15, 4, 5, -1, 7,
-    -6, -2, -6, 2, -3, 0, 0, -9, -1, 7, 2, 3, -3, -3, -1, 5 },
-  { 1, 18, -8, 18, -12, -10, 3, 4, -22, -12, 20, 8, -3, 9, 2, 10,
-    -10, -3, 9, 3, 6, -3, 10, -1, -3, 2, -2, 4, 2, 3, -3, -18 },
-  { 9, 10, -5, 9, -35, -21, -18, -16, -1, -12, -6, -7, -15, -19, 12, 4,
-    4, 9, -7, 2, 14, 1, 4, 0, -1, 6, -7, 2, 1, 1, -4, 4 },
-  { 31, 8, -17, 35, -8, 1, -5, -6, -7, -6, 10, -2, -3, 6, 9, 3,
-    -6, -2, 3, 3, 5, -3, 0, 6, 0, 1, -5, -3, -2, -4, -1, 0 },
-  { 18, 4, -8, 7, -8, -15, -1, -16, 12, 18, 3, 19, 2, 4, 8, 8,
-    0, -5, -8, -12, 10, -5, 0, 1, 0, 4, -3, 16, 11, 11, -2, -6 },
-  { 27, 15, -17, -10, -23, -22, -1, -14, -4, -7, 20, -2, -7, 6, 15, -5,
-    32, 4, 9, -11, -3, -8, 11, -4, -1, -4, -8, -6, -4, -5, -2, -7 },
-  { 22, 4, -7, 2, -15, -11, -17, -10, 2, 0, 15, 11, 7, 12, -8, 6,
-    -10, -18, -6, -12, 7, 3, 22, 3, -7, 14, -5, -2, -13, -7, -1, -7 },
-  { 18, 13, 9, 24, -4, -19, -9, -11, 13, 8, 2, 4, -1, 8, 14, 10,
-    -12, 0, 0, 5, 10, 5, 4, -1, 5, 1, -1, 11, 2, -4, 0, -9 },
-  { 15, 19, -5, 1, -4, -10, -8, -27, 6, 8, 5, 10, 4, 11, 5, -5,
-    -11, 0, -11, -14, -4, -9, -8, -8, 6, -9, 4, -5, -1, 1, 5, -4 },
-  { 18, 1, -13, 14, -14, 9, -15, -7, 12, 1, 13, -4, -20, 12, 10, 12,
-    -12, 7, 1, -13, 10, -6, 5, -3, 4, 8, 10, -13, -3, -6, 9, -3 },
-  { 19, -14, 5, -8, -6, 2, -5, 5, -3, -1, -28, 11, 18, -6, -4, -2,
-    11, 14, -43, -42, 9, 2, 20, -23, 6, 32, 0, 5, 0, 6, 9, 5 },
-  { 8, 11, -14, -1, 7, 12, -7, 2, -16, 2, 10, -3, -1, -7, -7, -1,
-    1, -10, -60, -23, -18, 42, -13, 9, 18, -11, 0, 1, 0, 2, -5, 1 },
-  { -5, -1, 2, 0, 3, -3, 3, -2, -6, 0, -3, -3, 7, 2, 0, -2,
-    -2, 3, -34, -15, 37, 47, 10, 20, 9, 1, 3, -21, -25, -33, -14, 8 },
-  { 5, 6, 2, -2, -2, -2, 6, 5, -5, 7, -3, 1, -5, -13, 9, 3,
-    -17, -19, -2, -79, -12, -7, -8, -6, -2, -2, -1, -1, -7, -13, 6, -1 },
-  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1,
-    0, 3, 4, -87, 6, -11, 16, -9, -1, 8, 0, 5, 0, 1, 2, 1 },
-  { -5, 6, 2, -24, 5, -9, -7, 0, 7, 3, -3, 16, -14, -16, 0, 18,
-    15, -9, -14, -28, -17, 53, 14, -6, -28, -1, -3, -10, -7, -14, 19, -15 },
-  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -3, 0,
-    -13, 0, -53, 3, -22, 63, 19, 16, 1, -11, 0, -3, 0, -3, 0, 1 },
-  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1,
-    -1, -6, -43, -43, -2, 65, -13, -4, 9, 1, 1, 2, 1, 0, 0, 1 },
-  { 0, 1, 0, 0, -1, 0, 1, 1, 0, 0, 1, 2, -1, -1, -3, -1,
-    -23, 1, -61, -55, 3, -28, -6, -4, -4, 8, 2, 1, 1, -1, 0, 0 },
-  { 0, 1, -1, 1, -1, 0, -1, 0, 1, -1, 0, 1, -1, 0, -9, -4,
-    -48, -19, -52, -46, 11, -12, 5, -14, 0, -10, 0, 0, -1, -2, -1, 0 },
-  { 0, -3, -1, -4, 2, -1, -7, 3, 1, 3, -1, 1, -3, 0, -7, 0,
-    3, -7, -61, -51, -4, -21, -16, -21, -11, 14, -7, 8, 3, -5, 1, 2 },
-  { 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 1, -1, 9, -3,
-    56, -11, -6, -67, -1, 13, 0, 7, 1, -9, -1, -1, 0, 0, 1, 0 },
-  { 14, 9, -2, 14, -10, -10, 9, -5, 1, -8, -23, 30, 8, -7, 23, 8,
-    2, 10, -1, -27, -17, 57, 22, 4, -5, 2, -12, -6, 2, -7, -4, -9 },
-  { 1, 5, 12, -2, -2, -3, 2, -3, 6, 0, 4, -2, -8, -6, 0, 16,
-    -15, 29, -55, -29, -24, 29, 3, 10, 6, 13, 10, -5, 21, 11, -14, 5 },
-  { 4, 2, 26, -6, 10, 11, -23, -10, -27, -20, 3, -24, -11, -10, -13, 25,
-    -10, 5, -9, -36, -7, 43, 3, -13, 6, 13, -2, 0, 1, 3, -3, -4 },
-  { -1, 0, -1, 0, 0, 0, 0, -1, 1, 0, -1, 0, 0, 0, -1, 1,
-    -12, 12, -26, -64, -15, 29, 37, -7, -3, -12, -5, 14, 8, -8, -10, -2 },
-  { 19, -4, -11, -16, 8, 14, 5, 19, 3, 22, -11, -21, -1, -6, -11, 11,
-    10, -24, -23, -40, -8, 20, 17, 5, 13, -6, 3, 14, -20, -8, 3, 28 },
-  { 2, -12, 10, -14, -18, 26, -22, 4, -2, 5, -21, 8, 3, 1, 19, 0,
-    -12, 24, -14, -40, 15, 29, -15, 6, 15, 1, -19, 2, 4, 7, -12, -3 },
-  { 0, 17, 13, 7, -5, -11, 2, -19, 3, 38, -21, -3, -6, -4, 7, 1,
-    1, -5, -40, -10, -2, 35, 8, 8, -10, -8, -9, 33, 4, 4, 0, -2 },
-  { -2, -12, 7, 29, -24, 2, 16, -1, -7, 16, 10, -2, -2, -2, 13, -2,
-    -37, 15, -22, -40, -11, 33, 10, -1, 8, 10, 6, 8, 9, 0, -12, 2 },
-  { 15, -8, -9, -2, 7, -17, 7, 19, 14, 4, 12, 27, 11, 10, 4, 11,
-    -15, 14, -13, -48, 5, 18, 0, -9, -36, -11, 2, 4, 5, 5, -15, -12 },
-  { -12, 0, 3, 4, 7, -5, 5, -14, -24, -18, -6, -15, -8, -20, 1, -7,
-    -33, -28, -40, -38, -18, -10, -5, 17, -12, 4, 3, -5, 5, -13, 4, -7 },
-  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1,
-    -3, -9, -49, -60, -5, 45, -1, 6, 0, 0, 0, 0, 0, 0, 0, 0 },
-  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1,
-    -3, -9, -49, -60, -5, 45, -1, 6, 0, 0, 0, 0, 0, 0, 0, 0 },
-  { 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0,
-    3, -2, 9, -29, -11, 55, 8, 32, -36, -13, -7, 37, 4, 11, 0, 3 },
-  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    4, -1, -39, -4, -30, 63, 28, -17, -6, 10, 7, -14, -9, 11, 9, 7 },
-  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1,
-    13, -2, -50, -32, 22, 51, 4, 7, 6, 11, -20, -13, 9, -5, 21, -4 },
-  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1,
-    -3, -9, -49, -60, -5, 45, -1, 6, 0, 0, 0, 0, 0, 0, 0, 0 },
-  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1,
-    -3, -9, -49, -60, -5, 45, -1, 6, 0, 0, 0, 0, 0, 0, 0, 0 },
-  { 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0,
-    3, -2, 9, -29, -11, 55, 8, 32, -36, -13, -7, 37, 4, 11, 0, 3 },
-  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    4, -1, -39, -4, -30, 63, 28, -17, -6, 10, 7, -14, -9, 11, 9, 7 },
-  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1,
-    13, -2, -50, -32, 22, 51, 4, 7, 6, 11, -20, -13, 9, -5, 21, -4 },
-  { -8, 2, 1, 22, -31, -6, -25, -3, -3, 1, -15, -11, -2, -3, 4, -13,
-    -9, 15, -18, 37, -7, -37, 12, -13, -11, -25, -10, -11, -22, 7, 16, 7 },
-  { 14, 10, 4, -10, -1, -5, -7, -3, 16, 13, -5, -15, 5, 11, -1, 8,
-    -27, 7, -12, 49, 17, -22, 9, -2, -9, -1, 2, -15, -1, 41, -18, -17 },
-  { -4, -9, -15, -3, 3, 4, 4, 2, 7, -3, -7, -8, -5, 17, -19, -7,
-    36, -9, -38, 17, 1, -48, 11, -18, -13, -2, -8, 4, -10, -5, 21, 11 },
-  { 15, -13, 4, 2, 1, -5, -2, 1, -10, 7, -1, 3, -6, 0, 11, -11,
-    8, 20, -17, 51, -17, -41, 2, 15, 4, 8, -2, 16, -32, -1, 17, 6 },
-  { -8, 8, -18, -5, 4, 6, -3, 8, 0, -4, 2, 0, -1, -4, 5, 8,
-    30, 30, -8, 70, 2, 8, 2, 0, 7, 1, 13, -1, -6, -7, -11, 2 },
-  { -8, -7, 9, -10, -13, 6, -11, -14, 13, 25, -26, 5, 2, -5, -5, 5,
-    -8, 4, 0, 33, 12, -38, -4, 6, 13, 6, 25, 34, -1, 25, -19, -5 },
-  { 18, 3, -17, 4, -8, 7, 20, 1, -1, 5, -5, -2, -8, 8, -35, 15,
-    24, 43, -5, 51, 5, -12, -3, 1, -2, 3, -3, -3, -9, 8, -9, 2 },
-  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
-    2, 10, 24, 76, -2, -22, 11, -1, 4, 33, 4, 1, -1, 1, 2, 0 },
-  { 0, -1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 2, 0,
-    24, 13, 32, 70, 26, 5, -21, -9, -6, -15, 2, -2, 2, 4, 1, 1 },
-  { 5, -4, -11, 4, -4, 22, 10, -2, 13, -11, -4, -21, -17, 0, -7, 4,
-    10, -34, 11, 52, 2, -46, -5, 0, 0, -1, 2, 4, -9, 1, 1, -7 },
-  { 0, 1, 1, 0, -1, 0, 1, 0, 1, 1, 0, 1, 0, 0, -3, 1,
-    -8, 9, -1, 64, -13, -61, -3, 3, -5, 10, 1, 3, -1, -1, -1, -1 },
-  { 0, 1, 0, -1, 0, -1, 0, 0, 1, 0, 0, 0, 1, 1, 2, 1,
-    10, -2, -31, 79, -10, 27, 0, -1, 3, 8, 1, 1, 0, -1, 0, -1 },
-  { 3, 12, 10, 26, -19, 10, -9, 6, -4, -15, 10, 3, -16, 6, 11, -19,
-    3, 10, 18, 44, 5, -30, 5, -9, 21, 4, 20, 10, 14, -25, 8, -17 },
-  { 0, 0, 0, 1, -1, 0, -1, 0, 1, 0, 1, 1, 0, 0, -6, -2,
-    8, -8, 13, 69, 26, -19, -25, -17, 16, 6, -12, 22, 2, -6, 9, 5 },
-  { 0, -1, 0, 1, 0, -1, -1, 0, 0, 1, -2, 1, 0, 0, -4, -1,
-    -34, -15, -33, 56, 9, -42, 9, 10, 6, 9, -8, -11, 0, -6, 15, 5 },
-  { 10, 2, -14, -3, -15, -35, -1, 7, -18, 14, 8, -1, -15, -26, 6, -15,
-    -18, 22, 9, 33, 0, -32, -9, 3, -11, 7, 4, -1, 5, 30, 9, 1 },
-  { 4, 15, 0, 6, -5, -11, 9, 6, 6, 6, 14, 2, -1, 10, -24, -25,
-    -2, -4, -1, 37, 2, -29, 14, -9, 22, 17, -2, 33, 10, -25, 11, -11 },
-  { 0, 5, 2, 18, -12, 21, 22, 33, -7, 21, -9, -7, 7, -15, -7, 16,
-    7, 0, -14, 44, 10, -25, 5, -4, 15, -8, 10, -4, 5, 9, -1, 16 },
-  { 3, 13, 12, 12, 8, 25, -23, 8, -22, -3, -18, -8, 15, 12, 9, 19,
-    0, 0, -9, 49, -27, -15, -9, -15, 12, -8, -16, -7, 13, 5, 13, 2 },
-  { 12, -6, 7, -2, 20, -9, -14, 12, 13, -5, -17, 22, -8, -4, 2, 7,
-    -13, -2, -15, 43, -5, -30, 27, 4, 10, -27, 5, 27, -10, -10, -18, 0 },
-  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
-    -1, 10, -18, 70, -2, -52, -1, -7, 0, 0, 0, 0, 0, 0, 0, 0 },
-  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
-    -1, 10, -18, 70, -2, -52, -1, -7, 0, 0, 0, 0, 0, 0, 0, 0 },
-  { 15, -13, -20, 16, 2, 13, 5, -11, -8, -5, -3, 2, 24, -23, 30, -7,
-    11, 30, -15, 43, 5, -15, 15, -3, -14, 1, -23, 8, 3, 9, 4, -11 },
-  { 0, -1, 0, 1, 0, -1, -1, 0, 0, 1, -2, 1, 0, 0, -4, -1,
-    -34, -15, -33, 56, 9, -42, 9, 10, 6, 9, -8, -11, 0, -6, 15, 5 },
-  { 10, 2, -14, -3, -15, -35, -1, 7, -18, 14, 8, -1, -15, -26, 6, -15,
-    -18, 22, 9, 33, 0, -32, -9, 3, -11, 7, 4, -1, 5, 30, 9, 1 },
-  { 4, 15, 0, 6, -5, -11, 9, 6, 6, 6, 14, 2, -1, 10, -24, -25,
-    -2, -4, -1, 37, 2, -29, 14, -9, 22, 17, -2, 33, 10, -25, 11, -11 },
-  { 0, 5, 2, 18, -12, 21, 22, 33, -7, 21, -9, -7, 7, -15, -7, 16,
-    7, 0, -14, 44, 10, -25, 5, -4, 15, -8, 10, -4, 5, 9, -1, 16 },
-  { 3, 13, 12, 12, 8, 25, -23, 8, -22, -3, -18, -8, 15, 12, 9, 19,
-    0, 0, -9, 49, -27, -15, -9, -15, 12, -8, -16, -7, 13, 5, 13, 2 },
-  { 12, -6, 7, -2, 20, -9, -14, 12, 13, -5, -17, 22, -8, -4, 2, 7,
-    -13, -2, -15, 43, -5, -30, 27, 4, 10, -27, 5, 27, -10, -10, -18, 0 },
-  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
-    -1, 10, -18, 70, -2, -52, -1, -7, 0, 0, 0, 0, 0, 0, 0, 0 },
-  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
-    -1, 10, -18, 70, -2, -52, -1, -7, 0, 0, 0, 0, 0, 0, 0, 0 },
-  { 15, -13, -20, 16, 2, 13, 5, -11, -8, -5, -3, 2, 24, -23, 30, -7,
-    11, 30, -15, 43, 5, -15, 15, -3, -14, 1, -23, 8, 3, 9, 4, -11 },
-  { 16, -18, 7, -4, 31, -15, -9, -13, 20, -12, -6, 0, 12, -6, -2, 4,
-    3, -3, -1, 0, 1, 3, 3, -2, 1, 6, 4, 0, -3, 2, -5, 1 },
-  { 38, -5, -13, -4, 8, -15, 11, 1, 2, -4, -1, 9, 13, 4, -12, -7,
-    0, -2, 7, 2, -6, -2, -3, -2, 3, -4, 6, 15, 1, 1, -11, -2 },
-  { 47, -22, 9, -26, 3, -5, 2, -7, 4, -2, 2, -2, 3, 0, 3, -4,
-    3, -3, 2, -3, 7, -3, -1, 1, 1, -5, 5, 0, 2, -5, -3, -2 },
-  { 14, -16, 2, -6, 7, -2, -7, -4, -4, -7, 14, -3, 7, -19, -14, -17,
-    -29, 6, 26, 16, -5, 13, -4, -1, 21, 14, 1, 3, -6, 0, -7, -1 },
-  { 29, -11, 5, -3, 4, 11, 4, -10, 1, -22, -3, -10, 5, 4, 2, 8,
-    -2, -7, -12, -12, -8, -3, -18, -2, -9, -5, -1, -3, 2, -14, -14, 7 },
-  { 28, -12, 5, 3, 9, -7, 0, -2, 2, 1, 4, 0, -7, -3, -2, 4,
-    4, 14, 8, -1, -4, 14, -7, 17, -2, -2, -9, 2, 19, -7, 9, -8 },
-  { 31, -18, -22, 8, 15, -5, -10, -15, 1, 10, 6, 7, 6, -8, 2, -1,
-    12, -3, 3, -1, 1, 5, -6, -4, 0, 1, 7, -10, -2, 4, -3, -4 },
-  { 53, -30, -4, 12, 2, 3, -3, -3, 0, 1, 6, 5, -5, -4, -7, 1,
-    0, 2, 1, 3, 1, 5, 0, 2, 2, -1, 0, 4, 2, 0, -2, 0 },
-  { 27, -18, -3, -2, 4, -8, 3, -2, -11, 2, 10, -8, -8, -4, 0, -2,
-    8, 0, 9, 0, -16, 11, 1, -6, 13, -3, -10, -13, -15, 25, 1, 0 },
-  { 35, -5, -1, -8, 23, 11, -14, -3, 2, -2, 8, -6, 17, -2, 7, 0,
-    -2, 10, -17, 13, -2, -2, 11, 11, -14, 2, -2, -3, -8, -1, -12, -5 },
-  { 29, -9, 7, 3, 2, -10, 0, 3, 9, 0, -3, 5, 1, -10, 10, -5,
-    3, 6, -20, -9, -6, -4, 1, 0, 12, 17, -8, 9, 3, -1, -9, 0 },
-  { 15, -16, 18, -19, 16, -15, 17, -18, 13, -16, 17, -14, 15, -9, 13, -17,
-    9, -7, 4, -5, 3, -4, -3, 0, -6, 7, -9, 7, -2, 7, -9, 9 },
-  { 21, -10, 7, -2, 12, -7, 13, -17, 11, -2, 20, 3, 5, -11, -6, -6,
-    -15, 0, -9, 5, -11, 7, -1, 7, 8, -10, -9, 3, -5, 9, -8, -2 },
-  { 23, -22, 15, -5, 16, -4, -3, -12, 9, 3, -1, -2, -8, 2, -2, -16,
-    3, 4, -2, -6, -7, 12, -8, 2, -14, 2, -7, 11, -2, 6, -4, -1 },
-  { 34, -17, -4, 8, 4, -6, 1, 8, 4, 16, 3, 6, 12, -1, -1, -15,
-    6, 4, -7, -6, 6, 0, 2, 1, -2, 2, 3, 3, -3, -2, 8, -6 },
-  { 18, -18, 2, -2, 10, 1, 18, -23, -3, -10, 0, 4, 20, -19, -3, -4,
-    2, 8, 6, 1, -3, 1, 1, 3, 5, -1, -11, 3, -7, 5, -1, 1 },
-  { 15, -14, 2, 3, 10, -8, 12, -13, 13, -15, 6, -8, -4, -10, 14, -9,
-    24, 2, -7, -18, 13, -11, 8, 14, -6, -2, 3, -1, -4, 7, -7, -4 },
-  { 20, -12, 13, 5, -1, -10, 15, -6, 8, -1, -3, -10, 17, 0, -6, -19,
-    2, -1, 8, -3, -16, 0, -3, 2, -2, 0, 8, -9, 0, 1, -10, -9 },
-  { 32, 0, -9, -5, -1, 5, 13, -11, 8, 3, 11, -11, 0, -8, -2, -14,
-    7, 10, 6, -5, 1, 10, 2, 12, -10, 4, 4, 6, 4, 0, -7, -10 },
-  { 16, -14, 10, -7, 11, -11, 11, -11, 18, -13, 8, -15, 16, -11, 13, -9,
-    8, -7, 12, -11, 7, -6, 3, -5, 9, -5, 4, -1, 7, -4, 8, -3 },
-  { 24, -27, -1, 5, 8, -5, 12, 7, 4, -3, 3, -1, -9, -11, -13, -5,
-    10, 0, -13, 7, 1, -5, 4, -9, 7, -3, 13, 2, -5, -3, -17, -2 },
-  { 23, -19, 15, 1, -10, -18, -12, -6, 8, -3, 12, 0, -12, -10, -4, -4,
-    8, -10, 4, 2, -2, -8, 13, -3, -2, -6, 2, -3, 5, -2, 2, 11 },
-  { 25, -12, 4, 2, 24, -3, 3, -6, 14, 11, 0, -21, -3, -3, 1, -8,
-    7, 0, 0, 3, 3, -6, -7, 6, 2, 1, -4, 5, -1, 10, -2, 9 },
-  { 24, -8, -6, 7, 16, -12, 13, -1, 11, -21, 2, -6, 3, -12, 0, 9,
-    4, 11, -7, 1, 4, 1, -8, 3, 3, -6, 3, 3, 0, -8, 8, 4 },
-  { 25, -21, 13, 14, 13, -18, 4, -3, 0, -5, -4, 5, -3, 0, 4, 12,
-    7, 3, 5, -5, 2, -2, 3, -10, 2, -9, -15, 6, 1, 7, -5, 1 },
-  { 23, -16, -2, 10, 4, -1, 3, 1, 32, 3, -5, -2, 9, 10, -1, -4,
-    -6, 2, 9, -1, 14, 12, -6, -1, -17, -2, -4, -9, -7, -6, -8, 3 },
-  { 50, -8, 5, 2, -11, 10, 0, 0, 6, -3, 7, 0, -3, -2, -3, 0,
-    6, -4, 2, -5, -9, 0, 3, 10, 1, -7, -2, -3, -6, -9, 1, -2 },
-  { 28, -17, 0, -2, 2, -9, 1, 5, -4, -1, 0, 0, 19, -27, 5, -12,
-    7, -14, -3, -6, 10, -2, -4, -2, 4, -5, -2, -7, 1, 7, -9, 4 },
-  { 22, -19, -6, -6, 3, -22, 3, 5, 20, -8, -14, -5, 1, 1, 20, 2,
-    16, 6, 3, 14, 4, 3, 5, 1, 5, -7, -10, -6, 3, -6, 1, -14 },
-  { 29, -14, -8, 13, 8, -10, -6, 4, 4, -6, 5, -7, 1, 12, 14, 11,
-    -7, 1, 2, -9, -11, -9, 0, 4, -1, 7, 10, 4, 4, 20, -1, -11 },
-  { 18, -9, 4, 1, 7, -29, 12, 1, -1, -9, -2, -1, -2, 2, 9, -8,
-    -13, 5, 4, -13, -4, 2, -5, -7, -6, 14, -10, -34, -3, 1, -3, -13 },
-  { 38, -9, 24, 8, 11, 4, -6, -11, -2, -12, 1, 1, -11, -8, -5, -2,
-    -15, -8, 8, 0, 1, -7, 5, 4, -1, 8, -2, 11, -3, -1, -5, -5 },
-  { -20, 11, -4, 24, -11, 1, 15, 4, 0, -28, -10, -1, 10, 10, -6, 5,
-    -6, 2, 7, -2, 1, -2, -6, -3, -7, 1, 2, 12, -1, 7, 0, -2 },
-  { -9, 10, -23, 27, -4, -17, 20, -6, 14, -17, 5, -1, 5, -9, -7, 5,
-    -6, 4, -2, 9, 0, 8, 0, 1, -3, -3, -5, -8, 5, -2, -2, 12 },
-  { -10, 19, 4, 9, 1, -16, 17, -2, 9, -29, -16, -11, -4, 7, -5, 4,
-    -1, -3, 3, 2, 3, -4, 5, -12, -2, 6, 5, -4, 4, 1, 4, 10 },
-  { -20, 10, -24, 14, -5, 11, 9, 0, 16, -20, 10, -5, -6, -6, -1, 2,
-    -4, 5, -16, 8, -2, 5, 5, -11, 9, -11, 4, -11, -1, -1, 4, 3 },
-  { -9, 11, 3, 19, 24, 4, 5, -14, 30, -17, -4, -2, -17, 7, 2, 3,
-    1, 3, -7, -4, 2, -3, 1, 4, -1, -1, 3, -12, -2, 3, -3, 10 },
-  { -19, 18, 11, 19, 19, 19, 10, 4, 13, 6, 5, 4, 8, 3, -2, 12,
-    -6, -2, 7, -6, 15, 12, 16, 16, 18, -3, -4, -20, 0, 10, -9, -3 },
-  { -21, 9, 20, 12, 0, -3, 5, -9, 15, -13, 5, -5, -6, 24, 2, 9,
-    -5, 2, -7, 2, 5, 7, -5, 2, 15, 3, 1, -1, -4, -2, 7, 0 },
-  { -18, 16, 13, 15, 2, -10, 14, -11, 4, -11, 5, 12, 12, 20, 8, 30,
-    2, 11, -9, 7, 0, -3, -16, -5, -6, 5, -4, -21, 0, 5, 6, 1 },
-  { -26, 8, -13, 9, 6, -10, 2, -11, 7, -4, 6, -19, -11, -6, -12, 16,
-    0, 5, -7, 8, 5, 6, 17, -9, 10, -10, 5, -3, -11, 2, 4, 10 },
-  { -11, 17, -3, 22, -5, 18, 3, 1, 4, -5, 14, -27, 5, -7, -4, -5,
-    -10, 11, 1, 15, 1, 1, -6, -5, 10, -22, -7, -7, -15, 13, -4, 5 },
-  { -17, 14, -7, 13, 3, 0, 13, -6, 9, -14, -22, -1, 1, 19, 14, -3,
-    4, -13, -13, 2, -4, 8, -2, -2, 13, -12, 13, -12, -7, -5, -3, 6 },
-  { -17, 17, -1, 33, 6, 3, 9, -16, 3, -14, -8, 6, -17, 8, 3, 13,
-    8, -6, 3, 1, -2, 0, -2, 8, 4, 9, 13, -10, 4, -17, 0, -6 },
-  { -20, 7, 7, 21, 1, -3, 7, -3, -2, -12, 9, -7, 2, -3, 14, 1,
-    -1, -7, 12, -10, 5, -20, 11, -2, 0, -24, -17, 6, 6, -4, 3, -1 },
-  { -8, 10, 6, 7, -1, -6, 28, -6, 10, -33, 1, -20, 0, -12, 10, 1,
-    -6, 8, -3, -1, -10, 8, 5, 0, 10, -2, 8, 16, -5, -3, -7, 4 },
-  { -17, 13, 3, 15, 1, -5, 27, -5, 6, -6, 12, 2, -4, 8, -1, -3,
-    -2, 12, -15, 3, 4, 1, 2, -9, 0, -16, -21, 2, -4, 16, -7, 4 },
-  { -15, 20, 8, 17, 5, -14, 15, -11, 21, -11, 13, -13, 2, -15, -13, 1,
-    -5, 5, 2, 10, -9, 4, -1, 3, 2, -4, 13, -5, 1, -4, 5, -3 },
-  { -21, 8, 2, 16, -1, 2, 15, -16, 13, -12, -12, -7, -8, 2, -7, 11,
-    -8, 5, 2, -7, 16, -4, 1, -7, 3, -15, 6, -5, -8, 2, -8, 5 },
-  { -15, 17, -6, 3, -3, 3, 9, -7, 14, -23, 11, 1, -1, 4, 7, 6,
-    -1, -14, 7, 6, -8, 5, 1, -15, 10, -9, 2, -3, -1, 4, -10, -4 },
-  { -10, 18, 3, 11, 1, 4, 14, -14, 7, -4, 15, -10, 10, -11, 10, -4,
-    5, -14, 10, 4, 15, -12, 15, -13, 20, -15, 14, -15, 8, -11, 4, -6 },
-  { -7, 23, 2, 20, 7, 8, 19, -5, 9, -16, -8, -17, -5, 1, 5, -6,
-    -8, 1, -6, -4, 10, 6, 6, 2, -11, -4, 0, 2, 4, 7, 9, -4 },
-  { -15, 20, -5, 22, 11, -8, 9, -5, 10, -13, -8, 8, 2, -2, -3, 7,
-    6, 10, 1, 2, -5, -9, 1, 10, 16, -22, -7, 0, 7, 7, 6, 1 },
-  { -26, 19, -5, 3, 5, 25, 18, -5, 9, -14, -8, -6, -2, -6, 2, 3,
-    -8, -2, -7, 7, -3, 7, 3, 4, -8, 0, 1, -8, -4, -2, -2, 1 },
-  { -20, 14, -10, 6, -3, 7, 8, -32, -2, -7, -2, -10, 16, -12, -9, 15,
-    -2, -5, -6, 2, -7, 5, 9, 1, 6, -7, -1, 0, -2, -4, -7, 3 },
-  { -14, 16, 4, 11, -8, 1, 23, -4, 17, -13, -10, 1, 12, 9, 12, -4,
-    7, -1, -1, 5, -8, -6, 3, 3, -6, -3, -18, 0, 18, 20, 4, -2 },
-  { -33, 19, -10, 30, 15, 2, -3, -1, -4, -14, 7, -7, -1, 7, -8, 9,
-    -1, -3, -5, 2, 2, 4, 0, 5, 0, 0, 2, 3, 3, -3, -3, 4 },
-  { -6, 20, 0, 5, 17, -10, 18, -17, 9, -16, 4, -13, -6, 2, -14, 14,
-    -28, 9, -12, 25, -4, 7, 7, -8, 6, -6, -2, -10, 2, -11, -1, 2 },
-  { -12, 14, 12, 52, -3, 5, -5, 4, 8, -13, 2, -5, -4, 2, -2, -1,
-    -2, 3, 3, 5, 2, 3, 0, 1, -5, 2, -4, -3, 1, -5, -2, 0 },
-  { -13, 6, 9, 24, 0, 8, 14, -15, 18, -9, -11, -8, 3, 15, -2, -4,
-    -9, 4, -3, 12, 14, -13, 11, -4, 2, -4, 0, -6, -6, -6, -14, -1 },
-  { -10, 28, 3, 12, 9, 3, 11, -28, 6, -11, -7, 4, 0, 7, 8, -9,
-    0, -6, 0, -16, 4, 7, 4, 4, 7, 3, 4, -7, 0, -3, -10, 6 },
-  { -11, 14, -2, 19, -1, -1, 7, 9, -2, -27, 10, -14, 15, -4, 12, -4,
-    2, -2, -6, 12, -6, 0, -5, -4, -5, 1, 3, -11, 5, -9, 3, -8 },
-  { -18, 7, 13, 16, -4, 3, 9, -10, 10, -10, -3, -22, -4, -12, 3, -16,
-    0, -3, -16, 8, -11, 1, 10, -7, 15, 3, 0, -1, -13, 8, 1, 6 },
-  { -20, 10, -10, 10, 8, -1, 6, 0, 16, -12, 9, -10, -1, -5, -4, -13,
-    13, 16, -8, 12, -2, 14, 18, 13, 0, -16, 2, -5, -5, -5, -4, 3 },
-  { -14, 5, -7, -17, 5, -13, 23, 20, -4, -1, 1, -6, 13, 5, -1, 4,
-    -14, -2, -7, 8, 3, 2, 2, -7, 2, -1, 4, 7, 3, -9, -1, -5 },
-  { -19, 3, -24, -28, -9, -7, 19, 3, 2, 19, 7, 5, -13, 8, -15, -17,
-    3, -11, 4, 13, 3, 2, -1, -3, -4, -4, 2, 0, -5, -6, 6, 2 },
-  { -17, 18, -30, -20, -2, -3, 1, 15, -1, -11, 6, -4, 11, 11, -4, -5,
-    -10, 0, 0, 1, 3, -7, 8, 2, 5, 1, 5, -5, 1, 6, 4, 1 },
-  { -6, 1, -30, -25, -1, -8, -2, -9, -17, 16, 3, -1, -2, -9, -6, -7,
-    -3, 12, 6, -4, -10, 0, 10, -8, -6, -5, -3, -11, -4, 0, -1, -3 },
-  { -1, -1, -34, -28, 1, -10, 2, 9, 4, 16, 2, 6, 14, 17, 0, 7,
-    -4, 4, 4, 4, 0, 1, -1, -5, 8, 1, -4, 1, -9, -2, 5, 6 },
-  { -11, 14, 1, -31, -7, -24, 9, 7, 6, 5, -13, 1, -1, 3, 4, -1,
-    -2, -8, -6, 3, 5, -4, -6, 7, -2, 5, 3, 3, 0, 0, -5, 2 },
-  { -25, 8, -11, -18, 1, -4, 8, -3, -4, 15, 6, -5, 8, 2, 3, 4,
-    -4, 5, 6, 8, -7, 6, 1, -11, -15, -13, 9, -4, -14, 10, 12, 7 },
-  { -20, 11, -15, -25, 3, 4, 18, 13, -4, -5, -9, -1, -5, -2, -2, -7,
-    16, 5, -4, -5, -7, -2, -3, -9, 11, -2, 0, -7, -17, -6, -11, 6 },
-  { -11, 18, -5, -20, -15, -3, 9, 11, -20, 12, 5, 5, 11, -3, 7, 1,
-    10, -6, -3, -3, 3, 3, 14, -7, 10, -17, 9, -11, -2, -6, 7, -12 },
-  { -20, 8, -14, -17, -9, -13, -3, 0, -27, -14, -3, -14, 4, 3, 6, -6,
-    7, 4, 23, 9, 11, 9, 3, -4, 9, 2, 4, -1, -6, 1, -8, -11 },
-  { -9, 14, 2, -37, -7, 13, 6, -11, -6, 9, 18, -11, -6, 2, 12, 4,
-    -1, 3, 1, -2, -2, 1, -9, -4, -2, -3, 3, 5, -6, 0, -2, -8 },
-  { -29, 8, -1, -13, -2, 8, 23, 2, -10, 7, 13, -6, -5, 11, 13, 0,
-    -10, -13, 11, -12, -10, 6, 4, 6, 4, 3, 6, -5, -9, -2, -1, 3 },
-  { -18, 6, -10, -55, -4, -11, -2, 0, 1, -3, -9, -6, 3, -2, -1, 6,
-    3, -1, 3, 1, -4, -7, -2, 6, 3, -2, -1, -3, -2, 0, 4, 1 },
-  { -14, 5, 3, -21, -8, -16, -4, -2, -11, 27, 15, -20, 3, 0, 1, 1,
-    2, -5, -5, 4, 1, -9, 5, -3, 3, 0, -4, -2, -11, -4, -3, 7 },
-  { -17, -1, -9, -17, -8, -18, 12, -13, -9, 13, -3, 3, 3, -3, 1, -2,
-    0, 16, -9, 6, 12, 9, 5, 11, 2, -15, 1, -4, -16, 7, -4, -12 },
-  { -18, 8, -6, -11, -8, -7, 13, 7, 1, 6, 8, -1, 21, -4, 14, 15,
-    18, -4, -3, 15, 0, 9, 4, 7, 3, -1, 9, -2, 0, 7, -8, 2 },
-  { -10, 7, -18, -29, 3, 12, 12, 9, 11, 4, -1, -15, 1, -1, 8, -2,
-    -2, 10, -15, -1, 0, 6, 12, -6, -1, 10, -6, -3, -11, -4, 9, -6 },
-  { -14, 14, -9, -21, -12, -2, -1, -7, -5, -10, 5, -8, 0, 6, 9, -11,
-    11, -3, -5, 3, 8, 15, -2, -4, -22, 4, -6, 12, 2, 13, 6, -7 },
-  { -12, 11, -5, -29, -25, 4, 12, -13, -11, -7, 4, 2, 2, -5, 5, 8,
-    7, -5, -5, 6, 3, -10, 1, -6, 6, -6, -5, -1, -2, -4, 7, 6 },
-  { -15, 11, -5, -16, 0, -13, 26, -23, -6, -3, 5, -2, -2, 21, -6, -3,
-    -5, -1, 6, -1, 0, -13, 2, -3, -9, -1, -4, -3, 5, -4, 12, -16 },
-  { -9, 9, -1, -17, -3, -6, 12, 6, -18, -2, 11, -14, -6, 3, 14, -12,
-    -11, -5, 14, 2, 5, -8, -4, -11, 2, -5, 16, 6, -7, -4, 8, 13 },
-  { -13, 5, 3, -28, -14, 0, 6, 23, 5, 4, -1, -17, 1, -3, 0, 0,
-    5, 4, 0, -18, 14, 10, 4, 2, 5, -2, 4, -3, 2, 0, 2, 0 },
-  { -15, 4, -13, -16, -3, -12, -2, 2, 7, 10, 9, 3, 11, 4, 23, 14,
-    9, 16, 4, 1, -12, -3, 4, -7, -15, -7, -10, -14, -6, -8, -1, -6 },
-  { -7, 10, -5, -10, -3, -13, 16, -1, -12, 7, -3, -12, 2, 13, 13, 2,
-    17, 15, -13, 1, -5, -2, 3, -1, 1, -3, 6, -3, -12, -16, 7, -7 },
-  { -11, -5, -12, -30, -6, -22, 1, 4, -6, -3, 12, 6, 7, 0, 16, 6,
-    -2, 0, -22, -2, -9, 2, -13, 8, 6, -8, 4, -7, -1, -6, 4, 6 },
-  { -14, 5, 1, -27, -4, 2, 1, 14, -11, -7, -8, -4, 1, 8, 0, -6,
-    -13, 11, -12, -7, -5, 1, 10, 7, 3, -2, 0, 6, -8, 2, 10, -1 },
-  { -10, 10, -25, -13, -20, -4, 19, 3, 13, 5, 5, 7, -8, 2, 4, 2,
-    3, -1, -1, -9, 14, 10, 9, 14, 3, 3, -6, 0, -5, 4, 1, -1 },
-  { -9, 15, -18, -17, 4, -11, 6, 7, -12, 8, -1, -11, 2, 3, 7, 16,
-    -3, -9, 7, -12, 23, 0, 6, 7, -14, -9, 8, 1, -2, 6, -2, -1 },
-  { -6, 9, -16, -26, -14, -11, 9, -6, 5, -2, 13, 17, 21, 7, 18, -19,
-    6, -23, -2, -15, -2, 2, -10, -8, 2, 1, -2, 4, -3, -4, -5, -4 },
-  { 0, 6, -5, -28, -17, -32, 2, -10, 11, 3, -5, 9, 10, 3, 11, 11,
-    -3, 12, -2, 2, 4, -6, 9, -4, -4, -4, -4, -9, 2, 0, 2, 4 },
-  { 0, -8, -18, -34, -9, -7, -4, -11, 10, 15, 11, -1, -8, 15, 6, -13,
-    9, 2, -4, -12, 0, -1, 19, 12, 6, 5, 0, -3, -10, -12, 3, -5 },
-  { -10, 6, -9, -17, -12, -11, 9, -6, 11, 11, 18, -7, 0, 16, 4, 2,
-    -6, 3, -12, -1, 0, 1, -5, -22, -2, -12, 0, 6, 17, 5, 5, 6 },
-  { 12, -5, 7, 1, -5, -2, -1, 2, 2, -4, -3, -3, -3, -2, -29, 11,
-    5, -13, -73, 24, 12, 4, -14, -10, 5, 1, 0, -11, -7, -7, 7, 3 },
-  { 10, -3, -1, -3, 4, -11, -5, -2, -8, 7, 9, 2, -8, -6, 6, 7,
-    21, 17, -54, 47, -14, -10, 14, 19, 13, 21, -4, 3, 1, 2, -4, 2 },
-  { -12, 4, -16, -12, 5, -9, -4, 19, -7, -22, -22, -17, 3, 0, -6, 8,
-    23, -4, -55, -28, 2, -26, 2, 1, 4, 0, -13, 6, 0, 10, -7, -11 },
-  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, -1,
-    35, -1, -67, -35, -24, -24, -6, 2, 2, -2, 1, 3, 2, 0, -1, 1 },
-  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 5, 0,
-    41, -4, -73, -15, 18, 4, 17, 8, -1, -16, -1, -2, 1, 0, 0, 0 },
-  { -4, -4, 4, 6, -1, 2, -16, -10, -15, -10, 21, -2, -6, -2, 14, -7,
-    10, -5, -55, 34, -12, 11, -13, -2, 2, 28, -26, 0, 7, 4, 21, -7 },
-  { 2, 1, 15, -22, 10, -3, 14, -6, -2, 15, -2, -7, 20, 6, -15, -7,
-    23, 10, -60, 8, -4, 29, -22, 2, -13, 9, -10, 12, -1, -3, 4, 7 },
-  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, -1, -2, 11, -5,
-    -21, -11, -60, -27, -17, -39, 6, 36, 0, -8, 2, 2, 0, 0, -2, 3 },
-  { 2, -5, 9, -17, -1, 2, -3, -6, 8, 12, 7, -6, -33, -11, -14, -40,
-    10, 36, -46, 0, -19, 5, 0, -10, 3, 12, -6, -8, 6, -12, -7, 1 },
-  { 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, -1, 0, 1, 0, -2, 0,
-    4, -2, -87, -3, -2, 2, -2, 20, 2, 6, -1, 6, 0, 0, 2, -1 },
-  { 1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, -1, 0, 0, 1,
-    1, 7, -76, 41, -7, -24, 0, -6, 3, 6, 0, -2, -1, 1, 0, 0 },
-  { 0, -3, 4, 2, 3, 2, 2, 0, 3, -1, 4, 0, -1, 4, -2, -4,
-    -32, -11, -64, -29, -9, -43, 2, -11, -1, -7, 0, -4, -2, -2, -2, 2 },
-  { 10, -20, 3, -3, 13, 13, 0, -4, 2, 7, -8, 7, -2, 2, -20, -20,
-    -19, 3, -47, -18, -16, -6, -15, -42, -17, 14, -6, 8, 12, -10, 11, -12 },
-  { -3, -2, -2, -1, -1, 4, -3, -1, -6, -2, 3, 2, -3, 6, -1, -9,
-    10, 13, -68, -9, 26, 3, 5, 3, -21, 10, -15, 21, -22, 19, 11, -14 },
-  { 1, 5, 18, -19, -29, -13, -2, 18, -10, 20, 2, 10, -10, 11, 1, 8,
-    -16, -17, -41, 10, -14, -25, 0, -14, -19, 17, 7, -12, 14, -11, 14, 5 },
-  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, -1, -43, 5,
-    6, -12, -48, 19, 8, -38, -8, -3, 22, -21, -10, 15, 20, -9, -5, 8 },
-  { 0, 0, 0, 0, -1, 1, -1, 0, 0, 0, 0, 0, 0, 0, 6, -3,
-    22, -14, -71, -24, -2, -33, 23, 7, -8, 7, -3, 2, -4, 1, -8, -2 },
-  { 1, 0, -1, 2, 0, -2, 0, 0, -1, 0, 4, 0, 26, -1, 10, -11,
-    -17, -32, -58, 14, -14, -11, -2, 15, 2, -8, 12, 10, -9, 13, -33, -14 },
-  { 15, -17, -19, 7, -8, -15, -32, -22, 7, 12, 18, 0, 0, -15, -4, 16,
-    37, -2, -46, 11, 2, -8, -10, -8, 14, 9, -4, 5, 7, -17, 4, 3 },
-  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -2, 0,
-    -5, 3, -85, 23, -9, -17, -2, -2, 0, 0, 0, 0, 0, 0, 0, 0 },
-  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -2, 0,
-    -5, 3, -85, 23, -9, -17, -2, -2, 0, 0, 0, 0, 0, 0, 0, 0 },
-  { 1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, -1, 0, 0, 1,
-    1, 7, -76, 41, -7, -24, 0, -6, 3, 6, 0, -2, -1, 1, 0, 0 },
-  { 0, -3, 4, 2, 3, 2, 2, 0, 3, -1, 4, 0, -1, 4, -2, -4,
-    -32, -11, -64, -29, -9, -43, 2, -11, -1, -7, 0, -4, -2, -2, -2, 2 },
-  { 10, -20, 3, -3, 13, 13, 0, -4, 2, 7, -8, 7, -2, 2, -20, -20,
-    -19, 3, -47, -18, -16, -6, -15, -42, -17, 14, -6, 8, 12, -10, 11, -12 },
-  { -3, -2, -2, -1, -1, 4, -3, -1, -6, -2, 3, 2, -3, 6, -1, -9,
-    10, 13, -68, -9, 26, 3, 5, 3, -21, 10, -15, 21, -22, 19, 11, -14 },
-  { 1, 5, 18, -19, -29, -13, -2, 18, -10, 20, 2, 10, -10, 11, 1, 8,
-    -16, -17, -41, 10, -14, -25, 0, -14, -19, 17, 7, -12, 14, -11, 14, 5 },
-  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, -1, -43, 5,
-    6, -12, -48, 19, 8, -38, -8, -3, 22, -21, -10, 15, 20, -9, -5, 8 },
-  { 0, 0, 0, 0, -1, 1, -1, 0, 0, 0, 0, 0, 0, 0, 6, -3,
-    22, -14, -71, -24, -2, -33, 23, 7, -8, 7, -3, 2, -4, 1, -8, -2 },
-  { 1, 0, -1, 2, 0, -2, 0, 0, -1, 0, 4, 0, 26, -1, 10, -11,
-    -17, -32, -58, 14, -14, -11, -2, 15, 2, -8, 12, 10, -9, 13, -33, -14 },
-  { 15, -17, -19, 7, -8, -15, -32, -22, 7, 12, 18, 0, 0, -15, -4, 16,
-    37, -2, -46, 11, 2, -8, -10, -8, 14, 9, -4, 5, 7, -17, 4, 3 },
-  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -2, 0,
-    -5, 3, -85, 23, -9, -17, -2, -2, 0, 0, 0, 0, 0, 0, 0, 0 },
-  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -2, 0,
-    -5, 3, -85, 23, -9, -17, -2, -2, 0, 0, 0, 0, 0, 0, 0, 0 },
-  { 16, 65, -2, -2, 4, 3, 0, -7, 3, 1, 3, 1, 0, 5, 1, -5,
-    0, 2, -1, 3, 0, 0, -1, -2, 6, 0, -2, 0, 0, -1, 1, 1 },
-  { 5, 37, -4, 8, -4, -1, 9, 17, 6, -7, 5, -1, 11, 6, -4, 7,
-    -2, 4, 1, -3, 11, 3, 3, -9, 6, 0, -2, -4, -5, 4, -12, -11 },
-  { 15, 24, -14, 2, 6, 17, 26, 5, 8, 11, -9, -7, -6, -8, 3, -5,
-    9, 10, -3, 10, 0, 1, 4, -9, 4, 9, 3, 0, 4, 0, -5, 3 },
-  { 9, 36, -9, -8, 7, 7, 4, 3, -1, -16, -2, 7, -5, -6, 6, 12,
-    -11, -12, 9, -1, -3, -9, 12, 6, -6, 2, 2, 5, 0, 5, 6, -6 },
-  { 25, 39, -5, 24, 3, 10, 3, -6, 13, -8, 3, -7, 2, -10, -5, 2,
-    -2, 3, 5, -2, 1, 5, -2, 3, -4, 1, -5, -4, 0, 1, -2, 0 },
-  { 16, 27, -1, 0, -14, 6, 4, -5, 7, -2, -6, 0, -3, -5, 2, -1,
-    -1, -19, 5, -8, 0, 11, 12, 5, 0, 3, 10, 6, -14, 14, -13, -15 },
-  { 12, 23, -14, 2, 1, 4, -3, 16, 7, -8, 2, -8, 8, 6, -8, -7,
-    -3, 0, 2, 8, -13, 7, 13, -6, -4, 6, -13, -16, 14, 11, -7, 5 },
-  { 16, 28, -7, -1, 6, -3, 9, 0, -7, 3, 0, 3, -12, 20, 8, 9,
-    8, 23, 8, -13, -2, 4, 9, 3, -5, 13, 5, -2, 12, 14, 5, -1 },
-  { 19, 37, 19, 5, 7, 5, 10, 5, 19, 10, 14, 0, 2, 5, 1, -4,
-    -4, 2, 2, -5, -2, -1, 2, -6, -4, -4, -5, -3, 2, -2, -2, -2 },
-  { 24, 21, 1, -11, -10, 17, -14, 14, 6, -1, -6, -1, 0, -13, -1, -12,
-    -2, -5, 6, -4, -12, 14, 5, -2, -8, -8, 15, -7, -30, -12, 4, 0 },
-  { 11, 26, -3, 3, 5, -1, -2, 3, -2, 10, 15, -4, 10, -28, 10, -17,
-    -8, 1, 2, -7, -1, -6, -15, -1, 4, 5, -7, 9, 0, -5, -4, 4 },
-  { 18, 32, 1, 2, -7, 4, 15, 2, -9, -2, 12, -11, 7, 11, 13, 2,
-    0, 5, 9, -10, 16, 3, -3, 5, -9, -23, 2, -2, -1, 5, 2, 11 },
-  { 35, 24, -20, 2, 4, -1, 5, 14, -10, -9, 8, -7, 0, 5, -7, -7,
-    11, 1, 5, 3, 2, 0, -2, 3, 0, 1, 4, 0, -2, -8, 0, -4 },
-  { 9, 35, -1, 2, -1, -19, -3, 12, -1, 8, 8, -13, -1, -2, 2, 5,
-    -8, -1, 13, -2, 11, 1, 0, -10, 0, -3, -7, 2, 1, -12, 3, 12 },
-  { 20, 27, -12, -12, 7, 4, -1, -13, -1, -9, 2, 13, -11, 5, 7, -9,
-    9, 1, 1, 8, -9, 0, -6, 7, 4, 2, -2, 7, 3, -2, 1, -9 },
-  { 8, 37, -20, -5, 0, -21, 10, -8, 3, 19, -9, 7, -3, -8, 10, -2,
-    0, 5, 6, -4, -2, -1, 0, -7, 6, 1, 0, 4, -5, 6, -8, 2 },
-  { 8, 27, 1, -3, -5, 1, 6, 0, 15, 2, 17, -1, 3, -17, 10, 5,
-    5, -6, -6, 6, -10, 18, -5, 0, 0, 13, 7, 10, -5, -6, -2, -4 },
-  { 14, 29, -20, -4, -3, 1, -5, -1, 2, 12, -10, -3, 4, -18, 4, 14,
-    -4, -1, -9, 15, -2, 2, -5, -3, 2, 9, -2, -14, -3, 4, -4, -7 },
-  { 23, 23, -23, -11, 27, 4, 4, -1, 7, 0, -5, 9, 2, -11, 3, 7,
-    -2, -5, 2, -7, -7, 13, -3, -6, 2, 3, 3, -4, -1, -8, 5, -2 },
-  { 16, 26, -6, 8, -9, -1, -2, -1, -8, 4, -2, 0, -12, 9, -1, 0,
-    -17, -9, 30, -5, -15, -16, -13, 0, 10, -11, -7, -3, -1, 0, -11, -2 },
-  { 12, 32, -4, -5, 10, 19, -10, 4, -12, 5, -6, 9, -12, -6, -6, -8,
-    4, 1, 3, 0, 8, 0, -3, -4, -7, -4, 10, 8, 6, 5, -1, 4 },
-  { 46, 42, -3, -14, -2, -6, 6, -2, -5, -1, -3, -3, 1, -1, 3, 1,
-    1, 4, -1, 2, 3, 1, -2, 6, 0, -1, -2, 4, -2, -1, 2, 2 },
-  { 9, 33, -13, 4, -11, 3, -8, 22, 12, -2, 4, 0, -16, 5, 4, -1,
-    7, -6, -9, 1, 7, 5, 0, -5, 5, -1, 10, 3, -2, -1, 3, -2 },
-  { 9, 30, 6, -3, 6, 1, -7, 5, 11, 14, 7, 1, 0, 2, 2, -1,
-    8, 7, -6, -13, -10, -2, 1, -6, 10, 7, 6, 5, -2, -5, -1, -16 },
-  { 9, 28, -11, -10, 9, -10, 15, 8, 4, 9, -4, -7, 0, -5, 9, 8,
-    -7, 2, -15, -23, 4, -4, 4, 16, -8, -3, 0, -8, 14, 5, -3, 15 },
-  { 17, 26, -5, -5, -1, -8, 20, 18, -7, -2, 4, -7, -8, -5, -4, 16,
-    0, 0, -7, -2, -13, -5, -2, 3, 12, 1, 3, -5, 2, 2, 0, -1 },
-  { 11, 37, 7, -23, 6, -1, 15, 13, 4, -9, 7, 5, 3, -3, -5, -8,
-    -2, 3, -5, -1, -8, 7, 2, 13, 1, 3, 0, -3, -1, 2, 0, -2 },
-  { 21, 33, 7, 20, 21, -10, 6, -5, -5, -6, -9, 2, 10, 0, 8, -4,
-    10, 2, -2, -2, 0, -10, -6, -2, 0, -5, 3, -11, 3, -9, -3, 1 },
-  { 6, 30, -15, -8, 16, 1, 4, 6, 4, 5, 8, -3, 8, -9, -1, -6,
-    8, 2, -2, 4, -2, 5, 11, -21, 3, -10, 16, -11, 24, 10, 14, -6 },
-  { 15, 36, -3, -9, -20, 12, 0, -7, -18, -4, -8, -9, 9, -7, -3, -1,
-    2, 7, -5, -8, 6, 2, 2, -1, 7, 1, 1, -3, 3, -4, -8, 1 },
-  { 16, 34, 21, 3, -9, 10, 7, 9, -7, 1, -4, -9, -4, -5, -5, 3,
-    3, -19, 1, 5, 4, -2, -6, -5, -10, -11, -8, -2, 2, -5, -8, -7 },
-  { 28, 29, -3, 18, -2, 0, -6, 12, -2, 10, -11, -4, -13, -12, -6, -4,
-    0, 4, -1, -8, 6, 4, 12, 11, 10, 10, -3, -6, 1, 2, 1, 7 },
-  { 3, 8, 22, -8, 3, 36, -8, -1, 9, 6, -13, -14, 8, -1, 1, 2,
-    -2, -8, 0, 3, 1, 2, -1, 5, -1, -8, 0, -2, 2, 2, -1, 1 },
-  { 0, 6, 0, 0, 4, 13, -7, -16, -6, 15, -14, -21, -9, -10, -10, -6,
-    -21, 5, 4, 2, 12, 4, 12, 11, -4, -6, -6, -10, -7, -18, 1, 4 },
-  { -1, 3, 10, 1, -1, 15, 4, -7, -16, 3, 0, -22, 10, 2, -3, -2,
-    13, 5, -8, 16, -5, 4, 0, -11, -10, -22, 0, -4, -17, 5, 2, 1 },
-  { 12, 8, -4, -9, 14, 40, -21, 0, 1, -15, -10, -12, 12, 6, -10, 2,
-    8, 6, -12, -10, -11, 1, 0, -11, 2, 1, 13, 0, 6, 3, 8, 4 },
-  { -10, 3, 5, -4, -3, 3, 0, -9, 2, 8, -22, -23, 17, 8, -17, -3,
-    14, -8, -4, 1, -8, 3, 0, 5, -1, -3, -2, -4, 1, -10, 0, -2 },
-  { 0, -1, 5, -7, 4, 12, -2, 0, -7, 2, -16, -15, 12, 21, -7, -4,
-    7, -7, -11, -15, -7, -9, -5, -8, 0, -6, 8, -3, -8, 22, -7, -9 },
-  { 7, 19, 4, -9, 24, 22, 2, -6, 8, 13, -14, -20, -4, 11, 8, -4,
-    -1, 2, 0, -7, 5, -17, -3, 3, -6, 5, 3, 4, -5, -7, -3, 14 },
-  { -2, 6, 2, 8, -2, 5, -4, -2, -10, 3, -45, -30, -3, -3, -12, -4,
-    -3, -3, -1, 9, -6, -6, 5, -4, 0, 5, -1, -2, -1, 0, -6, -1 },
-  { -3, 14, -16, -10, 10, 0, -2, -40, -9, 12, 2, -19, 15, -4, 4, 3,
-    3, -4, 7, 1, -4, -5, 0, 4, -1, 0, -9, -2, -4, -1, -2, 0 },
-  { 7, 16, 2, -7, 8, 2, 0, 1, 5, 21, -10, -26, 7, 2, -9, -7,
-    -3, -16, 8, 5, 5, -6, 10, 4, -14, -6, 5, 3, -2, -2, -4, 1 },
-  { -9, 14, -1, 3, 3, 11, 1, -5, -3, 13, -16, -18, 20, 6, -5, 0,
-    -3, 2, 8, 4, -19, -9, 12, 0, -8, 2, 2, 1, 6, 13, -7, -11 },
-  { 2, 5, 16, -4, 19, 15, 4, 0, -11, 7, -10, -10, -16, 18, -11, -12,
-    -9, -4, 7, -4, -4, -17, 1, 1, -8, -3, -3, 5, -2, -6, -11, -5 },
-  { 2, 12, 0, -9, -10, 14, 6, 2, -3, 2, -12, -28, 12, 1, -1, 2,
-    0, -3, -4, 7, 16, 5, -7, 8, -4, -3, -1, 3, -12, 4, -17, -5 },
-  { -4, 7, 11, 6, 1, 14, -4, -6, 5, 5, -6, -24, 23, -9, -15, 13,
-    -7, -9, -15, 10, -1, 8, -5, 1, 12, 6, 2, 0, 4, -2, 9, -10 },
-  { 1, 5, 11, 3, 6, 12, -3, 8, -21, 5, -7, -20, 12, -2, -9, -3,
-    17, -7, -8, -9, -14, 3, -13, 18, -8, 9, 2, -8, 4, -8, -5, -2 },
-  { -3, -3, -1, 5, -2, 15, 3, 2, 1, -8, 1, -39, -6, 13, -13, 0,
-    -2, -5, -6, -3, 0, -5, -2, 15, -9, 5, -3, -6, -2, 7, 0, -13 },
-  { 2, 8, 5, -12, -13, 22, 8, -16, 11, 5, -2, -32, -2, -4, 11, 5,
-    5, -6, 1, 3, 1, 5, 3, 6, -5, 4, 4, -8, 8, 4, 1, 3 },
-  { 13, 9, 5, -4, 9, 18, -11, 2, -1, 15, -10, -19, -2, 14, 0, -10,
-    1, 1, -18, 3, 2, -6, -8, 20, 7, -8, 16, 9, 9, -13, -3, -2 },
-  { -13, 11, 11, -9, -10, 13, -3, -18, 2, 10, 5, -21, 6, 15, -11, -21,
-    3, 14, 0, -12, 9, -1, -2, -4, 3, -3, -9, -8, -5, -2, -8, 2 },
-  { 3, 3, 11, 4, 0, 13, 1, -8, 10, 13, -6, -26, 2, 12, -3, -5,
-    12, -2, 1, 8, -7, -17, -19, 5, 10, 7, -3, 2, -3, 0, 5, 0 },
-  { 5, 0, 3, -3, -9, 5, -15, -5, -5, 17, -5, -31, 0, 13, 13, 5,
-    -1, -6, -14, 7, -8, 9, -14, -2, -16, -4, -4, -6, 6, -6, -10, 6 },
-  { 13, 3, 1, 7, -3, 4, -1, -2, -1, 4, -8, -32, -1, -4, 0, 3,
-    -10, 7, 10, -10, 4, -1, 6, 2, -16, -9, 4, 3, 13, -23, -3, -4 },
-  { 4, 11, -4, -9, 4, 11, -12, -12, -12, 6, 1, -28, -3, 14, 18, -2,
-    -12, 7, 15, -3, -5, -7, -3, 2, -6, 4, 4, -2, -5, -3, 2, -13 },
-  { 8, 7, -7, 0, 13, 7, -8, -7, 8, 36, -10, -22, 3, 23, -3, -10,
-    -3, 11, 1, -7, 3, 3, -1, -7, -4, 2, 3, 2, 5, 3, -4, -1 },
-  { -1, 1, 13, 1, -6, -1, -6, -9, -18, 17, -5, -37, -1, -1, -6, -4,
-    1, -6, -15, 2, 17, -9, 0, -3, 0, 4, 0, -5, 0, 4, 1, -5 },
-  { 0, 14, 5, 0, -7, 2, -6, 17, -6, -9, 7, -16, -5, 23, -14, -13,
-    8, -15, 11, 10, -11, -13, -33, -5, -2, 1, 6, 8, 0, -13, -9, 5 },
-  { 11, 7, -2, -8, 9, 11, 25, -14, 7, 3, -1, -33, 14, 8, -6, -19,
-    3, 3, 2, -1, -3, -1, -2, -10, -3, 1, 2, 1, 4, 2, -3, 4 },
-  { -2, 8, 4, -2, 9, 13, -4, -2, -15, -3, 19, -37, 9, 25, -9, 2,
-    -5, -2, -2, -4, 4, 2, 2, 0, 3, 3, 3, 5, -2, -3, -4, -3 },
-  { 10, 13, -1, -15, 4, 6, -18, -4, 25, 1, -23, -17, 15, 13, -8, -8,
-    7, 4, -5, 3, 6, 9, -7, 6, 0, -5, 8, 0, -6, -1, -2, -2 },
-  { 1, 3, 9, -5, 27, 15, -9, -31, -1, 23, -2, -9, 1, 8, -1, -7,
-    -2, -8, -4, -4, -2, -1, 3, 5, 0, 0, -1, 1, -7, 7, -3, -3 },
-  { -8, 7, 3, -6, 8, 3, -11, -2, 36, 14, 1, -30, 6, 10, -12, -6,
-    -6, -2, -4, -3, -5, 0, 9, 4, -5, -5, -8, 12, 4, -3, 1, -8 },
-  { -2, 9, 33, 0, 12, -3, -7, -4, -4, -1, 6, -25, 11, -6, -9, -11,
-    -2, -4, -2, 6, -1, -3, -6, 15, -6, 3, 10, -4, 1, 0, 5, 8 },
-  { -22, -21, -9, -19, -5, -7, -12, -15, -8, 9, -19, 14, -7, -4, 5, -8,
-    -2, 7, 1, -3, 4, -4, 6, 11, 2, 6, -3, -5, 2, -2, 0, -3 },
-  { -32, -13, 3, -24, 3, -8, 4, 1, -10, 14, -15, 0, 4, 6, -1, 6,
-    7, -1, 6, 4, -3, -17, 1, 4, -6, -1, 1, 0, 3, 3, -7, -4 },
-  { -32, -11, 7, -8, -12, 13, -5, -22, -4, 12, -16, 2, 0, 4, 0, 1,
-    0, 6, -5, -8, 2, 6, 5, 0, -3, -6, 5, 6, 5, 5, 13, -4 },
-  { -44, -33, 6, -4, 2, 0, -9, 10, 3, 4, 7, 0, -1, 7, 5, 1,
-    1, -3, 1, 6, -1, 0, 2, 3, -4, 0, 0, 1, 0, -1, -2, -1 },
-  { -30, -18, -24, -8, 5, 0, -2, 14, 7, 0, 1, 12, 6, 4, -9, 7,
-    5, 7, -11, -5, 1, -8, -1, 2, 2, -9, 7, -1, 7, 5, 6, 6 },
-  { -22, -20, -13, -9, 20, -3, 10, -8, 6, -4, 2, -7, 10, 8, 0, -1,
-    2, -3, 6, -19, 2, 4, 3, 3, -7, 2, -1, -6, 1, 1, 6, -2 },
-  { -27, -8, -1, 3, -1, -11, 24, 4, -1, 1, -8, 8, 5, -11, 15, -3,
-    -15, -1, -1, -13, -1, 1, -5, 5, 2, 3, -9, 0, 4, 3, -7, 6 },
-  { -33, -16, -1, -8, 10, -23, 6, 13, -1, -3, -9, 0, 5, -7, -5, -12,
-    -2, 3, 3, 6, -2, -3, 2, -3, 9, -6, -3, -2, 0, 5, -3, -4 },
-  { -22, -17, 11, -3, 3, 1, -1, -5, 17, 2, -15, -2, 10, -9, 6, 14,
-    -16, -12, 20, -1, -7, 6, -3, -12, 1, 10, -10, -1, 7, -3, -1, 10 },
-  { -28, -13, 1, -3, -1, -1, 0, 3, 3, 5, 1, 10, -10, -3, 7, 2,
-    4, 19, -1, -1, 10, 5, -8, 1, 11, -15, -4, -3, -5, 4, -13, 3 },
-  { -22, -13, 42, -20, 5, -13, 7, -11, 1, 1, -1, 1, 6, 3, 6, -11,
-    3, 3, -2, 0, -4, 4, -3, -1, -5, 2, 0, 0, -9, -1, 4, 4 },
-  { -26, -15, -2, -6, -4, -2, 16, 8, 21, 8, 1, -3, -10, 7, -8, -12,
-    -5, 12, -9, 3, -2, -3, 18, 1, -12, -15, -4, 5, -3, 0, 12, 7 },
-  { -26, -16, 5, 6, 14, -3, 15, 6, 1, -7, -13, 16, -15, 5, 11, -2,
-    9, -7, -4, -2, 0, 0, -2, 7, -8, -6, -5, 2, 7, -3, 2, 12 },
-  { -31, -17, -8, -30, 4, 14, 6, -6, 6, -11, 0, 3, -4, 0, 0, -4,
-    0, -4, 1, 4, 3, 4, 0, -5, 3, 2, 2, 0, 2, 1, 3, 5 },
-  { -61, -10, 4, 10, 4, 7, 0, -3, 0, 1, 0, -3, 0, 1, 0, -2,
-    -1, 1, 2, -2, 4, -3, 1, 1, -1, 1, -2, -4, -4, 4, 0, 0 },
-  { -28, -13, -8, -4, 3, -3, 2, 1, 11, 14, 3, 9, 1, 13, 3, 5,
-    -3, -2, -2, -12, -14, -9, -11, -15, -12, -5, -4, -12, 3, -3, 0, -5 },
-  { -41, 0, 12, -24, 13, 4, 5, 16, -5, -4, 0, 0, 13, -4, 1, -9,
-    9, -6, -1, 6, -2, 5, 2, 9, 6, -9, -8, 8, -2, -3, -6, -4 },
-  { -26, -19, -2, -15, 4, -14, 6, 0, 26, 20, 8, 9, 9, 3, -4, -5,
-    -8, 1, 0, -1, 5, 9, 3, 4, 4, 7, 1, 3, -2, -2, -10, 0 },
-  { -29, -18, 9, -4, 1, -5, -14, -12, 5, -10, -5, 4, -5, 0, -1, -1,
-    4, -5, 7, -16, -11, 2, 7, -15, 2, -4, 6, -4, -6, 7, -3, 7 },
-  { -27, -16, 9, -14, 3, -8, 9, 0, 7, -4, -3, -7, 0, -10, -1, 2,
-    1, -2, 15, -10, 14, 7, 6, 17, 3, -4, 3, -10, 8, -8, 3, 11 },
-  { -21, -20, -8, -8, 4, 5, -3, -2, 0, -5, 14, -10, 11, -4, 13, 0,
-    5, -11, 19, -18, 18, 3, -5, -3, -4, -8, 11, -10, 10, 3, 4, -9 },
-  { -35, -15, 13, -12, 4, 0, -2, -4, -12, -3, -8, -24, -7, 1, 7, 8,
-    -3, 0, -2, -1, 3, -2, -2, -6, 8, 1, 0, 1, -6, -1, 2, -6 },
-  { -19, -14, 13, -10, 9, -1, 1, 3, -12, 5, -16, 7, 13, 9, 4, -4,
-    6, -5, 4, 9, -3, 17, -4, 12, -11, -6, -5, -6, 13, 2, 7, -9 },
-  { -34, -8, -4, 1, 2, -1, 3, 6, -20, -11, 8, -1, 4, 2, -9, 4,
-    -4, -5, 16, 10, -4, 14, -13, 1, -6, 0, 2, -10, 0, -3, -3, 7 },
-  { -36, -10, -8, -3, 2, -2, 14, -4, -1, -7, -4, 10, -1, -3, 15, -11,
-    0, 2, 3, -1, 4, 0, 8, -1, 0, 18, -11, -5, 15, -5, 13, -12 },
-  { -22, -13, 14, -20, 15, 25, 16, 10, 8, -2, -10, -5, -1, -8, 11, 8,
-    -1, -2, -4, 1, 2, -1, -7, 0, 0, 0, -3, 0, 2, -1, 0, 2 },
-  { -31, -22, 7, 6, -2, 5, -20, 14, -6, 7, 0, 14, 3, -7, 3, -6,
-    -2, 1, -3, -5, 1, -10, 1, -24, 6, -2, 3, -7, 1, -7, 8, 7 },
-  { -25, -20, -3, -9, 10, 6, 12, 7, 5, 4, -3, 6, -1, -5, -6, -8,
-    3, 5, 6, 5, -10, 10, -4, -15, -15, -2, -9, 2, 18, 1, 8, 12 },
-  { -24, -19, -2, -4, -7, 11, 6, 9, 16, 2, -7, 18, 6, -7, 6, 6,
-    -2, -9, 3, 12, -2, 3, -1, 6, 7, 8, 0, 8, -11, 8, 4, 2 },
-  { -26, -20, -12, -12, -2, -3, 1, -5, -1, -2, 0, 3, 7, 9, -2, 2,
-    9, 22, 13, 4, -4, -1, -2, -14, 5, 15, -8, -5, -7, -11, -14, -6 },
-  { -21, -18, -1, -4, 0, 3, 7, -2, 10, 8, -8, -1, 15, 1, -9, 3,
-    1, 3, -5, -2, 2, 4, 0, -1, 10, 2, -19, -8, 8, 30, -7, 8 },
-  { -25, -6, 26, 4, -8, 4, -2, 21, 5, -4, -16, 5, 13, 4, -10, -1,
-    -6, -2, 2, -10, -13, 1, 3, -3, -6, -8, 2, 11, 1, -7, 0, 5 },
-  { 0, -1, -2, 19, -12, -48, -6, 11, 8, -2, -4, -2, -7, 5, -3, 2,
-    -2, -1, -1, -7, 0, -3, -3, -4, -4, 4, 1, 3, -3, -1, -2, -5 },
-  { -11, -8, -28, 18, 16, -24, -8, 19, 4, 8, -12, 9, -4, -2, 4, -7,
-    6, 2, 3, 3, -4, 0, 1, -6, -4, -2, 2, 6, 0, -3, 1, -16 },
-  { -9, -5, -26, 7, -3, -37, -16, -2, 2, -7, 4, -13, 0, -4, -6, -5,
-    -6, -4, 0, 3, 4, -3, -4, -4, 4, -3, 9, -4, -2, 2, 7, -4 },
-  { 2, 9, -18, 7, 29, -24, -1, 7, 14, 10, 3, -3, -2, -5, 6, -10,
-    -6, -3, -8, 0, 5, 1, 4, 3, -12, 2, 6, 1, 3, 4, 1, -3 },
-  { -20, 2, 8, 20, -9, -24, -4, 18, 3, 11, -1, -11, 6, 9, -1, -3,
-    1, -1, -15, 3, 15, 9, 3, 2, -13, 2, -8, 8, 1, -1, 1, -8 },
-  { -12, 5, -11, 6, 19, -26, -17, -6, 4, 14, 6, -8, 9, 5, -6, -5,
-    2, -1, 20, 1, -11, -10, -18, 20, -7, 0, -3, 4, 2, 0, 10, 4 },
-  { -15, 1, -2, 13, -8, -21, -22, 4, 4, 3, 3, -7, -31, 4, -10, -14,
-    0, 8, 4, 5, 8, 11, 2, -8, 6, 7, 0, -2, 6, 8, 8, 7 },
-  { -13, -10, -9, 12, 19, -16, -3, -2, 9, 2, 11, -29, -1, 9, 4, -3,
-    1, -10, -10, 16, 1, 7, -7, -6, -4, -1, -5, 3, 6, 0, 3, 1 },
-  { -17, -1, -5, 19, 12, -9, -21, -5, 2, 12, -7, -7, -3, 8, 7, -2,
-    6, -9, -9, 1, -4, 1, 1, 3, -14, 2, -8, 0, 10, 1, -12, -6 },
-  { -13, -5, 8, 15, 0, -20, -2, 20, 8, -8, 8, -19, 12, 10, 2, -11,
-    0, 12, 1, -11, 0, -11, -15, 5, -11, 2, 4, -4, -11, 5, -4, -5 },
-  { 3, -11, -7, 8, 0, -17, -26, 15, 19, -7, 10, -9, -5, -5, 14, -25,
-    0, -8, 2, -9, -3, 9, 1, -6, 4, -4, 3, -9, -1, 6, 2, 2 },
-  { -12, 5, 5, 9, 14, -18, -19, 4, 2, 16, 14, -21, -15, -9, -1, 16,
-    12, -11, -10, -5, -7, 4, 15, -8, -5, -1, 1, 14, 13, -7, -1, -4 },
-  { -10, -5, -1, 8, 7, -23, -10, 14, 6, 11, 10, -16, -3, 16, 6, 0,
-    0, 9, 6, -2, -7, 1, 22, 5, 3, -8, 0, 3, -2, -10, 3, 0 },
-  { -2, -14, 2, 16, 15, -17, -17, 6, 19, 4, -10, -15, -1, 15, 11, -14,
-    -8, 5, 8, 8, -2, -8, -11, 10, 10, -8, -14, 2, 13, 4, -2, -12 },
-  { -10, 3, 6, 4, 19, -23, -19, 1, 4, -9, -30, 3, -6, 18, 0, 2,
-    0, -11, 0, 3, 7, -2, 8, 5, 2, -3, 6, -9, 1, -4, 7, -6 },
-  { 9, 5, -2, 21, 20, -33, -13, 7, -10, 8, 8, -15, -6, -4, 1, 5,
-    3, 7, -2, -9, -1, 4, -6, 1, 0, 9, -1, -5, 2, 1, -3, 3 },
-  { -9, -3, 3, 15, -3, -30, -7, -7, -25, 6, 2, -6, 1, 19, 1, -12,
-    1, -8, -13, 9, 13, 1, 8, 2, 5, 15, -2, 3, -9, 0, -4, 4 },
-  { -6, -12, -17, 25, 22, -13, -10, 9, 2, 11, -7, -16, 4, 6, 1, 0,
-    0, 18, -4, -5, 4, -2, -1, -5, 0, -4, 6, 1, 6, -1, 7, 0 },
-  { -1, 0, -10, 8, 8, -27, 0, -2, 29, 16, -2, -4, 9, -1, 2, 0,
-    6, 10, 6, 4, 2, -7, 9, -18, 3, 3, 3, -10, 17, 10, 9, -6 },
-  { -3, -12, -6, 11, 20, -32, 5, 21, 3, -4, -9, 2, -10, 1, 7, -4,
-    5, 0, 0, -1, -8, -9, -7, 4, -10, 5, 0, 2, -5, 4, 9, 1 },
-  { -5, -1, -5, 1, 2, -19, -13, 1, 6, 12, 2, -16, -17, 11, 10, 13,
-    16, -12, -11, 3, -6, 0, 6, 4, -3, 1, 8, 2, 5, -11, 3, -14 },
-  { -19, 5, 10, 11, 2, -23, -9, 16, -2, 7, 0, -11, -7, 10, 6, -7,
-    26, -15, -4, 8, 6, -4, 7, -9, -15, 1, 8, -4, 4, 2, -12, 16 },
-  { -11, 1, 11, -4, 1, -31, -13, -1, 8, 5, 4, -2, 0, 13, 7, -17,
-    7, -10, -6, 1, 4, -1, 2, -9, -4, 9, 3, 3, -4, -5, 3, 4 },
-  { -3, 1, 10, -1, 0, -15, -22, 4, 40, -11, -4, -3, -14, 9, 11, -1,
-    9, -1, -6, 6, 3, -6, 0, 0, -12, 7, -2, 0, 9, 3, 1, 3 },
-  { -1, -1, -1, 14, 8, -24, -14, -8, 5, 8, 5, -12, -17, 8, 2, 7,
-    10, -8, 0, 4, -6, -6, -10, 8, 4, -12, 3, -9, -12, 5, 4, -3 },
-  { -5, 1, -11, 8, 9, -24, 0, 2, 2, 14, -12, -13, 1, 6, 7, 0,
-    7, -6, 9, 26, 11, -14, 8, 10, 1, 9, 0, 11, -2, 6, 2, -10 },
-  { -13, 1, 4, 34, 19, -17, -15, 0, 3, -2, -7, -1, 0, -3, -3, -1,
-    1, -1, -10, 8, 5, 0, -8, 4, -17, 9, -2, 0, 0, 6, 2, -3 },
-  { -6, -4, 1, 2, 2, -14, -29, 0, 9, 34, -3, -5, -14, 6, -10, -9,
-    -5, -1, 0, 3, 3, 0, 1, -1, -2, -1, -1, -3, -3, -4, 3, -3 },
-  { -4, 6, 3, 14, 14, -8, -29, 31, 11, 14, -4, -5, -6, 10, 6, -9,
-    -1, -11, -7, 1, 7, 4, 1, -6, 4, 0, 10, -7, -5, -1, 2, 4 },
-  { -4, -4, -2, 14, 6, -32, -6, -14, 14, -5, -11, 10, -18, -4, 6, -8,
-    9, 5, -4, 1, -4, 5, -2, -9, 3, 5, 2, -10, -6, -17, 3, 17 },
-  { -16, 9, 21, 19, 4, -20, -17, 14, 9, 15, -6, -17, -1, 1, 6, -3,
-    1, 1, 8, -3, -6, 6, 9, 4, 9, -9, -5, 1, -1, 0, -1, 2 },
-  { -7, -5, 3, 19, 1, -20, -9, 14, 21, -7, -18, -9, 26, -7, -17, -7,
-    12, 6, 0, -9, -6, 14, 9, -9, -8, 4, 15, -7, -9, -1, 9, 1 },
-  { -20, 30, -6, 11, 24, -4, 0, -6, -2, 8, -4, 12, -8, -17, 0, 5,
-    -4, 1, -1, 3, -3, 5, 3, 3, 7, -2, -3, -2, 4, 0, 0, -1 },
-  { -35, 17, 6, 1, -9, -1, -16, 3, -20, -13, 8, 7, -4, -7, -4, -20,
-    7, 12, -5, 5, -5, -11, 12, -1, 15, -9, -6, 16, -4, -9, -13, 4 },
-  { -21, 36, -19, 9, 0, -7, -8, 9, -4, -3, 3, 0, 7, -8, -2, -2,
-    -11, 13, -1, 5, -3, 7, 2, 3, -1, -2, -5, 1, -1, -2, -5, -3 },
-  { -12, 33, -4, 1, -12, -9, 0, -13, -1, 2, -8, 4, -10, 6, -16, -7,
-    -1, -4, -10, 15, -1, 0, -5, -8, 5, 5, -3, 0, 2, -7, 1, -7 },
-  { -14, 32, 5, -7, -15, 3, -5, 8, 14, 5, 9, 13, 3, 18, -3, 7,
-    4, -10, -10, 10, -1, 2, 0, -2, -11, 5, -3, -4, 2, 2, 7, 4 },
-  { -14, 34, 1, 20, -1, -12, 0, -3, -7, -4, 7, 18, 9, -3, 14, -7,
-    -9, -20, -7, -4, -13, 12, 1, 12, 5, -6, 2, -4, 0, -15, 1, 3 },
-  { -21, 23, 7, -8, 3, -13, -3, 0, -6, -2, -7, 6, -12, 9, -6, -2,
-    -2, -4, -1, 6, 9, 5, -9, 15, 0, 8, -8, 7, 6, -15, 3, -5 },
-  { -27, 32, -1, -4, -2, 4, -10, 12, -3, 8, 13, 7, 0, -15, 4, -2,
-    3, 5, 7, -4, 9, -12, -1, -2, -1, -4, 0, -4, 2, -5, 6, -6 },
-  { -17, 29, 15, 0, -1, -4, -10, 13, 12, -1, -8, -10, -10, 4, 7, -2,
-    6, -5, -13, 19, 6, 1, -7, 2, -9, -2, 12, -4, -8, -3, 2, 4 },
-  { -38, 27, 16, -15, -6, 3, -7, -4, 0, -1, 6, -2, -3, -6, 6, -6,
-    -3, 0, 2, 0, -4, 6, 1, -1, 0, 4, -1, 3, 4, 1, -2, 5 },
-  { -33, 40, -4, 2, 1, 0, 0, -10, -14, 0, -7, 4, -1, 3, -2, 5,
-    7, 6, -1, 4, 1, 3, 1, -7, 1, -4, 5, 7, 0, 4, 3, -4 },
-  { -20, 25, 12, -4, 16, -4, 2, 2, -14, -2, -3, 29, -1, 1, 3, 1,
-    9, -5, 2, -8, -3, 1, -7, -2, -7, 1, 0, 4, 16, -2, -1, -1 },
-  { -10, 30, 17, 3, -5, -2, 0, -5, -22, 4, 5, 5, -3, -18, -6, 10,
-    -5, -7, 2, 8, 7, -7, -11, -2, 0, -3, 3, 2, 11, -4, 4, -4 },
-  { -11, 30, 11, 4, -3, -8, 1, -2, 4, 18, 3, 1, -1, 0, -8, -4,
-    -3, 10, 13, 14, 5, -5, 1, 1, -10, 2, 15, 4, 9, -1, -5, -3 },
-  { -17, 32, 18, -18, -3, -5, 6, 10, 1, -15, -5, 9, 8, -12, -10, -6,
-    11, 9, -5, -8, -7, 10, 5, -10, -14, -4, -3, 1, 9, -11, 2, 1 },
-  { -13, 28, -11, -1, 2, -16, -2, 7, -24, 0, 3, 6, 3, -1, -8, -7,
-    -12, 2, 2, -20, 10, 4, 0, -13, -2, -2, 1, 8, -14, 0, 4, 1 },
-  { -14, 23, 12, 8, 8, -26, 2, -4, -14, 13, -14, 15, 3, -9, -1, -13,
-    -10, -2, -10, 6, -16, 12, 8, 0, 9, -10, -7, -4, -4, 7, -8, 8 },
-  { -20, 45, 10, -14, 4, 16, 8, -9, 1, -8, 10, 5, -7, -2, 2, -5,
-    -1, 0, -5, 4, -6, -2, 4, 1, 3, 4, -4, 2, -2, -2, 5, 1 },
-  { -20, 26, -4, 1, 7, 4, -8, 1, -5, -13, 2, 13, -7, -3, 6, -6,
-    22, 0, 5, 11, -4, -11, 8, -9, 2, -2, -4, -2, 2, -13, -4, -8 },
-  { -28, 18, 17, 3, -8, -23, -16, -6, 5, -10, 14, 10, 5, -1, -8, 4,
-    -2, 13, -3, -2, 3, 4, 3, -2, -3, -4, 0, 1, 3, 4, 0, 4 },
-  { -12, 32, -6, -16, 18, 12, -16, 0, 7, 13, -4, 5, -8, -1, -3, 4,
-    6, -2, -1, -13, 4, -1, 3, 12, -3, -10, 1, 6, 8, -11, -2, 4 },
-  { -18, 26, 2, 5, 0, -9, -17, 14, 5, 1, 7, -3, -8, -3, 11, 7,
-    -5, -12, -8, 7, 0, -7, 2, -12, -9, 13, -11, 9, 6, -11, -5, 11 },
-  { -24, 22, -15, -9, 8, 1, -7, -12, -9, 3, 11, 15, 14, -11, 12, -15,
-    -5, 7, -2, 0, -8, 3, 3, -1, 2, 11, -11, 14, -6, 13, 1, -6 },
-  { -20, 28, 18, -4, -6, -5, 12, 14, 2, 10, -13, -6, -8, -6, -13, -1,
-    -26, 22, -3, -14, 6, 0, 10, -15, -13, -9, 6, -7, 1, -5, -4, -1 },
-  { -19, 26, -8, -3, -14, -6, -9, -4, -8, 15, -8, 3, -12, -4, -2, -7,
-    -5, 3, 13, -3, -4, -25, 4, -1, 5, -12, -1, -13, 5, 2, 0, 6 },
-  { -18, 43, 14, -8, 1, -23, -2, -2, 1, 3, -7, 0, 0, 8, -1, -3,
-    -5, 1, 5, 2, 0, -2, -2, -2, 1, -1, -1, -7, 0, 3, -3, 9 },
-  { -11, 30, 10, -14, 3, 1, 10, -11, 1, -7, -4, 14, 2, 1, -9, 1,
-    -11, -2, -7, 5, -11, 1, 3, 14, 1, -16, -8, 3, -5, 7, -4, 4 },
-  { -18, 24, 6, 3, 8, 7, -22, -7, -7, 3, -8, 4, 23, 9, 3, -1,
-    3, 6, 7, -1, -7, 6, 4, 1, -3, 1, -6, -1, 2, -7, 3, 3 },
-  { -15, 38, -7, -1, -11, 2, -17, -24, 24, 8, 7, -4, -5, 2, 2, -7,
-    1, 4, 0, -9, 5, 0, -1, 1, -1, -5, -6, 3, 0, 7, 8, -3 },
-  { -14, 22, 1, -5, 9, -12, -9, -5, -6, 5, 7, 8, -1, -4, -9, -3,
-    -33, -16, -9, -1, 12, -11, 17, -7, -3, -1, -7, 3, 2, -3, 16, -4 },
-  { -14, 20, 6, 4, -10, -4, -4, -4, 1, -7, 2, 6, 8, -12, 4, 1,
-    -1, 12, 10, 3, -14, -10, -3, 18, -2, 33, -5, -17, 17, -5, 9, 7 },
-  { -12, 23, 13, 0, -11, -8, -11, 12, -5, -9, -16, 11, 6, 4, 12, -5,
-    5, -13, 7, -12, -3, 1, 2, 12, 1, -4, -1, 5, 4, 11, -12, -3 },
-  { 15, 2, 14, 7, 1, 2, 1, 12, 10, 23, 4, 6, -20, -10, 4, 26,
-    -6, 13, 4, 3, 2, -11, 5, -7, -10, 4, 9, 1, 10, -4, 11, 4 },
-  { 17, 15, 31, 17, 18, 16, 11, 24, 2, 4, 2, 3, -8, -3, 7, -3,
-    -5, -7, -2, -6, -4, -5, -4, -1, -4, -2, -5, -6, 2, -1, 4, -2 },
-  { 16, 8, 15, 14, 3, 7, 21, 9, 8, 15, 21, 6, 8, 12, 5, -5,
-    7, -3, 10, 2, -3, 8, 6, 0, 5, 5, 6, -3, 2, 4, 0, -5 },
-  { 5, -4, 6, 12, 6, 13, 24, 17, -5, 17, -1, -6, -7, -10, -8, -18,
-    3, -2, 2, 7, -15, -11, 12, -3, -2, -2, -4, -7, 2, 0, 5, 5 },
-  { 10, -6, 8, 11, 12, 20, 22, -11, -3, 15, -3, 15, -2, -2, 0, 2,
-    5, -8, 4, -5, -9, -4, -1, 2, -1, -3, 1, 3, 13, -1, 9, 7 },
-  { -5, 8, 5, 11, 14, -5, 14, -9, 2, 35, 8, 15, 1, -2, 2, -2,
-    4, -9, -3, -14, -12, -2, -2, -4, -2, -8, -3, 1, -6, 3, 10, 0 },
-  { 16, 0, -6, 15, -3, 4, 4, 3, 3, 20, 5, -4, 10, 9, -9, -3,
-    -10, -2, -7, 11, -11, -10, 17, -1, 3, -15, 2, 9, -15, -10, 16, 10 },
-  { 14, 4, -7, 19, 3, 0, 19, 8, 16, 34, -9, 6, -13, -1, 6, 5,
-    -1, -2, 4, 3, 2, 1, 1, -1, 0, -7, 2, -1, 1, 0, 6, -1 },
-  { 1, 6, 9, 13, 9, 10, 15, 16, 10, 18, 13, 17, 3, -1, -7, 2,
-    -15, -11, -10, -4, -13, -6, -17, -13, -6, -14, 1, -10, 6, 4, -1, -1 },
-  { 13, 1, 7, 10, 14, 13, -7, 5, 5, 28, 14, 14, -2, 2, 3, -3,
-    -13, -4, 10, -9, 19, -4, -3, 4, -5, -5, 0, 5, -5, 0, 3, -4 },
-  { 1, 0, 6, 22, 9, 18, 18, -3, 5, 10, 12, -2, 1, -3, -8, -12,
-    9, -10, -7, 1, -1, 19, 0, 2, -8, -11, -10, 9, 6, 11, 0, 3 },
-  { 10, 11, 19, 44, 0, 14, 1, -7, 6, 22, 2, -1, 9, 2, 0, -4,
-    4, 0, -6, -6, 3, 0, 0, -2, 2, -5, 1, -2, 0, 1, 1, 1 },
-  { 5, 7, 0, 32, 30, 26, 5, 4, -7, -3, 15, -6, 3, -10, 7, 6,
-    -8, -7, 2, -13, -5, -1, -3, 7, 3, -2, -8, 0, 6, 4, 5, 0 },
-  { 9, 8, -2, 4, 2, 11, 4, 29, -5, 14, 8, -5, -14, 8, 0, 9,
-    8, -10, 5, -15, -6, -9, 9, -1, 18, -16, 9, -21, -3, -13, -2, 8 },
-  { 25, 7, -9, 23, 20, 18, 6, 16, -9, 8, 8, -5, 11, 13, -8, 7,
-    4, 10, -2, -1, -7, -9, -7, -9, -4, 1, 1, -5, -10, 8, 4, -5 },
-  { 9, 2, 16, 14, -5, 14, 1, 0, -21, 17, -1, 9, 12, -3, -3, 4,
-    -4, 14, 10, 3, 0, -10, 7, 4, 4, -11, 2, 4, -1, -3, 9, -1 },
-  { 17, 8, 11, 26, 15, -3, 14, -1, 12, 9, 10, -8, 8, -18, -11, -3,
-    -14, -7, 7, -3, -3, -4, 1, -7, -3, 2, -3, 16, 10, 0, 9, 6 },
-  { 9, 8, 3, 8, 18, 14, 11, 1, 10, 6, 1, -4, -16, -2, 14, -2,
-    1, 8, 12, 14, 3, -3, 8, 8, 12, -15, 3, -3, 3, -2, 14, 10 },
-  { 22, -3, -11, 13, -7, 11, 4, 11, 3, 14, 0, -6, -2, -9, 4, 2,
-    -2, 0, -5, -27, -10, 3, -1, 5, 8, -24, -3, -11, -3, 2, 11, -1 },
-  { 19, 2, 8, 36, 5, -6, 3, 15, -3, -4, -5, 14, -10, 1, -12, -10,
-    -3, -4, 3, -2, 1, -8, 4, 3, 5, -3, 0, 4, 8, -2, 8, 4 },
-  { 8, 14, 15, 9, -4, 10, 5, 11, 9, 10, 8, 9, -15, 15, 6, -8,
-    -10, -13, 5, -8, -20, -13, -6, -11, -1, -3, -6, -4, -1, 0, 13, 15 },
-  { -2, -1, 9, 12, 2, 2, 13, 3, -23, 33, 15, 2, -4, -1, 3, 8,
-    8, 6, 6, -7, 8, 6, 9, -1, 3, -8, 0, -4, 1, -8, 11, -1 },
-  { 6, 5, -6, 16, 2, -3, 31, 21, -9, 12, 0, -1, -4, 1, -12, 3,
-    -13, -18, 2, -11, -9, 2, -8, -6, 11, -3, -1, 0, -1, 0, 13, 5 },
-  { 5, -1, 2, 0, 25, 5, 10, 16, -5, 21, 14, 12, 13, 2, -5, 5,
-    5, -3, -2, -14, 0, -12, 7, 11, -1, -7, 19, -1, -1, -1, 8, -1 },
-  { 10, 7, 3, 11, 0, 8, 22, 3, 3, 19, -4, 12, 15, 9, 5, 15,
-    2, 1, 2, -10, -10, 0, 2, -1, 0, 1, -12, -1, 21, 16, 9, -7 },
-  { 11, -4, -5, 24, -7, 11, 20, 11, -15, 18, 5, -13, -15, 0, -5, 9,
-    1, 0, -1, -9, 4, -8, 6, -8, 1, -2, -7, 20, 9, 3, 9, 3 },
-  { 20, 0, -12, -6, 9, 31, 9, 12, 8, 27, 15, 7, -16, 5, -3, -7,
-    -1, -9, -2, -7, -3, 4, -8, -3, 3, -6, -2, -2, -3, -6, -1, 2 },
-  { 6, -6, 48, 8, -3, 19, 12, 11, -7, 2, 3, 0, -1, 1, 8, -4,
-    4, -6, 0, -4, -4, -3, 3, 6, 3, -13, -8, 5, -3, -7, 8, 5 },
-  { 7, -2, 6, 11, 12, 2, 14, 4, -5, 12, 2, 9, 4, 2, 0, -1,
-    2, 0, -15, -9, -16, -2, 8, -17, -5, -22, -19, -5, -1, -10, 1, -2 },
-  { 11, -9, 3, 12, 6, 6, 1, 17, -6, 19, 14, 7, -7, -1, -1, -9,
-    9, -11, -17, 0, -6, 16, 0, 1, 9, -24, 3, 3, -9, -3, 3, -2 },
-  { 9, 0, 1, 8, 1, 7, 2, -5, -3, 8, -1, 7, 2, 6, -3, -6,
-    5, -2, 6, -2, -4, -3, 0, -3, 13, -50, 1, -2, 2, 4, 4, 3 },
-  { 7, 0, 26, 21, -4, 2, 17, 8, 7, 11, -7, 1, -1, -15, -1, -15,
-    -11, -4, -17, -4, 1, -7, 3, 6, 3, -9, 2, 3, 6, 10, 6, 12 },
-  { 1, -2, 2, -1, -10, -4, 6, -3, -5, -2, -8, 2, 2, 2, 8, 0,
-    1, 1, 6, 0, 11, 13, 3, 4, 0, -12, 11, -5, 19, 20, 2, 5 },
-  { 5, 3, -13, -2, 1, -12, 11, -7, -12, 7, 10, 0, 7, 0, -2, 4,
-    -6, -9, -11, -12, -23, 12, 10, -3, 0, 6, 19, -1, 24, 18, 9, 12 },
-  { 6, -3, 2, 5, 2, 2, -2, -5, -8, -11, -4, 3, -8, -4, 5, -3,
-    -16, -4, 3, -12, -4, 3, 32, 7, 2, 8, 32, -18, -1, 12, 1, 7 },
-  { 0, -8, -1, 0, -8, 7, -8, -1, -1, 4, -12, -1, 3, 0, 1, -18,
-    8, 8, -14, -10, -11, 19, 9, 5, -7, 6, 8, -4, 26, 12, -1, 6 },
-  { 3, 5, -14, 7, 14, 8, 20, -13, -16, -10, -2, 17, -7, 4, -8, -9,
-    14, -5, 3, -4, -12, 7, 14, -10, -19, -20, 35, 8, 13, 14, -2, 9 },
-  { -2, -4, -1, 1, -3, 0, -1, 1, 2, 2, 6, 0, 0, 4, 5, -2,
-    3, 3, 3, -2, -7, -3, -3, -1, 6, -2, 29, 22, 13, 34, 0, 14 },
-  { -3, -9, 3, 1, 5, -4, 2, 0, 7, -9, 0, 2, -5, -3, 0, 6,
-    -1, -1, -1, 2, 2, 4, 8, 7, 20, -6, 7, 16, 33, 20, 6, -1 },
-  { -11, 1, -3, -3, -11, 3, -9, -25, -1, -16, 4, -8, 15, 1, -2, 7,
-    8, 23, 2, 18, -13, 16, 3, -7, 6, 3, 16, -8, 12, 16, 3, 4 },
-  { 0, 5, 5, -5, 1, -1, 2, -3, -2, 1, -13, 2, 2, 10, 6, 7,
-    18, 18, 7, 9, 8, 9, 21, 14, 7, 12, 15, 14, 15, 12, 11, 5 },
-  { 1, -5, 11, -2, 17, 8, 3, 0, -1, 6, 11, -7, 6, 6, 7, 5,
-    -15, 14, 1, 11, 4, 10, 12, 1, 2, 4, 30, 1, 11, 1, 6, 13 },
-  { 2, 4, 3, -7, 5, 8, -11, 7, -5, 9, -10, 6, 8, -10, -3, 10,
-    1, -29, -4, -26, 5, -8, 13, 4, 3, 6, 35, 1, 3, 6, 3, 0 },
-  { -2, 1, 0, 0, -1, -3, -7, -3, -9, -3, -1, -6, 3, 4, 4, 0,
-    5, -1, -2, -2, -1, -4, -10, 8, 0, -6, 10, -4, 46, 12, 2, 28 },
-  { 4, -1, 4, 1, 0, 4, -2, -2, -2, -1, 2, -4, 1, 5, 0, -3,
-    1, 1, -2, 0, 1, -2, -1, -1, 3, -6, 35, -11, 13, 53, -3, -1 },
-  { -5, -2, 0, -13, -16, 5, -12, -11, 1, -30, 3, -18, -24, -8, -5, -19,
-    1, -3, -8, 7, -7, -8, 15, -19, 4, 10, 30, 24, 6, 1, -9, 10 },
-  { -4, 8, -7, -4, -6, 12, -1, -9, -4, 2, -9, 3, 2, -2, 4, 2,
-    22, 9, 4, -5, 0, 5, -2, -9, -3, 1, 18, -12, 18, 16, 4, 16 },
-  { -5, -8, -3, -5, -3, 6, -7, -3, -2, -5, -3, 1, 2, 2, 4, -6,
-    10, 3, 12, -3, 20, 0, 27, -4, 16, 5, 18, -3, 23, 4, 12, 11 },
-  { 0, 1, 0, 1, -2, 1, 2, 1, -1, 0, -2, 2, -2, -4, 1, -2,
-    -2, -1, -5, -2, 0, 0, -2, 2, 9, 7, 63, 5, 12, -1, 1, 0 },
-  { 4, -3, -7, -5, -11, -5, -12, -10, -10, -12, -15, -12, -14, -14, 1, 1,
-    10, -10, 16, 6, 2, 9, 11, 9, 9, 8, 12, -1, 13, 12, 6, 3 },
-  { 7, -3, -2, 4, 6, -8, 2, -3, -12, -5, -9, -8, -10, 15, -2, -4,
-    8, 9, 7, -13, -18, 34, -5, 7, 12, 22, 16, -11, 13, 25, -15, -11 },
-  { -3, -2, 0, -4, 1, 0, -3, -13, -7, 13, 12, -7, -10, 13, 19, 6,
-    16, 15, -12, -15, -3, 34, 1, 5, 1, -9, 11, 21, 8, 17, -5, -6 },
-  { 3, -5, 0, -4, 0, 4, -11, 4, -7, -3, -1, -8, 3, -2, 2, 1,
-    11, 5, 6, 14, -3, 2, -4, -7, 0, 31, 15, -2, 24, 11, 5, 4 },
-  { -1, -4, -9, 5, -8, -18, -4, -9, -20, -18, 7, -14, -16, 3, 8, -3,
-    29, 11, -13, -13, 7, 1, 17, 6, 6, 21, 11, 1, 14, -8, 2, 5 },
-  { -3, 8, -10, -6, 12, 2, 1, 3, 3, 3, 3, -6, -8, -14, 15, -5,
-    16, 4, 16, 0, 7, -1, 0, 16, 2, 1, 22, 4, 19, 13, -11, 1 },
-  { 2, -3, 10, 20, -4, -1, -8, 5, -8, -9, -6, -2, -4, -7, 8, -10,
-    0, 8, -6, 1, -8, 14, 13, 5, 17, -6, 26, -1, 7, -1, 0, 12 },
-  { -4, -7, -31, -2, -7, -1, 5, -5, -5, -12, 4, -7, -6, 3, 15, -2,
-    5, -2, 7, -1, 10, 7, 8, -1, 14, 20, 14, 9, 16, 16, 8, 24 },
-  { -7, 0, -3, -6, 1, 3, -13, -6, -4, -4, -5, -9, -1, -10, -4, -8,
-    2, 0, -1, 1, 24, 24, 21, 31, 5, 2, 11, 12, 7, 4, 3, 6 },
-  { -3, -5, 6, -4, -3, -1, 2, -1, -2, 1, 0, -8, -1, 2, 0, -4,
-    6, 22, -1, -5, 8, 12, -1, -2, 28, 27, 20, -27, 14, 1, 2, -3 },
-  { 1, -5, -2, -2, 6, -2, 9, 1, -2, -5, 3, 4, 11, 5, 2, 8,
-    -3, -1, 1, -2, -3, -5, 5, 8, 49, 12, 8, -3, 9, 20, 12, 17 },
-  { -6, 0, 1, 7, 0, 9, -2, -4, 8, 0, -2, -10, 0, 7, 21, -1,
-    0, 1, 17, -7, -5, 2, 4, 16, -2, 17, 14, -20, 15, 14, 4, 15 },
-  { 0, 3, -4, 9, -4, 0, 6, 4, -6, -6, -5, -7, 2, -9, -10, -2,
-    -5, 0, -3, -21, 9, 14, -11, 13, 29, 2, 25, 4, 22, -1, 2, -3 },
-  { 2, 12, -11, 2, 16, 9, -4, 7, 1, -10, -15, 11, -4, 3, -2, 4,
-    4, -5, -10, 1, 4, 19, -15, 6, -4, -2, 30, -7, 11, 21, -12, 5 },
-  { -2, -3, -2, 4, -1, -5, -3, -7, -5, 1, 0, -6, 1, -6, 7, 0,
-    8, -7, -3, -2, 2, 14, 2, -3, -26, -1, 26, 22, 32, 1, -2, 6 },
-  { 1, -38, -1, -20, -2, -3, -6, -4, 2, 2, 7, 0, 3, 5, 3, 10,
-    6, 1, -3, -5, 7, 5, -5, -4, 8, 3, 1, -14, -1, -9, -5, -4 },
-  { -5, -26, -7, -19, -10, -5, -11, 5, -11, -25, -8, -14, -9, -16, -8, -6,
-    -17, -14, -1, -1, 6, 2, 2, 2, 3, 0, 2, 8, -8, 3, 0, -3 },
-  { 17, -49, -3, -23, -1, 11, 7, 3, 4, -4, 0, 0, -1, 4, 2, 4,
-    -2, -4, 2, -2, -1, -2, 2, 0, 0, -1, 0, 0, 1, 2, 0, 0 },
-  { 4, -34, -6, -9, 1, 21, -7, 3, -2, -1, -3, 18, 2, -16, 7, -3,
-    8, 7, -5, 7, 2, 4, 8, -6, -7, -2, -5, -1, 4, 1, 2, -4 },
-  { 5, -29, 13, -2, -14, 3, 1, 18, -15, 4, -8, 8, -10, 8, 2, 1,
-    -8, 15, 3, -10, -4, -4, -2, 0, -3, -4, 2, -3, -4, -3, 12, -6 },
-  { 13, -20, 3, -18, -17, 4, -14, 13, 28, 11, -8, -6, 16, 6, 0, 10,
-    3, 4, -9, 13, 5, -7, 12, -5, 0, -7, 5, 1, 3, 3, 2, 1 },
-  { 3, -27, -5, -11, -21, -11, -12, 0, -5, 7, -22, 1, 3, 5, 0, -5,
-    8, 7, 1, -5, -7, 2, -5, 4, 1, 3, -8, -2, 0, 4, -2, 6 },
-  { 31, -45, 0, -1, -12, 1, 2, -6, 4, 3, -1, 3, 3, 0, 5, 3,
-    -5, 12, 4, 6, 2, 1, -2, 1, 3, 2, 5, 2, 2, 2, 3, -1 },
-  { 9, -45, 6, 5, -1, -17, -2, 18, -3, 2, 0, 1, 0, -1, 10, 8,
-    -7, -2, -5, -8, 6, -1, 0, 4, 6, -3, 12, -1, -2, 0, 5, -7 },
-  { 3, -26, -2, -12, -12, 2, -10, 16, -3, 12, 4, 5, 11, 8, -16, -17,
-    -2, -3, -3, 2, 5, -9, 13, 1, 10, 11, 3, 5, -2, 2, 2, -7 },
-  { 8, -26, 32, -7, -5, 22, 2, 14, -10, -8, -7, 3, 3, 7, 0, -5,
-    0, -1, -3, 0, 8, 4, -5, -7, 6, -1, 4, 8, 1, 1, 7, -6 },
-  { 4, -31, 2, -14, 2, 0, 1, 8, -6, -1, 17, -3, 13, -6, 5, -10,
-    -2, -10, -2, -10, -3, 7, 1, 5, -8, 8, -14, -3, -15, 7, -10, -6 },
-  { 16, -27, 13, -4, -23, 7, -9, 6, -7, 5, 4, 2, -1, -3, 23, -18,
-    7, 0, -3, 4, -3, 9, -6, -2, -1, 8, -6, 2, 6, -3, 2, -2 },
-  { -1, -35, -2, -8, 11, -1, -7, -3, -2, 11, 7, 6, -6, -10, 9, 6,
-    -3, -5, -6, -3, 9, 16, -16, -9, -20, 12, 3, 5, -3, 1, -9, 4 },
-  { 2, -24, 1, -12, -16, 5, -4, 3, -4, -1, -11, -11, -8, -14, 14, 10,
-    -8, 20, 8, -3, -11, 1, 1, -4, -4, -7, -3, 15, 2, -6, -2, 7 },
-  { 9, -21, 2, -19, -7, -5, -8, 25, 3, 17, 5, -3, 9, -12, 8, 2,
-    -4, 3, 3, 1, 11, -9, -4, -3, 4, 3, -22, 6, 4, 6, 11, -5 },
-  { 16, -23, 13, -17, -21, -12, 5, 9, -20, 7, 6, -6, 0, 2, -9, 6,
-    -6, -13, -7, -1, 5, -3, 5, -7, -10, 1, 0, 8, -9, 11, 0, -8 },
-  { 10, -26, -9, -7, -19, -4, 6, 16, -7, 5, -4, 4, 8, 0, 4, -1,
-    6, -7, 1, -8, -11, 10, -14, 0, -16, 6, -3, 5, -1, 14, 12, 1 },
-  { 8, -27, 12, -14, -1, -1, -19, 10, -11, 21, -14, 9, -8, -3, 8, -1,
-    12, -13, 3, -4, -2, 0, -9, 0, -7, 2, -3, 12, 1, -3, 3, 1 },
-  { 18, -20, -14, -14, -16, -3, -24, 6, -17, 2, -3, -11, 2, -3, 12, 10,
-    10, 1, 10, 7, 8, 5, 5, 4, -1, 7, 2, 2, 0, 4, 7, 0 },
-  { 0, -30, 9, -16, -18, 15, 12, -3, 4, -4, -5, -11, -4, -12, -10, 0,
-    2, -2, -4, -1, 2, 0, -1, -6, 2, -3, 4, -5, 7, 3, 5, 7 },
-  { 25, -24, -1, -6, -9, 6, -13, -2, 3, 15, -3, 11, 4, -8, -11, 2,
-    0, -9, -2, 7, 4, 8, 5, -8, 5, 6, -1, -11, -15, -5, 0, 11 },
-  { 0, -34, -7, -11, -7, 9, -3, 19, 4, -8, 3, -11, 11, -3, -9, 12,
-    9, 9, 2, 1, -7, 1, -3, 0, -6, -2, -1, 3, 0, -7, -2, -5 },
-  { 6, -34, -4, -5, -3, -9, 2, 9, -1, 9, -5, -3, -26, -12, 8, -6,
-    -7, 11, -8, 4, 4, 1, -1, 0, 8, 9, -4, 7, -1, 1, -3, -1 },
-  { 3, -30, 5, 6, -10, 3, -7, 6, 3, 3, -26, -19, -3, 1, 7, 5,
-    -4, -5, 6, 10, 13, -10, 4, -7, -4, 5, -3, 9, -6, 3, 9, 5 },
-  { 4, -24, 9, -19, 2, -4, -5, 8, -3, 2, 0, -15, -1, 9, -4, 22,
-    6, 9, 3, 7, 11, -9, 0, -3, 4, 5, -5, 10, -8, 5, -7, -3 },
-  { 8, -27, 7, -3, -1, 2, -9, 13, 7, 12, -4, -6, -6, 5, 0, 7,
-    5, 1, 15, -3, -4, 0, -5, -2, 7, -5, -7, 1, -2, 13, -8, 13 },
-  { 17, -22, -15, -11, -8, 16, -14, 18, 2, -1, 14, -7, 14, -6, -6, -7,
-    -8, 17, 6, 4, 4, -7, -5, -9, -14, -6, -1, 9, -3, 1, 6, -5 },
-  { 25, -30, 2, -12, -13, 18, -18, 16, 8, -3, 10, -8, -3, -1, -6, 3,
-    -5, -7, 4, 6, 7, 1, 1, -11, -5, 6, 2, -4, 9, -1, -5, -2 },
-  { 7, -23, 7, -15, -1, -3, -1, 0, -10, 12, 2, 5, -4, 0, 4, 6,
-    -1, 5, -9, -1, -1, -7, 1, 17, 9, -17, -16, 8, 4, -14, 11, 14 },
-  { 0, -31, 7, -13, 3, -11, -7, 6, 1, -11, 8, -7, 15, -3, 16, -11,
-    -1, -15, 16, -3, 5, 0, -2, -2, -6, 11, 5, 6, 5, -5, 6, 3 },
-  { 13, -24, -2, -20, -10, 7, -3, -1, 15, 2, 6, -5, -7, -10, -20, 1,
-    -4, 14, 8, -2, 3, -13, -3, 1, -4, 1, -3, 2, 8, -7, 16, -4 },
-  { 1, -2, -2, -3, -4, -7, 0, 3, 6, 7, 3, 2, 1, -2, -1, 0,
-    -6, 4, 2, -4, -3, -4, 5, 9, 5, 0, -3, -3, -4, -7, -31, -50 },
-  { -1, -3, 7, 2, -1, 2, 4, 6, 0, 10, -2, 0, -20, -6, -3, 9,
-    -20, -22, -1, -1, 15, 9, -12, 10, -13, -20, 12, 3, 5, 6, -7, -26 },
-  { 0, 4, -2, -14, -12, 6, -13, 11, -10, 3, 22, 6, 16, -2, -5, 1,
-    -3, -11, 0, -7, 5, -5, 0, 1, -1, -6, 8, 8, 10, 9, -5, -27 },
-  { -5, 10, -2, 7, 9, -9, 5, -9, 5, 4, -15, 14, 1, 3, -10, 5,
-    0, -2, 7, 3, -13, 6, 9, -6, 5, -14, -17, -1, 11, 14, -2, -26 },
-  { 0, 6, -3, 0, -8, 6, 0, 1, 4, -8, 2, -5, 4, 7, 15, 11,
-    9, 19, -2, 14, -8, 7, -1, 3, -3, -3, -10, -2, 12, -2, -12, -29 },
-  { -12, -5, 0, -3, -2, 6, 3, -3, 2, -2, 1, 11, 2, -7, 5, 1,
-    2, -2, -14, 0, -1, -5, 3, 8, -28, -26, 6, -6, 3, 8, -10, -27 },
-  { -1, -3, 6, 2, 4, 15, 1, 0, 2, -2, -2, 13, 3, 6, 0, 6,
-    -1, -4, -1, -5, 8, -1, 5, -5, -15, 11, -8, -5, 14, -6, -14, -29 },
-  { -5, -6, 0, 1, 0, 6, -3, 2, -5, -1, 5, -3, 2, -10, 3, 4,
-    3, 0, 13, -3, -1, 4, -4, -6, 2, 9, 8, 2, -3, 28, -11, -31 },
-  { 1, -4, -10, -9, -4, -3, -15, -6, 1, 5, -3, -6, 5, -6, -22, 27,
-    -13, 5, 3, -7, -4, 20, -7, -12, -1, -24, -4, -13, -8, -11, -15, -21 },
-  { -6, -4, 19, -6, 2, 11, -6, 1, -3, -10, 9, -9, 12, -10, 2, 1,
-    -9, 1, 15, 7, -5, 5, -29, -35, 4, -30, 9, 9, 19, 17, 2, -17 },
-  { -3, 3, -3, 1, 2, 5, -1, 5, -2, -3, 1, -3, -8, 3, -4, -2,
-    -4, -1, 12, 0, 2, -8, -6, -4, 16, -1, -14, -2, 25, -6, -15, -36 },
-  { 0, -1, 3, -4, -4, -1, 7, -4, 8, 0, 10, 9, -4, 1, 10, -1,
-    -3, -13, -5, -4, -1, -4, 8, 11, 14, -7, -5, 16, 12, 13, -1, -28 },
-  { 1, -2, 2, -3, -8, 10, 4, 9, 12, 3, 5, 0, 8, -3, -6, 2,
-    16, -11, 11, 0, 1, 6, 1, 18, -10, -16, -1, -4, 5, -14, -15, -20 },
-  { 1, -12, 5, 4, -7, 8, -1, -17, -2, -9, -14, -11, 6, -9, 5, -4,
-    3, -2, 7, 18, -5, 5, 6, -1, -11, -2, -10, -3, 8, -3, -2, -32 },
-  { -12, 5, 20, -5, -6, -11, -6, -6, -13, 4, -6, 19, -8, 2, 3, -9,
-    -4, -4, -1, 9, -1, 21, -1, 7, 15, -10, -1, -3, 9, -3, 2, -24 },
-  { 0, -3, 2, -6, 4, -1, -9, -2, -1, -3, 6, -1, -5, -6, -5, -8,
-    0, -2, -6, 9, -4, 3, 2, -13, 1, -7, 23, -13, 4, -3, -15, -33 },
-  { -7, 2, -15, 11, -10, 14, 0, -11, 3, -1, 12, -4, -4, 9, 11, -13,
-    -13, -3, -14, 1, 3, 6, -5, 8, 0, 5, 5, -10, 4, 5, -6, -30 },
-  { -6, 4, 0, -5, 4, 1, -1, -1, 3, 6, 5, -2, -5, 0, -2, 5,
-    -4, -2, -4, -2, 4, 7, -7, -1, 1, -4, -3, -19, 37, 12, 10, -40 },
-  { -7, 2, -7, -12, 17, 11, -7, 2, 2, 3, 1, -1, 3, 4, -2, -5,
-    9, -9, 6, 4, 9, 12, 11, -5, 2, -1, 0, 9, 5, -7, -2, -24 },
-  { -7, 6, 1, 3, 1, 0, 6, 0, 4, -12, -2, -2, 1, -9, 10, -2,
-    11, -1, 21, -12, 15, -5, 10, -5, 5, -5, 14, -6, 5, -7, -3, -29 },
-  { -2, 0, -5, -2, -3, 1, -3, 0, 4, 2, 3, 0, 2, -2, 7, -2,
-    3, -5, 2, -1, 6, -4, 0, -3, 8, -11, 19, -8, 22, -34, 13, -35 },
-  { -1, -3, -1, 9, 11, -3, -3, -1, 7, 18, 11, -5, 2, -12, -11, 18,
-    9, -5, 1, -6, -9, 12, 1, -3, -3, -9, -14, 9, 9, 8, -6, -26 },
-  { 0, 5, -5, -1, -1, -2, 4, 6, 8, 2, -1, -2, 5, 1, -5, -4,
-    1, 1, 18, 1, 7, -10, 3, -2, 12, -1, -15, 9, 12, -14, 13, -38 },
-  { 3, 0, -8, -1, 0, 8, -9, -3, -8, 16, 3, 16, -5, -9, 0, -1,
-    -7, -1, -4, 13, 7, 0, 1, 2, -1, -16, 0, -2, 1, 8, -8, -28 },
-  { 7, 9, -5, -3, -2, 2, 0, 3, 11, -6, -4, -2, -2, -5, 28, -18,
-    -6, 2, 15, -10, -15, -10, -2, 0, -2, -2, 4, -3, 7, 11, 5, -30 },
-  { 9, 0, -7, -1, -4, -7, 2, 2, 9, -2, 2, 3, -8, -6, -6, 3,
-    -10, 4, 10, 5, 21, -4, 14, -18, 1, 3, -10, -2, 6, 14, -8, -26 },
-  { -14, -1, 2, 3, -3, 7, 1, -22, -1, -1, 0, 1, 12, -14, 3, -5,
-    0, 10, -3, 1, -5, 12, -3, 10, -8, -22, -11, -13, -7, -10, -13, -25 },
-  { -2, -5, -4, -4, -9, -18, 9, -3, -5, 17, 13, 5, 6, 11, 3, 8,
-    20, 4, 2, 9, 8, 5, 6, 1, 7, -7, -6, -2, -7, 0, -17, -23 },
-  { -5, -5, 2, 0, 6, 2, -2, 2, -3, 4, 4, 0, -5, -2, -4, 6,
-    8, 10, -1, 1, -5, 5, -14, -2, -11, 8, 6, 25, 7, -1, 0, -43 },
-  { -4, 0, 4, -2, 7, 0, 3, 17, 5, 2, -5, 1, 21, 3, -2, -10,
-    -16, -9, 7, -12, 9, -8, 2, 5, -5, -10, -2, -11, -5, -1, -9, -30 },
-  { -2, 3, 1, -4, -1, 0, 8, 1, 12, 4, -1, -1, 3, -17, 13, 9,
-    0, 7, -6, -5, 9, 1, 5, 4, -10, -18, 0, 14, 11, -4, -16, -28 },
-  { -1, 0, 2, -1, 4, 1, -1, 1, -1, -2, -1, -2, 3, 0, 0, -1,
-    -1, 1, 2, -2, 3, 3, -2, 4, -2, -1, -6, 1, -1, -1, 6, -70 },
-  { 7, 3, -11, -1, 12, -4, -14, 4, 4, -4, 4, -2, 2, -12, -4, 15,
-    -17, -4, -3, 6, 8, -5, 22, -22, 5, -11, 15, -4, 4, -1, -21, -1 },
-  { 10, -2, -13, 11, 4, 14, 4, 9, 8, 8, 19, 15, 14, 15, 5, 10,
-    8, 15, -5, 4, 14, -8, 1, 1, 2, 1, -1, -3, 21, 8, -29, 13 },
-  { -6, 0, -6, 6, -1, 2, 8, -4, -5, 4, -4, -5, 0, -2, -4, 0,
-    9, -2, 1, -2, 26, -19, 21, -10, 4, 1, -8, 5, 22, -10, -13, 15 },
-  { 11, -5, 1, 0, 6, 3, 7, -2, -2, -3, -5, -1, -2, -6, 1, 1,
-    -8, -5, -13, 13, -2, -3, -1, -9, -28, 4, 2, -11, 18, -20, -24, 9 },
-  { 7, 4, -3, 6, 6, -6, -7, -5, -7, -4, -4, 0, -7, -5, -6, -5,
-    2, -13, -12, 2, 0, 5, 18, 15, -13, -7, 13, -20, 16, -10, -19, 6 },
-  { 5, -8, -1, 5, 10, 2, -1, -10, -11, 23, 8, -5, -8, 4, -5, -4,
-    -5, -5, -11, -8, 5, 1, 7, -9, -9, -6, 12, 14, 17, -12, -22, 3 },
-  { -5, -8, -3, 3, 12, -1, 0, -4, -5, 1, 1, 6, 1, 5, -5, 7,
-    -2, 7, 1, 6, 6, 2, 0, -5, 17, -4, -5, -24, 13, -20, -27, 14 },
-  { -1, 2, -3, 1, -3, 1, -3, 0, -2, 3, -2, 1, 2, -1, -2, -1,
-    -2, -5, 5, -2, 0, -7, 1, -6, 8, 8, 11, -5, 24, -43, -13, 2 },
-  { -2, 4, 7, -3, -4, 4, 13, -4, 0, 0, -2, 9, 0, -3, -6, 1,
-    -7, 1, -1, 10, 0, 5, -1, -24, 25, -15, 7, 2, 22, -10, -21, 0 },
-  { -5, 2, 6, -2, 13, 3, 5, -12, -11, 16, 6, 10, -5, 0, -3, 6,
-    5, -5, -5, 10, 12, 10, 11, -7, 8, -14, 2, -15, 13, -14, -8, -3 },
-  { 5, 6, -7, -5, 5, 2, 9, 5, 0, -1, -4, 2, 8, 0, 3, 5,
-    -12, 3, -3, -6, 2, -1, -5, 14, 11, -20, -21, -25, 24, -1, -10, 6 },
-  { -5, 5, -2, 9, 4, -4, -1, -6, 11, -6, 5, 0, 2, -3, 6, -1,
-    -17, -18, -4, -13, 9, -1, 9, -7, -4, -8, 2, -3, 12, -31, -18, 5 },
-  { -7, -11, 6, -8, 4, -3, -12, 0, -1, -6, -3, 0, 5, 9, 7, 2,
-    1, -8, -6, 8, 2, -5, 7, -1, 16, -10, 16, -12, 18, -1, -25, -12 },
-  { 3, -12, 1, 2, -2, -18, -8, -15, -10, -9, 2, -7, 11, -11, 2, -1,
-    -1, -1, -9, -6, 3, -14, -2, -1, 2, -13, -7, -9, 19, -5, -17, 2 },
-  { 7, 1, -8, 7, 17, -13, -10, 5, 7, 1, -6, 4, 9, -4, 0, 3,
-    8, 1, -14, -9, 4, 7, -9, 0, 6, -5, -12, -2, 25, -2, -19, 1 },
-  { 7, -3, 6, -3, 1, 6, -7, 0, 10, 0, 4, -5, -17, -4, 4, -1,
-    0, -3, -7, 19, 24, -1, 21, 8, 10, 9, 8, -1, 23, -2, -18, -2 },
-  { 3, -3, 0, 5, 8, -2, -9, 2, 9, 6, 19, 8, 2, 6, -9, -2,
-    -4, -3, -8, 7, -7, -8, 5, 4, 26, -6, 7, 18, 24, 0, -13, 4 },
-  { 0, -13, -11, -1, 3, -9, 5, 4, -7, 3, 0, 2, -1, 4, -5, 2,
-    9, -2, -11, 15, 1, -21, 1, -1, 0, 4, -14, -4, 24, -16, -13, 1 },
-  { 1, -9, -8, 0, 0, -4, 11, -1, 14, 16, 0, 17, -2, -9, -12, 0,
-    -1, -14, -9, -14, 0, -2, 19, 4, 6, 4, 4, -11, 8, -17, -19, -5 },
-  { -3, 1, 2, 12, -4, -18, -1, -4, -7, 14, -3, 2, 0, -7, -8, 12,
-    -5, -9, 14, 12, -9, -2, 4, -6, 4, 18, -1, -25, 22, 2, -23, -5 },
-  { -2, 0, 0, 0, 1, 3, 5, -1, 5, -2, -2, 2, -3, 0, 1, 2,
-    0, -1, 2, -1, -9, -6, -7, -4, -2, 4, -7, -5, 64, -3, -25, 4 },
-  { 12, -2, -3, 0, 8, -9, 13, -7, 6, -3, -12, 12, 15, -9, -4, 2,
-    9, -4, -12, 3, 14, 1, 7, -15, 15, 0, -6, -12, 0, -3, -20, 6 },
-  { 2, -1, -4, 5, 9, 6, -7, 2, -2, -7, -2, 0, -1, -18, -4, -6,
-    -15, -5, 11, 5, -10, -1, 2, 7, 12, -19, -7, 8, 21, -4, -15, 4 },
-  { 4, 2, 5, 5, -5, 1, 3, 2, -8, 13, 0, -5, -2, -14, -11, 6,
-    2, 17, 8, -13, 26, -2, 5, -15, -4, -14, 12, -9, 13, -21, -23, -4 },
-  { 2, -3, -2, -3, 3, -2, 6, 9, -9, 13, 4, 2, 12, -3, -3, 1,
-    -17, -22, -3, 4, 3, -2, 1, -9, 1, -6, 11, -13, 14, 0, -15, 6 },
-  { -16, -4, 17, -2, -20, -11, 11, 10, 5, -8, 16, 2, -17, -14, 11, 11,
-    -6, -11, -7, 12, 12, -10, -6, 5, 8, -4, -2, -5, 28, 3, -13, 4 },
-  { 0, -3, 3, -7, 6, 8, -12, 20, -19, 18, -11, 10, -5, 0, -9, 11,
-    3, 0, -2, 9, -7, -5, 18, 3, -2, -16, 1, 6, 12, -7, -16, 1 },
-  { 4, 1, 5, -5, 15, 2, -8, 3, 5, -11, 15, -3, 8, -8, -1, 7,
-    4, 7, -2, 6, -9, 5, 12, 2, 33, -2, -6, -18, 4, 0, -18, 11 },
-  { 3, -1, 1, -1, 0, 1, 4, -1, -5, 0, 1, 0, 4, 2, -1, 4,
-    -3, 2, 0, -2, 4, 6, -1, 6, 42, 19, -4, -37, 19, 1, -15, -4 },
-  { 2, 0, -5, 0, 10, 0, 0, -5, 3, 0, 0, -3, -3, 0, 2, -4,
-    -10, 2, -6, 4, 4, 1, 27, -7, 17, -34, 5, -9, 15, -16, -7, -5 },
-  { -2, 7, 7, -2, 9, -2, -15, 11, 11, 7, 5, 1, 15, 1, -9, 31,
-    2, -15, 2, 4, 3, 4, -1, -8, 2, -7, 6, -17, 11, -14, -11, 2 },
-  { 1, 1, -11, 9, 9, -6, -14, -11, -10, 8, -3, 11, 16, -9, -8, -13,
-    -8, 9, 0, 6, 6, -2, 13, -8, -2, 3, 13, -3, 10, -6, -17, 4 },
-  { 14, 5, 4, -6, -12, 10, -7, 8, 21, -8, -30, 15, -2, 1, 11, -9,
-    -5, 1, 0, -1, -1, -6, -2, 3, -5, 7, 9, 5, -5, 2, 0, 1 },
-  { -1, 2, 20, -17, -15, 3, 3, 7, 11, -17, -13, -6, -3, 18, 17, -15,
-    -4, -4, -5, 22, 14, -14, -2, -10, -7, 11, 8, -7, -3, 0, -7, 11 },
-  { 7, -11, -7, -8, -14, 22, 5, 2, 6, 13, -12, -2, 10, 3, 0, -21,
-    -4, 20, 3, 10, 21, -10, -12, 8, 11, 2, -5, 2, 1, 3, -1, 15 },
-  { -1, -2, -1, -2, -13, 8, -4, 0, 7, -2, -17, 8, 18, 5, 3, 8,
-    -8, -2, 3, -4, 14, -18, -13, 14, 15, -13, -1, -2, 4, 11, 1, 12 },
-  { 13, -6, -4, -16, -17, 16, 21, -2, 5, -11, -9, 19, 21, -17, -3, -17,
-    3, 12, 8, -12, -6, 1, -7, 9, 9, -7, -5, -1, -3, 5, -6, -4 },
-  { 11, 5, 12, -20, -6, 10, 4, 12, 8, -5, -10, 15, 13, 14, 10, -15,
-    -13, 1, 6, 14, 15, -17, -13, 4, -5, 10, 7, -6, -8, -3, -4, 12 },
-  { 25, -1, 7, -5, -7, 11, 1, 17, 13, -15, -14, -4, 5, 3, 8, -3,
-    -2, 2, 0, 6, 16, -12, -6, -4, 4, -3, 7, -10, -3, -7, -13, 7 },
-  { -8, 10, -3, -13, 5, 2, 4, 9, 9, -17, -13, 2, 11, 1, 6, -4,
-    8, -10, 4, 1, 19, -15, -4, 12, 31, 7, -5, -17, -4, 9, -2, 7 },
-  { 14, -6, -6, -6, -14, 13, 17, -5, 4, -14, -9, 7, 7, -9, 3, -16,
-    -15, 11, 11, 6, 4, -11, -19, 3, 5, 8, 13, -14, -14, 3, -4, 12 },
-  { -2, -4, 10, -4, -7, -1, 27, 5, 2, -16, -18, 4, 12, -2, -3, -2,
-    -1, 1, -8, -12, 3, -4, 8, 15, 2, 4, 9, -13, -14, 9, -7, 5 },
-  { 4, 2, -10, -5, -7, 2, 1, 4, -1, -6, -15, 6, 1, 10, 5, -10,
-    -9, -1, 13, -3, 5, -21, -11, 8, 8, 5, 27, -21, -18, -5, -1, 15 },
-  { 11, 1, -16, -8, -11, 0, 5, -8, -12, -13, -17, 22, 4, -6, -1, -18,
-    -10, 0, 19, 2, -2, -8, -7, -3, 2, -2, -9, -17, -5, 4, 4, 10 },
-  { 8, -6, -19, -5, -4, 12, 14, 15, 10, -9, -1, -9, 19, 12, 0, -1,
-    2, 4, 7, 9, 16, -16, -14, 9, -4, 3, 1, 0, -2, 10, -1, -1 },
-  { 12, -8, 12, -9, 0, 25, 7, 9, 2, -31, -9, -4, 15, 4, -5, 1,
-    -10, 11, 8, 10, 0, -6, 5, 11, -1, -6, 4, -10, -9, 6, 4, 5 },
-  { 14, 6, -17, -2, 17, 12, -9, 2, 0, -25, -14, 5, 20, 14, 8, -20,
-    5, 2, -2, -3, 9, -13, -3, -1, -6, 3, 7, -6, 0, 2, 3, 1 },
-  { 8, 4, -15, -3, 10, 18, -4, 13, 8, -22, -10, 9, 19, -15, 7, -5,
-    -13, 12, -4, 9, 2, -9, -6, 0, 2, 1, -9, -6, 6, 1, -1, 11 },
-  { 4, 1, 4, -5, -10, 18, 7, 2, -4, -9, -11, 0, 32, -7, 4, -16,
-    -1, 0, 6, 3, 6, -3, -14, 16, 9, -2, 7, -1, 0, -5, 5, -3 },
-  { -3, 2, 3, -8, -6, 4, 6, 2, 4, -12, -15, 2, 8, 8, 9, -3,
-    -18, 6, 34, 11, 12, -15, -1, 2, 9, 2, -4, -4, 2, 4, 2, -3 },
-  { 18, -6, -12, -8, -1, 15, 20, -4, -1, -11, -5, 6, 6, -11, -15, -7,
-    3, 7, 10, 2, 8, -10, -5, 8, 15, -5, 5, -17, -13, 13, 11, 7 },
-  { 8, -4, -6, -1, -14, -3, 6, -2, 1, -5, -1, 10, 10, -15, 5, 0,
-    -10, -4, -3, 7, -4, -19, -15, 27, 11, 18, 3, -19, -2, 6, 0, 12 },
-  { 12, 0, -5, 0, 4, -5, 1, 5, 10, -7, -11, 21, 29, 1, -2, 1,
-    -4, -11, -1, 13, 11, -20, -1, 4, 4, 4, -5, 6, -13, -2, 11, 9 },
-  { 2, -7, -7, -3, -10, -1, 20, 12, 1, -19, -19, -1, 5, 4, -7, -25,
-    14, 1, -3, 2, 12, -4, -3, -3, -2, 6, 1, 0, 3, 2, 5, -1 },
-  { 12, -8, 3, -12, -10, 10, 13, 0, 23, -14, -18, 10, 0, 15, 3, -12,
-    -3, -5, 5, -4, 2, -14, -10, 8, 2, 9, -1, -11, -3, 5, 13, 2 },
-  { 9, -6, 7, -7, -30, 17, 6, 13, 1, -14, 0, -1, 6, -9, 8, 3,
-    -4, 0, -1, -7, -5, -13, -19, -3, -4, 4, -6, -2, -13, 1, -2, 3 },
-  { 10, 1, 3, -18, -26, 17, 4, -16, 4, -3, -13, -4, -6, -11, -4, -21,
-    7, 8, 2, 5, 13, -6, 1, 5, 8, 7, 9, -6, -6, 1, -1, 2 },
-  { -3, -1, 0, -2, -2, 0, -1, 3, 4, -14, -8, -9, 13, 2, 50, -23,
-    -8, 8, 7, 11, 16, 3, -7, 0, -2, 6, 5, -1, 1, -2, 4, 3 },
-  { 1, 3, 1, 1, -6, 3, 6, 6, 2, -2, -3, 10, 2, -8, -5, -5,
-    5, 4, 4, -2, 10, -8, -40, -1, 21, 8, 3, -4, -1, 13, 4, 7 },
-  { 2, 0, -4, -8, 5, 2, 7, -5, 5, -8, -4, -1, 12, 2, 12, -13,
-    -9, 0, 1, -12, 9, -43, 1, -5, 12, 1, 3, 6, 1, -1, 3, -2 },
-  { 6, -2, -1, 1, 0, 4, 8, 14, 4, -7, -23, -5, 23, -17, -6, -15,
-    -8, 7, 10, -1, 7, -16, 4, -6, 2, 3, -3, -3, -1, 8, -1, 4 },
-  { 10, 4, -4, 1, 7, -3, 2, 11, 4, -6, -3, 8, 5, 4, 1, -45,
-    -6, -4, 4, 2, 1, -14, -10, 1, 1, 6, 2, -8, -1, -3, 3, 3 },
-  { 1, -1, 2, -3, -8, 9, 3, 3, -2, -5, -8, 8, 7, -7, -4, -6,
-    5, -9, 11, -2, 46, -5, -1, 9, -2, 0, 3, -5, -3, -5, 7, 0 },
-  { -4, 1, -2, -1, -11, 11, 8, -3, -2, -10, 0, 4, 9, 9, -17, -17,
-    -34, -4, -5, -7, -3, -12, -3, 11, 18, 3, -2, -5, -18, -5, -3, 6 },
-  { 7, -5, -3, 1, -4, -3, -5, -1, 2, 5, -2, 3, -10, 12, -18, -5,
-    -10, 12, -9, 4, -6, 2, 0, 16, -17, 15, 14, -12, -10, -2, -9, -1 },
-  { 4, -5, -3, -5, -3, -1, 7, 18, -7, 12, 3, 5, -8, -4, -20, 1,
-    -25, 1, -8, 13, -10, 8, -19, -1, -8, 10, 6, -9, -1, 0, 12, 4 },
-  { -4, 5, 0, -1, 2, 5, -8, -2, -6, 4, -8, 9, 3, 2, -7, 4,
-    -25, 13, -23, 10, 14, 15, -11, 3, -18, 4, 16, -4, 1, -10, -10, 3 },
-  { 5, -3, -1, -3, 4, 1, -3, -4, -5, 1, -12, 14, -7, 11, -15, 6,
-    -6, 24, -4, 13, -1, 15, -13, 8, 3, 7, -5, 2, 2, 0, 3, -7 },
-  { -3, 1, 0, 8, 6, -1, 6, 5, -5, -2, -12, 4, 0, -2, -3, 5,
-    -6, 0, -8, 9, -10, 4, -28, 12, -20, 11, -13, 7, -18, 1, -11, 1 },
-  { 1, -4, -15, 5, 0, -13, -5, 13, -11, 4, -4, -5, 5, -14, -16, 0,
-    -14, 5, -20, 12, 10, -7, -5, 6, 6, 22, 6, -4, -2, 3, 8, 11 },
-  { 13, -11, -2, 16, 16, -7, 0, 20, -7, -1, 0, 5, -9, 12, -2, -5,
-    -22, 5, -10, 12, -6, 11, 9, 21, -8, 15, 4, 0, -8, -4, -4, 10 },
-  { 18, -4, -13, 0, 1, -15, -1, -3, 2, 10, -1, 6, 1, -4, -20, -5,
-    -8, 6, -8, 17, -5, 5, -10, 8, -22, 6, -5, -2, 8, -17, 8, 2 },
-  { 1, -2, -9, 6, -31, -8, -8, 8, 0, 5, -9, -4, 2, 3, -12, 11,
-    -18, 10, -5, 3, -11, 13, -6, 11, -3, 12, -7, 3, -9, -1, 2, 11 },
-  { -9, -6, 21, -8, -15, 4, -11, 12, -11, 17, -1, 2, -6, 0, -15, 13,
-    -12, 19, 0, 2, -6, -3, -9, 10, 3, 17, -2, 5, -10, -3, 0, 1 },
-  { 4, -6, 5, -10, 1, -5, 1, 0, 0, 0, 2, 7, -2, 2, -2, 0,
-    -4, 3, -4, 1, -12, 6, -49, 16, -10, 13, 0, -2, 8, 6, 1, 8 },
-  { 5, -8, -7, 9, 13, -5, 7, 0, 10, 11, -4, -3, -1, 13, -14, 6,
-    -15, -6, -14, 16, 15, 1, -18, -4, -20, 20, -7, -1, -9, -2, -10, 10 },
-  { -12, 4, 0, 10, 0, 3, 8, 4, -27, -1, -2, 19, -4, 2, -13, 3,
-    1, 9, -12, 1, -22, 19, -5, 4, -9, 12, 2, -9, -8, 11, -3, 7 },
-  { 4, -5, 11, -6, 17, -17, 5, -4, -2, -6, 1, -5, 2, 4, -14, 6,
-    -20, 19, -20, 12, -21, 5, -14, 13, -2, 11, 4, -3, 0, -10, -4, -2 },
-  { -2, -1, -3, 8, -9, -7, -22, -3, -24, 13, -2, 10, -15, 5, -9, 4,
-    -7, 0, -5, 15, -8, 11, -13, 6, -4, 19, -8, 12, -4, 6, 9, 7 },
-  { 2, -3, 2, -1, 0, 3, 1, 2, 1, -4, -2, -3, 1, 5, -12, 6,
-    -16, 14, -23, 10, -14, 17, -15, 16, -2, 9, -25, 9, -10, 16, 4, 9 },
-  { -3, 7, -8, -3, 2, 2, -4, -8, -9, 10, 3, -11, 25, -10, -28, 27,
-    -9, 7, -13, 9, -2, 4, -12, -8, -14, 6, 7, -10, 3, 3, -3, 5 },
-  { -8, -3, 1, -10, 8, -3, -9, -4, 13, 7, 2, 4, -10, 4, 3, 7,
-    -18, 2, -22, 15, 4, 20, -7, 5, -6, 13, -1, 4, -7, -6, 6, 13 },
-  { -2, 3, 0, 2, -4, -2, 0, 0, 1, 2, -2, -5, 0, 1, -4, 0,
-    -2, -3, 1, 2, -1, 2, -8, -1, -24, 68, -3, 8, 3, 3, -1, -1 },
-  { -15, -2, -9, -7, -1, 8, -14, 8, 3, 6, 0, -1, -8, 8, -23, 2,
-    -14, 17, -15, 8, -4, 7, -18, 0, -8, -3, -1, -4, -10, 4, -1, 4 },
-  { 8, 0, 2, -7, 0, 5, 1, 3, -11, 4, -8, 14, 3, 20, 1, 26,
-    -11, 13, -13, 20, -2, 0, -8, 2, -6, 6, -1, 9, 3, -6, -3, 10 },
-  { 5, 0, -1, -7, 10, 1, -3, 5, 4, 7, -5, -1, -3, -1, 12, -3,
-    -15, 7, -9, 22, -19, 8, -9, 4, -23, 13, -14, 6, -6, -14, -4, 7 },
-  { 14, -5, -8, -10, 25, 3, -23, -7, -28, 0, -1, -9, 4, 1, -13, 20,
-    -8, 10, -16, 8, 12, -13, -21, 5, -13, 11, -2, 1, 12, -7, 2, -10 },
-  { -5, -4, 9, 5, -6, 35, -7, 8, 15, 2, -1, -9, -6, 2, -18, 7,
-    -15, 6, -3, 2, 8, 12, -30, 7, -4, 20, 2, 6, 13, -6, -4, 0 },
-  { 1, 8, -9, 9, -5, 12, -9, 16, -9, 16, -17, 14, -13, 15, -18, 14,
-    -15, 17, -12, 14, -13, 7, -16, 13, -9, 5, -11, 10, -9, 6, -12, 13 },
-  { -10, -4, 5, 3, 1, 6, 8, -14, -5, 15, 7, 4, 8, 7, -22, 8,
-    -7, -8, -15, 26, 1, 13, -3, 17, -5, 9, -2, 4, -6, 3, -8, 9 },
-  { 8, -3, 2, 3, 3, 1, -2, -1, -11, 8, -4, 0, -6, -5, -1, 13,
-    -37, 9, 1, -6, -10, -2, -10, 11, 8, 13, -3, -2, -6, 8, -4, 13 },
-  { 3, 2, -3, -4, -4, 7, -8, 9, -8, 9, -20, 12, -19, 15, -18, 17,
-    -15, 7, -1, 20, -11, 6, -6, 3, 1, 9, 2, -14, -2, -2, 2, 1 },
-  { -7, 1, -1, -3, -6, 4, 4, -3, 3, -1, 5, -4, 3, 2, -1, 9,
-    -59, 5, -4, 30, 3, 3, -2, -3, -1, 2, 2, 1, -1, -1, -2, 1 },
-  { 0, -3, 2, 0, -1, -8, 0, 2, -3, 4, -4, 1, 10, 6, -6, 8,
-    -7, 4, 10, 11, -41, 27, -20, 3, -3, 8, 1, 11, -5, -8, 0, 4 },
-  { 5, 1, 4, -2, 1, 2, -1, 6, -7, 2, 11, 4, 0, 0, -8, 7,
-    -10, 0, 0, 8, 2, 10, -1, 1, -2, 44, -2, -21, -12, -3, -1, 2 },
-  { -4, 4, -2, -2, 6, -8, 2, 1, -10, 14, 8, 6, 5, 1, -2, 4,
-    -13, 4, 2, 5, 10, -2, -21, 32, -3, 18, 9, -6, -9, -9, 10, 2 },
-  { 9, -16, -6, -2, 1, 4, 22, 2, -2, 1, -3, -2, -9, 3, 16, 19,
-    -24, -6, -6, -5, -8, -7, 8, -7, -1, -12, 5, -3, 0, 4, 2, -3 },
-  { 10, 3, -16, -4, -1, 13, 4, 4, 1, -3, 1, -6, -14, 18, 3, 8,
-    -8, -28, -16, 4, 4, 2, 12, 7, 9, -4, -4, 5, -1, -1, 2, 2 },
-  { -5, -13, -22, -3, -8, 21, -2, -9, 21, -4, -9, 5, -8, 15, 5, 1,
-    -5, -9, -7, -2, -5, -5, -1, -5, -5, -5, 3, 10, -4, 0, -7, -2 },
-  { 5, -10, -18, 2, 20, 4, 13, -10, 8, -15, -11, -3, -1, 16, 10, 9,
-    -8, 6, 7, -5, 6, 11, 5, 17, -4, 7, -11, 5, -3, -6, 2, 1 },
-  { 3, -5, -19, 1, 1, -3, -2, -25, -11, -17, 0, -13, -4, 10, 10, 2,
-    -5, 4, 0, 3, -3, -5, -10, -2, 13, -22, 0, 3, -11, -5, 7, -1 },
-  { 12, -14, -29, 6, -1, 10, 7, -17, -12, 14, 3, 9, -9, 9, 7, 6,
-    -3, -13, 0, 5, 3, -1, -6, -1, 0, 2, 4, -12, -5, -1, 2, 11 },
-  { 12, -15, -7, -2, -12, 17, 20, -16, -2, -12, -6, 15, -6, 12, 11, 9,
-    7, -6, 7, -4, -19, 6, 2, 2, 3, -11, -10, -4, -5, -3, 3, 2 },
-  { 11, -22, -6, 0, 8, 18, 3, -11, -4, -7, -15, -17, -12, 6, 16, 4,
-    -9, 4, -5, 3, 6, -16, 10, -7, -7, -3, 5, 0, 1, -15, -4, 5 },
-  { 12, -22, -16, 5, -6, 8, 12, -4, -9, -17, -11, 3, 5, 8, -17, 0,
-    11, -4, -13, -6, 2, -1, -1, 3, 3, -11, -12, -1, 1, 1, 12, -2 },
-  { 8, -10, -33, -5, -3, -6, 1, -7, -8, -4, -6, -1, 5, -4, -6, -12,
-    -16, -8, 11, 8, -14, 7, 12, 11, 4, -14, -3, 6, -7, -5, -3, 3 },
-  { 0, -8, -7, 2, -4, 24, 2, -9, -11, -3, -7, 11, -12, 17, 1, -1,
-    3, -5, -7, 12, 4, 11, 0, 3, 2, -18, -3, 4, 7, -6, 3, 15 },
-  { 10, -15, -16, -2, -4, -9, 7, -15, -6, 2, -16, 13, -8, 7, 19, -21,
-    -4, -12, -9, -3, -3, 6, 11, -3, -1, -19, 3, -7, -9, -4, 3, -6 },
-  { -5, -10, -21, 0, -3, -7, 18, -21, 15, -5, -12, -4, -13, 2, 6, -9,
-    -9, -11, -4, 13, -3, 6, 4, -1, 7, -9, -4, 9, 5, 2, 6, 3 },
-  { 15, -1, -27, -2, 10, 3, 7, -8, 9, -2, 7, 1, -2, -5, 18, 9,
-    -11, -17, -2, 7, -9, 11, 10, 0, -8, 6, -16, -3, 2, -7, 3, 11 },
-  { 4, -9, -39, 19, 6, -13, 13, -5, -5, -15, -2, 9, 0, 4, 14, 6,
-    -10, -4, -5, 2, -4, -2, 5, -11, 3, 3, -2, -2, -7, 9, 7, -10 },
-  { 5, -11, -8, 10, -2, 12, 16, 0, 12, -2, -6, 8, 14, 8, 7, 1,
-    18, -30, 4, 10, -4, -6, 2, -11, 9, -10, -8, 5, 0, 0, -7, 6 },
-  { -1, -16, -10, 11, 0, 13, 12, -4, -4, -5, -21, 12, 4, 13, 14, -7,
-    6, -16, -13, 8, 2, 9, 15, -12, 1, -9, -22, 10, -9, 9, 9, -7 },
-  { 4, -12, -27, 1, -2, 11, 15, 3, 14, -14, -9, 0, -9, 16, 22, 10,
-    16, -10, 5, -5, -9, 1, 1, 6, 6, -4, 2, -17, -5, -6, -15, -1 },
-  { 7, -12, -17, 1, -9, 5, 20, -7, 3, 23, -8, -8, -8, -1, 13, 17,
-    -7, -13, 4, -4, 7, 14, 8, 11, -3, -3, 4, 0, 4, 6, -1, -9 },
-  { 7, -15, -15, -4, 10, 12, 3, -13, 6, 14, 9, -8, -15, 14, 23, -5,
-    -10, -5, 1, 15, -10, -7, 1, 9, 4, -13, -10, 10, 7, -3, 2, 3 },
-  { 4, -10, -14, 0, 3, 4, 0, -9, -3, -4, -11, 2, -17, 8, 2, 15,
-    6, -12, -12, 15, -5, 17, 18, 3, -3, -3, -4, -6, -8, 13, 4, 10 },
-  { -2, -18, -26, 10, -4, 10, 13, 4, -4, -16, -7, -17, -3, 5, -4, 2,
-    -15, -10, -1, -8, -7, -3, 2, 2, 8, -10, -7, 2, 2, -4, 4, -1 },
-  { 4, -19, -5, -1, -1, -6, 2, -8, 10, -16, -28, -6, 8, -1, 11, 28,
-    2, -10, -4, 6, -6, 6, 11, 15, -4, -2, 7, 3, 7, -7, 4, 1 },
-  { -3, -6, -10, -5, 13, 18, 10, -15, -5, -3, -13, 5, 1, 2, 18, -5,
-    -10, -10, -7, 4, 2, 1, 5, 4, 2, 5, 4, 8, -9, -17, 7, 7 },
-  { 20, -12, -2, -4, 5, 14, 7, -11, -1, -16, -6, -4, -11, 17, 14, 0,
-    -8, -10, -8, 10, 3, 5, 10, -16, 3, -8, -14, 10, 3, 9, 0, 3 },
-  { 12, -10, -36, 0, 7, 15, 2, -16, 2, -1, 0, -1, 5, 4, 5, -3,
-    1, -10, 5, -1, -15, -3, -12, 12, 2, 5, -1, 5, 6, -3, -2, 2 },
-  { 17, -15, -31, 23, -4, 15, -2, -3, 6, -7, -5, 1, -12, 4, 6, 8,
-    -10, 8, 3, 5, -4, 1, 5, 3, -1, -4, -3, 1, 10, -4, -2, -2 },
-  { 6, -18, -5, 12, 10, 12, 14, -11, 15, 2, -9, -6, -5, -2, -9, 4,
-    -5, -28, -4, 14, 0, -16, 9, 14, -1, 3, -4, -4, 2, 1, 0, 4 },
-  { -5, -14, -31, 8, 16, 7, 13, -13, 5, 6, -16, 10, -5, 2, -2, 2,
-    14, -5, 8, -5, 7, -16, 6, -13, -5, 0, -5, 8, -3, -1, 4, 3 },
-  { 1, -2, -1, 0, 6, 5, 2, -4, -3, -1, 0, 1, 4, 2, 43, 28,
-    -12, -35, -2, -2, -7, -1, 0, 2, -1, -2, -2, 1, -4, 0, -2, 3 },
-  { 2, -9, -22, 12, 3, 3, -7, -4, -19, -22, -14, -4, -1, 21, 9, -3,
-    -15, -16, -13, 1, -11, 4, -9, 1, -7, -1, -1, 0, -2, 9, -13, -3 },
-  { -1, -3, -23, 0, 2, 12, 3, -9, -4, 7, 3, 9, -10, 1, 27, 28,
-    0, 9, -15, -2, -2, 1, 6, 8, -8, 7, -3, 20, 0, 0, -1, -6 },
-  { -1, 11, 8, -2, 1, 5, -6, -1, 4, 2, -4, 0, -1, -5, 4, -6,
-    -10, -12, 19, 1, -7, 9, -8, -9, -16, -11, -2, 12, 14, 4, 4, 34 },
-  { 17, 7, -6, 1, 4, -10, -5, 4, -11, 3, -18, 4, 14, -13, -3, 1,
-    0, 0, -11, 0, 7, -17, -4, 4, -11, -6, -8, 18, 0, 0, 0, 26 },
-  { -6, -7, -1, -1, 11, -8, 1, 3, 2, 11, -6, -6, 10, -3, 1, -3,
-    7, 4, -12, -8, 0, -9, 8, -22, -5, 0, -6, 22, -2, 11, -13, 24 },
-  { -3, 4, 0, 3, 9, 10, -1, 3, -9, -12, 1, -5, 18, 0, -3, 8,
-    25, 15, -8, 2, 2, -2, 4, 8, 9, -1, -5, 10, -3, 1, -1, 23 },
-  { -5, 2, -9, -1, -3, 0, 3, -1, -10, -4, 0, -13, 16, 9, -1, -14,
-    2, 6, -2, -6, -5, -2, -7, 7, 5, 3, 11, -2, -14, 0, -9, 30 },
-  { 4, 6, 6, 5, -3, -1, 4, 5, 10, 0, 5, -4, 7, -11, 14, 14,
-    7, 34, -9, 0, -10, 22, -7, -1, 7, -9, 2, -8, 0, -7, -5, 29 },
-  { -4, 3, -1, -4, -3, 5, 1, -4, 0, 2, 4, 2, 1, -1, -10, 1,
-    6, -6, -4, 1, 4, -3, -3, -5, 0, 3, 7, -12, 0, -2, -10, 55 },
-  { 5, 9, -1, 0, 4, 9, -21, -9, 4, 2, 6, -7, 11, -7, 1, -5,
-    0, -4, 2, -3, -13, -8, 0, -9, -4, 2, 16, -2, -15, -7, -11, 31 },
-  { 8, 2, -1, 0, 3, -5, -5, 5, 1, -1, -9, 1, 0, -6, -2, -1,
-    5, 2, 0, 0, 12, 20, -19, 1, 8, -12, -11, 0, 6, -5, 2, 31 },
-  { -1, -1, -2, 1, -1, 3, -9, -5, 8, -2, 5, -1, 0, -2, 4, -2,
-    -3, -12, 0, -2, 3, 0, 9, 4, -1, 21, -8, 3, -4, 9, -6, 30 },
-  { -4, 0, -7, 17, 10, -12, -2, -10, -12, -3, 10, 0, 11, -4, -13, -3,
-    5, 6, 10, 7, -8, 0, -7, -13, 1, 0, -2, 7, -12, 4, -3, 24 },
-  { -13, 9, 4, -2, 2, -4, -14, -1, -3, -5, -10, 4, 13, -2, 5, 13,
-    8, 3, -2, 1, 5, -6, 7, -18, -10, 1, -1, 5, 4, 1, 0, 25 },
-  { -5, -1, 18, 12, 8, 8, -16, -1, 1, 1, 1, -4, -5, 3, 3, 4,
-    4, -11, -12, -16, -6, 2, 12, -13, 0, 9, 7, 9, -9, 0, -10, 24 },
-  { -4, 1, -3, 0, 2, -4, 4, 1, 5, 0, -3, 2, -3, -2, 2, -1,
-    1, 4, -1, -2, -2, 1, -1, -1, -4, -1, -4, -2, -6, 6, 12, 69 },
-  { 8, 5, 11, 0, -15, -4, 13, 6, 0, -4, 9, 1, -5, -3, 15, 0,
-    1, 6, -5, 0, 1, 6, 5, 8, 0, 7, 1, -1, -4, -11, -9, 41 },
-  { -4, -9, 32, -6, 0, 7, -4, 6, -6, 1, -6, -2, 4, -8, -5, -3,
-    -16, -1, -2, -6, 1, 15, 0, 21, 3, -3, -4, 3, -12, 16, 2, 27 },
-  { -6, -5, 1, -9, -5, 3, 7, -3, 5, 5, 14, 13, 20, -7, -1, 12,
-    -1, 10, -11, -11, -7, -4, -14, 7, -14, 13, 22, 18, -1, 0, 14, 28 },
-  { -8, 3, -2, 0, 5, 6, -1, -4, 1, 3, -7, 3, 1, -15, 4, -9,
-    22, -10, -9, -4, 1, 8, -4, 9, -15, 2, -6, -4, -16, 12, -10, 23 },
-  { 0, 0, 2, 0, -1, 3, -3, -1, 3, -5, 7, 1, 5, -5, -8, 1,
-    13, -15, -5, -7, 12, -6, -2, 3, 10, -5, -8, 17, -5, -11, -14, 23 },
-  { -7, -4, 6, -4, 5, -6, -5, 2, -4, 11, 9, -4, 2, -2, -4, 6,
-    15, 3, -3, 18, -15, -2, -6, 3, 3, -20, 17, 11, -4, 2, 3, 29 },
-  { 6, 1, -6, 2, 3, 0, 0, -3, 3, 3, -1, 3, -4, -6, -6, -7,
-    -3, -2, -7, -2, -4, 5, 3, -5, -20, -13, -4, 10, -14, -29, 14, 37 },
-  { 3, 4, 3, -6, -4, 5, 0, 3, 2, 3, 0, -2, 4, 0, -3, -5,
-    -4, 4, -4, 4, 4, 3, 1, -4, -4, -9, -14, 20, -30, 3, -18, 33 },
-  { 0, 2, 5, -2, -4, -2, -1, 2, -6, -3, -2, -2, 2, -5, -1, 4,
-    3, 2, -3, 0, -1, -1, -10, -7, 2, -4, -18, 2, -37, -1, 12, 40 },
-  { -7, 2, -1, 0, -2, 4, -8, 1, -4, 12, 7, 4, 15, -7, 1, -9,
-    18, 0, 12, -17, -3, -1, 0, 0, 0, 2, -6, 0, -4, -3, -1, 26 },
-  { -6, 4, 8, -5, -6, -2, 2, -1, 1, -1, -15, 8, 7, -1, -17, -4,
-    1, 5, 6, -11, -6, 14, 17, -5, -15, 11, 8, 0, -3, -15, -6, 28 },
-  { -1, 0, 0, 0, 1, 0, -1, 0, 1, 3, 2, -2, 3, -1, -1, 2,
-    2, -1, -1, -7, 1, 2, -9, 0, -1, -4, -18, 7, -10, 49, -13, 32 },
-  { -1, -3, 4, 1, 2, -5, 1, -7, -1, 5, -9, 4, 4, 25, 1, -1,
-    2, -5, 2, -7, 17, -2, 10, -5, 0, 2, -15, 3, -9, 7, -9, 30 },
-  { -5, -1, 0, 2, 1, -1, 2, 5, -33, 3, -5, 14, 11, 7, 5, -3,
-    2, -8, -4, -2, -7, -6, 4, -8, -1, -8, 2, -2, -8, -1, -4, 27 },
-  { -1, 0, -1, -2, 1, -1, -2, -1, 2, 0, 1, 2, 2, 4, 1, 3,
-    4, 2, 1, -7, -4, 1, -3, -4, -35, -25, 17, 10, -3, -26, -7, 32 },
-  { -5, 1, 6, -2, 6, 6, -9, 3, -1, -4, 5, -4, -2, -2, -9, 2,
-    -5, 2, 2, 4, 3, 5, -5, -16, -31, -12, -11, 2, -19, 20, -2, 21 },
-  { -5, 2, 7, -7, -7, 5, -7, 2, 0, 0, -4, 3, -1, 0, -1, -2,
-    0, -3, 5, -11, -8, -3, -7, -7, 28, -11, -7, 0, -16, -11, -4, 29 },
-  { 2, 1, -3, -2, -1, 3, 4, 0, 1, 0, -1, -5, 4, -5, -12, 2,
-    -2, -5, -22, -2, -1, 11, 8, -7, -12, 0, -34, 6, -5, 11, -8, 19 },
-  { -1, -3, 5, 11, 18, -2, -2, -5, -2, 4, -1, 8, 5, -6, 1, -1,
-    2, 8, 4, -5, -8, -2, 5, -18, 7, 12, 7, 19, -18, 2, -6, -13 },
-  { 9, 0, 0, 5, 4, 3, -6, 4, 1, -4, 5, -1, -4, 8, 8, 6,
-    -8, -6, 0, 6, -3, 3, 5, -3, 17, 31, 16, 10, -13, 0, -9, -19 },
-  { 12, -10, 2, -2, -2, -1, -3, 6, -12, -5, -2, 14, -16, 4, 12, 12,
-    17, 4, 7, -16, 7, -6, 11, 7, 7, 2, -25, 23, -24, 5, -7, -9 },
-  { 10, 4, 13, 10, 10, 3, -6, 3, 3, 2, -1, -6, 8, 4, 10, 0,
-    1, 2, -4, 2, -3, -8, 0, -1, 9, 9, -10, -3, -29, 1, -1, -27 },
-  { 2, 2, 0, 7, 9, -2, -10, -1, -1, 1, -9, -5, 8, 4, 1, 2,
-    -10, 1, 13, 12, -3, 15, -9, 2, -7, 1, -10, 23, -20, -18, -9, -15 },
-  { -3, -5, -1, 8, 0, -5, -1, 4, 7, -1, -7, 2, -8, -5, 11, 7,
-    -6, 3, -3, -9, 7, 9, -22, 1, 6, -4, 14, 27, -25, -14, 3, -5 },
-  { 1, 3, 8, 4, 7, 6, 12, -17, -15, 1, -8, -10, 7, -14, -8, 6,
-    -2, -2, -11, -11, -7, 13, -2, -2, 4, 5, -5, 13, -23, -6, -17, -8 },
-  { -5, 4, -14, -5, -4, -5, 6, 5, -8, -5, -2, -11, -7, -12, 3, -11,
-    2, -6, 4, -10, -5, -7, 14, 5, 23, 11, 7, 12, -16, -6, -4, -16 },
-  { 5, 6, 2, 5, -2, -5, -5, -6, -5, -19, -13, -1, -3, -13, 5, 0,
-    6, -2, -2, -6, -7, -7, -1, -9, 4, 14, 17, -12, -27, 3, 0, -1 },
-  { 7, -1, 9, -10, 8, 2, -7, -2, 5, 2, -3, -7, 3, 0, 6, 4,
-    12, 5, 11, 14, -13, -1, 8, 1, 13, 9, 12, 12, -18, -14, -11, -16 },
-  { -7, -5, -6, -5, 0, -1, -3, 2, 2, 1, 4, 9, 2, 3, 5, -2,
-    2, 1, 8, 0, 3, 0, -2, 2, 1, 7, 29, 0, -36, -5, -9, -21 },
-  { 14, -6, -9, 0, -1, -8, -8, -11, 2, 2, -9, -12, 12, -4, 5, 3,
-    -5, -9, 11, -1, -3, 12, -21, -3, 12, 5, 3, 11, -18, -15, 1, -2 },
-  { -1, 3, -9, -3, 7, -7, -18, 2, 4, 12, -10, 2, 8, -3, -14, 13,
-    17, -5, 5, -9, 13, -3, -7, -18, 17, -2, 5, 7, -20, -3, -6, -11 },
-  { -3, 3, 3, -1, 1, -6, -5, 1, 5, -3, -14, -6, -5, -8, 14, -6,
-    7, -1, 5, 1, 15, -1, -7, -4, 6, -11, 9, -2, -37, 16, -7, -3 },
-  { -1, 0, 6, 1, -3, -9, 0, 11, -8, 2, -2, 0, 5, 2, 12, -10,
-    10, 13, 2, 7, -6, 2, -10, -10, 21, -5, 5, 5, -12, -23, 3, -14 },
-  { 6, 0, -2, 1, 0, 1, 0, -4, 1, 1, 8, -2, 2, -5, -2, 1,
-    8, -4, -1, -1, 4, -1, 2, 6, 32, 1, -5, -20, -40, -4, -18, -14 },
-  { 2, 2, -7, -2, 4, 4, -1, 2, 0, -2, -4, -7, 3, 5, 0, -5,
-    1, 2, -6, 4, -1, -2, -1, -15, 8, 3, 9, 46, -7, -18, 6, -11 },
-  { 5, 5, 16, 21, 3, -11, -4, 11, -12, 2, 4, -12, -1, 11, 8, 1,
-    -4, 11, -11, -21, 1, 1, -11, 3, 13, 1, 5, 12, -25, 1, -3, -2 },
-  { 1, 6, -7, 4, 2, 3, 1, -5, 8, 9, -15, 3, -3, -14, 17, 4,
-    -8, 14, -2, -8, -4, 5, 8, -7, 8, 9, 7, 6, -29, -17, 8, 4 },
-  { -7, -7, 4, 0, 13, 1, 0, 4, 4, -16, -10, -7, 5, 9, -15, -10,
-    -10, 8, -4, -1, -11, -1, -10, -15, 3, 3, 14, 10, -19, 2, -18, -12 },
-  { -4, 0, 2, 0, 5, -2, -9, 0, 4, -4, 2, -1, -2, 2, -4, 9,
-    2, -6, -4, -2, -1, -3, -3, -1, 2, 5, -1, 11, -24, -44, -9, -15 },
-  { -1, -10, 6, 21, 11, 15, -7, 10, -14, -9, -8, -8, 4, 6, 19, 1,
-    -6, 1, -5, -17, -8, -10, 9, 5, 11, 18, -1, 10, -16, -7, -9, -8 },
-  { 3, -5, 0, 0, -2, -2, -6, 4, -4, 1, -1, 0, 7, -3, 4, -4,
-    -7, 7, 17, -20, 6, 4, 1, -6, -12, 31, 13, 19, -14, -10, -7, -2 },
-  { -2, 6, -10, 3, 9, 6, -14, 15, 2, -5, 2, -11, 9, -8, 4, 6,
-    20, -15, -3, -3, -1, 32, -21, 6, 1, 9, 11, 17, -19, 6, -1, -3 },
-  { 8, 10, -2, 0, -8, -16, 7, 7, 6, 10, 4, -14, 7, -6, 21, -7,
-    10, 5, 5, 0, -7, 2, -6, 0, -7, 11, -9, 15, -20, -7, -11, 2 },
-  { 0, -7, 5, 2, 0, -3, -6, -4, -2, -1, -4, -5, -13, -1, 27, -9,
-    -6, -11, -7, 1, 11, -4, -4, -14, -2, 11, 6, 10, -19, -6, -15, 2 },
-  { 0, 7, -1, 2, -7, -15, -2, -3, 13, -5, -5, 12, 3, 0, 5, -5,
-    -22, 2, 7, 22, 13, 0, -1, 2, 3, 2, -7, 7, -27, -4, -4, -12 },
-  { 11, 1, -16, 6, -15, 1, 3, 2, 0, 2, -3, 2, 5, -2, -5, 9,
-    5, -3, 3, -2, -11, 3, 9, 6, 9, 3, -1, 12, -41, 8, -6, 9 },
-  { 3, -7, 3, 2, 5, 5, 0, -1, 1, 3, -5, -2, -13, 7, -1, -2,
-    -2, -6, 4, -6, 0, 2, -2, 2, 4, 1, -4, 1, -47, -21, 7, -6 },
-  { 3, 16, -7, 13, -4, -2, 10, -3, -1, 18, -13, 7, -13, -4, 8, 4,
-    8, 9, -5, 13, 8, -5, 3, -6, 7, 18, -8, 10, -25, -3, -12, -12 },
-  { 1, -1, -1, 0, 2, 5, -5, -3, 0, -5, -1, 0, -4, -8, -2, 3,
-    2, -2, -17, -6, -4, 1, 33, -6, -20, -6, 8, 31, -26, -8, -1, -4 },
-  { 3, -3, -3, 5, -3, -2, 1, 7, 0, 3, 6, 3, 6, -2, 9, 15,
-    -10, -3, -15, -5, -3, -4, -6, -30, 17, -8, -2, 2, -20, 0, -8, -2 },
-  { -2, -1, -1, -1, 3, -5, -2, -3, 4, -2, 0, 5, 8, -3, 1, -4,
-    1, 1, -3, 4, 4, -14, 3, 11, -5, 3, -3, 7, -3, 13, 23, -16 },
-  { 2, -6, 1, -3, 5, 0, -6, -11, -7, -4, -1, 2, -7, -1, -1, 7,
-    1, -2, 6, 12, -6, 8, -13, 17, 25, -23, -19, -7, -12, 9, 16, -17 },
-  { 9, 4, 4, 4, -3, -1, 6, -2, -3, 0, 13, -4, -7, 14, 1, -7,
-    0, -5, 3, -19, -3, 5, 3, 9, -1, 9, -13, 13, -17, 4, 21, -26 },
-  { 0, -5, 0, 0, -4, -5, 2, -6, -4, 5, -7, 10, 0, 2, 0, -2,
-    -2, 0, 4, -6, 7, -2, 6, 5, -5, 2, -12, 1, -29, 29, 27, 12 },
-  { 9, -10, -22, 6, -1, -1, 9, -14, -12, -2, 1, -1, 10, -11, -16, 0,
-    3, 11, 13, -14, -9, -2, -1, 6, 4, -14, 0, -10, -2, 16, 17, -11 },
-  { 2, 0, -1, -2, 4, 3, -6, -2, 1, -1, 1, 3, -4, 1, 3, -4,
-    -1, -1, 4, -1, 1, 0, 1, 6, -5, -7, 2, 1, -47, -3, 50, -17 },
-  { 8, -4, -11, -7, 11, 11, 14, -7, 12, -7, 6, 2, 13, -6, -3, -2,
-    -14, 6, 6, 6, 0, 2, -1, 5, -20, 2, -1, 4, -5, 6, 21, -11 },
-  { -2, -9, 3, 0, -6, 7, 8, -8, 1, -3, 4, 1, 5, -2, -3, -7,
-    4, 7, -12, -9, -2, 10, -6, 13, 6, 5, 20, 2, -15, 9, 28, -7 },
-  { 0, -5, -6, -6, -6, 1, -6, 6, -2, 4, 8, -3, 12, -1, -4, -2,
-    6, 16, -14, 9, -14, -2, -8, -27, -3, 18, -1, -7, -3, 8, 23, -23 },
-  { 1, 4, -9, -1, -5, 10, -2, 1, -11, 1, -9, 4, 7, 14, -9, -2,
-    -3, 2, -5, -1, -6, -10, -7, 11, 20, 2, 3, -19, 3, 15, 30, -9 },
-  { 7, 2, -14, -4, 0, -2, 5, 2, 5, -2, 8, -3, -7, 6, 6, -11,
-    -14, 1, 10, -1, -7, -8, 1, 10, 3, -6, -15, -12, -17, 4, 30, -6 },
-  { 4, 2, 1, -2, 3, 0, 1, 0, 2, 0, 1, 6, -7, 0, 3, 4,
-    4, -4, -2, -5, -2, 2, -1, -2, 0, -2, -11, -7, -3, 42, 24, -14 },
-  { 4, 1, 3, 2, 0, -2, -3, -2, 2, -1, 4, 11, -2, 2, 3, -4,
-    -5, 9, 2, -4, -9, 5, 8, -1, -7, 1, 24, -13, -28, 20, 15, -22 },
-  { -3, 7, 6, 3, -2, -5, -10, -2, -2, -1, -6, -6, -2, -14, -16, -6,
-    -5, 0, 18, 0, 9, 1, 7, -13, -5, -6, -9, 11, -15, 9, 22, -11 },
-  { 9, -2, 6, 5, 2, 9, -10, 1, 1, 5, -4, 12, 2, 2, -10, -7,
-    -4, -6, 7, 9, 6, 15, 6, 6, -10, 10, 5, -13, -5, 6, 24, -12 },
-  { 1, 3, -3, -3, 8, 1, -6, 2, -5, -3, 7, 2, 14, 6, 9, -6,
-    -5, -4, 27, 7, -3, 8, -6, 3, -8, 8, 22, -5, -6, -2, 22, -17 },
-  { -2, -2, 3, 10, 9, 9, 12, -15, -1, -11, -13, 3, -2, 1, -3, -11,
-    7, 9, 16, -3, -10, -5, -5, 1, 8, -3, 9, 9, -5, 3, 31, -12 },
-  { 7, -5, 10, -4, -8, 2, 16, -2, 10, 10, -3, -2, 3, -8, -3, 3,
-    -13, -6, 15, 20, -9, -3, -12, 1, -2, -16, 8, 8, -1, 16, 22, -5 },
-  { 5, -3, -15, -2, 12, -8, 8, -5, 2, -8, 20, -18, 14, -4, 3, 3,
-    7, -13, -16, 1, -10, 7, 16, 7, 4, -14, -4, -5, -9, 8, 23, -6 },
-  { 5, -4, -5, -4, 1, 8, 4, -7, -5, 8, 10, 6, -6, -10, -2, 6,
-    9, -17, -14, 11, 12, -3, -13, -7, 2, 18, 3, -25, -16, 18, 22, -5 },
-  { 5, 6, -7, -20, -4, 2, 8, 4, -24, -4, 1, 4, -5, -2, 1, -10,
-    -2, 9, 3, -4, -3, -4, -4, -4, 10, 10, 3, 0, -6, 25, 21, -11 },
-  { 0, 7, -1, 14, -6, -4, -10, 5, 4, 4, 4, -5, 3, 4, -1, -7,
-    8, -19, 0, 6, 2, 3, -18, -3, -6, 2, 8, 14, -26, 22, 27, -13 },
-  { -2, -6, 7, -5, 12, -7, 8, -1, 3, -2, 4, 1, 8, -2, 0, 14,
-    6, -5, 6, -4, -7, 7, -21, 8, 1, 8, -9, -4, -3, 11, 25, -13 },
-  { 4, 4, -1, -6, 4, 9, -8, 1, -3, -10, -2, 0, 15, -9, -16, 11,
-    1, 1, 6, 3, -9, -5, 16, 26, 1, -14, 1, -3, -14, 7, 15, -9 },
-  { -12, -2, -9, -13, 2, 6, 14, 0, 1, 0, -1, -13, 0, 10, -1, 6,
-    9, -7, 8, 8, 19, 6, -1, 9, 10, -4, 1, -7, -22, -2, 29, -7 },
-  { 2, 4, 13, -12, -8, -4, -5, 13, 12, -5, -3, -3, -4, 1, -1, 10,
-    15, -6, -1, -11, -30, 4, 15, -1, 9, -7, 0, -2, -7, 10, 25, -16 },
-  { 7, -15, -7, -7, -1, -5, -5, -11, -20, 10, 3, -10, -3, 5, 20, -4,
-    0, -2, -2, 17, 2, 0, -3, 3, 6, 5, -1, -12, -3, 15, 22, -16 },
-  { 4, -1, 3, 4, -5, 0, -1, -5, -24, -29, 4, -9, 1, -3, 0, 0,
-    0, -4, 7, -4, -4, -4, 3, 1, -6, 5, -3, -5, -10, 3, 25, -10 },
-  { -2, -1, -1, 4, 4, -1, 2, 0, -4, -4, 2, -1, -3, -1, -2, -2,
-    1, -3, -5, -1, 2, -3, -4, -4, -3, 5, -9, 1, -11, 7, 46, -46 },
-  { 0, -9, 3, 4, 4, 3, -5, -6, 5, -4, 4, -2, 1, 7, -4, -10,
-    13, 1, 3, -6, 4, -4, 7, 2, -19, -25, -3, -16, -12, 16, 20, -1 },
-  { 18, 6, 4, -12, 0, -14, 9, -6, -1, -4, -5, 2, 1, 12, 4, 2,
-    7, 0, 2, 5, -11, -5, -2, 2, -4, 10, 0, -9, -7, 9, 25, -8 },
-  { 5, 0, -6, 5, 6, 3, 3, -10, -5, 1, -1, 4, 3, -11, -8, 5,
-    4, -5, 5, -5, -7, -5, 11, 5, 20, -8, -16, 21, -4, 27, 23, -5 }
+  {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+     0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0 },
+  { -4, -2,  2,  1,-16,-10,  1,  3,  1,  0,  6,  1, -3,  7,  1,-22,
+     2, -4, -3, 11, 14,  6, -1,  1,-13, 29,-28, 10, 10, -8,  0, -9 },
+  { -8,  8, -7, 10, -3,-12, -5, -8,  1, -2,  9, -2, -5,-18,  1,  9,
+    -8, -8,  3, 41,  7, -9, -9, 22,-42,-29, 14,-18,-14,-32,  1,-15 },
+  {-16,  8, 15, 16,-16,  5,  2,  7, -6,-16, -7,  1,  1, -3, -2,  0,
+     8, 20,-26,-11,  2,-17,  0, -3,-34,-37, 10, 44, -2, 22,  2, -4 },
+  {  7, 14,  5,  6, 15, -1,  3, -3, -9,-23, -5,-14,  8, -1,-14, -6,
+    -5, -8, 54, 31, -6, 18,  2,-19, -2,-11,-30, -6,-19,  2, -2,-14 },
+  {  1,  2, -2, -1, -3, -3,  1, -5,  1, -3, -4, -8,  5, -4,  0,  1,
+     3,  7, -5, -4, -3,-12,  3, -2, -3, 12,-53,-51,  6, -1,  6,  8 },
+  {  0, -1,  5,  1, -6, -8,  7,  5,-18, -4, -1,  1,  0, -3, -3,-14,
+    -1, -6,  0,-14, -1, -1,  5, -3,-11,  1,-20, 10,  2, 19, -2, -2 },
+  {  2,  4,  3,  0,  5,  0,  3,  1, -2,  0, -6, -3, -4, -5, -3, -3,
+    -7,  0,-34,  4,-43, 17,  0,-53,-13, -7, 24, 14,  5,-18,  9,-20 },
+  {  1,  0, -3,  2,  3, -5, -2,  7,-21,  5,-25, 23, 11,-28,  2,  1,
+   -11,  9, 13, -6,-12,  5,  7,  2,  4,-11, -6, -1,  8,  0,  1, -2 },
+  {  2, -4, -6, -4,  0, -5,-29, 13, -6,-22, -3,-43, 12,-41,  5, 24,
+    18, -9,-36, -6,  4, -7, -4, 13,  4,-15, -1, -5,  1,  2, -5,  4 },
+  {  0, -1, 13, -6, -5,  1,  0, -3,  1, -5, 19,-22, 31,-27,  4,-15,
+    -6, 15,  9,-13,  1, -9, 10,-17,  4, -1, -1,  4,  2,  0, -3, -5 },
+  { -7,  3, -8, 13, 19,-12,  8,-19, -3, -2,-24, 31, 14,  0,  7,-13,
+   -18,  0,  3,  6, 13, -2,  1,-12,-21,  9, -2, 30, 21,-14,  2,-14 },
+  { -3, -7,  8, -1, -2, -9,  6,  1, -7,  7, 13,  3, -1,-10, 30,  4,
+   -10, 12,  5,  6,-13, -7, -4, -2, -2,  7, -3, -6,  3,  4,  1,  2 },
+  { -8,  9,  2, -3, -5,  2,  0,  9,  3,  7, -4,-16,-13,  3, 23,-27,
+    18, 46,-38,  6,  4, 43, -1,  0,  8, -7, -4, -1, 11, -7,  6, -3 },
+  {  1,  1, 18, -8, -6,  0,  3,  4, 22, -3, -4, -2, -4,-11, 40, -7,
+    -3,-13,-14, -7,-10, 14,  7,  5,-14, 11, -5,  7, 21, -2,  9, -3 },
+  {  0,  0, -2,  4, -2,  0,  2,  0, -1,  2, -1,  0,  0,  2,  2,  2,
+    -1,  1, -3, -1,-15, -2,-63,-27,-21,-47,-14,  1,-14, 10,  0,  2 },
+  {  1,  0, -4,  0, -3, -9,  4,  2,  6, -6,  0, -5, 11, -7,-15,  6,
+    -7, -6,  3,  7,-15, -5, 23,-13, -6, 12, -8,  9,  2, -3,  3,  4 },
+  {  6,  0,  3,  0, -2, -4,  2,  1,  1, -1,  1, -2, -1, -4,-22,-15,
+   -46,-66, 10, 20,  2,-17, 12, -6,  1, -2, -2,  0,  1, -5,  1,  2 },
+  { -1,  0,  0,  1,  0, -4,  0,  1,-10, -3, -8,  5,  7,-11,  2,-11,
+    29,-25, 11, 10,  0, -1,  5, -7, -2, -5, -2,  4,  4, -3,  5, -2 },
+  {  1, -1, -1, -3, -2,  1, -8, -3,  2, -2,  4, -5, -1, -7, -2,  1,
+   -14, -7,  3,-30,-15,-14,  3, -4, -1,  3,-13, -1, -3,  1,  2,  3 },
+  { -1, -2, -3,  2,  2, -3,  3,  1, -3,  2,  0, -4,  6,  5, -5, 10,
+   -57,  3, 22,-50,  1, -2, -5, -6, -1,  5,  1,  2,  2,  1, -2,  2 },
+  {  2,  0, -1, -7,  2,  1,  3,  2,  0,  4,  3, -2,  3, -3,  4, -4,
+    24,-35, -3, 38, -6, -5, 15, 20,  3, 16, -7, -5,  0, -4, -5,  0 },
+  {  0,  1,  0,  0,  0, -1, -1,  1,  1, -1,  1, -2,  0,  0,  0,  0,
+     0, -1, -2, -1, -5, -2,-43, -3, 46,-52,-10,  7, -8, 11, -2, -1 },
+  {  0,  0, -1,  0, -1,  2,-41, 33,-44,-48,-15,-26, -9,  6,  3,  3,
+    -3,  2,  2,  2,  2, -1, -1, -2,  1,  3,  0,  0,  5,  2,  3,  1 },
+  { -4,  1,  6,  1, -6, -1, -2,  1,-14, -4,  0, -5, -2,  2, -2,  0,
+    -6,  1,  0,  8,-21, 32, -3,-36, -6, -2, -1, -7,  3,  0,  1, -6 },
+  { -3, -2,  3,  0,  2,  2,  8, -4, -4,  6,  2,  1,  3, -6,  4,  3,
+    13,  0,-12, -1, 25,-20, -2,-23,-15,  7, -3,-11, -3,  6, -1,  0 },
+  {  0,  0, -3, -1,  0,  0, -2, -1, -2, -2,  1, -1,  0,  0, 10,  3,
+    -2,  3,  3, -7, -6, -5,  0, -4,-60,-16, -6, 38,  5,  6, -5,  0 },
+  {  0,  1,  0,  0,  0,  0,  0,  0,  1, -1, -1,  0,  1,  0,  0,  1,
+     0,  0, -1,  0, -8,  2, -9, 10, 40, 31,-56,-21,  4, 20, -4,  7 },
+  { -2, -2,  0,  4, -3, -1,  7,  3,  1,  3, -8,  0,  3,  1,  2,  5,
+     1, -2, 14,  5,  4,  5,  5,  5, -5,  9,-66,  0,-20, -2, -8,  4 },
+  { -2, -1,  4, -1, -8, -2, -4, -1, -3, -3,  2, -7, -3,  5,  7, -2,
+    45, 31,-17,-16, -2, -2, -1,-22,  1, -1, -3,  3,  5, -3,  5, -1 },
+  { -4,  0,  7,  5,  8,  7,  2,  9, -9, -9, -7,-11, -3, -8, 17, -4,
+    34, 32, 18, 22,  1,  2,  1, -7, -5,  6, -1,  6,  4, 10, -2, -7 },
+  {  6,  0, 14,  9,  6, -1, -2, -3,  4, -6, -8,  4,  7, -1, 28, 38,
+    15, -1, 16,-11,  5,  8,  4,-10,  3,-10,-17,  5,  3,  3,  3,  1 },
+  {  1,  1,  2, -1,  2,  1,  0,  0, -1,  0,  0, -2,  1, -3,  0,  1,
+     2, -2, -4, -2,  0, -1,  1, -3,  1,  1,  1, -1,  8,  8, 66, 33 },
+  { -5,  2, -3, -7,  2, -8, -4, 10, 17,-18, -7,  4, -4, -7, -6, -6,
+    -5,  5,-12,  2,  0,  6,  8, -2,  1,  4,-11,  2,  1,  8, 31, 19 },
+  {  6,  9, 16, -6, -6, -1, -2, -3,-11, -2,  7,  7, 17,  3,  4, 10,
+     2,  5,-13,  8,  7,  1,  4,  5,  7,  6,  7, -8,  9, -8, 33,  6 },
+  {  3, -1,  1,  0, -7, -5,  0, 14, -7,  1, -7,  1,  2, -4,  7, 10,
+   -16, 12,  1, -6,  3,  8, -1, 10,-13, -6,-12,-23, 12, -3, 30, 14 },
+  { -2,-15,  0,  8,  3,-19,  5, -3,  2,  3, 13,  7, 14, -3,-10,  0,
+     8,  5, -6,-16, -8, -8, 14,  2, -1,  1, -9,-11, 11, -5, 27,  9 },
+  { -8,  6, -4,  4, -4, -1,  5,  4,  1, -7, -5, -4,-15,  1,  9,  0,
+     8,  4,  1,-17, 11, -2,-19, -1, -6, -8,  3,-12,  3,-17, 33,-10 },
+  { -3, -1,  2,  7,  7, -2,  9,  8,-18, -1,-13,-10, -3, -3, 11,  8,
+    -2,-12, -8,  1,  4,  9, 14, 10, -3,  0,  2,  1, -2,  3, 31, 10 },
+  { -3,-10,  8, -1, -5,-11,  7, -5,  3,  6,  1,  4,-16, 10,  5, -4,
+    -2,-10, -1, 13,  6, -5, -7, 12,  7, -3,-17,  1, 12, -4, 29,  8 },
+  {  1,  2,  5,  2, -6, -7,  0, -1,  6, -1, 10,  6, -4,  5,  2,  2,
+    -2, -8, -6,-11, 14,-13, 27,  3, -2,-12,  5,-16,  2,-26, 20, 15 },
+  { -1, -3, -5, -3, -3,  6, -1,  3, -5,  1,  7,  2,  1,  0, -1, -1,
+     0, -1,  9,  7, -6, -3,  4, -5, -4,  8, -8,-25, -8, -4, 34, 23 },
+  { -1, -2,  1,  1, -1, -2, -1,  1, -1,  0,  0,  0,  0, -2, -1,  1,
+     0,  2,  1, -1,  4,  0,  0,  1, -1,  0,  5,  3, 12, -9, 68,-16 },
+  { 10,  0, -8, 14, -6,  1,-12,  0,  0, -3, -5,-11, -6, 12,  9,-10,
+    -3,  5,  0,  7, 11,  2,  4, -3, -8, -3,  7,  4,  3, -3, 34,  4 },
+  {-12, 13, -5,  7,-11, -2, -1,  1, -4,-14,-21,  3, -3, -3, -4, -7,
+    -9, -4,  3,-17, -2,-13, 10, -2, 12, -4,  0, -9,  1, -5, 31, 10 },
+  {-10,  6,  5,  6,  4, -7, 10,  0,-28, -3,  0,-11, -1, -5, 16,-10,
+   -16,  7, 20,  2, -4,  2, -5,  0, 15,  6,  5,-10,  7, -9, 20,  4 },
+  {  1, -7, -2, -7,  4, -3, -2, -7, -1,-14,  6,-16,  4, -5, -4, -6,
+    -5,  0, -2,  2, -6,  9, -5,  4,-18,  8,-10,  8, 15,  0, 32,  1 },
+  { -5,  7, -3,  7, 15, -4,  0,-16,  9,  5, -5,  5,  4, -3,-12, -9,
+   -18, 10,  2,  2, -3,  7,  3, -1,  6, -9,-10,  3, 15, -4, 35, -7 },
+  { -1,-10,  2,  2, -4, -2, 10,  2, -1,  2, -2,  1, -1,-14,-11,  3,
+    -8,  5, -8, -2,  6, -1, -7,  1,  7,  5,  7,  8, 30, -4, 30, 14 },
+  {  2, -2,  1,  2,  3, -8,  3,  0, -2,  0, -9,  2,  1,  4, -6, -1,
+    -2,  5,  0,  1, -2, 12,  6, -3,  9, -3,  4,-12, 21,-39, 24, -2 },
+  {  3,  5,  1, -2, -2, -2, -3,  6, -8, -2,-11, -8, -1,  4,  2,  2,
+    -4,-10, 12, -5,-11,  1,-15,-34,-11, -7,-11, -1,  7,-14, 38, -1 },
+  { -4,  4,  8,  9,  8,  1, -5, -9,  4, -2, 15, -4, 11,-15, 20, -1,
+    -1, -3,  4, -9, -2, -2, -2,  8,  6, 12, -5,  0, 11,-12, 27, -4 },
+  {  0,  8, -4,  3,-11,  6,-11,  2,  3,  0,  5, -8, -7, -6, -9,-21,
+     4,-11, -1,-16, -7, 16, -3,  7, -7,  4, -5,  0, 11, -7, 31,  3 },
+  {  1,  3,  4, 11,-11, -2, -3, -6,  6,  5,  0,  3, -9, -6,  4, -4,
+     0,  4, -8, 13, -6,-13, -1, -5, -1,  4,  0,  0,  9,-22, 24, 18 },
+  { -7,  3, 10,-13, -6,  6, -6,  6, 22,  1,  0,-14,  2,  3,  7, -1,
+     8, 20, -1,  5, -4, 13,  9, -9, -9,  6,  0, -4,  0, -8, 31, -4 },
+  { -3, -4,  0,  1,  7,  3, -7,  0,  5, -2,  1,  3,  3,  1, -5, -2,
+     5,  2,-11,  4,  0, -1, 12,  0, -3,-13, 15,  8, -6,-27, 34,  0 },
+  { -3, -3, 10, -4,  2, -1, -3,  0, -1, -1, -4,  2,  6, -2, 12,  1,
+     3, -6, -7, -6, -5,  4,-19, -6, -8,-34, -4, -8, 10, -7, 23, 10 },
+  { -7,  0, -1, -6,  8,  4, -4,  2, -5, -8, -7, -9, -8,  5,  9,  7,
+    -6,  1,-12,-12, -1,-16,  5,  0, 16,  3, -7, -8, 27, -4, 23, 15 },
+  { -8,  4,  8,  5,  6, 11, -3,  5,  3, -1,-11,  6, -5,  0,  2, -6,
+    -3, -6,  4, -1,  5, -5,-12, -6,  7, -5,  9,  3,  6, -7, 29,  1 },
+  {  1,  3, -2, -2, -6, -2,  1,  6, -6, -3,  1,  2,  3,  4,  1,  5,
+    -1,  0,  4,  2, 11,  6,  2, -3, 13, -9,-19, 18,-15,-10, 36, 21 },
+  { -3, -3,  2, -1, -7,  6, -4,  1, -3, -1, -2,  2,  3, -7, -3,  0,
+    -2,  0, -2,  6,-19,  3, -8,  2, -6,  7, -1,  0, 29, -6, 28,-10 },
+  { -5,  1, -3, -7,-12, -4,  1,  1, -1, 13,-10, -1, -9, -5,-13,  6,
+    13,  3, -4,  2,  3, 11,  2,  6,-25,-16, -6,  0, 14, -1, 27, 16 },
+  { -6, -1, -7, -5, -2, -5, -5, -1,  9,  1,  0,  3, -8,-12, -6,  5,
+    -6,  5,  3, -9,  1,  4, -7,-10, -9, -7,-17, -5,-15,-23, 25,  3 },
+  { -8, -2,  9, -3, -4,  3, -1,  8, -7, -7, -5, -4, -2,  9,  4, -1,
+    -7, -4, -5,-16,  3, -6, 18,-13, -9, 16,-15,  8, 15,-10, 24,  5 },
+  {  1,-38,  2, 34,  9, 10, 11,  2,  2, -6,  3,  2, -2,  5,  4, -7,
+    -1,  1,  4,  0,  3,  1, -8, -1, -6,  5,  4,  2, -4,  5,  2, -1 },
+  {  1,-22, 15, 18, -2, 10,-16, -9, -8,-11,  8,  4,  0,  7,-14, -5,
+    -1, -7, 12, 17,  9,  5, -7, -4,-12, -6,  7,  0,  7,  2, -2,  1 },
+  {-11,-29,  7, 10, 19, -1, -8, -9,  7,  1,  9,  6,  8, -7,-14,  8,
+    -3,-11,-13,  0, -7,-23, -2, -8, 12,  9,  2, 14, 19,  1, -1,  5 },
+  {-24,-27,-11, 36,  2,  6, -3,  4, -6,  8,  0, 12, -1, -4, -6,  3,
+     4, -1,  2, -3, -2,  3,  2, -1, -2, -4,  0, -1, -2,  7,  2,  3 },
+  { -9,-24, 11, 13,-10,-12, 12, -2,  7,  4,  8, 13, -3, -3,  2,  9,
+    -3, -4,  4, 13,  5, 13, -6, -3,  1, 15,  7, -3,  0, 19, -2, -9 },
+  { -8,-15,  7, 14, -4, -5,  2,-18,-19, -2,  2, 17, 16,  6,-10, 10,
+    -9, 14, -1, -5, -1, -6, -7,  2,  9, 11, 13,  6, -5,-12,  3,  2 },
+  {-10,-37, 13,  1,  3,-14,  0,-20,  4, -3,  8,  2, -2, -3, -9, -5,
+    -3,-17, -1, 13,-11,  2, -6,  4,  4,  0,  3,  1, -9, -4, -5, -4 },
+  { -2,-22, -5, 46, -8,  5,  9,-11,  8,  7,  7, -1, -1, -2, -7,  2,
+    -3,  3, -1, -2,  7,  0,  2, -1,  1, -2, -2, -3,  6,  0, -4, -6 },
+  {-16,-27, 15, 16, -4, 14, -7,-26,  2, -2,  6,  5, -3, 11,  0,  2,
+     3,  9, -7, -1,  2, -4, -4, -1,  6, 10,  1,  1, -3, -2,  3,  0 },
+  { -3,-22, 10, 26,  1,  2, -3,  3, 17, -3, -7,  9,  1,-21, -4,  5,
+     3,  0, -7, -6,  3,  3, -8, -7, -9,  3,  7,  1, -8, 12,  6, -7 },
+  { -9,-25,  3, 18,  9, -6,-11,  0, -5,-12,  9, -8, -7, -6, -6, 22,
+     2, -6, -3, 15,  3,  2, -2,  9, 14,-10, -7, 15, 13,  6, -2, 11 },
+  {  5,-20, -5, 28, 11, 10, -4, -4,  0, -7,  3,  5,  2, -5, -8,  2,
+     6, 10,  9, -9,-18,  3, 14,  1,  3, -3, -1, -6,  7,  7,  2, -1 },
+  { -8,-30,  7, 12, 10,  8,  7,-13,-16,  0,  1, -1, -6,-11,-15,  4,
+     1, -2, 10,-15,  1, 11, -2,  8,  9, -7, -7,  9, -5,  2,  7,-18 },
+  {-10,-32, 10, 11,  3, -1,  3, -5,  5,  2, 14, -6,  3,  1,  5,-15,
+   -11,  6, 20,  4,  0,-12, -7,  3,  1, -1, 10,  6, -1, -9, -4, -1 },
+  {  1,-25,-14, 12,-11,  9,  9,-16,-24,-17, 22, -9, 11,-30, -3, -4,
+     6, -7,  9,  2, -1, -5, -6,  2, -1, -1, 10,  1, -3,  3,  4,  8 },
+  {-14,-26, -6,  9,  8, 17,-11,-24, -7, -4, -8, -2, 10,  2,  2, -1,
+     2, 13, 12, -7,  4, -6,-10,  6,  6,-13,-11, -7,-16,  0, -2,  5 },
+  { -4,-30,-13, 12, 16, -6, 12,-16,-13,  5, 15, -2, -2,-10, -7,  7,
+    11, -1, -4, -2, -4,  7,  4, -8,  1,  3,  0, 11,  3, -2, -5,  4 },
+  { -4,-21, 20, 22,  2, 20, -8,  1,-12, -5, -9,  4,-10,-17, -3, -8,
+    -3,  3,-12,  1, -3,  0,  7,  4,  7,  7, -3,  7,  5,  3,  1, -5 },
+  {-12,-20,  2, 29, 11, -6,  9, -7, -6, -4,  0,  6, 17,-13, -2,-10,
+   -17, -1,-18,  2,  0, 14, -6,  1,  0,  3,  2,-10,  1, -5, -2,  5 },
+  { 16,-37, -1, 26, -2,-14,  1, -5,-14,  2,  2,  3,  6,  1,  1,  4,
+     0, -1,  0, -2, -2,  4,  9, -6,  0, -2, 10, -7, -2,  4,  1,  0 },
+  { -9,-24,-12,  5,  5,  3,-17,-14,  4,  3,  2, -4, 10,-22, -8, -3,
+     6,  1, 12, -8,  4,  1,  9, -1, 18, -3,  6,  5,  3, -5,  9, -5 },
+  {-14,-33, -2, 20,-13,-10,  2, -7, -1, 11, -9, -8, 18, -3,  1,  8,
+     0, -2, 10,  7, -2,-13,  9, -3, -4,  5, -2, -2, -1, -5,  1, -7 },
+  {-10,-23,  8, 14,  1,  7,  1, -3, -7,  4,  1,  1,  8, -7, 15,-14,
+    13, 14,  2,  5,-13, -5, -8, -1,  6,  3,  6,  9,  6, 15, 14,  5 },
+  {-13,-25,-10, 13,-17,-24, -7,-13, -6,-10, -8,  2,  0,-13,-10, -4,
+    -8,  4, -9,  9, -4,  4, -3, -3,  3,  3, -5, -9,  1, -2, 11,  2 },
+  {-12,-23,  1, 18,-11, -2,  5,  9, -5,  5, 14, -9, -3, -2, -6,  2,
+    -2, 11,-13,  1, -3, 11, -9, -4, -2, -6,  8, 10,  1,  4,  2,  1 },
+  { -5,-18, 16, 22,  2,  0,  8, -6, -9, -7, 10,-16, 23, 10,-11, -1,
+     7,  2,  7,  2,  1, -5,  6,  1,  0, -4,  9,  2, -3,  1,  0, -4 },
+  { -3,-26, 14, 11,  2, -9, 17, -2, -1, -5,-16, -9, -5, 10,-13,  1,
+     6, 12, 10, 11,  0,  0, -3,-14,  6, -2,  0,  4, -5, -1, -7, -1 },
+  {-10,-33,  1,  8, 11, -5,  1, -6,  7,  4,  5,  6,  1, -2,-10, -5,
+    -6, 12,-11,  5,-10,  4, 12, -1, -1, -3,  4, -1,  9,  0, 16,-17 },
+  {-14,-37,  7,  7, -2,  5, -8,-11,  2,-13,  4,-19,  1,  8,  8,  4,
+    -9,  2, -4,  3, 12,  2,  4, -4, -8,  8,  1,  4,  8, -1,  6, -2 },
+  { -6,-30, 18, 17,  1,-22, -3,  4, -7,-10,  7,  0, -8,  8, -1,  4,
+     2,  8,  6, -2,  2,  7,  4,  4,  3, -6,  2,  1, -3,  1, -1, -5 },
+  {-17,-18, -3, 22, -8,  1,  9, -2,-17, 20, -5, -5,-12, -5,  4, -5,
+    -9,  8, -2, 16, -3,  0, 19, -8,  8,  1,  2, -4,  0, 11,  0, -3 },
+  { -9,-23,  3, 10,  4,  4, -3, -2, -2, -2,  1,-22, 11,  0, -2,  5,
+    -2, 14, -9,-11, -4,  7,  5, 32,  1, -3, -7,  0, 21, -9,  7, -6 },
+  {  0,  0,  0,  2, -1,  1,  0,  1,  3,  0,  0,  1,  0,  1,  0,  1,
+    -3,  0, -1, -2,  0, -1, -1, -3, -1,  1, -4,  1, -1, -5,-69,-19 },
+  { -3, -5, -8,-12,  4, -3,-19,-11, -5,  0,-14,  7, 18, -6,  7, 22,
+     8, 14, 15, 10,  3, -1, -3,  5, -1,  7, -7,  1, -6,  3,-26,-11 },
+  { -1, -6,  4, -4, -5,-16,  0, -6, -3, 11,  1,  0,  9,  5, 16,  3,
+    -4,-33, -4,  4, -7,  0,  1,  6,-11, -2,-13, -2,-18, 20,-25,-16 },
+  {  4,  0, -1,  0, -5,  1,  0,  2,  0, 11,-10,  4,-10,  7, 16,  2,
+    16, 15,  2, -1,  2,  9,  2,  8, -3, -5, -2,  0, -3,  0,-33, -2 },
+  { -3,-15, 10, 10, -9, -1,  7,  3,  5, -5, -8, -8, -3, 15, -9,  4,
+    12, 13,-13,-14, 10, -6,  9, 22,-27, 23, -1,  5,-24,  2,-30,  5 },
+  {  0, -2,  7, -5, -5,  3,  5,  3, -3, -5,  2,  1, -4,  3, -3, -1,
+     1, -2, 10, 22, -3, -4, -2, -2, -7,  3,  8,  1, 14,  4,-37,  9 },
+  { -3, -4, -1,  1, -4,  0,  6,  2,  6, -7,-10,-10, -1, -4, 11, -3,
+     7, -6,  4,-12, -1,  5,  1, -7, 10, -6, 17, -4,  8,  3,-40, 13 },
+  {  2, 12,  4, -7, 14, -3, 16, -2, 18,  2, 13,  5,  5,  1, 11, -1,
+     0,  9,  2, -6, -1,  2, -6,  2, -5,  3,  5,  1, -1,  1,-32, -7 },
+  {-16, 11,  7, -4,  2, -5, -9,  9, 11, 11, 15,-13,-11, 11,  9,  4,
+     3, -8,-10, 12, 12,  0,  0,-16, -9, 13,  2,  9,  4,-13,-33,  3 },
+  {  6,  4,  5,  4,  3, -1,  5,  6,  4,  2,-11, -1,-15,-11, -1,  1,
+    11, -3, -2, 24, -4, -6,-25,-10,-15, -8,  0,  0, -5,  4,-30,  2 },
+  { 10, -3, -6,  1, -9, -5,  6,  9,-10, -3,  8, -1,  4, -1, 11,-11,
+     3,  9, 11, -3,  6,-17,  5, -8,-33,  9,-13, 19, -2,  9,-25,  2 },
+  {  0,  0, -1, -3,  0, -2,  1,  0,  0,  2,  1,  0, -2,  0, -1,  2,
+     0, -1,  4, -1,  2, -3,  4, -2,  3,  3,  1,  0,-15, 12,-63, 27 },
+  { -2, 14,  9, -1,  3,  0,  1,  1,-19, 15,  3,  4,  0,-10,  1, -5,
+     3,  0, -5,-10,  2,-16, -4,  8,-12, -6,  7, -5,-10, -1,-33, -4 },
+  {  0,  3,  1,  3,  1,  2,  4,  4,  9, -6, -8, -5,  1,-12,  3,  8,
+   -10,  6, -1,  1, 13, -5, -5,  2, -4, 13,-18,-10, -7, -9,-33, 10 },
+  { -6, -3,-12,  5, -1, 11, -6,  0, -2,  1,  2, -7,  3,  1,  3, -2,
+     1,  8,-10,  7, -1, -3,  3,  0, 13,  1,  6,  7,-16, -7,-39,  8 },
+  { -6, -1, 11,  6, -3,  8,  3, -5,  3,  0, -5, -2, -6, -3, -4,  2,
+    -3, 13,-11,  1,  7,  5, 19, -5, -3,-15, -1,  7, -1,  6,-33,  8 },
+  { -7,  3, -4, -3, -4,  1,  6, -5, -5,  6, -8, -1, -7,  4, -1, -6,
+    -2,  1,  7,  0,  1,  1, -5,  2, -2,  0,-13, -2,-31,-14,-39,-12 },
+  {-10,  9,  0, -3,  1, -1, -1,  0,  1, -5, -1, -4, -2,  5,  2, -7,
+    18, -8, -2,-19, -7, -7,-12,-14,-11, -1, -9,-13, -7,-12,-31, -9 },
+  { -3,-16, 10,  9,  1,-10,-12,  2, -2,  2,  7, -3, -3,  1, -4, -5,
+    -9,  5,  7,  3, -1,  4,-11, -8,  4, 13,-10, 13, 10, -4,-36,  1 },
+  { -7,-12,  4,-20, -7, -7,  2, 11, -1, -2,  3,-12,  1,  0, -6, -7,
+     6,  4, 13,  3, -3,  4,  3, -6,-12,  5, -5,-22,-13, -8,-37, -6 },
+  { -7,  5,  3,  5,  7,  9,-14, -3, 10, 17, -1,  1,-12,  5, -6,  0,
+    -4, -9,  0,-11,-14,  3, 13,  6,-25, -8,-12,  4,-10, 18,-30, -1 },
+  {-10,  6,-10,  6,  6,  1,-10,  0, -7,  5, -2, 17,-18, -4,  0, -3,
+   -16, -6, -3, -8,  5,  1, -4,  6, -7, 16,  6, 10, -1,  0,-32,-11 },
+  { -1,  9,  9, -5,  4,  9,  6,  9, -4, -2,  7, 11,  4,  2, -5, -4,
+    -6,  0,  2, -3, -1,  5, 10,  0, 12,-10,-18, -3, -1, 14,-33,  2 },
+  {  4, -8,-18, -4, -5,-11,  4,-10, -4,  9, 13,-12,  1, -6,  1,  2,
+     4, -9,  8,  3, -6, 21, 13, -1, -2,  1, -2,  6, -7,  0,-30,  1 },
+  {  6, -1,  2, -3, -1, -4,  6, -4,  0,  4,  2,  2, -9,  2,  6,  3,
+    -2,  4, -1,  9, -6,  0,  7, -8,  5, 19, -2,  9, -5,  2,-33, -8 },
+  {  2,  1, 12, -5, -8,  8,  3, -2, -4,  1, -2,  5, -4, -9, -8, -8,
+     7,-11, -4,  6,-10,  7, -1, -1, -2, -1, 16, 32, -7, 20,-33, -6 },
+  {-18,  2,  6, 13,  9,  9, -1,  3,-17, 24, -2, -6, 28,  8, -2,  6,
+     3,-10,-34,-16,-13, -4,-15,-11,-12, -3,-10,  4, -8,  4,-31, -4 },
+  {-11,  0, 18,  2,-16, -9,-13, -2, -2,-12, -3,-22, 30,  0,  8,  3,
+     9, -4,-16,  1,  0,-11, 15, -2, -4,  6, -5,  6,  1,  2,-25,-12 },
+  { 14, -1,  5,  7,  3,-15, -8,  1,  5, -2, 12, 13, 11,-25,  3,  1,
+     0, -2, -4,-16,-23,  0, -5,-17,  7,  5, -9,  6, -5,  2,-32, -7 },
+  {  3, -1,  6, 14,  2,-12, -9, -9,  4,  7,  4,  6,  5, -8,  4,  2,
+     4,  5, -2,  8,  8, -6,  0, 10,-20, -1,  3, -1,  8, 23,-33, -5 },
+  { -3, 11, -6,  3, -4,  5,  7,  3,  4,  5, -2,  3, -1, 30,  6,  1,
+     8, -6,  0,  0, -9,  6, -9,  4,  2,  9, -6,  1,-12,  0,-34, 18 },
+  {-17, 13,  0,  1,  9, -4,-11,  0,  7,  0,-10, -4, -1,  6, -6,  4,
+     1,  6, -9,  3, -5, -6,-11,  2, -4, 14, 23, -3,  2,  5,-30, 12 },
+  {-14,  5,-27,  2,  0,  7,  1,  4, 30,  8,  7,  5,  1, -1,  0,  5,
+     8,-10, 48,-11, 12, 33,  6,  8,-15, 20, -2, -5, 32,  5,-19, 10 },
+  {-16, -4,-12, -7, -2,  0,  8, -6,-20,-18, 16, -3,  0, 31, -2, 11,
+     2, -9, 49,-19,-12,-23, 10, 26, 16, -2,  4,-21,-14, 13,-11, -9 },
+  { -5, -9, -1,  3, -5,-21,  2, 10,  0,  0, 10,-21, -7,  7,-26, -9,
+    22, 32, 58, 11, -3, 11, -5, -8,-13,  6, -5, -9,  1, 10, 14, -8 },
+  {  7,  7, 10,  3, -2, -1,-11,-11, -6,-43, -3, 14,-19,-18, 19, 18,
+   -32, 10, 45, -6,  6, 21,-20,-12,  2,  4,  6,  6, -4,  3,  3,  1 },
+  { 21, 22, -3, -2,-11, -6, -1, -2,  8,  8, 32,-21,  7, 28, -4, -6,
+    -3, -2, 50,  2,  2, 27, -5, -8, 12,  7, -5, -1, -4,-17, 27,  6 },
+  { 13,  7,  2, -6,-12,  2,-10, -5,-17, 11,  4, 17,-12, -2,  5,-17,
+    37,-16, 48,-14,-18, 29,  8, 24, 11, -5, -9, 11, -1,  1,-13, -3 },
+  {  1,  1, -1,  2,  0,  0,  0, -1,  1, -1,  7,  2, -3,  3,  0,  6,
+     2, 10, 54,-25,  7, 54, -5, -6, -1,-15,  9, 13,-24,-15,-12,  3 },
+  { 21,  5,  8,  3, -3, -4, -2, -4,  3,-11, -5, -8,  9, 16,  8, -9,
+   -10, -3, 46,-46,  2,  1,-10, 10, 17, 11,-20,-36, 10, 14,  0, -5 },
+  {  7,-13, -6, -9,-24, 45,  2,  8,  8,  0, 17, 20, 12,-24,  1, -7,
+   -15, -3, 46,-13, -2, 20,  1,-13,-11,-13,  2, 15,  1, 10, -1,  3 },
+  {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -1,  0, -2, -1,
+   -16, -9, 31,-69,-34, 26,  7, 17, -1, -6, -1,  0,  0,  0,  0,  0 },
+  {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -4,
+    -5,-20, 18,-82, 22,  3, -7,  9,  4,  6,  2, -4, -1,  0, -2,  2 },
+  {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  4, -1,
+    15, -5, 62,-36,  4, 52, -7,  5,  0,  6,  1,  2,  1,  1, -1,  0 },
+  {  3,-19, 19,-20, 13, -4,-11,  8,  8,-16, 10,  1,-14, 30,  1,-33,
+    10,-11, 45,-30,  3, -4, -3,-13,  7, 12,  3,-22,  3, -2, -4, -2 },
+  { -1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  0,  2,  1,
+    11,  8, 70, 48,-10, 21,  4,  9, -9, -9, -4, -6,  0, -1,  0,  0 },
+  {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  2,  0,
+     2, -1, 80,  2,-15,-36,-10, -5, -2,  8, -2,  2,  0,  0,  0,  0 },
+  { 10,  8, -8, -8,-24, 12, -1,  0, 20,  9, -1, -2,  2, -2, 12,-10,
+    -2,-13, 35,-43, 44, 15,-10,-25,  4, 10, -3, -5, -5,  7, -1,  3 },
+  {  1,  1,  1,  1,  0,  0,  1,  0,  0,  0,  0,  0,  0,  0, -2, -1,
+   -18,  9, 49,-72,  7, -8,  7, -5,  2,  3,  2, -2,  1, -2, -3,  1 },
+  { -1,  4, -3, 10, 19,  4,  3, 20,  6,-24,  6,  9,  8, 15, 18, 18,
+   -36, 19, 57,-11,  4, -3,  8,  7,  2, -3, -2, -9,-15, -2, 12, -4 },
+  { 20,  3, 11, -9, -4, 22, 42,-25,  1,  5,-10,-19,  0,  9,-16,  5,
+     2, 10, 44,-29, 17, -3, -9, -2, -1,  8, 14, -7, -1, 16, -5,  1 },
+  { -7, 16,-11, 12,  6, 33,-15, 14,-23,  2,-26,  8,  2, 10,  0, -5,
+     8, -8, 38,-38, -4,  5,  5,  5,  1, 22,-15,  7,  6,  0,  4, 28 },
+  { -1,-12,  2, 10, -2,  0,  7, 17, 12, 22, -4, 10, 25, 29,  5, 18,
+     4,  1, 27,-39, 31, 17,  2,  2, 22,-23, 13, 16,  1, -7, -4, -5 },
+  {  0,  1,  0,  0,  0,  0,  0,  0,  0,  0, -1,  0, -2,  0,-14,  0,
+    -7,-11, 49,-22, -4, 19, 17,-39,  4,-29, 10,  2, 36, -4, 23, -1 },
+  { -2, -2, -2, -2,  1, 15, -5, -7,-16, -8,-19, 16, -3,-20, 36, -9,
+    -3, 20, 39,-20,  0,  2, 27,-16, 10, 10,-14,-22,-16, -3, 13, -8 },
+  {  5, -9,  6,-25,  7, 37, 13,-10, -5,  3, -5,  7, 18,-22, -7,  9,
+    -5, -4, 50,-11, -4, -5, -5,  8, -4, -2, -4,-27, 14, 20,  7, -9 },
+  {  0,-14,-10,-27,-14,-17, -6, 26, 10,  2, 14,-12, -5,  0,  8,  9,
+     0,-28, 55, -7,-12, -7,  4,-10, 10,  7,-12, 11,  3,  5,  9, -8 },
+  {  2, 23,  4, -2, -1,-20, -2, 14, 10, -9, -9,-24, 10,  0, 11,-12,
+    12, 11, 49,-25, -2, 29,  7,-13, 21,-10, 11,-17,  3,  1, -8,  5 },
+  {  3,  0,-14, -6, 18, -2, 17, -9,-19,  9, -5,  9, 14,  6, 19, -3,
+    27,  1, 41,-21, 20,-15, 33,  0, 26, 14,  7, 10,  3, 20, -3,-12 },
+  { -1, 16, 15, -8,  3, -8, -8, 21, -5,-16,-29,  4,  1, -6, -4,-28,
+     2, 31, 37,-26, -2, 13, 24,  8, -9, -6,-29, 10,  7,  2,  7,  8 },
+  {-10,-10, 11, 13,-32,  2, 16,  9, 14, 23,-15,-13, 24, 13,  4,-27,
+    14, 12, 31,-18, 17, 23, -2, -7,-14,  9,-17, -6,-10, 20,  9,  6 },
+  {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  2,  0,
+     5,  1, 89,  8, 10, -6,  2, -1,  0,  0,  0,  0,  0,  0,  0,  0 },
+  {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  2, -1,
+     4, -7, 64,-50,  7, 37,  2,  5,  0,  0,  0,  0,  0,  0,  0,  0 },
+  { -2,  5,  3, -4, -4, -3,  2, -3,  3, -3,  5,  4,  1, -6, -1,  1,
+     6, -2, 50,-35, -7, 43,  7, -7, -5,-26, 24, 21,  3,-15,  5,  6 },
+  { -8, 21,-19, 33, -8, 22,-11, 17,  3,  0,  0, -2,  1, -3,  6, -1,
+    10, -8,  4,-11, -4, -5,  0,  8, -4,  3,  1, -4,  4,  2,  8,  4 },
+  { -7,  5,-20,  9,-22,  3,-14,  1,  6, 13, 23, -2, -4, -7,  2,  0,
+    11,  4,  6,  3, -7,-11, -7,  4,  5,  5,-12,  8,  2,  4,  7, -3 },
+  { -7,  6, -4, 20,-20, 16, -2,  7,  6, 16, 11, 12, -7, -7,  5,  3,
+    -9, -4,  1,  2,  5,  2,  1, -9, -2,-17, -4,  6,-10,  7, -7, -6 },
+  { -9, 18,-17, 12,-24,  1, -1,  4, 14,  9,  4,  3,  2,  8,-12,-14,
+     4, -8, -4,  7,  7,  6, -1, 13, -9, -4, -1,  1,  0, -4, 15,  8 },
+  {-25,  2,-11,  6, -5, 24,-28, -5,  8, 12, -2,  6,  8, -3,  8, -9,
+    -1, -5, -1, -5,  6, -1, -1, -1, -4,  8,-12, -2,-13,  7,  2,  1 },
+  {-14, 14,-18, 20,-10, 12, -2,  9,  1,  0, 12, -2, 15,-10, 26,-17,
+    16,-11, 10,-10,  9, -2,  4, -8,  2, -3,  4,  4,  2, -3, -5,  1 },
+  {-18, 12,-18, 21, -6, 12, -6, 13,-25, 18,  1, 11, -9, -5,  0, 10,
+    -5,  3, -3,  8, -9,  7,  4,  2, -9,  0,  5,  0,  2, -3,  9, -8 },
+  { -4, 16,  1, 18,-30,  9,  1,  6, -8, 13, 13,-12, -6, -1, 13,  7,
+     6,  2,-15, -3,  5,  5,  1, -6,  1, -5,  0,  2,-16,  0,  3, -4 },
+  {-21,  1, -2,  6,-43, 18, -1,  5, -1,  4,  6, -2, -1, -3, -1, -3,
+     0,  1,  2, -9,  0, -1,  0, -2,  0, -1, -1, -2,  6,  0,  1, -2 },
+  {-23, 10,  4,  7,-32,-11,-18,  2, -2, -7, -6, -3, -3,-12, 19,  3,
+    -5, -6, 16, -6, 16,  2, 16, 16,  8, -2, 13,  8,-15,-11,  2, 10 },
+  { -8,  2,-13,  2,-29, 24,-20, 19,  1, 10, -4, 10,  1,  2, -9, 11,
+    -1, -2,  9, -5, 19, -7, 16, -9, -2,-18, 11,  1,  1,  0,  7, -3 },
+  { -6,  3,  4, 13,-26, 10,-10, 28, -7, 28,  1,  7,  0,-14,  5,  7,
+     4, -4,  3, -2,  3,  3,-11,  7,  6,  4,  0, -1,  2, -1, -3,  2 },
+  { -6, 16,-31, 13,-10, 17, -6,  4,-14,  4,  4, -1,-10, 12, -5,  1,
+   -14, 15,  0, -8,  1, -5,  3,  3,  9, -5,  7,-20,  7,  4, 11, -5 },
+  {-19,  3,-17, 14,-12, 16,-22, 18, 14,  8, -2,  4, 10, 12,-14,  4,
+    -3,  2,  3,  7, -7,  7, -6,  2, -2, -4, -5,  0, -5, -2,  2,  1 },
+  { -9, -7,-11, 24,-36, -9,-11,  5,  7,-12,-13, 18, -2, 20,  1, -4,
+    -1,-10, 15, -6, 14,  1,  0,  2,  1,  2, -9,-16,-11,  7, 13,  0 },
+  {-24, 24,-18, 18,-22, 14,-11, 13,-12, 11,-10, 11, -7, 11, -5, -4,
+    -1,  1,  5,  2,  3, -1,  1, -5,  7, -4,  5, -6,  8, -7,  8, -6 },
+  { -6, 18,-22, 22,  5, 11, -1,  6, 19, 22,  8,  4, -8, 20, -2, 15,
+    -6,-18,  0,-33, -9,-12, -1,  6,  5,  2,  5,  5, -5,-17, -3, -3 },
+  {  1, 11,-16,  9,-18, 11, -4, 18, 20, 26,-10,  8,  1,-11,  8, -4,
+     0,  7,  3,  5,  2,  2, 10, -2, -4,  4, -4, -2,  1, -4, -5, -1 },
+  {-10,  6, -1, 18,-17, 27, -3, 10, -2, 12, -7, -9,  1,  1, -1,  7,
+   -12, -1, -7, -6, -1,  8,  3,-15,  8,  9,  3, -7,  4, -1,  1, -1 },
+  {-14,  6,-16, 22,  2,  5,  0,  5,-18, 11,  6, -3, 22,-20, -9, -3,
+     6, -6, -7,-15,  1, 15, -8, 11,  8, -3, -8,  1, -8,  2,  6, -2 },
+  {-21,  5,-19, 19, -7,  4, -7,  0, -8,  6, 12,  5, -3,-22,-13, -6,
+    -1, -3, -2,-14,  6, -3,  1, -8, -7, -5, -6, 11, -3,-10, -5,  2 },
+  { -1,  9,-12, 15, -6,  6,-19, 14, -9, 11,  3, 12,-17, -3,  8, -4,
+    -3, -4,  1, -5,  4,  5, -7,-15, -7, 15, -6, -5,  1, -5, -3,  1 },
+  {-12, 20,-15, 20,-14,  3,-14,  9, -6, 33,-13,  6, -2,  8, -6,  7,
+    -5, -6, -3, -3,  0,  8, -3, -3,  1, -2,  2,  2,  6, -5, -5, -2 },
+  { -7, 12,-18, 12,-18, 10, -4,  8,  2,  4,  8,  9,  0,  3, -8,  3,
+     6,-12, -4,  1, 25, -5, -9,  6, -7,  0, -9, -7,  3, -5, -4, -4 },
+  {-18, 12,-10, 11,-22,  0,-15,  5, -2,  2, -3,  6, -4, -4, -3,-15,
+    -2, -3, 21,  6,-12,-11, 19,  3,  3,-14,  7,  0,-11,-22,-10,  0 },
+  {-15,  2,-30, 15,-17, 13,-16,  8, -7, 10, -8,  2, 11,  3, 10, -7,
+     7,-22, 12,-10,  3,-12,  6,-10, 12,-10,  7, -8,  5,  2,  9,  1 },
+  { -9, 11,-14,  6,-10, 21,  5, 12, -5,  5,  7, 21,  6,  2, -2, -1,
+    -1,  4,  2,-20,-18, -1,-14,  3, -1,  4, -7, 10,  1, 11,  4, -4 },
+  {-22,  8,-30, 13,-21, -4,  4, -1, 12,  9, -2, -3,  2, -6,  4,-13,
+    -2,  8,  8,  1, -7,  3, -4, -5, -1, -7, -2,  8,  8,  7,  8,  0 },
+  { -6, -4,-35, 16,-13, 15,-11, 14, -7,  9, -1, 11,  7,  0, 13, 10,
+    -1,  8,  1,  1, -2,  8, -1,  2,  2,  3,-10, -1,  7,-13, -3, -7 },
+  {-15,  7,-16, 14,-18, 17, -6, 14,  3,  4,  7, -3, 10,-22,  5,-15,
+     4, -4,-11, 15,-15, 11,-11, 20,  1,  0,  2,  1, 11, -3, 11, -7 },
+  {-12,  3,  5, 16,-37, -1, 15, 15,-15, 10,  3,-10,  1, 15,  7,-15,
+   -13,  8,  9, -3,  2, 12, -8,  2, -5,  0, -3,  4,  5, -9, -4,  5 },
+  {-16, 26, -4, 14,-22, 26,  6, -3, -8,  4, 21,  6, 16, -4,-11,  7,
+   -10,  3,  3,  7, -4,  2, -9,  8, -2,  2,  5, -2, -4, -2,  7, -1 },
+  { -7,-10,  4,  3,  2, -4,-12,-10, -4, -5, 16, 19,-16,  1,  2, -9,
+   -10,  0,  9,  7, -8,  3, 12,  8, -6,-11,-13, -1, -3,-20,  6, -5 },
+  {-14,-17,  3, -5, 14,-12,-12,  8, -6,-25, 21, 21, 10, -8,-12,  4,
+    10, -4,  3, -9, 11,  9,  0,  4,  2,-15,  1,-14,  4,  1,  0, -4 },
+  { -4, -9, -3, -1,  6,  3, -6,  6,-10, -4, 14,  8,  2, -3,-12,-19,
+     0, 11,-20,  1,  6, -2,-27, -6, 10,-17,-14,-17, -9,  8, -8,  3 },
+  {-12,-13, 16, -4, -2, 12, -7,-11,  2,-13,  3,  7,-16,-18, -1,-12,
+    -2,  1,-12, -9, -2, -6,  2,  9,-22, -3, -4,-14, -7,  7, -1,  2 },
+  { -7, -8, -8, 15, 15, 18, 15, 16, -4,-37, 11, 15,-12, -1, -3,  3,
+     6,  6,  0, -5, -3, -5,  9,  1,  1,-11, -1, -8, -6,  2,  3,  0 },
+  { -6,  7, -5,-12, 13, 10,-18, -4, -3,-21,  6, 16,-15, -7,-12, -9,
+     1,-12, -1, 10, -2, -1, -3,  4, -4,  1,-16, -1, 12, -9,  5,  9 },
+  {-14, -5,  9,  3,  4, 26,-28,  3, -6,-24,  4,  5,  3, 13,  5, -1,
+     3, -1,  3,  1,  1, -5,  3,  0, -7, -8, -7, -3,  3, -5,  4,  0 },
+  { -4,  2,-10, -6, 25, 26, -6, 10, -6, -8, 15, 11, -6, -3,  2, -7,
+     5, 14,  9, -1,  0,-12,  4, -4,-10,  1, -3,  3, -2, -2, -6, -1 },
+  {-10,  8,-15,-10, 19, 17, -8,  0, -3, -7,  7,  5,-13, -1,  7, -7,
+     1, 13,-12,-13, 17,-12,  1, 26,-18, -3, -5, -6,  4,  5,  8,  1 },
+  {  2, -5,  3,  0,  0,  0,  2, -3, -2, -5,  7, 13, -4,  9,  0, -5,
+     4, -1,-11, -8, -4,  0,-13,  2,-47,-23, -8,-11, -4,  4, -2, -3 },
+  {-18, -4,  4,  5, -1, 17,-12, -8,  1,-12,  7, 20,-12,  3, -2,-11,
+    16, 12, -6,  1,-13,-16, -6, -3, -3, -5,  4,-12, -5, -9, 10,  1 },
+  {-11,  0,  4,  7,  7,  8,  3, -1,  3,-19, 32,  8,-19, -8,  2,  4,
+   -12, 15,-16,  3,  1,  9, -2,  1, -2,  8,  5,  6, -4, -1, 11, -8 },
+  {  3, -1,  4, -2, 14, 32, -9,-23,-10,-12, 22, 15, -1, -2, 10,  0,
+     4,  6, -8,  4,-15, -2, -1, -4,  0, -8,  4,  1, -8,  3,  4,  1 },
+  {-17,-12,  6, -8, 16, 13,-20, -8, -1,-16, 10, 21,-19, 11, -9, -5,
+     7, 18, -6,  7, -7,-18, 13,  2, -2,  8,-12, -9,  2,  4, -5, 16 },
+  {  4,  0, 17,-11, 12,  7,-12,  5, -1,-25, 30, -8, -7, -6, -4, -7,
+     9,  8,  7,  3,  3,-16,  8,  0, -2, -2,-18, -3, -4, -5,  1,  4 },
+  { -3, -6,  6,-16, 17,  6, -3,  2, -9,-17, 12, 11, 11,  2,-20,  8,
+     1,  1,  0,  2, -2, -6,-21,-13, -9,-15, -1, -8, -6, -8,  0, -2 },
+  {-11, -7,  6, -9,  3,  6,  8, 16,  4, -5, 23, 26,-10, -3,  4,  0,
+     2,  2, -4,  4, -2,-12, 12, 10,-11,  0,-10,-16,  3,  0,  0,-10 },
+  { -5,-16, 10, -6, 27, 13, -3,  4, -2,-13, 15,  5,  2,  5,  3, -4,
+    13, 12,-11, -7,  0,  1, 11, 12,  2, 13,-15, -8,  9, -2,  3,  8 },
+  { -5, -8,  4,  3,  9,  3,-11, 10, 14,-25, 14,  8, -2,  5,-12,-21,
+     2, 10, -7,  2, -3,  2,  0,  2, -1, -3, -5, -6, -1,-16,  2,  8 },
+  { -1,  5,  1,-11,  5,  9, -7,  8,-13,-12,  4, 12, -4,  1, -1, -1,
+    27, 29, 10, 15,  2, -6, -3,  4,-21, 10, -9,-11, -6, -1, -9, -3 },
+  { -6, -3, -1, -6, 11, -5,  0, -2, -5,-31, 11,  3, -1,  5, -3,  4,
+     5,  7,-10,  5,-10,-13,  4, 12,-15, -2,  2, -7,  1, -9, -3,-10 },
+  { -3, -7, 17, -8, -5, 36,  8, -7, -8,-20, 12,  8,  1, -1,  3,  0,
+     1,  4,-10,  3,  1,  4, -2, -3, -2, -3,-10,  4, -1, -7,  3,  2 },
+  {-13, -3, -5,  9, 22,  6,-23,  3,-10, -7, 17, 17, 18,-14, -8, -8,
+     2,  4, -8,  2, -3, -8,  6,  4, -1,  7,  0,  0, -3,  0,-12, -3 },
+  { -3,-10,-15, -3,  9,  3,-23, -9,-13,-18, 12, 13, -2,  0,  1,  8,
+    -1,  2, -7,-12, -5, 14,  2,  1,-22,  6,-10, -8, -9, 28, -7,-14 },
+  { -3,  1,  2, -1, 13,  7, -2, -7,  1, -3,  6,  9, -3, -2,  4, -2,
+     2,  1,-10, -2, -2,-22, -2, -7,-10, -5,-11,-27,-12,-16,  4, -7 },
+  {  2, -6, -3,  1,  8,  0, -2, 12, -3, -4, 58, 15,-10, -4, -2,  2,
+    -2,  0, -2, -6,  2,  4, -1,  1, -4,  1, -1, -5, -4, -3,  3,  1 },
+  { 10, -1,  0,  5, 21,  7,-14,  6, -3,-16, 15, 17,-16, 13,  3, -6,
+    -4,  6,-12, -5,  1, -4, -7, -8,  2,  3, -6,  6, -1, -8,  5,  4 },
+  { -6, -2, -8,-11, 15, 10,  0,  8, -6,-15, 33,  8, -2, 18,-15,-11,
+     5, -1,  0, 15,-15, -4, -4, -1, 10,  7,-13,  4, -4,  0,  8,  3 },
+  { -7, -2,  0, -2,  0, -2, -4, -5,-14,-16, 12, 38,  7, 12,  6, -4,
+     0, -1,  0,  3, -2, -6,  0,  2, -9,  1,  0, -1,  0, -2,  4,  1 },
+  { -8, -4, 18,  1, 14,  5,-12, -3, 20,-17,  5, 19,-11, -8, 11, -3,
+     3,  9, -7, -8,  9,-17,  2, 15,-10,-11,  5, -5,  7, 15, -6, -2 },
+  { -7,  2, 38,  5, 19, 16, -5,  4,-13,-20,  0,  4, -4,  6,  4,  2,
+    -7,  6, -8, -2, -5, -7,  6,  3, -4, -3, -2, -3,  7, -6, -4,  0 },
+  {-11,-12,  8,-15, -3, 14, -7,-22,-11,  2, 22, 14,-19,  2,-19, -6,
+     1,  3,-18, 14,  2, -6, -2, -8, -3, -6,  5, -7, -8, -4,  1,  1 },
+  {  8,  7, 25,-21, 12, -6, -5, -4,-10,  6,  0, 10,  1,-12, 18, -5,
+   -15,  4,  1, 14, -1,  5,  8, -7,  1, -7, -3,  9, 10,  1, -1,  0 },
+  {  9, 10, 32,-15,  8,  2, 11, -7,-18, -8,  2, -6, -9,-16, -3,  3,
+    -1,  3,  1, -5,  4, -2,  1, -8,  0, -6, -3,-11,  1,  5,  0,  0 },
+  { 14,  0, 23,-25, 22,  3,  7, 10,  0, -2,  7,  8,  0, 10,  0,  0,
+     3,  2,  3,-10,  0, 10,  0, -7,  0, 10, -1, -5, -7,  1, -1,  2 },
+  { 12,  0, 25,-18, -5, -4, 13,-10,  3, -6,  7, 21,  0,-16,  3,-10,
+    -6,  5, -7, -3,  2,  5,  3, -6,  4,  9, -8, 12, -2,  3,  2,  4 },
+  { 31, 15, 27,-20, 10, -7, 15,-10,  9, -8,  4, -5,  3, -3,  5,  6,
+    11, -2,-12, -2,  6, -2,  1,  2, -1, -1,  1,  1,  3,  1,  1,  2 },
+  { 12, -4, 13,-23, 12, -6,  2,  4, -3, 13,  6, -7,  5,-19, -7, 18,
+     1, -7,  7,  1, 16, -7,  3,  0,  3,  0,-12,  8,-11,  9,  4,  7 },
+  { 29,  1,  3,-22, -5,  6,  0, 12,-14, 11,  1,  6, -3,  4,  6, -2,
+     4,-13, 12,  1,  1,  3,-11,  9,-10, -1, -7, 16,-11, -1,  3,  9 },
+  {  4,  4, 36,-23, -5, -8,-15,  1, -6,  3, 13, -1, -5, -7,  4,  9,
+     2,-11, -3,  5,  1,  3, -6, -1, -4, -4, -2,  2,  3, -1, -5, -2 },
+  { 19, 10,  6,-17,  2, -4, -2, -4, -3, 13,  2,  2,-13, -7, -3,-11,
+     9, -6,  1, -9, -5,  4, -5, -9,-18, -7,-11,  9,  4,-11,  8,  4 },
+  { 16, -3,  9,-16, 18, -2,-12,-16,-11, 11,-18, 16,-13,  6,  2,  8,
+     3,  8, -4,-16, 10,-11, -1, -3, -8,  5, -9, -4,  9, -4,  0, -3 },
+  { 14, 15,  3,-23, -5,  7, -8, -6,  2, 17,  2, 12, -8,-12, 13, -1,
+    -9,  3,  1,  1, 19, 15,  4, -1,  1,  2, -3,  2, -3,  1,  5,  3 },
+  { 32,  5,-10,-47, -5, -1,  4, 11, -7,  0,  2, -2,  1, -7,  6, -4,
+     6,  2, -4, -2,  2, -2,  0, -4,  1, -6, -5,  2, -2, -1, -3, -4 },
+  { 20,  8, 10,-21, -7, -9,-16, 12,  1,  4,  6, -5,  9,-11, -7,  4,
+   -11, 28, -3,  2,  4, -6, 10, -8, -5, -5, -9,  9, -2, -1,  6, -5 },
+  { 38,  3, 23,-25, -6,-18,  3,-10, -8,  6,-10,  1,-10,  2,  2,  0,
+    -7,  2, -4,  5, -1,  8, -3,  0,  3,  3, -1,  1,  0, -4, -4,  0 },
+  { 20,  5, 16,-22, 24,-18,  2,-12,-14, -7, -3, 10,  2,  7,-10,  2,
+    -8,  1,  8, -1,  4,  1,  4, -2,  5, -9,-18, -8,-13,  5,-11, 10 },
+  { 14,  8,-12,-16,  9,-11, -3, -6,-25, -7,  6,  5, -7,-16, 10,  2,
+    -7, -1, -9, -3, 16,  4,  3,  3, -3, -3,-15, 13, -3,  4, 13, -7 },
+  { 16, -9, 19,-23,  7,-19, -3, -5,-15, 11,-21, 21,-16, 18, -1,  6,
+    10,-10, 18,-14, 16,-15,  6, -5, -9,  5,-17, 13,-10, 13,  0, 10 },
+  {  8, -4,  4,-24,  8,-21,-18,  9,-11,  4, -6, 17,  5, -9, -2, -2,
+     2, 15, -2, -3, -2,  1,  7,-13, 15,-10, -8,-11,  3,  3, -1, -1 },
+  { 14, 17,  6,-32,  5,-17, -2,  0, 15, -1, -5, 16,  1, -5, -2,  9,
+    -3,  8,  4, -2, -2, -4, -3,  1,  0,  7, -3,  4, -5,  0, -7,  2 },
+  { 24,  6, 22,-12,  8,  3,-14,  4, -7,  8,  6,  5,  6,  1,  6,-12,
+    15, 10,  4, 11,  9,  6, -7, -4, 10, -9,  2, -1, -5, 11, 15,  3 },
+  { 17, 12,  3,-23,  5, -1, -2,  1, -9, -1, -3,  1,  8,  1, -5, 17,
+    11,  0, -2,-11,  7,  4,  0,-27, -7,  1,  2, -8,  9,  7,  5,  3 },
+  { 12, 10, 12,-10, -4,  5, -1,  2,-24,  5, -8,  2,  6,-17, 19,  5,
+    12, -2, 16, -7, -6,-14,  4,  1, -3, 13,-16,  5, -1,  4,  1,  1 },
+  { 31,  9, 11,-17, 10, -3, -7,  7,  1,  2,  2,  4, -3, -1, 11,  4,
+    -5, -8,  1,  4, 15, -6,-28,  1,  8,  3, -6,  5, 17, -2,  2, -4 },
+  { 11, 19, 16,-26,  0, -7, -7,  2,-13,-15,-12,  9, -3, 27,  8,  4,
+    -6,  1,  4, -6, 11, -1, -6, -7, -3,  0, -6,  4, -6, -7, -3, -1 },
+  { 10, 18, 16,-32, 19, -9, -4, -3, -7,  8,  8, -3,-11, -2, -6,-16,
+    13, 13, -6, -1, 10, -2, -2, -9,  0, -3,  9,  4, 11, -2, -6,  6 },
+  {  9,  4, 19,-33,  4,  7,-12, 36, -3, -1,  8, -2,  2, -8, -9, -4,
+    -8,  0,  1, -1,  0, -4, -4,  3,  0,  3,  6,  0, -6,  2,  0, -2 },
+  { 25,  7, 15,-12,  2,-24, -1, 24, -4,  4,  9,  0, -2, -9,  4,  6,
+     3, 13, -3,  1,  5, -1, -3, -5, -1,  7, -2,  3,  4,  4,  1,  0 },
+  { 19,  6,  8,-20,  9, -9,  5, -4,-13,  7, 11, -3,  5,-13, -9,  6,
+   -11, -1,  0,  4, 11, 26,  3,  6, -7, 12,  6, -3,  1, -9,  7,  1 },
+  { 15,  6, 19,-23, -3, -9,  3, 16, -6, -4,  6, -5,-10,  1, 16,-14,
+     2,  0,  2,-13, -3,  8, -6,  3,  1,  1,  2, -5, 12, -4, -8, -3 },
+  { 14,  4, 16,-20,  1, 12,  0,  6, -3,  9,  4, 16, 10,-16,  5,  7,
+     5, -4, -4,-18, -3,-11, -4,  4, -7,  3, 13,  7,  3,  3,  2, -7 },
+  { 22,  3, -1,-30, 18, -3, -9,  9, -2, 11,-16, -2,-14, 12,  0,  4,
+    -5,  4, -1,  3,-20, 12,  4,-10, -2, -2,-12,-12, 10,  6, 11, -3 },
+  { 15,  7,  2,-21,  5,  4,  9, -9,-33,  7,  7,  3, -6,-14, -8, 10,
+    12,  0,  2, -1,  5,  4, -2,  0, -7,  0,  2,  4,  0,  1, -3,  8 },
+  { -7,  0, 12,  3,  0, -6,  8, -4,  0,  2, 14,-15,  2, -7,-31, -3,
+    14,  0, 14,-15, -1, -4,-15, 10,  1, -3,  1,  2,  5,  2, -8,  1 },
+  { -2,  5,  1,  0, -3,  3,  3, -6, -1,  2, -4,  1,-19,  0,-11, 18,
+    11, 10, 21,  5,  6,  2, 10,  3, -6,  0, -2, 13,  5, -1, -2,  9 },
+  { -9,  1, -5,  0,  0,-15,  8,  4,  8,  3,  8, 12,-13, -2,-39, -2,
+     4, -4,  5, -3, -4,  3, -3,  3, 10,  5,  3,  2, -3,  5, -2,  8 },
+  { -9,  6,  6, -8, 12,-12, 23,-18,  4,-15, -5,  2,-20, 13, -7,  7,
+     7,-12, 14,-12,  6,  1,  1, -3, -8,  9,  0,  1, -7,  3,  7, -6 },
+  {-18, 13,  4,  3,-10,-30,-10, -6,-14,  1, -7, -4,-35,  5,-25, 11,
+     9,  8, 19, -4, -7, -3,-18, -8,  1,  5, 10, -4,-14, -9,  3, -4 },
+  { -6, -1,  4, -9, -9,  4, 20,  0,  0,  3, 11,  7,-16,-17,-20, 11,
+    -6,-14,  1,  4, 19,  2, -8,  6,-15,  3,  6, -5,-14,  3,  7,  2 },
+  {  1,  6, -2, -8, -5, -3,  3, -8, 21,  1,  3, 16,-14, -2, -9, -4,
+    13, -2, 18, 14, 14, 19,-13,  5,-10,  2, -3,  3,  5,  5,  1, -1 },
+  { -1, -5, -6, -2,-11, -7,  5, -4,  5, -1,  0,  3, -3,  2,-19, 18,
+    16,  4, 14,-22, -2,-11,-22,  1, -1, 11,  1,  2, 11,-10,  7,-12 },
+  {  1,  4,  5, -1, -9, -5,  1, 12,  5,  6, 12,  9,-24, 23,  1, 20,
+    14,-11, 13,  5, -2, -2,  5,  6,  2,  1, -9,  6, 10,  5, -4, 11 },
+  { -1, -1,  1,  7, -3, -4,  8,-16, 15, -1, -7,  9,-22,-11,-11, 10,
+    16,  9, -2,  4, 13, 10,  6, 16,  4,  7,  1, -8, -7,-14, -7,  4 },
+  {  1,  3, -6,  0, 15, -9, -4,  0,  4,  6, 12,  9, -6, -5,-22, 17,
+     7,-11, 15, -5,  1,  3,-19,  0,-15, -3, 16,  5,  5, -7,-11, 12 },
+  { -2, -1, 13,  2,  4,-24, 37, -5, -2, -6, 12,  7, -2,-23, -4,  9,
+     2, -3,  3,  2,  3,  3,-14, 11,  0, -4, -2, -2,  3, 10,-10,  4 },
+  {  2,  9,  8, -6,-28, 14, 28,-11, 18,-11,  0,  2, -2,  4,-12,  3,
+     6,  0,  7, -7, -6,  2,  5, -1, -1, -1,  5,  2,  3,  0, -3,  9 },
+  { -7, 14,  5,-10, -3,  7,  4, -5,  7, -8, -7,  4,-12, 14,-16, 25,
+     3,  0,  1, -5, 12,-10,  0,-10,  0, 12, 12, 17, 12, 10, -1,  0 },
+  { -4, -2,  5, -2,-17, -3,  5, -5,  7,-17,  1,  5, -4,  4,-20,  0,
+    11,-15, 13, -8, 10,  1,  1,  5,-12,  9, -8,  0,  6, -1,-11,  4 },
+  { -3, 12, 13,-15, -7, -7,  0,  5, 33,  3,  3, -6,-13, -7,-15, 10,
+     3,  3,  3, -5,  2,  7, -1,  0,-12,  2, 11, -6, -9,  0,  5, 11 },
+  { -8,  5, 10, -7,-14, -4, 13,  0, 18, -3, -6,  7,  1, -6,  0, 21,
+     8, -7, 10, -8, -3, 17, -9,  0, -5,  1,  4,  8, -3, 11, -5,  0 },
+  { -8,  8, -3, -8,  8,-11, 16,-16, 17,  0,  8, 16,-17, 10,-16, 10,
+    -8,  6, 11,  0, 10,  7,  4,  5,  7, -5, -5, -6, -7, -5, -1, 16 },
+  { -6,  0,  6,  1, -8, -8,  8, -7, -5,-10,-11,  8,-19,  6, -7, 13,
+     5, -3,  4, -8,  7, -1,-18,  9,  0, -5,  6, 26,  3,  8,  2,  4 },
+  { -2, -2, 23, -2,-20,  2,  7, -7, -6,-15,  3,  9,-19, -2,-10,  7,
+    -2,  7,  9, 11,  0,  4, -4,  6,  9, -2,  4, -3,  4,  3,  2,  8 },
+  { -6, 12, 10,-10, -7,  4, 17, 11, -6,  1, 12, 11,-18,  8,-12,  4,
+     1, 13,  6,-13, 23,  9, -5,  8, -2, -5,  1,  3,  0, -2, -4,  4 },
+  {  7,  1,  7,-17, -8,  8, -1, -7,  5, -6,  4, -3,-16,  9,-24, 18,
+    -3, 10, 13,-11, -6,-11, -4, 10,  0, 11,  8,  2,  6, -5,-11,  4 },
+  { -4,  1, -5,-10,  0, -3,  9, -2,  4, -1,  1,  5,-41,-10, -7,  4,
+    -3,  3,  1,  0,-12,  4, -3,  0,  2, -1, -2, -5,  3,  2, -7,  5 },
+  { -2,  1,  4,  4, -3, -6,  1,  0, 12, -5, 11,  0,-17, -3, -1, 11,
+     4,  1, 27,-12,  0,-14,  2,-15, -3, -9,  0, -7, -3, 15, -8,  6 },
+  { -6,  4,  9,  2,  4,  3,  7,-10, 28,  1, -2, 48,  7,  0,-10, 10,
+     1, -9,  2, -1,  0,  3, -5,  5, -4, -2,  7,  7,  1,  3,  2,  5 },
+  { -3,  3, -1,  3, -9,  0, -1,  3,  2, -6, 39,-14,-12,  5,-19, 21,
+     7, -6,  4, -1, -4,  0, -4,  1,  0, -9,  1, 10,  0, -2,  0,  7 },
+  {  4,  2,-29, 12,  5, -3, 16, -6, 15,-13, -4, -1,-13, 22,-16, 17,
+    16,  4,  9, -4,  4, -6, -4, 11, -8,  7,  8,  4,  3, -3, -7,-13 },
+  {  0,  3,  3, -6, -4,  0,  9,  0,  5,  0, 10, 10,  4,-13,-12, 16,
+    23, -4,-12, -6, -4, 20,  2,  0, -4, 23,  1,  8, 11, -4, -5, 15 },
+  { -6,  4,-15, -9, -1,-19, 12,-30,-17, -4,  1,-13,-13,  4, -3, 26,
+     5,-25, 11,-14, -6,-13,  0, -7,  9,  2,  8, -1, -8,  1, -8, 13 },
+  {  1,  6,  1, -4, -4,  1,  2,  0, -3,  2, 10,  6, -6, -2,-11,  4,
+    32, 15, 15,-47, -8,  3,-12,  4, -5,  4, -1,  0, -5,  5,  1, -7 },
+  {  2, -1,  0,  0, -1, -6,  0, -6,  4, -4,  5,  9, -5,  1, -3, 51,
+     4, -5,  4,-14, -1, -4, -3,  1, -4, -1,  0,  2, -8,  0,  1,  2 },
+  {  0,  4, -2, -7, -2, -9,  6, -8, 11, -3, -6,  3,-11, -8,-12,  8,
+    11,  5, 19,  3,-24, 19,-14, 11, -5,-18, -8,-12, -5, -4, -1,  4 },
+  { 16,  9, 10, 14,-18, -2,-18,-27, 10, -5, 12, 14,  4,  0, -2, -6,
+   -12, -7, -1,  3,  4,  7, 11, 10,  5, -5, -7,-16, -3, -6,  6,  9 },
+  {  7, 15, -9, 10,-19,  4, -5,-37, -2, -4,  8,  2,  4, -1,  1,  9,
+    -5, -5,-12,  1, -1, -8,  3, -3,  4,  6,  9,  3,  3, -1,  2,  4 },
+  { 13, 17,  3,  9, -7, -7,-15,-17, -8,-13, -4, -8, 19,  2, 16, 25,
+     7, 15,  2, 16, -5, -6,-10, -9, -7, -6, -2, -7,  7,  2,  4,  5 },
+  { 24,  7,  9,  8,-13, -2,  0, -4,  1,-13,  3,  6,  7, 10, -4, 15,
+     5,  7, -4,  5, -5,  3, 13, -7,  5, 15,-11, -2,  7,  5,  8,  6 },
+  { 17,  6,-15, 23, -2, -1, -6, -2,  0, -4, 11, -3, 12, 15,  6, -8,
+   -15, 10, -9,  7, -1,-11,  2, -8, -4,  3,  4,-10,  4,  4, 11,  1 },
+  { 21, 12, -3,  6, -8,  8,-11, -8, -5, -5,  3,  7, -1, -5, 12, 15,
+   -10,-11,  3, 15,  8,  4,  2,-15,  0, 14,  1, -8, -1,  3, 10, -7 },
+  { 16, 12,  5, 13, -6, 15,-23,  0,-17, -9,  0,  4, -9, 13,  6, 18,
+     0,  0, -4, -1,  0, 14,  5, -1,  8, -4, -8, -6,  5, -2, -2,  0 },
+  { 14, 16, -1, 12,-15, -9, -6,-20,  4,  6,  8,  9,  3,  1, -9, -4,
+    -1,-11,  9, 11,-12,  1,-14, -7,  2, -8, 11,  9, -4, 10,  4,-16 },
+  { 13, 10,  3,  7,  0, -8,-33, -6,  4, -4, 19, -2, 14,  6,  5,  7,
+     6, -3, -1,-10,-10, -9,  4, -3,  5,  9,  2,  2, 10,  9, -2, -3 },
+  { 11, 10, 25, 18, -1, -6,-21,-21,-11,-16,  6,  5, 14,  4,  8,  7,
+     0,-10, -7, -9, -5, -4,  3, -1,  1,  6, -1,  6, -2,  2, -3, -9 },
+  { 15,  9,  5, 22,-17, 15, -9,  7,  7, -9, 13,  9, 10, -1,  8, -3,
+    -2,  6,  1, 17,  8,-14,  7, -3, 12,  9,  1,  0,  1, -5, 17,-18 },
+  { 25, 19,-17, 12, -4,-10,  1,-13,-19, -7, -3,  9,  6, -2,  3,  1,
+     4, -2,-11,-14, -1, -7, -5, -9,  7, -1, -3,  4, -5,  1,  0, -1 },
+  { 20,  8, -3,-10,-24,  3, -6, -2,  0,-12, 14,  6,  7, 11,  4,  7,
+   -12, -5, -8,-10,  5, -1, -4,  4, 16,  7,-14,  6, -1, -2, -7,-11 },
+  { 16, 18, 17,  1,-15, -6, -5, -3, -1,-19,  8, -2,  2,  8, 12,-19,
+   -12,  8,  0, -3, -1, -1,  4,-14,  9, -1,-12, -1, -7, 10, -3,  5 },
+  { 18, 12, -7,  7,  0, -3,-13,  0, -1, -4,  9, -2,  6, -1,  0,  1,
+    15,-21,  1, -8, 25,-19, 13, -9,  2, 12,  5, -7, -3, -1, -3,  1 },
+  { 13, 16, -4,  9, -2,  2, -1,-19, -7, -4, 18, -6, 14, 18, -5,  4,
+    -6, -3,-19,-14, -1,-12, 10,  6,  7, 17,-12,-13,-10, -4,  5,  4 },
+  { 27, 17,  4, 14, -9, -2, -4, -8,  0, -6, 14,-11, -7,  2, -3, -3,
+    -2, -3,-13, 12, 16,  1, -5, -9,-10,-11, -2,  3, -7,  5, 11, -7 },
+  {  7, 17,-16, -2,-14,-28, -7, -8, 15,-10,  7, 15,  8, 17, 13, -1,
+     4, -7,-12,-11,  0,  0,  2,  3, -3,  7, -6,  6,  1,-16,  1, -2 },
+  { 23, 11, -9, 15,-23, -4, -6, -4,  2, -9, -7,  9, -8,  3,-13, -4,
+     8, 18, -6, -2,  1, -5,  6,-14, -5, -2, -6, -5, -3, -2,  4, -5 },
+  { 12, 13, 18, 18,-35,  2,  7,-17,  3,-11,  6,  9, -3, -2, 10, -4,
+     3,  3, -2, -7,  0,  2, -4,  0, -4,  0, -6,  5, 10,  4, -3, -1 },
+  { 19, 11,  1, 20,-14,  4, -9,-13, -2, 11,  0, 17, -1, -1, -1, -1,
+    -5, -8,  0,  5, -1, -8,  5, -1,  3,  2,-12, 21, -2,-24,  5,  7 },
+  { 15, 15,-15, 17,-14,-22,  3, -4,-11, -3, -7,  1, 18, 10,  1, 10,
+    -6, -3,  8,  2, -7,  0, -2,  1,  1,  2, -9, -2,  1,  2, -3,  4 },
+  { 45, 13,  8, 17, -5,  2,-16,  2,  8, -2,  8,-15,  4,  5, -1,  7,
+    -6, -2, -6,  2, -3,  0,  0, -9, -1,  7,  2,  3, -3, -3, -1,  5 },
+  {  1, 18, -8, 18,-12,-10,  3,  4,-22,-12, 20,  8, -3,  9,  2, 10,
+   -10, -3,  9,  3,  6, -3, 10, -1, -3,  2, -2,  4,  2,  3, -3,-18 },
+  {  9, 10, -5,  9,-35,-21,-18,-16, -1,-12, -6, -7,-15,-19, 12,  4,
+     4,  9, -7,  2, 14,  1,  4,  0, -1,  6, -7,  2,  1,  1, -4,  4 },
+  { 31,  8,-17, 35, -8,  1, -5, -6, -7, -6, 10, -2, -3,  6,  9,  3,
+    -6, -2,  3,  3,  5, -3,  0,  6,  0,  1, -5, -3, -2, -4, -1,  0 },
+  { 18,  4, -8,  7, -8,-15, -1,-16, 12, 18,  3, 19,  2,  4,  8,  8,
+     0, -5, -8,-12, 10, -5,  0,  1,  0,  4, -3, 16, 11, 11, -2, -6 },
+  { 27, 15,-17,-10,-23,-22, -1,-14, -4, -7, 20, -2, -7,  6, 15, -5,
+    32,  4,  9,-11, -3, -8, 11, -4, -1, -4, -8, -6, -4, -5, -2, -7 },
+  { 22,  4, -7,  2,-15,-11,-17,-10,  2,  0, 15, 11,  7, 12, -8,  6,
+   -10,-18, -6,-12,  7,  3, 22,  3, -7, 14, -5, -2,-13, -7, -1, -7 },
+  { 18, 13,  9, 24, -4,-19, -9,-11, 13,  8,  2,  4, -1,  8, 14, 10,
+   -12,  0,  0,  5, 10,  5,  4, -1,  5,  1, -1, 11,  2, -4,  0, -9 },
+  { 15, 19, -5,  1, -4,-10, -8,-27,  6,  8,  5, 10,  4, 11,  5, -5,
+   -11,  0,-11,-14, -4, -9, -8, -8,  6, -9,  4, -5, -1,  1,  5, -4 },
+  { 18,  1,-13, 14,-14,  9,-15, -7, 12,  1, 13, -4,-20, 12, 10, 12,
+   -12,  7,  1,-13, 10, -6,  5, -3,  4,  8, 10,-13, -3, -6,  9, -3 },
+  { 19,-14,  5, -8, -6,  2, -5,  5, -3, -1,-28, 11, 18, -6, -4, -2,
+    11, 14,-43,-42,  9,  2, 20,-23,  6, 32,  0,  5,  0,  6,  9,  5 },
+  {  8, 11,-14, -1,  7, 12, -7,  2,-16,  2, 10, -3, -1, -7, -7, -1,
+     1,-10,-60,-23,-18, 42,-13,  9, 18,-11,  0,  1,  0,  2, -5,  1 },
+  { -5, -1,  2,  0,  3, -3,  3, -2, -6,  0, -3, -3,  7,  2,  0, -2,
+    -2,  3,-34,-15, 37, 47, 10, 20,  9,  1,  3,-21,-25,-33,-14,  8 },
+  {  5,  6,  2, -2, -2, -2,  6,  5, -5,  7, -3,  1, -5,-13,  9,  3,
+   -17,-19, -2,-79,-12, -7, -8, -6, -2, -2, -1, -1, -7,-13,  6, -1 },
+  {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1, -1,
+     0,  3,  4,-87,  6,-11, 16, -9, -1,  8,  0,  5,  0,  1,  2,  1 },
+  { -5,  6,  2,-24,  5, -9, -7,  0,  7,  3, -3, 16,-14,-16,  0, 18,
+    15, -9,-14,-28,-17, 53, 14, -6,-28, -1, -3,-10, -7,-14, 19,-15 },
+  {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -3,  0,
+   -13,  0,-53,  3,-22, 63, 19, 16,  1,-11,  0, -3,  0, -3,  0,  1 },
+  {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -1, -1,
+    -1, -6,-43,-43, -2, 65,-13, -4,  9,  1,  1,  2,  1,  0,  0,  1 },
+  {  0,  1,  0,  0, -1,  0,  1,  1,  0,  0,  1,  2, -1, -1, -3, -1,
+   -23,  1,-61,-55,  3,-28, -6, -4, -4,  8,  2,  1,  1, -1,  0,  0 },
+  {  0,  1, -1,  1, -1,  0, -1,  0,  1, -1,  0,  1, -1,  0, -9, -4,
+   -48,-19,-52,-46, 11,-12,  5,-14,  0,-10,  0,  0, -1, -2, -1,  0 },
+  {  0, -3, -1, -4,  2, -1, -7,  3,  1,  3, -1,  1, -3,  0, -7,  0,
+     3, -7,-61,-51, -4,-21,-16,-21,-11, 14, -7,  8,  3, -5,  1,  2 },
+  {  0,  0,  0,  1,  0,  0, -1,  0,  0,  0,  0,  0,  1, -1,  9, -3,
+    56,-11, -6,-67, -1, 13,  0,  7,  1, -9, -1, -1,  0,  0,  1,  0 },
+  { 14,  9, -2, 14,-10,-10,  9, -5,  1, -8,-23, 30,  8, -7, 23,  8,
+     2, 10, -1,-27,-17, 57, 22,  4, -5,  2,-12, -6,  2, -7, -4, -9 },
+  {  1,  5, 12, -2, -2, -3,  2, -3,  6,  0,  4, -2, -8, -6,  0, 16,
+   -15, 29,-55,-29,-24, 29,  3, 10,  6, 13, 10, -5, 21, 11,-14,  5 },
+  {  4,  2, 26, -6, 10, 11,-23,-10,-27,-20,  3,-24,-11,-10,-13, 25,
+   -10,  5, -9,-36, -7, 43,  3,-13,  6, 13, -2,  0,  1,  3, -3, -4 },
+  { -1,  0, -1,  0,  0,  0,  0, -1,  1,  0, -1,  0,  0,  0, -1,  1,
+   -12, 12,-26,-64,-15, 29, 37, -7, -3,-12, -5, 14,  8, -8,-10, -2 },
+  { 19, -4,-11,-16,  8, 14,  5, 19,  3, 22,-11,-21, -1, -6,-11, 11,
+    10,-24,-23,-40, -8, 20, 17,  5, 13, -6,  3, 14,-20, -8,  3, 28 },
+  {  2,-12, 10,-14,-18, 26,-22,  4, -2,  5,-21,  8,  3,  1, 19,  0,
+   -12, 24,-14,-40, 15, 29,-15,  6, 15,  1,-19,  2,  4,  7,-12, -3 },
+  {  0, 17, 13,  7, -5,-11,  2,-19,  3, 38,-21, -3, -6, -4,  7,  1,
+     1, -5,-40,-10, -2, 35,  8,  8,-10, -8, -9, 33,  4,  4,  0, -2 },
+  { -2,-12,  7, 29,-24,  2, 16, -1, -7, 16, 10, -2, -2, -2, 13, -2,
+   -37, 15,-22,-40,-11, 33, 10, -1,  8, 10,  6,  8,  9,  0,-12,  2 },
+  { 15, -8, -9, -2,  7,-17,  7, 19, 14,  4, 12, 27, 11, 10,  4, 11,
+   -15, 14,-13,-48,  5, 18,  0, -9,-36,-11,  2,  4,  5,  5,-15,-12 },
+  {-12,  0,  3,  4,  7, -5,  5,-14,-24,-18, -6,-15, -8,-20,  1, -7,
+   -33,-28,-40,-38,-18,-10, -5, 17,-12,  4,  3, -5,  5,-13,  4, -7 },
+  {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -1, -1,
+    -3, -9,-49,-60, -5, 45, -1,  6,  0,  0,  0,  0,  0,  0,  0,  0 },
+  {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -1, -1,
+    -3, -9,-49,-60, -5, 45, -1,  6,  0,  0,  0,  0,  0,  0,  0,  0 },
+  {  0,  0,  0,  0,  0,  1,  0,  0,  0,  0,  0,  0, -1,  0,  0,  0,
+     3, -2,  9,-29,-11, 55,  8, 32,-36,-13, -7, 37,  4, 11,  0,  3 },
+  {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+     4, -1,-39, -4,-30, 63, 28,-17, -6, 10,  7,-14, -9, 11,  9,  7 },
+  {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -1,
+    13, -2,-50,-32, 22, 51,  4,  7,  6, 11,-20,-13,  9, -5, 21, -4 },
+  {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -1, -1,
+    -3, -9,-49,-60, -5, 45, -1,  6,  0,  0,  0,  0,  0,  0,  0,  0 },
+  {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -1, -1,
+    -3, -9,-49,-60, -5, 45, -1,  6,  0,  0,  0,  0,  0,  0,  0,  0 },
+  {  0,  0,  0,  0,  0,  1,  0,  0,  0,  0,  0,  0, -1,  0,  0,  0,
+     3, -2,  9,-29,-11, 55,  8, 32,-36,-13, -7, 37,  4, 11,  0,  3 },
+  {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+     4, -1,-39, -4,-30, 63, 28,-17, -6, 10,  7,-14, -9, 11,  9,  7 },
+  {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -1,
+    13, -2,-50,-32, 22, 51,  4,  7,  6, 11,-20,-13,  9, -5, 21, -4 },
+  { -8,  2,  1, 22,-31, -6,-25, -3, -3,  1,-15,-11, -2, -3,  4,-13,
+    -9, 15,-18, 37, -7,-37, 12,-13,-11,-25,-10,-11,-22,  7, 16,  7 },
+  { 14, 10,  4,-10, -1, -5, -7, -3, 16, 13, -5,-15,  5, 11, -1,  8,
+   -27,  7,-12, 49, 17,-22,  9, -2, -9, -1,  2,-15, -1, 41,-18,-17 },
+  { -4, -9,-15, -3,  3,  4,  4,  2,  7, -3, -7, -8, -5, 17,-19, -7,
+    36, -9,-38, 17,  1,-48, 11,-18,-13, -2, -8,  4,-10, -5, 21, 11 },
+  { 15,-13,  4,  2,  1, -5, -2,  1,-10,  7, -1,  3, -6,  0, 11,-11,
+     8, 20,-17, 51,-17,-41,  2, 15,  4,  8, -2, 16,-32, -1, 17,  6 },
+  { -8,  8,-18, -5,  4,  6, -3,  8,  0, -4,  2,  0, -1, -4,  5,  8,
+    30, 30, -8, 70,  2,  8,  2,  0,  7,  1, 13, -1, -6, -7,-11,  2 },
+  { -8, -7,  9,-10,-13,  6,-11,-14, 13, 25,-26,  5,  2, -5, -5,  5,
+    -8,  4,  0, 33, 12,-38, -4,  6, 13,  6, 25, 34, -1, 25,-19, -5 },
+  { 18,  3,-17,  4, -8,  7, 20,  1, -1,  5, -5, -2, -8,  8,-35, 15,
+    24, 43, -5, 51,  5,-12, -3,  1, -2,  3, -3, -3, -9,  8, -9,  2 },
+  {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,
+     2, 10, 24, 76, -2,-22, 11, -1,  4, 33,  4,  1, -1,  1,  2,  0 },
+  {  0, -1,  0,  1,  0,  1,  0,  1,  0,  0,  0,  0,  0,  1,  2,  0,
+    24, 13, 32, 70, 26,  5,-21, -9, -6,-15,  2, -2,  2,  4,  1,  1 },
+  {  5, -4,-11,  4, -4, 22, 10, -2, 13,-11, -4,-21,-17,  0, -7,  4,
+    10,-34, 11, 52,  2,-46, -5,  0,  0, -1,  2,  4, -9,  1,  1, -7 },
+  {  0,  1,  1,  0, -1,  0,  1,  0,  1,  1,  0,  1,  0,  0, -3,  1,
+    -8,  9, -1, 64,-13,-61, -3,  3, -5, 10,  1,  3, -1, -1, -1, -1 },
+  {  0,  1,  0, -1,  0, -1,  0,  0,  1,  0,  0,  0,  1,  1,  2,  1,
+    10, -2,-31, 79,-10, 27,  0, -1,  3,  8,  1,  1,  0, -1,  0, -1 },
+  {  3, 12, 10, 26,-19, 10, -9,  6, -4,-15, 10,  3,-16,  6, 11,-19,
+     3, 10, 18, 44,  5,-30,  5, -9, 21,  4, 20, 10, 14,-25,  8,-17 },
+  {  0,  0,  0,  1, -1,  0, -1,  0,  1,  0,  1,  1,  0,  0, -6, -2,
+     8, -8, 13, 69, 26,-19,-25,-17, 16,  6,-12, 22,  2, -6,  9,  5 },
+  {  0, -1,  0,  1,  0, -1, -1,  0,  0,  1, -2,  1,  0,  0, -4, -1,
+   -34,-15,-33, 56,  9,-42,  9, 10,  6,  9, -8,-11,  0, -6, 15,  5 },
+  { 10,  2,-14, -3,-15,-35, -1,  7,-18, 14,  8, -1,-15,-26,  6,-15,
+   -18, 22,  9, 33,  0,-32, -9,  3,-11,  7,  4, -1,  5, 30,  9,  1 },
+  {  4, 15,  0,  6, -5,-11,  9,  6,  6,  6, 14,  2, -1, 10,-24,-25,
+    -2, -4, -1, 37,  2,-29, 14, -9, 22, 17, -2, 33, 10,-25, 11,-11 },
+  {  0,  5,  2, 18,-12, 21, 22, 33, -7, 21, -9, -7,  7,-15, -7, 16,
+     7,  0,-14, 44, 10,-25,  5, -4, 15, -8, 10, -4,  5,  9, -1, 16 },
+  {  3, 13, 12, 12,  8, 25,-23,  8,-22, -3,-18, -8, 15, 12,  9, 19,
+     0,  0, -9, 49,-27,-15, -9,-15, 12, -8,-16, -7, 13,  5, 13,  2 },
+  { 12, -6,  7, -2, 20, -9,-14, 12, 13, -5,-17, 22, -8, -4,  2,  7,
+   -13, -2,-15, 43, -5,-30, 27,  4, 10,-27,  5, 27,-10,-10,-18,  0 },
+  {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,
+    -1, 10,-18, 70, -2,-52, -1, -7,  0,  0,  0,  0,  0,  0,  0,  0 },
+  {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,
+    -1, 10,-18, 70, -2,-52, -1, -7,  0,  0,  0,  0,  0,  0,  0,  0 },
+  { 15,-13,-20, 16,  2, 13,  5,-11, -8, -5, -3,  2, 24,-23, 30, -7,
+    11, 30,-15, 43,  5,-15, 15, -3,-14,  1,-23,  8,  3,  9,  4,-11 },
+  {  0, -1,  0,  1,  0, -1, -1,  0,  0,  1, -2,  1,  0,  0, -4, -1,
+   -34,-15,-33, 56,  9,-42,  9, 10,  6,  9, -8,-11,  0, -6, 15,  5 },
+  { 10,  2,-14, -3,-15,-35, -1,  7,-18, 14,  8, -1,-15,-26,  6,-15,
+   -18, 22,  9, 33,  0,-32, -9,  3,-11,  7,  4, -1,  5, 30,  9,  1 },
+  {  4, 15,  0,  6, -5,-11,  9,  6,  6,  6, 14,  2, -1, 10,-24,-25,
+    -2, -4, -1, 37,  2,-29, 14, -9, 22, 17, -2, 33, 10,-25, 11,-11 },
+  {  0,  5,  2, 18,-12, 21, 22, 33, -7, 21, -9, -7,  7,-15, -7, 16,
+     7,  0,-14, 44, 10,-25,  5, -4, 15, -8, 10, -4,  5,  9, -1, 16 },
+  {  3, 13, 12, 12,  8, 25,-23,  8,-22, -3,-18, -8, 15, 12,  9, 19,
+     0,  0, -9, 49,-27,-15, -9,-15, 12, -8,-16, -7, 13,  5, 13,  2 },
+  { 12, -6,  7, -2, 20, -9,-14, 12, 13, -5,-17, 22, -8, -4,  2,  7,
+   -13, -2,-15, 43, -5,-30, 27,  4, 10,-27,  5, 27,-10,-10,-18,  0 },
+  {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,
+    -1, 10,-18, 70, -2,-52, -1, -7,  0,  0,  0,  0,  0,  0,  0,  0 },
+  {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,
+    -1, 10,-18, 70, -2,-52, -1, -7,  0,  0,  0,  0,  0,  0,  0,  0 },
+  { 15,-13,-20, 16,  2, 13,  5,-11, -8, -5, -3,  2, 24,-23, 30, -7,
+    11, 30,-15, 43,  5,-15, 15, -3,-14,  1,-23,  8,  3,  9,  4,-11 },
+  { 16,-18,  7, -4, 31,-15, -9,-13, 20,-12, -6,  0, 12, -6, -2,  4,
+     3, -3, -1,  0,  1,  3,  3, -2,  1,  6,  4,  0, -3,  2, -5,  1 },
+  { 38, -5,-13, -4,  8,-15, 11,  1,  2, -4, -1,  9, 13,  4,-12, -7,
+     0, -2,  7,  2, -6, -2, -3, -2,  3, -4,  6, 15,  1,  1,-11, -2 },
+  { 47,-22,  9,-26,  3, -5,  2, -7,  4, -2,  2, -2,  3,  0,  3, -4,
+     3, -3,  2, -3,  7, -3, -1,  1,  1, -5,  5,  0,  2, -5, -3, -2 },
+  { 14,-16,  2, -6,  7, -2, -7, -4, -4, -7, 14, -3,  7,-19,-14,-17,
+   -29,  6, 26, 16, -5, 13, -4, -1, 21, 14,  1,  3, -6,  0, -7, -1 },
+  { 29,-11,  5, -3,  4, 11,  4,-10,  1,-22, -3,-10,  5,  4,  2,  8,
+    -2, -7,-12,-12, -8, -3,-18, -2, -9, -5, -1, -3,  2,-14,-14,  7 },
+  { 28,-12,  5,  3,  9, -7,  0, -2,  2,  1,  4,  0, -7, -3, -2,  4,
+     4, 14,  8, -1, -4, 14, -7, 17, -2, -2, -9,  2, 19, -7,  9, -8 },
+  { 31,-18,-22,  8, 15, -5,-10,-15,  1, 10,  6,  7,  6, -8,  2, -1,
+    12, -3,  3, -1,  1,  5, -6, -4,  0,  1,  7,-10, -2,  4, -3, -4 },
+  { 53,-30, -4, 12,  2,  3, -3, -3,  0,  1,  6,  5, -5, -4, -7,  1,
+     0,  2,  1,  3,  1,  5,  0,  2,  2, -1,  0,  4,  2,  0, -2,  0 },
+  { 27,-18, -3, -2,  4, -8,  3, -2,-11,  2, 10, -8, -8, -4,  0, -2,
+     8,  0,  9,  0,-16, 11,  1, -6, 13, -3,-10,-13,-15, 25,  1,  0 },
+  { 35, -5, -1, -8, 23, 11,-14, -3,  2, -2,  8, -6, 17, -2,  7,  0,
+    -2, 10,-17, 13, -2, -2, 11, 11,-14,  2, -2, -3, -8, -1,-12, -5 },
+  { 29, -9,  7,  3,  2,-10,  0,  3,  9,  0, -3,  5,  1,-10, 10, -5,
+     3,  6,-20, -9, -6, -4,  1,  0, 12, 17, -8,  9,  3, -1, -9,  0 },
+  { 15,-16, 18,-19, 16,-15, 17,-18, 13,-16, 17,-14, 15, -9, 13,-17,
+     9, -7,  4, -5,  3, -4, -3,  0, -6,  7, -9,  7, -2,  7, -9,  9 },
+  { 21,-10,  7, -2, 12, -7, 13,-17, 11, -2, 20,  3,  5,-11, -6, -6,
+   -15,  0, -9,  5,-11,  7, -1,  7,  8,-10, -9,  3, -5,  9, -8, -2 },
+  { 23,-22, 15, -5, 16, -4, -3,-12,  9,  3, -1, -2, -8,  2, -2,-16,
+     3,  4, -2, -6, -7, 12, -8,  2,-14,  2, -7, 11, -2,  6, -4, -1 },
+  { 34,-17, -4,  8,  4, -6,  1,  8,  4, 16,  3,  6, 12, -1, -1,-15,
+     6,  4, -7, -6,  6,  0,  2,  1, -2,  2,  3,  3, -3, -2,  8, -6 },
+  { 18,-18,  2, -2, 10,  1, 18,-23, -3,-10,  0,  4, 20,-19, -3, -4,
+     2,  8,  6,  1, -3,  1,  1,  3,  5, -1,-11,  3, -7,  5, -1,  1 },
+  { 15,-14,  2,  3, 10, -8, 12,-13, 13,-15,  6, -8, -4,-10, 14, -9,
+    24,  2, -7,-18, 13,-11,  8, 14, -6, -2,  3, -1, -4,  7, -7, -4 },
+  { 20,-12, 13,  5, -1,-10, 15, -6,  8, -1, -3,-10, 17,  0, -6,-19,
+     2, -1,  8, -3,-16,  0, -3,  2, -2,  0,  8, -9,  0,  1,-10, -9 },
+  { 32,  0, -9, -5, -1,  5, 13,-11,  8,  3, 11,-11,  0, -8, -2,-14,
+     7, 10,  6, -5,  1, 10,  2, 12,-10,  4,  4,  6,  4,  0, -7,-10 },
+  { 16,-14, 10, -7, 11,-11, 11,-11, 18,-13,  8,-15, 16,-11, 13, -9,
+     8, -7, 12,-11,  7, -6,  3, -5,  9, -5,  4, -1,  7, -4,  8, -3 },
+  { 24,-27, -1,  5,  8, -5, 12,  7,  4, -3,  3, -1, -9,-11,-13, -5,
+    10,  0,-13,  7,  1, -5,  4, -9,  7, -3, 13,  2, -5, -3,-17, -2 },
+  { 23,-19, 15,  1,-10,-18,-12, -6,  8, -3, 12,  0,-12,-10, -4, -4,
+     8,-10,  4,  2, -2, -8, 13, -3, -2, -6,  2, -3,  5, -2,  2, 11 },
+  { 25,-12,  4,  2, 24, -3,  3, -6, 14, 11,  0,-21, -3, -3,  1, -8,
+     7,  0,  0,  3,  3, -6, -7,  6,  2,  1, -4,  5, -1, 10, -2,  9 },
+  { 24, -8, -6,  7, 16,-12, 13, -1, 11,-21,  2, -6,  3,-12,  0,  9,
+     4, 11, -7,  1,  4,  1, -8,  3,  3, -6,  3,  3,  0, -8,  8,  4 },
+  { 25,-21, 13, 14, 13,-18,  4, -3,  0, -5, -4,  5, -3,  0,  4, 12,
+     7,  3,  5, -5,  2, -2,  3,-10,  2, -9,-15,  6,  1,  7, -5,  1 },
+  { 23,-16, -2, 10,  4, -1,  3,  1, 32,  3, -5, -2,  9, 10, -1, -4,
+    -6,  2,  9, -1, 14, 12, -6, -1,-17, -2, -4, -9, -7, -6, -8,  3 },
+  { 50, -8,  5,  2,-11, 10,  0,  0,  6, -3,  7,  0, -3, -2, -3,  0,
+     6, -4,  2, -5, -9,  0,  3, 10,  1, -7, -2, -3, -6, -9,  1, -2 },
+  { 28,-17,  0, -2,  2, -9,  1,  5, -4, -1,  0,  0, 19,-27,  5,-12,
+     7,-14, -3, -6, 10, -2, -4, -2,  4, -5, -2, -7,  1,  7, -9,  4 },
+  { 22,-19, -6, -6,  3,-22,  3,  5, 20, -8,-14, -5,  1,  1, 20,  2,
+    16,  6,  3, 14,  4,  3,  5,  1,  5, -7,-10, -6,  3, -6,  1,-14 },
+  { 29,-14, -8, 13,  8,-10, -6,  4,  4, -6,  5, -7,  1, 12, 14, 11,
+    -7,  1,  2, -9,-11, -9,  0,  4, -1,  7, 10,  4,  4, 20, -1,-11 },
+  { 18, -9,  4,  1,  7,-29, 12,  1, -1, -9, -2, -1, -2,  2,  9, -8,
+   -13,  5,  4,-13, -4,  2, -5, -7, -6, 14,-10,-34, -3,  1, -3,-13 },
+  { 38, -9, 24,  8, 11,  4, -6,-11, -2,-12,  1,  1,-11, -8, -5, -2,
+   -15, -8,  8,  0,  1, -7,  5,  4, -1,  8, -2, 11, -3, -1, -5, -5 },
+  {-20, 11, -4, 24,-11,  1, 15,  4,  0,-28,-10, -1, 10, 10, -6,  5,
+    -6,  2,  7, -2,  1, -2, -6, -3, -7,  1,  2, 12, -1,  7,  0, -2 },
+  { -9, 10,-23, 27, -4,-17, 20, -6, 14,-17,  5, -1,  5, -9, -7,  5,
+    -6,  4, -2,  9,  0,  8,  0,  1, -3, -3, -5, -8,  5, -2, -2, 12 },
+  {-10, 19,  4,  9,  1,-16, 17, -2,  9,-29,-16,-11, -4,  7, -5,  4,
+    -1, -3,  3,  2,  3, -4,  5,-12, -2,  6,  5, -4,  4,  1,  4, 10 },
+  {-20, 10,-24, 14, -5, 11,  9,  0, 16,-20, 10, -5, -6, -6, -1,  2,
+    -4,  5,-16,  8, -2,  5,  5,-11,  9,-11,  4,-11, -1, -1,  4,  3 },
+  { -9, 11,  3, 19, 24,  4,  5,-14, 30,-17, -4, -2,-17,  7,  2,  3,
+     1,  3, -7, -4,  2, -3,  1,  4, -1, -1,  3,-12, -2,  3, -3, 10 },
+  {-19, 18, 11, 19, 19, 19, 10,  4, 13,  6,  5,  4,  8,  3, -2, 12,
+    -6, -2,  7, -6, 15, 12, 16, 16, 18, -3, -4,-20,  0, 10, -9, -3 },
+  {-21,  9, 20, 12,  0, -3,  5, -9, 15,-13,  5, -5, -6, 24,  2,  9,
+    -5,  2, -7,  2,  5,  7, -5,  2, 15,  3,  1, -1, -4, -2,  7,  0 },
+  {-18, 16, 13, 15,  2,-10, 14,-11,  4,-11,  5, 12, 12, 20,  8, 30,
+     2, 11, -9,  7,  0, -3,-16, -5, -6,  5, -4,-21,  0,  5,  6,  1 },
+  {-26,  8,-13,  9,  6,-10,  2,-11,  7, -4,  6,-19,-11, -6,-12, 16,
+     0,  5, -7,  8,  5,  6, 17, -9, 10,-10,  5, -3,-11,  2,  4, 10 },
+  {-11, 17, -3, 22, -5, 18,  3,  1,  4, -5, 14,-27,  5, -7, -4, -5,
+   -10, 11,  1, 15,  1,  1, -6, -5, 10,-22, -7, -7,-15, 13, -4,  5 },
+  {-17, 14, -7, 13,  3,  0, 13, -6,  9,-14,-22, -1,  1, 19, 14, -3,
+     4,-13,-13,  2, -4,  8, -2, -2, 13,-12, 13,-12, -7, -5, -3,  6 },
+  {-17, 17, -1, 33,  6,  3,  9,-16,  3,-14, -8,  6,-17,  8,  3, 13,
+     8, -6,  3,  1, -2,  0, -2,  8,  4,  9, 13,-10,  4,-17,  0, -6 },
+  {-20,  7,  7, 21,  1, -3,  7, -3, -2,-12,  9, -7,  2, -3, 14,  1,
+    -1, -7, 12,-10,  5,-20, 11, -2,  0,-24,-17,  6,  6, -4,  3, -1 },
+  { -8, 10,  6,  7, -1, -6, 28, -6, 10,-33,  1,-20,  0,-12, 10,  1,
+    -6,  8, -3, -1,-10,  8,  5,  0, 10, -2,  8, 16, -5, -3, -7,  4 },
+  {-17, 13,  3, 15,  1, -5, 27, -5,  6, -6, 12,  2, -4,  8, -1, -3,
+    -2, 12,-15,  3,  4,  1,  2, -9,  0,-16,-21,  2, -4, 16, -7,  4 },
+  {-15, 20,  8, 17,  5,-14, 15,-11, 21,-11, 13,-13,  2,-15,-13,  1,
+    -5,  5,  2, 10, -9,  4, -1,  3,  2, -4, 13, -5,  1, -4,  5, -3 },
+  {-21,  8,  2, 16, -1,  2, 15,-16, 13,-12,-12, -7, -8,  2, -7, 11,
+    -8,  5,  2, -7, 16, -4,  1, -7,  3,-15,  6, -5, -8,  2, -8,  5 },
+  {-15, 17, -6,  3, -3,  3,  9, -7, 14,-23, 11,  1, -1,  4,  7,  6,
+    -1,-14,  7,  6, -8,  5,  1,-15, 10, -9,  2, -3, -1,  4,-10, -4 },
+  {-10, 18,  3, 11,  1,  4, 14,-14,  7, -4, 15,-10, 10,-11, 10, -4,
+     5,-14, 10,  4, 15,-12, 15,-13, 20,-15, 14,-15,  8,-11,  4, -6 },
+  { -7, 23,  2, 20,  7,  8, 19, -5,  9,-16, -8,-17, -5,  1,  5, -6,
+    -8,  1, -6, -4, 10,  6,  6,  2,-11, -4,  0,  2,  4,  7,  9, -4 },
+  {-15, 20, -5, 22, 11, -8,  9, -5, 10,-13, -8,  8,  2, -2, -3,  7,
+     6, 10,  1,  2, -5, -9,  1, 10, 16,-22, -7,  0,  7,  7,  6,  1 },
+  {-26, 19, -5,  3,  5, 25, 18, -5,  9,-14, -8, -6, -2, -6,  2,  3,
+    -8, -2, -7,  7, -3,  7,  3,  4, -8,  0,  1, -8, -4, -2, -2,  1 },
+  {-20, 14,-10,  6, -3,  7,  8,-32, -2, -7, -2,-10, 16,-12, -9, 15,
+    -2, -5, -6,  2, -7,  5,  9,  1,  6, -7, -1,  0, -2, -4, -7,  3 },
+  {-14, 16,  4, 11, -8,  1, 23, -4, 17,-13,-10,  1, 12,  9, 12, -4,
+     7, -1, -1,  5, -8, -6,  3,  3, -6, -3,-18,  0, 18, 20,  4, -2 },
+  {-33, 19,-10, 30, 15,  2, -3, -1, -4,-14,  7, -7, -1,  7, -8,  9,
+    -1, -3, -5,  2,  2,  4,  0,  5,  0,  0,  2,  3,  3, -3, -3,  4 },
+  { -6, 20,  0,  5, 17,-10, 18,-17,  9,-16,  4,-13, -6,  2,-14, 14,
+   -28,  9,-12, 25, -4,  7,  7, -8,  6, -6, -2,-10,  2,-11, -1,  2 },
+  {-12, 14, 12, 52, -3,  5, -5,  4,  8,-13,  2, -5, -4,  2, -2, -1,
+    -2,  3,  3,  5,  2,  3,  0,  1, -5,  2, -4, -3,  1, -5, -2,  0 },
+  {-13,  6,  9, 24,  0,  8, 14,-15, 18, -9,-11, -8,  3, 15, -2, -4,
+    -9,  4, -3, 12, 14,-13, 11, -4,  2, -4,  0, -6, -6, -6,-14, -1 },
+  {-10, 28,  3, 12,  9,  3, 11,-28,  6,-11, -7,  4,  0,  7,  8, -9,
+     0, -6,  0,-16,  4,  7,  4,  4,  7,  3,  4, -7,  0, -3,-10,  6 },
+  {-11, 14, -2, 19, -1, -1,  7,  9, -2,-27, 10,-14, 15, -4, 12, -4,
+     2, -2, -6, 12, -6,  0, -5, -4, -5,  1,  3,-11,  5, -9,  3, -8 },
+  {-18,  7, 13, 16, -4,  3,  9,-10, 10,-10, -3,-22, -4,-12,  3,-16,
+     0, -3,-16,  8,-11,  1, 10, -7, 15,  3,  0, -1,-13,  8,  1,  6 },
+  {-20, 10,-10, 10,  8, -1,  6,  0, 16,-12,  9,-10, -1, -5, -4,-13,
+    13, 16, -8, 12, -2, 14, 18, 13,  0,-16,  2, -5, -5, -5, -4,  3 },
+  {-14,  5, -7,-17,  5,-13, 23, 20, -4, -1,  1, -6, 13,  5, -1,  4,
+   -14, -2, -7,  8,  3,  2,  2, -7,  2, -1,  4,  7,  3, -9, -1, -5 },
+  {-19,  3,-24,-28, -9, -7, 19,  3,  2, 19,  7,  5,-13,  8,-15,-17,
+     3,-11,  4, 13,  3,  2, -1, -3, -4, -4,  2,  0, -5, -6,  6,  2 },
+  {-17, 18,-30,-20, -2, -3,  1, 15, -1,-11,  6, -4, 11, 11, -4, -5,
+   -10,  0,  0,  1,  3, -7,  8,  2,  5,  1,  5, -5,  1,  6,  4,  1 },
+  { -6,  1,-30,-25, -1, -8, -2, -9,-17, 16,  3, -1, -2, -9, -6, -7,
+    -3, 12,  6, -4,-10,  0, 10, -8, -6, -5, -3,-11, -4,  0, -1, -3 },
+  { -1, -1,-34,-28,  1,-10,  2,  9,  4, 16,  2,  6, 14, 17,  0,  7,
+    -4,  4,  4,  4,  0,  1, -1, -5,  8,  1, -4,  1, -9, -2,  5,  6 },
+  {-11, 14,  1,-31, -7,-24,  9,  7,  6,  5,-13,  1, -1,  3,  4, -1,
+    -2, -8, -6,  3,  5, -4, -6,  7, -2,  5,  3,  3,  0,  0, -5,  2 },
+  {-25,  8,-11,-18,  1, -4,  8, -3, -4, 15,  6, -5,  8,  2,  3,  4,
+    -4,  5,  6,  8, -7,  6,  1,-11,-15,-13,  9, -4,-14, 10, 12,  7 },
+  {-20, 11,-15,-25,  3,  4, 18, 13, -4, -5, -9, -1, -5, -2, -2, -7,
+    16,  5, -4, -5, -7, -2, -3, -9, 11, -2,  0, -7,-17, -6,-11,  6 },
+  {-11, 18, -5,-20,-15, -3,  9, 11,-20, 12,  5,  5, 11, -3,  7,  1,
+    10, -6, -3, -3,  3,  3, 14, -7, 10,-17,  9,-11, -2, -6,  7,-12 },
+  {-20,  8,-14,-17, -9,-13, -3,  0,-27,-14, -3,-14,  4,  3,  6, -6,
+     7,  4, 23,  9, 11,  9,  3, -4,  9,  2,  4, -1, -6,  1, -8,-11 },
+  { -9, 14,  2,-37, -7, 13,  6,-11, -6,  9, 18,-11, -6,  2, 12,  4,
+    -1,  3,  1, -2, -2,  1, -9, -4, -2, -3,  3,  5, -6,  0, -2, -8 },
+  {-29,  8, -1,-13, -2,  8, 23,  2,-10,  7, 13, -6, -5, 11, 13,  0,
+   -10,-13, 11,-12,-10,  6,  4,  6,  4,  3,  6, -5, -9, -2, -1,  3 },
+  {-18,  6,-10,-55, -4,-11, -2,  0,  1, -3, -9, -6,  3, -2, -1,  6,
+     3, -1,  3,  1, -4, -7, -2,  6,  3, -2, -1, -3, -2,  0,  4,  1 },
+  {-14,  5,  3,-21, -8,-16, -4, -2,-11, 27, 15,-20,  3,  0,  1,  1,
+     2, -5, -5,  4,  1, -9,  5, -3,  3,  0, -4, -2,-11, -4, -3,  7 },
+  {-17, -1, -9,-17, -8,-18, 12,-13, -9, 13, -3,  3,  3, -3,  1, -2,
+     0, 16, -9,  6, 12,  9,  5, 11,  2,-15,  1, -4,-16,  7, -4,-12 },
+  {-18,  8, -6,-11, -8, -7, 13,  7,  1,  6,  8, -1, 21, -4, 14, 15,
+    18, -4, -3, 15,  0,  9,  4,  7,  3, -1,  9, -2,  0,  7, -8,  2 },
+  {-10,  7,-18,-29,  3, 12, 12,  9, 11,  4, -1,-15,  1, -1,  8, -2,
+    -2, 10,-15, -1,  0,  6, 12, -6, -1, 10, -6, -3,-11, -4,  9, -6 },
+  {-14, 14, -9,-21,-12, -2, -1, -7, -5,-10,  5, -8,  0,  6,  9,-11,
+    11, -3, -5,  3,  8, 15, -2, -4,-22,  4, -6, 12,  2, 13,  6, -7 },
+  {-12, 11, -5,-29,-25,  4, 12,-13,-11, -7,  4,  2,  2, -5,  5,  8,
+     7, -5, -5,  6,  3,-10,  1, -6,  6, -6, -5, -1, -2, -4,  7,  6 },
+  {-15, 11, -5,-16,  0,-13, 26,-23, -6, -3,  5, -2, -2, 21, -6, -3,
+    -5, -1,  6, -1,  0,-13,  2, -3, -9, -1, -4, -3,  5, -4, 12,-16 },
+  { -9,  9, -1,-17, -3, -6, 12,  6,-18, -2, 11,-14, -6,  3, 14,-12,
+   -11, -5, 14,  2,  5, -8, -4,-11,  2, -5, 16,  6, -7, -4,  8, 13 },
+  {-13,  5,  3,-28,-14,  0,  6, 23,  5,  4, -1,-17,  1, -3,  0,  0,
+     5,  4,  0,-18, 14, 10,  4,  2,  5, -2,  4, -3,  2,  0,  2,  0 },
+  {-15,  4,-13,-16, -3,-12, -2,  2,  7, 10,  9,  3, 11,  4, 23, 14,
+     9, 16,  4,  1,-12, -3,  4, -7,-15, -7,-10,-14, -6, -8, -1, -6 },
+  { -7, 10, -5,-10, -3,-13, 16, -1,-12,  7, -3,-12,  2, 13, 13,  2,
+    17, 15,-13,  1, -5, -2,  3, -1,  1, -3,  6, -3,-12,-16,  7, -7 },
+  {-11, -5,-12,-30, -6,-22,  1,  4, -6, -3, 12,  6,  7,  0, 16,  6,
+    -2,  0,-22, -2, -9,  2,-13,  8,  6, -8,  4, -7, -1, -6,  4,  6 },
+  {-14,  5,  1,-27, -4,  2,  1, 14,-11, -7, -8, -4,  1,  8,  0, -6,
+   -13, 11,-12, -7, -5,  1, 10,  7,  3, -2,  0,  6, -8,  2, 10, -1 },
+  {-10, 10,-25,-13,-20, -4, 19,  3, 13,  5,  5,  7, -8,  2,  4,  2,
+     3, -1, -1, -9, 14, 10,  9, 14,  3,  3, -6,  0, -5,  4,  1, -1 },
+  { -9, 15,-18,-17,  4,-11,  6,  7,-12,  8, -1,-11,  2,  3,  7, 16,
+    -3, -9,  7,-12, 23,  0,  6,  7,-14, -9,  8,  1, -2,  6, -2, -1 },
+  { -6,  9,-16,-26,-14,-11,  9, -6,  5, -2, 13, 17, 21,  7, 18,-19,
+     6,-23, -2,-15, -2,  2,-10, -8,  2,  1, -2,  4, -3, -4, -5, -4 },
+  {  0,  6, -5,-28,-17,-32,  2,-10, 11,  3, -5,  9, 10,  3, 11, 11,
+    -3, 12, -2,  2,  4, -6,  9, -4, -4, -4, -4, -9,  2,  0,  2,  4 },
+  {  0, -8,-18,-34, -9, -7, -4,-11, 10, 15, 11, -1, -8, 15,  6,-13,
+     9,  2, -4,-12,  0, -1, 19, 12,  6,  5,  0, -3,-10,-12,  3, -5 },
+  {-10,  6, -9,-17,-12,-11,  9, -6, 11, 11, 18, -7,  0, 16,  4,  2,
+    -6,  3,-12, -1,  0,  1, -5,-22, -2,-12,  0,  6, 17,  5,  5,  6 },
+  { 12, -5,  7,  1, -5, -2, -1,  2,  2, -4, -3, -3, -3, -2,-29, 11,
+     5,-13,-73, 24, 12,  4,-14,-10,  5,  1,  0,-11, -7, -7,  7,  3 },
+  { 10, -3, -1, -3,  4,-11, -5, -2, -8,  7,  9,  2, -8, -6,  6,  7,
+    21, 17,-54, 47,-14,-10, 14, 19, 13, 21, -4,  3,  1,  2, -4,  2 },
+  {-12,  4,-16,-12,  5, -9, -4, 19, -7,-22,-22,-17,  3,  0, -6,  8,
+    23, -4,-55,-28,  2,-26,  2,  1,  4,  0,-13,  6,  0, 10, -7,-11 },
+  {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  3, -1,
+    35, -1,-67,-35,-24,-24, -6,  2,  2, -2,  1,  3,  2,  0, -1,  1 },
+  {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  5,  0,
+    41, -4,-73,-15, 18,  4, 17,  8, -1,-16, -1, -2,  1,  0,  0,  0 },
+  { -4, -4,  4,  6, -1,  2,-16,-10,-15,-10, 21, -2, -6, -2, 14, -7,
+    10, -5,-55, 34,-12, 11,-13, -2,  2, 28,-26,  0,  7,  4, 21, -7 },
+  {  2,  1, 15,-22, 10, -3, 14, -6, -2, 15, -2, -7, 20,  6,-15, -7,
+    23, 10,-60,  8, -4, 29,-22,  2,-13,  9,-10, 12, -1, -3,  4,  7 },
+  {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -1,  0, -1, -2, 11, -5,
+   -21,-11,-60,-27,-17,-39,  6, 36,  0, -8,  2,  2,  0,  0, -2,  3 },
+  {  2, -5,  9,-17, -1,  2, -3, -6,  8, 12,  7, -6,-33,-11,-14,-40,
+    10, 36,-46,  0,-19,  5,  0,-10,  3, 12, -6, -8,  6,-12, -7,  1 },
+  {  1,  1,  0,  0,  0,  0,  1,  0,  0,  0, -1,  0,  1,  0, -2,  0,
+     4, -2,-87, -3, -2,  2, -2, 20,  2,  6, -1,  6,  0,  0,  2, -1 },
+  {  1,  0,  0,  0,  0, -1,  0,  0,  0,  0,  0,  0, -1,  0,  0,  1,
+     1,  7,-76, 41, -7,-24,  0, -6,  3,  6,  0, -2, -1,  1,  0,  0 },
+  {  0, -3,  4,  2,  3,  2,  2,  0,  3, -1,  4,  0, -1,  4, -2, -4,
+   -32,-11,-64,-29, -9,-43,  2,-11, -1, -7,  0, -4, -2, -2, -2,  2 },
+  { 10,-20,  3, -3, 13, 13,  0, -4,  2,  7, -8,  7, -2,  2,-20,-20,
+   -19,  3,-47,-18,-16, -6,-15,-42,-17, 14, -6,  8, 12,-10, 11,-12 },
+  { -3, -2, -2, -1, -1,  4, -3, -1, -6, -2,  3,  2, -3,  6, -1, -9,
+    10, 13,-68, -9, 26,  3,  5,  3,-21, 10,-15, 21,-22, 19, 11,-14 },
+  {  1,  5, 18,-19,-29,-13, -2, 18,-10, 20,  2, 10,-10, 11,  1,  8,
+   -16,-17,-41, 10,-14,-25,  0,-14,-19, 17,  7,-12, 14,-11, 14,  5 },
+  {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  3, -1,-43,  5,
+     6,-12,-48, 19,  8,-38, -8, -3, 22,-21,-10, 15, 20, -9, -5,  8 },
+  {  0,  0,  0,  0, -1,  1, -1,  0,  0,  0,  0,  0,  0,  0,  6, -3,
+    22,-14,-71,-24, -2,-33, 23,  7, -8,  7, -3,  2, -4,  1, -8, -2 },
+  {  1,  0, -1,  2,  0, -2,  0,  0, -1,  0,  4,  0, 26, -1, 10,-11,
+   -17,-32,-58, 14,-14,-11, -2, 15,  2, -8, 12, 10, -9, 13,-33,-14 },
+  { 15,-17,-19,  7, -8,-15,-32,-22,  7, 12, 18,  0,  0,-15, -4, 16,
+    37, -2,-46, 11,  2, -8,-10, -8, 14,  9, -4,  5,  7,-17,  4,  3 },
+  {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -2,  0,
+    -5,  3,-85, 23, -9,-17, -2, -2,  0,  0,  0,  0,  0,  0,  0,  0 },
+  {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -2,  0,
+    -5,  3,-85, 23, -9,-17, -2, -2,  0,  0,  0,  0,  0,  0,  0,  0 },
+  {  1,  0,  0,  0,  0, -1,  0,  0,  0,  0,  0,  0, -1,  0,  0,  1,
+     1,  7,-76, 41, -7,-24,  0, -6,  3,  6,  0, -2, -1,  1,  0,  0 },
+  {  0, -3,  4,  2,  3,  2,  2,  0,  3, -1,  4,  0, -1,  4, -2, -4,
+   -32,-11,-64,-29, -9,-43,  2,-11, -1, -7,  0, -4, -2, -2, -2,  2 },
+  { 10,-20,  3, -3, 13, 13,  0, -4,  2,  7, -8,  7, -2,  2,-20,-20,
+   -19,  3,-47,-18,-16, -6,-15,-42,-17, 14, -6,  8, 12,-10, 11,-12 },
+  { -3, -2, -2, -1, -1,  4, -3, -1, -6, -2,  3,  2, -3,  6, -1, -9,
+    10, 13,-68, -9, 26,  3,  5,  3,-21, 10,-15, 21,-22, 19, 11,-14 },
+  {  1,  5, 18,-19,-29,-13, -2, 18,-10, 20,  2, 10,-10, 11,  1,  8,
+   -16,-17,-41, 10,-14,-25,  0,-14,-19, 17,  7,-12, 14,-11, 14,  5 },
+  {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  3, -1,-43,  5,
+     6,-12,-48, 19,  8,-38, -8, -3, 22,-21,-10, 15, 20, -9, -5,  8 },
+  {  0,  0,  0,  0, -1,  1, -1,  0,  0,  0,  0,  0,  0,  0,  6, -3,
+    22,-14,-71,-24, -2,-33, 23,  7, -8,  7, -3,  2, -4,  1, -8, -2 },
+  {  1,  0, -1,  2,  0, -2,  0,  0, -1,  0,  4,  0, 26, -1, 10,-11,
+   -17,-32,-58, 14,-14,-11, -2, 15,  2, -8, 12, 10, -9, 13,-33,-14 },
+  { 15,-17,-19,  7, -8,-15,-32,-22,  7, 12, 18,  0,  0,-15, -4, 16,
+    37, -2,-46, 11,  2, -8,-10, -8, 14,  9, -4,  5,  7,-17,  4,  3 },
+  {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -2,  0,
+    -5,  3,-85, 23, -9,-17, -2, -2,  0,  0,  0,  0,  0,  0,  0,  0 },
+  {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -2,  0,
+    -5,  3,-85, 23, -9,-17, -2, -2,  0,  0,  0,  0,  0,  0,  0,  0 },
+  { 16, 65, -2, -2,  4,  3,  0, -7,  3,  1,  3,  1,  0,  5,  1, -5,
+     0,  2, -1,  3,  0,  0, -1, -2,  6,  0, -2,  0,  0, -1,  1,  1 },
+  {  5, 37, -4,  8, -4, -1,  9, 17,  6, -7,  5, -1, 11,  6, -4,  7,
+    -2,  4,  1, -3, 11,  3,  3, -9,  6,  0, -2, -4, -5,  4,-12,-11 },
+  { 15, 24,-14,  2,  6, 17, 26,  5,  8, 11, -9, -7, -6, -8,  3, -5,
+     9, 10, -3, 10,  0,  1,  4, -9,  4,  9,  3,  0,  4,  0, -5,  3 },
+  {  9, 36, -9, -8,  7,  7,  4,  3, -1,-16, -2,  7, -5, -6,  6, 12,
+   -11,-12,  9, -1, -3, -9, 12,  6, -6,  2,  2,  5,  0,  5,  6, -6 },
+  { 25, 39, -5, 24,  3, 10,  3, -6, 13, -8,  3, -7,  2,-10, -5,  2,
+    -2,  3,  5, -2,  1,  5, -2,  3, -4,  1, -5, -4,  0,  1, -2,  0 },
+  { 16, 27, -1,  0,-14,  6,  4, -5,  7, -2, -6,  0, -3, -5,  2, -1,
+    -1,-19,  5, -8,  0, 11, 12,  5,  0,  3, 10,  6,-14, 14,-13,-15 },
+  { 12, 23,-14,  2,  1,  4, -3, 16,  7, -8,  2, -8,  8,  6, -8, -7,
+    -3,  0,  2,  8,-13,  7, 13, -6, -4,  6,-13,-16, 14, 11, -7,  5 },
+  { 16, 28, -7, -1,  6, -3,  9,  0, -7,  3,  0,  3,-12, 20,  8,  9,
+     8, 23,  8,-13, -2,  4,  9,  3, -5, 13,  5, -2, 12, 14,  5, -1 },
+  { 19, 37, 19,  5,  7,  5, 10,  5, 19, 10, 14,  0,  2,  5,  1, -4,
+    -4,  2,  2, -5, -2, -1,  2, -6, -4, -4, -5, -3,  2, -2, -2, -2 },
+  { 24, 21,  1,-11,-10, 17,-14, 14,  6, -1, -6, -1,  0,-13, -1,-12,
+    -2, -5,  6, -4,-12, 14,  5, -2, -8, -8, 15, -7,-30,-12,  4,  0 },
+  { 11, 26, -3,  3,  5, -1, -2,  3, -2, 10, 15, -4, 10,-28, 10,-17,
+    -8,  1,  2, -7, -1, -6,-15, -1,  4,  5, -7,  9,  0, -5, -4,  4 },
+  { 18, 32,  1,  2, -7,  4, 15,  2, -9, -2, 12,-11,  7, 11, 13,  2,
+     0,  5,  9,-10, 16,  3, -3,  5, -9,-23,  2, -2, -1,  5,  2, 11 },
+  { 35, 24,-20,  2,  4, -1,  5, 14,-10, -9,  8, -7,  0,  5, -7, -7,
+    11,  1,  5,  3,  2,  0, -2,  3,  0,  1,  4,  0, -2, -8,  0, -4 },
+  {  9, 35, -1,  2, -1,-19, -3, 12, -1,  8,  8,-13, -1, -2,  2,  5,
+    -8, -1, 13, -2, 11,  1,  0,-10,  0, -3, -7,  2,  1,-12,  3, 12 },
+  { 20, 27,-12,-12,  7,  4, -1,-13, -1, -9,  2, 13,-11,  5,  7, -9,
+     9,  1,  1,  8, -9,  0, -6,  7,  4,  2, -2,  7,  3, -2,  1, -9 },
+  {  8, 37,-20, -5,  0,-21, 10, -8,  3, 19, -9,  7, -3, -8, 10, -2,
+     0,  5,  6, -4, -2, -1,  0, -7,  6,  1,  0,  4, -5,  6, -8,  2 },
+  {  8, 27,  1, -3, -5,  1,  6,  0, 15,  2, 17, -1,  3,-17, 10,  5,
+     5, -6, -6,  6,-10, 18, -5,  0,  0, 13,  7, 10, -5, -6, -2, -4 },
+  { 14, 29,-20, -4, -3,  1, -5, -1,  2, 12,-10, -3,  4,-18,  4, 14,
+    -4, -1, -9, 15, -2,  2, -5, -3,  2,  9, -2,-14, -3,  4, -4, -7 },
+  { 23, 23,-23,-11, 27,  4,  4, -1,  7,  0, -5,  9,  2,-11,  3,  7,
+    -2, -5,  2, -7, -7, 13, -3, -6,  2,  3,  3, -4, -1, -8,  5, -2 },
+  { 16, 26, -6,  8, -9, -1, -2, -1, -8,  4, -2,  0,-12,  9, -1,  0,
+   -17, -9, 30, -5,-15,-16,-13,  0, 10,-11, -7, -3, -1,  0,-11, -2 },
+  { 12, 32, -4, -5, 10, 19,-10,  4,-12,  5, -6,  9,-12, -6, -6, -8,
+     4,  1,  3,  0,  8,  0, -3, -4, -7, -4, 10,  8,  6,  5, -1,  4 },
+  { 46, 42, -3,-14, -2, -6,  6, -2, -5, -1, -3, -3,  1, -1,  3,  1,
+     1,  4, -1,  2,  3,  1, -2,  6,  0, -1, -2,  4, -2, -1,  2,  2 },
+  {  9, 33,-13,  4,-11,  3, -8, 22, 12, -2,  4,  0,-16,  5,  4, -1,
+     7, -6, -9,  1,  7,  5,  0, -5,  5, -1, 10,  3, -2, -1,  3, -2 },
+  {  9, 30,  6, -3,  6,  1, -7,  5, 11, 14,  7,  1,  0,  2,  2, -1,
+     8,  7, -6,-13,-10, -2,  1, -6, 10,  7,  6,  5, -2, -5, -1,-16 },
+  {  9, 28,-11,-10,  9,-10, 15,  8,  4,  9, -4, -7,  0, -5,  9,  8,
+    -7,  2,-15,-23,  4, -4,  4, 16, -8, -3,  0, -8, 14,  5, -3, 15 },
+  { 17, 26, -5, -5, -1, -8, 20, 18, -7, -2,  4, -7, -8, -5, -4, 16,
+     0,  0, -7, -2,-13, -5, -2,  3, 12,  1,  3, -5,  2,  2,  0, -1 },
+  { 11, 37,  7,-23,  6, -1, 15, 13,  4, -9,  7,  5,  3, -3, -5, -8,
+    -2,  3, -5, -1, -8,  7,  2, 13,  1,  3,  0, -3, -1,  2,  0, -2 },
+  { 21, 33,  7, 20, 21,-10,  6, -5, -5, -6, -9,  2, 10,  0,  8, -4,
+    10,  2, -2, -2,  0,-10, -6, -2,  0, -5,  3,-11,  3, -9, -3,  1 },
+  {  6, 30,-15, -8, 16,  1,  4,  6,  4,  5,  8, -3,  8, -9, -1, -6,
+     8,  2, -2,  4, -2,  5, 11,-21,  3,-10, 16,-11, 24, 10, 14, -6 },
+  { 15, 36, -3, -9,-20, 12,  0, -7,-18, -4, -8, -9,  9, -7, -3, -1,
+     2,  7, -5, -8,  6,  2,  2, -1,  7,  1,  1, -3,  3, -4, -8,  1 },
+  { 16, 34, 21,  3, -9, 10,  7,  9, -7,  1, -4, -9, -4, -5, -5,  3,
+     3,-19,  1,  5,  4, -2, -6, -5,-10,-11, -8, -2,  2, -5, -8, -7 },
+  { 28, 29, -3, 18, -2,  0, -6, 12, -2, 10,-11, -4,-13,-12, -6, -4,
+     0,  4, -1, -8,  6,  4, 12, 11, 10, 10, -3, -6,  1,  2,  1,  7 },
+  {  3,  8, 22, -8,  3, 36, -8, -1,  9,  6,-13,-14,  8, -1,  1,  2,
+    -2, -8,  0,  3,  1,  2, -1,  5, -1, -8,  0, -2,  2,  2, -1,  1 },
+  {  0,  6,  0,  0,  4, 13, -7,-16, -6, 15,-14,-21, -9,-10,-10, -6,
+   -21,  5,  4,  2, 12,  4, 12, 11, -4, -6, -6,-10, -7,-18,  1,  4 },
+  { -1,  3, 10,  1, -1, 15,  4, -7,-16,  3,  0,-22, 10,  2, -3, -2,
+    13,  5, -8, 16, -5,  4,  0,-11,-10,-22,  0, -4,-17,  5,  2,  1 },
+  { 12,  8, -4, -9, 14, 40,-21,  0,  1,-15,-10,-12, 12,  6,-10,  2,
+     8,  6,-12,-10,-11,  1,  0,-11,  2,  1, 13,  0,  6,  3,  8,  4 },
+  {-10,  3,  5, -4, -3,  3,  0, -9,  2,  8,-22,-23, 17,  8,-17, -3,
+    14, -8, -4,  1, -8,  3,  0,  5, -1, -3, -2, -4,  1,-10,  0, -2 },
+  {  0, -1,  5, -7,  4, 12, -2,  0, -7,  2,-16,-15, 12, 21, -7, -4,
+     7, -7,-11,-15, -7, -9, -5, -8,  0, -6,  8, -3, -8, 22, -7, -9 },
+  {  7, 19,  4, -9, 24, 22,  2, -6,  8, 13,-14,-20, -4, 11,  8, -4,
+    -1,  2,  0, -7,  5,-17, -3,  3, -6,  5,  3,  4, -5, -7, -3, 14 },
+  { -2,  6,  2,  8, -2,  5, -4, -2,-10,  3,-45,-30, -3, -3,-12, -4,
+    -3, -3, -1,  9, -6, -6,  5, -4,  0,  5, -1, -2, -1,  0, -6, -1 },
+  { -3, 14,-16,-10, 10,  0, -2,-40, -9, 12,  2,-19, 15, -4,  4,  3,
+     3, -4,  7,  1, -4, -5,  0,  4, -1,  0, -9, -2, -4, -1, -2,  0 },
+  {  7, 16,  2, -7,  8,  2,  0,  1,  5, 21,-10,-26,  7,  2, -9, -7,
+    -3,-16,  8,  5,  5, -6, 10,  4,-14, -6,  5,  3, -2, -2, -4,  1 },
+  { -9, 14, -1,  3,  3, 11,  1, -5, -3, 13,-16,-18, 20,  6, -5,  0,
+    -3,  2,  8,  4,-19, -9, 12,  0, -8,  2,  2,  1,  6, 13, -7,-11 },
+  {  2,  5, 16, -4, 19, 15,  4,  0,-11,  7,-10,-10,-16, 18,-11,-12,
+    -9, -4,  7, -4, -4,-17,  1,  1, -8, -3, -3,  5, -2, -6,-11, -5 },
+  {  2, 12,  0, -9,-10, 14,  6,  2, -3,  2,-12,-28, 12,  1, -1,  2,
+     0, -3, -4,  7, 16,  5, -7,  8, -4, -3, -1,  3,-12,  4,-17, -5 },
+  { -4,  7, 11,  6,  1, 14, -4, -6,  5,  5, -6,-24, 23, -9,-15, 13,
+    -7, -9,-15, 10, -1,  8, -5,  1, 12,  6,  2,  0,  4, -2,  9,-10 },
+  {  1,  5, 11,  3,  6, 12, -3,  8,-21,  5, -7,-20, 12, -2, -9, -3,
+    17, -7, -8, -9,-14,  3,-13, 18, -8,  9,  2, -8,  4, -8, -5, -2 },
+  { -3, -3, -1,  5, -2, 15,  3,  2,  1, -8,  1,-39, -6, 13,-13,  0,
+    -2, -5, -6, -3,  0, -5, -2, 15, -9,  5, -3, -6, -2,  7,  0,-13 },
+  {  2,  8,  5,-12,-13, 22,  8,-16, 11,  5, -2,-32, -2, -4, 11,  5,
+     5, -6,  1,  3,  1,  5,  3,  6, -5,  4,  4, -8,  8,  4,  1,  3 },
+  { 13,  9,  5, -4,  9, 18,-11,  2, -1, 15,-10,-19, -2, 14,  0,-10,
+     1,  1,-18,  3,  2, -6, -8, 20,  7, -8, 16,  9,  9,-13, -3, -2 },
+  {-13, 11, 11, -9,-10, 13, -3,-18,  2, 10,  5,-21,  6, 15,-11,-21,
+     3, 14,  0,-12,  9, -1, -2, -4,  3, -3, -9, -8, -5, -2, -8,  2 },
+  {  3,  3, 11,  4,  0, 13,  1, -8, 10, 13, -6,-26,  2, 12, -3, -5,
+    12, -2,  1,  8, -7,-17,-19,  5, 10,  7, -3,  2, -3,  0,  5,  0 },
+  {  5,  0,  3, -3, -9,  5,-15, -5, -5, 17, -5,-31,  0, 13, 13,  5,
+    -1, -6,-14,  7, -8,  9,-14, -2,-16, -4, -4, -6,  6, -6,-10,  6 },
+  { 13,  3,  1,  7, -3,  4, -1, -2, -1,  4, -8,-32, -1, -4,  0,  3,
+   -10,  7, 10,-10,  4, -1,  6,  2,-16, -9,  4,  3, 13,-23, -3, -4 },
+  {  4, 11, -4, -9,  4, 11,-12,-12,-12,  6,  1,-28, -3, 14, 18, -2,
+   -12,  7, 15, -3, -5, -7, -3,  2, -6,  4,  4, -2, -5, -3,  2,-13 },
+  {  8,  7, -7,  0, 13,  7, -8, -7,  8, 36,-10,-22,  3, 23, -3,-10,
+    -3, 11,  1, -7,  3,  3, -1, -7, -4,  2,  3,  2,  5,  3, -4, -1 },
+  { -1,  1, 13,  1, -6, -1, -6, -9,-18, 17, -5,-37, -1, -1, -6, -4,
+     1, -6,-15,  2, 17, -9,  0, -3,  0,  4,  0, -5,  0,  4,  1, -5 },
+  {  0, 14,  5,  0, -7,  2, -6, 17, -6, -9,  7,-16, -5, 23,-14,-13,
+     8,-15, 11, 10,-11,-13,-33, -5, -2,  1,  6,  8,  0,-13, -9,  5 },
+  { 11,  7, -2, -8,  9, 11, 25,-14,  7,  3, -1,-33, 14,  8, -6,-19,
+     3,  3,  2, -1, -3, -1, -2,-10, -3,  1,  2,  1,  4,  2, -3,  4 },
+  { -2,  8,  4, -2,  9, 13, -4, -2,-15, -3, 19,-37,  9, 25, -9,  2,
+    -5, -2, -2, -4,  4,  2,  2,  0,  3,  3,  3,  5, -2, -3, -4, -3 },
+  { 10, 13, -1,-15,  4,  6,-18, -4, 25,  1,-23,-17, 15, 13, -8, -8,
+     7,  4, -5,  3,  6,  9, -7,  6,  0, -5,  8,  0, -6, -1, -2, -2 },
+  {  1,  3,  9, -5, 27, 15, -9,-31, -1, 23, -2, -9,  1,  8, -1, -7,
+    -2, -8, -4, -4, -2, -1,  3,  5,  0,  0, -1,  1, -7,  7, -3, -3 },
+  { -8,  7,  3, -6,  8,  3,-11, -2, 36, 14,  1,-30,  6, 10,-12, -6,
+    -6, -2, -4, -3, -5,  0,  9,  4, -5, -5, -8, 12,  4, -3,  1, -8 },
+  { -2,  9, 33,  0, 12, -3, -7, -4, -4, -1,  6,-25, 11, -6, -9,-11,
+    -2, -4, -2,  6, -1, -3, -6, 15, -6,  3, 10, -4,  1,  0,  5,  8 },
+  {-22,-21, -9,-19, -5, -7,-12,-15, -8,  9,-19, 14, -7, -4,  5, -8,
+    -2,  7,  1, -3,  4, -4,  6, 11,  2,  6, -3, -5,  2, -2,  0, -3 },
+  {-32,-13,  3,-24,  3, -8,  4,  1,-10, 14,-15,  0,  4,  6, -1,  6,
+     7, -1,  6,  4, -3,-17,  1,  4, -6, -1,  1,  0,  3,  3, -7, -4 },
+  {-32,-11,  7, -8,-12, 13, -5,-22, -4, 12,-16,  2,  0,  4,  0,  1,
+     0,  6, -5, -8,  2,  6,  5,  0, -3, -6,  5,  6,  5,  5, 13, -4 },
+  {-44,-33,  6, -4,  2,  0, -9, 10,  3,  4,  7,  0, -1,  7,  5,  1,
+     1, -3,  1,  6, -1,  0,  2,  3, -4,  0,  0,  1,  0, -1, -2, -1 },
+  {-30,-18,-24, -8,  5,  0, -2, 14,  7,  0,  1, 12,  6,  4, -9,  7,
+     5,  7,-11, -5,  1, -8, -1,  2,  2, -9,  7, -1,  7,  5,  6,  6 },
+  {-22,-20,-13, -9, 20, -3, 10, -8,  6, -4,  2, -7, 10,  8,  0, -1,
+     2, -3,  6,-19,  2,  4,  3,  3, -7,  2, -1, -6,  1,  1,  6, -2 },
+  {-27, -8, -1,  3, -1,-11, 24,  4, -1,  1, -8,  8,  5,-11, 15, -3,
+   -15, -1, -1,-13, -1,  1, -5,  5,  2,  3, -9,  0,  4,  3, -7,  6 },
+  {-33,-16, -1, -8, 10,-23,  6, 13, -1, -3, -9,  0,  5, -7, -5,-12,
+    -2,  3,  3,  6, -2, -3,  2, -3,  9, -6, -3, -2,  0,  5, -3, -4 },
+  {-22,-17, 11, -3,  3,  1, -1, -5, 17,  2,-15, -2, 10, -9,  6, 14,
+   -16,-12, 20, -1, -7,  6, -3,-12,  1, 10,-10, -1,  7, -3, -1, 10 },
+  {-28,-13,  1, -3, -1, -1,  0,  3,  3,  5,  1, 10,-10, -3,  7,  2,
+     4, 19, -1, -1, 10,  5, -8,  1, 11,-15, -4, -3, -5,  4,-13,  3 },
+  {-22,-13, 42,-20,  5,-13,  7,-11,  1,  1, -1,  1,  6,  3,  6,-11,
+     3,  3, -2,  0, -4,  4, -3, -1, -5,  2,  0,  0, -9, -1,  4,  4 },
+  {-26,-15, -2, -6, -4, -2, 16,  8, 21,  8,  1, -3,-10,  7, -8,-12,
+    -5, 12, -9,  3, -2, -3, 18,  1,-12,-15, -4,  5, -3,  0, 12,  7 },
+  {-26,-16,  5,  6, 14, -3, 15,  6,  1, -7,-13, 16,-15,  5, 11, -2,
+     9, -7, -4, -2,  0,  0, -2,  7, -8, -6, -5,  2,  7, -3,  2, 12 },
+  {-31,-17, -8,-30,  4, 14,  6, -6,  6,-11,  0,  3, -4,  0,  0, -4,
+     0, -4,  1,  4,  3,  4,  0, -5,  3,  2,  2,  0,  2,  1,  3,  5 },
+  {-61,-10,  4, 10,  4,  7,  0, -3,  0,  1,  0, -3,  0,  1,  0, -2,
+    -1,  1,  2, -2,  4, -3,  1,  1, -1,  1, -2, -4, -4,  4,  0,  0 },
+  {-28,-13, -8, -4,  3, -3,  2,  1, 11, 14,  3,  9,  1, 13,  3,  5,
+    -3, -2, -2,-12,-14, -9,-11,-15,-12, -5, -4,-12,  3, -3,  0, -5 },
+  {-41,  0, 12,-24, 13,  4,  5, 16, -5, -4,  0,  0, 13, -4,  1, -9,
+     9, -6, -1,  6, -2,  5,  2,  9,  6, -9, -8,  8, -2, -3, -6, -4 },
+  {-26,-19, -2,-15,  4,-14,  6,  0, 26, 20,  8,  9,  9,  3, -4, -5,
+    -8,  1,  0, -1,  5,  9,  3,  4,  4,  7,  1,  3, -2, -2,-10,  0 },
+  {-29,-18,  9, -4,  1, -5,-14,-12,  5,-10, -5,  4, -5,  0, -1, -1,
+     4, -5,  7,-16,-11,  2,  7,-15,  2, -4,  6, -4, -6,  7, -3,  7 },
+  {-27,-16,  9,-14,  3, -8,  9,  0,  7, -4, -3, -7,  0,-10, -1,  2,
+     1, -2, 15,-10, 14,  7,  6, 17,  3, -4,  3,-10,  8, -8,  3, 11 },
+  {-21,-20, -8, -8,  4,  5, -3, -2,  0, -5, 14,-10, 11, -4, 13,  0,
+     5,-11, 19,-18, 18,  3, -5, -3, -4, -8, 11,-10, 10,  3,  4, -9 },
+  {-35,-15, 13,-12,  4,  0, -2, -4,-12, -3, -8,-24, -7,  1,  7,  8,
+    -3,  0, -2, -1,  3, -2, -2, -6,  8,  1,  0,  1, -6, -1,  2, -6 },
+  {-19,-14, 13,-10,  9, -1,  1,  3,-12,  5,-16,  7, 13,  9,  4, -4,
+     6, -5,  4,  9, -3, 17, -4, 12,-11, -6, -5, -6, 13,  2,  7, -9 },
+  {-34, -8, -4,  1,  2, -1,  3,  6,-20,-11,  8, -1,  4,  2, -9,  4,
+    -4, -5, 16, 10, -4, 14,-13,  1, -6,  0,  2,-10,  0, -3, -3,  7 },
+  {-36,-10, -8, -3,  2, -2, 14, -4, -1, -7, -4, 10, -1, -3, 15,-11,
+     0,  2,  3, -1,  4,  0,  8, -1,  0, 18,-11, -5, 15, -5, 13,-12 },
+  {-22,-13, 14,-20, 15, 25, 16, 10,  8, -2,-10, -5, -1, -8, 11,  8,
+    -1, -2, -4,  1,  2, -1, -7,  0,  0,  0, -3,  0,  2, -1,  0,  2 },
+  {-31,-22,  7,  6, -2,  5,-20, 14, -6,  7,  0, 14,  3, -7,  3, -6,
+    -2,  1, -3, -5,  1,-10,  1,-24,  6, -2,  3, -7,  1, -7,  8,  7 },
+  {-25,-20, -3, -9, 10,  6, 12,  7,  5,  4, -3,  6, -1, -5, -6, -8,
+     3,  5,  6,  5,-10, 10, -4,-15,-15, -2, -9,  2, 18,  1,  8, 12 },
+  {-24,-19, -2, -4, -7, 11,  6,  9, 16,  2, -7, 18,  6, -7,  6,  6,
+    -2, -9,  3, 12, -2,  3, -1,  6,  7,  8,  0,  8,-11,  8,  4,  2 },
+  {-26,-20,-12,-12, -2, -3,  1, -5, -1, -2,  0,  3,  7,  9, -2,  2,
+     9, 22, 13,  4, -4, -1, -2,-14,  5, 15, -8, -5, -7,-11,-14, -6 },
+  {-21,-18, -1, -4,  0,  3,  7, -2, 10,  8, -8, -1, 15,  1, -9,  3,
+     1,  3, -5, -2,  2,  4,  0, -1, 10,  2,-19, -8,  8, 30, -7,  8 },
+  {-25, -6, 26,  4, -8,  4, -2, 21,  5, -4,-16,  5, 13,  4,-10, -1,
+    -6, -2,  2,-10,-13,  1,  3, -3, -6, -8,  2, 11,  1, -7,  0,  5 },
+  {  0, -1, -2, 19,-12,-48, -6, 11,  8, -2, -4, -2, -7,  5, -3,  2,
+    -2, -1, -1, -7,  0, -3, -3, -4, -4,  4,  1,  3, -3, -1, -2, -5 },
+  {-11, -8,-28, 18, 16,-24, -8, 19,  4,  8,-12,  9, -4, -2,  4, -7,
+     6,  2,  3,  3, -4,  0,  1, -6, -4, -2,  2,  6,  0, -3,  1,-16 },
+  { -9, -5,-26,  7, -3,-37,-16, -2,  2, -7,  4,-13,  0, -4, -6, -5,
+    -6, -4,  0,  3,  4, -3, -4, -4,  4, -3,  9, -4, -2,  2,  7, -4 },
+  {  2,  9,-18,  7, 29,-24, -1,  7, 14, 10,  3, -3, -2, -5,  6,-10,
+    -6, -3, -8,  0,  5,  1,  4,  3,-12,  2,  6,  1,  3,  4,  1, -3 },
+  {-20,  2,  8, 20, -9,-24, -4, 18,  3, 11, -1,-11,  6,  9, -1, -3,
+     1, -1,-15,  3, 15,  9,  3,  2,-13,  2, -8,  8,  1, -1,  1, -8 },
+  {-12,  5,-11,  6, 19,-26,-17, -6,  4, 14,  6, -8,  9,  5, -6, -5,
+     2, -1, 20,  1,-11,-10,-18, 20, -7,  0, -3,  4,  2,  0, 10,  4 },
+  {-15,  1, -2, 13, -8,-21,-22,  4,  4,  3,  3, -7,-31,  4,-10,-14,
+     0,  8,  4,  5,  8, 11,  2, -8,  6,  7,  0, -2,  6,  8,  8,  7 },
+  {-13,-10, -9, 12, 19,-16, -3, -2,  9,  2, 11,-29, -1,  9,  4, -3,
+     1,-10,-10, 16,  1,  7, -7, -6, -4, -1, -5,  3,  6,  0,  3,  1 },
+  {-17, -1, -5, 19, 12, -9,-21, -5,  2, 12, -7, -7, -3,  8,  7, -2,
+     6, -9, -9,  1, -4,  1,  1,  3,-14,  2, -8,  0, 10,  1,-12, -6 },
+  {-13, -5,  8, 15,  0,-20, -2, 20,  8, -8,  8,-19, 12, 10,  2,-11,
+     0, 12,  1,-11,  0,-11,-15,  5,-11,  2,  4, -4,-11,  5, -4, -5 },
+  {  3,-11, -7,  8,  0,-17,-26, 15, 19, -7, 10, -9, -5, -5, 14,-25,
+     0, -8,  2, -9, -3,  9,  1, -6,  4, -4,  3, -9, -1,  6,  2,  2 },
+  {-12,  5,  5,  9, 14,-18,-19,  4,  2, 16, 14,-21,-15, -9, -1, 16,
+    12,-11,-10, -5, -7,  4, 15, -8, -5, -1,  1, 14, 13, -7, -1, -4 },
+  {-10, -5, -1,  8,  7,-23,-10, 14,  6, 11, 10,-16, -3, 16,  6,  0,
+     0,  9,  6, -2, -7,  1, 22,  5,  3, -8,  0,  3, -2,-10,  3,  0 },
+  { -2,-14,  2, 16, 15,-17,-17,  6, 19,  4,-10,-15, -1, 15, 11,-14,
+    -8,  5,  8,  8, -2, -8,-11, 10, 10, -8,-14,  2, 13,  4, -2,-12 },
+  {-10,  3,  6,  4, 19,-23,-19,  1,  4, -9,-30,  3, -6, 18,  0,  2,
+     0,-11,  0,  3,  7, -2,  8,  5,  2, -3,  6, -9,  1, -4,  7, -6 },
+  {  9,  5, -2, 21, 20,-33,-13,  7,-10,  8,  8,-15, -6, -4,  1,  5,
+     3,  7, -2, -9, -1,  4, -6,  1,  0,  9, -1, -5,  2,  1, -3,  3 },
+  { -9, -3,  3, 15, -3,-30, -7, -7,-25,  6,  2, -6,  1, 19,  1,-12,
+     1, -8,-13,  9, 13,  1,  8,  2,  5, 15, -2,  3, -9,  0, -4,  4 },
+  { -6,-12,-17, 25, 22,-13,-10,  9,  2, 11, -7,-16,  4,  6,  1,  0,
+     0, 18, -4, -5,  4, -2, -1, -5,  0, -4,  6,  1,  6, -1,  7,  0 },
+  { -1,  0,-10,  8,  8,-27,  0, -2, 29, 16, -2, -4,  9, -1,  2,  0,
+     6, 10,  6,  4,  2, -7,  9,-18,  3,  3,  3,-10, 17, 10,  9, -6 },
+  { -3,-12, -6, 11, 20,-32,  5, 21,  3, -4, -9,  2,-10,  1,  7, -4,
+     5,  0,  0, -1, -8, -9, -7,  4,-10,  5,  0,  2, -5,  4,  9,  1 },
+  { -5, -1, -5,  1,  2,-19,-13,  1,  6, 12,  2,-16,-17, 11, 10, 13,
+    16,-12,-11,  3, -6,  0,  6,  4, -3,  1,  8,  2,  5,-11,  3,-14 },
+  {-19,  5, 10, 11,  2,-23, -9, 16, -2,  7,  0,-11, -7, 10,  6, -7,
+    26,-15, -4,  8,  6, -4,  7, -9,-15,  1,  8, -4,  4,  2,-12, 16 },
+  {-11,  1, 11, -4,  1,-31,-13, -1,  8,  5,  4, -2,  0, 13,  7,-17,
+     7,-10, -6,  1,  4, -1,  2, -9, -4,  9,  3,  3, -4, -5,  3,  4 },
+  { -3,  1, 10, -1,  0,-15,-22,  4, 40,-11, -4, -3,-14,  9, 11, -1,
+     9, -1, -6,  6,  3, -6,  0,  0,-12,  7, -2,  0,  9,  3,  1,  3 },
+  { -1, -1, -1, 14,  8,-24,-14, -8,  5,  8,  5,-12,-17,  8,  2,  7,
+    10, -8,  0,  4, -6, -6,-10,  8,  4,-12,  3, -9,-12,  5,  4, -3 },
+  { -5,  1,-11,  8,  9,-24,  0,  2,  2, 14,-12,-13,  1,  6,  7,  0,
+     7, -6,  9, 26, 11,-14,  8, 10,  1,  9,  0, 11, -2,  6,  2,-10 },
+  {-13,  1,  4, 34, 19,-17,-15,  0,  3, -2, -7, -1,  0, -3, -3, -1,
+     1, -1,-10,  8,  5,  0, -8,  4,-17,  9, -2,  0,  0,  6,  2, -3 },
+  { -6, -4,  1,  2,  2,-14,-29,  0,  9, 34, -3, -5,-14,  6,-10, -9,
+    -5, -1,  0,  3,  3,  0,  1, -1, -2, -1, -1, -3, -3, -4,  3, -3 },
+  { -4,  6,  3, 14, 14, -8,-29, 31, 11, 14, -4, -5, -6, 10,  6, -9,
+    -1,-11, -7,  1,  7,  4,  1, -6,  4,  0, 10, -7, -5, -1,  2,  4 },
+  { -4, -4, -2, 14,  6,-32, -6,-14, 14, -5,-11, 10,-18, -4,  6, -8,
+     9,  5, -4,  1, -4,  5, -2, -9,  3,  5,  2,-10, -6,-17,  3, 17 },
+  {-16,  9, 21, 19,  4,-20,-17, 14,  9, 15, -6,-17, -1,  1,  6, -3,
+     1,  1,  8, -3, -6,  6,  9,  4,  9, -9, -5,  1, -1,  0, -1,  2 },
+  { -7, -5,  3, 19,  1,-20, -9, 14, 21, -7,-18, -9, 26, -7,-17, -7,
+    12,  6,  0, -9, -6, 14,  9, -9, -8,  4, 15, -7, -9, -1,  9,  1 },
+  {-20, 30, -6, 11, 24, -4,  0, -6, -2,  8, -4, 12, -8,-17,  0,  5,
+    -4,  1, -1,  3, -3,  5,  3,  3,  7, -2, -3, -2,  4,  0,  0, -1 },
+  {-35, 17,  6,  1, -9, -1,-16,  3,-20,-13,  8,  7, -4, -7, -4,-20,
+     7, 12, -5,  5, -5,-11, 12, -1, 15, -9, -6, 16, -4, -9,-13,  4 },
+  {-21, 36,-19,  9,  0, -7, -8,  9, -4, -3,  3,  0,  7, -8, -2, -2,
+   -11, 13, -1,  5, -3,  7,  2,  3, -1, -2, -5,  1, -1, -2, -5, -3 },
+  {-12, 33, -4,  1,-12, -9,  0,-13, -1,  2, -8,  4,-10,  6,-16, -7,
+    -1, -4,-10, 15, -1,  0, -5, -8,  5,  5, -3,  0,  2, -7,  1, -7 },
+  {-14, 32,  5, -7,-15,  3, -5,  8, 14,  5,  9, 13,  3, 18, -3,  7,
+     4,-10,-10, 10, -1,  2,  0, -2,-11,  5, -3, -4,  2,  2,  7,  4 },
+  {-14, 34,  1, 20, -1,-12,  0, -3, -7, -4,  7, 18,  9, -3, 14, -7,
+    -9,-20, -7, -4,-13, 12,  1, 12,  5, -6,  2, -4,  0,-15,  1,  3 },
+  {-21, 23,  7, -8,  3,-13, -3,  0, -6, -2, -7,  6,-12,  9, -6, -2,
+    -2, -4, -1,  6,  9,  5, -9, 15,  0,  8, -8,  7,  6,-15,  3, -5 },
+  {-27, 32, -1, -4, -2,  4,-10, 12, -3,  8, 13,  7,  0,-15,  4, -2,
+     3,  5,  7, -4,  9,-12, -1, -2, -1, -4,  0, -4,  2, -5,  6, -6 },
+  {-17, 29, 15,  0, -1, -4,-10, 13, 12, -1, -8,-10,-10,  4,  7, -2,
+     6, -5,-13, 19,  6,  1, -7,  2, -9, -2, 12, -4, -8, -3,  2,  4 },
+  {-38, 27, 16,-15, -6,  3, -7, -4,  0, -1,  6, -2, -3, -6,  6, -6,
+    -3,  0,  2,  0, -4,  6,  1, -1,  0,  4, -1,  3,  4,  1, -2,  5 },
+  {-33, 40, -4,  2,  1,  0,  0,-10,-14,  0, -7,  4, -1,  3, -2,  5,
+     7,  6, -1,  4,  1,  3,  1, -7,  1, -4,  5,  7,  0,  4,  3, -4 },
+  {-20, 25, 12, -4, 16, -4,  2,  2,-14, -2, -3, 29, -1,  1,  3,  1,
+     9, -5,  2, -8, -3,  1, -7, -2, -7,  1,  0,  4, 16, -2, -1, -1 },
+  {-10, 30, 17,  3, -5, -2,  0, -5,-22,  4,  5,  5, -3,-18, -6, 10,
+    -5, -7,  2,  8,  7, -7,-11, -2,  0, -3,  3,  2, 11, -4,  4, -4 },
+  {-11, 30, 11,  4, -3, -8,  1, -2,  4, 18,  3,  1, -1,  0, -8, -4,
+    -3, 10, 13, 14,  5, -5,  1,  1,-10,  2, 15,  4,  9, -1, -5, -3 },
+  {-17, 32, 18,-18, -3, -5,  6, 10,  1,-15, -5,  9,  8,-12,-10, -6,
+    11,  9, -5, -8, -7, 10,  5,-10,-14, -4, -3,  1,  9,-11,  2,  1 },
+  {-13, 28,-11, -1,  2,-16, -2,  7,-24,  0,  3,  6,  3, -1, -8, -7,
+   -12,  2,  2,-20, 10,  4,  0,-13, -2, -2,  1,  8,-14,  0,  4,  1 },
+  {-14, 23, 12,  8,  8,-26,  2, -4,-14, 13,-14, 15,  3, -9, -1,-13,
+   -10, -2,-10,  6,-16, 12,  8,  0,  9,-10, -7, -4, -4,  7, -8,  8 },
+  {-20, 45, 10,-14,  4, 16,  8, -9,  1, -8, 10,  5, -7, -2,  2, -5,
+    -1,  0, -5,  4, -6, -2,  4,  1,  3,  4, -4,  2, -2, -2,  5,  1 },
+  {-20, 26, -4,  1,  7,  4, -8,  1, -5,-13,  2, 13, -7, -3,  6, -6,
+    22,  0,  5, 11, -4,-11,  8, -9,  2, -2, -4, -2,  2,-13, -4, -8 },
+  {-28, 18, 17,  3, -8,-23,-16, -6,  5,-10, 14, 10,  5, -1, -8,  4,
+    -2, 13, -3, -2,  3,  4,  3, -2, -3, -4,  0,  1,  3,  4,  0,  4 },
+  {-12, 32, -6,-16, 18, 12,-16,  0,  7, 13, -4,  5, -8, -1, -3,  4,
+     6, -2, -1,-13,  4, -1,  3, 12, -3,-10,  1,  6,  8,-11, -2,  4 },
+  {-18, 26,  2,  5,  0, -9,-17, 14,  5,  1,  7, -3, -8, -3, 11,  7,
+    -5,-12, -8,  7,  0, -7,  2,-12, -9, 13,-11,  9,  6,-11, -5, 11 },
+  {-24, 22,-15, -9,  8,  1, -7,-12, -9,  3, 11, 15, 14,-11, 12,-15,
+    -5,  7, -2,  0, -8,  3,  3, -1,  2, 11,-11, 14, -6, 13,  1, -6 },
+  {-20, 28, 18, -4, -6, -5, 12, 14,  2, 10,-13, -6, -8, -6,-13, -1,
+   -26, 22, -3,-14,  6,  0, 10,-15,-13, -9,  6, -7,  1, -5, -4, -1 },
+  {-19, 26, -8, -3,-14, -6, -9, -4, -8, 15, -8,  3,-12, -4, -2, -7,
+    -5,  3, 13, -3, -4,-25,  4, -1,  5,-12, -1,-13,  5,  2,  0,  6 },
+  {-18, 43, 14, -8,  1,-23, -2, -2,  1,  3, -7,  0,  0,  8, -1, -3,
+    -5,  1,  5,  2,  0, -2, -2, -2,  1, -1, -1, -7,  0,  3, -3,  9 },
+  {-11, 30, 10,-14,  3,  1, 10,-11,  1, -7, -4, 14,  2,  1, -9,  1,
+   -11, -2, -7,  5,-11,  1,  3, 14,  1,-16, -8,  3, -5,  7, -4,  4 },
+  {-18, 24,  6,  3,  8,  7,-22, -7, -7,  3, -8,  4, 23,  9,  3, -1,
+     3,  6,  7, -1, -7,  6,  4,  1, -3,  1, -6, -1,  2, -7,  3,  3 },
+  {-15, 38, -7, -1,-11,  2,-17,-24, 24,  8,  7, -4, -5,  2,  2, -7,
+     1,  4,  0, -9,  5,  0, -1,  1, -1, -5, -6,  3,  0,  7,  8, -3 },
+  {-14, 22,  1, -5,  9,-12, -9, -5, -6,  5,  7,  8, -1, -4, -9, -3,
+   -33,-16, -9, -1, 12,-11, 17, -7, -3, -1, -7,  3,  2, -3, 16, -4 },
+  {-14, 20,  6,  4,-10, -4, -4, -4,  1, -7,  2,  6,  8,-12,  4,  1,
+    -1, 12, 10,  3,-14,-10, -3, 18, -2, 33, -5,-17, 17, -5,  9,  7 },
+  {-12, 23, 13,  0,-11, -8,-11, 12, -5, -9,-16, 11,  6,  4, 12, -5,
+     5,-13,  7,-12, -3,  1,  2, 12,  1, -4, -1,  5,  4, 11,-12, -3 },
+  { 15,  2, 14,  7,  1,  2,  1, 12, 10, 23,  4,  6,-20,-10,  4, 26,
+    -6, 13,  4,  3,  2,-11,  5, -7,-10,  4,  9,  1, 10, -4, 11,  4 },
+  { 17, 15, 31, 17, 18, 16, 11, 24,  2,  4,  2,  3, -8, -3,  7, -3,
+    -5, -7, -2, -6, -4, -5, -4, -1, -4, -2, -5, -6,  2, -1,  4, -2 },
+  { 16,  8, 15, 14,  3,  7, 21,  9,  8, 15, 21,  6,  8, 12,  5, -5,
+     7, -3, 10,  2, -3,  8,  6,  0,  5,  5,  6, -3,  2,  4,  0, -5 },
+  {  5, -4,  6, 12,  6, 13, 24, 17, -5, 17, -1, -6, -7,-10, -8,-18,
+     3, -2,  2,  7,-15,-11, 12, -3, -2, -2, -4, -7,  2,  0,  5,  5 },
+  { 10, -6,  8, 11, 12, 20, 22,-11, -3, 15, -3, 15, -2, -2,  0,  2,
+     5, -8,  4, -5, -9, -4, -1,  2, -1, -3,  1,  3, 13, -1,  9,  7 },
+  { -5,  8,  5, 11, 14, -5, 14, -9,  2, 35,  8, 15,  1, -2,  2, -2,
+     4, -9, -3,-14,-12, -2, -2, -4, -2, -8, -3,  1, -6,  3, 10,  0 },
+  { 16,  0, -6, 15, -3,  4,  4,  3,  3, 20,  5, -4, 10,  9, -9, -3,
+   -10, -2, -7, 11,-11,-10, 17, -1,  3,-15,  2,  9,-15,-10, 16, 10 },
+  { 14,  4, -7, 19,  3,  0, 19,  8, 16, 34, -9,  6,-13, -1,  6,  5,
+    -1, -2,  4,  3,  2,  1,  1, -1,  0, -7,  2, -1,  1,  0,  6, -1 },
+  {  1,  6,  9, 13,  9, 10, 15, 16, 10, 18, 13, 17,  3, -1, -7,  2,
+   -15,-11,-10, -4,-13, -6,-17,-13, -6,-14,  1,-10,  6,  4, -1, -1 },
+  { 13,  1,  7, 10, 14, 13, -7,  5,  5, 28, 14, 14, -2,  2,  3, -3,
+   -13, -4, 10, -9, 19, -4, -3,  4, -5, -5,  0,  5, -5,  0,  3, -4 },
+  {  1,  0,  6, 22,  9, 18, 18, -3,  5, 10, 12, -2,  1, -3, -8,-12,
+     9,-10, -7,  1, -1, 19,  0,  2, -8,-11,-10,  9,  6, 11,  0,  3 },
+  { 10, 11, 19, 44,  0, 14,  1, -7,  6, 22,  2, -1,  9,  2,  0, -4,
+     4,  0, -6, -6,  3,  0,  0, -2,  2, -5,  1, -2,  0,  1,  1,  1 },
+  {  5,  7,  0, 32, 30, 26,  5,  4, -7, -3, 15, -6,  3,-10,  7,  6,
+    -8, -7,  2,-13, -5, -1, -3,  7,  3, -2, -8,  0,  6,  4,  5,  0 },
+  {  9,  8, -2,  4,  2, 11,  4, 29, -5, 14,  8, -5,-14,  8,  0,  9,
+     8,-10,  5,-15, -6, -9,  9, -1, 18,-16,  9,-21, -3,-13, -2,  8 },
+  { 25,  7, -9, 23, 20, 18,  6, 16, -9,  8,  8, -5, 11, 13, -8,  7,
+     4, 10, -2, -1, -7, -9, -7, -9, -4,  1,  1, -5,-10,  8,  4, -5 },
+  {  9,  2, 16, 14, -5, 14,  1,  0,-21, 17, -1,  9, 12, -3, -3,  4,
+    -4, 14, 10,  3,  0,-10,  7,  4,  4,-11,  2,  4, -1, -3,  9, -1 },
+  { 17,  8, 11, 26, 15, -3, 14, -1, 12,  9, 10, -8,  8,-18,-11, -3,
+   -14, -7,  7, -3, -3, -4,  1, -7, -3,  2, -3, 16, 10,  0,  9,  6 },
+  {  9,  8,  3,  8, 18, 14, 11,  1, 10,  6,  1, -4,-16, -2, 14, -2,
+     1,  8, 12, 14,  3, -3,  8,  8, 12,-15,  3, -3,  3, -2, 14, 10 },
+  { 22, -3,-11, 13, -7, 11,  4, 11,  3, 14,  0, -6, -2, -9,  4,  2,
+    -2,  0, -5,-27,-10,  3, -1,  5,  8,-24, -3,-11, -3,  2, 11, -1 },
+  { 19,  2,  8, 36,  5, -6,  3, 15, -3, -4, -5, 14,-10,  1,-12,-10,
+    -3, -4,  3, -2,  1, -8,  4,  3,  5, -3,  0,  4,  8, -2,  8,  4 },
+  {  8, 14, 15,  9, -4, 10,  5, 11,  9, 10,  8,  9,-15, 15,  6, -8,
+   -10,-13,  5, -8,-20,-13, -6,-11, -1, -3, -6, -4, -1,  0, 13, 15 },
+  { -2, -1,  9, 12,  2,  2, 13,  3,-23, 33, 15,  2, -4, -1,  3,  8,
+     8,  6,  6, -7,  8,  6,  9, -1,  3, -8,  0, -4,  1, -8, 11, -1 },
+  {  6,  5, -6, 16,  2, -3, 31, 21, -9, 12,  0, -1, -4,  1,-12,  3,
+   -13,-18,  2,-11, -9,  2, -8, -6, 11, -3, -1,  0, -1,  0, 13,  5 },
+  {  5, -1,  2,  0, 25,  5, 10, 16, -5, 21, 14, 12, 13,  2, -5,  5,
+     5, -3, -2,-14,  0,-12,  7, 11, -1, -7, 19, -1, -1, -1,  8, -1 },
+  { 10,  7,  3, 11,  0,  8, 22,  3,  3, 19, -4, 12, 15,  9,  5, 15,
+     2,  1,  2,-10,-10,  0,  2, -1,  0,  1,-12, -1, 21, 16,  9, -7 },
+  { 11, -4, -5, 24, -7, 11, 20, 11,-15, 18,  5,-13,-15,  0, -5,  9,
+     1,  0, -1, -9,  4, -8,  6, -8,  1, -2, -7, 20,  9,  3,  9,  3 },
+  { 20,  0,-12, -6,  9, 31,  9, 12,  8, 27, 15,  7,-16,  5, -3, -7,
+    -1, -9, -2, -7, -3,  4, -8, -3,  3, -6, -2, -2, -3, -6, -1,  2 },
+  {  6, -6, 48,  8, -3, 19, 12, 11, -7,  2,  3,  0, -1,  1,  8, -4,
+     4, -6,  0, -4, -4, -3,  3,  6,  3,-13, -8,  5, -3, -7,  8,  5 },
+  {  7, -2,  6, 11, 12,  2, 14,  4, -5, 12,  2,  9,  4,  2,  0, -1,
+     2,  0,-15, -9,-16, -2,  8,-17, -5,-22,-19, -5, -1,-10,  1, -2 },
+  { 11, -9,  3, 12,  6,  6,  1, 17, -6, 19, 14,  7, -7, -1, -1, -9,
+     9,-11,-17,  0, -6, 16,  0,  1,  9,-24,  3,  3, -9, -3,  3, -2 },
+  {  9,  0,  1,  8,  1,  7,  2, -5, -3,  8, -1,  7,  2,  6, -3, -6,
+     5, -2,  6, -2, -4, -3,  0, -3, 13,-50,  1, -2,  2,  4,  4,  3 },
+  {  7,  0, 26, 21, -4,  2, 17,  8,  7, 11, -7,  1, -1,-15, -1,-15,
+   -11, -4,-17, -4,  1, -7,  3,  6,  3, -9,  2,  3,  6, 10,  6, 12 },
+  {  1, -2,  2, -1,-10, -4,  6, -3, -5, -2, -8,  2,  2,  2,  8,  0,
+     1,  1,  6,  0, 11, 13,  3,  4,  0,-12, 11, -5, 19, 20,  2,  5 },
+  {  5,  3,-13, -2,  1,-12, 11, -7,-12,  7, 10,  0,  7,  0, -2,  4,
+    -6, -9,-11,-12,-23, 12, 10, -3,  0,  6, 19, -1, 24, 18,  9, 12 },
+  {  6, -3,  2,  5,  2,  2, -2, -5, -8,-11, -4,  3, -8, -4,  5, -3,
+   -16, -4,  3,-12, -4,  3, 32,  7,  2,  8, 32,-18, -1, 12,  1,  7 },
+  {  0, -8, -1,  0, -8,  7, -8, -1, -1,  4,-12, -1,  3,  0,  1,-18,
+     8,  8,-14,-10,-11, 19,  9,  5, -7,  6,  8, -4, 26, 12, -1,  6 },
+  {  3,  5,-14,  7, 14,  8, 20,-13,-16,-10, -2, 17, -7,  4, -8, -9,
+    14, -5,  3, -4,-12,  7, 14,-10,-19,-20, 35,  8, 13, 14, -2,  9 },
+  { -2, -4, -1,  1, -3,  0, -1,  1,  2,  2,  6,  0,  0,  4,  5, -2,
+     3,  3,  3, -2, -7, -3, -3, -1,  6, -2, 29, 22, 13, 34,  0, 14 },
+  { -3, -9,  3,  1,  5, -4,  2,  0,  7, -9,  0,  2, -5, -3,  0,  6,
+    -1, -1, -1,  2,  2,  4,  8,  7, 20, -6,  7, 16, 33, 20,  6, -1 },
+  {-11,  1, -3, -3,-11,  3, -9,-25, -1,-16,  4, -8, 15,  1, -2,  7,
+     8, 23,  2, 18,-13, 16,  3, -7,  6,  3, 16, -8, 12, 16,  3,  4 },
+  {  0,  5,  5, -5,  1, -1,  2, -3, -2,  1,-13,  2,  2, 10,  6,  7,
+    18, 18,  7,  9,  8,  9, 21, 14,  7, 12, 15, 14, 15, 12, 11,  5 },
+  {  1, -5, 11, -2, 17,  8,  3,  0, -1,  6, 11, -7,  6,  6,  7,  5,
+   -15, 14,  1, 11,  4, 10, 12,  1,  2,  4, 30,  1, 11,  1,  6, 13 },
+  {  2,  4,  3, -7,  5,  8,-11,  7, -5,  9,-10,  6,  8,-10, -3, 10,
+     1,-29, -4,-26,  5, -8, 13,  4,  3,  6, 35,  1,  3,  6,  3,  0 },
+  { -2,  1,  0,  0, -1, -3, -7, -3, -9, -3, -1, -6,  3,  4,  4,  0,
+     5, -1, -2, -2, -1, -4,-10,  8,  0, -6, 10, -4, 46, 12,  2, 28 },
+  {  4, -1,  4,  1,  0,  4, -2, -2, -2, -1,  2, -4,  1,  5,  0, -3,
+     1,  1, -2,  0,  1, -2, -1, -1,  3, -6, 35,-11, 13, 53, -3, -1 },
+  { -5, -2,  0,-13,-16,  5,-12,-11,  1,-30,  3,-18,-24, -8, -5,-19,
+     1, -3, -8,  7, -7, -8, 15,-19,  4, 10, 30, 24,  6,  1, -9, 10 },
+  { -4,  8, -7, -4, -6, 12, -1, -9, -4,  2, -9,  3,  2, -2,  4,  2,
+    22,  9,  4, -5,  0,  5, -2, -9, -3,  1, 18,-12, 18, 16,  4, 16 },
+  { -5, -8, -3, -5, -3,  6, -7, -3, -2, -5, -3,  1,  2,  2,  4, -6,
+    10,  3, 12, -3, 20,  0, 27, -4, 16,  5, 18, -3, 23,  4, 12, 11 },
+  {  0,  1,  0,  1, -2,  1,  2,  1, -1,  0, -2,  2, -2, -4,  1, -2,
+    -2, -1, -5, -2,  0,  0, -2,  2,  9,  7, 63,  5, 12, -1,  1,  0 },
+  {  4, -3, -7, -5,-11, -5,-12,-10,-10,-12,-15,-12,-14,-14,  1,  1,
+    10,-10, 16,  6,  2,  9, 11,  9,  9,  8, 12, -1, 13, 12,  6,  3 },
+  {  7, -3, -2,  4,  6, -8,  2, -3,-12, -5, -9, -8,-10, 15, -2, -4,
+     8,  9,  7,-13,-18, 34, -5,  7, 12, 22, 16,-11, 13, 25,-15,-11 },
+  { -3, -2,  0, -4,  1,  0, -3,-13, -7, 13, 12, -7,-10, 13, 19,  6,
+    16, 15,-12,-15, -3, 34,  1,  5,  1, -9, 11, 21,  8, 17, -5, -6 },
+  {  3, -5,  0, -4,  0,  4,-11,  4, -7, -3, -1, -8,  3, -2,  2,  1,
+    11,  5,  6, 14, -3,  2, -4, -7,  0, 31, 15, -2, 24, 11,  5,  4 },
+  { -1, -4, -9,  5, -8,-18, -4, -9,-20,-18,  7,-14,-16,  3,  8, -3,
+    29, 11,-13,-13,  7,  1, 17,  6,  6, 21, 11,  1, 14, -8,  2,  5 },
+  { -3,  8,-10, -6, 12,  2,  1,  3,  3,  3,  3, -6, -8,-14, 15, -5,
+    16,  4, 16,  0,  7, -1,  0, 16,  2,  1, 22,  4, 19, 13,-11,  1 },
+  {  2, -3, 10, 20, -4, -1, -8,  5, -8, -9, -6, -2, -4, -7,  8,-10,
+     0,  8, -6,  1, -8, 14, 13,  5, 17, -6, 26, -1,  7, -1,  0, 12 },
+  { -4, -7,-31, -2, -7, -1,  5, -5, -5,-12,  4, -7, -6,  3, 15, -2,
+     5, -2,  7, -1, 10,  7,  8, -1, 14, 20, 14,  9, 16, 16,  8, 24 },
+  { -7,  0, -3, -6,  1,  3,-13, -6, -4, -4, -5, -9, -1,-10, -4, -8,
+     2,  0, -1,  1, 24, 24, 21, 31,  5,  2, 11, 12,  7,  4,  3,  6 },
+  { -3, -5,  6, -4, -3, -1,  2, -1, -2,  1,  0, -8, -1,  2,  0, -4,
+     6, 22, -1, -5,  8, 12, -1, -2, 28, 27, 20,-27, 14,  1,  2, -3 },
+  {  1, -5, -2, -2,  6, -2,  9,  1, -2, -5,  3,  4, 11,  5,  2,  8,
+    -3, -1,  1, -2, -3, -5,  5,  8, 49, 12,  8, -3,  9, 20, 12, 17 },
+  { -6,  0,  1,  7,  0,  9, -2, -4,  8,  0, -2,-10,  0,  7, 21, -1,
+     0,  1, 17, -7, -5,  2,  4, 16, -2, 17, 14,-20, 15, 14,  4, 15 },
+  {  0,  3, -4,  9, -4,  0,  6,  4, -6, -6, -5, -7,  2, -9,-10, -2,
+    -5,  0, -3,-21,  9, 14,-11, 13, 29,  2, 25,  4, 22, -1,  2, -3 },
+  {  2, 12,-11,  2, 16,  9, -4,  7,  1,-10,-15, 11, -4,  3, -2,  4,
+     4, -5,-10,  1,  4, 19,-15,  6, -4, -2, 30, -7, 11, 21,-12,  5 },
+  { -2, -3, -2,  4, -1, -5, -3, -7, -5,  1,  0, -6,  1, -6,  7,  0,
+     8, -7, -3, -2,  2, 14,  2, -3,-26, -1, 26, 22, 32,  1, -2,  6 },
+  {  1,-38, -1,-20, -2, -3, -6, -4,  2,  2,  7,  0,  3,  5,  3, 10,
+     6,  1, -3, -5,  7,  5, -5, -4,  8,  3,  1,-14, -1, -9, -5, -4 },
+  { -5,-26, -7,-19,-10, -5,-11,  5,-11,-25, -8,-14, -9,-16, -8, -6,
+   -17,-14, -1, -1,  6,  2,  2,  2,  3,  0,  2,  8, -8,  3,  0, -3 },
+  { 17,-49, -3,-23, -1, 11,  7,  3,  4, -4,  0,  0, -1,  4,  2,  4,
+    -2, -4,  2, -2, -1, -2,  2,  0,  0, -1,  0,  0,  1,  2,  0,  0 },
+  {  4,-34, -6, -9,  1, 21, -7,  3, -2, -1, -3, 18,  2,-16,  7, -3,
+     8,  7, -5,  7,  2,  4,  8, -6, -7, -2, -5, -1,  4,  1,  2, -4 },
+  {  5,-29, 13, -2,-14,  3,  1, 18,-15,  4, -8,  8,-10,  8,  2,  1,
+    -8, 15,  3,-10, -4, -4, -2,  0, -3, -4,  2, -3, -4, -3, 12, -6 },
+  { 13,-20,  3,-18,-17,  4,-14, 13, 28, 11, -8, -6, 16,  6,  0, 10,
+     3,  4, -9, 13,  5, -7, 12, -5,  0, -7,  5,  1,  3,  3,  2,  1 },
+  {  3,-27, -5,-11,-21,-11,-12,  0, -5,  7,-22,  1,  3,  5,  0, -5,
+     8,  7,  1, -5, -7,  2, -5,  4,  1,  3, -8, -2,  0,  4, -2,  6 },
+  { 31,-45,  0, -1,-12,  1,  2, -6,  4,  3, -1,  3,  3,  0,  5,  3,
+    -5, 12,  4,  6,  2,  1, -2,  1,  3,  2,  5,  2,  2,  2,  3, -1 },
+  {  9,-45,  6,  5, -1,-17, -2, 18, -3,  2,  0,  1,  0, -1, 10,  8,
+    -7, -2, -5, -8,  6, -1,  0,  4,  6, -3, 12, -1, -2,  0,  5, -7 },
+  {  3,-26, -2,-12,-12,  2,-10, 16, -3, 12,  4,  5, 11,  8,-16,-17,
+    -2, -3, -3,  2,  5, -9, 13,  1, 10, 11,  3,  5, -2,  2,  2, -7 },
+  {  8,-26, 32, -7, -5, 22,  2, 14,-10, -8, -7,  3,  3,  7,  0, -5,
+     0, -1, -3,  0,  8,  4, -5, -7,  6, -1,  4,  8,  1,  1,  7, -6 },
+  {  4,-31,  2,-14,  2,  0,  1,  8, -6, -1, 17, -3, 13, -6,  5,-10,
+    -2,-10, -2,-10, -3,  7,  1,  5, -8,  8,-14, -3,-15,  7,-10, -6 },
+  { 16,-27, 13, -4,-23,  7, -9,  6, -7,  5,  4,  2, -1, -3, 23,-18,
+     7,  0, -3,  4, -3,  9, -6, -2, -1,  8, -6,  2,  6, -3,  2, -2 },
+  { -1,-35, -2, -8, 11, -1, -7, -3, -2, 11,  7,  6, -6,-10,  9,  6,
+    -3, -5, -6, -3,  9, 16,-16, -9,-20, 12,  3,  5, -3,  1, -9,  4 },
+  {  2,-24,  1,-12,-16,  5, -4,  3, -4, -1,-11,-11, -8,-14, 14, 10,
+    -8, 20,  8, -3,-11,  1,  1, -4, -4, -7, -3, 15,  2, -6, -2,  7 },
+  {  9,-21,  2,-19, -7, -5, -8, 25,  3, 17,  5, -3,  9,-12,  8,  2,
+    -4,  3,  3,  1, 11, -9, -4, -3,  4,  3,-22,  6,  4,  6, 11, -5 },
+  { 16,-23, 13,-17,-21,-12,  5,  9,-20,  7,  6, -6,  0,  2, -9,  6,
+    -6,-13, -7, -1,  5, -3,  5, -7,-10,  1,  0,  8, -9, 11,  0, -8 },
+  { 10,-26, -9, -7,-19, -4,  6, 16, -7,  5, -4,  4,  8,  0,  4, -1,
+     6, -7,  1, -8,-11, 10,-14,  0,-16,  6, -3,  5, -1, 14, 12,  1 },
+  {  8,-27, 12,-14, -1, -1,-19, 10,-11, 21,-14,  9, -8, -3,  8, -1,
+    12,-13,  3, -4, -2,  0, -9,  0, -7,  2, -3, 12,  1, -3,  3,  1 },
+  { 18,-20,-14,-14,-16, -3,-24,  6,-17,  2, -3,-11,  2, -3, 12, 10,
+    10,  1, 10,  7,  8,  5,  5,  4, -1,  7,  2,  2,  0,  4,  7,  0 },
+  {  0,-30,  9,-16,-18, 15, 12, -3,  4, -4, -5,-11, -4,-12,-10,  0,
+     2, -2, -4, -1,  2,  0, -1, -6,  2, -3,  4, -5,  7,  3,  5,  7 },
+  { 25,-24, -1, -6, -9,  6,-13, -2,  3, 15, -3, 11,  4, -8,-11,  2,
+     0, -9, -2,  7,  4,  8,  5, -8,  5,  6, -1,-11,-15, -5,  0, 11 },
+  {  0,-34, -7,-11, -7,  9, -3, 19,  4, -8,  3,-11, 11, -3, -9, 12,
+     9,  9,  2,  1, -7,  1, -3,  0, -6, -2, -1,  3,  0, -7, -2, -5 },
+  {  6,-34, -4, -5, -3, -9,  2,  9, -1,  9, -5, -3,-26,-12,  8, -6,
+    -7, 11, -8,  4,  4,  1, -1,  0,  8,  9, -4,  7, -1,  1, -3, -1 },
+  {  3,-30,  5,  6,-10,  3, -7,  6,  3,  3,-26,-19, -3,  1,  7,  5,
+    -4, -5,  6, 10, 13,-10,  4, -7, -4,  5, -3,  9, -6,  3,  9,  5 },
+  {  4,-24,  9,-19,  2, -4, -5,  8, -3,  2,  0,-15, -1,  9, -4, 22,
+     6,  9,  3,  7, 11, -9,  0, -3,  4,  5, -5, 10, -8,  5, -7, -3 },
+  {  8,-27,  7, -3, -1,  2, -9, 13,  7, 12, -4, -6, -6,  5,  0,  7,
+     5,  1, 15, -3, -4,  0, -5, -2,  7, -5, -7,  1, -2, 13, -8, 13 },
+  { 17,-22,-15,-11, -8, 16,-14, 18,  2, -1, 14, -7, 14, -6, -6, -7,
+    -8, 17,  6,  4,  4, -7, -5, -9,-14, -6, -1,  9, -3,  1,  6, -5 },
+  { 25,-30,  2,-12,-13, 18,-18, 16,  8, -3, 10, -8, -3, -1, -6,  3,
+    -5, -7,  4,  6,  7,  1,  1,-11, -5,  6,  2, -4,  9, -1, -5, -2 },
+  {  7,-23,  7,-15, -1, -3, -1,  0,-10, 12,  2,  5, -4,  0,  4,  6,
+    -1,  5, -9, -1, -1, -7,  1, 17,  9,-17,-16,  8,  4,-14, 11, 14 },
+  {  0,-31,  7,-13,  3,-11, -7,  6,  1,-11,  8, -7, 15, -3, 16,-11,
+    -1,-15, 16, -3,  5,  0, -2, -2, -6, 11,  5,  6,  5, -5,  6,  3 },
+  { 13,-24, -2,-20,-10,  7, -3, -1, 15,  2,  6, -5, -7,-10,-20,  1,
+    -4, 14,  8, -2,  3,-13, -3,  1, -4,  1, -3,  2,  8, -7, 16, -4 },
+  {  1, -2, -2, -3, -4, -7,  0,  3,  6,  7,  3,  2,  1, -2, -1,  0,
+    -6,  4,  2, -4, -3, -4,  5,  9,  5,  0, -3, -3, -4, -7,-31,-50 },
+  { -1, -3,  7,  2, -1,  2,  4,  6,  0, 10, -2,  0,-20, -6, -3,  9,
+   -20,-22, -1, -1, 15,  9,-12, 10,-13,-20, 12,  3,  5,  6, -7,-26 },
+  {  0,  4, -2,-14,-12,  6,-13, 11,-10,  3, 22,  6, 16, -2, -5,  1,
+    -3,-11,  0, -7,  5, -5,  0,  1, -1, -6,  8,  8, 10,  9, -5,-27 },
+  { -5, 10, -2,  7,  9, -9,  5, -9,  5,  4,-15, 14,  1,  3,-10,  5,
+     0, -2,  7,  3,-13,  6,  9, -6,  5,-14,-17, -1, 11, 14, -2,-26 },
+  {  0,  6, -3,  0, -8,  6,  0,  1,  4, -8,  2, -5,  4,  7, 15, 11,
+     9, 19, -2, 14, -8,  7, -1,  3, -3, -3,-10, -2, 12, -2,-12,-29 },
+  {-12, -5,  0, -3, -2,  6,  3, -3,  2, -2,  1, 11,  2, -7,  5,  1,
+     2, -2,-14,  0, -1, -5,  3,  8,-28,-26,  6, -6,  3,  8,-10,-27 },
+  { -1, -3,  6,  2,  4, 15,  1,  0,  2, -2, -2, 13,  3,  6,  0,  6,
+    -1, -4, -1, -5,  8, -1,  5, -5,-15, 11, -8, -5, 14, -6,-14,-29 },
+  { -5, -6,  0,  1,  0,  6, -3,  2, -5, -1,  5, -3,  2,-10,  3,  4,
+     3,  0, 13, -3, -1,  4, -4, -6,  2,  9,  8,  2, -3, 28,-11,-31 },
+  {  1, -4,-10, -9, -4, -3,-15, -6,  1,  5, -3, -6,  5, -6,-22, 27,
+   -13,  5,  3, -7, -4, 20, -7,-12, -1,-24, -4,-13, -8,-11,-15,-21 },
+  { -6, -4, 19, -6,  2, 11, -6,  1, -3,-10,  9, -9, 12,-10,  2,  1,
+    -9,  1, 15,  7, -5,  5,-29,-35,  4,-30,  9,  9, 19, 17,  2,-17 },
+  { -3,  3, -3,  1,  2,  5, -1,  5, -2, -3,  1, -3, -8,  3, -4, -2,
+    -4, -1, 12,  0,  2, -8, -6, -4, 16, -1,-14, -2, 25, -6,-15,-36 },
+  {  0, -1,  3, -4, -4, -1,  7, -4,  8,  0, 10,  9, -4,  1, 10, -1,
+    -3,-13, -5, -4, -1, -4,  8, 11, 14, -7, -5, 16, 12, 13, -1,-28 },
+  {  1, -2,  2, -3, -8, 10,  4,  9, 12,  3,  5,  0,  8, -3, -6,  2,
+    16,-11, 11,  0,  1,  6,  1, 18,-10,-16, -1, -4,  5,-14,-15,-20 },
+  {  1,-12,  5,  4, -7,  8, -1,-17, -2, -9,-14,-11,  6, -9,  5, -4,
+     3, -2,  7, 18, -5,  5,  6, -1,-11, -2,-10, -3,  8, -3, -2,-32 },
+  {-12,  5, 20, -5, -6,-11, -6, -6,-13,  4, -6, 19, -8,  2,  3, -9,
+    -4, -4, -1,  9, -1, 21, -1,  7, 15,-10, -1, -3,  9, -3,  2,-24 },
+  {  0, -3,  2, -6,  4, -1, -9, -2, -1, -3,  6, -1, -5, -6, -5, -8,
+     0, -2, -6,  9, -4,  3,  2,-13,  1, -7, 23,-13,  4, -3,-15,-33 },
+  { -7,  2,-15, 11,-10, 14,  0,-11,  3, -1, 12, -4, -4,  9, 11,-13,
+   -13, -3,-14,  1,  3,  6, -5,  8,  0,  5,  5,-10,  4,  5, -6,-30 },
+  { -6,  4,  0, -5,  4,  1, -1, -1,  3,  6,  5, -2, -5,  0, -2,  5,
+    -4, -2, -4, -2,  4,  7, -7, -1,  1, -4, -3,-19, 37, 12, 10,-40 },
+  { -7,  2, -7,-12, 17, 11, -7,  2,  2,  3,  1, -1,  3,  4, -2, -5,
+     9, -9,  6,  4,  9, 12, 11, -5,  2, -1,  0,  9,  5, -7, -2,-24 },
+  { -7,  6,  1,  3,  1,  0,  6,  0,  4,-12, -2, -2,  1, -9, 10, -2,
+    11, -1, 21,-12, 15, -5, 10, -5,  5, -5, 14, -6,  5, -7, -3,-29 },
+  { -2,  0, -5, -2, -3,  1, -3,  0,  4,  2,  3,  0,  2, -2,  7, -2,
+     3, -5,  2, -1,  6, -4,  0, -3,  8,-11, 19, -8, 22,-34, 13,-35 },
+  { -1, -3, -1,  9, 11, -3, -3, -1,  7, 18, 11, -5,  2,-12,-11, 18,
+     9, -5,  1, -6, -9, 12,  1, -3, -3, -9,-14,  9,  9,  8, -6,-26 },
+  {  0,  5, -5, -1, -1, -2,  4,  6,  8,  2, -1, -2,  5,  1, -5, -4,
+     1,  1, 18,  1,  7,-10,  3, -2, 12, -1,-15,  9, 12,-14, 13,-38 },
+  {  3,  0, -8, -1,  0,  8, -9, -3, -8, 16,  3, 16, -5, -9,  0, -1,
+    -7, -1, -4, 13,  7,  0,  1,  2, -1,-16,  0, -2,  1,  8, -8,-28 },
+  {  7,  9, -5, -3, -2,  2,  0,  3, 11, -6, -4, -2, -2, -5, 28,-18,
+    -6,  2, 15,-10,-15,-10, -2,  0, -2, -2,  4, -3,  7, 11,  5,-30 },
+  {  9,  0, -7, -1, -4, -7,  2,  2,  9, -2,  2,  3, -8, -6, -6,  3,
+   -10,  4, 10,  5, 21, -4, 14,-18,  1,  3,-10, -2,  6, 14, -8,-26 },
+  {-14, -1,  2,  3, -3,  7,  1,-22, -1, -1,  0,  1, 12,-14,  3, -5,
+     0, 10, -3,  1, -5, 12, -3, 10, -8,-22,-11,-13, -7,-10,-13,-25 },
+  { -2, -5, -4, -4, -9,-18,  9, -3, -5, 17, 13,  5,  6, 11,  3,  8,
+    20,  4,  2,  9,  8,  5,  6,  1,  7, -7, -6, -2, -7,  0,-17,-23 },
+  { -5, -5,  2,  0,  6,  2, -2,  2, -3,  4,  4,  0, -5, -2, -4,  6,
+     8, 10, -1,  1, -5,  5,-14, -2,-11,  8,  6, 25,  7, -1,  0,-43 },
+  { -4,  0,  4, -2,  7,  0,  3, 17,  5,  2, -5,  1, 21,  3, -2,-10,
+   -16, -9,  7,-12,  9, -8,  2,  5, -5,-10, -2,-11, -5, -1, -9,-30 },
+  { -2,  3,  1, -4, -1,  0,  8,  1, 12,  4, -1, -1,  3,-17, 13,  9,
+     0,  7, -6, -5,  9,  1,  5,  4,-10,-18,  0, 14, 11, -4,-16,-28 },
+  { -1,  0,  2, -1,  4,  1, -1,  1, -1, -2, -1, -2,  3,  0,  0, -1,
+    -1,  1,  2, -2,  3,  3, -2,  4, -2, -1, -6,  1, -1, -1,  6,-70 },
+  {  7,  3,-11, -1, 12, -4,-14,  4,  4, -4,  4, -2,  2,-12, -4, 15,
+   -17, -4, -3,  6,  8, -5, 22,-22,  5,-11, 15, -4,  4, -1,-21, -1 },
+  { 10, -2,-13, 11,  4, 14,  4,  9,  8,  8, 19, 15, 14, 15,  5, 10,
+     8, 15, -5,  4, 14, -8,  1,  1,  2,  1, -1, -3, 21,  8,-29, 13 },
+  { -6,  0, -6,  6, -1,  2,  8, -4, -5,  4, -4, -5,  0, -2, -4,  0,
+     9, -2,  1, -2, 26,-19, 21,-10,  4,  1, -8,  5, 22,-10,-13, 15 },
+  { 11, -5,  1,  0,  6,  3,  7, -2, -2, -3, -5, -1, -2, -6,  1,  1,
+    -8, -5,-13, 13, -2, -3, -1, -9,-28,  4,  2,-11, 18,-20,-24,  9 },
+  {  7,  4, -3,  6,  6, -6, -7, -5, -7, -4, -4,  0, -7, -5, -6, -5,
+     2,-13,-12,  2,  0,  5, 18, 15,-13, -7, 13,-20, 16,-10,-19,  6 },
+  {  5, -8, -1,  5, 10,  2, -1,-10,-11, 23,  8, -5, -8,  4, -5, -4,
+    -5, -5,-11, -8,  5,  1,  7, -9, -9, -6, 12, 14, 17,-12,-22,  3 },
+  { -5, -8, -3,  3, 12, -1,  0, -4, -5,  1,  1,  6,  1,  5, -5,  7,
+    -2,  7,  1,  6,  6,  2,  0, -5, 17, -4, -5,-24, 13,-20,-27, 14 },
+  { -1,  2, -3,  1, -3,  1, -3,  0, -2,  3, -2,  1,  2, -1, -2, -1,
+    -2, -5,  5, -2,  0, -7,  1, -6,  8,  8, 11, -5, 24,-43,-13,  2 },
+  { -2,  4,  7, -3, -4,  4, 13, -4,  0,  0, -2,  9,  0, -3, -6,  1,
+    -7,  1, -1, 10,  0,  5, -1,-24, 25,-15,  7,  2, 22,-10,-21,  0 },
+  { -5,  2,  6, -2, 13,  3,  5,-12,-11, 16,  6, 10, -5,  0, -3,  6,
+     5, -5, -5, 10, 12, 10, 11, -7,  8,-14,  2,-15, 13,-14, -8, -3 },
+  {  5,  6, -7, -5,  5,  2,  9,  5,  0, -1, -4,  2,  8,  0,  3,  5,
+   -12,  3, -3, -6,  2, -1, -5, 14, 11,-20,-21,-25, 24, -1,-10,  6 },
+  { -5,  5, -2,  9,  4, -4, -1, -6, 11, -6,  5,  0,  2, -3,  6, -1,
+   -17,-18, -4,-13,  9, -1,  9, -7, -4, -8,  2, -3, 12,-31,-18,  5 },
+  { -7,-11,  6, -8,  4, -3,-12,  0, -1, -6, -3,  0,  5,  9,  7,  2,
+     1, -8, -6,  8,  2, -5,  7, -1, 16,-10, 16,-12, 18, -1,-25,-12 },
+  {  3,-12,  1,  2, -2,-18, -8,-15,-10, -9,  2, -7, 11,-11,  2, -1,
+    -1, -1, -9, -6,  3,-14, -2, -1,  2,-13, -7, -9, 19, -5,-17,  2 },
+  {  7,  1, -8,  7, 17,-13,-10,  5,  7,  1, -6,  4,  9, -4,  0,  3,
+     8,  1,-14, -9,  4,  7, -9,  0,  6, -5,-12, -2, 25, -2,-19,  1 },
+  {  7, -3,  6, -3,  1,  6, -7,  0, 10,  0,  4, -5,-17, -4,  4, -1,
+     0, -3, -7, 19, 24, -1, 21,  8, 10,  9,  8, -1, 23, -2,-18, -2 },
+  {  3, -3,  0,  5,  8, -2, -9,  2,  9,  6, 19,  8,  2,  6, -9, -2,
+    -4, -3, -8,  7, -7, -8,  5,  4, 26, -6,  7, 18, 24,  0,-13,  4 },
+  {  0,-13,-11, -1,  3, -9,  5,  4, -7,  3,  0,  2, -1,  4, -5,  2,
+     9, -2,-11, 15,  1,-21,  1, -1,  0,  4,-14, -4, 24,-16,-13,  1 },
+  {  1, -9, -8,  0,  0, -4, 11, -1, 14, 16,  0, 17, -2, -9,-12,  0,
+    -1,-14, -9,-14,  0, -2, 19,  4,  6,  4,  4,-11,  8,-17,-19, -5 },
+  { -3,  1,  2, 12, -4,-18, -1, -4, -7, 14, -3,  2,  0, -7, -8, 12,
+    -5, -9, 14, 12, -9, -2,  4, -6,  4, 18, -1,-25, 22,  2,-23, -5 },
+  { -2,  0,  0,  0,  1,  3,  5, -1,  5, -2, -2,  2, -3,  0,  1,  2,
+     0, -1,  2, -1, -9, -6, -7, -4, -2,  4, -7, -5, 64, -3,-25,  4 },
+  { 12, -2, -3,  0,  8, -9, 13, -7,  6, -3,-12, 12, 15, -9, -4,  2,
+     9, -4,-12,  3, 14,  1,  7,-15, 15,  0, -6,-12,  0, -3,-20,  6 },
+  {  2, -1, -4,  5,  9,  6, -7,  2, -2, -7, -2,  0, -1,-18, -4, -6,
+   -15, -5, 11,  5,-10, -1,  2,  7, 12,-19, -7,  8, 21, -4,-15,  4 },
+  {  4,  2,  5,  5, -5,  1,  3,  2, -8, 13,  0, -5, -2,-14,-11,  6,
+     2, 17,  8,-13, 26, -2,  5,-15, -4,-14, 12, -9, 13,-21,-23, -4 },
+  {  2, -3, -2, -3,  3, -2,  6,  9, -9, 13,  4,  2, 12, -3, -3,  1,
+   -17,-22, -3,  4,  3, -2,  1, -9,  1, -6, 11,-13, 14,  0,-15,  6 },
+  {-16, -4, 17, -2,-20,-11, 11, 10,  5, -8, 16,  2,-17,-14, 11, 11,
+    -6,-11, -7, 12, 12,-10, -6,  5,  8, -4, -2, -5, 28,  3,-13,  4 },
+  {  0, -3,  3, -7,  6,  8,-12, 20,-19, 18,-11, 10, -5,  0, -9, 11,
+     3,  0, -2,  9, -7, -5, 18,  3, -2,-16,  1,  6, 12, -7,-16,  1 },
+  {  4,  1,  5, -5, 15,  2, -8,  3,  5,-11, 15, -3,  8, -8, -1,  7,
+     4,  7, -2,  6, -9,  5, 12,  2, 33, -2, -6,-18,  4,  0,-18, 11 },
+  {  3, -1,  1, -1,  0,  1,  4, -1, -5,  0,  1,  0,  4,  2, -1,  4,
+    -3,  2,  0, -2,  4,  6, -1,  6, 42, 19, -4,-37, 19,  1,-15, -4 },
+  {  2,  0, -5,  0, 10,  0,  0, -5,  3,  0,  0, -3, -3,  0,  2, -4,
+   -10,  2, -6,  4,  4,  1, 27, -7, 17,-34,  5, -9, 15,-16, -7, -5 },
+  { -2,  7,  7, -2,  9, -2,-15, 11, 11,  7,  5,  1, 15,  1, -9, 31,
+     2,-15,  2,  4,  3,  4, -1, -8,  2, -7,  6,-17, 11,-14,-11,  2 },
+  {  1,  1,-11,  9,  9, -6,-14,-11,-10,  8, -3, 11, 16, -9, -8,-13,
+    -8,  9,  0,  6,  6, -2, 13, -8, -2,  3, 13, -3, 10, -6,-17,  4 },
+  { 14,  5,  4, -6,-12, 10, -7,  8, 21, -8,-30, 15, -2,  1, 11, -9,
+    -5,  1,  0, -1, -1, -6, -2,  3, -5,  7,  9,  5, -5,  2,  0,  1 },
+  { -1,  2, 20,-17,-15,  3,  3,  7, 11,-17,-13, -6, -3, 18, 17,-15,
+    -4, -4, -5, 22, 14,-14, -2,-10, -7, 11,  8, -7, -3,  0, -7, 11 },
+  {  7,-11, -7, -8,-14, 22,  5,  2,  6, 13,-12, -2, 10,  3,  0,-21,
+    -4, 20,  3, 10, 21,-10,-12,  8, 11,  2, -5,  2,  1,  3, -1, 15 },
+  { -1, -2, -1, -2,-13,  8, -4,  0,  7, -2,-17,  8, 18,  5,  3,  8,
+    -8, -2,  3, -4, 14,-18,-13, 14, 15,-13, -1, -2,  4, 11,  1, 12 },
+  { 13, -6, -4,-16,-17, 16, 21, -2,  5,-11, -9, 19, 21,-17, -3,-17,
+     3, 12,  8,-12, -6,  1, -7,  9,  9, -7, -5, -1, -3,  5, -6, -4 },
+  { 11,  5, 12,-20, -6, 10,  4, 12,  8, -5,-10, 15, 13, 14, 10,-15,
+   -13,  1,  6, 14, 15,-17,-13,  4, -5, 10,  7, -6, -8, -3, -4, 12 },
+  { 25, -1,  7, -5, -7, 11,  1, 17, 13,-15,-14, -4,  5,  3,  8, -3,
+    -2,  2,  0,  6, 16,-12, -6, -4,  4, -3,  7,-10, -3, -7,-13,  7 },
+  { -8, 10, -3,-13,  5,  2,  4,  9,  9,-17,-13,  2, 11,  1,  6, -4,
+     8,-10,  4,  1, 19,-15, -4, 12, 31,  7, -5,-17, -4,  9, -2,  7 },
+  { 14, -6, -6, -6,-14, 13, 17, -5,  4,-14, -9,  7,  7, -9,  3,-16,
+   -15, 11, 11,  6,  4,-11,-19,  3,  5,  8, 13,-14,-14,  3, -4, 12 },
+  { -2, -4, 10, -4, -7, -1, 27,  5,  2,-16,-18,  4, 12, -2, -3, -2,
+    -1,  1, -8,-12,  3, -4,  8, 15,  2,  4,  9,-13,-14,  9, -7,  5 },
+  {  4,  2,-10, -5, -7,  2,  1,  4, -1, -6,-15,  6,  1, 10,  5,-10,
+    -9, -1, 13, -3,  5,-21,-11,  8,  8,  5, 27,-21,-18, -5, -1, 15 },
+  { 11,  1,-16, -8,-11,  0,  5, -8,-12,-13,-17, 22,  4, -6, -1,-18,
+   -10,  0, 19,  2, -2, -8, -7, -3,  2, -2, -9,-17, -5,  4,  4, 10 },
+  {  8, -6,-19, -5, -4, 12, 14, 15, 10, -9, -1, -9, 19, 12,  0, -1,
+     2,  4,  7,  9, 16,-16,-14,  9, -4,  3,  1,  0, -2, 10, -1, -1 },
+  { 12, -8, 12, -9,  0, 25,  7,  9,  2,-31, -9, -4, 15,  4, -5,  1,
+   -10, 11,  8, 10,  0, -6,  5, 11, -1, -6,  4,-10, -9,  6,  4,  5 },
+  { 14,  6,-17, -2, 17, 12, -9,  2,  0,-25,-14,  5, 20, 14,  8,-20,
+     5,  2, -2, -3,  9,-13, -3, -1, -6,  3,  7, -6,  0,  2,  3,  1 },
+  {  8,  4,-15, -3, 10, 18, -4, 13,  8,-22,-10,  9, 19,-15,  7, -5,
+   -13, 12, -4,  9,  2, -9, -6,  0,  2,  1, -9, -6,  6,  1, -1, 11 },
+  {  4,  1,  4, -5,-10, 18,  7,  2, -4, -9,-11,  0, 32, -7,  4,-16,
+    -1,  0,  6,  3,  6, -3,-14, 16,  9, -2,  7, -1,  0, -5,  5, -3 },
+  { -3,  2,  3, -8, -6,  4,  6,  2,  4,-12,-15,  2,  8,  8,  9, -3,
+   -18,  6, 34, 11, 12,-15, -1,  2,  9,  2, -4, -4,  2,  4,  2, -3 },
+  { 18, -6,-12, -8, -1, 15, 20, -4, -1,-11, -5,  6,  6,-11,-15, -7,
+     3,  7, 10,  2,  8,-10, -5,  8, 15, -5,  5,-17,-13, 13, 11,  7 },
+  {  8, -4, -6, -1,-14, -3,  6, -2,  1, -5, -1, 10, 10,-15,  5,  0,
+   -10, -4, -3,  7, -4,-19,-15, 27, 11, 18,  3,-19, -2,  6,  0, 12 },
+  { 12,  0, -5,  0,  4, -5,  1,  5, 10, -7,-11, 21, 29,  1, -2,  1,
+    -4,-11, -1, 13, 11,-20, -1,  4,  4,  4, -5,  6,-13, -2, 11,  9 },
+  {  2, -7, -7, -3,-10, -1, 20, 12,  1,-19,-19, -1,  5,  4, -7,-25,
+    14,  1, -3,  2, 12, -4, -3, -3, -2,  6,  1,  0,  3,  2,  5, -1 },
+  { 12, -8,  3,-12,-10, 10, 13,  0, 23,-14,-18, 10,  0, 15,  3,-12,
+    -3, -5,  5, -4,  2,-14,-10,  8,  2,  9, -1,-11, -3,  5, 13,  2 },
+  {  9, -6,  7, -7,-30, 17,  6, 13,  1,-14,  0, -1,  6, -9,  8,  3,
+    -4,  0, -1, -7, -5,-13,-19, -3, -4,  4, -6, -2,-13,  1, -2,  3 },
+  { 10,  1,  3,-18,-26, 17,  4,-16,  4, -3,-13, -4, -6,-11, -4,-21,
+     7,  8,  2,  5, 13, -6,  1,  5,  8,  7,  9, -6, -6,  1, -1,  2 },
+  { -3, -1,  0, -2, -2,  0, -1,  3,  4,-14, -8, -9, 13,  2, 50,-23,
+    -8,  8,  7, 11, 16,  3, -7,  0, -2,  6,  5, -1,  1, -2,  4,  3 },
+  {  1,  3,  1,  1, -6,  3,  6,  6,  2, -2, -3, 10,  2, -8, -5, -5,
+     5,  4,  4, -2, 10, -8,-40, -1, 21,  8,  3, -4, -1, 13,  4,  7 },
+  {  2,  0, -4, -8,  5,  2,  7, -5,  5, -8, -4, -1, 12,  2, 12,-13,
+    -9,  0,  1,-12,  9,-43,  1, -5, 12,  1,  3,  6,  1, -1,  3, -2 },
+  {  6, -2, -1,  1,  0,  4,  8, 14,  4, -7,-23, -5, 23,-17, -6,-15,
+    -8,  7, 10, -1,  7,-16,  4, -6,  2,  3, -3, -3, -1,  8, -1,  4 },
+  { 10,  4, -4,  1,  7, -3,  2, 11,  4, -6, -3,  8,  5,  4,  1,-45,
+    -6, -4,  4,  2,  1,-14,-10,  1,  1,  6,  2, -8, -1, -3,  3,  3 },
+  {  1, -1,  2, -3, -8,  9,  3,  3, -2, -5, -8,  8,  7, -7, -4, -6,
+     5, -9, 11, -2, 46, -5, -1,  9, -2,  0,  3, -5, -3, -5,  7,  0 },
+  { -4,  1, -2, -1,-11, 11,  8, -3, -2,-10,  0,  4,  9,  9,-17,-17,
+   -34, -4, -5, -7, -3,-12, -3, 11, 18,  3, -2, -5,-18, -5, -3,  6 },
+  {  7, -5, -3,  1, -4, -3, -5, -1,  2,  5, -2,  3,-10, 12,-18, -5,
+   -10, 12, -9,  4, -6,  2,  0, 16,-17, 15, 14,-12,-10, -2, -9, -1 },
+  {  4, -5, -3, -5, -3, -1,  7, 18, -7, 12,  3,  5, -8, -4,-20,  1,
+   -25,  1, -8, 13,-10,  8,-19, -1, -8, 10,  6, -9, -1,  0, 12,  4 },
+  { -4,  5,  0, -1,  2,  5, -8, -2, -6,  4, -8,  9,  3,  2, -7,  4,
+   -25, 13,-23, 10, 14, 15,-11,  3,-18,  4, 16, -4,  1,-10,-10,  3 },
+  {  5, -3, -1, -3,  4,  1, -3, -4, -5,  1,-12, 14, -7, 11,-15,  6,
+    -6, 24, -4, 13, -1, 15,-13,  8,  3,  7, -5,  2,  2,  0,  3, -7 },
+  { -3,  1,  0,  8,  6, -1,  6,  5, -5, -2,-12,  4,  0, -2, -3,  5,
+    -6,  0, -8,  9,-10,  4,-28, 12,-20, 11,-13,  7,-18,  1,-11,  1 },
+  {  1, -4,-15,  5,  0,-13, -5, 13,-11,  4, -4, -5,  5,-14,-16,  0,
+   -14,  5,-20, 12, 10, -7, -5,  6,  6, 22,  6, -4, -2,  3,  8, 11 },
+  { 13,-11, -2, 16, 16, -7,  0, 20, -7, -1,  0,  5, -9, 12, -2, -5,
+   -22,  5,-10, 12, -6, 11,  9, 21, -8, 15,  4,  0, -8, -4, -4, 10 },
+  { 18, -4,-13,  0,  1,-15, -1, -3,  2, 10, -1,  6,  1, -4,-20, -5,
+    -8,  6, -8, 17, -5,  5,-10,  8,-22,  6, -5, -2,  8,-17,  8,  2 },
+  {  1, -2, -9,  6,-31, -8, -8,  8,  0,  5, -9, -4,  2,  3,-12, 11,
+   -18, 10, -5,  3,-11, 13, -6, 11, -3, 12, -7,  3, -9, -1,  2, 11 },
+  { -9, -6, 21, -8,-15,  4,-11, 12,-11, 17, -1,  2, -6,  0,-15, 13,
+   -12, 19,  0,  2, -6, -3, -9, 10,  3, 17, -2,  5,-10, -3,  0,  1 },
+  {  4, -6,  5,-10,  1, -5,  1,  0,  0,  0,  2,  7, -2,  2, -2,  0,
+    -4,  3, -4,  1,-12,  6,-49, 16,-10, 13,  0, -2,  8,  6,  1,  8 },
+  {  5, -8, -7,  9, 13, -5,  7,  0, 10, 11, -4, -3, -1, 13,-14,  6,
+   -15, -6,-14, 16, 15,  1,-18, -4,-20, 20, -7, -1, -9, -2,-10, 10 },
+  {-12,  4,  0, 10,  0,  3,  8,  4,-27, -1, -2, 19, -4,  2,-13,  3,
+     1,  9,-12,  1,-22, 19, -5,  4, -9, 12,  2, -9, -8, 11, -3,  7 },
+  {  4, -5, 11, -6, 17,-17,  5, -4, -2, -6,  1, -5,  2,  4,-14,  6,
+   -20, 19,-20, 12,-21,  5,-14, 13, -2, 11,  4, -3,  0,-10, -4, -2 },
+  { -2, -1, -3,  8, -9, -7,-22, -3,-24, 13, -2, 10,-15,  5, -9,  4,
+    -7,  0, -5, 15, -8, 11,-13,  6, -4, 19, -8, 12, -4,  6,  9,  7 },
+  {  2, -3,  2, -1,  0,  3,  1,  2,  1, -4, -2, -3,  1,  5,-12,  6,
+   -16, 14,-23, 10,-14, 17,-15, 16, -2,  9,-25,  9,-10, 16,  4,  9 },
+  { -3,  7, -8, -3,  2,  2, -4, -8, -9, 10,  3,-11, 25,-10,-28, 27,
+    -9,  7,-13,  9, -2,  4,-12, -8,-14,  6,  7,-10,  3,  3, -3,  5 },
+  { -8, -3,  1,-10,  8, -3, -9, -4, 13,  7,  2,  4,-10,  4,  3,  7,
+   -18,  2,-22, 15,  4, 20, -7,  5, -6, 13, -1,  4, -7, -6,  6, 13 },
+  { -2,  3,  0,  2, -4, -2,  0,  0,  1,  2, -2, -5,  0,  1, -4,  0,
+    -2, -3,  1,  2, -1,  2, -8, -1,-24, 68, -3,  8,  3,  3, -1, -1 },
+  {-15, -2, -9, -7, -1,  8,-14,  8,  3,  6,  0, -1, -8,  8,-23,  2,
+   -14, 17,-15,  8, -4,  7,-18,  0, -8, -3, -1, -4,-10,  4, -1,  4 },
+  {  8,  0,  2, -7,  0,  5,  1,  3,-11,  4, -8, 14,  3, 20,  1, 26,
+   -11, 13,-13, 20, -2,  0, -8,  2, -6,  6, -1,  9,  3, -6, -3, 10 },
+  {  5,  0, -1, -7, 10,  1, -3,  5,  4,  7, -5, -1, -3, -1, 12, -3,
+   -15,  7, -9, 22,-19,  8, -9,  4,-23, 13,-14,  6, -6,-14, -4,  7 },
+  { 14, -5, -8,-10, 25,  3,-23, -7,-28,  0, -1, -9,  4,  1,-13, 20,
+    -8, 10,-16,  8, 12,-13,-21,  5,-13, 11, -2,  1, 12, -7,  2,-10 },
+  { -5, -4,  9,  5, -6, 35, -7,  8, 15,  2, -1, -9, -6,  2,-18,  7,
+   -15,  6, -3,  2,  8, 12,-30,  7, -4, 20,  2,  6, 13, -6, -4,  0 },
+  {  1,  8, -9,  9, -5, 12, -9, 16, -9, 16,-17, 14,-13, 15,-18, 14,
+   -15, 17,-12, 14,-13,  7,-16, 13, -9,  5,-11, 10, -9,  6,-12, 13 },
+  {-10, -4,  5,  3,  1,  6,  8,-14, -5, 15,  7,  4,  8,  7,-22,  8,
+    -7, -8,-15, 26,  1, 13, -3, 17, -5,  9, -2,  4, -6,  3, -8,  9 },
+  {  8, -3,  2,  3,  3,  1, -2, -1,-11,  8, -4,  0, -6, -5, -1, 13,
+   -37,  9,  1, -6,-10, -2,-10, 11,  8, 13, -3, -2, -6,  8, -4, 13 },
+  {  3,  2, -3, -4, -4,  7, -8,  9, -8,  9,-20, 12,-19, 15,-18, 17,
+   -15,  7, -1, 20,-11,  6, -6,  3,  1,  9,  2,-14, -2, -2,  2,  1 },
+  { -7,  1, -1, -3, -6,  4,  4, -3,  3, -1,  5, -4,  3,  2, -1,  9,
+   -59,  5, -4, 30,  3,  3, -2, -3, -1,  2,  2,  1, -1, -1, -2,  1 },
+  {  0, -3,  2,  0, -1, -8,  0,  2, -3,  4, -4,  1, 10,  6, -6,  8,
+    -7,  4, 10, 11,-41, 27,-20,  3, -3,  8,  1, 11, -5, -8,  0,  4 },
+  {  5,  1,  4, -2,  1,  2, -1,  6, -7,  2, 11,  4,  0,  0, -8,  7,
+   -10,  0,  0,  8,  2, 10, -1,  1, -2, 44, -2,-21,-12, -3, -1,  2 },
+  { -4,  4, -2, -2,  6, -8,  2,  1,-10, 14,  8,  6,  5,  1, -2,  4,
+   -13,  4,  2,  5, 10, -2,-21, 32, -3, 18,  9, -6, -9, -9, 10,  2 },
+  {  9,-16, -6, -2,  1,  4, 22,  2, -2,  1, -3, -2, -9,  3, 16, 19,
+   -24, -6, -6, -5, -8, -7,  8, -7, -1,-12,  5, -3,  0,  4,  2, -3 },
+  { 10,  3,-16, -4, -1, 13,  4,  4,  1, -3,  1, -6,-14, 18,  3,  8,
+    -8,-28,-16,  4,  4,  2, 12,  7,  9, -4, -4,  5, -1, -1,  2,  2 },
+  { -5,-13,-22, -3, -8, 21, -2, -9, 21, -4, -9,  5, -8, 15,  5,  1,
+    -5, -9, -7, -2, -5, -5, -1, -5, -5, -5,  3, 10, -4,  0, -7, -2 },
+  {  5,-10,-18,  2, 20,  4, 13,-10,  8,-15,-11, -3, -1, 16, 10,  9,
+    -8,  6,  7, -5,  6, 11,  5, 17, -4,  7,-11,  5, -3, -6,  2,  1 },
+  {  3, -5,-19,  1,  1, -3, -2,-25,-11,-17,  0,-13, -4, 10, 10,  2,
+    -5,  4,  0,  3, -3, -5,-10, -2, 13,-22,  0,  3,-11, -5,  7, -1 },
+  { 12,-14,-29,  6, -1, 10,  7,-17,-12, 14,  3,  9, -9,  9,  7,  6,
+    -3,-13,  0,  5,  3, -1, -6, -1,  0,  2,  4,-12, -5, -1,  2, 11 },
+  { 12,-15, -7, -2,-12, 17, 20,-16, -2,-12, -6, 15, -6, 12, 11,  9,
+     7, -6,  7, -4,-19,  6,  2,  2,  3,-11,-10, -4, -5, -3,  3,  2 },
+  { 11,-22, -6,  0,  8, 18,  3,-11, -4, -7,-15,-17,-12,  6, 16,  4,
+    -9,  4, -5,  3,  6,-16, 10, -7, -7, -3,  5,  0,  1,-15, -4,  5 },
+  { 12,-22,-16,  5, -6,  8, 12, -4, -9,-17,-11,  3,  5,  8,-17,  0,
+    11, -4,-13, -6,  2, -1, -1,  3,  3,-11,-12, -1,  1,  1, 12, -2 },
+  {  8,-10,-33, -5, -3, -6,  1, -7, -8, -4, -6, -1,  5, -4, -6,-12,
+   -16, -8, 11,  8,-14,  7, 12, 11,  4,-14, -3,  6, -7, -5, -3,  3 },
+  {  0, -8, -7,  2, -4, 24,  2, -9,-11, -3, -7, 11,-12, 17,  1, -1,
+     3, -5, -7, 12,  4, 11,  0,  3,  2,-18, -3,  4,  7, -6,  3, 15 },
+  { 10,-15,-16, -2, -4, -9,  7,-15, -6,  2,-16, 13, -8,  7, 19,-21,
+    -4,-12, -9, -3, -3,  6, 11, -3, -1,-19,  3, -7, -9, -4,  3, -6 },
+  { -5,-10,-21,  0, -3, -7, 18,-21, 15, -5,-12, -4,-13,  2,  6, -9,
+    -9,-11, -4, 13, -3,  6,  4, -1,  7, -9, -4,  9,  5,  2,  6,  3 },
+  { 15, -1,-27, -2, 10,  3,  7, -8,  9, -2,  7,  1, -2, -5, 18,  9,
+   -11,-17, -2,  7, -9, 11, 10,  0, -8,  6,-16, -3,  2, -7,  3, 11 },
+  {  4, -9,-39, 19,  6,-13, 13, -5, -5,-15, -2,  9,  0,  4, 14,  6,
+   -10, -4, -5,  2, -4, -2,  5,-11,  3,  3, -2, -2, -7,  9,  7,-10 },
+  {  5,-11, -8, 10, -2, 12, 16,  0, 12, -2, -6,  8, 14,  8,  7,  1,
+    18,-30,  4, 10, -4, -6,  2,-11,  9,-10, -8,  5,  0,  0, -7,  6 },
+  { -1,-16,-10, 11,  0, 13, 12, -4, -4, -5,-21, 12,  4, 13, 14, -7,
+     6,-16,-13,  8,  2,  9, 15,-12,  1, -9,-22, 10, -9,  9,  9, -7 },
+  {  4,-12,-27,  1, -2, 11, 15,  3, 14,-14, -9,  0, -9, 16, 22, 10,
+    16,-10,  5, -5, -9,  1,  1,  6,  6, -4,  2,-17, -5, -6,-15, -1 },
+  {  7,-12,-17,  1, -9,  5, 20, -7,  3, 23, -8, -8, -8, -1, 13, 17,
+    -7,-13,  4, -4,  7, 14,  8, 11, -3, -3,  4,  0,  4,  6, -1, -9 },
+  {  7,-15,-15, -4, 10, 12,  3,-13,  6, 14,  9, -8,-15, 14, 23, -5,
+   -10, -5,  1, 15,-10, -7,  1,  9,  4,-13,-10, 10,  7, -3,  2,  3 },
+  {  4,-10,-14,  0,  3,  4,  0, -9, -3, -4,-11,  2,-17,  8,  2, 15,
+     6,-12,-12, 15, -5, 17, 18,  3, -3, -3, -4, -6, -8, 13,  4, 10 },
+  { -2,-18,-26, 10, -4, 10, 13,  4, -4,-16, -7,-17, -3,  5, -4,  2,
+   -15,-10, -1, -8, -7, -3,  2,  2,  8,-10, -7,  2,  2, -4,  4, -1 },
+  {  4,-19, -5, -1, -1, -6,  2, -8, 10,-16,-28, -6,  8, -1, 11, 28,
+     2,-10, -4,  6, -6,  6, 11, 15, -4, -2,  7,  3,  7, -7,  4,  1 },
+  { -3, -6,-10, -5, 13, 18, 10,-15, -5, -3,-13,  5,  1,  2, 18, -5,
+   -10,-10, -7,  4,  2,  1,  5,  4,  2,  5,  4,  8, -9,-17,  7,  7 },
+  { 20,-12, -2, -4,  5, 14,  7,-11, -1,-16, -6, -4,-11, 17, 14,  0,
+    -8,-10, -8, 10,  3,  5, 10,-16,  3, -8,-14, 10,  3,  9,  0,  3 },
+  { 12,-10,-36,  0,  7, 15,  2,-16,  2, -1,  0, -1,  5,  4,  5, -3,
+     1,-10,  5, -1,-15, -3,-12, 12,  2,  5, -1,  5,  6, -3, -2,  2 },
+  { 17,-15,-31, 23, -4, 15, -2, -3,  6, -7, -5,  1,-12,  4,  6,  8,
+   -10,  8,  3,  5, -4,  1,  5,  3, -1, -4, -3,  1, 10, -4, -2, -2 },
+  {  6,-18, -5, 12, 10, 12, 14,-11, 15,  2, -9, -6, -5, -2, -9,  4,
+    -5,-28, -4, 14,  0,-16,  9, 14, -1,  3, -4, -4,  2,  1,  0,  4 },
+  { -5,-14,-31,  8, 16,  7, 13,-13,  5,  6,-16, 10, -5,  2, -2,  2,
+    14, -5,  8, -5,  7,-16,  6,-13, -5,  0, -5,  8, -3, -1,  4,  3 },
+  {  1, -2, -1,  0,  6,  5,  2, -4, -3, -1,  0,  1,  4,  2, 43, 28,
+   -12,-35, -2, -2, -7, -1,  0,  2, -1, -2, -2,  1, -4,  0, -2,  3 },
+  {  2, -9,-22, 12,  3,  3, -7, -4,-19,-22,-14, -4, -1, 21,  9, -3,
+   -15,-16,-13,  1,-11,  4, -9,  1, -7, -1, -1,  0, -2,  9,-13, -3 },
+  { -1, -3,-23,  0,  2, 12,  3, -9, -4,  7,  3,  9,-10,  1, 27, 28,
+     0,  9,-15, -2, -2,  1,  6,  8, -8,  7, -3, 20,  0,  0, -1, -6 },
+  { -1, 11,  8, -2,  1,  5, -6, -1,  4,  2, -4,  0, -1, -5,  4, -6,
+   -10,-12, 19,  1, -7,  9, -8, -9,-16,-11, -2, 12, 14,  4,  4, 34 },
+  { 17,  7, -6,  1,  4,-10, -5,  4,-11,  3,-18,  4, 14,-13, -3,  1,
+     0,  0,-11,  0,  7,-17, -4,  4,-11, -6, -8, 18,  0,  0,  0, 26 },
+  { -6, -7, -1, -1, 11, -8,  1,  3,  2, 11, -6, -6, 10, -3,  1, -3,
+     7,  4,-12, -8,  0, -9,  8,-22, -5,  0, -6, 22, -2, 11,-13, 24 },
+  { -3,  4,  0,  3,  9, 10, -1,  3, -9,-12,  1, -5, 18,  0, -3,  8,
+    25, 15, -8,  2,  2, -2,  4,  8,  9, -1, -5, 10, -3,  1, -1, 23 },
+  { -5,  2, -9, -1, -3,  0,  3, -1,-10, -4,  0,-13, 16,  9, -1,-14,
+     2,  6, -2, -6, -5, -2, -7,  7,  5,  3, 11, -2,-14,  0, -9, 30 },
+  {  4,  6,  6,  5, -3, -1,  4,  5, 10,  0,  5, -4,  7,-11, 14, 14,
+     7, 34, -9,  0,-10, 22, -7, -1,  7, -9,  2, -8,  0, -7, -5, 29 },
+  { -4,  3, -1, -4, -3,  5,  1, -4,  0,  2,  4,  2,  1, -1,-10,  1,
+     6, -6, -4,  1,  4, -3, -3, -5,  0,  3,  7,-12,  0, -2,-10, 55 },
+  {  5,  9, -1,  0,  4,  9,-21, -9,  4,  2,  6, -7, 11, -7,  1, -5,
+     0, -4,  2, -3,-13, -8,  0, -9, -4,  2, 16, -2,-15, -7,-11, 31 },
+  {  8,  2, -1,  0,  3, -5, -5,  5,  1, -1, -9,  1,  0, -6, -2, -1,
+     5,  2,  0,  0, 12, 20,-19,  1,  8,-12,-11,  0,  6, -5,  2, 31 },
+  { -1, -1, -2,  1, -1,  3, -9, -5,  8, -2,  5, -1,  0, -2,  4, -2,
+    -3,-12,  0, -2,  3,  0,  9,  4, -1, 21, -8,  3, -4,  9, -6, 30 },
+  { -4,  0, -7, 17, 10,-12, -2,-10,-12, -3, 10,  0, 11, -4,-13, -3,
+     5,  6, 10,  7, -8,  0, -7,-13,  1,  0, -2,  7,-12,  4, -3, 24 },
+  {-13,  9,  4, -2,  2, -4,-14, -1, -3, -5,-10,  4, 13, -2,  5, 13,
+     8,  3, -2,  1,  5, -6,  7,-18,-10,  1, -1,  5,  4,  1,  0, 25 },
+  { -5, -1, 18, 12,  8,  8,-16, -1,  1,  1,  1, -4, -5,  3,  3,  4,
+     4,-11,-12,-16, -6,  2, 12,-13,  0,  9,  7,  9, -9,  0,-10, 24 },
+  { -4,  1, -3,  0,  2, -4,  4,  1,  5,  0, -3,  2, -3, -2,  2, -1,
+     1,  4, -1, -2, -2,  1, -1, -1, -4, -1, -4, -2, -6,  6, 12, 69 },
+  {  8,  5, 11,  0,-15, -4, 13,  6,  0, -4,  9,  1, -5, -3, 15,  0,
+     1,  6, -5,  0,  1,  6,  5,  8,  0,  7,  1, -1, -4,-11, -9, 41 },
+  { -4, -9, 32, -6,  0,  7, -4,  6, -6,  1, -6, -2,  4, -8, -5, -3,
+   -16, -1, -2, -6,  1, 15,  0, 21,  3, -3, -4,  3,-12, 16,  2, 27 },
+  { -6, -5,  1, -9, -5,  3,  7, -3,  5,  5, 14, 13, 20, -7, -1, 12,
+    -1, 10,-11,-11, -7, -4,-14,  7,-14, 13, 22, 18, -1,  0, 14, 28 },
+  { -8,  3, -2,  0,  5,  6, -1, -4,  1,  3, -7,  3,  1,-15,  4, -9,
+    22,-10, -9, -4,  1,  8, -4,  9,-15,  2, -6, -4,-16, 12,-10, 23 },
+  {  0,  0,  2,  0, -1,  3, -3, -1,  3, -5,  7,  1,  5, -5, -8,  1,
+    13,-15, -5, -7, 12, -6, -2,  3, 10, -5, -8, 17, -5,-11,-14, 23 },
+  { -7, -4,  6, -4,  5, -6, -5,  2, -4, 11,  9, -4,  2, -2, -4,  6,
+    15,  3, -3, 18,-15, -2, -6,  3,  3,-20, 17, 11, -4,  2,  3, 29 },
+  {  6,  1, -6,  2,  3,  0,  0, -3,  3,  3, -1,  3, -4, -6, -6, -7,
+    -3, -2, -7, -2, -4,  5,  3, -5,-20,-13, -4, 10,-14,-29, 14, 37 },
+  {  3,  4,  3, -6, -4,  5,  0,  3,  2,  3,  0, -2,  4,  0, -3, -5,
+    -4,  4, -4,  4,  4,  3,  1, -4, -4, -9,-14, 20,-30,  3,-18, 33 },
+  {  0,  2,  5, -2, -4, -2, -1,  2, -6, -3, -2, -2,  2, -5, -1,  4,
+     3,  2, -3,  0, -1, -1,-10, -7,  2, -4,-18,  2,-37, -1, 12, 40 },
+  { -7,  2, -1,  0, -2,  4, -8,  1, -4, 12,  7,  4, 15, -7,  1, -9,
+    18,  0, 12,-17, -3, -1,  0,  0,  0,  2, -6,  0, -4, -3, -1, 26 },
+  { -6,  4,  8, -5, -6, -2,  2, -1,  1, -1,-15,  8,  7, -1,-17, -4,
+     1,  5,  6,-11, -6, 14, 17, -5,-15, 11,  8,  0, -3,-15, -6, 28 },
+  { -1,  0,  0,  0,  1,  0, -1,  0,  1,  3,  2, -2,  3, -1, -1,  2,
+     2, -1, -1, -7,  1,  2, -9,  0, -1, -4,-18,  7,-10, 49,-13, 32 },
+  { -1, -3,  4,  1,  2, -5,  1, -7, -1,  5, -9,  4,  4, 25,  1, -1,
+     2, -5,  2, -7, 17, -2, 10, -5,  0,  2,-15,  3, -9,  7, -9, 30 },
+  { -5, -1,  0,  2,  1, -1,  2,  5,-33,  3, -5, 14, 11,  7,  5, -3,
+     2, -8, -4, -2, -7, -6,  4, -8, -1, -8,  2, -2, -8, -1, -4, 27 },
+  { -1,  0, -1, -2,  1, -1, -2, -1,  2,  0,  1,  2,  2,  4,  1,  3,
+     4,  2,  1, -7, -4,  1, -3, -4,-35,-25, 17, 10, -3,-26, -7, 32 },
+  { -5,  1,  6, -2,  6,  6, -9,  3, -1, -4,  5, -4, -2, -2, -9,  2,
+    -5,  2,  2,  4,  3,  5, -5,-16,-31,-12,-11,  2,-19, 20, -2, 21 },
+  { -5,  2,  7, -7, -7,  5, -7,  2,  0,  0, -4,  3, -1,  0, -1, -2,
+     0, -3,  5,-11, -8, -3, -7, -7, 28,-11, -7,  0,-16,-11, -4, 29 },
+  {  2,  1, -3, -2, -1,  3,  4,  0,  1,  0, -1, -5,  4, -5,-12,  2,
+    -2, -5,-22, -2, -1, 11,  8, -7,-12,  0,-34,  6, -5, 11, -8, 19 },
+  { -1, -3,  5, 11, 18, -2, -2, -5, -2,  4, -1,  8,  5, -6,  1, -1,
+     2,  8,  4, -5, -8, -2,  5,-18,  7, 12,  7, 19,-18,  2, -6,-13 },
+  {  9,  0,  0,  5,  4,  3, -6,  4,  1, -4,  5, -1, -4,  8,  8,  6,
+    -8, -6,  0,  6, -3,  3,  5, -3, 17, 31, 16, 10,-13,  0, -9,-19 },
+  { 12,-10,  2, -2, -2, -1, -3,  6,-12, -5, -2, 14,-16,  4, 12, 12,
+    17,  4,  7,-16,  7, -6, 11,  7,  7,  2,-25, 23,-24,  5, -7, -9 },
+  { 10,  4, 13, 10, 10,  3, -6,  3,  3,  2, -1, -6,  8,  4, 10,  0,
+     1,  2, -4,  2, -3, -8,  0, -1,  9,  9,-10, -3,-29,  1, -1,-27 },
+  {  2,  2,  0,  7,  9, -2,-10, -1, -1,  1, -9, -5,  8,  4,  1,  2,
+   -10,  1, 13, 12, -3, 15, -9,  2, -7,  1,-10, 23,-20,-18, -9,-15 },
+  { -3, -5, -1,  8,  0, -5, -1,  4,  7, -1, -7,  2, -8, -5, 11,  7,
+    -6,  3, -3, -9,  7,  9,-22,  1,  6, -4, 14, 27,-25,-14,  3, -5 },
+  {  1,  3,  8,  4,  7,  6, 12,-17,-15,  1, -8,-10,  7,-14, -8,  6,
+    -2, -2,-11,-11, -7, 13, -2, -2,  4,  5, -5, 13,-23, -6,-17, -8 },
+  { -5,  4,-14, -5, -4, -5,  6,  5, -8, -5, -2,-11, -7,-12,  3,-11,
+     2, -6,  4,-10, -5, -7, 14,  5, 23, 11,  7, 12,-16, -6, -4,-16 },
+  {  5,  6,  2,  5, -2, -5, -5, -6, -5,-19,-13, -1, -3,-13,  5,  0,
+     6, -2, -2, -6, -7, -7, -1, -9,  4, 14, 17,-12,-27,  3,  0, -1 },
+  {  7, -1,  9,-10,  8,  2, -7, -2,  5,  2, -3, -7,  3,  0,  6,  4,
+    12,  5, 11, 14,-13, -1,  8,  1, 13,  9, 12, 12,-18,-14,-11,-16 },
+  { -7, -5, -6, -5,  0, -1, -3,  2,  2,  1,  4,  9,  2,  3,  5, -2,
+     2,  1,  8,  0,  3,  0, -2,  2,  1,  7, 29,  0,-36, -5, -9,-21 },
+  { 14, -6, -9,  0, -1, -8, -8,-11,  2,  2, -9,-12, 12, -4,  5,  3,
+    -5, -9, 11, -1, -3, 12,-21, -3, 12,  5,  3, 11,-18,-15,  1, -2 },
+  { -1,  3, -9, -3,  7, -7,-18,  2,  4, 12,-10,  2,  8, -3,-14, 13,
+    17, -5,  5, -9, 13, -3, -7,-18, 17, -2,  5,  7,-20, -3, -6,-11 },
+  { -3,  3,  3, -1,  1, -6, -5,  1,  5, -3,-14, -6, -5, -8, 14, -6,
+     7, -1,  5,  1, 15, -1, -7, -4,  6,-11,  9, -2,-37, 16, -7, -3 },
+  { -1,  0,  6,  1, -3, -9,  0, 11, -8,  2, -2,  0,  5,  2, 12,-10,
+    10, 13,  2,  7, -6,  2,-10,-10, 21, -5,  5,  5,-12,-23,  3,-14 },
+  {  6,  0, -2,  1,  0,  1,  0, -4,  1,  1,  8, -2,  2, -5, -2,  1,
+     8, -4, -1, -1,  4, -1,  2,  6, 32,  1, -5,-20,-40, -4,-18,-14 },
+  {  2,  2, -7, -2,  4,  4, -1,  2,  0, -2, -4, -7,  3,  5,  0, -5,
+     1,  2, -6,  4, -1, -2, -1,-15,  8,  3,  9, 46, -7,-18,  6,-11 },
+  {  5,  5, 16, 21,  3,-11, -4, 11,-12,  2,  4,-12, -1, 11,  8,  1,
+    -4, 11,-11,-21,  1,  1,-11,  3, 13,  1,  5, 12,-25,  1, -3, -2 },
+  {  1,  6, -7,  4,  2,  3,  1, -5,  8,  9,-15,  3, -3,-14, 17,  4,
+    -8, 14, -2, -8, -4,  5,  8, -7,  8,  9,  7,  6,-29,-17,  8,  4 },
+  { -7, -7,  4,  0, 13,  1,  0,  4,  4,-16,-10, -7,  5,  9,-15,-10,
+   -10,  8, -4, -1,-11, -1,-10,-15,  3,  3, 14, 10,-19,  2,-18,-12 },
+  { -4,  0,  2,  0,  5, -2, -9,  0,  4, -4,  2, -1, -2,  2, -4,  9,
+     2, -6, -4, -2, -1, -3, -3, -1,  2,  5, -1, 11,-24,-44, -9,-15 },
+  { -1,-10,  6, 21, 11, 15, -7, 10,-14, -9, -8, -8,  4,  6, 19,  1,
+    -6,  1, -5,-17, -8,-10,  9,  5, 11, 18, -1, 10,-16, -7, -9, -8 },
+  {  3, -5,  0,  0, -2, -2, -6,  4, -4,  1, -1,  0,  7, -3,  4, -4,
+    -7,  7, 17,-20,  6,  4,  1, -6,-12, 31, 13, 19,-14,-10, -7, -2 },
+  { -2,  6,-10,  3,  9,  6,-14, 15,  2, -5,  2,-11,  9, -8,  4,  6,
+    20,-15, -3, -3, -1, 32,-21,  6,  1,  9, 11, 17,-19,  6, -1, -3 },
+  {  8, 10, -2,  0, -8,-16,  7,  7,  6, 10,  4,-14,  7, -6, 21, -7,
+    10,  5,  5,  0, -7,  2, -6,  0, -7, 11, -9, 15,-20, -7,-11,  2 },
+  {  0, -7,  5,  2,  0, -3, -6, -4, -2, -1, -4, -5,-13, -1, 27, -9,
+    -6,-11, -7,  1, 11, -4, -4,-14, -2, 11,  6, 10,-19, -6,-15,  2 },
+  {  0,  7, -1,  2, -7,-15, -2, -3, 13, -5, -5, 12,  3,  0,  5, -5,
+   -22,  2,  7, 22, 13,  0, -1,  2,  3,  2, -7,  7,-27, -4, -4,-12 },
+  { 11,  1,-16,  6,-15,  1,  3,  2,  0,  2, -3,  2,  5, -2, -5,  9,
+     5, -3,  3, -2,-11,  3,  9,  6,  9,  3, -1, 12,-41,  8, -6,  9 },
+  {  3, -7,  3,  2,  5,  5,  0, -1,  1,  3, -5, -2,-13,  7, -1, -2,
+    -2, -6,  4, -6,  0,  2, -2,  2,  4,  1, -4,  1,-47,-21,  7, -6 },
+  {  3, 16, -7, 13, -4, -2, 10, -3, -1, 18,-13,  7,-13, -4,  8,  4,
+     8,  9, -5, 13,  8, -5,  3, -6,  7, 18, -8, 10,-25, -3,-12,-12 },
+  {  1, -1, -1,  0,  2,  5, -5, -3,  0, -5, -1,  0, -4, -8, -2,  3,
+     2, -2,-17, -6, -4,  1, 33, -6,-20, -6,  8, 31,-26, -8, -1, -4 },
+  {  3, -3, -3,  5, -3, -2,  1,  7,  0,  3,  6,  3,  6, -2,  9, 15,
+   -10, -3,-15, -5, -3, -4, -6,-30, 17, -8, -2,  2,-20,  0, -8, -2 },
+  { -2, -1, -1, -1,  3, -5, -2, -3,  4, -2,  0,  5,  8, -3,  1, -4,
+     1,  1, -3,  4,  4,-14,  3, 11, -5,  3, -3,  7, -3, 13, 23,-16 },
+  {  2, -6,  1, -3,  5,  0, -6,-11, -7, -4, -1,  2, -7, -1, -1,  7,
+     1, -2,  6, 12, -6,  8,-13, 17, 25,-23,-19, -7,-12,  9, 16,-17 },
+  {  9,  4,  4,  4, -3, -1,  6, -2, -3,  0, 13, -4, -7, 14,  1, -7,
+     0, -5,  3,-19, -3,  5,  3,  9, -1,  9,-13, 13,-17,  4, 21,-26 },
+  {  0, -5,  0,  0, -4, -5,  2, -6, -4,  5, -7, 10,  0,  2,  0, -2,
+    -2,  0,  4, -6,  7, -2,  6,  5, -5,  2,-12,  1,-29, 29, 27, 12 },
+  {  9,-10,-22,  6, -1, -1,  9,-14,-12, -2,  1, -1, 10,-11,-16,  0,
+     3, 11, 13,-14, -9, -2, -1,  6,  4,-14,  0,-10, -2, 16, 17,-11 },
+  {  2,  0, -1, -2,  4,  3, -6, -2,  1, -1,  1,  3, -4,  1,  3, -4,
+    -1, -1,  4, -1,  1,  0,  1,  6, -5, -7,  2,  1,-47, -3, 50,-17 },
+  {  8, -4,-11, -7, 11, 11, 14, -7, 12, -7,  6,  2, 13, -6, -3, -2,
+   -14,  6,  6,  6,  0,  2, -1,  5,-20,  2, -1,  4, -5,  6, 21,-11 },
+  { -2, -9,  3,  0, -6,  7,  8, -8,  1, -3,  4,  1,  5, -2, -3, -7,
+     4,  7,-12, -9, -2, 10, -6, 13,  6,  5, 20,  2,-15,  9, 28, -7 },
+  {  0, -5, -6, -6, -6,  1, -6,  6, -2,  4,  8, -3, 12, -1, -4, -2,
+     6, 16,-14,  9,-14, -2, -8,-27, -3, 18, -1, -7, -3,  8, 23,-23 },
+  {  1,  4, -9, -1, -5, 10, -2,  1,-11,  1, -9,  4,  7, 14, -9, -2,
+    -3,  2, -5, -1, -6,-10, -7, 11, 20,  2,  3,-19,  3, 15, 30, -9 },
+  {  7,  2,-14, -4,  0, -2,  5,  2,  5, -2,  8, -3, -7,  6,  6,-11,
+   -14,  1, 10, -1, -7, -8,  1, 10,  3, -6,-15,-12,-17,  4, 30, -6 },
+  {  4,  2,  1, -2,  3,  0,  1,  0,  2,  0,  1,  6, -7,  0,  3,  4,
+     4, -4, -2, -5, -2,  2, -1, -2,  0, -2,-11, -7, -3, 42, 24,-14 },
+  {  4,  1,  3,  2,  0, -2, -3, -2,  2, -1,  4, 11, -2,  2,  3, -4,
+    -5,  9,  2, -4, -9,  5,  8, -1, -7,  1, 24,-13,-28, 20, 15,-22 },
+  { -3,  7,  6,  3, -2, -5,-10, -2, -2, -1, -6, -6, -2,-14,-16, -6,
+    -5,  0, 18,  0,  9,  1,  7,-13, -5, -6, -9, 11,-15,  9, 22,-11 },
+  {  9, -2,  6,  5,  2,  9,-10,  1,  1,  5, -4, 12,  2,  2,-10, -7,
+    -4, -6,  7,  9,  6, 15,  6,  6,-10, 10,  5,-13, -5,  6, 24,-12 },
+  {  1,  3, -3, -3,  8,  1, -6,  2, -5, -3,  7,  2, 14,  6,  9, -6,
+    -5, -4, 27,  7, -3,  8, -6,  3, -8,  8, 22, -5, -6, -2, 22,-17 },
+  { -2, -2,  3, 10,  9,  9, 12,-15, -1,-11,-13,  3, -2,  1, -3,-11,
+     7,  9, 16, -3,-10, -5, -5,  1,  8, -3,  9,  9, -5,  3, 31,-12 },
+  {  7, -5, 10, -4, -8,  2, 16, -2, 10, 10, -3, -2,  3, -8, -3,  3,
+   -13, -6, 15, 20, -9, -3,-12,  1, -2,-16,  8,  8, -1, 16, 22, -5 },
+  {  5, -3,-15, -2, 12, -8,  8, -5,  2, -8, 20,-18, 14, -4,  3,  3,
+     7,-13,-16,  1,-10,  7, 16,  7,  4,-14, -4, -5, -9,  8, 23, -6 },
+  {  5, -4, -5, -4,  1,  8,  4, -7, -5,  8, 10,  6, -6,-10, -2,  6,
+     9,-17,-14, 11, 12, -3,-13, -7,  2, 18,  3,-25,-16, 18, 22, -5 },
+  {  5,  6, -7,-20, -4,  2,  8,  4,-24, -4,  1,  4, -5, -2,  1,-10,
+    -2,  9,  3, -4, -3, -4, -4, -4, 10, 10,  3,  0, -6, 25, 21,-11 },
+  {  0,  7, -1, 14, -6, -4,-10,  5,  4,  4,  4, -5,  3,  4, -1, -7,
+     8,-19,  0,  6,  2,  3,-18, -3, -6,  2,  8, 14,-26, 22, 27,-13 },
+  { -2, -6,  7, -5, 12, -7,  8, -1,  3, -2,  4,  1,  8, -2,  0, 14,
+     6, -5,  6, -4, -7,  7,-21,  8,  1,  8, -9, -4, -3, 11, 25,-13 },
+  {  4,  4, -1, -6,  4,  9, -8,  1, -3,-10, -2,  0, 15, -9,-16, 11,
+     1,  1,  6,  3, -9, -5, 16, 26,  1,-14,  1, -3,-14,  7, 15, -9 },
+  {-12, -2, -9,-13,  2,  6, 14,  0,  1,  0, -1,-13,  0, 10, -1,  6,
+     9, -7,  8,  8, 19,  6, -1,  9, 10, -4,  1, -7,-22, -2, 29, -7 },
+  {  2,  4, 13,-12, -8, -4, -5, 13, 12, -5, -3, -3, -4,  1, -1, 10,
+    15, -6, -1,-11,-30,  4, 15, -1,  9, -7,  0, -2, -7, 10, 25,-16 },
+  {  7,-15, -7, -7, -1, -5, -5,-11,-20, 10,  3,-10, -3,  5, 20, -4,
+     0, -2, -2, 17,  2,  0, -3,  3,  6,  5, -1,-12, -3, 15, 22,-16 },
+  {  4, -1,  3,  4, -5,  0, -1, -5,-24,-29,  4, -9,  1, -3,  0,  0,
+     0, -4,  7, -4, -4, -4,  3,  1, -6,  5, -3, -5,-10,  3, 25,-10 },
+  { -2, -1, -1,  4,  4, -1,  2,  0, -4, -4,  2, -1, -3, -1, -2, -2,
+     1, -3, -5, -1,  2, -3, -4, -4, -3,  5, -9,  1,-11,  7, 46,-46 },
+  {  0, -9,  3,  4,  4,  3, -5, -6,  5, -4,  4, -2,  1,  7, -4,-10,
+    13,  1,  3, -6,  4, -4,  7,  2,-19,-25, -3,-16,-12, 16, 20, -1 },
+  { 18,  6,  4,-12,  0,-14,  9, -6, -1, -4, -5,  2,  1, 12,  4,  2,
+     7,  0,  2,  5,-11, -5, -2,  2, -4, 10,  0, -9, -7,  9, 25, -8 },
+  {  5,  0, -6,  5,  6,  3,  3,-10, -5,  1, -1,  4,  3,-11, -8,  5,
+     4, -5,  5, -5, -7, -5, 11,  5, 20, -8,-16, 21, -4, 27, 23, -5 }
 };
 
 
diff --git a/libavcodec/dcadsp.c b/libavcodec/dcadsp.c
index af48e3c..14932e6 100644
--- a/libavcodec/dcadsp.c
+++ b/libavcodec/dcadsp.c
@@ -2,20 +2,20 @@
  * Copyright (c) 2004 Gildas Bazin
  * Copyright (c) 2010 Mans Rullgard <mans at mansr.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -23,7 +23,7 @@
 #include "dcadsp.h"
 
 static void dca_lfe_fir_c(float *out, const float *in, const float *coefs,
-                          int decifactor, float scale, float bias)
+                          int decifactor, float scale)
 {
     float *out2 = out + decifactor;
     const float *cf0 = coefs;
@@ -39,8 +39,8 @@ static void dca_lfe_fir_c(float *out, const float *in, const float *coefs,
             v0 += s * *cf0++;
             v1 += s * *--cf1;
         }
-        *out++  = (v0 * scale) + bias;
-        *out2++ = (v1 * scale) + bias;
+        *out++  = v0 * scale;
+        *out2++ = v1 * scale;
     }
 }
 
diff --git a/libavcodec/dcadsp.h b/libavcodec/dcadsp.h
index 20020ae..3c6f1f9 100644
--- a/libavcodec/dcadsp.h
+++ b/libavcodec/dcadsp.h
@@ -1,18 +1,18 @@
 /*
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -21,7 +21,7 @@
 
 typedef struct DCADSPContext {
     void (*lfe_fir)(float *out, const float *in, const float *coefs,
-                    int decifactor, float scale, float bias);
+                    int decifactor, float scale);
 } DCADSPContext;
 
 void ff_dcadsp_init(DCADSPContext *s);
diff --git a/libavcodec/dcahuff.h b/libavcodec/dcahuff.h
index cbc8429..254fc76 100644
--- a/libavcodec/dcahuff.h
+++ b/libavcodec/dcahuff.h
@@ -3,20 +3,20 @@
  * Copyright (C) 2004 Gildas Bazin
  * Copyright (C) 2007 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/dct-test.c b/libavcodec/dct-test.c
index 4f0a0c6..e943d6a 100644
--- a/libavcodec/dct-test.c
+++ b/libavcodec/dct-test.c
@@ -2,20 +2,20 @@
  * (c) 2001 Fabrice Bellard
  *     2007 Marc Hoffman <marc.hoffman at analog.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -32,6 +32,7 @@
 #include <unistd.h>
 #include <math.h>
 
+#include "libavutil/cpu.h"
 #include "libavutil/common.h"
 #include "libavutil/lfg.h"
 
@@ -94,24 +95,24 @@ struct algo algos[] = {
   {"SIMPLE-C",        1, ff_simple_idct,     ff_ref_idct, NO_PERM},
 
 #if HAVE_MMX
-  {"MMX",             0, ff_fdct_mmx,        ff_ref_fdct, NO_PERM, FF_MM_MMX},
+  {"MMX",             0, ff_fdct_mmx,        ff_ref_fdct, NO_PERM, AV_CPU_FLAG_MMX},
 #if HAVE_MMX2
-  {"MMX2",            0, ff_fdct_mmx2,       ff_ref_fdct, NO_PERM, FF_MM_MMX2},
-  {"SSE2",            0, ff_fdct_sse2,       ff_ref_fdct, NO_PERM, FF_MM_SSE2},
+  {"MMX2",            0, ff_fdct_mmx2,       ff_ref_fdct, NO_PERM, AV_CPU_FLAG_MMX2},
+  {"SSE2",            0, ff_fdct_sse2,       ff_ref_fdct, NO_PERM, AV_CPU_FLAG_SSE2},
 #endif
 
 #if CONFIG_GPL
-  {"LIBMPEG2-MMX",    1, ff_mmx_idct,        ff_ref_idct, MMX_PERM, FF_MM_MMX},
-  {"LIBMPEG2-MMX2",   1, ff_mmxext_idct,     ff_ref_idct, MMX_PERM, FF_MM_MMX2},
+  {"LIBMPEG2-MMX",    1, ff_mmx_idct,        ff_ref_idct, MMX_PERM, AV_CPU_FLAG_MMX},
+  {"LIBMPEG2-MMX2",   1, ff_mmxext_idct,     ff_ref_idct, MMX_PERM, AV_CPU_FLAG_MMX2},
 #endif
-  {"SIMPLE-MMX",      1, ff_simple_idct_mmx, ff_ref_idct, MMX_SIMPLE_PERM, FF_MM_MMX},
-  {"XVID-MMX",        1, ff_idct_xvid_mmx,   ff_ref_idct, NO_PERM, FF_MM_MMX},
-  {"XVID-MMX2",       1, ff_idct_xvid_mmx2,  ff_ref_idct, NO_PERM, FF_MM_MMX2},
-  {"XVID-SSE2",       1, ff_idct_xvid_sse2,  ff_ref_idct, SSE2_PERM, FF_MM_SSE2},
+  {"SIMPLE-MMX",      1, ff_simple_idct_mmx, ff_ref_idct, MMX_SIMPLE_PERM, AV_CPU_FLAG_MMX},
+  {"XVID-MMX",        1, ff_idct_xvid_mmx,   ff_ref_idct, NO_PERM, AV_CPU_FLAG_MMX},
+  {"XVID-MMX2",       1, ff_idct_xvid_mmx2,  ff_ref_idct, NO_PERM, AV_CPU_FLAG_MMX2},
+  {"XVID-SSE2",       1, ff_idct_xvid_sse2,  ff_ref_idct, SSE2_PERM, AV_CPU_FLAG_SSE2},
 #endif
 
 #if HAVE_ALTIVEC
-  {"altivecfdct",     0, fdct_altivec,       ff_ref_fdct, NO_PERM, FF_MM_ALTIVEC},
+  {"altivecfdct",     0, fdct_altivec,       ff_ref_fdct, NO_PERM, AV_CPU_FLAG_ALTIVEC},
 #endif
 
 #if ARCH_BFIN
@@ -187,7 +188,7 @@ DECLARE_ALIGNED(8, static DCTELEM, block_org)[64];
 static inline void mmx_emms(void)
 {
 #if HAVE_MMX
-    if (cpu_flags & FF_MM_MMX)
+    if (cpu_flags & AV_CPU_FLAG_MMX)
         __asm__ volatile ("emms\n\t");
 #endif
 }
@@ -554,7 +555,7 @@ int main(int argc, char **argv)
     int test_idct = 0, test_248_dct = 0;
     int c,i;
     int test=1;
-    cpu_flags = mm_support();
+    cpu_flags = av_get_cpu_flags();
 
     ff_ref_dct_init();
     idct_mmx_init();
diff --git a/libavcodec/dct.c b/libavcodec/dct.c
index 0840fec..83ea00f 100644
--- a/libavcodec/dct.c
+++ b/libavcodec/dct.c
@@ -4,20 +4,20 @@
  * Copyright (c) 2010 Alex Converse <alex.converse at gmail.com>
  * Copyright (c) 2010 Vitor Sessak
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
  */
 
@@ -29,7 +29,10 @@
 
 #include <math.h>
 #include "libavutil/mathematics.h"
-#include "fft.h"
+#include "dct.h"
+
+#define DCT32_FLOAT
+#include "dct32.c"
 
 /* sin((M_PI * x / (2*n)) */
 #define SIN(s,n,x) (s->costab[(n) - (x)])
@@ -55,7 +58,7 @@ static void ff_dst_calc_I_c(DCTContext *ctx, FFTSample *data)
     }
 
     data[n/2] *= 2;
-    ff_rdft_calc(&ctx->rdft, data);
+    ctx->rdft.rdft_calc(&ctx->rdft, data);
 
     data[0] *= 0.5f;
 
@@ -89,7 +92,7 @@ static void ff_dct_calc_I_c(DCTContext *ctx, FFTSample *data)
         data[n - i] = tmp1 + s;
     }
 
-    ff_rdft_calc(&ctx->rdft, data);
+    ctx->rdft.rdft_calc(&ctx->rdft, data);
     data[n] = data[1];
     data[1] = next;
 
@@ -117,7 +120,7 @@ static void ff_dct_calc_III_c(DCTContext *ctx, FFTSample *data)
 
     data[1] = 2 * next;
 
-    ff_rdft_calc(&ctx->rdft, data);
+    ctx->rdft.rdft_calc(&ctx->rdft, data);
 
     for (i = 0; i < n / 2; i++) {
         float tmp1 = data[i        ] * inv_n;
@@ -148,7 +151,7 @@ static void ff_dct_calc_II_c(DCTContext *ctx, FFTSample *data)
         data[n-i-1] = tmp1 - s;
     }
 
-    ff_rdft_calc(&ctx->rdft, data);
+    ctx->rdft.rdft_calc(&ctx->rdft, data);
 
     next = data[1] * 0.5;
     data[1] *= -1;
@@ -167,9 +170,9 @@ static void ff_dct_calc_II_c(DCTContext *ctx, FFTSample *data)
     }
 }
 
-void ff_dct_calc(DCTContext *s, FFTSample *data)
+static void dct32_func(DCTContext *ctx, FFTSample *data)
 {
-    s->dct_calc(s, data);
+    ctx->dct32(data, data);
 }
 
 av_cold int ff_dct_init(DCTContext *s, int nbits, enum DCTTransformType inverse)
@@ -200,6 +203,13 @@ av_cold int ff_dct_init(DCTContext *s, int nbits, enum DCTTransformType inverse)
     case DCT_III: s->dct_calc = ff_dct_calc_III_c; break;
     case DST_I  : s->dct_calc = ff_dst_calc_I_c; break;
     }
+
+    if (inverse == DCT_II && nbits == 5)
+        s->dct_calc = dct32_func;
+
+    s->dct32 = dct32;
+    if (HAVE_MMX)     ff_dct_init_mmx(s);
+
     return 0;
 }
 
diff --git a/libavcodec/dct.h b/libavcodec/dct.h
new file mode 100644
index 0000000..faddaa3
--- /dev/null
+++ b/libavcodec/dct.h
@@ -0,0 +1,52 @@
+/*
+ * (I)DCT Transforms
+ * Copyright (c) 2009 Peter Ross <pross at xvid.org>
+ * Copyright (c) 2010 Alex Converse <alex.converse at gmail.com>
+ * Copyright (c) 2010 Vitor Sessak
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifndef AVCODEC_DCT_H
+#define AVCODEC_DCT_H
+
+#include "rdft.h"
+
+struct DCTContext {
+    int nbits;
+    int inverse;
+    RDFTContext rdft;
+    const float *costab;
+    FFTSample *csc2;
+    void (*dct_calc)(struct DCTContext *s, FFTSample *data);
+    void (*dct32)(FFTSample *out, const FFTSample *in);
+};
+
+/**
+ * Set up DCT.
+ * @param nbits           size of the input array:
+ *                        (1 << nbits)     for DCT-II, DCT-III and DST-I
+ *                        (1 << nbits) + 1 for DCT-I
+ *
+ * @note the first element of the input of DST-I is ignored
+ */
+int  ff_dct_init(DCTContext *s, int nbits, enum DCTTransformType type);
+void ff_dct_end (DCTContext *s);
+
+void ff_dct_init_mmx(DCTContext *s);
+
+#endif
diff --git a/libavcodec/dct32.c b/libavcodec/dct32.c
new file mode 100644
index 0000000..ae99d88
--- /dev/null
+++ b/libavcodec/dct32.c
@@ -0,0 +1,267 @@
+/*
+ * Template for the Discrete Cosine Transform for 32 samples
+ * Copyright (c) 2001, 2002 Fabrice Bellard
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifdef DCT32_FLOAT
+#   define FIXHR(x)       ((float)(x))
+#   define MULH3(x, y, s) ((s)*(y)*(x))
+#   define INTFLOAT float
+#endif
+
+
+/* tab[i][j] = 1.0 / (2.0 * cos(pi*(2*k+1) / 2^(6 - j))) */
+
+/* cos(i*pi/64) */
+
+#define COS0_0  FIXHR(0.50060299823519630134/2)
+#define COS0_1  FIXHR(0.50547095989754365998/2)
+#define COS0_2  FIXHR(0.51544730992262454697/2)
+#define COS0_3  FIXHR(0.53104259108978417447/2)
+#define COS0_4  FIXHR(0.55310389603444452782/2)
+#define COS0_5  FIXHR(0.58293496820613387367/2)
+#define COS0_6  FIXHR(0.62250412303566481615/2)
+#define COS0_7  FIXHR(0.67480834145500574602/2)
+#define COS0_8  FIXHR(0.74453627100229844977/2)
+#define COS0_9  FIXHR(0.83934964541552703873/2)
+#define COS0_10 FIXHR(0.97256823786196069369/2)
+#define COS0_11 FIXHR(1.16943993343288495515/4)
+#define COS0_12 FIXHR(1.48416461631416627724/4)
+#define COS0_13 FIXHR(2.05778100995341155085/8)
+#define COS0_14 FIXHR(3.40760841846871878570/8)
+#define COS0_15 FIXHR(10.19000812354805681150/32)
+
+#define COS1_0 FIXHR(0.50241928618815570551/2)
+#define COS1_1 FIXHR(0.52249861493968888062/2)
+#define COS1_2 FIXHR(0.56694403481635770368/2)
+#define COS1_3 FIXHR(0.64682178335999012954/2)
+#define COS1_4 FIXHR(0.78815462345125022473/2)
+#define COS1_5 FIXHR(1.06067768599034747134/4)
+#define COS1_6 FIXHR(1.72244709823833392782/4)
+#define COS1_7 FIXHR(5.10114861868916385802/16)
+
+#define COS2_0 FIXHR(0.50979557910415916894/2)
+#define COS2_1 FIXHR(0.60134488693504528054/2)
+#define COS2_2 FIXHR(0.89997622313641570463/2)
+#define COS2_3 FIXHR(2.56291544774150617881/8)
+
+#define COS3_0 FIXHR(0.54119610014619698439/2)
+#define COS3_1 FIXHR(1.30656296487637652785/4)
+
+#define COS4_0 FIXHR(0.70710678118654752439/2)
+
+/* butterfly operator */
+#define BF(a, b, c, s)\
+{\
+    tmp0 = val##a + val##b;\
+    tmp1 = val##a - val##b;\
+    val##a = tmp0;\
+    val##b = MULH3(tmp1, c, 1<<(s));\
+}
+
+#define BF0(a, b, c, s)\
+{\
+    tmp0 = tab[a] + tab[b];\
+    tmp1 = tab[a] - tab[b];\
+    val##a = tmp0;\
+    val##b = MULH3(tmp1, c, 1<<(s));\
+}
+
+#define BF1(a, b, c, d)\
+{\
+    BF(a, b, COS4_0, 1);\
+    BF(c, d,-COS4_0, 1);\
+    val##c += val##d;\
+}
+
+#define BF2(a, b, c, d)\
+{\
+    BF(a, b, COS4_0, 1);\
+    BF(c, d,-COS4_0, 1);\
+    val##c += val##d;\
+    val##a += val##c;\
+    val##c += val##b;\
+    val##b += val##d;\
+}
+
+#define ADD(a, b) val##a += val##b
+
+/* DCT32 without 1/sqrt(2) coef zero scaling. */
+static void dct32(INTFLOAT *out, const INTFLOAT *tab)
+{
+    INTFLOAT tmp0, tmp1;
+
+    INTFLOAT val0 , val1 , val2 , val3 , val4 , val5 , val6 , val7 ,
+             val8 , val9 , val10, val11, val12, val13, val14, val15,
+             val16, val17, val18, val19, val20, val21, val22, val23,
+             val24, val25, val26, val27, val28, val29, val30, val31;
+
+    /* pass 1 */
+    BF0( 0, 31, COS0_0 , 1);
+    BF0(15, 16, COS0_15, 5);
+    /* pass 2 */
+    BF( 0, 15, COS1_0 , 1);
+    BF(16, 31,-COS1_0 , 1);
+    /* pass 1 */
+    BF0( 7, 24, COS0_7 , 1);
+    BF0( 8, 23, COS0_8 , 1);
+    /* pass 2 */
+    BF( 7,  8, COS1_7 , 4);
+    BF(23, 24,-COS1_7 , 4);
+    /* pass 3 */
+    BF( 0,  7, COS2_0 , 1);
+    BF( 8, 15,-COS2_0 , 1);
+    BF(16, 23, COS2_0 , 1);
+    BF(24, 31,-COS2_0 , 1);
+    /* pass 1 */
+    BF0( 3, 28, COS0_3 , 1);
+    BF0(12, 19, COS0_12, 2);
+    /* pass 2 */
+    BF( 3, 12, COS1_3 , 1);
+    BF(19, 28,-COS1_3 , 1);
+    /* pass 1 */
+    BF0( 4, 27, COS0_4 , 1);
+    BF0(11, 20, COS0_11, 2);
+    /* pass 2 */
+    BF( 4, 11, COS1_4 , 1);
+    BF(20, 27,-COS1_4 , 1);
+    /* pass 3 */
+    BF( 3,  4, COS2_3 , 3);
+    BF(11, 12,-COS2_3 , 3);
+    BF(19, 20, COS2_3 , 3);
+    BF(27, 28,-COS2_3 , 3);
+    /* pass 4 */
+    BF( 0,  3, COS3_0 , 1);
+    BF( 4,  7,-COS3_0 , 1);
+    BF( 8, 11, COS3_0 , 1);
+    BF(12, 15,-COS3_0 , 1);
+    BF(16, 19, COS3_0 , 1);
+    BF(20, 23,-COS3_0 , 1);
+    BF(24, 27, COS3_0 , 1);
+    BF(28, 31,-COS3_0 , 1);
+
+
+
+    /* pass 1 */
+    BF0( 1, 30, COS0_1 , 1);
+    BF0(14, 17, COS0_14, 3);
+    /* pass 2 */
+    BF( 1, 14, COS1_1 , 1);
+    BF(17, 30,-COS1_1 , 1);
+    /* pass 1 */
+    BF0( 6, 25, COS0_6 , 1);
+    BF0( 9, 22, COS0_9 , 1);
+    /* pass 2 */
+    BF( 6,  9, COS1_6 , 2);
+    BF(22, 25,-COS1_6 , 2);
+    /* pass 3 */
+    BF( 1,  6, COS2_1 , 1);
+    BF( 9, 14,-COS2_1 , 1);
+    BF(17, 22, COS2_1 , 1);
+    BF(25, 30,-COS2_1 , 1);
+
+    /* pass 1 */
+    BF0( 2, 29, COS0_2 , 1);
+    BF0(13, 18, COS0_13, 3);
+    /* pass 2 */
+    BF( 2, 13, COS1_2 , 1);
+    BF(18, 29,-COS1_2 , 1);
+    /* pass 1 */
+    BF0( 5, 26, COS0_5 , 1);
+    BF0(10, 21, COS0_10, 1);
+    /* pass 2 */
+    BF( 5, 10, COS1_5 , 2);
+    BF(21, 26,-COS1_5 , 2);
+    /* pass 3 */
+    BF( 2,  5, COS2_2 , 1);
+    BF(10, 13,-COS2_2 , 1);
+    BF(18, 21, COS2_2 , 1);
+    BF(26, 29,-COS2_2 , 1);
+    /* pass 4 */
+    BF( 1,  2, COS3_1 , 2);
+    BF( 5,  6,-COS3_1 , 2);
+    BF( 9, 10, COS3_1 , 2);
+    BF(13, 14,-COS3_1 , 2);
+    BF(17, 18, COS3_1 , 2);
+    BF(21, 22,-COS3_1 , 2);
+    BF(25, 26, COS3_1 , 2);
+    BF(29, 30,-COS3_1 , 2);
+
+    /* pass 5 */
+    BF1( 0,  1,  2,  3);
+    BF2( 4,  5,  6,  7);
+    BF1( 8,  9, 10, 11);
+    BF2(12, 13, 14, 15);
+    BF1(16, 17, 18, 19);
+    BF2(20, 21, 22, 23);
+    BF1(24, 25, 26, 27);
+    BF2(28, 29, 30, 31);
+
+    /* pass 6 */
+
+    ADD( 8, 12);
+    ADD(12, 10);
+    ADD(10, 14);
+    ADD(14,  9);
+    ADD( 9, 13);
+    ADD(13, 11);
+    ADD(11, 15);
+
+    out[ 0] = val0;
+    out[16] = val1;
+    out[ 8] = val2;
+    out[24] = val3;
+    out[ 4] = val4;
+    out[20] = val5;
+    out[12] = val6;
+    out[28] = val7;
+    out[ 2] = val8;
+    out[18] = val9;
+    out[10] = val10;
+    out[26] = val11;
+    out[ 6] = val12;
+    out[22] = val13;
+    out[14] = val14;
+    out[30] = val15;
+
+    ADD(24, 28);
+    ADD(28, 26);
+    ADD(26, 30);
+    ADD(30, 25);
+    ADD(25, 29);
+    ADD(29, 27);
+    ADD(27, 31);
+
+    out[ 1] = val16 + val24;
+    out[17] = val17 + val25;
+    out[ 9] = val18 + val26;
+    out[25] = val19 + val27;
+    out[ 5] = val20 + val28;
+    out[21] = val21 + val29;
+    out[13] = val22 + val30;
+    out[29] = val23 + val31;
+    out[ 3] = val24 + val20;
+    out[19] = val25 + val21;
+    out[11] = val26 + val22;
+    out[27] = val27 + val23;
+    out[ 7] = val28 + val18;
+    out[23] = val29 + val19;
+    out[15] = val30 + val17;
+    out[31] = val31;
+}
diff --git a/libavcodec/dctref.c b/libavcodec/dctref.c
index 851014b..ae3dec5 100644
--- a/libavcodec/dctref.c
+++ b/libavcodec/dctref.c
@@ -2,20 +2,20 @@
  * reference discrete cosine transform (double precision)
  * Copyright (C) 2009 Dylan Yudaken
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/dctref.h b/libavcodec/dctref.h
index adbaf68..ffd3533 100644
--- a/libavcodec/dctref.h
+++ b/libavcodec/dctref.h
@@ -2,20 +2,20 @@
  * reference discrete cosine transform (double precision)
  * Copyright (C) 2009 Dylan Yudaken
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/dfa.c b/libavcodec/dfa.c
new file mode 100644
index 0000000..b149791
--- /dev/null
+++ b/libavcodec/dfa.c
@@ -0,0 +1,395 @@
+/*
+ * Chronomaster DFA Video Decoder
+ * Copyright (c) 2011 Konstantin Shishkov
+ * based on work by Vladimir "VAG" Gneushev
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "avcodec.h"
+#include "libavutil/intreadwrite.h"
+#include "bytestream.h"
+#include "libavutil/lzo.h" // for av_memcpy_backptr
+
+typedef struct DfaContext {
+    AVFrame pic;
+
+    uint32_t pal[256];
+    uint8_t *frame_buf;
+} DfaContext;
+
+static av_cold int dfa_decode_init(AVCodecContext *avctx)
+{
+    DfaContext *s = avctx->priv_data;
+
+    avctx->pix_fmt = PIX_FMT_PAL8;
+
+    s->frame_buf = av_mallocz(avctx->width * avctx->height + AV_LZO_OUTPUT_PADDING);
+    if (!s->frame_buf)
+        return AVERROR(ENOMEM);
+
+    return 0;
+}
+
+static int decode_copy(uint8_t *frame, int width, int height,
+                       const uint8_t *src, const uint8_t *src_end)
+{
+    const int size = width * height;
+
+    if (src_end - src < size)
+        return -1;
+    bytestream_get_buffer(&src, frame, size);
+    return 0;
+}
+
+static int decode_tsw1(uint8_t *frame, int width, int height,
+                       const uint8_t *src, const uint8_t *src_end)
+{
+    const uint8_t *frame_start = frame;
+    const uint8_t *frame_end   = frame + width * height;
+    int mask = 0x10000, bitbuf = 0;
+    int v, offset, count, segments;
+
+    segments = bytestream_get_le32(&src);
+    frame   += bytestream_get_le32(&src);
+    if (frame < frame_start || frame > frame_end)
+        return -1;
+    while (segments--) {
+        if (mask == 0x10000) {
+            if (src >= src_end)
+                return -1;
+            bitbuf = bytestream_get_le16(&src);
+            mask = 1;
+        }
+        if (src_end - src < 2 || frame_end - frame < 2)
+            return -1;
+        if (bitbuf & mask) {
+            v = bytestream_get_le16(&src);
+            offset = (v & 0x1FFF) << 1;
+            count = ((v >> 13) + 2) << 1;
+            if (frame - frame_start < offset || frame_end - frame < count)
+                return -1;
+            av_memcpy_backptr(frame, offset, count);
+            frame += count;
+        } else {
+            *frame++ = *src++;
+            *frame++ = *src++;
+        }
+        mask <<= 1;
+    }
+
+    return 0;
+}
+
+static int decode_dsw1(uint8_t *frame, int width, int height,
+                       const uint8_t *src, const uint8_t *src_end)
+{
+    const uint8_t *frame_start = frame;
+    const uint8_t *frame_end   = frame + width * height;
+    int mask = 0x10000, bitbuf = 0;
+    int v, offset, count, segments;
+
+    segments = bytestream_get_le16(&src);
+    while (segments--) {
+        if (mask == 0x10000) {
+            if (src >= src_end)
+                return -1;
+            bitbuf = bytestream_get_le16(&src);
+            mask = 1;
+        }
+        if (src_end - src < 2 || frame_end - frame < 2)
+            return -1;
+        if (bitbuf & mask) {
+            v = bytestream_get_le16(&src);
+            offset = (v & 0x1FFF) << 1;
+            count = ((v >> 13) + 2) << 1;
+            if (frame - frame_start < offset || frame_end - frame < count)
+                return -1;
+            // can't use av_memcpy_backptr() since it can overwrite following pixels
+            for (v = 0; v < count; v++)
+                frame[v] = frame[v - offset];
+            frame += count;
+        } else if (bitbuf & (mask << 1)) {
+            frame += bytestream_get_le16(&src);
+        } else {
+            *frame++ = *src++;
+            *frame++ = *src++;
+        }
+        mask <<= 2;
+    }
+
+    return 0;
+}
+
+static int decode_dds1(uint8_t *frame, int width, int height,
+                       const uint8_t *src, const uint8_t *src_end)
+{
+    const uint8_t *frame_start = frame;
+    const uint8_t *frame_end   = frame + width * height;
+    int mask = 0x10000, bitbuf = 0;
+    int i, v, offset, count, segments;
+
+    segments = bytestream_get_le16(&src);
+    while (segments--) {
+        if (mask == 0x10000) {
+            if (src >= src_end)
+                return -1;
+            bitbuf = bytestream_get_le16(&src);
+            mask = 1;
+        }
+        if (src_end - src < 2 || frame_end - frame < 2)
+            return -1;
+        if (bitbuf & mask) {
+            v = bytestream_get_le16(&src);
+            offset = (v & 0x1FFF) << 2;
+            count = ((v >> 13) + 2) << 1;
+            if (frame - frame_start < offset || frame_end - frame < count*2 + width)
+                return -1;
+            for (i = 0; i < count; i++) {
+                frame[0] = frame[1] =
+                frame[width] = frame[width + 1] = frame[-offset];
+
+                frame += 2;
+            }
+        } else if (bitbuf & (mask << 1)) {
+            frame += bytestream_get_le16(&src) * 2;
+        } else {
+            frame[0] = frame[1] =
+            frame[width] = frame[width + 1] =  *src++;
+            frame += 2;
+            frame[0] = frame[1] =
+            frame[width] = frame[width + 1] =  *src++;
+            frame += 2;
+        }
+        mask <<= 2;
+    }
+
+    return 0;
+}
+
+static int decode_bdlt(uint8_t *frame, int width, int height,
+                       const uint8_t *src, const uint8_t *src_end)
+{
+    const uint8_t *frame_end = frame + width * height;
+    uint8_t *line_ptr;
+    int count, lines, segments;
+
+    count = bytestream_get_le16(&src);
+    if (count >= height || width * count < 0)
+        return -1;
+    frame += width * count;
+    lines = bytestream_get_le16(&src);
+    if (frame + lines * width > frame_end || src >= src_end)
+        return -1;
+
+    while (lines--) {
+        line_ptr = frame;
+        frame += width;
+        segments = *src++;
+        while (segments--) {
+            if (src_end - src < 3)
+                return -1;
+            line_ptr += *src++;
+            if (line_ptr >= frame)
+                return -1;
+            count = (int8_t)*src++;
+            if (count >= 0) {
+                if (line_ptr + count > frame || src_end - src < count)
+                    return -1;
+                bytestream_get_buffer(&src, line_ptr, count);
+            } else {
+                count = -count;
+                if (line_ptr + count > frame || src >= src_end)
+                    return -1;
+                memset(line_ptr, *src++, count);
+            }
+            line_ptr += count;
+        }
+    }
+
+    return 0;
+}
+
+static int decode_wdlt(uint8_t *frame, int width, int height,
+                       const uint8_t *src, const uint8_t *src_end)
+{
+    const uint8_t *frame_end   = frame + width * height;
+    uint8_t *line_ptr;
+    int count, i, v, lines, segments;
+
+    lines = bytestream_get_le16(&src);
+    if (frame + lines * width > frame_end || src >= src_end)
+        return -1;
+
+    while (lines--) {
+        segments = bytestream_get_le16(&src);
+        while ((segments & 0xC000) == 0xC000) {
+            frame    -= (int16_t)segments * width;
+            if (frame >= frame_end)
+                return -1;
+            segments = bytestream_get_le16(&src);
+        }
+        if (segments & 0x8000) {
+            frame[width - 1] = segments & 0xFF;
+            segments = bytestream_get_le16(&src);
+        }
+        line_ptr = frame;
+        frame += width;
+        while (segments--) {
+            if (src_end - src < 2)
+                return -1;
+            line_ptr += *src++;
+            if (line_ptr >= frame)
+                return -1;
+            count = (int8_t)*src++;
+            if (count >= 0) {
+                if (line_ptr + count*2 > frame || src_end - src < count*2)
+                    return -1;
+                bytestream_get_buffer(&src, line_ptr, count*2);
+                line_ptr += count * 2;
+            } else {
+                count = -count;
+                if (line_ptr + count*2 > frame || src_end - src < 2)
+                    return -1;
+                v = bytestream_get_le16(&src);
+                for (i = 0; i < count; i++)
+                    bytestream_put_le16(&line_ptr, v);
+            }
+        }
+    }
+
+    return 0;
+}
+
+static int decode_unk6(uint8_t *frame, int width, int height,
+                       const uint8_t *src, const uint8_t *src_end)
+{
+    return -1;
+}
+
+static int decode_blck(uint8_t *frame, int width, int height,
+                       const uint8_t *src, const uint8_t *src_end)
+{
+    memset(frame, 0, width * height);
+    return 0;
+}
+
+
+typedef int (*chunk_decoder)(uint8_t *frame, int width, int height,
+                             const uint8_t *src, const uint8_t *src_end);
+
+static const chunk_decoder decoder[8] = {
+    decode_copy, decode_tsw1, decode_bdlt, decode_wdlt,
+    decode_unk6, decode_dsw1, decode_blck, decode_dds1,
+};
+
+static const char* chunk_name[8] = {
+    "COPY", "TSW1", "BDLT", "WDLT", "????", "DSW1", "BLCK", "DDS1"
+};
+
+static int dfa_decode_frame(AVCodecContext *avctx,
+                            void *data, int *data_size,
+                            AVPacket *avpkt)
+{
+    DfaContext *s = avctx->priv_data;
+    const uint8_t *buf = avpkt->data;
+    const uint8_t *buf_end = avpkt->data + avpkt->size;
+    const uint8_t *tmp_buf;
+    uint32_t chunk_type, chunk_size;
+    uint8_t *dst;
+    int ret;
+    int i, pal_elems;
+
+    if (s->pic.data[0])
+        avctx->release_buffer(avctx, &s->pic);
+
+    if ((ret = avctx->get_buffer(avctx, &s->pic))) {
+        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
+        return ret;
+    }
+
+    while (buf < buf_end) {
+        chunk_size = AV_RL32(buf + 4);
+        chunk_type = AV_RL32(buf + 8);
+        buf += 12;
+        if (buf_end - buf < chunk_size) {
+            av_log(avctx, AV_LOG_ERROR, "Chunk size is too big (%d bytes)\n", chunk_size);
+            return -1;
+        }
+        if (!chunk_type)
+            break;
+        if (chunk_type == 1) {
+            pal_elems = FFMIN(chunk_size / 3, 256);
+            tmp_buf = buf;
+            for (i = 0; i < pal_elems; i++) {
+                s->pal[i] = bytestream_get_be24(&tmp_buf) << 2;
+                s->pal[i] |= (s->pal[i] >> 6) & 0x333;
+            }
+            s->pic.palette_has_changed = 1;
+        } else if (chunk_type <= 9) {
+            if (decoder[chunk_type - 2](s->frame_buf, avctx->width, avctx->height,
+                                        buf, buf + chunk_size)) {
+                av_log(avctx, AV_LOG_ERROR, "Error decoding %s chunk\n",
+                       chunk_name[chunk_type - 2]);
+                return -1;
+            }
+        } else {
+            av_log(avctx, AV_LOG_WARNING, "Ignoring unknown chunk type %d\n",
+                   chunk_type);
+        }
+        buf += chunk_size;
+    }
+
+    buf = s->frame_buf;
+    dst = s->pic.data[0];
+    for (i = 0; i < avctx->height; i++) {
+        memcpy(dst, buf, avctx->width);
+        dst += s->pic.linesize[0];
+        buf += avctx->width;
+    }
+    memcpy(s->pic.data[1], s->pal, sizeof(s->pal));
+
+    *data_size = sizeof(AVFrame);
+    *(AVFrame*)data = s->pic;
+
+    return avpkt->size;
+}
+
+static av_cold int dfa_decode_end(AVCodecContext *avctx)
+{
+    DfaContext *s = avctx->priv_data;
+
+    if (s->pic.data[0])
+        avctx->release_buffer(avctx, &s->pic);
+
+    av_freep(&s->frame_buf);
+
+    return 0;
+}
+
+AVCodec ff_dfa_decoder = {
+    "dfa",
+    AVMEDIA_TYPE_VIDEO,
+    CODEC_ID_DFA,
+    sizeof(DfaContext),
+    dfa_decode_init,
+    NULL,
+    dfa_decode_end,
+    dfa_decode_frame,
+    CODEC_CAP_DR1,
+    .long_name = NULL_IF_CONFIG_SMALL("Chronomaster DFA"),
+};
diff --git a/libavcodec/dirac.c b/libavcodec/dirac.c
index c65a51f..0256f29 100644
--- a/libavcodec/dirac.c
+++ b/libavcodec/dirac.c
@@ -2,20 +2,20 @@
  * Copyright (C) 2007 Marco Gerards <marco at gnu.org>
  * Copyright (C) 2009 David Conrad
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,6 +25,7 @@
  * @author Marco Gerards <marco at gnu.org>
  */
 
+#include "libavutil/imgutils.h"
 #include "dirac.h"
 #include "avcodec.h"
 #include "golomb.h"
@@ -268,7 +269,7 @@ int ff_dirac_parse_sequence_header(AVCodecContext *avctx, GetBitContext *gb,
     if (parse_source_parameters(avctx, gb, source))
         return -1;
 
-    if (avcodec_check_dimensions(avctx, source->width, source->height))
+    if (av_image_check_size(source->width, source->height, 0, avctx))
         return -1;
 
     avcodec_set_dimensions(avctx, source->width, source->height);
diff --git a/libavcodec/dirac.h b/libavcodec/dirac.h
index 09c5581..0be66c2 100644
--- a/libavcodec/dirac.h
+++ b/libavcodec/dirac.h
@@ -2,20 +2,20 @@
  * Copyright (C) 2007 Marco Gerards <marco at gnu.org>
  * Copyright (C) 2009 David Conrad
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -24,7 +24,7 @@
 
 /**
  * @file
- * Interfaces to Dirac Decoder/Encoder
+ * Interface to Dirac Decoder/Encoder
  * @author Marco Gerards <marco at gnu.org>
  */
 
diff --git a/libavcodec/dirac_parser.c b/libavcodec/dirac_parser.c
index c82f0e6..aa561f7 100644
--- a/libavcodec/dirac_parser.c
+++ b/libavcodec/dirac_parser.c
@@ -4,20 +4,20 @@
  * Copyright (c) 2007-2008 Marco Gerards <marco at gnu.org>
  * Copyright (c) 2008 BBC, Anuradha Suraparaju <asuraparaju at gmail.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -33,7 +33,7 @@
 #define DIRAC_PARSE_INFO_PREFIX 0x42424344
 
 /**
- * Finds the end of the current frame in the bitstream.
+ * Find the end of the current frame in the bitstream.
  * @return the position of the first byte of the next frame or -1
  */
 typedef struct DiracParseContext {
@@ -247,7 +247,7 @@ static void dirac_parse_close(AVCodecParserContext *s)
         av_free(pc->buffer);
 }
 
-AVCodecParser dirac_parser = {
+AVCodecParser ff_dirac_parser = {
     { CODEC_ID_DIRAC },
     sizeof(DiracParseContext),
     NULL,
diff --git a/libavcodec/dnxhd_parser.c b/libavcodec/dnxhd_parser.c
index 6149a2d..44ea8f0 100644
--- a/libavcodec/dnxhd_parser.c
+++ b/libavcodec/dnxhd_parser.c
@@ -2,20 +2,20 @@
  * DNxHD/VC-3 parser
  * Copyright (c) 2008 Baptiste Coudurier <baptiste.coudurier at free.fr>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -86,7 +86,7 @@ static int dnxhd_parse(AVCodecParserContext *s,
     return next;
 }
 
-AVCodecParser dnxhd_parser = {
+AVCodecParser ff_dnxhd_parser = {
     { CODEC_ID_DNXHD },
     sizeof(ParseContext),
     NULL,
diff --git a/libavcodec/dnxhddata.c b/libavcodec/dnxhddata.c
index 2625a9b..82d083c 100644
--- a/libavcodec/dnxhddata.c
+++ b/libavcodec/dnxhddata.c
@@ -2,20 +2,20 @@
  * VC3/DNxHD data.
  * Copyright (c) 2007 SmartJog S.A., Baptiste Coudurier <baptiste dot coudurier at smartjog dot com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/dnxhddata.h b/libavcodec/dnxhddata.h
index 32c77db..df84187 100644
--- a/libavcodec/dnxhddata.h
+++ b/libavcodec/dnxhddata.h
@@ -2,20 +2,20 @@
  * VC3/DNxHD decoder.
  * Copyright (c) 2007 SmartJog S.A., Baptiste Coudurier <baptiste dot coudurier at smartjog dot com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/dnxhddec.c b/libavcodec/dnxhddec.c
index 8b7c343..e4ad5cf 100644
--- a/libavcodec/dnxhddec.c
+++ b/libavcodec/dnxhddec.c
@@ -2,26 +2,27 @@
  * VC3/DNxHD decoder.
  * Copyright (c) 2007 SmartJog S.A., Baptiste Coudurier <baptiste dot coudurier at smartjog dot com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 //#define TRACE
 //#define DEBUG
 
+#include "libavutil/imgutils.h"
 #include "avcodec.h"
 #include "get_bits.h"
 #include "dnxhddata.h"
@@ -55,6 +56,7 @@ static av_cold int dnxhd_decode_init(AVCodecContext *avctx)
     dsputil_init(&ctx->dsp, avctx);
     avctx->coded_frame = &ctx->picture;
     ctx->picture.type = FF_I_TYPE;
+    ctx->picture.key_frame = 1;
     return 0;
 }
 
@@ -105,7 +107,7 @@ static int dnxhd_decode_header(DNXHDContext *ctx, const uint8_t *buf, int buf_si
     ctx->height = AV_RB16(buf + 0x18);
     ctx->width  = AV_RB16(buf + 0x1a);
 
-    dprintf(ctx->avctx, "width %d, heigth %d\n", ctx->width, ctx->height);
+    av_dlog(ctx->avctx, "width %d, heigth %d\n", ctx->width, ctx->height);
 
     if (buf[0x21] & 0x40) {
         av_log(ctx->avctx, AV_LOG_ERROR, "10 bit per component\n");
@@ -113,7 +115,7 @@ static int dnxhd_decode_header(DNXHDContext *ctx, const uint8_t *buf, int buf_si
     }
 
     ctx->cid = AV_RB32(buf + 0x28);
-    dprintf(ctx->avctx, "compression id %d\n", ctx->cid);
+    av_dlog(ctx->avctx, "compression id %d\n", ctx->cid);
 
     if (dnxhd_init_vlc(ctx, ctx->cid) < 0)
         return -1;
@@ -126,7 +128,7 @@ static int dnxhd_decode_header(DNXHDContext *ctx, const uint8_t *buf, int buf_si
     ctx->mb_width = ctx->width>>4;
     ctx->mb_height = buf[0x16d];
 
-    dprintf(ctx->avctx, "mb width %d, mb height %d\n", ctx->mb_width, ctx->mb_height);
+    av_dlog(ctx->avctx, "mb width %d, mb height %d\n", ctx->mb_width, ctx->mb_height);
 
     if ((ctx->height+15)>>4 == ctx->mb_height && ctx->picture.interlaced_frame)
         ctx->height <<= 1;
@@ -139,7 +141,7 @@ static int dnxhd_decode_header(DNXHDContext *ctx, const uint8_t *buf, int buf_si
 
     for (i = 0; i < ctx->mb_height; i++) {
         ctx->mb_scan_index[i] = AV_RB32(buf + 0x170 + (i<<2));
-        dprintf(ctx->avctx, "mb scan index %d\n", ctx->mb_scan_index[i]);
+        av_dlog(ctx->avctx, "mb scan index %d\n", ctx->mb_scan_index[i]);
         if (buf_size < ctx->mb_scan_index[i] + 0x280) {
             av_log(ctx->avctx, AV_LOG_ERROR, "invalid mb scan index\n");
             return -1;
@@ -291,7 +293,7 @@ static int dnxhd_decode_frame(AVCodecContext *avctx, void *data, int *data_size,
     AVFrame *picture = data;
     int first_field = 1;
 
-    dprintf(avctx, "frame size %d\n", buf_size);
+    av_dlog(avctx, "frame size %d\n", buf_size);
 
  decode_coding_unit:
     if (dnxhd_decode_header(ctx, buf, buf_size, first_field) < 0)
@@ -305,7 +307,7 @@ static int dnxhd_decode_frame(AVCodecContext *avctx, void *data, int *data_size,
     }
 
     avctx->pix_fmt = PIX_FMT_YUV422P;
-    if (avcodec_check_dimensions(avctx, ctx->width, ctx->height))
+    if (av_image_check_size(ctx->width, ctx->height, 0, avctx))
         return -1;
     avcodec_set_dimensions(avctx, ctx->width, ctx->height);
 
@@ -344,7 +346,7 @@ static av_cold int dnxhd_decode_close(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec dnxhd_decoder = {
+AVCodec ff_dnxhd_decoder = {
     "dnxhd",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_DNXHD,
diff --git a/libavcodec/dnxhdenc.c b/libavcodec/dnxhdenc.c
index 6b08929..958f9d4 100644
--- a/libavcodec/dnxhdenc.c
+++ b/libavcodec/dnxhdenc.c
@@ -4,31 +4,40 @@
  *
  * VC-3 encoder funded by the British Broadcasting Corporation
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 //#define DEBUG
 #define RC_VARIANCE 1 // use variance or ssd for fast rc
 
+#include "libavutil/opt.h"
 #include "avcodec.h"
 #include "dsputil.h"
 #include "mpegvideo.h"
 #include "dnxhdenc.h"
 
+#define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
+
+static const AVOption options[]={
+    {"nitris_compat", "encode with Avid Nitris compatibility", offsetof(DNXHDEncContext, nitris_compat), FF_OPT_TYPE_INT, 0, 0, 1, VE},
+{NULL}
+};
+static const AVClass class = { "dnxhd", av_default_item_name, options, LIBAVUTIL_VERSION_INT };
+
 int dct_quantize_c(MpegEncContext *s, DCTELEM *block, int n, int qscale, int *overflow);
 
 #define LAMBDA_FRAC_BITS 10
@@ -146,7 +155,7 @@ static int dnxhd_init_rc(DNXHDEncContext *ctx)
     if (ctx->m.avctx->mb_decision != FF_MB_DECISION_RD)
         FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->mb_cmp, ctx->m.mb_num*sizeof(RCCMPEntry), fail);
 
-    ctx->frame_bits = (ctx->cid_table->coding_unit_size - 640 - 4) * 8;
+    ctx->frame_bits = (ctx->cid_table->coding_unit_size - 640 - 4 - ctx->min_padding) * 8;
     ctx->qscale = 1;
     ctx->lambda = 2<<LAMBDA_FRAC_BITS; // qscale 2
     return 0;
@@ -198,6 +207,10 @@ static int dnxhd_encode_init(AVCodecContext *avctx)
     if (dnxhd_init_qmat(ctx, ctx->m.intra_quant_bias, 0) < 0) // XXX tune lbias/cbias
         return -1;
 
+    // Avid Nitris hardware decoder requires a minimum amount of padding in the coding unit payload
+    if (ctx->nitris_compat)
+        ctx->min_padding = 1600;
+
     if (dnxhd_init_vlc(ctx) < 0)
         return -1;
     if (dnxhd_init_rc(ctx) < 0)
@@ -239,12 +252,12 @@ static int dnxhd_write_header(AVCodecContext *avctx, uint8_t *buf)
     buf[5] = ctx->interlaced ? ctx->cur_field+2 : 0x01;
     buf[6] = 0x80; // crc flag off
     buf[7] = 0xa0; // reserved
-    AV_WB16(buf + 0x18, avctx->height); // ALPF
+    AV_WB16(buf + 0x18, avctx->height>>ctx->interlaced); // ALPF
     AV_WB16(buf + 0x1a, avctx->width);  // SPL
-    AV_WB16(buf + 0x1d, avctx->height); // NAL
+    AV_WB16(buf + 0x1d, avctx->height>>ctx->interlaced); // NAL
 
     buf[0x21] = 0x38; // FIXME 8 bit per comp
-    buf[0x22] = 0x88 + (ctx->frame.interlaced_frame<<2);
+    buf[0x22] = 0x88 + (ctx->interlaced<<2);
     AV_WB32(buf + 0x28, ctx->cid); // CID
     buf[0x2c] = ctx->interlaced ? 0 : 0x80;
 
@@ -552,7 +565,7 @@ static int dnxhd_encode_rdo(AVCodecContext *avctx, DNXHDEncContext *ctx)
             if (bits > ctx->frame_bits)
                 break;
         }
-        //dprintf(ctx->m.avctx, "lambda %d, up %u, down %u, bits %d, frame %d\n",
+        //av_dlog(ctx->m.avctx, "lambda %d, up %u, down %u, bits %d, frame %d\n",
         //        lambda, last_higher, last_lower, bits, ctx->frame_bits);
         if (end) {
             if (bits > ctx->frame_bits)
@@ -582,7 +595,7 @@ static int dnxhd_encode_rdo(AVCodecContext *avctx, DNXHDEncContext *ctx)
             down_step = 1<<LAMBDA_FRAC_BITS;
         }
     }
-    //dprintf(ctx->m.avctx, "out lambda %d\n", lambda);
+    //av_dlog(ctx->m.avctx, "out lambda %d\n", lambda);
     ctx->lambda = lambda;
     return 0;
 }
@@ -610,7 +623,7 @@ static int dnxhd_find_qscale(DNXHDEncContext *ctx)
             if (bits > ctx->frame_bits)
                 break;
         }
-        //dprintf(ctx->m.avctx, "%d, qscale %d, bits %d, frame %d, higher %d, lower %d\n",
+        //av_dlog(ctx->m.avctx, "%d, qscale %d, bits %d, frame %d, higher %d, lower %d\n",
         //        ctx->m.avctx->frame_number, qscale, bits, ctx->frame_bits, last_higher, last_lower);
         if (bits < ctx->frame_bits) {
             if (qscale == 1)
@@ -640,7 +653,7 @@ static int dnxhd_find_qscale(DNXHDEncContext *ctx)
                 return -1;
         }
     }
-    //dprintf(ctx->m.avctx, "out qscale %d\n", qscale);
+    //av_dlog(ctx->m.avctx, "out qscale %d\n", qscale);
     ctx->qscale = qscale;
     return 0;
 }
@@ -848,7 +861,7 @@ static int dnxhd_encode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec dnxhd_encoder = {
+AVCodec ff_dnxhd_encoder = {
     "dnxhd",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_DNXHD,
@@ -858,4 +871,5 @@ AVCodec dnxhd_encoder = {
     dnxhd_encode_end,
     .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUV422P, PIX_FMT_NONE},
     .long_name = NULL_IF_CONFIG_SMALL("VC3/DNxHD"),
+    .priv_class = &class,
 };
diff --git a/libavcodec/dnxhdenc.h b/libavcodec/dnxhdenc.h
index eaf33d5..83c0b1c 100644
--- a/libavcodec/dnxhdenc.h
+++ b/libavcodec/dnxhdenc.h
@@ -4,20 +4,20 @@
  *
  * VC-3 encoder funded by the British Broadcasting Corporation
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -55,6 +55,9 @@ typedef struct DNXHDEncContext {
     int interlaced;
     int cur_field;
 
+    int nitris_compat;
+    unsigned min_padding;
+
     DECLARE_ALIGNED(16, DCTELEM, blocks)[8][64];
 
     int      (*qmatrix_c)     [64];
diff --git a/libavcodec/dpcm.c b/libavcodec/dpcm.c
index 7c53516..af5bf8a 100644
--- a/libavcodec/dpcm.c
+++ b/libavcodec/dpcm.c
@@ -2,25 +2,25 @@
  * Assorted DPCM codecs
  * Copyright (c) 2003 The ffmpeg Project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 /**
- * @file: dpcm.c
+ * @file
  * Assorted DPCM (differential pulse code modulation) audio codecs
  * by Mike Melanson (melanson at pcisys.net)
  * Xan DPCM decoder by Mario Brito (mbrito at student.dei.uc.pt)
@@ -155,7 +155,7 @@ static av_cold int dpcm_decode_init(AVCodecContext *avctx)
         break;
     }
 
-    avctx->sample_fmt = SAMPLE_FMT_S16;
+    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
     return 0;
 }
 
@@ -299,7 +299,7 @@ static int dpcm_decode_frame(AVCodecContext *avctx,
 }
 
 #define DPCM_DECODER(id, name, long_name_)      \
-AVCodec name ## _decoder = {                    \
+AVCodec ff_ ## name ## _decoder = {             \
     #name,                                      \
     AVMEDIA_TYPE_AUDIO,                         \
     id,                                         \
@@ -309,7 +309,7 @@ AVCodec name ## _decoder = {                    \
     NULL,                                       \
     dpcm_decode_frame,                          \
     .long_name = NULL_IF_CONFIG_SMALL(long_name_), \
-};
+}
 
 DPCM_DECODER(CODEC_ID_INTERPLAY_DPCM, interplay_dpcm, "DPCM Interplay");
 DPCM_DECODER(CODEC_ID_ROQ_DPCM, roq_dpcm, "DPCM id RoQ");
diff --git a/libavcodec/dpx.c b/libavcodec/dpx.c
index 94a9181..36a4a39 100644
--- a/libavcodec/dpx.c
+++ b/libavcodec/dpx.c
@@ -2,24 +2,25 @@
  * DPX (.dpx) image decoder
  * Copyright (c) 2009 Jimmy Christensen
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "libavutil/intreadwrite.h"
+#include "libavutil/imgutils.h"
 #include "bytestream.h"
 #include "avcodec.h"
 
@@ -54,6 +55,7 @@ static int decode_frame(AVCodecContext *avctx,
                         AVPacket *avpkt)
 {
     const uint8_t *buf = avpkt->data;
+    const uint8_t *buf_end = avpkt->data + avpkt->size;
     int buf_size       = avpkt->size;
     DPXContext *const s = avctx->priv_data;
     AVFrame *picture  = data;
@@ -139,7 +141,7 @@ static int decode_frame(AVCodecContext *avctx,
 
     if (s->picture.data[0])
         avctx->release_buffer(avctx, &s->picture);
-    if (avcodec_check_dimensions(avctx, w, h))
+    if (av_image_check_size(w, h, 0, avctx))
         return -1;
     if (w != avctx->width || h != avctx->height)
         avcodec_set_dimensions(avctx, w, h);
@@ -171,6 +173,10 @@ static int decode_frame(AVCodecContext *avctx,
         case 8:
         case 12: // Treat 12-bit as 16-bit
         case 16:
+            if (source_packet_size*avctx->width*avctx->height > buf_end - buf) {
+                av_log(avctx, AV_LOG_ERROR, "Overread buffer. Invalid header?\n");
+                return -1;
+            }
             if (source_packet_size == target_packet_size) {
                 for (x = 0; x < avctx->height; x++) {
                     memcpy(ptr, buf, target_packet_size*avctx->width);
@@ -214,7 +220,7 @@ static av_cold int decode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec dpx_decoder = {
+AVCodec ff_dpx_decoder = {
     "dpx",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_DPX,
diff --git a/libavcodec/dsicinav.c b/libavcodec/dsicinav.c
index 895b623..643aed9 100644
--- a/libavcodec/dsicinav.c
+++ b/libavcodec/dsicinav.c
@@ -2,20 +2,20 @@
  * Delphine Software International CIN Audio/Video Decoders
  * Copyright (c) 2006 Gregory Montoir (cyx at users.sourceforge.net)
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -307,7 +307,7 @@ static av_cold int cinaudio_decode_init(AVCodecContext *avctx)
     cin->avctx = avctx;
     cin->initial_decode_frame = 1;
     cin->delta = 0;
-    avctx->sample_fmt = SAMPLE_FMT_S16;
+    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
 
     return 0;
 }
@@ -343,7 +343,7 @@ static int cinaudio_decode_frame(AVCodecContext *avctx,
 }
 
 
-AVCodec dsicinvideo_decoder = {
+AVCodec ff_dsicinvideo_decoder = {
     "dsicinvideo",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_DSICINVIDEO,
@@ -356,7 +356,7 @@ AVCodec dsicinvideo_decoder = {
     .long_name = NULL_IF_CONFIG_SMALL("Delphine Software International CIN video"),
 };
 
-AVCodec dsicinaudio_decoder = {
+AVCodec ff_dsicinaudio_decoder = {
     "dsicinaudio",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_DSICINAUDIO,
diff --git a/libavcodec/dsputil.c b/libavcodec/dsputil.c
index 0701324..215c1e4 100644
--- a/libavcodec/dsputil.c
+++ b/libavcodec/dsputil.c
@@ -5,20 +5,20 @@
  *
  * gmc & q-pel & 32/64 bit based MC by Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -27,6 +27,7 @@
  * DSP utils
  */
 
+#include "libavutil/imgutils.h"
 #include "avcodec.h"
 #include "dsputil.h"
 #include "simple_idct.h"
@@ -35,7 +36,6 @@
 #include "mathops.h"
 #include "mpegvideo.h"
 #include "config.h"
-#include "lpc.h"
 #include "ac3dec.h"
 #include "vorbis.h"
 #include "png.h"
@@ -96,44 +96,6 @@ const uint8_t ff_alternate_vertical_scan[64] = {
     38, 46, 54, 62, 39, 47, 55, 63,
 };
 
-/* a*inverse[b]>>32 == a/b for all 0<=a<=16909558 && 2<=b<=256
- * for a>16909558, is an overestimate by less than 1 part in 1<<24 */
-const uint32_t ff_inverse[257]={
-         0, 4294967295U,2147483648U,1431655766, 1073741824,  858993460,  715827883,  613566757,
- 536870912,  477218589,  429496730,  390451573,  357913942,  330382100,  306783379,  286331154,
- 268435456,  252645136,  238609295,  226050911,  214748365,  204522253,  195225787,  186737709,
- 178956971,  171798692,  165191050,  159072863,  153391690,  148102321,  143165577,  138547333,
- 134217728,  130150525,  126322568,  122713352,  119304648,  116080198,  113025456,  110127367,
- 107374183,  104755300,  102261127,   99882961,   97612894,   95443718,   93368855,   91382283,
-  89478486,   87652394,   85899346,   84215046,   82595525,   81037119,   79536432,   78090315,
-  76695845,   75350304,   74051161,   72796056,   71582789,   70409300,   69273667,   68174085,
-  67108864,   66076420,   65075263,   64103990,   63161284,   62245903,   61356676,   60492498,
-  59652324,   58835169,   58040099,   57266231,   56512728,   55778797,   55063684,   54366675,
-  53687092,   53024288,   52377650,   51746594,   51130564,   50529028,   49941481,   49367441,
-  48806447,   48258060,   47721859,   47197443,   46684428,   46182445,   45691142,   45210183,
-  44739243,   44278014,   43826197,   43383509,   42949673,   42524429,   42107523,   41698712,
-  41297763,   40904451,   40518560,   40139882,   39768216,   39403370,   39045158,   38693400,
-  38347923,   38008561,   37675152,   37347542,   37025581,   36709123,   36398028,   36092163,
-  35791395,   35495598,   35204650,   34918434,   34636834,   34359739,   34087043,   33818641,
-  33554432,   33294321,   33038210,   32786010,   32537632,   32292988,   32051995,   31814573,
-  31580642,   31350127,   31122952,   30899046,   30678338,   30460761,   30246249,   30034737,
-  29826162,   29620465,   29417585,   29217465,   29020050,   28825284,   28633116,   28443493,
-  28256364,   28071682,   27889399,   27709467,   27531842,   27356480,   27183338,   27012373,
-  26843546,   26676816,   26512144,   26349493,   26188825,   26030105,   25873297,   25718368,
-  25565282,   25414008,   25264514,   25116768,   24970741,   24826401,   24683721,   24542671,
-  24403224,   24265352,   24129030,   23994231,   23860930,   23729102,   23598722,   23469767,
-  23342214,   23216040,   23091223,   22967740,   22845571,   22724695,   22605092,   22486740,
-  22369622,   22253717,   22139007,   22025474,   21913099,   21801865,   21691755,   21582751,
-  21474837,   21367997,   21262215,   21157475,   21053762,   20951060,   20849356,   20748635,
-  20648882,   20550083,   20452226,   20355296,   20259280,   20164166,   20069941,   19976593,
-  19884108,   19792477,   19701685,   19611723,   19522579,   19434242,   19346700,   19259944,
-  19173962,   19088744,   19004281,   18920561,   18837576,   18755316,   18673771,   18592933,
-  18512791,   18433337,   18354562,   18276457,   18199014,   18122225,   18046082,   17970575,
-  17895698,   17821442,   17747799,   17674763,   17602325,   17530479,   17459217,   17388532,
-  17318417,   17248865,   17179870,   17111424,   17043522,   16976156,   16909321,   16843010,
-  16777216
-};
-
 /* Input permutation for the simple_idct_mmx */
 static const uint8_t simple_mmx_permutation[64]={
         0x00, 0x08, 0x04, 0x09, 0x01, 0x0C, 0x05, 0x0D,
@@ -246,20 +208,26 @@ static void bswap_buf(uint32_t *dst, const uint32_t *src, int w){
     int i;
 
     for(i=0; i+8<=w; i+=8){
-        dst[i+0]= bswap_32(src[i+0]);
-        dst[i+1]= bswap_32(src[i+1]);
-        dst[i+2]= bswap_32(src[i+2]);
-        dst[i+3]= bswap_32(src[i+3]);
-        dst[i+4]= bswap_32(src[i+4]);
-        dst[i+5]= bswap_32(src[i+5]);
-        dst[i+6]= bswap_32(src[i+6]);
-        dst[i+7]= bswap_32(src[i+7]);
+        dst[i+0]= av_bswap32(src[i+0]);
+        dst[i+1]= av_bswap32(src[i+1]);
+        dst[i+2]= av_bswap32(src[i+2]);
+        dst[i+3]= av_bswap32(src[i+3]);
+        dst[i+4]= av_bswap32(src[i+4]);
+        dst[i+5]= av_bswap32(src[i+5]);
+        dst[i+6]= av_bswap32(src[i+6]);
+        dst[i+7]= av_bswap32(src[i+7]);
     }
     for(;i<w; i++){
-        dst[i+0]= bswap_32(src[i+0]);
+        dst[i+0]= av_bswap32(src[i+0]);
     }
 }
 
+static void bswap16_buf(uint16_t *dst, const uint16_t *src, int len)
+{
+    while (len--)
+        *dst++ = av_bswap16(*src++);
+}
+
 static int sse4_c(void *v, uint8_t * pix1, uint8_t * pix2, int line_size, int h)
 {
     int s, i;
@@ -330,17 +298,11 @@ static int sse16_c(void *v, uint8_t *pix1, uint8_t *pix2, int line_size, int h)
 
 /* draw the edges of width 'w' of an image of size width, height */
 //FIXME check that this is ok for mpeg4 interlaced
-static void draw_edges_c(uint8_t *buf, int wrap, int width, int height, int w)
+static void draw_edges_c(uint8_t *buf, int wrap, int width, int height, int w, int sides)
 {
     uint8_t *ptr, *last_line;
     int i;
 
-    last_line = buf + (height - 1) * wrap;
-    for(i=0;i<w;i++) {
-        /* top and bottom */
-        memcpy(buf - (i + 1) * wrap, buf, width);
-        memcpy(last_line + (i + 1) * wrap, last_line, width);
-    }
     /* left and right */
     ptr = buf;
     for(i=0;i<height;i++) {
@@ -348,17 +310,20 @@ static void draw_edges_c(uint8_t *buf, int wrap, int width, int height, int w)
         memset(ptr + width, ptr[width-1], w);
         ptr += wrap;
     }
-    /* corners */
-    for(i=0;i<w;i++) {
-        memset(buf - (i + 1) * wrap - w, buf[0], w); /* top left */
-        memset(buf - (i + 1) * wrap + width, buf[width-1], w); /* top right */
-        memset(last_line + (i + 1) * wrap - w, last_line[0], w); /* top left */
-        memset(last_line + (i + 1) * wrap + width, last_line[width-1], w); /* top right */
-    }
+
+    /* top and bottom + corners */
+    buf -= w;
+    last_line = buf + (height - 1) * wrap;
+    if (sides & EDGE_TOP)
+        for(i = 0; i < w; i++)
+            memcpy(buf - (i + 1) * wrap, buf, width + w + w); // top
+    if (sides & EDGE_BOTTOM)
+        for (i = 0; i < w; i++)
+            memcpy(last_line + (i + 1) * wrap, last_line, width + w + w); // bottom
 }
 
 /**
- * Copies a rectangular area of samples to a temporary buffer and replicates the boarder samples.
+ * Copy a rectangular area of samples to a temporary buffer and replicate the border samples.
  * @param buf destination buffer
  * @param src source buffer
  * @param linesize number of bytes between 2 vertically adjacent samples in both the source and destination buffers
@@ -369,7 +334,7 @@ static void draw_edges_c(uint8_t *buf, int wrap, int width, int height, int w)
  * @param w width of the source buffer
  * @param h height of the source buffer
  */
-void ff_emulated_edge_mc(uint8_t *buf, uint8_t *src, int linesize, int block_w, int block_h,
+void ff_emulated_edge_mc(uint8_t *buf, const uint8_t *src, int linesize, int block_w, int block_h,
                                     int src_x, int src_y, int w, int h){
     int x, y;
     int start_y, start_x, end_y, end_x;
@@ -393,38 +358,45 @@ void ff_emulated_edge_mc(uint8_t *buf, uint8_t *src, int linesize, int block_w,
     start_x= FFMAX(0, -src_x);
     end_y= FFMIN(block_h, h-src_y);
     end_x= FFMIN(block_w, w-src_x);
+    assert(start_y < end_y && block_h);
+    assert(start_x < end_x && block_w);
 
-    // copy existing part
-    for(y=start_y; y<end_y; y++){
-        for(x=start_x; x<end_x; x++){
-            buf[x + y*linesize]= src[x + y*linesize];
-        }
-    }
+    w    = end_x - start_x;
+    src += start_y*linesize + start_x;
+    buf += start_x;
 
     //top
     for(y=0; y<start_y; y++){
-        for(x=start_x; x<end_x; x++){
-            buf[x + y*linesize]= buf[x + start_y*linesize];
-        }
+        memcpy(buf, src, w);
+        buf += linesize;
+    }
+
+    // copy existing part
+    for(; y<end_y; y++){
+        memcpy(buf, src, w);
+        src += linesize;
+        buf += linesize;
     }
 
     //bottom
-    for(y=end_y; y<block_h; y++){
-        for(x=start_x; x<end_x; x++){
-            buf[x + y*linesize]= buf[x + (end_y-1)*linesize];
-        }
+    src -= linesize;
+    for(; y<block_h; y++){
+        memcpy(buf, src, w);
+        buf += linesize;
     }
 
-    for(y=0; y<block_h; y++){
+    buf -= block_h * linesize + start_x;
+    while (block_h--){
        //left
         for(x=0; x<start_x; x++){
-            buf[x + y*linesize]= buf[start_x + y*linesize];
+            buf[x] = buf[start_x];
         }
 
        //right
         for(x=end_x; x<block_w; x++){
-            buf[x + y*linesize]= buf[end_x - 1 + y*linesize];
+            buf[x] = buf[end_x - 1];
         }
+        buf += linesize;
     }
 }
 
@@ -468,8 +440,8 @@ static void diff_pixels_c(DCTELEM *restrict block, const uint8_t *s1,
 }
 
 
-static void put_pixels_clamped_c(const DCTELEM *block, uint8_t *restrict pixels,
-                                 int line_size)
+void ff_put_pixels_clamped_c(const DCTELEM *block, uint8_t *restrict pixels,
+                             int line_size)
 {
     int i;
     uint8_t *cm = ff_cropTbl + MAX_NEG_CROP;
@@ -524,9 +496,9 @@ static void put_pixels_clamped2_c(const DCTELEM *block, uint8_t *restrict pixels
     }
 }
 
-static void put_signed_pixels_clamped_c(const DCTELEM *block,
-                                        uint8_t *restrict pixels,
-                                        int line_size)
+void ff_put_signed_pixels_clamped_c(const DCTELEM *block,
+                                    uint8_t *restrict pixels,
+                                    int line_size)
 {
     int i, j;
 
@@ -566,8 +538,8 @@ static void put_pixels_nonclamped_c(const DCTELEM *block, uint8_t *restrict pixe
     }
 }
 
-static void add_pixels_clamped_c(const DCTELEM *block, uint8_t *restrict pixels,
-                          int line_size)
+void ff_add_pixels_clamped_c(const DCTELEM *block, uint8_t *restrict pixels,
+                             int line_size)
 {
     int i;
     uint8_t *cm = ff_cropTbl + MAX_NEG_CROP;
@@ -945,7 +917,7 @@ static inline void OPNAME ## _pixels8_y2_c(uint8_t *block, const uint8_t *pixels
     OPNAME ## _pixels8_l2(block, pixels, pixels+line_size, line_size, line_size, line_size, h);\
 }\
 \
-static inline void OPNAME ## _pixels8_l4(uint8_t *dst, const uint8_t *src1, uint8_t *src2, uint8_t *src3, uint8_t *src4,\
+static inline void OPNAME ## _pixels8_l4(uint8_t *dst, const uint8_t *src1, const uint8_t *src2, const uint8_t *src3, const uint8_t *src4,\
                  int dst_stride, int src_stride1, int src_stride2,int src_stride3,int src_stride4, int h){\
     int i;\
     for(i=0; i<h; i++){\
@@ -997,7 +969,7 @@ static inline void OPNAME ## _pixels2_y2_c(uint8_t *block, const uint8_t *pixels
     OPNAME ## _pixels2_l2(block, pixels, pixels+line_size, line_size, line_size, line_size, h);\
 }\
 \
-static inline void OPNAME ## _no_rnd_pixels8_l4(uint8_t *dst, const uint8_t *src1, uint8_t *src2, uint8_t *src3, uint8_t *src4,\
+static inline void OPNAME ## _no_rnd_pixels8_l4(uint8_t *dst, const uint8_t *src1, const uint8_t *src2, const uint8_t *src3, const uint8_t *src4,\
                  int dst_stride, int src_stride1, int src_stride2,int src_stride3,int src_stride4, int h){\
     int i;\
     for(i=0; i<h; i++){\
@@ -1032,12 +1004,12 @@ static inline void OPNAME ## _no_rnd_pixels8_l4(uint8_t *dst, const uint8_t *src
         OP(*((uint32_t*)&dst[i*dst_stride+4]), h0+h1+(((l0+l1)>>2)&0x0F0F0F0FUL));\
     }\
 }\
-static inline void OPNAME ## _pixels16_l4(uint8_t *dst, const uint8_t *src1, uint8_t *src2, uint8_t *src3, uint8_t *src4,\
+static inline void OPNAME ## _pixels16_l4(uint8_t *dst, const uint8_t *src1, const uint8_t *src2, const uint8_t *src3, const uint8_t *src4,\
                  int dst_stride, int src_stride1, int src_stride2,int src_stride3,int src_stride4, int h){\
     OPNAME ## _pixels8_l4(dst  , src1  , src2  , src3  , src4  , dst_stride, src_stride1, src_stride2, src_stride3, src_stride4, h);\
     OPNAME ## _pixels8_l4(dst+8, src1+8, src2+8, src3+8, src4+8, dst_stride, src_stride1, src_stride2, src_stride3, src_stride4, h);\
 }\
-static inline void OPNAME ## _no_rnd_pixels16_l4(uint8_t *dst, const uint8_t *src1, uint8_t *src2, uint8_t *src3, uint8_t *src4,\
+static inline void OPNAME ## _no_rnd_pixels16_l4(uint8_t *dst, const uint8_t *src1, const uint8_t *src2, const uint8_t *src3, const uint8_t *src4,\
                  int dst_stride, int src_stride1, int src_stride2,int src_stride3,int src_stride4, int h){\
     OPNAME ## _no_rnd_pixels8_l4(dst  , src1  , src2  , src3  , src4  , dst_stride, src_stride1, src_stride2, src_stride3, src_stride4, h);\
     OPNAME ## _no_rnd_pixels8_l4(dst+8, src1+8, src2+8, src3+8, src4+8, dst_stride, src_stride1, src_stride2, src_stride3, src_stride4, h);\
@@ -1198,7 +1170,7 @@ CALL_2X_PIXELS(OPNAME ## _pixels16_c  , OPNAME ## _pixels8_c  , 8)\
 CALL_2X_PIXELS(OPNAME ## _pixels16_x2_c , OPNAME ## _pixels8_x2_c , 8)\
 CALL_2X_PIXELS(OPNAME ## _pixels16_y2_c , OPNAME ## _pixels8_y2_c , 8)\
 CALL_2X_PIXELS(OPNAME ## _pixels16_xy2_c, OPNAME ## _pixels8_xy2_c, 8)\
-CALL_2X_PIXELS(OPNAME ## _no_rnd_pixels16_c  , OPNAME ## _pixels8_c         , 8)\
+av_unused CALL_2X_PIXELS(OPNAME ## _no_rnd_pixels16_c  , OPNAME ## _pixels8_c         , 8)\
 CALL_2X_PIXELS(OPNAME ## _no_rnd_pixels16_x2_c , OPNAME ## _no_rnd_pixels8_x2_c , 8)\
 CALL_2X_PIXELS(OPNAME ## _no_rnd_pixels16_y2_c , OPNAME ## _no_rnd_pixels8_y2_c , 8)\
 CALL_2X_PIXELS(OPNAME ## _no_rnd_pixels16_xy2_c, OPNAME ## _no_rnd_pixels8_xy2_c, 8)\
@@ -1212,6 +1184,9 @@ PIXOP2(put, op_put)
 #undef op_avg
 #undef op_put
 
+#define put_no_rnd_pixels8_c  put_pixels8_c
+#define put_no_rnd_pixels16_c put_pixels16_c
+
 #define avg2(a,b) ((a+b+1)>>1)
 #define avg4(a,b,c,d) ((a+b+c+d+2)>>2)
 
@@ -1628,54 +1603,6 @@ H264_CHROMA_MC(avg_       , op_avg)
 #undef op_avg
 #undef op_put
 
-static void put_no_rnd_vc1_chroma_mc8_c(uint8_t *dst/*align 8*/, uint8_t *src/*align 1*/, int stride, int h, int x, int y){
-    const int A=(8-x)*(8-y);
-    const int B=(  x)*(8-y);
-    const int C=(8-x)*(  y);
-    const int D=(  x)*(  y);
-    int i;
-
-    assert(x<8 && y<8 && x>=0 && y>=0);
-
-    for(i=0; i<h; i++)
-    {
-        dst[0] = (A*src[0] + B*src[1] + C*src[stride+0] + D*src[stride+1] + 32 - 4) >> 6;
-        dst[1] = (A*src[1] + B*src[2] + C*src[stride+1] + D*src[stride+2] + 32 - 4) >> 6;
-        dst[2] = (A*src[2] + B*src[3] + C*src[stride+2] + D*src[stride+3] + 32 - 4) >> 6;
-        dst[3] = (A*src[3] + B*src[4] + C*src[stride+3] + D*src[stride+4] + 32 - 4) >> 6;
-        dst[4] = (A*src[4] + B*src[5] + C*src[stride+4] + D*src[stride+5] + 32 - 4) >> 6;
-        dst[5] = (A*src[5] + B*src[6] + C*src[stride+5] + D*src[stride+6] + 32 - 4) >> 6;
-        dst[6] = (A*src[6] + B*src[7] + C*src[stride+6] + D*src[stride+7] + 32 - 4) >> 6;
-        dst[7] = (A*src[7] + B*src[8] + C*src[stride+7] + D*src[stride+8] + 32 - 4) >> 6;
-        dst+= stride;
-        src+= stride;
-    }
-}
-
-static void avg_no_rnd_vc1_chroma_mc8_c(uint8_t *dst/*align 8*/, uint8_t *src/*align 1*/, int stride, int h, int x, int y){
-    const int A=(8-x)*(8-y);
-    const int B=(  x)*(8-y);
-    const int C=(8-x)*(  y);
-    const int D=(  x)*(  y);
-    int i;
-
-    assert(x<8 && y<8 && x>=0 && y>=0);
-
-    for(i=0; i<h; i++)
-    {
-        dst[0] = avg2(dst[0], ((A*src[0] + B*src[1] + C*src[stride+0] + D*src[stride+1] + 32 - 4) >> 6));
-        dst[1] = avg2(dst[1], ((A*src[1] + B*src[2] + C*src[stride+1] + D*src[stride+2] + 32 - 4) >> 6));
-        dst[2] = avg2(dst[2], ((A*src[2] + B*src[3] + C*src[stride+2] + D*src[stride+3] + 32 - 4) >> 6));
-        dst[3] = avg2(dst[3], ((A*src[3] + B*src[4] + C*src[stride+3] + D*src[stride+4] + 32 - 4) >> 6));
-        dst[4] = avg2(dst[4], ((A*src[4] + B*src[5] + C*src[stride+4] + D*src[stride+5] + 32 - 4) >> 6));
-        dst[5] = avg2(dst[5], ((A*src[5] + B*src[6] + C*src[stride+5] + D*src[stride+6] + 32 - 4) >> 6));
-        dst[6] = avg2(dst[6], ((A*src[6] + B*src[7] + C*src[stride+6] + D*src[stride+7] + 32 - 4) >> 6));
-        dst[7] = avg2(dst[7], ((A*src[7] + B*src[8] + C*src[stride+7] + D*src[stride+8] + 32 - 4) >> 6));
-        dst+= stride;
-        src+= stride;
-    }
-}
-
 #define QPEL_MC(r, OPNAME, RND, OP) \
 static void OPNAME ## mpeg4_qpel8_h_lowpass(uint8_t *dst, uint8_t *src, int dstStride, int srcStride, int h){\
     uint8_t *cm = ff_cropTbl + MAX_NEG_CROP;\
@@ -1794,10 +1721,6 @@ static void OPNAME ## mpeg4_qpel16_v_lowpass(uint8_t *dst, uint8_t *src, int dst
     }\
 }\
 \
-static void OPNAME ## qpel8_mc00_c (uint8_t *dst, uint8_t *src, int stride){\
-    OPNAME ## pixels8_c(dst, src, stride, 8);\
-}\
-\
 static void OPNAME ## qpel8_mc10_c(uint8_t *dst, uint8_t *src, int stride){\
     uint8_t half[64];\
     put ## RND ## mpeg4_qpel8_h_lowpass(half, src, 8, stride, 8);\
@@ -1976,9 +1899,6 @@ static void OPNAME ## qpel8_mc22_c(uint8_t *dst, uint8_t *src, int stride){\
     put ## RND ## mpeg4_qpel8_h_lowpass(halfH, src, 8, stride, 9);\
     OPNAME ## mpeg4_qpel8_v_lowpass(dst, halfH, stride, 8);\
 }\
-static void OPNAME ## qpel16_mc00_c (uint8_t *dst, uint8_t *src, int stride){\
-    OPNAME ## pixels16_c(dst, src, stride, 16);\
-}\
 \
 static void OPNAME ## qpel16_mc10_c(uint8_t *dst, uint8_t *src, int stride){\
     uint8_t half[256];\
@@ -2173,6 +2093,13 @@ QPEL_MC(0, avg_       , _       , op_avg)
 #undef op_put
 #undef op_put_no_rnd
 
+#define put_qpel8_mc00_c  ff_put_pixels8x8_c
+#define avg_qpel8_mc00_c  ff_avg_pixels8x8_c
+#define put_qpel16_mc00_c ff_put_pixels16x16_c
+#define avg_qpel16_mc00_c ff_avg_pixels16x16_c
+#define put_no_rnd_qpel8_mc00_c  ff_put_pixels8x8_c
+#define put_no_rnd_qpel16_mc00_c ff_put_pixels16x16_c
+
 #if 1
 #define H264_LOWPASS(OPNAME, OP, OP2) \
 static av_unused void OPNAME ## h264_qpel2_h_lowpass(uint8_t *dst, uint8_t *src, int dstStride, int srcStride){\
@@ -2439,7 +2366,7 @@ static void OPNAME ## h264_qpel16_hv_lowpass(uint8_t *dst, int16_t *tmp, uint8_t
 }\
 
 #define H264_MC(OPNAME, SIZE) \
-static void OPNAME ## h264_qpel ## SIZE ## _mc00_c (uint8_t *dst, uint8_t *src, int stride){\
+static av_unused void OPNAME ## h264_qpel ## SIZE ## _mc00_c (uint8_t *dst, uint8_t *src, int stride){\
     OPNAME ## pixels ## SIZE ## _c(dst, src, stride, SIZE);\
 }\
 \
@@ -2597,6 +2524,11 @@ H264_MC(avg_, 16)
 #undef op2_put
 #endif
 
+#define put_h264_qpel8_mc00_c  ff_put_pixels8x8_c
+#define avg_h264_qpel8_mc00_c  ff_avg_pixels8x8_c
+#define put_h264_qpel16_mc00_c ff_put_pixels16x16_c
+#define avg_h264_qpel16_mc00_c ff_avg_pixels16x16_c
+
 static void wmv2_mspel8_h_lowpass(uint8_t *dst, uint8_t *src, int dstStride, int srcStride, int h){
     uint8_t *cm = ff_cropTbl + MAX_NEG_CROP;
     int i;
@@ -2615,31 +2547,18 @@ static void wmv2_mspel8_h_lowpass(uint8_t *dst, uint8_t *src, int dstStride, int
     }
 }
 
-#if CONFIG_CAVS_DECODER
-/* AVS specific */
-void ff_put_cavs_qpel8_mc00_c(uint8_t *dst, uint8_t *src, int stride) {
+void ff_put_pixels8x8_c(uint8_t *dst, uint8_t *src, int stride) {
     put_pixels8_c(dst, src, stride, 8);
 }
-void ff_avg_cavs_qpel8_mc00_c(uint8_t *dst, uint8_t *src, int stride) {
+void ff_avg_pixels8x8_c(uint8_t *dst, uint8_t *src, int stride) {
     avg_pixels8_c(dst, src, stride, 8);
 }
-void ff_put_cavs_qpel16_mc00_c(uint8_t *dst, uint8_t *src, int stride) {
+void ff_put_pixels16x16_c(uint8_t *dst, uint8_t *src, int stride) {
     put_pixels16_c(dst, src, stride, 16);
 }
-void ff_avg_cavs_qpel16_mc00_c(uint8_t *dst, uint8_t *src, int stride) {
+void ff_avg_pixels16x16_c(uint8_t *dst, uint8_t *src, int stride) {
     avg_pixels16_c(dst, src, stride, 16);
 }
-#endif /* CONFIG_CAVS_DECODER */
-
-#if CONFIG_VC1_DECODER
-/* VC-1 specific */
-void ff_put_vc1_mspel_mc00_c(uint8_t *dst, const uint8_t *src, int stride, int rnd) {
-    put_pixels8_c(dst, src, stride, 8);
-}
-void ff_avg_vc1_mspel_mc00_c(uint8_t *dst, const uint8_t *src, int stride, int rnd) {
-    avg_pixels8_c(dst, src, stride, 8);
-}
-#endif /* CONFIG_VC1_DECODER */
 
 #if CONFIG_RV40_DECODER
 static void put_rv40_qpel16_mc33_c(uint8_t *dst, uint8_t *src, int stride){
@@ -2685,10 +2604,6 @@ static void wmv2_mspel8_v_lowpass(uint8_t *dst, uint8_t *src, int dstStride, int
     }
 }
 
-static void put_mspel8_mc00_c (uint8_t *dst, uint8_t *src, int stride){
-    put_pixels8_c(dst, src, stride, 8);
-}
-
 static void put_mspel8_mc10_c(uint8_t *dst, uint8_t *src, int stride){
     uint8_t half[64];
     wmv2_mspel8_h_lowpass(half, src, 8, stride, 8);
@@ -3797,10 +3712,10 @@ WRAPPER8_16_SQ(quant_psnr8x8_c, quant_psnr16_c)
 WRAPPER8_16_SQ(rd8x8_c, rd16_c)
 WRAPPER8_16_SQ(bit8x8_c, bit16_c)
 
-static void vector_fmul_c(float *dst, const float *src, int len){
+static void vector_fmul_c(float *dst, const float *src0, const float *src1, int len){
     int i;
     for(i=0; i<len; i++)
-        dst[i] *= src[i];
+        dst[i] = src0[i] * src1[i];
 }
 
 static void vector_fmul_reverse_c(float *dst, const float *src0, const float *src1, int len){
@@ -3816,7 +3731,9 @@ static void vector_fmul_add_c(float *dst, const float *src0, const float *src1,
         dst[i] = src0[i] * src1[i] + src2[i];
 }
 
-void ff_vector_fmul_window_c(float *dst, const float *src0, const float *src1, const float *win, float add_bias, int len){
+static void vector_fmul_window_c(float *dst, const float *src0,
+                                 const float *src1, const float *win, int len)
+{
     int i,j;
     dst += len;
     win += len;
@@ -3826,8 +3743,8 @@ void ff_vector_fmul_window_c(float *dst, const float *src0, const float *src1, c
         float s1 = src1[j];
         float wi = win[i];
         float wj = win[j];
-        dst[i] = s0*wj - s1*wi + add_bias;
-        dst[j] = s0*wi + s1*wj + add_bias;
+        dst[i] = s0*wj - s1*wi;
+        dst[j] = s0*wi + s1*wj;
     }
 }
 
@@ -3905,18 +3822,12 @@ static float scalarproduct_float_c(const float *v1, const float *v2, int len)
     return p;
 }
 
-static void int32_to_float_fmul_scalar_c(float *dst, const int *src, float mul, int len){
-    int i;
-    for(i=0; i<len; i++)
-        dst[i] = src[i] * mul;
-}
-
 static inline uint32_t clipf_c_one(uint32_t a, uint32_t mini,
                    uint32_t maxi, uint32_t maxisign)
 {
 
     if(a > mini) return mini;
-    else if((a^(1<<31)) > maxisign) return maxi;
+    else if((a^(1U<<31)) > maxisign) return maxi;
     else return a;
 }
 
@@ -3924,7 +3835,7 @@ static void vector_clipf_c_opposite_sign(float *dst, const float *src, float *mi
     int i;
     uint32_t mini = *(uint32_t*)min;
     uint32_t maxi = *(uint32_t*)max;
-    uint32_t maxisign = maxi ^ (1<<31);
+    uint32_t maxisign = maxi ^ (1U<<31);
     uint32_t *dsti = (uint32_t*)dst;
     const uint32_t *srci = (const uint32_t*)src;
     for(i=0; i<len; i+=8) {
@@ -3956,38 +3867,7 @@ static void vector_clipf_c(float *dst, const float *src, float min, float max, i
     }
 }
 
-static av_always_inline int float_to_int16_one(const float *src){
-    int_fast32_t tmp = *(const int32_t*)src;
-    if(tmp & 0xf0000){
-        tmp = (0x43c0ffff - tmp)>>31;
-        // is this faster on some gcc/cpu combinations?
-//      if(tmp > 0x43c0ffff) tmp = 0xFFFF;
-//      else                 tmp = 0;
-    }
-    return tmp - 0x8000;
-}
-
-void ff_float_to_int16_c(int16_t *dst, const float *src, long len){
-    int i;
-    for(i=0; i<len; i++)
-        dst[i] = float_to_int16_one(src+i);
-}
-
-void ff_float_to_int16_interleave_c(int16_t *dst, const float **src, long len, int channels){
-    int i,j,c;
-    if(channels==2){
-        for(i=0; i<len; i++){
-            dst[2*i]   = float_to_int16_one(src[0]+i);
-            dst[2*i+1] = float_to_int16_one(src[1]+i);
-        }
-    }else{
-        for(c=0; c<channels; c++)
-            for(i=0, j=c; i<len; i++, j+=channels)
-                dst[j] = float_to_int16_one(src[c]+i);
-    }
-}
-
-static int32_t scalarproduct_int16_c(int16_t * v1, int16_t * v2, int order, int shift)
+static int32_t scalarproduct_int16_c(const int16_t * v1, const int16_t * v2, int order, int shift)
 {
     int res = 0;
 
@@ -3997,7 +3877,7 @@ static int32_t scalarproduct_int16_c(int16_t * v1, int16_t * v2, int order, int
     return res;
 }
 
-static int32_t scalarproduct_and_madd_int16_c(int16_t *v1, int16_t *v2, int16_t *v3, int order, int mul)
+static int32_t scalarproduct_and_madd_int16_c(int16_t *v1, const int16_t *v2, const int16_t *v3, int order, int mul)
 {
     int res = 0;
     while (order--) {
@@ -4007,6 +3887,19 @@ static int32_t scalarproduct_and_madd_int16_c(int16_t *v1, int16_t *v2, int16_t
     return res;
 }
 
+static void apply_window_int16_c(int16_t *output, const int16_t *input,
+                                 const int16_t *window, unsigned int len)
+{
+    int i;
+    int len2 = len >> 1;
+
+    for (i = 0; i < len2; i++) {
+        int16_t w       = window[i];
+        output[i]       = (MUL16(input[i],       w) + (1 << 14)) >> 15;
+        output[len-i-1] = (MUL16(input[len-i-1], w) + (1 << 14)) >> 15;
+    }
+}
+
 #define W0 2048
 #define W1 2841 /* 2048*sqrt (2)*cos (1*pi/16) */
 #define W2 2676 /* 2048*sqrt (2)*cos (2*pi/16) */
@@ -4084,22 +3977,22 @@ void ff_wmv2_idct_c(short * block){
 static void ff_wmv2_idct_put_c(uint8_t *dest, int line_size, DCTELEM *block)
 {
     ff_wmv2_idct_c(block);
-    put_pixels_clamped_c(block, dest, line_size);
+    ff_put_pixels_clamped_c(block, dest, line_size);
 }
 static void ff_wmv2_idct_add_c(uint8_t *dest, int line_size, DCTELEM *block)
 {
     ff_wmv2_idct_c(block);
-    add_pixels_clamped_c(block, dest, line_size);
+    ff_add_pixels_clamped_c(block, dest, line_size);
 }
 static void ff_jref_idct_put(uint8_t *dest, int line_size, DCTELEM *block)
 {
     j_rev_dct (block);
-    put_pixels_clamped_c(block, dest, line_size);
+    ff_put_pixels_clamped_c(block, dest, line_size);
 }
 static void ff_jref_idct_add(uint8_t *dest, int line_size, DCTELEM *block)
 {
     j_rev_dct (block);
-    add_pixels_clamped_c(block, dest, line_size);
+    ff_add_pixels_clamped_c(block, dest, line_size);
 }
 
 static void ff_jref_idct4_put(uint8_t *dest, int line_size, DCTELEM *block)
@@ -4168,7 +4061,7 @@ int ff_check_alignment(void){
                 "Compiler did not align stack variables. Libavcodec has been miscompiled\n"
                 "and may be very slow or crash. This is not a bug in libavcodec,\n"
                 "but in the compiler. You may try recompiling using gcc >= 4.2.\n"
-                "Do not report crashes to FFmpeg developers.\n");
+                "Do not report crashes to Libav developers.\n");
 #endif
             did_fail=1;
         }
@@ -4258,13 +4151,14 @@ av_cold void dsputil_init(DSPContext* c, AVCodecContext *avctx)
 
     c->get_pixels = get_pixels_c;
     c->diff_pixels = diff_pixels_c;
-    c->put_pixels_clamped = put_pixels_clamped_c;
-    c->put_signed_pixels_clamped = put_signed_pixels_clamped_c;
+    c->put_pixels_clamped = ff_put_pixels_clamped_c;
+    c->put_signed_pixels_clamped = ff_put_signed_pixels_clamped_c;
     c->put_pixels_nonclamped = put_pixels_nonclamped_c;
-    c->add_pixels_clamped = add_pixels_clamped_c;
+    c->add_pixels_clamped = ff_add_pixels_clamped_c;
     c->add_pixels8 = add_pixels8_c;
     c->add_pixels4 = add_pixels4_c;
     c->sum_abs_dctelem = sum_abs_dctelem_c;
+    c->emulated_edge_mc = ff_emulated_edge_mc;
     c->gmc1 = gmc1_c;
     c->gmc = ff_gmc_c;
     c->clear_block = clear_block_c;
@@ -4375,21 +4269,12 @@ av_cold void dsputil_init(DSPContext* c, AVCodecContext *avctx)
     c->avg_h264_chroma_pixels_tab[0]= avg_h264_chroma_mc8_c;
     c->avg_h264_chroma_pixels_tab[1]= avg_h264_chroma_mc4_c;
     c->avg_h264_chroma_pixels_tab[2]= avg_h264_chroma_mc2_c;
-    c->put_no_rnd_vc1_chroma_pixels_tab[0]= put_no_rnd_vc1_chroma_mc8_c;
-    c->avg_no_rnd_vc1_chroma_pixels_tab[0]= avg_no_rnd_vc1_chroma_mc8_c;
 
     c->draw_edges = draw_edges_c;
 
-#if CONFIG_CAVS_DECODER
-    ff_cavsdsp_init(c,avctx);
-#endif
-
 #if CONFIG_MLP_DECODER || CONFIG_TRUEHD_DECODER
     ff_mlp_init(c, avctx);
 #endif
-#if CONFIG_VC1_DECODER
-    ff_vc1dsp_init(c,avctx);
-#endif
 #if CONFIG_WMV2_DECODER || CONFIG_VC1_DECODER
     ff_intrax8dsp_init(c,avctx);
 #endif
@@ -4404,7 +4289,7 @@ av_cold void dsputil_init(DSPContext* c, AVCodecContext *avctx)
     c->avg_rv40_qpel_pixels_tab[1][15] = avg_rv40_qpel8_mc33_c;
 #endif
 
-    c->put_mspel_pixels_tab[0]= put_mspel8_mc00_c;
+    c->put_mspel_pixels_tab[0]= ff_put_pixels8x8_c;
     c->put_mspel_pixels_tab[1]= put_mspel8_mc10_c;
     c->put_mspel_pixels_tab[2]= put_mspel8_mc20_c;
     c->put_mspel_pixels_tab[3]= put_mspel8_mc30_c;
@@ -4455,6 +4340,7 @@ av_cold void dsputil_init(DSPContext* c, AVCodecContext *avctx)
     c->add_hfyu_left_prediction  = add_hfyu_left_prediction_c;
     c->add_hfyu_left_prediction_bgr32 = add_hfyu_left_prediction_bgr32_c;
     c->bswap_buf= bswap_buf;
+    c->bswap16_buf = bswap16_buf;
 #if CONFIG_PNG_DECODER
     c->add_png_paeth_prediction= ff_add_png_paeth_prediction;
 #endif
@@ -4469,9 +4355,6 @@ av_cold void dsputil_init(DSPContext* c, AVCodecContext *avctx)
         c->vp3_v_loop_filter= ff_vp3_v_loop_filter_c;
         c->vp3_idct_dc_add= ff_vp3_idct_dc_add_c;
     }
-    if (CONFIG_VP6_DECODER) {
-        c->vp6_filter_diag4= ff_vp6_filter_diag4_c;
-    }
 
     c->h261_loop_filter= h261_loop_filter_c;
 
@@ -4484,19 +4367,14 @@ av_cold void dsputil_init(DSPContext* c, AVCodecContext *avctx)
 #if CONFIG_AC3_DECODER
     c->ac3_downmix = ff_ac3_downmix_c;
 #endif
-#if CONFIG_LPC
-    c->lpc_compute_autocorr = ff_lpc_compute_autocorr;
-#endif
     c->vector_fmul = vector_fmul_c;
     c->vector_fmul_reverse = vector_fmul_reverse_c;
     c->vector_fmul_add = vector_fmul_add_c;
-    c->vector_fmul_window = ff_vector_fmul_window_c;
-    c->int32_to_float_fmul_scalar = int32_to_float_fmul_scalar_c;
+    c->vector_fmul_window = vector_fmul_window_c;
     c->vector_clipf = vector_clipf_c;
-    c->float_to_int16 = ff_float_to_int16_c;
-    c->float_to_int16_interleave = ff_float_to_int16_interleave_c;
     c->scalarproduct_int16 = scalarproduct_int16_c;
     c->scalarproduct_and_madd_int16 = scalarproduct_and_madd_int16_c;
+    c->apply_window_int16 = apply_window_int16_c;
     c->scalarproduct_float = scalarproduct_float_c;
     c->butterflies_float = butterflies_float_c;
     c->vector_fmul_scalar = vector_fmul_scalar_c;
@@ -4507,7 +4385,7 @@ av_cold void dsputil_init(DSPContext* c, AVCodecContext *avctx)
     c->sv_fmul_scalar[0] = sv_fmul_scalar_2_c;
     c->sv_fmul_scalar[1] = sv_fmul_scalar_4_c;
 
-    c->shrink[0]= ff_img_copy_plane;
+    c->shrink[0]= av_image_copy_plane;
     c->shrink[1]= ff_shrink22;
     c->shrink[2]= ff_shrink44;
     c->shrink[3]= ff_shrink88;
@@ -4534,6 +4412,16 @@ av_cold void dsputil_init(DSPContext* c, AVCodecContext *avctx)
             c->avg_2tap_qpel_pixels_tab[0][i]= c->avg_h264_qpel_pixels_tab[0][i];
     }
 
+    c->put_rv30_tpel_pixels_tab[0][0] = c->put_h264_qpel_pixels_tab[0][0];
+    c->put_rv30_tpel_pixels_tab[1][0] = c->put_h264_qpel_pixels_tab[1][0];
+    c->avg_rv30_tpel_pixels_tab[0][0] = c->avg_h264_qpel_pixels_tab[0][0];
+    c->avg_rv30_tpel_pixels_tab[1][0] = c->avg_h264_qpel_pixels_tab[1][0];
+
+    c->put_rv40_qpel_pixels_tab[0][0] = c->put_h264_qpel_pixels_tab[0][0];
+    c->put_rv40_qpel_pixels_tab[1][0] = c->put_h264_qpel_pixels_tab[1][0];
+    c->avg_rv40_qpel_pixels_tab[0][0] = c->avg_h264_qpel_pixels_tab[0][0];
+    c->avg_rv40_qpel_pixels_tab[1][0] = c->avg_h264_qpel_pixels_tab[1][0];
+
     switch(c->idct_permutation_type){
     case FF_NO_IDCT_PERM:
         for(i=0; i<64; i++)
diff --git a/libavcodec/dsputil.h b/libavcodec/dsputil.h
index fd2d07f..99b3283 100644
--- a/libavcodec/dsputil.h
+++ b/libavcodec/dsputil.h
@@ -3,20 +3,20 @@
  * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -64,10 +64,9 @@ void ff_h264_idct_add16intra_c(uint8_t *dst, const int *blockoffset, DCTELEM *bl
 void ff_h264_idct8_add4_c(uint8_t *dst, const int *blockoffset, DCTELEM *block, int stride, const uint8_t nnzc[6*8]);
 void ff_h264_idct_add8_c(uint8_t **dest, const int *blockoffset, DCTELEM *block, int stride, const uint8_t nnzc[6*8]);
 
-void ff_vector_fmul_window_c(float *dst, const float *src0, const float *src1,
-                             const float *win, float add_bias, int len);
-void ff_float_to_int16_c(int16_t *dst, const float *src, long len);
-void ff_float_to_int16_interleave_c(int16_t *dst, const float **src, long len, int channels);
+void ff_h264_luma_dc_dequant_idct_c(DCTELEM *output, DCTELEM *input, int qmul);
+void ff_svq3_luma_dc_dequant_idct_c(DCTELEM *output, DCTELEM *input, int qp);
+void ff_svq3_add_idct_c(uint8_t *dst, DCTELEM *block, int stride, int qp, int dc);
 
 /* encoding scans */
 extern const uint8_t ff_alternate_horizontal_scan[64];
@@ -82,6 +81,11 @@ extern const uint8_t ff_zigzag248_direct[64];
 extern uint32_t ff_squareTbl[512];
 extern uint8_t ff_cropTbl[256 + 2 * MAX_NEG_CROP];
 
+void ff_put_pixels8x8_c(uint8_t *dst, uint8_t *src, int stride);
+void ff_avg_pixels8x8_c(uint8_t *dst, uint8_t *src, int stride);
+void ff_put_pixels16x16_c(uint8_t *dst, uint8_t *src, int stride);
+void ff_avg_pixels16x16_c(uint8_t *dst, uint8_t *src, int stride);
+
 /* VP3 DSP functions */
 void ff_vp3_idct_c(DCTELEM *block/* align 16*/);
 void ff_vp3_idct_put_c(uint8_t *dest/*align 8*/, int line_size, DCTELEM *block/*align 16*/);
@@ -91,30 +95,23 @@ void ff_vp3_idct_dc_add_c(uint8_t *dest/*align 8*/, int line_size, const DCTELEM
 void ff_vp3_v_loop_filter_c(uint8_t *src, int stride, int *bounding_values);
 void ff_vp3_h_loop_filter_c(uint8_t *src, int stride, int *bounding_values);
 
-/* VP6 DSP functions */
-void ff_vp6_filter_diag4_c(uint8_t *dst, uint8_t *src, int stride,
-                           const int16_t *h_weights, const int16_t *v_weights);
-
 /* Bink functions */
 void ff_bink_idct_c    (DCTELEM *block);
 void ff_bink_idct_add_c(uint8_t *dest, int linesize, DCTELEM *block);
 void ff_bink_idct_put_c(uint8_t *dest, int linesize, DCTELEM *block);
 
-/* CAVS functions */
-void ff_put_cavs_qpel8_mc00_c(uint8_t *dst, uint8_t *src, int stride);
-void ff_avg_cavs_qpel8_mc00_c(uint8_t *dst, uint8_t *src, int stride);
-void ff_put_cavs_qpel16_mc00_c(uint8_t *dst, uint8_t *src, int stride);
-void ff_avg_cavs_qpel16_mc00_c(uint8_t *dst, uint8_t *src, int stride);
-
-/* VC1 functions */
-void ff_put_vc1_mspel_mc00_c(uint8_t *dst, const uint8_t *src, int stride, int rnd);
-void ff_avg_vc1_mspel_mc00_c(uint8_t *dst, const uint8_t *src, int stride, int rnd);
-
 /* EA functions */
 void ff_ea_idct_put_c(uint8_t *dest, int linesize, DCTELEM *block);
 
 /* 1/2^n downscaling functions from imgconvert.c */
+#if LIBAVCODEC_VERSION_MAJOR < 53
+/**
+ * @deprecated Use av_image_copy_plane() instead.
+ */
+attribute_deprecated
 void ff_img_copy_plane(uint8_t *dst, int dst_wrap, const uint8_t *src, int src_wrap, int width, int height);
+#endif
+
 void ff_shrink22(uint8_t *dst, int dst_wrap, const uint8_t *src, int src_wrap, int width, int height);
 void ff_shrink44(uint8_t *dst, int dst_wrap, const uint8_t *src, int src_wrap, int width, int height);
 void ff_shrink88(uint8_t *dst, int dst_wrap, const uint8_t *src, int src_wrap, int width, int height);
@@ -125,7 +122,7 @@ void ff_gmc_c(uint8_t *dst, uint8_t *src, int stride, int h, int ox, int oy,
 /* minimum alignment rules ;)
 If you notice errors in the align stuff, need more alignment for some ASM code
 for some CPU or need to use a function with less aligned data then send a mail
-to the ffmpeg-devel mailing list, ...
+to the libav-devel mailing list, ...
 
 !warning These alignments might not match reality, (missing attribute((align))
 stuff somewhere possible).
@@ -197,10 +194,14 @@ typedef struct ScanTable{
 
 void ff_init_scantable(uint8_t *, ScanTable *st, const uint8_t *src_scantable);
 
-void ff_emulated_edge_mc(uint8_t *buf, uint8_t *src, int linesize,
+void ff_emulated_edge_mc(uint8_t *buf, const uint8_t *src, int linesize,
                          int block_w, int block_h,
                          int src_x, int src_y, int w, int h);
 
+void ff_add_pixels_clamped_c(const DCTELEM *block, uint8_t *dest, int linesize);
+void ff_put_pixels_clamped_c(const DCTELEM *block, uint8_t *dest, int linesize);
+void ff_put_signed_pixels_clamped_c(const DCTELEM *block, uint8_t *dest, int linesize);
+
 /**
  * DSPContext.
  */
@@ -216,6 +217,21 @@ typedef struct DSPContext {
     void (*add_pixels4)(uint8_t *pixels, DCTELEM *block, int line_size);
     int (*sum_abs_dctelem)(DCTELEM *block/*align 16*/);
     /**
+     * Motion estimation with emulated edge values.
+     * @param buf pointer to destination buffer (unaligned)
+     * @param src pointer to pixel source (unaligned)
+     * @param linesize width (in pixels) for src/buf
+     * @param block_w number of pixels (per row) to copy to buf
+     * @param block_h nummber of pixel rows to copy to buf
+     * @param src_x offset of src to start of row - this may be negative
+     * @param src_y offset of src to top of image - this may be negative
+     * @param w width of src in pixels
+     * @param h height of src in pixels
+     */
+    void (*emulated_edge_mc)(uint8_t *buf, const uint8_t *src, int linesize,
+                             int block_w, int block_h,
+                             int src_x, int src_y, int w, int h);
+    /**
      * translational global motion compensation.
      */
     void (*gmc1)(uint8_t *dst/*align 8*/, uint8_t *src/*align 1*/, int srcStride, int h, int x16, int y16, int rounder);
@@ -329,9 +345,6 @@ typedef struct DSPContext {
      */
     h264_chroma_mc_func put_h264_chroma_pixels_tab[3];
     h264_chroma_mc_func avg_h264_chroma_pixels_tab[3];
-    /* This is really one func used in VC-1 decoding */
-    h264_chroma_mc_func put_no_rnd_vc1_chroma_pixels_tab[3];
-    h264_chroma_mc_func avg_no_rnd_vc1_chroma_pixels_tab[3];
 
     qpel_mc_func put_h264_qpel_pixels_tab[4][16];
     qpel_mc_func avg_h264_qpel_pixels_tab[4][16];
@@ -339,15 +352,6 @@ typedef struct DSPContext {
     qpel_mc_func put_2tap_qpel_pixels_tab[4][16];
     qpel_mc_func avg_2tap_qpel_pixels_tab[4][16];
 
-    /* AVS specific */
-    qpel_mc_func put_cavs_qpel_pixels_tab[2][16];
-    qpel_mc_func avg_cavs_qpel_pixels_tab[2][16];
-    void (*cavs_filter_lv)(uint8_t *pix, int stride, int alpha, int beta, int tc, int bs1, int bs2);
-    void (*cavs_filter_lh)(uint8_t *pix, int stride, int alpha, int beta, int tc, int bs1, int bs2);
-    void (*cavs_filter_cv)(uint8_t *pix, int stride, int alpha, int beta, int tc, int bs1, int bs2);
-    void (*cavs_filter_ch)(uint8_t *pix, int stride, int alpha, int beta, int tc, int bs1, int bs2);
-    void (*cavs_idct8_add)(uint8_t *dst, DCTELEM *block, int stride);
-
     me_cmp_func pix_abs[2][4];
 
     /* huffyuv specific */
@@ -365,6 +369,7 @@ typedef struct DSPContext {
     /* this might write to dst[w] */
     void (*add_png_paeth_prediction)(uint8_t *dst, uint8_t *src, uint8_t *top, int w, int bpp);
     void (*bswap_buf)(uint32_t *dst, const uint32_t *src, int w);
+    void (*bswap16_buf)(uint16_t *dst, const uint16_t *src, int len);
 
     void (*h263_v_loop_filter)(uint8_t *src, int stride, int qscale);
     void (*h263_h_loop_filter)(uint8_t *src, int stride, int qscale);
@@ -378,23 +383,17 @@ typedef struct DSPContext {
     void (*vp3_v_loop_filter)(uint8_t *src, int stride, int *bounding_values);
     void (*vp3_h_loop_filter)(uint8_t *src, int stride, int *bounding_values);
 
-    void (*vp6_filter_diag4)(uint8_t *dst, uint8_t *src, int stride,
-                             const int16_t *h_weights,const int16_t *v_weights);
-
     /* assume len is a multiple of 4, and arrays are 16-byte aligned */
     void (*vorbis_inverse_coupling)(float *mag, float *ang, int blocksize);
     void (*ac3_downmix)(float (*samples)[256], float (*matrix)[2], int out_ch, int in_ch, int len);
-    /* no alignment needed */
-    void (*lpc_compute_autocorr)(const int32_t *data, int len, int lag, double *autoc);
     /* assume len is a multiple of 8, and arrays are 16-byte aligned */
-    void (*vector_fmul)(float *dst, const float *src, int len);
+    void (*vector_fmul)(float *dst, const float *src0, const float *src1, int len);
     void (*vector_fmul_reverse)(float *dst, const float *src0, const float *src1, int len);
     /* assume len is a multiple of 8, and src arrays are 16-byte aligned */
     void (*vector_fmul_add)(float *dst, const float *src0, const float *src1, const float *src2, int len);
     /* assume len is a multiple of 4, and arrays are 16-byte aligned */
-    void (*vector_fmul_window)(float *dst, const float *src0, const float *src1, const float *win, float add_bias, int len);
+    void (*vector_fmul_window)(float *dst, const float *src0, const float *src1, const float *win, int len);
     /* assume len is a multiple of 8, and arrays are 16-byte aligned */
-    void (*int32_to_float_fmul_scalar)(float *dst, const int *src, float mul, int len);
     void (*vector_clipf)(float *dst /* align 16 */, const float *src /* align 16 */, float min, float max, int len /* align 16 */);
     /**
      * Multiply a vector of floats by a scalar float.  Source and
@@ -447,11 +446,6 @@ typedef struct DSPContext {
      */
     void (*butterflies_float)(float *restrict v1, float *restrict v2, int len);
 
-    /* C version: convert floats from the range [384.0,386.0] to ints in [-32768,32767]
-     * simd versions: convert floats from [-32768.0,32767.0] without rescaling and arrays are 16byte aligned */
-    void (*float_to_int16)(int16_t *dst, const float *src, long len);
-    void (*float_to_int16_interleave)(int16_t *dst, const float **src, long len, int channels);
-
     /* (I)DCT */
     void (*fdct)(DCTELEM *block/* align 16*/);
     void (*fdct248)(DCTELEM *block/* align 16*/);
@@ -498,8 +492,10 @@ typedef struct DSPContext {
 #define BASIS_SHIFT 16
 #define RECON_SHIFT 6
 
-    void (*draw_edges)(uint8_t *buf, int wrap, int width, int height, int w);
+    void (*draw_edges)(uint8_t *buf, int wrap, int width, int height, int w, int sides);
 #define EDGE_WIDTH 16
+#define EDGE_TOP    1
+#define EDGE_BOTTOM 2
 
     void (*prefetch)(void *mem, int stride, int h);
 
@@ -511,29 +507,6 @@ typedef struct DSPContext {
                                unsigned int filter_shift, int32_t mask, int blocksize,
                                int32_t *sample_buffer);
 
-    /* vc1 functions */
-    void (*vc1_inv_trans_8x8)(DCTELEM *b);
-    void (*vc1_inv_trans_8x4)(uint8_t *dest, int line_size, DCTELEM *block);
-    void (*vc1_inv_trans_4x8)(uint8_t *dest, int line_size, DCTELEM *block);
-    void (*vc1_inv_trans_4x4)(uint8_t *dest, int line_size, DCTELEM *block);
-    void (*vc1_inv_trans_8x8_dc)(uint8_t *dest, int line_size, DCTELEM *block);
-    void (*vc1_inv_trans_8x4_dc)(uint8_t *dest, int line_size, DCTELEM *block);
-    void (*vc1_inv_trans_4x8_dc)(uint8_t *dest, int line_size, DCTELEM *block);
-    void (*vc1_inv_trans_4x4_dc)(uint8_t *dest, int line_size, DCTELEM *block);
-    void (*vc1_v_overlap)(uint8_t* src, int stride);
-    void (*vc1_h_overlap)(uint8_t* src, int stride);
-    void (*vc1_v_loop_filter4)(uint8_t *src, int stride, int pq);
-    void (*vc1_h_loop_filter4)(uint8_t *src, int stride, int pq);
-    void (*vc1_v_loop_filter8)(uint8_t *src, int stride, int pq);
-    void (*vc1_h_loop_filter8)(uint8_t *src, int stride, int pq);
-    void (*vc1_v_loop_filter16)(uint8_t *src, int stride, int pq);
-    void (*vc1_h_loop_filter16)(uint8_t *src, int stride, int pq);
-    /* put 8x8 block with bicubic interpolation and quarterpel precision
-     * last argument is actually round value instead of height
-     */
-    op_pixels_func put_vc1_mspel_pixels_tab[16];
-    op_pixels_func avg_vc1_mspel_pixels_tab[16];
-
     /* intrax8 functions */
     void (*x8_spatial_compensation[12])(uint8_t *src , uint8_t *dst, int linesize);
     void (*x8_setup_spatial_compensation)(uint8_t *src, uint8_t *dst, int linesize,
@@ -544,14 +517,28 @@ typedef struct DSPContext {
      * @param len length of vectors, should be multiple of 16
      * @param shift number of bits to discard from product
      */
-    int32_t (*scalarproduct_int16)(int16_t *v1, int16_t *v2/*align 16*/, int len, int shift);
+    int32_t (*scalarproduct_int16)(const int16_t *v1, const int16_t *v2/*align 16*/, int len, int shift);
     /* ape functions */
     /**
      * Calculate scalar product of v1 and v2,
      * and v1[i] += v3[i] * mul
      * @param len length of vectors, should be multiple of 16
      */
-    int32_t (*scalarproduct_and_madd_int16)(int16_t *v1/*align 16*/, int16_t *v2, int16_t *v3, int len, int mul);
+    int32_t (*scalarproduct_and_madd_int16)(int16_t *v1/*align 16*/, const int16_t *v2, const int16_t *v3, int len, int mul);
+
+    /**
+     * Apply symmetric window in 16-bit fixed-point.
+     * @param output destination array
+     *               constraints: 16-byte aligned
+     * @param input  source array
+     *               constraints: 16-byte aligned
+     * @param window window array
+     *               constraints: 16-byte aligned, at least len/2 elements
+     * @param len    full window length
+     *               constraints: multiple of ? greater than zero
+     */
+    void (*apply_window_int16)(int16_t *output, const int16_t *input,
+                               const int16_t *window, unsigned int len);
 
     /* rv30 functions */
     qpel_mc_func put_rv30_tpel_pixels_tab[4][16];
@@ -624,11 +611,6 @@ static inline int get_penalty_factor(int lambda, int lambda2, int type){
  */
 #define emms_c()
 
-/* should be defined by architectures supporting
-   one or more MultiMedia extension */
-int mm_support(void);
-extern int mm_flags;
-
 void dsputil_init_alpha(DSPContext* c, AVCodecContext *avctx);
 void dsputil_init_arm(DSPContext* c, AVCodecContext *avctx);
 void dsputil_init_bfin(DSPContext* c, AVCodecContext *avctx);
@@ -640,10 +622,8 @@ void dsputil_init_sh4(DSPContext* c, AVCodecContext *avctx);
 void dsputil_init_vis(DSPContext* c, AVCodecContext *avctx);
 
 void ff_dsputil_init_dwt(DSPContext *c);
-void ff_cavsdsp_init(DSPContext* c, AVCodecContext *avctx);
 void ff_rv30dsp_init(DSPContext* c, AVCodecContext *avctx);
 void ff_rv40dsp_init(DSPContext* c, AVCodecContext *avctx);
-void ff_vc1dsp_init(DSPContext* c, AVCodecContext *avctx);
 void ff_intrax8dsp_init(DSPContext* c, AVCodecContext *avctx);
 void ff_mlp_init(DSPContext* c, AVCodecContext *avctx);
 void ff_mlp_init_x86(DSPContext* c, AVCodecContext *avctx);
@@ -657,12 +637,7 @@ static inline void emms(void)
     __asm__ volatile ("emms;":::"memory");
 }
 
-
-#define emms_c() \
-{\
-    if (mm_flags & FF_MM_MMX)\
-        emms();\
-}
+#define emms_c() emms()
 
 #elif ARCH_ARM
 
@@ -678,31 +653,30 @@ static inline void emms(void)
 
 #define STRIDE_ALIGN 16
 
-#else
-
-#define mm_flags 0
-#define mm_support() 0
-
 #endif
 
 #ifndef STRIDE_ALIGN
 #   define STRIDE_ALIGN 8
 #endif
 
-#define LOCAL_ALIGNED(a, t, v, s, ...)                          \
-    uint8_t la_##v[sizeof(t s __VA_ARGS__) + (a)];              \
-    t (*v) __VA_ARGS__ = (void *)FFALIGN((uintptr_t)la_##v, a)
+#define LOCAL_ALIGNED_A(a, t, v, s, o, ...)             \
+    uint8_t la_##v[sizeof(t s o) + (a)];                \
+    t (*v) o = (void *)FFALIGN((uintptr_t)la_##v, a)
+
+#define LOCAL_ALIGNED_D(a, t, v, s, o, ...) DECLARE_ALIGNED(a, t, v) s o
+
+#define LOCAL_ALIGNED(a, t, v, ...) LOCAL_ALIGNED_A(a, t, v, __VA_ARGS__,,)
 
 #if HAVE_LOCAL_ALIGNED_8
-#   define LOCAL_ALIGNED_8(t, v, s, ...) DECLARE_ALIGNED(8, t, v) s __VA_ARGS__
+#   define LOCAL_ALIGNED_8(t, v, ...) LOCAL_ALIGNED_D(8, t, v, __VA_ARGS__,,)
 #else
-#   define LOCAL_ALIGNED_8(t, v, s, ...) LOCAL_ALIGNED(8, t, v, s, __VA_ARGS__)
+#   define LOCAL_ALIGNED_8(t, v, ...) LOCAL_ALIGNED(8, t, v, __VA_ARGS__)
 #endif
 
 #if HAVE_LOCAL_ALIGNED_16
-#   define LOCAL_ALIGNED_16(t, v, s, ...) DECLARE_ALIGNED(16, t, v) s __VA_ARGS__
+#   define LOCAL_ALIGNED_16(t, v, ...) LOCAL_ALIGNED_D(16, t, v, __VA_ARGS__,,)
 #else
-#   define LOCAL_ALIGNED_16(t, v, s, ...) LOCAL_ALIGNED(16, t, v, s, __VA_ARGS__)
+#   define LOCAL_ALIGNED_16(t, v, ...) LOCAL_ALIGNED(16, t, v, __VA_ARGS__)
 #endif
 
 /* PSNR */
diff --git a/libavcodec/dump_extradata_bsf.c b/libavcodec/dump_extradata_bsf.c
index db26349..ba77b15 100644
--- a/libavcodec/dump_extradata_bsf.c
+++ b/libavcodec/dump_extradata_bsf.c
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -43,7 +43,7 @@ static int dump_extradata(AVBitStreamFilterContext *bsfc, AVCodecContext *avctx,
     return 0;
 }
 
-AVBitStreamFilter dump_extradata_bsf={
+AVBitStreamFilter ff_dump_extradata_bsf={
     "dump_extra",
     0,
     dump_extradata,
diff --git a/libavcodec/dv.c b/libavcodec/dv.c
index ea1f661..0b87d28 100644
--- a/libavcodec/dv.c
+++ b/libavcodec/dv.c
@@ -16,20 +16,20 @@
  * Many thanks to Dan Dennedy <dan at dennedy.org> for providing wealth
  * of DV technical info.
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -787,7 +787,7 @@ static av_always_inline int dv_init_enc_block(EncBlockInfo* bi, uint8_t *data, i
        method suggested in SMPTE 314M Table 22, and an improved
        method. The SMPTE method is very conservative; it assigns class
        3 (i.e. severe quantization) to any block where the largest AC
-       component is greater than 36. FFmpeg's DV encoder tracks AC bit
+       component is greater than 36. Libav's DV encoder tracks AC bit
        consumption precisely, so there is no need to bias most blocks
        towards strongly lossy compression. Instead, we assign class 2
        to most blocks, and use class 3 only when strictly necessary
@@ -795,7 +795,7 @@ static av_always_inline int dv_init_enc_block(EncBlockInfo* bi, uint8_t *data, i
 
 #if 0 /* SMPTE spec method */
     static const int classes[] = {12, 24, 36, 0xffff};
-#else /* improved FFmpeg method */
+#else /* improved Libav method */
     static const int classes[] = {-1, -1, 255, 0xffff};
 #endif
     int max  = classes[0];
@@ -948,7 +948,7 @@ static int dv_encode_video_segment(AVCodecContext *avctx, void *arg)
     int mb_x, mb_y, c_offset, linesize, y_stride;
     uint8_t*  y_ptr;
     uint8_t*  dif;
-    uint8_t   scratch[64];
+    LOCAL_ALIGNED_8(uint8_t, scratch, [64]);
     EncBlockInfo  enc_blks[5*DV_MAX_BPM];
     PutBitContext pbs[5*DV_MAX_BPM];
     PutBitContext* pb;
@@ -1081,6 +1081,8 @@ static int dvvideo_decode_frame(AVCodecContext *avctx,
     const uint8_t *buf = avpkt->data;
     int buf_size = avpkt->size;
     DVVideoContext *s = avctx->priv_data;
+    const uint8_t* vsc_pack;
+    int apt, is16_9;
 
     s->sys = ff_dv_frame_profile(s->sys, buf, buf_size);
     if (!s->sys || buf_size < s->sys->frame_size || dv_init_dynamic_tables(s->sys)) {
@@ -1114,6 +1116,14 @@ static int dvvideo_decode_frame(AVCodecContext *avctx,
     *data_size = sizeof(AVFrame);
     *(AVFrame*)data = s->picture;
 
+    /* Determine the codec's sample_aspect ratio from the packet */
+    vsc_pack = buf + 80*5 + 48 + 5;
+    if ( *vsc_pack == dv_video_control ) {
+        apt = buf[4] & 0x07;
+        is16_9 = (vsc_pack && ((vsc_pack[2] & 0x07) == 0x02 || (!apt && (vsc_pack[2] & 0x07) == 0x07)));
+        avctx->sample_aspect_ratio = s->sys->sar[is16_9];
+    }
+
     return s->sys->frame_size;
 }
 #endif /* CONFIG_DVVIDEO_DECODER */
@@ -1280,7 +1290,7 @@ static int dvvideo_close(AVCodecContext *c)
 
 
 #if CONFIG_DVVIDEO_ENCODER
-AVCodec dvvideo_encoder = {
+AVCodec ff_dvvideo_encoder = {
     "dvvideo",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_DVVIDEO,
@@ -1293,7 +1303,7 @@ AVCodec dvvideo_encoder = {
 #endif // CONFIG_DVVIDEO_ENCODER
 
 #if CONFIG_DVVIDEO_DECODER
-AVCodec dvvideo_decoder = {
+AVCodec ff_dvvideo_decoder = {
     "dvvideo",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_DVVIDEO,
@@ -1304,6 +1314,7 @@ AVCodec dvvideo_decoder = {
     dvvideo_decode_frame,
     CODEC_CAP_DR1,
     NULL,
+    .max_lowres = 3,
     .long_name = NULL_IF_CONFIG_SMALL("DV (Digital Video)"),
 };
 #endif
diff --git a/libavcodec/dv_tablegen.c b/libavcodec/dv_tablegen.c
index 0e2b39d..f463550 100644
--- a/libavcodec/dv_tablegen.c
+++ b/libavcodec/dv_tablegen.c
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2010 Reimar Döffinger <Reimar.Doeffinger at gmx.de>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -29,9 +29,9 @@
 #include "tableprint.h"
 #include <inttypes.h>
 
-WRITE_1D_FUNC_ARGV(vlc_pair, struct dv_vlc_pair, 7,
+WRITE_1D_FUNC_ARGV(dv_vlc_pair, 7,
                    "{0x%"PRIx32", %"PRId8"}", data[i].vlc, data[i].size)
-WRITE_2D_FUNC(vlc_pair, struct dv_vlc_pair)
+WRITE_2D_FUNC(dv_vlc_pair)
 
 int main(void)
 {
@@ -40,7 +40,7 @@ int main(void)
     write_fileheader();
 
     printf("static const struct dv_vlc_pair dv_vlc_map[DV_VLC_MAP_RUN_SIZE][DV_VLC_MAP_LEV_SIZE] = {\n");
-    write_vlc_pair_2d_array(dv_vlc_map, DV_VLC_MAP_RUN_SIZE, DV_VLC_MAP_LEV_SIZE);
+    write_dv_vlc_pair_2d_array(dv_vlc_map, DV_VLC_MAP_RUN_SIZE, DV_VLC_MAP_LEV_SIZE);
     printf("};\n");
 
     return 0;
diff --git a/libavcodec/dv_tablegen.h b/libavcodec/dv_tablegen.h
index ee6e822..0810f8e 100644
--- a/libavcodec/dv_tablegen.h
+++ b/libavcodec/dv_tablegen.h
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2010 Reimar Döffinger <Reimar.Doeffinger at gmx.de>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -35,10 +35,10 @@
 #endif
 
 /* VLC encoding lookup table */
-struct dv_vlc_pair {
+typedef struct dv_vlc_pair {
    uint32_t vlc;
    uint32_t size;
-};
+} dv_vlc_pair;
 
 #if CONFIG_HARDCODED_TABLES
 #define dv_vlc_map_tableinit()
diff --git a/libavcodec/dv_vlc_data.h b/libavcodec/dv_vlc_data.h
index c23c564..b5c1dde 100644
--- a/libavcodec/dv_vlc_data.h
+++ b/libavcodec/dv_vlc_data.h
@@ -2,20 +2,20 @@
  * VLC constants for DV codec
  * Copyright (c) 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/dvbsub.c b/libavcodec/dvbsub.c
index 0f09826..206e50e 100644
--- a/libavcodec/dvbsub.c
+++ b/libavcodec/dvbsub.c
@@ -2,25 +2,25 @@
  * DVB subtitle encoding for ffmpeg
  * Copyright (c) 2005 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #include "avcodec.h"
 #include "bytestream.h"
-#include "colorspace.h"
+#include "libavutil/colorspace.h"
 
 typedef struct DVBSubtitleContext {
     int hide_state;
@@ -223,7 +223,7 @@ static int encode_dvb_subtitles(DVBSubtitleContext *s,
     else
         page_state = 2; /* mode change */
     /* page_version = 0 + page_state */
-    *q++ = s->object_version | (page_state << 2) | 3;
+    *q++ = (s->object_version << 4) | (page_state << 2) | 3;
 
     for (region_id = 0; region_id < h->num_rects; region_id++) {
         *q++ = region_id;
@@ -402,7 +402,7 @@ static int dvbsub_encode(AVCodecContext *avctx,
     return ret;
 }
 
-AVCodec dvbsub_encoder = {
+AVCodec ff_dvbsub_encoder = {
     "dvbsub",
     AVMEDIA_TYPE_SUBTITLE,
     CODEC_ID_DVB_SUBTITLE,
diff --git a/libavcodec/dvbsub_parser.c b/libavcodec/dvbsub_parser.c
index c9ccfd0..b54aac6 100644
--- a/libavcodec/dvbsub_parser.c
+++ b/libavcodec/dvbsub_parser.c
@@ -1,21 +1,21 @@
 /*
- * DVB subtitle parser for FFmpeg
+ * DVB subtitle parser for Libav
  * Copyright (c) 2005 Ian Caulfield
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #include "avcodec.h"
@@ -55,7 +55,7 @@ static int dvbsub_parse(AVCodecParserContext *s,
     uint8_t *p, *p_end;
     int len, buf_pos = 0;
 
-    dprintf(avctx, "DVB parse packet pts=%"PRIx64", lpts=%"PRIx64", cpts=%"PRIx64":\n",
+    av_dlog(avctx, "DVB parse packet pts=%"PRIx64", lpts=%"PRIx64", cpts=%"PRIx64":\n",
             s->pts, s->last_pts, s->cur_frame_pts[s->cur_frame_start_index]);
 
 #ifdef DEBUG_PACKET_CONTENTS
@@ -82,7 +82,7 @@ static int dvbsub_parse(AVCodecParserContext *s,
     {
         if (pc->packet_index != pc->packet_start)
         {
-            dprintf(avctx, "Discarding %d bytes\n",
+            av_dlog(avctx, "Discarding %d bytes\n",
                     pc->packet_index - pc->packet_start);
         }
 
@@ -90,7 +90,7 @@ static int dvbsub_parse(AVCodecParserContext *s,
         pc->packet_index = 0;
 
         if (buf_size < 2 || buf[0] != 0x20 || buf[1] != 0x00) {
-            dprintf(avctx, "Bad packet header\n");
+            av_dlog(avctx, "Bad packet header\n");
             return -1;
         }
 
@@ -147,7 +147,7 @@ static int dvbsub_parse(AVCodecParserContext *s,
         } else if (*p == 0xff) {
             if (p + 1 < p_end)
             {
-                dprintf(avctx, "Junk at end of packet\n");
+                av_dlog(avctx, "Junk at end of packet\n");
             }
             pc->packet_index = p - pc->packet_buf;
             pc->in_packet = 0;
@@ -179,7 +179,7 @@ static av_cold void dvbsub_parse_close(AVCodecParserContext *s)
     av_freep(&pc->packet_buf);
 }
 
-AVCodecParser dvbsub_parser = {
+AVCodecParser ff_dvbsub_parser = {
     { CODEC_ID_DVB_SUBTITLE },
     sizeof(DVBSubParseContext),
     dvbsub_parse_init,
diff --git a/libavcodec/dvbsubdec.c b/libavcodec/dvbsubdec.c
index 54c74b5..2c27f6b 100644
--- a/libavcodec/dvbsubdec.c
+++ b/libavcodec/dvbsubdec.c
@@ -2,26 +2,27 @@
  * DVB subtitle decoding for ffmpeg
  * Copyright (c) 2005 Ian Caulfield
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #include "avcodec.h"
 #include "dsputil.h"
 #include "get_bits.h"
-#include "colorspace.h"
+#include "bytestream.h"
+#include "libavutil/colorspace.h"
 
 //#define DEBUG
 //#define DEBUG_PACKET_CONTENTS
@@ -31,6 +32,7 @@
 #define DVBSUB_REGION_SEGMENT   0x11
 #define DVBSUB_CLUT_SEGMENT     0x12
 #define DVBSUB_OBJECT_SEGMENT   0x13
+#define DVBSUB_DISPLAYDEFINITION_SEGMENT 0x14
 #define DVBSUB_DISPLAY_SEGMENT  0x80
 
 #define cm (ff_cropTbl + MAX_NEG_CROP)
@@ -216,6 +218,15 @@ typedef struct DVBSubRegion {
     struct DVBSubRegion *next;
 } DVBSubRegion;
 
+typedef struct DVBSubDisplayDefinition {
+    int version;
+
+    int x;
+    int y;
+    int width;
+    int height;
+} DVBSubDisplayDefinition;
+
 typedef struct DVBSubContext {
     int composition_id;
     int ancillary_id;
@@ -227,6 +238,7 @@ typedef struct DVBSubContext {
 
     int display_list_size;
     DVBSubRegionDisplay *display_list;
+    DVBSubDisplayDefinition *display_definition;
 } DVBSubContext;
 
 
@@ -320,9 +332,7 @@ static void delete_state(DVBSubContext *ctx)
         ctx->region_list = region->next;
 
         delete_region_display_list(ctx, region);
-        if (region->pbuf)
-            av_free(region->pbuf);
-
+        av_free(region->pbuf);
         av_free(region);
     }
 
@@ -334,6 +344,8 @@ static void delete_state(DVBSubContext *ctx)
         av_free(clut);
     }
 
+    av_freep(&ctx->display_definition);
+
     /* Should already be null */
     if (ctx->object_list)
         av_log(0, AV_LOG_ERROR, "Memory deallocation error!\n");
@@ -342,12 +354,16 @@ static void delete_state(DVBSubContext *ctx)
 static av_cold int dvbsub_init_decoder(AVCodecContext *avctx)
 {
     int i, r, g, b, a = 0;
-    DVBSubContext *ctx = (DVBSubContext*) avctx->priv_data;
+    DVBSubContext *ctx = avctx->priv_data;
 
-    memset(avctx->priv_data, 0, sizeof(DVBSubContext));
-
-    ctx->composition_id = avctx->sub_id & 0xffff;
-    ctx->ancillary_id = avctx->sub_id >> 16;
+    if (!avctx->extradata || avctx->extradata_size != 4) {
+        av_log(avctx, AV_LOG_WARNING, "Invalid extradata, subtitle streams may be combined!\n");
+        ctx->composition_id = -1;
+        ctx->ancillary_id   = -1;
+    } else {
+        ctx->composition_id = AV_RB16(avctx->extradata);
+        ctx->ancillary_id   = AV_RB16(avctx->extradata + 2);
+    }
 
     default_clut.id = -1;
     default_clut.next = NULL;
@@ -414,7 +430,7 @@ static av_cold int dvbsub_init_decoder(AVCodecContext *avctx)
 
 static av_cold int dvbsub_close_decoder(AVCodecContext *avctx)
 {
-    DVBSubContext *ctx = (DVBSubContext*) avctx->priv_data;
+    DVBSubContext *ctx = avctx->priv_data;
     DVBSubRegionDisplay *display;
 
     delete_state(ctx);
@@ -717,7 +733,7 @@ static int dvbsub_read_8bit_string(uint8_t *destbuf, int dbuf_len,
 static void dvbsub_parse_pixel_data_block(AVCodecContext *avctx, DVBSubObjectDisplay *display,
                                           const uint8_t *buf, int buf_size, int top_bottom, int non_mod)
 {
-    DVBSubContext *ctx = (DVBSubContext*) avctx->priv_data;
+    DVBSubContext *ctx = avctx->priv_data;
 
     DVBSubRegion *region = get_region(ctx, display->region_id);
     const uint8_t *buf_end = buf + buf_size;
@@ -731,7 +747,7 @@ static void dvbsub_parse_pixel_data_block(AVCodecContext *avctx, DVBSubObjectDis
                          0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff};
     uint8_t *map_table;
 
-    dprintf(avctx, "DVB pixel block size %d, %s field:\n", buf_size,
+    av_dlog(avctx, "DVB pixel block size %d, %s field:\n", buf_size,
             top_bottom ? "bottom" : "top");
 
 #ifdef DEBUG_PACKET_CONTENTS
@@ -776,7 +792,7 @@ static void dvbsub_parse_pixel_data_block(AVCodecContext *avctx, DVBSubObjectDis
                 map_table = NULL;
 
             x_pos += dvbsub_read_2bit_string(pbuf + (y_pos * region->width) + x_pos,
-                                                region->width - x_pos, &buf, buf_size,
+                                                region->width - x_pos, &buf, buf_end - buf,
                                                 non_mod, map_table);
             break;
         case 0x11:
@@ -791,7 +807,7 @@ static void dvbsub_parse_pixel_data_block(AVCodecContext *avctx, DVBSubObjectDis
                 map_table = NULL;
 
             x_pos += dvbsub_read_4bit_string(pbuf + (y_pos * region->width) + x_pos,
-                                                region->width - x_pos, &buf, buf_size,
+                                                region->width - x_pos, &buf, buf_end - buf,
                                                 non_mod, map_table);
             break;
         case 0x12:
@@ -801,7 +817,7 @@ static void dvbsub_parse_pixel_data_block(AVCodecContext *avctx, DVBSubObjectDis
             }
 
             x_pos += dvbsub_read_8bit_string(pbuf + (y_pos * region->width) + x_pos,
-                                                region->width - x_pos, &buf, buf_size,
+                                                region->width - x_pos, &buf, buf_end - buf,
                                                 non_mod, NULL);
             break;
 
@@ -834,7 +850,7 @@ static void dvbsub_parse_pixel_data_block(AVCodecContext *avctx, DVBSubObjectDis
 static void dvbsub_parse_object_segment(AVCodecContext *avctx,
                                         const uint8_t *buf, int buf_size)
 {
-    DVBSubContext *ctx = (DVBSubContext*) avctx->priv_data;
+    DVBSubContext *ctx = avctx->priv_data;
 
     const uint8_t *buf_end = buf + buf_size;
     const uint8_t *block;
@@ -893,7 +909,7 @@ static void dvbsub_parse_object_segment(AVCodecContext *avctx,
 static void dvbsub_parse_clut_segment(AVCodecContext *avctx,
                                         const uint8_t *buf, int buf_size)
 {
-    DVBSubContext *ctx = (DVBSubContext*) avctx->priv_data;
+    DVBSubContext *ctx = avctx->priv_data;
 
     const uint8_t *buf_end = buf + buf_size;
     int clut_id;
@@ -966,7 +982,7 @@ static void dvbsub_parse_clut_segment(AVCodecContext *avctx,
         YUV_TO_RGB1_CCIR(cb, cr);
         YUV_TO_RGB2_CCIR(r, g, b, y);
 
-        dprintf(avctx, "clut %d := (%d,%d,%d,%d)\n", entry_id, r, g, b, alpha);
+        av_dlog(avctx, "clut %d := (%d,%d,%d,%d)\n", entry_id, r, g, b, alpha);
 
         if (depth & 0x80)
             clut->clut4[entry_id] = RGBA(r,g,b,255 - alpha);
@@ -981,7 +997,7 @@ static void dvbsub_parse_clut_segment(AVCodecContext *avctx,
 static void dvbsub_parse_region_segment(AVCodecContext *avctx,
                                         const uint8_t *buf, int buf_size)
 {
-    DVBSubContext *ctx = (DVBSubContext*) avctx->priv_data;
+    DVBSubContext *ctx = avctx->priv_data;
 
     const uint8_t *buf_end = buf + buf_size;
     int region_id, object_id;
@@ -1014,8 +1030,7 @@ static void dvbsub_parse_region_segment(AVCodecContext *avctx,
     buf += 2;
 
     if (region->width * region->height != region->buf_size) {
-        if (region->pbuf)
-            av_free(region->pbuf);
+        av_free(region->pbuf);
 
         region->buf_size = region->width * region->height;
 
@@ -1042,11 +1057,11 @@ static void dvbsub_parse_region_segment(AVCodecContext *avctx,
             region->bgcolor = (((*buf++) >> 2) & 3);
     }
 
-    dprintf(avctx, "Region %d, (%dx%d)\n", region_id, region->width, region->height);
+    av_dlog(avctx, "Region %d, (%dx%d)\n", region_id, region->width, region->height);
 
     if (fill) {
         memset(region->pbuf, region->bgcolor, region->buf_size);
-        dprintf(avctx, "Fill region (%d)\n", region->bgcolor);
+        av_dlog(avctx, "Fill region (%d)\n", region->bgcolor);
     }
 
     delete_region_display_list(ctx, region);
@@ -1093,7 +1108,7 @@ static void dvbsub_parse_region_segment(AVCodecContext *avctx,
 static void dvbsub_parse_page_segment(AVCodecContext *avctx,
                                         const uint8_t *buf, int buf_size)
 {
-    DVBSubContext *ctx = (DVBSubContext*) avctx->priv_data;
+    DVBSubContext *ctx = avctx->priv_data;
     DVBSubRegionDisplay *display;
     DVBSubRegionDisplay *tmp_display_list, **tmp_ptr;
 
@@ -1107,7 +1122,7 @@ static void dvbsub_parse_page_segment(AVCodecContext *avctx,
     ctx->time_out = *buf++;
     page_state = ((*buf++) >> 2) & 3;
 
-    dprintf(avctx, "Page time out %ds, state %d\n", ctx->time_out, page_state);
+    av_dlog(avctx, "Page time out %ds, state %d\n", ctx->time_out, page_state);
 
     if (page_state == 2) {
         delete_state(ctx);
@@ -1145,7 +1160,7 @@ static void dvbsub_parse_page_segment(AVCodecContext *avctx,
         ctx->display_list = display;
         ctx->display_list_size++;
 
-        dprintf(avctx, "Region %d, (%d,%d)\n", region_id, display->x_pos, display->y_pos);
+        av_dlog(avctx, "Region %d, (%d,%d)\n", region_id, display->x_pos, display->y_pos);
     }
 
     while (tmp_display_list) {
@@ -1254,10 +1269,51 @@ static void save_display_set(DVBSubContext *ctx)
 }
 #endif
 
+static void dvbsub_parse_display_definition_segment(AVCodecContext *avctx,
+                                                    const uint8_t *buf,
+                                                    int buf_size)
+{
+    DVBSubContext *ctx = avctx->priv_data;
+    DVBSubDisplayDefinition *display_def = ctx->display_definition;
+    int dds_version, info_byte;
+
+    if (buf_size < 5)
+        return;
+
+    info_byte   = bytestream_get_byte(&buf);
+    dds_version = info_byte >> 4;
+    if (display_def && display_def->version == dds_version)
+        return; // already have this display definition version
+
+    if (!display_def) {
+        display_def             = av_mallocz(sizeof(*display_def));
+        ctx->display_definition = display_def;
+    }
+    if (!display_def)
+        return;
+
+    display_def->version = dds_version;
+    display_def->x       = 0;
+    display_def->y       = 0;
+    display_def->width   = bytestream_get_be16(&buf) + 1;
+    display_def->height  = bytestream_get_be16(&buf) + 1;
+
+    if (buf_size < 13)
+        return;
+
+    if (info_byte & 1<<3) { // display_window_flag
+        display_def->x = bytestream_get_be16(&buf);
+        display_def->y = bytestream_get_be16(&buf);
+        display_def->width  = bytestream_get_be16(&buf) - display_def->x + 1;
+        display_def->height = bytestream_get_be16(&buf) - display_def->y + 1;
+    }
+}
+
 static int dvbsub_display_end_segment(AVCodecContext *avctx, const uint8_t *buf,
                                         int buf_size, AVSubtitle *sub)
 {
-    DVBSubContext *ctx = (DVBSubContext*) avctx->priv_data;
+    DVBSubContext *ctx = avctx->priv_data;
+    DVBSubDisplayDefinition *display_def = ctx->display_definition;
 
     DVBSubRegion *region;
     DVBSubRegionDisplay *display;
@@ -1265,12 +1321,18 @@ static int dvbsub_display_end_segment(AVCodecContext *avctx, const uint8_t *buf,
     DVBSubCLUT *clut;
     uint32_t *clut_table;
     int i;
+    int offset_x=0, offset_y=0;
 
     sub->rects = NULL;
     sub->start_display_time = 0;
     sub->end_display_time = ctx->time_out * 1000;
     sub->format = 0;
 
+    if (display_def) {
+        offset_x = display_def->x;
+        offset_y = display_def->y;
+    }
+
     sub->num_rects = ctx->display_list_size;
 
     if (sub->num_rects > 0){
@@ -1288,8 +1350,8 @@ static int dvbsub_display_end_segment(AVCodecContext *avctx, const uint8_t *buf,
         if (!region)
             continue;
 
-        rect->x = display->x_pos;
-        rect->y = display->y_pos;
+        rect->x = display->x_pos + offset_x;
+        rect->y = display->y_pos + offset_y;
         rect->w = region->width;
         rect->h = region->height;
         rect->nb_colors = 16;
@@ -1338,8 +1400,8 @@ static int dvbsub_decode(AVCodecContext *avctx,
 {
     const uint8_t *buf = avpkt->data;
     int buf_size = avpkt->size;
-    DVBSubContext *ctx = (DVBSubContext*) avctx->priv_data;
-    AVSubtitle *sub = (AVSubtitle*) data;
+    DVBSubContext *ctx = avctx->priv_data;
+    AVSubtitle *sub = data;
     const uint8_t *p, *p_end;
     int segment_type;
     int page_id;
@@ -1361,13 +1423,15 @@ static int dvbsub_decode(AVCodecContext *avctx,
 
 #endif
 
-    if (buf_size <= 2)
+    if (buf_size <= 6 || *buf != 0x0f) {
+        av_dlog(avctx, "incomplete or broken packet");
         return -1;
+    }
 
     p = buf;
     p_end = buf + buf_size;
 
-    while (p < p_end && *p == 0x0f) {
+    while (p_end - p >= 6 && *p == 0x0f) {
         p += 1;
         segment_type = *p++;
         page_id = AV_RB16(p);
@@ -1375,7 +1439,13 @@ static int dvbsub_decode(AVCodecContext *avctx,
         segment_length = AV_RB16(p);
         p += 2;
 
-        if (page_id == ctx->composition_id || page_id == ctx->ancillary_id) {
+        if (p_end - p < segment_length) {
+            av_dlog(avctx, "incomplete or broken packet");
+            return -1;
+        }
+
+        if (page_id == ctx->composition_id || page_id == ctx->ancillary_id ||
+            ctx->composition_id == -1 || ctx->ancillary_id == -1) {
             switch (segment_type) {
             case DVBSUB_PAGE_SEGMENT:
                 dvbsub_parse_page_segment(avctx, p, segment_length);
@@ -1389,11 +1459,13 @@ static int dvbsub_decode(AVCodecContext *avctx,
             case DVBSUB_OBJECT_SEGMENT:
                 dvbsub_parse_object_segment(avctx, p, segment_length);
                 break;
+            case DVBSUB_DISPLAYDEFINITION_SEGMENT:
+                dvbsub_parse_display_definition_segment(avctx, p, segment_length);
             case DVBSUB_DISPLAY_SEGMENT:
                 *data_size = dvbsub_display_end_segment(avctx, p, segment_length, sub);
                 break;
             default:
-                dprintf(avctx, "Subtitling segment type 0x%x, page id %d, length %d\n",
+                av_dlog(avctx, "Subtitling segment type 0x%x, page id %d, length %d\n",
                         segment_type, page_id, segment_length);
                 break;
             }
@@ -1402,16 +1474,11 @@ static int dvbsub_decode(AVCodecContext *avctx,
         p += segment_length;
     }
 
-    if (p != p_end) {
-        dprintf(avctx, "Junk at end of packet\n");
-        return -1;
-    }
-
-    return buf_size;
+    return p - buf;
 }
 
 
-AVCodec dvbsub_decoder = {
+AVCodec ff_dvbsub_decoder = {
     "dvbsub",
     AVMEDIA_TYPE_SUBTITLE,
     CODEC_ID_DVB_SUBTITLE,
diff --git a/libavcodec/dvdata.c b/libavcodec/dvdata.c
index 7232baf..a80d2da 100644
--- a/libavcodec/dvdata.c
+++ b/libavcodec/dvdata.c
@@ -2,20 +2,20 @@
  * Constants for DV codec
  * Copyright (c) 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -52,7 +52,7 @@ static const DVprofile dv_profiles[] = {
       .ltc_divisor = 30,
       .height = 480,
       .width = 720,
-      .sar = {{10, 11}, {40, 33}},
+      .sar = {{8, 9}, {32, 27}},
       .work_chunks = &work_chunks_dv25ntsc[0],
       .idct_factor = &dv_idct_factor_sd[0],
       .pix_fmt = PIX_FMT_YUV411P,
@@ -72,7 +72,7 @@ static const DVprofile dv_profiles[] = {
       .ltc_divisor = 25,
       .height = 576,
       .width = 720,
-      .sar = {{59, 54}, {118, 81}},
+      .sar = {{16, 15}, {64, 45}},
       .work_chunks = &work_chunks_dv25pal[0],
       .idct_factor = &dv_idct_factor_sd[0],
       .pix_fmt = PIX_FMT_YUV420P,
@@ -92,7 +92,7 @@ static const DVprofile dv_profiles[] = {
       .ltc_divisor = 25,
       .height = 576,
       .width = 720,
-      .sar = {{59, 54}, {118, 81}},
+      .sar = {{16, 15}, {64, 45}},
       .work_chunks = &work_chunks_dv25pal411[0],
       .idct_factor = &dv_idct_factor_sd[0],
       .pix_fmt = PIX_FMT_YUV411P,
@@ -112,7 +112,7 @@ static const DVprofile dv_profiles[] = {
       .ltc_divisor = 30,
       .height = 480,
       .width = 720,
-      .sar = {{10, 11}, {40, 33}},
+      .sar = {{8, 9}, {32, 27}},
       .work_chunks = &work_chunks_dv50ntsc[0],
       .idct_factor = &dv_idct_factor_sd[0],
       .pix_fmt = PIX_FMT_YUV422P,
@@ -132,7 +132,7 @@ static const DVprofile dv_profiles[] = {
       .ltc_divisor = 25,
       .height = 576,
       .width = 720,
-      .sar = {{59, 54}, {118, 81}},
+      .sar = {{16, 15}, {64, 45}},
       .work_chunks = &work_chunks_dv50pal[0],
       .idct_factor = &dv_idct_factor_sd[0],
       .pix_fmt = PIX_FMT_YUV422P,
@@ -232,7 +232,7 @@ static const DVprofile dv_profiles[] = {
       .ltc_divisor = 25,
       .height = 576,
       .width = 720,
-      .sar = {{59, 54}, {118, 81}},
+      .sar = {{16, 15}, {64, 45}},
       .work_chunks = &work_chunks_dv25pal[0],
       .idct_factor = &dv_idct_factor_sd[0],
       .pix_fmt = PIX_FMT_YUV420P,
@@ -255,7 +255,7 @@ const DVprofile* ff_dv_frame_profile(const DVprofile *sys,
    int stype = frame[80*5 + 48 + 3] & 0x1f;
 
    /* 576i50 25Mbps 4:1:1 is a special case */
-   if (dsf == 1 && stype == 0 && frame[5] & 0x07) {
+   if (dsf == 1 && stype == 0 && frame[4] & 0x07 /* the APT field */) {
        return &dv_profiles[2];
    }
 
diff --git a/libavcodec/dvdata.h b/libavcodec/dvdata.h
index 90f4059..817b506 100644
--- a/libavcodec/dvdata.h
+++ b/libavcodec/dvdata.h
@@ -2,20 +2,20 @@
  * Constants for DV codec
  * Copyright (c) 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/dvdsub_parser.c b/libavcodec/dvdsub_parser.c
index 8f1b8d0..5b07de6 100644
--- a/libavcodec/dvdsub_parser.c
+++ b/libavcodec/dvdsub_parser.c
@@ -2,20 +2,20 @@
  * DVD subtitle decoding for ffmpeg
  * Copyright (c) 2005 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -76,7 +76,7 @@ static av_cold void dvdsub_parse_close(AVCodecParserContext *s)
     av_freep(&pc->packet);
 }
 
-AVCodecParser dvdsub_parser = {
+AVCodecParser ff_dvdsub_parser = {
     { CODEC_ID_DVD_SUBTITLE },
     sizeof(DVDSubParseContext),
     dvdsub_parse_init,
diff --git a/libavcodec/dvdsubdec.c b/libavcodec/dvdsubdec.c
index 75b5256..87eb53b 100644
--- a/libavcodec/dvdsubdec.c
+++ b/libavcodec/dvdsubdec.c
@@ -2,26 +2,26 @@
  * DVD subtitle decoding for ffmpeg
  * Copyright (c) 2005 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #include "avcodec.h"
 #include "get_bits.h"
-#include "colorspace.h"
 #include "dsputil.h"
+#include "libavutil/colorspace.h"
 
 //#define DEBUG
 
@@ -190,7 +190,7 @@ static int decode_dvd_subtitles(AVSubtitle *sub_header,
     while (cmd_pos > 0 && cmd_pos < buf_size - 2 - offset_size) {
         date = AV_RB16(buf + cmd_pos);
         next_cmd_pos = READ_OFFSET(buf + cmd_pos + 2);
-        dprintf(NULL, "cmd_pos=0x%04x next=0x%04x date=%d\n",
+        av_dlog(NULL, "cmd_pos=0x%04x next=0x%04x date=%d\n",
                 cmd_pos, next_cmd_pos, date);
         pos = cmd_pos + 2 + offset_size;
         offset1 = -1;
@@ -198,7 +198,7 @@ static int decode_dvd_subtitles(AVSubtitle *sub_header,
         x1 = y1 = x2 = y2 = 0;
         while (pos < buf_size) {
             cmd = buf[pos++];
-            dprintf(NULL, "cmd=%02x\n", cmd);
+            av_dlog(NULL, "cmd=%02x\n", cmd);
             switch(cmd) {
             case 0x00:
                 /* menu subpicture */
@@ -231,7 +231,7 @@ static int decode_dvd_subtitles(AVSubtitle *sub_header,
                 alpha[1] = buf[pos + 1] >> 4;
                 alpha[0] = buf[pos + 1] & 0x0f;
                 pos += 2;
-            dprintf(NULL, "alpha=%x%x%x%x\n", alpha[0],alpha[1],alpha[2],alpha[3]);
+            av_dlog(NULL, "alpha=%x%x%x%x\n", alpha[0],alpha[1],alpha[2],alpha[3]);
                 break;
             case 0x05:
             case 0x85:
@@ -243,7 +243,7 @@ static int decode_dvd_subtitles(AVSubtitle *sub_header,
                 y2 = ((buf[pos + 4] & 0x0f) << 8) | buf[pos + 5];
                 if (cmd & 0x80)
                     is_8bit = 1;
-                dprintf(NULL, "x1=%d x2=%d y1=%d y2=%d\n", x1, x2, y1, y2);
+                av_dlog(NULL, "x1=%d x2=%d y1=%d y2=%d\n", x1, x2, y1, y2);
                 pos += 6;
                 break;
             case 0x06:
@@ -251,7 +251,7 @@ static int decode_dvd_subtitles(AVSubtitle *sub_header,
                     goto fail;
                 offset1 = AV_RB16(buf + pos);
                 offset2 = AV_RB16(buf + pos + 2);
-                dprintf(NULL, "offset1=0x%04x offset2=0x%04x\n", offset1, offset2);
+                av_dlog(NULL, "offset1=0x%04x offset2=0x%04x\n", offset1, offset2);
                 pos += 4;
                 break;
             case 0x86:
@@ -259,7 +259,7 @@ static int decode_dvd_subtitles(AVSubtitle *sub_header,
                     goto fail;
                 offset1 = AV_RB32(buf + pos);
                 offset2 = AV_RB32(buf + pos + 4);
-                dprintf(NULL, "offset1=0x%04x offset2=0x%04x\n", offset1, offset2);
+                av_dlog(NULL, "offset1=0x%04x offset2=0x%04x\n", offset1, offset2);
                 pos += 8;
                 break;
 
@@ -282,7 +282,7 @@ static int decode_dvd_subtitles(AVSubtitle *sub_header,
             case 0xff:
                 goto the_end;
             default:
-                dprintf(NULL, "unrecognised subpicture command 0x%x\n", cmd);
+                av_dlog(NULL, "unrecognised subpicture command 0x%x\n", cmd);
                 goto the_end;
             }
         }
@@ -460,7 +460,7 @@ static int dvdsub_decode(AVCodecContext *avctx,
 {
     const uint8_t *buf = avpkt->data;
     int buf_size = avpkt->size;
-    AVSubtitle *sub = (void *)data;
+    AVSubtitle *sub = data;
     int is_menu;
 
     is_menu = decode_dvd_subtitles(sub, buf, buf_size);
@@ -475,7 +475,7 @@ static int dvdsub_decode(AVCodecContext *avctx,
         goto no_subtitle;
 
 #if defined(DEBUG)
-    dprintf(NULL, "start=%d ms end =%d ms\n",
+    av_dlog(NULL, "start=%d ms end =%d ms\n",
             sub->start_display_time,
             sub->end_display_time);
     ppm_save("/tmp/a.ppm", sub->rects[0]->pict.data[0],
@@ -486,7 +486,7 @@ static int dvdsub_decode(AVCodecContext *avctx,
     return buf_size;
 }
 
-AVCodec dvdsub_decoder = {
+AVCodec ff_dvdsub_decoder = {
     "dvdsub",
     AVMEDIA_TYPE_SUBTITLE,
     CODEC_ID_DVD_SUBTITLE,
diff --git a/libavcodec/dvdsubenc.c b/libavcodec/dvdsubenc.c
index 4ee0f37..71c5e79 100644
--- a/libavcodec/dvdsubenc.c
+++ b/libavcodec/dvdsubenc.c
@@ -2,20 +2,20 @@
  * DVD subtitle encoding for ffmpeg
  * Copyright (c) 2005 Wolfram Gloger
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #include "avcodec.h"
@@ -215,7 +215,7 @@ static int dvdsub_encode(AVCodecContext *avctx,
     return ret;
 }
 
-AVCodec dvdsub_encoder = {
+AVCodec ff_dvdsub_encoder = {
     "dvdsub",
     AVMEDIA_TYPE_SUBTITLE,
     CODEC_ID_DVD_SUBTITLE,
diff --git a/libavcodec/dwt.c b/libavcodec/dwt.c
index 2ecb04a..2c5b56c 100644
--- a/libavcodec/dwt.c
+++ b/libavcodec/dwt.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (C) 2004-2010 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -697,7 +697,7 @@ void ff_spatial_idwt_buffered_slice(DWTContext *dsp, DWTCompose *cs, slice_buffe
     }
 }
 
-void ff_spatial_idwt_init(DWTCompose *cs, IDWTELEM *buffer, int width, int height, int stride, int type, int decomposition_count){
+static void ff_spatial_idwt_init(DWTCompose *cs, IDWTELEM *buffer, int width, int height, int stride, int type, int decomposition_count){
     int level;
     for(level=decomposition_count-1; level>=0; level--){
         switch(type){
@@ -707,7 +707,7 @@ void ff_spatial_idwt_init(DWTCompose *cs, IDWTELEM *buffer, int width, int heigh
     }
 }
 
-void ff_spatial_idwt_slice(DWTCompose *cs, IDWTELEM *buffer, int width, int height, int stride, int type, int decomposition_count, int y){
+static void ff_spatial_idwt_slice(DWTCompose *cs, IDWTELEM *buffer, int width, int height, int stride, int type, int decomposition_count, int y){
     const int support = type==1 ? 3 : 5;
     int level;
     if(type==2) return;
diff --git a/libavcodec/dwt.h b/libavcodec/dwt.h
index 8c3aa20..fc73fe7 100644
--- a/libavcodec/dwt.h
+++ b/libavcodec/dwt.h
@@ -1,20 +1,20 @@
 /*
  * Copyright (C) 2004-2010 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -146,8 +146,6 @@ void ff_spatial_dwt(int *buffer, int width, int height, int stride, int type, in
 
 void ff_spatial_idwt_buffered_init(DWTCompose *cs, slice_buffer * sb, int width, int height, int stride_line, int type, int decomposition_count);
 void ff_spatial_idwt_buffered_slice(DWTContext *dsp, DWTCompose *cs, slice_buffer * slice_buf, int width, int height, int stride_line, int type, int decomposition_count, int y);
-void ff_spatial_idwt_init(DWTCompose *cs, IDWTELEM *buffer, int width, int height, int stride, int type, int decomposition_count);
-void ff_spatial_idwt_slice(DWTCompose *cs, IDWTELEM *buffer, int width, int height, int stride, int type, int decomposition_count, int y);
 void ff_spatial_idwt(IDWTELEM *buffer, int width, int height, int stride, int type, int decomposition_count);
 
 void ff_dwt_init(DWTContext *c);
diff --git a/libavcodec/dxa.c b/libavcodec/dxa.c
index 62e4e0a..35fd443 100644
--- a/libavcodec/dxa.c
+++ b/libavcodec/dxa.c
@@ -2,20 +2,20 @@
  * Feeble Files/ScummVM DXA decoder
  * Copyright (c) 2007 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -317,7 +317,7 @@ static av_cold int decode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec dxa_decoder = {
+AVCodec ff_dxa_decoder = {
     "dxa",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_DXA,
diff --git a/libavcodec/dxva2.c b/libavcodec/dxva2.c
index 3f14311..25b021a 100644
--- a/libavcodec/dxva2.c
+++ b/libavcodec/dxva2.c
@@ -3,20 +3,20 @@
  *
  * copyright (c) 2010 Laurent Aimar
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/dxva2.h b/libavcodec/dxva2.h
index 5c5fe21..5db5d0b 100644
--- a/libavcodec/dxva2.h
+++ b/libavcodec/dxva2.h
@@ -3,20 +3,20 @@
  *
  * copyright (c) 2009 Laurent Aimar
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -29,7 +29,7 @@
 
 /**
  * This structure is used to provides the necessary configurations and data
- * to the DXVA2 FFmpeg HWAccel implementation.
+ * to the DXVA2 Libav HWAccel implementation.
  *
  * The application must make it available as AVCodecContext.hwaccel_context.
  */
@@ -60,7 +60,7 @@ struct dxva_context {
     uint64_t workaround;
 
     /**
-     * Private to the FFmpeg AVHWAccel implementation
+     * Private to the Libav AVHWAccel implementation
      */
     unsigned report_id;
 };
diff --git a/libavcodec/dxva2_h264.c b/libavcodec/dxva2_h264.c
index 22c76df..d99bb0a 100644
--- a/libavcodec/dxva2_h264.c
+++ b/libavcodec/dxva2_h264.c
@@ -3,20 +3,20 @@
  *
  * copyright (c) 2009 Laurent Aimar
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -46,7 +46,7 @@ static void fill_picture_parameters(struct dxva_context *ctx, const H264Context
 {
     const MpegEncContext *s = &h->s;
     const Picture *current_picture = s->current_picture_ptr;
-    int i;
+    int i, j;
 
     memset(pp, 0, sizeof(*pp));
     /* Configure current picture */
@@ -56,16 +56,16 @@ static void fill_picture_parameters(struct dxva_context *ctx, const H264Context
     /* Configure the set of references */
     pp->UsedForReferenceFlags  = 0;
     pp->NonExistingFrameFlags  = 0;
-    for (i = 0; i < FF_ARRAY_ELEMS(pp->RefFrameList); i++) {
-        if (i < h->short_ref_count + h->long_ref_count) {
-            const Picture *r;
-            if (i < h->short_ref_count) {
-                r = h->short_ref[i];
-                assert(!r->long_ref);
-            } else {
-                r = h->long_ref[i - h->short_ref_count];
-                assert(r->long_ref);
-            }
+    for (i = 0, j = 0; i < FF_ARRAY_ELEMS(pp->RefFrameList); i++) {
+        const Picture *r;
+        if (j < h->short_ref_count) {
+            r = h->short_ref[j++];
+        } else {
+            r = NULL;
+            while (!r && j < h->short_ref_count + 16)
+                r = h->long_ref[j++ - h->short_ref_count];
+        }
+        if (r) {
             fill_picture_entry(&pp->RefFrameList[i],
                                ff_dxva2_get_surface_index(ctx, r),
                                r->long_ref != 0);
@@ -95,7 +95,7 @@ static void fill_picture_parameters(struct dxva_context *ctx, const H264Context
     pp->wBitFields                    = ((s->picture_structure != PICT_FRAME) <<  0) |
                                         (h->sps.mb_aff                        <<  1) |
                                         (h->sps.residual_color_transform_flag <<  2) |
-                                        /* sp_for_switch_flag (not implemented by FFmpeg) */
+                                        /* sp_for_switch_flag (not implemented by Libav) */
                                         (0                                    <<  3) |
                                         (h->sps.chroma_format_idc             <<  4) |
                                         ((h->nal_ref_idc != 0)                <<  6) |
@@ -146,8 +146,8 @@ static void fill_picture_parameters(struct dxva_context *ctx, const H264Context
     pp->deblocking_filter_control_present_flag = h->pps.deblocking_filter_parameters_present;
     pp->redundant_pic_cnt_present_flag= h->pps.redundant_pic_cnt_present;
     pp->Reserved8BitsB                = 0;
-    pp->slice_group_change_rate_minus1= 0;  /* XXX not implemented by FFmpeg */
-    //pp->SliceGroupMap[810];               /* XXX not implemented by FFmpeg */
+    pp->slice_group_change_rate_minus1= 0;  /* XXX not implemented by Libav */
+    //pp->SliceGroupMap[810];               /* XXX not implemented by Libav */
 }
 
 static void fill_scaling_lists(const H264Context *h, DXVA_Qmatrix_H264 *qm)
@@ -194,7 +194,7 @@ static void fill_slice_long(AVCodecContext *avctx, DXVA_Slice_H264_Long *slice,
 
     slice->first_mb_in_slice     = (s->mb_y >> FIELD_OR_MBAFF_PICTURE) * s->mb_width + s->mb_x;
     slice->NumMbsForSlice        = 0; /* XXX it is set once we have all slices */
-    slice->BitOffsetToSliceData  = get_bits_count(&s->gb) + 8;
+    slice->BitOffsetToSliceData  = get_bits_count(&s->gb);
     slice->slice_type            = ff_h264_get_slice_type(h);
     if (h->slice_type_fixed)
         slice->slice_type += 5;
@@ -243,7 +243,7 @@ static void fill_slice_long(AVCodecContext *avctx, DXVA_Slice_H264_Long *slice,
             }
         }
     }
-    slice->slice_qs_delta    = 0; /* XXX not implemented by FFmpeg */
+    slice->slice_qs_delta    = 0; /* XXX not implemented by Libav */
     slice->slice_qp_delta    = s->qscale - h->pps.init_qp;
     slice->redundant_pic_cnt = h->redundant_pic_count;
     if (h->slice_type == FF_B_TYPE)
@@ -423,7 +423,7 @@ static int end_frame(AVCodecContext *avctx)
                                      commit_bitstream_and_slice_buffer);
 }
 
-AVHWAccel h264_dxva2_hwaccel = {
+AVHWAccel ff_h264_dxva2_hwaccel = {
     .name           = "h264_dxva2",
     .type           = AVMEDIA_TYPE_VIDEO,
     .id             = CODEC_ID_H264,
diff --git a/libavcodec/dxva2_internal.h b/libavcodec/dxva2_internal.h
index a9be7a0..57fc7bd 100644
--- a/libavcodec/dxva2_internal.h
+++ b/libavcodec/dxva2_internal.h
@@ -3,26 +3,28 @@
  *
  * copyright (c) 2010 Laurent Aimar
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #ifndef AVCODEC_DXVA_INTERNAL_H
 #define AVCODEC_DXVA_INTERNAL_H
 
+#define _WIN32_WINNT 0x0600
+#define COBJMACROS
 #include "dxva2.h"
 #include "avcodec.h"
 #include "mpegvideo.h"
diff --git a/libavcodec/dxva2_mpeg2.c b/libavcodec/dxva2_mpeg2.c
new file mode 100644
index 0000000..6868e39
--- /dev/null
+++ b/libavcodec/dxva2_mpeg2.c
@@ -0,0 +1,274 @@
+/*
+ * MPEG-2 HW acceleration.
+ *
+ * copyright (c) 2010 Laurent Aimar
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "dxva2_internal.h"
+
+#define MAX_SLICES (SLICE_MAX_START_CODE - SLICE_MIN_START_CODE + 1)
+struct dxva2_picture_context {
+    DXVA_PictureParameters pp;
+    DXVA_QmatrixData       qm;
+    unsigned               slice_count;
+    DXVA_SliceInfo         slice[MAX_SLICES];
+
+    const uint8_t          *bitstream;
+    unsigned               bitstream_size;
+};
+
+static void fill_picture_parameters(AVCodecContext *avctx,
+                                    struct dxva_context *ctx,
+                                    const struct MpegEncContext *s,
+                                    DXVA_PictureParameters *pp)
+{
+    const Picture *current_picture = s->current_picture_ptr;
+    int is_field = s->picture_structure != PICT_FRAME;
+
+    memset(pp, 0, sizeof(*pp));
+    pp->wDecodedPictureIndex         = ff_dxva2_get_surface_index(ctx, current_picture);
+    pp->wDeblockedPictureIndex       = 0;
+    if (s->pict_type != FF_I_TYPE)
+        pp->wForwardRefPictureIndex  = ff_dxva2_get_surface_index(ctx, &s->last_picture);
+    else
+        pp->wForwardRefPictureIndex  = 0xffff;
+    if (s->pict_type == FF_B_TYPE)
+        pp->wBackwardRefPictureIndex = ff_dxva2_get_surface_index(ctx, &s->next_picture);
+    else
+        pp->wBackwardRefPictureIndex = 0xffff;
+    pp->wPicWidthInMBminus1          = s->mb_width  - 1;
+    pp->wPicHeightInMBminus1         = (s->mb_height >> is_field) - 1;
+    pp->bMacroblockWidthMinus1       = 15;
+    pp->bMacroblockHeightMinus1      = 15;
+    pp->bBlockWidthMinus1            = 7;
+    pp->bBlockHeightMinus1           = 7;
+    pp->bBPPminus1                   = 7;
+    pp->bPicStructure                = s->picture_structure;
+    pp->bSecondField                 = is_field && !s->first_field;
+    pp->bPicIntra                    = s->pict_type == FF_I_TYPE;
+    pp->bPicBackwardPrediction       = s->pict_type == FF_B_TYPE;
+    pp->bBidirectionalAveragingMode  = 0;
+    pp->bMVprecisionAndChromaRelation= 0; /* FIXME */
+    pp->bChromaFormat                = s->chroma_format;
+    pp->bPicScanFixed                = 1;
+    pp->bPicScanMethod               = s->alternate_scan ? 1 : 0;
+    pp->bPicReadbackRequests         = 0;
+    pp->bRcontrol                    = 0;
+    pp->bPicSpatialResid8            = 0;
+    pp->bPicOverflowBlocks           = 0;
+    pp->bPicExtrapolation            = 0;
+    pp->bPicDeblocked                = 0;
+    pp->bPicDeblockConfined          = 0;
+    pp->bPic4MVallowed               = 0;
+    pp->bPicOBMC                     = 0;
+    pp->bPicBinPB                    = 0;
+    pp->bMV_RPS                      = 0;
+    pp->bReservedBits                = 0;
+    pp->wBitstreamFcodes             = (s->mpeg_f_code[0][0] << 12) |
+                                       (s->mpeg_f_code[0][1] <<  8) |
+                                       (s->mpeg_f_code[1][0] <<  4) |
+                                       (s->mpeg_f_code[1][1]      );
+    pp->wBitstreamPCEelements        = (s->intra_dc_precision         << 14) |
+                                       (s->picture_structure          << 12) |
+                                       (s->top_field_first            << 11) |
+                                       (s->frame_pred_frame_dct       << 10) |
+                                       (s->concealment_motion_vectors <<  9) |
+                                       (s->q_scale_type               <<  8) |
+                                       (s->intra_vlc_format           <<  7) |
+                                       (s->alternate_scan             <<  6) |
+                                       (s->repeat_first_field         <<  5) |
+                                       (s->chroma_420_type            <<  4) |
+                                       (s->progressive_frame          <<  3);
+    pp->bBitstreamConcealmentNeed    = 0;
+    pp->bBitstreamConcealmentMethod  = 0;
+}
+
+static void fill_quantization_matrices(AVCodecContext *avctx,
+                                       struct dxva_context *ctx,
+                                       const struct MpegEncContext *s,
+                                       DXVA_QmatrixData *qm)
+{
+    int i;
+    for (i = 0; i < 4; i++)
+        qm->bNewQmatrix[i] = 1;
+    for (i = 0; i < 64; i++) {
+        int n = s->dsp.idct_permutation[ff_zigzag_direct[i]];
+        qm->Qmatrix[0][i] = s->intra_matrix[n];;
+        qm->Qmatrix[1][i] = s->inter_matrix[n];;
+        qm->Qmatrix[2][i] = s->chroma_intra_matrix[n];;
+        qm->Qmatrix[3][i] = s->chroma_inter_matrix[n];;
+    }
+}
+
+static void fill_slice(AVCodecContext *avctx,
+                       const struct MpegEncContext *s,
+                       DXVA_SliceInfo *slice,
+                       unsigned position,
+                       const uint8_t *buffer, unsigned size)
+{
+    int is_field = s->picture_structure != PICT_FRAME;
+    GetBitContext gb;
+
+    memset(slice, 0, sizeof(*slice));
+    slice->wHorizontalPosition = s->mb_x;
+    slice->wVerticalPosition   = s->mb_y >> is_field;
+    slice->dwSliceBitsInBuffer = 8 * size;
+    slice->dwSliceDataLocation = position;
+    slice->bStartCodeBitOffset = 0;
+    slice->bReservedBits       = 0;
+    /* XXX We store the index of the first MB and it will be fixed later */
+    slice->wNumberMBsInSlice   = (s->mb_y >> is_field) * s->mb_width + s->mb_x;
+    slice->wBadSliceChopping   = 0;
+
+    init_get_bits(&gb, &buffer[4], 8 * (size - 4));
+
+    slice->wQuantizerScaleCode = get_bits(&gb, 5);
+    while (get_bits1(&gb))
+        skip_bits(&gb, 8);
+
+    slice->wMBbitOffset        = 4 * 8 + get_bits_count(&gb);
+}
+static int commit_bitstream_and_slice_buffer(AVCodecContext *avctx,
+                                             DXVA2_DecodeBufferDesc *bs,
+                                             DXVA2_DecodeBufferDesc *sc)
+{
+    const struct MpegEncContext *s = avctx->priv_data;
+    struct dxva_context *ctx = avctx->hwaccel_context;
+    struct dxva2_picture_context *ctx_pic =
+        s->current_picture_ptr->hwaccel_picture_private;
+    const int is_field = s->picture_structure != PICT_FRAME;
+    const unsigned mb_count = s->mb_width * (s->mb_height >> is_field);
+    uint8_t  *dxva_data, *current, *end;
+    unsigned dxva_size;
+    unsigned i;
+
+    if (FAILED(IDirectXVideoDecoder_GetBuffer(ctx->decoder,
+                                              DXVA2_BitStreamDateBufferType,
+                                              &dxva_data, &dxva_size)))
+        return -1;
+    current = dxva_data;
+    end = dxva_data + dxva_size;
+
+    for (i = 0; i < ctx_pic->slice_count; i++) {
+        DXVA_SliceInfo *slice = &ctx_pic->slice[i];
+        unsigned position = slice->dwSliceDataLocation;
+        unsigned size     = slice->dwSliceBitsInBuffer / 8;
+        if (size > end - current) {
+            av_log(avctx, AV_LOG_ERROR, "Failed to build bitstream");
+            break;
+        }
+        slice->dwSliceDataLocation = current - dxva_data;
+
+        if (i < ctx_pic->slice_count - 1)
+            slice->wNumberMBsInSlice =
+                slice[1].wNumberMBsInSlice - slice[0].wNumberMBsInSlice;
+        else
+            slice->wNumberMBsInSlice =
+                mb_count - slice[0].wNumberMBsInSlice;
+
+        memcpy(current, &ctx_pic->bitstream[position], size);
+        current += size;
+    }
+    if (FAILED(IDirectXVideoDecoder_ReleaseBuffer(ctx->decoder,
+                                                  DXVA2_BitStreamDateBufferType)))
+        return -1;
+    if (i < ctx_pic->slice_count)
+        return -1;
+
+    memset(bs, 0, sizeof(*bs));
+    bs->CompressedBufferType = DXVA2_BitStreamDateBufferType;
+    bs->DataSize             = current - dxva_data;
+    bs->NumMBsInBuffer       = mb_count;
+
+    return ff_dxva2_commit_buffer(avctx, ctx, sc,
+                                  DXVA2_SliceControlBufferType,
+                                  ctx_pic->slice,
+                                  ctx_pic->slice_count * sizeof(*ctx_pic->slice),
+                                  mb_count);
+}
+
+static int start_frame(AVCodecContext *avctx,
+                       av_unused const uint8_t *buffer,
+                       av_unused uint32_t size)
+{
+    const struct MpegEncContext *s = avctx->priv_data;
+    struct dxva_context *ctx = avctx->hwaccel_context;
+    struct dxva2_picture_context *ctx_pic =
+        s->current_picture_ptr->hwaccel_picture_private;
+
+    if (!ctx->decoder || !ctx->cfg || ctx->surface_count <= 0)
+        return -1;
+    assert(ctx_pic);
+
+    fill_picture_parameters(avctx, ctx, s, &ctx_pic->pp);
+    fill_quantization_matrices(avctx, ctx, s, &ctx_pic->qm);
+
+    ctx_pic->slice_count    = 0;
+    ctx_pic->bitstream_size = 0;
+    ctx_pic->bitstream      = NULL;
+    return 0;
+}
+
+static int decode_slice(AVCodecContext *avctx,
+                        const uint8_t *buffer, uint32_t size)
+{
+    const struct MpegEncContext *s = avctx->priv_data;
+    struct dxva2_picture_context *ctx_pic =
+        s->current_picture_ptr->hwaccel_picture_private;
+    unsigned position;
+
+    if (ctx_pic->slice_count >= MAX_SLICES)
+        return -1;
+
+    if (!ctx_pic->bitstream)
+        ctx_pic->bitstream = buffer;
+    ctx_pic->bitstream_size += size;
+
+    position = buffer - ctx_pic->bitstream;
+    fill_slice(avctx, s, &ctx_pic->slice[ctx_pic->slice_count++], position,
+               buffer, size);
+    return 0;
+}
+
+static int end_frame(AVCodecContext *avctx)
+{
+    struct MpegEncContext *s = avctx->priv_data;
+    struct dxva2_picture_context *ctx_pic =
+        s->current_picture_ptr->hwaccel_picture_private;
+
+    if (ctx_pic->slice_count <= 0 || ctx_pic->bitstream_size <= 0)
+        return -1;
+    return ff_dxva2_common_end_frame(avctx, s,
+                                     &ctx_pic->pp, sizeof(ctx_pic->pp),
+                                     &ctx_pic->qm, sizeof(ctx_pic->qm),
+                                     commit_bitstream_and_slice_buffer);
+}
+
+AVHWAccel ff_mpeg2_dxva2_hwaccel = {
+    .name           = "mpeg2_dxva2",
+    .type           = AVMEDIA_TYPE_VIDEO,
+    .id             = CODEC_ID_MPEG2VIDEO,
+    .pix_fmt        = PIX_FMT_DXVA2_VLD,
+    .capabilities   = 0,
+    .start_frame    = start_frame,
+    .decode_slice   = decode_slice,
+    .end_frame      = end_frame,
+    .priv_data_size = sizeof(struct dxva2_picture_context),
+};
+
diff --git a/libavcodec/dxva2_vc1.c b/libavcodec/dxva2_vc1.c
index a111213..8bc84a8 100644
--- a/libavcodec/dxva2_vc1.c
+++ b/libavcodec/dxva2_vc1.c
@@ -3,20 +3,20 @@
  *
  * copyright (c) 2010 Laurent Aimar
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -264,7 +264,7 @@ static int end_frame(AVCodecContext *avctx)
 }
 
 #if CONFIG_WMV3_DXVA2_HWACCEL
-AVHWAccel wmv3_dxva2_hwaccel = {
+AVHWAccel ff_wmv3_dxva2_hwaccel = {
     .name           = "wmv3_dxva2",
     .type           = AVMEDIA_TYPE_VIDEO,
     .id             = CODEC_ID_WMV3,
@@ -277,7 +277,7 @@ AVHWAccel wmv3_dxva2_hwaccel = {
 };
 #endif
 
-AVHWAccel vc1_dxva2_hwaccel = {
+AVHWAccel ff_vc1_dxva2_hwaccel = {
     .name           = "vc1_dxva2",
     .type           = AVMEDIA_TYPE_VIDEO,
     .id             = CODEC_ID_VC1,
diff --git a/libavcodec/eac3dec.c b/libavcodec/eac3dec.c
index 52d15c8..5400768 100644
--- a/libavcodec/eac3dec.c
+++ b/libavcodec/eac3dec.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2007 Bartlomiej Wolowiec <bartek.wolowiec at gmail.com>
  * Copyright (c) 2008 Justin Ruggles
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -410,7 +410,7 @@ int ff_eac3_parse_header(AC3DecodeContext *s)
 
     /* informational metadata */
     if (get_bits1(gbc)) {
-        skip_bits(gbc, 3); // skip bit stream mode
+        s->bitstream_mode = get_bits(gbc, 3);
         skip_bits(gbc, 2); // skip copyright bit and original bitstream bit
         if (s->channel_mode == AC3_CHMODE_STEREO) {
             skip_bits(gbc, 4); // skip Dolby surround and headphone mode
diff --git a/libavcodec/eac3dec_data.c b/libavcodec/eac3dec_data.c
index 031702e..4cea26f 100644
--- a/libavcodec/eac3dec_data.c
+++ b/libavcodec/eac3dec_data.c
@@ -2,20 +2,20 @@
  * E-AC-3 decoder tables
  * Copyright (c) 2007 Bartlomiej Wolowiec <bartek.wolowiec at gmail.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/eac3dec_data.h b/libavcodec/eac3dec_data.h
index 1331833..91892a3 100644
--- a/libavcodec/eac3dec_data.h
+++ b/libavcodec/eac3dec_data.h
@@ -2,20 +2,20 @@
  * E-AC-3 decoder tables
  * Copyright (c) 2007 Bartlomiej Wolowiec <bartek.wolowiec at gmail.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/eacmv.c b/libavcodec/eacmv.c
index 517b307..d5e0f45 100644
--- a/libavcodec/eacmv.c
+++ b/libavcodec/eacmv.c
@@ -2,20 +2,20 @@
  * Electronic Arts CMV Video Decoder
  * Copyright (c) 2007-2008 Peter Ross
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
  */
 
@@ -29,6 +29,7 @@
  */
 
 #include "libavutil/intreadwrite.h"
+#include "libavutil/imgutils.h"
 #include "avcodec.h"
 
 typedef struct CmvContext {
@@ -96,9 +97,10 @@ static void cmv_decode_inter(CmvContext * s, const uint8_t *buf, const uint8_t *
             }else if(raw<buf_end) {  /* inter using second-last frame as reference */
                 int xoffset = (*raw & 0xF) - 7;
                 int yoffset = ((*raw >> 4)) - 7;
-                cmv_motcomp(s->frame.data[0], s->frame.linesize[0],
-                            s->last2_frame.data[0], s->last2_frame.linesize[0],
-                            x*4, y*4, xoffset, yoffset, s->avctx->width, s->avctx->height);
+                if (s->last2_frame.data[0])
+                    cmv_motcomp(s->frame.data[0], s->frame.linesize[0],
+                                s->last2_frame.data[0], s->last2_frame.linesize[0],
+                                x*4, y*4, xoffset, yoffset, s->avctx->width, s->avctx->height);
                 raw++;
             }
         }else{  /* inter using last frame as reference */
@@ -156,7 +158,7 @@ static int cmv_decode_frame(AVCodecContext *avctx,
         return buf_size;
     }
 
-    if (avcodec_check_dimensions(s->avctx, s->width, s->height))
+    if (av_image_check_size(s->width, s->height, 0, s->avctx))
         return -1;
 
     /* shuffle */
@@ -203,7 +205,7 @@ static av_cold int cmv_decode_end(AVCodecContext *avctx){
     return 0;
 }
 
-AVCodec eacmv_decoder = {
+AVCodec ff_eacmv_decoder = {
     "eacmv",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_CMV,
diff --git a/libavcodec/eaidct.c b/libavcodec/eaidct.c
index 9972e42..9d829c4 100644
--- a/libavcodec/eaidct.c
+++ b/libavcodec/eaidct.c
@@ -2,20 +2,20 @@
  * Electronic Arts TGQ/TQI/MAD IDCT algorithm
  * Copyright (c) 2007-2008 Peter Ross <pross at xvid.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/eamad.c b/libavcodec/eamad.c
index 8fc5ef1..db22781 100644
--- a/libavcodec/eamad.c
+++ b/libavcodec/eamad.c
@@ -2,20 +2,20 @@
  * Electronic Arts Madcow Video Decoder
  * Copyright (c) 2007-2009 Peter Ross
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
  */
 
@@ -34,6 +34,7 @@
 #include "aandcttab.h"
 #include "mpeg12.h"
 #include "mpeg12data.h"
+#include "libavutil/imgutils.h"
 
 #define EA_PREAMBLE_SIZE    8
 #define MADk_TAG MKTAG('M', 'A', 'D', 'k')    /* MAD i-frame */
@@ -53,7 +54,7 @@ static void bswap16_buf(uint16_t *dst, const uint16_t *src, int count)
 {
     int i;
     for (i=0; i<count; i++)
-        dst[i] = bswap_16(src[i]);
+        dst[i] = av_bswap16(src[i]);
 }
 
 static av_cold int decode_init(AVCodecContext *avctx)
@@ -260,7 +261,7 @@ static int decode_frame(AVCodecContext *avctx,
     buf += 16;
 
     if (avctx->width != s->width || avctx->height != s->height) {
-        if (avcodec_check_dimensions(avctx, s->width, s->height) < 0)
+        if (av_image_check_size(s->width, s->height, 0, avctx) < 0)
             return -1;
         avcodec_set_dimensions(avctx, s->width, s->height);
         if (t->frame.data[0])
@@ -305,7 +306,7 @@ static av_cold int decode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec eamad_decoder = {
+AVCodec ff_eamad_decoder = {
     "eamad",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_MAD,
diff --git a/libavcodec/eatgq.c b/libavcodec/eatgq.c
index 7a98505..6181486 100644
--- a/libavcodec/eatgq.c
+++ b/libavcodec/eatgq.c
@@ -2,20 +2,20 @@
  * Electronic Arts TGQ Video Decoder
  * Copyright (c) 2007-2008 Peter Ross <pross at xvid.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
  */
 
@@ -243,7 +243,7 @@ static av_cold int tgq_decode_end(AVCodecContext *avctx){
     return 0;
 }
 
-AVCodec eatgq_decoder = {
+AVCodec ff_eatgq_decoder = {
     "eatgq",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_TGQ,
diff --git a/libavcodec/eatgv.c b/libavcodec/eatgv.c
index 8c6a654..0404f40 100644
--- a/libavcodec/eatgv.c
+++ b/libavcodec/eatgv.c
@@ -2,20 +2,20 @@
  * Electronic Arts TGV Video Decoder
  * Copyright (c) 2007-2008 Peter Ross
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
  */
 
@@ -32,6 +32,7 @@
 #define ALT_BITSTREAM_READER_LE
 #include "get_bits.h"
 #include "libavutil/lzo.h"
+#include "libavutil/imgutils.h"
 
 #define EA_PREAMBLE_SIZE    8
 #define kVGT_TAG MKTAG('k', 'V', 'G', 'T')
@@ -275,7 +276,7 @@ static int tgv_decode_frame(AVCodecContext *avctx,
         }
     }
 
-    if (avcodec_check_dimensions(avctx, s->width, s->height))
+    if (av_image_check_size(s->width, s->height, 0, avctx))
         return -1;
 
     /* shuffle */
@@ -333,7 +334,7 @@ static av_cold int tgv_decode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec eatgv_decoder = {
+AVCodec ff_eatgv_decoder = {
     "eatgv",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_TGV,
diff --git a/libavcodec/eatqi.c b/libavcodec/eatqi.c
index 7f1901d..aa96437 100644
--- a/libavcodec/eatqi.c
+++ b/libavcodec/eatqi.c
@@ -2,20 +2,20 @@
  * Electronic Arts TQI Video Decoder
  * Copyright (c) 2007-2009 Peter Ross <pross at xvid.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
  */
 
@@ -154,7 +154,7 @@ static av_cold int tqi_decode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec eatqi_decoder = {
+AVCodec ff_eatqi_decoder = {
     "eatqi",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_TQI,
diff --git a/libavcodec/elbg.c b/libavcodec/elbg.c
index d6a4ce7..030c3a6 100644
--- a/libavcodec/elbg.c
+++ b/libavcodec/elbg.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (C) 2007 Vitor Sessak <vitor1001 at gmail.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -53,6 +53,7 @@ typedef struct{
     int *nearest_cb;
     int *points;
     AVLFG *rand_state;
+    int *scratchbuf;
 } elbg_data;
 
 static inline int distance_limited(int *a, int *b, int dim, int limit)
@@ -117,7 +118,8 @@ static int get_high_utility_cell(elbg_data *elbg)
 /**
  * Implementation of the simple LBG algorithm for just two codebooks
  */
-static int simple_lbg(int dim,
+static int simple_lbg(elbg_data *elbg,
+                      int dim,
                       int *centroid[3],
                       int newutility[3],
                       int *points,
@@ -125,10 +127,13 @@ static int simple_lbg(int dim,
 {
     int i, idx;
     int numpoints[2] = {0,0};
-    int newcentroid[2][dim];
+    int *newcentroid[2] = {
+        elbg->scratchbuf + 3*dim,
+        elbg->scratchbuf + 4*dim
+    };
     cell *tempcell;
 
-    memset(newcentroid, 0, sizeof(newcentroid));
+    memset(newcentroid[0], 0, 2 * dim * sizeof(*newcentroid[0]));
 
     newutility[0] =
     newutility[1] = 0;
@@ -158,8 +163,8 @@ static void get_new_centroids(elbg_data *elbg, int huc, int *newcentroid_i,
                               int *newcentroid_p)
 {
     cell *tempcell;
-    int min[elbg->dim];
-    int max[elbg->dim];
+    int *min = newcentroid_i;
+    int *max = newcentroid_p;
     int i;
 
     for (i=0; i< elbg->dim; i++) {
@@ -174,8 +179,10 @@ static void get_new_centroids(elbg_data *elbg, int huc, int *newcentroid_i,
         }
 
     for (i=0; i<elbg->dim; i++) {
-        newcentroid_i[i] = min[i] + (max[i] - min[i])/3;
-        newcentroid_p[i] = min[i] + (2*(max[i] - min[i]))/3;
+        int ni = min[i] + (max[i] - min[i])/3;
+        int np = min[i] + (2*(max[i] - min[i]))/3;
+        newcentroid_i[i] = ni;
+        newcentroid_p[i] = np;
     }
 }
 
@@ -242,20 +249,19 @@ static void update_utility_and_n_cb(elbg_data *elbg, int idx, int newutility)
  * and update elbg->error, elbg->utility and elbg->nearest_cb.
  *
  * @param elbg  Internal elbg data
- * @param indexes      {luc (low utility cell, huc (high utility cell), cluc (closest cell to low utility cell)}
+ * @param idx   {luc (low utility cell, huc (high utility cell), cluc (closest cell to low utility cell)}
  */
 static void try_shift_candidate(elbg_data *elbg, int idx[3])
 {
     int j, k, olderror=0, newerror, cont=0;
     int newutility[3];
-    int newcentroid[3][elbg->dim];
-    int *newcentroid_ptrs[3];
+    int *newcentroid[3] = {
+        elbg->scratchbuf,
+        elbg->scratchbuf + elbg->dim,
+        elbg->scratchbuf + 2*elbg->dim
+    };
     cell *tempcell;
 
-    newcentroid_ptrs[0] = newcentroid[0];
-    newcentroid_ptrs[1] = newcentroid[1];
-    newcentroid_ptrs[2] = newcentroid[2];
-
     for (j=0; j<3; j++)
         olderror += elbg->utility[idx[j]];
 
@@ -277,11 +283,11 @@ static void try_shift_candidate(elbg_data *elbg, int idx[3])
 
     newerror = newutility[2];
 
-    newerror += simple_lbg(elbg->dim, newcentroid_ptrs, newutility, elbg->points,
+    newerror += simple_lbg(elbg, elbg->dim, newcentroid, newutility, elbg->points,
                            elbg->cells[idx[1]]);
 
     if (olderror > newerror) {
-        shift_codebook(elbg, idx, newcentroid_ptrs);
+        shift_codebook(elbg, idx, newcentroid);
 
         elbg->error += newerror - olderror;
 
@@ -366,6 +372,7 @@ void ff_do_elbg(int *points, int dim, int numpoints, int *codebook,
     elbg->nearest_cb = closest_cb;
     elbg->points = points;
     elbg->utility_inc = av_malloc(numCB*sizeof(int));
+    elbg->scratchbuf = av_malloc(5*dim*sizeof(int));
 
     elbg->rand_state = rand_state;
 
@@ -425,4 +432,5 @@ void ff_do_elbg(int *points, int dim, int numpoints, int *codebook,
     av_free(list_buffer);
     av_free(elbg->cells);
     av_free(elbg->utility_inc);
+    av_free(elbg->scratchbuf);
 }
diff --git a/libavcodec/elbg.h b/libavcodec/elbg.h
index e6f577e..b8ea489 100644
--- a/libavcodec/elbg.h
+++ b/libavcodec/elbg.h
@@ -1,20 +1,20 @@
 /*
  * Copyright (C) 2007 Vitor Sessak <vitor1001 at gmail.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/error_resilience.c b/libavcodec/error_resilience.c
index dc015b9..d4d5839 100644
--- a/libavcodec/error_resilience.c
+++ b/libavcodec/error_resilience.c
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/escape124.c b/libavcodec/escape124.c
index b51206a..9d216a4 100644
--- a/libavcodec/escape124.c
+++ b/libavcodec/escape124.c
@@ -2,20 +2,20 @@
  * Escape 124 Video Decoder
  * Copyright (C) 2008 Eli Friedman (eli.friedman at gmail.com)
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -195,15 +195,6 @@ static const uint16_t mask_matrix[] = {0x1,   0x2,   0x10,   0x20,
                                        0x100, 0x200, 0x1000, 0x2000,
                                        0x400, 0x800, 0x4000, 0x8000};
 
-/**
- * Decode a single frame
- * @param avctx decoder context
- * @param data decoded frame
- * @param data_size size of the decoded frame
- * @param buf input buffer
- * @param buf_size input buffer size
- * @return 0 success, -1 on error
- */
 static int escape124_decode_frame(AVCodecContext *avctx,
                                   void *data, int *data_size,
                                   AVPacket *avpkt)
@@ -372,7 +363,7 @@ static int escape124_decode_frame(AVCodecContext *avctx,
 }
 
 
-AVCodec escape124_decoder = {
+AVCodec ff_escape124_decoder = {
     "escape124",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_ESCAPE124,
diff --git a/libavcodec/eval.c b/libavcodec/eval.c
deleted file mode 100644
index ce4d0f5..0000000
--- a/libavcodec/eval.c
+++ /dev/null
@@ -1,451 +0,0 @@
-/*
- * Copyright (c) 2002-2006 Michael Niedermayer <michaelni at gmx.at>
- * Copyright (c) 2006 Oded Shimon <ods15 at ods15.dyndns.org>
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-/**
- * @file
- * simple arithmetic expression evaluator.
- *
- * see http://joe.hotchkiss.com/programming/eval/eval.html
- */
-
-#include "libavutil/avutil.h"
-#include "eval.h"
-
-typedef struct Parser{
-    int stack_index;
-    char *s;
-    const double *const_value;
-    const char * const *const_name;          // NULL terminated
-    double (* const *func1)(void *, double a);           // NULL terminated
-    const char * const *func1_name;          // NULL terminated
-    double (* const *func2)(void *, double a, double b); // NULL terminated
-    const char * const *func2_name;          // NULL terminated
-    void *opaque;
-    const char **error;
-#define VARS 10
-    double var[VARS];
-} Parser;
-
-static const int8_t si_prefixes['z' - 'E' + 1]={
-    ['y'-'E']= -24,
-    ['z'-'E']= -21,
-    ['a'-'E']= -18,
-    ['f'-'E']= -15,
-    ['p'-'E']= -12,
-    ['n'-'E']= - 9,
-    ['u'-'E']= - 6,
-    ['m'-'E']= - 3,
-    ['c'-'E']= - 2,
-    ['d'-'E']= - 1,
-    ['h'-'E']=   2,
-    ['k'-'E']=   3,
-    ['K'-'E']=   3,
-    ['M'-'E']=   6,
-    ['G'-'E']=   9,
-    ['T'-'E']=  12,
-    ['P'-'E']=  15,
-    ['E'-'E']=  18,
-    ['Z'-'E']=  21,
-    ['Y'-'E']=  24,
-};
-
-double av_strtod(const char *numstr, char **tail) {
-    double d;
-    char *next;
-    d = strtod(numstr, &next);
-    /* if parsing succeeded, check for and interpret postfixes */
-    if (next!=numstr) {
-
-        if(*next >= 'E' && *next <= 'z'){
-            int e= si_prefixes[*next - 'E'];
-            if(e){
-                if(next[1] == 'i'){
-                    d*= pow( 2, e/0.3);
-                    next+=2;
-                }else{
-                    d*= pow(10, e);
-                    next++;
-                }
-            }
-        }
-
-        if(*next=='B') {
-            d*=8;
-            next++;
-        }
-    }
-    /* if requested, fill in tail with the position after the last parsed
-       character */
-    if (tail)
-        *tail = next;
-    return d;
-}
-
-static int strmatch(const char *s, const char *prefix){
-    int i;
-    for(i=0; prefix[i]; i++){
-        if(prefix[i] != s[i]) return 0;
-    }
-    return 1;
-}
-
-struct AVExpr {
-    enum {
-        e_value, e_const, e_func0, e_func1, e_func2,
-        e_squish, e_gauss, e_ld,
-        e_mod, e_max, e_min, e_eq, e_gt, e_gte,
-        e_pow, e_mul, e_div, e_add,
-        e_last, e_st, e_while,
-    } type;
-    double value; // is sign in other types
-    union {
-        int const_index;
-        double (*func0)(double);
-        double (*func1)(void *, double);
-        double (*func2)(void *, double, double);
-    } a;
-    struct AVExpr *param[2];
-};
-
-static double eval_expr(Parser * p, AVExpr * e) {
-    switch (e->type) {
-        case e_value:  return e->value;
-        case e_const:  return e->value * p->const_value[e->a.const_index];
-        case e_func0:  return e->value * e->a.func0(eval_expr(p, e->param[0]));
-        case e_func1:  return e->value * e->a.func1(p->opaque, eval_expr(p, e->param[0]));
-        case e_func2:  return e->value * e->a.func2(p->opaque, eval_expr(p, e->param[0]), eval_expr(p, e->param[1]));
-        case e_squish: return 1/(1+exp(4*eval_expr(p, e->param[0])));
-        case e_gauss: { double d = eval_expr(p, e->param[0]); return exp(-d*d/2)/sqrt(2*M_PI); }
-        case e_ld:     return e->value * p->var[av_clip(eval_expr(p, e->param[0]), 0, VARS-1)];
-        case e_while: {
-            double d = NAN;
-            while(eval_expr(p, e->param[0]))
-                d=eval_expr(p, e->param[1]);
-            return d;
-        }
-        default: {
-            double d = eval_expr(p, e->param[0]);
-            double d2 = eval_expr(p, e->param[1]);
-            switch (e->type) {
-                case e_mod: return e->value * (d - floor(d/d2)*d2);
-                case e_max: return e->value * (d >  d2 ?   d : d2);
-                case e_min: return e->value * (d <  d2 ?   d : d2);
-                case e_eq:  return e->value * (d == d2 ? 1.0 : 0.0);
-                case e_gt:  return e->value * (d >  d2 ? 1.0 : 0.0);
-                case e_gte: return e->value * (d >= d2 ? 1.0 : 0.0);
-                case e_pow: return e->value * pow(d, d2);
-                case e_mul: return e->value * (d * d2);
-                case e_div: return e->value * (d / d2);
-                case e_add: return e->value * (d + d2);
-                case e_last:return e->value * d2;
-                case e_st : return e->value * (p->var[av_clip(d, 0, VARS-1)]= d2);
-            }
-        }
-    }
-    return NAN;
-}
-
-static AVExpr * parse_expr(Parser *p);
-
-void ff_free_expr(AVExpr * e) {
-    if (!e) return;
-    ff_free_expr(e->param[0]);
-    ff_free_expr(e->param[1]);
-    av_freep(&e);
-}
-
-static AVExpr * parse_primary(Parser *p) {
-    AVExpr * d = av_mallocz(sizeof(AVExpr));
-    char *next= p->s;
-    int i;
-
-    if (!d)
-        return NULL;
-
-    /* number */
-    d->value = av_strtod(p->s, &next);
-    if(next != p->s){
-        d->type = e_value;
-        p->s= next;
-        return d;
-    }
-    d->value = 1;
-
-    /* named constants */
-    for(i=0; p->const_name && p->const_name[i]; i++){
-        if(strmatch(p->s, p->const_name[i])){
-            p->s+= strlen(p->const_name[i]);
-            d->type = e_const;
-            d->a.const_index = i;
-            return d;
-        }
-    }
-
-    p->s= strchr(p->s, '(');
-    if(p->s==NULL){
-        *p->error = "undefined constant or missing (";
-        p->s= next;
-        ff_free_expr(d);
-        return NULL;
-    }
-    p->s++; // "("
-    if (*next == '(') { // special case do-nothing
-        av_freep(&d);
-        d = parse_expr(p);
-        if(p->s[0] != ')'){
-            *p->error = "missing )";
-            ff_free_expr(d);
-            return NULL;
-        }
-        p->s++; // ")"
-        return d;
-    }
-    d->param[0] = parse_expr(p);
-    if(p->s[0]== ','){
-        p->s++; // ","
-        d->param[1] = parse_expr(p);
-    }
-    if(p->s[0] != ')'){
-        *p->error = "missing )";
-        ff_free_expr(d);
-        return NULL;
-    }
-    p->s++; // ")"
-
-    d->type = e_func0;
-         if( strmatch(next, "sinh"  ) ) d->a.func0 = sinh;
-    else if( strmatch(next, "cosh"  ) ) d->a.func0 = cosh;
-    else if( strmatch(next, "tanh"  ) ) d->a.func0 = tanh;
-    else if( strmatch(next, "sin"   ) ) d->a.func0 = sin;
-    else if( strmatch(next, "cos"   ) ) d->a.func0 = cos;
-    else if( strmatch(next, "tan"   ) ) d->a.func0 = tan;
-    else if( strmatch(next, "atan"  ) ) d->a.func0 = atan;
-    else if( strmatch(next, "asin"  ) ) d->a.func0 = asin;
-    else if( strmatch(next, "acos"  ) ) d->a.func0 = acos;
-    else if( strmatch(next, "exp"   ) ) d->a.func0 = exp;
-    else if( strmatch(next, "log"   ) ) d->a.func0 = log;
-    else if( strmatch(next, "abs"   ) ) d->a.func0 = fabs;
-    else if( strmatch(next, "squish") ) d->type = e_squish;
-    else if( strmatch(next, "gauss" ) ) d->type = e_gauss;
-    else if( strmatch(next, "mod"   ) ) d->type = e_mod;
-    else if( strmatch(next, "max"   ) ) d->type = e_max;
-    else if( strmatch(next, "min"   ) ) d->type = e_min;
-    else if( strmatch(next, "eq"    ) ) d->type = e_eq;
-    else if( strmatch(next, "gte"   ) ) d->type = e_gte;
-    else if( strmatch(next, "gt"    ) ) d->type = e_gt;
-    else if( strmatch(next, "lte"   ) ) { AVExpr * tmp = d->param[1]; d->param[1] = d->param[0]; d->param[0] = tmp; d->type = e_gt; }
-    else if( strmatch(next, "lt"    ) ) { AVExpr * tmp = d->param[1]; d->param[1] = d->param[0]; d->param[0] = tmp; d->type = e_gte; }
-    else if( strmatch(next, "ld"    ) ) d->type = e_ld;
-    else if( strmatch(next, "st"    ) ) d->type = e_st;
-    else if( strmatch(next, "while" ) ) d->type = e_while;
-    else {
-        for(i=0; p->func1_name && p->func1_name[i]; i++){
-            if(strmatch(next, p->func1_name[i])){
-                d->a.func1 = p->func1[i];
-                d->type = e_func1;
-                return d;
-            }
-        }
-
-        for(i=0; p->func2_name && p->func2_name[i]; i++){
-            if(strmatch(next, p->func2_name[i])){
-                d->a.func2 = p->func2[i];
-                d->type = e_func2;
-                return d;
-            }
-        }
-
-        *p->error = "unknown function";
-        ff_free_expr(d);
-        return NULL;
-    }
-
-    return d;
-}
-
-static AVExpr * new_eval_expr(int type, int value, AVExpr *p0, AVExpr *p1){
-    AVExpr * e = av_mallocz(sizeof(AVExpr));
-    if (!e)
-        return NULL;
-    e->type     =type   ;
-    e->value    =value  ;
-    e->param[0] =p0     ;
-    e->param[1] =p1     ;
-    return e;
-}
-
-static AVExpr * parse_pow(Parser *p, int *sign){
-    *sign= (*p->s == '+') - (*p->s == '-');
-    p->s += *sign&1;
-    return parse_primary(p);
-}
-
-static AVExpr * parse_factor(Parser *p){
-    int sign, sign2;
-    AVExpr * e = parse_pow(p, &sign);
-    while(p->s[0]=='^'){
-        p->s++;
-        e= new_eval_expr(e_pow, 1, e, parse_pow(p, &sign2));
-        if (!e)
-            return NULL;
-        if (e->param[1]) e->param[1]->value *= (sign2|1);
-    }
-    if (e) e->value *= (sign|1);
-    return e;
-}
-
-static AVExpr * parse_term(Parser *p){
-    AVExpr * e = parse_factor(p);
-    while(p->s[0]=='*' || p->s[0]=='/'){
-        int c= *p->s++;
-        e= new_eval_expr(c == '*' ? e_mul : e_div, 1, e, parse_factor(p));
-        if (!e)
-            return NULL;
-    }
-    return e;
-}
-
-static AVExpr * parse_subexpr(Parser *p) {
-    AVExpr * e = parse_term(p);
-    while(*p->s == '+' || *p->s == '-') {
-        e= new_eval_expr(e_add, 1, e, parse_term(p));
-        if (!e)
-            return NULL;
-    };
-
-    return e;
-}
-
-static AVExpr * parse_expr(Parser *p) {
-    AVExpr * e;
-
-    if(p->stack_index <= 0) //protect against stack overflows
-        return NULL;
-    p->stack_index--;
-
-    e = parse_subexpr(p);
-
-    while(*p->s == ';') {
-        p->s++;
-        e= new_eval_expr(e_last, 1, e, parse_subexpr(p));
-        if (!e)
-            return NULL;
-    };
-
-    p->stack_index++;
-
-    return e;
-}
-
-static int verify_expr(AVExpr * e) {
-    if (!e) return 0;
-    switch (e->type) {
-        case e_value:
-        case e_const: return 1;
-        case e_func0:
-        case e_func1:
-        case e_squish:
-        case e_ld:
-        case e_gauss: return verify_expr(e->param[0]);
-        default: return verify_expr(e->param[0]) && verify_expr(e->param[1]);
-    }
-}
-
-AVExpr *ff_parse_expr(const char *s, const char * const *const_name,
-               double (* const *func1)(void *, double), const char * const *func1_name,
-               double (* const *func2)(void *, double, double), const char * const *func2_name,
-               const char **error){
-    Parser p;
-    AVExpr *e = NULL;
-    char *w = av_malloc(strlen(s) + 1);
-    char *wp = w;
-
-    if (!w)
-        goto end;
-
-    while (*s)
-        if (!isspace(*s++)) *wp++ = s[-1];
-    *wp++ = 0;
-
-    p.stack_index=100;
-    p.s= w;
-    p.const_name = const_name;
-    p.func1      = func1;
-    p.func1_name = func1_name;
-    p.func2      = func2;
-    p.func2_name = func2_name;
-    p.error= error;
-
-    e = parse_expr(&p);
-    if (!verify_expr(e)) {
-        ff_free_expr(e);
-        e = NULL;
-    }
-end:
-    av_free(w);
-    return e;
-}
-
-double ff_eval_expr(AVExpr * e, const double *const_value, void *opaque) {
-    Parser p;
-
-    p.const_value= const_value;
-    p.opaque     = opaque;
-    return eval_expr(&p, e);
-}
-
-double ff_parse_and_eval_expr(const char *s, const double *const_value, const char * const *const_name,
-               double (* const *func1)(void *, double), const char * const *func1_name,
-               double (* const *func2)(void *, double, double), const char * const *func2_name,
-               void *opaque, const char **error){
-    AVExpr * e = ff_parse_expr(s, const_name, func1, func1_name, func2, func2_name, error);
-    double d;
-    if (!e) return NAN;
-    d = ff_eval_expr(e, const_value, opaque);
-    ff_free_expr(e);
-    return d;
-}
-
-#ifdef TEST
-#undef printf
-static double const_values[]={
-    M_PI,
-    M_E,
-    0
-};
-static const char *const_names[]={
-    "PI",
-    "E",
-    0
-};
-int main(void){
-    int i;
-    printf("%f == 12.7\n", ff_parse_and_eval_expr("1+(5-2)^(3-1)+1/2+sin(PI)-max(-2.2,-3.1)", const_values, const_names, NULL, NULL, NULL, NULL, NULL, NULL));
-    printf("%f == 0.931322575\n", ff_parse_and_eval_expr("80G/80Gi", const_values, const_names, NULL, NULL, NULL, NULL, NULL, NULL));
-
-    for(i=0; i<1050; i++){
-        START_TIMER
-            ff_parse_and_eval_expr("1+(5-2)^(3-1)+1/2+sin(PI)-max(-2.2,-3.1)", const_values, const_names, NULL, NULL, NULL, NULL, NULL, NULL);
-        STOP_TIMER("ff_parse_and_eval_expr")
-    }
-    return 0;
-}
-#endif
diff --git a/libavcodec/eval.h b/libavcodec/eval.h
deleted file mode 100644
index 50c16af..0000000
--- a/libavcodec/eval.h
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * Copyright (c) 2002 Michael Niedermayer <michaelni at gmx.at>
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-/**
- * @file
- * simple arithmetic expression evaluator
- */
-
-#ifndef AVCODEC_EVAL_H
-#define AVCODEC_EVAL_H
-
-typedef struct AVExpr AVExpr;
-
-/**
- * Parses and evaluates an expression.
- * Note, this is significantly slower than ff_eval_expr().
- *
- * @param s expression as a zero terminated string for example "1+2^3+5*5+sin(2/3)"
- * @param func1 NULL terminated array of function pointers for functions which take 1 argument
- * @param func2 NULL terminated array of function pointers for functions which take 2 arguments
- * @param const_name NULL terminated array of zero terminated strings of constant identifers for example {"PI", "E", 0}
- * @param func1_name NULL terminated array of zero terminated strings of func1 identifers
- * @param func2_name NULL terminated array of zero terminated strings of func2 identifers
- * @param error pointer to a char* which is set to an error message if something goes wrong
- * @param const_value a zero terminated array of values for the identifers from const_name
- * @param opaque a pointer which will be passed to all functions from func1 and func2
- * @return the value of the expression
- */
-double ff_parse_and_eval_expr(const char *s, const double *const_value, const char * const *const_name,
-               double (* const *func1)(void *, double), const char * const *func1_name,
-               double (* const *func2)(void *, double, double), const char * const *func2_name,
-               void *opaque, const char **error);
-
-/**
- * Parses an expression.
- *
- * @param s expression as a zero terminated string for example "1+2^3+5*5+sin(2/3)"
- * @param func1 NULL terminated array of function pointers for functions which take 1 argument
- * @param func2 NULL terminated array of function pointers for functions which take 2 arguments
- * @param const_name NULL terminated array of zero terminated strings of constant identifers for example {"PI", "E", 0}
- * @param func1_name NULL terminated array of zero terminated strings of func1 identifers
- * @param func2_name NULL terminated array of zero terminated strings of func2 identifers
- * @param error pointer to a char* which is set to an error message if something goes wrong
- * @return AVExpr which must be freed with ff_free_expr() by the user when it is not needed anymore
- *         NULL if anything went wrong
- */
-AVExpr *ff_parse_expr(const char *s, const char * const *const_name,
-               double (* const *func1)(void *, double), const char * const *func1_name,
-               double (* const *func2)(void *, double, double), const char * const *func2_name,
-               const char **error);
-
-/**
- * Evaluates a previously parsed expression.
- *
- * @param const_value a zero terminated array of values for the identifers from ff_parse const_name
- * @param opaque a pointer which will be passed to all functions from func1 and func2
- * @return the value of the expression
- */
-double ff_eval_expr(AVExpr * e, const double *const_value, void *opaque);
-
-/**
- * Frees a parsed expression previously created with ff_parse().
- */
-void ff_free_expr(AVExpr *e);
-
-/**
- * Parses the string in numstr and returns its value as a double. If
- * the string is empty, contains only whitespaces, or does not contain
- * an initial substring that has the expected syntax for a
- * floating-point number, no conversion is performed. In this case,
- * returns a value of zero and the value returned in tail is the value
- * of numstr.
- *
- * @param numstr a string representing a number, may contain one of
- * the International System number postfixes, for example 'K', 'M',
- * 'G'. If 'i' is appended after the postfix, powers of 2 are used
- * instead of powers of 10. The 'B' postfix multiplies the value for
- * 8, and can be appended after another postfix or used alone. This
- * allows using for example 'KB', 'MiB', 'G' and 'B' as postfix.
- * @param tail if non-NULL puts here the pointer to the char next
- * after the last parsed character
- */
-double av_strtod(const char *numstr, char **tail);
-
-#endif /* AVCODEC_EVAL_H */
diff --git a/libavcodec/faandct.h b/libavcodec/faandct.h
index f43b62f..da8c0e4 100644
--- a/libavcodec/faandct.h
+++ b/libavcodec/faandct.h
@@ -2,20 +2,20 @@
  * Floating point AAN DCT
  * Copyright (c) 2003 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/faanidct.c b/libavcodec/faanidct.c
index dc3d8fb..0b9b458 100644
--- a/libavcodec/faanidct.c
+++ b/libavcodec/faanidct.c
@@ -2,20 +2,20 @@
  * Floating point AAN IDCT
  * Copyright (c) 2008 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #include "faanidct.h"
diff --git a/libavcodec/faanidct.h b/libavcodec/faanidct.h
index 4cf1189..f3896f7 100644
--- a/libavcodec/faanidct.h
+++ b/libavcodec/faanidct.h
@@ -2,20 +2,20 @@
  * Floating point AAN IDCT
  * Copyright (c) 2008 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/faxcompr.c b/libavcodec/faxcompr.c
index 34aa576..79e8d75 100644
--- a/libavcodec/faxcompr.c
+++ b/libavcodec/faxcompr.c
@@ -2,20 +2,20 @@
  * CCITT Fax Group 3 and 4 decompression
  * Copyright (c) 2008 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/faxcompr.h b/libavcodec/faxcompr.h
index 62f591c..4742d15 100644
--- a/libavcodec/faxcompr.h
+++ b/libavcodec/faxcompr.h
@@ -2,20 +2,20 @@
  * CCITT Fax Group 3 and 4 decompression
  * Copyright (c) 2008 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/fft-fixed-test.c b/libavcodec/fft-fixed-test.c
new file mode 100644
index 0000000..63cd194
--- /dev/null
+++ b/libavcodec/fft-fixed-test.c
@@ -0,0 +1,20 @@
+/*
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#define CONFIG_FFT_FLOAT 0
+#include "fft-test.c"
diff --git a/libavcodec/fft-internal.h b/libavcodec/fft-internal.h
new file mode 100644
index 0000000..d30571b
--- /dev/null
+++ b/libavcodec/fft-internal.h
@@ -0,0 +1,75 @@
+/*
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_FFT_INTERNAL_H
+#define AVCODEC_FFT_INTERNAL_H
+
+#if CONFIG_FFT_FLOAT
+
+#define FIX15(v) (v)
+#define sqrthalf (float)M_SQRT1_2
+
+#define BF(x, y, a, b) do {                     \
+        x = a - b;                              \
+        y = a + b;                              \
+    } while (0)
+
+#define CMUL(dre, dim, are, aim, bre, bim) do { \
+        (dre) = (are) * (bre) - (aim) * (bim);  \
+        (dim) = (are) * (bim) + (aim) * (bre);  \
+    } while (0)
+
+#else
+
+#include "libavutil/intmath.h"
+#include "mathops.h"
+
+void ff_mdct_calcw_c(FFTContext *s, FFTDouble *output, const FFTSample *input);
+
+#define SCALE_FLOAT(a, bits) lrint((a) * (double)(1 << (bits)))
+#define FIX15(a) av_clip(SCALE_FLOAT(a, 15), -32767, 32767)
+
+#define sqrthalf ((int16_t)((1<<15)*M_SQRT1_2))
+
+#define BF(x, y, a, b) do {                     \
+        x = (a - b) >> 1;                       \
+        y = (a + b) >> 1;                       \
+    } while (0)
+
+#define CMULS(dre, dim, are, aim, bre, bim, sh) do {            \
+        (dre) = (MUL16(are, bre) - MUL16(aim, bim)) >> sh;      \
+        (dim) = (MUL16(are, bim) + MUL16(aim, bre)) >> sh;      \
+    } while (0)
+
+#define CMUL(dre, dim, are, aim, bre, bim)      \
+    CMULS(dre, dim, are, aim, bre, bim, 15)
+
+#define CMULL(dre, dim, are, aim, bre, bim)     \
+    CMULS(dre, dim, are, aim, bre, bim, 0)
+
+#endif /* CONFIG_FFT_FLOAT */
+
+#define ff_imdct_calc_c FFT_NAME(ff_imdct_calc_c)
+#define ff_imdct_half_c FFT_NAME(ff_imdct_half_c)
+#define ff_mdct_calc_c  FFT_NAME(ff_mdct_calc_c)
+
+void ff_imdct_calc_c(FFTContext *s, FFTSample *output, const FFTSample *input);
+void ff_imdct_half_c(FFTContext *s, FFTSample *output, const FFTSample *input);
+void ff_mdct_calc_c(FFTContext *s, FFTSample *output, const FFTSample *input);
+
+#endif /* AVCODEC_FFT_INTERNAL_H */
diff --git a/libavcodec/fft-test.c b/libavcodec/fft-test.c
index ae43602..0112c6f 100644
--- a/libavcodec/fft-test.c
+++ b/libavcodec/fft-test.c
@@ -1,20 +1,20 @@
 /*
  * (c) 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -27,6 +27,10 @@
 #include "libavutil/lfg.h"
 #include "libavutil/log.h"
 #include "fft.h"
+#if CONFIG_FFT_FLOAT
+#include "dct.h"
+#include "rdft.h"
+#endif
 #include <math.h>
 #include <unistd.h>
 #include <sys/time.h>
@@ -45,7 +49,19 @@
    pim += (MUL16(are, bim) + MUL16(bre, aim));\
 }
 
-FFTComplex *exptab;
+#if CONFIG_FFT_FLOAT
+#   define RANGE 1.0
+#   define REF_SCALE(x, bits)  (x)
+#   define FMT "%10.6f"
+#else
+#   define RANGE 16384
+#   define REF_SCALE(x, bits) ((x) / (1<<(bits)))
+#   define FMT "%6d"
+#endif
+
+struct {
+    float re, im;
+} *exptab;
 
 static void fft_ref_init(int nbits, int inverse)
 {
@@ -53,7 +69,7 @@ static void fft_ref_init(int nbits, int inverse)
     double c1, s1, alpha;
 
     n = 1 << nbits;
-    exptab = av_malloc((n / 2) * sizeof(FFTComplex));
+    exptab = av_malloc((n / 2) * sizeof(*exptab));
 
     for (i = 0; i < (n/2); i++) {
         alpha = 2 * M_PI * (float)i / (float)n;
@@ -90,12 +106,12 @@ static void fft_ref(FFTComplex *tabr, FFTComplex *tab, int nbits)
             CMAC(tmp_re, tmp_im, c, s, q->re, q->im);
             q++;
         }
-        tabr[i].re = tmp_re;
-        tabr[i].im = tmp_im;
+        tabr[i].re = REF_SCALE(tmp_re, nbits);
+        tabr[i].im = REF_SCALE(tmp_im, nbits);
     }
 }
 
-static void imdct_ref(float *out, float *in, int nbits)
+static void imdct_ref(FFTSample *out, FFTSample *in, int nbits)
 {
     int n = 1<<nbits;
     int k, i, a;
@@ -108,12 +124,12 @@ static void imdct_ref(float *out, float *in, int nbits)
             f = cos(M_PI * a / (double)(2 * n));
             sum += f * in[k];
         }
-        out[i] = -sum;
+        out[i] = REF_SCALE(-sum, nbits - 2);
     }
 }
 
 /* NOTE: no normalisation by 1 / N is done */
-static void mdct_ref(float *output, float *input, int nbits)
+static void mdct_ref(FFTSample *output, FFTSample *input, int nbits)
 {
     int n = 1<<nbits;
     int k, i;
@@ -126,10 +142,11 @@ static void mdct_ref(float *output, float *input, int nbits)
             a = (2*M_PI*(2*i+1+n/2)*(2*k+1) / (4 * n));
             s += input[i] * cos(a);
         }
-        output[k] = s;
+        output[k] = REF_SCALE(s, nbits - 1);
     }
 }
 
+#if CONFIG_FFT_FLOAT
 static void idct_ref(float *output, float *input, int nbits)
 {
     int n = 1<<nbits;
@@ -162,11 +179,12 @@ static void dct_ref(float *output, float *input, int nbits)
         output[k] = s;
     }
 }
+#endif
 
 
-static float frandom(AVLFG *prng)
+static FFTSample frandom(AVLFG *prng)
 {
-    return (int16_t)av_lfg_get(prng) / 32768.0;
+    return (int16_t)av_lfg_get(prng) / 32768.0 * RANGE;
 }
 
 static int64_t gettime(void)
@@ -176,22 +194,25 @@ static int64_t gettime(void)
     return (int64_t)tv.tv_sec * 1000000 + tv.tv_usec;
 }
 
-static void check_diff(float *tab1, float *tab2, int n, double scale)
+static int check_diff(FFTSample *tab1, FFTSample *tab2, int n, double scale)
 {
     int i;
     double max= 0;
     double error= 0;
+    int err = 0;
 
     for (i = 0; i < n; i++) {
-        double e= fabsf(tab1[i] - (tab2[i] / scale));
+        double e = fabsf(tab1[i] - (tab2[i] / scale)) / RANGE;
         if (e >= 1e-3) {
-            av_log(NULL, AV_LOG_ERROR, "ERROR %d: %f %f\n",
+            av_log(NULL, AV_LOG_ERROR, "ERROR %5d: "FMT" "FMT"\n",
                    i, tab1[i], tab2[i]);
+            err = 1;
         }
         error+= e*e;
         if(e>max) max= e;
     }
     av_log(NULL, AV_LOG_INFO, "max:%f e:%g\n", max, sqrt(error)/n);
+    return err;
 }
 
 
@@ -223,12 +244,15 @@ int main(int argc, char **argv)
     FFTSample *tab2;
     int it, i, c;
     int do_speed = 0;
+    int err = 1;
     enum tf_transform transform = TRANSFORM_FFT;
     int do_inverse = 0;
     FFTContext s1, *s = &s1;
     FFTContext m1, *m = &m1;
+#if CONFIG_FFT_FLOAT
     RDFTContext r1, *r = &r1;
     DCTContext d1, *d = &d1;
+#endif
     int fft_nbits, fft_size, fft_size_2;
     double scale = 1.0;
     AVLFG prng;
@@ -291,6 +315,7 @@ int main(int argc, char **argv)
         ff_fft_init(s, fft_nbits, do_inverse);
         fft_ref_init(fft_nbits, do_inverse);
         break;
+#if CONFIG_FFT_FLOAT
     case TRANSFORM_RDFT:
         if (do_inverse)
             av_log(NULL, AV_LOG_INFO,"IDFT_C2R");
@@ -306,6 +331,10 @@ int main(int argc, char **argv)
             av_log(NULL, AV_LOG_INFO,"DCT_II");
         ff_dct_init(d, fft_nbits, do_inverse ? DCT_III : DCT_II);
         break;
+#endif
+    default:
+        av_log(NULL, AV_LOG_ERROR, "Requested transform not supported\n");
+        return 1;
     }
     av_log(NULL, AV_LOG_INFO," %d test\n", fft_size);
 
@@ -322,25 +351,26 @@ int main(int argc, char **argv)
     switch (transform) {
     case TRANSFORM_MDCT:
         if (do_inverse) {
-            imdct_ref((float *)tab_ref, (float *)tab1, fft_nbits);
-            ff_imdct_calc(m, tab2, (float *)tab1);
-            check_diff((float *)tab_ref, tab2, fft_size, scale);
+            imdct_ref((FFTSample *)tab_ref, (FFTSample *)tab1, fft_nbits);
+            m->imdct_calc(m, tab2, (FFTSample *)tab1);
+            err = check_diff((FFTSample *)tab_ref, tab2, fft_size, scale);
         } else {
-            mdct_ref((float *)tab_ref, (float *)tab1, fft_nbits);
+            mdct_ref((FFTSample *)tab_ref, (FFTSample *)tab1, fft_nbits);
 
-            ff_mdct_calc(m, tab2, (float *)tab1);
+            m->mdct_calc(m, tab2, (FFTSample *)tab1);
 
-            check_diff((float *)tab_ref, tab2, fft_size / 2, scale);
+            err = check_diff((FFTSample *)tab_ref, tab2, fft_size / 2, scale);
         }
         break;
     case TRANSFORM_FFT:
         memcpy(tab, tab1, fft_size * sizeof(FFTComplex));
-        ff_fft_permute(s, tab);
-        ff_fft_calc(s, tab);
+        s->fft_permute(s, tab);
+        s->fft_calc(s, tab);
 
         fft_ref(tab_ref, tab1, fft_nbits);
-        check_diff((float *)tab_ref, (float *)tab, fft_size * 2, 1.0);
+        err = check_diff((FFTSample *)tab_ref, (FFTSample *)tab, fft_size * 2, 1.0);
         break;
+#if CONFIG_FFT_FLOAT
     case TRANSFORM_RDFT:
         if (do_inverse) {
             tab1[         0].im = 0;
@@ -353,34 +383,35 @@ int main(int argc, char **argv)
             memcpy(tab2, tab1, fft_size * sizeof(FFTSample));
             tab2[1] = tab1[fft_size_2].re;
 
-            ff_rdft_calc(r, tab2);
+            r->rdft_calc(r, tab2);
             fft_ref(tab_ref, tab1, fft_nbits);
             for (i = 0; i < fft_size; i++) {
                 tab[i].re = tab2[i];
                 tab[i].im = 0;
             }
-            check_diff((float *)tab_ref, (float *)tab, fft_size * 2, 0.5);
+            err = check_diff((float *)tab_ref, (float *)tab, fft_size * 2, 0.5);
         } else {
             for (i = 0; i < fft_size; i++) {
                 tab2[i]    = tab1[i].re;
                 tab1[i].im = 0;
             }
-            ff_rdft_calc(r, tab2);
+            r->rdft_calc(r, tab2);
             fft_ref(tab_ref, tab1, fft_nbits);
             tab_ref[0].im = tab_ref[fft_size_2].re;
-            check_diff((float *)tab_ref, (float *)tab2, fft_size, 1.0);
+            err = check_diff((float *)tab_ref, (float *)tab2, fft_size, 1.0);
         }
         break;
     case TRANSFORM_DCT:
         memcpy(tab, tab1, fft_size * sizeof(FFTComplex));
-        ff_dct_calc(d, tab);
+        d->dct_calc(d, tab);
         if (do_inverse) {
             idct_ref(tab_ref, tab1, fft_nbits);
         } else {
             dct_ref(tab_ref, tab1, fft_nbits);
         }
-        check_diff((float *)tab_ref, (float *)tab, fft_size, 1.0);
+        err = check_diff((float *)tab_ref, (float *)tab, fft_size, 1.0);
         break;
+#endif
     }
 
     /* do a speed test */
@@ -398,23 +429,25 @@ int main(int argc, char **argv)
                 switch (transform) {
                 case TRANSFORM_MDCT:
                     if (do_inverse) {
-                        ff_imdct_calc(m, (float *)tab, (float *)tab1);
+                        m->imdct_calc(m, (FFTSample *)tab, (FFTSample *)tab1);
                     } else {
-                        ff_mdct_calc(m, (float *)tab, (float *)tab1);
+                        m->mdct_calc(m, (FFTSample *)tab, (FFTSample *)tab1);
                     }
                     break;
                 case TRANSFORM_FFT:
                     memcpy(tab, tab1, fft_size * sizeof(FFTComplex));
-                    ff_fft_calc(s, tab);
+                    s->fft_calc(s, tab);
                     break;
+#if CONFIG_FFT_FLOAT
                 case TRANSFORM_RDFT:
                     memcpy(tab2, tab1, fft_size * sizeof(FFTSample));
-                    ff_rdft_calc(r, tab2);
+                    r->rdft_calc(r, tab2);
                     break;
                 case TRANSFORM_DCT:
                     memcpy(tab2, tab1, fft_size * sizeof(FFTSample));
-                    ff_dct_calc(d, tab2);
+                    d->dct_calc(d, tab2);
                     break;
+#endif
                 }
             }
             duration = gettime() - time_start;
@@ -435,12 +468,21 @@ int main(int argc, char **argv)
     case TRANSFORM_FFT:
         ff_fft_end(s);
         break;
+#if CONFIG_FFT_FLOAT
     case TRANSFORM_RDFT:
         ff_rdft_end(r);
         break;
     case TRANSFORM_DCT:
         ff_dct_end(d);
         break;
+#endif
     }
-    return 0;
+
+    av_free(tab);
+    av_free(tab1);
+    av_free(tab2);
+    av_free(tab_ref);
+    av_free(exptab);
+
+    return err;
 }
diff --git a/libavcodec/fft.c b/libavcodec/fft.c
index bf240bf..077f471 100644
--- a/libavcodec/fft.c
+++ b/libavcodec/fft.c
@@ -4,20 +4,20 @@
  * Copyright (c) 2002 Fabrice Bellard
  * Partly based on libdjbfft by D. J. Bernstein
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -30,6 +30,7 @@
 #include <string.h>
 #include "libavutil/mathematics.h"
 #include "fft.h"
+#include "fft-internal.h"
 
 /* cos(2*pi*x/n) for 0<=x<=n/4, followed by its reverse */
 #if !CONFIG_HARDCODED_TABLES
@@ -47,12 +48,26 @@ COSTABLE(16384);
 COSTABLE(32768);
 COSTABLE(65536);
 #endif
-COSTABLE_CONST FFTSample * const ff_cos_tabs[] = {
+COSTABLE_CONST FFTSample * const FFT_NAME(ff_cos_tabs)[] = {
     NULL, NULL, NULL, NULL,
-    ff_cos_16, ff_cos_32, ff_cos_64, ff_cos_128, ff_cos_256, ff_cos_512, ff_cos_1024,
-    ff_cos_2048, ff_cos_4096, ff_cos_8192, ff_cos_16384, ff_cos_32768, ff_cos_65536,
+    FFT_NAME(ff_cos_16),
+    FFT_NAME(ff_cos_32),
+    FFT_NAME(ff_cos_64),
+    FFT_NAME(ff_cos_128),
+    FFT_NAME(ff_cos_256),
+    FFT_NAME(ff_cos_512),
+    FFT_NAME(ff_cos_1024),
+    FFT_NAME(ff_cos_2048),
+    FFT_NAME(ff_cos_4096),
+    FFT_NAME(ff_cos_8192),
+    FFT_NAME(ff_cos_16384),
+    FFT_NAME(ff_cos_32768),
+    FFT_NAME(ff_cos_65536),
 };
 
+static void ff_fft_permute_c(FFTContext *s, FFTComplex *z);
+static void ff_fft_calc_c(FFTContext *s, FFTComplex *z);
+
 static int split_radix_permutation(int i, int n, int inverse)
 {
     int m;
@@ -70,9 +85,9 @@ av_cold void ff_init_ff_cos_tabs(int index)
     int i;
     int m = 1<<index;
     double freq = 2*M_PI/m;
-    FFTSample *tab = ff_cos_tabs[index];
+    FFTSample *tab = FFT_NAME(ff_cos_tabs)[index];
     for(i=0; i<=m/4; i++)
-        tab[i] = cos(i*freq);
+        tab[i] = FIX15(cos(i*freq));
     for(i=1; i<m/4; i++)
         tab[m/2-i] = tab[i];
 #endif
@@ -80,25 +95,21 @@ av_cold void ff_init_ff_cos_tabs(int index)
 
 av_cold int ff_fft_init(FFTContext *s, int nbits, int inverse)
 {
-    int i, j, m, n;
-    float alpha, c1, s1, s2;
-    int av_unused has_vectors;
+    int i, j, n;
 
     if (nbits < 2 || nbits > 16)
         goto fail;
     s->nbits = nbits;
     n = 1 << nbits;
 
-    s->tmp_buf = NULL;
-    s->exptab  = av_malloc((n / 2) * sizeof(FFTComplex));
-    if (!s->exptab)
-        goto fail;
     s->revtab = av_malloc(n * sizeof(uint16_t));
     if (!s->revtab)
         goto fail;
+    s->tmp_buf = av_malloc(n * sizeof(FFTComplex));
+    if (!s->tmp_buf)
+        goto fail;
     s->inverse = inverse;
-
-    s2 = inverse ? 1.0 : -1.0;
+    s->fft_permutation = FF_FFT_PERM_DEFAULT;
 
     s->fft_permute = ff_fft_permute_c;
     s->fft_calc    = ff_fft_calc_c;
@@ -107,114 +118,50 @@ av_cold int ff_fft_init(FFTContext *s, int nbits, int inverse)
     s->imdct_half  = ff_imdct_half_c;
     s->mdct_calc   = ff_mdct_calc_c;
 #endif
-    s->exptab1     = NULL;
-    s->split_radix = 1;
 
+#if CONFIG_FFT_FLOAT
     if (ARCH_ARM)     ff_fft_init_arm(s);
     if (HAVE_ALTIVEC) ff_fft_init_altivec(s);
     if (HAVE_MMX)     ff_fft_init_mmx(s);
+    if (CONFIG_MDCT)  s->mdct_calcw = s->mdct_calc;
+#else
+    if (CONFIG_MDCT)  s->mdct_calcw = ff_mdct_calcw_c;
+    if (ARCH_ARM)     ff_fft_fixed_init_arm(s);
+#endif
 
-    if (s->split_radix) {
-        for(j=4; j<=nbits; j++) {
-            ff_init_ff_cos_tabs(j);
-        }
-        for(i=0; i<n; i++)
-            s->revtab[-split_radix_permutation(i, n, s->inverse) & (n-1)] = i;
-        s->tmp_buf = av_malloc(n * sizeof(FFTComplex));
-    } else {
-        int np, nblocks, np2, l;
-        FFTComplex *q;
-
-        for(i=0; i<(n/2); i++) {
-            alpha = 2 * M_PI * (float)i / (float)n;
-            c1 = cos(alpha);
-            s1 = sin(alpha) * s2;
-            s->exptab[i].re = c1;
-            s->exptab[i].im = s1;
-        }
-
-        np = 1 << nbits;
-        nblocks = np >> 3;
-        np2 = np >> 1;
-        s->exptab1 = av_malloc(np * 2 * sizeof(FFTComplex));
-        if (!s->exptab1)
-            goto fail;
-        q = s->exptab1;
-        do {
-            for(l = 0; l < np2; l += 2 * nblocks) {
-                *q++ = s->exptab[l];
-                *q++ = s->exptab[l + nblocks];
-
-                q->re = -s->exptab[l].im;
-                q->im = s->exptab[l].re;
-                q++;
-                q->re = -s->exptab[l + nblocks].im;
-                q->im = s->exptab[l + nblocks].re;
-                q++;
-            }
-            nblocks = nblocks >> 1;
-        } while (nblocks != 0);
-        av_freep(&s->exptab);
-
-        /* compute bit reverse table */
-        for(i=0;i<n;i++) {
-            m=0;
-            for(j=0;j<nbits;j++) {
-                m |= ((i >> j) & 1) << (nbits-j-1);
-            }
-            s->revtab[i]=m;
-        }
+    for(j=4; j<=nbits; j++) {
+        ff_init_ff_cos_tabs(j);
+    }
+    for(i=0; i<n; i++) {
+        int j = i;
+        if (s->fft_permutation == FF_FFT_PERM_SWAP_LSBS)
+            j = (j&~3) | ((j>>1)&1) | ((j<<1)&2);
+        s->revtab[-split_radix_permutation(i, n, s->inverse) & (n-1)] = j;
     }
 
     return 0;
  fail:
     av_freep(&s->revtab);
-    av_freep(&s->exptab);
-    av_freep(&s->exptab1);
     av_freep(&s->tmp_buf);
     return -1;
 }
 
-void ff_fft_permute_c(FFTContext *s, FFTComplex *z)
+static void ff_fft_permute_c(FFTContext *s, FFTComplex *z)
 {
-    int j, k, np;
-    FFTComplex tmp;
+    int j, np;
     const uint16_t *revtab = s->revtab;
     np = 1 << s->nbits;
-
-    if (s->tmp_buf) {
-        /* TODO: handle split-radix permute in a more optimal way, probably in-place */
-        for(j=0;j<np;j++) s->tmp_buf[revtab[j]] = z[j];
-        memcpy(z, s->tmp_buf, np * sizeof(FFTComplex));
-        return;
-    }
-
-    /* reverse */
-    for(j=0;j<np;j++) {
-        k = revtab[j];
-        if (k < j) {
-            tmp = z[k];
-            z[k] = z[j];
-            z[j] = tmp;
-        }
-    }
+    /* TODO: handle split-radix permute in a more optimal way, probably in-place */
+    for(j=0;j<np;j++) s->tmp_buf[revtab[j]] = z[j];
+    memcpy(z, s->tmp_buf, np * sizeof(FFTComplex));
 }
 
 av_cold void ff_fft_end(FFTContext *s)
 {
     av_freep(&s->revtab);
-    av_freep(&s->exptab);
-    av_freep(&s->exptab1);
     av_freep(&s->tmp_buf);
 }
 
-#define sqrthalf (float)M_SQRT1_2
-
-#define BF(x,y,a,b) {\
-    x = a - b;\
-    y = a + b;\
-}
-
 #define BUTTERFLIES(a0,a1,a2,a3) {\
     BF(t3, t5, t5, t1);\
     BF(a2.re, a0.re, a0.re, t5);\
@@ -238,10 +185,8 @@ av_cold void ff_fft_end(FFTContext *s)
 }
 
 #define TRANSFORM(a0,a1,a2,a3,wre,wim) {\
-    t1 = a2.re * wre + a2.im * wim;\
-    t2 = a2.im * wre - a2.re * wim;\
-    t5 = a3.re * wre - a3.im * wim;\
-    t6 = a3.im * wre + a3.re * wim;\
+    CMUL(t1, t2, a2.re, a2.im, wre, -wim);\
+    CMUL(t5, t6, a3.re, a3.im, wre,  wim);\
     BUTTERFLIES(a0,a1,a2,a3)\
 }
 
@@ -257,7 +202,7 @@ av_cold void ff_fft_end(FFTContext *s)
 #define PASS(name)\
 static void name(FFTComplex *z, const FFTSample *wre, unsigned int n)\
 {\
-    FFTSample t1, t2, t3, t4, t5, t6;\
+    FFTDouble t1, t2, t3, t4, t5, t6;\
     int o1 = 2*n;\
     int o2 = 4*n;\
     int o3 = 6*n;\
@@ -286,12 +231,12 @@ static void fft##n(FFTComplex *z)\
     fft##n2(z);\
     fft##n4(z+n4*2);\
     fft##n4(z+n4*3);\
-    pass(z,ff_cos_##n,n4/2);\
+    pass(z,FFT_NAME(ff_cos_##n),n4/2);\
 }
 
 static void fft4(FFTComplex *z)
 {
-    FFTSample t1, t2, t3, t4, t5, t6, t7, t8;
+    FFTDouble t1, t2, t3, t4, t5, t6, t7, t8;
 
     BF(t3, t1, z[0].re, z[1].re);
     BF(t8, t6, z[3].re, z[2].re);
@@ -305,28 +250,25 @@ static void fft4(FFTComplex *z)
 
 static void fft8(FFTComplex *z)
 {
-    FFTSample t1, t2, t3, t4, t5, t6, t7, t8;
+    FFTDouble t1, t2, t3, t4, t5, t6;
 
     fft4(z);
 
     BF(t1, z[5].re, z[4].re, -z[5].re);
     BF(t2, z[5].im, z[4].im, -z[5].im);
-    BF(t3, z[7].re, z[6].re, -z[7].re);
-    BF(t4, z[7].im, z[6].im, -z[7].im);
-    BF(t8, t1, t3, t1);
-    BF(t7, t2, t2, t4);
-    BF(z[4].re, z[0].re, z[0].re, t1);
-    BF(z[4].im, z[0].im, z[0].im, t2);
-    BF(z[6].re, z[2].re, z[2].re, t7);
-    BF(z[6].im, z[2].im, z[2].im, t8);
+    BF(t5, z[7].re, z[6].re, -z[7].re);
+    BF(t6, z[7].im, z[6].im, -z[7].im);
 
+    BUTTERFLIES(z[0],z[2],z[4],z[6]);
     TRANSFORM(z[1],z[3],z[5],z[7],sqrthalf,sqrthalf);
 }
 
 #if !CONFIG_SMALL
 static void fft16(FFTComplex *z)
 {
-    FFTSample t1, t2, t3, t4, t5, t6;
+    FFTDouble t1, t2, t3, t4, t5, t6;
+    FFTSample cos_16_1 = FFT_NAME(ff_cos_16)[1];
+    FFTSample cos_16_3 = FFT_NAME(ff_cos_16)[3];
 
     fft8(z);
     fft4(z+8);
@@ -334,8 +276,8 @@ static void fft16(FFTComplex *z)
 
     TRANSFORM_ZERO(z[0],z[4],z[8],z[12]);
     TRANSFORM(z[2],z[6],z[10],z[14],sqrthalf,sqrthalf);
-    TRANSFORM(z[1],z[5],z[9],z[13],ff_cos_16[1],ff_cos_16[3]);
-    TRANSFORM(z[3],z[7],z[11],z[15],ff_cos_16[3],ff_cos_16[1]);
+    TRANSFORM(z[1],z[5],z[9],z[13],cos_16_1,cos_16_3);
+    TRANSFORM(z[3],z[7],z[11],z[15],cos_16_3,cos_16_1);
 }
 #else
 DECL_FFT(16,8,4)
@@ -361,7 +303,7 @@ static void (* const fft_dispatch[])(FFTComplex*) = {
     fft2048, fft4096, fft8192, fft16384, fft32768, fft65536,
 };
 
-void ff_fft_calc_c(FFTContext *s, FFTComplex *z)
+static void ff_fft_calc_c(FFTContext *s, FFTComplex *z)
 {
     fft_dispatch[s->nbits-2](z);
 }
diff --git a/libavcodec/fft.h b/libavcodec/fft.h
index 1f5b2e8..a4fee00 100644
--- a/libavcodec/fft.h
+++ b/libavcodec/fft.h
@@ -2,72 +2,103 @@
  * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #ifndef AVCODEC_FFT_H
 #define AVCODEC_FFT_H
 
+#ifndef CONFIG_FFT_FLOAT
+#define CONFIG_FFT_FLOAT 1
+#endif
+
 #include <stdint.h>
 #include "config.h"
 #include "libavutil/mem.h"
+
+#if CONFIG_FFT_FLOAT
+
 #include "avfft.h"
 
+#define FFT_NAME(x) x
+
+typedef float FFTDouble;
+
+#else
+
+#define FFT_NAME(x) x ## _fixed
+
+typedef int16_t FFTSample;
+typedef int     FFTDouble;
+
+typedef struct FFTComplex {
+    int16_t re, im;
+} FFTComplex;
+
+typedef struct FFTContext FFTContext;
+
+#endif /* CONFIG_FFT_FLOAT */
+
+typedef struct FFTDComplex {
+    FFTDouble re, im;
+} FFTDComplex;
+
 /* FFT computation */
 
 struct FFTContext {
     int nbits;
     int inverse;
     uint16_t *revtab;
-    FFTComplex *exptab;
-    FFTComplex *exptab1; /* only used by SSE code */
     FFTComplex *tmp_buf;
     int mdct_size; /* size of MDCT (i.e. number of input data * 2) */
     int mdct_bits; /* n = 2^nbits */
     /* pre/post rotation tables */
     FFTSample *tcos;
     FFTSample *tsin;
+    /**
+     * Do the permutation needed BEFORE calling fft_calc().
+     */
     void (*fft_permute)(struct FFTContext *s, FFTComplex *z);
+    /**
+     * Do a complex FFT with the parameters defined in ff_fft_init(). The
+     * input data must be permuted before. No 1.0/sqrt(n) normalization is done.
+     */
     void (*fft_calc)(struct FFTContext *s, FFTComplex *z);
     void (*imdct_calc)(struct FFTContext *s, FFTSample *output, const FFTSample *input);
     void (*imdct_half)(struct FFTContext *s, FFTSample *output, const FFTSample *input);
     void (*mdct_calc)(struct FFTContext *s, FFTSample *output, const FFTSample *input);
-    int split_radix;
-    int permutation;
+    void (*mdct_calcw)(struct FFTContext *s, FFTDouble *output, const FFTSample *input);
+    int fft_permutation;
+#define FF_FFT_PERM_DEFAULT   0
+#define FF_FFT_PERM_SWAP_LSBS 1
+    int mdct_permutation;
 #define FF_MDCT_PERM_NONE       0
 #define FF_MDCT_PERM_INTERLEAVE 1
 };
 
 #if CONFIG_HARDCODED_TABLES
 #define COSTABLE_CONST const
-#define SINTABLE_CONST const
-#define SINETABLE_CONST const
 #else
 #define COSTABLE_CONST
-#define SINTABLE_CONST
-#define SINETABLE_CONST
 #endif
 
 #define COSTABLE(size) \
-    COSTABLE_CONST DECLARE_ALIGNED(16, FFTSample, ff_cos_##size)[size/2]
-#define SINTABLE(size) \
-    SINTABLE_CONST DECLARE_ALIGNED(16, FFTSample, ff_sin_##size)[size/2]
-#define SINETABLE(size) \
-    SINETABLE_CONST DECLARE_ALIGNED(16, float, ff_sine_##size)[size]
+    COSTABLE_CONST DECLARE_ALIGNED(16, FFTSample, FFT_NAME(ff_cos_##size))[size/2]
+
 extern COSTABLE(16);
 extern COSTABLE(32);
 extern COSTABLE(64);
@@ -81,160 +112,40 @@ extern COSTABLE(8192);
 extern COSTABLE(16384);
 extern COSTABLE(32768);
 extern COSTABLE(65536);
-extern COSTABLE_CONST FFTSample* const ff_cos_tabs[17];
+extern COSTABLE_CONST FFTSample* const FFT_NAME(ff_cos_tabs)[17];
+
+#define ff_init_ff_cos_tabs FFT_NAME(ff_init_ff_cos_tabs)
 
 /**
- * Initializes the cosine table in ff_cos_tabs[index]
+ * Initialize the cosine table in ff_cos_tabs[index]
  * \param index index in ff_cos_tabs array of the table to initialize
  */
 void ff_init_ff_cos_tabs(int index);
 
-extern SINTABLE(16);
-extern SINTABLE(32);
-extern SINTABLE(64);
-extern SINTABLE(128);
-extern SINTABLE(256);
-extern SINTABLE(512);
-extern SINTABLE(1024);
-extern SINTABLE(2048);
-extern SINTABLE(4096);
-extern SINTABLE(8192);
-extern SINTABLE(16384);
-extern SINTABLE(32768);
-extern SINTABLE(65536);
+#define ff_fft_init FFT_NAME(ff_fft_init)
+#define ff_fft_end  FFT_NAME(ff_fft_end)
 
 /**
- * Sets up a complex FFT.
+ * Set up a complex FFT.
  * @param nbits           log2 of the length of the input array
  * @param inverse         if 0 perform the forward transform, if 1 perform the inverse
  */
 int ff_fft_init(FFTContext *s, int nbits, int inverse);
-void ff_fft_permute_c(FFTContext *s, FFTComplex *z);
-void ff_fft_calc_c(FFTContext *s, FFTComplex *z);
 
+#if CONFIG_FFT_FLOAT
 void ff_fft_init_altivec(FFTContext *s);
 void ff_fft_init_mmx(FFTContext *s);
 void ff_fft_init_arm(FFTContext *s);
+#else
+void ff_fft_fixed_init_arm(FFTContext *s);
+#endif
 
-/**
- * Do the permutation needed BEFORE calling ff_fft_calc().
- */
-static inline void ff_fft_permute(FFTContext *s, FFTComplex *z)
-{
-    s->fft_permute(s, z);
-}
-/**
- * Do a complex FFT with the parameters defined in ff_fft_init(). The
- * input data must be permuted before. No 1.0/sqrt(n) normalization is done.
- */
-static inline void ff_fft_calc(FFTContext *s, FFTComplex *z)
-{
-    s->fft_calc(s, z);
-}
 void ff_fft_end(FFTContext *s);
 
-/* MDCT computation */
-
-static inline void ff_imdct_calc(FFTContext *s, FFTSample *output, const FFTSample *input)
-{
-    s->imdct_calc(s, output, input);
-}
-static inline void ff_imdct_half(FFTContext *s, FFTSample *output, const FFTSample *input)
-{
-    s->imdct_half(s, output, input);
-}
-
-static inline void ff_mdct_calc(FFTContext *s, FFTSample *output,
-                                const FFTSample *input)
-{
-    s->mdct_calc(s, output, input);
-}
-
-/**
- * Generate a Kaiser-Bessel Derived Window.
- * @param   window  pointer to half window
- * @param   alpha   determines window shape
- * @param   n       size of half window
- */
-void ff_kbd_window_init(float *window, float alpha, int n);
-
-/**
- * Generate a sine window.
- * @param   window  pointer to half window
- * @param   n       size of half window
- */
-void ff_sine_window_init(float *window, int n);
-
-/**
- * initialize the specified entry of ff_sine_windows
- */
-void ff_init_ff_sine_windows(int index);
-extern SINETABLE(  32);
-extern SINETABLE(  64);
-extern SINETABLE( 128);
-extern SINETABLE( 256);
-extern SINETABLE( 512);
-extern SINETABLE(1024);
-extern SINETABLE(2048);
-extern SINETABLE(4096);
-extern SINETABLE_CONST float * const ff_sine_windows[13];
+#define ff_mdct_init FFT_NAME(ff_mdct_init)
+#define ff_mdct_end  FFT_NAME(ff_mdct_end)
 
 int ff_mdct_init(FFTContext *s, int nbits, int inverse, double scale);
-void ff_imdct_calc_c(FFTContext *s, FFTSample *output, const FFTSample *input);
-void ff_imdct_half_c(FFTContext *s, FFTSample *output, const FFTSample *input);
-void ff_mdct_calc_c(FFTContext *s, FFTSample *output, const FFTSample *input);
 void ff_mdct_end(FFTContext *s);
 
-/* Real Discrete Fourier Transform */
-
-struct RDFTContext {
-    int nbits;
-    int inverse;
-    int sign_convention;
-
-    /* pre/post rotation tables */
-    const FFTSample *tcos;
-    SINTABLE_CONST FFTSample *tsin;
-    FFTContext fft;
-    void (*rdft_calc)(struct RDFTContext *s, FFTSample *z);
-};
-
-/**
- * Sets up a real FFT.
- * @param nbits           log2 of the length of the input array
- * @param trans           the type of transform
- */
-int ff_rdft_init(RDFTContext *s, int nbits, enum RDFTransformType trans);
-void ff_rdft_end(RDFTContext *s);
-
-void ff_rdft_init_arm(RDFTContext *s);
-
-static av_always_inline void ff_rdft_calc(RDFTContext *s, FFTSample *data)
-{
-    s->rdft_calc(s, data);
-}
-
-/* Discrete Cosine Transform */
-
-struct DCTContext {
-    int nbits;
-    int inverse;
-    RDFTContext rdft;
-    const float *costab;
-    FFTSample *csc2;
-    void (*dct_calc)(struct DCTContext *s, FFTSample *data);
-};
-
-/**
- * Sets up DCT.
- * @param nbits           size of the input array:
- *                        (1 << nbits)     for DCT-II, DCT-III and DST-I
- *                        (1 << nbits) + 1 for DCT-I
- *
- * @note the first element of the input of DST-I is ignored
- */
-int  ff_dct_init(DCTContext *s, int nbits, enum DCTTransformType type);
-void ff_dct_calc(DCTContext *s, FFTSample *data);
-void ff_dct_end (DCTContext *s);
-
 #endif /* AVCODEC_FFT_H */
diff --git a/libavcodec/fft_fixed.c b/libavcodec/fft_fixed.c
new file mode 100644
index 0000000..b28091d
--- /dev/null
+++ b/libavcodec/fft_fixed.c
@@ -0,0 +1,20 @@
+/*
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#define CONFIG_FFT_FLOAT 0
+#include "fft.c"
diff --git a/libavcodec/fft_float.c b/libavcodec/fft_float.c
new file mode 100644
index 0000000..24c9fdb
--- /dev/null
+++ b/libavcodec/fft_float.c
@@ -0,0 +1,20 @@
+/*
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#define CONFIG_FFT_FLOAT 1
+#include "fft.c"
diff --git a/libavcodec/ffv1.c b/libavcodec/ffv1.c
index 12056e1..8b46091 100644
--- a/libavcodec/ffv1.c
+++ b/libavcodec/ffv1.c
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2003 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -32,10 +32,14 @@
 #include "rangecoder.h"
 #include "golomb.h"
 #include "mathops.h"
+#include "libavutil/avassert.h"
 
 #define MAX_PLANES 4
 #define CONTEXT_SIZE 32
 
+#define MAX_QUANT_TABLES 8
+#define MAX_CONTEXT_INPUTS 5
+
 extern const uint8_t ff_log2_run[32];
 
 static const int8_t quant3[256]={
@@ -213,17 +217,23 @@ typedef struct VlcState{
 } VlcState;
 
 typedef struct PlaneContext{
+    int16_t quant_table[MAX_CONTEXT_INPUTS][256];
+    int quant_table_index;
     int context_count;
     uint8_t (*state)[CONTEXT_SIZE];
     VlcState *vlc_state;
     uint8_t interlace_bit_state[2];
 } PlaneContext;
 
+#define MAX_SLICES 256
+
 typedef struct FFV1Context{
     AVCodecContext *avctx;
     RangeCoder c;
     GetBitContext gb;
     PutBitContext pb;
+    uint64_t rc_stat[256][2];
+    uint64_t (*rc_stat2[MAX_QUANT_TABLES])[32][2];
     int version;
     int width, height;
     int chroma_h_shift, chroma_v_shift;
@@ -233,12 +243,28 @@ typedef struct FFV1Context{
     int plane_count;
     int ac;                              ///< 1=range coder <-> 0=golomb rice
     PlaneContext plane[MAX_PLANES];
-    int16_t quant_table[5][256];
+    int16_t quant_table[MAX_CONTEXT_INPUTS][256];
+    int16_t quant_tables[MAX_QUANT_TABLES][MAX_CONTEXT_INPUTS][256];
+    int context_count[MAX_QUANT_TABLES];
     uint8_t state_transition[256];
+    uint8_t (*initial_states[MAX_QUANT_TABLES])[32];
     int run_index;
     int colorspace;
+    int_fast16_t *sample_buffer;
+    int gob_count;
+
+    int quant_table_count;
 
     DSPContext dsp;
+
+    struct FFV1Context *slice_context[MAX_SLICES];
+    int slice_count;
+    int num_v_slices;
+    int num_h_slices;
+    int slice_width;
+    int slice_height;
+    int slice_x;
+    int slice_y;
 }FFV1Context;
 
 static av_always_inline int fold(int diff, int bits){
@@ -261,24 +287,75 @@ static inline int predict(int_fast16_t *src, int_fast16_t *last){
     return mid_pred(L, L + T - LT, T);
 }
 
-static inline int get_context(FFV1Context *f, int_fast16_t *src, int_fast16_t *last, int_fast16_t *last2){
+static inline int get_context(PlaneContext *p, int_fast16_t *src, int_fast16_t *last, int_fast16_t *last2){
     const int LT= last[-1];
     const int  T= last[ 0];
     const int RT= last[ 1];
     const int L =  src[-1];
 
-    if(f->quant_table[3][127]){
+    if(p->quant_table[3][127]){
         const int TT= last2[0];
         const int LL=  src[-2];
-        return f->quant_table[0][(L-LT) & 0xFF] + f->quant_table[1][(LT-T) & 0xFF] + f->quant_table[2][(T-RT) & 0xFF]
-              +f->quant_table[3][(LL-L) & 0xFF] + f->quant_table[4][(TT-T) & 0xFF];
+        return p->quant_table[0][(L-LT) & 0xFF] + p->quant_table[1][(LT-T) & 0xFF] + p->quant_table[2][(T-RT) & 0xFF]
+              +p->quant_table[3][(LL-L) & 0xFF] + p->quant_table[4][(TT-T) & 0xFF];
     }else
-        return f->quant_table[0][(L-LT) & 0xFF] + f->quant_table[1][(LT-T) & 0xFF] + f->quant_table[2][(T-RT) & 0xFF];
+        return p->quant_table[0][(L-LT) & 0xFF] + p->quant_table[1][(LT-T) & 0xFF] + p->quant_table[2][(T-RT) & 0xFF];
 }
 
-static inline void put_symbol_inline(RangeCoder *c, uint8_t *state, int v, int is_signed){
+static void find_best_state(uint8_t best_state[256][256], const uint8_t one_state[256]){
+    int i,j,k,m;
+    double l2tab[256];
+
+    for(i=1; i<256; i++)
+        l2tab[i]= log2(i/256.0);
+
+    for(i=0; i<256; i++){
+        double best_len[256];
+        double p= i/256.0;
+
+        for(j=0; j<256; j++)
+            best_len[j]= 1<<30;
+
+        for(j=FFMAX(i-10,1); j<FFMIN(i+11,256); j++){
+            double occ[256]={0};
+            double len=0;
+            occ[j]=1.0;
+            for(k=0; k<256; k++){
+                double newocc[256]={0};
+                for(m=0; m<256; m++){
+                    if(occ[m]){
+                        len -=occ[m]*(     p *l2tab[    m]
+                                      + (1-p)*l2tab[256-m]);
+                    }
+                }
+                if(len < best_len[k]){
+                    best_len[k]= len;
+                    best_state[i][k]= j;
+                }
+                for(m=0; m<256; m++){
+                    if(occ[m]){
+                        newocc[    one_state[    m]] += occ[m]*   p ;
+                        newocc[256-one_state[256-m]] += occ[m]*(1-p);
+                    }
+                }
+                memcpy(occ, newocc, sizeof(occ));
+            }
+        }
+    }
+}
+
+static av_always_inline av_flatten void put_symbol_inline(RangeCoder *c, uint8_t *state, int v, int is_signed, uint64_t rc_stat[256][2], uint64_t rc_stat2[32][2]){
     int i;
 
+#define put_rac(C,S,B) \
+do{\
+    if(rc_stat){\
+    rc_stat[*(S)][B]++;\
+        rc_stat2[(S)-state][B]++;\
+    }\
+    put_rac(C,S,B);\
+}while(0)
+
     if(v){
         const int a= FFABS(v);
         const int e= av_log2(a);
@@ -311,10 +388,11 @@ static inline void put_symbol_inline(RangeCoder *c, uint8_t *state, int v, int i
     }else{
         put_rac(c, state+0, 1);
     }
+#undef put_rac
 }
 
 static void av_noinline put_symbol(RangeCoder *c, uint8_t *state, int v, int is_signed){
-    put_symbol_inline(c, state, v, is_signed);
+    put_symbol_inline(c, state, v, is_signed, NULL, NULL);
 }
 
 static inline av_flatten int get_symbol_inline(RangeCoder *c, uint8_t *state, int is_signed){
@@ -428,7 +506,7 @@ static inline int get_vlc_symbol(GetBitContext *gb, VlcState * const state, int
 }
 
 #if CONFIG_FFV1_ENCODER
-static inline int encode_line(FFV1Context *s, int w, int_fast16_t *sample[2], int plane_index, int bits){
+static av_always_inline int encode_line(FFV1Context *s, int w, int_fast16_t *sample[2], int plane_index, int bits){
     PlaneContext * const p= &s->plane[plane_index];
     RangeCoder * const c= &s->c;
     int x;
@@ -451,7 +529,7 @@ static inline int encode_line(FFV1Context *s, int w, int_fast16_t *sample[2], in
     for(x=0; x<w; x++){
         int diff, context;
 
-        context= get_context(s, sample[0]+x, sample[1]+x, sample[2]+x);
+        context= get_context(p, sample[0]+x, sample[1]+x, sample[2]+x);
         diff= sample[0][x] - predict(sample[0]+x, sample[1]+x);
 
         if(context < 0){
@@ -462,7 +540,11 @@ static inline int encode_line(FFV1Context *s, int w, int_fast16_t *sample[2], in
         diff= fold(diff, bits);
 
         if(s->ac){
-            put_symbol_inline(c, p->state[context], diff, 1);
+            if(s->flags & CODEC_FLAG_PASS1){
+                put_symbol_inline(c, p->state[context], diff, 1, s->rc_stat, s->rc_stat2[p->quant_table_index][context]);
+            }else{
+                put_symbol_inline(c, p->state[context], diff, 1, NULL, NULL);
+            }
         }else{
             if(context == 0) run_mode=1;
 
@@ -509,14 +591,14 @@ static inline int encode_line(FFV1Context *s, int w, int_fast16_t *sample[2], in
 static void encode_plane(FFV1Context *s, uint8_t *src, int w, int h, int stride, int plane_index){
     int x,y,i;
     const int ring_size= s->avctx->context_model ? 3 : 2;
-    int_fast16_t sample_buffer[ring_size][w+6], *sample[ring_size];
+    int_fast16_t *sample[3];
     s->run_index=0;
 
-    memset(sample_buffer, 0, sizeof(sample_buffer));
+    memset(s->sample_buffer, 0, ring_size*(w+6)*sizeof(*s->sample_buffer));
 
     for(y=0; y<h; y++){
         for(i=0; i<ring_size; i++)
-            sample[i]= sample_buffer[(h+i-y)%ring_size]+3;
+            sample[i]= s->sample_buffer + (w+6)*((h+i-y)%ring_size) + 3;
 
         sample[0][-1]= sample[1][0  ];
         sample[1][ w]= sample[1][w-1];
@@ -539,15 +621,15 @@ static void encode_plane(FFV1Context *s, uint8_t *src, int w, int h, int stride,
 static void encode_rgb_frame(FFV1Context *s, uint32_t *src, int w, int h, int stride){
     int x, y, p, i;
     const int ring_size= s->avctx->context_model ? 3 : 2;
-    int_fast16_t sample_buffer[3][ring_size][w+6], *sample[3][ring_size];
+    int_fast16_t *sample[3][3];
     s->run_index=0;
 
-    memset(sample_buffer, 0, sizeof(sample_buffer));
+    memset(s->sample_buffer, 0, ring_size*3*(w+6)*sizeof(*s->sample_buffer));
 
     for(y=0; y<h; y++){
         for(i=0; i<ring_size; i++)
             for(p=0; p<3; p++)
-                sample[p][i]= sample_buffer[p][(h+i-y)%ring_size]+3;
+                sample[p][i]= s->sample_buffer + p*ring_size*(w+6) + ((h+i-y)%ring_size)*(w+6) + 3;
 
         for(x=0; x<w; x++){
             int v= src[x + stride*y];
@@ -590,31 +672,50 @@ static void write_quant_table(RangeCoder *c, int16_t *quant_table){
     put_symbol(c, state, i-last-1, 0);
 }
 
+static void write_quant_tables(RangeCoder *c, int16_t quant_table[MAX_CONTEXT_INPUTS][256]){
+    int i;
+    for(i=0; i<5; i++)
+        write_quant_table(c, quant_table[i]);
+}
+
 static void write_header(FFV1Context *f){
     uint8_t state[CONTEXT_SIZE];
-    int i;
-    RangeCoder * const c= &f->c;
+    int i, j;
+    RangeCoder * const c= &f->slice_context[0]->c;
 
     memset(state, 128, sizeof(state));
 
-    put_symbol(c, state, f->version, 0);
-    put_symbol(c, state, f->ac, 0);
-    if(f->ac>1){
-        for(i=1; i<256; i++){
-            f->state_transition[i]=ver2_state[i];
-            put_symbol(c, state, ver2_state[i] - c->one_state[i], 1);
+    if(f->version < 2){
+        put_symbol(c, state, f->version, 0);
+        put_symbol(c, state, f->ac, 0);
+        if(f->ac>1){
+            for(i=1; i<256; i++){
+                put_symbol(c, state, f->state_transition[i] - c->one_state[i], 1);
+            }
+        }
+        put_symbol(c, state, f->colorspace, 0); //YUV cs type
+        if(f->version>0)
+            put_symbol(c, state, f->avctx->bits_per_raw_sample, 0);
+        put_rac(c, state, 1); //chroma planes
+            put_symbol(c, state, f->chroma_h_shift, 0);
+            put_symbol(c, state, f->chroma_v_shift, 0);
+        put_rac(c, state, 0); //no transparency plane
+
+        write_quant_tables(c, f->quant_table);
+    }else{
+        put_symbol(c, state, f->slice_count, 0);
+        for(i=0; i<f->slice_count; i++){
+            FFV1Context *fs= f->slice_context[i];
+            put_symbol(c, state, (fs->slice_x     +1)*f->num_h_slices / f->width   , 0);
+            put_symbol(c, state, (fs->slice_y     +1)*f->num_v_slices / f->height  , 0);
+            put_symbol(c, state, (fs->slice_width +1)*f->num_h_slices / f->width -1, 0);
+            put_symbol(c, state, (fs->slice_height+1)*f->num_v_slices / f->height-1, 0);
+            for(j=0; j<f->plane_count; j++){
+                put_symbol(c, state, f->plane[j].quant_table_index, 0);
+                av_assert0(f->plane[j].quant_table_index == f->avctx->context_model);
+            }
         }
     }
-    put_symbol(c, state, f->colorspace, 0); //YUV cs type
-    if(f->version>0)
-        put_symbol(c, state, f->avctx->bits_per_raw_sample, 0);
-    put_rac(c, state, 1); //chroma planes
-        put_symbol(c, state, f->chroma_h_shift, 0);
-        put_symbol(c, state, f->chroma_v_shift, 0);
-    put_rac(c, state, 0); //no transparency plane
-
-    for(i=0; i<5; i++)
-        write_quant_table(c, f->quant_table[i]);
 }
 #endif /* CONFIG_FFV1_ENCODER */
 
@@ -630,66 +731,237 @@ static av_cold int common_init(AVCodecContext *avctx){
     s->height= avctx->height;
 
     assert(s->width && s->height);
+    //defaults
+    s->num_h_slices=1;
+    s->num_v_slices=1;
+
+
+    return 0;
+}
+
+static int init_slice_state(FFV1Context *f){
+    int i, j;
+
+    for(i=0; i<f->slice_count; i++){
+        FFV1Context *fs= f->slice_context[i];
+        for(j=0; j<f->plane_count; j++){
+            PlaneContext * const p= &fs->plane[j];
+
+            if(fs->ac){
+                if(!p->    state) p->    state= av_malloc(CONTEXT_SIZE*p->context_count*sizeof(uint8_t));
+                if(!p->    state)
+                    return AVERROR(ENOMEM);
+            }else{
+                if(!p->vlc_state) p->vlc_state= av_malloc(p->context_count*sizeof(VlcState));
+                if(!p->vlc_state)
+                    return AVERROR(ENOMEM);
+            }
+        }
+
+        if (fs->ac>1){
+            //FIXME only redo if state_transition changed
+            for(j=1; j<256; j++){
+                fs->c.one_state [    j]= fs->state_transition[j];
+                fs->c.zero_state[256-j]= 256-fs->c.one_state [j];
+            }
+        }
+    }
 
     return 0;
 }
 
+static av_cold int init_slice_contexts(FFV1Context *f){
+    int i;
+
+    f->slice_count= f->num_h_slices * f->num_v_slices;
+
+    for(i=0; i<f->slice_count; i++){
+        FFV1Context *fs= av_mallocz(sizeof(*fs));
+        int sx= i % f->num_h_slices;
+        int sy= i / f->num_h_slices;
+        int sxs= f->avctx->width * sx    / f->num_h_slices;
+        int sxe= f->avctx->width *(sx+1) / f->num_h_slices;
+        int sys= f->avctx->height* sy    / f->num_v_slices;
+        int sye= f->avctx->height*(sy+1) / f->num_v_slices;
+        f->slice_context[i]= fs;
+        memcpy(fs, f, sizeof(*fs));
+        memset(fs->rc_stat2, 0, sizeof(fs->rc_stat2));
+
+        fs->slice_width = sxe - sxs;
+        fs->slice_height= sye - sys;
+        fs->slice_x     = sxs;
+        fs->slice_y     = sys;
+
+        fs->sample_buffer = av_malloc(9 * (fs->width+6) * sizeof(*fs->sample_buffer));
+        if (!fs->sample_buffer)
+            return AVERROR(ENOMEM);
+    }
+    return 0;
+}
+
+static int allocate_initial_states(FFV1Context *f){
+    int i;
+
+    for(i=0; i<f->quant_table_count; i++){
+        f->initial_states[i]= av_malloc(f->context_count[i]*sizeof(*f->initial_states[i]));
+        if(!f->initial_states[i])
+            return AVERROR(ENOMEM);
+        memset(f->initial_states[i], 128, f->context_count[i]*sizeof(*f->initial_states[i]));
+    }
+    return 0;
+}
+
 #if CONFIG_FFV1_ENCODER
+static int write_extra_header(FFV1Context *f){
+    RangeCoder * const c= &f->c;
+    uint8_t state[CONTEXT_SIZE];
+    int i, j, k;
+    uint8_t state2[32][CONTEXT_SIZE];
+
+    memset(state2, 128, sizeof(state2));
+    memset(state, 128, sizeof(state));
+
+    f->avctx->extradata= av_malloc(f->avctx->extradata_size= 10000 + (11*11*5*5*5+11*11*11)*32);
+    ff_init_range_encoder(c, f->avctx->extradata, f->avctx->extradata_size);
+    ff_build_rac_states(c, 0.05*(1LL<<32), 256-8);
+
+    put_symbol(c, state, f->version, 0);
+    put_symbol(c, state, f->ac, 0);
+    if(f->ac>1){
+        for(i=1; i<256; i++){
+            put_symbol(c, state, f->state_transition[i] - c->one_state[i], 1);
+        }
+    }
+    put_symbol(c, state, f->colorspace, 0); //YUV cs type
+    put_symbol(c, state, f->avctx->bits_per_raw_sample, 0);
+    put_rac(c, state, 1); //chroma planes
+        put_symbol(c, state, f->chroma_h_shift, 0);
+        put_symbol(c, state, f->chroma_v_shift, 0);
+    put_rac(c, state, 0); //no transparency plane
+    put_symbol(c, state, f->num_h_slices-1, 0);
+    put_symbol(c, state, f->num_v_slices-1, 0);
+
+    put_symbol(c, state, f->quant_table_count, 0);
+    for(i=0; i<f->quant_table_count; i++)
+        write_quant_tables(c, f->quant_tables[i]);
+
+    for(i=0; i<f->quant_table_count; i++){
+        for(j=0; j<f->context_count[i]*CONTEXT_SIZE; j++)
+            if(f->initial_states[i] && f->initial_states[i][0][j] != 128)
+                break;
+        if(j<f->context_count[i]*CONTEXT_SIZE){
+            put_rac(c, state, 1);
+            for(j=0; j<f->context_count[i]; j++){
+                for(k=0; k<CONTEXT_SIZE; k++){
+                    int pred= j ? f->initial_states[i][j-1][k] : 128;
+                    put_symbol(c, state2[k], (int8_t)(f->initial_states[i][j][k]-pred), 1);
+                }
+            }
+        }else{
+            put_rac(c, state, 0);
+        }
+    }
+
+    f->avctx->extradata_size= ff_rac_terminate(c);
+
+    return 0;
+}
+
+static int sort_stt(FFV1Context *s, uint8_t stt[256]){
+    int i,i2,changed,print=0;
+
+    do{
+        changed=0;
+        for(i=12; i<244; i++){
+            for(i2=i+1; i2<245 && i2<i+4; i2++){
+#define COST(old, new) \
+    s->rc_stat[old][0]*-log2((256-(new))/256.0)\
+   +s->rc_stat[old][1]*-log2(     (new) /256.0)
+
+#define COST2(old, new) \
+    COST(old, new)\
+   +COST(256-(old), 256-(new))
+
+                double size0= COST2(i, i ) + COST2(i2, i2);
+                double sizeX= COST2(i, i2) + COST2(i2, i );
+                if(sizeX < size0 && i!=128 && i2!=128){
+                    int j;
+                    FFSWAP(int, stt[    i], stt[    i2]);
+                    FFSWAP(int, s->rc_stat[i    ][0],s->rc_stat[    i2][0]);
+                    FFSWAP(int, s->rc_stat[i    ][1],s->rc_stat[    i2][1]);
+                    if(i != 256-i2){
+                        FFSWAP(int, stt[256-i], stt[256-i2]);
+                        FFSWAP(int, s->rc_stat[256-i][0],s->rc_stat[256-i2][0]);
+                        FFSWAP(int, s->rc_stat[256-i][1],s->rc_stat[256-i2][1]);
+                    }
+                    for(j=1; j<256; j++){
+                        if     (stt[j] == i ) stt[j] = i2;
+                        else if(stt[j] == i2) stt[j] = i ;
+                        if(i != 256-i2){
+                            if     (stt[256-j] == 256-i ) stt[256-j] = 256-i2;
+                            else if(stt[256-j] == 256-i2) stt[256-j] = 256-i ;
+                        }
+                    }
+                    print=changed=1;
+                }
+            }
+        }
+    }while(changed);
+    return print;
+}
+
 static av_cold int encode_init(AVCodecContext *avctx)
 {
     FFV1Context *s = avctx->priv_data;
-    int i;
+    int i, j, k, m;
 
     common_init(avctx);
 
     s->version=0;
     s->ac= avctx->coder_type ? 2:0;
 
+    if(s->ac>1)
+        for(i=1; i<256; i++)
+            s->state_transition[i]=ver2_state[i];
+
     s->plane_count=2;
     for(i=0; i<256; i++){
+        s->quant_table_count=2;
         if(avctx->bits_per_raw_sample <=8){
-            s->quant_table[0][i]=           quant11[i];
-            s->quant_table[1][i]=        11*quant11[i];
-            if(avctx->context_model==0){
-                s->quant_table[2][i]=     11*11*quant11[i];
-                s->quant_table[3][i]=
-                s->quant_table[4][i]=0;
-            }else{
-                s->quant_table[2][i]=     11*11*quant5 [i];
-                s->quant_table[3][i]=   5*11*11*quant5 [i];
-                s->quant_table[4][i]= 5*5*11*11*quant5 [i];
-            }
+            s->quant_tables[0][0][i]=           quant11[i];
+            s->quant_tables[0][1][i]=        11*quant11[i];
+            s->quant_tables[0][2][i]=     11*11*quant11[i];
+            s->quant_tables[1][0][i]=           quant11[i];
+            s->quant_tables[1][1][i]=        11*quant11[i];
+            s->quant_tables[1][2][i]=     11*11*quant5 [i];
+            s->quant_tables[1][3][i]=   5*11*11*quant5 [i];
+            s->quant_tables[1][4][i]= 5*5*11*11*quant5 [i];
         }else{
-            s->quant_table[0][i]=           quant9_10bit[i];
-            s->quant_table[1][i]=        11*quant9_10bit[i];
-            if(avctx->context_model==0){
-                s->quant_table[2][i]=     11*11*quant9_10bit[i];
-                s->quant_table[3][i]=
-                s->quant_table[4][i]=0;
-            }else{
-                s->quant_table[2][i]=     11*11*quant5_10bit[i];
-                s->quant_table[3][i]=   5*11*11*quant5_10bit[i];
-                s->quant_table[4][i]= 5*5*11*11*quant5_10bit[i];
-            }
+            s->quant_tables[0][0][i]=           quant9_10bit[i];
+            s->quant_tables[0][1][i]=        11*quant9_10bit[i];
+            s->quant_tables[0][2][i]=     11*11*quant9_10bit[i];
+            s->quant_tables[1][0][i]=           quant9_10bit[i];
+            s->quant_tables[1][1][i]=        11*quant9_10bit[i];
+            s->quant_tables[1][2][i]=     11*11*quant5_10bit[i];
+            s->quant_tables[1][3][i]=   5*11*11*quant5_10bit[i];
+            s->quant_tables[1][4][i]= 5*5*11*11*quant5_10bit[i];
         }
     }
+    s->context_count[0]= (11*11*11+1)/2;
+    s->context_count[1]= (11*11*5*5*5+1)/2;
+    memcpy(s->quant_table, s->quant_tables[avctx->context_model], sizeof(s->quant_table));
 
     for(i=0; i<s->plane_count; i++){
         PlaneContext * const p= &s->plane[i];
 
-        if(avctx->context_model==0){
-            p->context_count= (11*11*11+1)/2;
-        }else{
-            p->context_count= (11*11*5*5*5+1)/2;
-        }
-
-        if(s->ac){
-            if(!p->state) p->state= av_malloc(CONTEXT_SIZE*p->context_count*sizeof(uint8_t));
-        }else{
-            if(!p->vlc_state) p->vlc_state= av_malloc(p->context_count*sizeof(VlcState));
-        }
+        memcpy(p->quant_table, s->quant_table, sizeof(p->quant_table));
+        p->quant_table_index= avctx->context_model;
+        p->context_count= s->context_count[p->quant_table_index];
     }
 
+    if(allocate_initial_states(s) < 0)
+        return AVERROR(ENOMEM);
+
     avctx->coded_frame= &s->picture;
     switch(avctx->pix_fmt){
     case PIX_FMT_YUV444P16:
@@ -703,7 +975,7 @@ static av_cold int encode_init(AVCodecContext *avctx)
             av_log(avctx, AV_LOG_ERROR, "bits_per_raw_sample of more than 8 needs -coder 1 currently\n");
             return -1;
         }
-        s->version= 1;
+        s->version= FFMAX(s->version, 1);
     case PIX_FMT_YUV444P:
     case PIX_FMT_YUV422P:
     case PIX_FMT_YUV420P:
@@ -722,43 +994,167 @@ static av_cold int encode_init(AVCodecContext *avctx)
 
     s->picture_number=0;
 
+    if(avctx->flags & (CODEC_FLAG_PASS1|CODEC_FLAG_PASS2)){
+        for(i=0; i<s->quant_table_count; i++){
+            s->rc_stat2[i]= av_mallocz(s->context_count[i]*sizeof(*s->rc_stat2[i]));
+            if(!s->rc_stat2[i])
+                return AVERROR(ENOMEM);
+        }
+    }
+    if(avctx->stats_in){
+        char *p= avctx->stats_in;
+        uint8_t best_state[256][256];
+        int gob_count=0;
+        char *next;
+
+        av_assert0(s->version>=2);
+
+        for(;;){
+            for(j=0; j<256; j++){
+                for(i=0; i<2; i++){
+                    s->rc_stat[j][i]= strtol(p, &next, 0);
+                    if(next==p){
+                        av_log(avctx, AV_LOG_ERROR, "2Pass file invalid at %d %d [%s]\n", j,i,p);
+                        return -1;
+                    }
+                    p=next;
+                }
+            }
+            for(i=0; i<s->quant_table_count; i++){
+                for(j=0; j<s->context_count[i]; j++){
+                    for(k=0; k<32; k++){
+                        for(m=0; m<2; m++){
+                            s->rc_stat2[i][j][k][m]= strtol(p, &next, 0);
+                            if(next==p){
+                                av_log(avctx, AV_LOG_ERROR, "2Pass file invalid at %d %d %d %d [%s]\n", i,j,k,m,p);
+                                return -1;
+                            }
+                            p=next;
+                        }
+                    }
+                }
+            }
+            gob_count= strtol(p, &next, 0);
+            if(next==p || gob_count <0){
+                av_log(avctx, AV_LOG_ERROR, "2Pass file invalid\n");
+                return -1;
+            }
+            p=next;
+            while(*p=='\n' || *p==' ') p++;
+            if(p[0]==0) break;
+        }
+        sort_stt(s, s->state_transition);
+
+        find_best_state(best_state, s->state_transition);
+
+        for(i=0; i<s->quant_table_count; i++){
+            for(j=0; j<s->context_count[i]; j++){
+                for(k=0; k<32; k++){
+                    double p= 128;
+                    if(s->rc_stat2[i][j][k][0]+s->rc_stat2[i][j][k][1]){
+                        p=256.0*s->rc_stat2[i][j][k][1] / (s->rc_stat2[i][j][k][0]+s->rc_stat2[i][j][k][1]);
+                    }
+                    s->initial_states[i][j][k]= best_state[av_clip(round(p), 1, 255)][av_clip((s->rc_stat2[i][j][k][0]+s->rc_stat2[i][j][k][1])/gob_count, 0, 255)];
+                }
+            }
+        }
+    }
+
+    if(s->version>1){
+        s->num_h_slices=2;
+        s->num_v_slices=2;
+        write_extra_header(s);
+    }
+
+    if(init_slice_contexts(s) < 0)
+        return -1;
+    if(init_slice_state(s) < 0)
+        return -1;
+
+#define STATS_OUT_SIZE 1024*1024*6
+    if(avctx->flags & CODEC_FLAG_PASS1){
+        avctx->stats_out= av_mallocz(STATS_OUT_SIZE);
+        for(i=0; i<s->quant_table_count; i++){
+            for(j=0; j<s->slice_count; j++){
+                FFV1Context *sf= s->slice_context[j];
+                av_assert0(!sf->rc_stat2[i]);
+                sf->rc_stat2[i]= av_mallocz(s->context_count[i]*sizeof(*sf->rc_stat2[i]));
+                if(!sf->rc_stat2[i])
+                    return AVERROR(ENOMEM);
+            }
+        }
+    }
+
     return 0;
 }
 #endif /* CONFIG_FFV1_ENCODER */
 
 
 static void clear_state(FFV1Context *f){
-    int i, j;
+    int i, si, j;
 
-    for(i=0; i<f->plane_count; i++){
-        PlaneContext *p= &f->plane[i];
+    for(si=0; si<f->slice_count; si++){
+        FFV1Context *fs= f->slice_context[si];
+        for(i=0; i<f->plane_count; i++){
+            PlaneContext *p= &fs->plane[i];
 
-        p->interlace_bit_state[0]= 128;
-        p->interlace_bit_state[1]= 128;
+            p->interlace_bit_state[0]= 128;
+            p->interlace_bit_state[1]= 128;
 
-        for(j=0; j<p->context_count; j++){
-            if(f->ac){
-                memset(p->state[j], 128, sizeof(uint8_t)*CONTEXT_SIZE);
+            if(fs->ac){
+                if(f->initial_states[p->quant_table_index]){
+                    memcpy(p->state, f->initial_states[p->quant_table_index], CONTEXT_SIZE*p->context_count);
+                }else
+                memset(p->state, 128, CONTEXT_SIZE*p->context_count);
             }else{
-                p->vlc_state[j].drift= 0;
-                p->vlc_state[j].error_sum= 4; //FFMAX((RANGE + 32)/64, 2);
-                p->vlc_state[j].bias= 0;
-                p->vlc_state[j].count= 1;
+            for(j=0; j<p->context_count; j++){
+                    p->vlc_state[j].drift= 0;
+                    p->vlc_state[j].error_sum= 4; //FFMAX((RANGE + 32)/64, 2);
+                    p->vlc_state[j].bias= 0;
+                    p->vlc_state[j].count= 1;
+            }
             }
         }
     }
 }
 
 #if CONFIG_FFV1_ENCODER
+static int encode_slice(AVCodecContext *c, void *arg){
+    FFV1Context *fs= *(void**)arg;
+    FFV1Context *f= fs->avctx->priv_data;
+    int width = fs->slice_width;
+    int height= fs->slice_height;
+    int x= fs->slice_x;
+    int y= fs->slice_y;
+    AVFrame * const p= &f->picture;
+
+    if(f->colorspace==0){
+        const int chroma_width = -((-width )>>f->chroma_h_shift);
+        const int chroma_height= -((-height)>>f->chroma_v_shift);
+        const int cx= x>>f->chroma_h_shift;
+        const int cy= y>>f->chroma_v_shift;
+
+        encode_plane(fs, p->data[0] + x + y*p->linesize[0], width, height, p->linesize[0], 0);
+
+        encode_plane(fs, p->data[1] + cx+cy*p->linesize[1], chroma_width, chroma_height, p->linesize[1], 1);
+        encode_plane(fs, p->data[2] + cx+cy*p->linesize[2], chroma_width, chroma_height, p->linesize[2], 1);
+    }else{
+        encode_rgb_frame(fs, (uint32_t*)(p->data[0]) + x + y*(p->linesize[0]/4), width, height, p->linesize[0]/4);
+    }
+    emms_c();
+
+    return 0;
+}
+
 static int encode_frame(AVCodecContext *avctx, unsigned char *buf, int buf_size, void *data){
     FFV1Context *f = avctx->priv_data;
-    RangeCoder * const c= &f->c;
+    RangeCoder * const c= &f->slice_context[0]->c;
     AVFrame *pict = data;
-    const int width= f->width;
-    const int height= f->height;
     AVFrame * const p= &f->picture;
     int used_count= 0;
     uint8_t keystate=128;
+    uint8_t *buf_p;
+    int i;
 
     ff_init_range_encoder(c, buf, buf_size);
     ff_build_rac_states(c, 0.05*(1LL<<32), 256-8);
@@ -769,6 +1165,7 @@ static int encode_frame(AVCodecContext *avctx, unsigned char *buf, int buf_size,
     if(avctx->gop_size==0 || f->picture_number % avctx->gop_size == 0){
         put_rac(c, &keystate, 1);
         p->key_frame= 1;
+        f->gob_count++;
         write_header(f);
         clear_state(f);
     }else{
@@ -779,7 +1176,7 @@ static int encode_frame(AVCodecContext *avctx, unsigned char *buf, int buf_size,
     if(!f->ac){
         used_count += ff_rac_terminate(c);
 //printf("pos=%d\n", used_count);
-        init_put_bits(&f->pb, buf + used_count, buf_size - used_count);
+        init_put_bits(&f->slice_context[0]->pb, buf + used_count, buf_size - used_count);
     }else if (f->ac>1){
         int i;
         for(i=1; i<256; i++){
@@ -788,39 +1185,121 @@ static int encode_frame(AVCodecContext *avctx, unsigned char *buf, int buf_size,
         }
     }
 
-    if(f->colorspace==0){
-        const int chroma_width = -((-width )>>f->chroma_h_shift);
-        const int chroma_height= -((-height)>>f->chroma_v_shift);
+    for(i=1; i<f->slice_count; i++){
+        FFV1Context *fs= f->slice_context[i];
+        uint8_t *start= buf + (buf_size-used_count)*i/f->slice_count;
+        int len= buf_size/f->slice_count;
 
-        encode_plane(f, p->data[0], width, height, p->linesize[0], 0);
-
-        encode_plane(f, p->data[1], chroma_width, chroma_height, p->linesize[1], 1);
-        encode_plane(f, p->data[2], chroma_width, chroma_height, p->linesize[2], 1);
-    }else{
-        encode_rgb_frame(f, (uint32_t*)(p->data[0]), width, height, p->linesize[0]/4);
+        if(fs->ac){
+            ff_init_range_encoder(&fs->c, start, len);
+        }else{
+            init_put_bits(&fs->pb, start, len);
+        }
     }
-    emms_c();
+    avctx->execute(avctx, encode_slice, &f->slice_context[0], NULL, f->slice_count, sizeof(void*));
 
-    f->picture_number++;
+    buf_p=buf;
+    for(i=0; i<f->slice_count; i++){
+        FFV1Context *fs= f->slice_context[i];
+        int bytes;
 
-    if(f->ac){
-        return ff_rac_terminate(c);
-    }else{
-        flush_put_bits(&f->pb); //nicer padding FIXME
-        return used_count + (put_bits_count(&f->pb)+7)/8;
+        if(fs->ac){
+            uint8_t state=128;
+            put_rac(&fs->c, &state, 0);
+            bytes= ff_rac_terminate(&fs->c);
+        }else{
+            flush_put_bits(&fs->pb); //nicer padding FIXME
+            bytes= used_count + (put_bits_count(&fs->pb)+7)/8;
+            used_count= 0;
+        }
+        if(i>0){
+            av_assert0(bytes < buf_size/f->slice_count);
+            memmove(buf_p, fs->ac ? fs->c.bytestream_start : fs->pb.buf, bytes);
+            av_assert0(bytes < (1<<24));
+            AV_WB24(buf_p+bytes, bytes);
+            bytes+=3;
+        }
+        buf_p += bytes;
     }
+
+    if((avctx->flags&CODEC_FLAG_PASS1) && (f->picture_number&31)==0){
+        int j, k, m;
+        char *p= avctx->stats_out;
+        char *end= p + STATS_OUT_SIZE;
+
+        memset(f->rc_stat, 0, sizeof(f->rc_stat));
+        for(i=0; i<f->quant_table_count; i++)
+            memset(f->rc_stat2[i], 0, f->context_count[i]*sizeof(*f->rc_stat2[i]));
+
+        for(j=0; j<f->slice_count; j++){
+            FFV1Context *fs= f->slice_context[j];
+            for(i=0; i<256; i++){
+                f->rc_stat[i][0] += fs->rc_stat[i][0];
+                f->rc_stat[i][1] += fs->rc_stat[i][1];
+            }
+            for(i=0; i<f->quant_table_count; i++){
+                for(k=0; k<f->context_count[i]; k++){
+                    for(m=0; m<32; m++){
+                        f->rc_stat2[i][k][m][0] += fs->rc_stat2[i][k][m][0];
+                        f->rc_stat2[i][k][m][1] += fs->rc_stat2[i][k][m][1];
+                    }
+                }
+            }
+        }
+
+        for(j=0; j<256; j++){
+            snprintf(p, end-p, "%"PRIu64" %"PRIu64" ", f->rc_stat[j][0], f->rc_stat[j][1]);
+            p+= strlen(p);
+        }
+        snprintf(p, end-p, "\n");
+
+        for(i=0; i<f->quant_table_count; i++){
+            for(j=0; j<f->context_count[i]; j++){
+                for(m=0; m<32; m++){
+                    snprintf(p, end-p, "%"PRIu64" %"PRIu64" ", f->rc_stat2[i][j][m][0], f->rc_stat2[i][j][m][1]);
+                    p+= strlen(p);
+                }
+            }
+        }
+        snprintf(p, end-p, "%d\n", f->gob_count);
+    } else if(avctx->flags&CODEC_FLAG_PASS1)
+        avctx->stats_out[0] = '\0';
+
+    f->picture_number++;
+    return buf_p-buf;
 }
 #endif /* CONFIG_FFV1_ENCODER */
 
 static av_cold int common_end(AVCodecContext *avctx){
     FFV1Context *s = avctx->priv_data;
-    int i;
+    int i, j;
 
-    for(i=0; i<s->plane_count; i++){
-        PlaneContext *p= &s->plane[i];
+    if (avctx->codec->decode && s->picture.data[0])
+        avctx->release_buffer(avctx, &s->picture);
 
-        av_freep(&p->state);
-        av_freep(&p->vlc_state);
+    for(j=0; j<s->slice_count; j++){
+        FFV1Context *fs= s->slice_context[j];
+        for(i=0; i<s->plane_count; i++){
+            PlaneContext *p= &fs->plane[i];
+
+            av_freep(&p->state);
+            av_freep(&p->vlc_state);
+        }
+        av_freep(&fs->sample_buffer);
+    }
+
+    av_freep(&avctx->stats_out);
+    for(j=0; j<s->quant_table_count; j++){
+        av_freep(&s->initial_states[j]);
+        for(i=0; i<s->slice_count; i++){
+            FFV1Context *sf= s->slice_context[i];
+            av_freep(&sf->rc_stat2[j]);
+        }
+        av_freep(&s->rc_stat2[j]);
+    }
+
+    for(i=0; i<s->slice_count; i++){
+        av_freep(&s->slice_context[i]);
     }
 
     return 0;
@@ -837,13 +1316,14 @@ static av_always_inline void decode_line(FFV1Context *s, int w, int_fast16_t *sa
     for(x=0; x<w; x++){
         int diff, context, sign;
 
-        context= get_context(s, sample[1] + x, sample[0] + x, sample[1] + x);
+        context= get_context(p, sample[1] + x, sample[0] + x, sample[1] + x);
         if(context < 0){
             context= -context;
             sign=1;
         }else
             sign=0;
 
+        av_assert2(context < p->context_count);
 
         if(s->ac){
             diff= get_symbol_inline(c, p->state[context], 1);
@@ -885,14 +1365,13 @@ static av_always_inline void decode_line(FFV1Context *s, int w, int_fast16_t *sa
 
 static void decode_plane(FFV1Context *s, uint8_t *src, int w, int h, int stride, int plane_index){
     int x, y;
-    int_fast16_t sample_buffer[2][w+6];
     int_fast16_t *sample[2];
-    sample[0]=sample_buffer[0]+3;
-    sample[1]=sample_buffer[1]+3;
+    sample[0]=s->sample_buffer    +3;
+    sample[1]=s->sample_buffer+w+6+3;
 
     s->run_index=0;
 
-    memset(sample_buffer, 0, sizeof(sample_buffer));
+    memset(s->sample_buffer, 0, 2*(w+6)*sizeof(*s->sample_buffer));
 
     for(y=0; y<h; y++){
         int_fast16_t *temp= sample[0]; //FIXME try a normal buffer
@@ -921,16 +1400,15 @@ static void decode_plane(FFV1Context *s, uint8_t *src, int w, int h, int stride,
 
 static void decode_rgb_frame(FFV1Context *s, uint32_t *src, int w, int h, int stride){
     int x, y, p;
-    int_fast16_t sample_buffer[3][2][w+6];
     int_fast16_t *sample[3][2];
     for(x=0; x<3; x++){
-        sample[x][0] = sample_buffer[x][0]+3;
-        sample[x][1] = sample_buffer[x][1]+3;
+        sample[x][0] = s->sample_buffer +  x*2   *(w+6) + 3;
+        sample[x][1] = s->sample_buffer + (x*2+1)*(w+6) + 3;
     }
 
     s->run_index=0;
 
-    memset(sample_buffer, 0, sizeof(sample_buffer));
+    memset(s->sample_buffer, 0, 6*(w+6)*sizeof(*s->sample_buffer));
 
     for(y=0; y<h; y++){
         for(p=0; p<3; p++){
@@ -957,11 +1435,39 @@ static void decode_rgb_frame(FFV1Context *s, uint32_t *src, int w, int h, int st
             b += g;
             r += g;
 
-            src[x + stride*y]= b + (g<<8) + (r<<16);
+            src[x + stride*y]= b + (g<<8) + (r<<16) + (0xFF<<24);
         }
     }
 }
 
+static int decode_slice(AVCodecContext *c, void *arg){
+    FFV1Context *fs= *(void**)arg;
+    FFV1Context *f= fs->avctx->priv_data;
+    int width = fs->slice_width;
+    int height= fs->slice_height;
+    int x= fs->slice_x;
+    int y= fs->slice_y;
+    AVFrame * const p= &f->picture;
+
+    av_assert1(width && height);
+    if(f->colorspace==0){
+        const int chroma_width = -((-width )>>f->chroma_h_shift);
+        const int chroma_height= -((-height)>>f->chroma_v_shift);
+        const int cx= x>>f->chroma_h_shift;
+        const int cy= y>>f->chroma_v_shift;
+        decode_plane(fs, p->data[0] + x + y*p->linesize[0], width, height, p->linesize[0], 0);
+
+        decode_plane(fs, p->data[1] + cx+cy*p->linesize[1], chroma_width, chroma_height, p->linesize[1], 1);
+        decode_plane(fs, p->data[2] + cx+cy*p->linesize[1], chroma_width, chroma_height, p->linesize[2], 1);
+    }else{
+        decode_rgb_frame(fs, (uint32_t*)p->data[0] + x + y*(p->linesize[0]/4), width, height, p->linesize[0]/4);
+    }
+
+    emms_c();
+
+    return 0;
+}
+
 static int read_quant_table(RangeCoder *c, int16_t *quant_table, int scale){
     int v;
     int i=0;
@@ -990,13 +1496,31 @@ static int read_quant_table(RangeCoder *c, int16_t *quant_table, int scale){
     return 2*v - 1;
 }
 
-static int read_header(FFV1Context *f){
-    uint8_t state[CONTEXT_SIZE];
-    int i, context_count;
+static int read_quant_tables(RangeCoder *c, int16_t quant_table[MAX_CONTEXT_INPUTS][256]){
+    int i;
+    int context_count=1;
+
+    for(i=0; i<5; i++){
+        context_count*= read_quant_table(c, quant_table[i], context_count);
+        if(context_count > 32768U){
+            return -1;
+        }
+    }
+    return (context_count+1)/2;
+}
+
+static int read_extra_header(FFV1Context *f){
     RangeCoder * const c= &f->c;
+    uint8_t state[CONTEXT_SIZE];
+    int i, j, k;
+    uint8_t state2[32][CONTEXT_SIZE];
 
+    memset(state2, 128, sizeof(state2));
     memset(state, 128, sizeof(state));
 
+    ff_init_range_decoder(c, f->avctx->extradata, f->avctx->extradata_size);
+    ff_build_rac_states(c, 0.05*(1LL<<32), 256-8);
+
     f->version= get_symbol(c, state, 0);
     f->ac= f->avctx->coder_type= get_symbol(c, state, 0);
     if(f->ac>1){
@@ -1005,13 +1529,70 @@ static int read_header(FFV1Context *f){
         }
     }
     f->colorspace= get_symbol(c, state, 0); //YUV cs type
-    if(f->version>0)
-        f->avctx->bits_per_raw_sample= get_symbol(c, state, 0);
+    f->avctx->bits_per_raw_sample= get_symbol(c, state, 0);
     get_rac(c, state); //no chroma = false
     f->chroma_h_shift= get_symbol(c, state, 0);
     f->chroma_v_shift= get_symbol(c, state, 0);
     get_rac(c, state); //transparency plane
     f->plane_count= 2;
+    f->num_h_slices= 1 + get_symbol(c, state, 0);
+    f->num_v_slices= 1 + get_symbol(c, state, 0);
+    if(f->num_h_slices > (unsigned)f->width || f->num_v_slices > (unsigned)f->height){
+        av_log(f->avctx, AV_LOG_ERROR, "too many slices\n");
+        return -1;
+    }
+
+    f->quant_table_count= get_symbol(c, state, 0);
+    if(f->quant_table_count > (unsigned)MAX_QUANT_TABLES)
+        return -1;
+    for(i=0; i<f->quant_table_count; i++){
+        if((f->context_count[i]= read_quant_tables(c, f->quant_tables[i])) < 0){
+            av_log(f->avctx, AV_LOG_ERROR, "read_quant_table error\n");
+            return -1;
+        }
+    }
+
+    if(allocate_initial_states(f) < 0)
+        return AVERROR(ENOMEM);
+
+    for(i=0; i<f->quant_table_count; i++){
+        if(get_rac(c, state)){
+            for(j=0; j<f->context_count[i]; j++){
+                for(k=0; k<CONTEXT_SIZE; k++){
+                    int pred= j ? f->initial_states[i][j-1][k] : 128;
+                    f->initial_states[i][j][k]= (pred+get_symbol(c, state2[k], 1))&0xFF;
+                }
+            }
+        }
+    }
+
+    return 0;
+}
+
+static int read_header(FFV1Context *f){
+    uint8_t state[CONTEXT_SIZE];
+    int i, j, context_count;
+    RangeCoder * const c= &f->slice_context[0]->c;
+
+    memset(state, 128, sizeof(state));
+
+    if(f->version < 2){
+        f->version= get_symbol(c, state, 0);
+        f->ac= f->avctx->coder_type= get_symbol(c, state, 0);
+        if(f->ac>1){
+            for(i=1; i<256; i++){
+                f->state_transition[i]= get_symbol(c, state, 1) + c->one_state[i];
+            }
+        }
+        f->colorspace= get_symbol(c, state, 0); //YUV cs type
+        if(f->version>0)
+            f->avctx->bits_per_raw_sample= get_symbol(c, state, 0);
+        get_rac(c, state); //no chroma = false
+        f->chroma_h_shift= get_symbol(c, state, 0);
+        f->chroma_v_shift= get_symbol(c, state, 0);
+        get_rac(c, state); //transparency plane
+        f->plane_count= 2;
+    }
 
     if(f->colorspace==0){
         if(f->avctx->bits_per_raw_sample<=8){
@@ -1047,26 +1628,60 @@ static int read_header(FFV1Context *f){
     }
 
 //printf("%d %d %d\n", f->chroma_h_shift, f->chroma_v_shift,f->avctx->pix_fmt);
-
-    context_count=1;
-    for(i=0; i<5; i++){
-        context_count*= read_quant_table(c, f->quant_table[i], context_count);
-        if(context_count < 0 || context_count > 32768){
-            av_log(f->avctx, AV_LOG_ERROR, "read_quant_table error\n");
-            return -1;
+    if(f->version < 2){
+        context_count= read_quant_tables(c, f->quant_table);
+        if(context_count < 0){
+                av_log(f->avctx, AV_LOG_ERROR, "read_quant_table error\n");
+                return -1;
         }
+    }else{
+        f->slice_count= get_symbol(c, state, 0);
+        if(f->slice_count > (unsigned)MAX_SLICES)
+            return -1;
     }
-    context_count= (context_count+1)/2;
 
-    for(i=0; i<f->plane_count; i++){
-        PlaneContext * const p= &f->plane[i];
+    for(j=0; j<f->slice_count; j++){
+        FFV1Context *fs= f->slice_context[j];
+        fs->ac= f->ac;
+
+        if(f->version >= 2){
+            fs->slice_x     = get_symbol(c, state, 0)   *f->width ;
+            fs->slice_y     = get_symbol(c, state, 0)   *f->height;
+            fs->slice_width =(get_symbol(c, state, 0)+1)*f->width  + fs->slice_x;
+            fs->slice_height=(get_symbol(c, state, 0)+1)*f->height + fs->slice_y;
+
+            fs->slice_x /= f->num_h_slices;
+            fs->slice_y /= f->num_v_slices;
+            fs->slice_width  = fs->slice_width /f->num_h_slices - fs->slice_x;
+            fs->slice_height = fs->slice_height/f->num_v_slices - fs->slice_y;
+            if((unsigned)fs->slice_width > f->width || (unsigned)fs->slice_height > f->height)
+                return -1;
+            if(    (unsigned)fs->slice_x + (uint64_t)fs->slice_width  > f->width
+                || (unsigned)fs->slice_y + (uint64_t)fs->slice_height > f->height)
+                return -1;
+        }
 
-        p->context_count= context_count;
+        for(i=0; i<f->plane_count; i++){
+            PlaneContext * const p= &fs->plane[i];
 
-        if(f->ac){
-            if(!p->state) p->state= av_malloc(CONTEXT_SIZE*p->context_count*sizeof(uint8_t));
-        }else{
-            if(!p->vlc_state) p->vlc_state= av_malloc(p->context_count*sizeof(VlcState));
+            if(f->version >= 2){
+                int idx=get_symbol(c, state, 0);
+                if(idx > (unsigned)f->quant_table_count){
+                    av_log(f->avctx, AV_LOG_ERROR, "quant_table_index out of range\n");
+                    return -1;
+                }
+                p->quant_table_index= idx;
+                memcpy(p->quant_table, f->quant_tables[idx], sizeof(p->quant_table));
+                context_count= f->context_count[idx];
+            }else{
+                memcpy(p->quant_table, f->quant_table, sizeof(p->quant_table));
+            }
+
+            if(p->context_count < context_count){
+                av_freep(&p->state);
+                av_freep(&p->vlc_state);
+            }
+            p->context_count= context_count;
         }
     }
 
@@ -1075,10 +1690,16 @@ static int read_header(FFV1Context *f){
 
 static av_cold int decode_init(AVCodecContext *avctx)
 {
-//    FFV1Context *s = avctx->priv_data;
+    FFV1Context *f = avctx->priv_data;
 
     common_init(avctx);
 
+    if(avctx->extradata && read_extra_header(f) < 0)
+        return -1;
+
+    if(init_slice_contexts(f) < 0)
+        return -1;
+
     return 0;
 }
 
@@ -1086,15 +1707,18 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPac
     const uint8_t *buf = avpkt->data;
     int buf_size = avpkt->size;
     FFV1Context *f = avctx->priv_data;
-    RangeCoder * const c= &f->c;
-    const int width= f->width;
-    const int height= f->height;
+    RangeCoder * const c= &f->slice_context[0]->c;
     AVFrame * const p= &f->picture;
-    int bytes_read;
+    int bytes_read, i;
     uint8_t keystate= 128;
+    const uint8_t *buf_p;
 
     AVFrame *picture = data;
 
+    /* release previously stored data */
+    if (p->data[0])
+        avctx->release_buffer(avctx, p);
+
     ff_init_range_decoder(c, buf, buf_size);
     ff_build_rac_states(c, 0.05*(1LL<<32), 256-8);
 
@@ -1104,6 +1728,9 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPac
         p->key_frame= 1;
         if(read_header(f) < 0)
             return -1;
+        if(init_slice_state(f) < 0)
+            return -1;
+
         clear_state(f);
     }else{
         p->key_frame= 0;
@@ -1116,9 +1743,6 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPac
         }
     }
 
-    if(!f->plane[0].state && !f->plane[0].vlc_state)
-        return -1;
-
     p->reference= 0;
     if(avctx->get_buffer(avctx, p) < 0){
         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
@@ -1132,43 +1756,37 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPac
         bytes_read = c->bytestream - c->bytestream_start - 1;
         if(bytes_read ==0) av_log(avctx, AV_LOG_ERROR, "error at end of AC stream\n"); //FIXME
 //printf("pos=%d\n", bytes_read);
-        init_get_bits(&f->gb, buf + bytes_read, buf_size - bytes_read);
+        init_get_bits(&f->slice_context[0]->gb, buf + bytes_read, buf_size - bytes_read);
     } else {
         bytes_read = 0; /* avoid warning */
     }
 
-    if(f->colorspace==0){
-        const int chroma_width = -((-width )>>f->chroma_h_shift);
-        const int chroma_height= -((-height)>>f->chroma_v_shift);
-        decode_plane(f, p->data[0], width, height, p->linesize[0], 0);
-
-        decode_plane(f, p->data[1], chroma_width, chroma_height, p->linesize[1], 1);
-        decode_plane(f, p->data[2], chroma_width, chroma_height, p->linesize[2], 1);
-    }else{
-        decode_rgb_frame(f, (uint32_t*)p->data[0], width, height, p->linesize[0]/4);
+    buf_p= buf + buf_size;
+    for(i=f->slice_count-1; i>0; i--){
+        FFV1Context *fs= f->slice_context[i];
+        int v= AV_RB24(buf_p-3)+3;
+        if(buf_p - buf <= v){
+            av_log(avctx, AV_LOG_ERROR, "Slice pointer chain broken\n");
+            return -1;
+        }
+        buf_p -= v;
+        if(fs->ac){
+            ff_init_range_decoder(&fs->c, buf_p, v);
+        }else{
+            init_get_bits(&fs->gb, buf_p, v);
+        }
     }
 
-    emms_c();
-
+    avctx->execute(avctx, decode_slice, &f->slice_context[0], NULL, f->slice_count, sizeof(void*));
     f->picture_number++;
 
     *picture= *p;
-
-    avctx->release_buffer(avctx, p); //FIXME
-
     *data_size = sizeof(AVFrame);
 
-    if(f->ac){
-        bytes_read= c->bytestream - c->bytestream_start - 1;
-        if(bytes_read ==0) av_log(f->avctx, AV_LOG_ERROR, "error at end of frame\n");
-    }else{
-        bytes_read+= (get_bits_count(&f->gb)+7)/8;
-    }
-
-    return bytes_read;
+    return buf_size;
 }
 
-AVCodec ffv1_decoder = {
+AVCodec ff_ffv1_decoder = {
     "ffv1",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_FFV1,
@@ -1183,7 +1801,7 @@ AVCodec ffv1_decoder = {
 };
 
 #if CONFIG_FFV1_ENCODER
-AVCodec ffv1_encoder = {
+AVCodec ff_ffv1_encoder = {
     "ffv1",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_FFV1,
diff --git a/libavcodec/flac.c b/libavcodec/flac.c
index a649e08..e6a427a 100644
--- a/libavcodec/flac.c
+++ b/libavcodec/flac.c
@@ -2,24 +2,132 @@
  * FLAC common code
  * Copyright (c) 2009 Justin Ruggles
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/crc.h"
 #include "flac.h"
+#include "flacdata.h"
+
+static const int8_t sample_size_table[] = { 0, 8, 12, 0, 16, 20, 24, 0 };
+
+static int64_t get_utf8(GetBitContext *gb)
+{
+    int64_t val;
+    GET_UTF8(val, get_bits(gb, 8), return -1;)
+    return val;
+}
+
+int ff_flac_decode_frame_header(AVCodecContext *avctx, GetBitContext *gb,
+                                FLACFrameInfo *fi, int log_level_offset)
+{
+    int bs_code, sr_code, bps_code;
+
+    /* frame sync code */
+    if ((get_bits(gb, 15) & 0x7FFF) != 0x7FFC) {
+        av_log(avctx, AV_LOG_ERROR + log_level_offset, "invalid sync code\n");
+        return -1;
+    }
+
+    /* variable block size stream code */
+    fi->is_var_size = get_bits1(gb);
+
+    /* block size and sample rate codes */
+    bs_code = get_bits(gb, 4);
+    sr_code = get_bits(gb, 4);
+
+    /* channels and decorrelation */
+    fi->ch_mode = get_bits(gb, 4);
+    if (fi->ch_mode < FLAC_MAX_CHANNELS) {
+        fi->channels = fi->ch_mode + 1;
+        fi->ch_mode = FLAC_CHMODE_INDEPENDENT;
+    } else if (fi->ch_mode <= FLAC_CHMODE_MID_SIDE) {
+        fi->channels = 2;
+    } else {
+        av_log(avctx, AV_LOG_ERROR + log_level_offset,
+               "invalid channel mode: %d\n", fi->ch_mode);
+        return -1;
+    }
+
+    /* bits per sample */
+    bps_code = get_bits(gb, 3);
+    if (bps_code == 3 || bps_code == 7) {
+        av_log(avctx, AV_LOG_ERROR + log_level_offset,
+               "invalid sample size code (%d)\n",
+               bps_code);
+        return -1;
+    }
+    fi->bps = sample_size_table[bps_code];
+
+    /* reserved bit */
+    if (get_bits1(gb)) {
+        av_log(avctx, AV_LOG_ERROR + log_level_offset,
+               "broken stream, invalid padding\n");
+        return -1;
+    }
+
+    /* sample or frame count */
+    fi->frame_or_sample_num = get_utf8(gb);
+    if (fi->frame_or_sample_num < 0) {
+        av_log(avctx, AV_LOG_ERROR + log_level_offset,
+               "sample/frame number invalid; utf8 fscked\n");
+        return -1;
+    }
+
+    /* blocksize */
+    if (bs_code == 0) {
+        av_log(avctx, AV_LOG_ERROR + log_level_offset,
+               "reserved blocksize code: 0\n");
+        return -1;
+    } else if (bs_code == 6) {
+        fi->blocksize = get_bits(gb, 8) + 1;
+    } else if (bs_code == 7) {
+        fi->blocksize = get_bits(gb, 16) + 1;
+    } else {
+        fi->blocksize = ff_flac_blocksize_table[bs_code];
+    }
+
+    /* sample rate */
+    if (sr_code < 12) {
+        fi->samplerate = ff_flac_sample_rate_table[sr_code];
+    } else if (sr_code == 12) {
+        fi->samplerate = get_bits(gb, 8) * 1000;
+    } else if (sr_code == 13) {
+        fi->samplerate = get_bits(gb, 16);
+    } else if (sr_code == 14) {
+        fi->samplerate = get_bits(gb, 16) * 10;
+    } else {
+        av_log(avctx, AV_LOG_ERROR + log_level_offset,
+               "illegal sample rate code %d\n",
+               sr_code);
+        return -1;
+    }
+
+    /* header CRC-8 check */
+    skip_bits(gb, 8);
+    if (av_crc(av_crc_get_table(AV_CRC_8_ATM), 0, gb->buffer,
+               get_bits_count(gb)/8)) {
+        av_log(avctx, AV_LOG_ERROR + log_level_offset,
+               "header crc mismatch\n");
+        return -1;
+    }
+
+    return 0;
+}
 
 int ff_flac_get_max_frame_size(int blocksize, int ch, int bps)
 {
diff --git a/libavcodec/flac.h b/libavcodec/flac.h
index 1b11463..6ec8a37 100644
--- a/libavcodec/flac.h
+++ b/libavcodec/flac.h
@@ -2,20 +2,20 @@
  * FLAC (Free Lossless Audio Codec) decoder/demuxer common functions
  * Copyright (c) 2008 Justin Ruggles
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -28,11 +28,13 @@
 #define AVCODEC_FLAC_H
 
 #include "avcodec.h"
+#include "get_bits.h"
 
 #define FLAC_STREAMINFO_SIZE   34
 #define FLAC_MAX_CHANNELS       8
 #define FLAC_MIN_BLOCKSIZE     16
 #define FLAC_MAX_BLOCKSIZE  65535
+#define FLAC_MIN_FRAME_SIZE    11
 
 enum {
     FLAC_CHMODE_INDEPENDENT =  0,
@@ -80,6 +82,11 @@ typedef struct FLACFrameInfo {
     FLACCOMMONINFO
     int blocksize;          /**< block size of the frame                 */
     int ch_mode;            /**< channel decorrelation mode              */
+    int64_t frame_or_sample_num;    /**< frame number or sample number   */
+    int is_var_size;                /**< specifies if the stream uses variable
+                                         block sizes or a fixed block size;
+                                         also determines the meaning of
+                                         frame_or_sample_num             */
 } FLACFrameInfo;
 
 /**
@@ -120,4 +127,14 @@ void ff_flac_parse_block_header(const uint8_t *block_header,
  */
 int ff_flac_get_max_frame_size(int blocksize, int ch, int bps);
 
+/**
+ * Validate and decode a frame header.
+ * @param      avctx AVCodecContext to use as av_log() context
+ * @param      gb    GetBitContext from which to read frame header
+ * @param[out] fi    frame information
+ * @param      log_level_offset  log level offset. can be used to silence error messages.
+ * @return non-zero on error, 0 if ok
+ */
+int ff_flac_decode_frame_header(AVCodecContext *avctx, GetBitContext *gb,
+                                FLACFrameInfo *fi, int log_level_offset);
 #endif /* AVCODEC_FLAC_H */
diff --git a/libavcodec/flac_parser.c b/libavcodec/flac_parser.c
new file mode 100644
index 0000000..947a5b6
--- /dev/null
+++ b/libavcodec/flac_parser.c
@@ -0,0 +1,682 @@
+/*
+ * FLAC parser
+ * Copyright (c) 2010 Michael Chinen
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * FLAC parser
+ *
+ * The FLAC parser buffers input until FLAC_MIN_HEADERS has been found.
+ * Each time it finds and verifies a CRC-8 header it sees which of the
+ * FLAC_MAX_SEQUENTIAL_HEADERS that came before it have a valid CRC-16 footer
+ * that ends at the newly found header.
+ * Headers are scored by FLAC_HEADER_BASE_SCORE plus the max of it's crc-verified
+ * children, penalized by changes in sample rate, frame number, etc.
+ * The parser returns the frame with the highest score.
+ **/
+
+#include "libavutil/crc.h"
+#include "libavutil/fifo.h"
+#include "bytestream.h"
+#include "parser.h"
+#include "flac.h"
+
+/** maximum number of adjacent headers that compare CRCs against each other   */
+#define FLAC_MAX_SEQUENTIAL_HEADERS 3
+/** minimum number of headers buffered and checked before returning frames    */
+#define FLAC_MIN_HEADERS 10
+/** estimate for average size of a FLAC frame                                 */
+#define FLAC_AVG_FRAME_SIZE 8192
+
+/** scoring settings for score_header */
+#define FLAC_HEADER_BASE_SCORE        10
+#define FLAC_HEADER_CHANGED_PENALTY   7
+#define FLAC_HEADER_CRC_FAIL_PENALTY  50
+#define FLAC_HEADER_NOT_PENALIZED_YET 100000
+#define FLAC_HEADER_NOT_SCORED_YET    -100000
+
+/** largest possible size of flac header */
+#define MAX_FRAME_HEADER_SIZE 16
+
+typedef struct FLACHeaderMarker {
+    int offset;       /**< byte offset from start of FLACParseContext->buffer */
+    int *link_penalty;  /**< pointer to array of local scores between this header
+                           and the one at a distance equal array position     */
+    int max_score;    /**< maximum score found after checking each child that
+                           has a valid CRC                                    */
+    FLACFrameInfo fi; /**< decoded frame header info                          */
+    struct FLACHeaderMarker *next;       /**< next CRC-8 verified header that
+                                              immediately follows this one in
+                                              the bytestream                  */
+    struct FLACHeaderMarker *best_child; /**< following frame header with
+                                              which this frame has the best
+                                              score with                      */
+} FLACHeaderMarker;
+
+typedef struct FLACParseContext {
+    AVCodecContext *avctx;         /**< codec context pointer for logging     */
+    FLACHeaderMarker *headers;     /**< linked-list that starts at the first
+                                        CRC-8 verified header within buffer   */
+    FLACHeaderMarker *best_header; /**< highest scoring header within buffer  */
+    int nb_headers_found;          /**< number of headers found in the last
+                                        flac_parse() call                     */
+    int nb_headers_buffered;       /**< number of headers that are buffered   */
+    int best_header_valid;         /**< flag set when the parser returns junk;
+                                        if set return best_header next time   */
+    AVFifoBuffer *fifo_buf;        /**< buffer to store all data until headers
+                                        can be verified                       */
+    int end_padded;                /**< specifies if fifo_buf's end is padded */
+    uint8_t *wrap_buf;             /**< general fifo read buffer when wrapped */
+    int wrap_buf_allocated_size;   /**< actual allocated size of the buffer   */
+} FLACParseContext;
+
+static int frame_header_is_valid(AVCodecContext *avctx, const uint8_t *buf,
+                                 FLACFrameInfo *fi)
+{
+    GetBitContext gb;
+    init_get_bits(&gb, buf, MAX_FRAME_HEADER_SIZE * 8);
+    return !ff_flac_decode_frame_header(avctx, &gb, fi, 127);
+}
+
+/**
+ * Non-destructive fast fifo pointer fetching
+ * Returns a pointer from the specified offset.
+ * If possible the pointer points within the fifo buffer.
+ * Otherwise (if it would cause a wrap around,) a pointer to a user-specified
+ * buffer is used.
+ * The pointer can be NULL.  In any case it will be reallocated to hold the size.
+ * If the returned pointer will be used after subsequent calls to flac_fifo_read_wrap
+ * then the subsequent calls should pass in a different wrap_buf so as to not
+ * overwrite the contents of the previous wrap_buf.
+ * This function is based on av_fifo_generic_read, which is why there is a comment
+ * about a memory barrier for SMP.
+ */
+static uint8_t* flac_fifo_read_wrap(FLACParseContext *fpc, int offset, int len,
+                               uint8_t** wrap_buf, int* allocated_size)
+{
+    AVFifoBuffer *f   = fpc->fifo_buf;
+    uint8_t *start    = f->rptr + offset;
+    uint8_t *tmp_buf;
+
+    if (start >= f->end)
+        start -= f->end - f->buffer;
+    if (f->end - start >= len)
+        return start;
+
+    tmp_buf = av_fast_realloc(*wrap_buf, allocated_size, len);
+
+    if (!tmp_buf) {
+        av_log(fpc->avctx, AV_LOG_ERROR,
+               "couldn't reallocate wrap buffer of size %d", len);
+        return NULL;
+    }
+    *wrap_buf = tmp_buf;
+    do {
+        int seg_len = FFMIN(f->end - start, len);
+        memcpy(tmp_buf, start, seg_len);
+        tmp_buf = (uint8_t*)tmp_buf + seg_len;
+// memory barrier needed for SMP here in theory
+
+        start += seg_len - (f->end - f->buffer);
+        len -= seg_len;
+    } while (len > 0);
+
+    return *wrap_buf;
+}
+
+/**
+ * Return a pointer in the fifo buffer where the offset starts at until
+ * the wrap point or end of request.
+ * len will contain the valid length of the returned buffer.
+ * A second call to flac_fifo_read (with new offset and len) should be called
+ * to get the post-wrap buf if the returned len is less than the requested.
+ **/
+static uint8_t* flac_fifo_read(FLACParseContext *fpc, int offset, int *len)
+{
+    AVFifoBuffer *f   = fpc->fifo_buf;
+    uint8_t *start    = f->rptr + offset;
+
+    if (start >= f->end)
+        start -= f->end - f->buffer;
+    *len = FFMIN(*len, f->end - start);
+    return start;
+}
+
+static int find_headers_search_validate(FLACParseContext *fpc, int offset)
+{
+    FLACFrameInfo fi;
+    uint8_t *header_buf;
+    int size = 0;
+    header_buf = flac_fifo_read_wrap(fpc, offset,
+                                     MAX_FRAME_HEADER_SIZE,
+                                     &fpc->wrap_buf,
+                                     &fpc->wrap_buf_allocated_size);
+    if (frame_header_is_valid(fpc->avctx, header_buf, &fi)) {
+        FLACHeaderMarker **end_handle = &fpc->headers;
+        int i;
+
+        size = 0;
+        while (*end_handle) {
+            end_handle = &(*end_handle)->next;
+            size++;
+        }
+
+        *end_handle = av_mallocz(sizeof(FLACHeaderMarker));
+        if (!*end_handle) {
+            av_log(fpc->avctx, AV_LOG_ERROR,
+                   "couldn't allocate FLACHeaderMarker\n");
+            return AVERROR(ENOMEM);
+        }
+        (*end_handle)->fi           = fi;
+        (*end_handle)->offset       = offset;
+        (*end_handle)->link_penalty = av_malloc(sizeof(int) *
+                                            FLAC_MAX_SEQUENTIAL_HEADERS);
+        for (i = 0; i < FLAC_MAX_SEQUENTIAL_HEADERS; i++)
+            (*end_handle)->link_penalty[i] = FLAC_HEADER_NOT_PENALIZED_YET;
+
+        fpc->nb_headers_found++;
+        size++;
+    }
+    return size;
+}
+
+static int find_headers_search(FLACParseContext *fpc, uint8_t *buf, int buf_size,
+                               int search_start)
+
+{
+    int size = 0, mod_offset = (buf_size - 1) % 4, i, j;
+    uint32_t x;
+
+    for (i = 0; i < mod_offset; i++) {
+        if ((AV_RB16(buf + i) & 0xFFFE) == 0xFFF8)
+            size = find_headers_search_validate(fpc, search_start + i);
+    }
+
+    for (; i < buf_size - 1; i += 4) {
+        x = AV_RB32(buf + i);
+        if (((x & ~(x + 0x01010101)) & 0x80808080)) {
+            for (j = 0; j < 4; j++) {
+                if ((AV_RB16(buf + i + j) & 0xFFFE) == 0xFFF8)
+                    size = find_headers_search_validate(fpc, search_start + i + j);
+            }
+        }
+    }
+    return size;
+}
+
+static int find_new_headers(FLACParseContext *fpc, int search_start)
+{
+    FLACHeaderMarker *end;
+    int search_end, size = 0, read_len, temp;
+    uint8_t *buf;
+    fpc->nb_headers_found = 0;
+
+    /* Search for a new header of at most 16 bytes. */
+    search_end = av_fifo_size(fpc->fifo_buf) - (MAX_FRAME_HEADER_SIZE - 1);
+    read_len   = search_end - search_start + 1;
+    buf        = flac_fifo_read(fpc, search_start, &read_len);
+    size       = find_headers_search(fpc, buf, read_len, search_start);
+    search_start += read_len - 1;
+
+    /* If fifo end was hit do the wrap around. */
+    if (search_start != search_end) {
+        uint8_t wrap[2];
+
+        wrap[0]  = buf[read_len - 1];
+        read_len = search_end - search_start + 1;
+
+        /* search_start + 1 is the post-wrap offset in the fifo. */
+        buf      = flac_fifo_read(fpc, search_start + 1, &read_len);
+        wrap[1]  = buf[0];
+
+        if ((AV_RB16(wrap) & 0xFFFE) == 0xFFF8) {
+            temp = find_headers_search_validate(fpc, search_start);
+            size = FFMAX(size, temp);
+        }
+        search_start++;
+
+        /* Continue to do the last half of the wrap. */
+        temp     = find_headers_search(fpc, buf, read_len, search_start);
+        size     = FFMAX(size, temp);
+        search_start += read_len - 1;
+    }
+
+    /* Return the size even if no new headers were found. */
+    if (!size && fpc->headers)
+        for (end = fpc->headers; end; end = end->next)
+            size++;
+    return size;
+}
+
+static int check_header_mismatch(FLACParseContext  *fpc,
+                                 FLACHeaderMarker  *header,
+                                 FLACHeaderMarker  *child,
+                                 int                log_level_offset)
+{
+    FLACFrameInfo  *header_fi = &header->fi, *child_fi = &child->fi;
+    int deduction = 0, deduction_expected = 0, i;
+    if (child_fi->samplerate != header_fi->samplerate) {
+        deduction += FLAC_HEADER_CHANGED_PENALTY;
+        av_log(fpc->avctx, AV_LOG_WARNING + log_level_offset,
+               "sample rate change detected in adjacent frames\n");
+    }
+    if (child_fi->bps != header_fi->bps) {
+        deduction += FLAC_HEADER_CHANGED_PENALTY;
+        av_log(fpc->avctx, AV_LOG_WARNING + log_level_offset,
+               "bits per sample change detected in adjacent frames\n");
+    }
+    if (child_fi->is_var_size != header_fi->is_var_size) {
+        /* Changing blocking strategy not allowed per the spec */
+        deduction += FLAC_HEADER_BASE_SCORE;
+        av_log(fpc->avctx, AV_LOG_WARNING + log_level_offset,
+                   "blocking strategy change detected in adjacent frames\n");
+    }
+    if (child_fi->channels != header_fi->channels) {
+        deduction += FLAC_HEADER_CHANGED_PENALTY;
+        av_log(fpc->avctx, AV_LOG_WARNING + log_level_offset,
+                   "number of channels change detected in adjacent frames\n");
+    }
+    /* Check sample and frame numbers. */
+    if ((child_fi->frame_or_sample_num - header_fi->frame_or_sample_num
+         != header_fi->blocksize) &&
+        (child_fi->frame_or_sample_num
+         != header_fi->frame_or_sample_num + 1)) {
+        FLACHeaderMarker *curr;
+        int expected_frame_num, expected_sample_num;
+        /* If there are frames in the middle we expect this deduction,
+           as they are probably valid and this one follows it */
+
+        expected_frame_num = expected_sample_num = header_fi->frame_or_sample_num;
+        curr = header;
+        while (curr != child) {
+            /* Ignore frames that failed all crc checks */
+            for (i = 0; i < FLAC_MAX_SEQUENTIAL_HEADERS; i++) {
+                if (curr->link_penalty[i] < FLAC_HEADER_CRC_FAIL_PENALTY) {
+                    expected_frame_num++;
+                    expected_sample_num += curr->fi.blocksize;
+                    break;
+                }
+            }
+            curr = curr->next;
+        }
+
+        if (expected_frame_num  == child_fi->frame_or_sample_num ||
+            expected_sample_num == child_fi->frame_or_sample_num)
+            deduction_expected = deduction ? 0 : 1;
+
+        deduction += FLAC_HEADER_CHANGED_PENALTY;
+        av_log(fpc->avctx, AV_LOG_WARNING + log_level_offset,
+                   "sample/frame number mismatch in adjacent frames\n");
+    }
+
+    /* If we have suspicious headers, check the CRC between them */
+    if (deduction && !deduction_expected) {
+        FLACHeaderMarker *curr;
+        int read_len;
+        uint8_t *buf;
+        uint32_t crc = 1;
+        int inverted_test = 0;
+
+        /* Since CRC is expensive only do it if we haven't yet.
+           This assumes a CRC penalty is greater than all other check penalties */
+        curr = header->next;
+        for (i = 0; i < FLAC_MAX_SEQUENTIAL_HEADERS && curr != child; i++)
+            curr = curr->next;
+
+        if (header->link_penalty[i] < FLAC_HEADER_CRC_FAIL_PENALTY ||
+            header->link_penalty[i] == FLAC_HEADER_NOT_PENALIZED_YET) {
+            FLACHeaderMarker *start, *end;
+
+            /* Although overlapping chains are scored, the crc should never
+               have to be computed twice for a single byte. */
+            start = header;
+            end   = child;
+            if (i > 0 &&
+                header->link_penalty[i - 1] >= FLAC_HEADER_CRC_FAIL_PENALTY) {
+                while (start->next != child)
+                    start = start->next;
+                inverted_test = 1;
+            } else if (i > 0 &&
+                       header->next->link_penalty[i-1] >=
+                       FLAC_HEADER_CRC_FAIL_PENALTY ) {
+                end = header->next;
+                inverted_test = 1;
+            }
+
+            read_len = end->offset - start->offset;
+            buf      = flac_fifo_read(fpc, start->offset, &read_len);
+            crc      = av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0, buf, read_len);
+            read_len = (end->offset - start->offset) - read_len;
+
+            if (read_len) {
+                buf = flac_fifo_read(fpc, end->offset - read_len, &read_len);
+                crc = av_crc(av_crc_get_table(AV_CRC_16_ANSI), crc, buf, read_len);
+            }
+        }
+
+        if (!crc ^ !inverted_test) {
+            deduction += FLAC_HEADER_CRC_FAIL_PENALTY;
+            av_log(fpc->avctx, AV_LOG_WARNING + log_level_offset,
+                   "crc check failed from offset %i (frame %"PRId64") to %i (frame %"PRId64")\n",
+                   header->offset, header_fi->frame_or_sample_num,
+                   child->offset, child_fi->frame_or_sample_num);
+        }
+    }
+    return deduction;
+}
+
+/**
+ * Score a header.
+ *
+ * Give FLAC_HEADER_BASE_SCORE points to a frame for existing.
+ * If it has children, (subsequent frames of which the preceding CRC footer
+ * validates against this one,) then take the maximum score of the children,
+ * with a penalty of FLAC_HEADER_CHANGED_PENALTY applied for each change to
+ * bps, sample rate, channels, but not decorrelation mode, or blocksize,
+ * because it can change often.
+ **/
+static int score_header(FLACParseContext *fpc, FLACHeaderMarker *header)
+{
+    FLACHeaderMarker *child;
+    int dist = 0;
+    int child_score;
+
+    if (header->max_score != FLAC_HEADER_NOT_SCORED_YET)
+        return header->max_score;
+
+    header->max_score = FLAC_HEADER_BASE_SCORE;
+
+    /* Check and compute the children's scores. */
+    child = header->next;
+    for (dist = 0; dist < FLAC_MAX_SEQUENTIAL_HEADERS && child; dist++) {
+        /* Look at the child's frame header info and penalize suspicious
+           changes between the headers. */
+        if (header->link_penalty[dist] == FLAC_HEADER_NOT_PENALIZED_YET) {
+            header->link_penalty[dist] = check_header_mismatch(fpc, header,
+                                                               child, AV_LOG_DEBUG);
+        }
+        child_score = score_header(fpc, child) - header->link_penalty[dist];
+
+        if (FLAC_HEADER_BASE_SCORE + child_score > header->max_score) {
+            /* Keep the child because the frame scoring is dynamic. */
+            header->best_child = child;
+            header->max_score  = FLAC_HEADER_BASE_SCORE + child_score;
+        }
+        child = child->next;
+    }
+
+    return header->max_score;
+}
+
+static void score_sequences(FLACParseContext *fpc)
+{
+    FLACHeaderMarker *curr;
+    int best_score = FLAC_HEADER_NOT_SCORED_YET;
+    /* First pass to clear all old scores. */
+    for (curr = fpc->headers; curr; curr = curr->next)
+        curr->max_score = FLAC_HEADER_NOT_SCORED_YET;
+
+    /* Do a second pass to score them all. */
+    for (curr = fpc->headers; curr; curr = curr->next) {
+        if (score_header(fpc, curr) > best_score) {
+            fpc->best_header = curr;
+            best_score       = curr->max_score;
+        }
+    }
+}
+
+static int get_best_header(FLACParseContext* fpc, const uint8_t **poutbuf,
+                           int *poutbuf_size)
+{
+    FLACHeaderMarker *header = fpc->best_header;
+    FLACHeaderMarker *child  = header->best_child;
+    if (!child) {
+        *poutbuf_size = av_fifo_size(fpc->fifo_buf) - header->offset;
+    } else {
+        *poutbuf_size = child->offset - header->offset;
+
+        /* If the child has suspicious changes, log them */
+        check_header_mismatch(fpc, header, child, 0);
+    }
+
+    fpc->avctx->sample_rate = header->fi.samplerate;
+    fpc->avctx->channels    = header->fi.channels;
+    fpc->avctx->frame_size  = header->fi.blocksize;
+    *poutbuf = flac_fifo_read_wrap(fpc, header->offset, *poutbuf_size,
+                                        &fpc->wrap_buf,
+                                        &fpc->wrap_buf_allocated_size);
+
+    fpc->best_header_valid = 0;
+    /* Return the negative overread index so the client can compute pos.
+       This should be the amount overread to the beginning of the child */
+    if (child)
+        return child->offset - av_fifo_size(fpc->fifo_buf);
+    return 0;
+}
+
+static int flac_parse(AVCodecParserContext *s, AVCodecContext *avctx,
+                      const uint8_t **poutbuf, int *poutbuf_size,
+                      const uint8_t *buf, int buf_size)
+{
+    FLACParseContext *fpc = s->priv_data;
+    FLACHeaderMarker *curr;
+    int nb_headers;
+    const uint8_t *read_end   = buf;
+    const uint8_t *read_start = buf;
+
+    if (s->flags & PARSER_FLAG_COMPLETE_FRAMES) {
+        FLACFrameInfo fi;
+        if (frame_header_is_valid(avctx, buf, &fi))
+            avctx->frame_size = fi.blocksize;
+        *poutbuf      = buf;
+        *poutbuf_size = buf_size;
+        return buf_size;
+    }
+
+    fpc->avctx = avctx;
+    if (fpc->best_header_valid)
+        return get_best_header(fpc, poutbuf, poutbuf_size);
+
+    /* If a best_header was found last call remove it with the buffer data. */
+    if (fpc->best_header && fpc->best_header->best_child) {
+        FLACHeaderMarker *temp;
+        FLACHeaderMarker *best_child = fpc->best_header->best_child;
+
+        /* Remove headers in list until the end of the best_header. */
+        for (curr = fpc->headers; curr != best_child; curr = temp) {
+            if (curr != fpc->best_header) {
+                av_log(avctx, AV_LOG_DEBUG,
+                       "dropping low score %i frame header from offset %i to %i\n",
+                       curr->max_score, curr->offset, curr->next->offset);
+            }
+            temp = curr->next;
+            av_freep(&curr->link_penalty);
+            av_free(curr);
+            fpc->nb_headers_buffered--;
+        }
+        /* Release returned data from ring buffer. */
+        av_fifo_drain(fpc->fifo_buf, best_child->offset);
+
+        /* Fix the offset for the headers remaining to match the new buffer. */
+        for (curr = best_child->next; curr; curr = curr->next)
+            curr->offset -= best_child->offset;
+
+        fpc->nb_headers_buffered--;
+        best_child->offset = 0;
+        fpc->headers       = best_child;
+        if (fpc->nb_headers_buffered >= FLAC_MIN_HEADERS) {
+            fpc->best_header = best_child;
+            return get_best_header(fpc, poutbuf, poutbuf_size);
+        }
+        fpc->best_header   = NULL;
+    } else if (fpc->best_header) {
+        /* No end frame no need to delete the buffer; probably eof */
+        FLACHeaderMarker *temp;
+
+        for (curr = fpc->headers; curr != fpc->best_header; curr = temp) {
+            temp = curr->next;
+            av_freep(&curr->link_penalty);
+            av_free(curr);
+        }
+        fpc->headers = fpc->best_header->next;
+        av_freep(&fpc->best_header->link_penalty);
+        av_freep(&fpc->best_header);
+    }
+
+    /* Find and score new headers. */
+    while ((buf && read_end < buf + buf_size &&
+            fpc->nb_headers_buffered < FLAC_MIN_HEADERS)
+           || (!buf && !fpc->end_padded)) {
+        int start_offset;
+
+        /* Pad the end once if EOF, to check the final region for headers. */
+        if (!buf) {
+            fpc->end_padded      = 1;
+            buf_size = MAX_FRAME_HEADER_SIZE;
+            read_end = read_start + MAX_FRAME_HEADER_SIZE;
+        } else {
+            /* The maximum read size is the upper-bound of what the parser
+               needs to have the required number of frames buffered */
+            int nb_desired = FLAC_MIN_HEADERS - fpc->nb_headers_buffered + 1;
+            read_end       = read_end + FFMIN(buf + buf_size - read_end,
+                                              nb_desired * FLAC_AVG_FRAME_SIZE);
+        }
+
+        /* Fill the buffer. */
+        if (av_fifo_realloc2(fpc->fifo_buf,
+                             (read_end - read_start) + av_fifo_size(fpc->fifo_buf)) < 0) {
+            av_log(avctx, AV_LOG_ERROR,
+                   "couldn't reallocate buffer of size %td\n",
+                   (read_end - read_start) + av_fifo_size(fpc->fifo_buf));
+            goto handle_error;
+        }
+
+        if (buf) {
+            av_fifo_generic_write(fpc->fifo_buf, (void*) read_start,
+                                  read_end - read_start, NULL);
+        } else {
+            int8_t pad[MAX_FRAME_HEADER_SIZE];
+            memset(pad, 0, sizeof(pad));
+            av_fifo_generic_write(fpc->fifo_buf, (void*) pad, sizeof(pad), NULL);
+        }
+
+        /* Tag headers and update sequences. */
+        start_offset = av_fifo_size(fpc->fifo_buf) -
+                       ((read_end - read_start) + (MAX_FRAME_HEADER_SIZE - 1));
+        start_offset = FFMAX(0, start_offset);
+        nb_headers   = find_new_headers(fpc, start_offset);
+
+        if (nb_headers < 0) {
+            av_log(avctx, AV_LOG_ERROR,
+                   "find_new_headers couldn't allocate FLAC header\n");
+            goto handle_error;
+        }
+
+        fpc->nb_headers_buffered = nb_headers;
+        /* Wait till FLAC_MIN_HEADERS to output a valid frame. */
+        if (!fpc->end_padded && fpc->nb_headers_buffered < FLAC_MIN_HEADERS) {
+            if (buf && read_end < buf + buf_size) {
+                read_start = read_end;
+                continue;
+            } else {
+                goto handle_error;
+            }
+        }
+
+        /* If headers found, update the scores since we have longer chains. */
+        if (fpc->end_padded || fpc->nb_headers_found)
+            score_sequences(fpc);
+
+        /* restore the state pre-padding */
+        if (fpc->end_padded) {
+            /* HACK: drain the tail of the fifo */
+            fpc->fifo_buf->wptr -= MAX_FRAME_HEADER_SIZE;
+            fpc->fifo_buf->wndx -= MAX_FRAME_HEADER_SIZE;
+            if (fpc->fifo_buf->wptr < 0) {
+                fpc->fifo_buf->wptr += fpc->fifo_buf->end -
+                    fpc->fifo_buf->buffer;
+            }
+            buf_size = 0;
+            read_start = read_end = NULL;
+        }
+    }
+
+    curr = fpc->headers;
+    for (curr = fpc->headers; curr; curr = curr->next)
+        if (!fpc->best_header || curr->max_score > fpc->best_header->max_score)
+            fpc->best_header = curr;
+
+    if (fpc->best_header) {
+        fpc->best_header_valid = 1;
+        if (fpc->best_header->offset > 0) {
+            /* Output a junk frame. */
+            av_log(avctx, AV_LOG_DEBUG, "Junk frame till offset %i\n",
+                   fpc->best_header->offset);
+
+            /* Set frame_size to 0. It is unknown or invalid in a junk frame. */
+            avctx->frame_size = 0;
+            *poutbuf_size     = fpc->best_header->offset;
+            *poutbuf          = flac_fifo_read_wrap(fpc, 0, *poutbuf_size,
+                                                    &fpc->wrap_buf,
+                                                    &fpc->wrap_buf_allocated_size);
+            return buf_size ? (read_end - buf) : (fpc->best_header->offset -
+                                           av_fifo_size(fpc->fifo_buf));
+        }
+        if (!buf_size)
+            return get_best_header(fpc, poutbuf, poutbuf_size);
+    }
+
+handle_error:
+    *poutbuf      = NULL;
+    *poutbuf_size = 0;
+    return read_end - buf;
+}
+
+static int flac_parse_init(AVCodecParserContext *c)
+{
+    FLACParseContext *fpc = c->priv_data;
+    /* There will generally be FLAC_MIN_HEADERS buffered in the fifo before
+       it drains.  This is allocated early to avoid slow reallocation. */
+    fpc->fifo_buf = av_fifo_alloc(FLAC_AVG_FRAME_SIZE * (FLAC_MIN_HEADERS + 3));
+    return 0;
+}
+
+static void flac_parse_close(AVCodecParserContext *c)
+{
+    FLACParseContext *fpc = c->priv_data;
+    FLACHeaderMarker *curr = fpc->headers, *temp;
+
+    while (curr) {
+        temp = curr->next;
+        av_freep(&curr->link_penalty);
+        av_free(curr);
+        curr = temp;
+    }
+    av_fifo_free(fpc->fifo_buf);
+    av_free(fpc->wrap_buf);
+}
+
+AVCodecParser ff_flac_parser = {
+    { CODEC_ID_FLAC },
+    sizeof(FLACParseContext),
+    flac_parse_init,
+    flac_parse,
+    flac_parse_close,
+};
diff --git a/libavcodec/flacdata.c b/libavcodec/flacdata.c
index 6fcbe39..820c3aa 100644
--- a/libavcodec/flacdata.c
+++ b/libavcodec/flacdata.c
@@ -2,20 +2,20 @@
  * FLAC data
  * Copyright (c) 2003 Alex Beregszaszi
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/flacdata.h b/libavcodec/flacdata.h
index 96a50b9..f566377 100644
--- a/libavcodec/flacdata.h
+++ b/libavcodec/flacdata.h
@@ -2,20 +2,20 @@
  * FLAC data header
  * Copyright (c) 2003 Alex Beregszaszi
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/flacdec.c b/libavcodec/flacdec.c
index 07acf6e..1ce8559 100644
--- a/libavcodec/flacdec.c
+++ b/libavcodec/flacdec.c
@@ -2,20 +2,20 @@
  * FLAC (Free Lossless Audio Codec) decoder
  * Copyright (c) 2003 Alex Beregszaszi
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -61,22 +61,8 @@ typedef struct FLACContext {
     int got_streaminfo;                     ///< indicates if the STREAMINFO has been read
 
     int32_t *decoded[FLAC_MAX_CHANNELS];    ///< decoded samples
-    uint8_t *bitstream;
-    unsigned int bitstream_size;
-    unsigned int bitstream_index;
-    unsigned int allocated_bitstream_size;
 } FLACContext;
 
-static const int sample_size_table[] =
-{ 0, 8, 12, 0, 16, 20, 24, 0 };
-
-static int64_t get_utf8(GetBitContext *gb)
-{
-    int64_t val;
-    GET_UTF8(val, get_bits(gb, 8), return -1;)
-    return val;
-}
-
 static void allocate_buffers(FLACContext *s);
 
 int ff_flac_is_extradata_valid(AVCodecContext *avctx,
@@ -113,7 +99,7 @@ static av_cold int flac_decode_init(AVCodecContext *avctx)
     FLACContext *s = avctx->priv_data;
     s->avctx = avctx;
 
-    avctx->sample_fmt = SAMPLE_FMT_S16;
+    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
 
     /* for now, the raw FLAC header is allowed to be passed to the decoder as
        frame data instead of extradata. */
@@ -126,9 +112,9 @@ static av_cold int flac_decode_init(AVCodecContext *avctx)
     /* initialize based on the demuxer-supplied streamdata header */
     ff_flac_parse_streaminfo(avctx, (FLACStreaminfo *)s, streaminfo);
     if (s->bps > 16)
-        avctx->sample_fmt = SAMPLE_FMT_S32;
+        avctx->sample_fmt = AV_SAMPLE_FMT_S32;
     else
-        avctx->sample_fmt = SAMPLE_FMT_S16;
+        avctx->sample_fmt = AV_SAMPLE_FMT_S16;
     allocate_buffers(s);
     s->got_streaminfo = 1;
 
@@ -150,20 +136,10 @@ static void allocate_buffers(FLACContext *s)
 
     assert(s->max_blocksize);
 
-    if (s->max_framesize == 0 && s->max_blocksize) {
-        s->max_framesize = ff_flac_get_max_frame_size(s->max_blocksize,
-                                                      s->channels, s->bps);
-    }
-
     for (i = 0; i < s->channels; i++) {
         s->decoded[i] = av_realloc(s->decoded[i],
                                    sizeof(int32_t)*s->max_blocksize);
     }
-
-    if (s->allocated_bitstream_size < s->max_framesize)
-        s->bitstream= av_fast_realloc(s->bitstream,
-                                      &s->allocated_bitstream_size,
-                                      s->max_framesize);
 }
 
 void ff_flac_parse_streaminfo(AVCodecContext *avctx, struct FLACStreaminfo *s,
@@ -480,129 +456,50 @@ static inline int decode_subframe(FLACContext *s, int channel)
     return 0;
 }
 
-/**
- * Validate and decode a frame header.
- * @param      avctx AVCodecContext to use as av_log() context
- * @param      gb    GetBitContext from which to read frame header
- * @param[out] fi    frame information
- * @return non-zero on error, 0 if ok
- */
-static int decode_frame_header(AVCodecContext *avctx, GetBitContext *gb,
-                               FLACFrameInfo *fi)
-{
-    int bs_code, sr_code, bps_code;
-
-    /* frame sync code */
-    skip_bits(gb, 16);
-
-    /* block size and sample rate codes */
-    bs_code = get_bits(gb, 4);
-    sr_code = get_bits(gb, 4);
-
-    /* channels and decorrelation */
-    fi->ch_mode = get_bits(gb, 4);
-    if (fi->ch_mode < FLAC_MAX_CHANNELS) {
-        fi->channels = fi->ch_mode + 1;
-        fi->ch_mode = FLAC_CHMODE_INDEPENDENT;
-    } else if (fi->ch_mode <= FLAC_CHMODE_MID_SIDE) {
-        fi->channels = 2;
-    } else {
-        av_log(avctx, AV_LOG_ERROR, "invalid channel mode: %d\n", fi->ch_mode);
-        return -1;
-    }
-
-    /* bits per sample */
-    bps_code = get_bits(gb, 3);
-    if (bps_code == 3 || bps_code == 7) {
-        av_log(avctx, AV_LOG_ERROR, "invalid sample size code (%d)\n",
-               bps_code);
-        return -1;
-    }
-    fi->bps = sample_size_table[bps_code];
-
-    /* reserved bit */
-    if (get_bits1(gb)) {
-        av_log(avctx, AV_LOG_ERROR, "broken stream, invalid padding\n");
-        return -1;
-    }
-
-    /* sample or frame count */
-    if (get_utf8(gb) < 0) {
-        av_log(avctx, AV_LOG_ERROR, "utf8 fscked\n");
-        return -1;
-    }
-
-    /* blocksize */
-    if (bs_code == 0) {
-        av_log(avctx, AV_LOG_ERROR, "reserved blocksize code: 0\n");
-        return -1;
-    } else if (bs_code == 6) {
-        fi->blocksize = get_bits(gb, 8) + 1;
-    } else if (bs_code == 7) {
-        fi->blocksize = get_bits(gb, 16) + 1;
-    } else {
-        fi->blocksize = ff_flac_blocksize_table[bs_code];
-    }
-
-    /* sample rate */
-    if (sr_code < 12) {
-        fi->samplerate = ff_flac_sample_rate_table[sr_code];
-    } else if (sr_code == 12) {
-        fi->samplerate = get_bits(gb, 8) * 1000;
-    } else if (sr_code == 13) {
-        fi->samplerate = get_bits(gb, 16);
-    } else if (sr_code == 14) {
-        fi->samplerate = get_bits(gb, 16) * 10;
-    } else {
-        av_log(avctx, AV_LOG_ERROR, "illegal sample rate code %d\n",
-               sr_code);
-        return -1;
-    }
-
-    /* header CRC-8 check */
-    skip_bits(gb, 8);
-    if (av_crc(av_crc_get_table(AV_CRC_8_ATM), 0, gb->buffer,
-               get_bits_count(gb)/8)) {
-        av_log(avctx, AV_LOG_ERROR, "header crc mismatch\n");
-        return -1;
-    }
-
-    return 0;
-}
-
 static int decode_frame(FLACContext *s)
 {
     int i;
     GetBitContext *gb = &s->gb;
     FLACFrameInfo fi;
 
-    if (decode_frame_header(s->avctx, gb, &fi)) {
+    if (ff_flac_decode_frame_header(s->avctx, gb, &fi, 0)) {
         av_log(s->avctx, AV_LOG_ERROR, "invalid frame header\n");
         return -1;
     }
 
-    if (fi.channels != s->channels) {
+    if (s->channels && fi.channels != s->channels) {
         av_log(s->avctx, AV_LOG_ERROR, "switching channel layout mid-stream "
                                        "is not supported\n");
         return -1;
     }
+    s->channels = s->avctx->channels = fi.channels;
     s->ch_mode = fi.ch_mode;
 
-    if (fi.bps && fi.bps != s->bps) {
+    if (!s->bps && !fi.bps) {
+        av_log(s->avctx, AV_LOG_ERROR, "bps not found in STREAMINFO or frame header\n");
+        return -1;
+    }
+    if (!fi.bps) {
+        fi.bps = s->bps;
+    } else if (s->bps && fi.bps != s->bps) {
         av_log(s->avctx, AV_LOG_ERROR, "switching bps mid-stream is not "
                                        "supported\n");
         return -1;
     }
+    s->bps = s->avctx->bits_per_raw_sample = fi.bps;
+
     if (s->bps > 16) {
-        s->avctx->sample_fmt = SAMPLE_FMT_S32;
+        s->avctx->sample_fmt = AV_SAMPLE_FMT_S32;
         s->sample_shift = 32 - s->bps;
         s->is32 = 1;
     } else {
-        s->avctx->sample_fmt = SAMPLE_FMT_S16;
+        s->avctx->sample_fmt = AV_SAMPLE_FMT_S16;
         s->sample_shift = 16 - s->bps;
         s->is32 = 0;
     }
 
+    if (!s->max_blocksize)
+        s->max_blocksize = FLAC_MAX_BLOCKSIZE;
     if (fi.blocksize > s->max_blocksize) {
         av_log(s->avctx, AV_LOG_ERROR, "blocksize %d > %d\n", fi.blocksize,
                s->max_blocksize);
@@ -610,14 +507,25 @@ static int decode_frame(FLACContext *s)
     }
     s->blocksize = fi.blocksize;
 
+    if (!s->samplerate && !fi.samplerate) {
+        av_log(s->avctx, AV_LOG_ERROR, "sample rate not found in STREAMINFO"
+                                        " or frame header\n");
+        return -1;
+    }
     if (fi.samplerate == 0) {
         fi.samplerate = s->samplerate;
-    } else if (fi.samplerate != s->samplerate) {
+    } else if (s->samplerate && fi.samplerate != s->samplerate) {
         av_log(s->avctx, AV_LOG_WARNING, "sample rate changed from %d to %d\n",
                s->samplerate, fi.samplerate);
     }
     s->samplerate = s->avctx->sample_rate = fi.samplerate;
 
+    if (!s->got_streaminfo) {
+        allocate_buffers(s);
+        s->got_streaminfo = 1;
+        dump_headers(s->avctx, (FLACStreaminfo *)s);
+    }
+
 //    dump_headers(s->avctx, (FLACStreaminfo *)s);
 
     /* subframes */
@@ -641,7 +549,7 @@ static int flac_decode_frame(AVCodecContext *avctx,
     const uint8_t *buf = avpkt->data;
     int buf_size = avpkt->size;
     FLACContext *s = avctx->priv_data;
-    int i, j = 0, input_buf_size = 0, bytes_read = 0;
+    int i, j = 0, bytes_read = 0;
     int16_t *samples_16 = data;
     int32_t *samples_32 = data;
     int alloc_data_size= *data_size;
@@ -650,42 +558,16 @@ static int flac_decode_frame(AVCodecContext *avctx,
     *data_size=0;
 
     if (s->max_framesize == 0) {
-        s->max_framesize= FFMAX(4, buf_size); // should hopefully be enough for the first header
-        s->bitstream= av_fast_realloc(s->bitstream, &s->allocated_bitstream_size, s->max_framesize);
-    }
-
-    if (1 && s->max_framesize) { //FIXME truncated
-        if (s->bitstream_size < 4 || AV_RL32(s->bitstream) != MKTAG('f','L','a','C'))
-            buf_size= FFMIN(buf_size, s->max_framesize - FFMIN(s->bitstream_size, s->max_framesize));
-        input_buf_size= buf_size;
-
-        if (s->bitstream_size + buf_size < buf_size || s->bitstream_index + s->bitstream_size + buf_size < s->bitstream_index)
-            return -1;
-
-        if (s->allocated_bitstream_size < s->bitstream_size + buf_size)
-            s->bitstream= av_fast_realloc(s->bitstream, &s->allocated_bitstream_size, s->bitstream_size + buf_size);
-
-        if (s->bitstream_index + s->bitstream_size + buf_size > s->allocated_bitstream_size) {
-            memmove(s->bitstream, &s->bitstream[s->bitstream_index],
-                    s->bitstream_size);
-            s->bitstream_index=0;
-        }
-        memcpy(&s->bitstream[s->bitstream_index + s->bitstream_size],
-               buf, buf_size);
-        buf= &s->bitstream[s->bitstream_index];
-        buf_size += s->bitstream_size;
-        s->bitstream_size= buf_size;
-
-        if (buf_size < s->max_framesize && input_buf_size) {
-            return input_buf_size;
-        }
+        s->max_framesize =
+            ff_flac_get_max_frame_size(s->max_blocksize ? s->max_blocksize : FLAC_MAX_BLOCKSIZE,
+                                       FLAC_MAX_CHANNELS, 32);
     }
 
     /* check that there is at least the smallest decodable amount of data.
        this amount corresponds to the smallest valid FLAC frame possible.
        FF F8 69 02 00 00 9A 00 00 34 46 */
-    if (buf_size < 11)
-        goto end;
+    if (buf_size < FLAC_MIN_FRAME_SIZE)
+        return buf_size;
 
     /* check for inline header */
     if (AV_RB32(buf) == MKBETAG('f','L','a','C')) {
@@ -693,26 +575,13 @@ static int flac_decode_frame(AVCodecContext *avctx,
             av_log(s->avctx, AV_LOG_ERROR, "invalid header\n");
             return -1;
         }
-        bytes_read = get_metadata_size(buf, buf_size);
-        goto end;
-    }
-
-    /* check for frame sync code and resync stream if necessary */
-    if ((AV_RB16(buf) & 0xFFFE) != 0xFFF8) {
-        const uint8_t *buf_end = buf + buf_size;
-        av_log(s->avctx, AV_LOG_ERROR, "FRAME HEADER not here\n");
-        while (buf+2 < buf_end && (AV_RB16(buf) & 0xFFFE) != 0xFFF8)
-            buf++;
-        bytes_read = buf_size - (buf_end - buf);
-        goto end; // we may not have enough bits left to decode a frame, so try next time
+        return get_metadata_size(buf, buf_size);
     }
 
     /* decode frame */
     init_get_bits(&s->gb, buf, buf_size*8);
     if (decode_frame(s) < 0) {
         av_log(s->avctx, AV_LOG_ERROR, "decode_frame() failed\n");
-        s->bitstream_size=0;
-        s->bitstream_index=0;
         return -1;
     }
     bytes_read = (get_bits_count(&s->gb)+7)/8;
@@ -722,7 +591,7 @@ static int flac_decode_frame(AVCodecContext *avctx,
     if (output_size > alloc_data_size) {
         av_log(s->avctx, AV_LOG_ERROR, "output data size is larger than "
                                        "allocated data size\n");
-        goto end;
+        return -1;
     }
     *data_size = output_size;
 
@@ -760,20 +629,16 @@ static int flac_decode_frame(AVCodecContext *avctx,
         DECORRELATE( (a-=b>>1) + b, a)
     }
 
-end:
     if (bytes_read > buf_size) {
         av_log(s->avctx, AV_LOG_ERROR, "overread: %d\n", bytes_read - buf_size);
-        s->bitstream_size=0;
-        s->bitstream_index=0;
         return -1;
     }
+    if (bytes_read < buf_size) {
+        av_log(s->avctx, AV_LOG_DEBUG, "underread: %d orig size: %d\n",
+               buf_size - bytes_read, buf_size);
+    }
 
-    if (s->bitstream_size) {
-        s->bitstream_index += bytes_read;
-        s->bitstream_size  -= bytes_read;
-        return input_buf_size;
-    } else
-        return bytes_read;
+    return bytes_read;
 }
 
 static av_cold int flac_decode_close(AVCodecContext *avctx)
@@ -784,20 +649,11 @@ static av_cold int flac_decode_close(AVCodecContext *avctx)
     for (i = 0; i < s->channels; i++) {
         av_freep(&s->decoded[i]);
     }
-    av_freep(&s->bitstream);
 
     return 0;
 }
 
-static void flac_flush(AVCodecContext *avctx)
-{
-    FLACContext *s = avctx->priv_data;
-
-    s->bitstream_size=
-    s->bitstream_index= 0;
-}
-
-AVCodec flac_decoder = {
+AVCodec ff_flac_decoder = {
     "flac",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_FLAC,
@@ -806,9 +662,5 @@ AVCodec flac_decoder = {
     NULL,
     flac_decode_close,
     flac_decode_frame,
-    CODEC_CAP_DELAY | CODEC_CAP_SUBFRAMES, /* FIXME: add a FLAC parser so that
-                                              we will not need to use either
-                                              of these capabilities */
-    .flush= flac_flush,
     .long_name= NULL_IF_CONFIG_SMALL("FLAC (Free Lossless Audio Codec)"),
 };
diff --git a/libavcodec/flacenc.c b/libavcodec/flacenc.c
index 89d40d5..d93bfb5 100644
--- a/libavcodec/flacenc.c
+++ b/libavcodec/flacenc.c
@@ -2,20 +2,20 @@
  * FLAC audio encoder
  * Copyright (c) 2006  Justin Ruggles <justin.ruggles at gmail.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -23,7 +23,6 @@
 #include "libavutil/md5.h"
 #include "avcodec.h"
 #include "get_bits.h"
-#include "dsputil.h"
 #include "golomb.h"
 #include "lpc.h"
 #include "flac.h"
@@ -44,7 +43,8 @@
 typedef struct CompressionOptions {
     int compression_level;
     int block_time_ms;
-    int use_lpc;
+    enum AVLPCType lpc_type;
+    int lpc_passes;
     int lpc_coeff_precision;
     int min_prediction_order;
     int max_prediction_order;
@@ -76,6 +76,7 @@ typedef struct FlacFrame {
     int bs_code[2];
     uint8_t crc8;
     int ch_mode;
+    int verbatim_only;
 } FlacFrame;
 
 typedef struct FlacEncodeContext {
@@ -93,12 +94,13 @@ typedef struct FlacEncodeContext {
     FlacFrame frame;
     CompressionOptions options;
     AVCodecContext *avctx;
-    DSPContext dsp;
+    LPCContext lpc_ctx;
     struct AVMD5 *md5ctx;
 } FlacEncodeContext;
 
+
 /**
- * Writes streaminfo metadata block to byte array
+ * Write streaminfo metadata block to byte array.
  */
 static void write_streaminfo(FlacEncodeContext *s, uint8_t *header)
 {
@@ -122,9 +124,10 @@ static void write_streaminfo(FlacEncodeContext *s, uint8_t *header)
     memcpy(&header[18], s->md5sum, 16);
 }
 
+
 /**
- * Sets blocksize based on samplerate
- * Chooses the closest predefined blocksize >= BLOCK_TIME_MS milliseconds
+ * Set blocksize based on samplerate.
+ * Choose the closest predefined blocksize >= BLOCK_TIME_MS milliseconds.
  */
 static int select_blocksize(int samplerate, int block_time_ms)
 {
@@ -134,41 +137,97 @@ static int select_blocksize(int samplerate, int block_time_ms)
 
     assert(samplerate > 0);
     blocksize = ff_flac_blocksize_table[1];
-    target = (samplerate * block_time_ms) / 1000;
-    for(i=0; i<16; i++) {
-        if(target >= ff_flac_blocksize_table[i] && ff_flac_blocksize_table[i] > blocksize) {
+    target    = (samplerate * block_time_ms) / 1000;
+    for (i = 0; i < 16; i++) {
+        if (target >= ff_flac_blocksize_table[i] &&
+            ff_flac_blocksize_table[i] > blocksize) {
             blocksize = ff_flac_blocksize_table[i];
         }
     }
     return blocksize;
 }
 
+
+static av_cold void dprint_compression_options(FlacEncodeContext *s)
+{
+    AVCodecContext     *avctx = s->avctx;
+    CompressionOptions *opt   = &s->options;
+
+    av_log(avctx, AV_LOG_DEBUG, " compression: %d\n", opt->compression_level);
+
+    switch (opt->lpc_type) {
+    case AV_LPC_TYPE_NONE:
+        av_log(avctx, AV_LOG_DEBUG, " lpc type: None\n");
+        break;
+    case AV_LPC_TYPE_FIXED:
+        av_log(avctx, AV_LOG_DEBUG, " lpc type: Fixed pre-defined coefficients\n");
+        break;
+    case AV_LPC_TYPE_LEVINSON:
+        av_log(avctx, AV_LOG_DEBUG, " lpc type: Levinson-Durbin recursion with Welch window\n");
+        break;
+    case AV_LPC_TYPE_CHOLESKY:
+        av_log(avctx, AV_LOG_DEBUG, " lpc type: Cholesky factorization, %d pass%s\n",
+               opt->lpc_passes, opt->lpc_passes == 1 ? "" : "es");
+        break;
+    }
+
+    av_log(avctx, AV_LOG_DEBUG, " prediction order: %d, %d\n",
+           opt->min_prediction_order, opt->max_prediction_order);
+
+    switch (opt->prediction_order_method) {
+    case ORDER_METHOD_EST:
+        av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "estimate");
+        break;
+    case ORDER_METHOD_2LEVEL:
+        av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "2-level");
+        break;
+    case ORDER_METHOD_4LEVEL:
+        av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "4-level");
+        break;
+    case ORDER_METHOD_8LEVEL:
+        av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "8-level");
+        break;
+    case ORDER_METHOD_SEARCH:
+        av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "full search");
+        break;
+    case ORDER_METHOD_LOG:
+        av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "log search");
+        break;
+    }
+
+
+    av_log(avctx, AV_LOG_DEBUG, " partition order: %d, %d\n",
+           opt->min_partition_order, opt->max_partition_order);
+
+    av_log(avctx, AV_LOG_DEBUG, " block size: %d\n", avctx->frame_size);
+
+    av_log(avctx, AV_LOG_DEBUG, " lpc precision: %d\n",
+           opt->lpc_coeff_precision);
+}
+
+
 static av_cold int flac_encode_init(AVCodecContext *avctx)
 {
     int freq = avctx->sample_rate;
     int channels = avctx->channels;
     FlacEncodeContext *s = avctx->priv_data;
-    int i, level;
+    int i, level, ret;
     uint8_t *streaminfo;
 
     s->avctx = avctx;
 
-    dsputil_init(&s->dsp, avctx);
-
-    if(avctx->sample_fmt != SAMPLE_FMT_S16) {
+    if (avctx->sample_fmt != AV_SAMPLE_FMT_S16)
         return -1;
-    }
 
-    if(channels < 1 || channels > FLAC_MAX_CHANNELS) {
+    if (channels < 1 || channels > FLAC_MAX_CHANNELS)
         return -1;
-    }
     s->channels = channels;
 
     /* find samplerate in table */
-    if(freq < 1)
+    if (freq < 1)
         return -1;
-    for(i=4; i<12; i++) {
-        if(freq == ff_flac_sample_rate_table[i]) {
+    for (i = 4; i < 12; i++) {
+        if (freq == ff_flac_sample_rate_table[i]) {
             s->samplerate = ff_flac_sample_rate_table[i];
             s->sr_code[0] = i;
             s->sr_code[1] = 0;
@@ -176,14 +235,14 @@ static av_cold int flac_encode_init(AVCodecContext *avctx)
         }
     }
     /* if not in table, samplerate is non-standard */
-    if(i == 12) {
-        if(freq % 1000 == 0 && freq < 255000) {
+    if (i == 12) {
+        if (freq % 1000 == 0 && freq < 255000) {
             s->sr_code[0] = 12;
             s->sr_code[1] = freq / 1000;
-        } else if(freq % 10 == 0 && freq < 655350) {
+        } else if (freq % 10 == 0 && freq < 655350) {
             s->sr_code[0] = 14;
             s->sr_code[1] = freq / 10;
-        } else if(freq < 65535) {
+        } else if (freq < 65535) {
             s->sr_code[0] = 13;
             s->sr_code[1] = freq;
         } else {
@@ -193,132 +252,143 @@ static av_cold int flac_encode_init(AVCodecContext *avctx)
     }
 
     /* set compression option defaults based on avctx->compression_level */
-    if(avctx->compression_level < 0) {
+    if (avctx->compression_level < 0)
         s->options.compression_level = 5;
-    } else {
+    else
         s->options.compression_level = avctx->compression_level;
-    }
-    av_log(avctx, AV_LOG_DEBUG, " compression: %d\n", s->options.compression_level);
 
-    level= s->options.compression_level;
-    if(level > 12) {
+    level = s->options.compression_level;
+    if (level > 12) {
         av_log(avctx, AV_LOG_ERROR, "invalid compression level: %d\n",
                s->options.compression_level);
         return -1;
     }
 
-    s->options.block_time_ms       = ((int[]){ 27, 27, 27,105,105,105,105,105,105,105,105,105,105})[level];
-    s->options.use_lpc             = ((int[]){  0,  0,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1})[level];
-    s->options.min_prediction_order= ((int[]){  2,  0,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1})[level];
-    s->options.max_prediction_order= ((int[]){  3,  4,  4,  6,  8,  8,  8,  8, 12, 12, 12, 32, 32})[level];
+    s->options.block_time_ms = ((int[]){ 27, 27, 27,105,105,105,105,105,105,105,105,105,105})[level];
+
+    s->options.lpc_type      = ((int[]){ AV_LPC_TYPE_FIXED,    AV_LPC_TYPE_FIXED,    AV_LPC_TYPE_FIXED,
+                                         AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON,
+                                         AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON,
+                                         AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON,
+                                         AV_LPC_TYPE_LEVINSON})[level];
+
+    s->options.min_prediction_order = ((int[]){  2,  0,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1})[level];
+    s->options.max_prediction_order = ((int[]){  3,  4,  4,  6,  8,  8,  8,  8, 12, 12, 12, 32, 32})[level];
+
     s->options.prediction_order_method = ((int[]){ ORDER_METHOD_EST,    ORDER_METHOD_EST,    ORDER_METHOD_EST,
                                                    ORDER_METHOD_EST,    ORDER_METHOD_EST,    ORDER_METHOD_EST,
                                                    ORDER_METHOD_4LEVEL, ORDER_METHOD_LOG,    ORDER_METHOD_4LEVEL,
                                                    ORDER_METHOD_LOG,    ORDER_METHOD_SEARCH, ORDER_METHOD_LOG,
                                                    ORDER_METHOD_SEARCH})[level];
+
     s->options.min_partition_order = ((int[]){  2,  2,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0})[level];
     s->options.max_partition_order = ((int[]){  2,  2,  3,  3,  3,  8,  8,  8,  8,  8,  8,  8,  8})[level];
 
     /* set compression option overrides from AVCodecContext */
-    if(avctx->use_lpc >= 0) {
-        s->options.use_lpc = av_clip(avctx->use_lpc, 0, 11);
+#if FF_API_USE_LPC
+    /* for compatibility with deprecated AVCodecContext.use_lpc */
+    if (avctx->use_lpc == 0) {
+        s->options.lpc_type = AV_LPC_TYPE_FIXED;
+    } else if (avctx->use_lpc == 1) {
+        s->options.lpc_type = AV_LPC_TYPE_LEVINSON;
+    } else if (avctx->use_lpc > 1) {
+        s->options.lpc_type   = AV_LPC_TYPE_CHOLESKY;
+        s->options.lpc_passes = avctx->use_lpc - 1;
     }
-    if(s->options.use_lpc == 1)
-        av_log(avctx, AV_LOG_DEBUG, " use lpc: Levinson-Durbin recursion with Welch window\n");
-    else if(s->options.use_lpc > 1)
-        av_log(avctx, AV_LOG_DEBUG, " use lpc: Cholesky factorization\n");
-
-    if(avctx->min_prediction_order >= 0) {
-        if(s->options.use_lpc) {
-            if(avctx->min_prediction_order < MIN_LPC_ORDER ||
-                    avctx->min_prediction_order > MAX_LPC_ORDER) {
-                av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
-                       avctx->min_prediction_order);
+#endif
+    if (avctx->lpc_type > AV_LPC_TYPE_DEFAULT) {
+        if (avctx->lpc_type > AV_LPC_TYPE_CHOLESKY) {
+            av_log(avctx, AV_LOG_ERROR, "unknown lpc type: %d\n", avctx->lpc_type);
+            return -1;
+        }
+        s->options.lpc_type = avctx->lpc_type;
+        if (s->options.lpc_type == AV_LPC_TYPE_CHOLESKY) {
+            if (avctx->lpc_passes < 0) {
+                // default number of passes for Cholesky
+                s->options.lpc_passes = 2;
+            } else if (avctx->lpc_passes == 0) {
+                av_log(avctx, AV_LOG_ERROR, "invalid number of lpc passes: %d\n",
+                       avctx->lpc_passes);
                 return -1;
+            } else {
+                s->options.lpc_passes = avctx->lpc_passes;
             }
-        } else {
-            if(avctx->min_prediction_order > MAX_FIXED_ORDER) {
+        }
+    }
+
+    if (s->options.lpc_type == AV_LPC_TYPE_NONE) {
+        s->options.min_prediction_order = 0;
+    } else if (avctx->min_prediction_order >= 0) {
+        if (s->options.lpc_type == AV_LPC_TYPE_FIXED) {
+            if (avctx->min_prediction_order > MAX_FIXED_ORDER) {
                 av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
                        avctx->min_prediction_order);
                 return -1;
             }
+        } else if (avctx->min_prediction_order < MIN_LPC_ORDER ||
+                   avctx->min_prediction_order > MAX_LPC_ORDER) {
+            av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
+                   avctx->min_prediction_order);
+            return -1;
         }
         s->options.min_prediction_order = avctx->min_prediction_order;
     }
-    if(avctx->max_prediction_order >= 0) {
-        if(s->options.use_lpc) {
-            if(avctx->max_prediction_order < MIN_LPC_ORDER ||
-                    avctx->max_prediction_order > MAX_LPC_ORDER) {
-                av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
-                       avctx->max_prediction_order);
-                return -1;
-            }
-        } else {
-            if(avctx->max_prediction_order > MAX_FIXED_ORDER) {
+    if (s->options.lpc_type == AV_LPC_TYPE_NONE) {
+        s->options.max_prediction_order = 0;
+    } else if (avctx->max_prediction_order >= 0) {
+        if (s->options.lpc_type == AV_LPC_TYPE_FIXED) {
+            if (avctx->max_prediction_order > MAX_FIXED_ORDER) {
                 av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
                        avctx->max_prediction_order);
                 return -1;
             }
+        } else if (avctx->max_prediction_order < MIN_LPC_ORDER ||
+                   avctx->max_prediction_order > MAX_LPC_ORDER) {
+            av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
+                   avctx->max_prediction_order);
+            return -1;
         }
         s->options.max_prediction_order = avctx->max_prediction_order;
     }
-    if(s->options.max_prediction_order < s->options.min_prediction_order) {
+    if (s->options.max_prediction_order < s->options.min_prediction_order) {
         av_log(avctx, AV_LOG_ERROR, "invalid prediction orders: min=%d max=%d\n",
                s->options.min_prediction_order, s->options.max_prediction_order);
         return -1;
     }
-    av_log(avctx, AV_LOG_DEBUG, " prediction order: %d, %d\n",
-           s->options.min_prediction_order, s->options.max_prediction_order);
 
-    if(avctx->prediction_order_method >= 0) {
-        if(avctx->prediction_order_method > ORDER_METHOD_LOG) {
+    if (avctx->prediction_order_method >= 0) {
+        if (avctx->prediction_order_method > ORDER_METHOD_LOG) {
             av_log(avctx, AV_LOG_ERROR, "invalid prediction order method: %d\n",
                    avctx->prediction_order_method);
             return -1;
         }
         s->options.prediction_order_method = avctx->prediction_order_method;
     }
-    switch(s->options.prediction_order_method) {
-        case ORDER_METHOD_EST:    av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
-                                         "estimate"); break;
-        case ORDER_METHOD_2LEVEL: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
-                                         "2-level"); break;
-        case ORDER_METHOD_4LEVEL: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
-                                         "4-level"); break;
-        case ORDER_METHOD_8LEVEL: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
-                                         "8-level"); break;
-        case ORDER_METHOD_SEARCH: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
-                                         "full search"); break;
-        case ORDER_METHOD_LOG:    av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
-                                         "log search"); break;
-    }
 
-    if(avctx->min_partition_order >= 0) {
-        if(avctx->min_partition_order > MAX_PARTITION_ORDER) {
+    if (avctx->min_partition_order >= 0) {
+        if (avctx->min_partition_order > MAX_PARTITION_ORDER) {
             av_log(avctx, AV_LOG_ERROR, "invalid min partition order: %d\n",
                    avctx->min_partition_order);
             return -1;
         }
         s->options.min_partition_order = avctx->min_partition_order;
     }
-    if(avctx->max_partition_order >= 0) {
-        if(avctx->max_partition_order > MAX_PARTITION_ORDER) {
+    if (avctx->max_partition_order >= 0) {
+        if (avctx->max_partition_order > MAX_PARTITION_ORDER) {
             av_log(avctx, AV_LOG_ERROR, "invalid max partition order: %d\n",
                    avctx->max_partition_order);
             return -1;
         }
         s->options.max_partition_order = avctx->max_partition_order;
     }
-    if(s->options.max_partition_order < s->options.min_partition_order) {
+    if (s->options.max_partition_order < s->options.min_partition_order) {
         av_log(avctx, AV_LOG_ERROR, "invalid partition orders: min=%d max=%d\n",
                s->options.min_partition_order, s->options.max_partition_order);
         return -1;
     }
-    av_log(avctx, AV_LOG_DEBUG, " partition order: %d, %d\n",
-           s->options.min_partition_order, s->options.max_partition_order);
 
-    if(avctx->frame_size > 0) {
-        if(avctx->frame_size < FLAC_MIN_BLOCKSIZE ||
+    if (avctx->frame_size > 0) {
+        if (avctx->frame_size < FLAC_MIN_BLOCKSIZE ||
                 avctx->frame_size > FLAC_MAX_BLOCKSIZE) {
             av_log(avctx, AV_LOG_ERROR, "invalid block size: %d\n",
                    avctx->frame_size);
@@ -328,11 +398,10 @@ static av_cold int flac_encode_init(AVCodecContext *avctx)
         s->avctx->frame_size = select_blocksize(s->samplerate, s->options.block_time_ms);
     }
     s->max_blocksize = s->avctx->frame_size;
-    av_log(avctx, AV_LOG_DEBUG, " block size: %d\n", s->avctx->frame_size);
 
     /* set LPC precision */
-    if(avctx->lpc_coeff_precision > 0) {
-        if(avctx->lpc_coeff_precision > MAX_LPC_PRECISION) {
+    if (avctx->lpc_coeff_precision > 0) {
+        if (avctx->lpc_coeff_precision > MAX_LPC_PRECISION) {
             av_log(avctx, AV_LOG_ERROR, "invalid lpc coeff precision: %d\n",
                    avctx->lpc_coeff_precision);
             return -1;
@@ -342,8 +411,6 @@ static av_cold int flac_encode_init(AVCodecContext *avctx)
         /* default LPC precision */
         s->options.lpc_coeff_precision = 15;
     }
-    av_log(avctx, AV_LOG_DEBUG, " lpc precision: %d\n",
-           s->options.lpc_coeff_precision);
 
     /* set maximum encoded frame size in verbatim mode */
     s->max_framesize = ff_flac_get_max_frame_size(s->avctx->frame_size,
@@ -351,24 +418,33 @@ static av_cold int flac_encode_init(AVCodecContext *avctx)
 
     /* initialize MD5 context */
     s->md5ctx = av_malloc(av_md5_size);
-    if(!s->md5ctx)
+    if (!s->md5ctx)
         return AVERROR(ENOMEM);
     av_md5_init(s->md5ctx);
 
     streaminfo = av_malloc(FLAC_STREAMINFO_SIZE);
+    if (!streaminfo)
+        return AVERROR(ENOMEM);
     write_streaminfo(s, streaminfo);
     avctx->extradata = streaminfo;
     avctx->extradata_size = FLAC_STREAMINFO_SIZE;
 
-    s->frame_count = 0;
+    s->frame_count   = 0;
     s->min_framesize = s->max_framesize;
 
     avctx->coded_frame = avcodec_alloc_frame();
-    avctx->coded_frame->key_frame = 1;
+    if (!avctx->coded_frame)
+        return AVERROR(ENOMEM);
 
-    return 0;
+    ret = ff_lpc_init(&s->lpc_ctx, avctx->frame_size,
+                      s->options.max_prediction_order, AV_LPC_TYPE_LEVINSON);
+
+    dprint_compression_options(s);
+
+    return ret;
 }
 
+
 static void init_frame(FlacEncodeContext *s)
 {
     int i, ch;
@@ -376,17 +452,17 @@ static void init_frame(FlacEncodeContext *s)
 
     frame = &s->frame;
 
-    for(i=0; i<16; i++) {
-        if(s->avctx->frame_size == ff_flac_blocksize_table[i]) {
-            frame->blocksize = ff_flac_blocksize_table[i];
+    for (i = 0; i < 16; i++) {
+        if (s->avctx->frame_size == ff_flac_blocksize_table[i]) {
+            frame->blocksize  = ff_flac_blocksize_table[i];
             frame->bs_code[0] = i;
             frame->bs_code[1] = 0;
             break;
         }
     }
-    if(i == 16) {
+    if (i == 16) {
         frame->blocksize = s->avctx->frame_size;
-        if(frame->blocksize <= 256) {
+        if (frame->blocksize <= 256) {
             frame->bs_code[0] = 6;
             frame->bs_code[1] = frame->blocksize-1;
         } else {
@@ -395,45 +471,107 @@ static void init_frame(FlacEncodeContext *s)
         }
     }
 
-    for(ch=0; ch<s->channels; ch++) {
+    for (ch = 0; ch < s->channels; ch++)
         frame->subframes[ch].obits = 16;
-    }
+
+    frame->verbatim_only = 0;
 }
 
+
 /**
- * Copy channel-interleaved input samples into separate subframes
+ * Copy channel-interleaved input samples into separate subframes.
  */
-static void copy_samples(FlacEncodeContext *s, int16_t *samples)
+static void copy_samples(FlacEncodeContext *s, const int16_t *samples)
 {
     int i, j, ch;
     FlacFrame *frame;
 
     frame = &s->frame;
-    for(i=0,j=0; i<frame->blocksize; i++) {
-        for(ch=0; ch<s->channels; ch++,j++) {
+    for (i = 0, j = 0; i < frame->blocksize; i++)
+        for (ch = 0; ch < s->channels; ch++, j++)
             frame->subframes[ch].samples[i] = samples[j];
+}
+
+
+static int rice_count_exact(int32_t *res, int n, int k)
+{
+    int i;
+    int count = 0;
+
+    for (i = 0; i < n; i++) {
+        int32_t v = -2 * res[i] - 1;
+        v ^= v >> 31;
+        count += (v >> k) + 1 + k;
+    }
+    return count;
+}
+
+
+static int subframe_count_exact(FlacEncodeContext *s, FlacSubframe *sub,
+                                int pred_order)
+{
+    int p, porder, psize;
+    int i, part_end;
+    int count = 0;
+
+    /* subframe header */
+    count += 8;
+
+    /* subframe */
+    if (sub->type == FLAC_SUBFRAME_CONSTANT) {
+        count += sub->obits;
+    } else if (sub->type == FLAC_SUBFRAME_VERBATIM) {
+        count += s->frame.blocksize * sub->obits;
+    } else {
+        /* warm-up samples */
+        count += pred_order * sub->obits;
+
+        /* LPC coefficients */
+        if (sub->type == FLAC_SUBFRAME_LPC)
+            count += 4 + 5 + pred_order * s->options.lpc_coeff_precision;
+
+        /* rice-encoded block */
+        count += 2;
+
+        /* partition order */
+        porder = sub->rc.porder;
+        psize  = s->frame.blocksize >> porder;
+        count += 4;
+
+        /* residual */
+        i        = pred_order;
+        part_end = psize;
+        for (p = 0; p < 1 << porder; p++) {
+            int k = sub->rc.params[p];
+            count += 4;
+            count += rice_count_exact(&sub->residual[i], part_end - i, k);
+            i = part_end;
+            part_end = FFMIN(s->frame.blocksize, part_end + psize);
         }
     }
+
+    return count;
 }
 
 
 #define rice_encode_count(sum, n, k) (((n)*((k)+1))+((sum-(n>>1))>>(k)))
 
 /**
- * Solve for d/dk(rice_encode_count) = n-((sum-(n>>1))>>(k+1)) = 0
+ * Solve for d/dk(rice_encode_count) = n-((sum-(n>>1))>>(k+1)) = 0.
  */
 static int find_optimal_param(uint32_t sum, int n)
 {
     int k;
     uint32_t sum2;
 
-    if(sum <= n>>1)
+    if (sum <= n >> 1)
         return 0;
-    sum2 = sum-(n>>1);
-    k = av_log2(n<256 ? FASTDIV(sum2,n) : sum2/n);
+    sum2 = sum - (n >> 1);
+    k    = av_log2(n < 256 ? FASTDIV(sum2, n) : sum2 / n);
     return FFMIN(k, MAX_RICE_PARAM);
 }
 
+
 static uint32_t calc_optimal_rice_params(RiceContext *rc, int porder,
                                          uint32_t *sums, int n, int pred_order)
 {
@@ -441,11 +579,11 @@ static uint32_t calc_optimal_rice_params(RiceContext *rc, int porder,
     int k, cnt, part;
     uint32_t all_bits;
 
-    part = (1 << porder);
+    part     = (1 << porder);
     all_bits = 4 * part;
 
     cnt = (n >> porder) - pred_order;
-    for(i=0; i<part; i++) {
+    for (i = 0; i < part; i++) {
         k = find_optimal_param(sums[i], cnt);
         rc->params[i] = k;
         all_bits += rice_encode_count(sums[i], cnt, k);
@@ -457,6 +595,7 @@ static uint32_t calc_optimal_rice_params(RiceContext *rc, int porder,
     return all_bits;
 }
 
+
 static void calc_sums(int pmin, int pmax, uint32_t *data, int n, int pred_order,
                       uint32_t sums[][MAX_PARTITIONS])
 {
@@ -465,26 +604,25 @@ static void calc_sums(int pmin, int pmax, uint32_t *data, int n, int pred_order,
     uint32_t *res, *res_end;
 
     /* sums for highest level */
-    parts = (1 << pmax);
-    res = &data[pred_order];
+    parts   = (1 << pmax);
+    res     = &data[pred_order];
     res_end = &data[n >> pmax];
-    for(i=0; i<parts; i++) {
+    for (i = 0; i < parts; i++) {
         uint32_t sum = 0;
-        while(res < res_end){
+        while (res < res_end)
             sum += *(res++);
-        }
         sums[pmax][i] = sum;
-        res_end+= n >> pmax;
+        res_end += n >> pmax;
     }
     /* sums for lower levels */
-    for(i=pmax-1; i>=pmin; i--) {
+    for (i = pmax - 1; i >= pmin; i--) {
         parts = (1 << i);
-        for(j=0; j<parts; j++) {
+        for (j = 0; j < parts; j++)
             sums[i][j] = sums[i+1][2*j] + sums[i+1][2*j+1];
-        }
     }
 }
 
+
 static uint32_t calc_rice_params(RiceContext *rc, int pmin, int pmax,
                                  int32_t *data, int n, int pred_order)
 {
@@ -500,19 +638,18 @@ static uint32_t calc_rice_params(RiceContext *rc, int pmin, int pmax,
     assert(pmin <= pmax);
 
     udata = av_malloc(n * sizeof(uint32_t));
-    for(i=0; i<n; i++) {
+    for (i = 0; i < n; i++)
         udata[i] = (2*data[i]) ^ (data[i]>>31);
-    }
 
     calc_sums(pmin, pmax, udata, n, pred_order, sums);
 
     opt_porder = pmin;
     bits[pmin] = UINT32_MAX;
-    for(i=pmin; i<=pmax; i++) {
+    for (i = pmin; i <= pmax; i++) {
         bits[i] = calc_optimal_rice_params(&tmp_rc, i, sums[i], n, pred_order);
-        if(bits[i] <= bits[opt_porder]) {
+        if (bits[i] <= bits[opt_porder]) {
             opt_porder = i;
-            *rc= tmp_rc;
+            *rc = tmp_rc;
         }
     }
 
@@ -520,155 +657,144 @@ static uint32_t calc_rice_params(RiceContext *rc, int pmin, int pmax,
     return bits[opt_porder];
 }
 
+
 static int get_max_p_order(int max_porder, int n, int order)
 {
     int porder = FFMIN(max_porder, av_log2(n^(n-1)));
-    if(order > 0)
+    if (order > 0)
         porder = FFMIN(porder, av_log2(n/order));
     return porder;
 }
 
-static uint32_t calc_rice_params_fixed(RiceContext *rc, int pmin, int pmax,
-                                       int32_t *data, int n, int pred_order,
-                                       int bps)
-{
-    uint32_t bits;
-    pmin = get_max_p_order(pmin, n, pred_order);
-    pmax = get_max_p_order(pmax, n, pred_order);
-    bits = pred_order*bps + 6;
-    bits += calc_rice_params(rc, pmin, pmax, data, n, pred_order);
-    return bits;
-}
 
-static uint32_t calc_rice_params_lpc(RiceContext *rc, int pmin, int pmax,
-                                     int32_t *data, int n, int pred_order,
-                                     int bps, int precision)
+static uint32_t find_subframe_rice_params(FlacEncodeContext *s,
+                                          FlacSubframe *sub, int pred_order)
 {
-    uint32_t bits;
-    pmin = get_max_p_order(pmin, n, pred_order);
-    pmax = get_max_p_order(pmax, n, pred_order);
-    bits = pred_order*bps + 4 + 5 + pred_order*precision + 6;
-    bits += calc_rice_params(rc, pmin, pmax, data, n, pred_order);
+    int pmin = get_max_p_order(s->options.min_partition_order,
+                               s->frame.blocksize, pred_order);
+    int pmax = get_max_p_order(s->options.max_partition_order,
+                               s->frame.blocksize, pred_order);
+
+    uint32_t bits = 8 + pred_order * sub->obits + 2 + 4;
+    if (sub->type == FLAC_SUBFRAME_LPC)
+        bits += 4 + 5 + pred_order * s->options.lpc_coeff_precision;
+    bits += calc_rice_params(&sub->rc, pmin, pmax, sub->residual,
+                             s->frame.blocksize, pred_order);
     return bits;
 }
 
-static void encode_residual_verbatim(int32_t *res, int32_t *smp, int n)
-{
-    assert(n > 0);
-    memcpy(res, smp, n * sizeof(int32_t));
-}
 
 static void encode_residual_fixed(int32_t *res, const int32_t *smp, int n,
                                   int order)
 {
     int i;
 
-    for(i=0; i<order; i++) {
+    for (i = 0; i < order; i++)
         res[i] = smp[i];
-    }
 
-    if(order==0){
-        for(i=order; i<n; i++)
-            res[i]= smp[i];
-    }else if(order==1){
-        for(i=order; i<n; i++)
-            res[i]= smp[i] - smp[i-1];
-    }else if(order==2){
+    if (order == 0) {
+        for (i = order; i < n; i++)
+            res[i] = smp[i];
+    } else if (order == 1) {
+        for (i = order; i < n; i++)
+            res[i] = smp[i] - smp[i-1];
+    } else if (order == 2) {
         int a = smp[order-1] - smp[order-2];
-        for(i=order; i<n; i+=2) {
-            int b = smp[i] - smp[i-1];
-            res[i]= b - a;
-            a = smp[i+1] - smp[i];
-            res[i+1]= a - b;
+        for (i = order; i < n; i += 2) {
+            int b    = smp[i  ] - smp[i-1];
+            res[i]   = b - a;
+            a        = smp[i+1] - smp[i  ];
+            res[i+1] = a - b;
         }
-    }else if(order==3){
-        int a = smp[order-1] - smp[order-2];
+    } else if (order == 3) {
+        int a = smp[order-1] -   smp[order-2];
         int c = smp[order-1] - 2*smp[order-2] + smp[order-3];
-        for(i=order; i<n; i+=2) {
-            int b = smp[i] - smp[i-1];
-            int d = b - a;
-            res[i]= d - c;
-            a = smp[i+1] - smp[i];
-            c = a - b;
-            res[i+1]= c - d;
+        for (i = order; i < n; i += 2) {
+            int b    = smp[i  ] - smp[i-1];
+            int d    = b - a;
+            res[i]   = d - c;
+            a        = smp[i+1] - smp[i  ];
+            c        = a - b;
+            res[i+1] = c - d;
         }
-    }else{
-        int a = smp[order-1] - smp[order-2];
-        int c = smp[order-1] - 2*smp[order-2] + smp[order-3];
+    } else {
+        int a = smp[order-1] -   smp[order-2];
+        int c = smp[order-1] - 2*smp[order-2] +   smp[order-3];
         int e = smp[order-1] - 3*smp[order-2] + 3*smp[order-3] - smp[order-4];
-        for(i=order; i<n; i+=2) {
-            int b = smp[i] - smp[i-1];
-            int d = b - a;
-            int f = d - c;
-            res[i]= f - e;
-            a = smp[i+1] - smp[i];
-            c = a - b;
-            e = c - d;
-            res[i+1]= e - f;
+        for (i = order; i < n; i += 2) {
+            int b    = smp[i  ] - smp[i-1];
+            int d    = b - a;
+            int f    = d - c;
+            res[i  ] = f - e;
+            a        = smp[i+1] - smp[i  ];
+            c        = a - b;
+            e        = c - d;
+            res[i+1] = e - f;
         }
     }
 }
 
+
 #define LPC1(x) {\
     int c = coefs[(x)-1];\
-    p0 += c*s;\
-    s = smp[i-(x)+1];\
-    p1 += c*s;\
+    p0   += c * s;\
+    s     = smp[i-(x)+1];\
+    p1   += c * s;\
 }
 
-static av_always_inline void encode_residual_lpc_unrolled(
-    int32_t *res, const int32_t *smp, int n,
-    int order, const int32_t *coefs, int shift, int big)
+static av_always_inline void encode_residual_lpc_unrolled(int32_t *res,
+                                    const int32_t *smp, int n, int order,
+                                    const int32_t *coefs, int shift, int big)
 {
     int i;
-    for(i=order; i<n; i+=2) {
-        int s = smp[i-order];
+    for (i = order; i < n; i += 2) {
+        int s  = smp[i-order];
         int p0 = 0, p1 = 0;
-        if(big) {
-            switch(order) {
-                case 32: LPC1(32)
-                case 31: LPC1(31)
-                case 30: LPC1(30)
-                case 29: LPC1(29)
-                case 28: LPC1(28)
-                case 27: LPC1(27)
-                case 26: LPC1(26)
-                case 25: LPC1(25)
-                case 24: LPC1(24)
-                case 23: LPC1(23)
-                case 22: LPC1(22)
-                case 21: LPC1(21)
-                case 20: LPC1(20)
-                case 19: LPC1(19)
-                case 18: LPC1(18)
-                case 17: LPC1(17)
-                case 16: LPC1(16)
-                case 15: LPC1(15)
-                case 14: LPC1(14)
-                case 13: LPC1(13)
-                case 12: LPC1(12)
-                case 11: LPC1(11)
-                case 10: LPC1(10)
-                case  9: LPC1( 9)
-                         LPC1( 8)
-                         LPC1( 7)
-                         LPC1( 6)
-                         LPC1( 5)
-                         LPC1( 4)
-                         LPC1( 3)
-                         LPC1( 2)
-                         LPC1( 1)
+        if (big) {
+            switch (order) {
+            case 32: LPC1(32)
+            case 31: LPC1(31)
+            case 30: LPC1(30)
+            case 29: LPC1(29)
+            case 28: LPC1(28)
+            case 27: LPC1(27)
+            case 26: LPC1(26)
+            case 25: LPC1(25)
+            case 24: LPC1(24)
+            case 23: LPC1(23)
+            case 22: LPC1(22)
+            case 21: LPC1(21)
+            case 20: LPC1(20)
+            case 19: LPC1(19)
+            case 18: LPC1(18)
+            case 17: LPC1(17)
+            case 16: LPC1(16)
+            case 15: LPC1(15)
+            case 14: LPC1(14)
+            case 13: LPC1(13)
+            case 12: LPC1(12)
+            case 11: LPC1(11)
+            case 10: LPC1(10)
+            case  9: LPC1( 9)
+                     LPC1( 8)
+                     LPC1( 7)
+                     LPC1( 6)
+                     LPC1( 5)
+                     LPC1( 4)
+                     LPC1( 3)
+                     LPC1( 2)
+                     LPC1( 1)
             }
         } else {
-            switch(order) {
-                case  8: LPC1( 8)
-                case  7: LPC1( 7)
-                case  6: LPC1( 6)
-                case  5: LPC1( 5)
-                case  4: LPC1( 4)
-                case  3: LPC1( 3)
-                case  2: LPC1( 2)
-                case  1: LPC1( 1)
+            switch (order) {
+            case  8: LPC1( 8)
+            case  7: LPC1( 7)
+            case  6: LPC1( 6)
+            case  5: LPC1( 5)
+            case  4: LPC1( 4)
+            case  3: LPC1( 3)
+            case  2: LPC1( 2)
+            case  1: LPC1( 1)
             }
         }
         res[i  ] = smp[i  ] - (p0 >> shift);
@@ -676,211 +802,231 @@ static av_always_inline void encode_residual_lpc_unrolled(
     }
 }
 
+
 static void encode_residual_lpc(int32_t *res, const int32_t *smp, int n,
                                 int order, const int32_t *coefs, int shift)
 {
     int i;
-    for(i=0; i<order; i++) {
+    for (i = 0; i < order; i++)
         res[i] = smp[i];
-    }
 #if CONFIG_SMALL
-    for(i=order; i<n; i+=2) {
+    for (i = order; i < n; i += 2) {
         int j;
-        int s = smp[i];
+        int s  = smp[i];
         int p0 = 0, p1 = 0;
-        for(j=0; j<order; j++) {
+        for (j = 0; j < order; j++) {
             int c = coefs[j];
-            p1 += c*s;
-            s = smp[i-j-1];
-            p0 += c*s;
+            p1   += c * s;
+            s     = smp[i-j-1];
+            p0   += c * s;
         }
         res[i  ] = smp[i  ] - (p0 >> shift);
         res[i+1] = smp[i+1] - (p1 >> shift);
     }
 #else
-    switch(order) {
-        case  1: encode_residual_lpc_unrolled(res, smp, n, 1, coefs, shift, 0); break;
-        case  2: encode_residual_lpc_unrolled(res, smp, n, 2, coefs, shift, 0); break;
-        case  3: encode_residual_lpc_unrolled(res, smp, n, 3, coefs, shift, 0); break;
-        case  4: encode_residual_lpc_unrolled(res, smp, n, 4, coefs, shift, 0); break;
-        case  5: encode_residual_lpc_unrolled(res, smp, n, 5, coefs, shift, 0); break;
-        case  6: encode_residual_lpc_unrolled(res, smp, n, 6, coefs, shift, 0); break;
-        case  7: encode_residual_lpc_unrolled(res, smp, n, 7, coefs, shift, 0); break;
-        case  8: encode_residual_lpc_unrolled(res, smp, n, 8, coefs, shift, 0); break;
-        default: encode_residual_lpc_unrolled(res, smp, n, order, coefs, shift, 1); break;
+    switch (order) {
+    case  1: encode_residual_lpc_unrolled(res, smp, n, 1, coefs, shift, 0); break;
+    case  2: encode_residual_lpc_unrolled(res, smp, n, 2, coefs, shift, 0); break;
+    case  3: encode_residual_lpc_unrolled(res, smp, n, 3, coefs, shift, 0); break;
+    case  4: encode_residual_lpc_unrolled(res, smp, n, 4, coefs, shift, 0); break;
+    case  5: encode_residual_lpc_unrolled(res, smp, n, 5, coefs, shift, 0); break;
+    case  6: encode_residual_lpc_unrolled(res, smp, n, 6, coefs, shift, 0); break;
+    case  7: encode_residual_lpc_unrolled(res, smp, n, 7, coefs, shift, 0); break;
+    case  8: encode_residual_lpc_unrolled(res, smp, n, 8, coefs, shift, 0); break;
+    default: encode_residual_lpc_unrolled(res, smp, n, order, coefs, shift, 1); break;
     }
 #endif
 }
 
-static int encode_residual(FlacEncodeContext *ctx, int ch)
+
+static int encode_residual_ch(FlacEncodeContext *s, int ch)
 {
     int i, n;
-    int min_order, max_order, opt_order, precision, omethod;
-    int min_porder, max_porder;
+    int min_order, max_order, opt_order, omethod;
     FlacFrame *frame;
     FlacSubframe *sub;
     int32_t coefs[MAX_LPC_ORDER][MAX_LPC_ORDER];
     int shift[MAX_LPC_ORDER];
     int32_t *res, *smp;
 
-    frame = &ctx->frame;
-    sub = &frame->subframes[ch];
-    res = sub->residual;
-    smp = sub->samples;
-    n = frame->blocksize;
+    frame = &s->frame;
+    sub   = &frame->subframes[ch];
+    res   = sub->residual;
+    smp   = sub->samples;
+    n     = frame->blocksize;
 
     /* CONSTANT */
-    for(i=1; i<n; i++) {
-        if(smp[i] != smp[0]) break;
-    }
-    if(i == n) {
+    for (i = 1; i < n; i++)
+        if(smp[i] != smp[0])
+            break;
+    if (i == n) {
         sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
         res[0] = smp[0];
-        return sub->obits;
+        return subframe_count_exact(s, sub, 0);
     }
 
     /* VERBATIM */
-    if(n < 5) {
+    if (frame->verbatim_only || n < 5) {
         sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
-        encode_residual_verbatim(res, smp, n);
-        return sub->obits * n;
+        memcpy(res, smp, n * sizeof(int32_t));
+        return subframe_count_exact(s, sub, 0);
     }
 
-    min_order = ctx->options.min_prediction_order;
-    max_order = ctx->options.max_prediction_order;
-    min_porder = ctx->options.min_partition_order;
-    max_porder = ctx->options.max_partition_order;
-    precision = ctx->options.lpc_coeff_precision;
-    omethod = ctx->options.prediction_order_method;
+    min_order  = s->options.min_prediction_order;
+    max_order  = s->options.max_prediction_order;
+    omethod    = s->options.prediction_order_method;
 
     /* FIXED */
-    if(!ctx->options.use_lpc || max_order == 0 || (n <= max_order)) {
+    sub->type = FLAC_SUBFRAME_FIXED;
+    if (s->options.lpc_type == AV_LPC_TYPE_NONE  ||
+        s->options.lpc_type == AV_LPC_TYPE_FIXED || n <= max_order) {
         uint32_t bits[MAX_FIXED_ORDER+1];
-        if(max_order > MAX_FIXED_ORDER) max_order = MAX_FIXED_ORDER;
+        if (max_order > MAX_FIXED_ORDER)
+            max_order = MAX_FIXED_ORDER;
         opt_order = 0;
-        bits[0] = UINT32_MAX;
-        for(i=min_order; i<=max_order; i++) {
+        bits[0]   = UINT32_MAX;
+        for (i = min_order; i <= max_order; i++) {
             encode_residual_fixed(res, smp, n, i);
-            bits[i] = calc_rice_params_fixed(&sub->rc, min_porder, max_porder, res,
-                                             n, i, sub->obits);
-            if(bits[i] < bits[opt_order]) {
+            bits[i] = find_subframe_rice_params(s, sub, i);
+            if (bits[i] < bits[opt_order])
                 opt_order = i;
-            }
         }
-        sub->order = opt_order;
-        sub->type = FLAC_SUBFRAME_FIXED;
+        sub->order     = opt_order;
         sub->type_code = sub->type | sub->order;
-        if(sub->order != max_order) {
+        if (sub->order != max_order) {
             encode_residual_fixed(res, smp, n, sub->order);
-            return calc_rice_params_fixed(&sub->rc, min_porder, max_porder, res, n,
-                                          sub->order, sub->obits);
+            find_subframe_rice_params(s, sub, sub->order);
         }
-        return bits[sub->order];
+        return subframe_count_exact(s, sub, sub->order);
     }
 
     /* LPC */
-    opt_order = ff_lpc_calc_coefs(&ctx->dsp, smp, n, min_order, max_order,
-                                  precision, coefs, shift, ctx->options.use_lpc,
-                                  omethod, MAX_LPC_SHIFT, 0);
-
-    if(omethod == ORDER_METHOD_2LEVEL ||
-       omethod == ORDER_METHOD_4LEVEL ||
-       omethod == ORDER_METHOD_8LEVEL) {
+    sub->type = FLAC_SUBFRAME_LPC;
+    opt_order = ff_lpc_calc_coefs(&s->lpc_ctx, smp, n, min_order, max_order,
+                                  s->options.lpc_coeff_precision, coefs, shift, s->options.lpc_type,
+                                  s->options.lpc_passes, omethod,
+                                  MAX_LPC_SHIFT, 0);
+
+    if (omethod == ORDER_METHOD_2LEVEL ||
+        omethod == ORDER_METHOD_4LEVEL ||
+        omethod == ORDER_METHOD_8LEVEL) {
         int levels = 1 << omethod;
-        uint32_t bits[levels];
+        uint32_t bits[1 << ORDER_METHOD_8LEVEL];
         int order;
-        int opt_index = levels-1;
-        opt_order = max_order-1;
+        int opt_index   = levels-1;
+        opt_order       = max_order-1;
         bits[opt_index] = UINT32_MAX;
-        for(i=levels-1; i>=0; i--) {
+        for (i = levels-1; i >= 0; i--) {
             order = min_order + (((max_order-min_order+1) * (i+1)) / levels)-1;
-            if(order < 0) order = 0;
+            if (order < 0)
+                order = 0;
             encode_residual_lpc(res, smp, n, order+1, coefs[order], shift[order]);
-            bits[i] = calc_rice_params_lpc(&sub->rc, min_porder, max_porder,
-                                           res, n, order+1, sub->obits, precision);
-            if(bits[i] < bits[opt_index]) {
+            bits[i] = find_subframe_rice_params(s, sub, order+1);
+            if (bits[i] < bits[opt_index]) {
                 opt_index = i;
                 opt_order = order;
             }
         }
         opt_order++;
-    } else if(omethod == ORDER_METHOD_SEARCH) {
+    } else if (omethod == ORDER_METHOD_SEARCH) {
         // brute-force optimal order search
         uint32_t bits[MAX_LPC_ORDER];
         opt_order = 0;
-        bits[0] = UINT32_MAX;
-        for(i=min_order-1; i<max_order; i++) {
+        bits[0]   = UINT32_MAX;
+        for (i = min_order-1; i < max_order; i++) {
             encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
-            bits[i] = calc_rice_params_lpc(&sub->rc, min_porder, max_porder,
-                                           res, n, i+1, sub->obits, precision);
-            if(bits[i] < bits[opt_order]) {
+            bits[i] = find_subframe_rice_params(s, sub, i+1);
+            if (bits[i] < bits[opt_order])
                 opt_order = i;
-            }
         }
         opt_order++;
-    } else if(omethod == ORDER_METHOD_LOG) {
+    } else if (omethod == ORDER_METHOD_LOG) {
         uint32_t bits[MAX_LPC_ORDER];
         int step;
 
-        opt_order= min_order - 1 + (max_order-min_order)/3;
+        opt_order = min_order - 1 + (max_order-min_order)/3;
         memset(bits, -1, sizeof(bits));
 
-        for(step=16 ;step; step>>=1){
-            int last= opt_order;
-            for(i=last-step; i<=last+step; i+= step){
-                if(i<min_order-1 || i>=max_order || bits[i] < UINT32_MAX)
+        for (step = 16; step; step >>= 1) {
+            int last = opt_order;
+            for (i = last-step; i <= last+step; i += step) {
+                if (i < min_order-1 || i >= max_order || bits[i] < UINT32_MAX)
                     continue;
                 encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
-                bits[i] = calc_rice_params_lpc(&sub->rc, min_porder, max_porder,
-                                            res, n, i+1, sub->obits, precision);
-                if(bits[i] < bits[opt_order])
-                    opt_order= i;
+                bits[i] = find_subframe_rice_params(s, sub, i+1);
+                if (bits[i] < bits[opt_order])
+                    opt_order = i;
             }
         }
         opt_order++;
     }
 
-    sub->order = opt_order;
-    sub->type = FLAC_SUBFRAME_LPC;
+    sub->order     = opt_order;
     sub->type_code = sub->type | (sub->order-1);
-    sub->shift = shift[sub->order-1];
-    for(i=0; i<sub->order; i++) {
+    sub->shift     = shift[sub->order-1];
+    for (i = 0; i < sub->order; i++)
         sub->coefs[i] = coefs[sub->order-1][i];
-    }
+
     encode_residual_lpc(res, smp, n, sub->order, sub->coefs, sub->shift);
-    return calc_rice_params_lpc(&sub->rc, min_porder, max_porder, res, n, sub->order,
-                                sub->obits, precision);
+
+    find_subframe_rice_params(s, sub, sub->order);
+
+    return subframe_count_exact(s, sub, sub->order);
 }
 
-static int encode_residual_v(FlacEncodeContext *ctx, int ch)
+
+static int count_frame_header(FlacEncodeContext *s)
 {
-    int i, n;
-    FlacFrame *frame;
-    FlacSubframe *sub;
-    int32_t *res, *smp;
+    uint8_t tmp;
+    int count;
+
+    /*
+    <14> Sync code
+    <1>  Reserved
+    <1>  Blocking strategy
+    <4>  Block size in inter-channel samples
+    <4>  Sample rate
+    <4>  Channel assignment
+    <3>  Sample size in bits
+    <1>  Reserved
+    */
+    count = 32;
+
+    /* coded frame number */
+    PUT_UTF8(s->frame_count, tmp, count += 8;)
+
+    /* explicit block size */
+    if (s->frame.bs_code[0] == 6)
+        count += 8;
+    else if (s->frame.bs_code[0] == 7)
+        count += 16;
+
+    /* explicit sample rate */
+    count += ((s->sr_code[0] == 12) + (s->sr_code[0] > 12)) * 8;
+
+    /* frame header CRC-8 */
+    count += 8;
+
+    return count;
+}
 
-    frame = &ctx->frame;
-    sub = &frame->subframes[ch];
-    res = sub->residual;
-    smp = sub->samples;
-    n = frame->blocksize;
 
-    /* CONSTANT */
-    for(i=1; i<n; i++) {
-        if(smp[i] != smp[0]) break;
-    }
-    if(i == n) {
-        sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
-        res[0] = smp[0];
-        return sub->obits;
-    }
+static int encode_frame(FlacEncodeContext *s)
+{
+    int ch, count;
 
-    /* VERBATIM */
-    sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
-    encode_residual_verbatim(res, smp, n);
-    return sub->obits * n;
+    count = count_frame_header(s);
+
+    for (ch = 0; ch < s->channels; ch++)
+        count += encode_residual_ch(s, ch);
+
+    count += (8 - (count & 7)) & 7; // byte alignment
+    count += 16;                    // CRC-16
+
+    return count >> 3;
 }
 
+
 static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n)
 {
     int i, best;
@@ -891,8 +1037,8 @@ static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n)
 
     /* calculate sum of 2nd order residual for each channel */
     sum[0] = sum[1] = sum[2] = sum[3] = 0;
-    for(i=2; i<n; i++) {
-        lt = left_ch[i] - 2*left_ch[i-1] + left_ch[i-2];
+    for (i = 2; i < n; i++) {
+        lt = left_ch[i]  - 2*left_ch[i-1]  + left_ch[i-2];
         rt = right_ch[i] - 2*right_ch[i-1] + right_ch[i-2];
         sum[2] += FFABS((lt + rt) >> 1);
         sum[3] += FFABS(lt - rt);
@@ -900,9 +1046,9 @@ static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n)
         sum[1] += FFABS(rt);
     }
     /* estimate bit counts */
-    for(i=0; i<4; i++) {
-        k = find_optimal_param(2*sum[i], n);
-        sum[i] = rice_encode_count(2*sum[i], n, k);
+    for (i = 0; i < 4; i++) {
+        k      = find_optimal_param(2 * sum[i], n);
+        sum[i] = rice_encode_count( 2 * sum[i], n, k);
     }
 
     /* calculate score for each mode */
@@ -913,37 +1059,36 @@ static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n)
 
     /* return mode with lowest score */
     best = 0;
-    for(i=1; i<4; i++) {
-        if(score[i] < score[best]) {
+    for (i = 1; i < 4; i++)
+        if (score[i] < score[best])
             best = i;
-        }
-    }
-    if(best == 0) {
+    if (best == 0) {
         return FLAC_CHMODE_INDEPENDENT;
-    } else if(best == 1) {
+    } else if (best == 1) {
         return FLAC_CHMODE_LEFT_SIDE;
-    } else if(best == 2) {
+    } else if (best == 2) {
         return FLAC_CHMODE_RIGHT_SIDE;
     } else {
         return FLAC_CHMODE_MID_SIDE;
     }
 }
 
+
 /**
- * Perform stereo channel decorrelation
+ * Perform stereo channel decorrelation.
  */
-static void channel_decorrelation(FlacEncodeContext *ctx)
+static void channel_decorrelation(FlacEncodeContext *s)
 {
     FlacFrame *frame;
     int32_t *left, *right;
     int i, n;
 
-    frame = &ctx->frame;
-    n = frame->blocksize;
+    frame = &s->frame;
+    n     = frame->blocksize;
     left  = frame->subframes[0].samples;
     right = frame->subframes[1].samples;
 
-    if(ctx->channels != 2) {
+    if (s->channels != 2) {
         frame->ch_mode = FLAC_CHMODE_INDEPENDENT;
         return;
     }
@@ -951,37 +1096,36 @@ static void channel_decorrelation(FlacEncodeContext *ctx)
     frame->ch_mode = estimate_stereo_mode(left, right, n);
 
     /* perform decorrelation and adjust bits-per-sample */
-    if(frame->ch_mode == FLAC_CHMODE_INDEPENDENT) {
+    if (frame->ch_mode == FLAC_CHMODE_INDEPENDENT)
         return;
-    }
-    if(frame->ch_mode == FLAC_CHMODE_MID_SIDE) {
+    if (frame->ch_mode == FLAC_CHMODE_MID_SIDE) {
         int32_t tmp;
-        for(i=0; i<n; i++) {
-            tmp = left[i];
-            left[i] = (tmp + right[i]) >> 1;
-            right[i] = tmp - right[i];
+        for (i = 0; i < n; i++) {
+            tmp      = left[i];
+            left[i]  = (tmp + right[i]) >> 1;
+            right[i] =  tmp - right[i];
         }
         frame->subframes[1].obits++;
-    } else if(frame->ch_mode == FLAC_CHMODE_LEFT_SIDE) {
-        for(i=0; i<n; i++) {
+    } else if (frame->ch_mode == FLAC_CHMODE_LEFT_SIDE) {
+        for (i = 0; i < n; i++)
             right[i] = left[i] - right[i];
-        }
         frame->subframes[1].obits++;
     } else {
-        for(i=0; i<n; i++) {
+        for (i = 0; i < n; i++)
             left[i] -= right[i];
-        }
         frame->subframes[0].obits++;
     }
 }
 
+
 static void write_utf8(PutBitContext *pb, uint32_t val)
 {
     uint8_t tmp;
     PUT_UTF8(val, tmp, put_bits(pb, 8, tmp);)
 }
 
-static void output_frame_header(FlacEncodeContext *s)
+
+static void write_frame_header(FlacEncodeContext *s)
 {
     FlacFrame *frame;
     int crc;
@@ -991,145 +1135,43 @@ static void output_frame_header(FlacEncodeContext *s)
     put_bits(&s->pb, 16, 0xFFF8);
     put_bits(&s->pb, 4, frame->bs_code[0]);
     put_bits(&s->pb, 4, s->sr_code[0]);
-    if(frame->ch_mode == FLAC_CHMODE_INDEPENDENT) {
+
+    if (frame->ch_mode == FLAC_CHMODE_INDEPENDENT)
         put_bits(&s->pb, 4, s->channels-1);
-    } else {
+    else
         put_bits(&s->pb, 4, frame->ch_mode);
-    }
+
     put_bits(&s->pb, 3, 4); /* bits-per-sample code */
     put_bits(&s->pb, 1, 0);
     write_utf8(&s->pb, s->frame_count);
-    if(frame->bs_code[0] == 6) {
+
+    if (frame->bs_code[0] == 6)
         put_bits(&s->pb, 8, frame->bs_code[1]);
-    } else if(frame->bs_code[0] == 7) {
+    else if (frame->bs_code[0] == 7)
         put_bits(&s->pb, 16, frame->bs_code[1]);
-    }
-    if(s->sr_code[0] == 12) {
+
+    if (s->sr_code[0] == 12)
         put_bits(&s->pb, 8, s->sr_code[1]);
-    } else if(s->sr_code[0] > 12) {
+    else if (s->sr_code[0] > 12)
         put_bits(&s->pb, 16, s->sr_code[1]);
-    }
+
     flush_put_bits(&s->pb);
-    crc = av_crc(av_crc_get_table(AV_CRC_8_ATM), 0,
-                 s->pb.buf, put_bits_count(&s->pb)>>3);
+    crc = av_crc(av_crc_get_table(AV_CRC_8_ATM), 0, s->pb.buf,
+                 put_bits_count(&s->pb) >> 3);
     put_bits(&s->pb, 8, crc);
 }
 
-static void output_subframe_constant(FlacEncodeContext *s, int ch)
-{
-    FlacSubframe *sub;
-    int32_t res;
-
-    sub = &s->frame.subframes[ch];
-    res = sub->residual[0];
-    put_sbits(&s->pb, sub->obits, res);
-}
-
-static void output_subframe_verbatim(FlacEncodeContext *s, int ch)
-{
-    int i;
-    FlacFrame *frame;
-    FlacSubframe *sub;
-    int32_t res;
-
-    frame = &s->frame;
-    sub = &frame->subframes[ch];
-
-    for(i=0; i<frame->blocksize; i++) {
-        res = sub->residual[i];
-        put_sbits(&s->pb, sub->obits, res);
-    }
-}
-
-static void output_residual(FlacEncodeContext *ctx, int ch)
-{
-    int i, j, p, n, parts;
-    int k, porder, psize, res_cnt;
-    FlacFrame *frame;
-    FlacSubframe *sub;
-    int32_t *res;
-
-    frame = &ctx->frame;
-    sub = &frame->subframes[ch];
-    res = sub->residual;
-    n = frame->blocksize;
-
-    /* rice-encoded block */
-    put_bits(&ctx->pb, 2, 0);
-
-    /* partition order */
-    porder = sub->rc.porder;
-    psize = n >> porder;
-    parts = (1 << porder);
-    put_bits(&ctx->pb, 4, porder);
-    res_cnt = psize - sub->order;
-
-    /* residual */
-    j = sub->order;
-    for(p=0; p<parts; p++) {
-        k = sub->rc.params[p];
-        put_bits(&ctx->pb, 4, k);
-        if(p == 1) res_cnt = psize;
-        for(i=0; i<res_cnt && j<n; i++, j++) {
-            set_sr_golomb_flac(&ctx->pb, res[j], k, INT32_MAX, 0);
-        }
-    }
-}
-
-static void output_subframe_fixed(FlacEncodeContext *ctx, int ch)
-{
-    int i;
-    FlacFrame *frame;
-    FlacSubframe *sub;
-
-    frame = &ctx->frame;
-    sub = &frame->subframes[ch];
-
-    /* warm-up samples */
-    for(i=0; i<sub->order; i++) {
-        put_sbits(&ctx->pb, sub->obits, sub->residual[i]);
-    }
 
-    /* residual */
-    output_residual(ctx, ch);
-}
-
-static void output_subframe_lpc(FlacEncodeContext *ctx, int ch)
+static void write_subframes(FlacEncodeContext *s)
 {
-    int i, cbits;
-    FlacFrame *frame;
-    FlacSubframe *sub;
-
-    frame = &ctx->frame;
-    sub = &frame->subframes[ch];
-
-    /* warm-up samples */
-    for(i=0; i<sub->order; i++) {
-        put_sbits(&ctx->pb, sub->obits, sub->residual[i]);
-    }
-
-    /* LPC coefficients */
-    cbits = ctx->options.lpc_coeff_precision;
-    put_bits(&ctx->pb, 4, cbits-1);
-    put_sbits(&ctx->pb, 5, sub->shift);
-    for(i=0; i<sub->order; i++) {
-        put_sbits(&ctx->pb, cbits, sub->coefs[i]);
-    }
-
-    /* residual */
-    output_residual(ctx, ch);
-}
-
-static void output_subframes(FlacEncodeContext *s)
-{
-    FlacFrame *frame;
-    FlacSubframe *sub;
     int ch;
 
-    frame = &s->frame;
-
-    for(ch=0; ch<s->channels; ch++) {
-        sub = &frame->subframes[ch];
+    for (ch = 0; ch < s->channels; ch++) {
+        FlacSubframe *sub = &s->frame.subframes[ch];
+        int i, p, porder, psize;
+        int32_t *part_end;
+        int32_t *res       =  sub->residual;
+        int32_t *frame_end = &sub->residual[s->frame.blocksize];
 
         /* subframe header */
         put_bits(&s->pb, 1, 0);
@@ -1137,57 +1179,91 @@ static void output_subframes(FlacEncodeContext *s)
         put_bits(&s->pb, 1, 0); /* no wasted bits */
 
         /* subframe */
-        if(sub->type == FLAC_SUBFRAME_CONSTANT) {
-            output_subframe_constant(s, ch);
-        } else if(sub->type == FLAC_SUBFRAME_VERBATIM) {
-            output_subframe_verbatim(s, ch);
-        } else if(sub->type == FLAC_SUBFRAME_FIXED) {
-            output_subframe_fixed(s, ch);
-        } else if(sub->type == FLAC_SUBFRAME_LPC) {
-            output_subframe_lpc(s, ch);
+        if (sub->type == FLAC_SUBFRAME_CONSTANT) {
+            put_sbits(&s->pb, sub->obits, res[0]);
+        } else if (sub->type == FLAC_SUBFRAME_VERBATIM) {
+            while (res < frame_end)
+                put_sbits(&s->pb, sub->obits, *res++);
+        } else {
+            /* warm-up samples */
+            for (i = 0; i < sub->order; i++)
+                put_sbits(&s->pb, sub->obits, *res++);
+
+            /* LPC coefficients */
+            if (sub->type == FLAC_SUBFRAME_LPC) {
+                int cbits = s->options.lpc_coeff_precision;
+                put_bits( &s->pb, 4, cbits-1);
+                put_sbits(&s->pb, 5, sub->shift);
+                for (i = 0; i < sub->order; i++)
+                    put_sbits(&s->pb, cbits, sub->coefs[i]);
+            }
+
+            /* rice-encoded block */
+            put_bits(&s->pb, 2, 0);
+
+            /* partition order */
+            porder  = sub->rc.porder;
+            psize   = s->frame.blocksize >> porder;
+            put_bits(&s->pb, 4, porder);
+
+            /* residual */
+            part_end  = &sub->residual[psize];
+            for (p = 0; p < 1 << porder; p++) {
+                int k = sub->rc.params[p];
+                put_bits(&s->pb, 4, k);
+                while (res < part_end)
+                    set_sr_golomb_flac(&s->pb, *res++, k, INT32_MAX, 0);
+                part_end = FFMIN(frame_end, part_end + psize);
+            }
         }
     }
 }
 
-static void output_frame_footer(FlacEncodeContext *s)
+
+static void write_frame_footer(FlacEncodeContext *s)
 {
     int crc;
     flush_put_bits(&s->pb);
-    crc = bswap_16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
-                          s->pb.buf, put_bits_count(&s->pb)>>3));
+    crc = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0, s->pb.buf,
+                            put_bits_count(&s->pb)>>3));
     put_bits(&s->pb, 16, crc);
     flush_put_bits(&s->pb);
 }
 
-static void update_md5_sum(FlacEncodeContext *s, int16_t *samples)
+
+static int write_frame(FlacEncodeContext *s, uint8_t *frame, int buf_size)
+{
+    init_put_bits(&s->pb, frame, buf_size);
+    write_frame_header(s);
+    write_subframes(s);
+    write_frame_footer(s);
+    return put_bits_count(&s->pb) >> 3;
+}
+
+
+static void update_md5_sum(FlacEncodeContext *s, const int16_t *samples)
 {
 #if HAVE_BIGENDIAN
     int i;
-    for(i = 0; i < s->frame.blocksize*s->channels; i++) {
-        int16_t smp = le2me_16(samples[i]);
+    for (i = 0; i < s->frame.blocksize * s->channels; i++) {
+        int16_t smp = av_le2ne16(samples[i]);
         av_md5_update(s->md5ctx, (uint8_t *)&smp, 2);
     }
 #else
-    av_md5_update(s->md5ctx, (uint8_t *)samples, s->frame.blocksize*s->channels*2);
+    av_md5_update(s->md5ctx, (const uint8_t *)samples, s->frame.blocksize*s->channels*2);
 #endif
 }
 
+
 static int flac_encode_frame(AVCodecContext *avctx, uint8_t *frame,
                              int buf_size, void *data)
 {
-    int ch;
     FlacEncodeContext *s;
-    int16_t *samples = data;
-    int out_bytes;
-    int reencoded=0;
+    const int16_t *samples = data;
+    int frame_bytes, out_bytes;
 
     s = avctx->priv_data;
 
-    if(buf_size < s->max_framesize*2) {
-        av_log(avctx, AV_LOG_ERROR, "output buffer too small\n");
-        return 0;
-    }
-
     /* when the last block is reached, update the header in extradata */
     if (!data) {
         s->max_framesize = s->max_encoded_framesize;
@@ -1196,39 +1272,35 @@ static int flac_encode_frame(AVCodecContext *avctx, uint8_t *frame,
         return 0;
     }
 
+    /* change max_framesize for small final frame */
+    if (avctx->frame_size < s->frame.blocksize) {
+        s->max_framesize = ff_flac_get_max_frame_size(avctx->frame_size,
+                                                      s->channels, 16);
+    }
+
     init_frame(s);
 
     copy_samples(s, samples);
 
     channel_decorrelation(s);
 
-    for(ch=0; ch<s->channels; ch++) {
-        encode_residual(s, ch);
-    }
+    frame_bytes = encode_frame(s);
 
-write_frame:
-    init_put_bits(&s->pb, frame, buf_size);
-    output_frame_header(s);
-    output_subframes(s);
-    output_frame_footer(s);
-    out_bytes = put_bits_count(&s->pb) >> 3;
-
-    if(out_bytes > s->max_framesize) {
-        if(reencoded) {
-            /* still too large. must be an error. */
-            av_log(avctx, AV_LOG_ERROR, "error encoding frame\n");
-            return -1;
-        }
+    /* fallback to verbatim mode if the compressed frame is larger than it
+       would be if encoded uncompressed. */
+    if (frame_bytes > s->max_framesize) {
+        s->frame.verbatim_only = 1;
+        frame_bytes = encode_frame(s);
+    }
 
-        /* frame too large. use verbatim mode */
-        for(ch=0; ch<s->channels; ch++) {
-            encode_residual_v(s, ch);
-        }
-        reencoded = 1;
-        goto write_frame;
+    if (buf_size < frame_bytes) {
+        av_log(avctx, AV_LOG_ERROR, "output buffer too small\n");
+        return 0;
     }
+    out_bytes = write_frame(s, frame, buf_size);
 
     s->frame_count++;
+    avctx->coded_frame->pts = s->sample_count;
     s->sample_count += avctx->frame_size;
     update_md5_sum(s, samples);
     if (out_bytes > s->max_encoded_framesize)
@@ -1239,11 +1311,13 @@ write_frame:
     return out_bytes;
 }
 
+
 static av_cold int flac_encode_close(AVCodecContext *avctx)
 {
     if (avctx->priv_data) {
         FlacEncodeContext *s = avctx->priv_data;
         av_freep(&s->md5ctx);
+        ff_lpc_end(&s->lpc_ctx);
     }
     av_freep(&avctx->extradata);
     avctx->extradata_size = 0;
@@ -1251,7 +1325,8 @@ static av_cold int flac_encode_close(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec flac_encoder = {
+
+AVCodec ff_flac_encoder = {
     "flac",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_FLAC,
@@ -1261,6 +1336,6 @@ AVCodec flac_encoder = {
     flac_encode_close,
     NULL,
     .capabilities = CODEC_CAP_SMALL_LAST_FRAME | CODEC_CAP_DELAY,
-    .sample_fmts = (const enum SampleFormat[]){SAMPLE_FMT_S16,SAMPLE_FMT_NONE},
+    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
     .long_name = NULL_IF_CONFIG_SMALL("FLAC (Free Lossless Audio Codec)"),
 };
diff --git a/libavcodec/flashsv.c b/libavcodec/flashsv.c
index 394ac0f..287cb10 100644
--- a/libavcodec/flashsv.c
+++ b/libavcodec/flashsv.c
@@ -3,20 +3,20 @@
  * Copyright (C) 2004 Alex Beregszaszi
  * Copyright (C) 2006 Benjamin Larsson
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -133,8 +133,7 @@ static int flashsv_decode_frame(AVCodecContext *avctx,
     /* the block size could change between frames, make sure the buffer
      * is large enough, if not, get a larger one */
     if(s->block_size < s->block_width*s->block_height) {
-        if (s->tmpblock != NULL)
-            av_free(s->tmpblock);
+        av_free(s->tmpblock);
         if ((s->tmpblock = av_malloc(3*s->block_width*s->block_height)) == NULL) {
             av_log(avctx, AV_LOG_ERROR, "Can't allocate decompression buffer.\n");
             return -1;
@@ -243,14 +242,13 @@ static av_cold int flashsv_decode_end(AVCodecContext *avctx)
         avctx->release_buffer(avctx, &s->frame);
 
     /* free the tmpblock */
-    if (s->tmpblock != NULL)
-        av_free(s->tmpblock);
+    av_free(s->tmpblock);
 
     return 0;
 }
 
 
-AVCodec flashsv_decoder = {
+AVCodec ff_flashsv_decoder = {
     "flashsv",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_FLASHSV,
diff --git a/libavcodec/flashsvenc.c b/libavcodec/flashsvenc.c
index ff917e9..2a12d0e 100644
--- a/libavcodec/flashsvenc.c
+++ b/libavcodec/flashsvenc.c
@@ -3,20 +3,20 @@
  * Copyright (C) 2004 Alex Beregszaszi
  * Copyright (C) 2006 Benjamin Larsson
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -280,7 +280,7 @@ static av_cold int flashsv_encode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec flashsv_encoder = {
+AVCodec ff_flashsv_encoder = {
     "flashsv",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_FLASHSV,
diff --git a/libavcodec/flicvideo.c b/libavcodec/flicvideo.c
index 429ded5..ed9972c 100644
--- a/libavcodec/flicvideo.c
+++ b/libavcodec/flicvideo.c
@@ -2,20 +2,20 @@
  * FLI/FLC Animation Video Decoder
  * Copyright (C) 2003, 2004 the ffmpeg project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -159,7 +159,7 @@ static int flic_decode_frame_8BPP(AVCodecContext *avctx,
     int pixel_skip;
     int pixel_countdown;
     unsigned char *pixels;
-    int pixel_limit;
+    unsigned int pixel_limit;
 
     s->frame.reference = 1;
     s->frame.buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE | FF_BUFFER_HINTS_REUSABLE;
@@ -253,10 +253,13 @@ static int flic_decode_frame_8BPP(AVCodecContext *avctx,
                     av_log(avctx, AV_LOG_ERROR, "Undefined opcode (%x) in DELTA_FLI\n", line_packets);
                 } else if ((line_packets & 0xC000) == 0x8000) {
                     // "last byte" opcode
-                    pixels[y_ptr + s->frame.linesize[0] - 1] = line_packets & 0xff;
+                    pixel_ptr= y_ptr + s->frame.linesize[0] - 1;
+                    CHECK_PIXEL_PTR(0);
+                    pixels[pixel_ptr] = line_packets & 0xff;
                 } else {
                     compressed_lines--;
                     pixel_ptr = y_ptr;
+                    CHECK_PIXEL_PTR(0);
                     pixel_countdown = s->avctx->width;
                     for (i = 0; i < line_packets; i++) {
                         /* account for the skip bytes */
@@ -268,7 +271,7 @@ static int flic_decode_frame_8BPP(AVCodecContext *avctx,
                             byte_run = -byte_run;
                             palette_idx1 = buf[stream_ptr++];
                             palette_idx2 = buf[stream_ptr++];
-                            CHECK_PIXEL_PTR(byte_run);
+                            CHECK_PIXEL_PTR(byte_run * 2);
                             for (j = 0; j < byte_run; j++, pixel_countdown -= 2) {
                                 pixels[pixel_ptr++] = palette_idx1;
                                 pixels[pixel_ptr++] = palette_idx2;
@@ -298,6 +301,7 @@ static int flic_decode_frame_8BPP(AVCodecContext *avctx,
             stream_ptr += 2;
             while (compressed_lines > 0) {
                 pixel_ptr = y_ptr;
+                CHECK_PIXEL_PTR(0);
                 pixel_countdown = s->avctx->width;
                 line_packets = buf[stream_ptr++];
                 if (line_packets > 0) {
@@ -453,7 +457,7 @@ static int flic_decode_frame_15_16BPP(AVCodecContext *avctx,
     int pixel_countdown;
     unsigned char *pixels;
     int pixel;
-    int pixel_limit;
+    unsigned int pixel_limit;
 
     s->frame.reference = 1;
     s->frame.buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE | FF_BUFFER_HINTS_REUSABLE;
@@ -503,6 +507,7 @@ static int flic_decode_frame_15_16BPP(AVCodecContext *avctx,
                 } else {
                     compressed_lines--;
                     pixel_ptr = y_ptr;
+                    CHECK_PIXEL_PTR(0);
                     pixel_countdown = s->avctx->width;
                     for (i = 0; i < line_packets; i++) {
                         /* account for the skip bytes */
@@ -514,13 +519,13 @@ static int flic_decode_frame_15_16BPP(AVCodecContext *avctx,
                             byte_run = -byte_run;
                             pixel    = AV_RL16(&buf[stream_ptr]);
                             stream_ptr += 2;
-                            CHECK_PIXEL_PTR(byte_run);
+                            CHECK_PIXEL_PTR(2 * byte_run);
                             for (j = 0; j < byte_run; j++, pixel_countdown -= 2) {
                                 *((signed short*)(&pixels[pixel_ptr])) = pixel;
                                 pixel_ptr += 2;
                             }
                         } else {
-                            CHECK_PIXEL_PTR(byte_run);
+                            CHECK_PIXEL_PTR(2 * byte_run);
                             for (j = 0; j < byte_run; j++, pixel_countdown--) {
                                 *((signed short*)(&pixels[pixel_ptr])) = AV_RL16(&buf[stream_ptr]);
                                 stream_ptr += 2;
@@ -611,7 +616,7 @@ static int flic_decode_frame_15_16BPP(AVCodecContext *avctx,
                     if (byte_run > 0) {
                         pixel    = AV_RL16(&buf[stream_ptr]);
                         stream_ptr += 2;
-                        CHECK_PIXEL_PTR(byte_run);
+                        CHECK_PIXEL_PTR(2 * byte_run);
                         for (j = 0; j < byte_run; j++) {
                             *((signed short*)(&pixels[pixel_ptr])) = pixel;
                             pixel_ptr += 2;
@@ -622,7 +627,7 @@ static int flic_decode_frame_15_16BPP(AVCodecContext *avctx,
                         }
                     } else {  /* copy pixels if byte_run < 0 */
                         byte_run = -byte_run;
-                        CHECK_PIXEL_PTR(byte_run);
+                        CHECK_PIXEL_PTR(2 * byte_run);
                         for (j = 0; j < byte_run; j++) {
                             *((signed short*)(&pixels[pixel_ptr])) = AV_RL16(&buf[stream_ptr]);
                             stream_ptr += 2;
@@ -737,7 +742,7 @@ static av_cold int flic_decode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec flic_decoder = {
+AVCodec ff_flic_decoder = {
     "flic",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_FLIC,
diff --git a/libavcodec/flv.h b/libavcodec/flv.h
index eb10f22..8411117 100644
--- a/libavcodec/flv.h
+++ b/libavcodec/flv.h
@@ -1,19 +1,19 @@
 /*
  * FLV specific private header.
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/flvdec.c b/libavcodec/flvdec.c
index cf9661c..485ee96 100644
--- a/libavcodec/flvdec.c
+++ b/libavcodec/flvdec.c
@@ -1,25 +1,26 @@
 /*
  * FLV decoding.
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "mpegvideo.h"
 #include "h263.h"
 #include "flv.h"
+#include "libavutil/imgutils.h"
 
 void ff_flv2_decode_ac_esc(GetBitContext *gb, int *level, int *run, int *last){
     int is11 = get_bits1(gb);
@@ -82,7 +83,7 @@ int ff_flv_decode_picture_header(MpegEncContext *s)
         width = height = 0;
         break;
     }
-    if(avcodec_check_dimensions(s->avctx, width, height))
+    if(av_image_check_size(width, height, 0, s->avctx))
         return -1;
     s->width = width;
     s->height = height;
@@ -117,7 +118,7 @@ int ff_flv_decode_picture_header(MpegEncContext *s)
     return 0;
 }
 
-AVCodec flv_decoder = {
+AVCodec ff_flv_decoder = {
     "flv",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_FLV1,
@@ -127,6 +128,7 @@ AVCodec flv_decoder = {
     ff_h263_decode_end,
     ff_h263_decode_frame,
     CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1,
+    .max_lowres= 3,
     .long_name= NULL_IF_CONFIG_SMALL("Flash Video (FLV) / Sorenson Spark / Sorenson H.263"),
     .pix_fmts= ff_pixfmt_list_420,
 };
diff --git a/libavcodec/flvenc.c b/libavcodec/flvenc.c
index bf320f2..af3e813 100644
--- a/libavcodec/flvenc.c
+++ b/libavcodec/flvenc.c
@@ -1,19 +1,19 @@
 /*
  * FLV Encoding specific code.
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -84,7 +84,7 @@ void ff_flv2_encode_ac_esc(PutBitContext *pb, int slevel, int level, int run, in
     }
 }
 
-AVCodec flv_encoder = {
+AVCodec ff_flv_encoder = {
     "flv",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_FLV1,
diff --git a/libavcodec/fmtconvert.c b/libavcodec/fmtconvert.c
new file mode 100644
index 0000000..e970755
--- /dev/null
+++ b/libavcodec/fmtconvert.c
@@ -0,0 +1,68 @@
+/*
+ * Format Conversion Utils
+ * Copyright (c) 2000, 2001 Fabrice Bellard
+ * Copyright (c) 2002-2004 Michael Niedermayer <michaelni at gmx.at>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "avcodec.h"
+#include "fmtconvert.h"
+
+static void int32_to_float_fmul_scalar_c(float *dst, const int *src, float mul, int len){
+    int i;
+    for(i=0; i<len; i++)
+        dst[i] = src[i] * mul;
+}
+
+static av_always_inline int float_to_int16_one(const float *src){
+    return av_clip_int16(lrintf(*src));
+}
+
+static void float_to_int16_c(int16_t *dst, const float *src, long len)
+{
+    int i;
+    for(i=0; i<len; i++)
+        dst[i] = float_to_int16_one(src+i);
+}
+
+static void float_to_int16_interleave_c(int16_t *dst, const float **src,
+                                        long len, int channels)
+{
+    int i,j,c;
+    if(channels==2){
+        for(i=0; i<len; i++){
+            dst[2*i]   = float_to_int16_one(src[0]+i);
+            dst[2*i+1] = float_to_int16_one(src[1]+i);
+        }
+    }else{
+        for(c=0; c<channels; c++)
+            for(i=0, j=c; i<len; i++, j+=channels)
+                dst[j] = float_to_int16_one(src[c]+i);
+    }
+}
+
+av_cold void ff_fmt_convert_init(FmtConvertContext *c, AVCodecContext *avctx)
+{
+    c->int32_to_float_fmul_scalar = int32_to_float_fmul_scalar_c;
+    c->float_to_int16             = float_to_int16_c;
+    c->float_to_int16_interleave  = float_to_int16_interleave_c;
+
+    if (ARCH_ARM) ff_fmt_convert_init_arm(c, avctx);
+    if (HAVE_ALTIVEC) ff_fmt_convert_init_altivec(c, avctx);
+    if (HAVE_MMX) ff_fmt_convert_init_x86(c, avctx);
+}
diff --git a/libavcodec/fmtconvert.h b/libavcodec/fmtconvert.h
new file mode 100644
index 0000000..e0afee4
--- /dev/null
+++ b/libavcodec/fmtconvert.h
@@ -0,0 +1,79 @@
+/*
+ * Format Conversion Utils
+ * Copyright (c) 2000, 2001 Fabrice Bellard
+ * Copyright (c) 2002-2004 Michael Niedermayer <michaelni at gmx.at>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_FMTCONVERT_H
+#define AVCODEC_FMTCONVERT_H
+
+#include "avcodec.h"
+
+typedef struct FmtConvertContext {
+    /**
+     * Convert an array of int32_t to float and multiply by a float value.
+     * @param dst destination array of float.
+     *            constraints: 16-byte aligned
+     * @param src source array of int32_t.
+     *            constraints: 16-byte aligned
+     * @param len number of elements to convert.
+     *            constraints: multiple of 8
+     */
+    void (*int32_to_float_fmul_scalar)(float *dst, const int *src, float mul, int len);
+
+    /**
+     * Convert an array of float to an array of int16_t.
+     *
+     * Convert floats from in the range [-32768.0,32767.0] to ints
+     * without rescaling
+     *
+     * @param dst destination array of int16_t.
+     *            constraints: 16-byte aligned
+     * @param src source array of float.
+     *            constraints: 16-byte aligned
+     * @param len number of elements to convert.
+     *            constraints: multiple of 8
+     */
+    void (*float_to_int16)(int16_t *dst, const float *src, long len);
+
+    /**
+     * Convert multiple arrays of float to an interleaved array of int16_t.
+     *
+     * Convert floats from in the range [-32768.0,32767.0] to ints
+     * without rescaling
+     *
+     * @param dst destination array of interleaved int16_t.
+     *            constraints: 16-byte aligned
+     * @param src source array of float arrays, one for each channel.
+     *            constraints: 16-byte aligned
+     * @param len number of elements to convert.
+     *            constraints: multiple of 8
+     * @param channels number of channels
+     */
+    void (*float_to_int16_interleave)(int16_t *dst, const float **src,
+                                      long len, int channels);
+} FmtConvertContext;
+
+void ff_fmt_convert_init(FmtConvertContext *c, AVCodecContext *avctx);
+
+void ff_fmt_convert_init_arm(FmtConvertContext *c, AVCodecContext *avctx);
+void ff_fmt_convert_init_altivec(FmtConvertContext *c, AVCodecContext *avctx);
+void ff_fmt_convert_init_x86(FmtConvertContext *c, AVCodecContext *avctx);
+
+#endif /* AVCODEC_FMTCONVERT_H */
diff --git a/libavcodec/fraps.c b/libavcodec/fraps.c
index 959ce92..a142484 100644
--- a/libavcodec/fraps.c
+++ b/libavcodec/fraps.c
@@ -3,27 +3,27 @@
  * Copyright (c) 2005 Roine Gustafsson
  * Copyright (c) 2006 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 /**
  * @file
  * Lossless Fraps 'FPS1' decoder
- * @author Roine Gustafsson <roine at users sf net>
+ * @author Roine Gustafsson (roine at users sf net)
  * @author Konstantin Shishkov
  *
  * Codec algorithm for version 0 is taken from Transcode <www.transcoding.org>
@@ -118,15 +118,6 @@ static int fraps2_decode_plane(FrapsContext *s, uint8_t *dst, int stride, int w,
     return 0;
 }
 
-/**
- * decode a frame
- * @param avctx codec context
- * @param data output AVFrame
- * @param data_size size of output data or 0 if no picture is returned
- * @param buf input data frame
- * @param buf_size size of input data frame
- * @return number of consumed bytes on success or negative if decode fails
- */
 static int decode_frame(AVCodecContext *avctx,
                         void *data, int *data_size,
                         AVPacket *avpkt)
@@ -164,7 +155,7 @@ static int decode_frame(AVCodecContext *avctx,
     case 0:
     default:
         /* Fraps v0 is a reordered YUV420 */
-        avctx->pix_fmt = PIX_FMT_YUV420P;
+        avctx->pix_fmt = PIX_FMT_YUVJ420P;
 
         if ( (buf_size != avctx->width*avctx->height*3/2+header_size) &&
              (buf_size != header_size) ) {
@@ -189,7 +180,7 @@ static int decode_frame(AVCodecContext *avctx,
             return -1;
         }
         /* bit 31 means same as previous pic */
-        f->pict_type = (header & (1<<31))? FF_P_TYPE : FF_I_TYPE;
+        f->pict_type = (header & (1U<<31))? FF_P_TYPE : FF_I_TYPE;
         f->key_frame = f->pict_type == FF_I_TYPE;
 
         if (f->pict_type == FF_I_TYPE) {
@@ -232,7 +223,7 @@ static int decode_frame(AVCodecContext *avctx,
             return -1;
         }
         /* bit 31 means same as previous pic */
-        f->pict_type = (header & (1<<31))? FF_P_TYPE : FF_I_TYPE;
+        f->pict_type = (header & (1U<<31))? FF_P_TYPE : FF_I_TYPE;
         f->key_frame = f->pict_type == FF_I_TYPE;
 
         if (f->pict_type == FF_I_TYPE) {
@@ -249,7 +240,7 @@ static int decode_frame(AVCodecContext *avctx,
          * Fraps v2 is Huffman-coded YUV420 planes
          * Fraps v4 is virtually the same
          */
-        avctx->pix_fmt = PIX_FMT_YUV420P;
+        avctx->pix_fmt = PIX_FMT_YUVJ420P;
         planes = 3;
         f->reference = 1;
         f->buffer_hints = FF_BUFFER_HINTS_VALID |
@@ -364,7 +355,7 @@ static av_cold int decode_end(AVCodecContext *avctx)
 }
 
 
-AVCodec fraps_decoder = {
+AVCodec ff_fraps_decoder = {
     "fraps",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_FRAPS,
diff --git a/libavcodec/frwu.c b/libavcodec/frwu.c
index b685248..bff7d0a 100644
--- a/libavcodec/frwu.c
+++ b/libavcodec/frwu.c
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2009 Reimar Döffinger <Reimar.Doeffinger at gmx.de>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -109,7 +109,7 @@ static av_cold int decode_close(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec frwu_decoder = {
+AVCodec ff_frwu_decoder = {
     "FRWU",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_FRWU,
diff --git a/libavcodec/g722.c b/libavcodec/g722.c
new file mode 100644
index 0000000..257292d
--- /dev/null
+++ b/libavcodec/g722.c
@@ -0,0 +1,583 @@
+/*
+ * G.722 ADPCM audio encoder/decoder
+ *
+ * Copyright (c) CMU 1993 Computer Science, Speech Group
+ *                        Chengxiang Lu and Alex Hauptmann
+ * Copyright (c) 2005 Steve Underwood <steveu at coppice.org>
+ * Copyright (c) 2009 Kenan Gillet
+ * Copyright (c) 2010 Martin Storsjo
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ *
+ * G.722 ADPCM audio codec
+ *
+ * This G.722 decoder is a bit-exact implementation of the ITU G.722
+ * specification for all three specified bitrates - 64000bps, 56000bps
+ * and 48000bps. It passes the ITU tests.
+ *
+ * @note For the 56000bps and 48000bps bitrates, the lowest 1 or 2 bits
+ *       respectively of each byte are ignored.
+ */
+
+#include "avcodec.h"
+#include "mathops.h"
+#include "get_bits.h"
+
+#define PREV_SAMPLES_BUF_SIZE 1024
+
+#define FREEZE_INTERVAL 128
+
+typedef struct {
+    int16_t prev_samples[PREV_SAMPLES_BUF_SIZE]; ///< memory of past decoded samples
+    int     prev_samples_pos;        ///< the number of values in prev_samples
+
+    /**
+     * The band[0] and band[1] correspond respectively to the lower band and higher band.
+     */
+    struct G722Band {
+        int16_t s_predictor;         ///< predictor output value
+        int32_t s_zero;              ///< previous output signal from zero predictor
+        int8_t  part_reconst_mem[2]; ///< signs of previous partially reconstructed signals
+        int16_t prev_qtzd_reconst;   ///< previous quantized reconstructed signal (internal value, using low_inv_quant4)
+        int16_t pole_mem[2];         ///< second-order pole section coefficient buffer
+        int32_t diff_mem[6];         ///< quantizer difference signal memory
+        int16_t zero_mem[6];         ///< Seventh-order zero section coefficient buffer
+        int16_t log_factor;          ///< delayed 2-logarithmic quantizer factor
+        int16_t scale_factor;        ///< delayed quantizer scale factor
+    } band[2];
+
+    struct TrellisNode {
+        struct G722Band state;
+        uint32_t ssd;
+        int path;
+    } *node_buf[2], **nodep_buf[2];
+
+    struct TrellisPath {
+        int value;
+        int prev;
+    } *paths[2];
+} G722Context;
+
+
+static const int8_t sign_lookup[2] = { -1, 1 };
+
+static const int16_t inv_log2_table[32] = {
+    2048, 2093, 2139, 2186, 2233, 2282, 2332, 2383,
+    2435, 2489, 2543, 2599, 2656, 2714, 2774, 2834,
+    2896, 2960, 3025, 3091, 3158, 3228, 3298, 3371,
+    3444, 3520, 3597, 3676, 3756, 3838, 3922, 4008
+};
+static const int16_t high_log_factor_step[2] = { 798, -214 };
+static const int16_t high_inv_quant[4] = { -926, -202, 926, 202 };
+/**
+ * low_log_factor_step[index] == wl[rl42[index]]
+ */
+static const int16_t low_log_factor_step[16] = {
+     -60, 3042, 1198, 538, 334, 172,  58, -30,
+    3042, 1198,  538, 334, 172,  58, -30, -60
+};
+static const int16_t low_inv_quant4[16] = {
+       0, -2557, -1612, -1121,  -786,  -530,  -323,  -150,
+    2557,  1612,  1121,   786,   530,   323,   150,     0
+};
+static const int16_t low_inv_quant6[64] = {
+     -17,   -17,   -17,   -17, -3101, -2738, -2376, -2088,
+   -1873, -1689, -1535, -1399, -1279, -1170, -1072,  -982,
+    -899,  -822,  -750,  -682,  -618,  -558,  -501,  -447,
+    -396,  -347,  -300,  -254,  -211,  -170,  -130,   -91,
+    3101,  2738,  2376,  2088,  1873,  1689,  1535,  1399,
+    1279,  1170,  1072,   982,   899,   822,   750,   682,
+     618,   558,   501,   447,   396,   347,   300,   254,
+     211,   170,   130,    91,    54,    17,   -54,   -17
+};
+
+/**
+ * quadrature mirror filter (QMF) coefficients
+ *
+ * ITU-T G.722 Table 11
+ */
+static const int16_t qmf_coeffs[12] = {
+    3, -11, 12, 32, -210, 951, 3876, -805, 362, -156, 53, -11,
+};
+
+
+/**
+ * adaptive predictor
+ *
+ * @param cur_diff the dequantized and scaled delta calculated from the
+ *                 current codeword
+ */
+static void do_adaptive_prediction(struct G722Band *band, const int cur_diff)
+{
+    int sg[2], limit, i, cur_qtzd_reconst;
+
+    const int cur_part_reconst = band->s_zero + cur_diff < 0;
+
+    sg[0] = sign_lookup[cur_part_reconst != band->part_reconst_mem[0]];
+    sg[1] = sign_lookup[cur_part_reconst == band->part_reconst_mem[1]];
+    band->part_reconst_mem[1] = band->part_reconst_mem[0];
+    band->part_reconst_mem[0] = cur_part_reconst;
+
+    band->pole_mem[1] = av_clip((sg[0] * av_clip(band->pole_mem[0], -8191, 8191) >> 5) +
+                                (sg[1] << 7) + (band->pole_mem[1] * 127 >> 7), -12288, 12288);
+
+    limit = 15360 - band->pole_mem[1];
+    band->pole_mem[0] = av_clip(-192 * sg[0] + (band->pole_mem[0] * 255 >> 8), -limit, limit);
+
+
+    if (cur_diff) {
+        for (i = 0; i < 6; i++)
+            band->zero_mem[i] = ((band->zero_mem[i]*255) >> 8) +
+                                ((band->diff_mem[i]^cur_diff) < 0 ? -128 : 128);
+    } else
+        for (i = 0; i < 6; i++)
+            band->zero_mem[i] = (band->zero_mem[i]*255) >> 8;
+
+    for (i = 5; i > 0; i--)
+        band->diff_mem[i] = band->diff_mem[i-1];
+    band->diff_mem[0] = av_clip_int16(cur_diff << 1);
+
+    band->s_zero = 0;
+    for (i = 5; i >= 0; i--)
+        band->s_zero += (band->zero_mem[i]*band->diff_mem[i]) >> 15;
+
+
+    cur_qtzd_reconst = av_clip_int16((band->s_predictor + cur_diff) << 1);
+    band->s_predictor = av_clip_int16(band->s_zero +
+                                      (band->pole_mem[0] * cur_qtzd_reconst >> 15) +
+                                      (band->pole_mem[1] * band->prev_qtzd_reconst >> 15));
+    band->prev_qtzd_reconst = cur_qtzd_reconst;
+}
+
+static int inline linear_scale_factor(const int log_factor)
+{
+    const int wd1 = inv_log2_table[(log_factor >> 6) & 31];
+    const int shift = log_factor >> 11;
+    return shift < 0 ? wd1 >> -shift : wd1 << shift;
+}
+
+static void update_low_predictor(struct G722Band *band, const int ilow)
+{
+    do_adaptive_prediction(band,
+                           band->scale_factor * low_inv_quant4[ilow] >> 10);
+
+    // quantizer adaptation
+    band->log_factor   = av_clip((band->log_factor * 127 >> 7) +
+                                 low_log_factor_step[ilow], 0, 18432);
+    band->scale_factor = linear_scale_factor(band->log_factor - (8 << 11));
+}
+
+static void update_high_predictor(struct G722Band *band, const int dhigh,
+                                  const int ihigh)
+{
+    do_adaptive_prediction(band, dhigh);
+
+    // quantizer adaptation
+    band->log_factor   = av_clip((band->log_factor * 127 >> 7) +
+                                 high_log_factor_step[ihigh&1], 0, 22528);
+    band->scale_factor = linear_scale_factor(band->log_factor - (10 << 11));
+}
+
+static void apply_qmf(const int16_t *prev_samples, int *xout1, int *xout2)
+{
+    int i;
+
+    *xout1 = 0;
+    *xout2 = 0;
+    for (i = 0; i < 12; i++) {
+        MAC16(*xout2, prev_samples[2*i  ], qmf_coeffs[i   ]);
+        MAC16(*xout1, prev_samples[2*i+1], qmf_coeffs[11-i]);
+    }
+}
+
+static av_cold int g722_init(AVCodecContext * avctx)
+{
+    G722Context *c = avctx->priv_data;
+
+    if (avctx->channels != 1) {
+        av_log(avctx, AV_LOG_ERROR, "Only mono tracks are allowed.\n");
+        return AVERROR_INVALIDDATA;
+    }
+    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
+
+    switch (avctx->bits_per_coded_sample) {
+    case 8:
+    case 7:
+    case 6:
+        break;
+    default:
+        av_log(avctx, AV_LOG_WARNING, "Unsupported bits_per_coded_sample [%d], "
+                                      "assuming 8\n",
+                                      avctx->bits_per_coded_sample);
+    case 0:
+        avctx->bits_per_coded_sample = 8;
+        break;
+    }
+
+    c->band[0].scale_factor = 8;
+    c->band[1].scale_factor = 2;
+    c->prev_samples_pos = 22;
+
+    if (avctx->lowres)
+        avctx->sample_rate /= 2;
+
+    if (avctx->trellis) {
+        int frontier = 1 << avctx->trellis;
+        int max_paths = frontier * FREEZE_INTERVAL;
+        int i;
+        for (i = 0; i < 2; i++) {
+            c->paths[i] = av_mallocz(max_paths * sizeof(**c->paths));
+            c->node_buf[i] = av_mallocz(2 * frontier * sizeof(**c->node_buf));
+            c->nodep_buf[i] = av_mallocz(2 * frontier * sizeof(**c->nodep_buf));
+        }
+    }
+
+    return 0;
+}
+
+static av_cold int g722_close(AVCodecContext *avctx)
+{
+    G722Context *c = avctx->priv_data;
+    int i;
+    for (i = 0; i < 2; i++) {
+        av_freep(&c->paths[i]);
+        av_freep(&c->node_buf[i]);
+        av_freep(&c->nodep_buf[i]);
+    }
+    return 0;
+}
+
+#if CONFIG_ADPCM_G722_DECODER
+static const int16_t low_inv_quant5[32] = {
+     -35,   -35, -2919, -2195, -1765, -1458, -1219, -1023,
+    -858,  -714,  -587,  -473,  -370,  -276,  -190,  -110,
+    2919,  2195,  1765,  1458,  1219,  1023,   858,   714,
+     587,   473,   370,   276,   190,   110,    35,   -35
+};
+
+static const int16_t *low_inv_quants[3] = { low_inv_quant6, low_inv_quant5,
+                                 low_inv_quant4 };
+
+static int g722_decode_frame(AVCodecContext *avctx, void *data,
+                             int *data_size, AVPacket *avpkt)
+{
+    G722Context *c = avctx->priv_data;
+    int16_t *out_buf = data;
+    int j, out_len = 0;
+    const int skip = 8 - avctx->bits_per_coded_sample;
+    const int16_t *quantizer_table = low_inv_quants[skip];
+    GetBitContext gb;
+
+    init_get_bits(&gb, avpkt->data, avpkt->size * 8);
+
+    for (j = 0; j < avpkt->size; j++) {
+        int ilow, ihigh, rlow;
+
+        ihigh = get_bits(&gb, 2);
+        ilow = get_bits(&gb, 6 - skip);
+        skip_bits(&gb, skip);
+
+        rlow = av_clip((c->band[0].scale_factor * quantizer_table[ilow] >> 10)
+                      + c->band[0].s_predictor, -16384, 16383);
+
+        update_low_predictor(&c->band[0], ilow >> (2 - skip));
+
+        if (!avctx->lowres) {
+            const int dhigh = c->band[1].scale_factor *
+                              high_inv_quant[ihigh] >> 10;
+            const int rhigh = av_clip(dhigh + c->band[1].s_predictor,
+                                      -16384, 16383);
+            int xout1, xout2;
+
+            update_high_predictor(&c->band[1], dhigh, ihigh);
+
+            c->prev_samples[c->prev_samples_pos++] = rlow + rhigh;
+            c->prev_samples[c->prev_samples_pos++] = rlow - rhigh;
+            apply_qmf(c->prev_samples + c->prev_samples_pos - 24,
+                      &xout1, &xout2);
+            out_buf[out_len++] = av_clip_int16(xout1 >> 12);
+            out_buf[out_len++] = av_clip_int16(xout2 >> 12);
+            if (c->prev_samples_pos >= PREV_SAMPLES_BUF_SIZE) {
+                memmove(c->prev_samples,
+                        c->prev_samples + c->prev_samples_pos - 22,
+                        22 * sizeof(c->prev_samples[0]));
+                c->prev_samples_pos = 22;
+            }
+        } else
+            out_buf[out_len++] = rlow;
+    }
+    *data_size = out_len << 1;
+    return avpkt->size;
+}
+
+AVCodec ff_adpcm_g722_decoder = {
+    .name           = "g722",
+    .type           = AVMEDIA_TYPE_AUDIO,
+    .id             = CODEC_ID_ADPCM_G722,
+    .priv_data_size = sizeof(G722Context),
+    .init           = g722_init,
+    .decode         = g722_decode_frame,
+    .long_name      = NULL_IF_CONFIG_SMALL("G.722 ADPCM"),
+    .max_lowres     = 1,
+};
+#endif
+
+#if CONFIG_ADPCM_G722_ENCODER
+static const int16_t low_quant[33] = {
+      35,   72,  110,  150,  190,  233,  276,  323,
+     370,  422,  473,  530,  587,  650,  714,  786,
+     858,  940, 1023, 1121, 1219, 1339, 1458, 1612,
+    1765, 1980, 2195, 2557, 2919
+};
+
+static inline void filter_samples(G722Context *c, const int16_t *samples,
+                                  int *xlow, int *xhigh)
+{
+    int xout1, xout2;
+    c->prev_samples[c->prev_samples_pos++] = samples[0];
+    c->prev_samples[c->prev_samples_pos++] = samples[1];
+    apply_qmf(c->prev_samples + c->prev_samples_pos - 24, &xout1, &xout2);
+    *xlow  = xout1 + xout2 >> 13;
+    *xhigh = xout1 - xout2 >> 13;
+    if (c->prev_samples_pos >= PREV_SAMPLES_BUF_SIZE) {
+        memmove(c->prev_samples,
+                c->prev_samples + c->prev_samples_pos - 22,
+                22 * sizeof(c->prev_samples[0]));
+        c->prev_samples_pos = 22;
+    }
+}
+
+static inline int encode_high(const struct G722Band *state, int xhigh)
+{
+    int diff = av_clip_int16(xhigh - state->s_predictor);
+    int pred = 141 * state->scale_factor >> 8;
+           /* = diff >= 0 ? (diff < pred) + 2 : diff >= -pred */
+    return ((diff ^ (diff >> (sizeof(diff)*8-1))) < pred) + 2*(diff >= 0);
+}
+
+static inline int encode_low(const struct G722Band* state, int xlow)
+{
+    int diff  = av_clip_int16(xlow - state->s_predictor);
+           /* = diff >= 0 ? diff : -(diff + 1) */
+    int limit = diff ^ (diff >> (sizeof(diff)*8-1));
+    int i = 0;
+    limit = limit + 1 << 10;
+    if (limit > low_quant[8] * state->scale_factor)
+        i = 9;
+    while (i < 29 && limit > low_quant[i] * state->scale_factor)
+        i++;
+    return (diff < 0 ? (i < 2 ? 63 : 33) : 61) - i;
+}
+
+static int g722_encode_trellis(AVCodecContext *avctx,
+                               uint8_t *dst, int buf_size, void *data)
+{
+    G722Context *c = avctx->priv_data;
+    const int16_t *samples = data;
+    int i, j, k;
+    int frontier = 1 << avctx->trellis;
+    struct TrellisNode **nodes[2];
+    struct TrellisNode **nodes_next[2];
+    int pathn[2] = {0, 0}, froze = -1;
+    struct TrellisPath *p[2];
+
+    for (i = 0; i < 2; i++) {
+        nodes[i] = c->nodep_buf[i];
+        nodes_next[i] = c->nodep_buf[i] + frontier;
+        memset(c->nodep_buf[i], 0, 2 * frontier * sizeof(*c->nodep_buf));
+        nodes[i][0] = c->node_buf[i] + frontier;
+        nodes[i][0]->ssd = 0;
+        nodes[i][0]->path = 0;
+        nodes[i][0]->state = c->band[i];
+    }
+
+    for (i = 0; i < buf_size >> 1; i++) {
+        int xlow, xhigh;
+        struct TrellisNode *next[2];
+        int heap_pos[2] = {0, 0};
+
+        for (j = 0; j < 2; j++) {
+            next[j] = c->node_buf[j] + frontier*(i & 1);
+            memset(nodes_next[j], 0, frontier * sizeof(**nodes_next));
+        }
+
+        filter_samples(c, &samples[2*i], &xlow, &xhigh);
+
+        for (j = 0; j < frontier && nodes[0][j]; j++) {
+            /* Only k >> 2 affects the future adaptive state, therefore testing
+             * small steps that don't change k >> 2 is useless, the orignal
+             * value from encode_low is better than them. Since we step k
+             * in steps of 4, make sure range is a multiple of 4, so that
+             * we don't miss the original value from encode_low. */
+            int range = j < frontier/2 ? 4 : 0;
+            struct TrellisNode *cur_node = nodes[0][j];
+
+            int ilow = encode_low(&cur_node->state, xlow);
+
+            for (k = ilow - range; k <= ilow + range && k <= 63; k += 4) {
+                int decoded, dec_diff, pos;
+                uint32_t ssd;
+                struct TrellisNode* node;
+
+                if (k < 0)
+                    continue;
+
+                decoded = av_clip((cur_node->state.scale_factor *
+                                  low_inv_quant6[k] >> 10)
+                                + cur_node->state.s_predictor, -16384, 16383);
+                dec_diff = xlow - decoded;
+
+#define STORE_NODE(index, UPDATE, VALUE)\
+                ssd = cur_node->ssd + dec_diff*dec_diff;\
+                /* Check for wraparound. Using 64 bit ssd counters would \
+                 * be simpler, but is slower on x86 32 bit. */\
+                if (ssd < cur_node->ssd)\
+                    continue;\
+                if (heap_pos[index] < frontier) {\
+                    pos = heap_pos[index]++;\
+                    assert(pathn[index] < FREEZE_INTERVAL * frontier);\
+                    node = nodes_next[index][pos] = next[index]++;\
+                    node->path = pathn[index]++;\
+                } else {\
+                    /* Try to replace one of the leaf nodes with the new \
+                     * one, but not always testing the same leaf position */\
+                    pos = (frontier>>1) + (heap_pos[index] & ((frontier>>1) - 1));\
+                    if (ssd >= nodes_next[index][pos]->ssd)\
+                        continue;\
+                    heap_pos[index]++;\
+                    node = nodes_next[index][pos];\
+                }\
+                node->ssd = ssd;\
+                node->state = cur_node->state;\
+                UPDATE;\
+                c->paths[index][node->path].value = VALUE;\
+                c->paths[index][node->path].prev = cur_node->path;\
+                /* Sift the newly inserted node up in the heap to restore \
+                 * the heap property */\
+                while (pos > 0) {\
+                    int parent = (pos - 1) >> 1;\
+                    if (nodes_next[index][parent]->ssd <= ssd)\
+                        break;\
+                    FFSWAP(struct TrellisNode*, nodes_next[index][parent],\
+                                                nodes_next[index][pos]);\
+                    pos = parent;\
+                }
+                STORE_NODE(0, update_low_predictor(&node->state, k >> 2), k);
+            }
+        }
+
+        for (j = 0; j < frontier && nodes[1][j]; j++) {
+            int ihigh;
+            struct TrellisNode *cur_node = nodes[1][j];
+
+            /* We don't try to get any initial guess for ihigh via
+             * encode_high - since there's only 4 possible values, test
+             * them all. Testing all of these gives a much, much larger
+             * gain than testing a larger range around ilow. */
+            for (ihigh = 0; ihigh < 4; ihigh++) {
+                int dhigh, decoded, dec_diff, pos;
+                uint32_t ssd;
+                struct TrellisNode* node;
+
+                dhigh = cur_node->state.scale_factor *
+                        high_inv_quant[ihigh] >> 10;
+                decoded = av_clip(dhigh + cur_node->state.s_predictor,
+                                  -16384, 16383);
+                dec_diff = xhigh - decoded;
+
+                STORE_NODE(1, update_high_predictor(&node->state, dhigh, ihigh), ihigh);
+            }
+        }
+
+        for (j = 0; j < 2; j++) {
+            FFSWAP(struct TrellisNode**, nodes[j], nodes_next[j]);
+
+            if (nodes[j][0]->ssd > (1 << 16)) {
+                for (k = 1; k < frontier && nodes[j][k]; k++)
+                    nodes[j][k]->ssd -= nodes[j][0]->ssd;
+                nodes[j][0]->ssd = 0;
+            }
+        }
+
+        if (i == froze + FREEZE_INTERVAL) {
+            p[0] = &c->paths[0][nodes[0][0]->path];
+            p[1] = &c->paths[1][nodes[1][0]->path];
+            for (j = i; j > froze; j--) {
+                dst[j] = p[1]->value << 6 | p[0]->value;
+                p[0] = &c->paths[0][p[0]->prev];
+                p[1] = &c->paths[1][p[1]->prev];
+            }
+            froze = i;
+            pathn[0] = pathn[1] = 0;
+            memset(nodes[0] + 1, 0, (frontier - 1)*sizeof(**nodes));
+            memset(nodes[1] + 1, 0, (frontier - 1)*sizeof(**nodes));
+        }
+    }
+
+    p[0] = &c->paths[0][nodes[0][0]->path];
+    p[1] = &c->paths[1][nodes[1][0]->path];
+    for (j = i; j > froze; j--) {
+        dst[j] = p[1]->value << 6 | p[0]->value;
+        p[0] = &c->paths[0][p[0]->prev];
+        p[1] = &c->paths[1][p[1]->prev];
+    }
+    c->band[0] = nodes[0][0]->state;
+    c->band[1] = nodes[1][0]->state;
+
+    return i;
+}
+
+static int g722_encode_frame(AVCodecContext *avctx,
+                             uint8_t *dst, int buf_size, void *data)
+{
+    G722Context *c = avctx->priv_data;
+    const int16_t *samples = data;
+    int i;
+
+    if (avctx->trellis)
+        return g722_encode_trellis(avctx, dst, buf_size, data);
+
+    for (i = 0; i < buf_size >> 1; i++) {
+        int xlow, xhigh, ihigh, ilow;
+        filter_samples(c, &samples[2*i], &xlow, &xhigh);
+        ihigh = encode_high(&c->band[1], xhigh);
+        ilow  = encode_low(&c->band[0], xlow);
+        update_high_predictor(&c->band[1], c->band[1].scale_factor *
+                              high_inv_quant[ihigh] >> 10, ihigh);
+        update_low_predictor(&c->band[0], ilow >> 2);
+        *dst++ = ihigh << 6 | ilow;
+    }
+    return i;
+}
+
+AVCodec ff_adpcm_g722_encoder = {
+    .name           = "g722",
+    .type           = AVMEDIA_TYPE_AUDIO,
+    .id             = CODEC_ID_ADPCM_G722,
+    .priv_data_size = sizeof(G722Context),
+    .init           = g722_init,
+    .close          = g722_close,
+    .encode         = g722_encode_frame,
+    .long_name      = NULL_IF_CONFIG_SMALL("G.722 ADPCM"),
+    .sample_fmts    = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
+};
+#endif
+
diff --git a/libavcodec/g726.c b/libavcodec/g726.c
index 5e00511..09df727 100644
--- a/libavcodec/g726.c
+++ b/libavcodec/g726.c
@@ -5,20 +5,20 @@
  * This is a very straightforward rendition of the G.726
  * Section 4 "Computational Details".
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #include <limits.h>
@@ -332,7 +332,12 @@ static av_cold int g726_init(AVCodecContext * avctx)
     avctx->coded_frame->key_frame = 1;
 
     if (avctx->codec->decode)
-        avctx->sample_fmt = SAMPLE_FMT_S16;
+        avctx->sample_fmt = AV_SAMPLE_FMT_S16;
+
+    /* select a frame size that will end on a byte boundary and have a size of
+       approximately 1024 bytes */
+    if (avctx->codec->encode)
+        avctx->frame_size = ((int[]){ 4096, 2736, 2048, 1640 })[index];
 
     return 0;
 }
@@ -348,12 +353,13 @@ static int g726_encode_frame(AVCodecContext *avctx,
                             uint8_t *dst, int buf_size, void *data)
 {
     G726Context *c = avctx->priv_data;
-    short *samples = data;
+    const short *samples = data;
     PutBitContext pb;
+    int i;
 
     init_put_bits(&pb, dst, 1024*1024);
 
-    for (; buf_size; buf_size--)
+    for (i = 0; i < avctx->frame_size; i++)
         put_bits(&pb, c->code_size, g726_encode(c, *samples++));
 
     flush_put_bits(&pb);
@@ -385,7 +391,7 @@ static int g726_decode_frame(AVCodecContext *avctx,
 }
 
 #if CONFIG_ADPCM_G726_ENCODER
-AVCodec adpcm_g726_encoder = {
+AVCodec ff_adpcm_g726_encoder = {
     "g726",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_ADPCM_G726,
@@ -394,12 +400,13 @@ AVCodec adpcm_g726_encoder = {
     g726_encode_frame,
     g726_close,
     NULL,
-    .sample_fmts = (const enum SampleFormat[]){SAMPLE_FMT_S16,SAMPLE_FMT_NONE},
+    .capabilities = CODEC_CAP_SMALL_LAST_FRAME,
+    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
     .long_name = NULL_IF_CONFIG_SMALL("G.726 ADPCM"),
 };
 #endif
 
-AVCodec adpcm_g726_decoder = {
+AVCodec ff_adpcm_g726_decoder = {
     "g726",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_ADPCM_G726,
diff --git a/libavcodec/g729.h b/libavcodec/g729.h
index 462cf8f..9cae471 100644
--- a/libavcodec/g729.h
+++ b/libavcodec/g729.h
@@ -2,20 +2,20 @@
  * G.729 decoder
  * Copyright (c) 2008 Vladimir Voroshilov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #ifndef AVCODEC_G729_H
diff --git a/libavcodec/g729data.h b/libavcodec/g729data.h
index 1d64553..48010a7 100644
--- a/libavcodec/g729data.h
+++ b/libavcodec/g729data.h
@@ -2,20 +2,20 @@
  * data for G.729 decoder
  * Copyright (c) 2007 Vladimir Voroshilov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/g729dec.c b/libavcodec/g729dec.c
index 3a6fb0f..5763108 100644
--- a/libavcodec/g729dec.c
+++ b/libavcodec/g729dec.c
@@ -2,20 +2,20 @@
  * G.729 decoder
  * Copyright (c) 2008 Vladimir Voroshilov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #include <stdlib.h>
@@ -312,7 +312,7 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *data_size,
     return buf_size;
 }
 
-AVCodec g729_decoder =
+AVCodec ff_g729_decoder =
 {
     "g729",
     AVMEDIA_TYPE_AUDIO,
diff --git a/libavcodec/get_bits.h b/libavcodec/get_bits.h
index 556f542..2d36b81 100644
--- a/libavcodec/get_bits.h
+++ b/libavcodec/get_bits.h
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2004 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -39,12 +39,11 @@
 #   define ALT_BITSTREAM_READER
 #endif
 
-#if !defined(LIBMPEG2_BITSTREAM_READER) && !defined(A32_BITSTREAM_READER) && !defined(ALT_BITSTREAM_READER)
+#if !defined(A32_BITSTREAM_READER) && !defined(ALT_BITSTREAM_READER)
 #   if ARCH_ARM && !HAVE_FAST_UNALIGNED
 #       define A32_BITSTREAM_READER
 #   else
 #       define ALT_BITSTREAM_READER
-//#define LIBMPEG2_BITSTREAM_READER
 //#define A32_BITSTREAM_READER
 #   endif
 #endif
@@ -55,10 +54,6 @@ typedef struct GetBitContext {
     const uint8_t *buffer, *buffer_end;
 #ifdef ALT_BITSTREAM_READER
     int index;
-#elif defined LIBMPEG2_BITSTREAM_READER
-    uint8_t *buffer_ptr;
-    uint32_t cache;
-    int bit_count;
 #elif defined A32_BITSTREAM_READER
     uint32_t *buffer_ptr;
     uint32_t cache0;
@@ -130,56 +125,46 @@ for examples see get_bits, show_bits, skip_bits, get_vlc
 #ifdef ALT_BITSTREAM_READER
 #   define MIN_CACHE_BITS 25
 
-#   define OPEN_READER(name, gb)\
-        unsigned int name##_index= (gb)->index;\
-        int name##_cache= 0;\
+#   define OPEN_READER(name, gb)                \
+    unsigned int name##_index = (gb)->index;    \
+    int name##_cache          = 0
 
-#   define CLOSE_READER(name, gb)\
-        (gb)->index= name##_index;\
+#   define CLOSE_READER(name, gb) (gb)->index = name##_index
 
 # ifdef ALT_BITSTREAM_READER_LE
-#   define UPDATE_CACHE(name, gb)\
-        name##_cache= AV_RL32( ((const uint8_t *)(gb)->buffer)+(name##_index>>3) ) >> (name##_index&0x07);\
+#   define UPDATE_CACHE(name, gb) \
+    name##_cache = AV_RL32(((const uint8_t *)(gb)->buffer)+(name##_index>>3)) >> (name##_index&0x07)
 
-#   define SKIP_CACHE(name, gb, num)\
-        name##_cache >>= (num);
+#   define SKIP_CACHE(name, gb, num) name##_cache >>= (num)
 # else
-#   define UPDATE_CACHE(name, gb)\
-        name##_cache= AV_RB32( ((const uint8_t *)(gb)->buffer)+(name##_index>>3) ) << (name##_index&0x07);\
+#   define UPDATE_CACHE(name, gb) \
+    name##_cache = AV_RB32(((const uint8_t *)(gb)->buffer)+(name##_index>>3)) << (name##_index&0x07)
 
-#   define SKIP_CACHE(name, gb, num)\
-        name##_cache <<= (num);
+#   define SKIP_CACHE(name, gb, num) name##_cache <<= (num)
 # endif
 
 // FIXME name?
-#   define SKIP_COUNTER(name, gb, num)\
-        name##_index += (num);\
+#   define SKIP_COUNTER(name, gb, num) name##_index += (num)
 
-#   define SKIP_BITS(name, gb, num)\
-        {\
-            SKIP_CACHE(name, gb, num)\
-            SKIP_COUNTER(name, gb, num)\
-        }\
+#   define SKIP_BITS(name, gb, num) do {        \
+        SKIP_CACHE(name, gb, num);              \
+        SKIP_COUNTER(name, gb, num);            \
+    } while (0)
 
 #   define LAST_SKIP_BITS(name, gb, num) SKIP_COUNTER(name, gb, num)
-#   define LAST_SKIP_CACHE(name, gb, num) ;
+#   define LAST_SKIP_CACHE(name, gb, num)
 
 # ifdef ALT_BITSTREAM_READER_LE
-#   define SHOW_UBITS(name, gb, num)\
-        zero_extend(name##_cache, num)
+#   define SHOW_UBITS(name, gb, num) zero_extend(name##_cache, num)
 
-#   define SHOW_SBITS(name, gb, num)\
-        sign_extend(name##_cache, num)
+#   define SHOW_SBITS(name, gb, num) sign_extend(name##_cache, num)
 # else
-#   define SHOW_UBITS(name, gb, num)\
-        NEG_USR32(name##_cache, num)
+#   define SHOW_UBITS(name, gb, num) NEG_USR32(name##_cache, num)
 
-#   define SHOW_SBITS(name, gb, num)\
-        NEG_SSR32(name##_cache, num)
+#   define SHOW_SBITS(name, gb, num) NEG_SSR32(name##_cache, num)
 # endif
 
-#   define GET_CACHE(name, gb)\
-        ((uint32_t)name##_cache)
+#   define GET_CACHE(name, gb) ((uint32_t)name##_cache)
 
 static inline int get_bits_count(const GetBitContext *s){
     return s->index;
@@ -189,140 +174,76 @@ static inline void skip_bits_long(GetBitContext *s, int n){
     s->index += n;
 }
 
-#elif defined LIBMPEG2_BITSTREAM_READER
-//libmpeg2 like reader
-
-#   define MIN_CACHE_BITS 17
-
-#   define OPEN_READER(name, gb)\
-        int name##_bit_count=(gb)->bit_count;\
-        int name##_cache= (gb)->cache;\
-        uint8_t * name##_buffer_ptr=(gb)->buffer_ptr;\
-
-#   define CLOSE_READER(name, gb)\
-        (gb)->bit_count= name##_bit_count;\
-        (gb)->cache= name##_cache;\
-        (gb)->buffer_ptr= name##_buffer_ptr;\
-
-#   define UPDATE_CACHE(name, gb)\
-    if(name##_bit_count >= 0){\
-        name##_cache+= AV_RB16(name##_buffer_ptr) << name##_bit_count; \
-        name##_buffer_ptr+=2;\
-        name##_bit_count-= 16;\
-    }\
-
-#   define SKIP_CACHE(name, gb, num)\
-        name##_cache <<= (num);\
-
-#   define SKIP_COUNTER(name, gb, num)\
-        name##_bit_count += (num);\
-
-#   define SKIP_BITS(name, gb, num)\
-        {\
-            SKIP_CACHE(name, gb, num)\
-            SKIP_COUNTER(name, gb, num)\
-        }\
-
-#   define LAST_SKIP_BITS(name, gb, num) SKIP_BITS(name, gb, num)
-#   define LAST_SKIP_CACHE(name, gb, num) SKIP_CACHE(name, gb, num)
-
-#   define SHOW_UBITS(name, gb, num)\
-        NEG_USR32(name##_cache, num)
-
-#   define SHOW_SBITS(name, gb, num)\
-        NEG_SSR32(name##_cache, num)
-
-#   define GET_CACHE(name, gb)\
-        ((uint32_t)name##_cache)
-
-static inline int get_bits_count(const GetBitContext *s){
-    return (s->buffer_ptr - s->buffer)*8 - 16 + s->bit_count;
-}
-
-static inline void skip_bits_long(GetBitContext *s, int n){
-    OPEN_READER(re, s)
-    re_bit_count += n;
-    re_buffer_ptr += 2*(re_bit_count>>4);
-    re_bit_count &= 15;
-    re_cache = ((re_buffer_ptr[-2]<<8) + re_buffer_ptr[-1]) << (16+re_bit_count);
-    UPDATE_CACHE(re, s)
-    CLOSE_READER(re, s)
-}
-
 #elif defined A32_BITSTREAM_READER
 
 #   define MIN_CACHE_BITS 32
 
-#   define OPEN_READER(name, gb)\
-        int name##_bit_count=(gb)->bit_count;\
-        uint32_t name##_cache0= (gb)->cache0;\
-        uint32_t name##_cache1= (gb)->cache1;\
-        uint32_t * name##_buffer_ptr=(gb)->buffer_ptr;\
-
-#   define CLOSE_READER(name, gb)\
-        (gb)->bit_count= name##_bit_count;\
-        (gb)->cache0= name##_cache0;\
-        (gb)->cache1= name##_cache1;\
-        (gb)->buffer_ptr= name##_buffer_ptr;\
-
-#   define UPDATE_CACHE(name, gb)\
-    if(name##_bit_count > 0){\
-        const uint32_t next= be2me_32( *name##_buffer_ptr );\
-        name##_cache0 |= NEG_USR32(next,name##_bit_count);\
-        name##_cache1 |= next<<name##_bit_count;\
-        name##_buffer_ptr++;\
-        name##_bit_count-= 32;\
-    }\
+#   define OPEN_READER(name, gb)                        \
+    int name##_bit_count        = (gb)->bit_count;      \
+    uint32_t name##_cache0      = (gb)->cache0;         \
+    uint32_t name##_cache1      = (gb)->cache1;         \
+    uint32_t *name##_buffer_ptr = (gb)->buffer_ptr
+
+#   define CLOSE_READER(name, gb) do {          \
+        (gb)->bit_count  = name##_bit_count;    \
+        (gb)->cache0     = name##_cache0;       \
+        (gb)->cache1     = name##_cache1;       \
+        (gb)->buffer_ptr = name##_buffer_ptr;   \
+    } while (0)
+
+#   define UPDATE_CACHE(name, gb) do {                                  \
+        if(name##_bit_count > 0){                                       \
+            const uint32_t next = av_be2ne32(*name##_buffer_ptr);       \
+            name##_cache0 |= NEG_USR32(next, name##_bit_count);         \
+            name##_cache1 |= next << name##_bit_count;                  \
+            name##_buffer_ptr++;                                        \
+            name##_bit_count -= 32;                                     \
+        }                                                               \
+    } while (0)
 
 #if ARCH_X86
-#   define SKIP_CACHE(name, gb, num)\
-        __asm__(\
-            "shldl %2, %1, %0          \n\t"\
-            "shll %2, %1               \n\t"\
-            : "+r" (name##_cache0), "+r" (name##_cache1)\
-            : "Ic" ((uint8_t)(num))\
-           );
+#   define SKIP_CACHE(name, gb, num)                            \
+    __asm__("shldl %2, %1, %0          \n\t"                    \
+            "shll  %2, %1              \n\t"                    \
+            : "+r" (name##_cache0), "+r" (name##_cache1)        \
+            : "Ic" ((uint8_t)(num)))
 #else
-#   define SKIP_CACHE(name, gb, num)\
-        name##_cache0 <<= (num);\
-        name##_cache0 |= NEG_USR32(name##_cache1,num);\
-        name##_cache1 <<= (num);
+#   define SKIP_CACHE(name, gb, num) do {               \
+        name##_cache0 <<= (num);                        \
+        name##_cache0 |= NEG_USR32(name##_cache1,num);  \
+        name##_cache1 <<= (num);                        \
+    } while (0)
 #endif
 
-#   define SKIP_COUNTER(name, gb, num)\
-        name##_bit_count += (num);\
+#   define SKIP_COUNTER(name, gb, num) name##_bit_count += (num)
 
-#   define SKIP_BITS(name, gb, num)\
-        {\
-            SKIP_CACHE(name, gb, num)\
-            SKIP_COUNTER(name, gb, num)\
-        }\
+#   define SKIP_BITS(name, gb, num) do {        \
+        SKIP_CACHE(name, gb, num);              \
+        SKIP_COUNTER(name, gb, num);            \
+    } while (0)
 
-#   define LAST_SKIP_BITS(name, gb, num) SKIP_BITS(name, gb, num)
+#   define LAST_SKIP_BITS(name, gb, num)  SKIP_BITS(name, gb, num)
 #   define LAST_SKIP_CACHE(name, gb, num) SKIP_CACHE(name, gb, num)
 
-#   define SHOW_UBITS(name, gb, num)\
-        NEG_USR32(name##_cache0, num)
+#   define SHOW_UBITS(name, gb, num) NEG_USR32(name##_cache0, num)
 
-#   define SHOW_SBITS(name, gb, num)\
-        NEG_SSR32(name##_cache0, num)
+#   define SHOW_SBITS(name, gb, num) NEG_SSR32(name##_cache0, num)
 
-#   define GET_CACHE(name, gb)\
-        (name##_cache0)
+#   define GET_CACHE(name, gb) name##_cache0
 
-static inline int get_bits_count(const GetBitContext *s){
+static inline int get_bits_count(const GetBitContext *s) {
     return ((uint8_t*)s->buffer_ptr - s->buffer)*8 - 32 + s->bit_count;
 }
 
 static inline void skip_bits_long(GetBitContext *s, int n){
-    OPEN_READER(re, s)
+    OPEN_READER(re, s);
     re_bit_count += n;
     re_buffer_ptr += re_bit_count>>5;
     re_bit_count &= 31;
-    re_cache0 = be2me_32( re_buffer_ptr[-1] ) << re_bit_count;
+    re_cache0 = av_be2ne32(re_buffer_ptr[-1]) << re_bit_count;
     re_cache1 = 0;
-    UPDATE_CACHE(re, s)
-    CLOSE_READER(re, s)
+    UPDATE_CACHE(re, s);
+    CLOSE_READER(re, s);
 }
 
 #endif
@@ -336,73 +257,70 @@ static inline void skip_bits_long(GetBitContext *s, int n){
 static inline int get_xbits(GetBitContext *s, int n){
     register int sign;
     register int32_t cache;
-    OPEN_READER(re, s)
-    UPDATE_CACHE(re, s)
-    cache = GET_CACHE(re,s);
-    sign=(~cache)>>31;
-    LAST_SKIP_BITS(re, s, n)
-    CLOSE_READER(re, s)
+    OPEN_READER(re, s);
+    UPDATE_CACHE(re, s);
+    cache = GET_CACHE(re, s);
+    sign = ~cache >> 31;
+    LAST_SKIP_BITS(re, s, n);
+    CLOSE_READER(re, s);
     return (NEG_USR32(sign ^ cache, n) ^ sign) - sign;
 }
 
 static inline int get_sbits(GetBitContext *s, int n){
     register int tmp;
-    OPEN_READER(re, s)
-    UPDATE_CACHE(re, s)
-    tmp= SHOW_SBITS(re, s, n);
-    LAST_SKIP_BITS(re, s, n)
-    CLOSE_READER(re, s)
+    OPEN_READER(re, s);
+    UPDATE_CACHE(re, s);
+    tmp = SHOW_SBITS(re, s, n);
+    LAST_SKIP_BITS(re, s, n);
+    CLOSE_READER(re, s);
     return tmp;
 }
 
 /**
- * reads 1-17 bits.
- * Note, the alt bitstream reader can read up to 25 bits, but the libmpeg2 reader can't
+ * Read 1-25 bits.
  */
 static inline unsigned int get_bits(GetBitContext *s, int n){
     register int tmp;
-    OPEN_READER(re, s)
-    UPDATE_CACHE(re, s)
-    tmp= SHOW_UBITS(re, s, n);
-    LAST_SKIP_BITS(re, s, n)
-    CLOSE_READER(re, s)
+    OPEN_READER(re, s);
+    UPDATE_CACHE(re, s);
+    tmp = SHOW_UBITS(re, s, n);
+    LAST_SKIP_BITS(re, s, n);
+    CLOSE_READER(re, s);
     return tmp;
 }
 
 /**
- * shows 1-17 bits.
- * Note, the alt bitstream reader can read up to 25 bits, but the libmpeg2 reader can't
+ * Shows 1-25 bits.
  */
 static inline unsigned int show_bits(GetBitContext *s, int n){
     register int tmp;
-    OPEN_READER(re, s)
-    UPDATE_CACHE(re, s)
-    tmp= SHOW_UBITS(re, s, n);
-//    CLOSE_READER(re, s)
+    OPEN_READER(re, s);
+    UPDATE_CACHE(re, s);
+    tmp = SHOW_UBITS(re, s, n);
     return tmp;
 }
 
 static inline void skip_bits(GetBitContext *s, int n){
  //Note gcc seems to optimize this to s->index+=n for the ALT_READER :))
-    OPEN_READER(re, s)
-    UPDATE_CACHE(re, s)
-    LAST_SKIP_BITS(re, s, n)
-    CLOSE_READER(re, s)
+    OPEN_READER(re, s);
+    UPDATE_CACHE(re, s);
+    LAST_SKIP_BITS(re, s, n);
+    CLOSE_READER(re, s);
 }
 
 static inline unsigned int get_bits1(GetBitContext *s){
 #ifdef ALT_BITSTREAM_READER
-    unsigned int index= s->index;
-    uint8_t result= s->buffer[ index>>3 ];
+    unsigned int index = s->index;
+    uint8_t result = s->buffer[index>>3];
 #ifdef ALT_BITSTREAM_READER_LE
-    result>>= (index&0x07);
-    result&= 1;
+    result >>= index & 7;
+    result &= 1;
 #else
-    result<<= (index&0x07);
-    result>>= 8 - 1;
+    result <<= index & 7;
+    result >>= 8 - 1;
 #endif
     index++;
-    s->index= index;
+    s->index = index;
 
     return result;
 #else
@@ -422,13 +340,13 @@ static inline void skip_bits1(GetBitContext *s){
  * reads 0-32 bits.
  */
 static inline unsigned int get_bits_long(GetBitContext *s, int n){
-    if(n<=MIN_CACHE_BITS) return get_bits(s, n);
-    else{
+    if (n <= MIN_CACHE_BITS) return get_bits(s, n);
+    else {
 #ifdef ALT_BITSTREAM_READER_LE
-        int ret= get_bits(s, 16);
+        int ret = get_bits(s, 16);
         return ret | (get_bits(s, n-16) << 16);
 #else
-        int ret= get_bits(s, 16) << (n-16);
+        int ret = get_bits(s, 16) << (n-16);
         return ret | get_bits(s, n-16);
 #endif
     }
@@ -445,17 +363,17 @@ static inline int get_sbits_long(GetBitContext *s, int n) {
  * shows 0-32 bits.
  */
 static inline unsigned int show_bits_long(GetBitContext *s, int n){
-    if(n<=MIN_CACHE_BITS) return show_bits(s, n);
-    else{
-        GetBitContext gb= *s;
+    if (n <= MIN_CACHE_BITS) return show_bits(s, n);
+    else {
+        GetBitContext gb = *s;
         return get_bits_long(&gb, n);
     }
 }
 
 static inline int check_marker(GetBitContext *s, const char *msg)
 {
-    int bit= get_bits1(s);
-    if(!bit)
+    int bit = get_bits1(s);
+    if (!bit)
         av_log(NULL, AV_LOG_INFO, "Marker bit missing %s\n", msg);
 
     return bit;
@@ -473,42 +391,38 @@ static inline int check_marker(GetBitContext *s, const char *msg)
 static inline void init_get_bits(GetBitContext *s,
                    const uint8_t *buffer, int bit_size)
 {
-    int buffer_size= (bit_size+7)>>3;
-    if(buffer_size < 0 || bit_size < 0) {
+    int buffer_size = (bit_size+7)>>3;
+    if (buffer_size < 0 || bit_size < 0) {
         buffer_size = bit_size = 0;
         buffer = NULL;
     }
 
-    s->buffer= buffer;
-    s->size_in_bits= bit_size;
-    s->buffer_end= buffer + buffer_size;
+    s->buffer       = buffer;
+    s->size_in_bits = bit_size;
+    s->buffer_end   = buffer + buffer_size;
 #ifdef ALT_BITSTREAM_READER
-    s->index=0;
-#elif defined LIBMPEG2_BITSTREAM_READER
-    s->buffer_ptr = (uint8_t*)((intptr_t)buffer&(~1));
-    s->bit_count = 16 + 8*((intptr_t)buffer&1);
-    skip_bits_long(s, 0);
+    s->index        = 0;
 #elif defined A32_BITSTREAM_READER
-    s->buffer_ptr = (uint32_t*)((intptr_t)buffer&(~3));
-    s->bit_count = 32 + 8*((intptr_t)buffer&3);
+    s->buffer_ptr   = (uint32_t*)((intptr_t)buffer & ~3);
+    s->bit_count    = 32 +     8*((intptr_t)buffer &  3);
     skip_bits_long(s, 0);
 #endif
 }
 
 static inline void align_get_bits(GetBitContext *s)
 {
-    int n= (-get_bits_count(s)) & 7;
-    if(n) skip_bits(s, n);
+    int n = -get_bits_count(s) & 7;
+    if (n) skip_bits(s, n);
 }
 
-#define init_vlc(vlc, nb_bits, nb_codes,\
-                 bits, bits_wrap, bits_size,\
-                 codes, codes_wrap, codes_size,\
-                 flags)\
-        init_vlc_sparse(vlc, nb_bits, nb_codes,\
-                 bits, bits_wrap, bits_size,\
-                 codes, codes_wrap, codes_size,\
-                 NULL, 0, 0, flags)
+#define init_vlc(vlc, nb_bits, nb_codes,                \
+                 bits, bits_wrap, bits_size,            \
+                 codes, codes_wrap, codes_size,         \
+                 flags)                                 \
+        init_vlc_sparse(vlc, nb_bits, nb_codes,         \
+                        bits, bits_wrap, bits_size,     \
+                        codes, codes_wrap, codes_size,  \
+                        NULL, 0, 0, flags)
 
 int init_vlc_sparse(VLC *vlc, int nb_bits, int nb_codes,
              const void *bits, int bits_wrap, int bits_size,
@@ -519,13 +433,12 @@ int init_vlc_sparse(VLC *vlc, int nb_bits, int nb_codes,
 #define INIT_VLC_USE_NEW_STATIC 4
 void free_vlc(VLC *vlc);
 
-#define INIT_VLC_STATIC(vlc, bits, a,b,c,d,e,f,g, static_size)\
-{\
-    static VLC_TYPE table[static_size][2];\
-    (vlc)->table= table;\
-    (vlc)->table_allocated= static_size;\
-    init_vlc(vlc, bits, a,b,c,d,e,f,g, INIT_VLC_USE_NEW_STATIC);\
-}
+#define INIT_VLC_STATIC(vlc, bits, a,b,c,d,e,f,g, static_size) do {     \
+        static VLC_TYPE table[static_size][2];                          \
+        (vlc)->table = table;                                           \
+        (vlc)->table_allocated = static_size;                           \
+        init_vlc(vlc, bits, a,b,c,d,e,f,g, INIT_VLC_USE_NEW_STATIC);    \
+    } while (0)
 
 
 /**
@@ -534,62 +447,60 @@ void free_vlc(VLC *vlc);
  * If the vlc code is invalid and max_depth>1, then the number of bits removed
  * is undefined.
  */
-#define GET_VLC(code, name, gb, table, bits, max_depth)\
-{\
-    int n, nb_bits;\
-    unsigned int index;\
-\
-    index= SHOW_UBITS(name, gb, bits);\
-    code = table[index][0];\
-    n    = table[index][1];\
-\
-    if(max_depth > 1 && n < 0){\
-        LAST_SKIP_BITS(name, gb, bits)\
-        UPDATE_CACHE(name, gb)\
-\
-        nb_bits = -n;\
-\
-        index= SHOW_UBITS(name, gb, nb_bits) + code;\
-        code = table[index][0];\
-        n    = table[index][1];\
-        if(max_depth > 2 && n < 0){\
-            LAST_SKIP_BITS(name, gb, nb_bits)\
-            UPDATE_CACHE(name, gb)\
-\
-            nb_bits = -n;\
-\
-            index= SHOW_UBITS(name, gb, nb_bits) + code;\
-            code = table[index][0];\
-            n    = table[index][1];\
-        }\
-    }\
-    SKIP_BITS(name, gb, n)\
-}
-
-#define GET_RL_VLC(level, run, name, gb, table, bits, max_depth, need_update)\
-{\
-    int n, nb_bits;\
-    unsigned int index;\
-\
-    index= SHOW_UBITS(name, gb, bits);\
-    level = table[index].level;\
-    n     = table[index].len;\
-\
-    if(max_depth > 1 && n < 0){\
-        SKIP_BITS(name, gb, bits)\
-        if(need_update){\
-            UPDATE_CACHE(name, gb)\
-        }\
-\
-        nb_bits = -n;\
-\
-        index= SHOW_UBITS(name, gb, nb_bits) + level;\
-        level = table[index].level;\
-        n     = table[index].len;\
-    }\
-    run= table[index].run;\
-    SKIP_BITS(name, gb, n)\
-}
+#define GET_VLC(code, name, gb, table, bits, max_depth) do {    \
+        int n, nb_bits;                                         \
+        unsigned int index;                                     \
+                                                                \
+        index = SHOW_UBITS(name, gb, bits);                     \
+        code  = table[index][0];                                \
+        n     = table[index][1];                                \
+                                                                \
+        if (max_depth > 1 && n < 0) {                           \
+            LAST_SKIP_BITS(name, gb, bits);                     \
+            UPDATE_CACHE(name, gb);                             \
+                                                                \
+            nb_bits = -n;                                       \
+                                                                \
+            index = SHOW_UBITS(name, gb, nb_bits) + code;       \
+            code  = table[index][0];                            \
+            n     = table[index][1];                            \
+            if (max_depth > 2 && n < 0) {                       \
+                LAST_SKIP_BITS(name, gb, nb_bits);              \
+                UPDATE_CACHE(name, gb);                         \
+                                                                \
+                nb_bits = -n;                                   \
+                                                                \
+                index = SHOW_UBITS(name, gb, nb_bits) + code;   \
+                code  = table[index][0];                        \
+                n     = table[index][1];                        \
+            }                                                   \
+        }                                                       \
+        SKIP_BITS(name, gb, n);                                 \
+    } while (0)
+
+#define GET_RL_VLC(level, run, name, gb, table, bits, max_depth, need_update) do { \
+        int n, nb_bits;                                                 \
+        unsigned int index;                                             \
+                                                                        \
+        index = SHOW_UBITS(name, gb, bits);                             \
+        level = table[index].level;                                     \
+        n     = table[index].len;                                       \
+                                                                        \
+        if (max_depth > 1 && n < 0) {                                   \
+            SKIP_BITS(name, gb, bits);                                  \
+            if (need_update) {                                          \
+                UPDATE_CACHE(name, gb);                                 \
+            }                                                           \
+                                                                        \
+            nb_bits = -n;                                               \
+                                                                        \
+            index = SHOW_UBITS(name, gb, nb_bits) + level;              \
+            level = table[index].level;                                 \
+            n     = table[index].len;                                   \
+        }                                                               \
+        run = table[index].run;                                         \
+        SKIP_BITS(name, gb, n);                                         \
+    } while (0)
 
 
 /**
@@ -605,53 +516,81 @@ static av_always_inline int get_vlc2(GetBitContext *s, VLC_TYPE (*table)[2],
 {
     int code;
 
-    OPEN_READER(re, s)
-    UPDATE_CACHE(re, s)
+    OPEN_READER(re, s);
+    UPDATE_CACHE(re, s);
 
-    GET_VLC(code, re, s, table, bits, max_depth)
+    GET_VLC(code, re, s, table, bits, max_depth);
 
-    CLOSE_READER(re, s)
+    CLOSE_READER(re, s);
     return code;
 }
 
+static inline int decode012(GetBitContext *gb){
+    int n;
+    n = get_bits1(gb);
+    if (n == 0)
+        return 0;
+    else
+        return get_bits1(gb) + 1;
+}
+
+static inline int decode210(GetBitContext *gb){
+    if (get_bits1(gb))
+        return 0;
+    else
+        return 2 - get_bits1(gb);
+}
+
+static inline int get_bits_left(GetBitContext *gb)
+{
+    return gb->size_in_bits - get_bits_count(gb);
+}
+
 //#define TRACE
 
 #ifdef TRACE
 static inline void print_bin(int bits, int n){
     int i;
 
-    for(i=n-1; i>=0; i--){
+    for (i = n-1; i >= 0; i--) {
         av_log(NULL, AV_LOG_DEBUG, "%d", (bits>>i)&1);
     }
-    for(i=n; i<24; i++)
+    for (i = n; i < 24; i++)
         av_log(NULL, AV_LOG_DEBUG, " ");
 }
 
-static inline int get_bits_trace(GetBitContext *s, int n, char *file, const char *func, int line){
-    int r= get_bits(s, n);
+static inline int get_bits_trace(GetBitContext *s, int n, char *file,
+                                 const char *func, int line){
+    int r = get_bits(s, n);
 
     print_bin(r, n);
-    av_log(NULL, AV_LOG_DEBUG, "%5d %2d %3d bit @%5d in %s %s:%d\n", r, n, r, get_bits_count(s)-n, file, func, line);
+    av_log(NULL, AV_LOG_DEBUG, "%5d %2d %3d bit @%5d in %s %s:%d\n",
+           r, n, r, get_bits_count(s)-n, file, func, line);
     return r;
 }
-static inline int get_vlc_trace(GetBitContext *s, VLC_TYPE (*table)[2], int bits, int max_depth, char *file, const char *func, int line){
-    int show= show_bits(s, 24);
-    int pos= get_bits_count(s);
-    int r= get_vlc2(s, table, bits, max_depth);
-    int len= get_bits_count(s) - pos;
-    int bits2= show>>(24-len);
+static inline int get_vlc_trace(GetBitContext *s, VLC_TYPE (*table)[2],
+                                int bits, int max_depth, char *file,
+                                const char *func, int line){
+    int show  = show_bits(s, 24);
+    int pos   = get_bits_count(s);
+    int r     = get_vlc2(s, table, bits, max_depth);
+    int len   = get_bits_count(s) - pos;
+    int bits2 = show >> (24-len);
 
     print_bin(bits2, len);
 
-    av_log(NULL, AV_LOG_DEBUG, "%5d %2d %3d vlc @%5d in %s %s:%d\n", bits2, len, r, pos, file, func, line);
+    av_log(NULL, AV_LOG_DEBUG, "%5d %2d %3d vlc @%5d in %s %s:%d\n",
+           bits2, len, r, pos, file, func, line);
     return r;
 }
-static inline int get_xbits_trace(GetBitContext *s, int n, char *file, const char *func, int line){
-    int show= show_bits(s, n);
-    int r= get_xbits(s, n);
+static inline int get_xbits_trace(GetBitContext *s, int n, char *file,
+                                  const char *func, int line){
+    int show = show_bits(s, n);
+    int r    = get_xbits(s, n);
 
     print_bin(show, n);
-    av_log(NULL, AV_LOG_DEBUG, "%5d %2d %3d xbt @%5d in %s %s:%d\n", show, n, r, get_bits_count(s)-n, file, func, line);
+    av_log(NULL, AV_LOG_DEBUG, "%5d %2d %3d xbt @%5d in %s %s:%d\n",
+           show, n, r, get_bits_count(s)-n, file, func, line);
     return r;
 }
 
@@ -667,25 +606,4 @@ static inline int get_xbits_trace(GetBitContext *s, int n, char *file, const cha
 #define tprintf(p, ...) {}
 #endif
 
-static inline int decode012(GetBitContext *gb){
-    int n;
-    n = get_bits1(gb);
-    if (n == 0)
-        return 0;
-    else
-        return get_bits1(gb) + 1;
-}
-
-static inline int decode210(GetBitContext *gb){
-    if (get_bits1(gb))
-        return 0;
-    else
-        return 2 - get_bits1(gb);
-}
-
-static inline int get_bits_left(GetBitContext *gb)
-{
-    return gb->size_in_bits - get_bits_count(gb);
-}
-
 #endif /* AVCODEC_GET_BITS_H */
diff --git a/libavcodec/gif.c b/libavcodec/gif.c
index 5114b89..6fb7051 100644
--- a/libavcodec/gif.c
+++ b/libavcodec/gif.c
@@ -4,20 +4,20 @@
  * Copyright (c) 2002 Francois Revol
  * Copyright (c) 2006 Baptiste Coudurier
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -87,7 +87,7 @@ static int gif_image_write_image(AVCodecContext *avctx,
                                  const uint8_t *buf, int linesize)
 {
     GIFContext *s = avctx->priv_data;
-    int len, height;
+    int len = 0, height;
     const uint8_t *ptr;
     /* image block */
 
@@ -166,7 +166,7 @@ static int gif_encode_close(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec gif_encoder = {
+AVCodec ff_gif_encoder = {
     "gif",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_GIF,
diff --git a/libavcodec/gifdec.c b/libavcodec/gifdec.c
index 1daf1b7..934c944 100644
--- a/libavcodec/gifdec.c
+++ b/libavcodec/gifdec.c
@@ -3,25 +3,26 @@
  * Copyright (c) 2003 Fabrice Bellard
  * Copyright (c) 2006 Baptiste Coudurier
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 //#define DEBUG
 
+#include "libavutil/imgutils.h"
 #include "avcodec.h"
 #include "bytestream.h"
 #include "lzw.h"
@@ -75,9 +76,8 @@ static int gif_read_image(GifState *s)
     is_interleaved = flags & 0x40;
     has_local_palette = flags & 0x80;
     bits_per_pixel = (flags & 0x07) + 1;
-#ifdef DEBUG
-    dprintf(s->avctx, "gif: image x=%d y=%d w=%d h=%d\n", left, top, width, height);
-#endif
+
+    av_dlog(s->avctx, "gif: image x=%d y=%d w=%d h=%d\n", left, top, width, height);
 
     if (has_local_palette) {
         bytestream_get_buffer(&s->bytestream, s->local_palette, 3 * (1 << bits_per_pixel));
@@ -162,9 +162,9 @@ static int gif_read_extension(GifState *s)
     /* extension */
     ext_code = bytestream_get_byte(&s->bytestream);
     ext_len = bytestream_get_byte(&s->bytestream);
-#ifdef DEBUG
-    dprintf(s->avctx, "gif: ext_code=0x%x len=%d\n", ext_code, ext_len);
-#endif
+
+    av_dlog(s->avctx, "gif: ext_code=0x%x len=%d\n", ext_code, ext_len);
+
     switch(ext_code) {
     case 0xf9:
         if (ext_len != 4)
@@ -178,11 +178,11 @@ static int gif_read_extension(GifState *s)
         else
             s->transparent_color_index = -1;
         s->gce_disposal = (gce_flags >> 2) & 0x7;
-#ifdef DEBUG
-        dprintf(s->avctx, "gif: gce_flags=%x delay=%d tcolor=%d disposal=%d\n",
+
+        av_dlog(s->avctx, "gif: gce_flags=%x delay=%d tcolor=%d disposal=%d\n",
                gce_flags, s->gce_delay,
                s->transparent_color_index, s->gce_disposal);
-#endif
+
         ext_len = bytestream_get_byte(&s->bytestream);
         break;
     }
@@ -193,9 +193,8 @@ static int gif_read_extension(GifState *s)
         for (i = 0; i < ext_len; i++)
             bytestream_get_byte(&s->bytestream);
         ext_len = bytestream_get_byte(&s->bytestream);
-#ifdef DEBUG
-        dprintf(s->avctx, "gif: ext_len1=%d\n", ext_len);
-#endif
+
+        av_dlog(s->avctx, "gif: ext_len1=%d\n", ext_len);
     }
     return 0;
 }
@@ -231,11 +230,11 @@ static int gif_read_header1(GifState *s)
     s->bits_per_pixel = (v & 0x07) + 1;
     s->background_color_index = bytestream_get_byte(&s->bytestream);
     bytestream_get_byte(&s->bytestream);                /* ignored */
-#ifdef DEBUG
-    dprintf(s->avctx, "gif: screen_w=%d screen_h=%d bpp=%d global_palette=%d\n",
+
+    av_dlog(s->avctx, "gif: screen_w=%d screen_h=%d bpp=%d global_palette=%d\n",
            s->screen_width, s->screen_height, s->bits_per_pixel,
            has_global_palette);
-#endif
+
     if (has_global_palette) {
         n = 1 << s->bits_per_pixel;
         if (s->bytestream_end < s->bytestream + n * 3)
@@ -249,9 +248,9 @@ static int gif_parse_next_image(GifState *s)
 {
     while (s->bytestream < s->bytestream_end) {
         int code = bytestream_get_byte(&s->bytestream);
-#ifdef DEBUG
-        dprintf(s->avctx, "gif: code=%02x '%c'\n", code, code);
-#endif
+
+        av_dlog(s->avctx, "gif: code=%02x '%c'\n", code, code);
+
         switch (code) {
         case ',':
             return gif_read_image(s);
@@ -296,7 +295,7 @@ static int gif_decode_frame(AVCodecContext *avctx, void *data, int *data_size, A
         return -1;
 
     avctx->pix_fmt = PIX_FMT_PAL8;
-    if (avcodec_check_dimensions(avctx, s->screen_width, s->screen_height))
+    if (av_image_check_size(s->screen_width, s->screen_height, 0, avctx))
         return -1;
     avcodec_set_dimensions(avctx, s->screen_width, s->screen_height);
 
@@ -326,7 +325,7 @@ static av_cold int gif_decode_close(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec gif_decoder = {
+AVCodec ff_gif_decoder = {
     "gif",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_GIF,
diff --git a/libavcodec/golomb.c b/libavcodec/golomb.c
index 611598c..550c41e 100644
--- a/libavcodec/golomb.c
+++ b/libavcodec/golomb.c
@@ -2,20 +2,20 @@
  * exp golomb vlc stuff
  * Copyright (c) 2003 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -29,7 +29,7 @@
 #include "libavutil/common.h"
 
 const uint8_t ff_golomb_vlc_len[512]={
-14,13,12,12,11,11,11,11,10,10,10,10,10,10,10,10,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
+19,17,15,15,13,13,13,13,11,11,11,11,11,11,11,11,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
@@ -48,7 +48,7 @@ const uint8_t ff_golomb_vlc_len[512]={
 };
 
 const uint8_t ff_ue_golomb_vlc_code[512]={
-31,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,
+32,32,32,32,32,32,32,32,31,32,32,32,32,32,32,32,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,
  7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,14,
  3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
@@ -67,7 +67,7 @@ const uint8_t ff_ue_golomb_vlc_code[512]={
 };
 
 const int8_t ff_se_golomb_vlc_code[512]={
- 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,  8, -8,  9, -9, 10,-10, 11,-11, 12,-12, 13,-13, 14,-14, 15,-15,
+ 17, 17, 17, 17, 17, 17, 17, 17, 16, 17, 17, 17, 17, 17, 17, 17,  8, -8,  9, -9, 10,-10, 11,-11, 12,-12, 13,-13, 14,-14, 15,-15,
   4,  4,  4,  4, -4, -4, -4, -4,  5,  5,  5,  5, -5, -5, -5, -5,  6,  6,  6,  6, -6, -6, -6, -6,  7,  7,  7,  7, -7, -7, -7, -7,
   2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
   3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3,
diff --git a/libavcodec/golomb.h b/libavcodec/golomb.h
index 90eeb30..83d277f 100644
--- a/libavcodec/golomb.h
+++ b/libavcodec/golomb.h
@@ -3,20 +3,20 @@
  * Copyright (c) 2003 Michael Niedermayer <michaelni at gmx.at>
  * Copyright (c) 2004 Alex Beregszaszi
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/gsmdec.c b/libavcodec/gsmdec.c
new file mode 100644
index 0000000..693febd
--- /dev/null
+++ b/libavcodec/gsmdec.c
@@ -0,0 +1,109 @@
+/*
+ * gsm 06.10 decoder
+ * Copyright (c) 2010 Reimar Döffinger <Reimar.Doeffinger at gmx.de>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * GSM decoder
+ */
+
+#include "avcodec.h"
+#include "get_bits.h"
+#include "msgsmdec.h"
+
+#include "gsmdec_template.c"
+
+static av_cold int gsm_init(AVCodecContext *avctx)
+{
+    avctx->channels = 1;
+    if (!avctx->sample_rate)
+        avctx->sample_rate = 8000;
+    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
+
+    switch (avctx->codec_id) {
+    case CODEC_ID_GSM:
+        avctx->frame_size  = GSM_FRAME_SIZE;
+        avctx->block_align = GSM_BLOCK_SIZE;
+        break;
+    case CODEC_ID_GSM_MS:
+        avctx->frame_size  = 2 * GSM_FRAME_SIZE;
+        avctx->block_align = GSM_MS_BLOCK_SIZE;
+    }
+
+    return 0;
+}
+
+static int gsm_decode_frame(AVCodecContext *avctx, void *data,
+                            int *data_size, AVPacket *avpkt)
+{
+    int res;
+    GetBitContext gb;
+    const uint8_t *buf = avpkt->data;
+    int buf_size = avpkt->size;
+    int16_t *samples = data;
+    int frame_bytes = 2 * avctx->frame_size;
+
+    if (*data_size < frame_bytes)
+        return -1;
+    *data_size = 0;
+    if(buf_size < avctx->block_align)
+        return AVERROR_INVALIDDATA;
+
+    switch (avctx->codec_id) {
+    case CODEC_ID_GSM:
+        init_get_bits(&gb, buf, buf_size * 8);
+        if (get_bits(&gb, 4) != 0xd)
+            av_log(avctx, AV_LOG_WARNING, "Missing GSM magic!\n");
+        res = gsm_decode_block(avctx, samples, &gb);
+        if (res < 0)
+            return res;
+        break;
+    case CODEC_ID_GSM_MS:
+        res = ff_msgsm_decode_block(avctx, samples, buf);
+        if (res < 0)
+            return res;
+    }
+    *data_size = frame_bytes;
+    return avctx->block_align;
+}
+
+AVCodec ff_gsm_decoder = {
+    "gsm",
+    AVMEDIA_TYPE_AUDIO,
+    CODEC_ID_GSM,
+    sizeof(GSMContext),
+    gsm_init,
+    NULL,
+    NULL,
+    gsm_decode_frame,
+    .long_name = NULL_IF_CONFIG_SMALL("GSM"),
+};
+
+AVCodec ff_gsm_ms_decoder = {
+    "gsm_ms",
+    AVMEDIA_TYPE_AUDIO,
+    CODEC_ID_GSM_MS,
+    sizeof(GSMContext),
+    gsm_init,
+    NULL,
+    NULL,
+    gsm_decode_frame,
+    .long_name = NULL_IF_CONFIG_SMALL("GSM Microsoft variant"),
+};
diff --git a/libavcodec/gsmdec_data.c b/libavcodec/gsmdec_data.c
new file mode 100644
index 0000000..8b75bb6
--- /dev/null
+++ b/libavcodec/gsmdec_data.c
@@ -0,0 +1,94 @@
+/*
+ * gsm 06.10 decoder data
+ * Copyright (c) 2010 Reimar Döffinger <Reimar.Doeffinger at gmx.de>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <stdint.h>
+#include "gsmdec_data.h"
+
+const uint16_t ff_gsm_long_term_gain_tab[4] = {
+    3277, 11469, 21299, 32767
+};
+
+const int16_t ff_gsm_dequant_tab[64][8] = {
+    {   -28,    -20,    -12,     -4,      4,     12,     20,     28},
+    {   -56,    -40,    -24,     -8,      8,     24,     40,     56},
+    {   -84,    -60,    -36,    -12,     12,     36,     60,     84},
+    {  -112,    -80,    -48,    -16,     16,     48,     80,    112},
+    {  -140,   -100,    -60,    -20,     20,     60,    100,    140},
+    {  -168,   -120,    -72,    -24,     24,     72,    120,    168},
+    {  -196,   -140,    -84,    -28,     28,     84,    140,    196},
+    {  -224,   -160,    -96,    -32,     32,     96,    160,    224},
+    {  -252,   -180,   -108,    -36,     36,    108,    180,    252},
+    {  -280,   -200,   -120,    -40,     40,    120,    200,    280},
+    {  -308,   -220,   -132,    -44,     44,    132,    220,    308},
+    {  -336,   -240,   -144,    -48,     48,    144,    240,    336},
+    {  -364,   -260,   -156,    -52,     52,    156,    260,    364},
+    {  -392,   -280,   -168,    -56,     56,    168,    280,    392},
+    {  -420,   -300,   -180,    -60,     60,    180,    300,    420},
+    {  -448,   -320,   -192,    -64,     64,    192,    320,    448},
+    {  -504,   -360,   -216,    -72,     72,    216,    360,    504},
+    {  -560,   -400,   -240,    -80,     80,    240,    400,    560},
+    {  -616,   -440,   -264,    -88,     88,    264,    440,    616},
+    {  -672,   -480,   -288,    -96,     96,    288,    480,    672},
+    {  -728,   -520,   -312,   -104,    104,    312,    520,    728},
+    {  -784,   -560,   -336,   -112,    112,    336,    560,    784},
+    {  -840,   -600,   -360,   -120,    120,    360,    600,    840},
+    {  -896,   -640,   -384,   -128,    128,    384,    640,    896},
+    { -1008,   -720,   -432,   -144,    144,    432,    720,   1008},
+    { -1120,   -800,   -480,   -160,    160,    480,    800,   1120},
+    { -1232,   -880,   -528,   -176,    176,    528,    880,   1232},
+    { -1344,   -960,   -576,   -192,    192,    576,    960,   1344},
+    { -1456,  -1040,   -624,   -208,    208,    624,   1040,   1456},
+    { -1568,  -1120,   -672,   -224,    224,    672,   1120,   1568},
+    { -1680,  -1200,   -720,   -240,    240,    720,   1200,   1680},
+    { -1792,  -1280,   -768,   -256,    256,    768,   1280,   1792},
+    { -2016,  -1440,   -864,   -288,    288,    864,   1440,   2016},
+    { -2240,  -1600,   -960,   -320,    320,    960,   1600,   2240},
+    { -2464,  -1760,  -1056,   -352,    352,   1056,   1760,   2464},
+    { -2688,  -1920,  -1152,   -384,    384,   1152,   1920,   2688},
+    { -2912,  -2080,  -1248,   -416,    416,   1248,   2080,   2912},
+    { -3136,  -2240,  -1344,   -448,    448,   1344,   2240,   3136},
+    { -3360,  -2400,  -1440,   -480,    480,   1440,   2400,   3360},
+    { -3584,  -2560,  -1536,   -512,    512,   1536,   2560,   3584},
+    { -4032,  -2880,  -1728,   -576,    576,   1728,   2880,   4032},
+    { -4480,  -3200,  -1920,   -640,    640,   1920,   3200,   4480},
+    { -4928,  -3520,  -2112,   -704,    704,   2112,   3520,   4928},
+    { -5376,  -3840,  -2304,   -768,    768,   2304,   3840,   5376},
+    { -5824,  -4160,  -2496,   -832,    832,   2496,   4160,   5824},
+    { -6272,  -4480,  -2688,   -896,    896,   2688,   4480,   6272},
+    { -6720,  -4800,  -2880,   -960,    960,   2880,   4800,   6720},
+    { -7168,  -5120,  -3072,  -1024,   1024,   3072,   5120,   7168},
+    { -8063,  -5759,  -3456,  -1152,   1152,   3456,   5760,   8064},
+    { -8959,  -6399,  -3840,  -1280,   1280,   3840,   6400,   8960},
+    { -9855,  -7039,  -4224,  -1408,   1408,   4224,   7040,   9856},
+    {-10751,  -7679,  -4608,  -1536,   1536,   4608,   7680,  10752},
+    {-11647,  -8319,  -4992,  -1664,   1664,   4992,   8320,  11648},
+    {-12543,  -8959,  -5376,  -1792,   1792,   5376,   8960,  12544},
+    {-13439,  -9599,  -5760,  -1920,   1920,   5760,   9600,  13440},
+    {-14335, -10239,  -6144,  -2048,   2048,   6144,  10240,  14336},
+    {-16127, -11519,  -6912,  -2304,   2304,   6912,  11519,  16127},
+    {-17919, -12799,  -7680,  -2560,   2560,   7680,  12799,  17919},
+    {-19711, -14079,  -8448,  -2816,   2816,   8448,  14079,  19711},
+    {-21503, -15359,  -9216,  -3072,   3072,   9216,  15359,  21503},
+    {-23295, -16639,  -9984,  -3328,   3328,   9984,  16639,  23295},
+    {-25087, -17919, -10752,  -3584,   3584,  10752,  17919,  25087},
+    {-26879, -19199, -11520,  -3840,   3840,  11520,  19199,  26879},
+    {-28671, -20479, -12288,  -4096,   4096,  12288,  20479,  28671}
+};
diff --git a/libavcodec/gsmdec_data.h b/libavcodec/gsmdec_data.h
new file mode 100644
index 0000000..32cd01e
--- /dev/null
+++ b/libavcodec/gsmdec_data.h
@@ -0,0 +1,47 @@
+/*
+ * gsm 06.10 decoder data
+ * Copyright (c) 2010 Reimar Döffinger <Reimar.Doeffinger at gmx.de>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef GSMDEC_DATA
+#define GSMDEC_DATA
+
+#include <stdint.h>
+
+// input and output sizes in byte
+#define GSM_BLOCK_SIZE    33
+#define GSM_MS_BLOCK_SIZE 65
+#define GSM_FRAME_SIZE   160
+
+typedef struct {
+    // Contains first 120 elements from the previous frame
+    // (used by long_term_synth according to the "lag"),
+    // then in the following 160 elements the current
+    // frame is constructed.
+    int16_t ref_buf[280];
+    int v[9];
+    int lar[2][8];
+    int lar_idx;
+    int msr;
+} GSMContext;
+
+extern const uint16_t ff_gsm_long_term_gain_tab[4];
+extern const int16_t ff_gsm_dequant_tab[64][8];
+
+#endif
diff --git a/libavcodec/gsmdec_template.c b/libavcodec/gsmdec_template.c
new file mode 100644
index 0000000..7e57c71
--- /dev/null
+++ b/libavcodec/gsmdec_template.c
@@ -0,0 +1,150 @@
+/*
+ * gsm 06.10 decoder
+ * Copyright (c) 2010 Reimar Döffinger <Reimar.Doeffinger at gmx.de>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * GSM decoder
+ */
+
+#include "get_bits.h"
+#include "gsmdec_data.h"
+
+static void apcm_dequant_add(GetBitContext *gb, int16_t *dst)
+{
+    int i;
+    int maxidx = get_bits(gb, 6);
+    const int16_t *tab = ff_gsm_dequant_tab[maxidx];
+    for (i = 0; i < 13; i++)
+        dst[3*i] += tab[get_bits(gb, 3)];
+}
+
+static inline int gsm_mult(int a, int b)
+{
+    return (a * b + (1 << 14)) >> 15;
+}
+
+static void long_term_synth(int16_t *dst, int lag, int gain_idx)
+{
+    int i;
+    const int16_t *src = dst - lag;
+    uint16_t gain = ff_gsm_long_term_gain_tab[gain_idx];
+    for (i = 0; i < 40; i++)
+        dst[i] = gsm_mult(gain, src[i]);
+}
+
+static inline int decode_log_area(int coded, int factor, int offset)
+{
+    coded <<= 10;
+    coded -= offset;
+    return gsm_mult(coded, factor) << 1;
+}
+
+static av_noinline int get_rrp(int filtered)
+{
+    int abs = FFABS(filtered);
+    if      (abs < 11059) abs <<= 1;
+    else if (abs < 20070) abs += 11059;
+    else                  abs = (abs >> 2) + 26112;
+    return filtered < 0 ? -abs : abs;
+}
+
+static int filter_value(int in, int rrp[8], int v[9])
+{
+    int i;
+    for (i = 7; i >= 0; i--) {
+        in -= gsm_mult(rrp[i], v[i]);
+        v[i + 1] = v[i] + gsm_mult(rrp[i], in);
+    }
+    v[0] = in;
+    return in;
+}
+
+static void short_term_synth(GSMContext *ctx, int16_t *dst, const int16_t *src)
+{
+    int i;
+    int rrp[8];
+    int *lar = ctx->lar[ctx->lar_idx];
+    int *lar_prev = ctx->lar[ctx->lar_idx ^ 1];
+    for (i = 0; i < 8; i++)
+        rrp[i] = get_rrp((lar_prev[i] >> 2) + (lar_prev[i] >> 1) + (lar[i] >> 2));
+    for (i = 0; i < 13; i++)
+        dst[i] = filter_value(src[i], rrp, ctx->v);
+
+    for (i = 0; i < 8; i++)
+        rrp[i] = get_rrp((lar_prev[i] >> 1) + (lar     [i] >> 1));
+    for (i = 13; i < 27; i++)
+        dst[i] = filter_value(src[i], rrp, ctx->v);
+
+    for (i = 0; i < 8; i++)
+        rrp[i] = get_rrp((lar_prev[i] >> 2) + (lar     [i] >> 1) + (lar[i] >> 2));
+    for (i = 27; i < 40; i++)
+        dst[i] = filter_value(src[i], rrp, ctx->v);
+
+    for (i = 0; i < 8; i++)
+        rrp[i] = get_rrp(lar[i]);
+    for (i = 40; i < 160; i++)
+        dst[i] = filter_value(src[i], rrp, ctx->v);
+
+    ctx->lar_idx ^= 1;
+}
+
+static int postprocess(int16_t *data, int msr)
+{
+    int i;
+    for (i = 0; i < 160; i++) {
+        msr = av_clip_int16(data[i] + gsm_mult(msr, 28180));
+        data[i] = av_clip_int16(msr << 1) & ~7;
+    }
+    return msr;
+}
+
+static int gsm_decode_block(AVCodecContext *avctx, int16_t *samples,
+                            GetBitContext *gb)
+{
+    GSMContext *ctx = avctx->priv_data;
+    int i;
+    int16_t *ref_dst = ctx->ref_buf + 120;
+    int *lar = ctx->lar[ctx->lar_idx];
+    lar[0] = decode_log_area(get_bits(gb, 6), 13107,  1 << 15);
+    lar[1] = decode_log_area(get_bits(gb, 6), 13107,  1 << 15);
+    lar[2] = decode_log_area(get_bits(gb, 5), 13107, (1 << 14) + 2048*2);
+    lar[3] = decode_log_area(get_bits(gb, 5), 13107, (1 << 14) - 2560*2);
+    lar[4] = decode_log_area(get_bits(gb, 4), 19223, (1 << 13) +   94*2);
+    lar[5] = decode_log_area(get_bits(gb, 4), 17476, (1 << 13) - 1792*2);
+    lar[6] = decode_log_area(get_bits(gb, 3), 31454, (1 << 12) -  341*2);
+    lar[7] = decode_log_area(get_bits(gb, 3), 29708, (1 << 12) - 1144*2);
+
+    for (i = 0; i < 4; i++) {
+        int lag      = get_bits(gb, 7);
+        int gain_idx = get_bits(gb, 2);
+        int offset   = get_bits(gb, 2);
+        lag = av_clip(lag, 40, 120);
+        long_term_synth(ref_dst, lag, gain_idx);
+        apcm_dequant_add(gb, ref_dst + offset);
+        ref_dst += 40;
+    }
+    memcpy(ctx->ref_buf, ctx->ref_buf + 160, 120 * sizeof(*ctx->ref_buf));
+    short_term_synth(ctx, samples, ctx->ref_buf + 120);
+    // for optimal speed this could be merged with short_term_synth,
+    // not done yet because it is a bit ugly
+    ctx->msr = postprocess(samples, ctx->msr);
+    return 0;
+}
diff --git a/libavcodec/h261.c b/libavcodec/h261.c
index 562a151..eab3640 100644
--- a/libavcodec/h261.c
+++ b/libavcodec/h261.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni at gmx.at>
  * Copyright (c) 2004 Maarten Daniels
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/h261.h b/libavcodec/h261.h
index 5b60dd6..6461329 100644
--- a/libavcodec/h261.h
+++ b/libavcodec/h261.h
@@ -3,20 +3,20 @@
  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni at gmx.at>
  * Copyright (c) 2004 Maarten Daniels
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/h261_parser.c b/libavcodec/h261_parser.c
index c32300d..20c2862 100644
--- a/libavcodec/h261_parser.c
+++ b/libavcodec/h261_parser.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni at gmx.at>
  * Copyright (c) 2004 Maarten Daniels
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -81,7 +81,7 @@ static int h261_parse(AVCodecParserContext *s,
     return next;
 }
 
-AVCodecParser h261_parser = {
+AVCodecParser ff_h261_parser = {
     { CODEC_ID_H261 },
     sizeof(ParseContext),
     NULL,
diff --git a/libavcodec/h261data.h b/libavcodec/h261data.h
index 82bae16..2c61015 100644
--- a/libavcodec/h261data.h
+++ b/libavcodec/h261data.h
@@ -2,20 +2,20 @@
  * copyright (c) 2002-2004 Michael Niedermayer <michaelni at gmx.at>
  * copyright (c) 2004 Maarten Daniels
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/h261dec.c b/libavcodec/h261dec.c
index bb5f27d..93c5cb4 100644
--- a/libavcodec/h261dec.c
+++ b/libavcodec/h261dec.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni at gmx.at>
  * Copyright (c) 2004 Maarten Daniels
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -553,8 +553,8 @@ static int h261_decode_frame(AVCodecContext *avctx,
     int ret;
     AVFrame *pict = data;
 
-    dprintf(avctx, "*****frame %d size=%d\n", avctx->frame_number, buf_size);
-    dprintf(avctx, "bytes=%x %x %x %x\n", buf[0], buf[1], buf[2], buf[3]);
+    av_dlog(avctx, "*****frame %d size=%d\n", avctx->frame_number, buf_size);
+    av_dlog(avctx, "bytes=%x %x %x %x\n", buf[0], buf[1], buf[2], buf[3]);
     s->flags= avctx->flags;
     s->flags2= avctx->flags2;
 
@@ -595,12 +595,14 @@ retry:
         goto retry;
     }
 
-    // for hurry_up==5
+    // for skipping the frame
     s->current_picture.pict_type= s->pict_type;
     s->current_picture.key_frame= s->pict_type == FF_I_TYPE;
 
+#if FF_API_HURRY_UP
     /* skip everything if we are in a hurry>=5 */
     if(avctx->hurry_up>=5) return get_consumed_bytes(s, buf_size);
+#endif
     if(  (avctx->skip_frame >= AVDISCARD_NONREF && s->pict_type==FF_B_TYPE)
        ||(avctx->skip_frame >= AVDISCARD_NONKEY && s->pict_type!=FF_I_TYPE)
        || avctx->skip_frame >= AVDISCARD_ALL)
@@ -641,7 +643,7 @@ static av_cold int h261_decode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec h261_decoder = {
+AVCodec ff_h261_decoder = {
     "h261",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_H261,
@@ -651,5 +653,6 @@ AVCodec h261_decoder = {
     h261_decode_end,
     h261_decode_frame,
     CODEC_CAP_DR1,
+    .max_lowres = 3,
     .long_name = NULL_IF_CONFIG_SMALL("H.261"),
 };
diff --git a/libavcodec/h261enc.c b/libavcodec/h261enc.c
index d3f2219..27746d5 100644
--- a/libavcodec/h261enc.c
+++ b/libavcodec/h261enc.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni at gmx.at>
  * Copyright (c) 2004 Maarten Daniels
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -84,7 +84,7 @@ void ff_h261_encode_picture_header(MpegEncContext * s, int picture_number){
 }
 
 /**
- * Encodes a group of blocks header.
+ * Encode a group of blocks header.
  */
 static void h261_encode_gob_header(MpegEncContext * s, int mb_line){
     H261Context * h = (H261Context *)s;
@@ -321,7 +321,7 @@ static void h261_encode_block(H261Context * h, DCTELEM * block, int n){
     }
 }
 
-AVCodec h261_encoder = {
+AVCodec ff_h261_encoder = {
     "h261",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_H261,
diff --git a/libavcodec/h263.c b/libavcodec/h263.c
index 50ea6ce..d816a59 100644
--- a/libavcodec/h263.c
+++ b/libavcodec/h263.c
@@ -5,20 +5,20 @@
  * Copyright (c) 2001 Juan J. Sierralta P
  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/h263.h b/libavcodec/h263.h
index 678588a..cdbe44e 100644
--- a/libavcodec/h263.h
+++ b/libavcodec/h263.h
@@ -1,20 +1,20 @@
 /*
  * H263 internal header
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #ifndef AVCODEC_H263_H
@@ -93,7 +93,7 @@ void h263_pred_acdc(MpegEncContext * s, DCTELEM *block, int n);
 
 
 /**
- * Prints picture info if FF_DEBUG_PICT_INFO is set.
+ * Print picture info if FF_DEBUG_PICT_INFO is set.
  */
 void ff_h263_show_pict_info(MpegEncContext *s);
 
@@ -102,8 +102,8 @@ int ff_h263_decode_mb(MpegEncContext *s,
                       DCTELEM block[6][64]);
 
 /**
- * Returns the value of the 3bit "source format" syntax element.
- * that represents some standard picture dimensions or indicates that
+ * Return the value of the 3bit "source format" syntax element.
+ * This represents some standard picture dimensions or indicates that
  * width&height are explicitly stored later.
  */
 int av_const h263_get_picture_format(int width, int height);
diff --git a/libavcodec/h263_parser.c b/libavcodec/h263_parser.c
index 16c5ea5..4b9fc11 100644
--- a/libavcodec/h263_parser.c
+++ b/libavcodec/h263_parser.c
@@ -2,20 +2,20 @@
  * H.263 parser
  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -83,7 +83,7 @@ static int h263_parse(AVCodecParserContext *s,
     return next;
 }
 
-AVCodecParser h263_parser = {
+AVCodecParser ff_h263_parser = {
     { CODEC_ID_H263 },
     sizeof(ParseContext),
     NULL,
diff --git a/libavcodec/h263_parser.h b/libavcodec/h263_parser.h
index 565a222..5bd715f 100644
--- a/libavcodec/h263_parser.h
+++ b/libavcodec/h263_parser.h
@@ -2,20 +2,20 @@
  * H.263 parser
  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/h263data.h b/libavcodec/h263data.h
index 81e3ddd..966da56 100644
--- a/libavcodec/h263data.h
+++ b/libavcodec/h263data.h
@@ -4,20 +4,20 @@
  * copyright (c) 2001 Juan J. Sierralta P
  * copyright (c) 2002-2004 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/h263dec.c b/libavcodec/h263dec.c
index c80cfcf..86ad0ba 100644
--- a/libavcodec/h263dec.c
+++ b/libavcodec/h263dec.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2001 Fabrice Bellard
  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,6 +25,7 @@
  * H.263 decoder.
  */
 
+#include "libavutil/cpu.h"
 #include "internal.h"
 #include "avcodec.h"
 #include "dsputil.h"
@@ -260,6 +261,13 @@ static int decode_slice(MpegEncContext *s){
 
     assert(s->mb_x==0 && s->mb_y==s->mb_height);
 
+    if(s->codec_id==CODEC_ID_MPEG4
+       && (s->workaround_bugs&FF_BUG_AUTODETECT)
+       && get_bits_left(&s->gb) >= 48
+       && show_bits(&s->gb, 24)==0x4010
+       && !s->data_partitioning)
+        s->padding_bug_score+=32;
+
     /* try to detect the padding bug */
     if(      s->codec_id==CODEC_ID_MPEG4
        &&   (s->workaround_bugs&FF_BUG_AUTODETECT)
@@ -553,7 +561,7 @@ retry:
 #endif
 
 #if HAVE_MMX
-    if(s->codec_id == CODEC_ID_MPEG4 && s->xvid_build>=0 && avctx->idct_algo == FF_IDCT_AUTO && (mm_flags & FF_MM_MMX)){
+    if (s->codec_id == CODEC_ID_MPEG4 && s->xvid_build>=0 && avctx->idct_algo == FF_IDCT_AUTO && (av_get_cpu_flags() & AV_CPU_FLAG_MMX)) {
         avctx->idct_algo= FF_IDCT_XVIDMMX;
         avctx->coded_width= 0; // force reinit
 //        dsputil_init(&s->dsp, avctx);
@@ -583,20 +591,24 @@ retry:
     if((s->codec_id==CODEC_ID_H263 || s->codec_id==CODEC_ID_H263P || s->codec_id == CODEC_ID_H263I))
         s->gob_index = ff_h263_get_gob_height(s);
 
-    // for hurry_up==5
+    // for skipping the frame
     s->current_picture.pict_type= s->pict_type;
     s->current_picture.key_frame= s->pict_type == FF_I_TYPE;
 
     /* skip B-frames if we don't have reference frames */
     if(s->last_picture_ptr==NULL && (s->pict_type==FF_B_TYPE || s->dropable)) return get_consumed_bytes(s, buf_size);
+#if FF_API_HURRY_UP
     /* skip b frames if we are in a hurry */
     if(avctx->hurry_up && s->pict_type==FF_B_TYPE) return get_consumed_bytes(s, buf_size);
+#endif
     if(   (avctx->skip_frame >= AVDISCARD_NONREF && s->pict_type==FF_B_TYPE)
        || (avctx->skip_frame >= AVDISCARD_NONKEY && s->pict_type!=FF_I_TYPE)
        ||  avctx->skip_frame >= AVDISCARD_ALL)
         return get_consumed_bytes(s, buf_size);
+#if FF_API_HURRY_UP
     /* skip everything if we are in a hurry>=5 */
     if(avctx->hurry_up>=5) return get_consumed_bytes(s, buf_size);
+#endif
 
     if(s->next_p_frame_damaged){
         if(s->pict_type==FF_B_TYPE)
@@ -727,7 +739,7 @@ av_log(avctx, AV_LOG_DEBUG, "%"PRId64"\n", rdtsc()-time);
     return get_consumed_bytes(s, buf_size);
 }
 
-AVCodec h263_decoder = {
+AVCodec ff_h263_decoder = {
     "h263",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_H263,
@@ -738,6 +750,7 @@ AVCodec h263_decoder = {
     ff_h263_decode_frame,
     CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY,
     .flush= ff_mpeg_flush,
+    .max_lowres= 3,
     .long_name= NULL_IF_CONFIG_SMALL("H.263 / H.263-1996, H.263+ / H.263-1998 / H.263 version 2"),
     .pix_fmts= ff_hwaccel_pixfmt_list_420,
 };
diff --git a/libavcodec/h264.c b/libavcodec/h264.c
index e4654f0..dbf71a7 100644
--- a/libavcodec/h264.c
+++ b/libavcodec/h264.c
@@ -1,21 +1,21 @@
 /*
- * H.26L/H.264/AVC/JVT/14496-10/... encoder/decoder
+ * H.26L/H.264/AVC/JVT/14496-10/... decoder
  * Copyright (c) 2003 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,6 +25,7 @@
  * @author Michael Niedermayer <michaelni at gmx.at>
  */
 
+#include "libavutil/imgutils.h"
 #include "internal.h"
 #include "dsputil.h"
 #include "avcodec.h"
@@ -32,11 +33,11 @@
 #include "h264.h"
 #include "h264data.h"
 #include "h264_mvpred.h"
-#include "h264_parser.h"
 #include "golomb.h"
 #include "mathops.h"
 #include "rectangle.h"
 #include "vdpau_internal.h"
+#include "libavutil/avassert.h"
 
 #include "cabac.h"
 
@@ -51,6 +52,13 @@ static const uint8_t div6[52]={
 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
 };
 
+static const enum PixelFormat hwaccel_pixfmt_list_h264_jpeg_420[] = {
+    PIX_FMT_DXVA2_VLD,
+    PIX_FMT_VAAPI_VLD,
+    PIX_FMT_YUVJ420P,
+    PIX_FMT_NONE
+};
+
 void ff_h264_write_back_intra_pred_mode(H264Context *h){
     int8_t *mode= h->intra4x4_pred_mode + h->mb2br_xy[h->mb_xy];
 
@@ -224,7 +232,11 @@ nsc:
     return dst;
 }
 
-int ff_h264_decode_rbsp_trailing(H264Context *h, const uint8_t *src){
+/**
+ * Identify the exact end of the bitstream
+ * @return the length of the trailing, or 0 if damaged
+ */
+static int ff_h264_decode_rbsp_trailing(H264Context *h, const uint8_t *src){
     int v= *src;
     int r;
 
@@ -237,46 +249,6 @@ int ff_h264_decode_rbsp_trailing(H264Context *h, const uint8_t *src){
     return 0;
 }
 
-/**
- * IDCT transforms the 16 dc values and dequantizes them.
- * @param qp quantization parameter
- */
-static void h264_luma_dc_dequant_idct_c(DCTELEM *block, int qp, int qmul){
-#define stride 16
-    int i;
-    int temp[16]; //FIXME check if this is a good idea
-    static const int x_offset[4]={0, 1*stride, 4* stride,  5*stride};
-    static const int y_offset[4]={0, 2*stride, 8* stride, 10*stride};
-
-//memset(block, 64, 2*256);
-//return;
-    for(i=0; i<4; i++){
-        const int offset= y_offset[i];
-        const int z0= block[offset+stride*0] + block[offset+stride*4];
-        const int z1= block[offset+stride*0] - block[offset+stride*4];
-        const int z2= block[offset+stride*1] - block[offset+stride*5];
-        const int z3= block[offset+stride*1] + block[offset+stride*5];
-
-        temp[4*i+0]= z0+z3;
-        temp[4*i+1]= z1+z2;
-        temp[4*i+2]= z1-z2;
-        temp[4*i+3]= z0-z3;
-    }
-
-    for(i=0; i<4; i++){
-        const int offset= x_offset[i];
-        const int z0= temp[4*0+i] + temp[4*2+i];
-        const int z1= temp[4*0+i] - temp[4*2+i];
-        const int z2= temp[4*1+i] - temp[4*3+i];
-        const int z3= temp[4*1+i] + temp[4*3+i];
-
-        block[stride*0 +offset]= ((((z0 + z3)*qmul + 128 ) >> 8)); //FIXME think about merging this into decode_residual
-        block[stride*2 +offset]= ((((z1 + z2)*qmul + 128 ) >> 8));
-        block[stride*8 +offset]= ((((z1 - z2)*qmul + 128 ) >> 8));
-        block[stride*10+offset]= ((((z0 - z3)*qmul + 128 ) >> 8));
-    }
-}
-
 #if 0
 /**
  * DCT transforms the 16 dc values.
@@ -320,7 +292,7 @@ static void h264_luma_dc_dct_c(DCTELEM *block/*, int qp*/){
 #undef xStride
 #undef stride
 
-static void chroma_dc_dequant_idct_c(DCTELEM *block, int qp, int qmul){
+static void chroma_dc_dequant_idct_c(DCTELEM *block, int qmul){
     const int stride= 16*2;
     const int xStride= 16;
     int a,b,c,d,e;
@@ -389,7 +361,7 @@ static inline void mc_dir_part(H264Context *h, Picture *pic, int n, int square,
        || full_my < 0-extra_height
        || full_mx + 16/*FIXME*/ > pic_width + extra_width
        || full_my + 16/*FIXME*/ > pic_height + extra_height){
-        ff_emulated_edge_mc(s->edge_emu_buffer, src_y - 2 - 2*h->mb_linesize, h->mb_linesize, 16+5, 16+5/*FIXME*/, full_mx-2, full_my-2, pic_width, pic_height);
+        s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_y - 2 - 2*h->mb_linesize, h->mb_linesize, 16+5, 16+5/*FIXME*/, full_mx-2, full_my-2, pic_width, pic_height);
             src_y= s->edge_emu_buffer + 2 + 2*h->mb_linesize;
         emu=1;
     }
@@ -410,13 +382,13 @@ static inline void mc_dir_part(H264Context *h, Picture *pic, int n, int square,
     src_cr= pic->data[2] + (mx>>3) + (my>>3)*h->mb_uvlinesize;
 
     if(emu){
-        ff_emulated_edge_mc(s->edge_emu_buffer, src_cb, h->mb_uvlinesize, 9, 9/*FIXME*/, (mx>>3), (my>>3), pic_width>>1, pic_height>>1);
+        s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cb, h->mb_uvlinesize, 9, 9/*FIXME*/, (mx>>3), (my>>3), pic_width>>1, pic_height>>1);
             src_cb= s->edge_emu_buffer;
     }
     chroma_op(dest_cb, src_cb, h->mb_uvlinesize, chroma_height, mx&7, my&7);
 
     if(emu){
-        ff_emulated_edge_mc(s->edge_emu_buffer, src_cr, h->mb_uvlinesize, 9, 9/*FIXME*/, (mx>>3), (my>>3), pic_width>>1, pic_height>>1);
+        s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cr, h->mb_uvlinesize, 9, 9/*FIXME*/, (mx>>3), (my>>3), pic_width>>1, pic_height>>1);
             src_cr= s->edge_emu_buffer;
     }
     chroma_op(dest_cr, src_cr, h->mb_uvlinesize, chroma_height, mx&7, my&7);
@@ -645,7 +617,7 @@ static void hl_motion(H264Context *h, uint8_t *dest_y, uint8_t *dest_cb, uint8_t
 }
 
 
-static void free_tables(H264Context *h){
+static void free_tables(H264Context *h, int free_rbsp){
     int i;
     H264Context *hx;
     av_freep(&h->intra4x4_pred_mode);
@@ -668,17 +640,18 @@ static void free_tables(H264Context *h){
         av_freep(&hx->top_borders[1]);
         av_freep(&hx->top_borders[0]);
         av_freep(&hx->s.obmc_scratchpad);
-        av_freep(&hx->rbsp_buffer[1]);
-        av_freep(&hx->rbsp_buffer[0]);
-        hx->rbsp_buffer_size[0] = 0;
-        hx->rbsp_buffer_size[1] = 0;
+        if (free_rbsp){
+            av_freep(&hx->rbsp_buffer[1]);
+            av_freep(&hx->rbsp_buffer[0]);
+            hx->rbsp_buffer_size[0] = 0;
+            hx->rbsp_buffer_size[1] = 0;
+        }
         if (i) av_freep(&h->thread_context[i]);
     }
 }
 
 static void init_dequant8_coeff_table(H264Context *h){
     int i,q,x;
-    const int transpose = (h->h264dsp.h264_idct8_add != ff_h264_idct8_add_c); //FIXME ugly
     h->dequant8_coeff[0] = h->dequant8_buffer[0];
     h->dequant8_coeff[1] = h->dequant8_buffer[1];
 
@@ -692,7 +665,7 @@ static void init_dequant8_coeff_table(H264Context *h){
             int shift = div6[q];
             int idx = rem6[q];
             for(x=0; x<64; x++)
-                h->dequant8_coeff[i][q][transpose ? (x>>3)|((x&7)<<3) : x] =
+                h->dequant8_coeff[i][q][(x>>3)|((x&7)<<3)] =
                     ((uint32_t)dequant8_coeff_init[idx][ dequant8_coeff_init_scan[((x>>1)&12) | (x&3)] ] *
                     h->pps.scaling_matrix8[i][x]) << shift;
         }
@@ -701,7 +674,6 @@ static void init_dequant8_coeff_table(H264Context *h){
 
 static void init_dequant4_coeff_table(H264Context *h){
     int i,j,q,x;
-    const int transpose = (h->h264dsp.h264_idct_add != ff_h264_idct_add_c); //FIXME ugly
     for(i=0; i<6; i++ ){
         h->dequant4_coeff[i] = h->dequant4_buffer[i];
         for(j=0; j<i; j++){
@@ -717,7 +689,7 @@ static void init_dequant4_coeff_table(H264Context *h){
             int shift = div6[q] + 2;
             int idx = rem6[q];
             for(x=0; x<16; x++)
-                h->dequant4_coeff[i][q][transpose ? (x>>2)|((x<<2)&0xF) : x] =
+                h->dequant4_coeff[i][q][(x>>2)|((x<<2)&0xF)] =
                     ((uint32_t)dequant4_coeff_init[idx][(x&1) + ((x>>2)&1)] *
                     h->pps.scaling_matrix4[i][x]) << shift;
         }
@@ -781,7 +753,7 @@ int ff_h264_alloc_tables(H264Context *h){
 
     return 0;
 fail:
-    free_tables(h);
+    free_tables(h, 1);
     return -1;
 }
 
@@ -844,41 +816,11 @@ static av_cold void common_init(H264Context *h){
     memset(h->pps.scaling_matrix8, 16, 2*64*sizeof(uint8_t));
 }
 
-av_cold int ff_h264_decode_init(AVCodecContext *avctx){
-    H264Context *h= avctx->priv_data;
-    MpegEncContext * const s = &h->s;
-
-    MPV_decode_defaults(s);
-
-    s->avctx = avctx;
-    common_init(h);
-
-    s->out_format = FMT_H264;
-    s->workaround_bugs= avctx->workaround_bugs;
-
-    // set defaults
-//    s->decode_mb= ff_h263_decode_mb;
-    s->quarter_sample = 1;
-    if(!avctx->has_b_frames)
-    s->low_delay= 1;
-
-    avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
-
-    ff_h264_decode_init_vlc();
-
-    h->thread_context[0] = h;
-    h->outputed_poc = INT_MIN;
-    h->prev_poc_msb= 1<<16;
-    h->x264_build = -1;
-    ff_h264_reset_sei(h);
-    if(avctx->codec_id == CODEC_ID_H264){
-        if(avctx->ticks_per_frame == 1){
-            s->avctx->time_base.den *=2;
-        }
-        avctx->ticks_per_frame = 2;
-    }
+int ff_h264_decode_extradata(H264Context *h)
+{
+    AVCodecContext *avctx = h->s.avctx;
 
-    if(avctx->extradata_size > 0 && avctx->extradata && *(char *)avctx->extradata == 1){
+    if(*(char *)avctx->extradata == 1){
         int i, cnt, nalsize;
         unsigned char *p = avctx->extradata;
 
@@ -916,9 +858,50 @@ av_cold int ff_h264_decode_init(AVCodecContext *avctx){
         h->nal_length_size = ((*(((char*)(avctx->extradata))+4))&0x03)+1;
     } else {
         h->is_avc = 0;
-        if(decode_nal_units(h, s->avctx->extradata, s->avctx->extradata_size) < 0)
+        if(decode_nal_units(h, avctx->extradata, avctx->extradata_size) < 0)
             return -1;
     }
+    return 0;
+}
+
+av_cold int ff_h264_decode_init(AVCodecContext *avctx){
+    H264Context *h= avctx->priv_data;
+    MpegEncContext * const s = &h->s;
+
+    MPV_decode_defaults(s);
+
+    s->avctx = avctx;
+    common_init(h);
+
+    s->out_format = FMT_H264;
+    s->workaround_bugs= avctx->workaround_bugs;
+
+    // set defaults
+//    s->decode_mb= ff_h263_decode_mb;
+    s->quarter_sample = 1;
+    if(!avctx->has_b_frames)
+    s->low_delay= 1;
+
+    avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
+
+    ff_h264_decode_init_vlc();
+
+    h->thread_context[0] = h;
+    h->outputed_poc = INT_MIN;
+    h->prev_poc_msb= 1<<16;
+    h->x264_build = -1;
+    ff_h264_reset_sei(h);
+    if(avctx->codec_id == CODEC_ID_H264){
+        if(avctx->ticks_per_frame == 1){
+            s->avctx->time_base.den *=2;
+        }
+        avctx->ticks_per_frame = 2;
+    }
+
+    if(avctx->extradata_size > 0 && avctx->extradata &&
+        ff_h264_decode_extradata(h))
+        return -1;
+
     if(h->sps.bitstream_restriction_flag && s->avctx->has_b_frames < h->sps.num_reorder_frames){
         s->avctx->has_b_frames = h->sps.num_reorder_frames;
         s->low_delay = 0;
@@ -959,7 +942,7 @@ int ff_h264_frame_start(H264Context *h){
     /* can't be in alloc_tables because linesize isn't known there.
      * FIXME: redo bipred weight to not require extra buffer? */
     for(i = 0; i < s->avctx->thread_count; i++)
-        if(!h->thread_context[i]->s.obmc_scratchpad)
+        if(h->thread_context[i] && !h->thread_context[i]->s.obmc_scratchpad)
             h->thread_context[i]->s.obmc_scratchpad = av_malloc(16*2*s->linesize + 8*2*s->uvlinesize);
 
     /* some macroblocks can be accessed before they're available in case of lost slices, mbaff or threading*/
@@ -1226,10 +1209,18 @@ static av_always_inline void hl_decode_mb_internal(H264Context *h, int simple){
             }else{
                 h->hpc.pred16x16[ h->intra16x16_pred_mode ](dest_y , linesize);
                 if(is_h264){
-                    if(!transform_bypass)
-                        h264_luma_dc_dequant_idct_c(h->mb, s->qscale, h->dequant4_coeff[0][s->qscale][0]);
+                    if(h->non_zero_count_cache[ scan8[LUMA_DC_BLOCK_INDEX] ]){
+                        if(!transform_bypass)
+                            h->h264dsp.h264_luma_dc_dequant_idct(h->mb, h->mb_luma_dc, h->dequant4_coeff[0][s->qscale][0]);
+                        else{
+                            static const uint8_t dc_mapping[16] = { 0*16, 1*16, 4*16, 5*16, 2*16, 3*16, 6*16, 7*16,
+                                                                    8*16, 9*16,12*16,13*16,10*16,11*16,14*16,15*16};
+                            for(i = 0; i < 16; i++)
+                                h->mb[dc_mapping[i]] = h->mb_luma_dc[i];
+                        }
+                    }
                 }else
-                    ff_svq3_luma_dc_dequant_idct_c(h->mb, s->qscale);
+                    ff_svq3_luma_dc_dequant_idct_c(h->mb, h->mb_luma_dc, s->qscale);
             }
             if(h->deblocking_filter)
                 xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 0, simple);
@@ -1297,18 +1288,17 @@ static av_always_inline void hl_decode_mb_internal(H264Context *h, int simple){
                     }
                 }
             }else{
-                chroma_dc_dequant_idct_c(h->mb + 16*16, h->chroma_qp[0], h->dequant4_coeff[IS_INTRA(mb_type) ? 1:4][h->chroma_qp[0]][0]);
-                chroma_dc_dequant_idct_c(h->mb + 16*16+4*16, h->chroma_qp[1], h->dequant4_coeff[IS_INTRA(mb_type) ? 2:5][h->chroma_qp[1]][0]);
                 if(is_h264){
-                    idct_add = h->h264dsp.h264_idct_add;
-                    idct_dc_add = h->h264dsp.h264_idct_dc_add;
-                    for(i=16; i<16+8; i++){
-                        if(h->non_zero_count_cache[ scan8[i] ])
-                            idct_add   (dest[(i&4)>>2] + block_offset[i], h->mb + i*16, uvlinesize);
-                        else if(h->mb[i*16])
-                            idct_dc_add(dest[(i&4)>>2] + block_offset[i], h->mb + i*16, uvlinesize);
-                    }
+                    if(h->non_zero_count_cache[ scan8[CHROMA_DC_BLOCK_INDEX+0] ])
+                        chroma_dc_dequant_idct_c(h->mb + 16*16     , h->dequant4_coeff[IS_INTRA(mb_type) ? 1:4][h->chroma_qp[0]][0]);
+                    if(h->non_zero_count_cache[ scan8[CHROMA_DC_BLOCK_INDEX+1] ])
+                        chroma_dc_dequant_idct_c(h->mb + 16*16+4*16, h->dequant4_coeff[IS_INTRA(mb_type) ? 2:5][h->chroma_qp[1]][0]);
+                    h->h264dsp.h264_idct_add8(dest, block_offset,
+                                              h->mb, uvlinesize,
+                                              h->non_zero_count_cache);
                 }else{
+                    chroma_dc_dequant_idct_c(h->mb + 16*16     , h->dequant4_coeff[IS_INTRA(mb_type) ? 1:4][h->chroma_qp[0]][0]);
+                    chroma_dc_dequant_idct_c(h->mb + 16*16+4*16, h->dequant4_coeff[IS_INTRA(mb_type) ? 2:5][h->chroma_qp[1]][0]);
                     for(i=16; i<16+8; i++){
                         if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){
                             uint8_t * const ptr= dest[(i&4)>>2] + block_offset[i];
@@ -1356,7 +1346,8 @@ static int pred_weight_table(H264Context *h){
     h->use_weight= 0;
     h->use_weight_chroma= 0;
     h->luma_log2_weight_denom= get_ue_golomb(&s->gb);
-    h->chroma_log2_weight_denom= get_ue_golomb(&s->gb);
+    if(CHROMA)
+        h->chroma_log2_weight_denom= get_ue_golomb(&s->gb);
     luma_def = 1<<h->luma_log2_weight_denom;
     chroma_def = 1<<h->chroma_log2_weight_denom;
 
@@ -1410,7 +1401,7 @@ static int pred_weight_table(H264Context *h){
 
 /**
  * Initialize implicit_weight table.
- * @param field, 0/1 initialize the weight for interlaced MBAFF
+ * @param field  0/1 initialize the weight for interlaced MBAFF
  *                -1 initializes the rest
  */
 static void implicit_weight_table(H264Context *h, int field){
@@ -1581,31 +1572,19 @@ static int init_poc(H264Context *h){
  */
 static void init_scan_tables(H264Context *h){
     int i;
-    if(h->h264dsp.h264_idct_add == ff_h264_idct_add_c){ //FIXME little ugly
-        memcpy(h->zigzag_scan, zigzag_scan, 16*sizeof(uint8_t));
-        memcpy(h-> field_scan,  field_scan, 16*sizeof(uint8_t));
-    }else{
-        for(i=0; i<16; i++){
+    for(i=0; i<16; i++){
 #define T(x) (x>>2) | ((x<<2) & 0xF)
-            h->zigzag_scan[i] = T(zigzag_scan[i]);
-            h-> field_scan[i] = T( field_scan[i]);
+        h->zigzag_scan[i] = T(zigzag_scan[i]);
+        h-> field_scan[i] = T( field_scan[i]);
 #undef T
-        }
     }
-    if(h->h264dsp.h264_idct8_add == ff_h264_idct8_add_c){
-        memcpy(h->zigzag_scan8x8,       ff_zigzag_direct,     64*sizeof(uint8_t));
-        memcpy(h->zigzag_scan8x8_cavlc, zigzag_scan8x8_cavlc, 64*sizeof(uint8_t));
-        memcpy(h->field_scan8x8,        field_scan8x8,        64*sizeof(uint8_t));
-        memcpy(h->field_scan8x8_cavlc,  field_scan8x8_cavlc,  64*sizeof(uint8_t));
-    }else{
-        for(i=0; i<64; i++){
+    for(i=0; i<64; i++){
 #define T(x) (x>>3) | ((x&7)<<3)
-            h->zigzag_scan8x8[i]       = T(ff_zigzag_direct[i]);
-            h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
-            h->field_scan8x8[i]        = T(field_scan8x8[i]);
-            h->field_scan8x8_cavlc[i]  = T(field_scan8x8_cavlc[i]);
+        h->zigzag_scan8x8[i]       = T(ff_zigzag_direct[i]);
+        h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
+        h->field_scan8x8[i]        = T(field_scan8x8[i]);
+        h->field_scan8x8_cavlc[i]  = T(field_scan8x8_cavlc[i]);
 #undef T
-        }
     }
     if(h->sps.transform_bypass){ //FIXME same ugly
         h->zigzag_scan_q0          = zigzag_scan;
@@ -1672,7 +1651,7 @@ static void field_end(H264Context *h){
 }
 
 /**
- * Replicates H264 "master" context to thread contexts.
+ * Replicate H264 "master" context to thread contexts.
  */
 static void clone_slice(H264Context *dst, H264Context *src)
 {
@@ -1699,6 +1678,33 @@ static void clone_slice(H264Context *dst, H264Context *src)
 }
 
 /**
+ * computes profile from profile_idc and constraint_set?_flags
+ *
+ * @param sps SPS
+ *
+ * @return profile as defined by FF_PROFILE_H264_*
+ */
+int ff_h264_get_profile(SPS *sps)
+{
+    int profile = sps->profile_idc;
+
+    switch(sps->profile_idc) {
+    case FF_PROFILE_H264_BASELINE:
+        // constraint_set1_flag set to 1
+        profile |= (sps->constraint_set_flags & 1<<1) ? FF_PROFILE_H264_CONSTRAINED : 0;
+        break;
+    case FF_PROFILE_H264_HIGH_10:
+    case FF_PROFILE_H264_HIGH_422:
+    case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
+        // constraint_set3_flag set to 1
+        profile |= (sps->constraint_set_flags & 1<<3) ? FF_PROFILE_H264_INTRA : 0;
+        break;
+    }
+
+    return profile;
+}
+
+/**
  * decodes a slice header.
  * This will also call MPV_common_init() and frame_start() as needed.
  *
@@ -1777,7 +1783,7 @@ static int decode_slice_header(H264Context *h, H264Context *h0){
     }
     h->sps = *h0->sps_buffers[h->pps.sps_id];
 
-    s->avctx->profile = h->sps.profile_idc;
+    s->avctx->profile = ff_h264_get_profile(&h->sps);
     s->avctx->level   = h->sps.level_idc;
     s->avctx->refs    = h->sps.ref_frame_count;
 
@@ -1795,14 +1801,14 @@ static int decode_slice_header(H264Context *h, H264Context *h0){
     if(h->sps.frame_mbs_only_flag)
         s->height= 16*s->mb_height - 2*FFMIN(h->sps.crop_bottom, 7);
     else
-        s->height= 16*s->mb_height - 4*FFMIN(h->sps.crop_bottom, 3);
+        s->height= 16*s->mb_height - 4*FFMIN(h->sps.crop_bottom, 7);
 
     if (s->context_initialized
         && (   s->width != s->avctx->width || s->height != s->avctx->height
             || av_cmp_q(h->sps.sar, s->avctx->sample_aspect_ratio))) {
         if(h != h0)
             return -1;   // width / height changed during parallelized decoding
-        free_tables(h);
+        free_tables(h, 0);
         flush_dpb(s->avctx);
         MPV_common_end(s);
     }
@@ -1812,8 +1818,7 @@ static int decode_slice_header(H264Context *h, H264Context *h0){
 
         avcodec_set_dimensions(s->avctx, s->width, s->height);
         s->avctx->sample_aspect_ratio= h->sps.sar;
-        if(!s->avctx->sample_aspect_ratio.den)
-            s->avctx->sample_aspect_ratio.den = 1;
+        av_assert0(s->avctx->sample_aspect_ratio.den);
 
         if(h->sps.video_signal_type_present_flag){
             s->avctx->color_range = h->sps.full_range ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
@@ -1831,7 +1836,12 @@ static int decode_slice_header(H264Context *h, H264Context *h0){
             av_reduce(&s->avctx->time_base.num, &s->avctx->time_base.den,
                       h->sps.num_units_in_tick, den, 1<<30);
         }
-        s->avctx->pix_fmt = s->avctx->get_format(s->avctx, s->avctx->codec->pix_fmts);
+        s->avctx->pix_fmt = s->avctx->get_format(s->avctx,
+                                                 s->avctx->codec->pix_fmts ?
+                                                 s->avctx->codec->pix_fmts :
+                                                 s->avctx->color_range == AVCOL_RANGE_JPEG ?
+                                                 hwaccel_pixfmt_list_h264_jpeg_420 :
+                                                 ff_hwaccel_pixfmt_list_420);
         s->avctx->hwaccel = ff_find_hwaccel(s->avctx->codec->id, s->avctx->pix_fmt);
 
         if (MPV_common_init(s) < 0)
@@ -1879,13 +1889,30 @@ static int decode_slice_header(H264Context *h, H264Context *h0){
     if(h0->current_slice == 0){
         while(h->frame_num !=  h->prev_frame_num &&
               h->frame_num != (h->prev_frame_num+1)%(1<<h->sps.log2_max_frame_num)){
-            av_log(NULL, AV_LOG_DEBUG, "Frame num gap %d %d\n", h->frame_num, h->prev_frame_num);
+            Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
+            av_log(h->s.avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n", h->frame_num, h->prev_frame_num);
             if (ff_h264_frame_start(h) < 0)
                 return -1;
             h->prev_frame_num++;
             h->prev_frame_num %= 1<<h->sps.log2_max_frame_num;
             s->current_picture_ptr->frame_num= h->prev_frame_num;
-            ff_h264_execute_ref_pic_marking(h, NULL, 0);
+            ff_generate_sliding_window_mmcos(h);
+            ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
+            /* Error concealment: if a ref is missing, copy the previous ref in its place.
+             * FIXME: avoiding a memcpy would be nice, but ref handling makes many assumptions
+             * about there being no actual duplicates.
+             * FIXME: this doesn't copy padding for out-of-frame motion vectors.  Given we're
+             * concealing a lost frame, this probably isn't noticable by comparison, but it should
+             * be fixed. */
+            if (h->short_ref_count) {
+                if (prev) {
+                    av_image_copy(h->short_ref[0]->data, h->short_ref[0]->linesize,
+                                  (const uint8_t**)prev->data, prev->linesize,
+                                  s->avctx->pix_fmt, s->mb_width*16, s->mb_height*16);
+                    h->short_ref[0]->poc = prev->poc+2;
+                }
+                h->short_ref[0]->frame_num = h->prev_frame_num;
+            }
         }
 
         /* See if we have a decoded first field looking for a pair... */
@@ -2747,14 +2774,9 @@ static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size){
             nalsize = 0;
             for(i = 0; i < h->nal_length_size; i++)
                 nalsize = (nalsize << 8) | buf[buf_index++];
-            if(nalsize <= 1 || nalsize > buf_size - buf_index){
-                if(nalsize == 1){
-                    buf_index++;
-                    continue;
-                }else{
-                    av_log(h->s.avctx, AV_LOG_ERROR, "AVC: nal size %d\n", nalsize);
-                    break;
-                }
+            if(nalsize <= 0 || nalsize > buf_size - buf_index){
+                av_log(h->s.avctx, AV_LOG_ERROR, "AVC: nal size %d\n", nalsize);
+                break;
             }
             next_avc= buf_index + nalsize;
         } else {
@@ -2798,8 +2820,12 @@ static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size){
 
         buf_index += consumed;
 
-        if(  (s->hurry_up == 1 && h->nal_ref_idc  == 0) //FIXME do not discard SEI id
-           ||(avctx->skip_frame >= AVDISCARD_NONREF && h->nal_ref_idc  == 0))
+        //FIXME do not discard SEI id
+        if(
+#if FF_API_HURRY_UP
+           (s->hurry_up == 1 && h->nal_ref_idc  == 0) ||
+#endif
+           (avctx->skip_frame >= AVDISCARD_NONREF && h->nal_ref_idc  == 0))
             continue;
 
       again:
@@ -2830,7 +2856,10 @@ static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size){
             s->current_picture_ptr->key_frame |=
                     (hx->nal_unit_type == NAL_IDR_SLICE) ||
                     (h->sei_recovery_frame_cnt >= 0);
-            if(hx->redundant_pic_count==0 && hx->s.hurry_up < 5
+            if(hx->redundant_pic_count==0
+#if FF_API_HURRY_UP
+               && hx->s.hurry_up < 5
+#endif
                && (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc)
                && (avctx->skip_frame < AVDISCARD_BIDIR  || hx->slice_type_nos!=FF_B_TYPE)
                && (avctx->skip_frame < AVDISCARD_NONKEY || hx->slice_type_nos==FF_I_TYPE)
@@ -2868,7 +2897,9 @@ static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size){
 
             if(hx->redundant_pic_count==0 && hx->intra_gb_ptr && hx->s.data_partitioning
                && s->context_initialized
+#if FF_API_HURRY_UP
                && s->hurry_up < 5
+#endif
                && (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc)
                && (avctx->skip_frame < AVDISCARD_BIDIR  || hx->slice_type_nos!=FF_B_TYPE)
                && (avctx->skip_frame < AVDISCARD_NONKEY || hx->slice_type_nos==FF_I_TYPE)
@@ -2954,6 +2985,7 @@ static int decode_frame(AVCodecContext *avctx,
     s->flags2= avctx->flags2;
 
    /* end of stream, output what is still in the buffers */
+ out:
     if (buf_size == 0) {
         Picture *out;
         int i, out_idx;
@@ -2982,8 +3014,18 @@ static int decode_frame(AVCodecContext *avctx,
     if(buf_index < 0)
         return -1;
 
+    if (!s->current_picture_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
+        buf_size = 0;
+        goto out;
+    }
+
     if(!(s->flags2 & CODEC_FLAG2_CHUNKS) && !s->current_picture_ptr){
-        if (avctx->skip_frame >= AVDISCARD_NONREF || s->hurry_up) return 0;
+        if (avctx->skip_frame >= AVDISCARD_NONREF
+#if FF_API_HURRY_UP
+                || s->hurry_up
+#endif
+           )
+            return 0;
         av_log(avctx, AV_LOG_ERROR, "no frame!\n");
         return -1;
     }
@@ -3335,7 +3377,7 @@ av_cold void ff_h264_free_context(H264Context *h)
 {
     int i;
 
-    free_tables(h); //FIXME cleanup init stuff perhaps
+    free_tables(h, 1); //FIXME cleanup init stuff perhaps
 
     for(i = 0; i < MAX_SPS_COUNT; i++)
         av_freep(h->sps_buffers + i);
@@ -3358,8 +3400,24 @@ av_cold int ff_h264_decode_end(AVCodecContext *avctx)
     return 0;
 }
 
+static const AVProfile profiles[] = {
+    { FF_PROFILE_H264_BASELINE,             "Baseline"              },
+    { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline"  },
+    { FF_PROFILE_H264_MAIN,                 "Main"                  },
+    { FF_PROFILE_H264_EXTENDED,             "Extended"              },
+    { FF_PROFILE_H264_HIGH,                 "High"                  },
+    { FF_PROFILE_H264_HIGH_10,              "High 10"               },
+    { FF_PROFILE_H264_HIGH_10_INTRA,        "High 10 Intra"         },
+    { FF_PROFILE_H264_HIGH_422,             "High 4:2:2"            },
+    { FF_PROFILE_H264_HIGH_422_INTRA,       "High 4:2:2 Intra"      },
+    { FF_PROFILE_H264_HIGH_444,             "High 4:4:4"            },
+    { FF_PROFILE_H264_HIGH_444_PREDICTIVE,  "High 4:4:4 Predictive" },
+    { FF_PROFILE_H264_HIGH_444_INTRA,       "High 4:4:4 Intra"      },
+    { FF_PROFILE_H264_CAVLC_444,            "CAVLC 4:4:4"           },
+    { FF_PROFILE_UNKNOWN },
+};
 
-AVCodec h264_decoder = {
+AVCodec ff_h264_decoder = {
     "h264",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_H264,
@@ -3371,11 +3429,11 @@ AVCodec h264_decoder = {
     /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 | CODEC_CAP_DELAY,
     .flush= flush_dpb,
     .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
-    .pix_fmts= ff_hwaccel_pixfmt_list_420,
+    .profiles = NULL_IF_CONFIG_SMALL(profiles),
 };
 
 #if CONFIG_H264_VDPAU_DECODER
-AVCodec h264_vdpau_decoder = {
+AVCodec ff_h264_vdpau_decoder = {
     "h264_vdpau",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_H264,
@@ -3388,5 +3446,6 @@ AVCodec h264_vdpau_decoder = {
     .flush= flush_dpb,
     .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
     .pix_fmts = (const enum PixelFormat[]){PIX_FMT_VDPAU_H264, PIX_FMT_NONE},
+    .profiles = NULL_IF_CONFIG_SMALL(profiles),
 };
 #endif
diff --git a/libavcodec/h264.h b/libavcodec/h264.h
index c6563af..96720ac 100644
--- a/libavcodec/h264.h
+++ b/libavcodec/h264.h
@@ -2,20 +2,20 @@
  * H.26L/H.264/AVC/JVT/14496-10/... encoder/decoder
  * Copyright (c) 2003 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -39,8 +39,8 @@
 #define interlaced_dct interlaced_dct_is_a_bad_name
 #define mb_intra mb_intra_is_not_initialized_see_mb_type
 
-#define LUMA_DC_BLOCK_INDEX   25
-#define CHROMA_DC_BLOCK_INDEX 26
+#define LUMA_DC_BLOCK_INDEX   24
+#define CHROMA_DC_BLOCK_INDEX 25
 
 #define CHROMA_DC_COEFF_TOKEN_VLC_BITS 8
 #define COEFF_TOKEN_VLC_BITS           8
@@ -209,6 +209,7 @@ typedef struct SPS{
     int bit_depth_luma;                ///< bit_depth_luma_minus8 + 8
     int bit_depth_chroma;              ///< bit_depth_chroma_minus8 + 8
     int residual_color_transform_flag; ///< residual_colour_transform_flag
+    int constraint_set_flags;          ///< constraint_set[0-3]_flag
 }SPS;
 
 /**
@@ -406,6 +407,7 @@ typedef struct H264Context{
     GetBitContext *inter_gb_ptr;
 
     DECLARE_ALIGNED(16, DCTELEM, mb)[16*24];
+    DECLARE_ALIGNED(16, DCTELEM, mb_luma_dc)[16];
     DCTELEM mb_padding[256];        ///< as mb is addressed by scantable[i] and scantable is uint8_t we can either check that i is not too large or ensure that there is some unused stuff after mb
 
     /**
@@ -464,6 +466,7 @@ typedef struct H264Context{
      */
     int is_avc; ///< this flag is != 0 if codec is avc1
     int nal_length_size; ///< Number of bytes used for nal length (1, 2 or 4)
+    int got_first; ///< this flag is != 0 if we've parsed a frame
 
     SPS *sps_buffers[MAX_SPS_COUNT];
     PPS *pps_buffers[MAX_PPS_COUNT];
@@ -599,10 +602,6 @@ typedef struct H264Context{
 
 extern const uint8_t ff_h264_chroma_qp[52];
 
-void ff_svq3_luma_dc_dequant_idct_c(DCTELEM *block, int qp);
-
-void ff_svq3_add_idct_c(uint8_t *dst, DCTELEM *block, int stride, int qp, int dc);
-
 /**
  * Decode SEI
  */
@@ -614,12 +613,17 @@ int ff_h264_decode_sei(H264Context *h);
 int ff_h264_decode_seq_parameter_set(H264Context *h);
 
 /**
+ * compute profile from sps
+ */
+int ff_h264_get_profile(SPS *sps);
+
+/**
  * Decode PPS
  */
 int ff_h264_decode_picture_parameter_set(H264Context *h, int bit_length);
 
 /**
- * Decodes a network abstraction layer unit.
+ * Decode a network abstraction layer unit.
  * @param consumed is the number of bytes used as input
  * @param length is the length of the array
  * @param dst_length is the number of decoded bytes FIXME here or a decode rbsp tailing?
@@ -628,29 +632,23 @@ int ff_h264_decode_picture_parameter_set(H264Context *h, int bit_length);
 const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src, int *dst_length, int *consumed, int length);
 
 /**
- * identifies the exact end of the bitstream
- * @return the length of the trailing, or 0 if damaged
- */
-int ff_h264_decode_rbsp_trailing(H264Context *h, const uint8_t *src);
-
-/**
- * frees any data that may have been allocated in the H264 context like SPS, PPS etc.
+ * Free any data that may have been allocated in the H264 context like SPS, PPS etc.
  */
 av_cold void ff_h264_free_context(H264Context *h);
 
 /**
- * reconstructs bitstream slice_type.
+ * Reconstruct bitstream slice_type.
  */
 int ff_h264_get_slice_type(const H264Context *h);
 
 /**
- * allocates tables.
+ * Allocate tables.
  * needs width/height
  */
 int ff_h264_alloc_tables(H264Context *h);
 
 /**
- * fills the default_ref_list.
+ * Fill the default_ref_list.
  */
 int ff_h264_fill_default_ref_list(H264Context *h);
 
@@ -659,38 +657,41 @@ void ff_h264_fill_mbaff_ref_list(H264Context *h);
 void ff_h264_remove_all_refs(H264Context *h);
 
 /**
- * Executes the reference picture marking (memory management control operations).
+ * Execute the reference picture marking (memory management control operations).
  */
 int ff_h264_execute_ref_pic_marking(H264Context *h, MMCO *mmco, int mmco_count);
 
 int ff_h264_decode_ref_pic_marking(H264Context *h, GetBitContext *gb);
 
+void ff_generate_sliding_window_mmcos(H264Context *h);
+
 
 /**
- * checks if the top & left blocks are available if needed & changes the dc mode so it only uses the available blocks.
+ * Check if the top & left blocks are available if needed & change the dc mode so it only uses the available blocks.
  */
 int ff_h264_check_intra4x4_pred_mode(H264Context *h);
 
 /**
- * checks if the top & left blocks are available if needed & changes the dc mode so it only uses the available blocks.
+ * Check if the top & left blocks are available if needed & change the dc mode so it only uses the available blocks.
  */
 int ff_h264_check_intra_pred_mode(H264Context *h, int mode);
 
 void ff_h264_write_back_intra_pred_mode(H264Context *h);
 void ff_h264_hl_decode_mb(H264Context *h);
 int ff_h264_frame_start(H264Context *h);
+int ff_h264_decode_extradata(H264Context *h);
 av_cold int ff_h264_decode_init(AVCodecContext *avctx);
 av_cold int ff_h264_decode_end(AVCodecContext *avctx);
 av_cold void ff_h264_decode_init_vlc(void);
 
 /**
- * decodes a macroblock
+ * Decode a macroblock
  * @return 0 if OK, AC_ERROR / DC_ERROR / MV_ERROR if an error is noticed
  */
 int ff_h264_decode_mb_cavlc(H264Context *h);
 
 /**
- * decodes a CABAC coded macroblock
+ * Decode a CABAC coded macroblock
  * @return 0 if OK, AC_ERROR / DC_ERROR / MV_ERROR if an error is noticed
  */
 int ff_h264_decode_mb_cabac(H264Context *h);
@@ -721,8 +722,20 @@ o-o o-o
  / / /
 o-o o-o
 */
+
+/* Scan8 organization:
+ *   0 1 2 3 4 5 6 7
+ * 0   u u y y y y y
+ * 1 u U U y Y Y Y Y
+ * 2 u U U y Y Y Y Y
+ * 3   v v y Y Y Y Y
+ * 4 v V V y Y Y Y Y
+ * 5 v V V   DYDUDV
+ * DY/DU/DV are for luma/chroma DC.
+ */
+
 //This table must be here because scan8[constant] must be known at compiletime
-static const uint8_t scan8[16 + 2*4]={
+static const uint8_t scan8[16 + 2*4 + 3]={
  4+1*8, 5+1*8, 4+2*8, 5+2*8,
  6+1*8, 7+1*8, 6+2*8, 7+2*8,
  4+3*8, 5+3*8, 4+4*8, 5+4*8,
@@ -731,6 +744,7 @@ static const uint8_t scan8[16 + 2*4]={
  1+2*8, 2+2*8,
  1+4*8, 2+4*8,
  1+5*8, 2+5*8,
+ 4+5*8, 5+5*8, 6+5*8
 };
 
 static av_always_inline uint32_t pack16to32(int a, int b){
@@ -1253,7 +1267,7 @@ static inline int get_dct8x8_allowed(H264Context *h){
 /**
  * decodes a P_SKIP or B_SKIP macroblock
  */
-static void decode_mb_skip(H264Context *h){
+static void av_unused decode_mb_skip(H264Context *h){
     MpegEncContext * const s = &h->s;
     const int mb_xy= h->mb_xy;
     int mb_type=0;
diff --git a/libavcodec/h264_cabac.c b/libavcodec/h264_cabac.c
index 4858378..02cf05e 100644
--- a/libavcodec/h264_cabac.c
+++ b/libavcodec/h264_cabac.c
@@ -2,20 +2,20 @@
  * H.26L/H.264/AVC/JVT/14496-10/... cabac decoding
  * Copyright (c) 2003 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -965,6 +965,7 @@ static av_always_inline int get_cabac_cbf_ctx( H264Context *h, int cat, int idx,
             nza = h->left_cbp&0x100;
             nzb = h-> top_cbp&0x100;
         } else {
+            idx -= CHROMA_DC_BLOCK_INDEX;
             nza = (h->left_cbp>>(6+idx))&0x01;
             nzb = (h-> top_cbp>>(6+idx))&0x01;
         }
@@ -1048,30 +1049,6 @@ static av_always_inline void decode_cabac_residual_internal( H264Context *h, DCT
 #define CC &h->cabac
 #endif
 
-
-    /* cat: 0-> DC 16x16  n = 0
-     *      1-> AC 16x16  n = luma4x4idx
-     *      2-> Luma4x4   n = luma4x4idx
-     *      3-> DC Chroma n = iCbCr
-     *      4-> AC Chroma n = 16 + 4 * iCbCr + chroma4x4idx
-     *      5-> Luma8x8   n = 4 * luma8x8idx
-     */
-
-    /* read coded block flag */
-    if( is_dc || cat != 5 ) {
-        if( get_cabac( CC, &h->cabac_state[85 + get_cabac_cbf_ctx( h, cat, n, is_dc ) ] ) == 0 ) {
-            if( !is_dc )
-                h->non_zero_count_cache[scan8[n]] = 0;
-
-#ifdef CABAC_ON_STACK
-            h->cabac.range     = cc.range     ;
-            h->cabac.low       = cc.low       ;
-            h->cabac.bytestream= cc.bytestream;
-#endif
-            return;
-        }
-    }
-
     significant_coeff_ctx_base = h->cabac_state
         + significant_coeff_flag_offset[MB_FIELD][cat];
     last_coeff_ctx_base = h->cabac_state
@@ -1112,7 +1089,8 @@ static av_always_inline void decode_cabac_residual_internal( H264Context *h, DCT
         if( cat == 0 )
             h->cbp_table[h->mb_xy] |= 0x100;
         else
-            h->cbp_table[h->mb_xy] |= 0x40 << n;
+            h->cbp_table[h->mb_xy] |= 0x40 << (n - CHROMA_DC_BLOCK_INDEX);
+        h->non_zero_count_cache[scan8[n]] = coeff_count;
     } else {
         if( cat == 5 )
             fill_rectangle(&h->non_zero_count_cache[scan8[n]], 2, 2, 8, coeff_count, 1);
@@ -1171,14 +1149,44 @@ static av_always_inline void decode_cabac_residual_internal( H264Context *h, DCT
 
 }
 
-static void decode_cabac_residual_dc( H264Context *h, DCTELEM *block, int cat, int n, const uint8_t *scantable, int max_coeff ) {
+static void decode_cabac_residual_dc_internal( H264Context *h, DCTELEM *block, int cat, int n, const uint8_t *scantable, int max_coeff ) {
     decode_cabac_residual_internal(h, block, cat, n, scantable, NULL, max_coeff, 1);
 }
 
-static void decode_cabac_residual_nondc( H264Context *h, DCTELEM *block, int cat, int n, const uint8_t *scantable, const uint32_t *qmul, int max_coeff ) {
+static void decode_cabac_residual_nondc_internal( H264Context *h, DCTELEM *block, int cat, int n, const uint8_t *scantable, const uint32_t *qmul, int max_coeff ) {
     decode_cabac_residual_internal(h, block, cat, n, scantable, qmul, max_coeff, 0);
 }
 
+/* cat: 0-> DC 16x16  n = 0
+ *      1-> AC 16x16  n = luma4x4idx
+ *      2-> Luma4x4   n = luma4x4idx
+ *      3-> DC Chroma n = iCbCr
+ *      4-> AC Chroma n = 16 + 4 * iCbCr + chroma4x4idx
+ *      5-> Luma8x8   n = 4 * luma8x8idx */
+
+/* Partially inline the CABAC residual decode: inline the coded block flag.
+ * This has very little impact on binary size and improves performance
+ * because it allows improved constant propagation into get_cabac_cbf_ctx,
+ * as well as because most blocks have zero CBFs. */
+
+static av_always_inline void decode_cabac_residual_dc( H264Context *h, DCTELEM *block, int cat, int n, const uint8_t *scantable, int max_coeff ) {
+    /* read coded block flag */
+    if( get_cabac( &h->cabac, &h->cabac_state[85 + get_cabac_cbf_ctx( h, cat, n, 1 ) ] ) == 0 ) {
+        h->non_zero_count_cache[scan8[n]] = 0;
+        return;
+    }
+    decode_cabac_residual_dc_internal( h, block, cat, n, scantable, max_coeff );
+}
+
+static av_always_inline void decode_cabac_residual_nondc( H264Context *h, DCTELEM *block, int cat, int n, const uint8_t *scantable, const uint32_t *qmul, int max_coeff ) {
+    /* read coded block flag */
+    if( cat != 5 && get_cabac( &h->cabac, &h->cabac_state[85 + get_cabac_cbf_ctx( h, cat, n, 0 ) ] ) == 0 ) {
+        h->non_zero_count_cache[scan8[n]] = 0;
+        return;
+    }
+    decode_cabac_residual_nondc_internal( h, block, cat, n, scantable, qmul, max_coeff );
+}
+
 /**
  * decodes a macroblock
  * @return 0 if OK, AC_ERROR / DC_ERROR / MV_ERROR if an error is noticed
@@ -1365,6 +1373,8 @@ decode_intra_mb:
             pred_mode= ff_h264_check_intra_pred_mode( h, pred_mode );
             if( pred_mode < 0 ) return -1;
             h->chroma_pred_mode= pred_mode;
+        } else {
+            h->chroma_pred_mode= DC_128_PRED8x8;
         }
     } else if( partition_count == 4 ) {
         int i, j, sub_partition_count[4], list, ref[2][4];
@@ -1597,17 +1607,15 @@ decode_intra_mb:
     s->current_picture.mb_type[mb_xy]= mb_type;
 
     if( cbp || IS_INTRA16x16( mb_type ) ) {
-        const uint8_t *scan, *scan8x8, *dc_scan;
+        const uint8_t *scan, *scan8x8;
         const uint32_t *qmul;
 
         if(IS_INTERLACED(mb_type)){
             scan8x8= s->qscale ? h->field_scan8x8 : h->field_scan8x8_q0;
             scan= s->qscale ? h->field_scan : h->field_scan_q0;
-            dc_scan= luma_dc_field_scan;
         }else{
             scan8x8= s->qscale ? h->zigzag_scan8x8 : h->zigzag_scan8x8_q0;
             scan= s->qscale ? h->zigzag_scan : h->zigzag_scan_q0;
-            dc_scan= luma_dc_zigzag_scan;
         }
 
         // decode_cabac_mb_dqp
@@ -1642,7 +1650,9 @@ decode_intra_mb:
         if( IS_INTRA16x16( mb_type ) ) {
             int i;
             //av_log( s->avctx, AV_LOG_ERROR, "INTRA16x16 DC\n" );
-            decode_cabac_residual_dc( h, h->mb, 0, 0, dc_scan, 16);
+            AV_ZERO128(h->mb_luma_dc+0);
+            AV_ZERO128(h->mb_luma_dc+8);
+            decode_cabac_residual_dc( h, h->mb_luma_dc, 0, LUMA_DC_BLOCK_INDEX, scan, 16);
 
             if( cbp&15 ) {
                 qmul = h->dequant4_coeff[0][s->qscale];
@@ -1681,7 +1691,7 @@ decode_intra_mb:
             int c;
             for( c = 0; c < 2; c++ ) {
                 //av_log( s->avctx, AV_LOG_ERROR, "INTRA C%d-DC\n",c );
-                decode_cabac_residual_dc(h, h->mb + 256 + 16*4*c, 3, c, chroma_dc_scan, 4);
+                decode_cabac_residual_dc(h, h->mb + 256 + 16*4*c, 3, CHROMA_DC_BLOCK_INDEX+c, chroma_dc_scan, 4);
             }
         }
 
diff --git a/libavcodec/h264_cavlc.c b/libavcodec/h264_cavlc.c
index 0475e94..a22a9e2 100644
--- a/libavcodec/h264_cavlc.c
+++ b/libavcodec/h264_cavlc.c
@@ -2,20 +2,20 @@
  * H.26L/H.264/AVC/JVT/14496-10/... cavlc bitstream decoding
  * Copyright (c) 2003 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -367,11 +367,11 @@ static int decode_residual(H264Context *h, GetBitContext *gb, DCTELEM *block, in
     MpegEncContext * const s = &h->s;
     static const int coeff_token_table_index[17]= {0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3};
     int level[16];
-    int zeros_left, coeff_num, coeff_token, total_coeff, i, j, trailing_ones, run_before;
+    int zeros_left, coeff_token, total_coeff, i, trailing_ones, run_before;
 
     //FIXME put trailing_onex into the context
 
-    if(n == CHROMA_DC_BLOCK_INDEX){
+    if(n >= CHROMA_DC_BLOCK_INDEX){
         coeff_token= get_vlc2(gb, chroma_dc_coeff_token_vlc.table, CHROMA_DC_COEFF_TOKEN_VLC_BITS, 1);
         total_coeff= coeff_token>>2;
     }else{
@@ -383,9 +383,9 @@ static int decode_residual(H264Context *h, GetBitContext *gb, DCTELEM *block, in
             total_coeff= pred_non_zero_count(h, n);
             coeff_token= get_vlc2(gb, coeff_token_vlc[ coeff_token_table_index[total_coeff] ].table, COEFF_TOKEN_VLC_BITS, 2);
             total_coeff= coeff_token>>2;
-            h->non_zero_count_cache[ scan8[n] ]= total_coeff;
         }
     }
+    h->non_zero_count_cache[ scan8[n] ]= total_coeff;
 
     //FIXME set last_non_zero?
 
@@ -482,45 +482,42 @@ static int decode_residual(H264Context *h, GetBitContext *gb, DCTELEM *block, in
     if(total_coeff == max_coeff)
         zeros_left=0;
     else{
-        if(n == CHROMA_DC_BLOCK_INDEX)
+        if(n >= CHROMA_DC_BLOCK_INDEX)
             zeros_left= get_vlc2(gb, (chroma_dc_total_zeros_vlc-1)[ total_coeff ].table, CHROMA_DC_TOTAL_ZEROS_VLC_BITS, 1);
         else
             zeros_left= get_vlc2(gb, (total_zeros_vlc-1)[ total_coeff ].table, TOTAL_ZEROS_VLC_BITS, 1);
     }
 
-    coeff_num = zeros_left + total_coeff - 1;
-    j = scantable[coeff_num];
-    if(n > 24){
-        block[j] = level[0];
-        for(i=1;i<total_coeff;i++) {
-            if(zeros_left <= 0)
-                run_before = 0;
-            else if(zeros_left < 7){
+    scantable += zeros_left + total_coeff - 1;
+    if(n >= LUMA_DC_BLOCK_INDEX){
+        block[*scantable] = level[0];
+        for(i=1;i<total_coeff && zeros_left > 0;i++) {
+            if(zeros_left < 7)
                 run_before= get_vlc2(gb, (run_vlc-1)[zeros_left].table, RUN_VLC_BITS, 1);
-            }else{
+            else
                 run_before= get_vlc2(gb, run7_vlc.table, RUN7_VLC_BITS, 2);
-            }
             zeros_left -= run_before;
-            coeff_num -= 1 + run_before;
-            j= scantable[ coeff_num ];
-
-            block[j]= level[i];
+            scantable -= 1 + run_before;
+            block[*scantable]= level[i];
+        }
+        for(;i<total_coeff;i++) {
+            scantable--;
+            block[*scantable]= level[i];
         }
     }else{
-        block[j] = (level[0] * qmul[j] + 32)>>6;
-        for(i=1;i<total_coeff;i++) {
-            if(zeros_left <= 0)
-                run_before = 0;
-            else if(zeros_left < 7){
+        block[*scantable] = (level[0] * qmul[*scantable] + 32)>>6;
+        for(i=1;i<total_coeff && zeros_left > 0;i++) {
+            if(zeros_left < 7)
                 run_before= get_vlc2(gb, (run_vlc-1)[zeros_left].table, RUN_VLC_BITS, 1);
-            }else{
+            else
                 run_before= get_vlc2(gb, run7_vlc.table, RUN7_VLC_BITS, 2);
-            }
             zeros_left -= run_before;
-            coeff_num -= 1 + run_before;
-            j= scantable[ coeff_num ];
-
-            block[j]= (level[i] * qmul[j] + 32)>>6;
+            scantable -= 1 + run_before;
+            block[*scantable]= (level[i] * qmul[*scantable] + 32)>>6;
+        }
+        for(;i<total_coeff;i++) {
+            scantable--;
+            block[*scantable]= (level[i] * qmul[*scantable] + 32)>>6;
         }
     }
 
@@ -668,6 +665,8 @@ decode_intra_mb:
             if(pred_mode < 0)
                 return -1;
             h->chroma_pred_mode= pred_mode;
+        } else {
+            h->chroma_pred_mode = DC_128_PRED8x8;
         }
     }else if(partition_count==4){
         int i, j, sub_partition_count[4], list, ref[2][4];
@@ -914,16 +913,14 @@ decode_intra_mb:
         int i8x8, i4x4, chroma_idx;
         int dquant;
         GetBitContext *gb= IS_INTRA(mb_type) ? h->intra_gb_ptr : h->inter_gb_ptr;
-        const uint8_t *scan, *scan8x8, *dc_scan;
+        const uint8_t *scan, *scan8x8;
 
         if(IS_INTERLACED(mb_type)){
             scan8x8= s->qscale ? h->field_scan8x8_cavlc : h->field_scan8x8_cavlc_q0;
             scan= s->qscale ? h->field_scan : h->field_scan_q0;
-            dc_scan= luma_dc_field_scan;
         }else{
             scan8x8= s->qscale ? h->zigzag_scan8x8_cavlc : h->zigzag_scan8x8_cavlc_q0;
             scan= s->qscale ? h->zigzag_scan : h->zigzag_scan_q0;
-            dc_scan= luma_dc_zigzag_scan;
         }
 
         dquant= get_se_golomb(&s->gb);
@@ -942,7 +939,9 @@ decode_intra_mb:
         h->chroma_qp[0]= get_chroma_qp(h, 0, s->qscale);
         h->chroma_qp[1]= get_chroma_qp(h, 1, s->qscale);
         if(IS_INTRA16x16(mb_type)){
-            if( decode_residual(h, h->intra_gb_ptr, h->mb, LUMA_DC_BLOCK_INDEX, dc_scan, h->dequant4_coeff[0][s->qscale], 16) < 0){
+            AV_ZERO128(h->mb_luma_dc+0);
+            AV_ZERO128(h->mb_luma_dc+8);
+            if( decode_residual(h, h->intra_gb_ptr, h->mb_luma_dc, LUMA_DC_BLOCK_INDEX, scan, h->dequant4_coeff[0][s->qscale], 16) < 0){
                 return -1; //FIXME continue if partitioned and other return -1 too
             }
 
@@ -991,7 +990,7 @@ decode_intra_mb:
 
         if(cbp&0x30){
             for(chroma_idx=0; chroma_idx<2; chroma_idx++)
-                if( decode_residual(h, gb, h->mb + 256 + 16*4*chroma_idx, CHROMA_DC_BLOCK_INDEX, chroma_dc_scan, NULL, 4) < 0){
+                if( decode_residual(h, gb, h->mb + 256 + 16*4*chroma_idx, CHROMA_DC_BLOCK_INDEX+chroma_idx, chroma_dc_scan, NULL, 4) < 0){
                     return -1;
                 }
         }
diff --git a/libavcodec/h264_direct.c b/libavcodec/h264_direct.c
index d22780d..c7df86f 100644
--- a/libavcodec/h264_direct.c
+++ b/libavcodec/h264_direct.c
@@ -2,20 +2,20 @@
  * H.26L/H.264/AVC/JVT/14496-10/... direct mb/block decoding
  * Copyright (c) 2003 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/h264_loopfilter.c b/libavcodec/h264_loopfilter.c
index 710e037..619ab19 100644
--- a/libavcodec/h264_loopfilter.c
+++ b/libavcodec/h264_loopfilter.c
@@ -2,20 +2,20 @@
  * H.26L/H.264/AVC/JVT/14496-10/... loop filter
  * Copyright (c) 2003 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/h264_mp4toannexb_bsf.c b/libavcodec/h264_mp4toannexb_bsf.c
index 0c92b36..bc49b14 100644
--- a/libavcodec/h264_mp4toannexb_bsf.c
+++ b/libavcodec/h264_mp4toannexb_bsf.c
@@ -2,20 +2,20 @@
  * H.264 MP4 to Annex B byte stream format filter
  * Copyright (c) 2007 Benoit Fouet <benoit.fouet at free.fr>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,27 +25,32 @@
 typedef struct H264BSFContext {
     uint8_t  length_size;
     uint8_t  first_idr;
-    uint8_t *sps_pps_data;
-    uint32_t size;
+    int      extradata_parsed;
 } H264BSFContext;
 
-static void alloc_and_copy(uint8_t **poutbuf,          int *poutbuf_size,
-                           const uint8_t *sps_pps, uint32_t sps_pps_size,
-                           const uint8_t *in,      uint32_t in_size) {
+static int alloc_and_copy(uint8_t **poutbuf,          int *poutbuf_size,
+                          const uint8_t *sps_pps, uint32_t sps_pps_size,
+                          const uint8_t *in,      uint32_t in_size) {
     uint32_t offset = *poutbuf_size;
     uint8_t nal_header_size = offset ? 3 : 4;
+    void *tmp;
 
     *poutbuf_size += sps_pps_size+in_size+nal_header_size;
-    *poutbuf = av_realloc(*poutbuf, *poutbuf_size);
+    tmp = av_realloc(*poutbuf, *poutbuf_size);
+    if (!tmp)
+        return AVERROR(ENOMEM);
+    *poutbuf = tmp;
     if (sps_pps)
         memcpy(*poutbuf+offset, sps_pps, sps_pps_size);
     memcpy(*poutbuf+sps_pps_size+nal_header_size+offset, in, in_size);
-    if (!offset)
+    if (!offset) {
         AV_WB32(*poutbuf+sps_pps_size, 1);
-    else {
+    } else {
         (*poutbuf+offset+sps_pps_size)[0] = (*poutbuf+offset+sps_pps_size)[1] = 0;
         (*poutbuf+offset+sps_pps_size)[2] = 1;
     }
+
+    return 0;
 }
 
 static int h264_mp4toannexb_filter(AVBitStreamFilterContext *bsfc,
@@ -67,10 +72,10 @@ static int h264_mp4toannexb_filter(AVBitStreamFilterContext *bsfc,
     }
 
     /* retrieve sps and pps NAL units from extradata */
-    if (!ctx->sps_pps_data) {
+    if (!ctx->extradata_parsed) {
         uint16_t unit_size;
-        uint32_t total_size = 0;
-        uint8_t *out = NULL, unit_nb, sps_done = 0;
+        uint64_t total_size = 0;
+        uint8_t *out = NULL, unit_nb, sps_done = 0, sps_seen = 0, pps_seen = 0;
         const uint8_t *extradata = avctx->extradata+4;
         static const uint8_t nalu_header[4] = {0, 0, 0, 1};
 
@@ -84,28 +89,53 @@ static int h264_mp4toannexb_filter(AVBitStreamFilterContext *bsfc,
         if (!unit_nb) {
             unit_nb = *extradata++; /* number of pps unit(s) */
             sps_done++;
+
+            if (unit_nb)
+                pps_seen = 1;
+        } else {
+            sps_seen = 1;
         }
+
         while (unit_nb--) {
+            void *tmp;
+
             unit_size = AV_RB16(extradata);
             total_size += unit_size+4;
-            if (extradata+2+unit_size > avctx->extradata+avctx->extradata_size) {
+            if (total_size > INT_MAX - FF_INPUT_BUFFER_PADDING_SIZE ||
+                extradata+2+unit_size > avctx->extradata+avctx->extradata_size) {
                 av_free(out);
                 return AVERROR(EINVAL);
             }
-            out = av_realloc(out, total_size);
-            if (!out)
+            tmp = av_realloc(out, total_size + FF_INPUT_BUFFER_PADDING_SIZE);
+            if (!tmp) {
+                av_free(out);
                 return AVERROR(ENOMEM);
+            }
+            out = tmp;
             memcpy(out+total_size-unit_size-4, nalu_header, 4);
             memcpy(out+total_size-unit_size,   extradata+2, unit_size);
             extradata += 2+unit_size;
 
-            if (!unit_nb && !sps_done++)
+            if (!unit_nb && !sps_done++) {
                 unit_nb = *extradata++; /* number of pps unit(s) */
+                if (unit_nb)
+                    pps_seen = 1;
+            }
         }
 
-        ctx->sps_pps_data = out;
-        ctx->size = total_size;
-        ctx->first_idr = 1;
+        if(out)
+            memset(out + total_size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
+
+        if (!sps_seen)
+            av_log(avctx, AV_LOG_WARNING, "Warning: SPS NALU missing or invalid. The resulting stream may not play.\n");
+        if (!pps_seen)
+            av_log(avctx, AV_LOG_WARNING, "Warning: PPS NALU missing or invalid. The resulting stream may not play.\n");
+
+        av_free(avctx->extradata);
+        avctx->extradata      = out;
+        avctx->extradata_size = total_size;
+        ctx->first_idr        = 1;
+        ctx->extradata_parsed = 1;
     }
 
     *poutbuf_size = 0;
@@ -114,11 +144,11 @@ static int h264_mp4toannexb_filter(AVBitStreamFilterContext *bsfc,
         if (buf + ctx->length_size > buf_end)
             goto fail;
 
-        if (ctx->length_size == 1)
+        if (ctx->length_size == 1) {
             nal_size = buf[0];
-        else if (ctx->length_size == 2)
+        } else if (ctx->length_size == 2) {
             nal_size = AV_RB16(buf);
-        else
+        } else
             nal_size = AV_RB32(buf);
 
         buf += ctx->length_size;
@@ -129,15 +159,16 @@ static int h264_mp4toannexb_filter(AVBitStreamFilterContext *bsfc,
 
         /* prepend only to the first type 5 NAL unit of an IDR picture */
         if (ctx->first_idr && unit_type == 5) {
-            alloc_and_copy(poutbuf, poutbuf_size,
-                           ctx->sps_pps_data, ctx->size,
-                           buf, nal_size);
+            if (alloc_and_copy(poutbuf, poutbuf_size,
+                               avctx->extradata, avctx->extradata_size,
+                               buf, nal_size) < 0)
+                goto fail;
             ctx->first_idr = 0;
-        }
-        else {
-            alloc_and_copy(poutbuf, poutbuf_size,
-                           NULL, 0,
-                           buf, nal_size);
+        } else {
+            if (alloc_and_copy(poutbuf, poutbuf_size,
+                               NULL, 0,
+                               buf, nal_size) < 0)
+                goto fail;
             if (!ctx->first_idr && unit_type == 1)
                 ctx->first_idr = 1;
         }
@@ -154,16 +185,9 @@ fail:
     return AVERROR(EINVAL);
 }
 
-static void h264_mp4toannexb_close(AVBitStreamFilterContext *bsfc)
-{
-    H264BSFContext *ctx = bsfc->priv_data;
-    av_freep(&ctx->sps_pps_data);
-}
-
-AVBitStreamFilter h264_mp4toannexb_bsf = {
+AVBitStreamFilter ff_h264_mp4toannexb_bsf = {
     "h264_mp4toannexb",
     sizeof(H264BSFContext),
     h264_mp4toannexb_filter,
-    h264_mp4toannexb_close,
 };
 
diff --git a/libavcodec/h264_mvpred.h b/libavcodec/h264_mvpred.h
index 661ef6c..1359072 100644
--- a/libavcodec/h264_mvpred.h
+++ b/libavcodec/h264_mvpred.h
@@ -2,20 +2,20 @@
  * H.26L/H.264/AVC/JVT/14496-10/... motion vector predicion
  * Copyright (c) 2003 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/h264_parser.c b/libavcodec/h264_parser.c
index a3cbe3b..91fbebc 100644
--- a/libavcodec/h264_parser.c
+++ b/libavcodec/h264_parser.c
@@ -2,20 +2,20 @@
  * H.26L/H.264/AVC/JVT/14496-10/... parser
  * Copyright (c) 2003 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -26,14 +26,13 @@
  */
 
 #include "parser.h"
-#include "h264_parser.h"
 #include "h264data.h"
 #include "golomb.h"
 
 #include <assert.h>
 
 
-int ff_h264_find_frame_end(H264Context *h, const uint8_t *buf, int buf_size)
+static int ff_h264_find_frame_end(H264Context *h, const uint8_t *buf, int buf_size)
 {
     int i;
     uint32_t state;
@@ -127,6 +126,9 @@ static inline int parse_nal_units(AVCodecParserContext *s,
     h->sei_cpb_removal_delay        = -1;
     h->sei_buffering_period_present =  0;
 
+    if (!buf_size)
+        return 0;
+
     for(;;) {
         int src_length, dst_length, consumed;
         buf = ff_find_start_code(buf, buf_end, &state);
@@ -185,7 +187,7 @@ static inline int parse_nal_units(AVCodecParserContext *s,
             h->sps = *h->sps_buffers[h->pps.sps_id];
             h->frame_num = get_bits(&h->s.gb, h->sps.log2_max_frame_num);
 
-            avctx->profile = h->sps.profile_idc;
+            avctx->profile = ff_h264_get_profile(&h->sps);
             avctx->level   = h->sps.level_idc;
 
             if(h->sps.frame_mbs_only_flag){
@@ -245,6 +247,14 @@ static int h264_parse(AVCodecParserContext *s,
     ParseContext *pc = &h->s.parse_context;
     int next;
 
+    if (!h->got_first) {
+        h->got_first = 1;
+        if (avctx->extradata_size) {
+            h->s.avctx = avctx;
+            ff_h264_decode_extradata(h);
+        }
+    }
+
     if(s->flags & PARSER_FLAG_COMPLETE_FRAMES){
         next= buf_size;
     }else{
@@ -272,6 +282,9 @@ static int h264_parse(AVCodecParserContext *s,
             s->dts_ref_dts_delta = INT_MIN;
             s->pts_dts_delta     = INT_MIN;
         }
+        if (s->flags & PARSER_FLAG_ONCE) {
+            s->flags &= PARSER_FLAG_COMPLETE_FRAMES;
+        }
     }
 
     *poutbuf = buf;
@@ -319,7 +332,7 @@ static int init(AVCodecParserContext *s)
     return 0;
 }
 
-AVCodecParser h264_parser = {
+AVCodecParser ff_h264_parser = {
     { CODEC_ID_H264 },
     sizeof(H264Context),
     init,
diff --git a/libavcodec/h264_parser.h b/libavcodec/h264_parser.h
deleted file mode 100644
index 149f49a..0000000
--- a/libavcodec/h264_parser.h
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * H.26L/H.264/AVC/JVT/14496-10/... parser
- * Copyright (c) 2003 Michael Niedermayer <michaelni at gmx.at>
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-/**
- * @file
- * H.264 / AVC / MPEG4 part10 parser.
- * @author Michael Niedermayer <michaelni at gmx.at>
- */
-
-#ifndef AVCODEC_H264_PARSER_H
-#define AVCODEC_H264_PARSER_H
-
-#include "h264.h"
-
-/**
- * finds the end of the current frame in the bitstream.
- * @return the position of the first byte of the next frame, or -1
- */
-int ff_h264_find_frame_end(H264Context *h, const uint8_t *buf, int buf_size);
-
-#endif /* AVCODEC_H264_PARSER_H */
diff --git a/libavcodec/h264_ps.c b/libavcodec/h264_ps.c
index 7648e2c..44b8381 100644
--- a/libavcodec/h264_ps.c
+++ b/libavcodec/h264_ps.c
@@ -2,20 +2,20 @@
  * H.26L/H.264/AVC/JVT/14496-10/... parameter set decoding
  * Copyright (c) 2003 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,6 +25,7 @@
  * @author Michael Niedermayer <michaelni at gmx.at>
  */
 
+#include "libavutil/imgutils.h"
 #include "internal.h"
 #include "dsputil.h"
 #include "avcodec.h"
@@ -266,16 +267,16 @@ static void decode_scaling_matrices(H264Context *h, SPS *sps, PPS *pps, int is_s
 
 int ff_h264_decode_seq_parameter_set(H264Context *h){
     MpegEncContext * const s = &h->s;
-    int profile_idc, level_idc;
+    int profile_idc, level_idc, constraint_set_flags = 0;
     unsigned int sps_id;
     int i;
     SPS *sps;
 
     profile_idc= get_bits(&s->gb, 8);
-    get_bits1(&s->gb);   //constraint_set0_flag
-    get_bits1(&s->gb);   //constraint_set1_flag
-    get_bits1(&s->gb);   //constraint_set2_flag
-    get_bits1(&s->gb);   //constraint_set3_flag
+    constraint_set_flags |= get_bits1(&s->gb) << 0;   //constraint_set0_flag
+    constraint_set_flags |= get_bits1(&s->gb) << 1;   //constraint_set1_flag
+    constraint_set_flags |= get_bits1(&s->gb) << 2;   //constraint_set2_flag
+    constraint_set_flags |= get_bits1(&s->gb) << 3;   //constraint_set3_flag
     get_bits(&s->gb, 4); // reserved
     level_idc= get_bits(&s->gb, 8);
     sps_id= get_ue_golomb_31(&s->gb);
@@ -288,7 +289,9 @@ int ff_h264_decode_seq_parameter_set(H264Context *h){
     if(sps == NULL)
         return -1;
 
+    sps->time_offset_length = 24;
     sps->profile_idc= profile_idc;
+    sps->constraint_set_flags = constraint_set_flags;
     sps->level_idc= level_idc;
 
     memset(sps->scaling_matrix4, 16, sizeof(sps->scaling_matrix4));
@@ -341,7 +344,7 @@ int ff_h264_decode_seq_parameter_set(H264Context *h){
     sps->mb_width = get_ue_golomb(&s->gb) + 1;
     sps->mb_height= get_ue_golomb(&s->gb) + 1;
     if((unsigned)sps->mb_width >= INT_MAX/16 || (unsigned)sps->mb_height >= INT_MAX/16 ||
-       avcodec_check_dimensions(NULL, 16*sps->mb_width, 16*sps->mb_height)){
+       av_image_check_size(16*sps->mb_width, 16*sps->mb_height, 0, h->s.avctx)){
         av_log(h->s.avctx, AV_LOG_ERROR, "mb_width/height overflow\n");
         goto fail;
     }
@@ -371,7 +374,7 @@ int ff_h264_decode_seq_parameter_set(H264Context *h){
         if(sps->crop_left || sps->crop_top){
             av_log(h->s.avctx, AV_LOG_ERROR, "insane cropping not completely supported, this could look slightly wrong ...\n");
         }
-        if(sps->crop_right >= 8 || sps->crop_bottom >= (8>> !sps->frame_mbs_only_flag)){
+        if(sps->crop_right >= 8 || sps->crop_bottom >= 8){
             av_log(h->s.avctx, AV_LOG_ERROR, "brainfart cropping not supported, this could look slightly wrong ...\n");
         }
     }else{
@@ -386,6 +389,9 @@ int ff_h264_decode_seq_parameter_set(H264Context *h){
         if (decode_vui_parameters(h, sps) < 0)
             goto fail;
 
+    if(!sps->sar.den)
+        sps->sar.den= 1;
+
     if(s->avctx->debug&FF_DEBUG_PICT_INFO){
         av_log(h->s.avctx, AV_LOG_DEBUG, "sps:%u profile:%d/%d poc:%d ref:%d %dx%d %s %s crop:%d/%d/%d/%d %s %s %d/%d\n",
                sps_id, sps->profile_idc, sps->level_idc,
diff --git a/libavcodec/h264_refs.c b/libavcodec/h264_refs.c
index ed715c6..da3ee91 100644
--- a/libavcodec/h264_refs.c
+++ b/libavcodec/h264_refs.c
@@ -2,20 +2,20 @@
  * H.26L/H.264/AVC/JVT/14496-10/... reference picture handling
  * Copyright (c) 2003 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -474,6 +474,25 @@ static void print_long_term(H264Context *h) {
     }
 }
 
+void ff_generate_sliding_window_mmcos(H264Context *h) {
+    MpegEncContext * const s = &h->s;
+    assert(h->long_ref_count + h->short_ref_count <= h->sps.ref_frame_count);
+
+    h->mmco_index= 0;
+    if(h->short_ref_count && h->long_ref_count + h->short_ref_count == h->sps.ref_frame_count &&
+            !(FIELD_PICTURE && !s->first_field && s->current_picture_ptr->reference)) {
+        h->mmco[0].opcode= MMCO_SHORT2UNUSED;
+        h->mmco[0].short_pic_num= h->short_ref[ h->short_ref_count - 1 ]->frame_num;
+        h->mmco_index= 1;
+        if (FIELD_PICTURE) {
+            h->mmco[0].short_pic_num *= 2;
+            h->mmco[1].opcode= MMCO_SHORT2UNUSED;
+            h->mmco[1].short_pic_num= h->mmco[0].short_pic_num + 1;
+            h->mmco_index= 2;
+        }
+    }
+}
+
 int ff_h264_execute_ref_pic_marking(H264Context *h, MMCO *mmco, int mmco_count){
     MpegEncContext * const s = &h->s;
     int i, av_uninit(j);
@@ -673,20 +692,7 @@ int ff_h264_decode_ref_pic_marking(H264Context *h, GetBitContext *gb){
             }
             h->mmco_index= i;
         }else{
-            assert(h->long_ref_count + h->short_ref_count <= h->sps.ref_frame_count);
-
-            if(h->short_ref_count && h->long_ref_count + h->short_ref_count == h->sps.ref_frame_count &&
-                    !(FIELD_PICTURE && !s->first_field && s->current_picture_ptr->reference)) {
-                h->mmco[0].opcode= MMCO_SHORT2UNUSED;
-                h->mmco[0].short_pic_num= h->short_ref[ h->short_ref_count - 1 ]->frame_num;
-                h->mmco_index= 1;
-                if (FIELD_PICTURE) {
-                    h->mmco[0].short_pic_num *= 2;
-                    h->mmco[1].opcode= MMCO_SHORT2UNUSED;
-                    h->mmco[1].short_pic_num= h->mmco[0].short_pic_num + 1;
-                    h->mmco_index= 2;
-                }
-            }
+            ff_generate_sliding_window_mmcos(h);
         }
     }
 
diff --git a/libavcodec/h264_sei.c b/libavcodec/h264_sei.c
index 195ea28..4f52bbe 100644
--- a/libavcodec/h264_sei.c
+++ b/libavcodec/h264_sei.c
@@ -2,20 +2,20 @@
  * H.26L/H.264/AVC/JVT/14496-10/... sei decoding
  * Copyright (c) 2003 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/h264data.h b/libavcodec/h264data.h
index b3631da..151f4e3 100644
--- a/libavcodec/h264data.h
+++ b/libavcodec/h264data.h
@@ -2,20 +2,20 @@
  * H26L/H264/AVC/JVT/14496-10/... encoder/decoder
  * Copyright (c) 2003 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/h264dsp.c b/libavcodec/h264dsp.c
index c01fc77..85dbb8f 100644
--- a/libavcodec/h264dsp.c
+++ b/libavcodec/h264dsp.c
@@ -2,20 +2,20 @@
  * H.26L/H.264/AVC/JVT/14496-10/... encoder/decoder
  * Copyright (c) 2003-2010 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -282,6 +282,7 @@ void ff_h264dsp_init(H264DSPContext *c)
     c->h264_idct8_add4     = ff_h264_idct8_add4_c;
     c->h264_idct_add8      = ff_h264_idct_add8_c;
     c->h264_idct_add16intra= ff_h264_idct_add16intra_c;
+    c->h264_luma_dc_dequant_idct= ff_h264_luma_dc_dequant_idct_c;
 
     c->weight_h264_pixels_tab[0]= weight_h264_pixels16x16_c;
     c->weight_h264_pixels_tab[1]= weight_h264_pixels16x8_c;
diff --git a/libavcodec/h264dsp.h b/libavcodec/h264dsp.h
index 3d32a9c..6fa1746 100644
--- a/libavcodec/h264dsp.h
+++ b/libavcodec/h264dsp.h
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2003-2010 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -57,19 +57,17 @@ typedef struct H264DSPContext{
                                       int bidir, int edges, int step, int mask_mv0, int mask_mv1, int field);
 
     /* IDCT */
-    /* NOTE!!! if you implement any of h264_idct8_add, h264_idct8_add4 then you must implement all of them
-       NOTE!!! if you implement any of h264_idct_add, h264_idct_add16, h264_idct_add16intra, h264_idct_add8 then you must implement all of them
-        The reason for above, is that no 2 out of one list may use a different permutation.
-    */
     void (*h264_idct_add)(uint8_t *dst/*align 4*/, DCTELEM *block/*align 16*/, int stride);
     void (*h264_idct8_add)(uint8_t *dst/*align 8*/, DCTELEM *block/*align 16*/, int stride);
     void (*h264_idct_dc_add)(uint8_t *dst/*align 4*/, DCTELEM *block/*align 16*/, int stride);
     void (*h264_idct8_dc_add)(uint8_t *dst/*align 8*/, DCTELEM *block/*align 16*/, int stride);
+
     void (*h264_dct)(DCTELEM block[4][4]);
     void (*h264_idct_add16)(uint8_t *dst/*align 16*/, const int *blockoffset, DCTELEM *block/*align 16*/, int stride, const uint8_t nnzc[6*8]);
     void (*h264_idct8_add4)(uint8_t *dst/*align 16*/, const int *blockoffset, DCTELEM *block/*align 16*/, int stride, const uint8_t nnzc[6*8]);
     void (*h264_idct_add8)(uint8_t **dst/*align 16*/, const int *blockoffset, DCTELEM *block/*align 16*/, int stride, const uint8_t nnzc[6*8]);
     void (*h264_idct_add16intra)(uint8_t *dst/*align 16*/, const int *blockoffset, DCTELEM *block/*align 16*/, int stride, const uint8_t nnzc[6*8]);
+    void (*h264_luma_dc_dequant_idct)(DCTELEM *output, DCTELEM *input/*align 16*/, int qmul);
 }H264DSPContext;
 
 void ff_h264dsp_init(H264DSPContext *c);
diff --git a/libavcodec/h264dspenc.c b/libavcodec/h264dspenc.c
deleted file mode 100644
index b65a2cc..0000000
--- a/libavcodec/h264dspenc.c
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * H.264/MPEG-4 Part 10 (Base profile) encoder.
- *
- * DSP functions
- *
- * Copyright (c) 2006 Expertisecentrum Digitale Media, UHasselt
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-/**
- * @file
- * H.264 encoder related DSP utils
- *
- */
-
-#include "dsputil.h"
-
-#define  H264_DCT_PART1(X) \
-         a = block[0][X]+block[3][X]; \
-         c = block[0][X]-block[3][X]; \
-         b = block[1][X]+block[2][X]; \
-         d = block[1][X]-block[2][X]; \
-         pieces[0][X] = a+b; \
-         pieces[2][X] = a-b; \
-         pieces[1][X] = (c<<1)+d; \
-         pieces[3][X] = c-(d<<1);
-
-#define  H264_DCT_PART2(X) \
-         a = pieces[X][0]+pieces[X][3]; \
-         c = pieces[X][0]-pieces[X][3]; \
-         b = pieces[X][1]+pieces[X][2]; \
-         d = pieces[X][1]-pieces[X][2]; \
-         block[0][X] = a+b; \
-         block[2][X] = a-b; \
-         block[1][X] = (c<<1)+d; \
-         block[3][X] = c-(d<<1);
-
-/**
- * Transform the provided matrix using the H.264 modified DCT.
- * @note
- * we'll always work with transposed input blocks, to avoid having to make a
- * distinction between C and mmx implementations.
- *
- * @param block transposed input block
- */
-static void h264_dct_c(DCTELEM block[4][4])
-{
-    DCTELEM pieces[4][4];
-    DCTELEM a, b, c, d;
-
-    H264_DCT_PART1(0);
-    H264_DCT_PART1(1);
-    H264_DCT_PART1(2);
-    H264_DCT_PART1(3);
-    H264_DCT_PART2(0);
-    H264_DCT_PART2(1);
-    H264_DCT_PART2(2);
-    H264_DCT_PART2(3);
-}
-
-av_cold void ff_h264dspenc_init(DSPContext* c, AVCodecContext *avctx)
-{
-    c->h264_dct = h264_dct_c;
-}
-
diff --git a/libavcodec/h264enc.c b/libavcodec/h264enc.c
deleted file mode 100644
index ad874f3..0000000
--- a/libavcodec/h264enc.c
+++ /dev/null
@@ -1,260 +0,0 @@
-/*
- * H.264 encoder
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-
-#include "libavutil/common.h"
-#include "get_bits.h"
-#include "mpegvideo.h"
-#include "h264data.h"
-
-/**
- * Write out the provided data into a NAL unit.
- * @param nal_ref_idc NAL reference IDC
- * @param nal_unit_type NAL unit payload type
- * @param dest the target buffer, dst+1 == src is allowed as a special case
- * @param destsize the length of the dst array
- * @param b2 the data which should be escaped
- * @return pointer to current position in the output buffer or NULL if an error occurred
- */
-static uint8_t *h264_write_nal_unit(int nal_ref_idc, int nal_unit_type, uint8_t *dest, int *destsize,
-                          PutBitContext *b2)
-{
-    PutBitContext b;
-    int i, destpos, rbsplen, escape_count;
-    uint8_t *rbsp;
-
-    if (nal_unit_type != NAL_END_STREAM)
-        put_bits(b2,1,1); // rbsp_stop_bit
-
-    // Align b2 on a byte boundary
-    align_put_bits(b2);
-    rbsplen = put_bits_count(b2)/8;
-    flush_put_bits(b2);
-    rbsp = b2->buf;
-
-    init_put_bits(&b,dest,*destsize);
-
-    put_bits(&b,16,0);
-    put_bits(&b,16,0x01);
-
-    put_bits(&b,1,0); // forbidden zero bit
-    put_bits(&b,2,nal_ref_idc); // nal_ref_idc
-    put_bits(&b,5,nal_unit_type); // nal_unit_type
-
-    flush_put_bits(&b);
-
-    destpos = 5;
-    escape_count= 0;
-
-    for (i=0; i<rbsplen; i+=2)
-    {
-        if (rbsp[i]) continue;
-        if (i>0 && rbsp[i-1]==0)
-            i--;
-        if (i+2<rbsplen && rbsp[i+1]==0 && rbsp[i+2]<=3)
-        {
-            escape_count++;
-            i+=2;
-        }
-    }
-
-    if(escape_count==0)
-    {
-        if(dest+destpos != rbsp)
-        {
-            memcpy(dest+destpos, rbsp, rbsplen);
-            *destsize -= (rbsplen+destpos);
-        }
-        return dest+rbsplen+destpos;
-    }
-
-    if(rbsplen + escape_count + 1> *destsize)
-    {
-        av_log(NULL, AV_LOG_ERROR, "Destination buffer too small!\n");
-        return NULL;
-    }
-
-    // this should be damn rare (hopefully)
-    for (i = 0 ; i < rbsplen ; i++)
-    {
-        if (i + 2 < rbsplen && (rbsp[i] == 0 && rbsp[i+1] == 0 && rbsp[i+2] < 4))
-        {
-            dest[destpos++] = rbsp[i++];
-            dest[destpos++] = rbsp[i];
-            dest[destpos++] = 0x03; // emulation prevention byte
-        }
-        else
-            dest[destpos++] = rbsp[i];
-    }
-    *destsize -= destpos;
-    return dest+destpos;
-}
-
-static const uint8_t pict_type_to_golomb[7] = {-1, 2, 0, 1, -1, 4, 3};
-
-static const uint8_t intra4x4_cbp_to_golomb[48] = {
-    3, 29, 30, 17, 31, 18, 37,  8, 32, 38, 19,  9, 20, 10, 11,  2,
-   16, 33, 34, 21, 35, 22, 39,  4, 36, 40, 23,  5, 24,  6,  7,  1,
-   41, 42, 43, 25, 44, 26, 46, 12, 45, 47, 27, 13, 28, 14, 15,  0
-};
-
-static const uint8_t inter_cbp_to_golomb[48] = {
-    0,  2,  3,  7,  4,  8, 17, 13,  5, 18,  9, 14, 10, 15, 16, 11,
-    1, 32, 33, 36, 34, 37, 44, 40, 35, 45, 38, 41, 39, 42, 43, 19,
-    6, 24, 25, 20, 26, 21, 46, 28, 27, 47, 22, 29, 23, 30, 31, 12
-};
-
-#define QUANT_SHIFT 22
-
-static const int quant_coeff[52][16] = {
-    { 419430, 258111, 419430, 258111, 258111, 167772, 258111, 167772, 419430, 258111, 419430, 258111, 258111, 167772, 258111, 167772,},
-    { 381300, 239675, 381300, 239675, 239675, 149131, 239675, 149131, 381300, 239675, 381300, 239675, 239675, 149131, 239675, 149131,},
-    { 322639, 209715, 322639, 209715, 209715, 134218, 209715, 134218, 322639, 209715, 322639, 209715, 209715, 134218, 209715, 134218,},
-    { 299593, 186414, 299593, 186414, 186414, 116711, 186414, 116711, 299593, 186414, 299593, 186414, 186414, 116711, 186414, 116711,},
-    { 262144, 167772, 262144, 167772, 167772, 107374, 167772, 107374, 262144, 167772, 262144, 167772, 167772, 107374, 167772, 107374,},
-    { 233017, 145889, 233017, 145889, 145889,  92564, 145889,  92564, 233017, 145889, 233017, 145889, 145889,  92564, 145889,  92564,},
-    { 209715, 129056, 209715, 129056, 129056,  83886, 129056,  83886, 209715, 129056, 209715, 129056, 129056,  83886, 129056,  83886,},
-    { 190650, 119837, 190650, 119837, 119837,  74565, 119837,  74565, 190650, 119837, 190650, 119837, 119837,  74565, 119837,  74565,},
-    { 161319, 104858, 161319, 104858, 104858,  67109, 104858,  67109, 161319, 104858, 161319, 104858, 104858,  67109, 104858,  67109,},
-    { 149797,  93207, 149797,  93207,  93207,  58356,  93207,  58356, 149797,  93207, 149797,  93207,  93207,  58356,  93207,  58356,},
-    { 131072,  83886, 131072,  83886,  83886,  53687,  83886,  53687, 131072,  83886, 131072,  83886,  83886,  53687,  83886,  53687,},
-    { 116508,  72944, 116508,  72944,  72944,  46282,  72944,  46282, 116508,  72944, 116508,  72944,  72944,  46282,  72944,  46282,},
-    { 104858,  64528, 104858,  64528,  64528,  41943,  64528,  41943, 104858,  64528, 104858,  64528,  64528,  41943,  64528,  41943,},
-    {  95325,  59919,  95325,  59919,  59919,  37283,  59919,  37283,  95325,  59919,  95325,  59919,  59919,  37283,  59919,  37283,},
-    {  80660,  52429,  80660,  52429,  52429,  33554,  52429,  33554,  80660,  52429,  80660,  52429,  52429,  33554,  52429,  33554,},
-    {  74898,  46603,  74898,  46603,  46603,  29178,  46603,  29178,  74898,  46603,  74898,  46603,  46603,  29178,  46603,  29178,},
-    {  65536,  41943,  65536,  41943,  41943,  26844,  41943,  26844,  65536,  41943,  65536,  41943,  41943,  26844,  41943,  26844,},
-    {  58254,  36472,  58254,  36472,  36472,  23141,  36472,  23141,  58254,  36472,  58254,  36472,  36472,  23141,  36472,  23141,},
-    {  52429,  32264,  52429,  32264,  32264,  20972,  32264,  20972,  52429,  32264,  52429,  32264,  32264,  20972,  32264,  20972,},
-    {  47663,  29959,  47663,  29959,  29959,  18641,  29959,  18641,  47663,  29959,  47663,  29959,  29959,  18641,  29959,  18641,},
-    {  40330,  26214,  40330,  26214,  26214,  16777,  26214,  16777,  40330,  26214,  40330,  26214,  26214,  16777,  26214,  16777,},
-    {  37449,  23302,  37449,  23302,  23302,  14589,  23302,  14589,  37449,  23302,  37449,  23302,  23302,  14589,  23302,  14589,},
-    {  32768,  20972,  32768,  20972,  20972,  13422,  20972,  13422,  32768,  20972,  32768,  20972,  20972,  13422,  20972,  13422,},
-    {  29127,  18236,  29127,  18236,  18236,  11570,  18236,  11570,  29127,  18236,  29127,  18236,  18236,  11570,  18236,  11570,},
-    {  26214,  16132,  26214,  16132,  16132,  10486,  16132,  10486,  26214,  16132,  26214,  16132,  16132,  10486,  16132,  10486,},
-    {  23831,  14980,  23831,  14980,  14980,   9321,  14980,   9321,  23831,  14980,  23831,  14980,  14980,   9321,  14980,   9321,},
-    {  20165,  13107,  20165,  13107,  13107,   8389,  13107,   8389,  20165,  13107,  20165,  13107,  13107,   8389,  13107,   8389,},
-    {  18725,  11651,  18725,  11651,  11651,   7294,  11651,   7294,  18725,  11651,  18725,  11651,  11651,   7294,  11651,   7294,},
-    {  16384,  10486,  16384,  10486,  10486,   6711,  10486,   6711,  16384,  10486,  16384,  10486,  10486,   6711,  10486,   6711,},
-    {  14564,   9118,  14564,   9118,   9118,   5785,   9118,   5785,  14564,   9118,  14564,   9118,   9118,   5785,   9118,   5785,},
-    {  13107,   8066,  13107,   8066,   8066,   5243,   8066,   5243,  13107,   8066,  13107,   8066,   8066,   5243,   8066,   5243,},
-    {  11916,   7490,  11916,   7490,   7490,   4660,   7490,   4660,  11916,   7490,  11916,   7490,   7490,   4660,   7490,   4660,},
-    {  10082,   6554,  10082,   6554,   6554,   4194,   6554,   4194,  10082,   6554,  10082,   6554,   6554,   4194,   6554,   4194,},
-    {   9362,   5825,   9362,   5825,   5825,   3647,   5825,   3647,   9362,   5825,   9362,   5825,   5825,   3647,   5825,   3647,},
-    {   8192,   5243,   8192,   5243,   5243,   3355,   5243,   3355,   8192,   5243,   8192,   5243,   5243,   3355,   5243,   3355,},
-    {   7282,   4559,   7282,   4559,   4559,   2893,   4559,   2893,   7282,   4559,   7282,   4559,   4559,   2893,   4559,   2893,},
-    {   6554,   4033,   6554,   4033,   4033,   2621,   4033,   2621,   6554,   4033,   6554,   4033,   4033,   2621,   4033,   2621,},
-    {   5958,   3745,   5958,   3745,   3745,   2330,   3745,   2330,   5958,   3745,   5958,   3745,   3745,   2330,   3745,   2330,},
-    {   5041,   3277,   5041,   3277,   3277,   2097,   3277,   2097,   5041,   3277,   5041,   3277,   3277,   2097,   3277,   2097,},
-    {   4681,   2913,   4681,   2913,   2913,   1824,   2913,   1824,   4681,   2913,   4681,   2913,   2913,   1824,   2913,   1824,},
-    {   4096,   2621,   4096,   2621,   2621,   1678,   2621,   1678,   4096,   2621,   4096,   2621,   2621,   1678,   2621,   1678,},
-    {   3641,   2280,   3641,   2280,   2280,   1446,   2280,   1446,   3641,   2280,   3641,   2280,   2280,   1446,   2280,   1446,},
-    {   3277,   2016,   3277,   2016,   2016,   1311,   2016,   1311,   3277,   2016,   3277,   2016,   2016,   1311,   2016,   1311,},
-    {   2979,   1872,   2979,   1872,   1872,   1165,   1872,   1165,   2979,   1872,   2979,   1872,   1872,   1165,   1872,   1165,},
-    {   2521,   1638,   2521,   1638,   1638,   1049,   1638,   1049,   2521,   1638,   2521,   1638,   1638,   1049,   1638,   1049,},
-    {   2341,   1456,   2341,   1456,   1456,    912,   1456,    912,   2341,   1456,   2341,   1456,   1456,    912,   1456,    912,},
-    {   2048,   1311,   2048,   1311,   1311,    839,   1311,    839,   2048,   1311,   2048,   1311,   1311,    839,   1311,    839,},
-    {   1820,   1140,   1820,   1140,   1140,    723,   1140,    723,   1820,   1140,   1820,   1140,   1140,    723,   1140,    723,},
-    {   1638,   1008,   1638,   1008,   1008,    655,   1008,    655,   1638,   1008,   1638,   1008,   1008,    655,   1008,    655,},
-    {   1489,    936,   1489,    936,    936,    583,    936,    583,   1489,    936,   1489,    936,    936,    583,    936,    583,},
-    {   1260,    819,   1260,    819,    819,    524,    819,    524,   1260,    819,   1260,    819,    819,    524,    819,    524,},
-    {   1170,    728,   1170,    728,    728,    456,    728,    456,   1170,    728,   1170,    728,    728,    456,    728,    456,},
-};
-
-//FIXME need to check that this does not overflow signed 32 bit for low qp, I am not sure, it's very close
-//FIXME check that gcc inlines this (and optimizes intra & separate_dc stuff away)
-static inline int quantize_c(DCTELEM *block, uint8_t *scantable, int qscale,
-                             int intra, int separate_dc)
-{
-    int i;
-    const int * const quant_table = quant_coeff[qscale];
-    const int bias = intra ? (1 << QUANT_SHIFT) / 3 : (1 << QUANT_SHIFT) / 6;
-    const unsigned int threshold1 = (1 << QUANT_SHIFT) - bias - 1;
-    const unsigned int threshold2 = (threshold1 << 1);
-    int last_non_zero;
-
-    if (separate_dc) {
-        if (qscale <= 18) {
-            //avoid overflows
-            const int dc_bias = intra ? (1 << (QUANT_SHIFT - 2)) / 3 : (1 << (QUANT_SHIFT - 2)) / 6;
-            const unsigned int dc_threshold1 = (1 << (QUANT_SHIFT - 2)) - dc_bias - 1;
-            const unsigned int dc_threshold2 = (dc_threshold1 << 1);
-
-            int level = block[0]*quant_coeff[qscale+18][0];
-            if (((unsigned)(level + dc_threshold1)) > dc_threshold2) {
-                if (level > 0) {
-                    level = (dc_bias + level) >> (QUANT_SHIFT - 2);
-                    block[0] = level;
-                } else {
-                    level = (dc_bias - level) >> (QUANT_SHIFT - 2);
-                    block[0] = -level;
-                }
-//                last_non_zero = i;
-            } else {
-                block[0] = 0;
-            }
-        } else {
-            const int dc_bias = intra ? (1 << (QUANT_SHIFT + 1)) / 3 : (1 << (QUANT_SHIFT + 1)) / 6;
-            const unsigned int dc_threshold1 = (1 << (QUANT_SHIFT + 1)) - dc_bias - 1;
-            const unsigned int dc_threshold2 = (dc_threshold1 << 1);
-
-            int level = block[0]*quant_table[0];
-            if (((unsigned)(level + dc_threshold1)) > dc_threshold2) {
-                if (level > 0) {
-                    level = (dc_bias + level) >> (QUANT_SHIFT + 1);
-                    block[0] = level;
-                } else {
-                    level = (dc_bias - level) >> (QUANT_SHIFT + 1);
-                    block[0] = -level;
-                }
-//                last_non_zero = i;
-            } else {
-                block[0] = 0;
-            }
-        }
-        last_non_zero = 0;
-        i = 1;
-    } else {
-        last_non_zero = -1;
-        i = 0;
-    }
-
-    for (; i < 16; i++) {
-        const int j = scantable[i];
-        int level = block[j]*quant_table[j];
-
-//        if (   bias+level >= (1 << (QMAT_SHIFT - 3))
-//            || bias-level >= (1 << (QMAT_SHIFT - 3))) {
-        if (((unsigned)(level + threshold1)) > threshold2) {
-            if (level > 0) {
-                level = (bias + level) >> QUANT_SHIFT;
-                block[j] = level;
-            } else {
-                level = (bias - level) >> QUANT_SHIFT;
-                block[j] = -level;
-            }
-            last_non_zero = i;
-        } else {
-            block[j] = 0;
-        }
-    }
-
-    return last_non_zero;
-}
diff --git a/libavcodec/h264idct.c b/libavcodec/h264idct.c
index da5c6a5..ecf669e 100644
--- a/libavcodec/h264idct.c
+++ b/libavcodec/h264idct.c
@@ -2,20 +2,20 @@
  * H.264 IDCT
  * Copyright (c) 2004 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -34,23 +34,23 @@ static av_always_inline void idct_internal(uint8_t *dst, DCTELEM *block, int str
     block[0] += 1<<(shift-1);
 
     for(i=0; i<4; i++){
-        const int z0=  block[0 + block_stride*i]     +  block[2 + block_stride*i];
-        const int z1=  block[0 + block_stride*i]     -  block[2 + block_stride*i];
-        const int z2= (block[1 + block_stride*i]>>1) -  block[3 + block_stride*i];
-        const int z3=  block[1 + block_stride*i]     + (block[3 + block_stride*i]>>1);
-
-        block[0 + block_stride*i]= z0 + z3;
-        block[1 + block_stride*i]= z1 + z2;
-        block[2 + block_stride*i]= z1 - z2;
-        block[3 + block_stride*i]= z0 - z3;
-    }
-
-    for(i=0; i<4; i++){
         const int z0=  block[i + block_stride*0]     +  block[i + block_stride*2];
         const int z1=  block[i + block_stride*0]     -  block[i + block_stride*2];
         const int z2= (block[i + block_stride*1]>>1) -  block[i + block_stride*3];
         const int z3=  block[i + block_stride*1]     + (block[i + block_stride*3]>>1);
 
+        block[i + block_stride*0]= z0 + z3;
+        block[i + block_stride*1]= z1 + z2;
+        block[i + block_stride*2]= z1 - z2;
+        block[i + block_stride*3]= z0 - z3;
+    }
+
+    for(i=0; i<4; i++){
+        const int z0=  block[0 + block_stride*i]     +  block[2 + block_stride*i];
+        const int z1=  block[0 + block_stride*i]     -  block[2 + block_stride*i];
+        const int z2= (block[1 + block_stride*i]>>1) -  block[3 + block_stride*i];
+        const int z3=  block[1 + block_stride*i]     + (block[3 + block_stride*i]>>1);
+
         dst[i + 0*stride]= cm[ add*dst[i + 0*stride] + ((z0 + z3) >> shift) ];
         dst[i + 1*stride]= cm[ add*dst[i + 1*stride] + ((z1 + z2) >> shift) ];
         dst[i + 2*stride]= cm[ add*dst[i + 2*stride] + ((z1 - z2) >> shift) ];
@@ -78,51 +78,51 @@ void ff_h264_idct8_add_c(uint8_t *dst, DCTELEM *block, int stride){
 
     for( i = 0; i < 8; i++ )
     {
-        const int a0 =  block[0+i*8] + block[4+i*8];
-        const int a2 =  block[0+i*8] - block[4+i*8];
-        const int a4 = (block[2+i*8]>>1) - block[6+i*8];
-        const int a6 = (block[6+i*8]>>1) + block[2+i*8];
+        const int a0 =  block[i+0*8] + block[i+4*8];
+        const int a2 =  block[i+0*8] - block[i+4*8];
+        const int a4 = (block[i+2*8]>>1) - block[i+6*8];
+        const int a6 = (block[i+6*8]>>1) + block[i+2*8];
 
         const int b0 = a0 + a6;
         const int b2 = a2 + a4;
         const int b4 = a2 - a4;
         const int b6 = a0 - a6;
 
-        const int a1 = -block[3+i*8] + block[5+i*8] - block[7+i*8] - (block[7+i*8]>>1);
-        const int a3 =  block[1+i*8] + block[7+i*8] - block[3+i*8] - (block[3+i*8]>>1);
-        const int a5 = -block[1+i*8] + block[7+i*8] + block[5+i*8] + (block[5+i*8]>>1);
-        const int a7 =  block[3+i*8] + block[5+i*8] + block[1+i*8] + (block[1+i*8]>>1);
+        const int a1 = -block[i+3*8] + block[i+5*8] - block[i+7*8] - (block[i+7*8]>>1);
+        const int a3 =  block[i+1*8] + block[i+7*8] - block[i+3*8] - (block[i+3*8]>>1);
+        const int a5 = -block[i+1*8] + block[i+7*8] + block[i+5*8] + (block[i+5*8]>>1);
+        const int a7 =  block[i+3*8] + block[i+5*8] + block[i+1*8] + (block[i+1*8]>>1);
 
         const int b1 = (a7>>2) + a1;
         const int b3 =  a3 + (a5>>2);
         const int b5 = (a3>>2) - a5;
         const int b7 =  a7 - (a1>>2);
 
-        block[0+i*8] = b0 + b7;
-        block[7+i*8] = b0 - b7;
-        block[1+i*8] = b2 + b5;
-        block[6+i*8] = b2 - b5;
-        block[2+i*8] = b4 + b3;
-        block[5+i*8] = b4 - b3;
-        block[3+i*8] = b6 + b1;
-        block[4+i*8] = b6 - b1;
+        block[i+0*8] = b0 + b7;
+        block[i+7*8] = b0 - b7;
+        block[i+1*8] = b2 + b5;
+        block[i+6*8] = b2 - b5;
+        block[i+2*8] = b4 + b3;
+        block[i+5*8] = b4 - b3;
+        block[i+3*8] = b6 + b1;
+        block[i+4*8] = b6 - b1;
     }
     for( i = 0; i < 8; i++ )
     {
-        const int a0 =  block[i+0*8] + block[i+4*8];
-        const int a2 =  block[i+0*8] - block[i+4*8];
-        const int a4 = (block[i+2*8]>>1) - block[i+6*8];
-        const int a6 = (block[i+6*8]>>1) + block[i+2*8];
+        const int a0 =  block[0+i*8] + block[4+i*8];
+        const int a2 =  block[0+i*8] - block[4+i*8];
+        const int a4 = (block[2+i*8]>>1) - block[6+i*8];
+        const int a6 = (block[6+i*8]>>1) + block[2+i*8];
 
         const int b0 = a0 + a6;
         const int b2 = a2 + a4;
         const int b4 = a2 - a4;
         const int b6 = a0 - a6;
 
-        const int a1 = -block[i+3*8] + block[i+5*8] - block[i+7*8] - (block[i+7*8]>>1);
-        const int a3 =  block[i+1*8] + block[i+7*8] - block[i+3*8] - (block[i+3*8]>>1);
-        const int a5 = -block[i+1*8] + block[i+7*8] + block[i+5*8] + (block[i+5*8]>>1);
-        const int a7 =  block[i+3*8] + block[i+5*8] + block[i+1*8] + (block[i+1*8]>>1);
+        const int a1 = -block[3+i*8] + block[5+i*8] - block[7+i*8] - (block[7+i*8]>>1);
+        const int a3 =  block[1+i*8] + block[7+i*8] - block[3+i*8] - (block[3+i*8]>>1);
+        const int a5 = -block[1+i*8] + block[7+i*8] + block[5+i*8] + (block[5+i*8]>>1);
+        const int a7 =  block[3+i*8] + block[5+i*8] + block[1+i*8] + (block[1+i*8]>>1);
 
         const int b1 = (a7>>2) + a1;
         const int b3 =  a3 + (a5>>2);
@@ -143,24 +143,24 @@ void ff_h264_idct8_add_c(uint8_t *dst, DCTELEM *block, int stride){
 // assumes all AC coefs are 0
 void ff_h264_idct_dc_add_c(uint8_t *dst, DCTELEM *block, int stride){
     int i, j;
-    uint8_t *cm = ff_cropTbl + MAX_NEG_CROP;
     int dc = (block[0] + 32) >> 6;
+    uint8_t *cm = ff_cropTbl + MAX_NEG_CROP + dc;
     for( j = 0; j < 4; j++ )
     {
         for( i = 0; i < 4; i++ )
-            dst[i] = cm[ dst[i] + dc ];
+            dst[i] = cm[ dst[i] ];
         dst += stride;
     }
 }
 
 void ff_h264_idct8_dc_add_c(uint8_t *dst, DCTELEM *block, int stride){
     int i, j;
-    uint8_t *cm = ff_cropTbl + MAX_NEG_CROP;
     int dc = (block[0] + 32) >> 6;
+    uint8_t *cm = ff_cropTbl + MAX_NEG_CROP + dc;
     for( j = 0; j < 8; j++ )
     {
         for( i = 0; i < 8; i++ )
-            dst[i] = cm[ dst[i] + dc ];
+            dst[i] = cm[ dst[i] ];
         dst += stride;
     }
 }
@@ -216,3 +216,38 @@ void ff_h264_idct_add8_c(uint8_t **dest, const int *block_offset, DCTELEM *block
             ff_h264_idct_dc_add_c(dest[(i&4)>>2] + block_offset[i], block + i*16, stride);
     }
 }
+/**
+ * IDCT transforms the 16 dc values and dequantizes them.
+ * @param qp quantization parameter
+ */
+void ff_h264_luma_dc_dequant_idct_c(DCTELEM *output, DCTELEM *input, int qmul){
+#define stride 16
+    int i;
+    int temp[16];
+    static const uint8_t x_offset[4]={0, 2*stride, 8*stride, 10*stride};
+
+    for(i=0; i<4; i++){
+        const int z0= input[4*i+0] + input[4*i+1];
+        const int z1= input[4*i+0] - input[4*i+1];
+        const int z2= input[4*i+2] - input[4*i+3];
+        const int z3= input[4*i+2] + input[4*i+3];
+
+        temp[4*i+0]= z0+z3;
+        temp[4*i+1]= z0-z3;
+        temp[4*i+2]= z1-z2;
+        temp[4*i+3]= z1+z2;
+    }
+
+    for(i=0; i<4; i++){
+        const int offset= x_offset[i];
+        const int z0= temp[4*0+i] + temp[4*2+i];
+        const int z1= temp[4*0+i] - temp[4*2+i];
+        const int z2= temp[4*1+i] - temp[4*3+i];
+        const int z3= temp[4*1+i] + temp[4*3+i];
+
+        output[stride* 0+offset]= ((((z0 + z3)*qmul + 128 ) >> 8));
+        output[stride* 1+offset]= ((((z1 + z2)*qmul + 128 ) >> 8));
+        output[stride* 4+offset]= ((((z1 - z2)*qmul + 128 ) >> 8));
+        output[stride* 5+offset]= ((((z0 - z3)*qmul + 128 ) >> 8));
+    }
+}
diff --git a/libavcodec/h264pred.c b/libavcodec/h264pred.c
index 9637b45..1a4ab81 100644
--- a/libavcodec/h264pred.c
+++ b/libavcodec/h264pred.c
@@ -2,20 +2,20 @@
  * H.26L/H.264/AVC/JVT/14496-10/... encoder/decoder
  * Copyright (c) 2003 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -28,8 +28,9 @@
 #include "avcodec.h"
 #include "mpegvideo.h"
 #include "h264pred.h"
+#include "mathops.h"
 
-static void pred4x4_vertical_c(uint8_t *src, uint8_t *topright, int stride){
+static void pred4x4_vertical_c(uint8_t *src, const uint8_t *topright, int stride){
     const uint32_t a= ((uint32_t*)(src-stride))[0];
     ((uint32_t*)(src+0*stride))[0]= a;
     ((uint32_t*)(src+1*stride))[0]= a;
@@ -37,14 +38,14 @@ static void pred4x4_vertical_c(uint8_t *src, uint8_t *topright, int stride){
     ((uint32_t*)(src+3*stride))[0]= a;
 }
 
-static void pred4x4_horizontal_c(uint8_t *src, uint8_t *topright, int stride){
+static void pred4x4_horizontal_c(uint8_t *src, const uint8_t *topright, int stride){
     ((uint32_t*)(src+0*stride))[0]= src[-1+0*stride]*0x01010101;
     ((uint32_t*)(src+1*stride))[0]= src[-1+1*stride]*0x01010101;
     ((uint32_t*)(src+2*stride))[0]= src[-1+2*stride]*0x01010101;
     ((uint32_t*)(src+3*stride))[0]= src[-1+3*stride]*0x01010101;
 }
 
-static void pred4x4_dc_c(uint8_t *src, uint8_t *topright, int stride){
+static void pred4x4_dc_c(uint8_t *src, const uint8_t *topright, int stride){
     const int dc= (  src[-stride] + src[1-stride] + src[2-stride] + src[3-stride]
                    + src[-1+0*stride] + src[-1+1*stride] + src[-1+2*stride] + src[-1+3*stride] + 4) >>3;
 
@@ -54,7 +55,7 @@ static void pred4x4_dc_c(uint8_t *src, uint8_t *topright, int stride){
     ((uint32_t*)(src+3*stride))[0]= dc* 0x01010101;
 }
 
-static void pred4x4_left_dc_c(uint8_t *src, uint8_t *topright, int stride){
+static void pred4x4_left_dc_c(uint8_t *src, const uint8_t *topright, int stride){
     const int dc= (  src[-1+0*stride] + src[-1+1*stride] + src[-1+2*stride] + src[-1+3*stride] + 2) >>2;
 
     ((uint32_t*)(src+0*stride))[0]=
@@ -63,7 +64,7 @@ static void pred4x4_left_dc_c(uint8_t *src, uint8_t *topright, int stride){
     ((uint32_t*)(src+3*stride))[0]= dc* 0x01010101;
 }
 
-static void pred4x4_top_dc_c(uint8_t *src, uint8_t *topright, int stride){
+static void pred4x4_top_dc_c(uint8_t *src, const uint8_t *topright, int stride){
     const int dc= (  src[-stride] + src[1-stride] + src[2-stride] + src[3-stride] + 2) >>2;
 
     ((uint32_t*)(src+0*stride))[0]=
@@ -72,13 +73,27 @@ static void pred4x4_top_dc_c(uint8_t *src, uint8_t *topright, int stride){
     ((uint32_t*)(src+3*stride))[0]= dc* 0x01010101;
 }
 
-static void pred4x4_128_dc_c(uint8_t *src, uint8_t *topright, int stride){
+static void pred4x4_128_dc_c(uint8_t *src, const uint8_t *topright, int stride){
     ((uint32_t*)(src+0*stride))[0]=
     ((uint32_t*)(src+1*stride))[0]=
     ((uint32_t*)(src+2*stride))[0]=
     ((uint32_t*)(src+3*stride))[0]= 128U*0x01010101U;
 }
 
+static void pred4x4_127_dc_c(uint8_t *src, const uint8_t *topright, int stride){
+    ((uint32_t*)(src+0*stride))[0]=
+    ((uint32_t*)(src+1*stride))[0]=
+    ((uint32_t*)(src+2*stride))[0]=
+    ((uint32_t*)(src+3*stride))[0]= 127U*0x01010101U;
+}
+
+static void pred4x4_129_dc_c(uint8_t *src, const uint8_t *topright, int stride){
+    ((uint32_t*)(src+0*stride))[0]=
+    ((uint32_t*)(src+1*stride))[0]=
+    ((uint32_t*)(src+2*stride))[0]=
+    ((uint32_t*)(src+3*stride))[0]= 129U*0x01010101U;
+}
+
 
 #define LOAD_TOP_RIGHT_EDGE\
     const int av_unused t4= topright[0];\
@@ -104,7 +119,32 @@ static void pred4x4_128_dc_c(uint8_t *src, uint8_t *topright, int stride){
     const int av_unused t2= src[ 2-1*stride];\
     const int av_unused t3= src[ 3-1*stride];\
 
-static void pred4x4_down_right_c(uint8_t *src, uint8_t *topright, int stride){
+static void pred4x4_vertical_vp8_c(uint8_t *src, const uint8_t *topright, int stride){
+    const int lt= src[-1-1*stride];
+    LOAD_TOP_EDGE
+    LOAD_TOP_RIGHT_EDGE
+    uint32_t v = PACK_4U8((lt + 2*t0 + t1 + 2) >> 2,
+                            (t0 + 2*t1 + t2 + 2) >> 2,
+                            (t1 + 2*t2 + t3 + 2) >> 2,
+                            (t2 + 2*t3 + t4 + 2) >> 2);
+
+    AV_WN32A(src+0*stride, v);
+    AV_WN32A(src+1*stride, v);
+    AV_WN32A(src+2*stride, v);
+    AV_WN32A(src+3*stride, v);
+}
+
+static void pred4x4_horizontal_vp8_c(uint8_t *src, const uint8_t *topright, int stride){
+    const int lt= src[-1-1*stride];
+    LOAD_LEFT_EDGE
+
+    AV_WN32A(src+0*stride, ((lt + 2*l0 + l1 + 2) >> 2)*0x01010101);
+    AV_WN32A(src+1*stride, ((l0 + 2*l1 + l2 + 2) >> 2)*0x01010101);
+    AV_WN32A(src+2*stride, ((l1 + 2*l2 + l3 + 2) >> 2)*0x01010101);
+    AV_WN32A(src+3*stride, ((l2 + 2*l3 + l3 + 2) >> 2)*0x01010101);
+}
+
+static void pred4x4_down_right_c(uint8_t *src, const uint8_t *topright, int stride){
     const int lt= src[-1-1*stride];
     LOAD_TOP_EDGE
     LOAD_LEFT_EDGE
@@ -127,7 +167,7 @@ static void pred4x4_down_right_c(uint8_t *src, uint8_t *topright, int stride){
     src[3+0*stride]=(t1 + 2*t2 + t3 + 2)>>2;
 }
 
-static void pred4x4_down_left_c(uint8_t *src, uint8_t *topright, int stride){
+static void pred4x4_down_left_c(uint8_t *src, const uint8_t *topright, int stride){
     LOAD_TOP_EDGE
     LOAD_TOP_RIGHT_EDGE
 //    LOAD_LEFT_EDGE
@@ -150,7 +190,7 @@ static void pred4x4_down_left_c(uint8_t *src, uint8_t *topright, int stride){
     src[3+3*stride]=(t6 + 3*t7 + 2)>>2;
 }
 
-static void pred4x4_down_left_svq3_c(uint8_t *src, uint8_t *topright, int stride){
+static void pred4x4_down_left_svq3_c(uint8_t *src, const uint8_t *topright, int stride){
     LOAD_TOP_EDGE
     LOAD_LEFT_EDGE
     const av_unused int unu0= t0;
@@ -174,7 +214,7 @@ static void pred4x4_down_left_svq3_c(uint8_t *src, uint8_t *topright, int stride
     src[3+3*stride]=(l3 + t3)>>1;
 }
 
-static void pred4x4_down_left_rv40_c(uint8_t *src, uint8_t *topright, int stride){
+static void pred4x4_down_left_rv40_c(uint8_t *src, const uint8_t *topright, int stride){
     LOAD_TOP_EDGE
     LOAD_TOP_RIGHT_EDGE
     LOAD_LEFT_EDGE
@@ -198,7 +238,7 @@ static void pred4x4_down_left_rv40_c(uint8_t *src, uint8_t *topright, int stride
     src[3+3*stride]=(t6 + t7 + 1 + l6 + l7 + 1)>>2;
 }
 
-static void pred4x4_down_left_rv40_nodown_c(uint8_t *src, uint8_t *topright, int stride){
+static void pred4x4_down_left_rv40_nodown_c(uint8_t *src, const uint8_t *topright, int stride){
     LOAD_TOP_EDGE
     LOAD_TOP_RIGHT_EDGE
     LOAD_LEFT_EDGE
@@ -221,7 +261,7 @@ static void pred4x4_down_left_rv40_nodown_c(uint8_t *src, uint8_t *topright, int
     src[3+3*stride]=(t6 + t7 + 1 + 2*l3 + 1)>>2;
 }
 
-static void pred4x4_vertical_right_c(uint8_t *src, uint8_t *topright, int stride){
+static void pred4x4_vertical_right_c(uint8_t *src, const uint8_t *topright, int stride){
     const int lt= src[-1-1*stride];
     LOAD_TOP_EDGE
     LOAD_LEFT_EDGE
@@ -244,7 +284,7 @@ static void pred4x4_vertical_right_c(uint8_t *src, uint8_t *topright, int stride
     src[0+3*stride]=(l0 + 2*l1 + l2 + 2)>>2;
 }
 
-static void pred4x4_vertical_left_c(uint8_t *src, uint8_t *topright, int stride){
+static void pred4x4_vertical_left_c(uint8_t *src, const uint8_t *topright, int stride){
     LOAD_TOP_EDGE
     LOAD_TOP_RIGHT_EDGE
 
@@ -266,7 +306,7 @@ static void pred4x4_vertical_left_c(uint8_t *src, uint8_t *topright, int stride)
     src[3+3*stride]=(t4 + 2*t5 + t6 + 2)>>2;
 }
 
-static void pred4x4_vertical_left_rv40(uint8_t *src, uint8_t *topright, int stride,
+static void pred4x4_vertical_left_rv40(uint8_t *src, const uint8_t *topright, int stride,
                                       const int l0, const int l1, const int l2, const int l3, const int l4){
     LOAD_TOP_EDGE
     LOAD_TOP_RIGHT_EDGE
@@ -289,20 +329,42 @@ static void pred4x4_vertical_left_rv40(uint8_t *src, uint8_t *topright, int stri
     src[3+3*stride]=(t4 + 2*t5 + t6 + 2)>>2;
 }
 
-static void pred4x4_vertical_left_rv40_c(uint8_t *src, uint8_t *topright, int stride){
+static void pred4x4_vertical_left_rv40_c(uint8_t *src, const uint8_t *topright, int stride){
     LOAD_LEFT_EDGE
     LOAD_DOWN_LEFT_EDGE
 
     pred4x4_vertical_left_rv40(src, topright, stride, l0, l1, l2, l3, l4);
 }
 
-static void pred4x4_vertical_left_rv40_nodown_c(uint8_t *src, uint8_t *topright, int stride){
+static void pred4x4_vertical_left_rv40_nodown_c(uint8_t *src, const uint8_t *topright, int stride){
     LOAD_LEFT_EDGE
 
     pred4x4_vertical_left_rv40(src, topright, stride, l0, l1, l2, l3, l3);
 }
 
-static void pred4x4_horizontal_up_c(uint8_t *src, uint8_t *topright, int stride){
+static void pred4x4_vertical_left_vp8_c(uint8_t *src, const uint8_t *topright, int stride){
+    LOAD_TOP_EDGE
+    LOAD_TOP_RIGHT_EDGE
+
+    src[0+0*stride]=(t0 + t1 + 1)>>1;
+    src[1+0*stride]=
+    src[0+2*stride]=(t1 + t2 + 1)>>1;
+    src[2+0*stride]=
+    src[1+2*stride]=(t2 + t3 + 1)>>1;
+    src[3+0*stride]=
+    src[2+2*stride]=(t3 + t4 + 1)>>1;
+    src[0+1*stride]=(t0 + 2*t1 + t2 + 2)>>2;
+    src[1+1*stride]=
+    src[0+3*stride]=(t1 + 2*t2 + t3 + 2)>>2;
+    src[2+1*stride]=
+    src[1+3*stride]=(t2 + 2*t3 + t4 + 2)>>2;
+    src[3+1*stride]=
+    src[2+3*stride]=(t3 + 2*t4 + t5 + 2)>>2;
+    src[3+2*stride]=(t4 + 2*t5 + t6 + 2)>>2;
+    src[3+3*stride]=(t5 + 2*t6 + t7 + 2)>>2;
+}
+
+static void pred4x4_horizontal_up_c(uint8_t *src, const uint8_t *topright, int stride){
     LOAD_LEFT_EDGE
 
     src[0+0*stride]=(l0 + l1 + 1)>>1;
@@ -323,7 +385,7 @@ static void pred4x4_horizontal_up_c(uint8_t *src, uint8_t *topright, int stride)
     src[3+3*stride]=l3;
 }
 
-static void pred4x4_horizontal_up_rv40_c(uint8_t *src, uint8_t *topright, int stride){
+static void pred4x4_horizontal_up_rv40_c(uint8_t *src, const uint8_t *topright, int stride){
     LOAD_LEFT_EDGE
     LOAD_DOWN_LEFT_EDGE
     LOAD_TOP_EDGE
@@ -347,7 +409,7 @@ static void pred4x4_horizontal_up_rv40_c(uint8_t *src, uint8_t *topright, int st
     src[3+3*stride]=(l4 + 2*l5 + l6 + 2)>>2;
 }
 
-static void pred4x4_horizontal_up_rv40_nodown_c(uint8_t *src, uint8_t *topright, int stride){
+static void pred4x4_horizontal_up_rv40_nodown_c(uint8_t *src, const uint8_t *topright, int stride){
     LOAD_LEFT_EDGE
     LOAD_TOP_EDGE
     LOAD_TOP_RIGHT_EDGE
@@ -370,7 +432,7 @@ static void pred4x4_horizontal_up_rv40_nodown_c(uint8_t *src, uint8_t *topright,
     src[3+3*stride]=l3;
 }
 
-static void pred4x4_horizontal_down_c(uint8_t *src, uint8_t *topright, int stride){
+static void pred4x4_horizontal_down_c(uint8_t *src, const uint8_t *topright, int stride){
     const int lt= src[-1-1*stride];
     LOAD_TOP_EDGE
     LOAD_LEFT_EDGE
@@ -393,6 +455,21 @@ static void pred4x4_horizontal_down_c(uint8_t *src, uint8_t *topright, int strid
     src[1+3*stride]=(l1 + 2*l2 + l3 + 2)>>2;
 }
 
+static void pred4x4_tm_vp8_c(uint8_t *src, const uint8_t *topright, int stride){
+    uint8_t *cm = ff_cropTbl + MAX_NEG_CROP - src[-1-stride];
+    uint8_t *top = src-stride;
+    int y;
+
+    for (y = 0; y < 4; y++) {
+        uint8_t *cm_in = cm + src[-1];
+        src[0] = cm_in[top[0]];
+        src[1] = cm_in[top[1]];
+        src[2] = cm_in[top[2]];
+        src[3] = cm_in[top[3]];
+        src += stride;
+    }
+}
+
 static void pred16x16_vertical_c(uint8_t *src, int stride){
     int i;
     const uint32_t a= ((uint32_t*)(src-stride))[0];
@@ -484,6 +561,28 @@ static void pred16x16_128_dc_c(uint8_t *src, int stride){
     }
 }
 
+static void pred16x16_127_dc_c(uint8_t *src, int stride){
+    int i;
+
+    for(i=0; i<16; i++){
+        ((uint32_t*)(src+i*stride))[0]=
+        ((uint32_t*)(src+i*stride))[1]=
+        ((uint32_t*)(src+i*stride))[2]=
+        ((uint32_t*)(src+i*stride))[3]= 0x01010101U*127U;
+    }
+}
+
+static void pred16x16_129_dc_c(uint8_t *src, int stride){
+    int i;
+
+    for(i=0; i<16; i++){
+        ((uint32_t*)(src+i*stride))[0]=
+        ((uint32_t*)(src+i*stride))[1]=
+        ((uint32_t*)(src+i*stride))[2]=
+        ((uint32_t*)(src+i*stride))[3]= 0x01010101U*129U;
+    }
+}
+
 static inline void pred16x16_plane_compat_c(uint8_t *src, int stride, const int svq3, const int rv40){
   int i, j, k;
   int a;
@@ -539,6 +638,33 @@ static void pred16x16_plane_rv40_c(uint8_t *src, int stride){
     pred16x16_plane_compat_c(src, stride, 0, 1);
 }
 
+static void pred16x16_tm_vp8_c(uint8_t *src, int stride){
+    uint8_t *cm = ff_cropTbl + MAX_NEG_CROP - src[-1-stride];
+    uint8_t *top = src-stride;
+    int y;
+
+    for (y = 0; y < 16; y++) {
+        uint8_t *cm_in = cm + src[-1];
+        src[0]  = cm_in[top[0]];
+        src[1]  = cm_in[top[1]];
+        src[2]  = cm_in[top[2]];
+        src[3]  = cm_in[top[3]];
+        src[4]  = cm_in[top[4]];
+        src[5]  = cm_in[top[5]];
+        src[6]  = cm_in[top[6]];
+        src[7]  = cm_in[top[7]];
+        src[8]  = cm_in[top[8]];
+        src[9]  = cm_in[top[9]];
+        src[10] = cm_in[top[10]];
+        src[11] = cm_in[top[11]];
+        src[12] = cm_in[top[12]];
+        src[13] = cm_in[top[13]];
+        src[14] = cm_in[top[14]];
+        src[15] = cm_in[top[15]];
+        src += stride;
+    }
+}
+
 static void pred8x8_vertical_c(uint8_t *src, int stride){
     int i;
     const uint32_t a= ((uint32_t*)(src-stride))[0];
@@ -568,6 +694,23 @@ static void pred8x8_128_dc_c(uint8_t *src, int stride){
     }
 }
 
+static void pred8x8_127_dc_c(uint8_t *src, int stride){
+    int i;
+
+    for(i=0; i<8; i++){
+        ((uint32_t*)(src+i*stride))[0]=
+        ((uint32_t*)(src+i*stride))[1]= 0x01010101U*127U;
+    }
+}
+static void pred8x8_129_dc_c(uint8_t *src, int stride){
+    int i;
+
+    for(i=0; i<8; i++){
+        ((uint32_t*)(src+i*stride))[0]=
+        ((uint32_t*)(src+i*stride))[1]= 0x01010101U*129U;
+    }
+}
+
 static void pred8x8_left_dc_c(uint8_t *src, int stride){
     int i;
     int dc0, dc2;
@@ -745,6 +888,25 @@ static void pred8x8_plane_c(uint8_t *src, int stride){
   }
 }
 
+static void pred8x8_tm_vp8_c(uint8_t *src, int stride){
+    uint8_t *cm = ff_cropTbl + MAX_NEG_CROP - src[-1-stride];
+    uint8_t *top = src-stride;
+    int y;
+
+    for (y = 0; y < 8; y++) {
+        uint8_t *cm_in = cm + src[-1];
+        src[0] = cm_in[top[0]];
+        src[1] = cm_in[top[1]];
+        src[2] = cm_in[top[2]];
+        src[3] = cm_in[top[3]];
+        src[4] = cm_in[top[4]];
+        src[5] = cm_in[top[5]];
+        src[6] = cm_in[top[6]];
+        src[7] = cm_in[top[7]];
+        src += stride;
+    }
+}
+
 #define SRC(x,y) src[(x)+(y)*stride]
 #define PL(y) \
     const int l##y = (SRC(-1,y-1) + 2*SRC(-1,y) + SRC(-1,y+1) + 2) >> 2;
@@ -1075,14 +1237,19 @@ static void pred8x8_horizontal_add_c(uint8_t *pix, const int *block_offset, cons
 
 
 /**
- * Sets the intra prediction function pointers.
+ * Set the intra prediction function pointers.
  */
 void ff_h264_pred_init(H264PredContext *h, int codec_id){
 //    MpegEncContext * const s = &h->s;
 
     if(codec_id != CODEC_ID_RV40){
-        h->pred4x4[VERT_PRED           ]= pred4x4_vertical_c;
-        h->pred4x4[HOR_PRED            ]= pred4x4_horizontal_c;
+        if(codec_id == CODEC_ID_VP8) {
+            h->pred4x4[VERT_PRED       ]= pred4x4_vertical_vp8_c;
+            h->pred4x4[HOR_PRED        ]= pred4x4_horizontal_vp8_c;
+        } else {
+            h->pred4x4[VERT_PRED       ]= pred4x4_vertical_c;
+            h->pred4x4[HOR_PRED        ]= pred4x4_horizontal_c;
+        }
         h->pred4x4[DC_PRED             ]= pred4x4_dc_c;
         if(codec_id == CODEC_ID_SVQ3)
             h->pred4x4[DIAG_DOWN_LEFT_PRED ]= pred4x4_down_left_svq3_c;
@@ -1091,11 +1258,22 @@ void ff_h264_pred_init(H264PredContext *h, int codec_id){
         h->pred4x4[DIAG_DOWN_RIGHT_PRED]= pred4x4_down_right_c;
         h->pred4x4[VERT_RIGHT_PRED     ]= pred4x4_vertical_right_c;
         h->pred4x4[HOR_DOWN_PRED       ]= pred4x4_horizontal_down_c;
-        h->pred4x4[VERT_LEFT_PRED      ]= pred4x4_vertical_left_c;
+        if (codec_id == CODEC_ID_VP8) {
+            h->pred4x4[VERT_LEFT_PRED  ]= pred4x4_vertical_left_vp8_c;
+        } else
+            h->pred4x4[VERT_LEFT_PRED  ]= pred4x4_vertical_left_c;
         h->pred4x4[HOR_UP_PRED         ]= pred4x4_horizontal_up_c;
-        h->pred4x4[LEFT_DC_PRED        ]= pred4x4_left_dc_c;
-        h->pred4x4[TOP_DC_PRED         ]= pred4x4_top_dc_c;
-        h->pred4x4[DC_128_PRED         ]= pred4x4_128_dc_c;
+        if(codec_id != CODEC_ID_VP8) {
+            h->pred4x4[LEFT_DC_PRED    ]= pred4x4_left_dc_c;
+            h->pred4x4[TOP_DC_PRED     ]= pred4x4_top_dc_c;
+            h->pred4x4[DC_128_PRED     ]= pred4x4_128_dc_c;
+        } else {
+            h->pred4x4[TM_VP8_PRED     ]= pred4x4_tm_vp8_c;
+            h->pred4x4[DC_127_PRED     ]= pred4x4_127_dc_c;
+            h->pred4x4[DC_129_PRED     ]= pred4x4_129_dc_c;
+            h->pred4x4[VERT_VP8_PRED   ]= pred4x4_vertical_c;
+            h->pred4x4[HOR_VP8_PRED    ]= pred4x4_horizontal_c;
+        }
     }else{
         h->pred4x4[VERT_PRED           ]= pred4x4_vertical_c;
         h->pred4x4[HOR_PRED            ]= pred4x4_horizontal_c;
@@ -1129,8 +1307,11 @@ void ff_h264_pred_init(H264PredContext *h, int codec_id){
 
     h->pred8x8[VERT_PRED8x8   ]= pred8x8_vertical_c;
     h->pred8x8[HOR_PRED8x8    ]= pred8x8_horizontal_c;
-    h->pred8x8[PLANE_PRED8x8  ]= pred8x8_plane_c;
-    if(codec_id != CODEC_ID_RV40){
+    if (codec_id != CODEC_ID_VP8) {
+        h->pred8x8[PLANE_PRED8x8]= pred8x8_plane_c;
+    } else
+        h->pred8x8[PLANE_PRED8x8]= pred8x8_tm_vp8_c;
+    if(codec_id != CODEC_ID_RV40 && codec_id != CODEC_ID_VP8){
         h->pred8x8[DC_PRED8x8     ]= pred8x8_dc_c;
         h->pred8x8[LEFT_DC_PRED8x8]= pred8x8_left_dc_c;
         h->pred8x8[TOP_DC_PRED8x8 ]= pred8x8_top_dc_c;
@@ -1142,13 +1323,16 @@ void ff_h264_pred_init(H264PredContext *h, int codec_id){
         h->pred8x8[DC_PRED8x8     ]= pred8x8_dc_rv40_c;
         h->pred8x8[LEFT_DC_PRED8x8]= pred8x8_left_dc_rv40_c;
         h->pred8x8[TOP_DC_PRED8x8 ]= pred8x8_top_dc_rv40_c;
+        if (codec_id == CODEC_ID_VP8) {
+            h->pred8x8[DC_127_PRED8x8]= pred8x8_127_dc_c;
+            h->pred8x8[DC_129_PRED8x8]= pred8x8_129_dc_c;
+        }
     }
     h->pred8x8[DC_128_PRED8x8 ]= pred8x8_128_dc_c;
 
     h->pred16x16[DC_PRED8x8     ]= pred16x16_dc_c;
     h->pred16x16[VERT_PRED8x8   ]= pred16x16_vertical_c;
     h->pred16x16[HOR_PRED8x8    ]= pred16x16_horizontal_c;
-    h->pred16x16[PLANE_PRED8x8  ]= pred16x16_plane_c;
     switch(codec_id){
     case CODEC_ID_SVQ3:
        h->pred16x16[PLANE_PRED8x8  ]= pred16x16_plane_svq3_c;
@@ -1156,8 +1340,14 @@ void ff_h264_pred_init(H264PredContext *h, int codec_id){
     case CODEC_ID_RV40:
        h->pred16x16[PLANE_PRED8x8  ]= pred16x16_plane_rv40_c;
        break;
+    case CODEC_ID_VP8:
+       h->pred16x16[PLANE_PRED8x8  ]= pred16x16_tm_vp8_c;
+       h->pred16x16[DC_127_PRED8x8]= pred16x16_127_dc_c;
+       h->pred16x16[DC_129_PRED8x8]= pred16x16_129_dc_c;
+       break;
     default:
        h->pred16x16[PLANE_PRED8x8  ]= pred16x16_plane_c;
+       break;
     }
     h->pred16x16[LEFT_DC_PRED8x8]= pred16x16_left_dc_c;
     h->pred16x16[TOP_DC_PRED8x8 ]= pred16x16_top_dc_c;
@@ -1174,4 +1364,5 @@ void ff_h264_pred_init(H264PredContext *h, int codec_id){
     h->pred16x16_add[ HOR_PRED8x8]= pred16x16_horizontal_add_c;
 
     if (ARCH_ARM) ff_h264_pred_init_arm(h, codec_id);
+    if (HAVE_MMX) ff_h264_pred_init_x86(h, codec_id);
 }
diff --git a/libavcodec/h264pred.h b/libavcodec/h264pred.h
index c52aeaa..db3f580 100644
--- a/libavcodec/h264pred.h
+++ b/libavcodec/h264pred.h
@@ -2,20 +2,20 @@
  * H.26L/H.264/AVC/JVT/14496-10/... encoder/decoder
  * Copyright (c) 2003 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -45,37 +45,55 @@
 #define VERT_LEFT_PRED        7
 #define HOR_UP_PRED           8
 
+// DC edge (not for VP8)
 #define LEFT_DC_PRED          9
 #define TOP_DC_PRED           10
 #define DC_128_PRED           11
 
+// RV40 specific
 #define DIAG_DOWN_LEFT_PRED_RV40_NODOWN   12
 #define HOR_UP_PRED_RV40_NODOWN           13
 #define VERT_LEFT_PRED_RV40_NODOWN        14
 
+// VP8 specific
+#define TM_VP8_PRED           9     ///< "True Motion", used instead of plane
+#define VERT_VP8_PRED         10    ///< for VP8, #VERT_PRED is the average of
+                                    ///< (left col+cur col x2+right col) / 4;
+                                    ///< this is the "unaveraged" one
+#define HOR_VP8_PRED          11    ///< unaveraged version of #HOR_PRED, see
+                                    ///< #VERT_VP8_PRED for details
+#define DC_127_PRED           12
+#define DC_129_PRED           13
+
 #define DC_PRED8x8            0
 #define HOR_PRED8x8           1
 #define VERT_PRED8x8          2
 #define PLANE_PRED8x8         3
 
+// DC edge
 #define LEFT_DC_PRED8x8       4
 #define TOP_DC_PRED8x8        5
 #define DC_128_PRED8x8        6
 
+// H264/SVQ3 (8x8) specific
 #define ALZHEIMER_DC_L0T_PRED8x8 7
 #define ALZHEIMER_DC_0LT_PRED8x8 8
 #define ALZHEIMER_DC_L00_PRED8x8 9
 #define ALZHEIMER_DC_0L0_PRED8x8 10
+
+// VP8 specific
+#define DC_127_PRED8x8        7
+#define DC_129_PRED8x8        8
 //@}
 
 /**
  * Context for storing H.264 prediction functions
  */
 typedef struct H264PredContext{
-    void (*pred4x4  [9+3+3])(uint8_t *src, uint8_t *topright, int stride);//FIXME move to dsp?
+    void (*pred4x4  [9+3+3])(uint8_t *src, const uint8_t *topright, int stride);//FIXME move to dsp?
     void (*pred8x8l [9+3])(uint8_t *src, int topleft, int topright, int stride);
     void (*pred8x8  [4+3+4])(uint8_t *src, int stride);
-    void (*pred16x16[4+3])(uint8_t *src, int stride);
+    void (*pred16x16[4+3+2])(uint8_t *src, int stride);
 
     void (*pred4x4_add  [2])(uint8_t *pix/*align  4*/, const DCTELEM *block/*align 16*/, int stride);
     void (*pred8x8l_add [2])(uint8_t *pix/*align  8*/, const DCTELEM *block/*align 16*/, int stride);
@@ -85,5 +103,6 @@ typedef struct H264PredContext{
 
 void ff_h264_pred_init(H264PredContext *h, int codec_id);
 void ff_h264_pred_init_arm(H264PredContext *h, int codec_id);
+void ff_h264_pred_init_x86(H264PredContext *h, int codec_id);
 
 #endif /* AVCODEC_H264PRED_H */
diff --git a/libavcodec/huffman.c b/libavcodec/huffman.c
index 853fa64..211ea63 100644
--- a/libavcodec/huffman.c
+++ b/libavcodec/huffman.c
@@ -3,20 +3,20 @@
  * huffman tree builder and VLC generator
  * Copyright (c) 2006 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/huffman.h b/libavcodec/huffman.h
index 3c08e6f..4a60187 100644
--- a/libavcodec/huffman.h
+++ b/libavcodec/huffman.h
@@ -3,20 +3,20 @@
  * huffman tree builder and VLC generator
  * Copyright (C) 2007  Aurelien Jacobs <aurel at gnuage.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/huffyuv.c b/libavcodec/huffyuv.c
index 7764c35..183ce0e 100644
--- a/libavcodec/huffyuv.c
+++ b/libavcodec/huffyuv.c
@@ -6,20 +6,20 @@
  * see http://www.pcisys.net/~melanson/codecs/huffyuv.txt for a description of
  * the algorithm used
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -32,6 +32,7 @@
 #include "get_bits.h"
 #include "put_bits.h"
 #include "dsputil.h"
+#include "thread.h"
 
 #define VLC_BITS 11
 
@@ -231,11 +232,12 @@ static void heap_sift(HeapElem *h, int root, int size)
     }
 }
 
-static void generate_len_table(uint8_t *dst, const uint64_t *stats, int size){
-    HeapElem h[size];
-    int up[2*size];
-    int len[2*size];
+static void generate_len_table(uint8_t *dst, const uint64_t *stats){
+    HeapElem h[256];
+    int up[2*256];
+    int len[2*256];
     int offset, i, next;
+    int size = 256;
 
     for(offset=1; ; offset<<=1){
         for(i=0; i<size; i++){
@@ -526,6 +528,28 @@ s->bgr32=1;
 
     return 0;
 }
+
+static av_cold int decode_init_thread_copy(AVCodecContext *avctx)
+{
+    HYuvContext *s = avctx->priv_data;
+    int i;
+
+    avctx->coded_frame= &s->picture;
+    alloc_temp(s);
+
+    for (i = 0; i < 6; i++)
+        s->vlc[i].table = NULL;
+
+    if(s->version==2){
+        if(read_huffman_tables(s, ((uint8_t*)avctx->extradata)+4, avctx->extradata_size) < 0)
+            return -1;
+    }else{
+        if(read_old_huffman_tables(s) < 0)
+            return -1;
+    }
+
+    return 0;
+}
 #endif /* CONFIG_HUFFYUV_DECODER || CONFIG_FFVHUFF_DECODER */
 
 #if CONFIG_HUFFYUV_ENCODER || CONFIG_FFVHUFF_ENCODER
@@ -646,7 +670,7 @@ static av_cold int encode_init(AVCodecContext *avctx)
     }
 
     for(i=0; i<3; i++){
-        generate_len_table(s->len[i], s->stats[i], 256);
+        generate_len_table(s->len[i], s->stats[i]);
 
         if(generate_bits_table(s->bits[i], s->len[i])<0){
             return -1;
@@ -949,10 +973,10 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPac
     s->dsp.bswap_buf((uint32_t*)s->bitstream_buffer, (const uint32_t*)buf, buf_size/4);
 
     if(p->data[0])
-        avctx->release_buffer(avctx, p);
+        ff_thread_release_buffer(avctx, p);
 
     p->reference= 0;
-    if(avctx->get_buffer(avctx, p) < 0){
+    if(ff_thread_get_buffer(avctx, p) < 0){
         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
         return -1;
     }
@@ -1224,7 +1248,7 @@ static int encode_frame(AVCodecContext *avctx, unsigned char *buf, int buf_size,
 
     if(s->context){
         for(i=0; i<3; i++){
-            generate_len_table(s->len[i], s->stats[i], 256);
+            generate_len_table(s->len[i], s->stats[i]);
             if(generate_bits_table(s->bits[i], s->len[i])<0)
                 return -1;
             size+= store_table(s, s->len[i], &buf[size]);
@@ -1415,7 +1439,7 @@ static av_cold int encode_end(AVCodecContext *avctx)
 #endif /* CONFIG_HUFFYUV_ENCODER || CONFIG_FFVHUFF_ENCODER */
 
 #if CONFIG_HUFFYUV_DECODER
-AVCodec huffyuv_decoder = {
+AVCodec ff_huffyuv_decoder = {
     "huffyuv",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_HUFFYUV,
@@ -1424,14 +1448,15 @@ AVCodec huffyuv_decoder = {
     NULL,
     decode_end,
     decode_frame,
-    CODEC_CAP_DR1 | CODEC_CAP_DRAW_HORIZ_BAND,
+    CODEC_CAP_DR1 | CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_FRAME_THREADS,
     NULL,
+    .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
     .long_name = NULL_IF_CONFIG_SMALL("Huffyuv / HuffYUV"),
 };
 #endif
 
 #if CONFIG_FFVHUFF_DECODER
-AVCodec ffvhuff_decoder = {
+AVCodec ff_ffvhuff_decoder = {
     "ffvhuff",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_FFVHUFF,
@@ -1440,14 +1465,15 @@ AVCodec ffvhuff_decoder = {
     NULL,
     decode_end,
     decode_frame,
-    CODEC_CAP_DR1 | CODEC_CAP_DRAW_HORIZ_BAND,
+    CODEC_CAP_DR1 | CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_FRAME_THREADS,
     NULL,
+    .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
     .long_name = NULL_IF_CONFIG_SMALL("Huffyuv FFmpeg variant"),
 };
 #endif
 
 #if CONFIG_HUFFYUV_ENCODER
-AVCodec huffyuv_encoder = {
+AVCodec ff_huffyuv_encoder = {
     "huffyuv",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_HUFFYUV,
@@ -1461,7 +1487,7 @@ AVCodec huffyuv_encoder = {
 #endif
 
 #if CONFIG_FFVHUFF_ENCODER
-AVCodec ffvhuff_encoder = {
+AVCodec ff_ffvhuff_encoder = {
     "ffvhuff",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_FFVHUFF,
diff --git a/libavcodec/idcinvideo.c b/libavcodec/idcinvideo.c
index 203812b..ac56e19 100644
--- a/libavcodec/idcinvideo.c
+++ b/libavcodec/idcinvideo.c
@@ -2,20 +2,20 @@
  * id Quake II CIN Video Decoder
  * Copyright (C) 2003 the ffmpeg project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -72,12 +72,13 @@ typedef struct IdcinContext {
     hnode huff_nodes[256][HUF_TOKENS*2];
     int num_huff_nodes[256];
 
+    uint32_t pal[256];
 } IdcinContext;
 
 /*
  * Find the lowest probability node in a Huffman table, and mark it as
  * being assigned to a higher probability.
- * Returns the node index of the lowest unused node, or -1 if all nodes
+ * @return the node index of the lowest unused node, or -1 if all nodes
  * are used.
  */
 static int huff_smallest_node(hnode *hnodes, int num_hnodes) {
@@ -213,7 +214,7 @@ static int idcin_decode_frame(AVCodecContext *avctx,
     const uint8_t *buf = avpkt->data;
     int buf_size = avpkt->size;
     IdcinContext *s = avctx->priv_data;
-    AVPaletteControl *palette_control = avctx->palctrl;
+    const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, NULL);
 
     s->buf = buf;
     s->size = buf_size;
@@ -228,13 +229,12 @@ static int idcin_decode_frame(AVCodecContext *avctx,
 
     idcin_decode_vlcs(s);
 
-    /* make the palette available on the way out */
-    memcpy(s->frame.data[1], palette_control->palette, PALETTE_COUNT * 4);
-    /* If palette changed inform application*/
-    if (palette_control->palette_changed) {
-        palette_control->palette_changed = 0;
+    if (pal) {
         s->frame.palette_has_changed = 1;
+        memcpy(s->pal, pal, AVPALETTE_SIZE);
     }
+    /* make the palette available on the way out */
+    memcpy(s->frame.data[1], s->pal, AVPALETTE_SIZE);
 
     *data_size = sizeof(AVFrame);
     *(AVFrame*)data = s->frame;
@@ -253,7 +253,7 @@ static av_cold int idcin_decode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec idcin_decoder = {
+AVCodec ff_idcin_decoder = {
     "idcinvideo",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_IDCIN,
diff --git a/libavcodec/iff.c b/libavcodec/iff.c
index 2989bb0..63e1f31 100644
--- a/libavcodec/iff.c
+++ b/libavcodec/iff.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2010 Peter Ross <pross at xvid.org>
  * Copyright (c) 2010 Sebastian Vater <cdgs.basty at googlemail.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,21 +25,101 @@
  * IFF PBM/ILBM bitmap decoder
  */
 
+#include "libavutil/imgutils.h"
 #include "bytestream.h"
 #include "avcodec.h"
 #include "get_bits.h"
-#include "iff.h"
 
 typedef struct {
     AVFrame frame;
     int planesize;
     uint8_t * planebuf;
+    int init; // 1 if buffer and palette data already initialized, 0 otherwise
 } IffContext;
 
+#define LUT8_PART(plane, v)                             \
+    AV_LE2NE64C(UINT64_C(0x0000000)<<32 | v) << plane,  \
+    AV_LE2NE64C(UINT64_C(0x1000000)<<32 | v) << plane,  \
+    AV_LE2NE64C(UINT64_C(0x0010000)<<32 | v) << plane,  \
+    AV_LE2NE64C(UINT64_C(0x1010000)<<32 | v) << plane,  \
+    AV_LE2NE64C(UINT64_C(0x0000100)<<32 | v) << plane,  \
+    AV_LE2NE64C(UINT64_C(0x1000100)<<32 | v) << plane,  \
+    AV_LE2NE64C(UINT64_C(0x0010100)<<32 | v) << plane,  \
+    AV_LE2NE64C(UINT64_C(0x1010100)<<32 | v) << plane,  \
+    AV_LE2NE64C(UINT64_C(0x0000001)<<32 | v) << plane,  \
+    AV_LE2NE64C(UINT64_C(0x1000001)<<32 | v) << plane,  \
+    AV_LE2NE64C(UINT64_C(0x0010001)<<32 | v) << plane,  \
+    AV_LE2NE64C(UINT64_C(0x1010001)<<32 | v) << plane,  \
+    AV_LE2NE64C(UINT64_C(0x0000101)<<32 | v) << plane,  \
+    AV_LE2NE64C(UINT64_C(0x1000101)<<32 | v) << plane,  \
+    AV_LE2NE64C(UINT64_C(0x0010101)<<32 | v) << plane,  \
+    AV_LE2NE64C(UINT64_C(0x1010101)<<32 | v) << plane
+
+#define LUT8(plane) {                           \
+    LUT8_PART(plane, 0x0000000),                \
+    LUT8_PART(plane, 0x1000000),                \
+    LUT8_PART(plane, 0x0010000),                \
+    LUT8_PART(plane, 0x1010000),                \
+    LUT8_PART(plane, 0x0000100),                \
+    LUT8_PART(plane, 0x1000100),                \
+    LUT8_PART(plane, 0x0010100),                \
+    LUT8_PART(plane, 0x1010100),                \
+    LUT8_PART(plane, 0x0000001),                \
+    LUT8_PART(plane, 0x1000001),                \
+    LUT8_PART(plane, 0x0010001),                \
+    LUT8_PART(plane, 0x1010001),                \
+    LUT8_PART(plane, 0x0000101),                \
+    LUT8_PART(plane, 0x1000101),                \
+    LUT8_PART(plane, 0x0010101),                \
+    LUT8_PART(plane, 0x1010101),                \
+}
+
+// 8 planes * 8-bit mask
+static const uint64_t plane8_lut[8][256] = {
+    LUT8(0), LUT8(1), LUT8(2), LUT8(3),
+    LUT8(4), LUT8(5), LUT8(6), LUT8(7),
+};
+
+#define LUT32(plane) {                                \
+             0,          0,          0,          0,   \
+             0,          0,          0, 1 << plane,   \
+             0,          0, 1 << plane,          0,   \
+             0,          0, 1 << plane, 1 << plane,   \
+             0, 1 << plane,          0,          0,   \
+             0, 1 << plane,          0, 1 << plane,   \
+             0, 1 << plane, 1 << plane,          0,   \
+             0, 1 << plane, 1 << plane, 1 << plane,   \
+    1 << plane,          0,          0,          0,   \
+    1 << plane,          0,          0, 1 << plane,   \
+    1 << plane,          0, 1 << plane,          0,   \
+    1 << plane,          0, 1 << plane, 1 << plane,   \
+    1 << plane, 1 << plane,          0,          0,   \
+    1 << plane, 1 << plane,          0, 1 << plane,   \
+    1 << plane, 1 << plane, 1 << plane,          0,   \
+    1 << plane, 1 << plane, 1 << plane, 1 << plane,   \
+}
+
+// 32 planes * 4-bit mask * 4 lookup tables each
+static const uint32_t plane32_lut[32][16*4] = {
+    LUT32( 0), LUT32( 1), LUT32( 2), LUT32( 3),
+    LUT32( 4), LUT32( 5), LUT32( 6), LUT32( 7),
+    LUT32( 8), LUT32( 9), LUT32(10), LUT32(11),
+    LUT32(12), LUT32(13), LUT32(14), LUT32(15),
+    LUT32(16), LUT32(17), LUT32(18), LUT32(19),
+    LUT32(20), LUT32(21), LUT32(22), LUT32(23),
+    LUT32(24), LUT32(25), LUT32(26), LUT32(27),
+    LUT32(28), LUT32(29), LUT32(30), LUT32(31),
+};
+
+// Gray to RGB, required for palette table of grayscale images with bpp < 8
+static av_always_inline uint32_t gray2rgb(const uint32_t x) {
+    return x << 16 | x << 8 | x;
+}
+
 /**
  * Convert CMAP buffer (stored in extradata) to lavc palette format
  */
-int ff_cmap_read_palette(AVCodecContext *avctx, uint32_t *pal)
+static int ff_cmap_read_palette(AVCodecContext *avctx, uint32_t *pal)
 {
     int count, i;
 
@@ -49,12 +129,18 @@ int ff_cmap_read_palette(AVCodecContext *avctx, uint32_t *pal)
     }
 
     count = 1 << avctx->bits_per_coded_sample;
-    if (avctx->extradata_size < count * 3) {
-        av_log(avctx, AV_LOG_ERROR, "palette data underflow\n");
-        return AVERROR_INVALIDDATA;
-    }
-    for (i=0; i < count; i++) {
-        pal[i] = 0xFF000000 | AV_RB24( avctx->extradata + i*3 );
+    // If extradata is smaller than actually needed, fill the remaining with black.
+    count = FFMIN(avctx->extradata_size / 3, count);
+    if (count) {
+        for (i=0; i < count; i++) {
+            pal[i] = 0xFF000000 | AV_RB24( avctx->extradata + i*3 );
+        }
+    } else { // Create gray-scale color palette for bps < 8
+        count = 1 << avctx->bits_per_coded_sample;
+
+        for (i=0; i < count; i++) {
+            pal[i] = 0xFF000000 | gray2rgb((i * 255) >> avctx->bits_per_coded_sample);
+        }
     }
     return 0;
 }
@@ -65,26 +151,25 @@ static av_cold int decode_init(AVCodecContext *avctx)
     int err;
 
     if (avctx->bits_per_coded_sample <= 8) {
-        avctx->pix_fmt = PIX_FMT_PAL8;
+        avctx->pix_fmt = (avctx->bits_per_coded_sample < 8 ||
+                          avctx->extradata_size) ? PIX_FMT_PAL8
+                                                 : PIX_FMT_GRAY8;
     } else if (avctx->bits_per_coded_sample <= 32) {
         avctx->pix_fmt = PIX_FMT_BGR32;
     } else {
         return AVERROR_INVALIDDATA;
     }
 
-    s->planesize = avctx->width >> 3;
+    if ((err = av_image_check_size(avctx->width, avctx->height, 0, avctx)))
+        return err;
+    s->planesize = FFALIGN(avctx->width, 16) >> 3; // Align plane size in bits to word-boundary
     s->planebuf = av_malloc(s->planesize + FF_INPUT_BUFFER_PADDING_SIZE);
     if (!s->planebuf)
         return AVERROR(ENOMEM);
 
     s->frame.reference = 1;
-    if ((err = avctx->get_buffer(avctx, &s->frame) < 0)) {
-        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
-        return err;
-    }
 
-    return avctx->bits_per_coded_sample <= 8 ?
-       ff_cmap_read_palette(avctx, (uint32_t*)s->frame.data[1]) : 0;
+    return 0;
 }
 
 /**
@@ -92,18 +177,16 @@ static av_cold int decode_init(AVCodecContext *avctx)
  * @param dst Destination buffer
  * @param buf Source buffer
  * @param buf_size
- * @param bps bits_per_coded_sample (must be <= 8)
  * @param plane plane number to decode as
  */
-static void decodeplane8(uint8_t *dst, const uint8_t *const buf, int buf_size, int bps, int plane)
+static void decodeplane8(uint8_t *dst, const uint8_t *buf, int buf_size, int plane)
 {
-    GetBitContext gb;
-    int i;
-    const int b = (buf_size * 8) + bps - 1;
-    init_get_bits(&gb, buf, buf_size * 8);
-    for(i = 0; i < b; i++) {
-        dst[i] |= get_bits1(&gb) << plane;
-    }
+    const uint64_t *lut = plane8_lut[plane];
+    do {
+        uint64_t v = AV_RN64A(dst) | lut[*buf++];
+        AV_WN64A(dst, v);
+        dst += 8;
+    } while (--buf_size);
 }
 
 /**
@@ -111,18 +194,55 @@ static void decodeplane8(uint8_t *dst, const uint8_t *const buf, int buf_size, i
  * @param dst Destination buffer
  * @param buf Source buffer
  * @param buf_size
- * @param bps bits_per_coded_sample
  * @param plane plane number to decode as
  */
-static void decodeplane32(uint32_t *dst, const uint8_t *const buf, int buf_size, int bps, int plane)
+static void decodeplane32(uint32_t *dst, const uint8_t *buf, int buf_size, int plane)
 {
-    GetBitContext gb;
-    int i;
-    const int b = (buf_size * 8) + bps - 1;
-    init_get_bits(&gb, buf, buf_size * 8);
-    for(i = 0; i < b; i++) {
-        dst[i] |= get_bits1(&gb) << plane;
+    const uint32_t *lut = plane32_lut[plane];
+    do {
+        unsigned mask = (*buf >> 2) & ~3;
+        dst[0] |= lut[mask++];
+        dst[1] |= lut[mask++];
+        dst[2] |= lut[mask++];
+        dst[3] |= lut[mask];
+        mask = (*buf++ << 2) & 0x3F;
+        dst[4] |= lut[mask++];
+        dst[5] |= lut[mask++];
+        dst[6] |= lut[mask++];
+        dst[7] |= lut[mask];
+        dst += 8;
+    } while (--buf_size);
+}
+
+/**
+ * Decode one complete byterun1 encoded line.
+ *
+ * @param dst the destination buffer where to store decompressed bitstream
+ * @param dst_size the destination plane size in bytes
+ * @param buf the source byterun1 compressed bitstream
+ * @param buf_end the EOF of source byterun1 compressed bitstream
+ * @return number of consumed bytes in byterun1 compressed bitstream
+*/
+static int decode_byterun(uint8_t *dst, int dst_size,
+                          const uint8_t *buf, const uint8_t *const buf_end) {
+    const uint8_t *const buf_start = buf;
+    unsigned x;
+    for (x = 0; x < dst_size && buf < buf_end;) {
+        unsigned length;
+        const int8_t value = *buf++;
+        if (value >= 0) {
+            length = value + 1;
+            memcpy(dst + x, buf, FFMIN3(length, dst_size - x, buf_end - buf));
+            buf += length;
+        } else if (value > -128) {
+            length = -value + 1;
+            memset(dst + x, *buf++, FFMIN(length, dst_size - x));
+        } else { // noop
+            continue;
+        }
+        x += length;
     }
+    return buf - buf_start;
 }
 
 static int decode_frame_ilbm(AVCodecContext *avctx,
@@ -133,30 +253,47 @@ static int decode_frame_ilbm(AVCodecContext *avctx,
     const uint8_t *buf = avpkt->data;
     int buf_size = avpkt->size;
     const uint8_t *buf_end = buf+buf_size;
-    int y, plane;
+    int y, plane, res;
 
-    if (avctx->reget_buffer(avctx, &s->frame) < 0){
+    if (s->init) {
+        if ((res = avctx->reget_buffer(avctx, &s->frame)) < 0) {
+            av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
+            return res;
+        }
+    } else if ((res = avctx->get_buffer(avctx, &s->frame)) < 0) {
         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
-        return -1;
+        return res;
+    } else if (avctx->bits_per_coded_sample <= 8 && avctx->pix_fmt != PIX_FMT_GRAY8) {
+        if ((res = ff_cmap_read_palette(avctx, (uint32_t*)s->frame.data[1])) < 0)
+            return res;
     }
+    s->init = 1;
 
-    if (avctx->pix_fmt == PIX_FMT_PAL8) {
-        for(y = 0; y < avctx->height; y++ ) {
-            uint8_t *row = &s->frame.data[0][ y*s->frame.linesize[0] ];
-            memset(row, 0, avctx->width);
-            for (plane = 0; plane < avctx->bits_per_coded_sample && buf < buf_end; plane++) {
-                decodeplane8(row, buf, FFMIN(s->planesize, buf_end - buf), avctx->bits_per_coded_sample, plane);
-                buf += s->planesize;
+    if (avctx->codec_tag == MKTAG('I','L','B','M')) { // interleaved
+        if (avctx->pix_fmt == PIX_FMT_PAL8 || avctx->pix_fmt == PIX_FMT_GRAY8) {
+            for(y = 0; y < avctx->height; y++ ) {
+                uint8_t *row = &s->frame.data[0][ y*s->frame.linesize[0] ];
+                memset(row, 0, avctx->width);
+                for (plane = 0; plane < avctx->bits_per_coded_sample && buf < buf_end; plane++) {
+                    decodeplane8(row, buf, FFMIN(s->planesize, buf_end - buf), plane);
+                    buf += s->planesize;
+                }
+            }
+        } else { // PIX_FMT_BGR32
+            for(y = 0; y < avctx->height; y++ ) {
+                uint8_t *row = &s->frame.data[0][y*s->frame.linesize[0]];
+                memset(row, 0, avctx->width << 2);
+                for (plane = 0; plane < avctx->bits_per_coded_sample && buf < buf_end; plane++) {
+                    decodeplane32((uint32_t *) row, buf, FFMIN(s->planesize, buf_end - buf), plane);
+                    buf += s->planesize;
+                }
             }
         }
-    } else { // PIX_FMT_BGR32
+    } else if (avctx->pix_fmt == PIX_FMT_PAL8 || avctx->pix_fmt == PIX_FMT_GRAY8) { // IFF-PBM
         for(y = 0; y < avctx->height; y++ ) {
-            uint8_t *row = &s->frame.data[0][y*s->frame.linesize[0]];
-            memset(row, 0, avctx->width << 2);
-            for (plane = 0; plane < avctx->bits_per_coded_sample && buf < buf_end; plane++) {
-                decodeplane32((uint32_t *) row, buf, FFMIN(s->planesize, buf_end - buf), avctx->bits_per_coded_sample, plane);
-                buf += s->planesize;
-            }
+            uint8_t *row = &s->frame.data[0][y * s->frame.linesize[0]];
+            memcpy(row, buf, FFMIN(avctx->width, buf_end - buf));
+            buf += avctx->width + (avctx->width % 2); // padding if odd
         }
     }
 
@@ -173,35 +310,30 @@ static int decode_frame_byterun1(AVCodecContext *avctx,
     const uint8_t *buf = avpkt->data;
     int buf_size = avpkt->size;
     const uint8_t *buf_end = buf+buf_size;
-    int y, plane, x;
+    int y, plane, res;
 
-    if (avctx->reget_buffer(avctx, &s->frame) < 0){
+    if (s->init) {
+        if ((res = avctx->reget_buffer(avctx, &s->frame)) < 0) {
+            av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
+            return res;
+        }
+    } else if ((res = avctx->get_buffer(avctx, &s->frame)) < 0) {
         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
-        return -1;
+        return res;
+    } else if (avctx->bits_per_coded_sample <= 8 && avctx->pix_fmt != PIX_FMT_GRAY8) {
+        if ((res = ff_cmap_read_palette(avctx, (uint32_t*)s->frame.data[1])) < 0)
+            return res;
     }
+    s->init = 1;
 
     if (avctx->codec_tag == MKTAG('I','L','B','M')) { //interleaved
-        if (avctx->pix_fmt == PIX_FMT_PAL8) {
+        if (avctx->pix_fmt == PIX_FMT_PAL8 || avctx->pix_fmt == PIX_FMT_GRAY8) {
             for(y = 0; y < avctx->height ; y++ ) {
                 uint8_t *row = &s->frame.data[0][ y*s->frame.linesize[0] ];
                 memset(row, 0, avctx->width);
                 for (plane = 0; plane < avctx->bits_per_coded_sample; plane++) {
-                    for(x = 0; x < s->planesize && buf < buf_end; ) {
-                        int8_t value = *buf++;
-                        unsigned length;
-                        if (value >= 0) {
-                            length = value + 1;
-                            memcpy(s->planebuf + x, buf, FFMIN3(length, s->planesize - x, buf_end - buf));
-                            buf += length;
-                        } else if (value > -128) {
-                            length = -value + 1;
-                            memset(s->planebuf + x, *buf++, FFMIN(length, s->planesize - x));
-                        } else { //noop
-                            continue;
-                        }
-                        x += length;
-                    }
-                    decodeplane8(row, s->planebuf, s->planesize, avctx->bits_per_coded_sample, plane);
+                    buf += decode_byterun(s->planebuf, s->planesize, buf, buf_end);
+                    decodeplane8(row, s->planebuf, s->planesize, plane);
                 }
             }
         } else { //PIX_FMT_BGR32
@@ -209,43 +341,15 @@ static int decode_frame_byterun1(AVCodecContext *avctx,
                 uint8_t *row = &s->frame.data[0][y*s->frame.linesize[0]];
                 memset(row, 0, avctx->width << 2);
                 for (plane = 0; plane < avctx->bits_per_coded_sample; plane++) {
-                    for(x = 0; x < s->planesize && buf < buf_end; ) {
-                        int8_t value = *buf++;
-                        unsigned length;
-                        if (value >= 0) {
-                            length = value + 1;
-                            memcpy(s->planebuf + x, buf, FFMIN3(length, s->planesize - x, buf_end - buf));
-                            buf += length;
-                        } else if (value > -128) {
-                            length = -value + 1;
-                            memset(s->planebuf + x, *buf++, FFMIN(length, s->planesize - x));
-                        } else { // noop
-                            continue;
-                        }
-                        x += length;
-                    }
-                    decodeplane32((uint32_t *) row, s->planebuf, s->planesize, avctx->bits_per_coded_sample, plane);
+                    buf += decode_byterun(s->planebuf, s->planesize, buf, buf_end);
+                    decodeplane32((uint32_t *) row, s->planebuf, s->planesize, plane);
                 }
             }
         }
     } else {
         for(y = 0; y < avctx->height ; y++ ) {
             uint8_t *row = &s->frame.data[0][y*s->frame.linesize[0]];
-            for(x = 0; x < avctx->width && buf < buf_end; ) {
-                int8_t value = *buf++;
-                unsigned length;
-                if (value >= 0) {
-                    length = value + 1;
-                    memcpy(row + x, buf, FFMIN3(length, buf_end - buf, avctx->width - x));
-                    buf += length;
-                } else if (value > -128) {
-                    length = -value + 1;
-                    memset(row + x, *buf++, FFMIN(length, avctx->width - x));
-                } else { //noop
-                    continue;
-                }
-                x += length;
-            }
+            buf += decode_byterun(row, avctx->width, buf, buf_end);
         }
     }
 
@@ -263,7 +367,7 @@ static av_cold int decode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec iff_ilbm_decoder = {
+AVCodec ff_iff_ilbm_decoder = {
     "iff_ilbm",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_IFF_ILBM,
@@ -276,7 +380,7 @@ AVCodec iff_ilbm_decoder = {
     .long_name = NULL_IF_CONFIG_SMALL("IFF ILBM"),
 };
 
-AVCodec iff_byterun1_decoder = {
+AVCodec ff_iff_byterun1_decoder = {
     "iff_byterun1",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_IFF_BYTERUN1,
diff --git a/libavcodec/iff.h b/libavcodec/iff.h
deleted file mode 100644
index 76db10b..0000000
--- a/libavcodec/iff.h
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * IFF PBM/ILBM bitmap decoder
- * Copyright (c) 2010 Peter Ross <pross at xvid.org>
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-#ifndef AVCODEC_IFF_H
-#define AVCODEC_IFF_H
-
-#include <stdint.h>
-#include "avcodec.h"
-
-int ff_cmap_read_palette(AVCodecContext *avctx, uint32_t *pal);
-
-#endif /* AVCODEC_IFF_H */
diff --git a/libavcodec/iirfilter.c b/libavcodec/iirfilter.c
index 90af431..56d17d2 100644
--- a/libavcodec/iirfilter.c
+++ b/libavcodec/iirfilter.c
@@ -2,20 +2,20 @@
  * IIR filter
  * Copyright (c) 2008 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -47,25 +47,25 @@ typedef struct FFIIRFilterState{
 /// maximum supported filter order
 #define MAXORDER 30
 
-av_cold struct FFIIRFilterCoeffs* ff_iir_filter_init_coeffs(enum IIRFilterType filt_type,
-                                                    enum IIRFilterMode filt_mode,
-                                                    int order, float cutoff_ratio,
-                                                    float stopband, float ripple)
+static int butterworth_init_coeffs(void *avc, struct FFIIRFilterCoeffs *c,
+                                   enum IIRFilterMode filt_mode,
+                                   int order, float cutoff_ratio,
+                                   float stopband)
 {
     int i, j;
-    FFIIRFilterCoeffs *c;
     double wa;
     double p[MAXORDER + 1][2];
 
-    if(filt_type != FF_FILTER_TYPE_BUTTERWORTH || filt_mode != FF_FILTER_MODE_LOWPASS)
-        return NULL;
-    if(order <= 1 || (order & 1) || order > MAXORDER || cutoff_ratio >= 1.0)
-        return NULL;
-
-    c = av_malloc(sizeof(FFIIRFilterCoeffs));
-    c->cx = av_malloc(sizeof(c->cx[0]) * ((order >> 1) + 1));
-    c->cy = av_malloc(sizeof(c->cy[0]) * order);
-    c->order = order;
+    if (filt_mode != FF_FILTER_MODE_LOWPASS) {
+        av_log(avc, AV_LOG_ERROR, "Butterworth filter currently only supports "
+               "low-pass filter mode\n");
+        return -1;
+    }
+    if (order & 1) {
+        av_log(avc, AV_LOG_ERROR, "Butterworth filter currently only supports "
+               "even filter orders\n");
+        return -1;
+    }
 
     wa = 2 * tan(M_PI * 0.5 * cutoff_ratio);
 
@@ -109,7 +109,94 @@ av_cold struct FFIIRFilterCoeffs* ff_iir_filter_init_coeffs(enum IIRFilterType f
     }
     c->gain /= 1 << order;
 
-    return c;
+    return 0;
+}
+
+static int biquad_init_coeffs(void *avc, struct FFIIRFilterCoeffs *c,
+                              enum IIRFilterMode filt_mode, int order,
+                              float cutoff_ratio, float stopband)
+{
+    double cos_w0, sin_w0;
+    double a0, x0, x1;
+
+    if (filt_mode != FF_FILTER_MODE_HIGHPASS &&
+        filt_mode != FF_FILTER_MODE_LOWPASS) {
+        av_log(avc, AV_LOG_ERROR, "Biquad filter currently only supports "
+               "high-pass and low-pass filter modes\n");
+        return -1;
+    }
+    if (order != 2) {
+        av_log(avc, AV_LOG_ERROR, "Biquad filter must have order of 2\n");
+        return -1;
+    }
+
+    cos_w0 = cos(M_PI * cutoff_ratio);
+    sin_w0 = sin(M_PI * cutoff_ratio);
+
+    a0 = 1.0 + (sin_w0 / 2.0);
+
+    if (filt_mode == FF_FILTER_MODE_HIGHPASS) {
+        c->gain  =  ((1.0 + cos_w0) / 2.0)  / a0;
+        x0       =  ((1.0 + cos_w0) / 2.0)  / a0;
+        x1       = (-(1.0 + cos_w0))        / a0;
+    } else { // FF_FILTER_MODE_LOWPASS
+        c->gain  =  ((1.0 - cos_w0) / 2.0)  / a0;
+        x0       =  ((1.0 - cos_w0) / 2.0)  / a0;
+        x1       =   (1.0 - cos_w0)         / a0;
+    }
+    c->cy[0] = (-1.0 + (sin_w0 / 2.0)) / a0;
+    c->cy[1] =  (2.0 *  cos_w0)        / a0;
+
+    // divide by gain to make the x coeffs integers.
+    // during filtering, the delay state will include the gain multiplication
+    c->cx[0] = lrintf(x0 / c->gain);
+    c->cx[1] = lrintf(x1 / c->gain);
+    c->cy[0] /= c->gain;
+    c->cy[1] /= c->gain;
+
+    return 0;
+}
+
+av_cold struct FFIIRFilterCoeffs* ff_iir_filter_init_coeffs(void *avc,
+                                                enum IIRFilterType filt_type,
+                                                enum IIRFilterMode filt_mode,
+                                                int order, float cutoff_ratio,
+                                                float stopband, float ripple)
+{
+    FFIIRFilterCoeffs *c;
+    int ret = 0;
+
+    if (order <= 0 || order > MAXORDER || cutoff_ratio >= 1.0)
+        return NULL;
+
+    FF_ALLOCZ_OR_GOTO(avc, c,     sizeof(FFIIRFilterCoeffs),
+                      init_fail);
+    FF_ALLOC_OR_GOTO (avc, c->cx, sizeof(c->cx[0]) * ((order >> 1) + 1),
+                      init_fail);
+    FF_ALLOC_OR_GOTO (avc, c->cy, sizeof(c->cy[0]) * order,
+                      init_fail);
+    c->order = order;
+
+    switch (filt_type) {
+    case FF_FILTER_TYPE_BUTTERWORTH:
+        ret = butterworth_init_coeffs(avc, c, filt_mode, order, cutoff_ratio,
+                                      stopband);
+        break;
+    case FF_FILTER_TYPE_BIQUAD:
+        ret = biquad_init_coeffs(avc, c, filt_mode, order, cutoff_ratio,
+                                 stopband);
+        break;
+    default:
+        av_log(avc, AV_LOG_ERROR, "filter type is not currently implemented\n");
+        goto init_fail;
+    }
+
+    if (!ret)
+        return c;
+
+init_fail:
+    ff_iir_filter_free_coeffs(c);
+    return NULL;
 }
 
 av_cold struct FFIIRFilterState* ff_iir_filter_init_state(int order)
@@ -118,48 +205,96 @@ av_cold struct FFIIRFilterState* ff_iir_filter_init_state(int order)
     return s;
 }
 
-#define FILTER(i0, i1, i2, i3)                    \
-    in =   *src * c->gain                         \
-         + c->cy[0]*s->x[i0] + c->cy[1]*s->x[i1]  \
-         + c->cy[2]*s->x[i2] + c->cy[3]*s->x[i3]; \
-    res =  (s->x[i0] + in      )*1                \
-         + (s->x[i1] + s->x[i3])*4                \
-         +  s->x[i2]            *6;               \
-    *dst = av_clip_int16(lrintf(res));            \
-    s->x[i0] = in;                                \
-    src += sstep;                                 \
-    dst += dstep;                                 \
-
-void ff_iir_filter(const struct FFIIRFilterCoeffs *c, struct FFIIRFilterState *s, int size, const int16_t *src, int sstep, int16_t *dst, int dstep)
-{
-    int i;
+#define CONV_S16(dest, source) dest = av_clip_int16(lrintf(source));
 
-    if(c->order == 4){
-        for(i = 0; i < size; i += 4){
-            float in, res;
+#define CONV_FLT(dest, source) dest = source;
 
-            FILTER(0, 1, 2, 3);
-            FILTER(1, 2, 3, 0);
-            FILTER(2, 3, 0, 1);
-            FILTER(3, 0, 1, 2);
-        }
-    }else{
-        for(i = 0; i < size; i++){
-            int j;
-            float in, res;
-            in = *src * c->gain;
-            for(j = 0; j < c->order; j++)
-                in += c->cy[j] * s->x[j];
-            res = s->x[0] + in + s->x[c->order >> 1] * c->cx[c->order >> 1];
-            for(j = 1; j < c->order >> 1; j++)
-                res += (s->x[j] + s->x[c->order - j]) * c->cx[j];
-            for(j = 0; j < c->order - 1; j++)
-                s->x[j] = s->x[j + 1];
-            *dst = av_clip_int16(lrintf(res));
-            s->x[c->order - 1] = in;
-            src += sstep;
-            dst += sstep;
-        }
+#define FILTER_BW_O4_1(i0, i1, i2, i3, fmt)         \
+    in = *src0 * c->gain                            \
+         + c->cy[0]*s->x[i0] + c->cy[1]*s->x[i1]    \
+         + c->cy[2]*s->x[i2] + c->cy[3]*s->x[i3];   \
+    res =  (s->x[i0] + in      )*1                  \
+         + (s->x[i1] + s->x[i3])*4                  \
+         +  s->x[i2]            *6;                 \
+    CONV_##fmt(*dst0, res)                          \
+    s->x[i0] = in;                                  \
+    src0 += sstep;                                  \
+    dst0 += dstep;
+
+#define FILTER_BW_O4(type, fmt) {           \
+    int i;                                  \
+    const type *src0 = src;                 \
+    type       *dst0 = dst;                 \
+    for (i = 0; i < size; i += 4) {         \
+        float in, res;                      \
+        FILTER_BW_O4_1(0, 1, 2, 3, fmt);    \
+        FILTER_BW_O4_1(1, 2, 3, 0, fmt);    \
+        FILTER_BW_O4_1(2, 3, 0, 1, fmt);    \
+        FILTER_BW_O4_1(3, 0, 1, 2, fmt);    \
+    }                                       \
+}
+
+#define FILTER_DIRECT_FORM_II(type, fmt) {                                  \
+    int i;                                                                  \
+    const type *src0 = src;                                                 \
+    type       *dst0 = dst;                                                 \
+    for (i = 0; i < size; i++) {                                            \
+        int j;                                                              \
+        float in, res;                                                      \
+        in = *src0 * c->gain;                                               \
+        for(j = 0; j < c->order; j++)                                       \
+            in += c->cy[j] * s->x[j];                                       \
+        res = s->x[0] + in + s->x[c->order >> 1] * c->cx[c->order >> 1];    \
+        for(j = 1; j < c->order >> 1; j++)                                  \
+            res += (s->x[j] + s->x[c->order - j]) * c->cx[j];               \
+        for(j = 0; j < c->order - 1; j++)                                   \
+            s->x[j] = s->x[j + 1];                                          \
+        CONV_##fmt(*dst0, res)                                              \
+        s->x[c->order - 1] = in;                                            \
+        src0 += sstep;                                                      \
+        dst0 += dstep;                                                      \
+    }                                                                       \
+}
+
+#define FILTER_O2(type, fmt) {                                              \
+    int i;                                                                  \
+    const type *src0 = src;                                                 \
+    type       *dst0 = dst;                                                 \
+    for (i = 0; i < size; i++) {                                            \
+        float in = *src0   * c->gain  +                                     \
+                   s->x[0] * c->cy[0] +                                     \
+                   s->x[1] * c->cy[1];                                      \
+        CONV_##fmt(*dst0, s->x[0] + in + s->x[1] * c->cx[1])                \
+        s->x[0] = s->x[1];                                                  \
+        s->x[1] = in;                                                       \
+        src0 += sstep;                                                      \
+        dst0 += dstep;                                                      \
+    }                                                                       \
+}
+
+void ff_iir_filter(const struct FFIIRFilterCoeffs *c,
+                   struct FFIIRFilterState *s, int size,
+                   const int16_t *src, int sstep, int16_t *dst, int dstep)
+{
+    if (c->order == 2) {
+        FILTER_O2(int16_t, S16)
+    } else if (c->order == 4) {
+        FILTER_BW_O4(int16_t, S16)
+    } else {
+        FILTER_DIRECT_FORM_II(int16_t, S16)
+    }
+}
+
+void ff_iir_filter_flt(const struct FFIIRFilterCoeffs *c,
+                       struct FFIIRFilterState *s, int size,
+                       const float *src, int sstep, float *dst, int dstep)
+{
+    if (c->order == 2) {
+        FILTER_O2(float, FLT)
+    } else if (c->order == 4) {
+        FILTER_BW_O4(float, FLT)
+    } else {
+        FILTER_DIRECT_FORM_II(float, FLT)
     }
 }
 
diff --git a/libavcodec/iirfilter.h b/libavcodec/iirfilter.h
index f660955..bc65a96 100644
--- a/libavcodec/iirfilter.h
+++ b/libavcodec/iirfilter.h
@@ -2,20 +2,20 @@
  * IIR filter
  * Copyright (c) 2008 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -34,6 +34,7 @@ struct FFIIRFilterState;
 
 enum IIRFilterType{
     FF_FILTER_TYPE_BESSEL,
+    FF_FILTER_TYPE_BIQUAD,
     FF_FILTER_TYPE_BUTTERWORTH,
     FF_FILTER_TYPE_CHEBYSHEV,
     FF_FILTER_TYPE_ELLIPTIC,
@@ -49,6 +50,8 @@ enum IIRFilterMode{
 /**
  * Initialize filter coefficients.
  *
+ * @param avc          a pointer to an arbitrary struct of which the first
+ *                     field is a pointer to an AVClass struct
  * @param filt_type    filter type (e.g. Butterworth)
  * @param filt_mode    filter mode (e.g. lowpass)
  * @param order        filter order
@@ -58,10 +61,11 @@ enum IIRFilterMode{
  *
  * @return pointer to filter coefficients structure or NULL if filter cannot be created
  */
-struct FFIIRFilterCoeffs* ff_iir_filter_init_coeffs(enum IIRFilterType filt_type,
-                                                    enum IIRFilterMode filt_mode,
-                                                    int order, float cutoff_ratio,
-                                                    float stopband, float ripple);
+struct FFIIRFilterCoeffs* ff_iir_filter_init_coeffs(void *avc,
+                                                enum IIRFilterType filt_type,
+                                                enum IIRFilterMode filt_mode,
+                                                int order, float cutoff_ratio,
+                                                float stopband, float ripple);
 
 /**
  * Create new filter state.
@@ -87,7 +91,7 @@ void ff_iir_filter_free_coeffs(struct FFIIRFilterCoeffs *coeffs);
 void ff_iir_filter_free_state(struct FFIIRFilterState *state);
 
 /**
- * Perform lowpass filtering on input samples.
+ * Perform IIR filtering on signed 16-bit input samples.
  *
  * @param coeffs pointer to filter coefficients
  * @param state  pointer to filter state
@@ -100,4 +104,19 @@ void ff_iir_filter_free_state(struct FFIIRFilterState *state);
 void ff_iir_filter(const struct FFIIRFilterCoeffs *coeffs, struct FFIIRFilterState *state,
                    int size, const int16_t *src, int sstep, int16_t *dst, int dstep);
 
+/**
+ * Perform IIR filtering on floating-point input samples.
+ *
+ * @param coeffs pointer to filter coefficients
+ * @param state  pointer to filter state
+ * @param size   input length
+ * @param src    source samples
+ * @param sstep  source stride
+ * @param dst    filtered samples (destination may be the same as input)
+ * @param dstep  destination stride
+ */
+void ff_iir_filter_flt(const struct FFIIRFilterCoeffs *coeffs,
+                       struct FFIIRFilterState *state, int size,
+                       const float *src, int sstep, float *dst, int dstep);
+
 #endif /* AVCODEC_IIRFILTER_H */
diff --git a/libavcodec/imc.c b/libavcodec/imc.c
index 2a420f5..e48a709 100644
--- a/libavcodec/imc.c
+++ b/libavcodec/imc.c
@@ -4,20 +4,20 @@
  * Copyright (c) 2006 Benjamin Larsson
  * Copyright (c) 2006 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -40,6 +40,8 @@
 #include "get_bits.h"
 #include "dsputil.h"
 #include "fft.h"
+#include "libavutil/audioconvert.h"
+#include "sinewin.h"
 
 #include "imcdata.h"
 
@@ -87,7 +89,7 @@ typedef struct {
     DSPContext dsp;
     FFTContext fft;
     DECLARE_ALIGNED(16, FFTComplex, samples)[COEFFS/2];
-    DECLARE_ALIGNED(16, float, out_samples)[COEFFS];
+    float *out_samples;
 } IMCContext;
 
 static VLC huffman_vlc[4][4];
@@ -116,8 +118,8 @@ static av_cold int imc_decode_init(AVCodecContext * avctx)
     for(i = 0; i < COEFFS; i++)
         q->mdct_sine_window[i] *= sqrt(2.0);
     for(i = 0; i < COEFFS/2; i++){
-        q->post_cos[i] = cos(i / 256.0 * M_PI);
-        q->post_sin[i] = sin(i / 256.0 * M_PI);
+        q->post_cos[i] = (1.0f / 32768) * cos(i / 256.0 * M_PI);
+        q->post_sin[i] = (1.0f / 32768) * sin(i / 256.0 * M_PI);
 
         r1 = sin((i * 4.0 + 1.0) / 1024.0 * M_PI);
         r2 = cos((i * 4.0 + 1.0) / 1024.0 * M_PI);
@@ -156,8 +158,8 @@ static av_cold int imc_decode_init(AVCodecContext * avctx)
 
     ff_fft_init(&q->fft, 7, 1);
     dsputil_init(&q->dsp, avctx);
-    avctx->sample_fmt = SAMPLE_FMT_S16;
-    avctx->channel_layout = (avctx->channels==2) ? CH_LAYOUT_STEREO : CH_LAYOUT_MONO;
+    avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
+    avctx->channel_layout = (avctx->channels==2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;
     return 0;
 }
 
@@ -362,7 +364,7 @@ static int bit_allocation (IMCContext* q, int stream_format_code, int freebits,
         iacc = 0;
 
         for(j = (stream_format_code & 0x2)?4:0; j < BANDS; j++) {
-            cwlen = av_clip((int)((q->flcoeffs4[j] * 0.5) - summa + 0.5), 0, 6);
+            cwlen = av_clipf(((q->flcoeffs4[j] * 0.5) - summa + 0.5), 0, 6);
 
             q->bitsBandT[j] = cwlen;
             summer += q->bandWidthT[j] * cwlen;
@@ -563,8 +565,8 @@ static void imc_imdct256(IMCContext *q) {
     }
 
     /* FFT */
-    ff_fft_permute(&q->fft, q->samples);
-    ff_fft_calc (&q->fft, q->samples);
+    q->fft.fft_permute(&q->fft, q->samples);
+    q->fft.fft_calc   (&q->fft, q->samples);
 
     /* postrotation, window and reorder */
     for(i = 0; i < COEFFS/2; i++){
@@ -660,8 +662,9 @@ static int imc_decode_frame(AVCodecContext * avctx,
         return -1;
     }
     for(i = 0; i < IMC_BLOCK_SIZE / 2; i++)
-        buf16[i] = bswap_16(((const uint16_t*)buf)[i]);
+        buf16[i] = av_bswap16(((const uint16_t*)buf)[i]);
 
+    q->out_samples = data;
     init_get_bits(&q->gb, (const uint8_t*)buf16, IMC_BLOCK_SIZE * 8);
 
     /* Check the frame header */
@@ -805,9 +808,7 @@ static int imc_decode_frame(AVCodecContext * avctx,
 
     imc_imdct256(q);
 
-    q->dsp.float_to_int16(data, q->out_samples, COEFFS);
-
-    *data_size = COEFFS * sizeof(int16_t);
+    *data_size = COEFFS * sizeof(float);
 
     return IMC_BLOCK_SIZE;
 }
@@ -822,7 +823,7 @@ static av_cold int imc_decode_close(AVCodecContext * avctx)
 }
 
 
-AVCodec imc_decoder = {
+AVCodec ff_imc_decoder = {
     .name = "imc",
     .type = AVMEDIA_TYPE_AUDIO,
     .id = CODEC_ID_IMC,
diff --git a/libavcodec/imcdata.h b/libavcodec/imcdata.h
index 64e7c71..8e99391 100644
--- a/libavcodec/imcdata.h
+++ b/libavcodec/imcdata.h
@@ -4,20 +4,20 @@
  * Copyright (c) 2006 Benjamin Larsson
  * Copyright (c) 2006 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/imgconvert.c b/libavcodec/imgconvert.c
index 8f789c4..09ccdbc 100644
--- a/libavcodec/imgconvert.c
+++ b/libavcodec/imgconvert.c
@@ -2,20 +2,20 @@
  * Misc image conversion routines
  * Copyright (c) 2001, 2002, 2003 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -32,13 +32,13 @@
 
 #include "avcodec.h"
 #include "dsputil.h"
-#include "colorspace.h"
 #include "internal.h"
 #include "imgconvert.h"
+#include "libavutil/colorspace.h"
 #include "libavutil/pixdesc.h"
+#include "libavutil/imgutils.h"
 
-#if HAVE_MMX
-#include "x86/mmx.h"
+#if HAVE_MMX && HAVE_YASM
 #include "x86/dsputil_mmx.h"
 #endif
 
@@ -54,6 +54,14 @@
 #define FF_PIXEL_PACKED   1 /**< only one components containing all the channels */
 #define FF_PIXEL_PALETTE  2  /**< one components containing indexes for a palette */
 
+#if HAVE_MMX && HAVE_YASM
+#define deinterlace_line_inplace ff_deinterlace_line_inplace_mmx
+#define deinterlace_line         ff_deinterlace_line_mmx
+#else
+#define deinterlace_line_inplace deinterlace_line_inplace_c
+#define deinterlace_line         deinterlace_line_c
+#endif
+
 typedef struct PixFmtInfo {
     uint8_t nb_channels;     /**< number of channels (including alpha) */
     uint8_t color_type;      /**< color type (see FF_COLOR_xxx constants) */
@@ -411,7 +419,7 @@ void avcodec_get_chroma_sub_sample(enum PixelFormat pix_fmt, int *h_shift, int *
 
 const char *avcodec_get_pix_fmt_name(enum PixelFormat pix_fmt)
 {
-    if (pix_fmt < 0 || pix_fmt >= PIX_FMT_NB)
+    if ((unsigned)pix_fmt >= PIX_FMT_NB)
         return NULL;
     else
         return av_pix_fmt_descriptors[pix_fmt].name;
@@ -422,291 +430,77 @@ enum PixelFormat avcodec_get_pix_fmt(const char *name)
 {
     return av_get_pix_fmt(name);
 }
-#endif
 
 void avcodec_pix_fmt_string (char *buf, int buf_size, enum PixelFormat pix_fmt)
 {
-    /* print header */
-    if (pix_fmt < 0)
-        snprintf (buf, buf_size,
-                  "name      " " nb_channels" " depth" " is_alpha"
-            );
-    else{
-        PixFmtInfo info= pix_fmt_info[pix_fmt];
-
-        char is_alpha_char= info.is_alpha ? 'y' : 'n';
-
-        snprintf (buf, buf_size,
-                  "%-11s %5d %9d %6c",
-                  av_pix_fmt_descriptors[pix_fmt].name,
-                  info.nb_channels,
-                  info.depth,
-                  is_alpha_char
-            );
-    }
+    av_get_pix_fmt_string(buf, buf_size, pix_fmt);
 }
+#endif
 
 int ff_is_hwaccel_pix_fmt(enum PixelFormat pix_fmt)
 {
     return av_pix_fmt_descriptors[pix_fmt].flags & PIX_FMT_HWACCEL;
 }
 
+#if LIBAVCODEC_VERSION_MAJOR < 53
 int ff_set_systematic_pal(uint32_t pal[256], enum PixelFormat pix_fmt){
-    int i;
-
-    for(i=0; i<256; i++){
-        int r,g,b;
-
-        switch(pix_fmt) {
-        case PIX_FMT_RGB8:
-            r= (i>>5    )*36;
-            g= ((i>>2)&7)*36;
-            b= (i&3     )*85;
-            break;
-        case PIX_FMT_BGR8:
-            b= (i>>6    )*85;
-            g= ((i>>3)&7)*36;
-            r= (i&7     )*36;
-            break;
-        case PIX_FMT_RGB4_BYTE:
-            r= (i>>3    )*255;
-            g= ((i>>1)&3)*85;
-            b= (i&1     )*255;
-            break;
-        case PIX_FMT_BGR4_BYTE:
-            b= (i>>3    )*255;
-            g= ((i>>1)&3)*85;
-            r= (i&1     )*255;
-            break;
-        case PIX_FMT_GRAY8:
-            r=b=g= i;
-            break;
-        default:
-            return -1;
-        }
-        pal[i] =  b + (g<<8) + (r<<16);
-    }
-
-    return 0;
+    return ff_set_systematic_pal2(pal, pix_fmt);
 }
 
 int ff_fill_linesize(AVPicture *picture, enum PixelFormat pix_fmt, int width)
 {
-    int i;
-    const AVPixFmtDescriptor *desc = &av_pix_fmt_descriptors[pix_fmt];
-    int max_plane_step     [4];
-    int max_plane_step_comp[4];
-
-    memset(picture->linesize, 0, sizeof(picture->linesize));
-
-    if (desc->flags & PIX_FMT_HWACCEL)
-        return -1;
-
-    if (desc->flags & PIX_FMT_BITSTREAM) {
-        picture->linesize[0] = (width * (desc->comp[0].step_minus1+1) + 7) >> 3;
-        return 0;
-    }
-
-    memset(max_plane_step     , 0, sizeof(max_plane_step     ));
-    memset(max_plane_step_comp, 0, sizeof(max_plane_step_comp));
-    for (i = 0; i < 4; i++) {
-        const AVComponentDescriptor *comp = &(desc->comp[i]);
-        if ((comp->step_minus1+1) > max_plane_step[comp->plane]) {
-            max_plane_step     [comp->plane] = comp->step_minus1+1;
-            max_plane_step_comp[comp->plane] = i;
-        }
-    }
-
-    for (i = 0; i < 4; i++) {
-        int s = (max_plane_step_comp[i] == 1 || max_plane_step_comp[i] == 2) ? desc->log2_chroma_w : 0;
-        picture->linesize[i] = max_plane_step[i] * (((width + (1 << s) - 1)) >> s);
-    }
-
-    return 0;
+    return av_image_fill_linesizes(picture->linesize, pix_fmt, width);
 }
 
 int ff_fill_pointer(AVPicture *picture, uint8_t *ptr, enum PixelFormat pix_fmt,
                     int height)
 {
-    int size, h2, size2;
-    const AVPixFmtDescriptor *desc = &av_pix_fmt_descriptors[pix_fmt];
-
-    size = picture->linesize[0] * height;
-    switch(pix_fmt) {
-    case PIX_FMT_YUV420P:
-    case PIX_FMT_YUV422P:
-    case PIX_FMT_YUV444P:
-    case PIX_FMT_YUV410P:
-    case PIX_FMT_YUV411P:
-    case PIX_FMT_YUV440P:
-    case PIX_FMT_YUVJ420P:
-    case PIX_FMT_YUVJ422P:
-    case PIX_FMT_YUVJ444P:
-    case PIX_FMT_YUVJ440P:
-    case PIX_FMT_YUV420P16LE:
-    case PIX_FMT_YUV422P16LE:
-    case PIX_FMT_YUV444P16LE:
-    case PIX_FMT_YUV420P16BE:
-    case PIX_FMT_YUV422P16BE:
-    case PIX_FMT_YUV444P16BE:
-        h2 = (height + (1 << desc->log2_chroma_h) - 1) >> desc->log2_chroma_h;
-        size2 = picture->linesize[1] * h2;
-        picture->data[0] = ptr;
-        picture->data[1] = picture->data[0] + size;
-        picture->data[2] = picture->data[1] + size2;
-        picture->data[3] = NULL;
-        return size + 2 * size2;
-    case PIX_FMT_YUVA420P:
-        h2 = (height + (1 << desc->log2_chroma_h) - 1) >> desc->log2_chroma_h;
-        size2 = picture->linesize[1] * h2;
-        picture->data[0] = ptr;
-        picture->data[1] = picture->data[0] + size;
-        picture->data[2] = picture->data[1] + size2;
-        picture->data[3] = picture->data[1] + size2 + size2;
-        return 2 * size + 2 * size2;
-    case PIX_FMT_NV12:
-    case PIX_FMT_NV21:
-        h2 = (height + (1 << desc->log2_chroma_h) - 1) >> desc->log2_chroma_h;
-        size2 = picture->linesize[1] * h2;
-        picture->data[0] = ptr;
-        picture->data[1] = picture->data[0] + size;
-        picture->data[2] = NULL;
-        picture->data[3] = NULL;
-        return size + size2;
-    case PIX_FMT_RGB24:
-    case PIX_FMT_BGR24:
-    case PIX_FMT_ARGB:
-    case PIX_FMT_ABGR:
-    case PIX_FMT_RGBA:
-    case PIX_FMT_BGRA:
-    case PIX_FMT_RGB48BE:
-    case PIX_FMT_RGB48LE:
-    case PIX_FMT_GRAY16BE:
-    case PIX_FMT_GRAY16LE:
-    case PIX_FMT_BGR444BE:
-    case PIX_FMT_BGR444LE:
-    case PIX_FMT_BGR555BE:
-    case PIX_FMT_BGR555LE:
-    case PIX_FMT_BGR565BE:
-    case PIX_FMT_BGR565LE:
-    case PIX_FMT_RGB444BE:
-    case PIX_FMT_RGB444LE:
-    case PIX_FMT_RGB555BE:
-    case PIX_FMT_RGB555LE:
-    case PIX_FMT_RGB565BE:
-    case PIX_FMT_RGB565LE:
-    case PIX_FMT_YUYV422:
-    case PIX_FMT_UYVY422:
-    case PIX_FMT_UYYVYY411:
-    case PIX_FMT_RGB4:
-    case PIX_FMT_BGR4:
-    case PIX_FMT_MONOWHITE:
-    case PIX_FMT_MONOBLACK:
-    case PIX_FMT_Y400A:
-        picture->data[0] = ptr;
-        picture->data[1] = NULL;
-        picture->data[2] = NULL;
-        picture->data[3] = NULL;
-        return size;
-    case PIX_FMT_PAL8:
-    case PIX_FMT_RGB8:
-    case PIX_FMT_BGR8:
-    case PIX_FMT_RGB4_BYTE:
-    case PIX_FMT_BGR4_BYTE:
-    case PIX_FMT_GRAY8:
-        size2 = (size + 3) & ~3;
-        picture->data[0] = ptr;
-        picture->data[1] = ptr + size2; /* palette is stored here as 256 32 bit words */
-        picture->data[2] = NULL;
-        picture->data[3] = NULL;
-        return size2 + 256 * 4;
-    default:
-        picture->data[0] = NULL;
-        picture->data[1] = NULL;
-        picture->data[2] = NULL;
-        picture->data[3] = NULL;
-        return -1;
-    }
+    return av_image_fill_pointers(picture->data, pix_fmt, height, ptr, picture->linesize);
 }
+#endif
 
 int avpicture_fill(AVPicture *picture, uint8_t *ptr,
                    enum PixelFormat pix_fmt, int width, int height)
 {
+    int ret;
 
-    if(avcodec_check_dimensions(NULL, width, height))
-        return -1;
+    if ((ret = av_image_check_size(width, height, 0, NULL)) < 0)
+        return ret;
 
-    if (ff_fill_linesize(picture, pix_fmt, width))
-        return -1;
+    if ((ret = av_image_fill_linesizes(picture->linesize, pix_fmt, width)) < 0)
+        return ret;
 
-    return ff_fill_pointer(picture, ptr, pix_fmt, height);
+    return av_image_fill_pointers(picture->data, pix_fmt, height, ptr, picture->linesize);
 }
 
 int avpicture_layout(const AVPicture* src, enum PixelFormat pix_fmt, int width, int height,
                      unsigned char *dest, int dest_size)
 {
-    const PixFmtInfo* pf = &pix_fmt_info[pix_fmt];
+    int i, j, nb_planes = 0, linesizes[4];
     const AVPixFmtDescriptor *desc = &av_pix_fmt_descriptors[pix_fmt];
-    int i, j, w, ow, h, oh, data_planes;
-    const unsigned char* s;
     int size = avpicture_get_size(pix_fmt, width, height);
 
     if (size > dest_size || size < 0)
-        return -1;
+        return AVERROR(EINVAL);
 
-    if (pf->pixel_type == FF_PIXEL_PACKED || pf->pixel_type == FF_PIXEL_PALETTE) {
-        if (pix_fmt == PIX_FMT_YUYV422 ||
-            pix_fmt == PIX_FMT_UYVY422 ||
-            pix_fmt == PIX_FMT_BGR565BE ||
-            pix_fmt == PIX_FMT_BGR565LE ||
-            pix_fmt == PIX_FMT_BGR555BE ||
-            pix_fmt == PIX_FMT_BGR555LE ||
-            pix_fmt == PIX_FMT_BGR444BE ||
-            pix_fmt == PIX_FMT_BGR444LE ||
-            pix_fmt == PIX_FMT_RGB565BE ||
-            pix_fmt == PIX_FMT_RGB565LE ||
-            pix_fmt == PIX_FMT_RGB555BE ||
-            pix_fmt == PIX_FMT_RGB555LE ||
-            pix_fmt == PIX_FMT_RGB444BE ||
-            pix_fmt == PIX_FMT_RGB444LE)
-            w = width * 2;
-        else if (pix_fmt == PIX_FMT_UYYVYY411)
-            w = width + width/2;
-        else if (pix_fmt == PIX_FMT_PAL8)
-            w = width;
-        else
-            w = width * (pf->depth * pf->nb_channels / 8);
-
-        data_planes = 1;
-        h = height;
-    } else {
-        data_planes = pf->nb_channels;
-        w = (width*pf->depth + 7)/8;
-        h = height;
-    }
+    for (i = 0; i < desc->nb_components; i++)
+        nb_planes = FFMAX(desc->comp[i].plane, nb_planes);
+    nb_planes++;
 
-    ow = w;
-    oh = h;
+    av_image_fill_linesizes(linesizes, pix_fmt, width);
+    for (i = 0; i < nb_planes; i++) {
+        int h, shift = (i == 1 || i == 2) ? desc->log2_chroma_h : 0;
+        const unsigned char *s = src->data[i];
+        h = (height + (1 << shift) - 1) >> shift;
 
-    for (i=0; i<data_planes; i++) {
-        if (i == 1) {
-            w = (- ((-width) >> desc->log2_chroma_w) * pf->depth + 7) / 8;
-            h = -((-height) >> desc->log2_chroma_h);
-            if (pix_fmt == PIX_FMT_NV12 || pix_fmt == PIX_FMT_NV21)
-                w <<= 1;
-        } else if (i == 3) {
-            w = ow;
-            h = oh;
-        }
-        s = src->data[i];
-        for(j=0; j<h; j++) {
-            memcpy(dest, s, w);
-            dest += w;
+        for (j = 0; j < h; j++) {
+            memcpy(dest, s, linesizes[i]);
+            dest += linesizes[i];
             s += src->linesize[i];
         }
     }
 
-    if (pf->pixel_type == FF_PIXEL_PALETTE)
+    if (desc->flags & PIX_FMT_PAL)
         memcpy((unsigned char *)(((size_t)dest + 3) & ~3), src->data[1], 256 * 4);
 
     return size;
@@ -715,7 +509,7 @@ int avpicture_layout(const AVPicture* src, enum PixelFormat pix_fmt, int width,
 int avpicture_get_size(enum PixelFormat pix_fmt, int width, int height)
 {
     AVPicture dummy_pict;
-    if(avcodec_check_dimensions(NULL, width, height))
+    if(av_image_check_size(width, height, 0, NULL))
         return -1;
     switch (pix_fmt) {
     case PIX_FMT_RGB8:
@@ -899,99 +693,33 @@ enum PixelFormat avcodec_find_best_pix_fmt(int64_t pix_fmt_mask, enum PixelForma
     return dst_pix_fmt;
 }
 
+#if LIBAVCODEC_VERSION_MAJOR < 53
 void ff_img_copy_plane(uint8_t *dst, int dst_wrap,
                            const uint8_t *src, int src_wrap,
                            int width, int height)
 {
-    if((!dst) || (!src))
-        return;
-    for(;height > 0; height--) {
-        memcpy(dst, src, width);
-        dst += dst_wrap;
-        src += src_wrap;
-    }
+    av_image_copy_plane(dst, dst_wrap, src, src_wrap, width, height);
 }
 
 int ff_get_plane_bytewidth(enum PixelFormat pix_fmt, int width, int plane)
 {
-    int bits;
-    const PixFmtInfo *pf = &pix_fmt_info[pix_fmt];
-    const AVPixFmtDescriptor *desc = &av_pix_fmt_descriptors[pix_fmt];
-
-    pf = &pix_fmt_info[pix_fmt];
-    switch(pf->pixel_type) {
-    case FF_PIXEL_PACKED:
-        switch(pix_fmt) {
-        case PIX_FMT_YUYV422:
-        case PIX_FMT_UYVY422:
-        case PIX_FMT_RGB565BE:
-        case PIX_FMT_RGB565LE:
-        case PIX_FMT_RGB555BE:
-        case PIX_FMT_RGB555LE:
-        case PIX_FMT_RGB444BE:
-        case PIX_FMT_RGB444LE:
-        case PIX_FMT_BGR565BE:
-        case PIX_FMT_BGR565LE:
-        case PIX_FMT_BGR555BE:
-        case PIX_FMT_BGR555LE:
-        case PIX_FMT_BGR444BE:
-        case PIX_FMT_BGR444LE:
-            bits = 16;
-            break;
-        case PIX_FMT_UYYVYY411:
-            bits = 12;
-            break;
-        default:
-            bits = pf->depth * pf->nb_channels;
-            break;
-        }
-        return (width * bits + 7) >> 3;
-        break;
-    case FF_PIXEL_PLANAR:
-            if (plane == 1 || plane == 2)
-                width= -((-width)>>desc->log2_chroma_w);
-
-            return (width * pf->depth + 7) >> 3;
-        break;
-    case FF_PIXEL_PALETTE:
-        if (plane == 0)
-            return width;
-        break;
-    }
+    return av_image_get_linesize(pix_fmt, width, plane);
+}
 
-    return -1;
+void av_picture_data_copy(uint8_t *dst_data[4], int dst_linesize[4],
+                          uint8_t *src_data[4], int src_linesize[4],
+                          enum PixelFormat pix_fmt, int width, int height)
+{
+    av_image_copy(dst_data, dst_linesize, src_data, src_linesize,
+                  pix_fmt, width, height);
 }
+#endif
 
 void av_picture_copy(AVPicture *dst, const AVPicture *src,
                      enum PixelFormat pix_fmt, int width, int height)
 {
-    int i;
-    const PixFmtInfo *pf = &pix_fmt_info[pix_fmt];
-    const AVPixFmtDescriptor *desc = &av_pix_fmt_descriptors[pix_fmt];
-
-    switch(pf->pixel_type) {
-    case FF_PIXEL_PACKED:
-    case FF_PIXEL_PLANAR:
-        for(i = 0; i < pf->nb_channels; i++) {
-            int h;
-            int bwidth = ff_get_plane_bytewidth(pix_fmt, width, i);
-            h = height;
-            if (i == 1 || i == 2) {
-                h= -((-height)>>desc->log2_chroma_h);
-            }
-            ff_img_copy_plane(dst->data[i], dst->linesize[i],
-                           src->data[i], src->linesize[i],
-                           bwidth, h);
-        }
-        break;
-    case FF_PIXEL_PALETTE:
-        ff_img_copy_plane(dst->data[0], dst->linesize[0],
-                       src->data[0], src->linesize[0],
-                       width, height);
-        /* copy the palette */
-        memcpy(dst->data[1], src->data[1], 4*256);
-        break;
-    }
+    av_image_copy(dst->data, dst->linesize, src->data,
+                  src->linesize, pix_fmt, width, height);
 }
 
 /* 2x2 -> 1x1 */
@@ -1084,23 +812,14 @@ void ff_shrink88(uint8_t *dst, int dst_wrap,
 int avpicture_alloc(AVPicture *picture,
                     enum PixelFormat pix_fmt, int width, int height)
 {
-    int size;
-    void *ptr;
-
-    size = avpicture_fill(picture, NULL, pix_fmt, width, height);
-    if(size<0)
-        goto fail;
-    ptr = av_malloc(size);
-    if (!ptr)
-        goto fail;
-    avpicture_fill(picture, ptr, pix_fmt, width, height);
-    if(picture->data[1] && !picture->data[2])
-        ff_set_systematic_pal((uint32_t*)picture->data[1], pix_fmt);
+    int ret;
+
+    if ((ret = av_image_alloc(picture->data, picture->linesize, width, height, pix_fmt, 1)) < 0) {
+        memset(picture, 0, sizeof(AVPicture));
+        return ret;
+    }
 
     return 0;
- fail:
-    memset(picture, 0, sizeof(AVPicture));
-    return -1;
 }
 
 void avpicture_free(AVPicture *picture)
@@ -1245,61 +964,14 @@ int img_get_alpha_info(const AVPicture *src,
     return ret;
 }
 
-#if HAVE_MMX
-#define DEINT_INPLACE_LINE_LUM \
-                    movd_m2r(lum_m4[0],mm0);\
-                    movd_m2r(lum_m3[0],mm1);\
-                    movd_m2r(lum_m2[0],mm2);\
-                    movd_m2r(lum_m1[0],mm3);\
-                    movd_m2r(lum[0],mm4);\
-                    punpcklbw_r2r(mm7,mm0);\
-                    movd_r2m(mm2,lum_m4[0]);\
-                    punpcklbw_r2r(mm7,mm1);\
-                    punpcklbw_r2r(mm7,mm2);\
-                    punpcklbw_r2r(mm7,mm3);\
-                    punpcklbw_r2r(mm7,mm4);\
-                    paddw_r2r(mm3,mm1);\
-                    psllw_i2r(1,mm2);\
-                    paddw_r2r(mm4,mm0);\
-                    psllw_i2r(2,mm1);\
-                    paddw_r2r(mm6,mm2);\
-                    paddw_r2r(mm2,mm1);\
-                    psubusw_r2r(mm0,mm1);\
-                    psrlw_i2r(3,mm1);\
-                    packuswb_r2r(mm7,mm1);\
-                    movd_r2m(mm1,lum_m2[0]);
-
-#define DEINT_LINE_LUM \
-                    movd_m2r(lum_m4[0],mm0);\
-                    movd_m2r(lum_m3[0],mm1);\
-                    movd_m2r(lum_m2[0],mm2);\
-                    movd_m2r(lum_m1[0],mm3);\
-                    movd_m2r(lum[0],mm4);\
-                    punpcklbw_r2r(mm7,mm0);\
-                    punpcklbw_r2r(mm7,mm1);\
-                    punpcklbw_r2r(mm7,mm2);\
-                    punpcklbw_r2r(mm7,mm3);\
-                    punpcklbw_r2r(mm7,mm4);\
-                    paddw_r2r(mm3,mm1);\
-                    psllw_i2r(1,mm2);\
-                    paddw_r2r(mm4,mm0);\
-                    psllw_i2r(2,mm1);\
-                    paddw_r2r(mm6,mm2);\
-                    paddw_r2r(mm2,mm1);\
-                    psubusw_r2r(mm0,mm1);\
-                    psrlw_i2r(3,mm1);\
-                    packuswb_r2r(mm7,mm1);\
-                    movd_r2m(mm1,dst[0]);
-#endif
-
+#if !(HAVE_MMX && HAVE_YASM)
 /* filter parameters: [-1 4 2 4 -1] // 8 */
-static void deinterlace_line(uint8_t *dst,
+static void deinterlace_line_c(uint8_t *dst,
                              const uint8_t *lum_m4, const uint8_t *lum_m3,
                              const uint8_t *lum_m2, const uint8_t *lum_m1,
                              const uint8_t *lum,
                              int size)
 {
-#if !HAVE_MMX
     uint8_t *cm = ff_cropTbl + MAX_NEG_CROP;
     int sum;
 
@@ -1317,27 +989,12 @@ static void deinterlace_line(uint8_t *dst,
         lum++;
         dst++;
     }
-#else
-
-    {
-        pxor_r2r(mm7,mm7);
-        movq_m2r(ff_pw_4,mm6);
-    }
-    for (;size > 3; size-=4) {
-        DEINT_LINE_LUM
-        lum_m4+=4;
-        lum_m3+=4;
-        lum_m2+=4;
-        lum_m1+=4;
-        lum+=4;
-        dst+=4;
-    }
-#endif
 }
-static void deinterlace_line_inplace(uint8_t *lum_m4, uint8_t *lum_m3, uint8_t *lum_m2, uint8_t *lum_m1, uint8_t *lum,
-                             int size)
+
+static void deinterlace_line_inplace_c(uint8_t *lum_m4, uint8_t *lum_m3,
+                                       uint8_t *lum_m2, uint8_t *lum_m1,
+                                       uint8_t *lum, int size)
 {
-#if !HAVE_MMX
     uint8_t *cm = ff_cropTbl + MAX_NEG_CROP;
     int sum;
 
@@ -1355,22 +1012,8 @@ static void deinterlace_line_inplace(uint8_t *lum_m4, uint8_t *lum_m3, uint8_t *
         lum_m1++;
         lum++;
     }
-#else
-
-    {
-        pxor_r2r(mm7,mm7);
-        movq_m2r(ff_pw_4,mm6);
-    }
-    for (;size > 3; size-=4) {
-        DEINT_INPLACE_LINE_LUM
-        lum_m4+=4;
-        lum_m3+=4;
-        lum_m2+=4;
-        lum_m1+=4;
-        lum+=4;
-    }
-#endif
 }
+#endif
 
 /* deinterlacing : 2 temporal taps, 3 spatial taps linear filter. The
    top field is copied as is, but the bottom field is deinterlaced
@@ -1435,7 +1078,9 @@ int avpicture_deinterlace(AVPicture *dst, const AVPicture *src,
     int i;
 
     if (pix_fmt != PIX_FMT_YUV420P &&
+        pix_fmt != PIX_FMT_YUVJ420P &&
         pix_fmt != PIX_FMT_YUV422P &&
+        pix_fmt != PIX_FMT_YUVJ422P &&
         pix_fmt != PIX_FMT_YUV444P &&
         pix_fmt != PIX_FMT_YUV411P &&
         pix_fmt != PIX_FMT_GRAY8)
@@ -1446,11 +1091,13 @@ int avpicture_deinterlace(AVPicture *dst, const AVPicture *src,
     for(i=0;i<3;i++) {
         if (i == 1) {
             switch(pix_fmt) {
+            case PIX_FMT_YUVJ420P:
             case PIX_FMT_YUV420P:
                 width >>= 1;
                 height >>= 1;
                 break;
             case PIX_FMT_YUV422P:
+            case PIX_FMT_YUVJ422P:
                 width >>= 1;
                 break;
             case PIX_FMT_YUV411P:
diff --git a/libavcodec/imgconvert.h b/libavcodec/imgconvert.h
index 48e2f12..c99e587 100644
--- a/libavcodec/imgconvert.h
+++ b/libavcodec/imgconvert.h
@@ -4,20 +4,20 @@
  *
  * Copyright (c) 2008 Vitor Sessak
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -27,12 +27,18 @@
 #include <stdint.h>
 #include "avcodec.h"
 
+#if LIBAVCODEC_VERSION_MAJOR < 53
+attribute_deprecated
 int ff_fill_linesize(AVPicture *picture, enum PixelFormat pix_fmt, int width);
 
+attribute_deprecated
 int ff_fill_pointer(AVPicture *picture, uint8_t *ptr, enum PixelFormat pix_fmt, int height);
 
+attribute_deprecated
 int ff_get_plane_bytewidth(enum PixelFormat pix_fmt, int width, int plane);
 
+attribute_deprecated
 int ff_set_systematic_pal(uint32_t pal[256], enum PixelFormat pix_fmt);
+#endif
 
 #endif /* AVCODEC_IMGCONVERT_H */
diff --git a/libavcodec/imx_dump_header_bsf.c b/libavcodec/imx_dump_header_bsf.c
index 2310185..3724daf 100644
--- a/libavcodec/imx_dump_header_bsf.c
+++ b/libavcodec/imx_dump_header_bsf.c
@@ -2,20 +2,20 @@
  * imx dump header bitstream filter
  * Copyright (c) 2007 Baptiste Coudurier
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -52,7 +52,7 @@ static int imx_dump_header(AVBitStreamFilterContext *bsfc, AVCodecContext *avctx
     return 1;
 }
 
-AVBitStreamFilter imx_dump_header_bsf = {
+AVBitStreamFilter ff_imx_dump_header_bsf = {
     "imxdump",
     0,
     imx_dump_header,
diff --git a/libavcodec/indeo2.c b/libavcodec/indeo2.c
index a3d6c80..0e588c3 100644
--- a/libavcodec/indeo2.c
+++ b/libavcodec/indeo2.c
@@ -2,20 +2,20 @@
  * Intel Indeo 2 codec
  * Copyright (c) 2005 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -224,7 +224,7 @@ static av_cold int ir2_decode_end(AVCodecContext *avctx){
     return 0;
 }
 
-AVCodec indeo2_decoder = {
+AVCodec ff_indeo2_decoder = {
     "indeo2",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_INDEO2,
diff --git a/libavcodec/indeo2data.h b/libavcodec/indeo2data.h
index b2e0b8a..ef85e32 100644
--- a/libavcodec/indeo2data.h
+++ b/libavcodec/indeo2data.h
@@ -2,20 +2,20 @@
  * Intel Indeo 2 codec
  * copyright (c) 2005 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/indeo3.c b/libavcodec/indeo3.c
index e5df32c..29a8d4a 100644
--- a/libavcodec/indeo3.c
+++ b/libavcodec/indeo3.c
@@ -2,20 +2,20 @@
  * Intel Indeo 3 (IV31, IV32, etc.) video decoder for ffmpeg
  * written, produced, and directed by Alan Smithee
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -23,6 +23,7 @@
 #include <stdlib.h>
 #include <string.h>
 
+#include "libavutil/imgutils.h"
 #include "avcodec.h"
 #include "dsputil.h"
 #include "bytestream.h"
@@ -359,14 +360,14 @@ static void iv_Decode_Chunk(Indeo3DecodeContext *s,
 
                             switch(correction_type_sp[0][k]) {
                             case 0:
-                                *cur_lp = le2me_32(((le2me_32(*ref_lp) >> 1) + correction_lp[lp2 & 0x01][k]) << 1);
+                                *cur_lp = av_le2ne32(((av_le2ne32(*ref_lp) >> 1) + correction_lp[lp2 & 0x01][k]) << 1);
                                 lp2++;
                                 break;
                             case 1:
-                                res = ((le2me_16(((unsigned short *)(ref_lp))[0]) >> 1) + correction_lp[lp2 & 0x01][*buf1]) << 1;
-                                ((unsigned short *)cur_lp)[0] = le2me_16(res);
-                                res = ((le2me_16(((unsigned short *)(ref_lp))[1]) >> 1) + correction_lp[lp2 & 0x01][k]) << 1;
-                                ((unsigned short *)cur_lp)[1] = le2me_16(res);
+                                res = ((av_le2ne16(((unsigned short *)(ref_lp))[0]) >> 1) + correction_lp[lp2 & 0x01][*buf1]) << 1;
+                                ((unsigned short *)cur_lp)[0] = av_le2ne16(res);
+                                res = ((av_le2ne16(((unsigned short *)(ref_lp))[1]) >> 1) + correction_lp[lp2 & 0x01][k]) << 1;
+                                ((unsigned short *)cur_lp)[1] = av_le2ne16(res);
                                 buf1++;
                                 lp2++;
                                 break;
@@ -462,19 +463,19 @@ static void iv_Decode_Chunk(Indeo3DecodeContext *s,
 
                             switch(correction_type_sp[lp2 & 0x01][k]) {
                             case 0:
-                                cur_lp[width_tbl[1]] = le2me_32(((le2me_32(*ref_lp) >> 1) + correction_lp[lp2 & 0x01][k]) << 1);
+                                cur_lp[width_tbl[1]] = av_le2ne32(((av_le2ne32(*ref_lp) >> 1) + correction_lp[lp2 & 0x01][k]) << 1);
                                 if(lp2 > 0 || flag1 == 0 || strip->ypos != 0)
                                     cur_lp[0] = ((cur_lp[-width_tbl[1]] >> 1) + (cur_lp[width_tbl[1]] >> 1)) & 0xFEFEFEFE;
                                 else
-                                    cur_lp[0] = le2me_32(((le2me_32(*ref_lp) >> 1) + correction_lp[lp2 & 0x01][k]) << 1);
+                                    cur_lp[0] = av_le2ne32(((av_le2ne32(*ref_lp) >> 1) + correction_lp[lp2 & 0x01][k]) << 1);
                                 lp2++;
                                 break;
 
                             case 1:
-                                res = ((le2me_16(((unsigned short *)ref_lp)[0]) >> 1) + correction_lp[lp2 & 0x01][*buf1]) << 1;
-                                ((unsigned short *)cur_lp)[width_tbl[2]] = le2me_16(res);
-                                res = ((le2me_16(((unsigned short *)ref_lp)[1]) >> 1) + correction_lp[lp2 & 0x01][k]) << 1;
-                                ((unsigned short *)cur_lp)[width_tbl[2]+1] = le2me_16(res);
+                                res = ((av_le2ne16(((unsigned short *)ref_lp)[0]) >> 1) + correction_lp[lp2 & 0x01][*buf1]) << 1;
+                                ((unsigned short *)cur_lp)[width_tbl[2]] = av_le2ne16(res);
+                                res = ((av_le2ne16(((unsigned short *)ref_lp)[1]) >> 1) + correction_lp[lp2 & 0x01][k]) << 1;
+                                ((unsigned short *)cur_lp)[width_tbl[2]+1] = av_le2ne16(res);
 
                                 if(lp2 > 0 || flag1 == 0 || strip->ypos != 0)
                                     cur_lp[0] = ((cur_lp[-width_tbl[1]] >> 1) + (cur_lp[width_tbl[1]] >> 1)) & 0xFEFEFEFE;
@@ -591,8 +592,8 @@ static void iv_Decode_Chunk(Indeo3DecodeContext *s,
 
                                 switch(correction_type_sp[lp2 & 0x01][k]) {
                                 case 0:
-                                    cur_lp[width_tbl[1]] = le2me_32(((le2me_32(lv1) >> 1) + correctionloworder_lp[lp2 & 0x01][k]) << 1);
-                                    cur_lp[width_tbl[1]+1] = le2me_32(((le2me_32(lv2) >> 1) + correctionhighorder_lp[lp2 & 0x01][k]) << 1);
+                                    cur_lp[width_tbl[1]] = av_le2ne32(((av_le2ne32(lv1) >> 1) + correctionloworder_lp[lp2 & 0x01][k]) << 1);
+                                    cur_lp[width_tbl[1]+1] = av_le2ne32(((av_le2ne32(lv2) >> 1) + correctionhighorder_lp[lp2 & 0x01][k]) << 1);
                                     if(lp2 > 0 || strip->ypos != 0 || flag1 == 0) {
                                         cur_lp[0] = ((cur_lp[-width_tbl[1]] >> 1) + (cur_lp[width_tbl[1]] >> 1)) & 0xFEFEFEFE;
                                         cur_lp[1] = ((cur_lp[-width_tbl[1]+1] >> 1) + (cur_lp[width_tbl[1]+1] >> 1)) & 0xFEFEFEFE;
@@ -604,8 +605,8 @@ static void iv_Decode_Chunk(Indeo3DecodeContext *s,
                                     break;
 
                                 case 1:
-                                    cur_lp[width_tbl[1]] = le2me_32(((le2me_32(lv1) >> 1) + correctionloworder_lp[lp2 & 0x01][*buf1]) << 1);
-                                    cur_lp[width_tbl[1]+1] = le2me_32(((le2me_32(lv2) >> 1) + correctionloworder_lp[lp2 & 0x01][k]) << 1);
+                                    cur_lp[width_tbl[1]] = av_le2ne32(((av_le2ne32(lv1) >> 1) + correctionloworder_lp[lp2 & 0x01][*buf1]) << 1);
+                                    cur_lp[width_tbl[1]+1] = av_le2ne32(((av_le2ne32(lv2) >> 1) + correctionloworder_lp[lp2 & 0x01][k]) << 1);
                                     if(lp2 > 0 || strip->ypos != 0 || flag1 == 0) {
                                         cur_lp[0] = ((cur_lp[-width_tbl[1]] >> 1) + (cur_lp[width_tbl[1]] >> 1)) & 0xFEFEFEFE;
                                         cur_lp[1] = ((cur_lp[-width_tbl[1]+1] >> 1) + (cur_lp[width_tbl[1]+1] >> 1)) & 0xFEFEFEFE;
@@ -748,20 +749,20 @@ static void iv_Decode_Chunk(Indeo3DecodeContext *s,
                                 case 0:
                                     lv1 = correctionloworder_lp[lp2 & 0x01][k];
                                     lv2 = correctionhighorder_lp[lp2 & 0x01][k];
-                                    cur_lp[0] = le2me_32(((le2me_32(ref_lp[0]) >> 1) + lv1) << 1);
-                                    cur_lp[1] = le2me_32(((le2me_32(ref_lp[1]) >> 1) + lv2) << 1);
-                                    cur_lp[width_tbl[1]] = le2me_32(((le2me_32(ref_lp[width_tbl[1]]) >> 1) + lv1) << 1);
-                                    cur_lp[width_tbl[1]+1] = le2me_32(((le2me_32(ref_lp[width_tbl[1]+1]) >> 1) + lv2) << 1);
+                                    cur_lp[0] = av_le2ne32(((av_le2ne32(ref_lp[0]) >> 1) + lv1) << 1);
+                                    cur_lp[1] = av_le2ne32(((av_le2ne32(ref_lp[1]) >> 1) + lv2) << 1);
+                                    cur_lp[width_tbl[1]] = av_le2ne32(((av_le2ne32(ref_lp[width_tbl[1]]) >> 1) + lv1) << 1);
+                                    cur_lp[width_tbl[1]+1] = av_le2ne32(((av_le2ne32(ref_lp[width_tbl[1]+1]) >> 1) + lv2) << 1);
                                     lp2++;
                                     break;
 
                                 case 1:
                                     lv1 = correctionloworder_lp[lp2 & 0x01][*buf1++];
                                     lv2 = correctionloworder_lp[lp2 & 0x01][k];
-                                    cur_lp[0] = le2me_32(((le2me_32(ref_lp[0]) >> 1) + lv1) << 1);
-                                    cur_lp[1] = le2me_32(((le2me_32(ref_lp[1]) >> 1) + lv2) << 1);
-                                    cur_lp[width_tbl[1]] = le2me_32(((le2me_32(ref_lp[width_tbl[1]]) >> 1) + lv1) << 1);
-                                    cur_lp[width_tbl[1]+1] = le2me_32(((le2me_32(ref_lp[width_tbl[1]+1]) >> 1) + lv2) << 1);
+                                    cur_lp[0] = av_le2ne32(((av_le2ne32(ref_lp[0]) >> 1) + lv1) << 1);
+                                    cur_lp[1] = av_le2ne32(((av_le2ne32(ref_lp[1]) >> 1) + lv2) << 1);
+                                    cur_lp[width_tbl[1]] = av_le2ne32(((av_le2ne32(ref_lp[width_tbl[1]]) >> 1) + lv1) << 1);
+                                    cur_lp[width_tbl[1]+1] = av_le2ne32(((av_le2ne32(ref_lp[width_tbl[1]+1]) >> 1) + lv2) << 1);
                                     lp2++;
                                     break;
 
@@ -849,22 +850,22 @@ static void iv_Decode_Chunk(Indeo3DecodeContext *s,
 
                             switch(correction_type_sp[lp2 & 0x01][k]) {
                             case 0:
-                                cur_lp[0] = le2me_32(((le2me_32(*ref_lp) >> 1) + correction_lp[lp2 & 0x01][k]) << 1);
-                                cur_lp[width_tbl[1]] = le2me_32(((le2me_32(ref_lp[width_tbl[1]]) >> 1) + correction_lp[lp2 & 0x01][k]) << 1);
+                                cur_lp[0] = av_le2ne32(((av_le2ne32(*ref_lp) >> 1) + correction_lp[lp2 & 0x01][k]) << 1);
+                                cur_lp[width_tbl[1]] = av_le2ne32(((av_le2ne32(ref_lp[width_tbl[1]]) >> 1) + correction_lp[lp2 & 0x01][k]) << 1);
                                 lp2++;
                                 break;
 
                             case 1:
                                 lv1 = (unsigned short)(correction_lp[lp2 & 0x01][*buf1++]);
                                 lv2 = (unsigned short)(correction_lp[lp2 & 0x01][k]);
-                                res = (unsigned short)(((le2me_16(((unsigned short *)ref_lp)[0]) >> 1) + lv1) << 1);
-                                ((unsigned short *)cur_lp)[0] = le2me_16(res);
-                                res = (unsigned short)(((le2me_16(((unsigned short *)ref_lp)[1]) >> 1) + lv2) << 1);
-                                ((unsigned short *)cur_lp)[1] = le2me_16(res);
-                                res = (unsigned short)(((le2me_16(((unsigned short *)ref_lp)[width_tbl[2]]) >> 1) + lv1) << 1);
-                                ((unsigned short *)cur_lp)[width_tbl[2]] = le2me_16(res);
-                                res = (unsigned short)(((le2me_16(((unsigned short *)ref_lp)[width_tbl[2]+1]) >> 1) + lv2) << 1);
-                                ((unsigned short *)cur_lp)[width_tbl[2]+1] = le2me_16(res);
+                                res = (unsigned short)(((av_le2ne16(((unsigned short *)ref_lp)[0]) >> 1) + lv1) << 1);
+                                ((unsigned short *)cur_lp)[0] = av_le2ne16(res);
+                                res = (unsigned short)(((av_le2ne16(((unsigned short *)ref_lp)[1]) >> 1) + lv2) << 1);
+                                ((unsigned short *)cur_lp)[1] = av_le2ne16(res);
+                                res = (unsigned short)(((av_le2ne16(((unsigned short *)ref_lp)[width_tbl[2]]) >> 1) + lv1) << 1);
+                                ((unsigned short *)cur_lp)[width_tbl[2]] = av_le2ne16(res);
+                                res = (unsigned short)(((av_le2ne16(((unsigned short *)ref_lp)[width_tbl[2]+1]) >> 1) + lv2) << 1);
+                                ((unsigned short *)cur_lp)[width_tbl[2]+1] = av_le2ne16(res);
                                 lp2++;
                                 break;
 
@@ -995,7 +996,7 @@ static int iv_decode_frame(AVCodecContext *avctx,
     image_height = bytestream_get_le16(&buf_pos);
     image_width  = bytestream_get_le16(&buf_pos);
 
-    if(avcodec_check_dimensions(avctx, image_width, image_height))
+    if(av_image_check_size(image_width, image_height, 0, avctx))
         return -1;
     if (image_width != avctx->width || image_height != avctx->height) {
         int ret;
@@ -1136,7 +1137,7 @@ static av_cold int indeo3_decode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec indeo3_decoder = {
+AVCodec ff_indeo3_decoder = {
     "indeo3",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_INDEO3,
diff --git a/libavcodec/indeo3data.h b/libavcodec/indeo3data.h
index bbc4c95..334c3e0 100644
--- a/libavcodec/indeo3data.h
+++ b/libavcodec/indeo3data.h
@@ -2,20 +2,20 @@
  * Intel Indeo 3 (IV31, IV32, etc.) video decoder for ffmpeg
  * written, produced, and directed by Alan Smithee
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/indeo5.c b/libavcodec/indeo5.c
index 2593e55..088b45a 100644
--- a/libavcodec/indeo5.c
+++ b/libavcodec/indeo5.c
@@ -2,20 +2,20 @@
  * Indeo Video Interactive v5 compatible decoder
  * Copyright (c) 2009 Maxim Poliakovski
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -80,17 +80,18 @@ typedef struct {
 
 
 /**
- *  Decodes Indeo5 GOP (Group of pictures) header.
+ *  Decode Indeo5 GOP (Group of pictures) header.
  *  This header is present in key frames only.
  *  It defines parameters for all frames in a GOP.
  *
- *  @param ctx      [in,out] ptr to the decoder context
- *  @param avctx    [in] ptr to the AVCodecContext
+ *  @param[in,out] ctx    ptr to the decoder context
+ *  @param[in]     avctx  ptr to the AVCodecContext
  *  @return         result code: 0 = OK, -1 = error
  */
 static int decode_gop_header(IVI5DecContext *ctx, AVCodecContext *avctx)
 {
-    int             result, i, p, tile_size, pic_size_indx, mb_size, blk_size, blk_size_changed = 0;
+    int             result, i, p, tile_size, pic_size_indx, mb_size, blk_size;
+    int             quant_mat, blk_size_changed = 0;
     IVIBandDesc     *band, *band1, *band2;
     IVIPicConfig    pic_conf;
 
@@ -185,25 +186,25 @@ static int decode_gop_header(IVI5DecContext *ctx, AVCodecContext *avctx)
             case 1:
                 band->inv_transform = ff_ivi_row_slant8;
                 band->dc_transform  = ff_ivi_dc_row_slant;
-                band->scan          = ivi5_scans8x8[0];
+                band->scan          = ff_ivi_vertical_scan_8x8;
                 break;
 
             case 2:
                 band->inv_transform = ff_ivi_col_slant8;
                 band->dc_transform  = ff_ivi_dc_col_slant;
-                band->scan          = ivi5_scans8x8[1];
+                band->scan          = ff_ivi_horizontal_scan_8x8;
                 break;
 
             case 3:
                 band->inv_transform = ff_ivi_put_pixels_8x8;
                 band->dc_transform  = ff_ivi_put_dc_pixel_8x8;
-                band->scan          = ivi5_scans8x8[1];
+                band->scan          = ff_ivi_horizontal_scan_8x8;
                 break;
 
             case 4:
                 band->inv_transform = ff_ivi_inverse_slant_4x4;
                 band->dc_transform  = ff_ivi_dc_slant_2d;
-                band->scan          = ivi5_scan4x4;
+                band->scan          = ff_ivi_direct_scan_4x4;
                 break;
             }
 
@@ -212,9 +213,21 @@ static int decode_gop_header(IVI5DecContext *ctx, AVCodecContext *avctx)
 
             /* select dequant matrix according to plane and band number */
             if (!p) {
-                band->quant_mat = (pic_conf.luma_bands > 1) ? i+1 : 0;
+                quant_mat = (pic_conf.luma_bands > 1) ? i+1 : 0;
             } else {
-                band->quant_mat = 5;
+                quant_mat = 5;
+            }
+
+            if (band->blk_size == 8) {
+                band->intra_base  = &ivi5_base_quant_8x8_intra[quant_mat][0];
+                band->inter_base  = &ivi5_base_quant_8x8_inter[quant_mat][0];
+                band->intra_scale = &ivi5_scale_quant_8x8_intra[quant_mat][0];
+                band->inter_scale = &ivi5_scale_quant_8x8_inter[quant_mat][0];
+            } else {
+                band->intra_base  = ivi5_base_quant_4x4_intra;
+                band->inter_base  = ivi5_base_quant_4x4_inter;
+                band->intra_scale = ivi5_scale_quant_4x4_intra;
+                band->inter_scale = ivi5_scale_quant_4x4_inter;
             }
 
             if (get_bits(&ctx->gb, 2)) {
@@ -234,7 +247,10 @@ static int decode_gop_header(IVI5DecContext *ctx, AVCodecContext *avctx)
         band2->mb_size       = band1->mb_size;
         band2->blk_size      = band1->blk_size;
         band2->is_halfpel    = band1->is_halfpel;
-        band2->quant_mat     = band1->quant_mat;
+        band2->intra_base    = band1->intra_base;
+        band2->inter_base    = band1->inter_base;
+        band2->intra_scale   = band1->intra_scale;
+        band2->inter_scale   = band1->inter_scale;
         band2->scan          = band1->scan;
         band2->inv_transform = band1->inv_transform;
         band2->dc_transform  = band1->dc_transform;
@@ -280,9 +296,9 @@ static int decode_gop_header(IVI5DecContext *ctx, AVCodecContext *avctx)
 
 
 /**
- *  Skips a header extension.
+ *  Skip a header extension.
  *
- *  @param gb   [in,out] the GetBit context
+ *  @param[in,out]  gb  the GetBit context
  */
 static inline void skip_hdr_extension(GetBitContext *gb)
 {
@@ -296,10 +312,10 @@ static inline void skip_hdr_extension(GetBitContext *gb)
 
 
 /**
- *  Decodes Indeo5 picture header.
+ *  Decode Indeo5 picture header.
  *
- *  @param ctx      [in,out] ptr to the decoder context
- *  @param avctx    [in] ptr to the AVCodecContext
+ *  @param[in,out]  ctx    ptr to the decoder context
+ *  @param[in]      avctx  ptr to the AVCodecContext
  *  @return         result code: 0 = OK, -1 = error
  */
 static int decode_pic_hdr(IVI5DecContext *ctx, AVCodecContext *avctx)
@@ -348,11 +364,11 @@ static int decode_pic_hdr(IVI5DecContext *ctx, AVCodecContext *avctx)
 
 
 /**
- *  Decodes Indeo5 band header.
+ *  Decode Indeo5 band header.
  *
- *  @param ctx      [in,out] ptr to the decoder context
- *  @param band     [in,out] ptr to the band descriptor
- *  @param avctx    [in] ptr to the AVCodecContext
+ *  @param[in,out]  ctx    ptr to the decoder context
+ *  @param[in,out]  band   ptr to the band descriptor
+ *  @param[in]      avctx  ptr to the AVCodecContext
  *  @return         result code: 0 = OK, -1 = error
  */
 static int decode_band_hdr(IVI5DecContext *ctx, IVIBandDesc *band,
@@ -416,13 +432,13 @@ static int decode_band_hdr(IVI5DecContext *ctx, IVIBandDesc *band,
 
 
 /**
- *  Decodes info (block type, cbp, quant delta, motion vector)
+ *  Decode info (block type, cbp, quant delta, motion vector)
  *  for all macroblocks in the current tile.
  *
- *  @param ctx      [in,out] ptr to the decoder context
- *  @param band     [in,out] ptr to the band descriptor
- *  @param tile     [in,out] ptr to the tile descriptor
- *  @param avctx    [in] ptr to the AVCodecContext
+ *  @param[in,out]  ctx    ptr to the decoder context
+ *  @param[in,out]  band   ptr to the band descriptor
+ *  @param[in,out]  tile   ptr to the tile descriptor
+ *  @param[in]      avctx  ptr to the AVCodecContext
  *  @return         result code: 0 = OK, -1 = error
  */
 static int decode_mb_info(IVI5DecContext *ctx, IVIBandDesc *band,
@@ -541,11 +557,11 @@ static int decode_mb_info(IVI5DecContext *ctx, IVIBandDesc *band,
 
 
 /**
- *  Decodes an Indeo5 band.
+ *  Decode an Indeo5 band.
  *
- *  @param ctx      [in,out] ptr to the decoder context
- *  @param band     [in,out] ptr to the band descriptor
- *  @param avctx    [in] ptr to the AVCodecContext
+ *  @param[in,out]  ctx    ptr to the decoder context
+ *  @param[in,out]  band   ptr to the band descriptor
+ *  @param[in]      avctx  ptr to the AVCodecContext
  *  @return         result code: 0 = OK, -1 = error
  */
 static int decode_band(IVI5DecContext *ctx, int plane_num,
@@ -570,18 +586,6 @@ static int decode_band(IVI5DecContext *ctx, int plane_num,
         return -1;
     }
 
-    if (band->blk_size == 8) {
-        band->intra_base  = &ivi5_base_quant_8x8_intra[band->quant_mat][0];
-        band->inter_base  = &ivi5_base_quant_8x8_inter[band->quant_mat][0];
-        band->intra_scale = &ivi5_scale_quant_8x8_intra[band->quant_mat][0];
-        band->inter_scale = &ivi5_scale_quant_8x8_inter[band->quant_mat][0];
-    } else {
-        band->intra_base  = ivi5_base_quant_4x4_intra;
-        band->inter_base  = ivi5_base_quant_4x4_inter;
-        band->intra_scale = ivi5_scale_quant_4x4_intra;
-        band->inter_scale = ivi5_scale_quant_4x4_inter;
-    }
-
     band->rv_map = &ctx->rvmap_tabs[band->rvmap_sel];
 
     /* apply corrections to the selected rvmap table if present */
@@ -643,12 +647,11 @@ static int decode_band(IVI5DecContext *ctx, int plane_num,
 
 
 /**
- *  Switches buffers.
+ *  Switch buffers.
  *
- *  @param ctx      [in,out] ptr to the decoder context
- *  @param avctx    [in] ptr to the AVCodecContext
+ *  @param[in,out] ctx  ptr to the decoder context
  */
-static void switch_buffers(IVI5DecContext *ctx, AVCodecContext *avctx)
+static void switch_buffers(IVI5DecContext *ctx)
 {
     switch (ctx->prev_frame_type) {
     case FRAMETYPE_INTRA:
@@ -687,7 +690,7 @@ static void switch_buffers(IVI5DecContext *ctx, AVCodecContext *avctx)
 
 
 /**
- *  Initializes Indeo5 decoder.
+ *  Initialize Indeo5 decoder.
  */
 static av_cold int decode_init(AVCodecContext *avctx)
 {
@@ -752,7 +755,7 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *data_size,
         return -1;
     }
 
-    switch_buffers(ctx, avctx);
+    switch_buffers(ctx);
 
     //START_TIMER;
 
@@ -797,7 +800,7 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *data_size,
 
 
 /**
- *  Closes Indeo5 decoder and cleans up its context.
+ *  Close Indeo5 decoder and clean up its context.
  */
 static av_cold int decode_close(AVCodecContext *avctx)
 {
@@ -815,7 +818,7 @@ static av_cold int decode_close(AVCodecContext *avctx)
 }
 
 
-AVCodec indeo5_decoder = {
+AVCodec ff_indeo5_decoder = {
     .name           = "indeo5",
     .type           = AVMEDIA_TYPE_VIDEO,
     .id             = CODEC_ID_INDEO5,
diff --git a/libavcodec/indeo5data.h b/libavcodec/indeo5data.h
index 972e598..f4252b5 100644
--- a/libavcodec/indeo5data.h
+++ b/libavcodec/indeo5data.h
@@ -2,20 +2,20 @@
  * Indeo Video Interactive 5 compatible decoder
  * Copyright (c) 2009 Maxim Poliakovski
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -37,29 +37,6 @@ static const uint8_t ivi5_common_pic_sizes[30] = {
     176,  60, 20, 15, 22, 18,   0,   0,  0,  0,  0,  0
 };
 
-/**
- *  Indeo5 8x8 scan (zigzag) patterns
- */
-static const uint8_t ivi5_scans8x8[2][64] = {
-    {0,  8, 16, 24, 32, 40, 48, 56,  1,  9, 17, 25, 33, 41, 49, 57,
-     2, 10, 18, 26, 34, 42, 50, 58,  3, 11, 19, 27, 35, 43, 51, 59,
-     4, 12, 20, 28, 36, 44, 52, 60,  5, 13, 21, 29, 37, 45, 53, 61,
-     6, 14, 22, 30, 38, 46, 54, 62,  7, 15, 23, 31, 39, 47, 55, 63
-    },
-    {0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15,
-    16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
-    32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
-    48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63
-    }
-};
-
-/**
- *  Indeo5 4x4 scan (zigzag) pattern
- */
-static const uint8_t ivi5_scan4x4[16] = {
-    0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15
-};
-
 
 /**
  *  Indeo5 dequantization matrixes consist of two tables: base table
@@ -70,68 +47,68 @@ static const uint8_t ivi5_scan4x4[16] = {
  *  ivi5_base_quant_bbb_ttt  - base  tables for block size 'bbb' of type 'ttt'
  *  ivi5_scale_quant_bbb_ttt - scale tables for block size 'bbb' of type 'ttt'
  */
-static const uint8_t ivi5_base_quant_8x8_inter[5][64] = {
-    {0x13, 0x1d, 0x1f, 0x23, 0x25, 0x27, 0x29, 0x2d, 0x1d, 0x1f, 0x21, 0x23, 0x25, 0x27, 0x2b, 0x2f,
-     0x1f, 0x21, 0x23, 0x24, 0x26, 0x29, 0x2d, 0x31, 0x23, 0x23, 0x24, 0x25, 0x27, 0x2b, 0x2f, 0x33,
-     0x25, 0x25, 0x26, 0x27, 0x29, 0x2d, 0x31, 0x35, 0x27, 0x27, 0x29, 0x2b, 0x2d, 0x2f, 0x33, 0x37,
-     0x29, 0x2b, 0x2d, 0x2f, 0x31, 0x33, 0x35, 0x39, 0x2d, 0x2f, 0x31, 0x33, 0x35, 0x37, 0x39, 0x3b
-    },
-    {0x13, 0x1d, 0x1f, 0x23, 0x25, 0x27, 0x29, 0x2d, 0x1d, 0x1f, 0x21, 0x23, 0x25, 0x27, 0x2b, 0x2f,
-     0x1f, 0x21, 0x23, 0x24, 0x26, 0x29, 0x2d, 0x31, 0x23, 0x23, 0x24, 0x25, 0x27, 0x2b, 0x2f, 0x33,
-     0x25, 0x25, 0x26, 0x27, 0x29, 0x2d, 0x31, 0x35, 0x27, 0x27, 0x29, 0x2b, 0x2d, 0x2f, 0x33, 0x37,
-     0x29, 0x2b, 0x2d, 0x2f, 0x31, 0x33, 0x35, 0x39, 0x2d, 0x2f, 0x31, 0x33, 0x35, 0x37, 0x39, 0x3b
-    },
-    {0x27, 0x55, 0x79, 0x6a, 0x6f, 0x61, 0x6b, 0x61, 0x27, 0x55, 0x79, 0x6a, 0x6f, 0x61, 0x6b, 0x61,
-     0x27, 0x55, 0x79, 0x6a, 0x6f, 0x61, 0x6b, 0x61, 0x27, 0x55, 0x79, 0x6a, 0x6f, 0x61, 0x6b, 0x61,
-     0x27, 0x55, 0x79, 0x6a, 0x6f, 0x61, 0x6b, 0x61, 0x27, 0x55, 0x79, 0x6a, 0x6f, 0x61, 0x6b, 0x61,
-     0x27, 0x55, 0x79, 0x6a, 0x6f, 0x61, 0x6b, 0x61, 0x27, 0x55, 0x79, 0x6a, 0x6f, 0x61, 0x6b, 0x61
-    },
-    {0x27, 0x27, 0x27, 0x27, 0x27, 0x27, 0x27, 0x27, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
-     0x79, 0x79, 0x79, 0x79, 0x79, 0x79, 0x79, 0x79, 0x6a, 0x6a, 0x6a, 0x6a, 0x6a, 0x6a, 0x6a, 0x6a,
-     0x6f, 0x6f, 0x6f, 0x6f, 0x6f, 0x6f, 0x6f, 0x6f, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61,
-     0x6b, 0x6b, 0x6b, 0x6b, 0x6b, 0x6b, 0x6b, 0x6b, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61
-    },
-    {0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f,
-     0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f,
-     0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f,
-     0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f
+static const uint16_t ivi5_base_quant_8x8_inter[5][64] = {
+    {0x26, 0x3a, 0x3e, 0x46, 0x4a, 0x4e, 0x52, 0x5a, 0x3a, 0x3e, 0x42, 0x46, 0x4a, 0x4e, 0x56, 0x5e,
+     0x3e, 0x42, 0x46, 0x48, 0x4c, 0x52, 0x5a, 0x62, 0x46, 0x46, 0x48, 0x4a, 0x4e, 0x56, 0x5e, 0x66,
+     0x4a, 0x4a, 0x4c, 0x4e, 0x52, 0x5a, 0x62, 0x6a, 0x4e, 0x4e, 0x52, 0x56, 0x5a, 0x5e, 0x66, 0x6e,
+     0x52, 0x56, 0x5a, 0x5e, 0x62, 0x66, 0x6a, 0x72, 0x5a, 0x5e, 0x62, 0x66, 0x6a, 0x6e, 0x72, 0x76,
+    },
+    {0x26, 0x3a, 0x3e, 0x46, 0x4a, 0x4e, 0x52, 0x5a, 0x3a, 0x3e, 0x42, 0x46, 0x4a, 0x4e, 0x56, 0x5e,
+     0x3e, 0x42, 0x46, 0x48, 0x4c, 0x52, 0x5a, 0x62, 0x46, 0x46, 0x48, 0x4a, 0x4e, 0x56, 0x5e, 0x66,
+     0x4a, 0x4a, 0x4c, 0x4e, 0x52, 0x5a, 0x62, 0x6a, 0x4e, 0x4e, 0x52, 0x56, 0x5a, 0x5e, 0x66, 0x6e,
+     0x52, 0x56, 0x5a, 0x5e, 0x62, 0x66, 0x6a, 0x72, 0x5a, 0x5e, 0x62, 0x66, 0x6a, 0x6e, 0x72, 0x76,
+    },
+    {0x4e, 0xaa, 0xf2, 0xd4, 0xde, 0xc2, 0xd6, 0xc2, 0x4e, 0xaa, 0xf2, 0xd4, 0xde, 0xc2, 0xd6, 0xc2,
+     0x4e, 0xaa, 0xf2, 0xd4, 0xde, 0xc2, 0xd6, 0xc2, 0x4e, 0xaa, 0xf2, 0xd4, 0xde, 0xc2, 0xd6, 0xc2,
+     0x4e, 0xaa, 0xf2, 0xd4, 0xde, 0xc2, 0xd6, 0xc2, 0x4e, 0xaa, 0xf2, 0xd4, 0xde, 0xc2, 0xd6, 0xc2,
+     0x4e, 0xaa, 0xf2, 0xd4, 0xde, 0xc2, 0xd6, 0xc2, 0x4e, 0xaa, 0xf2, 0xd4, 0xde, 0xc2, 0xd6, 0xc2,
+    },
+    {0x4e, 0x4e, 0x4e, 0x4e, 0x4e, 0x4e, 0x4e, 0x4e, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+     0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xd4, 0xd4, 0xd4, 0xd4, 0xd4, 0xd4, 0xd4, 0xd4,
+     0xde, 0xde, 0xde, 0xde, 0xde, 0xde, 0xde, 0xde, 0xc2, 0xc2, 0xc2, 0xc2, 0xc2, 0xc2, 0xc2, 0xc2,
+     0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xc2, 0xc2, 0xc2, 0xc2, 0xc2, 0xc2, 0xc2, 0xc2,
+    },
+    {0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e,
+     0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e,
+     0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e,
+     0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e,
     }
 };
 
-static const uint8_t ivi5_base_quant_8x8_intra[5][64] = {
-    {0x0d, 0x17, 0x1b, 0x21, 0x23, 0x25, 0x27, 0x2d, 0x17, 0x19, 0x1f, 0x21, 0x23, 0x27, 0x2b, 0x35,
-     0x1b, 0x1f, 0x1f, 0x22, 0x25, 0x2a, 0x33, 0x39, 0x21, 0x21, 0x22, 0x25, 0x29, 0x31, 0x36, 0x3d,
-     0x23, 0x23, 0x25, 0x29, 0x2f, 0x33, 0x39, 0x47, 0x25, 0x27, 0x2a, 0x31, 0x33, 0x37, 0x43, 0x53,
-     0x27, 0x2b, 0x33, 0x36, 0x39, 0x43, 0x4d, 0x65, 0x2d, 0x35, 0x39, 0x3d, 0x47, 0x53, 0x65, 0x7f
-    },
-    {0x13, 0x1d, 0x1f, 0x23, 0x25, 0x27, 0x29, 0x2d, 0x1d, 0x1f, 0x21, 0x23, 0x25, 0x27, 0x2b, 0x2f,
-     0x1f, 0x21, 0x23, 0x24, 0x26, 0x29, 0x2d, 0x31, 0x23, 0x23, 0x24, 0x25, 0x27, 0x2b, 0x2f, 0x33,
-     0x25, 0x25, 0x26, 0x27, 0x29, 0x2d, 0x31, 0x35, 0x27, 0x27, 0x29, 0x2b, 0x2d, 0x2f, 0x33, 0x37,
-     0x29, 0x2b, 0x2d, 0x2f, 0x31, 0x33, 0x35, 0x39, 0x2d, 0x2f, 0x31, 0x33, 0x35, 0x37, 0x39, 0x3b
-    },
-    {0x27, 0x55, 0x79, 0x6a, 0x6f, 0x61, 0x6b, 0x61, 0x27, 0x55, 0x79, 0x6a, 0x6f, 0x61, 0x6b, 0x61,
-     0x27, 0x55, 0x79, 0x6a, 0x6f, 0x61, 0x6b, 0x61, 0x27, 0x55, 0x79, 0x6a, 0x6f, 0x61, 0x6b, 0x61,
-     0x27, 0x55, 0x79, 0x6a, 0x6f, 0x61, 0x6b, 0x61, 0x27, 0x55, 0x79, 0x6a, 0x6f, 0x61, 0x6b, 0x61,
-     0x27, 0x55, 0x79, 0x6a, 0x6f, 0x61, 0x6b, 0x61, 0x27, 0x55, 0x79, 0x6a, 0x6f, 0x61, 0x6b, 0x61
-    },
-    {0x27, 0x27, 0x27, 0x27, 0x27, 0x27, 0x27, 0x27, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
-     0x79, 0x79, 0x79, 0x79, 0x79, 0x79, 0x79, 0x79, 0x6a, 0x6a, 0x6a, 0x6a, 0x6a, 0x6a, 0x6a, 0x6a,
-     0x6f, 0x6f, 0x6f, 0x6f, 0x6f, 0x6f, 0x6f, 0x6f, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61,
-     0x6b, 0x6b, 0x6b, 0x6b, 0x6b, 0x6b, 0x6b, 0x6b, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61
-    },
-    {0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f,
-     0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f,
-     0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f,
-     0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f
+static const uint16_t ivi5_base_quant_8x8_intra[5][64] = {
+    {0x1a, 0x2e, 0x36, 0x42, 0x46, 0x4a, 0x4e, 0x5a, 0x2e, 0x32, 0x3e, 0x42, 0x46, 0x4e, 0x56, 0x6a,
+     0x36, 0x3e, 0x3e, 0x44, 0x4a, 0x54, 0x66, 0x72, 0x42, 0x42, 0x44, 0x4a, 0x52, 0x62, 0x6c, 0x7a,
+     0x46, 0x46, 0x4a, 0x52, 0x5e, 0x66, 0x72, 0x8e, 0x4a, 0x4e, 0x54, 0x62, 0x66, 0x6e, 0x86, 0xa6,
+     0x4e, 0x56, 0x66, 0x6c, 0x72, 0x86, 0x9a, 0xca, 0x5a, 0x6a, 0x72, 0x7a, 0x8e, 0xa6, 0xca, 0xfe,
+    },
+    {0x26, 0x3a, 0x3e, 0x46, 0x4a, 0x4e, 0x52, 0x5a, 0x3a, 0x3e, 0x42, 0x46, 0x4a, 0x4e, 0x56, 0x5e,
+     0x3e, 0x42, 0x46, 0x48, 0x4c, 0x52, 0x5a, 0x62, 0x46, 0x46, 0x48, 0x4a, 0x4e, 0x56, 0x5e, 0x66,
+     0x4a, 0x4a, 0x4c, 0x4e, 0x52, 0x5a, 0x62, 0x6a, 0x4e, 0x4e, 0x52, 0x56, 0x5a, 0x5e, 0x66, 0x6e,
+     0x52, 0x56, 0x5a, 0x5e, 0x62, 0x66, 0x6a, 0x72, 0x5a, 0x5e, 0x62, 0x66, 0x6a, 0x6e, 0x72, 0x76,
+    },
+    {0x4e, 0xaa, 0xf2, 0xd4, 0xde, 0xc2, 0xd6, 0xc2, 0x4e, 0xaa, 0xf2, 0xd4, 0xde, 0xc2, 0xd6, 0xc2,
+     0x4e, 0xaa, 0xf2, 0xd4, 0xde, 0xc2, 0xd6, 0xc2, 0x4e, 0xaa, 0xf2, 0xd4, 0xde, 0xc2, 0xd6, 0xc2,
+     0x4e, 0xaa, 0xf2, 0xd4, 0xde, 0xc2, 0xd6, 0xc2, 0x4e, 0xaa, 0xf2, 0xd4, 0xde, 0xc2, 0xd6, 0xc2,
+     0x4e, 0xaa, 0xf2, 0xd4, 0xde, 0xc2, 0xd6, 0xc2, 0x4e, 0xaa, 0xf2, 0xd4, 0xde, 0xc2, 0xd6, 0xc2,
+    },
+    {0x4e, 0x4e, 0x4e, 0x4e, 0x4e, 0x4e, 0x4e, 0x4e, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+     0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xd4, 0xd4, 0xd4, 0xd4, 0xd4, 0xd4, 0xd4, 0xd4,
+     0xde, 0xde, 0xde, 0xde, 0xde, 0xde, 0xde, 0xde, 0xc2, 0xc2, 0xc2, 0xc2, 0xc2, 0xc2, 0xc2, 0xc2,
+     0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xc2, 0xc2, 0xc2, 0xc2, 0xc2, 0xc2, 0xc2, 0xc2,
+    },
+    {0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e,
+     0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e,
+     0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e,
+     0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e,
     }
 };
 
-static const uint8_t ivi5_base_quant_4x4_inter[16] = {
-    0x0f, 0x1f, 0x25, 0x29, 0x1f, 0x25, 0x29, 0x2b, 0x25, 0x29, 0x2b, 0x2f, 0x29, 0x2b, 0x2f, 0x33
+static const uint16_t ivi5_base_quant_4x4_inter[16] = {
+    0x1e, 0x3e, 0x4a, 0x52, 0x3e, 0x4a, 0x52, 0x56, 0x4a, 0x52, 0x56, 0x5e, 0x52, 0x56, 0x5e, 0x66
 };
 
-static const uint8_t ivi5_base_quant_4x4_intra[16] = {
-    0x0f, 0x1f, 0x25, 0x29, 0x1f, 0x25, 0x29, 0x2f, 0x25, 0x29, 0x2f, 0x3d, 0x29, 0x2f, 0x3d, 0x49
+static const uint16_t ivi5_base_quant_4x4_intra[16] = {
+    0x1e, 0x3e, 0x4a, 0x52, 0x3e, 0x4a, 0x52, 0x5e, 0x4a, 0x52, 0x5e, 0x7a, 0x52, 0x5e, 0x7a, 0x92
 };
 
 
diff --git a/libavcodec/intelh263dec.c b/libavcodec/intelh263dec.c
index 5e45129..414c45a 100644
--- a/libavcodec/intelh263dec.c
+++ b/libavcodec/intelh263dec.c
@@ -1,20 +1,20 @@
 /*
  * H.263i decoder
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -115,7 +115,7 @@ int ff_intel_h263_decode_picture_header(MpegEncContext *s)
     return 0;
 }
 
-AVCodec h263i_decoder = {
+AVCodec ff_h263i_decoder = {
     "h263i",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_H263I,
diff --git a/libavcodec/internal.h b/libavcodec/internal.h
index 97c0dcb..fe853ab 100644
--- a/libavcodec/internal.h
+++ b/libavcodec/internal.h
@@ -1,18 +1,18 @@
 /*
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -28,12 +28,12 @@
 #include "avcodec.h"
 
 /**
- * Determines whether pix_fmt is a hardware accelerated format.
+ * Determine whether pix_fmt is a hardware accelerated format.
  */
 int ff_is_hwaccel_pix_fmt(enum PixelFormat pix_fmt);
 
 /**
- * Returns the hardware accelerated codec for codec codec_id and
+ * Return the hardware accelerated codec for codec codec_id and
  * pixel format pix_fmt.
  *
  * @param codec_id the codec to match
@@ -48,4 +48,6 @@ AVHWAccel *ff_find_hwaccel(enum CodecID codec_id, enum PixelFormat pix_fmt);
  */
 int ff_match_2uint16(const uint16_t (*tab)[2], int size, int a, int b);
 
+unsigned int ff_toupper4(unsigned int x);
+
 #endif /* AVCODEC_INTERNAL_H */
diff --git a/libavcodec/interplayvideo.c b/libavcodec/interplayvideo.c
index b98386f..c12b241 100644
--- a/libavcodec/interplayvideo.c
+++ b/libavcodec/interplayvideo.c
@@ -2,20 +2,20 @@
  * Interplay MVE Video Decoder
  * Copyright (C) 2003 the ffmpeg project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -77,6 +77,7 @@ typedef struct IpvideoContext {
     int stride;
     int upper_motion_limit_offset;
 
+    uint32_t pal[256];
 } IpvideoContext;
 
 #define CHECK_STREAM_PTR(stream_ptr, stream_end, n) \
@@ -99,6 +100,10 @@ static int copy_from(IpvideoContext *s, AVFrame *src, int delta_x, int delta_y)
             motion_offset, s->upper_motion_limit_offset);
         return -1;
     }
+    if (src->data[0] == NULL) {
+        av_log(s->avctx, AV_LOG_ERROR, "Invalid decode type, corrupted header?\n");
+        return AVERROR(EINVAL);
+    }
     s->dsp.put_pixels_tab[!s->is_16bpp][0](s->pixel_ptr, src->data[0] + motion_offset,
                                            s->current_frame.linesize[0], 8);
     return 0;
@@ -965,7 +970,7 @@ static void ipvideo_decode_opcodes(IpvideoContext *s)
 
     if (!s->is_16bpp) {
         /* this is PAL8, so make the palette available */
-        memcpy(s->current_frame.data[1], s->avctx->palctrl->palette, PALETTE_COUNT * 4);
+        memcpy(s->current_frame.data[1], s->pal, AVPALETTE_SIZE);
 
         s->stride = s->current_frame.linesize[0];
         s->stream_ptr = s->buf + 14;  /* data starts 14 bytes in */
@@ -1019,10 +1024,6 @@ static av_cold int ipvideo_decode_init(AVCodecContext *avctx)
 
     s->is_16bpp = avctx->bits_per_coded_sample == 16;
     avctx->pix_fmt = s->is_16bpp ? PIX_FMT_RGB555 : PIX_FMT_PAL8;
-    if (!s->is_16bpp && s->avctx->palctrl == NULL) {
-        av_log(avctx, AV_LOG_ERROR, " Interplay video: palette expected.\n");
-        return -1;
-    }
 
     dsputil_init(&s->dsp, avctx);
 
@@ -1042,7 +1043,6 @@ static int ipvideo_decode_frame(AVCodecContext *avctx,
     const uint8_t *buf = avpkt->data;
     int buf_size = avpkt->size;
     IpvideoContext *s = avctx->priv_data;
-    AVPaletteControl *palette_control = avctx->palctrl;
 
     /* compressed buffer needs to be large enough to at least hold an entire
      * decoding map */
@@ -1059,13 +1059,16 @@ static int ipvideo_decode_frame(AVCodecContext *avctx,
         return -1;
     }
 
-    ipvideo_decode_opcodes(s);
-
-    if (!s->is_16bpp && palette_control->palette_changed) {
-        palette_control->palette_changed = 0;
-        s->current_frame.palette_has_changed = 1;
+    if (!s->is_16bpp) {
+        const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, NULL);
+        if (pal) {
+            s->current_frame.palette_has_changed = 1;
+            memcpy(s->pal, pal, AVPALETTE_SIZE);
+        }
     }
 
+    ipvideo_decode_opcodes(s);
+
     *data_size = sizeof(AVFrame);
     *(AVFrame*)data = s->current_frame;
 
@@ -1093,7 +1096,7 @@ static av_cold int ipvideo_decode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec interplay_video_decoder = {
+AVCodec ff_interplay_video_decoder = {
     "interplayvideo",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_INTERPLAY_VIDEO,
diff --git a/libavcodec/intrax8.c b/libavcodec/intrax8.c
index 75166e8..69f940a 100644
--- a/libavcodec/intrax8.c
+++ b/libavcodec/intrax8.c
@@ -1,18 +1,18 @@
 /*
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/intrax8.h b/libavcodec/intrax8.h
index 8ce4f8d..3a58938 100644
--- a/libavcodec/intrax8.h
+++ b/libavcodec/intrax8.h
@@ -1,18 +1,18 @@
 /*
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/intrax8dsp.c b/libavcodec/intrax8dsp.c
index 692e1b1..1a62fcd 100644
--- a/libavcodec/intrax8dsp.c
+++ b/libavcodec/intrax8dsp.c
@@ -1,18 +1,18 @@
 /*
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/intrax8huf.h b/libavcodec/intrax8huf.h
index 375906b..6bf01f3 100644
--- a/libavcodec/intrax8huf.h
+++ b/libavcodec/intrax8huf.h
@@ -1,18 +1,18 @@
 /*
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/inverse.c b/libavcodec/inverse.c
new file mode 100644
index 0000000..04681d2
--- /dev/null
+++ b/libavcodec/inverse.c
@@ -0,0 +1 @@
+#include "libavutil/inverse.c"
diff --git a/libavcodec/ituh263dec.c b/libavcodec/ituh263dec.c
index 8b5d939..676349c 100644
--- a/libavcodec/ituh263dec.c
+++ b/libavcodec/ituh263dec.c
@@ -5,20 +5,20 @@
  * Copyright (c) 2001 Juan J. Sierralta P
  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -325,7 +325,7 @@ static int h263p_decode_umotion(MpegEncContext * s, int pred)
    code >>= 1;
 
    code = (sign) ? (pred - code) : (pred + code);
-   dprintf(s->avctx,"H.263+ UMV Motion = %d\n", code);
+   av_dlog(s->avctx,"H.263+ UMV Motion = %d\n", code);
    return code;
 
 }
@@ -951,7 +951,7 @@ int h263_decode_picture_header(MpegEncContext *s)
         if (ufep == 1) {
             /* OPPTYPE */
             format = get_bits(&s->gb, 3);
-            dprintf(s->avctx, "ufep=1, format: %d\n", format);
+            av_dlog(s->avctx, "ufep=1, format: %d\n", format);
             s->custom_pcf= get_bits1(&s->gb);
             s->umvplus = get_bits1(&s->gb); /* Unrestricted Motion Vector */
             if (get_bits1(&s->gb) != 0) {
@@ -1002,7 +1002,7 @@ int h263_decode_picture_header(MpegEncContext *s)
             if (format == 6) {
                 /* Custom Picture Format (CPFMT) */
                 s->aspect_ratio_info = get_bits(&s->gb, 4);
-                dprintf(s->avctx, "aspect: %d\n", s->aspect_ratio_info);
+                av_dlog(s->avctx, "aspect: %d\n", s->aspect_ratio_info);
                 /* aspect ratios:
                 0 - forbidden
                 1 - 1:1
@@ -1015,7 +1015,7 @@ int h263_decode_picture_header(MpegEncContext *s)
                 width = (get_bits(&s->gb, 9) + 1) * 4;
                 skip_bits1(&s->gb);
                 height = get_bits(&s->gb, 9) * 4;
-                dprintf(s->avctx, "\nH.263+ Custom picture: %dx%d\n",width,height);
+                av_dlog(s->avctx, "\nH.263+ Custom picture: %dx%d\n",width,height);
                 if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) {
                     /* aspected dimensions */
                     s->avctx->sample_aspect_ratio.num= get_bits(&s->gb, 8);
diff --git a/libavcodec/ituh263enc.c b/libavcodec/ituh263enc.c
index f736d7c..6a9a174 100644
--- a/libavcodec/ituh263enc.c
+++ b/libavcodec/ituh263enc.c
@@ -5,20 +5,20 @@
  * Copyright (c) 2001 Juan J. Sierralta P
  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -84,7 +84,7 @@ static const uint8_t wrong_run[102] = {
 };
 
 /**
- * Returns the 4 bit value that specifies the given aspect ratio.
+ * Return the 4 bit value that specifies the given aspect ratio.
  * This may be one of the standard aspect ratios or it specifies
  * that the aspect will be stored explicitly later.
  */
@@ -162,7 +162,7 @@ void h263_encode_picture_header(MpegEncContext * s, int picture_number)
 
         put_bits(&s->pb, 3, 7);
         put_bits(&s->pb,3,ufep); /* Update Full Extended PTYPE */
-        if (format == 7)
+        if (format == 8)
             put_bits(&s->pb,3,6); /* Custom Source Format */
         else
             put_bits(&s->pb, 3, format);
@@ -192,7 +192,7 @@ void h263_encode_picture_header(MpegEncContext * s, int picture_number)
         /* This should be here if PLUSPTYPE */
         put_bits(&s->pb, 1, 0); /* Continuous Presence Multipoint mode: off */
 
-                if (format == 7) {
+        if (format == 8) {
             /* Custom Picture Format (CPFMT) */
             s->aspect_ratio_info= ff_h263_aspect_to_info(s->avctx->sample_aspect_ratio);
 
@@ -245,7 +245,7 @@ void h263_encode_picture_header(MpegEncContext * s, int picture_number)
 }
 
 /**
- * Encodes a group of blocks header.
+ * Encode a group of blocks header.
  */
 void h263_encode_gob_header(MpegEncContext * s, int mb_line)
 {
diff --git a/libavcodec/ivi_common.c b/libavcodec/ivi_common.c
index a0596f6..ac4c68e 100644
--- a/libavcodec/ivi_common.c
+++ b/libavcodec/ivi_common.c
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2009 Maxim Poliakovski
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -40,7 +40,7 @@ VLC ff_ivi_mb_vlc_tabs [8];
 VLC ff_ivi_blk_vlc_tabs[8];
 
 /**
- *  Reverses "nbits" bits of the value "val" and returns the result
+ *  Reverse "nbits" bits of the value "val" and return the result
  *  in the least significant bits.
  */
 static uint16_t inv_bits(uint16_t val, int nbits)
@@ -338,7 +338,8 @@ int ff_ivi_decode_blocks(GetBitContext *gb, IVIBandDesc *band, IVITile *tile)
     RVMapDesc   *rvmap = band->rv_map;
     void (*mc_with_delta_func)(int16_t *buf, const int16_t *ref_buf, uint32_t pitch, int mc_type);
     void (*mc_no_delta_func)  (int16_t *buf, const int16_t *ref_buf, uint32_t pitch, int mc_type);
-    const uint8_t   *base_tab, *scale_tab;
+    const uint16_t  *base_tab;
+    const uint8_t   *scale_tab;
 
     prev_dc = 0; /* init intra prediction for the DC coefficient */
 
@@ -363,6 +364,8 @@ int ff_ivi_decode_blocks(GetBitContext *gb, IVIBandDesc *band, IVITile *tile)
 
         base_tab  = is_intra ? band->intra_base  : band->inter_base;
         scale_tab = is_intra ? band->intra_scale : band->inter_scale;
+        if (scale_tab)
+            quant = scale_tab[quant];
 
         if (!is_intra) {
             mv_x = mb->mv_x;
@@ -401,6 +404,10 @@ int ff_ivi_decode_blocks(GetBitContext *gb, IVIBandDesc *band, IVITile *tile)
                         hi  = get_vlc2(gb, band->blk_vlc.tab->table, IVI_VLC_BITS, 1);
                         val = IVI_TOSIGNED((hi << 6) | lo); /* merge them and convert into signed val */
                     } else {
+                        if (sym >= 256U) {
+                            av_log(NULL, AV_LOG_ERROR, "Invalid sym encountered: %d.\n", sym);
+                            return -1;
+                        }
                         run = rvmap->runtab[sym];
                         val = rvmap->valtab[sym];
                     }
@@ -414,9 +421,9 @@ int ff_ivi_decode_blocks(GetBitContext *gb, IVIBandDesc *band, IVITile *tile)
                     if (IVI_DEBUG && !val)
                         av_log(NULL, AV_LOG_ERROR, "Val = 0 encountered!\n");
 
-                    q = (base_tab[pos] * scale_tab[quant]) >> 8;
+                    q = (base_tab[pos] * quant) >> 9;
                     if (q > 1)
-                        val = val * q + FFSIGN(val) * ((q >> 1) - (q & 1));
+                        val = val * q + FFSIGN(val) * (((q ^ 1) - 1) >> 1);
                     trvec[pos] = val;
                     col_flags[pos & col_mask] |= !!val; /* track columns containing non-zero coeffs */
                 }// while
@@ -643,6 +650,36 @@ const IVIHuffDesc ff_ivi_blk_huff_desc[8] = {
 
 
 /**
+ *  Scan patterns shared between indeo4 and indeo5
+ */
+const uint8_t ff_ivi_vertical_scan_8x8[64] = {
+    0,  8, 16, 24, 32, 40, 48, 56,
+    1,  9, 17, 25, 33, 41, 49, 57,
+    2, 10, 18, 26, 34, 42, 50, 58,
+    3, 11, 19, 27, 35, 43, 51, 59,
+    4, 12, 20, 28, 36, 44, 52, 60,
+    5, 13, 21, 29, 37, 45, 53, 61,
+    6, 14, 22, 30, 38, 46, 54, 62,
+    7, 15, 23, 31, 39, 47, 55, 63
+};
+
+const uint8_t ff_ivi_horizontal_scan_8x8[64] = {
+     0,  1,  2,  3,  4,  5,  6,  7,
+     8,  9, 10, 11, 12, 13, 14, 15,
+    16, 17, 18, 19, 20, 21, 22, 23,
+    24, 25, 26, 27, 28, 29, 30, 31,
+    32, 33, 34, 35, 36, 37, 38, 39,
+    40, 41, 42, 43, 44, 45, 46, 47,
+    48, 49, 50, 51, 52, 53, 54, 55,
+    56, 57, 58, 59, 60, 61, 62, 63
+};
+
+const uint8_t ff_ivi_direct_scan_4x4[16] = {
+    0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15
+};
+
+
+/**
  *  Run-value (RLE) tables.
  */
 const RVMapDesc ff_ivi_rvmap_tabs[9] = {
diff --git a/libavcodec/ivi_common.h b/libavcodec/ivi_common.h
index 64793e4..582a1d7 100644
--- a/libavcodec/ivi_common.h
+++ b/libavcodec/ivi_common.h
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2009 Maxim Poliakovski
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -68,6 +68,21 @@ extern VLC ff_ivi_blk_vlc_tabs[8]; ///< static block Huffman tables
 
 
 /**
+ *  Common scan patterns (defined in ivi_common.c)
+ */
+extern const uint8_t ff_ivi_vertical_scan_8x8[64];
+extern const uint8_t ff_ivi_horizontal_scan_8x8[64];
+extern const uint8_t ff_ivi_direct_scan_4x4[16];
+
+
+/**
+ *  Declare inverse transform function types
+ */
+typedef void (InvTransformPtr)(const int32_t *in, int16_t *out, uint32_t pitch, const uint8_t *flags);
+typedef void (DCTransformPtr) (const int32_t *in, int16_t *out, uint32_t pitch, int blk_size);
+
+
+/**
  *  run-value (RLE) table descriptor
  */
 typedef struct {
@@ -138,22 +153,20 @@ typedef struct {
 
     IVIHuffTab      blk_vlc;        ///< vlc table for decoding block data
 
-    uint16_t        *dequant_intra; ///< ptr to dequant tables for intra blocks
-    uint16_t        *dequant_inter; ///< ptr dequant tables for inter blocks
     int             num_corr;       ///< number of correction entries
     uint8_t         corr[61*2];     ///< rvmap correction pairs
     int             rvmap_sel;      ///< rvmap table selector
     RVMapDesc       *rv_map;        ///< ptr to the RLE table for this band
     int             num_tiles;      ///< number of tiles in this band
     IVITile         *tiles;         ///< array of tile descriptors
-    void (*inv_transform)(const int32_t *in, int16_t *out, uint32_t pitch, const uint8_t *flags); ///< inverse transform function pointer
-    void (*dc_transform) (const int32_t *in, int16_t *out, uint32_t pitch, int blk_size);   ///< dc transform function pointer, it may be NULL
+    InvTransformPtr *inv_transform;
+    DCTransformPtr  *dc_transform;
     int             is_2d_trans;    ///< 1 indicates that the two-dimensional inverse transform is used
     int32_t         checksum;       ///< for debug purposes
     int             checksum_present;
     int             bufsize;        ///< band buffer size in bytes
-    const uint8_t   *intra_base;    ///< quantization matrix for intra blocks
-    const uint8_t   *inter_base;    ///< quantization matrix for inter blocks
+    const uint16_t  *intra_base;    ///< quantization matrix for intra blocks
+    const uint16_t  *inter_base;    ///< quantization matrix for inter blocks
     const uint8_t   *intra_scale;   ///< quantization coefficient for intra blocks
     const uint8_t   *inter_scale;   ///< quantization coefficient for inter blocks
 } IVIBandDesc;
@@ -181,7 +194,7 @@ typedef struct {
     uint8_t     chroma_bands;
 } IVIPicConfig;
 
-/** compares some properties of two pictures */
+/** compare some properties of two pictures */
 static inline int ivi_pic_config_cmp(IVIPicConfig *str1, IVIPicConfig *str2)
 {
     return (str1->pic_width    != str2->pic_width    || str1->pic_height    != str2->pic_height    ||
@@ -200,141 +213,141 @@ static inline int ivi_pic_config_cmp(IVIPicConfig *str1, IVIPicConfig *str2)
 /** convert unsigned values into signed ones (the sign is in the LSB) */
 #define IVI_TOSIGNED(val) (-(((val) >> 1) ^ -((val) & 1)))
 
-/** scales motion vector */
+/** scale motion vector */
 static inline int ivi_scale_mv(int mv, int mv_scale)
 {
     return (mv + (mv > 0) + (mv_scale - 1)) >> mv_scale;
 }
 
 /**
- *  Generates a huffman codebook from the given descriptor
- *  and converts it into the FFmpeg VLC table.
+ *  Generate a huffman codebook from the given descriptor
+ *  and convert it into the Libav VLC table.
  *
- *  @param cb   [in]  pointer to codebook descriptor
- *  @param vlc  [out] where to place the generated VLC table
- *  @param flag [in]  flag: 1 - for static or 0 for dynamic tables
+ *  @param[in]   cb    pointer to codebook descriptor
+ *  @param[out]  vlc   where to place the generated VLC table
+ *  @param[in]   flag  flag: 1 - for static or 0 for dynamic tables
  *  @return     result code: 0 - OK, -1 = error (invalid codebook descriptor)
  */
 int  ff_ivi_create_huff_from_desc(const IVIHuffDesc *cb, VLC *vlc, int flag);
 
 /**
- * Initializes static codes used for macroblock and block decoding.
+ * Initialize static codes used for macroblock and block decoding.
  */
 void ff_ivi_init_static_vlc(void);
 
 /**
- *  Decodes a huffman codebook descriptor from the bitstream
- *  and selects specified huffman table.
+ *  Decode a huffman codebook descriptor from the bitstream
+ *  and select specified huffman table.
  *
- *  @param gb           [in,out] the GetBit context
- *  @param desc_coded   [in] flag signalling if table descriptor was coded
- *  @param which_tab    [in] codebook purpose (IVI_MB_HUFF or IVI_BLK_HUFF)
- *  @param huff_tab     [out] pointer to the descriptor of the selected table
- *  @param avctx        [in] AVCodecContext pointer
+ *  @param[in,out]  gb          the GetBit context
+ *  @param[in]      desc_coded  flag signalling if table descriptor was coded
+ *  @param[in]      which_tab   codebook purpose (IVI_MB_HUFF or IVI_BLK_HUFF)
+ *  @param[out]     huff_tab    pointer to the descriptor of the selected table
+ *  @param[in]      avctx       AVCodecContext pointer
  *  @return             zero on success, negative value otherwise
  */
 int  ff_ivi_dec_huff_desc(GetBitContext *gb, int desc_coded, int which_tab,
                           IVIHuffTab *huff_tab, AVCodecContext *avctx);
 
 /**
- *  Compares two huffman codebook descriptors.
+ *  Compare two huffman codebook descriptors.
  *
- *  @param desc1    [in] ptr to the 1st descriptor to compare
- *  @param desc2    [in] ptr to the 2nd descriptor to compare
+ *  @param[in]  desc1  ptr to the 1st descriptor to compare
+ *  @param[in]  desc2  ptr to the 2nd descriptor to compare
  *  @return         comparison result: 0 - equal, 1 - not equal
  */
 int  ff_ivi_huff_desc_cmp(const IVIHuffDesc *desc1, const IVIHuffDesc *desc2);
 
 /**
- *  Copies huffman codebook descriptors.
+ *  Copy huffman codebook descriptors.
  *
- *  @param dst  [out] ptr to the destination descriptor
- *  @param src  [in]  ptr to the source descriptor
+ *  @param[out]  dst  ptr to the destination descriptor
+ *  @param[in]   src  ptr to the source descriptor
  */
 void ff_ivi_huff_desc_copy(IVIHuffDesc *dst, const IVIHuffDesc *src);
 
 /**
- *  Initializes planes (prepares descriptors, allocates buffers etc).
+ *  Initialize planes (prepares descriptors, allocates buffers etc).
  *
- *  @param planes       [in,out] pointer to the array of the plane descriptors
- *  @param cfg          [in] pointer to the ivi_pic_config structure describing picture layout
+ *  @param[in,out]  planes  pointer to the array of the plane descriptors
+ *  @param[in]      cfg     pointer to the ivi_pic_config structure describing picture layout
  *  @return             result code: 0 - OK
  */
 int  ff_ivi_init_planes(IVIPlaneDesc *planes, const IVIPicConfig *cfg);
 
 /**
- *  Frees planes, bands and macroblocks buffers.
+ *  Free planes, bands and macroblocks buffers.
  *
- *  @param planes       [in] pointer to the array of the plane descriptors
+ *  @param[in]  planes  pointer to the array of the plane descriptors
  */
 void ff_ivi_free_buffers(IVIPlaneDesc *planes);
 
 /**
- *  Initializes tile and macroblock descriptors.
+ *  Initialize tile and macroblock descriptors.
  *
- *  @param planes       [in,out] pointer to the array of the plane descriptors
- *  @param tile_width   [in]     tile width
- *  @param tile_height  [in]     tile height
+ *  @param[in,out]  planes       pointer to the array of the plane descriptors
+ *  @param[in]      tile_width   tile width
+ *  @param[in]      tile_height  tile height
  *  @return             result code: 0 - OK
  */
 int  ff_ivi_init_tiles(IVIPlaneDesc *planes, int tile_width, int tile_height);
 
 /**
- *  Decodes size of the tile data.
+ *  Decode size of the tile data.
  *  The size is stored as a variable-length field having the following format:
  *  if (tile_data_size < 255) than this field is only one byte long
  *  if (tile_data_size >= 255) than this field four is byte long: 0xFF X1 X2 X3
  *  where X1-X3 is size of the tile data
  *
- *  @param gb   [in,out] the GetBit context
+ *  @param[in,out]  gb  the GetBit context
  *  @return     size of the tile data in bytes
  */
 int  ff_ivi_dec_tile_data_size(GetBitContext *gb);
 
 /**
- *  Decodes block data:
- *  extracts huffman-coded transform coefficients from the bitstream,
- *  dequantizes them, applies inverse transform and motion compensation
+ *  Decode block data:
+ *  extract huffman-coded transform coefficients from the bitstream,
+ *  dequantize them, apply inverse transform and motion compensation
  *  in order to reconstruct the picture.
  *
- *  @param gb   [in,out] the GetBit context
- *  @param band [in]     pointer to the band descriptor
- *  @param tile [in]     pointer to the tile descriptor
+ *  @param[in,out]  gb    the GetBit context
+ *  @param[in]      band  pointer to the band descriptor
+ *  @param[in]      tile  pointer to the tile descriptor
  *  @return     result code: 0 - OK, -1 = error (corrupted blocks data)
  */
 int  ff_ivi_decode_blocks(GetBitContext *gb, IVIBandDesc *band, IVITile *tile);
 
 /**
- *  Handles empty tiles by performing data copying and motion
+ *  Handle empty tiles by performing data copying and motion
  *  compensation respectively.
  *
- *  @param avctx    [in] ptr to the AVCodecContext
- *  @param band     [in] pointer to the band descriptor
- *  @param tile     [in] pointer to the tile descriptor
- *  @param mv_scale [in] scaling factor for motion vectors
+ *  @param[in]  avctx     ptr to the AVCodecContext
+ *  @param[in]  band      pointer to the band descriptor
+ *  @param[in]  tile      pointer to the tile descriptor
+ *  @param[in]  mv_scale  scaling factor for motion vectors
  */
 void ff_ivi_process_empty_tile(AVCodecContext *avctx, IVIBandDesc *band,
                                IVITile *tile, int32_t mv_scale);
 
 /**
- *  Converts and outputs the current plane.
+ *  Convert and output the current plane.
  *  This conversion is done by adding back the bias value of 128
  *  (subtracted in the encoder) and clipping the result.
  *
- *  @param plane        [in]  pointer to the descriptor of the plane being processed
- *  @param dst          [out] pointer to the buffer receiving converted pixels
- *  @param dst_pitch    [in]  pitch for moving to the next y line
+ *  @param[in]   plane      pointer to the descriptor of the plane being processed
+ *  @param[out]  dst        pointer to the buffer receiving converted pixels
+ *  @param[in]   dst_pitch  pitch for moving to the next y line
  */
 void ff_ivi_output_plane(IVIPlaneDesc *plane, uint8_t *dst, int dst_pitch);
 
 #if IVI_DEBUG
 /**
- *  Calculates band checksum from band data.
+ *  Calculate band checksum from band data.
  */
 uint16_t ivi_calc_band_checksum (IVIBandDesc *band);
 
 /**
- *  Verifies that band data lies in range.
+ *  Verify that band data lies in range.
  */
 int ivi_check_band (IVIBandDesc *band, const uint8_t *ref, int pitch);
 #endif
diff --git a/libavcodec/ivi_dsp.c b/libavcodec/ivi_dsp.c
index ccaffd4..6b62dc8 100644
--- a/libavcodec/ivi_dsp.c
+++ b/libavcodec/ivi_dsp.c
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2009 Maxim Poliakovski
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -461,7 +461,7 @@ void ff_ivi_mc_ ## size ##x## size ## suffix (int16_t *buf, const int16_t *ref_b
 #define OP_PUT(a, b)  (a) = (b)
 #define OP_ADD(a, b)  (a) += (b)
 
-IVI_MC_TEMPLATE(8, _no_delta, OP_PUT);
-IVI_MC_TEMPLATE(8, _delta,    OP_ADD);
-IVI_MC_TEMPLATE(4, _no_delta, OP_PUT);
-IVI_MC_TEMPLATE(4, _delta,    OP_ADD);
+IVI_MC_TEMPLATE(8, _no_delta, OP_PUT)
+IVI_MC_TEMPLATE(8, _delta,    OP_ADD)
+IVI_MC_TEMPLATE(4, _no_delta, OP_PUT)
+IVI_MC_TEMPLATE(4, _delta,    OP_ADD)
diff --git a/libavcodec/ivi_dsp.h b/libavcodec/ivi_dsp.h
index bdd9654..9632966 100644
--- a/libavcodec/ivi_dsp.h
+++ b/libavcodec/ivi_dsp.h
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2009 Maxim Poliakovski
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -35,10 +35,10 @@
 /**
  *  5/3 wavelet recomposition filter for Indeo5
  *
- *  @param plane        [in]  pointer to the descriptor of the plane being processed
- *  @param dst          [out] pointer to the destination buffer
- *  @param dst_pitch    [in]  pitch of the destination buffer
- *  @param num_bands    [in]  number of wavelet bands to be processed
+ *  @param[in]   plane        pointer to the descriptor of the plane being processed
+ *  @param[out]  dst          pointer to the destination buffer
+ *  @param[in]   dst_pitch    pitch of the destination buffer
+ *  @param[in]   num_bands    number of wavelet bands to be processed
  */
 void ff_ivi_recompose53(const IVIPlaneDesc *plane, uint8_t *dst,
                         const int dst_pitch, const int num_bands);
@@ -46,10 +46,10 @@ void ff_ivi_recompose53(const IVIPlaneDesc *plane, uint8_t *dst,
 /**
  *  two-dimensional inverse slant 8x8 transform
  *
- *  @param  in      [in]  pointer to the vector of transform coefficients
- *  @param  out     [out] pointer to the output buffer (frame)
- *  @param  pitch   [in]  pitch to move to the next y line
- *  @param  flags   [in]  pointer to the array of column flags:
+ *  @param[in]    in      pointer to the vector of transform coefficients
+ *  @param[out]   out     pointer to the output buffer (frame)
+ *  @param[in]    pitch   pitch to move to the next y line
+ *  @param[in]    flags   pointer to the array of column flags:
  *                        != 0 - non_empty column, 0 - empty one
  *                        (this array must be filled by caller)
  */
@@ -59,10 +59,10 @@ void ff_ivi_inverse_slant_8x8(const int32_t *in, int16_t *out, uint32_t pitch,
 /**
  *  two-dimensional inverse slant 4x4 transform
  *
- *  @param  in      [in]  pointer to the vector of transform coefficients
- *  @param  out     [out] pointer to the output buffer (frame)
- *  @param  pitch   [in]  pitch to move to the next y line
- *  @param  flags   [in]  pointer to the array of column flags:
+ *  @param[in]    in      pointer to the vector of transform coefficients
+ *  @param[out]   out     pointer to the output buffer (frame)
+ *  @param[in]    pitch   pitch to move to the next y line
+ *  @param[in]    flags   pointer to the array of column flags:
  *                        != 0 - non_empty column, 0 - empty one
  *                        (this array must be filled by caller)
  */
@@ -75,20 +75,20 @@ void ff_ivi_inverse_slant_4x4(const int32_t *in, int16_t *out, uint32_t pitch,
  *  spreading (DC_coeff + 1)/2 over the whole block.
  *  It works much faster than performing the slant transform on a vector of zeroes.
  *
- *  @param  in          [in]  pointer to the dc coefficient
- *  @param  out         [out] pointer to the output buffer (frame)
- *  @param  pitch       [in]  pitch to move to the next y line
- *  @param  blk_size    [in]  transform block size
+ *  @param[in]    in          pointer to the dc coefficient
+ *  @param[out]   out         pointer to the output buffer (frame)
+ *  @param[in]    pitch       pitch to move to the next y line
+ *  @param[in]    blk_size    transform block size
  */
 void ff_ivi_dc_slant_2d(const int32_t *in, int16_t *out, uint32_t pitch, int blk_size);
 
 /**
  *  inverse 1D row slant transform
  *
- *  @param  in      [in]  pointer to the vector of transform coefficients
- *  @param  out     [out] pointer to the output buffer (frame)
- *  @param  pitch   [in]  pitch to move to the next y line
- *  @param  flags   [in]  pointer to the array of column flags (unused here)
+ *  @param[in]    in      pointer to the vector of transform coefficients
+ *  @param[out]   out     pointer to the output buffer (frame)
+ *  @param[in]    pitch   pitch to move to the next y line
+ *  @param[in]    flags   pointer to the array of column flags (unused here)
  */
 void ff_ivi_row_slant8(const int32_t *in, int16_t *out, uint32_t pitch,
                        const uint8_t *flags);
@@ -96,10 +96,10 @@ void ff_ivi_row_slant8(const int32_t *in, int16_t *out, uint32_t pitch,
 /**
  *  inverse 1D column slant transform
  *
- *  @param  in      [in]  pointer to the vector of transform coefficients
- *  @param  out     [out] pointer to the output buffer (frame)
- *  @param  pitch   [in]  pitch to move to the next y line
- *  @param  flags   [in]  pointer to the array of column flags:
+ *  @param[in]    in      pointer to the vector of transform coefficients
+ *  @param[out]   out     pointer to the output buffer (frame)
+ *  @param[in]    pitch   pitch to move to the next y line
+ *  @param[in]    flags   pointer to the array of column flags:
  *                        != 0 - non_empty column, 0 - empty one
  *                        (this array must be filled by caller)
  */
@@ -117,53 +117,53 @@ void ff_ivi_dc_row_slant(const int32_t *in, int16_t *out, uint32_t pitch, int bl
 void ff_ivi_dc_col_slant(const int32_t *in, int16_t *out, uint32_t pitch, int blk_size);
 
 /**
- *  Copies the pixels into the frame buffer.
+ *  Copy the pixels into the frame buffer.
  */
 void ff_ivi_put_pixels_8x8(const int32_t *in, int16_t *out, uint32_t pitch, const uint8_t *flags);
 
 /**
- *  Copies the DC coefficient into the first pixel of the block and
- *  zeroes all others.
+ *  Copy the DC coefficient into the first pixel of the block and
+ *  zero all others.
  */
 void ff_ivi_put_dc_pixel_8x8(const int32_t *in, int16_t *out, uint32_t pitch, int blk_size);
 
 /**
  *  8x8 block motion compensation with adding delta
  *
- *  @param  buf     [in,out] pointer to the block in the current frame buffer containing delta
- *  @param  ref_buf [in]     pointer to the corresponding block in the reference frame
- *  @param  pitch   [in]     pitch for moving to the next y line
- *  @param  mc_type [in]     interpolation type
+ *  @param[in,out]   buf      pointer to the block in the current frame buffer containing delta
+ *  @param[in]       ref_buf  pointer to the corresponding block in the reference frame
+ *  @param[in]       pitch    pitch for moving to the next y line
+ *  @param[in]       mc_type  interpolation type
  */
 void ff_ivi_mc_8x8_delta(int16_t *buf, const int16_t *ref_buf, uint32_t pitch, int mc_type);
 
 /**
  *  4x4 block motion compensation with adding delta
  *
- *  @param  buf     [in,out] pointer to the block in the current frame buffer containing delta
- *  @param  ref_buf [in]     pointer to the corresponding block in the reference frame
- *  @param  pitch   [in]     pitch for moving to the next y line
- *  @param  mc_type [in]     interpolation type
+ *  @param[in,out]   buf      pointer to the block in the current frame buffer containing delta
+ *  @param[in]       ref_buf  pointer to the corresponding block in the reference frame
+ *  @param[in]       pitch    pitch for moving to the next y line
+ *  @param[in]       mc_type  interpolation type
  */
 void ff_ivi_mc_4x4_delta(int16_t *buf, const int16_t *ref_buf, uint32_t pitch, int mc_type);
 
 /**
  *  motion compensation without adding delta
  *
- *  @param  buf     [in,out] pointer to the block in the current frame receiving the result
- *  @param  ref_buf [in]     pointer to the corresponding block in the reference frame
- *  @param  pitch   [in]     pitch for moving to the next y line
- *  @param  mc_type [in]     interpolation type
+ *  @param[in,out]  buf      pointer to the block in the current frame receiving the result
+ *  @param[in]      ref_buf  pointer to the corresponding block in the reference frame
+ *  @param[in]      pitch    pitch for moving to the next y line
+ *  @param[in]      mc_type  interpolation type
  */
 void ff_ivi_mc_8x8_no_delta(int16_t *buf, const int16_t *ref_buf, uint32_t pitch, int mc_type);
 
 /**
  *  4x4 block motion compensation without adding delta
  *
- *  @param  buf     [in,out] pointer to the block in the current frame receiving the result
- *  @param  ref_buf [in]     pointer to the corresponding block in the reference frame
- *  @param  pitch   [in]     pitch for moving to the next y line
- *  @param  mc_type [in]     interpolation type
+ *  @param[in,out]  buf      pointer to the block in the current frame receiving the result
+ *  @param[in]      ref_buf  pointer to the corresponding block in the reference frame
+ *  @param[in]      pitch    pitch for moving to the next y line
+ *  @param[in]      mc_type  interpolation type
  */
 void ff_ivi_mc_4x4_no_delta(int16_t *buf, const int16_t *ref_buf, uint32_t pitch, int mc_type);
 
diff --git a/libavcodec/jpegls.c b/libavcodec/jpegls.c
index c40b929..ebe6b85 100644
--- a/libavcodec/jpegls.c
+++ b/libavcodec/jpegls.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2003 Michael Niedermayer
  * Copyright (c) 2006 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/jpegls.h b/libavcodec/jpegls.h
index 28c7524..1c1817e 100644
--- a/libavcodec/jpegls.h
+++ b/libavcodec/jpegls.h
@@ -3,20 +3,20 @@
  * Copyright (c) 2003 Michael Niedermayer
  * Copyright (c) 2006 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/jpeglsdec.c b/libavcodec/jpeglsdec.c
index 6b7dd94..69cc1d3 100644
--- a/libavcodec/jpeglsdec.c
+++ b/libavcodec/jpeglsdec.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2003 Michael Niedermayer
  * Copyright (c) 2006 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -40,7 +40,7 @@
 * (or test broken JPEG-LS decoder) and slow down ordinary decoding a bit.
 *
 * There is no Golomb code with length >= 32 bits possible, so check and
-* avoid situation of 32 zeros, FFmpeg Golomb decoder is painfully slow
+* avoid situation of 32 zeros, Libav Golomb decoder is painfully slow
 * on this errors.
 */
 //#define JLS_BROKEN
@@ -262,9 +262,9 @@ int ff_jpegls_decode_picture(MJpegDecodeContext *s, int near, int point_transfor
     JLSState *state;
     int off = 0, stride = 1, width, shift;
 
-    zero = av_mallocz(s->picture.linesize[0]);
+    zero = av_mallocz(s->picture_ptr->linesize[0]);
     last = zero;
-    cur = s->picture.data[0];
+    cur = s->picture_ptr->data[0];
 
     state = av_mallocz(sizeof(JLSState));
     /* initialize JPEG-LS state from JPEG parameters */
@@ -299,7 +299,7 @@ int ff_jpegls_decode_picture(MJpegDecodeContext *s, int near, int point_transfor
                 t = *((uint16_t*)last);
             }
             last = cur;
-            cur += s->picture.linesize[0];
+            cur += s->picture_ptr->linesize[0];
 
             if (s->restart_interval && !--s->restart_count) {
                 align_get_bits(&s->gb);
@@ -309,7 +309,7 @@ int ff_jpegls_decode_picture(MJpegDecodeContext *s, int near, int point_transfor
     } else if(ilv == 1) { /* line interleaving */
         int j;
         int Rc[3] = {0, 0, 0};
-        memset(cur, 0, s->picture.linesize[0]);
+        memset(cur, 0, s->picture_ptr->linesize[0]);
         width = s->width * 3;
         for(i = 0; i < s->height; i++) {
             for(j = 0; j < 3; j++) {
@@ -322,7 +322,7 @@ int ff_jpegls_decode_picture(MJpegDecodeContext *s, int near, int point_transfor
                 }
             }
             last = cur;
-            cur += s->picture.linesize[0];
+            cur += s->picture_ptr->linesize[0];
         }
     } else if(ilv == 2) { /* sample interleaving */
         av_log(s->avctx, AV_LOG_ERROR, "Sample interleaved images are not supported.\n");
@@ -337,22 +337,22 @@ int ff_jpegls_decode_picture(MJpegDecodeContext *s, int near, int point_transfor
         w = s->width * s->nb_components;
 
         if(s->bits <= 8){
-            uint8_t *src = s->picture.data[0];
+            uint8_t *src = s->picture_ptr->data[0];
 
             for(i = 0; i < s->height; i++){
                 for(x = off; x < w; x+= stride){
                     src[x] <<= shift;
                 }
-                src += s->picture.linesize[0];
+                src += s->picture_ptr->linesize[0];
             }
         }else{
-            uint16_t *src = (uint16_t*) s->picture.data[0];
+            uint16_t *src = (uint16_t*) s->picture_ptr->data[0];
 
             for(i = 0; i < s->height; i++){
                 for(x = 0; x < w; x++){
                     src[x] <<= shift;
                 }
-                src += s->picture.linesize[0]/2;
+                src += s->picture_ptr->linesize[0]/2;
             }
         }
     }
@@ -363,7 +363,7 @@ int ff_jpegls_decode_picture(MJpegDecodeContext *s, int near, int point_transfor
 }
 
 
-AVCodec jpegls_decoder = {
+AVCodec ff_jpegls_decoder = {
     "jpegls",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_JPEGLS,
diff --git a/libavcodec/jpeglsdec.h b/libavcodec/jpeglsdec.h
index 5204ecb..4732822 100644
--- a/libavcodec/jpeglsdec.h
+++ b/libavcodec/jpeglsdec.h
@@ -3,20 +3,20 @@
  * Copyright (c) 2003 Michael Niedermayer
  * Copyright (c) 2006 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/jpeglsenc.c b/libavcodec/jpeglsenc.c
index 08ef71f..56c6fb0 100644
--- a/libavcodec/jpeglsenc.c
+++ b/libavcodec/jpeglsenc.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2003 Michael Niedermayer
  * Copyright (c) 2006 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -382,7 +382,7 @@ static av_cold int encode_init_ls(AVCodecContext *ctx) {
     return 0;
 }
 
-AVCodec jpegls_encoder = { //FIXME avoid MPV_* lossless JPEG should not need them
+AVCodec ff_jpegls_encoder = { //FIXME avoid MPV_* lossless JPEG should not need them
     "jpegls",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_JPEGLS,
diff --git a/libavcodec/jvdec.c b/libavcodec/jvdec.c
new file mode 100644
index 0000000..8f19ba3
--- /dev/null
+++ b/libavcodec/jvdec.c
@@ -0,0 +1,215 @@
+/*
+ * Bitmap Brothers JV video decoder
+ * Copyright (c) 2011 Peter Ross <pross at xvid.org>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * Bitmap Brothers JV video decoder
+ * @author Peter Ross <pross at xvid.org>
+ */
+
+#include "avcodec.h"
+#include "dsputil.h"
+#include "get_bits.h"
+#include "libavutil/intreadwrite.h"
+
+typedef struct JvContext {
+    DSPContext dsp;
+    AVFrame    frame;
+    uint32_t   palette[AVPALETTE_COUNT];
+    int        palette_has_changed;
+} JvContext;
+
+static av_cold int decode_init(AVCodecContext *avctx)
+{
+    JvContext *s = avctx->priv_data;
+    avctx->pix_fmt = PIX_FMT_PAL8;
+    dsputil_init(&s->dsp, avctx);
+    return 0;
+}
+
+/**
+ * Decode 2x2 block
+ */
+static inline void decode2x2(GetBitContext *gb, uint8_t *dst, int linesize)
+{
+    int i, j, v[2];
+
+    switch (get_bits(gb, 2)) {
+    case 1:
+        v[0] = get_bits(gb, 8);
+        for (j = 0; j < 2; j++)
+            memset(dst + j*linesize, v[0], 2);
+        break;
+    case 2:
+        v[0] = get_bits(gb, 8);
+        v[1] = get_bits(gb, 8);
+        for (j = 0; j < 2; j++)
+            for (i = 0; i < 2; i++)
+                dst[j*linesize + i] = v[get_bits1(gb)];
+        break;
+    case 3:
+        for (j = 0; j < 2; j++)
+            for (i = 0; i < 2; i++)
+                dst[j*linesize + i] = get_bits(gb, 8);
+    }
+}
+
+/**
+ * Decode 4x4 block
+ */
+static inline void decode4x4(GetBitContext *gb, uint8_t *dst, int linesize)
+{
+    int i, j, v[2];
+
+    switch (get_bits(gb, 2)) {
+    case 1:
+        v[0] = get_bits(gb, 8);
+        for (j = 0; j < 4; j++)
+            memset(dst + j*linesize, v[0], 4);
+        break;
+    case 2:
+        v[0] = get_bits(gb, 8);
+        v[1] = get_bits(gb, 8);
+        for (j = 2; j >= 0; j -= 2) {
+            for (i = 0; i < 4; i++)
+                dst[j*linesize + i]     = v[get_bits1(gb)];
+            for (i = 0; i < 4; i++)
+                dst[(j+1)*linesize + i] = v[get_bits1(gb)];
+        }
+        break;
+    case 3:
+        for (j = 0; j < 4; j += 2)
+            for (i = 0; i < 4; i += 2)
+                decode2x2(gb, dst + j*linesize + i, linesize);
+    }
+}
+
+/**
+ * Decode 8x8 block
+ */
+static inline void decode8x8(GetBitContext *gb, uint8_t *dst, int linesize, DSPContext *dsp)
+{
+    int i, j, v[2];
+
+    switch (get_bits(gb, 2)) {
+    case 1:
+        v[0] = get_bits(gb, 8);
+        dsp->fill_block_tab[1](dst, v[0], linesize, 8);
+        break;
+    case 2:
+        v[0] = get_bits(gb, 8);
+        v[1] = get_bits(gb, 8);
+        for (j = 7; j >= 0; j--)
+            for (i = 0; i <  8; i++)
+                dst[j*linesize + i] = v[get_bits1(gb)];
+        break;
+    case 3:
+        for (j = 0; j < 8; j += 4)
+            for (i = 0; i < 8; i += 4)
+                decode4x4(gb, dst + j*linesize + i, linesize);
+    }
+}
+
+static int decode_frame(AVCodecContext *avctx,
+                        void *data, int *data_size,
+                        AVPacket *avpkt)
+{
+    JvContext *s           = avctx->priv_data;
+    int buf_size           = avpkt->size;
+    const uint8_t *buf     = avpkt->data;
+    const uint8_t *buf_end = buf + buf_size;
+    int video_size, video_type, i, j;
+
+    video_size = AV_RL32(buf);
+    video_type = buf[4];
+    buf += 5;
+
+    if (video_size) {
+        if (avctx->reget_buffer(avctx, &s->frame) < 0) {
+            av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
+            return -1;
+        }
+
+        if (video_type == 0 || video_type == 1) {
+            GetBitContext gb;
+            init_get_bits(&gb, buf, FFMIN(video_size, buf_end - buf));
+
+            for (j = 0; j < avctx->height; j += 8)
+                for (i = 0; i < avctx->width; i += 8)
+                    decode8x8(&gb, s->frame.data[0] + j*s->frame.linesize[0] + i,
+                              s->frame.linesize[0], &s->dsp);
+
+            buf += video_size;
+        } else if (video_type == 2) {
+            if (buf + 1 <= buf_end) {
+                int v = *buf++;
+                for (j = 0; j < avctx->height; j++)
+                    memset(s->frame.data[0] + j*s->frame.linesize[0], v, avctx->width);
+            }
+        } else {
+            av_log(avctx, AV_LOG_WARNING, "unsupported frame type %i\n", video_type);
+            return AVERROR_INVALIDDATA;
+        }
+    }
+
+    if (buf < buf_end) {
+        for (i = 0; i < AVPALETTE_COUNT && buf + 3 <= buf_end; i++) {
+            s->palette[i] = AV_RB24(buf) << 2;
+            buf += 3;
+        }
+        s->palette_has_changed = 1;
+    }
+
+    if (video_size) {
+        s->frame.key_frame           = 1;
+        s->frame.pict_type           = FF_I_TYPE;
+        s->frame.palette_has_changed = s->palette_has_changed;
+        s->palette_has_changed       = 0;
+        memcpy(s->frame.data[1], s->palette, AVPALETTE_SIZE);
+
+        *data_size      = sizeof(AVFrame);
+        *(AVFrame*)data = s->frame;
+    }
+
+    return buf_size;
+}
+
+static av_cold int decode_close(AVCodecContext *avctx)
+{
+    JvContext *s = avctx->priv_data;
+
+    if(s->frame.data[0])
+        avctx->release_buffer(avctx, &s->frame);
+
+    return 0;
+}
+
+AVCodec ff_jv_decoder = {
+    .name           = "jv",
+    .long_name      = NULL_IF_CONFIG_SMALL("Bitmap Brothers JV video"),
+    .type           = AVMEDIA_TYPE_VIDEO,
+    .id             = CODEC_ID_JV,
+    .priv_data_size = sizeof(JvContext),
+    .init           = decode_init,
+    .close          = decode_close,
+    .decode         = decode_frame,
+    .capabilities   = CODEC_CAP_DR1,
+};
diff --git a/libavcodec/kbdwin.c b/libavcodec/kbdwin.c
new file mode 100644
index 0000000..c2c1c59
--- /dev/null
+++ b/libavcodec/kbdwin.c
@@ -0,0 +1,48 @@
+/*
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <assert.h>
+#include <libavutil/mathematics.h>
+#include "libavutil/attributes.h"
+#include "kbdwin.h"
+
+#define BESSEL_I0_ITER 50 // default: 50 iterations of Bessel I0 approximation
+
+av_cold void ff_kbd_window_init(float *window, float alpha, int n)
+{
+   int i, j;
+   double sum = 0.0, bessel, tmp;
+   double local_window[FF_KBD_WINDOW_MAX];
+   double alpha2 = (alpha * M_PI / n) * (alpha * M_PI / n);
+
+   assert(n <= FF_KBD_WINDOW_MAX);
+
+   for (i = 0; i < n; i++) {
+       tmp = i * (n - i) * alpha2;
+       bessel = 1.0;
+       for (j = BESSEL_I0_ITER; j > 0; j--)
+           bessel = bessel * tmp / (j * j) + 1;
+       sum += bessel;
+       local_window[i] = sum;
+   }
+
+   sum++;
+   for (i = 0; i < n; i++)
+       window[i] = sqrt(local_window[i] / sum);
+}
+
diff --git a/libavcodec/kbdwin.h b/libavcodec/kbdwin.h
new file mode 100644
index 0000000..5ac2b8c
--- /dev/null
+++ b/libavcodec/kbdwin.h
@@ -0,0 +1,35 @@
+/*
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_KBDWIN_H
+#define AVCODEC_KBDWIN_H
+
+/**
+ * Maximum window size for ff_kbd_window_init.
+ */
+#define FF_KBD_WINDOW_MAX 1024
+
+/**
+ * Generate a Kaiser-Bessel Derived Window.
+ * @param   window  pointer to half window
+ * @param   alpha   determines window shape
+ * @param   n       size of half window, max FF_KBD_WINDOW_MAX
+ */
+void ff_kbd_window_init(float *window, float alpha, int n);
+
+#endif
diff --git a/libavcodec/kgv1dec.c b/libavcodec/kgv1dec.c
index 5af6b3b..5768434 100644
--- a/libavcodec/kgv1dec.c
+++ b/libavcodec/kgv1dec.c
@@ -2,20 +2,20 @@
  * Kega Game Video (KGV1) decoder
  * Copyright (c) 2010 Daniel Verkamp
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,6 +25,7 @@
  */
 
 #include "libavutil/intreadwrite.h"
+#include "libavutil/imgutils.h"
 #include "avcodec.h"
 
 typedef struct {
@@ -50,7 +51,7 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPac
     h = (buf[1] + 1) * 8;
     buf += 2;
 
-    if (avcodec_check_dimensions(avctx, w, h))
+    if (av_image_check_size(w, h, 0, avctx))
         return -1;
 
     if (w != avctx->width || h != avctx->height)
@@ -163,7 +164,7 @@ static av_cold int decode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec kgv1_decoder = {
+AVCodec ff_kgv1_decoder = {
     "kgv1",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_KGV1,
@@ -172,5 +173,6 @@ AVCodec kgv1_decoder = {
     NULL,
     decode_end,
     decode_frame,
+    .max_lowres = 1,
     .long_name = NULL_IF_CONFIG_SMALL("Kega Game Video"),
 };
diff --git a/libavcodec/kmvc.c b/libavcodec/kmvc.c
index 3e8dccd..c41c882 100644
--- a/libavcodec/kmvc.c
+++ b/libavcodec/kmvc.c
@@ -2,20 +2,20 @@
  * KMVC decoder
  * Copyright (c) 2006 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -233,6 +233,7 @@ static int decode_frame(AVCodecContext * avctx, void *data, int *data_size, AVPa
     int i;
     int header;
     int blocksize;
+    const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, NULL);
 
     if (ctx->pic.data[0])
         avctx->release_buffer(avctx, &ctx->pic);
@@ -264,13 +265,6 @@ static int decode_frame(AVCodecContext * avctx, void *data, int *data_size, AVPa
         ctx->pic.pict_type = FF_P_TYPE;
     }
 
-    /* if palette has been changed, copy it from palctrl */
-    if (ctx->avctx->palctrl && ctx->avctx->palctrl->palette_changed) {
-        memcpy(ctx->pal, ctx->avctx->palctrl->palette, AVPALETTE_SIZE);
-        ctx->setpal = 1;
-        ctx->avctx->palctrl->palette_changed = 0;
-    }
-
     if (header & KMVC_PALETTE) {
         ctx->pic.palette_has_changed = 1;
         // palette starts from index 1 and has 127 entries
@@ -279,6 +273,11 @@ static int decode_frame(AVCodecContext * avctx, void *data, int *data_size, AVPa
         }
     }
 
+    if (pal) {
+        ctx->pic.palette_has_changed = 1;
+        memcpy(ctx->pal, pal, AVPALETTE_SIZE);
+    }
+
     if (ctx->setpal) {
         ctx->setpal = 0;
         ctx->pic.palette_has_changed = 1;
@@ -374,9 +373,6 @@ static av_cold int decode_init(AVCodecContext * avctx)
             src += 4;
         }
         c->setpal = 1;
-        if (c->avctx->palctrl) {
-            c->avctx->palctrl->palette_changed = 0;
-        }
     }
 
     avctx->pix_fmt = PIX_FMT_PAL8;
@@ -401,7 +397,7 @@ static av_cold int decode_end(AVCodecContext * avctx)
     return 0;
 }
 
-AVCodec kmvc_decoder = {
+AVCodec ff_kmvc_decoder = {
     "kmvc",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_KMVC,
diff --git a/libavcodec/lagarith.c b/libavcodec/lagarith.c
new file mode 100644
index 0000000..53f274d
--- /dev/null
+++ b/libavcodec/lagarith.c
@@ -0,0 +1,522 @@
+/*
+ * Lagarith lossless decoder
+ * Copyright (c) 2009 Nathan Caldwell <saintdev (at) gmail.com>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file libavcodec/lagarith.c
+ * Lagarith lossless decoder
+ * @author Nathan Caldwell
+ */
+
+#include "avcodec.h"
+#include "get_bits.h"
+#include "mathops.h"
+#include "dsputil.h"
+#include "lagarithrac.h"
+
+enum LagarithFrameType {
+    FRAME_RAW           = 1,    /*!< uncompressed */
+    FRAME_U_RGB24       = 2,    /*!< unaligned RGB24 */
+    FRAME_ARITH_YUY2    = 3,    /*!< arithmetic coded YUY2 */
+    FRAME_ARITH_RGB24   = 4,    /*!< arithmetic coded RGB24 */
+    FRAME_SOLID_GRAY    = 5,    /*!< solid grayscale color frame */
+    FRAME_SOLID_COLOR   = 6,    /*!< solid non-grayscale color frame */
+    FRAME_OLD_ARITH_RGB = 7,    /*!< obsolete arithmetic coded RGB (no longer encoded by upstream since version 1.1.0) */
+    FRAME_ARITH_RGBA    = 8,    /*!< arithmetic coded RGBA */
+    FRAME_SOLID_RGBA    = 9,    /*!< solid RGBA color frame */
+    FRAME_ARITH_YV12    = 10,   /*!< arithmetic coded YV12 */
+    FRAME_REDUCED_RES   = 11,   /*!< reduced resolution YV12 frame */
+};
+
+typedef struct LagarithContext {
+    AVCodecContext *avctx;
+    AVFrame picture;
+    DSPContext dsp;
+    int zeros;                  /*!< number of consecutive zero bytes encountered */
+    int zeros_rem;              /*!< number of zero bytes remaining to output */
+} LagarithContext;
+
+/**
+ * Compute the 52bit mantissa of 1/(double)denom.
+ * This crazy format uses floats in an entropy coder and we have to match x86
+ * rounding exactly, thus ordinary floats aren't portable enough.
+ * @param denom denominator
+ * @return 52bit mantissa
+ * @see softfloat_mul
+ */
+static uint64_t softfloat_reciprocal(uint32_t denom)
+{
+    int shift = av_log2(denom - 1) + 1;
+    uint64_t ret = (1ULL << 52) / denom;
+    uint64_t err = (1ULL << 52) - ret * denom;
+    ret <<= shift;
+    err <<= shift;
+    err +=  denom / 2;
+    return ret + err / denom;
+}
+
+/**
+ * (uint32_t)(x*f), where f has the given mantissa, and exponent 0
+ * Used in combination with softfloat_reciprocal computes x/(double)denom.
+ * @param x 32bit integer factor
+ * @param mantissa mantissa of f with exponent 0
+ * @return 32bit integer value (x*f)
+ * @see softfloat_reciprocal
+ */
+static uint32_t softfloat_mul(uint32_t x, uint64_t mantissa)
+{
+    uint64_t l = x * (mantissa & 0xffffffff);
+    uint64_t h = x * (mantissa >> 32);
+    h += l >> 32;
+    l &= 0xffffffff;
+    l += 1 << av_log2(h >> 21);
+    h += l >> 32;
+    return h >> 20;
+}
+
+static uint8_t lag_calc_zero_run(int8_t x)
+{
+    return (x << 1) ^ (x >> 7);
+}
+
+static int lag_decode_prob(GetBitContext *gb, uint32_t *value)
+{
+    static const uint8_t series[] = { 1, 2, 3, 5, 8, 13, 21 };
+    int i;
+    int bit     = 0;
+    int bits    = 0;
+    int prevbit = 0;
+    unsigned val;
+
+    for (i = 0; i < 7; i++) {
+        if (prevbit && bit)
+            break;
+        prevbit = bit;
+        bit = get_bits1(gb);
+        if (bit && !prevbit)
+            bits += series[i];
+    }
+    bits--;
+    if (bits < 0 || bits > 31) {
+        *value = 0;
+        return -1;
+    } else if (bits == 0) {
+        *value = 0;
+        return 0;
+    }
+
+    val  = get_bits_long(gb, bits);
+    val |= 1 << bits;
+
+    *value = val - 1;
+
+    return 0;
+}
+
+static int lag_read_prob_header(lag_rac *rac, GetBitContext *gb)
+{
+    int i, j, scale_factor;
+    unsigned prob, cumulative_target;
+    unsigned cumul_prob = 0;
+    unsigned scaled_cumul_prob = 0;
+
+    rac->prob[0] = 0;
+    rac->prob[257] = UINT_MAX;
+    /* Read probabilities from bitstream */
+    for (i = 1; i < 257; i++) {
+        if (lag_decode_prob(gb, &rac->prob[i]) < 0) {
+            av_log(rac->avctx, AV_LOG_ERROR, "Invalid probability encountered.\n");
+            return -1;
+        }
+        if ((uint64_t)cumul_prob + rac->prob[i] > UINT_MAX) {
+            av_log(rac->avctx, AV_LOG_ERROR, "Integer overflow encountered in cumulative probability calculation.\n");
+            return -1;
+        }
+        cumul_prob += rac->prob[i];
+        if (!rac->prob[i]) {
+            if (lag_decode_prob(gb, &prob)) {
+                av_log(rac->avctx, AV_LOG_ERROR, "Invalid probability run encountered.\n");
+                return -1;
+            }
+            if (prob > 257 - i)
+                prob = 257 - i;
+            for (j = 0; j < prob; j++)
+                rac->prob[++i] = 0;
+        }
+    }
+
+    if (!cumul_prob) {
+        av_log(rac->avctx, AV_LOG_ERROR, "All probabilities are 0!\n");
+        return -1;
+    }
+
+    /* Scale probabilities so cumulative probability is an even power of 2. */
+    scale_factor = av_log2(cumul_prob);
+
+    if (cumul_prob & (cumul_prob - 1)) {
+        uint64_t mul = softfloat_reciprocal(cumul_prob);
+        for (i = 1; i < 257; i++) {
+            rac->prob[i] = softfloat_mul(rac->prob[i], mul);
+            scaled_cumul_prob += rac->prob[i];
+        }
+
+        scale_factor++;
+        cumulative_target = 1 << scale_factor;
+
+        if (scaled_cumul_prob > cumulative_target) {
+            av_log(rac->avctx, AV_LOG_ERROR,
+                   "Scaled probabilities are larger than target!\n");
+            return -1;
+        }
+
+        scaled_cumul_prob = cumulative_target - scaled_cumul_prob;
+
+        for (i = 1; scaled_cumul_prob; i = (i & 0x7f) + 1) {
+            if (rac->prob[i]) {
+                rac->prob[i]++;
+                scaled_cumul_prob--;
+            }
+            /* Comment from reference source:
+             * if (b & 0x80 == 0) {     // order of operations is 'wrong'; it has been left this way
+             *                          // since the compression change is negligable and fixing it
+             *                          // breaks backwards compatibilty
+             *      b =- (signed int)b;
+             *      b &= 0xFF;
+             * } else {
+             *      b++;
+             *      b &= 0x7f;
+             * }
+             */
+        }
+    }
+
+    rac->scale = scale_factor;
+
+    /* Fill probability array with cumulative probability for each symbol. */
+    for (i = 1; i < 257; i++)
+        rac->prob[i] += rac->prob[i - 1];
+
+    return 0;
+}
+
+static void add_lag_median_prediction(uint8_t *dst, uint8_t *src1,
+                                      uint8_t *diff, int w, int *left,
+                                      int *left_top)
+{
+    /* This is almost identical to add_hfyu_median_prediction in dsputil.h.
+     * However the &0xFF on the gradient predictor yealds incorrect output
+     * for lagarith.
+     */
+    int i;
+    uint8_t l, lt;
+
+    l  = *left;
+    lt = *left_top;
+
+    for (i = 0; i < w; i++) {
+        l = mid_pred(l, src1[i], l + src1[i] - lt) + diff[i];
+        lt = src1[i];
+        dst[i] = l;
+    }
+
+    *left     = l;
+    *left_top = lt;
+}
+
+static void lag_pred_line(LagarithContext *l, uint8_t *buf,
+                          int width, int stride, int line)
+{
+    int L, TL;
+
+    if (!line) {
+        /* Left prediction only for first line */
+        L = l->dsp.add_hfyu_left_prediction(buf + 1, buf + 1,
+                                            width - 1, buf[0]);
+        return;
+    } else if (line == 1) {
+        /* Second line, left predict first pixel, the rest of the line is median predicted */
+        /* FIXME: In the case of RGB this pixel is top predicted */
+        TL = buf[-stride];
+    } else {
+        /* Top left is 2 rows back, last pixel */
+        TL = buf[width - (2 * stride) - 1];
+    }
+    /* Left pixel is actually prev_row[width] */
+    L = buf[width - stride - 1];
+
+    add_lag_median_prediction(buf, buf - stride, buf,
+                              width, &L, &TL);
+}
+
+static int lag_decode_line(LagarithContext *l, lag_rac *rac,
+                           uint8_t *dst, int width, int stride,
+                           int esc_count)
+{
+    int i = 0;
+    int ret = 0;
+
+    if (!esc_count)
+        esc_count = -1;
+
+    /* Output any zeros remaining from the previous run */
+handle_zeros:
+    if (l->zeros_rem) {
+        int count = FFMIN(l->zeros_rem, width - i);
+        memset(dst + i, 0, count);
+        i += count;
+        l->zeros_rem -= count;
+    }
+
+    while (i < width) {
+        dst[i] = lag_get_rac(rac);
+        ret++;
+
+        if (dst[i])
+            l->zeros = 0;
+        else
+            l->zeros++;
+
+        i++;
+        if (l->zeros == esc_count) {
+            int index = lag_get_rac(rac);
+            ret++;
+
+            l->zeros = 0;
+
+            l->zeros_rem = lag_calc_zero_run(index);
+            goto handle_zeros;
+        }
+    }
+    return ret;
+}
+
+static int lag_decode_zero_run_line(LagarithContext *l, uint8_t *dst,
+                                    const uint8_t *src, int width,
+                                    int esc_count)
+{
+    int i = 0;
+    int count;
+    uint8_t zero_run = 0;
+    const uint8_t *start = src;
+    uint8_t mask1 = -(esc_count < 2);
+    uint8_t mask2 = -(esc_count < 3);
+    uint8_t *end = dst + (width - 2);
+
+output_zeros:
+    if (l->zeros_rem) {
+        count = FFMIN(l->zeros_rem, width - i);
+        memset(dst, 0, count);
+        l->zeros_rem -= count;
+        dst += count;
+    }
+
+    while (dst < end) {
+        i = 0;
+        while (!zero_run && dst + i < end) {
+            i++;
+            zero_run =
+                !(src[i] | (src[i + 1] & mask1) | (src[i + 2] & mask2));
+        }
+        if (zero_run) {
+            zero_run = 0;
+            i += esc_count;
+            memcpy(dst, src, i);
+            dst += i;
+            l->zeros_rem = lag_calc_zero_run(src[i]);
+
+            src += i + 1;
+            goto output_zeros;
+        } else {
+            memcpy(dst, src, i);
+            src += i;
+        }
+    }
+    return start - src;
+}
+
+
+
+static int lag_decode_arith_plane(LagarithContext *l, uint8_t *dst,
+                                  int width, int height, int stride,
+                                  const uint8_t *src, int src_size)
+{
+    int i = 0;
+    int read = 0;
+    uint32_t length;
+    uint32_t offset = 1;
+    int esc_count = src[0];
+    GetBitContext gb;
+    lag_rac rac;
+
+    rac.avctx = l->avctx;
+    l->zeros = 0;
+
+    if (esc_count < 4) {
+        length = width * height;
+        if (esc_count && AV_RL32(src + 1) < length) {
+            length = AV_RL32(src + 1);
+            offset += 4;
+        }
+
+        init_get_bits(&gb, src + offset, src_size * 8);
+
+        if (lag_read_prob_header(&rac, &gb) < 0)
+            return -1;
+
+        lag_rac_init(&rac, &gb, length - stride);
+
+        for (i = 0; i < height; i++)
+            read += lag_decode_line(l, &rac, dst + (i * stride), width,
+                                    stride, esc_count);
+
+        if (read > length)
+            av_log(l->avctx, AV_LOG_WARNING,
+                   "Output more bytes than length (%d of %d)\n", read,
+                   length);
+    } else if (esc_count < 8) {
+        esc_count -= 4;
+        if (esc_count > 0) {
+            /* Zero run coding only, no range coding. */
+            for (i = 0; i < height; i++)
+                src += lag_decode_zero_run_line(l, dst + (i * stride), src,
+                                                width, esc_count);
+        } else {
+            /* Plane is stored uncompressed */
+            for (i = 0; i < height; i++) {
+                memcpy(dst + (i * stride), src, width);
+                src += width;
+            }
+        }
+    } else if (esc_count == 0xff) {
+        /* Plane is a solid run of given value */
+        for (i = 0; i < height; i++)
+            memset(dst + i * stride, src[1], width);
+        /* Do not apply prediction.
+           Note: memset to 0 above, setting first value to src[1]
+           and applying prediction gives the same result. */
+        return 0;
+    } else {
+        av_log(l->avctx, AV_LOG_ERROR,
+               "Invalid zero run escape code! (%#x)\n", esc_count);
+        return -1;
+    }
+
+    for (i = 0; i < height; i++) {
+        lag_pred_line(l, dst, width, stride, i);
+        dst += stride;
+    }
+
+    return 0;
+}
+
+/**
+ * Decode a frame.
+ * @param avctx codec context
+ * @param data output AVFrame
+ * @param data_size size of output data or 0 if no picture is returned
+ * @param avpkt input packet
+ * @return number of consumed bytes on success or negative if decode fails
+ */
+static int lag_decode_frame(AVCodecContext *avctx,
+                            void *data, int *data_size, AVPacket *avpkt)
+{
+    const uint8_t *buf = avpkt->data;
+    int buf_size = avpkt->size;
+    LagarithContext *l = avctx->priv_data;
+    AVFrame *const p = &l->picture;
+    uint8_t frametype = 0;
+    uint32_t offset_gu = 0, offset_bv = 0, offset_ry = 9;
+
+    AVFrame *picture = data;
+
+    if (p->data[0])
+        avctx->release_buffer(avctx, p);
+
+    p->reference = 0;
+    p->key_frame = 1;
+
+    frametype = buf[0];
+
+    offset_gu = AV_RL32(buf + 1);
+    offset_bv = AV_RL32(buf + 5);
+
+    switch (frametype) {
+    case FRAME_ARITH_YV12:
+        avctx->pix_fmt = PIX_FMT_YUV420P;
+
+        if (avctx->get_buffer(avctx, p) < 0) {
+            av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
+            return -1;
+        }
+
+        lag_decode_arith_plane(l, p->data[0], avctx->width, avctx->height,
+                               p->linesize[0], buf + offset_ry,
+                               buf_size);
+        lag_decode_arith_plane(l, p->data[2], avctx->width / 2,
+                               avctx->height / 2, p->linesize[2],
+                               buf + offset_gu, buf_size);
+        lag_decode_arith_plane(l, p->data[1], avctx->width / 2,
+                               avctx->height / 2, p->linesize[1],
+                               buf + offset_bv, buf_size);
+        break;
+    default:
+        av_log(avctx, AV_LOG_ERROR,
+               "Unsupported Lagarith frame type: %#x\n", frametype);
+        return -1;
+    }
+
+    *picture = *p;
+    *data_size = sizeof(AVFrame);
+
+    return buf_size;
+}
+
+static av_cold int lag_decode_init(AVCodecContext *avctx)
+{
+    LagarithContext *l = avctx->priv_data;
+    l->avctx = avctx;
+
+    dsputil_init(&l->dsp, avctx);
+
+    return 0;
+}
+
+static av_cold int lag_decode_end(AVCodecContext *avctx)
+{
+    LagarithContext *l = avctx->priv_data;
+
+    if (l->picture.data[0])
+        avctx->release_buffer(avctx, &l->picture);
+
+    return 0;
+}
+
+AVCodec ff_lagarith_decoder = {
+    "lagarith",
+    AVMEDIA_TYPE_VIDEO,
+    CODEC_ID_LAGARITH,
+    sizeof(LagarithContext),
+    lag_decode_init,
+    NULL,
+    lag_decode_end,
+    lag_decode_frame,
+    CODEC_CAP_DR1,
+    .long_name = NULL_IF_CONFIG_SMALL("Lagarith lossless"),
+};
diff --git a/libavcodec/lagarithrac.c b/libavcodec/lagarithrac.c
new file mode 100644
index 0000000..f1ffbf0
--- /dev/null
+++ b/libavcodec/lagarithrac.c
@@ -0,0 +1,58 @@
+/*
+ * Lagarith range decoder
+ * Copyright (c) 2009 Nathan Caldwell <saintdev (at) gmail.com>
+ * Copyright (c) 2009 David Conrad
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file libavcodec/lagarithrac.c
+ * Lagarith range decoder
+ * @author Nathan Caldwell
+ * @author David Conrad
+ */
+
+#include "get_bits.h"
+#include "lagarithrac.h"
+
+void lag_rac_init(lag_rac *l, GetBitContext *gb, int length)
+{
+    int i, j;
+
+    /* According to reference decoder "1st byte is garbage",
+     * however, it gets skipped by the call to align_get_bits()
+     */
+    align_get_bits(gb);
+    l->bytestream_start =
+    l->bytestream       = gb->buffer + get_bits_count(gb) / 8;
+    l->bytestream_end   = l->bytestream_start + length;
+
+    l->range        = 0x80;
+    l->low          = *l->bytestream >> 1;
+    l->hash_shift   = FFMAX(l->scale - 8, 0);
+
+    for (i = j = 0; i < 256; i++) {
+        unsigned r = i << l->hash_shift;
+        while (l->prob[j + 1] <= r)
+            j++;
+        l->range_hash[i] = j;
+    }
+
+    /* Add conversion factor to hash_shift so we don't have to in lag_get_rac. */
+    l->hash_shift += 23;
+}
diff --git a/libavcodec/lagarithrac.h b/libavcodec/lagarithrac.h
new file mode 100644
index 0000000..7d0d05c
--- /dev/null
+++ b/libavcodec/lagarithrac.h
@@ -0,0 +1,116 @@
+/*
+ * Lagarith range decoder
+ * Copyright (c) 2009 Nathan Caldwell <saintdev (at) gmail.com>
+ * Copyright (c) 2009 David Conrad
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file libavcodec/lagarithrac.h
+ * Lagarith range decoder
+ * @author Nathan Caldwell
+ * @author David Conrad
+ */
+
+#ifndef AVCODEC_LAGARITHRAC_H
+#define AVCODEC_LAGARITHRAC_H
+
+#include <stdint.h>
+#include "libavutil/common.h"
+#include "libavutil/intreadwrite.h"
+#include "avcodec.h"
+#include "get_bits.h"
+
+typedef struct lag_rac {
+    AVCodecContext *avctx;
+    unsigned low;
+    unsigned range;
+    unsigned scale;             /*!< Number of bits of precision in range. */
+    unsigned hash_shift;        /*!< Number of bits to shift to calculate hash for radix search. */
+
+    const uint8_t *bytestream_start;  /*!< Start of input bytestream. */
+    const uint8_t *bytestream;        /*!< Current position in input bytestream. */
+    const uint8_t *bytestream_end;    /*!< End position of input bytestream. */
+
+    uint32_t prob[258];         /*!< Table of cumulative probability for each symbol. */
+    uint8_t  range_hash[256];   /*!< Hash table mapping upper byte to approximate symbol. */
+} lag_rac;
+
+void lag_rac_init(lag_rac *l, GetBitContext *gb, int length);
+
+/* TODO: Optimize */
+static inline void lag_rac_refill(lag_rac *l)
+{
+    while (l->range <= 0x800000) {
+        l->low   <<= 8;
+        l->range <<= 8;
+        l->low |= 0xff & (AV_RB16(l->bytestream) >> 1);
+        if (l->bytestream < l->bytestream_end)
+            l->bytestream++;
+    }
+}
+
+/**
+ * Decode a single byte from the compressed plane described by *l.
+ * @param l pointer to lag_rac for the current plane
+ * @return next byte of decoded data
+ */
+static inline uint8_t lag_get_rac(lag_rac *l)
+{
+    unsigned range_scaled, low_scaled, div;
+    int val;
+    uint8_t shift;
+
+    lag_rac_refill(l);
+
+    range_scaled = l->range >> l->scale;
+
+    if (l->low < range_scaled * l->prob[255]) {
+        /* val = 0 is frequent enough to deserve a shortcut */
+        if (l->low < range_scaled * l->prob[1]) {
+            val = 0;
+        } else {
+            /* FIXME __builtin_clz is ~20% faster here, but not allowed in generic code. */
+            shift = 30 - av_log2(range_scaled);
+            div = ((range_scaled << shift) + (1 << 23) - 1) >> 23;
+            /* low>>24 ensures that any cases too big for exact FASTDIV are
+             * under- rather than over-estimated
+             */
+            low_scaled = FASTDIV(l->low - (l->low >> 24), div);
+            shift -= l->hash_shift;
+            shift &= 31;
+            low_scaled = (low_scaled << shift) | (low_scaled >> (32 - shift));
+            /* low_scaled is now a lower bound of low/range_scaled */
+            val = l->range_hash[(uint8_t) low_scaled];
+            while (l->low >= range_scaled * l->prob[val + 1])
+                val++;
+        }
+
+        l->range = range_scaled * (l->prob[val + 1] - l->prob[val]);
+    } else {
+        val = 255;
+        l->range -= range_scaled * l->prob[255];
+    }
+
+    l->low -= range_scaled * l->prob[val];
+
+    return val;
+}
+
+
+#endif /* AVCODEC_LAGARITHRAC_H */
diff --git a/libavcodec/latm_parser.c b/libavcodec/latm_parser.c
new file mode 100644
index 0000000..fe39de8
--- /dev/null
+++ b/libavcodec/latm_parser.c
@@ -0,0 +1,114 @@
+/*
+ * copyright (c) 2008 Paul Kendall <paul at kcbbs.gen.nz>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * AAC LATM parser
+ */
+
+#include <stdint.h>
+#include "parser.h"
+
+#define LATM_HEADER     0x56e000        // 0x2b7 (11 bits)
+#define LATM_MASK       0xFFE000        // top 11 bits
+#define LATM_SIZE_MASK  0x001FFF        // bottom 13 bits
+
+typedef struct LATMParseContext{
+    ParseContext pc;
+    int count;
+} LATMParseContext;
+
+/**
+ * finds the end of the current frame in the bitstream.
+ * @return the position of the first byte of the next frame, or -1
+ */
+static int latm_find_frame_end(AVCodecParserContext *s1, const uint8_t *buf,
+                               int buf_size)
+{
+    LATMParseContext *s = s1->priv_data;
+    ParseContext *pc    = &s->pc;
+    int pic_found, i;
+    uint32_t state;
+
+    pic_found = pc->frame_start_found;
+    state     = pc->state;
+
+    i = 0;
+    if (!pic_found) {
+        for (i = 0; i < buf_size; i++) {
+            state = (state<<8) | buf[i];
+            if ((state & LATM_MASK) == LATM_HEADER) {
+                i++;
+                s->count  = -i;
+                pic_found = 1;
+                break;
+            }
+        }
+    }
+
+    if (pic_found) {
+        /* EOF considered as end of frame */
+        if (buf_size == 0)
+            return 0;
+        if ((state & LATM_SIZE_MASK) - s->count <= buf_size) {
+            pc->frame_start_found = 0;
+            pc->state             = -1;
+            return (state & LATM_SIZE_MASK) - s->count;
+        }
+    }
+
+    s->count             += buf_size;
+    pc->frame_start_found = pic_found;
+    pc->state             = state;
+
+    return END_NOT_FOUND;
+}
+
+static int latm_parse(AVCodecParserContext *s1, AVCodecContext *avctx,
+                      const uint8_t **poutbuf, int *poutbuf_size,
+                      const uint8_t *buf, int buf_size)
+{
+    LATMParseContext *s = s1->priv_data;
+    ParseContext *pc    = &s->pc;
+    int next;
+
+    if (s1->flags & PARSER_FLAG_COMPLETE_FRAMES) {
+        next = buf_size;
+    } else {
+        next = latm_find_frame_end(s1, buf, buf_size);
+
+        if (ff_combine_frame(pc, next, &buf, &buf_size) < 0) {
+            *poutbuf      = NULL;
+            *poutbuf_size = 0;
+            return buf_size;
+        }
+    }
+    *poutbuf      = buf;
+    *poutbuf_size = buf_size;
+    return next;
+}
+
+AVCodecParser ff_aac_latm_parser = {
+    { CODEC_ID_AAC_LATM },
+    sizeof(LATMParseContext),
+    NULL,
+    latm_parse,
+    ff_parse_close
+};
diff --git a/libavcodec/lcl.h b/libavcodec/lcl.h
index b60c0e9..4e7e170 100644
--- a/libavcodec/lcl.h
+++ b/libavcodec/lcl.h
@@ -2,20 +2,20 @@
  * LCL (LossLess Codec Library) Codec
  * Copyright (c) 2002-2004 Roberto Togni
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/lcldec.c b/libavcodec/lcldec.c
index 2bf448a..70414d4 100644
--- a/libavcodec/lcldec.c
+++ b/libavcodec/lcldec.c
@@ -2,20 +2,20 @@
  * LCL (LossLess Codec Library) Codec
  * Copyright (c) 2002-2004 Roberto Togni
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -117,6 +117,7 @@ static unsigned int mszh_decomp(const unsigned char * srcptr, int srclen, unsign
 }
 
 
+#if CONFIG_ZLIB_DECODER
 /**
  * \brief decompress a zlib-compressed data block into decomp_buf
  * \param src compressed input buffer
@@ -124,7 +125,6 @@ static unsigned int mszh_decomp(const unsigned char * srcptr, int srclen, unsign
  * \param offset offset in decomp_buf
  * \param expected expected decompressed length
  */
-#if CONFIG_ZLIB_DECODER
 static int zlib_decomp(AVCodecContext *avctx, const uint8_t *src, int src_len, int offset, int expected)
 {
     LclDecContext *c = avctx->priv_data;
@@ -609,7 +609,7 @@ static av_cold int decode_end(AVCodecContext *avctx)
 }
 
 #if CONFIG_MSZH_DECODER
-AVCodec mszh_decoder = {
+AVCodec ff_mszh_decoder = {
     "mszh",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_MSZH,
@@ -624,7 +624,7 @@ AVCodec mszh_decoder = {
 #endif
 
 #if CONFIG_ZLIB_DECODER
-AVCodec zlib_decoder = {
+AVCodec ff_zlib_decoder = {
     "zlib",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_ZLIB,
diff --git a/libavcodec/lclenc.c b/libavcodec/lclenc.c
index 8d7c5bf..63cb237 100644
--- a/libavcodec/lclenc.c
+++ b/libavcodec/lclenc.c
@@ -2,20 +2,20 @@
  * LCL (LossLess Codec Library) Codec
  * Copyright (c) 2002-2004 Roberto Togni
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -130,16 +130,8 @@ static av_cold int encode_init(AVCodecContext *avctx)
     // Will be user settable someday
     c->compression = 6;
     c->flags = 0;
-
-    switch(avctx->pix_fmt){
-        case PIX_FMT_BGR24:
-            c->imgtype = IMGTYPE_RGB24;
-            avctx->bits_per_coded_sample= 24;
-            break;
-        default:
-            av_log(avctx, AV_LOG_ERROR, "Input pixel format %s not supported\n", avcodec_get_pix_fmt_name(avctx->pix_fmt));
-            return -1;
-    }
+    c->imgtype = IMGTYPE_RGB24;
+    avctx->bits_per_coded_sample= 24;
 
     avctx->extradata[0]= 4;
     avctx->extradata[1]= 0;
@@ -178,7 +170,7 @@ static av_cold int encode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec zlib_encoder = {
+AVCodec ff_zlib_encoder = {
     "zlib",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_ZLIB,
@@ -186,5 +178,6 @@ AVCodec zlib_encoder = {
     encode_init,
     encode_frame,
     encode_end,
+    .pix_fmts = (const enum PixelFormat[]) { PIX_FMT_BGR24, PIX_FMT_NONE },
     .long_name = NULL_IF_CONFIG_SMALL("LCL (LossLess Codec Library) ZLIB"),
 };
diff --git a/libavcodec/libavcodec.v b/libavcodec/libavcodec.v
index 561a42c..6569903 100644
--- a/libavcodec/libavcodec.v
+++ b/libavcodec/libavcodec.v
@@ -1,3 +1,9 @@
 LIBAVCODEC_$MAJOR {
         global: *;
+        local:
+                ff_*_bsf;
+                ff_*_decoder;
+                ff_*_encoder;
+                ff_*_hwaccel;
+                ff_*_parser;
 };
diff --git a/libavcodec/libdirac.h b/libavcodec/libdirac.h
index 0dc19ca..7f79122 100644
--- a/libavcodec/libdirac.h
+++ b/libavcodec/libdirac.h
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2008 BBC, Anuradha Suraparaju <asuraparaju at gmail dot com >
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -30,7 +30,7 @@
 #include <libdirac_common/dirac_types.h>
 
 /**
-* Table providing a Dirac chroma format to FFmpeg pixel format mapping.
+* Table providing a Dirac chroma format to Libav pixel format mapping.
 */
 static const struct {
     enum PixelFormat ff_pix_fmt;
diff --git a/libavcodec/libdirac_libschro.c b/libavcodec/libdirac_libschro.c
index aee1858..525d866 100644
--- a/libavcodec/libdirac_libschro.c
+++ b/libavcodec/libdirac_libschro.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2008 BBC, Anuradha Suraparaju <asuraparaju at gmail dot com >
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/libdirac_libschro.h b/libavcodec/libdirac_libschro.h
index 3d63f97..9c2e9e7 100644
--- a/libavcodec/libdirac_libschro.h
+++ b/libavcodec/libdirac_libschro.h
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2008 BBC, Anuradha Suraparaju <asuraparaju at gmail dot com >
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/libdiracdec.c b/libavcodec/libdiracdec.c
index d24d3ba..08fec3d 100644
--- a/libavcodec/libdiracdec.c
+++ b/libavcodec/libdiracdec.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2005 BBC, Andrew Kennedy <dirac at rd dot bbc dot co dot uk>
  * Copyright (c) 2006-2008 BBC, Anuradha Suraparaju <asuraparaju at gmail dot com >
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -28,6 +28,7 @@
 * (http://dirac.sourceforge.net/specification.html).
 */
 
+#include "libavutil/imgutils.h"
 #include "libdirac.h"
 
 #undef NDEBUG
@@ -46,7 +47,7 @@ typedef struct FfmpegDiracDecoderParams {
 
 
 /**
-* returns FFmpeg chroma format
+* returns Libav chroma format
 */
 static enum PixelFormat GetFfmpegChromaFormat(dirac_chroma_t dirac_pix_fmt)
 {
@@ -102,11 +103,11 @@ static int libdirac_decode_frame(AVCodecContext *avccontext,
 
         case STATE_SEQUENCE:
         {
-            /* tell FFmpeg about sequence details */
+            /* tell Libav about sequence details */
             dirac_sourceparams_t *src_params = &p_dirac_params->p_decoder->src_params;
 
-            if (avcodec_check_dimensions(avccontext, src_params->width,
-                                         src_params->height) < 0) {
+            if (av_image_check_size(src_params->width, src_params->height,
+                                    0, avccontext) < 0) {
                 av_log(avccontext, AV_LOG_ERROR, "Invalid dimensions (%dx%d)\n",
                        src_params->width, src_params->height);
                 avccontext->height = avccontext->width = 0;
@@ -193,7 +194,7 @@ static void libdirac_flush(AVCodecContext *avccontext)
 
 
 
-AVCodec libdirac_decoder = {
+AVCodec ff_libdirac_decoder = {
     "libdirac",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_DIRAC,
diff --git a/libavcodec/libdiracenc.c b/libavcodec/libdiracenc.c
index d390aa8..ff4b92f 100644
--- a/libavcodec/libdiracenc.c
+++ b/libavcodec/libdiracenc.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2005 BBC, Andrew Kennedy <dirac at rd dot bbc dot co dot uk>
  * Copyright (c) 2006-2008 BBC, Anuradha Suraparaju <asuraparaju at gmail dot com >
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -391,7 +391,7 @@ static av_cold int libdirac_encode_close(AVCodecContext *avccontext)
 }
 
 
-AVCodec libdirac_encoder = {
+AVCodec ff_libdirac_encoder = {
     "libdirac",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_DIRAC,
diff --git a/libavcodec/libfaac.c b/libavcodec/libfaac.c
index 82fd05b..51d965e 100644
--- a/libavcodec/libfaac.c
+++ b/libavcodec/libfaac.c
@@ -2,20 +2,20 @@
  * Interface to libfaac for aac encoding
  * Copyright (c) 2002 Gildas Bazin <gbazin at netcourrier.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -124,10 +124,11 @@ static int Faac_encode_frame(AVCodecContext *avctx,
 {
     FaacAudioContext *s = avctx->priv_data;
     int bytes_written;
+    int num_samples = data ? avctx->frame_size : 0;
 
     bytes_written = faacEncEncode(s->faac_handle,
                                   data,
-                                  avctx->frame_size * avctx->channels,
+                                  num_samples * avctx->channels,
                                   frame,
                                   buf_size);
 
@@ -145,7 +146,15 @@ static av_cold int Faac_encode_close(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec libfaac_encoder = {
+static const AVProfile profiles[] = {
+    { FF_PROFILE_AAC_MAIN, "Main" },
+    { FF_PROFILE_AAC_LOW,  "LC"   },
+    { FF_PROFILE_AAC_SSR,  "SSR"  },
+    { FF_PROFILE_AAC_LTP,  "LTP"  },
+    { FF_PROFILE_UNKNOWN },
+};
+
+AVCodec ff_libfaac_encoder = {
     "libfaac",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_AAC,
@@ -153,6 +162,8 @@ AVCodec libfaac_encoder = {
     Faac_encode_init,
     Faac_encode_frame,
     Faac_encode_close,
-    .sample_fmts = (const enum SampleFormat[]){SAMPLE_FMT_S16,SAMPLE_FMT_NONE},
+    .capabilities = CODEC_CAP_SMALL_LAST_FRAME | CODEC_CAP_DELAY,
+    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
     .long_name = NULL_IF_CONFIG_SMALL("libfaac AAC (Advanced Audio Codec)"),
+    .profiles = NULL_IF_CONFIG_SMALL(profiles),
 };
diff --git a/libavcodec/libfaad.c b/libavcodec/libfaad.c
deleted file mode 100644
index 679729a..0000000
--- a/libavcodec/libfaad.c
+++ /dev/null
@@ -1,333 +0,0 @@
-/*
- * Faad decoder
- * Copyright (c) 2003 Zdenek Kabelac
- * Copyright (c) 2004 Thomas Raivio
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-/**
- * @file
- * AAC decoder.
- *
- * still a bit unfinished - but it plays something
- */
-
-#include "avcodec.h"
-#include "faad.h"
-
-#ifndef FAADAPI
-#define FAADAPI
-#endif
-
-/*
- * when CONFIG_LIBFAADBIN is true libfaad will be opened at runtime
- */
-//#undef CONFIG_LIBFAADBIN
-//#define CONFIG_LIBFAADBIN 0
-//#define CONFIG_LIBFAADBIN 1
-
-#if CONFIG_LIBFAADBIN
-#include <dlfcn.h>
-static const char* const libfaadname = "libfaad.so";
-#else
-#define dlopen(a)
-#define dlclose(a)
-#endif
-
-typedef struct {
-    void* handle;               /* dlopen handle */
-    void* faac_handle;          /* FAAD library handle */
-    int sample_size;
-    int init;
-
-    /* faad calls */
-    faacDecHandle FAADAPI (*faacDecOpen)(void);
-    faacDecConfigurationPtr FAADAPI (*faacDecGetCurrentConfiguration)(faacDecHandle hDecoder);
-#ifndef FAAD2_VERSION
-    int FAADAPI (*faacDecSetConfiguration)(faacDecHandle hDecoder,
-                                           faacDecConfigurationPtr config);
-    int FAADAPI (*faacDecInit)(faacDecHandle hDecoder,
-                               unsigned char *buffer,
-                               unsigned long *samplerate,
-                               unsigned long *channels);
-    int FAADAPI (*faacDecInit2)(faacDecHandle hDecoder, unsigned char *pBuffer,
-                                unsigned long SizeOfDecoderSpecificInfo,
-                                unsigned long *samplerate, unsigned long *channels);
-    int FAADAPI (*faacDecDecode)(faacDecHandle hDecoder,
-                                 unsigned char *buffer,
-                                 unsigned long *bytesconsumed,
-                                 short *sample_buffer,
-                                 unsigned long *samples);
-#else
-    unsigned char FAADAPI (*faacDecSetConfiguration)(faacDecHandle hDecoder,
-                                                     faacDecConfigurationPtr config);
-    long FAADAPI (*faacDecInit)(faacDecHandle hDecoder,
-                                unsigned char *buffer,
-                                unsigned long buffer_size,
-                                unsigned long *samplerate,
-                                unsigned char *channels);
-    char FAADAPI (*faacDecInit2)(faacDecHandle hDecoder, unsigned char *pBuffer,
-                                 unsigned long SizeOfDecoderSpecificInfo,
-                                 unsigned long *samplerate, unsigned char *channels);
-    void *FAADAPI (*faacDecDecode)(faacDecHandle hDecoder,
-                                   faacDecFrameInfo *hInfo,
-                                   unsigned char *buffer,
-                                   unsigned long buffer_size);
-    char* FAADAPI (*faacDecGetErrorMessage)(unsigned char errcode);
-#endif
-
-    void FAADAPI (*faacDecClose)(faacDecHandle hDecoder);
-
-
-} FAACContext;
-
-static const unsigned long faac_srates[] =
-{
-    96000, 88200, 64000, 48000, 44100, 32000,
-    24000, 22050, 16000, 12000, 11025, 8000
-};
-
-static void channel_setup(AVCodecContext *avctx)
-{
-#ifdef FAAD2_VERSION
-    FAACContext *s = avctx->priv_data;
-    if (avctx->request_channels > 0 && avctx->request_channels == 2 &&
-        avctx->request_channels < avctx->channels) {
-        faacDecConfigurationPtr faac_cfg;
-        avctx->channels = 2;
-        faac_cfg = s->faacDecGetCurrentConfiguration(s->faac_handle);
-        faac_cfg->downMatrix = 1;
-        s->faacDecSetConfiguration(s->faac_handle, faac_cfg);
-    }
-#endif
-}
-
-static av_cold int faac_init_mp4(AVCodecContext *avctx)
-{
-    FAACContext *s = avctx->priv_data;
-    unsigned long samplerate;
-#ifndef FAAD2_VERSION
-    unsigned long channels;
-#else
-    unsigned char channels;
-#endif
-    int r = 0;
-
-    if (avctx->extradata){
-        r = s->faacDecInit2(s->faac_handle, (uint8_t*) avctx->extradata,
-                            avctx->extradata_size,
-                            &samplerate, &channels);
-        if (r < 0){
-            av_log(avctx, AV_LOG_ERROR,
-                   "faacDecInit2 failed r:%d   sr:%ld  ch:%ld  s:%d\n",
-                   r, samplerate, (long)channels, avctx->extradata_size);
-        } else {
-            avctx->sample_rate = samplerate;
-            avctx->channels = channels;
-            channel_setup(avctx);
-            s->init = 1;
-        }
-    }
-
-    return r;
-}
-
-static int faac_decode_frame(AVCodecContext *avctx,
-                             void *data, int *data_size,
-                             AVPacket *avpkt)
-{
-    const uint8_t *buf = avpkt->data;
-    int buf_size = avpkt->size;
-    FAACContext *s = avctx->priv_data;
-#ifndef FAAD2_VERSION
-    unsigned long bytesconsumed;
-    short *sample_buffer = NULL;
-    unsigned long samples;
-    int out;
-#else
-    faacDecFrameInfo frame_info;
-    void *out;
-#endif
-    if(buf_size == 0)
-        return 0;
-#ifndef FAAD2_VERSION
-    out = s->faacDecDecode(s->faac_handle,
-                           (unsigned char*)buf,
-                           &bytesconsumed,
-                           data,
-                           &samples);
-    samples *= s->sample_size;
-    if (data_size)
-        *data_size = samples;
-    return (buf_size < (int)bytesconsumed)
-        ? buf_size : (int)bytesconsumed;
-#else
-
-    if(!s->init){
-        unsigned long srate;
-        unsigned char channels;
-        int r = s->faacDecInit(s->faac_handle, buf, buf_size, &srate, &channels);
-        if(r < 0){
-            av_log(avctx, AV_LOG_ERROR, "libfaad: codec init failed.\n");
-            return -1;
-        }
-        avctx->sample_rate = srate;
-        avctx->channels = channels;
-        channel_setup(avctx);
-        s->init = 1;
-    }
-
-    out = s->faacDecDecode(s->faac_handle, &frame_info, (unsigned char*)buf, (unsigned long)buf_size);
-
-    if (frame_info.error > 0) {
-        av_log(avctx, AV_LOG_ERROR, "libfaad: frame decoding failed: %s\n",
-               s->faacDecGetErrorMessage(frame_info.error));
-        return -1;
-    }
-    if (!avctx->frame_size)
-        avctx->frame_size = frame_info.samples/avctx->channels;
-    frame_info.samples *= s->sample_size;
-    memcpy(data, out, frame_info.samples); // CHECKME - can we cheat this one
-
-    if (data_size)
-        *data_size = frame_info.samples;
-
-    return (buf_size < (int)frame_info.bytesconsumed)
-        ? buf_size : (int)frame_info.bytesconsumed;
-#endif
-}
-
-static av_cold int faac_decode_end(AVCodecContext *avctx)
-{
-    FAACContext *s = avctx->priv_data;
-
-    s->faacDecClose(s->faac_handle);
-
-    dlclose(s->handle);
-    return 0;
-}
-
-static av_cold int faac_decode_init(AVCodecContext *avctx)
-{
-    FAACContext *s = avctx->priv_data;
-    faacDecConfigurationPtr faac_cfg;
-
-#if CONFIG_LIBFAADBIN
-    const char* err = 0;
-
-    s->handle = dlopen(libfaadname, RTLD_LAZY);
-    if (!s->handle)
-    {
-        av_log(avctx, AV_LOG_ERROR, "FAAD library: %s could not be opened! \n%s\n",
-               libfaadname, dlerror());
-        return -1;
-    }
-
-#define dfaac(a) do {                                                   \
-        const char* n = AV_STRINGIFY(faacDec ## a);                     \
-        if (!err && !(s->faacDec ## a = dlsym(s->handle, n))) {         \
-            err = n;                                                    \
-        }                                                               \
-    } while(0)
-#else  /* !CONFIG_LIBFAADBIN */
-#define dfaac(a)     s->faacDec ## a = faacDec ## a
-#endif /* CONFIG_LIBFAADBIN */
-
-    // resolve all needed function calls
-    dfaac(Open);
-    dfaac(Close);
-    dfaac(GetCurrentConfiguration);
-    dfaac(SetConfiguration);
-    dfaac(Init);
-    dfaac(Init2);
-    dfaac(Decode);
-#ifdef FAAD2_VERSION
-    dfaac(GetErrorMessage);
-#endif
-
-#undef dfaac
-
-#if CONFIG_LIBFAADBIN
-    if (err) {
-        dlclose(s->handle);
-        av_log(avctx, AV_LOG_ERROR, "FAAD library: cannot resolve %s in %s!\n",
-               err, libfaadname);
-        return -1;
-    }
-#endif
-
-    s->faac_handle = s->faacDecOpen();
-    if (!s->faac_handle) {
-        av_log(avctx, AV_LOG_ERROR, "FAAD library: cannot create handler!\n");
-        faac_decode_end(avctx);
-        return -1;
-    }
-
-
-    faac_cfg = s->faacDecGetCurrentConfiguration(s->faac_handle);
-
-    if (faac_cfg) {
-        switch (avctx->bits_per_coded_sample) {
-        case 8: av_log(avctx, AV_LOG_ERROR, "FAADlib unsupported bps %d\n", avctx->bits_per_coded_sample); break;
-        default:
-        case 16:
-#ifdef FAAD2_VERSION
-            faac_cfg->outputFormat = FAAD_FMT_16BIT;
-#endif
-            s->sample_size = 2;
-            break;
-        case 24:
-#ifdef FAAD2_VERSION
-            faac_cfg->outputFormat = FAAD_FMT_24BIT;
-#endif
-            s->sample_size = 3;
-            break;
-        case 32:
-#ifdef FAAD2_VERSION
-            faac_cfg->outputFormat = FAAD_FMT_32BIT;
-#endif
-            s->sample_size = 4;
-            break;
-        }
-
-        faac_cfg->defSampleRate = (!avctx->sample_rate) ? 44100 : avctx->sample_rate;
-        faac_cfg->defObjectType = LC;
-    }
-
-    s->faacDecSetConfiguration(s->faac_handle, faac_cfg);
-
-    faac_init_mp4(avctx);
-
-    if(!s->init && avctx->channels > 0)
-        channel_setup(avctx);
-
-    avctx->sample_fmt = SAMPLE_FMT_S16;
-    return 0;
-}
-
-AVCodec libfaad_decoder = {
-    "libfaad",
-    AVMEDIA_TYPE_AUDIO,
-    CODEC_ID_AAC,
-    sizeof(FAACContext),
-    faac_decode_init,
-    NULL,
-    faac_decode_end,
-    faac_decode_frame,
-    .long_name = NULL_IF_CONFIG_SMALL("libfaad AAC (Advanced Audio Codec)"),
-};
diff --git a/libavcodec/libgsm.c b/libavcodec/libgsm.c
index 1062099..34f2957 100644
--- a/libavcodec/libgsm.c
+++ b/libavcodec/libgsm.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2005 Alban Bedel <albeu at free.fr>
  * Copyright (c) 2006, 2007 Michel Bardiaux <mbardiaux at mediaxim.be>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -49,12 +49,12 @@ static av_cold int libgsm_init(AVCodecContext *avctx) {
         if(!avctx->sample_rate)
             avctx->sample_rate= 8000;
 
-        avctx->sample_fmt = SAMPLE_FMT_S16;
+        avctx->sample_fmt = AV_SAMPLE_FMT_S16;
     }else{
         if (avctx->sample_rate != 8000) {
             av_log(avctx, AV_LOG_ERROR, "Sample rate 8000Hz required for GSM, got %dHz\n",
                 avctx->sample_rate);
-            if(avctx->strict_std_compliance > FF_COMPLIANCE_INOFFICIAL)
+            if(avctx->strict_std_compliance > FF_COMPLIANCE_UNOFFICIAL)
                 return -1;
         }
         if (avctx->bit_rate != 13000 /* Official */ &&
@@ -62,7 +62,7 @@ static av_cold int libgsm_init(AVCodecContext *avctx) {
             avctx->bit_rate != 0 /* Unknown; a.o. mov does not set bitrate when decoding */ ) {
             av_log(avctx, AV_LOG_ERROR, "Bitrate 13000bps required for GSM, got %dbps\n",
                 avctx->bit_rate);
-            if(avctx->strict_std_compliance > FF_COMPLIANCE_INOFFICIAL)
+            if(avctx->strict_std_compliance > FF_COMPLIANCE_UNOFFICIAL)
                 return -1;
         }
     }
@@ -112,7 +112,7 @@ static int libgsm_encode_frame(AVCodecContext *avctx,
 }
 
 
-AVCodec libgsm_encoder = {
+AVCodec ff_libgsm_encoder = {
     "libgsm",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_GSM,
@@ -120,11 +120,11 @@ AVCodec libgsm_encoder = {
     libgsm_init,
     libgsm_encode_frame,
     libgsm_close,
-    .sample_fmts = (const enum SampleFormat[]){SAMPLE_FMT_S16,SAMPLE_FMT_NONE},
+    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
     .long_name = NULL_IF_CONFIG_SMALL("libgsm GSM"),
 };
 
-AVCodec libgsm_ms_encoder = {
+AVCodec ff_libgsm_ms_encoder = {
     "libgsm_ms",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_GSM_MS,
@@ -132,7 +132,7 @@ AVCodec libgsm_ms_encoder = {
     libgsm_init,
     libgsm_encode_frame,
     libgsm_close,
-    .sample_fmts = (const enum SampleFormat[]){SAMPLE_FMT_S16,SAMPLE_FMT_NONE},
+    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
     .long_name = NULL_IF_CONFIG_SMALL("libgsm GSM Microsoft variant"),
 };
 
@@ -156,7 +156,7 @@ static int libgsm_decode_frame(AVCodecContext *avctx,
     return avctx->block_align;
 }
 
-AVCodec libgsm_decoder = {
+AVCodec ff_libgsm_decoder = {
     "libgsm",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_GSM,
@@ -168,7 +168,7 @@ AVCodec libgsm_decoder = {
     .long_name = NULL_IF_CONFIG_SMALL("libgsm GSM"),
 };
 
-AVCodec libgsm_ms_decoder = {
+AVCodec ff_libgsm_ms_decoder = {
     "libgsm_ms",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_GSM_MS,
diff --git a/libavcodec/libmp3lame.c b/libavcodec/libmp3lame.c
index 1d74d6d..62b55c9 100644
--- a/libavcodec/libmp3lame.c
+++ b/libavcodec/libmp3lame.c
@@ -2,20 +2,20 @@
  * Interface to libmp3lame for mp3 encoding
  * Copyright (c) 2002 Lennert Buytenhek <buytenh at gnu.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -55,13 +55,12 @@ static av_cold int MP3lame_encode_init(AVCodecContext *avctx)
     } else {
         lame_set_quality(s->gfp, avctx->compression_level);
     }
-    /* lame 3.91 doesn't work in mono */
-    lame_set_mode(s->gfp, JOINT_STEREO);
+    lame_set_mode(s->gfp, s->stereo ? JOINT_STEREO : MONO);
     lame_set_brate(s->gfp, avctx->bit_rate/1000);
     if(avctx->flags & CODEC_FLAG_QSCALE) {
         lame_set_brate(s->gfp, 0);
         lame_set_VBR(s->gfp, vbr_default);
-        lame_set_VBR_q(s->gfp, avctx->global_quality / (float)FF_QP2LAMBDA);
+        lame_set_VBR_quality(s->gfp, avctx->global_quality/(float)FF_QP2LAMBDA);
     }
     lame_set_bWriteVbrTag(s->gfp,0);
     lame_set_disable_reservoir(s->gfp, avctx->flags2 & CODEC_FLAG2_BIT_RESERVOIR ? 0 : 1);
@@ -214,7 +213,7 @@ static av_cold int MP3lame_encode_close(AVCodecContext *avctx)
 }
 
 
-AVCodec libmp3lame_encoder = {
+AVCodec ff_libmp3lame_encoder = {
     "libmp3lame",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_MP3,
@@ -223,7 +222,7 @@ AVCodec libmp3lame_encoder = {
     MP3lame_encode_frame,
     MP3lame_encode_close,
     .capabilities= CODEC_CAP_DELAY,
-    .sample_fmts = (const enum SampleFormat[]){SAMPLE_FMT_S16,SAMPLE_FMT_NONE},
+    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
     .supported_samplerates= sSampleRates,
     .long_name= NULL_IF_CONFIG_SMALL("libmp3lame MP3 (MPEG audio layer 3)"),
 };
diff --git a/libavcodec/libopencore-amr.c b/libavcodec/libopencore-amr.c
index 2661645..cf8bdbb 100644
--- a/libavcodec/libopencore-amr.c
+++ b/libavcodec/libopencore-amr.c
@@ -2,24 +2,26 @@
  * AMR Audio decoder stub
  * Copyright (c) 2003 the ffmpeg project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "avcodec.h"
+#include "libavutil/avstring.h"
+#include "libavutil/opt.h"
 
 static void amr_decode_fix_avctx(AVCodecContext *avctx)
 {
@@ -32,7 +34,7 @@ static void amr_decode_fix_avctx(AVCodecContext *avctx)
         avctx->channels = 1;
 
     avctx->frame_size = 160 * is_amr_wb;
-    avctx->sample_fmt = SAMPLE_FMT_S16;
+    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
 }
 
 #if CONFIG_LIBOPENCORE_AMRNB
@@ -40,9 +42,6 @@ static void amr_decode_fix_avctx(AVCodecContext *avctx)
 #include <opencore-amrnb/interf_dec.h>
 #include <opencore-amrnb/interf_enc.h>
 
-static const char nb_bitrate_unsupported[] =
-    "bitrate not supported: use one of 4.75k, 5.15k, 5.9k, 6.7k, 7.4k, 7.95k, 10.2k or 12.2k\n";
-
 /* Common code for fixed and float version*/
 typedef struct AMR_bitrates {
     int       rate;
@@ -50,41 +49,61 @@ typedef struct AMR_bitrates {
 } AMR_bitrates;
 
 /* Match desired bitrate */
-static int getBitrateMode(int bitrate)
+static int get_bitrate_mode(int bitrate, void *log_ctx)
 {
     /* make the correspondance between bitrate and mode */
-    AMR_bitrates rates[] = { { 4750, MR475},
-                             { 5150, MR515},
-                             { 5900, MR59},
-                             { 6700, MR67},
-                             { 7400, MR74},
-                             { 7950, MR795},
-                             {10200, MR102},
-                             {12200, MR122}, };
-    int i;
-
-    for (i = 0; i < 8; i++)
+    static const AMR_bitrates rates[] = {
+        { 4750, MR475 }, { 5150, MR515 }, {  5900, MR59  }, {  6700, MR67  },
+        { 7400, MR74 },  { 7950, MR795 }, { 10200, MR102 }, { 12200, MR122 }
+    };
+    int i, best = -1, min_diff = 0;
+    char log_buf[200];
+
+    for (i = 0; i < 8; i++) {
         if (rates[i].rate == bitrate)
             return rates[i].mode;
-    /* no bitrate matching, return an error */
-    return -1;
+        if (best < 0 || abs(rates[i].rate - bitrate) < min_diff) {
+            best     = i;
+            min_diff = abs(rates[i].rate - bitrate);
+        }
+    }
+    /* no bitrate matching exactly, log a warning */
+    snprintf(log_buf, sizeof(log_buf), "bitrate not supported: use one of ");
+    for (i = 0; i < 8; i++)
+        av_strlcatf(log_buf, sizeof(log_buf), "%.2fk, ", rates[i].rate    / 1000.f);
+    av_strlcatf(log_buf, sizeof(log_buf), "using %.2fk", rates[best].rate / 1000.f);
+    av_log(log_ctx, AV_LOG_WARNING, "%s\n", log_buf);
+
+    return best;
 }
 
 typedef struct AMRContext {
-    int   frameCount;
-    void *decState;
-    int  *enstate;
+    AVClass *av_class;
+    int   frame_count;
+    void *dec_state;
+    void *enc_state;
     int   enc_bitrate;
+    int   enc_mode;
+    int   enc_dtx;
 } AMRContext;
 
+static const AVOption options[] = {
+    { "dtx", "Allow DTX (generate comfort noise)", offsetof(AMRContext, enc_dtx), FF_OPT_TYPE_INT, 0, 0, 1, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM },
+    { NULL }
+};
+
+static const AVClass class = {
+    "libopencore_amrnb", av_default_item_name, options, LIBAVUTIL_VERSION_INT
+};
+
 static av_cold int amr_nb_decode_init(AVCodecContext *avctx)
 {
-    AMRContext *s = avctx->priv_data;
+    AMRContext *s  = avctx->priv_data;
 
-    s->frameCount = 0;
-    s->decState   = Decoder_Interface_init();
-    if (!s->decState) {
-        av_log(avctx, AV_LOG_ERROR, "Decoder_Interface_init error\r\n");
+    s->frame_count = 0;
+    s->dec_state   = Decoder_Interface_init();
+    if (!s->dec_state) {
+        av_log(avctx, AV_LOG_ERROR, "Decoder_Interface_init error\n");
         return -1;
     }
 
@@ -92,7 +111,7 @@ static av_cold int amr_nb_decode_init(AVCodecContext *avctx)
 
     if (avctx->channels > 1) {
         av_log(avctx, AV_LOG_ERROR, "amr_nb: multichannel decoding not supported\n");
-        return -1;
+        return AVERROR(ENOSYS);
     }
 
     return 0;
@@ -102,7 +121,7 @@ static av_cold int amr_nb_decode_close(AVCodecContext *avctx)
 {
     AMRContext *s = avctx->priv_data;
 
-    Decoder_Interface_exit(s->decState);
+    Decoder_Interface_exit(s->dec_state);
     return 0;
 }
 
@@ -111,35 +130,34 @@ static int amr_nb_decode_frame(AVCodecContext *avctx, void *data,
 {
     const uint8_t *buf = avpkt->data;
     int buf_size       = avpkt->size;
-    AMRContext *s = avctx->priv_data;
-    const uint8_t *amrData = buf;
+    AMRContext *s      = avctx->priv_data;
     static const uint8_t block_size[16] = { 12, 13, 15, 17, 19, 20, 26, 31, 5, 0, 0, 0, 0, 0, 0, 0 };
     enum Mode dec_mode;
     int packet_size;
 
-    /* av_log(NULL, AV_LOG_DEBUG, "amr_decode_frame buf=%p buf_size=%d frameCount=%d!!\n",
-              buf, buf_size, s->frameCount); */
+    av_dlog(avctx, "amr_decode_frame buf=%p buf_size=%d frame_count=%d!!\n",
+            buf, buf_size, s->frame_count);
 
-    dec_mode = (buf[0] >> 3) & 0x000F;
+    dec_mode    = (buf[0] >> 3) & 0x000F;
     packet_size = block_size[dec_mode] + 1;
 
     if (packet_size > buf_size) {
         av_log(avctx, AV_LOG_ERROR, "amr frame too short (%u, should be %u)\n",
                buf_size, packet_size);
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
 
-    s->frameCount++;
-    /* av_log(NULL, AV_LOG_DEBUG, "packet_size=%d amrData= 0x%X %X %X %X\n",
-              packet_size, amrData[0], amrData[1], amrData[2], amrData[3]); */
+    s->frame_count++;
+    av_dlog(avctx, "packet_size=%d buf= 0x%X %X %X %X\n",
+              packet_size, buf[0], buf[1], buf[2], buf[3]);
     /* call decoder */
-    Decoder_Interface_Decode(s->decState, amrData, data, 0);
+    Decoder_Interface_Decode(s->dec_state, buf, data, 0);
     *data_size = 160 * 2;
 
     return packet_size;
 }
 
-AVCodec libopencore_amrnb_decoder = {
+AVCodec ff_libopencore_amrnb_decoder = {
     "libopencore_amrnb",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_AMR_NB,
@@ -155,31 +173,29 @@ static av_cold int amr_nb_encode_init(AVCodecContext *avctx)
 {
     AMRContext *s = avctx->priv_data;
 
-    s->frameCount = 0;
+    s->frame_count = 0;
 
     if (avctx->sample_rate != 8000) {
         av_log(avctx, AV_LOG_ERROR, "Only 8000Hz sample rate supported\n");
-        return -1;
+        return AVERROR(ENOSYS);
     }
 
     if (avctx->channels != 1) {
         av_log(avctx, AV_LOG_ERROR, "Only mono supported\n");
-        return -1;
+        return AVERROR(ENOSYS);
     }
 
     avctx->frame_size  = 160;
     avctx->coded_frame = avcodec_alloc_frame();
 
-    s->enstate=Encoder_Interface_init(0);
-    if (!s->enstate) {
+    s->enc_state = Encoder_Interface_init(s->enc_dtx);
+    if (!s->enc_state) {
         av_log(avctx, AV_LOG_ERROR, "Encoder_Interface_init error\n");
         return -1;
     }
 
-    if ((s->enc_bitrate = getBitrateMode(avctx->bit_rate)) < 0) {
-        av_log(avctx, AV_LOG_ERROR, nb_bitrate_unsupported);
-        return -1;
-    }
+    s->enc_mode    = get_bitrate_mode(avctx->bit_rate, avctx);
+    s->enc_bitrate = avctx->bit_rate;
 
     return 0;
 }
@@ -188,7 +204,7 @@ static av_cold int amr_nb_encode_close(AVCodecContext *avctx)
 {
     AMRContext *s = avctx->priv_data;
 
-    Encoder_Interface_exit(s->enstate);
+    Encoder_Interface_exit(s->enc_state);
     av_freep(&avctx->coded_frame);
     return 0;
 }
@@ -200,20 +216,20 @@ static int amr_nb_encode_frame(AVCodecContext *avctx,
     AMRContext *s = avctx->priv_data;
     int written;
 
-    if ((s->enc_bitrate = getBitrateMode(avctx->bit_rate)) < 0) {
-        av_log(avctx, AV_LOG_ERROR, nb_bitrate_unsupported);
-        return -1;
+    if (s->enc_bitrate != avctx->bit_rate) {
+        s->enc_mode    = get_bitrate_mode(avctx->bit_rate, avctx);
+        s->enc_bitrate = avctx->bit_rate;
     }
 
-    written = Encoder_Interface_Encode(s->enstate, s->enc_bitrate, data,
+    written = Encoder_Interface_Encode(s->enc_state, s->enc_mode, data,
                                        frame, 0);
-    /* av_log(NULL, AV_LOG_DEBUG, "amr_nb_encode_frame encoded %u bytes, bitrate %u, first byte was %#02x\n",
-              written, s->enc_bitrate, frame[0] ); */
+    av_dlog(avctx, "amr_nb_encode_frame encoded %u bytes, bitrate %u, first byte was %#02x\n",
+            written, s->enc_mode, frame[0]);
 
     return written;
 }
 
-AVCodec libopencore_amrnb_encoder = {
+AVCodec ff_libopencore_amrnb_encoder = {
     "libopencore_amrnb",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_AMR_NB,
@@ -222,8 +238,9 @@ AVCodec libopencore_amrnb_encoder = {
     amr_nb_encode_frame,
     amr_nb_encode_close,
     NULL,
-    .sample_fmts = (const enum SampleFormat[]){SAMPLE_FMT_S16,SAMPLE_FMT_NONE},
+    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
     .long_name = NULL_IF_CONFIG_SMALL("OpenCORE Adaptive Multi-Rate (AMR) Narrow-Band"),
+    .priv_class = &class,
 };
 
 #endif
@@ -231,42 +248,24 @@ AVCodec libopencore_amrnb_encoder = {
 /* -----------AMR wideband ------------*/
 #if CONFIG_LIBOPENCORE_AMRWB
 
-#ifdef _TYPEDEF_H
-//To avoid duplicate typedefs from typedef in amr-nb
-#define typedef_h
-#endif
-
 #include <opencore-amrwb/dec_if.h>
 #include <opencore-amrwb/if_rom.h>
 
-static const char wb_bitrate_unsupported[] =
-    "bitrate not supported: use one of 6.6k, 8.85k, 12.65k, 14.25k, 15.85k, 18.25k, 19.85k, 23.05k, or 23.85k\n";
-
-/* Common code for fixed and float version*/
-typedef struct AMRWB_bitrates {
-    int rate;
-    int mode;
-} AMRWB_bitrates;
-
 typedef struct AMRWBContext {
-    int    frameCount;
     void  *state;
-    int    mode;
-    Word16 allow_dtx;
 } AMRWBContext;
 
 static av_cold int amr_wb_decode_init(AVCodecContext *avctx)
 {
     AMRWBContext *s = avctx->priv_data;
 
-    s->frameCount = 0;
-    s->state      = D_IF_init();
+    s->state        = D_IF_init();
 
     amr_decode_fix_avctx(avctx);
 
     if (avctx->channels > 1) {
         av_log(avctx, AV_LOG_ERROR, "amr_wb: multichannel decoding not supported\n");
-        return -1;
+        return AVERROR(ENOSYS);
     }
 
     return 0;
@@ -277,8 +276,7 @@ static int amr_wb_decode_frame(AVCodecContext *avctx, void *data,
 {
     const uint8_t *buf = avpkt->data;
     int buf_size       = avpkt->size;
-    AMRWBContext *s = avctx->priv_data;
-    const uint8_t *amrData = buf;
+    AMRWBContext *s    = avctx->priv_data;
     int mode;
     int packet_size;
     static const uint8_t block_size[16] = {18, 24, 33, 37, 41, 47, 51, 59, 61, 6, 6, 0, 0, 0, 1, 1};
@@ -287,17 +285,16 @@ static int amr_wb_decode_frame(AVCodecContext *avctx, void *data,
         /* nothing to do */
         return 0;
 
-    mode = (amrData[0] >> 3) & 0x000F;
+    mode        = (buf[0] >> 3) & 0x000F;
     packet_size = block_size[mode];
 
     if (packet_size > buf_size) {
         av_log(avctx, AV_LOG_ERROR, "amr frame too short (%u, should be %u)\n",
                buf_size, packet_size + 1);
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
 
-    s->frameCount++;
-    D_IF_decode(s->state, amrData, data, _good_frame);
+    D_IF_decode(s->state, buf, data, _good_frame);
     *data_size = 320 * 2;
     return packet_size;
 }
@@ -310,7 +307,7 @@ static int amr_wb_decode_close(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec libopencore_amrwb_decoder = {
+AVCodec ff_libopencore_amrwb_decoder = {
     "libopencore_amrwb",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_AMR_WB,
diff --git a/libavcodec/libopenjpeg.c b/libavcodec/libopenjpeg.c
index 0956da9..342dcd9 100644
--- a/libavcodec/libopenjpeg.c
+++ b/libavcodec/libopenjpeg.c
@@ -2,20 +2,20 @@
  * JPEG 2000 decoding support via OpenJPEG
  * Copyright (c) 2009 Jaikrishnan Menon <realityman at gmx.net>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -24,6 +24,7 @@
 * JPEG 2000 decoder using libopenjpeg
 */
 
+#include "libavutil/imgutils.h"
 #include "avcodec.h"
 #include "libavutil/intreadwrite.h"
 #define  OPJ_STATIC
@@ -113,7 +114,7 @@ static int libopenjpeg_decode_frame(AVCodecContext *avctx,
     }
     width  = image->comps[0].w << avctx->lowres;
     height = image->comps[0].h << avctx->lowres;
-    if(avcodec_check_dimensions(avctx, width, height) < 0) {
+    if(av_image_check_size(width, height, 0, avctx) < 0) {
         av_log(avctx, AV_LOG_ERROR, "%dx%d dimension invalid.\n", width, height);
         goto done;
     }
@@ -183,7 +184,7 @@ static av_cold int libopenjpeg_decode_close(AVCodecContext *avctx)
 }
 
 
-AVCodec libopenjpeg_decoder = {
+AVCodec ff_libopenjpeg_decoder = {
     "libopenjpeg",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_JPEG2000,
@@ -193,5 +194,6 @@ AVCodec libopenjpeg_decoder = {
     libopenjpeg_decode_close,
     libopenjpeg_decode_frame,
     CODEC_CAP_DR1,
+    .max_lowres = 5,
     .long_name = NULL_IF_CONFIG_SMALL("OpenJPEG based JPEG 2000 decoder"),
 } ;
diff --git a/libavcodec/libschroedinger.c b/libavcodec/libschroedinger.c
index 04c15a2..804d652 100644
--- a/libavcodec/libschroedinger.c
+++ b/libavcodec/libschroedinger.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2008 BBC, Anuradha Suraparaju <asuraparaju at gmail dot com >
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/libschroedinger.h b/libavcodec/libschroedinger.h
index 65a41e6..c9e2a5e 100644
--- a/libavcodec/libschroedinger.h
+++ b/libavcodec/libschroedinger.h
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2008 BBC, Anuradha Suraparaju <asuraparaju at gmail dot com >
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/libschroedingerdec.c b/libavcodec/libschroedingerdec.c
index ef20f20..ee29704 100644
--- a/libavcodec/libschroedingerdec.c
+++ b/libavcodec/libschroedingerdec.c
@@ -2,20 +2,20 @@
  * Dirac decoder support via Schroedinger libraries
  * Copyright (c) 2008 BBC, Anuradha Suraparaju <asuraparaju at gmail dot com >
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -27,6 +27,7 @@
 * (http://dirac.sourceforge.net/specification.html).
 */
 
+#include "libavutil/imgutils.h"
 #include "avcodec.h"
 #include "libdirac_libschro.h"
 #include "libschroedinger.h"
@@ -117,7 +118,7 @@ static SchroBuffer* FfmpegFindNextSchroParseUnit(FfmpegSchroParseUnitContext *pa
 }
 
 /**
-* Returns FFmpeg chroma format.
+* Returns Libav chroma format.
 */
 static enum PixelFormat GetFfmpegChromaFormat(SchroChromaFormat schro_pix_fmt)
 {
@@ -168,9 +169,9 @@ static void libschroedinger_handle_first_access_unit(AVCodecContext *avccontext)
 
     p_schro_params->format = schro_decoder_get_video_format(decoder);
 
-    /* Tell FFmpeg about sequence details. */
-    if (avcodec_check_dimensions(avccontext, p_schro_params->format->width,
-                                 p_schro_params->format->height) < 0) {
+    /* Tell Libav about sequence details. */
+    if (av_image_check_size(p_schro_params->format->width, p_schro_params->format->height,
+                            0, avccontext) < 0) {
         av_log(avccontext, AV_LOG_ERROR, "invalid dimensions (%dx%d)\n",
                p_schro_params->format->width, p_schro_params->format->height);
         avccontext->height = avccontext->width = 0;
@@ -345,7 +346,7 @@ static void libschroedinger_flush(AVCodecContext *avccontext)
     p_schro_params->eos_signalled = 0;
 }
 
-AVCodec libschroedinger_decoder = {
+AVCodec ff_libschroedinger_decoder = {
     "libschroedinger",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_DIRAC,
diff --git a/libavcodec/libschroedingerenc.c b/libavcodec/libschroedingerenc.c
index c375c73..d7190d0 100644
--- a/libavcodec/libschroedingerenc.c
+++ b/libavcodec/libschroedingerenc.c
@@ -2,20 +2,20 @@
  * Dirac encoder support via Schroedinger libraries
  * Copyright (c) 2008 BBC, Anuradha Suraparaju <asuraparaju at gmail dot com >
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -37,6 +37,7 @@
 #include "avcodec.h"
 #include "libdirac_libschro.h"
 #include "libschroedinger.h"
+#include "bytestream.h"
 
 
 /** libschroedinger encoder private data */
@@ -127,6 +128,24 @@ static int libschroedinger_encode_init(AVCodecContext *avccontext)
     if (SetSchroChromaFormat(avccontext) == -1)
         return -1;
 
+    if (avccontext->color_primaries == AVCOL_PRI_BT709) {
+        p_schro_params->format->colour_primaries = SCHRO_COLOUR_PRIMARY_HDTV;
+    } else if (avccontext->color_primaries == AVCOL_PRI_BT470BG) {
+        p_schro_params->format->colour_primaries = SCHRO_COLOUR_PRIMARY_SDTV_625;
+    } else if (avccontext->color_primaries == AVCOL_PRI_SMPTE170M) {
+        p_schro_params->format->colour_primaries = SCHRO_COLOUR_PRIMARY_SDTV_525;
+    }
+
+    if (avccontext->colorspace == AVCOL_SPC_BT709) {
+        p_schro_params->format->colour_matrix = SCHRO_COLOUR_MATRIX_HDTV;
+    } else if (avccontext->colorspace == AVCOL_SPC_BT470BG) {
+        p_schro_params->format->colour_matrix = SCHRO_COLOUR_MATRIX_SDTV;
+    }
+
+    if (avccontext->color_trc == AVCOL_TRC_BT709) {
+        p_schro_params->format->transfer_function = SCHRO_TRANSFER_CHAR_TV_GAMMA;
+    }
+
     if (ff_get_schro_frame_format(p_schro_params->format->chroma_format,
                                   &p_schro_params->frame_format) == -1) {
         av_log(avccontext, AV_LOG_ERROR,
@@ -154,8 +173,7 @@ static int libschroedinger_encode_init(AVCodecContext *avccontext)
                                              "enable_noarith", 1);
     } else {
         schro_encoder_setting_set_double(p_schro_params->encoder,
-                                         "gop_structure",
-                                         SCHRO_ENCODER_GOP_BIREF);
+                                         "au_distance", avccontext->gop_size);
         avccontext->has_b_frames = 1;
     }
 
@@ -167,17 +185,16 @@ static int libschroedinger_encode_init(AVCodecContext *avccontext)
                                              "rate_control",
                                              SCHRO_ENCODER_RATE_CONTROL_LOSSLESS);
         } else {
-            int noise_threshold;
+            int quality;
             schro_encoder_setting_set_double(p_schro_params->encoder,
                                              "rate_control",
-                                             SCHRO_ENCODER_RATE_CONTROL_CONSTANT_NOISE_THRESHOLD);
+                                             SCHRO_ENCODER_RATE_CONTROL_CONSTANT_QUALITY);
 
-            noise_threshold = avccontext->global_quality / FF_QP2LAMBDA;
-            if (noise_threshold > 100)
-                noise_threshold = 100;
+            quality = avccontext->global_quality / FF_QP2LAMBDA;
+            if (quality > 10)
+                quality = 10;
             schro_encoder_setting_set_double(p_schro_params->encoder,
-                                             "noise_threshold",
-                                             noise_threshold);
+                                             "quality", quality);
         }
     } else {
         schro_encoder_setting_set_double(p_schro_params->encoder,
@@ -196,6 +213,9 @@ static int libschroedinger_encode_init(AVCodecContext *avccontext)
         schro_encoder_setting_set_double(p_schro_params->encoder,
                                          "interlaced_coding", 1);
 
+    schro_encoder_setting_set_double(p_schro_params->encoder, "open_gop",
+                                     !(avccontext->flags & CODEC_FLAG_CLOSED_GOP));
+
     /* FIXME: Signal range hardcoded to 8-bit data until both libschroedinger
      * and libdirac support other bit-depth data. */
     schro_video_format_set_std_signal_range(p_schro_params->format,
@@ -318,10 +338,7 @@ static int libschroedinger_encode_frame(AVCodecContext *avccontext,
 
             /* Parse the coded frame number from the bitstream. Bytes 14
              * through 17 represesent the frame number. */
-                p_frame_output->frame_num = (enc_buf->data[13] << 24) +
-                                            (enc_buf->data[14] << 16) +
-                                            (enc_buf->data[15] <<  8) +
-                                             enc_buf->data[16];
+            p_frame_output->frame_num = AV_RB32(enc_buf->data + 13);
 
             ff_dirac_schro_queue_push_back(&p_schro_params->enc_frame_queue,
                                            p_frame_output);
@@ -405,7 +422,7 @@ static int libschroedinger_encode_close(AVCodecContext *avccontext)
 }
 
 
-AVCodec libschroedinger_encoder = {
+AVCodec ff_libschroedinger_encoder = {
     "libschroedinger",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_DIRAC,
diff --git a/libavcodec/libspeexdec.c b/libavcodec/libspeexdec.c
index c5cfbd5..e6626dc 100644
--- a/libavcodec/libspeexdec.c
+++ b/libavcodec/libspeexdec.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (C) 2008 David Conrad
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -49,7 +49,7 @@ static av_cold int libspeex_decode_init(AVCodecContext *avctx)
     if (avctx->extradata_size >= 80)
         s->header = speex_packet_to_header(avctx->extradata, avctx->extradata_size);
 
-    avctx->sample_fmt = SAMPLE_FMT_S16;
+    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
     if (s->header) {
         avctx->sample_rate = s->header->rate;
         avctx->channels    = s->header->nb_channels;
@@ -138,7 +138,7 @@ static av_cold int libspeex_decode_close(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec libspeex_decoder = {
+AVCodec ff_libspeex_decoder = {
     "libspeex",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_SPEEX,
diff --git a/libavcodec/libtheoraenc.c b/libavcodec/libtheoraenc.c
index 2dc45a9..86cc09f 100644
--- a/libavcodec/libtheoraenc.c
+++ b/libavcodec/libtheoraenc.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2006 Paul Richards <paul.richards at gmail.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -30,7 +30,7 @@
  * and o_ prefixes on variables which are libogg types.
  */
 
-/* FFmpeg includes */
+/* Libav includes */
 #include "libavutil/intreadwrite.h"
 #include "libavutil/log.h"
 #include "libavutil/base64.h"
@@ -49,7 +49,7 @@ typedef struct TheoraContext {
     int         keyframe_mask;
 } TheoraContext;
 
-/** Concatenates an ogg_packet into the extradata. */
+/** Concatenate an ogg_packet into the extradata. */
 static int concatenate_packet(unsigned int* offset,
                               AVCodecContext* avc_context,
                               const ogg_packet* packet)
@@ -101,7 +101,7 @@ static int get_stats(AVCodecContext *avctx, int eos)
         memcpy(h->stats + h->stats_offset, buf, bytes);
         h->stats_offset += bytes;
     } else {
-        int b64_size = ((h->stats_offset + 2) / 3) * 4 + 1;
+        int b64_size = AV_BASE64_SIZE(h->stats_offset);
         // libtheora generates a summary header at the end
         memcpy(h->stats, buf, bytes);
         avctx->stats_out = av_malloc(b64_size);
@@ -357,7 +357,7 @@ static av_cold int encode_close(AVCodecContext* avc_context)
 }
 
 /** AVCodec struct exposed to libavcodec */
-AVCodec libtheora_encoder = {
+AVCodec ff_libtheora_encoder = {
     .name = "libtheora",
     .type = AVMEDIA_TYPE_VIDEO,
     .id = CODEC_ID_THEORA,
diff --git a/libavcodec/libvo-aacenc.c b/libavcodec/libvo-aacenc.c
new file mode 100644
index 0000000..5a75bcb
--- /dev/null
+++ b/libavcodec/libvo-aacenc.c
@@ -0,0 +1,130 @@
+/*
+ * AAC encoder wrapper
+ * Copyright (c) 2010 Martin Storsjo
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <vo-aacenc/voAAC.h>
+#include <vo-aacenc/cmnMemory.h>
+
+#include "avcodec.h"
+#include "mpeg4audio.h"
+
+typedef struct AACContext {
+    VO_AUDIO_CODECAPI codec_api;
+    VO_HANDLE handle;
+    VO_MEM_OPERATOR mem_operator;
+    VO_CODEC_INIT_USERDATA user_data;
+} AACContext;
+
+static av_cold int aac_encode_init(AVCodecContext *avctx)
+{
+    AACContext *s = avctx->priv_data;
+    AACENC_PARAM params = { 0 };
+    int index;
+
+    avctx->coded_frame = avcodec_alloc_frame();
+    avctx->frame_size = 1024;
+
+    voGetAACEncAPI(&s->codec_api);
+
+    s->mem_operator.Alloc = cmnMemAlloc;
+    s->mem_operator.Copy = cmnMemCopy;
+    s->mem_operator.Free = cmnMemFree;
+    s->mem_operator.Set = cmnMemSet;
+    s->mem_operator.Check = cmnMemCheck;
+    s->user_data.memflag = VO_IMF_USERMEMOPERATOR;
+    s->user_data.memData = &s->mem_operator;
+    s->codec_api.Init(&s->handle, VO_AUDIO_CodingAAC, &s->user_data);
+
+    params.sampleRate = avctx->sample_rate;
+    params.bitRate    = avctx->bit_rate;
+    params.nChannels  = avctx->channels;
+    params.adtsUsed   = !(avctx->flags & CODEC_FLAG_GLOBAL_HEADER);
+    if (s->codec_api.SetParam(s->handle, VO_PID_AAC_ENCPARAM, &params)
+        != VO_ERR_NONE) {
+        av_log(avctx, AV_LOG_ERROR, "Unable to set encoding parameters\n");
+        return AVERROR(EINVAL);
+    }
+
+    for (index = 0; index < 16; index++)
+        if (avctx->sample_rate == ff_mpeg4audio_sample_rates[index])
+            break;
+    if (index == 16) {
+        av_log(avctx, AV_LOG_ERROR, "Unsupported sample rate %d\n",
+                                    avctx->sample_rate);
+        return AVERROR(ENOSYS);
+    }
+    if (avctx->flags & CODEC_FLAG_GLOBAL_HEADER) {
+        avctx->extradata_size = 2;
+        avctx->extradata      = av_mallocz(avctx->extradata_size +
+                                           FF_INPUT_BUFFER_PADDING_SIZE);
+        if (!avctx->extradata)
+            return AVERROR(ENOMEM);
+
+        avctx->extradata[0] = 0x02 << 3 | index >> 1;
+        avctx->extradata[1] = (index & 0x01) << 7 | avctx->channels << 3;
+    }
+    return 0;
+}
+
+static int aac_encode_close(AVCodecContext *avctx)
+{
+    AACContext *s = avctx->priv_data;
+
+    s->codec_api.Uninit(s->handle);
+    av_freep(&avctx->coded_frame);
+
+    return 0;
+}
+
+static int aac_encode_frame(AVCodecContext *avctx,
+                            unsigned char *frame/*out*/,
+                            int buf_size, void *data/*in*/)
+{
+    AACContext *s = avctx->priv_data;
+    VO_CODECBUFFER input = { 0 }, output = { 0 };
+    VO_AUDIO_OUTPUTINFO output_info = { { 0 } };
+
+    input.Buffer = data;
+    input.Length = 2 * avctx->channels * avctx->frame_size;
+    output.Buffer = frame;
+    output.Length = buf_size;
+
+    s->codec_api.SetInputData(s->handle, &input);
+    if (s->codec_api.GetOutputData(s->handle, &output, &output_info)
+        != VO_ERR_NONE) {
+        av_log(avctx, AV_LOG_ERROR, "Unable to encode frame\n");
+        return AVERROR(EINVAL);
+    }
+    return output.Length;
+}
+
+AVCodec ff_libvo_aacenc_encoder = {
+    "libvo_aacenc",
+    AVMEDIA_TYPE_AUDIO,
+    CODEC_ID_AAC,
+    sizeof(AACContext),
+    aac_encode_init,
+    aac_encode_frame,
+    aac_encode_close,
+    NULL,
+    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
+    .long_name = NULL_IF_CONFIG_SMALL("Android VisualOn AAC"),
+};
+
diff --git a/libavcodec/libvo-amrwbenc.c b/libavcodec/libvo-amrwbenc.c
new file mode 100644
index 0000000..b3615ed
--- /dev/null
+++ b/libavcodec/libvo-amrwbenc.c
@@ -0,0 +1,134 @@
+/*
+ * AMR Audio encoder stub
+ * Copyright (c) 2003 the ffmpeg project
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <vo-amrwbenc/enc_if.h>
+
+#include "avcodec.h"
+#include "libavutil/avstring.h"
+#include "libavutil/opt.h"
+
+typedef struct AMRWBContext {
+    AVClass *av_class;
+    void  *state;
+    int    mode;
+    int    last_bitrate;
+    int    allow_dtx;
+} AMRWBContext;
+
+static const AVOption options[] = {
+    { "dtx", "Allow DTX (generate comfort noise)", offsetof(AMRWBContext, allow_dtx), FF_OPT_TYPE_INT, 0, 0, 1, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM },
+    { NULL }
+};
+
+static const AVClass class = {
+    "libvo_amrwbenc", av_default_item_name, options, LIBAVUTIL_VERSION_INT
+};
+
+static int get_wb_bitrate_mode(int bitrate, void *log_ctx)
+{
+    /* make the correspondance between bitrate and mode */
+    static const int rates[] = {  6600,  8850, 12650, 14250, 15850, 18250,
+                                 19850, 23050, 23850 };
+    int i, best = -1, min_diff = 0;
+    char log_buf[200];
+
+    for (i = 0; i < 9; i++) {
+        if (rates[i] == bitrate)
+            return i;
+        if (best < 0 || abs(rates[i] - bitrate) < min_diff) {
+            best     = i;
+            min_diff = abs(rates[i] - bitrate);
+        }
+    }
+    /* no bitrate matching exactly, log a warning */
+    snprintf(log_buf, sizeof(log_buf), "bitrate not supported: use one of ");
+    for (i = 0; i < 9; i++)
+        av_strlcatf(log_buf, sizeof(log_buf), "%.2fk, ", rates[i]    / 1000.f);
+    av_strlcatf(log_buf, sizeof(log_buf), "using %.2fk", rates[best] / 1000.f);
+    av_log(log_ctx, AV_LOG_WARNING, "%s\n", log_buf);
+
+    return best;
+}
+
+static av_cold int amr_wb_encode_init(AVCodecContext *avctx)
+{
+    AMRWBContext *s = avctx->priv_data;
+
+    if (avctx->sample_rate != 16000) {
+        av_log(avctx, AV_LOG_ERROR, "Only 16000Hz sample rate supported\n");
+        return AVERROR(ENOSYS);
+    }
+
+    if (avctx->channels != 1) {
+        av_log(avctx, AV_LOG_ERROR, "Only mono supported\n");
+        return AVERROR(ENOSYS);
+    }
+
+    s->mode            = get_wb_bitrate_mode(avctx->bit_rate, avctx);
+    s->last_bitrate    = avctx->bit_rate;
+
+    avctx->frame_size  = 320;
+    avctx->coded_frame = avcodec_alloc_frame();
+
+    s->state     = E_IF_init();
+
+    return 0;
+}
+
+static int amr_wb_encode_close(AVCodecContext *avctx)
+{
+    AMRWBContext *s = avctx->priv_data;
+
+    E_IF_exit(s->state);
+    av_freep(&avctx->coded_frame);
+    return 0;
+}
+
+static int amr_wb_encode_frame(AVCodecContext *avctx,
+                               unsigned char *frame/*out*/,
+                               int buf_size, void *data/*in*/)
+{
+    AMRWBContext *s = avctx->priv_data;
+    int size;
+
+    if (s->last_bitrate != avctx->bit_rate) {
+        s->mode         = get_wb_bitrate_mode(avctx->bit_rate, avctx);
+        s->last_bitrate = avctx->bit_rate;
+    }
+    size = E_IF_encode(s->state, s->mode, data, frame, s->allow_dtx);
+    return size;
+}
+
+AVCodec ff_libvo_amrwbenc_encoder = {
+    "libvo_amrwbenc",
+    AVMEDIA_TYPE_AUDIO,
+    CODEC_ID_AMR_WB,
+    sizeof(AMRWBContext),
+    amr_wb_encode_init,
+    amr_wb_encode_frame,
+    amr_wb_encode_close,
+    NULL,
+    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
+    .long_name = NULL_IF_CONFIG_SMALL("Android VisualOn Adaptive Multi-Rate "
+                                      "(AMR) Wide-Band"),
+    .priv_class = &class,
+};
+
diff --git a/libavcodec/libvorbis.c b/libavcodec/libvorbis.c
index 81d328a..0a52daf 100644
--- a/libavcodec/libvorbis.c
+++ b/libavcodec/libvorbis.c
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2002 Mark Hills <mark at pogo.org.uk>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -26,8 +26,10 @@
 
 #include <vorbis/vorbisenc.h>
 
+#include "libavutil/opt.h"
 #include "avcodec.h"
 #include "bytestream.h"
+#include "vorbis.h"
 
 #undef NDEBUG
 #include <assert.h>
@@ -37,6 +39,7 @@
 #define BUFFER_SIZE (1024*64)
 
 typedef struct OggVorbisContext {
+    AVClass *av_class;
     vorbis_info vi ;
     vorbis_dsp_state vd ;
     vorbis_block vb ;
@@ -47,10 +50,18 @@ typedef struct OggVorbisContext {
     /* decoder */
     vorbis_comment vc ;
     ogg_packet op;
+
+    double iblock;
 } OggVorbisContext ;
 
+static const AVOption options[]={
+{"iblock", "Sets the impulse block bias", offsetof(OggVorbisContext, iblock), FF_OPT_TYPE_DOUBLE, 0, -15, 0, AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_ENCODING_PARAM},
+{NULL}
+};
+static const AVClass class = { "libvorbis", av_default_item_name, options, LIBAVUTIL_VERSION_INT };
 
 static av_cold int oggvorbis_init_encoder(vorbis_info *vi, AVCodecContext *avccontext) {
+    OggVorbisContext *context = avccontext->priv_data ;
     double cfreq;
 
     if(avccontext->flags & CODEC_FLAG_QSCALE) {
@@ -60,16 +71,18 @@ static av_cold int oggvorbis_init_encoder(vorbis_info *vi, AVCodecContext *avcco
                 avccontext->global_quality / (float)FF_QP2LAMBDA / 10.0))
             return -1;
     } else {
+        int minrate = avccontext->rc_min_rate > 0 ? avccontext->rc_min_rate : -1;
+        int maxrate = avccontext->rc_min_rate > 0 ? avccontext->rc_max_rate : -1;
+
         /* constant bitrate */
         if(vorbis_encode_setup_managed(vi, avccontext->channels,
-                avccontext->sample_rate, -1, avccontext->bit_rate, -1))
+                avccontext->sample_rate, minrate, avccontext->bit_rate, maxrate))
             return -1;
 
-#ifdef OGGVORBIS_VBR_BY_ESTIMATE
-        /* variable bitrate by estimate */
-        if(vorbis_encode_ctl(vi, OV_ECTL_RATEMANAGE_AVG, NULL))
-            return -1;
-#endif
+        /* variable bitrate by estimate, disable slow rate management */
+        if(minrate == -1 && maxrate == -1)
+            if(vorbis_encode_ctl(vi, OV_ECTL_RATEMANAGE2_SET, NULL))
+                return -1;
     }
 
     /* cutoff frequency */
@@ -79,14 +92,21 @@ static av_cold int oggvorbis_init_encoder(vorbis_info *vi, AVCodecContext *avcco
             return -1;
     }
 
+    if(context->iblock){
+        vorbis_encode_ctl(vi, OV_ECTL_IBLOCK_SET, &context->iblock);
+    }
+
     return vorbis_encode_setup_init(vi);
 }
 
+/* How many bytes are needed for a buffer of length 'l' */
+static int xiph_len(int l) { return (1 + l / 255 + l); }
+
 static av_cold int oggvorbis_encode_init(AVCodecContext *avccontext) {
     OggVorbisContext *context = avccontext->priv_data ;
     ogg_packet header, header_comm, header_code;
     uint8_t *p;
-    unsigned int offset, len;
+    unsigned int offset;
 
     vorbis_info_init(&context->vi) ;
     if(oggvorbis_init_encoder(&context->vi, avccontext) < 0) {
@@ -102,9 +122,11 @@ static av_cold int oggvorbis_encode_init(AVCodecContext *avccontext) {
     vorbis_analysis_headerout(&context->vd, &context->vc, &header,
                                 &header_comm, &header_code);
 
-    len = header.bytes + header_comm.bytes +  header_code.bytes;
-    avccontext->extradata_size= 64 + len + len/255;
-    p = avccontext->extradata= av_mallocz(avccontext->extradata_size);
+    avccontext->extradata_size=
+        1 + xiph_len(header.bytes) + xiph_len(header_comm.bytes) +
+        header_code.bytes;
+    p = avccontext->extradata =
+      av_malloc(avccontext->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
     p[0] = 2;
     offset = 1;
     offset += av_xiphlacing(&p[offset], header.bytes);
@@ -115,8 +137,7 @@ static av_cold int oggvorbis_encode_init(AVCodecContext *avccontext) {
     offset += header_comm.bytes;
     memcpy(&p[offset], header_code.packet, header_code.bytes);
     offset += header_code.bytes;
-    avccontext->extradata_size = offset;
-    avccontext->extradata= av_realloc(avccontext->extradata, avccontext->extradata_size);
+    assert(offset == avccontext->extradata_size);
 
 /*    vorbis_block_clear(&context->vb);
     vorbis_dsp_clear(&context->vd);
@@ -142,18 +163,16 @@ static int oggvorbis_encode_frame(AVCodecContext *avccontext,
     int l;
 
     if(data) {
-        int samples = OGGVORBIS_FRAME_SIZE;
+        const int samples = avccontext->frame_size;
         float **buffer ;
+        int c, channels = context->vi.channels;
 
         buffer = vorbis_analysis_buffer(&context->vd, samples) ;
-        if(context->vi.channels == 1) {
+        for (c = 0; c < channels; c++) {
+            int co = (channels > 8) ? c :
+                ff_vorbis_encoding_channel_layout_offsets[channels-1][c];
             for(l = 0 ; l < samples ; l++)
-                buffer[0][l]=audio[l]/32768.f;
-        } else {
-            for(l = 0 ; l < samples ; l++){
-                buffer[0][l]=audio[l*2]/32768.f;
-                buffer[1][l]=audio[l*2+1]/32768.f;
-            }
+                buffer[c][l]=audio[l*channels+co]/32768.f;
         }
         vorbis_analysis_wrote(&context->vd, samples) ;
     } else {
@@ -169,8 +188,12 @@ static int oggvorbis_encode_frame(AVCodecContext *avccontext,
         while(vorbis_bitrate_flushpacket(&context->vd, &op)) {
             /* i'd love to say the following line is a hack, but sadly it's
              * not, apparently the end of stream decision is in libogg. */
-            if(op.bytes==1)
+            if(op.bytes==1 && op.e_o_s)
                 continue;
+            if (context->buffer_index + sizeof(ogg_packet) + op.bytes > BUFFER_SIZE) {
+                av_log(avccontext, AV_LOG_ERROR, "libvorbis: buffer overflow.");
+                return -1;
+            }
             memcpy(context->buffer + context->buffer_index, &op, sizeof(ogg_packet));
             context->buffer_index += sizeof(ogg_packet);
             memcpy(context->buffer + context->buffer_index, op.packet, op.bytes);
@@ -188,9 +211,14 @@ static int oggvorbis_encode_frame(AVCodecContext *avccontext,
         avccontext->coded_frame->pts= av_rescale_q(op2->granulepos, (AVRational){1, avccontext->sample_rate}, avccontext->time_base);
         //FIXME we should reorder the user supplied pts and not assume that they are spaced by 1/sample_rate
 
+        if (l > buf_size) {
+            av_log(avccontext, AV_LOG_ERROR, "libvorbis: buffer overflow.");
+            return -1;
+        }
+
         memcpy(packets, op2->packet, l);
         context->buffer_index -= l + sizeof(ogg_packet);
-        memcpy(context->buffer, context->buffer + l + sizeof(ogg_packet), context->buffer_index);
+        memmove(context->buffer, context->buffer + l + sizeof(ogg_packet), context->buffer_index);
 //        av_log(avccontext, AV_LOG_DEBUG, "E%d\n", l);
     }
 
@@ -215,7 +243,7 @@ static av_cold int oggvorbis_encode_close(AVCodecContext *avccontext) {
 }
 
 
-AVCodec libvorbis_encoder = {
+AVCodec ff_libvorbis_encoder = {
     "libvorbis",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_VORBIS,
@@ -224,6 +252,7 @@ AVCodec libvorbis_encoder = {
     oggvorbis_encode_frame,
     oggvorbis_encode_close,
     .capabilities= CODEC_CAP_DELAY,
-    .sample_fmts = (const enum SampleFormat[]){SAMPLE_FMT_S16,SAMPLE_FMT_NONE},
+    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
     .long_name= NULL_IF_CONFIG_SMALL("libvorbis Vorbis"),
+    .priv_class= &class,
 } ;
diff --git a/libavcodec/libvpxdec.c b/libavcodec/libvpxdec.c
index 0464d12..2aa077c 100644
--- a/libavcodec/libvpxdec.c
+++ b/libavcodec/libvpxdec.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2010, Google, Inc.
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -27,6 +27,7 @@
 #include <vpx/vpx_decoder.h>
 #include <vpx/vp8dx.h>
 
+#include "libavutil/imgutils.h"
 #include "avcodec.h"
 
 typedef struct VP8DecoderContext {
@@ -86,7 +87,7 @@ static int vp8_decode(AVCodecContext *avctx,
         if ((int) img->d_w != avctx->width || (int) img->d_h != avctx->height) {
             av_log(avctx, AV_LOG_INFO, "dimension change! %dx%d -> %dx%d\n",
                    avctx->width, avctx->height, img->d_w, img->d_h);
-            if (avcodec_check_dimensions(avctx, img->d_w, img->d_h))
+            if (av_image_check_size(img->d_w, img->d_h, 0, avctx))
                 return AVERROR_INVALIDDATA;
             avcodec_set_dimensions(avctx, img->d_w, img->d_h);
         }
@@ -110,7 +111,7 @@ static av_cold int vp8_free(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec libvpx_decoder = {
+AVCodec ff_libvpx_decoder = {
     "libvpx",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_VP8,
diff --git a/libavcodec/libvpxenc.c b/libavcodec/libvpxenc.c
index fa393b8..2d818e1 100644
--- a/libavcodec/libvpxenc.c
+++ b/libavcodec/libvpxenc.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2010, Google, Inc.
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -36,13 +36,13 @@
  * One encoded frame returned from the library.
  */
 struct FrameListData {
-    void *buf;                       /**≤ compressed data buffer */
-    size_t sz;                       /**≤ length of compressed data */
-    int64_t pts;                     /**≤ time stamp to show frame
+    void *buf;                       /**< compressed data buffer */
+    size_t sz;                       /**< length of compressed data */
+    int64_t pts;                     /**< time stamp to show frame
                                           (in timebase units) */
-    unsigned long duration;          /**≤ duration to show frame
+    unsigned long duration;          /**< duration to show frame
                                           (in timebase units) */
-    uint32_t flags;                  /**≤ flags for this frame */
+    uint32_t flags;                  /**< flags for this frame */
     struct FrameListData *next;
 };
 
@@ -237,14 +237,28 @@ static av_cold int vp8_init(AVCodecContext *avctx)
     enccfg.rc_target_bitrate = av_rescale_rnd(avctx->bit_rate, 1, 1000,
                                               AV_ROUND_NEAR_INF);
 
-    //convert [1,51] -> [0,63]
-    enccfg.rc_min_quantizer = ((avctx->qmin * 5 + 1) >> 2) - 1;
-    enccfg.rc_max_quantizer = ((avctx->qmax * 5 + 1) >> 2) - 1;
-
+    enccfg.rc_min_quantizer = avctx->qmin;
+    enccfg.rc_max_quantizer = avctx->qmax;
+    enccfg.rc_dropframe_thresh = avctx->frame_skip_threshold;
+
+    //0-100 (0 => CBR, 100 => VBR)
+    enccfg.rc_2pass_vbr_bias_pct           = round(avctx->qcompress * 100);
+    enccfg.rc_2pass_vbr_minsection_pct     =
+        avctx->rc_min_rate * 100LL / avctx->bit_rate;
+    if (avctx->rc_max_rate)
+        enccfg.rc_2pass_vbr_maxsection_pct =
+            avctx->rc_max_rate * 100LL / avctx->bit_rate;
+
+    if (avctx->rc_buffer_size)
+        enccfg.rc_buf_sz         =
+            avctx->rc_buffer_size * 1000LL / avctx->bit_rate;
+    if (avctx->rc_initial_buffer_occupancy)
+        enccfg.rc_buf_initial_sz =
+            avctx->rc_initial_buffer_occupancy * 1000LL / avctx->bit_rate;
+    enccfg.rc_buf_optimal_sz     = enccfg.rc_buf_sz * 5 / 6;
+
+    //_enc_init() will balk if kf_min_dist differs from max w/VPX_KF_AUTO
     if (avctx->keyint_min == avctx->gop_size)
-        enccfg.kf_mode = VPX_KF_FIXED;
-    //_enc_init() will balk if kf_min_dist is set in this case
-    if (enccfg.kf_mode != VPX_KF_AUTO)
         enccfg.kf_min_dist = avctx->keyint_min;
     enccfg.kf_max_dist     = avctx->gop_size;
 
@@ -278,6 +292,11 @@ static av_cold int vp8_init(AVCodecContext *avctx)
     }
 
     ctx->deadline = VPX_DL_GOOD_QUALITY;
+    /* 0-3: For non-zero values the encoder increasingly optimizes for reduced
+       complexity playback on low powered devices at the expense of encode
+       quality. */
+   if (avctx->profile != FF_PROFILE_UNKNOWN)
+       enccfg.g_profile = avctx->profile;
 
     dump_enc_cfg(avctx, &enccfg);
     /* Construct Encoder Context */
@@ -291,6 +310,7 @@ static av_cold int vp8_init(AVCodecContext *avctx)
     av_log(avctx, AV_LOG_DEBUG, "vpx_codec_control\n");
     codecctl_int(avctx, VP8E_SET_CPUUSED,           cpuused);
     codecctl_int(avctx, VP8E_SET_NOISE_SENSITIVITY, avctx->noise_reduction);
+    codecctl_int(avctx, VP8E_SET_TOKEN_PARTITIONS,  av_log2(avctx->slices));
 
     //provide dummy value to initialize wrapper, values will be updated each _encode()
     vpx_img_wrap(&ctx->rawimg, VPX_IMG_FMT_I420, avctx->width, avctx->height, 1,
@@ -460,7 +480,7 @@ static int vp8_encode(AVCodecContext *avctx, uint8_t *buf, int buf_size,
     coded_size = queue_frames(avctx, buf, buf_size, avctx->coded_frame);
 
     if (!frame && avctx->flags & CODEC_FLAG_PASS1) {
-        unsigned int b64_size = ((ctx->twopass_stats.sz + 2) / 3) * 4 + 1;
+        unsigned int b64_size = AV_BASE64_SIZE(ctx->twopass_stats.sz);
 
         avctx->stats_out = av_malloc(b64_size);
         if (!avctx->stats_out) {
@@ -474,7 +494,7 @@ static int vp8_encode(AVCodecContext *avctx, uint8_t *buf, int buf_size,
     return coded_size;
 }
 
-AVCodec libvpx_encoder = {
+AVCodec ff_libvpx_encoder = {
     "libvpx",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_VP8,
diff --git a/libavcodec/libx264.c b/libavcodec/libx264.c
index df7b2e8..5825945 100644
--- a/libavcodec/libx264.c
+++ b/libavcodec/libx264.c
@@ -2,20 +2,20 @@
  * H.264 encoding using the x264 library
  * Copyright (C) 2005  Mans Rullgard <mans at mansr.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -89,6 +89,7 @@ static int X264_frame(AVCodecContext *ctx, uint8_t *buf,
     int nnal, i;
     x264_picture_t pic_out;
 
+    x264_picture_init( &x4->pic );
     x4->pic.img.i_csp   = X264_CSP_I420;
     x4->pic.img.i_plane = 3;
 
@@ -99,15 +100,25 @@ static int X264_frame(AVCodecContext *ctx, uint8_t *buf,
         }
 
         x4->pic.i_pts  = frame->pts;
-        x4->pic.i_type = X264_TYPE_AUTO;
+        x4->pic.i_type =
+            frame->pict_type == FF_I_TYPE ? X264_TYPE_KEYFRAME :
+            frame->pict_type == FF_P_TYPE ? X264_TYPE_P :
+            frame->pict_type == FF_B_TYPE ? X264_TYPE_B :
+                                            X264_TYPE_AUTO;
+        if (x4->params.b_tff != frame->top_field_first) {
+            x4->params.b_tff = frame->top_field_first;
+            x264_encoder_reconfig(x4->enc, &x4->params);
+        }
     }
 
+    do {
     if (x264_encoder_encode(x4->enc, &nal, &nnal, frame? &x4->pic: NULL, &pic_out) < 0)
         return -1;
 
     bufsize = encode_nals(ctx, buf, bufsize, nal, nnal, 0);
     if (bufsize < 0)
         return -1;
+    } while (!bufsize && !frame && x264_encoder_delayed_frames(x4->enc));
 
     /* FIXME: libx264 now provides DTS, but AVFrame doesn't have a field for it. */
     x4->out_pic.pts = pic_out.i_pts;
@@ -156,6 +167,7 @@ static av_cold int X264_init(AVCodecContext *avctx)
     x4->params.p_log_private        = avctx;
 
     x4->params.i_keyint_max         = avctx->gop_size;
+    x4->params.b_intra_refresh      = avctx->flags2 & CODEC_FLAG2_INTRA_REFRESH;
     x4->params.rc.i_bitrate         = avctx->bit_rate       / 1000;
     x4->params.rc.i_vbv_buffer_size = avctx->rc_buffer_size / 1000;
     x4->params.rc.i_vbv_max_bitrate = avctx->rc_max_rate    / 1000;
@@ -166,6 +178,7 @@ static av_cold int X264_init(AVCodecContext *avctx)
         if (avctx->crf) {
             x4->params.rc.i_rc_method   = X264_RC_CRF;
             x4->params.rc.f_rf_constant = avctx->crf;
+            x4->params.rc.f_rf_constant_max = avctx->crf_max;
         } else if (avctx->cqp > -1) {
             x4->params.rc.i_rc_method   = X264_RC_CQP;
             x4->params.rc.i_qp_constant = avctx->cqp;
@@ -264,15 +277,11 @@ static av_cold int X264_init(AVCodecContext *avctx)
     if (avctx->level > 0)
         x4->params.i_level_idc = avctx->level;
 
-    x4->params.rc.f_rate_tolerance =
-        (float)avctx->bit_rate_tolerance/avctx->bit_rate;
-
-    if ((avctx->rc_buffer_size != 0) &&
+    if (avctx->rc_buffer_size && avctx->rc_initial_buffer_occupancy &&
         (avctx->rc_initial_buffer_occupancy <= avctx->rc_buffer_size)) {
         x4->params.rc.f_vbv_buffer_init =
             (float)avctx->rc_initial_buffer_occupancy / avctx->rc_buffer_size;
-    } else
-        x4->params.rc.f_vbv_buffer_init = 0.9;
+    }
 
     x4->params.rc.b_mb_tree               = !!(avctx->flags2 & CODEC_FLAG2_MBTREE);
     x4->params.rc.f_ip_factor             = 1 / fabs(avctx->i_quant_factor);
@@ -289,6 +298,10 @@ static av_cold int X264_init(AVCodecContext *avctx)
 
     x4->params.b_interlaced   = avctx->flags & CODEC_FLAG_INTERLACED_DCT;
 
+    x4->params.i_slice_count  = avctx->slices;
+
+    x4->params.vui.b_fullrange = avctx->pix_fmt == PIX_FMT_YUVJ420P;
+
     if (avctx->flags & CODEC_FLAG_GLOBAL_HEADER)
         x4->params.b_repeat_headers = 0;
 
@@ -315,7 +328,7 @@ static av_cold int X264_init(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec libx264_encoder = {
+AVCodec ff_libx264_encoder = {
     .name           = "libx264",
     .type           = AVMEDIA_TYPE_VIDEO,
     .id             = CODEC_ID_H264,
@@ -324,6 +337,6 @@ AVCodec libx264_encoder = {
     .encode         = X264_frame,
     .close          = X264_close,
     .capabilities   = CODEC_CAP_DELAY,
-    .pix_fmts       = (const enum PixelFormat[]) { PIX_FMT_YUV420P, PIX_FMT_NONE },
+    .pix_fmts       = (const enum PixelFormat[]) { PIX_FMT_YUV420P, PIX_FMT_YUVJ420P, PIX_FMT_NONE },
     .long_name      = NULL_IF_CONFIG_SMALL("libx264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
 };
diff --git a/libavcodec/libxavs.c b/libavcodec/libxavs.c
new file mode 100644
index 0000000..7732914
--- /dev/null
+++ b/libavcodec/libxavs.c
@@ -0,0 +1,351 @@
+/*
+ * AVS encoding using the xavs library
+ * Copyright (C) 2010 Amanda, Y.N. Wu <amanda11192003 at gmail.com>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <math.h>
+#include <stdint.h>
+#include <xavs.h>
+#include "avcodec.h"
+
+#define END_OF_STREAM 0x001
+
+#define XAVS_PART_I8X8 0x002 /* Analyze i8x8 (requires 8x8 transform) */
+#define XAVS_PART_P8X8 0x010 /* Analyze p16x8, p8x16 and p8x8 */
+#define XAVS_PART_B8X8 0x100 /* Analyze b16x8, b*/
+
+typedef struct XavsContext {
+    xavs_param_t    params;
+    xavs_t         *enc;
+    xavs_picture_t  pic;
+    uint8_t        *sei;
+    int             sei_size;
+    AVFrame         out_pic;
+    int             end_of_stream;
+} XavsContext;
+
+static void XAVS_log(void *p, int level, const char *fmt, va_list args)
+{
+    static const int level_map[] = {
+        [XAVS_LOG_ERROR]   = AV_LOG_ERROR,
+        [XAVS_LOG_WARNING] = AV_LOG_WARNING,
+        [XAVS_LOG_INFO]    = AV_LOG_INFO,
+        [XAVS_LOG_DEBUG]   = AV_LOG_DEBUG
+    };
+
+    if (level < 0 || level > XAVS_LOG_DEBUG)
+        return;
+
+    av_vlog(p, level_map[level], fmt, args);
+}
+
+static int encode_nals(AVCodecContext *ctx, uint8_t *buf,
+                       int size, xavs_nal_t *nals,
+                       int nnal, int skip_sei)
+{
+    XavsContext *x4 = ctx->priv_data;
+    uint8_t *p = buf;
+    int i, s;
+
+    /* Write the SEI as part of the first frame. */
+    if (x4->sei_size > 0 && nnal > 0) {
+        memcpy(p, x4->sei, x4->sei_size);
+        p += x4->sei_size;
+        x4->sei_size = 0;
+    }
+
+    for (i = 0; i < nnal; i++) {
+        /* Don't put the SEI in extradata. */
+        if (skip_sei && nals[i].i_type == NAL_SEI) {
+            x4->sei = av_malloc( 5 + nals[i].i_payload * 4 / 3 );
+            if (xavs_nal_encode(x4->sei, &x4->sei_size, 1, nals + i) < 0)
+                return -1;
+
+            continue;
+        }
+        s = xavs_nal_encode(p, &size, 1, nals + i);
+        if (s < 0)
+            return -1;
+        p += s;
+    }
+
+    return p - buf;
+}
+
+static int XAVS_frame(AVCodecContext *ctx, uint8_t *buf,
+                      int bufsize, void *data)
+{
+    XavsContext *x4 = ctx->priv_data;
+    AVFrame *frame = data;
+    xavs_nal_t *nal;
+    int nnal, i;
+    xavs_picture_t pic_out;
+
+    x4->pic.img.i_csp   = XAVS_CSP_I420;
+    x4->pic.img.i_plane = 3;
+
+    if (frame) {
+       for (i = 0; i < 3; i++) {
+            x4->pic.img.plane[i] = frame->data[i];
+            x4->pic.img.i_stride[i] = frame->linesize[i];
+       }
+
+        x4->pic.i_pts  = frame->pts;
+        x4->pic.i_type = XAVS_TYPE_AUTO;
+    }
+
+    if (xavs_encoder_encode(x4->enc, &nal, &nnal,
+                            frame? &x4->pic: NULL, &pic_out) < 0)
+    return -1;
+
+    bufsize = encode_nals(ctx, buf, bufsize, nal, nnal, 0);
+
+    if (bufsize < 0)
+        return -1;
+
+    if (!bufsize && !frame && !(x4->end_of_stream)){
+        buf[bufsize]   = 0x0;
+        buf[bufsize+1] = 0x0;
+        buf[bufsize+2] = 0x01;
+        buf[bufsize+3] = 0xb1;
+        bufsize += 4;
+        x4->end_of_stream = END_OF_STREAM;
+        return bufsize;
+    }
+    /* FIXME: libxavs now provides DTS */
+    /* but AVFrame doesn't have a field for it. */
+    x4->out_pic.pts = pic_out.i_pts;
+
+    switch (pic_out.i_type) {
+    case XAVS_TYPE_IDR:
+    case XAVS_TYPE_I:
+        x4->out_pic.pict_type = FF_I_TYPE;
+        break;
+    case XAVS_TYPE_P:
+        x4->out_pic.pict_type = FF_P_TYPE;
+        break;
+    case XAVS_TYPE_B:
+    case XAVS_TYPE_BREF:
+        x4->out_pic.pict_type = FF_B_TYPE;
+        break;
+    }
+
+    /* There is no IDR frame in AVS JiZhun */
+    /* Sequence header is used as a flag */
+    x4->out_pic.key_frame = pic_out.i_type == XAVS_TYPE_I;
+
+    x4->out_pic.quality   = (pic_out.i_qpplus1 - 1) * FF_QP2LAMBDA;
+
+    return bufsize;
+}
+
+static av_cold int XAVS_close(AVCodecContext *avctx)
+{
+    XavsContext *x4 = avctx->priv_data;
+
+    av_freep(&avctx->extradata);
+    av_free(x4->sei);
+
+    if (x4->enc)
+        xavs_encoder_close(x4->enc);
+
+    return 0;
+}
+
+static av_cold int XAVS_init(AVCodecContext *avctx)
+{
+    XavsContext *x4 = avctx->priv_data;
+
+    x4->sei_size = 0;
+    xavs_param_default(&x4->params);
+
+    x4->params.pf_log               = XAVS_log;
+    x4->params.p_log_private        = avctx;
+    x4->params.i_keyint_max         = avctx->gop_size;
+    x4->params.rc.i_bitrate         = avctx->bit_rate       / 1000;
+    x4->params.rc.i_vbv_buffer_size = avctx->rc_buffer_size / 1000;
+    x4->params.rc.i_vbv_max_bitrate = avctx->rc_max_rate    / 1000;
+    x4->params.rc.b_stat_write      = avctx->flags & CODEC_FLAG_PASS1;
+    if (avctx->flags & CODEC_FLAG_PASS2) {
+        x4->params.rc.b_stat_read = 1;
+    } else {
+        if (avctx->crf) {
+            x4->params.rc.i_rc_method   = XAVS_RC_CRF;
+            x4->params.rc.f_rf_constant = avctx->crf;
+        } else if (avctx->cqp > -1) {
+            x4->params.rc.i_rc_method   = XAVS_RC_CQP;
+            x4->params.rc.i_qp_constant = avctx->cqp;
+        }
+    }
+
+    /* if neither crf nor cqp modes are selected we have to enable the RC */
+    /* we do it this way because we cannot check if the bitrate has been set */
+    if (!(avctx->crf || (avctx->cqp > -1)))
+        x4->params.rc.i_rc_method = XAVS_RC_ABR;
+
+    x4->params.i_bframe          = avctx->max_b_frames;
+    /* cabac is not included in AVS JiZhun Profile */
+    x4->params.b_cabac           = 0;
+
+    x4->params.i_bframe_adaptive = avctx->b_frame_strategy;
+    x4->params.i_bframe_bias     = avctx->bframebias;
+
+    avctx->has_b_frames          = !!avctx->max_b_frames;
+
+    /* AVS doesn't allow B picture as reference */
+    /* The max allowed reference frame number of B is 2 */
+    x4->params.i_keyint_min      = avctx->keyint_min;
+    if (x4->params.i_keyint_min > x4->params.i_keyint_max)
+        x4->params.i_keyint_min = x4->params.i_keyint_max;
+
+    x4->params.i_scenecut_threshold        = avctx->scenechange_threshold;
+
+   // x4->params.b_deblocking_filter       = avctx->flags & CODEC_FLAG_LOOP_FILTER;
+    x4->params.i_deblocking_filter_alphac0 = avctx->deblockalpha;
+    x4->params.i_deblocking_filter_beta    = avctx->deblockbeta;
+
+    x4->params.rc.i_qp_min                 = avctx->qmin;
+    x4->params.rc.i_qp_max                 = avctx->qmax;
+    x4->params.rc.i_qp_step                = avctx->max_qdiff;
+
+    x4->params.rc.f_qcompress       = avctx->qcompress; /* 0.0 => cbr, 1.0 => constant qp */
+    x4->params.rc.f_qblur           = avctx->qblur;     /* temporally blur quants */
+    x4->params.rc.f_complexity_blur = avctx->complexityblur;
+
+    x4->params.i_frame_reference    = avctx->refs;
+
+    x4->params.i_width              = avctx->width;
+    x4->params.i_height             = avctx->height;
+    x4->params.vui.i_sar_width      = avctx->sample_aspect_ratio.num;
+    x4->params.vui.i_sar_height     = avctx->sample_aspect_ratio.den;
+    /* This is only used for counting the fps */
+    x4->params.i_fps_num            = avctx->time_base.den;
+    x4->params.i_fps_den            = avctx->time_base.num;
+    x4->params.analyse.inter        = XAVS_ANALYSE_I8x8 |XAVS_ANALYSE_PSUB16x16| XAVS_ANALYSE_BSUB16x16;
+    if (avctx->partitions) {
+        if (avctx->partitions & XAVS_PART_I8X8)
+            x4->params.analyse.inter |= XAVS_ANALYSE_I8x8;
+
+        if (avctx->partitions & XAVS_PART_P8X8)
+            x4->params.analyse.inter |= XAVS_ANALYSE_PSUB16x16;
+
+        if (avctx->partitions & XAVS_PART_B8X8)
+            x4->params.analyse.inter |= XAVS_ANALYSE_BSUB16x16;
+    }
+
+    x4->params.analyse.i_direct_mv_pred  = avctx->directpred;
+
+    x4->params.analyse.b_weighted_bipred = avctx->flags2 & CODEC_FLAG2_WPRED;
+
+    switch (avctx->me_method) {
+         case  ME_EPZS:
+               x4->params.analyse.i_me_method = XAVS_ME_DIA;
+               break;
+         case  ME_HEX:
+               x4->params.analyse.i_me_method = XAVS_ME_HEX;
+               break;
+         case  ME_UMH:
+               x4->params.analyse.i_me_method = XAVS_ME_UMH;
+               break;
+         case  ME_FULL:
+               x4->params.analyse.i_me_method = XAVS_ME_ESA;
+               break;
+         case  ME_TESA:
+               x4->params.analyse.i_me_method = XAVS_ME_TESA;
+               break;
+         default:
+               x4->params.analyse.i_me_method = XAVS_ME_HEX;
+    }
+
+    x4->params.analyse.i_me_range = avctx->me_range;
+    x4->params.analyse.i_subpel_refine    = avctx->me_subpel_quality;
+
+    x4->params.analyse.b_mixed_references = avctx->flags2 & CODEC_FLAG2_MIXED_REFS;
+    x4->params.analyse.b_chroma_me        = avctx->me_cmp & FF_CMP_CHROMA;
+    /* AVS P2 only enables 8x8 transform */
+    x4->params.analyse.b_transform_8x8    = 1; //avctx->flags2 & CODEC_FLAG2_8X8DCT;
+    x4->params.analyse.b_fast_pskip       = avctx->flags2 & CODEC_FLAG2_FASTPSKIP;
+
+    x4->params.analyse.i_trellis          = avctx->trellis;
+    x4->params.analyse.i_noise_reduction  = avctx->noise_reduction;
+
+    if (avctx->level > 0)
+        x4->params.i_level_idc = avctx->level;
+
+    x4->params.rc.f_rate_tolerance =
+        (float)avctx->bit_rate_tolerance/avctx->bit_rate;
+
+    if ((avctx->rc_buffer_size) &&
+        (avctx->rc_initial_buffer_occupancy <= avctx->rc_buffer_size)) {
+        x4->params.rc.f_vbv_buffer_init =
+            (float)avctx->rc_initial_buffer_occupancy / avctx->rc_buffer_size;
+    } else
+        x4->params.rc.f_vbv_buffer_init = 0.9;
+
+    /* TAG:do we have MB tree RC method */
+    /* what is the RC method we are now using? Default NO */
+    x4->params.rc.b_mb_tree               = !!(avctx->flags2 & CODEC_FLAG2_MBTREE);
+    x4->params.rc.f_ip_factor             = 1 / fabs(avctx->i_quant_factor);
+    x4->params.rc.f_pb_factor             = avctx->b_quant_factor;
+    x4->params.analyse.i_chroma_qp_offset = avctx->chromaoffset;
+
+    x4->params.analyse.b_psnr = avctx->flags & CODEC_FLAG_PSNR;
+    x4->params.i_log_level    = XAVS_LOG_DEBUG;
+    x4->params.b_aud          = avctx->flags2 & CODEC_FLAG2_AUD;
+    x4->params.i_threads      = avctx->thread_count;
+    x4->params.b_interlaced   = avctx->flags & CODEC_FLAG_INTERLACED_DCT;
+
+    if (avctx->flags & CODEC_FLAG_GLOBAL_HEADER)
+        x4->params.b_repeat_headers = 0;
+
+    x4->enc = xavs_encoder_open(&x4->params);
+    if (!x4->enc)
+        return -1;
+
+    avctx->coded_frame = &x4->out_pic;
+    /* TAG: Do we have GLOBAL HEADER in AVS */
+    /* We Have PPS and SPS in AVS */
+    if (avctx->flags & CODEC_FLAG_GLOBAL_HEADER) {
+        xavs_nal_t *nal;
+        int nnal, s;
+
+        s = xavs_encoder_headers(x4->enc, &nal, &nnal);
+
+        avctx->extradata      = av_malloc(s);
+        avctx->extradata_size = encode_nals(avctx, avctx->extradata, s, nal, nnal, 1);
+    }
+    return 0;
+}
+
+AVCodec ff_libxavs_encoder = {
+    .name           = "libxavs",
+    .type           = AVMEDIA_TYPE_VIDEO,
+    .id             = CODEC_ID_CAVS,
+    .priv_data_size = sizeof(XavsContext),
+    .init           = XAVS_init,
+    .encode         = XAVS_frame,
+    .close          = XAVS_close,
+    .capabilities   = CODEC_CAP_DELAY,
+    .pix_fmts       = (const enum PixelFormat[]) { PIX_FMT_YUV420P, PIX_FMT_NONE },
+    .long_name      = NULL_IF_CONFIG_SMALL("libxavs - the Chinese Audio Video Standard Encoder"),
+};
+
diff --git a/libavcodec/libxvid_internal.h b/libavcodec/libxvid_internal.h
index ffa5cf8..a2dc6ef 100644
--- a/libavcodec/libxvid_internal.h
+++ b/libavcodec/libxvid_internal.h
@@ -1,20 +1,20 @@
 /*
  * copyright (C) 2006 Corey Hickey
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -27,6 +27,6 @@
  */
 
 
-int av_tempfile(char *prefix, char **filename);
+int ff_tempfile(const char *prefix, char **filename);
 
 #endif /* AVCODEC_LIBXVID_INTERNAL_H */
diff --git a/libavcodec/libxvid_rc.c b/libavcodec/libxvid_rc.c
index c161ba7..9e33170 100644
--- a/libavcodec/libxvid_rc.c
+++ b/libavcodec/libxvid_rc.c
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -40,7 +40,7 @@ int ff_xvid_rate_control_init(MpegEncContext *s){
 
 //xvid_debug=-1;
 
-    fd=av_tempfile("xvidrc.", &tmp_name);
+    fd=ff_tempfile("xvidrc.", &tmp_name);
     if (fd == -1) {
         av_log(NULL, AV_LOG_ERROR, "Can't create temporary pass2 file.\n");
         return -1;
diff --git a/libavcodec/libxvidff.c b/libavcodec/libxvidff.c
index 2a404cd..89360e0 100644
--- a/libavcodec/libxvidff.c
+++ b/libavcodec/libxvidff.c
@@ -2,20 +2,20 @@
  * Interface to xvidcore for mpeg4 encoding
  * Copyright (c) 2004 Adam Thayer <krevnik at comcast.net>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,11 +25,18 @@
  * @author Adam Thayer (krevnik at comcast.net)
  */
 
+/* needed for mkstemp() */
+#define _XOPEN_SOURCE 600
+
 #include <xvid.h>
 #include <unistd.h>
 #include "avcodec.h"
+#include "libavutil/cpu.h"
 #include "libavutil/intreadwrite.h"
 #include "libxvid_internal.h"
+#if !HAVE_MKSTEMP
+#include <fcntl.h>
+#endif
 
 /**
  * Buffer management macros.
@@ -38,35 +45,33 @@
 #define BUFFER_REMAINING(x)         (BUFFER_SIZE - strlen(x))
 #define BUFFER_CAT(x)               (&((x)[strlen(x)]))
 
-/* For PPC Use */
-int has_altivec(void);
-
 /**
  * Structure for the private Xvid context.
  * This stores all the private context for the codec.
  */
 struct xvid_context {
-    void *encoder_handle;          /** Handle for Xvid encoder */
-    int xsize, ysize;              /** Frame size */
-    int vop_flags;                 /** VOP flags for Xvid encoder */
-    int vol_flags;                 /** VOL flags for Xvid encoder */
-    int me_flags;                  /** Motion Estimation flags */
-    int qscale;                    /** Do we use constant scale? */
-    int quicktime_format;          /** Are we in a QT-based format? */
-    AVFrame encoded_picture;       /** Encoded frame information */
-    char *twopassbuffer;           /** Character buffer for two-pass */
-    char *old_twopassbuffer;       /** Old character buffer (two-pass) */
-    char *twopassfile;             /** second pass temp file name */
-    unsigned char *intra_matrix;   /** P-Frame Quant Matrix */
-    unsigned char *inter_matrix;   /** I-Frame Quant Matrix */
+    void *encoder_handle;          /**< Handle for Xvid encoder */
+    int xsize;                     /**< Frame x size */
+    int ysize;                     /**< Frame y size */
+    int vop_flags;                 /**< VOP flags for Xvid encoder */
+    int vol_flags;                 /**< VOL flags for Xvid encoder */
+    int me_flags;                  /**< Motion Estimation flags */
+    int qscale;                    /**< Do we use constant scale? */
+    int quicktime_format;          /**< Are we in a QT-based format? */
+    AVFrame encoded_picture;       /**< Encoded frame information */
+    char *twopassbuffer;           /**< Character buffer for two-pass */
+    char *old_twopassbuffer;       /**< Old character buffer (two-pass) */
+    char *twopassfile;             /**< second pass temp file name */
+    unsigned char *intra_matrix;   /**< P-Frame Quant Matrix */
+    unsigned char *inter_matrix;   /**< I-Frame Quant Matrix */
 };
 
 /**
  * Structure for the private first-pass plugin.
  */
 struct xvid_ff_pass1 {
-    int     version;                /** Xvid version */
-    struct xvid_context *context;        /** Pointer to private context */
+    int     version;                /**< Xvid version */
+    struct xvid_context *context;   /**< Pointer to private context */
 };
 
 /* Prototypes - See function implementation for details */
@@ -74,8 +79,46 @@ int xvid_strip_vol_header(AVCodecContext *avctx, unsigned char *frame, unsigned
 int xvid_ff_2pass(void *ref, int opt, void *p1, void *p2);
 void xvid_correct_framerate(AVCodecContext *avctx);
 
+/* Wrapper to work around the lack of mkstemp() on mingw.
+ * Also, tries to create file in /tmp first, if possible.
+ * *prefix can be a character constant; *filename will be allocated internally.
+ * @return file descriptor of opened file (or -1 on error)
+ * and opened file name in **filename. */
+int ff_tempfile(const char *prefix, char **filename) {
+    int fd=-1;
+#if !HAVE_MKSTEMP
+    *filename = tempnam(".", prefix);
+#else
+    size_t len = strlen(prefix) + 12; /* room for "/tmp/" and "XXXXXX\0" */
+    *filename = av_malloc(len);
+#endif
+    /* -----common section-----*/
+    if (*filename == NULL) {
+        av_log(NULL, AV_LOG_ERROR, "ff_tempfile: Cannot allocate file name\n");
+        return -1;
+    }
+#if !HAVE_MKSTEMP
+    fd = open(*filename, O_RDWR | O_BINARY | O_CREAT, 0444);
+#else
+    snprintf(*filename, len, "/tmp/%sXXXXXX", prefix);
+    fd = mkstemp(*filename);
+    if (fd < 0) {
+        snprintf(*filename, len, "./%sXXXXXX", prefix);
+        fd = mkstemp(*filename);
+    }
+#endif
+    /* -----common section-----*/
+    if (fd < 0) {
+        av_log(NULL, AV_LOG_ERROR, "ff_tempfile: Cannot open temporary file %s\n", *filename);
+        return -1;
+    }
+    return fd; /* success */
+}
+
+#if CONFIG_LIBXVID_ENCODER
+
 /**
- * Creates the private context for the encoder.
+ * Create the private context for the encoder.
  * All buffers are allocated, settings are loaded from the user,
  * and the encoder context created.
  *
@@ -170,7 +213,7 @@ static av_cold int xvid_encode_init(AVCodecContext *avctx)  {
 #if ARCH_PPC
     /* Xvid's PPC support is borked, use libavcodec to detect */
 #if HAVE_ALTIVEC
-    if( has_altivec() ) {
+    if (av_get_cpu_flags() & AV_CPU_FLAG_ALTIVEC) {
         xvid_gbl_init.cpu_flags = XVID_CPU_FORCE | XVID_CPU_ALTIVEC;
     } else
 #endif
@@ -229,7 +272,7 @@ static av_cold int xvid_encode_init(AVCodecContext *avctx)  {
         rc2pass2.version = XVID_VERSION;
         rc2pass2.bitrate = avctx->bit_rate;
 
-        fd = av_tempfile("xvidff.", &(x->twopassfile));
+        fd = ff_tempfile("xvidff.", &(x->twopassfile));
         if( fd == -1 ) {
             av_log(avctx, AV_LOG_ERROR,
                 "Xvid: Cannot write 2-pass pipe\n");
@@ -359,7 +402,7 @@ static av_cold int xvid_encode_init(AVCodecContext *avctx)  {
 }
 
 /**
- * Encodes a single frame.
+ * Encode a single frame.
  *
  * @param avctx AVCodecContext pointer to context
  * @param frame Pointer to encoded frame buffer
@@ -406,7 +449,11 @@ static int xvid_encode_frame(AVCodecContext *avctx,
     xvid_enc_frame.vop_flags = x->vop_flags;
     xvid_enc_frame.vol_flags = x->vol_flags;
     xvid_enc_frame.motion = x->me_flags;
-    xvid_enc_frame.type = XVID_TYPE_AUTO;
+    xvid_enc_frame.type =
+        picture->pict_type == FF_I_TYPE ? XVID_TYPE_IVOP :
+        picture->pict_type == FF_P_TYPE ? XVID_TYPE_PVOP :
+        picture->pict_type == FF_B_TYPE ? XVID_TYPE_BVOP :
+                                          XVID_TYPE_AUTO;
 
     /* Pixel aspect ratio setting */
     if (avctx->sample_aspect_ratio.num < 1 || avctx->sample_aspect_ratio.num > 255 ||
@@ -469,7 +516,7 @@ static int xvid_encode_frame(AVCodecContext *avctx,
 }
 
 /**
- * Destroys the private context for the encoder.
+ * Destroy the private context for the encoder.
  * All buffers are freed, and the Xvid encoder context is destroyed.
  *
  * @param avctx AVCodecContext pointer to context
@@ -480,18 +527,14 @@ static av_cold int xvid_encode_close(AVCodecContext *avctx) {
 
     xvid_encore(x->encoder_handle, XVID_ENC_DESTROY, NULL, NULL);
 
-    if( avctx->extradata != NULL )
-        av_freep(&avctx->extradata);
+    av_freep(&avctx->extradata);
     if( x->twopassbuffer != NULL ) {
         av_free(x->twopassbuffer);
         av_free(x->old_twopassbuffer);
     }
-    if( x->twopassfile != NULL )
-        av_free(x->twopassfile);
-    if( x->intra_matrix != NULL )
-        av_free(x->intra_matrix);
-    if( x->inter_matrix != NULL )
-        av_free(x->inter_matrix);
+    av_free(x->twopassfile);
+    av_free(x->intra_matrix);
+    av_free(x->inter_matrix);
 
     return 0;
 }
@@ -609,7 +652,7 @@ void xvid_correct_framerate(AVCodecContext *avctx) {
  */
 
 /**
- * Initializes the two-pass plugin and context.
+ * Initialize the two-pass plugin and context.
  *
  * @param param Input construction parameter structure
  * @param handle Private context handle
@@ -640,7 +683,7 @@ static int xvid_ff_2pass_create(xvid_plg_create_t * param,
 }
 
 /**
- * Destroys the two-pass plugin context.
+ * Destroy the two-pass plugin context.
  *
  * @param ref Context pointer for the plugin
  * @param param Destrooy context
@@ -656,7 +699,7 @@ static int xvid_ff_2pass_destroy(struct xvid_context *ref,
 }
 
 /**
- * Enables fast encode mode during the first pass.
+ * Enable fast encode mode during the first pass.
  *
  * @param ref Context pointer for the plugin
  * @param param Frame data
@@ -699,7 +742,7 @@ static int xvid_ff_2pass_before(struct xvid_context *ref,
 }
 
 /**
- * Captures statistic data and writes it during first pass.
+ * Capture statistic data and write it during first pass.
  *
  * @param ref Context pointer for the plugin
  * @param param Statistic data
@@ -767,7 +810,7 @@ int xvid_ff_2pass(void *ref, int cmd, void *p1, void *p2) {
 /**
  * Xvid codec definition for libavcodec.
  */
-AVCodec libxvid_encoder = {
+AVCodec ff_libxvid_encoder = {
     "libxvid",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_MPEG4,
@@ -778,3 +821,5 @@ AVCodec libxvid_encoder = {
     .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
     .long_name= NULL_IF_CONFIG_SMALL("libxvidcore MPEG-4 part 2"),
 };
+
+#endif /* CONFIG_LIBXVID_ENCODER */
diff --git a/libavcodec/ljpegenc.c b/libavcodec/ljpegenc.c
index 2ef07c3..9eeb6f2 100644
--- a/libavcodec/ljpegenc.c
+++ b/libavcodec/ljpegenc.c
@@ -8,20 +8,20 @@
  * aspecting, new decode_frame mechanism and apple mjpeg-b support
  *                                  by Alex Beregszaszi
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -186,7 +186,7 @@ static int encode_picture_lossless(AVCodecContext *avctx, unsigned char *buf, in
 }
 
 
-AVCodec ljpeg_encoder = { //FIXME avoid MPV_* lossless JPEG should not need them
+AVCodec ff_ljpeg_encoder = { //FIXME avoid MPV_* lossless JPEG should not need them
     "ljpeg",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_LJPEG,
diff --git a/libavcodec/loco.c b/libavcodec/loco.c
index d19a80c..0733d09 100644
--- a/libavcodec/loco.c
+++ b/libavcodec/loco.c
@@ -2,20 +2,20 @@
  * LOCO codec
  * Copyright (c) 2005 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -285,7 +285,7 @@ static av_cold int decode_end(AVCodecContext *avctx){
     return 0;
 }
 
-AVCodec loco_decoder = {
+AVCodec ff_loco_decoder = {
     "loco",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_LOCO,
diff --git a/libavcodec/lpc.c b/libavcodec/lpc.c
index 49e41d8..58bb02d 100644
--- a/libavcodec/lpc.c
+++ b/libavcodec/lpc.c
@@ -2,25 +2,24 @@
  * LPC utility code
  * Copyright (c) 2006  Justin Ruggles <justin.ruggles at gmail.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "libavutil/lls.h"
-#include "dsputil.h"
 
 #define LPC_USE_DOUBLE
 #include "lpc.h"
@@ -29,7 +28,8 @@
 /**
  * Apply Welch window function to audio block
  */
-static void apply_welch_window(const int32_t *data, int len, double *w_data)
+static void lpc_apply_welch_window_c(const int32_t *data, int len,
+                                     double *w_data)
 {
     int i, n2;
     double w;
@@ -52,27 +52,19 @@ static void apply_welch_window(const int32_t *data, int len, double *w_data)
 }
 
 /**
- * Calculates autocorrelation data from audio samples
+ * Calculate autocorrelation data from audio samples
  * A Welch window function is applied before calculation.
  */
-void ff_lpc_compute_autocorr(const int32_t *data, int len, int lag,
-                             double *autoc)
+static void lpc_compute_autocorr_c(const double *data, int len, int lag,
+                                   double *autoc)
 {
     int i, j;
-    double tmp[len + lag + 1];
-    double *data1= tmp + lag;
-
-    apply_welch_window(data, len, data1);
-
-    for(j=0; j<lag; j++)
-        data1[j-lag]= 0.0;
-    data1[len] = 0.0;
 
     for(j=0; j<lag; j+=2){
         double sum0 = 1.0, sum1 = 1.0;
         for(i=j; i<len; i++){
-            sum0 += data1[i] * data1[i-j];
-            sum1 += data1[i] * data1[i-j-1];
+            sum0 += data[i] * data[i-j];
+            sum1 += data[i] * data[i-j-1];
         }
         autoc[j  ] = sum0;
         autoc[j+1] = sum1;
@@ -81,8 +73,8 @@ void ff_lpc_compute_autocorr(const int32_t *data, int len, int lag,
     if(j==lag){
         double sum = 1.0;
         for(i=j-1; i<len; i+=2){
-            sum += data1[i  ] * data1[i-j  ]
-                 + data1[i+1] * data1[i-j+1];
+            sum += data[i  ] * data[i-j  ]
+                 + data[i+1] * data[i-j+1];
         }
         autoc[j] = sum;
     }
@@ -162,10 +154,11 @@ static int estimate_best_order(double *ref, int min_order, int max_order)
  * 1  = LPC with coeffs determined by Levinson-Durbin recursion
  * 2+ = LPC with coeffs determined by Cholesky factorization using (use_lpc-1) passes.
  */
-int ff_lpc_calc_coefs(DSPContext *s,
+int ff_lpc_calc_coefs(LPCContext *s,
                       const int32_t *samples, int blocksize, int min_order,
                       int max_order, int precision,
-                      int32_t coefs[][MAX_LPC_ORDER], int *shift, int use_lpc,
+                      int32_t coefs[][MAX_LPC_ORDER], int *shift,
+                      enum AVLPCType lpc_type, int lpc_passes,
                       int omethod, int max_shift, int zero_shift)
 {
     double autoc[MAX_LPC_ORDER+1];
@@ -174,20 +167,32 @@ int ff_lpc_calc_coefs(DSPContext *s,
     int i, j, pass;
     int opt_order;
 
-    assert(max_order >= MIN_LPC_ORDER && max_order <= MAX_LPC_ORDER && use_lpc > 0);
+    assert(max_order >= MIN_LPC_ORDER && max_order <= MAX_LPC_ORDER &&
+           lpc_type > AV_LPC_TYPE_FIXED);
+
+    /* reinit LPC context if parameters have changed */
+    if (blocksize != s->blocksize || max_order != s->max_order ||
+        lpc_type  != s->lpc_type) {
+        ff_lpc_end(s);
+        ff_lpc_init(s, blocksize, max_order, lpc_type);
+    }
+
+    if (lpc_type == AV_LPC_TYPE_LEVINSON) {
+        double *windowed_samples = s->windowed_samples + max_order;
 
-    if(use_lpc == 1){
-        s->lpc_compute_autocorr(samples, blocksize, max_order, autoc);
+        s->lpc_apply_welch_window(samples, blocksize, windowed_samples);
+
+        s->lpc_compute_autocorr(windowed_samples, blocksize, max_order, autoc);
 
         compute_lpc_coefs(autoc, max_order, &lpc[0][0], MAX_LPC_ORDER, 0, 1);
 
         for(i=0; i<max_order; i++)
             ref[i] = fabs(lpc[i][i]);
-    }else{
+    } else if (lpc_type == AV_LPC_TYPE_CHOLESKY) {
         LLSModel m[2];
         double var[MAX_LPC_ORDER+1], av_uninit(weight);
 
-        for(pass=0; pass<use_lpc-1; pass++){
+        for(pass=0; pass<lpc_passes; pass++){
             av_init_lls(&m[pass&1], max_order);
 
             weight=0;
@@ -234,3 +239,33 @@ int ff_lpc_calc_coefs(DSPContext *s,
 
     return opt_order;
 }
+
+av_cold int ff_lpc_init(LPCContext *s, int blocksize, int max_order,
+                        enum AVLPCType lpc_type)
+{
+    s->blocksize = blocksize;
+    s->max_order = max_order;
+    s->lpc_type  = lpc_type;
+
+    if (lpc_type == AV_LPC_TYPE_LEVINSON) {
+        s->windowed_samples = av_mallocz((blocksize + max_order + 2) *
+                                         sizeof(*s->windowed_samples));
+        if (!s->windowed_samples)
+            return AVERROR(ENOMEM);
+    } else {
+        s->windowed_samples = NULL;
+    }
+
+    s->lpc_apply_welch_window = lpc_apply_welch_window_c;
+    s->lpc_compute_autocorr   = lpc_compute_autocorr_c;
+
+    if (HAVE_MMX)
+        ff_lpc_init_x86(s);
+
+    return 0;
+}
+
+av_cold void ff_lpc_end(LPCContext *s)
+{
+    av_freep(&s->windowed_samples);
+}
diff --git a/libavcodec/lpc.h b/libavcodec/lpc.h
index d3754f0..c2d3428 100644
--- a/libavcodec/lpc.h
+++ b/libavcodec/lpc.h
@@ -2,20 +2,20 @@
  * LPC utility code
  * Copyright (c) 2006  Justin Ruggles <justin.ruggles at gmail.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -36,17 +36,61 @@
 #define MAX_LPC_ORDER       32
 
 
+typedef struct LPCContext {
+    int blocksize;
+    int max_order;
+    enum AVLPCType lpc_type;
+    double *windowed_samples;
+
+    /**
+     * Apply a Welch window to an array of input samples.
+     * The output samples have the same scale as the input, but are in double
+     * sample format.
+     * @param data    input samples
+     * @param len     number of input samples
+     * @param w_data  output samples
+     */
+    void (*lpc_apply_welch_window)(const int32_t *data, int len,
+                                   double *w_data);
+    /**
+     * Perform autocorrelation on input samples with delay of 0 to lag.
+     * @param data  input samples.
+     *              constraints: no alignment needed, but must have have at
+     *              least lag*sizeof(double) valid bytes preceeding it, and
+     *              size must be at least (len+1)*sizeof(double) if data is
+     *              16-byte aligned or (len+2)*sizeof(double) if data is
+     *              unaligned.
+     * @param len   number of input samples to process
+     * @param lag   maximum delay to calculate
+     * @param autoc output autocorrelation coefficients.
+     *              constraints: array size must be at least lag+1.
+     */
+    void (*lpc_compute_autocorr)(const double *data, int len, int lag,
+                                 double *autoc);
+} LPCContext;
+
+
 /**
  * Calculate LPC coefficients for multiple orders
  */
-int ff_lpc_calc_coefs(DSPContext *s,
+int ff_lpc_calc_coefs(LPCContext *s,
                       const int32_t *samples, int blocksize, int min_order,
                       int max_order, int precision,
-                      int32_t coefs[][MAX_LPC_ORDER], int *shift, int use_lpc,
+                      int32_t coefs[][MAX_LPC_ORDER], int *shift,
+                      enum AVLPCType lpc_type, int lpc_passes,
                       int omethod, int max_shift, int zero_shift);
 
-void ff_lpc_compute_autocorr(const int32_t *data, int len, int lag,
-                             double *autoc);
+/**
+ * Initialize LPCContext.
+ */
+int ff_lpc_init(LPCContext *s, int blocksize, int max_order,
+                enum AVLPCType lpc_type);
+void ff_lpc_init_x86(LPCContext *s);
+
+/**
+ * Uninitialize LPCContext.
+ */
+void ff_lpc_end(LPCContext *s);
 
 #ifdef LPC_USE_DOUBLE
 #define LPC_TYPE double
@@ -56,7 +100,7 @@ void ff_lpc_compute_autocorr(const int32_t *data, int len, int lag,
 
 /**
  * Levinson-Durbin recursion.
- * Produces LPC coefficients from autocorrelation data.
+ * Produce LPC coefficients from autocorrelation data.
  */
 static inline int compute_lpc_coefs(const LPC_TYPE *autoc, int max_order,
                                     LPC_TYPE *lpc, int lpc_stride, int fail,
diff --git a/libavcodec/lsp.c b/libavcodec/lsp.c
index 003ffbc..d9ddd7d 100644
--- a/libavcodec/lsp.c
+++ b/libavcodec/lsp.c
@@ -4,20 +4,20 @@
  * Copyright (c) 2007 Reynaldo H. Verdejo Pinochet (QCELP decoder)
  * Copyright (c) 2008 Vladimir Voroshilov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -65,6 +65,14 @@ void ff_acelp_lsf2lsp(int16_t *lsp, const int16_t *lsf, int lp_order)
         lsp[i] = ff_cos(lsf[i] * 20861 >> 15); // divide by PI and (0,13) -> (0,14)
 }
 
+void ff_acelp_lsf2lspd(double *lsp, const float *lsf, int lp_order)
+{
+    int i;
+
+    for(i = 0; i < lp_order; i++)
+        lsp[i] = cos(2.0 * M_PI * lsf[i]);
+}
+
 /**
  * \brief decodes polynomial coefficients from LSP
  * \param f [out] decoded polynomial coefficients (-0x20000000 <= (3.22) <= 0x1fffffff)
@@ -90,8 +98,8 @@ static void lsp2poly(int* f, const int16_t* lsp, int lp_half_order)
 void ff_acelp_lsp2lpc(int16_t* lp, const int16_t* lsp, int lp_half_order)
 {
     int i;
-    int f1[lp_half_order+1]; // (3.22)
-    int f2[lp_half_order+1]; // (3.22)
+    int f1[MAX_LP_HALF_ORDER+1]; // (3.22)
+    int f2[MAX_LP_HALF_ORDER+1]; // (3.22)
 
     lsp2poly(f1, lsp  , lp_half_order);
     lsp2poly(f2, lsp+1, lp_half_order);
@@ -109,9 +117,35 @@ void ff_acelp_lsp2lpc(int16_t* lp, const int16_t* lsp, int lp_half_order)
     }
 }
 
+void ff_amrwb_lsp2lpc(const double *lsp, float *lp, int lp_order)
+{
+    int lp_half_order = lp_order >> 1;
+    double buf[lp_half_order + 1];
+    double pa[lp_half_order + 1];
+    double *qa = buf + 1;
+    int i,j;
+
+    qa[-1] = 0.0;
+
+    ff_lsp2polyf(lsp    , pa, lp_half_order    );
+    ff_lsp2polyf(lsp + 1, qa, lp_half_order - 1);
+
+    for (i = 1, j = lp_order - 1; i < lp_half_order; i++, j--) {
+        double paf =  pa[i]            * (1 + lsp[lp_order - 1]);
+        double qaf = (qa[i] - qa[i-2]) * (1 - lsp[lp_order - 1]);
+        lp[i-1]  = (paf + qaf) * 0.5;
+        lp[j-1]  = (paf - qaf) * 0.5;
+    }
+
+    lp[lp_half_order - 1] = (1.0 + lsp[lp_order - 1]) *
+        pa[lp_half_order] * 0.5;
+
+    lp[lp_order - 1] = lsp[lp_order - 1];
+}
+
 void ff_acelp_lp_decode(int16_t* lp_1st, int16_t* lp_2nd, const int16_t* lsp_2nd, const int16_t* lsp_prev, int lp_order)
 {
-    int16_t lsp_1st[lp_order]; // (0.15)
+    int16_t lsp_1st[MAX_LP_ORDER]; // (0.15)
     int i;
 
     /* LSP values for first subframe (3.2.5 of G.729, Equation 24)*/
diff --git a/libavcodec/lsp.h b/libavcodec/lsp.h
index c3aee7b..388de51 100644
--- a/libavcodec/lsp.h
+++ b/libavcodec/lsp.h
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2008 Vladimir Voroshilov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -31,7 +31,7 @@
 
 /**
  * \brief ensure a minimum distance between LSFs
- * \param lsfq [in/out] LSF to check and adjust
+ * \param[in,out] lsfq LSF to check and adjust
  * \param lsfq_min_distance minimum distance between LSFs
  * \param lsfq_min minimum allowed LSF value
  * \param lsfq_max maximum allowed LSF value
@@ -48,13 +48,13 @@ void ff_acelp_reorder_lsf(int16_t* lsfq, int lsfq_min_distance, int lsfq_min, in
  *
  * @param[in,out] lsf    LSFs in Hertz
  * @param min_spacing    minimum distance between two consecutive lsf values
- * @param                size size of the lsf vector
+ * @param size           size of the lsf vector
  */
-void ff_set_min_dist_lsf(float *lsf, double min_spacing, int order);
+void ff_set_min_dist_lsf(float *lsf, double min_spacing, int size);
 
 /**
  * \brief Convert LSF to LSP
- * \param lsp [out] LSP coefficients (-0x8000 <= (0.15) < 0x8000)
+ * \param[out] lsp LSP coefficients (-0x8000 <= (0.15) < 0x8000)
  * \param lsf normalized LSF coefficients (0 <= (2.13) < 0x2000 * PI)
  * \param lp_order LP filter order
  *
@@ -63,17 +63,27 @@ void ff_set_min_dist_lsf(float *lsf, double min_spacing, int order);
 void ff_acelp_lsf2lsp(int16_t *lsp, const int16_t *lsf, int lp_order);
 
 /**
+ * Floating point version of ff_acelp_lsf2lsp()
+ */
+void ff_acelp_lsf2lspd(double *lsp, const float *lsf, int lp_order);
+
+/**
  * \brief LSP to LP conversion (3.2.6 of G.729)
- * \param lp [out] decoded LP coefficients (-0x8000 <= (3.12) < 0x8000)
+ * \param[out] lp decoded LP coefficients (-0x8000 <= (3.12) < 0x8000)
  * \param lsp LSP coefficients (-0x8000 <= (0.15) < 0x8000)
  * \param lp_half_order LP filter order, divided by 2
  */
 void ff_acelp_lsp2lpc(int16_t* lp, const int16_t* lsp, int lp_half_order);
 
 /**
+ * LSP to LP conversion (5.2.4 of AMR-WB)
+ */
+void ff_amrwb_lsp2lpc(const double *lsp, float *lp, int lp_order);
+
+/**
  * \brief Interpolate LSP for the first subframe and convert LSP -> LP for both subframes (3.2.5 and 3.2.6 of G.729)
- * \param lp_1st [out] decoded LP coefficients for first subframe (-0x8000 <= (3.12) < 0x8000)
- * \param lp_2nd [out] decoded LP coefficients for second subframe (-0x8000 <= (3.12) < 0x8000)
+ * \param[out] lp_1st decoded LP coefficients for first subframe  (-0x8000 <= (3.12) < 0x8000)
+ * \param[out] lp_2nd decoded LP coefficients for second subframe (-0x8000 <= (3.12) < 0x8000)
  * \param lsp_2nd LSP coefficients of the second subframe (-0x8000 <= (0.15) < 0x8000)
  * \param lsp_prev LSP coefficients from the second subframe of the previous frame (-0x8000 <= (0.15) < 0x8000)
  * \param lp_order LP filter order
@@ -82,9 +92,10 @@ void ff_acelp_lp_decode(int16_t* lp_1st, int16_t* lp_2nd, const int16_t* lsp_2nd
 
 
 #define MAX_LP_HALF_ORDER 8
+#define MAX_LP_ORDER      (2*MAX_LP_HALF_ORDER)
 
 /**
- * Reconstructs LPC coefficients from the line spectral pair frequencies.
+ * Reconstruct LPC coefficients from the line spectral pair frequencies.
  *
  * @param lsp line spectral pairs in cosine domain
  * @param lpc linear predictive coding coefficients
@@ -105,12 +116,12 @@ void ff_acelp_lspd2lpc(const double *lsp, float *lpc, int lp_half_order);
 void ff_sort_nearly_sorted_floats(float *vals, int len);
 
 /**
- * Computes the Pa / (1 + z(-1)) or Qa / (1 - z(-1)) coefficients
+ * Compute the Pa / (1 + z(-1)) or Qa / (1 - z(-1)) coefficients
  * needed for LSP to LPC conversion.
  * We only need to calculate the 6 first elements of the polynomial.
  *
  * @param lsp line spectral pairs in cosine domain
- * @param f [out] polynomial input/output as a vector
+ * @param[out] f polynomial input/output as a vector
  *
  * TIA/EIA/IS-733 2.4.3.3.5-1/2
  */
diff --git a/libavcodec/lzw.c b/libavcodec/lzw.c
index 8043789..6129429 100644
--- a/libavcodec/lzw.c
+++ b/libavcodec/lzw.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2003 Fabrice Bellard
  * Copyright (c) 2006 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -121,7 +121,7 @@ av_cold void ff_lzw_decode_close(LZWState **p)
 
 /**
  * Initialize LZW decoder
- * @param s LZW context
+ * @param p LZW context
  * @param csize initial code size in bits
  * @param buf input data
  * @param buf_size input data size
@@ -161,7 +161,7 @@ int ff_lzw_decode_init(LZWState *p, int csize, const uint8_t *buf, int buf_size,
  * NOTE: the algorithm here is inspired from the LZW GIF decoder
  *  written by Steven A. Bennett in 1987.
  *
- * @param s LZW context
+ * @param p LZW context
  * @param buf output buffer
  * @param len number of bytes to decode
  * @return number of bytes decoded
diff --git a/libavcodec/lzw.h b/libavcodec/lzw.h
index 76a5b67..d1efdaf 100644
--- a/libavcodec/lzw.h
+++ b/libavcodec/lzw.h
@@ -3,20 +3,20 @@
  * Copyright (c) 2003 Fabrice Bellard
  * Copyright (c) 2006 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/lzwenc.c b/libavcodec/lzwenc.c
index 23248a6..df38116 100644
--- a/libavcodec/lzwenc.c
+++ b/libavcodec/lzwenc.c
@@ -2,20 +2,20 @@
  * LZW encoder
  * Copyright (c) 2007 Bartlomiej Wolowiec
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/mace.c b/libavcodec/mace.c
index 3c71320..53ec056 100644
--- a/libavcodec/mace.c
+++ b/libavcodec/mace.c
@@ -2,20 +2,20 @@
  * MACE decoder
  * Copyright (c) 2002 Laszlo Torok <torokl at alpha.dfmk.hu>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -230,7 +230,7 @@ static av_cold int mace_decode_init(AVCodecContext * avctx)
 {
     if (avctx->channels > 2)
         return -1;
-    avctx->sample_fmt = SAMPLE_FMT_S16;
+    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
     return 0;
 }
 
@@ -279,7 +279,7 @@ static int mace_decode_frame(AVCodecContext *avctx,
     return buf_size;
 }
 
-AVCodec mace3_decoder = {
+AVCodec ff_mace3_decoder = {
     "mace3",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_MACE3,
@@ -291,7 +291,7 @@ AVCodec mace3_decoder = {
     .long_name = NULL_IF_CONFIG_SMALL("MACE (Macintosh Audio Compression/Expansion) 3:1"),
 };
 
-AVCodec mace6_decoder = {
+AVCodec ff_mace6_decoder = {
     "mace6",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_MACE6,
diff --git a/libavcodec/mathops.h b/libavcodec/mathops.h
index 149910b..547bc1a 100644
--- a/libavcodec/mathops.h
+++ b/libavcodec/mathops.h
@@ -3,20 +3,20 @@
  * Copyright (c) 2001, 2002 Fabrice Bellard
  * Copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at> et al
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #ifndef AVCODEC_MATHOPS_H
@@ -118,14 +118,14 @@ static inline av_const int mid_pred(int a, int b, int c)
 #ifndef sign_extend
 static inline av_const int sign_extend(int val, unsigned bits)
 {
-    return (val << (INT_BIT - bits)) >> (INT_BIT - bits);
+    return (val << ((8 * sizeof(int)) - bits)) >> ((8 * sizeof(int)) - bits);
 }
 #endif
 
 #ifndef zero_extend
 static inline av_const unsigned zero_extend(unsigned val, unsigned bits)
 {
-    return (val << (INT_BIT - bits)) >> (INT_BIT - bits);
+    return (val << ((8 * sizeof(int)) - bits)) >> ((8 * sizeof(int)) - bits);
 }
 #endif
 
@@ -146,5 +146,37 @@ if ((y) < (x)) {\
 #   define NEG_USR32(a,s) (((uint32_t)(a))>>(32-(s)))
 #endif
 
+#if HAVE_BIGENDIAN
+# ifndef PACK_2U8
+#   define PACK_2U8(a,b)     (((a) <<  8) | (b))
+# endif
+# ifndef PACK_4U8
+#   define PACK_4U8(a,b,c,d) (((a) << 24) | ((b) << 16) | ((c) << 8) | (d))
+# endif
+# ifndef PACK_2U16
+#   define PACK_2U16(a,b)    (((a) << 16) | (b))
+# endif
+#else
+# ifndef PACK_2U8
+#   define PACK_2U8(a,b)     (((b) <<  8) | (a))
+# endif
+# ifndef PACK_4U2
+#   define PACK_4U8(a,b,c,d) (((d) << 24) | ((c) << 16) | ((b) << 8) | (a))
+# endif
+# ifndef PACK_2U16
+#   define PACK_2U16(a,b)    (((b) << 16) | (a))
+# endif
+#endif
+
+#ifndef PACK_2S8
+#   define PACK_2S8(a,b)     PACK_2U8((a)&255, (b)&255)
+#endif
+#ifndef PACK_4S8
+#   define PACK_4S8(a,b,c,d) PACK_4U8((a)&255, (b)&255, (c)&255, (d)&255)
+#endif
+#ifndef PACK_2S16
+#   define PACK_2S16(a,b)    PACK_2U16((a)&0xffff, (b)&0xffff)
+#endif
+
 #endif /* AVCODEC_MATHOPS_H */
 
diff --git a/libavcodec/mdct.c b/libavcodec/mdct.c
index 69e1bbf..6f64534 100644
--- a/libavcodec/mdct.c
+++ b/libavcodec/mdct.c
@@ -2,20 +2,20 @@
  * MDCT/IMDCT transforms
  * Copyright (c) 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -24,36 +24,18 @@
 #include "libavutil/common.h"
 #include "libavutil/mathematics.h"
 #include "fft.h"
+#include "fft-internal.h"
 
 /**
  * @file
  * MDCT/IMDCT transforms.
  */
 
-// Generate a Kaiser-Bessel Derived Window.
-#define BESSEL_I0_ITER 50 // default: 50 iterations of Bessel I0 approximation
-av_cold void ff_kbd_window_init(float *window, float alpha, int n)
-{
-   int i, j;
-   double sum = 0.0, bessel, tmp;
-   double local_window[n];
-   double alpha2 = (alpha * M_PI / n) * (alpha * M_PI / n);
-
-   for (i = 0; i < n; i++) {
-       tmp = i * (n - i) * alpha2;
-       bessel = 1.0;
-       for (j = BESSEL_I0_ITER; j > 0; j--)
-           bessel = bessel * tmp / (j * j) + 1;
-       sum += bessel;
-       local_window[i] = sum;
-   }
-
-   sum++;
-   for (i = 0; i < n; i++)
-       window[i] = sqrt(local_window[i] / sum);
-}
-
-#include "mdct_tablegen.h"
+#if CONFIG_FFT_FLOAT
+#   define RSCALE(x) (x)
+#else
+#   define RSCALE(x) ((x) >> 1)
+#endif
 
 /**
  * init MDCT or IMDCT computation.
@@ -69,7 +51,7 @@ av_cold int ff_mdct_init(FFTContext *s, int nbits, int inverse, double scale)
     s->mdct_bits = nbits;
     s->mdct_size = n;
     n4 = n >> 2;
-    s->permutation = FF_MDCT_PERM_NONE;
+    s->mdct_permutation = FF_MDCT_PERM_NONE;
 
     if (ff_fft_init(s, s->mdct_bits - 2, inverse) < 0)
         goto fail;
@@ -78,7 +60,7 @@ av_cold int ff_mdct_init(FFTContext *s, int nbits, int inverse, double scale)
     if (!s->tcos)
         goto fail;
 
-    switch (s->permutation) {
+    switch (s->mdct_permutation) {
     case FF_MDCT_PERM_NONE:
         s->tsin = s->tcos + n4;
         tstep = 1;
@@ -95,8 +77,8 @@ av_cold int ff_mdct_init(FFTContext *s, int nbits, int inverse, double scale)
     scale = sqrt(fabs(scale));
     for(i=0;i<n4;i++) {
         alpha = 2 * M_PI * (i + theta) / n;
-        s->tcos[i*tstep] = -cos(alpha) * scale;
-        s->tsin[i*tstep] = -sin(alpha) * scale;
+        s->tcos[i*tstep] = FIX15(-cos(alpha) * scale);
+        s->tsin[i*tstep] = FIX15(-sin(alpha) * scale);
     }
     return 0;
  fail:
@@ -104,17 +86,6 @@ av_cold int ff_mdct_init(FFTContext *s, int nbits, int inverse, double scale)
     return -1;
 }
 
-/* complex multiplication: p = a * b */
-#define CMUL(pre, pim, are, aim, bre, bim) \
-{\
-    FFTSample _are = (are);\
-    FFTSample _aim = (aim);\
-    FFTSample _bre = (bre);\
-    FFTSample _bim = (bim);\
-    (pre) = _are * _bre - _aim * _bim;\
-    (pim) = _are * _bim + _aim * _bre;\
-}
-
 /**
  * Compute the middle half of the inverse MDCT of size N = 2^nbits,
  * thus excluding the parts that can be derived by symmetry
@@ -144,7 +115,7 @@ void ff_imdct_half_c(FFTContext *s, FFTSample *output, const FFTSample *input)
         in1 += 2;
         in2 -= 2;
     }
-    ff_fft_calc(s, z);
+    s->fft_calc(s, z);
 
     /* post rotation + reordering */
     for(k = 0; k < n8; k++) {
@@ -186,7 +157,7 @@ void ff_imdct_calc_c(FFTContext *s, FFTSample *output, const FFTSample *input)
 void ff_mdct_calc_c(FFTContext *s, FFTSample *out, const FFTSample *input)
 {
     int i, j, n, n8, n4, n2, n3;
-    FFTSample re, im;
+    FFTDouble re, im;
     const uint16_t *revtab = s->revtab;
     const FFTSample *tcos = s->tcos;
     const FFTSample *tsin = s->tsin;
@@ -200,18 +171,18 @@ void ff_mdct_calc_c(FFTContext *s, FFTSample *out, const FFTSample *input)
 
     /* pre rotation */
     for(i=0;i<n8;i++) {
-        re = -input[2*i+3*n4] - input[n3-1-2*i];
-        im = -input[n4+2*i] + input[n4-1-2*i];
+        re = RSCALE(-input[2*i+n3] - input[n3-1-2*i]);
+        im = RSCALE(-input[n4+2*i] + input[n4-1-2*i]);
         j = revtab[i];
         CMUL(x[j].re, x[j].im, re, im, -tcos[i], tsin[i]);
 
-        re = input[2*i] - input[n2-1-2*i];
-        im = -(input[n2+2*i] + input[n-1-2*i]);
+        re = RSCALE( input[2*i]    - input[n2-1-2*i]);
+        im = RSCALE(-input[n2+2*i] - input[ n-1-2*i]);
         j = revtab[n8 + i];
         CMUL(x[j].re, x[j].im, re, im, -tcos[n8 + i], tsin[n8 + i]);
     }
 
-    ff_fft_calc(s, x);
+    s->fft_calc(s, x);
 
     /* post rotation */
     for(i=0;i<n8;i++) {
diff --git a/libavcodec/mdct_fixed.c b/libavcodec/mdct_fixed.c
new file mode 100644
index 0000000..94527f9
--- /dev/null
+++ b/libavcodec/mdct_fixed.c
@@ -0,0 +1,64 @@
+/*
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#define CONFIG_FFT_FLOAT 0
+#include "mdct.c"
+
+/* same as ff_mdct_calcw_c with double-width unscaled output */
+void ff_mdct_calcw_c(FFTContext *s, FFTDouble *out, const FFTSample *input)
+{
+    int i, j, n, n8, n4, n2, n3;
+    FFTDouble re, im;
+    const uint16_t *revtab = s->revtab;
+    const FFTSample *tcos = s->tcos;
+    const FFTSample *tsin = s->tsin;
+    FFTComplex *x = s->tmp_buf;
+    FFTDComplex *o = (FFTDComplex *)out;
+
+    n = 1 << s->mdct_bits;
+    n2 = n >> 1;
+    n4 = n >> 2;
+    n8 = n >> 3;
+    n3 = 3 * n4;
+
+    /* pre rotation */
+    for(i=0;i<n8;i++) {
+        re = RSCALE(-input[2*i+n3] - input[n3-1-2*i]);
+        im = RSCALE(-input[n4+2*i] + input[n4-1-2*i]);
+        j = revtab[i];
+        CMUL(x[j].re, x[j].im, re, im, -tcos[i], tsin[i]);
+
+        re = RSCALE( input[2*i]    - input[n2-1-2*i]);
+        im = RSCALE(-input[n2+2*i] - input[ n-1-2*i]);
+        j = revtab[n8 + i];
+        CMUL(x[j].re, x[j].im, re, im, -tcos[n8 + i], tsin[n8 + i]);
+    }
+
+    s->fft_calc(s, x);
+
+    /* post rotation */
+    for(i=0;i<n8;i++) {
+        FFTDouble r0, i0, r1, i1;
+        CMULL(i1, r0, x[n8-i-1].re, x[n8-i-1].im, -tsin[n8-i-1], -tcos[n8-i-1]);
+        CMULL(i0, r1, x[n8+i  ].re, x[n8+i  ].im, -tsin[n8+i  ], -tcos[n8+i  ]);
+        o[n8-i-1].re = r0;
+        o[n8-i-1].im = i0;
+        o[n8+i  ].re = r1;
+        o[n8+i  ].im = i1;
+    }
+}
diff --git a/libavcodec/mdct_float.c b/libavcodec/mdct_float.c
new file mode 100644
index 0000000..e4f5549
--- /dev/null
+++ b/libavcodec/mdct_float.c
@@ -0,0 +1,20 @@
+/*
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#define CONFIG_FFT_FLOAT 1
+#include "mdct.c"
diff --git a/libavcodec/mdct_tablegen.c b/libavcodec/mdct_tablegen.c
deleted file mode 100644
index 6205f06..0000000
--- a/libavcodec/mdct_tablegen.c
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Generate a header file for hardcoded MDCT tables
- *
- * Copyright (c) 2009 Reimar Döffinger <Reimar.Doeffinger at gmx.de>
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-#include <stdlib.h>
-#define CONFIG_HARDCODED_TABLES 0
-#define SINETABLE_CONST
-#define SINETABLE(size) \
-    float ff_sine_##size[size]
-#define FF_ARRAY_ELEMS(a) (sizeof(a) / sizeof((a)[0]))
-#ifndef M_PI
-#define M_PI 3.14159265358979323846
-#endif
-#include "mdct_tablegen.h"
-#include "tableprint.h"
-
-int main(void)
-{
-    int i;
-
-    write_fileheader();
-
-    for (i = 5; i <= 12; i++) {
-        ff_init_ff_sine_windows(i);
-        printf("SINETABLE(%4i) = {\n", 1 << i);
-        write_float_array(ff_sine_windows[i], 1 << i);
-        printf("};\n");
-    }
-
-    return 0;
-}
diff --git a/libavcodec/mdct_tablegen.h b/libavcodec/mdct_tablegen.h
deleted file mode 100644
index 1722c3b..0000000
--- a/libavcodec/mdct_tablegen.h
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Header file for hardcoded MDCT tables
- *
- * Copyright (c) 2009 Reimar Döffinger <Reimar.Doeffinger at gmx.de>
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-#include <assert.h>
-// do not use libavutil/mathematics.h since this is compiled both
-// for the host and the target and config.h is only valid for the target
-#include <math.h>
-#include "../libavutil/attributes.h"
-
-#if !CONFIG_HARDCODED_TABLES
-SINETABLE(  32);
-SINETABLE(  64);
-SINETABLE( 128);
-SINETABLE( 256);
-SINETABLE( 512);
-SINETABLE(1024);
-SINETABLE(2048);
-SINETABLE(4096);
-#else
-#include "libavcodec/mdct_tables.h"
-#endif
-
-SINETABLE_CONST float * const ff_sine_windows[] = {
-    NULL, NULL, NULL, NULL, NULL, // unused
-    ff_sine_32 , ff_sine_64 ,
-    ff_sine_128, ff_sine_256, ff_sine_512, ff_sine_1024, ff_sine_2048, ff_sine_4096
-};
-
-// Generate a sine window.
-av_cold void ff_sine_window_init(float *window, int n) {
-    int i;
-    for(i = 0; i < n; i++)
-        window[i] = sinf((i + 0.5) * (M_PI / (2.0 * n)));
-}
-
-av_cold void ff_init_ff_sine_windows(int index) {
-    assert(index >= 0 && index < FF_ARRAY_ELEMS(ff_sine_windows));
-#if !CONFIG_HARDCODED_TABLES
-    ff_sine_window_init(ff_sine_windows[index], 1 << index);
-#endif
-}
diff --git a/libavcodec/mdec.c b/libavcodec/mdec.c
index 606a749..510aa7b 100644
--- a/libavcodec/mdec.c
+++ b/libavcodec/mdec.c
@@ -4,20 +4,20 @@
  *
  * based upon code from Sebastian Jedruszkiewicz <elf at frogger.rules.pl>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -229,9 +229,11 @@ static av_cold int decode_init(AVCodecContext *avctx){
     ff_mpeg12_init_vlcs();
     ff_init_scantable(a->dsp.idct_permutation, &a->scantable, ff_zigzag_direct);
 
+    if( avctx->idct_algo == FF_IDCT_AUTO )
+        avctx->idct_algo = FF_IDCT_SIMPLE;
     p->qstride= 0;
     p->qscale_table= av_mallocz(a->mb_width);
-    avctx->pix_fmt= PIX_FMT_YUV420P;
+    avctx->pix_fmt= PIX_FMT_YUVJ420P;
 
     return 0;
 }
@@ -248,7 +250,7 @@ static av_cold int decode_end(AVCodecContext *avctx){
     return 0;
 }
 
-AVCodec mdec_decoder = {
+AVCodec ff_mdec_decoder = {
     "mdec",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_MDEC,
diff --git a/libavcodec/mimic.c b/libavcodec/mimic.c
index e5f7123..0f3ae59 100644
--- a/libavcodec/mimic.c
+++ b/libavcodec/mimic.c
@@ -1,21 +1,21 @@
 /*
  * Copyright (C) 2005  Ole André Vadla Ravnås <oleavr at gmail.com>
- * Copyright (C) 2008  Ramiro Polla <ramiro at lisha.ufsc.br>
+ * Copyright (C) 2008  Ramiro Polla
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -27,6 +27,7 @@
 #include "get_bits.h"
 #include "bytestream.h"
 #include "dsputil.h"
+#include "thread.h"
 
 #define MIMIC_HEADER_SIZE   20
 
@@ -51,6 +52,10 @@ typedef struct {
     ScanTable       scantable;
     DSPContext      dsp;
     VLC             vlc;
+
+    /* Kept in the context so multithreading can have a constant to read from */
+    int             next_cur_index;
+    int             next_prev_index;
 } MimicContext;
 
 static const uint32_t huffcodes[] = {
@@ -121,6 +126,23 @@ static av_cold int mimic_decode_init(AVCodecContext *avctx)
     return 0;
 }
 
+static int mimic_decode_update_thread_context(AVCodecContext *avctx, const AVCodecContext *avctx_from)
+{
+    MimicContext *dst = avctx->priv_data, *src = avctx_from->priv_data;
+
+    if (avctx == avctx_from) return 0;
+
+    dst->cur_index  = src->next_cur_index;
+    dst->prev_index = src->next_prev_index;
+
+    memcpy(dst->buf_ptrs, src->buf_ptrs, sizeof(src->buf_ptrs));
+    memcpy(dst->flipped_ptrs, src->flipped_ptrs, sizeof(src->flipped_ptrs));
+
+    memset(&dst->buf_ptrs[dst->cur_index], 0, sizeof(AVFrame));
+
+    return 0;
+}
+
 static const int8_t vlcdec_lookup[9][64] = {
     {    0, },
     {   -1,   1, },
@@ -187,7 +209,7 @@ static int vlc_decode_block(MimicContext *ctx, int num_coeffs, int qscale)
 
         value = get_bits(&ctx->gb, num_bits);
 
-        /* FFmpeg's IDCT behaves somewhat different from the original code, so
+        /* Libav's IDCT behaves somewhat different from the original code, so
          * a factor of 4 was added to the input */
 
         coeff = vlcdec_lookup[num_bits][value];
@@ -205,7 +227,7 @@ static int vlc_decode_block(MimicContext *ctx, int num_coeffs, int qscale)
 static int decode(MimicContext *ctx, int quality, int num_coeffs,
                   int is_iframe)
 {
-    int y, x, plane;
+    int y, x, plane, cur_row = 0;
 
     for(plane = 0; plane < 3; plane++) {
         const int is_chroma = !!plane;
@@ -236,6 +258,7 @@ static int decode(MimicContext *ctx, int quality, int num_coeffs,
                         int index = (ctx->cur_index+backref)&15;
                         uint8_t *p = ctx->flipped_ptrs[index].data[0];
 
+                        ff_thread_await_progress(&ctx->buf_ptrs[index], cur_row, 0);
                         if(p) {
                             p += src -
                                 ctx->flipped_ptrs[ctx->prev_index].data[plane];
@@ -246,6 +269,7 @@ static int decode(MimicContext *ctx, int quality, int num_coeffs,
                         }
                     }
                 } else {
+                    ff_thread_await_progress(&ctx->buf_ptrs[ctx->prev_index], cur_row, 0);
                     ctx->dsp.put_pixels_tab[1][0](dst, src, stride, 8);
                 }
                 src += 8;
@@ -253,6 +277,8 @@ static int decode(MimicContext *ctx, int quality, int num_coeffs,
             }
             src += (stride - ctx->num_hblocks[plane])<<3;
             dst += (stride - ctx->num_hblocks[plane])<<3;
+
+            ff_thread_report_progress(&ctx->buf_ptrs[ctx->cur_index], cur_row++, 0);
         }
     }
 
@@ -326,14 +352,20 @@ static int mimic_decode_frame(AVCodecContext *avctx, void *data,
     }
 
     ctx->buf_ptrs[ctx->cur_index].reference = 1;
-    if(avctx->get_buffer(avctx, &ctx->buf_ptrs[ctx->cur_index])) {
+    ctx->buf_ptrs[ctx->cur_index].pict_type = is_pframe ? FF_P_TYPE:FF_I_TYPE;
+    if(ff_thread_get_buffer(avctx, &ctx->buf_ptrs[ctx->cur_index])) {
         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
         return -1;
     }
 
+    ctx->next_prev_index = ctx->cur_index;
+    ctx->next_cur_index  = (ctx->cur_index - 1) & 15;
+
     prepare_avpic(ctx, &ctx->flipped_ptrs[ctx->cur_index],
                   (AVPicture*) &ctx->buf_ptrs[ctx->cur_index]);
 
+    ff_thread_finish_setup(avctx);
+
     av_fast_malloc(&ctx->swap_buf, &ctx->swap_buf_size,
                                  swap_buf_size + FF_INPUT_BUFFER_PADDING_SIZE);
     if(!ctx->swap_buf)
@@ -345,21 +377,23 @@ static int mimic_decode_frame(AVCodecContext *avctx, void *data,
     init_get_bits(&ctx->gb, ctx->swap_buf, swap_buf_size << 3);
 
     if(!decode(ctx, quality, num_coeffs, !is_pframe)) {
-        avctx->release_buffer(avctx, &ctx->buf_ptrs[ctx->cur_index]);
-        return -1;
+        if (avctx->active_thread_type&FF_THREAD_FRAME)
+            ff_thread_report_progress(&ctx->buf_ptrs[ctx->cur_index], INT_MAX, 0);
+        else {
+            ff_thread_release_buffer(avctx, &ctx->buf_ptrs[ctx->cur_index]);
+            return -1;
+        }
     }
 
-    ctx->buf_ptrs[ctx->cur_index].pict_type = is_pframe ? FF_P_TYPE:FF_I_TYPE;
     *(AVFrame*)data = ctx->buf_ptrs[ctx->cur_index];
     *data_size = sizeof(AVFrame);
 
-    ctx->prev_index = ctx->cur_index;
-    ctx->cur_index--;
-    ctx->cur_index &= 15;
+    ctx->prev_index = ctx->next_prev_index;
+    ctx->cur_index  = ctx->next_cur_index;
 
     /* Only release frames that aren't used for backreferences anymore */
     if(ctx->buf_ptrs[ctx->cur_index].data[0])
-        avctx->release_buffer(avctx, &ctx->buf_ptrs[ctx->cur_index]);
+        ff_thread_release_buffer(avctx, &ctx->buf_ptrs[ctx->cur_index]);
 
     return buf_size;
 }
@@ -370,15 +404,18 @@ static av_cold int mimic_decode_end(AVCodecContext *avctx)
     int i;
 
     av_free(ctx->swap_buf);
+
+    if(avctx->is_copy) return 0;
+
     for(i = 0; i < 16; i++)
         if(ctx->buf_ptrs[i].data[0])
-            avctx->release_buffer(avctx, &ctx->buf_ptrs[i]);
+            ff_thread_release_buffer(avctx, &ctx->buf_ptrs[i]);
     free_vlc(&ctx->vlc);
 
     return 0;
 }
 
-AVCodec mimic_decoder = {
+AVCodec ff_mimic_decoder = {
     "mimic",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_MIMIC,
@@ -387,6 +424,7 @@ AVCodec mimic_decoder = {
     NULL,
     mimic_decode_end,
     mimic_decode_frame,
-    CODEC_CAP_DR1,
+    CODEC_CAP_DR1 | CODEC_CAP_FRAME_THREADS,
     .long_name = NULL_IF_CONFIG_SMALL("Mimic"),
+    .update_thread_context = ONLY_IF_THREADS_ENABLED(mimic_decode_update_thread_context)
 };
diff --git a/libavcodec/mips/mathops.h b/libavcodec/mips/mathops.h
index a1b04ed..573745b 100644
--- a/libavcodec/mips/mathops.h
+++ b/libavcodec/mips/mathops.h
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2009 Mans Rullgard <mans at mansr.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,6 +25,8 @@
 #include "config.h"
 #include "libavutil/common.h"
 
+#if HAVE_INLINE_ASM
+
 #if HAVE_LOONGSON
 
 static inline av_const int64_t MAC64(int64_t d, int a, int b)
@@ -73,4 +75,6 @@ static inline av_const int64_t MLS64(int64_t d, int a, int b)
 
 #endif
 
+#endif /* HAVE_INLINE_ASM */
+
 #endif /* AVCODEC_MIPS_MATHOPS_H */
diff --git a/libavcodec/mjpeg.c b/libavcodec/mjpeg.c
index 6eba27d..9f2d50f 100644
--- a/libavcodec/mjpeg.c
+++ b/libavcodec/mjpeg.c
@@ -8,20 +8,20 @@
  * aspecting, new decode_frame mechanism and apple mjpeg-b support
  *                                  by Alex Beregszaszi
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/mjpeg.h b/libavcodec/mjpeg.h
index 3c88471..c3fde44 100644
--- a/libavcodec/mjpeg.h
+++ b/libavcodec/mjpeg.h
@@ -8,20 +8,20 @@
  * aspecting, new decode_frame mechanism and apple mjpeg-b support
  *                                  by Alex Beregszaszi
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/mjpeg2jpeg_bsf.c b/libavcodec/mjpeg2jpeg_bsf.c
new file mode 100644
index 0000000..335a73b
--- /dev/null
+++ b/libavcodec/mjpeg2jpeg_bsf.c
@@ -0,0 +1,113 @@
+/*
+ * MJPEG/AVI1 to JPEG/JFIF bitstream format filter
+ * Copyright (c) 2010 Adrian Daerr and Nicolas George
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/*
+ * Adapted from mjpeg2jpeg.c, with original copyright:
+ * Paris 2010 Adrian Daerr, public domain
+ */
+
+#include <string.h>
+#include "avcodec.h"
+#include "mjpeg.h"
+
+static const uint8_t jpeg_header[] = {
+    0xff, 0xd8,                     // SOI
+    0xff, 0xe0,                     // APP0
+    0x00, 0x10,                     // APP0 header size (including
+                                    // this field, but excluding preceding)
+    0x4a, 0x46, 0x49, 0x46, 0x00,   // ID string 'JFIF\0'
+    0x01, 0x01,                     // version
+    0x00,                           // bits per type
+    0x00, 0x00,                     // X density
+    0x00, 0x00,                     // Y density
+    0x00,                           // X thumbnail size
+    0x00,                           // Y thumbnail size
+};
+
+static const int dht_segment_size = 420;
+static const uint8_t dht_segment_head[] = { 0xFF, 0xC4, 0x01, 0xA2, 0x00 };
+static const uint8_t dht_segment_frag[] = {
+    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
+    0x0a, 0x0b, 0x01, 0x00, 0x03, 0x01, 0x01, 0x01, 0x01, 0x01,
+    0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
+};
+
+static uint8_t *append(uint8_t *buf, const uint8_t *src, int size)
+{
+    memcpy(buf, src, size);
+    return buf + size;
+}
+
+static uint8_t *append_dht_segment(uint8_t *buf)
+{
+    buf = append(buf, dht_segment_head, sizeof(dht_segment_head));
+    buf = append(buf, ff_mjpeg_bits_dc_luminance + 1, 16);
+    buf = append(buf, dht_segment_frag, sizeof(dht_segment_frag));
+    buf = append(buf, ff_mjpeg_val_dc, 12);
+    *(buf++) = 0x10;
+    buf = append(buf, ff_mjpeg_bits_ac_luminance + 1, 16);
+    buf = append(buf, ff_mjpeg_val_ac_luminance, 162);
+    *(buf++) = 0x11;
+    buf = append(buf, ff_mjpeg_bits_ac_chrominance + 1, 16);
+    buf = append(buf, ff_mjpeg_val_ac_chrominance, 162);
+    return buf;
+}
+
+static int mjpeg2jpeg_filter(AVBitStreamFilterContext *bsfc,
+                             AVCodecContext *avctx, const char *args,
+                             uint8_t **poutbuf, int *poutbuf_size,
+                             const uint8_t *buf, int buf_size,
+                             int keyframe)
+{
+    int input_skip, output_size;
+    uint8_t *output, *out;
+
+    if (buf_size < 12) {
+        av_log(avctx, AV_LOG_ERROR, "input is truncated\n");
+        return AVERROR_INVALIDDATA;
+    }
+    if (memcmp("AVI1", buf + 6, 4)) {
+        av_log(avctx, AV_LOG_ERROR, "input is not MJPEG/AVI1\n");
+        return AVERROR_INVALIDDATA;
+    }
+    input_skip = (buf[4] << 8) + buf[5] + 4;
+    if (buf_size < input_skip) {
+        av_log(avctx, AV_LOG_ERROR, "input is truncated\n");
+        return AVERROR_INVALIDDATA;
+    }
+    output_size = buf_size - input_skip +
+                  sizeof(jpeg_header) + dht_segment_size;
+    output = out = av_malloc(output_size);
+    if (!output)
+        return AVERROR(ENOMEM);
+    out = append(out, jpeg_header, sizeof(jpeg_header));
+    out = append_dht_segment(out);
+    out = append(out, buf + input_skip, buf_size - input_skip);
+    *poutbuf = output;
+    *poutbuf_size = output_size;
+    return 1;
+}
+
+AVBitStreamFilter ff_mjpeg2jpeg_bsf = {
+    .name           = "mjpeg2jpeg",
+    .priv_data_size = 0,
+    .filter         = mjpeg2jpeg_filter,
+};
diff --git a/libavcodec/mjpeg_parser.c b/libavcodec/mjpeg_parser.c
index b1848fa..b5282f1 100644
--- a/libavcodec/mjpeg_parser.c
+++ b/libavcodec/mjpeg_parser.c
@@ -4,20 +4,20 @@
  * Copyright (c) 2003 Alex Beregszaszi
  * Copyright (c) 2003-2004 Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -96,7 +96,7 @@ static int jpeg_parse(AVCodecParserContext *s,
 }
 
 
-AVCodecParser mjpeg_parser = {
+AVCodecParser ff_mjpeg_parser = {
     { CODEC_ID_MJPEG },
     sizeof(ParseContext),
     NULL,
diff --git a/libavcodec/mjpega_dump_header_bsf.c b/libavcodec/mjpega_dump_header_bsf.c
index bb7858e..2a181fc 100644
--- a/libavcodec/mjpega_dump_header_bsf.c
+++ b/libavcodec/mjpega_dump_header_bsf.c
@@ -2,20 +2,20 @@
  * MJPEG A dump header bitstream filter
  * Copyright (c) 2006 Baptiste Coudurier
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -87,7 +87,7 @@ static int mjpega_dump_header(AVBitStreamFilterContext *bsfc, AVCodecContext *av
     return 0;
 }
 
-AVBitStreamFilter mjpega_dump_header_bsf = {
+AVBitStreamFilter ff_mjpega_dump_header_bsf = {
     "mjpegadump",
     0,
     mjpega_dump_header,
diff --git a/libavcodec/mjpegbdec.c b/libavcodec/mjpegbdec.c
index b418f57..837304e 100644
--- a/libavcodec/mjpegbdec.c
+++ b/libavcodec/mjpegbdec.c
@@ -2,20 +2,20 @@
  * Apple MJPEG-B decoder
  * Copyright (c) 2002 Alex Beregszaszi
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -113,7 +113,7 @@ read_header:
         init_get_bits(&s->gb, buf_ptr+sos_offs, field_size*8);
         s->mjpb_skiptosod = (sod_offs - sos_offs - show_bits(&s->gb, 16));
         s->start_code = SOS;
-        ff_mjpeg_decode_sos(s);
+        ff_mjpeg_decode_sos(s, NULL, NULL);
     }
 
     if (s->interlaced) {
@@ -129,7 +129,7 @@ read_header:
 
     //XXX FIXME factorize, this looks very similar to the EOI code
 
-    *picture= s->picture;
+    *picture= *s->picture_ptr;
     *data_size = sizeof(AVFrame);
 
     if(!s->lossless){
@@ -145,7 +145,7 @@ read_header:
     return buf_ptr - buf;
 }
 
-AVCodec mjpegb_decoder = {
+AVCodec ff_mjpegb_decoder = {
     "mjpegb",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_MJPEGB,
@@ -156,5 +156,6 @@ AVCodec mjpegb_decoder = {
     mjpegb_decode_frame,
     CODEC_CAP_DR1,
     NULL,
+    .max_lowres = 3,
     .long_name = NULL_IF_CONFIG_SMALL("Apple MJPEG-B"),
 };
diff --git a/libavcodec/mjpegdec.c b/libavcodec/mjpegdec.c
index 7f57af9..6f29e46 100644
--- a/libavcodec/mjpegdec.c
+++ b/libavcodec/mjpegdec.c
@@ -8,20 +8,20 @@
  * aspecting, new decode_frame mechanism and apple mjpeg-b support
  *                                  by Alex Beregszaszi
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -33,6 +33,7 @@
 //#define DEBUG
 #include <assert.h>
 
+#include "libavutil/imgutils.h"
 #include "avcodec.h"
 #include "dsputil.h"
 #include "mjpeg.h"
@@ -43,23 +44,22 @@
 static int build_vlc(VLC *vlc, const uint8_t *bits_table, const uint8_t *val_table,
                       int nb_codes, int use_static, int is_ac)
 {
-    uint8_t huff_size[256+16];
-    uint16_t huff_code[256+16];
+    uint8_t huff_size[256];
+    uint16_t huff_code[256];
+    uint16_t huff_sym[256];
+    int i;
 
     assert(nb_codes <= 256);
 
     memset(huff_size, 0, sizeof(huff_size));
     ff_mjpeg_build_huffman_codes(huff_size, huff_code, bits_table, val_table);
 
-    if(is_ac){
-        memmove(huff_size+16, huff_size, sizeof(uint8_t)*nb_codes);
-        memmove(huff_code+16, huff_code, sizeof(uint16_t)*nb_codes);
-        memset(huff_size, 0, sizeof(uint8_t)*16);
-        memset(huff_code, 0, sizeof(uint16_t)*16);
-        nb_codes += 16;
-    }
+    for(i=0; i<256; i++)
+        huff_sym[i]= i + 16*is_ac;
+
+    if(is_ac) huff_sym[0]= 16*256;
 
-    return init_vlc(vlc, 9, nb_codes, huff_size, 1, 1, huff_code, 2, 2, use_static);
+    return init_vlc_sparse(vlc, 9, nb_codes, huff_size, 1, 1, huff_code, 2, 2, huff_sym, 2, 2, use_static);
 }
 
 static void build_basic_mjpeg_vlc(MJpegDecodeContext * s) {
@@ -71,12 +71,19 @@ static void build_basic_mjpeg_vlc(MJpegDecodeContext * s) {
               ff_mjpeg_val_ac_luminance, 251, 0, 1);
     build_vlc(&s->vlcs[1][1], ff_mjpeg_bits_ac_chrominance,
               ff_mjpeg_val_ac_chrominance, 251, 0, 1);
+    build_vlc(&s->vlcs[2][0], ff_mjpeg_bits_ac_luminance,
+              ff_mjpeg_val_ac_luminance, 251, 0, 0);
+    build_vlc(&s->vlcs[2][1], ff_mjpeg_bits_ac_chrominance,
+              ff_mjpeg_val_ac_chrominance, 251, 0, 0);
 }
 
 av_cold int ff_mjpeg_decode_init(AVCodecContext *avctx)
 {
     MJpegDecodeContext *s = avctx->priv_data;
 
+    if (!s->picture_ptr)
+        s->picture_ptr = &s->picture;
+
     s->avctx = avctx;
     dsputil_init(&s->dsp, avctx);
     ff_init_scantable(s->dsp.idct_permutation, &s->scantable, ff_zigzag_direct);
@@ -190,6 +197,13 @@ int ff_mjpeg_decode_dht(MJpegDecodeContext *s)
         if(build_vlc(&s->vlcs[class][index], bits_table, val_table, code_max + 1, 0, class > 0) < 0){
             return -1;
         }
+
+        if(class>0){
+            free_vlc(&s->vlcs[2][index]);
+            if(build_vlc(&s->vlcs[2][index], bits_table, val_table, code_max + 1, 0, 0) < 0){
+            return -1;
+            }
+        }
     }
     return 0;
 }
@@ -218,7 +232,7 @@ int ff_mjpeg_decode_sof(MJpegDecodeContext *s)
         height= s->height;
 
     av_log(s->avctx, AV_LOG_DEBUG, "sof0: picture: %dx%d\n", width, height);
-    if(avcodec_check_dimensions(s->avctx, width, height))
+    if(av_image_check_size(width, height, 0, s->avctx))
         return -1;
 
     nb_components = get_bits(&s->gb, 8);
@@ -271,8 +285,8 @@ int ff_mjpeg_decode_sof(MJpegDecodeContext *s)
             s->height < ((s->org_height * 3) / 4)) {
             s->interlaced = 1;
             s->bottom_field = s->interlace_polarity;
-            s->picture.interlaced_frame = 1;
-            s->picture.top_field_first = !s->interlace_polarity;
+            s->picture_ptr->interlaced_frame = 1;
+            s->picture_ptr->top_field_first = !s->interlace_polarity;
             height *= 2;
         }
 
@@ -331,20 +345,19 @@ int ff_mjpeg_decode_sof(MJpegDecodeContext *s)
             s->avctx->pix_fmt = PIX_FMT_GRAY16;
     }
 
-    if(s->picture.data[0])
-        s->avctx->release_buffer(s->avctx, &s->picture);
+    if(s->picture_ptr->data[0])
+        s->avctx->release_buffer(s->avctx, s->picture_ptr);
 
-    s->picture.reference= 0;
-    if(s->avctx->get_buffer(s->avctx, &s->picture) < 0){
+    if(s->avctx->get_buffer(s->avctx, s->picture_ptr) < 0){
         av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
         return -1;
     }
-    s->picture.pict_type= FF_I_TYPE;
-    s->picture.key_frame= 1;
+    s->picture_ptr->pict_type= FF_I_TYPE;
+    s->picture_ptr->key_frame= 1;
     s->got_picture = 1;
 
     for(i=0; i<3; i++){
-        s->linesize[i]= s->picture.linesize[i] << s->interlaced;
+        s->linesize[i]= s->picture_ptr->linesize[i] << s->interlaced;
     }
 
 //    printf("%d %d %d %d %d %d\n", s->width, s->height, s->linesize[0], s->linesize[1], s->interlaced, s->avctx->height);
@@ -405,19 +418,16 @@ static int decode_block(MJpegDecodeContext *s, DCTELEM *block,
     block[0] = val;
     /* AC coefs */
     i = 0;
-    {OPEN_READER(re, &s->gb)
-    for(;;) {
+    {OPEN_READER(re, &s->gb);
+    do {
         UPDATE_CACHE(re, &s->gb);
-        GET_VLC(code, re, &s->gb, s->vlcs[1][ac_index].table, 9, 2)
+        GET_VLC(code, re, &s->gb, s->vlcs[1][ac_index].table, 9, 2);
 
-        /* EOB */
-        if (code == 0x10)
-            break;
         i += ((unsigned)code) >> 4;
-        if(code != 0x100){
             code &= 0xf;
+        if(code){
             if(code > MIN_CACHE_BITS - 16){
-                UPDATE_CACHE(re, &s->gb)
+                UPDATE_CACHE(re, &s->gb);
             }
             {
                 int cache=GET_CACHE(re,&s->gb);
@@ -425,22 +435,17 @@ static int decode_block(MJpegDecodeContext *s, DCTELEM *block,
                 level = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
             }
 
-            LAST_SKIP_BITS(re, &s->gb, code)
+            LAST_SKIP_BITS(re, &s->gb, code);
 
-            if (i >= 63) {
-                if(i == 63){
-                    j = s->scantable.permutated[63];
-                    block[j] = level * quant_matrix[j];
-                    break;
-                }
+            if (i > 63) {
                 av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);
                 return -1;
             }
             j = s->scantable.permutated[i];
             block[j] = level * quant_matrix[j];
         }
-    }
-    CLOSE_READER(re, &s->gb)}
+    }while(i<63);
+    CLOSE_READER(re, &s->gb);}
 
     return 0;
 }
@@ -472,17 +477,17 @@ static int decode_block_progressive(MJpegDecodeContext *s, DCTELEM *block, uint8
         (*EOBRUN)--;
         return 0;
     }
-    {OPEN_READER(re, &s->gb)
+    {OPEN_READER(re, &s->gb);
     for(i=ss;;i++) {
         UPDATE_CACHE(re, &s->gb);
-        GET_VLC(code, re, &s->gb, s->vlcs[1][ac_index].table, 9, 2)
-        /* Progressive JPEG use AC coeffs from zero and this decoder sets offset 16 by default */
-        code -= 16;
-        if(code & 0xF) {
-            i += ((unsigned) code) >> 4;
-            code &= 0xf;
+        GET_VLC(code, re, &s->gb, s->vlcs[2][ac_index].table, 9, 2);
+
+        run = ((unsigned) code) >> 4;
+        code &= 0xF;
+        if(code) {
+            i += run;
             if(code > MIN_CACHE_BITS - 16){
-                UPDATE_CACHE(re, &s->gb)
+                UPDATE_CACHE(re, &s->gb);
             }
             {
                 int cache=GET_CACHE(re,&s->gb);
@@ -490,7 +495,7 @@ static int decode_block_progressive(MJpegDecodeContext *s, DCTELEM *block, uint8
                 level = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
             }
 
-            LAST_SKIP_BITS(re, &s->gb, code)
+            LAST_SKIP_BITS(re, &s->gb, code);
 
             if (i >= se) {
                 if(i == se){
@@ -504,22 +509,25 @@ static int decode_block_progressive(MJpegDecodeContext *s, DCTELEM *block, uint8
             j = s->scantable.permutated[i];
             block[j] = level * quant_matrix[j] << Al;
         }else{
-            run = ((unsigned) code) >> 4;
             if(run == 0xF){// ZRL - skip 15 coefficients
                 i += 15;
+                if (i >= se) {
+                    av_log(s->avctx, AV_LOG_ERROR, "ZRL overflow: %d\n", i);
+                    return -1;
+                }
             }else{
-                val = run;
-                run = (1 << run);
-                UPDATE_CACHE(re, &s->gb);
-                run += (GET_CACHE(re, &s->gb) >> (32 - val)) & (run - 1);
-                if(val)
-                    LAST_SKIP_BITS(re, &s->gb, val);
-                *EOBRUN = run - 1;
+                val = (1 << run);
+                if(run){
+                    UPDATE_CACHE(re, &s->gb);
+                    val += NEG_USR32(GET_CACHE(re, &s->gb), run);
+                    LAST_SKIP_BITS(re, &s->gb, run);
+                }
+                *EOBRUN = val - 1;
                 break;
             }
         }
     }
-    CLOSE_READER(re, &s->gb)}
+    CLOSE_READER(re, &s->gb);}
     if(i > *last_nnz)
         *last_nnz = i;
     return 0;
@@ -563,9 +571,8 @@ static int decode_block_refinement(MJpegDecodeContext *s, DCTELEM *block, uint8_
     else {
         for(;;i++) {
             UPDATE_CACHE(re, &s->gb);
-            GET_VLC(code, re, &s->gb, s->vlcs[1][ac_index].table, 9, 2)
-            /* Progressive JPEG use AC coeffs from zero and this decoder sets offset 16 by default */
-            code -= 16;
+            GET_VLC(code, re, &s->gb, s->vlcs[2][ac_index].table, 9, 2);
+
             if(code & 0xF) {
                 run = ((unsigned) code) >> 4;
                 UPDATE_CACHE(re, &s->gb);
@@ -578,7 +585,7 @@ static int decode_block_refinement(MJpegDecodeContext *s, DCTELEM *block, uint8_
                 if(i == se) {
                     if(i > *last_nnz)
                         *last_nnz = i;
-                    CLOSE_READER(re, &s->gb)
+                    CLOSE_READER(re, &s->gb);
                     return 0;
                 }
             }else{
@@ -630,7 +637,7 @@ static int ljpeg_decode_rgb_scan(MJpegDecodeContext *s, int predictor, int point
     }
     for(mb_y = 0; mb_y < s->mb_height; mb_y++) {
         const int modified_predictor= mb_y ? predictor : 1;
-        uint8_t *ptr = s->picture.data[0] + (linesize * mb_y);
+        uint8_t *ptr = s->picture_ptr->data[0] + (linesize * mb_y);
 
         if (s->interlaced && s->bottom_field)
             ptr += linesize >> 1;
@@ -707,7 +714,7 @@ static int ljpeg_decode_yuv_scan(MJpegDecodeContext *s, int predictor, int point
                     for(j=0; j<n; j++) {
                         int pred;
 
-                        ptr = s->picture.data[c] + (linesize * (v * mb_y + y)) + (h * mb_x + x); //FIXME optimize this crap
+                        ptr = s->picture_ptr->data[c] + (linesize * (v * mb_y + y)) + (h * mb_x + x); //FIXME optimize this crap
                         if(y==0 && mb_y==0){
                             if(x==0 && mb_x==0){
                                 pred= 128 << point_transform;
@@ -747,7 +754,7 @@ static int ljpeg_decode_yuv_scan(MJpegDecodeContext *s, int predictor, int point
                     for(j=0; j<n; j++) {
                         int pred;
 
-                        ptr = s->picture.data[c] + (linesize * (v * mb_y + y)) + (h * mb_x + x); //FIXME optimize this crap
+                        ptr = s->picture_ptr->data[c] + (linesize * (v * mb_y + y)) + (h * mb_x + x); //FIXME optimize this crap
                         PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor);
                         *ptr= pred + (mjpeg_decode_dc(s, s->dc_index[i]) << point_transform);
                         if (++x == h) {
@@ -766,10 +773,32 @@ static int ljpeg_decode_yuv_scan(MJpegDecodeContext *s, int predictor, int point
     return 0;
 }
 
-static int mjpeg_decode_scan(MJpegDecodeContext *s, int nb_components, int Ah, int Al){
+static av_always_inline void mjpeg_copy_block(uint8_t *dst, const uint8_t *src,
+                                              int linesize, int lowres)
+{
+    switch (lowres) {
+    case 0: copy_block8(dst, src, linesize, linesize, 8);
+        break;
+    case 1: copy_block4(dst, src, linesize, linesize, 4);
+        break;
+    case 2: copy_block2(dst, src, linesize, linesize, 2);
+        break;
+    case 3: *dst = *src;
+        break;
+    }
+}
+
+static int mjpeg_decode_scan(MJpegDecodeContext *s, int nb_components, int Ah, int Al,
+                             const uint8_t *mb_bitmask, const AVFrame *reference){
     int i, mb_x, mb_y;
     uint8_t* data[MAX_COMPONENTS];
+    const uint8_t *reference_data[MAX_COMPONENTS];
     int linesize[MAX_COMPONENTS];
+    GetBitContext mb_bitmask_gb;
+
+    if (mb_bitmask) {
+        init_get_bits(&mb_bitmask_gb, mb_bitmask, s->mb_width*s->mb_height);
+    }
 
     if(s->flipped && s->avctx->flags & CODEC_FLAG_EMU_EDGE) {
         av_log(s->avctx, AV_LOG_ERROR, "Can not flip image with CODEC_FLAG_EMU_EDGE set!\n");
@@ -777,24 +806,30 @@ static int mjpeg_decode_scan(MJpegDecodeContext *s, int nb_components, int Ah, i
     }
     for(i=0; i < nb_components; i++) {
         int c = s->comp_index[i];
-        data[c] = s->picture.data[c];
+        data[c] = s->picture_ptr->data[c];
+        reference_data[c] = reference ? reference->data[c] : NULL;
         linesize[c]=s->linesize[c];
         s->coefs_finished[c] |= 1;
         if(s->flipped) {
             //picture should be flipped upside-down for this codec
-            data[c] += (linesize[c] * (s->v_scount[i] * (8 * s->mb_height -((s->height/s->v_max)&7)) - 1 ));
+            int offset = (linesize[c] * (s->v_scount[i] * (8 * s->mb_height -((s->height/s->v_max)&7)) - 1 ));
+            data[c] += offset;
+            reference_data[c] += offset;
             linesize[c] *= -1;
         }
     }
 
     for(mb_y = 0; mb_y < s->mb_height; mb_y++) {
         for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
+            const int copy_mb = mb_bitmask && !get_bits1(&mb_bitmask_gb);
+
             if (s->restart_interval && !s->restart_count)
                 s->restart_count = s->restart_interval;
 
             for(i=0;i<nb_components;i++) {
                 uint8_t *ptr;
                 int n, h, v, x, y, c, j;
+                int block_offset;
                 n = s->nb_blocks[i];
                 c = s->comp_index[i];
                 h = s->h_scount[i];
@@ -802,12 +837,16 @@ static int mjpeg_decode_scan(MJpegDecodeContext *s, int nb_components, int Ah, i
                 x = 0;
                 y = 0;
                 for(j=0;j<n;j++) {
-                    ptr = data[c] +
-                        (((linesize[c] * (v * mb_y + y) * 8) +
-                        (h * mb_x + x) * 8) >> s->avctx->lowres);
+                    block_offset = (((linesize[c] * (v * mb_y + y) * 8) +
+                                     (h * mb_x + x) * 8) >> s->avctx->lowres);
+
                     if(s->interlaced && s->bottom_field)
-                        ptr += linesize[c] >> 1;
+                        block_offset += linesize[c] >> 1;
+                    ptr = data[c] + block_offset;
                     if(!s->progressive) {
+                        if (copy_mb) {
+                            mjpeg_copy_block(ptr, reference_data[c] + block_offset, linesize[c], s->avctx->lowres);
+                        } else {
                         s->dsp.clear_block(s->block);
                         if(decode_block(s, s->block, i,
                                      s->dc_index[i], s->ac_index[i],
@@ -816,6 +855,7 @@ static int mjpeg_decode_scan(MJpegDecodeContext *s, int nb_components, int Ah, i
                             return -1;
                         }
                         s->dsp.idct_put(ptr, linesize[c], s->block);
+                        }
                     } else {
                         int block_idx = s->block_stride[c] * (v * mb_y + y) + (h * mb_x + x);
                         DCTELEM *block = s->blocks[c][block_idx];
@@ -846,29 +886,43 @@ static int mjpeg_decode_scan(MJpegDecodeContext *s, int nb_components, int Ah, i
     return 0;
 }
 
-static int mjpeg_decode_scan_progressive_ac(MJpegDecodeContext *s, int ss, int se, int Ah, int Al){
+static int mjpeg_decode_scan_progressive_ac(MJpegDecodeContext *s, int ss, int se, int Ah, int Al,
+                                            const uint8_t *mb_bitmask, const AVFrame *reference){
     int mb_x, mb_y;
     int EOBRUN = 0;
     int c = s->comp_index[0];
-    uint8_t* data = s->picture.data[c];
+    uint8_t* data = s->picture_ptr->data[c];
+    const uint8_t *reference_data = reference ? reference->data[c] : NULL;
     int linesize = s->linesize[c];
     int last_scan = 0;
     int16_t *quant_matrix = s->quant_matrixes[ s->quant_index[c] ];
+    GetBitContext mb_bitmask_gb;
+
+    if (mb_bitmask) {
+        init_get_bits(&mb_bitmask_gb, mb_bitmask, s->mb_width*s->mb_height);
+    }
 
     if(!Al) {
         s->coefs_finished[c] |= (1LL<<(se+1))-(1LL<<ss);
         last_scan = !~s->coefs_finished[c];
     }
 
-    if(s->interlaced && s->bottom_field)
-        data += linesize >> 1;
+    if(s->interlaced && s->bottom_field) {
+        int offset = linesize >> 1;
+        data += offset;
+        reference_data += offset;
+    }
 
     for(mb_y = 0; mb_y < s->mb_height; mb_y++) {
-        uint8_t *ptr = data + (mb_y*linesize*8 >> s->avctx->lowres);
+        int block_offset = (mb_y*linesize*8 >> s->avctx->lowres);
+        uint8_t *ptr = data + block_offset;
         int block_idx = mb_y * s->block_stride[c];
         DCTELEM (*block)[64] = &s->blocks[c][block_idx];
         uint8_t *last_nnz = &s->last_nnz[c][block_idx];
         for(mb_x = 0; mb_x < s->mb_width; mb_x++, block++, last_nnz++) {
+            const int copy_mb = mb_bitmask && !get_bits1(&mb_bitmask_gb);
+
+            if (!copy_mb) {
             int ret;
             if(Ah)
                 ret = decode_block_refinement(s, *block, last_nnz, s->ac_index[0],
@@ -880,16 +934,23 @@ static int mjpeg_decode_scan_progressive_ac(MJpegDecodeContext *s, int ss, int s
                 av_log(s->avctx, AV_LOG_ERROR, "error y=%d x=%d\n", mb_y, mb_x);
                 return -1;
             }
+            }
+
             if(last_scan) {
+                if (copy_mb) {
+                    mjpeg_copy_block(ptr, reference_data + block_offset, linesize, s->avctx->lowres);
+                } else {
                 s->dsp.idct_put(ptr, linesize, *block);
                 ptr += 8 >> s->avctx->lowres;
+                }
             }
         }
     }
     return 0;
 }
 
-int ff_mjpeg_decode_sos(MJpegDecodeContext *s)
+int ff_mjpeg_decode_sos(MJpegDecodeContext *s,
+                        const uint8_t *mb_bitmask, const AVFrame *reference)
 {
     int len, nb_components, i, h, v, predictor, point_transform;
     int index, id;
@@ -991,10 +1052,12 @@ int ff_mjpeg_decode_sos(MJpegDecodeContext *s)
         }
     }else{
         if(s->progressive && predictor) {
-            if(mjpeg_decode_scan_progressive_ac(s, predictor, ilv, prev_shift, point_transform) < 0)
+            if(mjpeg_decode_scan_progressive_ac(s, predictor, ilv, prev_shift, point_transform,
+                                                mb_bitmask, reference) < 0)
                 return -1;
         } else {
-            if(mjpeg_decode_scan(s, nb_components, prev_shift, point_transform) < 0)
+            if(mjpeg_decode_scan(s, nb_components, prev_shift, point_transform,
+                                 mb_bitmask, reference) < 0)
                 return -1;
         }
     }
@@ -1026,8 +1089,8 @@ static int mjpeg_decode_app(MJpegDecodeContext *s)
     if(8*len + get_bits_count(&s->gb) > s->gb.size_in_bits)
         return -1;
 
-    id = (get_bits(&s->gb, 16) << 16) | get_bits(&s->gb, 16);
-    id = be2me_32(id);
+    id = get_bits_long(&s->gb, 32);
+    id = av_be2ne32(id);
     len -= 6;
 
     if(s->avctx->debug & FF_DEBUG_STARTCODE){
@@ -1133,8 +1196,8 @@ static int mjpeg_decode_app(MJpegDecodeContext *s)
     /* Apple MJPEG-A */
     if ((s->start_code == APP1) && (len > (0x28 - 8)))
     {
-        id = (get_bits(&s->gb, 16) << 16) | get_bits(&s->gb, 16);
-        id = be2me_32(id);
+        id = get_bits_long(&s->gb, 32);
+        id = av_be2ne32(id);
         len -= 4;
         if (id == AV_RL32("mjpg")) /* Apple MJPEG-A */
         {
@@ -1250,48 +1313,31 @@ static int find_marker(const uint8_t **pbuf_ptr, const uint8_t *buf_end)
     }
     val = -1;
 found:
-    dprintf(NULL, "find_marker skipped %d bytes\n", skipped);
+    av_dlog(NULL, "find_marker skipped %d bytes\n", skipped);
     *pbuf_ptr = buf_ptr;
     return val;
 }
 
-int ff_mjpeg_decode_frame(AVCodecContext *avctx,
-                              void *data, int *data_size,
-                              AVPacket *avpkt)
+int ff_mjpeg_find_marker(MJpegDecodeContext *s,
+                         const uint8_t **buf_ptr, const uint8_t *buf_end,
+                         const uint8_t **unescaped_buf_ptr, int *unescaped_buf_size)
 {
-    const uint8_t *buf = avpkt->data;
-    int buf_size = avpkt->size;
-    MJpegDecodeContext *s = avctx->priv_data;
-    const uint8_t *buf_end, *buf_ptr;
     int start_code;
-    AVFrame *picture = data;
-
-    s->got_picture = 0; // picture from previous image can not be reused
-    buf_ptr = buf;
-    buf_end = buf + buf_size;
-    while (buf_ptr < buf_end) {
-        /* find start next marker */
-        start_code = find_marker(&buf_ptr, buf_end);
-        {
-            /* EOF */
-            if (start_code < 0) {
-                goto the_end;
-            } else {
-                av_log(avctx, AV_LOG_DEBUG, "marker=%x avail_size_in_buf=%td\n", start_code, buf_end - buf_ptr);
+    start_code = find_marker(buf_ptr, buf_end);
 
-                if ((buf_end - buf_ptr) > s->buffer_size)
+                if ((buf_end - *buf_ptr) > s->buffer_size)
                 {
                     av_free(s->buffer);
-                    s->buffer_size = buf_end-buf_ptr;
+                    s->buffer_size = buf_end - *buf_ptr;
                     s->buffer = av_malloc(s->buffer_size + FF_INPUT_BUFFER_PADDING_SIZE);
-                    av_log(avctx, AV_LOG_DEBUG, "buffer too small, expanding to %d bytes\n",
+                    av_log(s->avctx, AV_LOG_DEBUG, "buffer too small, expanding to %d bytes\n",
                         s->buffer_size);
                 }
 
                 /* unescape buffer of SOS, use special treatment for JPEG-LS */
                 if (start_code == SOS && !s->ls)
                 {
-                    const uint8_t *src = buf_ptr;
+                    const uint8_t *src = *buf_ptr;
                     uint8_t *dst = s->buffer;
 
                     while (src<buf_end)
@@ -1299,7 +1345,7 @@ int ff_mjpeg_decode_frame(AVCodecContext *avctx,
                         uint8_t x = *(src++);
 
                         *(dst++) = x;
-                        if (avctx->codec_id != CODEC_ID_THP)
+                        if (s->avctx->codec_id != CODEC_ID_THP)
                         {
                             if (x == 0xff) {
                                 while (src < buf_end && x == 0xff)
@@ -1312,13 +1358,14 @@ int ff_mjpeg_decode_frame(AVCodecContext *avctx,
                             }
                         }
                     }
-                    init_get_bits(&s->gb, s->buffer, (dst - s->buffer)*8);
+                    *unescaped_buf_ptr  = s->buffer;
+                    *unescaped_buf_size = dst - s->buffer;
 
-                    av_log(avctx, AV_LOG_DEBUG, "escaping removed %td bytes\n",
-                           (buf_end - buf_ptr) - (dst - s->buffer));
+                    av_log(s->avctx, AV_LOG_DEBUG, "escaping removed %td bytes\n",
+                           (buf_end - *buf_ptr) - (dst - s->buffer));
                 }
                 else if(start_code == SOS && s->ls){
-                    const uint8_t *src = buf_ptr;
+                    const uint8_t *src = *buf_ptr;
                     uint8_t *dst = s->buffer;
                     int bit_count = 0;
                     int t = 0, b = 0;
@@ -1354,10 +1401,46 @@ int ff_mjpeg_decode_frame(AVCodecContext *avctx,
                     }
                     flush_put_bits(&pb);
 
-                    init_get_bits(&s->gb, dst, bit_count);
+                    *unescaped_buf_ptr  = dst;
+                    *unescaped_buf_size = (bit_count + 7) >> 3;
                 }
                 else
-                    init_get_bits(&s->gb, buf_ptr, (buf_end - buf_ptr)*8);
+                {
+                    *unescaped_buf_ptr  = *buf_ptr;
+                    *unescaped_buf_size = buf_end - *buf_ptr;
+                }
+
+    return start_code;
+}
+
+int ff_mjpeg_decode_frame(AVCodecContext *avctx,
+                              void *data, int *data_size,
+                              AVPacket *avpkt)
+{
+    const uint8_t *buf = avpkt->data;
+    int buf_size = avpkt->size;
+    MJpegDecodeContext *s = avctx->priv_data;
+    const uint8_t *buf_end, *buf_ptr;
+    const uint8_t *unescaped_buf_ptr;
+    int unescaped_buf_size;
+    int start_code;
+    AVFrame *picture = data;
+
+    s->got_picture = 0; // picture from previous image can not be reused
+    buf_ptr = buf;
+    buf_end = buf + buf_size;
+    while (buf_ptr < buf_end) {
+        /* find start next marker */
+        start_code = ff_mjpeg_find_marker(s, &buf_ptr, buf_end,
+                                          &unescaped_buf_ptr, &unescaped_buf_size);
+        {
+            /* EOF */
+            if (start_code < 0) {
+                goto the_end;
+            } else {
+                av_log(avctx, AV_LOG_DEBUG, "marker=%x avail_size_in_buf=%td\n", start_code, buf_end - buf_ptr);
+
+                init_get_bits(&s->gb, unescaped_buf_ptr, unescaped_buf_size*8);
 
                 s->start_code = start_code;
                 if(s->avctx->debug & FF_DEBUG_STARTCODE){
@@ -1440,7 +1523,7 @@ eoi_parser:
                             if (s->bottom_field == !s->interlace_polarity)
                                 goto not_the_end;
                         }
-                        *picture = s->picture;
+                        *picture = *s->picture_ptr;
                         *data_size = sizeof(AVFrame);
 
                         if(!s->lossless){
@@ -1461,7 +1544,7 @@ eoi_parser:
                         av_log(avctx, AV_LOG_WARNING, "Can not process SOS before SOF, skipping\n");
                         break;
                     }
-                    ff_mjpeg_decode_sos(s);
+                    ff_mjpeg_decode_sos(s, NULL, NULL);
                     /* buggy avid puts EOI every 10-20th frame */
                     /* if restart period is over process EOI */
                     if ((s->buggy_avid && !s->interlaced) || s->restart_interval)
@@ -1512,15 +1595,15 @@ av_cold int ff_mjpeg_decode_end(AVCodecContext *avctx)
     MJpegDecodeContext *s = avctx->priv_data;
     int i, j;
 
-    if (s->picture.data[0])
-        avctx->release_buffer(avctx, &s->picture);
+    if (s->picture_ptr && s->picture_ptr->data[0])
+        avctx->release_buffer(avctx, s->picture_ptr);
 
     av_free(s->buffer);
     av_free(s->qscale_table);
     av_freep(&s->ljpeg_buffer);
     s->ljpeg_buffer_size=0;
 
-    for(i=0;i<2;i++) {
+    for(i=0;i<3;i++) {
         for(j=0;j<4;j++)
             free_vlc(&s->vlcs[i][j]);
     }
@@ -1531,7 +1614,7 @@ av_cold int ff_mjpeg_decode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec mjpeg_decoder = {
+AVCodec ff_mjpeg_decoder = {
     "mjpeg",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_MJPEG,
@@ -1542,10 +1625,11 @@ AVCodec mjpeg_decoder = {
     ff_mjpeg_decode_frame,
     CODEC_CAP_DR1,
     NULL,
+    .max_lowres = 3,
     .long_name = NULL_IF_CONFIG_SMALL("MJPEG (Motion JPEG)"),
 };
 
-AVCodec thp_decoder = {
+AVCodec ff_thp_decoder = {
     "thp",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_THP,
@@ -1556,5 +1640,6 @@ AVCodec thp_decoder = {
     ff_mjpeg_decode_frame,
     CODEC_CAP_DR1,
     NULL,
+    .max_lowres = 3,
     .long_name = NULL_IF_CONFIG_SMALL("Nintendo Gamecube THP video"),
 };
diff --git a/libavcodec/mjpegdec.h b/libavcodec/mjpegdec.h
index bbf734b..52c256e 100644
--- a/libavcodec/mjpegdec.h
+++ b/libavcodec/mjpegdec.h
@@ -4,20 +4,20 @@
  * Copyright (c) 2003 Alex Beregszaszi
  * Copyright (c) 2003-2004 Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -44,7 +44,7 @@ typedef struct MJpegDecodeContext {
     uint8_t *buffer;
 
     int16_t quant_matrixes[4][64];
-    VLC vlcs[2][4];
+    VLC vlcs[3][4];
     int qscale[4];      ///< quantizer scale calculated from quant_matrixes
 
     int org_height;  /* size given at codec init */
@@ -81,6 +81,7 @@ typedef struct MJpegDecodeContext {
     int quant_index[4];   /* quant table index for each component */
     int last_dc[MAX_COMPONENTS]; /* last DEQUANTIZED dc (XXX: am I right to do that ?) */
     AVFrame picture; /* picture structure */
+    AVFrame *picture_ptr; /* pointer to picture structure */
     int got_picture;                                ///< we found a SOF and picture is valid, too.
     int linesize[MAX_COMPONENTS];                   ///< linesize << interlaced
     int8_t *qscale_table;
@@ -115,6 +116,10 @@ int ff_mjpeg_decode_frame(AVCodecContext *avctx,
 int ff_mjpeg_decode_dqt(MJpegDecodeContext *s);
 int ff_mjpeg_decode_dht(MJpegDecodeContext *s);
 int ff_mjpeg_decode_sof(MJpegDecodeContext *s);
-int ff_mjpeg_decode_sos(MJpegDecodeContext *s);
+int ff_mjpeg_decode_sos(MJpegDecodeContext *s,
+                        const uint8_t *mb_bitmask, const AVFrame *reference);
+int ff_mjpeg_find_marker(MJpegDecodeContext *s,
+                         const uint8_t **buf_ptr, const uint8_t *buf_end,
+                         const uint8_t **unescaped_buf_ptr, int *unescaped_buf_size);
 
 #endif /* AVCODEC_MJPEGDEC_H */
diff --git a/libavcodec/mjpegenc.c b/libavcodec/mjpegenc.c
index ec819c8..169d19e 100644
--- a/libavcodec/mjpegenc.c
+++ b/libavcodec/mjpegenc.c
@@ -8,20 +8,20 @@
  * aspecting, new decode_frame mechanism and apple mjpeg-b support
  *                                  by Alex Beregszaszi
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -441,9 +441,11 @@ void ff_mjpeg_encode_mb(MpegEncContext *s, DCTELEM block[6][64])
         encode_block(s, block[5], 5);
         encode_block(s, block[7], 7);
     }
+
+    s->i_tex_bits += get_bits_diff(s);
 }
 
-AVCodec mjpeg_encoder = {
+AVCodec ff_mjpeg_encoder = {
     "mjpeg",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_MJPEG,
diff --git a/libavcodec/mjpegenc.h b/libavcodec/mjpegenc.h
index 49627a3..12ff540 100644
--- a/libavcodec/mjpegenc.h
+++ b/libavcodec/mjpegenc.h
@@ -8,20 +8,20 @@
  * aspecting, new decode_frame mechanism and apple mjpeg-b support
  *                                  by Alex Beregszaszi
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/mlib/dsputil_mlib.c b/libavcodec/mlib/dsputil_mlib.c
index 6be0ba4..9e49c91 100644
--- a/libavcodec/mlib/dsputil_mlib.c
+++ b/libavcodec/mlib/dsputil_mlib.c
@@ -2,20 +2,20 @@
  * Sun mediaLib optimized DSP utils
  * Copyright (c) 2001 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/mlp.c b/libavcodec/mlp.c
index 87f7c77..9615b66 100644
--- a/libavcodec/mlp.c
+++ b/libavcodec/mlp.c
@@ -2,20 +2,20 @@
  * MLP codec common code
  * Copyright (c) 2007-2008 Ian Caulfield
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/mlp.h b/libavcodec/mlp.h
index 628b58d..b001ad2 100644
--- a/libavcodec/mlp.h
+++ b/libavcodec/mlp.h
@@ -2,20 +2,20 @@
  * MLP codec common header file
  * Copyright (c) 2007-2008 Ian Caulfield
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/mlp_parser.c b/libavcodec/mlp_parser.c
index 90bf939..e85eb72 100644
--- a/libavcodec/mlp_parser.c
+++ b/libavcodec/mlp_parser.c
@@ -2,20 +2,20 @@
  * MLP parser
  * Copyright (c) 2007 Ian Caulfield
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -27,6 +27,7 @@
 #include <stdint.h>
 
 #include "libavutil/crc.h"
+#include "libavutil/audioconvert.h"
 #include "get_bits.h"
 #include "parser.h"
 #include "mlp_parser.h"
@@ -42,11 +43,52 @@ static const uint8_t mlp_channels[32] = {
     5, 6, 5, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
 };
 
+static const uint64_t mlp_layout[32] = {
+    AV_CH_LAYOUT_MONO,
+    AV_CH_LAYOUT_STEREO,
+    AV_CH_LAYOUT_2_1,
+    AV_CH_LAYOUT_2_2,
+    AV_CH_LAYOUT_STEREO|AV_CH_LOW_FREQUENCY,
+    AV_CH_LAYOUT_2_1|AV_CH_LOW_FREQUENCY,
+    AV_CH_LAYOUT_2_2|AV_CH_LOW_FREQUENCY,
+    AV_CH_LAYOUT_SURROUND,
+    AV_CH_LAYOUT_4POINT0,
+    AV_CH_LAYOUT_5POINT0,
+    AV_CH_LAYOUT_SURROUND|AV_CH_LOW_FREQUENCY,
+    AV_CH_LAYOUT_4POINT0|AV_CH_LOW_FREQUENCY,
+    AV_CH_LAYOUT_5POINT1,
+    AV_CH_LAYOUT_4POINT0,
+    AV_CH_LAYOUT_5POINT0,
+    AV_CH_LAYOUT_SURROUND|AV_CH_LOW_FREQUENCY,
+    AV_CH_LAYOUT_4POINT0|AV_CH_LOW_FREQUENCY,
+    AV_CH_LAYOUT_5POINT1,
+    AV_CH_LAYOUT_2_2|AV_CH_LOW_FREQUENCY,
+    AV_CH_LAYOUT_5POINT0,
+    AV_CH_LAYOUT_5POINT1,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+};
+
 static const uint8_t thd_chancount[13] = {
 //  LR    C   LFE  LRs LRvh  LRc LRrs  Cs   Ts  LRsd  LRw  Cvh  LFE2
      2,   1,   1,   2,   2,   2,   2,   1,   1,   2,   2,   1,   1
 };
 
+static const uint64_t thd_layout[13] = {
+    AV_CH_FRONT_LEFT|AV_CH_FRONT_RIGHT,                     // LR
+    AV_CH_FRONT_CENTER,                                     // C
+    AV_CH_LOW_FREQUENCY,                                    // LFE
+    AV_CH_SIDE_LEFT|AV_CH_SIDE_RIGHT,                       // LRs
+    AV_CH_TOP_FRONT_LEFT|AV_CH_TOP_FRONT_RIGHT,             // LRvh
+    AV_CH_SIDE_LEFT|AV_CH_SIDE_RIGHT,                       // LRc
+    AV_CH_BACK_LEFT|AV_CH_BACK_RIGHT,                       // LRrs
+    AV_CH_BACK_CENTER,                                      // Cs
+    AV_CH_TOP_BACK_CENTER,                                  // Ts
+    AV_CH_SIDE_LEFT|AV_CH_SIDE_RIGHT,                       // LRsd
+    AV_CH_FRONT_LEFT_OF_CENTER|AV_CH_FRONT_RIGHT_OF_CENTER, // LRw
+    AV_CH_TOP_BACK_CENTER,                                  // Cvh
+    AV_CH_LOW_FREQUENCY                                     // LFE2
+};
+
 static int mlp_samplerate(int in)
 {
     if (in == 0xF)
@@ -65,6 +107,16 @@ static int truehd_channels(int chanmap)
     return channels;
 }
 
+static int64_t truehd_layout(int chanmap)
+{
+    int layout = 0, i;
+
+    for (i = 0; i < 13; i++)
+        layout |= thd_layout[i] * ((chanmap >> i) & 1);
+
+    return layout;
+}
+
 /** Read a major sync info header - contains high level information about
  *  the stream - sample rate, channel arrangement etc. Most of this
  *  information is not actually necessary for decoding, only for playback.
@@ -255,21 +307,25 @@ static int mlp_parse(AVCodecParserContext *s,
 
         avctx->bits_per_raw_sample = mh.group1_bits;
         if (avctx->bits_per_raw_sample > 16)
-            avctx->sample_fmt = SAMPLE_FMT_S32;
+            avctx->sample_fmt = AV_SAMPLE_FMT_S32;
         else
-            avctx->sample_fmt = SAMPLE_FMT_S16;
+            avctx->sample_fmt = AV_SAMPLE_FMT_S16;
         avctx->sample_rate = mh.group1_samplerate;
         avctx->frame_size = mh.access_unit_size;
 
         if (mh.stream_type == 0xbb) {
             /* MLP stream */
             avctx->channels = mlp_channels[mh.channels_mlp];
+            avctx->channel_layout = mlp_layout[mh.channels_mlp];
         } else { /* mh.stream_type == 0xba */
             /* TrueHD stream */
-            if (mh.channels_thd_stream2)
+            if (mh.channels_thd_stream2) {
                 avctx->channels = truehd_channels(mh.channels_thd_stream2);
-            else
+                avctx->channel_layout = truehd_layout(mh.channels_thd_stream2);
+            } else {
                 avctx->channels = truehd_channels(mh.channels_thd_stream1);
+                avctx->channel_layout = truehd_layout(mh.channels_thd_stream1);
+            }
         }
 
         if (!mh.is_vbr) /* Stream is CBR */
@@ -288,7 +344,7 @@ lost_sync:
     return 1;
 }
 
-AVCodecParser mlp_parser = {
+AVCodecParser ff_mlp_parser = {
     { CODEC_ID_MLP, CODEC_ID_TRUEHD },
     sizeof(MLPParseContext),
     mlp_init,
diff --git a/libavcodec/mlp_parser.h b/libavcodec/mlp_parser.h
index d7ce2b8..940ba83 100644
--- a/libavcodec/mlp_parser.h
+++ b/libavcodec/mlp_parser.h
@@ -2,20 +2,20 @@
  * MLP parser prototypes
  * Copyright (c) 2007 Ian Caulfield
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/mlpdec.c b/libavcodec/mlpdec.c
index 80fbbdb..5e50eba 100644
--- a/libavcodec/mlpdec.c
+++ b/libavcodec/mlpdec.c
@@ -2,20 +2,20 @@
  * MLP decoder
  * Copyright (c) 2007-2008 Ian Caulfield
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -41,7 +41,7 @@
 
 static const char* sample_message =
     "Please file a bug report following the instructions at "
-    "http://ffmpeg.org/bugreports.html and include "
+    "http://libav.org/bugreports.html and include "
     "a sample of this file.";
 
 typedef struct SubStream {
@@ -318,9 +318,9 @@ static int read_major_sync(MLPDecodeContext *m, GetBitContext *gb)
 
     m->avctx->bits_per_raw_sample = mh.group1_bits;
     if (mh.group1_bits > 16)
-        m->avctx->sample_fmt = SAMPLE_FMT_S32;
+        m->avctx->sample_fmt = AV_SAMPLE_FMT_S32;
     else
-        m->avctx->sample_fmt = SAMPLE_FMT_S16;
+        m->avctx->sample_fmt = AV_SAMPLE_FMT_S16;
 
     m->params_valid = 1;
     for (substr = 0; substr < MAX_SUBSTREAMS; substr++)
@@ -931,7 +931,7 @@ static int output_data_internal(MLPDecodeContext *m, unsigned int substr,
 static int output_data(MLPDecodeContext *m, unsigned int substr,
                        uint8_t *data, unsigned int *data_size)
 {
-    if (m->avctx->sample_fmt == SAMPLE_FMT_S32)
+    if (m->avctx->sample_fmt == AV_SAMPLE_FMT_S32)
         return output_data_internal(m, substr, data, data_size, 1);
     else
         return output_data_internal(m, substr, data, data_size, 0);
@@ -939,8 +939,8 @@ static int output_data(MLPDecodeContext *m, unsigned int substr,
 
 
 /** Read an access unit from the stream.
- *  Returns < 0 on error, 0 if not enough data is present in the input stream
- *  otherwise returns the number of bytes consumed. */
+ *  @return negative on error, 0 if not enough data is present in the input stream,
+ *  otherwise the number of bytes consumed. */
 
 static int read_access_unit(AVCodecContext *avctx, void* data, int *data_size,
                             AVPacket *avpkt)
@@ -1137,7 +1137,7 @@ error:
     return -1;
 }
 
-AVCodec mlp_decoder = {
+AVCodec ff_mlp_decoder = {
     "mlp",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_MLP,
@@ -1150,7 +1150,7 @@ AVCodec mlp_decoder = {
 };
 
 #if CONFIG_TRUEHD_DECODER
-AVCodec truehd_decoder = {
+AVCodec ff_truehd_decoder = {
     "truehd",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_TRUEHD,
diff --git a/libavcodec/mlpdsp.c b/libavcodec/mlpdsp.c
index a0647ee..0053df8 100644
--- a/libavcodec/mlpdsp.c
+++ b/libavcodec/mlpdsp.c
@@ -2,20 +2,20 @@
  * Copyright (c) 2007-2008 Ian Caulfield
  *               2009 Ramiro Polla
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/mmvideo.c b/libavcodec/mmvideo.c
index 6dbc0c4..b65335e 100644
--- a/libavcodec/mmvideo.c
+++ b/libavcodec/mmvideo.c
@@ -2,20 +2,20 @@
  * American Laser Games MM Video Decoder
  * Copyright (c) 2006,2008 Peter Ross
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -59,10 +59,6 @@ static av_cold int mm_decode_init(AVCodecContext *avctx)
     avctx->pix_fmt = PIX_FMT_PAL8;
 
     s->frame.reference = 1;
-    if (avctx->get_buffer(avctx, &s->frame)) {
-        av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
-        return -1;
-    }
 
     return 0;
 }
@@ -78,6 +74,10 @@ static void mm_decode_pal(MmContext *s, const uint8_t *buf, const uint8_t *buf_e
     }
 }
 
+/**
+ * @param half_horiz Half horizontal resolution (0 or 1)
+ * @param half_vert Half vertical resolution (0 or 1)
+ */
 static void mm_decode_intra(MmContext * s, int half_horiz, int half_vert, const uint8_t *buf, int buf_size)
 {
     int i, x, y;
@@ -86,6 +86,9 @@ static void mm_decode_intra(MmContext * s, int half_horiz, int half_vert, const
     while(i<buf_size) {
         int run_length, color;
 
+        if (y >= s->avctx->height)
+            return;
+
         if (buf[i] & 0x80) {
             run_length = 1;
             color = buf[i];
@@ -108,11 +111,15 @@ static void mm_decode_intra(MmContext * s, int half_horiz, int half_vert, const
 
         if (x >= s->avctx->width) {
             x=0;
-            y += half_vert ? 2 : 1;
+            y += 1 + half_vert;
         }
     }
 }
 
+/*
+ * @param half_horiz Half horizontal resolution (0 or 1)
+ * @param half_vert Half vertical resolution (0 or 1)
+ */
 static void mm_decode_inter(MmContext * s, int half_horiz, int half_vert, const uint8_t *buf, int buf_size)
 {
     const int data_ptr = 2 + AV_RL16(&buf[0]);
@@ -130,6 +137,9 @@ static void mm_decode_inter(MmContext * s, int half_horiz, int half_vert, const
             continue;
         }
 
+        if (y + half_vert >= s->avctx->height)
+            return;
+
         for(i=0; i<length; i++) {
             for(j=0; j<8; j++) {
                 int replace = (buf[r+i] >> (7-j)) & 1;
@@ -145,12 +155,12 @@ static void mm_decode_inter(MmContext * s, int half_horiz, int half_vert, const
                     }
                     d++;
                 }
-                x += half_horiz ? 2 : 1;
+                x += 1 + half_horiz;
             }
         }
 
         r += length;
-        y += half_vert ? 2 : 1;
+        y += 1 + half_vert;
     }
 }
 
@@ -168,6 +178,11 @@ static int mm_decode_frame(AVCodecContext *avctx,
     buf += MM_PREAMBLE_SIZE;
     buf_size -= MM_PREAMBLE_SIZE;
 
+    if (avctx->reget_buffer(avctx, &s->frame) < 0) {
+        av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
+        return -1;
+    }
+
     switch(type) {
     case MM_TYPE_PALETTE   : mm_decode_pal(s, buf, buf_end); return buf_size;
     case MM_TYPE_INTRA     : mm_decode_intra(s, 0, 0, buf, buf_size); break;
@@ -198,7 +213,7 @@ static av_cold int mm_decode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec mmvideo_decoder = {
+AVCodec ff_mmvideo_decoder = {
     "mmvideo",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_MMVIDEO,
diff --git a/libavcodec/motion-test.c b/libavcodec/motion-test.c
index 37f55a6..b88917c 100644
--- a/libavcodec/motion-test.c
+++ b/libavcodec/motion-test.c
@@ -1,20 +1,20 @@
 /*
  * (c) 2001 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -128,7 +128,7 @@ int main(int argc, char **argv)
     AVCodecContext *ctx;
     int c;
     DSPContext cctx, mmxctx;
-    int flags[2] = { FF_MM_MMX, FF_MM_MMX2 };
+    int flags[2] = { AV_CPU_FLAG_MMX, AV_CPU_FLAG_MMX2 };
     int flags_size = HAVE_MMX2 ? 2 : 1;
 
     for(;;) {
@@ -145,11 +145,11 @@ int main(int argc, char **argv)
     printf("ffmpeg motion test\n");
 
     ctx = avcodec_alloc_context();
-    ctx->dsp_mask = FF_MM_FORCE;
+    ctx->dsp_mask = AV_CPU_FLAG_FORCE;
     dsputil_init(&cctx, ctx);
     for (c = 0; c < flags_size; c++) {
         int x;
-        ctx->dsp_mask = FF_MM_FORCE | flags[c];
+        ctx->dsp_mask = AV_CPU_FLAG_FORCE | flags[c];
         dsputil_init(&mmxctx, ctx);
 
         for (x = 0; x < 2; x++) {
diff --git a/libavcodec/motion_est.c b/libavcodec/motion_est.c
index 82a36d0..8e85219 100644
--- a/libavcodec/motion_est.c
+++ b/libavcodec/motion_est.c
@@ -5,20 +5,20 @@
  *
  * new motion estimation (X1/EPZS) by Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -1476,6 +1476,7 @@ static inline int bidir_refine(MpegEncContext * s, int mb_x, int mb_y)
     const int xmax= c->xmax<<shift;
     const int ymax= c->ymax<<shift;
 #define HASH(fx,fy,bx,by) ((fx)+17*(fy)+63*(bx)+117*(by))
+#define HASH8(fx,fy,bx,by) ((uint8_t)HASH(fx,fy,bx,by))
     int hashidx= HASH(motion_fx,motion_fy, motion_bx, motion_by);
     uint8_t map[256];
 
@@ -1510,21 +1511,21 @@ static inline int bidir_refine(MpegEncContext * s, int mb_x, int mb_y)
 { 1, 1,-1,-1}, {-1,-1, 1, 1}, { 1,-1,-1, 1}, {-1, 1, 1,-1}, { 1,-1, 1,-1}, {-1, 1,-1, 1},
         };
         static const uint8_t hash[]={
-HASH( 0, 0, 0, 1), HASH( 0, 0, 0,-1), HASH( 0, 0, 1, 0), HASH( 0, 0,-1, 0), HASH( 0, 1, 0, 0), HASH( 0,-1, 0, 0), HASH( 1, 0, 0, 0), HASH(-1, 0, 0, 0),
+HASH8( 0, 0, 0, 1), HASH8( 0, 0, 0,-1), HASH8( 0, 0, 1, 0), HASH8( 0, 0,-1, 0), HASH8( 0, 1, 0, 0), HASH8( 0,-1, 0, 0), HASH8( 1, 0, 0, 0), HASH8(-1, 0, 0, 0),
 
-HASH( 0, 0, 1, 1), HASH( 0, 0,-1,-1), HASH( 0, 1, 1, 0), HASH( 0,-1,-1, 0), HASH( 1, 1, 0, 0), HASH(-1,-1, 0, 0), HASH( 1, 0, 0, 1), HASH(-1, 0, 0,-1),
-HASH( 0, 1, 0, 1), HASH( 0,-1, 0,-1), HASH( 1, 0, 1, 0), HASH(-1, 0,-1, 0),
-HASH( 0, 0,-1, 1), HASH( 0, 0, 1,-1), HASH( 0,-1, 1, 0), HASH( 0, 1,-1, 0), HASH(-1, 1, 0, 0), HASH( 1,-1, 0, 0), HASH( 1, 0, 0,-1), HASH(-1, 0, 0, 1),
-HASH( 0,-1, 0, 1), HASH( 0, 1, 0,-1), HASH(-1, 0, 1, 0), HASH( 1, 0,-1, 0),
+HASH8( 0, 0, 1, 1), HASH8( 0, 0,-1,-1), HASH8( 0, 1, 1, 0), HASH8( 0,-1,-1, 0), HASH8( 1, 1, 0, 0), HASH8(-1,-1, 0, 0), HASH8( 1, 0, 0, 1), HASH8(-1, 0, 0,-1),
+HASH8( 0, 1, 0, 1), HASH8( 0,-1, 0,-1), HASH8( 1, 0, 1, 0), HASH8(-1, 0,-1, 0),
+HASH8( 0, 0,-1, 1), HASH8( 0, 0, 1,-1), HASH8( 0,-1, 1, 0), HASH8( 0, 1,-1, 0), HASH8(-1, 1, 0, 0), HASH8( 1,-1, 0, 0), HASH8( 1, 0, 0,-1), HASH8(-1, 0, 0, 1),
+HASH8( 0,-1, 0, 1), HASH8( 0, 1, 0,-1), HASH8(-1, 0, 1, 0), HASH8( 1, 0,-1, 0),
 
-HASH( 0, 1, 1, 1), HASH( 0,-1,-1,-1), HASH( 1, 1, 1, 0), HASH(-1,-1,-1, 0), HASH( 1, 1, 0, 1), HASH(-1,-1, 0,-1), HASH( 1, 0, 1, 1), HASH(-1, 0,-1,-1),
-HASH( 0,-1, 1, 1), HASH( 0, 1,-1,-1), HASH(-1, 1, 1, 0), HASH( 1,-1,-1, 0), HASH( 1, 1, 0,-1), HASH(-1,-1, 0, 1), HASH( 1, 0,-1, 1), HASH(-1, 0, 1,-1),
-HASH( 0, 1,-1, 1), HASH( 0,-1, 1,-1), HASH( 1,-1, 1, 0), HASH(-1, 1,-1, 0), HASH(-1, 1, 0, 1), HASH( 1,-1, 0,-1), HASH( 1, 0, 1,-1), HASH(-1, 0,-1, 1),
-HASH( 0, 1, 1,-1), HASH( 0,-1,-1, 1), HASH( 1, 1,-1, 0), HASH(-1,-1, 1, 0), HASH( 1,-1, 0, 1), HASH(-1, 1, 0,-1), HASH(-1, 0, 1, 1), HASH( 1, 0,-1,-1),
+HASH8( 0, 1, 1, 1), HASH8( 0,-1,-1,-1), HASH8( 1, 1, 1, 0), HASH8(-1,-1,-1, 0), HASH8( 1, 1, 0, 1), HASH8(-1,-1, 0,-1), HASH8( 1, 0, 1, 1), HASH8(-1, 0,-1,-1),
+HASH8( 0,-1, 1, 1), HASH8( 0, 1,-1,-1), HASH8(-1, 1, 1, 0), HASH8( 1,-1,-1, 0), HASH8( 1, 1, 0,-1), HASH8(-1,-1, 0, 1), HASH8( 1, 0,-1, 1), HASH8(-1, 0, 1,-1),
+HASH8( 0, 1,-1, 1), HASH8( 0,-1, 1,-1), HASH8( 1,-1, 1, 0), HASH8(-1, 1,-1, 0), HASH8(-1, 1, 0, 1), HASH8( 1,-1, 0,-1), HASH8( 1, 0, 1,-1), HASH8(-1, 0,-1, 1),
+HASH8( 0, 1, 1,-1), HASH8( 0,-1,-1, 1), HASH8( 1, 1,-1, 0), HASH8(-1,-1, 1, 0), HASH8( 1,-1, 0, 1), HASH8(-1, 1, 0,-1), HASH8(-1, 0, 1, 1), HASH8( 1, 0,-1,-1),
 
-HASH( 1, 1, 1, 1), HASH(-1,-1,-1,-1),
-HASH( 1, 1, 1,-1), HASH(-1,-1,-1, 1), HASH( 1, 1,-1, 1), HASH(-1,-1, 1,-1), HASH( 1,-1, 1, 1), HASH(-1, 1,-1,-1), HASH(-1, 1, 1, 1), HASH( 1,-1,-1,-1),
-HASH( 1, 1,-1,-1), HASH(-1,-1, 1, 1), HASH( 1,-1,-1, 1), HASH(-1, 1, 1,-1), HASH( 1,-1, 1,-1), HASH(-1, 1,-1, 1),
+HASH8( 1, 1, 1, 1), HASH8(-1,-1,-1,-1),
+HASH8( 1, 1, 1,-1), HASH8(-1,-1,-1, 1), HASH8( 1, 1,-1, 1), HASH8(-1,-1, 1,-1), HASH8( 1,-1, 1, 1), HASH8(-1, 1,-1,-1), HASH8(-1, 1, 1, 1), HASH8( 1,-1,-1,-1),
+HASH8( 1, 1,-1,-1), HASH8(-1,-1, 1, 1), HASH8( 1,-1,-1, 1), HASH8(-1, 1, 1,-1), HASH8( 1,-1, 1,-1), HASH8(-1, 1,-1, 1),
 };
 
 #define CHECK_BIDIR(fx,fy,bx,by)\
diff --git a/libavcodec/motion_est_template.c b/libavcodec/motion_est_template.c
index 8f730ef..faf03d2 100644
--- a/libavcodec/motion_est_template.c
+++ b/libavcodec/motion_est_template.c
@@ -2,20 +2,20 @@
  * Motion estimation
  * Copyright (c) 2002-2004 Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/motionpixels.c b/libavcodec/motionpixels.c
index 9bc5e20..ebc4b31 100644
--- a/libavcodec/motionpixels.c
+++ b/libavcodec/motionpixels.c
@@ -2,20 +2,20 @@
  * Motion Pixels Video Decoder
  * Copyright (c) 2008 Gregory Montoir (cyx at users.sourceforge.net)
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -302,7 +302,7 @@ static av_cold int mp_decode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec motionpixels_decoder = {
+AVCodec ff_motionpixels_decoder = {
     "motionpixels",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_MOTIONPIXELS,
diff --git a/libavcodec/motionpixels_tablegen.c b/libavcodec/motionpixels_tablegen.c
index 5f1220a..ad8e0d9 100644
--- a/libavcodec/motionpixels_tablegen.c
+++ b/libavcodec/motionpixels_tablegen.c
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2009 Reimar Döffinger <Reimar.Doeffinger at gmx.de>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -34,7 +34,7 @@ int main(void)
     write_fileheader();
 
     printf("static const YuvPixel mp_rgb_yuv_table[1 << 15] = {\n");
-    write_int8_2d_array(mp_rgb_yuv_table, 1 << 15, 3);
+    write_int8_t_2d_array(mp_rgb_yuv_table, 1 << 15, 3);
     printf("};\n");
 
     return 0;
diff --git a/libavcodec/motionpixels_tablegen.h b/libavcodec/motionpixels_tablegen.h
index 5d6df52..9516dfe 100644
--- a/libavcodec/motionpixels_tablegen.h
+++ b/libavcodec/motionpixels_tablegen.h
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2009 Reimar Döffinger <Reimar.Doeffinger at gmx.de>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/movsub_bsf.c b/libavcodec/movsub_bsf.c
index 2423f2d..423ebeb 100644
--- a/libavcodec/movsub_bsf.c
+++ b/libavcodec/movsub_bsf.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2008 Reimar Döffinger
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -33,7 +33,7 @@ static int text2movsub(AVBitStreamFilterContext *bsfc, AVCodecContext *avctx, co
     return 1;
 }
 
-AVBitStreamFilter text2movsub_bsf={
+AVBitStreamFilter ff_text2movsub_bsf={
     "text2movsub",
     0,
     text2movsub,
@@ -49,7 +49,7 @@ static int mov2textsub(AVBitStreamFilterContext *bsfc, AVCodecContext *avctx, co
     return 1;
 }
 
-AVBitStreamFilter mov2textsub_bsf={
+AVBitStreamFilter ff_mov2textsub_bsf={
     "mov2textsub",
     0,
     mov2textsub,
diff --git a/libavcodec/mp3_header_compress_bsf.c b/libavcodec/mp3_header_compress_bsf.c
index f5c5138..5a69377 100644
--- a/libavcodec/mp3_header_compress_bsf.c
+++ b/libavcodec/mp3_header_compress_bsf.c
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -79,7 +79,7 @@ output_unchanged:
     return 1;
 }
 
-AVBitStreamFilter mp3_header_compress_bsf={
+AVBitStreamFilter ff_mp3_header_compress_bsf={
     "mp3comp",
     0,
     mp3_header_compress,
diff --git a/libavcodec/mp3_header_decompress_bsf.c b/libavcodec/mp3_header_decompress_bsf.c
index d897ed9..7dda795 100644
--- a/libavcodec/mp3_header_decompress_bsf.c
+++ b/libavcodec/mp3_header_decompress_bsf.c
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -89,7 +89,7 @@ static int mp3_header_decompress(AVBitStreamFilterContext *bsfc, AVCodecContext
     return 1;
 }
 
-AVBitStreamFilter mp3_header_decompress_bsf={
+AVBitStreamFilter ff_mp3_header_decompress_bsf={
     "mp3decomp",
     0,
     mp3_header_decompress,
diff --git a/libavcodec/mpc.c b/libavcodec/mpc.c
index 30ae591..36e0f04 100644
--- a/libavcodec/mpc.c
+++ b/libavcodec/mpc.c
@@ -2,20 +2,20 @@
  * Musepack decoder core
  * Copyright (c) 2006 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -42,27 +42,27 @@ void ff_mpc_init(void)
 /**
  * Process decoded Musepack data and produce PCM
  */
-static void mpc_synth(MPCContext *c, int16_t *out)
+static void mpc_synth(MPCContext *c, int16_t *out, int channels)
 {
     int dither_state = 0;
     int i, ch;
     OUT_INT samples[MPA_MAX_CHANNELS * MPA_FRAME_SIZE], *samples_ptr;
 
-    for(ch = 0;  ch < 2; ch++){
+    for(ch = 0;  ch < channels; ch++){
         samples_ptr = samples + ch;
         for(i = 0; i < SAMPLES_PER_BAND; i++) {
             ff_mpa_synth_filter(c->synth_buf[ch], &(c->synth_buf_offset[ch]),
                                 ff_mpa_synth_window, &dither_state,
-                                samples_ptr, 2,
+                                samples_ptr, channels,
                                 c->sb_samples[ch][i]);
-            samples_ptr += 64;
+            samples_ptr += 32 * channels;
         }
     }
-    for(i = 0; i < MPC_FRAME_SIZE*2; i++)
+    for(i = 0; i < MPC_FRAME_SIZE*channels; i++)
         *out++=samples[i];
 }
 
-void ff_mpc_dequantize_and_synth(MPCContext * c, int maxband, void *data)
+void ff_mpc_dequantize_and_synth(MPCContext * c, int maxband, void *data, int channels)
 {
     int i, j, ch;
     Band *bands = c->bands;
@@ -98,5 +98,5 @@ void ff_mpc_dequantize_and_synth(MPCContext * c, int maxband, void *data)
         }
     }
 
-    mpc_synth(c, data);
+    mpc_synth(c, data, channels);
 }
diff --git a/libavcodec/mpc.h b/libavcodec/mpc.h
index 25d1d2c..67fc7fe 100644
--- a/libavcodec/mpc.h
+++ b/libavcodec/mpc.h
@@ -2,20 +2,20 @@
  * Musepack decoder
  * Copyright (c) 2006 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -72,6 +72,6 @@ typedef struct {
 } MPCContext;
 
 void ff_mpc_init(void);
-void ff_mpc_dequantize_and_synth(MPCContext *c, int maxband, void *dst);
+void ff_mpc_dequantize_and_synth(MPCContext *c, int maxband, void *dst, int channels);
 
 #endif /* AVCODEC_MPC_H */
diff --git a/libavcodec/mpc7.c b/libavcodec/mpc7.c
index 42de27e..6a4bf57 100644
--- a/libavcodec/mpc7.c
+++ b/libavcodec/mpc7.c
@@ -2,20 +2,20 @@
  * Musepack SV7 decoder
  * Copyright (c) 2006 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -30,6 +30,7 @@
 #include "get_bits.h"
 #include "dsputil.h"
 #include "mpegaudio.h"
+#include "libavutil/audioconvert.h"
 
 #include "mpc.h"
 #include "mpc7data.h"
@@ -85,8 +86,8 @@ static av_cold int mpc7_decode_init(AVCodecContext * avctx)
             c->IS, c->MSS, c->gapless, c->lastframelen, c->maxbands);
     c->frames_to_skip = 0;
 
-    avctx->sample_fmt = SAMPLE_FMT_S16;
-    avctx->channel_layout = (avctx->channels==2) ? CH_LAYOUT_STEREO : CH_LAYOUT_MONO;
+    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
+    avctx->channel_layout = (avctx->channels==2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;
 
     if(vlc_initialized) return 0;
     av_log(avctx, AV_LOG_DEBUG, "Initing VLC\n");
@@ -206,7 +207,7 @@ static int mpc7_decode_frame(AVCodecContext * avctx,
     bits = av_malloc(((buf_size - 1) & ~3) + FF_INPUT_BUFFER_PADDING_SIZE);
     c->dsp.bswap_buf((uint32_t*)bits, (const uint32_t*)(buf + 4), (buf_size - 4) >> 2);
     init_get_bits(&gb, bits, (buf_size - 4)* 8);
-    skip_bits(&gb, buf[0]);
+    skip_bits_long(&gb, buf[0]);
 
     /* read subband indexes */
     for(i = 0; i <= c->maxbands; i++){
@@ -260,7 +261,7 @@ static int mpc7_decode_frame(AVCodecContext * avctx,
         for(ch = 0; ch < 2; ch++)
             idx_to_quant(c, &gb, bands[i].res[ch], c->Q[ch] + off);
 
-    ff_mpc_dequantize_and_synth(c, mb, data);
+    ff_mpc_dequantize_and_synth(c, mb, data, 2);
 
     av_free(bits);
 
@@ -288,7 +289,7 @@ static void mpc7_decode_flush(AVCodecContext *avctx)
     c->frames_to_skip = 32;
 }
 
-AVCodec mpc7_decoder = {
+AVCodec ff_mpc7_decoder = {
     "mpc7",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_MUSEPACK7,
diff --git a/libavcodec/mpc7data.h b/libavcodec/mpc7data.h
index 5609e8f..f205ffe 100644
--- a/libavcodec/mpc7data.h
+++ b/libavcodec/mpc7data.h
@@ -2,20 +2,20 @@
  * Musepack decoder
  * Copyright (c) 2006 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/mpc8.c b/libavcodec/mpc8.c
index 3762746..5de8c15 100644
--- a/libavcodec/mpc8.c
+++ b/libavcodec/mpc8.c
@@ -2,20 +2,20 @@
  * Musepack SV8 decoder
  * Copyright (c) 2007 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -30,6 +30,7 @@
 #include "get_bits.h"
 #include "dsputil.h"
 #include "mpegaudio.h"
+#include "libavutil/audioconvert.h"
 
 #include "mpc.h"
 #include "mpcdata.h"
@@ -99,6 +100,7 @@ static av_cold int mpc8_decode_init(AVCodecContext * avctx)
     MPCContext *c = avctx->priv_data;
     GetBitContext gb;
     static int vlc_initialized = 0;
+    int channels;
 
     static VLC_TYPE band_table[542][2];
     static VLC_TYPE q1_table[520][2];
@@ -125,12 +127,16 @@ static av_cold int mpc8_decode_init(AVCodecContext * avctx)
 
     skip_bits(&gb, 3);//sample rate
     c->maxbands = get_bits(&gb, 5) + 1;
-    skip_bits(&gb, 4);//channels
+    channels = get_bits(&gb, 4) + 1;
+    if (channels > 2) {
+        av_log_missing_feature(avctx, "Multichannel MPC SV8", 1);
+        return -1;
+    }
     c->MSS = get_bits1(&gb);
     c->frames = 1 << (get_bits(&gb, 3) * 2);
 
-    avctx->sample_fmt = SAMPLE_FMT_S16;
-    avctx->channel_layout = (avctx->channels==2) ? CH_LAYOUT_STEREO : CH_LAYOUT_MONO;
+    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
+    avctx->channel_layout = (avctx->channels==2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;
 
     if(vlc_initialized) return 0;
     av_log(avctx, AV_LOG_DEBUG, "Initing VLC\n");
@@ -387,19 +393,19 @@ static int mpc8_decode_frame(AVCodecContext * avctx,
         }
     }
 
-    ff_mpc_dequantize_and_synth(c, maxband, data);
+    ff_mpc_dequantize_and_synth(c, maxband, data, avctx->channels);
 
     c->cur_frame++;
 
     c->last_bits_used = get_bits_count(gb);
     if(c->cur_frame >= c->frames)
         c->cur_frame = 0;
-    *data_size =  MPC_FRAME_SIZE * 4;
+    *data_size =  MPC_FRAME_SIZE * 2 * avctx->channels;
 
     return c->cur_frame ? c->last_bits_used >> 3 : buf_size;
 }
 
-AVCodec mpc8_decoder = {
+AVCodec ff_mpc8_decoder = {
     "mpc8",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_MUSEPACK8,
diff --git a/libavcodec/mpc8data.h b/libavcodec/mpc8data.h
index 22c2be4..2940b30 100644
--- a/libavcodec/mpc8data.h
+++ b/libavcodec/mpc8data.h
@@ -2,20 +2,20 @@
  * Musepack SV8 decoder
  * Copyright (c) 2007 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/mpc8huff.h b/libavcodec/mpc8huff.h
index 8491037..6005e21 100644
--- a/libavcodec/mpc8huff.h
+++ b/libavcodec/mpc8huff.h
@@ -2,20 +2,20 @@
  * Musepack SV8 decoder
  * Copyright (c) 2007 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/mpcdata.h b/libavcodec/mpcdata.h
index a2212ec..ad06b7a 100644
--- a/libavcodec/mpcdata.h
+++ b/libavcodec/mpcdata.h
@@ -2,20 +2,20 @@
  * Musepack decoder
  * Copyright (c) 2006 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/mpeg12.c b/libavcodec/mpeg12.c
index bc9ddcc..3e9f74a 100644
--- a/libavcodec/mpeg12.c
+++ b/libavcodec/mpeg12.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2000,2001 Fabrice Bellard
  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -137,6 +137,9 @@ void ff_mpeg1_clean_buffers(MpegEncContext *s){
 /******************************************/
 /* decoding */
 
+VLC ff_dc_lum_vlc;
+VLC ff_dc_chroma_vlc;
+
 static VLC mv_vlc;
 static VLC mbincr_vlc;
 static VLC mb_ptype_vlc;
@@ -150,10 +153,10 @@ av_cold void ff_mpeg12_init_vlcs(void)
     if (!done) {
         done = 1;
 
-        INIT_VLC_STATIC(&dc_lum_vlc, DC_VLC_BITS, 12,
+        INIT_VLC_STATIC(&ff_dc_lum_vlc, DC_VLC_BITS, 12,
                  ff_mpeg12_vlc_dc_lum_bits, 1, 1,
                  ff_mpeg12_vlc_dc_lum_code, 2, 2, 512);
-        INIT_VLC_STATIC(&dc_chroma_vlc,  DC_VLC_BITS, 12,
+        INIT_VLC_STATIC(&ff_dc_chroma_vlc,  DC_VLC_BITS, 12,
                  ff_mpeg12_vlc_dc_chroma_bits, 1, 1,
                  ff_mpeg12_vlc_dc_chroma_code, 2, 2, 514);
         INIT_VLC_STATIC(&mv_vlc, MV_VLC_BITS, 17,
@@ -210,7 +213,7 @@ static int mpeg_decode_mb(MpegEncContext *s,
     int i, j, k, cbp, val, mb_type, motion_type;
     const int mb_block_count = 4 + (1<< s->chroma_format);
 
-    dprintf(s->avctx, "decode_mb: x=%d y=%d\n", s->mb_x, s->mb_y);
+    av_dlog(s->avctx, "decode_mb: x=%d y=%d\n", s->mb_x, s->mb_y);
 
     assert(s->mb_skipped==0);
 
@@ -269,7 +272,7 @@ static int mpeg_decode_mb(MpegEncContext *s,
         mb_type = btype2mb_type[ mb_type ];
         break;
     }
-    dprintf(s->avctx, "mb_type=%x\n", mb_type);
+    av_dlog(s->avctx, "mb_type=%x\n", mb_type);
 //    motion_type = 0; /* avoid warning */
     if (IS_INTRA(mb_type)) {
         s->dsp.clear_blocks(s->block[0]);
@@ -367,7 +370,7 @@ static int mpeg_decode_mb(MpegEncContext *s,
 
             /* motion vectors */
             s->mv_dir= (mb_type>>13)&3;
-            dprintf(s->avctx, "motion_type=%d\n", motion_type);
+            av_dlog(s->avctx, "motion_type=%d\n", motion_type);
             switch(motion_type) {
             case MT_FRAME: /* or MT_16X8 */
                 if (s->picture_structure == PICT_FRAME) {
@@ -418,12 +421,12 @@ static int mpeg_decode_mb(MpegEncContext *s,
                                                          s->last_mv[i][j][0]);
                                 s->last_mv[i][j][0] = val;
                                 s->mv[i][j][0] = val;
-                                dprintf(s->avctx, "fmx=%d\n", val);
+                                av_dlog(s->avctx, "fmx=%d\n", val);
                                 val = mpeg_decode_motion(s, s->mpeg_f_code[i][1],
                                                          s->last_mv[i][j][1] >> 1);
                                 s->last_mv[i][j][1] = val << 1;
                                 s->mv[i][j][1] = val;
-                                dprintf(s->avctx, "fmy=%d\n", val);
+                                av_dlog(s->avctx, "fmy=%d\n", val);
                             }
                         }
                     }
@@ -629,7 +632,7 @@ static inline int mpeg1_decode_block_intra(MpegEncContext *s,
     dc += diff;
     s->last_dc[component] = dc;
     block[0] = dc*quant_matrix[0];
-    dprintf(s->avctx, "dc=%d diff=%d\n", dc, diff);
+    av_dlog(s->avctx, "dc=%d diff=%d\n", dc, diff);
     i = 0;
     {
         OPEN_READER(re, &s->gb);
@@ -715,9 +718,6 @@ static inline int mpeg1_decode_block_inter(MpegEncContext *s,
             if(((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)
                 goto end;
         }
-#if MIN_CACHE_BITS < 19
-        UPDATE_CACHE(re, &s->gb);
-#endif
         /* now quantify & encode AC coefficients */
         for(;;) {
             GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2, 0);
@@ -757,14 +757,9 @@ static inline int mpeg1_decode_block_inter(MpegEncContext *s,
             }
 
             block[j] = level;
-#if MIN_CACHE_BITS < 19
-            UPDATE_CACHE(re, &s->gb);
-#endif
             if(((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)
                 break;
-#if MIN_CACHE_BITS >= 19
             UPDATE_CACHE(re, &s->gb);
-#endif
         }
 end:
         LAST_SKIP_BITS(re, &s->gb, 2);
@@ -797,9 +792,6 @@ static inline int mpeg1_fast_decode_block_inter(MpegEncContext *s, DCTELEM *bloc
             if(((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)
                 goto end;
         }
-#if MIN_CACHE_BITS < 19
-        UPDATE_CACHE(re, &s->gb);
-#endif
 
         /* now quantify & encode AC coefficients */
         for(;;) {
@@ -836,14 +828,9 @@ static inline int mpeg1_fast_decode_block_inter(MpegEncContext *s, DCTELEM *bloc
             }
 
             block[j] = level;
-#if MIN_CACHE_BITS < 19
-            UPDATE_CACHE(re, &s->gb);
-#endif
             if(((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)
                 break;
-#if MIN_CACHE_BITS >= 19
             UPDATE_CACHE(re, &s->gb);
-#endif
         }
 end:
         LAST_SKIP_BITS(re, &s->gb, 2);
@@ -888,9 +875,6 @@ static inline int mpeg2_decode_block_non_intra(MpegEncContext *s,
             if(((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)
                 goto end;
         }
-#if MIN_CACHE_BITS < 19
-        UPDATE_CACHE(re, &s->gb);
-#endif
 
         /* now quantify & encode AC coefficients */
         for(;;) {
@@ -924,14 +908,9 @@ static inline int mpeg2_decode_block_non_intra(MpegEncContext *s,
 
             mismatch ^= level;
             block[j] = level;
-#if MIN_CACHE_BITS < 19
-            UPDATE_CACHE(re, &s->gb);
-#endif
             if(((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)
                 break;
-#if MIN_CACHE_BITS >= 19
             UPDATE_CACHE(re, &s->gb);
-#endif
         }
 end:
         LAST_SKIP_BITS(re, &s->gb, 2);
@@ -966,9 +945,6 @@ static inline int mpeg2_fast_decode_block_non_intra(MpegEncContext *s,
         if(((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)
             goto end;
     }
-#if MIN_CACHE_BITS < 19
-    UPDATE_CACHE(re, &s->gb);
-#endif
 
     /* now quantify & encode AC coefficients */
     for(;;) {
@@ -997,14 +973,9 @@ static inline int mpeg2_fast_decode_block_non_intra(MpegEncContext *s,
         }
 
         block[j] = level;
-#if MIN_CACHE_BITS < 19
-        UPDATE_CACHE(re, &s->gb);
-#endif
         if(((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)
             break;
-#if MIN_CACHE_BITS >=19
         UPDATE_CACHE(re, &s->gb);
-#endif
     }
 end:
     LAST_SKIP_BITS(re, &s->gb, 2);
@@ -1041,7 +1012,7 @@ static inline int mpeg2_decode_block_intra(MpegEncContext *s,
     dc += diff;
     s->last_dc[component] = dc;
     block[0] = dc << (3 - s->intra_dc_precision);
-    dprintf(s->avctx, "dc=%d\n", block[0]);
+    av_dlog(s->avctx, "dc=%d\n", block[0]);
     mismatch = block[0] ^ 1;
     i = 0;
     if (s->intra_vlc_format)
@@ -1168,7 +1139,7 @@ typedef struct Mpeg1Context {
     MpegEncContext mpeg_enc_ctx;
     int mpeg_enc_ctx_allocated; /* true if decoding context allocated */
     int repeat_field; /* true if we must repeat the field */
-    AVPanScan pan_scan; /** some temporary storage for the panscan */
+    AVPanScan pan_scan;              /**< some temporary storage for the panscan */
     int slice_count;
     int swap_uv;//indicate VCR2
     int save_aspect_info;
@@ -1415,7 +1386,7 @@ static void mpeg_decode_sequence_extension(Mpeg1Context *s1)
     s1->frame_rate_ext.num = get_bits(&s->gb, 2)+1;
     s1->frame_rate_ext.den = get_bits(&s->gb, 5)+1;
 
-    dprintf(s->avctx, "sequence extension\n");
+    av_dlog(s->avctx, "sequence extension\n");
     s->codec_id= s->avctx->codec_id= CODEC_ID_MPEG2VIDEO;
     s->avctx->sub_id = 2; /* indicates MPEG-2 found */
 
@@ -1440,7 +1411,7 @@ static void mpeg_decode_sequence_display_extension(Mpeg1Context *s1)
     w= get_bits(&s->gb, 14);
     skip_bits(&s->gb, 1); //marker
     h= get_bits(&s->gb, 14);
-    skip_bits(&s->gb, 1); //marker
+    // remaining 3 bits are zero padding
 
     s1->pan_scan.width= 16*w;
     s1->pan_scan.height=16*h;
@@ -1506,7 +1477,7 @@ static int load_matrix(MpegEncContext *s, uint16_t matrix0[64], uint16_t matrix1
 
 static void mpeg_decode_quant_matrix_extension(MpegEncContext *s)
 {
-    dprintf(s->avctx, "matrix extension\n");
+    av_dlog(s->avctx, "matrix extension\n");
 
     if(get_bits1(&s->gb)) load_matrix(s, s->chroma_intra_matrix, s->intra_matrix, 1);
     if(get_bits1(&s->gb)) load_matrix(s, s->chroma_inter_matrix, s->inter_matrix, 0);
@@ -1580,15 +1551,15 @@ static void mpeg_decode_picture_coding_extension(Mpeg1Context *s1)
     }
 
     /* composite display not parsed */
-    dprintf(s->avctx, "intra_dc_precision=%d\n", s->intra_dc_precision);
-    dprintf(s->avctx, "picture_structure=%d\n", s->picture_structure);
-    dprintf(s->avctx, "top field first=%d\n", s->top_field_first);
-    dprintf(s->avctx, "repeat first field=%d\n", s->repeat_first_field);
-    dprintf(s->avctx, "conceal=%d\n", s->concealment_motion_vectors);
-    dprintf(s->avctx, "intra_vlc_format=%d\n", s->intra_vlc_format);
-    dprintf(s->avctx, "alternate_scan=%d\n", s->alternate_scan);
-    dprintf(s->avctx, "frame_pred_frame_dct=%d\n", s->frame_pred_frame_dct);
-    dprintf(s->avctx, "progressive_frame=%d\n", s->progressive_frame);
+    av_dlog(s->avctx, "intra_dc_precision=%d\n", s->intra_dc_precision);
+    av_dlog(s->avctx, "picture_structure=%d\n", s->picture_structure);
+    av_dlog(s->avctx, "top field first=%d\n", s->top_field_first);
+    av_dlog(s->avctx, "repeat first field=%d\n", s->repeat_first_field);
+    av_dlog(s->avctx, "conceal=%d\n", s->concealment_motion_vectors);
+    av_dlog(s->avctx, "intra_vlc_format=%d\n", s->intra_vlc_format);
+    av_dlog(s->avctx, "alternate_scan=%d\n", s->alternate_scan);
+    av_dlog(s->avctx, "frame_pred_frame_dct=%d\n", s->frame_pred_frame_dct);
+    av_dlog(s->avctx, "progressive_frame=%d\n", s->progressive_frame);
 }
 
 static void exchange_uv(MpegEncContext *s){
@@ -1911,7 +1882,9 @@ static int slice_decode_thread(AVCodecContext *c, void *arg){
 
         start_code= -1;
         buf = ff_find_start_code(buf, s->gb.buffer_end, &start_code);
-        mb_y= start_code - SLICE_MIN_START_CODE;
+        mb_y= (start_code - SLICE_MIN_START_CODE) << field_pic;
+        if (s->picture_structure == PICT_BOTTOM_FIELD)
+            mb_y++;
         if(mb_y < 0 || mb_y >= s->end_mb_y)
             return -1;
     }
@@ -1920,7 +1893,7 @@ static int slice_decode_thread(AVCodecContext *c, void *arg){
 }
 
 /**
- * Handles slice ends.
+ * Handle slice ends.
  * @return 1 if it seems to be the last slice
  */
 static int slice_end(AVCodecContext *avctx, AVFrame *pict)
@@ -2155,7 +2128,7 @@ static void mpeg_decode_gop(AVCodecContext *avctx,
             time_code_pictures, s->closed_gop, broken_link);
 }
 /**
- * Finds the end of the current frame in the bitstream.
+ * Find the end of the current frame in the bitstream.
  * @return the position of the first byte of the next frame, or -1
  */
 int ff_mpeg1_find_frame_end(ParseContext *pc, const uint8_t *buf, int buf_size, AVCodecParserContext *s)
@@ -2229,7 +2202,7 @@ static int mpeg_decode_frame(AVCodecContext *avctx,
     Mpeg1Context *s = avctx->priv_data;
     AVFrame *picture = data;
     MpegEncContext *s2 = &s->mpeg_enc_ctx;
-    dprintf(avctx, "fill_buffer\n");
+    av_dlog(avctx, "fill_buffer\n");
 
     if (buf_size == 0 || (buf_size == 4 && AV_RB32(buf) == SEQ_END_CODE)) {
         /* special case for last picture */
@@ -2328,6 +2301,16 @@ static int decode_chunks(AVCodecContext *avctx,
             break;
 
         case PICTURE_START_CODE:
+            if (HAVE_THREADS && (avctx->active_thread_type&FF_THREAD_SLICE) && s->slice_count) {
+                int i;
+
+                avctx->execute(avctx, slice_decode_thread,
+                               s2->thread_context, NULL,
+                               s->slice_count, sizeof(void*));
+                for (i = 0; i < s->slice_count; i++)
+                    s2->error_count += s2->thread_context[i]->error_count;
+                s->slice_count = 0;
+            }
             if(last_code == 0 || last_code == SLICE_MIN_START_CODE){
             if(mpeg_decode_postinit(avctx) < 0){
                 av_log(avctx, AV_LOG_ERROR, "mpeg_decode_postinit() failure\n");
@@ -2415,14 +2398,18 @@ static int decode_chunks(AVCodecContext *avctx,
                 /* Skip P-frames if we do not have a reference frame or we have an invalid header. */
                     if(s2->pict_type==FF_P_TYPE && !s->sync) break;
                 }
+#if FF_API_HURRY_UP
                 /* Skip B-frames if we are in a hurry. */
                 if(avctx->hurry_up && s2->pict_type==FF_B_TYPE) break;
+#endif
                 if(  (avctx->skip_frame >= AVDISCARD_NONREF && s2->pict_type==FF_B_TYPE)
                     ||(avctx->skip_frame >= AVDISCARD_NONKEY && s2->pict_type!=FF_I_TYPE)
                     || avctx->skip_frame >= AVDISCARD_ALL)
                     break;
+#if FF_API_HURRY_UP
                 /* Skip everything if we are in a hurry>=5. */
                 if(avctx->hurry_up>=5) break;
+#endif
 
                 if (!s->mpeg_enc_ctx_allocated) break;
 
@@ -2500,7 +2487,19 @@ static int mpeg_decode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec mpeg1video_decoder = {
+static const AVProfile mpeg2_video_profiles[] = {
+    { FF_PROFILE_MPEG2_422,          "4:2:2"              },
+    { FF_PROFILE_MPEG2_HIGH,         "High"               },
+    { FF_PROFILE_MPEG2_SS,           "Spatially Scalable" },
+    { FF_PROFILE_MPEG2_SNR_SCALABLE, "SNR Scalable"       },
+    { FF_PROFILE_MPEG2_MAIN,         "Main"               },
+    { FF_PROFILE_MPEG2_SIMPLE,       "Simple"             },
+    { FF_PROFILE_RESERVED,           "Reserved"           },
+    { FF_PROFILE_RESERVED,           "Reserved"           },
+};
+
+
+AVCodec ff_mpeg1video_decoder = {
     "mpeg1video",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_MPEG1VIDEO,
@@ -2511,10 +2510,11 @@ AVCodec mpeg1video_decoder = {
     mpeg_decode_frame,
     CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY,
     .flush= flush,
+    .max_lowres= 3,
     .long_name= NULL_IF_CONFIG_SMALL("MPEG-1 video"),
 };
 
-AVCodec mpeg2video_decoder = {
+AVCodec ff_mpeg2video_decoder = {
     "mpeg2video",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_MPEG2VIDEO,
@@ -2525,11 +2525,13 @@ AVCodec mpeg2video_decoder = {
     mpeg_decode_frame,
     CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY,
     .flush= flush,
+    .max_lowres= 3,
     .long_name= NULL_IF_CONFIG_SMALL("MPEG-2 video"),
+    .profiles = NULL_IF_CONFIG_SMALL(mpeg2_video_profiles),
 };
 
 //legacy decoder
-AVCodec mpegvideo_decoder = {
+AVCodec ff_mpegvideo_decoder = {
     "mpegvideo",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_MPEG2VIDEO,
@@ -2540,6 +2542,7 @@ AVCodec mpegvideo_decoder = {
     mpeg_decode_frame,
     CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY,
     .flush= flush,
+    .max_lowres= 3,
     .long_name= NULL_IF_CONFIG_SMALL("MPEG-1 video"),
 };
 
@@ -2550,7 +2553,7 @@ static av_cold int mpeg_mc_decode_init(AVCodecContext *avctx){
     if( !(avctx->slice_flags & SLICE_FLAG_CODED_ORDER) )
         return -1;
     if( !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD) ){
-        dprintf(avctx, "mpeg12.c: XvMC decoder will work better if SLICE_FLAG_ALLOW_FIELD is set\n");
+        av_dlog(avctx, "mpeg12.c: XvMC decoder will work better if SLICE_FLAG_ALLOW_FIELD is set\n");
     }
     mpeg_decode_init(avctx);
 
@@ -2560,7 +2563,7 @@ static av_cold int mpeg_mc_decode_init(AVCodecContext *avctx){
     return 0;
 }
 
-AVCodec mpeg_xvmc_decoder = {
+AVCodec ff_mpeg_xvmc_decoder = {
     "mpegvideo_xvmc",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_MPEG2VIDEO_XVMC,
@@ -2577,7 +2580,7 @@ AVCodec mpeg_xvmc_decoder = {
 #endif
 
 #if CONFIG_MPEG_VDPAU_DECODER
-AVCodec mpeg_vdpau_decoder = {
+AVCodec ff_mpeg_vdpau_decoder = {
     "mpegvideo_vdpau",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_MPEG2VIDEO,
@@ -2593,7 +2596,7 @@ AVCodec mpeg_vdpau_decoder = {
 #endif
 
 #if CONFIG_MPEG1_VDPAU_DECODER
-AVCodec mpeg1_vdpau_decoder = {
+AVCodec ff_mpeg1_vdpau_decoder = {
     "mpeg1video_vdpau",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_MPEG1VIDEO,
diff --git a/libavcodec/mpeg12.h b/libavcodec/mpeg12.h
index 30bb675..4c55726 100644
--- a/libavcodec/mpeg12.h
+++ b/libavcodec/mpeg12.h
@@ -2,20 +2,20 @@
  * MPEG1/2 common code
  * Copyright (c) 2007 Aurelien Jacobs <aurel at gnuage.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -27,8 +27,8 @@
 #define DC_VLC_BITS 9
 #define TEX_VLC_BITS 9
 
-static VLC dc_lum_vlc;
-static VLC dc_chroma_vlc;
+extern VLC ff_dc_lum_vlc;
+extern VLC ff_dc_chroma_vlc;
 
 extern uint8_t ff_mpeg12_static_rl_table_store[2][2][2*MAX_RUN + MAX_LEVEL + 3];
 
@@ -40,9 +40,9 @@ static inline int decode_dc(GetBitContext *gb, int component)
     int code, diff;
 
     if (component == 0) {
-        code = get_vlc2(gb, dc_lum_vlc.table, DC_VLC_BITS, 2);
+        code = get_vlc2(gb, ff_dc_lum_vlc.table, DC_VLC_BITS, 2);
     } else {
-        code = get_vlc2(gb, dc_chroma_vlc.table, DC_VLC_BITS, 2);
+        code = get_vlc2(gb, ff_dc_chroma_vlc.table, DC_VLC_BITS, 2);
     }
     if (code < 0){
         av_log(NULL, AV_LOG_ERROR, "invalid dc code at\n");
diff --git a/libavcodec/mpeg12data.c b/libavcodec/mpeg12data.c
index 8b1f563..299215f 100644
--- a/libavcodec/mpeg12data.c
+++ b/libavcodec/mpeg12data.c
@@ -3,20 +3,20 @@
  * copyright (c) 2000,2001 Fabrice Bellard
  * copyright (c) 2002-2004 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/mpeg12data.h b/libavcodec/mpeg12data.h
index 9695e9d..3586a61 100644
--- a/libavcodec/mpeg12data.h
+++ b/libavcodec/mpeg12data.h
@@ -3,20 +3,20 @@
  * copyright (c) 2000,2001 Fabrice Bellard
  * copyright (c) 2002-2004 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/mpeg12decdata.h b/libavcodec/mpeg12decdata.h
index 66ca5c4..323a902 100644
--- a/libavcodec/mpeg12decdata.h
+++ b/libavcodec/mpeg12decdata.h
@@ -3,20 +3,20 @@
  * copyright (c) 2000,2001 Fabrice Bellard
  * copyright (c) 2002-2004 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/mpeg12enc.c b/libavcodec/mpeg12enc.c
index bf36129..206e7d6 100644
--- a/libavcodec/mpeg12enc.c
+++ b/libavcodec/mpeg12enc.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2000,2001 Fabrice Bellard
  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -119,7 +119,7 @@ static int find_frame_rate_index(MpegEncContext *s){
     for(i=1;i<14;i++) {
         int64_t n0= 1001LL/ff_frame_rate_tab[i].den*ff_frame_rate_tab[i].num*s->avctx->time_base.num;
         int64_t n1= 1001LL*s->avctx->time_base.den;
-        if(s->avctx->strict_std_compliance > FF_COMPLIANCE_INOFFICIAL && i>=9) break;
+        if(s->avctx->strict_std_compliance > FF_COMPLIANCE_UNOFFICIAL && i>=9) break;
 
         d = FFABS(n0 - n1);
         if(d < dmin){
@@ -890,7 +890,7 @@ static void mpeg1_encode_block(MpegEncContext *s,
     next_coef:
 #if 0
         if (level != 0)
-            dprintf(s->avctx, "level[%d]=%d\n", i, level);
+            av_dlog(s->avctx, "level[%d]=%d\n", i, level);
 #endif
         /* encode using VLC */
         if (level != 0) {
@@ -930,7 +930,7 @@ static void mpeg1_encode_block(MpegEncContext *s,
     put_bits(&s->pb, table_vlc[112][1], table_vlc[112][0]);
 }
 
-AVCodec mpeg1video_encoder = {
+AVCodec ff_mpeg1video_encoder = {
     "mpeg1video",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_MPEG1VIDEO,
@@ -944,7 +944,7 @@ AVCodec mpeg1video_encoder = {
     .long_name= NULL_IF_CONFIG_SMALL("MPEG-1 video"),
 };
 
-AVCodec mpeg2video_encoder = {
+AVCodec ff_mpeg2video_encoder = {
     "mpeg2video",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_MPEG2VIDEO,
diff --git a/libavcodec/mpeg4audio.c b/libavcodec/mpeg4audio.c
index 7507212..f0399af 100644
--- a/libavcodec/mpeg4audio.c
+++ b/libavcodec/mpeg4audio.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2008 Baptiste Coudurier <baptiste.coudurier at free.fr>
  * Copyright (c) 2009 Alex Converse <alex.converse at gmail.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -131,6 +131,14 @@ int ff_mpeg4audio_get_config(MPEG4AudioConfig *c, const uint8_t *buf, int buf_si
                 get_bits1(&gb); // skip 1 bit
         }
     }
+
+    //PS requires SBR
+    if (!c->sbr)
+        c->ps = 0;
+    //Limit implicit PS to the HE-AACv2 Profile
+    if ((c->ps == -1 && c->object_type != AOT_AAC_LC) || c->channels & ~0x01)
+        c->ps = 0;
+
     return specific_config_bitindex;
 }
 
diff --git a/libavcodec/mpeg4audio.h b/libavcodec/mpeg4audio.h
index b941850..2d2b4a2 100644
--- a/libavcodec/mpeg4audio.h
+++ b/libavcodec/mpeg4audio.h
@@ -2,20 +2,20 @@
  * MPEG-4 Audio common header
  * Copyright (c) 2008 Baptiste Coudurier <baptiste.coudurier at free.fr>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -57,7 +57,7 @@ enum AudioObjectType {
     AOT_AAC_MAIN,              ///< Y                       Main
     AOT_AAC_LC,                ///< Y                       Low Complexity
     AOT_AAC_SSR,               ///< N (code in SoC repo)    Scalable Sample Rate
-    AOT_AAC_LTP,               ///< N (code in SoC repo)    Long Term Prediction
+    AOT_AAC_LTP,               ///< Y                       Long Term Prediction
     AOT_SBR,                   ///< Y                       Spectral Band Replication
     AOT_AAC_SCALABLE,          ///< N                       Scalable
     AOT_TWINVQ,                ///< N                       Twin Vector Quantizer
diff --git a/libavcodec/mpeg4data.h b/libavcodec/mpeg4data.h
index bef5f88..07cbeee 100644
--- a/libavcodec/mpeg4data.h
+++ b/libavcodec/mpeg4data.h
@@ -3,20 +3,20 @@
  * H263+ support
  * copyright (c) 2002-2004 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -115,7 +115,7 @@ RLTable ff_mpeg4_rl_intra = {
 };
 
 /* Note this is identical to the intra rvlc except that it is reordered. */
-const uint16_t inter_rvlc[170][2]={
+static const uint16_t inter_rvlc[170][2]={
 {0x0006,  3},{0x0001,  4},{0x0004,  5},{0x001C,  7},
 {0x003C,  8},{0x003D,  8},{0x007C,  9},{0x00FC, 10},
 {0x00FD, 10},{0x01FC, 11},{0x01FD, 11},{0x03FC, 12},
@@ -219,7 +219,7 @@ RLTable rvlc_rl_inter = {
     inter_rvlc_level,
 };
 
-const uint16_t intra_rvlc[170][2]={
+static const uint16_t intra_rvlc[170][2]={
 {0x0006,  3},{0x0007,  3},{0x000A,  4},{0x0009,  5},
 {0x0014,  6},{0x0015,  6},{0x0034,  7},{0x0074,  8},
 {0x0075,  8},{0x00DD,  9},{0x00EC,  9},{0x01EC, 10},
diff --git a/libavcodec/mpeg4video.c b/libavcodec/mpeg4video.c
index dd4dd8a..98781b4 100644
--- a/libavcodec/mpeg4video.c
+++ b/libavcodec/mpeg4video.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2000,2001 Fabrice Bellard
  * Copyright (c) 2002-2010 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/mpeg4video.h b/libavcodec/mpeg4video.h
index aab3236..015193e 100644
--- a/libavcodec/mpeg4video.h
+++ b/libavcodec/mpeg4video.h
@@ -3,20 +3,20 @@
  * Copyright (c) 2000,2001 Fabrice Bellard
  * Copyright (c) 2002-2010 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -66,10 +66,7 @@ extern const uint16_t ff_mpeg4_intra_vlc[103][2];
 extern RLTable ff_mpeg4_rl_intra;
 
 /* Note this is identical to the intra rvlc except that it is reordered. */
-extern const uint16_t inter_rvlc[170][2];
 extern RLTable rvlc_rl_inter;
-
-extern const uint16_t intra_rvlc[170][2];
 extern RLTable rvlc_rl_intra;
 
 extern const uint16_t sprite_trajectory_tab[15][2];
diff --git a/libavcodec/mpeg4video_parser.c b/libavcodec/mpeg4video_parser.c
index 5dbda8b..2e498d1 100644
--- a/libavcodec/mpeg4video_parser.c
+++ b/libavcodec/mpeg4video_parser.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2003 Fabrice Bellard
  * Copyright (c) 2003 Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -129,7 +129,7 @@ static int mpeg4video_parse(AVCodecParserContext *s,
 }
 
 
-AVCodecParser mpeg4video_parser = {
+AVCodecParser ff_mpeg4video_parser = {
     { CODEC_ID_MPEG4 },
     sizeof(ParseContext1),
     mpeg4video_parse_init,
diff --git a/libavcodec/mpeg4video_parser.h b/libavcodec/mpeg4video_parser.h
index 822a24c..d907dc4 100644
--- a/libavcodec/mpeg4video_parser.h
+++ b/libavcodec/mpeg4video_parser.h
@@ -3,20 +3,20 @@
  * Copyright (c) 2003 Fabrice Bellard
  * Copyright (c) 2003 Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/mpeg4videodec.c b/libavcodec/mpeg4videodec.c
index fa69c9e..8ed8531 100644
--- a/libavcodec/mpeg4videodec.c
+++ b/libavcodec/mpeg4videodec.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2000,2001 Fabrice Bellard
  * Copyright (c) 2002-2010 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -1023,12 +1023,7 @@ static inline int mpeg4_decode_block(MpegEncContext * s, DCTELEM * block,
                     if(last) i+=192;
                 } else {
                     /* second escape */
-#if MIN_CACHE_BITS < 20
-                    LAST_SKIP_BITS(re, &s->gb, 2);
-                    UPDATE_CACHE(re, &s->gb);
-#else
                     SKIP_BITS(re, &s->gb, 2);
-#endif
                     GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1);
                     i+= run + rl->max_run[run>>7][level/qmul] +1; //FIXME opt indexing
                     level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
@@ -1036,12 +1031,7 @@ static inline int mpeg4_decode_block(MpegEncContext * s, DCTELEM * block,
                 }
             } else {
                 /* first escape */
-#if MIN_CACHE_BITS < 19
-                LAST_SKIP_BITS(re, &s->gb, 1);
-                UPDATE_CACHE(re, &s->gb);
-#else
                 SKIP_BITS(re, &s->gb, 1);
-#endif
                 GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1);
                 i+= run;
                 level = level + rl->max_level[run>>7][(run-1)&63] * qmul;//FIXME opt indexing
@@ -1504,16 +1494,17 @@ end:
 
 static int mpeg4_decode_gop_header(MpegEncContext * s, GetBitContext *gb){
     int hours, minutes, seconds;
-
-    hours= get_bits(gb, 5);
-    minutes= get_bits(gb, 6);
-    skip_bits1(gb);
-    seconds= get_bits(gb, 6);
-
-    s->time_base= seconds + 60*(minutes + 60*hours);
-
-    skip_bits1(gb);
-    skip_bits1(gb);
+    unsigned time_code = show_bits(gb, 18);
+
+    if (time_code & 0x40) {     /* marker_bit */
+        hours   = time_code >> 13;
+        minutes = time_code >>  7 & 0x3f;
+        seconds = time_code       & 0x3f;
+        s->time_base = seconds + 60*(minutes + 60*hours);
+        skip_bits(gb, 20);      /* time_code, closed_gov, broken_link */
+    } else {
+        av_log(s->avctx, AV_LOG_WARNING, "GOP header missing marker_bit\n");
+    }
 
     return 0;
 }
@@ -1575,6 +1566,7 @@ static int decode_vol_header(MpegEncContext *s, GetBitContext *gb){
     s->avctx->time_base.den = get_bits(gb, 16);
     if(!s->avctx->time_base.den){
         av_log(s->avctx, AV_LOG_ERROR, "time_base.den==0\n");
+        s->avctx->time_base.num = 0;
         return -1;
     }
 
@@ -2080,7 +2072,7 @@ static int decode_vop_header(MpegEncContext *s, GetBitContext *gb){
      /* detect buggy encoders which don't set the low_delay flag (divx4/xvid/opendivx)*/
      // note we cannot detect divx5 without b-frames easily (although it's buggy too)
      if(s->vo_type==0 && s->vol_control_parameters==0 && s->divx_version==-1 && s->picture_number==0){
-         av_log(s->avctx, AV_LOG_ERROR, "looks like this file was encoded with (divx4/(old)xvid/opendivx) -> forcing low_delay flag\n");
+         av_log(s->avctx, AV_LOG_WARNING, "looks like this file was encoded with (divx4/(old)xvid/opendivx) -> forcing low_delay flag\n");
          s->low_delay=1;
      }
 
@@ -2119,7 +2111,7 @@ int ff_mpeg4_decode_picture_header(MpegEncContext * s, GetBitContext *gb)
     for(;;) {
         if(get_bits_count(gb) >= gb->size_in_bits){
             if(gb->size_in_bits==8 && (s->divx_version>=0 || s->xvid_build>=0)){
-                av_log(s->avctx, AV_LOG_ERROR, "frame skip %d\n", gb->size_in_bits);
+                av_log(s->avctx, AV_LOG_WARNING, "frame skip %d\n", gb->size_in_bits);
                 return FRAME_SKIPPED; //divx bug
             }else
                 return -1; //end of stream
@@ -2234,7 +2226,7 @@ static av_cold int decode_init(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec mpeg4_decoder = {
+AVCodec ff_mpeg4_decoder = {
     "mpeg4",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_MPEG4,
@@ -2245,13 +2237,14 @@ AVCodec mpeg4_decoder = {
     ff_h263_decode_frame,
     CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY,
     .flush= ff_mpeg_flush,
+    .max_lowres= 3,
     .long_name= NULL_IF_CONFIG_SMALL("MPEG-4 part 2"),
     .pix_fmts= ff_hwaccel_pixfmt_list_420,
 };
 
 
 #if CONFIG_MPEG4_VDPAU_DECODER
-AVCodec mpeg4_vdpau_decoder = {
+AVCodec ff_mpeg4_vdpau_decoder = {
     "mpeg4_vdpau",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_MPEG4,
diff --git a/libavcodec/mpeg4videoenc.c b/libavcodec/mpeg4videoenc.c
index 79190f0..134894c 100644
--- a/libavcodec/mpeg4videoenc.c
+++ b/libavcodec/mpeg4videoenc.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2000,2001 Fabrice Bellard
  * Copyright (c) 2002-2010 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -54,7 +54,7 @@ max run: 29/41
 
 
 /**
- * Returns the number of bits that encoding the 8x8 block in block would need.
+ * Return the number of bits that encoding the 8x8 block in block would need.
  * @param[in]  block_last_index last index in scantable order that refers to a non zero element in block.
  */
 static inline int get_block_rate(MpegEncContext * s, DCTELEM block[64], int block_last_index, uint8_t scantable[64]){
@@ -82,7 +82,7 @@ static inline int get_block_rate(MpegEncContext * s, DCTELEM block[64], int bloc
 
 
 /**
- * Restores the ac coefficients in block that have been changed by decide_ac_pred().
+ * Restore the ac coefficients in block that have been changed by decide_ac_pred().
  * This function also restores s->block_last_index.
  * @param[in,out] block MB coefficients, these will be restored
  * @param[in] dir ac prediction direction for each 8x8 block
@@ -113,7 +113,7 @@ static inline void restore_ac_coeffs(MpegEncContext * s, DCTELEM block[6][64], c
 }
 
 /**
- * Returns the optimal value (0 or 1) for the ac_pred element for the given MB in mpeg4.
+ * Return the optimal value (0 or 1) for the ac_pred element for the given MB in mpeg4.
  * This function will also update s->block_last_index and s->ac_val.
  * @param[in,out] block MB coefficients, these will be updated if 1 is returned
  * @param[in] dir ac prediction direction for each 8x8 block
@@ -1338,7 +1338,7 @@ void ff_mpeg4_encode_video_packet_header(MpegEncContext *s)
     put_bits(&s->pb, 1, 0); /* no HEC */
 }
 
-AVCodec mpeg4_encoder = {
+AVCodec ff_mpeg4_encoder = {
     "mpeg4",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_MPEG4,
diff --git a/libavcodec/mpegaudio.c b/libavcodec/mpegaudio.c
index cba5299..1a83635 100644
--- a/libavcodec/mpegaudio.c
+++ b/libavcodec/mpegaudio.c
@@ -2,20 +2,20 @@
  * MPEG Audio common code
  * Copyright (c) 2001, 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/mpegaudio.h b/libavcodec/mpegaudio.h
index 26ec2be..fbfddcc 100644
--- a/libavcodec/mpegaudio.h
+++ b/libavcodec/mpegaudio.h
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2001 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -26,9 +26,14 @@
 #ifndef AVCODEC_MPEGAUDIO_H
 #define AVCODEC_MPEGAUDIO_H
 
+#ifndef CONFIG_FLOAT
+#   define CONFIG_FLOAT 0
+#endif
+
 #include "avcodec.h"
 #include "get_bits.h"
 #include "dsputil.h"
+#include "dct.h"
 
 #define CONFIG_AUDIO_NONSHORT 0
 
@@ -65,23 +70,31 @@
 
 #define FIX(a)   ((int)((a) * FRAC_ONE))
 
-#if CONFIG_MPEGAUDIO_HP && CONFIG_AUDIO_NONSHORT
+#if CONFIG_FLOAT
+typedef float OUT_INT;
+#define OUT_FMT AV_SAMPLE_FMT_FLT
+#elif CONFIG_MPEGAUDIO_HP && CONFIG_AUDIO_NONSHORT
 typedef int32_t OUT_INT;
 #define OUT_MAX INT32_MAX
 #define OUT_MIN INT32_MIN
 #define OUT_SHIFT (WFRAC_BITS + FRAC_BITS - 31)
-#define OUT_FMT SAMPLE_FMT_S32
+#define OUT_FMT AV_SAMPLE_FMT_S32
 #else
 typedef int16_t OUT_INT;
 #define OUT_MAX INT16_MAX
 #define OUT_MIN INT16_MIN
 #define OUT_SHIFT (WFRAC_BITS + FRAC_BITS - 15)
-#define OUT_FMT SAMPLE_FMT_S16
+#define OUT_FMT AV_SAMPLE_FMT_S16
 #endif
 
-#if FRAC_BITS <= 15
+#if CONFIG_FLOAT
+#   define INTFLOAT float
+typedef float MPA_INT;
+#elif FRAC_BITS <= 15
+#   define INTFLOAT int
 typedef int16_t MPA_INT;
 #else
+#   define INTFLOAT int
 typedef int32_t MPA_INT;
 #endif
 
@@ -105,7 +118,7 @@ typedef struct GranuleDef {
     int preflag;
     int short_start, long_end; /* long/short band indexes */
     uint8_t scale_factors[40];
-    int32_t sb_hybrid[SBLIMIT * 18]; /* 576 samples */
+    INTFLOAT sb_hybrid[SBLIMIT * 18]; /* 576 samples */
 } GranuleDef;
 
 #define MPA_DECODE_HEADER \
@@ -134,17 +147,21 @@ typedef struct MPADecodeContext {
     GetBitContext in_gb;
     DECLARE_ALIGNED(16, MPA_INT, synth_buf)[MPA_MAX_CHANNELS][512 * 2];
     int synth_buf_offset[MPA_MAX_CHANNELS];
-    DECLARE_ALIGNED(16, int32_t, sb_samples)[MPA_MAX_CHANNELS][36][SBLIMIT];
-    int32_t mdct_buf[MPA_MAX_CHANNELS][SBLIMIT * 18]; /* previous samples, for layer 3 MDCT */
+    DECLARE_ALIGNED(16, INTFLOAT, sb_samples)[MPA_MAX_CHANNELS][36][SBLIMIT];
+    INTFLOAT mdct_buf[MPA_MAX_CHANNELS][SBLIMIT * 18]; /* previous samples, for layer 3 MDCT */
     GranuleDef granules[2][2]; /* Used in Layer 3 */
 #ifdef DEBUG
     int frame_count;
 #endif
-    void (*compute_antialias)(struct MPADecodeContext *s, struct GranuleDef *g);
     int adu_mode; ///< 0 for standard mp3, 1 for adu formatted mp3
     int dither_state;
     int error_recognition;
     AVCodecContext* avctx;
+#if CONFIG_FLOAT
+    DCTContext dct;
+#endif
+    void (*apply_window_mp3)(MPA_INT *synth_buf, MPA_INT *window,
+                             int *dither_state, OUT_INT *samples, int incr);
 } MPADecodeContext;
 
 /* layer 3 huffman tables */
@@ -161,7 +178,17 @@ void ff_mpa_synth_init(MPA_INT *window);
 void ff_mpa_synth_filter(MPA_INT *synth_buf_ptr, int *synth_buf_offset,
                          MPA_INT *window, int *dither_state,
                          OUT_INT *samples, int incr,
-                         int32_t sb_samples[SBLIMIT]);
+                         INTFLOAT sb_samples[SBLIMIT]);
+
+void ff_mpa_synth_init_float(MPA_INT *window);
+void ff_mpa_synth_filter_float(MPADecodeContext *s,
+                         MPA_INT *synth_buf_ptr, int *synth_buf_offset,
+                         MPA_INT *window, int *dither_state,
+                         OUT_INT *samples, int incr,
+                         INTFLOAT sb_samples[SBLIMIT]);
+
+void ff_mpegaudiodec_init_mmx(MPADecodeContext *s);
+void ff_mpegaudiodec_init_altivec(MPADecodeContext *s);
 
 /* fast header check for resync */
 static inline int ff_mpa_check_header(uint32_t header){
diff --git a/libavcodec/mpegaudio3.h b/libavcodec/mpegaudio3.h
index c374a59..7047652 100644
--- a/libavcodec/mpegaudio3.h
+++ b/libavcodec/mpegaudio3.h
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2007 Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/mpegaudio_parser.c b/libavcodec/mpegaudio_parser.c
index 6d7ab8a..3bf1a18 100644
--- a/libavcodec/mpegaudio_parser.c
+++ b/libavcodec/mpegaudio_parser.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2003 Fabrice Bellard
  * Copyright (c) 2003 Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -140,7 +140,7 @@ static int mpegaudio_parse(AVCodecParserContext *s1,
 }
 
 
-AVCodecParser mpegaudio_parser = {
+AVCodecParser ff_mpegaudio_parser = {
     { CODEC_ID_MP1, CODEC_ID_MP2, CODEC_ID_MP3 },
     sizeof(MpegAudioParseContext),
     NULL,
diff --git a/libavcodec/mpegaudio_tablegen.c b/libavcodec/mpegaudio_tablegen.c
index 70d145b..27da219 100644
--- a/libavcodec/mpegaudio_tablegen.c
+++ b/libavcodec/mpegaudio_tablegen.c
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2009 Reimar Döffinger <Reimar.Doeffinger at gmx.de>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -31,21 +31,12 @@ int main(void)
 
     write_fileheader();
 
-    printf("static const int8_t table_4_3_exp[TABLE_4_3_SIZE] = {\n");
-    write_int8_array(table_4_3_exp, TABLE_4_3_SIZE);
-    printf("};\n");
-
-    printf("static const uint32_t table_4_3_value[TABLE_4_3_SIZE] = {\n");
-    write_uint32_array(table_4_3_value, TABLE_4_3_SIZE);
-    printf("};\n");
-
-    printf("static const uint32_t exp_table[512] = {\n");
-    write_uint32_array(exp_table, 512);
-    printf("};\n");
-
-    printf("static const uint32_t expval_table[512][16] = {\n");
-    write_uint32_2d_array(expval_table, 512, 16);
-    printf("};\n");
+    WRITE_ARRAY("static const", int8_t, table_4_3_exp);
+    WRITE_ARRAY("static const", uint32_t, table_4_3_value);
+    WRITE_ARRAY("static const", uint32_t, exp_table);
+    WRITE_ARRAY("static const", float, exp_table_float);
+    WRITE_2D_ARRAY("static const", uint32_t, expval_table);
+    WRITE_2D_ARRAY("static const", float, expval_table_float);
 
     return 0;
 }
diff --git a/libavcodec/mpegaudio_tablegen.h b/libavcodec/mpegaudio_tablegen.h
index 9d056cb..ccaaf0b 100644
--- a/libavcodec/mpegaudio_tablegen.h
+++ b/libavcodec/mpegaudio_tablegen.h
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2009 Reimar Döffinger <Reimar.Doeffinger at gmx.de>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -24,8 +24,6 @@
 #define MPEGAUDIO_TABLEGEN_H
 
 #include <stdint.h>
-// do not use libavutil/mathematics.h since this is compiled both
-// for the host and the target and config.h is only valid for the target
 #include <math.h>
 
 #define TABLE_4_3_SIZE (8191 + 16)*4
@@ -37,6 +35,8 @@ static int8_t   table_4_3_exp[TABLE_4_3_SIZE];
 static uint32_t table_4_3_value[TABLE_4_3_SIZE];
 static uint32_t exp_table[512];
 static uint32_t expval_table[512][16];
+static float exp_table_float[512];
+static float expval_table_float[512][16];
 
 static void mpegaudio_tableinit(void)
 {
@@ -58,8 +58,10 @@ static void mpegaudio_tableinit(void)
         for (value = 0; value < 16; value++) {
             double f = (double)value * cbrtf(value) * pow(2, (exponent - 400) * 0.25 + FRAC_BITS + 5);
             expval_table[exponent][value] = llrint(f);
+            expval_table_float[exponent][value] = f;
         }
         exp_table[exponent] = expval_table[exponent][1];
+        exp_table_float[exponent] = expval_table_float[exponent][1];
     }
 }
 #endif /* CONFIG_HARDCODED_TABLES */
diff --git a/libavcodec/mpegaudiodata.c b/libavcodec/mpegaudiodata.c
index c9dabf3..b850d22 100644
--- a/libavcodec/mpegaudiodata.c
+++ b/libavcodec/mpegaudiodata.c
@@ -2,20 +2,20 @@
  * MPEG Audio common tables
  * copyright (c) 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/mpegaudiodata.h b/libavcodec/mpegaudiodata.h
index 5626e3d..841ec51 100644
--- a/libavcodec/mpegaudiodata.h
+++ b/libavcodec/mpegaudiodata.h
@@ -2,20 +2,20 @@
  * MPEG Audio common tables
  * copyright (c) 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/mpegaudiodec.c b/libavcodec/mpegaudiodec.c
index 25fad80..024d618 100644
--- a/libavcodec/mpegaudiodec.c
+++ b/libavcodec/mpegaudiodec.c
@@ -2,20 +2,20 @@
  * MPEG Audio decoder
  * Copyright (c) 2001, 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -24,6 +24,7 @@
  * MPEG Audio decoder.
  */
 
+#include "libavutil/audioconvert.h"
 #include "avcodec.h"
 #include "get_bits.h"
 #include "dsputil.h"
@@ -39,11 +40,26 @@
 
 #include "mathops.h"
 
+#if CONFIG_FLOAT
+#   define SHR(a,b)       ((a)*(1.0f/(1<<(b))))
+#   define compute_antialias compute_antialias_float
+#   define FIXR_OLD(a)    ((int)((a) * FRAC_ONE + 0.5))
+#   define FIXR(x)        ((float)(x))
+#   define FIXHR(x)       ((float)(x))
+#   define MULH3(x, y, s) ((s)*(y)*(x))
+#   define MULLx(x, y, s) ((y)*(x))
+#   define RENAME(a) a ## _float
+#else
+#   define SHR(a,b)       ((a)>>(b))
+#   define compute_antialias compute_antialias_integer
 /* WARNING: only correct for posititive numbers */
-#define FIXR(a)   ((int)((a) * FRAC_ONE + 0.5))
-#define FRAC_RND(a) (((a) + (FRAC_ONE/2)) >> FRAC_BITS)
-
-#define FIXHR(a) ((int)((a) * (1LL<<32) + 0.5))
+#   define FIXR_OLD(a)    ((int)((a) * FRAC_ONE + 0.5))
+#   define FIXR(a)        ((int)((a) * FRAC_ONE + 0.5))
+#   define FIXHR(a)       ((int)((a) * (1LL<<32) + 0.5))
+#   define MULH3(x, y, s) MULH((s)*(x), y)
+#   define MULLx(x, y, s) MULL(x,y,s)
+#   define RENAME(a)      a
+#endif
 
 /****************/
 
@@ -52,8 +68,15 @@
 #include "mpegaudiodata.h"
 #include "mpegaudiodectab.h"
 
-static void compute_antialias_integer(MPADecodeContext *s, GranuleDef *g);
-static void compute_antialias_float(MPADecodeContext *s, GranuleDef *g);
+#if CONFIG_FLOAT
+#    include "fft.h"
+#else
+#    include "dct32.c"
+#endif
+
+static void compute_antialias(MPADecodeContext *s, GranuleDef *g);
+static void apply_window_mp3_c(MPA_INT *synth_buf, MPA_INT *window,
+                               int *dither_state, OUT_INT *samples, int incr);
 
 /* vlc structure for decoding layer 3 huffman tables */
 static VLC huff_vlc[16];
@@ -74,11 +97,19 @@ static const int huff_quad_vlc_tables_sizes[2] = {
 static uint16_t band_index_long[9][23];
 #include "mpegaudio_tablegen.h"
 /* intensity stereo coef table */
-static int32_t is_table[2][16];
-static int32_t is_table_lsf[2][2][16];
+static INTFLOAT is_table[2][16];
+static INTFLOAT is_table_lsf[2][2][16];
 static int32_t csa_table[8][4];
 static float csa_table_float[8][4];
-static int32_t mdct_win[8][36];
+static INTFLOAT mdct_win[8][36];
+
+static int16_t division_tab3[1<<6 ];
+static int16_t division_tab5[1<<8 ];
+static int16_t division_tab9[1<<11];
+
+static int16_t * const division_tabs[4] = {
+    division_tab3, division_tab5, NULL, division_tab9
+};
 
 /* lower 2 bits: modulo 3, higher bits: shift */
 static uint16_t scale_factor_modshift[64];
@@ -87,7 +118,7 @@ static int32_t scale_factor_mult[15][3];
 /* mult table for layer 2 group quantization */
 
 #define SCALE_GEN(v) \
-{ FIXR(1.0 * (v)), FIXR(0.7937005259 * (v)), FIXR(0.6299605249 * (v)) }
+{ FIXR_OLD(1.0 * (v)), FIXR_OLD(0.7937005259 * (v)), FIXR_OLD(0.6299605249 * (v)) }
 
 static const int32_t scale_factor_mult2[3][3] = {
     SCALE_GEN(4.0 / 3.0), /* 3 steps */
@@ -95,7 +126,7 @@ static const int32_t scale_factor_mult2[3][3] = {
     SCALE_GEN(4.0 / 9.0), /* 9 steps */
 };
 
-DECLARE_ALIGNED(16, MPA_INT, ff_mpa_synth_window)[512];
+DECLARE_ALIGNED(16, MPA_INT, RENAME(ff_mpa_synth_window))[512+256];
 
 /**
  * Convert region offsets to region sizes and truncate
@@ -290,15 +321,18 @@ static av_cold int decode_init(AVCodecContext * avctx)
     int i, j, k;
 
     s->avctx = avctx;
+    s->apply_window_mp3 = apply_window_mp3_c;
+#if HAVE_MMX && CONFIG_FLOAT
+    ff_mpegaudiodec_init_mmx(s);
+#endif
+#if CONFIG_FLOAT
+    ff_dct_init(&s->dct, 5, DCT_II);
+#endif
+    if (HAVE_ALTIVEC && CONFIG_FLOAT) ff_mpegaudiodec_init_altivec(s);
 
     avctx->sample_fmt= OUT_FMT;
     s->error_recognition= avctx->error_recognition;
 
-    if(avctx->antialias_algo != FF_AA_FLOAT)
-        s->compute_antialias= compute_antialias_integer;
-    else
-        s->compute_antialias= compute_antialias_float;
-
     if (!init && !avctx->parse_only) {
         int offset;
 
@@ -316,17 +350,17 @@ static av_cold int decode_init(AVCodecContext * avctx)
             int n, norm;
             n = i + 2;
             norm = ((INT64_C(1) << n) * FRAC_ONE) / ((1 << n) - 1);
-            scale_factor_mult[i][0] = MULL(FIXR(1.0 * 2.0), norm, FRAC_BITS);
-            scale_factor_mult[i][1] = MULL(FIXR(0.7937005259 * 2.0), norm, FRAC_BITS);
-            scale_factor_mult[i][2] = MULL(FIXR(0.6299605249 * 2.0), norm, FRAC_BITS);
-            dprintf(avctx, "%d: norm=%x s=%x %x %x\n",
+            scale_factor_mult[i][0] = MULLx(norm, FIXR(1.0          * 2.0), FRAC_BITS);
+            scale_factor_mult[i][1] = MULLx(norm, FIXR(0.7937005259 * 2.0), FRAC_BITS);
+            scale_factor_mult[i][2] = MULLx(norm, FIXR(0.6299605249 * 2.0), FRAC_BITS);
+            av_dlog(avctx, "%d: norm=%x s=%x %x %x\n",
                     i, norm,
                     scale_factor_mult[i][0],
                     scale_factor_mult[i][1],
                     scale_factor_mult[i][2]);
         }
 
-        ff_mpa_synth_init(ff_mpa_synth_window);
+        RENAME(ff_mpa_synth_init)(RENAME(ff_mpa_synth_window));
 
         /* huffman decode tables */
         offset = 0;
@@ -384,9 +418,23 @@ static av_cold int decode_init(AVCodecContext * avctx)
         int_pow_init();
         mpegaudio_tableinit();
 
+        for (i = 0; i < 4; i++)
+            if (ff_mpa_quant_bits[i] < 0)
+                for (j = 0; j < (1<<(-ff_mpa_quant_bits[i]+1)); j++) {
+                    int val1, val2, val3, steps;
+                    int val = j;
+                    steps  = ff_mpa_quant_steps[i];
+                    val1 = val % steps;
+                    val /= steps;
+                    val2 = val % steps;
+                    val3 = val / steps;
+                    division_tabs[i][j] = val1 + (val2 << 4) + (val3 << 8);
+                }
+
+
         for(i=0;i<7;i++) {
             float f;
-            int v;
+            INTFLOAT v;
             if (i != 6) {
                 f = tan((double)i * M_PI / 12.0);
                 v = FIXR(f / (1.0 + f));
@@ -410,7 +458,7 @@ static av_cold int decode_init(AVCodecContext * avctx)
                 k = i & 1;
                 is_table_lsf[j][k ^ 1][i] = FIXR(f);
                 is_table_lsf[j][k][i] = FIXR(1.0);
-                dprintf(avctx, "is_table_lsf %d %d: %x %x\n",
+                av_dlog(avctx, "is_table_lsf %d %d: %x %x\n",
                         i, j, is_table_lsf[j][0][i], is_table_lsf[j][1][i]);
             }
         }
@@ -475,234 +523,24 @@ static av_cold int decode_init(AVCodecContext * avctx)
     return 0;
 }
 
-/* tab[i][j] = 1.0 / (2.0 * cos(pi*(2*k+1) / 2^(6 - j))) */
-
-/* cos(i*pi/64) */
-
-#define COS0_0  FIXHR(0.50060299823519630134/2)
-#define COS0_1  FIXHR(0.50547095989754365998/2)
-#define COS0_2  FIXHR(0.51544730992262454697/2)
-#define COS0_3  FIXHR(0.53104259108978417447/2)
-#define COS0_4  FIXHR(0.55310389603444452782/2)
-#define COS0_5  FIXHR(0.58293496820613387367/2)
-#define COS0_6  FIXHR(0.62250412303566481615/2)
-#define COS0_7  FIXHR(0.67480834145500574602/2)
-#define COS0_8  FIXHR(0.74453627100229844977/2)
-#define COS0_9  FIXHR(0.83934964541552703873/2)
-#define COS0_10 FIXHR(0.97256823786196069369/2)
-#define COS0_11 FIXHR(1.16943993343288495515/4)
-#define COS0_12 FIXHR(1.48416461631416627724/4)
-#define COS0_13 FIXHR(2.05778100995341155085/8)
-#define COS0_14 FIXHR(3.40760841846871878570/8)
-#define COS0_15 FIXHR(10.19000812354805681150/32)
-
-#define COS1_0 FIXHR(0.50241928618815570551/2)
-#define COS1_1 FIXHR(0.52249861493968888062/2)
-#define COS1_2 FIXHR(0.56694403481635770368/2)
-#define COS1_3 FIXHR(0.64682178335999012954/2)
-#define COS1_4 FIXHR(0.78815462345125022473/2)
-#define COS1_5 FIXHR(1.06067768599034747134/4)
-#define COS1_6 FIXHR(1.72244709823833392782/4)
-#define COS1_7 FIXHR(5.10114861868916385802/16)
-
-#define COS2_0 FIXHR(0.50979557910415916894/2)
-#define COS2_1 FIXHR(0.60134488693504528054/2)
-#define COS2_2 FIXHR(0.89997622313641570463/2)
-#define COS2_3 FIXHR(2.56291544774150617881/8)
-
-#define COS3_0 FIXHR(0.54119610014619698439/2)
-#define COS3_1 FIXHR(1.30656296487637652785/4)
-
-#define COS4_0 FIXHR(0.70710678118654752439/2)
-
-/* butterfly operator */
-#define BF(a, b, c, s)\
-{\
-    tmp0 = tab[a] + tab[b];\
-    tmp1 = tab[a] - tab[b];\
-    tab[a] = tmp0;\
-    tab[b] = MULH(tmp1<<(s), c);\
-}
 
-#define BF1(a, b, c, d)\
-{\
-    BF(a, b, COS4_0, 1);\
-    BF(c, d,-COS4_0, 1);\
-    tab[c] += tab[d];\
+#if CONFIG_FLOAT
+static inline float round_sample(float *sum)
+{
+    float sum1=*sum;
+    *sum = 0;
+    return sum1;
 }
 
-#define BF2(a, b, c, d)\
-{\
-    BF(a, b, COS4_0, 1);\
-    BF(c, d,-COS4_0, 1);\
-    tab[c] += tab[d];\
-    tab[a] += tab[c];\
-    tab[c] += tab[b];\
-    tab[b] += tab[d];\
-}
+/* signed 16x16 -> 32 multiply add accumulate */
+#define MACS(rt, ra, rb) rt+=(ra)*(rb)
 
-#define ADD(a, b) tab[a] += tab[b]
+/* signed 16x16 -> 32 multiply */
+#define MULS(ra, rb) ((ra)*(rb))
 
-/* DCT32 without 1/sqrt(2) coef zero scaling. */
-static void dct32(int32_t *out, int32_t *tab)
-{
-    int tmp0, tmp1;
-
-    /* pass 1 */
-    BF( 0, 31, COS0_0 , 1);
-    BF(15, 16, COS0_15, 5);
-    /* pass 2 */
-    BF( 0, 15, COS1_0 , 1);
-    BF(16, 31,-COS1_0 , 1);
-    /* pass 1 */
-    BF( 7, 24, COS0_7 , 1);
-    BF( 8, 23, COS0_8 , 1);
-    /* pass 2 */
-    BF( 7,  8, COS1_7 , 4);
-    BF(23, 24,-COS1_7 , 4);
-    /* pass 3 */
-    BF( 0,  7, COS2_0 , 1);
-    BF( 8, 15,-COS2_0 , 1);
-    BF(16, 23, COS2_0 , 1);
-    BF(24, 31,-COS2_0 , 1);
-    /* pass 1 */
-    BF( 3, 28, COS0_3 , 1);
-    BF(12, 19, COS0_12, 2);
-    /* pass 2 */
-    BF( 3, 12, COS1_3 , 1);
-    BF(19, 28,-COS1_3 , 1);
-    /* pass 1 */
-    BF( 4, 27, COS0_4 , 1);
-    BF(11, 20, COS0_11, 2);
-    /* pass 2 */
-    BF( 4, 11, COS1_4 , 1);
-    BF(20, 27,-COS1_4 , 1);
-    /* pass 3 */
-    BF( 3,  4, COS2_3 , 3);
-    BF(11, 12,-COS2_3 , 3);
-    BF(19, 20, COS2_3 , 3);
-    BF(27, 28,-COS2_3 , 3);
-    /* pass 4 */
-    BF( 0,  3, COS3_0 , 1);
-    BF( 4,  7,-COS3_0 , 1);
-    BF( 8, 11, COS3_0 , 1);
-    BF(12, 15,-COS3_0 , 1);
-    BF(16, 19, COS3_0 , 1);
-    BF(20, 23,-COS3_0 , 1);
-    BF(24, 27, COS3_0 , 1);
-    BF(28, 31,-COS3_0 , 1);
-
-
-
-    /* pass 1 */
-    BF( 1, 30, COS0_1 , 1);
-    BF(14, 17, COS0_14, 3);
-    /* pass 2 */
-    BF( 1, 14, COS1_1 , 1);
-    BF(17, 30,-COS1_1 , 1);
-    /* pass 1 */
-    BF( 6, 25, COS0_6 , 1);
-    BF( 9, 22, COS0_9 , 1);
-    /* pass 2 */
-    BF( 6,  9, COS1_6 , 2);
-    BF(22, 25,-COS1_6 , 2);
-    /* pass 3 */
-    BF( 1,  6, COS2_1 , 1);
-    BF( 9, 14,-COS2_1 , 1);
-    BF(17, 22, COS2_1 , 1);
-    BF(25, 30,-COS2_1 , 1);
-
-    /* pass 1 */
-    BF( 2, 29, COS0_2 , 1);
-    BF(13, 18, COS0_13, 3);
-    /* pass 2 */
-    BF( 2, 13, COS1_2 , 1);
-    BF(18, 29,-COS1_2 , 1);
-    /* pass 1 */
-    BF( 5, 26, COS0_5 , 1);
-    BF(10, 21, COS0_10, 1);
-    /* pass 2 */
-    BF( 5, 10, COS1_5 , 2);
-    BF(21, 26,-COS1_5 , 2);
-    /* pass 3 */
-    BF( 2,  5, COS2_2 , 1);
-    BF(10, 13,-COS2_2 , 1);
-    BF(18, 21, COS2_2 , 1);
-    BF(26, 29,-COS2_2 , 1);
-    /* pass 4 */
-    BF( 1,  2, COS3_1 , 2);
-    BF( 5,  6,-COS3_1 , 2);
-    BF( 9, 10, COS3_1 , 2);
-    BF(13, 14,-COS3_1 , 2);
-    BF(17, 18, COS3_1 , 2);
-    BF(21, 22,-COS3_1 , 2);
-    BF(25, 26, COS3_1 , 2);
-    BF(29, 30,-COS3_1 , 2);
-
-    /* pass 5 */
-    BF1( 0,  1,  2,  3);
-    BF2( 4,  5,  6,  7);
-    BF1( 8,  9, 10, 11);
-    BF2(12, 13, 14, 15);
-    BF1(16, 17, 18, 19);
-    BF2(20, 21, 22, 23);
-    BF1(24, 25, 26, 27);
-    BF2(28, 29, 30, 31);
-
-    /* pass 6 */
-
-    ADD( 8, 12);
-    ADD(12, 10);
-    ADD(10, 14);
-    ADD(14,  9);
-    ADD( 9, 13);
-    ADD(13, 11);
-    ADD(11, 15);
-
-    out[ 0] = tab[0];
-    out[16] = tab[1];
-    out[ 8] = tab[2];
-    out[24] = tab[3];
-    out[ 4] = tab[4];
-    out[20] = tab[5];
-    out[12] = tab[6];
-    out[28] = tab[7];
-    out[ 2] = tab[8];
-    out[18] = tab[9];
-    out[10] = tab[10];
-    out[26] = tab[11];
-    out[ 6] = tab[12];
-    out[22] = tab[13];
-    out[14] = tab[14];
-    out[30] = tab[15];
-
-    ADD(24, 28);
-    ADD(28, 26);
-    ADD(26, 30);
-    ADD(30, 25);
-    ADD(25, 29);
-    ADD(29, 27);
-    ADD(27, 31);
-
-    out[ 1] = tab[16] + tab[24];
-    out[17] = tab[17] + tab[25];
-    out[ 9] = tab[18] + tab[26];
-    out[25] = tab[19] + tab[27];
-    out[ 5] = tab[20] + tab[28];
-    out[21] = tab[21] + tab[29];
-    out[13] = tab[22] + tab[30];
-    out[29] = tab[23] + tab[31];
-    out[ 3] = tab[24] + tab[20];
-    out[19] = tab[25] + tab[21];
-    out[11] = tab[26] + tab[22];
-    out[27] = tab[27] + tab[23];
-    out[ 7] = tab[28] + tab[18];
-    out[23] = tab[29] + tab[19];
-    out[15] = tab[30] + tab[17];
-    out[31] = tab[31];
-}
+#define MLSS(rt, ra, rb) rt-=(ra)*(rb)
 
-#if FRAC_BITS <= 15
+#elif FRAC_BITS <= 15
 
 static inline int round_sample(int *sum)
 {
@@ -749,7 +587,7 @@ static inline int round_sample(int64_t *sum)
 
 #define SUM8P2(sum1, op1, sum2, op2, w1, w2, p) \
 {                                               \
-    int tmp;\
+    INTFLOAT tmp;\
     tmp = p[0 * 64];\
     op1(sum1, (w1)[0 * 64], tmp);\
     op2(sum2, (w2)[0 * 64], tmp);\
@@ -776,15 +614,17 @@ static inline int round_sample(int64_t *sum)
     op2(sum2, (w2)[7 * 64], tmp);\
 }
 
-void av_cold ff_mpa_synth_init(MPA_INT *window)
+void av_cold RENAME(ff_mpa_synth_init)(MPA_INT *window)
 {
-    int i;
+    int i, j;
 
     /* max = 18760, max sum over all 16 coefs : 44736 */
     for(i=0;i<257;i++) {
-        int v;
+        INTFLOAT v;
         v = ff_mpa_enwindow[i];
-#if WFRAC_BITS < 16
+#if CONFIG_FLOAT
+        v *= 1.0 / (1LL<<(16 + FRAC_BITS));
+#elif WFRAC_BITS < 16
         v = (v + (1 << (16 - WFRAC_BITS - 1))) >> (16 - WFRAC_BITS);
 #endif
         window[i] = v;
@@ -793,43 +633,33 @@ void av_cold ff_mpa_synth_init(MPA_INT *window)
         if (i != 0)
             window[512 - i] = v;
     }
+
+    // Needed for avoiding shuffles in ASM implementations
+    for(i=0; i < 8; i++)
+        for(j=0; j < 16; j++)
+            window[512+16*i+j] = window[64*i+32-j];
+
+    for(i=0; i < 8; i++)
+        for(j=0; j < 16; j++)
+            window[512+128+16*i+j] = window[64*i+48-j];
 }
 
-/* 32 sub band synthesis filter. Input: 32 sub band samples, Output:
-   32 samples. */
-/* XXX: optimize by avoiding ring buffer usage */
-void ff_mpa_synth_filter(MPA_INT *synth_buf_ptr, int *synth_buf_offset,
-                         MPA_INT *window, int *dither_state,
-                         OUT_INT *samples, int incr,
-                         int32_t sb_samples[SBLIMIT])
+static void apply_window_mp3_c(MPA_INT *synth_buf, MPA_INT *window,
+                               int *dither_state, OUT_INT *samples, int incr)
 {
-    register MPA_INT *synth_buf;
     register const MPA_INT *w, *w2, *p;
-    int j, offset;
+    int j;
     OUT_INT *samples2;
-#if FRAC_BITS <= 15
-    int32_t tmp[32];
+#if CONFIG_FLOAT
+    float sum, sum2;
+#elif FRAC_BITS <= 15
     int sum, sum2;
 #else
     int64_t sum, sum2;
 #endif
 
-    offset = *synth_buf_offset;
-    synth_buf = synth_buf_ptr + offset;
-
-#if FRAC_BITS <= 15
-    dct32(tmp, sb_samples);
-    for(j=0;j<32;j++) {
-        /* NOTE: can cause a loss in precision if very high amplitude
-           sound */
-        synth_buf[j] = av_clip_int16(tmp[j]);
-    }
-#else
-    dct32(synth_buf, sb_samples);
-#endif
-
     /* copy to avoid wrap */
-    memcpy(synth_buf + 512, synth_buf, 32 * sizeof(MPA_INT));
+    memcpy(synth_buf + 512, synth_buf, 32 * sizeof(*synth_buf));
 
     samples2 = samples + 31 * incr;
     w = window;
@@ -866,15 +696,50 @@ void ff_mpa_synth_filter(MPA_INT *synth_buf_ptr, int *synth_buf_offset,
     SUM8(MLSS, sum, w + 32, p);
     *samples = round_sample(&sum);
     *dither_state= sum;
+}
+
+
+/* 32 sub band synthesis filter. Input: 32 sub band samples, Output:
+   32 samples. */
+/* XXX: optimize by avoiding ring buffer usage */
+#if !CONFIG_FLOAT
+void ff_mpa_synth_filter(MPA_INT *synth_buf_ptr, int *synth_buf_offset,
+                         MPA_INT *window, int *dither_state,
+                         OUT_INT *samples, int incr,
+                         INTFLOAT sb_samples[SBLIMIT])
+{
+    register MPA_INT *synth_buf;
+    int offset;
+#if FRAC_BITS <= 15
+    int32_t tmp[32];
+    int j;
+#endif
+
+    offset = *synth_buf_offset;
+    synth_buf = synth_buf_ptr + offset;
+
+#if FRAC_BITS <= 15
+    dct32(tmp, sb_samples);
+    for(j=0;j<32;j++) {
+        /* NOTE: can cause a loss in precision if very high amplitude
+           sound */
+        synth_buf[j] = av_clip_int16(tmp[j]);
+    }
+#else
+    dct32(synth_buf, sb_samples);
+#endif
+
+    apply_window_mp3_c(synth_buf, window, dither_state, samples, incr);
 
     offset = (offset - 32) & 511;
     *synth_buf_offset = offset;
 }
+#endif
 
 #define C3 FIXHR(0.86602540378443864676/2)
 
 /* 0.5 / cos(pi*(2*i+1)/36) */
-static const int icos36[9] = {
+static const INTFLOAT icos36[9] = {
     FIXR(0.50190991877167369479),
     FIXR(0.51763809020504152469), //0
     FIXR(0.55168895948124587824),
@@ -887,7 +752,7 @@ static const int icos36[9] = {
 };
 
 /* 0.5 / cos(pi*(2*i+1)/36) */
-static const int icos36h[9] = {
+static const INTFLOAT icos36h[9] = {
     FIXHR(0.50190991877167369479/2),
     FIXHR(0.51763809020504152469/2), //0
     FIXHR(0.55168895948124587824/2),
@@ -901,9 +766,9 @@ static const int icos36h[9] = {
 
 /* 12 points IMDCT. We compute it "by hand" by factorizing obvious
    cases. */
-static void imdct12(int *out, int *in)
+static void imdct12(INTFLOAT *out, INTFLOAT *in)
 {
-    int in0, in1, in2, in3, in4, in5, t1, t2;
+    INTFLOAT in0, in1, in2, in3, in4, in5, t1, t2;
 
     in0= in[0*3];
     in1= in[1*3] + in[0*3];
@@ -914,28 +779,28 @@ static void imdct12(int *out, int *in)
     in5 += in3;
     in3 += in1;
 
-    in2= MULH(2*in2, C3);
-    in3= MULH(4*in3, C3);
+    in2= MULH3(in2, C3, 2);
+    in3= MULH3(in3, C3, 4);
 
     t1 = in0 - in4;
-    t2 = MULH(2*(in1 - in5), icos36h[4]);
+    t2 = MULH3(in1 - in5, icos36h[4], 2);
 
     out[ 7]=
     out[10]= t1 + t2;
     out[ 1]=
     out[ 4]= t1 - t2;
 
-    in0 += in4>>1;
+    in0 += SHR(in4, 1);
     in4 = in0 + in2;
     in5 += 2*in1;
-    in1 = MULH(in5 + in3, icos36h[1]);
+    in1 = MULH3(in5 + in3, icos36h[1], 1);
     out[ 8]=
     out[ 9]= in4 + in1;
     out[ 2]=
     out[ 3]= in4 - in1;
 
     in0 -= in2;
-    in5 = MULH(2*(in5 - in3), icos36h[7]);
+    in5 = MULH3(in5 - in3, icos36h[7], 2);
     out[ 0]=
     out[ 5]= in0 - in5;
     out[ 6]=
@@ -954,10 +819,11 @@ static void imdct12(int *out, int *in)
 
 
 /* using Lee like decomposition followed by hand coded 9 points DCT */
-static void imdct36(int *out, int *buf, int *in, int *win)
+static void imdct36(INTFLOAT *out, INTFLOAT *buf, INTFLOAT *in, INTFLOAT *win)
 {
-    int i, j, t0, t1, t2, t3, s0, s1, s2, s3;
-    int tmp[18], *tmp1, *in1;
+    int i, j;
+    INTFLOAT t0, t1, t2, t3, s0, s1, s2, s3;
+    INTFLOAT tmp[18], *tmp1, *in1;
 
     for(i=17;i>=1;i--)
         in[i] += in[i-1];
@@ -967,61 +833,32 @@ static void imdct36(int *out, int *buf, int *in, int *win)
     for(j=0;j<2;j++) {
         tmp1 = tmp + j;
         in1 = in + j;
-#if 0
-//more accurate but slower
-        int64_t t0, t1, t2, t3;
-        t2 = in1[2*4] + in1[2*8] - in1[2*2];
-
-        t3 = (in1[2*0] + (int64_t)(in1[2*6]>>1))<<32;
-        t1 = in1[2*0] - in1[2*6];
-        tmp1[ 6] = t1 - (t2>>1);
-        tmp1[16] = t1 + t2;
-
-        t0 = MUL64(2*(in1[2*2] + in1[2*4]),    C2);
-        t1 = MUL64(   in1[2*4] - in1[2*8] , -2*C8);
-        t2 = MUL64(2*(in1[2*2] + in1[2*8]),   -C4);
-
-        tmp1[10] = (t3 - t0 - t2) >> 32;
-        tmp1[ 2] = (t3 + t0 + t1) >> 32;
-        tmp1[14] = (t3 + t2 - t1) >> 32;
 
-        tmp1[ 4] = MULH(2*(in1[2*5] + in1[2*7] - in1[2*1]), -C3);
-        t2 = MUL64(2*(in1[2*1] + in1[2*5]),    C1);
-        t3 = MUL64(   in1[2*5] - in1[2*7] , -2*C7);
-        t0 = MUL64(2*in1[2*3], C3);
-
-        t1 = MUL64(2*(in1[2*1] + in1[2*7]),   -C5);
-
-        tmp1[ 0] = (t2 + t3 + t0) >> 32;
-        tmp1[12] = (t2 + t1 - t0) >> 32;
-        tmp1[ 8] = (t3 - t1 - t0) >> 32;
-#else
         t2 = in1[2*4] + in1[2*8] - in1[2*2];
 
-        t3 = in1[2*0] + (in1[2*6]>>1);
+        t3 = in1[2*0] + SHR(in1[2*6],1);
         t1 = in1[2*0] - in1[2*6];
-        tmp1[ 6] = t1 - (t2>>1);
+        tmp1[ 6] = t1 - SHR(t2,1);
         tmp1[16] = t1 + t2;
 
-        t0 = MULH(2*(in1[2*2] + in1[2*4]),    C2);
-        t1 = MULH(   in1[2*4] - in1[2*8] , -2*C8);
-        t2 = MULH(2*(in1[2*2] + in1[2*8]),   -C4);
+        t0 = MULH3(in1[2*2] + in1[2*4] ,    C2, 2);
+        t1 = MULH3(in1[2*4] - in1[2*8] , -2*C8, 1);
+        t2 = MULH3(in1[2*2] + in1[2*8] ,   -C4, 2);
 
         tmp1[10] = t3 - t0 - t2;
         tmp1[ 2] = t3 + t0 + t1;
         tmp1[14] = t3 + t2 - t1;
 
-        tmp1[ 4] = MULH(2*(in1[2*5] + in1[2*7] - in1[2*1]), -C3);
-        t2 = MULH(2*(in1[2*1] + in1[2*5]),    C1);
-        t3 = MULH(   in1[2*5] - in1[2*7] , -2*C7);
-        t0 = MULH(2*in1[2*3], C3);
+        tmp1[ 4] = MULH3(in1[2*5] + in1[2*7] - in1[2*1], -C3, 2);
+        t2 = MULH3(in1[2*1] + in1[2*5],    C1, 2);
+        t3 = MULH3(in1[2*5] - in1[2*7], -2*C7, 1);
+        t0 = MULH3(in1[2*3], C3, 2);
 
-        t1 = MULH(2*(in1[2*1] + in1[2*7]),   -C5);
+        t1 = MULH3(in1[2*1] + in1[2*7],   -C5, 2);
 
         tmp1[ 0] = t2 + t3 + t0;
         tmp1[12] = t2 + t1 - t0;
         tmp1[ 8] = t3 - t1 - t0;
-#endif
     }
 
     i = 0;
@@ -1033,33 +870,33 @@ static void imdct36(int *out, int *buf, int *in, int *win)
 
         t2 = tmp[i + 1];
         t3 = tmp[i + 3];
-        s1 = MULH(2*(t3 + t2), icos36h[j]);
-        s3 = MULL(t3 - t2, icos36[8 - j], FRAC_BITS);
+        s1 = MULH3(t3 + t2, icos36h[j], 2);
+        s3 = MULLx(t3 - t2, icos36[8 - j], FRAC_BITS);
 
         t0 = s0 + s1;
         t1 = s0 - s1;
-        out[(9 + j)*SBLIMIT] =  MULH(t1, win[9 + j]) + buf[9 + j];
-        out[(8 - j)*SBLIMIT] =  MULH(t1, win[8 - j]) + buf[8 - j];
-        buf[9 + j] = MULH(t0, win[18 + 9 + j]);
-        buf[8 - j] = MULH(t0, win[18 + 8 - j]);
+        out[(9 + j)*SBLIMIT] =  MULH3(t1, win[9 + j], 1) + buf[9 + j];
+        out[(8 - j)*SBLIMIT] =  MULH3(t1, win[8 - j], 1) + buf[8 - j];
+        buf[9 + j] = MULH3(t0, win[18 + 9 + j], 1);
+        buf[8 - j] = MULH3(t0, win[18 + 8 - j], 1);
 
         t0 = s2 + s3;
         t1 = s2 - s3;
-        out[(9 + 8 - j)*SBLIMIT] =  MULH(t1, win[9 + 8 - j]) + buf[9 + 8 - j];
-        out[(        j)*SBLIMIT] =  MULH(t1, win[        j]) + buf[        j];
-        buf[9 + 8 - j] = MULH(t0, win[18 + 9 + 8 - j]);
-        buf[      + j] = MULH(t0, win[18         + j]);
+        out[(9 + 8 - j)*SBLIMIT] =  MULH3(t1, win[9 + 8 - j], 1) + buf[9 + 8 - j];
+        out[(        j)*SBLIMIT] =  MULH3(t1, win[        j], 1) + buf[        j];
+        buf[9 + 8 - j] = MULH3(t0, win[18 + 9 + 8 - j], 1);
+        buf[      + j] = MULH3(t0, win[18         + j], 1);
         i += 4;
     }
 
     s0 = tmp[16];
-    s1 = MULH(2*tmp[17], icos36h[4]);
+    s1 = MULH3(tmp[17], icos36h[4], 2);
     t0 = s0 + s1;
     t1 = s0 - s1;
-    out[(9 + 4)*SBLIMIT] =  MULH(t1, win[9 + 4]) + buf[9 + 4];
-    out[(8 - 4)*SBLIMIT] =  MULH(t1, win[8 - 4]) + buf[8 - 4];
-    buf[9 + 4] = MULH(t0, win[18 + 9 + 4]);
-    buf[8 - 4] = MULH(t0, win[18 + 8 - 4]);
+    out[(9 + 4)*SBLIMIT] =  MULH3(t1, win[9 + 4], 1) + buf[9 + 4];
+    out[(8 - 4)*SBLIMIT] =  MULH3(t1, win[8 - 4], 1) + buf[8 - 4];
+    buf[9 + 4] = MULH3(t0, win[18 + 9 + 4], 1);
+    buf[8 - 4] = MULH3(t0, win[18 + 8 - 4], 1);
 }
 
 /* return the number of decoded frames */
@@ -1150,7 +987,7 @@ static int mp_decode_layer2(MPADecodeContext *s)
     else
         bound = sblimit;
 
-    dprintf(s->avctx, "bound=%d sblimit=%d\n", bound, sblimit);
+    av_dlog(s->avctx, "bound=%d sblimit=%d\n", bound, sblimit);
 
     /* sanity check */
     if( bound > sblimit ) bound = sblimit;
@@ -1225,17 +1062,18 @@ static int mp_decode_layer2(MPADecodeContext *s)
                         qindex = alloc_table[j+b];
                         bits = ff_mpa_quant_bits[qindex];
                         if (bits < 0) {
+                            int v2;
                             /* 3 values at the same time */
                             v = get_bits(&s->gb, -bits);
-                            steps = ff_mpa_quant_steps[qindex];
+                            v2 = division_tabs[qindex][v];
+                            steps  = ff_mpa_quant_steps[qindex];
+
                             s->sb_samples[ch][k * 12 + l + 0][i] =
-                                l2_unscale_group(steps, v % steps, scale);
-                            v = v / steps;
+                                l2_unscale_group(steps, v2        & 15, scale);
                             s->sb_samples[ch][k * 12 + l + 1][i] =
-                                l2_unscale_group(steps, v % steps, scale);
-                            v = v / steps;
+                                l2_unscale_group(steps, (v2 >> 4) & 15, scale);
                             s->sb_samples[ch][k * 12 + l + 2][i] =
-                                l2_unscale_group(steps, v, scale);
+                                l2_unscale_group(steps,  v2 >> 8      , scale);
                         } else {
                             for(m=0;m<3;m++) {
                                 v = get_bits(&s->gb, bits);
@@ -1404,6 +1242,22 @@ static void switch_buffer(MPADecodeContext *s, int *pos, int *end_pos, int *end_
     }
 }
 
+/* Following is a optimized code for
+            INTFLOAT v = *src
+            if(get_bits1(&s->gb))
+                v = -v;
+            *dst = v;
+*/
+#if CONFIG_FLOAT
+#define READ_FLIP_SIGN(dst,src)\
+            v = AV_RN32A(src) ^ (get_bits1(&s->gb)<<31);\
+            AV_WN32A(dst, v);
+#else
+#define READ_FLIP_SIGN(dst,src)\
+            v= -get_bits1(&s->gb);\
+            *(dst) = (*(src) ^ v) - v;
+#endif
+
 static int huffman_decode(MPADecodeContext *s, GranuleDef *g,
                           int16_t *exponents, int end_pos2)
 {
@@ -1434,7 +1288,8 @@ static int huffman_decode(MPADecodeContext *s, GranuleDef *g,
 
         /* read huffcode and compute each couple */
         for(;j>0;j--) {
-            int exponent, x, y, v;
+            int exponent, x, y;
+            int v;
             int pos= get_bits_count(&s->gb);
 
             if (pos >= end_pos){
@@ -1455,43 +1310,42 @@ static int huffman_decode(MPADecodeContext *s, GranuleDef *g,
 
             exponent= exponents[s_index];
 
-            dprintf(s->avctx, "region=%d n=%d x=%d y=%d exp=%d\n",
+            av_dlog(s->avctx, "region=%d n=%d x=%d y=%d exp=%d\n",
                     i, g->region_size[i] - j, x, y, exponent);
             if(y&16){
                 x = y >> 5;
                 y = y & 0x0f;
                 if (x < 15){
-                    v = expval_table[ exponent ][ x ];
-//                      v = expval_table[ (exponent&3) ][ x ] >> FFMIN(0 - (exponent>>2), 31);
+                    READ_FLIP_SIGN(g->sb_hybrid+s_index, RENAME(expval_table)[ exponent ]+x)
                 }else{
                     x += get_bitsz(&s->gb, linbits);
                     v = l3_unscale(x, exponent);
+                    if (get_bits1(&s->gb))
+                        v = -v;
+                    g->sb_hybrid[s_index] = v;
                 }
-                if (get_bits1(&s->gb))
-                    v = -v;
-                g->sb_hybrid[s_index] = v;
                 if (y < 15){
-                    v = expval_table[ exponent ][ y ];
+                    READ_FLIP_SIGN(g->sb_hybrid+s_index+1, RENAME(expval_table)[ exponent ]+y)
                 }else{
                     y += get_bitsz(&s->gb, linbits);
                     v = l3_unscale(y, exponent);
+                    if (get_bits1(&s->gb))
+                        v = -v;
+                    g->sb_hybrid[s_index+1] = v;
                 }
-                if (get_bits1(&s->gb))
-                    v = -v;
-                g->sb_hybrid[s_index+1] = v;
             }else{
                 x = y >> 5;
                 y = y & 0x0f;
                 x += y;
                 if (x < 15){
-                    v = expval_table[ exponent ][ x ];
+                    READ_FLIP_SIGN(g->sb_hybrid+s_index+!!y, RENAME(expval_table)[ exponent ]+x)
                 }else{
                     x += get_bitsz(&s->gb, linbits);
                     v = l3_unscale(x, exponent);
+                    if (get_bits1(&s->gb))
+                        v = -v;
+                    g->sb_hybrid[s_index+!!y] = v;
                 }
-                if (get_bits1(&s->gb))
-                    v = -v;
-                g->sb_hybrid[s_index+!!y] = v;
                 g->sb_hybrid[s_index+ !y] = 0;
             }
             s_index+=2;
@@ -1524,7 +1378,7 @@ static int huffman_decode(MPADecodeContext *s, GranuleDef *g,
         last_pos= pos;
 
         code = get_vlc2(&s->gb, vlc->table, vlc->bits, 1);
-        dprintf(s->avctx, "t=%d code=%d\n", g->count1table_select, code);
+        av_dlog(s->avctx, "t=%d code=%d\n", g->count1table_select, code);
         g->sb_hybrid[s_index+0]=
         g->sb_hybrid[s_index+1]=
         g->sb_hybrid[s_index+2]=
@@ -1534,11 +1388,7 @@ static int huffman_decode(MPADecodeContext *s, GranuleDef *g,
             int v;
             int pos= s_index+idxtab[code];
             code ^= 8>>idxtab[code];
-            v = exp_table[ exponents[pos] ];
-//            v = exp_table[ (exponents[pos]&3) ] >> FFMIN(0 - (exponents[pos]>>2), 31);
-            if(get_bits1(&s->gb))
-                v = -v;
-            g->sb_hybrid[pos] = v;
+            READ_FLIP_SIGN(g->sb_hybrid+pos, RENAME(exp_table)+exponents[pos])
         }
         s_index+=4;
     }
@@ -1567,8 +1417,8 @@ static int huffman_decode(MPADecodeContext *s, GranuleDef *g,
 static void reorder_block(MPADecodeContext *s, GranuleDef *g)
 {
     int i, j, len;
-    int32_t *ptr, *dst, *ptr1;
-    int32_t tmp[576];
+    INTFLOAT *ptr, *dst, *ptr1;
+    INTFLOAT tmp[576];
 
     if (g->block_type != 2)
         return;
@@ -1604,10 +1454,8 @@ static void compute_stereo(MPADecodeContext *s,
                            GranuleDef *g0, GranuleDef *g1)
 {
     int i, j, k, l;
-    int32_t v1, v2;
-    int sf_max, tmp0, tmp1, sf, len, non_zero_found;
-    int32_t (*is_tab)[16];
-    int32_t *tab0, *tab1;
+    int sf_max, sf, len, non_zero_found;
+    INTFLOAT (*is_tab)[16], *tab0, *tab1, tmp0, tmp1, v1, v2;
     int non_zero_found_short[3];
 
     /* intensity stereo */
@@ -1651,8 +1499,8 @@ static void compute_stereo(MPADecodeContext *s,
                     v2 = is_tab[1][sf];
                     for(j=0;j<len;j++) {
                         tmp0 = tab0[j];
-                        tab0[j] = MULL(tmp0, v1, FRAC_BITS);
-                        tab1[j] = MULL(tmp0, v2, FRAC_BITS);
+                        tab0[j] = MULLx(tmp0, v1, FRAC_BITS);
+                        tab1[j] = MULLx(tmp0, v2, FRAC_BITS);
                     }
                 } else {
                 found1:
@@ -1662,8 +1510,8 @@ static void compute_stereo(MPADecodeContext *s,
                         for(j=0;j<len;j++) {
                             tmp0 = tab0[j];
                             tmp1 = tab1[j];
-                            tab0[j] = MULL(tmp0 + tmp1, ISQRT2, FRAC_BITS);
-                            tab1[j] = MULL(tmp0 - tmp1, ISQRT2, FRAC_BITS);
+                            tab0[j] = MULLx(tmp0 + tmp1, ISQRT2, FRAC_BITS);
+                            tab1[j] = MULLx(tmp0 - tmp1, ISQRT2, FRAC_BITS);
                         }
                     }
                 }
@@ -1695,8 +1543,8 @@ static void compute_stereo(MPADecodeContext *s,
                 v2 = is_tab[1][sf];
                 for(j=0;j<len;j++) {
                     tmp0 = tab0[j];
-                    tab0[j] = MULL(tmp0, v1, FRAC_BITS);
-                    tab1[j] = MULL(tmp0, v2, FRAC_BITS);
+                    tab0[j] = MULLx(tmp0, v1, FRAC_BITS);
+                    tab1[j] = MULLx(tmp0, v2, FRAC_BITS);
                 }
             } else {
             found2:
@@ -1706,8 +1554,8 @@ static void compute_stereo(MPADecodeContext *s,
                     for(j=0;j<len;j++) {
                         tmp0 = tab0[j];
                         tmp1 = tab1[j];
-                        tab0[j] = MULL(tmp0 + tmp1, ISQRT2, FRAC_BITS);
-                        tab1[j] = MULL(tmp0 - tmp1, ISQRT2, FRAC_BITS);
+                        tab0[j] = MULLx(tmp0 + tmp1, ISQRT2, FRAC_BITS);
+                        tab1[j] = MULLx(tmp0 - tmp1, ISQRT2, FRAC_BITS);
                     }
                 }
             }
@@ -1727,6 +1575,7 @@ static void compute_stereo(MPADecodeContext *s,
     }
 }
 
+#if !CONFIG_FLOAT
 static void compute_antialias_integer(MPADecodeContext *s,
                               GranuleDef *g)
 {
@@ -1766,62 +1615,25 @@ static void compute_antialias_integer(MPADecodeContext *s,
         ptr += 18;
     }
 }
-
-static void compute_antialias_float(MPADecodeContext *s,
-                              GranuleDef *g)
-{
-    int32_t *ptr;
-    int n, i;
-
-    /* we antialias only "long" bands */
-    if (g->block_type == 2) {
-        if (!g->switch_point)
-            return;
-        /* XXX: check this for 8000Hz case */
-        n = 1;
-    } else {
-        n = SBLIMIT - 1;
-    }
-
-    ptr = g->sb_hybrid + 18;
-    for(i = n;i > 0;i--) {
-        float tmp0, tmp1;
-        float *csa = &csa_table_float[0][0];
-#define FLOAT_AA(j)\
-        tmp0= ptr[-1-j];\
-        tmp1= ptr[   j];\
-        ptr[-1-j] = lrintf(tmp0 * csa[0+4*j] - tmp1 * csa[1+4*j]);\
-        ptr[   j] = lrintf(tmp0 * csa[1+4*j] + tmp1 * csa[0+4*j]);
-
-        FLOAT_AA(0)
-        FLOAT_AA(1)
-        FLOAT_AA(2)
-        FLOAT_AA(3)
-        FLOAT_AA(4)
-        FLOAT_AA(5)
-        FLOAT_AA(6)
-        FLOAT_AA(7)
-
-        ptr += 18;
-    }
-}
+#endif
 
 static void compute_imdct(MPADecodeContext *s,
                           GranuleDef *g,
-                          int32_t *sb_samples,
-                          int32_t *mdct_buf)
+                          INTFLOAT *sb_samples,
+                          INTFLOAT *mdct_buf)
 {
-    int32_t *ptr, *win, *win1, *buf, *out_ptr, *ptr1;
-    int32_t out2[12];
-    int i, j, mdct_long_end, v, sblimit;
+    INTFLOAT *win, *win1, *out_ptr, *ptr, *buf, *ptr1;
+    INTFLOAT out2[12];
+    int i, j, mdct_long_end, sblimit;
 
     /* find last non zero block */
     ptr = g->sb_hybrid + 576;
     ptr1 = g->sb_hybrid + 2 * 18;
     while (ptr >= ptr1) {
+        int32_t *p;
         ptr -= 6;
-        v = ptr[0] | ptr[1] | ptr[2] | ptr[3] | ptr[4] | ptr[5];
-        if (v != 0)
+        p= (int32_t*)ptr;
+        if(p[0] | p[1] | p[2] | p[3] | p[4] | p[5])
             break;
     }
     sblimit = ((ptr - g->sb_hybrid) / 18) + 1;
@@ -1864,20 +1676,20 @@ static void compute_imdct(MPADecodeContext *s,
         }
         imdct12(out2, ptr + 0);
         for(i=0;i<6;i++) {
-            *out_ptr = MULH(out2[i], win[i]) + buf[i + 6*1];
-            buf[i + 6*2] = MULH(out2[i + 6], win[i + 6]);
+            *out_ptr     = MULH3(out2[i    ], win[i    ], 1) + buf[i + 6*1];
+            buf[i + 6*2] = MULH3(out2[i + 6], win[i + 6], 1);
             out_ptr += SBLIMIT;
         }
         imdct12(out2, ptr + 1);
         for(i=0;i<6;i++) {
-            *out_ptr = MULH(out2[i], win[i]) + buf[i + 6*2];
-            buf[i + 6*0] = MULH(out2[i + 6], win[i + 6]);
+            *out_ptr     = MULH3(out2[i    ], win[i    ], 1) + buf[i + 6*2];
+            buf[i + 6*0] = MULH3(out2[i + 6], win[i + 6], 1);
             out_ptr += SBLIMIT;
         }
         imdct12(out2, ptr + 2);
         for(i=0;i<6;i++) {
-            buf[i + 6*0] = MULH(out2[i], win[i]) + buf[i + 6*0];
-            buf[i + 6*1] = MULH(out2[i + 6], win[i + 6]);
+            buf[i + 6*0] = MULH3(out2[i    ], win[i    ], 1) + buf[i + 6*0];
+            buf[i + 6*1] = MULH3(out2[i + 6], win[i + 6], 1);
             buf[i + 6*2] = 0;
         }
         ptr += 18;
@@ -1902,7 +1714,7 @@ static int mp_decode_layer3(MPADecodeContext *s)
     int nb_granules, main_data_begin, private_bits;
     int gr, ch, blocksplit_flag, i, j, k, n, bits_pos;
     GranuleDef *g;
-    int16_t exponents[576];
+    int16_t exponents[576]; //FIXME try INTFLOAT
 
     /* read side info */
     if (s->lsf) {
@@ -1924,7 +1736,7 @@ static int mp_decode_layer3(MPADecodeContext *s)
 
     for(gr=0;gr<nb_granules;gr++) {
         for(ch=0;ch<s->nb_channels;ch++) {
-            dprintf(s->avctx, "gr=%d ch=%d: side_info\n", gr, ch);
+            av_dlog(s->avctx, "gr=%d ch=%d: side_info\n", gr, ch);
             g = &s->granules[ch][gr];
             g->part2_3_length = get_bits(&s->gb, 12);
             g->big_values = get_bits(&s->gb, 9);
@@ -1965,7 +1777,7 @@ static int mp_decode_layer3(MPADecodeContext *s)
                 /* compute huffman coded region sizes */
                 region_address1 = get_bits(&s->gb, 4);
                 region_address2 = get_bits(&s->gb, 3);
-                dprintf(s->avctx, "region1=%d region2=%d\n",
+                av_dlog(s->avctx, "region1=%d region2=%d\n",
                         region_address1, region_address2);
                 ff_init_long_region(s, g, region_address1, region_address2);
             }
@@ -1977,7 +1789,7 @@ static int mp_decode_layer3(MPADecodeContext *s)
                 g->preflag = get_bits1(&s->gb);
             g->scalefac_scale = get_bits1(&s->gb);
             g->count1table_select = get_bits1(&s->gb);
-            dprintf(s->avctx, "block_type=%d switch_point=%d\n",
+            av_dlog(s->avctx, "block_type=%d switch_point=%d\n",
                     g->block_type, g->switch_point);
         }
     }
@@ -1986,7 +1798,7 @@ static int mp_decode_layer3(MPADecodeContext *s)
     const uint8_t *ptr = s->gb.buffer + (get_bits_count(&s->gb)>>3);
     assert((get_bits_count(&s->gb) & 7) == 0);
     /* now we get bits from the main_data_begin offset */
-    dprintf(s->avctx, "seekback: %d\n", main_data_begin);
+    av_dlog(s->avctx, "seekback: %d\n", main_data_begin);
 //av_log(NULL, AV_LOG_ERROR, "backstep:%d, lastbuf:%d\n", main_data_begin, s->last_buf_size);
 
     memcpy(s->last_buf + s->last_buf_size, ptr, EXTRABYTES);
@@ -2020,7 +1832,7 @@ static int mp_decode_layer3(MPADecodeContext *s)
                 /* MPEG1 scale factors */
                 slen1 = slen_table[0][g->scalefac_compress];
                 slen2 = slen_table[1][g->scalefac_compress];
-                dprintf(s->avctx, "slen1=%d slen2=%d\n", slen1, slen2);
+                av_dlog(s->avctx, "slen1=%d slen2=%d\n", slen1, slen2);
                 if (g->block_type == 2) {
                     n = g->switch_point ? 17 : 18;
                     j = 0;
@@ -2132,7 +1944,7 @@ static int mp_decode_layer3(MPADecodeContext *s)
             g = &s->granules[ch][gr];
 
             reorder_block(s, g);
-            s->compute_antialias(s, g);
+            compute_antialias(s, g);
             compute_imdct(s, g, &s->sb_samples[ch][18 * gr][0], s->mdct_buf[ch]);
         }
     } /* gr */
@@ -2153,7 +1965,7 @@ static int mp_decode_frame(MPADecodeContext *s,
     if (s->error_protection)
         skip_bits(&s->gb, 16);
 
-    dprintf(s->avctx, "frame %d:\n", s->frame_count);
+    av_dlog(s->avctx, "frame %d:\n", s->frame_count);
     switch(s->layer) {
     case 1:
         s->avctx->frame_size = 384;
@@ -2201,8 +2013,12 @@ static int mp_decode_frame(MPADecodeContext *s,
     for(ch=0;ch<s->nb_channels;ch++) {
         samples_ptr = samples + ch;
         for(i=0;i<nb_frames;i++) {
-            ff_mpa_synth_filter(s->synth_buf[ch], &(s->synth_buf_offset[ch]),
-                         ff_mpa_synth_window, &s->dither_state,
+            RENAME(ff_mpa_synth_filter)(
+#if CONFIG_FLOAT
+                         s,
+#endif
+                         s->synth_buf[ch], &(s->synth_buf_offset[ch]),
+                         RENAME(ff_mpa_synth_window), &s->dither_state,
                          samples_ptr, s->nb_channels,
                          s->sb_samples[ch][i]);
             samples_ptr += 32 * s->nb_channels;
@@ -2239,7 +2055,9 @@ static int decode_frame(AVCodecContext * avctx,
     }
     /* update codec info */
     avctx->channels = s->nb_channels;
-    avctx->bit_rate = s->bit_rate;
+    avctx->channel_layout = s->nb_channels == 1 ? AV_CH_LAYOUT_MONO : AV_CH_LAYOUT_STEREO;
+    if (!avctx->bit_rate)
+        avctx->bit_rate = s->bit_rate;
     avctx->sub_id = s->layer;
 
     if(*data_size < 1152*avctx->channels*sizeof(OUT_INT))
@@ -2271,7 +2089,7 @@ static void flush(AVCodecContext *avctx){
     s->last_buf_size= 0;
 }
 
-#if CONFIG_MP3ADU_DECODER
+#if CONFIG_MP3ADU_DECODER || CONFIG_MP3ADUFLOAT_DECODER
 static int decode_frame_adu(AVCodecContext * avctx,
                         void *data, int *data_size,
                         AVPacket *avpkt)
@@ -2307,7 +2125,8 @@ static int decode_frame_adu(AVCodecContext * avctx,
     /* update codec info */
     avctx->sample_rate = s->sample_rate;
     avctx->channels = s->nb_channels;
-    avctx->bit_rate = s->bit_rate;
+    if (!avctx->bit_rate)
+        avctx->bit_rate = s->bit_rate;
     avctx->sub_id = s->layer;
 
     s->frame_size = len;
@@ -2321,9 +2140,9 @@ static int decode_frame_adu(AVCodecContext * avctx,
     *data_size = out_size;
     return buf_size;
 }
-#endif /* CONFIG_MP3ADU_DECODER */
+#endif /* CONFIG_MP3ADU_DECODER || CONFIG_MP3ADUFLOAT_DECODER */
 
-#if CONFIG_MP3ON4_DECODER
+#if CONFIG_MP3ON4_DECODER || CONFIG_MP3ON4FLOAT_DECODER
 
 /**
  * Context for MP3On4 decoder
@@ -2396,7 +2215,6 @@ static int decode_init_mp3on4(AVCodecContext * avctx)
      */
     for (i = 1; i < s->frames; i++) {
         s->mp3decctx[i] = av_mallocz(sizeof(MPADecodeContext));
-        s->mp3decctx[i]->compute_antialias = s->mp3decctx[0]->compute_antialias;
         s->mp3decctx[i]->adu_mode = 1;
         s->mp3decctx[i]->avctx = avctx;
     }
@@ -2411,8 +2229,7 @@ static av_cold int decode_close_mp3on4(AVCodecContext * avctx)
     int i;
 
     for (i = 0; i < s->frames; i++)
-        if (s->mp3decctx[i])
-            av_free(s->mp3decctx[i]);
+        av_free(s->mp3decctx[i]);
 
     return 0;
 }
@@ -2488,10 +2305,11 @@ static int decode_frame_mp3on4(AVCodecContext * avctx,
     *data_size = out_size;
     return buf_size;
 }
-#endif /* CONFIG_MP3ON4_DECODER */
+#endif /* CONFIG_MP3ON4_DECODER || CONFIG_MP3ON4FLOAT_DECODER */
 
+#if !CONFIG_FLOAT
 #if CONFIG_MP1_DECODER
-AVCodec mp1_decoder =
+AVCodec ff_mp1_decoder =
 {
     "mp1",
     AVMEDIA_TYPE_AUDIO,
@@ -2507,7 +2325,7 @@ AVCodec mp1_decoder =
 };
 #endif
 #if CONFIG_MP2_DECODER
-AVCodec mp2_decoder =
+AVCodec ff_mp2_decoder =
 {
     "mp2",
     AVMEDIA_TYPE_AUDIO,
@@ -2523,7 +2341,7 @@ AVCodec mp2_decoder =
 };
 #endif
 #if CONFIG_MP3_DECODER
-AVCodec mp3_decoder =
+AVCodec ff_mp3_decoder =
 {
     "mp3",
     AVMEDIA_TYPE_AUDIO,
@@ -2539,7 +2357,7 @@ AVCodec mp3_decoder =
 };
 #endif
 #if CONFIG_MP3ADU_DECODER
-AVCodec mp3adu_decoder =
+AVCodec ff_mp3adu_decoder =
 {
     "mp3adu",
     AVMEDIA_TYPE_AUDIO,
@@ -2555,7 +2373,7 @@ AVCodec mp3adu_decoder =
 };
 #endif
 #if CONFIG_MP3ON4_DECODER
-AVCodec mp3on4_decoder =
+AVCodec ff_mp3on4_decoder =
 {
     "mp3on4",
     AVMEDIA_TYPE_AUDIO,
@@ -2569,3 +2387,4 @@ AVCodec mp3on4_decoder =
     .long_name= NULL_IF_CONFIG_SMALL("MP3onMP4"),
 };
 #endif
+#endif
diff --git a/libavcodec/mpegaudiodec_float.c b/libavcodec/mpegaudiodec_float.c
new file mode 100644
index 0000000..e9041fc
--- /dev/null
+++ b/libavcodec/mpegaudiodec_float.c
@@ -0,0 +1,168 @@
+/*
+ * Float MPEG Audio decoder
+ * Copyright (c) 2010 Michael Niedermayer
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#define CONFIG_FLOAT 1
+#include "mpegaudiodec.c"
+
+void ff_mpa_synth_filter_float(MPADecodeContext *s, float *synth_buf_ptr,
+                               int *synth_buf_offset,
+                               float *window, int *dither_state,
+                               float *samples, int incr,
+                               float sb_samples[SBLIMIT])
+{
+    float *synth_buf;
+    int offset;
+
+    offset = *synth_buf_offset;
+    synth_buf = synth_buf_ptr + offset;
+
+    s->dct.dct32(synth_buf, sb_samples);
+    s->apply_window_mp3(synth_buf, window, dither_state, samples, incr);
+
+    offset = (offset - 32) & 511;
+    *synth_buf_offset = offset;
+}
+
+static void compute_antialias_float(MPADecodeContext *s,
+                              GranuleDef *g)
+{
+    float *ptr;
+    int n, i;
+
+    /* we antialias only "long" bands */
+    if (g->block_type == 2) {
+        if (!g->switch_point)
+            return;
+        /* XXX: check this for 8000Hz case */
+        n = 1;
+    } else {
+        n = SBLIMIT - 1;
+    }
+
+    ptr = g->sb_hybrid + 18;
+    for(i = n;i > 0;i--) {
+        float tmp0, tmp1;
+        float *csa = &csa_table_float[0][0];
+#define FLOAT_AA(j)\
+        tmp0= ptr[-1-j];\
+        tmp1= ptr[   j];\
+        ptr[-1-j] = tmp0 * csa[0+4*j] - tmp1 * csa[1+4*j];\
+        ptr[   j] = tmp0 * csa[1+4*j] + tmp1 * csa[0+4*j];
+
+        FLOAT_AA(0)
+        FLOAT_AA(1)
+        FLOAT_AA(2)
+        FLOAT_AA(3)
+        FLOAT_AA(4)
+        FLOAT_AA(5)
+        FLOAT_AA(6)
+        FLOAT_AA(7)
+
+        ptr += 18;
+    }
+}
+
+static av_cold int decode_end(AVCodecContext * avctx)
+{
+    MPADecodeContext *s = avctx->priv_data;
+    ff_dct_end(&s->dct);
+    return 0;
+}
+
+#if CONFIG_MP1FLOAT_DECODER
+AVCodec ff_mp1float_decoder =
+{
+    "mp1float",
+    AVMEDIA_TYPE_AUDIO,
+    CODEC_ID_MP1,
+    sizeof(MPADecodeContext),
+    decode_init,
+    NULL,
+    decode_end,
+    decode_frame,
+    CODEC_CAP_PARSE_ONLY,
+    .flush= flush,
+    .long_name= NULL_IF_CONFIG_SMALL("MP1 (MPEG audio layer 1)"),
+};
+#endif
+#if CONFIG_MP2FLOAT_DECODER
+AVCodec ff_mp2float_decoder =
+{
+    "mp2float",
+    AVMEDIA_TYPE_AUDIO,
+    CODEC_ID_MP2,
+    sizeof(MPADecodeContext),
+    decode_init,
+    NULL,
+    decode_end,
+    decode_frame,
+    CODEC_CAP_PARSE_ONLY,
+    .flush= flush,
+    .long_name= NULL_IF_CONFIG_SMALL("MP2 (MPEG audio layer 2)"),
+};
+#endif
+#if CONFIG_MP3FLOAT_DECODER
+AVCodec ff_mp3float_decoder =
+{
+    "mp3float",
+    AVMEDIA_TYPE_AUDIO,
+    CODEC_ID_MP3,
+    sizeof(MPADecodeContext),
+    decode_init,
+    NULL,
+    decode_end,
+    decode_frame,
+    CODEC_CAP_PARSE_ONLY,
+    .flush= flush,
+    .long_name= NULL_IF_CONFIG_SMALL("MP3 (MPEG audio layer 3)"),
+};
+#endif
+#if CONFIG_MP3ADUFLOAT_DECODER
+AVCodec ff_mp3adufloat_decoder =
+{
+    "mp3adufloat",
+    AVMEDIA_TYPE_AUDIO,
+    CODEC_ID_MP3ADU,
+    sizeof(MPADecodeContext),
+    decode_init,
+    NULL,
+    decode_end,
+    decode_frame_adu,
+    CODEC_CAP_PARSE_ONLY,
+    .flush= flush,
+    .long_name= NULL_IF_CONFIG_SMALL("ADU (Application Data Unit) MP3 (MPEG audio layer 3)"),
+};
+#endif
+#if CONFIG_MP3ON4FLOAT_DECODER
+AVCodec ff_mp3on4float_decoder =
+{
+    "mp3on4float",
+    AVMEDIA_TYPE_AUDIO,
+    CODEC_ID_MP3ON4,
+    sizeof(MP3On4DecodeContext),
+    decode_init_mp3on4,
+    NULL,
+    decode_close_mp3on4,
+    decode_frame_mp3on4,
+    .flush= flush,
+    .long_name= NULL_IF_CONFIG_SMALL("MP3onMP4"),
+};
+#endif
diff --git a/libavcodec/mpegaudiodecheader.c b/libavcodec/mpegaudiodecheader.c
index 67f882f..a0bd4fc 100644
--- a/libavcodec/mpegaudiodecheader.c
+++ b/libavcodec/mpegaudiodecheader.c
@@ -2,20 +2,20 @@
  * MPEG Audio header decoder
  * Copyright (c) 2001, 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -91,20 +91,20 @@ int ff_mpegaudio_decode_header(MPADecodeHeader *s, uint32_t header)
     }
 
 #if defined(DEBUG)
-    dprintf(NULL, "layer%d, %d Hz, %d kbits/s, ",
+    av_dlog(NULL, "layer%d, %d Hz, %d kbits/s, ",
            s->layer, s->sample_rate, s->bit_rate);
     if (s->nb_channels == 2) {
         if (s->layer == 3) {
             if (s->mode_ext & MODE_EXT_MS_STEREO)
-                dprintf(NULL, "ms-");
+                av_dlog(NULL, "ms-");
             if (s->mode_ext & MODE_EXT_I_STEREO)
-                dprintf(NULL, "i-");
+                av_dlog(NULL, "i-");
         }
-        dprintf(NULL, "stereo");
+        av_dlog(NULL, "stereo");
     } else {
-        dprintf(NULL, "mono");
+        av_dlog(NULL, "mono");
     }
-    dprintf(NULL, "\n");
+    av_dlog(NULL, "\n");
 #endif
     return 0;
 }
diff --git a/libavcodec/mpegaudiodecheader.h b/libavcodec/mpegaudiodecheader.h
index 5578618..41a491b 100644
--- a/libavcodec/mpegaudiodecheader.h
+++ b/libavcodec/mpegaudiodecheader.h
@@ -2,20 +2,20 @@
  * MPEG Audio header decoder
  * Copyright (c) 2001, 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/mpegaudiodectab.h b/libavcodec/mpegaudiodectab.h
index 234a70e..fdcf83f 100644
--- a/libavcodec/mpegaudiodectab.h
+++ b/libavcodec/mpegaudiodectab.h
@@ -2,20 +2,20 @@
  * MPEG Audio decoder
  * copyright (c) 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/mpegaudioenc.c b/libavcodec/mpegaudioenc.c
index 264175e..bd581cf 100644
--- a/libavcodec/mpegaudioenc.c
+++ b/libavcodec/mpegaudioenc.c
@@ -2,20 +2,20 @@
  * The simplest mpeg audio layer 2 encoder
  * Copyright (c) 2000, 2001 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -40,12 +40,10 @@
 typedef struct MpegAudioContext {
     PutBitContext pb;
     int nb_channels;
-    int freq, bit_rate;
     int lsf;           /* 1 if mpeg2 low bitrate selected */
     int bitrate_index; /* bit rate */
     int freq_index;
     int frame_size; /* frame size, in bits, without padding */
-    int64_t nb_samples; /* total number of samples encoded */
     /* padding computation */
     int frame_frac, frame_frac_incr, do_padding;
     short samples_buf[MPA_MAX_CHANNELS][SAMPLES_BUF_SIZE]; /* buffer for filter */
@@ -79,8 +77,6 @@ static av_cold int MPA_encode_init(AVCodecContext *avctx)
     }
     bitrate = bitrate / 1000;
     s->nb_channels = channels;
-    s->freq = freq;
-    s->bit_rate = bitrate * 1000;
     avctx->frame_size = MPA_FRAME_SIZE;
 
     /* encoding freq */
@@ -126,7 +122,7 @@ static av_cold int MPA_encode_init(AVCodecContext *avctx)
     s->sblimit = ff_mpa_sblimit_table[table];
     s->alloc_table = ff_mpa_alloc_tables[table];
 
-    dprintf(avctx, "%d kb/s, %d Hz, frame_size=%d bits, table=%d, padincr=%x\n",
+    av_dlog(avctx, "%d kb/s, %d Hz, frame_size=%d bits, table=%d, padincr=%x\n",
             bitrate, freq, s->frame_size, table, s->frame_frac_incr);
 
     for(i=0;i<s->nb_channels;i++)
@@ -310,7 +306,7 @@ static void idct32(int *out, int *tab)
 
 #define WSHIFT (WFRAC_BITS + 15 - FRAC_BITS)
 
-static void filter(MpegAudioContext *s, int ch, short *samples, int incr)
+static void filter(MpegAudioContext *s, int ch, const short *samples, int incr)
 {
     short *p, *q;
     int sum, offset, i, j;
@@ -756,7 +752,7 @@ static int MPA_encode_frame(AVCodecContext *avctx,
                             unsigned char *frame, int buf_size, void *data)
 {
     MpegAudioContext *s = avctx->priv_data;
-    short *samples = data;
+    const short *samples = data;
     short smr[MPA_MAX_CHANNELS][SBLIMIT];
     unsigned char bit_alloc[MPA_MAX_CHANNELS][SBLIMIT];
     int padding, i;
@@ -778,7 +774,6 @@ static int MPA_encode_frame(AVCodecContext *avctx,
 
     encode_frame(s, bit_alloc, padding);
 
-    s->nb_samples += MPA_FRAME_SIZE;
     return put_bits_ptr(&s->pb) - s->pb.buf;
 }
 
@@ -788,7 +783,7 @@ static av_cold int MPA_encode_close(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec mp2_encoder = {
+AVCodec ff_mp2_encoder = {
     "mp2",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_MP2,
@@ -797,7 +792,7 @@ AVCodec mp2_encoder = {
     MPA_encode_frame,
     MPA_encode_close,
     NULL,
-    .sample_fmts = (const enum SampleFormat[]){SAMPLE_FMT_S16,SAMPLE_FMT_NONE},
+    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
     .supported_samplerates= (const int[]){44100, 48000,  32000, 22050, 24000, 16000, 0},
     .long_name = NULL_IF_CONFIG_SMALL("MP2 (MPEG audio layer 2)"),
 };
diff --git a/libavcodec/mpegaudiotab.h b/libavcodec/mpegaudiotab.h
index 35129e6..45afe9b 100644
--- a/libavcodec/mpegaudiotab.h
+++ b/libavcodec/mpegaudiotab.h
@@ -4,20 +4,20 @@
  *
  * Copyright (c) 2000, 2001 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/mpegvideo.c b/libavcodec/mpegvideo.c
index e11fee8..b6cc459 100644
--- a/libavcodec/mpegvideo.c
+++ b/libavcodec/mpegvideo.c
@@ -5,20 +5,20 @@
  *
  * 4MV & hq & B-frame encoding stuff by Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -28,8 +28,10 @@
  */
 
 #include "libavutil/intmath.h"
+#include "libavutil/imgutils.h"
 #include "avcodec.h"
 #include "dsputil.h"
+#include "internal.h"
 #include "mpegvideo.h"
 #include "mpegvideo_common.h"
 #include "mjpegenc.h"
@@ -199,7 +201,7 @@ void ff_copy_picture(Picture *dst, Picture *src){
 }
 
 /**
- * Releases a frame buffer
+ * Release a frame buffer
  */
 static void free_frame_buffer(MpegEncContext *s, Picture *pic)
 {
@@ -208,7 +210,7 @@ static void free_frame_buffer(MpegEncContext *s, Picture *pic)
 }
 
 /**
- * Allocates a frame buffer
+ * Allocate a frame buffer
  */
 static int alloc_frame_buffer(MpegEncContext *s, Picture *pic)
 {
@@ -355,6 +357,9 @@ static void free_picture(MpegEncContext *s, Picture *pic){
 }
 
 static int init_duplicate_context(MpegEncContext *s, MpegEncContext *base){
+    int y_size = s->b8_stride * (2 * s->mb_height + 1);
+    int c_size = s->mb_stride * (s->mb_height + 1);
+    int yc_size = y_size + 2 * c_size;
     int i;
 
     // edge emu needs blocksize + filter length - 1 (=17x17 for halfpel / 21x21 for h264)
@@ -380,6 +385,15 @@ static int init_duplicate_context(MpegEncContext *s, MpegEncContext *base){
     for(i=0;i<12;i++){
         s->pblocks[i] = &s->block[i];
     }
+
+    if (s->out_format == FMT_H263) {
+        /* ac values */
+        FF_ALLOCZ_OR_GOTO(s->avctx, s->ac_val_base, yc_size * sizeof(int16_t) * 16, fail);
+        s->ac_val[0] = s->ac_val_base + s->b8_stride + 1;
+        s->ac_val[1] = s->ac_val_base + y_size + s->mb_stride + 1;
+        s->ac_val[2] = s->ac_val[1] + c_size;
+    }
+
     return 0;
 fail:
     return -1; //free() through MPV_common_end()
@@ -399,6 +413,7 @@ static void free_duplicate_context(MpegEncContext *s){
     av_freep(&s->me.map);
     av_freep(&s->me.score_map);
     av_freep(&s->blocks);
+    av_freep(&s->ac_val_base);
     s->block= NULL;
 }
 
@@ -422,6 +437,10 @@ static void backup_duplicate_context(MpegEncContext *bak, MpegEncContext *src){
     COPY(dct_error_sum);
     COPY(dct_count[0]);
     COPY(dct_count[1]);
+    COPY(ac_val_base);
+    COPY(ac_val[0]);
+    COPY(ac_val[1]);
+    COPY(ac_val[2]);
 #undef COPY
 }
 
@@ -479,7 +498,7 @@ av_cold int MPV_common_init(MpegEncContext *s)
 
     if(s->codec_id == CODEC_ID_MPEG2VIDEO && !s->progressive_sequence)
         s->mb_height = (s->height + 31) / 32 * 2;
-    else
+    else if (s->codec_id != CODEC_ID_H264)
         s->mb_height = (s->height + 15) / 16;
 
     if(s->avctx->pix_fmt == PIX_FMT_NONE){
@@ -492,7 +511,7 @@ av_cold int MPV_common_init(MpegEncContext *s)
         return -1;
     }
 
-    if((s->width || s->height) && avcodec_check_dimensions(s->avctx, s->width, s->height))
+    if((s->width || s->height) && av_image_check_size(s->width, s->height, 0, s->avctx))
         return -1;
 
     dsputil_init(&s->dsp, s->avctx);
@@ -530,15 +549,9 @@ av_cold int MPV_common_init(MpegEncContext *s)
     yc_size = y_size + 2 * c_size;
 
     /* convert fourcc to upper case */
-    s->codec_tag=          toupper( s->avctx->codec_tag     &0xFF)
-                        + (toupper((s->avctx->codec_tag>>8 )&0xFF)<<8 )
-                        + (toupper((s->avctx->codec_tag>>16)&0xFF)<<16)
-                        + (toupper((s->avctx->codec_tag>>24)&0xFF)<<24);
+    s->codec_tag = ff_toupper4(s->avctx->codec_tag);
 
-    s->stream_codec_tag=          toupper( s->avctx->stream_codec_tag     &0xFF)
-                               + (toupper((s->avctx->stream_codec_tag>>8 )&0xFF)<<8 )
-                               + (toupper((s->avctx->stream_codec_tag>>16)&0xFF)<<16)
-                               + (toupper((s->avctx->stream_codec_tag>>24)&0xFF)<<24);
+    s->stream_codec_tag = ff_toupper4(s->avctx->stream_codec_tag);
 
     s->avctx->coded_frame= (AVFrame*)&s->current_picture;
 
@@ -610,12 +623,6 @@ av_cold int MPV_common_init(MpegEncContext *s)
             }
     }
     if (s->out_format == FMT_H263) {
-        /* ac values */
-        FF_ALLOCZ_OR_GOTO(s->avctx, s->ac_val_base, yc_size * sizeof(int16_t) * 16, fail);
-        s->ac_val[0] = s->ac_val_base + s->b8_stride + 1;
-        s->ac_val[1] = s->ac_val_base + y_size + s->mb_stride + 1;
-        s->ac_val[2] = s->ac_val[1] + c_size;
-
         /* cbp values */
         FF_ALLOCZ_OR_GOTO(s->avctx, s->coded_block_base, y_size, fail);
         s->coded_block= s->coded_block_base + s->b8_stride + 1;
@@ -717,7 +724,6 @@ void MPV_common_end(MpegEncContext *s)
     }
 
     av_freep(&s->dc_val_base);
-    av_freep(&s->ac_val_base);
     av_freep(&s->coded_block_base);
     av_freep(&s->mbintra_table);
     av_freep(&s->cbp_table);
@@ -957,7 +963,12 @@ int MPV_frame_start(MpegEncContext *s, AVCodecContext *avctx)
             return -1;
 
         s->current_picture_ptr= pic;
-        s->current_picture_ptr->top_field_first= s->top_field_first; //FIXME use only the vars from current_pic
+        //FIXME use only the vars from current_pic
+        s->current_picture_ptr->top_field_first= s->top_field_first;
+        if(s->codec_id == CODEC_ID_MPEG1VIDEO || s->codec_id == CODEC_ID_MPEG2VIDEO) {
+            if(s->picture_structure != PICT_FRAME)
+                s->current_picture_ptr->top_field_first= (s->picture_structure == PICT_TOP_FIELD) == s->first_field;
+        }
         s->current_picture_ptr->interlaced_frame= !s->progressive_frame && !s->progressive_sequence;
     }
 
@@ -1014,7 +1025,9 @@ int MPV_frame_start(MpegEncContext *s, AVCodecContext *avctx)
         }
     }
 
+#if FF_API_HURRY_UP
     s->hurry_up= s->avctx->hurry_up;
+#endif
     s->error_recognition= avctx->error_recognition;
 
     /* set dequantizer, we can't do it during init as it might change for mpeg4
@@ -1056,9 +1069,15 @@ void MPV_frame_end(MpegEncContext *s)
        && s->current_picture.reference
        && !s->intra_only
        && !(s->flags&CODEC_FLAG_EMU_EDGE)) {
-            s->dsp.draw_edges(s->current_picture.data[0], s->linesize  , s->h_edge_pos   , s->v_edge_pos   , EDGE_WIDTH  );
-            s->dsp.draw_edges(s->current_picture.data[1], s->uvlinesize, s->h_edge_pos>>1, s->v_edge_pos>>1, EDGE_WIDTH/2);
-            s->dsp.draw_edges(s->current_picture.data[2], s->uvlinesize, s->h_edge_pos>>1, s->v_edge_pos>>1, EDGE_WIDTH/2);
+            s->dsp.draw_edges(s->current_picture.data[0], s->linesize  ,
+                              s->h_edge_pos   , s->v_edge_pos   ,
+                              EDGE_WIDTH  , EDGE_TOP | EDGE_BOTTOM);
+            s->dsp.draw_edges(s->current_picture.data[1], s->uvlinesize,
+                              s->h_edge_pos>>1, s->v_edge_pos>>1,
+                              EDGE_WIDTH/2, EDGE_TOP | EDGE_BOTTOM);
+            s->dsp.draw_edges(s->current_picture.data[2], s->uvlinesize,
+                              s->h_edge_pos>>1, s->v_edge_pos>>1,
+                              EDGE_WIDTH/2, EDGE_TOP | EDGE_BOTTOM);
     }
     emms_c();
 
@@ -1249,7 +1268,7 @@ void ff_print_debug_info(MpegEncContext *s, AVFrame *pict){
                         av_log(s->avctx, AV_LOG_DEBUG, "?");
 
 
-                    if(IS_INTERLACED(mb_type) && s->codec_id == CODEC_ID_H264)
+                    if(IS_INTERLACED(mb_type))
                         av_log(s->avctx, AV_LOG_DEBUG, "=");
                     else
                         av_log(s->avctx, AV_LOG_DEBUG, " ");
@@ -1468,7 +1487,7 @@ static inline int hpel_motion_lowres(MpegEncContext *s,
 
     if(   (unsigned)src_x > h_edge_pos                 - (!!sx) - w
        || (unsigned)src_y >(v_edge_pos >> field_based) - (!!sy) - h){
-        ff_emulated_edge_mc(s->edge_emu_buffer, src, s->linesize, w+1, (h+1)<<field_based,
+        s->dsp.emulated_edge_mc(s->edge_emu_buffer, src, s->linesize, w+1, (h+1)<<field_based,
                             src_x, src_y<<field_based, h_edge_pos, v_edge_pos);
         src= s->edge_emu_buffer;
         emu=1;
@@ -1541,14 +1560,14 @@ static av_always_inline void mpeg_motion_lowres(MpegEncContext *s,
 
     if(   (unsigned)src_x > h_edge_pos                 - (!!sx) - 2*block_s
        || (unsigned)src_y >(v_edge_pos >> field_based) - (!!sy) - h){
-            ff_emulated_edge_mc(s->edge_emu_buffer, ptr_y, s->linesize, 17, 17+field_based,
+            s->dsp.emulated_edge_mc(s->edge_emu_buffer, ptr_y, s->linesize, 17, 17+field_based,
                              src_x, src_y<<field_based, h_edge_pos, v_edge_pos);
             ptr_y = s->edge_emu_buffer;
             if(!CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
                 uint8_t *uvbuf= s->edge_emu_buffer+18*s->linesize;
-                ff_emulated_edge_mc(uvbuf  , ptr_cb, s->uvlinesize, 9, 9+field_based,
+                s->dsp.emulated_edge_mc(uvbuf  , ptr_cb, s->uvlinesize, 9, 9+field_based,
                                  uvsrc_x, uvsrc_y<<field_based, h_edge_pos>>1, v_edge_pos>>1);
-                ff_emulated_edge_mc(uvbuf+16, ptr_cr, s->uvlinesize, 9, 9+field_based,
+                s->dsp.emulated_edge_mc(uvbuf+16, ptr_cr, s->uvlinesize, 9, 9+field_based,
                                  uvsrc_x, uvsrc_y<<field_based, h_edge_pos>>1, v_edge_pos>>1);
                 ptr_cb= uvbuf;
                 ptr_cr= uvbuf+16;
@@ -1614,7 +1633,7 @@ static inline void chroma_4mv_motion_lowres(MpegEncContext *s,
     if(s->flags&CODEC_FLAG_EMU_EDGE){
         if(   (unsigned)src_x > h_edge_pos - (!!sx) - block_s
            || (unsigned)src_y > v_edge_pos - (!!sy) - block_s){
-            ff_emulated_edge_mc(s->edge_emu_buffer, ptr, s->uvlinesize, 9, 9, src_x, src_y, h_edge_pos, v_edge_pos);
+            s->dsp.emulated_edge_mc(s->edge_emu_buffer, ptr, s->uvlinesize, 9, 9, src_x, src_y, h_edge_pos, v_edge_pos);
             ptr= s->edge_emu_buffer;
             emu=1;
         }
@@ -1625,7 +1644,7 @@ static inline void chroma_4mv_motion_lowres(MpegEncContext *s,
 
     ptr = ref_picture[2] + offset;
     if(emu){
-        ff_emulated_edge_mc(s->edge_emu_buffer, ptr, s->uvlinesize, 9, 9, src_x, src_y, h_edge_pos, v_edge_pos);
+        s->dsp.emulated_edge_mc(s->edge_emu_buffer, ptr, s->uvlinesize, 9, 9, src_x, src_y, h_edge_pos, v_edge_pos);
         ptr= s->edge_emu_buffer;
     }
     pix_op[op_index](dest_cr, ptr, s->uvlinesize, block_s, sx, sy);
@@ -1639,7 +1658,7 @@ static inline void chroma_4mv_motion_lowres(MpegEncContext *s,
  * @param dest_cr chroma cr/v destination pointer
  * @param dir direction (0->forward, 1->backward)
  * @param ref_picture array[3] of pointers to the 3 planes of the reference picture
- * @param pic_op halfpel motion compensation function (average or put normally)
+ * @param pix_op halfpel motion compensation function (average or put normally)
  * the motion vectors are taken from s->mv and the MV type from s->mv_type
  */
 static inline void MPV_motion_lowres(MpegEncContext *s,
@@ -1945,7 +1964,9 @@ void MPV_decode_mb_internal(MpegEncContext *s, DCTELEM block[12][64],
             }
 
             /* skip dequant / idct if we are really late ;) */
+#if FF_API_HURRY_UP
             if(s->hurry_up>1) goto skip_idct;
+#endif
             if(s->avctx->skip_idct){
                 if(  (s->avctx->skip_idct >= AVDISCARD_NONREF && s->pict_type == FF_B_TYPE)
                    ||(s->avctx->skip_idct >= AVDISCARD_NONKEY && s->pict_type != FF_I_TYPE)
diff --git a/libavcodec/mpegvideo.h b/libavcodec/mpegvideo.h
index 8cd20b7..0ff08d2 100644
--- a/libavcodec/mpegvideo.h
+++ b/libavcodec/mpegvideo.h
@@ -3,20 +3,20 @@
  * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
  * Copyright (c) 2002-2004 Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -224,9 +224,6 @@ typedef struct MpegEncContext {
     int stream_codec_tag;      ///< internal stream_codec_tag upper case converted from avctx stream_codec_tag
     /* the following fields are managed internally by the encoder */
 
-    /** bit output */
-    PutBitContext pb;
-
     /* sequence parameters */
     int context_initialized;
     int input_picture_number;  ///< used to set pic->display_picture_number, should not be used for/by anything else
@@ -247,6 +244,23 @@ typedef struct MpegEncContext {
     Picture **input_picture;   ///< next pictures on display order for encoding
     Picture **reordered_input_picture; ///< pointer to the next pictures in codedorder for encoding
 
+    int y_dc_scale, c_dc_scale;
+    int ac_pred;
+    int block_last_index[12];  ///< last non zero coefficient in block
+    int h263_aic;              ///< Advanded INTRA Coding (AIC)
+
+    /* scantables */
+    ScanTable inter_scantable; ///< if inter == intra then intra should be used to reduce tha cache usage
+    ScanTable intra_scantable;
+    ScanTable intra_h_scantable;
+    ScanTable intra_v_scantable;
+
+    /* WARNING: changes above this line require updates to hardcoded
+     *          offsets used in asm. */
+
+    /** bit output */
+    PutBitContext pb;
+
     int start_mb_y;            ///< start mb_y of this thread (so current thread should process start_mb_y <= row < end_mb_y)
     int end_mb_y;              ///< end   mb_y of this thread (so current thread should process start_mb_y <= row < end_mb_y)
     struct MpegEncContext *thread_context[MAX_THREADS];
@@ -283,7 +297,6 @@ typedef struct MpegEncContext {
     int16_t *dc_val_base;
     int16_t *dc_val[3];            ///< used for mpeg4 DC prediction, all 3 arrays must be continuous
     int16_t dc_cache[4*5];
-    int y_dc_scale, c_dc_scale;
     const uint8_t *y_dc_scale_table;     ///< qscale -> y_dc_scale table
     const uint8_t *c_dc_scale_table;     ///< qscale -> c_dc_scale table
     const uint8_t *chroma_qscale_table;  ///< qscale -> chroma_qscale (h263)
@@ -291,7 +304,6 @@ typedef struct MpegEncContext {
     uint8_t *coded_block;          ///< used for coded block pattern prediction (msmpeg4v3, wmv1)
     int16_t (*ac_val_base)[16];
     int16_t (*ac_val[3])[16];      ///< used for for mpeg4 AC prediction, all 3 arrays must be continuous
-    int ac_pred;
     uint8_t *prev_pict_types;     ///< previous picture types in bitstream order, used for mb skip
 #define PREV_PICT_TYPES_BUFFER_SIZE 256
     int mb_skipped;                ///< MUST BE SET only during DECODING
@@ -375,8 +387,10 @@ typedef struct MpegEncContext {
     int no_rounding;  /**< apply no rounding to motion compensation (MPEG4, msmpeg4, ...)
                         for b-frames rounding mode is always 0 */
 
+#if FF_API_HURRY_UP
     int hurry_up;     /**< when set to 1 during decoding, b frames will be skipped
                          when set to 2 idct/dequant will be skipped too */
+#endif
 
     /* macroblock layer */
     int mb_x, mb_y;
@@ -434,12 +448,6 @@ typedef struct MpegEncContext {
     /** identical to the above but for MMX & these are not permutated, second 64 entries are bias*/
     uint16_t (*q_intra_matrix16)[2][64];
     uint16_t (*q_inter_matrix16)[2][64];
-    int block_last_index[12];  ///< last non zero coefficient in block
-    /* scantables */
-    ScanTable intra_scantable;
-    ScanTable intra_h_scantable;
-    ScanTable intra_v_scantable;
-    ScanTable inter_scantable; ///< if inter == intra then intra should be used to reduce tha cache usage
 
     /* noise reduction */
     int (*dct_error_sum)[64];
@@ -495,7 +503,6 @@ typedef struct MpegEncContext {
 
     /* H.263+ specific */
     int umvplus;                    ///< == H263+ && unrestricted_mv
-    int h263_aic;                   ///< Advanded INTRA Coding (AIC)
     int h263_aic_dir;               ///< AIC direction: 0 = left, 1 = top
     int h263_slice_structured;
     int alt_inter_vlc;              ///< alternative inter vlc
diff --git a/libavcodec/mpegvideo_common.h b/libavcodec/mpegvideo_common.h
index 7310666..f6c94fb 100644
--- a/libavcodec/mpegvideo_common.h
+++ b/libavcodec/mpegvideo_common.h
@@ -5,20 +5,20 @@
  *
  * 4MV & hq & B-frame encoding stuff by Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -40,8 +40,6 @@
 #include <limits.h>
 
 int dct_quantize_c(MpegEncContext *s, DCTELEM *block, int n, int qscale, int *overflow);
-int dct_quantize_trellis_c(MpegEncContext *s, DCTELEM *block, int n, int qscale, int *overflow);
-void  denoise_dct_c(MpegEncContext *s, DCTELEM *block);
 
 /**
  * allocates a Picture
@@ -85,7 +83,7 @@ static inline void gmc1_motion(MpegEncContext *s,
     if(s->flags&CODEC_FLAG_EMU_EDGE){
         if(   (unsigned)src_x >= s->h_edge_pos - 17
            || (unsigned)src_y >= s->v_edge_pos - 17){
-            ff_emulated_edge_mc(s->edge_emu_buffer, ptr, linesize, 17, 17, src_x, src_y, s->h_edge_pos, s->v_edge_pos);
+            s->dsp.emulated_edge_mc(s->edge_emu_buffer, ptr, linesize, 17, 17, src_x, src_y, s->h_edge_pos, s->v_edge_pos);
             ptr= s->edge_emu_buffer;
         }
     }
@@ -124,7 +122,7 @@ static inline void gmc1_motion(MpegEncContext *s,
     if(s->flags&CODEC_FLAG_EMU_EDGE){
         if(   (unsigned)src_x >= (s->h_edge_pos>>1) - 9
            || (unsigned)src_y >= (s->v_edge_pos>>1) - 9){
-            ff_emulated_edge_mc(s->edge_emu_buffer, ptr, uvlinesize, 9, 9, src_x, src_y, s->h_edge_pos>>1, s->v_edge_pos>>1);
+            s->dsp.emulated_edge_mc(s->edge_emu_buffer, ptr, uvlinesize, 9, 9, src_x, src_y, s->h_edge_pos>>1, s->v_edge_pos>>1);
             ptr= s->edge_emu_buffer;
             emu=1;
         }
@@ -133,7 +131,7 @@ static inline void gmc1_motion(MpegEncContext *s,
 
     ptr = ref_picture[2] + offset;
     if(emu){
-        ff_emulated_edge_mc(s->edge_emu_buffer, ptr, uvlinesize, 9, 9, src_x, src_y, s->h_edge_pos>>1, s->v_edge_pos>>1);
+        s->dsp.emulated_edge_mc(s->edge_emu_buffer, ptr, uvlinesize, 9, 9, src_x, src_y, s->h_edge_pos>>1, s->v_edge_pos>>1);
         ptr= s->edge_emu_buffer;
     }
     s->dsp.gmc1(dest_cr, ptr, uvlinesize, 8, motion_x&15, motion_y&15, 128 - s->no_rounding);
@@ -225,7 +223,7 @@ static inline int hpel_motion(MpegEncContext *s,
     if(s->unrestricted_mv && (s->flags&CODEC_FLAG_EMU_EDGE)){
         if(   (unsigned)src_x > h_edge_pos - (motion_x&1) - w
            || (unsigned)src_y > v_edge_pos - (motion_y&1) - h){
-            ff_emulated_edge_mc(s->edge_emu_buffer, src, s->linesize, w+1, (h+1)<<field_based,
+            s->dsp.emulated_edge_mc(s->edge_emu_buffer, src, s->linesize, w+1, (h+1)<<field_based,
                              src_x, src_y<<field_based, h_edge_pos, s->v_edge_pos);
             src= s->edge_emu_buffer;
             emu=1;
@@ -317,19 +315,19 @@ if(s->quarter_sample)
                         "MPEG motion vector out of boundary (%d %d)\n", src_x, src_y);
                 return;
             }
-            ff_emulated_edge_mc(s->edge_emu_buffer, ptr_y, s->linesize,
+            s->dsp.emulated_edge_mc(s->edge_emu_buffer, ptr_y, s->linesize,
                                 17, 17+field_based,
                                 src_x, src_y<<field_based,
                                 s->h_edge_pos, s->v_edge_pos);
             ptr_y = s->edge_emu_buffer;
             if(!CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
                 uint8_t *uvbuf= s->edge_emu_buffer+18*s->linesize;
-                ff_emulated_edge_mc(uvbuf ,
+                s->dsp.emulated_edge_mc(uvbuf ,
                                     ptr_cb, s->uvlinesize,
                                     9, 9+field_based,
                                     uvsrc_x, uvsrc_y<<field_based,
                                     s->h_edge_pos>>1, s->v_edge_pos>>1);
-                ff_emulated_edge_mc(uvbuf+16,
+                s->dsp.emulated_edge_mc(uvbuf+16,
                                     ptr_cr, s->uvlinesize,
                                     9, 9+field_based,
                                     uvsrc_x, uvsrc_y<<field_based,
@@ -514,17 +512,17 @@ static inline void qpel_motion(MpegEncContext *s,
 
     if(   (unsigned)src_x > s->h_edge_pos - (motion_x&3) - 16
        || (unsigned)src_y >    v_edge_pos - (motion_y&3) - h  ){
-        ff_emulated_edge_mc(s->edge_emu_buffer, ptr_y, s->linesize,
+        s->dsp.emulated_edge_mc(s->edge_emu_buffer, ptr_y, s->linesize,
                             17, 17+field_based, src_x, src_y<<field_based,
                             s->h_edge_pos, s->v_edge_pos);
         ptr_y= s->edge_emu_buffer;
         if(!CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
             uint8_t *uvbuf= s->edge_emu_buffer + 18*s->linesize;
-            ff_emulated_edge_mc(uvbuf, ptr_cb, s->uvlinesize,
+            s->dsp.emulated_edge_mc(uvbuf, ptr_cb, s->uvlinesize,
                                 9, 9 + field_based,
                                 uvsrc_x, uvsrc_y<<field_based,
                                 s->h_edge_pos>>1, s->v_edge_pos>>1);
-            ff_emulated_edge_mc(uvbuf + 16, ptr_cr, s->uvlinesize,
+            s->dsp.emulated_edge_mc(uvbuf + 16, ptr_cr, s->uvlinesize,
                                 9, 9 + field_based,
                                 uvsrc_x, uvsrc_y<<field_based,
                                 s->h_edge_pos>>1, s->v_edge_pos>>1);
@@ -580,11 +578,11 @@ static inline void chroma_4mv_motion(MpegEncContext *s,
 
     src_x = s->mb_x * 8 + mx;
     src_y = s->mb_y * 8 + my;
-    src_x = av_clip(src_x, -8, s->width/2);
-    if (src_x == s->width/2)
+    src_x = av_clip(src_x, -8, (s->width >> 1));
+    if (src_x == (s->width >> 1))
         dxy &= ~1;
-    src_y = av_clip(src_y, -8, s->height/2);
-    if (src_y == s->height/2)
+    src_y = av_clip(src_y, -8, (s->height >> 1));
+    if (src_y == (s->height >> 1))
         dxy &= ~2;
 
     offset = (src_y * (s->uvlinesize)) + src_x;
@@ -592,7 +590,7 @@ static inline void chroma_4mv_motion(MpegEncContext *s,
     if(s->flags&CODEC_FLAG_EMU_EDGE){
         if(   (unsigned)src_x > (s->h_edge_pos>>1) - (dxy &1) - 8
            || (unsigned)src_y > (s->v_edge_pos>>1) - (dxy>>1) - 8){
-            ff_emulated_edge_mc(s->edge_emu_buffer, ptr, s->uvlinesize,
+            s->dsp.emulated_edge_mc(s->edge_emu_buffer, ptr, s->uvlinesize,
                                 9, 9, src_x, src_y,
                                 s->h_edge_pos>>1, s->v_edge_pos>>1);
             ptr= s->edge_emu_buffer;
@@ -603,7 +601,7 @@ static inline void chroma_4mv_motion(MpegEncContext *s,
 
     ptr = ref_picture[2] + offset;
     if(emu){
-        ff_emulated_edge_mc(s->edge_emu_buffer, ptr, s->uvlinesize,
+        s->dsp.emulated_edge_mc(s->edge_emu_buffer, ptr, s->uvlinesize,
                             9, 9, src_x, src_y,
                             s->h_edge_pos>>1, s->v_edge_pos>>1);
         ptr= s->edge_emu_buffer;
@@ -631,8 +629,8 @@ static inline void prefetch_motion(MpegEncContext *s, uint8_t **pix, int dir){
  * @param dest_cr chroma cr/v destination pointer
  * @param dir direction (0->forward, 1->backward)
  * @param ref_picture array[3] of pointers to the 3 planes of the reference picture
- * @param pic_op halfpel motion compensation function (average or put normally)
- * @param pic_op qpel motion compensation function (average or put normally)
+ * @param pix_op halfpel motion compensation function (average or put normally)
+ * @param qpix_op qpel motion compensation function (average or put normally)
  * the motion vectors are taken from s->mv and the MV type from s->mv_type
  */
 static av_always_inline void MPV_motion_internal(MpegEncContext *s,
@@ -670,19 +668,19 @@ static av_always_inline void MPV_motion_internal(MpegEncContext *s,
         }
 
         if(mb_x==0 || IS_INTRA(s->current_picture.mb_type[xy-1])){
-            *(int32_t*)mv_cache[1][0]= *(int32_t*)mv_cache[1][1];
-            *(int32_t*)mv_cache[2][0]= *(int32_t*)mv_cache[2][1];
+            AV_COPY32(mv_cache[1][0], mv_cache[1][1]);
+            AV_COPY32(mv_cache[2][0], mv_cache[2][1]);
         }else{
-            *(int32_t*)mv_cache[1][0]= *(int32_t*)s->current_picture.motion_val[0][mot_xy-1];
-            *(int32_t*)mv_cache[2][0]= *(int32_t*)s->current_picture.motion_val[0][mot_xy-1+mot_stride];
+            AV_COPY32(mv_cache[1][0], s->current_picture.motion_val[0][mot_xy-1]);
+            AV_COPY32(mv_cache[2][0], s->current_picture.motion_val[0][mot_xy-1+mot_stride]);
         }
 
         if(mb_x+1>=s->mb_width || IS_INTRA(s->current_picture.mb_type[xy+1])){
-            *(int32_t*)mv_cache[1][3]= *(int32_t*)mv_cache[1][2];
-            *(int32_t*)mv_cache[2][3]= *(int32_t*)mv_cache[2][2];
+            AV_COPY32(mv_cache[1][3], mv_cache[1][2]);
+            AV_COPY32(mv_cache[2][3], mv_cache[2][2]);
         }else{
-            *(int32_t*)mv_cache[1][3]= *(int32_t*)s->current_picture.motion_val[0][mot_xy+2];
-            *(int32_t*)mv_cache[2][3]= *(int32_t*)s->current_picture.motion_val[0][mot_xy+2+mot_stride];
+            AV_COPY32(mv_cache[1][3], s->current_picture.motion_val[0][mot_xy+2]);
+            AV_COPY32(mv_cache[2][3], s->current_picture.motion_val[0][mot_xy+2+mot_stride]);
         }
 
         mx = 0;
@@ -764,7 +762,7 @@ static av_always_inline void MPV_motion_internal(MpegEncContext *s,
                 if(s->flags&CODEC_FLAG_EMU_EDGE){
                     if(   (unsigned)src_x > s->h_edge_pos - (motion_x&3) - 8
                        || (unsigned)src_y > s->v_edge_pos - (motion_y&3) - 8 ){
-                        ff_emulated_edge_mc(s->edge_emu_buffer, ptr,
+                        s->dsp.emulated_edge_mc(s->edge_emu_buffer, ptr,
                                             s->linesize, 9, 9,
                                             src_x, src_y,
                                             s->h_edge_pos, s->v_edge_pos);
diff --git a/libavcodec/mpegvideo_enc.c b/libavcodec/mpegvideo_enc.c
index a8616d0..7f98923 100644
--- a/libavcodec/mpegvideo_enc.c
+++ b/libavcodec/mpegvideo_enc.c
@@ -5,20 +5,20 @@
  *
  * 4MV & hq & B-frame encoding stuff by Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -48,6 +48,8 @@
 static int encode_picture(MpegEncContext *s, int picture_number);
 static int dct_quantize_refine(MpegEncContext *s, DCTELEM *block, int16_t *weight, DCTELEM *orig, int n, int qscale);
 static int sse_mb(MpegEncContext *s);
+static void denoise_dct_c(MpegEncContext *s, DCTELEM *block);
+static int dct_quantize_trellis_c(MpegEncContext *s, DCTELEM *block, int n, int qscale, int *overflow);
 
 /* enable all paranoid tests for rounding, overflows, etc... */
 //#define PARANOID
@@ -252,9 +254,15 @@ av_cold int MPV_encode_init(AVCodecContext *avctx)
         }
         break;
     case CODEC_ID_LJPEG:
+        if(avctx->pix_fmt != PIX_FMT_YUVJ420P && avctx->pix_fmt != PIX_FMT_YUVJ422P && avctx->pix_fmt != PIX_FMT_YUVJ444P && avctx->pix_fmt != PIX_FMT_BGRA &&
+           ((avctx->pix_fmt != PIX_FMT_YUV420P && avctx->pix_fmt != PIX_FMT_YUV422P && avctx->pix_fmt != PIX_FMT_YUV444P) || avctx->strict_std_compliance>FF_COMPLIANCE_UNOFFICIAL)){
+            av_log(avctx, AV_LOG_ERROR, "colorspace not supported in LJPEG\n");
+            return -1;
+        }
+        break;
     case CODEC_ID_MJPEG:
-        if(avctx->pix_fmt != PIX_FMT_YUVJ420P && avctx->pix_fmt != PIX_FMT_YUVJ422P && avctx->pix_fmt != PIX_FMT_RGB32 &&
-           ((avctx->pix_fmt != PIX_FMT_YUV420P && avctx->pix_fmt != PIX_FMT_YUV422P) || avctx->strict_std_compliance>FF_COMPLIANCE_INOFFICIAL)){
+        if(avctx->pix_fmt != PIX_FMT_YUVJ420P && avctx->pix_fmt != PIX_FMT_YUVJ422P &&
+           ((avctx->pix_fmt != PIX_FMT_YUV420P && avctx->pix_fmt != PIX_FMT_YUV422P) || avctx->strict_std_compliance>FF_COMPLIANCE_UNOFFICIAL)){
             av_log(avctx, AV_LOG_ERROR, "colorspace not supported in jpeg\n");
             return -1;
         }
@@ -351,12 +359,12 @@ av_cold int MPV_encode_init(AVCodecContext *avctx)
         av_log(avctx, AV_LOG_INFO, "impossible bitrate constraints, this will fail\n");
     }
 
-    if(avctx->rc_buffer_size && avctx->bit_rate*av_q2d(avctx->time_base) > avctx->rc_buffer_size){
+    if(avctx->rc_buffer_size && avctx->bit_rate*(int64_t)avctx->time_base.num > avctx->rc_buffer_size * (int64_t)avctx->time_base.den){
         av_log(avctx, AV_LOG_ERROR, "VBV buffer too small for bitrate\n");
         return -1;
     }
 
-    if(avctx->bit_rate*av_q2d(avctx->time_base) > avctx->bit_rate_tolerance){
+    if(!s->fixed_qscale && avctx->bit_rate*av_q2d(avctx->time_base) > avctx->bit_rate_tolerance){
         av_log(avctx, AV_LOG_ERROR, "bitrate tolerance too small for bitrate\n");
         return -1;
     }
@@ -519,7 +527,9 @@ av_cold int MPV_encode_init(AVCodecContext *avctx)
     avcodec_get_chroma_sub_sample(avctx->pix_fmt, &chroma_h_shift, &chroma_v_shift);
 
     if(avctx->codec_id == CODEC_ID_MPEG4 && s->avctx->time_base.den > (1<<16)-1){
-        av_log(avctx, AV_LOG_ERROR, "timebase not supported by mpeg 4 standard\n");
+        av_log(avctx, AV_LOG_ERROR, "timebase %d/%d not supported by MPEG 4 standard, "
+               "the maximum admitted value for the timebase denominator is %d\n",
+               s->avctx->time_base.num, s->avctx->time_base.den, (1<<16)-1);
         return -1;
     }
     s->time_increment_bits = av_log2(s->avctx->time_base.den - 1) + 1;
@@ -570,7 +580,7 @@ av_cold int MPV_encode_init(AVCodecContext *avctx)
         break;
     case CODEC_ID_H263:
         if (!CONFIG_H263_ENCODER)  return -1;
-        if (ff_match_2uint16(h263_format, FF_ARRAY_ELEMS(h263_format), s->width, s->height) == 7) {
+        if (ff_match_2uint16(h263_format, FF_ARRAY_ELEMS(h263_format), s->width, s->height) == 8) {
             av_log(avctx, AV_LOG_INFO, "The specified picture size of %dx%d is not valid for the H.263 codec.\nValid sizes are 128x96, 176x144, 352x288, 704x576, and 1408x1152. Try H.263+.\n", s->width, s->height);
             return -1;
         }
@@ -618,7 +628,7 @@ av_cold int MPV_encode_init(AVCodecContext *avctx)
         s->h263_aic=1;
         s->h263_plus=1;
         s->loop_filter=1;
-        s->unrestricted_mv= s->obmc || s->loop_filter || s->umvplus;
+        s->unrestricted_mv= 0;
         break;
     case CODEC_ID_MPEG4:
         s->out_format = FMT_H263;
@@ -1371,6 +1381,7 @@ vbv_retry:
             s->vbv_delay_ptr[1]  = vbv_delay>>5;
             s->vbv_delay_ptr[2] &= 0x07;
             s->vbv_delay_ptr[2] |= vbv_delay<<3;
+            avctx->vbv_delay = vbv_delay*300;
         }
         s->total_bits += s->frame_bits;
         avctx->frame_bits  = s->frame_bits;
@@ -1538,11 +1549,11 @@ static av_always_inline void encode_mb_internal(MpegEncContext *s, int motion_x,
 
     if(mb_x*16+16 > s->width || mb_y*16+16 > s->height){
         uint8_t *ebuf= s->edge_emu_buffer + 32;
-        ff_emulated_edge_mc(ebuf            , ptr_y , wrap_y,16,16,mb_x*16,mb_y*16, s->width   , s->height);
+        s->dsp.emulated_edge_mc(ebuf            , ptr_y , wrap_y,16,16,mb_x*16,mb_y*16, s->width   , s->height);
         ptr_y= ebuf;
-        ff_emulated_edge_mc(ebuf+18*wrap_y  , ptr_cb, wrap_c, 8, mb_block_height, mb_x*8, mb_y*8, s->width>>1, s->height>>1);
+        s->dsp.emulated_edge_mc(ebuf+18*wrap_y  , ptr_cb, wrap_c, 8, mb_block_height, mb_x*8, mb_y*8, s->width>>1, s->height>>1);
         ptr_cb= ebuf+18*wrap_y;
-        ff_emulated_edge_mc(ebuf+18*wrap_y+8, ptr_cr, wrap_c, 8, mb_block_height, mb_x*8, mb_y*8, s->width>>1, s->height>>1);
+        s->dsp.emulated_edge_mc(ebuf+18*wrap_y+8, ptr_cr, wrap_c, 8, mb_block_height, mb_x*8, mb_y*8, s->width>>1, s->height>>1);
         ptr_cr= ebuf+18*wrap_y+8;
     }
 
@@ -2974,7 +2985,7 @@ static int encode_picture(MpegEncContext *s, int picture_number)
     return 0;
 }
 
-void  denoise_dct_c(MpegEncContext *s, DCTELEM *block){
+static void denoise_dct_c(MpegEncContext *s, DCTELEM *block){
     const int intra= s->mb_intra;
     int i;
 
@@ -2998,9 +3009,9 @@ void  denoise_dct_c(MpegEncContext *s, DCTELEM *block){
     }
 }
 
-int dct_quantize_trellis_c(MpegEncContext *s,
-                        DCTELEM *block, int n,
-                        int qscale, int *overflow){
+static int dct_quantize_trellis_c(MpegEncContext *s,
+                                  DCTELEM *block, int n,
+                                  int qscale, int *overflow){
     const int *qmat;
     const uint8_t *scantable= s->intra_scantable.scantable;
     const uint8_t *perm_scantable= s->intra_scantable.permutated;
@@ -3769,7 +3780,7 @@ int dct_quantize_c(MpegEncContext *s,
     return last_non_zero;
 }
 
-AVCodec h263_encoder = {
+AVCodec ff_h263_encoder = {
     "h263",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_H263,
@@ -3781,7 +3792,7 @@ AVCodec h263_encoder = {
     .long_name= NULL_IF_CONFIG_SMALL("H.263 / H.263-1996"),
 };
 
-AVCodec h263p_encoder = {
+AVCodec ff_h263p_encoder = {
     "h263p",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_H263P,
@@ -3793,7 +3804,7 @@ AVCodec h263p_encoder = {
     .long_name= NULL_IF_CONFIG_SMALL("H.263+ / H.263-1998 / H.263 version 2"),
 };
 
-AVCodec msmpeg4v1_encoder = {
+AVCodec ff_msmpeg4v1_encoder = {
     "msmpeg4v1",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_MSMPEG4V1,
@@ -3805,7 +3816,7 @@ AVCodec msmpeg4v1_encoder = {
     .long_name= NULL_IF_CONFIG_SMALL("MPEG-4 part 2 Microsoft variant version 1"),
 };
 
-AVCodec msmpeg4v2_encoder = {
+AVCodec ff_msmpeg4v2_encoder = {
     "msmpeg4v2",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_MSMPEG4V2,
@@ -3817,7 +3828,7 @@ AVCodec msmpeg4v2_encoder = {
     .long_name= NULL_IF_CONFIG_SMALL("MPEG-4 part 2 Microsoft variant version 2"),
 };
 
-AVCodec msmpeg4v3_encoder = {
+AVCodec ff_msmpeg4v3_encoder = {
     "msmpeg4",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_MSMPEG4V3,
@@ -3829,7 +3840,7 @@ AVCodec msmpeg4v3_encoder = {
     .long_name= NULL_IF_CONFIG_SMALL("MPEG-4 part 2 Microsoft variant version 3"),
 };
 
-AVCodec wmv1_encoder = {
+AVCodec ff_wmv1_encoder = {
     "wmv1",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_WMV1,
diff --git a/libavcodec/mpegvideo_parser.c b/libavcodec/mpegvideo_parser.c
index 546c3bd..8115df5 100644
--- a/libavcodec/mpegvideo_parser.c
+++ b/libavcodec/mpegvideo_parser.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2000,2001 Fabrice Bellard
  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -176,7 +176,7 @@ static int mpegvideo_split(AVCodecContext *avctx,
     return 0;
 }
 
-AVCodecParser mpegvideo_parser = {
+AVCodecParser ff_mpegvideo_parser = {
     { CODEC_ID_MPEG1VIDEO, CODEC_ID_MPEG2VIDEO },
     sizeof(ParseContext1),
     NULL,
diff --git a/libavcodec/mpegvideo_xvmc.c b/libavcodec/mpegvideo_xvmc.c
index df81e5d..d05eb48 100644
--- a/libavcodec/mpegvideo_xvmc.c
+++ b/libavcodec/mpegvideo_xvmc.c
@@ -2,20 +2,20 @@
  * XVideo Motion Compensation
  * Copyright (c) 2003 Ivan Kalvachev
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -33,7 +33,7 @@
 #include "xvmc_internal.h"
 
 /**
- * Initializes the block field of the MpegEncContext pointer passed as
+ * Initialize the block field of the MpegEncContext pointer passed as
  * parameter after making sure that the data is not corrupted.
  * In order to implement something like direct rendering instead of decoding
  * coefficients in s->blocks and then copying them, copy them directly
@@ -48,7 +48,7 @@ void ff_xvmc_init_block(MpegEncContext *s)
 }
 
 /**
- * Fills individual block pointers, so there are no gaps in the data_block array
+ * Fill individual block pointers, so there are no gaps in the data_block array
  * in case not all blocks in the macroblock are coded.
  */
 void ff_xvmc_pack_pblocks(MpegEncContext *s, int cbp)
@@ -67,7 +67,7 @@ void ff_xvmc_pack_pblocks(MpegEncContext *s, int cbp)
 }
 
 /**
- * Finds and stores the surfaces that are used as reference frames.
+ * Find and store the surfaces that are used as reference frames.
  * This function should be called for every new field and/or frame.
  * It should be safe to call the function a few times for the same field.
  */
@@ -134,7 +134,7 @@ return -1;
 }
 
 /**
- * Completes frame/field rendering by passing any remaining blocks.
+ * Complete frame/field rendering by passing any remaining blocks.
  * Normally ff_draw_horiz_band() is called for each slice, however,
  * some leftover blocks, for example from error_resilience(), may remain.
  * It should be safe to call the function a few times for the same field.
@@ -149,8 +149,8 @@ void ff_xvmc_field_end(MpegEncContext *s)
 }
 
 /**
- * Synthesizes the data needed by XvMC to render one macroblock of data.
- * Fills all relevant fields, if necessary do IDCT.
+ * Synthesize the data needed by XvMC to render one macroblock of data.
+ * Fill all relevant fields, if necessary do IDCT.
  */
 void ff_xvmc_decode_mb(MpegEncContext *s)
 {
@@ -301,7 +301,7 @@ void ff_xvmc_decode_mb(MpegEncContext *s)
     for (i = 0; i < blocks_per_mb; i++) {
         if (s->block_last_index[i] >= 0) {
             // I do not have unsigned_intra MOCO to test, hope it is OK.
-            if (s->mb_intra && (render->idct || (!render->idct && !render->unsigned_intra)))
+            if (s->mb_intra && (render->idct || !render->unsigned_intra))
                 *s->pblocks[i][0] -= 1 << 10;
             if (!render->idct) {
                 s->dsp.idct(*s->pblocks[i]);
diff --git a/libavcodec/msgsmdec.c b/libavcodec/msgsmdec.c
new file mode 100644
index 0000000..ff9b275
--- /dev/null
+++ b/libavcodec/msgsmdec.c
@@ -0,0 +1,37 @@
+/*
+ * gsm 06.10 decoder, Microsoft variant
+ * Copyright (c) 2010 Reimar Döffinger <Reimar.Doeffinger at gmx.de>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#define ALT_BITSTREAM_READER_LE
+#include "avcodec.h"
+#include "msgsmdec.h"
+#include "gsmdec_template.c"
+
+int ff_msgsm_decode_block(AVCodecContext *avctx, int16_t *samples,
+                          const uint8_t *buf)
+{
+    int res;
+    GetBitContext gb;
+    init_get_bits(&gb, buf, GSM_MS_BLOCK_SIZE * 8);
+    res = gsm_decode_block(avctx, samples, &gb);
+    if (res < 0)
+        return res;
+    return gsm_decode_block(avctx, samples + GSM_FRAME_SIZE, &gb);
+}
diff --git a/libavcodec/msgsmdec.h b/libavcodec/msgsmdec.h
new file mode 100644
index 0000000..cf58baa
--- /dev/null
+++ b/libavcodec/msgsmdec.h
@@ -0,0 +1,30 @@
+/*
+ * gsm 06.10 decoder, Microsoft variant
+ * Copyright (c) 2010 Reimar Döffinger <Reimar.Doeffinger at gmx.de>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef MSGSMDEC_H
+#define MSGSMDEC_H
+
+#include "avcodec.h"
+
+int ff_msgsm_decode_block(AVCodecContext *avctx, int16_t *samples,
+                          const uint8_t *buf);
+
+#endif
diff --git a/libavcodec/msmpeg4.c b/libavcodec/msmpeg4.c
index 84658fe..0dba8d9 100644
--- a/libavcodec/msmpeg4.c
+++ b/libavcodec/msmpeg4.c
@@ -5,20 +5,20 @@
  *
  * msmpeg4v1 & v2 stuff by Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -1279,7 +1279,8 @@ av_cold int ff_msmpeg4_decode_init(AVCodecContext *avctx)
     int i;
     MVTable *mv;
 
-    ff_h263_decode_init(avctx);
+    if (ff_h263_decode_init(avctx) < 0)
+        return -1;
 
     common_init(s);
 
@@ -1395,8 +1396,7 @@ return -1;
 #endif
 
     if(s->msmpeg4_version==1){
-        int start_code;
-        start_code = (get_bits(&s->gb, 16)<<16) | get_bits(&s->gb, 16);
+        int start_code = get_bits_long(&s->gb, 32);
         if(start_code!=0x00000100){
             av_log(s->avctx, AV_LOG_ERROR, "invalid startcode\n");
             return -1;
@@ -1798,12 +1798,7 @@ int ff_msmpeg4_decode_block(MpegEncContext * s, DCTELEM * block,
 #endif
                 } else {
                     /* second escape */
-#if MIN_CACHE_BITS < 23
-                    LAST_SKIP_BITS(re, &s->gb, 2);
-                    UPDATE_CACHE(re, &s->gb);
-#else
                     SKIP_BITS(re, &s->gb, 2);
-#endif
                     GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1);
                     i+= run + rl->max_run[run>>7][level/qmul] + run_diff; //FIXME opt indexing
                     level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
@@ -1817,12 +1812,7 @@ int ff_msmpeg4_decode_block(MpegEncContext * s, DCTELEM * block,
                 }
             } else {
                 /* first escape */
-#if MIN_CACHE_BITS < 22
-                LAST_SKIP_BITS(re, &s->gb, 1);
-                UPDATE_CACHE(re, &s->gb);
-#else
                 SKIP_BITS(re, &s->gb, 1);
-#endif
                 GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1);
                 i+= run;
                 level = level + rl->max_level[run>>7][(run-1)&63] * qmul;//FIXME opt indexing
@@ -1919,7 +1909,7 @@ int ff_msmpeg4_decode_motion(MpegEncContext * s,
     return 0;
 }
 
-AVCodec msmpeg4v1_decoder = {
+AVCodec ff_msmpeg4v1_decoder = {
     "msmpeg4v1",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_MSMPEG4V1,
@@ -1929,11 +1919,12 @@ AVCodec msmpeg4v1_decoder = {
     ff_h263_decode_end,
     ff_h263_decode_frame,
     CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1,
+    .max_lowres= 3,
     .long_name= NULL_IF_CONFIG_SMALL("MPEG-4 part 2 Microsoft variant version 1"),
     .pix_fmts= ff_pixfmt_list_420,
 };
 
-AVCodec msmpeg4v2_decoder = {
+AVCodec ff_msmpeg4v2_decoder = {
     "msmpeg4v2",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_MSMPEG4V2,
@@ -1943,11 +1934,12 @@ AVCodec msmpeg4v2_decoder = {
     ff_h263_decode_end,
     ff_h263_decode_frame,
     CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1,
+    .max_lowres= 3,
     .long_name= NULL_IF_CONFIG_SMALL("MPEG-4 part 2 Microsoft variant version 2"),
     .pix_fmts= ff_pixfmt_list_420,
 };
 
-AVCodec msmpeg4v3_decoder = {
+AVCodec ff_msmpeg4v3_decoder = {
     "msmpeg4",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_MSMPEG4V3,
@@ -1957,11 +1949,12 @@ AVCodec msmpeg4v3_decoder = {
     ff_h263_decode_end,
     ff_h263_decode_frame,
     CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1,
+    .max_lowres= 3,
     .long_name= NULL_IF_CONFIG_SMALL("MPEG-4 part 2 Microsoft variant version 3"),
     .pix_fmts= ff_pixfmt_list_420,
 };
 
-AVCodec wmv1_decoder = {
+AVCodec ff_wmv1_decoder = {
     "wmv1",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_WMV1,
@@ -1971,6 +1964,7 @@ AVCodec wmv1_decoder = {
     ff_h263_decode_end,
     ff_h263_decode_frame,
     CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1,
+    .max_lowres= 3,
     .long_name= NULL_IF_CONFIG_SMALL("Windows Media Video 7"),
     .pix_fmts= ff_pixfmt_list_420,
 };
diff --git a/libavcodec/msmpeg4.h b/libavcodec/msmpeg4.h
index 28372a0..0570bf9 100644
--- a/libavcodec/msmpeg4.h
+++ b/libavcodec/msmpeg4.h
@@ -2,20 +2,20 @@
  * MSMPEG4 backend for ffmpeg encoder and decoder
  * copyright (c) 2007 Aurelien Jacobs <aurel at gnuage.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/msmpeg4data.c b/libavcodec/msmpeg4data.c
index f72715d..eeb8122 100644
--- a/libavcodec/msmpeg4data.c
+++ b/libavcodec/msmpeg4data.c
@@ -5,20 +5,20 @@
  *
  * msmpeg4v1 & v2 stuff by Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/msmpeg4data.h b/libavcodec/msmpeg4data.h
index 623d957..bbb802e 100644
--- a/libavcodec/msmpeg4data.h
+++ b/libavcodec/msmpeg4data.h
@@ -5,20 +5,20 @@
  *
  * msmpeg4v1 & v2 stuff by Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/msrle.c b/libavcodec/msrle.c
index 28eb5d3..f426b05 100644
--- a/libavcodec/msrle.c
+++ b/libavcodec/msrle.c
@@ -2,20 +2,20 @@
  * Micrsoft RLE Video Decoder
  * Copyright (C) 2003 the ffmpeg project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -26,9 +26,6 @@
  *   http://www.pcisys.net/~melanson/codecs/
  *
  * The MS RLE decoder outputs PAL8 colorspace data.
- *
- * Note that this decoder expects the palette colors from the end of the
- * BITMAPINFO header passed through palctrl.
  */
 
 #include <stdio.h>
@@ -46,6 +43,7 @@ typedef struct MsrleContext {
     const unsigned char *buf;
     int size;
 
+    uint32_t pal[256];
 } MsrleContext;
 
 static av_cold int msrle_decode_init(AVCodecContext *avctx)
@@ -91,13 +89,16 @@ static int msrle_decode_frame(AVCodecContext *avctx,
         return -1;
     }
 
-    if (s->avctx->palctrl) {
-        /* make the palette available */
-        memcpy(s->frame.data[1], s->avctx->palctrl->palette, AVPALETTE_SIZE);
-        if (s->avctx->palctrl->palette_changed) {
+    if (avctx->bits_per_coded_sample <= 8) {
+        const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, NULL);
+
+        if (pal) {
             s->frame.palette_has_changed = 1;
-            s->avctx->palctrl->palette_changed = 0;
+            memcpy(s->pal, pal, AVPALETTE_SIZE);
         }
+
+        /* make the palette available */
+        memcpy(s->frame.data[1], s->pal, AVPALETTE_SIZE);
     }
 
     /* FIXME how to correctly detect RLE ??? */
@@ -143,7 +144,7 @@ static av_cold int msrle_decode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec msrle_decoder = {
+AVCodec ff_msrle_decoder = {
     "msrle",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_MSRLE,
diff --git a/libavcodec/msrledec.c b/libavcodec/msrledec.c
index 6e16d53..46cd50d 100644
--- a/libavcodec/msrledec.c
+++ b/libavcodec/msrledec.c
@@ -2,20 +2,20 @@
  * Microsoft RLE decoder
  * Copyright (C) 2008 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -45,7 +45,7 @@ static int msrle_decode_pal4(AVCodecContext *avctx, AVPicture *pic,
     unsigned char rle_code;
     unsigned char extra_byte, odd_pixel;
     unsigned char stream_byte;
-    int pixel_ptr = 0;
+    unsigned int pixel_ptr = 0;
     int row_dec = pic->linesize[0];
     int row_ptr = (avctx->height - 1) * row_dec;
     int frame_size = row_dec * avctx->height;
@@ -70,39 +70,37 @@ static int msrle_decode_pal4(AVCodecContext *avctx, AVPicture *pic,
                 pixel_ptr += stream_byte;
                 FETCH_NEXT_STREAM_BYTE();
                 row_ptr -= stream_byte * row_dec;
-        } else {
-            // copy pixels from encoded stream
-            odd_pixel =  stream_byte & 1;
-            rle_code = (stream_byte + 1) / 2;
-            extra_byte = rle_code & 0x01;
-            if ((row_ptr + pixel_ptr + stream_byte > frame_size) ||
-                (row_ptr < 0)) {
-                av_log(avctx, AV_LOG_ERROR, " MS RLE: frame ptr just went out of bounds (1)\n");
-                return -1;
-            }
+            } else {
+                // copy pixels from encoded stream
+                odd_pixel =  stream_byte & 1;
+                rle_code = (stream_byte + 1) / 2;
+                extra_byte = rle_code & 0x01;
+                if (row_ptr + pixel_ptr + stream_byte > frame_size) {
+                    av_log(avctx, AV_LOG_ERROR, " MS RLE: frame ptr just went out of bounds (1)\n");
+                    return -1;
+                }
 
-            for (i = 0; i < rle_code; i++) {
-                if (pixel_ptr >= avctx->width)
-                    break;
-                FETCH_NEXT_STREAM_BYTE();
-                pic->data[0][row_ptr + pixel_ptr] = stream_byte >> 4;
-                pixel_ptr++;
-                if (i + 1 == rle_code && odd_pixel)
-                    break;
-                if (pixel_ptr >= avctx->width)
-                    break;
-                pic->data[0][row_ptr + pixel_ptr] = stream_byte & 0x0F;
-                pixel_ptr++;
-            }
+                for (i = 0; i < rle_code; i++) {
+                    if (pixel_ptr >= avctx->width)
+                        break;
+                    FETCH_NEXT_STREAM_BYTE();
+                    pic->data[0][row_ptr + pixel_ptr] = stream_byte >> 4;
+                    pixel_ptr++;
+                    if (i + 1 == rle_code && odd_pixel)
+                        break;
+                    if (pixel_ptr >= avctx->width)
+                        break;
+                    pic->data[0][row_ptr + pixel_ptr] = stream_byte & 0x0F;
+                    pixel_ptr++;
+                }
 
-            // if the RLE code is odd, skip a byte in the stream
-            if (extra_byte)
-              stream_ptr++;
+                // if the RLE code is odd, skip a byte in the stream
+                if (extra_byte)
+                    stream_ptr++;
             }
         } else {
             // decode a run of data
-            if ((row_ptr + pixel_ptr + stream_byte > frame_size) ||
-                (row_ptr < 0)) {
+            if (row_ptr + pixel_ptr + stream_byte > frame_size) {
                 av_log(avctx, AV_LOG_ERROR, " MS RLE: frame ptr just went out of bounds (1)\n");
                 return -1;
             }
@@ -138,6 +136,7 @@ static int msrle_decode_8_16_24_32(AVCodecContext *avctx, AVPicture *pic, int de
     int p1, p2, line=avctx->height - 1, pos=0, i;
     uint16_t av_uninit(pix16);
     uint32_t av_uninit(pix32);
+    unsigned int width= FFABS(pic->linesize[0]) / (depth >> 3);
 
     output = pic->data[0] + (avctx->height - 1) * pic->linesize[0];
     output_end = pic->data[0] + (avctx->height) * pic->linesize[0];
@@ -159,11 +158,11 @@ static int msrle_decode_8_16_24_32(AVCodecContext *avctx, AVPicture *pic, int de
                 p1 = *src++;
                 p2 = *src++;
                 line -= p2;
-                if (line < 0){
+                pos += p1;
+                if (line < 0 || pos >= width){
                     av_log(avctx, AV_LOG_ERROR, "Skip beyond picture bounds\n");
                     return -1;
                 }
-                pos += p1;
                 output = pic->data[0] + line * pic->linesize[0] + pos * (depth >> 3);
                 continue;
             }
diff --git a/libavcodec/msrledec.h b/libavcodec/msrledec.h
index 7495de5..5bde35a 100644
--- a/libavcodec/msrledec.h
+++ b/libavcodec/msrledec.h
@@ -2,20 +2,20 @@
  * Microsoft RLE decoder
  * Copyright (C) 2008 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,7 +25,7 @@
 #include "avcodec.h"
 
 /**
- * Decodes stream in MS RLE format into frame.
+ * Decode stream in MS RLE format into frame.
  *
  * @param avctx     codec context
  * @param pic       destination frame
diff --git a/libavcodec/msvideo1.c b/libavcodec/msvideo1.c
index 30aca39..a89ec6a 100644
--- a/libavcodec/msvideo1.c
+++ b/libavcodec/msvideo1.c
@@ -2,20 +2,20 @@
  * Microsoft Video-1 Decoder
  * Copyright (C) 2003 the ffmpeg project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,9 +25,6 @@
  * For more information about the MS Video-1 format, visit:
  *   http://www.pcisys.net/~melanson/codecs/
  *
- * This decoder outputs either PAL8 or RGB555 data, depending on the
- * whether a RGB palette was passed through palctrl;
- * if it's present, then the data is PAL8; RGB555 otherwise.
  */
 
 #include <stdio.h>
@@ -55,6 +52,7 @@ typedef struct Msvideo1Context {
 
     int mode_8bit;  /* if it's not 8-bit, it's 16-bit */
 
+    uint32_t pal[256];
 } Msvideo1Context;
 
 static av_cold int msvideo1_decode_init(AVCodecContext *avctx)
@@ -64,7 +62,7 @@ static av_cold int msvideo1_decode_init(AVCodecContext *avctx)
     s->avctx = avctx;
 
     /* figure out the colorspace based on the presence of a palette */
-    if (s->avctx->palctrl) {
+    if (s->avctx->bits_per_coded_sample == 8) {
         s->mode_8bit = 1;
         avctx->pix_fmt = PIX_FMT_PAL8;
     } else {
@@ -173,13 +171,8 @@ static void msvideo1_decode_8bit(Msvideo1Context *s)
     }
 
     /* make the palette available on the way out */
-    if (s->avctx->pix_fmt == PIX_FMT_PAL8) {
-        memcpy(s->frame.data[1], s->avctx->palctrl->palette, AVPALETTE_SIZE);
-        if (s->avctx->palctrl->palette_changed) {
-            s->frame.palette_has_changed = 1;
-            s->avctx->palctrl->palette_changed = 0;
-        }
-    }
+    if (s->avctx->pix_fmt == PIX_FMT_PAL8)
+        memcpy(s->frame.data[1], s->pal, AVPALETTE_SIZE);
 }
 
 static void msvideo1_decode_16bit(Msvideo1Context *s)
@@ -309,6 +302,15 @@ static int msvideo1_decode_frame(AVCodecContext *avctx,
         return -1;
     }
 
+    if (s->mode_8bit) {
+        const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, NULL);
+
+        if (pal) {
+            memcpy(s->pal, pal, AVPALETTE_SIZE);
+            s->frame.palette_has_changed = 1;
+        }
+    }
+
     if (s->mode_8bit)
         msvideo1_decode_8bit(s);
     else
@@ -331,7 +333,7 @@ static av_cold int msvideo1_decode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec msvideo1_decoder = {
+AVCodec ff_msvideo1_decoder = {
     "msvideo1",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_MSVIDEO1,
diff --git a/libavcodec/mxpegdec.c b/libavcodec/mxpegdec.c
new file mode 100644
index 0000000..7d6f759
--- /dev/null
+++ b/libavcodec/mxpegdec.c
@@ -0,0 +1,340 @@
+/*
+ * MxPEG decoder
+ * Copyright (c) 2011 Anatoly Nenashev
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+
+/**
+ * @file
+ * MxPEG decoder
+ */
+
+#include "mjpeg.h"
+#include "mjpegdec.h"
+
+typedef struct MXpegDecodeContext {
+    MJpegDecodeContext jpg;
+    AVFrame picture[2]; /* pictures array */
+    int picture_index; /* index of current picture */
+    int got_sof_data; /* true if SOF data successfully parsed */
+    int got_mxm_bitmask; /* true if MXM bitmask available */
+    uint8_t *mxm_bitmask; /* bitmask buffer */
+    unsigned bitmask_size; /* size of bitmask */
+    int has_complete_frame; /* true if has complete frame */
+    uint8_t *completion_bitmask; /* completion bitmask of macroblocks */
+    unsigned mb_width, mb_height; /* size of picture in MB's from MXM header */
+} MXpegDecodeContext;
+
+static av_cold int mxpeg_decode_init(AVCodecContext *avctx)
+{
+    MXpegDecodeContext *s = avctx->priv_data;
+
+    s->picture[0].reference = s->picture[1].reference = 3;
+    s->jpg.picture_ptr      = &s->picture[0];
+    ff_mjpeg_decode_init(avctx);
+
+    return 0;
+}
+
+static int mxpeg_decode_app(MXpegDecodeContext *s,
+                            const uint8_t *buf_ptr, int buf_size)
+{
+    int len;
+    if (buf_size < 2)
+        return 0;
+    len = AV_RB16(buf_ptr);
+    skip_bits(&s->jpg.gb, 8*FFMIN(len,buf_size));
+
+    return 0;
+}
+
+static int mxpeg_decode_mxm(MXpegDecodeContext *s,
+                            const uint8_t *buf_ptr, int buf_size)
+{
+    unsigned bitmask_size, mb_count;
+    int i;
+
+    s->mb_width  = AV_RL16(buf_ptr+4);
+    s->mb_height = AV_RL16(buf_ptr+6);
+    mb_count = s->mb_width * s->mb_height;
+
+    bitmask_size = (mb_count + 7) >> 3;
+    if (bitmask_size > buf_size - 12) {
+        av_log(s->jpg.avctx, AV_LOG_ERROR,
+               "MXM bitmask is not complete\n");
+        return AVERROR(EINVAL);
+    }
+
+    if (s->bitmask_size != bitmask_size) {
+        av_freep(&s->mxm_bitmask);
+        s->mxm_bitmask = av_malloc(bitmask_size);
+        if (!s->mxm_bitmask) {
+            av_log(s->jpg.avctx, AV_LOG_ERROR,
+                   "MXM bitmask memory allocation error\n");
+            return AVERROR(ENOMEM);
+        }
+
+        av_freep(&s->completion_bitmask);
+        s->completion_bitmask = av_mallocz(bitmask_size);
+        if (!s->completion_bitmask) {
+            av_log(s->jpg.avctx, AV_LOG_ERROR,
+                   "Completion bitmask memory allocation error\n");
+            return AVERROR(ENOMEM);
+        }
+
+        s->bitmask_size = bitmask_size;
+    }
+
+    memcpy(s->mxm_bitmask, buf_ptr + 12, bitmask_size);
+    s->got_mxm_bitmask = 1;
+
+    if (!s->has_complete_frame) {
+        uint8_t completion_check = 0xFF;
+        for (i = 0; i < bitmask_size; ++i) {
+            s->completion_bitmask[i] |= s->mxm_bitmask[i];
+            completion_check &= s->completion_bitmask[i];
+        }
+        s->has_complete_frame = !(completion_check ^ 0xFF);
+    }
+
+    return 0;
+}
+
+static int mxpeg_decode_com(MXpegDecodeContext *s,
+                            const uint8_t *buf_ptr, int buf_size)
+{
+    int len, ret = 0;
+    if (buf_size < 2)
+        return 0;
+    len = AV_RB16(buf_ptr);
+    if (len > 14 && len <= buf_size && !strncmp(buf_ptr + 2, "MXM", 3)) {
+        ret = mxpeg_decode_mxm(s, buf_ptr + 2, len - 2);
+    }
+    skip_bits(&s->jpg.gb, 8*FFMIN(len,buf_size));
+
+    return ret;
+}
+
+static int mxpeg_check_dimensions(MXpegDecodeContext *s, MJpegDecodeContext *jpg,
+                                  AVFrame *reference_ptr)
+{
+    if ((jpg->width + 0x0F)>>4 != s->mb_width ||
+        (jpg->height + 0x0F)>>4 != s->mb_height) {
+        av_log(jpg->avctx, AV_LOG_ERROR,
+               "Picture dimensions stored in SOF and MXM mismatch\n");
+        return AVERROR(EINVAL);
+    }
+
+    if (reference_ptr->data[0]) {
+        int i;
+        for (i = 0; i < MAX_COMPONENTS; ++i) {
+            if ( (!reference_ptr->data[i] ^ !jpg->picture_ptr->data[i]) ||
+                 reference_ptr->linesize[i] != jpg->picture_ptr->linesize[i]) {
+                av_log(jpg->avctx, AV_LOG_ERROR,
+                       "Dimensions of current and reference picture mismatch\n");
+                return AVERROR(EINVAL);
+            }
+        }
+    }
+
+    return 0;
+}
+
+static int mxpeg_decode_frame(AVCodecContext *avctx,
+                          void *data, int *data_size,
+                          AVPacket *avpkt)
+{
+    const uint8_t *buf = avpkt->data;
+    int buf_size = avpkt->size;
+    MXpegDecodeContext *s = avctx->priv_data;
+    MJpegDecodeContext *jpg = &s->jpg;
+    const uint8_t *buf_end, *buf_ptr;
+    const uint8_t *unescaped_buf_ptr;
+    int unescaped_buf_size;
+    int start_code;
+    AVFrame *picture = data;
+    int ret;
+
+    buf_ptr = buf;
+    buf_end = buf + buf_size;
+    jpg->got_picture = 0;
+    s->got_mxm_bitmask = 0;
+    while (buf_ptr < buf_end) {
+        start_code = ff_mjpeg_find_marker(jpg, &buf_ptr, buf_end,
+                                          &unescaped_buf_ptr, &unescaped_buf_size);
+        if (start_code < 0)
+            goto the_end;
+        {
+            init_get_bits(&jpg->gb, unescaped_buf_ptr, unescaped_buf_size*8);
+
+            if (start_code >= APP0 && start_code <= APP15) {
+                mxpeg_decode_app(s, unescaped_buf_ptr, unescaped_buf_size);
+            }
+
+            switch (start_code) {
+            case SOI:
+                if (jpg->got_picture) //emulating EOI
+                    goto the_end;
+                break;
+            case EOI:
+                goto the_end;
+            case DQT:
+                ret = ff_mjpeg_decode_dqt(jpg);
+                if (ret < 0) {
+                    av_log(avctx, AV_LOG_ERROR,
+                           "quantization table decode error\n");
+                    return ret;
+                }
+                break;
+            case DHT:
+                ret = ff_mjpeg_decode_dht(jpg);
+                if (ret < 0) {
+                    av_log(avctx, AV_LOG_ERROR,
+                           "huffman table decode error\n");
+                    return ret;
+                }
+                break;
+            case COM:
+                ret = mxpeg_decode_com(s, unescaped_buf_ptr,
+                                       unescaped_buf_size);
+                if (ret < 0)
+                    return ret;
+                break;
+            case SOF0:
+                s->got_sof_data = 0;
+                ret = ff_mjpeg_decode_sof(jpg);
+                if (ret < 0) {
+                    av_log(avctx, AV_LOG_ERROR,
+                           "SOF data decode error\n");
+                    return ret;
+                }
+                if (jpg->interlaced) {
+                    av_log(avctx, AV_LOG_ERROR,
+                           "Interlaced mode not supported in MxPEG\n");
+                    return AVERROR(EINVAL);
+                }
+                s->got_sof_data = 1;
+                break;
+            case SOS:
+                if (!s->got_sof_data) {
+                    av_log(avctx, AV_LOG_WARNING,
+                           "Can not process SOS without SOF data, skipping\n");
+                    break;
+                }
+                if (!jpg->got_picture) {
+                    if (jpg->first_picture) {
+                        av_log(avctx, AV_LOG_WARNING,
+                               "First picture has no SOF, skipping\n");
+                        break;
+                    }
+                    if (!s->got_mxm_bitmask){
+                        av_log(avctx, AV_LOG_WARNING,
+                               "Non-key frame has no MXM, skipping\n");
+                        break;
+                    }
+                    /* use stored SOF data to allocate current picture */
+                    if (jpg->picture_ptr->data[0])
+                        avctx->release_buffer(avctx, jpg->picture_ptr);
+                    if (avctx->get_buffer(avctx, jpg->picture_ptr) < 0) {
+                        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
+                        return AVERROR(ENOMEM);
+                    }
+                    jpg->picture_ptr->pict_type = FF_P_TYPE;
+                    jpg->picture_ptr->key_frame = 0;
+                    jpg->got_picture = 1;
+                } else {
+                    jpg->picture_ptr->pict_type = FF_I_TYPE;
+                    jpg->picture_ptr->key_frame = 1;
+                }
+
+                if (s->got_mxm_bitmask) {
+                    AVFrame *reference_ptr = &s->picture[s->picture_index ^ 1];
+                    if (mxpeg_check_dimensions(s, jpg, reference_ptr) < 0)
+                        break;
+
+                    /* allocate dummy reference picture if needed */
+                    if (!reference_ptr->data[0] &&
+                        avctx->get_buffer(avctx, reference_ptr) < 0) {
+                        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
+                        return AVERROR(ENOMEM);
+                    }
+
+                    ff_mjpeg_decode_sos(jpg, s->mxm_bitmask, reference_ptr);
+                } else {
+                    ff_mjpeg_decode_sos(jpg, NULL, NULL);
+                }
+
+                break;
+            }
+
+            buf_ptr += (get_bits_count(&jpg->gb)+7) >> 3;
+        }
+
+    }
+
+the_end:
+    if (jpg->got_picture) {
+        *data_size = sizeof(AVFrame);
+        *picture = *jpg->picture_ptr;
+        s->picture_index ^= 1;
+        jpg->picture_ptr = &s->picture[s->picture_index];
+
+        if (!s->has_complete_frame) {
+            if (!s->got_mxm_bitmask)
+                s->has_complete_frame = 1;
+            else
+                *data_size = 0;
+        }
+    }
+
+    return buf_ptr - buf;
+}
+
+static av_cold int mxpeg_decode_end(AVCodecContext *avctx)
+{
+    MXpegDecodeContext *s = avctx->priv_data;
+    MJpegDecodeContext *jpg = &s->jpg;
+    int i;
+
+    jpg->picture_ptr = NULL;
+    ff_mjpeg_decode_end(avctx);
+
+    for (i = 0; i < 2; ++i) {
+        if (s->picture[i].data[0])
+            avctx->release_buffer(avctx, &s->picture[i]);
+    }
+
+    av_freep(&s->mxm_bitmask);
+    av_freep(&s->completion_bitmask);
+
+    return 0;
+}
+
+AVCodec ff_mxpeg_decoder = {
+    .name           = "mxpeg",
+    .long_name      = NULL_IF_CONFIG_SMALL("Mobotix MxPEG video"),
+    .type           = AVMEDIA_TYPE_VIDEO,
+    .id             = CODEC_ID_MXPEG,
+    .priv_data_size = sizeof(MXpegDecodeContext),
+    .init           = mxpeg_decode_init,
+    .close          = mxpeg_decode_end,
+    .decode         = mxpeg_decode_frame,
+    .capabilities   = CODEC_CAP_DR1,
+    .max_lowres     = 3
+};
diff --git a/libavcodec/nellymoserdec.c b/libavcodec/nellymoserdec.c
index 82a3f07..5ad49ab 100644
--- a/libavcodec/nellymoserdec.c
+++ b/libavcodec/nellymoserdec.c
@@ -34,9 +34,12 @@
 #include "nellymoser.h"
 #include "libavutil/lfg.h"
 #include "libavutil/random_seed.h"
+#include "libavutil/audioconvert.h"
 #include "avcodec.h"
 #include "dsputil.h"
 #include "fft.h"
+#include "fmtconvert.h"
+#include "sinewin.h"
 
 #define ALT_BITSTREAM_READER_LE
 #include "get_bits.h"
@@ -48,10 +51,10 @@ typedef struct NellyMoserDecodeContext {
     float           state[128];
     AVLFG           random_state;
     GetBitContext   gb;
-    int             add_bias;
     float           scale_bias;
     DSPContext      dsp;
     FFTContext      imdct_ctx;
+    FmtConvertContext fmt_conv;
     DECLARE_ALIGNED(16, float,imdct_out)[NELLY_BUF_LEN * 2];
 } NellyMoserDecodeContext;
 
@@ -64,7 +67,7 @@ static void overlap_and_window(NellyMoserDecodeContext *s, float *state, float *
 
     while (bot < NELLY_BUF_LEN) {
         audio[bot] = a_in [bot]*ff_sine_128[bot]
-                    +state[bot]*ff_sine_128[top] + s->add_bias;
+                    +state[bot]*ff_sine_128[top];
 
         bot++;
         top--;
@@ -119,7 +122,7 @@ static void nelly_decode_block(NellyMoserDecodeContext *s,
         memset(&aptr[NELLY_FILL_LEN], 0,
                (NELLY_BUF_LEN - NELLY_FILL_LEN) * sizeof(float));
 
-        ff_imdct_calc(&s->imdct_ctx, s->imdct_out, aptr);
+        s->imdct_ctx.imdct_calc(&s->imdct_ctx, s->imdct_out, aptr);
         /* XXX: overlapping and windowing should be part of a more
            generic imdct function */
         overlap_and_window(s, s->state, aptr, s->imdct_out);
@@ -134,21 +137,16 @@ static av_cold int decode_init(AVCodecContext * avctx) {
     ff_mdct_init(&s->imdct_ctx, 8, 1, 1.0);
 
     dsputil_init(&s->dsp, avctx);
+    ff_fmt_convert_init(&s->fmt_conv, avctx);
 
-    if(s->dsp.float_to_int16 == ff_float_to_int16_c) {
-        s->add_bias = 385;
-        s->scale_bias = 1.0/(8*32768);
-    } else {
-        s->add_bias = 0;
-        s->scale_bias = 1.0/(1*8);
-    }
+    s->scale_bias = 1.0/(1*8);
 
     /* Generate overlap window */
     if (!ff_sine_128[127])
         ff_init_ff_sine_windows(7);
 
-    avctx->sample_fmt = SAMPLE_FMT_S16;
-    avctx->channel_layout = CH_LAYOUT_MONO;
+    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
+    avctx->channel_layout = AV_CH_LAYOUT_MONO;
     return 0;
 }
 
@@ -166,25 +164,22 @@ static int decode_tag(AVCodecContext * avctx,
     if (buf_size < avctx->block_align)
         return buf_size;
 
-    switch (buf_size) {
-        case 64:    // 8000Hz
-            blocks = 1; break;
-        case 128:   // 11025Hz
-            blocks = 2; break;
-        case 192:   // 16000Hz
-            blocks = 3; break;
-        case 256:   // 22050Hz
-            blocks = 4; break;
-        case 512:   // 44100Hz
-            blocks = 8; break;
-        default:
-            av_log(avctx, AV_LOG_DEBUG, "Tag size %d.\n", buf_size);
-            return buf_size;
+    if (buf_size % 64) {
+        av_log(avctx, AV_LOG_ERROR, "Tag size %d.\n", buf_size);
+        return buf_size;
     }
+    blocks = buf_size / 64;
+    /* Normal numbers of blocks for sample rates:
+     *  8000 Hz - 1
+     * 11025 Hz - 2
+     * 16000 Hz - 3
+     * 22050 Hz - 4
+     * 44100 Hz - 8
+     */
 
     for (i=0 ; i<blocks ; i++) {
         nelly_decode_block(s, &buf[i*NELLY_BLOCK_LEN], s->float_buf);
-        s->dsp.float_to_int16(&samples[i*NELLY_SAMPLES], s->float_buf, NELLY_SAMPLES);
+        s->fmt_conv.float_to_int16(&samples[i*NELLY_SAMPLES], s->float_buf, NELLY_SAMPLES);
         *data_size += NELLY_SAMPLES*sizeof(int16_t);
     }
 
@@ -198,7 +193,7 @@ static av_cold int decode_end(AVCodecContext * avctx) {
     return 0;
 }
 
-AVCodec nellymoser_decoder = {
+AVCodec ff_nellymoser_decoder = {
     "nellymoser",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_NELLYMOSER,
diff --git a/libavcodec/nellymoserenc.c b/libavcodec/nellymoserenc.c
index dd9a271..676e306 100644
--- a/libavcodec/nellymoserenc.c
+++ b/libavcodec/nellymoserenc.c
@@ -4,20 +4,20 @@
  *
  * Copyright (c) 2008 Bartlomiej Wolowiec
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -28,7 +28,7 @@
  *
  * Generic codec information: libavcodec/nellymoserdec.c
  *
- * Some information also from: http://samples.mplayerhq.hu/A-codecs/Nelly_Moser/ASAO/ASAO.zip
+ * Some information also from: http://samples.libav.org/A-codecs/Nelly_Moser/ASAO/ASAO.zip
  *                             (Copyright Joseph Artsimovich and UAB "DKD")
  *
  * for more information about nellymoser format, visit:
@@ -39,6 +39,7 @@
 #include "avcodec.h"
 #include "dsputil.h"
 #include "fft.h"
+#include "sinewin.h"
 
 #define BITSTREAM_WRITER_LE
 #include "put_bits.h"
@@ -113,16 +114,16 @@ static const uint8_t quant_lut_offset[8] = { 0, 0, 1, 4, 11, 32, 81, 230 };
 
 static void apply_mdct(NellyMoserEncodeContext *s)
 {
-    memcpy(s->in_buff, s->buf[s->bufsel], NELLY_BUF_LEN * sizeof(float));
-    s->dsp.vector_fmul(s->in_buff, ff_sine_128, NELLY_BUF_LEN);
+    s->dsp.vector_fmul(s->in_buff, s->buf[s->bufsel], ff_sine_128, NELLY_BUF_LEN);
     s->dsp.vector_fmul_reverse(s->in_buff + NELLY_BUF_LEN, s->buf[s->bufsel] + NELLY_BUF_LEN, ff_sine_128,
                                NELLY_BUF_LEN);
-    ff_mdct_calc(&s->mdct_ctx, s->mdct_out, s->in_buff);
+    s->mdct_ctx.mdct_calc(&s->mdct_ctx, s->mdct_out, s->in_buff);
 
-    s->dsp.vector_fmul(s->buf[s->bufsel] + NELLY_BUF_LEN, ff_sine_128, NELLY_BUF_LEN);
+    s->dsp.vector_fmul(s->buf[s->bufsel] + NELLY_BUF_LEN, s->buf[s->bufsel] + NELLY_BUF_LEN,
+                       ff_sine_128, NELLY_BUF_LEN);
     s->dsp.vector_fmul_reverse(s->buf[s->bufsel] + 2 * NELLY_BUF_LEN, s->buf[1 - s->bufsel], ff_sine_128,
                                NELLY_BUF_LEN);
-    ff_mdct_calc(&s->mdct_ctx, s->mdct_out + NELLY_BUF_LEN, s->buf[s->bufsel] + NELLY_BUF_LEN);
+    s->mdct_ctx.mdct_calc(&s->mdct_ctx, s->mdct_out + NELLY_BUF_LEN, s->buf[s->bufsel] + NELLY_BUF_LEN);
 }
 
 static av_cold int encode_init(AVCodecContext *avctx)
@@ -270,7 +271,7 @@ static void get_exponent_dynamic(NellyMoserEncodeContext *s, float *cand, int *i
 }
 
 /**
- * Encodes NELLY_SAMPLES samples. It assumes, that samples contains 3 * NELLY_BUF_LEN values
+ * Encode NELLY_SAMPLES samples. It assumes, that samples contains 3 * NELLY_BUF_LEN values
  *  @param s               encoder context
  *  @param output          output buffer
  *  @param output_size     size of output buffer
@@ -351,7 +352,7 @@ static void encode_block(NellyMoserEncodeContext *s, unsigned char *output, int
 static int encode_frame(AVCodecContext *avctx, uint8_t *frame, int buf_size, void *data)
 {
     NellyMoserEncodeContext *s = avctx->priv_data;
-    int16_t *samples = data;
+    const int16_t *samples = data;
     int i;
 
     if (s->last_frame)
@@ -382,7 +383,7 @@ static int encode_frame(AVCodecContext *avctx, uint8_t *frame, int buf_size, voi
     return 0;
 }
 
-AVCodec nellymoser_encoder = {
+AVCodec ff_nellymoser_encoder = {
     .name = "nellymoser",
     .type = AVMEDIA_TYPE_AUDIO,
     .id = CODEC_ID_NELLYMOSER,
@@ -392,4 +393,5 @@ AVCodec nellymoser_encoder = {
     .close = encode_end,
     .capabilities = CODEC_CAP_SMALL_LAST_FRAME | CODEC_CAP_DELAY,
     .long_name = NULL_IF_CONFIG_SMALL("Nellymoser Asao"),
+    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
 };
diff --git a/libavcodec/noise_bsf.c b/libavcodec/noise_bsf.c
index c49dd1f..489e3c7 100644
--- a/libavcodec/noise_bsf.c
+++ b/libavcodec/noise_bsf.c
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -39,7 +39,7 @@ static int noise(AVBitStreamFilterContext *bsfc, AVCodecContext *avctx, const ch
     return 1;
 }
 
-AVBitStreamFilter noise_bsf={
+AVBitStreamFilter ff_noise_bsf={
     "noise",
     sizeof(int),
     noise,
diff --git a/libavcodec/nuv.c b/libavcodec/nuv.c
index 791f450..61e2800 100644
--- a/libavcodec/nuv.c
+++ b/libavcodec/nuv.c
@@ -2,20 +2,20 @@
  * NuppelVideo decoder
  * Copyright (c) 2006 Reimar Doeffinger
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #include <stdio.h>
@@ -23,6 +23,7 @@
 
 #include "libavutil/bswap.h"
 #include "libavutil/lzo.h"
+#include "libavutil/imgutils.h"
 #include "avcodec.h"
 #include "dsputil.h"
 #include "rtjpeg.h"
@@ -111,12 +112,11 @@ static int codec_reinit(AVCodecContext *avctx, int width, int height, int qualit
     if (quality >= 0)
         get_quant_quality(c, quality);
     if (width != c->width || height != c->height) {
-        if (avcodec_check_dimensions(avctx, height, width) < 0)
+        if (av_image_check_size(height, width, 0, avctx) < 0)
             return 0;
         avctx->width = c->width = width;
         avctx->height = c->height = height;
-        c->decomp_size = c->height * c->width * 3 / 2;
-        c->decomp_buf = av_realloc(c->decomp_buf, c->decomp_size + AV_LZO_OUTPUT_PADDING);
+        av_fast_malloc(&c->decomp_buf, &c->decomp_size, c->height * c->width * 3 / 2);
         if (!c->decomp_buf) {
             av_log(avctx, AV_LOG_ERROR, "Can't allocate decompression buffer.\n");
             return 0;
@@ -272,7 +272,7 @@ static av_cold int decode_end(AVCodecContext *avctx) {
     return 0;
 }
 
-AVCodec nuv_decoder = {
+AVCodec ff_nuv_decoder = {
     "nuv",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_NUV,
diff --git a/libavcodec/opt.c b/libavcodec/opt.c
index f9cba05..f41fae0 100644
--- a/libavcodec/opt.c
+++ b/libavcodec/opt.c
@@ -1,205 +1,71 @@
 /*
- * AVOptions
- * Copyright (c) 2005 Michael Niedermayer <michaelni at gmx.at>
+ * AVOptions ABI compatibility wrapper
+ * Copyright (c) 2010 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
-/**
- * @file
- * AVOptions
- * @author Michael Niedermayer <michaelni at gmx.at>
- */
-
 #include "avcodec.h"
 #include "opt.h"
-#include "eval.h"
 
-//FIXME order them and do a bin search
-const AVOption *av_find_opt(void *v, const char *name, const char *unit, int mask, int flags){
-    AVClass *c= *(AVClass**)v; //FIXME silly way of storing AVClass
-    const AVOption *o= c->option;
+#if LIBAVCODEC_VERSION_MAJOR < 53 && CONFIG_SHARED && HAVE_SYMVER
 
-    for(;o && o->name; o++){
-        if(!strcmp(o->name, name) && (!unit || (o->unit && !strcmp(o->unit, unit))) && (o->flags & mask) == flags )
-            return o;
-    }
-    return NULL;
+FF_SYMVER(const AVOption *, av_find_opt, (void *obj, const char *name, const char *unit, int mask, int flags), "LIBAVCODEC_52"){
+    return av_find_opt(obj, name, unit, mask, flags);
 }
-
-const AVOption *av_next_option(void *obj, const AVOption *last){
-    if(last && last[1].name) return ++last;
-    else if(last)            return NULL;
-    else                     return (*(AVClass**)obj)->option;
+FF_SYMVER(int, av_set_string3, (void *obj, const char *name, const char *val, int alloc, const AVOption **o_out), "LIBAVCODEC_52"){
+    return av_set_string3(obj, name, val, alloc, o_out);
 }
-
-static int av_set_number2(void *obj, const char *name, double num, int den, int64_t intnum, const AVOption **o_out){
-    const AVOption *o= av_find_opt(obj, name, NULL, 0, 0);
-    void *dst;
-    if(o_out)
-        *o_out= o;
-    if(!o || o->offset<=0)
-        return AVERROR(ENOENT);
-
-    if(o->max*den < num*intnum || o->min*den > num*intnum) {
-        av_log(obj, AV_LOG_ERROR, "Value %lf for parameter '%s' out of range\n", num, name);
-        return AVERROR(ERANGE);
-    }
-
-    dst= ((uint8_t*)obj) + o->offset;
-
-    switch(o->type){
-    case FF_OPT_TYPE_FLAGS:
-    case FF_OPT_TYPE_INT:   *(int       *)dst= llrint(num/den)*intnum; break;
-    case FF_OPT_TYPE_INT64: *(int64_t   *)dst= llrint(num/den)*intnum; break;
-    case FF_OPT_TYPE_FLOAT: *(float     *)dst= num*intnum/den;         break;
-    case FF_OPT_TYPE_DOUBLE:*(double    *)dst= num*intnum/den;         break;
-    case FF_OPT_TYPE_RATIONAL:
-        if((int)num == num) *(AVRational*)dst= (AVRational){num*intnum, den};
-        else                *(AVRational*)dst= av_d2q(num*intnum/den, 1<<24);
-        break;
-    default:
-        return AVERROR(EINVAL);
-    }
-    return 0;
+FF_SYMVER(const AVOption *, av_set_double, (void *obj, const char *name, double n), "LIBAVCODEC_52"){
+    return av_set_double(obj, name, n);
 }
-
-static const AVOption *av_set_number(void *obj, const char *name, double num, int den, int64_t intnum){
-    const AVOption *o = NULL;
-    if (av_set_number2(obj, name, num, den, intnum, &o) < 0)
-        return NULL;
-    else
-        return o;
+FF_SYMVER(const AVOption *, av_set_q, (void *obj, const char *name, AVRational n), "LIBAVCODEC_52"){
+    return av_set_q(obj, name, n);
 }
-
-static const double const_values[]={
-    M_PI,
-    M_E,
-    FF_QP2LAMBDA,
-    0
-};
-
-static const char * const const_names[]={
-    "PI",
-    "E",
-    "QP2LAMBDA",
-    0
-};
-
-static int hexchar2int(char c) {
-    if (c >= '0' && c <= '9') return c - '0';
-    if (c >= 'a' && c <= 'f') return c - 'a' + 10;
-    if (c >= 'A' && c <= 'F') return c - 'A' + 10;
-    return -1;
+FF_SYMVER(const AVOption *, av_set_int, (void *obj, const char *name, int64_t n), "LIBAVCODEC_52"){
+    return av_set_int(obj, name, n);
 }
-
-int av_set_string3(void *obj, const char *name, const char *val, int alloc, const AVOption **o_out){
-    int ret;
-    const AVOption *o= av_find_opt(obj, name, NULL, 0, 0);
-    if (o_out)
-        *o_out = o;
-    if(!o)
-        return AVERROR(ENOENT);
-    if(!val || o->offset<=0)
-        return AVERROR(EINVAL);
-
-    if(o->type == FF_OPT_TYPE_BINARY){
-        uint8_t **dst = (uint8_t **)(((uint8_t*)obj) + o->offset);
-        int *lendst = (int *)(dst + 1);
-        uint8_t *bin, *ptr;
-        int len = strlen(val);
-        av_freep(dst);
-        *lendst = 0;
-        if (len & 1) return AVERROR(EINVAL);
-        len /= 2;
-        ptr = bin = av_malloc(len);
-        while (*val) {
-            int a = hexchar2int(*val++);
-            int b = hexchar2int(*val++);
-            if (a < 0 || b < 0) {
-                av_free(bin);
-                return AVERROR(EINVAL);
-            }
-            *ptr++ = (a << 4) | b;
-        }
-        *dst = bin;
-        *lendst = len;
-        return 0;
-    }
-    if(o->type != FF_OPT_TYPE_STRING){
-        int notfirst=0;
-        for(;;){
-            int i;
-            char buf[256];
-            int cmd=0;
-            double d;
-            const char *error = NULL;
-
-            if(*val == '+' || *val == '-')
-                cmd= *(val++);
-
-            for(i=0; i<sizeof(buf)-1 && val[i] && val[i]!='+' && val[i]!='-'; i++)
-                buf[i]= val[i];
-            buf[i]=0;
-
-            d = ff_parse_and_eval_expr(buf, const_values, const_names, NULL, NULL, NULL, NULL, NULL, &error);
-            if(isnan(d)) {
-                const AVOption *o_named= av_find_opt(obj, buf, o->unit, 0, 0);
-                if(o_named && o_named->type == FF_OPT_TYPE_CONST)
-                    d= o_named->default_val;
-                else if(!strcmp(buf, "default")) d= o->default_val;
-                else if(!strcmp(buf, "max"    )) d= o->max;
-                else if(!strcmp(buf, "min"    )) d= o->min;
-                else if(!strcmp(buf, "none"   )) d= 0;
-                else if(!strcmp(buf, "all"    )) d= ~0;
-                else {
-                    if (error)
-                        av_log(obj, AV_LOG_ERROR, "Unable to parse option value \"%s\": %s\n", val, error);
-                    return AVERROR(EINVAL);
-                }
-            }
-            if(o->type == FF_OPT_TYPE_FLAGS){
-                if     (cmd=='+') d= av_get_int(obj, name, NULL) | (int64_t)d;
-                else if(cmd=='-') d= av_get_int(obj, name, NULL) &~(int64_t)d;
-            }else{
-                if     (cmd=='+') d= notfirst*av_get_double(obj, name, NULL) + d;
-                else if(cmd=='-') d= notfirst*av_get_double(obj, name, NULL) - d;
-            }
-
-            if ((ret = av_set_number2(obj, name, d, 1, 1, o_out)) < 0)
-                return ret;
-            val+= i;
-            if(!*val)
-                return 0;
-            notfirst=1;
-        }
-        return AVERROR(EINVAL);
-    }
-
-    if(alloc){
-        av_free(*(void**)(((uint8_t*)obj) + o->offset));
-        val= av_strdup(val);
-    }
-
-    memcpy(((uint8_t*)obj) + o->offset, &val, sizeof(val));
-    return 0;
+FF_SYMVER(double, av_get_double, (void *obj, const char *name, const AVOption **o_out), "LIBAVCODEC_52"){
+    return av_get_double(obj, name, o_out);
+}
+FF_SYMVER(AVRational, av_get_q, (void *obj, const char *name, const AVOption **o_out), "LIBAVCODEC_52"){
+    return av_get_q(obj, name, o_out);
+}
+FF_SYMVER(int64_t, av_get_int, (void *obj, const char *name, const AVOption **o_out), "LIBAVCODEC_52"){
+    return av_get_int(obj, name, o_out);
+}
+FF_SYMVER(const char *, av_get_string, (void *obj, const char *name, const AVOption **o_out, char *buf, int buf_len), "LIBAVCODEC_52"){
+    return av_get_string(obj, name, o_out, buf, buf_len);
+}
+FF_SYMVER(const AVOption *, av_next_option, (void *obj, const AVOption *last), "LIBAVCODEC_52"){
+    return av_next_option(obj, last);
 }
+FF_SYMVER(int, av_opt_show2, (void *obj, void *av_log_obj, int req_flags, int rej_flags), "LIBAVCODEC_52"){
+    return av_opt_show2(obj, av_log_obj, req_flags, rej_flags);
+}
+FF_SYMVER(void, av_opt_set_defaults, (void *s), "LIBAVCODEC_52"){
+    return av_opt_set_defaults(s);
+}
+FF_SYMVER(void, av_opt_set_defaults2, (void *s, int mask, int flags), "LIBAVCODEC_52"){
+    return av_opt_set_defaults2(s, mask, flags);
+}
+#endif
 
-#if LIBAVCODEC_VERSION_MAJOR < 53
+#if FF_API_SET_STRING_OLD
 const AVOption *av_set_string2(void *obj, const char *name, const char *val, int alloc){
     const AVOption *o;
     if (av_set_string3(obj, name, val, alloc, &o) < 0)
@@ -215,241 +81,9 @@ const AVOption *av_set_string(void *obj, const char *name, const char *val){
 }
 #endif
 
-const AVOption *av_set_double(void *obj, const char *name, double n){
-    return av_set_number(obj, name, n, 1, 1);
-}
-
-const AVOption *av_set_q(void *obj, const char *name, AVRational n){
-    return av_set_number(obj, name, n.num, n.den, 1);
-}
-
-const AVOption *av_set_int(void *obj, const char *name, int64_t n){
-    return av_set_number(obj, name, 1, 1, n);
-}
-
-/**
- *
- * @param buf a buffer which is used for returning non string values as strings, can be NULL
- * @param buf_len allocated length in bytes of buf
- */
-const char *av_get_string(void *obj, const char *name, const AVOption **o_out, char *buf, int buf_len){
-    const AVOption *o= av_find_opt(obj, name, NULL, 0, 0);
-    void *dst;
-    uint8_t *bin;
-    int len, i;
-    if(!o || o->offset<=0)
-        return NULL;
-    if(o->type != FF_OPT_TYPE_STRING && (!buf || !buf_len))
-        return NULL;
-
-    dst= ((uint8_t*)obj) + o->offset;
-    if(o_out) *o_out= o;
-
-    switch(o->type){
-    case FF_OPT_TYPE_FLAGS:     snprintf(buf, buf_len, "0x%08X",*(int    *)dst);break;
-    case FF_OPT_TYPE_INT:       snprintf(buf, buf_len, "%d" , *(int    *)dst);break;
-    case FF_OPT_TYPE_INT64:     snprintf(buf, buf_len, "%"PRId64, *(int64_t*)dst);break;
-    case FF_OPT_TYPE_FLOAT:     snprintf(buf, buf_len, "%f" , *(float  *)dst);break;
-    case FF_OPT_TYPE_DOUBLE:    snprintf(buf, buf_len, "%f" , *(double *)dst);break;
-    case FF_OPT_TYPE_RATIONAL:  snprintf(buf, buf_len, "%d/%d", ((AVRational*)dst)->num, ((AVRational*)dst)->den);break;
-    case FF_OPT_TYPE_STRING:    return *(void**)dst;
-    case FF_OPT_TYPE_BINARY:
-        len = *(int*)(((uint8_t *)dst) + sizeof(uint8_t *));
-        if(len >= (buf_len + 1)/2) return NULL;
-        bin = *(uint8_t**)dst;
-        for(i = 0; i < len; i++) snprintf(buf + i*2, 3, "%02X", bin[i]);
-        break;
-    default: return NULL;
-    }
-    return buf;
-}
-
-static int av_get_number(void *obj, const char *name, const AVOption **o_out, double *num, int *den, int64_t *intnum){
-    const AVOption *o= av_find_opt(obj, name, NULL, 0, 0);
-    void *dst;
-    if(!o || o->offset<=0)
-        goto error;
-
-    dst= ((uint8_t*)obj) + o->offset;
-
-    if(o_out) *o_out= o;
-
-    switch(o->type){
-    case FF_OPT_TYPE_FLAGS:     *intnum= *(unsigned int*)dst;return 0;
-    case FF_OPT_TYPE_INT:       *intnum= *(int    *)dst;return 0;
-    case FF_OPT_TYPE_INT64:     *intnum= *(int64_t*)dst;return 0;
-    case FF_OPT_TYPE_FLOAT:     *num=    *(float  *)dst;return 0;
-    case FF_OPT_TYPE_DOUBLE:    *num=    *(double *)dst;return 0;
-    case FF_OPT_TYPE_RATIONAL:  *intnum= ((AVRational*)dst)->num;
-                                *den   = ((AVRational*)dst)->den;
-                                                        return 0;
-    }
-error:
-    *den=*intnum=0;
-    return -1;
-}
-
-double av_get_double(void *obj, const char *name, const AVOption **o_out){
-    int64_t intnum=1;
-    double num=1;
-    int den=1;
-
-    av_get_number(obj, name, o_out, &num, &den, &intnum);
-    return num*intnum/den;
-}
-
-AVRational av_get_q(void *obj, const char *name, const AVOption **o_out){
-    int64_t intnum=1;
-    double num=1;
-    int den=1;
-
-    av_get_number(obj, name, o_out, &num, &den, &intnum);
-    if(num == 1.0 && (int)intnum == intnum)
-        return (AVRational){intnum, den};
-    else
-        return av_d2q(num*intnum/den, 1<<24);
-}
-
-int64_t av_get_int(void *obj, const char *name, const AVOption **o_out){
-    int64_t intnum=1;
-    double num=1;
-    int den=1;
-
-    av_get_number(obj, name, o_out, &num, &den, &intnum);
-    return num*intnum/den;
-}
-
-static void opt_list(void *obj, void *av_log_obj, const char *unit)
-{
-    const AVOption *opt=NULL;
-
-    while((opt= av_next_option(obj, opt))){
-        if(!(opt->flags & (AV_OPT_FLAG_ENCODING_PARAM|AV_OPT_FLAG_DECODING_PARAM)))
-            continue;
-
-        /* Don't print CONST's on level one.
-         * Don't print anything but CONST's on level two.
-         * Only print items from the requested unit.
-         */
-        if (!unit && opt->type==FF_OPT_TYPE_CONST)
-            continue;
-        else if (unit && opt->type!=FF_OPT_TYPE_CONST)
-            continue;
-        else if (unit && opt->type==FF_OPT_TYPE_CONST && strcmp(unit, opt->unit))
-            continue;
-        else if (unit && opt->type == FF_OPT_TYPE_CONST)
-            av_log(av_log_obj, AV_LOG_INFO, "   %-15s ", opt->name);
-        else
-            av_log(av_log_obj, AV_LOG_INFO, "-%-17s ", opt->name);
-
-        switch( opt->type )
-        {
-            case FF_OPT_TYPE_FLAGS:
-                av_log( av_log_obj, AV_LOG_INFO, "%-7s ", "<flags>" );
-                break;
-            case FF_OPT_TYPE_INT:
-                av_log( av_log_obj, AV_LOG_INFO, "%-7s ", "<int>" );
-                break;
-            case FF_OPT_TYPE_INT64:
-                av_log( av_log_obj, AV_LOG_INFO, "%-7s ", "<int64>" );
-                break;
-            case FF_OPT_TYPE_DOUBLE:
-                av_log( av_log_obj, AV_LOG_INFO, "%-7s ", "<double>" );
-                break;
-            case FF_OPT_TYPE_FLOAT:
-                av_log( av_log_obj, AV_LOG_INFO, "%-7s ", "<float>" );
-                break;
-            case FF_OPT_TYPE_STRING:
-                av_log( av_log_obj, AV_LOG_INFO, "%-7s ", "<string>" );
-                break;
-            case FF_OPT_TYPE_RATIONAL:
-                av_log( av_log_obj, AV_LOG_INFO, "%-7s ", "<rational>" );
-                break;
-            case FF_OPT_TYPE_BINARY:
-                av_log( av_log_obj, AV_LOG_INFO, "%-7s ", "<binary>" );
-                break;
-            case FF_OPT_TYPE_CONST:
-            default:
-                av_log( av_log_obj, AV_LOG_INFO, "%-7s ", "" );
-                break;
-        }
-        av_log(av_log_obj, AV_LOG_INFO, "%c", (opt->flags & AV_OPT_FLAG_ENCODING_PARAM) ? 'E' : '.');
-        av_log(av_log_obj, AV_LOG_INFO, "%c", (opt->flags & AV_OPT_FLAG_DECODING_PARAM) ? 'D' : '.');
-        av_log(av_log_obj, AV_LOG_INFO, "%c", (opt->flags & AV_OPT_FLAG_VIDEO_PARAM   ) ? 'V' : '.');
-        av_log(av_log_obj, AV_LOG_INFO, "%c", (opt->flags & AV_OPT_FLAG_AUDIO_PARAM   ) ? 'A' : '.');
-        av_log(av_log_obj, AV_LOG_INFO, "%c", (opt->flags & AV_OPT_FLAG_SUBTITLE_PARAM) ? 'S' : '.');
-
-        if(opt->help)
-            av_log(av_log_obj, AV_LOG_INFO, " %s", opt->help);
-        av_log(av_log_obj, AV_LOG_INFO, "\n");
-        if (opt->unit && opt->type != FF_OPT_TYPE_CONST) {
-            opt_list(obj, av_log_obj, opt->unit);
-        }
-    }
-}
-
+#if FF_API_OPT_SHOW
 int av_opt_show(void *obj, void *av_log_obj){
-    if(!obj)
-        return -1;
-
-    av_log(av_log_obj, AV_LOG_INFO, "%s AVOptions:\n", (*(AVClass**)obj)->class_name);
-
-    opt_list(obj, av_log_obj, NULL);
-
-    return 0;
-}
-
-/** Set the values of the AVCodecContext or AVFormatContext structure.
- * They are set to the defaults specified in the according AVOption options
- * array default_val field.
- *
- * @param s AVCodecContext or AVFormatContext for which the defaults will be set
- */
-void av_opt_set_defaults2(void *s, int mask, int flags)
-{
-    const AVOption *opt = NULL;
-    while ((opt = av_next_option(s, opt)) != NULL) {
-        if((opt->flags & mask) != flags)
-            continue;
-        switch(opt->type) {
-            case FF_OPT_TYPE_CONST:
-                /* Nothing to be done here */
-            break;
-            case FF_OPT_TYPE_FLAGS:
-            case FF_OPT_TYPE_INT: {
-                int val;
-                val = opt->default_val;
-                av_set_int(s, opt->name, val);
-            }
-            break;
-            case FF_OPT_TYPE_INT64:
-                if((double)(opt->default_val+0.6) == opt->default_val)
-                    av_log(s, AV_LOG_DEBUG, "loss of precision in default of %s\n", opt->name);
-                av_set_int(s, opt->name, opt->default_val);
-            break;
-            case FF_OPT_TYPE_FLOAT: {
-                double val;
-                val = opt->default_val;
-                av_set_double(s, opt->name, val);
-            }
-            break;
-            case FF_OPT_TYPE_RATIONAL: {
-                AVRational val;
-                val = av_d2q(opt->default_val, INT_MAX);
-                av_set_q(s, opt->name, val);
-            }
-            break;
-            case FF_OPT_TYPE_STRING:
-            case FF_OPT_TYPE_BINARY:
-                /* Cannot set default for string as default_val is of type * double */
-            break;
-            default:
-                av_log(s, AV_LOG_DEBUG, "AVOption type %d of option %s not implemented yet\n", opt->type, opt->name);
-        }
-    }
+    return av_opt_show2(obj, av_log_obj,
+                        AV_OPT_FLAG_ENCODING_PARAM|AV_OPT_FLAG_DECODING_PARAM, 0);
 }
-
-void av_opt_set_defaults(void *s){
-    av_opt_set_defaults2(s, 0, 0);
-}
-
+#endif
diff --git a/libavcodec/opt.h b/libavcodec/opt.h
index 55ca4ea..cf54354 100644
--- a/libavcodec/opt.h
+++ b/libavcodec/opt.h
@@ -2,20 +2,20 @@
  * AVOptions
  * copyright (c) 2005 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -29,130 +29,9 @@
 
 #include "libavutil/rational.h"
 #include "avcodec.h"
+#include "libavutil/opt.h"
 
-enum AVOptionType{
-    FF_OPT_TYPE_FLAGS,
-    FF_OPT_TYPE_INT,
-    FF_OPT_TYPE_INT64,
-    FF_OPT_TYPE_DOUBLE,
-    FF_OPT_TYPE_FLOAT,
-    FF_OPT_TYPE_STRING,
-    FF_OPT_TYPE_RATIONAL,
-    FF_OPT_TYPE_BINARY,  ///< offset must point to a pointer immediately followed by an int for the length
-    FF_OPT_TYPE_CONST=128,
-};
-
-/**
- * AVOption
- */
-typedef struct AVOption {
-    const char *name;
-
-    /**
-     * short English help text
-     * @todo What about other languages?
-     */
-    const char *help;
-
-    /**
-     * The offset relative to the context structure where the option
-     * value is stored. It should be 0 for named constants.
-     */
-    int offset;
-    enum AVOptionType type;
-
-    /**
-     * the default value for scalar options
-     */
-    double default_val;
-    double min;                 ///< minimum valid value for the option
-    double max;                 ///< maximum valid value for the option
-
-    int flags;
-#define AV_OPT_FLAG_ENCODING_PARAM  1   ///< a generic parameter which can be set by the user for muxing or encoding
-#define AV_OPT_FLAG_DECODING_PARAM  2   ///< a generic parameter which can be set by the user for demuxing or decoding
-#define AV_OPT_FLAG_METADATA        4   ///< some data extracted or inserted into the file like title, comment, ...
-#define AV_OPT_FLAG_AUDIO_PARAM     8
-#define AV_OPT_FLAG_VIDEO_PARAM     16
-#define AV_OPT_FLAG_SUBTITLE_PARAM  32
-//FIXME think about enc-audio, ... style flags
-
-    /**
-     * The logical unit to which the option belongs. Non-constant
-     * options and corresponding named constants share the same
-     * unit. May be NULL.
-     */
-    const char *unit;
-} AVOption;
-
-/**
- * AVOption2.
- * THIS IS NOT PART OF THE API/ABI YET!
- * This is identical to AVOption except that default_val was replaced by
- * an union, it should be compatible with AVOption on normal platforms.
- */
-typedef struct AVOption2 {
-    const char *name;
-
-    /**
-     * short English help text
-     * @todo What about other languages?
-     */
-    const char *help;
-
-    /**
-     * The offset relative to the context structure where the option
-     * value is stored. It should be 0 for named constants.
-     */
-    int offset;
-    enum AVOptionType type;
-
-    /**
-     * the default value for scalar options
-     */
-    union {
-        double dbl;
-        const char *str;
-    } default_val;
-
-    double min;                 ///< minimum valid value for the option
-    double max;                 ///< maximum valid value for the option
-
-    int flags;
-/*
-#define AV_OPT_FLAG_ENCODING_PARAM  1   ///< a generic parameter which can be set by the user for muxing or encoding
-#define AV_OPT_FLAG_DECODING_PARAM  2   ///< a generic parameter which can be set by the user for demuxing or decoding
-#define AV_OPT_FLAG_METADATA        4   ///< some data extracted or inserted into the file like title, comment, ...
-#define AV_OPT_FLAG_AUDIO_PARAM     8
-#define AV_OPT_FLAG_VIDEO_PARAM     16
-#define AV_OPT_FLAG_SUBTITLE_PARAM  32
-*/
-//FIXME think about enc-audio, ... style flags
-
-    /**
-     * The logical unit to which the option belongs. Non-constant
-     * options and corresponding named constants share the same
-     * unit. May be NULL.
-     */
-    const char *unit;
-} AVOption2;
-
-
-/**
- * Looks for an option in obj. Looks only for the options which
- * have the flags set as specified in mask and flags (that is,
- * for which it is the case that opt->flags & mask == flags).
- *
- * @param[in] obj a pointer to a struct whose first element is a
- * pointer to an AVClass
- * @param[in] name the name of the option to look for
- * @param[in] unit the unit of the option to look for, or any if NULL
- * @return a pointer to the option found, or NULL if no option
- * has been found
- */
-const AVOption *av_find_opt(void *obj, const char *name, const char *unit, int mask, int flags);
-
-#if LIBAVCODEC_VERSION_MAJOR < 53
+#if FF_API_SET_STRING_OLD
 /**
  * @see av_set_string2()
  */
@@ -166,46 +45,11 @@ attribute_deprecated const AVOption *av_set_string(void *obj, const char *name,
  */
 attribute_deprecated const AVOption *av_set_string2(void *obj, const char *name, const char *val, int alloc);
 #endif
-
+#if FF_API_OPT_SHOW
 /**
- * Sets the field of obj with the given name to value.
- *
- * @param[in] obj A struct whose first element is a pointer to an
- * AVClass.
- * @param[in] name the name of the field to set
- * @param[in] val The value to set. If the field is not of a string
- * type, then the given string is parsed.
- * SI postfixes and some named scalars are supported.
- * If the field is of a numeric type, it has to be a numeric or named
- * scalar. Behavior with more than one scalar and +- infix operators
- * is undefined.
- * If the field is of a flags type, it has to be a sequence of numeric
- * scalars or named flags separated by '+' or '-'. Prefixing a flag
- * with '+' causes it to be set without affecting the other flags;
- * similarly, '-' unsets a flag.
- * @param[out] o_out if non-NULL put here a pointer to the AVOption
- * found
- * @param alloc when 1 then the old value will be av_freed() and the
- *                     new av_strduped()
- *              when 0 then no av_free() nor av_strdup() will be used
- * @return 0 if the value has been set, or an AVERROR code in case of
- * error:
- * AVERROR(ENOENT) if no matching option exists
- * AVERROR(ERANGE) if the value is out of range
- * AVERROR(EINVAL) if the value is not valid
+ * @deprecated Use av_opt_show2() instead.
  */
-int av_set_string3(void *obj, const char *name, const char *val, int alloc, const AVOption **o_out);
-
-const AVOption *av_set_double(void *obj, const char *name, double n);
-const AVOption *av_set_q(void *obj, const char *name, AVRational n);
-const AVOption *av_set_int(void *obj, const char *name, int64_t n);
-double av_get_double(void *obj, const char *name, const AVOption **o_out);
-AVRational av_get_q(void *obj, const char *name, const AVOption **o_out);
-int64_t av_get_int(void *obj, const char *name, const AVOption **o_out);
-const char *av_get_string(void *obj, const char *name, const AVOption **o_out, char *buf, int buf_len);
-const AVOption *av_next_option(void *obj, const AVOption *last);
-int av_opt_show(void *obj, void *av_log_obj);
-void av_opt_set_defaults(void *s);
-void av_opt_set_defaults2(void *s, int mask, int flags);
+attribute_deprecated int av_opt_show(void *obj, void *av_log_obj);
+#endif
 
 #endif /* AVCODEC_OPT_H */
diff --git a/libavcodec/options.c b/libavcodec/options.c
index 6835352..5856f96 100644
--- a/libavcodec/options.c
+++ b/libavcodec/options.c
@@ -2,20 +2,20 @@
  * Copyright (c) 2001 Fabrice Bellard
  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,7 +25,7 @@
  */
 
 #include "avcodec.h"
-#include "opt.h"
+#include "libavutil/opt.h"
 #include <float.h>              /* FLT_MIN, FLT_MAX */
 
 static const char* context_to_name(void* ptr) {
@@ -105,7 +105,9 @@ static const AVOption options[]={
 {"extradata_size", NULL, OFFSET(extradata_size), FF_OPT_TYPE_INT, DEFAULT, INT_MIN, INT_MAX},
 {"time_base", NULL, OFFSET(time_base), FF_OPT_TYPE_RATIONAL, DEFAULT, INT_MIN, INT_MAX},
 {"g", "set the group of picture size", OFFSET(gop_size), FF_OPT_TYPE_INT, 12, INT_MIN, INT_MAX, V|E},
+#if FF_API_RATE_EMU
 {"rate_emu", "frame rate emulation", OFFSET(rate_emu), FF_OPT_TYPE_INT, DEFAULT, INT_MIN, INT_MAX},
+#endif
 {"ar", "set audio sampling rate (in Hz)", OFFSET(sample_rate), FF_OPT_TYPE_INT, DEFAULT, INT_MIN, INT_MAX},
 {"ac", "set number of audio channels", OFFSET(channels), FF_OPT_TYPE_INT, DEFAULT, INT_MIN, INT_MAX},
 {"cutoff", "set cutoff bandwidth", OFFSET(cutoff), FF_OPT_TYPE_INT, DEFAULT, INT_MIN, INT_MAX, A|E},
@@ -117,15 +119,17 @@ static const AVOption options[]={
 {"delay", NULL, OFFSET(delay), FF_OPT_TYPE_INT, DEFAULT, INT_MIN, INT_MAX},
 {"qcomp", "video quantizer scale compression (VBR)", OFFSET(qcompress), FF_OPT_TYPE_FLOAT, 0.5, -FLT_MAX, FLT_MAX, V|E},
 {"qblur", "video quantizer scale blur (VBR)", OFFSET(qblur), FF_OPT_TYPE_FLOAT, 0.5, 0, FLT_MAX, V|E},
-{"qmin", "min video quantizer scale (VBR)", OFFSET(qmin), FF_OPT_TYPE_INT, 2, 1, 51, V|E},
-{"qmax", "max video quantizer scale (VBR)", OFFSET(qmax), FF_OPT_TYPE_INT, 31, 1, 51, V|E},
+{"qmin", "min video quantizer scale (VBR)", OFFSET(qmin), FF_OPT_TYPE_INT, 2, 0, 69, V|E},
+{"qmax", "max video quantizer scale (VBR)", OFFSET(qmax), FF_OPT_TYPE_INT, 31, 0, 69, V|E},
 {"qdiff", "max difference between the quantizer scale (VBR)", OFFSET(max_qdiff), FF_OPT_TYPE_INT, 3, INT_MIN, INT_MAX, V|E},
 {"bf", "use 'frames' B frames", OFFSET(max_b_frames), FF_OPT_TYPE_INT, DEFAULT, 0, FF_MAX_B_FRAMES, V|E},
 {"b_qfactor", "qp factor between p and b frames", OFFSET(b_quant_factor), FF_OPT_TYPE_FLOAT, 1.25, -FLT_MAX, FLT_MAX, V|E},
 {"rc_strategy", "ratecontrol method", OFFSET(rc_strategy), FF_OPT_TYPE_INT, DEFAULT, INT_MIN, INT_MAX, V|E},
 {"b_strategy", "strategy to choose between I/P/B-frames", OFFSET(b_frame_strategy), FF_OPT_TYPE_INT, 0, INT_MIN, INT_MAX, V|E},
 {"wpredp", "weighted prediction analysis method", OFFSET(weighted_p_pred), FF_OPT_TYPE_INT, 0, INT_MIN, INT_MAX, V|E},
-{"hurry_up", NULL, OFFSET(hurry_up), FF_OPT_TYPE_INT, DEFAULT, INT_MIN, INT_MAX, V|D},
+#if FF_API_HURRY_UP
+{"hurry_up", "deprecated, use skip_idct/skip_frame instead", OFFSET(hurry_up), FF_OPT_TYPE_INT, DEFAULT, INT_MIN, INT_MAX, V|D},
+#endif
 {"ps", "rtp payload size in bytes", OFFSET(rtp_payload_size), FF_OPT_TYPE_INT, DEFAULT, INT_MIN, INT_MAX, V|E},
 {"mv_bits", NULL, OFFSET(mv_bits), FF_OPT_TYPE_INT, DEFAULT, INT_MIN, INT_MAX},
 {"header_bits", NULL, OFFSET(header_bits), FF_OPT_TYPE_INT, DEFAULT, INT_MIN, INT_MAX},
@@ -160,7 +164,10 @@ static const AVOption options[]={
 {"very", "strictly conform to a older more strict version of the spec or reference software", 0, FF_OPT_TYPE_CONST, FF_COMPLIANCE_VERY_STRICT, INT_MIN, INT_MAX, V|D|E, "strict"},
 {"strict", "strictly conform to all the things in the spec no matter what consequences", 0, FF_OPT_TYPE_CONST, FF_COMPLIANCE_STRICT, INT_MIN, INT_MAX, V|D|E, "strict"},
 {"normal", NULL, 0, FF_OPT_TYPE_CONST, FF_COMPLIANCE_NORMAL, INT_MIN, INT_MAX, V|D|E, "strict"},
-{"inofficial", "allow unofficial extensions", 0, FF_OPT_TYPE_CONST, FF_COMPLIANCE_INOFFICIAL, INT_MIN, INT_MAX, V|D|E, "strict"},
+#if FF_API_INOFFICIAL
+{"inofficial", "allow unofficial extensions (deprecated - use unofficial)", 0, FF_OPT_TYPE_CONST, FF_COMPLIANCE_UNOFFICIAL, INT_MIN, INT_MAX, V|D|E, "strict"},
+#endif
+{"unofficial", "allow unofficial extensions", 0, FF_OPT_TYPE_CONST, FF_COMPLIANCE_UNOFFICIAL, INT_MIN, INT_MAX, V|D|E, "strict"},
 {"experimental", "allow non standardized experimental things", 0, FF_OPT_TYPE_CONST, FF_COMPLIANCE_EXPERIMENTAL, INT_MIN, INT_MAX, V|D|E, "strict"},
 {"b_qoffset", "qp offset between P and B frames", OFFSET(b_quant_offset), FF_OPT_TYPE_FLOAT, 1.25, -FLT_MAX, FLT_MAX, V|E},
 {"er", "set error detection aggressivity", OFFSET(error_recognition), FF_OPT_TYPE_INT, FF_ER_CAREFUL, INT_MIN, INT_MAX, A|V|D, "er"},
@@ -247,12 +254,15 @@ static const AVOption options[]={
 {"vis_qp", "visualize quantization parameter (QP), lower QP are tinted greener", 0, FF_OPT_TYPE_CONST, FF_DEBUG_VIS_QP, INT_MIN, INT_MAX, V|D, "debug"},
 {"vis_mb_type", "visualize block types", 0, FF_OPT_TYPE_CONST, FF_DEBUG_VIS_MB_TYPE, INT_MIN, INT_MAX, V|D, "debug"},
 {"buffers", "picture buffer allocations", 0, FF_OPT_TYPE_CONST, FF_DEBUG_BUFFERS, INT_MIN, INT_MAX, V|D, "debug"},
+{"thread_ops", "threading operations", 0, FF_OPT_TYPE_CONST, FF_DEBUG_THREADS, INT_MIN, INT_MAX, V|D, "debug"},
 {"vismv", "visualize motion vectors (MVs)", OFFSET(debug_mv), FF_OPT_TYPE_INT, DEFAULT, 0, INT_MAX, V|D, "debug_mv"},
 {"pf", "forward predicted MVs of P-frames", 0, FF_OPT_TYPE_CONST, FF_DEBUG_VIS_MV_P_FOR, INT_MIN, INT_MAX, V|D, "debug_mv"},
 {"bf", "forward predicted MVs of B-frames", 0, FF_OPT_TYPE_CONST, FF_DEBUG_VIS_MV_B_FOR, INT_MIN, INT_MAX, V|D, "debug_mv"},
 {"bb", "backward predicted MVs of B-frames", 0, FF_OPT_TYPE_CONST, FF_DEBUG_VIS_MV_B_BACK, INT_MIN, INT_MAX, V|D, "debug_mv"},
+#if FF_API_MB_Q
 {"mb_qmin", "obsolete, use qmin", OFFSET(mb_qmin), FF_OPT_TYPE_INT, DEFAULT, INT_MIN, INT_MAX, V|E},
 {"mb_qmax", "obsolete, use qmax", OFFSET(mb_qmax), FF_OPT_TYPE_INT, DEFAULT, INT_MIN, INT_MAX, V|E},
+#endif
 {"cmp", "full pel me compare function", OFFSET(me_cmp), FF_OPT_TYPE_INT, DEFAULT, INT_MIN, INT_MAX, V|E, "cmp_func"},
 {"subcmp", "sub pel me compare function", OFFSET(me_sub_cmp), FF_OPT_TYPE_INT, DEFAULT, INT_MIN, INT_MAX, V|E, "cmp_func"},
 {"mbcmp", "macroblock compare function", OFFSET(mb_cmp), FF_OPT_TYPE_INT, DEFAULT, INT_MIN, INT_MAX, V|E, "cmp_func"},
@@ -270,7 +280,7 @@ static const AVOption options[]={
 {"rd", "rate distortion optimal, slow", 0, FF_OPT_TYPE_CONST, FF_CMP_RD, INT_MIN, INT_MAX, V|E, "cmp_func"},
 {"zero", "0", 0, FF_OPT_TYPE_CONST, FF_CMP_ZERO, INT_MIN, INT_MAX, V|E, "cmp_func"},
 {"vsad", "sum of absolute vertical differences", 0, FF_OPT_TYPE_CONST, FF_CMP_VSAD, INT_MIN, INT_MAX, V|E, "cmp_func"},
-{"vsse","sum of squared vertical differences", 0, FF_OPT_TYPE_CONST, FF_CMP_VSSE, INT_MIN, INT_MAX, V|E, "cmp_func"},
+{"vsse", "sum of squared vertical differences", 0, FF_OPT_TYPE_CONST, FF_CMP_VSSE, INT_MIN, INT_MAX, V|E, "cmp_func"},
 {"nsse", "noise preserving sum of squared differences", 0, FF_OPT_TYPE_CONST, FF_CMP_NSSE, INT_MIN, INT_MAX, V|E, "cmp_func"},
 #if CONFIG_SNOW_ENCODER
 {"w53", "5/3 wavelet, only used in snow", 0, FF_OPT_TYPE_CONST, FF_CMP_W53, INT_MIN, INT_MAX, V|E, "cmp_func"},
@@ -309,7 +319,9 @@ static const AVOption options[]={
 {"inter_threshold", NULL, OFFSET(inter_threshold), FF_OPT_TYPE_INT, DEFAULT, INT_MIN, INT_MAX, V|E},
 {"flags2", NULL, OFFSET(flags2), FF_OPT_TYPE_FLAGS, CODEC_FLAG2_FASTPSKIP|CODEC_FLAG2_BIT_RESERVOIR|CODEC_FLAG2_PSY|CODEC_FLAG2_MBTREE, 0, UINT_MAX, V|A|E|D, "flags2"},
 {"error", NULL, OFFSET(error_rate), FF_OPT_TYPE_INT, DEFAULT, INT_MIN, INT_MAX, V|E},
+#if FF_API_ANTIALIAS_ALGO
 {"antialias", "MP3 antialias algorithm", OFFSET(antialias_algo), FF_OPT_TYPE_INT, DEFAULT, INT_MIN, INT_MAX, V|D, "aa"},
+#endif
 {"auto", NULL, 0, FF_OPT_TYPE_CONST, FF_AA_AUTO, INT_MIN, INT_MAX, V|D, "aa"},
 {"fastint", NULL, 0, FF_OPT_TYPE_CONST, FF_AA_FASTINT, INT_MIN, INT_MAX, V|D, "aa"},
 {"int", NULL, 0, FF_OPT_TYPE_CONST, FF_AA_INT, INT_MIN, INT_MAX, V|D, "aa"},
@@ -328,9 +340,14 @@ static const AVOption options[]={
 {"aac_low", NULL, 0, FF_OPT_TYPE_CONST, FF_PROFILE_AAC_LOW, INT_MIN, INT_MAX, A|E, "profile"},
 {"aac_ssr", NULL, 0, FF_OPT_TYPE_CONST, FF_PROFILE_AAC_SSR, INT_MIN, INT_MAX, A|E, "profile"},
 {"aac_ltp", NULL, 0, FF_OPT_TYPE_CONST, FF_PROFILE_AAC_LTP, INT_MIN, INT_MAX, A|E, "profile"},
+{"dts", NULL, 0, FF_OPT_TYPE_CONST, FF_PROFILE_DTS, INT_MIN, INT_MAX, A|E, "profile"},
+{"dts_es", NULL, 0, FF_OPT_TYPE_CONST, FF_PROFILE_DTS_ES, INT_MIN, INT_MAX, A|E, "profile"},
+{"dts_96_24", NULL, 0, FF_OPT_TYPE_CONST, FF_PROFILE_DTS_96_24, INT_MIN, INT_MAX, A|E, "profile"},
+{"dts_hd_hra", NULL, 0, FF_OPT_TYPE_CONST, FF_PROFILE_DTS_HD_HRA, INT_MIN, INT_MAX, A|E, "profile"},
+{"dts_hd_ma", NULL, 0, FF_OPT_TYPE_CONST, FF_PROFILE_DTS_HD_MA, INT_MIN, INT_MAX, A|E, "profile"},
 {"level", NULL, OFFSET(level), FF_OPT_TYPE_INT, FF_LEVEL_UNKNOWN, INT_MIN, INT_MAX, V|A|E, "level"},
 {"unknown", NULL, 0, FF_OPT_TYPE_CONST, FF_LEVEL_UNKNOWN, INT_MIN, INT_MAX, V|A|E, "level"},
-{"lowres", "decode at 1= 1/2, 2=1/4, 3=1/8 resolutions", OFFSET(lowres), FF_OPT_TYPE_INT, 0, 0, INT_MAX, V|D},
+{"lowres", "decode at 1= 1/2, 2=1/4, 3=1/8 resolutions", OFFSET(lowres), FF_OPT_TYPE_INT, 0, 0, INT_MAX, V|A|D},
 {"skip_threshold", "frame skip threshold", OFFSET(frame_skip_threshold), FF_OPT_TYPE_INT, DEFAULT, INT_MIN, INT_MAX, V|E},
 {"skip_factor", "frame skip factor", OFFSET(frame_skip_factor), FF_OPT_TYPE_INT, DEFAULT, INT_MIN, INT_MAX, V|E},
 {"skip_exp", "frame skip exponent", OFFSET(frame_skip_exp), FF_OPT_TYPE_INT, DEFAULT, INT_MIN, INT_MAX, V|E},
@@ -379,7 +396,9 @@ static const AVOption options[]={
 {"ivlc", "intra vlc table", 0, FF_OPT_TYPE_CONST, CODEC_FLAG2_INTRA_VLC, INT_MIN, INT_MAX, V|E, "flags2"},
 {"b_sensitivity", "adjusts sensitivity of b_frame_strategy 1", OFFSET(b_sensitivity), FF_OPT_TYPE_INT, 40, 1, INT_MAX, V|E},
 {"compression_level", NULL, OFFSET(compression_level), FF_OPT_TYPE_INT, FF_COMPRESSION_DEFAULT, INT_MIN, INT_MAX, V|A|E},
+#if FF_API_USE_LPC
 {"use_lpc", "sets whether to use LPC mode (FLAC)", OFFSET(use_lpc), FF_OPT_TYPE_INT, -1, INT_MIN, INT_MAX, A|E},
+#endif
 {"lpc_coeff_precision", "LPC coefficient precision (FLAC)", OFFSET(lpc_coeff_precision), FF_OPT_TYPE_INT, DEFAULT, 0, INT_MAX, A|E},
 {"min_prediction_order", NULL, OFFSET(min_prediction_order), FF_OPT_TYPE_INT, -1, INT_MIN, INT_MAX, A|E},
 {"max_prediction_order", NULL, OFFSET(max_prediction_order), FF_OPT_TYPE_INT, -1, INT_MIN, INT_MAX, A|E},
@@ -389,7 +408,9 @@ static const AVOption options[]={
 {"timecode_frame_start", "GOP timecode frame start number, in non drop frame format", OFFSET(timecode_frame_start), FF_OPT_TYPE_INT64, 0, 0, INT64_MAX, V|E},
 {"drop_frame_timecode", NULL, 0, FF_OPT_TYPE_CONST, CODEC_FLAG2_DROP_FRAME_TIMECODE, INT_MIN, INT_MAX, V|E, "flags2"},
 {"non_linear_q", "use non linear quantizer", 0, FF_OPT_TYPE_CONST, CODEC_FLAG2_NON_LINEAR_QUANT, INT_MIN, INT_MAX, V|E, "flags2"},
+#if FF_API_REQUEST_CHANNELS
 {"request_channels", "set desired number of audio channels", OFFSET(request_channels), FF_OPT_TYPE_INT, DEFAULT, 0, INT_MAX, A|D},
+#endif
 {"drc_scale", "percentage of dynamic range compression to apply", OFFSET(drc_scale), FF_OPT_TYPE_FLOAT, 1.0, 0.0, 1.0, A|D},
 {"reservoir", "use bit reservoir", 0, FF_OPT_TYPE_CONST, CODEC_FLAG2_BIT_RESERVOIR, INT_MIN, INT_MAX, A|E, "flags2"},
 {"mbtree", "use macroblock tree ratecontrol (x264 only)", 0, FF_OPT_TYPE_CONST, CODEC_FLAG2_MBTREE, INT_MIN, INT_MAX, V|E, "flags2"},
@@ -411,6 +432,30 @@ static const AVOption options[]={
 {"aq_strength", "specify aq strength", OFFSET(aq_strength), FF_OPT_TYPE_FLOAT, 1.0, 0, FLT_MAX, V|E},
 {"rc_lookahead", "specify number of frames to look ahead for frametype", OFFSET(rc_lookahead), FF_OPT_TYPE_INT, 40, 0, INT_MAX, V|E},
 {"ssim", "ssim will be calculated during encoding", 0, FF_OPT_TYPE_CONST, CODEC_FLAG2_SSIM, INT_MIN, INT_MAX, V|E, "flags2"},
+{"intra_refresh", "use periodic insertion of intra blocks instead of keyframes", 0, FF_OPT_TYPE_CONST, CODEC_FLAG2_INTRA_REFRESH, INT_MIN, INT_MAX, V|E, "flags2"},
+{"crf_max", "in crf mode, prevents vbv from lowering quality beyond this point", OFFSET(crf_max), FF_OPT_TYPE_FLOAT, DEFAULT, 0, 51, V|E},
+{"log_level_offset", "set the log level offset", OFFSET(log_level_offset), FF_OPT_TYPE_INT, 0, INT_MIN, INT_MAX },
+{"lpc_type", "specify LPC algorithm", OFFSET(lpc_type), FF_OPT_TYPE_INT, AV_LPC_TYPE_DEFAULT, AV_LPC_TYPE_DEFAULT, AV_LPC_TYPE_NB-1, A|E},
+{"none",     NULL, 0, FF_OPT_TYPE_CONST, AV_LPC_TYPE_NONE,     INT_MIN, INT_MAX, A|E, "lpc_type"},
+{"fixed",    NULL, 0, FF_OPT_TYPE_CONST, AV_LPC_TYPE_FIXED,    INT_MIN, INT_MAX, A|E, "lpc_type"},
+{"levinson", NULL, 0, FF_OPT_TYPE_CONST, AV_LPC_TYPE_LEVINSON, INT_MIN, INT_MAX, A|E, "lpc_type"},
+{"cholesky", NULL, 0, FF_OPT_TYPE_CONST, AV_LPC_TYPE_CHOLESKY, INT_MIN, INT_MAX, A|E, "lpc_type"},
+{"lpc_passes", "number of passes to use for Cholesky factorization during LPC analysis", OFFSET(lpc_passes), FF_OPT_TYPE_INT, -1, INT_MIN, INT_MAX, A|E},
+{"slices", "number of slices, used in parallelized decoding", OFFSET(slices), FF_OPT_TYPE_INT, 0, 0, INT_MAX, V|E},
+{"thread_type", "select multithreading type", OFFSET(thread_type), FF_OPT_TYPE_INT, FF_THREAD_SLICE|FF_THREAD_FRAME, 0, INT_MAX, V|E|D, "thread_type"},
+{"slice", NULL, 0, FF_OPT_TYPE_CONST, FF_THREAD_SLICE, INT_MIN, INT_MAX, V|E|D, "thread_type"},
+{"frame", NULL, 0, FF_OPT_TYPE_CONST, FF_THREAD_FRAME, INT_MIN, INT_MAX, V|E|D, "thread_type"},
+{"vbv_delay", "initial buffer fill time in periods of 27Mhz clock", 0, FF_OPT_TYPE_INT64, 0, 0, INT64_MAX},
+{"audio_service_type", "audio service type", OFFSET(audio_service_type), FF_OPT_TYPE_INT, AV_AUDIO_SERVICE_TYPE_MAIN, 0, AV_AUDIO_SERVICE_TYPE_NB-1, A|E, "audio_service_type"},
+{"ma", "Main Audio Service", 0, FF_OPT_TYPE_CONST, AV_AUDIO_SERVICE_TYPE_MAIN,              INT_MIN, INT_MAX, A|E, "audio_service_type"},
+{"ef", "Effects",            0, FF_OPT_TYPE_CONST, AV_AUDIO_SERVICE_TYPE_EFFECTS,           INT_MIN, INT_MAX, A|E, "audio_service_type"},
+{"vi", "Visually Impaired",  0, FF_OPT_TYPE_CONST, AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED, INT_MIN, INT_MAX, A|E, "audio_service_type"},
+{"hi", "Hearing Impaired",   0, FF_OPT_TYPE_CONST, AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED,  INT_MIN, INT_MAX, A|E, "audio_service_type"},
+{"di", "Dialogue",           0, FF_OPT_TYPE_CONST, AV_AUDIO_SERVICE_TYPE_DIALOGUE,          INT_MIN, INT_MAX, A|E, "audio_service_type"},
+{"co", "Commentary",         0, FF_OPT_TYPE_CONST, AV_AUDIO_SERVICE_TYPE_COMMENTARY,        INT_MIN, INT_MAX, A|E, "audio_service_type"},
+{"em", "Emergency",          0, FF_OPT_TYPE_CONST, AV_AUDIO_SERVICE_TYPE_EMERGENCY,         INT_MIN, INT_MAX, A|E, "audio_service_type"},
+{"vo", "Voice Over",         0, FF_OPT_TYPE_CONST, AV_AUDIO_SERVICE_TYPE_VOICE_OVER,        INT_MIN, INT_MAX, A|E, "audio_service_type"},
+{"ka", "Karaoke",            0, FF_OPT_TYPE_CONST, AV_AUDIO_SERVICE_TYPE_KARAOKE,           INT_MIN, INT_MAX, A|E, "audio_service_type"},
 {NULL},
 };
 
@@ -421,7 +466,7 @@ static const AVOption options[]={
 #undef D
 #undef DEFAULT
 
-static const AVClass av_codec_context_class = { "AVCodecContext", context_to_name, options, LIBAVUTIL_VERSION_INT };
+static const AVClass av_codec_context_class = { "AVCodecContext", context_to_name, options, LIBAVUTIL_VERSION_INT, OFFSET(log_level_offset) };
 
 void avcodec_get_context_defaults2(AVCodecContext *s, enum AVMediaType codec_type){
     int flags=0;
@@ -446,13 +491,43 @@ void avcodec_get_context_defaults2(AVCodecContext *s, enum AVMediaType codec_typ
     s->execute2= avcodec_default_execute2;
     s->sample_aspect_ratio= (AVRational){0,1};
     s->pix_fmt= PIX_FMT_NONE;
-    s->sample_fmt= SAMPLE_FMT_NONE;
+    s->sample_fmt= AV_SAMPLE_FMT_NONE;
 
     s->palctrl = NULL;
     s->reget_buffer= avcodec_default_reget_buffer;
     s->reordered_opaque= AV_NOPTS_VALUE;
 }
 
+int avcodec_get_context_defaults3(AVCodecContext *s, AVCodec *codec){
+    avcodec_get_context_defaults2(s, codec ? codec->type : AVMEDIA_TYPE_UNKNOWN);
+    if(codec && codec->priv_data_size){
+        if(!s->priv_data){
+            s->priv_data= av_mallocz(codec->priv_data_size);
+            if (!s->priv_data) {
+                return AVERROR(ENOMEM);
+            }
+        }
+        if(codec->priv_class){
+            *(AVClass**)s->priv_data= codec->priv_class;
+            av_opt_set_defaults(s->priv_data);
+        }
+    }
+    return 0;
+}
+
+AVCodecContext *avcodec_alloc_context3(AVCodec *codec){
+    AVCodecContext *avctx= av_malloc(sizeof(AVCodecContext));
+
+    if(avctx==NULL) return NULL;
+
+    if(avcodec_get_context_defaults3(avctx, codec) < 0){
+        av_free(avctx);
+        return NULL;
+    }
+
+    return avctx;
+}
+
 AVCodecContext *avcodec_alloc_context2(enum AVMediaType codec_type){
     AVCodecContext *avctx= av_malloc(sizeof(AVCodecContext));
 
@@ -488,9 +563,6 @@ int avcodec_copy_context(AVCodecContext *dest, const AVCodecContext *src)
     dest->slice_offset    = NULL;
     dest->internal_buffer = NULL;
     dest->hwaccel         = NULL;
-    dest->execute         = NULL;
-    dest->execute2        = NULL;
-    dest->reget_buffer    = NULL;
     dest->thread_opaque   = NULL;
 
     /* reallocate values that should be allocated separately */
diff --git a/libavcodec/os2thread.c b/libavcodec/os2thread.c
deleted file mode 100644
index 3d1367c..0000000
--- a/libavcodec/os2thread.c
+++ /dev/null
@@ -1,148 +0,0 @@
-/*
- * Copyright (c) 2004 Michael Niedermayer <michaelni at gmx.at>
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-//#define DEBUG
-
-// Ported by Vlad Stelmahovsky
-
-#include "avcodec.h"
-
-#define INCL_DOS
-#define INCL_DOSERRORS
-#define INCL_DOSDEVIOCTL
-#include <os2.h>
-
-typedef struct ThreadContext{
-    AVCodecContext *avctx;
-    int thread;
-    HEV work_sem;
-    HEV done_sem;
-    int (*func)(AVCodecContext *c, void *arg);
-    void *arg;
-    int ret;
-}ThreadContext;
-
-
-static void attribute_align_arg thread_func(void *v){
-    ThreadContext *c= v;
-
-    for(;;){
-        //printf("thread_func %X enter wait\n", (int)v); fflush(stdout);
-        DosWaitEventSem(c->work_sem, SEM_INDEFINITE_WAIT);
-//        WaitForSingleObject(c->work_sem, INFINITE);
-//printf("thread_func %X after wait (func=%X)\n", (int)v, (int)c->func); fflush(stdout);
-        if(c->func)
-            c->ret= c->func(c->avctx, c->arg);
-        else
-            return;
-        //printf("thread_func %X signal complete\n", (int)v); fflush(stdout);
-        DosPostEventSem(c->done_sem);
-//        ReleaseSemaphore(c->done_sem, 1, 0);
-    }
-
-    return;
-}
-
-/**
- * free what has been allocated by avcodec_thread_init().
- * must be called after decoding has finished, especially do not call while avcodec_thread_execute() is running
- */
-void avcodec_thread_free(AVCodecContext *s){
-    ThreadContext *c= s->thread_opaque;
-    int i;
-
-    for(i=0; i<s->thread_count; i++){
-
-        c[i].func= NULL;
-        DosPostEventSem(c[i].work_sem);
-        //        ReleaseSemaphore(c[i].work_sem, 1, 0);
-        DosWaitThread((PTID)&c[i].thread,DCWW_WAIT);
-//        WaitForSingleObject(c[i].thread, INFINITE);
-        if(c[i].work_sem) DosCloseEventSem(c[i].work_sem);//CloseHandle(c[i].work_sem);
-        if(c[i].done_sem) DosCloseEventSem(c[i].done_sem);//CloseHandle(c[i].done_sem);
-    }
-
-    av_freep(&s->thread_opaque);
-}
-
-static int avcodec_thread_execute(AVCodecContext *s, int (*func)(AVCodecContext *c2, void *arg2),void *arg, int *ret, int count, int size){
-    ThreadContext *c= s->thread_opaque;
-    int i;
-
-    assert(s == c->avctx);
-    assert(count <= s->thread_count);
-
-    /* note, we can be certain that this is not called with the same AVCodecContext by different threads at the same time */
-
-    for(i=0; i<count; i++){
-
-        c[i].arg= (char*)arg + i*size;
-        c[i].func= func;
-        c[i].ret= 12345;
-
-        DosPostEventSem(c[i].work_sem);
-//        ReleaseSemaphore(c[i].work_sem, 1, 0);
-    }
-    for(i=0; i<count; i++){
-        DosWaitEventSem(c[i].done_sem,SEM_INDEFINITE_WAIT);
-//        WaitForSingleObject(c[i].done_sem, INFINITE);
-
-        c[i].func= NULL;
-        if(ret) ret[i]= c[i].ret;
-    }
-    return 0;
-}
-
-int avcodec_thread_init(AVCodecContext *s, int thread_count){
-    int i;
-    ThreadContext *c;
-    uint32_t threadid;
-
-    s->thread_count= thread_count;
-
-    if (thread_count <= 1)
-        return 0;
-
-    assert(!s->thread_opaque);
-    c= av_mallocz(sizeof(ThreadContext)*thread_count);
-    s->thread_opaque= c;
-
-    for(i=0; i<thread_count; i++){
-//printf("init semaphors %d\n", i); fflush(stdout);
-        c[i].avctx= s;
-
-        if (DosCreateEventSem(NULL,&c[i].work_sem,DC_SEM_SHARED,0))
-            goto fail;
-        if (DosCreateEventSem(NULL,&c[i].done_sem,DC_SEM_SHARED,0))
-            goto fail;
-
-//printf("create thread %d\n", i); fflush(stdout);
-//        c[i].thread = (HANDLE)_beginthreadex(NULL, 0, thread_func, &c[i], 0, &threadid );
-        c[i].thread = _beginthread(thread_func, NULL, 0x10000, &c[i]);
-        if( c[i].thread <= 0 ) goto fail;
-    }
-//printf("init done\n"); fflush(stdout);
-
-    s->execute= avcodec_thread_execute;
-
-    return 0;
-fail:
-    avcodec_thread_free(s);
-    return -1;
-}
diff --git a/libavcodec/pamenc.c b/libavcodec/pamenc.c
index ae0ea3a..8225a62 100644
--- a/libavcodec/pamenc.c
+++ b/libavcodec/pamenc.c
@@ -2,20 +2,20 @@
  * PAM image format
  * Copyright (c) 2002, 2003 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -108,7 +108,7 @@ static int pam_encode_frame(AVCodecContext *avctx, unsigned char *outbuf,
 }
 
 
-AVCodec pam_encoder = {
+AVCodec ff_pam_encoder = {
     "pam",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_PAM,
diff --git a/libavcodec/parser.c b/libavcodec/parser.c
index 864b5f2..3ba3e9c 100644
--- a/libavcodec/parser.c
+++ b/libavcodec/parser.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2003 Fabrice Bellard
  * Copyright (c) 2003 Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -74,7 +74,7 @@ AVCodecParserContext *av_parser_init(int codec_id)
     s->fetch_timestamp=1;
     s->pict_type = FF_I_TYPE;
     s->key_frame = -1;
-    s->convergence_duration = AV_NOPTS_VALUE;
+    s->convergence_duration = 0;
     s->dts_sync_point       = INT_MIN;
     s->dts_ref_dts_delta    = INT_MIN;
     s->pts_dts_delta        = INT_MIN;
@@ -105,6 +105,7 @@ void ff_fetch_timestamp(AVCodecParserContext *s, int off, int remove){
     }
 }
 
+#if LIBAVCODEC_VERSION_MAJOR < 53
 /**
  *
  * @param buf           input
@@ -139,6 +140,7 @@ int av_parser_parse(AVCodecParserContext *s,
 {
     return av_parser_parse2(s, avctx, poutbuf, poutbuf_size, buf, buf_size, pts, dts, AV_NOPTS_VALUE);
 }
+#endif
 
 int av_parser_parse2(AVCodecParserContext *s,
                      AVCodecContext *avctx,
@@ -150,6 +152,12 @@ int av_parser_parse2(AVCodecParserContext *s,
     int index, i;
     uint8_t dummy_buf[FF_INPUT_BUFFER_PADDING_SIZE];
 
+    if(!(s->flags & PARSER_FLAG_FETCHED_OFFSET)) {
+        s->next_frame_offset =
+        s->cur_offset        = pos;
+        s->flags |= PARSER_FLAG_FETCHED_OFFSET;
+    }
+
     if (buf_size == 0) {
         /* padding is always necessary even if EOF, so we add it here */
         memset(dummy_buf, 0, sizeof(dummy_buf));
diff --git a/libavcodec/parser.h b/libavcodec/parser.h
index 6274bb2..1e85ae4 100644
--- a/libavcodec/parser.h
+++ b/libavcodec/parser.h
@@ -3,20 +3,20 @@
  * Copyright (c) 2003 Fabrice Bellard
  * Copyright (c) 2003 Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -61,7 +61,7 @@ void ff_parse_close(AVCodecParserContext *s);
 void ff_parse1_close(AVCodecParserContext *s);
 
 /**
- * Fetches timestamps for a specific byte within the current access unit.
+ * Fetch timestamps for a specific byte within the current access unit.
  * @param off byte position within the access unit
  * @param remove Found timestamps will be removed if set to 1, kept if set to 0.
  */
diff --git a/libavcodec/pcm-mpeg.c b/libavcodec/pcm-mpeg.c
index c2343a6..a55d48c 100644
--- a/libavcodec/pcm-mpeg.c
+++ b/libavcodec/pcm-mpeg.c
@@ -2,20 +2,20 @@
  * LPCM codecs for PCM formats found in MPEG streams
  * Copyright (c) 2009 Christian Schmidt
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -24,6 +24,7 @@
  * PCM codecs for encodings found in MPEG streams (DVD/Blu-ray)
  */
 
+#include "libavutil/audioconvert.h"
 #include "avcodec.h"
 #include "bytestream.h"
 
@@ -53,9 +54,9 @@ static int pcm_bluray_parse_header(AVCodecContext *avctx,
 {
     static const uint8_t bits_per_samples[4] = { 0, 16, 20, 24 };
     static const uint32_t channel_layouts[16] = {
-        0, CH_LAYOUT_MONO, 0, CH_LAYOUT_STEREO, CH_LAYOUT_SURROUND,
-        CH_LAYOUT_2_1, CH_LAYOUT_4POINT0, CH_LAYOUT_2_2, CH_LAYOUT_5POINT0,
-        CH_LAYOUT_5POINT1, CH_LAYOUT_7POINT0, CH_LAYOUT_7POINT1, 0, 0, 0, 0
+        0, AV_CH_LAYOUT_MONO, 0, AV_CH_LAYOUT_STEREO, AV_CH_LAYOUT_SURROUND,
+        AV_CH_LAYOUT_2_1, AV_CH_LAYOUT_4POINT0, AV_CH_LAYOUT_2_2, AV_CH_LAYOUT_5POINT0,
+        AV_CH_LAYOUT_5POINT1, AV_CH_LAYOUT_7POINT0, AV_CH_LAYOUT_7POINT1, 0, 0, 0, 0
     };
     static const uint8_t channels[16] = {
         0, 1, 0, 2, 3, 3, 4, 4, 5, 6, 7, 8, 0, 0, 0, 0
@@ -63,7 +64,7 @@ static int pcm_bluray_parse_header(AVCodecContext *avctx,
     uint8_t channel_layout = header[2] >> 4;
 
     if (avctx->debug & FF_DEBUG_PICT_INFO)
-        dprintf(avctx, "pcm_bluray_parse_header: header = %02x%02x%02x%02x\n",
+        av_dlog(avctx, "pcm_bluray_parse_header: header = %02x%02x%02x%02x\n",
                 header[0], header[1], header[2], header[3]);
 
     /* get the sample depth and derive the sample format from it */
@@ -72,8 +73,8 @@ static int pcm_bluray_parse_header(AVCodecContext *avctx,
         av_log(avctx, AV_LOG_ERROR, "unsupported sample depth (0)\n");
         return -1;
     }
-    avctx->sample_fmt = avctx->bits_per_coded_sample == 16 ? SAMPLE_FMT_S16 :
-                                                             SAMPLE_FMT_S32;
+    avctx->sample_fmt = avctx->bits_per_coded_sample == 16 ? AV_SAMPLE_FMT_S16 :
+                                                             AV_SAMPLE_FMT_S32;
 
     /* get the sample rate. Not all values are known or exist. */
     switch (header[2] & 0x0f) {
@@ -111,7 +112,7 @@ static int pcm_bluray_parse_header(AVCodecContext *avctx,
                       avctx->bits_per_coded_sample;
 
     if (avctx->debug & FF_DEBUG_PICT_INFO)
-        dprintf(avctx,
+        av_dlog(avctx,
                 "pcm_bluray_parse_header: %d channels, %d bits per sample, %d kHz, %d kbit\n",
                 avctx->channels, avctx->bits_per_coded_sample,
                 avctx->sample_rate, avctx->bit_rate);
@@ -146,7 +147,7 @@ static int pcm_bluray_decode_frame(AVCodecContext *avctx,
     samples = buf_size / sample_size;
 
     output_size = samples * avctx->channels *
-                  (avctx->sample_fmt == SAMPLE_FMT_S32 ? 4 : 2);
+                  (avctx->sample_fmt == AV_SAMPLE_FMT_S32 ? 4 : 2);
     if (output_size > *data_size) {
         av_log(avctx, AV_LOG_ERROR,
                "Insufficient output buffer space (%d bytes, needed %d bytes)\n",
@@ -158,11 +159,11 @@ static int pcm_bluray_decode_frame(AVCodecContext *avctx,
     if (samples) {
         switch (avctx->channel_layout) {
             /* cases with same number of source and coded channels */
-        case CH_LAYOUT_STEREO:
-        case CH_LAYOUT_4POINT0:
-        case CH_LAYOUT_2_2:
+        case AV_CH_LAYOUT_STEREO:
+        case AV_CH_LAYOUT_4POINT0:
+        case AV_CH_LAYOUT_2_2:
             samples *= num_source_channels;
-            if (SAMPLE_FMT_S16 == avctx->sample_fmt) {
+            if (AV_SAMPLE_FMT_S16 == avctx->sample_fmt) {
 #if HAVE_BIGENDIAN
                 memcpy(dst16, src, output_size);
 #else
@@ -177,11 +178,11 @@ static int pcm_bluray_decode_frame(AVCodecContext *avctx,
             }
             break;
         /* cases where number of source channels = coded channels + 1 */
-        case CH_LAYOUT_MONO:
-        case CH_LAYOUT_SURROUND:
-        case CH_LAYOUT_2_1:
-        case CH_LAYOUT_5POINT0:
-            if (SAMPLE_FMT_S16 == avctx->sample_fmt) {
+        case AV_CH_LAYOUT_MONO:
+        case AV_CH_LAYOUT_SURROUND:
+        case AV_CH_LAYOUT_2_1:
+        case AV_CH_LAYOUT_5POINT0:
+            if (AV_SAMPLE_FMT_S16 == avctx->sample_fmt) {
                 do {
 #if HAVE_BIGENDIAN
                     memcpy(dst16, src, avctx->channels * 2);
@@ -206,8 +207,8 @@ static int pcm_bluray_decode_frame(AVCodecContext *avctx,
             }
             break;
             /* remapping: L, R, C, LBack, RBack, LF */
-        case CH_LAYOUT_5POINT1:
-            if (SAMPLE_FMT_S16 == avctx->sample_fmt) {
+        case AV_CH_LAYOUT_5POINT1:
+            if (AV_SAMPLE_FMT_S16 == avctx->sample_fmt) {
                 do {
                     dst16[0] = bytestream_get_be16(&src);
                     dst16[1] = bytestream_get_be16(&src);
@@ -230,8 +231,8 @@ static int pcm_bluray_decode_frame(AVCodecContext *avctx,
             }
             break;
             /* remapping: L, R, C, LSide, LBack, RBack, RSide, <unused> */
-        case CH_LAYOUT_7POINT0:
-            if (SAMPLE_FMT_S16 == avctx->sample_fmt) {
+        case AV_CH_LAYOUT_7POINT0:
+            if (AV_SAMPLE_FMT_S16 == avctx->sample_fmt) {
                 do {
                     dst16[0] = bytestream_get_be16(&src);
                     dst16[1] = bytestream_get_be16(&src);
@@ -258,8 +259,8 @@ static int pcm_bluray_decode_frame(AVCodecContext *avctx,
             }
             break;
             /* remapping: L, R, C, LSide, LBack, RBack, RSide, LF */
-        case CH_LAYOUT_7POINT1:
-            if (SAMPLE_FMT_S16 == avctx->sample_fmt) {
+        case AV_CH_LAYOUT_7POINT1:
+            if (AV_SAMPLE_FMT_S16 == avctx->sample_fmt) {
                 do {
                     dst16[0] = bytestream_get_be16(&src);
                     dst16[1] = bytestream_get_be16(&src);
@@ -290,12 +291,12 @@ static int pcm_bluray_decode_frame(AVCodecContext *avctx,
 
     retval = src - avpkt->data;
     if (avctx->debug & FF_DEBUG_BITSTREAM)
-        dprintf(avctx, "pcm_bluray_decode_frame: decoded %d -> %d bytes\n",
+        av_dlog(avctx, "pcm_bluray_decode_frame: decoded %d -> %d bytes\n",
                 retval, *data_size);
     return retval;
 }
 
-AVCodec pcm_bluray_decoder = {
+AVCodec ff_pcm_bluray_decoder = {
     "pcm_bluray",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_PCM_BLURAY,
@@ -304,7 +305,7 @@ AVCodec pcm_bluray_decoder = {
     NULL,
     NULL,
     pcm_bluray_decode_frame,
-    .sample_fmts = (const enum SampleFormat[]){SAMPLE_FMT_S16, SAMPLE_FMT_S32,
-                                         SAMPLE_FMT_NONE},
+    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_S32,
+                                         AV_SAMPLE_FMT_NONE},
     .long_name = NULL_IF_CONFIG_SMALL("PCM signed 16|20|24-bit big-endian for Blu-ray media"),
 };
diff --git a/libavcodec/pcm.c b/libavcodec/pcm.c
index 746a520..e2a7334 100644
--- a/libavcodec/pcm.c
+++ b/libavcodec/pcm.c
@@ -2,20 +2,20 @@
  * PCM codecs
  * Copyright (c) 2001 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -81,14 +81,14 @@ static int pcm_encode_frame(AVCodecContext *avctx,
                             unsigned char *frame, int buf_size, void *data)
 {
     int n, sample_size, v;
-    short *samples;
+    const short *samples;
     unsigned char *dst;
-    uint8_t *srcu8;
-    int16_t *samples_int16_t;
-    int32_t *samples_int32_t;
-    int64_t *samples_int64_t;
-    uint16_t *samples_uint16_t;
-    uint32_t *samples_uint32_t;
+    const uint8_t *srcu8;
+    const int16_t *samples_int16_t;
+    const int32_t *samples_int32_t;
+    const int64_t *samples_int64_t;
+    const uint16_t *samples_uint16_t;
+    const uint32_t *samples_uint32_t;
 
     sample_size = av_get_bits_per_sample(avctx->codec->id)/8;
     n = buf_size / sample_size;
@@ -227,6 +227,10 @@ static av_cold int pcm_decode_init(AVCodecContext * avctx)
     }
 
     avctx->sample_fmt = avctx->codec->sample_fmts[0];
+
+    if (avctx->sample_fmt == AV_SAMPLE_FMT_S32)
+        avctx->bits_per_raw_sample = av_get_bits_per_sample(avctx->codec->id);
+
     return 0;
 }
 
@@ -255,7 +259,7 @@ static int pcm_decode_frame(AVCodecContext *avctx,
     const uint8_t *buf = avpkt->data;
     int buf_size = avpkt->size;
     PCMDecode *s = avctx->priv_data;
-    int sample_size, c, n;
+    int sample_size, c, n, i;
     short *samples;
     const uint8_t *src, *src8, *src2[MAX_CHANNELS];
     uint8_t *dstu8;
@@ -284,6 +288,14 @@ static int pcm_decode_frame(AVCodecContext *avctx,
     if (CODEC_ID_PCM_DVD == avctx->codec_id)
         /* 2 samples are interleaved per block in PCM_DVD */
         sample_size = avctx->bits_per_coded_sample * 2 / 8;
+    else if (avctx->codec_id == CODEC_ID_PCM_LXF)
+        /* we process 40-bit blocks per channel for LXF */
+        sample_size = 5;
+
+    if (sample_size == 0) {
+        av_log(avctx, AV_LOG_ERROR, "Invalid sample_size\n");
+        return AVERROR(EINVAL);
+    }
 
     n = avctx->channels * sample_size;
 
@@ -432,6 +444,26 @@ static int pcm_decode_frame(AVCodecContext *avctx,
         }
         samples = (short *) dst_int32_t;
         break;
+    case CODEC_ID_PCM_LXF:
+        dst_int32_t = data;
+        n /= avctx->channels;
+        //unpack and de-planerize
+        for (i = 0; i < n; i++) {
+            for (c = 0, src8 = src + i*5; c < avctx->channels; c++, src8 += n*5) {
+                //extract low 20 bits and expand to 32 bits
+                *dst_int32_t++ = (src8[2] << 28) | (src8[1] << 20) | (src8[0] << 12) |
+                                 ((src8[2] & 0xF) << 8) | src8[1];
+            }
+
+            for (c = 0, src8 = src + i*5; c < avctx->channels; c++, src8 += n*5) {
+                //extract high 20 bits and expand to 32 bits
+                *dst_int32_t++ = (src8[4] << 24) | (src8[3] << 16) |
+                                 ((src8[2] & 0xF0) << 8) | (src8[4] << 4) | (src8[3] >> 4);
+            }
+        }
+        src += n * avctx->channels * 5;
+        samples = (short *) dst_int32_t;
+        break;
     default:
         return -1;
     }
@@ -440,66 +472,63 @@ static int pcm_decode_frame(AVCodecContext *avctx,
 }
 
 #if CONFIG_ENCODERS
-#define PCM_ENCODER(id,sample_fmt_,name,long_name_) \
-AVCodec name ## _encoder = {                    \
-    #name,                                      \
-    AVMEDIA_TYPE_AUDIO,                         \
-    id,                                         \
-    0,                                          \
-    pcm_encode_init,                            \
-    pcm_encode_frame,                           \
-    pcm_encode_close,                           \
-    NULL,                                       \
-    .sample_fmts = (const enum SampleFormat[]){sample_fmt_,SAMPLE_FMT_NONE}, \
+#define PCM_ENCODER(id_,sample_fmt_,name_,long_name_) \
+AVCodec ff_ ## name_ ## _encoder = {            \
+    .name        = #name_,                      \
+    .type        = AVMEDIA_TYPE_AUDIO,          \
+    .id          = id_,                         \
+    .init        = pcm_encode_init,             \
+    .encode      = pcm_encode_frame,            \
+    .close       = pcm_encode_close,            \
+    .sample_fmts = (const enum AVSampleFormat[]){sample_fmt_,AV_SAMPLE_FMT_NONE}, \
     .long_name = NULL_IF_CONFIG_SMALL(long_name_), \
-};
+}
 #else
 #define PCM_ENCODER(id,sample_fmt_,name,long_name_)
 #endif
 
 #if CONFIG_DECODERS
-#define PCM_DECODER(id,sample_fmt_,name,long_name_)         \
-AVCodec name ## _decoder = {                    \
-    #name,                                      \
-    AVMEDIA_TYPE_AUDIO,                         \
-    id,                                         \
-    sizeof(PCMDecode),                          \
-    pcm_decode_init,                            \
-    NULL,                                       \
-    NULL,                                       \
-    pcm_decode_frame,                           \
-    .sample_fmts = (const enum SampleFormat[]){sample_fmt_,SAMPLE_FMT_NONE}, \
+#define PCM_DECODER(id_,sample_fmt_,name_,long_name_)         \
+AVCodec ff_ ## name_ ## _decoder = {            \
+    .name           = #name_,                   \
+    .type           = AVMEDIA_TYPE_AUDIO,       \
+    .id             = id_,                      \
+    .priv_data_size = sizeof(PCMDecode),        \
+    .init           = pcm_decode_init,          \
+    .decode         = pcm_decode_frame,         \
+    .sample_fmts = (const enum AVSampleFormat[]){sample_fmt_,AV_SAMPLE_FMT_NONE}, \
     .long_name = NULL_IF_CONFIG_SMALL(long_name_), \
-};
+}
 #else
 #define PCM_DECODER(id,sample_fmt_,name,long_name_)
 #endif
 
 #define PCM_CODEC(id, sample_fmt_, name, long_name_)         \
-    PCM_ENCODER(id,sample_fmt_,name,long_name_) PCM_DECODER(id,sample_fmt_,name,long_name_)
+    PCM_ENCODER(id,sample_fmt_,name,long_name_); PCM_DECODER(id,sample_fmt_,name,long_name_)
 
 /* Note: Do not forget to add new entries to the Makefile as well. */
-PCM_CODEC  (CODEC_ID_PCM_ALAW,  SAMPLE_FMT_S16, pcm_alaw, "PCM A-law");
-PCM_CODEC  (CODEC_ID_PCM_DVD,   SAMPLE_FMT_S32, pcm_dvd, "PCM signed 20|24-bit big-endian");
-PCM_CODEC  (CODEC_ID_PCM_F32BE, SAMPLE_FMT_FLT, pcm_f32be, "PCM 32-bit floating point big-endian");
-PCM_CODEC  (CODEC_ID_PCM_F32LE, SAMPLE_FMT_FLT, pcm_f32le, "PCM 32-bit floating point little-endian");
-PCM_CODEC  (CODEC_ID_PCM_F64BE, SAMPLE_FMT_DBL, pcm_f64be, "PCM 64-bit floating point big-endian");
-PCM_CODEC  (CODEC_ID_PCM_F64LE, SAMPLE_FMT_DBL, pcm_f64le, "PCM 64-bit floating point little-endian");
-PCM_CODEC  (CODEC_ID_PCM_MULAW, SAMPLE_FMT_S16, pcm_mulaw, "PCM mu-law");
-PCM_CODEC  (CODEC_ID_PCM_S8,    SAMPLE_FMT_U8,  pcm_s8, "PCM signed 8-bit");
-PCM_CODEC  (CODEC_ID_PCM_S16BE, SAMPLE_FMT_S16, pcm_s16be, "PCM signed 16-bit big-endian");
-PCM_CODEC  (CODEC_ID_PCM_S16LE, SAMPLE_FMT_S16, pcm_s16le, "PCM signed 16-bit little-endian");
-PCM_DECODER(CODEC_ID_PCM_S16LE_PLANAR, SAMPLE_FMT_S16, pcm_s16le_planar, "PCM 16-bit little-endian planar");
-PCM_CODEC  (CODEC_ID_PCM_S24BE, SAMPLE_FMT_S32, pcm_s24be, "PCM signed 24-bit big-endian");
-PCM_CODEC  (CODEC_ID_PCM_S24DAUD, SAMPLE_FMT_S16,  pcm_s24daud, "PCM D-Cinema audio signed 24-bit");
-PCM_CODEC  (CODEC_ID_PCM_S24LE, SAMPLE_FMT_S32, pcm_s24le, "PCM signed 24-bit little-endian");
-PCM_CODEC  (CODEC_ID_PCM_S32BE, SAMPLE_FMT_S32, pcm_s32be, "PCM signed 32-bit big-endian");
-PCM_CODEC  (CODEC_ID_PCM_S32LE, SAMPLE_FMT_S32, pcm_s32le, "PCM signed 32-bit little-endian");
-PCM_CODEC  (CODEC_ID_PCM_U8,    SAMPLE_FMT_U8,  pcm_u8, "PCM unsigned 8-bit");
-PCM_CODEC  (CODEC_ID_PCM_U16BE, SAMPLE_FMT_S16, pcm_u16be, "PCM unsigned 16-bit big-endian");
-PCM_CODEC  (CODEC_ID_PCM_U16LE, SAMPLE_FMT_S16, pcm_u16le, "PCM unsigned 16-bit little-endian");
-PCM_CODEC  (CODEC_ID_PCM_U24BE, SAMPLE_FMT_S32, pcm_u24be, "PCM unsigned 24-bit big-endian");
-PCM_CODEC  (CODEC_ID_PCM_U24LE, SAMPLE_FMT_S32, pcm_u24le, "PCM unsigned 24-bit little-endian");
-PCM_CODEC  (CODEC_ID_PCM_U32BE, SAMPLE_FMT_S32, pcm_u32be, "PCM unsigned 32-bit big-endian");
-PCM_CODEC  (CODEC_ID_PCM_U32LE, SAMPLE_FMT_S32, pcm_u32le, "PCM unsigned 32-bit little-endian");
-PCM_CODEC  (CODEC_ID_PCM_ZORK,  SAMPLE_FMT_S16, pcm_zork, "PCM Zork");
+PCM_CODEC  (CODEC_ID_PCM_ALAW,  AV_SAMPLE_FMT_S16, pcm_alaw, "PCM A-law");
+PCM_DECODER(CODEC_ID_PCM_DVD,   AV_SAMPLE_FMT_S32, pcm_dvd, "PCM signed 20|24-bit big-endian");
+PCM_CODEC  (CODEC_ID_PCM_F32BE, AV_SAMPLE_FMT_FLT, pcm_f32be, "PCM 32-bit floating point big-endian");
+PCM_CODEC  (CODEC_ID_PCM_F32LE, AV_SAMPLE_FMT_FLT, pcm_f32le, "PCM 32-bit floating point little-endian");
+PCM_CODEC  (CODEC_ID_PCM_F64BE, AV_SAMPLE_FMT_DBL, pcm_f64be, "PCM 64-bit floating point big-endian");
+PCM_CODEC  (CODEC_ID_PCM_F64LE, AV_SAMPLE_FMT_DBL, pcm_f64le, "PCM 64-bit floating point little-endian");
+PCM_DECODER(CODEC_ID_PCM_LXF,   AV_SAMPLE_FMT_S32, pcm_lxf, "PCM signed 20-bit little-endian planar");
+PCM_CODEC  (CODEC_ID_PCM_MULAW, AV_SAMPLE_FMT_S16, pcm_mulaw, "PCM mu-law");
+PCM_CODEC  (CODEC_ID_PCM_S8,    AV_SAMPLE_FMT_U8,  pcm_s8, "PCM signed 8-bit");
+PCM_CODEC  (CODEC_ID_PCM_S16BE, AV_SAMPLE_FMT_S16, pcm_s16be, "PCM signed 16-bit big-endian");
+PCM_CODEC  (CODEC_ID_PCM_S16LE, AV_SAMPLE_FMT_S16, pcm_s16le, "PCM signed 16-bit little-endian");
+PCM_DECODER(CODEC_ID_PCM_S16LE_PLANAR, AV_SAMPLE_FMT_S16, pcm_s16le_planar, "PCM 16-bit little-endian planar");
+PCM_CODEC  (CODEC_ID_PCM_S24BE, AV_SAMPLE_FMT_S32, pcm_s24be, "PCM signed 24-bit big-endian");
+PCM_CODEC  (CODEC_ID_PCM_S24DAUD, AV_SAMPLE_FMT_S16,  pcm_s24daud, "PCM D-Cinema audio signed 24-bit");
+PCM_CODEC  (CODEC_ID_PCM_S24LE, AV_SAMPLE_FMT_S32, pcm_s24le, "PCM signed 24-bit little-endian");
+PCM_CODEC  (CODEC_ID_PCM_S32BE, AV_SAMPLE_FMT_S32, pcm_s32be, "PCM signed 32-bit big-endian");
+PCM_CODEC  (CODEC_ID_PCM_S32LE, AV_SAMPLE_FMT_S32, pcm_s32le, "PCM signed 32-bit little-endian");
+PCM_CODEC  (CODEC_ID_PCM_U8,    AV_SAMPLE_FMT_U8,  pcm_u8, "PCM unsigned 8-bit");
+PCM_CODEC  (CODEC_ID_PCM_U16BE, AV_SAMPLE_FMT_S16, pcm_u16be, "PCM unsigned 16-bit big-endian");
+PCM_CODEC  (CODEC_ID_PCM_U16LE, AV_SAMPLE_FMT_S16, pcm_u16le, "PCM unsigned 16-bit little-endian");
+PCM_CODEC  (CODEC_ID_PCM_U24BE, AV_SAMPLE_FMT_S32, pcm_u24be, "PCM unsigned 24-bit big-endian");
+PCM_CODEC  (CODEC_ID_PCM_U24LE, AV_SAMPLE_FMT_S32, pcm_u24le, "PCM unsigned 24-bit little-endian");
+PCM_CODEC  (CODEC_ID_PCM_U32BE, AV_SAMPLE_FMT_S32, pcm_u32be, "PCM unsigned 32-bit big-endian");
+PCM_CODEC  (CODEC_ID_PCM_U32LE, AV_SAMPLE_FMT_S32, pcm_u32le, "PCM unsigned 32-bit little-endian");
+PCM_CODEC  (CODEC_ID_PCM_ZORK,  AV_SAMPLE_FMT_S16, pcm_zork, "PCM Zork");
diff --git a/libavcodec/pcm_tablegen.c b/libavcodec/pcm_tablegen.c
index 57ecb43..8a9bcb6 100644
--- a/libavcodec/pcm_tablegen.c
+++ b/libavcodec/pcm_tablegen.c
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2010 Reimar Döffinger <Reimar.Doeffinger at gmx.de>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -32,13 +32,8 @@ int main(void)
 
     write_fileheader();
 
-    printf("static const uint8_t linear_to_alaw[1 << 14] = {\n");
-    write_uint8_array(linear_to_alaw, 1 << 14);
-    printf("};\n");
-
-    printf("static const uint8_t linear_to_ulaw[1 << 14] = {\n");
-    write_uint8_array(linear_to_ulaw, 1 << 14);
-    printf("};\n");
+    WRITE_ARRAY("static const", uint8_t, linear_to_alaw);
+    WRITE_ARRAY("static const", uint8_t, linear_to_ulaw);
 
     return 0;
 }
diff --git a/libavcodec/pcm_tablegen.h b/libavcodec/pcm_tablegen.h
index 8921baa..838052e 100644
--- a/libavcodec/pcm_tablegen.h
+++ b/libavcodec/pcm_tablegen.h
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2010 Reimar Döffinger <Reimar.Doeffinger at gmx.de>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -24,7 +24,7 @@
 #define PCM_TABLEGEN_H
 
 #include <stdint.h>
-#include "../libavutil/attributes.h"
+#include "libavutil/attributes.h"
 
 /* from g711.c by SUN microsystems (unrestricted use) */
 
diff --git a/libavcodec/pcx.c b/libavcodec/pcx.c
index 2174184..fc0093f 100644
--- a/libavcodec/pcx.c
+++ b/libavcodec/pcx.c
@@ -5,23 +5,24 @@
  * This decoder does not support CGA palettes. I am unable to find samples
  * and Netpbm cannot generate them.
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/imgutils.h"
 #include "avcodec.h"
 #include "bytestream.h"
 #include "get_bits.h"
@@ -87,6 +88,8 @@ static int pcx_decode_frame(AVCodecContext *avctx, void *data, int *data_size,
                  bytes_per_scanline;
     uint8_t *ptr;
     uint8_t const *bufstart = buf;
+    uint8_t *scanline;
+    int ret = -1;
 
     if (buf[0] != 0x0a || buf[1] > 5) {
         av_log(avctx, AV_LOG_ERROR, "this is not PCX encoded data\n");
@@ -140,7 +143,7 @@ static int pcx_decode_frame(AVCodecContext *avctx, void *data, int *data_size,
     if (p->data[0])
         avctx->release_buffer(avctx, p);
 
-    if (avcodec_check_dimensions(avctx, w, h))
+    if (av_image_check_size(w, h, 0, avctx))
         return -1;
     if (w != avctx->width || h != avctx->height)
         avcodec_set_dimensions(avctx, w, h);
@@ -154,9 +157,11 @@ static int pcx_decode_frame(AVCodecContext *avctx, void *data, int *data_size,
     ptr    = p->data[0];
     stride = p->linesize[0];
 
-    if (nplanes == 3 && bits_per_pixel == 8) {
-        uint8_t scanline[bytes_per_scanline];
+    scanline = av_malloc(bytes_per_scanline);
+    if (!scanline)
+        return AVERROR(ENOMEM);
 
+    if (nplanes == 3 && bits_per_pixel == 8) {
         for (y=0; y<h; y++) {
             buf = pcx_rle_decode(buf, scanline, bytes_per_scanline, compressed);
 
@@ -170,7 +175,6 @@ static int pcx_decode_frame(AVCodecContext *avctx, void *data, int *data_size,
         }
 
     } else if (nplanes == 1 && bits_per_pixel == 8) {
-        uint8_t scanline[bytes_per_scanline];
         const uint8_t *palstart = bufstart + buf_size - 769;
 
         for (y=0; y<h; y++, ptr+=stride) {
@@ -184,11 +188,10 @@ static int pcx_decode_frame(AVCodecContext *avctx, void *data, int *data_size,
         }
         if (*buf++ != 12) {
             av_log(avctx, AV_LOG_ERROR, "expected palette after image data\n");
-            return -1;
+            goto end;
         }
 
     } else if (nplanes == 1) {   /* all packed formats, max. 16 colors */
-        uint8_t scanline[bytes_per_scanline];
         GetBitContext s;
 
         for (y=0; y<h; y++) {
@@ -202,7 +205,6 @@ static int pcx_decode_frame(AVCodecContext *avctx, void *data, int *data_size,
         }
 
     } else {    /* planar, 4, 8 or 16 colors */
-        uint8_t scanline[bytes_per_scanline];
         int i;
 
         for (y=0; y<h; y++) {
@@ -230,7 +232,10 @@ static int pcx_decode_frame(AVCodecContext *avctx, void *data, int *data_size,
     *picture = s->picture;
     *data_size = sizeof(AVFrame);
 
-    return buf - bufstart;
+    ret = buf - bufstart;
+end:
+    av_free(scanline);
+    return ret;
 }
 
 static av_cold int pcx_end(AVCodecContext *avctx) {
@@ -242,7 +247,7 @@ static av_cold int pcx_end(AVCodecContext *avctx) {
     return 0;
 }
 
-AVCodec pcx_decoder = {
+AVCodec ff_pcx_decoder = {
     "pcx",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_PCX,
diff --git a/libavcodec/pcxenc.c b/libavcodec/pcxenc.c
index a3ce284..2f2ae69 100644
--- a/libavcodec/pcxenc.c
+++ b/libavcodec/pcxenc.c
@@ -2,20 +2,20 @@
  * PC Paintbrush PCX (.pcx) image encoder
  * Copyright (c) 2009 Daniel Verkamp <daniel at drv.nu>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -33,7 +33,7 @@ typedef struct PCXContext {
     AVFrame picture;
 } PCXContext;
 
-static const uint32_t monoblack_pal[] = { 0x000000, 0xFFFFFF };
+static const uint32_t monoblack_pal[16] = { 0x000000, 0xFFFFFF };
 
 static av_cold int pcx_encode_init(AVCodecContext *avctx)
 {
@@ -189,7 +189,7 @@ static int pcx_encode_frame(AVCodecContext *avctx,
     return buf - buf_start;
 }
 
-AVCodec pcx_encoder = {
+AVCodec ff_pcx_encoder = {
     "pcx",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_PCX,
diff --git a/libavcodec/pgssubdec.c b/libavcodec/pgssubdec.c
index 5512006..ea53e55 100644
--- a/libavcodec/pgssubdec.c
+++ b/libavcodec/pgssubdec.c
@@ -2,20 +2,20 @@
  * PGS subtitle decoder
  * Copyright (c) 2009 Stephen Backway
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -26,8 +26,9 @@
 
 #include "avcodec.h"
 #include "dsputil.h"
-#include "colorspace.h"
 #include "bytestream.h"
+#include "libavutil/colorspace.h"
+#include "libavutil/imgutils.h"
 
 //#define DEBUG_PACKET_CONTENTS
 
@@ -44,9 +45,8 @@ enum SegmentType {
 typedef struct PGSSubPresentation {
     int x;
     int y;
-    int video_w;
-    int video_h;
     int id_number;
+    int object_number;
 } PGSSubPresentation;
 
 typedef struct PGSSubPicture {
@@ -54,6 +54,7 @@ typedef struct PGSSubPicture {
     int          h;
     uint8_t      *rle;
     unsigned int rle_buffer_size, rle_data_len;
+    unsigned int rle_remaining_len;
 } PGSSubPicture;
 
 typedef struct PGSSubContext {
@@ -64,7 +65,7 @@ typedef struct PGSSubContext {
 
 static av_cold int init_decoder(AVCodecContext *avctx)
 {
-    avctx->pix_fmt     = PIX_FMT_RGB32;
+    avctx->pix_fmt = PIX_FMT_PAL8;
 
     return 0;
 }
@@ -80,7 +81,7 @@ static av_cold int close_decoder(AVCodecContext *avctx)
 }
 
 /**
- * Decodes the RLE data.
+ * Decode the RLE data.
  *
  * The subtitle is stored as an Run Length Encoded image.
  *
@@ -135,13 +136,18 @@ static int decode_rle(AVCodecContext *avctx, AVSubtitle *sub,
         }
     }
 
-    dprintf(avctx, "Pixel Count = %d, Area = %d\n", pixel_count, sub->rects[0]->w * sub->rects[0]->h);
+    if (pixel_count < sub->rects[0]->w * sub->rects[0]->h) {
+        av_log(avctx, AV_LOG_ERROR, "Insufficient RLE data for subtitle\n");
+        return -1;
+    }
+
+    av_dlog(avctx, "Pixel Count = %d, Area = %d\n", pixel_count, sub->rects[0]->w * sub->rects[0]->h);
 
     return 0;
 }
 
 /**
- * Parses the picture segment packet.
+ * Parse the picture segment packet.
  *
  * The picture segment contains details on the sequence id,
  * width, height and Run Length Encoded (RLE) bitmap data.
@@ -159,6 +165,10 @@ static int parse_picture_segment(AVCodecContext *avctx,
     uint8_t sequence_desc;
     unsigned int rle_bitmap_len, width, height;
 
+    if (buf_size <= 4)
+        return -1;
+    buf_size -= 4;
+
     /* skip 3 unknown bytes: Object ID (2 bytes), Version Number */
     buf += 3;
 
@@ -166,27 +176,30 @@ static int parse_picture_segment(AVCodecContext *avctx,
     sequence_desc = bytestream_get_byte(&buf);
 
     if (!(sequence_desc & 0x80)) {
-        av_log(avctx, AV_LOG_ERROR, "Decoder does not support object data over multiple packets.\n");
-        return -1;
-    }
+        /* Additional RLE data */
+        if (buf_size > ctx->picture.rle_remaining_len)
+            return -1;
 
-    /* Decode rle bitmap length */
-    rle_bitmap_len = bytestream_get_be24(&buf);
+        memcpy(ctx->picture.rle + ctx->picture.rle_data_len, buf, buf_size);
+        ctx->picture.rle_data_len += buf_size;
+        ctx->picture.rle_remaining_len -= buf_size;
 
-    /* Check to ensure we have enough data for rle_bitmap_length if just a single packet */
-    if (rle_bitmap_len > buf_size - 7) {
-        av_log(avctx, AV_LOG_ERROR, "Not enough RLE data for specified length of %d.\n", rle_bitmap_len);
-        return -1;
+        return 0;
     }
 
-    ctx->picture.rle_data_len = rle_bitmap_len;
+    if (buf_size <= 7)
+        return -1;
+    buf_size -= 7;
+
+    /* Decode rle bitmap length, stored size includes width/height data */
+    rle_bitmap_len = bytestream_get_be24(&buf) - 2*2;
 
     /* Get bitmap dimensions from data */
     width  = bytestream_get_be16(&buf);
     height = bytestream_get_be16(&buf);
 
     /* Make sure the bitmap is not too large */
-    if (ctx->presentation.video_w < width || ctx->presentation.video_h < height) {
+    if (avctx->width < width || avctx->height < height) {
         av_log(avctx, AV_LOG_ERROR, "Bitmap dimensions larger then video.\n");
         return -1;
     }
@@ -199,13 +212,15 @@ static int parse_picture_segment(AVCodecContext *avctx,
     if (!ctx->picture.rle)
         return -1;
 
-    memcpy(ctx->picture.rle, buf, rle_bitmap_len);
+    memcpy(ctx->picture.rle, buf, buf_size);
+    ctx->picture.rle_data_len = buf_size;
+    ctx->picture.rle_remaining_len = rle_bitmap_len - buf_size;
 
     return 0;
 }
 
 /**
- * Parses the palette segment packet.
+ * Parse the palette segment packet.
  *
  * The palette segment contains details of the palette,
  * a maximum of 256 colors can be defined.
@@ -238,7 +253,7 @@ static void parse_palette_segment(AVCodecContext *avctx,
         YUV_TO_RGB1(cb, cr);
         YUV_TO_RGB2(r, g, b, y);
 
-        dprintf(avctx, "Color %d := (%d,%d,%d,%d)\n", color_id, r, g, b, alpha);
+        av_dlog(avctx, "Color %d := (%d,%d,%d,%d)\n", color_id, r, g, b, alpha);
 
         /* Store color in palette */
         ctx->clut[color_id] = RGBA(r,g,b,alpha);
@@ -246,7 +261,7 @@ static void parse_palette_segment(AVCodecContext *avctx,
 }
 
 /**
- * Parses the presentation segment packet.
+ * Parse the presentation segment packet.
  *
  * The presentation segment contains details on the video
  * width, video height, x & y subtitle position.
@@ -256,7 +271,6 @@ static void parse_palette_segment(AVCodecContext *avctx,
  * @param buf_size size of packet to process
  * @todo TODO: Implement cropping
  * @todo TODO: Implement forcing of subtitles
- * @todo TODO: Blanking of subtitle
  */
 static void parse_presentation_segment(AVCodecContext *avctx,
                                        const uint8_t *buf, int buf_size)
@@ -264,60 +278,60 @@ static void parse_presentation_segment(AVCodecContext *avctx,
     PGSSubContext *ctx = avctx->priv_data;
 
     int x, y;
-    uint8_t block;
 
-    ctx->presentation.video_w = bytestream_get_be16(&buf);
-    ctx->presentation.video_h = bytestream_get_be16(&buf);
+    int w = bytestream_get_be16(&buf);
+    int h = bytestream_get_be16(&buf);
 
-    dprintf(avctx, "Video Dimensions %dx%d\n",
-            ctx->presentation.video_w, ctx->presentation.video_h);
+    av_dlog(avctx, "Video Dimensions %dx%d\n",
+            w, h);
+    if (av_image_check_size(w, h, 0, avctx) >= 0)
+        avcodec_set_dimensions(avctx, w, h);
 
     /* Skip 1 bytes of unknown, frame rate? */
     buf++;
 
     ctx->presentation.id_number = bytestream_get_be16(&buf);
 
-    /* Next byte is the state. */
-    block = bytestream_get_byte(&buf);;
-    if (block == 0x80) {
-        /*
-         * Skip 7 bytes of unknown:
-         *     palette_update_flag (0x80),
-         *     palette_id_to_use,
-         *     Object Number (if > 0 determines if more data to process),
-         *     object_id_ref (2 bytes),
-         *     window_id_ref,
-         *     composition_flag (0x80 - object cropped, 0x40 - object forced)
-         */
-        buf += 7;
-
-        x = bytestream_get_be16(&buf);
-        y = bytestream_get_be16(&buf);
-
-        /* TODO If cropping, cropping_x, cropping_y, cropping_width, cropping_height (all 2 bytes).*/
-
-        dprintf(avctx, "Subtitle Placement x=%d, y=%d\n", x, y);
-
-        if (x > ctx->presentation.video_w || y > ctx->presentation.video_h) {
-            av_log(avctx, AV_LOG_ERROR, "Subtitle out of video bounds. x = %d, y = %d, video width = %d, video height = %d.\n",
-                   x, y, ctx->presentation.video_w, ctx->presentation.video_h);
-            x = 0; y = 0;
-        }
+    /*
+     * Skip 3 bytes of unknown:
+     *     state
+     *     palette_update_flag (0x80),
+     *     palette_id_to_use,
+     */
+    buf += 3;
+
+    ctx->presentation.object_number = bytestream_get_byte(&buf);
+    if (!ctx->presentation.object_number)
+        return;
+
+    /*
+     * Skip 4 bytes of unknown:
+     *     object_id_ref (2 bytes),
+     *     window_id_ref,
+     *     composition_flag (0x80 - object cropped, 0x40 - object forced)
+     */
+    buf += 4;
 
-        /* Fill in dimensions */
-        ctx->presentation.x = x;
-        ctx->presentation.y = y;
-    } else if (block == 0x00) {
-        /* TODO: Blank context as subtitle should not be displayed.
-         *       If the subtitle is blanked now the subtitle is not
-         *       on screen long enough to read, due to a delay in
-         *       initial display timing.
-         */
+    x = bytestream_get_be16(&buf);
+    y = bytestream_get_be16(&buf);
+
+    /* TODO If cropping, cropping_x, cropping_y, cropping_width, cropping_height (all 2 bytes).*/
+
+    av_dlog(avctx, "Subtitle Placement x=%d, y=%d\n", x, y);
+
+    if (x > avctx->width || y > avctx->height) {
+        av_log(avctx, AV_LOG_ERROR, "Subtitle out of video bounds. x = %d, y = %d, video width = %d, video height = %d.\n",
+               x, y, avctx->width, avctx->height);
+        x = 0; y = 0;
     }
+
+    /* Fill in dimensions */
+    ctx->presentation.x = x;
+    ctx->presentation.y = y;
 }
 
 /**
- * Parses the display segment packet.
+ * Parse the display segment packet.
  *
  * The display segment controls the updating of the display.
  *
@@ -344,6 +358,10 @@ static int display_end_segment(AVCodecContext *avctx, void *data,
      */
 
     memset(sub, 0, sizeof(*sub));
+    // Blank if last object_number was 0.
+    // Note that this may be wrong for more complex subtitles.
+    if (!ctx->presentation.object_number)
+        return 1;
     sub->start_display_time = 0;
     sub->end_display_time   = 20000;
     sub->format             = 0;
@@ -361,10 +379,13 @@ static int display_end_segment(AVCodecContext *avctx, void *data,
     /* Process bitmap */
     sub->rects[0]->pict.linesize[0] = ctx->picture.w;
 
-    if (ctx->picture.rle)
+    if (ctx->picture.rle) {
+        if (ctx->picture.rle_remaining_len)
+            av_log(avctx, AV_LOG_ERROR, "RLE data length %u is %u bytes shorter than expected\n",
+                   ctx->picture.rle_data_len, ctx->picture.rle_remaining_len);
         if(decode_rle(avctx, sub, ctx->picture.rle, ctx->picture.rle_data_len) < 0)
             return 0;
-
+    }
     /* Allocate memory for colors */
     sub->rects[0]->nb_colors    = 256;
     sub->rects[0]->pict.data[1] = av_mallocz(AVPALETTE_SIZE);
@@ -412,7 +433,7 @@ static int decode(AVCodecContext *avctx, void *data, int *data_size,
         segment_type   = bytestream_get_byte(&buf);
         segment_length = bytestream_get_be16(&buf);
 
-        dprintf(avctx, "Segment Length %d, Segment Type %x\n", segment_length, segment_type);
+        av_dlog(avctx, "Segment Length %d, Segment Type %x\n", segment_length, segment_type);
 
         if (segment_type != DISPLAY_SEGMENT && segment_length > buf_end - buf)
             break;
@@ -452,7 +473,7 @@ static int decode(AVCodecContext *avctx, void *data, int *data_size,
     return buf_size;
 }
 
-AVCodec pgssub_decoder = {
+AVCodec ff_pgssub_decoder = {
     "pgssub",
     AVMEDIA_TYPE_SUBTITLE,
     CODEC_ID_HDMV_PGS_SUBTITLE,
diff --git a/libavcodec/pictordec.c b/libavcodec/pictordec.c
new file mode 100644
index 0000000..74a49c8
--- /dev/null
+++ b/libavcodec/pictordec.c
@@ -0,0 +1,251 @@
+/*
+ * Pictor/PC Paint decoder
+ * Copyright (c) 2010 Peter Ross <pross at xvid.org>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * Pictor/PC Paint decoder
+ */
+
+#include "libavutil/imgutils.h"
+#include "avcodec.h"
+#include "bytestream.h"
+#include "cga_data.h"
+
+typedef struct PicContext {
+    AVFrame frame;
+    int width, height;
+    int nb_planes;
+} PicContext;
+
+static void picmemset_8bpp(PicContext *s, int value, int run, int *x, int *y)
+{
+    while (run > 0) {
+        uint8_t *d = s->frame.data[0] + *y * s->frame.linesize[0];
+        if (*x + run >= s->width) {
+            int n = s->width - *x;
+            memset(d + *x, value, n);
+            run -= n;
+            *x = 0;
+            *y -= 1;
+            if (*y < 0)
+                break;
+        } else {
+            memset(d + *x, value, run);
+            *x += run;
+            break;
+        }
+    }
+}
+
+static void picmemset(PicContext *s, int value, int run, int *x, int *y, int *plane, int bits_per_plane)
+{
+    uint8_t *d;
+    int shift = *plane * bits_per_plane;
+    int mask  = ((1 << bits_per_plane) - 1) << shift;
+    value   <<= shift;
+
+    while (run > 0) {
+        int j;
+        for (j = 8-bits_per_plane; j >= 0; j -= bits_per_plane) {
+            d = s->frame.data[0] + *y * s->frame.linesize[0];
+            d[*x] |= (value >> j) & mask;
+            *x += 1;
+            if (*x == s->width) {
+                *y -= 1;
+                *x = 0;
+                if (*y < 0) {
+                   *y = s->height - 1;
+                   *plane += 1;
+                   value <<= bits_per_plane;
+                   mask  <<= bits_per_plane;
+                   if (*plane >= s->nb_planes)
+                       break;
+                }
+            }
+        }
+        run--;
+    }
+}
+
+static const uint8_t cga_mode45_index[6][4] = {
+    [0] = { 0, 3,  5,   7 }, // mode4, palette#1, low intensity
+    [1] = { 0, 2,  4,   6 }, // mode4, palette#2, low intensity
+    [2] = { 0, 3,  4,   7 }, // mode5, low intensity
+    [3] = { 0, 11, 13, 15 }, // mode4, palette#1, high intensity
+    [4] = { 0, 10, 12, 14 }, // mode4, palette#2, high intensity
+    [5] = { 0, 11, 12, 15 }, // mode5, high intensity
+};
+
+static int decode_frame(AVCodecContext *avctx,
+                        void *data, int *data_size,
+                        AVPacket *avpkt)
+{
+    PicContext *s = avctx->priv_data;
+    int buf_size = avpkt->size;
+    const uint8_t *buf = avpkt->data;
+    const uint8_t *buf_end = avpkt->data + buf_size;
+    uint32_t *palette;
+    int bits_per_plane, bpp, etype, esize, npal;
+    int i, x, y, plane;
+
+    if (buf_size < 11)
+        return AVERROR_INVALIDDATA;
+
+    if (bytestream_get_le16(&buf) != 0x1234)
+        return AVERROR_INVALIDDATA;
+    s->width  = bytestream_get_le16(&buf);
+    s->height = bytestream_get_le16(&buf);
+    buf += 4;
+    bits_per_plane    = *buf & 0xF;
+    s->nb_planes      = (*buf++ >> 4) + 1;
+    bpp               = s->nb_planes ? bits_per_plane*s->nb_planes : bits_per_plane;
+    if (bits_per_plane > 8 || bpp < 1 || bpp > 32) {
+        av_log_ask_for_sample(s, "unsupported bit depth\n");
+        return AVERROR_INVALIDDATA;
+    }
+
+    if (*buf == 0xFF) {
+        buf += 2;
+        etype  = bytestream_get_le16(&buf);
+        esize  = bytestream_get_le16(&buf);
+        if (buf_end - buf < esize)
+            return AVERROR_INVALIDDATA;
+    } else {
+        etype = -1;
+        esize = 0;
+    }
+
+    avctx->pix_fmt = PIX_FMT_PAL8;
+
+    if (s->width != avctx->width && s->height != avctx->height) {
+        if (av_image_check_size(s->width, s->height, 0, avctx) < 0)
+            return -1;
+        avcodec_set_dimensions(avctx, s->width, s->height);
+        if (s->frame.data[0])
+            avctx->release_buffer(avctx, &s->frame);
+    }
+
+    if (avctx->get_buffer(avctx, &s->frame) < 0){
+        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
+        return -1;
+    }
+    memset(s->frame.data[0], 0, s->height * s->frame.linesize[0]);
+    s->frame.pict_type           = FF_I_TYPE;
+    s->frame.palette_has_changed = 1;
+
+    palette = (uint32_t*)s->frame.data[1];
+    if (etype == 1 && esize > 1 && *buf < 6) {
+        int idx = *buf;
+        npal = 4;
+        for (i = 0; i < npal; i++)
+            palette[i] = ff_cga_palette[ cga_mode45_index[idx][i] ];
+    } else if (etype == 2) {
+        npal = FFMIN(esize, 16);
+        for (i = 0; i < npal; i++)
+            palette[i] = ff_cga_palette[ FFMIN(buf[i], 16)];
+    } else if (etype == 3) {
+        npal = FFMIN(esize, 16);
+        for (i = 0; i < npal; i++)
+            palette[i] = ff_ega_palette[ FFMIN(buf[i], 63)];
+    } else if (etype == 4 || etype == 5) {
+        npal = FFMIN(esize / 3, 256);
+        for (i = 0; i < npal; i++)
+            palette[i] = AV_RB24(buf + i*3) << 2;
+    } else {
+        if (bpp == 1) {
+            npal = 2;
+            palette[0] = 0x000000;
+            palette[1] = 0xFFFFFF;
+        } else if (bpp == 2) {
+            npal = 4;
+            for (i = 0; i < npal; i++)
+                palette[i] = ff_cga_palette[ cga_mode45_index[0][i] ];
+        } else {
+            npal = 16;
+            memcpy(palette, ff_cga_palette, npal * 4);
+        }
+    }
+    // fill remaining palette entries
+    memset(palette + npal, 0, AVPALETTE_SIZE - npal * 4);
+    buf += esize;
+
+
+    x = 0;
+    y = s->height - 1;
+    plane = 0;
+    if (bytestream_get_le16(&buf)) {
+        while (buf_end - buf >= 6) {
+            const uint8_t *buf_pend = buf + FFMIN(AV_RL16(buf), buf_end - buf);
+            //ignore uncompressed block size reported at buf[2]
+            int marker = buf[4];
+            buf += 5;
+
+            while (plane < s->nb_planes && buf_pend - buf >= 1) {
+                int run = 1;
+                int val = *buf++;
+                if (val == marker) {
+                    run = *buf++;
+                    if (run == 0)
+                        run = bytestream_get_le16(&buf);
+                    val = *buf++;
+                }
+                if (buf > buf_end)
+                    break;
+
+                if (bits_per_plane == 8) {
+                    picmemset_8bpp(s, val, run, &x, &y);
+                    if (y < 0)
+                        break;
+                } else {
+                    picmemset(s, val, run, &x, &y, &plane, bits_per_plane);
+                }
+            }
+        }
+    } else {
+        av_log_ask_for_sample(s, "uncompressed image\n");
+        return buf_size;
+    }
+
+    *data_size = sizeof(AVFrame);
+    *(AVFrame*)data = s->frame;
+    return buf_size;
+}
+
+static av_cold int decode_end(AVCodecContext *avctx)
+{
+    PicContext *s = avctx->priv_data;
+    if (s->frame.data[0])
+        avctx->release_buffer(avctx, &s->frame);
+    return 0;
+}
+
+AVCodec ff_pictor_decoder = {
+    "pictor",
+    AVMEDIA_TYPE_VIDEO,
+    CODEC_ID_PICTOR,
+    sizeof(PicContext),
+    NULL,
+    NULL,
+    decode_end,
+    decode_frame,
+    CODEC_CAP_DR1,
+    .long_name = NULL_IF_CONFIG_SMALL("Pictor/PC Paint"),
+};
diff --git a/libavcodec/png.c b/libavcodec/png.c
index 534dc68..70a080e 100644
--- a/libavcodec/png.c
+++ b/libavcodec/png.c
@@ -2,20 +2,20 @@
  * PNG image format
  * Copyright (c) 2003 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #include "avcodec.h"
@@ -31,12 +31,12 @@ const uint8_t ff_png_pass_ymask[NB_PASSES] = {
 };
 
 /* minimum x value */
-const uint8_t ff_png_pass_xmin[NB_PASSES] = {
+static const uint8_t ff_png_pass_xmin[NB_PASSES] = {
     0, 4, 0, 2, 0, 1, 0
 };
 
 /* x shift to get row width */
-const uint8_t ff_png_pass_xshift[NB_PASSES] = {
+static const uint8_t ff_png_pass_xshift[NB_PASSES] = {
     3, 3, 2, 2, 1, 1, 0
 };
 
diff --git a/libavcodec/png.h b/libavcodec/png.h
index 7c0ab9f..b8c72ee 100644
--- a/libavcodec/png.h
+++ b/libavcodec/png.h
@@ -2,20 +2,20 @@
  * PNG image format
  * Copyright (c) 2003 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -55,12 +55,6 @@ extern const uint8_t ff_mngsig[8];
 /* Mask to determine which y pixels are valid in a pass */
 extern const uint8_t ff_png_pass_ymask[NB_PASSES];
 
-/* minimum x value */
-extern const uint8_t ff_png_pass_xmin[NB_PASSES];
-
-/* x shift to get row width */
-extern const uint8_t ff_png_pass_xshift[NB_PASSES];
-
 /* Mask to determine which pixels are valid in a pass */
 extern const uint8_t ff_png_pass_mask[NB_PASSES];
 
diff --git a/libavcodec/pngdec.c b/libavcodec/pngdec.c
index 03859a9..b1521de 100644
--- a/libavcodec/pngdec.c
+++ b/libavcodec/pngdec.c
@@ -2,22 +2,23 @@
  * PNG image format
  * Copyright (c) 2003 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
+#include "libavutil/imgutils.h"
 #include "avcodec.h"
 #include "bytestream.h"
 #include "png.h"
@@ -429,8 +430,8 @@ static int decode_frame(AVCodecContext *avctx,
         if (length > 0x7fffffff)
             goto fail;
         tag32 = bytestream_get_be32(&s->bytestream);
-        tag = bswap_32(tag32);
-        dprintf(avctx, "png: tag=%c%c%c%c length=%u\n",
+        tag = av_bswap32(tag32);
+        av_dlog(avctx, "png: tag=%c%c%c%c length=%u\n",
                 (tag & 0xff),
                 ((tag >> 8) & 0xff),
                 ((tag >> 16) & 0xff),
@@ -441,7 +442,7 @@ static int decode_frame(AVCodecContext *avctx,
                 goto fail;
             s->width = bytestream_get_be32(&s->bytestream);
             s->height = bytestream_get_be32(&s->bytestream);
-            if(avcodec_check_dimensions(avctx, s->width, s->height)){
+            if(av_image_check_size(s->width, s->height, 0, avctx)){
                 s->width= s->height= 0;
                 goto fail;
             }
@@ -452,7 +453,7 @@ static int decode_frame(AVCodecContext *avctx,
             s->interlace_type = *s->bytestream++;
             crc = bytestream_get_be32(&s->bytestream);
             s->state |= PNG_IHDR;
-            dprintf(avctx, "width=%d height=%d depth=%d color_type=%d compression_type=%d filter_type=%d interlace_type=%d\n",
+            av_dlog(avctx, "width=%d height=%d depth=%d color_type=%d compression_type=%d filter_type=%d interlace_type=%d\n",
                     s->width, s->height, s->bit_depth, s->color_type,
                     s->compression_type, s->filter_type, s->interlace_type);
             break;
@@ -516,7 +517,7 @@ static int decode_frame(AVCodecContext *avctx,
                                                          s->width);
                     s->crow_size = s->pass_row_size + 1;
                 }
-                dprintf(avctx, "row_size=%d crow_size =%d\n",
+                av_dlog(avctx, "row_size=%d crow_size =%d\n",
                         s->row_size, s->crow_size);
                 s->image_buf = p->data[0];
                 s->image_linesize = p->linesize[0];
@@ -656,7 +657,7 @@ static av_cold int png_dec_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec png_decoder = {
+AVCodec ff_png_decoder = {
     "png",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_PNG,
@@ -667,5 +668,6 @@ AVCodec png_decoder = {
     decode_frame,
     CODEC_CAP_DR1 /*| CODEC_CAP_DRAW_HORIZ_BAND*/,
     NULL,
+    .max_lowres = 5,
     .long_name = NULL_IF_CONFIG_SMALL("PNG image"),
 };
diff --git a/libavcodec/pngenc.c b/libavcodec/pngenc.c
index 615bcc4..e7b09ef 100644
--- a/libavcodec/pngenc.c
+++ b/libavcodec/pngenc.c
@@ -2,20 +2,20 @@
  * PNG image format
  * Copyright (c) 2003 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #include "avcodec.h"
@@ -199,7 +199,7 @@ static void png_write_chunk(uint8_t **f, uint32_t tag,
     crc = crc32(0, Z_NULL, 0);
     AV_WL32(tagbuf, tag);
     crc = crc32(crc, tagbuf, 4);
-    bytestream_put_be32(f, bswap_32(tag));
+    bytestream_put_be32(f, av_bswap32(tag));
     if (length > 0) {
         crc = crc32(crc, buf, length);
         memcpy(*f, buf, length);
@@ -436,7 +436,7 @@ static av_cold int png_enc_init(AVCodecContext *avctx){
     return 0;
 }
 
-AVCodec png_encoder = {
+AVCodec ff_png_encoder = {
     "png",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_PNG,
diff --git a/libavcodec/pnm.c b/libavcodec/pnm.c
index cb6a713..54b55cf 100644
--- a/libavcodec/pnm.c
+++ b/libavcodec/pnm.c
@@ -2,23 +2,24 @@
  * PNM image format
  * Copyright (c) 2002, 2003 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/imgutils.h"
 #include "avcodec.h"
 #include "pnm.h"
 
@@ -101,7 +102,7 @@ int ff_pnm_decode_header(AVCodecContext *avctx, PNMContext * const s)
             }
         }
         /* check that all tags are present */
-        if (w <= 0 || h <= 0 || maxval <= 0 || depth <= 0 || tuple_type[0] == '\0' || avcodec_check_dimensions(avctx, w, h))
+        if (w <= 0 || h <= 0 || maxval <= 0 || depth <= 0 || tuple_type[0] == '\0' || av_image_check_size(w, h, 0, avctx))
             return -1;
 
         avctx->width  = w;
@@ -134,11 +135,15 @@ int ff_pnm_decode_header(AVCodecContext *avctx, PNMContext * const s)
         return -1;
     pnm_get(s, buf1, sizeof(buf1));
     avctx->height = atoi(buf1);
-    if(avcodec_check_dimensions(avctx, avctx->width, avctx->height))
+    if(av_image_check_size(avctx->width, avctx->height, 0, avctx))
         return -1;
     if (avctx->pix_fmt != PIX_FMT_MONOWHITE) {
         pnm_get(s, buf1, sizeof(buf1));
         s->maxval = atoi(buf1);
+        if (s->maxval <= 0) {
+            av_log(avctx, AV_LOG_ERROR, "Invalid maxval: %d\n", s->maxval);
+            s->maxval = 255;
+        }
         if (s->maxval >= 256) {
             if (avctx->pix_fmt == PIX_FMT_GRAY8) {
                 avctx->pix_fmt = PIX_FMT_GRAY16BE;
diff --git a/libavcodec/pnm.h b/libavcodec/pnm.h
index ac4b108..702921f 100644
--- a/libavcodec/pnm.h
+++ b/libavcodec/pnm.h
@@ -2,20 +2,20 @@
  * PNM image format
  * Copyright (c) 2002, 2003 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/pnm_parser.c b/libavcodec/pnm_parser.c
index b8ba1a8..2dc2987 100644
--- a/libavcodec/pnm_parser.c
+++ b/libavcodec/pnm_parser.c
@@ -2,20 +2,20 @@
  * PNM image parser
  * Copyright (c) 2002, 2003 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -83,7 +83,7 @@ retry:
     return next;
 }
 
-AVCodecParser pnm_parser = {
+AVCodecParser ff_pnm_parser = {
     { CODEC_ID_PGM, CODEC_ID_PGMYUV, CODEC_ID_PPM, CODEC_ID_PBM, CODEC_ID_PAM},
     sizeof(ParseContext),
     NULL,
diff --git a/libavcodec/pnmdec.c b/libavcodec/pnmdec.c
index 66033c1..663def6 100644
--- a/libavcodec/pnmdec.c
+++ b/libavcodec/pnmdec.c
@@ -2,20 +2,20 @@
  * PNM image format
  * Copyright (c) 2002, 2003 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -124,7 +124,7 @@ static int pnm_decode_frame(AVCodecContext *avctx, void *data,
             } else if (upgrade == 2) {
                 unsigned int j, v, f = (65535 * 32768 + s->maxval / 2) / s->maxval;
                 for (j = 0; j < n / 2; j++) {
-                    v = be2me_16(((uint16_t *)s->bytestream)[j]);
+                    v = av_be2ne16(((uint16_t *)s->bytestream)[j]);
                     ((uint16_t *)ptr)[j] = (v * f + 16384) >> 15;
                 }
             }
@@ -188,7 +188,7 @@ static int pnm_decode_frame(AVCodecContext *avctx, void *data,
 
 
 #if CONFIG_PGM_DECODER
-AVCodec pgm_decoder = {
+AVCodec ff_pgm_decoder = {
     "pgm",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_PGM,
@@ -199,12 +199,13 @@ AVCodec pgm_decoder = {
     pnm_decode_frame,
     CODEC_CAP_DR1,
     .pix_fmts  = (const enum PixelFormat[]){PIX_FMT_GRAY8, PIX_FMT_GRAY16BE, PIX_FMT_NONE},
+    .max_lowres = 5,
     .long_name = NULL_IF_CONFIG_SMALL("PGM (Portable GrayMap) image"),
 };
 #endif
 
 #if CONFIG_PGMYUV_DECODER
-AVCodec pgmyuv_decoder = {
+AVCodec ff_pgmyuv_decoder = {
     "pgmyuv",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_PGMYUV,
@@ -215,12 +216,13 @@ AVCodec pgmyuv_decoder = {
     pnm_decode_frame,
     CODEC_CAP_DR1,
     .pix_fmts  = (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
+    .max_lowres = 5,
     .long_name = NULL_IF_CONFIG_SMALL("PGMYUV (Portable GrayMap YUV) image"),
 };
 #endif
 
 #if CONFIG_PPM_DECODER
-AVCodec ppm_decoder = {
+AVCodec ff_ppm_decoder = {
     "ppm",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_PPM,
@@ -231,12 +233,13 @@ AVCodec ppm_decoder = {
     pnm_decode_frame,
     CODEC_CAP_DR1,
     .pix_fmts  = (const enum PixelFormat[]){PIX_FMT_RGB24, PIX_FMT_RGB48BE, PIX_FMT_NONE},
+    .max_lowres = 5,
     .long_name = NULL_IF_CONFIG_SMALL("PPM (Portable PixelMap) image"),
 };
 #endif
 
 #if CONFIG_PBM_DECODER
-AVCodec pbm_decoder = {
+AVCodec ff_pbm_decoder = {
     "pbm",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_PBM,
@@ -247,12 +250,13 @@ AVCodec pbm_decoder = {
     pnm_decode_frame,
     CODEC_CAP_DR1,
     .pix_fmts  = (const enum PixelFormat[]){PIX_FMT_MONOWHITE, PIX_FMT_NONE},
+    .max_lowres = 5,
     .long_name = NULL_IF_CONFIG_SMALL("PBM (Portable BitMap) image"),
 };
 #endif
 
 #if CONFIG_PAM_DECODER
-AVCodec pam_decoder = {
+AVCodec ff_pam_decoder = {
     "pam",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_PAM,
@@ -263,6 +267,7 @@ AVCodec pam_decoder = {
     pnm_decode_frame,
     CODEC_CAP_DR1,
     .pix_fmts  = (const enum PixelFormat[]){PIX_FMT_RGB24, PIX_FMT_RGB32, PIX_FMT_GRAY8, PIX_FMT_MONOWHITE, PIX_FMT_NONE},
+    .max_lowres = 5,
     .long_name = NULL_IF_CONFIG_SMALL("PAM (Portable AnyMap) image"),
 };
 #endif
diff --git a/libavcodec/pnmenc.c b/libavcodec/pnmenc.c
index 1fbf665..a04b864 100644
--- a/libavcodec/pnmenc.c
+++ b/libavcodec/pnmenc.c
@@ -2,20 +2,20 @@
  * PNM image format
  * Copyright (c) 2002, 2003 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -113,7 +113,7 @@ static int pnm_encode_frame(AVCodecContext *avctx, unsigned char *outbuf,
 
 
 #if CONFIG_PGM_ENCODER
-AVCodec pgm_encoder = {
+AVCodec ff_pgm_encoder = {
     "pgm",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_PGM,
@@ -126,7 +126,7 @@ AVCodec pgm_encoder = {
 #endif
 
 #if CONFIG_PGMYUV_ENCODER
-AVCodec pgmyuv_encoder = {
+AVCodec ff_pgmyuv_encoder = {
     "pgmyuv",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_PGMYUV,
@@ -139,7 +139,7 @@ AVCodec pgmyuv_encoder = {
 #endif
 
 #if CONFIG_PPM_ENCODER
-AVCodec ppm_encoder = {
+AVCodec ff_ppm_encoder = {
     "ppm",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_PPM,
@@ -152,7 +152,7 @@ AVCodec ppm_encoder = {
 #endif
 
 #if CONFIG_PBM_ENCODER
-AVCodec pbm_encoder = {
+AVCodec ff_pbm_encoder = {
     "pbm",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_PBM,
diff --git a/libavcodec/ppc/Makefile b/libavcodec/ppc/Makefile
index 5d5a59b..35ea0c3 100644
--- a/libavcodec/ppc/Makefile
+++ b/libavcodec/ppc/Makefile
@@ -5,12 +5,23 @@ ALTIVEC-OBJS-$(CONFIG_VC1_DECODER)     += ppc/vc1dsp_altivec.o
 ALTIVEC-OBJS-$(CONFIG_VP3_DECODER)     += ppc/vp3dsp_altivec.o
 ALTIVEC-OBJS-$(CONFIG_VP5_DECODER)     += ppc/vp3dsp_altivec.o
 ALTIVEC-OBJS-$(CONFIG_VP6_DECODER)     += ppc/vp3dsp_altivec.o
+ALTIVEC-OBJS-$(CONFIG_VP8_DECODER)     += ppc/vp8dsp_altivec.o
 
-OBJS-$(HAVE_ALTIVEC)                   += ppc/check_altivec.o           \
-                                          ppc/dsputil_altivec.o         \
+ALTIVEC-OBJS-$(CONFIG_MP1FLOAT_DECODER)    += ppc/mpegaudiodec_altivec.o
+ALTIVEC-OBJS-$(CONFIG_MP2FLOAT_DECODER)    += ppc/mpegaudiodec_altivec.o
+ALTIVEC-OBJS-$(CONFIG_MP3FLOAT_DECODER)    += ppc/mpegaudiodec_altivec.o
+ALTIVEC-OBJS-$(CONFIG_MP3ON4FLOAT_DECODER) += ppc/mpegaudiodec_altivec.o
+ALTIVEC-OBJS-$(CONFIG_MP3ADUFLOAT_DECODER) += ppc/mpegaudiodec_altivec.o
+
+FFT-OBJS-$(HAVE_GNU_AS)                += ppc/fft_altivec_s.o           \
+
+ALTIVEC-OBJS-$(CONFIG_FFT)             += ppc/fft_altivec.o             \
+                                          $(FFT-OBJS-yes)
+
+OBJS-$(HAVE_ALTIVEC)                   += ppc/dsputil_altivec.o         \
                                           ppc/fdct_altivec.o            \
-                                          ppc/fft_altivec.o             \
                                           ppc/float_altivec.o           \
+                                          ppc/fmtconvert_altivec.o      \
                                           ppc/gmc_altivec.o             \
                                           ppc/idct_altivec.o            \
                                           ppc/int_altivec.o             \
diff --git a/libavcodec/ppc/asm.S b/libavcodec/ppc/asm.S
new file mode 100644
index 0000000..5cbbf97
--- /dev/null
+++ b/libavcodec/ppc/asm.S
@@ -0,0 +1,120 @@
+/*
+ * Copyright (c) 2009 Loren Merritt
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "config.h"
+
+#define GLUE(a, b) a ## b
+#define JOIN(a, b) GLUE(a, b)
+#define X(s) JOIN(EXTERN_ASM, s)
+
+#if ARCH_PPC64
+
+#define PTR  .quad
+#define lp   ld
+#define lpx  ldx
+#define stp  std
+#define stpu stdu
+#define PS   8
+#define L(s) JOIN(., s)
+
+.macro extfunc name
+    .global X(\name)
+    .section .opd, "aw"
+X(\name):
+    .quad L(\name), .TOC. at tocbase, 0
+    .previous
+    .type X(\name), STT_FUNC
+L(\name):
+.endm
+
+.macro movrel rd, sym
+    ld      \rd, \sym at got(r2)
+.endm
+
+#else /* ARCH_PPC64 */
+
+#define PTR  .int
+#define lp   lwz
+#define lpx  lwzx
+#define stp  stw
+#define stpu stwu
+#define PS   4
+#define L(s) s
+
+.macro extfunc name
+    .global X(\name)
+    .type   X(\name), STT_FUNC
+X(\name):
+\name:
+.endm
+
+.macro movrel rd, sym
+#if CONFIG_PIC
+    lwz     \rd, \sym at got(r2)
+#else
+    lis     \rd, \sym at ha
+    la      \rd, \sym at l(\rd)
+#endif
+.endm
+
+#endif /* ARCH_PPC64 */
+
+#if HAVE_IBM_ASM
+
+.macro DEFINE_REG n
+    .equiv r\n, \n
+    .equiv f\n, \n
+    .equiv v\n, \n
+.endm
+
+DEFINE_REG 0
+DEFINE_REG 1
+DEFINE_REG 2
+DEFINE_REG 3
+DEFINE_REG 4
+DEFINE_REG 5
+DEFINE_REG 6
+DEFINE_REG 7
+DEFINE_REG 8
+DEFINE_REG 9
+DEFINE_REG 10
+DEFINE_REG 11
+DEFINE_REG 12
+DEFINE_REG 13
+DEFINE_REG 14
+DEFINE_REG 15
+DEFINE_REG 16
+DEFINE_REG 17
+DEFINE_REG 18
+DEFINE_REG 19
+DEFINE_REG 20
+DEFINE_REG 21
+DEFINE_REG 22
+DEFINE_REG 23
+DEFINE_REG 24
+DEFINE_REG 25
+DEFINE_REG 26
+DEFINE_REG 27
+DEFINE_REG 28
+DEFINE_REG 29
+DEFINE_REG 30
+DEFINE_REG 31
+
+#endif /* HAVE_IBM_ASM */
diff --git a/libavcodec/ppc/check_altivec.c b/libavcodec/ppc/check_altivec.c
deleted file mode 100644
index c8bc6ed..0000000
--- a/libavcodec/ppc/check_altivec.c
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-
-/**
- * @file
- * Checks for AltiVec presence.
- */
-
-#ifdef __APPLE__
-#undef _POSIX_C_SOURCE
-#include <sys/sysctl.h>
-#elif defined(__OpenBSD__)
-#include <sys/param.h>
-#include <sys/sysctl.h>
-#include <machine/cpu.h>
-#elif defined(__AMIGAOS4__)
-#include <exec/exec.h>
-#include <interfaces/exec.h>
-#include <proto/exec.h>
-#endif /* __APPLE__ */
-
-#include "config.h"
-#include "dsputil_altivec.h"
-
-/**
- * This function MAY rely on signal() or fork() in order to make sure AltiVec
- * is present.
- */
-
-int has_altivec(void)
-{
-#ifdef __AMIGAOS4__
-    ULONG result = 0;
-    extern struct ExecIFace *IExec;
-
-    IExec->GetCPUInfoTags(GCIT_VectorUnit, &result, TAG_DONE);
-    if (result == VECTORTYPE_ALTIVEC) return 1;
-    return 0;
-#elif defined(__APPLE__) || defined(__OpenBSD__)
-#ifdef __OpenBSD__
-    int sels[2] = {CTL_MACHDEP, CPU_ALTIVEC};
-#else
-    int sels[2] = {CTL_HW, HW_VECTORUNIT};
-#endif
-    int has_vu = 0;
-    size_t len = sizeof(has_vu);
-    int err;
-
-    err = sysctl(sels, 2, &has_vu, &len, NULL, 0);
-
-    if (err == 0) return has_vu != 0;
-    return 0;
-#elif CONFIG_RUNTIME_CPUDETECT
-    int proc_ver;
-    // Support of mfspr PVR emulation added in Linux 2.6.17.
-    __asm__ volatile("mfspr %0, 287" : "=r" (proc_ver));
-    proc_ver >>= 16;
-    if (proc_ver  & 0x8000 ||
-        proc_ver == 0x000c ||
-        proc_ver == 0x0039 || proc_ver == 0x003c ||
-        proc_ver == 0x0044 || proc_ver == 0x0045 ||
-        proc_ver == 0x0070)
-        return 1;
-    return 0;
-#else
-    // Since we were compiled for AltiVec, just assume we have it
-    // until someone comes up with a proper way (not involving signal hacks).
-    return 1;
-#endif /* __AMIGAOS4__ */
-}
-
diff --git a/libavcodec/ppc/dsputil_altivec.c b/libavcodec/ppc/dsputil_altivec.c
index 925b6c8..9111d03 100644
--- a/libavcodec/ppc/dsputil_altivec.c
+++ b/libavcodec/ppc/dsputil_altivec.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2002 Dieter Shirley
  * Copyright (c) 2003-2004 Romain Dolbeau <romain at dolbeau.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,7 +25,6 @@
 #include <altivec.h>
 #endif
 #include "libavcodec/dsputil.h"
-#include "dsputil_ppc.h"
 #include "util_altivec.h"
 #include "types_altivec.h"
 #include "dsputil_altivec.h"
@@ -231,7 +230,7 @@ static int sad16_altivec(void *v, uint8_t *pix1, uint8_t *pix2, int line_size, i
     int i;
     int s;
     const vector unsigned int zero = (const vector unsigned int)vec_splat_u32(0);
-    vector unsigned char perm1, perm2, *pix1v, *pix2v;
+    vector unsigned char perm1, perm2, pix1v_low, pix1v_high, pix2v_low, pix2v_high;
     vector unsigned char t1, t2, t3,t4, t5;
     vector unsigned int sad;
     vector signed int sumdiffs;
@@ -242,11 +241,13 @@ static int sad16_altivec(void *v, uint8_t *pix1, uint8_t *pix2, int line_size, i
     for (i = 0; i < h; i++) {
         /* Read potentially unaligned pixels into t1 and t2 */
         perm1 = vec_lvsl(0, pix1);
-        pix1v = (vector unsigned char *) pix1;
+        pix1v_high = vec_ld( 0, pix1);
+        pix1v_low  = vec_ld(15, pix1);
         perm2 = vec_lvsl(0, pix2);
-        pix2v = (vector unsigned char *) pix2;
-        t1 = vec_perm(pix1v[0], pix1v[1], perm1);
-        t2 = vec_perm(pix2v[0], pix2v[1], perm2);
+        pix2v_high = vec_ld( 0, pix2);
+        pix2v_low  = vec_ld(15, pix2);
+        t1 = vec_perm(pix1v_high, pix1v_low, perm1);
+        t2 = vec_perm(pix2v_high, pix2v_low, perm2);
 
         /* Calculate a sum of abs differences vector */
         t3 = vec_max(t1, t2);
@@ -610,7 +611,6 @@ static void add_bytes_altivec(uint8_t *dst, uint8_t *src, int w) {
 /* next one assumes that ((line_size % 16) == 0) */
 void put_pixels16_altivec(uint8_t *block, const uint8_t *pixels, int line_size, int h)
 {
-POWERPC_PERF_DECLARE(altivec_put_pixels16_num, 1);
     register vector unsigned char pixelsv1, pixelsv2;
     register vector unsigned char pixelsv1B, pixelsv2B;
     register vector unsigned char pixelsv1C, pixelsv2C;
@@ -622,7 +622,6 @@ POWERPC_PERF_DECLARE(altivec_put_pixels16_num, 1);
     register int line_size_3 = line_size + line_size_2;
     register int line_size_4 = line_size << 2;
 
-POWERPC_PERF_START_COUNT(altivec_put_pixels16_num, 1);
 // hand-unrolling the loop by 4 gains about 15%
 // mininum execution time goes from 74 to 60 cycles
 // it's faster than -funroll-loops, but using
@@ -659,20 +658,16 @@ POWERPC_PERF_START_COUNT(altivec_put_pixels16_num, 1);
         block +=line_size_4;
     }
 #endif
-POWERPC_PERF_STOP_COUNT(altivec_put_pixels16_num, 1);
 }
 
 /* next one assumes that ((line_size % 16) == 0) */
 #define op_avg(a,b)  a = ( ((a)|(b)) - ((((a)^(b))&0xFEFEFEFEUL)>>1) )
 void avg_pixels16_altivec(uint8_t *block, const uint8_t *pixels, int line_size, int h)
 {
-POWERPC_PERF_DECLARE(altivec_avg_pixels16_num, 1);
     register vector unsigned char pixelsv1, pixelsv2, pixelsv, blockv;
     register vector unsigned char perm = vec_lvsl(0, pixels);
     int i;
 
-POWERPC_PERF_START_COUNT(altivec_avg_pixels16_num, 1);
-
     for (i = 0; i < h; i++) {
         pixelsv1 = vec_ld( 0, pixels);
         pixelsv2 = vec_ld(16,pixels);
@@ -683,19 +678,14 @@ POWERPC_PERF_START_COUNT(altivec_avg_pixels16_num, 1);
         pixels+=line_size;
         block +=line_size;
     }
-
-POWERPC_PERF_STOP_COUNT(altivec_avg_pixels16_num, 1);
 }
 
 /* next one assumes that ((line_size % 8) == 0) */
 static void avg_pixels8_altivec(uint8_t * block, const uint8_t * pixels, int line_size, int h)
 {
-POWERPC_PERF_DECLARE(altivec_avg_pixels8_num, 1);
     register vector unsigned char pixelsv1, pixelsv2, pixelsv, blockv;
     int i;
 
-POWERPC_PERF_START_COUNT(altivec_avg_pixels8_num, 1);
-
    for (i = 0; i < h; i++) {
        /* block is 8 bytes-aligned, so we're either in the
           left block (16 bytes-aligned) or in the right block (not) */
@@ -719,14 +709,11 @@ POWERPC_PERF_START_COUNT(altivec_avg_pixels8_num, 1);
        pixels += line_size;
        block += line_size;
    }
-
-POWERPC_PERF_STOP_COUNT(altivec_avg_pixels8_num, 1);
 }
 
 /* next one assumes that ((line_size % 8) == 0) */
 static void put_pixels8_xy2_altivec(uint8_t *block, const uint8_t *pixels, int line_size, int h)
 {
-POWERPC_PERF_DECLARE(altivec_put_pixels8_xy2_num, 1);
     register int i;
     register vector unsigned char pixelsv1, pixelsv2, pixelsavg;
     register vector unsigned char blockv, temp1, temp2;
@@ -748,7 +735,6 @@ POWERPC_PERF_DECLARE(altivec_put_pixels8_xy2_num, 1);
                          (vector unsigned short)pixelsv2);
     pixelssum1 = vec_add(pixelssum1, vctwo);
 
-POWERPC_PERF_START_COUNT(altivec_put_pixels8_xy2_num, 1);
     for (i = 0; i < h ; i++) {
         int rightside = ((unsigned long)block & 0x0000000F);
         blockv = vec_ld(0, block);
@@ -782,14 +768,11 @@ POWERPC_PERF_START_COUNT(altivec_put_pixels8_xy2_num, 1);
         block += line_size;
         pixels += line_size;
     }
-
-POWERPC_PERF_STOP_COUNT(altivec_put_pixels8_xy2_num, 1);
 }
 
 /* next one assumes that ((line_size % 8) == 0) */
 static void put_no_rnd_pixels8_xy2_altivec(uint8_t *block, const uint8_t *pixels, int line_size, int h)
 {
-POWERPC_PERF_DECLARE(altivec_put_no_rnd_pixels8_xy2_num, 1);
     register int i;
     register vector unsigned char pixelsv1, pixelsv2, pixelsavg;
     register vector unsigned char blockv, temp1, temp2;
@@ -812,7 +795,6 @@ POWERPC_PERF_DECLARE(altivec_put_no_rnd_pixels8_xy2_num, 1);
                          (vector unsigned short)pixelsv2);
     pixelssum1 = vec_add(pixelssum1, vcone);
 
-POWERPC_PERF_START_COUNT(altivec_put_no_rnd_pixels8_xy2_num, 1);
     for (i = 0; i < h ; i++) {
         int rightside = ((unsigned long)block & 0x0000000F);
         blockv = vec_ld(0, block);
@@ -846,14 +828,11 @@ POWERPC_PERF_START_COUNT(altivec_put_no_rnd_pixels8_xy2_num, 1);
         block += line_size;
         pixels += line_size;
     }
-
-POWERPC_PERF_STOP_COUNT(altivec_put_no_rnd_pixels8_xy2_num, 1);
 }
 
 /* next one assumes that ((line_size % 16) == 0) */
 static void put_pixels16_xy2_altivec(uint8_t * block, const uint8_t * pixels, int line_size, int h)
 {
-POWERPC_PERF_DECLARE(altivec_put_pixels16_xy2_num, 1);
     register int i;
     register vector unsigned char pixelsv1, pixelsv2, pixelsv3, pixelsv4;
     register vector unsigned char blockv, temp1, temp2;
@@ -862,8 +841,6 @@ POWERPC_PERF_DECLARE(altivec_put_pixels16_xy2_num, 1);
     register const vector unsigned char vczero = (const vector unsigned char)vec_splat_u8(0);
     register const vector unsigned short vctwo = (const vector unsigned short)vec_splat_u16(2);
 
-POWERPC_PERF_START_COUNT(altivec_put_pixels16_xy2_num, 1);
-
     temp1 = vec_ld(0, pixels);
     temp2 = vec_ld(16, pixels);
     pixelsv1 = vec_perm(temp1, temp2, vec_lvsl(0, pixels));
@@ -919,14 +896,11 @@ POWERPC_PERF_START_COUNT(altivec_put_pixels16_xy2_num, 1);
         block += line_size;
         pixels += line_size;
     }
-
-POWERPC_PERF_STOP_COUNT(altivec_put_pixels16_xy2_num, 1);
 }
 
 /* next one assumes that ((line_size % 16) == 0) */
 static void put_no_rnd_pixels16_xy2_altivec(uint8_t * block, const uint8_t * pixels, int line_size, int h)
 {
-POWERPC_PERF_DECLARE(altivec_put_no_rnd_pixels16_xy2_num, 1);
     register int i;
     register vector unsigned char pixelsv1, pixelsv2, pixelsv3, pixelsv4;
     register vector unsigned char blockv, temp1, temp2;
@@ -936,8 +910,6 @@ POWERPC_PERF_DECLARE(altivec_put_no_rnd_pixels16_xy2_num, 1);
     register const vector unsigned short vcone = (const vector unsigned short)vec_splat_u16(1);
     register const vector unsigned short vctwo = (const vector unsigned short)vec_splat_u16(2);
 
-POWERPC_PERF_START_COUNT(altivec_put_no_rnd_pixels16_xy2_num, 1);
-
     temp1 = vec_ld(0, pixels);
     temp2 = vec_ld(16, pixels);
     pixelsv1 = vec_perm(temp1, temp2, vec_lvsl(0, pixels));
@@ -993,18 +965,14 @@ POWERPC_PERF_START_COUNT(altivec_put_no_rnd_pixels16_xy2_num, 1);
         block += line_size;
         pixels += line_size;
     }
-
-POWERPC_PERF_STOP_COUNT(altivec_put_no_rnd_pixels16_xy2_num, 1);
 }
 
 static int hadamard8_diff8x8_altivec(/*MpegEncContext*/ void *s, uint8_t *dst, uint8_t *src, int stride, int h){
-POWERPC_PERF_DECLARE(altivec_hadamard8_diff8x8_num, 1);
     int sum;
     register const vector unsigned char vzero =
                             (const vector unsigned char)vec_splat_u8(0);
     register vector signed short temp0, temp1, temp2, temp3, temp4,
                                  temp5, temp6, temp7;
-POWERPC_PERF_START_COUNT(altivec_hadamard8_diff8x8_num, 1);
     {
     register const vector signed short vprod1 =(const vector signed short)
                                                { 1,-1, 1,-1, 1,-1, 1,-1 };
@@ -1100,7 +1068,6 @@ POWERPC_PERF_START_COUNT(altivec_hadamard8_diff8x8_num, 1);
     vsum = vec_splat(vsum, 3);
     vec_ste(vsum, 0, &sum);
     }
-POWERPC_PERF_STOP_COUNT(altivec_hadamard8_diff8x8_num, 1);
     return sum;
 }
 
@@ -1319,16 +1286,13 @@ static int hadamard8_diff16x8_altivec(/*MpegEncContext*/ void *s, uint8_t *dst,
 }
 
 static int hadamard8_diff16_altivec(/*MpegEncContext*/ void *s, uint8_t *dst, uint8_t *src, int stride, int h){
-POWERPC_PERF_DECLARE(altivec_hadamard8_diff16_num, 1);
     int score;
-POWERPC_PERF_START_COUNT(altivec_hadamard8_diff16_num, 1);
     score = hadamard8_diff16x8_altivec(s, dst, src, stride, 8);
     if (h==16) {
         dst += 8*stride;
         src += 8*stride;
         score += hadamard8_diff16x8_altivec(s, dst, src, stride, 8);
     }
-POWERPC_PERF_STOP_COUNT(altivec_hadamard8_diff16_num, 1);
     return score;
 }
 
@@ -1358,7 +1322,6 @@ static void vorbis_inverse_coupling_altivec(float *mag, float *ang,
 /* next one assumes that ((line_size % 8) == 0) */
 static void avg_pixels8_xy2_altivec(uint8_t *block, const uint8_t *pixels, int line_size, int h)
 {
-POWERPC_PERF_DECLARE(altivec_avg_pixels8_xy2_num, 1);
     register int i;
     register vector unsigned char pixelsv1, pixelsv2, pixelsavg;
     register vector unsigned char blockv, temp1, temp2, blocktemp;
@@ -1383,7 +1346,6 @@ POWERPC_PERF_DECLARE(altivec_avg_pixels8_xy2_num, 1);
                          (vector unsigned short)pixelsv2);
     pixelssum1 = vec_add(pixelssum1, vctwo);
 
-POWERPC_PERF_START_COUNT(altivec_avg_pixels8_xy2_num, 1);
     for (i = 0; i < h ; i++) {
         int rightside = ((unsigned long)block & 0x0000000F);
         blockv = vec_ld(0, block);
@@ -1418,8 +1380,6 @@ POWERPC_PERF_START_COUNT(altivec_avg_pixels8_xy2_num, 1);
         block += line_size;
         pixels += line_size;
     }
-
-POWERPC_PERF_STOP_COUNT(altivec_avg_pixels8_xy2_num, 1);
 }
 
 void dsputil_init_altivec(DSPContext* c, AVCodecContext *avctx)
diff --git a/libavcodec/ppc/dsputil_altivec.h b/libavcodec/ppc/dsputil_altivec.h
index 18f8dd8..abf2dd3 100644
--- a/libavcodec/ppc/dsputil_altivec.h
+++ b/libavcodec/ppc/dsputil_altivec.h
@@ -3,20 +3,20 @@
  * Copyright (c) 2002 Dieter Shirley
  * Copyright (c) 2003-2004 Romain Dolbeau <romain at dolbeau.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -30,8 +30,6 @@ void put_pixels16_altivec(uint8_t *block, const uint8_t *pixels, int line_size,
 
 void avg_pixels16_altivec(uint8_t *block, const uint8_t *pixels, int line_size, int h);
 
-int has_altivec(void);
-
 void fdct_altivec(int16_t *block);
 void gmc1_altivec(uint8_t *dst, uint8_t *src, int stride, int h,
                   int x16, int y16, int rounder);
@@ -45,7 +43,6 @@ void ff_vp3_idct_add_altivec(uint8_t *dest, int line_size, DCTELEM *block);
 void dsputil_h264_init_ppc(DSPContext* c, AVCodecContext *avctx);
 
 void dsputil_init_altivec(DSPContext* c, AVCodecContext *avctx);
-void vc1dsp_init_altivec(DSPContext* c, AVCodecContext *avctx);
 void float_init_altivec(DSPContext* c, AVCodecContext *avctx);
 void int_init_altivec(DSPContext* c, AVCodecContext *avctx);
 
diff --git a/libavcodec/ppc/dsputil_ppc.c b/libavcodec/ppc/dsputil_ppc.c
index cf0ac39..c52ea61 100644
--- a/libavcodec/ppc/dsputil_ppc.c
+++ b/libavcodec/ppc/dsputil_ppc.c
@@ -3,99 +3,27 @@
  * Copyright (c) 2002 Dieter Shirley
  * Copyright (c) 2003-2004 Romain Dolbeau <romain at dolbeau.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/cpu.h"
 #include "libavcodec/dsputil.h"
-
-#include "dsputil_ppc.h"
-
 #include "dsputil_altivec.h"
 
-int mm_flags = 0;
-
-int mm_support(void)
-{
-    int result = 0;
-#if HAVE_ALTIVEC
-    if (has_altivec()) {
-        result |= FF_MM_ALTIVEC;
-    }
-#endif /* result */
-    return result;
-}
-
-#if CONFIG_POWERPC_PERF
-unsigned long long perfdata[POWERPC_NUM_PMC_ENABLED][powerpc_perf_total][powerpc_data_total];
-/* list below must match enum in dsputil_ppc.h */
-static unsigned char* perfname[] = {
-    "ff_fft_calc_altivec",
-    "gmc1_altivec",
-    "dct_unquantize_h263_altivec",
-    "fdct_altivec",
-    "idct_add_altivec",
-    "idct_put_altivec",
-    "put_pixels16_altivec",
-    "avg_pixels16_altivec",
-    "avg_pixels8_altivec",
-    "put_pixels8_xy2_altivec",
-    "put_no_rnd_pixels8_xy2_altivec",
-    "put_pixels16_xy2_altivec",
-    "put_no_rnd_pixels16_xy2_altivec",
-    "hadamard8_diff8x8_altivec",
-    "hadamard8_diff16_altivec",
-    "avg_pixels8_xy2_altivec",
-    "clear_blocks_dcbz32_ppc",
-    "clear_blocks_dcbz128_ppc",
-    "put_h264_chroma_mc8_altivec",
-    "avg_h264_chroma_mc8_altivec",
-    "put_h264_qpel16_h_lowpass_altivec",
-    "avg_h264_qpel16_h_lowpass_altivec",
-    "put_h264_qpel16_v_lowpass_altivec",
-    "avg_h264_qpel16_v_lowpass_altivec",
-    "put_h264_qpel16_hv_lowpass_altivec",
-    "avg_h264_qpel16_hv_lowpass_altivec",
-    ""
-};
-#include <stdio.h>
-#endif
-
-#if CONFIG_POWERPC_PERF
-void powerpc_display_perf_report(void)
-{
-    int i, j;
-    av_log(NULL, AV_LOG_INFO, "PowerPC performance report\n Values are from the PMC registers, and represent whatever the registers are set to record.\n");
-    for(i = 0 ; i < powerpc_perf_total ; i++) {
-        for (j = 0; j < POWERPC_NUM_PMC_ENABLED ; j++) {
-            if (perfdata[j][i][powerpc_data_num] != (unsigned long long)0)
-                av_log(NULL, AV_LOG_INFO,
-                       " Function \"%s\" (pmc%d):\n\tmin: %"PRIu64"\n\tmax: %"PRIu64"\n\tavg: %1.2lf (%"PRIu64")\n",
-                       perfname[i],
-                       j+1,
-                       perfdata[j][i][powerpc_data_min],
-                       perfdata[j][i][powerpc_data_max],
-                       (double)perfdata[j][i][powerpc_data_sum] /
-                       (double)perfdata[j][i][powerpc_data_num],
-                       perfdata[j][i][powerpc_data_num]);
-        }
-    }
-}
-#endif /* CONFIG_POWERPC_PERF */
-
 /* ***** WARNING ***** WARNING ***** WARNING ***** */
 /*
 clear_blocks_dcbz32_ppc will not work properly on PowerPC processors with a
@@ -118,10 +46,8 @@ and <http://developer.apple.com/technotes/tn/tn2086.html>
 */
 static void clear_blocks_dcbz32_ppc(DCTELEM *blocks)
 {
-POWERPC_PERF_DECLARE(powerpc_clear_blocks_dcbz32, 1);
     register int misal = ((unsigned long)blocks & 0x00000010);
     register int i = 0;
-POWERPC_PERF_START_COUNT(powerpc_clear_blocks_dcbz32, 1);
 #if 1
     if (misal) {
         ((unsigned long*)blocks)[0] = 0L;
@@ -143,7 +69,6 @@ POWERPC_PERF_START_COUNT(powerpc_clear_blocks_dcbz32, 1);
 #else
     memset(blocks, 0, sizeof(DCTELEM)*6*64);
 #endif
-POWERPC_PERF_STOP_COUNT(powerpc_clear_blocks_dcbz32, 1);
 }
 
 /* same as above, when dcbzl clear a whole 128B cache line
@@ -151,10 +76,8 @@ POWERPC_PERF_STOP_COUNT(powerpc_clear_blocks_dcbz32, 1);
 #if HAVE_DCBZL
 static void clear_blocks_dcbz128_ppc(DCTELEM *blocks)
 {
-POWERPC_PERF_DECLARE(powerpc_clear_blocks_dcbz128, 1);
     register int misal = ((unsigned long)blocks & 0x0000007f);
     register int i = 0;
-POWERPC_PERF_START_COUNT(powerpc_clear_blocks_dcbz128, 1);
 #if 1
     if (misal) {
         // we could probably also optimize this case,
@@ -169,7 +92,6 @@ POWERPC_PERF_START_COUNT(powerpc_clear_blocks_dcbz128, 1);
 #else
     memset(blocks, 0, sizeof(DCTELEM)*6*64);
 #endif
-POWERPC_PERF_STOP_COUNT(powerpc_clear_blocks_dcbz128, 1);
 }
 #else
 static void clear_blocks_dcbz128_ppc(DCTELEM *blocks)
@@ -247,12 +169,8 @@ void dsputil_init_ppc(DSPContext* c, AVCodecContext *avctx)
 #if HAVE_ALTIVEC
     if(CONFIG_H264_DECODER) dsputil_h264_init_ppc(c, avctx);
 
-    if (has_altivec()) {
-        mm_flags |= FF_MM_ALTIVEC;
-
+    if (av_get_cpu_flags() & AV_CPU_FLAG_ALTIVEC) {
         dsputil_init_altivec(c, avctx);
-        if(CONFIG_VC1_DECODER)
-            vc1dsp_init_altivec(c, avctx);
         float_init_altivec(c, avctx);
         int_init_altivec(c, avctx);
         c->gmc1 = gmc1_altivec;
@@ -279,19 +197,6 @@ void dsputil_init_ppc(DSPContext* c, AVCodecContext *avctx)
             }
         }
 
-#if CONFIG_POWERPC_PERF
-        {
-            int i, j;
-            for (i = 0 ; i < powerpc_perf_total ; i++) {
-                for (j = 0; j < POWERPC_NUM_PMC_ENABLED ; j++) {
-                    perfdata[j][i][powerpc_data_min] = 0xFFFFFFFFFFFFFFFFULL;
-                    perfdata[j][i][powerpc_data_max] = 0x0000000000000000ULL;
-                    perfdata[j][i][powerpc_data_sum] = 0x0000000000000000ULL;
-                    perfdata[j][i][powerpc_data_num] = 0x0000000000000000ULL;
-                }
-            }
-        }
-#endif /* CONFIG_POWERPC_PERF */
     }
 #endif /* HAVE_ALTIVEC */
 }
diff --git a/libavcodec/ppc/dsputil_ppc.h b/libavcodec/ppc/dsputil_ppc.h
deleted file mode 100644
index d028574..0000000
--- a/libavcodec/ppc/dsputil_ppc.h
+++ /dev/null
@@ -1,154 +0,0 @@
-/*
- * Copyright (c) 2003-2004 Romain Dolbeau <romain at dolbeau.org>
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-#ifndef AVCODEC_PPC_DSPUTIL_PPC_H
-#define AVCODEC_PPC_DSPUTIL_PPC_H
-
-#include "config.h"
-
-#if CONFIG_POWERPC_PERF
-void powerpc_display_perf_report(void);
-/* the 604* have 2, the G3* have 4, the G4s have 6,
-   and the G5 are completely different (they MUST use
-   ARCH_PPC64, and let's hope all future 64 bis PPC
-   will use the same PMCs... */
-#define POWERPC_NUM_PMC_ENABLED 6
-/* if you add to the enum below, also add to the perfname array
-   in dsputil_ppc.c */
-enum powerpc_perf_index {
-    altivec_fft_num = 0,
-    altivec_gmc1_num,
-    altivec_dct_unquantize_h263_num,
-    altivec_fdct,
-    altivec_idct_add_num,
-    altivec_idct_put_num,
-    altivec_put_pixels16_num,
-    altivec_avg_pixels16_num,
-    altivec_avg_pixels8_num,
-    altivec_put_pixels8_xy2_num,
-    altivec_put_no_rnd_pixels8_xy2_num,
-    altivec_put_pixels16_xy2_num,
-    altivec_put_no_rnd_pixels16_xy2_num,
-    altivec_hadamard8_diff8x8_num,
-    altivec_hadamard8_diff16_num,
-    altivec_avg_pixels8_xy2_num,
-    powerpc_clear_blocks_dcbz32,
-    powerpc_clear_blocks_dcbz128,
-    altivec_put_h264_chroma_mc8_num,
-    altivec_avg_h264_chroma_mc8_num,
-    altivec_put_h264_qpel16_h_lowpass_num,
-    altivec_avg_h264_qpel16_h_lowpass_num,
-    altivec_put_h264_qpel16_v_lowpass_num,
-    altivec_avg_h264_qpel16_v_lowpass_num,
-    altivec_put_h264_qpel16_hv_lowpass_num,
-    altivec_avg_h264_qpel16_hv_lowpass_num,
-    powerpc_perf_total
-};
-enum powerpc_data_index {
-    powerpc_data_min = 0,
-    powerpc_data_max,
-    powerpc_data_sum,
-    powerpc_data_num,
-    powerpc_data_total
-};
-extern unsigned long long perfdata[POWERPC_NUM_PMC_ENABLED][powerpc_perf_total][powerpc_data_total];
-
-#if !ARCH_PPC64
-#define POWERP_PMC_DATATYPE unsigned long
-#define POWERPC_GET_PMC1(a) __asm__ volatile("mfspr %0, 937" : "=r" (a))
-#define POWERPC_GET_PMC2(a) __asm__ volatile("mfspr %0, 938" : "=r" (a))
-#if (POWERPC_NUM_PMC_ENABLED > 2)
-#define POWERPC_GET_PMC3(a) __asm__ volatile("mfspr %0, 941" : "=r" (a))
-#define POWERPC_GET_PMC4(a) __asm__ volatile("mfspr %0, 942" : "=r" (a))
-#else
-#define POWERPC_GET_PMC3(a) do {} while (0)
-#define POWERPC_GET_PMC4(a) do {} while (0)
-#endif
-#if (POWERPC_NUM_PMC_ENABLED > 4)
-#define POWERPC_GET_PMC5(a) __asm__ volatile("mfspr %0, 929" : "=r" (a))
-#define POWERPC_GET_PMC6(a) __asm__ volatile("mfspr %0, 930" : "=r" (a))
-#else
-#define POWERPC_GET_PMC5(a) do {} while (0)
-#define POWERPC_GET_PMC6(a) do {} while (0)
-#endif
-#else /* ARCH_PPC64 */
-#define POWERP_PMC_DATATYPE unsigned long long
-#define POWERPC_GET_PMC1(a) __asm__ volatile("mfspr %0, 771" : "=r" (a))
-#define POWERPC_GET_PMC2(a) __asm__ volatile("mfspr %0, 772" : "=r" (a))
-#if (POWERPC_NUM_PMC_ENABLED > 2)
-#define POWERPC_GET_PMC3(a) __asm__ volatile("mfspr %0, 773" : "=r" (a))
-#define POWERPC_GET_PMC4(a) __asm__ volatile("mfspr %0, 774" : "=r" (a))
-#else
-#define POWERPC_GET_PMC3(a) do {} while (0)
-#define POWERPC_GET_PMC4(a) do {} while (0)
-#endif
-#if (POWERPC_NUM_PMC_ENABLED > 4)
-#define POWERPC_GET_PMC5(a) __asm__ volatile("mfspr %0, 775" : "=r" (a))
-#define POWERPC_GET_PMC6(a) __asm__ volatile("mfspr %0, 776" : "=r" (a))
-#else
-#define POWERPC_GET_PMC5(a) do {} while (0)
-#define POWERPC_GET_PMC6(a) do {} while (0)
-#endif
-#endif /* ARCH_PPC64 */
-#define POWERPC_PERF_DECLARE(a, cond)       \
-    POWERP_PMC_DATATYPE                     \
-        pmc_start[POWERPC_NUM_PMC_ENABLED], \
-        pmc_stop[POWERPC_NUM_PMC_ENABLED],  \
-        pmc_loop_index;
-#define POWERPC_PERF_START_COUNT(a, cond) do { \
-    POWERPC_GET_PMC6(pmc_start[5]); \
-    POWERPC_GET_PMC5(pmc_start[4]); \
-    POWERPC_GET_PMC4(pmc_start[3]); \
-    POWERPC_GET_PMC3(pmc_start[2]); \
-    POWERPC_GET_PMC2(pmc_start[1]); \
-    POWERPC_GET_PMC1(pmc_start[0]); \
-    } while (0)
-#define POWERPC_PERF_STOP_COUNT(a, cond) do { \
-    POWERPC_GET_PMC1(pmc_stop[0]);            \
-    POWERPC_GET_PMC2(pmc_stop[1]);            \
-    POWERPC_GET_PMC3(pmc_stop[2]);            \
-    POWERPC_GET_PMC4(pmc_stop[3]);            \
-    POWERPC_GET_PMC5(pmc_stop[4]);            \
-    POWERPC_GET_PMC6(pmc_stop[5]);            \
-    if (cond) {                               \
-        for(pmc_loop_index = 0;               \
-            pmc_loop_index < POWERPC_NUM_PMC_ENABLED; \
-            pmc_loop_index++) {               \
-            if (pmc_stop[pmc_loop_index] >= pmc_start[pmc_loop_index]) {  \
-                POWERP_PMC_DATATYPE diff =                                \
-                  pmc_stop[pmc_loop_index] - pmc_start[pmc_loop_index];   \
-                if (diff < perfdata[pmc_loop_index][a][powerpc_data_min]) \
-                    perfdata[pmc_loop_index][a][powerpc_data_min] = diff; \
-                if (diff > perfdata[pmc_loop_index][a][powerpc_data_max]) \
-                    perfdata[pmc_loop_index][a][powerpc_data_max] = diff; \
-                perfdata[pmc_loop_index][a][powerpc_data_sum] += diff;    \
-                perfdata[pmc_loop_index][a][powerpc_data_num] ++;         \
-            }                                 \
-        }                                     \
-    }                                         \
-} while (0)
-#else /* CONFIG_POWERPC_PERF */
-// those are needed to avoid empty statements.
-#define POWERPC_PERF_DECLARE(a, cond)        int altivec_placeholder __attribute__ ((unused))
-#define POWERPC_PERF_START_COUNT(a, cond)    do {} while (0)
-#define POWERPC_PERF_STOP_COUNT(a, cond)     do {} while (0)
-#endif /* CONFIG_POWERPC_PERF */
-
-#endif /*  AVCODEC_PPC_DSPUTIL_PPC_H */
diff --git a/libavcodec/ppc/fdct_altivec.c b/libavcodec/ppc/fdct_altivec.c
index 8f3bc26..8dbfe33 100644
--- a/libavcodec/ppc/fdct_altivec.c
+++ b/libavcodec/ppc/fdct_altivec.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (C) 2003  James Klicman <james at klicman.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -24,7 +24,6 @@
 #endif
 #include "libavutil/common.h"
 #include "libavcodec/dsputil.h"
-#include "dsputil_ppc.h"
 #include "dsputil_altivec.h"
 
 #define vs16(v) ((vector signed short)(v))
@@ -198,7 +197,6 @@ static vector float fdctconsts[3] = {
 
 void fdct_altivec(int16_t *block)
 {
-POWERPC_PERF_DECLARE(altivec_fdct, 1);
     vector signed short *bp;
     vector float *cp;
     vector float b00, b10, b20, b30, b40, b50, b60, b70;
@@ -206,9 +204,6 @@ POWERPC_PERF_DECLARE(altivec_fdct, 1);
     vector float mzero, cnst, cnsts0, cnsts1, cnsts2;
     vector float x0, x1, x2, x3, x4, x5, x6, x7, x8;
 
-    POWERPC_PERF_START_COUNT(altivec_fdct, 1);
-
-
     /* setup constants {{{ */
     /* mzero = -0.0 */
     mzero = ((vector float)vec_splat_u32(-1));
@@ -487,8 +482,6 @@ POWERPC_PERF_DECLARE(altivec_fdct, 1);
 
 #undef CTS
     /* }}} */
-
-POWERPC_PERF_STOP_COUNT(altivec_fdct, 1);
 }
 
 /* vim:set foldmethod=marker foldlevel=0: */
diff --git a/libavcodec/ppc/fft_altivec.c b/libavcodec/ppc/fft_altivec.c
index ce35ab6..435024a 100644
--- a/libavcodec/ppc/fft_altivec.c
+++ b/libavcodec/ppc/fft_altivec.c
@@ -1,29 +1,27 @@
 /*
  * FFT/IFFT transforms
  * AltiVec-enabled
- * Copyright (c) 2003 Romain Dolbeau <romain at dolbeau.org>
- * Based on code Copyright (c) 2002 Fabrice Bellard
+ * Copyright (c) 2009 Loren Merritt
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #include "libavcodec/fft.h"
-#include "dsputil_ppc.h"
 #include "util_altivec.h"
-#include "dsputil_altivec.h"
+#include "types_altivec.h"
 
 /**
  * Do a complex FFT with the parameters defined in ff_fft_init(). The
@@ -32,112 +30,118 @@
  * AltiVec-enabled
  * This code assumes that the 'z' pointer is 16 bytes-aligned
  * It also assumes all FFTComplex are 8 bytes-aligned pair of float
- * The code is exactly the same as the SSE version, except
- * that successive MUL + ADD/SUB have been merged into
- * fused multiply-add ('vec_madd' in altivec)
  */
-static void ff_fft_calc_altivec(FFTContext *s, FFTComplex *z)
-{
-POWERPC_PERF_DECLARE(altivec_fft_num, s->nbits >= 6);
-    register const vector float vczero = (const vector float)vec_splat_u32(0.);
-
-    int ln = s->nbits;
-    int j, np, np2;
-    int nblocks, nloops;
-    register FFTComplex *p, *q;
-    FFTComplex *cptr, *cptr1;
-    int k;
-
-POWERPC_PERF_START_COUNT(altivec_fft_num, s->nbits >= 6);
-
-    np = 1 << ln;
-
-    {
-        vector float *r, a, b, a1, c1, c2;
-
-        r = (vector float *)&z[0];
 
-        c1 = vcii(p,p,n,n);
+void ff_fft_calc_altivec(FFTContext *s, FFTComplex *z);
+void ff_fft_calc_interleave_altivec(FFTContext *s, FFTComplex *z);
 
-        if (s->inverse) {
-            c2 = vcii(p,p,n,p);
-        } else {
-            c2 = vcii(p,p,p,n);
-        }
-
-        j = (np >> 2);
-        do {
-            a = vec_ld(0, r);
-            a1 = vec_ld(sizeof(vector float), r);
-
-            b = vec_perm(a,a,vcprmle(1,0,3,2));
-            a = vec_madd(a,c1,b);
-            /* do the pass 0 butterfly */
-
-            b = vec_perm(a1,a1,vcprmle(1,0,3,2));
-            b = vec_madd(a1,c1,b);
-            /* do the pass 0 butterfly */
-
-            /* multiply third by -i */
-            b = vec_perm(b,b,vcprmle(2,3,1,0));
-
-            /* do the pass 1 butterfly */
-            vec_st(vec_madd(b,c2,a), 0, r);
-            vec_st(vec_nmsub(b,c2,a), sizeof(vector float), r);
-
-            r += 2;
-        } while (--j != 0);
-    }
-    /* pass 2 .. ln-1 */
-
-    nblocks = np >> 3;
-    nloops = 1 << 2;
-    np2 = np >> 1;
-
-    cptr1 = s->exptab1;
+#if HAVE_GNU_AS
+static void ff_imdct_half_altivec(FFTContext *s, FFTSample *output, const FFTSample *input)
+{
+    int j, k;
+    int n = 1 << s->mdct_bits;
+    int n4 = n >> 2;
+    int n8 = n >> 3;
+    int n32 = n >> 5;
+    const uint16_t *revtabj = s->revtab;
+    const uint16_t *revtabk = s->revtab+n4;
+    const vec_f *tcos = (const vec_f*)(s->tcos+n8);
+    const vec_f *tsin = (const vec_f*)(s->tsin+n8);
+    const vec_f *pin = (const vec_f*)(input+n4);
+    vec_f *pout = (vec_f*)(output+n4);
+
+    /* pre rotation */
+    k = n32-1;
     do {
-        p = z;
-        q = z + nloops;
-        j = nblocks;
-        do {
-            cptr = cptr1;
-            k = nloops >> 1;
-            do {
-                vector float a,b,c,t1;
-
-                a = vec_ld(0, (float*)p);
-                b = vec_ld(0, (float*)q);
-
-                /* complex mul */
-                c = vec_ld(0, (float*)cptr);
-                /*  cre*re cim*re */
-                t1 = vec_madd(c, vec_perm(b,b,vcprmle(2,2,0,0)),vczero);
-                c = vec_ld(sizeof(vector float), (float*)cptr);
-                /*  -cim*im cre*im */
-                b = vec_madd(c, vec_perm(b,b,vcprmle(3,3,1,1)),t1);
-
-                /* butterfly */
-                vec_st(vec_add(a,b), 0, (float*)p);
-                vec_st(vec_sub(a,b), 0, (float*)q);
-
-                p += 2;
-                q += 2;
-                cptr += 4;
-            } while (--k);
-
-            p += nloops;
-            q += nloops;
-        } while (--j);
-        cptr1 += nloops * 2;
-        nblocks = nblocks >> 1;
-        nloops = nloops << 1;
-    } while (nblocks != 0);
+        vec_f cos,sin,cos0,sin0,cos1,sin1,re,im,r0,i0,r1,i1,a,b,c,d;
+#define CMULA(p,o0,o1,o2,o3)\
+        a = pin[ k*2+p];                       /* { z[k].re,    z[k].im,    z[k+1].re,  z[k+1].im  } */\
+        b = pin[-k*2-p-1];                     /* { z[-k-2].re, z[-k-2].im, z[-k-1].re, z[-k-1].im } */\
+        re = vec_perm(a, b, vcprm(0,2,s0,s2)); /* { z[k].re,    z[k+1].re,  z[-k-2].re, z[-k-1].re } */\
+        im = vec_perm(a, b, vcprm(s3,s1,3,1)); /* { z[-k-1].im, z[-k-2].im, z[k+1].im,  z[k].im    } */\
+        cos = vec_perm(cos0, cos1, vcprm(o0,o1,s##o2,s##o3)); /* { cos[k], cos[k+1], cos[-k-2], cos[-k-1] } */\
+        sin = vec_perm(sin0, sin1, vcprm(o0,o1,s##o2,s##o3));\
+        r##p = im*cos - re*sin;\
+        i##p = re*cos + im*sin;
+#define STORE2(v,dst)\
+        j = dst;\
+        vec_ste(v, 0, output+j*2);\
+        vec_ste(v, 4, output+j*2);
+#define STORE8(p)\
+        a = vec_perm(r##p, i##p, vcprm(0,s0,0,s0));\
+        b = vec_perm(r##p, i##p, vcprm(1,s1,1,s1));\
+        c = vec_perm(r##p, i##p, vcprm(2,s2,2,s2));\
+        d = vec_perm(r##p, i##p, vcprm(3,s3,3,s3));\
+        STORE2(a, revtabk[ p*2-4]);\
+        STORE2(b, revtabk[ p*2-3]);\
+        STORE2(c, revtabj[-p*2+2]);\
+        STORE2(d, revtabj[-p*2+3]);
+
+        cos0 = tcos[k];
+        sin0 = tsin[k];
+        cos1 = tcos[-k-1];
+        sin1 = tsin[-k-1];
+        CMULA(0, 0,1,2,3);
+        CMULA(1, 2,3,0,1);
+        STORE8(0);
+        STORE8(1);
+        revtabj += 4;
+        revtabk -= 4;
+        k--;
+    } while(k >= 0);
+
+    ff_fft_calc_altivec(s, (FFTComplex*)output);
+
+    /* post rotation + reordering */
+    j = -n32;
+    k = n32-1;
+    do {
+        vec_f cos,sin,re,im,a,b,c,d;
+#define CMULB(d0,d1,o)\
+        re = pout[o*2];\
+        im = pout[o*2+1];\
+        cos = tcos[o];\
+        sin = tsin[o];\
+        d0 = im*sin - re*cos;\
+        d1 = re*sin + im*cos;
+
+        CMULB(a,b,j);
+        CMULB(c,d,k);
+        pout[2*j]   = vec_perm(a, d, vcprm(0,s3,1,s2));
+        pout[2*j+1] = vec_perm(a, d, vcprm(2,s1,3,s0));
+        pout[2*k]   = vec_perm(c, b, vcprm(0,s3,1,s2));
+        pout[2*k+1] = vec_perm(c, b, vcprm(2,s1,3,s0));
+        j++;
+        k--;
+    } while(k >= 0);
+}
 
-POWERPC_PERF_STOP_COUNT(altivec_fft_num, s->nbits >= 6);
+static void ff_imdct_calc_altivec(FFTContext *s, FFTSample *output, const FFTSample *input)
+{
+    int k;
+    int n = 1 << s->mdct_bits;
+    int n4 = n >> 2;
+    int n16 = n >> 4;
+    vec_u32 sign = {1U<<31,1U<<31,1U<<31,1U<<31};
+    vec_u32 *p0 = (vec_u32*)(output+n4);
+    vec_u32 *p1 = (vec_u32*)(output+n4*3);
+
+    ff_imdct_half_altivec(s, output+n4, input);
+
+    for (k = 0; k < n16; k++) {
+        vec_u32 a = p0[k] ^ sign;
+        vec_u32 b = p1[-k-1];
+        p0[-k-1] = vec_perm(a, a, vcprm(3,2,1,0));
+        p1[k]    = vec_perm(b, b, vcprm(3,2,1,0));
+    }
 }
+#endif /* HAVE_GNU_AS */
 
 av_cold void ff_fft_init_altivec(FFTContext *s)
 {
-    s->fft_calc = ff_fft_calc_altivec;
-    s->split_radix = 0;
+#if HAVE_GNU_AS
+    s->fft_calc   = ff_fft_calc_interleave_altivec;
+    s->imdct_calc = ff_imdct_calc_altivec;
+    s->imdct_half = ff_imdct_half_altivec;
+#endif
 }
diff --git a/libavcodec/ppc/fft_altivec_s.S b/libavcodec/ppc/fft_altivec_s.S
new file mode 100644
index 0000000..ab33900
--- /dev/null
+++ b/libavcodec/ppc/fft_altivec_s.S
@@ -0,0 +1,448 @@
+/*
+ * FFT transform with Altivec optimizations
+ * Copyright (c) 2009 Loren Merritt
+ *
+ * This algorithm (though not any of the implementation details) is
+ * based on libdjbfft by D. J. Bernstein.
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/*
+ * These functions are not individually interchangeable with the C versions.
+ * While C takes arrays of FFTComplex, Altivec leaves intermediate results
+ * in blocks as convenient to the vector size.
+ * i.e. {4x real, 4x imaginary, 4x real, ...}
+ *
+ * I ignore standard calling convention.
+ * Instead, the following registers are treated as global constants:
+ * v14: zero
+ * v15..v18: cosines
+ * v19..v29: permutations
+ * r9: 16
+ * r12: ff_cos_tabs
+ * and the rest are free for local use.
+ */
+
+#include "config.h"
+#include "asm.S"
+
+.text
+
+.macro addi2 ra, imm // add 32-bit immediate
+.if \imm & 0xffff
+    addi \ra, \ra, \imm at l
+.endif
+.if (\imm+0x8000)>>16
+    addis \ra, \ra, \imm at ha
+.endif
+.endm
+
+.macro FFT4 a0, a1, a2, a3 // in:0-1 out:2-3
+    vperm   \a2,\a0,\a1,v20 // vcprm(0,1,s2,s1) // {r0,i0,r3,i2}
+    vperm   \a3,\a0,\a1,v21 // vcprm(2,3,s0,s3) // {r1,i1,r2,i3}
+    vaddfp  \a0,\a2,\a3                         // {t1,t2,t6,t5}
+    vsubfp  \a1,\a2,\a3                         // {t3,t4,t8,t7}
+    vmrghw  \a2,\a0,\a1     // vcprm(0,s0,1,s1) // {t1,t3,t2,t4}
+    vperm   \a3,\a0,\a1,v22 // vcprm(2,s3,3,s2) // {t6,t7,t5,t8}
+    vaddfp  \a0,\a2,\a3                         // {r0,r1,i0,i1}
+    vsubfp  \a1,\a2,\a3                         // {r2,r3,i2,i3}
+    vperm   \a2,\a0,\a1,v23 // vcprm(0,1,s0,s1) // {r0,r1,r2,r3}
+    vperm   \a3,\a0,\a1,v24 // vcprm(2,3,s2,s3) // {i0,i1,i2,i3}
+.endm
+
+.macro FFT4x2 a0, a1, b0, b1, a2, a3, b2, b3
+    vperm   \a2,\a0,\a1,v20 // vcprm(0,1,s2,s1) // {r0,i0,r3,i2}
+    vperm   \a3,\a0,\a1,v21 // vcprm(2,3,s0,s3) // {r1,i1,r2,i3}
+    vperm   \b2,\b0,\b1,v20
+    vperm   \b3,\b0,\b1,v21
+    vaddfp  \a0,\a2,\a3                         // {t1,t2,t6,t5}
+    vsubfp  \a1,\a2,\a3                         // {t3,t4,t8,t7}
+    vaddfp  \b0,\b2,\b3
+    vsubfp  \b1,\b2,\b3
+    vmrghw  \a2,\a0,\a1     // vcprm(0,s0,1,s1) // {t1,t3,t2,t4}
+    vperm   \a3,\a0,\a1,v22 // vcprm(2,s3,3,s2) // {t6,t7,t5,t8}
+    vmrghw  \b2,\b0,\b1
+    vperm   \b3,\b0,\b1,v22
+    vaddfp  \a0,\a2,\a3                         // {r0,r1,i0,i1}
+    vsubfp  \a1,\a2,\a3                         // {r2,r3,i2,i3}
+    vaddfp  \b0,\b2,\b3
+    vsubfp  \b1,\b2,\b3
+    vperm   \a2,\a0,\a1,v23 // vcprm(0,1,s0,s1) // {r0,r1,r2,r3}
+    vperm   \a3,\a0,\a1,v24 // vcprm(2,3,s2,s3) // {i0,i1,i2,i3}
+    vperm   \b2,\b0,\b1,v23
+    vperm   \b3,\b0,\b1,v24
+.endm
+
+.macro FFT8 a0, a1, b0, b1, a2, a3, b2, b3, b4 // in,out:a0-b1
+    vmrghw  \b2,\b0,\b1     // vcprm(0,s0,1,s1) // {r4,r6,i4,i6}
+    vmrglw  \b3,\b0,\b1     // vcprm(2,s2,3,s3) // {r5,r7,i5,i7}
+    vperm   \a2,\a0,\a1,v20         // FFT4 ...
+    vperm   \a3,\a0,\a1,v21
+    vaddfp  \b0,\b2,\b3                         // {t1,t3,t2,t4}
+    vsubfp  \b1,\b2,\b3                         // {r5,r7,i5,i7}
+    vperm   \b4,\b1,\b1,v25 // vcprm(2,3,0,1)   // {i5,i7,r5,r7}
+    vaddfp  \a0,\a2,\a3
+    vsubfp  \a1,\a2,\a3
+    vmaddfp \b1,\b1,v17,v14 // * {-1,1,1,-1}/sqrt(2)
+    vmaddfp \b1,\b4,v18,\b1 // * { 1,1,1,1 }/sqrt(2) // {t8,ta,t7,t9}
+    vmrghw  \a2,\a0,\a1
+    vperm   \a3,\a0,\a1,v22
+    vperm   \b2,\b0,\b1,v26 // vcprm(1,2,s3,s0) // {t3,t2,t9,t8}
+    vperm   \b3,\b0,\b1,v27 // vcprm(0,3,s2,s1) // {t1,t4,t7,ta}
+    vaddfp  \a0,\a2,\a3
+    vsubfp  \a1,\a2,\a3
+    vaddfp  \b0,\b2,\b3                         // {t1,t2,t9,ta}
+    vsubfp  \b1,\b2,\b3                         // {t6,t5,tc,tb}
+    vperm   \a2,\a0,\a1,v23
+    vperm   \a3,\a0,\a1,v24
+    vperm   \b2,\b0,\b1,v28 // vcprm(0,2,s1,s3) // {t1,t9,t5,tb}
+    vperm   \b3,\b0,\b1,v29 // vcprm(1,3,s0,s2) // {t2,ta,t6,tc}
+    vsubfp  \b0,\a2,\b2                         // {r4,r5,r6,r7}
+    vsubfp  \b1,\a3,\b3                         // {i4,i5,i6,i7}
+    vaddfp  \a0,\a2,\b2                         // {r0,r1,r2,r3}
+    vaddfp  \a1,\a3,\b3                         // {i0,i1,i2,i3}
+.endm
+
+.macro BF d0,d1,s0,s1
+    vsubfp  \d1,\s0,\s1
+    vaddfp  \d0,\s0,\s1
+.endm
+
+.macro zip d0,d1,s0,s1
+    vmrghw  \d0,\s0,\s1
+    vmrglw  \d1,\s0,\s1
+.endm
+
+.macro def_fft4 interleave
+fft4\interleave\()_altivec:
+    lvx    v0, 0,r3
+    lvx    v1,r9,r3
+    FFT4   v0,v1,v2,v3
+.ifnb \interleave
+    zip    v0,v1,v2,v3
+    stvx   v0, 0,r3
+    stvx   v1,r9,r3
+.else
+    stvx   v2, 0,r3
+    stvx   v3,r9,r3
+.endif
+    blr
+.endm
+
+.macro def_fft8 interleave
+fft8\interleave\()_altivec:
+    addi   r4,r3,32
+    lvx    v0, 0,r3
+    lvx    v1,r9,r3
+    lvx    v2, 0,r4
+    lvx    v3,r9,r4
+    FFT8   v0,v1,v2,v3,v4,v5,v6,v7,v8
+.ifnb \interleave
+    zip    v4,v5,v0,v1
+    zip    v6,v7,v2,v3
+    stvx   v4, 0,r3
+    stvx   v5,r9,r3
+    stvx   v6, 0,r4
+    stvx   v7,r9,r4
+.else
+    stvx   v0, 0,r3
+    stvx   v1,r9,r3
+    stvx   v2, 0,r4
+    stvx   v3,r9,r4
+.endif
+    blr
+.endm
+
+.macro def_fft16 interleave
+fft16\interleave\()_altivec:
+    addi   r5,r3,64
+    addi   r6,r3,96
+    addi   r4,r3,32
+    lvx    v0, 0,r5
+    lvx    v1,r9,r5
+    lvx    v2, 0,r6
+    lvx    v3,r9,r6
+    FFT4x2 v0,v1,v2,v3,v4,v5,v6,v7
+    lvx    v0, 0,r3
+    lvx    v1,r9,r3
+    lvx    v2, 0,r4
+    lvx    v3,r9,r4
+    FFT8   v0,v1,v2,v3,v8,v9,v10,v11,v12
+    vmaddfp   v8,v4,v15,v14 // r2*wre
+    vmaddfp   v9,v5,v15,v14 // i2*wre
+    vmaddfp  v10,v6,v15,v14 // r3*wre
+    vmaddfp  v11,v7,v15,v14 // i3*wre
+    vmaddfp   v8,v5,v16,v8  // i2*wim
+    vnmsubfp  v9,v4,v16,v9  // r2*wim
+    vnmsubfp v10,v7,v16,v10 // i3*wim
+    vmaddfp  v11,v6,v16,v11 // r3*wim
+    BF     v10,v12,v10,v8
+    BF     v11,v13,v9,v11
+    BF     v0,v4,v0,v10
+    BF     v3,v7,v3,v12
+    BF     v1,v5,v1,v11
+    BF     v2,v6,v2,v13
+.ifnb \interleave
+    zip     v8, v9,v0,v1
+    zip    v10,v11,v2,v3
+    zip    v12,v13,v4,v5
+    zip    v14,v15,v6,v7
+    stvx    v8, 0,r3
+    stvx    v9,r9,r3
+    stvx   v10, 0,r4
+    stvx   v11,r9,r4
+    stvx   v12, 0,r5
+    stvx   v13,r9,r5
+    stvx   v14, 0,r6
+    stvx   v15,r9,r6
+.else
+    stvx   v0, 0,r3
+    stvx   v4, 0,r5
+    stvx   v3,r9,r4
+    stvx   v7,r9,r6
+    stvx   v1,r9,r3
+    stvx   v5,r9,r5
+    stvx   v2, 0,r4
+    stvx   v6, 0,r6
+.endif
+    blr
+.endm
+
+// void pass(float *z, float *wre, int n)
+.macro PASS interleave, suffix
+fft_pass\suffix\()_altivec:
+    mtctr  r5
+    slwi   r0,r5,4
+    slwi   r7,r5,6   // o2
+    slwi   r5,r5,5   // o1
+    add   r10,r5,r7  // o3
+    add    r0,r4,r0  // wim
+    addi   r6,r5,16  // o1+16
+    addi   r8,r7,16  // o2+16
+    addi  r11,r10,16 // o3+16
+1:
+    lvx    v8, 0,r4  // wre
+    lvx   v10, 0,r0  // wim
+    sub    r0,r0,r9
+    lvx    v9, 0,r0
+    vperm  v9,v9,v10,v19   // vcprm(s0,3,2,1) => wim[0 .. -3]
+    lvx    v4,r3,r7        // r2 = z[o2]
+    lvx    v5,r3,r8        // i2 = z[o2+16]
+    lvx    v6,r3,r10       // r3 = z[o3]
+    lvx    v7,r3,r11       // i3 = z[o3+16]
+    vmaddfp  v10,v4,v8,v14 // r2*wre
+    vmaddfp  v11,v5,v8,v14 // i2*wre
+    vmaddfp  v12,v6,v8,v14 // r3*wre
+    vmaddfp  v13,v7,v8,v14 // i3*wre
+    lvx    v0, 0,r3        // r0 = z[0]
+    lvx    v3,r3,r6        // i1 = z[o1+16]
+    vmaddfp  v10,v5,v9,v10 // i2*wim
+    vnmsubfp v11,v4,v9,v11 // r2*wim
+    vnmsubfp v12,v7,v9,v12 // i3*wim
+    vmaddfp  v13,v6,v9,v13 // r3*wim
+    lvx    v1,r3,r9        // i0 = z[16]
+    lvx    v2,r3,r5        // r1 = z[o1]
+    BF     v12,v8,v12,v10
+    BF     v13,v9,v11,v13
+    BF     v0,v4,v0,v12
+    BF     v3,v7,v3,v8
+.if !\interleave
+    stvx   v0, 0,r3
+    stvx   v4,r3,r7
+    stvx   v3,r3,r6
+    stvx   v7,r3,r11
+.endif
+    BF     v1,v5,v1,v13
+    BF     v2,v6,v2,v9
+.if !\interleave
+    stvx   v1,r3,r9
+    stvx   v2,r3,r5
+    stvx   v5,r3,r8
+    stvx   v6,r3,r10
+.else
+    vmrghw v8,v0,v1
+    vmrglw v9,v0,v1
+    stvx   v8, 0,r3
+    stvx   v9,r3,r9
+    vmrghw v8,v2,v3
+    vmrglw v9,v2,v3
+    stvx   v8,r3,r5
+    stvx   v9,r3,r6
+    vmrghw v8,v4,v5
+    vmrglw v9,v4,v5
+    stvx   v8,r3,r7
+    stvx   v9,r3,r8
+    vmrghw v8,v6,v7
+    vmrglw v9,v6,v7
+    stvx   v8,r3,r10
+    stvx   v9,r3,r11
+.endif
+    addi   r3,r3,32
+    addi   r4,r4,16
+    bdnz 1b
+    sub    r3,r3,r5
+    blr
+.endm
+
+#define M_SQRT1_2      0.70710678118654752440  /* 1/sqrt(2) */
+
+#define WORD_0  0x00,0x01,0x02,0x03
+#define WORD_1  0x04,0x05,0x06,0x07
+#define WORD_2  0x08,0x09,0x0a,0x0b
+#define WORD_3  0x0c,0x0d,0x0e,0x0f
+#define WORD_s0 0x10,0x11,0x12,0x13
+#define WORD_s1 0x14,0x15,0x16,0x17
+#define WORD_s2 0x18,0x19,0x1a,0x1b
+#define WORD_s3 0x1c,0x1d,0x1e,0x1f
+
+#define vcprm(a, b, c, d) .byte WORD_##a, WORD_##b, WORD_##c, WORD_##d
+
+    .rodata
+    .align 4
+fft_data:
+    .float  0, 0, 0, 0
+    .float  1, 0.92387953, M_SQRT1_2, 0.38268343
+    .float  0, 0.38268343, M_SQRT1_2, 0.92387953
+    .float  -M_SQRT1_2, M_SQRT1_2, M_SQRT1_2,-M_SQRT1_2
+    .float   M_SQRT1_2, M_SQRT1_2, M_SQRT1_2, M_SQRT1_2
+    vcprm(s0,3,2,1)
+    vcprm(0,1,s2,s1)
+    vcprm(2,3,s0,s3)
+    vcprm(2,s3,3,s2)
+    vcprm(0,1,s0,s1)
+    vcprm(2,3,s2,s3)
+    vcprm(2,3,0,1)
+    vcprm(1,2,s3,s0)
+    vcprm(0,3,s2,s1)
+    vcprm(0,2,s1,s3)
+    vcprm(1,3,s0,s2)
+
+.macro lvm  b, r, regs:vararg
+    lvx     \r, 0, \b
+    addi    \b, \b, 16
+  .ifnb \regs
+    lvm     \b, \regs
+  .endif
+.endm
+
+.macro stvm b, r, regs:vararg
+    stvx    \r, 0, \b
+    addi    \b, \b, 16
+  .ifnb \regs
+    stvm    \b, \regs
+  .endif
+.endm
+
+.macro fft_calc interleave
+extfunc ff_fft_calc\interleave\()_altivec
+    mflr    r0
+    stp     r0, 2*PS(r1)
+    stpu    r1, -(160+16*PS)(r1)
+    addi    r6, r1, 16*PS
+    stvm    r6, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29
+    mfvrsave r0
+    stw     r0, 15*PS(r1)
+    li      r6, 0xfffffffc
+    mtvrsave r6
+
+    movrel  r6, fft_data
+    lvm     r6, v14, v15, v16, v17, v18, v19, v20, v21
+    lvm     r6, v22, v23, v24, v25, v26, v27, v28, v29
+
+    li      r9, 16
+    movrel  r12, X(ff_cos_tabs)
+
+    movrel  r6, fft_dispatch_tab\interleave\()_altivec
+    lwz     r3, 0(r3)
+    subi    r3, r3, 2
+    slwi    r3, r3, 2+ARCH_PPC64
+    lpx     r3, r3, r6
+    mtctr   r3
+    mr      r3, r4
+    bctrl
+
+    addi    r6, r1, 16*PS
+    lvm     r6, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29
+    lwz     r6, 15*PS(r1)
+    mtvrsave r6
+    lp      r1, 0(r1)
+    lp      r0, 2*PS(r1)
+    mtlr    r0
+    blr
+.endm
+
+.macro DECL_FFT suffix, bits, n, n2, n4
+fft\n\suffix\()_altivec:
+    mflr  r0
+    stp   r0,PS*(\bits-3)(r1)
+    bl    fft\n2\()_altivec
+    addi2 r3,\n*4
+    bl    fft\n4\()_altivec
+    addi2 r3,\n*2
+    bl    fft\n4\()_altivec
+    addi2 r3,\n*-6
+    lp    r0,PS*(\bits-3)(r1)
+    lp    r4,\bits*PS(r12)
+    mtlr  r0
+    li    r5,\n/16
+    b     fft_pass\suffix\()_altivec
+.endm
+
+.macro DECL_FFTS interleave, suffix
+    .text
+    def_fft4  \suffix
+    def_fft8  \suffix
+    def_fft16 \suffix
+    PASS \interleave, \suffix
+    DECL_FFT \suffix, 5,   32,   16,    8
+    DECL_FFT \suffix, 6,   64,   32,   16
+    DECL_FFT \suffix, 7,  128,   64,   32
+    DECL_FFT \suffix, 8,  256,  128,   64
+    DECL_FFT \suffix, 9,  512,  256,  128
+    DECL_FFT \suffix,10, 1024,  512,  256
+    DECL_FFT \suffix,11, 2048, 1024,  512
+    DECL_FFT \suffix,12, 4096, 2048, 1024
+    DECL_FFT \suffix,13, 8192, 4096, 2048
+    DECL_FFT \suffix,14,16384, 8192, 4096
+    DECL_FFT \suffix,15,32768,16384, 8192
+    DECL_FFT \suffix,16,65536,32768,16384
+
+    fft_calc \suffix
+
+    .rodata
+    .align 3
+fft_dispatch_tab\suffix\()_altivec:
+    PTR fft4\suffix\()_altivec
+    PTR fft8\suffix\()_altivec
+    PTR fft16\suffix\()_altivec
+    PTR fft32\suffix\()_altivec
+    PTR fft64\suffix\()_altivec
+    PTR fft128\suffix\()_altivec
+    PTR fft256\suffix\()_altivec
+    PTR fft512\suffix\()_altivec
+    PTR fft1024\suffix\()_altivec
+    PTR fft2048\suffix\()_altivec
+    PTR fft4096\suffix\()_altivec
+    PTR fft8192\suffix\()_altivec
+    PTR fft16384\suffix\()_altivec
+    PTR fft32768\suffix\()_altivec
+    PTR fft65536\suffix\()_altivec
+.endm
+
+DECL_FFTS 0
+DECL_FFTS 1, _interleave
diff --git a/libavcodec/ppc/float_altivec.c b/libavcodec/ppc/float_altivec.c
index d1f9f1a..e401069 100644
--- a/libavcodec/ppc/float_altivec.c
+++ b/libavcodec/ppc/float_altivec.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2006 Luca Barbato <lu_zero at gentoo.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -23,16 +23,16 @@
 #include "dsputil_altivec.h"
 #include "util_altivec.h"
 
-static void vector_fmul_altivec(float *dst, const float *src, int len)
+static void vector_fmul_altivec(float *dst, const float *src0, const float *src1, int len)
 {
     int i;
     vector float d0, d1, s, zero = (vector float)vec_splat_u32(0);
     for(i=0; i<len-7; i+=8) {
-        d0 = vec_ld(0, dst+i);
-        s = vec_ld(0, src+i);
-        d1 = vec_ld(16, dst+i);
+        d0 = vec_ld(0, src0+i);
+        s = vec_ld(0, src1+i);
+        d1 = vec_ld(16, src0+i);
         d0 = vec_madd(d0, s, zero);
-        d1 = vec_madd(d1, vec_ld(16,src+i), zero);
+        d1 = vec_madd(d1, vec_ld(16,src1+i), zero);
         vec_st(d0, 0, dst+i);
         vec_st(d1, 16, dst+i);
     }
@@ -90,13 +90,9 @@ static void vector_fmul_add_altivec(float *dst, const float *src0,
     }
 }
 
-static void vector_fmul_window_altivec(float *dst, const float *src0, const float *src1, const float *win, float add_bias, int len)
+static void vector_fmul_window_altivec(float *dst, const float *src0, const float *src1, const float *win, int len)
 {
-    union {
-        vector float v;
-        float s[4];
-    } vadd;
-    vector float vadd_bias, zero, t0, t1, s0, s1, wi, wj;
+    vector float zero, t0, t1, s0, s1, wi, wj;
     const vector unsigned char reverse = vcprm(3,2,1,0);
     int i,j;
 
@@ -104,8 +100,6 @@ static void vector_fmul_window_altivec(float *dst, const float *src0, const floa
     win += len;
     src0+= len;
 
-    vadd.s[0] = add_bias;
-    vadd_bias = vec_splat(vadd.v, 0);
     zero = (vector float)vec_splat_u32(0);
 
     for(i=-len*4, j=len*4-16; i<0; i+=16, j-=16) {
@@ -117,9 +111,9 @@ static void vector_fmul_window_altivec(float *dst, const float *src0, const floa
         s1 = vec_perm(s1, s1, reverse);
         wj = vec_perm(wj, wj, reverse);
 
-        t0 = vec_madd(s0, wj, vadd_bias);
+        t0 = vec_madd(s0, wj, zero);
         t0 = vec_nmsub(s1, wi, t0);
-        t1 = vec_madd(s0, wi, vadd_bias);
+        t1 = vec_madd(s0, wi, zero);
         t1 = vec_madd(s1, wj, t1);
         t1 = vec_perm(t1, t1, reverse);
 
@@ -128,124 +122,12 @@ static void vector_fmul_window_altivec(float *dst, const float *src0, const floa
     }
 }
 
-static void int32_to_float_fmul_scalar_altivec(float *dst, const int *src, float mul, int len)
-{
-    union {
-        vector float v;
-        float s[4];
-    } mul_u;
-    int i;
-    vector float src1, src2, dst1, dst2, mul_v, zero;
-
-    zero = (vector float)vec_splat_u32(0);
-    mul_u.s[0] = mul;
-    mul_v = vec_splat(mul_u.v, 0);
-
-    for(i=0; i<len; i+=8) {
-        src1 = vec_ctf(vec_ld(0,  src+i), 0);
-        src2 = vec_ctf(vec_ld(16, src+i), 0);
-        dst1 = vec_madd(src1, mul_v, zero);
-        dst2 = vec_madd(src2, mul_v, zero);
-        vec_st(dst1,  0, dst+i);
-        vec_st(dst2, 16, dst+i);
-    }
-}
-
-
-static vector signed short
-float_to_int16_one_altivec(const float *src)
-{
-    vector float s0 = vec_ld(0, src);
-    vector float s1 = vec_ld(16, src);
-    vector signed int t0 = vec_cts(s0, 0);
-    vector signed int t1 = vec_cts(s1, 0);
-    return vec_packs(t0,t1);
-}
-
-static void float_to_int16_altivec(int16_t *dst, const float *src, long len)
-{
-    int i;
-    vector signed short d0, d1, d;
-    vector unsigned char align;
-    if(((long)dst)&15) //FIXME
-    for(i=0; i<len-7; i+=8) {
-        d0 = vec_ld(0, dst+i);
-        d = float_to_int16_one_altivec(src+i);
-        d1 = vec_ld(15, dst+i);
-        d1 = vec_perm(d1, d0, vec_lvsl(0,dst+i));
-        align = vec_lvsr(0, dst+i);
-        d0 = vec_perm(d1, d, align);
-        d1 = vec_perm(d, d1, align);
-        vec_st(d0, 0, dst+i);
-        vec_st(d1,15, dst+i);
-    }
-    else
-    for(i=0; i<len-7; i+=8) {
-        d = float_to_int16_one_altivec(src+i);
-        vec_st(d, 0, dst+i);
-    }
-}
-
-static void
-float_to_int16_interleave_altivec(int16_t *dst, const float **src,
-                                  long len, int channels)
-{
-    int i;
-    vector signed short d0, d1, d2, c0, c1, t0, t1;
-    vector unsigned char align;
-    if(channels == 1)
-        float_to_int16_altivec(dst, src[0], len);
-    else
-        if (channels == 2) {
-        if(((long)dst)&15)
-        for(i=0; i<len-7; i+=8) {
-            d0 = vec_ld(0, dst + i);
-            t0 = float_to_int16_one_altivec(src[0] + i);
-            d1 = vec_ld(31, dst + i);
-            t1 = float_to_int16_one_altivec(src[1] + i);
-            c0 = vec_mergeh(t0, t1);
-            c1 = vec_mergel(t0, t1);
-            d2 = vec_perm(d1, d0, vec_lvsl(0, dst + i));
-            align = vec_lvsr(0, dst + i);
-            d0 = vec_perm(d2, c0, align);
-            d1 = vec_perm(c0, c1, align);
-            vec_st(d0,  0, dst + i);
-            d0 = vec_perm(c1, d2, align);
-            vec_st(d1, 15, dst + i);
-            vec_st(d0, 31, dst + i);
-            dst+=8;
-        }
-        else
-        for(i=0; i<len-7; i+=8) {
-            t0 = float_to_int16_one_altivec(src[0] + i);
-            t1 = float_to_int16_one_altivec(src[1] + i);
-            d0 = vec_mergeh(t0, t1);
-            d1 = vec_mergel(t0, t1);
-            vec_st(d0,  0, dst + i);
-            vec_st(d1, 16, dst + i);
-            dst+=8;
-        }
-    } else {
-        DECLARE_ALIGNED(16, int16_t, tmp)[len];
-        int c, j;
-        for (c = 0; c < channels; c++) {
-            float_to_int16_altivec(tmp, src[c], len);
-            for (i = 0, j = c; i < len; i++, j+=channels) {
-                dst[j] = tmp[i];
-            }
-        }
-   }
-}
-
 void float_init_altivec(DSPContext* c, AVCodecContext *avctx)
 {
     c->vector_fmul = vector_fmul_altivec;
     c->vector_fmul_reverse = vector_fmul_reverse_altivec;
     c->vector_fmul_add = vector_fmul_add_altivec;
-    c->int32_to_float_fmul_scalar = int32_to_float_fmul_scalar_altivec;
     if(!(avctx->flags & CODEC_FLAG_BITEXACT)) {
         c->vector_fmul_window = vector_fmul_window_altivec;
-        c->float_to_int16 = float_to_int16_altivec;
-        c->float_to_int16_interleave = float_to_int16_interleave_altivec;
     }
 }
diff --git a/libavcodec/ppc/fmtconvert_altivec.c b/libavcodec/ppc/fmtconvert_altivec.c
new file mode 100644
index 0000000..b1eaf9b
--- /dev/null
+++ b/libavcodec/ppc/fmtconvert_altivec.c
@@ -0,0 +1,142 @@
+/*
+ * Copyright (c) 2006 Luca Barbato <lu_zero at gentoo.org>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "libavcodec/fmtconvert.h"
+
+#include "dsputil_altivec.h"
+#include "util_altivec.h"
+
+static void int32_to_float_fmul_scalar_altivec(float *dst, const int *src, float mul, int len)
+{
+    union {
+        vector float v;
+        float s[4];
+    } mul_u;
+    int i;
+    vector float src1, src2, dst1, dst2, mul_v, zero;
+
+    zero = (vector float)vec_splat_u32(0);
+    mul_u.s[0] = mul;
+    mul_v = vec_splat(mul_u.v, 0);
+
+    for(i=0; i<len; i+=8) {
+        src1 = vec_ctf(vec_ld(0,  src+i), 0);
+        src2 = vec_ctf(vec_ld(16, src+i), 0);
+        dst1 = vec_madd(src1, mul_v, zero);
+        dst2 = vec_madd(src2, mul_v, zero);
+        vec_st(dst1,  0, dst+i);
+        vec_st(dst2, 16, dst+i);
+    }
+}
+
+
+static vector signed short
+float_to_int16_one_altivec(const float *src)
+{
+    vector float s0 = vec_ld(0, src);
+    vector float s1 = vec_ld(16, src);
+    vector signed int t0 = vec_cts(s0, 0);
+    vector signed int t1 = vec_cts(s1, 0);
+    return vec_packs(t0,t1);
+}
+
+static void float_to_int16_altivec(int16_t *dst, const float *src, long len)
+{
+    int i;
+    vector signed short d0, d1, d;
+    vector unsigned char align;
+    if(((long)dst)&15) //FIXME
+    for(i=0; i<len-7; i+=8) {
+        d0 = vec_ld(0, dst+i);
+        d = float_to_int16_one_altivec(src+i);
+        d1 = vec_ld(15, dst+i);
+        d1 = vec_perm(d1, d0, vec_lvsl(0,dst+i));
+        align = vec_lvsr(0, dst+i);
+        d0 = vec_perm(d1, d, align);
+        d1 = vec_perm(d, d1, align);
+        vec_st(d0, 0, dst+i);
+        vec_st(d1,15, dst+i);
+    }
+    else
+    for(i=0; i<len-7; i+=8) {
+        d = float_to_int16_one_altivec(src+i);
+        vec_st(d, 0, dst+i);
+    }
+}
+
+static void
+float_to_int16_interleave_altivec(int16_t *dst, const float **src,
+                                  long len, int channels)
+{
+    int i;
+    vector signed short d0, d1, d2, c0, c1, t0, t1;
+    vector unsigned char align;
+    if(channels == 1)
+        float_to_int16_altivec(dst, src[0], len);
+    else
+        if (channels == 2) {
+        if(((long)dst)&15)
+        for(i=0; i<len-7; i+=8) {
+            d0 = vec_ld(0, dst + i);
+            t0 = float_to_int16_one_altivec(src[0] + i);
+            d1 = vec_ld(31, dst + i);
+            t1 = float_to_int16_one_altivec(src[1] + i);
+            c0 = vec_mergeh(t0, t1);
+            c1 = vec_mergel(t0, t1);
+            d2 = vec_perm(d1, d0, vec_lvsl(0, dst + i));
+            align = vec_lvsr(0, dst + i);
+            d0 = vec_perm(d2, c0, align);
+            d1 = vec_perm(c0, c1, align);
+            vec_st(d0,  0, dst + i);
+            d0 = vec_perm(c1, d2, align);
+            vec_st(d1, 15, dst + i);
+            vec_st(d0, 31, dst + i);
+            dst+=8;
+        }
+        else
+        for(i=0; i<len-7; i+=8) {
+            t0 = float_to_int16_one_altivec(src[0] + i);
+            t1 = float_to_int16_one_altivec(src[1] + i);
+            d0 = vec_mergeh(t0, t1);
+            d1 = vec_mergel(t0, t1);
+            vec_st(d0,  0, dst + i);
+            vec_st(d1, 16, dst + i);
+            dst+=8;
+        }
+    } else {
+        DECLARE_ALIGNED(16, int16_t, tmp)[len];
+        int c, j;
+        for (c = 0; c < channels; c++) {
+            float_to_int16_altivec(tmp, src[c], len);
+            for (i = 0, j = c; i < len; i++, j+=channels) {
+                dst[j] = tmp[i];
+            }
+        }
+   }
+}
+
+void ff_fmt_convert_init_altivec(FmtConvertContext *c, AVCodecContext *avctx)
+{
+    c->int32_to_float_fmul_scalar = int32_to_float_fmul_scalar_altivec;
+    if(!(avctx->flags & CODEC_FLAG_BITEXACT)) {
+        c->float_to_int16 = float_to_int16_altivec;
+        c->float_to_int16_interleave = float_to_int16_interleave_altivec;
+    }
+}
diff --git a/libavcodec/ppc/gmc_altivec.c b/libavcodec/ppc/gmc_altivec.c
index fa71047..0ed70ab 100644
--- a/libavcodec/ppc/gmc_altivec.c
+++ b/libavcodec/ppc/gmc_altivec.c
@@ -3,25 +3,24 @@
  * AltiVec-enabled
  * Copyright (c) 2003 Romain Dolbeau <romain at dolbeau.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "libavcodec/dsputil.h"
-#include "dsputil_ppc.h"
 #include "util_altivec.h"
 #include "types_altivec.h"
 #include "dsputil_altivec.h"
@@ -30,10 +29,8 @@
   altivec-enhanced gmc1. ATM this code assume stride is a multiple of 8,
   to preserve proper dst alignment.
 */
-#define GMC1_PERF_COND (h==8)
 void gmc1_altivec(uint8_t *dst /* align 8 */, uint8_t *src /* align1 */, int stride, int h, int x16, int y16, int rounder)
 {
-POWERPC_PERF_DECLARE(altivec_gmc1_num, GMC1_PERF_COND);
     const DECLARE_ALIGNED(16, unsigned short, rounder_a) = rounder;
     const DECLARE_ALIGNED(16, unsigned short, ABCD)[8] =
         {
@@ -51,9 +48,6 @@ POWERPC_PERF_DECLARE(altivec_gmc1_num, GMC1_PERF_COND);
     unsigned long dst_odd = (unsigned long)dst & 0x0000000F;
     unsigned long src_really_odd = (unsigned long)src & 0x0000000F;
 
-
-POWERPC_PERF_START_COUNT(altivec_gmc1_num, GMC1_PERF_COND);
-
     tempA = vec_ld(0, (unsigned short*)ABCD);
     Av = vec_splat(tempA, 0);
     Bv = vec_splat(tempA, 1);
@@ -133,6 +127,4 @@ POWERPC_PERF_START_COUNT(altivec_gmc1_num, GMC1_PERF_COND);
         dst += stride;
         src += stride;
     }
-
-POWERPC_PERF_STOP_COUNT(altivec_gmc1_num, GMC1_PERF_COND);
 }
diff --git a/libavcodec/ppc/h264_altivec.c b/libavcodec/ppc/h264_altivec.c
index 47e416b..02699be 100644
--- a/libavcodec/ppc/h264_altivec.c
+++ b/libavcodec/ppc/h264_altivec.c
@@ -1,28 +1,28 @@
 /*
  * Copyright (c) 2004 Romain Dolbeau <romain at dolbeau.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/cpu.h"
 #include "libavcodec/dsputil.h"
 #include "libavcodec/h264data.h"
 #include "libavcodec/h264dsp.h"
 
-#include "dsputil_ppc.h"
 #include "dsputil_altivec.h"
 #include "util_altivec.h"
 #include "types_altivec.h"
@@ -32,7 +32,6 @@
 
 #define OP_U8_ALTIVEC                          PUT_OP_U8_ALTIVEC
 #define PREFIX_h264_chroma_mc8_altivec         put_h264_chroma_mc8_altivec
-#define PREFIX_no_rnd_vc1_chroma_mc8_altivec   put_no_rnd_vc1_chroma_mc8_altivec
 #define PREFIX_h264_chroma_mc8_num             altivec_put_h264_chroma_mc8_num
 #define PREFIX_h264_qpel16_h_lowpass_altivec   put_h264_qpel16_h_lowpass_altivec
 #define PREFIX_h264_qpel16_h_lowpass_num       altivec_put_h264_qpel16_h_lowpass_num
@@ -43,7 +42,6 @@
 #include "h264_template_altivec.c"
 #undef OP_U8_ALTIVEC
 #undef PREFIX_h264_chroma_mc8_altivec
-#undef PREFIX_no_rnd_vc1_chroma_mc8_altivec
 #undef PREFIX_h264_chroma_mc8_num
 #undef PREFIX_h264_qpel16_h_lowpass_altivec
 #undef PREFIX_h264_qpel16_h_lowpass_num
@@ -54,7 +52,6 @@
 
 #define OP_U8_ALTIVEC                          AVG_OP_U8_ALTIVEC
 #define PREFIX_h264_chroma_mc8_altivec         avg_h264_chroma_mc8_altivec
-#define PREFIX_no_rnd_vc1_chroma_mc8_altivec   avg_no_rnd_vc1_chroma_mc8_altivec
 #define PREFIX_h264_chroma_mc8_num             altivec_avg_h264_chroma_mc8_num
 #define PREFIX_h264_qpel16_h_lowpass_altivec   avg_h264_qpel16_h_lowpass_altivec
 #define PREFIX_h264_qpel16_h_lowpass_num       altivec_avg_h264_qpel16_h_lowpass_num
@@ -65,7 +62,6 @@
 #include "h264_template_altivec.c"
 #undef OP_U8_ALTIVEC
 #undef PREFIX_h264_chroma_mc8_altivec
-#undef PREFIX_no_rnd_vc1_chroma_mc8_altivec
 #undef PREFIX_h264_chroma_mc8_num
 #undef PREFIX_h264_qpel16_h_lowpass_altivec
 #undef PREFIX_h264_qpel16_h_lowpass_num
@@ -970,11 +966,9 @@ H264_WEIGHT( 8, 4)
 
 void dsputil_h264_init_ppc(DSPContext* c, AVCodecContext *avctx) {
 
-    if (has_altivec()) {
+    if (av_get_cpu_flags() & AV_CPU_FLAG_ALTIVEC) {
         c->put_h264_chroma_pixels_tab[0] = put_h264_chroma_mc8_altivec;
         c->avg_h264_chroma_pixels_tab[0] = avg_h264_chroma_mc8_altivec;
-        c->put_no_rnd_vc1_chroma_pixels_tab[0] = put_no_rnd_vc1_chroma_mc8_altivec;
-        c->avg_no_rnd_vc1_chroma_pixels_tab[0] = avg_no_rnd_vc1_chroma_mc8_altivec;
 
 #define dspfunc(PFX, IDX, NUM) \
         c->PFX ## _pixels_tab[IDX][ 0] = PFX ## NUM ## _mc00_altivec; \
@@ -1002,7 +996,7 @@ void dsputil_h264_init_ppc(DSPContext* c, AVCodecContext *avctx) {
 
 void ff_h264dsp_init_ppc(H264DSPContext *c)
 {
-    if (has_altivec()) {
+    if (av_get_cpu_flags() & AV_CPU_FLAG_ALTIVEC) {
         c->h264_idct_add = ff_h264_idct_add_altivec;
         c->h264_idct_add8 = ff_h264_idct_add8_altivec;
         c->h264_idct_add16 = ff_h264_idct_add16_altivec;
diff --git a/libavcodec/ppc/h264_template_altivec.c b/libavcodec/ppc/h264_template_altivec.c
index c0a4eb7..020d7c7 100644
--- a/libavcodec/ppc/h264_template_altivec.c
+++ b/libavcodec/ppc/h264_template_altivec.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2004 Romain Dolbeau <romain at dolbeau.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -75,9 +75,9 @@
 #define noop(a) a
 #define add28(a) vec_add(v28ss, a)
 
+#ifdef PREFIX_h264_chroma_mc8_altivec
 static void PREFIX_h264_chroma_mc8_altivec(uint8_t * dst, uint8_t * src,
                                     int stride, int h, int x, int y) {
-  POWERPC_PERF_DECLARE(PREFIX_h264_chroma_mc8_num, 1);
     DECLARE_ALIGNED(16, signed int, ABCD)[4] =
                         {((8 - x) * (8 - y)),
                          ((    x) * (8 - y)),
@@ -103,8 +103,6 @@ static void PREFIX_h264_chroma_mc8_altivec(uint8_t * dst, uint8_t * src,
     vec_s16 vsrc2ssH, vsrc3ssH, psum;
     vec_u8 vdst, ppsum, vfdst, fsum;
 
-  POWERPC_PERF_START_COUNT(PREFIX_h264_chroma_mc8_num, 1);
-
     if (((unsigned long)dst) % 16 == 0) {
         fperm = (vec_u8){0x10, 0x11, 0x12, 0x13,
                          0x14, 0x15, 0x16, 0x17,
@@ -203,10 +201,11 @@ static void PREFIX_h264_chroma_mc8_altivec(uint8_t * dst, uint8_t * src,
             }
         }
     }
-    POWERPC_PERF_STOP_COUNT(PREFIX_h264_chroma_mc8_num, 1);
 }
+#endif
 
 /* this code assume that stride % 16 == 0 */
+#ifdef PREFIX_no_rnd_vc1_chroma_mc8_altivec
 static void PREFIX_no_rnd_vc1_chroma_mc8_altivec(uint8_t * dst, uint8_t * src, int stride, int h, int x, int y) {
    DECLARE_ALIGNED(16, signed int, ABCD)[4] =
                         {((8 - x) * (8 - y)),
@@ -288,14 +287,15 @@ static void PREFIX_no_rnd_vc1_chroma_mc8_altivec(uint8_t * dst, uint8_t * src, i
         }
     }
 }
+#endif
 
 #undef noop
 #undef add28
 #undef CHROMA_MC8_ALTIVEC_CORE
 
 /* this code assume stride % 16 == 0 */
+#ifdef PREFIX_h264_qpel16_h_lowpass_altivec
 static void PREFIX_h264_qpel16_h_lowpass_altivec(uint8_t * dst, uint8_t * src, int dstStride, int srcStride) {
-    POWERPC_PERF_DECLARE(PREFIX_h264_qpel16_h_lowpass_num, 1);
     register int i;
 
     LOAD_ZERO;
@@ -323,8 +323,6 @@ static void PREFIX_h264_qpel16_h_lowpass_altivec(uint8_t * dst, uint8_t * src, i
 
     vec_u8 sum, vdst, fsum;
 
-    POWERPC_PERF_START_COUNT(PREFIX_h264_qpel16_h_lowpass_num, 1);
-
     for (i = 0 ; i < 16 ; i ++) {
         vec_u8 srcR1 = vec_ld(-2, src);
         vec_u8 srcR2 = vec_ld(14, src);
@@ -433,13 +431,12 @@ static void PREFIX_h264_qpel16_h_lowpass_altivec(uint8_t * dst, uint8_t * src, i
         src += srcStride;
         dst += dstStride;
     }
-    POWERPC_PERF_STOP_COUNT(PREFIX_h264_qpel16_h_lowpass_num, 1);
 }
+#endif
 
 /* this code assume stride % 16 == 0 */
+#ifdef PREFIX_h264_qpel16_v_lowpass_altivec
 static void PREFIX_h264_qpel16_v_lowpass_altivec(uint8_t * dst, uint8_t * src, int dstStride, int srcStride) {
-    POWERPC_PERF_DECLARE(PREFIX_h264_qpel16_v_lowpass_num, 1);
-
     register int i;
 
     LOAD_ZERO;
@@ -490,8 +487,6 @@ static void PREFIX_h264_qpel16_v_lowpass_altivec(uint8_t * dst, uint8_t * src, i
 
     vec_u8 sum, vdst, fsum, srcP3a, srcP3b, srcP3;
 
-    POWERPC_PERF_START_COUNT(PREFIX_h264_qpel16_v_lowpass_num, 1);
-
     for (i = 0 ; i < 16 ; i++) {
         srcP3a = vec_ld(0, srcbis += srcStride);
         srcP3b = vec_ld(16, srcbis);
@@ -544,12 +539,12 @@ static void PREFIX_h264_qpel16_v_lowpass_altivec(uint8_t * dst, uint8_t * src, i
 
         dst += dstStride;
     }
-    POWERPC_PERF_STOP_COUNT(PREFIX_h264_qpel16_v_lowpass_num, 1);
 }
+#endif
 
 /* this code assume stride % 16 == 0 *and* tmp is properly aligned */
+#ifdef PREFIX_h264_qpel16_hv_lowpass_altivec
 static void PREFIX_h264_qpel16_hv_lowpass_altivec(uint8_t * dst, int16_t * tmp, uint8_t * src, int dstStride, int tmpStride, int srcStride) {
-    POWERPC_PERF_DECLARE(PREFIX_h264_qpel16_hv_lowpass_num, 1);
     register int i;
     LOAD_ZERO;
     const vec_u8 permM2 = vec_lvsl(-2, src);
@@ -589,7 +584,6 @@ static void PREFIX_h264_qpel16_hv_lowpass_altivec(uint8_t * dst, int16_t * tmp,
     vec_u8 fsum, sumv, sum, vdst;
     vec_s16 ssume, ssumo;
 
-    POWERPC_PERF_START_COUNT(PREFIX_h264_qpel16_hv_lowpass_num, 1);
     src -= (2 * srcStride);
     for (i = 0 ; i < 21 ; i ++) {
         vec_u8 srcM2, srcM1, srcP0, srcP1, srcP2, srcP3;
@@ -779,5 +773,5 @@ static void PREFIX_h264_qpel16_hv_lowpass_altivec(uint8_t * dst, int16_t * tmp,
 
         dst += dstStride;
     }
-    POWERPC_PERF_STOP_COUNT(PREFIX_h264_qpel16_hv_lowpass_num, 1);
 }
+#endif
diff --git a/libavcodec/ppc/idct_altivec.c b/libavcodec/ppc/idct_altivec.c
index 7c6b79e..cc3adcb 100644
--- a/libavcodec/ppc/idct_altivec.c
+++ b/libavcodec/ppc/idct_altivec.c
@@ -1,31 +1,31 @@
 /*
  * Copyright (c) 2001 Michel Lespinasse
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 /*
  * NOTE: This code is based on GPL code from the libmpeg2 project.  The
  * author, Michel Lespinasses, has given explicit permission to release
- * under LGPL as part of FFmpeg.
+ * under LGPL as part of Libav.
  */
 
 /*
- * FFmpeg integration by Dieter Shirley
+ * Libav integration by Dieter Shirley
  *
  * This file is a direct copy of the AltiVec IDCT module from the libmpeg2
  * project.  I've deleted all of the libmpeg2-specific code, renamed the
@@ -43,7 +43,6 @@
 #endif
 #include "libavcodec/dsputil.h"
 #include "types_altivec.h"
-#include "dsputil_ppc.h"
 #include "dsputil_altivec.h"
 
 #define IDCT_HALF                                       \
@@ -161,13 +160,9 @@ static const vec_s16 constants[5] = {
 
 void idct_put_altivec(uint8_t* dest, int stride, int16_t *blk)
 {
-POWERPC_PERF_DECLARE(altivec_idct_put_num, 1);
     vec_s16 *block = (vec_s16*)blk;
     vec_u8 tmp;
 
-#if CONFIG_POWERPC_PERF
-POWERPC_PERF_START_COUNT(altivec_idct_put_num, 1);
-#endif
     IDCT
 
 #define COPY(dest,src)                                          \
@@ -183,13 +178,10 @@ POWERPC_PERF_START_COUNT(altivec_idct_put_num, 1);
     COPY (dest, vx5)    dest += stride;
     COPY (dest, vx6)    dest += stride;
     COPY (dest, vx7)
-
-POWERPC_PERF_STOP_COUNT(altivec_idct_put_num, 1);
 }
 
 void idct_add_altivec(uint8_t* dest, int stride, int16_t *blk)
 {
-POWERPC_PERF_DECLARE(altivec_idct_add_num, 1);
     vec_s16 *block = (vec_s16*)blk;
     vec_u8 tmp;
     vec_s16 tmp2, tmp3;
@@ -197,10 +189,6 @@ POWERPC_PERF_DECLARE(altivec_idct_add_num, 1);
     vec_u8 perm1;
     vec_u8 p0, p1, p;
 
-#if CONFIG_POWERPC_PERF
-POWERPC_PERF_START_COUNT(altivec_idct_add_num, 1);
-#endif
-
     IDCT
 
     p0 = vec_lvsl (0, dest);
@@ -226,7 +214,5 @@ POWERPC_PERF_START_COUNT(altivec_idct_add_num, 1);
     ADD (dest, vx5, perm1)      dest += stride;
     ADD (dest, vx6, perm0)      dest += stride;
     ADD (dest, vx7, perm1)
-
-POWERPC_PERF_STOP_COUNT(altivec_idct_add_num, 1);
 }
 
diff --git a/libavcodec/ppc/int_altivec.c b/libavcodec/ppc/int_altivec.c
index 7fb11dd..25cbb8f 100644
--- a/libavcodec/ppc/int_altivec.c
+++ b/libavcodec/ppc/int_altivec.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2007 Luca Barbato <lu_zero at gentoo.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -79,7 +79,7 @@ static int ssd_int8_vs_int16_altivec(const int8_t *pix1, const int16_t *pix2,
     return u.score[3];
 }
 
-static int32_t scalarproduct_int16_altivec(int16_t * v1, int16_t * v2, int order, const int shift)
+static int32_t scalarproduct_int16_altivec(const int16_t * v1, const int16_t * v2, int order, const int shift)
 {
     int i;
     LOAD_ZERO;
@@ -109,7 +109,7 @@ static int32_t scalarproduct_int16_altivec(int16_t * v1, int16_t * v2, int order
     return ires;
 }
 
-static int32_t scalarproduct_and_madd_int16_altivec(int16_t *v1, int16_t *v2, int16_t *v3, int order, int mul)
+static int32_t scalarproduct_and_madd_int16_altivec(int16_t *v1, const int16_t *v2, const int16_t *v3, int order, int mul)
 {
     LOAD_ZERO;
     vec_s16 *pv1 = (vec_s16*)v1;
diff --git a/libavcodec/ppc/mathops.h b/libavcodec/ppc/mathops.h
index dbd714f..34ddb11 100644
--- a/libavcodec/ppc/mathops.h
+++ b/libavcodec/ppc/mathops.h
@@ -3,20 +3,20 @@
  * Copyright (c) 2001, 2002 Fabrice Bellard
  * Copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at> et al
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/ppc/mpegaudiodec_altivec.c b/libavcodec/ppc/mpegaudiodec_altivec.c
new file mode 100644
index 0000000..af94276
--- /dev/null
+++ b/libavcodec/ppc/mpegaudiodec_altivec.c
@@ -0,0 +1,130 @@
+/*
+ * Altivec optimized MP3 decoding functions
+ * Copyright (c) 2010 Vitor Sessak
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "dsputil_altivec.h"
+#include "util_altivec.h"
+
+#define CONFIG_FLOAT 1
+#include "libavcodec/mpegaudio.h"
+
+#define MACS(rt, ra, rb) rt+=(ra)*(rb)
+#define MLSS(rt, ra, rb) rt-=(ra)*(rb)
+
+#define SUM8(op, sum, w, p)               \
+{                                         \
+    op(sum, (w)[0 * 64], (p)[0 * 64]);    \
+    op(sum, (w)[1 * 64], (p)[1 * 64]);    \
+    op(sum, (w)[2 * 64], (p)[2 * 64]);    \
+    op(sum, (w)[3 * 64], (p)[3 * 64]);    \
+    op(sum, (w)[4 * 64], (p)[4 * 64]);    \
+    op(sum, (w)[5 * 64], (p)[5 * 64]);    \
+    op(sum, (w)[6 * 64], (p)[6 * 64]);    \
+    op(sum, (w)[7 * 64], (p)[7 * 64]);    \
+}
+
+static void apply_window(const float *buf, const float *win1,
+                         const float *win2, float *sum1, float *sum2, int len)
+{
+    const vector float *win1a = (const vector float *) win1;
+    const vector float *win2a = (const vector float *) win2;
+    const vector float *bufa  = (const vector float *) buf;
+    vector float *sum1a = (vector float *) sum1;
+    vector float *sum2a = (vector float *) sum2;
+    vector float av_uninit(v0), av_uninit(v4);
+    vector float v1, v2, v3;
+
+    len = len >> 2;
+
+#define MULT(a, b)                         \
+    {                                      \
+        v1 = vec_ld(a, win1a);             \
+        v2 = vec_ld(b, win2a);             \
+        v3 = vec_ld(a, bufa);              \
+        v0 = vec_madd(v3, v1, v0);         \
+        v4 = vec_madd(v2, v3, v4);         \
+    }
+
+    while (len--) {
+        v0 = vec_xor(v0, v0);
+        v4 = vec_xor(v4, v4);
+
+        MULT(   0,   0);
+        MULT( 256,  64);
+        MULT( 512, 128);
+        MULT( 768, 192);
+        MULT(1024, 256);
+        MULT(1280, 320);
+        MULT(1536, 384);
+        MULT(1792, 448);
+
+        vec_st(v0, 0, sum1a);
+        vec_st(v4, 0, sum2a);
+        sum1a++;
+        sum2a++;
+        win1a++;
+        win2a++;
+        bufa++;
+    }
+}
+
+static void apply_window_mp3(float *in, float *win, int *unused, float *out,
+                             int incr)
+{
+    LOCAL_ALIGNED_16(float, suma, [17]);
+    LOCAL_ALIGNED_16(float, sumb, [17]);
+    LOCAL_ALIGNED_16(float, sumc, [17]);
+    LOCAL_ALIGNED_16(float, sumd, [17]);
+
+    float sum;
+    int j;
+    float *out2 = out + 32 * incr;
+
+    /* copy to avoid wrap */
+    memcpy(in + 512, in, 32 * sizeof(*in));
+
+    apply_window(in + 16, win     , win + 512, suma, sumc, 16);
+    apply_window(in + 32, win + 48, win + 640, sumb, sumd, 16);
+
+    SUM8(MLSS, suma[0], win + 32, in + 48);
+
+    sumc[ 0] = 0;
+    sumb[16] = 0;
+    sumd[16] = 0;
+
+    out[0  ]  = suma[   0];
+    out += incr;
+    out2 -= incr;
+    for(j=1;j<16;j++) {
+        *out  =  suma[   j] - sumd[16-j];
+        *out2 = -sumb[16-j] - sumc[   j];
+        out  += incr;
+        out2 -= incr;
+    }
+
+    sum = 0;
+    SUM8(MLSS, sum, win + 16 + 32, in + 32);
+    *out = sum;
+}
+
+void ff_mpegaudiodec_init_altivec(MPADecodeContext *s)
+{
+    s->apply_window_mp3 = apply_window_mp3;
+}
diff --git a/libavcodec/ppc/mpegvideo_altivec.c b/libavcodec/ppc/mpegvideo_altivec.c
index 07e63be..e02c094 100644
--- a/libavcodec/ppc/mpegvideo_altivec.c
+++ b/libavcodec/ppc/mpegvideo_altivec.c
@@ -4,29 +4,29 @@
  * dct_unquantize_h263_altivec:
  * Copyright (c) 2003 Romain Dolbeau <romain at dolbeau.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include <stdlib.h>
 #include <stdio.h>
+#include "libavutil/cpu.h"
 #include "libavcodec/dsputil.h"
 #include "libavcodec/mpegvideo.h"
 
-#include "dsputil_ppc.h"
 #include "util_altivec.h"
 #include "types_altivec.h"
 #include "dsputil_altivec.h"
@@ -479,14 +479,11 @@ static int dct_quantize_altivec(MpegEncContext* s,
 static void dct_unquantize_h263_altivec(MpegEncContext *s,
                                  DCTELEM *block, int n, int qscale)
 {
-POWERPC_PERF_DECLARE(altivec_dct_unquantize_h263_num, 1);
     int i, level, qmul, qadd;
     int nCoeffs;
 
     assert(s->block_last_index[n]>=0);
 
-POWERPC_PERF_START_COUNT(altivec_dct_unquantize_h263_num, 1);
-
     qadd = (qscale - 1) | 1;
     qmul = qscale << 1;
 
@@ -569,13 +566,12 @@ POWERPC_PERF_START_COUNT(altivec_dct_unquantize_h263_num, 1);
             block[0] = backup_0;
         }
     }
-POWERPC_PERF_STOP_COUNT(altivec_dct_unquantize_h263_num, nCoeffs == 63);
 }
 
 
 void MPV_common_init_altivec(MpegEncContext *s)
 {
-    if ((mm_flags & FF_MM_ALTIVEC) == 0) return;
+    if (!(av_get_cpu_flags() & AV_CPU_FLAG_ALTIVEC)) return;
 
     if (s->avctx->lowres==0) {
         if ((s->avctx->idct_algo == FF_IDCT_AUTO) ||
diff --git a/libavcodec/ppc/regs.h b/libavcodec/ppc/regs.h
new file mode 100644
index 0000000..2edd639
--- /dev/null
+++ b/libavcodec/ppc/regs.h
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) 2010 Mans Rullgard
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_PPC_REGS_H
+#define AVCODEC_PPC_REGS_H
+
+#include "libavutil/avutil.h"
+#include "config.h"
+
+#if HAVE_IBM_ASM
+#   define r(n) AV_TOSTRING(n)
+#   define f(n) AV_TOSTRING(n)
+#   define v(n) AV_TOSTRING(n)
+#else
+#   define r(n) AV_TOSTRING(r ## n)
+#   define f(n) AV_TOSTRING(f ## n)
+#   define v(n) AV_TOSTRING(v ## n)
+#endif
+
+#endif /* AVCODEC_PPC_REGS_H */
diff --git a/libavcodec/ppc/types_altivec.h b/libavcodec/ppc/types_altivec.h
index 2870e83..defa20e 100644
--- a/libavcodec/ppc/types_altivec.h
+++ b/libavcodec/ppc/types_altivec.h
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2006 Guillaume Poirier <gpoirier at mplayerhq.hu>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -30,6 +30,7 @@
 #define vec_s16 vector signed short
 #define vec_u32 vector unsigned int
 #define vec_s32 vector signed int
+#define vec_f   vector float
 
 /***********************************************************************
  * Null vector
diff --git a/libavcodec/ppc/util_altivec.h b/libavcodec/ppc/util_altivec.h
index 62f228a..e68e5b5 100644
--- a/libavcodec/ppc/util_altivec.h
+++ b/libavcodec/ppc/util_altivec.h
@@ -1,18 +1,18 @@
 /*
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -32,6 +32,8 @@
 #include <altivec.h>
 #endif
 
+#include "types_altivec.h"
+
 // used to build registers permutation vectors (vcprm)
 // the 's' are for words in the _s_econd vector
 #define WORD_0 0x00,0x01,0x02,0x03
@@ -102,4 +104,15 @@ static inline vector unsigned char unaligned_load(int offset, uint8_t *src)
     return vec_perm(first, second, mask);
 }
 
+/**
+ * loads vector known misalignment
+ * @param perm_vec the align permute vector to combine the two loads from lvsl
+ */
+static inline vec_u8 load_with_perm_vec(int offset, uint8_t *src, vec_u8 perm_vec)
+{
+    vec_u8 a = vec_ld(offset, src);
+    vec_u8 b = vec_ld(offset+15, src);
+    return vec_perm(a, b, perm_vec);
+}
+
 #endif /* AVCODEC_PPC_UTIL_ALTIVEC_H */
diff --git a/libavcodec/ppc/vc1dsp_altivec.c b/libavcodec/ppc/vc1dsp_altivec.c
index a2f55f2..c52b5a9 100644
--- a/libavcodec/ppc/vc1dsp_altivec.c
+++ b/libavcodec/ppc/vc1dsp_altivec.c
@@ -2,24 +2,25 @@
  * VC-1 and WMV3 decoder - DSP functions AltiVec-optimized
  * Copyright (c) 2006 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "libavcodec/dsputil.h"
+#include "libavcodec/vc1dsp.h"
 
 #include "util_altivec.h"
 #include "dsputil_altivec.h"
@@ -129,7 +130,8 @@ do { \
 
 /** Do inverse transform on 8x8 block
 */
-static void vc1_inv_trans_8x8_altivec(DCTELEM block[64])
+static void vc1_inv_trans_8x8_altivec(DCTELEM block[64],
+                                      int sign, int rangered)
 {
     vector signed short src0, src1, src2, src3, src4, src5, src6, src7;
     vector signed int s0, s1, s2, s3, s4, s5, s6, s7;
@@ -143,7 +145,9 @@ static void vc1_inv_trans_8x8_altivec(DCTELEM block[64])
     const vector unsigned int vec_2 = vec_splat_u32(2);
     const vector  signed int vec_1s = vec_splat_s32(1);
     const vector unsigned int vec_1 = vec_splat_u32(1);
-
+    const vector unsigned short rangered_shift = vec_splat_u16(1);
+    const vector   signed short signed_bias = vec_sl(vec_splat_s16(4),
+                                                     vec_splat_u16(4));
 
     src0 = vec_ld(  0, block);
     src1 = vec_ld( 16, block);
@@ -154,7 +158,6 @@ static void vc1_inv_trans_8x8_altivec(DCTELEM block[64])
     src6 = vec_ld( 96, block);
     src7 = vec_ld(112, block);
 
-    TRANSPOSE8(src0, src1, src2, src3, src4, src5, src6, src7);
     s0 = vec_unpackl(src0);
     s1 = vec_unpackl(src1);
     s2 = vec_unpackl(src2);
@@ -214,6 +217,27 @@ static void vc1_inv_trans_8x8_altivec(DCTELEM block[64])
     src6 = vec_pack(sE, s6);
     src7 = vec_pack(sF, s7);
 
+    if (rangered) {
+        if (!sign) {
+            src0 = vec_sub(src0, signed_bias);
+            src1 = vec_sub(src1, signed_bias);
+            src2 = vec_sub(src2, signed_bias);
+            src3 = vec_sub(src3, signed_bias);
+            src4 = vec_sub(src4, signed_bias);
+            src5 = vec_sub(src5, signed_bias);
+            src6 = vec_sub(src6, signed_bias);
+            src7 = vec_sub(src7, signed_bias);
+        }
+        src0 = vec_sl(src0, rangered_shift);
+        src1 = vec_sl(src1, rangered_shift);
+        src2 = vec_sl(src2, rangered_shift);
+        src3 = vec_sl(src3, rangered_shift);
+        src4 = vec_sl(src4, rangered_shift);
+        src5 = vec_sl(src5, rangered_shift);
+        src6 = vec_sl(src6, rangered_shift);
+        src7 = vec_sl(src7, rangered_shift);
+    }
+
     vec_st(src0,  0, block);
     vec_st(src1, 16, block);
     vec_st(src2, 32, block);
@@ -224,6 +248,36 @@ static void vc1_inv_trans_8x8_altivec(DCTELEM block[64])
     vec_st(src7,112, block);
 }
 
+static void vc1_inv_trans_8x8_add_altivec(uint8_t *dest, int stride, DCTELEM *b)
+{
+    vc1_inv_trans_8x8_altivec(b, 0, 0);
+    ff_add_pixels_clamped_c(b, dest, stride);
+}
+
+static void vc1_inv_trans_8x8_put_signed_altivec(uint8_t *dest, int stride, DCTELEM *b)
+{
+    vc1_inv_trans_8x8_altivec(b, 1, 0);
+    ff_put_signed_pixels_clamped_c(b, dest, stride);
+}
+
+static void vc1_inv_trans_8x8_put_signed_rangered_altivec(uint8_t *dest, int stride, DCTELEM *b)
+{
+    vc1_inv_trans_8x8_altivec(b, 1, 1);
+    ff_put_signed_pixels_clamped_c(b, dest, stride);
+}
+
+static void vc1_inv_trans_8x8_put_altivec(uint8_t *dest, int stride, DCTELEM *b)
+{
+    vc1_inv_trans_8x8_altivec(b, 0, 0);
+    ff_put_pixels_clamped_c(b, dest, stride);
+}
+
+static void vc1_inv_trans_8x8_put_rangered_altivec(uint8_t *dest, int stride, DCTELEM *b)
+{
+    vc1_inv_trans_8x8_altivec(b, 0, 1);
+    ff_put_pixels_clamped_c(b, dest, stride);
+}
+
 /** Do inverse transform on 8x4 part of block
 */
 static void vc1_inv_trans_8x4_altivec(uint8_t *dest, int stride, DCTELEM *block)
@@ -322,8 +376,32 @@ static void vc1_inv_trans_8x4_altivec(uint8_t *dest, int stride, DCTELEM *block)
     ADD (dest, src3, perm1)
 }
 
+#define PUT_OP_U8_ALTIVEC(d, s, dst) d = s
+#define AVG_OP_U8_ALTIVEC(d, s, dst) d = vec_avg(dst, s)
+
+#define OP_U8_ALTIVEC                          PUT_OP_U8_ALTIVEC
+#define PREFIX_no_rnd_vc1_chroma_mc8_altivec   put_no_rnd_vc1_chroma_mc8_altivec
+#include "h264_template_altivec.c"
+#undef OP_U8_ALTIVEC
+#undef PREFIX_no_rnd_vc1_chroma_mc8_altivec
+
+#define OP_U8_ALTIVEC                          AVG_OP_U8_ALTIVEC
+#define PREFIX_no_rnd_vc1_chroma_mc8_altivec   avg_no_rnd_vc1_chroma_mc8_altivec
+#include "h264_template_altivec.c"
+#undef OP_U8_ALTIVEC
+#undef PREFIX_no_rnd_vc1_chroma_mc8_altivec
+
+void ff_vc1dsp_init_altivec(VC1DSPContext* dsp)
+{
+    if (!(av_get_cpu_flags() & AV_CPU_FLAG_ALTIVEC))
+        return;
 
-void vc1dsp_init_altivec(DSPContext* dsp, AVCodecContext *avctx) {
-    dsp->vc1_inv_trans_8x8 = vc1_inv_trans_8x8_altivec;
+    dsp->vc1_inv_trans_8x8_add = vc1_inv_trans_8x8_add_altivec;
+    dsp->vc1_inv_trans_8x8_put_signed[0] = vc1_inv_trans_8x8_put_signed_altivec;
+    dsp->vc1_inv_trans_8x8_put_signed[1] = vc1_inv_trans_8x8_put_signed_rangered_altivec;
+    dsp->vc1_inv_trans_8x8_put[0] = vc1_inv_trans_8x8_put_altivec;
+    dsp->vc1_inv_trans_8x8_put[1] = vc1_inv_trans_8x8_put_rangered_altivec;
     dsp->vc1_inv_trans_8x4 = vc1_inv_trans_8x4_altivec;
+    dsp->put_no_rnd_vc1_chroma_pixels_tab[0] = put_no_rnd_vc1_chroma_mc8_altivec;
+    dsp->avg_no_rnd_vc1_chroma_pixels_tab[0] = avg_no_rnd_vc1_chroma_mc8_altivec;
 }
diff --git a/libavcodec/ppc/vp3dsp_altivec.c b/libavcodec/ppc/vp3dsp_altivec.c
index b0509d8..bbe9170 100644
--- a/libavcodec/ppc/vp3dsp_altivec.c
+++ b/libavcodec/ppc/vp3dsp_altivec.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (C) 2009 David Conrad
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/ppc/vp8dsp_altivec.c b/libavcodec/ppc/vp8dsp_altivec.c
new file mode 100644
index 0000000..06874b8
--- /dev/null
+++ b/libavcodec/ppc/vp8dsp_altivec.c
@@ -0,0 +1,303 @@
+/**
+ * VP8 compatible video decoder
+ *
+ * Copyright (C) 2010 David Conrad
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "libavutil/cpu.h"
+#include "libavcodec/vp8dsp.h"
+#include "dsputil_altivec.h"
+#include "types_altivec.h"
+#include "util_altivec.h"
+
+#define REPT4(...) { __VA_ARGS__, __VA_ARGS__, __VA_ARGS__, __VA_ARGS__ }
+
+// h subpel filter uses msum to multiply+add 4 pixel taps at once
+static const vec_s8 h_subpel_filters_inner[7] =
+{
+    REPT4( -6, 123,  12,  -1),
+    REPT4(-11, 108,  36,  -8),
+    REPT4( -9,  93,  50,  -6),
+    REPT4(-16,  77,  77, -16),
+    REPT4( -6,  50,  93,  -9),
+    REPT4( -8,  36, 108, -11),
+    REPT4( -1,  12, 123,  -6),
+};
+
+// for 6tap filters, these are the outer two taps
+// The zeros mask off pixels 4-7 when filtering 0-3
+// and vice-versa
+static const vec_s8 h_subpel_filters_outer[3] =
+{
+    REPT4(0, 0, 2, 1),
+    REPT4(0, 0, 3, 3),
+    REPT4(0, 0, 1, 2),
+};
+
+#define LOAD_H_SUBPEL_FILTER(i) \
+    vec_s8 filter_inner  = h_subpel_filters_inner[i]; \
+    vec_s8 filter_outerh = h_subpel_filters_outer[(i)>>1]; \
+    vec_s8 filter_outerl = vec_sld(filter_outerh, filter_outerh, 2)
+
+#define FILTER_H(dstv, off) \
+    a = vec_ld((off)-is6tap-1,    src); \
+    b = vec_ld((off)-is6tap-1+15, src); \
+\
+    pixh  = vec_perm(a, b, permh##off); \
+    pixl  = vec_perm(a, b, perml##off); \
+    filth = vec_msum(filter_inner, pixh, c64); \
+    filtl = vec_msum(filter_inner, pixl, c64); \
+\
+    if (is6tap) { \
+        outer = vec_perm(a, b, perm_6tap##off); \
+        filth = vec_msum(filter_outerh, outer, filth); \
+        filtl = vec_msum(filter_outerl, outer, filtl); \
+    } \
+    if (w == 4) \
+        filtl = filth; /* discard pixels 4-7 */ \
+    dstv = vec_packs(filth, filtl); \
+    dstv = vec_sra(dstv, c7)
+
+static av_always_inline
+void put_vp8_epel_h_altivec_core(uint8_t *dst, int dst_stride,
+                                 uint8_t *src, int src_stride,
+                                 int h, int mx, int w, int is6tap)
+{
+    LOAD_H_SUBPEL_FILTER(mx-1);
+    vec_u8 align_vec0, align_vec8, permh0, permh8, filt;
+    vec_u8 perm_6tap0, perm_6tap8, perml0, perml8;
+    vec_u8 a, b, pixh, pixl, outer;
+    vec_s16 f16h, f16l;
+    vec_s32 filth, filtl;
+
+    vec_u8 perm_inner6 = { 1,2,3,4, 2,3,4,5, 3,4,5,6, 4,5,6,7 };
+    vec_u8 perm_inner4 = { 0,1,2,3, 1,2,3,4, 2,3,4,5, 3,4,5,6 };
+    vec_u8 perm_inner  = is6tap ? perm_inner6 : perm_inner4;
+    vec_u8 perm_outer = { 4,9, 0,5, 5,10, 1,6, 6,11, 2,7, 7,12, 3,8 };
+    vec_s32 c64 = vec_sl(vec_splat_s32(1), vec_splat_u32(6));
+    vec_u16 c7  = vec_splat_u16(7);
+
+    align_vec0 = vec_lvsl( -is6tap-1, src);
+    align_vec8 = vec_lvsl(8-is6tap-1, src);
+
+    permh0     = vec_perm(align_vec0, align_vec0, perm_inner);
+    permh8     = vec_perm(align_vec8, align_vec8, perm_inner);
+    perm_inner = vec_add(perm_inner, vec_splat_u8(4));
+    perml0     = vec_perm(align_vec0, align_vec0, perm_inner);
+    perml8     = vec_perm(align_vec8, align_vec8, perm_inner);
+    perm_6tap0 = vec_perm(align_vec0, align_vec0, perm_outer);
+    perm_6tap8 = vec_perm(align_vec8, align_vec8, perm_outer);
+
+    while (h --> 0) {
+        FILTER_H(f16h, 0);
+
+        if (w == 16) {
+            FILTER_H(f16l, 8);
+            filt = vec_packsu(f16h, f16l);
+            vec_st(filt, 0, dst);
+        } else {
+            filt = vec_packsu(f16h, f16h);
+            vec_ste((vec_u32)filt, 0, (uint32_t*)dst);
+            if (w == 8)
+                vec_ste((vec_u32)filt, 4, (uint32_t*)dst);
+        }
+        src += src_stride;
+        dst += dst_stride;
+    }
+}
+
+// v subpel filter does a simple vertical multiply + add
+static const vec_u8 v_subpel_filters[7] =
+{
+    { 0,   6, 123,  12,   1,   0 },
+    { 2,  11, 108,  36,   8,   1 },
+    { 0,   9,  93,  50,   6,   0 },
+    { 3,  16,  77,  77,  16,   3 },
+    { 0,   6,  50,  93,   9,   0 },
+    { 1,   8,  36, 108,  11,   2 },
+    { 0,   1,  12, 123,   6,   0 },
+};
+
+#define LOAD_V_SUBPEL_FILTER(i) \
+    vec_u8 subpel_filter = v_subpel_filters[i]; \
+    vec_u8 f0 = vec_splat(subpel_filter, 0); \
+    vec_u8 f1 = vec_splat(subpel_filter, 1); \
+    vec_u8 f2 = vec_splat(subpel_filter, 2); \
+    vec_u8 f3 = vec_splat(subpel_filter, 3); \
+    vec_u8 f4 = vec_splat(subpel_filter, 4); \
+    vec_u8 f5 = vec_splat(subpel_filter, 5)
+
+#define FILTER_V(dstv, vec_mul) \
+    s1f = (vec_s16)vec_mul(s1, f1); \
+    s2f = (vec_s16)vec_mul(s2, f2); \
+    s3f = (vec_s16)vec_mul(s3, f3); \
+    s4f = (vec_s16)vec_mul(s4, f4); \
+    s2f = vec_subs(s2f, s1f); \
+    s3f = vec_subs(s3f, s4f); \
+    if (is6tap) { \
+        s0f = (vec_s16)vec_mul(s0, f0); \
+        s5f = (vec_s16)vec_mul(s5, f5); \
+        s2f = vec_adds(s2f, s0f); \
+        s3f = vec_adds(s3f, s5f); \
+    } \
+    dstv = vec_adds(s2f, s3f); \
+    dstv = vec_adds(dstv, c64); \
+    dstv = vec_sra(dstv, c7)
+
+static av_always_inline
+void put_vp8_epel_v_altivec_core(uint8_t *dst, int dst_stride,
+                                 uint8_t *src, int src_stride,
+                                 int h, int my, int w, int is6tap)
+{
+    LOAD_V_SUBPEL_FILTER(my-1);
+    vec_u8 s0, s1, s2, s3, s4, s5, filt, align_vech, perm_vec, align_vecl;
+    vec_s16 s0f, s1f, s2f, s3f, s4f, s5f, f16h, f16l;
+    vec_s16 c64 = vec_sl(vec_splat_s16(1), vec_splat_u16(6));
+    vec_u16 c7  = vec_splat_u16(7);
+
+    // we want pixels 0-7 to be in the even positions and 8-15 in the odd,
+    // so combine this permute with the alignment permute vector
+    align_vech = vec_lvsl(0, src);
+    align_vecl = vec_sld(align_vech, align_vech, 8);
+    if (w ==16)
+        perm_vec = vec_mergeh(align_vech, align_vecl);
+    else
+        perm_vec = vec_mergeh(align_vech, align_vech);
+
+    if (is6tap)
+        s0 = load_with_perm_vec(-2*src_stride, src, perm_vec);
+    s1 = load_with_perm_vec(-1*src_stride, src, perm_vec);
+    s2 = load_with_perm_vec( 0*src_stride, src, perm_vec);
+    s3 = load_with_perm_vec( 1*src_stride, src, perm_vec);
+    if (is6tap)
+        s4 = load_with_perm_vec( 2*src_stride, src, perm_vec);
+
+    src += (2+is6tap)*src_stride;
+
+    while (h --> 0) {
+        if (is6tap)
+            s5 = load_with_perm_vec(0, src, perm_vec);
+        else
+            s4 = load_with_perm_vec(0, src, perm_vec);
+
+        FILTER_V(f16h, vec_mule);
+
+        if (w == 16) {
+            FILTER_V(f16l, vec_mulo);
+            filt = vec_packsu(f16h, f16l);
+            vec_st(filt, 0, dst);
+        } else {
+            filt = vec_packsu(f16h, f16h);
+            if (w == 4)
+                filt = (vec_u8)vec_splat((vec_u32)filt, 0);
+            else
+                vec_ste((vec_u32)filt, 4, (uint32_t*)dst);
+            vec_ste((vec_u32)filt, 0, (uint32_t*)dst);
+        }
+
+        if (is6tap)
+            s0 = s1;
+        s1 = s2;
+        s2 = s3;
+        s3 = s4;
+        if (is6tap)
+            s4 = s5;
+
+        dst += dst_stride;
+        src += src_stride;
+    }
+}
+
+#define EPEL_FUNCS(WIDTH, TAPS) \
+static av_noinline \
+void put_vp8_epel ## WIDTH ## _h ## TAPS ## _altivec(uint8_t *dst, int dst_stride, uint8_t *src, int src_stride, int h, int mx, int my) \
+{ \
+    put_vp8_epel_h_altivec_core(dst, dst_stride, src, src_stride, h, mx, WIDTH, TAPS == 6); \
+} \
+\
+static av_noinline \
+void put_vp8_epel ## WIDTH ## _v ## TAPS ## _altivec(uint8_t *dst, int dst_stride, uint8_t *src, int src_stride, int h, int mx, int my) \
+{ \
+    put_vp8_epel_v_altivec_core(dst, dst_stride, src, src_stride, h, my, WIDTH, TAPS == 6); \
+}
+
+#define EPEL_HV(WIDTH, HTAPS, VTAPS) \
+static void put_vp8_epel ## WIDTH ## _h ## HTAPS ## v ## VTAPS ## _altivec(uint8_t *dst, int stride, uint8_t *src, int s, int h, int mx, int my) \
+{ \
+    DECLARE_ALIGNED(16, uint8_t, tmp)[(2*WIDTH+5)*16]; \
+    if (VTAPS == 6) { \
+        put_vp8_epel ## WIDTH ## _h ## HTAPS ## _altivec(tmp, 16,     src-2*stride, stride, h+5, mx, my); \
+        put_vp8_epel ## WIDTH ## _v ## VTAPS ## _altivec(dst, stride, tmp+2*16,     16,     h,   mx, my); \
+    } else { \
+        put_vp8_epel ## WIDTH ## _h ## HTAPS ## _altivec(tmp, 16,     src-stride, stride, h+4, mx, my); \
+        put_vp8_epel ## WIDTH ## _v ## VTAPS ## _altivec(dst, stride, tmp+16,     16,     h,   mx, my); \
+    } \
+}
+
+EPEL_FUNCS(16,6)
+EPEL_FUNCS(8, 6)
+EPEL_FUNCS(8, 4)
+EPEL_FUNCS(4, 6)
+EPEL_FUNCS(4, 4)
+
+EPEL_HV(16, 6,6)
+EPEL_HV(8,  6,6)
+EPEL_HV(8,  4,6)
+EPEL_HV(8,  6,4)
+EPEL_HV(8,  4,4)
+EPEL_HV(4,  6,6)
+EPEL_HV(4,  4,6)
+EPEL_HV(4,  6,4)
+EPEL_HV(4,  4,4)
+
+static void put_vp8_pixels16_altivec(uint8_t *dst, int stride, uint8_t *src, int s, int h, int mx, int my)
+{
+    put_pixels16_altivec(dst, src, stride, h);
+}
+
+av_cold void ff_vp8dsp_init_altivec(VP8DSPContext *c)
+{
+    if (!(av_get_cpu_flags() & AV_CPU_FLAG_ALTIVEC))
+        return;
+
+    c->put_vp8_epel_pixels_tab[0][0][0] = put_vp8_pixels16_altivec;
+    c->put_vp8_epel_pixels_tab[0][0][2] = put_vp8_epel16_h6_altivec;
+    c->put_vp8_epel_pixels_tab[0][2][0] = put_vp8_epel16_v6_altivec;
+    c->put_vp8_epel_pixels_tab[0][2][2] = put_vp8_epel16_h6v6_altivec;
+
+    c->put_vp8_epel_pixels_tab[1][0][2] = put_vp8_epel8_h6_altivec;
+    c->put_vp8_epel_pixels_tab[1][2][0] = put_vp8_epel8_v6_altivec;
+    c->put_vp8_epel_pixels_tab[1][0][1] = put_vp8_epel8_h4_altivec;
+    c->put_vp8_epel_pixels_tab[1][1][0] = put_vp8_epel8_v4_altivec;
+
+    c->put_vp8_epel_pixels_tab[1][2][2] = put_vp8_epel8_h6v6_altivec;
+    c->put_vp8_epel_pixels_tab[1][1][1] = put_vp8_epel8_h4v4_altivec;
+    c->put_vp8_epel_pixels_tab[1][1][2] = put_vp8_epel8_h6v4_altivec;
+    c->put_vp8_epel_pixels_tab[1][2][1] = put_vp8_epel8_h4v6_altivec;
+
+    c->put_vp8_epel_pixels_tab[2][0][2] = put_vp8_epel4_h6_altivec;
+    c->put_vp8_epel_pixels_tab[2][2][0] = put_vp8_epel4_v6_altivec;
+    c->put_vp8_epel_pixels_tab[2][0][1] = put_vp8_epel4_h4_altivec;
+    c->put_vp8_epel_pixels_tab[2][1][0] = put_vp8_epel4_v4_altivec;
+
+    c->put_vp8_epel_pixels_tab[2][2][2] = put_vp8_epel4_h6v6_altivec;
+    c->put_vp8_epel_pixels_tab[2][1][1] = put_vp8_epel4_h4v4_altivec;
+    c->put_vp8_epel_pixels_tab[2][1][2] = put_vp8_epel4_h6v4_altivec;
+    c->put_vp8_epel_pixels_tab[2][2][1] = put_vp8_epel4_h4v6_altivec;
+}
diff --git a/libavcodec/ps2/dsputil_mmi.c b/libavcodec/ps2/dsputil_mmi.c
index 15b5b56..b6096b3 100644
--- a/libavcodec/ps2/dsputil_mmi.c
+++ b/libavcodec/ps2/dsputil_mmi.c
@@ -5,20 +5,20 @@
  * MMI optimization by Leon van Stuivenberg
  * clear_blocks_mmi() by BroadQ
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/ps2/idct_mmi.c b/libavcodec/ps2/idct_mmi.c
index bfe362a..86df092 100644
--- a/libavcodec/ps2/idct_mmi.c
+++ b/libavcodec/ps2/idct_mmi.c
@@ -8,20 +8,20 @@
  *
  * MMI port and (c) 2002 by Leon van Stuivenberg
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/ps2/mmi.h b/libavcodec/ps2/mmi.h
index 0265456..fc8d328 100644
--- a/libavcodec/ps2/mmi.h
+++ b/libavcodec/ps2/mmi.h
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2002 Leon van Stuivenberg
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/ps2/mpegvideo_mmi.c b/libavcodec/ps2/mpegvideo_mmi.c
index 68c3b0d..ed56893 100644
--- a/libavcodec/ps2/mpegvideo_mmi.c
+++ b/libavcodec/ps2/mpegvideo_mmi.c
@@ -3,20 +3,20 @@
  *
  * MMI optimization by Leon van Stuivenberg
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/psymodel.c b/libavcodec/psymodel.c
index f87dbcf..a943ae1 100644
--- a/libavcodec/psymodel.c
+++ b/libavcodec/psymodel.c
@@ -2,20 +2,20 @@
  * audio encoder psychoacoustic model
  * Copyright (C) 2008 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -53,7 +53,7 @@ FFPsyWindowInfo ff_psy_suggest_window(FFPsyContext *ctx,
 }
 
 void ff_psy_set_band_info(FFPsyContext *ctx, int channel,
-                          const float *coeffs, FFPsyWindowInfo *wi)
+                          const float *coeffs, const FFPsyWindowInfo *wi)
 {
     ctx->model->analyze(ctx, channel, coeffs, wi);
 }
@@ -88,8 +88,9 @@ av_cold struct FFPsyPreprocessContext* ff_psy_preprocess_init(AVCodecContext *av
         cutoff_coeff = 2.0 * avctx->cutoff / avctx->sample_rate;
 
     if (cutoff_coeff)
-    ctx->fcoeffs = ff_iir_filter_init_coeffs(FF_FILTER_TYPE_BUTTERWORTH, FF_FILTER_MODE_LOWPASS,
-                                             FILT_ORDER, cutoff_coeff, 0.0, 0.0);
+    ctx->fcoeffs = ff_iir_filter_init_coeffs(avctx, FF_FILTER_TYPE_BUTTERWORTH,
+                                             FF_FILTER_MODE_LOWPASS, FILT_ORDER,
+                                             cutoff_coeff, 0.0, 0.0);
     if (ctx->fcoeffs) {
         ctx->fstate = av_mallocz(sizeof(ctx->fstate[0]) * avctx->channels);
         for (i = 0; i < avctx->channels; i++)
@@ -123,5 +124,6 @@ av_cold void ff_psy_preprocess_end(struct FFPsyPreprocessContext *ctx)
         for (i = 0; i < ctx->avctx->channels; i++)
             ff_iir_filter_free_state(ctx->fstate[i]);
     av_freep(&ctx->fstate);
+    av_free(ctx);
 }
 
diff --git a/libavcodec/psymodel.h b/libavcodec/psymodel.h
index bc19d49..91eb9ae 100644
--- a/libavcodec/psymodel.h
+++ b/libavcodec/psymodel.h
@@ -2,20 +2,20 @@
  * audio encoder psychoacoustic model
  * Copyright (C) 2008 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -26,6 +26,8 @@
 
 /** maximum possible number of bands */
 #define PSY_MAX_BANDS 128
+/** maximum number of channels */
+#define PSY_MAX_CHANS 20
 
 /**
  * single band psychoacoustic information
@@ -62,6 +64,13 @@ typedef struct FFPsyContext {
     int     *num_bands;               ///< number of scalefactor bands for possible frame sizes
     int num_lens;                     ///< number of scalefactor band sets
 
+    float pe[PSY_MAX_CHANS];          ///< total PE for each channel in the frame
+
+    struct {
+        int size;                     ///< size of the bitresevoir in bits
+        int bits;                     ///< number of bits used in the bitresevoir
+    } bitres;
+
     void* model_priv_data;            ///< psychoacoustic model implementation private data
 } FFPsyContext;
 
@@ -72,7 +81,7 @@ typedef struct FFPsyModel {
     const char *name;
     int  (*init)   (FFPsyContext *apc);
     FFPsyWindowInfo (*window)(FFPsyContext *ctx, const int16_t *audio, const int16_t *la, int channel, int prev_type);
-    void (*analyze)(FFPsyContext *ctx, int channel, const float *coeffs, FFPsyWindowInfo *wi);
+    void (*analyze)(FFPsyContext *ctx, int channel, const float *coeffs, const FFPsyWindowInfo *wi);
     void (*end)    (FFPsyContext *apc);
 } FFPsyModel;
 
@@ -116,7 +125,7 @@ FFPsyWindowInfo ff_psy_suggest_window(FFPsyContext *ctx,
  * @param wi      window information
  */
 void ff_psy_set_band_info(FFPsyContext *ctx, int channel, const float *coeffs,
-                          FFPsyWindowInfo *wi);
+                          const FFPsyWindowInfo *wi);
 
 /**
  * Cleanup model context at the end.
diff --git a/libavcodec/pthread.c b/libavcodec/pthread.c
index 1628b21..ba6e395 100644
--- a/libavcodec/pthread.c
+++ b/libavcodec/pthread.c
@@ -1,29 +1,38 @@
 /*
  * Copyright (c) 2004 Roman Shaposhnik
+ * Copyright (c) 2008 Alexander Strange (astrange at ithinksw.com)
  *
  * Many thanks to Steven M. Schultz for providing clever ideas and
  * to Michael Niedermayer <michaelni at gmx.at> for writing initial
  * implementation.
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
+
+/**
+ * @file
+ * Multithreading support functions
+ * @see doc/multithreading.txt
+ */
+
 #include <pthread.h>
 
 #include "avcodec.h"
+#include "thread.h"
 
 typedef int (action_func)(AVCodecContext *c, void *arg);
 typedef int (action_func2)(AVCodecContext *c, void *arg, int jobnr, int threadnr);
@@ -45,6 +54,78 @@ typedef struct ThreadContext {
     int done;
 } ThreadContext;
 
+/// Max number of frame buffers that can be allocated when using frame threads.
+#define MAX_BUFFERS 32
+
+/**
+ * Context used by codec threads and stored in their AVCodecContext thread_opaque.
+ */
+typedef struct PerThreadContext {
+    struct FrameThreadContext *parent;
+
+    pthread_t      thread;
+    pthread_cond_t input_cond;      ///< Used to wait for a new packet from the main thread.
+    pthread_cond_t progress_cond;   ///< Used by child threads to wait for progress to change.
+    pthread_cond_t output_cond;     ///< Used by the main thread to wait for frames to finish.
+
+    pthread_mutex_t mutex;          ///< Mutex used to protect the contents of the PerThreadContext.
+    pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
+
+    AVCodecContext *avctx;          ///< Context used to decode packets passed to this thread.
+
+    AVPacket       avpkt;           ///< Input packet (for decoding) or output (for encoding).
+    int            allocated_buf_size; ///< Size allocated for avpkt.data
+
+    AVFrame frame;                  ///< Output frame (for decoding) or input (for encoding).
+    int     got_frame;              ///< The output of got_picture_ptr from the last avcodec_decode_video() call.
+    int     result;                 ///< The result of the last codec decode/encode() call.
+
+    enum {
+        STATE_INPUT_READY,          ///< Set when the thread is awaiting a packet.
+        STATE_SETTING_UP,           ///< Set before the codec has called ff_thread_finish_setup().
+        STATE_GET_BUFFER,           /**<
+                                     * Set when the codec calls get_buffer().
+                                     * State is returned to STATE_SETTING_UP afterwards.
+                                     */
+        STATE_SETUP_FINISHED        ///< Set after the codec has called ff_thread_finish_setup().
+    } state;
+
+    /**
+     * Array of frames passed to ff_thread_release_buffer().
+     * Frames are released after all threads referencing them are finished.
+     */
+    AVFrame released_buffers[MAX_BUFFERS];
+    int     num_released_buffers;
+
+    /**
+     * Array of progress values used by ff_thread_get_buffer().
+     */
+    int     progress[MAX_BUFFERS][2];
+    uint8_t progress_used[MAX_BUFFERS];
+
+    AVFrame *requested_frame;       ///< AVFrame the codec passed to get_buffer()
+} PerThreadContext;
+
+/**
+ * Context stored in the client AVCodecContext thread_opaque.
+ */
+typedef struct FrameThreadContext {
+    PerThreadContext *threads;     ///< The contexts for each thread.
+    PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
+
+    pthread_mutex_t buffer_mutex;  ///< Mutex used to protect get/release_buffer().
+
+    int next_decoding;             ///< The next context to submit a packet to.
+    int next_finished;             ///< The next context to return output from.
+
+    int delaying;                  /**<
+                                    * Set for the first N packets, where N is the number of threads.
+                                    * While it is set, ff_thread_en/decode_frame won't return any results.
+                                    */
+
+    int die;                       ///< Set when threads should exit.
+} FrameThreadContext;
+
 static void* attribute_align_arg worker(void *v)
 {
     AVCodecContext *avctx = v;
@@ -84,7 +165,7 @@ static av_always_inline void avcodec_thread_park_workers(ThreadContext *c, int t
     pthread_mutex_unlock(&c->current_job_lock);
 }
 
-void avcodec_thread_free(AVCodecContext *avctx)
+static void thread_free(AVCodecContext *avctx)
 {
     ThreadContext *c = avctx->thread_opaque;
     int i;
@@ -109,6 +190,9 @@ static int avcodec_thread_execute(AVCodecContext *avctx, action_func* func, void
     ThreadContext *c= avctx->thread_opaque;
     int dummy_ret;
 
+    if (!(avctx->active_thread_type&FF_THREAD_SLICE) || avctx->thread_count <= 1)
+        return avcodec_default_execute(avctx, func, arg, ret, job_count, job_size);
+
     if (job_count <= 0)
         return 0;
 
@@ -140,12 +224,11 @@ static int avcodec_thread_execute2(AVCodecContext *avctx, action_func2* func2, v
     return avcodec_thread_execute(avctx, NULL, arg, ret, job_count, 0);
 }
 
-int avcodec_thread_init(AVCodecContext *avctx, int thread_count)
+static int thread_init(AVCodecContext *avctx)
 {
     int i;
     ThreadContext *c;
-
-    avctx->thread_count = thread_count;
+    int thread_count = avctx->thread_count;
 
     if (thread_count <= 1)
         return 0;
@@ -173,7 +256,7 @@ int avcodec_thread_init(AVCodecContext *avctx, int thread_count)
         if(pthread_create(&c->workers[i], NULL, worker, avctx)) {
            avctx->thread_count = i;
            pthread_mutex_unlock(&c->current_job_lock);
-           avcodec_thread_free(avctx);
+           ff_thread_free(avctx);
            return -1;
         }
     }
@@ -184,3 +267,644 @@ int avcodec_thread_init(AVCodecContext *avctx, int thread_count)
     avctx->execute2 = avcodec_thread_execute2;
     return 0;
 }
+
+/**
+ * Codec worker thread.
+ *
+ * Automatically calls ff_thread_finish_setup() if the codec does
+ * not provide an update_thread_context method, or if the codec returns
+ * before calling it.
+ */
+static attribute_align_arg void *frame_worker_thread(void *arg)
+{
+    PerThreadContext *p = arg;
+    FrameThreadContext *fctx = p->parent;
+    AVCodecContext *avctx = p->avctx;
+    AVCodec *codec = avctx->codec;
+
+    while (1) {
+        if (p->state == STATE_INPUT_READY && !fctx->die) {
+            pthread_mutex_lock(&p->mutex);
+            while (p->state == STATE_INPUT_READY && !fctx->die)
+                pthread_cond_wait(&p->input_cond, &p->mutex);
+            pthread_mutex_unlock(&p->mutex);
+        }
+
+        if (fctx->die) break;
+
+        if (!codec->update_thread_context && avctx->thread_safe_callbacks)
+            ff_thread_finish_setup(avctx);
+
+        pthread_mutex_lock(&p->mutex);
+        avcodec_get_frame_defaults(&p->frame);
+        p->got_frame = 0;
+        p->result = codec->decode(avctx, &p->frame, &p->got_frame, &p->avpkt);
+
+        if (p->state == STATE_SETTING_UP) ff_thread_finish_setup(avctx);
+
+        p->state = STATE_INPUT_READY;
+
+        pthread_mutex_lock(&p->progress_mutex);
+        pthread_cond_signal(&p->output_cond);
+        pthread_mutex_unlock(&p->progress_mutex);
+
+        pthread_mutex_unlock(&p->mutex);
+    }
+
+    return NULL;
+}
+
+/**
+ * Updates the next thread's AVCodecContext with values from the reference thread's context.
+ *
+ * @param dst The destination context.
+ * @param src The source context.
+ * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
+ */
+static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
+{
+    int err = 0;
+
+    if (dst != src) {
+        dst->sub_id    = src->sub_id;
+        dst->time_base = src->time_base;
+        dst->width     = src->width;
+        dst->height    = src->height;
+        dst->pix_fmt   = src->pix_fmt;
+
+        dst->has_b_frames = src->has_b_frames;
+        dst->idct_algo    = src->idct_algo;
+        dst->slice_count  = src->slice_count;
+
+        dst->bits_per_coded_sample = src->bits_per_coded_sample;
+        dst->sample_aspect_ratio   = src->sample_aspect_ratio;
+        dst->dtg_active_format     = src->dtg_active_format;
+
+        dst->profile = src->profile;
+        dst->level   = src->level;
+
+        dst->bits_per_raw_sample = src->bits_per_raw_sample;
+        dst->ticks_per_frame     = src->ticks_per_frame;
+        dst->color_primaries     = src->color_primaries;
+
+        dst->color_trc   = src->color_trc;
+        dst->colorspace  = src->colorspace;
+        dst->color_range = src->color_range;
+        dst->chroma_sample_location = src->chroma_sample_location;
+    }
+
+    if (for_user) {
+        dst->coded_frame   = src->coded_frame;
+        dst->has_b_frames += src->thread_count - 1;
+    } else {
+        if (dst->codec->update_thread_context)
+            err = dst->codec->update_thread_context(dst, src);
+    }
+
+    return err;
+}
+
+/**
+ * Update the next thread's AVCodecContext with values set by the user.
+ *
+ * @param dst The destination context.
+ * @param src The source context.
+ */
+static void update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
+{
+#define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
+    dst->flags          = src->flags;
+
+    dst->draw_horiz_band= src->draw_horiz_band;
+    dst->get_buffer     = src->get_buffer;
+    dst->release_buffer = src->release_buffer;
+
+    dst->opaque   = src->opaque;
+#if FF_API_HURRY_UP
+    dst->hurry_up = src->hurry_up;
+#endif
+    dst->dsp_mask = src->dsp_mask;
+    dst->debug    = src->debug;
+    dst->debug_mv = src->debug_mv;
+
+    dst->slice_flags = src->slice_flags;
+    dst->flags2      = src->flags2;
+
+    copy_fields(skip_loop_filter, bidir_refine);
+
+    dst->frame_number     = src->frame_number;
+    dst->reordered_opaque = src->reordered_opaque;
+#undef copy_fields
+}
+
+static void free_progress(AVFrame *f)
+{
+    PerThreadContext *p = f->owner->thread_opaque;
+    int *progress = f->thread_opaque;
+
+    p->progress_used[(progress - p->progress[0]) / 2] = 0;
+}
+
+/// Releases the buffers that this decoding thread was the last user of.
+static void release_delayed_buffers(PerThreadContext *p)
+{
+    FrameThreadContext *fctx = p->parent;
+
+    while (p->num_released_buffers > 0) {
+        AVFrame *f = &p->released_buffers[--p->num_released_buffers];
+
+        pthread_mutex_lock(&fctx->buffer_mutex);
+        free_progress(f);
+        f->thread_opaque = NULL;
+
+        f->owner->release_buffer(f->owner, f);
+        pthread_mutex_unlock(&fctx->buffer_mutex);
+    }
+}
+
+static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
+{
+    FrameThreadContext *fctx = p->parent;
+    PerThreadContext *prev_thread = fctx->prev_thread;
+    AVCodec *codec = p->avctx->codec;
+    uint8_t *buf = p->avpkt.data;
+
+    if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
+
+    pthread_mutex_lock(&p->mutex);
+
+    release_delayed_buffers(p);
+
+    if (prev_thread) {
+        int err;
+        if (prev_thread->state == STATE_SETTING_UP) {
+            pthread_mutex_lock(&prev_thread->progress_mutex);
+            while (prev_thread->state == STATE_SETTING_UP)
+                pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
+            pthread_mutex_unlock(&prev_thread->progress_mutex);
+        }
+
+        err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
+        if (err) {
+            pthread_mutex_unlock(&p->mutex);
+            return err;
+        }
+    }
+
+    av_fast_malloc(&buf, &p->allocated_buf_size, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
+    p->avpkt = *avpkt;
+    p->avpkt.data = buf;
+    memcpy(buf, avpkt->data, avpkt->size);
+    memset(buf + avpkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
+
+    p->state = STATE_SETTING_UP;
+    pthread_cond_signal(&p->input_cond);
+    pthread_mutex_unlock(&p->mutex);
+
+    /*
+     * If the client doesn't have a thread-safe get_buffer(),
+     * then decoding threads call back to the main thread,
+     * and it calls back to the client here.
+     */
+
+    if (!p->avctx->thread_safe_callbacks &&
+         p->avctx->get_buffer != avcodec_default_get_buffer) {
+        while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
+            pthread_mutex_lock(&p->progress_mutex);
+            while (p->state == STATE_SETTING_UP)
+                pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
+
+            if (p->state == STATE_GET_BUFFER) {
+                p->result = p->avctx->get_buffer(p->avctx, p->requested_frame);
+                p->state  = STATE_SETTING_UP;
+                pthread_cond_signal(&p->progress_cond);
+            }
+            pthread_mutex_unlock(&p->progress_mutex);
+        }
+    }
+
+    fctx->prev_thread = p;
+
+    return 0;
+}
+
+int ff_thread_decode_frame(AVCodecContext *avctx,
+                           AVFrame *picture, int *got_picture_ptr,
+                           AVPacket *avpkt)
+{
+    FrameThreadContext *fctx = avctx->thread_opaque;
+    int finished = fctx->next_finished;
+    PerThreadContext *p;
+    int err;
+
+    /*
+     * Submit a packet to the next decoding thread.
+     */
+
+    p = &fctx->threads[fctx->next_decoding];
+    update_context_from_user(p->avctx, avctx);
+    err = submit_packet(p, avpkt);
+    if (err) return err;
+
+    fctx->next_decoding++;
+
+    /*
+     * If we're still receiving the initial packets, don't return a frame.
+     */
+
+    if (fctx->delaying && avpkt->size) {
+        if (fctx->next_decoding >= (avctx->thread_count-1)) fctx->delaying = 0;
+
+        *got_picture_ptr=0;
+        return 0;
+    }
+
+    /*
+     * Return the next available frame from the oldest thread.
+     * If we're at the end of the stream, then we have to skip threads that
+     * didn't output a frame, because we don't want to accidentally signal
+     * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
+     */
+
+    do {
+        p = &fctx->threads[finished++];
+
+        if (p->state != STATE_INPUT_READY) {
+            pthread_mutex_lock(&p->progress_mutex);
+            while (p->state != STATE_INPUT_READY)
+                pthread_cond_wait(&p->output_cond, &p->progress_mutex);
+            pthread_mutex_unlock(&p->progress_mutex);
+        }
+
+        *picture = p->frame;
+        *got_picture_ptr = p->got_frame;
+        picture->pkt_dts = p->avpkt.dts;
+
+        /*
+         * A later call with avkpt->size == 0 may loop over all threads,
+         * including this one, searching for a frame to return before being
+         * stopped by the "finished != fctx->next_finished" condition.
+         * Make sure we don't mistakenly return the same frame again.
+         */
+        p->got_frame = 0;
+
+        if (finished >= avctx->thread_count) finished = 0;
+    } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
+
+    update_context_from_thread(avctx, p->avctx, 1);
+
+    if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
+
+    fctx->next_finished = finished;
+
+    return p->result;
+}
+
+void ff_thread_report_progress(AVFrame *f, int n, int field)
+{
+    PerThreadContext *p;
+    int *progress = f->thread_opaque;
+
+    if (!progress || progress[field] >= n) return;
+
+    p = f->owner->thread_opaque;
+
+    if (f->owner->debug&FF_DEBUG_THREADS)
+        av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
+
+    pthread_mutex_lock(&p->progress_mutex);
+    progress[field] = n;
+    pthread_cond_broadcast(&p->progress_cond);
+    pthread_mutex_unlock(&p->progress_mutex);
+}
+
+void ff_thread_await_progress(AVFrame *f, int n, int field)
+{
+    PerThreadContext *p;
+    int *progress = f->thread_opaque;
+
+    if (!progress || progress[field] >= n) return;
+
+    p = f->owner->thread_opaque;
+
+    if (f->owner->debug&FF_DEBUG_THREADS)
+        av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
+
+    pthread_mutex_lock(&p->progress_mutex);
+    while (progress[field] < n)
+        pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
+    pthread_mutex_unlock(&p->progress_mutex);
+}
+
+void ff_thread_finish_setup(AVCodecContext *avctx) {
+    PerThreadContext *p = avctx->thread_opaque;
+
+    if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
+
+    pthread_mutex_lock(&p->progress_mutex);
+    p->state = STATE_SETUP_FINISHED;
+    pthread_cond_broadcast(&p->progress_cond);
+    pthread_mutex_unlock(&p->progress_mutex);
+}
+
+/// Waits for all threads to finish.
+static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
+{
+    int i;
+
+    for (i = 0; i < thread_count; i++) {
+        PerThreadContext *p = &fctx->threads[i];
+
+        if (p->state != STATE_INPUT_READY) {
+            pthread_mutex_lock(&p->progress_mutex);
+            while (p->state != STATE_INPUT_READY)
+                pthread_cond_wait(&p->output_cond, &p->progress_mutex);
+            pthread_mutex_unlock(&p->progress_mutex);
+        }
+    }
+}
+
+static void frame_thread_free(AVCodecContext *avctx, int thread_count)
+{
+    FrameThreadContext *fctx = avctx->thread_opaque;
+    AVCodec *codec = avctx->codec;
+    int i;
+
+    park_frame_worker_threads(fctx, thread_count);
+
+    if (fctx->prev_thread)
+        update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0);
+
+    fctx->die = 1;
+
+    for (i = 0; i < thread_count; i++) {
+        PerThreadContext *p = &fctx->threads[i];
+
+        pthread_mutex_lock(&p->mutex);
+        pthread_cond_signal(&p->input_cond);
+        pthread_mutex_unlock(&p->mutex);
+
+        pthread_join(p->thread, NULL);
+
+        if (codec->close)
+            codec->close(p->avctx);
+
+        avctx->codec = NULL;
+
+        release_delayed_buffers(p);
+    }
+
+    for (i = 0; i < thread_count; i++) {
+        PerThreadContext *p = &fctx->threads[i];
+
+        avcodec_default_free_buffers(p->avctx);
+
+        pthread_mutex_destroy(&p->mutex);
+        pthread_mutex_destroy(&p->progress_mutex);
+        pthread_cond_destroy(&p->input_cond);
+        pthread_cond_destroy(&p->progress_cond);
+        pthread_cond_destroy(&p->output_cond);
+        av_freep(&p->avpkt.data);
+
+        if (i)
+            av_freep(&p->avctx->priv_data);
+
+        av_freep(&p->avctx);
+    }
+
+    av_freep(&fctx->threads);
+    pthread_mutex_destroy(&fctx->buffer_mutex);
+    av_freep(&avctx->thread_opaque);
+}
+
+static int frame_thread_init(AVCodecContext *avctx)
+{
+    int thread_count = avctx->thread_count;
+    AVCodec *codec = avctx->codec;
+    AVCodecContext *src = avctx;
+    FrameThreadContext *fctx;
+    int i, err = 0;
+
+    if (thread_count <= 1) {
+        avctx->active_thread_type = 0;
+        return 0;
+    }
+
+    avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
+
+    fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
+    pthread_mutex_init(&fctx->buffer_mutex, NULL);
+    fctx->delaying = 1;
+
+    for (i = 0; i < thread_count; i++) {
+        AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
+        PerThreadContext *p  = &fctx->threads[i];
+
+        pthread_mutex_init(&p->mutex, NULL);
+        pthread_mutex_init(&p->progress_mutex, NULL);
+        pthread_cond_init(&p->input_cond, NULL);
+        pthread_cond_init(&p->progress_cond, NULL);
+        pthread_cond_init(&p->output_cond, NULL);
+
+        p->parent = fctx;
+        p->avctx  = copy;
+
+        *copy = *src;
+        copy->thread_opaque = p;
+        copy->pkt = &p->avpkt;
+
+        if (!i) {
+            src = copy;
+
+            if (codec->init)
+                err = codec->init(copy);
+
+            update_context_from_thread(avctx, copy, 1);
+        } else {
+            copy->is_copy   = 1;
+            copy->priv_data = av_malloc(codec->priv_data_size);
+            memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
+
+            if (codec->init_thread_copy)
+                err = codec->init_thread_copy(copy);
+        }
+
+        if (err) goto error;
+
+        pthread_create(&p->thread, NULL, frame_worker_thread, p);
+    }
+
+    return 0;
+
+error:
+    frame_thread_free(avctx, i+1);
+
+    return err;
+}
+
+void ff_thread_flush(AVCodecContext *avctx)
+{
+    FrameThreadContext *fctx = avctx->thread_opaque;
+
+    if (!avctx->thread_opaque) return;
+
+    park_frame_worker_threads(fctx, avctx->thread_count);
+
+    if (fctx->prev_thread)
+        update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0);
+
+    fctx->next_decoding = fctx->next_finished = 0;
+    fctx->delaying = 1;
+    fctx->prev_thread = NULL;
+}
+
+static int *allocate_progress(PerThreadContext *p)
+{
+    int i;
+
+    for (i = 0; i < MAX_BUFFERS; i++)
+        if (!p->progress_used[i]) break;
+
+    if (i == MAX_BUFFERS) {
+        av_log(p->avctx, AV_LOG_ERROR, "allocate_progress() overflow\n");
+        return NULL;
+    }
+
+    p->progress_used[i] = 1;
+
+    return p->progress[i];
+}
+
+int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f)
+{
+    PerThreadContext *p = avctx->thread_opaque;
+    int *progress, err;
+
+    f->owner = avctx;
+
+    if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
+        f->thread_opaque = NULL;
+        return avctx->get_buffer(avctx, f);
+    }
+
+    if (p->state != STATE_SETTING_UP &&
+        (avctx->codec->update_thread_context || !avctx->thread_safe_callbacks)) {
+        av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
+        return -1;
+    }
+
+    pthread_mutex_lock(&p->parent->buffer_mutex);
+    f->thread_opaque = progress = allocate_progress(p);
+
+    if (!progress) {
+        pthread_mutex_unlock(&p->parent->buffer_mutex);
+        return -1;
+    }
+
+    progress[0] =
+    progress[1] = -1;
+
+    if (avctx->thread_safe_callbacks ||
+        avctx->get_buffer == avcodec_default_get_buffer) {
+        err = avctx->get_buffer(avctx, f);
+    } else {
+        p->requested_frame = f;
+        p->state = STATE_GET_BUFFER;
+        pthread_mutex_lock(&p->progress_mutex);
+        pthread_cond_signal(&p->progress_cond);
+
+        while (p->state != STATE_SETTING_UP)
+            pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
+
+        err = p->result;
+
+        pthread_mutex_unlock(&p->progress_mutex);
+
+        if (!avctx->codec->update_thread_context)
+            ff_thread_finish_setup(avctx);
+    }
+
+    pthread_mutex_unlock(&p->parent->buffer_mutex);
+
+    /*
+     * Buffer age is difficult to keep track of between
+     * multiple threads, and the optimizations it allows
+     * are not worth the effort. It is disabled for now.
+     */
+    f->age = INT_MAX;
+
+    return err;
+}
+
+void ff_thread_release_buffer(AVCodecContext *avctx, AVFrame *f)
+{
+    PerThreadContext *p = avctx->thread_opaque;
+
+    if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
+        avctx->release_buffer(avctx, f);
+        return;
+    }
+
+    if (p->num_released_buffers >= MAX_BUFFERS) {
+        av_log(p->avctx, AV_LOG_ERROR, "too many thread_release_buffer calls!\n");
+        return;
+    }
+
+    if(avctx->debug & FF_DEBUG_BUFFERS)
+        av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p, %d buffers used\n",
+                                    f, f->owner->internal_buffer_count);
+
+    p->released_buffers[p->num_released_buffers++] = *f;
+    memset(f->data, 0, sizeof(f->data));
+}
+
+/**
+ * Set the threading algorithms used.
+ *
+ * Threading requires more than one thread.
+ * Frame threading requires entire frames to be passed to the codec,
+ * and introduces extra decoding delay, so is incompatible with low_delay.
+ *
+ * @param avctx The context.
+ */
+static void validate_thread_parameters(AVCodecContext *avctx)
+{
+    int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
+                                && !(avctx->flags & CODEC_FLAG_TRUNCATED)
+                                && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
+                                && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
+    if (avctx->thread_count == 1) {
+        avctx->active_thread_type = 0;
+    } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
+        avctx->active_thread_type = FF_THREAD_FRAME;
+    } else if (avctx->thread_type & FF_THREAD_SLICE) {
+        avctx->active_thread_type = FF_THREAD_SLICE;
+    }
+}
+
+int ff_thread_init(AVCodecContext *avctx)
+{
+    if (avctx->thread_opaque) {
+        av_log(avctx, AV_LOG_ERROR, "avcodec_thread_init is ignored after avcodec_open\n");
+        return -1;
+    }
+
+    if (avctx->codec) {
+        validate_thread_parameters(avctx);
+
+        if (avctx->active_thread_type&FF_THREAD_SLICE)
+            return thread_init(avctx);
+        else if (avctx->active_thread_type&FF_THREAD_FRAME)
+            return frame_thread_init(avctx);
+    }
+
+    return 0;
+}
+
+void ff_thread_free(AVCodecContext *avctx)
+{
+    if (avctx->active_thread_type&FF_THREAD_FRAME)
+        frame_thread_free(avctx, avctx->thread_count);
+    else
+        thread_free(avctx);
+}
diff --git a/libavcodec/ptx.c b/libavcodec/ptx.c
index d8798f2..94f1656 100644
--- a/libavcodec/ptx.c
+++ b/libavcodec/ptx.c
@@ -2,24 +2,25 @@
  * V.Flash PTX (.ptx) image decoder
  * Copyright (c) 2007 Ivo van Poorten
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "libavutil/intreadwrite.h"
+#include "libavutil/imgutils.h"
 #include "avcodec.h"
 
 typedef struct PTXContext {
@@ -50,21 +51,21 @@ static int ptx_decode_frame(AVCodecContext *avctx, void *data, int *data_size,
     bytes_per_pixel = AV_RL16(buf+12) >> 3;
 
     if (bytes_per_pixel != 2) {
-        av_log(avctx, AV_LOG_ERROR, "image format is not rgb15, please report on ffmpeg-users mailing list\n");
+        av_log_ask_for_sample(avctx, "Image format is not RGB15.\n");
         return -1;
     }
 
     avctx->pix_fmt = PIX_FMT_RGB555;
 
     if (offset != 0x2c)
-        av_log(avctx, AV_LOG_WARNING, "offset != 0x2c, untested due to lack of sample files\n");
+        av_log_ask_for_sample(avctx, "offset != 0x2c\n");
 
     buf += offset;
 
     if (p->data[0])
         avctx->release_buffer(avctx, p);
 
-    if (avcodec_check_dimensions(avctx, w, h))
+    if (av_image_check_size(w, h, 0, avctx))
         return -1;
     if (w != avctx->width || h != avctx->height)
         avcodec_set_dimensions(avctx, w, h);
@@ -105,7 +106,7 @@ static av_cold int ptx_end(AVCodecContext *avctx) {
     return 0;
 }
 
-AVCodec ptx_decoder = {
+AVCodec ff_ptx_decoder = {
     "ptx",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_PTX,
diff --git a/libavcodec/put_bits.h b/libavcodec/put_bits.h
index 80a514d..c426540 100644
--- a/libavcodec/put_bits.h
+++ b/libavcodec/put_bits.h
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2004 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -52,7 +52,7 @@ typedef struct PutBitContext {
 } PutBitContext;
 
 /**
- * Initializes the PutBitContext s.
+ * Initialize the PutBitContext s.
  *
  * @param buffer the buffer where to put bits
  * @param buffer_size the size in bytes of buffer
@@ -79,7 +79,7 @@ static inline void init_put_bits(PutBitContext *s, uint8_t *buffer, int buffer_s
 }
 
 /**
- * Returns the total number of bits written to the bitstream.
+ * @return the total number of bits written to the bitstream.
  */
 static inline int put_bits_count(PutBitContext *s)
 {
@@ -91,7 +91,7 @@ static inline int put_bits_count(PutBitContext *s)
 }
 
 /**
- * Pads the end of the output stream with zeros.
+ * Pad the end of the output stream with zeros.
  */
 static inline void flush_put_bits(PutBitContext *s)
 {
@@ -123,19 +123,19 @@ static inline void flush_put_bits(PutBitContext *s)
 #define ff_copy_bits ff_copy_bits_unsupported_here
 #else
 /**
- * Pads the bitstream with zeros up to the next byte boundary.
+ * Pad the bitstream with zeros up to the next byte boundary.
  */
 void align_put_bits(PutBitContext *s);
 
 /**
- * Puts the string string in the bitstream.
+ * Put the string string in the bitstream.
  *
  * @param terminate_string 0-terminates the written string if value is 1
  */
 void ff_put_string(PutBitContext *pb, const char *string, int terminate_string);
 
 /**
- * Copies the content of src to the bitstream.
+ * Copy the content of src to the bitstream.
  *
  * @param length the number of bits of src to copy
  */
@@ -143,7 +143,7 @@ void ff_copy_bits(PutBitContext *pb, const uint8_t *src, int length);
 #endif
 
 /**
- * Writes up to 31 bits into a bitstream.
+ * Write up to 31 bits into a bitstream.
  * Use put_bits32 to write 32 bits.
  */
 static inline void put_bits(PutBitContext *s, int n, unsigned int value)
@@ -168,7 +168,7 @@ static inline void put_bits(PutBitContext *s, int n, unsigned int value)
             AV_WL32(s->buf_ptr, bit_buf);
         } else
 #endif
-        *(uint32_t *)s->buf_ptr = le2me_32(bit_buf);
+        *(uint32_t *)s->buf_ptr = av_le2ne32(bit_buf);
         s->buf_ptr+=4;
         bit_buf = (bit_left==32)?0:value >> bit_left;
         bit_left+=32;
@@ -186,7 +186,7 @@ static inline void put_bits(PutBitContext *s, int n, unsigned int value)
             AV_WB32(s->buf_ptr, bit_buf);
         } else
 #endif
-        *(uint32_t *)s->buf_ptr = be2me_32(bit_buf);
+        *(uint32_t *)s->buf_ptr = av_be2ne32(bit_buf);
         //printf("bitbuf = %08x\n", bit_buf);
         s->buf_ptr+=4;
         bit_left+=32 - n;
@@ -224,8 +224,8 @@ static inline void put_bits(PutBitContext *s, int n, unsigned int value)
 
     value<<= 32-n;
 
-    ptr[0] |= be2me_32(value>>(index&31));
-    ptr[1]  = be2me_32(value<<(32-(index&31)));
+    ptr[0] |= av_be2ne32(value>>(index&31));
+    ptr[1]  = av_be2ne32(value<<(32-(index&31)));
 //if(n>24) printf("%d %d\n", n, value);
     index+= n;
     s->index= index;
@@ -252,7 +252,7 @@ static inline void put_bits(PutBitContext *s, int n, unsigned int value)
     int index= s->index;
     uint32_t *ptr= (uint32_t*)(((uint8_t *)s->buf)+(index>>3));
 
-    ptr[0] |= be2me_32(value<<(32-n-(index&7) ));
+    ptr[0] |= av_be2ne32(value<<(32-n-(index&7) ));
     ptr[1] = 0;
 //if(n>24) printf("%d %d\n", n, value);
     index+= n;
@@ -270,7 +270,7 @@ static inline void put_sbits(PutBitContext *pb, int n, int32_t value)
 }
 
 /**
- * Writes exactly 32 bits into a bitstream.
+ * Write exactly 32 bits into a bitstream.
  */
 static void av_unused put_bits32(PutBitContext *s, uint32_t value)
 {
@@ -286,7 +286,7 @@ static void av_unused put_bits32(PutBitContext *s, uint32_t value)
 }
 
 /**
- * Returns the pointer to the byte where the bitstream writer will put
+ * Return the pointer to the byte where the bitstream writer will put
  * the next bit.
  */
 static inline uint8_t* put_bits_ptr(PutBitContext *s)
@@ -299,7 +299,7 @@ static inline uint8_t* put_bits_ptr(PutBitContext *s)
 }
 
 /**
- * Skips the given number of bytes.
+ * Skip the given number of bytes.
  * PutBitContext must be flushed & aligned to a byte boundary before calling this.
  */
 static inline void skip_put_bytes(PutBitContext *s, int n)
@@ -315,7 +315,7 @@ static inline void skip_put_bytes(PutBitContext *s, int n)
 }
 
 /**
- * Skips the given number of bits.
+ * Skip the given number of bits.
  * Must only be used if the actual values in the bitstream do not matter.
  * If n is 0 the behavior is undefined.
  */
@@ -331,7 +331,7 @@ static inline void skip_put_bits(PutBitContext *s, int n)
 }
 
 /**
- * Changes the end of the buffer.
+ * Change the end of the buffer.
  *
  * @param size the new size in bytes of the buffer where to put bits
  */
diff --git a/libavcodec/qcelpdata.h b/libavcodec/qcelpdata.h
index d79cea9..df33e91 100644
--- a/libavcodec/qcelpdata.h
+++ b/libavcodec/qcelpdata.h
@@ -2,20 +2,20 @@
  * QCELP decoder
  * Copyright (c) 2007 Reynaldo H. Verdejo Pinochet
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -26,7 +26,7 @@
  * @file
  * Data tables for the QCELP decoder
  * @author Reynaldo H. Verdejo Pinochet
- * @remark FFmpeg merging spearheaded by Kenan Gillet
+ * @remark Libav merging spearheaded by Kenan Gillet
  * @remark Development mentored by Benjamin Larson
  */
 
diff --git a/libavcodec/qcelpdec.c b/libavcodec/qcelpdec.c
index 97785ad..3095a24 100644
--- a/libavcodec/qcelpdec.c
+++ b/libavcodec/qcelpdec.c
@@ -2,20 +2,20 @@
  * QCELP decoder
  * Copyright (c) 2007 Reynaldo H. Verdejo Pinochet
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -23,7 +23,7 @@
  * @file
  * QCELP decoder
  * @author Reynaldo H. Verdejo Pinochet
- * @remark FFmpeg merging spearheaded by Kenan Gillet
+ * @remark Libav merging spearheaded by Kenan Gillet
  * @remark Development mentored by Benjamin Larson
  */
 
@@ -92,7 +92,7 @@ static av_cold int qcelp_decode_init(AVCodecContext *avctx)
     QCELPContext *q = avctx->priv_data;
     int i;
 
-    avctx->sample_fmt = SAMPLE_FMT_FLT;
+    avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
 
     for(i=0; i<10; i++)
         q->prev_lspf[i] = (i+1)/11.;
@@ -101,8 +101,8 @@ static av_cold int qcelp_decode_init(AVCodecContext *avctx)
 }
 
 /**
- * Decodes the 10 quantized LSP frequencies from the LSPV/LSP
- * transmission codes of any bitrate and checks for badly received packets.
+ * Decode the 10 quantized LSP frequencies from the LSPV/LSP
+ * transmission codes of any bitrate and check for badly received packets.
  *
  * @param q the context
  * @param lspf line spectral pair frequencies
@@ -197,7 +197,7 @@ static int decode_lspf(QCELPContext *q, float *lspf)
 }
 
 /**
- * Converts codebook transmission codes to GAIN and INDEX.
+ * Convert codebook transmission codes to GAIN and INDEX.
  *
  * @param q the context
  * @param gain array holding the decoded gain
@@ -309,7 +309,7 @@ static int codebook_sanity_check_for_rate_quarter(const uint8_t *cbgain)
 }
 
 /**
- * Computes the scaled codebook vector Cdn From INDEX and GAIN
+ * Compute the scaled codebook vector Cdn From INDEX and GAIN
  * for all rates.
  *
  * The specification lacks some information here.
@@ -564,8 +564,8 @@ static void apply_pitch_filters(QCELPContext *q, float *cdn_vector)
 }
 
 /**
- * Reconstructs LPC coefficients from the line spectral pair frequencies
- * and performs bandwidth expansion.
+ * Reconstruct LPC coefficients from the line spectral pair frequencies
+ * and perform bandwidth expansion.
  *
  * @param lspf line spectral pair frequencies
  * @param lpc linear predictive coding coefficients
@@ -594,7 +594,7 @@ static void lspf2lpc(const float *lspf, float *lpc)
 }
 
 /**
- * Interpolates LSP frequencies and computes LPC coefficients
+ * Interpolate LSP frequencies and compute LPC coefficients
  * for a given bitrate & pitch subframe.
  *
  * TIA/EIA/IS-733 2.4.3.3.4, 2.4.8.7.2
@@ -842,7 +842,7 @@ erasure:
     return *data_size;
 }
 
-AVCodec qcelp_decoder =
+AVCodec ff_qcelp_decoder =
 {
     .name   = "qcelp",
     .type   = AVMEDIA_TYPE_AUDIO,
diff --git a/libavcodec/qdm2.c b/libavcodec/qdm2.c
index 6451fbe..3ef712c 100644
--- a/libavcodec/qdm2.c
+++ b/libavcodec/qdm2.c
@@ -5,20 +5,20 @@
  * Copyright (c) 2005 Alex Beregszaszi
  * Copyright (c) 2005 Roberto Togni
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -385,7 +385,7 @@ static uint16_t qdm2_packet_checksum (const uint8_t *data, int length, int value
 
 
 /**
- * Fills a QDM2SubPacket structure with packet type, size, and data pointer.
+ * Fill a QDM2SubPacket structure with packet type, size, and data pointer.
  *
  * @param gb            bitreader context
  * @param sub_packet    packet under analysis
@@ -436,7 +436,7 @@ static QDM2SubPNode* qdm2_search_subpacket_type_in_list (QDM2SubPNode *list, int
 
 
 /**
- * Replaces 8 elements with their average value.
+ * Replace 8 elements with their average value.
  * Called by qdm2_decode_superblock before starting subblock decoding.
  *
  * @param q       context
@@ -942,7 +942,6 @@ static void synthfilt_build_sb_samples (QDM2Context *q, GetBitContext *gb, int l
  * This is similar to process_subpacket_9, but for a single channel and for element [0]
  * same VLC tables as process_subpacket_9 are used.
  *
- * @param q         context
  * @param quantized_coeffs    pointer to quantized_coeffs[ch][0]
  * @param gb        bitreader context
  * @param length    packet length in bits
@@ -1210,7 +1209,8 @@ static void qdm2_decode_super_block (QDM2Context *q)
     init_get_bits(&gb, header.data, header.size*8);
 
     if (header.type == 2 || header.type == 4 || header.type == 5) {
-        int csum = 257 * get_bits(&gb, 8) + 2 * get_bits(&gb, 8);
+        int csum  = 257 * get_bits(&gb, 8);
+            csum +=   2 * get_bits(&gb, 8);
 
         csum = qdm2_packet_checksum(q->compressed_data, q->checksum_size, csum);
 
@@ -1588,7 +1588,7 @@ static void qdm2_calculate_fft (QDM2Context *q, int channel, int sub_packet)
     int i;
     q->fft.complex[channel][0].re *= 2.0f;
     q->fft.complex[channel][0].im = 0.0f;
-    ff_rdft_calc(&q->rdft_ctx, (FFTSample *)q->fft.complex[channel]);
+    q->rdft_ctx.rdft_calc(&q->rdft_ctx, (FFTSample *)q->fft.complex[channel]);
     /* add samples to output buffer */
     for (i = 0; i < ((q->fft_frame_size + 15) & ~15); i++)
         q->output_buffer[q->channels * i + channel] += ((float *) q->fft.complex[channel])[i] * gain;
@@ -1866,7 +1866,7 @@ static av_cold int qdm2_decode_init(AVCodecContext *avctx)
 
     qdm2_init(s);
 
-    avctx->sample_fmt = SAMPLE_FMT_S16;
+    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
 
 //    dump_context(s);
     return 0;
@@ -1883,7 +1883,7 @@ static av_cold int qdm2_decode_close(AVCodecContext *avctx)
 }
 
 
-static void qdm2_decode (QDM2Context *q, const uint8_t *in, int16_t *out)
+static int qdm2_decode (QDM2Context *q, const uint8_t *in, int16_t *out)
 {
     int ch, i;
     const int frame_size = (q->frame_size * q->channels);
@@ -1919,7 +1919,7 @@ static void qdm2_decode (QDM2Context *q, const uint8_t *in, int16_t *out)
 
         if (!q->has_errors && q->sub_packet_list_C[0].packet != NULL) {
             SAMPLES_NEEDED_2("has errors, and C list is not empty")
-            return;
+            return -1;
         }
     }
 
@@ -1940,6 +1940,8 @@ static void qdm2_decode (QDM2Context *q, const uint8_t *in, int16_t *out)
 
         out[i] = value;
     }
+
+    return 0;
 }
 
 
@@ -1950,28 +1952,29 @@ static int qdm2_decode_frame(AVCodecContext *avctx,
     const uint8_t *buf = avpkt->data;
     int buf_size = avpkt->size;
     QDM2Context *s = avctx->priv_data;
+    int16_t *out = data;
+    int i;
 
     if(!buf)
         return 0;
     if(buf_size < s->checksum_size)
         return -1;
 
-    *data_size = s->channels * s->frame_size * sizeof(int16_t);
-
     av_log(avctx, AV_LOG_DEBUG, "decode(%d): %p[%d] -> %p[%d]\n",
        buf_size, buf, s->checksum_size, data, *data_size);
 
-    qdm2_decode(s, buf, data);
-
-    // reading only when next superblock found
-    if (s->sub_packet == 0) {
-        return s->checksum_size;
+    for (i = 0; i < 16; i++) {
+        if (qdm2_decode(s, buf, out) < 0)
+            return -1;
+        out += s->channels * s->frame_size;
     }
 
-    return 0;
+    *data_size = (uint8_t*)out - (uint8_t*)data;
+
+    return s->checksum_size;
 }
 
-AVCodec qdm2_decoder =
+AVCodec ff_qdm2_decoder =
 {
     .name = "qdm2",
     .type = AVMEDIA_TYPE_AUDIO,
diff --git a/libavcodec/qdm2_tablegen.c b/libavcodec/qdm2_tablegen.c
index c225bc4..59d82df 100644
--- a/libavcodec/qdm2_tablegen.c
+++ b/libavcodec/qdm2_tablegen.c
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2010 Reimar Döffinger <Reimar.Doeffinger at gmx.de>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -33,25 +33,12 @@ int main(void)
 
     write_fileheader();
 
-    printf("static const uint16_t softclip_table[HARDCLIP_THRESHOLD - SOFTCLIP_THRESHOLD + 1] = {\n");
-    write_uint16_array(softclip_table, HARDCLIP_THRESHOLD - SOFTCLIP_THRESHOLD + 1);
-    printf("};\n");
+    WRITE_ARRAY("static const", uint16_t, softclip_table);
+    WRITE_ARRAY("static const", float, noise_table);
+    WRITE_ARRAY("static const", float, noise_samples);
 
-    printf("static const float noise_table[4096] = {\n");
-    write_float_array(noise_table, 4096);
-    printf("};\n");
-
-    printf("static const uint8_t random_dequant_index[256][5] = {\n");
-    write_uint8_2d_array(random_dequant_index, 256, 5);
-    printf("};\n");
-
-    printf("static const uint8_t random_dequant_type24[128][3] = {\n");
-    write_uint8_2d_array(random_dequant_type24, 128, 3);
-    printf("};\n");
-
-    printf("static const float noise_samples[128] = {\n");
-    write_float_array(noise_samples, 128);
-    printf("};\n");
+    WRITE_2D_ARRAY("static const", uint8_t, random_dequant_index);
+    WRITE_2D_ARRAY("static const", uint8_t, random_dequant_type24);
 
     return 0;
 }
diff --git a/libavcodec/qdm2_tablegen.h b/libavcodec/qdm2_tablegen.h
index de9ff0c..769d53b 100644
--- a/libavcodec/qdm2_tablegen.h
+++ b/libavcodec/qdm2_tablegen.h
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2010 Reimar Döffinger <Reimar.Doeffinger at gmx.de>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,7 +25,7 @@
 
 #include <stdint.h>
 #include <math.h>
-#include "../libavutil/attributes.h"
+#include "libavutil/attributes.h"
 
 #define SOFTCLIP_THRESHOLD 27600
 #define HARDCLIP_THRESHOLD 35716
diff --git a/libavcodec/qdm2data.h b/libavcodec/qdm2data.h
index 355d613..ad6ea88 100644
--- a/libavcodec/qdm2data.h
+++ b/libavcodec/qdm2data.h
@@ -5,20 +5,20 @@
  * Copyright (c) 2005 Alex Beregszaszi
  * Copyright (c) 2005 Roberto Togni
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/qdrw.c b/libavcodec/qdrw.c
index 5750058..3768c1b 100644
--- a/libavcodec/qdrw.c
+++ b/libavcodec/qdrw.c
@@ -2,20 +2,20 @@
  * QuickDraw (qdrw) codec
  * Copyright (c) 2004 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -150,7 +150,7 @@ static av_cold int decode_end(AVCodecContext *avctx){
     return 0;
 }
 
-AVCodec qdraw_decoder = {
+AVCodec ff_qdraw_decoder = {
     "qdraw",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_QDRAW,
diff --git a/libavcodec/qpeg.c b/libavcodec/qpeg.c
index e6a0b30..c96184f 100644
--- a/libavcodec/qpeg.c
+++ b/libavcodec/qpeg.c
@@ -2,20 +2,20 @@
  * QPEG codec
  * Copyright (c) 2004 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -30,6 +30,7 @@ typedef struct QpegContext{
     AVCodecContext *avctx;
     AVFrame pic;
     uint8_t *refdata;
+    uint32_t pal[256];
 } QpegContext;
 
 static void qpeg_decode_intra(const uint8_t *src, uint8_t *dst, int size,
@@ -256,6 +257,7 @@ static int decode_frame(AVCodecContext *avctx,
     AVFrame * const p= (AVFrame*)&a->pic;
     uint8_t* outdata;
     int delta;
+    const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, NULL);
 
     if(p->data[0])
         avctx->release_buffer(avctx, p);
@@ -274,11 +276,11 @@ static int decode_frame(AVCodecContext *avctx,
     }
 
     /* make the palette available on the way out */
-    memcpy(a->pic.data[1], a->avctx->palctrl->palette, AVPALETTE_SIZE);
-    if (a->avctx->palctrl->palette_changed) {
+    if (pal) {
         a->pic.palette_has_changed = 1;
-        a->avctx->palctrl->palette_changed = 0;
+        memcpy(a->pal, pal, AVPALETTE_SIZE);
     }
+    memcpy(a->pic.data[1], a->pal, AVPALETTE_SIZE);
 
     *data_size = sizeof(AVFrame);
     *(AVFrame*)data = a->pic;
@@ -289,10 +291,6 @@ static int decode_frame(AVCodecContext *avctx,
 static av_cold int decode_init(AVCodecContext *avctx){
     QpegContext * const a = avctx->priv_data;
 
-    if (!avctx->palctrl) {
-        av_log(avctx, AV_LOG_FATAL, "Missing required palette via palctrl\n");
-        return -1;
-    }
     a->avctx = avctx;
     avctx->pix_fmt= PIX_FMT_PAL8;
     a->refdata = av_malloc(avctx->width * avctx->height);
@@ -311,7 +309,7 @@ static av_cold int decode_end(AVCodecContext *avctx){
     return 0;
 }
 
-AVCodec qpeg_decoder = {
+AVCodec ff_qpeg_decoder = {
     "qpeg",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_QPEG,
diff --git a/libavcodec/qtrle.c b/libavcodec/qtrle.c
index 1fd9a80..e14c306 100644
--- a/libavcodec/qtrle.c
+++ b/libavcodec/qtrle.c
@@ -2,20 +2,20 @@
  * Quicktime Animation (RLE) Video Decoder
  * Copyright (C) 2004 the ffmpeg project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -46,6 +46,7 @@ typedef struct QtrleContext {
     const unsigned char *buf;
     int size;
 
+    uint32_t pal[256];
 } QtrleContext;
 
 #define CHECK_STREAM_PTR(n) \
@@ -511,12 +512,15 @@ static int qtrle_decode_frame(AVCodecContext *avctx,
     }
 
     if(has_palette) {
-        /* make the palette available on the way out */
-        memcpy(s->frame.data[1], s->avctx->palctrl->palette, AVPALETTE_SIZE);
-        if (s->avctx->palctrl->palette_changed) {
+        const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, NULL);
+
+        if (pal) {
             s->frame.palette_has_changed = 1;
-            s->avctx->palctrl->palette_changed = 0;
+            memcpy(s->pal, pal, AVPALETTE_SIZE);
         }
+
+        /* make the palette available on the way out */
+        memcpy(s->frame.data[1], s->pal, AVPALETTE_SIZE);
     }
 
 done:
@@ -537,7 +541,7 @@ static av_cold int qtrle_decode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec qtrle_decoder = {
+AVCodec ff_qtrle_decoder = {
     "qtrle",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_QTRLE,
diff --git a/libavcodec/qtrleenc.c b/libavcodec/qtrleenc.c
index 7f95c7f..d35bc20 100644
--- a/libavcodec/qtrleenc.c
+++ b/libavcodec/qtrleenc.c
@@ -5,23 +5,24 @@
  *
  * This file is based on flashsvenc.c.
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/imgutils.h"
 #include "avcodec.h"
 #include "bytestream.h"
 
@@ -62,7 +63,7 @@ static av_cold int qtrle_encode_init(AVCodecContext *avctx)
 {
     QtrleEncContext *s = avctx->priv_data;
 
-    if (avcodec_check_dimensions(avctx, avctx->width, avctx->height) < 0) {
+    if (av_image_check_size(avctx->width, avctx->height, 0, avctx) < 0) {
         return -1;
     }
     s->avctx=avctx;
@@ -104,7 +105,7 @@ static av_cold int qtrle_encode_init(AVCodecContext *avctx)
 }
 
 /**
- * Computes the best RLE sequence for a line
+ * Compute the best RLE sequence for a line
  */
 static void qtrle_encode_line(QtrleEncContext *s, AVFrame *p, int line, uint8_t **buf)
 {
@@ -235,7 +236,7 @@ static void qtrle_encode_line(QtrleEncContext *s, AVFrame *p, int line, uint8_t
     bytestream_put_byte(buf, -1); // end RLE line
 }
 
-/** Encodes frame including header */
+/** Encode frame including header */
 static int encode_frame(QtrleEncContext *s, AVFrame *p, uint8_t *buf)
 {
     int i;
@@ -320,7 +321,7 @@ static av_cold int qtrle_encode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec qtrle_encoder = {
+AVCodec ff_qtrle_encoder = {
     "qtrle",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_QTRLE,
diff --git a/libavcodec/r210dec.c b/libavcodec/r210dec.c
index 416f764..ae215fe 100644
--- a/libavcodec/r210dec.c
+++ b/libavcodec/r210dec.c
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2009 Reimar Doeffinger <Reimar.Doeffinger at gmx.de>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -61,11 +61,17 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *data_size,
     for (h = 0; h < avctx->height; h++) {
         uint16_t *dst = (uint16_t *)dst_line;
         for (w = 0; w < avctx->width; w++) {
-            uint32_t pixel = be2me_32(*src++);
+            uint32_t pixel = av_be2ne32(*src++);
             uint16_t r, g, b;
-            b =  pixel <<  6;
-            g = (pixel >>  4) & 0xffc0;
-            r = (pixel >> 14) & 0xffc0;
+            if (avctx->codec_id==CODEC_ID_R210) {
+                b =  pixel <<  6;
+                g = (pixel >>  4) & 0xffc0;
+                r = (pixel >> 14) & 0xffc0;
+            } else {
+                b =  pixel <<  4;
+                g = (pixel >>  6) & 0xffc0;
+                r = (pixel >> 16) & 0xffc0;
+            }
             *dst++ = r | (r >> 10);
             *dst++ = g | (g >> 10);
             *dst++ = b | (b >> 10);
@@ -90,7 +96,8 @@ static av_cold int decode_close(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec r210_decoder = {
+#if CONFIG_R210_DECODER
+AVCodec ff_r210_decoder = {
     "r210",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_R210,
@@ -102,3 +109,18 @@ AVCodec r210_decoder = {
     CODEC_CAP_DR1,
     .long_name = NULL_IF_CONFIG_SMALL("Uncompressed RGB 10-bit"),
 };
+#endif
+#if CONFIG_R10K_DECODER
+AVCodec ff_r10k_decoder = {
+    "r10k",
+    AVMEDIA_TYPE_VIDEO,
+    CODEC_ID_R10K,
+    0,
+    decode_init,
+    NULL,
+    decode_close,
+    decode_frame,
+    CODEC_CAP_DR1,
+    .long_name = NULL_IF_CONFIG_SMALL("AJA Kona 10-bit RGB Codec"),
+};
+#endif
diff --git a/libavcodec/ra144.c b/libavcodec/ra144.c
index efa62c4..fd2ed32 100644
--- a/libavcodec/ra144.c
+++ b/libavcodec/ra144.c
@@ -1,147 +1,1517 @@
 /*
  * Real Audio 1.0 (14.4K)
+ * Copyright (c) 2003 the ffmpeg project
  *
- * Copyright (c) 2008 Vitor Sessak
- * Copyright (c) 2003 Nick Kurshev
- *     Based on public domain decoder at http://www.honeypot.net/audio
+ * This file is part of Libav.
  *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
-#include "libavutil/intmath.h"
+#include <stdint.h>
 #include "avcodec.h"
-#include "get_bits.h"
-#include "ra144.h"
 #include "celp_filters.h"
+#include "ra144.h"
 
-#define NBLOCKS         4       ///< number of subblocks within a block
-#define BLOCKSIZE       40      ///< subblock size in 16-bit words
-#define BUFFERSIZE      146     ///< the size of the adaptive codebook
-
-
-typedef struct {
-    AVCodecContext *avctx;
-
-    unsigned int     old_energy;        ///< previous frame energy
-
-    unsigned int     lpc_tables[2][10];
-
-    /** LPC coefficients: lpc_coef[0] is the coefficients of the current frame
-     *  and lpc_coef[1] of the previous one. */
-    unsigned int    *lpc_coef[2];
-
-    unsigned int     lpc_refl_rms[2];
-
-    /** The current subblock padded by the last 10 values of the previous one. */
-    int16_t curr_sblock[50];
-
-    /** Adaptive codebook, its size is two units bigger to avoid a
-     *  buffer overflow. */
-    uint16_t adapt_cb[146+2];
-} RA144Context;
+const int16_t ff_gain_val_tab[256][3] = {
+    { 541, 956,  768}, { 877, 581,  568}, { 675,1574,  635}, {1248,1464,  668},
+    {1246, 839, 1394}, {2560,1386,  991}, { 925, 687,  608}, {2208, 797, 1144},
+    { 535, 832,  799}, { 762, 605, 1154}, { 832,1122, 1003}, {1180, 687, 1176},
+    {1292, 901,  732}, {1656, 689,  896}, {1750,1248,  848}, {2284, 942, 1022},
+    { 824,1472,  643}, { 517, 765,  512}, { 562,1816, 1522}, { 694,1826, 2700},
+    { 704, 524,  672}, {1442, 757, 2232}, { 884, 551, 1266}, {2232,1007, 1692},
+    { 932, 746,  777}, {1132, 822,  926}, {1226, 771,  611}, {2948,1342, 1008},
+    {1302, 594, 1158}, {1602, 636, 1128}, {3408, 910, 1438}, {1996, 614,  575},
+    { 665, 935,  628}, { 631,1192,  829}, { 644, 926, 1052}, { 879, 988, 1226},
+    { 941,2768, 2772}, { 565,1344, 2304}, { 547, 628,  740}, { 639, 532, 1074},
+    { 955,1208,  598}, {1124,1160,  900}, {1206, 899, 1242}, { 746, 533,  624},
+    {1458,1028,  735}, {1706,1102,  692}, {1898,1018, 1004}, {2176, 988,  735},
+    {1578, 782, 1642}, { 897, 516,  754}, {2068, 702, 1656}, {2344, 818, 1526},
+    { 907, 652,  592}, {1056, 652,  642}, {2124,1416,  780}, {2664,1250,  727},
+    {1894, 727, 1108}, {2196, 657,  981}, {4840, 920, 1704}, {4992,1238,  983},
+    {2420, 909, 1094}, {2760, 935, 1032}, {2800, 612,  853}, {3068, 832,  574},
+    { 523,1796,  923}, { 722,1916, 1382}, {1226,1542,  928}, { 758, 757,  584},
+    { 512,1134,  577}, { 615,1276,  698}, { 574,2568, 2356}, { 993,2728, 3512},
+    { 539, 890,  913}, { 694, 928, 1088}, { 805, 600, 1360}, {2160, 951, 3128},
+    { 816, 950,  590}, { 955, 847,  811}, {1094, 883,  556}, {1304, 888,  604},
+    { 863,1170,  855}, {1023, 997, 1032}, { 932,1228, 1280}, { 627, 564,  573},
+    { 876, 900, 1448}, {1030, 857, 1792}, {1294, 953, 1758}, {1612, 854, 1714},
+    {1090,1166,  631}, {1314,1202,  751}, {1480, 905,  795}, {1682,1016,  568},
+    {1494,1178,  983}, { 878, 613,  526}, {1728,1446,  779}, {2136,1348,  774},
+    { 950, 649,  939}, {1180, 703,  899}, {1236, 527, 1158}, {1450, 647,  972},
+    {1282, 647,  707}, {1460, 663,  644}, {1614, 572,  578}, {3516,1222,  821},
+    {2668, 729, 1682}, {3128, 585, 1502}, {3208, 733,  976}, {6800, 871, 1416},
+    {3480, 743, 1408}, {3764, 899, 1170}, {3772, 632,  875}, {4092, 732,  638},
+    {3112, 753, 2620}, {3372, 945, 1890}, {3768, 969, 2288}, {2016, 559,  854},
+    {1736, 729,  787}, {1940, 686,  547}, {2140, 635,  674}, {4480,1272,  828},
+    {3976, 592, 1666}, {4384, 621, 1388}, {4400, 801,  955}, {4656, 522,  646},
+    {4848, 625, 1636}, {4984, 591,  874}, {5352, 535, 1001}, {11216,938, 1184},
+    { 925,3280, 1476}, { 735,1580, 1088}, {1150,1576,  674}, { 655, 783,  528},
+    { 527,2052, 1354}, { 782,1704, 1880}, { 578, 910, 1026}, { 692, 882, 1468},
+    { 586, 683,  715}, { 739, 609,  717}, { 778, 773,  697}, { 922, 785,  813},
+    { 766, 651,  984}, { 978, 596, 1030}, {1070, 757, 1080}, {1324, 687, 1178},
+    {1108,2144,  979}, { 723, 982,  690}, { 936, 956,  527}, {1180,1002,  547},
+    { 517,1306,  825}, { 832,1184,  974}, {1024, 957,  903}, {1262,1090,  906},
+    {1028, 720,  649}, {1192, 679,  694}, {2468,1480,  979}, {2844,1370,  877},
+    {1310, 835,  848}, {1508, 839,  698}, {1742,1030,  769}, {1910, 852,  573},
+    {1280, 859, 1174}, {1584, 863, 1108}, {1686, 708, 1364}, {1942, 768, 1104},
+    { 891, 536,  690}, {1016, 560,  663}, {2172, 870, 1348}, {2404, 999, 1170},
+    {1890, 966,  889}, {2116, 912,  777}, {2296,1020,  714}, {4872,1844,  932},
+    {2392, 778,  929}, {2604, 772,  744}, {2764, 957,  722}, {5832,1532,  984},
+    {2188, 519, 1264}, {2332, 532,  922}, {5064, 995, 2412}, {2708, 571,  874},
+    {2408, 545,  666}, {5016,1084,  875}, {5376, 983, 1196}, {5536, 979,  730},
+    {5344, 634, 1744}, {5688, 706, 1348}, {5912, 977, 1190}, {6072, 905,  763},
+    {6048, 582, 1526}, {11968,1013,1816}, {12864,937, 1900}, {12560,1086, 998},
+    {1998, 684, 1884}, {2504, 633, 1992}, {1252, 567,  835}, {1478, 571,  973},
+    {2620, 769, 1414}, {2808, 952, 1142}, {2908, 712, 1028}, {2976, 686,  741},
+    {1462, 552,  714}, {3296, 991, 1452}, {1590, 615,  544}, {3480,1150,  824},
+    {3212, 832,  923}, {3276, 839,  531}, {3548, 786,  852}, {3732, 764,  570},
+    {5728, 906, 2616}, {6272, 804, 2252}, {3096, 535,  876}, {3228, 598,  649},
+    {6536, 759, 1436}, {6648, 993,  846}, {6864, 567, 1210},{14016,1012, 1302},
+    {3408, 548, 1098}, {7160,1008, 1742}, {7136,1000, 1182}, {7480,1032,  836},
+    {7448, 612, 1552}, {7744, 614,  816}, {8384, 777, 1438}, {8784, 694,  786},
+    { 882,1508, 1068}, { 597, 837,  766}, {1270, 954, 1408}, { 803, 550,  798},
+    {1398,1308,  798}, {1848,1534,  738}, { 970, 675,  608}, {1264, 706,  684},
+    {1716, 767, 1126}, {2108, 765, 1404}, {2236, 924, 1003}, {2472,1048,  611},
+    { 999, 942,  963}, {1094, 857,  935}, {2936, 926, 1138}, {1934, 746,  551},
+    {3336, 633, 1762}, {3764, 701, 1454}, {1890, 564,  636}, {4096,1126,  793},
+    {3936, 556, 1140}, {3936, 540,  740}, {4216, 764,  874}, {8480,1328, 1014},
+    {2184, 515, 1042}, {4432, 934, 1344}, {4784, 945, 1112}, {5016,1062,  733},
+    {9216,1020, 2028}, {9968, 924, 1188}, {5424, 909, 1206}, {6512, 744, 1086}
+};
 
-static av_cold int ra144_decode_init(AVCodecContext * avctx)
-{
-    RA144Context *ractx = avctx->priv_data;
+const uint8_t ff_gain_exp_tab[256] = {
+   15, 15, 15, 15, 15, 16, 14, 15, 14, 14, 14, 14, 14, 14, 14, 14,
+   14, 13, 14, 14, 13, 14, 13, 14, 13, 13, 13, 14, 13, 13, 14, 13,
+   13, 13, 13, 13, 14, 13, 12, 12, 13, 13, 13, 12, 13, 13, 13, 13,
+   13, 12, 13, 13, 12, 12, 13, 13, 13, 13, 14, 14, 13, 13, 13, 13,
+   13, 13, 13, 12, 12, 12, 13, 13, 12, 12, 12, 13, 12, 12, 12, 12,
+   12, 12, 12, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 11, 12, 12,
+   12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 14, 13, 13, 13, 13,
+   13, 13, 13, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 14,
+   13, 12, 12, 11, 12, 12, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
+   12, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 11, 11, 11, 11,
+   12, 12, 12, 12, 11, 11, 12, 12, 12, 12, 12, 13, 12, 12, 12, 13,
+   12, 12, 13, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14,
+   12, 12, 11, 11, 12, 12, 12, 12, 11, 12, 11, 12, 12, 12, 12, 12,
+   13, 13, 12, 12, 13, 13, 13, 14, 12, 13, 13, 13, 13, 13, 13, 13,
+   11, 10, 11, 10, 11, 11, 10, 10, 11, 11, 11, 11, 10,  9, 11, 10,
+   12, 12, 11, 12, 12, 12, 12, 13, 11, 12, 12, 12, 13, 13, 12, 12
+};
 
-    ractx->avctx = avctx;
+const int8_t ff_cb1_vects[128][40]={
+    {
+     38,  -4,  15,  -4,  14, -13,  12, -11,  -2,  -6,
+     -6, -11, -45, -16, -11, -13,  -7,   6, -12,   4,
+    -20,   3, -16,  12,  -1,  12,  46,  24,   0,  33,
+     -3,   9, -12, -12,  -8,  -7,  17,  -6,   0,  -2,
+    }, {
+     60, -16,   3, -22,  10, -32,   0, -28, -17, -18,
+     -3, -25, -37, -23, -10,   3,   2,   3,   0,   3,
+    -14,   0, -14,  -1,   0,   2,  32,   9,  -1,  25,
+      7,  13,  -5,  13,   8,   1,   2,   8, -10,   6,
+    }, {
+     27, -12,  28,  -2,   6,  -7,  15,   9, -11,   1,
+    -13, -11, -40,   4, -29, -14, -19,  -5, -23,  -8,
+    -30, -13, -17,   0, -14,  12,  34,  20,  -2,  25,
+      2, -16,  -4, -12,  15,  16,  29,   7,  24,  10,
+    }, {
+     49, -24,  16, -20,   2, -26,   2,  -7, -25, -10,
+    -11, -25, -32,  -3, -27,   2,  -8,  -8, -11,  -9,
+    -24, -17, -16, -14, -13,   2,  20,   5,  -4,  17,
+     14, -12,   3,  13,  33,  25,  14,  23,  15,  19,
+    }, {
+     46,  -6,  21,   8,  -2, -16,  -5,  -8, -11,   4,
+      8,  15, -24,   4,  -2, -26,  -3, -16, -16, -14,
+     -9,  -2,  -1,   4,  19,   7,  36,  17,   9,  13,
+      0,  31,  -5, -12,   7,  -8,  11, -15, -13,  -4,
+    }, {
+     68, -18,   9,  -9,  -6, -35, -18, -25, -26,  -7,
+     10,   1, -16,  -3,  -1,  -9,   6, -19,  -4, -15,
+     -4,  -6,   0,  -8,  20,  -2,  23,   2,   7,   5,
+     12,  35,   1,  13,  24,   0,  -3,   0, -22,   4,
+    }, {
+     35, -14,  34,  10, -10, -10,  -1,  12, -20,  12,
+      0,  15, -18,  24, -20, -27, -14, -28, -27, -27,
+    -20, -19,  -2,  -8,   5,   7,  25,  13,   5,   5,
+      6,   5,   2, -12,  31,  15,  23,  -1,  12,   8,
+    }, {
+     57, -26,  22,  -7, -14, -28, -14,  -3, -35,   0,
+      3,   1, -11,  16, -18, -10,  -4, -31, -15, -28,
+    -14, -23,  -1, -21,   7,  -2,  11,  -1,   3,  -1,
+     18,   9,  10,  13,  49,  24,   8,  14,   2,  16,
+    }, {
+     25,  15,  22,  11,  18,   4,  15, -22,   8,  -2,
+    -17,  -9, -48, -20, -30, -17, -16,  11,  -1,  16,
+      2,  10,  -5,  26,  -2,  -4,  22,   0,   2,  10,
+     -6,  13, -14,  10, -23,   0,  10,  -2,   1,   0,
+    }, {
+     47,   3,  11,  -6,  15, -13,   2, -38,  -6, -13,
+    -15, -22, -40, -28, -28,   0,  -5,   8,  10,  15,
+      7,   7,  -4,  13,  -1, -14,   9, -14,   0,   2,
+      4,  18,  -7,  36,  -6,   8,  -3,  13,  -7,   8,
+    }, {
+     14,   7,  36,  13,  10,  10,  18,   0,   0,   5,
+    -25,  -8, -43,   0, -48, -18, -27,   0, -12,   3,
+     -7,  -6,  -7,  13, -15,  -5,  11,  -3,   0,   2,
+      0, -12,  -6,  10,   0,  23,  22,  11,  26,  12,
+    }, {
+     36,  -5,  24,  -4,   7,  -7,   6, -17, -14,  -5,
+    -22, -22, -35,  -8, -46,  -1, -17,  -3,   0,   2,
+     -2, -10,  -5,   0, -14, -15,  -2, -18,  -2,  -4,
+     11,  -7,   1,  36,  18,  32,   7,  27,  17,  20,
+    }, {
+     33,  13,  29,  24,   1,   1,  -2, -18,   0,   9,
+     -3,  17, -27,   0, -21, -30, -12, -11,  -5,  -2,
+     12,   4,   9,  19,  18,  -9,  13,  -6,  11,  -8,
+     -2,  35,  -8,  10,  -7,  -1,   4, -11, -10,  -2,
+    }, {
+     55,   1,  17,   6,  -1, -16, -15, -35, -15,  -2,
+      0,   4, -19,  -8, -20, -13,  -1, -14,   7,  -3,
+     18,   0,  10,   5,  19, -19,   0, -21,   8, -16,
+      9,  39,   0,  36,  10,   7,  -9,   4, -20,   5,
+    }, {
+     22,   5,  42,  26,  -6,   8,   1,   2,  -9,  17,
+    -10,  18, -21,  19, -39, -31, -23, -23, -16, -15,
+      2, -12,   7,   6,   5,  -9,   1, -10,   7, -16,
+      4,   9,   0,  10,  17,  22,  16,   2,  14,   9,
+    }, {
+     44,  -6,  30,   8,  -9, -10, -11, -14, -23,   5,
+     -8,   4, -14,  12, -37, -14, -12, -26,  -4, -16,
+      8, -16,   9,  -7,   6, -19, -12, -25,   5, -24,
+     15,  13,   8,  36,  34,  31,   1,  18,   4,  18,
+    }, {
+     -3,  -5,  -9,  -7,  15,  -1,   5,  13,   2,  12,
+      5,   2, -21, -23,  -2, -16,   0,   5,  -6,  13,
+    -23,   3, -32,  10, -15,   8,  44,  28,   9,  37,
+     -2,  13,  -9, -15, -12, -27,  -7, -12,   0, -11,
+    }, {
+     18, -17, -21, -25,  11, -19,  -6,  -3, -11,   0,
+      7, -11, -13, -31,  -1,   0,   9,   1,   5,  12,
+    -18,   0, -31,  -2, -13,  -1,  30,  14,   7,  29,
+      9,  18,  -1,  10,   4, -18, -22,   3, -10,  -2,
+    }, {
+    -13, -13,   3,  -5,   7,   4,   9,  34,  -5,  20,
+     -2,   3, -16,  -3, -20, -17, -11,  -7, -17,   0,
+    -34, -13, -33,  -2, -28,   8,  32,  24,   5,  29,
+      3, -12,   0, -15,  11,  -3,   3,   2,  24,   1,
+    }, {
+      8, -25,  -8, -23,   3, -13,  -3,  17, -20,   8,
+      0, -10,  -8, -11, -18,   0,  -1, -10,  -5,   0,
+    -28, -17, -32, -15, -26,  -1,  19,   9,   3,  21,
+     15,  -7,   6,   9,  29,   5, -10,  17,  15,   9,
+    }, {
+      4,  -6,  -3,   5,  -1,  -4, -11,  16,  -6,  23,
+     19,  29,   0,  -3,   6, -30,   3, -17, -10,  -5,
+    -13,  -2, -17,   3,   5,   3,  35,  21,  17,  17,
+      2,  35,  -2, -15,   3, -28, -13, -21, -13, -13,
+    }, {
+     26, -19, -15, -12,  -5, -22, -24,   0, -21,  12,
+     21,  15,   8, -11,   7, -12,  14, -20,   2,  -6,
+     -7,  -6, -16,  -9,   6,  -5,  21,   7,  15,  10,
+     13,  39,   5,  10,  20, -19, -28,  -5, -22,  -5,
+    }, {
+     -5, -15,   9,   7,  -9,   2,  -8,  37, -14,  31,
+     11,  29,   5,  16, -11, -30,  -7, -29, -21, -18,
+    -23, -19, -18,  -9,  -7,   3,  23,  17,  14,   9,
+      8,   9,   6, -15,  27,  -4,  -2,  -6,  12,  -1,
+    }, {
+     16, -27,  -2, -10, -13, -16, -20,  20, -29,  20,
+     14,  16,  13,   8,  -9, -13,   2, -33,  -9, -19,
+    -17, -23, -17, -22,  -6,  -6,   9,   2,  12,   2,
+     20,  13,  13,  10,  45,   4, -16,   8,   2,   7,
+    }, {
+    -16,  14,  -2,   8,  20,  17,   9,   2,  14,  16,
+     -6,   5, -24, -28, -21, -20,  -8,   9,   4,  25,
+     -1,  11, -22,  24, -15,  -8,  21,   5,  11,  14,
+     -5,  18, -11,   7, -27, -20, -14,  -7,   1,  -9,
+    }, {
+      6,   2, -14,  -9,  16,  -1,  -3, -14,   0,   5,
+     -3,  -8, -16, -36, -19,  -3,   1,   6,  17,  24,
+      4,   7, -21,  11, -14, -18,   7,  -9,   9,   7,
+      6,  22,  -3,  33, -10, -11, -28,   7,  -7,   0,
+    }, {
+    -26,   6,  11,  10,  12,  23,  12,  23,   5,  24,
+    -13,   5, -19,  -8, -38, -21, -20,  -2,  -6,  12,
+    -11,  -5, -23,  11, -29,  -9,   9,   0,   7,   6,
+      1,  -7,  -2,   7,  -3,   3,  -2,   6,  27,   3,
+    }, {
+     -4,  -6,   0,  -7,   8,   4,   0,   6,  -9,  13,
+    -11,  -7, -11, -15, -37,  -4,  -9,  -5,   5,  11,
+     -5,  -9, -22,  -1, -27, -18,  -4, -14,   5,   0,
+     12,  -3,   4,  32,  14,  12, -17,  22,  17,  11,
+    }, {
+     -8,  12,   3,  21,   3,  14,  -8,   5,   4,  28,
+      7,  32,  -2,  -8, -12, -34,  -4, -12,   1,   6,
+      9,   4,  -7,  17,   4, -13,  11,  -1,  19,  -4,
+      0,  39,  -4,   7, -11, -21, -20, -16, -10, -11,
+    }, {
+     13,   0,  -8,   3,   0,  -4, -21, -11,  -9,  16,
+     10,  18,   5, -16, -10, -16,   5, -15,  13,   5,
+     15,   1,  -6,   4,   6, -23,  -2, -16,  17, -12,
+     10,  44,   3,  33,   6, -12, -34,  -1, -20,  -3,
+    }, {
+    -18,   4,  17,  23,  -4,  20,  -4,  26,  -3,  36,
+      0,  32,   2,  12, -29, -34, -16, -24, -10,  -6,
+      0, -12,  -8,   4,  -8, -13,   0,  -6,  16, -12,
+      5,  13,   3,   7,  13,   3,  -8,  -2,  14,   0,
+    }, {
+      3,  -7,   5,   5,  -8,   2, -17,   9, -18,  24,
+      2,  19,  10,   4, -28, -17,  -5, -28,   2,  -7,
+      4, -15,  -7,  -8,  -6, -23, -13, -21,  14, -20,
+     17,  18,  11,  33,  30,  11, -23,  13,   5,   9,
+    }, {
+     60,  10,   7,  -1,   9,  -8,   6, -13,   2, -15,
+     -1, -10, -13, -11,  15,   0,   6,   9,  -1,   0,
+    -13,   1, -11,  -3, -13,  21,  13,  26,  -7,  31,
+    -10,  -7, -16, -33, -31, -10,  22,  -8,   1,  -2,
+    }, {
+     82,  -1,  -4, -19,   6, -27,  -6, -29, -12, -26,
+      1, -24,  -5, -18,  17,  17,  17,   6,  10,   0,
+     -7,  -2,  -9, -16, -12,  11,   0,  11,  -9,  23,
+      0,  -3,  -8,  -8, -13,  -1,   8,   7,  -7,   6,
+    }, {
+     49,   2,  21,   0,   1,  -2,   9,   8,  -6,  -6,
+     -8, -10,  -8,   9,  -2,   0,  -4,  -2, -13, -12,
+    -23, -15, -12, -16, -26,  21,   2,  21, -11,  23,
+     -4, -33,  -7, -33,  -6,  13,  34,   5,  27,  10,
+    }, {
+     71, -10,   9, -17,  -1, -20,  -3,  -8, -21, -18,
+     -6, -24,   0,   1,   0,  16,   6,  -5,   0, -13,
+    -17, -19, -11, -29, -25,  11, -11,   6, -13,  15,
+      7, -29,   0,  -8,  11,  22,  20,  21,  17,  18,
+    }, {
+     67,   8,  14,  11,  -7, -11, -11,  -9,  -7,  -3,
+     13,  16,   8,   9,  24, -12,  10, -13,  -5, -17,
+     -2,  -4,   3, -10,   6,  17,   4,  19,   0,  11,
+     -6,  13,  -9, -33, -14, -10,  16, -17, -10,  -4,
+    }, {
+     90,  -3,   2,  -6, -10, -29, -24, -26, -21, -15,
+     15,   2,  16,   1,  25,   4,  21, -16,   6, -18,
+      3,  -8,   5, -24,   8,   7,  -9,   4,  -1,   3,
+      5,  18,  -1,  -7,   2,  -1,   2,  -1, -19,   3,
+    }, {
+     57,   0,  27,  13, -14,  -5,  -7,  11, -15,   4,
+      5,  16,  13,  29,   6, -13,   0, -25, -16, -31,
+    -12, -22,   2, -23,  -6,  16,  -7,  14,  -2,   3,
+      0, -12,   0, -33,   9,  13,  28,  -3,  14,   7,
+    }, {
+     79, -11,  15,  -4, -18, -23, -20,  -5, -30,  -7,
+      7,   2,  21,  21,   8,   3,  10, -28,  -4, -31,
+     -6, -25,   3, -37,  -4,   7, -20,   0,  -4,  -4,
+     11,  -7,   6,  -8,  27,  22,  14,  12,   5,  16,
+    }, {
+     47,  30,  15,  14,  14,   9,   9, -23,  13, -10,
+    -12,  -7, -16, -15,  -3,  -3,  -1,  14,   9,  12,
+      9,   8,   0,  10, -14,   4,  -9,   2,  -5,   8,
+    -13,  -3, -18, -10, -45,  -3,  16,  -4,   4,   0,
+    }, {
+     69,  17,   3,  -3,  10,  -8,  -3, -40,  -1, -21,
+    -10, -21,  -8, -23,  -1,  13,   8,  11,  21,  11,
+     15,   4,   0,  -2, -13,  -5, -23, -12,  -7,   0,
+     -1,   0, -10,  14, -28,   5,   1,  11,  -5,   7,
+    }, {
+     36,  21,  28,  16,   6,  16,  12,  -2,   4,  -2,
+    -20,  -7, -11,   4, -20,  -4, -12,   2,  -1,   0,
+      0,  -8,  -2,  -2, -27,   4, -21,  -2,  -9,   0,
+     -6, -29,  -9, -10, -21,  21,  28,  10,  29,  11,
+    }, {
+     58,   9,  16,  -1,   2,  -2,   0, -19, -10, -13,
+    -17, -21,  -3,  -3, -19,  12,  -2,   0,  10,  -1,
+      5, -12,   0, -15, -26,  -5, -34, -16, -11,  -7,
+      4, -25,  -2,  14,  -3,  29,  13,  25,  20,  20,
+    }, {
+     55,  28,  21,  27,  -2,   7,  -8, -20,   4,   1,
+      1,  18,   5,   4,   5, -16,   2,  -8,   5,  -5,
+     19,   2,  14,   3,   6,   0, -18,  -4,   2, -11,
+     -8,  18, -11, -10, -29,  -3,  10, -13,  -8,  -3,
+    }, {
+     77,  16,   9,   9,  -6, -11, -21, -37, -10, -10,
+      4,   5,  13,  -3,   7,   0,  13, -11,  17,  -6,
+     25,  -1,  15,  -9,   7,  -9, -32, -19,   0, -18,
+      2,  22,  -3,  15, -12,   5,  -4,   2, -17,   5,
+    }, {
+     44,  20,  34,  29, -10,  13,  -4,   0,  -4,   9,
+     -5,  19,  10,  24, -11, -17,  -8, -20,  -5, -19,
+      9, -14,  12,  -9,  -6,   0, -30,  -9,   0, -19,
+     -2,  -7,  -2, -10,  -5,  20,  21,   1,  17,   9,
+    }, {
+     66,   8,  23,  11, -14,  -5, -17, -16, -19,  -2,
+     -3,   5,  18,  17, -10,   0,   1, -23,   6, -20,
+     15, -18,  14, -22,  -5, -10, -44, -23,  -2, -26,
+      9,  -3,   4,  14,  12,  29,   7,  16,   7,  18,
+    }, {
+     18,   9, -17,  -4,  11,   3,   0,  11,   7,   4,
+     10,   3,  10, -18,  24,  -3,  14,   7,   4,  10,
+    -16,   1, -27,  -4, -27,  17,  12,  30,   0,  35,
+     -9,  -3, -12, -36, -35, -30,  -2, -13,   2, -11,
+    }, {
+     40,  -2, -29, -22,   7, -14, -12,  -5,  -7,  -7,
+     12,  -9,  18, -26,  26,  14,  24,   4,  16,   9,
+    -10,  -2, -26, -18, -26,   7,  -1,  15,  -1,  27,
+      2,   0,  -4, -11, -17, -21, -16,   1,  -7,  -3,
+    }, {
+      8,   1,  -3,  -2,   3,  10,   3,  32,  -1,  12,
+      2,   4,  15,   1,   7,  -3,   2,  -4,  -6,  -3,
+    -26, -15, -29, -17, -40,  17,   0,  26,  -2,  27,
+     -2, -29,  -4, -36, -10,  -6,   9,   0,  27,   0,
+    }, {
+     30, -11, -15, -20,   0,  -8,  -9,  15, -15,   0,
+      5,  -9,  23,  -6,   8,  13,  13,  -7,   5,  -3,
+    -20, -19, -27, -31, -39,   7, -13,  11,  -4,  19,
+      8, -25,   3, -11,   7,   2,  -4,  16,  18,   9,
+    }, {
+     26,   7, -11,   8,  -5,   1, -17,  14,  -1,  15,
+     24,  30,  32,   1,  33, -16,  18, -14,   0,  -8,
+     -6,  -4, -12, -12,  -6,  13,   2,  23,   8,  15,
+     -4,  17,  -5, -36, -18, -30,  -8, -22, -10, -14,
+    }, {
+     48,  -4, -23,  -9,  -9, -17, -30,  -2, -16,   3,
+     26,  16,  40,  -6,  35,   1,  28, -17,  12,  -9,
+      0,  -8, -11, -25,  -5,   3, -10,   8,   6,   7,
+      6,  22,   1, -11,  -1, -21, -22,  -7, -19,  -5,
+    }, {
+     15,   0,   2,  10, -13,   7, -14,  35, -10,  23,
+     16,  31,  37,  21,  16, -17,   6, -26, -10, -21,
+    -16, -21, -13, -25, -19,  13,  -8,  19,   5,   7,
+      1,  -8,   2, -36,   5,  -6,   3,  -8,  15,  -1,
+    }, {
+     37, -12,  -9,  -7, -17, -11, -26,  18, -25,  12,
+     19,  17,  45,  14,  17,   0,  17, -30,   1, -22,
+    -10, -25, -12, -38, -18,   3, -22,   4,   3,   0,
+     13,  -3,  10, -11,  23,   2, -10,   7,   5,   7,
+    }, {
+      5,  29,  -9,  11,  15,  22,   3,   0,  18,   8,
+     -1,   6,   7, -23,   6,  -6,   5,  12,  15,  21,
+      5,   8, -17,   9, -28,   0, -11,   6,   2,  12,
+    -11,   0, -14, -13, -49, -22,  -8,  -9,   4,  -9,
+    }, {
+     27,  16, -21,  -6,  12,   3,  -9, -16,   3,  -2,
+      1,  -7,  15, -31,   7,  10,  16,   9,  27,  21,
+     11,   5, -16,  -3, -26,  -9, -24,  -7,   0,   4,
+      0,   4,  -6,  11, -32, -14, -23,   6,  -5,  -1,
+    }, {
+     -4,  20,   3,  13,   8,  28,   6,  21,  10,  16,
+     -8,   7,  12,  -3, -11,  -7,  -5,   0,   4,   8,
+     -4,  -8, -18,  -3, -41,   0, -22,   2,   0,   4,
+     -5, -25,  -6, -14, -25,   1,   2,   4,  29,   2,
+    }, {
+     17,   8,  -8,  -4,   4,  10,  -6,   5,  -4,   5,
+     -6,  -6,  20, -10,  -9,   9,   4,  -2,  16,   7,
+      1, -12, -17, -16, -39,  -9, -36, -12,  -2,  -3,
+      6, -21,   1,  11,  -7,  10, -11,  20,  20,  11,
+    }, {
+     13,  27,  -3,  24,  -1,  19, -14,   3,   9,  20,
+     12,  33,  29,  -3,  15, -20,   9,  -9,  11,   3,
+     16,   2,  -2,   2,  -7,  -3, -20,   0,  10,  -7,
+     -7,  22,  -7, -13, -33, -23, -14, -18,  -7, -12,
+    }, {
+     35,  15, -15,   6,  -4,   1, -27, -12,  -5,   8,
+     15,  19,  37, -11,  16,  -2,  20, -12,  23,   2,
+     22,  -1,  -1, -11,  -5, -13, -34, -14,   8, -14,
+      4,  26,   0,  11, -16, -14, -29,  -2, -17,  -3,
+    }, {
+      3,  19,   9,  26,  -8,  26, -10,  24,   0,  28,
+      5,  33,  34,  17,  -2, -20,  -1, -22,   0, -10,
+      6, -14,  -3, -10, -20,  -4, -32,  -4,   7, -15,
+      0,  -3,   0, -13,  -9,   0,  -3,  -4,  17,   0,
+    }, {
+     25,   7,  -2,   8, -12,   7, -23,   8, -13,  16,
+      7,  20,  42,   9,   0,  -3,   9, -25,  12, -10,
+     12, -18,  -2, -24, -19, -13, -46, -19,   5, -22,
+     10,   0,   8,  11,   8,   9, -17,  11,   7,   8,
+    }, {
+    -25,  -7,   2,  -8,  12,  -7,  23,  -8,  13, -16,
+     -7, -20, -42,  -9,   0,   3,  -9,  25, -12,  10,
+    -12,  18,   2,  24,  19,  13,  46,  19,  -5,  22,
+    -10,   0,  -8, -11,  -8,  -9,  17, -11,  -7,  -8,
+    }, {
+     -3, -19,  -9, -26,   8, -26,  10, -24,   0, -28,
+     -5, -33, -34, -17,   2,  20,   1,  22,   0,  10,
+     -6,  14,   3,  10,  20,   4,  32,   4,  -7,  15,
+      0,   3,   0,  13,   9,   0,   3,   4, -17,   0,
+    }, {
+    -35, -15,  15,  -6,   4,  -1,  27,  12,   5,  -8,
+    -15, -19, -37,  11, -16,   2, -20,  12, -23,  -2,
+    -22,   1,   1,  11,   5,  13,  34,  14,  -8,  14,
+     -4, -26,   0, -11,  16,  14,  29,   2,  17,   3,
+    }, {
+    -13, -27,   3, -24,   1, -19,  14,  -3,  -9, -20,
+    -12, -33, -29,   3, -15,  20,  -9,   9, -11,  -3,
+    -16,  -2,   2,  -2,   7,   3,  20,   0, -10,   7,
+      7, -22,   7,  13,  33,  23,  14,  18,   7,  12,
+    }, {
+    -17,  -8,   8,   4,  -4, -10,   6,  -5,   4,  -5,
+      6,   6, -20,  10,   9,  -9,  -4,   2, -16,  -7,
+     -1,  12,  17,  16,  39,   9,  36,  12,   2,   3,
+     -6,  21,  -1, -11,   7, -10,  11, -20, -20, -11,
+    }, {
+      4, -20,  -3, -13,  -8, -28,  -6, -21, -10, -16,
+      8,  -7, -12,   3,  11,   7,   5,   0,  -4,  -8,
+      4,   8,  18,   3,  41,   0,  22,  -2,   0,  -4,
+      5,  25,   6,  14,  25,  -1,  -2,  -4, -29,  -2,
+    }, {
+    -27, -16,  21,   6, -12,  -3,   9,  16,  -3,   2,
+     -1,   7, -15,  31,  -7, -10, -16,  -9, -27, -21,
+    -11,  -5,  16,   3,  26,   9,  24,   7,   0,  -4,
+      0,  -4,   6, -11,  32,  14,  23,  -6,   5,   1,
+    }, {
+     -5, -29,   9, -11, -15, -22,  -3,   0, -18,  -8,
+      1,  -6,  -7,  23,  -6,   6,  -5, -12, -15, -21,
+     -5,  -8,  17,  -9,  28,   0,  11,  -6,  -2, -12,
+     11,   0,  14,  13,  49,  22,   8,   9,  -4,   9,
+    }, {
+    -37,  12,   9,   7,  17,  11,  26, -18,  25, -12,
+    -19, -17, -45, -14, -17,   0, -17,  30,  -1,  22,
+     10,  25,  12,  38,  18,  -3,  22,  -4,  -3,   0,
+    -13,   3, -10,  11, -23,  -2,  10,  -7,  -5,  -7,
+    }, {
+    -15,   0,  -2, -10,  13,  -7,  14, -35,  10, -23,
+    -16, -31, -37, -21, -16,  17,  -6,  26,  10,  21,
+     16,  21,  13,  25,  19, -13,   8, -19,  -5,  -7,
+     -1,   8,  -2,  36,  -5,   6,  -3,   8, -15,   1,
+    }, {
+    -48,   4,  23,   9,   9,  17,  30,   2,  16,  -3,
+    -26, -16, -40,   6, -35,  -1, -28,  17, -12,   9,
+      0,   8,  11,  25,   5,  -3,  10,  -8,  -6,  -7,
+     -6, -22,  -1,  11,   1,  21,  22,   7,  19,   5,
+    }, {
+    -26,  -7,  11,  -8,   5,  -1,  17, -14,   1, -15,
+    -24, -30, -32,  -1, -33,  16, -18,  14,   0,   8,
+      6,   4,  12,  12,   6, -13,  -2, -23,  -8, -15,
+      4, -17,   5,  36,  18,  30,   8,  22,  10,  14,
+    }, {
+    -30,  11,  15,  20,   0,   8,   9, -15,  15,   0,
+     -5,   9, -23,   6,  -8, -13, -13,   7,  -5,   3,
+     20,  19,  27,  31,  39,  -7,  13, -11,   4, -19,
+     -8,  25,  -3,  11,  -7,  -2,   4, -16, -18,  -9,
+    }, {
+     -8,  -1,   3,   2,  -3, -10,  -3, -32,   1, -12,
+     -2,  -4, -15,  -1,  -7,   3,  -2,   4,   6,   3,
+     26,  15,  29,  17,  40, -17,   0, -26,   2, -27,
+      2,  29,   4,  36,  10,   6,  -9,   0, -27,   0,
+    }, {
+    -40,   2,  29,  22,  -7,  14,  12,   5,   7,   7,
+    -12,   9, -18,  26, -26, -14, -24,  -4, -16,  -9,
+     10,   2,  26,  18,  26,  -7,   1, -15,   1, -27,
+     -2,   0,   4,  11,  17,  21,  16,  -1,   7,   3,
+    }, {
+    -18,  -9,  17,   4, -11,  -3,   0, -11,  -7,  -4,
+    -10,  -3, -10,  18, -24,   3, -14,  -7,  -4, -10,
+     16,  -1,  27,   4,  27, -17, -12, -30,   0, -35,
+      9,   3,  12,  36,  35,  30,   2,  13,  -2,  11,
+    }, {
+    -66,  -8, -23, -11,  14,   5,  17,  16,  19,   2,
+      3,  -5, -18, -17,  10,   0,  -1,  23,  -6,  20,
+    -15,  18, -14,  22,   5,  10,  44,  23,   2,  26,
+     -9,   3,  -4, -14, -12, -29,  -7, -16,  -7, -18,
+    }, {
+    -44, -20, -34, -29,  10, -13,   4,   0,   4,  -9,
+      5, -19, -10, -24,  11,  17,   8,  20,   5,  19,
+     -9,  14, -12,   9,   6,   0,  30,   9,   0,  19,
+      2,   7,   2,  10,   5, -20, -21,  -1, -17,  -9,
+    }, {
+    -77, -16,  -9,  -9,   6,  11,  21,  37,  10,  10,
+     -4,  -5, -13,   3,  -7,   0, -13,  11, -17,   6,
+    -25,   1, -15,   9,  -7,   9,  32,  19,   0,  18,
+     -2, -22,   3, -15,  12,  -5,   4,  -2,  17,  -5,
+    }, {
+    -55, -28, -21, -27,   2,  -7,   8,  20,  -4,  -1,
+     -1, -18,  -5,  -4,  -5,  16,  -2,   8,  -5,   5,
+    -19,  -2, -14,  -3,  -6,   0,  18,   4,  -2,  11,
+      8, -18,  11,  10,  29,   3, -10,  13,   8,   3,
+    }, {
+    -58,  -9, -16,   1,  -2,   2,   0,  19,  10,  13,
+     17,  21,   3,   3,  19, -12,   2,   0, -10,   1,
+     -5,  12,   0,  15,  26,   5,  34,  16,  11,   7,
+     -4,  25,   2, -14,   3, -29, -13, -25, -20, -20,
+    }, {
+    -36, -21, -28, -16,  -6, -16, -12,   2,  -4,   2,
+     20,   7,  11,  -4,  20,   4,  12,  -2,   1,   0,
+      0,   8,   2,   2,  27,  -4,  21,   2,   9,   0,
+      6,  29,   9,  10,  21, -21, -28, -10, -29, -11,
+    }, {
+    -69, -17,  -3,   3, -10,   8,   3,  40,   1,  21,
+     10,  21,   8,  23,   1, -13,  -8, -11, -21, -11,
+    -15,  -4,   0,   2,  13,   5,  23,  12,   7,   0,
+      1,   0,  10, -14,  28,  -5,  -1, -11,   5,  -7,
+    }, {
+    -47, -30, -15, -14, -14,  -9,  -9,  23, -13,  10,
+     12,   7,  16,  15,   3,   3,   1, -14,  -9, -12,
+     -9,  -8,   0, -10,  14,  -4,   9,  -2,   5,  -8,
+     13,   3,  18,  10,  45,   3, -16,   4,  -4,   0,
+    }, {
+    -79,  11, -15,   4,  18,  23,  20,   5,  30,   7,
+     -7,  -2, -21, -21,  -8,  -3, -10,  28,   4,  31,
+      6,  25,  -3,  37,   4,  -7,  20,   0,   4,   4,
+    -11,   7,  -6,   8, -27, -22, -14, -12,  -5, -16,
+    }, {
+    -57,   0, -27, -13,  14,   5,   7, -11,  15,  -4,
+     -5, -16, -13, -29,  -6,  13,   0,  25,  16,  31,
+     12,  22,  -2,  23,   6, -16,   7, -14,   2,  -3,
+      0,  12,   0,  33,  -9, -13, -28,   3, -14,  -7,
+    }, {
+    -90,   3,  -2,   6,  10,  29,  24,  26,  21,  15,
+    -15,  -2, -16,  -1, -25,  -4, -21,  16,  -6,  18,
+     -3,   8,  -5,  24,  -8,  -7,   9,  -4,   1,  -3,
+     -5, -18,   1,   7,  -2,   1,  -2,   1,  19,  -3,
+    }, {
+    -67,  -8, -14, -11,   7,  11,  11,   9,   7,   3,
+    -13, -16,  -8,  -9, -24,  12, -10,  13,   5,  17,
+      2,   4,  -3,  10,  -6, -17,  -4, -19,   0, -11,
+      6, -13,   9,  33,  14,  10, -16,  17,  10,   4,
+    }, {
+    -71,  10,  -9,  17,   1,  20,   3,   8,  21,  18,
+      6,  24,   0,  -1,   0, -16,  -6,   5,   0,  13,
+     17,  19,  11,  29,  25, -11,  11,  -6,  13, -15,
+     -7,  29,   0,   8, -11, -22, -20, -21, -17, -18,
+    }, {
+    -49,  -2, -21,   0,  -1,   2,  -9,  -8,   6,   6,
+      8,  10,   8,  -9,   2,   0,   4,   2,  13,  12,
+     23,  15,  12,  16,  26, -21,  -2, -21,  11, -23,
+      4,  33,   7,  33,   6, -13, -34,  -5, -27, -10,
+    }, {
+    -82,   1,   4,  19,  -6,  27,   6,  29,  12,  26,
+     -1,  24,   5,  18, -17, -17, -17,  -6, -10,   0,
+      7,   2,   9,  16,  12, -11,   0, -11,   9, -23,
+      0,   3,   8,   8,  13,   1,  -8,  -7,   7,  -6,
+    }, {
+    -60, -10,  -7,   1,  -9,   8,  -6,  13,  -2,  15,
+      1,  10,  13,  11, -15,   0,  -6,  -9,   1,   0,
+     13,  -1,  11,   3,  13, -21, -13, -26,   7, -31,
+     10,   7,  16,  33,  31,  10, -22,   8,  -1,   2,
+    }, {
+     -3,   7,  -5,  -5,   8,  -2,  17,  -9,  18, -24,
+     -2, -19, -10,  -4,  28,  17,   5,  28,  -2,   7,
+     -4,  15,   7,   8,   6,  23,  13,  21, -14,  20,
+    -17, -18, -11, -33, -30, -11,  23, -13,  -5,  -9,
+    }, {
+     18,  -4, -17, -23,   4, -20,   4, -26,   3, -36,
+      0, -32,  -2, -12,  29,  34,  16,  24,  10,   6,
+      0,  12,   8,  -4,   8,  13,   0,   6, -16,  12,
+     -5, -13,  -3,  -7, -13,  -3,   8,   2, -14,   0,
+    }, {
+    -13,   0,   8,  -3,   0,   4,  21,  11,   9, -16,
+    -10, -18,  -5,  16,  10,  16,  -5,  15, -13,  -5,
+    -15,  -1,   6,  -4,  -6,  23,   2,  16, -17,  12,
+    -10, -44,  -3, -33,  -6,  12,  34,   1,  20,   3,
+    }, {
+      8, -12,  -3, -21,  -3, -14,   8,  -5,  -4, -28,
+     -7, -32,   2,   8,  12,  34,   4,  12,  -1,  -6,
+     -9,  -4,   7, -17,  -4,  13, -11,   1, -19,   4,
+      0, -39,   4,  -7,  11,  21,  20,  16,  10,  11,
+    }, {
+      4,   6,   0,   7,  -8,  -4,   0,  -6,   9, -13,
+     11,   7,  11,  15,  37,   4,   9,   5,  -5, -11,
+      5,   9,  22,   1,  27,  18,   4,  14,  -5,   0,
+    -12,   3,  -4, -32, -14, -12,  17, -22, -17, -11,
+    }, {
+     26,  -6, -11, -10, -12, -23, -12, -23,  -5, -24,
+     13,  -5,  19,   8,  38,  21,  20,   2,   6, -12,
+     11,   5,  23, -11,  29,   9,  -9,   0,  -7,  -6,
+     -1,   7,   2,  -7,   3,  -3,   2,  -6, -27,  -3,
+    }, {
+     -6,  -2,  14,   9, -16,   1,   3,  14,   0,  -5,
+      3,   8,  16,  36,  19,   3,  -1,  -6, -17, -24,
+     -4,  -7,  21, -11,  14,  18,  -7,   9,  -9,  -7,
+     -6, -22,   3, -33,  10,  11,  28,  -7,   7,   0,
+    }, {
+     16, -14,   2,  -8, -20, -17,  -9,  -2, -14, -16,
+      6,  -5,  24,  28,  21,  20,   8,  -9,  -4, -25,
+      1, -11,  22, -24,  15,   8, -21,  -5, -11, -14,
+      5, -18,  11,  -7,  27,  20,  14,   7,  -1,   9,
+    }, {
+    -16,  27,   2,  10,  13,  16,  20, -20,  29, -20,
+    -14, -16, -13,  -8,   9,  13,  -2,  33,   9,  19,
+     17,  23,  17,  22,   6,   6,  -9,  -2, -12,  -2,
+    -20, -13, -13, -10, -45,  -4,  16,  -8,  -2,  -7,
+    }, {
+      5,  15,  -9,  -7,   9,  -2,   8, -37,  14, -31,
+    -11, -29,  -5, -16,  11,  30,   7,  29,  21,  18,
+     23,  19,  18,   9,   7,  -3, -23, -17, -14,  -9,
+     -8,  -9,  -6,  15, -27,   4,   2,   6, -12,   1,
+    }, {
+    -26,  19,  15,  12,   5,  22,  24,   0,  21, -12,
+    -21, -15,  -8,  11,  -7,  12, -14,  20,  -2,   6,
+      7,   6,  16,   9,  -6,   5, -21,  -7, -15, -10,
+    -13, -39,  -5, -10, -20,  19,  28,   5,  22,   5,
+    }, {
+     -4,   6,   3,  -5,   1,   4,  11, -16,   6, -23,
+    -19, -29,   0,   3,  -6,  30,  -3,  17,  10,   5,
+     13,   2,  17,  -3,  -5,  -3, -35, -21, -17, -17,
+     -2, -35,   2,  15,  -3,  28,  13,  21,  13,  13,
+    }, {
+     -8,  25,   8,  23,  -3,  13,   3, -17,  20,  -8,
+      0,  10,   8,  11,  18,   0,   1,  10,   5,   0,
+     28,  17,  32,  15,  26,   1, -19,  -9,  -3, -21,
+    -15,   7,  -6,  -9, -29,  -5,  10, -17, -15,  -9,
+    }, {
+     13,  13,  -3,   5,  -7,  -4,  -9, -34,   5, -20,
+      2,  -3,  16,   3,  20,  17,  11,   7,  17,   0,
+     34,  13,  33,   2,  28,  -8, -32, -24,  -5, -29,
+     -3,  12,   0,  15, -11,   3,  -3,  -2, -24,  -1,
+    }, {
+    -18,  17,  21,  25, -11,  19,   6,   3,  11,   0,
+     -7,  11,  13,  31,   1,   0,  -9,  -1,  -5, -12,
+     18,   0,  31,   2,  13,   1, -30, -14,  -7, -29,
+     -9, -18,   1, -10,  -4,  18,  22,  -3,  10,   2,
+    }, {
+      3,   5,   9,   7, -15,   1,  -5, -13,  -2, -12,
+     -5,  -2,  21,  23,   2,  16,   0,  -5,   6, -13,
+     23,  -3,  32, -10,  15,  -8, -44, -28,  -9, -37,
+      2, -13,   9,  15,  12,  27,   7,  12,   0,  11,
+    }, {
+    -44,   6, -30,  -8,   9,  10,  11,  14,  23,  -5,
+      8,  -4,  14, -12,  37,  14,  12,  26,   4,  16,
+     -8,  16,  -9,   7,  -6,  19,  12,  25,  -5,  24,
+    -15, -13,  -8, -36, -34, -31,  -1, -18,  -4, -18,
+    }, {
+    -22,  -5, -42, -26,   6,  -8,  -1,  -2,   9, -17,
+     10, -18,  21, -19,  39,  31,  23,  23,  16,  15,
+     -2,  12,  -7,  -6,  -5,   9,  -1,  10,  -7,  16,
+     -4,  -9,   0, -10, -17, -22, -16,  -2, -14,  -9,
+    }, {
+    -55,  -1, -17,  -6,   1,  16,  15,  35,  15,   2,
+      0,  -4,  19,   8,  20,  13,   1,  14,  -7,   3,
+    -18,   0, -10,  -5, -19,  19,   0,  21,  -8,  16,
+     -9, -39,   0, -36, -10,  -7,   9,  -4,  20,  -5,
+    }, {
+    -33, -13, -29, -24,  -1,  -1,   2,  18,   0,  -9,
+      3, -17,  27,   0,  21,  30,  12,  11,   5,   2,
+    -12,  -4,  -9, -19, -18,   9, -13,   6, -11,   8,
+      2, -35,   8, -10,   7,   1,  -4,  11,  10,   2,
+    }, {
+    -36,   5, -24,   4,  -7,   7,  -6,  17,  14,   5,
+     22,  22,  35,   8,  46,   1,  17,   3,   0,  -2,
+      2,  10,   5,   0,  14,  15,   2,  18,   2,   4,
+    -11,   7,  -1, -36, -18, -32,  -7, -27, -17, -20,
+    }, {
+    -14,  -7, -36, -13, -10, -10, -18,   0,   0,  -5,
+     25,   8,  43,   0,  48,  18,  27,   0,  12,  -3,
+      7,   6,   7, -13,  15,   5, -11,   3,   0,  -2,
+      0,  12,   6, -10,   0, -23, -22, -11, -26, -12,
+    }, {
+    -47,  -3, -11,   6, -15,  13,  -2,  38,   6,  13,
+     15,  22,  40,  28,  28,   0,   5,  -8, -10, -15,
+     -7,  -7,   4, -13,   1,  14,  -9,  14,   0,  -2,
+     -4, -18,   7, -36,   6,  -8,   3, -13,   7,  -8,
+    }, {
+    -25, -15, -22, -11, -18,  -4, -15,  22,  -8,   2,
+     17,   9,  48,  20,  30,  17,  16, -11,   1, -16,
+     -2, -10,   5, -26,   2,   4, -22,   0,  -2, -10,
+      6, -13,  14, -10,  23,   0, -10,   2,  -1,   0,
+    }, {
+    -57,  26, -22,   7,  14,  28,  14,   3,  35,   0,
+     -3,  -1,  11, -16,  18,  10,   4,  31,  15,  28,
+     14,  23,   1,  21,  -7,   2, -11,   1,  -3,   1,
+    -18,  -9, -10, -13, -49, -24,  -8, -14,  -2, -16,
+    }, {
+    -35,  14, -34, -10,  10,  10,   1, -12,  20, -12,
+      0, -15,  18, -24,  20,  27,  14,  28,  27,  27,
+     20,  19,   2,   8,  -5,  -7, -25, -13,  -5,  -5,
+     -6,  -5,  -2,  12, -31, -15, -23,   1, -12,  -8,
+    }, {
+    -68,  18,  -9,   9,   6,  35,  18,  25,  26,   7,
+    -10,  -1,  16,   3,   1,   9,  -6,  19,   4,  15,
+      4,   6,   0,   8, -20,   2, -23,  -2,  -7,  -5,
+    -12, -35,  -1, -13, -24,   0,   3,   0,  22,  -4,
+    }, {
+    -46,   6, -21,  -8,   2,  16,   5,   8,  11,  -4,
+     -8, -15,  24,  -4,   2,  26,   3,  16,  16,  14,
+      9,   2,   1,  -4, -19,  -7, -36, -17,  -9, -13,
+      0, -31,   5,  12,  -7,   8, -11,  15,  13,   4,
+    }, {
+    -49,  24, -16,  20,  -2,  26,  -2,   7,  25,  10,
+     11,  25,  32,   3,  27,  -2,   8,   8,  11,   9,
+     24,  17,  16,  14,  13,  -2, -20,  -5,   4, -17,
+    -14,  12,  -3, -13, -33, -25, -14, -23, -15, -19,
+    }, {
+    -27,  12, -28,   2,  -6,   7, -15,  -9,  11,  -1,
+     13,  11,  40,  -4,  29,  14,  19,   5,  23,   8,
+     30,  13,  17,   0,  14, -12, -34, -20,   2, -25,
+     -2,  16,   4,  12, -15, -16, -29,  -7, -24, -10,
+    }, {
+    -60,  16,  -3,  22, -10,  32,   0,  28,  17,  18,
+      3,  25,  37,  23,  10,  -3,  -2,  -3,   0,  -3,
+     14,   0,  14,   1,   0,  -2, -32,  -9,   1, -25,
+     -7, -13,   5, -13,  -8,  -1,  -2,  -8,  10,  -6,
+    }, {
+    -38,   4, -15,   4, -14,  13, -12,  11,   2,   6,
+      6,  11,  45,  16,  11,  13,   7,  -6,  12,  -4,
+     20,  -3,  16, -12,   1, -12, -46, -24,   0, -33,
+      3,  -9,  12,  12,   8,   7, -17,   6,   0,   2
+    }
+};
 
-    ractx->lpc_coef[0] = ractx->lpc_tables[0];
-    ractx->lpc_coef[1] = ractx->lpc_tables[1];
+const int8_t ff_cb2_vects[128][40]={
+    {
+     73, -32, -60, -15, -26,  59,   2, -33,  30, -10,
+     -3, -17,   8,  30,  -1, -26,  -4, -22,  10,  16,
+    -36,  -5, -11,  56,  37,   6, -10,  -5, -13,  -3,
+      6,  -5,  11,   4, -19,  -5, -16,  41,  24,  13,
+    }, {
+      4, -11, -37,  23,  -5,  46,  -2, -29,  -5, -39,
+    -21,  -9,   0,  49,  12,  -9, -16, -26,  22,  15,
+    -45, -20,  -5,  40,  22,  17, -26,  31, -14,   2,
+    -14,  10,  30,  20, -27,  -9, -39,  39,  18,   5,
+    }, {
+     34, -25, -48, -28, -11,  34,  -2, -41,   9,  -7,
+    -17,  21,  20,  24, -17, -33,   0, -24,  10,  42,
+      3,  -5,  10,  42,  11,   8,  -3,   3,  16,   9,
+     22,  -2,   0, -33, -10,  18,   7,  58,  10,  28,
+    }, {
+    -34,  -4, -25,  10,   9,  21,  -7, -36, -26, -36,
+    -35,  28,  12,  42,  -3, -16, -12, -28,  21,  42,
+     -5, -21,  16,  26,  -4,  19, -19,  39,  15,  15,
+      1,  13,  19, -17, -17,  14, -15,  55,   4,  19,
+    }, {
+     28, -20, -51, -14,  -6,   7,   0, -26,  27,  -4,
+     18, -40,  -6,  16,  -1, -15,   0, -55,  -5, -16,
+    -19,  14,  -3,  49,  14,   1, -22, -30, -12,   0,
+     24,  15,   9, -17, -45, -29,   4,  28,  51,  35,
+    }, {
+    -40,   0, -28,  24,  14,  -5,  -4, -21,  -7, -33,
+      0, -32, -15,  35,  12,   1, -11, -58,   5, -16,
+    -28,   0,   1,  33,   0,  11, -39,   5, -14,   6,
+      3,  31,  28,  -1, -53, -33, -19,  25,  46,  26,
+    }, {
+    -11, -14, -39, -27,   9, -17,  -4, -33,   6,   0,
+      4,  -1,   5,  10, -17, -22,   5, -57,  -5,   9,
+     20,  13,  18,  35, -11,   3, -16, -22,  17,  13,
+     40,  19,  -1, -55, -35,  -5,  27,  44,  37,  49,
+    }, {
+    -80,   6, -16,  11,  30, -30,  -9, -28, -28, -29,
+    -13,   6,  -2,  28,  -3,  -5,  -7, -60,   5,   9,
+     11,  -1,  24,  19, -27,  13, -32,  13,  15,  19,
+     19,  35,  17, -39, -43,  -9,   4,  42,  32,  41,
+    }, {
+     78, -21, -43,   4, -38,  17,  17,  -5,  55,  24,
+    -15, -36,  14,   4,  24, -24,  12,   5,  17,  31,
+    -54,  -5,  -2,  27,  43, -12,   2,   9,  -9, -15,
+     22,  -3,  28,  21, -20,   3,  20,  28,   9,  -5,
+    }, {
+      9,  -1, -20,  43, -17,   3,  12,   0,  20,  -4,
+    -33, -29,   6,  22,  38,  -7,   0,   1,  29,  30,
+    -63, -21,   3,  11,  27,  -1, -14,  45, -10,  -9,
+      1,  12,  47,  37, -28,   0,  -2,  26,   4, -13,
+    }, {
+     39, -14, -30,  -8, -22,  -8,  12, -12,  34,  27,
+    -29,   2,  26,  -2,   8, -31,  16,   3,  17,  57,
+    -14,  -6,  19,  13,  16, -10,   8,  17,  20,  -2,
+     38,   0,  17, -16, -11,  27,  44,  45,  -4,   8,
+    }, {
+    -29,   5,  -7,  30,  -1, -21,   7,  -7,   0,   0,
+    -47,   9,  18,  15,  22, -14,   4,   0,  28,  57,
+    -23, -21,  25,  -2,   1,   0,  -7,  53,  19,   3,
+     17,  15,  36,   0, -19,  24,  21,  43,  -9,   0,
+    }, {
+     33, -10, -34,   5, -17, -35,  15,   1,  53,  30,
+      6, -59,   0, -10,  24, -13,  17, -27,   1,  -1,
+    -37,  13,   4,  20,  20, -18, -10, -16,  -8, -11,
+     39,  18,  26,   0, -46, -20,  41,  15,  37,  15,
+    }, {
+    -35,  10, -11,  44,   3, -48,  10,   6,  17,   2,
+    -11, -51,  -8,   8,  38,   3,   4, -31,  12,  -2,
+    -46,  -1,  10,   4,   5,  -7, -26,  19, -10,  -5,
+     18,  34,  45,  15, -54, -24,  18,  13,  31,   7,
+    }, {
+     -5,  -3, -21,  -7,  -2, -60,  10,  -5,  32,  34,
+     -7, -20,  11, -16,   8, -20,  21, -29,   1,  24,
+      2,  13,  27,   6,  -5, -15,  -3,  -8,  21,   1,
+     55,  21,  15, -38, -37,   3,  65,  32,  23,  30,
+    }, {
+    -74,  17,   0,  31,  18, -73,   5,   0,  -3,   5,
+    -25, -12,   3,   1,  22,  -3,   9, -33,  12,  24,
+     -6,  -2,  33,  -9, -21,  -5, -20,  27,  19,   7,
+     34,  37,  34, -22, -44,   0,  41,  29,  17,  21,
+    }, {
+     76, -35, -31, -28, -49,  43, -40,   0,  29, -14,
+      8,   5,  10,  18, -26, -46,   0,   7,   6,   3,
+    -25,  -7,  -2,  40,  28,  14,  18,  -3, -27, -28,
+     -8, -45, -13,  34, -13, -27, -15,  31,  12,   3,
+    }, {
+      7, -15,  -9,   9, -28,  29, -45,   5,  -6, -43,
+     -9,  12,   2,  36, -12, -30, -11,   3,  17,   3,
+    -34, -22,   3,  24,  12,  24,   2,  32, -28, -22,
+    -29, -29,   5,  50, -21, -31, -38,  29,   7,  -5,
+    }, {
+     36, -29, -19, -41, -34,  18, -45,  -6,   8, -10,
+     -5,  43,  23,  11, -42, -53,   5,   5,   6,  30,
+     14,  -8,  20,  26,   1,  16,  25,   4,   3, -15,
+      7, -41, -23,  -3,  -4,  -3,   8,  48,  -1,  17,
+    }, {
+    -32,  -8,   3,  -2, -13,   4, -50,  -1, -27, -39,
+    -23,  51,  15,  30, -27, -37,  -7,   1,  17,  29,
+      5, -23,  25,  10, -14,  26,   8,  41,   1,  -9,
+    -13, -26,  -5,  12, -12,  -7, -14,  45,  -6,   9,
+    }, {
+     31, -24, -23, -27, -29,  -9, -43,   8,  26,  -7,
+     30, -17,  -4,   3, -26, -35,   5, -24, -10, -28,
+     -9,  12,   5,  33,   5,   8,   5, -29, -26, -24,
+      9, -23, -14,  12, -39, -52,   5,  18,  39,  24,
+    }, {
+    -37,  -3,   0,  10,  -7, -22, -48,  12,  -8, -36,
+     12,  -9, -12,  22, -12, -19,  -6, -28,   0, -29,
+    -18,  -3,  11,  17, -10,  18, -10,   7, -27, -18,
+    -11,  -7,   3,  28, -47, -55, -18,  15,  34,  16,
+    }, {
+     -8, -17, -10, -40, -13, -34, -47,   0,   5,  -4,
+     16,  21,   8,  -2, -42, -43,  10, -26, -10,  -2,
+     31,  11,  27,  19, -21,  10,  12, -20,   3, -11,
+     25, -20, -25, -25, -29, -28,  28,  34,  25,  38,
+    }, {
+    -77,   2,  11,  -1,   7, -47, -52,   5, -29, -33,
+     -1,  28,   0,  15, -28, -26,  -2, -30,   0,  -2,
+     22,  -4,  33,   3, -36,  21,  -3,  15,   2,  -5,
+      4,  -4,  -6,  -9, -37, -31,   5,  32,  20,  30,
+    }, {
+     81, -25, -14,  -8, -61,   0, -25,  28,  54,  20,
+     -3, -14,  17,  -8,   0, -44,  16,  35,  13,  18,
+    -43,  -7,   6,  11,  33,  -4,  30,  11, -22, -40,
+      6, -43,   3,  50, -14, -18,  22,  18,  -1, -16,
+    }, {
+     12,  -4,   8,  29, -39, -12, -30,  33,  19,  -8,
+    -21,  -6,   8,   9,  13, -28,   4,  31,  24,  18,
+    -52, -23,  12,  -4,  18,   5,  14,  47, -24, -34,
+    -14, -27,  22,  66, -22, -22,  -1,  16,  -6, -24,
+    }, {
+     41, -18,  -2, -21, -45, -24, -30,  21,  33,  24,
+    -17,  24,  29, -15, -16, -51,  21,  33,  13,  45,
+     -3,  -8,  28,  -2,   7,  -2,  37,  19,   7, -27,
+     22, -39,  -7,  12,  -5,   5,  45,  35, -15,  -1,
+    }, {
+    -27,   1,  20,  17, -24, -38, -35,  26,  -1,  -4,
+    -35,  32,  21,   3,  -2, -35,   8,  29,  24,  44,
+    -12, -24,  34, -18,  -8,   7,  21,  55,   5, -21,
+      2, -23,  11,  28, -13,   1,  22,  33, -21, -10,
+    }, {
+     36, -13,  -5,  -7, -40, -51, -28,  36,  52,  27,
+     18, -36,   2, -22,   0, -33,  21,   2,  -3, -13,
+    -26,  11,  14,   4,  10, -10,  18, -14, -22, -36,
+     24, -21,   1,  28, -40, -42,  42,   5,  25,   5,
+    }, {
+    -32,   6,  17,  31, -19, -65, -33,  41,  16,  -1,
+      0, -29,  -6,  -4,  13, -17,   9,  -1,   8, -14,
+    -35,  -3,  19, -11,  -4,   0,   1,  21, -23, -30,
+      3,  -5,  20,  44, -48, -46,  19,   3,  20,  -3,
+    }, {
+     -3,  -7,   6, -20, -25, -77, -32,  29,  31,  30,
+      4,   2,  14, -29, -16, -40,  26,   0,  -3,  12,
+     13,  10,  36,  -9, -15,  -8,  24,  -6,   7, -22,
+     40, -17,  -8,  -9, -31, -18,  66,  22,  11,  19,
+    }, {
+    -72,  13,  29,  18,  -4, -90, -37,  34,  -4,   1,
+    -13,   9,   6, -11,  -2, -24,  13,  -3,   7,  11,
+      4,  -4,  42, -25, -31,   1,   8,  29,   6, -17,
+     19,  -2,  10,   6, -38, -22,  42,  19,   6,  11,
+    }, {
+    116, -20, -68, -30, -28,  83,  28, -18,  32, -22,
+    -13, -21,   5,  28,   5,  -7, -24,  -8, -22,  17,
+    -23,  30, -25,  45,  15,  -9, -11, -18,  22, -10,
+      4,  -2,  19, -12,  23,   3, -43,   2,  12,  -4,
+    }, {
+     47,   0, -45,   7,  -7,  69,  23, -13,  -2, -51,
+    -32, -14,  -3,  47,  19,   8, -37, -11, -10,  16,
+    -32,  15, -19,  29,   0,   1, -28,  18,  20,  -4,
+    -16,  13,  38,   3,  15,   0, -66,   0,   7, -13,
+    }, {
+     77, -13, -56, -43, -13,  57,  23, -26,  11, -19,
+    -27,  16,  17,  22, -10, -15, -19, -10, -22,  43,
+     16,  30,  -2,  31, -11,  -6,  -5,  -9,  52,   2,
+     20,   0,   8, -50,  33,  27, -19,  19,  -1,   9,
+    }, {
+      8,   6, -33,  -4,   7,  44,  18, -21, -23, -48,
+    -46,  24,   9,  40,   3,   1, -32, -13, -11,  43,
+      7,  14,   3,  15, -26,   3, -21,  26,  50,   8,
+      0,  16,  27, -34,  25,  23, -43,  17,  -6,   1,
+    }, {
+     71,  -9, -59, -29,  -8,  30,  26, -11,  30, -16,
+      8, -44,  -9,  14,   5,   2, -19, -40, -38, -15,
+     -7,  50, -17,  38,  -7, -14, -24, -43,  22,  -6,
+     22,  19,  17, -34,  -2, -20, -23, -10,  39,  16,
+    }, {
+      2,  11, -36,   9,  13,  17,  21,  -6,  -5, -45,
+    -10, -36, -18,  33,  19,  19, -31, -44, -27, -15,
+    -16,  34, -11,  22, -22,  -4, -40,  -7,  21,   0,
+      1,  35,  36, -18, -10, -24, -46, -12,  34,   8,
+    }, {
+     32,  -2, -47, -42,   7,   5,  21, -18,   9, -12,
+     -5,  -5,   2,   8, -10,  -4, -14, -42, -38,  10,
+     33,  49,   5,  24, -33, -12, -17, -35,  52,   6,
+     38,  22,   7, -72,   7,   3,   0,   6,  25,  30,
+    }, {
+    -36,  18, -24,  -3,  28,  -7,  16, -13, -26, -41,
+    -24,   1,  -5,  26,   3,  12, -27, -46, -27,  10,
+     24,  34,  10,   8, -49,  -2, -34,   0,  51,  12,
+     17,  38,  25, -56,   0,   0, -22,   3,  20,  22,
+    }, {
+    121,  -9, -50, -10, -40,  40,  43,   9,  58,  12,
+    -25, -41,  11,   2,  31,  -5,  -8,  19, -15,  32,
+    -41,  30, -16,  16,  20, -28,   0,  -3,  26, -22,
+     19,   0,  36,   4,  22,  12,  -6,  -9,  -1, -24,
+    }, {
+     52,  10, -27,  27, -18,  26,  38,  14,  23, -16,
+    -44, -33,   3,  20,  45,  10, -20,  15,  -3,  31,
+    -50,  14, -10,   0,   5, -17, -15,  32,  24, -16,
+     -1,  15,  55,  20,  14,   8, -29, -12,  -7, -32,
+    }, {
+     82,  -3, -38, -23, -24,  15,  38,   2,  37,  15,
+    -39,  -2,  23,  -4,  15, -12,  -3,  17, -15,  58,
+     -1,  29,   6,   2,  -5, -26,   7,   4,  56,  -9,
+     35,   3,  25, -33,  32,  36,  17,   7, -15,  -9,
+    }, {
+     13,  17, -15,  15,  -3,   1,  33,   7,   1, -12,
+    -58,   5,  15,  13,  29,   3, -16,  13,  -4,  57,
+    -10,  13,  11, -13, -21, -15,  -9,  40,  55,  -3,
+     14,  19,  44, -17,  24,  32,  -5,   4, -21, -18,
+    }, {
+     76,   1, -41,  -9, -19, -12,  41,  17,  55,  18,
+     -3, -63,  -3, -12,  30,   5,  -3, -12, -31,   0,
+    -24,  49,  -8,   9,  -1, -33, -12, -29,  27, -18,
+     37,  21,  34, -17,  -3, -11,  14, -23,  25,  -2,
+    }, {
+      7,  22, -18,  29,   1, -25,  36,  21,  20,  -9,
+    -22, -56, -11,   6,  45,  21, -15, -16, -20,  -1,
+    -33,  34,  -2,  -6, -17, -23, -28,   6,  25, -12,
+     16,  37,  53,  -1, -11, -15,  -8, -25,  20, -11,
+    }, {
+     37,   8, -29, -22,  -4, -37,  36,   9,  34,  22,
+    -17, -24,   8, -18,  15,  -2,   1, -14, -31,  25,
+     15,  48,  13,  -4, -28, -31,  -5, -21,  57,  -4,
+     53,  24,  23, -55,   6,  12,  37,  -6,  11,  11,
+    }, {
+    -31,  28,  -6,  16,  16, -50,  31,  14,   0,  -6,
+    -36, -17,   0,   0,  29,  14, -11, -18, -20,  25,
+      6,  33,  19, -20, -43, -21, -21,  14,  55,   0,
+     32,  40,  42, -39,  -1,   8,  14,  -8,   6,   3,
+    }, {
+    119, -24, -39, -44, -51,  66, -14,  15,  31, -26,
+     -1,   0,   7,  16, -19, -28, -19,  22, -26,   4,
+    -13,  28, -16,  29,   5,  -1,  16, -16,   8, -35,
+    -10, -42,  -4,  17,  29, -19, -42,  -7,   0, -15,
+    }, {
+     50,  -3, -16,  -5, -30,  53, -19,  20,  -3, -55,
+    -19,   8,   0,  34,  -5, -11, -32,  18, -15,   4,
+    -22,  13, -10,  13,  -9,   8,   0,  19,   7, -29,
+    -31, -26,  13,  33,  21, -22, -65,  -9,  -4, -23,
+    }, {
+     79, -17, -27, -56, -36,  41, -19,   8,  10, -22,
+    -15,  39,  20,   9, -35, -35, -15,  20, -26,  31,
+     26,  27,   6,  15, -20,   0,  23,  -8,  38, -22,
+      5, -38, -15, -20,  39,   4, -18,   9, -13,  -1,
+    }, {
+     10,   3,  -4, -18, -15,  27, -24,  13, -24, -51,
+    -34,  47,  12,  28, -21, -19, -27,  16, -15,  30,
+     17,  12,  12,   0, -36,  10,   7,  27,  37, -16,
+    -15, -22,   3,  -4,  31,   1, -42,   7, -18,  -9,
+    }, {
+     74, -12, -30, -42, -30,  14, -16,  23,  29, -19,
+     20, -21,  -7,   1, -19, -17, -14, -10, -43, -27,
+      3,  48,  -8,  22, -16,  -7,   4, -42,   9, -31,
+      6, -20,  -6,  -4,   3, -43, -22, -20,  28,   5,
+    }, {
+      5,   7,  -7,  -4,  -9,   0, -21,  28,  -6, -48,
+      2, -14, -15,  20,  -5,   0, -27, -14, -32, -28,
+     -5,  32,  -2,   6, -32,   3, -12,  -5,   8, -25,
+    -14,  -4,  12,  11,  -4, -47, -45, -22,  22,  -2,
+    }, {
+     34,  -6, -18, -55, -15, -11, -21,  16,   8, -16,
+      6,  16,   5,  -4, -35, -24, -10, -12, -43,  -1,
+     43,  47,  14,   8, -43,  -5,  10, -34,  39, -18,
+     22, -16, -17, -42,  13, -19,   1,  -3,  14,  20,
+    }, {
+    -34,  14,   4, -17,   5, -24, -26,  20, -27, -45,
+    -12,  24,  -2,  13, -21,  -8, -22, -16, -32,  -2,
+     34,  31,  20,  -7, -58,   5,  -5,   2,  38, -12,
+      2,  -1,   1, -26,   5, -23, -21,  -6,   8,  11,
+    }, {
+    124, -13, -21, -23, -62,  23,   0,  43,  57,   8,
+    -13, -18,  14, -10,   6, -26,  -3,  49, -19,  19,
+    -31,  27,  -7,   0,  11, -20,  29,  -1,  12, -47,
+      4, -39,  11,  34,  28,  -9,  -5, -19, -13, -34,
+    }, {
+     55,   6,   1,  14, -41,  10,  -4,  48,  22, -20,
+    -31, -10,   5,   7,  20,  -9, -16,  45,  -8,  19,
+    -40,  12,  -1, -15,  -4, -10,  12,  34,  11, -41,
+    -16, -24,  30,  49,  20, -13, -28, -22, -18, -43,
+    }, {
+     84,  -6,  -9, -36, -47,  -1,  -4,  36,  36,  12,
+    -27,  20,  26, -17,  -9, -33,   1,  47, -19,  46,
+      9,  27,  15, -13, -15, -18,  35,   6,  42, -33,
+     20, -36,   1,  -4,  38,  14,  18,  -2, -27, -20,
+    }, {
+     15,  13,  13,   1, -26, -14,  -9,  41,   1, -16,
+    -46,  27,  18,   1,   4, -16, -11,  43,  -8,  45,
+      0,  11,  21, -29, -30,  -8,  19,  42,  41, -28,
+      0, -20,  20,  11,  30,  10,  -4,  -5, -32, -28,
+    }, {
+     79,  -2, -12, -22, -42, -28,  -1,  51,  54,  15,
+      8, -41,   0, -24,   6, -15,   1,  17, -36, -12,
+    -14,  47,   0,  -6, -11, -26,  16, -27,  13, -43,
+     22, -18,  10,  12,   2, -34,  15, -33,  13, -13,
+    }, {
+     10,  18,  10,  15, -21, -41,  -6,  56,  19, -13,
+     -9, -33,  -9,  -6,  20,   1, -11,  13, -24, -13,
+    -23,  32,   6, -22, -26, -15,   0,   8,  12, -37,
+      1,  -2,  28,  27,  -5, -37,  -7, -35,   8, -21,
+    }, {
+     39,   4,   0, -35, -27, -53,  -6,  44,  33,  18,
+     -5,  -2,  11, -31,  -9, -22,   6,  15, -36,  13,
+     25,  46,  23, -20, -37, -24,  23, -19,  43, -29,
+     38, -14,   0, -26,  12, -10,  38, -16,   0,   0,
+    }, {
+    -29,  25,  22,   2,  -6, -67, -11,  49,  -1, -10,
+    -24,   5,   3, -13,   4,  -5,  -6,  11, -25,  12,
+     16,  31,  28, -36, -53, -13,   6,  16,  42, -24,
+     17,   1,  18, -10,   4, -13,  15, -18,  -5,  -7,
+    }, {
+     29, -25, -22,  -2,   6,  67,  11, -49,   1,  10,
+     24,  -5,  -3,  13,  -4,   5,   6, -11,  25, -12,
+    -16, -31, -28,  36,  53,  13,  -6, -16, -42,  24,
+    -17,  -1, -18,  10,  -4,  13, -15,  18,   5,   7,
+    }, {
+    -39,  -4,   0,  35,  27,  53,   6, -44, -33, -18,
+      5,   2, -11,  31,   9,  22,  -6, -15,  36, -13,
+    -25, -46, -23,  20,  37,  24, -23,  19, -43,  29,
+    -38,  14,   0,  26, -12,  10, -38,  16,   0,   0,
+    }, {
+    -10, -18, -10, -15,  21,  41,   6, -56, -19,  13,
+      9,  33,   9,   6, -20,  -1,  11, -13,  24,  13,
+     23, -32,  -6,  22,  26,  15,   0,  -8, -12,  37,
+     -1,   2, -28, -27,   5,  37,   7,  35,  -8,  21,
+    }, {
+    -79,   2,  12,  22,  42,  28,   1, -51, -54, -15,
+     -8,  41,   0,  24,  -6,  15,  -1, -17,  36,  12,
+     14, -47,   0,   6,  11,  26, -16,  27, -13,  43,
+    -22,  18, -10, -12,  -2,  34, -15,  33, -13,  13,
+    }, {
+    -15, -13, -13,  -1,  26,  14,   9, -41,  -1,  16,
+     46, -27, -18,  -1,  -4,  16,  11, -43,   8, -45,
+      0, -11, -21,  29,  30,   8, -19, -42, -41,  28,
+      0,  20, -20, -11, -30, -10,   4,   5,  32,  28,
+    }, {
+    -84,   6,   9,  36,  47,   1,   4, -36, -36, -12,
+     27, -20, -26,  17,   9,  33,  -1, -47,  19, -46,
+     -9, -27, -15,  13,  15,  18, -35,  -6, -42,  33,
+    -20,  36,  -1,   4, -38, -14, -18,   2,  27,  20,
+    }, {
+    -55,  -6,  -1, -14,  41, -10,   4, -48, -22,  20,
+     31,  10,  -5,  -7, -20,   9,  16, -45,   8, -19,
+     40, -12,   1,  15,   4,  10, -12, -34, -11,  41,
+     16,  24, -30, -49, -20,  13,  28,  22,  18,  43,
+    }, {
+   -124,  13,  21,  23,  62, -23,   0, -43, -57,  -8,
+     13,  18, -14,  10,  -6,  26,   3, -49,  19, -19,
+     31, -27,   7,   0, -11,  20, -29,   1, -12,  47,
+     -4,  39, -11, -34, -28,   9,   5,  19,  13,  34,
+    }, {
+     34, -14,  -4,  17,  -5,  24,  26, -20,  27,  45,
+     12, -24,   2, -13,  21,   8,  22,  16,  32,   2,
+    -34, -31, -20,   7,  58,  -5,   5,  -2, -38,  12,
+     -2,   1,  -1,  26,  -5,  23,  21,   6,  -8, -11,
+    }, {
+    -34,   6,  18,  55,  15,  11,  21, -16,  -8,  16,
+     -6, -16,  -5,   4,  35,  24,  10,  12,  43,   1,
+    -43, -47, -14,  -8,  43,   5, -10,  34, -39,  18,
+    -22,  16,  17,  42, -13,  19,  -1,   3, -14, -20,
+    }, {
+     -5,  -7,   7,   4,   9,   0,  21, -28,   6,  48,
+     -2,  14,  15, -20,   5,   0,  27,  14,  32,  28,
+      5, -32,   2,  -6,  32,  -3,  12,   5,  -8,  25,
+     14,   4, -12, -11,   4,  47,  45,  22, -22,   2,
+    }, {
+    -74,  12,  30,  42,  30, -14,  16, -23, -29,  19,
+    -20,  21,   7,  -1,  19,  17,  14,  10,  43,  27,
+     -3, -48,   8, -22,  16,   7,  -4,  42,  -9,  31,
+     -6,  20,   6,   4,  -3,  43,  22,  20, -28,  -5,
+    }, {
+    -10,  -3,   4,  18,  15, -27,  24, -13,  24,  51,
+     34, -47, -12, -28,  21,  19,  27, -16,  15, -30,
+    -17, -12, -12,   0,  36, -10,  -7, -27, -37,  16,
+     15,  22,  -3,   4, -31,  -1,  42,  -7,  18,   9,
+    }, {
+    -79,  17,  27,  56,  36, -41,  19,  -8, -10,  22,
+     15, -39, -20,  -9,  35,  35,  15, -20,  26, -31,
+    -26, -27,  -6, -15,  20,   0, -23,   8, -38,  22,
+     -5,  38,  15,  20, -39,  -4,  18,  -9,  13,   1,
+    }, {
+    -50,   3,  16,   5,  30, -53,  19, -20,   3,  55,
+     19,  -8,   0, -34,   5,  11,  32, -18,  15,  -4,
+     22, -13,  10, -13,   9,  -8,   0, -19,  -7,  29,
+     31,  26, -13, -33, -21,  22,  65,   9,   4,  23,
+    }, {
+   -119,  24,  39,  44,  51, -66,  14, -15, -31,  26,
+      1,   0,  -7, -16,  19,  28,  19, -22,  26,  -4,
+     13, -28,  16, -29,  -5,   1, -16,  16,  -8,  35,
+     10,  42,   4, -17, -29,  19,  42,   7,   0,  15,
+    }, {
+     31, -28,   6, -16, -16,  50, -31, -14,   0,   6,
+     36,  17,   0,   0, -29, -14,  11,  18,  20, -25,
+     -6, -33, -19,  20,  43,  21,  21, -14, -55,   0,
+    -32, -40, -42,  39,   1,  -8, -14,   8,  -6,  -3,
+    }, {
+    -37,  -8,  29,  22,   4,  37, -36,  -9, -34, -22,
+     17,  24,  -8,  18, -15,   2,  -1,  14,  31, -25,
+    -15, -48, -13,   4,  28,  31,   5,  21, -57,   4,
+    -53, -24, -23,  55,  -6, -12, -37,   6, -11, -11,
+    }, {
+     -7, -22,  18, -29,  -1,  25, -36, -21, -20,   9,
+     22,  56,  11,  -6, -45, -21,  15,  16,  20,   1,
+     33, -34,   2,   6,  17,  23,  28,  -6, -25,  12,
+    -16, -37, -53,   1,  11,  15,   8,  25, -20,  11,
+    }, {
+    -76,  -1,  41,   9,  19,  12, -41, -17, -55, -18,
+      3,  63,   3,  12, -30,  -5,   3,  12,  31,   0,
+     24, -49,   8,  -9,   1,  33,  12,  29, -27,  18,
+    -37, -21, -34,  17,   3,  11, -14,  23, -25,   2,
+    }, {
+    -13, -17,  15, -15,   3,  -1, -33,  -7,  -1,  12,
+     58,  -5, -15, -13, -29,  -3,  16, -13,   4, -57,
+     10, -13, -11,  13,  21,  15,   9, -40, -55,   3,
+    -14, -19, -44,  17, -24, -32,   5,  -4,  21,  18,
+    }, {
+    -82,   3,  38,  23,  24, -15, -38,  -2, -37, -15,
+     39,   2, -23,   4, -15,  12,   3, -17,  15, -58,
+      1, -29,  -6,  -2,   5,  26,  -7,  -4, -56,   9,
+    -35,  -3, -25,  33, -32, -36, -17,  -7,  15,   9,
+    }, {
+    -52, -10,  27, -27,  18, -26, -38, -14, -23,  16,
+     44,  33,  -3, -20, -45, -10,  20, -15,   3, -31,
+     50, -14,  10,   0,  -5,  17,  15, -32, -24,  16,
+      1, -15, -55, -20, -14,  -8,  29,  12,   7,  32,
+    }, {
+   -121,   9,  50,  10,  40, -40, -43,  -9, -58, -12,
+     25,  41, -11,  -2, -31,   5,   8, -19,  15, -32,
+     41, -30,  16, -16, -20,  28,   0,   3, -26,  22,
+    -19,   0, -36,  -4, -22, -12,   6,   9,   1,  24,
+    }, {
+     36, -18,  24,   3, -28,   7, -16,  13,  26,  41,
+     24,  -1,   5, -26,  -3, -12,  27,  46,  27, -10,
+    -24, -34, -10,  -8,  49,   2,  34,   0, -51, -12,
+    -17, -38, -25,  56,   0,   0,  22,  -3, -20, -22,
+    }, {
+    -32,   2,  47,  42,  -7,  -5, -21,  18,  -9,  12,
+      5,   5,  -2,  -8,  10,   4,  14,  42,  38, -10,
+    -33, -49,  -5, -24,  33,  12,  17,  35, -52,  -6,
+    -38, -22,  -7,  72,  -7,  -3,   0,  -6, -25, -30,
+    }, {
+     -2, -11,  36,  -9, -13, -17, -21,   6,   5,  45,
+     10,  36,  18, -33, -19, -19,  31,  44,  27,  15,
+     16, -34,  11, -22,  22,   4,  40,   7, -21,   0,
+     -1, -35, -36,  18,  10,  24,  46,  12, -34,  -8,
+    }, {
+    -71,   9,  59,  29,   8, -30, -26,  11, -30,  16,
+     -8,  44,   9, -14,  -5,  -2,  19,  40,  38,  15,
+      7, -50,  17, -38,   7,  14,  24,  43, -22,   6,
+    -22, -19, -17,  34,   2,  20,  23,  10, -39, -16,
+    }, {
+     -8,  -6,  33,   4,  -7, -44, -18,  21,  23,  48,
+     46, -24,  -9, -40,  -3,  -1,  32,  13,  11, -43,
+     -7, -14,  -3, -15,  26,  -3,  21, -26, -50,  -8,
+      0, -16, -27,  34, -25, -23,  43, -17,   6,  -1,
+    }, {
+    -77,  13,  56,  43,  13, -57, -23,  26, -11,  19,
+     27, -16, -17, -22,  10,  15,  19,  10,  22, -43,
+    -16, -30,   2, -31,  11,   6,   5,   9, -52,  -2,
+    -20,   0,  -8,  50, -33, -27,  19, -19,   1,  -9,
+    }, {
+    -47,   0,  45,  -7,   7, -69, -23,  13,   2,  51,
+     32,  14,   3, -47, -19,  -8,  37,  11,  10, -16,
+     32, -15,  19, -29,   0,  -1,  28, -18, -20,   4,
+     16, -13, -38,  -3, -15,   0,  66,   0,  -7,  13,
+    }, {
+   -116,  20,  68,  30,  28, -83, -28,  18, -32,  22,
+     13,  21,  -5, -28,  -5,   7,  24,   8,  22, -17,
+     23, -30,  25, -45, -15,   9,  11,  18, -22,  10,
+     -4,   2, -19,  12, -23,  -3,  43,  -2, -12,   4,
+    }, {
+     72, -13, -29, -18,   4,  90,  37, -34,   4,  -1,
+     13,  -9,  -6,  11,   2,  24, -13,   3,  -7, -11,
+     -4,   4, -42,  25,  31,  -1,  -8, -29,  -6,  17,
+    -19,   2, -10,  -6,  38,  22, -42, -19,  -6, -11,
+    }, {
+      3,   7,  -6,  20,  25,  77,  32, -29, -31, -30,
+     -4,  -2, -14,  29,  16,  40, -26,   0,   3, -12,
+    -13, -10, -36,   9,  15,   8, -24,   6,  -7,  22,
+    -40,  17,   8,   9,  31,  18, -66, -22, -11, -19,
+    }, {
+     32,  -6, -17, -31,  19,  65,  33, -41, -16,   1,
+      0,  29,   6,   4, -13,  17,  -9,   1,  -8,  14,
+     35,   3, -19,  11,   4,   0,  -1, -21,  23,  30,
+     -3,   5, -20, -44,  48,  46, -19,  -3, -20,   3,
+    }, {
+    -36,  13,   5,   7,  40,  51,  28, -36, -52, -27,
+    -18,  36,  -2,  22,   0,  33, -21,  -2,   3,  13,
+     26, -11, -14,  -4, -10,  10, -18,  14,  22,  36,
+    -24,  21,  -1, -28,  40,  42, -42,  -5, -25,  -5,
+    }, {
+     27,  -1, -20, -17,  24,  38,  35, -26,   1,   4,
+     35, -32, -21,  -3,   2,  35,  -8, -29, -24, -44,
+     12,  24, -34,  18,   8,  -7, -21, -55,  -5,  21,
+     -2,  23, -11, -28,  13,  -1, -22, -33,  21,  10,
+    }, {
+    -41,  18,   2,  21,  45,  24,  30, -21, -33, -24,
+     17, -24, -29,  15,  16,  51, -21, -33, -13, -45,
+      3,   8, -28,   2,  -7,   2, -37, -19,  -7,  27,
+    -22,  39,   7, -12,   5,  -5, -45, -35,  15,   1,
+    }, {
+    -12,   4,  -8, -29,  39,  12,  30, -33, -19,   8,
+     21,   6,  -8,  -9, -13,  28,  -4, -31, -24, -18,
+     52,  23, -12,   4, -18,  -5, -14, -47,  24,  34,
+     14,  27, -22, -66,  22,  22,   1, -16,   6,  24,
+    }, {
+    -81,  25,  14,   8,  61,   0,  25, -28, -54, -20,
+      3,  14, -17,   8,   0,  44, -16, -35, -13, -18,
+     43,   7,  -6, -11, -33,   4, -30, -11,  22,  40,
+     -6,  43,  -3, -50,  14,  18, -22, -18,   1,  16,
+    }, {
+     77,  -2, -11,   1,  -7,  47,  52,  -5,  29,  33,
+      1, -28,   0, -15,  28,  26,   2,  30,   0,   2,
+    -22,   4, -33,  -3,  36, -21,   3, -15,  -2,   5,
+     -4,   4,   6,   9,  37,  31,  -5, -32, -20, -30,
+    }, {
+      8,  17,  10,  40,  13,  34,  47,   0,  -5,   4,
+    -16, -21,  -8,   2,  42,  43, -10,  26,  10,   2,
+    -31, -11, -27, -19,  21, -10, -12,  20,  -3,  11,
+    -25,  20,  25,  25,  29,  28, -28, -34, -25, -38,
+    }, {
+     37,   3,   0, -10,   7,  22,  48, -12,   8,  36,
+    -12,   9,  12, -22,  12,  19,   6,  28,   0,  29,
+     18,   3, -11, -17,  10, -18,  10,  -7,  27,  18,
+     11,   7,  -3, -28,  47,  55,  18, -15, -34, -16,
+    }, {
+    -31,  24,  23,  27,  29,   9,  43,  -8, -26,   7,
+    -30,  17,   4,  -3,  26,  35,  -5,  24,  10,  28,
+      9, -12,  -5, -33,  -5,  -8,  -5,  29,  26,  24,
+     -9,  23,  14, -12,  39,  52,  -5, -18, -39, -24,
+    }, {
+     32,   8,  -3,   2,  13,  -4,  50,   1,  27,  39,
+     23, -51, -15, -30,  27,  37,   7,  -1, -17, -29,
+     -5,  23, -25, -10,  14, -26,  -8, -41,  -1,   9,
+     13,  26,   5, -12,  12,   7,  14, -45,   6,  -9,
+    }, {
+    -36,  29,  19,  41,  34, -18,  45,   6,  -8,  10,
+      5, -43, -23, -11,  42,  53,  -5,  -5,  -6, -30,
+    -14,   8, -20, -26,  -1, -16, -25,  -4,  -3,  15,
+     -7,  41,  23,   3,   4,   3,  -8, -48,   1, -17,
+    }, {
+     -7,  15,   9,  -9,  28, -29,  45,  -5,   6,  43,
+      9, -12,  -2, -36,  12,  30,  11,  -3, -17,  -3,
+     34,  22,  -3, -24, -12, -24,  -2, -32,  28,  22,
+     29,  29,  -5, -50,  21,  31,  38, -29,  -7,   5,
+    }, {
+    -76,  35,  31,  28,  49, -43,  40,   0, -29,  14,
+     -8,  -5, -10, -18,  26,  46,   0,  -7,  -6,  -3,
+     25,   7,   2, -40, -28, -14, -18,   3,  27,  28,
+      8,  45,  13, -34,  13,  27,  15, -31, -12,  -3,
+    }, {
+     74, -17,   0, -31, -18,  73,  -5,   0,   3,  -5,
+     25,  12,  -3,  -1, -22,   3,  -9,  33, -12, -24,
+      6,   2, -33,   9,  21,   5,  20, -27, -19,  -7,
+    -34, -37, -34,  22,  44,   0, -41, -29, -17, -21,
+    }, {
+      5,   3,  21,   7,   2,  60, -10,   5, -32, -34,
+      7,  20, -11,  16,  -8,  20, -21,  29,  -1, -24,
+     -2, -13, -27,  -6,   5,  15,   3,   8, -21,  -1,
+    -55, -21, -15,  38,  37,  -3, -65, -32, -23, -30,
+    }, {
+     35, -10,  11, -44,  -3,  48, -10,  -6, -17,  -2,
+     11,  51,   8,  -8, -38,  -3,  -4,  31, -12,   2,
+     46,   1, -10,  -4,  -5,   7,  26, -19,  10,   5,
+    -18, -34, -45, -15,  54,  24, -18, -13, -31,  -7,
+    }, {
+    -33,  10,  34,  -5,  17,  35, -15,  -1, -53, -30,
+     -6,  59,   0,  10, -24,  13, -17,  27,  -1,   1,
+     37, -13,  -4, -20, -20,  18,  10,  16,   8,  11,
+    -39, -18, -26,   0,  46,  20, -41, -15, -37, -15,
+    }, {
+     29,  -5,   7, -30,   1,  21,  -7,   7,   0,   0,
+     47,  -9, -18, -15, -22,  14,  -4,   0, -28, -57,
+     23,  21, -25,   2,  -1,   0,   7, -53, -19,  -3,
+    -17, -15, -36,   0,  19, -24, -21, -43,   9,   0,
+    }, {
+    -39,  14,  30,   8,  22,   8, -12,  12, -34, -27,
+     29,  -2, -26,   2,  -8,  31, -16,  -3, -17, -57,
+     14,   6, -19, -13, -16,  10,  -8, -17, -20,   2,
+    -38,   0, -17,  16,  11, -27, -44, -45,   4,  -8,
+    }, {
+     -9,   1,  20, -43,  17,  -3, -12,   0, -20,   4,
+     33,  29,  -6, -22, -38,   7,   0,  -1, -29, -30,
+     63,  21,  -3, -11, -27,   1,  14, -45,  10,   9,
+     -1, -12, -47, -37,  28,   0,   2, -26,  -4,  13,
+    }, {
+    -78,  21,  43,  -4,  38, -17, -17,   5, -55, -24,
+     15,  36, -14,  -4, -24,  24, -12,  -5, -17, -31,
+     54,   5,   2, -27, -43,  12,  -2,  -9,   9,  15,
+    -22,   3, -28, -21,  20,  -3, -20, -28,  -9,   5,
+    }, {
+     80,  -6,  16, -11, -30,  30,   9,  28,  28,  29,
+     13,  -6,   2, -28,   3,   5,   7,  60,  -5,  -9,
+    -11,   1, -24, -19,  27, -13,  32, -13, -15, -19,
+    -19, -35, -17,  39,  43,   9,  -4, -42, -32, -41,
+    }, {
+     11,  14,  39,  27,  -9,  17,   4,  33,  -6,   0,
+     -4,   1,  -5, -10,  17,  22,  -5,  57,   5,  -9,
+    -20, -13, -18, -35,  11,  -3,  16,  22, -17, -13,
+    -40, -19,   1,  55,  35,   5, -27, -44, -37, -49,
+    }, {
+     40,   0,  28, -24, -14,   5,   4,  21,   7,  33,
+      0,  32,  15, -35, -12,  -1,  11,  58,  -5,  16,
+     28,   0,  -1, -33,   0, -11,  39,  -5,  14,  -6,
+     -3, -31, -28,   1,  53,  33,  19, -25, -46, -26,
+    }, {
+    -28,  20,  51,  14,   6,  -7,   0,  26, -27,   4,
+    -18,  40,   6, -16,   1,  15,   0,  55,   5,  16,
+     19, -14,   3, -49, -14,  -1,  22,  30,  12,   0,
+    -24, -15,  -9,  17,  45,  29,  -4, -28, -51, -35,
+    }, {
+     34,   4,  25, -10,  -9, -21,   7,  36,  26,  36,
+     35, -28, -12, -42,   3,  16,  12,  28, -21, -42,
+      5,  21, -16, -26,   4, -19,  19, -39, -15, -15,
+     -1, -13, -19,  17,  17, -14,  15, -55,  -4, -19,
+    }, {
+    -34,  25,  48,  28,  11, -34,   2,  41,  -9,   7,
+     17, -21, -20, -24,  17,  33,   0,  24, -10, -42,
+     -3,   5, -10, -42, -11,  -8,   3,  -3, -16,  -9,
+    -22,   2,   0,  33,  10, -18,  -7, -58, -10, -28,
+    }, {
+     -4,  11,  37, -23,   5, -46,   2,  29,   5,  39,
+     21,   9,   0, -49, -12,   9,  16,  26, -22, -15,
+     45,  20,   5, -40, -22, -17,  26, -31,  14,  -2,
+     14, -10, -30, -20,  27,   9,  39, -39, -18,  -5,
+    }, {
+    -73,  32,  60,  15,  26, -59,  -2,  33, -30,  10,
+      3,  17,  -8, -30,   1,  26,   4,  22, -10, -16,
+     36,   5,  11, -56, -37,  -6,  10,   5,  13,   3,
+     -6,   5, -11,  -4,  19,   5,  16, -41, -24, -13
+    }
+};
 
-    avctx->sample_fmt = SAMPLE_FMT_S16;
-    return 0;
-}
+const uint16_t ff_cb1_base[128]={
+    19657, 18474, 18365, 17520, 21048, 18231, 18584, 16671,
+    20363, 19069, 19409, 18430, 21844, 18753, 19613, 17411,
+    20389, 21772, 20129, 21702, 20978, 20472, 19627, 19387,
+    21477, 23134, 21841, 23919, 22089, 21519, 21134, 20852,
+    19675, 17821, 19044, 17477, 19986, 16955, 18446, 16086,
+    21138, 18899, 20952, 18929, 21452, 17833, 20104, 17159,
+    19770, 20056, 20336, 20866, 19329, 18217, 18908, 18004,
+    21556, 21948, 23079, 23889, 20922, 19544, 20984, 19781,
+    19781, 20984, 19544, 20922, 23889, 23079, 21948, 21556,
+    18004, 18908, 18217, 19329, 20866, 20336, 20056, 19770,
+    17159, 20104, 17833, 21452, 18929, 20952, 18899, 21138,
+    16086, 18446, 16955, 19986, 17477, 19044, 17821, 19675,
+    20852, 21134, 21519, 22089, 23919, 21841, 23134, 21477,
+    19387, 19627, 20472, 20978, 21702, 20129, 21772, 20389,
+    17411, 19613, 18753, 21844, 18430, 19409, 19069, 20363,
+    16671, 18584, 18231, 21048, 17520, 18365, 18474, 19657,
+};
 
-/**
- * Evaluate sqrt(x << 24). x must fit in 20 bits. This value is evaluated in an
- * odd way to make the output identical to the binary decoder.
- */
-static int t_sqrt(unsigned int x)
-{
-    int s = 2;
-    while (x > 0xfff) {
-        s++;
-        x >>= 2;
-    }
+const uint16_t ff_cb2_base[128]={
+    12174, 13380, 13879, 13832, 13170, 13227, 13204, 12053,
+    12410, 13988, 14348, 14631, 13100, 13415, 13224, 12268,
+    11982, 13825, 13499, 14210, 13877, 14788, 13811, 13109,
+    11449, 13275, 12833, 13717, 12728, 13696, 12759, 12405,
+    10230, 12185, 11628, 13161, 11762, 13458, 12312, 12818,
+    10443, 12773, 12011, 14020, 11818, 13825, 12453, 13226,
+    10446, 13162, 11881, 14300, 12859, 16288, 13490, 15053,
+    10155, 12820, 11519, 13973, 12041, 15081, 12635, 14198,
+    14198, 12635, 15081, 12041, 13973, 11519, 12820, 10155,
+    15053, 13490, 16288, 12859, 14300, 11881, 13162, 10446,
+    13226, 12453, 13825, 11818, 14020, 12011, 12773, 10443,
+    12818, 12312, 13458, 11762, 13161, 11628, 12185, 10230,
+    12405, 12759, 13696, 12728, 13717, 12833, 13275, 11449,
+    13109, 13811, 14788, 13877, 14210, 13499, 13825, 11982,
+    12268, 13224, 13415, 13100, 14631, 14348, 13988, 12410,
+    12053, 13204, 13227, 13170, 13832, 13879, 13380, 12174,
+};
 
-    return ff_sqrt(x << 20) << s;
-}
+const int16_t ff_energy_tab[32]={
+        0,    16,    20,    25,    32,    41,    51,    65,
+       81,   103,   129,   163,   205,   259,   326,   410,
+      516,   650,   819,  1031,  1298,  1634,  2057,  2590,
+     3261,  4105,  5168,  6507,  8192, 10313, 12983, 16345
+};
 
-/**
- * Evaluate the LPC filter coefficients from the reflection coefficients.
- * Does the inverse of the eval_refl() function.
- */
-static void eval_coefs(int *coefs, const int *refl)
-{
-    int buffer[10];
-    int *b1 = buffer;
-    int *b2 = coefs;
-    int i, j;
+static const int16_t lpc_refl_cb1[64]={
+    -4041, -4018, -3998, -3977, -3954, -3930, -3906, -3879,
+    -3852, -3825, -3795, -3764, -3731, -3699, -3666, -3631,
+    -3594, -3555, -3513, -3468, -3420, -3372, -3321, -3268,
+    -3212, -3153, -3090, -3021, -2944, -2863, -2772, -2676,
+    -2565, -2445, -2328, -2202, -2072, -1941, -1808, -1660,
+    -1508, -1348, -1185,  -994,  -798,  -600,  -374,  -110,
+      152,   447,   720,   982,  1229,  1456,  1682,  1916,
+     2130,  2353,  2595,  2853,  3118,  3363,  3588,  3814
+};
 
-    for (i=0; i < 10; i++) {
-        b1[i] = refl[i] << 4;
+static const int16_t lpc_refl_cb2[32]={
+    -3091, -2386, -1871, -1425, -1021,  -649,  -316,   -20,
+      267,   544,   810,  1065,  1305,  1534,  1756,  1970,
+     2171,  2359,  2536,  2700,  2854,  2996,  3133,  3263,
+     3386,  3499,  3603,  3701,  3789,  3870,  3947,  4020
+};
 
-        for (j=0; j < i; j++)
-            b1[j] = ((refl[i] * b2[i-j-1]) >> 12) + b2[j];
+static const int16_t lpc_refl_cb3[32]={
+    -3525, -3295, -3081, -2890, -2696, -2511, -2328, -2149,
+    -1979, -1817, -1658, -1498, -1341, -1188, -1032,  -876,
+     -721,  -561,  -394,  -228,   -54,   119,   296,   484,
+      683,   895,  1123,  1373,  1651,  1965,  2360,  2854
+};
 
-        FFSWAP(int *, b1, b2);
-    }
+static const int16_t lpc_refl_cb4[16]={
+    -1845, -1057,  -522,   -77,   301,   647,   975,  1285,
+     1582,  1873,  2163,  2452,  2735,  3017,  3299,  3569
+};
 
-    for (i=0; i < 10; i++)
-        coefs[i] >>= 4;
-}
+static const int16_t lpc_refl_cb5[16]={
+    -2691, -2187, -1788, -1435, -1118,  -837,  -571,  -316,
+      -59,   201,   470,   759,  1077,  1457,  1908,  2495
+};
 
-/**
- * Copy the last offset values of *source to *target. If those values are not
- * enough to fill the target buffer, fill it with another copy of those values.
- */
-static void copy_and_dup(int16_t *target, const int16_t *source, int offset)
-{
-    source += BUFFERSIZE - offset;
+static const int16_t lpc_refl_cb6[8]={
+    -1372,  -474,   133,   632,  1100,  1571,  2075,  2672
+};
 
-    memcpy(target, source, FFMIN(BLOCKSIZE, offset)*sizeof(*target));
-    if (offset < BLOCKSIZE)
-        memcpy(target + offset, source, (BLOCKSIZE - offset)*sizeof(*target));
-}
+static const int16_t lpc_refl_cb7[8]={
+    -2389, -1787, -1231,  -717,  -239,   234,   770,  1474
+};
 
-/** inverse root mean square */
-static int irms(const int16_t *data)
-{
-    unsigned int i, sum = 0;
+static const int16_t lpc_refl_cb8[8]={
+    -1569,  -864,  -296,   200,   670,  1151,  1709,  2385
+};
 
-    for (i=0; i < BLOCKSIZE; i++)
-        sum += data[i] * data[i];
+static const int16_t lpc_refl_cb9[8]={
+    -2200, -1608, -1062,  -569,  -120,   338,   863,  1621
+};
 
-    if (sum == 0)
-        return 0; /* OOPS - division by zero */
+static const int16_t lpc_refl_cb10[4]={
+     -617,   190,   802,  1483
+};
 
-    return 0x20000000 / (t_sqrt(sum) >> 8);
-}
+const int16_t * const ff_lpc_refl_cb[10]={
+    lpc_refl_cb1, lpc_refl_cb2, lpc_refl_cb3, lpc_refl_cb4, lpc_refl_cb5,
+    lpc_refl_cb6, lpc_refl_cb7, lpc_refl_cb8, lpc_refl_cb9, lpc_refl_cb10
+};
 
-static void add_wav(int16_t *dest, int n, int skip_first, int *m,
-                    const int16_t *s1, const int8_t *s2, const int8_t *s3)
+static void ff_add_wav(int16_t *dest, int n, int skip_first, int *m, const int16_t *s1,
+                       const int8_t *s2, const int8_t *s3)
 {
     int i;
     int v[3];
 
     v[0] = 0;
     for (i=!skip_first; i<3; i++)
-        v[i] = (gain_val_tab[n][i] * m[i]) >> gain_exp_tab[n];
+        v[i] = (ff_gain_val_tab[n][i] * m[i]) >> ff_gain_exp_tab[n];
 
     if (v[0]) {
         for (i=0; i < BLOCKSIZE; i++)
@@ -152,86 +1522,26 @@ static void add_wav(int16_t *dest, int n, int skip_first, int *m,
     }
 }
 
-static unsigned int rescale_rms(unsigned int rms, unsigned int energy)
-{
-    return (rms * energy) >> 10;
-}
-
-static unsigned int rms(const int *data)
-{
-    int i;
-    unsigned int res = 0x10000;
-    int b = 10;
-
-    for (i=0; i < 10; i++) {
-        res = (((0x1000000 - data[i]*data[i]) >> 12) * res) >> 12;
-
-        if (res == 0)
-            return 0;
-
-        while (res <= 0x3fff) {
-            b++;
-            res <<= 2;
-        }
-    }
-
-    return t_sqrt(res) >> b;
-}
-
-static void do_output_subblock(RA144Context *ractx, const uint16_t  *lpc_coefs,
-                               int gval, GetBitContext *gb)
-{
-    uint16_t buffer_a[40];
-    uint16_t *block;
-    int cba_idx = get_bits(gb, 7); // index of the adaptive CB, 0 if none
-    int gain    = get_bits(gb, 8);
-    int cb1_idx = get_bits(gb, 7);
-    int cb2_idx = get_bits(gb, 7);
-    int m[3];
-
-    if (cba_idx) {
-        cba_idx += BLOCKSIZE/2 - 1;
-        copy_and_dup(buffer_a, ractx->adapt_cb, cba_idx);
-        m[0] = (irms(buffer_a) * gval) >> 12;
-    } else {
-        m[0] = 0;
-    }
-
-    m[1] = (cb1_base[cb1_idx] * gval) >> 8;
-    m[2] = (cb2_base[cb2_idx] * gval) >> 8;
-
-    memmove(ractx->adapt_cb, ractx->adapt_cb + BLOCKSIZE,
-            (BUFFERSIZE - BLOCKSIZE) * sizeof(*ractx->adapt_cb));
-
-    block = ractx->adapt_cb + BUFFERSIZE - BLOCKSIZE;
-
-    add_wav(block, gain, cba_idx, m, cba_idx? buffer_a: NULL,
-            cb1_vects[cb1_idx], cb2_vects[cb2_idx]);
-
-    memcpy(ractx->curr_sblock, ractx->curr_sblock + 40,
-           10*sizeof(*ractx->curr_sblock));
-
-    if (ff_celp_lp_synthesis_filter(ractx->curr_sblock + 10, lpc_coefs,
-                                    block, BLOCKSIZE, 10, 1, 0xfff))
-        memset(ractx->curr_sblock, 0, 50*sizeof(*ractx->curr_sblock));
-}
-
-static void int_to_int16(int16_t *out, const int *inp)
+/**
+ * Copy the last offset values of *source to *target. If those values are not
+ * enough to fill the target buffer, fill it with another copy of those values.
+ */
+void ff_copy_and_dup(int16_t *target, const int16_t *source, int offset)
 {
-    int i;
+    source += BUFFERSIZE - offset;
 
-    for (i=0; i < 10; i++)
-        *out++ = *inp++;
+    memcpy(target, source, FFMIN(BLOCKSIZE, offset)*sizeof(*target));
+    if (offset < BLOCKSIZE)
+        memcpy(target + offset, source, (BLOCKSIZE - offset)*sizeof(*target));
 }
 
 /**
  * Evaluate the reflection coefficients from the filter coefficients.
- * Does the inverse of the eval_coefs() function.
  *
  * @return 1 if one of the reflection coefficients is greater than
  *         4095, 0 if not.
  */
-static int eval_refl(int *refl, const int16_t *coefs, AVCodecContext *avctx)
+int ff_eval_refl(int *refl, const int16_t *coefs, AVCodecContext *avctx)
 {
     int b, i, j;
     int buffer1[10];
@@ -268,8 +1578,75 @@ static int eval_refl(int *refl, const int16_t *coefs, AVCodecContext *avctx)
     return 0;
 }
 
-static int interp(RA144Context *ractx, int16_t *out, int a,
-                  int copyold, int energy)
+/**
+ * Evaluate the LPC filter coefficients from the reflection coefficients.
+ * Does the inverse of the ff_eval_refl() function.
+ */
+void ff_eval_coefs(int *coefs, const int *refl)
+{
+    int buffer[10];
+    int *b1 = buffer;
+    int *b2 = coefs;
+    int i, j;
+
+    for (i=0; i < 10; i++) {
+        b1[i] = refl[i] << 4;
+
+        for (j=0; j < i; j++)
+            b1[j] = ((refl[i] * b2[i-j-1]) >> 12) + b2[j];
+
+        FFSWAP(int *, b1, b2);
+    }
+
+    for (i=0; i < 10; i++)
+        coefs[i] >>= 4;
+}
+
+void ff_int_to_int16(int16_t *out, const int *inp)
+{
+    int i;
+
+    for (i=0; i < 10; i++)
+        *out++ = *inp++;
+}
+
+/**
+ * Evaluate sqrt(x << 24). x must fit in 20 bits. This value is evaluated in an
+ * odd way to make the output identical to the binary decoder.
+ */
+int ff_t_sqrt(unsigned int x)
+{
+    int s = 2;
+    while (x > 0xfff) {
+        s++;
+        x >>= 2;
+    }
+
+    return ff_sqrt(x << 20) << s;
+}
+
+unsigned int ff_rms(const int *data)
+{
+    int i;
+    unsigned int res = 0x10000;
+    int b = 10;
+
+    for (i=0; i < 10; i++) {
+        res = (((0x1000000 - data[i]*data[i]) >> 12) * res) >> 12;
+
+        if (res == 0)
+            return 0;
+
+        while (res <= 0x3fff) {
+            b++;
+            res <<= 2;
+        }
+    }
+
+    return ff_t_sqrt(res) >> b;
+}
+
+int ff_interp(RA144Context *ractx, int16_t *out, int a, int copyold, int energy)
 {
     int work[10];
     int b = NBLOCKS - a;
@@ -280,85 +1657,64 @@ static int interp(RA144Context *ractx, int16_t *out, int a,
     for (i=0; i<10; i++)
         out[i] = (a * ractx->lpc_coef[0][i] + b * ractx->lpc_coef[1][i])>> 2;
 
-    if (eval_refl(work, out, ractx->avctx)) {
+    if (ff_eval_refl(work, out, ractx->avctx)) {
         // The interpolated coefficients are unstable, copy either new or old
         // coefficients.
-        int_to_int16(out, ractx->lpc_coef[copyold]);
-        return rescale_rms(ractx->lpc_refl_rms[copyold], energy);
+        ff_int_to_int16(out, ractx->lpc_coef[copyold]);
+        return ff_rescale_rms(ractx->lpc_refl_rms[copyold], energy);
     } else {
-        return rescale_rms(rms(work), energy);
+        return ff_rescale_rms(ff_rms(work), energy);
     }
 }
 
-/** Uncompress one block (20 bytes -> 160*2 bytes). */
-static int ra144_decode_frame(AVCodecContext * avctx, void *vdata,
-                              int *data_size, AVPacket *avpkt)
+unsigned int ff_rescale_rms(unsigned int rms, unsigned int energy)
 {
-    const uint8_t *buf = avpkt->data;
-    int buf_size = avpkt->size;
-    static const uint8_t sizes[10] = {6, 5, 5, 4, 4, 3, 3, 3, 3, 2};
-    unsigned int refl_rms[4];    // RMS of the reflection coefficients
-    uint16_t block_coefs[4][10]; // LPC coefficients of each sub-block
-    unsigned int lpc_refl[10];   // LPC reflection coefficients of the frame
-    int i, j;
-    int16_t *data = vdata;
-    unsigned int energy;
-
-    RA144Context *ractx = avctx->priv_data;
-    GetBitContext gb;
-
-    if (*data_size < 2*160)
-        return -1;
-
-    if(buf_size < 20) {
-        av_log(avctx, AV_LOG_ERROR,
-               "Frame too small (%d bytes). Truncated file?\n", buf_size);
-        *data_size = 0;
-        return buf_size;
-    }
-    init_get_bits(&gb, buf, 20 * 8);
-
-    for (i=0; i<10; i++)
-        lpc_refl[i] = lpc_refl_cb[i][get_bits(&gb, sizes[i])];
+    return (rms * energy) >> 10;
+}
 
-    eval_coefs(ractx->lpc_coef[0], lpc_refl);
-    ractx->lpc_refl_rms[0] = rms(lpc_refl);
+/** inverse root mean square */
+int ff_irms(const int16_t *data)
+{
+    unsigned int i, sum = 0;
 
-    energy = energy_tab[get_bits(&gb, 5)];
+    for (i=0; i < BLOCKSIZE; i++)
+        sum += data[i] * data[i];
 
-    refl_rms[0] = interp(ractx, block_coefs[0], 1, 1, ractx->old_energy);
-    refl_rms[1] = interp(ractx, block_coefs[1], 2, energy <= ractx->old_energy,
-                    t_sqrt(energy*ractx->old_energy) >> 12);
-    refl_rms[2] = interp(ractx, block_coefs[2], 3, 0, energy);
-    refl_rms[3] = rescale_rms(ractx->lpc_refl_rms[0], energy);
+    if (sum == 0)
+        return 0; /* OOPS - division by zero */
 
-    int_to_int16(block_coefs[3], ractx->lpc_coef[0]);
+    return 0x20000000 / (ff_t_sqrt(sum) >> 8);
+}
 
-    for (i=0; i < 4; i++) {
-        do_output_subblock(ractx, block_coefs[i], refl_rms[i], &gb);
+void ff_subblock_synthesis(RA144Context *ractx, const uint16_t *lpc_coefs,
+                           int cba_idx, int cb1_idx, int cb2_idx,
+                           int gval, int gain)
+{
+    uint16_t buffer_a[40];
+    uint16_t *block;
+    int m[3];
 
-        for (j=0; j < BLOCKSIZE; j++)
-            *data++ = av_clip_int16(ractx->curr_sblock[j + 10] << 2);
+    if (cba_idx) {
+        cba_idx += BLOCKSIZE/2 - 1;
+        ff_copy_and_dup(buffer_a, ractx->adapt_cb, cba_idx);
+        m[0] = (ff_irms(buffer_a) * gval) >> 12;
+    } else {
+        m[0] = 0;
     }
+    m[1] = (ff_cb1_base[cb1_idx] * gval) >> 8;
+    m[2] = (ff_cb2_base[cb2_idx] * gval) >> 8;
+    memmove(ractx->adapt_cb, ractx->adapt_cb + BLOCKSIZE,
+            (BUFFERSIZE - BLOCKSIZE) * sizeof(*ractx->adapt_cb));
 
-    ractx->old_energy = energy;
-    ractx->lpc_refl_rms[1] = ractx->lpc_refl_rms[0];
+    block = ractx->adapt_cb + BUFFERSIZE - BLOCKSIZE;
 
-    FFSWAP(unsigned int *, ractx->lpc_coef[0], ractx->lpc_coef[1]);
+    ff_add_wav(block, gain, cba_idx, m, cba_idx? buffer_a: NULL,
+               ff_cb1_vects[cb1_idx], ff_cb2_vects[cb2_idx]);
 
-    *data_size = 2*160;
-    return 20;
-}
+    memcpy(ractx->curr_sblock, ractx->curr_sblock + 40,
+           10*sizeof(*ractx->curr_sblock));
 
-AVCodec ra_144_decoder =
-{
-    "real_144",
-    AVMEDIA_TYPE_AUDIO,
-    CODEC_ID_RA_144,
-    sizeof(RA144Context),
-    ra144_decode_init,
-    NULL,
-    NULL,
-    ra144_decode_frame,
-    .long_name = NULL_IF_CONFIG_SMALL("RealAudio 1.0 (14.4K)"),
-};
+    if (ff_celp_lp_synthesis_filter(ractx->curr_sblock + 10, lpc_coefs,
+                                    block, BLOCKSIZE, 10, 1, 0xfff))
+        memset(ractx->curr_sblock, 0, 50*sizeof(*ractx->curr_sblock));
+}
diff --git a/libavcodec/ra144.h b/libavcodec/ra144.h
index 4413530..dcdfbb8 100644
--- a/libavcodec/ra144.h
+++ b/libavcodec/ra144.h
@@ -2,20 +2,20 @@
  * Real Audio 1.0 (14.4K)
  * Copyright (c) 2003 the ffmpeg project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -23,1484 +23,60 @@
 #define AVCODEC_RA144_H
 
 #include <stdint.h>
-
-static const int16_t gain_val_tab[256][3] = {
-    { 541, 956,  768}, { 877, 581,  568}, { 675,1574,  635}, {1248,1464,  668},
-    {1246, 839, 1394}, {2560,1386,  991}, { 925, 687,  608}, {2208, 797, 1144},
-    { 535, 832,  799}, { 762, 605, 1154}, { 832,1122, 1003}, {1180, 687, 1176},
-    {1292, 901,  732}, {1656, 689,  896}, {1750,1248,  848}, {2284, 942, 1022},
-    { 824,1472,  643}, { 517, 765,  512}, { 562,1816, 1522}, { 694,1826, 2700},
-    { 704, 524,  672}, {1442, 757, 2232}, { 884, 551, 1266}, {2232,1007, 1692},
-    { 932, 746,  777}, {1132, 822,  926}, {1226, 771,  611}, {2948,1342, 1008},
-    {1302, 594, 1158}, {1602, 636, 1128}, {3408, 910, 1438}, {1996, 614,  575},
-    { 665, 935,  628}, { 631,1192,  829}, { 644, 926, 1052}, { 879, 988, 1226},
-    { 941,2768, 2772}, { 565,1344, 2304}, { 547, 628,  740}, { 639, 532, 1074},
-    { 955,1208,  598}, {1124,1160,  900}, {1206, 899, 1242}, { 746, 533,  624},
-    {1458,1028,  735}, {1706,1102,  692}, {1898,1018, 1004}, {2176, 988,  735},
-    {1578, 782, 1642}, { 897, 516,  754}, {2068, 702, 1656}, {2344, 818, 1526},
-    { 907, 652,  592}, {1056, 652,  642}, {2124,1416,  780}, {2664,1250,  727},
-    {1894, 727, 1108}, {2196, 657,  981}, {4840, 920, 1704}, {4992,1238,  983},
-    {2420, 909, 1094}, {2760, 935, 1032}, {2800, 612,  853}, {3068, 832,  574},
-    { 523,1796,  923}, { 722,1916, 1382}, {1226,1542,  928}, { 758, 757,  584},
-    { 512,1134,  577}, { 615,1276,  698}, { 574,2568, 2356}, { 993,2728, 3512},
-    { 539, 890,  913}, { 694, 928, 1088}, { 805, 600, 1360}, {2160, 951, 3128},
-    { 816, 950,  590}, { 955, 847,  811}, {1094, 883,  556}, {1304, 888,  604},
-    { 863,1170,  855}, {1023, 997, 1032}, { 932,1228, 1280}, { 627, 564,  573},
-    { 876, 900, 1448}, {1030, 857, 1792}, {1294, 953, 1758}, {1612, 854, 1714},
-    {1090,1166,  631}, {1314,1202,  751}, {1480, 905,  795}, {1682,1016,  568},
-    {1494,1178,  983}, { 878, 613,  526}, {1728,1446,  779}, {2136,1348,  774},
-    { 950, 649,  939}, {1180, 703,  899}, {1236, 527, 1158}, {1450, 647,  972},
-    {1282, 647,  707}, {1460, 663,  644}, {1614, 572,  578}, {3516,1222,  821},
-    {2668, 729, 1682}, {3128, 585, 1502}, {3208, 733,  976}, {6800, 871, 1416},
-    {3480, 743, 1408}, {3764, 899, 1170}, {3772, 632,  875}, {4092, 732,  638},
-    {3112, 753, 2620}, {3372, 945, 1890}, {3768, 969, 2288}, {2016, 559,  854},
-    {1736, 729,  787}, {1940, 686,  547}, {2140, 635,  674}, {4480,1272,  828},
-    {3976, 592, 1666}, {4384, 621, 1388}, {4400, 801,  955}, {4656, 522,  646},
-    {4848, 625, 1636}, {4984, 591,  874}, {5352, 535, 1001}, {11216,938, 1184},
-    { 925,3280, 1476}, { 735,1580, 1088}, {1150,1576,  674}, { 655, 783,  528},
-    { 527,2052, 1354}, { 782,1704, 1880}, { 578, 910, 1026}, { 692, 882, 1468},
-    { 586, 683,  715}, { 739, 609,  717}, { 778, 773,  697}, { 922, 785,  813},
-    { 766, 651,  984}, { 978, 596, 1030}, {1070, 757, 1080}, {1324, 687, 1178},
-    {1108,2144,  979}, { 723, 982,  690}, { 936, 956,  527}, {1180,1002,  547},
-    { 517,1306,  825}, { 832,1184,  974}, {1024, 957,  903}, {1262,1090,  906},
-    {1028, 720,  649}, {1192, 679,  694}, {2468,1480,  979}, {2844,1370,  877},
-    {1310, 835,  848}, {1508, 839,  698}, {1742,1030,  769}, {1910, 852,  573},
-    {1280, 859, 1174}, {1584, 863, 1108}, {1686, 708, 1364}, {1942, 768, 1104},
-    { 891, 536,  690}, {1016, 560,  663}, {2172, 870, 1348}, {2404, 999, 1170},
-    {1890, 966,  889}, {2116, 912,  777}, {2296,1020,  714}, {4872,1844,  932},
-    {2392, 778,  929}, {2604, 772,  744}, {2764, 957,  722}, {5832,1532,  984},
-    {2188, 519, 1264}, {2332, 532,  922}, {5064, 995, 2412}, {2708, 571,  874},
-    {2408, 545,  666}, {5016,1084,  875}, {5376, 983, 1196}, {5536, 979,  730},
-    {5344, 634, 1744}, {5688, 706, 1348}, {5912, 977, 1190}, {6072, 905,  763},
-    {6048, 582, 1526}, {11968,1013,1816}, {12864,937, 1900}, {12560,1086, 998},
-    {1998, 684, 1884}, {2504, 633, 1992}, {1252, 567,  835}, {1478, 571,  973},
-    {2620, 769, 1414}, {2808, 952, 1142}, {2908, 712, 1028}, {2976, 686,  741},
-    {1462, 552,  714}, {3296, 991, 1452}, {1590, 615,  544}, {3480,1150,  824},
-    {3212, 832,  923}, {3276, 839,  531}, {3548, 786,  852}, {3732, 764,  570},
-    {5728, 906, 2616}, {6272, 804, 2252}, {3096, 535,  876}, {3228, 598,  649},
-    {6536, 759, 1436}, {6648, 993,  846}, {6864, 567, 1210},{14016,1012, 1302},
-    {3408, 548, 1098}, {7160,1008, 1742}, {7136,1000, 1182}, {7480,1032,  836},
-    {7448, 612, 1552}, {7744, 614,  816}, {8384, 777, 1438}, {8784, 694,  786},
-    { 882,1508, 1068}, { 597, 837,  766}, {1270, 954, 1408}, { 803, 550,  798},
-    {1398,1308,  798}, {1848,1534,  738}, { 970, 675,  608}, {1264, 706,  684},
-    {1716, 767, 1126}, {2108, 765, 1404}, {2236, 924, 1003}, {2472,1048,  611},
-    { 999, 942,  963}, {1094, 857,  935}, {2936, 926, 1138}, {1934, 746,  551},
-    {3336, 633, 1762}, {3764, 701, 1454}, {1890, 564,  636}, {4096,1126,  793},
-    {3936, 556, 1140}, {3936, 540,  740}, {4216, 764,  874}, {8480,1328, 1014},
-    {2184, 515, 1042}, {4432, 934, 1344}, {4784, 945, 1112}, {5016,1062,  733},
-    {9216,1020, 2028}, {9968, 924, 1188}, {5424, 909, 1206}, {6512, 744, 1086}
-};
-
-static const uint8_t gain_exp_tab[256] = {
-   15, 15, 15, 15, 15, 16, 14, 15, 14, 14, 14, 14, 14, 14, 14, 14,
-   14, 13, 14, 14, 13, 14, 13, 14, 13, 13, 13, 14, 13, 13, 14, 13,
-   13, 13, 13, 13, 14, 13, 12, 12, 13, 13, 13, 12, 13, 13, 13, 13,
-   13, 12, 13, 13, 12, 12, 13, 13, 13, 13, 14, 14, 13, 13, 13, 13,
-   13, 13, 13, 12, 12, 12, 13, 13, 12, 12, 12, 13, 12, 12, 12, 12,
-   12, 12, 12, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 11, 12, 12,
-   12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 14, 13, 13, 13, 13,
-   13, 13, 13, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 14,
-   13, 12, 12, 11, 12, 12, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
-   12, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 11, 11, 11, 11,
-   12, 12, 12, 12, 11, 11, 12, 12, 12, 12, 12, 13, 12, 12, 12, 13,
-   12, 12, 13, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14,
-   12, 12, 11, 11, 12, 12, 12, 12, 11, 12, 11, 12, 12, 12, 12, 12,
-   13, 13, 12, 12, 13, 13, 13, 14, 12, 13, 13, 13, 13, 13, 13, 13,
-   11, 10, 11, 10, 11, 11, 10, 10, 11, 11, 11, 11, 10,  9, 11, 10,
-   12, 12, 11, 12, 12, 12, 12, 13, 11, 12, 12, 12, 13, 13, 12, 12
-};
-
-static const int8_t cb1_vects[128][40]={
-    {
-     38,  -4,  15,  -4,  14, -13,  12, -11,  -2,  -6,
-     -6, -11, -45, -16, -11, -13,  -7,   6, -12,   4,
-    -20,   3, -16,  12,  -1,  12,  46,  24,   0,  33,
-     -3,   9, -12, -12,  -8,  -7,  17,  -6,   0,  -2,
-    }, {
-     60, -16,   3, -22,  10, -32,   0, -28, -17, -18,
-     -3, -25, -37, -23, -10,   3,   2,   3,   0,   3,
-    -14,   0, -14,  -1,   0,   2,  32,   9,  -1,  25,
-      7,  13,  -5,  13,   8,   1,   2,   8, -10,   6,
-    }, {
-     27, -12,  28,  -2,   6,  -7,  15,   9, -11,   1,
-    -13, -11, -40,   4, -29, -14, -19,  -5, -23,  -8,
-    -30, -13, -17,   0, -14,  12,  34,  20,  -2,  25,
-      2, -16,  -4, -12,  15,  16,  29,   7,  24,  10,
-    }, {
-     49, -24,  16, -20,   2, -26,   2,  -7, -25, -10,
-    -11, -25, -32,  -3, -27,   2,  -8,  -8, -11,  -9,
-    -24, -17, -16, -14, -13,   2,  20,   5,  -4,  17,
-     14, -12,   3,  13,  33,  25,  14,  23,  15,  19,
-    }, {
-     46,  -6,  21,   8,  -2, -16,  -5,  -8, -11,   4,
-      8,  15, -24,   4,  -2, -26,  -3, -16, -16, -14,
-     -9,  -2,  -1,   4,  19,   7,  36,  17,   9,  13,
-      0,  31,  -5, -12,   7,  -8,  11, -15, -13,  -4,
-    }, {
-     68, -18,   9,  -9,  -6, -35, -18, -25, -26,  -7,
-     10,   1, -16,  -3,  -1,  -9,   6, -19,  -4, -15,
-     -4,  -6,   0,  -8,  20,  -2,  23,   2,   7,   5,
-     12,  35,   1,  13,  24,   0,  -3,   0, -22,   4,
-    }, {
-     35, -14,  34,  10, -10, -10,  -1,  12, -20,  12,
-      0,  15, -18,  24, -20, -27, -14, -28, -27, -27,
-    -20, -19,  -2,  -8,   5,   7,  25,  13,   5,   5,
-      6,   5,   2, -12,  31,  15,  23,  -1,  12,   8,
-    }, {
-     57, -26,  22,  -7, -14, -28, -14,  -3, -35,   0,
-      3,   1, -11,  16, -18, -10,  -4, -31, -15, -28,
-    -14, -23,  -1, -21,   7,  -2,  11,  -1,   3,  -1,
-     18,   9,  10,  13,  49,  24,   8,  14,   2,  16,
-    }, {
-     25,  15,  22,  11,  18,   4,  15, -22,   8,  -2,
-    -17,  -9, -48, -20, -30, -17, -16,  11,  -1,  16,
-      2,  10,  -5,  26,  -2,  -4,  22,   0,   2,  10,
-     -6,  13, -14,  10, -23,   0,  10,  -2,   1,   0,
-    }, {
-     47,   3,  11,  -6,  15, -13,   2, -38,  -6, -13,
-    -15, -22, -40, -28, -28,   0,  -5,   8,  10,  15,
-      7,   7,  -4,  13,  -1, -14,   9, -14,   0,   2,
-      4,  18,  -7,  36,  -6,   8,  -3,  13,  -7,   8,
-    }, {
-     14,   7,  36,  13,  10,  10,  18,   0,   0,   5,
-    -25,  -8, -43,   0, -48, -18, -27,   0, -12,   3,
-     -7,  -6,  -7,  13, -15,  -5,  11,  -3,   0,   2,
-      0, -12,  -6,  10,   0,  23,  22,  11,  26,  12,
-    }, {
-     36,  -5,  24,  -4,   7,  -7,   6, -17, -14,  -5,
-    -22, -22, -35,  -8, -46,  -1, -17,  -3,   0,   2,
-     -2, -10,  -5,   0, -14, -15,  -2, -18,  -2,  -4,
-     11,  -7,   1,  36,  18,  32,   7,  27,  17,  20,
-    }, {
-     33,  13,  29,  24,   1,   1,  -2, -18,   0,   9,
-     -3,  17, -27,   0, -21, -30, -12, -11,  -5,  -2,
-     12,   4,   9,  19,  18,  -9,  13,  -6,  11,  -8,
-     -2,  35,  -8,  10,  -7,  -1,   4, -11, -10,  -2,
-    }, {
-     55,   1,  17,   6,  -1, -16, -15, -35, -15,  -2,
-      0,   4, -19,  -8, -20, -13,  -1, -14,   7,  -3,
-     18,   0,  10,   5,  19, -19,   0, -21,   8, -16,
-      9,  39,   0,  36,  10,   7,  -9,   4, -20,   5,
-    }, {
-     22,   5,  42,  26,  -6,   8,   1,   2,  -9,  17,
-    -10,  18, -21,  19, -39, -31, -23, -23, -16, -15,
-      2, -12,   7,   6,   5,  -9,   1, -10,   7, -16,
-      4,   9,   0,  10,  17,  22,  16,   2,  14,   9,
-    }, {
-     44,  -6,  30,   8,  -9, -10, -11, -14, -23,   5,
-     -8,   4, -14,  12, -37, -14, -12, -26,  -4, -16,
-      8, -16,   9,  -7,   6, -19, -12, -25,   5, -24,
-     15,  13,   8,  36,  34,  31,   1,  18,   4,  18,
-    }, {
-     -3,  -5,  -9,  -7,  15,  -1,   5,  13,   2,  12,
-      5,   2, -21, -23,  -2, -16,   0,   5,  -6,  13,
-    -23,   3, -32,  10, -15,   8,  44,  28,   9,  37,
-     -2,  13,  -9, -15, -12, -27,  -7, -12,   0, -11,
-    }, {
-     18, -17, -21, -25,  11, -19,  -6,  -3, -11,   0,
-      7, -11, -13, -31,  -1,   0,   9,   1,   5,  12,
-    -18,   0, -31,  -2, -13,  -1,  30,  14,   7,  29,
-      9,  18,  -1,  10,   4, -18, -22,   3, -10,  -2,
-    }, {
-    -13, -13,   3,  -5,   7,   4,   9,  34,  -5,  20,
-     -2,   3, -16,  -3, -20, -17, -11,  -7, -17,   0,
-    -34, -13, -33,  -2, -28,   8,  32,  24,   5,  29,
-      3, -12,   0, -15,  11,  -3,   3,   2,  24,   1,
-    }, {
-      8, -25,  -8, -23,   3, -13,  -3,  17, -20,   8,
-      0, -10,  -8, -11, -18,   0,  -1, -10,  -5,   0,
-    -28, -17, -32, -15, -26,  -1,  19,   9,   3,  21,
-     15,  -7,   6,   9,  29,   5, -10,  17,  15,   9,
-    }, {
-      4,  -6,  -3,   5,  -1,  -4, -11,  16,  -6,  23,
-     19,  29,   0,  -3,   6, -30,   3, -17, -10,  -5,
-    -13,  -2, -17,   3,   5,   3,  35,  21,  17,  17,
-      2,  35,  -2, -15,   3, -28, -13, -21, -13, -13,
-    }, {
-     26, -19, -15, -12,  -5, -22, -24,   0, -21,  12,
-     21,  15,   8, -11,   7, -12,  14, -20,   2,  -6,
-     -7,  -6, -16,  -9,   6,  -5,  21,   7,  15,  10,
-     13,  39,   5,  10,  20, -19, -28,  -5, -22,  -5,
-    }, {
-     -5, -15,   9,   7,  -9,   2,  -8,  37, -14,  31,
-     11,  29,   5,  16, -11, -30,  -7, -29, -21, -18,
-    -23, -19, -18,  -9,  -7,   3,  23,  17,  14,   9,
-      8,   9,   6, -15,  27,  -4,  -2,  -6,  12,  -1,
-    }, {
-     16, -27,  -2, -10, -13, -16, -20,  20, -29,  20,
-     14,  16,  13,   8,  -9, -13,   2, -33,  -9, -19,
-    -17, -23, -17, -22,  -6,  -6,   9,   2,  12,   2,
-     20,  13,  13,  10,  45,   4, -16,   8,   2,   7,
-    }, {
-    -16,  14,  -2,   8,  20,  17,   9,   2,  14,  16,
-     -6,   5, -24, -28, -21, -20,  -8,   9,   4,  25,
-     -1,  11, -22,  24, -15,  -8,  21,   5,  11,  14,
-     -5,  18, -11,   7, -27, -20, -14,  -7,   1,  -9,
-    }, {
-      6,   2, -14,  -9,  16,  -1,  -3, -14,   0,   5,
-     -3,  -8, -16, -36, -19,  -3,   1,   6,  17,  24,
-      4,   7, -21,  11, -14, -18,   7,  -9,   9,   7,
-      6,  22,  -3,  33, -10, -11, -28,   7,  -7,   0,
-    }, {
-    -26,   6,  11,  10,  12,  23,  12,  23,   5,  24,
-    -13,   5, -19,  -8, -38, -21, -20,  -2,  -6,  12,
-    -11,  -5, -23,  11, -29,  -9,   9,   0,   7,   6,
-      1,  -7,  -2,   7,  -3,   3,  -2,   6,  27,   3,
-    }, {
-     -4,  -6,   0,  -7,   8,   4,   0,   6,  -9,  13,
-    -11,  -7, -11, -15, -37,  -4,  -9,  -5,   5,  11,
-     -5,  -9, -22,  -1, -27, -18,  -4, -14,   5,   0,
-     12,  -3,   4,  32,  14,  12, -17,  22,  17,  11,
-    }, {
-     -8,  12,   3,  21,   3,  14,  -8,   5,   4,  28,
-      7,  32,  -2,  -8, -12, -34,  -4, -12,   1,   6,
-      9,   4,  -7,  17,   4, -13,  11,  -1,  19,  -4,
-      0,  39,  -4,   7, -11, -21, -20, -16, -10, -11,
-    }, {
-     13,   0,  -8,   3,   0,  -4, -21, -11,  -9,  16,
-     10,  18,   5, -16, -10, -16,   5, -15,  13,   5,
-     15,   1,  -6,   4,   6, -23,  -2, -16,  17, -12,
-     10,  44,   3,  33,   6, -12, -34,  -1, -20,  -3,
-    }, {
-    -18,   4,  17,  23,  -4,  20,  -4,  26,  -3,  36,
-      0,  32,   2,  12, -29, -34, -16, -24, -10,  -6,
-      0, -12,  -8,   4,  -8, -13,   0,  -6,  16, -12,
-      5,  13,   3,   7,  13,   3,  -8,  -2,  14,   0,
-    }, {
-      3,  -7,   5,   5,  -8,   2, -17,   9, -18,  24,
-      2,  19,  10,   4, -28, -17,  -5, -28,   2,  -7,
-      4, -15,  -7,  -8,  -6, -23, -13, -21,  14, -20,
-     17,  18,  11,  33,  30,  11, -23,  13,   5,   9,
-    }, {
-     60,  10,   7,  -1,   9,  -8,   6, -13,   2, -15,
-     -1, -10, -13, -11,  15,   0,   6,   9,  -1,   0,
-    -13,   1, -11,  -3, -13,  21,  13,  26,  -7,  31,
-    -10,  -7, -16, -33, -31, -10,  22,  -8,   1,  -2,
-    }, {
-     82,  -1,  -4, -19,   6, -27,  -6, -29, -12, -26,
-      1, -24,  -5, -18,  17,  17,  17,   6,  10,   0,
-     -7,  -2,  -9, -16, -12,  11,   0,  11,  -9,  23,
-      0,  -3,  -8,  -8, -13,  -1,   8,   7,  -7,   6,
-    }, {
-     49,   2,  21,   0,   1,  -2,   9,   8,  -6,  -6,
-     -8, -10,  -8,   9,  -2,   0,  -4,  -2, -13, -12,
-    -23, -15, -12, -16, -26,  21,   2,  21, -11,  23,
-     -4, -33,  -7, -33,  -6,  13,  34,   5,  27,  10,
-    }, {
-     71, -10,   9, -17,  -1, -20,  -3,  -8, -21, -18,
-     -6, -24,   0,   1,   0,  16,   6,  -5,   0, -13,
-    -17, -19, -11, -29, -25,  11, -11,   6, -13,  15,
-      7, -29,   0,  -8,  11,  22,  20,  21,  17,  18,
-    }, {
-     67,   8,  14,  11,  -7, -11, -11,  -9,  -7,  -3,
-     13,  16,   8,   9,  24, -12,  10, -13,  -5, -17,
-     -2,  -4,   3, -10,   6,  17,   4,  19,   0,  11,
-     -6,  13,  -9, -33, -14, -10,  16, -17, -10,  -4,
-    }, {
-     90,  -3,   2,  -6, -10, -29, -24, -26, -21, -15,
-     15,   2,  16,   1,  25,   4,  21, -16,   6, -18,
-      3,  -8,   5, -24,   8,   7,  -9,   4,  -1,   3,
-      5,  18,  -1,  -7,   2,  -1,   2,  -1, -19,   3,
-    }, {
-     57,   0,  27,  13, -14,  -5,  -7,  11, -15,   4,
-      5,  16,  13,  29,   6, -13,   0, -25, -16, -31,
-    -12, -22,   2, -23,  -6,  16,  -7,  14,  -2,   3,
-      0, -12,   0, -33,   9,  13,  28,  -3,  14,   7,
-    }, {
-     79, -11,  15,  -4, -18, -23, -20,  -5, -30,  -7,
-      7,   2,  21,  21,   8,   3,  10, -28,  -4, -31,
-     -6, -25,   3, -37,  -4,   7, -20,   0,  -4,  -4,
-     11,  -7,   6,  -8,  27,  22,  14,  12,   5,  16,
-    }, {
-     47,  30,  15,  14,  14,   9,   9, -23,  13, -10,
-    -12,  -7, -16, -15,  -3,  -3,  -1,  14,   9,  12,
-      9,   8,   0,  10, -14,   4,  -9,   2,  -5,   8,
-    -13,  -3, -18, -10, -45,  -3,  16,  -4,   4,   0,
-    }, {
-     69,  17,   3,  -3,  10,  -8,  -3, -40,  -1, -21,
-    -10, -21,  -8, -23,  -1,  13,   8,  11,  21,  11,
-     15,   4,   0,  -2, -13,  -5, -23, -12,  -7,   0,
-     -1,   0, -10,  14, -28,   5,   1,  11,  -5,   7,
-    }, {
-     36,  21,  28,  16,   6,  16,  12,  -2,   4,  -2,
-    -20,  -7, -11,   4, -20,  -4, -12,   2,  -1,   0,
-      0,  -8,  -2,  -2, -27,   4, -21,  -2,  -9,   0,
-     -6, -29,  -9, -10, -21,  21,  28,  10,  29,  11,
-    }, {
-     58,   9,  16,  -1,   2,  -2,   0, -19, -10, -13,
-    -17, -21,  -3,  -3, -19,  12,  -2,   0,  10,  -1,
-      5, -12,   0, -15, -26,  -5, -34, -16, -11,  -7,
-      4, -25,  -2,  14,  -3,  29,  13,  25,  20,  20,
-    }, {
-     55,  28,  21,  27,  -2,   7,  -8, -20,   4,   1,
-      1,  18,   5,   4,   5, -16,   2,  -8,   5,  -5,
-     19,   2,  14,   3,   6,   0, -18,  -4,   2, -11,
-     -8,  18, -11, -10, -29,  -3,  10, -13,  -8,  -3,
-    }, {
-     77,  16,   9,   9,  -6, -11, -21, -37, -10, -10,
-      4,   5,  13,  -3,   7,   0,  13, -11,  17,  -6,
-     25,  -1,  15,  -9,   7,  -9, -32, -19,   0, -18,
-      2,  22,  -3,  15, -12,   5,  -4,   2, -17,   5,
-    }, {
-     44,  20,  34,  29, -10,  13,  -4,   0,  -4,   9,
-     -5,  19,  10,  24, -11, -17,  -8, -20,  -5, -19,
-      9, -14,  12,  -9,  -6,   0, -30,  -9,   0, -19,
-     -2,  -7,  -2, -10,  -5,  20,  21,   1,  17,   9,
-    }, {
-     66,   8,  23,  11, -14,  -5, -17, -16, -19,  -2,
-     -3,   5,  18,  17, -10,   0,   1, -23,   6, -20,
-     15, -18,  14, -22,  -5, -10, -44, -23,  -2, -26,
-      9,  -3,   4,  14,  12,  29,   7,  16,   7,  18,
-    }, {
-     18,   9, -17,  -4,  11,   3,   0,  11,   7,   4,
-     10,   3,  10, -18,  24,  -3,  14,   7,   4,  10,
-    -16,   1, -27,  -4, -27,  17,  12,  30,   0,  35,
-     -9,  -3, -12, -36, -35, -30,  -2, -13,   2, -11,
-    }, {
-     40,  -2, -29, -22,   7, -14, -12,  -5,  -7,  -7,
-     12,  -9,  18, -26,  26,  14,  24,   4,  16,   9,
-    -10,  -2, -26, -18, -26,   7,  -1,  15,  -1,  27,
-      2,   0,  -4, -11, -17, -21, -16,   1,  -7,  -3,
-    }, {
-      8,   1,  -3,  -2,   3,  10,   3,  32,  -1,  12,
-      2,   4,  15,   1,   7,  -3,   2,  -4,  -6,  -3,
-    -26, -15, -29, -17, -40,  17,   0,  26,  -2,  27,
-     -2, -29,  -4, -36, -10,  -6,   9,   0,  27,   0,
-    }, {
-     30, -11, -15, -20,   0,  -8,  -9,  15, -15,   0,
-      5,  -9,  23,  -6,   8,  13,  13,  -7,   5,  -3,
-    -20, -19, -27, -31, -39,   7, -13,  11,  -4,  19,
-      8, -25,   3, -11,   7,   2,  -4,  16,  18,   9,
-    }, {
-     26,   7, -11,   8,  -5,   1, -17,  14,  -1,  15,
-     24,  30,  32,   1,  33, -16,  18, -14,   0,  -8,
-     -6,  -4, -12, -12,  -6,  13,   2,  23,   8,  15,
-     -4,  17,  -5, -36, -18, -30,  -8, -22, -10, -14,
-    }, {
-     48,  -4, -23,  -9,  -9, -17, -30,  -2, -16,   3,
-     26,  16,  40,  -6,  35,   1,  28, -17,  12,  -9,
-      0,  -8, -11, -25,  -5,   3, -10,   8,   6,   7,
-      6,  22,   1, -11,  -1, -21, -22,  -7, -19,  -5,
-    }, {
-     15,   0,   2,  10, -13,   7, -14,  35, -10,  23,
-     16,  31,  37,  21,  16, -17,   6, -26, -10, -21,
-    -16, -21, -13, -25, -19,  13,  -8,  19,   5,   7,
-      1,  -8,   2, -36,   5,  -6,   3,  -8,  15,  -1,
-    }, {
-     37, -12,  -9,  -7, -17, -11, -26,  18, -25,  12,
-     19,  17,  45,  14,  17,   0,  17, -30,   1, -22,
-    -10, -25, -12, -38, -18,   3, -22,   4,   3,   0,
-     13,  -3,  10, -11,  23,   2, -10,   7,   5,   7,
-    }, {
-      5,  29,  -9,  11,  15,  22,   3,   0,  18,   8,
-     -1,   6,   7, -23,   6,  -6,   5,  12,  15,  21,
-      5,   8, -17,   9, -28,   0, -11,   6,   2,  12,
-    -11,   0, -14, -13, -49, -22,  -8,  -9,   4,  -9,
-    }, {
-     27,  16, -21,  -6,  12,   3,  -9, -16,   3,  -2,
-      1,  -7,  15, -31,   7,  10,  16,   9,  27,  21,
-     11,   5, -16,  -3, -26,  -9, -24,  -7,   0,   4,
-      0,   4,  -6,  11, -32, -14, -23,   6,  -5,  -1,
-    }, {
-     -4,  20,   3,  13,   8,  28,   6,  21,  10,  16,
-     -8,   7,  12,  -3, -11,  -7,  -5,   0,   4,   8,
-     -4,  -8, -18,  -3, -41,   0, -22,   2,   0,   4,
-     -5, -25,  -6, -14, -25,   1,   2,   4,  29,   2,
-    }, {
-     17,   8,  -8,  -4,   4,  10,  -6,   5,  -4,   5,
-     -6,  -6,  20, -10,  -9,   9,   4,  -2,  16,   7,
-      1, -12, -17, -16, -39,  -9, -36, -12,  -2,  -3,
-      6, -21,   1,  11,  -7,  10, -11,  20,  20,  11,
-    }, {
-     13,  27,  -3,  24,  -1,  19, -14,   3,   9,  20,
-     12,  33,  29,  -3,  15, -20,   9,  -9,  11,   3,
-     16,   2,  -2,   2,  -7,  -3, -20,   0,  10,  -7,
-     -7,  22,  -7, -13, -33, -23, -14, -18,  -7, -12,
-    }, {
-     35,  15, -15,   6,  -4,   1, -27, -12,  -5,   8,
-     15,  19,  37, -11,  16,  -2,  20, -12,  23,   2,
-     22,  -1,  -1, -11,  -5, -13, -34, -14,   8, -14,
-      4,  26,   0,  11, -16, -14, -29,  -2, -17,  -3,
-    }, {
-      3,  19,   9,  26,  -8,  26, -10,  24,   0,  28,
-      5,  33,  34,  17,  -2, -20,  -1, -22,   0, -10,
-      6, -14,  -3, -10, -20,  -4, -32,  -4,   7, -15,
-      0,  -3,   0, -13,  -9,   0,  -3,  -4,  17,   0,
-    }, {
-     25,   7,  -2,   8, -12,   7, -23,   8, -13,  16,
-      7,  20,  42,   9,   0,  -3,   9, -25,  12, -10,
-     12, -18,  -2, -24, -19, -13, -46, -19,   5, -22,
-     10,   0,   8,  11,   8,   9, -17,  11,   7,   8,
-    }, {
-    -25,  -7,   2,  -8,  12,  -7,  23,  -8,  13, -16,
-     -7, -20, -42,  -9,   0,   3,  -9,  25, -12,  10,
-    -12,  18,   2,  24,  19,  13,  46,  19,  -5,  22,
-    -10,   0,  -8, -11,  -8,  -9,  17, -11,  -7,  -8,
-    }, {
-     -3, -19,  -9, -26,   8, -26,  10, -24,   0, -28,
-     -5, -33, -34, -17,   2,  20,   1,  22,   0,  10,
-     -6,  14,   3,  10,  20,   4,  32,   4,  -7,  15,
-      0,   3,   0,  13,   9,   0,   3,   4, -17,   0,
-    }, {
-    -35, -15,  15,  -6,   4,  -1,  27,  12,   5,  -8,
-    -15, -19, -37,  11, -16,   2, -20,  12, -23,  -2,
-    -22,   1,   1,  11,   5,  13,  34,  14,  -8,  14,
-     -4, -26,   0, -11,  16,  14,  29,   2,  17,   3,
-    }, {
-    -13, -27,   3, -24,   1, -19,  14,  -3,  -9, -20,
-    -12, -33, -29,   3, -15,  20,  -9,   9, -11,  -3,
-    -16,  -2,   2,  -2,   7,   3,  20,   0, -10,   7,
-      7, -22,   7,  13,  33,  23,  14,  18,   7,  12,
-    }, {
-    -17,  -8,   8,   4,  -4, -10,   6,  -5,   4,  -5,
-      6,   6, -20,  10,   9,  -9,  -4,   2, -16,  -7,
-     -1,  12,  17,  16,  39,   9,  36,  12,   2,   3,
-     -6,  21,  -1, -11,   7, -10,  11, -20, -20, -11,
-    }, {
-      4, -20,  -3, -13,  -8, -28,  -6, -21, -10, -16,
-      8,  -7, -12,   3,  11,   7,   5,   0,  -4,  -8,
-      4,   8,  18,   3,  41,   0,  22,  -2,   0,  -4,
-      5,  25,   6,  14,  25,  -1,  -2,  -4, -29,  -2,
-    }, {
-    -27, -16,  21,   6, -12,  -3,   9,  16,  -3,   2,
-     -1,   7, -15,  31,  -7, -10, -16,  -9, -27, -21,
-    -11,  -5,  16,   3,  26,   9,  24,   7,   0,  -4,
-      0,  -4,   6, -11,  32,  14,  23,  -6,   5,   1,
-    }, {
-     -5, -29,   9, -11, -15, -22,  -3,   0, -18,  -8,
-      1,  -6,  -7,  23,  -6,   6,  -5, -12, -15, -21,
-     -5,  -8,  17,  -9,  28,   0,  11,  -6,  -2, -12,
-     11,   0,  14,  13,  49,  22,   8,   9,  -4,   9,
-    }, {
-    -37,  12,   9,   7,  17,  11,  26, -18,  25, -12,
-    -19, -17, -45, -14, -17,   0, -17,  30,  -1,  22,
-     10,  25,  12,  38,  18,  -3,  22,  -4,  -3,   0,
-    -13,   3, -10,  11, -23,  -2,  10,  -7,  -5,  -7,
-    }, {
-    -15,   0,  -2, -10,  13,  -7,  14, -35,  10, -23,
-    -16, -31, -37, -21, -16,  17,  -6,  26,  10,  21,
-     16,  21,  13,  25,  19, -13,   8, -19,  -5,  -7,
-     -1,   8,  -2,  36,  -5,   6,  -3,   8, -15,   1,
-    }, {
-    -48,   4,  23,   9,   9,  17,  30,   2,  16,  -3,
-    -26, -16, -40,   6, -35,  -1, -28,  17, -12,   9,
-      0,   8,  11,  25,   5,  -3,  10,  -8,  -6,  -7,
-     -6, -22,  -1,  11,   1,  21,  22,   7,  19,   5,
-    }, {
-    -26,  -7,  11,  -8,   5,  -1,  17, -14,   1, -15,
-    -24, -30, -32,  -1, -33,  16, -18,  14,   0,   8,
-      6,   4,  12,  12,   6, -13,  -2, -23,  -8, -15,
-      4, -17,   5,  36,  18,  30,   8,  22,  10,  14,
-    }, {
-    -30,  11,  15,  20,   0,   8,   9, -15,  15,   0,
-     -5,   9, -23,   6,  -8, -13, -13,   7,  -5,   3,
-     20,  19,  27,  31,  39,  -7,  13, -11,   4, -19,
-     -8,  25,  -3,  11,  -7,  -2,   4, -16, -18,  -9,
-    }, {
-     -8,  -1,   3,   2,  -3, -10,  -3, -32,   1, -12,
-     -2,  -4, -15,  -1,  -7,   3,  -2,   4,   6,   3,
-     26,  15,  29,  17,  40, -17,   0, -26,   2, -27,
-      2,  29,   4,  36,  10,   6,  -9,   0, -27,   0,
-    }, {
-    -40,   2,  29,  22,  -7,  14,  12,   5,   7,   7,
-    -12,   9, -18,  26, -26, -14, -24,  -4, -16,  -9,
-     10,   2,  26,  18,  26,  -7,   1, -15,   1, -27,
-     -2,   0,   4,  11,  17,  21,  16,  -1,   7,   3,
-    }, {
-    -18,  -9,  17,   4, -11,  -3,   0, -11,  -7,  -4,
-    -10,  -3, -10,  18, -24,   3, -14,  -7,  -4, -10,
-     16,  -1,  27,   4,  27, -17, -12, -30,   0, -35,
-      9,   3,  12,  36,  35,  30,   2,  13,  -2,  11,
-    }, {
-    -66,  -8, -23, -11,  14,   5,  17,  16,  19,   2,
-      3,  -5, -18, -17,  10,   0,  -1,  23,  -6,  20,
-    -15,  18, -14,  22,   5,  10,  44,  23,   2,  26,
-     -9,   3,  -4, -14, -12, -29,  -7, -16,  -7, -18,
-    }, {
-    -44, -20, -34, -29,  10, -13,   4,   0,   4,  -9,
-      5, -19, -10, -24,  11,  17,   8,  20,   5,  19,
-     -9,  14, -12,   9,   6,   0,  30,   9,   0,  19,
-      2,   7,   2,  10,   5, -20, -21,  -1, -17,  -9,
-    }, {
-    -77, -16,  -9,  -9,   6,  11,  21,  37,  10,  10,
-     -4,  -5, -13,   3,  -7,   0, -13,  11, -17,   6,
-    -25,   1, -15,   9,  -7,   9,  32,  19,   0,  18,
-     -2, -22,   3, -15,  12,  -5,   4,  -2,  17,  -5,
-    }, {
-    -55, -28, -21, -27,   2,  -7,   8,  20,  -4,  -1,
-     -1, -18,  -5,  -4,  -5,  16,  -2,   8,  -5,   5,
-    -19,  -2, -14,  -3,  -6,   0,  18,   4,  -2,  11,
-      8, -18,  11,  10,  29,   3, -10,  13,   8,   3,
-    }, {
-    -58,  -9, -16,   1,  -2,   2,   0,  19,  10,  13,
-     17,  21,   3,   3,  19, -12,   2,   0, -10,   1,
-     -5,  12,   0,  15,  26,   5,  34,  16,  11,   7,
-     -4,  25,   2, -14,   3, -29, -13, -25, -20, -20,
-    }, {
-    -36, -21, -28, -16,  -6, -16, -12,   2,  -4,   2,
-     20,   7,  11,  -4,  20,   4,  12,  -2,   1,   0,
-      0,   8,   2,   2,  27,  -4,  21,   2,   9,   0,
-      6,  29,   9,  10,  21, -21, -28, -10, -29, -11,
-    }, {
-    -69, -17,  -3,   3, -10,   8,   3,  40,   1,  21,
-     10,  21,   8,  23,   1, -13,  -8, -11, -21, -11,
-    -15,  -4,   0,   2,  13,   5,  23,  12,   7,   0,
-      1,   0,  10, -14,  28,  -5,  -1, -11,   5,  -7,
-    }, {
-    -47, -30, -15, -14, -14,  -9,  -9,  23, -13,  10,
-     12,   7,  16,  15,   3,   3,   1, -14,  -9, -12,
-     -9,  -8,   0, -10,  14,  -4,   9,  -2,   5,  -8,
-     13,   3,  18,  10,  45,   3, -16,   4,  -4,   0,
-    }, {
-    -79,  11, -15,   4,  18,  23,  20,   5,  30,   7,
-     -7,  -2, -21, -21,  -8,  -3, -10,  28,   4,  31,
-      6,  25,  -3,  37,   4,  -7,  20,   0,   4,   4,
-    -11,   7,  -6,   8, -27, -22, -14, -12,  -5, -16,
-    }, {
-    -57,   0, -27, -13,  14,   5,   7, -11,  15,  -4,
-     -5, -16, -13, -29,  -6,  13,   0,  25,  16,  31,
-     12,  22,  -2,  23,   6, -16,   7, -14,   2,  -3,
-      0,  12,   0,  33,  -9, -13, -28,   3, -14,  -7,
-    }, {
-    -90,   3,  -2,   6,  10,  29,  24,  26,  21,  15,
-    -15,  -2, -16,  -1, -25,  -4, -21,  16,  -6,  18,
-     -3,   8,  -5,  24,  -8,  -7,   9,  -4,   1,  -3,
-     -5, -18,   1,   7,  -2,   1,  -2,   1,  19,  -3,
-    }, {
-    -67,  -8, -14, -11,   7,  11,  11,   9,   7,   3,
-    -13, -16,  -8,  -9, -24,  12, -10,  13,   5,  17,
-      2,   4,  -3,  10,  -6, -17,  -4, -19,   0, -11,
-      6, -13,   9,  33,  14,  10, -16,  17,  10,   4,
-    }, {
-    -71,  10,  -9,  17,   1,  20,   3,   8,  21,  18,
-      6,  24,   0,  -1,   0, -16,  -6,   5,   0,  13,
-     17,  19,  11,  29,  25, -11,  11,  -6,  13, -15,
-     -7,  29,   0,   8, -11, -22, -20, -21, -17, -18,
-    }, {
-    -49,  -2, -21,   0,  -1,   2,  -9,  -8,   6,   6,
-      8,  10,   8,  -9,   2,   0,   4,   2,  13,  12,
-     23,  15,  12,  16,  26, -21,  -2, -21,  11, -23,
-      4,  33,   7,  33,   6, -13, -34,  -5, -27, -10,
-    }, {
-    -82,   1,   4,  19,  -6,  27,   6,  29,  12,  26,
-     -1,  24,   5,  18, -17, -17, -17,  -6, -10,   0,
-      7,   2,   9,  16,  12, -11,   0, -11,   9, -23,
-      0,   3,   8,   8,  13,   1,  -8,  -7,   7,  -6,
-    }, {
-    -60, -10,  -7,   1,  -9,   8,  -6,  13,  -2,  15,
-      1,  10,  13,  11, -15,   0,  -6,  -9,   1,   0,
-     13,  -1,  11,   3,  13, -21, -13, -26,   7, -31,
-     10,   7,  16,  33,  31,  10, -22,   8,  -1,   2,
-    }, {
-     -3,   7,  -5,  -5,   8,  -2,  17,  -9,  18, -24,
-     -2, -19, -10,  -4,  28,  17,   5,  28,  -2,   7,
-     -4,  15,   7,   8,   6,  23,  13,  21, -14,  20,
-    -17, -18, -11, -33, -30, -11,  23, -13,  -5,  -9,
-    }, {
-     18,  -4, -17, -23,   4, -20,   4, -26,   3, -36,
-      0, -32,  -2, -12,  29,  34,  16,  24,  10,   6,
-      0,  12,   8,  -4,   8,  13,   0,   6, -16,  12,
-     -5, -13,  -3,  -7, -13,  -3,   8,   2, -14,   0,
-    }, {
-    -13,   0,   8,  -3,   0,   4,  21,  11,   9, -16,
-    -10, -18,  -5,  16,  10,  16,  -5,  15, -13,  -5,
-    -15,  -1,   6,  -4,  -6,  23,   2,  16, -17,  12,
-    -10, -44,  -3, -33,  -6,  12,  34,   1,  20,   3,
-    }, {
-      8, -12,  -3, -21,  -3, -14,   8,  -5,  -4, -28,
-     -7, -32,   2,   8,  12,  34,   4,  12,  -1,  -6,
-     -9,  -4,   7, -17,  -4,  13, -11,   1, -19,   4,
-      0, -39,   4,  -7,  11,  21,  20,  16,  10,  11,
-    }, {
-      4,   6,   0,   7,  -8,  -4,   0,  -6,   9, -13,
-     11,   7,  11,  15,  37,   4,   9,   5,  -5, -11,
-      5,   9,  22,   1,  27,  18,   4,  14,  -5,   0,
-    -12,   3,  -4, -32, -14, -12,  17, -22, -17, -11,
-    }, {
-     26,  -6, -11, -10, -12, -23, -12, -23,  -5, -24,
-     13,  -5,  19,   8,  38,  21,  20,   2,   6, -12,
-     11,   5,  23, -11,  29,   9,  -9,   0,  -7,  -6,
-     -1,   7,   2,  -7,   3,  -3,   2,  -6, -27,  -3,
-    }, {
-     -6,  -2,  14,   9, -16,   1,   3,  14,   0,  -5,
-      3,   8,  16,  36,  19,   3,  -1,  -6, -17, -24,
-     -4,  -7,  21, -11,  14,  18,  -7,   9,  -9,  -7,
-     -6, -22,   3, -33,  10,  11,  28,  -7,   7,   0,
-    }, {
-     16, -14,   2,  -8, -20, -17,  -9,  -2, -14, -16,
-      6,  -5,  24,  28,  21,  20,   8,  -9,  -4, -25,
-      1, -11,  22, -24,  15,   8, -21,  -5, -11, -14,
-      5, -18,  11,  -7,  27,  20,  14,   7,  -1,   9,
-    }, {
-    -16,  27,   2,  10,  13,  16,  20, -20,  29, -20,
-    -14, -16, -13,  -8,   9,  13,  -2,  33,   9,  19,
-     17,  23,  17,  22,   6,   6,  -9,  -2, -12,  -2,
-    -20, -13, -13, -10, -45,  -4,  16,  -8,  -2,  -7,
-    }, {
-      5,  15,  -9,  -7,   9,  -2,   8, -37,  14, -31,
-    -11, -29,  -5, -16,  11,  30,   7,  29,  21,  18,
-     23,  19,  18,   9,   7,  -3, -23, -17, -14,  -9,
-     -8,  -9,  -6,  15, -27,   4,   2,   6, -12,   1,
-    }, {
-    -26,  19,  15,  12,   5,  22,  24,   0,  21, -12,
-    -21, -15,  -8,  11,  -7,  12, -14,  20,  -2,   6,
-      7,   6,  16,   9,  -6,   5, -21,  -7, -15, -10,
-    -13, -39,  -5, -10, -20,  19,  28,   5,  22,   5,
-    }, {
-     -4,   6,   3,  -5,   1,   4,  11, -16,   6, -23,
-    -19, -29,   0,   3,  -6,  30,  -3,  17,  10,   5,
-     13,   2,  17,  -3,  -5,  -3, -35, -21, -17, -17,
-     -2, -35,   2,  15,  -3,  28,  13,  21,  13,  13,
-    }, {
-     -8,  25,   8,  23,  -3,  13,   3, -17,  20,  -8,
-      0,  10,   8,  11,  18,   0,   1,  10,   5,   0,
-     28,  17,  32,  15,  26,   1, -19,  -9,  -3, -21,
-    -15,   7,  -6,  -9, -29,  -5,  10, -17, -15,  -9,
-    }, {
-     13,  13,  -3,   5,  -7,  -4,  -9, -34,   5, -20,
-      2,  -3,  16,   3,  20,  17,  11,   7,  17,   0,
-     34,  13,  33,   2,  28,  -8, -32, -24,  -5, -29,
-     -3,  12,   0,  15, -11,   3,  -3,  -2, -24,  -1,
-    }, {
-    -18,  17,  21,  25, -11,  19,   6,   3,  11,   0,
-     -7,  11,  13,  31,   1,   0,  -9,  -1,  -5, -12,
-     18,   0,  31,   2,  13,   1, -30, -14,  -7, -29,
-     -9, -18,   1, -10,  -4,  18,  22,  -3,  10,   2,
-    }, {
-      3,   5,   9,   7, -15,   1,  -5, -13,  -2, -12,
-     -5,  -2,  21,  23,   2,  16,   0,  -5,   6, -13,
-     23,  -3,  32, -10,  15,  -8, -44, -28,  -9, -37,
-      2, -13,   9,  15,  12,  27,   7,  12,   0,  11,
-    }, {
-    -44,   6, -30,  -8,   9,  10,  11,  14,  23,  -5,
-      8,  -4,  14, -12,  37,  14,  12,  26,   4,  16,
-     -8,  16,  -9,   7,  -6,  19,  12,  25,  -5,  24,
-    -15, -13,  -8, -36, -34, -31,  -1, -18,  -4, -18,
-    }, {
-    -22,  -5, -42, -26,   6,  -8,  -1,  -2,   9, -17,
-     10, -18,  21, -19,  39,  31,  23,  23,  16,  15,
-     -2,  12,  -7,  -6,  -5,   9,  -1,  10,  -7,  16,
-     -4,  -9,   0, -10, -17, -22, -16,  -2, -14,  -9,
-    }, {
-    -55,  -1, -17,  -6,   1,  16,  15,  35,  15,   2,
-      0,  -4,  19,   8,  20,  13,   1,  14,  -7,   3,
-    -18,   0, -10,  -5, -19,  19,   0,  21,  -8,  16,
-     -9, -39,   0, -36, -10,  -7,   9,  -4,  20,  -5,
-    }, {
-    -33, -13, -29, -24,  -1,  -1,   2,  18,   0,  -9,
-      3, -17,  27,   0,  21,  30,  12,  11,   5,   2,
-    -12,  -4,  -9, -19, -18,   9, -13,   6, -11,   8,
-      2, -35,   8, -10,   7,   1,  -4,  11,  10,   2,
-    }, {
-    -36,   5, -24,   4,  -7,   7,  -6,  17,  14,   5,
-     22,  22,  35,   8,  46,   1,  17,   3,   0,  -2,
-      2,  10,   5,   0,  14,  15,   2,  18,   2,   4,
-    -11,   7,  -1, -36, -18, -32,  -7, -27, -17, -20,
-    }, {
-    -14,  -7, -36, -13, -10, -10, -18,   0,   0,  -5,
-     25,   8,  43,   0,  48,  18,  27,   0,  12,  -3,
-      7,   6,   7, -13,  15,   5, -11,   3,   0,  -2,
-      0,  12,   6, -10,   0, -23, -22, -11, -26, -12,
-    }, {
-    -47,  -3, -11,   6, -15,  13,  -2,  38,   6,  13,
-     15,  22,  40,  28,  28,   0,   5,  -8, -10, -15,
-     -7,  -7,   4, -13,   1,  14,  -9,  14,   0,  -2,
-     -4, -18,   7, -36,   6,  -8,   3, -13,   7,  -8,
-    }, {
-    -25, -15, -22, -11, -18,  -4, -15,  22,  -8,   2,
-     17,   9,  48,  20,  30,  17,  16, -11,   1, -16,
-     -2, -10,   5, -26,   2,   4, -22,   0,  -2, -10,
-      6, -13,  14, -10,  23,   0, -10,   2,  -1,   0,
-    }, {
-    -57,  26, -22,   7,  14,  28,  14,   3,  35,   0,
-     -3,  -1,  11, -16,  18,  10,   4,  31,  15,  28,
-     14,  23,   1,  21,  -7,   2, -11,   1,  -3,   1,
-    -18,  -9, -10, -13, -49, -24,  -8, -14,  -2, -16,
-    }, {
-    -35,  14, -34, -10,  10,  10,   1, -12,  20, -12,
-      0, -15,  18, -24,  20,  27,  14,  28,  27,  27,
-     20,  19,   2,   8,  -5,  -7, -25, -13,  -5,  -5,
-     -6,  -5,  -2,  12, -31, -15, -23,   1, -12,  -8,
-    }, {
-    -68,  18,  -9,   9,   6,  35,  18,  25,  26,   7,
-    -10,  -1,  16,   3,   1,   9,  -6,  19,   4,  15,
-      4,   6,   0,   8, -20,   2, -23,  -2,  -7,  -5,
-    -12, -35,  -1, -13, -24,   0,   3,   0,  22,  -4,
-    }, {
-    -46,   6, -21,  -8,   2,  16,   5,   8,  11,  -4,
-     -8, -15,  24,  -4,   2,  26,   3,  16,  16,  14,
-      9,   2,   1,  -4, -19,  -7, -36, -17,  -9, -13,
-      0, -31,   5,  12,  -7,   8, -11,  15,  13,   4,
-    }, {
-    -49,  24, -16,  20,  -2,  26,  -2,   7,  25,  10,
-     11,  25,  32,   3,  27,  -2,   8,   8,  11,   9,
-     24,  17,  16,  14,  13,  -2, -20,  -5,   4, -17,
-    -14,  12,  -3, -13, -33, -25, -14, -23, -15, -19,
-    }, {
-    -27,  12, -28,   2,  -6,   7, -15,  -9,  11,  -1,
-     13,  11,  40,  -4,  29,  14,  19,   5,  23,   8,
-     30,  13,  17,   0,  14, -12, -34, -20,   2, -25,
-     -2,  16,   4,  12, -15, -16, -29,  -7, -24, -10,
-    }, {
-    -60,  16,  -3,  22, -10,  32,   0,  28,  17,  18,
-      3,  25,  37,  23,  10,  -3,  -2,  -3,   0,  -3,
-     14,   0,  14,   1,   0,  -2, -32,  -9,   1, -25,
-     -7, -13,   5, -13,  -8,  -1,  -2,  -8,  10,  -6,
-    }, {
-    -38,   4, -15,   4, -14,  13, -12,  11,   2,   6,
-      6,  11,  45,  16,  11,  13,   7,  -6,  12,  -4,
-     20,  -3,  16, -12,   1, -12, -46, -24,   0, -33,
-      3,  -9,  12,  12,   8,   7, -17,   6,   0,   2
-    }
-};
-
-static const int8_t cb2_vects[128][40]={
-    {
-     73, -32, -60, -15, -26,  59,   2, -33,  30, -10,
-     -3, -17,   8,  30,  -1, -26,  -4, -22,  10,  16,
-    -36,  -5, -11,  56,  37,   6, -10,  -5, -13,  -3,
-      6,  -5,  11,   4, -19,  -5, -16,  41,  24,  13,
-    }, {
-      4, -11, -37,  23,  -5,  46,  -2, -29,  -5, -39,
-    -21,  -9,   0,  49,  12,  -9, -16, -26,  22,  15,
-    -45, -20,  -5,  40,  22,  17, -26,  31, -14,   2,
-    -14,  10,  30,  20, -27,  -9, -39,  39,  18,   5,
-    }, {
-     34, -25, -48, -28, -11,  34,  -2, -41,   9,  -7,
-    -17,  21,  20,  24, -17, -33,   0, -24,  10,  42,
-      3,  -5,  10,  42,  11,   8,  -3,   3,  16,   9,
-     22,  -2,   0, -33, -10,  18,   7,  58,  10,  28,
-    }, {
-    -34,  -4, -25,  10,   9,  21,  -7, -36, -26, -36,
-    -35,  28,  12,  42,  -3, -16, -12, -28,  21,  42,
-     -5, -21,  16,  26,  -4,  19, -19,  39,  15,  15,
-      1,  13,  19, -17, -17,  14, -15,  55,   4,  19,
-    }, {
-     28, -20, -51, -14,  -6,   7,   0, -26,  27,  -4,
-     18, -40,  -6,  16,  -1, -15,   0, -55,  -5, -16,
-    -19,  14,  -3,  49,  14,   1, -22, -30, -12,   0,
-     24,  15,   9, -17, -45, -29,   4,  28,  51,  35,
-    }, {
-    -40,   0, -28,  24,  14,  -5,  -4, -21,  -7, -33,
-      0, -32, -15,  35,  12,   1, -11, -58,   5, -16,
-    -28,   0,   1,  33,   0,  11, -39,   5, -14,   6,
-      3,  31,  28,  -1, -53, -33, -19,  25,  46,  26,
-    }, {
-    -11, -14, -39, -27,   9, -17,  -4, -33,   6,   0,
-      4,  -1,   5,  10, -17, -22,   5, -57,  -5,   9,
-     20,  13,  18,  35, -11,   3, -16, -22,  17,  13,
-     40,  19,  -1, -55, -35,  -5,  27,  44,  37,  49,
-    }, {
-    -80,   6, -16,  11,  30, -30,  -9, -28, -28, -29,
-    -13,   6,  -2,  28,  -3,  -5,  -7, -60,   5,   9,
-     11,  -1,  24,  19, -27,  13, -32,  13,  15,  19,
-     19,  35,  17, -39, -43,  -9,   4,  42,  32,  41,
-    }, {
-     78, -21, -43,   4, -38,  17,  17,  -5,  55,  24,
-    -15, -36,  14,   4,  24, -24,  12,   5,  17,  31,
-    -54,  -5,  -2,  27,  43, -12,   2,   9,  -9, -15,
-     22,  -3,  28,  21, -20,   3,  20,  28,   9,  -5,
-    }, {
-      9,  -1, -20,  43, -17,   3,  12,   0,  20,  -4,
-    -33, -29,   6,  22,  38,  -7,   0,   1,  29,  30,
-    -63, -21,   3,  11,  27,  -1, -14,  45, -10,  -9,
-      1,  12,  47,  37, -28,   0,  -2,  26,   4, -13,
-    }, {
-     39, -14, -30,  -8, -22,  -8,  12, -12,  34,  27,
-    -29,   2,  26,  -2,   8, -31,  16,   3,  17,  57,
-    -14,  -6,  19,  13,  16, -10,   8,  17,  20,  -2,
-     38,   0,  17, -16, -11,  27,  44,  45,  -4,   8,
-    }, {
-    -29,   5,  -7,  30,  -1, -21,   7,  -7,   0,   0,
-    -47,   9,  18,  15,  22, -14,   4,   0,  28,  57,
-    -23, -21,  25,  -2,   1,   0,  -7,  53,  19,   3,
-     17,  15,  36,   0, -19,  24,  21,  43,  -9,   0,
-    }, {
-     33, -10, -34,   5, -17, -35,  15,   1,  53,  30,
-      6, -59,   0, -10,  24, -13,  17, -27,   1,  -1,
-    -37,  13,   4,  20,  20, -18, -10, -16,  -8, -11,
-     39,  18,  26,   0, -46, -20,  41,  15,  37,  15,
-    }, {
-    -35,  10, -11,  44,   3, -48,  10,   6,  17,   2,
-    -11, -51,  -8,   8,  38,   3,   4, -31,  12,  -2,
-    -46,  -1,  10,   4,   5,  -7, -26,  19, -10,  -5,
-     18,  34,  45,  15, -54, -24,  18,  13,  31,   7,
-    }, {
-     -5,  -3, -21,  -7,  -2, -60,  10,  -5,  32,  34,
-     -7, -20,  11, -16,   8, -20,  21, -29,   1,  24,
-      2,  13,  27,   6,  -5, -15,  -3,  -8,  21,   1,
-     55,  21,  15, -38, -37,   3,  65,  32,  23,  30,
-    }, {
-    -74,  17,   0,  31,  18, -73,   5,   0,  -3,   5,
-    -25, -12,   3,   1,  22,  -3,   9, -33,  12,  24,
-     -6,  -2,  33,  -9, -21,  -5, -20,  27,  19,   7,
-     34,  37,  34, -22, -44,   0,  41,  29,  17,  21,
-    }, {
-     76, -35, -31, -28, -49,  43, -40,   0,  29, -14,
-      8,   5,  10,  18, -26, -46,   0,   7,   6,   3,
-    -25,  -7,  -2,  40,  28,  14,  18,  -3, -27, -28,
-     -8, -45, -13,  34, -13, -27, -15,  31,  12,   3,
-    }, {
-      7, -15,  -9,   9, -28,  29, -45,   5,  -6, -43,
-     -9,  12,   2,  36, -12, -30, -11,   3,  17,   3,
-    -34, -22,   3,  24,  12,  24,   2,  32, -28, -22,
-    -29, -29,   5,  50, -21, -31, -38,  29,   7,  -5,
-    }, {
-     36, -29, -19, -41, -34,  18, -45,  -6,   8, -10,
-     -5,  43,  23,  11, -42, -53,   5,   5,   6,  30,
-     14,  -8,  20,  26,   1,  16,  25,   4,   3, -15,
-      7, -41, -23,  -3,  -4,  -3,   8,  48,  -1,  17,
-    }, {
-    -32,  -8,   3,  -2, -13,   4, -50,  -1, -27, -39,
-    -23,  51,  15,  30, -27, -37,  -7,   1,  17,  29,
-      5, -23,  25,  10, -14,  26,   8,  41,   1,  -9,
-    -13, -26,  -5,  12, -12,  -7, -14,  45,  -6,   9,
-    }, {
-     31, -24, -23, -27, -29,  -9, -43,   8,  26,  -7,
-     30, -17,  -4,   3, -26, -35,   5, -24, -10, -28,
-     -9,  12,   5,  33,   5,   8,   5, -29, -26, -24,
-      9, -23, -14,  12, -39, -52,   5,  18,  39,  24,
-    }, {
-    -37,  -3,   0,  10,  -7, -22, -48,  12,  -8, -36,
-     12,  -9, -12,  22, -12, -19,  -6, -28,   0, -29,
-    -18,  -3,  11,  17, -10,  18, -10,   7, -27, -18,
-    -11,  -7,   3,  28, -47, -55, -18,  15,  34,  16,
-    }, {
-     -8, -17, -10, -40, -13, -34, -47,   0,   5,  -4,
-     16,  21,   8,  -2, -42, -43,  10, -26, -10,  -2,
-     31,  11,  27,  19, -21,  10,  12, -20,   3, -11,
-     25, -20, -25, -25, -29, -28,  28,  34,  25,  38,
-    }, {
-    -77,   2,  11,  -1,   7, -47, -52,   5, -29, -33,
-     -1,  28,   0,  15, -28, -26,  -2, -30,   0,  -2,
-     22,  -4,  33,   3, -36,  21,  -3,  15,   2,  -5,
-      4,  -4,  -6,  -9, -37, -31,   5,  32,  20,  30,
-    }, {
-     81, -25, -14,  -8, -61,   0, -25,  28,  54,  20,
-     -3, -14,  17,  -8,   0, -44,  16,  35,  13,  18,
-    -43,  -7,   6,  11,  33,  -4,  30,  11, -22, -40,
-      6, -43,   3,  50, -14, -18,  22,  18,  -1, -16,
-    }, {
-     12,  -4,   8,  29, -39, -12, -30,  33,  19,  -8,
-    -21,  -6,   8,   9,  13, -28,   4,  31,  24,  18,
-    -52, -23,  12,  -4,  18,   5,  14,  47, -24, -34,
-    -14, -27,  22,  66, -22, -22,  -1,  16,  -6, -24,
-    }, {
-     41, -18,  -2, -21, -45, -24, -30,  21,  33,  24,
-    -17,  24,  29, -15, -16, -51,  21,  33,  13,  45,
-     -3,  -8,  28,  -2,   7,  -2,  37,  19,   7, -27,
-     22, -39,  -7,  12,  -5,   5,  45,  35, -15,  -1,
-    }, {
-    -27,   1,  20,  17, -24, -38, -35,  26,  -1,  -4,
-    -35,  32,  21,   3,  -2, -35,   8,  29,  24,  44,
-    -12, -24,  34, -18,  -8,   7,  21,  55,   5, -21,
-      2, -23,  11,  28, -13,   1,  22,  33, -21, -10,
-    }, {
-     36, -13,  -5,  -7, -40, -51, -28,  36,  52,  27,
-     18, -36,   2, -22,   0, -33,  21,   2,  -3, -13,
-    -26,  11,  14,   4,  10, -10,  18, -14, -22, -36,
-     24, -21,   1,  28, -40, -42,  42,   5,  25,   5,
-    }, {
-    -32,   6,  17,  31, -19, -65, -33,  41,  16,  -1,
-      0, -29,  -6,  -4,  13, -17,   9,  -1,   8, -14,
-    -35,  -3,  19, -11,  -4,   0,   1,  21, -23, -30,
-      3,  -5,  20,  44, -48, -46,  19,   3,  20,  -3,
-    }, {
-     -3,  -7,   6, -20, -25, -77, -32,  29,  31,  30,
-      4,   2,  14, -29, -16, -40,  26,   0,  -3,  12,
-     13,  10,  36,  -9, -15,  -8,  24,  -6,   7, -22,
-     40, -17,  -8,  -9, -31, -18,  66,  22,  11,  19,
-    }, {
-    -72,  13,  29,  18,  -4, -90, -37,  34,  -4,   1,
-    -13,   9,   6, -11,  -2, -24,  13,  -3,   7,  11,
-      4,  -4,  42, -25, -31,   1,   8,  29,   6, -17,
-     19,  -2,  10,   6, -38, -22,  42,  19,   6,  11,
-    }, {
-    116, -20, -68, -30, -28,  83,  28, -18,  32, -22,
-    -13, -21,   5,  28,   5,  -7, -24,  -8, -22,  17,
-    -23,  30, -25,  45,  15,  -9, -11, -18,  22, -10,
-      4,  -2,  19, -12,  23,   3, -43,   2,  12,  -4,
-    }, {
-     47,   0, -45,   7,  -7,  69,  23, -13,  -2, -51,
-    -32, -14,  -3,  47,  19,   8, -37, -11, -10,  16,
-    -32,  15, -19,  29,   0,   1, -28,  18,  20,  -4,
-    -16,  13,  38,   3,  15,   0, -66,   0,   7, -13,
-    }, {
-     77, -13, -56, -43, -13,  57,  23, -26,  11, -19,
-    -27,  16,  17,  22, -10, -15, -19, -10, -22,  43,
-     16,  30,  -2,  31, -11,  -6,  -5,  -9,  52,   2,
-     20,   0,   8, -50,  33,  27, -19,  19,  -1,   9,
-    }, {
-      8,   6, -33,  -4,   7,  44,  18, -21, -23, -48,
-    -46,  24,   9,  40,   3,   1, -32, -13, -11,  43,
-      7,  14,   3,  15, -26,   3, -21,  26,  50,   8,
-      0,  16,  27, -34,  25,  23, -43,  17,  -6,   1,
-    }, {
-     71,  -9, -59, -29,  -8,  30,  26, -11,  30, -16,
-      8, -44,  -9,  14,   5,   2, -19, -40, -38, -15,
-     -7,  50, -17,  38,  -7, -14, -24, -43,  22,  -6,
-     22,  19,  17, -34,  -2, -20, -23, -10,  39,  16,
-    }, {
-      2,  11, -36,   9,  13,  17,  21,  -6,  -5, -45,
-    -10, -36, -18,  33,  19,  19, -31, -44, -27, -15,
-    -16,  34, -11,  22, -22,  -4, -40,  -7,  21,   0,
-      1,  35,  36, -18, -10, -24, -46, -12,  34,   8,
-    }, {
-     32,  -2, -47, -42,   7,   5,  21, -18,   9, -12,
-     -5,  -5,   2,   8, -10,  -4, -14, -42, -38,  10,
-     33,  49,   5,  24, -33, -12, -17, -35,  52,   6,
-     38,  22,   7, -72,   7,   3,   0,   6,  25,  30,
-    }, {
-    -36,  18, -24,  -3,  28,  -7,  16, -13, -26, -41,
-    -24,   1,  -5,  26,   3,  12, -27, -46, -27,  10,
-     24,  34,  10,   8, -49,  -2, -34,   0,  51,  12,
-     17,  38,  25, -56,   0,   0, -22,   3,  20,  22,
-    }, {
-    121,  -9, -50, -10, -40,  40,  43,   9,  58,  12,
-    -25, -41,  11,   2,  31,  -5,  -8,  19, -15,  32,
-    -41,  30, -16,  16,  20, -28,   0,  -3,  26, -22,
-     19,   0,  36,   4,  22,  12,  -6,  -9,  -1, -24,
-    }, {
-     52,  10, -27,  27, -18,  26,  38,  14,  23, -16,
-    -44, -33,   3,  20,  45,  10, -20,  15,  -3,  31,
-    -50,  14, -10,   0,   5, -17, -15,  32,  24, -16,
-     -1,  15,  55,  20,  14,   8, -29, -12,  -7, -32,
-    }, {
-     82,  -3, -38, -23, -24,  15,  38,   2,  37,  15,
-    -39,  -2,  23,  -4,  15, -12,  -3,  17, -15,  58,
-     -1,  29,   6,   2,  -5, -26,   7,   4,  56,  -9,
-     35,   3,  25, -33,  32,  36,  17,   7, -15,  -9,
-    }, {
-     13,  17, -15,  15,  -3,   1,  33,   7,   1, -12,
-    -58,   5,  15,  13,  29,   3, -16,  13,  -4,  57,
-    -10,  13,  11, -13, -21, -15,  -9,  40,  55,  -3,
-     14,  19,  44, -17,  24,  32,  -5,   4, -21, -18,
-    }, {
-     76,   1, -41,  -9, -19, -12,  41,  17,  55,  18,
-     -3, -63,  -3, -12,  30,   5,  -3, -12, -31,   0,
-    -24,  49,  -8,   9,  -1, -33, -12, -29,  27, -18,
-     37,  21,  34, -17,  -3, -11,  14, -23,  25,  -2,
-    }, {
-      7,  22, -18,  29,   1, -25,  36,  21,  20,  -9,
-    -22, -56, -11,   6,  45,  21, -15, -16, -20,  -1,
-    -33,  34,  -2,  -6, -17, -23, -28,   6,  25, -12,
-     16,  37,  53,  -1, -11, -15,  -8, -25,  20, -11,
-    }, {
-     37,   8, -29, -22,  -4, -37,  36,   9,  34,  22,
-    -17, -24,   8, -18,  15,  -2,   1, -14, -31,  25,
-     15,  48,  13,  -4, -28, -31,  -5, -21,  57,  -4,
-     53,  24,  23, -55,   6,  12,  37,  -6,  11,  11,
-    }, {
-    -31,  28,  -6,  16,  16, -50,  31,  14,   0,  -6,
-    -36, -17,   0,   0,  29,  14, -11, -18, -20,  25,
-      6,  33,  19, -20, -43, -21, -21,  14,  55,   0,
-     32,  40,  42, -39,  -1,   8,  14,  -8,   6,   3,
-    }, {
-    119, -24, -39, -44, -51,  66, -14,  15,  31, -26,
-     -1,   0,   7,  16, -19, -28, -19,  22, -26,   4,
-    -13,  28, -16,  29,   5,  -1,  16, -16,   8, -35,
-    -10, -42,  -4,  17,  29, -19, -42,  -7,   0, -15,
-    }, {
-     50,  -3, -16,  -5, -30,  53, -19,  20,  -3, -55,
-    -19,   8,   0,  34,  -5, -11, -32,  18, -15,   4,
-    -22,  13, -10,  13,  -9,   8,   0,  19,   7, -29,
-    -31, -26,  13,  33,  21, -22, -65,  -9,  -4, -23,
-    }, {
-     79, -17, -27, -56, -36,  41, -19,   8,  10, -22,
-    -15,  39,  20,   9, -35, -35, -15,  20, -26,  31,
-     26,  27,   6,  15, -20,   0,  23,  -8,  38, -22,
-      5, -38, -15, -20,  39,   4, -18,   9, -13,  -1,
-    }, {
-     10,   3,  -4, -18, -15,  27, -24,  13, -24, -51,
-    -34,  47,  12,  28, -21, -19, -27,  16, -15,  30,
-     17,  12,  12,   0, -36,  10,   7,  27,  37, -16,
-    -15, -22,   3,  -4,  31,   1, -42,   7, -18,  -9,
-    }, {
-     74, -12, -30, -42, -30,  14, -16,  23,  29, -19,
-     20, -21,  -7,   1, -19, -17, -14, -10, -43, -27,
-      3,  48,  -8,  22, -16,  -7,   4, -42,   9, -31,
-      6, -20,  -6,  -4,   3, -43, -22, -20,  28,   5,
-    }, {
-      5,   7,  -7,  -4,  -9,   0, -21,  28,  -6, -48,
-      2, -14, -15,  20,  -5,   0, -27, -14, -32, -28,
-     -5,  32,  -2,   6, -32,   3, -12,  -5,   8, -25,
-    -14,  -4,  12,  11,  -4, -47, -45, -22,  22,  -2,
-    }, {
-     34,  -6, -18, -55, -15, -11, -21,  16,   8, -16,
-      6,  16,   5,  -4, -35, -24, -10, -12, -43,  -1,
-     43,  47,  14,   8, -43,  -5,  10, -34,  39, -18,
-     22, -16, -17, -42,  13, -19,   1,  -3,  14,  20,
-    }, {
-    -34,  14,   4, -17,   5, -24, -26,  20, -27, -45,
-    -12,  24,  -2,  13, -21,  -8, -22, -16, -32,  -2,
-     34,  31,  20,  -7, -58,   5,  -5,   2,  38, -12,
-      2,  -1,   1, -26,   5, -23, -21,  -6,   8,  11,
-    }, {
-    124, -13, -21, -23, -62,  23,   0,  43,  57,   8,
-    -13, -18,  14, -10,   6, -26,  -3,  49, -19,  19,
-    -31,  27,  -7,   0,  11, -20,  29,  -1,  12, -47,
-      4, -39,  11,  34,  28,  -9,  -5, -19, -13, -34,
-    }, {
-     55,   6,   1,  14, -41,  10,  -4,  48,  22, -20,
-    -31, -10,   5,   7,  20,  -9, -16,  45,  -8,  19,
-    -40,  12,  -1, -15,  -4, -10,  12,  34,  11, -41,
-    -16, -24,  30,  49,  20, -13, -28, -22, -18, -43,
-    }, {
-     84,  -6,  -9, -36, -47,  -1,  -4,  36,  36,  12,
-    -27,  20,  26, -17,  -9, -33,   1,  47, -19,  46,
-      9,  27,  15, -13, -15, -18,  35,   6,  42, -33,
-     20, -36,   1,  -4,  38,  14,  18,  -2, -27, -20,
-    }, {
-     15,  13,  13,   1, -26, -14,  -9,  41,   1, -16,
-    -46,  27,  18,   1,   4, -16, -11,  43,  -8,  45,
-      0,  11,  21, -29, -30,  -8,  19,  42,  41, -28,
-      0, -20,  20,  11,  30,  10,  -4,  -5, -32, -28,
-    }, {
-     79,  -2, -12, -22, -42, -28,  -1,  51,  54,  15,
-      8, -41,   0, -24,   6, -15,   1,  17, -36, -12,
-    -14,  47,   0,  -6, -11, -26,  16, -27,  13, -43,
-     22, -18,  10,  12,   2, -34,  15, -33,  13, -13,
-    }, {
-     10,  18,  10,  15, -21, -41,  -6,  56,  19, -13,
-     -9, -33,  -9,  -6,  20,   1, -11,  13, -24, -13,
-    -23,  32,   6, -22, -26, -15,   0,   8,  12, -37,
-      1,  -2,  28,  27,  -5, -37,  -7, -35,   8, -21,
-    }, {
-     39,   4,   0, -35, -27, -53,  -6,  44,  33,  18,
-     -5,  -2,  11, -31,  -9, -22,   6,  15, -36,  13,
-     25,  46,  23, -20, -37, -24,  23, -19,  43, -29,
-     38, -14,   0, -26,  12, -10,  38, -16,   0,   0,
-    }, {
-    -29,  25,  22,   2,  -6, -67, -11,  49,  -1, -10,
-    -24,   5,   3, -13,   4,  -5,  -6,  11, -25,  12,
-     16,  31,  28, -36, -53, -13,   6,  16,  42, -24,
-     17,   1,  18, -10,   4, -13,  15, -18,  -5,  -7,
-    }, {
-     29, -25, -22,  -2,   6,  67,  11, -49,   1,  10,
-     24,  -5,  -3,  13,  -4,   5,   6, -11,  25, -12,
-    -16, -31, -28,  36,  53,  13,  -6, -16, -42,  24,
-    -17,  -1, -18,  10,  -4,  13, -15,  18,   5,   7,
-    }, {
-    -39,  -4,   0,  35,  27,  53,   6, -44, -33, -18,
-      5,   2, -11,  31,   9,  22,  -6, -15,  36, -13,
-    -25, -46, -23,  20,  37,  24, -23,  19, -43,  29,
-    -38,  14,   0,  26, -12,  10, -38,  16,   0,   0,
-    }, {
-    -10, -18, -10, -15,  21,  41,   6, -56, -19,  13,
-      9,  33,   9,   6, -20,  -1,  11, -13,  24,  13,
-     23, -32,  -6,  22,  26,  15,   0,  -8, -12,  37,
-     -1,   2, -28, -27,   5,  37,   7,  35,  -8,  21,
-    }, {
-    -79,   2,  12,  22,  42,  28,   1, -51, -54, -15,
-     -8,  41,   0,  24,  -6,  15,  -1, -17,  36,  12,
-     14, -47,   0,   6,  11,  26, -16,  27, -13,  43,
-    -22,  18, -10, -12,  -2,  34, -15,  33, -13,  13,
-    }, {
-    -15, -13, -13,  -1,  26,  14,   9, -41,  -1,  16,
-     46, -27, -18,  -1,  -4,  16,  11, -43,   8, -45,
-      0, -11, -21,  29,  30,   8, -19, -42, -41,  28,
-      0,  20, -20, -11, -30, -10,   4,   5,  32,  28,
-    }, {
-    -84,   6,   9,  36,  47,   1,   4, -36, -36, -12,
-     27, -20, -26,  17,   9,  33,  -1, -47,  19, -46,
-     -9, -27, -15,  13,  15,  18, -35,  -6, -42,  33,
-    -20,  36,  -1,   4, -38, -14, -18,   2,  27,  20,
-    }, {
-    -55,  -6,  -1, -14,  41, -10,   4, -48, -22,  20,
-     31,  10,  -5,  -7, -20,   9,  16, -45,   8, -19,
-     40, -12,   1,  15,   4,  10, -12, -34, -11,  41,
-     16,  24, -30, -49, -20,  13,  28,  22,  18,  43,
-    }, {
-   -124,  13,  21,  23,  62, -23,   0, -43, -57,  -8,
-     13,  18, -14,  10,  -6,  26,   3, -49,  19, -19,
-     31, -27,   7,   0, -11,  20, -29,   1, -12,  47,
-     -4,  39, -11, -34, -28,   9,   5,  19,  13,  34,
-    }, {
-     34, -14,  -4,  17,  -5,  24,  26, -20,  27,  45,
-     12, -24,   2, -13,  21,   8,  22,  16,  32,   2,
-    -34, -31, -20,   7,  58,  -5,   5,  -2, -38,  12,
-     -2,   1,  -1,  26,  -5,  23,  21,   6,  -8, -11,
-    }, {
-    -34,   6,  18,  55,  15,  11,  21, -16,  -8,  16,
-     -6, -16,  -5,   4,  35,  24,  10,  12,  43,   1,
-    -43, -47, -14,  -8,  43,   5, -10,  34, -39,  18,
-    -22,  16,  17,  42, -13,  19,  -1,   3, -14, -20,
-    }, {
-     -5,  -7,   7,   4,   9,   0,  21, -28,   6,  48,
-     -2,  14,  15, -20,   5,   0,  27,  14,  32,  28,
-      5, -32,   2,  -6,  32,  -3,  12,   5,  -8,  25,
-     14,   4, -12, -11,   4,  47,  45,  22, -22,   2,
-    }, {
-    -74,  12,  30,  42,  30, -14,  16, -23, -29,  19,
-    -20,  21,   7,  -1,  19,  17,  14,  10,  43,  27,
-     -3, -48,   8, -22,  16,   7,  -4,  42,  -9,  31,
-     -6,  20,   6,   4,  -3,  43,  22,  20, -28,  -5,
-    }, {
-    -10,  -3,   4,  18,  15, -27,  24, -13,  24,  51,
-     34, -47, -12, -28,  21,  19,  27, -16,  15, -30,
-    -17, -12, -12,   0,  36, -10,  -7, -27, -37,  16,
-     15,  22,  -3,   4, -31,  -1,  42,  -7,  18,   9,
-    }, {
-    -79,  17,  27,  56,  36, -41,  19,  -8, -10,  22,
-     15, -39, -20,  -9,  35,  35,  15, -20,  26, -31,
-    -26, -27,  -6, -15,  20,   0, -23,   8, -38,  22,
-     -5,  38,  15,  20, -39,  -4,  18,  -9,  13,   1,
-    }, {
-    -50,   3,  16,   5,  30, -53,  19, -20,   3,  55,
-     19,  -8,   0, -34,   5,  11,  32, -18,  15,  -4,
-     22, -13,  10, -13,   9,  -8,   0, -19,  -7,  29,
-     31,  26, -13, -33, -21,  22,  65,   9,   4,  23,
-    }, {
-   -119,  24,  39,  44,  51, -66,  14, -15, -31,  26,
-      1,   0,  -7, -16,  19,  28,  19, -22,  26,  -4,
-     13, -28,  16, -29,  -5,   1, -16,  16,  -8,  35,
-     10,  42,   4, -17, -29,  19,  42,   7,   0,  15,
-    }, {
-     31, -28,   6, -16, -16,  50, -31, -14,   0,   6,
-     36,  17,   0,   0, -29, -14,  11,  18,  20, -25,
-     -6, -33, -19,  20,  43,  21,  21, -14, -55,   0,
-    -32, -40, -42,  39,   1,  -8, -14,   8,  -6,  -3,
-    }, {
-    -37,  -8,  29,  22,   4,  37, -36,  -9, -34, -22,
-     17,  24,  -8,  18, -15,   2,  -1,  14,  31, -25,
-    -15, -48, -13,   4,  28,  31,   5,  21, -57,   4,
-    -53, -24, -23,  55,  -6, -12, -37,   6, -11, -11,
-    }, {
-     -7, -22,  18, -29,  -1,  25, -36, -21, -20,   9,
-     22,  56,  11,  -6, -45, -21,  15,  16,  20,   1,
-     33, -34,   2,   6,  17,  23,  28,  -6, -25,  12,
-    -16, -37, -53,   1,  11,  15,   8,  25, -20,  11,
-    }, {
-    -76,  -1,  41,   9,  19,  12, -41, -17, -55, -18,
-      3,  63,   3,  12, -30,  -5,   3,  12,  31,   0,
-     24, -49,   8,  -9,   1,  33,  12,  29, -27,  18,
-    -37, -21, -34,  17,   3,  11, -14,  23, -25,   2,
-    }, {
-    -13, -17,  15, -15,   3,  -1, -33,  -7,  -1,  12,
-     58,  -5, -15, -13, -29,  -3,  16, -13,   4, -57,
-     10, -13, -11,  13,  21,  15,   9, -40, -55,   3,
-    -14, -19, -44,  17, -24, -32,   5,  -4,  21,  18,
-    }, {
-    -82,   3,  38,  23,  24, -15, -38,  -2, -37, -15,
-     39,   2, -23,   4, -15,  12,   3, -17,  15, -58,
-      1, -29,  -6,  -2,   5,  26,  -7,  -4, -56,   9,
-    -35,  -3, -25,  33, -32, -36, -17,  -7,  15,   9,
-    }, {
-    -52, -10,  27, -27,  18, -26, -38, -14, -23,  16,
-     44,  33,  -3, -20, -45, -10,  20, -15,   3, -31,
-     50, -14,  10,   0,  -5,  17,  15, -32, -24,  16,
-      1, -15, -55, -20, -14,  -8,  29,  12,   7,  32,
-    }, {
-   -121,   9,  50,  10,  40, -40, -43,  -9, -58, -12,
-     25,  41, -11,  -2, -31,   5,   8, -19,  15, -32,
-     41, -30,  16, -16, -20,  28,   0,   3, -26,  22,
-    -19,   0, -36,  -4, -22, -12,   6,   9,   1,  24,
-    }, {
-     36, -18,  24,   3, -28,   7, -16,  13,  26,  41,
-     24,  -1,   5, -26,  -3, -12,  27,  46,  27, -10,
-    -24, -34, -10,  -8,  49,   2,  34,   0, -51, -12,
-    -17, -38, -25,  56,   0,   0,  22,  -3, -20, -22,
-    }, {
-    -32,   2,  47,  42,  -7,  -5, -21,  18,  -9,  12,
-      5,   5,  -2,  -8,  10,   4,  14,  42,  38, -10,
-    -33, -49,  -5, -24,  33,  12,  17,  35, -52,  -6,
-    -38, -22,  -7,  72,  -7,  -3,   0,  -6, -25, -30,
-    }, {
-     -2, -11,  36,  -9, -13, -17, -21,   6,   5,  45,
-     10,  36,  18, -33, -19, -19,  31,  44,  27,  15,
-     16, -34,  11, -22,  22,   4,  40,   7, -21,   0,
-     -1, -35, -36,  18,  10,  24,  46,  12, -34,  -8,
-    }, {
-    -71,   9,  59,  29,   8, -30, -26,  11, -30,  16,
-     -8,  44,   9, -14,  -5,  -2,  19,  40,  38,  15,
-      7, -50,  17, -38,   7,  14,  24,  43, -22,   6,
-    -22, -19, -17,  34,   2,  20,  23,  10, -39, -16,
-    }, {
-     -8,  -6,  33,   4,  -7, -44, -18,  21,  23,  48,
-     46, -24,  -9, -40,  -3,  -1,  32,  13,  11, -43,
-     -7, -14,  -3, -15,  26,  -3,  21, -26, -50,  -8,
-      0, -16, -27,  34, -25, -23,  43, -17,   6,  -1,
-    }, {
-    -77,  13,  56,  43,  13, -57, -23,  26, -11,  19,
-     27, -16, -17, -22,  10,  15,  19,  10,  22, -43,
-    -16, -30,   2, -31,  11,   6,   5,   9, -52,  -2,
-    -20,   0,  -8,  50, -33, -27,  19, -19,   1,  -9,
-    }, {
-    -47,   0,  45,  -7,   7, -69, -23,  13,   2,  51,
-     32,  14,   3, -47, -19,  -8,  37,  11,  10, -16,
-     32, -15,  19, -29,   0,  -1,  28, -18, -20,   4,
-     16, -13, -38,  -3, -15,   0,  66,   0,  -7,  13,
-    }, {
-   -116,  20,  68,  30,  28, -83, -28,  18, -32,  22,
-     13,  21,  -5, -28,  -5,   7,  24,   8,  22, -17,
-     23, -30,  25, -45, -15,   9,  11,  18, -22,  10,
-     -4,   2, -19,  12, -23,  -3,  43,  -2, -12,   4,
-    }, {
-     72, -13, -29, -18,   4,  90,  37, -34,   4,  -1,
-     13,  -9,  -6,  11,   2,  24, -13,   3,  -7, -11,
-     -4,   4, -42,  25,  31,  -1,  -8, -29,  -6,  17,
-    -19,   2, -10,  -6,  38,  22, -42, -19,  -6, -11,
-    }, {
-      3,   7,  -6,  20,  25,  77,  32, -29, -31, -30,
-     -4,  -2, -14,  29,  16,  40, -26,   0,   3, -12,
-    -13, -10, -36,   9,  15,   8, -24,   6,  -7,  22,
-    -40,  17,   8,   9,  31,  18, -66, -22, -11, -19,
-    }, {
-     32,  -6, -17, -31,  19,  65,  33, -41, -16,   1,
-      0,  29,   6,   4, -13,  17,  -9,   1,  -8,  14,
-     35,   3, -19,  11,   4,   0,  -1, -21,  23,  30,
-     -3,   5, -20, -44,  48,  46, -19,  -3, -20,   3,
-    }, {
-    -36,  13,   5,   7,  40,  51,  28, -36, -52, -27,
-    -18,  36,  -2,  22,   0,  33, -21,  -2,   3,  13,
-     26, -11, -14,  -4, -10,  10, -18,  14,  22,  36,
-    -24,  21,  -1, -28,  40,  42, -42,  -5, -25,  -5,
-    }, {
-     27,  -1, -20, -17,  24,  38,  35, -26,   1,   4,
-     35, -32, -21,  -3,   2,  35,  -8, -29, -24, -44,
-     12,  24, -34,  18,   8,  -7, -21, -55,  -5,  21,
-     -2,  23, -11, -28,  13,  -1, -22, -33,  21,  10,
-    }, {
-    -41,  18,   2,  21,  45,  24,  30, -21, -33, -24,
-     17, -24, -29,  15,  16,  51, -21, -33, -13, -45,
-      3,   8, -28,   2,  -7,   2, -37, -19,  -7,  27,
-    -22,  39,   7, -12,   5,  -5, -45, -35,  15,   1,
-    }, {
-    -12,   4,  -8, -29,  39,  12,  30, -33, -19,   8,
-     21,   6,  -8,  -9, -13,  28,  -4, -31, -24, -18,
-     52,  23, -12,   4, -18,  -5, -14, -47,  24,  34,
-     14,  27, -22, -66,  22,  22,   1, -16,   6,  24,
-    }, {
-    -81,  25,  14,   8,  61,   0,  25, -28, -54, -20,
-      3,  14, -17,   8,   0,  44, -16, -35, -13, -18,
-     43,   7,  -6, -11, -33,   4, -30, -11,  22,  40,
-     -6,  43,  -3, -50,  14,  18, -22, -18,   1,  16,
-    }, {
-     77,  -2, -11,   1,  -7,  47,  52,  -5,  29,  33,
-      1, -28,   0, -15,  28,  26,   2,  30,   0,   2,
-    -22,   4, -33,  -3,  36, -21,   3, -15,  -2,   5,
-     -4,   4,   6,   9,  37,  31,  -5, -32, -20, -30,
-    }, {
-      8,  17,  10,  40,  13,  34,  47,   0,  -5,   4,
-    -16, -21,  -8,   2,  42,  43, -10,  26,  10,   2,
-    -31, -11, -27, -19,  21, -10, -12,  20,  -3,  11,
-    -25,  20,  25,  25,  29,  28, -28, -34, -25, -38,
-    }, {
-     37,   3,   0, -10,   7,  22,  48, -12,   8,  36,
-    -12,   9,  12, -22,  12,  19,   6,  28,   0,  29,
-     18,   3, -11, -17,  10, -18,  10,  -7,  27,  18,
-     11,   7,  -3, -28,  47,  55,  18, -15, -34, -16,
-    }, {
-    -31,  24,  23,  27,  29,   9,  43,  -8, -26,   7,
-    -30,  17,   4,  -3,  26,  35,  -5,  24,  10,  28,
-      9, -12,  -5, -33,  -5,  -8,  -5,  29,  26,  24,
-     -9,  23,  14, -12,  39,  52,  -5, -18, -39, -24,
-    }, {
-     32,   8,  -3,   2,  13,  -4,  50,   1,  27,  39,
-     23, -51, -15, -30,  27,  37,   7,  -1, -17, -29,
-     -5,  23, -25, -10,  14, -26,  -8, -41,  -1,   9,
-     13,  26,   5, -12,  12,   7,  14, -45,   6,  -9,
-    }, {
-    -36,  29,  19,  41,  34, -18,  45,   6,  -8,  10,
-      5, -43, -23, -11,  42,  53,  -5,  -5,  -6, -30,
-    -14,   8, -20, -26,  -1, -16, -25,  -4,  -3,  15,
-     -7,  41,  23,   3,   4,   3,  -8, -48,   1, -17,
-    }, {
-     -7,  15,   9,  -9,  28, -29,  45,  -5,   6,  43,
-      9, -12,  -2, -36,  12,  30,  11,  -3, -17,  -3,
-     34,  22,  -3, -24, -12, -24,  -2, -32,  28,  22,
-     29,  29,  -5, -50,  21,  31,  38, -29,  -7,   5,
-    }, {
-    -76,  35,  31,  28,  49, -43,  40,   0, -29,  14,
-     -8,  -5, -10, -18,  26,  46,   0,  -7,  -6,  -3,
-     25,   7,   2, -40, -28, -14, -18,   3,  27,  28,
-      8,  45,  13, -34,  13,  27,  15, -31, -12,  -3,
-    }, {
-     74, -17,   0, -31, -18,  73,  -5,   0,   3,  -5,
-     25,  12,  -3,  -1, -22,   3,  -9,  33, -12, -24,
-      6,   2, -33,   9,  21,   5,  20, -27, -19,  -7,
-    -34, -37, -34,  22,  44,   0, -41, -29, -17, -21,
-    }, {
-      5,   3,  21,   7,   2,  60, -10,   5, -32, -34,
-      7,  20, -11,  16,  -8,  20, -21,  29,  -1, -24,
-     -2, -13, -27,  -6,   5,  15,   3,   8, -21,  -1,
-    -55, -21, -15,  38,  37,  -3, -65, -32, -23, -30,
-    }, {
-     35, -10,  11, -44,  -3,  48, -10,  -6, -17,  -2,
-     11,  51,   8,  -8, -38,  -3,  -4,  31, -12,   2,
-     46,   1, -10,  -4,  -5,   7,  26, -19,  10,   5,
-    -18, -34, -45, -15,  54,  24, -18, -13, -31,  -7,
-    }, {
-    -33,  10,  34,  -5,  17,  35, -15,  -1, -53, -30,
-     -6,  59,   0,  10, -24,  13, -17,  27,  -1,   1,
-     37, -13,  -4, -20, -20,  18,  10,  16,   8,  11,
-    -39, -18, -26,   0,  46,  20, -41, -15, -37, -15,
-    }, {
-     29,  -5,   7, -30,   1,  21,  -7,   7,   0,   0,
-     47,  -9, -18, -15, -22,  14,  -4,   0, -28, -57,
-     23,  21, -25,   2,  -1,   0,   7, -53, -19,  -3,
-    -17, -15, -36,   0,  19, -24, -21, -43,   9,   0,
-    }, {
-    -39,  14,  30,   8,  22,   8, -12,  12, -34, -27,
-     29,  -2, -26,   2,  -8,  31, -16,  -3, -17, -57,
-     14,   6, -19, -13, -16,  10,  -8, -17, -20,   2,
-    -38,   0, -17,  16,  11, -27, -44, -45,   4,  -8,
-    }, {
-     -9,   1,  20, -43,  17,  -3, -12,   0, -20,   4,
-     33,  29,  -6, -22, -38,   7,   0,  -1, -29, -30,
-     63,  21,  -3, -11, -27,   1,  14, -45,  10,   9,
-     -1, -12, -47, -37,  28,   0,   2, -26,  -4,  13,
-    }, {
-    -78,  21,  43,  -4,  38, -17, -17,   5, -55, -24,
-     15,  36, -14,  -4, -24,  24, -12,  -5, -17, -31,
-     54,   5,   2, -27, -43,  12,  -2,  -9,   9,  15,
-    -22,   3, -28, -21,  20,  -3, -20, -28,  -9,   5,
-    }, {
-     80,  -6,  16, -11, -30,  30,   9,  28,  28,  29,
-     13,  -6,   2, -28,   3,   5,   7,  60,  -5,  -9,
-    -11,   1, -24, -19,  27, -13,  32, -13, -15, -19,
-    -19, -35, -17,  39,  43,   9,  -4, -42, -32, -41,
-    }, {
-     11,  14,  39,  27,  -9,  17,   4,  33,  -6,   0,
-     -4,   1,  -5, -10,  17,  22,  -5,  57,   5,  -9,
-    -20, -13, -18, -35,  11,  -3,  16,  22, -17, -13,
-    -40, -19,   1,  55,  35,   5, -27, -44, -37, -49,
-    }, {
-     40,   0,  28, -24, -14,   5,   4,  21,   7,  33,
-      0,  32,  15, -35, -12,  -1,  11,  58,  -5,  16,
-     28,   0,  -1, -33,   0, -11,  39,  -5,  14,  -6,
-     -3, -31, -28,   1,  53,  33,  19, -25, -46, -26,
-    }, {
-    -28,  20,  51,  14,   6,  -7,   0,  26, -27,   4,
-    -18,  40,   6, -16,   1,  15,   0,  55,   5,  16,
-     19, -14,   3, -49, -14,  -1,  22,  30,  12,   0,
-    -24, -15,  -9,  17,  45,  29,  -4, -28, -51, -35,
-    }, {
-     34,   4,  25, -10,  -9, -21,   7,  36,  26,  36,
-     35, -28, -12, -42,   3,  16,  12,  28, -21, -42,
-      5,  21, -16, -26,   4, -19,  19, -39, -15, -15,
-     -1, -13, -19,  17,  17, -14,  15, -55,  -4, -19,
-    }, {
-    -34,  25,  48,  28,  11, -34,   2,  41,  -9,   7,
-     17, -21, -20, -24,  17,  33,   0,  24, -10, -42,
-     -3,   5, -10, -42, -11,  -8,   3,  -3, -16,  -9,
-    -22,   2,   0,  33,  10, -18,  -7, -58, -10, -28,
-    }, {
-     -4,  11,  37, -23,   5, -46,   2,  29,   5,  39,
-     21,   9,   0, -49, -12,   9,  16,  26, -22, -15,
-     45,  20,   5, -40, -22, -17,  26, -31,  14,  -2,
-     14, -10, -30, -20,  27,   9,  39, -39, -18,  -5,
-    }, {
-    -73,  32,  60,  15,  26, -59,  -2,  33, -30,  10,
-      3,  17,  -8, -30,   1,  26,   4,  22, -10, -16,
-     36,   5,  11, -56, -37,  -6,  10,   5,  13,   3,
-     -6,   5, -11,  -4,  19,   5,  16, -41, -24, -13
-    }
-};
-
-static const uint16_t cb1_base[128]={
-    19657, 18474, 18365, 17520, 21048, 18231, 18584, 16671,
-    20363, 19069, 19409, 18430, 21844, 18753, 19613, 17411,
-    20389, 21772, 20129, 21702, 20978, 20472, 19627, 19387,
-    21477, 23134, 21841, 23919, 22089, 21519, 21134, 20852,
-    19675, 17821, 19044, 17477, 19986, 16955, 18446, 16086,
-    21138, 18899, 20952, 18929, 21452, 17833, 20104, 17159,
-    19770, 20056, 20336, 20866, 19329, 18217, 18908, 18004,
-    21556, 21948, 23079, 23889, 20922, 19544, 20984, 19781,
-    19781, 20984, 19544, 20922, 23889, 23079, 21948, 21556,
-    18004, 18908, 18217, 19329, 20866, 20336, 20056, 19770,
-    17159, 20104, 17833, 21452, 18929, 20952, 18899, 21138,
-    16086, 18446, 16955, 19986, 17477, 19044, 17821, 19675,
-    20852, 21134, 21519, 22089, 23919, 21841, 23134, 21477,
-    19387, 19627, 20472, 20978, 21702, 20129, 21772, 20389,
-    17411, 19613, 18753, 21844, 18430, 19409, 19069, 20363,
-    16671, 18584, 18231, 21048, 17520, 18365, 18474, 19657,
-};
-
-static const uint16_t cb2_base[128]={
-    12174, 13380, 13879, 13832, 13170, 13227, 13204, 12053,
-    12410, 13988, 14348, 14631, 13100, 13415, 13224, 12268,
-    11982, 13825, 13499, 14210, 13877, 14788, 13811, 13109,
-    11449, 13275, 12833, 13717, 12728, 13696, 12759, 12405,
-    10230, 12185, 11628, 13161, 11762, 13458, 12312, 12818,
-    10443, 12773, 12011, 14020, 11818, 13825, 12453, 13226,
-    10446, 13162, 11881, 14300, 12859, 16288, 13490, 15053,
-    10155, 12820, 11519, 13973, 12041, 15081, 12635, 14198,
-    14198, 12635, 15081, 12041, 13973, 11519, 12820, 10155,
-    15053, 13490, 16288, 12859, 14300, 11881, 13162, 10446,
-    13226, 12453, 13825, 11818, 14020, 12011, 12773, 10443,
-    12818, 12312, 13458, 11762, 13161, 11628, 12185, 10230,
-    12405, 12759, 13696, 12728, 13717, 12833, 13275, 11449,
-    13109, 13811, 14788, 13877, 14210, 13499, 13825, 11982,
-    12268, 13224, 13415, 13100, 14631, 14348, 13988, 12410,
-    12053, 13204, 13227, 13170, 13832, 13879, 13380, 12174,
-};
-
-static const int16_t energy_tab[32]={
-        0,    16,    20,    25,    32,    41,    51,    65,
-       81,   103,   129,   163,   205,   259,   326,   410,
-      516,   650,   819,  1031,  1298,  1634,  2057,  2590,
-     3261,  4105,  5168,  6507,  8192, 10313, 12983, 16345
-};
-
-static const int16_t lpc_refl_cb1[64]={
-    -4041, -4018, -3998, -3977, -3954, -3930, -3906, -3879,
-    -3852, -3825, -3795, -3764, -3731, -3699, -3666, -3631,
-    -3594, -3555, -3513, -3468, -3420, -3372, -3321, -3268,
-    -3212, -3153, -3090, -3021, -2944, -2863, -2772, -2676,
-    -2565, -2445, -2328, -2202, -2072, -1941, -1808, -1660,
-    -1508, -1348, -1185,  -994,  -798,  -600,  -374,  -110,
-      152,   447,   720,   982,  1229,  1456,  1682,  1916,
-     2130,  2353,  2595,  2853,  3118,  3363,  3588,  3814
-};
-
-static const int16_t lpc_refl_cb2[32]={
-    -3091, -2386, -1871, -1425, -1021,  -649,  -316,   -20,
-      267,   544,   810,  1065,  1305,  1534,  1756,  1970,
-     2171,  2359,  2536,  2700,  2854,  2996,  3133,  3263,
-     3386,  3499,  3603,  3701,  3789,  3870,  3947,  4020
-};
-
-static const int16_t lpc_refl_cb3[32]={
-    -3525, -3295, -3081, -2890, -2696, -2511, -2328, -2149,
-    -1979, -1817, -1658, -1498, -1341, -1188, -1032,  -876,
-     -721,  -561,  -394,  -228,   -54,   119,   296,   484,
-      683,   895,  1123,  1373,  1651,  1965,  2360,  2854
-};
-
-static const int16_t lpc_refl_cb4[16]={
-    -1845, -1057,  -522,   -77,   301,   647,   975,  1285,
-     1582,  1873,  2163,  2452,  2735,  3017,  3299,  3569
-};
-
-static const int16_t lpc_refl_cb5[16]={
-    -2691, -2187, -1788, -1435, -1118,  -837,  -571,  -316,
-      -59,   201,   470,   759,  1077,  1457,  1908,  2495
-};
-
-static const int16_t lpc_refl_cb6[8]={
-    -1372,  -474,   133,   632,  1100,  1571,  2075,  2672
-};
-
-static const int16_t lpc_refl_cb7[8]={
-    -2389, -1787, -1231,  -717,  -239,   234,   770,  1474
-};
-
-static const int16_t lpc_refl_cb8[8]={
-    -1569,  -864,  -296,   200,   670,  1151,  1709,  2385
-};
-
-static const int16_t lpc_refl_cb9[8]={
-    -2200, -1608, -1062,  -569,  -120,   338,   863,  1621
-};
-
-static const int16_t lpc_refl_cb10[4]={
-     -617,   190,   802,  1483
-};
-
-static const int16_t * const lpc_refl_cb[10]={
-    lpc_refl_cb1, lpc_refl_cb2, lpc_refl_cb3, lpc_refl_cb4, lpc_refl_cb5,
-    lpc_refl_cb6, lpc_refl_cb7, lpc_refl_cb8, lpc_refl_cb9, lpc_refl_cb10
-};
+#include "lpc.h"
+
+#define NBLOCKS         4       ///< number of subblocks within a block
+#define BLOCKSIZE       40      ///< subblock size in 16-bit words
+#define BUFFERSIZE      146     ///< the size of the adaptive codebook
+#define FIXED_CB_SIZE   128     ///< size of fixed codebooks
+#define FRAMESIZE       20      ///< size of encoded frame
+#define LPC_ORDER       10      ///< order of LPC filter
+
+typedef struct {
+    AVCodecContext *avctx;
+    LPCContext lpc_ctx;
+
+    unsigned int     old_energy;        ///< previous frame energy
+
+    unsigned int     lpc_tables[2][10];
+
+    /** LPC coefficients: lpc_coef[0] is the coefficients of the current frame
+     *  and lpc_coef[1] of the previous one. */
+    unsigned int    *lpc_coef[2];
+
+    unsigned int     lpc_refl_rms[2];
+
+    int16_t curr_block[NBLOCKS * BLOCKSIZE];
+
+    /** The current subblock padded by the last 10 values of the previous one. */
+    int16_t curr_sblock[50];
+
+    /** Adaptive codebook, its size is two units bigger to avoid a
+     *  buffer overflow. */
+    uint16_t adapt_cb[146+2];
+} RA144Context;
+
+void ff_copy_and_dup(int16_t *target, const int16_t *source, int offset);
+int ff_eval_refl(int *refl, const int16_t *coefs, AVCodecContext *avctx);
+void ff_eval_coefs(int *coefs, const int *refl);
+void ff_int_to_int16(int16_t *out, const int *inp);
+int ff_t_sqrt(unsigned int x);
+unsigned int ff_rms(const int *data);
+int ff_interp(RA144Context *ractx, int16_t *out, int a, int copyold,
+              int energy);
+unsigned int ff_rescale_rms(unsigned int rms, unsigned int energy);
+int ff_irms(const int16_t *data);
+void ff_subblock_synthesis(RA144Context *ractx, const uint16_t *lpc_coefs,
+                           int cba_idx, int cb1_idx, int cb2_idx,
+                           int gval, int gain);
+
+extern const int16_t ff_gain_val_tab[256][3];
+extern const uint8_t ff_gain_exp_tab[256];
+extern const int8_t ff_cb1_vects[128][40];
+extern const int8_t ff_cb2_vects[128][40];
+extern const uint16_t ff_cb1_base[128];
+extern const uint16_t ff_cb2_base[128];
+extern const int16_t ff_energy_tab[32];
+extern const int16_t * const ff_lpc_refl_cb[10];
 
 #endif /* AVCODEC_RA144_H */
diff --git a/libavcodec/ra144dec.c b/libavcodec/ra144dec.c
new file mode 100644
index 0000000..e64b6c2
--- /dev/null
+++ b/libavcodec/ra144dec.c
@@ -0,0 +1,128 @@
+/*
+ * Real Audio 1.0 (14.4K)
+ *
+ * Copyright (c) 2008 Vitor Sessak
+ * Copyright (c) 2003 Nick Kurshev
+ *     Based on public domain decoder at http://www.honeypot.net/audio
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "libavutil/intmath.h"
+#include "avcodec.h"
+#include "get_bits.h"
+#include "ra144.h"
+
+
+static av_cold int ra144_decode_init(AVCodecContext * avctx)
+{
+    RA144Context *ractx = avctx->priv_data;
+
+    ractx->avctx = avctx;
+
+    ractx->lpc_coef[0] = ractx->lpc_tables[0];
+    ractx->lpc_coef[1] = ractx->lpc_tables[1];
+
+    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
+    return 0;
+}
+
+static void do_output_subblock(RA144Context *ractx, const uint16_t  *lpc_coefs,
+                               int gval, GetBitContext *gb)
+{
+    int cba_idx = get_bits(gb, 7); // index of the adaptive CB, 0 if none
+    int gain    = get_bits(gb, 8);
+    int cb1_idx = get_bits(gb, 7);
+    int cb2_idx = get_bits(gb, 7);
+
+    ff_subblock_synthesis(ractx, lpc_coefs, cba_idx, cb1_idx, cb2_idx, gval,
+                          gain);
+}
+
+/** Uncompress one block (20 bytes -> 160*2 bytes). */
+static int ra144_decode_frame(AVCodecContext * avctx, void *vdata,
+                              int *data_size, AVPacket *avpkt)
+{
+    const uint8_t *buf = avpkt->data;
+    int buf_size = avpkt->size;
+    static const uint8_t sizes[10] = {6, 5, 5, 4, 4, 3, 3, 3, 3, 2};
+    unsigned int refl_rms[4];    // RMS of the reflection coefficients
+    uint16_t block_coefs[4][10]; // LPC coefficients of each sub-block
+    unsigned int lpc_refl[10];   // LPC reflection coefficients of the frame
+    int i, j;
+    int16_t *data = vdata;
+    unsigned int energy;
+
+    RA144Context *ractx = avctx->priv_data;
+    GetBitContext gb;
+
+    if (*data_size < 2*160)
+        return -1;
+
+    if(buf_size < 20) {
+        av_log(avctx, AV_LOG_ERROR,
+               "Frame too small (%d bytes). Truncated file?\n", buf_size);
+        *data_size = 0;
+        return buf_size;
+    }
+    init_get_bits(&gb, buf, 20 * 8);
+
+    for (i=0; i<10; i++)
+        lpc_refl[i] = ff_lpc_refl_cb[i][get_bits(&gb, sizes[i])];
+
+    ff_eval_coefs(ractx->lpc_coef[0], lpc_refl);
+    ractx->lpc_refl_rms[0] = ff_rms(lpc_refl);
+
+    energy = ff_energy_tab[get_bits(&gb, 5)];
+
+    refl_rms[0] = ff_interp(ractx, block_coefs[0], 1, 1, ractx->old_energy);
+    refl_rms[1] = ff_interp(ractx, block_coefs[1], 2,
+                            energy <= ractx->old_energy,
+                            ff_t_sqrt(energy*ractx->old_energy) >> 12);
+    refl_rms[2] = ff_interp(ractx, block_coefs[2], 3, 0, energy);
+    refl_rms[3] = ff_rescale_rms(ractx->lpc_refl_rms[0], energy);
+
+    ff_int_to_int16(block_coefs[3], ractx->lpc_coef[0]);
+
+    for (i=0; i < 4; i++) {
+        do_output_subblock(ractx, block_coefs[i], refl_rms[i], &gb);
+
+        for (j=0; j < BLOCKSIZE; j++)
+            *data++ = av_clip_int16(ractx->curr_sblock[j + 10] << 2);
+    }
+
+    ractx->old_energy = energy;
+    ractx->lpc_refl_rms[1] = ractx->lpc_refl_rms[0];
+
+    FFSWAP(unsigned int *, ractx->lpc_coef[0], ractx->lpc_coef[1]);
+
+    *data_size = 2*160;
+    return 20;
+}
+
+AVCodec ff_ra_144_decoder =
+{
+    "real_144",
+    AVMEDIA_TYPE_AUDIO,
+    CODEC_ID_RA_144,
+    sizeof(RA144Context),
+    ra144_decode_init,
+    NULL,
+    NULL,
+    ra144_decode_frame,
+    .long_name = NULL_IF_CONFIG_SMALL("RealAudio 1.0 (14.4K)"),
+};
diff --git a/libavcodec/ra144enc.c b/libavcodec/ra144enc.c
new file mode 100644
index 0000000..24ba934
--- /dev/null
+++ b/libavcodec/ra144enc.c
@@ -0,0 +1,521 @@
+/*
+ * Real Audio 1.0 (14.4K) encoder
+ * Copyright (c) 2010 Francesco Lavra <francescolavra at interfree.it>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * Real Audio 1.0 (14.4K) encoder
+ * @author Francesco Lavra <francescolavra at interfree.it>
+ */
+
+#include <float.h>
+
+#include "avcodec.h"
+#include "put_bits.h"
+#include "celp_filters.h"
+#include "ra144.h"
+
+
+static av_cold int ra144_encode_init(AVCodecContext * avctx)
+{
+    RA144Context *ractx;
+    int ret;
+
+    if (avctx->sample_fmt != AV_SAMPLE_FMT_S16) {
+        av_log(avctx, AV_LOG_ERROR, "invalid sample format\n");
+        return -1;
+    }
+    if (avctx->channels != 1) {
+        av_log(avctx, AV_LOG_ERROR, "invalid number of channels: %d\n",
+               avctx->channels);
+        return -1;
+    }
+    avctx->frame_size = NBLOCKS * BLOCKSIZE;
+    avctx->bit_rate = 8000;
+    ractx = avctx->priv_data;
+    ractx->lpc_coef[0] = ractx->lpc_tables[0];
+    ractx->lpc_coef[1] = ractx->lpc_tables[1];
+    ractx->avctx = avctx;
+    ret = ff_lpc_init(&ractx->lpc_ctx, avctx->frame_size, LPC_ORDER,
+                      AV_LPC_TYPE_LEVINSON);
+    return ret;
+}
+
+
+static av_cold int ra144_encode_close(AVCodecContext *avctx)
+{
+    RA144Context *ractx = avctx->priv_data;
+    ff_lpc_end(&ractx->lpc_ctx);
+    return 0;
+}
+
+
+/**
+ * Quantize a value by searching a sorted table for the element with the
+ * nearest value
+ *
+ * @param value value to quantize
+ * @param table array containing the quantization table
+ * @param size size of the quantization table
+ * @return index of the quantization table corresponding to the element with the
+ *         nearest value
+ */
+static int quantize(int value, const int16_t *table, unsigned int size)
+{
+    unsigned int low = 0, high = size - 1;
+
+    while (1) {
+        int index = (low + high) >> 1;
+        int error = table[index] - value;
+
+        if (index == low)
+            return table[high] + error > value ? low : high;
+        if (error > 0) {
+            high = index;
+        } else {
+            low = index;
+        }
+    }
+}
+
+
+/**
+ * Orthogonalize a vector to another vector
+ *
+ * @param v vector to orthogonalize
+ * @param u vector against which orthogonalization is performed
+ */
+static void orthogonalize(float *v, const float *u)
+{
+    int i;
+    float num = 0, den = 0;
+
+    for (i = 0; i < BLOCKSIZE; i++) {
+        num += v[i] * u[i];
+        den += u[i] * u[i];
+    }
+    num /= den;
+    for (i = 0; i < BLOCKSIZE; i++)
+        v[i] -= num * u[i];
+}
+
+
+/**
+ * Calculate match score and gain of an LPC-filtered vector with respect to
+ * input data, possibly othogonalizing it to up to 2 other vectors
+ *
+ * @param work array used to calculate the filtered vector
+ * @param coefs coefficients of the LPC filter
+ * @param vect original vector
+ * @param ortho1 first vector against which orthogonalization is performed
+ * @param ortho2 second vector against which orthogonalization is performed
+ * @param data input data
+ * @param score pointer to variable where match score is returned
+ * @param gain pointer to variable where gain is returned
+ */
+static void get_match_score(float *work, const float *coefs, float *vect,
+                            const float *ortho1, const float *ortho2,
+                            const float *data, float *score, float *gain)
+{
+    float c, g;
+    int i;
+
+    ff_celp_lp_synthesis_filterf(work, coefs, vect, BLOCKSIZE, LPC_ORDER);
+    if (ortho1)
+        orthogonalize(work, ortho1);
+    if (ortho2)
+        orthogonalize(work, ortho2);
+    c = g = 0;
+    for (i = 0; i < BLOCKSIZE; i++) {
+        g += work[i] * work[i];
+        c += data[i] * work[i];
+    }
+    if (c <= 0) {
+        *score = 0;
+        return;
+    }
+    *gain = c / g;
+    *score = *gain * c;
+}
+
+
+/**
+ * Create a vector from the adaptive codebook at a given lag value
+ *
+ * @param vect array where vector is stored
+ * @param cb adaptive codebook
+ * @param lag lag value
+ */
+static void create_adapt_vect(float *vect, const int16_t *cb, int lag)
+{
+    int i;
+
+    cb += BUFFERSIZE - lag;
+    for (i = 0; i < FFMIN(BLOCKSIZE, lag); i++)
+        vect[i] = cb[i];
+    if (lag < BLOCKSIZE)
+        for (i = 0; i < BLOCKSIZE - lag; i++)
+            vect[lag + i] = cb[i];
+}
+
+
+/**
+ * Search the adaptive codebook for the best entry and gain and remove its
+ * contribution from input data
+ *
+ * @param adapt_cb array from which the adaptive codebook is extracted
+ * @param work array used to calculate LPC-filtered vectors
+ * @param coefs coefficients of the LPC filter
+ * @param data input data
+ * @return index of the best entry of the adaptive codebook
+ */
+static int adaptive_cb_search(const int16_t *adapt_cb, float *work,
+                              const float *coefs, float *data)
+{
+    int i, best_vect;
+    float score, gain, best_score, best_gain;
+    float exc[BLOCKSIZE];
+
+    gain = best_score = 0;
+    for (i = BLOCKSIZE / 2; i <= BUFFERSIZE; i++) {
+        create_adapt_vect(exc, adapt_cb, i);
+        get_match_score(work, coefs, exc, NULL, NULL, data, &score, &gain);
+        if (score > best_score) {
+            best_score = score;
+            best_vect = i;
+            best_gain = gain;
+        }
+    }
+    if (!best_score)
+        return 0;
+
+    /**
+     * Re-calculate the filtered vector from the vector with maximum match score
+     * and remove its contribution from input data.
+     */
+    create_adapt_vect(exc, adapt_cb, best_vect);
+    ff_celp_lp_synthesis_filterf(work, coefs, exc, BLOCKSIZE, LPC_ORDER);
+    for (i = 0; i < BLOCKSIZE; i++)
+        data[i] -= best_gain * work[i];
+    return (best_vect - BLOCKSIZE / 2 + 1);
+}
+
+
+/**
+ * Find the best vector of a fixed codebook by applying an LPC filter to
+ * codebook entries, possibly othogonalizing them to up to 2 other vectors and
+ * matching the results with input data
+ *
+ * @param work array used to calculate the filtered vectors
+ * @param coefs coefficients of the LPC filter
+ * @param cb fixed codebook
+ * @param ortho1 first vector against which orthogonalization is performed
+ * @param ortho2 second vector against which orthogonalization is performed
+ * @param data input data
+ * @param idx pointer to variable where the index of the best codebook entry is
+ *        returned
+ * @param gain pointer to variable where the gain of the best codebook entry is
+ *        returned
+ */
+static void find_best_vect(float *work, const float *coefs,
+                           const int8_t cb[][BLOCKSIZE], const float *ortho1,
+                           const float *ortho2, float *data, int *idx,
+                           float *gain)
+{
+    int i, j;
+    float g, score, best_score;
+    float vect[BLOCKSIZE];
+
+    *idx = *gain = best_score = 0;
+    for (i = 0; i < FIXED_CB_SIZE; i++) {
+        for (j = 0; j < BLOCKSIZE; j++)
+            vect[j] = cb[i][j];
+        get_match_score(work, coefs, vect, ortho1, ortho2, data, &score, &g);
+        if (score > best_score) {
+            best_score = score;
+            *idx = i;
+            *gain = g;
+        }
+    }
+}
+
+
+/**
+ * Search the two fixed codebooks for the best entry and gain
+ *
+ * @param work array used to calculate LPC-filtered vectors
+ * @param coefs coefficients of the LPC filter
+ * @param data input data
+ * @param cba_idx index of the best entry of the adaptive codebook
+ * @param cb1_idx pointer to variable where the index of the best entry of the
+ *        first fixed codebook is returned
+ * @param cb2_idx pointer to variable where the index of the best entry of the
+ *        second fixed codebook is returned
+ */
+static void fixed_cb_search(float *work, const float *coefs, float *data,
+                            int cba_idx, int *cb1_idx, int *cb2_idx)
+{
+    int i, ortho_cb1;
+    float gain;
+    float cba_vect[BLOCKSIZE], cb1_vect[BLOCKSIZE];
+    float vect[BLOCKSIZE];
+
+    /**
+     * The filtered vector from the adaptive codebook can be retrieved from
+     * work, because this function is called just after adaptive_cb_search().
+     */
+    if (cba_idx)
+        memcpy(cba_vect, work, sizeof(cba_vect));
+
+    find_best_vect(work, coefs, ff_cb1_vects, cba_idx ? cba_vect : NULL, NULL,
+                   data, cb1_idx, &gain);
+
+    /**
+     * Re-calculate the filtered vector from the vector with maximum match score
+     * and remove its contribution from input data.
+     */
+    if (gain) {
+        for (i = 0; i < BLOCKSIZE; i++)
+            vect[i] = ff_cb1_vects[*cb1_idx][i];
+        ff_celp_lp_synthesis_filterf(work, coefs, vect, BLOCKSIZE, LPC_ORDER);
+        if (cba_idx)
+            orthogonalize(work, cba_vect);
+        for (i = 0; i < BLOCKSIZE; i++)
+            data[i] -= gain * work[i];
+        memcpy(cb1_vect, work, sizeof(cb1_vect));
+        ortho_cb1 = 1;
+    } else
+        ortho_cb1 = 0;
+
+    find_best_vect(work, coefs, ff_cb2_vects, cba_idx ? cba_vect : NULL,
+                   ortho_cb1 ? cb1_vect : NULL, data, cb2_idx, &gain);
+}
+
+
+/**
+ * Encode a subblock of the current frame
+ *
+ * @param ractx encoder context
+ * @param sblock_data input data of the subblock
+ * @param lpc_coefs coefficients of the LPC filter
+ * @param rms RMS of the reflection coefficients
+ * @param pb pointer to PutBitContext of the current frame
+ */
+static void ra144_encode_subblock(RA144Context *ractx,
+                                  const int16_t *sblock_data,
+                                  const int16_t *lpc_coefs, unsigned int rms,
+                                  PutBitContext *pb)
+{
+    float data[BLOCKSIZE], work[LPC_ORDER + BLOCKSIZE];
+    float coefs[LPC_ORDER];
+    float zero[BLOCKSIZE], cba[BLOCKSIZE], cb1[BLOCKSIZE], cb2[BLOCKSIZE];
+    int16_t cba_vect[BLOCKSIZE];
+    int cba_idx, cb1_idx, cb2_idx, gain;
+    int i, n, m[3];
+    float g[3];
+    float error, best_error;
+
+    for (i = 0; i < LPC_ORDER; i++) {
+        work[i] = ractx->curr_sblock[BLOCKSIZE + i];
+        coefs[i] = lpc_coefs[i] * (1/4096.0);
+    }
+
+    /**
+     * Calculate the zero-input response of the LPC filter and subtract it from
+     * input data.
+     */
+    memset(data, 0, sizeof(data));
+    ff_celp_lp_synthesis_filterf(work + LPC_ORDER, coefs, data, BLOCKSIZE,
+                                 LPC_ORDER);
+    for (i = 0; i < BLOCKSIZE; i++) {
+        zero[i] = work[LPC_ORDER + i];
+        data[i] = sblock_data[i] - zero[i];
+    }
+
+    /**
+     * Codebook search is performed without taking into account the contribution
+     * of the previous subblock, since it has been just subtracted from input
+     * data.
+     */
+    memset(work, 0, LPC_ORDER * sizeof(*work));
+
+    cba_idx = adaptive_cb_search(ractx->adapt_cb, work + LPC_ORDER, coefs,
+                                 data);
+    if (cba_idx) {
+        /**
+         * The filtered vector from the adaptive codebook can be retrieved from
+         * work, see implementation of adaptive_cb_search().
+         */
+        memcpy(cba, work + LPC_ORDER, sizeof(cba));
+
+        ff_copy_and_dup(cba_vect, ractx->adapt_cb, cba_idx + BLOCKSIZE / 2 - 1);
+        m[0] = (ff_irms(cba_vect) * rms) >> 12;
+    }
+    fixed_cb_search(work + LPC_ORDER, coefs, data, cba_idx, &cb1_idx, &cb2_idx);
+    for (i = 0; i < BLOCKSIZE; i++) {
+        cb1[i] = ff_cb1_vects[cb1_idx][i];
+        cb2[i] = ff_cb2_vects[cb2_idx][i];
+    }
+    ff_celp_lp_synthesis_filterf(work + LPC_ORDER, coefs, cb1, BLOCKSIZE,
+                                 LPC_ORDER);
+    memcpy(cb1, work + LPC_ORDER, sizeof(cb1));
+    m[1] = (ff_cb1_base[cb1_idx] * rms) >> 8;
+    ff_celp_lp_synthesis_filterf(work + LPC_ORDER, coefs, cb2, BLOCKSIZE,
+                                 LPC_ORDER);
+    memcpy(cb2, work + LPC_ORDER, sizeof(cb2));
+    m[2] = (ff_cb2_base[cb2_idx] * rms) >> 8;
+    best_error = FLT_MAX;
+    gain = 0;
+    for (n = 0; n < 256; n++) {
+        g[1] = ((ff_gain_val_tab[n][1] * m[1]) >> ff_gain_exp_tab[n]) *
+               (1/4096.0);
+        g[2] = ((ff_gain_val_tab[n][2] * m[2]) >> ff_gain_exp_tab[n]) *
+               (1/4096.0);
+        error = 0;
+        if (cba_idx) {
+            g[0] = ((ff_gain_val_tab[n][0] * m[0]) >> ff_gain_exp_tab[n]) *
+                   (1/4096.0);
+            for (i = 0; i < BLOCKSIZE; i++) {
+                data[i] = zero[i] + g[0] * cba[i] + g[1] * cb1[i] +
+                          g[2] * cb2[i];
+                error += (data[i] - sblock_data[i]) *
+                         (data[i] - sblock_data[i]);
+            }
+        } else {
+            for (i = 0; i < BLOCKSIZE; i++) {
+                data[i] = zero[i] + g[1] * cb1[i] + g[2] * cb2[i];
+                error += (data[i] - sblock_data[i]) *
+                         (data[i] - sblock_data[i]);
+            }
+        }
+        if (error < best_error) {
+            best_error = error;
+            gain = n;
+        }
+    }
+    put_bits(pb, 7, cba_idx);
+    put_bits(pb, 8, gain);
+    put_bits(pb, 7, cb1_idx);
+    put_bits(pb, 7, cb2_idx);
+    ff_subblock_synthesis(ractx, lpc_coefs, cba_idx, cb1_idx, cb2_idx, rms,
+                          gain);
+}
+
+
+static int ra144_encode_frame(AVCodecContext *avctx, uint8_t *frame,
+                              int buf_size, void *data)
+{
+    static const uint8_t sizes[LPC_ORDER] = {64, 32, 32, 16, 16, 8, 8, 8, 8, 4};
+    static const uint8_t bit_sizes[LPC_ORDER] = {6, 5, 5, 4, 4, 3, 3, 3, 3, 2};
+    RA144Context *ractx;
+    PutBitContext pb;
+    int32_t lpc_data[NBLOCKS * BLOCKSIZE];
+    int32_t lpc_coefs[LPC_ORDER][MAX_LPC_ORDER];
+    int shift[LPC_ORDER];
+    int16_t block_coefs[NBLOCKS][LPC_ORDER];
+    int lpc_refl[LPC_ORDER];    /**< reflection coefficients of the frame */
+    unsigned int refl_rms[NBLOCKS]; /**< RMS of the reflection coefficients */
+    int energy = 0;
+    int i, idx;
+
+    if (buf_size < FRAMESIZE) {
+        av_log(avctx, AV_LOG_ERROR, "output buffer too small\n");
+        return 0;
+    }
+    ractx = avctx->priv_data;
+
+    /**
+     * Since the LPC coefficients are calculated on a frame centered over the
+     * fourth subframe, to encode a given frame, data from the next frame is
+     * needed. In each call to this function, the previous frame (whose data are
+     * saved in the encoder context) is encoded, and data from the current frame
+     * are saved in the encoder context to be used in the next function call.
+     */
+    for (i = 0; i < (2 * BLOCKSIZE + BLOCKSIZE / 2); i++) {
+        lpc_data[i] = ractx->curr_block[BLOCKSIZE + BLOCKSIZE / 2 + i];
+        energy += (lpc_data[i] * lpc_data[i]) >> 4;
+    }
+    for (i = 2 * BLOCKSIZE + BLOCKSIZE / 2; i < NBLOCKS * BLOCKSIZE; i++) {
+        lpc_data[i] = *((int16_t *)data + i - 2 * BLOCKSIZE - BLOCKSIZE / 2) >>
+                      2;
+        energy += (lpc_data[i] * lpc_data[i]) >> 4;
+    }
+    energy = ff_energy_tab[quantize(ff_t_sqrt(energy >> 5) >> 10, ff_energy_tab,
+                                    32)];
+
+    ff_lpc_calc_coefs(&ractx->lpc_ctx, lpc_data, NBLOCKS * BLOCKSIZE, LPC_ORDER,
+                      LPC_ORDER, 16, lpc_coefs, shift, AV_LPC_TYPE_LEVINSON,
+                      0, ORDER_METHOD_EST, 12, 0);
+    for (i = 0; i < LPC_ORDER; i++)
+        block_coefs[NBLOCKS - 1][i] = -(lpc_coefs[LPC_ORDER - 1][i] <<
+                                        (12 - shift[LPC_ORDER - 1]));
+
+    /**
+     * TODO: apply perceptual weighting of the input speech through bandwidth
+     * expansion of the LPC filter.
+     */
+
+    if (ff_eval_refl(lpc_refl, block_coefs[NBLOCKS - 1], avctx)) {
+        /**
+         * The filter is unstable: use the coefficients of the previous frame.
+         */
+        ff_int_to_int16(block_coefs[NBLOCKS - 1], ractx->lpc_coef[1]);
+        ff_eval_refl(lpc_refl, block_coefs[NBLOCKS - 1], avctx);
+    }
+    init_put_bits(&pb, frame, buf_size);
+    for (i = 0; i < LPC_ORDER; i++) {
+        idx = quantize(lpc_refl[i], ff_lpc_refl_cb[i], sizes[i]);
+        put_bits(&pb, bit_sizes[i], idx);
+        lpc_refl[i] = ff_lpc_refl_cb[i][idx];
+    }
+    ractx->lpc_refl_rms[0] = ff_rms(lpc_refl);
+    ff_eval_coefs(ractx->lpc_coef[0], lpc_refl);
+    refl_rms[0] = ff_interp(ractx, block_coefs[0], 1, 1, ractx->old_energy);
+    refl_rms[1] = ff_interp(ractx, block_coefs[1], 2,
+                            energy <= ractx->old_energy,
+                            ff_t_sqrt(energy * ractx->old_energy) >> 12);
+    refl_rms[2] = ff_interp(ractx, block_coefs[2], 3, 0, energy);
+    refl_rms[3] = ff_rescale_rms(ractx->lpc_refl_rms[0], energy);
+    ff_int_to_int16(block_coefs[NBLOCKS - 1], ractx->lpc_coef[0]);
+    put_bits(&pb, 5, quantize(energy, ff_energy_tab, 32));
+    for (i = 0; i < NBLOCKS; i++)
+        ra144_encode_subblock(ractx, ractx->curr_block + i * BLOCKSIZE,
+                              block_coefs[i], refl_rms[i], &pb);
+    flush_put_bits(&pb);
+    ractx->old_energy = energy;
+    ractx->lpc_refl_rms[1] = ractx->lpc_refl_rms[0];
+    FFSWAP(unsigned int *, ractx->lpc_coef[0], ractx->lpc_coef[1]);
+    for (i = 0; i < NBLOCKS * BLOCKSIZE; i++)
+        ractx->curr_block[i] = *((int16_t *)data + i) >> 2;
+    return FRAMESIZE;
+}
+
+
+AVCodec ff_ra_144_encoder =
+{
+    "real_144",
+    AVMEDIA_TYPE_AUDIO,
+    CODEC_ID_RA_144,
+    sizeof(RA144Context),
+    ra144_encode_init,
+    ra144_encode_frame,
+    ra144_encode_close,
+    .long_name = NULL_IF_CONFIG_SMALL("RealAudio 1.0 (14.4K) encoder"),
+};
diff --git a/libavcodec/ra288.c b/libavcodec/ra288.c
index 20a21f5..64d765c 100644
--- a/libavcodec/ra288.c
+++ b/libavcodec/ra288.c
@@ -2,20 +2,20 @@
  * RealAudio 2.0 (28.8K)
  * Copyright (c) 2003 the ffmpeg project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -27,6 +27,10 @@
 #include "celp_math.h"
 #include "celp_filters.h"
 
+#define MAX_BACKWARD_FILTER_ORDER  36
+#define MAX_BACKWARD_FILTER_LEN    40
+#define MAX_BACKWARD_FILTER_NONREC 35
+
 typedef struct {
     float sp_lpc[36];      ///< LPC coefficients for speech data (spec: A)
     float gain_lpc[10];    ///< LPC coefficients for gain        (spec: GB)
@@ -50,7 +54,7 @@ typedef struct {
 
 static av_cold int ra288_decode_init(AVCodecContext *avctx)
 {
-    avctx->sample_fmt = SAMPLE_FMT_FLT;
+    avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
     return 0;
 }
 
@@ -120,9 +124,9 @@ static void do_hybrid_window(int order, int n, int non_rec, float *out,
                              float *hist, float *out2, const float *window)
 {
     int i;
-    float buffer1[order + 1];
-    float buffer2[order + 1];
-    float work[order + n + non_rec];
+    float buffer1[MAX_BACKWARD_FILTER_ORDER + 1];
+    float buffer2[MAX_BACKWARD_FILTER_ORDER + 1];
+    float work[MAX_BACKWARD_FILTER_ORDER + MAX_BACKWARD_FILTER_LEN + MAX_BACKWARD_FILTER_NONREC];
 
     apply_window(work, window, hist, order + n + non_rec);
 
@@ -145,7 +149,7 @@ static void backward_filter(float *hist, float *rec, const float *window,
                             float *lpc, const float *tab,
                             int order, int n, int non_rec, int move_size)
 {
-    float temp[order+1];
+    float temp[MAX_BACKWARD_FILTER_ORDER+1];
 
     do_hybrid_window(order, n, non_rec, temp, hist, rec, window);
 
@@ -199,7 +203,7 @@ static int ra288_decode_frame(AVCodecContext * avctx, void *data,
     return avctx->block_align;
 }
 
-AVCodec ra_288_decoder =
+AVCodec ff_ra_288_decoder =
 {
     "real_288",
     AVMEDIA_TYPE_AUDIO,
diff --git a/libavcodec/ra288.h b/libavcodec/ra288.h
index d7fd4b5..8857f40 100644
--- a/libavcodec/ra288.h
+++ b/libavcodec/ra288.h
@@ -2,20 +2,20 @@
  * RealAudio 2.0 (28.8K)
  * Copyright (c) 2003 the ffmpeg project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/rangecoder.c b/libavcodec/rangecoder.c
index 04c2738..1cd6762 100644
--- a/libavcodec/rangecoder.c
+++ b/libavcodec/rangecoder.c
@@ -2,20 +2,20 @@
  * Range coder
  * Copyright (c) 2004 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/rangecoder.h b/libavcodec/rangecoder.h
index 47c0362..7ad1bd2 100644
--- a/libavcodec/rangecoder.h
+++ b/libavcodec/rangecoder.h
@@ -2,20 +2,20 @@
  * Range coder
  * Copyright (c) 2004 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/ratecontrol.c b/libavcodec/ratecontrol.c
index e52ef1a..380e354 100644
--- a/libavcodec/ratecontrol.c
+++ b/libavcodec/ratecontrol.c
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -30,7 +30,7 @@
 #include "dsputil.h"
 #include "ratecontrol.h"
 #include "mpegvideo.h"
-#include "eval.h"
+#include "libavutil/eval.h"
 
 #undef NDEBUG // Always check asserts, the speed effect is far too small to disable them.
 #include <assert.h>
@@ -66,8 +66,7 @@ static inline double bits2qp(RateControlEntry *rce, double bits){
 int ff_rate_control_init(MpegEncContext *s)
 {
     RateControlContext *rcc= &s->rc_context;
-    int i;
-    const char *error = NULL;
+    int i, res;
     static const char * const const_names[]={
         "PI",
         "E",
@@ -107,10 +106,10 @@ int ff_rate_control_init(MpegEncContext *s)
     };
     emms_c();
 
-    rcc->rc_eq_eval = ff_parse_expr(s->avctx->rc_eq ? s->avctx->rc_eq : "tex^qComp", const_names, func1, func1_names, NULL, NULL, &error);
-    if (!rcc->rc_eq_eval) {
-        av_log(s->avctx, AV_LOG_ERROR, "Error parsing rc_eq \"%s\": %s\n", s->avctx->rc_eq, error? error : "");
-        return -1;
+    res = av_expr_parse(&rcc->rc_eq_eval, s->avctx->rc_eq ? s->avctx->rc_eq : "tex^qComp", const_names, func1_names, func1, NULL, NULL, 0, s->avctx);
+    if (res < 0) {
+        av_log(s->avctx, AV_LOG_ERROR, "Error parsing rc_eq \"%s\"\n", s->avctx->rc_eq);
+        return res;
     }
 
     for(i=0; i<5; i++){
@@ -255,7 +254,7 @@ void ff_rate_control_uninit(MpegEncContext *s)
     RateControlContext *rcc= &s->rc_context;
     emms_c();
 
-    ff_free_expr(rcc->rc_eq_eval);
+    av_expr_free(rcc->rc_eq_eval);
     av_freep(&rcc->entry);
 
 #if CONFIG_LIBXVID
@@ -339,7 +338,7 @@ static double get_qscale(MpegEncContext *s, RateControlEntry *rce, double rate_f
         0
     };
 
-    bits= ff_eval_expr(rcc->rc_eq_eval, const_values, rce);
+    bits = av_expr_eval(rcc->rc_eq_eval, const_values, rce);
     if (isnan(bits)) {
         av_log(s->avctx, AV_LOG_ERROR, "Error evaluating rc_eq \"%s\"\n", s->avctx->rc_eq);
         return -1;
diff --git a/libavcodec/ratecontrol.h b/libavcodec/ratecontrol.h
index d5fe2bc..6cd4a18 100644
--- a/libavcodec/ratecontrol.h
+++ b/libavcodec/ratecontrol.h
@@ -3,20 +3,20 @@
  * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
  * Copyright (c) 2002-2004 Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -30,7 +30,7 @@
 
 #include <stdio.h>
 #include <stdint.h>
-#include "eval.h"
+#include "libavutil/eval.h"
 
 typedef struct Predictor{
     double coeff;
diff --git a/libavcodec/raw.c b/libavcodec/raw.c
index c2ce3bc..c2a060b 100644
--- a/libavcodec/raw.c
+++ b/libavcodec/raw.c
@@ -2,20 +2,20 @@
  * Raw Video Codec
  * Copyright (c) 2001 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -27,7 +27,7 @@
 #include "avcodec.h"
 #include "raw.h"
 
-const PixelFormatTag ff_raw_pixelFormatTags[] = {
+const PixelFormatTag ff_raw_pix_fmt_tags[] = {
     { PIX_FMT_YUV420P, MKTAG('I', '4', '2', '0') }, /* Planar formats */
     { PIX_FMT_YUV420P, MKTAG('I', 'Y', 'U', 'V') },
     { PIX_FMT_YUV420P, MKTAG('Y', 'V', '1', '2') },
@@ -36,9 +36,15 @@ const PixelFormatTag ff_raw_pixelFormatTags[] = {
     { PIX_FMT_YUV411P, MKTAG('Y', '4', '1', 'B') },
     { PIX_FMT_YUV422P, MKTAG('Y', '4', '2', 'B') },
     { PIX_FMT_YUV422P, MKTAG('P', '4', '2', '2') },
-    { PIX_FMT_GRAY8,   MKTAG('Y', '8', '0', '0') },
-    { PIX_FMT_GRAY8,   MKTAG(' ', ' ', 'Y', '8') },
-
+    /* yuvjXXX formats are deprecated hacks specific to libav*,
+       they are identical to yuvXXX  */
+    { PIX_FMT_YUVJ420P, MKTAG('I', '4', '2', '0') }, /* Planar formats */
+    { PIX_FMT_YUVJ420P, MKTAG('I', 'Y', 'U', 'V') },
+    { PIX_FMT_YUVJ420P, MKTAG('Y', 'V', '1', '2') },
+    { PIX_FMT_YUVJ422P, MKTAG('Y', '4', '2', 'B') },
+    { PIX_FMT_YUVJ422P, MKTAG('P', '4', '2', '2') },
+    { PIX_FMT_GRAY8,    MKTAG('Y', '8', '0', '0') },
+    { PIX_FMT_GRAY8,    MKTAG(' ', ' ', 'Y', '8') },
 
     { PIX_FMT_YUYV422, MKTAG('Y', 'U', 'Y', '2') }, /* Packed formats */
     { PIX_FMT_YUYV422, MKTAG('Y', '4', '2', '2') },
@@ -55,12 +61,57 @@ const PixelFormatTag ff_raw_pixelFormatTags[] = {
     { PIX_FMT_UYVY422, MKTAG('A', 'V', '1', 'x') }, /* Avid 1:1x */
     { PIX_FMT_UYVY422, MKTAG('A', 'V', 'u', 'p') },
     { PIX_FMT_UYVY422, MKTAG('V', 'D', 'T', 'Z') }, /* SoftLab-NSK VideoTizer */
+    { PIX_FMT_UYYVYY411, MKTAG('Y', '4', '1', '1') },
     { PIX_FMT_GRAY8,   MKTAG('G', 'R', 'E', 'Y') },
+    { PIX_FMT_NV12,    MKTAG('N', 'V', '1', '2') },
+    { PIX_FMT_NV21,    MKTAG('N', 'V', '2', '1') },
+
+    /* nut */
     { PIX_FMT_RGB555LE, MKTAG('R', 'G', 'B', 15) },
     { PIX_FMT_BGR555LE, MKTAG('B', 'G', 'R', 15) },
     { PIX_FMT_RGB565LE, MKTAG('R', 'G', 'B', 16) },
     { PIX_FMT_BGR565LE, MKTAG('B', 'G', 'R', 16) },
-    { PIX_FMT_RGB565LE, MKTAG( 3 ,  0 ,  0 ,  0) },
+    { PIX_FMT_RGB555BE, MKTAG(15 , 'B', 'G', 'R') },
+    { PIX_FMT_BGR555BE, MKTAG(15 , 'R', 'G', 'B') },
+    { PIX_FMT_RGB565BE, MKTAG(16 , 'B', 'G', 'R') },
+    { PIX_FMT_BGR565BE, MKTAG(16 , 'R', 'G', 'B') },
+    { PIX_FMT_RGB444LE, MKTAG('R', 'G', 'B', 12) },
+    { PIX_FMT_BGR444LE, MKTAG('B', 'G', 'R', 12) },
+    { PIX_FMT_RGB444BE, MKTAG(12 , 'B', 'G', 'R') },
+    { PIX_FMT_BGR444BE, MKTAG(12 , 'R', 'G', 'B') },
+    { PIX_FMT_RGBA,     MKTAG('R', 'G', 'B', 'A') },
+    { PIX_FMT_BGRA,     MKTAG('B', 'G', 'R', 'A') },
+    { PIX_FMT_ABGR,     MKTAG('A', 'B', 'G', 'R') },
+    { PIX_FMT_ARGB,     MKTAG('A', 'R', 'G', 'B') },
+    { PIX_FMT_RGB24,    MKTAG('R', 'G', 'B', 24 ) },
+    { PIX_FMT_BGR24,    MKTAG('B', 'G', 'R', 24 ) },
+    { PIX_FMT_YUV411P,  MKTAG('4', '1', '1', 'P') },
+    { PIX_FMT_YUV422P,  MKTAG('4', '2', '2', 'P') },
+    { PIX_FMT_YUVJ422P, MKTAG('4', '2', '2', 'P') },
+    { PIX_FMT_YUV440P,  MKTAG('4', '4', '0', 'P') },
+    { PIX_FMT_YUVJ440P, MKTAG('4', '4', '0', 'P') },
+    { PIX_FMT_YUV444P,  MKTAG('4', '4', '4', 'P') },
+    { PIX_FMT_YUVJ444P, MKTAG('4', '4', '4', 'P') },
+    { PIX_FMT_MONOWHITE,MKTAG('B', '1', 'W', '0') },
+    { PIX_FMT_MONOBLACK,MKTAG('B', '0', 'W', '1') },
+    { PIX_FMT_BGR8,     MKTAG('B', 'G', 'R',  8 ) },
+    { PIX_FMT_RGB8,     MKTAG('R', 'G', 'B',  8 ) },
+    { PIX_FMT_BGR4,     MKTAG('B', 'G', 'R',  4 ) },
+    { PIX_FMT_RGB4,     MKTAG('R', 'G', 'B',  4 ) },
+    { PIX_FMT_RGB4_BYTE,MKTAG('B', '4', 'B', 'Y') },
+    { PIX_FMT_BGR4_BYTE,MKTAG('R', '4', 'B', 'Y') },
+    { PIX_FMT_RGB48LE,  MKTAG('R', 'G', 'B', 48 ) },
+    { PIX_FMT_RGB48BE,  MKTAG( 48, 'R', 'G', 'B') },
+    { PIX_FMT_GRAY16LE,    MKTAG('Y', '1',  0 , 16 ) },
+    { PIX_FMT_GRAY16BE,    MKTAG(16 ,  0 , '1', 'Y') },
+    { PIX_FMT_YUV420P16LE, MKTAG('Y', '3', 11 , 16 ) },
+    { PIX_FMT_YUV420P16BE, MKTAG(16 , 11 , '3', 'Y') },
+    { PIX_FMT_YUV422P16LE, MKTAG('Y', '3', 10 , 16 ) },
+    { PIX_FMT_YUV422P16BE, MKTAG(16 , 10 , '3', 'Y') },
+    { PIX_FMT_YUV444P16LE, MKTAG('Y', '3',  0 , 16 ) },
+    { PIX_FMT_YUV444P16BE, MKTAG(16 ,  0 , '3', 'Y') },
+    { PIX_FMT_YUVA420P,    MKTAG('Y', '4', 11 ,  8 ) },
+    { PIX_FMT_Y400A,       MKTAG('Y', '2',  0 ,  8 ) },
 
     /* quicktime */
     { PIX_FMT_UYVY422, MKTAG('2', 'v', 'u', 'y') },
@@ -69,13 +120,25 @@ const PixelFormatTag ff_raw_pixelFormatTags[] = {
     { PIX_FMT_YUYV422, MKTAG('y', 'u', 'v', '2') },
     { PIX_FMT_YUYV422, MKTAG('y', 'u', 'v', 's') },
     { PIX_FMT_PAL8,    MKTAG('W', 'R', 'A', 'W') },
+    { PIX_FMT_RGB555LE,MKTAG('L', '5', '5', '5') },
+    { PIX_FMT_RGB565LE,MKTAG('L', '5', '6', '5') },
+    { PIX_FMT_RGB565BE,MKTAG('B', '5', '6', '5') },
+    { PIX_FMT_BGR24,   MKTAG('2', '4', 'B', 'G') },
+    { PIX_FMT_BGRA,    MKTAG('B', 'G', 'R', 'A') },
+    { PIX_FMT_RGBA,    MKTAG('R', 'G', 'B', 'A') },
+    { PIX_FMT_ABGR,    MKTAG('A', 'B', 'G', 'R') },
+    { PIX_FMT_GRAY16BE,MKTAG('b', '1', '6', 'g') },
+    { PIX_FMT_RGB48BE, MKTAG('b', '4', '8', 'r') },
+
+    /* special */
+    { PIX_FMT_RGB565LE,MKTAG( 3 ,  0 ,  0 ,  0 ) }, /* flipped RGB565LE */
 
     { PIX_FMT_NONE, 0 },
 };
 
 unsigned int avcodec_pix_fmt_to_codec_tag(enum PixelFormat fmt)
 {
-    const PixelFormatTag * tags = ff_raw_pixelFormatTags;
+    const PixelFormatTag *tags = ff_raw_pix_fmt_tags;
     while (tags->pix_fmt >= 0) {
         if (tags->pix_fmt == fmt)
             return tags->fourcc;
diff --git a/libavcodec/raw.h b/libavcodec/raw.h
index e74006a..2caa3fa 100644
--- a/libavcodec/raw.h
+++ b/libavcodec/raw.h
@@ -2,20 +2,20 @@
  * Raw Video Codec
  * Copyright (c) 2001 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -34,6 +34,6 @@ typedef struct PixelFormatTag {
     unsigned int fourcc;
 } PixelFormatTag;
 
-extern const PixelFormatTag ff_raw_pixelFormatTags[];
+extern const PixelFormatTag ff_raw_pix_fmt_tags[];
 
 #endif /* AVCODEC_RAW_H */
diff --git a/libavcodec/rawdec.c b/libavcodec/rawdec.c
index 8b398d2..3dbfdfe 100644
--- a/libavcodec/rawdec.c
+++ b/libavcodec/rawdec.c
@@ -2,20 +2,20 @@
  * Raw Video Decoder
  * Copyright (c) 2001 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,19 +25,23 @@
  */
 
 #include "avcodec.h"
+#include "imgconvert.h"
 #include "raw.h"
 #include "libavutil/intreadwrite.h"
+#include "libavutil/imgutils.h"
 
 typedef struct RawVideoContext {
+    uint32_t palette[AVPALETTE_COUNT];
     unsigned char * buffer;  /* block of memory for holding one frame */
     int             length;  /* number of bytes in buffer */
     int flip;
     AVFrame pic;             ///< AVCodecContext.coded_frame
 } RawVideoContext;
 
-static const PixelFormatTag pixelFormatBpsAVI[] = {
+static const PixelFormatTag pix_fmt_bps_avi[] = {
     { PIX_FMT_PAL8,    4 },
     { PIX_FMT_PAL8,    8 },
+    { PIX_FMT_RGB444, 12 },
     { PIX_FMT_RGB555, 15 },
     { PIX_FMT_RGB555, 16 },
     { PIX_FMT_BGR24,  24 },
@@ -45,7 +49,7 @@ static const PixelFormatTag pixelFormatBpsAVI[] = {
     { PIX_FMT_NONE, 0 },
 };
 
-static const PixelFormatTag pixelFormatBpsMOV[] = {
+static const PixelFormatTag pix_fmt_bps_mov[] = {
     { PIX_FMT_MONOWHITE, 1 },
     { PIX_FMT_PAL8,      2 },
     { PIX_FMT_PAL8,      4 },
@@ -58,7 +62,7 @@ static const PixelFormatTag pixelFormatBpsMOV[] = {
     { PIX_FMT_NONE, 0 },
 };
 
-static enum PixelFormat findPixelFormat(const PixelFormatTag *tags, unsigned int fourcc)
+static enum PixelFormat find_pix_fmt(const PixelFormatTag *tags, unsigned int fourcc)
 {
     while (tags->pix_fmt >= 0) {
         if (tags->fourcc == fourcc)
@@ -73,22 +77,26 @@ static av_cold int raw_init_decoder(AVCodecContext *avctx)
     RawVideoContext *context = avctx->priv_data;
 
     if (avctx->codec_tag == MKTAG('r','a','w',' '))
-        avctx->pix_fmt = findPixelFormat(pixelFormatBpsMOV, avctx->bits_per_coded_sample);
+        avctx->pix_fmt = find_pix_fmt(pix_fmt_bps_mov, avctx->bits_per_coded_sample);
     else if (avctx->codec_tag)
-        avctx->pix_fmt = findPixelFormat(ff_raw_pixelFormatTags, avctx->codec_tag);
-    else if (avctx->bits_per_coded_sample)
-        avctx->pix_fmt = findPixelFormat(pixelFormatBpsAVI, avctx->bits_per_coded_sample);
+        avctx->pix_fmt = find_pix_fmt(ff_raw_pix_fmt_tags, avctx->codec_tag);
+    else if (avctx->pix_fmt == PIX_FMT_NONE && avctx->bits_per_coded_sample)
+        avctx->pix_fmt = find_pix_fmt(pix_fmt_bps_avi, avctx->bits_per_coded_sample);
 
+    ff_set_systematic_pal2(context->palette, avctx->pix_fmt);
     context->length = avpicture_get_size(avctx->pix_fmt, avctx->width, avctx->height);
-    context->buffer = av_malloc(context->length);
+    if((avctx->bits_per_coded_sample == 4 || avctx->bits_per_coded_sample == 2) &&
+       avctx->pix_fmt==PIX_FMT_PAL8 &&
+       (!avctx->codec_tag || avctx->codec_tag == MKTAG('r','a','w',' '))){
+        context->buffer = av_malloc(context->length);
+        if (!context->buffer)
+            return -1;
+    }
     context->pic.pict_type = FF_I_TYPE;
     context->pic.key_frame = 1;
 
     avctx->coded_frame= &context->pic;
 
-    if (!context->buffer)
-        return -1;
-
     if((avctx->extradata_size >= 9 && !memcmp(avctx->extradata + avctx->extradata_size - 9, "BottomUp", 9)) ||
        avctx->codec_tag == MKTAG( 3 ,  0 ,  0 ,  0 ))
         context->flip=1;
@@ -114,13 +122,13 @@ static int raw_decode(AVCodecContext *avctx,
 
     frame->interlaced_frame = avctx->coded_frame->interlaced_frame;
     frame->top_field_first = avctx->coded_frame->top_field_first;
+    frame->reordered_opaque = avctx->reordered_opaque;
+    frame->pkt_pts          = avctx->pkt->pts;
 
     //2bpp and 4bpp raw in avi and mov (yes this is ugly ...)
-    if((avctx->bits_per_coded_sample == 4 || avctx->bits_per_coded_sample == 2) &&
-       avctx->pix_fmt==PIX_FMT_PAL8 &&
-       (!avctx->codec_tag || avctx->codec_tag == MKTAG('r','a','w',' '))){
+    if (context->buffer) {
         int i;
-        uint8_t *dst = context->buffer + 256*4;
+        uint8_t *dst = context->buffer;
         buf_size = context->length - 256*4;
         if (avctx->bits_per_coded_sample == 4){
             for(i=0; 2*i+1 < buf_size; i++){
@@ -145,12 +153,18 @@ static int raw_decode(AVCodecContext *avctx,
         return -1;
 
     avpicture_fill(picture, buf, avctx->pix_fmt, avctx->width, avctx->height);
-    if(avctx->pix_fmt==PIX_FMT_PAL8 && buf_size < context->length){
-        frame->data[1]= context->buffer;
+    if((avctx->pix_fmt==PIX_FMT_PAL8 && buf_size < context->length) ||
+       (avctx->pix_fmt!=PIX_FMT_PAL8 &&
+        (av_pix_fmt_descriptors[avctx->pix_fmt].flags & PIX_FMT_PAL))){
+        frame->data[1]= context->palette;
     }
-    if (avctx->palctrl && avctx->palctrl->palette_changed) {
-        memcpy(frame->data[1], avctx->palctrl->palette, AVPALETTE_SIZE);
-        avctx->palctrl->palette_changed = 0;
+    if (avctx->pix_fmt == PIX_FMT_PAL8) {
+        const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, NULL);
+
+        if (pal) {
+            memcpy(frame->data[1], pal, AVPALETTE_SIZE);
+            frame->palette_has_changed = 1;
+        }
     }
     if(avctx->pix_fmt==PIX_FMT_BGR24 && ((frame->linesize[0]+3)&~3)*avctx->height <= buf_size)
         frame->linesize[0] = (frame->linesize[0]+3)&~3;
@@ -185,7 +199,7 @@ static av_cold int raw_close_decoder(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec rawvideo_decoder = {
+AVCodec ff_rawvideo_decoder = {
     "rawvideo",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_RAWVIDEO,
diff --git a/libavcodec/rawenc.c b/libavcodec/rawenc.c
index 4199704..229f01f 100644
--- a/libavcodec/rawenc.c
+++ b/libavcodec/rawenc.c
@@ -2,20 +2,20 @@
  * Raw Video Encoder
  * Copyright (c) 2001 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -55,7 +55,7 @@ static int raw_encode(AVCodecContext *avctx,
     return ret;
 }
 
-AVCodec rawvideo_encoder = {
+AVCodec ff_rawvideo_encoder = {
     "rawvideo",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_RAWVIDEO,
diff --git a/libavcodec/rdft.c b/libavcodec/rdft.c
index f37263b..116cfa4 100644
--- a/libavcodec/rdft.c
+++ b/libavcodec/rdft.c
@@ -2,26 +2,26 @@
  * (I)RDFT transforms
  * Copyright (c) 2009 Alex Converse <alex dot converse at gmail dot com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #include <stdlib.h>
 #include <math.h>
 #include "libavutil/mathematics.h"
-#include "fft.h"
+#include "rdft.h"
 
 /**
  * @file
@@ -44,7 +44,7 @@ SINTABLE(16384);
 SINTABLE(32768);
 SINTABLE(65536);
 #endif
-SINTABLE_CONST FFTSample * const ff_sin_tabs[] = {
+static SINTABLE_CONST FFTSample * const ff_sin_tabs[] = {
     NULL, NULL, NULL, NULL,
     ff_sin_16, ff_sin_32, ff_sin_64, ff_sin_128, ff_sin_256, ff_sin_512, ff_sin_1024,
     ff_sin_2048, ff_sin_4096, ff_sin_8192, ff_sin_16384, ff_sin_32768, ff_sin_65536,
@@ -65,8 +65,8 @@ static void ff_rdft_calc_c(RDFTContext* s, FFTSample* data)
     const FFTSample *tsin = s->tsin;
 
     if (!s->inverse) {
-        ff_fft_permute(&s->fft, (FFTComplex*)data);
-        ff_fft_calc(&s->fft, (FFTComplex*)data);
+        s->fft.fft_permute(&s->fft, (FFTComplex*)data);
+        s->fft.fft_calc(&s->fft, (FFTComplex*)data);
     }
     /* i=0 is a special case because of packing, the DC term is real, so we
        are going to throw the N/2 term (also real) in with it. */
@@ -91,8 +91,8 @@ static void ff_rdft_calc_c(RDFTContext* s, FFTSample* data)
     if (s->inverse) {
         data[0] *= k1;
         data[1] *= k1;
-        ff_fft_permute(&s->fft, (FFTComplex*)data);
-        ff_fft_calc(&s->fft, (FFTComplex*)data);
+        s->fft.fft_permute(&s->fft, (FFTComplex*)data);
+        s->fft.fft_calc(&s->fft, (FFTComplex*)data);
     }
 }
 
diff --git a/libavcodec/rdft.h b/libavcodec/rdft.h
new file mode 100644
index 0000000..7572c6c
--- /dev/null
+++ b/libavcodec/rdft.h
@@ -0,0 +1,74 @@
+/*
+ * (I)RDFT transforms
+ * Copyright (c) 2009 Alex Converse <alex dot converse at gmail dot com>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_RDFT_H
+#define AVCODEC_RDFT_H
+
+#include "config.h"
+#include "fft.h"
+
+#if CONFIG_HARDCODED_TABLES
+#   define SINTABLE_CONST const
+#else
+#   define SINTABLE_CONST
+#endif
+
+#define SINTABLE(size) \
+    SINTABLE_CONST DECLARE_ALIGNED(16, FFTSample, ff_sin_##size)[size/2]
+
+extern SINTABLE(16);
+extern SINTABLE(32);
+extern SINTABLE(64);
+extern SINTABLE(128);
+extern SINTABLE(256);
+extern SINTABLE(512);
+extern SINTABLE(1024);
+extern SINTABLE(2048);
+extern SINTABLE(4096);
+extern SINTABLE(8192);
+extern SINTABLE(16384);
+extern SINTABLE(32768);
+extern SINTABLE(65536);
+
+struct RDFTContext {
+    int nbits;
+    int inverse;
+    int sign_convention;
+
+    /* pre/post rotation tables */
+    const FFTSample *tcos;
+    SINTABLE_CONST FFTSample *tsin;
+    FFTContext fft;
+    void (*rdft_calc)(struct RDFTContext *s, FFTSample *z);
+};
+
+/**
+ * Set up a real FFT.
+ * @param nbits           log2 of the length of the input array
+ * @param trans           the type of transform
+ */
+int ff_rdft_init(RDFTContext *s, int nbits, enum RDFTransformType trans);
+void ff_rdft_end(RDFTContext *s);
+
+void ff_rdft_init_arm(RDFTContext *s);
+
+
+#endif
diff --git a/libavcodec/rectangle.h b/libavcodec/rectangle.h
index cf4a9cc..5cc81fe 100644
--- a/libavcodec/rectangle.h
+++ b/libavcodec/rectangle.h
@@ -2,20 +2,20 @@
  * rectangle filling function
  * Copyright (c) 2003 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/remove_extradata_bsf.c b/libavcodec/remove_extradata_bsf.c
index 95bd98b..460482a 100644
--- a/libavcodec/remove_extradata_bsf.c
+++ b/libavcodec/remove_extradata_bsf.c
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -48,7 +48,7 @@ static int remove_extradata(AVBitStreamFilterContext *bsfc, AVCodecContext *avct
     return 0;
 }
 
-AVBitStreamFilter remove_extradata_bsf={
+AVBitStreamFilter ff_remove_extradata_bsf={
     "remove_extra",
     0,
     remove_extradata,
diff --git a/libavcodec/resample.c b/libavcodec/resample.c
index b008180..8e66689 100644
--- a/libavcodec/resample.c
+++ b/libavcodec/resample.c
@@ -2,20 +2,20 @@
  * samplerate conversion for both audio and video
  * Copyright (c) 2000 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -26,7 +26,8 @@
 
 #include "avcodec.h"
 #include "audioconvert.h"
-#include "opt.h"
+#include "libavutil/opt.h"
+#include "libavutil/samplefmt.h"
 
 struct AVResampleContext;
 
@@ -46,7 +47,7 @@ struct ReSampleContext {
     /* channel convert */
     int input_channels, output_channels, filter_channels;
     AVAudioConvert *convert_ctx[2];
-    enum SampleFormat sample_fmt[2]; ///< input and output sample format
+    enum AVSampleFormat sample_fmt[2]; ///< input and output sample format
     unsigned sample_size[2];         ///< size of one sample in sample_fmt
     short *buffer[2];                ///< buffers used for conversion to S16
     unsigned buffer_size[2];         ///< sizes of allocated buffers
@@ -143,8 +144,8 @@ static void ac3_5p1_mux(short *output, short *input1, short *input2, int n)
 
 ReSampleContext *av_audio_resample_init(int output_channels, int input_channels,
                                         int output_rate, int input_rate,
-                                        enum SampleFormat sample_fmt_out,
-                                        enum SampleFormat sample_fmt_in,
+                                        enum AVSampleFormat sample_fmt_out,
+                                        enum AVSampleFormat sample_fmt_in,
                                         int filter_length, int log2_phase_count,
                                         int linear, double cutoff)
 {
@@ -174,26 +175,26 @@ ReSampleContext *av_audio_resample_init(int output_channels, int input_channels,
 
     s->sample_fmt [0] = sample_fmt_in;
     s->sample_fmt [1] = sample_fmt_out;
-    s->sample_size[0] = av_get_bits_per_sample_format(s->sample_fmt[0])>>3;
-    s->sample_size[1] = av_get_bits_per_sample_format(s->sample_fmt[1])>>3;
+    s->sample_size[0] = av_get_bits_per_sample_fmt(s->sample_fmt[0])>>3;
+    s->sample_size[1] = av_get_bits_per_sample_fmt(s->sample_fmt[1])>>3;
 
-    if (s->sample_fmt[0] != SAMPLE_FMT_S16) {
-        if (!(s->convert_ctx[0] = av_audio_convert_alloc(SAMPLE_FMT_S16, 1,
+    if (s->sample_fmt[0] != AV_SAMPLE_FMT_S16) {
+        if (!(s->convert_ctx[0] = av_audio_convert_alloc(AV_SAMPLE_FMT_S16, 1,
                                                          s->sample_fmt[0], 1, NULL, 0))) {
             av_log(s, AV_LOG_ERROR,
                    "Cannot convert %s sample format to s16 sample format\n",
-                   avcodec_get_sample_fmt_name(s->sample_fmt[0]));
+                   av_get_sample_fmt_name(s->sample_fmt[0]));
             av_free(s);
             return NULL;
         }
     }
 
-    if (s->sample_fmt[1] != SAMPLE_FMT_S16) {
+    if (s->sample_fmt[1] != AV_SAMPLE_FMT_S16) {
         if (!(s->convert_ctx[1] = av_audio_convert_alloc(s->sample_fmt[1], 1,
-                                                         SAMPLE_FMT_S16, 1, NULL, 0))) {
+                                                         AV_SAMPLE_FMT_S16, 1, NULL, 0))) {
             av_log(s, AV_LOG_ERROR,
                    "Cannot convert s16 sample format to %s sample format\n",
-                   avcodec_get_sample_fmt_name(s->sample_fmt[1]));
+                   av_get_sample_fmt_name(s->sample_fmt[1]));
             av_audio_convert_free(s->convert_ctx[0]);
             av_free(s);
             return NULL;
@@ -217,13 +218,13 @@ ReSampleContext *av_audio_resample_init(int output_channels, int input_channels,
     return s;
 }
 
-#if LIBAVCODEC_VERSION_MAJOR < 53
+#if FF_API_AUDIO_OLD
 ReSampleContext *audio_resample_init(int output_channels, int input_channels,
                                      int output_rate, int input_rate)
 {
     return av_audio_resample_init(output_channels, input_channels,
                                   output_rate, input_rate,
-                                  SAMPLE_FMT_S16, SAMPLE_FMT_S16,
+                                  AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_S16,
                                   TAPS, 10, 0, 0.8);
 }
 #endif
@@ -245,7 +246,7 @@ int audio_resample(ReSampleContext *s, short *output, short *input, int nb_sampl
         return nb_samples;
     }
 
-    if (s->sample_fmt[0] != SAMPLE_FMT_S16) {
+    if (s->sample_fmt[0] != AV_SAMPLE_FMT_S16) {
         int istride[1] = { s->sample_size[0] };
         int ostride[1] = { 2 };
         const void *ibuf[1] = { input };
@@ -275,7 +276,7 @@ int audio_resample(ReSampleContext *s, short *output, short *input, int nb_sampl
 
     lenout= 4*nb_samples * s->ratio + 16;
 
-    if (s->sample_fmt[1] != SAMPLE_FMT_S16) {
+    if (s->sample_fmt[1] != AV_SAMPLE_FMT_S16) {
         output_bak = output;
 
         if (!s->buffer_size[1] || s->buffer_size[1] < lenout) {
@@ -340,7 +341,7 @@ int audio_resample(ReSampleContext *s, short *output, short *input, int nb_sampl
         ac3_5p1_mux(output, buftmp3[0], buftmp3[1], nb_samples1);
     }
 
-    if (s->sample_fmt[1] != SAMPLE_FMT_S16) {
+    if (s->sample_fmt[1] != AV_SAMPLE_FMT_S16) {
         int istride[1] = { 2 };
         int ostride[1] = { s->sample_size[1] };
         const void *ibuf[1] = { output };
diff --git a/libavcodec/resample2.c b/libavcodec/resample2.c
index 45f41a1..7560d84 100644
--- a/libavcodec/resample2.c
+++ b/libavcodec/resample2.c
@@ -2,20 +2,20 @@
  * audio resampling
  * Copyright (c) 2004 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -94,12 +94,17 @@ static double bessel(double x){
  * @param factor resampling factor
  * @param scale wanted sum of coefficients for each filter
  * @param type 0->cubic, 1->blackman nuttall windowed sinc, 2..16->kaiser windowed sinc beta=2..16
+ * @return 0 on success, negative on error
  */
-static void build_filter(FELEM *filter, double factor, int tap_count, int phase_count, int scale, int type){
+static int build_filter(FELEM *filter, double factor, int tap_count, int phase_count, int scale, int type){
     int ph, i;
-    double x, y, w, tab[tap_count];
+    double x, y, w;
+    double *tab = av_malloc(tap_count * sizeof(*tab));
     const int center= (tap_count-1)/2;
 
+    if (!tab)
+        return AVERROR(ENOMEM);
+
     /* if upsampling, only need to interpolate, no filter */
     if (factor > 1.0)
         factor = 1.0;
@@ -176,6 +181,9 @@ static void build_filter(FELEM *filter, double factor, int tap_count, int phase_
         }
     }
 #endif
+
+    av_free(tab);
+    return 0;
 }
 
 AVResampleContext *av_resample_init(int out_rate, int in_rate, int filter_size, int phase_shift, int linear, double cutoff){
@@ -183,13 +191,19 @@ AVResampleContext *av_resample_init(int out_rate, int in_rate, int filter_size,
     double factor= FFMIN(out_rate * cutoff / in_rate, 1.0);
     int phase_count= 1<<phase_shift;
 
+    if (!c)
+        return NULL;
+
     c->phase_shift= phase_shift;
     c->phase_mask= phase_count-1;
     c->linear= linear;
 
     c->filter_length= FFMAX((int)ceil(filter_size/factor), 1);
     c->filter_bank= av_mallocz(c->filter_length*(phase_count+1)*sizeof(FELEM));
-    build_filter(c->filter_bank, factor, c->filter_length, phase_count, 1<<FILTER_SHIFT, WINDOW_TYPE);
+    if (!c->filter_bank)
+        goto error;
+    if (build_filter(c->filter_bank, factor, c->filter_length, phase_count, 1<<FILTER_SHIFT, WINDOW_TYPE))
+        goto error;
     memcpy(&c->filter_bank[c->filter_length*phase_count+1], c->filter_bank, (c->filter_length-1)*sizeof(FELEM));
     c->filter_bank[c->filter_length*phase_count]= c->filter_bank[c->filter_length - 1];
 
@@ -198,6 +212,10 @@ AVResampleContext *av_resample_init(int out_rate, int in_rate, int filter_size,
     c->index= -phase_count*((c->filter_length-1)/2);
 
     return c;
+error:
+    av_free(c->filter_bank);
+    av_free(c);
+    return NULL;
 }
 
 void av_resample_close(AVResampleContext *c){
diff --git a/libavcodec/rl.h b/libavcodec/rl.h
index b244589..9c1ad7a 100644
--- a/libavcodec/rl.h
+++ b/libavcodec/rl.h
@@ -2,20 +2,20 @@
  * Copyright (c) 2000-2002 Fabrice Bellard
  * Copyright (c) 2002-2004 Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/rl2.c b/libavcodec/rl2.c
index 30f5e83..3d1cea3 100644
--- a/libavcodec/rl2.c
+++ b/libavcodec/rl2.c
@@ -2,20 +2,20 @@
  * RL2 Video Decoder
  * Copyright (C) 2008 Sascha Sommer (saschasommer at freenet.de)
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -50,7 +50,7 @@ typedef struct Rl2Context {
 /**
  * Run Length Decode a single 320x200 frame
  * @param s rl2 context
- * @param buf input buffer
+ * @param in input buffer
  * @param size input buffer size
  * @param out ouput buffer
  * @param stride stride of the output buffer
@@ -169,15 +169,6 @@ static av_cold int rl2_decode_init(AVCodecContext *avctx)
 }
 
 
-/**
- * Decode a single frame
- * @param avctx decoder context
- * @param data decoded frame
- * @param data_size size of the decoded frame
- * @param buf input buffer
- * @param buf_size input buffer size
- * @return 0 success, -1 on error
- */
 static int rl2_decode_frame(AVCodecContext *avctx,
                               void *data, int *data_size,
                               AVPacket *avpkt)
@@ -228,7 +219,7 @@ static av_cold int rl2_decode_end(AVCodecContext *avctx)
 }
 
 
-AVCodec rl2_decoder = {
+AVCodec ff_rl2_decoder = {
     "rl2",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_RL2,
diff --git a/libavcodec/rle.c b/libavcodec/rle.c
index 6e468f8..8a009e7 100644
--- a/libavcodec/rle.c
+++ b/libavcodec/rle.c
@@ -2,20 +2,20 @@
  * RLE encoder
  * Copyright (c) 2007 Bobby Bingham
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #include "avcodec.h"
diff --git a/libavcodec/rle.h b/libavcodec/rle.h
index f892443..00261d3 100644
--- a/libavcodec/rle.h
+++ b/libavcodec/rle.h
@@ -1,20 +1,20 @@
 /*
  * RLE encoder
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -28,7 +28,7 @@
  *                                                      Value before raw bytes is      (count ^ xor_raw) + add_raw.
  * @param outbuf Output buffer
  * @param out_size Maximum output size
- * @param ptr Input buffer
+ * @param inbuf Input buffer
  * @param bpp Bytes per pixel
  * @param w Image width
  * @return Size of output in bytes, or -1 if larger than out_size
diff --git a/libavcodec/roqaudioenc.c b/libavcodec/roqaudioenc.c
index 11fd6f0..46aefb4 100644
--- a/libavcodec/roqaudioenc.c
+++ b/libavcodec/roqaudioenc.c
@@ -4,20 +4,20 @@
  * Copyright (c) 2005 Eric Lasota
  *    Based on RoQ specs (c)2001 Tim Ferguson
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -49,7 +49,7 @@ static av_cold int roq_dpcm_encode_init(AVCodecContext *avctx)
         av_log(avctx, AV_LOG_ERROR, "Audio must be 22050 Hz\n");
         return -1;
     }
-    if (avctx->sample_fmt != SAMPLE_FMT_S16) {
+    if (avctx->sample_fmt != AV_SAMPLE_FMT_S16) {
         av_log(avctx, AV_LOG_ERROR, "Audio must be signed 16-bit\n");
         return -1;
     }
@@ -108,7 +108,7 @@ static int roq_dpcm_encode_frame(AVCodecContext *avctx,
                 unsigned char *frame, int buf_size, void *data)
 {
     int i, samples, stereo, ch;
-    short *in;
+    const short *in;
     unsigned char *out;
 
     ROQDPCMContext *context = avctx->priv_data;
@@ -153,7 +153,7 @@ static av_cold int roq_dpcm_encode_close(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec roq_dpcm_encoder = {
+AVCodec ff_roq_dpcm_encoder = {
     "roq_dpcm",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_ROQ_DPCM,
@@ -162,6 +162,6 @@ AVCodec roq_dpcm_encoder = {
     roq_dpcm_encode_frame,
     roq_dpcm_encode_close,
     NULL,
-    .sample_fmts = (const enum SampleFormat[]){SAMPLE_FMT_S16,SAMPLE_FMT_NONE},
+    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
     .long_name = NULL_IF_CONFIG_SMALL("id RoQ DPCM"),
 };
diff --git a/libavcodec/roqvideo.c b/libavcodec/roqvideo.c
index 830eb7b..77df079 100644
--- a/libavcodec/roqvideo.c
+++ b/libavcodec/roqvideo.c
@@ -2,20 +2,20 @@
  * Copyright (C) 2003 Mike Melanson
  * Copyright (C) 2003 Dr. Tim Ferguson
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -115,6 +115,11 @@ static inline void apply_motion_generic(RoqContext *ri, int x, int y, int deltax
         return;
     }
 
+    if (ri->last_frame->data[0] == NULL) {
+        av_log(ri->avctx, AV_LOG_ERROR, "Invalid decode type. Invalid header?\n");
+        return;
+    }
+
     for(cp = 0; cp < 3; cp++) {
         int outstride = ri->current_frame->linesize[cp];
         int instride  = ri->last_frame   ->linesize[cp];
diff --git a/libavcodec/roqvideo.h b/libavcodec/roqvideo.h
index 3fe11c6..a1ff10a 100644
--- a/libavcodec/roqvideo.h
+++ b/libavcodec/roqvideo.h
@@ -2,20 +2,20 @@
  * Copyright (C) 2003 Mike Melanson
  * Copyright (C) 2003 Dr. Tim Ferguson
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/roqvideodec.c b/libavcodec/roqvideodec.c
index 7c6f5ff..06d1309 100644
--- a/libavcodec/roqvideodec.c
+++ b/libavcodec/roqvideodec.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (C) 2003 the ffmpeg project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -210,7 +210,7 @@ static av_cold int roq_decode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec roq_decoder = {
+AVCodec ff_roq_decoder = {
     "roqvideo",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_ROQ,
diff --git a/libavcodec/roqvideoenc.c b/libavcodec/roqvideoenc.c
index f9fbb64..052dcef 100644
--- a/libavcodec/roqvideoenc.c
+++ b/libavcodec/roqvideoenc.c
@@ -5,27 +5,27 @@
  * Copyright (C) 2004-2007 Eric Lasota
  *    Based on RoQ specs (C) 2001 Tim Ferguson
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 /**
  * @file
  * id RoQ encoder by Vitor. Based on the Switchblade3 library and the
- * Switchblade3 FFmpeg glue by Eric Lasota.
+ * Switchblade3 Libav glue by Eric Lasota.
  */
 
 /*
@@ -165,7 +165,7 @@ static int eval_motion_dist(RoqContext *enc, int x, int y, motion_vect vect,
 }
 
 /**
- * Returns distortion between two macroblocks
+ * @return distortion between two macroblocks
  */
 static inline int squared_diff_macroblock(uint8_t a[], uint8_t b[], int size)
 {
@@ -240,7 +240,7 @@ typedef struct RoqTempData
 } RoqTempdata;
 
 /**
- * Initializes cel evaluators and sets their source coordinates
+ * Initialize cel evaluators and set their source coordinates
  */
 static void create_cel_evals(RoqContext *enc, RoqTempdata *tempData)
 {
@@ -393,7 +393,7 @@ static void motion_search(RoqContext *enc, int blocksize)
 }
 
 /**
- * Gets distortion for all options available to a subcel
+ * Get distortion for all options available to a subcel
  */
 static void gather_data_for_subcel(SubcelEvaluation *subcel, int x,
                                    int y, RoqContext *enc, RoqTempdata *tempData)
@@ -457,7 +457,7 @@ static void gather_data_for_subcel(SubcelEvaluation *subcel, int x,
 }
 
 /**
- * Gets distortion for all options available to a cel
+ * Get distortion for all options available to a cel
  */
 static void gather_data_for_cel(CelEvaluation *cel, RoqContext *enc,
                                 RoqTempdata *tempData)
@@ -773,7 +773,7 @@ static inline void frame_block_to_cell(uint8_t *block, uint8_t **data,
 }
 
 /**
- * Creates YUV clusters for the entire image
+ * Create YUV clusters for the entire image
  */
 static void create_clusters(AVFrame *frame, int w, int h, uint8_t *yuvClusters)
 {
@@ -898,9 +898,20 @@ static void roq_encode_video(RoqContext *enc)
     for (i=0; i<enc->width*enc->height/64; i++)
         gather_data_for_cel(tempData->cel_evals + i, enc, tempData);
 
-    /* Quake 3 can't handle chunks bigger than 65536 bytes */
-    if (tempData->mainChunkSize/8 > 65536) {
-        enc->lambda *= .8;
+    /* Quake 3 can't handle chunks bigger than 65535 bytes */
+    if (tempData->mainChunkSize/8 > 65535) {
+        av_log(enc->avctx, AV_LOG_ERROR,
+               "Warning, generated a frame too big (%d > 65535), "
+               "try using a smaller qscale value.\n",
+               tempData->mainChunkSize/8);
+        enc->lambda *= 1.5;
+        tempData->mainChunkSize = 0;
+        memset(tempData->used_option, 0, sizeof(tempData->used_option));
+        memset(tempData->codebooks.usedCB4, 0,
+               sizeof(tempData->codebooks.usedCB4));
+        memset(tempData->codebooks.usedCB2, 0,
+               sizeof(tempData->codebooks.usedCB2));
+
         goto retry_encode;
     }
 
@@ -1054,7 +1065,7 @@ static int roq_encode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec roq_encoder =
+AVCodec ff_roq_encoder =
 {
     "roqvideo",
     AVMEDIA_TYPE_VIDEO,
diff --git a/libavcodec/rpza.c b/libavcodec/rpza.c
index e103f52..958f103 100644
--- a/libavcodec/rpza.c
+++ b/libavcodec/rpza.c
@@ -2,20 +2,20 @@
  * Quicktime Video (RPZA) Video Decoder
  * Copyright (C) 2003 the ffmpeg project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -275,7 +275,7 @@ static av_cold int rpza_decode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec rpza_decoder = {
+AVCodec ff_rpza_decoder = {
     "rpza",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_RPZA,
diff --git a/libavcodec/rtjpeg.c b/libavcodec/rtjpeg.c
index 4c48f25..616c402 100644
--- a/libavcodec/rtjpeg.c
+++ b/libavcodec/rtjpeg.c
@@ -2,20 +2,20 @@
  * RTJpeg decoding functions
  * Copyright (c) 2006 Reimar Doeffinger
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #include "libavutil/common.h"
diff --git a/libavcodec/rtjpeg.h b/libavcodec/rtjpeg.h
index 4bcb9f7..d537c93 100644
--- a/libavcodec/rtjpeg.h
+++ b/libavcodec/rtjpeg.h
@@ -2,20 +2,20 @@
  * RTJpeg decoding functions
  * copyright (c) 2006 Reimar Doeffinger
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/rv10.c b/libavcodec/rv10.c
index b6ca031..5df162b 100644
--- a/libavcodec/rv10.c
+++ b/libavcodec/rv10.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2000,2001 Fabrice Bellard
  * Copyright (c) 2002-2004 Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,6 +25,7 @@
  * RV10/RV20 decoder
  */
 
+#include "libavutil/imgutils.h"
 #include "avcodec.h"
 #include "dsputil.h"
 #include "mpegvideo.h"
@@ -245,7 +246,7 @@ static int rv10_decode_picture_header(MpegEncContext *s)
     if(!marker) av_log(s->avctx, AV_LOG_ERROR, "marker missing\n");
     pb_frame = get_bits1(&s->gb);
 
-    dprintf(s->avctx, "pict_type=%d pb_frame=%d\n", s->pict_type, pb_frame);
+    av_dlog(s->avctx, "pict_type=%d pb_frame=%d\n", s->pict_type, pb_frame);
 
     if (pb_frame){
         av_log(s->avctx, AV_LOG_ERROR, "pb frame not supported\n");
@@ -264,7 +265,7 @@ static int rv10_decode_picture_header(MpegEncContext *s)
             s->last_dc[0] = get_bits(&s->gb, 8);
             s->last_dc[1] = get_bits(&s->gb, 8);
             s->last_dc[2] = get_bits(&s->gb, 8);
-            dprintf(s->avctx, "DC:%d %d %d\n", s->last_dc[0],
+            av_dlog(s->avctx, "DC:%d %d %d\n", s->last_dc[0],
                     s->last_dc[1], s->last_dc[2]);
         }
     }
@@ -369,7 +370,7 @@ static int rv20_decode_picture_header(MpegEncContext *s)
         }
         if(new_w != s->width || new_h != s->height){
             av_log(s->avctx, AV_LOG_DEBUG, "attempting to change resolution to %dx%d\n", new_w, new_h);
-            if (avcodec_check_dimensions(s->avctx, new_w, new_h) < 0)
+            if (av_image_check_size(new_w, new_h, 0, s->avctx) < 0)
                 return -1;
             MPV_common_end(s);
             avcodec_set_dimensions(s->avctx, new_w, new_h);
@@ -560,7 +561,7 @@ static int rv10_decode_packet(AVCodecContext *avctx,
         ff_er_frame_start(s);
     }
 
-    dprintf(avctx, "qscale=%d\n", s->qscale);
+    av_dlog(avctx, "qscale=%d\n", s->qscale);
 
     /* default quantization values */
     if(s->codec_id== CODEC_ID_RV10){
@@ -599,7 +600,7 @@ static int rv10_decode_packet(AVCodecContext *avctx,
     for(s->mb_num_left= mb_count; s->mb_num_left>0; s->mb_num_left--) {
         int ret;
         ff_update_block_index(s);
-        dprintf(avctx, "**mb x=%d y=%d\n", s->mb_x, s->mb_y);
+        av_dlog(avctx, "**mb x=%d y=%d\n", s->mb_x, s->mb_y);
 
         s->mv_dir = MV_DIR_FORWARD;
         s->mv_type = MV_TYPE_16X16;
@@ -654,7 +655,7 @@ static int rv10_decode_frame(AVCodecContext *avctx,
     int slice_count;
     const uint8_t *slices_hdr = NULL;
 
-    dprintf(avctx, "*****frame %d size=%d\n", avctx->frame_number, buf_size);
+    av_dlog(avctx, "*****frame %d size=%d\n", avctx->frame_number, buf_size);
 
     /* no supplementary picture */
     if (buf_size == 0) {
@@ -706,7 +707,7 @@ static int rv10_decode_frame(AVCodecContext *avctx,
     return buf_size;
 }
 
-AVCodec rv10_decoder = {
+AVCodec ff_rv10_decoder = {
     "rv10",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_RV10,
@@ -716,11 +717,12 @@ AVCodec rv10_decoder = {
     rv10_decode_end,
     rv10_decode_frame,
     CODEC_CAP_DR1,
+    .max_lowres = 3,
     .long_name = NULL_IF_CONFIG_SMALL("RealVideo 1.0"),
     .pix_fmts= ff_pixfmt_list_420,
 };
 
-AVCodec rv20_decoder = {
+AVCodec ff_rv20_decoder = {
     "rv20",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_RV20,
@@ -731,6 +733,7 @@ AVCodec rv20_decoder = {
     rv10_decode_frame,
     CODEC_CAP_DR1 | CODEC_CAP_DELAY,
     .flush= ff_mpeg_flush,
+    .max_lowres = 3,
     .long_name = NULL_IF_CONFIG_SMALL("RealVideo 2.0"),
     .pix_fmts= ff_pixfmt_list_420,
 };
diff --git a/libavcodec/rv10enc.c b/libavcodec/rv10enc.c
index 51ca691..1830b35 100644
--- a/libavcodec/rv10enc.c
+++ b/libavcodec/rv10enc.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2000,2001 Fabrice Bellard
  * Copyright (c) 2002-2004 Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -56,7 +56,7 @@ void rv10_encode_picture_header(MpegEncContext *s, int picture_number)
     put_bits(&s->pb, 3, 0);     /* ignored */
 }
 
-AVCodec rv10_encoder = {
+AVCodec ff_rv10_encoder = {
     "rv10",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_RV10,
diff --git a/libavcodec/rv20enc.c b/libavcodec/rv20enc.c
index 5ab0b9a..dbce0b3 100644
--- a/libavcodec/rv20enc.c
+++ b/libavcodec/rv20enc.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2000,2001 Fabrice Bellard
  * Copyright (c) 2002-2004 Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -41,7 +41,7 @@ void rv20_encode_picture_header(MpegEncContext *s, int picture_number){
     put_bits(&s->pb, 1, s->no_rounding);
 
     assert(s->f_code == 1);
-    assert(s->unrestricted_mv == 1);
+    assert(s->unrestricted_mv == 0);
     assert(s->alt_inter_vlc == 0);
     assert(s->umvplus == 0);
     assert(s->modified_quant==1);
@@ -57,7 +57,7 @@ void rv20_encode_picture_header(MpegEncContext *s, int picture_number){
     }
 }
 
-AVCodec rv20_encoder = {
+AVCodec ff_rv20_encoder = {
     "rv20",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_RV20,
diff --git a/libavcodec/rv30.c b/libavcodec/rv30.c
index 22a5dd5..b4a52e0 100644
--- a/libavcodec/rv30.c
+++ b/libavcodec/rv30.c
@@ -2,20 +2,20 @@
  * RV30 decoder
  * Copyright (c) 2007 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -266,7 +266,7 @@ static av_cold int rv30_decode_init(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec rv30_decoder = {
+AVCodec ff_rv30_decoder = {
     "rv30",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_RV30,
diff --git a/libavcodec/rv30data.h b/libavcodec/rv30data.h
index 9cc48a6..5ee3048 100644
--- a/libavcodec/rv30data.h
+++ b/libavcodec/rv30data.h
@@ -2,20 +2,20 @@
  * RealVideo 3 decoder
  * copyright (c) 2007 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/rv30dsp.c b/libavcodec/rv30dsp.c
index 4700e78..c6e0614 100644
--- a/libavcodec/rv30dsp.c
+++ b/libavcodec/rv30dsp.c
@@ -2,20 +2,20 @@
  * RV30 decoder motion compensation functions
  * Copyright (c) 2007 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/rv34.c b/libavcodec/rv34.c
index 88652f9..8122b66 100644
--- a/libavcodec/rv34.c
+++ b/libavcodec/rv34.c
@@ -2,20 +2,20 @@
  * RV30/40 decoder common data
  * Copyright (c) 2007 Mike Melanson, Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -103,8 +103,8 @@ static void rv34_gen_vlc(const uint8_t *bits, int size, VLC *vlc, const uint8_t
 {
     int i;
     int counts[17] = {0}, codes[17];
-    uint16_t cw[size], syms[size];
-    uint8_t bits2[size];
+    uint16_t cw[MAX_VLC_SIZE], syms[MAX_VLC_SIZE];
+    uint8_t bits2[MAX_VLC_SIZE];
     int maxbits = 0, realsize = 0;
 
     for(i = 0; i < size; i++){
@@ -393,7 +393,7 @@ static inline void rv34_dequant4x4_16x16(DCTELEM *block, int Qdc, int Q)
 
 
 /**
- * @defgroup bitstream RV30/40 bitstream parsing
+ * @defgroup rv3040_bitstream RV30/40 bitstream parsing
  * @{
  */
 
@@ -718,12 +718,12 @@ static inline void rv34_mc(RV34DecContext *r, const int block_type,
         uint8_t *uvbuf= s->edge_emu_buffer + 22 * s->linesize;
 
         srcY -= 2 + 2*s->linesize;
-        ff_emulated_edge_mc(s->edge_emu_buffer, srcY, s->linesize, (width<<3)+6, (height<<3)+6,
+        s->dsp.emulated_edge_mc(s->edge_emu_buffer, srcY, s->linesize, (width<<3)+6, (height<<3)+6,
                             src_x - 2, src_y - 2, s->h_edge_pos, s->v_edge_pos);
         srcY = s->edge_emu_buffer + 2 + 2*s->linesize;
-        ff_emulated_edge_mc(uvbuf     , srcU, s->uvlinesize, (width<<2)+1, (height<<2)+1,
+        s->dsp.emulated_edge_mc(uvbuf     , srcU, s->uvlinesize, (width<<2)+1, (height<<2)+1,
                             uvsrc_x, uvsrc_y, s->h_edge_pos >> 1, s->v_edge_pos >> 1);
-        ff_emulated_edge_mc(uvbuf + 16, srcV, s->uvlinesize, (width<<2)+1, (height<<2)+1,
+        s->dsp.emulated_edge_mc(uvbuf + 16, srcV, s->uvlinesize, (width<<2)+1, (height<<2)+1,
                             uvsrc_x, uvsrc_y, s->h_edge_pos >> 1, s->v_edge_pos >> 1);
         srcU = uvbuf;
         srcV = uvbuf + 16;
@@ -1142,7 +1142,7 @@ static int rv34_set_deblock_coef(RV34DecContext *r)
     MpegEncContext *s = &r->s;
     int hmvmask = 0, vmvmask = 0, i, j;
     int midx = s->mb_x * 2 + s->mb_y * 2 * s->b8_stride;
-    int16_t (*motion_val)[2] = s->current_picture_ptr->motion_val[0][midx];
+    int16_t (*motion_val)[2] = &s->current_picture_ptr->motion_val[0][midx];
     for(j = 0; j < 16; j += 8){
         for(i = 0; i < 2; i++){
             if(is_mv_diff_gt_3(motion_val + i, 1))
@@ -1454,15 +1454,19 @@ int ff_rv34_decode_frame(AVCodecContext *avctx,
     }
     if((!s->last_picture_ptr || !s->last_picture_ptr->data[0]) && si.type == FF_B_TYPE)
         return -1;
+#if FF_API_HURRY_UP
     /* skip b frames if we are in a hurry */
     if(avctx->hurry_up && si.type==FF_B_TYPE) return buf_size;
+#endif
     if(   (avctx->skip_frame >= AVDISCARD_NONREF && si.type==FF_B_TYPE)
        || (avctx->skip_frame >= AVDISCARD_NONKEY && si.type!=FF_I_TYPE)
        ||  avctx->skip_frame >= AVDISCARD_ALL)
         return buf_size;
+#if FF_API_HURRY_UP
     /* skip everything if we are in a hurry>=5 */
     if(avctx->hurry_up>=5)
         return buf_size;
+#endif
 
     for(i=0; i<slice_count; i++){
         int offset= get_slice_offset(avctx, slices_hdr, i);
diff --git a/libavcodec/rv34.h b/libavcodec/rv34.h
index 24a27ce..c9f4ff7 100644
--- a/libavcodec/rv34.h
+++ b/libavcodec/rv34.h
@@ -2,20 +2,20 @@
  * RV30/40 decoder common data declarations
  * Copyright (c) 2007 Mike Melanson, Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/rv34data.h b/libavcodec/rv34data.h
index 2155084..f8f941d 100644
--- a/libavcodec/rv34data.h
+++ b/libavcodec/rv34data.h
@@ -2,20 +2,20 @@
  * RealVideo 4 decoder
  * copyright (c) 2007 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/rv34vlc.h b/libavcodec/rv34vlc.h
index 2b89e4c..f4670c1 100644
--- a/libavcodec/rv34vlc.h
+++ b/libavcodec/rv34vlc.h
@@ -2,20 +2,20 @@
  * RealVideo 3/4 decoder
  * Copyright (c) 2007 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -37,6 +37,7 @@
 #define FIRSTBLK_VLC_SIZE  864
 #define OTHERBLK_VLC_SIZE  108
 #define COEFF_VLC_SIZE      32
+#define MAX_VLC_SIZE      1296
 
 static const uint8_t rv34_table_intra_cbppat[NUM_INTRA_TABLES][2][CBPPAT_VLC_SIZE] = {
   {
diff --git a/libavcodec/rv40.c b/libavcodec/rv40.c
index abdeeff..ea6c3c1 100644
--- a/libavcodec/rv40.c
+++ b/libavcodec/rv40.c
@@ -2,20 +2,20 @@
  * RV40 decoder
  * Copyright (c) 2007 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -24,6 +24,8 @@
  * RV40 decoder
  */
 
+#include "libavutil/imgutils.h"
+
 #include "avcodec.h"
 #include "dsputil.h"
 #include "mpegvideo.h"
@@ -142,7 +144,7 @@ static int rv40_parse_slice_header(RV34DecContext *r, GetBitContext *gb, SliceIn
     si->pts = get_bits(gb, 13);
     if(!si->type || !get_bits1(gb))
         rv40_parse_picture_size(gb, &w, &h);
-    if(avcodec_check_dimensions(r->s.avctx, w, h) < 0)
+    if(av_image_check_size(w, h, 0, r->s.avctx) < 0)
         return -1;
     si->width  = w;
     si->height = h;
@@ -307,7 +309,7 @@ static inline void rv40_weak_loop_filter(uint8_t *src, const int step,
     }
 }
 
-static inline void rv40_adaptive_loop_filter(uint8_t *src, const int step,
+static av_always_inline void rv40_adaptive_loop_filter(uint8_t *src, const int step,
                                              const int stride, const int dmode,
                                              const int lim_q1, const int lim_p1,
                                              const int alpha,
@@ -666,7 +668,7 @@ static av_cold int rv40_decode_init(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec rv40_decoder = {
+AVCodec ff_rv40_decoder = {
     "rv40",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_RV40,
diff --git a/libavcodec/rv40data.h b/libavcodec/rv40data.h
index 5566569..4787075 100644
--- a/libavcodec/rv40data.h
+++ b/libavcodec/rv40data.h
@@ -2,20 +2,20 @@
  * RealVideo 4 decoder
  * copyright (c) 2007 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -65,7 +65,7 @@ static const uint8_t rv40_luma_dc_quant[2][32] = {
 };
 
 /**
- * @begingroup loopfilter coefficients used by the RV40 loop filter
+ * @defgroup loopfilter coefficients used by the RV40 loop filter
  * @{
  */
 /**
diff --git a/libavcodec/rv40dsp.c b/libavcodec/rv40dsp.c
index 27bc79e..2271f54 100644
--- a/libavcodec/rv40dsp.c
+++ b/libavcodec/rv40dsp.c
@@ -2,20 +2,20 @@
  * RV40 decoder motion compensation functions
  * Copyright (c) 2008 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/rv40vlc2.h b/libavcodec/rv40vlc2.h
index 15119a1..2f63fc2 100644
--- a/libavcodec/rv40vlc2.h
+++ b/libavcodec/rv40vlc2.h
@@ -2,20 +2,20 @@
  * RealVideo 4 decoder
  * copyright (c) 2007 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/s3tc.c b/libavcodec/s3tc.c
index 546ee21..e8ca688 100644
--- a/libavcodec/s3tc.c
+++ b/libavcodec/s3tc.c
@@ -4,20 +4,20 @@
  *
  * see also: http://wiki.multimedia.cx/index.php?title=S3TC
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/s3tc.h b/libavcodec/s3tc.h
index 4919c07..45da6fa 100644
--- a/libavcodec/s3tc.h
+++ b/libavcodec/s3tc.h
@@ -2,20 +2,20 @@
  * S3 Texture Compression (S3TC) decoding functions
  * Copyright (c) 2007 by Ivo van Poorten
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/sbr.h b/libavcodec/sbr.h
index 2d9f4a5..cbf3e23 100644
--- a/libavcodec/sbr.h
+++ b/libavcodec/sbr.h
@@ -3,20 +3,20 @@
  * Copyright (c) 2008-2009 Robert Swain ( rob opendot cl )
  * Copyright (c) 2010      Alex Converse <alex.converse at gmail.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -31,6 +31,7 @@
 
 #include <stdint.h>
 #include "fft.h"
+#include "aacps.h"
 
 /**
  * Spectral Band Replication header - spectrum parameters that invoke a reset if they differ from the previous header.
@@ -57,7 +58,7 @@ typedef struct {
  */
 typedef struct {
     /**
-     * @defgroup bitstream     Main bitstream data variables
+     * @defgroup aac_bitstream     Main bitstream data variables
      * @{
      */
     unsigned           bs_frame_class;
@@ -133,6 +134,7 @@ typedef struct {
     ///The number of frequency bands in f_master
     unsigned           n_master;
     SBRData            data[2];
+    PSContext          ps;
     ///N_Low and N_High respectively, the number of frequency bands for low and high resolution
     unsigned           n[2];
     ///Number of noise floor bands
@@ -157,7 +159,7 @@ typedef struct {
     ///QMF output of the HF generator
     float              X_high[64][40][2];
     ///QMF values of the reconstructed signal
-    DECLARE_ALIGNED(16, float, X)[2][2][32][64];
+    DECLARE_ALIGNED(16, float, X)[2][2][38][64];
     ///Zeroth coefficient used to filter the subband signals
     float              alpha0[64][2];
     ///First coefficient used to filter the subband signals
@@ -176,7 +178,7 @@ typedef struct {
     float              s_m[7][48];
     float              gain[7][48];
     DECLARE_ALIGNED(16, float, qmf_filter_scratch)[5][64];
-    RDFTContext        rdft;
+    FFTContext         mdct_ana;
     FFTContext         mdct;
 } SpectralBandReplication;
 
diff --git a/libavcodec/sgi.h b/libavcodec/sgi.h
index be17f2e..ca531f0 100644
--- a/libavcodec/sgi.h
+++ b/libavcodec/sgi.h
@@ -2,20 +2,20 @@
  * SGI image encoder
  * Xiaohui Sun <tjnksxh at hotmail.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/sgidec.c b/libavcodec/sgidec.c
index bbfd94b..49f79b6 100644
--- a/libavcodec/sgidec.c
+++ b/libavcodec/sgidec.c
@@ -2,23 +2,24 @@
  * SGI image decoder
  * Todd Kirby <doubleshot at pacbell.net>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/imgutils.h"
 #include "avcodec.h"
 #include "bytestream.h"
 #include "sgi.h"
@@ -201,7 +202,7 @@ static int decode_frame(AVCodecContext *avctx,
         return -1;
     }
 
-    if (avcodec_check_dimensions(avctx, s->width, s->height))
+    if (av_image_check_size(s->width, s->height, 0, avctx))
         return -1;
     avcodec_set_dimensions(avctx, s->width, s->height);
 
@@ -258,7 +259,7 @@ static av_cold int sgi_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec sgi_decoder = {
+AVCodec ff_sgi_decoder = {
     "sgi",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_SGI,
diff --git a/libavcodec/sgienc.c b/libavcodec/sgienc.c
index f9f3709..805935b 100644
--- a/libavcodec/sgienc.c
+++ b/libavcodec/sgienc.c
@@ -2,20 +2,20 @@
  * SGI image encoder
  * Todd Kirby <doubleshot at pacbell.net>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -159,7 +159,7 @@ static int encode_frame(AVCodecContext *avctx, unsigned char *buf,
     return buf - orig_buf;
 }
 
-AVCodec sgi_encoder = {
+AVCodec ff_sgi_encoder = {
     "sgi",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_SGI,
diff --git a/libavcodec/sh4/dsputil_align.c b/libavcodec/sh4/dsputil_align.c
index 9e7efde..7a8d60d 100644
--- a/libavcodec/sh4/dsputil_align.c
+++ b/libavcodec/sh4/dsputil_align.c
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2001-2003 BERO <bero at geocities.co.jp>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/sh4/dsputil_sh4.c b/libavcodec/sh4/dsputil_sh4.c
index ec06e24..0c724c3 100644
--- a/libavcodec/sh4/dsputil_sh4.c
+++ b/libavcodec/sh4/dsputil_sh4.c
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2003 BERO <bero at geocities.co.jp>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/sh4/dsputil_sh4.h b/libavcodec/sh4/dsputil_sh4.h
index 2c1f77c..1a8b7af 100644
--- a/libavcodec/sh4/dsputil_sh4.h
+++ b/libavcodec/sh4/dsputil_sh4.h
@@ -1,18 +1,18 @@
 /*
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/sh4/idct_sh4.c b/libavcodec/sh4/idct_sh4.c
index 8d1a316..0758cd9 100644
--- a/libavcodec/sh4/idct_sh4.c
+++ b/libavcodec/sh4/idct_sh4.c
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2001-2003 BERO <bero at geocities.co.jp>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/sh4/qpel.c b/libavcodec/sh4/qpel.c
index 917068d..ff88b76 100644
--- a/libavcodec/sh4/qpel.c
+++ b/libavcodec/sh4/qpel.c
@@ -4,20 +4,20 @@
  *
  * copyright (c) 2001-2003 BERO <bero at geocities.co.jp>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/sh4/sh4.h b/libavcodec/sh4/sh4.h
index 5d46540..acd12e6 100644
--- a/libavcodec/sh4/sh4.h
+++ b/libavcodec/sh4/sh4.h
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2008 Mans Rullgard <mans at mansr.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/shorten.c b/libavcodec/shorten.c
index 7e17f18..f19f0fe 100644
--- a/libavcodec/shorten.c
+++ b/libavcodec/shorten.c
@@ -2,20 +2,20 @@
  * Shorten decoder
  * Copyright (c) 2005 Jeff Muizelaar
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -83,6 +83,7 @@ typedef struct ShortenContext {
 
     int32_t *decoded[MAX_CHANNELS];
     int32_t *offset[MAX_CHANNELS];
+    int *coeffs;
     uint8_t *bitstream;
     int bitstream_size;
     int bitstream_index;
@@ -104,7 +105,7 @@ static av_cold int shorten_decode_init(AVCodecContext * avctx)
 {
     ShortenContext *s = avctx->priv_data;
     s->avctx = avctx;
-    avctx->sample_fmt = SAMPLE_FMT_S16;
+    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
 
     return 0;
 }
@@ -112,6 +113,8 @@ static av_cold int shorten_decode_init(AVCodecContext * avctx)
 static int allocate_buffers(ShortenContext *s)
 {
     int i, chan;
+    int *coeffs;
+
     for (chan=0; chan<s->channels; chan++) {
         if(FFMAX(1, s->nmean) >= UINT_MAX/sizeof(int32_t)){
             av_log(s->avctx, AV_LOG_ERROR, "nmean too large\n");
@@ -129,6 +132,12 @@ static int allocate_buffers(ShortenContext *s)
             s->decoded[chan][i] = 0;
         s->decoded[chan] += s->nwrap;
     }
+
+    coeffs = av_realloc(s->coeffs, s->nwrap * sizeof(*s->coeffs));
+    if (!coeffs)
+        return AVERROR(ENOMEM);
+    s->coeffs = coeffs;
+
     return 0;
 }
 
@@ -175,12 +184,12 @@ static void init_offset(ShortenContext *s)
 
 static inline int get_le32(GetBitContext *gb)
 {
-    return bswap_32(get_bits_long(gb, 32));
+    return av_bswap32(get_bits_long(gb, 32));
 }
 
 static inline short get_le16(GetBitContext *gb)
 {
-    return bswap_16(get_bits_long(gb, 16));
+    return av_bswap16(get_bits_long(gb, 16));
 }
 
 static int decode_wave_header(AVCodecContext *avctx, uint8_t *header, int header_size)
@@ -253,7 +262,7 @@ static int16_t * interleave_buffer(int16_t *samples, int nchan, int blocksize, i
 static void decode_subframe_lpc(ShortenContext *s, int channel, int residual_size, int pred_order)
 {
     int sum, i, j;
-    int coeffs[pred_order];
+    int *coeffs = s->coeffs;
 
     for (i=0; i<pred_order; i++)
         coeffs[i] = get_sr_golomb_shorten(&s->gb, LPCQUANT);
@@ -296,7 +305,7 @@ static int shorten_decode_frame(AVCodecContext *avctx,
         s->bitstream_size= buf_size;
 
         if(buf_size < s->max_framesize){
-            //dprintf(avctx, "wanna more data ... %d\n", buf_size);
+            //av_dlog(avctx, "wanna more data ... %d\n", buf_size);
             *data_size = 0;
             return input_buf_size;
         }
@@ -427,6 +436,12 @@ static int shorten_decode_frame(AVCodecContext *avctx,
                         case FN_QLPC:
                             {
                                 int pred_order = get_ur_golomb_shorten(&s->gb, LPCQSIZE);
+                                if (pred_order > s->nwrap) {
+                                    av_log(avctx, AV_LOG_ERROR,
+                                           "invalid pred_order %d\n",
+                                           pred_order);
+                                    return -1;
+                                }
                                 for (i=0; i<pred_order; i++)
                                     s->decoded[channel][i - pred_order] -= coffset;
                                 decode_subframe_lpc(s, channel, residual_size, pred_order);
@@ -515,6 +530,7 @@ static av_cold int shorten_decode_close(AVCodecContext *avctx)
         av_freep(&s->offset[i]);
     }
     av_freep(&s->bitstream);
+    av_freep(&s->coeffs);
     return 0;
 }
 
@@ -525,7 +541,7 @@ static void shorten_flush(AVCodecContext *avctx){
         s->bitstream_index= 0;
 }
 
-AVCodec shorten_decoder = {
+AVCodec ff_shorten_decoder = {
     "shorten",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_SHORTEN,
diff --git a/libavcodec/simple_idct.c b/libavcodec/simple_idct.c
index 475be6d..4af11be 100644
--- a/libavcodec/simple_idct.c
+++ b/libavcodec/simple_idct.c
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2001 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/simple_idct.h b/libavcodec/simple_idct.h
index 24f6a6d..23bae9c 100644
--- a/libavcodec/simple_idct.h
+++ b/libavcodec/simple_idct.h
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2001 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/sinewin.c b/libavcodec/sinewin.c
new file mode 100644
index 0000000..be38dbc
--- /dev/null
+++ b/libavcodec/sinewin.c
@@ -0,0 +1,20 @@
+/*
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "sinewin.h"
+#include "sinewin_tablegen.h"
diff --git a/libavcodec/sinewin.h b/libavcodec/sinewin.h
new file mode 100644
index 0000000..2ed386a
--- /dev/null
+++ b/libavcodec/sinewin.h
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2008 Robert Swain
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_SINEWIN_H
+#define AVCODEC_SINEWIN_H
+
+#include "config.h"
+#include "libavutil/mem.h"
+
+#if CONFIG_HARDCODED_TABLES
+#   define SINETABLE_CONST const
+#else
+#   define SINETABLE_CONST
+#endif
+
+#define SINETABLE(size) \
+    SINETABLE_CONST DECLARE_ALIGNED(16, float, ff_sine_##size)[size]
+
+/**
+ * Generate a sine window.
+ * @param   window  pointer to half window
+ * @param   n       size of half window
+ */
+void ff_sine_window_init(float *window, int n);
+
+/**
+ * initialize the specified entry of ff_sine_windows
+ */
+void ff_init_ff_sine_windows(int index);
+
+extern SINETABLE(  32);
+extern SINETABLE(  64);
+extern SINETABLE( 128);
+extern SINETABLE( 256);
+extern SINETABLE( 512);
+extern SINETABLE(1024);
+extern SINETABLE(2048);
+extern SINETABLE(4096);
+
+extern SINETABLE_CONST float * const ff_sine_windows[13];
+
+#endif
diff --git a/libavcodec/sinewin_tablegen.c b/libavcodec/sinewin_tablegen.c
new file mode 100644
index 0000000..2f4d1aa
--- /dev/null
+++ b/libavcodec/sinewin_tablegen.c
@@ -0,0 +1,49 @@
+/*
+ * Generate a header file for hardcoded sine windows
+ *
+ * Copyright (c) 2009 Reimar Döffinger <Reimar.Doeffinger at gmx.de>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <stdlib.h>
+#define CONFIG_HARDCODED_TABLES 0
+#define SINETABLE_CONST
+#define SINETABLE(size) \
+    float ff_sine_##size[size]
+#define FF_ARRAY_ELEMS(a) (sizeof(a) / sizeof((a)[0]))
+#ifndef M_PI
+#define M_PI 3.14159265358979323846
+#endif
+#include "sinewin_tablegen.h"
+#include "tableprint.h"
+
+int main(void)
+{
+    int i;
+
+    write_fileheader();
+
+    for (i = 5; i <= 12; i++) {
+        ff_init_ff_sine_windows(i);
+        printf("SINETABLE(%4i) = {\n", 1 << i);
+        write_float_array(ff_sine_windows[i], 1 << i);
+        printf("};\n");
+    }
+
+    return 0;
+}
diff --git a/libavcodec/sinewin_tablegen.h b/libavcodec/sinewin_tablegen.h
new file mode 100644
index 0000000..91c26c1
--- /dev/null
+++ b/libavcodec/sinewin_tablegen.h
@@ -0,0 +1,60 @@
+/*
+ * Header file for hardcoded sine windows
+ *
+ * Copyright (c) 2009 Reimar Döffinger <Reimar.Doeffinger at gmx.de>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <assert.h>
+// do not use libavutil/libm.h since this is compiled both
+// for the host and the target and config.h is only valid for the target
+#include <math.h>
+#include "libavutil/attributes.h"
+
+#if !CONFIG_HARDCODED_TABLES
+SINETABLE(  32);
+SINETABLE(  64);
+SINETABLE( 128);
+SINETABLE( 256);
+SINETABLE( 512);
+SINETABLE(1024);
+SINETABLE(2048);
+SINETABLE(4096);
+#else
+#include "libavcodec/sinewin_tables.h"
+#endif
+
+SINETABLE_CONST float * const ff_sine_windows[] = {
+    NULL, NULL, NULL, NULL, NULL, // unused
+    ff_sine_32 , ff_sine_64 ,
+    ff_sine_128, ff_sine_256, ff_sine_512, ff_sine_1024, ff_sine_2048, ff_sine_4096
+};
+
+// Generate a sine window.
+av_cold void ff_sine_window_init(float *window, int n) {
+    int i;
+    for(i = 0; i < n; i++)
+        window[i] = sinf((i + 0.5) * (M_PI / (2.0 * n)));
+}
+
+av_cold void ff_init_ff_sine_windows(int index) {
+    assert(index >= 0 && index < FF_ARRAY_ELEMS(ff_sine_windows));
+#if !CONFIG_HARDCODED_TABLES
+    ff_sine_window_init(ff_sine_windows[index], 1 << index);
+#endif
+}
diff --git a/libavcodec/sipr.c b/libavcodec/sipr.c
index b76e891..17e7e85 100644
--- a/libavcodec/sipr.c
+++ b/libavcodec/sipr.c
@@ -4,20 +4,20 @@
  * Copyright (c) 2008 Vladimir Voroshilov
  * Copyright (c) 2009 Vitor Sessak
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -184,7 +184,7 @@ static void pitch_sharpening(int pitch_lag_int, float beta,
 }
 
 /**
- * Extracts decoding parameters from the input bitstream.
+ * Extract decoding parameters from the input bitstream.
  * @param parms          parameters structure
  * @param pgb            pointer to initialized GetBitContext structure
  */
@@ -209,32 +209,6 @@ static void decode_parameters(SiprParameters* parms, GetBitContext *pgb,
     }
 }
 
-static void lsp2lpc_sipr(const double *lsp, float *Az)
-{
-    int lp_half_order = LP_FILTER_ORDER >> 1;
-    double buf[(LP_FILTER_ORDER >> 1) + 1];
-    double pa[(LP_FILTER_ORDER >> 1) + 1];
-    double *qa = buf + 1;
-    int i,j;
-
-    qa[-1] = 0.0;
-
-    ff_lsp2polyf(lsp    , pa, lp_half_order    );
-    ff_lsp2polyf(lsp + 1, qa, lp_half_order - 1);
-
-    for (i = 1, j = LP_FILTER_ORDER - 1; i < lp_half_order; i++, j--) {
-        double paf =  pa[i]            * (1 + lsp[LP_FILTER_ORDER - 1]);
-        double qaf = (qa[i] - qa[i-2]) * (1 - lsp[LP_FILTER_ORDER - 1]);
-        Az[i-1]  = (paf + qaf) * 0.5;
-        Az[j-1]  = (paf - qaf) * 0.5;
-    }
-
-    Az[lp_half_order - 1] = (1.0 + lsp[LP_FILTER_ORDER - 1]) *
-        pa[lp_half_order] * 0.5;
-
-    Az[LP_FILTER_ORDER - 1] = lsp[LP_FILTER_ORDER - 1];
-}
-
 static void sipr_decode_lp(float *lsfnew, const float *lsfold, float *Az,
                            int num_subfr)
 {
@@ -247,14 +221,14 @@ static void sipr_decode_lp(float *lsfnew, const float *lsfold, float *Az,
         for (j = 0; j < LP_FILTER_ORDER; j++)
             lsfint[j] = lsfold[j] * (1 - t) + t * lsfnew[j];
 
-        lsp2lpc_sipr(lsfint, Az);
+        ff_amrwb_lsp2lpc(lsfint, Az, LP_FILTER_ORDER);
         Az += LP_FILTER_ORDER;
         t += t0;
     }
 }
 
 /**
- * Evaluates the adaptive impulse response.
+ * Evaluate the adaptive impulse response.
  */
 static void eval_ir(const float *Az, int pitch_lag, float *freq,
                     float pitch_sharp_factor)
@@ -276,7 +250,7 @@ static void eval_ir(const float *Az, int pitch_lag, float *freq,
 }
 
 /**
- * Evaluates the convolution of a vector with a sparse vector.
+ * Evaluate the convolution of a vector with a sparse vector.
  */
 static void convolute_with_sparse(float *out, const AMRFixed *pulses,
                                   const float *shape, int length)
@@ -519,7 +493,7 @@ static av_cold int sipr_decoder_init(AVCodecContext * avctx)
     for (i = 0; i < 4; i++)
         ctx->energy_history[i] = -14;
 
-    avctx->sample_fmt = SAMPLE_FMT_FLT;
+    avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
 
     dsputil_init(&ctx->dsp, avctx);
 
@@ -573,9 +547,9 @@ static int sipr_decode_frame(AVCodecContext *avctx, void *datap,
         mode_par->subframe_count * sizeof(float);
 
     return mode_par->bits_per_frame >> 3;
-};
+}
 
-AVCodec sipr_decoder = {
+AVCodec ff_sipr_decoder = {
     "sipr",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_SIPR,
diff --git a/libavcodec/sipr.h b/libavcodec/sipr.h
index 66e7696..33984b1 100644
--- a/libavcodec/sipr.h
+++ b/libavcodec/sipr.h
@@ -4,20 +4,20 @@
  * Copyright (c) 2008 Vladimir Voroshilov
  * Copyright (c) 2009 Vitor Sessak
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/sipr16k.c b/libavcodec/sipr16k.c
index 7fb9252..ca10cd9 100644
--- a/libavcodec/sipr16k.c
+++ b/libavcodec/sipr16k.c
@@ -4,20 +4,20 @@
  * Copyright (c) 2008 Vladimir Voroshilov
  * Copyright (c) 2009 Vitor Sessak
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/sipr16kdata.h b/libavcodec/sipr16kdata.h
index 96bf0e9..ec60c29 100644
--- a/libavcodec/sipr16kdata.h
+++ b/libavcodec/sipr16kdata.h
@@ -4,20 +4,20 @@
  * Copyright (c) 2008 Vladimir Voroshilov
  * Copyright (c) 2009 Vitor Sessak
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/siprdata.h b/libavcodec/siprdata.h
index ed804ee..92037a4 100644
--- a/libavcodec/siprdata.h
+++ b/libavcodec/siprdata.h
@@ -4,20 +4,20 @@
  * Copyright (c) 2008 Vladimir Voroshilov
  * Copyright (c) 2009 Vitor Sessak
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/smacker.c b/libavcodec/smacker.c
index 1d85f68..3a97b72 100644
--- a/libavcodec/smacker.c
+++ b/libavcodec/smacker.c
@@ -2,20 +2,20 @@
  * Smacker decoder
  * Copyright (c) 2006 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -32,6 +32,7 @@
 #include <stdlib.h>
 
 #include "avcodec.h"
+#include "libavutil/audioconvert.h"
 
 #define ALT_BITSTREAM_READER_LE
 #include "get_bits.h"
@@ -167,7 +168,7 @@ static int smacker_decode_bigtree(GetBitContext *gb, HuffContext *hc, DBCtx *ctx
 }
 
 /**
- * Store large tree as FFmpeg's vlc codes
+ * Store large tree as Libav's vlc codes
  */
 static int smacker_decode_header_tree(SmackVContext *smk, GetBitContext *gb, int **recodes, int *last, int size)
 {
@@ -554,8 +555,8 @@ static av_cold int decode_end(AVCodecContext *avctx)
 
 static av_cold int smka_decode_init(AVCodecContext *avctx)
 {
-    avctx->channel_layout = (avctx->channels==2) ? CH_LAYOUT_STEREO : CH_LAYOUT_MONO;
-    avctx->sample_fmt = avctx->bits_per_coded_sample == 8 ? SAMPLE_FMT_U8 : SAMPLE_FMT_S16;
+    avctx->channel_layout = (avctx->channels==2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;
+    avctx->sample_fmt = avctx->bits_per_coded_sample == 8 ? AV_SAMPLE_FMT_U8 : AV_SAMPLE_FMT_S16;
     return 0;
 }
 
@@ -618,7 +619,7 @@ static int smka_decode_frame(AVCodecContext *avctx, void *data, int *data_size,
     }
     if(bits) { //decode 16-bit data
         for(i = stereo; i >= 0; i--)
-            pred[i] = bswap_16(get_bits(&gb, 16));
+            pred[i] = av_bswap16(get_bits(&gb, 16));
         for(i = 0; i < stereo; i++)
             *samples++ = pred[i];
         for(i = 0; i < unp_size / 2; i++) {
@@ -677,19 +678,16 @@ static int smka_decode_frame(AVCodecContext *avctx, void *data, int *data_size,
     for(i = 0; i < 4; i++) {
         if(vlc[i].table)
             free_vlc(&vlc[i]);
-        if(h[i].bits)
-            av_free(h[i].bits);
-        if(h[i].lengths)
-            av_free(h[i].lengths);
-        if(h[i].values)
-            av_free(h[i].values);
+        av_free(h[i].bits);
+        av_free(h[i].lengths);
+        av_free(h[i].values);
     }
 
     *data_size = unp_size;
     return buf_size;
 }
 
-AVCodec smacker_decoder = {
+AVCodec ff_smacker_decoder = {
     "smackvid",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_SMACKVIDEO,
@@ -702,7 +700,7 @@ AVCodec smacker_decoder = {
     .long_name = NULL_IF_CONFIG_SMALL("Smacker video"),
 };
 
-AVCodec smackaud_decoder = {
+AVCodec ff_smackaud_decoder = {
     "smackaud",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_SMACKAUDIO,
diff --git a/libavcodec/smc.c b/libavcodec/smc.c
index 2e2dffd..e75203d 100644
--- a/libavcodec/smc.c
+++ b/libavcodec/smc.c
@@ -2,20 +2,20 @@
  * Quicktime Graphics (SMC) Video Decoder
  * Copyright (C) 2003 the ffmpeg project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -54,6 +54,7 @@ typedef struct SmcContext {
     unsigned char color_quads[COLORS_PER_TABLE * CQUAD];
     unsigned char color_octets[COLORS_PER_TABLE * COCTET];
 
+    uint32_t pal[256];
 } SmcContext;
 
 #define GET_BLOCK_COUNT() \
@@ -110,11 +111,7 @@ static void smc_decode_stream(SmcContext *s)
     int color_octet_index = 0;
 
     /* make the palette available */
-    memcpy(s->frame.data[1], s->avctx->palctrl->palette, AVPALETTE_SIZE);
-    if (s->avctx->palctrl->palette_changed) {
-        s->frame.palette_has_changed = 1;
-        s->avctx->palctrl->palette_changed = 0;
-    }
+    memcpy(s->frame.data[1], s->pal, AVPALETTE_SIZE);
 
     chunk_size = AV_RB32(&s->buf[stream_ptr]) & 0x00FFFFFF;
     stream_ptr += 4;
@@ -440,6 +437,7 @@ static int smc_decode_frame(AVCodecContext *avctx,
     const uint8_t *buf = avpkt->data;
     int buf_size = avpkt->size;
     SmcContext *s = avctx->priv_data;
+    const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, NULL);
 
     s->buf = buf;
     s->size = buf_size;
@@ -452,6 +450,11 @@ static int smc_decode_frame(AVCodecContext *avctx,
         return -1;
     }
 
+    if (pal) {
+        s->frame.palette_has_changed = 1;
+        memcpy(s->pal, pal, AVPALETTE_SIZE);
+    }
+
     smc_decode_stream(s);
 
     *data_size = sizeof(AVFrame);
@@ -471,7 +474,7 @@ static av_cold int smc_decode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec smc_decoder = {
+AVCodec ff_smc_decoder = {
     "smc",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_SMC,
diff --git a/libavcodec/snow.c b/libavcodec/snow.c
index 5ef9e5e..42145f5 100644
--- a/libavcodec/snow.c
+++ b/libavcodec/snow.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (C) 2004 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -920,7 +920,7 @@ static void decode_blocks(SnowContext *s){
     }
 }
 
-static void mc_block(Plane *p, uint8_t *dst, const uint8_t *src, uint8_t *tmp, int stride, int b_w, int b_h, int dx, int dy){
+static void mc_block(Plane *p, uint8_t *dst, const uint8_t *src, int stride, int b_w, int b_h, int dx, int dy){
     static const uint8_t weight[64]={
     8,7,6,5,4,3,2,1,
     7,7,0,0,0,0,0,1,
@@ -1106,9 +1106,8 @@ static void mc_block(Plane *p, uint8_t *dst, const uint8_t *src, uint8_t *tmp, i
 
 #define mca(dx,dy,b_w)\
 static void mc_block_hpel ## dx ## dy ## b_w(uint8_t *dst, const uint8_t *src, int stride, int h){\
-    uint8_t tmp[stride*(b_w+HTAPS_MAX-1)];\
     assert(h==b_w);\
-    mc_block(NULL, dst, src-(HTAPS_MAX/2-1)-(HTAPS_MAX/2-1)*stride, tmp, stride, b_w, b_w, dx, dy);\
+    mc_block(NULL, dst, src-(HTAPS_MAX/2-1)-(HTAPS_MAX/2-1)*stride, stride, b_w, b_w, dx, dy);\
 }
 
 mca( 0, 0,16)
@@ -1172,7 +1171,7 @@ static void pred_block(SnowContext *s, uint8_t *dst, uint8_t *tmp, int stride, i
         src += sx + sy*stride;
         if(   (unsigned)sx >= w - b_w - (HTAPS_MAX-2)
            || (unsigned)sy >= h - b_h - (HTAPS_MAX-2)){
-            ff_emulated_edge_mc(tmp + MB_SIZE, src, stride, b_w+HTAPS_MAX-1, b_h+HTAPS_MAX-1, sx, sy, w, h);
+            s->dsp.emulated_edge_mc(tmp + MB_SIZE, src, stride, b_w+HTAPS_MAX-1, b_h+HTAPS_MAX-1, sx, sy, w, h);
             src= tmp + MB_SIZE;
         }
 //        assert(b_w == b_h || 2*b_w == b_h || b_w == 2*b_h);
@@ -1180,7 +1179,7 @@ static void pred_block(SnowContext *s, uint8_t *dst, uint8_t *tmp, int stride, i
         assert(b_w>1 && b_h>1);
         assert((tab_index>=0 && tab_index<4) || b_w==32);
         if((dx&3) || (dy&3) || !(b_w == b_h || 2*b_w == b_h || b_w == 2*b_h) || (b_w&(b_w-1)) || !s->plane[plane_index].fast_mc )
-            mc_block(&s->plane[plane_index], dst, src, tmp, stride, b_w, b_h, dx, dy);
+            mc_block(&s->plane[plane_index], dst, src, stride, b_w, b_h, dx, dy);
         else if(b_w==32){
             int y;
             for(y=0; y<b_h; y+=16){
@@ -1977,9 +1976,15 @@ static int frame_start(SnowContext *s){
    int h= s->avctx->height;
 
     if(s->current_picture.data[0]){
-        s->dsp.draw_edges(s->current_picture.data[0], s->current_picture.linesize[0], w   , h   , EDGE_WIDTH  );
-        s->dsp.draw_edges(s->current_picture.data[1], s->current_picture.linesize[1], w>>1, h>>1, EDGE_WIDTH/2);
-        s->dsp.draw_edges(s->current_picture.data[2], s->current_picture.linesize[2], w>>1, h>>1, EDGE_WIDTH/2);
+        s->dsp.draw_edges(s->current_picture.data[0],
+                          s->current_picture.linesize[0], w   , h   ,
+                          EDGE_WIDTH  , EDGE_TOP | EDGE_BOTTOM);
+        s->dsp.draw_edges(s->current_picture.data[1],
+                          s->current_picture.linesize[1], w>>1, h>>1,
+                          EDGE_WIDTH/2, EDGE_TOP | EDGE_BOTTOM);
+        s->dsp.draw_edges(s->current_picture.data[2],
+                          s->current_picture.linesize[2], w>>1, h>>1,
+                          EDGE_WIDTH/2, EDGE_TOP | EDGE_BOTTOM);
     }
 
     release_buffer(s->avctx);
@@ -2235,7 +2240,7 @@ static av_cold int decode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec snow_decoder = {
+AVCodec ff_snow_decoder = {
     "snow",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_SNOW,
@@ -3986,7 +3991,7 @@ static av_cold int encode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec snow_encoder = {
+AVCodec ff_snow_encoder = {
     "snow",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_SNOW,
diff --git a/libavcodec/snow.h b/libavcodec/snow.h
index 7d847e4..db61b87 100644
--- a/libavcodec/snow.h
+++ b/libavcodec/snow.h
@@ -2,20 +2,20 @@
  * Copyright (C) 2004 Michael Niedermayer <michaelni at gmx.at>
  * Copyright (C) 2006 Robert Edele <yartrebo at earthlink.net>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/sonic.c b/libavcodec/sonic.c
deleted file mode 100644
index d24931f..0000000
--- a/libavcodec/sonic.c
+++ /dev/null
@@ -1,977 +0,0 @@
-/*
- * Simple free lossless/lossy audio codec
- * Copyright (c) 2004 Alex Beregszaszi
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-#include "avcodec.h"
-#include "get_bits.h"
-#include "golomb.h"
-
-/**
- * @file
- * Simple free lossless/lossy audio codec
- * Based on Paul Francis Harrison's Bonk (http://www.logarithmic.net/pfh/bonk)
- * Written and designed by Alex Beregszaszi
- *
- * TODO:
- *  - CABAC put/get_symbol
- *  - independent quantizer for channels
- *  - >2 channels support
- *  - more decorrelation types
- *  - more tap_quant tests
- *  - selectable intlist writers/readers (bonk-style, golomb, cabac)
- */
-
-#define MAX_CHANNELS 2
-
-#define MID_SIDE 0
-#define LEFT_SIDE 1
-#define RIGHT_SIDE 2
-
-typedef struct SonicContext {
-    int lossless, decorrelation;
-
-    int num_taps, downsampling;
-    double quantization;
-
-    int channels, samplerate, block_align, frame_size;
-
-    int *tap_quant;
-    int *int_samples;
-    int *coded_samples[MAX_CHANNELS];
-
-    // for encoding
-    int *tail;
-    int tail_size;
-    int *window;
-    int window_size;
-
-    // for decoding
-    int *predictor_k;
-    int *predictor_state[MAX_CHANNELS];
-} SonicContext;
-
-#define LATTICE_SHIFT   10
-#define SAMPLE_SHIFT    4
-#define LATTICE_FACTOR  (1 << LATTICE_SHIFT)
-#define SAMPLE_FACTOR   (1 << SAMPLE_SHIFT)
-
-#define BASE_QUANT      0.6
-#define RATE_VARIATION  3.0
-
-static inline int divide(int a, int b)
-{
-    if (a < 0)
-        return -( (-a + b/2)/b );
-    else
-        return (a + b/2)/b;
-}
-
-static inline int shift(int a,int b)
-{
-    return (a+(1<<(b-1))) >> b;
-}
-
-static inline int shift_down(int a,int b)
-{
-    return (a>>b)+((a<0)?1:0);
-}
-
-#if 1
-static inline int intlist_write(PutBitContext *pb, int *buf, int entries, int base_2_part)
-{
-    int i;
-
-    for (i = 0; i < entries; i++)
-        set_se_golomb(pb, buf[i]);
-
-    return 1;
-}
-
-static inline int intlist_read(GetBitContext *gb, int *buf, int entries, int base_2_part)
-{
-    int i;
-
-    for (i = 0; i < entries; i++)
-        buf[i] = get_se_golomb(gb);
-
-    return 1;
-}
-
-#else
-
-#define ADAPT_LEVEL 8
-
-static int bits_to_store(uint64_t x)
-{
-    int res = 0;
-
-    while(x)
-    {
-        res++;
-        x >>= 1;
-    }
-    return res;
-}
-
-static void write_uint_max(PutBitContext *pb, unsigned int value, unsigned int max)
-{
-    int i, bits;
-
-    if (!max)
-        return;
-
-    bits = bits_to_store(max);
-
-    for (i = 0; i < bits-1; i++)
-        put_bits(pb, 1, value & (1 << i));
-
-    if ( (value | (1 << (bits-1))) <= max)
-        put_bits(pb, 1, value & (1 << (bits-1)));
-}
-
-static unsigned int read_uint_max(GetBitContext *gb, int max)
-{
-    int i, bits, value = 0;
-
-    if (!max)
-        return 0;
-
-    bits = bits_to_store(max);
-
-    for (i = 0; i < bits-1; i++)
-        if (get_bits1(gb))
-            value += 1 << i;
-
-    if ( (value | (1<<(bits-1))) <= max)
-        if (get_bits1(gb))
-            value += 1 << (bits-1);
-
-    return value;
-}
-
-static int intlist_write(PutBitContext *pb, int *buf, int entries, int base_2_part)
-{
-    int i, j, x = 0, low_bits = 0, max = 0;
-    int step = 256, pos = 0, dominant = 0, any = 0;
-    int *copy, *bits;
-
-    copy = av_mallocz(4* entries);
-    if (!copy)
-        return -1;
-
-    if (base_2_part)
-    {
-        int energy = 0;
-
-        for (i = 0; i < entries; i++)
-            energy += abs(buf[i]);
-
-        low_bits = bits_to_store(energy / (entries * 2));
-        if (low_bits > 15)
-            low_bits = 15;
-
-        put_bits(pb, 4, low_bits);
-    }
-
-    for (i = 0; i < entries; i++)
-    {
-        put_bits(pb, low_bits, abs(buf[i]));
-        copy[i] = abs(buf[i]) >> low_bits;
-        if (copy[i] > max)
-            max = abs(copy[i]);
-    }
-
-    bits = av_mallocz(4* entries*max);
-    if (!bits)
-    {
-//        av_free(copy);
-        return -1;
-    }
-
-    for (i = 0; i <= max; i++)
-    {
-        for (j = 0; j < entries; j++)
-            if (copy[j] >= i)
-                bits[x++] = copy[j] > i;
-    }
-
-    // store bitstream
-    while (pos < x)
-    {
-        int steplet = step >> 8;
-
-        if (pos + steplet > x)
-            steplet = x - pos;
-
-        for (i = 0; i < steplet; i++)
-            if (bits[i+pos] != dominant)
-                any = 1;
-
-        put_bits(pb, 1, any);
-
-        if (!any)
-        {
-            pos += steplet;
-            step += step / ADAPT_LEVEL;
-        }
-        else
-        {
-            int interloper = 0;
-
-            while (((pos + interloper) < x) && (bits[pos + interloper] == dominant))
-                interloper++;
-
-            // note change
-            write_uint_max(pb, interloper, (step >> 8) - 1);
-
-            pos += interloper + 1;
-            step -= step / ADAPT_LEVEL;
-        }
-
-        if (step < 256)
-        {
-            step = 65536 / step;
-            dominant = !dominant;
-        }
-    }
-
-    // store signs
-    for (i = 0; i < entries; i++)
-        if (buf[i])
-            put_bits(pb, 1, buf[i] < 0);
-
-//    av_free(bits);
-//    av_free(copy);
-
-    return 0;
-}
-
-static int intlist_read(GetBitContext *gb, int *buf, int entries, int base_2_part)
-{
-    int i, low_bits = 0, x = 0;
-    int n_zeros = 0, step = 256, dominant = 0;
-    int pos = 0, level = 0;
-    int *bits = av_mallocz(4* entries);
-
-    if (!bits)
-        return -1;
-
-    if (base_2_part)
-    {
-        low_bits = get_bits(gb, 4);
-
-        if (low_bits)
-            for (i = 0; i < entries; i++)
-                buf[i] = get_bits(gb, low_bits);
-    }
-
-//    av_log(NULL, AV_LOG_INFO, "entries: %d, low bits: %d\n", entries, low_bits);
-
-    while (n_zeros < entries)
-    {
-        int steplet = step >> 8;
-
-        if (!get_bits1(gb))
-        {
-            for (i = 0; i < steplet; i++)
-                bits[x++] = dominant;
-
-            if (!dominant)
-                n_zeros += steplet;
-
-            step += step / ADAPT_LEVEL;
-        }
-        else
-        {
-            int actual_run = read_uint_max(gb, steplet-1);
-
-//            av_log(NULL, AV_LOG_INFO, "actual run: %d\n", actual_run);
-
-            for (i = 0; i < actual_run; i++)
-                bits[x++] = dominant;
-
-            bits[x++] = !dominant;
-
-            if (!dominant)
-                n_zeros += actual_run;
-            else
-                n_zeros++;
-
-            step -= step / ADAPT_LEVEL;
-        }
-
-        if (step < 256)
-        {
-            step = 65536 / step;
-            dominant = !dominant;
-        }
-    }
-
-    // reconstruct unsigned values
-    n_zeros = 0;
-    for (i = 0; n_zeros < entries; i++)
-    {
-        while(1)
-        {
-            if (pos >= entries)
-            {
-                pos = 0;
-                level += 1 << low_bits;
-            }
-
-            if (buf[pos] >= level)
-                break;
-
-            pos++;
-        }
-
-        if (bits[i])
-            buf[pos] += 1 << low_bits;
-        else
-            n_zeros++;
-
-        pos++;
-    }
-//    av_free(bits);
-
-    // read signs
-    for (i = 0; i < entries; i++)
-        if (buf[i] && get_bits1(gb))
-            buf[i] = -buf[i];
-
-//    av_log(NULL, AV_LOG_INFO, "zeros: %d pos: %d\n", n_zeros, pos);
-
-    return 0;
-}
-#endif
-
-static void predictor_init_state(int *k, int *state, int order)
-{
-    int i;
-
-    for (i = order-2; i >= 0; i--)
-    {
-        int j, p, x = state[i];
-
-        for (j = 0, p = i+1; p < order; j++,p++)
-            {
-            int tmp = x + shift_down(k[j] * state[p], LATTICE_SHIFT);
-            state[p] += shift_down(k[j]*x, LATTICE_SHIFT);
-            x = tmp;
-        }
-    }
-}
-
-static int predictor_calc_error(int *k, int *state, int order, int error)
-{
-    int i, x = error - shift_down(k[order-1] * state[order-1], LATTICE_SHIFT);
-
-#if 1
-    int *k_ptr = &(k[order-2]),
-        *state_ptr = &(state[order-2]);
-    for (i = order-2; i >= 0; i--, k_ptr--, state_ptr--)
-    {
-        int k_value = *k_ptr, state_value = *state_ptr;
-        x -= shift_down(k_value * state_value, LATTICE_SHIFT);
-        state_ptr[1] = state_value + shift_down(k_value * x, LATTICE_SHIFT);
-    }
-#else
-    for (i = order-2; i >= 0; i--)
-    {
-        x -= shift_down(k[i] * state[i], LATTICE_SHIFT);
-        state[i+1] = state[i] + shift_down(k[i] * x, LATTICE_SHIFT);
-    }
-#endif
-
-    // don't drift too far, to avoid overflows
-    if (x >  (SAMPLE_FACTOR<<16)) x =  (SAMPLE_FACTOR<<16);
-    if (x < -(SAMPLE_FACTOR<<16)) x = -(SAMPLE_FACTOR<<16);
-
-    state[0] = x;
-
-    return x;
-}
-
-#if CONFIG_SONIC_ENCODER || CONFIG_SONIC_LS_ENCODER
-// Heavily modified Levinson-Durbin algorithm which
-// copes better with quantization, and calculates the
-// actual whitened result as it goes.
-
-static void modified_levinson_durbin(int *window, int window_entries,
-        int *out, int out_entries, int channels, int *tap_quant)
-{
-    int i;
-    int *state = av_mallocz(4* window_entries);
-
-    memcpy(state, window, 4* window_entries);
-
-    for (i = 0; i < out_entries; i++)
-    {
-        int step = (i+1)*channels, k, j;
-        double xx = 0.0, xy = 0.0;
-#if 1
-        int *x_ptr = &(window[step]), *state_ptr = &(state[0]);
-        j = window_entries - step;
-        for (;j>=0;j--,x_ptr++,state_ptr++)
-        {
-            double x_value = *x_ptr, state_value = *state_ptr;
-            xx += state_value*state_value;
-            xy += x_value*state_value;
-        }
-#else
-        for (j = 0; j <= (window_entries - step); j++);
-        {
-            double stepval = window[step+j], stateval = window[j];
-//            xx += (double)window[j]*(double)window[j];
-//            xy += (double)window[step+j]*(double)window[j];
-            xx += stateval*stateval;
-            xy += stepval*stateval;
-        }
-#endif
-        if (xx == 0.0)
-            k = 0;
-        else
-            k = (int)(floor(-xy/xx * (double)LATTICE_FACTOR / (double)(tap_quant[i]) + 0.5));
-
-        if (k > (LATTICE_FACTOR/tap_quant[i]))
-            k = LATTICE_FACTOR/tap_quant[i];
-        if (-k > (LATTICE_FACTOR/tap_quant[i]))
-            k = -(LATTICE_FACTOR/tap_quant[i]);
-
-        out[i] = k;
-        k *= tap_quant[i];
-
-#if 1
-        x_ptr = &(window[step]);
-        state_ptr = &(state[0]);
-        j = window_entries - step;
-        for (;j>=0;j--,x_ptr++,state_ptr++)
-        {
-            int x_value = *x_ptr, state_value = *state_ptr;
-            *x_ptr = x_value + shift_down(k*state_value,LATTICE_SHIFT);
-            *state_ptr = state_value + shift_down(k*x_value, LATTICE_SHIFT);
-        }
-#else
-        for (j=0; j <= (window_entries - step); j++)
-        {
-            int stepval = window[step+j], stateval=state[j];
-            window[step+j] += shift_down(k * stateval, LATTICE_SHIFT);
-            state[j] += shift_down(k * stepval, LATTICE_SHIFT);
-        }
-#endif
-    }
-
-    av_free(state);
-}
-
-static inline int code_samplerate(int samplerate)
-{
-    switch (samplerate)
-    {
-        case 44100: return 0;
-        case 22050: return 1;
-        case 11025: return 2;
-        case 96000: return 3;
-        case 48000: return 4;
-        case 32000: return 5;
-        case 24000: return 6;
-        case 16000: return 7;
-        case 8000: return 8;
-    }
-    return -1;
-}
-
-static av_cold int sonic_encode_init(AVCodecContext *avctx)
-{
-    SonicContext *s = avctx->priv_data;
-    PutBitContext pb;
-    int i, version = 0;
-
-    if (avctx->channels > MAX_CHANNELS)
-    {
-        av_log(avctx, AV_LOG_ERROR, "Only mono and stereo streams are supported by now\n");
-        return -1; /* only stereo or mono for now */
-    }
-
-    if (avctx->channels == 2)
-        s->decorrelation = MID_SIDE;
-
-    if (avctx->codec->id == CODEC_ID_SONIC_LS)
-    {
-        s->lossless = 1;
-        s->num_taps = 32;
-        s->downsampling = 1;
-        s->quantization = 0.0;
-    }
-    else
-    {
-        s->num_taps = 128;
-        s->downsampling = 2;
-        s->quantization = 1.0;
-    }
-
-    // max tap 2048
-    if ((s->num_taps < 32) || (s->num_taps > 1024) ||
-        ((s->num_taps>>5)<<5 != s->num_taps))
-    {
-        av_log(avctx, AV_LOG_ERROR, "Invalid number of taps\n");
-        return -1;
-    }
-
-    // generate taps
-    s->tap_quant = av_mallocz(4* s->num_taps);
-    for (i = 0; i < s->num_taps; i++)
-        s->tap_quant[i] = (int)(sqrt(i+1));
-
-    s->channels = avctx->channels;
-    s->samplerate = avctx->sample_rate;
-
-    s->block_align = (int)(2048.0*s->samplerate/44100)/s->downsampling;
-    s->frame_size = s->channels*s->block_align*s->downsampling;
-
-    s->tail = av_mallocz(4* s->num_taps*s->channels);
-    if (!s->tail)
-        return -1;
-    s->tail_size = s->num_taps*s->channels;
-
-    s->predictor_k = av_mallocz(4 * s->num_taps);
-    if (!s->predictor_k)
-        return -1;
-
-    for (i = 0; i < s->channels; i++)
-    {
-        s->coded_samples[i] = av_mallocz(4* s->block_align);
-        if (!s->coded_samples[i])
-            return -1;
-    }
-
-    s->int_samples = av_mallocz(4* s->frame_size);
-
-    s->window_size = ((2*s->tail_size)+s->frame_size);
-    s->window = av_mallocz(4* s->window_size);
-    if (!s->window)
-        return -1;
-
-    avctx->extradata = av_mallocz(16);
-    if (!avctx->extradata)
-        return -1;
-    init_put_bits(&pb, avctx->extradata, 16*8);
-
-    put_bits(&pb, 2, version); // version
-    if (version == 1)
-    {
-        put_bits(&pb, 2, s->channels);
-        put_bits(&pb, 4, code_samplerate(s->samplerate));
-    }
-    put_bits(&pb, 1, s->lossless);
-    if (!s->lossless)
-        put_bits(&pb, 3, SAMPLE_SHIFT); // XXX FIXME: sample precision
-    put_bits(&pb, 2, s->decorrelation);
-    put_bits(&pb, 2, s->downsampling);
-    put_bits(&pb, 5, (s->num_taps >> 5)-1); // 32..1024
-    put_bits(&pb, 1, 0); // XXX FIXME: no custom tap quant table
-
-    flush_put_bits(&pb);
-    avctx->extradata_size = put_bits_count(&pb)/8;
-
-    av_log(avctx, AV_LOG_INFO, "Sonic: ver: %d ls: %d dr: %d taps: %d block: %d frame: %d downsamp: %d\n",
-        version, s->lossless, s->decorrelation, s->num_taps, s->block_align, s->frame_size, s->downsampling);
-
-    avctx->coded_frame = avcodec_alloc_frame();
-    if (!avctx->coded_frame)
-        return AVERROR(ENOMEM);
-    avctx->coded_frame->key_frame = 1;
-    avctx->frame_size = s->block_align*s->downsampling;
-
-    return 0;
-}
-
-static av_cold int sonic_encode_close(AVCodecContext *avctx)
-{
-    SonicContext *s = avctx->priv_data;
-    int i;
-
-    av_freep(&avctx->coded_frame);
-
-    for (i = 0; i < s->channels; i++)
-        av_free(s->coded_samples[i]);
-
-    av_free(s->predictor_k);
-    av_free(s->tail);
-    av_free(s->tap_quant);
-    av_free(s->window);
-    av_free(s->int_samples);
-
-    return 0;
-}
-
-static int sonic_encode_frame(AVCodecContext *avctx,
-                            uint8_t *buf, int buf_size, void *data)
-{
-    SonicContext *s = avctx->priv_data;
-    PutBitContext pb;
-    int i, j, ch, quant = 0, x = 0;
-    short *samples = data;
-
-    init_put_bits(&pb, buf, buf_size*8);
-
-    // short -> internal
-    for (i = 0; i < s->frame_size; i++)
-        s->int_samples[i] = samples[i];
-
-    if (!s->lossless)
-        for (i = 0; i < s->frame_size; i++)
-            s->int_samples[i] = s->int_samples[i] << SAMPLE_SHIFT;
-
-    switch(s->decorrelation)
-    {
-        case MID_SIDE:
-            for (i = 0; i < s->frame_size; i += s->channels)
-            {
-                s->int_samples[i] += s->int_samples[i+1];
-                s->int_samples[i+1] -= shift(s->int_samples[i], 1);
-            }
-            break;
-        case LEFT_SIDE:
-            for (i = 0; i < s->frame_size; i += s->channels)
-                s->int_samples[i+1] -= s->int_samples[i];
-            break;
-        case RIGHT_SIDE:
-            for (i = 0; i < s->frame_size; i += s->channels)
-                s->int_samples[i] -= s->int_samples[i+1];
-            break;
-    }
-
-    memset(s->window, 0, 4* s->window_size);
-
-    for (i = 0; i < s->tail_size; i++)
-        s->window[x++] = s->tail[i];
-
-    for (i = 0; i < s->frame_size; i++)
-        s->window[x++] = s->int_samples[i];
-
-    for (i = 0; i < s->tail_size; i++)
-        s->window[x++] = 0;
-
-    for (i = 0; i < s->tail_size; i++)
-        s->tail[i] = s->int_samples[s->frame_size - s->tail_size + i];
-
-    // generate taps
-    modified_levinson_durbin(s->window, s->window_size,
-                s->predictor_k, s->num_taps, s->channels, s->tap_quant);
-    if (intlist_write(&pb, s->predictor_k, s->num_taps, 0) < 0)
-        return -1;
-
-    for (ch = 0; ch < s->channels; ch++)
-    {
-        x = s->tail_size+ch;
-        for (i = 0; i < s->block_align; i++)
-        {
-            int sum = 0;
-            for (j = 0; j < s->downsampling; j++, x += s->channels)
-                sum += s->window[x];
-            s->coded_samples[ch][i] = sum;
-        }
-    }
-
-    // simple rate control code
-    if (!s->lossless)
-    {
-        double energy1 = 0.0, energy2 = 0.0;
-        for (ch = 0; ch < s->channels; ch++)
-        {
-            for (i = 0; i < s->block_align; i++)
-            {
-                double sample = s->coded_samples[ch][i];
-                energy2 += sample*sample;
-                energy1 += fabs(sample);
-            }
-        }
-
-        energy2 = sqrt(energy2/(s->channels*s->block_align));
-        energy1 = sqrt(2.0)*energy1/(s->channels*s->block_align);
-
-        // increase bitrate when samples are like a gaussian distribution
-        // reduce bitrate when samples are like a two-tailed exponential distribution
-
-        if (energy2 > energy1)
-            energy2 += (energy2-energy1)*RATE_VARIATION;
-
-        quant = (int)(BASE_QUANT*s->quantization*energy2/SAMPLE_FACTOR);
-//        av_log(avctx, AV_LOG_DEBUG, "quant: %d energy: %f / %f\n", quant, energy1, energy2);
-
-        if (quant < 1)
-            quant = 1;
-        if (quant > 65535)
-            quant = 65535;
-
-        set_ue_golomb(&pb, quant);
-
-        quant *= SAMPLE_FACTOR;
-    }
-
-    // write out coded samples
-    for (ch = 0; ch < s->channels; ch++)
-    {
-        if (!s->lossless)
-            for (i = 0; i < s->block_align; i++)
-                s->coded_samples[ch][i] = divide(s->coded_samples[ch][i], quant);
-
-        if (intlist_write(&pb, s->coded_samples[ch], s->block_align, 1) < 0)
-            return -1;
-    }
-
-//    av_log(avctx, AV_LOG_DEBUG, "used bytes: %d\n", (put_bits_count(&pb)+7)/8);
-
-    flush_put_bits(&pb);
-    return (put_bits_count(&pb)+7)/8;
-}
-#endif /* CONFIG_SONIC_ENCODER || CONFIG_SONIC_LS_ENCODER */
-
-#if CONFIG_SONIC_DECODER
-static const int samplerate_table[] =
-    { 44100, 22050, 11025, 96000, 48000, 32000, 24000, 16000, 8000 };
-
-static av_cold int sonic_decode_init(AVCodecContext *avctx)
-{
-    SonicContext *s = avctx->priv_data;
-    GetBitContext gb;
-    int i, version;
-
-    s->channels = avctx->channels;
-    s->samplerate = avctx->sample_rate;
-
-    if (!avctx->extradata)
-    {
-        av_log(avctx, AV_LOG_ERROR, "No mandatory headers present\n");
-        return -1;
-    }
-
-    init_get_bits(&gb, avctx->extradata, avctx->extradata_size);
-
-    version = get_bits(&gb, 2);
-    if (version > 1)
-    {
-        av_log(avctx, AV_LOG_ERROR, "Unsupported Sonic version, please report\n");
-        return -1;
-    }
-
-    if (version == 1)
-    {
-        s->channels = get_bits(&gb, 2);
-        s->samplerate = samplerate_table[get_bits(&gb, 4)];
-        av_log(avctx, AV_LOG_INFO, "Sonicv2 chans: %d samprate: %d\n",
-            s->channels, s->samplerate);
-    }
-
-    if (s->channels > MAX_CHANNELS)
-    {
-        av_log(avctx, AV_LOG_ERROR, "Only mono and stereo streams are supported by now\n");
-        return -1;
-    }
-
-    s->lossless = get_bits1(&gb);
-    if (!s->lossless)
-        skip_bits(&gb, 3); // XXX FIXME
-    s->decorrelation = get_bits(&gb, 2);
-
-    s->downsampling = get_bits(&gb, 2);
-    s->num_taps = (get_bits(&gb, 5)+1)<<5;
-    if (get_bits1(&gb)) // XXX FIXME
-        av_log(avctx, AV_LOG_INFO, "Custom quant table\n");
-
-    s->block_align = (int)(2048.0*(s->samplerate/44100))/s->downsampling;
-    s->frame_size = s->channels*s->block_align*s->downsampling;
-//    avctx->frame_size = s->block_align;
-
-    av_log(avctx, AV_LOG_INFO, "Sonic: ver: %d ls: %d dr: %d taps: %d block: %d frame: %d downsamp: %d\n",
-        version, s->lossless, s->decorrelation, s->num_taps, s->block_align, s->frame_size, s->downsampling);
-
-    // generate taps
-    s->tap_quant = av_mallocz(4* s->num_taps);
-    for (i = 0; i < s->num_taps; i++)
-        s->tap_quant[i] = (int)(sqrt(i+1));
-
-    s->predictor_k = av_mallocz(4* s->num_taps);
-
-    for (i = 0; i < s->channels; i++)
-    {
-        s->predictor_state[i] = av_mallocz(4* s->num_taps);
-        if (!s->predictor_state[i])
-            return -1;
-    }
-
-    for (i = 0; i < s->channels; i++)
-    {
-        s->coded_samples[i] = av_mallocz(4* s->block_align);
-        if (!s->coded_samples[i])
-            return -1;
-    }
-    s->int_samples = av_mallocz(4* s->frame_size);
-
-    avctx->sample_fmt = SAMPLE_FMT_S16;
-    return 0;
-}
-
-static av_cold int sonic_decode_close(AVCodecContext *avctx)
-{
-    SonicContext *s = avctx->priv_data;
-    int i;
-
-    av_free(s->int_samples);
-    av_free(s->tap_quant);
-    av_free(s->predictor_k);
-
-    for (i = 0; i < s->channels; i++)
-    {
-        av_free(s->predictor_state[i]);
-        av_free(s->coded_samples[i]);
-    }
-
-    return 0;
-}
-
-static int sonic_decode_frame(AVCodecContext *avctx,
-                            void *data, int *data_size,
-                            AVPacket *avpkt)
-{
-    const uint8_t *buf = avpkt->data;
-    int buf_size = avpkt->size;
-    SonicContext *s = avctx->priv_data;
-    GetBitContext gb;
-    int i, quant, ch, j;
-    short *samples = data;
-
-    if (buf_size == 0) return 0;
-
-//    av_log(NULL, AV_LOG_INFO, "buf_size: %d\n", buf_size);
-
-    init_get_bits(&gb, buf, buf_size*8);
-
-    intlist_read(&gb, s->predictor_k, s->num_taps, 0);
-
-    // dequantize
-    for (i = 0; i < s->num_taps; i++)
-        s->predictor_k[i] *= s->tap_quant[i];
-
-    if (s->lossless)
-        quant = 1;
-    else
-        quant = get_ue_golomb(&gb) * SAMPLE_FACTOR;
-
-//    av_log(NULL, AV_LOG_INFO, "quant: %d\n", quant);
-
-    for (ch = 0; ch < s->channels; ch++)
-    {
-        int x = ch;
-
-        predictor_init_state(s->predictor_k, s->predictor_state[ch], s->num_taps);
-
-        intlist_read(&gb, s->coded_samples[ch], s->block_align, 1);
-
-        for (i = 0; i < s->block_align; i++)
-        {
-            for (j = 0; j < s->downsampling - 1; j++)
-            {
-                s->int_samples[x] = predictor_calc_error(s->predictor_k, s->predictor_state[ch], s->num_taps, 0);
-                x += s->channels;
-            }
-
-            s->int_samples[x] = predictor_calc_error(s->predictor_k, s->predictor_state[ch], s->num_taps, s->coded_samples[ch][i] * quant);
-            x += s->channels;
-        }
-
-        for (i = 0; i < s->num_taps; i++)
-            s->predictor_state[ch][i] = s->int_samples[s->frame_size - s->channels + ch - i*s->channels];
-    }
-
-    switch(s->decorrelation)
-    {
-        case MID_SIDE:
-            for (i = 0; i < s->frame_size; i += s->channels)
-            {
-                s->int_samples[i+1] += shift(s->int_samples[i], 1);
-                s->int_samples[i] -= s->int_samples[i+1];
-            }
-            break;
-        case LEFT_SIDE:
-            for (i = 0; i < s->frame_size; i += s->channels)
-                s->int_samples[i+1] += s->int_samples[i];
-            break;
-        case RIGHT_SIDE:
-            for (i = 0; i < s->frame_size; i += s->channels)
-                s->int_samples[i] += s->int_samples[i+1];
-            break;
-    }
-
-    if (!s->lossless)
-        for (i = 0; i < s->frame_size; i++)
-            s->int_samples[i] = shift(s->int_samples[i], SAMPLE_SHIFT);
-
-    // internal -> short
-    for (i = 0; i < s->frame_size; i++)
-        samples[i] = av_clip_int16(s->int_samples[i]);
-
-    align_get_bits(&gb);
-
-    *data_size = s->frame_size * 2;
-
-    return (get_bits_count(&gb)+7)/8;
-}
-
-AVCodec sonic_decoder = {
-    "sonic",
-    AVMEDIA_TYPE_AUDIO,
-    CODEC_ID_SONIC,
-    sizeof(SonicContext),
-    sonic_decode_init,
-    NULL,
-    sonic_decode_close,
-    sonic_decode_frame,
-    .long_name = NULL_IF_CONFIG_SMALL("Sonic"),
-};
-#endif /* CONFIG_SONIC_DECODER */
-
-#if CONFIG_SONIC_ENCODER
-AVCodec sonic_encoder = {
-    "sonic",
-    AVMEDIA_TYPE_AUDIO,
-    CODEC_ID_SONIC,
-    sizeof(SonicContext),
-    sonic_encode_init,
-    sonic_encode_frame,
-    sonic_encode_close,
-    NULL,
-    .long_name = NULL_IF_CONFIG_SMALL("Sonic"),
-};
-#endif
-
-#if CONFIG_SONIC_LS_ENCODER
-AVCodec sonic_ls_encoder = {
-    "sonicls",
-    AVMEDIA_TYPE_AUDIO,
-    CODEC_ID_SONIC_LS,
-    sizeof(SonicContext),
-    sonic_encode_init,
-    sonic_encode_frame,
-    sonic_encode_close,
-    NULL,
-    .long_name = NULL_IF_CONFIG_SMALL("Sonic lossless"),
-};
-#endif
diff --git a/libavcodec/sp5x.h b/libavcodec/sp5x.h
index b2c53cc..23c893b 100644
--- a/libavcodec/sp5x.h
+++ b/libavcodec/sp5x.h
@@ -2,20 +2,20 @@
  * Sunplus JPEG tables
  * Copyright (c) 2003 the ffmpeg project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/sp5xdec.c b/libavcodec/sp5xdec.c
index 754926a..e2c371a 100644
--- a/libavcodec/sp5xdec.c
+++ b/libavcodec/sp5xdec.c
@@ -2,20 +2,20 @@
  * Sunplus JPEG decoder (SP5X)
  * Copyright (c) 2003 Alex Beregszaszi
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -37,9 +37,6 @@ static int sp5x_decode_frame(AVCodecContext *avctx,
     const uint8_t *buf = avpkt->data;
     int buf_size = avpkt->size;
     AVPacket avpkt_recoded;
-#if 0
-    MJpegDecodeContext *s = avctx->priv_data;
-#endif
     const int qscale = 5;
     const uint8_t *buf_ptr;
     uint8_t *recoded;
@@ -50,7 +47,6 @@ static int sp5x_decode_frame(AVCodecContext *avctx,
 
     buf_ptr = buf;
 
-#if 1
     recoded = av_mallocz(buf_size + 1024);
     if (!recoded)
         return -1;
@@ -98,102 +94,10 @@ static int sp5x_decode_frame(AVCodecContext *avctx,
 
     av_free(recoded);
 
-#else
-    /* SOF */
-    s->bits = 8;
-    s->width  = avctx->coded_width;
-    s->height = avctx->coded_height;
-    s->nb_components = 3;
-    s->component_id[0] = 0;
-    s->h_count[0] = 2;
-    s->v_count[0] = 2;
-    s->quant_index[0] = 0;
-    s->component_id[1] = 1;
-    s->h_count[1] = 1;
-    s->v_count[1] = 1;
-    s->quant_index[1] = 1;
-    s->component_id[2] = 2;
-    s->h_count[2] = 1;
-    s->v_count[2] = 1;
-    s->quant_index[2] = 1;
-    s->h_max = 2;
-    s->v_max = 2;
-
-    s->qscale_table = av_mallocz((s->width+15)/16);
-    avctx->pix_fmt = s->cs_itu601 ? PIX_FMT_YUV420P : PIX_FMT_YUVJ420;
-    s->interlaced = 0;
-
-    s->picture.reference = 0;
-    if (avctx->get_buffer(avctx, &s->picture) < 0)
-    {
-        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
-        return -1;
-    }
-
-    s->picture.pict_type = FF_I_TYPE;
-    s->picture.key_frame = 1;
-
-    for (i = 0; i < 3; i++)
-        s->linesize[i] = s->picture.linesize[i] << s->interlaced;
-
-    /* DQT */
-    for (i = 0; i < 64; i++)
-    {
-        j = s->scantable.permutated[i];
-        s->quant_matrixes[0][j] = sp5x_quant_table[(qscale * 2) + i];
-    }
-    s->qscale[0] = FFMAX(
-        s->quant_matrixes[0][s->scantable.permutated[1]],
-        s->quant_matrixes[0][s->scantable.permutated[8]]) >> 1;
-
-    for (i = 0; i < 64; i++)
-    {
-        j = s->scantable.permutated[i];
-        s->quant_matrixes[1][j] = sp5x_quant_table[(qscale * 2) + 1 + i];
-    }
-    s->qscale[1] = FFMAX(
-        s->quant_matrixes[1][s->scantable.permutated[1]],
-        s->quant_matrixes[1][s->scantable.permutated[8]]) >> 1;
-
-    /* DHT */
-
-    /* SOS */
-    s->comp_index[0] = 0;
-    s->nb_blocks[0] = s->h_count[0] * s->v_count[0];
-    s->h_scount[0] = s->h_count[0];
-    s->v_scount[0] = s->v_count[0];
-    s->dc_index[0] = 0;
-    s->ac_index[0] = 0;
-
-    s->comp_index[1] = 1;
-    s->nb_blocks[1] = s->h_count[1] * s->v_count[1];
-    s->h_scount[1] = s->h_count[1];
-    s->v_scount[1] = s->v_count[1];
-    s->dc_index[1] = 1;
-    s->ac_index[1] = 1;
-
-    s->comp_index[2] = 2;
-    s->nb_blocks[2] = s->h_count[2] * s->v_count[2];
-    s->h_scount[2] = s->h_count[2];
-    s->v_scount[2] = s->v_count[2];
-    s->dc_index[2] = 1;
-    s->ac_index[2] = 1;
-
-    for (i = 0; i < 3; i++)
-        s->last_dc[i] = 1024;
-
-    s->mb_width = (s->width * s->h_max * 8 -1) / (s->h_max * 8);
-    s->mb_height = (s->height * s->v_max * 8 -1) / (s->v_max * 8);
-
-    init_get_bits(&s->gb, buf+14, (buf_size-14)*8);
-
-    return mjpeg_decode_scan(s);
-#endif
-
     return i;
 }
 
-AVCodec sp5x_decoder = {
+AVCodec ff_sp5x_decoder = {
     "sp5x",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_SP5X,
@@ -204,10 +108,11 @@ AVCodec sp5x_decoder = {
     sp5x_decode_frame,
     CODEC_CAP_DR1,
     NULL,
+    .max_lowres = 5,
     .long_name = NULL_IF_CONFIG_SMALL("Sunplus JPEG (SP5X)"),
 };
 
-AVCodec amv_decoder = {
+AVCodec ff_amv_decoder = {
     "amv",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_AMV,
diff --git a/libavcodec/sparc/dsputil_vis.c b/libavcodec/sparc/dsputil_vis.c
index a39096c..baf555b 100644
--- a/libavcodec/sparc/dsputil_vis.c
+++ b/libavcodec/sparc/dsputil_vis.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (C) 2003 David S. Miller <davem at redhat.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/sparc/dsputil_vis.h b/libavcodec/sparc/dsputil_vis.h
index 97ff965..b590e59 100644
--- a/libavcodec/sparc/dsputil_vis.h
+++ b/libavcodec/sparc/dsputil_vis.h
@@ -1,18 +1,18 @@
 /*
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/sparc/simple_idct_vis.c b/libavcodec/sparc/simple_idct_vis.c
index d98bf37..f9fcf80 100644
--- a/libavcodec/sparc/simple_idct_vis.c
+++ b/libavcodec/sparc/simple_idct_vis.c
@@ -5,20 +5,20 @@
  * I did consult the following fine web page about dct
  * http://www.geocities.com/ssavekar/dct.htm
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/sparc/vis.h b/libavcodec/sparc/vis.h
index adee91b..505c735 100644
--- a/libavcodec/sparc/vis.h
+++ b/libavcodec/sparc/vis.h
@@ -1,20 +1,20 @@
 /*
  * Copyright (C) 2003 David S. Miller <davem at redhat.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/srtdec.c b/libavcodec/srtdec.c
new file mode 100644
index 0000000..da625aa
--- /dev/null
+++ b/libavcodec/srtdec.c
@@ -0,0 +1,241 @@
+/*
+ * SubRip subtitle decoder
+ * Copyright (c) 2010  Aurelien Jacobs <aurel at gnuage.org>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "libavutil/avstring.h"
+#include "libavutil/parseutils.h"
+#include "avcodec.h"
+#include "ass.h"
+
+static int html_color_parse(AVCodecContext *avctx, const char *str)
+{
+    uint8_t rgba[4];
+    if (av_parse_color(rgba, str, strcspn(str, "\" >"), avctx) < 0)
+        return -1;
+    return rgba[0] | rgba[1] << 8 | rgba[2] << 16;
+}
+
+enum {
+    PARAM_UNKNOWN = -1,
+    PARAM_SIZE,
+    PARAM_COLOR,
+    PARAM_FACE,
+    PARAM_NUMBER
+};
+
+typedef struct {
+    char tag[128];
+    char param[PARAM_NUMBER][128];
+} SrtStack;
+
+static const char *srt_to_ass(AVCodecContext *avctx, char *out, char *out_end,
+                              const char *in, int x1, int y1, int x2, int y2)
+{
+    char c, *param, buffer[128], tmp[128];
+    int len, tag_close, sptr = 1, line_start = 1, an = 0, end = 0;
+    SrtStack stack[16];
+
+    stack[0].tag[0] = 0;
+    strcpy(stack[0].param[PARAM_SIZE],  "{\\fs}");
+    strcpy(stack[0].param[PARAM_COLOR], "{\\c}");
+    strcpy(stack[0].param[PARAM_FACE],  "{\\fn}");
+
+    if (x1 >= 0 && y1 >= 0) {
+        if (x2 >= 0 && y2 >= 0 && (x2 != x1 || y2 != y1))
+            out += snprintf(out, out_end-out,
+                            "{\\an1}{\\move(%d,%d,%d,%d)}", x1, y1, x2, y2);
+        else
+            out += snprintf(out, out_end-out, "{\\an1}{\\pos(%d,%d)}", x1, y1);
+    }
+
+    for (; out < out_end && !end && *in; in++) {
+        switch (*in) {
+        case '\r':
+            break;
+        case '\n':
+            if (line_start) {
+                end = 1;
+                break;
+            }
+            while (out[-1] == ' ')
+                out--;
+            out += snprintf(out, out_end-out, "\\N");
+            line_start = 1;
+            break;
+        case ' ':
+            if (!line_start)
+                *out++ = *in;
+            break;
+        case '{':    /* skip all {\xxx} substrings except for {\an%d}
+                        and all microdvd like styles such as {Y:xxx} */
+            an += sscanf(in, "{\\an%*1u}%c", &c) == 1;
+            if ((an != 1 && sscanf(in, "{\\%*[^}]}%n%c", &len, &c) > 0) ||
+                sscanf(in, "{%*1[CcFfoPSsYy]:%*[^}]}%n%c", &len, &c) > 0) {
+                in += len - 1;
+            } else
+                *out++ = *in;
+            break;
+        case '<':
+            tag_close = in[1] == '/';
+            if (sscanf(in+tag_close+1, "%128[^>]>%n%c", buffer, &len,&c) >= 2) {
+                if ((param = strchr(buffer, ' ')))
+                    *param++ = 0;
+                if ((!tag_close && sptr < FF_ARRAY_ELEMS(stack)) ||
+                    ( tag_close && sptr > 0 && !strcmp(stack[sptr-1].tag, buffer))) {
+                    int i, j, unknown = 0;
+                    in += len + tag_close;
+                    if (!tag_close)
+                        memset(stack+sptr, 0, sizeof(*stack));
+                    if (!strcmp(buffer, "font")) {
+                        if (tag_close) {
+                            for (i=PARAM_NUMBER-1; i>=0; i--)
+                                if (stack[sptr-1].param[i][0])
+                                    for (j=sptr-2; j>=0; j--)
+                                        if (stack[j].param[i][0]) {
+                                            out += snprintf(out, out_end-out,
+                                                            stack[j].param[i]);
+                                            break;
+                                        }
+                        } else {
+                            while (param) {
+                                if (!strncmp(param, "size=", 5)) {
+                                    unsigned font_size;
+                                    param += 5 + (param[5] == '"');
+                                    if (sscanf(param, "%u", &font_size) == 1) {
+                                        snprintf(stack[sptr].param[PARAM_SIZE],
+                                             sizeof(stack[0].param[PARAM_SIZE]),
+                                             "{\\fs%u}", font_size);
+                                    }
+                                } else if (!strncmp(param, "color=", 6)) {
+                                    param += 6 + (param[6] == '"');
+                                    snprintf(stack[sptr].param[PARAM_COLOR],
+                                         sizeof(stack[0].param[PARAM_COLOR]),
+                                         "{\\c&H%X&}",
+                                         html_color_parse(avctx, param));
+                                } else if (!strncmp(param, "face=", 5)) {
+                                    param += 5 + (param[5] == '"');
+                                    len = strcspn(param,
+                                                  param[-1] == '"' ? "\"" :" ");
+                                    av_strlcpy(tmp, param,
+                                               FFMIN(sizeof(tmp), len+1));
+                                    param += len;
+                                    snprintf(stack[sptr].param[PARAM_FACE],
+                                             sizeof(stack[0].param[PARAM_FACE]),
+                                             "{\\fn%s}", tmp);
+                                }
+                                if ((param = strchr(param, ' ')))
+                                    param++;
+                            }
+                            for (i=0; i<PARAM_NUMBER; i++)
+                                if (stack[sptr].param[i][0])
+                                    out += snprintf(out, out_end-out,
+                                                    stack[sptr].param[i]);
+                        }
+                    } else if (!buffer[1] && strspn(buffer, "bisu") == 1) {
+                        out += snprintf(out, out_end-out,
+                                        "{\\%c%d}", buffer[0], !tag_close);
+                    } else {
+                        unknown = 1;
+                        snprintf(tmp, sizeof(tmp), "</%s>", buffer);
+                    }
+                    if (tag_close) {
+                        sptr--;
+                    } else if (unknown && !strstr(in, tmp)) {
+                        in -= len + tag_close;
+                        *out++ = *in;
+                    } else
+                        av_strlcpy(stack[sptr++].tag, buffer,
+                                   sizeof(stack[0].tag));
+                    break;
+                }
+            }
+        default:
+            *out++ = *in;
+            break;
+        }
+        if (*in != ' ' && *in != '\r' && *in != '\n')
+            line_start = 0;
+    }
+
+    out = FFMIN(out, out_end-3);
+    while (!strncmp(out-2, "\\N", 2))
+        out -= 2;
+    while (out[-1] == ' ')
+        out--;
+    out += snprintf(out, out_end-out, "\r\n");
+    return in;
+}
+
+static const char *read_ts(const char *buf, int *ts_start, int *ts_end,
+                           int *x1, int *y1, int *x2, int *y2)
+{
+    int i, hs, ms, ss, he, me, se;
+
+    for (i=0; i<2; i++) {
+        /* try to read timestamps in either the first or second line */
+        int c = sscanf(buf, "%d:%2d:%2d%*1[,.]%3d --> %d:%2d:%2d%*1[,.]%3d"
+                       "%*[ ]X1:%u X2:%u Y1:%u Y2:%u",
+                       &hs, &ms, &ss, ts_start, &he, &me, &se, ts_end,
+                       x1, x2, y1, y2);
+        buf += strcspn(buf, "\n") + 1;
+        if (c >= 8) {
+            *ts_start = 100*(ss + 60*(ms + 60*hs)) + *ts_start/10;
+            *ts_end   = 100*(se + 60*(me + 60*he)) + *ts_end  /10;
+            return buf;
+        }
+    }
+    return NULL;
+}
+
+static int srt_decode_frame(AVCodecContext *avctx,
+                            void *data, int *got_sub_ptr, AVPacket *avpkt)
+{
+    AVSubtitle *sub = data;
+    int ts_start, ts_end, x1 = -1, y1 = -1, x2 = -1, y2 = -1;
+    char buffer[2048];
+    const char *ptr = avpkt->data;
+    const char *end = avpkt->data + avpkt->size;
+
+    if (avpkt->size <= 0)
+        return avpkt->size;
+
+    ff_ass_init(sub);
+
+    while (ptr < end && *ptr) {
+        ptr = read_ts(ptr, &ts_start, &ts_end, &x1, &y1, &x2, &y2);
+        if (!ptr)
+            break;
+        ptr = srt_to_ass(avctx, buffer, buffer+sizeof(buffer), ptr,
+                         x1, y1, x2, y2);
+        ff_ass_add_rect(sub, buffer, ts_start, ts_end, 0);
+    }
+
+    *got_sub_ptr = sub->num_rects > 0;
+    return avpkt->size;
+}
+
+AVCodec ff_srt_decoder = {
+    .name         = "srt",
+    .long_name    = NULL_IF_CONFIG_SMALL("SubRip subtitle"),
+    .type         = AVMEDIA_TYPE_SUBTITLE,
+    .id           = CODEC_ID_SRT,
+    .init         = ff_ass_subtitle_header_default,
+    .decode       = srt_decode_frame,
+};
diff --git a/libavcodec/sunrast.c b/libavcodec/sunrast.c
index 456ab85..749a41b 100644
--- a/libavcodec/sunrast.c
+++ b/libavcodec/sunrast.c
@@ -2,24 +2,25 @@
  * Sun Rasterfile (.sun/.ras/im{1,8,24}/.sunras) image decoder
  * Copyright (c) 2007, 2008 Ivo van Poorten
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "libavutil/intreadwrite.h"
+#include "libavutil/imgutils.h"
 #include "avcodec.h"
 
 #define RT_OLD          0
@@ -97,7 +98,7 @@ static int sunrast_decode_frame(AVCodecContext *avctx, void *data,
     if (p->data[0])
         avctx->release_buffer(avctx, p);
 
-    if (avcodec_check_dimensions(avctx, w, h))
+    if (av_image_check_size(w, h, 0, avctx))
         return -1;
     if (w != avctx->width || h != avctx->height)
         avcodec_set_dimensions(avctx, w, h);
@@ -183,7 +184,7 @@ static av_cold int sunrast_end(AVCodecContext *avctx) {
     return 0;
 }
 
-AVCodec sunrast_decoder = {
+AVCodec ff_sunrast_decoder = {
     "sunrast",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_SUNRAST,
diff --git a/libavcodec/svq1.c b/libavcodec/svq1.c
index d0e1132..b7e3af0 100644
--- a/libavcodec/svq1.c
+++ b/libavcodec/svq1.c
@@ -8,20 +8,20 @@
  *
  * SVQ1 Encoder (c) 2004 Mike Melanson <melanson at pcisys.net>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/svq1.h b/libavcodec/svq1.h
index 3ade05d..066ea47 100644
--- a/libavcodec/svq1.h
+++ b/libavcodec/svq1.h
@@ -8,20 +8,20 @@
  *
  * SVQ1 Encoder (c) 2004 Mike Melanson <melanson at pcisys.net>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/svq1_cb.h b/libavcodec/svq1_cb.h
index 7926ce1..e22cd60 100644
--- a/libavcodec/svq1_cb.h
+++ b/libavcodec/svq1_cb.h
@@ -6,20 +6,20 @@
  * Copyright (C) 2002 the xine project
  * Copyright (C) 2002 the ffmpeg project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/svq1_vlc.h b/libavcodec/svq1_vlc.h
index 272597e..4d03b08 100644
--- a/libavcodec/svq1_vlc.h
+++ b/libavcodec/svq1_vlc.h
@@ -1,20 +1,20 @@
 /*
  * copyright (C) 2003 the ffmpeg project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/svq1dec.c b/libavcodec/svq1dec.c
index 2aa28ab..5439abb 100644
--- a/libavcodec/svq1dec.c
+++ b/libavcodec/svq1dec.c
@@ -8,20 +8,20 @@
  *
  * SVQ1 Encoder (c) 2004 Mike Melanson <melanson at pcisys.net>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -650,6 +650,7 @@ static int svq1_decode_frame(AVCodecContext *avctx,
   uint8_t        *current, *previous;
   int             result, i, x, y, width, height;
   AVFrame *pict = data;
+  svq1_pmv *pmv;
 
   /* initialize bit buffer */
   init_get_bits(&s->gb,buf,buf_size*8);
@@ -683,7 +684,9 @@ static int svq1_decode_frame(AVCodecContext *avctx,
   //this should be removed after libavcodec can handle more flexible picture types & ordering
   if(s->pict_type==FF_B_TYPE && s->last_picture_ptr==NULL) return buf_size;
 
+#if FF_API_HURRY_UP
   if(avctx->hurry_up && s->pict_type==FF_B_TYPE) return buf_size;
+#endif
   if(  (avctx->skip_frame >= AVDISCARD_NONREF && s->pict_type==FF_B_TYPE)
      ||(avctx->skip_frame >= AVDISCARD_NONKEY && s->pict_type!=FF_I_TYPE)
      || avctx->skip_frame >= AVDISCARD_ALL)
@@ -692,6 +695,10 @@ static int svq1_decode_frame(AVCodecContext *avctx,
   if(MPV_frame_start(s, avctx) < 0)
       return -1;
 
+  pmv = av_malloc((FFALIGN(s->width, 16)/8 + 3) * sizeof(*pmv));
+  if (!pmv)
+      return -1;
+
   /* decode y, u and v components */
   for (i=0; i < 3; i++) {
     int linesize;
@@ -724,13 +731,12 @@ static int svq1_decode_frame(AVCodecContext *avctx,
 //#ifdef DEBUG_SVQ1
             av_log(s->avctx, AV_LOG_INFO, "Error in svq1_decode_block %i (keyframe)\n",result);
 //#endif
-            return result;
+            goto err;
           }
         }
         current += 16*linesize;
       }
     } else {
-      svq1_pmv pmv[width/8+3];
       /* delta frame */
       memset (pmv, 0, ((width / 8) + 3) * sizeof(svq1_pmv));
 
@@ -743,7 +749,7 @@ static int svq1_decode_frame(AVCodecContext *avctx,
 #ifdef DEBUG_SVQ1
     av_log(s->avctx, AV_LOG_INFO, "Error in svq1_decode_delta_block %i\n",result);
 #endif
-            return result;
+            goto err;
           }
         }
 
@@ -761,7 +767,10 @@ static int svq1_decode_frame(AVCodecContext *avctx,
   MPV_frame_end(s);
 
   *data_size=sizeof(AVFrame);
-  return buf_size;
+  result = buf_size;
+err:
+  av_free(pmv);
+  return result;
 }
 
 static av_cold int svq1_decode_init(AVCodecContext *avctx)
@@ -826,7 +835,7 @@ static av_cold int svq1_decode_end(AVCodecContext *avctx)
 }
 
 
-AVCodec svq1_decoder = {
+AVCodec ff_svq1_decoder = {
     "svq1",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_SVQ1,
diff --git a/libavcodec/svq1enc.c b/libavcodec/svq1enc.c
index c89be25..cf10d85 100644
--- a/libavcodec/svq1enc.c
+++ b/libavcodec/svq1enc.c
@@ -2,20 +2,20 @@
  * SVQ1 Encoder
  * Copyright (C) 2004 Mike Melanson <melanson at pcisys.net>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -572,7 +572,7 @@ static av_cold int svq1_encode_end(AVCodecContext *avctx)
 }
 
 
-AVCodec svq1_encoder = {
+AVCodec ff_svq1_encoder = {
     "svq1",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_SVQ1,
diff --git a/libavcodec/svq1enc_cb.h b/libavcodec/svq1enc_cb.h
index 7eff82e..1c86ebe 100644
--- a/libavcodec/svq1enc_cb.h
+++ b/libavcodec/svq1enc_cb.h
@@ -2,20 +2,20 @@
  * SVQ1 Encoder
  * Copyright (C) 2004 Mike Melanson <melanson at pcisys.net>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/svq3.c b/libavcodec/svq3.c
index bf7659a..50c5d22 100644
--- a/libavcodec/svq3.c
+++ b/libavcodec/svq3.c
@@ -1,20 +1,20 @@
 /*
- * Copyright (c) 2003 The FFmpeg Project
+ * Copyright (c) 2003 The Libav Project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -37,7 +37,7 @@
  *
  * You will know you have these parameters passed correctly when the decoder
  * correctly decodes this file:
- *  http://samples.mplayerhq.hu/V-codecs/SVQ3/Vertical400kbit.sorenson3.mov
+ *  http://samples.libav.org/V-codecs/SVQ3/Vertical400kbit.sorenson3.mov
  */
 #include "internal.h"
 #include "dsputil.h"
@@ -125,22 +125,18 @@ static const uint32_t svq3_dequant_coeff[32] = {
     61694, 68745, 77615, 89113,100253,109366,126635,141533
 };
 
-
-void ff_svq3_luma_dc_dequant_idct_c(DCTELEM *block, int qp)
-{
+void ff_svq3_luma_dc_dequant_idct_c(DCTELEM *output, DCTELEM *input, int qp){
     const int qmul = svq3_dequant_coeff[qp];
 #define stride 16
     int i;
     int temp[16];
-    static const int x_offset[4] = {0, 1*stride, 4* stride,  5*stride};
-    static const int y_offset[4] = {0, 2*stride, 8* stride, 10*stride};
+    static const uint8_t x_offset[4]={0, 1*stride, 4*stride, 5*stride};
 
-    for (i = 0; i < 4; i++){
-        const int offset = y_offset[i];
-        const int z0 = 13*(block[offset+stride*0] +    block[offset+stride*4]);
-        const int z1 = 13*(block[offset+stride*0] -    block[offset+stride*4]);
-        const int z2 =  7* block[offset+stride*1] - 17*block[offset+stride*5];
-        const int z3 = 17* block[offset+stride*1] +  7*block[offset+stride*5];
+    for(i=0; i<4; i++){
+        const int z0 = 13*(input[4*i+0] +    input[4*i+2]);
+        const int z1 = 13*(input[4*i+0] -    input[4*i+2]);
+        const int z2 =  7* input[4*i+1] - 17*input[4*i+3];
+        const int z3 = 17* input[4*i+1] +  7*input[4*i+3];
 
         temp[4*i+0] = z0+z3;
         temp[4*i+1] = z1+z2;
@@ -148,17 +144,17 @@ void ff_svq3_luma_dc_dequant_idct_c(DCTELEM *block, int qp)
         temp[4*i+3] = z0-z3;
     }
 
-    for (i = 0; i < 4; i++){
-        const int offset = x_offset[i];
-        const int z0 = 13*(temp[4*0+i] +    temp[4*2+i]);
-        const int z1 = 13*(temp[4*0+i] -    temp[4*2+i]);
-        const int z2 =  7* temp[4*1+i] - 17*temp[4*3+i];
-        const int z3 = 17* temp[4*1+i] +  7*temp[4*3+i];
-
-        block[stride*0 +offset] = ((z0 + z3)*qmul + 0x80000) >> 20;
-        block[stride*2 +offset] = ((z1 + z2)*qmul + 0x80000) >> 20;
-        block[stride*8 +offset] = ((z1 - z2)*qmul + 0x80000) >> 20;
-        block[stride*10+offset] = ((z0 - z3)*qmul + 0x80000) >> 20;
+    for(i=0; i<4; i++){
+        const int offset= x_offset[i];
+        const int z0= 13*(temp[4*0+i] +    temp[4*2+i]);
+        const int z1= 13*(temp[4*0+i] -    temp[4*2+i]);
+        const int z2=  7* temp[4*1+i] - 17*temp[4*3+i];
+        const int z3= 17* temp[4*1+i] +  7*temp[4*3+i];
+
+        output[stride* 0+offset] = ((z0 + z3)*qmul + 0x80000) >> 20;
+        output[stride* 2+offset] = ((z1 + z2)*qmul + 0x80000) >> 20;
+        output[stride* 8+offset] = ((z1 - z2)*qmul + 0x80000) >> 20;
+        output[stride*10+offset] = ((z0 - z3)*qmul + 0x80000) >> 20;
     }
 }
 #undef stride
@@ -287,7 +283,7 @@ static inline void svq3_mc_dir_part(MpegEncContext *s,
     src  = pic->data[0] + mx + my*s->linesize;
 
     if (emu) {
-        ff_emulated_edge_mc(s->edge_emu_buffer, src, s->linesize, (width + 1), (height + 1),
+        s->dsp.emulated_edge_mc(s->edge_emu_buffer, src, s->linesize, (width + 1), (height + 1),
                             mx, my, s->h_edge_pos, s->v_edge_pos);
         src = s->edge_emu_buffer;
     }
@@ -308,7 +304,7 @@ static inline void svq3_mc_dir_part(MpegEncContext *s,
             src  = pic->data[i] + mx + my*s->uvlinesize;
 
             if (emu) {
-                ff_emulated_edge_mc(s->edge_emu_buffer, src, s->uvlinesize, (width + 1), (height + 1),
+                s->dsp.emulated_edge_mc(s->edge_emu_buffer, src, s->uvlinesize, (width + 1), (height + 1),
                                     mx, my, (s->h_edge_pos >> 1), (s->v_edge_pos >> 1));
                 src = s->edge_emu_buffer;
             }
@@ -648,7 +644,9 @@ static int svq3_decode_mb(H264Context *h, unsigned int mb_type)
         }
     }
     if (IS_INTRA16x16(mb_type)) {
-        if (svq3_decode_block(&s->gb, h->mb, 0, 0)){
+        AV_ZERO128(h->mb_luma_dc+0);
+        AV_ZERO128(h->mb_luma_dc+8);
+        if (svq3_decode_block(&s->gb, h->mb_luma_dc, 0, 1)){
             av_log(h->s.avctx, AV_LOG_ERROR, "error while decoding intra luma dc\n");
             return -1;
         }
@@ -796,11 +794,6 @@ static av_cold int svq3_decode_init(AVCodecContext *avctx)
     unsigned char *extradata;
     unsigned int size;
 
-    if(avctx->thread_count > 1){
-        av_log(avctx, AV_LOG_ERROR, "SVQ3 does not support multithreaded decoding, patch welcome! (check latest SVN too)\n");
-        return -1;
-    }
-
     if (ff_h264_decode_init(avctx) < 0)
         return -1;
 
@@ -886,7 +879,7 @@ static av_cold int svq3_decode_init(AVCodecContext *avctx)
                 int u2 = get_bits(&gb, 8);
                 int u3 = get_bits(&gb, 2);
                 int u4 = svq3_get_ue_golomb(&gb);
-                unsigned buf_len = watermark_width*watermark_height*4;
+                unsigned long buf_len = watermark_width*watermark_height*4;
                 int offset = (get_bits_count(&gb)+7)>>3;
                 uint8_t *buf;
 
@@ -896,7 +889,7 @@ static av_cold int svq3_decode_init(AVCodecContext *avctx)
                 buf = av_malloc(buf_len);
                 av_log(avctx, AV_LOG_DEBUG, "watermark size: %dx%d\n", watermark_width, watermark_height);
                 av_log(avctx, AV_LOG_DEBUG, "u1: %x u2: %x u3: %x compressed data size: %d offset: %d\n", u1, u2, u3, u4, offset);
-                if (uncompress(buf, (uLong*)&buf_len, extradata + 8 + offset, size - offset) != Z_OK) {
+                if (uncompress(buf, &buf_len, extradata + 8 + offset, size - offset) != Z_OK) {
                     av_log(avctx, AV_LOG_ERROR, "could not uncompress watermark logo\n");
                     av_free(buf);
                     return -1;
@@ -952,19 +945,21 @@ static int svq3_decode_frame(AVCodecContext *avctx,
                s->adaptive_quant, s->qscale, h->slice_num);
     }
 
-    /* for hurry_up == 5 */
+    /* for skipping the frame */
     s->current_picture.pict_type = s->pict_type;
     s->current_picture.key_frame = (s->pict_type == FF_I_TYPE);
 
     /* Skip B-frames if we do not have reference frames. */
     if (s->last_picture_ptr == NULL && s->pict_type == FF_B_TYPE)
         return 0;
+#if FF_API_HURRY_UP
     /* Skip B-frames if we are in a hurry. */
     if (avctx->hurry_up && s->pict_type == FF_B_TYPE)
         return 0;
     /* Skip everything if we are in a hurry >= 5. */
     if (avctx->hurry_up >= 5)
         return 0;
+#endif
     if (  (avctx->skip_frame >= AVDISCARD_NONREF && s->pict_type == FF_B_TYPE)
         ||(avctx->skip_frame >= AVDISCARD_NONKEY && s->pict_type != FF_I_TYPE)
         || avctx->skip_frame >= AVDISCARD_ALL)
@@ -1069,7 +1064,7 @@ static int svq3_decode_frame(AVCodecContext *avctx,
 }
 
 
-AVCodec svq3_decoder = {
+AVCodec ff_svq3_decoder = {
     "svq3",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_SVQ3,
diff --git a/libavcodec/synth_filter.c b/libavcodec/synth_filter.c
index a0ae364..8e6f120 100644
--- a/libavcodec/synth_filter.c
+++ b/libavcodec/synth_filter.c
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2008 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -24,12 +24,12 @@
 static void synth_filter_float(FFTContext *imdct,
                            float *synth_buf_ptr, int *synth_buf_offset,
                            float synth_buf2[32], const float window[512],
-                           float out[32], const float in[32], float scale, float bias)
+                           float out[32], const float in[32], float scale)
 {
     float *synth_buf= synth_buf_ptr + *synth_buf_offset;
     int i, j;
 
-    ff_imdct_half(imdct, synth_buf, in);
+    imdct->imdct_half(imdct, synth_buf, in);
 
     for (i = 0; i < 16; i++){
         float a= synth_buf2[i     ];
@@ -48,8 +48,8 @@ static void synth_filter_float(FFTContext *imdct,
             c += window[i + j + 32]*( synth_buf[16 + i + j - 512]);
             d += window[i + j + 48]*( synth_buf[31 - i + j - 512]);
         }
-        out[i     ] = a*scale + bias;
-        out[i + 16] = b*scale + bias;
+        out[i     ] = a*scale;
+        out[i + 16] = b*scale;
         synth_buf2[i     ] = c;
         synth_buf2[i + 16] = d;
     }
diff --git a/libavcodec/synth_filter.h b/libavcodec/synth_filter.h
index d6209d5..7b73578 100644
--- a/libavcodec/synth_filter.h
+++ b/libavcodec/synth_filter.h
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2008 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -28,7 +28,7 @@ typedef struct SynthFilterContext {
                                float *synth_buf_ptr, int *synth_buf_offset,
                                float synth_buf2[32], const float window[512],
                                float out[32], const float in[32],
-                               float scale, float bias);
+                               float scale);
 } SynthFilterContext;
 
 void ff_synth_filter_init(SynthFilterContext *c);
diff --git a/libavcodec/tableprint.c b/libavcodec/tableprint.c
index e39606b..da77525 100644
--- a/libavcodec/tableprint.c
+++ b/libavcodec/tableprint.c
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2009 Reimar Döffinger <Reimar.Doeffinger at gmx.de>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -24,15 +24,16 @@
 #include <inttypes.h>
 #include "tableprint.h"
 
-WRITE_1D_FUNC(int8,   int8_t,   "%3"PRIi8, 15)
-WRITE_1D_FUNC(uint8,  uint8_t,  "0x%02"PRIx8, 15)
-WRITE_1D_FUNC(uint16, uint16_t, "0x%08"PRIx16, 7)
-WRITE_1D_FUNC(uint32, uint32_t, "0x%08"PRIx32, 7)
-WRITE_1D_FUNC(float,  float,    "%.18e", 3)
+WRITE_1D_FUNC(int8_t,   "%3"PRIi8, 15)
+WRITE_1D_FUNC(uint8_t,  "0x%02"PRIx8, 15)
+WRITE_1D_FUNC(uint16_t, "0x%08"PRIx16, 7)
+WRITE_1D_FUNC(uint32_t, "0x%08"PRIx32, 7)
+WRITE_1D_FUNC(float,    "%.18e", 3)
 
-WRITE_2D_FUNC(int8,   int8_t)
-WRITE_2D_FUNC(uint8,  uint8_t)
-WRITE_2D_FUNC(uint32, uint32_t)
+WRITE_2D_FUNC(int8_t)
+WRITE_2D_FUNC(uint8_t)
+WRITE_2D_FUNC(uint32_t)
+WRITE_2D_FUNC(float)
 
 void write_fileheader(void) {
     printf("/* This file was generated by libavcodec/tableprint */\n");
diff --git a/libavcodec/tableprint.h b/libavcodec/tableprint.h
index d81af97..af69fe8 100644
--- a/libavcodec/tableprint.h
+++ b/libavcodec/tableprint.h
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2009 Reimar Döffinger <Reimar.Doeffinger at gmx.de>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,9 +25,10 @@
 
 #include <stdint.h>
 #include <stdio.h>
+#include "libavutil/common.h"
 
-#define WRITE_1D_FUNC_ARGV(name, type, linebrk, fmtstr, ...)\
-void write_##name##_array(const type *data, int len)\
+#define WRITE_1D_FUNC_ARGV(type, linebrk, fmtstr, ...)\
+void write_##type##_array(const type *data, int len)\
 {\
     int i;\
     printf("   ");\
@@ -38,17 +39,17 @@ void write_##name##_array(const type *data, int len)\
     printf(" "fmtstr"\n", __VA_ARGS__);\
 }
 
-#define WRITE_1D_FUNC(name, type, fmtstr, linebrk)\
-    WRITE_1D_FUNC_ARGV(name, type, linebrk, fmtstr, data[i])
+#define WRITE_1D_FUNC(type, fmtstr, linebrk)\
+    WRITE_1D_FUNC_ARGV(type, linebrk, fmtstr, data[i])
 
-#define WRITE_2D_FUNC(name, type)\
-void write_##name##_2d_array(const void *arg, int len, int len2)\
+#define WRITE_2D_FUNC(type)\
+void write_##type##_2d_array(const void *arg, int len, int len2)\
 {\
     const type *data = arg;\
     int i;\
     printf("    {\n");\
     for (i = 0; i < len; i++) {\
-        write_##name##_array(data + i * len2, len2);\
+        write_##type##_array(data + i * len2, len2);\
         printf(i == len - 1 ? "    }\n" : "    }, {\n");\
     }\
 }
@@ -58,17 +59,37 @@ void write_##name##_2d_array(const void *arg, int len, int len2)\
  *
  * \{
  */
-void write_int8_array     (const int8_t   *, int);
-void write_uint8_array    (const uint8_t  *, int);
-void write_uint16_array   (const uint16_t *, int);
-void write_uint32_array   (const uint32_t *, int);
-void write_float_array    (const float    *, int);
-void write_int8_2d_array  (const void *, int, int);
-void write_uint8_2d_array (const void *, int, int);
-void write_uint32_2d_array(const void *, int, int);
+void write_int8_t_array     (const int8_t   *, int);
+void write_uint8_t_array    (const uint8_t  *, int);
+void write_uint16_t_array   (const uint16_t *, int);
+void write_uint32_t_array   (const uint32_t *, int);
+void write_float_array      (const float    *, int);
+void write_int8_t_2d_array  (const void *, int, int);
+void write_uint8_t_2d_array (const void *, int, int);
+void write_uint32_t_2d_array(const void *, int, int);
+void write_float_2d_array   (const void *, int, int);
 /** \} */ // end of printfuncs group
 
 /** Write a standard file header */
 void write_fileheader(void);
 
+#define WRITE_ARRAY(prefix, type, name)                 \
+    do {                                                \
+        const size_t array_size = FF_ARRAY_ELEMS(name); \
+        printf(prefix" "#type" "#name"[%zu] = {\n",     \
+               array_size);                             \
+        write_##type##_array(name, array_size);         \
+        printf("};\n");                                 \
+    } while(0)
+
+#define WRITE_2D_ARRAY(prefix, type, name)                              \
+    do {                                                                \
+        const size_t array_size1 = FF_ARRAY_ELEMS(name);                \
+        const size_t array_size2 = FF_ARRAY_ELEMS(name[0]);             \
+        printf(prefix" "#type" "#name"[%zu][%zu] = {\n",                \
+               array_size1, array_size2 );                              \
+        write_##type##_2d_array(name, array_size1, array_size2);        \
+        printf("};\n");                                                 \
+    } while(0)
+
 #endif /* AVCODEC_TABLEPRINT_H */
diff --git a/libavcodec/targa.c b/libavcodec/targa.c
index 50fe107..910cc1b 100644
--- a/libavcodec/targa.c
+++ b/libavcodec/targa.c
@@ -2,33 +2,27 @@
  * Targa (.tga) image decoder
  * Copyright (c) 2006 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "libavutil/intreadwrite.h"
+#include "libavutil/imgutils.h"
 #include "avcodec.h"
-
-enum TargaCompr{
-    TGA_NODATA = 0, // no image data
-    TGA_PAL    = 1, // palettized
-    TGA_RGB    = 2, // true-color
-    TGA_BW     = 3, // black & white or grayscale
-    TGA_RLE    = 8, // flag pointing that data is RLE-coded
-};
+#include "targa.h"
 
 typedef struct TargaContext {
     AVFrame picture;
@@ -39,22 +33,35 @@ typedef struct TargaContext {
     int compression_type;
 } TargaContext;
 
-static void targa_decode_rle(AVCodecContext *avctx, TargaContext *s, const uint8_t *src, uint8_t *dst, int w, int h, int stride, int bpp)
+#define CHECK_BUFFER_SIZE(buf, buf_end, needed, where) \
+    if(needed > buf_end - buf){ \
+        av_log(avctx, AV_LOG_ERROR, "Problem: unexpected end of data while reading " where "\n"); \
+        return -1; \
+    } \
+
+static int targa_decode_rle(AVCodecContext *avctx, TargaContext *s, const uint8_t *src, int src_size, uint8_t *dst, int w, int h, int stride, int bpp)
 {
     int i, x, y;
     int depth = (bpp + 1) >> 3;
     int type, count;
     int diff;
+    const uint8_t *src_end = src + src_size;
 
     diff = stride - w * depth;
     x = y = 0;
     while(y < h){
+        CHECK_BUFFER_SIZE(src, src_end, 1, "image type");
         type = *src++;
         count = (type & 0x7F) + 1;
         type &= 0x80;
         if((x + count > w) && (x + count + 1 > (h - y) * w)){
             av_log(avctx, AV_LOG_ERROR, "Packet went out of bounds: position (%i,%i) size %i\n", x, y, count);
-            return;
+            return -1;
+        }
+        if(type){
+            CHECK_BUFFER_SIZE(src, src_end, depth, "image data");
+        }else{
+            CHECK_BUFFER_SIZE(src, src_end, count * depth, "image data");
         }
         for(i = 0; i < count; i++){
             switch(depth){
@@ -87,6 +94,7 @@ static void targa_decode_rle(AVCodecContext *avctx, TargaContext *s, const uint8
         if(type)
             src += depth;
     }
+    return src_size;
 }
 
 static int decode_frame(AVCodecContext *avctx,
@@ -94,7 +102,7 @@ static int decode_frame(AVCodecContext *avctx,
                         AVPacket *avpkt)
 {
     const uint8_t *buf = avpkt->data;
-    int buf_size = avpkt->size;
+    const uint8_t *buf_end = avpkt->data + avpkt->size;
     TargaContext * const s = avctx->priv_data;
     AVFrame *picture = data;
     AVFrame * const p= (AVFrame*)&s->picture;
@@ -104,6 +112,7 @@ static int decode_frame(AVCodecContext *avctx,
     int first_clr, colors, csize;
 
     /* parse image header */
+    CHECK_BUFFER_SIZE(buf, buf_end, 18, "header");
     idlen = *buf++;
     pal = *buf++;
     compr = *buf++;
@@ -117,6 +126,7 @@ static int decode_frame(AVCodecContext *avctx,
     bpp = *buf++;
     flags = *buf++;
     //skip identifier if any
+    CHECK_BUFFER_SIZE(buf, buf_end, idlen, "identifiers");
     buf += idlen;
     s->bpp = bpp;
     s->width = w;
@@ -145,7 +155,7 @@ static int decode_frame(AVCodecContext *avctx,
     if(s->picture.data[0])
         avctx->release_buffer(avctx, &s->picture);
 
-    if(avcodec_check_dimensions(avctx, w, h))
+    if(av_image_check_size(w, h, 0, avctx))
         return -1;
     if(w != avctx->width || h != avctx->height)
         avcodec_set_dimensions(avctx, w, h);
@@ -161,14 +171,8 @@ static int decode_frame(AVCodecContext *avctx,
         stride = -p->linesize[0];
     }
 
-    if(avctx->pix_fmt == PIX_FMT_PAL8 && avctx->palctrl){
-        memcpy(p->data[1], avctx->palctrl->palette, AVPALETTE_SIZE);
-        if(avctx->palctrl->palette_changed){
-            p->palette_has_changed = 1;
-            avctx->palctrl->palette_changed = 0;
-        }
-    }
     if(colors){
+        size_t pal_size;
         if((colors + first_clr) > 256){
             av_log(avctx, AV_LOG_ERROR, "Incorrect palette: %i colors with offset %i\n", colors, first_clr);
             return -1;
@@ -177,8 +181,10 @@ static int decode_frame(AVCodecContext *avctx,
             av_log(avctx, AV_LOG_ERROR, "Palette entry size %i bits is not supported\n", csize);
             return -1;
         }
+        pal_size = colors * ((csize + 1) >> 3);
+        CHECK_BUFFER_SIZE(buf, buf_end, pal_size, "color table");
         if(avctx->pix_fmt != PIX_FMT_PAL8)//should not occur but skip palette anyway
-            buf += colors * ((csize + 1) >> 3);
+            buf += pal_size;
         else{
             int r, g, b, t;
             int32_t *pal = ((int32_t*)p->data[1]) + first_clr;
@@ -194,9 +200,14 @@ static int decode_frame(AVCodecContext *avctx,
     if((compr & (~TGA_RLE)) == TGA_NODATA)
         memset(p->data[0], 0, p->linesize[0] * s->height);
     else{
-        if(compr & TGA_RLE)
-            targa_decode_rle(avctx, s, buf, dst, avctx->width, avctx->height, stride, bpp);
-        else{
+        if(compr & TGA_RLE){
+            int res = targa_decode_rle(avctx, s, buf, buf_end - buf, dst, avctx->width, avctx->height, stride, bpp);
+            if (res < 0)
+                return -1;
+            buf += res;
+        }else{
+            size_t img_size = s->width * ((s->bpp + 1) >> 3);
+            CHECK_BUFFER_SIZE(buf, buf_end, img_size, "image data");
             for(y = 0; y < s->height; y++){
 #if HAVE_BIGENDIAN
                 if((s->bpp + 1) >> 3 == 2){
@@ -209,10 +220,10 @@ static int decode_frame(AVCodecContext *avctx,
                         dst32[x] = AV_RL32(buf + x * 4);
                 }else
 #endif
-                    memcpy(dst, buf, s->width * ((s->bpp + 1) >> 3));
+                    memcpy(dst, buf, img_size);
 
                 dst += stride;
-                buf += s->width * ((s->bpp + 1) >> 3);
+                buf += img_size;
             }
         }
     }
@@ -220,7 +231,7 @@ static int decode_frame(AVCodecContext *avctx,
     *picture= *(AVFrame*)&s->picture;
     *data_size = sizeof(AVPicture);
 
-    return buf_size;
+    return avpkt->size;
 }
 
 static av_cold int targa_init(AVCodecContext *avctx){
@@ -241,7 +252,7 @@ static av_cold int targa_end(AVCodecContext *avctx){
     return 0;
 }
 
-AVCodec targa_decoder = {
+AVCodec ff_targa_decoder = {
     "targa",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_TARGA,
diff --git a/libavcodec/targa.h b/libavcodec/targa.h
new file mode 100644
index 0000000..d7c3f45
--- /dev/null
+++ b/libavcodec/targa.h
@@ -0,0 +1,36 @@
+/*
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * targa file common definitions
+ *
+ * Based on:
+ * http://www.gamers.org/dEngine/quake3/TGA.txt
+ *
+ * and other specs you can find referenced for example in:
+ * http://en.wikipedia.org/wiki/Truevision_TGA
+ */
+
+enum TargaCompr {
+    TGA_NODATA = 0, // no image data
+    TGA_PAL    = 1, // palettized
+    TGA_RGB    = 2, // true-color
+    TGA_BW     = 3, // black & white or grayscale
+    TGA_RLE    = 8, // flag pointing that data is RLE-coded
+};
diff --git a/libavcodec/targaenc.c b/libavcodec/targaenc.c
index e5d0042..617087c 100644
--- a/libavcodec/targaenc.c
+++ b/libavcodec/targaenc.c
@@ -2,26 +2,27 @@
  * Targa (.tga) image encoder
  * Copyright (c) 2007 Bobby Bingham
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "libavutil/intreadwrite.h"
 #include "avcodec.h"
 #include "rle.h"
+#include "targa.h"
 
 typedef struct TargaContext {
     AVFrame picture;
@@ -81,12 +82,12 @@ static int targa_encode_frame(AVCodecContext *avctx,
 
     if(avctx->width > 0xffff || avctx->height > 0xffff) {
         av_log(avctx, AV_LOG_ERROR, "image dimensions too large\n");
-        return -1;
+        return AVERROR(EINVAL);
     }
     picsize = avpicture_get_size(avctx->pix_fmt, avctx->width, avctx->height);
     if(buf_size < picsize + 45) {
         av_log(avctx, AV_LOG_ERROR, "encoded frame too large\n");
-        return -1;
+        return AVERROR(EINVAL);
     }
 
     p->pict_type= FF_I_TYPE;
@@ -96,24 +97,30 @@ static int targa_encode_frame(AVCodecContext *avctx,
     memset(outbuf, 0, 12);
     AV_WL16(outbuf+12, avctx->width);
     AV_WL16(outbuf+14, avctx->height);
-    outbuf[17] = 0x20;           /* origin is top-left. no alpha */
+    /* image descriptor byte: origin is always top-left, bits 0-3 specify alpha */
+    outbuf[17] = 0x20 | (avctx->pix_fmt == PIX_FMT_BGRA ? 8 : 0);
 
-    /* TODO: support alpha channel */
     switch(avctx->pix_fmt) {
     case PIX_FMT_GRAY8:
-        outbuf[2] = 3;           /* uncompressed grayscale image */
+        outbuf[2] = TGA_BW;      /* uncompressed grayscale image */
         outbuf[16] = 8;          /* bpp */
         break;
     case PIX_FMT_RGB555LE:
-        outbuf[2] = 2;           /* uncompresses true-color image */
+        outbuf[2] = TGA_RGB;     /* uncompresses true-color image */
         outbuf[16] = 16;         /* bpp */
         break;
     case PIX_FMT_BGR24:
-        outbuf[2] = 2;           /* uncompressed true-color image */
+        outbuf[2] = TGA_RGB;     /* uncompressed true-color image */
         outbuf[16] = 24;         /* bpp */
         break;
+    case PIX_FMT_BGRA:
+        outbuf[2] = TGA_RGB;     /* uncompressed true-color image */
+        outbuf[16] = 32;         /* bpp */
+        break;
     default:
-        return -1;
+        av_log(avctx, AV_LOG_ERROR, "Pixel format '%s' not supported.\n",
+               avcodec_get_pix_fmt_name(avctx->pix_fmt));
+        return AVERROR(EINVAL);
     }
     bpp = outbuf[16] >> 3;
 
@@ -151,13 +158,13 @@ static av_cold int targa_encode_init(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec targa_encoder = {
+AVCodec ff_targa_encoder = {
     .name = "targa",
     .type = AVMEDIA_TYPE_VIDEO,
     .id = CODEC_ID_TARGA,
     .priv_data_size = sizeof(TargaContext),
     .init = targa_encode_init,
     .encode = targa_encode_frame,
-    .pix_fmts= (const enum PixelFormat[]){PIX_FMT_BGR24, PIX_FMT_RGB555LE, PIX_FMT_GRAY8, PIX_FMT_NONE},
+    .pix_fmts= (const enum PixelFormat[]){PIX_FMT_BGR24, PIX_FMT_BGRA, PIX_FMT_RGB555LE, PIX_FMT_GRAY8, PIX_FMT_NONE},
     .long_name= NULL_IF_CONFIG_SMALL("Truevision Targa image"),
 };
diff --git a/libavcodec/thread.h b/libavcodec/thread.h
new file mode 100644
index 0000000..401c4d2
--- /dev/null
+++ b/libavcodec/thread.h
@@ -0,0 +1,114 @@
+/*
+ * Copyright (c) 2008 Alexander Strange <astrange at ithinksw.com>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * Multithreading support functions
+ * @author Alexander Strange <astrange at ithinksw.com>
+ */
+
+#ifndef AVCODEC_THREAD_H
+#define AVCODEC_THREAD_H
+
+#include "config.h"
+#include "avcodec.h"
+
+/**
+ * Waits for decoding threads to finish and resets internal
+ * state. Called by avcodec_flush_buffers().
+ *
+ * @param avctx The context.
+ */
+void ff_thread_flush(AVCodecContext *avctx);
+
+/**
+ * Submits a new frame to a decoding thread.
+ * Returns the next available frame in picture. *got_picture_ptr
+ * will be 0 if none is available.
+ *
+ * Parameters are the same as avcodec_decode_video2().
+ */
+int ff_thread_decode_frame(AVCodecContext *avctx, AVFrame *picture,
+                           int *got_picture_ptr, AVPacket *avpkt);
+
+/**
+ * If the codec defines update_thread_context(), call this
+ * when they are ready for the next thread to start decoding
+ * the next frame. After calling it, do not change any variables
+ * read by the update_thread_context() method, or call ff_thread_get_buffer().
+ *
+ * @param avctx The context.
+ */
+void ff_thread_finish_setup(AVCodecContext *avctx);
+
+/**
+ * Notifies later decoding threads when part of their reference picture
+ * is ready.
+ * Call this when some part of the picture is finished decoding.
+ * Later calls with lower values of progress have no effect.
+ *
+ * @param f The picture being decoded.
+ * @param progress Value, in arbitrary units, of how much of the picture has decoded.
+ * @param field The field being decoded, for field-picture codecs.
+ * 0 for top field or frame pictures, 1 for bottom field.
+ */
+void ff_thread_report_progress(AVFrame *f, int progress, int field);
+
+/**
+ * Waits for earlier decoding threads to finish reference pictures
+ * Call this before accessing some part of a picture, with a given
+ * value for progress, and it will return after the responsible decoding
+ * thread calls ff_thread_report_progress() with the same or
+ * higher value for progress.
+ *
+ * @param f The picture being referenced.
+ * @param progress Value, in arbitrary units, to wait for.
+ * @param field The field being referenced, for field-picture codecs.
+ * 0 for top field or frame pictures, 1 for bottom field.
+ */
+void ff_thread_await_progress(AVFrame *f, int progress, int field);
+
+/**
+ * Wrapper around get_buffer() for frame-multithreaded codecs.
+ * Call this function instead of avctx->get_buffer(f).
+ * Cannot be called after the codec has called ff_thread_finish_setup().
+ *
+ * @param avctx The current context.
+ * @param f The frame to write into.
+ */
+int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f);
+
+/**
+ * Wrapper around release_buffer() frame-for multithreaded codecs.
+ * Call this function instead of avctx->release_buffer(f).
+ * The AVFrame will be copied and the actual release_buffer() call
+ * will be performed later. The contents of data pointed to by the
+ * AVFrame should not be changed until ff_thread_get_buffer() is called
+ * on it.
+ *
+ * @param avctx The current context.
+ * @param f The picture being released.
+ */
+void ff_thread_release_buffer(AVCodecContext *avctx, AVFrame *f);
+
+int ff_thread_init(AVCodecContext *s);
+void ff_thread_free(AVCodecContext *s);
+
+#endif /* AVCODEC_THREAD_H */
diff --git a/libavcodec/tiertexseqv.c b/libavcodec/tiertexseqv.c
index c5f632e..4468f00 100644
--- a/libavcodec/tiertexseqv.c
+++ b/libavcodec/tiertexseqv.c
@@ -2,20 +2,20 @@
  * Tiertex Limited SEQ Video Decoder
  * Copyright (c) 2006 Gregory Montoir (cyx at users.sourceforge.net)
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -219,7 +219,7 @@ static av_cold int seqvideo_decode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec tiertexseqvideo_decoder = {
+AVCodec ff_tiertexseqvideo_decoder = {
     "tiertexseqvideo",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_TIERTEXSEQVIDEO,
diff --git a/libavcodec/tiff.c b/libavcodec/tiff.c
index 2f3cef2..3cc3a42 100644
--- a/libavcodec/tiff.c
+++ b/libavcodec/tiff.c
@@ -2,20 +2,20 @@
  * TIFF image decoder
  * Copyright (c) 2006 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -33,6 +33,7 @@
 #include "faxcompr.h"
 #include "libavutil/common.h"
 #include "libavutil/intreadwrite.h"
+#include "libavutil/imgutils.h"
 
 typedef struct TiffContext {
     AVCodecContext *avctx;
@@ -262,6 +263,10 @@ static int tiff_decode_tag(TiffContext *s, const uint8_t *start, const uint8_t *
         s->height = value;
         break;
     case TIFF_BPP:
+        if(count > 4){
+            av_log(s->avctx, AV_LOG_ERROR, "This format is not supported (bpp=%d, %d components)\n", s->bpp, count);
+            return -1;
+        }
         if(count == 1) s->bpp = value;
         else{
             switch(type){
@@ -277,10 +282,6 @@ static int tiff_decode_tag(TiffContext *s, const uint8_t *start, const uint8_t *
                 s->bpp = -1;
             }
         }
-        if(count > 4){
-            av_log(s->avctx, AV_LOG_ERROR, "This format is not supported (bpp=%d, %d components)\n", s->bpp, count);
-            return -1;
-        }
         switch(s->bpp*10 + count){
         case 11:
             s->avctx->pix_fmt = PIX_FMT_MONOBLACK;
@@ -305,7 +306,7 @@ static int tiff_decode_tag(TiffContext *s, const uint8_t *start, const uint8_t *
             return -1;
         }
         if(s->width != s->avctx->width || s->height != s->avctx->height){
-            if(avcodec_check_dimensions(s->avctx, s->width, s->height))
+            if(av_image_check_size(s->width, s->height, 0, s->avctx))
                 return -1;
             avcodec_set_dimensions(s->avctx, s->width, s->height);
         }
@@ -507,7 +508,7 @@ static int decode_frame(AVCodecContext *avctx,
         s->bpp = 1;
         avctx->pix_fmt = PIX_FMT_MONOBLACK;
         if(s->width != s->avctx->width || s->height != s->avctx->height){
-            if(avcodec_check_dimensions(s->avctx, s->width, s->height))
+            if(av_image_check_size(s->width, s->height, 0, s->avctx))
                 return -1;
             avcodec_set_dimensions(s->avctx, s->width, s->height);
         }
@@ -530,10 +531,19 @@ static int decode_frame(AVCodecContext *avctx,
         else
             ssize = s->stripsize;
 
+        if (ssize > buf_size) {
+            av_log(avctx, AV_LOG_ERROR, "Buffer size is smaller than strip size\n");
+            return -1;
+        }
+
         if(s->stripdata){
             soff = tget(&s->stripdata, s->sot, s->le);
         }else
             soff = s->stripoff;
+        if (soff < 0) {
+            av_log(avctx, AV_LOG_ERROR, "Invalid stripoff: %d\n", soff);
+            return AVERROR(EINVAL);
+        }
         if(tiff_unpack_strip(s, dst, stride, orig_buf + soff, ssize, FFMIN(s->rps, s->height - i)) < 0)
             break;
         dst += s->rps * stride;
@@ -590,7 +600,7 @@ static av_cold int tiff_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec tiff_decoder = {
+AVCodec ff_tiff_decoder = {
     "tiff",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_TIFF,
diff --git a/libavcodec/tiff.h b/libavcodec/tiff.h
index 235a998..cd7ec83 100644
--- a/libavcodec/tiff.h
+++ b/libavcodec/tiff.h
@@ -2,20 +2,20 @@
  * TIFF tables
  * Copyright (c) 2006 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/tiffenc.c b/libavcodec/tiffenc.c
index 0905cea..049b28f 100644
--- a/libavcodec/tiffenc.c
+++ b/libavcodec/tiffenc.c
@@ -2,20 +2,20 @@
  * TIFF image encoder
  * Copyright (c) 2007 Bartlomiej Wolowiec
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -442,7 +442,7 @@ fail:
     return ret;
 }
 
-AVCodec tiff_encoder = {
+AVCodec ff_tiff_encoder = {
     "tiff",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_TIFF,
diff --git a/libavcodec/tmv.c b/libavcodec/tmv.c
index 5117cd0..3c2ae01 100644
--- a/libavcodec/tmv.c
+++ b/libavcodec/tmv.c
@@ -2,20 +2,20 @@
  * 8088flex TMV video decoder
  * Copyright (c) 2009 Daniel Verkamp <daniel at drv.nu>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -39,10 +39,10 @@ static int tmv_decode_frame(AVCodecContext *avctx, void *data,
 {
     TMVContext *tmv    = avctx->priv_data;
     const uint8_t *src = avpkt->data;
-    uint8_t *dst, *dst_char;
+    uint8_t *dst;
     unsigned char_cols = avctx->width >> 3;
     unsigned char_rows = avctx->height >> 3;
-    unsigned x, y, mask, char_y, fg, bg, c;
+    unsigned x, y, fg, bg, c;
 
     if (tmv->pic.data[0])
         avctx->release_buffer(avctx, &tmv->pic);
@@ -68,17 +68,11 @@ static int tmv_decode_frame(AVCodecContext *avctx, void *data,
 
     for (y = 0; y < char_rows; y++) {
         for (x = 0; x < char_cols; x++) {
-            c  = *src++ * 8;
+            c  = *src++;
             bg = *src  >> 4;
             fg = *src++ & 0xF;
-
-            dst_char = dst + x * 8;
-            for (char_y = 0; char_y < 8; char_y++) {
-                for (mask = 0x80; mask; mask >>= 1) {
-                    *dst_char++ = ff_cga_font[c + char_y] & mask ? fg : bg;
-                }
-                dst_char += tmv->pic.linesize[0] - 8;
-            }
+            ff_draw_pc_font(dst + x * 8, tmv->pic.linesize[0],
+                            ff_cga_font, 8, c, fg, bg);
         }
         dst += tmv->pic.linesize[0] * 8;
     }
@@ -98,7 +92,7 @@ static av_cold int tmv_decode_close(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec tmv_decoder = {
+AVCodec ff_tmv_decoder = {
     .name           = "tmv",
     .type           = AVMEDIA_TYPE_VIDEO,
     .id             = CODEC_ID_TMV,
diff --git a/libavcodec/truemotion1.c b/libavcodec/truemotion1.c
index 4306917..afa9cf2 100644
--- a/libavcodec/truemotion1.c
+++ b/libavcodec/truemotion1.c
@@ -2,20 +2,20 @@
  * Duck TrueMotion 1.0 Decoder
  * Copyright (C) 2003 Alex Beregszaszi & Mike Melanson
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -35,6 +35,7 @@
 
 #include "avcodec.h"
 #include "dsputil.h"
+#include "libavutil/imgutils.h"
 
 #include "truemotion1data.h"
 
@@ -71,6 +72,7 @@ typedef struct TrueMotion1Context {
     int last_deltaset, last_vectable;
 
     unsigned int *vert_pred;
+    int vert_pred_size;
 
 } TrueMotion1Context;
 
@@ -178,11 +180,7 @@ static int make_ydt15_entry(int p1, int p2, int16_t *ydt)
     return (lo + (hi << 16)) << 1;
 }
 
-#if HAVE_BIGENDIAN
-static int make_cdt15_entry(int p2, int p1, int16_t *cdt)
-#else
 static int make_cdt15_entry(int p1, int p2, int16_t *cdt)
-#endif
 {
     int r, b, lo;
 
@@ -207,11 +205,7 @@ static int make_ydt16_entry(int p1, int p2, int16_t *ydt)
     return (lo + (hi << 16)) << 1;
 }
 
-#if HAVE_BIGENDIAN
-static int make_cdt16_entry(int p2, int p1, int16_t *cdt)
-#else
 static int make_cdt16_entry(int p1, int p2, int16_t *cdt)
-#endif
 {
     int r, b, lo;
 
@@ -221,11 +215,7 @@ static int make_cdt16_entry(int p1, int p2, int16_t *cdt)
     return (lo + (lo << 16)) << 1;
 }
 
-#if HAVE_BIGENDIAN
-static int make_ydt24_entry(int p2, int p1, int16_t *ydt)
-#else
 static int make_ydt24_entry(int p1, int p2, int16_t *ydt)
-#endif
 {
     int lo, hi;
 
@@ -234,11 +224,7 @@ static int make_ydt24_entry(int p1, int p2, int16_t *ydt)
     return (lo + (hi << 8) + (hi << 16)) << 1;
 }
 
-#if HAVE_BIGENDIAN
-static int make_cdt24_entry(int p2, int p1, int16_t *cdt)
-#else
 static int make_cdt24_entry(int p1, int p2, int16_t *cdt)
-#endif
 {
     int r, b;
 
@@ -321,15 +307,12 @@ static void gen_vector_table24(TrueMotion1Context *s, const uint8_t *sel_vector_
 static int truemotion1_decode_header(TrueMotion1Context *s)
 {
     int i;
+    int width_shift = 0;
+    int new_pix_fmt;
     struct frame_header header;
     uint8_t header_buffer[128];  /* logical maximum size of the header */
     const uint8_t *sel_vector_table;
 
-    /* There is 1 change bit per 4 pixels, so each change byte represents
-     * 32 pixels; divide width by 4 to obtain the number of change bits and
-     * then round up to the nearest byte. */
-    s->mb_change_bits_row_size = ((s->avctx->width >> 2) + 7) >> 3;
-
     header.header_size = ((s->buf[0] >> 5) | (s->buf[0] << 3)) & 0x7f;
     if (s->buf[0] < 0x10)
     {
@@ -404,7 +387,7 @@ static int truemotion1_decode_header(TrueMotion1Context *s)
     if ((header.compression & 1) && header.header_type)
         sel_vector_table = pc_tbl2;
     else {
-        if (header.vectable < 4)
+        if (header.vectable > 0 && header.vectable < 4)
             sel_vector_table = tables[header.vectable - 1];
         else {
             av_log(s->avctx, AV_LOG_ERROR, "invalid vector table id (%d)\n", header.vectable);
@@ -412,11 +395,30 @@ static int truemotion1_decode_header(TrueMotion1Context *s)
         }
     }
 
-    // FIXME: where to place this ?!?!
-    if (compression_types[header.compression].algorithm == ALGO_RGB24H)
-        s->avctx->pix_fmt = PIX_FMT_RGB32;
-    else
-        s->avctx->pix_fmt = PIX_FMT_RGB555; // RGB565 is supported as well
+    if (compression_types[header.compression].algorithm == ALGO_RGB24H) {
+        new_pix_fmt = PIX_FMT_RGB32;
+        width_shift = 1;
+    } else
+        new_pix_fmt = PIX_FMT_RGB555; // RGB565 is supported as well
+
+    s->w >>= width_shift;
+    if (av_image_check_size(s->w, s->h, 0, s->avctx) < 0)
+        return -1;
+
+    if (s->w != s->avctx->width || s->h != s->avctx->height ||
+        new_pix_fmt != s->avctx->pix_fmt) {
+        if (s->frame.data[0])
+            s->avctx->release_buffer(s->avctx, &s->frame);
+        s->avctx->sample_aspect_ratio = (AVRational){ 1 << width_shift, 1 };
+        s->avctx->pix_fmt = new_pix_fmt;
+        avcodec_set_dimensions(s->avctx, s->w, s->h);
+        av_fast_malloc(&s->vert_pred, &s->vert_pred_size, s->avctx->width * sizeof(unsigned int));
+    }
+
+    /* There is 1 change bit per 4 pixels, so each change byte represents
+     * 32 pixels; divide width by 4 to obtain the number of change bits and
+     * then round up to the nearest byte. */
+    s->mb_change_bits_row_size = ((s->avctx->width >> (2 - width_shift)) + 7) >> 3;
 
     if ((header.deltaset != s->last_deltaset) || (header.vectable != s->last_vectable))
     {
@@ -476,8 +478,7 @@ static av_cold int truemotion1_decode_init(AVCodecContext *avctx)
 
     /* there is a vertical predictor for each pixel in a line; each vertical
      * predictor is 0 to start with */
-    s->vert_pred =
-        (unsigned int *)av_malloc(s->avctx->width * sizeof(unsigned int));
+    av_fast_malloc(&s->vert_pred, &s->vert_pred_size, s->avctx->width * sizeof(unsigned int));
 
     return 0;
 }
@@ -831,7 +832,7 @@ static void truemotion1_decode_24bit(TrueMotion1Context *s)
                 }
             }
 
-            pixels_left -= 4;
+            pixels_left -= 2;
         }
 
         /* next change row */
@@ -890,7 +891,7 @@ static av_cold int truemotion1_decode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec truemotion1_decoder = {
+AVCodec ff_truemotion1_decoder = {
     "truemotion1",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_TRUEMOTION1,
diff --git a/libavcodec/truemotion1data.h b/libavcodec/truemotion1data.h
index 6a9822a..c94e3b5 100644
--- a/libavcodec/truemotion1data.h
+++ b/libavcodec/truemotion1data.h
@@ -6,20 +6,20 @@
  * GNU LGPL using the common understanding that data tables necessary for
  * decoding algorithms are not necessarily licensable.
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #ifndef AVCODEC_TRUEMOTION1DATA_H
diff --git a/libavcodec/truemotion2.c b/libavcodec/truemotion2.c
index 5013a9e..6c3ed8c 100644
--- a/libavcodec/truemotion2.c
+++ b/libavcodec/truemotion2.c
@@ -2,20 +2,20 @@
  * Duck/ON2 TrueMotion 2 Decoder
  * Copyright (c) 2005 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -64,7 +64,7 @@ typedef struct TM2Context{
 * Huffman codes for each of streams
 */
 typedef struct TM2Codes{
-    VLC vlc; ///< table for FFmpeg bitstream reader
+    VLC vlc; ///< table for Libav bitstream reader
     int bits;
     int *recode; ///< table for converting from code indexes to values
     int length;
@@ -185,8 +185,7 @@ static int tm2_build_huff_table(TM2Context *ctx, TM2Codes *code)
 
 static void tm2_free_codes(TM2Codes *code)
 {
-    if(code->recode)
-        av_free(code->recode);
+    av_free(code->recode);
     if(code->vlc.table)
         free_vlc(&code->vlc);
 }
@@ -260,7 +259,8 @@ static int tm2_read_deltas(TM2Context *ctx, int stream_id) {
     return 0;
 }
 
-static int tm2_read_stream(TM2Context *ctx, const uint8_t *buf, int stream_id) {
+static int tm2_read_stream(TM2Context *ctx, const uint8_t *buf, int stream_id, int buf_size)
+{
     int i;
     int cur = 0;
     int skip = 0;
@@ -274,6 +274,11 @@ static int tm2_read_stream(TM2Context *ctx, const uint8_t *buf, int stream_id) {
     if(len == 0)
         return 4;
 
+    if (len >= INT_MAX/4-1 || len < 0 || len > buf_size) {
+        av_log(ctx->avctx, AV_LOG_ERROR, "Error, invalid stream size.\n");
+        return -1;
+    }
+
     toks = AV_RB32(buf); buf += 4; cur += 4;
     if(toks & 1) {
         len = AV_RB32(buf); buf += 4; cur += 4;
@@ -313,8 +318,13 @@ static int tm2_read_stream(TM2Context *ctx, const uint8_t *buf, int stream_id) {
     len = AV_RB32(buf); buf += 4; cur += 4;
     if(len > 0) {
         init_get_bits(&ctx->gb, buf, (skip - cur) * 8);
-        for(i = 0; i < toks; i++)
+        for(i = 0; i < toks; i++) {
+            if (get_bits_left(&ctx->gb) <= 0) {
+                av_log(ctx->avctx, AV_LOG_ERROR, "Incorrect number of tokens: %i\n", toks);
+                return -1;
+            }
             ctx->tokens[stream_id][i] = tm2_get_token(&ctx->gb, &codes);
+        }
     } else {
         for(i = 0; i < toks; i++)
             ctx->tokens[stream_id][i] = codes.recode[0];
@@ -788,7 +798,7 @@ static int decode_frame(AVCodecContext *avctx,
     }
 
     for(i = 0; i < TM2_NUM_STREAMS; i++){
-        t = tm2_read_stream(l, swbuf + skip, tm2_stream_order[i]);
+        t = tm2_read_stream(l, swbuf + skip, tm2_stream_order[i], buf_size);
         if(t == -1){
             av_free(swbuf);
             return -1;
@@ -848,13 +858,10 @@ static av_cold int decode_end(AVCodecContext *avctx){
     AVFrame *pic = &l->pic;
     int i;
 
-    if(l->last)
-        av_free(l->last);
-    if(l->clast)
-        av_free(l->clast);
+    av_free(l->last);
+    av_free(l->clast);
     for(i = 0; i < TM2_NUM_STREAMS; i++)
-        if(l->tokens[i])
-            av_free(l->tokens[i]);
+        av_free(l->tokens[i]);
     if(l->Y1){
         av_free(l->Y1);
         av_free(l->U1);
@@ -870,7 +877,7 @@ static av_cold int decode_end(AVCodecContext *avctx){
     return 0;
 }
 
-AVCodec truemotion2_decoder = {
+AVCodec ff_truemotion2_decoder = {
     "truemotion2",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_TRUEMOTION2,
diff --git a/libavcodec/truespeech.c b/libavcodec/truespeech.c
index 37fbef9..df9d918 100644
--- a/libavcodec/truespeech.c
+++ b/libavcodec/truespeech.c
@@ -2,20 +2,20 @@
  * DSP Group TrueSpeech compatible decoder
  * Copyright (c) 2005 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -56,7 +56,7 @@ static av_cold int truespeech_decode_init(AVCodecContext * avctx)
 {
 //    TSContext *c = avctx->priv_data;
 
-    avctx->sample_fmt = SAMPLE_FMT_S16;
+    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
     return 0;
 }
 
@@ -165,7 +165,7 @@ static void truespeech_correlate_filter(TSContext *dec)
         dec->cvector[i] = (8 - dec->vector[i]) >> 3;
     }
     for(i = 0; i < 8; i++)
-        dec->cvector[i] = (dec->cvector[i] * ts_230[i]) >> 15;
+        dec->cvector[i] = (dec->cvector[i] * ts_decay_994_1000[i]) >> 15;
 
     dec->filtval = dec->vector[0];
 }
@@ -207,7 +207,7 @@ static void truespeech_apply_twopoint_filter(TSContext *dec, int quart)
     off = (t / 25) + dec->offset1[quart >> 1] + 18;
     ptr0 = tmp + 145 - off;
     ptr1 = tmp + 146;
-    filter = (const int16_t*)ts_240 + (t % 25) * 2;
+    filter = (const int16_t*)ts_order2_coeffs + (t % 25) * 2;
     for(i = 0; i < 60; i++){
         t = (ptr0[0] * filter[0] + ptr0[1] * filter[1] + 0x2000) >> 14;
         ptr0++;
@@ -228,11 +228,11 @@ static void truespeech_place_pulses(TSContext *dec, int16_t *out, int quart)
     for(i = 0; i < 7; i++) {
         t = dec->pulseval[quart] & 3;
         dec->pulseval[quart] >>= 2;
-        tmp[6 - i] = ts_562[dec->pulseoff[quart] * 4 + t];
+        tmp[6 - i] = ts_pulse_scales[dec->pulseoff[quart] * 4 + t];
     }
 
     coef = dec->pulsepos[quart] >> 15;
-    ptr1 = (const int16_t*)ts_140 + 30;
+    ptr1 = (const int16_t*)ts_pulse_values + 30;
     ptr2 = tmp;
     for(i = 0, j = 3; (i < 30) && (j > 0); i++){
         t = *ptr1++;
@@ -245,7 +245,7 @@ static void truespeech_place_pulses(TSContext *dec, int16_t *out, int quart)
         }
     }
     coef = dec->pulsepos[quart] & 0x7FFF;
-    ptr1 = (const int16_t*)ts_140;
+    ptr1 = (const int16_t*)ts_pulse_values;
     for(i = 30, j = 4; (i < 60) && (j > 0); i++){
         t = *ptr1++;
         if(coef >= t)
@@ -291,7 +291,7 @@ static void truespeech_synth(TSContext *dec, int16_t *out, int quart)
     }
 
     for(i = 0; i < 8; i++)
-        t[i] = (ts_5E2[i] * ptr1[i]) >> 15;
+        t[i] = (ts_decay_35_64[i] * ptr1[i]) >> 15;
 
     ptr0 = dec->tmp2;
     for(i = 0; i < 60; i++){
@@ -305,7 +305,7 @@ static void truespeech_synth(TSContext *dec, int16_t *out, int quart)
     }
 
     for(i = 0; i < 8; i++)
-        t[i] = (ts_5F2[i] * ptr1[i]) >> 15;
+        t[i] = (ts_decay_3_4[i] * ptr1[i]) >> 15;
 
     ptr0 = dec->tmp3;
     for(i = 0; i < 60; i++){
@@ -347,6 +347,11 @@ static int truespeech_decode_frame(AVCodecContext *avctx,
     if (!buf_size)
         return 0;
 
+    if (buf_size < 32) {
+        av_log(avctx, AV_LOG_ERROR,
+               "Too small input buffer (%d bytes), need at least 32 bytes\n", buf_size);
+        return -1;
+    }
     iterations = FFMIN(buf_size / 32, *data_size / 480);
     for(j = 0; j < iterations; j++) {
         truespeech_read_frame(c, buf + consumed);
@@ -376,7 +381,7 @@ static int truespeech_decode_frame(AVCodecContext *avctx,
     return consumed;
 }
 
-AVCodec truespeech_decoder = {
+AVCodec ff_truespeech_decoder = {
     "truespeech",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_TRUESPEECH,
diff --git a/libavcodec/truespeech_data.h b/libavcodec/truespeech_data.h
index eef7da8..6e9806a 100644
--- a/libavcodec/truespeech_data.h
+++ b/libavcodec/truespeech_data.h
@@ -2,20 +2,20 @@
  * DSP Group TrueSpeech compatible decoder
  * copyright (c) 2005 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -71,7 +71,7 @@ static const int16_t * const ts_codebook[8] = {
 };
 
 /* table used for decoding pulse positions */
-static const int16_t ts_140[120] = {
+static const int16_t ts_pulse_values[120] = {
     0x0E46, 0x0CCC, 0x0B6D, 0x0A28, 0x08FC, 0x07E8, 0x06EB, 0x0604,
     0x0532, 0x0474, 0x03C9, 0x0330, 0x02A8, 0x0230, 0x01C7, 0x016C,
     0x011E, 0x00DC, 0x00A5, 0x0078, 0x0054, 0x0038, 0x0023, 0x0014,
@@ -94,11 +94,11 @@ static const int16_t ts_140[120] = {
 };
 
 /* filter for correlated input filter */
-static const int16_t ts_230[8] =
+static const int16_t ts_decay_994_1000[8] =
     { 0x7F3B, 0x7E78, 0x7DB6, 0x7CF5, 0x7C35, 0x7B76, 0x7AB8, 0x79FC };
 
 /* two-point filters table */
-static const int16_t ts_240[25 * 2] = {
+static const int16_t ts_order2_coeffs[25 * 2] = {
     0xED2F, 0x5239,
     0x54F1, 0xE4A9,
     0x2620, 0xEE3E,
@@ -131,7 +131,7 @@ static const int16_t ts_240[25 * 2] = {
 };
 
 /* possible pulse values */
-static const int16_t ts_562[64] = {
+static const int16_t ts_pulse_scales[64] = {
     0x0002, 0x0006, 0xFFFE, 0xFFFA,
     0x0004, 0x000C, 0xFFFC, 0xFFF4,
     0x0006, 0x0012, 0xFFFA, 0xFFEE,
@@ -151,9 +151,9 @@ static const int16_t ts_562[64] = {
 };
 
 /* filters used in final output calculations */
-static const int16_t ts_5E2[8] =
+static const int16_t ts_decay_35_64[8] =
     { 0x4666, 0x26B8, 0x154C, 0x0BB6, 0x0671, 0x038B, 0x01F3, 0x0112 };
-static const int16_t ts_5F2[8] =
+static const int16_t ts_decay_3_4[8] =
     { 0x6000, 0x4800, 0x3600, 0x2880, 0x1E60, 0x16C8, 0x1116, 0x0CD1 };
 
 #endif /* AVCODEC_TRUESPEECH_DATA_H */
diff --git a/libavcodec/tscc.c b/libavcodec/tscc.c
index 2b717c1..bd05f02 100644
--- a/libavcodec/tscc.c
+++ b/libavcodec/tscc.c
@@ -2,20 +2,20 @@
  * TechSmith Camtasia decoder
  * Copyright (c) 2004 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -60,6 +60,8 @@ typedef struct TsccContext {
     unsigned char* decomp_buf;
     int height;
     z_stream zstream;
+
+    uint32_t pal[256];
 } CamtasiaContext;
 
 /*
@@ -111,11 +113,13 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPac
 
     /* make the palette available on the way out */
     if (c->avctx->pix_fmt == PIX_FMT_PAL8) {
-        memcpy(c->pic.data[1], c->avctx->palctrl->palette, AVPALETTE_SIZE);
-        if (c->avctx->palctrl->palette_changed) {
+        const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, NULL);
+
+        if (pal) {
             c->pic.palette_has_changed = 1;
-            c->avctx->palctrl->palette_changed = 0;
+            memcpy(c->pal, pal, AVPALETTE_SIZE);
         }
+        memcpy(c->pic.data[1], c->pal, AVPALETTE_SIZE);
     }
 
     *data_size = sizeof(AVFrame);
@@ -197,7 +201,7 @@ static av_cold int decode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec tscc_decoder = {
+AVCodec ff_tscc_decoder = {
         "camtasia",
         AVMEDIA_TYPE_VIDEO,
         CODEC_ID_TSCC,
diff --git a/libavcodec/tta.c b/libavcodec/tta.c
index 4bdfd73..fbfc59e 100644
--- a/libavcodec/tta.c
+++ b/libavcodec/tta.c
@@ -2,20 +2,20 @@
  * TTA (The Lossless True Audio) decoder
  * Copyright (c) 2006 Alex Beregszaszi
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -36,6 +36,24 @@
 #define FORMAT_INT 1
 #define FORMAT_FLOAT 3
 
+#define MAX_ORDER 16
+typedef struct TTAFilter {
+    int32_t shift, round, error, mode;
+    int32_t qm[MAX_ORDER];
+    int32_t dx[MAX_ORDER];
+    int32_t dl[MAX_ORDER];
+} TTAFilter;
+
+typedef struct TTARice {
+    uint32_t k0, k1, sum0, sum1;
+} TTARice;
+
+typedef struct TTAChannel {
+    int32_t predictor;
+    TTAFilter filter;
+    TTARice rice;
+} TTAChannel;
+
 typedef struct TTAContext {
     AVCodecContext *avctx;
     GetBitContext gb;
@@ -44,6 +62,8 @@ typedef struct TTAContext {
     int frame_length, last_frame_length, total_frames;
 
     int32_t *decode_buffer;
+
+    TTAChannel *ch_ctx;
 } TTAContext;
 
 #if 0
@@ -79,14 +99,6 @@ static const uint32_t shift_1[] = {
 static const uint32_t * const shift_16 = shift_1 + 4;
 #endif
 
-#define MAX_ORDER 16
-typedef struct TTAFilter {
-    int32_t shift, round, error, mode;
-    int32_t qm[MAX_ORDER];
-    int32_t dx[MAX_ORDER];
-    int32_t dl[MAX_ORDER];
-} TTAFilter;
-
 static const int32_t ttafilter_configs[4][2] = {
     {10, 1},
     {9, 1},
@@ -175,10 +187,6 @@ static inline void ttafilter_process(TTAFilter *c, int32_t *in, int32_t mode) {
     memshl(c->dx, c->dx + 1);
 }
 
-typedef struct TTARice {
-    uint32_t k0, k1, sum0, sum1;
-} TTARice;
-
 static void rice_init(TTARice *c, uint32_t k0, uint32_t k1)
 {
     c->k0 = k0;
@@ -213,7 +221,7 @@ static av_cold int tta_decode_init(AVCodecContext * avctx)
     {
         /* signature */
         skip_bits(&s->gb, 32);
-//        if (get_bits_long(&s->gb, 32) != bswap_32(AV_RL32("TTA1"))) {
+//        if (get_bits_long(&s->gb, 32) != av_bswap32(AV_RL32("TTA1"))) {
 //            av_log(s->avctx, AV_LOG_ERROR, "Missing magic\n");
 //            return -1;
 //        }
@@ -238,15 +246,15 @@ static av_cold int tta_decode_init(AVCodecContext * avctx)
 
         if (s->is_float)
         {
-            avctx->sample_fmt = SAMPLE_FMT_FLT;
+            avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
             av_log(s->avctx, AV_LOG_ERROR, "Unsupported sample format. Please contact the developers.\n");
             return -1;
         }
         else switch(s->bps) {
-//            case 1: avctx->sample_fmt = SAMPLE_FMT_U8; break;
-            case 2: avctx->sample_fmt = SAMPLE_FMT_S16; break;
-//            case 3: avctx->sample_fmt = SAMPLE_FMT_S24; break;
-            case 4: avctx->sample_fmt = SAMPLE_FMT_S32; break;
+//            case 1: avctx->sample_fmt = AV_SAMPLE_FMT_U8; break;
+            case 2: avctx->sample_fmt = AV_SAMPLE_FMT_S16; break;
+//            case 3: avctx->sample_fmt = AV_SAMPLE_FMT_S24; break;
+            case 4: avctx->sample_fmt = AV_SAMPLE_FMT_S32; break;
             default:
                 av_log(s->avctx, AV_LOG_ERROR, "Invalid/unsupported sample format. Please contact the developers.\n");
                 return -1;
@@ -277,6 +285,9 @@ static av_cold int tta_decode_init(AVCodecContext * avctx)
         }
 
         s->decode_buffer = av_mallocz(sizeof(int32_t)*s->frame_length*s->channels);
+        s->ch_ctx = av_malloc(avctx->channels * sizeof(*s->ch_ctx));
+        if (!s->ch_ctx)
+            return AVERROR(ENOMEM);
     } else {
         av_log(avctx, AV_LOG_ERROR, "Wrong extradata present\n");
         return -1;
@@ -296,9 +307,6 @@ static int tta_decode_frame(AVCodecContext *avctx,
 
     init_get_bits(&s->gb, buf, buf_size*8);
     {
-        int32_t predictors[s->channels];
-        TTAFilter filters[s->channels];
-        TTARice rices[s->channels];
         int cur_chan = 0, framelen = s->frame_length;
         int32_t *p;
 
@@ -313,15 +321,15 @@ static int tta_decode_frame(AVCodecContext *avctx,
 
         // init per channel states
         for (i = 0; i < s->channels; i++) {
-            predictors[i] = 0;
-            ttafilter_init(&(filters[i]), ttafilter_configs[s->bps-1][0], ttafilter_configs[s->bps-1][1]);
-            rice_init(&(rices[i]), 10, 10);
+            s->ch_ctx[i].predictor = 0;
+            ttafilter_init(&s->ch_ctx[i].filter, ttafilter_configs[s->bps-1][0], ttafilter_configs[s->bps-1][1]);
+            rice_init(&s->ch_ctx[i].rice, 10, 10);
         }
 
         for (p = s->decode_buffer; p < s->decode_buffer + (framelen * s->channels); p++) {
-            int32_t *predictor = &(predictors[cur_chan]);
-            TTAFilter *filter = &(filters[cur_chan]);
-            TTARice *rice = &(rices[cur_chan]);
+            int32_t *predictor = &s->ch_ctx[cur_chan].predictor;
+            TTAFilter *filter = &s->ch_ctx[cur_chan].filter;
+            TTARice *rice = &s->ch_ctx[cur_chan].rice;
             uint32_t unary, depth, k;
             int32_t value;
 
@@ -441,13 +449,13 @@ static int tta_decode_frame(AVCodecContext *avctx,
 static av_cold int tta_decode_close(AVCodecContext *avctx) {
     TTAContext *s = avctx->priv_data;
 
-    if (s->decode_buffer)
-        av_free(s->decode_buffer);
+    av_free(s->decode_buffer);
+    av_freep(&s->ch_ctx);
 
     return 0;
 }
 
-AVCodec tta_decoder = {
+AVCodec ff_tta_decoder = {
     "tta",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_TTA,
diff --git a/libavcodec/twinvq.c b/libavcodec/twinvq.c
index 6ab3a46..e1a8dc4 100644
--- a/libavcodec/twinvq.c
+++ b/libavcodec/twinvq.c
@@ -2,20 +2,20 @@
  * TwinVQ decoder
  * Copyright (c) 2009 Vitor Sessak
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -24,6 +24,7 @@
 #include "dsputil.h"
 #include "fft.h"
 #include "lsp.h"
+#include "sinewin.h"
 
 #include <math.h>
 #include <stdint.h>
@@ -202,6 +203,7 @@ typedef struct TwinContext {
 } TwinContext;
 
 #define PPC_SHAPE_CB_SIZE 64
+#define PPC_SHAPE_LEN_MAX 60
 #define SUB_AMP_MAX       4500.0
 #define MULAW_MU          100.0
 #define GAIN_BITS         8
@@ -209,6 +211,11 @@ typedef struct TwinContext {
 #define SUB_GAIN_BITS     5
 #define WINDOW_TYPE_BITS  4
 #define PGAIN_MU          200
+#define LSP_COEFS_MAX     20
+#define LSP_SPLIT_MAX     4
+#define CHANNELS_MAX      2
+#define SUBBLOCKS_MAX     16
+#define BARK_N_COEF_MAX   4
 
 /** @note not speed critical, hence not optimized */
 static void memset_float(float *buf, float val, int size)
@@ -252,7 +259,7 @@ static float eval_lpc_spectrum(const float *lsp, float cos_val, int order)
 }
 
 /**
- * Evaluates the LPC amplitude spectrum envelope from the line spectrum pairs.
+ * Evaluate the LPC amplitude spectrum envelope from the line spectrum pairs.
  */
 static void eval_lpcenv(TwinContext *tctx, const float *cos_vals, float *lpc)
 {
@@ -285,7 +292,7 @@ static inline float get_cos(int idx, int part, const float *cos_tab, int size)
 }
 
 /**
- * Evaluates the LPC amplitude spectrum envelope from the line spectrum pairs.
+ * Evaluate the LPC amplitude spectrum envelope from the line spectrum pairs.
  * Probably for speed reasons, the coefficients are evaluated as
  * siiiibiiiisiiiibiiiisiiiibiiiisiiiibiiiis ...
  * where s is an evaluated value, i is a value interpolated from the others
@@ -602,6 +609,7 @@ static void dec_lpc_spectrum_inv(TwinContext *tctx, float *lsp,
 static void imdct_and_window(TwinContext *tctx, enum FrameType ftype, int wtype,
                             float *in, float *prev, int ch)
 {
+    FFTContext *mdct = &tctx->mdct_ctx[ftype];
     const ModeTab *mtab = tctx->mtab;
     int bsize = mtab->size / mtab->fmode[ftype].sub;
     int size  = mtab->size;
@@ -634,13 +642,12 @@ static void imdct_and_window(TwinContext *tctx, enum FrameType ftype, int wtype,
 
         wsize = types_sizes[wtype_to_wsize[sub_wtype]];
 
-        ff_imdct_half(&tctx->mdct_ctx[ftype], buf1 + bsize*j, in + bsize*j);
+        mdct->imdct_half(mdct, buf1 + bsize*j, in + bsize*j);
 
         tctx->dsp.vector_fmul_window(out2,
                                      prev_buf + (bsize-wsize)/2,
                                      buf1 + bsize*j,
                                      ff_sine_windows[av_log2(wsize)],
-                                     0.0,
                                      wsize/2);
         out2 += wsize;
 
@@ -727,14 +734,14 @@ static void read_and_decode_spectrum(TwinContext *tctx, GetBitContext *gb,
     int channels = tctx->avctx->channels;
     int sub = mtab->fmode[ftype].sub;
     int block_size = mtab->size / sub;
-    float gain[channels*sub];
-    float ppc_shape[mtab->ppc_shape_len * channels * 4];
-    uint8_t bark1[channels][sub][mtab->fmode[ftype].bark_n_coef];
-    uint8_t bark_use_hist[channels][sub];
+    float gain[CHANNELS_MAX*SUBBLOCKS_MAX];
+    float ppc_shape[PPC_SHAPE_LEN_MAX * CHANNELS_MAX * 4];
+    uint8_t bark1[CHANNELS_MAX][SUBBLOCKS_MAX][BARK_N_COEF_MAX];
+    uint8_t bark_use_hist[CHANNELS_MAX][SUBBLOCKS_MAX];
 
-    uint8_t lpc_idx1[channels];
-    uint8_t lpc_idx2[channels][tctx->mtab->lsp_split];
-    uint8_t lpc_hist_idx[channels];
+    uint8_t lpc_idx1[CHANNELS_MAX];
+    uint8_t lpc_idx2[CHANNELS_MAX][LSP_SPLIT_MAX];
+    uint8_t lpc_hist_idx[CHANNELS_MAX];
 
     int i, j, k;
 
@@ -771,13 +778,13 @@ static void read_and_decode_spectrum(TwinContext *tctx, GetBitContext *gb,
 
     for (i = 0; i < channels; i++) {
         float *chunk = out + mtab->size * i;
-        float lsp[tctx->mtab->n_lsp];
+        float lsp[LSP_COEFS_MAX];
 
         for (j = 0; j < sub; j++) {
             dec_bark_env(tctx, bark1[i][j], bark_use_hist[i][j], i,
                          tctx->tmp_buf, gain[sub*i+j], ftype);
 
-            tctx->dsp.vector_fmul(chunk + block_size*j, tctx->tmp_buf,
+            tctx->dsp.vector_fmul(chunk + block_size*j, chunk + block_size*j, tctx->tmp_buf,
                                   block_size);
 
         }
@@ -799,7 +806,7 @@ static void read_and_decode_spectrum(TwinContext *tctx, GetBitContext *gb,
         dec_lpc_spectrum_inv(tctx, lsp, ftype, tctx->tmp_buf);
 
         for (j = 0; j < mtab->fmode[ftype].sub; j++) {
-            tctx->dsp.vector_fmul(chunk, tctx->tmp_buf, block_size);
+            tctx->dsp.vector_fmul(chunk, chunk, tctx->tmp_buf, block_size);
             chunk += block_size;
         }
     }
@@ -1062,9 +1069,9 @@ static av_cold int twin_decode_init(AVCodecContext *avctx)
     int ibps = avctx->bit_rate/(1000 * avctx->channels);
 
     tctx->avctx       = avctx;
-    avctx->sample_fmt = SAMPLE_FMT_FLT;
+    avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
 
-    if (avctx->channels > 2) {
+    if (avctx->channels > CHANNELS_MAX) {
         av_log(avctx, AV_LOG_ERROR, "Unsupported number of channels: %i\n",
                avctx->channels);
         return -1;
@@ -1113,7 +1120,7 @@ static av_cold int twin_decode_close(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec twinvq_decoder =
+AVCodec ff_twinvq_decoder =
 {
     "twinvq",
     AVMEDIA_TYPE_AUDIO,
diff --git a/libavcodec/twinvq_data.h b/libavcodec/twinvq_data.h
index 3042cd1..1f1f334 100644
--- a/libavcodec/twinvq_data.h
+++ b/libavcodec/twinvq_data.h
@@ -2,20 +2,20 @@
  * TwinVQ decoder
  * Copyright (c) 2009 Vitor Sessak
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/txd.c b/libavcodec/txd.c
index ac8229f..98719fa 100644
--- a/libavcodec/txd.c
+++ b/libavcodec/txd.c
@@ -4,24 +4,25 @@
  *
  * See also: http://wiki.multimedia.cx/index.php?title=TXD
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "libavutil/intreadwrite.h"
+#include "libavutil/imgutils.h"
 #include "avcodec.h"
 #include "s3tc.h"
 
@@ -79,7 +80,7 @@ static int txd_decode_frame(AVCodecContext *avctx, void *data, int *data_size,
     if (p->data[0])
         avctx->release_buffer(avctx, p);
 
-    if (avcodec_check_dimensions(avctx, w, h))
+    if (av_image_check_size(w, h, 0, avctx))
         return -1;
     if (w != avctx->width || h != avctx->height)
         avcodec_set_dimensions(avctx, w, h);
@@ -154,7 +155,7 @@ static av_cold int txd_end(AVCodecContext *avctx) {
     return 0;
 }
 
-AVCodec txd_decoder = {
+AVCodec ff_txd_decoder = {
     "txd",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_TXD,
diff --git a/libavcodec/ulti.c b/libavcodec/ulti.c
index 1d04c80..31b1c4a 100644
--- a/libavcodec/ulti.c
+++ b/libavcodec/ulti.c
@@ -2,20 +2,20 @@
  * IBM Ultimotion Video Decoder
  * Copyright (C) 2004 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -404,7 +404,7 @@ static int ulti_decode_frame(AVCodecContext *avctx,
     return buf_size;
 }
 
-AVCodec ulti_decoder = {
+AVCodec ff_ulti_decoder = {
     "ultimotion",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_ULTI,
diff --git a/libavcodec/ulti_cb.h b/libavcodec/ulti_cb.h
index 7061d83..0bd83ff 100644
--- a/libavcodec/ulti_cb.h
+++ b/libavcodec/ulti_cb.h
@@ -2,20 +2,20 @@
  * IBM Ultimotion Video Decoder
  * copyright (C) 2004 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/unary.h b/libavcodec/unary.h
index 908dc93..d14929f 100644
--- a/libavcodec/unary.h
+++ b/libavcodec/unary.h
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2004 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/utils.c b/libavcodec/utils.c
index 014427d..6d31254 100644
--- a/libavcodec/utils.c
+++ b/libavcodec/utils.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2001 Fabrice Bellard
  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,55 +25,55 @@
  * utils.
  */
 
-/* needed for mkstemp() */
-#define _XOPEN_SOURCE 600
-
 #include "libavutil/avstring.h"
 #include "libavutil/integer.h"
 #include "libavutil/crc.h"
 #include "libavutil/pixdesc.h"
+#include "libavutil/audioconvert.h"
+#include "libavutil/imgutils.h"
+#include "libavutil/samplefmt.h"
 #include "avcodec.h"
 #include "dsputil.h"
-#include "opt.h"
+#include "libavutil/opt.h"
 #include "imgconvert.h"
+#include "thread.h"
 #include "audioconvert.h"
-#include "libxvid_internal.h"
 #include "internal.h"
 #include <stdlib.h>
 #include <stdarg.h>
 #include <limits.h>
 #include <float.h>
-#if !HAVE_MKSTEMP
-#include <fcntl.h>
-#endif
 
 static int volatile entangled_thread_counter=0;
-int (*ff_lockmgr_cb)(void **mutex, enum AVLockOp op);
+static int (*ff_lockmgr_cb)(void **mutex, enum AVLockOp op);
 static void *codec_mutex;
 
-void *av_fast_realloc(void *ptr, unsigned int *size, unsigned int min_size)
+void *av_fast_realloc(void *ptr, unsigned int *size, FF_INTERNALC_MEM_TYPE min_size)
 {
     if(min_size < *size)
         return ptr;
 
-    *size= FFMAX(17*min_size/16 + 32, min_size);
+    min_size= FFMAX(17*min_size/16 + 32, min_size);
 
-    ptr= av_realloc(ptr, *size);
+    ptr= av_realloc(ptr, min_size);
     if(!ptr) //we could set this to the unmodified min_size but this is safer if the user lost the ptr and uses NULL now
-        *size= 0;
+        min_size= 0;
+
+    *size= min_size;
 
     return ptr;
 }
 
-void av_fast_malloc(void *ptr, unsigned int *size, unsigned int min_size)
+void av_fast_malloc(void *ptr, unsigned int *size, FF_INTERNALC_MEM_TYPE min_size)
 {
     void **p = ptr;
     if (min_size < *size)
         return;
-    *size= FFMAX(17*min_size/16 + 32, min_size);
+    min_size= FFMAX(17*min_size/16 + 32, min_size);
     av_free(*p);
-    *p = av_malloc(*size);
-    if (!*p) *size = 0;
+    *p = av_malloc(min_size);
+    if (!*p) min_size = 0;
+    *size= min_size;
 }
 
 /* encoder management */
@@ -145,7 +145,7 @@ void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height, int l
     case PIX_FMT_YUVA420P:
         w_align= 16; //FIXME check for non mpeg style codecs and use less alignment
         h_align= 16;
-        if(s->codec_id == CODEC_ID_MPEG2VIDEO || s->codec_id == CODEC_ID_MJPEG || s->codec_id == CODEC_ID_AMV || s->codec_id == CODEC_ID_THP)
+        if(s->codec_id == CODEC_ID_MPEG2VIDEO || s->codec_id == CODEC_ID_MJPEG || s->codec_id == CODEC_ID_AMV || s->codec_id == CODEC_ID_THP || s->codec_id == CODEC_ID_H264)
             h_align= 32; // interlaced is rounded up to 2 MBs
         break;
     case PIX_FMT_YUV411P:
@@ -185,8 +185,9 @@ void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height, int l
 
     *width = FFALIGN(*width , w_align);
     *height= FFALIGN(*height, h_align);
-    if(s->codec_id == CODEC_ID_H264)
+    if(s->codec_id == CODEC_ID_H264 || s->lowres)
         *height+=2; // some of the optimized chroma MC reads one line too much
+                    // which is also done in mpeg decoders with lowres > 0
 
     linesize_align[0] =
     linesize_align[1] =
@@ -219,13 +220,11 @@ void avcodec_align_dimensions(AVCodecContext *s, int *width, int *height){
     *width=FFALIGN(*width, align);
 }
 
+#if LIBAVCODEC_VERSION_MAJOR < 53
 int avcodec_check_dimensions(void *av_log_ctx, unsigned int w, unsigned int h){
-    if((int)w>0 && (int)h>0 && (w+128)*(uint64_t)(h+128) < INT_MAX/8)
-        return 0;
-
-    av_log(av_log_ctx, AV_LOG_ERROR, "picture size invalid (%ux%u)\n", w, h);
-    return AVERROR(EINVAL);
+    return av_image_check_size(w, h, 0, av_log_ctx);
 }
+#endif
 
 int avcodec_default_get_buffer(AVCodecContext *s, AVFrame *pic){
     int i;
@@ -243,7 +242,7 @@ int avcodec_default_get_buffer(AVCodecContext *s, AVFrame *pic){
         return -1;
     }
 
-    if(avcodec_check_dimensions(s,w,h))
+    if(av_image_check_size(w, h, 0, s))
         return -1;
 
     if(s->internal_buffer==NULL){
@@ -262,6 +261,11 @@ int avcodec_default_get_buffer(AVCodecContext *s, AVFrame *pic){
     (*picture_number)++;
 
     if(buf->base[0] && (buf->width != w || buf->height != h || buf->pix_fmt != s->pix_fmt)){
+        if(s->active_thread_type&FF_THREAD_FRAME) {
+            av_log_missing_feature(s, "Width/height changing with frame threads is", 0);
+            return -1;
+        }
+
         for(i=0; i<4; i++){
             av_freep(&buf->base[i]);
             buf->data[i]= NULL;
@@ -291,7 +295,7 @@ int avcodec_default_get_buffer(AVCodecContext *s, AVFrame *pic){
         do {
             // NOTE: do not align linesizes individually, this breaks e.g. assumptions
             // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
-            ff_fill_linesize(&picture, s->pix_fmt, w);
+            av_image_fill_linesizes(picture.linesize, s->pix_fmt, w);
             // increase alignment of w for next try (rhs gives the lowest bit set in w)
             w += w & ~(w-1);
 
@@ -301,7 +305,7 @@ int avcodec_default_get_buffer(AVCodecContext *s, AVFrame *pic){
             }
         } while (unaligned);
 
-        tmpsize = ff_fill_pointer(&picture, NULL, s->pix_fmt, h);
+        tmpsize = av_image_fill_pointers(picture.data, s->pix_fmt, h, NULL, picture.linesize);
         if (tmpsize < 0)
             return -1;
 
@@ -323,14 +327,14 @@ int avcodec_default_get_buffer(AVCodecContext *s, AVFrame *pic){
             if(buf->base[i]==NULL) return -1;
             memset(buf->base[i], 128, size[i]);
 
-            // no edge if EDEG EMU or not planar YUV
+            // no edge if EDGE EMU or not planar YUV
             if((s->flags&CODEC_FLAG_EMU_EDGE) || !size[2])
                 buf->data[i] = buf->base[i];
             else
                 buf->data[i] = buf->base[i] + FFALIGN((buf->linesize[i]*EDGE_WIDTH>>v_shift) + (EDGE_WIDTH>>h_shift), stride_align[i]);
         }
         if(size[1] && !size[2])
-            ff_set_systematic_pal((uint32_t*)buf->data[1], s->pix_fmt);
+            ff_set_systematic_pal2((uint32_t*)buf->data[1], s->pix_fmt);
         buf->width  = s->width;
         buf->height = s->height;
         buf->pix_fmt= s->pix_fmt;
@@ -345,6 +349,8 @@ int avcodec_default_get_buffer(AVCodecContext *s, AVFrame *pic){
     }
     s->internal_buffer_count++;
 
+    if(s->pkt) pic->pkt_pts= s->pkt->pts;
+    else       pic->pkt_pts= AV_NOPTS_VALUE;
     pic->reordered_opaque= s->reordered_opaque;
 
     if(s->debug&FF_DEBUG_BUFFERS)
@@ -395,6 +401,8 @@ int avcodec_default_reget_buffer(AVCodecContext *s, AVFrame *pic){
 
     /* If internal buffer type return the same buffer */
     if(pic->type == FF_BUFFER_TYPE_INTERNAL) {
+        if(s->pkt) pic->pkt_pts= s->pkt->pts;
+        else       pic->pkt_pts= AV_NOPTS_VALUE;
         pic->reordered_opaque= s->reordered_opaque;
         return 0;
     }
@@ -479,11 +487,17 @@ int attribute_align_arg avcodec_open(AVCodecContext *avctx, AVCodec *codec)
         goto end;
 
     if (codec->priv_data_size > 0) {
+      if(!avctx->priv_data){
         avctx->priv_data = av_mallocz(codec->priv_data_size);
         if (!avctx->priv_data) {
             ret = AVERROR(ENOMEM);
             goto end;
         }
+        if(codec->priv_class){ //this can be droped once all user apps use   avcodec_get_context_defaults3()
+            *(AVClass**)avctx->priv_data= codec->priv_class;
+            av_opt_set_defaults(avctx->priv_data);
+        }
+      }
     } else {
         avctx->priv_data = NULL;
     }
@@ -493,10 +507,20 @@ int attribute_align_arg avcodec_open(AVCodecContext *avctx, AVCodec *codec)
     else if(avctx->width && avctx->height)
         avcodec_set_dimensions(avctx, avctx->width, avctx->height);
 
+    if ((avctx->coded_width || avctx->coded_height || avctx->width || avctx->height)
+        && (  av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx) < 0
+           || av_image_check_size(avctx->width,       avctx->height,       0, avctx) < 0)) {
+        av_log(avctx, AV_LOG_WARNING, "ignoring invalid width/height values\n");
+        avcodec_set_dimensions(avctx, 0, 0);
+    }
+
+    /* if the decoder init function was already called previously,
+       free the already allocated subtitle_header before overwriting it */
+    if (codec->decode)
+        av_freep(&avctx->subtitle_header);
+
 #define SANE_NB_CHANNELS 128U
-    if (((avctx->coded_width || avctx->coded_height)
-        && avcodec_check_dimensions(avctx, avctx->coded_width, avctx->coded_height))
-        || avctx->channels > SANE_NB_CHANNELS) {
+    if (avctx->channels > SANE_NB_CHANNELS) {
         ret = AVERROR(EINVAL);
         goto free_and_end;
     }
@@ -507,12 +531,37 @@ int attribute_align_arg avcodec_open(AVCodecContext *avctx, AVCodec *codec)
         avctx->codec_type = codec->type;
         avctx->codec_id   = codec->id;
     }
-    if(avctx->codec_id != codec->id || avctx->codec_type != codec->type){
+    if (avctx->codec_id != codec->id || (avctx->codec_type != codec->type
+                           && avctx->codec_type != AVMEDIA_TYPE_ATTACHMENT)) {
         av_log(avctx, AV_LOG_ERROR, "codec type or id mismatches\n");
         goto free_and_end;
     }
     avctx->frame_number = 0;
-    if(avctx->codec->init){
+
+    if (HAVE_THREADS && !avctx->thread_opaque) {
+        ret = ff_thread_init(avctx);
+        if (ret < 0) {
+            goto free_and_end;
+        }
+    }
+
+    if (avctx->codec->max_lowres < avctx->lowres) {
+        av_log(avctx, AV_LOG_ERROR, "The maximum value for lowres supported by the decoder is %d\n",
+               avctx->codec->max_lowres);
+        goto free_and_end;
+    }
+    if (avctx->codec->sample_fmts && avctx->codec->encode) {
+        int i;
+        for (i = 0; avctx->codec->sample_fmts[i] != AV_SAMPLE_FMT_NONE; i++)
+            if (avctx->sample_fmt == avctx->codec->sample_fmts[i])
+                break;
+        if (avctx->codec->sample_fmts[i] == AV_SAMPLE_FMT_NONE) {
+            av_log(avctx, AV_LOG_ERROR, "Specified sample_fmt is not supported.\n");
+            goto free_and_end;
+        }
+    }
+
+    if(avctx->codec->init && !(avctx->active_thread_type&FF_THREAD_FRAME)){
         ret = avctx->codec->init(avctx);
         if (ret < 0) {
             goto free_and_end;
@@ -555,7 +604,7 @@ int attribute_align_arg avcodec_encode_video(AVCodecContext *avctx, uint8_t *buf
         av_log(avctx, AV_LOG_ERROR, "buffer smaller than minimum size\n");
         return -1;
     }
-    if(avcodec_check_dimensions(avctx,avctx->width,avctx->height))
+    if(av_image_check_size(avctx->width, avctx->height, 0, avctx))
         return -1;
     if((avctx->codec->capabilities & CODEC_CAP_DELAY) || pict){
         int ret = avctx->codec->encode(avctx, buf, buf_size, pict);
@@ -582,7 +631,7 @@ int avcodec_encode_subtitle(AVCodecContext *avctx, uint8_t *buf, int buf_size,
     return ret;
 }
 
-#if LIBAVCODEC_VERSION_MAJOR < 53
+#if FF_API_VIDEO_OLD
 int attribute_align_arg avcodec_decode_video(AVCodecContext *avctx, AVFrame *picture,
                          int *got_picture_ptr,
                          const uint8_t *buf, int buf_size)
@@ -605,11 +654,20 @@ int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *pi
     int ret;
 
     *got_picture_ptr= 0;
-    if((avctx->coded_width||avctx->coded_height) && avcodec_check_dimensions(avctx,avctx->coded_width,avctx->coded_height))
+    if((avctx->coded_width||avctx->coded_height) && av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx))
         return -1;
-    if((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size){
-        ret = avctx->codec->decode(avctx, picture, got_picture_ptr,
-                                avpkt);
+
+    avctx->pkt = avpkt;
+
+    if((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type&FF_THREAD_FRAME)){
+        if (HAVE_PTHREADS && avctx->active_thread_type&FF_THREAD_FRAME)
+             ret = ff_thread_decode_frame(avctx, picture, got_picture_ptr,
+                                          avpkt);
+        else {
+            ret = avctx->codec->decode(avctx, picture, got_picture_ptr,
+                              avpkt);
+            picture->pkt_dts= avpkt->dts;
+        }
 
         emms_c(); //needed to avoid an emms_c() call before every return;
 
@@ -621,7 +679,7 @@ int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *pi
     return ret;
 }
 
-#if LIBAVCODEC_VERSION_MAJOR < 53
+#if FF_API_AUDIO_OLD
 int attribute_align_arg avcodec_decode_audio2(AVCodecContext *avctx, int16_t *samples,
                          int *frame_size_ptr,
                          const uint8_t *buf, int buf_size)
@@ -641,6 +699,8 @@ int attribute_align_arg avcodec_decode_audio3(AVCodecContext *avctx, int16_t *sa
 {
     int ret;
 
+    avctx->pkt = avpkt;
+
     if((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size){
         //FIXME remove the check below _after_ ensuring that all audio check that the available space is enough
         if(*frame_size_ptr < AVCODEC_MAX_AUDIO_FRAME_SIZE){
@@ -662,7 +722,7 @@ int attribute_align_arg avcodec_decode_audio3(AVCodecContext *avctx, int16_t *sa
     return ret;
 }
 
-#if LIBAVCODEC_VERSION_MAJOR < 53
+#if FF_API_SUBTITLE_OLD
 int avcodec_decode_subtitle(AVCodecContext *avctx, AVSubtitle *sub,
                             int *got_sub_ptr,
                             const uint8_t *buf, int buf_size)
@@ -682,6 +742,7 @@ int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
 {
     int ret;
 
+    avctx->pkt = avpkt;
     *got_sub_ptr = 0;
     ret = avctx->codec->decode(avctx, sub, got_sub_ptr, avpkt);
     if (*got_sub_ptr)
@@ -689,6 +750,26 @@ int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
     return ret;
 }
 
+void avsubtitle_free(AVSubtitle *sub)
+{
+    int i;
+
+    for (i = 0; i < sub->num_rects; i++)
+    {
+        av_freep(&sub->rects[i]->pict.data[0]);
+        av_freep(&sub->rects[i]->pict.data[1]);
+        av_freep(&sub->rects[i]->pict.data[2]);
+        av_freep(&sub->rects[i]->pict.data[3]);
+        av_freep(&sub->rects[i]->text);
+        av_freep(&sub->rects[i]->ass);
+        av_freep(&sub->rects[i]);
+    }
+
+    av_freep(&sub->rects);
+
+    memset(sub, 0, sizeof(AVSubtitle));
+}
+
 av_cold int avcodec_close(AVCodecContext *avctx)
 {
     /* If there is a user-supplied mutex locking routine, call it. */
@@ -705,14 +786,16 @@ av_cold int avcodec_close(AVCodecContext *avctx)
     }
 
     if (HAVE_THREADS && avctx->thread_opaque)
-        avcodec_thread_free(avctx);
+        ff_thread_free(avctx);
     if (avctx->codec && avctx->codec->close)
         avctx->codec->close(avctx);
     avcodec_default_free_buffers(avctx);
+    avctx->coded_frame = NULL;
     av_freep(&avctx->priv_data);
     if(avctx->codec && avctx->codec->encode)
         av_freep(&avctx->extradata);
     avctx->codec = NULL;
+    avctx->active_thread_type = 0;
     entangled_thread_counter--;
 
     /* Release any user-supplied mutex. */
@@ -801,9 +884,25 @@ static int get_bit_rate(AVCodecContext *ctx)
     return bit_rate;
 }
 
+size_t av_get_codec_tag_string(char *buf, size_t buf_size, unsigned int codec_tag)
+{
+    int i, len, ret = 0;
+
+    for (i = 0; i < 4; i++) {
+        len = snprintf(buf, buf_size,
+                       isprint(codec_tag&0xFF) ? "%c" : "[%d]", codec_tag&0xFF);
+        buf      += len;
+        buf_size  = buf_size > len ? buf_size - len : 0;
+        ret      += len;
+        codec_tag>>=8;
+    }
+    return ret;
+}
+
 void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode)
 {
     const char *codec_name;
+    const char *profile = NULL;
     AVCodec *p;
     char buf1[32];
     int bitrate;
@@ -816,6 +915,7 @@ void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode)
 
     if (p) {
         codec_name = p->name;
+        profile = av_get_profile_name(p, enc->profile);
     } else if (enc->codec_id == CODEC_ID_MPEG2TS) {
         /* fake mpeg2 transport stream codec (currently not
            registered) */
@@ -824,17 +924,9 @@ void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode)
         codec_name = enc->codec_name;
     } else {
         /* output avi tags */
-        if(   isprint(enc->codec_tag&0xFF) && isprint((enc->codec_tag>>8)&0xFF)
-           && isprint((enc->codec_tag>>16)&0xFF) && isprint((enc->codec_tag>>24)&0xFF)){
-            snprintf(buf1, sizeof(buf1), "%c%c%c%c / 0x%04X",
-                     enc->codec_tag & 0xff,
-                     (enc->codec_tag >> 8) & 0xff,
-                     (enc->codec_tag >> 16) & 0xff,
-                     (enc->codec_tag >> 24) & 0xff,
-                      enc->codec_tag);
-        } else {
-            snprintf(buf1, sizeof(buf1), "0x%04x", enc->codec_tag);
-        }
+        char tag_buf[32];
+        av_get_codec_tag_string(tag_buf, sizeof(tag_buf), enc->codec_tag);
+        snprintf(buf1, sizeof(buf1), "%s / 0x%04X", tag_buf, enc->codec_tag);
         codec_name = buf1;
     }
 
@@ -843,6 +935,9 @@ void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode)
         snprintf(buf, buf_size,
                  "Video: %s%s",
                  codec_name, enc->mb_decision ? " (hq)" : "");
+        if (profile)
+            snprintf(buf + strlen(buf), buf_size - strlen(buf),
+                     " (%s)", profile);
         if (enc->pix_fmt != PIX_FMT_NONE) {
             snprintf(buf + strlen(buf), buf_size - strlen(buf),
                      ", %s",
@@ -878,15 +973,18 @@ void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode)
         snprintf(buf, buf_size,
                  "Audio: %s",
                  codec_name);
+        if (profile)
+            snprintf(buf + strlen(buf), buf_size - strlen(buf),
+                     " (%s)", profile);
         if (enc->sample_rate) {
             snprintf(buf + strlen(buf), buf_size - strlen(buf),
                      ", %d Hz", enc->sample_rate);
         }
         av_strlcat(buf, ", ", buf_size);
-        avcodec_get_channel_layout_string(buf + strlen(buf), buf_size - strlen(buf), enc->channels, enc->channel_layout);
-        if (enc->sample_fmt != SAMPLE_FMT_NONE) {
+        av_get_channel_layout_string(buf + strlen(buf), buf_size - strlen(buf), enc->channels, enc->channel_layout);
+        if (enc->sample_fmt != AV_SAMPLE_FMT_NONE) {
             snprintf(buf + strlen(buf), buf_size - strlen(buf),
-                     ", %s", avcodec_get_sample_fmt_name(enc->sample_fmt));
+                     ", %s", av_get_sample_fmt_name(enc->sample_fmt));
         }
         break;
     case AVMEDIA_TYPE_DATA:
@@ -917,6 +1015,19 @@ void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode)
     }
 }
 
+const char *av_get_profile_name(const AVCodec *codec, int profile)
+{
+    const AVProfile *p;
+    if (profile == FF_PROFILE_UNKNOWN || !codec->profiles)
+        return NULL;
+
+    for (p = codec->profiles; p->profile != FF_PROFILE_UNKNOWN; p++)
+        if (p->profile == profile)
+            return p->name;
+
+    return NULL;
+}
+
 unsigned avcodec_version( void )
 {
   return LIBAVCODEC_VERSION_INT;
@@ -924,13 +1035,13 @@ unsigned avcodec_version( void )
 
 const char *avcodec_configuration(void)
 {
-    return FFMPEG_CONFIGURATION;
+    return LIBAV_CONFIGURATION;
 }
 
 const char *avcodec_license(void)
 {
 #define LICENSE_PREFIX "libavcodec license: "
-    return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1;
+    return LICENSE_PREFIX LIBAV_LICENSE + sizeof(LICENSE_PREFIX) - 1;
 }
 
 void avcodec_init(void)
@@ -946,6 +1057,8 @@ void avcodec_init(void)
 
 void avcodec_flush_buffers(AVCodecContext *avctx)
 {
+    if(HAVE_PTHREADS && avctx->active_thread_type&FF_THREAD_FRAME)
+        ff_thread_flush(avctx);
     if(avctx->codec->flush)
         avctx->codec->flush(avctx);
 }
@@ -994,6 +1107,7 @@ int av_get_bits_per_sample(enum CodecID codec_id){
     case CODEC_ID_ADPCM_MS:
     case CODEC_ID_ADPCM_YAMAHA:
         return 4;
+    case CODEC_ID_ADPCM_G722:
     case CODEC_ID_PCM_ALAW:
     case CODEC_ID_PCM_MULAW:
     case CODEC_ID_PCM_S8:
@@ -1027,25 +1141,14 @@ int av_get_bits_per_sample(enum CodecID codec_id){
     }
 }
 
-int av_get_bits_per_sample_format(enum SampleFormat sample_fmt) {
-    switch (sample_fmt) {
-    case SAMPLE_FMT_U8:
-        return 8;
-    case SAMPLE_FMT_S16:
-        return 16;
-    case SAMPLE_FMT_S32:
-    case SAMPLE_FMT_FLT:
-        return 32;
-    case SAMPLE_FMT_DBL:
-        return 64;
-    default:
-        return 0;
-    }
+#if FF_API_OLD_SAMPLE_FMT
+int av_get_bits_per_sample_format(enum AVSampleFormat sample_fmt) {
+    return av_get_bits_per_sample_fmt(sample_fmt);
 }
+#endif
 
 #if !HAVE_THREADS
-int avcodec_thread_init(AVCodecContext *s, int thread_count){
-    s->thread_count = thread_count;
+int ff_thread_init(AVCodecContext *s){
     return -1;
 }
 #endif
@@ -1064,168 +1167,19 @@ unsigned int av_xiphlacing(unsigned char *s, unsigned int v)
     return n;
 }
 
-/* Wrapper to work around the lack of mkstemp() on mingw/cygin.
- * Also, tries to create file in /tmp first, if possible.
- * *prefix can be a character constant; *filename will be allocated internally.
- * Returns file descriptor of opened file (or -1 on error)
- * and opened file name in **filename. */
-int av_tempfile(char *prefix, char **filename) {
-    int fd=-1;
-#if !HAVE_MKSTEMP
-    *filename = tempnam(".", prefix);
-#else
-    size_t len = strlen(prefix) + 12; /* room for "/tmp/" and "XXXXXX\0" */
-    *filename = av_malloc(len);
-#endif
-    /* -----common section-----*/
-    if (*filename == NULL) {
-        av_log(NULL, AV_LOG_ERROR, "ff_tempfile: Cannot allocate file name\n");
-        return -1;
-    }
-#if !HAVE_MKSTEMP
-    fd = open(*filename, O_RDWR | O_BINARY | O_CREAT, 0444);
-#else
-    snprintf(*filename, len, "/tmp/%sXXXXXX", prefix);
-    fd = mkstemp(*filename);
-    if (fd < 0) {
-        snprintf(*filename, len, "./%sXXXXXX", prefix);
-        fd = mkstemp(*filename);
-    }
-#endif
-    /* -----common section-----*/
-    if (fd < 0) {
-        av_log(NULL, AV_LOG_ERROR, "ff_tempfile: Cannot open temporary file %s\n", *filename);
-        return -1;
-    }
-    return fd; /* success */
-}
-
-typedef struct {
-    const char *abbr;
-    int width, height;
-} VideoFrameSizeAbbr;
-
-typedef struct {
-    const char *abbr;
-    int rate_num, rate_den;
-} VideoFrameRateAbbr;
-
-static const VideoFrameSizeAbbr video_frame_size_abbrs[] = {
-    { "ntsc",      720, 480 },
-    { "pal",       720, 576 },
-    { "qntsc",     352, 240 }, /* VCD compliant NTSC */
-    { "qpal",      352, 288 }, /* VCD compliant PAL */
-    { "sntsc",     640, 480 }, /* square pixel NTSC */
-    { "spal",      768, 576 }, /* square pixel PAL */
-    { "film",      352, 240 },
-    { "ntsc-film", 352, 240 },
-    { "sqcif",     128,  96 },
-    { "qcif",      176, 144 },
-    { "cif",       352, 288 },
-    { "4cif",      704, 576 },
-    { "16cif",    1408,1152 },
-    { "qqvga",     160, 120 },
-    { "qvga",      320, 240 },
-    { "vga",       640, 480 },
-    { "svga",      800, 600 },
-    { "xga",      1024, 768 },
-    { "uxga",     1600,1200 },
-    { "qxga",     2048,1536 },
-    { "sxga",     1280,1024 },
-    { "qsxga",    2560,2048 },
-    { "hsxga",    5120,4096 },
-    { "wvga",      852, 480 },
-    { "wxga",     1366, 768 },
-    { "wsxga",    1600,1024 },
-    { "wuxga",    1920,1200 },
-    { "woxga",    2560,1600 },
-    { "wqsxga",   3200,2048 },
-    { "wquxga",   3840,2400 },
-    { "whsxga",   6400,4096 },
-    { "whuxga",   7680,4800 },
-    { "cga",       320, 200 },
-    { "ega",       640, 350 },
-    { "hd480",     852, 480 },
-    { "hd720",    1280, 720 },
-    { "hd1080",   1920,1080 },
-};
-
-static const VideoFrameRateAbbr video_frame_rate_abbrs[]= {
-    { "ntsc",      30000, 1001 },
-    { "pal",          25,    1 },
-    { "qntsc",     30000, 1001 }, /* VCD compliant NTSC */
-    { "qpal",         25,    1 }, /* VCD compliant PAL */
-    { "sntsc",     30000, 1001 }, /* square pixel NTSC */
-    { "spal",         25,    1 }, /* square pixel PAL */
-    { "film",         24,    1 },
-    { "ntsc-film", 24000, 1001 },
-};
+#if LIBAVCODEC_VERSION_MAJOR < 53
+#include "libavutil/parseutils.h"
 
 int av_parse_video_frame_size(int *width_ptr, int *height_ptr, const char *str)
 {
-    int i;
-    int n = FF_ARRAY_ELEMS(video_frame_size_abbrs);
-    char *p;
-    int frame_width = 0, frame_height = 0;
-
-    for(i=0;i<n;i++) {
-        if (!strcmp(video_frame_size_abbrs[i].abbr, str)) {
-            frame_width = video_frame_size_abbrs[i].width;
-            frame_height = video_frame_size_abbrs[i].height;
-            break;
-        }
-    }
-    if (i == n) {
-        p = str;
-        frame_width = strtol(p, &p, 10);
-        if (*p)
-            p++;
-        frame_height = strtol(p, &p, 10);
-    }
-    if (frame_width <= 0 || frame_height <= 0)
-        return -1;
-    *width_ptr = frame_width;
-    *height_ptr = frame_height;
-    return 0;
+    return av_parse_video_size(width_ptr, height_ptr, str);
 }
 
 int av_parse_video_frame_rate(AVRational *frame_rate, const char *arg)
 {
-    int i;
-    int n = FF_ARRAY_ELEMS(video_frame_rate_abbrs);
-    char* cp;
-
-    /* First, we check our abbreviation table */
-    for (i = 0; i < n; ++i)
-         if (!strcmp(video_frame_rate_abbrs[i].abbr, arg)) {
-             frame_rate->num = video_frame_rate_abbrs[i].rate_num;
-             frame_rate->den = video_frame_rate_abbrs[i].rate_den;
-             return 0;
-         }
-
-    /* Then, we try to parse it as fraction */
-    cp = strchr(arg, '/');
-    if (!cp)
-        cp = strchr(arg, ':');
-    if (cp) {
-        char* cpp;
-        frame_rate->num = strtol(arg, &cpp, 10);
-        if (cpp != arg || cpp == cp)
-            frame_rate->den = strtol(cp+1, &cpp, 10);
-        else
-           frame_rate->num = 0;
-    }
-    else {
-        /* Finally we give up and parse it as double */
-        AVRational time_base = av_d2q(strtod(arg, 0), 1001000);
-        frame_rate->den = time_base.den;
-        frame_rate->num = time_base.num;
-    }
-    if (!frame_rate->num || !frame_rate->den)
-        return -1;
-    else
-        return 0;
+    return av_parse_video_rate(frame_rate, arg);
 }
+#endif
 
 int ff_match_2uint16(const uint16_t (*tab)[2], int size, int a, int b){
     int i;
@@ -1235,8 +1189,8 @@ int ff_match_2uint16(const uint16_t (*tab)[2], int size, int a, int b){
 
 void av_log_missing_feature(void *avc, const char *feature, int want_sample)
 {
-    av_log(avc, AV_LOG_WARNING, "%s not implemented. Update your FFmpeg "
-            "version to the newest one from SVN. If the problem still "
+    av_log(avc, AV_LOG_WARNING, "%s not implemented. Update your Libav "
+            "version to the newest one from Git. If the problem still "
             "occurs, it means that your file has a feature which has not "
             "been implemented.", feature);
     if(want_sample)
@@ -1250,8 +1204,8 @@ void av_log_ask_for_sample(void *avc, const char *msg)
     if (msg)
         av_log(avc, AV_LOG_WARNING, "%s ", msg);
     av_log(avc, AV_LOG_WARNING, "If you want to help, upload a sample "
-            "of this file to ftp://upload.ffmpeg.org/MPlayer/incoming/ "
-            "and contact the ffmpeg-devel mailing list.\n");
+            "of this file to ftp://upload.libav.org/incoming/ "
+            "and contact the libav-devel mailing list.\n");
 }
 
 static AVHWAccel *first_hwaccel = NULL;
@@ -1297,3 +1251,55 @@ int av_lockmgr_register(int (*cb)(void **mutex, enum AVLockOp op))
     }
     return 0;
 }
+
+unsigned int ff_toupper4(unsigned int x)
+{
+    return     toupper( x     &0xFF)
+            + (toupper((x>>8 )&0xFF)<<8 )
+            + (toupper((x>>16)&0xFF)<<16)
+            + (toupper((x>>24)&0xFF)<<24);
+}
+
+#if !HAVE_PTHREADS
+
+int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f)
+{
+    f->owner = avctx;
+    return avctx->get_buffer(avctx, f);
+}
+
+void ff_thread_release_buffer(AVCodecContext *avctx, AVFrame *f)
+{
+    f->owner->release_buffer(f->owner, f);
+}
+
+void ff_thread_finish_setup(AVCodecContext *avctx)
+{
+}
+
+void ff_thread_report_progress(AVFrame *f, int progress, int field)
+{
+}
+
+void ff_thread_await_progress(AVFrame *f, int progress, int field)
+{
+}
+
+#endif
+
+#if LIBAVCODEC_VERSION_MAJOR < 53
+
+int avcodec_thread_init(AVCodecContext *s, int thread_count)
+{
+    s->thread_count = thread_count;
+    return ff_thread_init(s);
+}
+
+void avcodec_thread_free(AVCodecContext *s)
+{
+#if HAVE_THREADS
+    ff_thread_free(s);
+#endif
+}
+
+#endif
diff --git a/libavcodec/v210dec.c b/libavcodec/v210dec.c
index a1a0827..420bc47 100644
--- a/libavcodec/v210dec.c
+++ b/libavcodec/v210dec.c
@@ -4,20 +4,20 @@
  * Copyright (C) 2009 Michael Niedermayer <michaelni at gmx.at>
  * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -68,7 +68,7 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *data_size,
 
 #define READ_PIXELS(a, b, c)         \
     do {                             \
-        val  = le2me_32(*src++);     \
+        val  = av_le2ne32(*src++);     \
         *a++ =  val <<  6;           \
         *b++ = (val >>  4) & 0xFFC0; \
         *c++ = (val >> 14) & 0xFFC0; \
@@ -86,14 +86,14 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *data_size,
         if (w < avctx->width - 1) {
             READ_PIXELS(u, y, v);
 
-            val  = le2me_32(*src++);
+            val  = av_le2ne32(*src++);
             *y++ =  val <<  6;
         }
         if (w < avctx->width - 3) {
             *u++ = (val >>  4) & 0xFFC0;
             *y++ = (val >> 14) & 0xFFC0;
 
-            val  = le2me_32(*src++);
+            val  = av_le2ne32(*src++);
             *v++ =  val <<  6;
             *y++ = (val >>  4) & 0xFFC0;
         }
@@ -120,7 +120,7 @@ static av_cold int decode_close(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec v210_decoder = {
+AVCodec ff_v210_decoder = {
     "v210",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_V210,
diff --git a/libavcodec/v210enc.c b/libavcodec/v210enc.c
index 11e0e0e..ad03703 100644
--- a/libavcodec/v210enc.c
+++ b/libavcodec/v210enc.c
@@ -4,20 +4,20 @@
  * Copyright (C) 2009 Michael Niedermayer <michaelni at gmx.at>
  * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -117,7 +117,7 @@ static av_cold int encode_close(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec v210_encoder = {
+AVCodec ff_v210_encoder = {
     "v210",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_V210,
diff --git a/libavcodec/v210x.c b/libavcodec/v210x.c
index d869d64..3d8bdcf 100644
--- a/libavcodec/v210x.c
+++ b/libavcodec/v210x.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (C) 2009 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -67,12 +67,12 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPac
     pic->key_frame= 1;
 
     for(;;){
-        uint32_t v= be2me_32(*src++);
+        uint32_t v= av_be2ne32(*src++);
         *udst++= (v>>16) & 0xFFC0;
         *ydst++= (v>>6 ) & 0xFFC0;
         *vdst++= (v<<4 ) & 0xFFC0;
 
-        v= be2me_32(*src++);
+        v= av_be2ne32(*src++);
         *ydst++= (v>>16) & 0xFFC0;
 
         if(ydst >= yend){
@@ -87,7 +87,7 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPac
         *udst++= (v>>6 ) & 0xFFC0;
         *ydst++= (v<<4 ) & 0xFFC0;
 
-        v= be2me_32(*src++);
+        v= av_be2ne32(*src++);
         *vdst++= (v>>16) & 0xFFC0;
         *ydst++= (v>>6 ) & 0xFFC0;
 
@@ -102,7 +102,7 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPac
 
         *udst++= (v<<4 ) & 0xFFC0;
 
-        v= be2me_32(*src++);
+        v= av_be2ne32(*src++);
         *ydst++= (v>>16) & 0xFFC0;
         *vdst++= (v>>6 ) & 0xFFC0;
         *ydst++= (v<<4 ) & 0xFFC0;
@@ -132,7 +132,7 @@ static av_cold int decode_close(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec v210x_decoder = {
+AVCodec ff_v210x_decoder = {
     "v210x",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_V210X,
diff --git a/libavcodec/vaapi.c b/libavcodec/vaapi.c
index 10f9054..cc2fec3 100644
--- a/libavcodec/vaapi.c
+++ b/libavcodec/vaapi.c
@@ -4,20 +4,20 @@
  *
  * Copyright (C) 2008-2009 Splitted-Desktop Systems
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -180,7 +180,7 @@ int ff_vaapi_common_end_frame(MpegEncContext *s)
     struct vaapi_context * const vactx = s->avctx->hwaccel_context;
     int ret = -1;
 
-    dprintf(s->avctx, "ff_vaapi_common_end_frame()\n");
+    av_dlog(s->avctx, "ff_vaapi_common_end_frame()\n");
 
     if (commit_slices(vactx) < 0)
         goto done;
diff --git a/libavcodec/vaapi.h b/libavcodec/vaapi.h
index 07568a4..306e164 100644
--- a/libavcodec/vaapi.h
+++ b/libavcodec/vaapi.h
@@ -1,23 +1,23 @@
 /*
- * Video Acceleration API (shared data between FFmpeg and the video player)
+ * Video Acceleration API (shared data between Libav and the video player)
  * HW decode acceleration for MPEG-2, MPEG-4, H.264 and VC-1
  *
  * Copyright (C) 2008-2009 Splitted-Desktop Systems
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -33,7 +33,7 @@
  */
 
 /**
- * This structure is used to share data between the FFmpeg library and
+ * This structure is used to share data between the Libav library and
  * the client video application.
  * This shall be zero-allocated and available as
  * AVCodecContext.hwaccel_context. All user members can be set once
diff --git a/libavcodec/vaapi_h264.c b/libavcodec/vaapi_h264.c
index 6d4251a..3d57a21 100644
--- a/libavcodec/vaapi_h264.c
+++ b/libavcodec/vaapi_h264.c
@@ -3,20 +3,20 @@
  *
  * Copyright (C) 2008-2009 Splitted-Desktop Systems
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -24,12 +24,12 @@
 #include "h264.h"
 
 /** @file
- *  This file implements the glue code between FFmpeg's and VA API's
+ *  This file implements the glue code between Libav's and VA API's
  *  structures for H.264 decoding.
  */
 
 /**
- * Initializes an empty VA API picture.
+ * Initialize an empty VA API picture.
  *
  * VA API requires a fixed-size reference picture array.
  */
@@ -42,10 +42,10 @@ static void init_vaapi_pic(VAPictureH264 *va_pic)
 }
 
 /**
- * Translates an FFmpeg Picture into its VA API form.
+ * Translate an Libav Picture into its VA API form.
  *
  * @param[out] va_pic          A pointer to VA API's own picture struct
- * @param[in]  pic             A pointer to the FFmpeg picture struct to convert
+ * @param[in]  pic             A pointer to the Libav picture struct to convert
  * @param[in]  pic_structure   The picture field type (as defined in mpegvideo.h),
  *                             supersedes pic's field type if nonzero.
  */
@@ -55,6 +55,7 @@ static void fill_vaapi_pic(VAPictureH264 *va_pic,
 {
     if (pic_structure == 0)
         pic_structure = pic->reference;
+    pic_structure &= PICT_FRAME; /* PICT_TOP_FIELD|PICT_BOTTOM_FIELD */
 
     va_pic->picture_id = ff_vaapi_get_surface_id(pic);
     va_pic->frame_idx  = pic->long_ref ? pic->pic_id : pic->frame_num;
@@ -82,7 +83,7 @@ typedef struct DPB {
 } DPB;
 
 /**
- * Appends picture to the decoded picture buffer, in a VA API form that
+ * Append picture to the decoded picture buffer, in a VA API form that
  * merges the second field picture attributes with the first, if
  * available.  The decoded picture buffer's size must be large enough
  * to receive the new VA API picture object.
@@ -117,7 +118,7 @@ static int dpb_add(DPB *dpb, Picture *pic)
     return 0;
 }
 
-/** Fills in VA API reference frames array. */
+/** Fill in VA API reference frames array. */
 static int fill_vaapi_ReferenceFrames(VAPictureParameterBufferH264 *pic_param,
                                       H264Context                  *h)
 {
@@ -145,11 +146,11 @@ static int fill_vaapi_ReferenceFrames(VAPictureParameterBufferH264 *pic_param,
 }
 
 /**
- * Fills in VA API reference picture lists from the FFmpeg reference
+ * Fill in VA API reference picture lists from the Libav reference
  * picture list.
  *
  * @param[out] RefPicList  VA API internal reference picture list
- * @param[in]  ref_list    A pointer to the FFmpeg reference list
+ * @param[in]  ref_list    A pointer to the Libav reference list
  * @param[in]  ref_count   The number of reference pictures in ref_list
  */
 static void fill_vaapi_RefPicList(VAPictureH264 RefPicList[32],
@@ -166,7 +167,7 @@ static void fill_vaapi_RefPicList(VAPictureH264 RefPicList[32],
 }
 
 /**
- * Fills in prediction weight table.
+ * Fill in prediction weight table.
  *
  * VA API requires a plain prediction weight table as it does not infer
  * any value.
@@ -216,7 +217,7 @@ static void fill_vaapi_plain_pred_weight_table(H264Context   *h,
     }
 }
 
-/** Initializes and starts decoding a frame with VA API. */
+/** Initialize and start decoding a frame with VA API. */
 static int start_frame(AVCodecContext          *avctx,
                        av_unused const uint8_t *buffer,
                        av_unused uint32_t       size)
@@ -227,7 +228,7 @@ static int start_frame(AVCodecContext          *avctx,
     VAPictureParameterBufferH264 *pic_param;
     VAIQMatrixBufferH264 *iq_matrix;
 
-    dprintf(avctx, "start_frame()\n");
+    av_dlog(avctx, "start_frame()\n");
 
     vactx->slice_param_size = sizeof(VASliceParameterBufferH264);
 
@@ -257,7 +258,7 @@ static int start_frame(AVCodecContext          *avctx,
     pic_param->seq_fields.bits.delta_pic_order_always_zero_flag = h->sps.delta_pic_order_always_zero_flag;
     pic_param->num_slice_groups_minus1                          = h->pps.slice_group_count - 1;
     pic_param->slice_group_map_type                             = h->pps.mb_slice_group_map_type;
-    pic_param->slice_group_change_rate_minus1                   = 0; /* XXX: unimplemented in FFmpeg */
+    pic_param->slice_group_change_rate_minus1                   = 0; /* XXX: unimplemented in Libav */
     pic_param->pic_init_qp_minus26                              = h->pps.init_qp - 26;
     pic_param->pic_init_qs_minus26                              = h->pps.init_qs - 26;
     pic_param->chroma_qp_index_offset                           = h->pps.chroma_qp_index_offset[0];
@@ -284,16 +285,16 @@ static int start_frame(AVCodecContext          *avctx,
     return 0;
 }
 
-/** Ends a hardware decoding based frame. */
+/** End a hardware decoding based frame. */
 static int end_frame(AVCodecContext *avctx)
 {
     H264Context * const h = avctx->priv_data;
 
-    dprintf(avctx, "end_frame()\n");
+    av_dlog(avctx, "end_frame()\n");
     return ff_vaapi_common_end_frame(&h->s);
 }
 
-/** Decodes the given H.264 slice with VA API. */
+/** Decode the given H.264 slice with VA API. */
 static int decode_slice(AVCodecContext *avctx,
                         const uint8_t  *buffer,
                         uint32_t        size)
@@ -302,7 +303,7 @@ static int decode_slice(AVCodecContext *avctx,
     MpegEncContext * const s = &h->s;
     VASliceParameterBufferH264 *slice_param;
 
-    dprintf(avctx, "decode_slice(): buffer %p, size %d\n", buffer, size);
+    av_dlog(avctx, "decode_slice(): buffer %p, size %d\n", buffer, size);
 
     /* Fill in VASliceParameterBufferH264. */
     slice_param = (VASliceParameterBufferH264 *)ff_vaapi_alloc_slice(avctx->hwaccel_context, buffer, size);
@@ -334,7 +335,7 @@ static int decode_slice(AVCodecContext *avctx,
     return 0;
 }
 
-AVHWAccel h264_vaapi_hwaccel = {
+AVHWAccel ff_h264_vaapi_hwaccel = {
     .name           = "h264_vaapi",
     .type           = AVMEDIA_TYPE_VIDEO,
     .id             = CODEC_ID_H264,
diff --git a/libavcodec/vaapi_internal.h b/libavcodec/vaapi_internal.h
index 2c0fdf9..3a14a2b 100644
--- a/libavcodec/vaapi_internal.h
+++ b/libavcodec/vaapi_internal.h
@@ -4,20 +4,20 @@
  *
  * Copyright (C) 2008-2009 Splitted-Desktop Systems
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/vaapi_mpeg2.c b/libavcodec/vaapi_mpeg2.c
index 2e870dc..fd57363 100644
--- a/libavcodec/vaapi_mpeg2.c
+++ b/libavcodec/vaapi_mpeg2.c
@@ -3,20 +3,20 @@
  *
  * Copyright (C) 2008-2009 Splitted-Desktop Systems
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -44,7 +44,7 @@ static int vaapi_mpeg2_start_frame(AVCodecContext *avctx, av_unused const uint8_
     VAIQMatrixBufferMPEG2 *iq_matrix;
     int i;
 
-    dprintf(avctx, "vaapi_mpeg2_start_frame()\n");
+    av_dlog(avctx, "vaapi_mpeg2_start_frame()\n");
 
     vactx->slice_param_size = sizeof(VASliceParameterBufferMPEG2);
 
@@ -111,7 +111,7 @@ static int vaapi_mpeg2_decode_slice(AVCodecContext *avctx, const uint8_t *buffer
     GetBitContext gb;
     uint32_t start_code, quantiser_scale_code, intra_slice_flag, macroblock_offset;
 
-    dprintf(avctx, "vaapi_mpeg2_decode_slice(): buffer %p, size %d\n", buffer, size);
+    av_dlog(avctx, "vaapi_mpeg2_decode_slice(): buffer %p, size %d\n", buffer, size);
 
     /* Determine macroblock_offset */
     init_get_bits(&gb, buffer, 8 * size);
@@ -138,7 +138,7 @@ static int vaapi_mpeg2_decode_slice(AVCodecContext *avctx, const uint8_t *buffer
     return 0;
 }
 
-AVHWAccel mpeg2_vaapi_hwaccel = {
+AVHWAccel ff_mpeg2_vaapi_hwaccel = {
     .name           = "mpeg2_vaapi",
     .type           = AVMEDIA_TYPE_VIDEO,
     .id             = CODEC_ID_MPEG2VIDEO,
diff --git a/libavcodec/vaapi_mpeg4.c b/libavcodec/vaapi_mpeg4.c
index 466ce2f..1b3817a 100644
--- a/libavcodec/vaapi_mpeg4.c
+++ b/libavcodec/vaapi_mpeg4.c
@@ -3,24 +3,25 @@
  *
  * Copyright (C) 2008-2009 Splitted-Desktop Systems
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "vaapi_internal.h"
+#include "h263.h"
 
 /** Reconstruct bitstream intra_dc_vlc_thr */
 static int mpeg4_get_intra_dc_vlc_thr(MpegEncContext *s)
@@ -46,7 +47,7 @@ static int vaapi_mpeg4_start_frame(AVCodecContext *avctx, av_unused const uint8_
     VAIQMatrixBufferMPEG4 *iq_matrix;
     int i;
 
-    dprintf(avctx, "vaapi_mpeg4_start_frame()\n");
+    av_dlog(avctx, "vaapi_mpeg4_start_frame()\n");
 
     vactx->slice_param_size = sizeof(VASliceParameterBufferMPEG4);
 
@@ -124,11 +125,11 @@ static int vaapi_mpeg4_decode_slice(AVCodecContext *avctx, const uint8_t *buffer
     MpegEncContext * const s = avctx->priv_data;
     VASliceParameterBufferMPEG4 *slice_param;
 
-    dprintf(avctx, "vaapi_mpeg4_decode_slice(): buffer %p, size %d\n", buffer, size);
+    av_dlog(avctx, "vaapi_mpeg4_decode_slice(): buffer %p, size %d\n", buffer, size);
 
     /* video_plane_with_short_video_header() contains all GOBs
      * in-order, and this is what VA API (Intel backend) expects: only
-     * a single slice param. So fake macroblock_number for FFmpeg so
+     * a single slice param. So fake macroblock_number for Libav so
      * that we don't call vaapi_mpeg4_decode_slice() again
      */
     if (avctx->codec->id == CODEC_ID_H263)
@@ -149,7 +150,7 @@ static int vaapi_mpeg4_decode_slice(AVCodecContext *avctx, const uint8_t *buffer
 }
 
 #if CONFIG_MPEG4_VAAPI_HWACCEL
-AVHWAccel mpeg4_vaapi_hwaccel = {
+AVHWAccel ff_mpeg4_vaapi_hwaccel = {
     .name           = "mpeg4_vaapi",
     .type           = AVMEDIA_TYPE_VIDEO,
     .id             = CODEC_ID_MPEG4,
@@ -163,7 +164,7 @@ AVHWAccel mpeg4_vaapi_hwaccel = {
 #endif
 
 #if CONFIG_H263_VAAPI_HWACCEL
-AVHWAccel h263_vaapi_hwaccel = {
+AVHWAccel ff_h263_vaapi_hwaccel = {
     .name           = "h263_vaapi",
     .type           = AVMEDIA_TYPE_VIDEO,
     .id             = CODEC_ID_H263,
diff --git a/libavcodec/vaapi_vc1.c b/libavcodec/vaapi_vc1.c
index 992e1da..8effa7e 100644
--- a/libavcodec/vaapi_vc1.c
+++ b/libavcodec/vaapi_vc1.c
@@ -3,20 +3,20 @@
  *
  * Copyright (C) 2008-2009 Splitted-Desktop Systems
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -24,7 +24,7 @@
 #include "vc1.h"
 #include "vc1data.h"
 
-/** Translates FFmpeg MV modes to VA API */
+/** Translate Libav MV modes to VA API */
 static int get_VAMvModeVC1(enum MVModes mv_mode)
 {
     switch (mv_mode) {
@@ -37,7 +37,7 @@ static int get_VAMvModeVC1(enum MVModes mv_mode)
     return 0;
 }
 
-/** Checks whether the MVTYPEMB bitplane is present */
+/** Check whether the MVTYPEMB bitplane is present */
 static inline int vc1_has_MVTYPEMB_bitplane(VC1Context *v)
 {
     if (v->mv_type_is_raw)
@@ -48,7 +48,7 @@ static inline int vc1_has_MVTYPEMB_bitplane(VC1Context *v)
               v->mv_mode2 == MV_PMODE_MIXED_MV)));
 }
 
-/** Checks whether the SKIPMB bitplane is present */
+/** Check whether the SKIPMB bitplane is present */
 static inline int vc1_has_SKIPMB_bitplane(VC1Context *v)
 {
     if (v->skip_is_raw)
@@ -57,7 +57,7 @@ static inline int vc1_has_SKIPMB_bitplane(VC1Context *v)
             (v->s.pict_type == FF_B_TYPE && !v->bi_type));
 }
 
-/** Checks whether the DIRECTMB bitplane is present */
+/** Check whether the DIRECTMB bitplane is present */
 static inline int vc1_has_DIRECTMB_bitplane(VC1Context *v)
 {
     if (v->dmb_is_raw)
@@ -65,7 +65,7 @@ static inline int vc1_has_DIRECTMB_bitplane(VC1Context *v)
     return v->s.pict_type == FF_B_TYPE && !v->bi_type;
 }
 
-/** Checks whether the ACPRED bitplane is present */
+/** Check whether the ACPRED bitplane is present */
 static inline int vc1_has_ACPRED_bitplane(VC1Context *v)
 {
     if (v->acpred_is_raw)
@@ -116,7 +116,7 @@ static inline VAMvModeVC1 vc1_get_MVMODE2(VC1Context *v)
     return 0;
 }
 
-/** Pack FFmpeg bitplanes into a VABitPlaneBuffer element */
+/** Pack Libav bitplanes into a VABitPlaneBuffer element */
 static inline void vc1_pack_bitplanes(uint8_t *bitplane, int n, const uint8_t *ff_bp[3], int x, int y, int stride)
 {
     const int bitplane_index = n / 2;
@@ -138,7 +138,7 @@ static int vaapi_vc1_start_frame(AVCodecContext *avctx, av_unused const uint8_t
     struct vaapi_context * const vactx = avctx->hwaccel_context;
     VAPictureParameterBufferVC1 *pic_param;
 
-    dprintf(avctx, "vaapi_vc1_start_frame()\n");
+    av_dlog(avctx, "vaapi_vc1_start_frame()\n");
 
     vactx->slice_param_size = sizeof(VASliceParameterBufferVC1);
 
@@ -160,6 +160,9 @@ static int vaapi_vc1_start_frame(AVCodecContext *avctx, av_unused const uint8_t
     pic_param->sequence_fields.bits.syncmarker                      = s->resync_marker;
     pic_param->sequence_fields.bits.rangered                        = v->rangered;
     pic_param->sequence_fields.bits.max_b_frames                    = s->avctx->max_b_frames;
+#if VA_CHECK_VERSION(0,32,0)
+    pic_param->sequence_fields.bits.profile                         = v->profile;
+#endif
     pic_param->coded_width                                          = s->avctx->coded_width;
     pic_param->coded_height                                         = s->avctx->coded_height;
     pic_param->entrypoint_fields.value                              = 0; /* reset all bits */
@@ -308,7 +311,7 @@ static int vaapi_vc1_decode_slice(AVCodecContext *avctx, const uint8_t *buffer,
     MpegEncContext * const s = &v->s;
     VASliceParameterBufferVC1 *slice_param;
 
-    dprintf(avctx, "vaapi_vc1_decode_slice(): buffer %p, size %d\n", buffer, size);
+    av_dlog(avctx, "vaapi_vc1_decode_slice(): buffer %p, size %d\n", buffer, size);
 
     /* Current bit buffer is beyond any marker for VC-1, so skip it */
     if (avctx->codec_id == CODEC_ID_VC1 && IS_MARKER(AV_RB32(buffer))) {
@@ -326,7 +329,7 @@ static int vaapi_vc1_decode_slice(AVCodecContext *avctx, const uint8_t *buffer,
 }
 
 #if CONFIG_WMV3_VAAPI_HWACCEL
-AVHWAccel wmv3_vaapi_hwaccel = {
+AVHWAccel ff_wmv3_vaapi_hwaccel = {
     .name           = "wmv3_vaapi",
     .type           = AVMEDIA_TYPE_VIDEO,
     .id             = CODEC_ID_WMV3,
@@ -339,7 +342,7 @@ AVHWAccel wmv3_vaapi_hwaccel = {
 };
 #endif
 
-AVHWAccel vc1_vaapi_hwaccel = {
+AVHWAccel ff_vc1_vaapi_hwaccel = {
     .name           = "vc1_vaapi",
     .type           = AVMEDIA_TYPE_VIDEO,
     .id             = CODEC_ID_VC1,
diff --git a/libavcodec/vb.c b/libavcodec/vb.c
index 13c4b0a..fb37283 100644
--- a/libavcodec/vb.c
+++ b/libavcodec/vb.c
@@ -2,20 +2,20 @@
  * Beam Software VB decoder
  * Copyright (c) 2007 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -287,7 +287,7 @@ static av_cold int decode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec vb_decoder = {
+AVCodec ff_vb_decoder = {
     "vb",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_VB,
diff --git a/libavcodec/vc1.c b/libavcodec/vc1.c
index 7d00072..b058a38 100644
--- a/libavcodec/vc1.c
+++ b/libavcodec/vc1.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2006-2007 Konstantin Shishkov
  * Partly based on vc9.c (c) 2005 Anonymous, Alex Beregszaszi, Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -280,6 +280,28 @@ static int vop_dquant_decoding(VC1Context *v)
 
 static int decode_sequence_header_adv(VC1Context *v, GetBitContext *gb);
 
+static void simple_idct_put_rangered(uint8_t *dest, int line_size, DCTELEM *block)
+{
+    int i;
+    ff_simple_idct(block);
+    for (i = 0; i < 64; i++) block[i] = (block[i] - 64) << 1;
+    ff_put_pixels_clamped_c(block, dest, line_size);
+}
+
+static void simple_idct_put_signed(uint8_t *dest, int line_size, DCTELEM *block)
+{
+    ff_simple_idct(block);
+    ff_put_signed_pixels_clamped_c(block, dest, line_size);
+}
+
+static void simple_idct_put_signed_rangered(uint8_t *dest, int line_size, DCTELEM *block)
+{
+    int i;
+    ff_simple_idct(block);
+    for (i = 0; i < 64; i++) block[i] <<= 1;
+    ff_put_signed_pixels_clamped_c(block, dest, line_size);
+}
+
 /**
  * Decode Simple/Main Profiles sequence header
  * @see Figure 7-8, p16-17
@@ -293,7 +315,7 @@ int vc1_decode_sequence_header(AVCodecContext *avctx, VC1Context *v, GetBitConte
     v->profile = get_bits(gb, 2);
     if (v->profile == PROFILE_COMPLEX)
     {
-        av_log(avctx, AV_LOG_ERROR, "WMV3 Complex Profile is not fully supported\n");
+        av_log(avctx, AV_LOG_WARNING, "WMV3 Complex Profile is not fully supported\n");
     }
 
     if (v->profile == PROFILE_ADVANCED)
@@ -306,13 +328,17 @@ int vc1_decode_sequence_header(AVCodecContext *avctx, VC1Context *v, GetBitConte
     {
         v->zz_8x4 = wmv2_scantableA;
         v->zz_4x8 = wmv2_scantableB;
-        v->res_sm = get_bits(gb, 2); //reserved
-        if (v->res_sm)
+        v->res_y411   = get_bits1(gb);
+        v->res_sprite = get_bits1(gb);
+        if (v->res_y411)
         {
             av_log(avctx, AV_LOG_ERROR,
-                   "Reserved RES_SM=%i is forbidden\n", v->res_sm);
+                   "Old interlaced mode is not supported\n");
             return -1;
         }
+        if (v->res_sprite) {
+            av_log(avctx, AV_LOG_ERROR, "WMVP is not fully supported\n");
+        }
     }
 
     // (fps-2)/4 (->30)
@@ -333,14 +359,18 @@ int vc1_decode_sequence_header(AVCodecContext *avctx, VC1Context *v, GetBitConte
     v->res_fasttx = get_bits1(gb);
     if (!v->res_fasttx)
     {
-        v->s.dsp.vc1_inv_trans_8x8 = ff_simple_idct;
-        v->s.dsp.vc1_inv_trans_8x4 = ff_simple_idct84_add;
-        v->s.dsp.vc1_inv_trans_4x8 = ff_simple_idct48_add;
-        v->s.dsp.vc1_inv_trans_4x4 = ff_simple_idct44_add;
-        v->s.dsp.vc1_inv_trans_8x8_dc = ff_simple_idct_add;
-        v->s.dsp.vc1_inv_trans_8x4_dc = ff_simple_idct84_add;
-        v->s.dsp.vc1_inv_trans_4x8_dc = ff_simple_idct48_add;
-        v->s.dsp.vc1_inv_trans_4x4_dc = ff_simple_idct44_add;
+        v->vc1dsp.vc1_inv_trans_8x8_add = ff_simple_idct_add;
+        v->vc1dsp.vc1_inv_trans_8x8_put[0] = ff_simple_idct_put;
+        v->vc1dsp.vc1_inv_trans_8x8_put[1] = simple_idct_put_rangered;
+        v->vc1dsp.vc1_inv_trans_8x8_put_signed[0] = simple_idct_put_signed;
+        v->vc1dsp.vc1_inv_trans_8x8_put_signed[1] = simple_idct_put_signed_rangered;
+        v->vc1dsp.vc1_inv_trans_8x4 = ff_simple_idct84_add;
+        v->vc1dsp.vc1_inv_trans_4x8 = ff_simple_idct48_add;
+        v->vc1dsp.vc1_inv_trans_4x4 = ff_simple_idct44_add;
+        v->vc1dsp.vc1_inv_trans_8x8_dc = ff_simple_idct_add;
+        v->vc1dsp.vc1_inv_trans_8x4_dc = ff_simple_idct84_add;
+        v->vc1dsp.vc1_inv_trans_4x8_dc = ff_simple_idct48_add;
+        v->vc1dsp.vc1_inv_trans_4x4_dc = ff_simple_idct44_add;
     }
 
     v->fastuvmc =  get_bits1(gb); //common
@@ -382,13 +412,27 @@ int vc1_decode_sequence_header(AVCodecContext *avctx, VC1Context *v, GetBitConte
     v->quantizer_mode = get_bits(gb, 2); //common
 
     v->finterpflag = get_bits1(gb); //common
-    v->res_rtm_flag = get_bits1(gb); //reserved
+
+    if (v->res_sprite) {
+        v->s.avctx->width  = v->s.avctx->coded_width  = get_bits(gb, 11);
+        v->s.avctx->height = v->s.avctx->coded_height = get_bits(gb, 11);
+        skip_bits(gb, 5); //frame rate
+        v->res_x8 = get_bits1(gb);
+        if (get_bits1(gb)) { // something to do with DC VLC selection
+            av_log(avctx, AV_LOG_ERROR, "Unsupported sprite feature\n");
+            return -1;
+        }
+        skip_bits(gb, 3); //slice code
+        v->res_rtm_flag = 0;
+    } else {
+        v->res_rtm_flag = get_bits1(gb); //reserved
+    }
     if (!v->res_rtm_flag)
     {
 //            av_log(avctx, AV_LOG_ERROR,
 //                   "0 for reserved RES_RTM_FLAG is forbidden\n");
         av_log(avctx, AV_LOG_ERROR,
-               "Old WMV3 version detected, only I-frames will be decoded\n");
+               "Old WMV3 version detected, some frames may be decoded incorrectly\n");
         //return -1;
     }
     //TODO: figure out what they mean (always 0x402F)
@@ -816,6 +860,7 @@ int vc1_parse_frame_header_adv(VC1Context *v, GetBitContext* gb)
         }
     }
     if(v->panscanflag) {
+        av_log_missing_feature(v->s.avctx, "Pan-scan", 0);
         //...
     }
     v->rnd = get_bits1(gb);
diff --git a/libavcodec/vc1.h b/libavcodec/vc1.h
index d5f0e05..db8a7f4 100644
--- a/libavcodec/vc1.h
+++ b/libavcodec/vc1.h
@@ -3,20 +3,20 @@
  * Copyright (c) 2006-2007 Konstantin Shishkov
  * Partly based on vc9.c (c) 2005 Anonymous, Alex Beregszaszi, Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -26,6 +26,7 @@
 #include "avcodec.h"
 #include "mpegvideo.h"
 #include "intrax8.h"
+#include "vc1dsp.h"
 
 /** Markers used in VC-1 AP frame data */
 //@{
@@ -155,12 +156,14 @@ enum COTypes {
 typedef struct VC1Context{
     MpegEncContext s;
     IntraX8Context x8;
+    VC1DSPContext vc1dsp;
 
     int bits;
 
     /** Simple/Main Profile sequence header */
     //@{
-    int res_sm;           ///< reserved, 2b
+    int res_sprite;       ///< reserved, sprite mode
+    int res_y411;         ///< reserved, old interlaced mode
     int res_x8;           ///< reserved
     int multires;         ///< frame-level RESPIC syntax element present
     int res_fasttx;       ///< reserved, always 1
@@ -214,6 +217,8 @@ typedef struct VC1Context{
     int k_y;              ///< Number of bits for MVs (depends on MV range)
     int range_x, range_y; ///< MV range
     uint8_t pq, altpq;    ///< Current/alternate frame quantizer scale
+    uint8_t zz_8x8[4][64];///< Zigzag table for TT_8x8, permuted for IDCT
+    int left_blk_sh, top_blk_sh; ///< Either 3 or 0, positions of l/t in blk[]
     const uint8_t* zz_8x4;///< Zigzag scan table for TT_8x4 coding mode
     const uint8_t* zz_4x8;///< Zigzag scan table for TT_4x8 coding mode
     /** pquant parameters */
@@ -232,7 +237,7 @@ typedef struct VC1Context{
     //@}
     int ttfrm;            ///< Transform type info present at frame level
     uint8_t ttmbf;        ///< Transform type flag
-    uint8_t ttblk4x4;     ///< Value of ttblk which indicates a 4x4 transform
+    int *ttblk_base, *ttblk; ///< Transform type at the block level
     int codingset;        ///< index of current table set from 11.8 to use for luma block decoding
     int codingset2;       ///< index of current table set from 11.8 to use for chroma block decoding
     int pqindex;          ///< raw pqindex used in coding set selection
@@ -302,11 +307,19 @@ typedef struct VC1Context{
     uint8_t range_mapuv;
     //@}
 
+    /** Frame decoding info for sprite modes */
+    //@{
+    int new_sprite;
+    int two_sprites;
+    //@}
+
     int p_frame_skipped;
     int bi_type;
     int x8_type;
 
     uint32_t *cbp_base, *cbp;
+    uint8_t *is_intra_base, *is_intra;
+    int16_t (*luma_mv_base)[2], (*luma_mv)[2];
     uint8_t bfraction_lut_index;///< Index for BFRACTION value (see Table 40, reproduced into ff_vc1_bfraction_lut[])
     uint8_t broken_link;        ///< Broken link flag (BROKEN_LINK syntax element)
     uint8_t closed_entry;       ///< Closed entry point flag (CLOSED_ENTRY syntax element)
diff --git a/libavcodec/vc1_parser.c b/libavcodec/vc1_parser.c
index 6e559de..da8ba87 100644
--- a/libavcodec/vc1_parser.c
+++ b/libavcodec/vc1_parser.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2006-2007 Konstantin Shishkov
  * Partly based on vc9.c (c) 2005 Anonymous, Alex Beregszaszi, Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -169,7 +169,7 @@ static int vc1_split(AVCodecContext *avctx,
     return 0;
 }
 
-AVCodecParser vc1_parser = {
+AVCodecParser ff_vc1_parser = {
     { CODEC_ID_VC1 },
     sizeof(VC1ParseContext),
     NULL,
diff --git a/libavcodec/vc1acdata.h b/libavcodec/vc1acdata.h
index 78de0f9..a7a33ff 100644
--- a/libavcodec/vc1acdata.h
+++ b/libavcodec/vc1acdata.h
@@ -2,20 +2,20 @@
  * VC-1 and WMV3 decoder
  * copyright (c) 2006 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/vc1data.c b/libavcodec/vc1data.c
index 5298079..1cbf93e 100644
--- a/libavcodec/vc1data.c
+++ b/libavcodec/vc1data.c
@@ -3,20 +3,20 @@
  * copyright (c) 2006 Konstantin Shishkov
  * (c) 2005 anonymous, Alex Beregszaszi, Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/vc1data.h b/libavcodec/vc1data.h
index 934627a..1ccc9bb 100644
--- a/libavcodec/vc1data.h
+++ b/libavcodec/vc1data.h
@@ -3,20 +3,20 @@
  * copyright (c) 2006 Konstantin Shishkov
  * (c) 2005 anonymous, Alex Beregszaszi, Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/vc1dec.c b/libavcodec/vc1dec.c
index 52392c3..6e73317 100644
--- a/libavcodec/vc1dec.c
+++ b/libavcodec/vc1dec.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2006-2007 Konstantin Shishkov
  * Partly based on vc9.c (c) 2005 Anonymous, Alex Beregszaszi, Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -160,52 +160,30 @@ enum Imode {
 
 /** @} */ //Bitplane group
 
-static void vc1_loop_filter_iblk(MpegEncContext *s, int pq)
+static void vc1_loop_filter_iblk(VC1Context *v, int pq)
 {
-    int i, j;
-    if(!s->first_slice_line)
-        s->dsp.vc1_v_loop_filter16(s->dest[0], s->linesize, pq);
-    s->dsp.vc1_v_loop_filter16(s->dest[0] + 8*s->linesize, s->linesize, pq);
-    for(i = !s->mb_x*8; i < 16; i += 8)
-        s->dsp.vc1_h_loop_filter16(s->dest[0] + i, s->linesize, pq);
-    for(j = 0; j < 2; j++){
-        if(!s->first_slice_line)
-            s->dsp.vc1_v_loop_filter8(s->dest[j+1], s->uvlinesize, pq);
-        if(s->mb_x)
-            s->dsp.vc1_h_loop_filter8(s->dest[j+1], s->uvlinesize, pq);
-    }
-}
-
-/** Put block onto picture
- */
-static void vc1_put_block(VC1Context *v, DCTELEM block[6][64])
-{
-    uint8_t *Y;
-    int ys, us, vs;
-    DSPContext *dsp = &v->s.dsp;
-
-    if(v->rangeredfrm) {
-        int i, j, k;
-        for(k = 0; k < 6; k++)
-            for(j = 0; j < 8; j++)
-                for(i = 0; i < 8; i++)
-                    block[k][i + j*8] = ((block[k][i + j*8] - 128) << 1) + 128;
-
+    MpegEncContext *s = &v->s;
+    int j;
+    if (!s->first_slice_line) {
+        v->vc1dsp.vc1_v_loop_filter16(s->dest[0], s->linesize, pq);
+        if (s->mb_x)
+            v->vc1dsp.vc1_h_loop_filter16(s->dest[0] - 16*s->linesize, s->linesize, pq);
+        v->vc1dsp.vc1_h_loop_filter16(s->dest[0] - 16*s->linesize+8, s->linesize, pq);
+        for(j = 0; j < 2; j++){
+            v->vc1dsp.vc1_v_loop_filter8(s->dest[j+1], s->uvlinesize, pq);
+            if (s->mb_x)
+                v->vc1dsp.vc1_h_loop_filter8(s->dest[j+1]-8*s->uvlinesize, s->uvlinesize, pq);
+        }
     }
-    ys = v->s.current_picture.linesize[0];
-    us = v->s.current_picture.linesize[1];
-    vs = v->s.current_picture.linesize[2];
-    Y = v->s.dest[0];
+    v->vc1dsp.vc1_v_loop_filter16(s->dest[0] + 8*s->linesize, s->linesize, pq);
 
-    dsp->put_pixels_clamped(block[0], Y, ys);
-    dsp->put_pixels_clamped(block[1], Y + 8, ys);
-    Y += ys * 8;
-    dsp->put_pixels_clamped(block[2], Y, ys);
-    dsp->put_pixels_clamped(block[3], Y + 8, ys);
-
-    if(!(v->s.flags & CODEC_FLAG_GRAY)) {
-        dsp->put_pixels_clamped(block[4], v->s.dest[1], us);
-        dsp->put_pixels_clamped(block[5], v->s.dest[2], vs);
+    if (s->mb_y == s->mb_height-1) {
+        if (s->mb_x) {
+            v->vc1dsp.vc1_h_loop_filter16(s->dest[0], s->linesize, pq);
+            v->vc1dsp.vc1_h_loop_filter8(s->dest[1], s->uvlinesize, pq);
+            v->vc1dsp.vc1_h_loop_filter8(s->dest[2], s->uvlinesize, pq);
+        }
+        v->vc1dsp.vc1_h_loop_filter16(s->dest[0] + 8, s->linesize, pq);
     }
 }
 
@@ -231,6 +209,8 @@ static void vc1_mc_1mv(VC1Context *v, int dir)
     }
     uvmx = (mx + ((mx & 3) == 3)) >> 1;
     uvmy = (my + ((my & 3) == 3)) >> 1;
+    v->luma_mv[s->mb_x][0] = uvmx;
+    v->luma_mv[s->mb_x][1] = uvmy;
     if(v->fastuvmc) {
         uvmx = uvmx + ((uvmx<0)?(uvmx&1):-(uvmx&1));
         uvmy = uvmy + ((uvmy<0)?(uvmy&1):-(uvmy&1));
@@ -278,12 +258,12 @@ static void vc1_mc_1mv(VC1Context *v, int dir)
         uint8_t *uvbuf= s->edge_emu_buffer + 19 * s->linesize;
 
         srcY -= s->mspel * (1 + s->linesize);
-        ff_emulated_edge_mc(s->edge_emu_buffer, srcY, s->linesize, 17+s->mspel*2, 17+s->mspel*2,
+        s->dsp.emulated_edge_mc(s->edge_emu_buffer, srcY, s->linesize, 17+s->mspel*2, 17+s->mspel*2,
                             src_x - s->mspel, src_y - s->mspel, s->h_edge_pos, s->v_edge_pos);
         srcY = s->edge_emu_buffer;
-        ff_emulated_edge_mc(uvbuf     , srcU, s->uvlinesize, 8+1, 8+1,
+        s->dsp.emulated_edge_mc(uvbuf     , srcU, s->uvlinesize, 8+1, 8+1,
                             uvsrc_x, uvsrc_y, s->h_edge_pos >> 1, s->v_edge_pos >> 1);
-        ff_emulated_edge_mc(uvbuf + 16, srcV, s->uvlinesize, 8+1, 8+1,
+        s->dsp.emulated_edge_mc(uvbuf + 16, srcV, s->uvlinesize, 8+1, 8+1,
                             uvsrc_x, uvsrc_y, s->h_edge_pos >> 1, s->v_edge_pos >> 1);
         srcU = uvbuf;
         srcV = uvbuf + 16;
@@ -332,11 +312,11 @@ static void vc1_mc_1mv(VC1Context *v, int dir)
 
     if(s->mspel) {
         dxy = ((my & 3) << 2) | (mx & 3);
-        dsp->put_vc1_mspel_pixels_tab[dxy](s->dest[0]    , srcY    , s->linesize, v->rnd);
-        dsp->put_vc1_mspel_pixels_tab[dxy](s->dest[0] + 8, srcY + 8, s->linesize, v->rnd);
+        v->vc1dsp.put_vc1_mspel_pixels_tab[dxy](s->dest[0]    , srcY    , s->linesize, v->rnd);
+        v->vc1dsp.put_vc1_mspel_pixels_tab[dxy](s->dest[0] + 8, srcY + 8, s->linesize, v->rnd);
         srcY += s->linesize * 8;
-        dsp->put_vc1_mspel_pixels_tab[dxy](s->dest[0] + 8 * s->linesize    , srcY    , s->linesize, v->rnd);
-        dsp->put_vc1_mspel_pixels_tab[dxy](s->dest[0] + 8 * s->linesize + 8, srcY + 8, s->linesize, v->rnd);
+        v->vc1dsp.put_vc1_mspel_pixels_tab[dxy](s->dest[0] + 8 * s->linesize    , srcY    , s->linesize, v->rnd);
+        v->vc1dsp.put_vc1_mspel_pixels_tab[dxy](s->dest[0] + 8 * s->linesize + 8, srcY + 8, s->linesize, v->rnd);
     } else { // hpel mc - always used for luma
         dxy = (my & 2) | ((mx & 2) >> 1);
 
@@ -354,8 +334,8 @@ static void vc1_mc_1mv(VC1Context *v, int dir)
         dsp->put_h264_chroma_pixels_tab[0](s->dest[1], srcU, s->uvlinesize, 8, uvmx, uvmy);
         dsp->put_h264_chroma_pixels_tab[0](s->dest[2], srcV, s->uvlinesize, 8, uvmx, uvmy);
     }else{
-        dsp->put_no_rnd_vc1_chroma_pixels_tab[0](s->dest[1], srcU, s->uvlinesize, 8, uvmx, uvmy);
-        dsp->put_no_rnd_vc1_chroma_pixels_tab[0](s->dest[2], srcV, s->uvlinesize, 8, uvmx, uvmy);
+        v->vc1dsp.put_no_rnd_vc1_chroma_pixels_tab[0](s->dest[1], srcU, s->uvlinesize, 8, uvmx, uvmy);
+        v->vc1dsp.put_no_rnd_vc1_chroma_pixels_tab[0](s->dest[2], srcV, s->uvlinesize, 8, uvmx, uvmy);
     }
 }
 
@@ -393,7 +373,7 @@ static void vc1_mc_4mv_luma(VC1Context *v, int n)
        || (unsigned)(src_x - s->mspel) > s->h_edge_pos - (mx&3) - 8 - s->mspel*2
        || (unsigned)(src_y - s->mspel) > s->v_edge_pos - (my&3) - 8 - s->mspel*2){
         srcY -= s->mspel * (1 + s->linesize);
-        ff_emulated_edge_mc(s->edge_emu_buffer, srcY, s->linesize, 9+s->mspel*2, 9+s->mspel*2,
+        s->dsp.emulated_edge_mc(s->edge_emu_buffer, srcY, s->linesize, 9+s->mspel*2, 9+s->mspel*2,
                             src_x - s->mspel, src_y - s->mspel, s->h_edge_pos, s->v_edge_pos);
         srcY = s->edge_emu_buffer;
         /* if we deal with range reduction we need to scale source blocks */
@@ -423,7 +403,7 @@ static void vc1_mc_4mv_luma(VC1Context *v, int n)
 
     if(s->mspel) {
         dxy = ((my & 3) << 2) | (mx & 3);
-        dsp->put_vc1_mspel_pixels_tab[dxy](s->dest[0] + off, srcY, s->linesize, v->rnd);
+        v->vc1dsp.put_vc1_mspel_pixels_tab[dxy](s->dest[0] + off, srcY, s->linesize, v->rnd);
     } else { // hpel mc - always used for luma
         dxy = (my & 2) | ((mx & 2) >> 1);
         if(!v->rnd)
@@ -499,6 +479,7 @@ static void vc1_mc_4mv_chroma(VC1Context *v)
     } else {
         s->current_picture.motion_val[1][s->block_index[0]][0] = 0;
         s->current_picture.motion_val[1][s->block_index[0]][1] = 0;
+        v->luma_mv[s->mb_x][0] = v->luma_mv[s->mb_x][1] = 0;
         return; //no need to do MC for inter blocks
     }
 
@@ -506,6 +487,8 @@ static void vc1_mc_4mv_chroma(VC1Context *v)
     s->current_picture.motion_val[1][s->block_index[0]][1] = ty;
     uvmx = (tx + ((tx&3) == 3)) >> 1;
     uvmy = (ty + ((ty&3) == 3)) >> 1;
+    v->luma_mv[s->mb_x][0] = uvmx;
+    v->luma_mv[s->mb_x][1] = uvmy;
     if(v->fastuvmc) {
         uvmx = uvmx + ((uvmx<0)?(uvmx&1):-(uvmx&1));
         uvmy = uvmy + ((uvmy<0)?(uvmy&1):-(uvmy&1));
@@ -527,9 +510,9 @@ static void vc1_mc_4mv_chroma(VC1Context *v)
     if(v->rangeredfrm || (v->mv_mode == MV_PMODE_INTENSITY_COMP)
        || (unsigned)uvsrc_x > (s->h_edge_pos >> 1) - 9
        || (unsigned)uvsrc_y > (s->v_edge_pos >> 1) - 9){
-        ff_emulated_edge_mc(s->edge_emu_buffer     , srcU, s->uvlinesize, 8+1, 8+1,
+        s->dsp.emulated_edge_mc(s->edge_emu_buffer     , srcU, s->uvlinesize, 8+1, 8+1,
                             uvsrc_x, uvsrc_y, s->h_edge_pos >> 1, s->v_edge_pos >> 1);
-        ff_emulated_edge_mc(s->edge_emu_buffer + 16, srcV, s->uvlinesize, 8+1, 8+1,
+        s->dsp.emulated_edge_mc(s->edge_emu_buffer + 16, srcV, s->uvlinesize, 8+1, 8+1,
                             uvsrc_x, uvsrc_y, s->h_edge_pos >> 1, s->v_edge_pos >> 1);
         srcU = s->edge_emu_buffer;
         srcV = s->edge_emu_buffer + 16;
@@ -573,8 +556,8 @@ static void vc1_mc_4mv_chroma(VC1Context *v)
         dsp->put_h264_chroma_pixels_tab[0](s->dest[1], srcU, s->uvlinesize, 8, uvmx, uvmy);
         dsp->put_h264_chroma_pixels_tab[0](s->dest[2], srcV, s->uvlinesize, 8, uvmx, uvmy);
     }else{
-        dsp->put_no_rnd_vc1_chroma_pixels_tab[0](s->dest[1], srcU, s->uvlinesize, 8, uvmx, uvmy);
-        dsp->put_no_rnd_vc1_chroma_pixels_tab[0](s->dest[2], srcV, s->uvlinesize, 8, uvmx, uvmy);
+        v->vc1dsp.put_no_rnd_vc1_chroma_pixels_tab[0](s->dest[1], srcU, s->uvlinesize, 8, uvmx, uvmy);
+        v->vc1dsp.put_no_rnd_vc1_chroma_pixels_tab[0](s->dest[2], srcV, s->uvlinesize, 8, uvmx, uvmy);
     }
 }
 
@@ -674,8 +657,9 @@ static void vc1_mc_4mv_chroma(VC1Context *v)
 
 /** Predict and set motion vector
  */
-static inline void vc1_pred_mv(MpegEncContext *s, int n, int dmv_x, int dmv_y, int mv1, int r_x, int r_y, uint8_t* is_intra)
+static inline void vc1_pred_mv(VC1Context *v, int n, int dmv_x, int dmv_y, int mv1, int r_x, int r_y, uint8_t* is_intra)
 {
+    MpegEncContext *s = &v->s;
     int xy, wrap, off = 0;
     int16_t *A, *B, *C;
     int px, py;
@@ -700,6 +684,7 @@ static inline void vc1_pred_mv(MpegEncContext *s, int n, int dmv_x, int dmv_y, i
             s->current_picture.motion_val[0][xy + wrap][1] = 0;
             s->current_picture.motion_val[0][xy + wrap + 1][0] = 0;
             s->current_picture.motion_val[0][xy + wrap + 1][1] = 0;
+            v->luma_mv[s->mb_x][0] = v->luma_mv[s->mb_x][1] = 0;
             s->current_picture.motion_val[1][xy + 1][0] = 0;
             s->current_picture.motion_val[1][xy + 1][1] = 0;
             s->current_picture.motion_val[1][xy + wrap][0] = 0;
@@ -862,12 +847,12 @@ static void vc1_interp_mc(VC1Context *v)
         uint8_t *uvbuf= s->edge_emu_buffer + 19 * s->linesize;
 
         srcY -= s->mspel * (1 + s->linesize);
-        ff_emulated_edge_mc(s->edge_emu_buffer, srcY, s->linesize, 17+s->mspel*2, 17+s->mspel*2,
+        s->dsp.emulated_edge_mc(s->edge_emu_buffer, srcY, s->linesize, 17+s->mspel*2, 17+s->mspel*2,
                             src_x - s->mspel, src_y - s->mspel, s->h_edge_pos, s->v_edge_pos);
         srcY = s->edge_emu_buffer;
-        ff_emulated_edge_mc(uvbuf     , srcU, s->uvlinesize, 8+1, 8+1,
+        s->dsp.emulated_edge_mc(uvbuf     , srcU, s->uvlinesize, 8+1, 8+1,
                             uvsrc_x, uvsrc_y, s->h_edge_pos >> 1, s->v_edge_pos >> 1);
-        ff_emulated_edge_mc(uvbuf + 16, srcV, s->uvlinesize, 8+1, 8+1,
+        s->dsp.emulated_edge_mc(uvbuf + 16, srcV, s->uvlinesize, 8+1, 8+1,
                             uvsrc_x, uvsrc_y, s->h_edge_pos >> 1, s->v_edge_pos >> 1);
         srcU = uvbuf;
         srcV = uvbuf + 16;
@@ -896,11 +881,11 @@ static void vc1_interp_mc(VC1Context *v)
 
     if(s->mspel) {
         dxy = ((my & 3) << 2) | (mx & 3);
-        dsp->avg_vc1_mspel_pixels_tab[dxy](s->dest[0]    , srcY    , s->linesize, v->rnd);
-        dsp->avg_vc1_mspel_pixels_tab[dxy](s->dest[0] + 8, srcY + 8, s->linesize, v->rnd);
+        v->vc1dsp.avg_vc1_mspel_pixels_tab[dxy](s->dest[0]    , srcY    , s->linesize, v->rnd);
+        v->vc1dsp.avg_vc1_mspel_pixels_tab[dxy](s->dest[0] + 8, srcY + 8, s->linesize, v->rnd);
         srcY += s->linesize * 8;
-        dsp->avg_vc1_mspel_pixels_tab[dxy](s->dest[0] + 8 * s->linesize    , srcY    , s->linesize, v->rnd);
-        dsp->avg_vc1_mspel_pixels_tab[dxy](s->dest[0] + 8 * s->linesize + 8, srcY + 8, s->linesize, v->rnd);
+        v->vc1dsp.avg_vc1_mspel_pixels_tab[dxy](s->dest[0] + 8 * s->linesize    , srcY    , s->linesize, v->rnd);
+        v->vc1dsp.avg_vc1_mspel_pixels_tab[dxy](s->dest[0] + 8 * s->linesize + 8, srcY + 8, s->linesize, v->rnd);
     } else { // hpel mc
         dxy = (my & 2) | ((mx & 2) >> 1);
 
@@ -918,8 +903,8 @@ static void vc1_interp_mc(VC1Context *v)
         dsp->avg_h264_chroma_pixels_tab[0](s->dest[1], srcU, s->uvlinesize, 8, uvmx, uvmy);
         dsp->avg_h264_chroma_pixels_tab[0](s->dest[2], srcV, s->uvlinesize, 8, uvmx, uvmy);
     }else{
-        dsp->avg_no_rnd_vc1_chroma_pixels_tab[0](s->dest[1], srcU, s->uvlinesize, 8, uvmx, uvmy);
-        dsp->avg_no_rnd_vc1_chroma_pixels_tab[0](s->dest[2], srcV, s->uvlinesize, 8, uvmx, uvmy);
+        v->vc1dsp.avg_no_rnd_vc1_chroma_pixels_tab[0](s->dest[1], srcU, s->uvlinesize, 8, uvmx, uvmy);
+        v->vc1dsp.avg_no_rnd_vc1_chroma_pixels_tab[0](s->dest[2], srcV, s->uvlinesize, 8, uvmx, uvmy);
     }
 }
 
@@ -1365,7 +1350,7 @@ static void vc1_decode_ac_coeff(VC1Context *v, int *last, int *skip, int *value,
     if (index != vc1_ac_sizes[codingset] - 1) {
         run = vc1_index_decode_table[codingset][index][0];
         level = vc1_index_decode_table[codingset][index][1];
-        lst = index >= vc1_last_decode_table[codingset];
+        lst = index >= vc1_last_decode_table[codingset] || get_bits_left(gb) < 0;
         if(get_bits1(gb))
             level = -level;
     } else {
@@ -1481,7 +1466,7 @@ static int vc1_decode_i_block(VC1Context *v, DCTELEM block[64], int n, int coded
 
     {
         int last = 0, skip, value;
-        const int8_t *zz_table;
+        const uint8_t *zz_table;
         int scale;
         int k;
 
@@ -1489,11 +1474,11 @@ static int vc1_decode_i_block(VC1Context *v, DCTELEM block[64], int n, int coded
 
         if(v->s.ac_pred) {
             if(!dc_pred_dir)
-                zz_table = wmv1_scantable[2];
+                zz_table = v->zz_8x8[2];
             else
-                zz_table = wmv1_scantable[3];
+                zz_table = v->zz_8x8[3];
         } else
-            zz_table = wmv1_scantable[1];
+            zz_table = v->zz_8x8[1];
 
         ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
         ac_val2 = ac_val;
@@ -1514,16 +1499,16 @@ static int vc1_decode_i_block(VC1Context *v, DCTELEM block[64], int n, int coded
         if(s->ac_pred) {
             if(dc_pred_dir) { //left
                 for(k = 1; k < 8; k++)
-                    block[k << 3] += ac_val[k];
+                    block[k << v->left_blk_sh] += ac_val[k];
             } else { //top
                 for(k = 1; k < 8; k++)
-                    block[k] += ac_val[k + 8];
+                    block[k << v->top_blk_sh] += ac_val[k + 8];
             }
         }
         /* save AC coeffs for further prediction */
         for(k = 1; k < 8; k++) {
-            ac_val2[k] = block[k << 3];
-            ac_val2[k + 8] = block[k];
+            ac_val2[k]     = block[k << v->left_blk_sh];
+            ac_val2[k + 8] = block[k << v->top_blk_sh];
         }
 
         /* scale AC coeffs */
@@ -1560,15 +1545,15 @@ not_coded:
         if(s->ac_pred) {
             if(dc_pred_dir) { //left
                 for(k = 1; k < 8; k++) {
-                    block[k << 3] = ac_val[k] * scale;
-                    if(!v->pquantizer && block[k << 3])
-                        block[k << 3] += (block[k << 3] < 0) ? -v->pq : v->pq;
+                    block[k << v->left_blk_sh] = ac_val[k] * scale;
+                    if(!v->pquantizer && block[k << v->left_blk_sh])
+                        block[k << v->left_blk_sh] += (block[k << v->left_blk_sh] < 0) ? -v->pq : v->pq;
                 }
             } else { //top
                 for(k = 1; k < 8; k++) {
-                    block[k] = ac_val[k + 8] * scale;
-                    if(!v->pquantizer && block[k])
-                        block[k] += (block[k] < 0) ? -v->pq : v->pq;
+                    block[k << v->top_blk_sh] = ac_val[k + 8] * scale;
+                    if(!v->pquantizer && block[k << v->top_blk_sh])
+                        block[k << v->top_blk_sh] += (block[k << v->top_blk_sh] < 0) ? -v->pq : v->pq;
                 }
             }
             i = 63;
@@ -1667,16 +1652,16 @@ static int vc1_decode_i_block_adv(VC1Context *v, DCTELEM block[64], int n, int c
 
     if(coded) {
         int last = 0, skip, value;
-        const int8_t *zz_table;
+        const uint8_t *zz_table;
         int k;
 
         if(v->s.ac_pred) {
             if(!dc_pred_dir)
-                zz_table = wmv1_scantable[2];
+                zz_table = v->zz_8x8[2];
             else
-                zz_table = wmv1_scantable[3];
+                zz_table = v->zz_8x8[3];
         } else
-            zz_table = wmv1_scantable[1];
+            zz_table = v->zz_8x8[1];
 
         while (!last) {
             vc1_decode_ac_coeff(v, &last, &skip, &value, codingset);
@@ -1695,25 +1680,25 @@ static int vc1_decode_i_block_adv(VC1Context *v, DCTELEM block[64], int n, int c
 
                 if(dc_pred_dir) { //left
                     for(k = 1; k < 8; k++)
-                        block[k << 3] += (ac_val[k] * q2 * ff_vc1_dqscale[q1 - 1] + 0x20000) >> 18;
+                        block[k << v->left_blk_sh] += (ac_val[k] * q2 * ff_vc1_dqscale[q1 - 1] + 0x20000) >> 18;
                 } else { //top
                     for(k = 1; k < 8; k++)
-                        block[k] += (ac_val[k + 8] * q2 * ff_vc1_dqscale[q1 - 1] + 0x20000) >> 18;
+                        block[k << v->top_blk_sh] += (ac_val[k + 8] * q2 * ff_vc1_dqscale[q1 - 1] + 0x20000) >> 18;
                 }
             } else {
                 if(dc_pred_dir) { //left
                     for(k = 1; k < 8; k++)
-                        block[k << 3] += ac_val[k];
+                        block[k << v->left_blk_sh] += ac_val[k];
                 } else { //top
                     for(k = 1; k < 8; k++)
-                        block[k] += ac_val[k + 8];
+                        block[k << v->top_blk_sh] += ac_val[k + 8];
                 }
             }
         }
         /* save AC coeffs for further prediction */
         for(k = 1; k < 8; k++) {
-            ac_val2[k] = block[k << 3];
-            ac_val2[k + 8] = block[k];
+            ac_val2[k    ] = block[k << v->left_blk_sh];
+            ac_val2[k + 8] = block[k << v->top_blk_sh];
         }
 
         /* scale AC coeffs */
@@ -1755,15 +1740,15 @@ static int vc1_decode_i_block_adv(VC1Context *v, DCTELEM block[64], int n, int c
         if(use_pred) {
             if(dc_pred_dir) { //left
                 for(k = 1; k < 8; k++) {
-                    block[k << 3] = ac_val2[k] * scale;
-                    if(!v->pquantizer && block[k << 3])
-                        block[k << 3] += (block[k << 3] < 0) ? -mquant : mquant;
+                    block[k << v->left_blk_sh] = ac_val2[k] * scale;
+                    if(!v->pquantizer && block[k << v->left_blk_sh])
+                        block[k << v->left_blk_sh] += (block[k << v->left_blk_sh] < 0) ? -mquant : mquant;
                 }
             } else { //top
                 for(k = 1; k < 8; k++) {
-                    block[k] = ac_val2[k + 8] * scale;
-                    if(!v->pquantizer && block[k])
-                        block[k] += (block[k] < 0) ? -mquant : mquant;
+                    block[k << v->top_blk_sh] = ac_val2[k + 8] * scale;
+                    if(!v->pquantizer && block[k << v->top_blk_sh])
+                        block[k << v->top_blk_sh] += (block[k << v->top_blk_sh] < 0) ? -mquant : mquant;
                 }
             }
             i = 63;
@@ -1874,17 +1859,14 @@ static int vc1_decode_intra_block(VC1Context *v, DCTELEM block[64], int n, int c
 
     if(coded) {
         int last = 0, skip, value;
-        const int8_t *zz_table;
         int k;
 
-        zz_table = wmv1_scantable[0];
-
         while (!last) {
             vc1_decode_ac_coeff(v, &last, &skip, &value, codingset);
             i += skip;
             if(i > 63)
                 break;
-            block[zz_table[i++]] = value;
+            block[v->zz_8x8[0][i++]] = value;
         }
 
         /* apply AC prediction if needed */
@@ -1896,25 +1878,25 @@ static int vc1_decode_intra_block(VC1Context *v, DCTELEM block[64], int n, int c
 
                 if(dc_pred_dir) { //left
                     for(k = 1; k < 8; k++)
-                        block[k << 3] += (ac_val[k] * q2 * ff_vc1_dqscale[q1 - 1] + 0x20000) >> 18;
+                        block[k << v->left_blk_sh] += (ac_val[k] * q2 * ff_vc1_dqscale[q1 - 1] + 0x20000) >> 18;
                 } else { //top
                     for(k = 1; k < 8; k++)
-                        block[k] += (ac_val[k + 8] * q2 * ff_vc1_dqscale[q1 - 1] + 0x20000) >> 18;
+                        block[k << v->top_blk_sh] += (ac_val[k + 8] * q2 * ff_vc1_dqscale[q1 - 1] + 0x20000) >> 18;
                 }
             } else {
                 if(dc_pred_dir) { //left
                     for(k = 1; k < 8; k++)
-                        block[k << 3] += ac_val[k];
+                        block[k << v->left_blk_sh] += ac_val[k];
                 } else { //top
                     for(k = 1; k < 8; k++)
-                        block[k] += ac_val[k + 8];
+                        block[k << v->top_blk_sh] += ac_val[k + 8];
                 }
             }
         }
         /* save AC coeffs for further prediction */
         for(k = 1; k < 8; k++) {
-            ac_val2[k] = block[k << 3];
-            ac_val2[k + 8] = block[k];
+            ac_val2[k    ] = block[k << v->left_blk_sh];
+            ac_val2[k + 8] = block[k << v->top_blk_sh];
         }
 
         /* scale AC coeffs */
@@ -1956,15 +1938,15 @@ static int vc1_decode_intra_block(VC1Context *v, DCTELEM block[64], int n, int c
         if(use_pred) {
             if(dc_pred_dir) { //left
                 for(k = 1; k < 8; k++) {
-                    block[k << 3] = ac_val2[k] * scale;
-                    if(!v->pquantizer && block[k << 3])
-                        block[k << 3] += (block[k << 3] < 0) ? -mquant : mquant;
+                    block[k << v->left_blk_sh] = ac_val2[k] * scale;
+                    if(!v->pquantizer && block[k << v->left_blk_sh])
+                        block[k << v->left_blk_sh] += (block[k << v->left_blk_sh] < 0) ? -mquant : mquant;
                 }
             } else { //top
                 for(k = 1; k < 8; k++) {
-                    block[k] = ac_val2[k + 8] * scale;
-                    if(!v->pquantizer && block[k])
-                        block[k] += (block[k] < 0) ? -mquant : mquant;
+                    block[k << v->top_blk_sh] = ac_val2[k + 8] * scale;
+                    if(!v->pquantizer && block[k << v->top_blk_sh])
+                        block[k << v->top_blk_sh] += (block[k << v->top_blk_sh] < 0) ? -mquant : mquant;
                 }
             }
             i = 63;
@@ -1978,7 +1960,7 @@ static int vc1_decode_intra_block(VC1Context *v, DCTELEM block[64], int n, int c
 /** Decode P block
  */
 static int vc1_decode_p_block(VC1Context *v, DCTELEM block[64], int n, int mquant, int ttmb, int first_block,
-                              uint8_t *dst, int linesize, int skip_block, int apply_filter, int cbp_top, int cbp_left)
+                              uint8_t *dst, int linesize, int skip_block, int *ttmb_out)
 {
     MpegEncContext *s = &v->s;
     GetBitContext *gb = &s->gb;
@@ -1996,7 +1978,9 @@ static int vc1_decode_p_block(VC1Context *v, DCTELEM block[64], int n, int mquan
     if(ttblk == TT_4X4) {
         subblkpat = ~(get_vlc2(gb, ff_vc1_subblkpat_vlc[v->tt_index].table, VC1_SUBBLKPAT_VLC_BITS, 1) + 1);
     }
-    if((ttblk != TT_8X8 && ttblk != TT_4X4) && (v->ttmbf || (ttmb != -1 && (ttmb & 8) && !first_block))) {
+    if((ttblk != TT_8X8 && ttblk != TT_4X4)
+        && ((v->ttmbf || (ttmb != -1 && (ttmb & 8) && !first_block))
+            || (!v->res_rtm_flag && !first_block))) {
         subblkpat = decode012(gb);
         if(subblkpat) subblkpat ^= 3; //swap decoded pattern bits
         if(ttblk == TT_8X4_TOP || ttblk == TT_8X4_BOTTOM) ttblk = TT_8X4;
@@ -2023,22 +2007,17 @@ static int vc1_decode_p_block(VC1Context *v, DCTELEM block[64], int n, int mquan
             i += skip;
             if(i > 63)
                 break;
-            idx = wmv1_scantable[0][i++];
+            idx = v->zz_8x8[0][i++];
             block[idx] = value * scale;
             if(!v->pquantizer)
                 block[idx] += (block[idx] < 0) ? -mquant : mquant;
         }
         if(!skip_block){
             if(i==1)
-                s->dsp.vc1_inv_trans_8x8_dc(dst, linesize, block);
+                v->vc1dsp.vc1_inv_trans_8x8_dc(dst, linesize, block);
             else{
-                s->dsp.vc1_inv_trans_8x8(block);
-                s->dsp.add_pixels_clamped(block, dst, linesize);
+                v->vc1dsp.vc1_inv_trans_8x8_add(dst, linesize, block);
             }
-            if(apply_filter && cbp_top  & 0xC)
-                s->dsp.vc1_v_loop_filter8(dst, linesize, v->pq);
-            if(apply_filter && cbp_left & 0xA)
-                s->dsp.vc1_h_loop_filter8(dst, linesize, v->pq);
         }
         break;
     case TT_4X4:
@@ -2059,13 +2038,9 @@ static int vc1_decode_p_block(VC1Context *v, DCTELEM block[64], int n, int mquan
             }
             if(!(subblkpat & (1 << (3 - j))) && !skip_block){
                 if(i==1)
-                    s->dsp.vc1_inv_trans_4x4_dc(dst + (j&1)*4 + (j&2)*2*linesize, linesize, block + off);
+                    v->vc1dsp.vc1_inv_trans_4x4_dc(dst + (j&1)*4 + (j&2)*2*linesize, linesize, block + off);
                 else
-                    s->dsp.vc1_inv_trans_4x4(dst + (j&1)*4 + (j&2)*2*linesize, linesize, block + off);
-                if(apply_filter && (j&2 ? pat & (1<<(j-2)) : (cbp_top & (1 << (j + 2)))))
-                    s->dsp.vc1_v_loop_filter4(dst + (j&1)*4 + (j&2)*2*linesize, linesize, v->pq);
-                if(apply_filter && (j&1 ? pat & (1<<(j-1)) : (cbp_left & (1 << (j + 1)))))
-                    s->dsp.vc1_h_loop_filter4(dst + (j&1)*4 + (j&2)*2*linesize, linesize, v->pq);
+                    v->vc1dsp.vc1_inv_trans_4x4(dst + (j&1)*4 + (j&2)*2*linesize, linesize, block + off);
             }
         }
         break;
@@ -2087,13 +2062,9 @@ static int vc1_decode_p_block(VC1Context *v, DCTELEM block[64], int n, int mquan
             }
             if(!(subblkpat & (1 << (1 - j))) && !skip_block){
                 if(i==1)
-                    s->dsp.vc1_inv_trans_8x4_dc(dst + j*4*linesize, linesize, block + off);
+                    v->vc1dsp.vc1_inv_trans_8x4_dc(dst + j*4*linesize, linesize, block + off);
                 else
-                    s->dsp.vc1_inv_trans_8x4(dst + j*4*linesize, linesize, block + off);
-                if(apply_filter && j ? pat & 0x3 : (cbp_top & 0xC))
-                    s->dsp.vc1_v_loop_filter8(dst + j*4*linesize, linesize, v->pq);
-                if(apply_filter && cbp_left & (2 << j))
-                    s->dsp.vc1_h_loop_filter4(dst + j*4*linesize, linesize, v->pq);
+                    v->vc1dsp.vc1_inv_trans_8x4(dst + j*4*linesize, linesize, block + off);
             }
         }
         break;
@@ -2115,17 +2086,15 @@ static int vc1_decode_p_block(VC1Context *v, DCTELEM block[64], int n, int mquan
             }
             if(!(subblkpat & (1 << (1 - j))) && !skip_block){
                 if(i==1)
-                    s->dsp.vc1_inv_trans_4x8_dc(dst + j*4, linesize, block + off);
+                    v->vc1dsp.vc1_inv_trans_4x8_dc(dst + j*4, linesize, block + off);
                 else
-                    s->dsp.vc1_inv_trans_4x8(dst + j*4, linesize, block + off);
-                if(apply_filter && cbp_top & (2 << j))
-                    s->dsp.vc1_v_loop_filter4(dst + j*4, linesize, v->pq);
-                if(apply_filter && j ? pat & 0x5 : (cbp_left & 0xA))
-                    s->dsp.vc1_h_loop_filter8(dst + j*4, linesize, v->pq);
+                    v->vc1dsp.vc1_inv_trans_4x8(dst + j*4, linesize, block + off);
             }
         }
         break;
     }
+    if (ttmb_out)
+        *ttmb_out |= ttblk << (n * 4);
     return pat;
 }
 
@@ -2134,13 +2103,162 @@ static int vc1_decode_p_block(VC1Context *v, DCTELEM block[64], int n, int mquan
 static const int size_table  [6] = { 0, 2, 3, 4,  5,  8 };
 static const int offset_table[6] = { 0, 1, 3, 7, 15, 31 };
 
+static av_always_inline void vc1_apply_p_v_loop_filter(VC1Context *v, int block_num)
+{
+    MpegEncContext *s = &v->s;
+    int mb_cbp         = v->cbp[s->mb_x - s->mb_stride],
+        block_cbp      = mb_cbp      >> (block_num * 4), bottom_cbp,
+        mb_is_intra    = v->is_intra[s->mb_x - s->mb_stride],
+        block_is_intra = mb_is_intra >> (block_num * 4), bottom_is_intra;
+    int idx, linesize = block_num > 3 ? s->uvlinesize : s->linesize, ttblk;
+    uint8_t *dst;
+
+    if(block_num > 3) {
+        dst      = s->dest[block_num - 3];
+    } else {
+        dst      = s->dest[0] + (block_num & 1) * 8 + ((block_num & 2) * 4 - 8) * linesize;
+    }
+    if (s->mb_y != s->mb_height || block_num < 2) {
+        int16_t (*mv)[2];
+        int mv_stride;
+
+        if(block_num > 3) {
+            bottom_cbp      = v->cbp[s->mb_x]      >> (block_num * 4);
+            bottom_is_intra = v->is_intra[s->mb_x] >> (block_num * 4);
+            mv              = &v->luma_mv[s->mb_x - s->mb_stride];
+            mv_stride       = s->mb_stride;
+        } else {
+            bottom_cbp      = (block_num < 2) ? (mb_cbp               >> ((block_num + 2) * 4)) :
+                                                (v->cbp[s->mb_x]      >> ((block_num - 2) * 4));
+            bottom_is_intra = (block_num < 2) ? (mb_is_intra          >> ((block_num + 2) * 4)) :
+                                                (v->is_intra[s->mb_x] >> ((block_num - 2) * 4));
+            mv_stride       = s->b8_stride;
+            mv              = &s->current_picture.motion_val[0][s->block_index[block_num] - 2 * mv_stride];
+        }
+
+        if (bottom_is_intra & 1 || block_is_intra & 1 ||
+            mv[0][0] != mv[mv_stride][0] || mv[0][1] != mv[mv_stride][1]) {
+            v->vc1dsp.vc1_v_loop_filter8(dst, linesize, v->pq);
+        } else {
+            idx = ((bottom_cbp >> 2) | block_cbp) & 3;
+            if(idx == 3) {
+                v->vc1dsp.vc1_v_loop_filter8(dst, linesize, v->pq);
+            } else if (idx) {
+                if (idx == 1)
+                    v->vc1dsp.vc1_v_loop_filter4(dst + 4, linesize, v->pq);
+                else
+                    v->vc1dsp.vc1_v_loop_filter4(dst,     linesize, v->pq);
+            }
+        }
+    }
+
+    dst -= 4 * linesize;
+    ttblk = (v->ttblk[s->mb_x - s->mb_stride] >> (block_num * 4)) & 0xf;
+    if (ttblk == TT_4X4 || ttblk == TT_8X4) {
+        idx = (block_cbp | (block_cbp >> 2)) & 3;
+        if (idx == 3) {
+            v->vc1dsp.vc1_v_loop_filter8(dst, linesize, v->pq);
+        } else if (idx) {
+            if (idx == 1)
+                v->vc1dsp.vc1_v_loop_filter4(dst + 4, linesize, v->pq);
+            else
+                v->vc1dsp.vc1_v_loop_filter4(dst,     linesize, v->pq);
+        }
+    }
+}
+
+static av_always_inline void vc1_apply_p_h_loop_filter(VC1Context *v, int block_num)
+{
+    MpegEncContext *s = &v->s;
+    int mb_cbp         = v->cbp[s->mb_x - 1 - s->mb_stride],
+        block_cbp      = mb_cbp      >> (block_num * 4), right_cbp,
+        mb_is_intra    = v->is_intra[s->mb_x - 1 - s->mb_stride],
+        block_is_intra = mb_is_intra >> (block_num * 4), right_is_intra;
+    int idx, linesize = block_num > 3 ? s->uvlinesize : s->linesize, ttblk;
+    uint8_t *dst;
+
+    if (block_num > 3) {
+        dst = s->dest[block_num - 3] - 8 * linesize;
+    } else {
+        dst = s->dest[0] + (block_num & 1) * 8 + ((block_num & 2) * 4 - 16) * linesize - 8;
+    }
+
+    if (s->mb_x != s->mb_width || !(block_num & 5)) {
+        int16_t (*mv)[2];
+
+        if(block_num > 3) {
+            right_cbp      = v->cbp[s->mb_x - s->mb_stride] >> (block_num * 4);
+            right_is_intra = v->is_intra[s->mb_x - s->mb_stride] >> (block_num * 4);
+            mv             = &v->luma_mv[s->mb_x - s->mb_stride - 1];
+        }else{
+            right_cbp      = (block_num & 1) ? (v->cbp[s->mb_x - s->mb_stride]      >> ((block_num - 1) * 4)) :
+                                               (mb_cbp                              >> ((block_num + 1) * 4));
+            right_is_intra = (block_num & 1) ? (v->is_intra[s->mb_x - s->mb_stride] >> ((block_num - 1) * 4)) :
+                                               (mb_is_intra                         >> ((block_num + 1) * 4));
+            mv             = &s->current_picture.motion_val[0][s->block_index[block_num] - s->b8_stride * 2 - 2];
+        }
+        if (block_is_intra & 1 || right_is_intra & 1 || mv[0][0] != mv[1][0] || mv[0][1] != mv[1][1]) {
+            v->vc1dsp.vc1_h_loop_filter8(dst, linesize, v->pq);
+        } else {
+            idx = ((right_cbp >> 1) | block_cbp) & 5; // FIXME check
+            if (idx == 5) {
+                v->vc1dsp.vc1_h_loop_filter8(dst, linesize, v->pq);
+            } else if (idx) {
+                if (idx == 1)
+                    v->vc1dsp.vc1_h_loop_filter4(dst+4*linesize, linesize, v->pq);
+                else
+                    v->vc1dsp.vc1_h_loop_filter4(dst,            linesize, v->pq);
+            }
+        }
+    }
+
+    dst -= 4;
+    ttblk = (v->ttblk[s->mb_x - s->mb_stride - 1] >> (block_num * 4)) & 0xf;
+    if (ttblk == TT_4X4 || ttblk == TT_4X8) {
+        idx = (block_cbp | (block_cbp >> 1)) & 5;
+        if (idx == 5) {
+            v->vc1dsp.vc1_h_loop_filter8(dst, linesize, v->pq);
+        } else if (idx) {
+            if (idx == 1)
+                v->vc1dsp.vc1_h_loop_filter4(dst + linesize*4, linesize, v->pq);
+            else
+                v->vc1dsp.vc1_h_loop_filter4(dst,              linesize, v->pq);
+        }
+    }
+}
+
+static void vc1_apply_p_loop_filter(VC1Context *v)
+{
+    MpegEncContext *s = &v->s;
+    int i;
+
+    for (i = 0; i < 6; i++) {
+        vc1_apply_p_v_loop_filter(v, i);
+    }
+
+    /* V always preceedes H, therefore we run H one MB before V;
+     * at the end of a row, we catch up to complete the row */
+    if (s->mb_x) {
+        for (i = 0; i < 6; i++) {
+            vc1_apply_p_h_loop_filter(v, i);
+        }
+        if (s->mb_x == s->mb_width - 1) {
+            s->mb_x++;
+            ff_update_block_index(s);
+            for (i = 0; i < 6; i++) {
+                vc1_apply_p_h_loop_filter(v, i);
+            }
+        }
+    }
+}
+
 /** Decode one P-frame MB (in Simple/Main profile)
  */
 static int vc1_decode_p_mb(VC1Context *v)
 {
     MpegEncContext *s = &v->s;
     GetBitContext *gb = &s->gb;
-    int i, j;
+    int i;
     int mb_pos = s->mb_x + s->mb_y * s->mb_stride;
     int cbp; /* cbp decoding stuff */
     int mqdiff, mquant; /* MB quantization */
@@ -2153,8 +2271,7 @@ static int vc1_decode_p_mb(VC1Context *v)
     int first_block = 1;
     int dst_idx, off;
     int skipped, fourmv;
-    int block_cbp = 0, pat;
-    int apply_loop_filter;
+    int block_cbp = 0, pat, block_tt = 0, block_intra = 0;
 
     mquant = v->pq; /* Loosy initialization */
 
@@ -2167,11 +2284,12 @@ static int vc1_decode_p_mb(VC1Context *v)
     else
         skipped = v->s.mbskip_table[mb_pos];
 
-    apply_loop_filter = s->loop_filter && !(s->avctx->skip_loop_filter >= AVDISCARD_NONKEY);
     if (!fourmv) /* 1MV mode */
     {
         if (!skipped)
         {
+            vc1_idct_func idct8x8_fn;
+
             GET_MVDATA(dmv_x, dmv_y);
 
             if (s->mb_intra) {
@@ -2179,7 +2297,7 @@ static int vc1_decode_p_mb(VC1Context *v)
                 s->current_picture.motion_val[1][s->block_index[0]][1] = 0;
             }
             s->current_picture.mb_type[mb_pos] = s->mb_intra ? MB_TYPE_INTRA : MB_TYPE_16x16;
-            vc1_pred_mv(s, 0, dmv_x, dmv_y, 1, v->range_x, v->range_y, v->mb_type[0]);
+            vc1_pred_mv(v, 0, dmv_x, dmv_y, 1, v->range_x, v->range_y, v->mb_type[0]);
 
             /* FIXME Set DC val for inter block ? */
             if (s->mb_intra && !mb_has_coeffs)
@@ -2206,6 +2324,7 @@ static int vc1_decode_p_mb(VC1Context *v)
                                 VC1_TTMB_VLC_BITS, 2);
             if(!s->mb_intra) vc1_mc_1mv(v, 0);
             dst_idx = 0;
+            idct8x8_fn = v->vc1dsp.vc1_inv_trans_8x8_put_signed[!!v->rangeredfrm];
             for (i=0; i<6; i++)
             {
                 s->dc_val[0][s->block_index[i]] = 0;
@@ -2223,47 +2342,19 @@ static int vc1_decode_p_mb(VC1Context *v)
 
                     vc1_decode_intra_block(v, s->block[i], i, val, mquant, (i&4)?v->codingset2:v->codingset);
                     if((i>3) && (s->flags & CODEC_FLAG_GRAY)) continue;
-                    s->dsp.vc1_inv_trans_8x8(s->block[i]);
-                    if(v->rangeredfrm) for(j = 0; j < 64; j++) s->block[i][j] <<= 1;
-                    s->dsp.put_signed_pixels_clamped(s->block[i], s->dest[dst_idx] + off, s->linesize >> ((i & 4) >> 2));
+                    idct8x8_fn(s->dest[dst_idx] + off,
+                               i & 4 ? s->uvlinesize : s->linesize,
+                               s->block[i]);
                     if(v->pq >= 9 && v->overlap) {
                         if(v->c_avail)
-                            s->dsp.vc1_h_overlap(s->dest[dst_idx] + off, s->linesize >> ((i & 4) >> 2));
+                            v->vc1dsp.vc1_h_overlap(s->dest[dst_idx] + off, i & 4 ? s->uvlinesize : s->linesize);
                         if(v->a_avail)
-                            s->dsp.vc1_v_overlap(s->dest[dst_idx] + off, s->linesize >> ((i & 4) >> 2));
-                    }
-                    if(apply_loop_filter && s->mb_x && s->mb_x != (s->mb_width - 1) && s->mb_y && s->mb_y != (s->mb_height - 1)){
-                        int left_cbp, top_cbp;
-                        if(i & 4){
-                            left_cbp = v->cbp[s->mb_x - 1]            >> (i * 4);
-                            top_cbp  = v->cbp[s->mb_x - s->mb_stride] >> (i * 4);
-                        }else{
-                            left_cbp = (i & 1) ? (cbp >> ((i-1)*4)) : (v->cbp[s->mb_x - 1]           >> ((i+1)*4));
-                            top_cbp  = (i & 2) ? (cbp >> ((i-2)*4)) : (v->cbp[s->mb_x - s->mb_stride] >> ((i+2)*4));
-                        }
-                        if(left_cbp & 0xC)
-                            s->dsp.vc1_v_loop_filter8(s->dest[dst_idx] + off, i & 4 ? s->uvlinesize : s->linesize, v->pq);
-                        if(top_cbp  & 0xA)
-                            s->dsp.vc1_h_loop_filter8(s->dest[dst_idx] + off, i & 4 ? s->uvlinesize : s->linesize, v->pq);
+                            v->vc1dsp.vc1_v_overlap(s->dest[dst_idx] + off, i & 4 ? s->uvlinesize : s->linesize);
                     }
                     block_cbp |= 0xF << (i << 2);
+                    block_intra |= 1 << i;
                 } else if(val) {
-                    int left_cbp = 0, top_cbp = 0, filter = 0;
-                    if(apply_loop_filter && s->mb_x && s->mb_x != (s->mb_width - 1) && s->mb_y && s->mb_y != (s->mb_height - 1)){
-                        filter = 1;
-                        if(i & 4){
-                            left_cbp = v->cbp[s->mb_x - 1]            >> (i * 4);
-                            top_cbp  = v->cbp[s->mb_x - s->mb_stride] >> (i * 4);
-                        }else{
-                            left_cbp = (i & 1) ? (cbp >> ((i-1)*4)) : (v->cbp[s->mb_x - 1]           >> ((i+1)*4));
-                            top_cbp  = (i & 2) ? (cbp >> ((i-2)*4)) : (v->cbp[s->mb_x - s->mb_stride] >> ((i+2)*4));
-                        }
-                        if(left_cbp & 0xC)
-                            s->dsp.vc1_v_loop_filter8(s->dest[dst_idx] + off, i & 4 ? s->uvlinesize : s->linesize, v->pq);
-                        if(top_cbp  & 0xA)
-                            s->dsp.vc1_h_loop_filter8(s->dest[dst_idx] + off, i & 4 ? s->uvlinesize : s->linesize, v->pq);
-                    }
-                    pat = vc1_decode_p_block(v, s->block[i], i, mquant, ttmb, first_block, s->dest[dst_idx] + off, (i&4)?s->uvlinesize:s->linesize, (i&4) && (s->flags & CODEC_FLAG_GRAY), filter, left_cbp, top_cbp);
+                    pat = vc1_decode_p_block(v, s->block[i], i, mquant, ttmb, first_block, s->dest[dst_idx] + off, (i&4)?s->uvlinesize:s->linesize, (i&4) && (s->flags & CODEC_FLAG_GRAY), &block_tt);
                     block_cbp |= pat << (i << 2);
                     if(!v->ttmbf && ttmb < 8) ttmb = -1;
                     first_block = 0;
@@ -2279,9 +2370,8 @@ static int vc1_decode_p_mb(VC1Context *v)
             }
             s->current_picture.mb_type[mb_pos] = MB_TYPE_SKIP;
             s->current_picture.qscale_table[mb_pos] = 0;
-            vc1_pred_mv(s, 0, 0, 0, 1, v->range_x, v->range_y, v->mb_type[0]);
+            vc1_pred_mv(v, 0, 0, 0, 1, v->range_x, v->range_y, v->mb_type[0]);
             vc1_mc_1mv(v, 0);
-            return 0;
         }
     } //1MV mode
     else //4MV mode
@@ -2290,6 +2380,7 @@ static int vc1_decode_p_mb(VC1Context *v)
         {
             int intra_count = 0, coded_inter = 0;
             int is_intra[6], is_coded[6];
+            vc1_idct_func idct8x8_fn;
             /* Get CBPCY */
             cbp = get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2);
             for (i=0; i<6; i++)
@@ -2304,7 +2395,7 @@ static int vc1_decode_p_mb(VC1Context *v)
                     if(val) {
                         GET_MVDATA(dmv_x, dmv_y);
                     }
-                    vc1_pred_mv(s, i, dmv_x, dmv_y, 0, v->range_x, v->range_y, v->mb_type[0]);
+                    vc1_pred_mv(v, i, dmv_x, dmv_y, 0, v->range_x, v->range_y, v->mb_type[0]);
                     if(!s->mb_intra) vc1_mc_4mv_luma(v, i);
                     intra_count += s->mb_intra;
                     is_intra[i] = s->mb_intra;
@@ -2319,8 +2410,9 @@ static int vc1_decode_p_mb(VC1Context *v)
                 if(!coded_inter) coded_inter = !is_intra[i] & is_coded[i];
             }
             // if there are no coded blocks then don't do anything more
-            if(!intra_count && !coded_inter) return 0;
             dst_idx = 0;
+            if(!intra_count && !coded_inter)
+                goto end;
             GET_MQUANT();
             s->current_picture.qscale_table[mb_pos] = mquant;
             /* test if block is intra and has pred */
@@ -2339,6 +2431,7 @@ static int vc1_decode_p_mb(VC1Context *v)
             }
             if (!v->ttmbf && coded_inter)
                 ttmb = get_vlc2(gb, ff_vc1_ttmb_vlc[v->tt_index].table, VC1_TTMB_VLC_BITS, 2);
+            idct8x8_fn = v->vc1dsp.vc1_inv_trans_8x8_put_signed[!!v->rangeredfrm];
             for (i=0; i<6; i++)
             {
                 dst_idx += i >> 2;
@@ -2354,53 +2447,24 @@ static int vc1_decode_p_mb(VC1Context *v)
 
                     vc1_decode_intra_block(v, s->block[i], i, is_coded[i], mquant, (i&4)?v->codingset2:v->codingset);
                     if((i>3) && (s->flags & CODEC_FLAG_GRAY)) continue;
-                    s->dsp.vc1_inv_trans_8x8(s->block[i]);
-                    if(v->rangeredfrm) for(j = 0; j < 64; j++) s->block[i][j] <<= 1;
-                    s->dsp.put_signed_pixels_clamped(s->block[i], s->dest[dst_idx] + off, (i&4)?s->uvlinesize:s->linesize);
+                    idct8x8_fn(s->dest[dst_idx] + off,
+                               (i&4)?s->uvlinesize:s->linesize,
+                               s->block[i]);
                     if(v->pq >= 9 && v->overlap) {
                         if(v->c_avail)
-                            s->dsp.vc1_h_overlap(s->dest[dst_idx] + off, s->linesize >> ((i & 4) >> 2));
+                            v->vc1dsp.vc1_h_overlap(s->dest[dst_idx] + off, i & 4 ? s->uvlinesize : s->linesize);
                         if(v->a_avail)
-                            s->dsp.vc1_v_overlap(s->dest[dst_idx] + off, s->linesize >> ((i & 4) >> 2));
-                    }
-                    if(v->s.loop_filter && s->mb_x && s->mb_x != (s->mb_width - 1) && s->mb_y && s->mb_y != (s->mb_height - 1)){
-                        int left_cbp, top_cbp;
-                        if(i & 4){
-                            left_cbp = v->cbp[s->mb_x - 1]            >> (i * 4);
-                            top_cbp  = v->cbp[s->mb_x - s->mb_stride] >> (i * 4);
-                        }else{
-                            left_cbp = (i & 1) ? (cbp >> ((i-1)*4)) : (v->cbp[s->mb_x - 1]           >> ((i+1)*4));
-                            top_cbp  = (i & 2) ? (cbp >> ((i-2)*4)) : (v->cbp[s->mb_x - s->mb_stride] >> ((i+2)*4));
-                        }
-                        if(left_cbp & 0xC)
-                            s->dsp.vc1_v_loop_filter8(s->dest[dst_idx] + off, i & 4 ? s->uvlinesize : s->linesize, v->pq);
-                        if(top_cbp  & 0xA)
-                            s->dsp.vc1_h_loop_filter8(s->dest[dst_idx] + off, i & 4 ? s->uvlinesize : s->linesize, v->pq);
+                            v->vc1dsp.vc1_v_overlap(s->dest[dst_idx] + off, i & 4 ? s->uvlinesize : s->linesize);
                     }
                     block_cbp |= 0xF << (i << 2);
+                    block_intra |= 1 << i;
                 } else if(is_coded[i]) {
-                    int left_cbp = 0, top_cbp = 0, filter = 0;
-                    if(v->s.loop_filter && s->mb_x && s->mb_x != (s->mb_width - 1) && s->mb_y && s->mb_y != (s->mb_height - 1)){
-                        filter = 1;
-                        if(i & 4){
-                            left_cbp = v->cbp[s->mb_x - 1]            >> (i * 4);
-                            top_cbp  = v->cbp[s->mb_x - s->mb_stride] >> (i * 4);
-                        }else{
-                            left_cbp = (i & 1) ? (cbp >> ((i-1)*4)) : (v->cbp[s->mb_x - 1]           >> ((i+1)*4));
-                            top_cbp  = (i & 2) ? (cbp >> ((i-2)*4)) : (v->cbp[s->mb_x - s->mb_stride] >> ((i+2)*4));
-                        }
-                        if(left_cbp & 0xC)
-                            s->dsp.vc1_v_loop_filter8(s->dest[dst_idx] + off, i & 4 ? s->uvlinesize : s->linesize, v->pq);
-                        if(top_cbp  & 0xA)
-                            s->dsp.vc1_h_loop_filter8(s->dest[dst_idx] + off, i & 4 ? s->uvlinesize : s->linesize, v->pq);
-                    }
-                    pat = vc1_decode_p_block(v, s->block[i], i, mquant, ttmb, first_block, s->dest[dst_idx] + off, (i&4)?s->uvlinesize:s->linesize, (i&4) && (s->flags & CODEC_FLAG_GRAY), filter, left_cbp, top_cbp);
+                    pat = vc1_decode_p_block(v, s->block[i], i, mquant, ttmb, first_block, s->dest[dst_idx] + off, (i&4)?s->uvlinesize:s->linesize, (i&4) && (s->flags & CODEC_FLAG_GRAY), &block_tt);
                     block_cbp |= pat << (i << 2);
                     if(!v->ttmbf && ttmb < 8) ttmb = -1;
                     first_block = 0;
                 }
             }
-            return 0;
         }
         else //Skipped MB
         {
@@ -2412,18 +2476,19 @@ static int vc1_decode_p_mb(VC1Context *v)
             }
             for (i=0; i<4; i++)
             {
-                vc1_pred_mv(s, i, 0, 0, 0, v->range_x, v->range_y, v->mb_type[0]);
+                vc1_pred_mv(v, i, 0, 0, 0, v->range_x, v->range_y, v->mb_type[0]);
                 vc1_mc_4mv_luma(v, i);
             }
             vc1_mc_4mv_chroma(v);
             s->current_picture.qscale_table[mb_pos] = 0;
-            return 0;
         }
     }
+end:
     v->cbp[s->mb_x] = block_cbp;
+    v->ttblk[s->mb_x] = block_tt;
+    v->is_intra[s->mb_x] = block_intra;
 
-    /* Should never happen */
-    return -1;
+    return 0;
 }
 
 /** Decode one B-frame MB (in Main profile)
@@ -2432,7 +2497,7 @@ static void vc1_decode_b_mb(VC1Context *v)
 {
     MpegEncContext *s = &v->s;
     GetBitContext *gb = &s->gb;
-    int i, j;
+    int i;
     int mb_pos = s->mb_x + s->mb_y * s->mb_stride;
     int cbp = 0; /* cbp decoding stuff */
     int mqdiff, mquant; /* MB quantization */
@@ -2445,6 +2510,7 @@ static void vc1_decode_b_mb(VC1Context *v)
     int skipped, direct;
     int dmv_x[2], dmv_y[2];
     int bmvtype = BMV_TYPE_BACKWARD;
+    vc1_idct_func idct8x8_fn;
 
     mquant = v->pq; /* Loosy initialization */
     s->mb_intra = 0;
@@ -2542,6 +2608,7 @@ static void vc1_decode_b_mb(VC1Context *v)
         }
     }
     dst_idx = 0;
+    idct8x8_fn = v->vc1dsp.vc1_inv_trans_8x8_put_signed[!!v->rangeredfrm];
     for (i=0; i<6; i++)
     {
         s->dc_val[0][s->block_index[i]] = 0;
@@ -2559,11 +2626,11 @@ static void vc1_decode_b_mb(VC1Context *v)
 
             vc1_decode_intra_block(v, s->block[i], i, val, mquant, (i&4)?v->codingset2:v->codingset);
             if((i>3) && (s->flags & CODEC_FLAG_GRAY)) continue;
-            s->dsp.vc1_inv_trans_8x8(s->block[i]);
-            if(v->rangeredfrm) for(j = 0; j < 64; j++) s->block[i][j] <<= 1;
-            s->dsp.put_signed_pixels_clamped(s->block[i], s->dest[dst_idx] + off, s->linesize >> ((i & 4) >> 2));
+            idct8x8_fn(s->dest[dst_idx] + off,
+                       i & 4 ? s->uvlinesize : s->linesize,
+                       s->block[i]);
         } else if(val) {
-            vc1_decode_p_block(v, s->block[i], i, mquant, ttmb, first_block, s->dest[dst_idx] + off, (i&4)?s->uvlinesize:s->linesize, (i&4) && (s->flags & CODEC_FLAG_GRAY), 0, 0, 0);
+            vc1_decode_p_block(v, s->block[i], i, mquant, ttmb, first_block, s->dest[dst_idx] + off, (i&4)?s->uvlinesize:s->linesize, (i&4) && (s->flags & CODEC_FLAG_GRAY), NULL);
             if(!v->ttmbf && ttmb < 8) ttmb = -1;
             first_block = 0;
         }
@@ -2574,11 +2641,12 @@ static void vc1_decode_b_mb(VC1Context *v)
  */
 static void vc1_decode_i_blocks(VC1Context *v)
 {
-    int k, j;
+    int k;
     MpegEncContext *s = &v->s;
     int cbp, val;
     uint8_t *coded_val;
     int mb_pos;
+    vc1_idct_func idct8x8_fn;
 
     /* select codingmode used for VLC tables selection */
     switch(v->y_ac_table_index){
@@ -2613,11 +2681,22 @@ static void vc1_decode_i_blocks(VC1Context *v)
     s->mb_x = s->mb_y = 0;
     s->mb_intra = 1;
     s->first_slice_line = 1;
+    if(v->pq >= 9 && v->overlap) {
+        idct8x8_fn = v->vc1dsp.vc1_inv_trans_8x8_put_signed[!!v->rangeredfrm];
+    } else
+        idct8x8_fn = v->vc1dsp.vc1_inv_trans_8x8_put[!!v->rangeredfrm];
     for(s->mb_y = 0; s->mb_y < s->mb_height; s->mb_y++) {
         s->mb_x = 0;
         ff_init_block_index(s);
         for(; s->mb_x < s->mb_width; s->mb_x++) {
+            uint8_t *dst[6];
             ff_update_block_index(s);
+            dst[0] = s->dest[0];
+            dst[1] = dst[0] + 8;
+            dst[2] = s->dest[0] + s->linesize * 8;
+            dst[3] = dst[2] + 8;
+            dst[4] = s->dest[1];
+            dst[5] = s->dest[2];
             s->dsp.clear_blocks(s->block[0]);
             mb_pos = s->mb_x + s->mb_y * s->mb_width;
             s->current_picture.mb_type[mb_pos] = MB_TYPE_INTRA;
@@ -2641,36 +2720,35 @@ static void vc1_decode_i_blocks(VC1Context *v)
 
                 vc1_decode_i_block(v, s->block[k], k, val, (k<4)? v->codingset : v->codingset2);
 
-                s->dsp.vc1_inv_trans_8x8(s->block[k]);
-                if(v->pq >= 9 && v->overlap) {
-                    for(j = 0; j < 64; j++) s->block[k][j] += 128;
-                }
+                if (k > 3 && (s->flags & CODEC_FLAG_GRAY)) continue;
+                idct8x8_fn(dst[k],
+                           k & 4 ? s->uvlinesize : s->linesize,
+                           s->block[k]);
             }
 
-            vc1_put_block(v, s->block);
             if(v->pq >= 9 && v->overlap) {
                 if(s->mb_x) {
-                    s->dsp.vc1_h_overlap(s->dest[0], s->linesize);
-                    s->dsp.vc1_h_overlap(s->dest[0] + 8 * s->linesize, s->linesize);
+                    v->vc1dsp.vc1_h_overlap(s->dest[0], s->linesize);
+                    v->vc1dsp.vc1_h_overlap(s->dest[0] + 8 * s->linesize, s->linesize);
                     if(!(s->flags & CODEC_FLAG_GRAY)) {
-                        s->dsp.vc1_h_overlap(s->dest[1], s->uvlinesize);
-                        s->dsp.vc1_h_overlap(s->dest[2], s->uvlinesize);
+                        v->vc1dsp.vc1_h_overlap(s->dest[1], s->uvlinesize);
+                        v->vc1dsp.vc1_h_overlap(s->dest[2], s->uvlinesize);
                     }
                 }
-                s->dsp.vc1_h_overlap(s->dest[0] + 8, s->linesize);
-                s->dsp.vc1_h_overlap(s->dest[0] + 8 * s->linesize + 8, s->linesize);
+                v->vc1dsp.vc1_h_overlap(s->dest[0] + 8, s->linesize);
+                v->vc1dsp.vc1_h_overlap(s->dest[0] + 8 * s->linesize + 8, s->linesize);
                 if(!s->first_slice_line) {
-                    s->dsp.vc1_v_overlap(s->dest[0], s->linesize);
-                    s->dsp.vc1_v_overlap(s->dest[0] + 8, s->linesize);
+                    v->vc1dsp.vc1_v_overlap(s->dest[0], s->linesize);
+                    v->vc1dsp.vc1_v_overlap(s->dest[0] + 8, s->linesize);
                     if(!(s->flags & CODEC_FLAG_GRAY)) {
-                        s->dsp.vc1_v_overlap(s->dest[1], s->uvlinesize);
-                        s->dsp.vc1_v_overlap(s->dest[2], s->uvlinesize);
+                        v->vc1dsp.vc1_v_overlap(s->dest[1], s->uvlinesize);
+                        v->vc1dsp.vc1_v_overlap(s->dest[2], s->uvlinesize);
                     }
                 }
-                s->dsp.vc1_v_overlap(s->dest[0] + 8 * s->linesize, s->linesize);
-                s->dsp.vc1_v_overlap(s->dest[0] + 8 * s->linesize + 8, s->linesize);
+                v->vc1dsp.vc1_v_overlap(s->dest[0] + 8 * s->linesize, s->linesize);
+                v->vc1dsp.vc1_v_overlap(s->dest[0] + 8 * s->linesize + 8, s->linesize);
             }
-            if(v->s.loop_filter) vc1_loop_filter_iblk(s, v->pq);
+            if(v->s.loop_filter) vc1_loop_filter_iblk(v, v->pq);
 
             if(get_bits_count(&s->gb) > v->bits) {
                 ff_er_add_slice(s, 0, 0, s->mb_x, s->mb_y, (AC_END|DC_END|MV_END));
@@ -2678,17 +2756,23 @@ static void vc1_decode_i_blocks(VC1Context *v)
                 return;
             }
         }
-        ff_draw_horiz_band(s, s->mb_y * 16, 16);
+        if (!v->s.loop_filter)
+            ff_draw_horiz_band(s, s->mb_y * 16, 16);
+        else if (s->mb_y)
+            ff_draw_horiz_band(s, (s->mb_y-1) * 16, 16);
+
         s->first_slice_line = 0;
     }
+    if (v->s.loop_filter)
+        ff_draw_horiz_band(s, (s->mb_height-1)*16, 16);
     ff_er_add_slice(s, 0, 0, s->mb_width - 1, s->mb_height - 1, (AC_END|DC_END|MV_END));
 }
 
 /** Decode blocks of I-frame for advanced profile
  */
-static void vc1_decode_i_blocks_adv(VC1Context *v)
+static void vc1_decode_i_blocks_adv(VC1Context *v, int mby_start, int mby_end)
 {
-    int k, j;
+    int k;
     MpegEncContext *s = &v->s;
     int cbp, val;
     uint8_t *coded_val;
@@ -2697,6 +2781,7 @@ static void vc1_decode_i_blocks_adv(VC1Context *v)
     int mqdiff;
     int overlap;
     GetBitContext *gb = &s->gb;
+    vc1_idct_func idct8x8_fn;
 
     /* select codingmode used for VLC tables selection */
     switch(v->y_ac_table_index){
@@ -2727,11 +2812,26 @@ static void vc1_decode_i_blocks_adv(VC1Context *v)
     s->mb_x = s->mb_y = 0;
     s->mb_intra = 1;
     s->first_slice_line = 1;
-    for(s->mb_y = 0; s->mb_y < s->mb_height; s->mb_y++) {
+    s->mb_y = mby_start;
+    if (mby_start) {
+        s->mb_x = 0;
+        ff_init_block_index(s);
+        memset(&s->coded_block[s->block_index[0]-s->b8_stride], 0,
+               s->b8_stride * sizeof(*s->coded_block));
+    }
+    idct8x8_fn = v->vc1dsp.vc1_inv_trans_8x8_put_signed[0];
+    for(; s->mb_y < mby_end; s->mb_y++) {
         s->mb_x = 0;
         ff_init_block_index(s);
         for(;s->mb_x < s->mb_width; s->mb_x++) {
+            uint8_t *dst[6];
             ff_update_block_index(s);
+            dst[0] = s->dest[0];
+            dst[1] = dst[0] + 8;
+            dst[2] = s->dest[0] + s->linesize * 8;
+            dst[3] = dst[2] + 8;
+            dst[4] = s->dest[1];
+            dst[5] = s->dest[2];
             s->dsp.clear_blocks(s->block[0]);
             mb_pos = s->mb_x + s->mb_y * s->mb_stride;
             s->current_picture.mb_type[mb_pos] = MB_TYPE_INTRA;
@@ -2775,50 +2875,57 @@ static void vc1_decode_i_blocks_adv(VC1Context *v)
 
                 vc1_decode_i_block_adv(v, s->block[k], k, val, (k<4)? v->codingset : v->codingset2, mquant);
 
-                s->dsp.vc1_inv_trans_8x8(s->block[k]);
-                for(j = 0; j < 64; j++) s->block[k][j] += 128;
+                if (k > 3 && (s->flags & CODEC_FLAG_GRAY)) continue;
+                idct8x8_fn(dst[k],
+                           k & 4 ? s->uvlinesize : s->linesize,
+                           s->block[k]);
             }
 
-            vc1_put_block(v, s->block);
             if(overlap) {
                 if(s->mb_x) {
-                    s->dsp.vc1_h_overlap(s->dest[0], s->linesize);
-                    s->dsp.vc1_h_overlap(s->dest[0] + 8 * s->linesize, s->linesize);
+                    v->vc1dsp.vc1_h_overlap(s->dest[0], s->linesize);
+                    v->vc1dsp.vc1_h_overlap(s->dest[0] + 8 * s->linesize, s->linesize);
                     if(!(s->flags & CODEC_FLAG_GRAY)) {
-                        s->dsp.vc1_h_overlap(s->dest[1], s->uvlinesize);
-                        s->dsp.vc1_h_overlap(s->dest[2], s->uvlinesize);
+                        v->vc1dsp.vc1_h_overlap(s->dest[1], s->uvlinesize);
+                        v->vc1dsp.vc1_h_overlap(s->dest[2], s->uvlinesize);
                     }
                 }
-                s->dsp.vc1_h_overlap(s->dest[0] + 8, s->linesize);
-                s->dsp.vc1_h_overlap(s->dest[0] + 8 * s->linesize + 8, s->linesize);
+                v->vc1dsp.vc1_h_overlap(s->dest[0] + 8, s->linesize);
+                v->vc1dsp.vc1_h_overlap(s->dest[0] + 8 * s->linesize + 8, s->linesize);
                 if(!s->first_slice_line) {
-                    s->dsp.vc1_v_overlap(s->dest[0], s->linesize);
-                    s->dsp.vc1_v_overlap(s->dest[0] + 8, s->linesize);
+                    v->vc1dsp.vc1_v_overlap(s->dest[0], s->linesize);
+                    v->vc1dsp.vc1_v_overlap(s->dest[0] + 8, s->linesize);
                     if(!(s->flags & CODEC_FLAG_GRAY)) {
-                        s->dsp.vc1_v_overlap(s->dest[1], s->uvlinesize);
-                        s->dsp.vc1_v_overlap(s->dest[2], s->uvlinesize);
+                        v->vc1dsp.vc1_v_overlap(s->dest[1], s->uvlinesize);
+                        v->vc1dsp.vc1_v_overlap(s->dest[2], s->uvlinesize);
                     }
                 }
-                s->dsp.vc1_v_overlap(s->dest[0] + 8 * s->linesize, s->linesize);
-                s->dsp.vc1_v_overlap(s->dest[0] + 8 * s->linesize + 8, s->linesize);
+                v->vc1dsp.vc1_v_overlap(s->dest[0] + 8 * s->linesize, s->linesize);
+                v->vc1dsp.vc1_v_overlap(s->dest[0] + 8 * s->linesize + 8, s->linesize);
             }
-            if(v->s.loop_filter) vc1_loop_filter_iblk(s, v->pq);
+            if(v->s.loop_filter) vc1_loop_filter_iblk(v, v->pq);
 
             if(get_bits_count(&s->gb) > v->bits) {
-                ff_er_add_slice(s, 0, 0, s->mb_x, s->mb_y, (AC_END|DC_END|MV_END));
+                ff_er_add_slice(s, 0, mby_start, s->mb_x, s->mb_y, (AC_END|DC_END|MV_END));
                 av_log(s->avctx, AV_LOG_ERROR, "Bits overconsumption: %i > %i\n", get_bits_count(&s->gb), v->bits);
                 return;
             }
         }
-        ff_draw_horiz_band(s, s->mb_y * 16, 16);
+        if (!v->s.loop_filter)
+            ff_draw_horiz_band(s, s->mb_y * 16, 16);
+        else if (s->mb_y)
+            ff_draw_horiz_band(s, (s->mb_y-1) * 16, 16);
         s->first_slice_line = 0;
     }
-    ff_er_add_slice(s, 0, 0, s->mb_width - 1, s->mb_height - 1, (AC_END|DC_END|MV_END));
+    if (v->s.loop_filter)
+        ff_draw_horiz_band(s, (s->mb_height-1)*16, 16);
+    ff_er_add_slice(s, 0, mby_start, s->mb_width - 1, mby_end - 1, (AC_END|DC_END|MV_END));
 }
 
-static void vc1_decode_p_blocks(VC1Context *v)
+static void vc1_decode_p_blocks(VC1Context *v, int mby_start, int mby_end)
 {
     MpegEncContext *s = &v->s;
+    int apply_loop_filter;
 
     /* select codingmode used for VLC tables selection */
     switch(v->c_ac_table_index){
@@ -2845,29 +2952,45 @@ static void vc1_decode_p_blocks(VC1Context *v)
         break;
     }
 
+    apply_loop_filter = s->loop_filter && !(s->avctx->skip_loop_filter >= AVDISCARD_NONKEY);
     s->first_slice_line = 1;
     memset(v->cbp_base, 0, sizeof(v->cbp_base[0])*2*s->mb_stride);
-    for(s->mb_y = 0; s->mb_y < s->mb_height; s->mb_y++) {
+    for(s->mb_y = mby_start; s->mb_y < mby_end; s->mb_y++) {
         s->mb_x = 0;
         ff_init_block_index(s);
         for(; s->mb_x < s->mb_width; s->mb_x++) {
             ff_update_block_index(s);
 
             vc1_decode_p_mb(v);
+            if (s->mb_y != mby_start && apply_loop_filter)
+                vc1_apply_p_loop_filter(v);
             if(get_bits_count(&s->gb) > v->bits || get_bits_count(&s->gb) < 0) {
-                ff_er_add_slice(s, 0, 0, s->mb_x, s->mb_y, (AC_END|DC_END|MV_END));
+                ff_er_add_slice(s, 0, mby_start, s->mb_x, s->mb_y, (AC_END|DC_END|MV_END));
                 av_log(s->avctx, AV_LOG_ERROR, "Bits overconsumption: %i > %i at %ix%i\n", get_bits_count(&s->gb), v->bits,s->mb_x,s->mb_y);
                 return;
             }
         }
         memmove(v->cbp_base, v->cbp, sizeof(v->cbp_base[0])*s->mb_stride);
-        ff_draw_horiz_band(s, s->mb_y * 16, 16);
+        memmove(v->ttblk_base, v->ttblk, sizeof(v->ttblk_base[0])*s->mb_stride);
+        memmove(v->is_intra_base, v->is_intra, sizeof(v->is_intra_base[0])*s->mb_stride);
+        memmove(v->luma_mv_base, v->luma_mv, sizeof(v->luma_mv_base[0])*s->mb_stride);
+        if (s->mb_y != mby_start) ff_draw_horiz_band(s, (s->mb_y-1) * 16, 16);
         s->first_slice_line = 0;
     }
-    ff_er_add_slice(s, 0, 0, s->mb_width - 1, s->mb_height - 1, (AC_END|DC_END|MV_END));
+    if (apply_loop_filter) {
+        s->mb_x = 0;
+        ff_init_block_index(s);
+        for (; s->mb_x < s->mb_width; s->mb_x++) {
+            ff_update_block_index(s);
+            vc1_apply_p_loop_filter(v);
+        }
+    }
+    if (mby_end >= mby_start)
+        ff_draw_horiz_band(s, (mby_end-1) * 16, 16);
+    ff_er_add_slice(s, 0, mby_start, s->mb_width - 1, mby_end - 1, (AC_END|DC_END|MV_END));
 }
 
-static void vc1_decode_b_blocks(VC1Context *v)
+static void vc1_decode_b_blocks(VC1Context *v, int mby_start, int mby_end)
 {
     MpegEncContext *s = &v->s;
 
@@ -2897,7 +3020,7 @@ static void vc1_decode_b_blocks(VC1Context *v)
     }
 
     s->first_slice_line = 1;
-    for(s->mb_y = 0; s->mb_y < s->mb_height; s->mb_y++) {
+    for(s->mb_y = mby_start; s->mb_y < mby_end; s->mb_y++) {
         s->mb_x = 0;
         ff_init_block_index(s);
         for(; s->mb_x < s->mb_width; s->mb_x++) {
@@ -2905,16 +3028,21 @@ static void vc1_decode_b_blocks(VC1Context *v)
 
             vc1_decode_b_mb(v);
             if(get_bits_count(&s->gb) > v->bits || get_bits_count(&s->gb) < 0) {
-                ff_er_add_slice(s, 0, 0, s->mb_x, s->mb_y, (AC_END|DC_END|MV_END));
+                ff_er_add_slice(s, 0, mby_start, s->mb_x, s->mb_y, (AC_END|DC_END|MV_END));
                 av_log(s->avctx, AV_LOG_ERROR, "Bits overconsumption: %i > %i at %ix%i\n", get_bits_count(&s->gb), v->bits,s->mb_x,s->mb_y);
                 return;
             }
-            if(v->s.loop_filter) vc1_loop_filter_iblk(s, v->pq);
+            if(v->s.loop_filter) vc1_loop_filter_iblk(v, v->pq);
         }
-        ff_draw_horiz_band(s, s->mb_y * 16, 16);
+        if (!v->s.loop_filter)
+            ff_draw_horiz_band(s, s->mb_y * 16, 16);
+        else if (s->mb_y)
+            ff_draw_horiz_band(s, (s->mb_y-1) * 16, 16);
         s->first_slice_line = 0;
     }
-    ff_er_add_slice(s, 0, 0, s->mb_width - 1, s->mb_height - 1, (AC_END|DC_END|MV_END));
+    if (v->s.loop_filter)
+        ff_draw_horiz_band(s, (s->mb_height-1)*16, 16);
+    ff_er_add_slice(s, 0, mby_start, s->mb_width - 1, mby_end - 1, (AC_END|DC_END|MV_END));
 }
 
 static void vc1_decode_skip_blocks(VC1Context *v)
@@ -2936,18 +3064,17 @@ static void vc1_decode_skip_blocks(VC1Context *v)
     s->pict_type = FF_P_TYPE;
 }
 
-static void vc1_decode_blocks(VC1Context *v)
+static void vc1_decode_blocks(VC1Context *v, int mby_start, int mby_end)
 {
 
     v->s.esc3_level_length = 0;
     if(v->x8_type){
         ff_intrax8_decode_picture(&v->x8, 2*v->pq+v->halfpq, v->pq*(!v->pquantizer) );
     }else{
-
         switch(v->s.pict_type) {
         case FF_I_TYPE:
             if(v->profile == PROFILE_ADVANCED)
-                vc1_decode_i_blocks_adv(v);
+                vc1_decode_i_blocks_adv(v, mby_start, mby_end);
             else
                 vc1_decode_i_blocks(v);
             break;
@@ -2955,21 +3082,131 @@ static void vc1_decode_blocks(VC1Context *v)
             if(v->p_frame_skipped)
                 vc1_decode_skip_blocks(v);
             else
-                vc1_decode_p_blocks(v);
+                vc1_decode_p_blocks(v, mby_start, mby_end);
             break;
         case FF_B_TYPE:
             if(v->bi_type){
                 if(v->profile == PROFILE_ADVANCED)
-                    vc1_decode_i_blocks_adv(v);
+                    vc1_decode_i_blocks_adv(v, mby_start, mby_end);
                 else
                     vc1_decode_i_blocks(v);
             }else
-                vc1_decode_b_blocks(v);
+                vc1_decode_b_blocks(v, mby_start, mby_end);
             break;
         }
     }
 }
 
+static inline float get_float_val(GetBitContext* gb)
+{
+    return (float)get_bits_long(gb, 30) / (1<<15) - (1<<14);
+}
+
+static void vc1_sprite_parse_transform(VC1Context *v, GetBitContext* gb, float c[7])
+{
+    c[1] = c[3] = 0.0f;
+
+    switch (get_bits(gb, 2)) {
+    case 0:
+        c[0] = 1.0f;
+        c[2] = get_float_val(gb);
+        c[4] = 1.0f;
+        break;
+    case 1:
+        c[0] = c[4] = get_float_val(gb);
+        c[2] = get_float_val(gb);
+        break;
+    case 2:
+        c[0] = get_float_val(gb);
+        c[2] = get_float_val(gb);
+        c[4] = get_float_val(gb);
+        break;
+    case 3:
+        av_log_ask_for_sample(v->s.avctx, NULL);
+        c[0] = get_float_val(gb);
+        c[1] = get_float_val(gb);
+        c[2] = get_float_val(gb);
+        c[3] = get_float_val(gb);
+        c[4] = get_float_val(gb);
+        break;
+    }
+    c[5] = get_float_val(gb);
+    if (get_bits1(gb))
+        c[6] = get_float_val(gb);
+    else
+        c[6] = 1.0f;
+}
+
+static void vc1_parse_sprites(VC1Context *v, GetBitContext* gb)
+{
+    int effect_type, effect_flag, effect_pcount1, effect_pcount2, i;
+    float effect_params1[14], effect_params2[10];
+
+    float coefs[2][7];
+    vc1_sprite_parse_transform(v, gb, coefs[0]);
+    av_log(v->s.avctx, AV_LOG_DEBUG, "S1:");
+    for (i = 0; i < 7; i++)
+        av_log(v->s.avctx, AV_LOG_DEBUG, " %.3f", coefs[0][i]);
+    av_log(v->s.avctx, AV_LOG_DEBUG, "\n");
+
+    if (v->two_sprites) {
+        vc1_sprite_parse_transform(v, gb, coefs[1]);
+        av_log(v->s.avctx, AV_LOG_DEBUG, "S2:");
+        for (i = 0; i < 7; i++)
+            av_log(v->s.avctx, AV_LOG_DEBUG, " %.3f", coefs[1][i]);
+        av_log(v->s.avctx, AV_LOG_DEBUG, "\n");
+    }
+    skip_bits(gb, 2);
+    if (effect_type = get_bits_long(gb, 30)){
+        switch (effect_pcount1 = get_bits(gb, 4)) {
+        case 2:
+            effect_params1[0] = get_float_val(gb);
+            effect_params1[1] = get_float_val(gb);
+            break;
+        case 7:
+            vc1_sprite_parse_transform(v, gb, effect_params1);
+            break;
+        case 14:
+            vc1_sprite_parse_transform(v, gb, effect_params1);
+            vc1_sprite_parse_transform(v, gb, &effect_params1[7]);
+            break;
+        default:
+            av_log_ask_for_sample(v->s.avctx, NULL);
+            return;
+        }
+        if (effect_type != 13 || effect_params1[0] != coefs[0][6]) {
+            // effect 13 is simple alpha blending and matches the opacity above
+            av_log(v->s.avctx, AV_LOG_DEBUG, "Effect: %d; params: ", effect_type);
+            for (i = 0; i < effect_pcount1; i++)
+                av_log(v->s.avctx, AV_LOG_DEBUG, " %.3f", effect_params1[i]);
+            av_log(v->s.avctx, AV_LOG_DEBUG, "\n");
+        }
+
+        effect_pcount2 = get_bits(gb, 16);
+        if (effect_pcount2 > 10) {
+            av_log(v->s.avctx, AV_LOG_ERROR, "Too many effect parameters\n");
+            return;
+        } else if (effect_pcount2) {
+            i = 0;
+            av_log(v->s.avctx, AV_LOG_DEBUG, "Effect params 2: ");
+            while (i < effect_pcount2){
+                effect_params2[i] = get_float_val(gb);
+                av_log(v->s.avctx, AV_LOG_DEBUG, " %.3f", effect_params2[i]);
+                i++;
+            }
+            av_log(v->s.avctx, AV_LOG_DEBUG, "\n");
+        }
+    }
+    if (effect_flag = get_bits1(gb))
+        av_log(v->s.avctx, AV_LOG_DEBUG, "Effect flag set\n");
+
+    if (get_bits_count(gb) >= gb->size_in_bits +
+       (v->s.avctx->codec_id == CODEC_ID_WMV3 ? 64 : 0))
+        av_log(v->s.avctx, AV_LOG_ERROR, "Buffer overrun\n");
+    if (get_bits_count(gb) < gb->size_in_bits - 8)
+        av_log(v->s.avctx, AV_LOG_WARNING, "Buffer not fully read\n");
+}
+
 /** Initialize a VC1/WMV3 decoder
  * @todo TODO: Handle VC-1 IDUs (Transport level?)
  * @todo TODO: Decypher remaining bits in extra_data
@@ -2979,6 +3216,7 @@ static av_cold int vc1_decode_init(AVCodecContext *avctx)
     VC1Context *v = avctx->priv_data;
     MpegEncContext *s = &v->s;
     GetBitContext gb;
+    int i;
 
     if (!avctx->extradata_size || !avctx->extradata) return -1;
     if (!(avctx->flags & CODEC_FLAG_GRAY))
@@ -2997,6 +3235,7 @@ static av_cold int vc1_decode_init(AVCodecContext *avctx)
     if(ff_msmpeg4_decode_init(avctx) < 0)
         return -1;
     if (vc1_init_common(v) < 0) return -1;
+    ff_vc1dsp_init(&v->vc1dsp);
 
     avctx->coded_width = avctx->width;
     avctx->coded_height = avctx->height;
@@ -3024,7 +3263,7 @@ static av_cold int vc1_decode_init(AVCodecContext *avctx)
         {
             av_log(avctx, AV_LOG_INFO, "Read %i bits in overflow\n", -count);
         }
-    } else { // VC1/WVC1
+    } else { // VC1/WVC1/WVP2
         const uint8_t *start = avctx->extradata;
         uint8_t *end = avctx->extradata + avctx->extradata_size;
         const uint8_t *next;
@@ -3068,13 +3307,34 @@ static av_cold int vc1_decode_init(AVCodecContext *avctx)
             av_log(avctx, AV_LOG_ERROR, "Incomplete extradata\n");
             return -1;
         }
+        v->res_sprite = (avctx->codec_tag == MKTAG('W','V','P','2'));
     }
+    avctx->profile = v->profile;
+    if (v->profile == PROFILE_ADVANCED)
+        avctx->level = v->level;
+
     avctx->has_b_frames= !!(avctx->max_b_frames);
     s->low_delay = !avctx->has_b_frames;
 
     s->mb_width = (avctx->coded_width+15)>>4;
     s->mb_height = (avctx->coded_height+15)>>4;
 
+    if (v->profile == PROFILE_ADVANCED || v->res_fasttx) {
+        for (i = 0; i < 64;  i++) {
+#define transpose(x) ((x>>3) | ((x&7)<<3))
+            v->zz_8x8[0][i] = transpose(wmv1_scantable[0][i]);
+            v->zz_8x8[1][i] = transpose(wmv1_scantable[1][i]);
+            v->zz_8x8[2][i] = transpose(wmv1_scantable[2][i]);
+            v->zz_8x8[3][i] = transpose(wmv1_scantable[3][i]);
+        }
+        v->left_blk_sh = 0;
+        v->top_blk_sh  = 3;
+    } else {
+        memcpy(v->zz_8x8, wmv1_scantable, 4*64);
+        v->left_blk_sh = 3;
+        v->top_blk_sh  = 0;
+    }
+
     /* Allocate mb bitplanes */
     v->mv_type_mb_plane = av_malloc(s->mb_stride * s->mb_height);
     v->direct_mb_plane = av_malloc(s->mb_stride * s->mb_height);
@@ -3083,6 +3343,12 @@ static av_cold int vc1_decode_init(AVCodecContext *avctx)
 
     v->cbp_base = av_malloc(sizeof(v->cbp_base[0]) * 2 * s->mb_stride);
     v->cbp = v->cbp_base + s->mb_stride;
+    v->ttblk_base = av_malloc(sizeof(v->ttblk_base[0]) * 2 * s->mb_stride);
+    v->ttblk = v->ttblk_base + s->mb_stride;
+    v->is_intra_base = av_malloc(sizeof(v->is_intra_base[0]) * 2 * s->mb_stride);
+    v->is_intra = v->is_intra_base + s->mb_stride;
+    v->luma_mv_base = av_malloc(sizeof(v->luma_mv_base[0]) * 2 * s->mb_stride);
+    v->luma_mv = v->luma_mv_base + s->mb_stride;
 
     /* allocate block type info in that way so it could be used with s->block_index[] */
     v->mb_type_base = av_malloc(s->b8_stride * (s->mb_height * 2 + 1) + s->mb_stride * (s->mb_height + 1) * 2);
@@ -3112,15 +3378,20 @@ static int vc1_decode_frame(AVCodecContext *avctx,
                             AVPacket *avpkt)
 {
     const uint8_t *buf = avpkt->data;
-    int buf_size = avpkt->size;
+    int buf_size = avpkt->size, n_slices = 0, i;
     VC1Context *v = avctx->priv_data;
     MpegEncContext *s = &v->s;
     AVFrame *pict = data;
     uint8_t *buf2 = NULL;
     const uint8_t *buf_start = buf;
+    struct {
+        uint8_t *buf;
+        GetBitContext gb;
+        int mby_start;
+    } *slices = NULL;
 
     /* no supplementary picture */
-    if (buf_size == 0) {
+    if (buf_size == 0 || (buf_size == 4 && AV_RB32(buf) == VC1_CODE_ENDOFSEQ)) {
         /* special case for last picture */
         if (s->low_delay==0 && s->next_picture_ptr) {
             *pict= *(AVFrame*)s->next_picture_ptr;
@@ -3172,10 +3443,20 @@ static int vc1_decode_frame(AVCodecContext *avctx,
                     init_get_bits(&s->gb, buf2, buf_size2*8);
                     vc1_decode_entry_point(avctx, v, &s->gb);
                     break;
-                case VC1_CODE_SLICE:
-                    av_log(avctx, AV_LOG_ERROR, "Sliced decoding is not implemented (yet)\n");
-                    av_free(buf2);
-                    return -1;
+                case VC1_CODE_SLICE: {
+                    int buf_size3;
+                    slices = av_realloc(slices, sizeof(*slices) * (n_slices+1));
+                    if (!slices) goto err;
+                    slices[n_slices].buf = av_mallocz(buf_size + FF_INPUT_BUFFER_PADDING_SIZE);
+                    if (!slices[n_slices].buf) goto err;
+                    buf_size3 = vc1_unescape_buffer(start + 4, size,
+                                                    slices[n_slices].buf);
+                    init_get_bits(&slices[n_slices].gb, slices[n_slices].buf,
+                                  buf_size3 << 3);
+                    slices[n_slices].mby_start = get_bits(&slices[n_slices].gb, 9);
+                    n_slices++;
+                    break;
+                }
                 }
             }
         }else if(v->interlace && ((buf[0] & 0xC0) == 0xC0)){ /* WVC1 interlaced stores both fields divided by marker */
@@ -3184,72 +3465,76 @@ static int vc1_decode_frame(AVCodecContext *avctx,
             divider = find_next_marker(buf, buf + buf_size);
             if((divider == (buf + buf_size)) || AV_RB32(divider) != VC1_CODE_FIELD){
                 av_log(avctx, AV_LOG_ERROR, "Error in WVC1 interlaced frame\n");
-                av_free(buf2);
-                return -1;
+                goto err;
             }
 
             buf_size2 = vc1_unescape_buffer(buf, divider - buf, buf2);
             // TODO
             if(!v->warn_interlaced++)
                 av_log(v->s.avctx, AV_LOG_ERROR, "Interlaced WVC1 support is not implemented\n");
-            av_free(buf2);return -1;
+            goto err;
         }else{
             buf_size2 = vc1_unescape_buffer(buf, buf_size, buf2);
         }
         init_get_bits(&s->gb, buf2, buf_size2*8);
     } else
         init_get_bits(&s->gb, buf, buf_size*8);
+
+    if (v->res_sprite) {
+        v->new_sprite = !get_bits1(&s->gb);
+        v->two_sprites = get_bits1(&s->gb);
+        if (!v->new_sprite)
+            goto end;
+    }
+
     // do parse frame header
     if(v->profile < PROFILE_ADVANCED) {
         if(vc1_parse_frame_header(v, &s->gb) == -1) {
-            av_free(buf2);
-            return -1;
+            goto err;
         }
     } else {
         if(vc1_parse_frame_header_adv(v, &s->gb) == -1) {
-            av_free(buf2);
-            return -1;
+            goto err;
         }
     }
 
-    if(s->pict_type != FF_I_TYPE && !v->res_rtm_flag){
-        av_free(buf2);
-        return -1;
+    if (v->res_sprite && s->pict_type!=FF_I_TYPE) {
+        av_log(v->s.avctx, AV_LOG_WARNING, "Sprite decoder: expected I-frame\n");
     }
 
-    // for hurry_up==5
+    // for skipping the frame
     s->current_picture.pict_type= s->pict_type;
     s->current_picture.key_frame= s->pict_type == FF_I_TYPE;
 
     /* skip B-frames if we don't have reference frames */
     if(s->last_picture_ptr==NULL && (s->pict_type==FF_B_TYPE || s->dropable)){
-        av_free(buf2);
-        return -1;//buf_size;
+        goto err;
     }
+#if FF_API_HURRY_UP
     /* skip b frames if we are in a hurry */
     if(avctx->hurry_up && s->pict_type==FF_B_TYPE) return -1;//buf_size;
+#endif
     if(   (avctx->skip_frame >= AVDISCARD_NONREF && s->pict_type==FF_B_TYPE)
        || (avctx->skip_frame >= AVDISCARD_NONKEY && s->pict_type!=FF_I_TYPE)
        ||  avctx->skip_frame >= AVDISCARD_ALL) {
-        av_free(buf2);
-        return buf_size;
+        goto end;
     }
+#if FF_API_HURRY_UP
     /* skip everything if we are in a hurry>=5 */
     if(avctx->hurry_up>=5) {
-        av_free(buf2);
-        return -1;//buf_size;
+        goto err;
     }
+#endif
 
     if(s->next_p_frame_damaged){
         if(s->pict_type==FF_B_TYPE)
-            return buf_size;
+            goto end;
         else
             s->next_p_frame_damaged=0;
     }
 
     if(MPV_frame_start(s, avctx) < 0) {
-        av_free(buf2);
-        return -1;
+        goto err;
     }
 
     s->me.qpel_put= s->dsp.put_qpel_pixels_tab;
@@ -3260,17 +3545,23 @@ static int vc1_decode_frame(AVCodecContext *avctx,
         ff_vdpau_vc1_decode_picture(s, buf_start, (buf + buf_size) - buf_start);
     else if (avctx->hwaccel) {
         if (avctx->hwaccel->start_frame(avctx, buf, buf_size) < 0)
-            return -1;
+            goto err;
         if (avctx->hwaccel->decode_slice(avctx, buf_start, (buf + buf_size) - buf_start) < 0)
-            return -1;
+            goto err;
         if (avctx->hwaccel->end_frame(avctx) < 0)
-            return -1;
+            goto err;
     } else {
         ff_er_frame_start(s);
 
         v->bits = buf_size * 8;
-        vc1_decode_blocks(v);
-//av_log(s->avctx, AV_LOG_INFO, "Consumed %i/%i bits\n", get_bits_count(&s->gb), buf_size*8);
+        for (i = 0; i <= n_slices; i++) {
+            if (i && get_bits1(&s->gb))
+                vc1_parse_frame_header_adv(v, &s->gb);
+            vc1_decode_blocks(v, i == 0 ? 0 : FFMAX(0, slices[i-1].mby_start),
+                i == n_slices ? s->mb_height : FFMIN(s->mb_height, slices[i].mby_start));
+            if (i != n_slices) s->gb = slices[i].gb;
+        }
+//av_log(s->avctx, AV_LOG_INFO, "Consumed %i/%i bits\n", get_bits_count(&s->gb), s->gb.size_in_bits);
 //  if(get_bits_count(&s->gb) > buf_size * 8)
 //      return -1;
         ff_er_frame_end(s);
@@ -3291,8 +3582,21 @@ assert(s->current_picture.pict_type == s->pict_type);
         ff_print_debug_info(s, pict);
     }
 
+end:
+    if (v->res_sprite)
+        vc1_parse_sprites(v, &s->gb);
     av_free(buf2);
+    for (i = 0; i < n_slices; i++)
+        av_free(slices[i].buf);
+    av_free(slices);
     return buf_size;
+
+err:
+    av_free(buf2);
+    for (i = 0; i < n_slices; i++)
+        av_free(slices[i].buf);
+    av_free(slices);
+    return -1;
 }
 
 
@@ -3312,12 +3616,22 @@ static av_cold int vc1_decode_end(AVCodecContext *avctx)
     av_freep(&v->over_flags_plane);
     av_freep(&v->mb_type_base);
     av_freep(&v->cbp_base);
+    av_freep(&v->ttblk_base);
+    av_freep(&v->is_intra_base); // FIXME use v->mb_type[]
+    av_freep(&v->luma_mv_base);
     ff_intrax8_common_end(&v->x8);
     return 0;
 }
 
+static const AVProfile profiles[] = {
+    { FF_PROFILE_VC1_SIMPLE,   "Simple"   },
+    { FF_PROFILE_VC1_MAIN,     "Main"     },
+    { FF_PROFILE_VC1_COMPLEX,  "Complex"  },
+    { FF_PROFILE_VC1_ADVANCED, "Advanced" },
+    { FF_PROFILE_UNKNOWN },
+};
 
-AVCodec vc1_decoder = {
+AVCodec ff_vc1_decoder = {
     "vc1",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_VC1,
@@ -3329,11 +3643,12 @@ AVCodec vc1_decoder = {
     CODEC_CAP_DR1 | CODEC_CAP_DELAY,
     NULL,
     .long_name = NULL_IF_CONFIG_SMALL("SMPTE VC-1"),
-    .pix_fmts = ff_hwaccel_pixfmt_list_420
+    .pix_fmts = ff_hwaccel_pixfmt_list_420,
+    .profiles = NULL_IF_CONFIG_SMALL(profiles)
 };
 
 #if CONFIG_WMV3_DECODER
-AVCodec wmv3_decoder = {
+AVCodec ff_wmv3_decoder = {
     "wmv3",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_WMV3,
@@ -3345,12 +3660,13 @@ AVCodec wmv3_decoder = {
     CODEC_CAP_DR1 | CODEC_CAP_DELAY,
     NULL,
     .long_name = NULL_IF_CONFIG_SMALL("Windows Media Video 9"),
-    .pix_fmts = ff_hwaccel_pixfmt_list_420
+    .pix_fmts = ff_hwaccel_pixfmt_list_420,
+    .profiles = NULL_IF_CONFIG_SMALL(profiles)
 };
 #endif
 
 #if CONFIG_WMV3_VDPAU_DECODER
-AVCodec wmv3_vdpau_decoder = {
+AVCodec ff_wmv3_vdpau_decoder = {
     "wmv3_vdpau",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_WMV3,
@@ -3362,12 +3678,13 @@ AVCodec wmv3_vdpau_decoder = {
     CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
     NULL,
     .long_name = NULL_IF_CONFIG_SMALL("Windows Media Video 9 VDPAU"),
-    .pix_fmts = (const enum PixelFormat[]){PIX_FMT_VDPAU_WMV3, PIX_FMT_NONE}
+    .pix_fmts = (const enum PixelFormat[]){PIX_FMT_VDPAU_WMV3, PIX_FMT_NONE},
+    .profiles = NULL_IF_CONFIG_SMALL(profiles)
 };
 #endif
 
 #if CONFIG_VC1_VDPAU_DECODER
-AVCodec vc1_vdpau_decoder = {
+AVCodec ff_vc1_vdpau_decoder = {
     "vc1_vdpau",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_VC1,
@@ -3379,6 +3696,7 @@ AVCodec vc1_vdpau_decoder = {
     CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
     NULL,
     .long_name = NULL_IF_CONFIG_SMALL("SMPTE VC-1 VDPAU"),
-    .pix_fmts = (const enum PixelFormat[]){PIX_FMT_VDPAU_VC1, PIX_FMT_NONE}
+    .pix_fmts = (const enum PixelFormat[]){PIX_FMT_VDPAU_VC1, PIX_FMT_NONE},
+    .profiles = NULL_IF_CONFIG_SMALL(profiles)
 };
 #endif
diff --git a/libavcodec/vc1dsp.c b/libavcodec/vc1dsp.c
index 47b69c8..3d02db7 100644
--- a/libavcodec/vc1dsp.c
+++ b/libavcodec/vc1dsp.c
@@ -2,20 +2,20 @@
  * VC-1 and WMV3 decoder - DSP functions
  * Copyright (c) 2006 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,7 +25,7 @@
  *
  */
 
-#include "dsputil.h"
+#include "vc1dsp.h"
 
 
 /** Apply overlap transform to horizontal edge
@@ -182,45 +182,46 @@ static void vc1_inv_trans_8x8_dc_c(uint8_t *dest, int linesize, DCTELEM *block)
 {
     int i;
     int dc = block[0];
-    const uint8_t *cm = ff_cropTbl + MAX_NEG_CROP;
+    const uint8_t *cm;
     dc = (3 * dc +  1) >> 1;
     dc = (3 * dc + 16) >> 5;
+    cm = ff_cropTbl + MAX_NEG_CROP + dc;
     for(i = 0; i < 8; i++){
-        dest[0] = cm[dest[0]+dc];
-        dest[1] = cm[dest[1]+dc];
-        dest[2] = cm[dest[2]+dc];
-        dest[3] = cm[dest[3]+dc];
-        dest[4] = cm[dest[4]+dc];
-        dest[5] = cm[dest[5]+dc];
-        dest[6] = cm[dest[6]+dc];
-        dest[7] = cm[dest[7]+dc];
+        dest[0] = cm[dest[0]];
+        dest[1] = cm[dest[1]];
+        dest[2] = cm[dest[2]];
+        dest[3] = cm[dest[3]];
+        dest[4] = cm[dest[4]];
+        dest[5] = cm[dest[5]];
+        dest[6] = cm[dest[6]];
+        dest[7] = cm[dest[7]];
         dest += linesize;
     }
 }
 
-static void vc1_inv_trans_8x8_c(DCTELEM block[64])
+static av_always_inline void vc1_inv_trans_8x8_c(DCTELEM block[64], int shl, int sub)
 {
     int i;
     register int t1,t2,t3,t4,t5,t6,t7,t8;
-    DCTELEM *src, *dst;
+    DCTELEM *src, *dst, temp[64];
 
     src = block;
-    dst = block;
+    dst = temp;
     for(i = 0; i < 8; i++){
-        t1 = 12 * (src[0] + src[4]) + 4;
-        t2 = 12 * (src[0] - src[4]) + 4;
-        t3 = 16 * src[2] +  6 * src[6];
-        t4 =  6 * src[2] - 16 * src[6];
+        t1 = 12 * (src[ 0] + src[32]) + 4;
+        t2 = 12 * (src[ 0] - src[32]) + 4;
+        t3 = 16 * src[16] +  6 * src[48];
+        t4 =  6 * src[16] - 16 * src[48];
 
         t5 = t1 + t3;
         t6 = t2 + t4;
         t7 = t2 - t4;
         t8 = t1 - t3;
 
-        t1 = 16 * src[1] + 15 * src[3] +  9 * src[5] +  4 * src[7];
-        t2 = 15 * src[1] -  4 * src[3] - 16 * src[5] -  9 * src[7];
-        t3 =  9 * src[1] - 16 * src[3] +  4 * src[5] + 15 * src[7];
-        t4 =  4 * src[1] -  9 * src[3] + 15 * src[5] - 16 * src[7];
+        t1 = 16 * src[ 8] + 15 * src[24] +  9 * src[40] +  4 * src[56];
+        t2 = 15 * src[ 8] -  4 * src[24] - 16 * src[40] -  9 * src[56];
+        t3 =  9 * src[ 8] - 16 * src[24] +  4 * src[40] + 15 * src[56];
+        t4 =  4 * src[ 8] -  9 * src[24] + 15 * src[40] - 16 * src[56];
 
         dst[0] = (t5 + t1) >> 3;
         dst[1] = (t6 + t2) >> 3;
@@ -231,11 +232,11 @@ static void vc1_inv_trans_8x8_c(DCTELEM block[64])
         dst[6] = (t6 - t2) >> 3;
         dst[7] = (t5 - t1) >> 3;
 
-        src += 8;
+        src += 1;
         dst += 8;
     }
 
-    src = block;
+    src = temp;
     dst = block;
     for(i = 0; i < 8; i++){
         t1 = 12 * (src[ 0] + src[32]) + 64;
@@ -253,38 +254,69 @@ static void vc1_inv_trans_8x8_c(DCTELEM block[64])
         t3 =  9 * src[ 8] - 16 * src[24] +  4 * src[40] + 15 * src[56];
         t4 =  4 * src[ 8] -  9 * src[24] + 15 * src[40] - 16 * src[56];
 
-        dst[ 0] = (t5 + t1) >> 7;
-        dst[ 8] = (t6 + t2) >> 7;
-        dst[16] = (t7 + t3) >> 7;
-        dst[24] = (t8 + t4) >> 7;
-        dst[32] = (t8 - t4 + 1) >> 7;
-        dst[40] = (t7 - t3 + 1) >> 7;
-        dst[48] = (t6 - t2 + 1) >> 7;
-        dst[56] = (t5 - t1 + 1) >> 7;
+        dst[ 0] = (((t5 + t1    ) >> 7) - sub) << shl;
+        dst[ 8] = (((t6 + t2    ) >> 7) - sub) << shl;
+        dst[16] = (((t7 + t3    ) >> 7) - sub) << shl;
+        dst[24] = (((t8 + t4    ) >> 7) - sub) << shl;
+        dst[32] = (((t8 - t4 + 1) >> 7) - sub) << shl;
+        dst[40] = (((t7 - t3 + 1) >> 7) - sub) << shl;
+        dst[48] = (((t6 - t2 + 1) >> 7) - sub) << shl;
+        dst[56] = (((t5 - t1 + 1) >> 7) - sub) << shl;
 
         src++;
         dst++;
     }
 }
 
+static void vc1_inv_trans_8x8_add_c(uint8_t *dest, int linesize, DCTELEM *block)
+{
+    vc1_inv_trans_8x8_c(block, 0, 0);
+    ff_add_pixels_clamped_c(block, dest, linesize);
+}
+
+static void vc1_inv_trans_8x8_put_signed_c(uint8_t *dest, int linesize, DCTELEM *block)
+{
+    vc1_inv_trans_8x8_c(block, 0, 0);
+    ff_put_signed_pixels_clamped_c(block, dest, linesize);
+}
+
+static void vc1_inv_trans_8x8_put_signed_rangered_c(uint8_t *dest, int linesize, DCTELEM *block)
+{
+    vc1_inv_trans_8x8_c(block, 1, 0);
+    ff_put_signed_pixels_clamped_c(block, dest, linesize);
+}
+
+static void vc1_inv_trans_8x8_put_c(uint8_t *dest, int linesize, DCTELEM *block)
+{
+    vc1_inv_trans_8x8_c(block, 0, 0);
+    ff_put_pixels_clamped_c(block, dest, linesize);
+}
+
+static void vc1_inv_trans_8x8_put_rangered_c(uint8_t *dest, int linesize, DCTELEM *block)
+{
+    vc1_inv_trans_8x8_c(block, 1, 64);
+    ff_put_pixels_clamped_c(block, dest, linesize);
+}
+
 /** Do inverse transform on 8x4 part of block
 */
 static void vc1_inv_trans_8x4_dc_c(uint8_t *dest, int linesize, DCTELEM *block)
 {
     int i;
     int dc = block[0];
-    const uint8_t *cm = ff_cropTbl + MAX_NEG_CROP;
+    const uint8_t *cm;
     dc = ( 3 * dc +  1) >> 1;
     dc = (17 * dc + 64) >> 7;
+    cm = ff_cropTbl + MAX_NEG_CROP + dc;
     for(i = 0; i < 4; i++){
-        dest[0] = cm[dest[0]+dc];
-        dest[1] = cm[dest[1]+dc];
-        dest[2] = cm[dest[2]+dc];
-        dest[3] = cm[dest[3]+dc];
-        dest[4] = cm[dest[4]+dc];
-        dest[5] = cm[dest[5]+dc];
-        dest[6] = cm[dest[6]+dc];
-        dest[7] = cm[dest[7]+dc];
+        dest[0] = cm[dest[0]];
+        dest[1] = cm[dest[1]];
+        dest[2] = cm[dest[2]];
+        dest[3] = cm[dest[3]];
+        dest[4] = cm[dest[4]];
+        dest[5] = cm[dest[5]];
+        dest[6] = cm[dest[6]];
+        dest[7] = cm[dest[7]];
         dest += linesize;
     }
 }
@@ -350,14 +382,15 @@ static void vc1_inv_trans_4x8_dc_c(uint8_t *dest, int linesize, DCTELEM *block)
 {
     int i;
     int dc = block[0];
-    const uint8_t *cm = ff_cropTbl + MAX_NEG_CROP;
+    const uint8_t *cm;
     dc = (17 * dc +  4) >> 3;
     dc = (12 * dc + 64) >> 7;
+    cm = ff_cropTbl + MAX_NEG_CROP + dc;
     for(i = 0; i < 8; i++){
-        dest[0] = cm[dest[0]+dc];
-        dest[1] = cm[dest[1]+dc];
-        dest[2] = cm[dest[2]+dc];
-        dest[3] = cm[dest[3]+dc];
+        dest[0] = cm[dest[0]];
+        dest[1] = cm[dest[1]];
+        dest[2] = cm[dest[2]];
+        dest[3] = cm[dest[3]];
         dest += linesize;
     }
 }
@@ -423,14 +456,15 @@ static void vc1_inv_trans_4x4_dc_c(uint8_t *dest, int linesize, DCTELEM *block)
 {
     int i;
     int dc = block[0];
-    const uint8_t *cm = ff_cropTbl + MAX_NEG_CROP;
+    const uint8_t *cm;
     dc = (17 * dc +  4) >> 3;
     dc = (17 * dc + 64) >> 7;
+    cm = ff_cropTbl + MAX_NEG_CROP + dc;
     for(i = 0; i < 4; i++){
-        dest[0] = cm[dest[0]+dc];
-        dest[1] = cm[dest[1]+dc];
-        dest[2] = cm[dest[2]+dc];
-        dest[3] = cm[dest[3]+dc];
+        dest[0] = cm[dest[0]];
+        dest[1] = cm[dest[1]];
+        dest[2] = cm[dest[2]];
+        dest[3] = cm[dest[3]];
         dest += linesize;
     }
 }
@@ -608,8 +642,61 @@ PUT_VC1_MSPEL(1, 3)
 PUT_VC1_MSPEL(2, 3)
 PUT_VC1_MSPEL(3, 3)
 
-av_cold void ff_vc1dsp_init(DSPContext* dsp, AVCodecContext *avctx) {
-    dsp->vc1_inv_trans_8x8 = vc1_inv_trans_8x8_c;
+static void put_no_rnd_vc1_chroma_mc8_c(uint8_t *dst/*align 8*/, uint8_t *src/*align 1*/, int stride, int h, int x, int y){
+    const int A=(8-x)*(8-y);
+    const int B=(  x)*(8-y);
+    const int C=(8-x)*(  y);
+    const int D=(  x)*(  y);
+    int i;
+
+    assert(x<8 && y<8 && x>=0 && y>=0);
+
+    for(i=0; i<h; i++)
+    {
+        dst[0] = (A*src[0] + B*src[1] + C*src[stride+0] + D*src[stride+1] + 32 - 4) >> 6;
+        dst[1] = (A*src[1] + B*src[2] + C*src[stride+1] + D*src[stride+2] + 32 - 4) >> 6;
+        dst[2] = (A*src[2] + B*src[3] + C*src[stride+2] + D*src[stride+3] + 32 - 4) >> 6;
+        dst[3] = (A*src[3] + B*src[4] + C*src[stride+3] + D*src[stride+4] + 32 - 4) >> 6;
+        dst[4] = (A*src[4] + B*src[5] + C*src[stride+4] + D*src[stride+5] + 32 - 4) >> 6;
+        dst[5] = (A*src[5] + B*src[6] + C*src[stride+5] + D*src[stride+6] + 32 - 4) >> 6;
+        dst[6] = (A*src[6] + B*src[7] + C*src[stride+6] + D*src[stride+7] + 32 - 4) >> 6;
+        dst[7] = (A*src[7] + B*src[8] + C*src[stride+7] + D*src[stride+8] + 32 - 4) >> 6;
+        dst+= stride;
+        src+= stride;
+    }
+}
+
+#define avg2(a,b) ((a+b+1)>>1)
+static void avg_no_rnd_vc1_chroma_mc8_c(uint8_t *dst/*align 8*/, uint8_t *src/*align 1*/, int stride, int h, int x, int y){
+    const int A=(8-x)*(8-y);
+    const int B=(  x)*(8-y);
+    const int C=(8-x)*(  y);
+    const int D=(  x)*(  y);
+    int i;
+
+    assert(x<8 && y<8 && x>=0 && y>=0);
+
+    for(i=0; i<h; i++)
+    {
+        dst[0] = avg2(dst[0], ((A*src[0] + B*src[1] + C*src[stride+0] + D*src[stride+1] + 32 - 4) >> 6));
+        dst[1] = avg2(dst[1], ((A*src[1] + B*src[2] + C*src[stride+1] + D*src[stride+2] + 32 - 4) >> 6));
+        dst[2] = avg2(dst[2], ((A*src[2] + B*src[3] + C*src[stride+2] + D*src[stride+3] + 32 - 4) >> 6));
+        dst[3] = avg2(dst[3], ((A*src[3] + B*src[4] + C*src[stride+3] + D*src[stride+4] + 32 - 4) >> 6));
+        dst[4] = avg2(dst[4], ((A*src[4] + B*src[5] + C*src[stride+4] + D*src[stride+5] + 32 - 4) >> 6));
+        dst[5] = avg2(dst[5], ((A*src[5] + B*src[6] + C*src[stride+5] + D*src[stride+6] + 32 - 4) >> 6));
+        dst[6] = avg2(dst[6], ((A*src[6] + B*src[7] + C*src[stride+6] + D*src[stride+7] + 32 - 4) >> 6));
+        dst[7] = avg2(dst[7], ((A*src[7] + B*src[8] + C*src[stride+7] + D*src[stride+8] + 32 - 4) >> 6));
+        dst+= stride;
+        src+= stride;
+    }
+}
+
+av_cold void ff_vc1dsp_init(VC1DSPContext* dsp) {
+    dsp->vc1_inv_trans_8x8_add = vc1_inv_trans_8x8_add_c;
+    dsp->vc1_inv_trans_8x8_put_signed[0] = vc1_inv_trans_8x8_put_signed_c;
+    dsp->vc1_inv_trans_8x8_put_signed[1] = vc1_inv_trans_8x8_put_signed_rangered_c;
+    dsp->vc1_inv_trans_8x8_put[0] = vc1_inv_trans_8x8_put_c;
+    dsp->vc1_inv_trans_8x8_put[1] = vc1_inv_trans_8x8_put_rangered_c;
     dsp->vc1_inv_trans_4x8 = vc1_inv_trans_4x8_c;
     dsp->vc1_inv_trans_8x4 = vc1_inv_trans_8x4_c;
     dsp->vc1_inv_trans_4x4 = vc1_inv_trans_4x4_c;
@@ -626,7 +713,7 @@ av_cold void ff_vc1dsp_init(DSPContext* dsp, AVCodecContext *avctx) {
     dsp->vc1_v_loop_filter16 = vc1_v_loop_filter16_c;
     dsp->vc1_h_loop_filter16 = vc1_h_loop_filter16_c;
 
-    dsp->put_vc1_mspel_pixels_tab[ 0] = ff_put_vc1_mspel_mc00_c;
+    dsp->put_vc1_mspel_pixels_tab[ 0] = ff_put_pixels8x8_c;
     dsp->put_vc1_mspel_pixels_tab[ 1] = put_vc1_mspel_mc10_c;
     dsp->put_vc1_mspel_pixels_tab[ 2] = put_vc1_mspel_mc20_c;
     dsp->put_vc1_mspel_pixels_tab[ 3] = put_vc1_mspel_mc30_c;
@@ -643,7 +730,7 @@ av_cold void ff_vc1dsp_init(DSPContext* dsp, AVCodecContext *avctx) {
     dsp->put_vc1_mspel_pixels_tab[14] = put_vc1_mspel_mc23_c;
     dsp->put_vc1_mspel_pixels_tab[15] = put_vc1_mspel_mc33_c;
 
-    dsp->avg_vc1_mspel_pixels_tab[ 0] = ff_avg_vc1_mspel_mc00_c;
+    dsp->avg_vc1_mspel_pixels_tab[ 0] = ff_avg_pixels8x8_c;
     dsp->avg_vc1_mspel_pixels_tab[ 1] = avg_vc1_mspel_mc10_c;
     dsp->avg_vc1_mspel_pixels_tab[ 2] = avg_vc1_mspel_mc20_c;
     dsp->avg_vc1_mspel_pixels_tab[ 3] = avg_vc1_mspel_mc30_c;
@@ -659,4 +746,12 @@ av_cold void ff_vc1dsp_init(DSPContext* dsp, AVCodecContext *avctx) {
     dsp->avg_vc1_mspel_pixels_tab[13] = avg_vc1_mspel_mc13_c;
     dsp->avg_vc1_mspel_pixels_tab[14] = avg_vc1_mspel_mc23_c;
     dsp->avg_vc1_mspel_pixels_tab[15] = avg_vc1_mspel_mc33_c;
+
+    dsp->put_no_rnd_vc1_chroma_pixels_tab[0]= put_no_rnd_vc1_chroma_mc8_c;
+    dsp->avg_no_rnd_vc1_chroma_pixels_tab[0]= avg_no_rnd_vc1_chroma_mc8_c;
+
+    if (HAVE_ALTIVEC)
+        ff_vc1dsp_init_altivec(dsp);
+    if (HAVE_MMX)
+        ff_vc1dsp_init_mmx(dsp);
 }
diff --git a/libavcodec/vc1dsp.h b/libavcodec/vc1dsp.h
new file mode 100644
index 0000000..32bb25b
--- /dev/null
+++ b/libavcodec/vc1dsp.h
@@ -0,0 +1,71 @@
+/*
+ * VC-1 and WMV3 decoder - DSP functions
+ * Copyright (c) 2006 Konstantin Shishkov
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * VC-1 and WMV3 decoder
+ *
+ */
+
+#ifndef AVCODEC_VC1DSP_H
+#define AVCODEC_VC1DSP_H
+
+#include "dsputil.h"
+
+typedef void (*vc1_idct_func)(uint8_t *dest, int line_size, DCTELEM *block);
+
+typedef struct VC1DSPContext {
+    /* vc1 functions */
+    vc1_idct_func vc1_inv_trans_8x8_add;
+    vc1_idct_func vc1_inv_trans_8x8_put_signed[2];
+    vc1_idct_func vc1_inv_trans_8x8_put[2];
+    void (*vc1_inv_trans_8x4)(uint8_t *dest, int line_size, DCTELEM *block);
+    void (*vc1_inv_trans_4x8)(uint8_t *dest, int line_size, DCTELEM *block);
+    void (*vc1_inv_trans_4x4)(uint8_t *dest, int line_size, DCTELEM *block);
+    void (*vc1_inv_trans_8x8_dc)(uint8_t *dest, int line_size, DCTELEM *block);
+    void (*vc1_inv_trans_8x4_dc)(uint8_t *dest, int line_size, DCTELEM *block);
+    void (*vc1_inv_trans_4x8_dc)(uint8_t *dest, int line_size, DCTELEM *block);
+    void (*vc1_inv_trans_4x4_dc)(uint8_t *dest, int line_size, DCTELEM *block);
+    void (*vc1_v_overlap)(uint8_t* src, int stride);
+    void (*vc1_h_overlap)(uint8_t* src, int stride);
+    void (*vc1_v_loop_filter4)(uint8_t *src, int stride, int pq);
+    void (*vc1_h_loop_filter4)(uint8_t *src, int stride, int pq);
+    void (*vc1_v_loop_filter8)(uint8_t *src, int stride, int pq);
+    void (*vc1_h_loop_filter8)(uint8_t *src, int stride, int pq);
+    void (*vc1_v_loop_filter16)(uint8_t *src, int stride, int pq);
+    void (*vc1_h_loop_filter16)(uint8_t *src, int stride, int pq);
+
+    /* put 8x8 block with bicubic interpolation and quarterpel precision
+     * last argument is actually round value instead of height
+     */
+    op_pixels_func put_vc1_mspel_pixels_tab[16];
+    op_pixels_func avg_vc1_mspel_pixels_tab[16];
+
+    /* This is really one func used in VC-1 decoding */
+    h264_chroma_mc_func put_no_rnd_vc1_chroma_pixels_tab[3];
+    h264_chroma_mc_func avg_no_rnd_vc1_chroma_pixels_tab[3];
+} VC1DSPContext;
+
+void ff_vc1dsp_init(VC1DSPContext* c);
+void ff_vc1dsp_init_altivec(VC1DSPContext* c);
+void ff_vc1dsp_init_mmx(VC1DSPContext* dsp);
+
+#endif /* AVCODEC_VC1DSP_H */
diff --git a/libavcodec/vcr1.c b/libavcodec/vcr1.c
index 31da94f..93942e1 100644
--- a/libavcodec/vcr1.c
+++ b/libavcodec/vcr1.c
@@ -2,20 +2,20 @@
  * ATI VCR1 codec
  * Copyright (c) 2003 Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -176,7 +176,7 @@ static av_cold int encode_init(AVCodecContext *avctx){
 }
 #endif
 
-AVCodec vcr1_decoder = {
+AVCodec ff_vcr1_decoder = {
     "vcr1",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_VCR1,
@@ -190,7 +190,7 @@ AVCodec vcr1_decoder = {
 };
 
 #if CONFIG_VCR1_ENCODER
-AVCodec vcr1_encoder = {
+AVCodec ff_vcr1_encoder = {
     "vcr1",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_VCR1,
diff --git a/libavcodec/vdpau.c b/libavcodec/vdpau.c
index bd721e8..1a193c1 100644
--- a/libavcodec/vdpau.c
+++ b/libavcodec/vdpau.c
@@ -4,20 +4,20 @@
  *
  * Copyright (c) 2008 NVIDIA
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/vdpau.h b/libavcodec/vdpau.h
index a8fa4d3..d06ba63 100644
--- a/libavcodec/vdpau.h
+++ b/libavcodec/vdpau.h
@@ -4,20 +4,20 @@
  *
  * Copyright (C) 2008 NVIDIA
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -31,14 +31,13 @@
  * - VDPAU decoding
  * - VDPAU presentation
  *
- * The VDPAU decoding module parses all headers using FFmpeg
+ * The VDPAU decoding module parses all headers using Libav
  * parsing mechanisms and uses VDPAU for the actual decoding.
  *
  * As per the current implementation, the actual decoding
  * and rendering (API calls) are done as part of the VDPAU
  * presentation (vo_vdpau.c) module.
  *
- * @{
  * \defgroup  VDPAU_Decoding VDPAU Decoding
  * \ingroup Decoder
  * @{
@@ -57,11 +56,11 @@
 #define FF_VDPAU_STATE_USED_FOR_REFERENCE 2
 
 /**
- * \brief This structure is used as a callback between the FFmpeg
+ * \brief This structure is used as a callback between the Libav
  * decoder (vd_) and presentation (vo_) module.
  * This is used for defining a video frame containing surface,
  * picture parameter, bitstream information etc which are passed
- * between the FFmpeg decoder and its clients.
+ * between the Libav decoder and its clients.
  */
 struct vdpau_render_state {
     VdpVideoSurface surface; ///< Used as rendered surface, never changed.
diff --git a/libavcodec/vdpau_internal.h b/libavcodec/vdpau_internal.h
index 0a8d0b6..673fd33 100644
--- a/libavcodec/vdpau_internal.h
+++ b/libavcodec/vdpau_internal.h
@@ -4,20 +4,20 @@
  *
  * Copyright (C) 2008 NVIDIA
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/version.h b/libavcodec/version.h
new file mode 100644
index 0000000..7e53474
--- /dev/null
+++ b/libavcodec/version.h
@@ -0,0 +1,90 @@
+/*
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_VERSION_H
+#define AVCODEC_VERSION_H
+
+#define LIBAVCODEC_VERSION_MAJOR 53
+#define LIBAVCODEC_VERSION_MINOR  0
+#define LIBAVCODEC_VERSION_MICRO  0
+
+#define LIBAVCODEC_VERSION_INT  AV_VERSION_INT(LIBAVCODEC_VERSION_MAJOR, \
+                                               LIBAVCODEC_VERSION_MINOR, \
+                                               LIBAVCODEC_VERSION_MICRO)
+#define LIBAVCODEC_VERSION      AV_VERSION(LIBAVCODEC_VERSION_MAJOR,    \
+                                           LIBAVCODEC_VERSION_MINOR,    \
+                                           LIBAVCODEC_VERSION_MICRO)
+#define LIBAVCODEC_BUILD        LIBAVCODEC_VERSION_INT
+
+#define LIBAVCODEC_IDENT        "Lavc" AV_STRINGIFY(LIBAVCODEC_VERSION)
+
+/**
+ * Those FF_API_* defines are not part of public API.
+ * They may change, break or disappear at any time.
+ */
+#ifndef FF_API_PALETTE_CONTROL
+#define FF_API_PALETTE_CONTROL  (LIBAVCODEC_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_MM_FLAGS
+#define FF_API_MM_FLAGS         (LIBAVCODEC_VERSION_MAJOR < 53)
+#endif
+#ifndef FF_API_OPT_SHOW
+#define FF_API_OPT_SHOW         (LIBAVCODEC_VERSION_MAJOR < 53)
+#endif
+#ifndef FF_API_AUDIO_OLD
+#define FF_API_AUDIO_OLD        (LIBAVCODEC_VERSION_MAJOR < 53)
+#endif
+#ifndef FF_API_VIDEO_OLD
+#define FF_API_VIDEO_OLD        (LIBAVCODEC_VERSION_MAJOR < 53)
+#endif
+#ifndef FF_API_SUBTITLE_OLD
+#define FF_API_SUBTITLE_OLD     (LIBAVCODEC_VERSION_MAJOR < 53)
+#endif
+#ifndef FF_API_USE_LPC
+#define FF_API_USE_LPC          (LIBAVCODEC_VERSION_MAJOR < 53)
+#endif
+#ifndef FF_API_SET_STRING_OLD
+#define FF_API_SET_STRING_OLD   (LIBAVCODEC_VERSION_MAJOR < 53)
+#endif
+#ifndef FF_API_INOFFICIAL
+#define FF_API_INOFFICIAL       (LIBAVCODEC_VERSION_MAJOR < 53)
+#endif
+#ifndef FF_API_OLD_SAMPLE_FMT
+#define FF_API_OLD_SAMPLE_FMT   (LIBAVCODEC_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_OLD_AUDIOCONVERT
+#define FF_API_OLD_AUDIOCONVERT (LIBAVCODEC_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_HURRY_UP
+#define FF_API_HURRY_UP         (LIBAVCODEC_VERSION_MAJOR < 53)
+#endif
+#ifndef FF_API_RATE_EMU
+#define FF_API_RATE_EMU         (LIBAVCODEC_VERSION_MAJOR < 53)
+#endif
+#ifndef FF_API_MB_Q
+#define FF_API_MB_Q             (LIBAVCODEC_VERSION_MAJOR < 53)
+#endif
+#ifndef FF_API_ANTIALIAS_ALGO
+#define FF_API_ANTIALIAS_ALGO   (LIBAVCODEC_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_REQUEST_CHANNELS
+#define FF_API_REQUEST_CHANNELS (LIBAVCODEC_VERSION_MAJOR < 54)
+#endif
+
+#endif /* AVCODEC_VERSION_H */
diff --git a/libavcodec/vmdav.c b/libavcodec/vmdav.c
index 4914d2a..710c202 100644
--- a/libavcodec/vmdav.c
+++ b/libavcodec/vmdav.c
@@ -2,20 +2,20 @@
  * Sierra VMD Audio & Video Decoders
  * Copyright (C) 2004 the ffmpeg project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -414,11 +414,13 @@ static av_cold int vmdvideo_decode_end(AVCodecContext *avctx)
  * Audio Decoder
  */
 
+#define BLOCK_TYPE_AUDIO    1
+#define BLOCK_TYPE_INITIAL  2
+#define BLOCK_TYPE_SILENCE  3
+
 typedef struct VmdAudioContext {
     AVCodecContext *avctx;
-    int channels;
-    int bits;
-    int block_align;
+    int out_bps;
     int predictors[2];
 } VmdAudioContext;
 
@@ -443,13 +445,16 @@ static av_cold int vmdaudio_decode_init(AVCodecContext *avctx)
     VmdAudioContext *s = avctx->priv_data;
 
     s->avctx = avctx;
-    s->channels = avctx->channels;
-    s->bits = avctx->bits_per_coded_sample;
-    s->block_align = avctx->block_align;
-    avctx->sample_fmt = SAMPLE_FMT_S16;
+    if (avctx->bits_per_coded_sample == 16)
+        avctx->sample_fmt = AV_SAMPLE_FMT_S16;
+    else
+        avctx->sample_fmt = AV_SAMPLE_FMT_U8;
+    s->out_bps = av_get_bits_per_sample_fmt(avctx->sample_fmt) >> 3;
 
-    av_log(s->avctx, AV_LOG_DEBUG, "%d channels, %d bits/sample, block align = %d, sample rate = %d\n",
-            s->channels, s->bits, s->block_align, avctx->sample_rate);
+    av_log(avctx, AV_LOG_DEBUG, "%d channels, %d bits/sample, "
+           "block align = %d, sample rate = %d\n",
+           avctx->channels, avctx->bits_per_coded_sample, avctx->block_align,
+           avctx->sample_rate);
 
     return 0;
 }
@@ -473,49 +478,22 @@ static void vmdaudio_decode_audio(VmdAudioContext *s, unsigned char *data,
 }
 
 static int vmdaudio_loadsound(VmdAudioContext *s, unsigned char *data,
-    const uint8_t *buf, int silence, int data_size)
+    const uint8_t *buf, int silent_chunks, int data_size)
 {
-    int bytes_decoded = 0;
-    int i;
+    int silent_size = s->avctx->block_align * silent_chunks * s->out_bps;
 
-//    if (silence)
-//        av_log(s->avctx, AV_LOG_INFO, "silent block!\n");
-    if (s->channels == 2) {
-
-        /* stereo handling */
-        if (silence) {
-            memset(data, 0, data_size * 2);
-        } else {
-            if (s->bits == 16)
-                vmdaudio_decode_audio(s, data, buf, data_size, 1);
-            else {
-                /* copy the data but convert it to signed */
-                for (i = 0; i < data_size; i++){
-                    *data++ = buf[i] + 0x80;
-                    *data++ = buf[i] + 0x80;
-                }
-            }
-        }
-    } else {
-        bytes_decoded = data_size * 2;
-
-        /* mono handling */
-        if (silence) {
-            memset(data, 0, data_size * 2);
-        } else {
-            if (s->bits == 16) {
-                vmdaudio_decode_audio(s, data, buf, data_size, 0);
-            } else {
-                /* copy the data but convert it to signed */
-                for (i = 0; i < data_size; i++){
-                    *data++ = buf[i] + 0x80;
-                    *data++ = buf[i] + 0x80;
-                }
-            }
-        }
+    if (silent_chunks) {
+        memset(data, s->out_bps == 2 ? 0x00 : 0x80, silent_size);
+        data += silent_size;
+    }
+    if (s->avctx->bits_per_coded_sample == 16)
+        vmdaudio_decode_audio(s, data, buf, data_size, s->avctx->channels == 2);
+    else {
+        /* just copy the data */
+        memcpy(data, buf, data_size);
     }
 
-    return data_size * 2;
+    return silent_size + data_size * s->out_bps;
 }
 
 static int vmdaudio_decode_frame(AVCodecContext *avctx,
@@ -525,39 +503,41 @@ static int vmdaudio_decode_frame(AVCodecContext *avctx,
     const uint8_t *buf = avpkt->data;
     int buf_size = avpkt->size;
     VmdAudioContext *s = avctx->priv_data;
+    int block_type, silent_chunks;
     unsigned char *output_samples = (unsigned char *)data;
 
-    /* point to the start of the encoded data */
-    const unsigned char *p = buf + 16;
-
-    if (buf_size < 16)
+    if (buf_size < 16) {
+        av_log(avctx, AV_LOG_WARNING, "skipping small junk packet\n");
+        *data_size = 0;
         return buf_size;
+    }
 
-    if (buf[6] == 1) {
-        /* the chunk contains audio */
-        *data_size = vmdaudio_loadsound(s, output_samples, p, 0, buf_size - 16);
-    } else if (buf[6] == 2) {
-        /* initial chunk, may contain audio and silence */
-        uint32_t flags = AV_RB32(p);
-        int raw_block_size = s->block_align * s->bits / 8;
-        int silent_chunks;
-        if(flags == 0xFFFFFFFF)
-            silent_chunks = 32;
-        else
-            silent_chunks = av_log2(flags + 1);
-        if(*data_size < (s->block_align*silent_chunks + buf_size - 20) * 2)
-            return -1;
-        *data_size = 0;
-        memset(output_samples, 0, raw_block_size * silent_chunks);
-        output_samples += raw_block_size * silent_chunks;
-        *data_size = raw_block_size * silent_chunks;
-        *data_size += vmdaudio_loadsound(s, output_samples, p + 4, 0, buf_size - 20);
-    } else if (buf[6] == 3) {
-        /* silent chunk */
-        *data_size = vmdaudio_loadsound(s, output_samples, p, 1, 0);
+    block_type = buf[6];
+    if (block_type < BLOCK_TYPE_AUDIO || block_type > BLOCK_TYPE_SILENCE) {
+        av_log(avctx, AV_LOG_ERROR, "unknown block type: %d\n", block_type);
+        return AVERROR(EINVAL);
+    }
+    buf      += 16;
+    buf_size -= 16;
+
+    silent_chunks = 0;
+    if (block_type == BLOCK_TYPE_INITIAL) {
+        uint32_t flags = AV_RB32(buf);
+        silent_chunks  = av_popcount(flags);
+        buf      += 4;
+        buf_size -= 4;
+    } else if (block_type == BLOCK_TYPE_SILENCE) {
+        silent_chunks = 1;
+        buf_size = 0; // should already be zero but set it just to be sure
     }
 
-    return buf_size;
+    /* ensure output buffer is large enough */
+    if (*data_size < (avctx->block_align*silent_chunks + buf_size) * s->out_bps)
+        return -1;
+
+    *data_size = vmdaudio_loadsound(s, output_samples, buf, silent_chunks, buf_size);
+
+    return avpkt->size;
 }
 
 
@@ -565,7 +545,7 @@ static int vmdaudio_decode_frame(AVCodecContext *avctx,
  * Public Data Structures
  */
 
-AVCodec vmdvideo_decoder = {
+AVCodec ff_vmdvideo_decoder = {
     "vmdvideo",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_VMDVIDEO,
@@ -578,7 +558,7 @@ AVCodec vmdvideo_decoder = {
     .long_name = NULL_IF_CONFIG_SMALL("Sierra VMD video"),
 };
 
-AVCodec vmdaudio_decoder = {
+AVCodec ff_vmdaudio_decoder = {
     "vmdaudio",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_VMDAUDIO,
diff --git a/libavcodec/vmnc.c b/libavcodec/vmnc.c
index 49aaeb2..5618184 100644
--- a/libavcodec/vmnc.c
+++ b/libavcodec/vmnc.c
@@ -2,20 +2,20 @@
  * VMware Screen Codec (VMnc) decoder
  * Copyright (c) 2006 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -508,7 +508,7 @@ static av_cold int decode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec vmnc_decoder = {
+AVCodec ff_vmnc_decoder = {
     "vmnc",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_VMNC,
diff --git a/libavcodec/vorbis.c b/libavcodec/vorbis.c
index 47388d8..d576a20 100644
--- a/libavcodec/vorbis.c
+++ b/libavcodec/vorbis.c
@@ -3,20 +3,20 @@
  * Common code for Vorbis I encoder and decoder
  * @author Denes Balatoni  ( dbalatoni programozo hu )
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/vorbis.h b/libavcodec/vorbis.h
index ce9bead..e475455 100644
--- a/libavcodec/vorbis.h
+++ b/libavcodec/vorbis.h
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2006 Oded Shimon <ods15 at ods15.dyndns.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -26,6 +26,7 @@
 extern const float ff_vorbis_floor1_inverse_db_table[256];
 extern const float * const ff_vorbis_vwin[8];
 extern const uint8_t ff_vorbis_channel_layout_offsets[8][8];
+extern const uint8_t ff_vorbis_encoding_channel_layout_offsets[8][8];
 extern const int64_t ff_vorbis_channel_layouts[9];
 
 typedef struct {
diff --git a/libavcodec/vorbis_data.c b/libavcodec/vorbis_data.c
index 9bc7979..4e1fe00 100644
--- a/libavcodec/vorbis_data.c
+++ b/libavcodec/vorbis_data.c
@@ -1,46 +1,58 @@
 /*
  * copyright (c) 2005 Denes Balatoni ( dbalatoni programozo hu )
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "dsputil.h"
 #include "vorbis.h"
+#include "libavutil/audioconvert.h"
 
 const uint8_t ff_vorbis_channel_layout_offsets[8][8] = {
-    { 0, },
-    { 0, 1, },
-    { 0, 2, 1, },
-    { 0, 1, 2, 3, },
-    { 0, 2, 1, 3, 4, },
-    { 0, 2, 1, 5, 3, 4, },
-    { 0, 2, 1, 6, 5, 3, 4, },
-    { 0, 2, 1, 7, 5, 6, 3, 4},
+    { 0 },
+    { 0, 1 },
+    { 0, 2, 1 },
+    { 0, 1, 2, 3 },
+    { 0, 2, 1, 3, 4 },
+    { 0, 2, 1, 5, 3, 4 },
+    { 0, 2, 1, 6, 5, 3, 4 },
+    { 0, 2, 1, 7, 5, 6, 3, 4 },
+};
+
+const uint8_t ff_vorbis_encoding_channel_layout_offsets[8][8] = {
+    { 0 },
+    { 0, 1 },
+    { 0, 2, 1 },
+    { 0, 1, 2, 3 },
+    { 0, 2, 1, 3, 4 },
+    { 0, 2, 1, 4, 5, 3 },
+    { 0, 2, 1, 5, 6, 4, 3 },
+    { 0, 2, 1, 6, 7, 4, 5, 3 },
 };
 
 const int64_t ff_vorbis_channel_layouts[9] = {
-    CH_LAYOUT_MONO,
-    CH_LAYOUT_STEREO,
-    CH_LAYOUT_SURROUND,
-    CH_LAYOUT_QUAD,
-    CH_LAYOUT_5POINT0_BACK,
-    CH_LAYOUT_5POINT1_BACK,
-    CH_LAYOUT_5POINT1|CH_BACK_CENTER,
-    CH_LAYOUT_7POINT1,
+    AV_CH_LAYOUT_MONO,
+    AV_CH_LAYOUT_STEREO,
+    AV_CH_LAYOUT_SURROUND,
+    AV_CH_LAYOUT_QUAD,
+    AV_CH_LAYOUT_5POINT0_BACK,
+    AV_CH_LAYOUT_5POINT1_BACK,
+    AV_CH_LAYOUT_5POINT1|AV_CH_BACK_CENTER,
+    AV_CH_LAYOUT_7POINT1,
     0
 };
 
diff --git a/libavcodec/vorbis_dec.c b/libavcodec/vorbis_dec.c
index 8c56400..5fa7be1 100644
--- a/libavcodec/vorbis_dec.c
+++ b/libavcodec/vorbis_dec.c
@@ -3,20 +3,20 @@
  * Vorbis I decoder
  * @author Denes Balatoni  ( dbalatoni programozo hu )
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -31,6 +31,7 @@
 #include "get_bits.h"
 #include "dsputil.h"
 #include "fft.h"
+#include "fmtconvert.h"
 
 #include "vorbis.h"
 #include "xiph.h"
@@ -61,8 +62,8 @@ typedef struct vorbis_floor0_s vorbis_floor0;
 typedef struct vorbis_floor1_s vorbis_floor1;
 struct vorbis_context_s;
 typedef
-uint_fast8_t (* vorbis_floor_decode_func)
-             (struct vorbis_context_s *, vorbis_floor_data *, float *);
+int (* vorbis_floor_decode_func)
+    (struct vorbis_context_s *, vorbis_floor_data *, float *);
 typedef struct {
     uint_fast8_t floor_type;
     vorbis_floor_decode_func decode;
@@ -81,8 +82,7 @@ typedef struct {
         } t0;
         struct vorbis_floor1_s {
             uint_fast8_t partitions;
-            uint_fast8_t maximum_class;
-            uint_fast8_t partition_class[32];
+            uint8_t      partition_class[32];
             uint_fast8_t class_dimensions[16];
             uint_fast8_t class_subclasses[16];
             uint_fast8_t class_masterbook[16];
@@ -98,11 +98,13 @@ typedef struct {
     uint_fast16_t type;
     uint_fast32_t begin;
     uint_fast32_t end;
-    uint_fast32_t partition_size;
+    unsigned      partition_size;
     uint_fast8_t  classifications;
     uint_fast8_t  classbook;
     int_fast16_t  books[64][8];
     uint_fast8_t  maxpass;
+    uint_fast16_t ptns_to_read;
+    uint8_t *classifs;
 } vorbis_residue;
 
 typedef struct {
@@ -126,6 +128,7 @@ typedef struct vorbis_context_s {
     AVCodecContext *avccontext;
     GetBitContext gb;
     DSPContext dsp;
+    FmtConvertContext fmt_conv;
 
     FFTContext mdct[2];
     uint_fast8_t  first_frame;
@@ -152,8 +155,7 @@ typedef struct vorbis_context_s {
     float        *channel_residues;
     float        *channel_floors;
     float        *saved;
-    uint_fast32_t add_bias; // for float->int conversion
-    uint_fast32_t exp_bias;
+    float         scale_bias; // for float->int conversion
 } vorbis_context;
 
 /* Helper functions */
@@ -195,6 +197,8 @@ static void vorbis_free(vorbis_context *vc)
     av_freep(&vc->channel_floors);
     av_freep(&vc->saved);
 
+    for (i = 0; i < vc->residue_count; i++)
+        av_free(vc->residues[i].classifs);
     av_freep(&vc->residues);
     av_freep(&vc->modes);
 
@@ -237,6 +241,7 @@ static int vorbis_parse_setup_hdr_codebooks(vorbis_context *vc)
     uint8_t  *tmp_vlc_bits;
     uint32_t *tmp_vlc_codes;
     GetBitContext *gb = &vc->gb;
+    uint_fast16_t *codebook_multiplicands;
 
     vc->codebook_count = get_bits(gb, 8) + 1;
 
@@ -245,6 +250,7 @@ static int vorbis_parse_setup_hdr_codebooks(vorbis_context *vc)
     vc->codebooks = av_mallocz(vc->codebook_count * sizeof(vorbis_codebook));
     tmp_vlc_bits  = av_mallocz(V_MAX_VLCS * sizeof(uint8_t));
     tmp_vlc_codes = av_mallocz(V_MAX_VLCS * sizeof(uint32_t));
+    codebook_multiplicands = av_malloc(V_MAX_VLCS * sizeof(*codebook_multiplicands));
 
     for (cb = 0; cb < vc->codebook_count; ++cb) {
         vorbis_codebook *codebook_setup = &vc->codebooks[cb];
@@ -337,7 +343,6 @@ static int vorbis_parse_setup_hdr_codebooks(vorbis_context *vc)
         if (codebook_setup->lookup_type == 1) {
             uint_fast16_t i, j, k;
             uint_fast16_t codebook_lookup_values = ff_vorbis_nth_root(entries, codebook_setup->dimensions);
-            uint_fast16_t codebook_multiplicands[codebook_lookup_values];
 
             float codebook_minimum_value = vorbisfloat2float(get_bits_long(gb, 32));
             float codebook_delta_value   = vorbisfloat2float(get_bits_long(gb, 32));
@@ -421,12 +426,14 @@ static int vorbis_parse_setup_hdr_codebooks(vorbis_context *vc)
 
     av_free(tmp_vlc_bits);
     av_free(tmp_vlc_codes);
+    av_free(codebook_multiplicands);
     return 0;
 
 // Error:
 error:
     av_free(tmp_vlc_bits);
     av_free(tmp_vlc_codes);
+    av_free(codebook_multiplicands);
     return -1;
 }
 
@@ -453,15 +460,15 @@ static int vorbis_parse_setup_hdr_tdtransforms(vorbis_context *vc)
 
 // Process floors part
 
-static uint_fast8_t vorbis_floor0_decode(vorbis_context *vc,
-                                         vorbis_floor_data *vfu, float *vec);
+static int vorbis_floor0_decode(vorbis_context *vc,
+                                vorbis_floor_data *vfu, float *vec);
 static void create_map(vorbis_context *vc, uint_fast8_t floor_number);
-static uint_fast8_t vorbis_floor1_decode(vorbis_context *vc,
-                                         vorbis_floor_data *vfu, float *vec);
+static int vorbis_floor1_decode(vorbis_context *vc,
+                                vorbis_floor_data *vfu, float *vec);
 static int vorbis_parse_setup_hdr_floors(vorbis_context *vc)
 {
     GetBitContext *gb = &vc->gb;
-    uint_fast16_t i,j,k;
+    int i,j,k;
 
     vc->floor_count = get_bits(gb, 6) + 1;
 
@@ -475,8 +482,9 @@ static int vorbis_parse_setup_hdr_floors(vorbis_context *vc)
         AV_DEBUG(" %d. floor type %d \n", i, floor_setup->floor_type);
 
         if (floor_setup->floor_type == 1) {
-            uint_fast8_t  maximum_class = 0;
+            int maximum_class = -1;
             uint_fast8_t  rangebits;
+            uint_fast32_t rangemax;
             uint_fast16_t floor1_values = 2;
 
             floor_setup->decode = vorbis_floor1_decode;
@@ -496,8 +504,6 @@ static int vorbis_parse_setup_hdr_floors(vorbis_context *vc)
 
             AV_DEBUG(" maximum class %d \n", maximum_class);
 
-            floor_setup->data.t1.maximum_class = maximum_class;
-
             for (j = 0; j <= maximum_class; ++j) {
                 floor_setup->data.t1.class_dimensions[j] = get_bits(gb, 3) + 1;
                 floor_setup->data.t1.class_subclasses[j] = get_bits(gb, 2);
@@ -530,8 +536,15 @@ static int vorbis_parse_setup_hdr_floors(vorbis_context *vc)
 
 
             rangebits = get_bits(gb, 4);
+            rangemax = (1 << rangebits);
+            if (rangemax > vc->blocksize[1] / 2) {
+                av_log(vc->avccontext, AV_LOG_ERROR,
+                       "Floor value is too large for blocksize: %d (%d)\n",
+                       rangemax, vc->blocksize[1] / 2);
+                return -1;
+            }
             floor_setup->data.t1.list[0].x = 0;
-            floor_setup->data.t1.list[1].x = (1 << rangebits);
+            floor_setup->data.t1.list[1].x = rangemax;
 
             for (j = 0; j < floor_setup->data.t1.partitions; ++j) {
                 for (k = 0; k < floor_setup->data.t1.class_dimensions[floor_setup->data.t1.partition_class[j]]; ++k, ++floor1_values) {
@@ -555,9 +568,9 @@ static int vorbis_parse_setup_hdr_floors(vorbis_context *vc)
             /* zero would result in a div by zero later *
              * 2^0 - 1 == 0                             */
             if (floor_setup->data.t0.amplitude_bits == 0) {
-              av_log(vc->avccontext, AV_LOG_ERROR,
-                     "Floor 0 amplitude bits is 0.\n");
-              return -1;
+                av_log(vc->avccontext, AV_LOG_ERROR,
+                       "Floor 0 amplitude bits is 0.\n");
+                return -1;
             }
             floor_setup->data.t0.amplitude_offset = get_bits(gb, 8);
             floor_setup->data.t0.num_books        = get_bits(gb, 4) + 1;
@@ -572,7 +585,8 @@ static int vorbis_parse_setup_hdr_floors(vorbis_context *vc)
                 int idx;
                 uint_fast8_t book_idx;
                 for (idx = 0; idx < floor_setup->data.t0.num_books; ++idx) {
-                    GET_VALIDATED_INDEX(floor_setup->data.t0.book_list[idx], 8, vc->codebook_count)
+                    GET_VALIDATED_INDEX(book_idx, 8, vc->codebook_count)
+                    floor_setup->data.t0.book_list[idx] = book_idx;
                     if (vc->codebooks[book_idx].dimensions > max_codebook_dim)
                         max_codebook_dim = vc->codebooks[book_idx].dimensions;
                 }
@@ -580,37 +594,34 @@ static int vorbis_parse_setup_hdr_floors(vorbis_context *vc)
 
             create_map(vc, i);
 
-            /* allocate mem for lsp coefficients */
-            {
-                /* codebook dim is for padding if codebook dim doesn't *
-                 * divide order+1 then we need to read more data       */
-                floor_setup->data.t0.lsp =
-                    av_malloc((floor_setup->data.t0.order+1 + max_codebook_dim)
-                              * sizeof(float));
-                if (!floor_setup->data.t0.lsp)
-                    return -1;
-            }
+            /* codebook dim is for padding if codebook dim doesn't *
+             * divide order+1 then we need to read more data       */
+            floor_setup->data.t0.lsp =
+                av_malloc((floor_setup->data.t0.order+1 + max_codebook_dim)
+                          * sizeof(float));
+            if (!floor_setup->data.t0.lsp)
+                return -1;
 
 #ifdef V_DEBUG /* debug output parsed headers */
             AV_DEBUG("floor0 order: %u\n", floor_setup->data.t0.order);
             AV_DEBUG("floor0 rate: %u\n", floor_setup->data.t0.rate);
             AV_DEBUG("floor0 bark map size: %u\n",
-              floor_setup->data.t0.bark_map_size);
+                     floor_setup->data.t0.bark_map_size);
             AV_DEBUG("floor0 amplitude bits: %u\n",
-              floor_setup->data.t0.amplitude_bits);
+                     floor_setup->data.t0.amplitude_bits);
             AV_DEBUG("floor0 amplitude offset: %u\n",
-              floor_setup->data.t0.amplitude_offset);
+                     floor_setup->data.t0.amplitude_offset);
             AV_DEBUG("floor0 number of books: %u\n",
-              floor_setup->data.t0.num_books);
+                     floor_setup->data.t0.num_books);
             AV_DEBUG("floor0 book list pointer: %p\n",
-              floor_setup->data.t0.book_list);
+                     floor_setup->data.t0.book_list);
             {
-              int idx;
-              for (idx = 0; idx < floor_setup->data.t0.num_books; ++idx) {
-                  AV_DEBUG("  Book %d: %u\n",
-                           idx+1,
-                           floor_setup->data.t0.book_list[idx]);
-              }
+                int idx;
+                for (idx = 0; idx < floor_setup->data.t0.num_books; ++idx) {
+                    AV_DEBUG("  Book %d: %u\n",
+                             idx+1,
+                             floor_setup->data.t0.book_list[idx]);
+                }
             }
 #endif
         } else {
@@ -648,15 +659,23 @@ static int vorbis_parse_setup_hdr_residues(vorbis_context *vc)
         res_setup->partition_size = get_bits(gb, 24) + 1;
         /* Validations to prevent a buffer overflow later. */
         if (res_setup->begin>res_setup->end ||
-            res_setup->end>vc->blocksize[1] / (res_setup->type == 2 ? 1 : 2) ||
+            res_setup->end > vc->avccontext->channels * vc->blocksize[1] / 2 ||
             (res_setup->end-res_setup->begin) / res_setup->partition_size > V_MAX_PARTITIONS) {
-            av_log(vc->avccontext, AV_LOG_ERROR, "partition out of bounds: type, begin, end, size, blocksize: %"PRIdFAST16", %"PRIdFAST32", %"PRIdFAST32", %"PRIdFAST32", %"PRIdFAST32"\n", res_setup->type, res_setup->begin, res_setup->end, res_setup->partition_size, vc->blocksize[1] / 2);
+            av_log(vc->avccontext, AV_LOG_ERROR, "partition out of bounds: type, begin, end, size, blocksize: %"PRIdFAST16", %"PRIdFAST32", %"PRIdFAST32", %u, %"PRIdFAST32"\n", res_setup->type, res_setup->begin, res_setup->end, res_setup->partition_size, vc->blocksize[1] / 2);
             return -1;
         }
 
         res_setup->classifications = get_bits(gb, 6) + 1;
         GET_VALIDATED_INDEX(res_setup->classbook, 8, vc->codebook_count)
 
+        res_setup->ptns_to_read =
+            (res_setup->end - res_setup->begin) / res_setup->partition_size;
+        res_setup->classifs = av_malloc(res_setup->ptns_to_read *
+                                        vc->audio_channels *
+                                        sizeof(*res_setup->classifs));
+        if (!res_setup->classifs)
+            return AVERROR(ENOMEM);
+
         AV_DEBUG("    begin %d end %d part.size %d classif.s %d classbook %d \n", res_setup->begin, res_setup->end, res_setup->partition_size,
           res_setup->classifications, res_setup->classbook);
 
@@ -780,12 +799,12 @@ static void create_map(vorbis_context *vc, uint_fast8_t floor_number)
         vf->map_size[blockflag] = n;
     }
 
-#   ifdef V_DEBUG
+#ifdef V_DEBUG
     for (idx = 0; idx <= n; ++idx) {
         AV_DEBUG("floor0 map: map at pos %d is %d\n",
                  idx, map[idx]);
     }
-#   endif
+#endif
 }
 
 static int vorbis_parse_setup_hdr_modes(vorbis_context *vc)
@@ -911,8 +930,8 @@ static int vorbis_parse_id_hdr(vorbis_context *vc)
     vc->saved            =  av_mallocz((vc->blocksize[1] / 4) * vc->audio_channels * sizeof(float));
     vc->previous_window  = 0;
 
-    ff_mdct_init(&vc->mdct[0], bl0, 1, vc->exp_bias ? -(1 << 15) : -1.0);
-    ff_mdct_init(&vc->mdct[1], bl1, 1, vc->exp_bias ? -(1 << 15) : -1.0);
+    ff_mdct_init(&vc->mdct[0], bl0, 1, -vc->scale_bias);
+    ff_mdct_init(&vc->mdct[1], bl1, 1, -vc->scale_bias);
 
     AV_DEBUG(" vorbis version %d \n audio_channels %d \n audio_samplerate %d \n bitrate_max %d \n bitrate_nom %d \n bitrate_min %d \n blk_0 %d blk_1 %d \n ",
             vc->version, vc->audio_channels, vc->audio_samplerate, vc->bitrate_maximum, vc->bitrate_nominal, vc->bitrate_minimum, vc->blocksize[0], vc->blocksize[1]);
@@ -941,14 +960,9 @@ static av_cold int vorbis_decode_init(AVCodecContext *avccontext)
 
     vc->avccontext = avccontext;
     dsputil_init(&vc->dsp, avccontext);
+    ff_fmt_convert_init(&vc->fmt_conv, avccontext);
 
-    if (vc->dsp.float_to_int16_interleave == ff_float_to_int16_interleave_c) {
-        vc->add_bias = 385;
-        vc->exp_bias = 0;
-    } else {
-        vc->add_bias = 0;
-        vc->exp_bias = 15 << 23;
-    }
+    vc->scale_bias = 32768.0f;
 
     if (!headers_len) {
         av_log(avccontext, AV_LOG_ERROR, "Extradata missing.\n");
@@ -993,7 +1007,7 @@ static av_cold int vorbis_decode_init(AVCodecContext *avccontext)
     avccontext->channels    = vc->audio_channels;
     avccontext->sample_rate = vc->audio_samplerate;
     avccontext->frame_size  = FFMIN(vc->blocksize[0], vc->blocksize[1]) >> 2;
-    avccontext->sample_fmt  = SAMPLE_FMT_S16;
+    avccontext->sample_fmt  = AV_SAMPLE_FMT_S16;
 
     return 0 ;
 }
@@ -1002,8 +1016,8 @@ static av_cold int vorbis_decode_init(AVCodecContext *avccontext)
 
 // Read and decode floor
 
-static uint_fast8_t vorbis_floor0_decode(vorbis_context *vc,
-                                         vorbis_floor_data *vfu, float *vec)
+static int vorbis_floor0_decode(vorbis_context *vc,
+                                vorbis_floor_data *vfu, float *vec)
 {
     vorbis_floor0 *vf = &vfu->t0;
     float *lsp = vf->lsp;
@@ -1023,10 +1037,12 @@ static uint_fast8_t vorbis_floor0_decode(vorbis_context *vc,
             av_log(vc->avccontext, AV_LOG_ERROR,
                     "floor0 dec: booknumber too high!\n");
             book_idx =  0;
-            //FIXME: look above
         }
         AV_DEBUG("floor0 dec: booknumber: %u\n", book_idx);
         codebook = vc->codebooks[vf->book_list[book_idx]];
+        /* Invalid codebook! */
+        if (!codebook.codevectors)
+            return -1;
 
         while (lsp_len<vf->order) {
             int vec_off;
@@ -1090,11 +1106,9 @@ static uint_fast8_t vorbis_floor0_decode(vorbis_context *vc,
                 }
 
                 /* calculate linear floor value */
-                {
-                    q = exp((((amplitude*vf->amplitude_offset) /
-                              (((1 << vf->amplitude_bits) - 1) * sqrt(p + q)))
-                             - vf->amplitude_offset) * .11512925f);
-                }
+                q = exp((((amplitude*vf->amplitude_offset) /
+                          (((1 << vf->amplitude_bits) - 1) * sqrt(p + q)))
+                         - vf->amplitude_offset) * .11512925f);
 
                 /* fill vector */
                 do {
@@ -1112,16 +1126,16 @@ static uint_fast8_t vorbis_floor0_decode(vorbis_context *vc,
     return 0;
 }
 
-static uint_fast8_t vorbis_floor1_decode(vorbis_context *vc,
-                                         vorbis_floor_data *vfu, float *vec)
+static int vorbis_floor1_decode(vorbis_context *vc,
+                                vorbis_floor_data *vfu, float *vec)
 {
     vorbis_floor1 *vf = &vfu->t1;
     GetBitContext *gb = &vc->gb;
     uint_fast16_t range_v[4] = { 256, 128, 86, 64 };
     uint_fast16_t range = range_v[vf->multiplier-1];
-    uint_fast16_t floor1_Y[vf->x_list_dim];
-    uint_fast16_t floor1_Y_final[vf->x_list_dim];
-    int floor1_flag[vf->x_list_dim];
+    uint_fast16_t floor1_Y[258];
+    uint_fast16_t floor1_Y_final[258];
+    int floor1_flag[258];
     uint_fast8_t class_;
     uint_fast8_t cdim;
     uint_fast8_t cbits;
@@ -1130,8 +1144,8 @@ static uint_fast8_t vorbis_floor1_decode(vorbis_context *vc,
     int_fast16_t book;
     uint_fast16_t offset;
     uint_fast16_t i,j;
-    /*u*/int_fast16_t adx, ady, off, predicted; // WTF ? dy/adx =  (unsigned)dy/adx ?
-    int_fast16_t dy, err;
+    int_fast16_t adx, ady, dy, off, predicted;
+    int_fast32_t err;
 
 
     if (!get_bits1(gb)) // silence
@@ -1194,7 +1208,7 @@ static uint_fast8_t vorbis_floor1_decode(vorbis_context *vc,
         adx = vf->list[high_neigh_offs].x - vf->list[low_neigh_offs].x;
         ady = FFABS(dy);
         err = ady * (vf->list[i].x - vf->list[low_neigh_offs].x);
-        off = (int16_t)err / (int16_t)adx;
+        off = err / adx;
         if (dy < 0) {
             predicted = floor1_Y_final[low_neigh_offs] - off;
         } else {
@@ -1255,9 +1269,8 @@ static av_always_inline int vorbis_residue_decode_internal(vorbis_context *vc,
 {
     GetBitContext *gb = &vc->gb;
     uint_fast8_t c_p_c = vc->codebooks[vr->classbook].dimensions;
-    uint_fast16_t n_to_read = vr->end-vr->begin;
-    uint_fast16_t ptns_to_read = n_to_read/vr->partition_size;
-    uint_fast8_t classifs[ptns_to_read*vc->audio_channels];
+    uint_fast16_t ptns_to_read = vr->ptns_to_read;
+    uint8_t *classifs = vr->classifs;
     uint_fast8_t pass;
     uint_fast8_t ch_used;
     uint_fast8_t i,j,l;
@@ -1430,38 +1443,25 @@ void vorbis_inverse_coupling(float *mag, float *ang, int blocksize)
     }
 }
 
-static void copy_normalize(float *dst, float *src, int len, int exp_bias,
-                           float add_bias)
-{
-    int i;
-    if (exp_bias) {
-        memcpy(dst, src, len * sizeof(float));
-    } else {
-        for (i = 0; i < len; i++)
-            dst[i] = src[i] + add_bias;
-    }
-}
-
 // Decode the audio packet using the functions above
 
 static int vorbis_parse_audio_packet(vorbis_context *vc)
 {
     GetBitContext *gb = &vc->gb;
-
+    FFTContext *mdct;
     uint_fast8_t previous_window = vc->previous_window;
     uint_fast8_t mode_number;
     uint_fast8_t blockflag;
     uint_fast16_t blocksize;
     int_fast32_t i,j;
-    uint_fast8_t no_residue[vc->audio_channels];
-    uint_fast8_t do_not_decode[vc->audio_channels];
+    uint_fast8_t no_residue[255];
+    uint_fast8_t do_not_decode[255];
     vorbis_mapping *mapping;
     float *ch_res_ptr   = vc->channel_residues;
     float *ch_floor_ptr = vc->channel_floors;
-    uint_fast8_t res_chan[vc->audio_channels];
+    uint_fast8_t res_chan[255];
     uint_fast8_t res_num = 0;
     int_fast16_t retlen  = 0;
-    float fadd_bias = vc->add_bias;
 
     if (get_bits1(gb)) {
         av_log(vc->avccontext, AV_LOG_ERROR, "Not a Vorbis I audio packet.\n");
@@ -1490,13 +1490,20 @@ static int vorbis_parse_audio_packet(vorbis_context *vc)
 
     for (i = 0; i < vc->audio_channels; ++i) {
         vorbis_floor *floor;
+        int ret;
         if (mapping->submaps > 1) {
             floor = &vc->floors[mapping->submap_floor[mapping->mux[i]]];
         } else {
             floor = &vc->floors[mapping->submap_floor[0]];
         }
 
-        no_residue[i] = floor->decode(vc, &floor->data, ch_floor_ptr);
+        ret = floor->decode(vc, &floor->data, ch_floor_ptr);
+
+        if (ret < 0) {
+            av_log(vc->avccontext, AV_LOG_ERROR, "Invalid codebook in vorbis_floor_decode.\n");
+            return -1;
+        }
+        no_residue[i] = ret;
         ch_floor_ptr += blocksize / 2;
     }
 
@@ -1545,11 +1552,13 @@ static int vorbis_parse_audio_packet(vorbis_context *vc)
 
 // Dotproduct, MDCT
 
+    mdct = &vc->mdct[blockflag];
+
     for (j = vc->audio_channels-1;j >= 0; j--) {
         ch_floor_ptr = vc->channel_floors   + j           * blocksize / 2;
         ch_res_ptr   = vc->channel_residues + res_chan[j] * blocksize / 2;
-        vc->dsp.vector_fmul(ch_floor_ptr, ch_res_ptr, blocksize / 2);
-        ff_imdct_half(&vc->mdct[blockflag], ch_res_ptr, ch_floor_ptr);
+        vc->dsp.vector_fmul(ch_floor_ptr, ch_floor_ptr, ch_res_ptr, blocksize / 2);
+        mdct->imdct_half(mdct, ch_res_ptr, ch_floor_ptr);
     }
 
 // Overlap/add, save data for next overlapping  FPMATH
@@ -1565,13 +1574,13 @@ static int vorbis_parse_audio_packet(vorbis_context *vc)
         const float *win  = vc->win[blockflag & previous_window];
 
         if (blockflag == previous_window) {
-            vc->dsp.vector_fmul_window(ret, saved, buf, win, fadd_bias, blocksize / 4);
+            vc->dsp.vector_fmul_window(ret, saved, buf, win, blocksize / 4);
         } else if (blockflag > previous_window) {
-            vc->dsp.vector_fmul_window(ret, saved, buf, win, fadd_bias, bs0 / 4);
-            copy_normalize(ret+bs0/2, buf+bs0/4, (bs1-bs0)/4, vc->exp_bias, fadd_bias);
+            vc->dsp.vector_fmul_window(ret, saved, buf, win, bs0 / 4);
+            memcpy(ret+bs0/2, buf+bs0/4, ((bs1-bs0)/4) * sizeof(float));
         } else {
-            copy_normalize(ret, saved, (bs1 - bs0) / 4, vc->exp_bias, fadd_bias);
-            vc->dsp.vector_fmul_window(ret + (bs1 - bs0) / 4, saved + (bs1 - bs0) / 4, buf, win, fadd_bias, bs0 / 4);
+            memcpy(ret, saved, ((bs1 - bs0) / 4) * sizeof(float));
+            vc->dsp.vector_fmul_window(ret + (bs1 - bs0) / 4, saved + (bs1 - bs0) / 4, buf, win, bs0 / 4);
         }
         memcpy(saved, buf + blocksize / 4, blocksize / 4 * sizeof(float));
     }
@@ -1590,7 +1599,7 @@ static int vorbis_decode_frame(AVCodecContext *avccontext,
     int buf_size       = avpkt->size;
     vorbis_context *vc = avccontext->priv_data ;
     GetBitContext *gb = &(vc->gb);
-    const float *channel_ptrs[vc->audio_channels];
+    const float *channel_ptrs[255];
     int i;
 
     int_fast16_t len;
@@ -1626,7 +1635,8 @@ static int vorbis_decode_frame(AVCodecContext *avccontext,
                               len * ff_vorbis_channel_layout_offsets[vc->audio_channels - 1][i];
     }
 
-    vc->dsp.float_to_int16_interleave(data, channel_ptrs, len, vc->audio_channels);
+    vc->fmt_conv.float_to_int16_interleave(data, channel_ptrs, len,
+                                           vc->audio_channels);
     *data_size = len * 2 * vc->audio_channels;
 
     return buf_size ;
@@ -1643,7 +1653,7 @@ static av_cold int vorbis_decode_close(AVCodecContext *avccontext)
     return 0 ;
 }
 
-AVCodec vorbis_decoder = {
+AVCodec ff_vorbis_decoder = {
     "vorbis",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_VORBIS,
diff --git a/libavcodec/vorbis_enc.c b/libavcodec/vorbis_enc.c
index 934463d..74933af 100644
--- a/libavcodec/vorbis_enc.c
+++ b/libavcodec/vorbis_enc.c
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2006 Oded Shimon <ods15 at ods15.dyndns.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -126,6 +126,17 @@ typedef struct {
     int64_t sample_count;
 } vorbis_enc_context;
 
+#define MAX_CHANNELS     2
+#define MAX_CODEBOOK_DIM 8
+
+#define MAX_FLOOR_CLASS_DIM  4
+#define NUM_FLOOR_PARTITIONS 8
+#define MAX_FLOOR_VALUES     (MAX_FLOOR_CLASS_DIM*NUM_FLOOR_PARTITIONS+2)
+
+#define RESIDUE_SIZE           1600
+#define RESIDUE_PART_SIZE      32
+#define NUM_RESIDUE_PARTITIONS (RESIDUE_SIZE/RESIDUE_PART_SIZE)
+
 static inline void put_codeword(PutBitContext *pb, vorbis_enc_codebook *cb,
                                 int entry)
 {
@@ -263,7 +274,7 @@ static void create_vorbis_context(vorbis_enc_context *venc,
 
     // just 1 floor
     fc = &venc->floors[0];
-    fc->partitions         = 8;
+    fc->partitions         = NUM_FLOOR_PARTITIONS;
     fc->partition_to_class = av_malloc(sizeof(int) * fc->partitions);
     fc->nclasses           = 0;
     for (i = 0; i < fc->partitions; i++) {
@@ -383,7 +394,7 @@ static void put_float(PutBitContext *pb, float f)
     mant = (int)ldexp(frexp(f, &exp), 20);
     exp += 788 - 20;
     if (mant < 0) {
-        res |= (1 << 31);
+        res |= (1U << 31);
         mant = -mant;
     }
     res |= mant | (exp << 21);
@@ -668,7 +679,7 @@ static void floor_fit(vorbis_enc_context *venc, vorbis_enc_floor *fc,
     int range = 255 / fc->multiplier + 1;
     int i;
     float tot_average = 0.;
-    float averages[fc->values];
+    float averages[MAX_FLOOR_VALUES];
     for (i = 0; i < fc->values; i++) {
         averages[i] = get_floor_average(fc, coeffs, i);
         tot_average += averages[i];
@@ -681,7 +692,7 @@ static void floor_fit(vorbis_enc_context *venc, vorbis_enc_floor *fc,
         float average = averages[i];
         int j;
 
-        average *= pow(tot_average / average, 0.5) * pow(1.25, position/200.); // MAGIC!
+        average = sqrt(tot_average * average) * pow(1.25f, position*0.005f); // MAGIC!
         for (j = 0; j < range - 1; j++)
             if (ff_vorbis_floor1_inverse_db_table[j * fc->multiplier] > average)
                 break;
@@ -699,7 +710,7 @@ static void floor_encode(vorbis_enc_context *venc, vorbis_enc_floor *fc,
                          float *floor, int samples)
 {
     int range = 255 / fc->multiplier + 1;
-    int coded[fc->values]; // first 2 values are unused
+    int coded[MAX_FLOOR_VALUES]; // first 2 values are unused
     int i, counter;
 
     put_bits(pb, 1, 1); // non zero
@@ -807,7 +818,7 @@ static void residue_encode(vorbis_enc_context *venc, vorbis_enc_residue *rc,
     int psize      = rc->partition_size;
     int partitions = (rc->end - rc->begin) / psize;
     int channels   = (rc->type == 2) ? 1 : real_ch;
-    int classes[channels][partitions];
+    int classes[MAX_CHANNELS][NUM_RESIDUE_PARTITIONS];
     int classwords = venc->codebooks[rc->classbook].ndimentions;
 
     assert(rc->type == 2);
@@ -864,7 +875,7 @@ static void residue_encode(vorbis_enc_context *venc, vorbis_enc_residue *rc,
                         s  = real_ch * samples;
                         for (k = 0; k < psize; k += book->ndimentions) {
                             int dim, a2 = a1, b2 = b1;
-                            float vec[book->ndimentions], *pv = vec;
+                            float vec[MAX_CODEBOOK_DIM], *pv = vec;
                             for (dim = book->ndimentions; dim--; ) {
                                 *pv++ = coeffs[a2 + b2];
                                 if ((a2 += samples) == s) {
@@ -888,7 +899,7 @@ static void residue_encode(vorbis_enc_context *venc, vorbis_enc_residue *rc,
     }
 }
 
-static int apply_window_and_mdct(vorbis_enc_context *venc, signed short *audio,
+static int apply_window_and_mdct(vorbis_enc_context *venc, const signed short *audio,
                                  int samples)
 {
     int i, j, channel;
@@ -915,7 +926,7 @@ static int apply_window_and_mdct(vorbis_enc_context *venc, signed short *audio,
             float * offset = venc->samples + channel*window_len*2 + window_len;
             j = channel;
             for (i = 0; i < samples; i++, j += venc->channels)
-                offset[i] = -audio[j] / 32768. / n * win[window_len - i - 1]; //FIXME find out why the sign has to be fliped
+                offset[i] = audio[j] / 32768. / n * win[window_len - i - 1];
         }
     } else {
         for (channel = 0; channel < venc->channels; channel++)
@@ -924,7 +935,7 @@ static int apply_window_and_mdct(vorbis_enc_context *venc, signed short *audio,
     }
 
     for (channel = 0; channel < venc->channels; channel++)
-        ff_mdct_calc(&venc->mdct[0], venc->coeffs + channel * window_len,
+        venc->mdct[0].mdct_calc(&venc->mdct[0], venc->coeffs + channel * window_len,
                      venc->samples + channel * window_len * 2);
 
     if (samples) {
@@ -932,7 +943,7 @@ static int apply_window_and_mdct(vorbis_enc_context *venc, signed short *audio,
             float *offset = venc->saved + channel * window_len;
             j = channel;
             for (i = 0; i < samples; i++, j += venc->channels)
-                offset[i] = -audio[j] / 32768. / n * win[i]; //FIXME find out why the sign has to be fliped
+                offset[i] = audio[j] / 32768. / n * win[i];
         }
         venc->have_saved = 1;
     } else {
@@ -946,7 +957,7 @@ static av_cold int vorbis_encode_init(AVCodecContext *avccontext)
     vorbis_enc_context *venc = avccontext->priv_data;
 
     if (avccontext->channels != 2) {
-        av_log(avccontext, AV_LOG_ERROR, "Current FFmpeg Vorbis encoder only supports 2 channels.\n");
+        av_log(avccontext, AV_LOG_ERROR, "Current Libav Vorbis encoder only supports 2 channels.\n");
         return -1;
     }
 
@@ -955,7 +966,7 @@ static av_cold int vorbis_encode_init(AVCodecContext *avccontext)
     if (avccontext->flags & CODEC_FLAG_QSCALE)
         venc->quality = avccontext->global_quality / (float)FF_QP2LAMBDA / 10.;
     else
-        venc->quality = 1.;
+        venc->quality = 0.03;
     venc->quality *= venc->quality;
 
     avccontext->extradata_size = put_main_header(venc, (uint8_t**)&avccontext->extradata);
@@ -973,7 +984,7 @@ static int vorbis_encode_frame(AVCodecContext *avccontext,
                                int buf_size, void *data)
 {
     vorbis_enc_context *venc = avccontext->priv_data;
-    signed short *audio = data;
+    const signed short *audio = data;
     int samples = data ? avccontext->frame_size : 0;
     vorbis_enc_mode *mode;
     vorbis_enc_mapping *mapping;
@@ -999,7 +1010,7 @@ static int vorbis_encode_frame(AVCodecContext *avccontext,
 
     for (i = 0; i < venc->channels; i++) {
         vorbis_enc_floor *fc = &venc->floors[mapping->floor[mapping->mux[i]]];
-        uint_fast16_t posts[fc->values];
+        uint_fast16_t posts[MAX_FLOOR_VALUES];
         floor_fit(venc, fc, &venc->coeffs[i * samples], posts, samples);
         floor_encode(venc, fc, &pb, posts, &venc->floor[i * samples], samples);
     }
@@ -1091,7 +1102,7 @@ static av_cold int vorbis_encode_close(AVCodecContext *avccontext)
     return 0 ;
 }
 
-AVCodec vorbis_encoder = {
+AVCodec ff_vorbis_encoder = {
     "vorbis",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_VORBIS,
@@ -1100,6 +1111,6 @@ AVCodec vorbis_encoder = {
     vorbis_encode_frame,
     vorbis_encode_close,
     .capabilities= CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
-    .sample_fmts = (const enum SampleFormat[]){SAMPLE_FMT_S16,SAMPLE_FMT_NONE},
+    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
     .long_name = NULL_IF_CONFIG_SMALL("Vorbis"),
 };
diff --git a/libavcodec/vorbis_enc_data.h b/libavcodec/vorbis_enc_data.h
index affc3d6..a1e743e 100644
--- a/libavcodec/vorbis_enc_data.h
+++ b/libavcodec/vorbis_enc_data.h
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2006 Oded Shimon <ods15 at ods15.dyndns.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/vp3.c b/libavcodec/vp3.c
index c08de6c..bcbb70f 100644
--- a/libavcodec/vp3.c
+++ b/libavcodec/vp3.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (C) 2003-2004 the ffmpeg project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -33,12 +33,14 @@
 #include <stdlib.h>
 #include <string.h>
 
+#include "libavutil/imgutils.h"
 #include "avcodec.h"
 #include "dsputil.h"
 #include "get_bits.h"
 
 #include "vp3data.h"
 #include "xiph.h"
+#include "thread.h"
 
 #define FRAGMENT_PIXELS 8
 
@@ -136,6 +138,7 @@ typedef struct Vp3DecodeContext {
     DSPContext dsp;
     int flipped_image;
     int last_slice_end;
+    int skip_loop_filter;
 
     int qps[3];
     int nqps;
@@ -234,8 +237,7 @@ typedef struct Vp3DecodeContext {
      * is coded. */
     unsigned char *macroblock_coding;
 
-    uint8_t edge_emu_buffer[9*2048]; //FIXME dynamic alloc
-    int8_t qscale_table[2048]; //FIXME dynamic alloc (width+15)/16
+    uint8_t *edge_emu_buffer;
 
     /* Huffman decode */
     int hti;
@@ -257,7 +259,7 @@ typedef struct Vp3DecodeContext {
  * superblocks <-> fragments, macroblocks <-> fragments,
  * superblocks <-> macroblocks
  *
- * Returns 0 is successful; returns 1 if *anything* went wrong.
+ * @return 0 is successful; returns 1 if *anything* went wrong.
  */
 static int init_block_mapping(Vp3DecodeContext *s)
 {
@@ -322,8 +324,6 @@ static void init_dequantizer(Vp3DecodeContext *s, int qpi)
             s->qmat[qpi][inter][plane][0] = s->qmat[0][inter][plane][0];
         }
     }
-
-    memset(s->qscale_table, (FFMAX(s->qmat[0][0][0][1], s->qmat[0][0][1][1])+8)/16, 512); //FIXME finetune
 }
 
 /*
@@ -378,8 +378,15 @@ static int unpack_superblocks(Vp3DecodeContext *s, GetBitContext *gb)
     } else {
 
         /* unpack the list of partially-coded superblocks */
-        bit = get_bits1(gb);
+        bit = get_bits1(gb) ^ 1;
+        current_run = 0;
+
         while (current_superblock < s->superblock_count && get_bits_left(gb) > 0) {
+            if (s->theora && current_run == MAXIMUM_LONG_BIT_RUN)
+                bit = get_bits1(gb);
+            else
+                bit ^= 1;
+
                 current_run = get_vlc2(gb,
                     s->superblock_run_length_vlc.table, 6, 2) + 1;
                 if (current_run == 34)
@@ -395,11 +402,6 @@ static int unpack_superblocks(Vp3DecodeContext *s, GetBitContext *gb)
             current_superblock += current_run;
             if (bit)
                 num_partial_superblocks += current_run;
-
-            if (s->theora && current_run == MAXIMUM_LONG_BIT_RUN)
-                bit = get_bits1(gb);
-            else
-                bit ^= 1;
         }
 
         /* unpack the list of fully coded superblocks if any of the blocks were
@@ -408,9 +410,17 @@ static int unpack_superblocks(Vp3DecodeContext *s, GetBitContext *gb)
             int superblocks_decoded = 0;
 
             current_superblock = 0;
-            bit = get_bits1(gb);
+            bit = get_bits1(gb) ^ 1;
+            current_run = 0;
+
             while (superblocks_decoded < s->superblock_count - num_partial_superblocks
                    && get_bits_left(gb) > 0) {
+
+                if (s->theora && current_run == MAXIMUM_LONG_BIT_RUN)
+                    bit = get_bits1(gb);
+                else
+                    bit ^= 1;
+
                         current_run = get_vlc2(gb,
                             s->superblock_run_length_vlc.table, 6, 2) + 1;
                         if (current_run == 34)
@@ -429,11 +439,6 @@ static int unpack_superblocks(Vp3DecodeContext *s, GetBitContext *gb)
                 }
                 }
                 superblocks_decoded += current_run;
-
-                if (s->theora && current_run == MAXIMUM_LONG_BIT_RUN)
-                    bit = get_bits1(gb);
-                else
-                    bit ^= 1;
             }
         }
 
@@ -800,9 +805,15 @@ static int unpack_block_qpis(Vp3DecodeContext *s, GetBitContext *gb)
     for (qpi = 0; qpi < s->nqps-1 && num_blocks > 0; qpi++) {
         i = blocks_decoded = num_blocks_at_qpi = 0;
 
-        bit = get_bits1(gb);
+        bit = get_bits1(gb) ^ 1;
+        run_length = 0;
 
         do {
+            if (run_length == MAXIMUM_LONG_BIT_RUN)
+                bit = get_bits1(gb);
+            else
+                bit ^= 1;
+
             run_length = get_vlc2(gb, s->superblock_run_length_vlc.table, 6, 2) + 1;
             if (run_length == 34)
                 run_length += get_bits(gb, 12);
@@ -820,11 +831,6 @@ static int unpack_block_qpis(Vp3DecodeContext *s, GetBitContext *gb)
                     j++;
                 }
             }
-
-            if (run_length == MAXIMUM_LONG_BIT_RUN)
-                bit = get_bits1(gb);
-            else
-                bit ^= 1;
         } while (blocks_decoded < num_blocks && get_bits_left(gb) > 0);
 
         num_blocks -= num_blocks_at_qpi;
@@ -1263,7 +1269,7 @@ static void apply_loop_filter(Vp3DecodeContext *s, int plane, int ystart, int ye
 }
 
 /**
- * Pulls DCT tokens from the 64 levels to decode and dequant the coefficients
+ * Pull DCT tokens from the 64 levels to decode and dequant the coefficients
  * for the next block in coding order
  */
 static inline int vp3_dequant(Vp3DecodeContext *s, Vp3Fragment *frag,
@@ -1310,19 +1316,27 @@ static void vp3_draw_horiz_band(Vp3DecodeContext *s, int y)
     int h, cy;
     int offset[4];
 
+    if (HAVE_PTHREADS && s->avctx->active_thread_type&FF_THREAD_FRAME) {
+        int y_flipped = s->flipped_image ? s->avctx->height-y : y;
+
+        // At the end of the frame, report INT_MAX instead of the height of the frame.
+        // This makes the other threads' ff_thread_await_progress() calls cheaper, because
+        // they don't have to clip their values.
+        ff_thread_report_progress(&s->current_frame, y_flipped==s->avctx->height ? INT_MAX : y_flipped-1, 0);
+    }
+
     if(s->avctx->draw_horiz_band==NULL)
         return;
 
     h= y - s->last_slice_end;
+    s->last_slice_end= y;
     y -= h;
 
     if (!s->flipped_image) {
-        if (y == 0)
-            h -= s->height - s->avctx->height;  // account for non-mod16
-        y = s->height - y - h;
+        y = s->avctx->height - y - h;
     }
 
-    cy = y >> 1;
+    cy = y >> s->chroma_y_shift;
     offset[0] = s->current_frame.linesize[0]*y;
     offset[1] = s->current_frame.linesize[1]*cy;
     offset[2] = s->current_frame.linesize[2]*cy;
@@ -1330,7 +1344,28 @@ static void vp3_draw_horiz_band(Vp3DecodeContext *s, int y)
 
     emms_c();
     s->avctx->draw_horiz_band(s->avctx, &s->current_frame, offset, y, 3, h);
-    s->last_slice_end= y + h;
+}
+
+/**
+ * Wait for the reference frame of the current fragment.
+ * The progress value is in luma pixel rows.
+ */
+static void await_reference_row(Vp3DecodeContext *s, Vp3Fragment *fragment, int motion_y, int y)
+{
+    AVFrame *ref_frame;
+    int ref_row;
+    int border = motion_y&1;
+
+    if (fragment->coding_method == MODE_USING_GOLDEN ||
+        fragment->coding_method == MODE_GOLDEN_MV)
+        ref_frame = &s->golden_frame;
+    else
+        ref_frame = &s->last_frame;
+
+    ref_row = y + (motion_y>>1);
+    ref_row = FFMAX(FFABS(ref_row), ref_row + 8 + border);
+
+    ff_thread_await_progress(ref_frame, ref_row, 0);
 }
 
 /*
@@ -1339,7 +1374,7 @@ static void vp3_draw_horiz_band(Vp3DecodeContext *s, int y)
  */
 static void render_slice(Vp3DecodeContext *s, int slice)
 {
-    int x, y, i, j;
+    int x, y, i, j, fragment;
     LOCAL_ALIGNED_16(DCTELEM, block, [64]);
     int motion_x = 0xdeadbeef, motion_y = 0xdeadbeef;
     int motion_halfpel_index;
@@ -1365,15 +1400,12 @@ static void render_slice(Vp3DecodeContext *s, int slice)
         int fragment_width    = s->fragment_width[!!plane];
         int fragment_height   = s->fragment_height[!!plane];
         int fragment_start    = s->fragment_start[plane];
+        int do_await          = !plane && HAVE_PTHREADS && (s->avctx->active_thread_type&FF_THREAD_FRAME);
 
         if (!s->flipped_image) stride = -stride;
         if (CONFIG_GRAY && plane && (s->avctx->flags & CODEC_FLAG_GRAY))
             continue;
 
-
-        if(FFABS(stride) > 2048)
-            return; //various tables are fixed size
-
         /* for each superblock row in the slice (both of them)... */
         for (; sb_y < slice_height; sb_y++) {
 
@@ -1384,8 +1416,9 @@ static void render_slice(Vp3DecodeContext *s, int slice)
                 for (j = 0; j < 16; j++) {
                     x = 4*sb_x + hilbert_offset[j][0];
                     y = 4*sb_y + hilbert_offset[j][1];
+                    fragment = y*fragment_width + x;
 
-                    i = fragment_start + y*fragment_width + x;
+                    i = fragment_start + fragment;
 
                     // bounds check
                     if (x >= fragment_width || y >= fragment_height)
@@ -1393,6 +1426,9 @@ static void render_slice(Vp3DecodeContext *s, int slice)
 
                 first_pixel = 8*y*stride + 8*x;
 
+                if (do_await && s->all_fragments[i].coding_method != MODE_INTRA)
+                    await_reference_row(s, &s->all_fragments[i], motion_val[fragment][1], (16*y) >> s->chroma_y_shift);
+
                 /* transform if this block was coded */
                 if (s->all_fragments[i].coding_method != MODE_COPY) {
                     if ((s->all_fragments[i].coding_method == MODE_USING_GOLDEN) ||
@@ -1409,8 +1445,8 @@ static void render_slice(Vp3DecodeContext *s, int slice)
                     if ((s->all_fragments[i].coding_method > MODE_INTRA) &&
                         (s->all_fragments[i].coding_method != MODE_USING_GOLDEN)) {
                         int src_x, src_y;
-                        motion_x = motion_val[y*fragment_width + x][0];
-                        motion_y = motion_val[y*fragment_width + x][1];
+                        motion_x = motion_val[fragment][0];
+                        motion_y = motion_val[fragment][1];
 
                         src_x= (motion_x>>1) + 8*x;
                         src_y= (motion_y>>1) + 8*y;
@@ -1423,10 +1459,9 @@ static void render_slice(Vp3DecodeContext *s, int slice)
 
                         if(src_x<0 || src_y<0 || src_x + 9 >= plane_width || src_y + 9 >= plane_height){
                             uint8_t *temp= s->edge_emu_buffer;
-                            if(stride<0) temp -= 9*stride;
-                            else temp += 9*stride;
+                            if(stride<0) temp -= 8*stride;
 
-                            ff_emulated_edge_mc(temp, motion_source, stride, 9, 9, src_x, src_y, plane_width, plane_height);
+                            s->dsp.emulated_edge_mc(temp, motion_source, stride, 9, 9, src_x, src_y, plane_width, plane_height);
                             motion_source= temp;
                         }
                     }
@@ -1488,7 +1523,8 @@ static void render_slice(Vp3DecodeContext *s, int slice)
             }
 
             // Filter up to the last row in the superblock row
-            apply_loop_filter(s, plane, 4*sb_y - !!sb_y, FFMIN(4*sb_y+3, fragment_height-1));
+            if (!s->skip_loop_filter)
+                apply_loop_filter(s, plane, 4*sb_y - !!sb_y, FFMIN(4*sb_y+3, fragment_height-1));
         }
     }
 
@@ -1500,7 +1536,39 @@ static void render_slice(Vp3DecodeContext *s, int slice)
       *     dispatch (slice - 1);
       */
 
-    vp3_draw_horiz_band(s, FFMIN(64*slice + 64-16, s->height-16));
+    vp3_draw_horiz_band(s, FFMIN((32 << s->chroma_y_shift) * (slice + 1) -16, s->height-16));
+}
+
+/// Allocate tables for per-frame data in Vp3DecodeContext
+static av_cold int allocate_tables(AVCodecContext *avctx)
+{
+    Vp3DecodeContext *s = avctx->priv_data;
+    int y_fragment_count, c_fragment_count;
+
+    y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
+    c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
+
+    s->superblock_coding = av_malloc(s->superblock_count);
+    s->all_fragments = av_malloc(s->fragment_count * sizeof(Vp3Fragment));
+    s->coded_fragment_list[0] = av_malloc(s->fragment_count * sizeof(int));
+    s->dct_tokens_base = av_malloc(64*s->fragment_count * sizeof(*s->dct_tokens_base));
+    s->motion_val[0] = av_malloc(y_fragment_count * sizeof(*s->motion_val[0]));
+    s->motion_val[1] = av_malloc(c_fragment_count * sizeof(*s->motion_val[1]));
+
+    /* work out the block mapping tables */
+    s->superblock_fragments = av_malloc(s->superblock_count * 16 * sizeof(int));
+    s->macroblock_coding = av_malloc(s->macroblock_count + 1);
+
+    if (!s->superblock_coding || !s->all_fragments || !s->dct_tokens_base ||
+        !s->coded_fragment_list[0] || !s->superblock_fragments || !s->macroblock_coding ||
+        !s->motion_val[0] || !s->motion_val[1]) {
+        vp3_decode_end(avctx);
+        return -1;
+    }
+
+    init_block_mapping(s);
+
+    return 0;
 }
 
 /*
@@ -1552,7 +1620,6 @@ static av_cold int vp3_decode_init(AVCodecContext *avctx)
     s->superblock_count = s->y_superblock_count + (s->c_superblock_count * 2);
     s->u_superblock_start = s->y_superblock_count;
     s->v_superblock_start = s->u_superblock_start + s->c_superblock_count;
-    s->superblock_coding = av_malloc(s->superblock_count);
 
     s->macroblock_width = (s->width + 15) / 16;
     s->macroblock_height = (s->height + 15) / 16;
@@ -1570,18 +1637,6 @@ static av_cold int vp3_decode_init(AVCodecContext *avctx)
     s->fragment_start[1] = y_fragment_count;
     s->fragment_start[2] = y_fragment_count + c_fragment_count;
 
-    s->all_fragments = av_malloc(s->fragment_count * sizeof(Vp3Fragment));
-    s->coded_fragment_list[0] = av_malloc(s->fragment_count * sizeof(int));
-    s->dct_tokens_base = av_malloc(64*s->fragment_count * sizeof(*s->dct_tokens_base));
-    s->motion_val[0] = av_malloc(y_fragment_count * sizeof(*s->motion_val[0]));
-    s->motion_val[1] = av_malloc(c_fragment_count * sizeof(*s->motion_val[1]));
-
-    if (!s->superblock_coding || !s->all_fragments || !s->dct_tokens_base ||
-        !s->coded_fragment_list[0] || !s->motion_val[0] || !s->motion_val[1]) {
-        vp3_decode_end(avctx);
-        return -1;
-    }
-
     if (!s->theora_tables)
     {
         for (i = 0; i < 64; i++) {
@@ -1681,28 +1736,92 @@ static av_cold int vp3_decode_init(AVCodecContext *avctx)
         &motion_vector_vlc_table[0][1], 2, 1,
         &motion_vector_vlc_table[0][0], 2, 1, 0);
 
-    /* work out the block mapping tables */
-    s->superblock_fragments = av_malloc(s->superblock_count * 16 * sizeof(int));
-    s->macroblock_coding = av_malloc(s->macroblock_count + 1);
-    if (!s->superblock_fragments || !s->macroblock_coding) {
-        vp3_decode_end(avctx);
-        return -1;
-    }
-    init_block_mapping(s);
-
     for (i = 0; i < 3; i++) {
         s->current_frame.data[i] = NULL;
         s->last_frame.data[i] = NULL;
         s->golden_frame.data[i] = NULL;
     }
 
-    return 0;
+    return allocate_tables(avctx);
 
 vlc_fail:
     av_log(avctx, AV_LOG_FATAL, "Invalid huffman table\n");
     return -1;
 }
 
+/// Release and shuffle frames after decode finishes
+static void update_frames(AVCodecContext *avctx)
+{
+    Vp3DecodeContext *s = avctx->priv_data;
+
+    /* release the last frame, if it is allocated and if it is not the
+     * golden frame */
+    if (s->last_frame.data[0] && s->last_frame.type != FF_BUFFER_TYPE_COPY)
+        ff_thread_release_buffer(avctx, &s->last_frame);
+
+    /* shuffle frames (last = current) */
+    s->last_frame= s->current_frame;
+
+    if (s->keyframe) {
+        if (s->golden_frame.data[0])
+            ff_thread_release_buffer(avctx, &s->golden_frame);
+        s->golden_frame = s->current_frame;
+        s->last_frame.type = FF_BUFFER_TYPE_COPY;
+    }
+
+    s->current_frame.data[0]= NULL; /* ensure that we catch any access to this released frame */
+}
+
+static int vp3_update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
+{
+    Vp3DecodeContext *s = dst->priv_data, *s1 = src->priv_data;
+    int qps_changed = 0, i, err;
+
+    if (!s1->current_frame.data[0]
+        ||s->width != s1->width
+        ||s->height!= s1->height)
+        return -1;
+
+    if (s != s1) {
+        // init tables if the first frame hasn't been decoded
+        if (!s->current_frame.data[0]) {
+            int y_fragment_count, c_fragment_count;
+            s->avctx = dst;
+            err = allocate_tables(dst);
+            if (err)
+                return err;
+            y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
+            c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
+            memcpy(s->motion_val[0], s1->motion_val[0], y_fragment_count * sizeof(*s->motion_val[0]));
+            memcpy(s->motion_val[1], s1->motion_val[1], c_fragment_count * sizeof(*s->motion_val[1]));
+        }
+
+#define copy_fields(to, from, start_field, end_field) memcpy(&to->start_field, &from->start_field, (char*)&to->end_field - (char*)&to->start_field)
+
+        // copy previous frame data
+        copy_fields(s, s1, golden_frame, dsp);
+
+        // copy qscale data if necessary
+        for (i = 0; i < 3; i++) {
+            if (s->qps[i] != s1->qps[1]) {
+                qps_changed = 1;
+                memcpy(&s->qmat[i], &s1->qmat[i], sizeof(s->qmat[i]));
+            }
+        }
+
+        if (s->qps[0] != s1->qps[0])
+            memcpy(&s->bounding_values_array, &s1->bounding_values_array, sizeof(s->bounding_values_array));
+
+        if (qps_changed)
+            copy_fields(s, s1, qps, superblock_count);
+#undef copy_fields
+    }
+
+    update_frames(dst);
+
+    return 0;
+}
+
 /*
  * This is the ffmpeg/libavcodec API frame decode function.
  */
@@ -1714,7 +1833,6 @@ static int vp3_decode_frame(AVCodecContext *avctx,
     int buf_size = avpkt->size;
     Vp3DecodeContext *s = avctx->priv_data;
     GetBitContext gb;
-    static int counter = 0;
     int i;
 
     init_get_bits(&gb, buf, buf_size * 8);
@@ -1740,8 +1858,10 @@ static int vp3_decode_frame(AVCodecContext *avctx,
 
     if (s->avctx->debug & FF_DEBUG_PICT_INFO)
         av_log(s->avctx, AV_LOG_INFO, " VP3 %sframe #%d: Q index = %d\n",
-            s->keyframe?"key":"", counter, s->qps[0]);
-    counter++;
+            s->keyframe?"key":"", avctx->frame_number+1, s->qps[0]);
+
+    s->skip_loop_filter = !s->filter_limit_values[s->qps[0]] ||
+        avctx->skip_loop_filter >= (s->keyframe ? AVDISCARD_ALL : AVDISCARD_NONKEY);
 
     if (s->qps[0] != s->last_qps[0])
         init_loop_filter(s);
@@ -1757,11 +1877,14 @@ static int vp3_decode_frame(AVCodecContext *avctx,
 
     s->current_frame.reference = 3;
     s->current_frame.pict_type = s->keyframe ? FF_I_TYPE : FF_P_TYPE;
-    if (avctx->get_buffer(avctx, &s->current_frame) < 0) {
+    if (ff_thread_get_buffer(avctx, &s->current_frame) < 0) {
         av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
         goto error;
     }
 
+    if (!s->edge_emu_buffer)
+        s->edge_emu_buffer = av_malloc(9*FFABS(s->current_frame.linesize[0]));
+
     if (s->keyframe) {
         if (!s->theora)
         {
@@ -1770,7 +1893,7 @@ static int vp3_decode_frame(AVCodecContext *avctx,
             if (s->version)
             {
                 s->version = get_bits(&gb, 5);
-                if (counter == 1)
+                if (avctx->frame_number == 0)
                     av_log(s->avctx, AV_LOG_DEBUG, "VP version: %d\n", s->version);
             }
         }
@@ -1786,19 +1909,18 @@ static int vp3_decode_frame(AVCodecContext *avctx,
 
             s->golden_frame.reference = 3;
             s->golden_frame.pict_type = FF_I_TYPE;
-            if (avctx->get_buffer(avctx, &s->golden_frame) < 0) {
+            if (ff_thread_get_buffer(avctx, &s->golden_frame) < 0) {
                 av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
                 goto error;
             }
             s->last_frame = s->golden_frame;
             s->last_frame.type = FF_BUFFER_TYPE_COPY;
+            ff_thread_report_progress(&s->last_frame, INT_MAX, 0);
         }
     }
 
-    s->current_frame.qscale_table= s->qscale_table; //FIXME allocate individual tables per AVFrame
-    s->current_frame.qstride= 0;
-
     memset(s->all_fragments, 0, s->fragment_count * sizeof(Vp3Fragment));
+    ff_thread_finish_setup(avctx);
 
     if (unpack_superblocks(s, &gb)){
         av_log(s->avctx, AV_LOG_ERROR, "error in unpack_superblocks\n");
@@ -1838,33 +1960,22 @@ static int vp3_decode_frame(AVCodecContext *avctx,
         int row = (s->height >> (3+(i && s->chroma_y_shift))) - 1;
         apply_loop_filter(s, i, row, row+1);
     }
-    vp3_draw_horiz_band(s, s->height);
+    vp3_draw_horiz_band(s, s->avctx->height);
 
     *data_size=sizeof(AVFrame);
     *(AVFrame*)data= s->current_frame;
 
-    /* release the last frame, if it is allocated and if it is not the
-     * golden frame */
-    if (s->last_frame.data[0] && s->last_frame.type != FF_BUFFER_TYPE_COPY)
-        avctx->release_buffer(avctx, &s->last_frame);
-
-    /* shuffle frames (last = current) */
-    s->last_frame= s->current_frame;
-
-    if (s->keyframe) {
-        if (s->golden_frame.data[0])
-            avctx->release_buffer(avctx, &s->golden_frame);
-        s->golden_frame = s->current_frame;
-        s->last_frame.type = FF_BUFFER_TYPE_COPY;
-    }
-
-    s->current_frame.data[0]= NULL; /* ensure that we catch any access to this released frame */
+    if (!HAVE_PTHREADS || !(s->avctx->active_thread_type&FF_THREAD_FRAME))
+        update_frames(avctx);
 
     return buf_size;
 
 error:
-    if (s->current_frame.data[0])
+    ff_thread_report_progress(&s->current_frame, INT_MAX, 0);
+
+    if (!HAVE_PTHREADS || !(s->avctx->active_thread_type&FF_THREAD_FRAME))
         avctx->release_buffer(avctx, &s->current_frame);
+
     return -1;
 }
 
@@ -1876,6 +1987,9 @@ static av_cold int vp3_decode_end(AVCodecContext *avctx)
     Vp3DecodeContext *s = avctx->priv_data;
     int i;
 
+    if (avctx->is_copy && !s->current_frame.data[0])
+        return 0;
+
     av_free(s->superblock_coding);
     av_free(s->all_fragments);
     av_free(s->coded_fragment_list[0]);
@@ -1884,6 +1998,9 @@ static av_cold int vp3_decode_end(AVCodecContext *avctx)
     av_free(s->macroblock_coding);
     av_free(s->motion_val[0]);
     av_free(s->motion_val[1]);
+    av_free(s->edge_emu_buffer);
+
+    if (avctx->is_copy) return 0;
 
     for (i = 0; i < 16; i++) {
         free_vlc(&s->dc_vlc[i]);
@@ -1900,9 +2017,9 @@ static av_cold int vp3_decode_end(AVCodecContext *avctx)
 
     /* release all frames */
     if (s->golden_frame.data[0])
-        avctx->release_buffer(avctx, &s->golden_frame);
+        ff_thread_release_buffer(avctx, &s->golden_frame);
     if (s->last_frame.data[0] && s->last_frame.type != FF_BUFFER_TYPE_COPY)
-        avctx->release_buffer(avctx, &s->last_frame);
+        ff_thread_release_buffer(avctx, &s->last_frame);
     /* no need to release the current_frame since it will always be pointing
      * to the same frame as either the golden or last frame */
 
@@ -1953,7 +2070,7 @@ static int theora_decode_header(AVCodecContext *avctx, GetBitContext *gb)
     Vp3DecodeContext *s = avctx->priv_data;
     int visible_width, visible_height, colorspace;
     int offset_x = 0, offset_y = 0;
-    AVRational fps;
+    AVRational fps, aspect;
 
     s->theora = get_bits_long(gb, 24);
     av_log(avctx, AV_LOG_DEBUG, "Theora bitstream version %X\n", s->theora);
@@ -1969,7 +2086,7 @@ static int theora_decode_header(AVCodecContext *avctx, GetBitContext *gb)
     visible_width  = s->width  = get_bits(gb, 16) << 4;
     visible_height = s->height = get_bits(gb, 16) << 4;
 
-    if(avcodec_check_dimensions(avctx, s->width, s->height)){
+    if(av_image_check_size(s->width, s->height, 0, avctx)){
         av_log(avctx, AV_LOG_ERROR, "Invalid dimensions (%dx%d)\n", s->width, s->height);
         s->width= s->height= 0;
         return -1;
@@ -1990,8 +2107,13 @@ static int theora_decode_header(AVCodecContext *avctx, GetBitContext *gb)
                   fps.den, fps.num, 1<<30);
     }
 
-    avctx->sample_aspect_ratio.num = get_bits_long(gb, 24);
-    avctx->sample_aspect_ratio.den = get_bits_long(gb, 24);
+    aspect.num = get_bits_long(gb, 24);
+    aspect.den = get_bits_long(gb, 24);
+    if (aspect.num && aspect.den) {
+        av_reduce(&avctx->sample_aspect_ratio.num,
+                  &avctx->sample_aspect_ratio.den,
+                  aspect.num, aspect.den, 1<<30);
+    }
 
     if (s->theora < 0x030200)
         skip_bits(gb, 5); /* keyframe frequency force */
@@ -2037,13 +2159,9 @@ static int theora_decode_tables(AVCodecContext *avctx, GetBitContext *gb)
     if (s->theora >= 0x030200) {
         n = get_bits(gb, 3);
         /* loop filter limit values table */
-        for (i = 0; i < 64; i++) {
-            s->filter_limit_values[i] = get_bits(gb, n);
-            if (s->filter_limit_values[i] > 127) {
-                av_log(avctx, AV_LOG_ERROR, "filter limit value too large (%i > 127), clamping\n", s->filter_limit_values[i]);
-                s->filter_limit_values[i] = 127;
-            }
-        }
+        if (n)
+            for (i = 0; i < 64; i++)
+                s->filter_limit_values[i] = get_bits(gb, n);
     }
 
     if (s->theora >= 0x030200)
@@ -2203,7 +2321,7 @@ static av_cold int theora_decode_init(AVCodecContext *avctx)
     return vp3_decode_init(avctx);
 }
 
-AVCodec theora_decoder = {
+AVCodec ff_theora_decoder = {
     "theora",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_THEORA,
@@ -2212,13 +2330,14 @@ AVCodec theora_decoder = {
     NULL,
     vp3_decode_end,
     vp3_decode_frame,
-    CODEC_CAP_DR1 | CODEC_CAP_DRAW_HORIZ_BAND,
+    CODEC_CAP_DR1 | CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_FRAME_THREADS,
     NULL,
     .long_name = NULL_IF_CONFIG_SMALL("Theora"),
+    .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context)
 };
 #endif
 
-AVCodec vp3_decoder = {
+AVCodec ff_vp3_decoder = {
     "vp3",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_VP3,
@@ -2227,7 +2346,8 @@ AVCodec vp3_decoder = {
     NULL,
     vp3_decode_end,
     vp3_decode_frame,
-    CODEC_CAP_DR1 | CODEC_CAP_DRAW_HORIZ_BAND,
+    CODEC_CAP_DR1 | CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_FRAME_THREADS,
     NULL,
     .long_name = NULL_IF_CONFIG_SMALL("On2 VP3"),
+    .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context)
 };
diff --git a/libavcodec/vp3_parser.c b/libavcodec/vp3_parser.c
index c22e6dd..3a9428f 100644
--- a/libavcodec/vp3_parser.c
+++ b/libavcodec/vp3_parser.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (C) 2008 Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -35,7 +35,7 @@ static int parse(AVCodecParserContext *s,
     return buf_size;
 }
 
-AVCodecParser vp3_parser = {
+AVCodecParser ff_vp3_parser = {
     { CODEC_ID_THEORA, CODEC_ID_VP3,
       CODEC_ID_VP6,    CODEC_ID_VP6F, CODEC_ID_VP6A },
     0,
diff --git a/libavcodec/vp3data.h b/libavcodec/vp3data.h
index 904ec6a..54d5a6c 100644
--- a/libavcodec/vp3data.h
+++ b/libavcodec/vp3data.h
@@ -1,20 +1,20 @@
 /*
  * copyright (C) 2003 the ffmpeg project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/vp3dsp.c b/libavcodec/vp3dsp.c
index 058eb56..baa22a5 100644
--- a/libavcodec/vp3dsp.c
+++ b/libavcodec/vp3dsp.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (C) 2004 the ffmpeg project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -224,20 +224,18 @@ void ff_vp3_idct_add_c(uint8_t *dest/*align 8*/, int line_size, DCTELEM *block/*
 }
 
 void ff_vp3_idct_dc_add_c(uint8_t *dest/*align 8*/, int line_size, const DCTELEM *block/*align 16*/){
-    const uint8_t *cm = ff_cropTbl + MAX_NEG_CROP;
-    int i, dc = block[0];
-    dc = (46341*dc)>>16;
-    dc = (46341*dc + (8<<16))>>20;
+    int i, dc = (block[0] + 15) >> 5;
+    const uint8_t *cm = ff_cropTbl + MAX_NEG_CROP + dc;
 
     for(i = 0; i < 8; i++){
-        dest[0] = cm[dest[0]+dc];
-        dest[1] = cm[dest[1]+dc];
-        dest[2] = cm[dest[2]+dc];
-        dest[3] = cm[dest[3]+dc];
-        dest[4] = cm[dest[4]+dc];
-        dest[5] = cm[dest[5]+dc];
-        dest[6] = cm[dest[6]+dc];
-        dest[7] = cm[dest[7]+dc];
+        dest[0] = cm[dest[0]];
+        dest[1] = cm[dest[1]];
+        dest[2] = cm[dest[2]];
+        dest[3] = cm[dest[3]];
+        dest[4] = cm[dest[4]];
+        dest[5] = cm[dest[5]];
+        dest[6] = cm[dest[6]];
+        dest[7] = cm[dest[7]];
         dest += line_size;
     }
 }
diff --git a/libavcodec/vp5.c b/libavcodec/vp5.c
index 1479344..807309f 100644
--- a/libavcodec/vp5.c
+++ b/libavcodec/vp5.c
@@ -4,20 +4,20 @@
  *
  * Copyright (C) 2006  Aurelien Jacobs <aurel at gnuage.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -39,10 +39,10 @@ static int vp5_parse_header(VP56Context *s, const uint8_t *buf, int buf_size,
     VP56RangeCoder *c = &s->c;
     int rows, cols;
 
-    vp56_init_range_decoder(&s->c, buf, buf_size);
+    ff_vp56_init_range_decoder(&s->c, buf, buf_size);
     s->framep[VP56_FRAME_CURRENT]->key_frame = !vp56_rac_get(c);
     vp56_rac_get(c);
-    vp56_init_dequant(s, vp56_rac_gets(c, 6));
+    ff_vp56_init_dequant(s, vp56_rac_gets(c, 6));
     if (s->framep[VP56_FRAME_CURRENT]->key_frame)
     {
         vp56_rac_gets(c, 8);
@@ -254,7 +254,7 @@ static av_cold int vp5_decode_init(AVCodecContext *avctx)
 {
     VP56Context *s = avctx->priv_data;
 
-    vp56_init(avctx, 1, 0);
+    ff_vp56_init(avctx, 1, 0);
     s->vp56_coord_div = vp5_coord_div;
     s->parse_vector_adjustment = vp5_parse_vector_adjustment;
     s->parse_coeff = vp5_parse_coeff;
@@ -266,15 +266,15 @@ static av_cold int vp5_decode_init(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec vp5_decoder = {
+AVCodec ff_vp5_decoder = {
     "vp5",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_VP5,
     sizeof(VP56Context),
     vp5_decode_init,
     NULL,
-    vp56_free,
-    vp56_decode_frame,
+    ff_vp56_free,
+    ff_vp56_decode_frame,
     CODEC_CAP_DR1,
     .long_name = NULL_IF_CONFIG_SMALL("On2 VP5"),
 };
diff --git a/libavcodec/vp56.c b/libavcodec/vp56.c
index 74fe5ff..63373d3 100644
--- a/libavcodec/vp56.c
+++ b/libavcodec/vp56.c
@@ -4,20 +4,20 @@
  *
  * Copyright (C) 2006  Aurelien Jacobs <aurel at gnuage.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -28,7 +28,7 @@
 #include "vp56data.h"
 
 
-void vp56_init_dequant(VP56Context *s, int quantizer)
+void ff_vp56_init_dequant(VP56Context *s, int quantizer)
 {
     s->quantizer = quantizer;
     s->dequant_dc = vp56_dc_dequant[quantizer] << 2;
@@ -337,7 +337,7 @@ static void vp56_mc(VP56Context *s, int b, int plane, uint8_t *src,
 
     if (x<0 || x+12>=s->plane_width[plane] ||
         y<0 || y+12>=s->plane_height[plane]) {
-        ff_emulated_edge_mc(s->edge_emu_buffer,
+        s->dsp.emulated_edge_mc(s->edge_emu_buffer,
                             src + s->block_offset[b] + (dy-2)*stride + (dx-2),
                             stride, 12, 12, x, y,
                             s->plane_width[plane],
@@ -481,8 +481,8 @@ static int vp56_size_changed(AVCodecContext *avctx)
     return 0;
 }
 
-int vp56_decode_frame(AVCodecContext *avctx, void *data, int *data_size,
-                      AVPacket *avpkt)
+int ff_vp56_decode_frame(AVCodecContext *avctx, void *data, int *data_size,
+                         AVPacket *avpkt)
 {
     const uint8_t *buf = avpkt->data;
     VP56Context *s = avctx->priv_data;
@@ -639,7 +639,7 @@ int vp56_decode_frame(AVCodecContext *avctx, void *data, int *data_size,
     return avpkt->size;
 }
 
-av_cold void vp56_init(AVCodecContext *avctx, int flip, int has_alpha)
+av_cold void ff_vp56_init(AVCodecContext *avctx, int flip, int has_alpha)
 {
     VP56Context *s = avctx->priv_data;
     int i;
@@ -678,7 +678,7 @@ av_cold void vp56_init(AVCodecContext *avctx, int flip, int has_alpha)
     }
 }
 
-av_cold int vp56_free(AVCodecContext *avctx)
+av_cold int ff_vp56_free(AVCodecContext *avctx)
 {
     VP56Context *s = avctx->priv_data;
 
diff --git a/libavcodec/vp56.h b/libavcodec/vp56.h
index 89eba05..5a55f7d 100644
--- a/libavcodec/vp56.h
+++ b/libavcodec/vp56.h
@@ -4,20 +4,20 @@
  *
  * Copyright (C) 2006  Aurelien Jacobs <aurel at gnuage.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -28,10 +28,15 @@
 #include "dsputil.h"
 #include "get_bits.h"
 #include "bytestream.h"
+#include "cabac.h"
 #include "vp56dsp.h"
 
 typedef struct vp56_context VP56Context;
-typedef struct vp56_mv VP56mv;
+
+typedef struct {
+    int16_t x;
+    int16_t y;
+} DECLARE_ALIGNED(4, , VP56mv);
 
 typedef void (*VP56ParseVectorAdjustment)(VP56Context *s,
                                           VP56mv *vect);
@@ -47,10 +52,11 @@ typedef int  (*VP56ParseHeader)(VP56Context *s, const uint8_t *buf,
 
 typedef struct {
     int high;
-    int bits;
+    int bits; /* stored negated (i.e. negative "bits" is a positive number of
+                 bits left) in order to eliminate a negate in cache refilling */
     const uint8_t *buffer;
     const uint8_t *end;
-    unsigned long code_word;
+    unsigned int code_word;
 } VP56RangeCoder;
 
 typedef struct {
@@ -59,11 +65,6 @@ typedef struct {
     DCTELEM dc_coeff;
 } VP56RefDc;
 
-struct vp56_mv {
-    int x;
-    int y;
-};
-
 typedef struct {
     uint8_t type;
     VP56mv mv;
@@ -169,75 +170,104 @@ struct vp56_context {
 };
 
 
-void vp56_init(AVCodecContext *avctx, int flip, int has_alpha);
-int vp56_free(AVCodecContext *avctx);
-void vp56_init_dequant(VP56Context *s, int quantizer);
-int vp56_decode_frame(AVCodecContext *avctx, void *data, int *data_size,
-                      AVPacket *avpkt);
+void ff_vp56_init(AVCodecContext *avctx, int flip, int has_alpha);
+int ff_vp56_free(AVCodecContext *avctx);
+void ff_vp56_init_dequant(VP56Context *s, int quantizer);
+int ff_vp56_decode_frame(AVCodecContext *avctx, void *data, int *data_size,
+                         AVPacket *avpkt);
 
 
 /**
  * vp56 specific range coder implementation
  */
 
-static inline void vp56_init_range_decoder(VP56RangeCoder *c,
-                                           const uint8_t *buf, int buf_size)
+extern const uint8_t ff_vp56_norm_shift[256];
+void ff_vp56_init_range_decoder(VP56RangeCoder *c, const uint8_t *buf, int buf_size);
+
+static av_always_inline unsigned int vp56_rac_renorm(VP56RangeCoder *c)
 {
-    c->high = 255;
-    c->bits = 8;
-    c->buffer = buf;
-    c->end = buf + buf_size;
-    c->code_word = bytestream_get_be16(&c->buffer);
+    int shift = ff_vp56_norm_shift[c->high];
+    int bits = c->bits;
+    unsigned int code_word = c->code_word;
+
+    c->high   <<= shift;
+    code_word <<= shift;
+    bits       += shift;
+    if(bits >= 0 && c->buffer < c->end) {
+        code_word |= bytestream_get_be16(&c->buffer) << bits;
+        bits -= 16;
+    }
+    c->bits = bits;
+    return code_word;
 }
 
-static inline int vp56_rac_get_prob(VP56RangeCoder *c, uint8_t prob)
+#if   ARCH_ARM
+#include "arm/vp56_arith.h"
+#elif ARCH_X86
+#include "x86/vp56_arith.h"
+#endif
+
+#ifndef vp56_rac_get_prob
+#define vp56_rac_get_prob vp56_rac_get_prob
+static av_always_inline int vp56_rac_get_prob(VP56RangeCoder *c, uint8_t prob)
 {
-    unsigned int low = 1 + (((c->high - 1) * prob) / 256);
-    unsigned int low_shift = low << 8;
-    int bit = c->code_word >= low_shift;
+    unsigned int code_word = vp56_rac_renorm(c);
+    unsigned int low = 1 + (((c->high - 1) * prob) >> 8);
+    unsigned int low_shift = low << 16;
+    int bit = code_word >= low_shift;
 
-    if (bit) {
-        c->high -= low;
-        c->code_word -= low_shift;
-    } else {
-        c->high = low;
-    }
+    c->high = bit ? c->high - low : low;
+    c->code_word = bit ? code_word - low_shift : code_word;
 
-    /* normalize */
-    while (c->high < 128) {
-        c->high <<= 1;
-        c->code_word <<= 1;
-        if (--c->bits == 0 && c->buffer < c->end) {
-            c->bits = 8;
-            c->code_word |= *c->buffer++;
-        }
-    }
     return bit;
 }
+#endif
+
+#ifndef vp56_rac_get_prob_branchy
+// branchy variant, to be used where there's a branch based on the bit decoded
+static av_always_inline int vp56_rac_get_prob_branchy(VP56RangeCoder *c, int prob)
+{
+    unsigned long code_word = vp56_rac_renorm(c);
+    unsigned low = 1 + (((c->high - 1) * prob) >> 8);
+    unsigned low_shift = low << 16;
+
+    if (code_word >= low_shift) {
+        c->high     -= low;
+        c->code_word = code_word - low_shift;
+        return 1;
+    }
+
+    c->high = low;
+    c->code_word = code_word;
+    return 0;
+}
+#endif
 
-static inline int vp56_rac_get(VP56RangeCoder *c)
+static av_always_inline int vp56_rac_get(VP56RangeCoder *c)
 {
+    unsigned int code_word = vp56_rac_renorm(c);
     /* equiprobable */
     int low = (c->high + 1) >> 1;
-    unsigned int low_shift = low << 8;
-    int bit = c->code_word >= low_shift;
+    unsigned int low_shift = low << 16;
+    int bit = code_word >= low_shift;
     if (bit) {
-        c->high = (c->high - low) << 1;
-        c->code_word -= low_shift;
+        c->high   -= low;
+        code_word -= low_shift;
     } else {
-        c->high = low << 1;
+        c->high = low;
     }
 
-    /* normalize */
-    c->code_word <<= 1;
-    if (--c->bits == 0 && c->buffer < c->end) {
-        c->bits = 8;
-        c->code_word |= *c->buffer++;
-    }
+    c->code_word = code_word;
     return bit;
 }
 
-static inline int vp56_rac_gets(VP56RangeCoder *c, int bits)
+// rounding is different than vp56_rac_get, is vp56_rac_get wrong?
+static av_always_inline int vp8_rac_get(VP56RangeCoder *c)
+{
+    return vp56_rac_get_prob(c, 128);
+}
+
+static av_unused int vp56_rac_gets(VP56RangeCoder *c, int bits)
 {
     int value = 0;
 
@@ -248,15 +278,50 @@ static inline int vp56_rac_gets(VP56RangeCoder *c, int bits)
     return value;
 }
 
-static inline int vp56_rac_gets_nn(VP56RangeCoder *c, int bits)
+static av_unused int vp8_rac_get_uint(VP56RangeCoder *c, int bits)
+{
+    int value = 0;
+
+    while (bits--) {
+        value = (value << 1) | vp8_rac_get(c);
+    }
+
+    return value;
+}
+
+// fixme: add 1 bit to all the calls to this?
+static av_unused int vp8_rac_get_sint(VP56RangeCoder *c, int bits)
+{
+    int v;
+
+    if (!vp8_rac_get(c))
+        return 0;
+
+    v = vp8_rac_get_uint(c, bits);
+
+    if (vp8_rac_get(c))
+        v = -v;
+
+    return v;
+}
+
+// P(7)
+static av_unused int vp56_rac_gets_nn(VP56RangeCoder *c, int bits)
 {
     int v = vp56_rac_gets(c, 7) << 1;
     return v + !v;
 }
 
-static inline int vp56_rac_get_tree(VP56RangeCoder *c,
-                                    const VP56Tree *tree,
-                                    const uint8_t *probs)
+static av_unused int vp8_rac_get_nn(VP56RangeCoder *c)
+{
+    int v = vp8_rac_get_uint(c, 7) << 1;
+    return v + !v;
+}
+
+static av_always_inline
+int vp56_rac_get_tree(VP56RangeCoder *c,
+                      const VP56Tree *tree,
+                      const uint8_t *probs)
 {
     while (tree->val > 0) {
         if (vp56_rac_get_prob(c, probs[tree->prob_idx]))
@@ -267,4 +332,41 @@ static inline int vp56_rac_get_tree(VP56RangeCoder *c,
     return -tree->val;
 }
 
+/**
+ * This is identical to vp8_rac_get_tree except for the possibility of starting
+ * on a node other than the root node, needed for coeff decode where this is
+ * used to save a bit after a 0 token (by disallowing EOB to immediately follow.)
+ */
+static av_always_inline
+int vp8_rac_get_tree_with_offset(VP56RangeCoder *c, const int8_t (*tree)[2],
+                                 const uint8_t *probs, int i)
+{
+    do {
+        i = tree[i][vp56_rac_get_prob(c, probs[i])];
+    } while (i > 0);
+
+    return -i;
+}
+
+// how probabilities are associated with decisions is different I think
+// well, the new scheme fits in the old but this way has one fewer branches per decision
+static av_always_inline
+int vp8_rac_get_tree(VP56RangeCoder *c, const int8_t (*tree)[2],
+                     const uint8_t *probs)
+{
+    return vp8_rac_get_tree_with_offset(c, tree, probs, 0);
+}
+
+// DCTextra
+static av_always_inline int vp8_rac_get_coeff(VP56RangeCoder *c, const uint8_t *prob)
+{
+    int v = 0;
+
+    do {
+        v = (v<<1) + vp56_rac_get_prob(c, *prob++);
+    } while (*prob);
+
+    return v;
+}
+
 #endif /* AVCODEC_VP56_H */
diff --git a/libavcodec/vp56data.c b/libavcodec/vp56data.c
index b0515c2..7a41876 100644
--- a/libavcodec/vp56data.c
+++ b/libavcodec/vp56data.c
@@ -4,20 +4,20 @@
  *
  * Copyright (C) 2006  Aurelien Jacobs <aurel at gnuage.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/vp56data.h b/libavcodec/vp56data.h
index 57b0968..7be5921 100644
--- a/libavcodec/vp56data.h
+++ b/libavcodec/vp56data.h
@@ -4,20 +4,20 @@
  *
  * Copyright (C) 2006  Aurelien Jacobs <aurel at gnuage.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/vp56dsp.c b/libavcodec/vp56dsp.c
index 9eb9299..7b4a771 100644
--- a/libavcodec/vp56dsp.c
+++ b/libavcodec/vp56dsp.c
@@ -2,20 +2,20 @@
  * Copyright (c) 2006 Aurelien Jacobs <aurel at gnuage.org>
  * Copyright (c) 2010 Mans Rullgard <mans at mansr.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -82,7 +82,12 @@ void ff_vp56dsp_init(VP56DSPContext *s, enum CodecID codec)
     } else {
         s->edge_filter_hor = vp6_edge_filter_hor;
         s->edge_filter_ver = vp6_edge_filter_ver;
+
+        if (CONFIG_VP6_DECODER) {
+            s->vp6_filter_diag4 = ff_vp6_filter_diag4_c;
+        }
     }
 
     if (ARCH_ARM) ff_vp56dsp_init_arm(s, codec);
+    if (HAVE_MMX) ff_vp56dsp_init_x86(s, codec);
 }
diff --git a/libavcodec/vp56dsp.h b/libavcodec/vp56dsp.h
index 2d6941f..3bd6d27 100644
--- a/libavcodec/vp56dsp.h
+++ b/libavcodec/vp56dsp.h
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2010 Mans Rullgard <mans at mansr.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -22,13 +22,21 @@
 #define AVCODEC_VP56DSP_H
 
 #include <stdint.h>
+#include "avcodec.h"
 
 typedef struct VP56DSPContext {
     void (*edge_filter_hor)(uint8_t *yuv, int stride, int t);
     void (*edge_filter_ver)(uint8_t *yuv, int stride, int t);
+
+    void (*vp6_filter_diag4)(uint8_t *dst, uint8_t *src, int stride,
+                             const int16_t *h_weights,const int16_t *v_weights);
 } VP56DSPContext;
 
+void ff_vp6_filter_diag4_c(uint8_t *dst, uint8_t *src, int stride,
+                           const int16_t *h_weights, const int16_t *v_weights);
+
 void ff_vp56dsp_init(VP56DSPContext *s, enum CodecID codec);
 void ff_vp56dsp_init_arm(VP56DSPContext *s, enum CodecID codec);
+void ff_vp56dsp_init_x86(VP56DSPContext* c, enum CodecID codec);
 
 #endif /* AVCODEC_VP56DSP_H */
diff --git a/libavcodec/vp56rac.c b/libavcodec/vp56rac.c
new file mode 100644
index 0000000..c009cad
--- /dev/null
+++ b/libavcodec/vp56rac.c
@@ -0,0 +1,47 @@
+/*
+ * VP5/6/8 decoder
+ * Copyright (c) 2010 Jason Garrett-Glaser <darkshikari at gmail.com>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "libavutil/common.h"
+#include "vp56.h"
+
+const uint8_t ff_vp56_norm_shift[256]= {
+ 8,7,6,6,5,5,5,5,4,4,4,4,4,4,4,4,
+ 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
+ 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
+ 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
+ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
+ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
+ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
+ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+};
+
+void ff_vp56_init_range_decoder(VP56RangeCoder *c, const uint8_t *buf, int buf_size)
+{
+    c->high = 255;
+    c->bits = -16;
+    c->buffer = buf;
+    c->end = buf + buf_size;
+    c->code_word = bytestream_get_be24(&c->buffer);
+}
diff --git a/libavcodec/vp5data.h b/libavcodec/vp5data.h
index 5c2d46c..11144a3 100644
--- a/libavcodec/vp5data.h
+++ b/libavcodec/vp5data.h
@@ -4,20 +4,20 @@
  *
  * Copyright (C) 2006  Aurelien Jacobs <aurel at gnuage.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/vp6.c b/libavcodec/vp6.c
index 58c31f9..4f3f402 100644
--- a/libavcodec/vp6.c
+++ b/libavcodec/vp6.c
@@ -8,20 +8,20 @@
  *  - upper 4bits: difference between encoded width and visible width
  *  - lower 4bits: difference between encoded height and visible height
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -36,6 +36,7 @@
 #include "vp56data.h"
 #include "vp6data.h"
 
+#define VP6_MAX_HUFF_SIZE 12
 
 static void vp6_parse_coeff(VP56Context *s);
 static void vp6_parse_coeff_huffman(VP56Context *s);
@@ -53,7 +54,7 @@ static int vp6_parse_header(VP56Context *s, const uint8_t *buf, int buf_size,
     int separated_coeff = buf[0] & 1;
 
     s->framep[VP56_FRAME_CURRENT]->key_frame = !(buf[0] & 0x80);
-    vp56_init_dequant(s, (buf[0] >> 1) & 0x3F);
+    ff_vp56_init_dequant(s, (buf[0] >> 1) & 0x3F);
 
     if (s->framep[VP56_FRAME_CURRENT]->key_frame) {
         sub_version = buf[1] >> 3;
@@ -86,7 +87,7 @@ static int vp6_parse_header(VP56Context *s, const uint8_t *buf, int buf_size,
             res = 2;
         }
 
-        vp56_init_range_decoder(c, buf+6, buf_size-6);
+        ff_vp56_init_range_decoder(c, buf+6, buf_size-6);
         vp56_rac_gets(c, 2);
 
         parse_filter_info = s->filter_header;
@@ -102,7 +103,7 @@ static int vp6_parse_header(VP56Context *s, const uint8_t *buf, int buf_size,
             buf += 2;
             buf_size -= 2;
         }
-        vp56_init_range_decoder(c, buf+1, buf_size-1);
+        ff_vp56_init_range_decoder(c, buf+1, buf_size-1);
 
         *golden_frame = vp56_rac_get(c);
         if (s->filter_header) {
@@ -142,7 +143,7 @@ static int vp6_parse_header(VP56Context *s, const uint8_t *buf, int buf_size,
             s->parse_coeff = vp6_parse_coeff_huffman;
             init_get_bits(&s->gb, buf, buf_size<<3);
         } else {
-            vp56_init_range_decoder(&s->cc, buf, buf_size);
+            ff_vp56_init_range_decoder(&s->cc, buf, buf_size);
             s->ccp = &s->cc;
         }
     } else {
@@ -215,7 +216,7 @@ static int vp6_huff_cmp(const void *va, const void *vb)
 static void vp6_build_huff_tree(VP56Context *s, uint8_t coeff_model[],
                                 const uint8_t *map, unsigned size, VLC *vlc)
 {
-    Node nodes[2*size], *tmp = &nodes[size];
+    Node nodes[2*VP6_MAX_HUFF_SIZE], *tmp = &nodes[size];
     int a, b, i;
 
     /* first compute probabilities from model */
@@ -558,7 +559,7 @@ static void vp6_filter(VP56Context *s, uint8_t *dst, uint8_t *src,
             vp6_filter_hv4(dst, src+offset1, stride, stride,
                            vp6_block_copy_filter[select][y8]);
         } else {
-            s->dsp.vp6_filter_diag4(dst, src+offset1+((mv.x^mv.y)>>31), stride,
+            s->vp56dsp.vp6_filter_diag4(dst, src+offset1+((mv.x^mv.y)>>31), stride,
                              vp6_block_copy_filter[select][x8],
                              vp6_block_copy_filter[select][y8]);
         }
@@ -575,8 +576,8 @@ static av_cold int vp6_decode_init(AVCodecContext *avctx)
 {
     VP56Context *s = avctx->priv_data;
 
-    vp56_init(avctx, avctx->codec->id == CODEC_ID_VP6,
-                     avctx->codec->id == CODEC_ID_VP6A);
+    ff_vp56_init(avctx, avctx->codec->id == CODEC_ID_VP6,
+                        avctx->codec->id == CODEC_ID_VP6A);
     s->vp56_coord_div = vp6_coord_div;
     s->parse_vector_adjustment = vp6_parse_vector_adjustment;
     s->filter = vp6_filter;
@@ -593,7 +594,7 @@ static av_cold int vp6_decode_free(AVCodecContext *avctx)
     VP56Context *s = avctx->priv_data;
     int pt, ct, cg;
 
-    vp56_free(avctx);
+    ff_vp56_free(avctx);
 
     for (pt=0; pt<2; pt++) {
         free_vlc(&s->dccv_vlc[pt]);
@@ -605,7 +606,7 @@ static av_cold int vp6_decode_free(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec vp6_decoder = {
+AVCodec ff_vp6_decoder = {
     "vp6",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_VP6,
@@ -613,13 +614,13 @@ AVCodec vp6_decoder = {
     vp6_decode_init,
     NULL,
     vp6_decode_free,
-    vp56_decode_frame,
+    ff_vp56_decode_frame,
     CODEC_CAP_DR1,
     .long_name = NULL_IF_CONFIG_SMALL("On2 VP6"),
 };
 
 /* flash version, not flipped upside-down */
-AVCodec vp6f_decoder = {
+AVCodec ff_vp6f_decoder = {
     "vp6f",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_VP6F,
@@ -627,13 +628,13 @@ AVCodec vp6f_decoder = {
     vp6_decode_init,
     NULL,
     vp6_decode_free,
-    vp56_decode_frame,
+    ff_vp56_decode_frame,
     CODEC_CAP_DR1,
     .long_name = NULL_IF_CONFIG_SMALL("On2 VP6 (Flash version)"),
 };
 
 /* flash version, not flipped upside-down, with alpha channel */
-AVCodec vp6a_decoder = {
+AVCodec ff_vp6a_decoder = {
     "vp6a",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_VP6A,
@@ -641,7 +642,7 @@ AVCodec vp6a_decoder = {
     vp6_decode_init,
     NULL,
     vp6_decode_free,
-    vp56_decode_frame,
+    ff_vp56_decode_frame,
     CODEC_CAP_DR1,
     .long_name = NULL_IF_CONFIG_SMALL("On2 VP6 (Flash version, with alpha channel)"),
 };
diff --git a/libavcodec/vp6data.h b/libavcodec/vp6data.h
index 1cfdbe7..2ba3ef3 100644
--- a/libavcodec/vp6data.h
+++ b/libavcodec/vp6data.h
@@ -4,20 +4,20 @@
  *
  * Copyright (C) 2006  Aurelien Jacobs <aurel at gnuage.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/vp6dsp.c b/libavcodec/vp6dsp.c
index 69a11ee..64282a5 100644
--- a/libavcodec/vp6dsp.c
+++ b/libavcodec/vp6dsp.c
@@ -4,25 +4,25 @@
  *
  * Copyright (C) 2006  Aurelien Jacobs <aurel at gnuage.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "libavutil/common.h"
-#include "dsputil.h"
+#include "vp56dsp.h"
 
 
 void ff_vp6_filter_diag4_c(uint8_t *dst, uint8_t *src, int stride,
diff --git a/libavcodec/vp8.c b/libavcodec/vp8.c
new file mode 100644
index 0000000..de4a51d
--- /dev/null
+++ b/libavcodec/vp8.c
@@ -0,0 +1,1686 @@
+/**
+ * VP8 compatible video decoder
+ *
+ * Copyright (C) 2010 David Conrad
+ * Copyright (C) 2010 Ronald S. Bultje
+ * Copyright (C) 2010 Jason Garrett-Glaser
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "libavutil/imgutils.h"
+#include "avcodec.h"
+#include "vp8.h"
+#include "vp8data.h"
+#include "rectangle.h"
+
+#if ARCH_ARM
+#   include "arm/vp8.h"
+#endif
+
+static void vp8_decode_flush(AVCodecContext *avctx)
+{
+    VP8Context *s = avctx->priv_data;
+    int i;
+
+    for (i = 0; i < 4; i++)
+        if (s->frames[i].data[0])
+            avctx->release_buffer(avctx, &s->frames[i]);
+    memset(s->framep, 0, sizeof(s->framep));
+
+    av_freep(&s->macroblocks_base);
+    av_freep(&s->filter_strength);
+    av_freep(&s->intra4x4_pred_mode_top);
+    av_freep(&s->top_nnz);
+    av_freep(&s->edge_emu_buffer);
+    av_freep(&s->top_border);
+    av_freep(&s->segmentation_map);
+
+    s->macroblocks        = NULL;
+}
+
+static int update_dimensions(VP8Context *s, int width, int height)
+{
+    if (av_image_check_size(width, height, 0, s->avctx))
+        return AVERROR_INVALIDDATA;
+
+    vp8_decode_flush(s->avctx);
+
+    avcodec_set_dimensions(s->avctx, width, height);
+
+    s->mb_width  = (s->avctx->coded_width +15) / 16;
+    s->mb_height = (s->avctx->coded_height+15) / 16;
+
+    s->macroblocks_base        = av_mallocz((s->mb_width+s->mb_height*2+1)*sizeof(*s->macroblocks));
+    s->filter_strength         = av_mallocz(s->mb_width*sizeof(*s->filter_strength));
+    s->intra4x4_pred_mode_top  = av_mallocz(s->mb_width*4);
+    s->top_nnz                 = av_mallocz(s->mb_width*sizeof(*s->top_nnz));
+    s->top_border              = av_mallocz((s->mb_width+1)*sizeof(*s->top_border));
+    s->segmentation_map        = av_mallocz(s->mb_width*s->mb_height);
+
+    if (!s->macroblocks_base || !s->filter_strength || !s->intra4x4_pred_mode_top ||
+        !s->top_nnz || !s->top_border || !s->segmentation_map)
+        return AVERROR(ENOMEM);
+
+    s->macroblocks        = s->macroblocks_base + 1;
+
+    return 0;
+}
+
+static void parse_segment_info(VP8Context *s)
+{
+    VP56RangeCoder *c = &s->c;
+    int i;
+
+    s->segmentation.update_map = vp8_rac_get(c);
+
+    if (vp8_rac_get(c)) { // update segment feature data
+        s->segmentation.absolute_vals = vp8_rac_get(c);
+
+        for (i = 0; i < 4; i++)
+            s->segmentation.base_quant[i]   = vp8_rac_get_sint(c, 7);
+
+        for (i = 0; i < 4; i++)
+            s->segmentation.filter_level[i] = vp8_rac_get_sint(c, 6);
+    }
+    if (s->segmentation.update_map)
+        for (i = 0; i < 3; i++)
+            s->prob->segmentid[i] = vp8_rac_get(c) ? vp8_rac_get_uint(c, 8) : 255;
+}
+
+static void update_lf_deltas(VP8Context *s)
+{
+    VP56RangeCoder *c = &s->c;
+    int i;
+
+    for (i = 0; i < 4; i++)
+        s->lf_delta.ref[i]  = vp8_rac_get_sint(c, 6);
+
+    for (i = MODE_I4x4; i <= VP8_MVMODE_SPLIT; i++)
+        s->lf_delta.mode[i] = vp8_rac_get_sint(c, 6);
+}
+
+static int setup_partitions(VP8Context *s, const uint8_t *buf, int buf_size)
+{
+    const uint8_t *sizes = buf;
+    int i;
+
+    s->num_coeff_partitions = 1 << vp8_rac_get_uint(&s->c, 2);
+
+    buf      += 3*(s->num_coeff_partitions-1);
+    buf_size -= 3*(s->num_coeff_partitions-1);
+    if (buf_size < 0)
+        return -1;
+
+    for (i = 0; i < s->num_coeff_partitions-1; i++) {
+        int size = AV_RL24(sizes + 3*i);
+        if (buf_size - size < 0)
+            return -1;
+
+        ff_vp56_init_range_decoder(&s->coeff_partition[i], buf, size);
+        buf      += size;
+        buf_size -= size;
+    }
+    ff_vp56_init_range_decoder(&s->coeff_partition[i], buf, buf_size);
+
+    return 0;
+}
+
+static void get_quants(VP8Context *s)
+{
+    VP56RangeCoder *c = &s->c;
+    int i, base_qi;
+
+    int yac_qi     = vp8_rac_get_uint(c, 7);
+    int ydc_delta  = vp8_rac_get_sint(c, 4);
+    int y2dc_delta = vp8_rac_get_sint(c, 4);
+    int y2ac_delta = vp8_rac_get_sint(c, 4);
+    int uvdc_delta = vp8_rac_get_sint(c, 4);
+    int uvac_delta = vp8_rac_get_sint(c, 4);
+
+    for (i = 0; i < 4; i++) {
+        if (s->segmentation.enabled) {
+            base_qi = s->segmentation.base_quant[i];
+            if (!s->segmentation.absolute_vals)
+                base_qi += yac_qi;
+        } else
+            base_qi = yac_qi;
+
+        s->qmat[i].luma_qmul[0]    =       vp8_dc_qlookup[av_clip(base_qi + ydc_delta , 0, 127)];
+        s->qmat[i].luma_qmul[1]    =       vp8_ac_qlookup[av_clip(base_qi             , 0, 127)];
+        s->qmat[i].luma_dc_qmul[0] =   2 * vp8_dc_qlookup[av_clip(base_qi + y2dc_delta, 0, 127)];
+        s->qmat[i].luma_dc_qmul[1] = 155 * vp8_ac_qlookup[av_clip(base_qi + y2ac_delta, 0, 127)] / 100;
+        s->qmat[i].chroma_qmul[0]  =       vp8_dc_qlookup[av_clip(base_qi + uvdc_delta, 0, 127)];
+        s->qmat[i].chroma_qmul[1]  =       vp8_ac_qlookup[av_clip(base_qi + uvac_delta, 0, 127)];
+
+        s->qmat[i].luma_dc_qmul[1] = FFMAX(s->qmat[i].luma_dc_qmul[1], 8);
+        s->qmat[i].chroma_qmul[0]  = FFMIN(s->qmat[i].chroma_qmul[0], 132);
+    }
+}
+
+/**
+ * Determine which buffers golden and altref should be updated with after this frame.
+ * The spec isn't clear here, so I'm going by my understanding of what libvpx does
+ *
+ * Intra frames update all 3 references
+ * Inter frames update VP56_FRAME_PREVIOUS if the update_last flag is set
+ * If the update (golden|altref) flag is set, it's updated with the current frame
+ *      if update_last is set, and VP56_FRAME_PREVIOUS otherwise.
+ * If the flag is not set, the number read means:
+ *      0: no update
+ *      1: VP56_FRAME_PREVIOUS
+ *      2: update golden with altref, or update altref with golden
+ */
+static VP56Frame ref_to_update(VP8Context *s, int update, VP56Frame ref)
+{
+    VP56RangeCoder *c = &s->c;
+
+    if (update)
+        return VP56_FRAME_CURRENT;
+
+    switch (vp8_rac_get_uint(c, 2)) {
+    case 1:
+        return VP56_FRAME_PREVIOUS;
+    case 2:
+        return (ref == VP56_FRAME_GOLDEN) ? VP56_FRAME_GOLDEN2 : VP56_FRAME_GOLDEN;
+    }
+    return VP56_FRAME_NONE;
+}
+
+static void update_refs(VP8Context *s)
+{
+    VP56RangeCoder *c = &s->c;
+
+    int update_golden = vp8_rac_get(c);
+    int update_altref = vp8_rac_get(c);
+
+    s->update_golden = ref_to_update(s, update_golden, VP56_FRAME_GOLDEN);
+    s->update_altref = ref_to_update(s, update_altref, VP56_FRAME_GOLDEN2);
+}
+
+static int decode_frame_header(VP8Context *s, const uint8_t *buf, int buf_size)
+{
+    VP56RangeCoder *c = &s->c;
+    int header_size, hscale, vscale, i, j, k, l, m, ret;
+    int width  = s->avctx->width;
+    int height = s->avctx->height;
+
+    s->keyframe  = !(buf[0] & 1);
+    s->profile   =  (buf[0]>>1) & 7;
+    s->invisible = !(buf[0] & 0x10);
+    header_size  = AV_RL24(buf) >> 5;
+    buf      += 3;
+    buf_size -= 3;
+
+    if (s->profile > 3)
+        av_log(s->avctx, AV_LOG_WARNING, "Unknown profile %d\n", s->profile);
+
+    if (!s->profile)
+        memcpy(s->put_pixels_tab, s->vp8dsp.put_vp8_epel_pixels_tab, sizeof(s->put_pixels_tab));
+    else    // profile 1-3 use bilinear, 4+ aren't defined so whatever
+        memcpy(s->put_pixels_tab, s->vp8dsp.put_vp8_bilinear_pixels_tab, sizeof(s->put_pixels_tab));
+
+    if (header_size > buf_size - 7*s->keyframe) {
+        av_log(s->avctx, AV_LOG_ERROR, "Header size larger than data provided\n");
+        return AVERROR_INVALIDDATA;
+    }
+
+    if (s->keyframe) {
+        if (AV_RL24(buf) != 0x2a019d) {
+            av_log(s->avctx, AV_LOG_ERROR, "Invalid start code 0x%x\n", AV_RL24(buf));
+            return AVERROR_INVALIDDATA;
+        }
+        width  = AV_RL16(buf+3) & 0x3fff;
+        height = AV_RL16(buf+5) & 0x3fff;
+        hscale = buf[4] >> 6;
+        vscale = buf[6] >> 6;
+        buf      += 7;
+        buf_size -= 7;
+
+        if (hscale || vscale)
+            av_log_missing_feature(s->avctx, "Upscaling", 1);
+
+        s->update_golden = s->update_altref = VP56_FRAME_CURRENT;
+        for (i = 0; i < 4; i++)
+            for (j = 0; j < 16; j++)
+                memcpy(s->prob->token[i][j], vp8_token_default_probs[i][vp8_coeff_band[j]],
+                       sizeof(s->prob->token[i][j]));
+        memcpy(s->prob->pred16x16, vp8_pred16x16_prob_inter, sizeof(s->prob->pred16x16));
+        memcpy(s->prob->pred8x8c , vp8_pred8x8c_prob_inter , sizeof(s->prob->pred8x8c));
+        memcpy(s->prob->mvc      , vp8_mv_default_prob     , sizeof(s->prob->mvc));
+        memset(&s->segmentation, 0, sizeof(s->segmentation));
+    }
+
+    if (!s->macroblocks_base || /* first frame */
+        width != s->avctx->width || height != s->avctx->height) {
+        if ((ret = update_dimensions(s, width, height) < 0))
+            return ret;
+    }
+
+    ff_vp56_init_range_decoder(c, buf, header_size);
+    buf      += header_size;
+    buf_size -= header_size;
+
+    if (s->keyframe) {
+        if (vp8_rac_get(c))
+            av_log(s->avctx, AV_LOG_WARNING, "Unspecified colorspace\n");
+        vp8_rac_get(c); // whether we can skip clamping in dsp functions
+    }
+
+    if ((s->segmentation.enabled = vp8_rac_get(c)))
+        parse_segment_info(s);
+    else
+        s->segmentation.update_map = 0; // FIXME: move this to some init function?
+
+    s->filter.simple    = vp8_rac_get(c);
+    s->filter.level     = vp8_rac_get_uint(c, 6);
+    s->filter.sharpness = vp8_rac_get_uint(c, 3);
+
+    if ((s->lf_delta.enabled = vp8_rac_get(c)))
+        if (vp8_rac_get(c))
+            update_lf_deltas(s);
+
+    if (setup_partitions(s, buf, buf_size)) {
+        av_log(s->avctx, AV_LOG_ERROR, "Invalid partitions\n");
+        return AVERROR_INVALIDDATA;
+    }
+
+    get_quants(s);
+
+    if (!s->keyframe) {
+        update_refs(s);
+        s->sign_bias[VP56_FRAME_GOLDEN]               = vp8_rac_get(c);
+        s->sign_bias[VP56_FRAME_GOLDEN2 /* altref */] = vp8_rac_get(c);
+    }
+
+    // if we aren't saving this frame's probabilities for future frames,
+    // make a copy of the current probabilities
+    if (!(s->update_probabilities = vp8_rac_get(c)))
+        s->prob[1] = s->prob[0];
+
+    s->update_last = s->keyframe || vp8_rac_get(c);
+
+    for (i = 0; i < 4; i++)
+        for (j = 0; j < 8; j++)
+            for (k = 0; k < 3; k++)
+                for (l = 0; l < NUM_DCT_TOKENS-1; l++)
+                    if (vp56_rac_get_prob_branchy(c, vp8_token_update_probs[i][j][k][l])) {
+                        int prob = vp8_rac_get_uint(c, 8);
+                        for (m = 0; vp8_coeff_band_indexes[j][m] >= 0; m++)
+                            s->prob->token[i][vp8_coeff_band_indexes[j][m]][k][l] = prob;
+                    }
+
+    if ((s->mbskip_enabled = vp8_rac_get(c)))
+        s->prob->mbskip = vp8_rac_get_uint(c, 8);
+
+    if (!s->keyframe) {
+        s->prob->intra  = vp8_rac_get_uint(c, 8);
+        s->prob->last   = vp8_rac_get_uint(c, 8);
+        s->prob->golden = vp8_rac_get_uint(c, 8);
+
+        if (vp8_rac_get(c))
+            for (i = 0; i < 4; i++)
+                s->prob->pred16x16[i] = vp8_rac_get_uint(c, 8);
+        if (vp8_rac_get(c))
+            for (i = 0; i < 3; i++)
+                s->prob->pred8x8c[i]  = vp8_rac_get_uint(c, 8);
+
+        // 17.2 MV probability update
+        for (i = 0; i < 2; i++)
+            for (j = 0; j < 19; j++)
+                if (vp56_rac_get_prob_branchy(c, vp8_mv_update_prob[i][j]))
+                    s->prob->mvc[i][j] = vp8_rac_get_nn(c);
+    }
+
+    return 0;
+}
+
+static av_always_inline void clamp_mv(VP8Context *s, VP56mv *dst, const VP56mv *src)
+{
+    dst->x = av_clip(src->x, s->mv_min.x, s->mv_max.x);
+    dst->y = av_clip(src->y, s->mv_min.y, s->mv_max.y);
+}
+
+/**
+ * Motion vector coding, 17.1.
+ */
+static int read_mv_component(VP56RangeCoder *c, const uint8_t *p)
+{
+    int bit, x = 0;
+
+    if (vp56_rac_get_prob_branchy(c, p[0])) {
+        int i;
+
+        for (i = 0; i < 3; i++)
+            x += vp56_rac_get_prob(c, p[9 + i]) << i;
+        for (i = 9; i > 3; i--)
+            x += vp56_rac_get_prob(c, p[9 + i]) << i;
+        if (!(x & 0xFFF0) || vp56_rac_get_prob(c, p[12]))
+            x += 8;
+    } else {
+        // small_mvtree
+        const uint8_t *ps = p+2;
+        bit = vp56_rac_get_prob(c, *ps);
+        ps += 1 + 3*bit;
+        x  += 4*bit;
+        bit = vp56_rac_get_prob(c, *ps);
+        ps += 1 + bit;
+        x  += 2*bit;
+        x  += vp56_rac_get_prob(c, *ps);
+    }
+
+    return (x && vp56_rac_get_prob(c, p[1])) ? -x : x;
+}
+
+static av_always_inline
+const uint8_t *get_submv_prob(uint32_t left, uint32_t top)
+{
+    if (left == top)
+        return vp8_submv_prob[4-!!left];
+    if (!top)
+        return vp8_submv_prob[2];
+    return vp8_submv_prob[1-!!left];
+}
+
+/**
+ * Split motion vector prediction, 16.4.
+ * @returns the number of motion vectors parsed (2, 4 or 16)
+ */
+static av_always_inline
+int decode_splitmvs(VP8Context *s, VP56RangeCoder *c, VP8Macroblock *mb)
+{
+    int part_idx;
+    int n, num;
+    VP8Macroblock *top_mb  = &mb[2];
+    VP8Macroblock *left_mb = &mb[-1];
+    const uint8_t *mbsplits_left = vp8_mbsplits[left_mb->partitioning],
+                  *mbsplits_top = vp8_mbsplits[top_mb->partitioning],
+                  *mbsplits_cur, *firstidx;
+    VP56mv *top_mv  = top_mb->bmv;
+    VP56mv *left_mv = left_mb->bmv;
+    VP56mv *cur_mv  = mb->bmv;
+
+    if (vp56_rac_get_prob_branchy(c, vp8_mbsplit_prob[0])) {
+        if (vp56_rac_get_prob_branchy(c, vp8_mbsplit_prob[1])) {
+            part_idx = VP8_SPLITMVMODE_16x8 + vp56_rac_get_prob(c, vp8_mbsplit_prob[2]);
+        } else {
+            part_idx = VP8_SPLITMVMODE_8x8;
+        }
+    } else {
+        part_idx = VP8_SPLITMVMODE_4x4;
+    }
+
+    num = vp8_mbsplit_count[part_idx];
+    mbsplits_cur = vp8_mbsplits[part_idx],
+    firstidx = vp8_mbfirstidx[part_idx];
+    mb->partitioning = part_idx;
+
+    for (n = 0; n < num; n++) {
+        int k = firstidx[n];
+        uint32_t left, above;
+        const uint8_t *submv_prob;
+
+        if (!(k & 3))
+            left = AV_RN32A(&left_mv[mbsplits_left[k + 3]]);
+        else
+            left  = AV_RN32A(&cur_mv[mbsplits_cur[k - 1]]);
+        if (k <= 3)
+            above = AV_RN32A(&top_mv[mbsplits_top[k + 12]]);
+        else
+            above = AV_RN32A(&cur_mv[mbsplits_cur[k - 4]]);
+
+        submv_prob = get_submv_prob(left, above);
+
+        if (vp56_rac_get_prob_branchy(c, submv_prob[0])) {
+            if (vp56_rac_get_prob_branchy(c, submv_prob[1])) {
+                if (vp56_rac_get_prob_branchy(c, submv_prob[2])) {
+                    mb->bmv[n].y = mb->mv.y + read_mv_component(c, s->prob->mvc[0]);
+                    mb->bmv[n].x = mb->mv.x + read_mv_component(c, s->prob->mvc[1]);
+                } else {
+                    AV_ZERO32(&mb->bmv[n]);
+                }
+            } else {
+                AV_WN32A(&mb->bmv[n], above);
+            }
+        } else {
+            AV_WN32A(&mb->bmv[n], left);
+        }
+    }
+
+    return num;
+}
+
+static av_always_inline
+void decode_mvs(VP8Context *s, VP8Macroblock *mb, int mb_x, int mb_y)
+{
+    VP8Macroblock *mb_edge[3] = { mb + 2 /* top */,
+                                  mb - 1 /* left */,
+                                  mb + 1 /* top-left */ };
+    enum { CNT_ZERO, CNT_NEAREST, CNT_NEAR, CNT_SPLITMV };
+    enum { VP8_EDGE_TOP, VP8_EDGE_LEFT, VP8_EDGE_TOPLEFT };
+    int idx = CNT_ZERO;
+    int cur_sign_bias = s->sign_bias[mb->ref_frame];
+    int8_t *sign_bias = s->sign_bias;
+    VP56mv near_mv[4];
+    uint8_t cnt[4] = { 0 };
+    VP56RangeCoder *c = &s->c;
+
+    AV_ZERO32(&near_mv[0]);
+    AV_ZERO32(&near_mv[1]);
+
+    /* Process MB on top, left and top-left */
+    #define MV_EDGE_CHECK(n)\
+    {\
+        VP8Macroblock *edge = mb_edge[n];\
+        int edge_ref = edge->ref_frame;\
+        if (edge_ref != VP56_FRAME_CURRENT) {\
+            uint32_t mv = AV_RN32A(&edge->mv);\
+            if (mv) {\
+                if (cur_sign_bias != sign_bias[edge_ref]) {\
+                    /* SWAR negate of the values in mv. */\
+                    mv = ~mv;\
+                    mv = ((mv&0x7fff7fff) + 0x00010001) ^ (mv&0x80008000);\
+                }\
+                if (!n || mv != AV_RN32A(&near_mv[idx]))\
+                    AV_WN32A(&near_mv[++idx], mv);\
+                cnt[idx]      += 1 + (n != 2);\
+            } else\
+                cnt[CNT_ZERO] += 1 + (n != 2);\
+        }\
+    }
+
+    MV_EDGE_CHECK(0)
+    MV_EDGE_CHECK(1)
+    MV_EDGE_CHECK(2)
+
+    mb->partitioning = VP8_SPLITMVMODE_NONE;
+    if (vp56_rac_get_prob_branchy(c, vp8_mode_contexts[cnt[CNT_ZERO]][0])) {
+        mb->mode = VP8_MVMODE_MV;
+
+        /* If we have three distinct MVs, merge first and last if they're the same */
+        if (cnt[CNT_SPLITMV] && AV_RN32A(&near_mv[1 + VP8_EDGE_TOP]) == AV_RN32A(&near_mv[1 + VP8_EDGE_TOPLEFT]))
+            cnt[CNT_NEAREST] += 1;
+
+        /* Swap near and nearest if necessary */
+        if (cnt[CNT_NEAR] > cnt[CNT_NEAREST]) {
+            FFSWAP(uint8_t,     cnt[CNT_NEAREST],     cnt[CNT_NEAR]);
+            FFSWAP( VP56mv, near_mv[CNT_NEAREST], near_mv[CNT_NEAR]);
+        }
+
+        if (vp56_rac_get_prob_branchy(c, vp8_mode_contexts[cnt[CNT_NEAREST]][1])) {
+            if (vp56_rac_get_prob_branchy(c, vp8_mode_contexts[cnt[CNT_NEAR]][2])) {
+
+                /* Choose the best mv out of 0,0 and the nearest mv */
+                clamp_mv(s, &mb->mv, &near_mv[CNT_ZERO + (cnt[CNT_NEAREST] >= cnt[CNT_ZERO])]);
+                cnt[CNT_SPLITMV] = ((mb_edge[VP8_EDGE_LEFT]->mode    == VP8_MVMODE_SPLIT) +
+                                    (mb_edge[VP8_EDGE_TOP]->mode     == VP8_MVMODE_SPLIT)) * 2 +
+                                    (mb_edge[VP8_EDGE_TOPLEFT]->mode == VP8_MVMODE_SPLIT);
+
+                if (vp56_rac_get_prob_branchy(c, vp8_mode_contexts[cnt[CNT_SPLITMV]][3])) {
+                    mb->mode = VP8_MVMODE_SPLIT;
+                    mb->mv = mb->bmv[decode_splitmvs(s, c, mb) - 1];
+                } else {
+                    mb->mv.y += read_mv_component(c, s->prob->mvc[0]);
+                    mb->mv.x += read_mv_component(c, s->prob->mvc[1]);
+                    mb->bmv[0] = mb->mv;
+                }
+            } else {
+                clamp_mv(s, &mb->mv, &near_mv[CNT_NEAR]);
+                mb->bmv[0] = mb->mv;
+            }
+        } else {
+            clamp_mv(s, &mb->mv, &near_mv[CNT_NEAREST]);
+            mb->bmv[0] = mb->mv;
+        }
+    } else {
+        mb->mode = VP8_MVMODE_ZERO;
+        AV_ZERO32(&mb->mv);
+        mb->bmv[0] = mb->mv;
+    }
+}
+
+static av_always_inline
+void decode_intra4x4_modes(VP8Context *s, VP56RangeCoder *c,
+                           int mb_x, int keyframe)
+{
+    uint8_t *intra4x4 = s->intra4x4_pred_mode_mb;
+    if (keyframe) {
+        int x, y;
+        uint8_t* const top = s->intra4x4_pred_mode_top + 4 * mb_x;
+        uint8_t* const left = s->intra4x4_pred_mode_left;
+        for (y = 0; y < 4; y++) {
+            for (x = 0; x < 4; x++) {
+                const uint8_t *ctx;
+                ctx = vp8_pred4x4_prob_intra[top[x]][left[y]];
+                *intra4x4 = vp8_rac_get_tree(c, vp8_pred4x4_tree, ctx);
+                left[y] = top[x] = *intra4x4;
+                intra4x4++;
+            }
+        }
+    } else {
+        int i;
+        for (i = 0; i < 16; i++)
+            intra4x4[i] = vp8_rac_get_tree(c, vp8_pred4x4_tree, vp8_pred4x4_prob_inter);
+    }
+}
+
+static av_always_inline
+void decode_mb_mode(VP8Context *s, VP8Macroblock *mb, int mb_x, int mb_y, uint8_t *segment)
+{
+    VP56RangeCoder *c = &s->c;
+
+    if (s->segmentation.update_map)
+        *segment = vp8_rac_get_tree(c, vp8_segmentid_tree, s->prob->segmentid);
+    s->segment = *segment;
+
+    mb->skip = s->mbskip_enabled ? vp56_rac_get_prob(c, s->prob->mbskip) : 0;
+
+    if (s->keyframe) {
+        mb->mode = vp8_rac_get_tree(c, vp8_pred16x16_tree_intra, vp8_pred16x16_prob_intra);
+
+        if (mb->mode == MODE_I4x4) {
+            decode_intra4x4_modes(s, c, mb_x, 1);
+        } else {
+            const uint32_t modes = vp8_pred4x4_mode[mb->mode] * 0x01010101u;
+            AV_WN32A(s->intra4x4_pred_mode_top + 4 * mb_x, modes);
+            AV_WN32A(s->intra4x4_pred_mode_left, modes);
+        }
+
+        s->chroma_pred_mode = vp8_rac_get_tree(c, vp8_pred8x8c_tree, vp8_pred8x8c_prob_intra);
+        mb->ref_frame = VP56_FRAME_CURRENT;
+    } else if (vp56_rac_get_prob_branchy(c, s->prob->intra)) {
+        // inter MB, 16.2
+        if (vp56_rac_get_prob_branchy(c, s->prob->last))
+            mb->ref_frame = vp56_rac_get_prob(c, s->prob->golden) ?
+                VP56_FRAME_GOLDEN2 /* altref */ : VP56_FRAME_GOLDEN;
+        else
+            mb->ref_frame = VP56_FRAME_PREVIOUS;
+        s->ref_count[mb->ref_frame-1]++;
+
+        // motion vectors, 16.3
+        decode_mvs(s, mb, mb_x, mb_y);
+    } else {
+        // intra MB, 16.1
+        mb->mode = vp8_rac_get_tree(c, vp8_pred16x16_tree_inter, s->prob->pred16x16);
+
+        if (mb->mode == MODE_I4x4)
+            decode_intra4x4_modes(s, c, mb_x, 0);
+
+        s->chroma_pred_mode = vp8_rac_get_tree(c, vp8_pred8x8c_tree, s->prob->pred8x8c);
+        mb->ref_frame = VP56_FRAME_CURRENT;
+        mb->partitioning = VP8_SPLITMVMODE_NONE;
+        AV_ZERO32(&mb->bmv[0]);
+    }
+}
+
+#ifndef decode_block_coeffs_internal
+/**
+ * @param c arithmetic bitstream reader context
+ * @param block destination for block coefficients
+ * @param probs probabilities to use when reading trees from the bitstream
+ * @param i initial coeff index, 0 unless a separate DC block is coded
+ * @param zero_nhood the initial prediction context for number of surrounding
+ *                   all-zero blocks (only left/top, so 0-2)
+ * @param qmul array holding the dc/ac dequant factor at position 0/1
+ * @return 0 if no coeffs were decoded
+ *         otherwise, the index of the last coeff decoded plus one
+ */
+static int decode_block_coeffs_internal(VP56RangeCoder *c, DCTELEM block[16],
+                                        uint8_t probs[16][3][NUM_DCT_TOKENS-1],
+                                        int i, uint8_t *token_prob, int16_t qmul[2])
+{
+    goto skip_eob;
+    do {
+        int coeff;
+        if (!vp56_rac_get_prob_branchy(c, token_prob[0]))   // DCT_EOB
+            return i;
+
+skip_eob:
+        if (!vp56_rac_get_prob_branchy(c, token_prob[1])) { // DCT_0
+            if (++i == 16)
+                return i; // invalid input; blocks should end with EOB
+            token_prob = probs[i][0];
+            goto skip_eob;
+        }
+
+        if (!vp56_rac_get_prob_branchy(c, token_prob[2])) { // DCT_1
+            coeff = 1;
+            token_prob = probs[i+1][1];
+        } else {
+            if (!vp56_rac_get_prob_branchy(c, token_prob[3])) { // DCT 2,3,4
+                coeff = vp56_rac_get_prob_branchy(c, token_prob[4]);
+                if (coeff)
+                    coeff += vp56_rac_get_prob(c, token_prob[5]);
+                coeff += 2;
+            } else {
+                // DCT_CAT*
+                if (!vp56_rac_get_prob_branchy(c, token_prob[6])) {
+                    if (!vp56_rac_get_prob_branchy(c, token_prob[7])) { // DCT_CAT1
+                        coeff  = 5 + vp56_rac_get_prob(c, vp8_dct_cat1_prob[0]);
+                    } else {                                    // DCT_CAT2
+                        coeff  = 7;
+                        coeff += vp56_rac_get_prob(c, vp8_dct_cat2_prob[0]) << 1;
+                        coeff += vp56_rac_get_prob(c, vp8_dct_cat2_prob[1]);
+                    }
+                } else {    // DCT_CAT3 and up
+                    int a = vp56_rac_get_prob(c, token_prob[8]);
+                    int b = vp56_rac_get_prob(c, token_prob[9+a]);
+                    int cat = (a<<1) + b;
+                    coeff  = 3 + (8<<cat);
+                    coeff += vp8_rac_get_coeff(c, ff_vp8_dct_cat_prob[cat]);
+                }
+            }
+            token_prob = probs[i+1][2];
+        }
+        block[zigzag_scan[i]] = (vp8_rac_get(c) ? -coeff : coeff) * qmul[!!i];
+    } while (++i < 16);
+
+    return i;
+}
+#endif
+
+static av_always_inline
+int decode_block_coeffs(VP56RangeCoder *c, DCTELEM block[16],
+                        uint8_t probs[16][3][NUM_DCT_TOKENS-1],
+                        int i, int zero_nhood, int16_t qmul[2])
+{
+    uint8_t *token_prob = probs[i][zero_nhood];
+    if (!vp56_rac_get_prob_branchy(c, token_prob[0]))   // DCT_EOB
+        return 0;
+    return decode_block_coeffs_internal(c, block, probs, i, token_prob, qmul);
+}
+
+static av_always_inline
+void decode_mb_coeffs(VP8Context *s, VP56RangeCoder *c, VP8Macroblock *mb,
+                      uint8_t t_nnz[9], uint8_t l_nnz[9])
+{
+    int i, x, y, luma_start = 0, luma_ctx = 3;
+    int nnz_pred, nnz, nnz_total = 0;
+    int segment = s->segment;
+    int block_dc = 0;
+
+    if (mb->mode != MODE_I4x4 && mb->mode != VP8_MVMODE_SPLIT) {
+        nnz_pred = t_nnz[8] + l_nnz[8];
+
+        // decode DC values and do hadamard
+        nnz = decode_block_coeffs(c, s->block_dc, s->prob->token[1], 0, nnz_pred,
+                                  s->qmat[segment].luma_dc_qmul);
+        l_nnz[8] = t_nnz[8] = !!nnz;
+        if (nnz) {
+            nnz_total += nnz;
+            block_dc = 1;
+            if (nnz == 1)
+                s->vp8dsp.vp8_luma_dc_wht_dc(s->block, s->block_dc);
+            else
+                s->vp8dsp.vp8_luma_dc_wht(s->block, s->block_dc);
+        }
+        luma_start = 1;
+        luma_ctx = 0;
+    }
+
+    // luma blocks
+    for (y = 0; y < 4; y++)
+        for (x = 0; x < 4; x++) {
+            nnz_pred = l_nnz[y] + t_nnz[x];
+            nnz = decode_block_coeffs(c, s->block[y][x], s->prob->token[luma_ctx], luma_start,
+                                      nnz_pred, s->qmat[segment].luma_qmul);
+            // nnz+block_dc may be one more than the actual last index, but we don't care
+            s->non_zero_count_cache[y][x] = nnz + block_dc;
+            t_nnz[x] = l_nnz[y] = !!nnz;
+            nnz_total += nnz;
+        }
+
+    // chroma blocks
+    // TODO: what to do about dimensions? 2nd dim for luma is x,
+    // but for chroma it's (y<<1)|x
+    for (i = 4; i < 6; i++)
+        for (y = 0; y < 2; y++)
+            for (x = 0; x < 2; x++) {
+                nnz_pred = l_nnz[i+2*y] + t_nnz[i+2*x];
+                nnz = decode_block_coeffs(c, s->block[i][(y<<1)+x], s->prob->token[2], 0,
+                                          nnz_pred, s->qmat[segment].chroma_qmul);
+                s->non_zero_count_cache[i][(y<<1)+x] = nnz;
+                t_nnz[i+2*x] = l_nnz[i+2*y] = !!nnz;
+                nnz_total += nnz;
+            }
+
+    // if there were no coded coeffs despite the macroblock not being marked skip,
+    // we MUST not do the inner loop filter and should not do IDCT
+    // Since skip isn't used for bitstream prediction, just manually set it.
+    if (!nnz_total)
+        mb->skip = 1;
+}
+
+static av_always_inline
+void backup_mb_border(uint8_t *top_border, uint8_t *src_y, uint8_t *src_cb, uint8_t *src_cr,
+                      int linesize, int uvlinesize, int simple)
+{
+    AV_COPY128(top_border, src_y + 15*linesize);
+    if (!simple) {
+        AV_COPY64(top_border+16, src_cb + 7*uvlinesize);
+        AV_COPY64(top_border+24, src_cr + 7*uvlinesize);
+    }
+}
+
+static av_always_inline
+void xchg_mb_border(uint8_t *top_border, uint8_t *src_y, uint8_t *src_cb, uint8_t *src_cr,
+                    int linesize, int uvlinesize, int mb_x, int mb_y, int mb_width,
+                    int simple, int xchg)
+{
+    uint8_t *top_border_m1 = top_border-32;     // for TL prediction
+    src_y  -=   linesize;
+    src_cb -= uvlinesize;
+    src_cr -= uvlinesize;
+
+#define XCHG(a,b,xchg) do {                     \
+        if (xchg) AV_SWAP64(b,a);               \
+        else      AV_COPY64(b,a);               \
+    } while (0)
+
+    XCHG(top_border_m1+8, src_y-8, xchg);
+    XCHG(top_border,      src_y,   xchg);
+    XCHG(top_border+8,    src_y+8, 1);
+    if (mb_x < mb_width-1)
+        XCHG(top_border+32, src_y+16, 1);
+
+    // only copy chroma for normal loop filter
+    // or to initialize the top row to 127
+    if (!simple || !mb_y) {
+        XCHG(top_border_m1+16, src_cb-8, xchg);
+        XCHG(top_border_m1+24, src_cr-8, xchg);
+        XCHG(top_border+16,    src_cb, 1);
+        XCHG(top_border+24,    src_cr, 1);
+    }
+}
+
+static av_always_inline
+int check_dc_pred8x8_mode(int mode, int mb_x, int mb_y)
+{
+    if (!mb_x) {
+        return mb_y ? TOP_DC_PRED8x8 : DC_128_PRED8x8;
+    } else {
+        return mb_y ? mode : LEFT_DC_PRED8x8;
+    }
+}
+
+static av_always_inline
+int check_tm_pred8x8_mode(int mode, int mb_x, int mb_y)
+{
+    if (!mb_x) {
+        return mb_y ? VERT_PRED8x8 : DC_129_PRED8x8;
+    } else {
+        return mb_y ? mode : HOR_PRED8x8;
+    }
+}
+
+static av_always_inline
+int check_intra_pred8x8_mode(int mode, int mb_x, int mb_y)
+{
+    if (mode == DC_PRED8x8) {
+        return check_dc_pred8x8_mode(mode, mb_x, mb_y);
+    } else {
+        return mode;
+    }
+}
+
+static av_always_inline
+int check_intra_pred8x8_mode_emuedge(int mode, int mb_x, int mb_y)
+{
+    switch (mode) {
+    case DC_PRED8x8:
+        return check_dc_pred8x8_mode(mode, mb_x, mb_y);
+    case VERT_PRED8x8:
+        return !mb_y ? DC_127_PRED8x8 : mode;
+    case HOR_PRED8x8:
+        return !mb_x ? DC_129_PRED8x8 : mode;
+    case PLANE_PRED8x8 /*TM*/:
+        return check_tm_pred8x8_mode(mode, mb_x, mb_y);
+    }
+    return mode;
+}
+
+static av_always_inline
+int check_tm_pred4x4_mode(int mode, int mb_x, int mb_y)
+{
+    if (!mb_x) {
+        return mb_y ? VERT_VP8_PRED : DC_129_PRED;
+    } else {
+        return mb_y ? mode : HOR_VP8_PRED;
+    }
+}
+
+static av_always_inline
+int check_intra_pred4x4_mode_emuedge(int mode, int mb_x, int mb_y, int *copy_buf)
+{
+    switch (mode) {
+    case VERT_PRED:
+        if (!mb_x && mb_y) {
+            *copy_buf = 1;
+            return mode;
+        }
+        /* fall-through */
+    case DIAG_DOWN_LEFT_PRED:
+    case VERT_LEFT_PRED:
+        return !mb_y ? DC_127_PRED : mode;
+    case HOR_PRED:
+        if (!mb_y) {
+            *copy_buf = 1;
+            return mode;
+        }
+        /* fall-through */
+    case HOR_UP_PRED:
+        return !mb_x ? DC_129_PRED : mode;
+    case TM_VP8_PRED:
+        return check_tm_pred4x4_mode(mode, mb_x, mb_y);
+    case DC_PRED: // 4x4 DC doesn't use the same "H.264-style" exceptions as 16x16/8x8 DC
+    case DIAG_DOWN_RIGHT_PRED:
+    case VERT_RIGHT_PRED:
+    case HOR_DOWN_PRED:
+        if (!mb_y || !mb_x)
+            *copy_buf = 1;
+        return mode;
+    }
+    return mode;
+}
+
+static av_always_inline
+void intra_predict(VP8Context *s, uint8_t *dst[3], VP8Macroblock *mb,
+                   int mb_x, int mb_y)
+{
+    AVCodecContext *avctx = s->avctx;
+    int x, y, mode, nnz, tr;
+
+    // for the first row, we need to run xchg_mb_border to init the top edge to 127
+    // otherwise, skip it if we aren't going to deblock
+    if (!(avctx->flags & CODEC_FLAG_EMU_EDGE && !mb_y) && (s->deblock_filter || !mb_y))
+        xchg_mb_border(s->top_border[mb_x+1], dst[0], dst[1], dst[2],
+                       s->linesize, s->uvlinesize, mb_x, mb_y, s->mb_width,
+                       s->filter.simple, 1);
+
+    if (mb->mode < MODE_I4x4) {
+        if (avctx->flags & CODEC_FLAG_EMU_EDGE) { // tested
+            mode = check_intra_pred8x8_mode_emuedge(mb->mode, mb_x, mb_y);
+        } else {
+            mode = check_intra_pred8x8_mode(mb->mode, mb_x, mb_y);
+        }
+        s->hpc.pred16x16[mode](dst[0], s->linesize);
+    } else {
+        uint8_t *ptr = dst[0];
+        uint8_t *intra4x4 = s->intra4x4_pred_mode_mb;
+        uint8_t tr_top[4] = { 127, 127, 127, 127 };
+
+        // all blocks on the right edge of the macroblock use bottom edge
+        // the top macroblock for their topright edge
+        uint8_t *tr_right = ptr - s->linesize + 16;
+
+        // if we're on the right edge of the frame, said edge is extended
+        // from the top macroblock
+        if (!(!mb_y && avctx->flags & CODEC_FLAG_EMU_EDGE) &&
+            mb_x == s->mb_width-1) {
+            tr = tr_right[-1]*0x01010101;
+            tr_right = (uint8_t *)&tr;
+        }
+
+        if (mb->skip)
+            AV_ZERO128(s->non_zero_count_cache);
+
+        for (y = 0; y < 4; y++) {
+            uint8_t *topright = ptr + 4 - s->linesize;
+            for (x = 0; x < 4; x++) {
+                int copy = 0, linesize = s->linesize;
+                uint8_t *dst = ptr+4*x;
+                DECLARE_ALIGNED(4, uint8_t, copy_dst)[5*8];
+
+                if ((y == 0 || x == 3) && mb_y == 0 && avctx->flags & CODEC_FLAG_EMU_EDGE) {
+                    topright = tr_top;
+                } else if (x == 3)
+                    topright = tr_right;
+
+                if (avctx->flags & CODEC_FLAG_EMU_EDGE) { // mb_x+x or mb_y+y is a hack but works
+                    mode = check_intra_pred4x4_mode_emuedge(intra4x4[x], mb_x + x, mb_y + y, &copy);
+                    if (copy) {
+                        dst = copy_dst + 12;
+                        linesize = 8;
+                        if (!(mb_y + y)) {
+                            copy_dst[3] = 127U;
+                            AV_WN32A(copy_dst+4, 127U * 0x01010101U);
+                        } else {
+                            AV_COPY32(copy_dst+4, ptr+4*x-s->linesize);
+                            if (!(mb_x + x)) {
+                                copy_dst[3] = 129U;
+                            } else {
+                                copy_dst[3] = ptr[4*x-s->linesize-1];
+                            }
+                        }
+                        if (!(mb_x + x)) {
+                            copy_dst[11] =
+                            copy_dst[19] =
+                            copy_dst[27] =
+                            copy_dst[35] = 129U;
+                        } else {
+                            copy_dst[11] = ptr[4*x              -1];
+                            copy_dst[19] = ptr[4*x+s->linesize  -1];
+                            copy_dst[27] = ptr[4*x+s->linesize*2-1];
+                            copy_dst[35] = ptr[4*x+s->linesize*3-1];
+                        }
+                    }
+                } else {
+                    mode = intra4x4[x];
+                }
+                s->hpc.pred4x4[mode](dst, topright, linesize);
+                if (copy) {
+                    AV_COPY32(ptr+4*x              , copy_dst+12);
+                    AV_COPY32(ptr+4*x+s->linesize  , copy_dst+20);
+                    AV_COPY32(ptr+4*x+s->linesize*2, copy_dst+28);
+                    AV_COPY32(ptr+4*x+s->linesize*3, copy_dst+36);
+                }
+
+                nnz = s->non_zero_count_cache[y][x];
+                if (nnz) {
+                    if (nnz == 1)
+                        s->vp8dsp.vp8_idct_dc_add(ptr+4*x, s->block[y][x], s->linesize);
+                    else
+                        s->vp8dsp.vp8_idct_add(ptr+4*x, s->block[y][x], s->linesize);
+                }
+                topright += 4;
+            }
+
+            ptr   += 4*s->linesize;
+            intra4x4 += 4;
+        }
+    }
+
+    if (avctx->flags & CODEC_FLAG_EMU_EDGE) {
+        mode = check_intra_pred8x8_mode_emuedge(s->chroma_pred_mode, mb_x, mb_y);
+    } else {
+        mode = check_intra_pred8x8_mode(s->chroma_pred_mode, mb_x, mb_y);
+    }
+    s->hpc.pred8x8[mode](dst[1], s->uvlinesize);
+    s->hpc.pred8x8[mode](dst[2], s->uvlinesize);
+
+    if (!(avctx->flags & CODEC_FLAG_EMU_EDGE && !mb_y) && (s->deblock_filter || !mb_y))
+        xchg_mb_border(s->top_border[mb_x+1], dst[0], dst[1], dst[2],
+                       s->linesize, s->uvlinesize, mb_x, mb_y, s->mb_width,
+                       s->filter.simple, 0);
+}
+
+static const uint8_t subpel_idx[3][8] = {
+    { 0, 1, 2, 1, 2, 1, 2, 1 }, // nr. of left extra pixels,
+                                // also function pointer index
+    { 0, 3, 5, 3, 5, 3, 5, 3 }, // nr. of extra pixels required
+    { 0, 2, 3, 2, 3, 2, 3, 2 }, // nr. of right extra pixels
+};
+
+/**
+ * Generic MC function.
+ *
+ * @param s VP8 decoding context
+ * @param luma 1 for luma (Y) planes, 0 for chroma (Cb/Cr) planes
+ * @param dst target buffer for block data at block position
+ * @param src reference picture buffer at origin (0, 0)
+ * @param mv motion vector (relative to block position) to get pixel data from
+ * @param x_off horizontal position of block from origin (0, 0)
+ * @param y_off vertical position of block from origin (0, 0)
+ * @param block_w width of block (16, 8 or 4)
+ * @param block_h height of block (always same as block_w)
+ * @param width width of src/dst plane data
+ * @param height height of src/dst plane data
+ * @param linesize size of a single line of plane data, including padding
+ * @param mc_func motion compensation function pointers (bilinear or sixtap MC)
+ */
+static av_always_inline
+void vp8_mc_luma(VP8Context *s, uint8_t *dst, uint8_t *src, const VP56mv *mv,
+                 int x_off, int y_off, int block_w, int block_h,
+                 int width, int height, int linesize,
+                 vp8_mc_func mc_func[3][3])
+{
+    if (AV_RN32A(mv)) {
+
+        int mx = (mv->x << 1)&7, mx_idx = subpel_idx[0][mx];
+        int my = (mv->y << 1)&7, my_idx = subpel_idx[0][my];
+
+        x_off += mv->x >> 2;
+        y_off += mv->y >> 2;
+
+        // edge emulation
+        src += y_off * linesize + x_off;
+        if (x_off < mx_idx || x_off >= width  - block_w - subpel_idx[2][mx] ||
+            y_off < my_idx || y_off >= height - block_h - subpel_idx[2][my]) {
+            s->dsp.emulated_edge_mc(s->edge_emu_buffer, src - my_idx * linesize - mx_idx, linesize,
+                                    block_w + subpel_idx[1][mx], block_h + subpel_idx[1][my],
+                                    x_off - mx_idx, y_off - my_idx, width, height);
+            src = s->edge_emu_buffer + mx_idx + linesize * my_idx;
+        }
+        mc_func[my_idx][mx_idx](dst, linesize, src, linesize, block_h, mx, my);
+    } else
+        mc_func[0][0](dst, linesize, src + y_off * linesize + x_off, linesize, block_h, 0, 0);
+}
+
+static av_always_inline
+void vp8_mc_chroma(VP8Context *s, uint8_t *dst1, uint8_t *dst2, uint8_t *src1,
+                   uint8_t *src2, const VP56mv *mv, int x_off, int y_off,
+                   int block_w, int block_h, int width, int height, int linesize,
+                   vp8_mc_func mc_func[3][3])
+{
+    if (AV_RN32A(mv)) {
+        int mx = mv->x&7, mx_idx = subpel_idx[0][mx];
+        int my = mv->y&7, my_idx = subpel_idx[0][my];
+
+        x_off += mv->x >> 3;
+        y_off += mv->y >> 3;
+
+        // edge emulation
+        src1 += y_off * linesize + x_off;
+        src2 += y_off * linesize + x_off;
+        if (x_off < mx_idx || x_off >= width  - block_w - subpel_idx[2][mx] ||
+            y_off < my_idx || y_off >= height - block_h - subpel_idx[2][my]) {
+            s->dsp.emulated_edge_mc(s->edge_emu_buffer, src1 - my_idx * linesize - mx_idx, linesize,
+                                    block_w + subpel_idx[1][mx], block_h + subpel_idx[1][my],
+                                    x_off - mx_idx, y_off - my_idx, width, height);
+            src1 = s->edge_emu_buffer + mx_idx + linesize * my_idx;
+            mc_func[my_idx][mx_idx](dst1, linesize, src1, linesize, block_h, mx, my);
+
+            s->dsp.emulated_edge_mc(s->edge_emu_buffer, src2 - my_idx * linesize - mx_idx, linesize,
+                                    block_w + subpel_idx[1][mx], block_h + subpel_idx[1][my],
+                                    x_off - mx_idx, y_off - my_idx, width, height);
+            src2 = s->edge_emu_buffer + mx_idx + linesize * my_idx;
+            mc_func[my_idx][mx_idx](dst2, linesize, src2, linesize, block_h, mx, my);
+        } else {
+            mc_func[my_idx][mx_idx](dst1, linesize, src1, linesize, block_h, mx, my);
+            mc_func[my_idx][mx_idx](dst2, linesize, src2, linesize, block_h, mx, my);
+        }
+    } else {
+        mc_func[0][0](dst1, linesize, src1 + y_off * linesize + x_off, linesize, block_h, 0, 0);
+        mc_func[0][0](dst2, linesize, src2 + y_off * linesize + x_off, linesize, block_h, 0, 0);
+    }
+}
+
+static av_always_inline
+void vp8_mc_part(VP8Context *s, uint8_t *dst[3],
+                 AVFrame *ref_frame, int x_off, int y_off,
+                 int bx_off, int by_off,
+                 int block_w, int block_h,
+                 int width, int height, VP56mv *mv)
+{
+    VP56mv uvmv = *mv;
+
+    /* Y */
+    vp8_mc_luma(s, dst[0] + by_off * s->linesize + bx_off,
+                ref_frame->data[0], mv, x_off + bx_off, y_off + by_off,
+                block_w, block_h, width, height, s->linesize,
+                s->put_pixels_tab[block_w == 8]);
+
+    /* U/V */
+    if (s->profile == 3) {
+        uvmv.x &= ~7;
+        uvmv.y &= ~7;
+    }
+    x_off   >>= 1; y_off   >>= 1;
+    bx_off  >>= 1; by_off  >>= 1;
+    width   >>= 1; height  >>= 1;
+    block_w >>= 1; block_h >>= 1;
+    vp8_mc_chroma(s, dst[1] + by_off * s->uvlinesize + bx_off,
+                  dst[2] + by_off * s->uvlinesize + bx_off, ref_frame->data[1],
+                  ref_frame->data[2], &uvmv, x_off + bx_off, y_off + by_off,
+                  block_w, block_h, width, height, s->uvlinesize,
+                  s->put_pixels_tab[1 + (block_w == 4)]);
+}
+
+/* Fetch pixels for estimated mv 4 macroblocks ahead.
+ * Optimized for 64-byte cache lines.  Inspired by ffh264 prefetch_motion. */
+static av_always_inline void prefetch_motion(VP8Context *s, VP8Macroblock *mb, int mb_x, int mb_y, int mb_xy, int ref)
+{
+    /* Don't prefetch refs that haven't been used very often this frame. */
+    if (s->ref_count[ref-1] > (mb_xy >> 5)) {
+        int x_off = mb_x << 4, y_off = mb_y << 4;
+        int mx = (mb->mv.x>>2) + x_off + 8;
+        int my = (mb->mv.y>>2) + y_off;
+        uint8_t **src= s->framep[ref]->data;
+        int off= mx + (my + (mb_x&3)*4)*s->linesize + 64;
+        s->dsp.prefetch(src[0]+off, s->linesize, 4);
+        off= (mx>>1) + ((my>>1) + (mb_x&7))*s->uvlinesize + 64;
+        s->dsp.prefetch(src[1]+off, src[2]-src[1], 2);
+    }
+}
+
+/**
+ * Apply motion vectors to prediction buffer, chapter 18.
+ */
+static av_always_inline
+void inter_predict(VP8Context *s, uint8_t *dst[3], VP8Macroblock *mb,
+                   int mb_x, int mb_y)
+{
+    int x_off = mb_x << 4, y_off = mb_y << 4;
+    int width = 16*s->mb_width, height = 16*s->mb_height;
+    AVFrame *ref = s->framep[mb->ref_frame];
+    VP56mv *bmv = mb->bmv;
+
+    switch (mb->partitioning) {
+    case VP8_SPLITMVMODE_NONE:
+        vp8_mc_part(s, dst, ref, x_off, y_off,
+                    0, 0, 16, 16, width, height, &mb->mv);
+        break;
+    case VP8_SPLITMVMODE_4x4: {
+        int x, y;
+        VP56mv uvmv;
+
+        /* Y */
+        for (y = 0; y < 4; y++) {
+            for (x = 0; x < 4; x++) {
+                vp8_mc_luma(s, dst[0] + 4*y*s->linesize + x*4,
+                            ref->data[0], &bmv[4*y + x],
+                            4*x + x_off, 4*y + y_off, 4, 4,
+                            width, height, s->linesize,
+                            s->put_pixels_tab[2]);
+            }
+        }
+
+        /* U/V */
+        x_off >>= 1; y_off >>= 1; width >>= 1; height >>= 1;
+        for (y = 0; y < 2; y++) {
+            for (x = 0; x < 2; x++) {
+                uvmv.x = mb->bmv[ 2*y    * 4 + 2*x  ].x +
+                         mb->bmv[ 2*y    * 4 + 2*x+1].x +
+                         mb->bmv[(2*y+1) * 4 + 2*x  ].x +
+                         mb->bmv[(2*y+1) * 4 + 2*x+1].x;
+                uvmv.y = mb->bmv[ 2*y    * 4 + 2*x  ].y +
+                         mb->bmv[ 2*y    * 4 + 2*x+1].y +
+                         mb->bmv[(2*y+1) * 4 + 2*x  ].y +
+                         mb->bmv[(2*y+1) * 4 + 2*x+1].y;
+                uvmv.x = (uvmv.x + 2 + (uvmv.x >> (INT_BIT-1))) >> 2;
+                uvmv.y = (uvmv.y + 2 + (uvmv.y >> (INT_BIT-1))) >> 2;
+                if (s->profile == 3) {
+                    uvmv.x &= ~7;
+                    uvmv.y &= ~7;
+                }
+                vp8_mc_chroma(s, dst[1] + 4*y*s->uvlinesize + x*4,
+                              dst[2] + 4*y*s->uvlinesize + x*4,
+                              ref->data[1], ref->data[2], &uvmv,
+                              4*x + x_off, 4*y + y_off, 4, 4,
+                              width, height, s->uvlinesize,
+                              s->put_pixels_tab[2]);
+            }
+        }
+        break;
+    }
+    case VP8_SPLITMVMODE_16x8:
+        vp8_mc_part(s, dst, ref, x_off, y_off,
+                    0, 0, 16, 8, width, height, &bmv[0]);
+        vp8_mc_part(s, dst, ref, x_off, y_off,
+                    0, 8, 16, 8, width, height, &bmv[1]);
+        break;
+    case VP8_SPLITMVMODE_8x16:
+        vp8_mc_part(s, dst, ref, x_off, y_off,
+                    0, 0, 8, 16, width, height, &bmv[0]);
+        vp8_mc_part(s, dst, ref, x_off, y_off,
+                    8, 0, 8, 16, width, height, &bmv[1]);
+        break;
+    case VP8_SPLITMVMODE_8x8:
+        vp8_mc_part(s, dst, ref, x_off, y_off,
+                    0, 0, 8, 8, width, height, &bmv[0]);
+        vp8_mc_part(s, dst, ref, x_off, y_off,
+                    8, 0, 8, 8, width, height, &bmv[1]);
+        vp8_mc_part(s, dst, ref, x_off, y_off,
+                    0, 8, 8, 8, width, height, &bmv[2]);
+        vp8_mc_part(s, dst, ref, x_off, y_off,
+                    8, 8, 8, 8, width, height, &bmv[3]);
+        break;
+    }
+}
+
+static av_always_inline void idct_mb(VP8Context *s, uint8_t *dst[3], VP8Macroblock *mb)
+{
+    int x, y, ch;
+
+    if (mb->mode != MODE_I4x4) {
+        uint8_t *y_dst = dst[0];
+        for (y = 0; y < 4; y++) {
+            uint32_t nnz4 = AV_RL32(s->non_zero_count_cache[y]);
+            if (nnz4) {
+                if (nnz4&~0x01010101) {
+                    for (x = 0; x < 4; x++) {
+                        if ((uint8_t)nnz4 == 1)
+                            s->vp8dsp.vp8_idct_dc_add(y_dst+4*x, s->block[y][x], s->linesize);
+                        else if((uint8_t)nnz4 > 1)
+                            s->vp8dsp.vp8_idct_add(y_dst+4*x, s->block[y][x], s->linesize);
+                        nnz4 >>= 8;
+                        if (!nnz4)
+                            break;
+                    }
+                } else {
+                    s->vp8dsp.vp8_idct_dc_add4y(y_dst, s->block[y], s->linesize);
+                }
+            }
+            y_dst += 4*s->linesize;
+        }
+    }
+
+    for (ch = 0; ch < 2; ch++) {
+        uint32_t nnz4 = AV_RL32(s->non_zero_count_cache[4+ch]);
+        if (nnz4) {
+            uint8_t *ch_dst = dst[1+ch];
+            if (nnz4&~0x01010101) {
+                for (y = 0; y < 2; y++) {
+                    for (x = 0; x < 2; x++) {
+                        if ((uint8_t)nnz4 == 1)
+                            s->vp8dsp.vp8_idct_dc_add(ch_dst+4*x, s->block[4+ch][(y<<1)+x], s->uvlinesize);
+                        else if((uint8_t)nnz4 > 1)
+                            s->vp8dsp.vp8_idct_add(ch_dst+4*x, s->block[4+ch][(y<<1)+x], s->uvlinesize);
+                        nnz4 >>= 8;
+                        if (!nnz4)
+                            goto chroma_idct_end;
+                    }
+                    ch_dst += 4*s->uvlinesize;
+                }
+            } else {
+                s->vp8dsp.vp8_idct_dc_add4uv(ch_dst, s->block[4+ch], s->uvlinesize);
+            }
+        }
+chroma_idct_end: ;
+    }
+}
+
+static av_always_inline void filter_level_for_mb(VP8Context *s, VP8Macroblock *mb, VP8FilterStrength *f )
+{
+    int interior_limit, filter_level;
+
+    if (s->segmentation.enabled) {
+        filter_level = s->segmentation.filter_level[s->segment];
+        if (!s->segmentation.absolute_vals)
+            filter_level += s->filter.level;
+    } else
+        filter_level = s->filter.level;
+
+    if (s->lf_delta.enabled) {
+        filter_level += s->lf_delta.ref[mb->ref_frame];
+        filter_level += s->lf_delta.mode[mb->mode];
+    }
+
+/* Like av_clip for inputs 0 and max, where max is equal to (2^n-1) */
+#define POW2CLIP(x,max) (((x) & ~max) ? (-(x))>>31 & max : (x));
+    filter_level = POW2CLIP(filter_level, 63);
+
+    interior_limit = filter_level;
+    if (s->filter.sharpness) {
+        interior_limit >>= (s->filter.sharpness + 3) >> 2;
+        interior_limit = FFMIN(interior_limit, 9 - s->filter.sharpness);
+    }
+    interior_limit = FFMAX(interior_limit, 1);
+
+    f->filter_level = filter_level;
+    f->inner_limit = interior_limit;
+    f->inner_filter = !mb->skip || mb->mode == MODE_I4x4 || mb->mode == VP8_MVMODE_SPLIT;
+}
+
+static av_always_inline void filter_mb(VP8Context *s, uint8_t *dst[3], VP8FilterStrength *f, int mb_x, int mb_y)
+{
+    int mbedge_lim, bedge_lim, hev_thresh;
+    int filter_level = f->filter_level;
+    int inner_limit = f->inner_limit;
+    int inner_filter = f->inner_filter;
+    int linesize = s->linesize;
+    int uvlinesize = s->uvlinesize;
+    static const uint8_t hev_thresh_lut[2][64] = {
+        { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1,
+          2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+          3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
+          3, 3, 3, 3 },
+        { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1,
+          1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+          2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+          2, 2, 2, 2 }
+    };
+
+    if (!filter_level)
+        return;
+
+     bedge_lim = 2*filter_level + inner_limit;
+    mbedge_lim = bedge_lim + 4;
+
+    hev_thresh = hev_thresh_lut[s->keyframe][filter_level];
+
+    if (mb_x) {
+        s->vp8dsp.vp8_h_loop_filter16y(dst[0],     linesize,
+                                       mbedge_lim, inner_limit, hev_thresh);
+        s->vp8dsp.vp8_h_loop_filter8uv(dst[1],     dst[2],      uvlinesize,
+                                       mbedge_lim, inner_limit, hev_thresh);
+    }
+
+    if (inner_filter) {
+        s->vp8dsp.vp8_h_loop_filter16y_inner(dst[0]+ 4, linesize, bedge_lim,
+                                             inner_limit, hev_thresh);
+        s->vp8dsp.vp8_h_loop_filter16y_inner(dst[0]+ 8, linesize, bedge_lim,
+                                             inner_limit, hev_thresh);
+        s->vp8dsp.vp8_h_loop_filter16y_inner(dst[0]+12, linesize, bedge_lim,
+                                             inner_limit, hev_thresh);
+        s->vp8dsp.vp8_h_loop_filter8uv_inner(dst[1] + 4, dst[2] + 4,
+                                             uvlinesize,  bedge_lim,
+                                             inner_limit, hev_thresh);
+    }
+
+    if (mb_y) {
+        s->vp8dsp.vp8_v_loop_filter16y(dst[0],     linesize,
+                                       mbedge_lim, inner_limit, hev_thresh);
+        s->vp8dsp.vp8_v_loop_filter8uv(dst[1],     dst[2],      uvlinesize,
+                                       mbedge_lim, inner_limit, hev_thresh);
+    }
+
+    if (inner_filter) {
+        s->vp8dsp.vp8_v_loop_filter16y_inner(dst[0]+ 4*linesize,
+                                             linesize,    bedge_lim,
+                                             inner_limit, hev_thresh);
+        s->vp8dsp.vp8_v_loop_filter16y_inner(dst[0]+ 8*linesize,
+                                             linesize,    bedge_lim,
+                                             inner_limit, hev_thresh);
+        s->vp8dsp.vp8_v_loop_filter16y_inner(dst[0]+12*linesize,
+                                             linesize,    bedge_lim,
+                                             inner_limit, hev_thresh);
+        s->vp8dsp.vp8_v_loop_filter8uv_inner(dst[1] + 4 * uvlinesize,
+                                             dst[2] + 4 * uvlinesize,
+                                             uvlinesize,  bedge_lim,
+                                             inner_limit, hev_thresh);
+    }
+}
+
+static av_always_inline void filter_mb_simple(VP8Context *s, uint8_t *dst, VP8FilterStrength *f, int mb_x, int mb_y)
+{
+    int mbedge_lim, bedge_lim;
+    int filter_level = f->filter_level;
+    int inner_limit = f->inner_limit;
+    int inner_filter = f->inner_filter;
+    int linesize = s->linesize;
+
+    if (!filter_level)
+        return;
+
+     bedge_lim = 2*filter_level + inner_limit;
+    mbedge_lim = bedge_lim + 4;
+
+    if (mb_x)
+        s->vp8dsp.vp8_h_loop_filter_simple(dst, linesize, mbedge_lim);
+    if (inner_filter) {
+        s->vp8dsp.vp8_h_loop_filter_simple(dst+ 4, linesize, bedge_lim);
+        s->vp8dsp.vp8_h_loop_filter_simple(dst+ 8, linesize, bedge_lim);
+        s->vp8dsp.vp8_h_loop_filter_simple(dst+12, linesize, bedge_lim);
+    }
+
+    if (mb_y)
+        s->vp8dsp.vp8_v_loop_filter_simple(dst, linesize, mbedge_lim);
+    if (inner_filter) {
+        s->vp8dsp.vp8_v_loop_filter_simple(dst+ 4*linesize, linesize, bedge_lim);
+        s->vp8dsp.vp8_v_loop_filter_simple(dst+ 8*linesize, linesize, bedge_lim);
+        s->vp8dsp.vp8_v_loop_filter_simple(dst+12*linesize, linesize, bedge_lim);
+    }
+}
+
+static void filter_mb_row(VP8Context *s, int mb_y)
+{
+    VP8FilterStrength *f = s->filter_strength;
+    uint8_t *dst[3] = {
+        s->framep[VP56_FRAME_CURRENT]->data[0] + 16*mb_y*s->linesize,
+        s->framep[VP56_FRAME_CURRENT]->data[1] +  8*mb_y*s->uvlinesize,
+        s->framep[VP56_FRAME_CURRENT]->data[2] +  8*mb_y*s->uvlinesize
+    };
+    int mb_x;
+
+    for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
+        backup_mb_border(s->top_border[mb_x+1], dst[0], dst[1], dst[2], s->linesize, s->uvlinesize, 0);
+        filter_mb(s, dst, f++, mb_x, mb_y);
+        dst[0] += 16;
+        dst[1] += 8;
+        dst[2] += 8;
+    }
+}
+
+static void filter_mb_row_simple(VP8Context *s, int mb_y)
+{
+    VP8FilterStrength *f = s->filter_strength;
+    uint8_t *dst = s->framep[VP56_FRAME_CURRENT]->data[0] + 16*mb_y*s->linesize;
+    int mb_x;
+
+    for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
+        backup_mb_border(s->top_border[mb_x+1], dst, NULL, NULL, s->linesize, 0, 1);
+        filter_mb_simple(s, dst, f++, mb_x, mb_y);
+        dst += 16;
+    }
+}
+
+static int vp8_decode_frame(AVCodecContext *avctx, void *data, int *data_size,
+                            AVPacket *avpkt)
+{
+    VP8Context *s = avctx->priv_data;
+    int ret, mb_x, mb_y, i, y, referenced;
+    enum AVDiscard skip_thresh;
+    AVFrame *av_uninit(curframe);
+
+    if ((ret = decode_frame_header(s, avpkt->data, avpkt->size)) < 0)
+        return ret;
+
+    referenced = s->update_last || s->update_golden == VP56_FRAME_CURRENT
+                                || s->update_altref == VP56_FRAME_CURRENT;
+
+    skip_thresh = !referenced ? AVDISCARD_NONREF :
+                    !s->keyframe ? AVDISCARD_NONKEY : AVDISCARD_ALL;
+
+    if (avctx->skip_frame >= skip_thresh) {
+        s->invisible = 1;
+        goto skip_decode;
+    }
+    s->deblock_filter = s->filter.level && avctx->skip_loop_filter < skip_thresh;
+
+    for (i = 0; i < 4; i++)
+        if (&s->frames[i] != s->framep[VP56_FRAME_PREVIOUS] &&
+            &s->frames[i] != s->framep[VP56_FRAME_GOLDEN] &&
+            &s->frames[i] != s->framep[VP56_FRAME_GOLDEN2]) {
+            curframe = s->framep[VP56_FRAME_CURRENT] = &s->frames[i];
+            break;
+        }
+    if (curframe->data[0])
+        avctx->release_buffer(avctx, curframe);
+
+    curframe->key_frame = s->keyframe;
+    curframe->pict_type = s->keyframe ? FF_I_TYPE : FF_P_TYPE;
+    curframe->reference = referenced ? 3 : 0;
+    if ((ret = avctx->get_buffer(avctx, curframe))) {
+        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed!\n");
+        return ret;
+    }
+
+    // Given that arithmetic probabilities are updated every frame, it's quite likely
+    // that the values we have on a random interframe are complete junk if we didn't
+    // start decode on a keyframe. So just don't display anything rather than junk.
+    if (!s->keyframe && (!s->framep[VP56_FRAME_PREVIOUS] ||
+                         !s->framep[VP56_FRAME_GOLDEN] ||
+                         !s->framep[VP56_FRAME_GOLDEN2])) {
+        av_log(avctx, AV_LOG_WARNING, "Discarding interframe without a prior keyframe!\n");
+        return AVERROR_INVALIDDATA;
+    }
+
+    s->linesize   = curframe->linesize[0];
+    s->uvlinesize = curframe->linesize[1];
+
+    if (!s->edge_emu_buffer)
+        s->edge_emu_buffer = av_malloc(21*s->linesize);
+
+    memset(s->top_nnz, 0, s->mb_width*sizeof(*s->top_nnz));
+
+    /* Zero macroblock structures for top/top-left prediction from outside the frame. */
+    memset(s->macroblocks + s->mb_height*2 - 1, 0, (s->mb_width+1)*sizeof(*s->macroblocks));
+
+    // top edge of 127 for intra prediction
+    if (!(avctx->flags & CODEC_FLAG_EMU_EDGE)) {
+        s->top_border[0][15] = s->top_border[0][23] = 127;
+        memset(s->top_border[1]-1, 127, s->mb_width*sizeof(*s->top_border)+1);
+    }
+    memset(s->ref_count, 0, sizeof(s->ref_count));
+    if (s->keyframe)
+        memset(s->intra4x4_pred_mode_top, DC_PRED, s->mb_width*4);
+
+    #define MARGIN (16 << 2)
+    s->mv_min.y = -MARGIN;
+    s->mv_max.y = ((s->mb_height - 1) << 6) + MARGIN;
+
+    for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
+        VP56RangeCoder *c = &s->coeff_partition[mb_y & (s->num_coeff_partitions-1)];
+        VP8Macroblock *mb = s->macroblocks + (s->mb_height - mb_y - 1)*2;
+        int mb_xy = mb_y*s->mb_width;
+        uint8_t *dst[3] = {
+            curframe->data[0] + 16*mb_y*s->linesize,
+            curframe->data[1] +  8*mb_y*s->uvlinesize,
+            curframe->data[2] +  8*mb_y*s->uvlinesize
+        };
+
+        memset(mb - 1, 0, sizeof(*mb));   // zero left macroblock
+        memset(s->left_nnz, 0, sizeof(s->left_nnz));
+        AV_WN32A(s->intra4x4_pred_mode_left, DC_PRED*0x01010101);
+
+        // left edge of 129 for intra prediction
+        if (!(avctx->flags & CODEC_FLAG_EMU_EDGE)) {
+            for (i = 0; i < 3; i++)
+                for (y = 0; y < 16>>!!i; y++)
+                    dst[i][y*curframe->linesize[i]-1] = 129;
+            if (mb_y == 1) // top left edge is also 129
+                s->top_border[0][15] = s->top_border[0][23] = s->top_border[0][31] = 129;
+        }
+
+        s->mv_min.x = -MARGIN;
+        s->mv_max.x = ((s->mb_width  - 1) << 6) + MARGIN;
+
+        for (mb_x = 0; mb_x < s->mb_width; mb_x++, mb_xy++, mb++) {
+            /* Prefetch the current frame, 4 MBs ahead */
+            s->dsp.prefetch(dst[0] + (mb_x&3)*4*s->linesize + 64, s->linesize, 4);
+            s->dsp.prefetch(dst[1] + (mb_x&7)*s->uvlinesize + 64, dst[2] - dst[1], 2);
+
+            decode_mb_mode(s, mb, mb_x, mb_y, s->segmentation_map + mb_xy);
+
+            prefetch_motion(s, mb, mb_x, mb_y, mb_xy, VP56_FRAME_PREVIOUS);
+
+            if (!mb->skip)
+                decode_mb_coeffs(s, c, mb, s->top_nnz[mb_x], s->left_nnz);
+
+            if (mb->mode <= MODE_I4x4)
+                intra_predict(s, dst, mb, mb_x, mb_y);
+            else
+                inter_predict(s, dst, mb, mb_x, mb_y);
+
+            prefetch_motion(s, mb, mb_x, mb_y, mb_xy, VP56_FRAME_GOLDEN);
+
+            if (!mb->skip) {
+                idct_mb(s, dst, mb);
+            } else {
+                AV_ZERO64(s->left_nnz);
+                AV_WN64(s->top_nnz[mb_x], 0);   // array of 9, so unaligned
+
+                // Reset DC block predictors if they would exist if the mb had coefficients
+                if (mb->mode != MODE_I4x4 && mb->mode != VP8_MVMODE_SPLIT) {
+                    s->left_nnz[8]      = 0;
+                    s->top_nnz[mb_x][8] = 0;
+                }
+            }
+
+            if (s->deblock_filter)
+                filter_level_for_mb(s, mb, &s->filter_strength[mb_x]);
+
+            prefetch_motion(s, mb, mb_x, mb_y, mb_xy, VP56_FRAME_GOLDEN2);
+
+            dst[0] += 16;
+            dst[1] += 8;
+            dst[2] += 8;
+            s->mv_min.x -= 64;
+            s->mv_max.x -= 64;
+        }
+        if (s->deblock_filter) {
+            if (s->filter.simple)
+                filter_mb_row_simple(s, mb_y);
+            else
+                filter_mb_row(s, mb_y);
+        }
+        s->mv_min.y -= 64;
+        s->mv_max.y -= 64;
+    }
+
+skip_decode:
+    // if future frames don't use the updated probabilities,
+    // reset them to the values we saved
+    if (!s->update_probabilities)
+        s->prob[0] = s->prob[1];
+
+    // check if golden and altref are swapped
+    if (s->update_altref == VP56_FRAME_GOLDEN &&
+        s->update_golden == VP56_FRAME_GOLDEN2)
+        FFSWAP(AVFrame *, s->framep[VP56_FRAME_GOLDEN], s->framep[VP56_FRAME_GOLDEN2]);
+    else {
+        if (s->update_altref != VP56_FRAME_NONE)
+            s->framep[VP56_FRAME_GOLDEN2] = s->framep[s->update_altref];
+
+        if (s->update_golden != VP56_FRAME_NONE)
+            s->framep[VP56_FRAME_GOLDEN] = s->framep[s->update_golden];
+    }
+
+    if (s->update_last) // move cur->prev
+        s->framep[VP56_FRAME_PREVIOUS] = s->framep[VP56_FRAME_CURRENT];
+
+    // release no longer referenced frames
+    for (i = 0; i < 4; i++)
+        if (s->frames[i].data[0] &&
+            &s->frames[i] != s->framep[VP56_FRAME_CURRENT] &&
+            &s->frames[i] != s->framep[VP56_FRAME_PREVIOUS] &&
+            &s->frames[i] != s->framep[VP56_FRAME_GOLDEN] &&
+            &s->frames[i] != s->framep[VP56_FRAME_GOLDEN2])
+            avctx->release_buffer(avctx, &s->frames[i]);
+
+    if (!s->invisible) {
+        *(AVFrame*)data = *s->framep[VP56_FRAME_CURRENT];
+        *data_size = sizeof(AVFrame);
+    }
+
+    return avpkt->size;
+}
+
+static av_cold int vp8_decode_init(AVCodecContext *avctx)
+{
+    VP8Context *s = avctx->priv_data;
+
+    s->avctx = avctx;
+    avctx->pix_fmt = PIX_FMT_YUV420P;
+
+    dsputil_init(&s->dsp, avctx);
+    ff_h264_pred_init(&s->hpc, CODEC_ID_VP8);
+    ff_vp8dsp_init(&s->vp8dsp);
+
+    return 0;
+}
+
+static av_cold int vp8_decode_free(AVCodecContext *avctx)
+{
+    vp8_decode_flush(avctx);
+    return 0;
+}
+
+AVCodec ff_vp8_decoder = {
+    "vp8",
+    AVMEDIA_TYPE_VIDEO,
+    CODEC_ID_VP8,
+    sizeof(VP8Context),
+    vp8_decode_init,
+    NULL,
+    vp8_decode_free,
+    vp8_decode_frame,
+    CODEC_CAP_DR1,
+    .flush = vp8_decode_flush,
+    .long_name = NULL_IF_CONFIG_SMALL("On2 VP8"),
+};
diff --git a/libavcodec/vp8.h b/libavcodec/vp8.h
new file mode 100644
index 0000000..e4a6ef1
--- /dev/null
+++ b/libavcodec/vp8.h
@@ -0,0 +1,241 @@
+/**
+ * VP8 compatible video decoder
+ *
+ * Copyright (C) 2010 David Conrad
+ * Copyright (C) 2010 Ronald S. Bultje
+ * Copyright (C) 2010 Jason Garrett-Glaser
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_VP8_H
+#define AVCODEC_VP8_H
+
+#include "vp56.h"
+#include "vp56data.h"
+#include "vp8dsp.h"
+#include "h264pred.h"
+
+#define VP8_MAX_QUANT 127
+
+enum dct_token {
+    DCT_0,
+    DCT_1,
+    DCT_2,
+    DCT_3,
+    DCT_4,
+    DCT_CAT1,
+    DCT_CAT2,
+    DCT_CAT3,
+    DCT_CAT4,
+    DCT_CAT5,
+    DCT_CAT6,
+    DCT_EOB,
+
+    NUM_DCT_TOKENS
+};
+
+// used to signal 4x4 intra pred in luma MBs
+#define MODE_I4x4 4
+
+enum inter_mvmode {
+    VP8_MVMODE_ZERO = MODE_I4x4 + 1,
+    VP8_MVMODE_MV,
+    VP8_MVMODE_SPLIT
+};
+
+enum inter_splitmvmode {
+    VP8_SPLITMVMODE_16x8 = 0,    ///< 2 16x8 blocks (vertical)
+    VP8_SPLITMVMODE_8x16,        ///< 2 8x16 blocks (horizontal)
+    VP8_SPLITMVMODE_8x8,         ///< 2x2 blocks of 8x8px each
+    VP8_SPLITMVMODE_4x4,         ///< 4x4 blocks of 4x4px each
+    VP8_SPLITMVMODE_NONE,        ///< (only used in prediction) no split MVs
+};
+
+typedef struct {
+    uint8_t filter_level;
+    uint8_t inner_limit;
+    uint8_t inner_filter;
+} VP8FilterStrength;
+
+typedef struct {
+    uint8_t skip;
+    // todo: make it possible to check for at least (i4x4 or split_mv)
+    // in one op. are others needed?
+    uint8_t mode;
+    uint8_t ref_frame;
+    uint8_t partitioning;
+    VP56mv mv;
+    VP56mv bmv[16];
+} VP8Macroblock;
+
+typedef struct {
+    AVCodecContext *avctx;
+    AVFrame *framep[4];
+    uint8_t *edge_emu_buffer;
+
+    uint16_t mb_width;   /* number of horizontal MB */
+    uint16_t mb_height;  /* number of vertical MB */
+    int linesize;
+    int uvlinesize;
+
+    uint8_t keyframe;
+    uint8_t deblock_filter;
+    uint8_t mbskip_enabled;
+    uint8_t segment;             ///< segment of the current macroblock
+    uint8_t chroma_pred_mode;    ///< 8x8c pred mode of the current macroblock
+    uint8_t profile;
+    VP56mv mv_min;
+    VP56mv mv_max;
+
+    int8_t sign_bias[4]; ///< one state [0, 1] per ref frame type
+    int ref_count[3];
+
+    /**
+     * Base parameters for segmentation, i.e. per-macroblock parameters.
+     * These must be kept unchanged even if segmentation is not used for
+     * a frame, since the values persist between interframes.
+     */
+    struct {
+        uint8_t enabled;
+        uint8_t absolute_vals;
+        uint8_t update_map;
+        int8_t base_quant[4];
+        int8_t filter_level[4];     ///< base loop filter level
+    } segmentation;
+
+    struct {
+        uint8_t simple;
+        uint8_t level;
+        uint8_t sharpness;
+    } filter;
+
+    VP8Macroblock *macroblocks;
+    VP8FilterStrength *filter_strength;
+
+    uint8_t *intra4x4_pred_mode_top;
+    uint8_t intra4x4_pred_mode_left[4];
+    uint8_t *segmentation_map;
+
+    /**
+     * Macroblocks can have one of 4 different quants in a frame when
+     * segmentation is enabled.
+     * If segmentation is disabled, only the first segment's values are used.
+     */
+    struct {
+        // [0] - DC qmul  [1] - AC qmul
+        int16_t luma_qmul[2];
+        int16_t luma_dc_qmul[2];    ///< luma dc-only block quant
+        int16_t chroma_qmul[2];
+    } qmat[4];
+
+    struct {
+        uint8_t enabled;    ///< whether each mb can have a different strength based on mode/ref
+
+        /**
+         * filter strength adjustment for the following macroblock modes:
+         * [0-3] - i16x16 (always zero)
+         * [4]   - i4x4
+         * [5]   - zero mv
+         * [6]   - inter modes except for zero or split mv
+         * [7]   - split mv
+         *  i16x16 modes never have any adjustment
+         */
+        int8_t mode[VP8_MVMODE_SPLIT+1];
+
+        /**
+         * filter strength adjustment for macroblocks that reference:
+         * [0] - intra / VP56_FRAME_CURRENT
+         * [1] - VP56_FRAME_PREVIOUS
+         * [2] - VP56_FRAME_GOLDEN
+         * [3] - altref / VP56_FRAME_GOLDEN2
+         */
+        int8_t ref[4];
+    } lf_delta;
+
+    /**
+     * Cache of the top row needed for intra prediction
+     * 16 for luma, 8 for each chroma plane
+     */
+    uint8_t (*top_border)[16+8+8];
+
+    /**
+     * For coeff decode, we need to know whether the above block had non-zero
+     * coefficients. This means for each macroblock, we need data for 4 luma
+     * blocks, 2 u blocks, 2 v blocks, and the luma dc block, for a total of 9
+     * per macroblock. We keep the last row in top_nnz.
+     */
+    uint8_t (*top_nnz)[9];
+    DECLARE_ALIGNED(8, uint8_t, left_nnz)[9];
+
+    /**
+     * This is the index plus one of the last non-zero coeff
+     * for each of the blocks in the current macroblock.
+     * So, 0 -> no coeffs
+     *     1 -> dc-only (special transform)
+     *     2+-> full transform
+     */
+    DECLARE_ALIGNED(16, uint8_t, non_zero_count_cache)[6][4];
+    VP56RangeCoder c;   ///< header context, includes mb modes and motion vectors
+    DECLARE_ALIGNED(16, DCTELEM, block)[6][4][16];
+    DECLARE_ALIGNED(16, DCTELEM, block_dc)[16];
+    uint8_t intra4x4_pred_mode_mb[16];
+
+    /**
+     * These are all of the updatable probabilities for binary decisions.
+     * They are only implictly reset on keyframes, making it quite likely
+     * for an interframe to desync if a prior frame's header was corrupt
+     * or missing outright!
+     */
+    struct {
+        uint8_t segmentid[3];
+        uint8_t mbskip;
+        uint8_t intra;
+        uint8_t last;
+        uint8_t golden;
+        uint8_t pred16x16[4];
+        uint8_t pred8x8c[3];
+        uint8_t token[4][16][3][NUM_DCT_TOKENS-1];
+        uint8_t mvc[2][19];
+    } prob[2];
+
+    VP8Macroblock *macroblocks_base;
+    int invisible;
+    int update_last;    ///< update VP56_FRAME_PREVIOUS with the current one
+    int update_golden;  ///< VP56_FRAME_NONE if not updated, or which frame to copy if so
+    int update_altref;
+
+    /**
+     * If this flag is not set, all the probability updates
+     * are discarded after this frame is decoded.
+     */
+    int update_probabilities;
+
+    /**
+     * All coefficients are contained in separate arith coding contexts.
+     * There can be 1, 2, 4, or 8 of these after the header context.
+     */
+    int num_coeff_partitions;
+    VP56RangeCoder coeff_partition[8];
+    DSPContext dsp;
+    VP8DSPContext vp8dsp;
+    H264PredContext hpc;
+    vp8_mc_func put_pixels_tab[3][3][3];
+    AVFrame frames[4];
+} VP8Context;
+
+#endif
diff --git a/libavcodec/vp8_parser.c b/libavcodec/vp8_parser.c
new file mode 100644
index 0000000..0f2dd4e
--- /dev/null
+++ b/libavcodec/vp8_parser.c
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2008 Michael Niedermayer
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "parser.h"
+
+static int parse(AVCodecParserContext *s,
+                           AVCodecContext *avctx,
+                           const uint8_t **poutbuf, int *poutbuf_size,
+                           const uint8_t *buf, int buf_size)
+{
+    s->pict_type= (buf[0]&0x01) ? FF_P_TYPE : FF_I_TYPE;
+
+    *poutbuf = buf;
+    *poutbuf_size = buf_size;
+    return buf_size;
+}
+
+AVCodecParser ff_vp8_parser = {
+    { CODEC_ID_VP8 },
+    0,
+    NULL,
+    parse,
+};
diff --git a/libavcodec/vp8data.h b/libavcodec/vp8data.h
new file mode 100644
index 0000000..6d1c070
--- /dev/null
+++ b/libavcodec/vp8data.h
@@ -0,0 +1,688 @@
+/**
+ * VP8 compatible video decoder
+ *
+ * Copyright (C) 2010 David Conrad
+ * Copyright (C) 2010 Ronald S. Bultje
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_VP8DATA_H
+#define AVCODEC_VP8DATA_H
+
+#include "vp8.h"
+#include "h264pred.h"
+
+static const uint8_t vp8_pred4x4_mode[] =
+{
+    [DC_PRED8x8]    = DC_PRED,
+    [VERT_PRED8x8]  = VERT_PRED,
+    [HOR_PRED8x8]   = HOR_PRED,
+    [PLANE_PRED8x8] = TM_VP8_PRED,
+};
+
+static const int8_t vp8_pred16x16_tree_intra[4][2] =
+{
+    { -MODE_I4x4, 1 },                      // '0'
+     { 2, 3 },
+      {  -DC_PRED8x8,  -VERT_PRED8x8 },     // '100', '101'
+      { -HOR_PRED8x8, -PLANE_PRED8x8 },     // '110', '111'
+};
+
+static const int8_t vp8_pred16x16_tree_inter[4][2] =
+{
+    { -DC_PRED8x8, 1 },                     // '0'
+     { 2, 3 },
+      {  -VERT_PRED8x8, -HOR_PRED8x8 },     // '100', '101'
+      { -PLANE_PRED8x8, -MODE_I4x4 },       // '110', '111'
+};
+
+static const int vp8_mode_contexts[6][4] = {
+    {   7,   1,   1, 143 },
+    {  14,  18,  14, 107 },
+    { 135,  64,  57,  68 },
+    {  60,  56, 128,  65 },
+    { 159, 134, 128,  34 },
+    { 234, 188, 128,  28 },
+};
+
+static const uint8_t vp8_mbsplits[5][16] = {
+    {  0,  0,  0,  0,  0,  0,  0,  0,
+       1,  1,  1,  1,  1,  1,  1,  1  },
+    {  0,  0,  1,  1,  0,  0,  1,  1,
+       0,  0,  1,  1,  0,  0,  1,  1  },
+    {  0,  0,  1,  1,  0,  0,  1,  1,
+       2,  2,  3,  3,  2,  2,  3,  3  },
+    {  0,  1,  2,  3,  4,  5,  6,  7,
+       8,  9, 10, 11, 12, 13, 14, 15  },
+    {  0,  0,  0,  0,  0,  0,  0,  0,
+       0,  0,  0,  0,  0,  0,  0,  0  }
+};
+
+static const uint8_t vp8_mbfirstidx[4][16] = {
+    {  0,  8 }, {  0,  2 }, {  0,  2,  8,  10 },
+    {  0,  1,  2,  3,  4,  5,  6,  7,
+       8,  9, 10, 11, 12, 13, 14, 15 }
+};
+
+static const uint8_t vp8_mbsplit_count[4] = {   2,   2,   4,  16 };
+static const uint8_t vp8_mbsplit_prob[3]  = { 110, 111, 150 };
+
+static const uint8_t vp8_submv_prob[5][3] = {
+    { 147, 136,  18 },
+    { 106, 145,   1 },
+    { 179, 121,   1 },
+    { 223,   1,  34 },
+    { 208,   1,   1 }
+};
+
+static const uint8_t vp8_pred16x16_prob_intra[4] = { 145, 156, 163, 128 };
+static const uint8_t vp8_pred16x16_prob_inter[4] = { 112,  86, 140,  37 };
+
+static const int8_t vp8_pred4x4_tree[9][2] =
+{
+    { -DC_PRED, 1 },                                    // '0'
+     { -TM_VP8_PRED, 2 },                               // '10'
+      { -VERT_PRED, 3 },                                // '110'
+       { 4, 6 },
+        { -HOR_PRED, 5 },                               // '11100'
+         { -DIAG_DOWN_RIGHT_PRED, -VERT_RIGHT_PRED },   // '111010', '111011'
+        { -DIAG_DOWN_LEFT_PRED, 7 },                    // '11110'
+         { -VERT_LEFT_PRED, 8 },                        // '111110'
+          { -HOR_DOWN_PRED, -HOR_UP_PRED },             // '1111110', '1111111'
+};
+
+static const int8_t vp8_pred8x8c_tree[3][2] =
+{
+    { -DC_PRED8x8, 1 },                 // '0'
+     { -VERT_PRED8x8, 2 },              // '10
+      { -HOR_PRED8x8, -PLANE_PRED8x8 }, // '110', '111'
+};
+
+static const uint8_t vp8_pred8x8c_prob_intra[3] = { 142, 114, 183 };
+static const uint8_t vp8_pred8x8c_prob_inter[3] = { 162, 101, 204 };
+
+static const uint8_t vp8_pred4x4_prob_inter[9] =
+{
+    120, 90, 79, 133, 87, 85, 80, 111, 151
+};
+
+static const uint8_t vp8_pred4x4_prob_intra[10][10][9] =
+{
+    {
+        {  39,  53, 200,  87,  26,  21,  43, 232, 171 },
+        {  56,  34,  51, 104, 114, 102,  29,  93,  77 },
+        {  88,  88, 147, 150,  42,  46,  45, 196, 205 },
+        { 107,  54,  32,  26,  51,   1,  81,  43,  31 },
+        {  39,  28,  85, 171,  58, 165,  90,  98,  64 },
+        {  34,  22, 116, 206,  23,  34,  43, 166,  73 },
+        {  34,  19,  21, 102, 132, 188,  16,  76, 124 },
+        {  68,  25, 106,  22,  64, 171,  36, 225, 114 },
+        {  62,  18,  78,  95,  85,  57,  50,  48,  51 },
+        {  43,  97, 183, 117,  85,  38,  35, 179,  61 },
+    },
+    {
+        { 112, 113,  77,  85, 179, 255,  38, 120, 114 },
+        {  40,  42,   1, 196, 245, 209,  10,  25, 109 },
+        { 193, 101,  35, 159, 215, 111,  89,  46, 111 },
+        { 100,  80,   8,  43, 154,   1,  51,  26,  71 },
+        {  88,  43,  29, 140, 166, 213,  37,  43, 154 },
+        {  61,  63,  30, 155,  67,  45,  68,   1, 209 },
+        {  41,  40,   5, 102, 211, 183,   4,   1, 221 },
+        { 142,  78,  78,  16, 255, 128,  34, 197, 171 },
+        {  51,  50,  17, 168, 209, 192,  23,  25,  82 },
+        {  60, 148,  31, 172, 219, 228,  21,  18, 111 },
+    },
+    {
+        { 175,  69, 143,  80,  85,  82,  72, 155, 103 },
+        {  56,  58,  10, 171, 218, 189,  17,  13, 152 },
+        { 231, 120,  48,  89, 115, 113, 120, 152, 112 },
+        { 144,  71,  10,  38, 171, 213, 144,  34,  26 },
+        { 114,  26,  17, 163,  44, 195,  21,  10, 173 },
+        { 121,  24,  80, 195,  26,  62,  44,  64,  85 },
+        {  63,  20,   8, 114, 114, 208,  12,   9, 226 },
+        { 170,  46,  55,  19, 136, 160,  33, 206,  71 },
+        {  81,  40,  11,  96, 182,  84,  29,  16,  36 },
+        { 152, 179,  64, 126, 170, 118,  46,  70,  95 },
+    },
+    {
+        {  75,  79, 123,  47,  51, 128,  81, 171,   1 },
+        {  57,  17,   5,  71, 102,  57,  53,  41,  49 },
+        { 125,  98,  42,  88, 104,  85, 117, 175,  82 },
+        { 115,  21,   2,  10, 102, 255, 166,  23,   6 },
+        {  38,  33,  13, 121,  57,  73,  26,   1,  85 },
+        {  41,  10,  67, 138,  77, 110,  90,  47, 114 },
+        {  57,  18,  10, 102, 102, 213,  34,  20,  43 },
+        { 101,  29,  16,  10,  85, 128, 101, 196,  26 },
+        { 117,  20,  15,  36, 163, 128,  68,   1,  26 },
+        {  95,  84,  53,  89, 128, 100, 113, 101,  45 },
+    },
+    {
+        {  63,  59,  90, 180,  59, 166,  93,  73, 154 },
+        {  40,  40,  21, 116, 143, 209,  34,  39, 175 },
+        { 138,  31,  36, 171,  27, 166,  38,  44, 229 },
+        {  57,  46,  22,  24, 128,   1,  54,  17,  37 },
+        {  47,  15,  16, 183,  34, 223,  49,  45, 183 },
+        {  46,  17,  33, 183,   6,  98,  15,  32, 183 },
+        {  40,   3,   9, 115,  51, 192,  18,   6, 223 },
+        {  65,  32,  73, 115,  28, 128,  23, 128, 205 },
+        {  87,  37,   9, 115,  59,  77,  64,  21,  47 },
+        {  67,  87,  58, 169,  82, 115,  26,  59, 179 },
+    },
+    {
+        {  54,  57, 112, 184,   5,  41,  38, 166, 213 },
+        {  30,  34,  26, 133, 152, 116,  10,  32, 134 },
+        { 104,  55,  44, 218,   9,  54,  53, 130, 226 },
+        {  75,  32,  12,  51, 192, 255, 160,  43,  51 },
+        {  39,  19,  53, 221,  26, 114,  32,  73, 255 },
+        {  31,   9,  65, 234,   2,  15,   1, 118,  73 },
+        {  56,  21,  23, 111,  59, 205,  45,  37, 192 },
+        {  88,  31,  35,  67, 102,  85,  55, 186,  85 },
+        {  55,  38,  70, 124,  73, 102,   1,  34,  98 },
+        {  64,  90,  70, 205,  40,  41,  23,  26,  57 },
+    },
+    {
+        {  86,  40,  64, 135, 148, 224,  45, 183, 128 },
+        {  22,  26,  17, 131, 240, 154,  14,   1, 209 },
+        { 164,  50,  31, 137, 154, 133,  25,  35, 218 },
+        {  83,  12,  13,  54, 192, 255,  68,  47,  28 },
+        {  45,  16,  21,  91,  64, 222,   7,   1, 197 },
+        {  56,  21,  39, 155,  60, 138,  23, 102, 213 },
+        {  18,  11,   7,  63, 144, 171,   4,   4, 246 },
+        {  85,  26,  85,  85, 128, 128,  32, 146, 171 },
+        {  35,  27,  10, 146, 174, 171,  12,  26, 128 },
+        {  51, 103,  44, 131, 131, 123,  31,   6, 158 },
+    },
+    {
+        {  68,  45, 128,  34,   1,  47,  11, 245, 171 },
+        {  62,  17,  19,  70, 146,  85,  55,  62,  70 },
+        { 102,  61,  71,  37,  34,  53,  31, 243, 192 },
+        {  75,  15,   9,   9,  64, 255, 184, 119,  16 },
+        {  37,  43,  37, 154, 100, 163,  85, 160,   1 },
+        {  63,   9,  92, 136,  28,  64,  32, 201,  85 },
+        {  56,   8,  17, 132, 137, 255,  55, 116, 128 },
+        {  86,   6,  28,   5,  64, 255,  25, 248,   1 },
+        {  58,  15,  20,  82, 135,  57,  26, 121,  40 },
+        {  69,  60,  71,  38,  73, 119,  28, 222,  37 },
+    },
+    {
+        { 101,  75, 128, 139, 118, 146, 116, 128,  85 },
+        {  56,  41,  15, 176, 236,  85,  37,   9,  62 },
+        { 190,  80,  35,  99, 180,  80, 126,  54,  45 },
+        { 146,  36,  19,  30, 171, 255,  97,  27,  20 },
+        {  71,  30,  17, 119, 118, 255,  17,  18, 138 },
+        { 101,  38,  60, 138,  55,  70,  43,  26, 142 },
+        {  32,  41,  20, 117, 151, 142,  20,  21, 163 },
+        { 138,  45,  61,  62, 219,   1,  81, 188,  64 },
+        { 112,  19,  12,  61, 195, 128,  48,   4,  24 },
+        {  85, 126,  47,  87, 176,  51,  41,  20,  32 },
+    },
+    {
+        {  66, 102, 167,  99,  74,  62,  40, 234, 128 },
+        {  41,  53,   9, 178, 241, 141,  26,   8, 107 },
+        { 134, 183,  89, 137,  98, 101, 106, 165, 148 },
+        { 104,  79,  12,  27, 217, 255,  87,  17,   7 },
+        {  74,  43,  26, 146,  73, 166,  49,  23, 157 },
+        {  65,  38, 105, 160,  51,  52,  31, 115, 128 },
+        {  47,  41,  14, 110, 182, 183,  21,  17, 194 },
+        {  87,  68,  71,  44, 114,  51,  15, 186,  23 },
+        {  66,  45,  25, 102, 197, 189,  23,  18,  22 },
+        {  72, 187, 100, 130, 157, 111,  32,  75,  80 },
+    },
+};
+
+static const int8_t vp8_segmentid_tree[][2] =
+{
+    { 1, 2 },
+     { -0, -1 },    // '00', '01'
+     { -2, -3 },    // '10', '11'
+};
+
+static const uint8_t vp8_coeff_band[16] =
+{
+    0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7
+};
+
+/* Inverse of vp8_coeff_band: mappings of bands to coefficient indexes.
+ * Each list is -1-terminated. */
+static const int8_t vp8_coeff_band_indexes[8][10] =
+{
+    {0, -1},
+    {1, -1},
+    {2, -1},
+    {3, -1},
+    {5, -1},
+    {6, -1},
+    {4, 7, 8, 9, 10, 11, 12, 13, 14, -1},
+    {15, -1}
+};
+
+static const uint8_t vp8_dct_cat1_prob[] = { 159, 0 };
+static const uint8_t vp8_dct_cat2_prob[] = { 165, 145, 0 };
+static const uint8_t vp8_dct_cat3_prob[] = { 173, 148, 140, 0 };
+static const uint8_t vp8_dct_cat4_prob[] = { 176, 155, 140, 135, 0 };
+static const uint8_t vp8_dct_cat5_prob[] = { 180, 157, 141, 134, 130, 0 };
+static const uint8_t vp8_dct_cat6_prob[] = { 254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129, 0 };
+
+// only used for cat3 and above; cat 1 and 2 are referenced directly
+const uint8_t * const ff_vp8_dct_cat_prob[] =
+{
+    vp8_dct_cat3_prob,
+    vp8_dct_cat4_prob,
+    vp8_dct_cat5_prob,
+    vp8_dct_cat6_prob,
+};
+
+static const uint8_t vp8_token_default_probs[4][8][3][NUM_DCT_TOKENS-1] =
+{
+    {
+        {
+            { 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128 },
+            { 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128 },
+            { 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128 },
+        },
+        {
+            { 253, 136, 254, 255, 228, 219, 128, 128, 128, 128, 128 },
+            { 189, 129, 242, 255, 227, 213, 255, 219, 128, 128, 128 },
+            { 106, 126, 227, 252, 214, 209, 255, 255, 128, 128, 128 },
+        },
+        {
+            {   1,  98, 248, 255, 236, 226, 255, 255, 128, 128, 128 },
+            { 181, 133, 238, 254, 221, 234, 255, 154, 128, 128, 128 },
+            {  78, 134, 202, 247, 198, 180, 255, 219, 128, 128, 128 },
+        },
+        {
+            {   1, 185, 249, 255, 243, 255, 128, 128, 128, 128, 128 },
+            { 184, 150, 247, 255, 236, 224, 128, 128, 128, 128, 128 },
+            {  77, 110, 216, 255, 236, 230, 128, 128, 128, 128, 128 },
+        },
+        {
+            {   1, 101, 251, 255, 241, 255, 128, 128, 128, 128, 128 },
+            { 170, 139, 241, 252, 236, 209, 255, 255, 128, 128, 128 },
+            {  37, 116, 196, 243, 228, 255, 255, 255, 128, 128, 128 },
+        },
+        {
+            {   1, 204, 254, 255, 245, 255, 128, 128, 128, 128, 128 },
+            { 207, 160, 250, 255, 238, 128, 128, 128, 128, 128, 128 },
+            { 102, 103, 231, 255, 211, 171, 128, 128, 128, 128, 128 },
+        },
+        {
+            {   1, 152, 252, 255, 240, 255, 128, 128, 128, 128, 128 },
+            { 177, 135, 243, 255, 234, 225, 128, 128, 128, 128, 128 },
+            {  80, 129, 211, 255, 194, 224, 128, 128, 128, 128, 128 },
+        },
+        {
+            {   1,   1, 255, 128, 128, 128, 128, 128, 128, 128, 128 },
+            { 246,   1, 255, 128, 128, 128, 128, 128, 128, 128, 128 },
+            { 255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128 },
+        },
+    },
+    {
+        {
+            { 198,  35, 237, 223, 193, 187, 162, 160, 145, 155,  62 },
+            { 131,  45, 198, 221, 172, 176, 220, 157, 252, 221,   1 },
+            {  68,  47, 146, 208, 149, 167, 221, 162, 255, 223, 128 },
+        },
+        {
+            {   1, 149, 241, 255, 221, 224, 255, 255, 128, 128, 128 },
+            { 184, 141, 234, 253, 222, 220, 255, 199, 128, 128, 128 },
+            {  81,  99, 181, 242, 176, 190, 249, 202, 255, 255, 128 },
+        },
+        {
+            {   1, 129, 232, 253, 214, 197, 242, 196, 255, 255, 128 },
+            {  99, 121, 210, 250, 201, 198, 255, 202, 128, 128, 128 },
+            {  23,  91, 163, 242, 170, 187, 247, 210, 255, 255, 128 },
+        },
+        {
+            {   1, 200, 246, 255, 234, 255, 128, 128, 128, 128, 128 },
+            { 109, 178, 241, 255, 231, 245, 255, 255, 128, 128, 128 },
+            {  44, 130, 201, 253, 205, 192, 255, 255, 128, 128, 128 },
+        },
+        {
+            {   1, 132, 239, 251, 219, 209, 255, 165, 128, 128, 128 },
+            {  94, 136, 225, 251, 218, 190, 255, 255, 128, 128, 128 },
+            {  22, 100, 174, 245, 186, 161, 255, 199, 128, 128, 128 },
+        },
+        {
+            {   1, 182, 249, 255, 232, 235, 128, 128, 128, 128, 128 },
+            { 124, 143, 241, 255, 227, 234, 128, 128, 128, 128, 128 },
+            {  35,  77, 181, 251, 193, 211, 255, 205, 128, 128, 128 },
+        },
+        {
+            {   1, 157, 247, 255, 236, 231, 255, 255, 128, 128, 128 },
+            { 121, 141, 235, 255, 225, 227, 255, 255, 128, 128, 128 },
+            {  45,  99, 188, 251, 195, 217, 255, 224, 128, 128, 128 },
+        },
+        {
+            {   1,   1, 251, 255, 213, 255, 128, 128, 128, 128, 128 },
+            { 203,   1, 248, 255, 255, 128, 128, 128, 128, 128, 128 },
+            { 137,   1, 177, 255, 224, 255, 128, 128, 128, 128, 128 },
+        },
+    },
+    {
+        {
+            { 253,   9, 248, 251, 207, 208, 255, 192, 128, 128, 128 },
+            { 175,  13, 224, 243, 193, 185, 249, 198, 255, 255, 128 },
+            {  73,  17, 171, 221, 161, 179, 236, 167, 255, 234, 128 },
+        },
+        {
+            {   1,  95, 247, 253, 212, 183, 255, 255, 128, 128, 128 },
+            { 239,  90, 244, 250, 211, 209, 255, 255, 128, 128, 128 },
+            { 155,  77, 195, 248, 188, 195, 255, 255, 128, 128, 128 },
+        },
+        {
+            {   1,  24, 239, 251, 218, 219, 255, 205, 128, 128, 128 },
+            { 201,  51, 219, 255, 196, 186, 128, 128, 128, 128, 128 },
+            {  69,  46, 190, 239, 201, 218, 255, 228, 128, 128, 128 },
+        },
+        {
+            {   1, 191, 251, 255, 255, 128, 128, 128, 128, 128, 128 },
+            { 223, 165, 249, 255, 213, 255, 128, 128, 128, 128, 128 },
+            { 141, 124, 248, 255, 255, 128, 128, 128, 128, 128, 128 },
+        },
+        {
+            {   1,  16, 248, 255, 255, 128, 128, 128, 128, 128, 128 },
+            { 190,  36, 230, 255, 236, 255, 128, 128, 128, 128, 128 },
+            { 149,   1, 255, 128, 128, 128, 128, 128, 128, 128, 128 },
+        },
+        {
+            {   1, 226, 255, 128, 128, 128, 128, 128, 128, 128, 128 },
+            { 247, 192, 255, 128, 128, 128, 128, 128, 128, 128, 128 },
+            { 240, 128, 255, 128, 128, 128, 128, 128, 128, 128, 128 },
+        },
+        {
+            {   1, 134, 252, 255, 255, 128, 128, 128, 128, 128, 128 },
+            { 213,  62, 250, 255, 255, 128, 128, 128, 128, 128, 128 },
+            {  55,  93, 255, 128, 128, 128, 128, 128, 128, 128, 128 },
+        },
+        {
+            { 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128 },
+            { 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128 },
+            { 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128 },
+        },
+    },
+    {
+        {
+            { 202,  24, 213, 235, 186, 191, 220, 160, 240, 175, 255 },
+            { 126,  38, 182, 232, 169, 184, 228, 174, 255, 187, 128 },
+            {  61,  46, 138, 219, 151, 178, 240, 170, 255, 216, 128 },
+        },
+        {
+            {   1, 112, 230, 250, 199, 191, 247, 159, 255, 255, 128 },
+            { 166, 109, 228, 252, 211, 215, 255, 174, 128, 128, 128 },
+            {  39,  77, 162, 232, 172, 180, 245, 178, 255, 255, 128 },
+        },
+        {
+            {   1,  52, 220, 246, 198, 199, 249, 220, 255, 255, 128 },
+            { 124,  74, 191, 243, 183, 193, 250, 221, 255, 255, 128 },
+            {  24,  71, 130, 219, 154, 170, 243, 182, 255, 255, 128 },
+        },
+        {
+            {   1, 182, 225, 249, 219, 240, 255, 224, 128, 128, 128 },
+            { 149, 150, 226, 252, 216, 205, 255, 171, 128, 128, 128 },
+            {  28, 108, 170, 242, 183, 194, 254, 223, 255, 255, 128 },
+        },
+        {
+            {   1,  81, 230, 252, 204, 203, 255, 192, 128, 128, 128 },
+            { 123, 102, 209, 247, 188, 196, 255, 233, 128, 128, 128 },
+            {  20,  95, 153, 243, 164, 173, 255, 203, 128, 128, 128 },
+        },
+        {
+            {   1, 222, 248, 255, 216, 213, 128, 128, 128, 128, 128 },
+            { 168, 175, 246, 252, 235, 205, 255, 255, 128, 128, 128 },
+            {  47, 116, 215, 255, 211, 212, 255, 255, 128, 128, 128 },
+        },
+        {
+            {   1, 121, 236, 253, 212, 214, 255, 255, 128, 128, 128 },
+            { 141,  84, 213, 252, 201, 202, 255, 219, 128, 128, 128 },
+            {  42,  80, 160, 240, 162, 185, 255, 205, 128, 128, 128 },
+        },
+        {
+            {   1,   1, 255, 128, 128, 128, 128, 128, 128, 128, 128 },
+            { 244,   1, 255, 128, 128, 128, 128, 128, 128, 128, 128 },
+            { 238,   1, 255, 128, 128, 128, 128, 128, 128, 128, 128 },
+        },
+    },
+};
+
+static const uint8_t vp8_token_update_probs[4][8][3][NUM_DCT_TOKENS-1] =
+{
+    {
+        {
+            { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+        },
+        {
+            { 176, 246, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 223, 241, 252, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 249, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255 },
+        },
+        {
+            { 255, 244, 252, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 234, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+        },
+        {
+            { 255, 246, 254, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 239, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255 },
+        },
+        {
+            { 255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 251, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+        },
+        {
+            { 255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 251, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255 },
+        },
+        {
+            { 255, 254, 253, 255, 254, 255, 255, 255, 255, 255, 255 },
+            { 250, 255, 254, 255, 254, 255, 255, 255, 255, 255, 255 },
+            { 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+        },
+        {
+            { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+        },
+    },
+    {
+        {
+            { 217, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 225, 252, 241, 253, 255, 255, 254, 255, 255, 255, 255 },
+            { 234, 250, 241, 250, 253, 255, 253, 254, 255, 255, 255 },
+        },
+        {
+            { 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 223, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 238, 253, 254, 254, 255, 255, 255, 255, 255, 255, 255 },
+        },
+        {
+            { 255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 249, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+        },
+        {
+            { 255, 253, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 247, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+        },
+        {
+            { 255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 252, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+        },
+        {
+            { 255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+        },
+        {
+            { 255, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+        },
+        {
+            { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+        },
+    },
+    {
+        {
+            { 186, 251, 250, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 234, 251, 244, 254, 255, 255, 255, 255, 255, 255, 255 },
+            { 251, 251, 243, 253, 254, 255, 254, 255, 255, 255, 255 },
+        },
+        {
+            { 255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 236, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 251, 253, 253, 254, 254, 255, 255, 255, 255, 255, 255 },
+        },
+        {
+            { 255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+        },
+        {
+            { 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+        },
+        {
+            { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+        },
+        {
+            { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+        },
+        {
+            { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+        },
+        {
+            { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+        },
+    },
+    {
+        {
+            { 248, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 250, 254, 252, 254, 255, 255, 255, 255, 255, 255, 255 },
+            { 248, 254, 249, 253, 255, 255, 255, 255, 255, 255, 255 },
+        },
+        {
+            { 255, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 246, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 252, 254, 251, 254, 254, 255, 255, 255, 255, 255, 255 },
+        },
+        {
+            { 255, 254, 252, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 248, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 253, 255, 254, 254, 255, 255, 255, 255, 255, 255, 255 },
+        },
+        {
+            { 255, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 245, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 253, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255 },
+        },
+        {
+            { 255, 251, 253, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 252, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+        },
+        {
+            { 255, 252, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 249, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255 },
+        },
+        {
+            { 255, 255, 253, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+        },
+        {
+            { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+            { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
+        },
+    },
+};
+
+// fixme: copied from h264data.h
+static const uint8_t zigzag_scan[16]={
+    0+0*4, 1+0*4, 0+1*4, 0+2*4,
+    1+1*4, 2+0*4, 3+0*4, 2+1*4,
+    1+2*4, 0+3*4, 1+3*4, 2+2*4,
+    3+1*4, 3+2*4, 2+3*4, 3+3*4,
+};
+
+static const uint8_t vp8_dc_qlookup[VP8_MAX_QUANT+1] =
+{
+      4,   5,   6,   7,   8,   9,  10,  10,  11,  12,  13,  14,  15,  16,  17,  17,
+     18,  19,  20,  20,  21,  21,  22,  22,  23,  23,  24,  25,  25,  26,  27,  28,
+     29,  30,  31,  32,  33,  34,  35,  36,  37,  37,  38,  39,  40,  41,  42,  43,
+     44,  45,  46,  46,  47,  48,  49,  50,  51,  52,  53,  54,  55,  56,  57,  58,
+     59,  60,  61,  62,  63,  64,  65,  66,  67,  68,  69,  70,  71,  72,  73,  74,
+     75,  76,  76,  77,  78,  79,  80,  81,  82,  83,  84,  85,  86,  87,  88,  89,
+     91,  93,  95,  96,  98, 100, 101, 102, 104, 106, 108, 110, 112, 114, 116, 118,
+    122, 124, 126, 128, 130, 132, 134, 136, 138, 140, 143, 145, 148, 151, 154, 157,
+};
+
+static const uint16_t vp8_ac_qlookup[VP8_MAX_QUANT+1] =
+{
+      4,   5,   6,   7,   8,   9,  10,  11,  12,  13,  14,  15,  16,  17,  18,  19,
+     20,  21,  22,  23,  24,  25,  26,  27,  28,  29,  30,  31,  32,  33,  34,  35,
+     36,  37,  38,  39,  40,  41,  42,  43,  44,  45,  46,  47,  48,  49,  50,  51,
+     52,  53,  54,  55,  56,  57,  58,  60,  62,  64,  66,  68,  70,  72,  74,  76,
+     78,  80,  82,  84,  86,  88,  90,  92,  94,  96,  98, 100, 102, 104, 106, 108,
+    110, 112, 114, 116, 119, 122, 125, 128, 131, 134, 137, 140, 143, 146, 149, 152,
+    155, 158, 161, 164, 167, 170, 173, 177, 181, 185, 189, 193, 197, 201, 205, 209,
+    213, 217, 221, 225, 229, 234, 239, 245, 249, 254, 259, 264, 269, 274, 279, 284,
+};
+
+static const uint8_t vp8_mv_update_prob[2][19] = {
+    { 237,
+      246,
+      253, 253, 254, 254, 254, 254, 254,
+      254, 254, 254, 254, 254, 250, 250, 252, 254, 254 },
+    { 231,
+      243,
+      245, 253, 254, 254, 254, 254, 254,
+      254, 254, 254, 254, 254, 251, 251, 254, 254, 254 }
+};
+
+static const uint8_t vp8_mv_default_prob[2][19] = {
+    { 162,
+      128,
+      225, 146, 172, 147, 214, 39, 156,
+      128, 129, 132,  75, 145, 178, 206, 239, 254, 254 },
+    { 164,
+      128,
+      204, 170, 119, 235, 140, 230, 228,
+      128, 130, 130,  74, 148, 180, 203, 236, 254, 254 }
+};
+
+#endif
diff --git a/libavcodec/vp8dsp.c b/libavcodec/vp8dsp.c
new file mode 100644
index 0000000..159c070
--- /dev/null
+++ b/libavcodec/vp8dsp.c
@@ -0,0 +1,528 @@
+/**
+ * VP8 compatible video decoder
+ *
+ * Copyright (C) 2010 David Conrad
+ * Copyright (C) 2010 Ronald S. Bultje
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "dsputil.h"
+#include "vp8dsp.h"
+
+// TODO: Maybe add dequant
+static void vp8_luma_dc_wht_c(DCTELEM block[4][4][16], DCTELEM dc[16])
+{
+    int i, t0, t1, t2, t3;
+
+    for (i = 0; i < 4; i++) {
+        t0 = dc[0*4+i] + dc[3*4+i];
+        t1 = dc[1*4+i] + dc[2*4+i];
+        t2 = dc[1*4+i] - dc[2*4+i];
+        t3 = dc[0*4+i] - dc[3*4+i];
+
+        dc[0*4+i] = t0 + t1;
+        dc[1*4+i] = t3 + t2;
+        dc[2*4+i] = t0 - t1;
+        dc[3*4+i] = t3 - t2;
+    }
+
+    for (i = 0; i < 4; i++) {
+        t0 = dc[i*4+0] + dc[i*4+3] + 3; // rounding
+        t1 = dc[i*4+1] + dc[i*4+2];
+        t2 = dc[i*4+1] - dc[i*4+2];
+        t3 = dc[i*4+0] - dc[i*4+3] + 3; // rounding
+        dc[i*4+0] = 0;
+        dc[i*4+1] = 0;
+        dc[i*4+2] = 0;
+        dc[i*4+3] = 0;
+
+        block[i][0][0] = (t0 + t1) >> 3;
+        block[i][1][0] = (t3 + t2) >> 3;
+        block[i][2][0] = (t0 - t1) >> 3;
+        block[i][3][0] = (t3 - t2) >> 3;
+    }
+}
+
+static void vp8_luma_dc_wht_dc_c(DCTELEM block[4][4][16], DCTELEM dc[16])
+{
+    int i, val = (dc[0] + 3) >> 3;
+    dc[0] = 0;
+
+    for (i = 0; i < 4; i++) {
+        block[i][0][0] = val;
+        block[i][1][0] = val;
+        block[i][2][0] = val;
+        block[i][3][0] = val;
+    }
+}
+
+#define MUL_20091(a) ((((a)*20091) >> 16) + (a))
+#define MUL_35468(a)  (((a)*35468) >> 16)
+
+static void vp8_idct_add_c(uint8_t *dst, DCTELEM block[16], int stride)
+{
+    int i, t0, t1, t2, t3;
+    uint8_t *cm = ff_cropTbl + MAX_NEG_CROP;
+    DCTELEM tmp[16];
+
+    for (i = 0; i < 4; i++) {
+        t0 = block[0*4+i] + block[2*4+i];
+        t1 = block[0*4+i] - block[2*4+i];
+        t2 = MUL_35468(block[1*4+i]) - MUL_20091(block[3*4+i]);
+        t3 = MUL_20091(block[1*4+i]) + MUL_35468(block[3*4+i]);
+        block[0*4+i] = 0;
+        block[1*4+i] = 0;
+        block[2*4+i] = 0;
+        block[3*4+i] = 0;
+
+        tmp[i*4+0] = t0 + t3;
+        tmp[i*4+1] = t1 + t2;
+        tmp[i*4+2] = t1 - t2;
+        tmp[i*4+3] = t0 - t3;
+    }
+
+    for (i = 0; i < 4; i++) {
+        t0 = tmp[0*4+i] + tmp[2*4+i];
+        t1 = tmp[0*4+i] - tmp[2*4+i];
+        t2 = MUL_35468(tmp[1*4+i]) - MUL_20091(tmp[3*4+i]);
+        t3 = MUL_20091(tmp[1*4+i]) + MUL_35468(tmp[3*4+i]);
+
+        dst[0] = cm[dst[0] + ((t0 + t3 + 4) >> 3)];
+        dst[1] = cm[dst[1] + ((t1 + t2 + 4) >> 3)];
+        dst[2] = cm[dst[2] + ((t1 - t2 + 4) >> 3)];
+        dst[3] = cm[dst[3] + ((t0 - t3 + 4) >> 3)];
+        dst += stride;
+    }
+}
+
+static void vp8_idct_dc_add_c(uint8_t *dst, DCTELEM block[16], int stride)
+{
+    int i, dc = (block[0] + 4) >> 3;
+    uint8_t *cm = ff_cropTbl + MAX_NEG_CROP + dc;
+    block[0] = 0;
+
+    for (i = 0; i < 4; i++) {
+        dst[0] = cm[dst[0]];
+        dst[1] = cm[dst[1]];
+        dst[2] = cm[dst[2]];
+        dst[3] = cm[dst[3]];
+        dst += stride;
+    }
+}
+
+static void vp8_idct_dc_add4uv_c(uint8_t *dst, DCTELEM block[4][16], int stride)
+{
+    vp8_idct_dc_add_c(dst+stride*0+0, block[0], stride);
+    vp8_idct_dc_add_c(dst+stride*0+4, block[1], stride);
+    vp8_idct_dc_add_c(dst+stride*4+0, block[2], stride);
+    vp8_idct_dc_add_c(dst+stride*4+4, block[3], stride);
+}
+
+static void vp8_idct_dc_add4y_c(uint8_t *dst, DCTELEM block[4][16], int stride)
+{
+    vp8_idct_dc_add_c(dst+ 0, block[0], stride);
+    vp8_idct_dc_add_c(dst+ 4, block[1], stride);
+    vp8_idct_dc_add_c(dst+ 8, block[2], stride);
+    vp8_idct_dc_add_c(dst+12, block[3], stride);
+}
+
+// because I like only having two parameters to pass functions...
+#define LOAD_PIXELS\
+    int av_unused p3 = p[-4*stride];\
+    int av_unused p2 = p[-3*stride];\
+    int av_unused p1 = p[-2*stride];\
+    int av_unused p0 = p[-1*stride];\
+    int av_unused q0 = p[ 0*stride];\
+    int av_unused q1 = p[ 1*stride];\
+    int av_unused q2 = p[ 2*stride];\
+    int av_unused q3 = p[ 3*stride];
+
+#define clip_int8(n) (cm[n+0x80]-0x80)
+
+static av_always_inline void filter_common(uint8_t *p, int stride, int is4tap)
+{
+    LOAD_PIXELS
+    int a, f1, f2;
+    uint8_t *cm = ff_cropTbl + MAX_NEG_CROP;
+
+    a = 3*(q0 - p0);
+
+    if (is4tap)
+        a += clip_int8(p1 - q1);
+
+    a = clip_int8(a);
+
+    // We deviate from the spec here with c(a+3) >> 3
+    // since that's what libvpx does.
+    f1 = FFMIN(a+4, 127) >> 3;
+    f2 = FFMIN(a+3, 127) >> 3;
+
+    // Despite what the spec says, we do need to clamp here to
+    // be bitexact with libvpx.
+    p[-1*stride] = cm[p0 + f2];
+    p[ 0*stride] = cm[q0 - f1];
+
+    // only used for _inner on blocks without high edge variance
+    if (!is4tap) {
+        a = (f1+1)>>1;
+        p[-2*stride] = cm[p1 + a];
+        p[ 1*stride] = cm[q1 - a];
+    }
+}
+
+static av_always_inline int simple_limit(uint8_t *p, int stride, int flim)
+{
+    LOAD_PIXELS
+    return 2*FFABS(p0-q0) + (FFABS(p1-q1) >> 1) <= flim;
+}
+
+/**
+ * E - limit at the macroblock edge
+ * I - limit for interior difference
+ */
+static av_always_inline int normal_limit(uint8_t *p, int stride, int E, int I)
+{
+    LOAD_PIXELS
+    return simple_limit(p, stride, E)
+        && FFABS(p3-p2) <= I && FFABS(p2-p1) <= I && FFABS(p1-p0) <= I
+        && FFABS(q3-q2) <= I && FFABS(q2-q1) <= I && FFABS(q1-q0) <= I;
+}
+
+// high edge variance
+static av_always_inline int hev(uint8_t *p, int stride, int thresh)
+{
+    LOAD_PIXELS
+    return FFABS(p1-p0) > thresh || FFABS(q1-q0) > thresh;
+}
+
+static av_always_inline void filter_mbedge(uint8_t *p, int stride)
+{
+    int a0, a1, a2, w;
+    uint8_t *cm = ff_cropTbl + MAX_NEG_CROP;
+
+    LOAD_PIXELS
+
+    w = clip_int8(p1-q1);
+    w = clip_int8(w + 3*(q0-p0));
+
+    a0 = (27*w + 63) >> 7;
+    a1 = (18*w + 63) >> 7;
+    a2 = ( 9*w + 63) >> 7;
+
+    p[-3*stride] = cm[p2 + a2];
+    p[-2*stride] = cm[p1 + a1];
+    p[-1*stride] = cm[p0 + a0];
+    p[ 0*stride] = cm[q0 - a0];
+    p[ 1*stride] = cm[q1 - a1];
+    p[ 2*stride] = cm[q2 - a2];
+}
+
+#define LOOP_FILTER(dir, size, stridea, strideb, maybe_inline) \
+static maybe_inline void vp8_ ## dir ## _loop_filter ## size ## _c(uint8_t *dst, int stride,\
+                                     int flim_E, int flim_I, int hev_thresh)\
+{\
+    int i;\
+\
+    for (i = 0; i < size; i++)\
+        if (normal_limit(dst+i*stridea, strideb, flim_E, flim_I)) {\
+            if (hev(dst+i*stridea, strideb, hev_thresh))\
+                filter_common(dst+i*stridea, strideb, 1);\
+            else\
+                filter_mbedge(dst+i*stridea, strideb);\
+        }\
+}\
+\
+static maybe_inline void vp8_ ## dir ## _loop_filter ## size ## _inner_c(uint8_t *dst, int stride,\
+                                      int flim_E, int flim_I, int hev_thresh)\
+{\
+    int i;\
+\
+    for (i = 0; i < size; i++)\
+        if (normal_limit(dst+i*stridea, strideb, flim_E, flim_I)) {\
+            int hv = hev(dst+i*stridea, strideb, hev_thresh);\
+            if (hv) \
+                filter_common(dst+i*stridea, strideb, 1);\
+            else \
+                filter_common(dst+i*stridea, strideb, 0);\
+        }\
+}
+
+LOOP_FILTER(v, 16, 1, stride,)
+LOOP_FILTER(h, 16, stride, 1,)
+
+#define UV_LOOP_FILTER(dir, stridea, strideb) \
+LOOP_FILTER(dir, 8, stridea, strideb, av_always_inline) \
+static void vp8_ ## dir ## _loop_filter8uv_c(uint8_t *dstU, uint8_t *dstV, int stride,\
+                                      int fE, int fI, int hev_thresh)\
+{\
+  vp8_ ## dir ## _loop_filter8_c(dstU, stride, fE, fI, hev_thresh);\
+  vp8_ ## dir ## _loop_filter8_c(dstV, stride, fE, fI, hev_thresh);\
+}\
+static void vp8_ ## dir ## _loop_filter8uv_inner_c(uint8_t *dstU, uint8_t *dstV, int stride,\
+                                      int fE, int fI, int hev_thresh)\
+{\
+  vp8_ ## dir ## _loop_filter8_inner_c(dstU, stride, fE, fI, hev_thresh);\
+  vp8_ ## dir ## _loop_filter8_inner_c(dstV, stride, fE, fI, hev_thresh);\
+}
+
+UV_LOOP_FILTER(v, 1, stride)
+UV_LOOP_FILTER(h, stride, 1)
+
+static void vp8_v_loop_filter_simple_c(uint8_t *dst, int stride, int flim)
+{
+    int i;
+
+    for (i = 0; i < 16; i++)
+        if (simple_limit(dst+i, stride, flim))
+            filter_common(dst+i, stride, 1);
+}
+
+static void vp8_h_loop_filter_simple_c(uint8_t *dst, int stride, int flim)
+{
+    int i;
+
+    for (i = 0; i < 16; i++)
+        if (simple_limit(dst+i*stride, 1, flim))
+            filter_common(dst+i*stride, 1, 1);
+}
+
+static const uint8_t subpel_filters[7][6] = {
+    { 0,   6, 123,  12,   1,   0 },
+    { 2,  11, 108,  36,   8,   1 },
+    { 0,   9,  93,  50,   6,   0 },
+    { 3,  16,  77,  77,  16,   3 },
+    { 0,   6,  50,  93,   9,   0 },
+    { 1,   8,  36, 108,  11,   2 },
+    { 0,   1,  12, 123,   6,   0 },
+};
+
+#define PUT_PIXELS(WIDTH) \
+static void put_vp8_pixels ## WIDTH ##_c(uint8_t *dst, int dststride, uint8_t *src, int srcstride, int h, int x, int y) { \
+    int i; \
+    for (i = 0; i < h; i++, dst+= dststride, src+= srcstride) { \
+        memcpy(dst, src, WIDTH); \
+    } \
+}
+
+PUT_PIXELS(16)
+PUT_PIXELS(8)
+PUT_PIXELS(4)
+
+#define FILTER_6TAP(src, F, stride) \
+    cm[(F[2]*src[x+0*stride] - F[1]*src[x-1*stride] + F[0]*src[x-2*stride] + \
+        F[3]*src[x+1*stride] - F[4]*src[x+2*stride] + F[5]*src[x+3*stride] + 64) >> 7]
+
+#define FILTER_4TAP(src, F, stride) \
+    cm[(F[2]*src[x+0*stride] - F[1]*src[x-1*stride] + \
+        F[3]*src[x+1*stride] - F[4]*src[x+2*stride] + 64) >> 7]
+
+#define VP8_EPEL_H(SIZE, TAPS) \
+static void put_vp8_epel ## SIZE ## _h ## TAPS ## _c(uint8_t *dst, int dststride, uint8_t *src, int srcstride, int h, int mx, int my) \
+{ \
+    const uint8_t *filter = subpel_filters[mx-1]; \
+    uint8_t *cm = ff_cropTbl + MAX_NEG_CROP; \
+    int x, y; \
+\
+    for (y = 0; y < h; y++) { \
+        for (x = 0; x < SIZE; x++) \
+            dst[x] = FILTER_ ## TAPS ## TAP(src, filter, 1); \
+        dst += dststride; \
+        src += srcstride; \
+    } \
+}
+#define VP8_EPEL_V(SIZE, TAPS) \
+static void put_vp8_epel ## SIZE ## _v ## TAPS ## _c(uint8_t *dst, int dststride, uint8_t *src, int srcstride, int h, int mx, int my) \
+{ \
+    const uint8_t *filter = subpel_filters[my-1]; \
+    uint8_t *cm = ff_cropTbl + MAX_NEG_CROP; \
+    int x, y; \
+\
+    for (y = 0; y < h; y++) { \
+        for (x = 0; x < SIZE; x++) \
+            dst[x] = FILTER_ ## TAPS ## TAP(src, filter, srcstride); \
+        dst += dststride; \
+        src += srcstride; \
+    } \
+}
+#define VP8_EPEL_HV(SIZE, HTAPS, VTAPS) \
+static void put_vp8_epel ## SIZE ## _h ## HTAPS ## v ## VTAPS ## _c(uint8_t *dst, int dststride, uint8_t *src, int srcstride, int h, int mx, int my) \
+{ \
+    const uint8_t *filter = subpel_filters[mx-1]; \
+    uint8_t *cm = ff_cropTbl + MAX_NEG_CROP; \
+    int x, y; \
+    uint8_t tmp_array[(2*SIZE+VTAPS-1)*SIZE]; \
+    uint8_t *tmp = tmp_array; \
+    src -= (2-(VTAPS==4))*srcstride; \
+\
+    for (y = 0; y < h+VTAPS-1; y++) { \
+        for (x = 0; x < SIZE; x++) \
+            tmp[x] = FILTER_ ## HTAPS ## TAP(src, filter, 1); \
+        tmp += SIZE; \
+        src += srcstride; \
+    } \
+\
+    tmp = tmp_array + (2-(VTAPS==4))*SIZE; \
+    filter = subpel_filters[my-1]; \
+\
+    for (y = 0; y < h; y++) { \
+        for (x = 0; x < SIZE; x++) \
+            dst[x] = FILTER_ ## VTAPS ## TAP(tmp, filter, SIZE); \
+        dst += dststride; \
+        tmp += SIZE; \
+    } \
+}
+
+VP8_EPEL_H(16, 4)
+VP8_EPEL_H(8,  4)
+VP8_EPEL_H(4,  4)
+VP8_EPEL_H(16, 6)
+VP8_EPEL_H(8,  6)
+VP8_EPEL_H(4,  6)
+VP8_EPEL_V(16, 4)
+VP8_EPEL_V(8,  4)
+VP8_EPEL_V(4,  4)
+VP8_EPEL_V(16, 6)
+VP8_EPEL_V(8,  6)
+VP8_EPEL_V(4,  6)
+VP8_EPEL_HV(16, 4, 4)
+VP8_EPEL_HV(8,  4, 4)
+VP8_EPEL_HV(4,  4, 4)
+VP8_EPEL_HV(16, 4, 6)
+VP8_EPEL_HV(8,  4, 6)
+VP8_EPEL_HV(4,  4, 6)
+VP8_EPEL_HV(16, 6, 4)
+VP8_EPEL_HV(8,  6, 4)
+VP8_EPEL_HV(4,  6, 4)
+VP8_EPEL_HV(16, 6, 6)
+VP8_EPEL_HV(8,  6, 6)
+VP8_EPEL_HV(4,  6, 6)
+
+#define VP8_BILINEAR(SIZE) \
+static void put_vp8_bilinear ## SIZE ## _h_c(uint8_t *dst, int stride, uint8_t *src, int s2, int h, int mx, int my) \
+{ \
+    int a = 8-mx, b = mx; \
+    int x, y; \
+\
+    for (y = 0; y < h; y++) { \
+        for (x = 0; x < SIZE; x++) \
+            dst[x] = (a*src[x] + b*src[x+1] + 4) >> 3; \
+        dst += stride; \
+        src += stride; \
+    } \
+} \
+static void put_vp8_bilinear ## SIZE ## _v_c(uint8_t *dst, int stride, uint8_t *src, int s2, int h, int mx, int my) \
+{ \
+    int c = 8-my, d = my; \
+    int x, y; \
+\
+    for (y = 0; y < h; y++) { \
+        for (x = 0; x < SIZE; x++) \
+            dst[x] = (c*src[x] + d*src[x+stride] + 4) >> 3; \
+        dst += stride; \
+        src += stride; \
+    } \
+} \
+\
+static void put_vp8_bilinear ## SIZE ## _hv_c(uint8_t *dst, int stride, uint8_t *src, int s2, int h, int mx, int my) \
+{ \
+    int a = 8-mx, b = mx; \
+    int c = 8-my, d = my; \
+    int x, y; \
+    uint8_t tmp_array[(2*SIZE+1)*SIZE]; \
+    uint8_t *tmp = tmp_array; \
+\
+    for (y = 0; y < h+1; y++) { \
+        for (x = 0; x < SIZE; x++) \
+            tmp[x] = (a*src[x] + b*src[x+1] + 4) >> 3; \
+        tmp += SIZE; \
+        src += stride; \
+    } \
+\
+    tmp = tmp_array; \
+\
+    for (y = 0; y < h; y++) { \
+        for (x = 0; x < SIZE; x++) \
+            dst[x] = (c*tmp[x] + d*tmp[x+SIZE] + 4) >> 3; \
+        dst += stride; \
+        tmp += SIZE; \
+    } \
+}
+
+VP8_BILINEAR(16)
+VP8_BILINEAR(8)
+VP8_BILINEAR(4)
+
+#define VP8_MC_FUNC(IDX, SIZE) \
+    dsp->put_vp8_epel_pixels_tab[IDX][0][0] = put_vp8_pixels ## SIZE ## _c; \
+    dsp->put_vp8_epel_pixels_tab[IDX][0][1] = put_vp8_epel ## SIZE ## _h4_c; \
+    dsp->put_vp8_epel_pixels_tab[IDX][0][2] = put_vp8_epel ## SIZE ## _h6_c; \
+    dsp->put_vp8_epel_pixels_tab[IDX][1][0] = put_vp8_epel ## SIZE ## _v4_c; \
+    dsp->put_vp8_epel_pixels_tab[IDX][1][1] = put_vp8_epel ## SIZE ## _h4v4_c; \
+    dsp->put_vp8_epel_pixels_tab[IDX][1][2] = put_vp8_epel ## SIZE ## _h6v4_c; \
+    dsp->put_vp8_epel_pixels_tab[IDX][2][0] = put_vp8_epel ## SIZE ## _v6_c; \
+    dsp->put_vp8_epel_pixels_tab[IDX][2][1] = put_vp8_epel ## SIZE ## _h4v6_c; \
+    dsp->put_vp8_epel_pixels_tab[IDX][2][2] = put_vp8_epel ## SIZE ## _h6v6_c
+
+#define VP8_BILINEAR_MC_FUNC(IDX, SIZE) \
+    dsp->put_vp8_bilinear_pixels_tab[IDX][0][0] = put_vp8_pixels ## SIZE ## _c; \
+    dsp->put_vp8_bilinear_pixels_tab[IDX][0][1] = put_vp8_bilinear ## SIZE ## _h_c; \
+    dsp->put_vp8_bilinear_pixels_tab[IDX][0][2] = put_vp8_bilinear ## SIZE ## _h_c; \
+    dsp->put_vp8_bilinear_pixels_tab[IDX][1][0] = put_vp8_bilinear ## SIZE ## _v_c; \
+    dsp->put_vp8_bilinear_pixels_tab[IDX][1][1] = put_vp8_bilinear ## SIZE ## _hv_c; \
+    dsp->put_vp8_bilinear_pixels_tab[IDX][1][2] = put_vp8_bilinear ## SIZE ## _hv_c; \
+    dsp->put_vp8_bilinear_pixels_tab[IDX][2][0] = put_vp8_bilinear ## SIZE ## _v_c; \
+    dsp->put_vp8_bilinear_pixels_tab[IDX][2][1] = put_vp8_bilinear ## SIZE ## _hv_c; \
+    dsp->put_vp8_bilinear_pixels_tab[IDX][2][2] = put_vp8_bilinear ## SIZE ## _hv_c
+
+av_cold void ff_vp8dsp_init(VP8DSPContext *dsp)
+{
+    dsp->vp8_luma_dc_wht    = vp8_luma_dc_wht_c;
+    dsp->vp8_luma_dc_wht_dc = vp8_luma_dc_wht_dc_c;
+    dsp->vp8_idct_add       = vp8_idct_add_c;
+    dsp->vp8_idct_dc_add    = vp8_idct_dc_add_c;
+    dsp->vp8_idct_dc_add4y  = vp8_idct_dc_add4y_c;
+    dsp->vp8_idct_dc_add4uv = vp8_idct_dc_add4uv_c;
+
+    dsp->vp8_v_loop_filter16y = vp8_v_loop_filter16_c;
+    dsp->vp8_h_loop_filter16y = vp8_h_loop_filter16_c;
+    dsp->vp8_v_loop_filter8uv = vp8_v_loop_filter8uv_c;
+    dsp->vp8_h_loop_filter8uv = vp8_h_loop_filter8uv_c;
+
+    dsp->vp8_v_loop_filter16y_inner = vp8_v_loop_filter16_inner_c;
+    dsp->vp8_h_loop_filter16y_inner = vp8_h_loop_filter16_inner_c;
+    dsp->vp8_v_loop_filter8uv_inner = vp8_v_loop_filter8uv_inner_c;
+    dsp->vp8_h_loop_filter8uv_inner = vp8_h_loop_filter8uv_inner_c;
+
+    dsp->vp8_v_loop_filter_simple = vp8_v_loop_filter_simple_c;
+    dsp->vp8_h_loop_filter_simple = vp8_h_loop_filter_simple_c;
+
+    VP8_MC_FUNC(0, 16);
+    VP8_MC_FUNC(1, 8);
+    VP8_MC_FUNC(2, 4);
+
+    VP8_BILINEAR_MC_FUNC(0, 16);
+    VP8_BILINEAR_MC_FUNC(1, 8);
+    VP8_BILINEAR_MC_FUNC(2, 4);
+
+    if (HAVE_MMX)
+        ff_vp8dsp_init_x86(dsp);
+    if (HAVE_ALTIVEC)
+        ff_vp8dsp_init_altivec(dsp);
+    if (ARCH_ARM)
+        ff_vp8dsp_init_arm(dsp);
+}
diff --git a/libavcodec/vp8dsp.h b/libavcodec/vp8dsp.h
new file mode 100644
index 0000000..e2fb8e7
--- /dev/null
+++ b/libavcodec/vp8dsp.h
@@ -0,0 +1,84 @@
+/**
+ * VP8 compatible video decoder
+ *
+ * Copyright (C) 2010 David Conrad
+ * Copyright (C) 2010 Ronald S. Bultje
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+
+#ifndef AVCODEC_VP8DSP_H
+#define AVCODEC_VP8DSP_H
+
+#include "dsputil.h"
+
+typedef void (*vp8_mc_func)(uint8_t *dst/*align 8*/, int dstStride, uint8_t *src/*align 1*/, int srcStride, int h, int x, int y);
+
+typedef struct VP8DSPContext {
+    void (*vp8_luma_dc_wht)(DCTELEM block[4][4][16], DCTELEM dc[16]);
+    void (*vp8_luma_dc_wht_dc)(DCTELEM block[4][4][16], DCTELEM dc[16]);
+    void (*vp8_idct_add)(uint8_t *dst, DCTELEM block[16], int stride);
+    void (*vp8_idct_dc_add)(uint8_t *dst, DCTELEM block[16], int stride);
+    void (*vp8_idct_dc_add4y)(uint8_t *dst, DCTELEM block[4][16], int stride);
+    void (*vp8_idct_dc_add4uv)(uint8_t *dst, DCTELEM block[4][16], int stride);
+
+    // loop filter applied to edges between macroblocks
+    void (*vp8_v_loop_filter16y)(uint8_t *dst, int stride,
+                                 int flim_E, int flim_I, int hev_thresh);
+    void (*vp8_h_loop_filter16y)(uint8_t *dst, int stride,
+                                 int flim_E, int flim_I, int hev_thresh);
+    void (*vp8_v_loop_filter8uv)(uint8_t *dstU, uint8_t *dstV, int stride,
+                                 int flim_E, int flim_I, int hev_thresh);
+    void (*vp8_h_loop_filter8uv)(uint8_t *dstU, uint8_t *dstV, int stride,
+                                 int flim_E, int flim_I, int hev_thresh);
+
+    // loop filter applied to inner macroblock edges
+    void (*vp8_v_loop_filter16y_inner)(uint8_t *dst, int stride,
+                                       int flim_E, int flim_I, int hev_thresh);
+    void (*vp8_h_loop_filter16y_inner)(uint8_t *dst, int stride,
+                                       int flim_E, int flim_I, int hev_thresh);
+    void (*vp8_v_loop_filter8uv_inner)(uint8_t *dstU, uint8_t *dstV, int stride,
+                                       int flim_E, int flim_I, int hev_thresh);
+    void (*vp8_h_loop_filter8uv_inner)(uint8_t *dstU, uint8_t *dstV, int stride,
+                                       int flim_E, int flim_I, int hev_thresh);
+
+    void (*vp8_v_loop_filter_simple)(uint8_t *dst, int stride, int flim);
+    void (*vp8_h_loop_filter_simple)(uint8_t *dst, int stride, int flim);
+
+    /**
+     * first dimension: width>>3, height is assumed equal to width
+     * second dimension: 0 if no vertical interpolation is needed;
+     *                   1 4-tap vertical interpolation filter (my & 1)
+     *                   2 6-tap vertical interpolation filter (!(my & 1))
+     * third dimension: same as second dimention, for horizontal interpolation
+     * so something like put_vp8_epel_pixels_tab[width>>3][2*!!my-(my&1)][2*!!mx-(mx&1)](..., mx, my)
+     */
+    vp8_mc_func put_vp8_epel_pixels_tab[3][3][3];
+    vp8_mc_func put_vp8_bilinear_pixels_tab[3][3][3];
+} VP8DSPContext;
+
+void ff_put_vp8_pixels16_c(uint8_t *dst, uint8_t *src, int stride, int h, int x, int y);
+void ff_put_vp8_pixels8_c(uint8_t *dst, uint8_t *src, int stride, int h, int x, int y);
+void ff_put_vp8_pixels4_c(uint8_t *dst, uint8_t *src, int stride, int h, int x, int y);
+
+void ff_vp8dsp_init(VP8DSPContext *c);
+void ff_vp8dsp_init_x86(VP8DSPContext *c);
+void ff_vp8dsp_init_altivec(VP8DSPContext *c);
+void ff_vp8dsp_init_arm(VP8DSPContext *c);
+
+#endif /* AVCODEC_VP8DSP_H */
diff --git a/libavcodec/vqavideo.c b/libavcodec/vqavideo.c
index a169839..40004a0 100644
--- a/libavcodec/vqavideo.c
+++ b/libavcodec/vqavideo.c
@@ -2,20 +2,20 @@
  * Westwood Studios VQA Video Decoder
  * Copyright (C) 2003 the ffmpeg project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -68,6 +68,7 @@
 #include <string.h>
 
 #include "libavutil/intreadwrite.h"
+#include "libavutil/imgutils.h"
 #include "avcodec.h"
 
 #define PALETTE_COUNT 256
@@ -147,7 +148,7 @@ static av_cold int vqa_decode_init(AVCodecContext *avctx)
     s->vqa_version = vqa_header[0];
     s->width = AV_RL16(&vqa_header[6]);
     s->height = AV_RL16(&vqa_header[8]);
-    if(avcodec_check_dimensions(avctx, s->width, s->height)){
+    if(av_image_check_size(s->width, s->height, 0, avctx)){
         s->width= s->height= 0;
         return -1;
     }
@@ -608,7 +609,7 @@ static av_cold int vqa_decode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec vqa_decoder = {
+AVCodec ff_vqa_decoder = {
     "vqavideo",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_WS_VQA,
diff --git a/libavcodec/w32thread.c b/libavcodec/w32thread.c
index f7a1430..023be0e 100644
--- a/libavcodec/w32thread.c
+++ b/libavcodec/w32thread.c
@@ -1,25 +1,26 @@
 /*
  * Copyright (c) 2004 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 //#define DEBUG
 
 #include "avcodec.h"
+#include "thread.h"
 
 #define WIN32_LEAN_AND_MEAN
 #include <windows.h>
@@ -69,10 +70,10 @@ static unsigned WINAPI attribute_align_arg thread_func(void *v){
 }
 
 /**
- * Free what has been allocated by avcodec_thread_init().
+ * Free what has been allocated by ff_thread_init().
  * Must be called after decoding has finished, especially do not call while avcodec_thread_execute() is running.
  */
-void avcodec_thread_free(AVCodecContext *s){
+void ff_thread_free(AVCodecContext *s){
     ThreadContext *c= s->thread_opaque;
     int i;
 
@@ -124,18 +125,23 @@ static int avcodec_thread_execute2(AVCodecContext *s, int (*func)(AVCodecContext
     avcodec_thread_execute(s, NULL, arg, ret, count, 0);
 }
 
-int avcodec_thread_init(AVCodecContext *s, int thread_count){
+int ff_thread_init(AVCodecContext *s){
     int i;
     ThreadContext *c;
     uint32_t threadid;
 
-    s->thread_count= thread_count;
+    if(!(s->thread_type & FF_THREAD_SLICE)){
+        av_log(s, AV_LOG_WARNING, "The requested thread algorithm is not supported with this thread library.\n");
+        return 0;
+    }
 
-    if (thread_count <= 1)
+    s->active_thread_type= FF_THREAD_SLICE;
+
+    if (s->thread_count <= 1)
         return 0;
 
     assert(!s->thread_opaque);
-    c= av_mallocz(sizeof(ThreadContext)*thread_count);
+    c= av_mallocz(sizeof(ThreadContext)*s->thread_count);
     s->thread_opaque= c;
     if(!(c[0].work_sem = CreateSemaphore(NULL, 0, INT_MAX, NULL)))
         goto fail;
@@ -144,7 +150,7 @@ int avcodec_thread_init(AVCodecContext *s, int thread_count){
     if(!(c[0].done_sem = CreateSemaphore(NULL, 0, INT_MAX, NULL)))
         goto fail;
 
-    for(i=0; i<thread_count; i++){
+    for(i=0; i<s->thread_count; i++){
 //printf("init semaphors %d\n", i); fflush(stdout);
         c[i].avctx= s;
         c[i].work_sem = c[0].work_sem;
@@ -163,6 +169,6 @@ int avcodec_thread_init(AVCodecContext *s, int thread_count){
 
     return 0;
 fail:
-    avcodec_thread_free(s);
+    ff_thread_free(s);
     return -1;
 }
diff --git a/libavcodec/wavpack.c b/libavcodec/wavpack.c
index 7358d29..e4fe217 100644
--- a/libavcodec/wavpack.c
+++ b/libavcodec/wavpack.c
@@ -1,27 +1,28 @@
 /*
  * WavPack lossless audio decoder
- * Copyright (c) 2006 Konstantin Shishkov
+ * Copyright (c) 2006,2011 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #define ALT_BITSTREAM_READER_LE
 #include "avcodec.h"
 #include "get_bits.h"
 #include "unary.h"
+#include "libavutil/audioconvert.h"
 
 /**
  * @file
@@ -91,7 +92,7 @@ typedef struct WvChannel {
     int bitrate_acc, bitrate_delta;
 } WvChannel;
 
-typedef struct WavpackContext {
+typedef struct WavpackFrameContext {
     AVCodecContext *avctx;
     int frame_flags;
     int stereo, stereo_in;
@@ -118,6 +119,22 @@ typedef struct WavpackContext {
     int max_samples;
     int pos;
     SavedContext sc, extra_sc;
+} WavpackFrameContext;
+
+#define WV_MAX_FRAME_DECODERS 14
+
+typedef struct WavpackContext {
+    AVCodecContext *avctx;
+
+    WavpackFrameContext *fdec[WV_MAX_FRAME_DECODERS];
+    int fdec_num;
+
+    int multichannel;
+    int mkv_mode;
+    int block;
+    int samples;
+    int samples_left;
+    int ch_offset;
 } WavpackContext;
 
 // exponent table copied from WavPack source
@@ -224,7 +241,7 @@ static av_always_inline int get_tail(GetBitContext *gb, int k)
     return res;
 }
 
-static void update_error_limit(WavpackContext *ctx)
+static void update_error_limit(WavpackFrameContext *ctx)
 {
     int i, br[2], sl[2];
 
@@ -258,7 +275,7 @@ static void update_error_limit(WavpackContext *ctx)
     }
 }
 
-static int wv_get_value(WavpackContext *ctx, GetBitContext *gb, int channel, int *last)
+static int wv_get_value(WavpackFrameContext *ctx, GetBitContext *gb, int channel, int *last)
 {
     int t, t2;
     int sign, base, add, ret;
@@ -361,7 +378,7 @@ static int wv_get_value(WavpackContext *ctx, GetBitContext *gb, int channel, int
     return sign ? ~ret : ret;
 }
 
-static inline int wv_get_value_integer(WavpackContext *s, uint32_t *crc, int S)
+static inline int wv_get_value_integer(WavpackFrameContext *s, uint32_t *crc, int S)
 {
     int bit;
 
@@ -377,7 +394,7 @@ static inline int wv_get_value_integer(WavpackContext *s, uint32_t *crc, int S)
     return (((S + bit) << s->shift) - bit) << s->post_shift;
 }
 
-static float wv_get_value_float(WavpackContext *s, uint32_t *crc, int S)
+static float wv_get_value_float(WavpackFrameContext *s, uint32_t *crc, int S)
 {
     union {
         float    f;
@@ -450,13 +467,13 @@ static float wv_get_value_float(WavpackContext *s, uint32_t *crc, int S)
     return value.f;
 }
 
-static void wv_reset_saved_context(WavpackContext *s)
+static void wv_reset_saved_context(WavpackFrameContext *s)
 {
     s->pos = 0;
     s->sc.crc = s->extra_sc.crc = 0xFFFFFFFF;
 }
 
-static inline int wv_unpack_stereo(WavpackContext *s, GetBitContext *gb, void *dst, const int type)
+static inline int wv_unpack_stereo(WavpackFrameContext *s, GetBitContext *gb, void *dst, const int type)
 {
     int i, j, count = 0;
     int last, t;
@@ -467,6 +484,7 @@ static inline int wv_unpack_stereo(WavpackContext *s, GetBitContext *gb, void *d
     int16_t *dst16 = dst;
     int32_t *dst32 = dst;
     float   *dstfl = dst;
+    const int channel_pad = s->avctx->channels - 2;
 
     if(s->samples_left == s->samples)
         s->one = s->zero = s->zeroes = 0;
@@ -494,7 +512,7 @@ static inline int wv_unpack_stereo(WavpackContext *s, GetBitContext *gb, void *d
                     B = s->decorr[i].samplesB[pos];
                     j = (pos + t) & 7;
                 }
-                if(type != SAMPLE_FMT_S16){
+                if(type != AV_SAMPLE_FMT_S16){
                     L2 = L + ((s->decorr[i].weightA * (int64_t)A + 512) >> 10);
                     R2 = R + ((s->decorr[i].weightB * (int64_t)B + 512) >> 10);
                 }else{
@@ -506,13 +524,13 @@ static inline int wv_unpack_stereo(WavpackContext *s, GetBitContext *gb, void *d
                 s->decorr[i].samplesA[j] = L = L2;
                 s->decorr[i].samplesB[j] = R = R2;
             }else if(t == -1){
-                if(type != SAMPLE_FMT_S16)
+                if(type != AV_SAMPLE_FMT_S16)
                     L2 = L + ((s->decorr[i].weightA * (int64_t)s->decorr[i].samplesA[0] + 512) >> 10);
                 else
                     L2 = L + ((s->decorr[i].weightA * s->decorr[i].samplesA[0] + 512) >> 10);
                 UPDATE_WEIGHT_CLIP(s->decorr[i].weightA, s->decorr[i].delta, s->decorr[i].samplesA[0], L);
                 L = L2;
-                if(type != SAMPLE_FMT_S16)
+                if(type != AV_SAMPLE_FMT_S16)
                     R2 = R + ((s->decorr[i].weightB * (int64_t)L2 + 512) >> 10);
                 else
                     R2 = R + ((s->decorr[i].weightB * L2 + 512) >> 10);
@@ -520,7 +538,7 @@ static inline int wv_unpack_stereo(WavpackContext *s, GetBitContext *gb, void *d
                 R = R2;
                 s->decorr[i].samplesA[0] = R;
             }else{
-                if(type != SAMPLE_FMT_S16)
+                if(type != AV_SAMPLE_FMT_S16)
                     R2 = R + ((s->decorr[i].weightB * (int64_t)s->decorr[i].samplesB[0] + 512) >> 10);
                 else
                     R2 = R + ((s->decorr[i].weightB * s->decorr[i].samplesB[0] + 512) >> 10);
@@ -532,7 +550,7 @@ static inline int wv_unpack_stereo(WavpackContext *s, GetBitContext *gb, void *d
                     s->decorr[i].samplesA[0] = R;
                 }
 
-                if(type != SAMPLE_FMT_S16)
+                if(type != AV_SAMPLE_FMT_S16)
                     L2 = L + ((s->decorr[i].weightA * (int64_t)R2 + 512) >> 10);
                 else
                     L2 = L + ((s->decorr[i].weightA * R2 + 512) >> 10);
@@ -546,15 +564,18 @@ static inline int wv_unpack_stereo(WavpackContext *s, GetBitContext *gb, void *d
             L += (R -= (L >> 1));
         crc = (crc * 3 + L) * 3 + R;
 
-        if(type == SAMPLE_FMT_FLT){
+        if(type == AV_SAMPLE_FMT_FLT){
             *dstfl++ = wv_get_value_float(s, &crc_extra_bits, L);
             *dstfl++ = wv_get_value_float(s, &crc_extra_bits, R);
-        } else if(type == SAMPLE_FMT_S32){
+            dstfl += channel_pad;
+        } else if(type == AV_SAMPLE_FMT_S32){
             *dst32++ = wv_get_value_integer(s, &crc_extra_bits, L);
             *dst32++ = wv_get_value_integer(s, &crc_extra_bits, R);
+            dst32 += channel_pad;
         } else {
             *dst16++ = wv_get_value_integer(s, &crc_extra_bits, L);
             *dst16++ = wv_get_value_integer(s, &crc_extra_bits, R);
+            dst16 += channel_pad;
         }
         count++;
     }while(!last && count < s->max_samples);
@@ -582,7 +603,7 @@ static inline int wv_unpack_stereo(WavpackContext *s, GetBitContext *gb, void *d
     return count * 2;
 }
 
-static inline int wv_unpack_mono(WavpackContext *s, GetBitContext *gb, void *dst, const int type)
+static inline int wv_unpack_mono(WavpackFrameContext *s, GetBitContext *gb, void *dst, const int type)
 {
     int i, j, count = 0;
     int last, t;
@@ -593,6 +614,7 @@ static inline int wv_unpack_mono(WavpackContext *s, GetBitContext *gb, void *dst
     int16_t *dst16 = dst;
     int32_t *dst32 = dst;
     float   *dstfl = dst;
+    const int channel_stride = s->avctx->channels;
 
     if(s->samples_left == s->samples)
         s->one = s->zero = s->zeroes = 0;
@@ -613,7 +635,7 @@ static inline int wv_unpack_mono(WavpackContext *s, GetBitContext *gb, void *dst
                 A = s->decorr[i].samplesA[pos];
                 j = (pos + t) & 7;
             }
-            if(type != SAMPLE_FMT_S16)
+            if(type != AV_SAMPLE_FMT_S16)
                 S = T + ((s->decorr[i].weightA * (int64_t)A + 512) >> 10);
             else
                 S = T + ((s->decorr[i].weightA * A + 512) >> 10);
@@ -623,14 +645,18 @@ static inline int wv_unpack_mono(WavpackContext *s, GetBitContext *gb, void *dst
         pos = (pos + 1) & 7;
         crc = crc * 3 + S;
 
-        if(type == SAMPLE_FMT_FLT)
-            *dstfl++ = wv_get_value_float(s, &crc_extra_bits, S);
-        else if(type == SAMPLE_FMT_S32)
-            *dst32++ = wv_get_value_integer(s, &crc_extra_bits, S);
-        else
-            *dst16++ = wv_get_value_integer(s, &crc_extra_bits, S);
+        if(type == AV_SAMPLE_FMT_FLT){
+            *dstfl = wv_get_value_float(s, &crc_extra_bits, S);
+            dstfl += channel_stride;
+        }else if(type == AV_SAMPLE_FMT_S32){
+            *dst32 = wv_get_value_integer(s, &crc_extra_bits, S);
+            dst32 += channel_stride;
+        }else{
+            *dst16 = wv_get_value_integer(s, &crc_extra_bits, S);
+            dst16 += channel_stride;
+        }
         count++;
-    }while(!last && count < s->samples);
+    }while(!last && count < s->max_samples);
 
     s->samples_left -= count;
     if(!s->samples_left){
@@ -655,43 +681,92 @@ static inline int wv_unpack_mono(WavpackContext *s, GetBitContext *gb, void *dst
     return count;
 }
 
+static av_cold int wv_alloc_frame_context(WavpackContext *c)
+{
+
+    if(c->fdec_num == WV_MAX_FRAME_DECODERS)
+        return -1;
+
+    c->fdec[c->fdec_num] = av_mallocz(sizeof(**c->fdec));
+    if(!c->fdec[c->fdec_num])
+        return -1;
+    c->fdec_num++;
+    c->fdec[c->fdec_num - 1]->avctx = c->avctx;
+    wv_reset_saved_context(c->fdec[c->fdec_num - 1]);
+
+    return 0;
+}
+
 static av_cold int wavpack_decode_init(AVCodecContext *avctx)
 {
     WavpackContext *s = avctx->priv_data;
 
     s->avctx = avctx;
-    s->stereo = (avctx->channels == 2);
     if(avctx->bits_per_coded_sample <= 16)
-        avctx->sample_fmt = SAMPLE_FMT_S16;
+        avctx->sample_fmt = AV_SAMPLE_FMT_S16;
     else
-        avctx->sample_fmt = SAMPLE_FMT_S32;
-    avctx->channel_layout = (avctx->channels==2) ? CH_LAYOUT_STEREO : CH_LAYOUT_MONO;
+        avctx->sample_fmt = AV_SAMPLE_FMT_S32;
+    if(avctx->channels <= 2 && !avctx->channel_layout)
+        avctx->channel_layout = (avctx->channels==2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;
+
+    s->multichannel = avctx->channels > 2;
+    /* lavf demuxer does not provide extradata, Matroska stores 0x403
+       there, use this to detect decoding mode for multichannel */
+    s->mkv_mode = 0;
+    if(s->multichannel && avctx->extradata && avctx->extradata_size == 2){
+        int ver = AV_RL16(avctx->extradata);
+        if(ver >= 0x402 && ver <= 0x410)
+            s->mkv_mode = 1;
+    }
 
-    wv_reset_saved_context(s);
+    s->fdec_num = 0;
 
     return 0;
 }
 
-static int wavpack_decode_frame(AVCodecContext *avctx,
-                            void *data, int *data_size,
-                            AVPacket *avpkt)
+static av_cold int wavpack_decode_end(AVCodecContext *avctx)
 {
-    const uint8_t *buf = avpkt->data;
-    int buf_size = avpkt->size;
     WavpackContext *s = avctx->priv_data;
+    int i;
+
+    for(i = 0; i < s->fdec_num; i++)
+        av_freep(&s->fdec[i]);
+    s->fdec_num = 0;
+
+    return 0;
+}
+
+static int wavpack_decode_block(AVCodecContext *avctx, int block_no,
+                                void *data, int *data_size,
+                                const uint8_t *buf, int buf_size)
+{
+    WavpackContext *wc = avctx->priv_data;
+    WavpackFrameContext *s;
     void *samples = data;
     int samplecount;
     int got_terms = 0, got_weights = 0, got_samples = 0, got_entropy = 0, got_bs = 0, got_float = 0;
     int got_hybrid = 0;
+    const uint8_t* orig_buf = buf;
     const uint8_t* buf_end = buf + buf_size;
     int i, j, id, size, ssize, weights, t;
-    int bpp;
+    int bpp, chan, chmask;
 
     if (buf_size == 0){
         *data_size = 0;
         return 0;
     }
 
+    if(block_no >= wc->fdec_num && wv_alloc_frame_context(wc) < 0){
+        av_log(avctx, AV_LOG_ERROR, "Error creating frame decode context\n");
+        return -1;
+    }
+
+    s = wc->fdec[block_no];
+    if(!s){
+        av_log(avctx, AV_LOG_ERROR, "Context for block %d is not present\n", block_no);
+        return -1;
+    }
+
     if(!s->samples_left){
         memset(s->decorr, 0, MAX_TERMS * sizeof(Decorr));
         memset(s->ch, 0, sizeof(s->ch));
@@ -700,28 +775,39 @@ static int wavpack_decode_frame(AVCodecContext *avctx,
         s->got_extra_bits = 0;
     }
 
-    s->samples = AV_RL32(buf); buf += 4;
-    if(!s->samples){
-        *data_size = 0;
-        return buf_size;
+    if(!wc->mkv_mode){
+        s->samples = AV_RL32(buf); buf += 4;
+        if(!s->samples){
+            *data_size = 0;
+            return buf_size;
+        }
+    }else{
+        s->samples = wc->samples;
     }
     s->frame_flags = AV_RL32(buf); buf += 4;
     if(s->frame_flags&0x80){
         bpp = sizeof(float);
-        avctx->sample_fmt = SAMPLE_FMT_FLT;
+        avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
     } else if((s->frame_flags&0x03) <= 1){
         bpp = 2;
-        avctx->sample_fmt = SAMPLE_FMT_S16;
+        avctx->sample_fmt = AV_SAMPLE_FMT_S16;
     } else {
         bpp = 4;
-        avctx->sample_fmt = SAMPLE_FMT_S32;
+        avctx->sample_fmt = AV_SAMPLE_FMT_S32;
     }
+    samples = (uint8_t*)samples + bpp * wc->ch_offset;
+
+    s->stereo = !(s->frame_flags & WV_MONO);
     s->stereo_in = (s->frame_flags & WV_FALSE_STEREO) ? 0 : s->stereo;
     s->joint = s->frame_flags & WV_JOINT_STEREO;
     s->hybrid = s->frame_flags & WV_HYBRID_MODE;
     s->hybrid_bitrate = s->frame_flags & WV_HYBRID_BITRATE;
     s->post_shift = 8 * (bpp-1-(s->frame_flags&0x03)) + ((s->frame_flags >> 13) & 0x1f);
     s->CRC = AV_RL32(buf); buf += 4;
+    if(wc->mkv_mode)
+        buf += 4; //skip block size;
+
+    wc->ch_offset += 1 + s->stereo;
 
     s->max_samples = *data_size / (bpp * avctx->channels);
     s->max_samples = FFMIN(s->max_samples, s->samples);
@@ -895,7 +981,7 @@ static int wavpack_decode_frame(AVCodecContext *avctx,
             got_float = 1;
             break;
         case WP_ID_DATA:
-            s->sc.offset = buf - avpkt->data;
+            s->sc.offset = buf - orig_buf;
             s->sc.size   = size * 8;
             init_get_bits(&s->gb, buf, size * 8);
             s->data_size = size * 8;
@@ -908,13 +994,50 @@ static int wavpack_decode_frame(AVCodecContext *avctx,
                 buf += size;
                 continue;
             }
-            s->extra_sc.offset = buf - avpkt->data;
+            s->extra_sc.offset = buf - orig_buf;
             s->extra_sc.size   = size * 8;
             init_get_bits(&s->gb_extra_bits, buf, size * 8);
             s->crc_extra_bits = get_bits_long(&s->gb_extra_bits, 32);
             buf += size;
             s->got_extra_bits = 1;
             break;
+        case WP_ID_CHANINFO:
+            if(size <= 1){
+                av_log(avctx, AV_LOG_ERROR, "Insufficient channel information\n");
+                return -1;
+            }
+            chan = *buf++;
+            switch(size - 2){
+            case 0:
+                chmask = *buf;
+                break;
+            case 1:
+                chmask = AV_RL16(buf);
+                break;
+            case 2:
+                chmask = AV_RL24(buf);
+                break;
+            case 3:
+                chmask = AV_RL32(buf);
+                break;
+            case 5:
+                chan |= (buf[1] & 0xF) << 8;
+                chmask = AV_RL24(buf + 2);
+                break;
+            default:
+                av_log(avctx, AV_LOG_ERROR, "Invalid channel info size %d\n", size);
+                chan = avctx->channels;
+                chmask = avctx->channel_layout;
+            }
+            if(chan != avctx->channels){
+                av_log(avctx, AV_LOG_ERROR, "Block reports total %d channels, decoder believes it's %d channels\n",
+                       chan, avctx->channels);
+                return -1;
+            }
+            if(!avctx->channel_layout)
+                avctx->channel_layout = chmask;
+            buf += size - 1;
+            break;
         default:
             buf += size;
         }
@@ -945,11 +1068,11 @@ static int wavpack_decode_frame(AVCodecContext *avctx,
             av_log(avctx, AV_LOG_ERROR, "Packed samples not found\n");
             return -1;
         }
-        if(!got_float && avctx->sample_fmt == SAMPLE_FMT_FLT){
+        if(!got_float && avctx->sample_fmt == AV_SAMPLE_FMT_FLT){
             av_log(avctx, AV_LOG_ERROR, "Float information not found\n");
             return -1;
         }
-        if(s->got_extra_bits && avctx->sample_fmt != SAMPLE_FMT_FLT){
+        if(s->got_extra_bits && avctx->sample_fmt != AV_SAMPLE_FMT_FLT){
             const int size = get_bits_left(&s->gb_extra_bits);
             const int wanted = s->samples * s->extra_bits << s->stereo_in;
             if(size < wanted){
@@ -959,73 +1082,121 @@ static int wavpack_decode_frame(AVCodecContext *avctx,
         }
         s->samples_left = s->samples;
     }else{
-        init_get_bits(&s->gb, avpkt->data + s->sc.offset, s->sc.size);
+        init_get_bits(&s->gb, orig_buf + s->sc.offset, s->sc.size);
         skip_bits_long(&s->gb, s->sc.bits_used);
         if(s->got_extra_bits){
-            init_get_bits(&s->gb_extra_bits, avpkt->data + s->extra_sc.offset,
+            init_get_bits(&s->gb_extra_bits, orig_buf + s->extra_sc.offset,
                           s->extra_sc.size);
             skip_bits_long(&s->gb_extra_bits, s->extra_sc.bits_used);
         }
     }
 
     if(s->stereo_in){
-        if(avctx->sample_fmt == SAMPLE_FMT_S16)
-            samplecount = wv_unpack_stereo(s, &s->gb, samples, SAMPLE_FMT_S16);
-        else if(avctx->sample_fmt == SAMPLE_FMT_S32)
-            samplecount = wv_unpack_stereo(s, &s->gb, samples, SAMPLE_FMT_S32);
+        if(avctx->sample_fmt == AV_SAMPLE_FMT_S16)
+            samplecount = wv_unpack_stereo(s, &s->gb, samples, AV_SAMPLE_FMT_S16);
+        else if(avctx->sample_fmt == AV_SAMPLE_FMT_S32)
+            samplecount = wv_unpack_stereo(s, &s->gb, samples, AV_SAMPLE_FMT_S32);
         else
-            samplecount = wv_unpack_stereo(s, &s->gb, samples, SAMPLE_FMT_FLT);
-
+            samplecount = wv_unpack_stereo(s, &s->gb, samples, AV_SAMPLE_FMT_FLT);
+        samplecount >>= 1;
     }else{
-        if(avctx->sample_fmt == SAMPLE_FMT_S16)
-            samplecount = wv_unpack_mono(s, &s->gb, samples, SAMPLE_FMT_S16);
-        else if(avctx->sample_fmt == SAMPLE_FMT_S32)
-            samplecount = wv_unpack_mono(s, &s->gb, samples, SAMPLE_FMT_S32);
+        const int channel_stride = avctx->channels;
+
+        if(avctx->sample_fmt == AV_SAMPLE_FMT_S16)
+            samplecount = wv_unpack_mono(s, &s->gb, samples, AV_SAMPLE_FMT_S16);
+        else if(avctx->sample_fmt == AV_SAMPLE_FMT_S32)
+            samplecount = wv_unpack_mono(s, &s->gb, samples, AV_SAMPLE_FMT_S32);
         else
-            samplecount = wv_unpack_mono(s, &s->gb, samples, SAMPLE_FMT_FLT);
+            samplecount = wv_unpack_mono(s, &s->gb, samples, AV_SAMPLE_FMT_FLT);
 
-        if(s->stereo && avctx->sample_fmt == SAMPLE_FMT_S16){
-            int16_t *dst = (int16_t*)samples + samplecount * 2;
-            int16_t *src = (int16_t*)samples + samplecount;
+        if(s->stereo && avctx->sample_fmt == AV_SAMPLE_FMT_S16){
+            int16_t *dst = (int16_t*)samples + 1;
+            int16_t *src = (int16_t*)samples;
             int cnt = samplecount;
             while(cnt--){
-                *--dst = *--src;
-                *--dst = *src;
+                *dst = *src;
+                src += channel_stride;
+                dst += channel_stride;
             }
-            samplecount *= 2;
-        }else if(s->stereo && avctx->sample_fmt == SAMPLE_FMT_S32){
-            int32_t *dst = (int32_t*)samples + samplecount * 2;
-            int32_t *src = (int32_t*)samples + samplecount;
+        }else if(s->stereo && avctx->sample_fmt == AV_SAMPLE_FMT_S32){
+            int32_t *dst = (int32_t*)samples + 1;
+            int32_t *src = (int32_t*)samples;
             int cnt = samplecount;
             while(cnt--){
-                *--dst = *--src;
-                *--dst = *src;
+                *dst = *src;
+                src += channel_stride;
+                dst += channel_stride;
             }
-            samplecount *= 2;
         }else if(s->stereo){
-            float *dst = (float*)samples + samplecount * 2;
-            float *src = (float*)samples + samplecount;
+            float *dst = (float*)samples + 1;
+            float *src = (float*)samples;
             int cnt = samplecount;
             while(cnt--){
-                *--dst = *--src;
-                *--dst = *src;
+                *dst = *src;
+                src += channel_stride;
+                dst += channel_stride;
             }
-            samplecount *= 2;
         }
     }
-    *data_size = samplecount * bpp;
 
-    return s->samples_left > 0 ? 0 : buf_size;
+    wc->samples_left = s->samples_left;
+
+    return samplecount * bpp;
 }
 
-AVCodec wavpack_decoder = {
+static int wavpack_decode_frame(AVCodecContext *avctx,
+                            void *data, int *data_size,
+                            AVPacket *avpkt)
+{
+    WavpackContext *s = avctx->priv_data;
+    const uint8_t *buf = avpkt->data;
+    int buf_size = avpkt->size;
+    int frame_size;
+    int samplecount = 0;
+
+    s->block = 0;
+    s->samples_left = 0;
+    s->ch_offset = 0;
+
+    if(s->mkv_mode){
+        s->samples = AV_RL32(buf); buf += 4;
+    }
+    while(buf_size > 0){
+        if(!s->multichannel){
+            frame_size = buf_size;
+        }else{
+            if(!s->mkv_mode){
+                frame_size = AV_RL32(buf) - 12; buf += 4; buf_size -= 4;
+            }else{
+                if(buf_size < 12) //MKV files can have zero flags after last block
+                    break;
+                frame_size = AV_RL32(buf + 8) + 12;
+            }
+        }
+        if(frame_size < 0 || frame_size > buf_size){
+            av_log(avctx, AV_LOG_ERROR, "Block %d has invalid size (size %d vs. %d bytes left)\n",
+                   s->block, frame_size, buf_size);
+            return -1;
+        }
+        if((samplecount = wavpack_decode_block(avctx, s->block, data,
+                                               data_size, buf, frame_size)) < 0)
+            return -1;
+        s->block++;
+        buf += frame_size; buf_size -= frame_size;
+    }
+    *data_size = samplecount * avctx->channels;
+
+    return s->samples_left > 0 ? 0 : avpkt->size;
+}
+
+AVCodec ff_wavpack_decoder = {
     "wavpack",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_WAVPACK,
     sizeof(WavpackContext),
     wavpack_decode_init,
     NULL,
-    NULL,
+    wavpack_decode_end,
     wavpack_decode_frame,
     .capabilities = CODEC_CAP_SUBFRAMES,
     .long_name = NULL_IF_CONFIG_SMALL("WavPack"),
diff --git a/libavcodec/wma.c b/libavcodec/wma.c
index 6578045..bed47ec 100644
--- a/libavcodec/wma.c
+++ b/libavcodec/wma.c
@@ -1,25 +1,26 @@
 /*
  * WMA compatible codec
- * Copyright (c) 2002-2007 The FFmpeg Project
+ * Copyright (c) 2002-2007 The Libav Project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "avcodec.h"
+#include "sinewin.h"
 #include "wma.h"
 #include "wmadata.h"
 
@@ -126,6 +127,7 @@ int ff_wma_init(AVCodecContext *avctx, int flags2)
     s->block_align = avctx->block_align;
 
     dsputil_init(&s->dsp, avctx);
+    ff_fmt_convert_init(&s->fmt_conv, avctx);
 
     if (avctx->codec->id == CODEC_ID_WMAV1) {
         s->version = 1;
@@ -217,13 +219,13 @@ int ff_wma_init(AVCodecContext *avctx, int flags2)
             high_freq = high_freq * 0.5;
         }
     }
-    dprintf(s->avctx, "flags2=0x%x\n", flags2);
-    dprintf(s->avctx, "version=%d channels=%d sample_rate=%d bitrate=%d block_align=%d\n",
+    av_dlog(s->avctx, "flags2=0x%x\n", flags2);
+    av_dlog(s->avctx, "version=%d channels=%d sample_rate=%d bitrate=%d block_align=%d\n",
             s->version, s->nb_channels, s->sample_rate, s->bit_rate,
             s->block_align);
-    dprintf(s->avctx, "bps=%f bps1=%f high_freq=%f bitoffset=%d\n",
+    av_dlog(s->avctx, "bps=%f bps1=%f high_freq=%f bitoffset=%d\n",
             bps, bps1, high_freq, s->byte_offset_bits);
-    dprintf(s->avctx, "use_noise_coding=%d use_exp_vlc=%d nb_block_sizes=%d\n",
+    av_dlog(s->avctx, "use_noise_coding=%d use_exp_vlc=%d nb_block_sizes=%d\n",
             s->use_noise_coding, s->use_exp_vlc, s->nb_block_sizes);
 
     /* compute the scale factor band sizes for each MDCT block size */
@@ -429,7 +431,7 @@ int ff_wma_end(AVCodecContext *avctx)
 
 /**
  * Decode an uncompressed coefficient.
- * @param s codec context
+ * @param gb GetBitContext
  * @return the decoded coefficient
  */
 unsigned int ff_wma_get_large_val(GetBitContext* gb)
diff --git a/libavcodec/wma.h b/libavcodec/wma.h
index 11274ad..d12c55c 100644
--- a/libavcodec/wma.h
+++ b/libavcodec/wma.h
@@ -1,21 +1,21 @@
 /*
  * WMA compatible codec
- * Copyright (c) 2002-2007 The FFmpeg Project
+ * Copyright (c) 2002-2007 The Libav Project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -26,6 +26,7 @@
 #include "put_bits.h"
 #include "dsputil.h"
 #include "fft.h"
+#include "fmtconvert.h"
 
 /* size of blocks */
 #define BLOCK_MIN_BITS 7
@@ -134,6 +135,7 @@ typedef struct WMACodecContext {
     float lsp_pow_m_table1[(1 << LSP_POW_BITS)];
     float lsp_pow_m_table2[(1 << LSP_POW_BITS)];
     DSPContext dsp;
+    FmtConvertContext fmt_conv;
 
 #ifdef TRACE
     int frame_count;
diff --git a/libavcodec/wmadata.h b/libavcodec/wmadata.h
index 381f182..07a1afe 100644
--- a/libavcodec/wmadata.h
+++ b/libavcodec/wmadata.h
@@ -1,21 +1,21 @@
 /*
  * WMA compatible decoder
- * copyright (c) 2002 The FFmpeg Project
+ * copyright (c) 2002 The Libav Project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/wmadec.c b/libavcodec/wmadec.c
index a24256d..f6ed26c 100644
--- a/libavcodec/wmadec.c
+++ b/libavcodec/wmadec.c
@@ -1,21 +1,21 @@
 /*
  * WMA compatible decoder
- * Copyright (c) 2002 The FFmpeg Project
+ * Copyright (c) 2002 The Libav Project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -123,7 +123,7 @@ static int wma_decode_init(AVCodecContext * avctx)
         wma_lsp_to_curve_init(s, s->frame_len);
     }
 
-    avctx->sample_fmt = SAMPLE_FMT_S16;
+    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
     return 0;
 }
 
@@ -447,6 +447,7 @@ static int wma_decode_block(WMACodecContext *s)
     int coef_nb_bits, total_gain;
     int nb_coefs[MAX_CHANNELS];
     float mdct_norm;
+    FFTContext *mdct;
 
 #ifdef TRACE
     tprintf(s->avctx, "***decode_block: %d:%d\n", s->frame_count - 1, s->block_num);
@@ -742,12 +743,14 @@ static int wma_decode_block(WMACodecContext *s)
     }
 
 next:
+    mdct = &s->mdct_ctx[bsize];
+
     for(ch = 0; ch < s->nb_channels; ch++) {
         int n4, index;
 
         n4 = s->block_len / 2;
         if(s->channel_coded[ch]){
-            ff_imdct_calc(&s->mdct_ctx[bsize], s->output, s->coefs[ch]);
+            mdct->imdct_calc(mdct, s->output, s->coefs[ch]);
         }else if(!(s->ms_stereo && ch==1))
             memset(s->output, 0, sizeof(s->output));
 
@@ -768,9 +771,8 @@ next:
 /* decode a frame of frame_len samples */
 static int wma_decode_frame(WMACodecContext *s, int16_t *samples)
 {
-    int ret, i, n, ch, incr;
-    int16_t *ptr;
-    float *iptr;
+    int ret, n, ch, incr;
+    const float *output[MAX_CHANNELS];
 
 #ifdef TRACE
     tprintf(s->avctx, "***decode_frame: %d size=%d\n", s->frame_count++, s->frame_len);
@@ -790,28 +792,12 @@ static int wma_decode_frame(WMACodecContext *s, int16_t *samples)
     /* convert frame to integer */
     n = s->frame_len;
     incr = s->nb_channels;
-    if (s->dsp.float_to_int16_interleave == ff_float_to_int16_interleave_c) {
-        for(ch = 0; ch < s->nb_channels; ch++) {
-            ptr = samples + ch;
-            iptr = s->frame_out[ch];
-
-            for(i=0;i<n;i++) {
-                *ptr = av_clip_int16(lrintf(*iptr++));
-                ptr += incr;
-            }
-            /* prepare for next block */
-            memmove(&s->frame_out[ch][0], &s->frame_out[ch][s->frame_len],
-                    s->frame_len * sizeof(float));
-        }
-    } else {
-        float *output[MAX_CHANNELS];
-        for (ch = 0; ch < MAX_CHANNELS; ch++)
-            output[ch] = s->frame_out[ch];
-        s->dsp.float_to_int16_interleave(samples, (const float **)output, n, incr);
-        for(ch = 0; ch < incr; ch++) {
-            /* prepare for next block */
-            memmove(&s->frame_out[ch][0], &s->frame_out[ch][n], n * sizeof(float));
-        }
+    for (ch = 0; ch < MAX_CHANNELS; ch++)
+        output[ch] = s->frame_out[ch];
+    s->fmt_conv.float_to_int16_interleave(samples, output, n, incr);
+    for (ch = 0; ch < incr; ch++) {
+        /* prepare for next block */
+        memmove(&s->frame_out[ch][0], &s->frame_out[ch][n], n * sizeof(float));
     }
 
 #ifdef TRACE
@@ -939,7 +925,7 @@ static av_cold void flush(AVCodecContext *avctx)
     s->last_superframe_len= 0;
 }
 
-AVCodec wmav1_decoder =
+AVCodec ff_wmav1_decoder =
 {
     "wmav1",
     AVMEDIA_TYPE_AUDIO,
@@ -953,7 +939,7 @@ AVCodec wmav1_decoder =
     .long_name = NULL_IF_CONFIG_SMALL("Windows Media Audio 1"),
 };
 
-AVCodec wmav2_decoder =
+AVCodec ff_wmav2_decoder =
 {
     "wmav2",
     AVMEDIA_TYPE_AUDIO,
diff --git a/libavcodec/wmaenc.c b/libavcodec/wmaenc.c
index 7aaeb70..d2e811f 100644
--- a/libavcodec/wmaenc.c
+++ b/libavcodec/wmaenc.c
@@ -2,20 +2,20 @@
  * WMA compatible encoder
  * Copyright (c) 2007 Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -74,9 +74,10 @@ static int encode_init(AVCodecContext * avctx){
 }
 
 
-static void apply_window_and_mdct(AVCodecContext * avctx, signed short * audio, int len) {
+static void apply_window_and_mdct(AVCodecContext * avctx, const signed short * audio, int len) {
     WMACodecContext *s = avctx->priv_data;
     int window_index= s->frame_len_bits - s->block_len_bits;
+    FFTContext *mdct = &s->mdct_ctx[window_index];
     int i, j, channel;
     const float * win = s->windows[window_index];
     int window_len = 1 << s->block_len_bits;
@@ -89,7 +90,7 @@ static void apply_window_and_mdct(AVCodecContext * avctx, signed short * audio,
             s->output[i+window_len]  = audio[j] / n * win[window_len - i - 1];
             s->frame_out[channel][i] = audio[j] / n * win[i];
         }
-        ff_mdct_calc(&s->mdct_ctx[window_index], s->coefs[channel], s->output);
+        mdct->mdct_calc(mdct, s->coefs[channel], s->output);
     }
 }
 
@@ -328,7 +329,7 @@ static int encode_frame(WMACodecContext *s, float (*src_coefs)[BLOCK_MAX_SIZE],
 static int encode_superframe(AVCodecContext *avctx,
                             unsigned char *buf, int buf_size, void *data){
     WMACodecContext *s = avctx->priv_data;
-    short *samples = data;
+    const short *samples = data;
     int i, total_gain;
 
     s->block_len_bits= s->frame_len_bits; //required by non variable block len
@@ -383,7 +384,7 @@ static int encode_superframe(AVCodecContext *avctx,
     return put_bits_ptr(&s->pb) - s->pb.buf;
 }
 
-AVCodec wmav1_encoder =
+AVCodec ff_wmav1_encoder =
 {
     "wmav1",
     AVMEDIA_TYPE_AUDIO,
@@ -392,11 +393,11 @@ AVCodec wmav1_encoder =
     encode_init,
     encode_superframe,
     ff_wma_end,
-    .sample_fmts = (const enum SampleFormat[]){SAMPLE_FMT_S16,SAMPLE_FMT_NONE},
+    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
     .long_name = NULL_IF_CONFIG_SMALL("Windows Media Audio 1"),
 };
 
-AVCodec wmav2_encoder =
+AVCodec ff_wmav2_encoder =
 {
     "wmav2",
     AVMEDIA_TYPE_AUDIO,
@@ -405,6 +406,6 @@ AVCodec wmav2_encoder =
     encode_init,
     encode_superframe,
     ff_wma_end,
-    .sample_fmts = (const enum SampleFormat[]){SAMPLE_FMT_S16,SAMPLE_FMT_NONE},
+    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
     .long_name = NULL_IF_CONFIG_SMALL("Windows Media Audio 2"),
 };
diff --git a/libavcodec/wmaprodata.h b/libavcodec/wmaprodata.h
index 5382479..f8a52bf 100644
--- a/libavcodec/wmaprodata.h
+++ b/libavcodec/wmaprodata.h
@@ -3,20 +3,20 @@
  * Copyright (c) 2007 Baptiste Coudurier, Benjamin Larsson, Ulion
  * Copyright (c) 2008 - 2009 Sascha Sommer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/wmaprodec.c b/libavcodec/wmaprodec.c
index 3eca101..c9048a9 100644
--- a/libavcodec/wmaprodec.c
+++ b/libavcodec/wmaprodec.c
@@ -1,22 +1,22 @@
 /*
  * Wmapro compatible decoder
  * Copyright (c) 2007 Baptiste Coudurier, Benjamin Larsson, Ulion
- * Copyright (c) 2008 - 2009 Sascha Sommer, Benjamin Larsson
+ * Copyright (c) 2008 - 2011 Sascha Sommer, Benjamin Larsson
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -92,6 +92,7 @@
 #include "put_bits.h"
 #include "wmaprodata.h"
 #include "dsputil.h"
+#include "sinewin.h"
 #include "wma.h"
 
 /** current decoder limitations */
@@ -100,9 +101,10 @@
 #define MAX_BANDS      29                                    ///< max number of scale factor bands
 #define MAX_FRAMESIZE  32768                                 ///< maximum compressed frame size
 
+#define WMAPRO_BLOCK_MIN_BITS  6                                           ///< log2 of min block size
 #define WMAPRO_BLOCK_MAX_BITS 12                                           ///< log2 of max block size
 #define WMAPRO_BLOCK_MAX_SIZE (1 << WMAPRO_BLOCK_MAX_BITS)                 ///< maximum block size
-#define WMAPRO_BLOCK_SIZES    (WMAPRO_BLOCK_MAX_BITS - BLOCK_MIN_BITS + 1) ///< possible block sizes
+#define WMAPRO_BLOCK_SIZES    (WMAPRO_BLOCK_MAX_BITS - WMAPRO_BLOCK_MIN_BITS + 1) ///< possible block sizes
 
 
 #define VLCBITS            9
@@ -142,6 +144,7 @@ typedef struct {
     int*     scale_factors;                           ///< pointer to the scale factor values used for decoding
     uint8_t  table_idx;                               ///< index in sf_offsets for the scale factor reference block
     float*   coeffs;                                  ///< pointer to the subframe decode buffer
+    uint16_t num_vec_coeffs;                          ///< number of vector coded coefficients
     DECLARE_ALIGNED(16, float, out)[WMAPRO_BLOCK_MAX_SIZE + WMAPRO_BLOCK_MAX_SIZE / 2]; ///< output buffer
 } WMAProChannelCtx;
 
@@ -190,6 +193,7 @@ typedef struct WMAProDecodeCtx {
 
     /* packet decode state */
     GetBitContext    pgb;                           ///< bitstream reader context for the packet
+    int              next_packet_start;             ///< start offset of the next wma packet in the demuxer packet
     uint8_t          packet_offset;                 ///< frame offset in the packet
     uint8_t          packet_sequence_number;        ///< current packet number
     int              num_saved_bits;                ///< saved number of bits
@@ -213,6 +217,7 @@ typedef struct WMAProDecodeCtx {
     int8_t           channels_for_cur_subframe;     ///< number of channels that contain the subframe
     int8_t           channel_indexes_for_cur_subframe[WMAPRO_MAX_CHANNELS];
     int8_t           num_bands;                     ///< number of scale factor bands
+    int8_t           transmit_num_vec_coeffs;       ///< number of vector coded coefficients is part of the bitstream
     int16_t*         cur_sfb_offsets;               ///< sfb offsets for the current block
     uint8_t          table_idx;                     ///< index for the num_sfb, sfb_offsets, sf_offsets and subwoofer_cutoffs tables
     int8_t           esc_len;                       ///< length of escaped coefficients
@@ -276,7 +281,7 @@ static av_cold int decode_init(AVCodecContext *avctx)
     dsputil_init(&s->dsp, avctx);
     init_put_bits(&s->pb, s->frame_data, MAX_FRAMESIZE);
 
-    avctx->sample_fmt = SAMPLE_FMT_FLT;
+    avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
 
     if (avctx->extradata_size >= 18) {
         s->decode_flags    = AV_RL16(edata_ptr+14);
@@ -284,8 +289,8 @@ static av_cold int decode_init(AVCodecContext *avctx)
         s->bits_per_sample = AV_RL16(edata_ptr);
         /** dump the extradata */
         for (i = 0; i < avctx->extradata_size; i++)
-            dprintf(avctx, "[%x] ", avctx->extradata[i]);
-        dprintf(avctx, "\n");
+            av_dlog(avctx, "[%x] ", avctx->extradata[i]);
+        av_dlog(avctx, "\n");
 
     } else {
         av_log_ask_for_sample(avctx, "Unknown extradata size\n");
@@ -296,15 +301,10 @@ static av_cold int decode_init(AVCodecContext *avctx)
     s->log2_frame_size = av_log2(avctx->block_align) + 4;
 
     /** frame info */
-    s->skip_frame  = 1; /** skip first frame */
+    s->skip_frame  = 1; /* skip first frame */
     s->packet_loss = 1;
     s->len_prefix  = (s->decode_flags & 0x40);
 
-    if (!s->len_prefix) {
-        av_log_ask_for_sample(avctx, "no length prefix\n");
-        return AVERROR_INVALIDDATA;
-    }
-
     /** get frame len */
     s->samples_per_frame = 1 << ff_wma_get_frame_len_bits(avctx->sample_rate,
                                                           3, s->decode_flags);
@@ -316,7 +316,7 @@ static av_cold int decode_init(AVCodecContext *avctx)
     /** subframe info */
     log2_max_num_subframes       = ((s->decode_flags & 0x38) >> 3);
     s->max_num_subframes         = 1 << log2_max_num_subframes;
-    if (s->max_num_subframes == 16)
+    if (s->max_num_subframes == 16 || s->max_num_subframes == 4)
         s->max_subframe_len_bit = 1;
     s->subframe_len_bits = av_log2(log2_max_num_subframes) + 1;
 
@@ -422,8 +422,8 @@ static av_cold int decode_init(AVCodecContext *avctx)
 
     /** init MDCT, FIXME: only init needed sizes */
     for (i = 0; i < WMAPRO_BLOCK_SIZES; i++)
-        ff_mdct_init(&s->mdct_ctx[i], BLOCK_MIN_BITS+1+i, 1,
-                     1.0 / (1 << (BLOCK_MIN_BITS + i - 1))
+        ff_mdct_init(&s->mdct_ctx[i], WMAPRO_BLOCK_MIN_BITS+1+i, 1,
+                     1.0 / (1 << (WMAPRO_BLOCK_MIN_BITS + i - 1))
                      / (1 << (s->bits_per_sample - 1)));
 
     /** init MDCT windows: simple sinus window */
@@ -508,11 +508,11 @@ static int decode_subframe_length(WMAProDecodeCtx *s, int offset)
  */
 static int decode_tilehdr(WMAProDecodeCtx *s)
 {
-    uint16_t num_samples[WMAPRO_MAX_CHANNELS];        /** sum of samples for all currently known subframes of a channel */
-    uint8_t  contains_subframe[WMAPRO_MAX_CHANNELS];  /** flag indicating if a channel contains the current subframe */
-    int channels_for_cur_subframe = s->num_channels;  /** number of channels that contain the current subframe */
-    int fixed_channel_layout = 0;                     /** flag indicating that all channels use the same subframe offsets and sizes */
-    int min_channel_len = 0;                          /** smallest sum of samples (channels with this length will be processed first) */
+    uint16_t num_samples[WMAPRO_MAX_CHANNELS];        /**< sum of samples for all currently known subframes of a channel */
+    uint8_t  contains_subframe[WMAPRO_MAX_CHANNELS];  /**< flag indicating if a channel contains the current subframe */
+    int channels_for_cur_subframe = s->num_channels;  /**< number of channels that contain the current subframe */
+    int fixed_channel_layout = 0;                     /**< flag indicating that all channels use the same subframe offsets and sizes */
+    int min_channel_len = 0;                          /**< smallest sum of samples (channels with this length will be processed first) */
     int c;
 
     /* Should never consume more than 3073 bits (256 iterations for the
@@ -583,7 +583,7 @@ static int decode_tilehdr(WMAProDecodeCtx *s)
         int i;
         int offset = 0;
         for (i = 0; i < s->channel[c].num_subframes; i++) {
-            dprintf(s->avctx, "frame[%i] channel[%i] subframe[%i]"
+            av_dlog(s->avctx, "frame[%i] channel[%i] subframe[%i]"
                     " len %i\n", s->frame_num, c, i,
                     s->channel[c].subframe_len[i]);
             s->channel[c].subframe_offset[i] = offset;
@@ -782,7 +782,7 @@ static int decode_coeffs(WMAProDecodeCtx *s, int c)
     const uint16_t* run;
     const float* level;
 
-    dprintf(s->avctx, "decode coefficients for channel %i\n", c);
+    av_dlog(s->avctx, "decode coefficients for channel %i\n", c);
 
     vlctable = get_bits1(&s->gb);
     vlc = &coef_vlc[vlctable];
@@ -797,7 +797,8 @@ static int decode_coeffs(WMAProDecodeCtx *s, int c)
 
     /** decode vector coefficients (consumes up to 167 bits per iteration for
       4 vector coded large values) */
-    while (!rl_mode && cur_coeff + 3 < s->subframe_len) {
+    while ((s->transmit_num_vec_coeffs || !rl_mode) &&
+           (cur_coeff + 3 < ci->num_vec_coeffs)) {
         int vals[4];
         int i;
         unsigned int idx;
@@ -846,7 +847,7 @@ static int decode_coeffs(WMAProDecodeCtx *s, int c)
     }
 
     /** decode run level coded coefficients */
-    if (rl_mode) {
+    if (cur_coeff < s->subframe_len) {
         memset(&ci->coeffs[cur_coeff], 0,
                sizeof(*ci->coeffs) * (s->subframe_len - cur_coeff));
         if (ff_wma_run_level_decode(s->avctx, &s->gb, vlc,
@@ -1026,12 +1027,12 @@ static void wmapro_window(WMAProDecodeCtx *s)
             winlen = s->subframe_len;
         }
 
-        window = s->windows[av_log2(winlen) - BLOCK_MIN_BITS];
+        window = s->windows[av_log2(winlen) - WMAPRO_BLOCK_MIN_BITS];
 
         winlen >>= 1;
 
         s->dsp.vector_fmul_window(start, start, start + winlen,
-                                  window, 0, winlen);
+                                  window, winlen);
 
         s->channel[c].prev_block_len = s->subframe_len;
     }
@@ -1066,7 +1067,7 @@ static int decode_subframe(WMAProDecodeCtx *s)
         }
     }
 
-    dprintf(s->avctx,
+    av_dlog(s->avctx,
             "processing subframe with offset %i len %i\n", offset, subframe_len);
 
     /** get a list of all channels that contain the estimated block */
@@ -1093,7 +1094,7 @@ static int decode_subframe(WMAProDecodeCtx *s)
         s->parsed_all_subframes = 1;
 
 
-    dprintf(s->avctx, "subframe is part of %i channels\n",
+    av_dlog(s->avctx, "subframe is part of %i channels\n",
             s->channels_for_cur_subframe);
 
     /** calculate number of scale factor bands and their offsets */
@@ -1151,10 +1152,19 @@ static int decode_subframe(WMAProDecodeCtx *s)
     if (transmit_coeffs) {
         int step;
         int quant_step = 90 * s->bits_per_sample >> 4;
-        if ((get_bits1(&s->gb))) {
-            /** FIXME: might change run level mode decision */
-            av_log_ask_for_sample(s->avctx, "unsupported quant step coding\n");
-            return AVERROR_INVALIDDATA;
+
+        /** decode number of vector coded coefficients */
+        if ((s->transmit_num_vec_coeffs = get_bits1(&s->gb))) {
+            int num_bits = av_log2((s->subframe_len + 3)/4) + 1;
+            for (i = 0; i < s->channels_for_cur_subframe; i++) {
+                int c = s->channel_indexes_for_cur_subframe[i];
+                s->channel[c].num_vec_coeffs = get_bits(&s->gb, num_bits) << 2;
+            }
+        } else {
+            for (i = 0; i < s->channels_for_cur_subframe; i++) {
+                int c = s->channel_indexes_for_cur_subframe[i];
+                s->channel[c].num_vec_coeffs = s->subframe_len;
+            }
         }
         /** decode quantization step */
         step = get_sbits(&s->gb, 6);
@@ -1195,7 +1205,7 @@ static int decode_subframe(WMAProDecodeCtx *s)
             return AVERROR_INVALIDDATA;
     }
 
-    dprintf(s->avctx, "BITSTREAM: subframe header length was %i\n",
+    av_dlog(s->avctx, "BITSTREAM: subframe header length was %i\n",
             get_bits_count(&s->gb) - s->subframe_offset);
 
     /** parse coefficients */
@@ -1209,10 +1219,11 @@ static int decode_subframe(WMAProDecodeCtx *s)
                    sizeof(*s->channel[c].coeffs) * subframe_len);
     }
 
-    dprintf(s->avctx, "BITSTREAM: subframe length was %i\n",
+    av_dlog(s->avctx, "BITSTREAM: subframe length was %i\n",
             get_bits_count(&s->gb) - s->subframe_offset);
 
     if (transmit_coeffs) {
+        FFTContext *mdct = &s->mdct_ctx[av_log2(subframe_len) - WMAPRO_BLOCK_MIN_BITS];
         /** reconstruct the per channel data */
         inverse_channel_transform(s);
         for (i = 0; i < s->channels_for_cur_subframe; i++) {
@@ -1237,9 +1248,8 @@ static int decode_subframe(WMAProDecodeCtx *s)
                                           quant, end - start);
             }
 
-            /** apply imdct (ff_imdct_half == DCTIV with reverse) */
-            ff_imdct_half(&s->mdct_ctx[av_log2(subframe_len) - BLOCK_MIN_BITS],
-                          s->channel[c].coeffs, s->tmp);
+            /** apply imdct (imdct_half == DCTIV with reverse) */
+            mdct->imdct_half(mdct, s->channel[c].coeffs, s->tmp);
         }
     }
 
@@ -1285,7 +1295,7 @@ static int decode_frame(WMAProDecodeCtx *s)
     if (s->len_prefix)
         len = get_bits(gb, s->log2_frame_size);
 
-    dprintf(s->avctx, "decoding frame with length %x\n", len);
+    av_dlog(s->avctx, "decoding frame with length %x\n", len);
 
     /** decode tile information */
     if (decode_tilehdr(s)) {
@@ -1295,15 +1305,16 @@ static int decode_frame(WMAProDecodeCtx *s)
 
     /** read postproc transform */
     if (s->num_channels > 1 && get_bits1(gb)) {
-        av_log_ask_for_sample(s->avctx, "Unsupported postproc transform found\n");
-        s->packet_loss = 1;
-        return 0;
+        if (get_bits1(gb)) {
+            for (i = 0; i < s->num_channels * s->num_channels; i++)
+                skip_bits(gb, 4);
+        }
     }
 
     /** read drc info */
     if (s->dynamic_range_compression) {
         s->drc_gain = get_bits(gb, 8);
-        dprintf(s->avctx, "drc_gain %i\n", s->drc_gain);
+        av_dlog(s->avctx, "drc_gain %i\n", s->drc_gain);
     }
 
     /** no idea what these are for, might be the number of samples
@@ -1314,18 +1325,18 @@ static int decode_frame(WMAProDecodeCtx *s)
         /** usually true for the first frame */
         if (get_bits1(gb)) {
             skip = get_bits(gb, av_log2(s->samples_per_frame * 2));
-            dprintf(s->avctx, "start skip: %i\n", skip);
+            av_dlog(s->avctx, "start skip: %i\n", skip);
         }
 
         /** sometimes true for the last frame */
         if (get_bits1(gb)) {
             skip = get_bits(gb, av_log2(s->samples_per_frame * 2));
-            dprintf(s->avctx, "end skip: %i\n", skip);
+            av_dlog(s->avctx, "end skip: %i\n", skip);
         }
 
     }
 
-    dprintf(s->avctx, "BITSTREAM: frame header length was %i\n",
+    av_dlog(s->avctx, "BITSTREAM: frame header length was %i\n",
             get_bits_count(gb) - s->frame_offset);
 
     /** reset subframe states */
@@ -1368,16 +1379,22 @@ static int decode_frame(WMAProDecodeCtx *s)
     } else
         s->samples += s->num_channels * s->samples_per_frame;
 
-    if (len != (get_bits_count(gb) - s->frame_offset) + 2) {
-        /** FIXME: not sure if this is always an error */
-        av_log(s->avctx, AV_LOG_ERROR, "frame[%i] would have to skip %i bits\n",
-               s->frame_num, len - (get_bits_count(gb) - s->frame_offset) - 1);
-        s->packet_loss = 1;
-        return 0;
-    }
+    if (s->len_prefix) {
+        if (len != (get_bits_count(gb) - s->frame_offset) + 2) {
+            /** FIXME: not sure if this is always an error */
+            av_log(s->avctx, AV_LOG_ERROR,
+                   "frame[%i] would have to skip %i bits\n", s->frame_num,
+                   len - (get_bits_count(gb) - s->frame_offset) - 1);
+            s->packet_loss = 1;
+            return 0;
+        }
 
-    /** skip the rest of the frame data */
-    skip_bits_long(gb, len - (get_bits_count(gb) - s->frame_offset) - 1);
+        /** skip the rest of the frame data */
+        skip_bits_long(gb, len - (get_bits_count(gb) - s->frame_offset) - 1);
+    } else {
+        while (get_bits_count(gb) < s->num_saved_bits && get_bits1(gb) == 0) {
+        }
+    }
 
     /** decode trailer bit */
     more_frames = get_bits1(gb);
@@ -1473,13 +1490,14 @@ static int decode_packet(AVCodecContext *avctx,
 
     if (s->packet_done || s->packet_loss) {
         s->packet_done = 0;
-        s->buf_bit_size = buf_size << 3;
 
         /** sanity check for the buffer length */
         if (buf_size < avctx->block_align)
             return 0;
 
+        s->next_packet_start = buf_size - avctx->block_align;
         buf_size = avctx->block_align;
+        s->buf_bit_size = buf_size << 3;
 
         /** parse packet header */
         init_get_bits(gb, buf, s->buf_bit_size);
@@ -1488,7 +1506,7 @@ static int decode_packet(AVCodecContext *avctx,
 
         /** get number of bits that need to be added to the previous frame */
         num_bits_prev_frame = get_bits(gb, s->log2_frame_size);
-        dprintf(avctx, "packet[%d]: nbpf %x\n", avctx->frame_number,
+        av_dlog(avctx, "packet[%d]: nbpf %x\n", avctx->frame_number,
                 num_bits_prev_frame);
 
         /** check for packet loss */
@@ -1501,32 +1519,54 @@ static int decode_packet(AVCodecContext *avctx,
         s->packet_sequence_number = packet_sequence_number;
 
         if (num_bits_prev_frame > 0) {
+            int remaining_packet_bits = s->buf_bit_size - get_bits_count(gb);
+            if (num_bits_prev_frame >= remaining_packet_bits) {
+                num_bits_prev_frame = remaining_packet_bits;
+                s->packet_done = 1;
+            }
+
             /** append the previous frame data to the remaining data from the
                 previous packet to create a full frame */
             save_bits(s, gb, num_bits_prev_frame, 1);
-            dprintf(avctx, "accumulated %x bits of frame data\n",
+            av_dlog(avctx, "accumulated %x bits of frame data\n",
                     s->num_saved_bits - s->frame_offset);
 
             /** decode the cross packet frame if it is valid */
             if (!s->packet_loss)
                 decode_frame(s);
         } else if (s->num_saved_bits - s->frame_offset) {
-            dprintf(avctx, "ignoring %x previously saved bits\n",
+            av_dlog(avctx, "ignoring %x previously saved bits\n",
                     s->num_saved_bits - s->frame_offset);
         }
 
-        s->packet_loss = 0;
+        if (s->packet_loss) {
+            /** reset number of saved bits so that the decoder
+                does not start to decode incomplete frames in the
+                s->len_prefix == 0 case */
+            s->num_saved_bits = 0;
+            s->packet_loss = 0;
+        }
 
     } else {
         int frame_size;
-        s->buf_bit_size = avpkt->size << 3;
+        s->buf_bit_size = (avpkt->size - s->next_packet_start) << 3;
         init_get_bits(gb, avpkt->data, s->buf_bit_size);
         skip_bits(gb, s->packet_offset);
-        if (remaining_bits(s, gb) > s->log2_frame_size &&
+        if (s->len_prefix && remaining_bits(s, gb) > s->log2_frame_size &&
             (frame_size = show_bits(gb, s->log2_frame_size)) &&
             frame_size <= remaining_bits(s, gb)) {
             save_bits(s, gb, frame_size, 0);
             s->packet_done = !decode_frame(s);
+        } else if (!s->len_prefix
+                   && s->num_saved_bits > get_bits_count(&s->gb)) {
+            /** when the frames do not have a length prefix, we don't know
+                the compressed length of the individual frames
+                however, we know what part of a new packet belongs to the
+                previous frame
+                therefore we save the incoming packet first, then we append
+                the "previous frame" data from the next packet so that
+                we get a buffer that only contains full frames */
+            s->packet_done = !decode_frame(s);
         } else
             s->packet_done = 1;
     }
@@ -1564,7 +1604,7 @@ static void flush(AVCodecContext *avctx)
 /**
  *@brief wmapro decoder
  */
-AVCodec wmapro_decoder = {
+AVCodec ff_wmapro_decoder = {
     "wmapro",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_WMAPRO,
diff --git a/libavcodec/wmavoice.c b/libavcodec/wmavoice.c
index 4ec17eb..33c34a0 100644
--- a/libavcodec/wmavoice.c
+++ b/libavcodec/wmavoice.c
@@ -2,20 +2,20 @@
  * Windows Media Audio Voice decoder.
  * Copyright (c) 2009 Ronald S. Bultje
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -36,8 +36,9 @@
 #include "acelp_filters.h"
 #include "lsp.h"
 #include "libavutil/lzo.h"
-#include "avfft.h"
-#include "fft.h"
+#include "dct.h"
+#include "rdft.h"
+#include "sinewin.h"
 
 #define MAX_BLOCKS           8   ///< maximum number of blocks per frame
 #define MAX_LSPS             16  ///< maximum filter order
@@ -256,7 +257,7 @@ typedef struct {
     /**
      * @}
      * @defgroup post_filter Postfilter values
-     * Varibales used for postfilter implementation, mostly history for
+     * Variables used for postfilter implementation, mostly history for
      * smoothing and so on, and context variables for FFT/iFFT.
      * @{
      */
@@ -287,7 +288,7 @@ typedef struct {
 } WMAVoiceContext;
 
 /**
- * Sets up the variable bit mode (VBM) tree from container extradata.
+ * Set up the variable bit mode (VBM) tree from container extradata.
  * @param gb bit I/O context.
  *           The bit context (s->gb) should be loaded with byte 23-46 of the
  *           container extradata (i.e. the ones containing the VBM tree).
@@ -425,7 +426,7 @@ static av_cold int wmavoice_decode_init(AVCodecContext *ctx)
                                   2 * (s->block_conv_table[1] - 2 * s->min_pitch_val);
     s->block_pitch_nbits        = av_ceil_log2(s->block_pitch_range);
 
-    ctx->sample_fmt             = SAMPLE_FMT_FLT;
+    ctx->sample_fmt             = AV_SAMPLE_FMT_FLT;
 
     return 0;
 }
@@ -558,7 +559,7 @@ static void calc_input_response(WMAVoiceContext *s, float *lpcs,
     int n, idx;
 
     /* Create frequency power spectrum of speech input (i.e. RDFT of LPCs) */
-    ff_rdft_calc(&s->rdft, lpcs);
+    s->rdft.rdft_calc(&s->rdft, lpcs);
 #define log_range(var, assign) do { \
         float tmp = log10f(assign);  var = tmp; \
         max       = FFMAX(max, tmp); min = FFMIN(min, tmp); \
@@ -582,14 +583,14 @@ static void calc_input_response(WMAVoiceContext *s, float *lpcs,
                                                           (5.0 / 14.7));
     angle_mul = gain_mul * (8.0 * M_LN10 / M_PI);
     for (n = 0; n <= 64; n++) {
-        float pow;
+        float pwr;
 
         idx = FFMAX(0, lrint((max - lpcs[n]) * irange) - 1);
-        pow = wmavoice_denoise_power_table[s->denoise_strength][idx];
-        lpcs[n] = angle_mul * pow;
+        pwr = wmavoice_denoise_power_table[s->denoise_strength][idx];
+        lpcs[n] = angle_mul * pwr;
 
         /* 70.57 =~ 1/log10(1.0331663) */
-        idx = (pow * gain_mul - 0.0295) * 70.570526123;
+        idx = (pwr * gain_mul - 0.0295) * 70.570526123;
         if (idx > 127) { // fallback if index falls outside table range
             coeffs[n] = wmavoice_energy_table[127] *
                         powf(1.0331663, idx - 127);
@@ -601,8 +602,8 @@ static void calc_input_response(WMAVoiceContext *s, float *lpcs,
      * is a sinus input) by doing a phase shift (in theory, H(sin())=cos()).
      * Hilbert_Transform(RDFT(x)) = Laplace_Transform(x), which calculates the
      * "moment" of the LPCs in this filter. */
-    ff_dct_calc(&s->dct, lpcs);
-    ff_dct_calc(&s->dst, lpcs);
+    s->dct.dct_calc(&s->dct, lpcs);
+    s->dst.dct_calc(&s->dst, lpcs);
 
     /* Split out the coefficient indexes into phase/magnitude pairs */
     idx = 255 + av_clip(lpcs[64],               -255, 255);
@@ -623,7 +624,7 @@ static void calc_input_response(WMAVoiceContext *s, float *lpcs,
     coeffs[1] = last_coeff;
 
     /* move into real domain */
-    ff_rdft_calc(&s->irdft, coeffs);
+    s->irdft.rdft_calc(&s->irdft, coeffs);
 
     /* tilt correction and normalize scale */
     memset(&coeffs[remainder], 0, sizeof(coeffs[0]) * (128 - remainder));
@@ -660,7 +661,7 @@ static void calc_input_response(WMAVoiceContext *s, float *lpcs,
  *    overlap-add method (otherwise you get clicking-artifacts).
  *
  * @param s WMA Voice decoding context
- * @param s fcb_type Frame (codebook) type
+ * @param fcb_type Frame (codebook) type
  * @param synth_pf input: the noisy speech signal, output: denoised speech
  *                 data; should be 16-byte aligned (for ASM purposes)
  * @param size size of the speech data
@@ -693,8 +694,8 @@ static void wiener_denoise(WMAVoiceContext *s, int fcb_type,
         /* apply coefficients (in frequency spectrum domain), i.e. complex
          * number multiplication */
         memset(&synth_pf[size], 0, sizeof(synth_pf[0]) * (128 - size));
-        ff_rdft_calc(&s->rdft, synth_pf);
-        ff_rdft_calc(&s->rdft, coeffs);
+        s->rdft.rdft_calc(&s->rdft, synth_pf);
+        s->rdft.rdft_calc(&s->rdft, coeffs);
         synth_pf[0] *= coeffs[0];
         synth_pf[1] *= coeffs[1];
         for (n = 1; n < 64; n++) {
@@ -702,7 +703,7 @@ static void wiener_denoise(WMAVoiceContext *s, int fcb_type,
             synth_pf[n * 2]     = v1 * coeffs[n * 2] - v2 * coeffs[n * 2 + 1];
             synth_pf[n * 2 + 1] = v2 * coeffs[n * 2] + v1 * coeffs[n * 2 + 1];
         }
-        ff_rdft_calc(&s->irdft, synth_pf);
+        s->irdft.rdft_calc(&s->irdft, synth_pf);
     }
 
     /* merge filter output with the history of previous runs */
@@ -744,6 +745,7 @@ static void wiener_denoise(WMAVoiceContext *s, int fcb_type,
  * @param samples Output buffer for filtered samples
  * @param size Buffer size of synth & samples
  * @param lpcs Generated LPCs used for speech synthesis
+ * @param zero_exc_pf destination for zero synthesis filter (16-byte aligned)
  * @param fcb_type Frame type (silence, hardcoded, AW-pulses or FCB-pulses)
  * @param pitch Pitch of the input signal
  */
@@ -1032,7 +1034,8 @@ static void aw_parse_coords(WMAVoiceContext *s, GetBitContext *gb,
 static void aw_pulse_set2(WMAVoiceContext *s, GetBitContext *gb,
                           int block_idx, AMRFixed *fcb)
 {
-    uint16_t use_mask[7]; // only 5 are used, rest is padding
+    uint16_t use_mask_mem[9]; // only 5 are used, rest is padding
+    uint16_t *use_mask = use_mask_mem + 2;
     /* in this function, idx is the index in the 80-bit (+ padding) use_mask
      * bit-array. Since use_mask consists of 16-bit values, the lower 4 bits
      * of idx are the position of the bit within a particular item in the
@@ -1064,6 +1067,7 @@ static void aw_pulse_set2(WMAVoiceContext *s, GetBitContext *gb,
     /* aw_pulse_set1() already applies pulses around pulse_off (to be exactly,
      * in the range of [pulse_off, pulse_off + s->aw_pulse_range], and thus
      * we exclude that range from being pulsed again in this function. */
+    memset(&use_mask[-2], 0, 2 * sizeof(use_mask[0]));
     memset( use_mask,   -1, 5 * sizeof(use_mask[0]));
     memset(&use_mask[5], 0, 2 * sizeof(use_mask[0]));
     if (s->aw_n_pulses[block_idx] > 0)
@@ -1342,7 +1346,7 @@ static void synth_block_fcb_acb(WMAVoiceContext *s, GetBitContext *gb,
                                   wmavoice_ipol2_coeffs, 4,
                                   idx, 8, size);
         } else
-            av_memcpy_backptr(excitation, sizeof(float) * block_pitch,
+            av_memcpy_backptr((uint8_t *) excitation, sizeof(float) * block_pitch,
                               sizeof(float) * size);
     }
 
@@ -1901,14 +1905,14 @@ static int wmavoice_decode_packet(AVCodecContext *ctx, void *data,
 
     if (*data_size < 480 * sizeof(float)) {
         av_log(ctx, AV_LOG_ERROR,
-               "Output buffer too small (%d given - %lu needed)\n",
+               "Output buffer too small (%d given - %zu needed)\n",
                *data_size, 480 * sizeof(float));
         return -1;
     }
     *data_size = 0;
 
     /* Packets are sometimes a multiple of ctx->block_align, with a packet
-     * header at each ctx->block_align bytes. However, FFmpeg's ASF demuxer
+     * header at each ctx->block_align bytes. However, Libav's ASF demuxer
      * feeds us ASF packets, which may concatenate multiple "codec" packets
      * in a single "muxer" packet, so we artificially emulate that by
      * capping the packet size at ctx->block_align. */
@@ -2015,7 +2019,7 @@ static av_cold void wmavoice_flush(AVCodecContext *ctx)
     }
 }
 
-AVCodec wmavoice_decoder = {
+AVCodec ff_wmavoice_decoder = {
     "wmavoice",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_WMAVOICE,
diff --git a/libavcodec/wmavoice_data.h b/libavcodec/wmavoice_data.h
index cbf65b0..7f14fb8 100644
--- a/libavcodec/wmavoice_data.h
+++ b/libavcodec/wmavoice_data.h
@@ -2,20 +2,20 @@
  * Windows Media Voice (WMAVoice) tables.
  * Copyright (c) 2009 Ronald S. Bultje
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/wmv2.c b/libavcodec/wmv2.c
index e872b44..74389ef 100644
--- a/libavcodec/wmv2.c
+++ b/libavcodec/wmv2.c
@@ -1,20 +1,20 @@
 /*
- * Copyright (c) 2002 The FFmpeg Project
+ * Copyright (c) 2002 The Libav Project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -102,7 +102,7 @@ void ff_mspel_motion(MpegEncContext *s,
     if(s->flags&CODEC_FLAG_EMU_EDGE){
         if(src_x<1 || src_y<1 || src_x + 17  >= s->h_edge_pos
                               || src_y + h+1 >= v_edge_pos){
-            ff_emulated_edge_mc(s->edge_emu_buffer, ptr - 1 - s->linesize, s->linesize, 19, 19,
+            s->dsp.emulated_edge_mc(s->edge_emu_buffer, ptr - 1 - s->linesize, s->linesize, 19, 19,
                              src_x-1, src_y-1, s->h_edge_pos, s->v_edge_pos);
             ptr= s->edge_emu_buffer + 1 + s->linesize;
             emu=1;
@@ -143,7 +143,7 @@ void ff_mspel_motion(MpegEncContext *s,
     offset = (src_y * uvlinesize) + src_x;
     ptr = ref_picture[1] + offset;
     if(emu){
-        ff_emulated_edge_mc(s->edge_emu_buffer, ptr, s->uvlinesize, 9, 9,
+        s->dsp.emulated_edge_mc(s->edge_emu_buffer, ptr, s->uvlinesize, 9, 9,
                          src_x, src_y, s->h_edge_pos>>1, s->v_edge_pos>>1);
         ptr= s->edge_emu_buffer;
     }
@@ -151,7 +151,7 @@ void ff_mspel_motion(MpegEncContext *s,
 
     ptr = ref_picture[2] + offset;
     if(emu){
-        ff_emulated_edge_mc(s->edge_emu_buffer, ptr, s->uvlinesize, 9, 9,
+        s->dsp.emulated_edge_mc(s->edge_emu_buffer, ptr, s->uvlinesize, 9, 9,
                          src_x, src_y, s->h_edge_pos>>1, s->v_edge_pos>>1);
         ptr= s->edge_emu_buffer;
     }
diff --git a/libavcodec/wmv2.h b/libavcodec/wmv2.h
index c69c9f4..80f36cc 100644
--- a/libavcodec/wmv2.h
+++ b/libavcodec/wmv2.h
@@ -1,20 +1,20 @@
 /*
- * Copyright (c) 2002 The FFmpeg Project
+ * Copyright (c) 2002 The Libav Project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/wmv2dec.c b/libavcodec/wmv2dec.c
index a9bb80c..578cce9 100644
--- a/libavcodec/wmv2dec.c
+++ b/libavcodec/wmv2dec.c
@@ -1,20 +1,20 @@
 /*
- * Copyright (c) 2002 The FFmpeg Project
+ * Copyright (c) 2002 The Libav Project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -87,7 +87,7 @@ static int decode_ext_header(Wmv2Context *w){
 
     if(s->avctx->extradata_size<4) return -1;
 
-    init_get_bits(&gb, s->avctx->extradata, s->avctx->extradata_size*8);
+    init_get_bits(&gb, s->avctx->extradata, 32);
 
     fps                = get_bits(&gb, 5);
     s->bit_rate        = get_bits(&gb, 11)*1024;
@@ -484,7 +484,7 @@ static av_cold int wmv2_decode_end(AVCodecContext *avctx)
     return ff_h263_decode_end(avctx);
 }
 
-AVCodec wmv2_decoder = {
+AVCodec ff_wmv2_decoder = {
     "wmv2",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_WMV2,
@@ -494,6 +494,7 @@ AVCodec wmv2_decoder = {
     wmv2_decode_end,
     ff_h263_decode_frame,
     CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1,
+    .max_lowres = 3,
     .long_name = NULL_IF_CONFIG_SMALL("Windows Media Video 8"),
     .pix_fmts= ff_pixfmt_list_420,
 };
diff --git a/libavcodec/wmv2enc.c b/libavcodec/wmv2enc.c
index 7416f85..d59cbaf 100644
--- a/libavcodec/wmv2enc.c
+++ b/libavcodec/wmv2enc.c
@@ -1,20 +1,20 @@
 /*
- * Copyright (c) 2002 The FFmpeg Project
+ * Copyright (c) 2002 The Libav Project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -211,7 +211,7 @@ void ff_wmv2_encode_mb(MpegEncContext * s,
     }
 }
 
-AVCodec wmv2_encoder = {
+AVCodec ff_wmv2_encoder = {
     "wmv2",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_WMV2,
diff --git a/libavcodec/wnv1.c b/libavcodec/wnv1.c
index 56634d1..7c0a537 100644
--- a/libavcodec/wnv1.c
+++ b/libavcodec/wnv1.c
@@ -2,20 +2,20 @@
  * Winnov WNV1 codec
  * Copyright (c) 2005 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -154,7 +154,7 @@ static av_cold int decode_end(AVCodecContext *avctx){
     return 0;
 }
 
-AVCodec wnv1_decoder = {
+AVCodec ff_wnv1_decoder = {
     "wnv1",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_WNV1,
diff --git a/libavcodec/ws-snd1.c b/libavcodec/ws-snd1.c
index a383673..534be56 100644
--- a/libavcodec/ws-snd1.c
+++ b/libavcodec/ws-snd1.c
@@ -2,23 +2,24 @@
  * Westwood SNDx codecs
  * Copyright (c) 2005 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include <stdint.h>
 #include "libavutil/intreadwrite.h"
 #include "avcodec.h"
 
@@ -31,8 +32,8 @@
  * http://www.multimedia.cx
  */
 
-static const char ws_adpcm_2bit[] = { -2, -1, 0, 1};
-static const char ws_adpcm_4bit[] = {
+static const int8_t ws_adpcm_2bit[] = { -2, -1, 0, 1};
+static const int8_t ws_adpcm_4bit[] = {
     -9, -8, -6, -5, -4, -3, -2, -1,
      0,  1,  2,  3,  4,  5,  6,  8 };
 
@@ -42,7 +43,7 @@ static av_cold int ws_snd_decode_init(AVCodecContext * avctx)
 {
 //    WSSNDContext *c = avctx->priv_data;
 
-    avctx->sample_fmt = SAMPLE_FMT_S16;
+    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
     return 0;
 }
 
@@ -120,7 +121,7 @@ static int ws_snd_decode_frame(AVCodecContext *avctx,
             break;
         case 2: /* no compression */
             if (count & 0x20) { /* big delta */
-                char t;
+                int8_t t;
                 t = count;
                 t <<= 3;
                 sample += t >> 3;
@@ -145,7 +146,7 @@ static int ws_snd_decode_frame(AVCodecContext *avctx,
     return buf_size;
 }
 
-AVCodec ws_snd1_decoder = {
+AVCodec ff_ws_snd1_decoder = {
     "ws_snd1",
     AVMEDIA_TYPE_AUDIO,
     CODEC_ID_WESTWOOD_SND1,
diff --git a/libavcodec/x86/Makefile b/libavcodec/x86/Makefile
index f4d0c84..f8d456d 100644
--- a/libavcodec/x86/Makefile
+++ b/libavcodec/x86/Makefile
@@ -6,34 +6,55 @@ YASM-OBJS-FFT-$(HAVE_AMD3DNOWEXT)      += x86/fft_3dn2.o
 YASM-OBJS-FFT-$(HAVE_SSE)              += x86/fft_sse.o
 YASM-OBJS-$(CONFIG_FFT)                += x86/fft_mmx.o                 \
                                           $(YASM-OBJS-FFT-yes)
-YASM-OBJS-$(CONFIG_GPL)                += x86/h264_deblock_sse2.o       \
-                                          x86/h264_idct_sse2.o          \
 
+MMX-OBJS-$(CONFIG_H264DSP)             += x86/h264dsp_mmx.o
+YASM-OBJS-$(CONFIG_H264DSP)            += x86/h264_deblock.o            \
+                                          x86/h264_weight.o             \
+                                          x86/h264_idct.o               \
+
+YASM-OBJS-$(CONFIG_H264PRED)           += x86/h264_intrapred.o
+MMX-OBJS-$(CONFIG_H264PRED)            += x86/h264_intrapred_init.o
+
+YASM-OBJS-$(CONFIG_VC1_DECODER)        += x86/vc1dsp_yasm.o
+
+MMX-OBJS-$(CONFIG_AC3DSP)              += x86/ac3dsp_mmx.o
+YASM-OBJS-$(CONFIG_AC3DSP)             += x86/ac3dsp.o
 MMX-OBJS-$(CONFIG_CAVS_DECODER)        += x86/cavsdsp_mmx.o
+MMX-OBJS-$(CONFIG_MP1FLOAT_DECODER)    += x86/mpegaudiodec_mmx.o
+MMX-OBJS-$(CONFIG_MP2FLOAT_DECODER)    += x86/mpegaudiodec_mmx.o
+MMX-OBJS-$(CONFIG_MP3FLOAT_DECODER)    += x86/mpegaudiodec_mmx.o
+MMX-OBJS-$(CONFIG_MP3ON4FLOAT_DECODER) += x86/mpegaudiodec_mmx.o
+MMX-OBJS-$(CONFIG_MP3ADUFLOAT_DECODER) += x86/mpegaudiodec_mmx.o
 MMX-OBJS-$(CONFIG_ENCODERS)            += x86/dsputilenc_mmx.o
+YASM-OBJS-$(CONFIG_ENCODERS)           += x86/dsputilenc_yasm.o
 MMX-OBJS-$(CONFIG_GPL)                 += x86/idct_mmx.o
 MMX-OBJS-$(CONFIG_LPC)                 += x86/lpc_mmx.o
 MMX-OBJS-$(CONFIG_DWT)                 += x86/snowdsp_mmx.o
 MMX-OBJS-$(CONFIG_VC1_DECODER)         += x86/vc1dsp_mmx.o
-MMX-OBJS-$(CONFIG_VP3_DECODER)         += x86/vp3dsp_mmx.o              \
-                                          x86/vp3dsp_sse2.o
-MMX-OBJS-$(CONFIG_VP5_DECODER)         += x86/vp3dsp_mmx.o              \
-                                          x86/vp3dsp_sse2.o
-MMX-OBJS-$(CONFIG_VP6_DECODER)         += x86/vp3dsp_mmx.o              \
-                                          x86/vp3dsp_sse2.o             \
-                                          x86/vp6dsp_mmx.o              \
-                                          x86/vp6dsp_sse2.o
+YASM-OBJS-$(CONFIG_VP3_DECODER)        += x86/vp3dsp.o
+YASM-OBJS-$(CONFIG_VP5_DECODER)        += x86/vp3dsp.o
+MMX-OBJS-$(CONFIG_VP5_DECODER)         += x86/vp56dsp_init.o
+YASM-OBJS-$(CONFIG_VP6_DECODER)        += x86/vp3dsp.o                  \
+                                          x86/vp56dsp.o
+MMX-OBJS-$(CONFIG_VP6_DECODER)         += x86/vp56dsp_init.o
+YASM-OBJS-$(CONFIG_VP8_DECODER)        += x86/vp8dsp.o
+MMX-OBJS-$(CONFIG_VP8_DECODER)         += x86/vp8dsp-init.o
 MMX-OBJS-$(HAVE_YASM)                  += x86/dsputil_yasm.o            \
+                                          x86/deinterlace.o             \
+                                          x86/fmtconvert.o              \
+                                          x86/h264_chromamc.o           \
                                           $(YASM-OBJS-yes)
 
 MMX-OBJS-$(CONFIG_FFT)                 += x86/fft.o
 
-OBJS-$(HAVE_MMX)                       += x86/cpuid.o                   \
-                                          x86/dnxhd_mmx.o               \
+OBJS-$(HAVE_MMX)                       += x86/dnxhd_mmx.o               \
                                           x86/dsputil_mmx.o             \
                                           x86/fdct_mmx.o                \
+                                          x86/fmtconvert_mmx.o          \
                                           x86/idct_mmx_xvid.o           \
                                           x86/idct_sse2_xvid.o          \
                                           x86/motion_est_mmx.o          \
                                           x86/mpegvideo_mmx.o           \
                                           x86/simple_idct_mmx.o         \
+
+MMX-OBJS-$(CONFIG_DCT)                 += x86/dct32_sse.o
diff --git a/libavcodec/x86/ac3dsp.asm b/libavcodec/x86/ac3dsp.asm
new file mode 100644
index 0000000..1b34751
--- /dev/null
+++ b/libavcodec/x86/ac3dsp.asm
@@ -0,0 +1,295 @@
+;*****************************************************************************
+;* x86-optimized AC-3 DSP utils
+;* Copyright (c) 2011 Justin Ruggles
+;*
+;* This file is part of Libav.
+;*
+;* Libav is free software; you can redistribute it and/or
+;* modify it under the terms of the GNU Lesser General Public
+;* License as published by the Free Software Foundation; either
+;* version 2.1 of the License, or (at your option) any later version.
+;*
+;* Libav is distributed in the hope that it will be useful,
+;* but WITHOUT ANY WARRANTY; without even the implied warranty of
+;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+;* Lesser General Public License for more details.
+;*
+;* You should have received a copy of the GNU Lesser General Public
+;* License along with Libav; if not, write to the Free Software
+;* 51, Inc., Foundation Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+;******************************************************************************
+
+%include "x86inc.asm"
+%include "x86util.asm"
+
+SECTION_RODATA
+
+; 16777216.0f - used in ff_float_to_fixed24()
+pf_1_24: times 4 dd 0x4B800000
+
+SECTION .text
+
+;-----------------------------------------------------------------------------
+; void ff_ac3_exponent_min(uint8_t *exp, int num_reuse_blocks, int nb_coefs)
+;-----------------------------------------------------------------------------
+
+%macro AC3_EXPONENT_MIN 1
+cglobal ac3_exponent_min_%1, 3,4,2, exp, reuse_blks, expn, offset
+    shl  reuse_blksq, 8
+    jz .end
+    LOOP_ALIGN
+.nextexp:
+    mov      offsetq, reuse_blksq
+    mova          m0, [expq+offsetq]
+    sub      offsetq, 256
+    LOOP_ALIGN
+.nextblk:
+    PMINUB        m0, [expq+offsetq], m1
+    sub      offsetq, 256
+    jae .nextblk
+    mova      [expq], m0
+    add         expq, mmsize
+    sub        expnq, mmsize
+    jg .nextexp
+.end:
+    REP_RET
+%endmacro
+
+%define PMINUB PMINUB_MMX
+%define LOOP_ALIGN
+INIT_MMX
+AC3_EXPONENT_MIN mmx
+%ifdef HAVE_MMX2
+%define PMINUB PMINUB_MMXEXT
+%define LOOP_ALIGN ALIGN 16
+AC3_EXPONENT_MIN mmxext
+%endif
+%ifdef HAVE_SSE
+INIT_XMM
+AC3_EXPONENT_MIN sse2
+%endif
+%undef PMINUB
+%undef LOOP_ALIGN
+
+;-----------------------------------------------------------------------------
+; int ff_ac3_max_msb_abs_int16(const int16_t *src, int len)
+;
+; This function uses 2 different methods to calculate a valid result.
+; 1) logical 'or' of abs of each element
+;        This is used for ssse3 because of the pabsw instruction.
+;        It is also used for mmx because of the lack of min/max instructions.
+; 2) calculate min/max for the array, then or(abs(min),abs(max))
+;        This is used for mmxext and sse2 because they have pminsw/pmaxsw.
+;-----------------------------------------------------------------------------
+
+%macro AC3_MAX_MSB_ABS_INT16 2
+cglobal ac3_max_msb_abs_int16_%1, 2,2,5, src, len
+    pxor        m2, m2
+    pxor        m3, m3
+.loop:
+%ifidn %2, min_max
+    mova        m0, [srcq]
+    mova        m1, [srcq+mmsize]
+    pminsw      m2, m0
+    pminsw      m2, m1
+    pmaxsw      m3, m0
+    pmaxsw      m3, m1
+%else ; or_abs
+%ifidn %1, mmx
+    mova        m0, [srcq]
+    mova        m1, [srcq+mmsize]
+    ABS2        m0, m1, m3, m4
+%else ; ssse3
+    ; using memory args is faster for ssse3
+    pabsw       m0, [srcq]
+    pabsw       m1, [srcq+mmsize]
+%endif
+    por         m2, m0
+    por         m2, m1
+%endif
+    add       srcq, mmsize*2
+    sub       lend, mmsize
+    ja .loop
+%ifidn %2, min_max
+    ABS2        m2, m3, m0, m1
+    por         m2, m3
+%endif
+%ifidn mmsize, 16
+    movhlps     m0, m2
+    por         m2, m0
+%endif
+    PSHUFLW     m0, m2, 0xe
+    por         m2, m0
+    PSHUFLW     m0, m2, 0x1
+    por         m2, m0
+    movd       eax, m2
+    and        eax, 0xFFFF
+    RET
+%endmacro
+
+INIT_MMX
+%define ABS2 ABS2_MMX
+%define PSHUFLW pshufw
+AC3_MAX_MSB_ABS_INT16 mmx, or_abs
+%define ABS2 ABS2_MMX2
+AC3_MAX_MSB_ABS_INT16 mmxext, min_max
+INIT_XMM
+%define PSHUFLW pshuflw
+AC3_MAX_MSB_ABS_INT16 sse2, min_max
+%define ABS2 ABS2_SSSE3
+AC3_MAX_MSB_ABS_INT16 ssse3, or_abs
+
+;-----------------------------------------------------------------------------
+; macro used for ff_ac3_lshift_int16() and ff_ac3_rshift_int32()
+;-----------------------------------------------------------------------------
+
+%macro AC3_SHIFT 4 ; l/r, 16/32, shift instruction, instruction set
+cglobal ac3_%1shift_int%2_%4, 3,3,5, src, len, shift
+    movd      m0, shiftd
+.loop:
+    mova      m1, [srcq         ]
+    mova      m2, [srcq+mmsize  ]
+    mova      m3, [srcq+mmsize*2]
+    mova      m4, [srcq+mmsize*3]
+    %3        m1, m0
+    %3        m2, m0
+    %3        m3, m0
+    %3        m4, m0
+    mova  [srcq         ], m1
+    mova  [srcq+mmsize  ], m2
+    mova  [srcq+mmsize*2], m3
+    mova  [srcq+mmsize*3], m4
+    add     srcq, mmsize*4
+    sub     lend, mmsize*32/%2
+    ja .loop
+.end:
+    REP_RET
+%endmacro
+
+;-----------------------------------------------------------------------------
+; void ff_ac3_lshift_int16(int16_t *src, unsigned int len, unsigned int shift)
+;-----------------------------------------------------------------------------
+
+INIT_MMX
+AC3_SHIFT l, 16, psllw, mmx
+INIT_XMM
+AC3_SHIFT l, 16, psllw, sse2
+
+;-----------------------------------------------------------------------------
+; void ff_ac3_rshift_int32(int32_t *src, unsigned int len, unsigned int shift)
+;-----------------------------------------------------------------------------
+
+INIT_MMX
+AC3_SHIFT r, 32, psrad, mmx
+INIT_XMM
+AC3_SHIFT r, 32, psrad, sse2
+
+;-----------------------------------------------------------------------------
+; void ff_float_to_fixed24(int32_t *dst, const float *src, unsigned int len)
+;-----------------------------------------------------------------------------
+
+; The 3DNow! version is not bit-identical because pf2id uses truncation rather
+; than round-to-nearest.
+INIT_MMX
+cglobal float_to_fixed24_3dnow, 3,3,0, dst, src, len
+    movq   m0, [pf_1_24]
+.loop:
+    movq   m1, [srcq   ]
+    movq   m2, [srcq+8 ]
+    movq   m3, [srcq+16]
+    movq   m4, [srcq+24]
+    pfmul  m1, m0
+    pfmul  m2, m0
+    pfmul  m3, m0
+    pfmul  m4, m0
+    pf2id  m1, m1
+    pf2id  m2, m2
+    pf2id  m3, m3
+    pf2id  m4, m4
+    movq  [dstq   ], m1
+    movq  [dstq+8 ], m2
+    movq  [dstq+16], m3
+    movq  [dstq+24], m4
+    add  srcq, 32
+    add  dstq, 32
+    sub  lend, 8
+    ja .loop
+    REP_RET
+
+INIT_XMM
+cglobal float_to_fixed24_sse, 3,3,3, dst, src, len
+    movaps     m0, [pf_1_24]
+.loop:
+    movaps     m1, [srcq   ]
+    movaps     m2, [srcq+16]
+    mulps      m1, m0
+    mulps      m2, m0
+    cvtps2pi  mm0, m1
+    movhlps    m1, m1
+    cvtps2pi  mm1, m1
+    cvtps2pi  mm2, m2
+    movhlps    m2, m2
+    cvtps2pi  mm3, m2
+    movq  [dstq   ], mm0
+    movq  [dstq+ 8], mm1
+    movq  [dstq+16], mm2
+    movq  [dstq+24], mm3
+    add      srcq, 32
+    add      dstq, 32
+    sub      lend, 8
+    ja .loop
+    REP_RET
+
+INIT_XMM
+cglobal float_to_fixed24_sse2, 3,3,9, dst, src, len
+    movaps     m0, [pf_1_24]
+.loop:
+    movaps     m1, [srcq    ]
+    movaps     m2, [srcq+16 ]
+    movaps     m3, [srcq+32 ]
+    movaps     m4, [srcq+48 ]
+%ifdef m8
+    movaps     m5, [srcq+64 ]
+    movaps     m6, [srcq+80 ]
+    movaps     m7, [srcq+96 ]
+    movaps     m8, [srcq+112]
+%endif
+    mulps      m1, m0
+    mulps      m2, m0
+    mulps      m3, m0
+    mulps      m4, m0
+%ifdef m8
+    mulps      m5, m0
+    mulps      m6, m0
+    mulps      m7, m0
+    mulps      m8, m0
+%endif
+    cvtps2dq   m1, m1
+    cvtps2dq   m2, m2
+    cvtps2dq   m3, m3
+    cvtps2dq   m4, m4
+%ifdef m8
+    cvtps2dq   m5, m5
+    cvtps2dq   m6, m6
+    cvtps2dq   m7, m7
+    cvtps2dq   m8, m8
+%endif
+    movdqa  [dstq    ], m1
+    movdqa  [dstq+16 ], m2
+    movdqa  [dstq+32 ], m3
+    movdqa  [dstq+48 ], m4
+%ifdef m8
+    movdqa  [dstq+64 ], m5
+    movdqa  [dstq+80 ], m6
+    movdqa  [dstq+96 ], m7
+    movdqa  [dstq+112], m8
+    add      srcq, 128
+    add      dstq, 128
+    sub      lenq, 32
+%else
+    add      srcq, 64
+    add      dstq, 64
+    sub      lenq, 16
+%endif
+    ja .loop
+    REP_RET
diff --git a/libavcodec/x86/ac3dsp_mmx.c b/libavcodec/x86/ac3dsp_mmx.c
new file mode 100644
index 0000000..4750423
--- /dev/null
+++ b/libavcodec/x86/ac3dsp_mmx.c
@@ -0,0 +1,81 @@
+/*
+ * x86-optimized AC-3 DSP utils
+ * Copyright (c) 2011 Justin Ruggles
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "libavutil/x86_cpu.h"
+#include "dsputil_mmx.h"
+#include "libavcodec/ac3dsp.h"
+
+extern void ff_ac3_exponent_min_mmx   (uint8_t *exp, int num_reuse_blocks, int nb_coefs);
+extern void ff_ac3_exponent_min_mmxext(uint8_t *exp, int num_reuse_blocks, int nb_coefs);
+extern void ff_ac3_exponent_min_sse2  (uint8_t *exp, int num_reuse_blocks, int nb_coefs);
+
+extern int ff_ac3_max_msb_abs_int16_mmx   (const int16_t *src, int len);
+extern int ff_ac3_max_msb_abs_int16_mmxext(const int16_t *src, int len);
+extern int ff_ac3_max_msb_abs_int16_sse2  (const int16_t *src, int len);
+extern int ff_ac3_max_msb_abs_int16_ssse3 (const int16_t *src, int len);
+
+extern void ff_ac3_lshift_int16_mmx (int16_t *src, unsigned int len, unsigned int shift);
+extern void ff_ac3_lshift_int16_sse2(int16_t *src, unsigned int len, unsigned int shift);
+
+extern void ff_ac3_rshift_int32_mmx (int32_t *src, unsigned int len, unsigned int shift);
+extern void ff_ac3_rshift_int32_sse2(int32_t *src, unsigned int len, unsigned int shift);
+
+extern void ff_float_to_fixed24_3dnow(int32_t *dst, const float *src, unsigned int len);
+extern void ff_float_to_fixed24_sse  (int32_t *dst, const float *src, unsigned int len);
+extern void ff_float_to_fixed24_sse2 (int32_t *dst, const float *src, unsigned int len);
+
+av_cold void ff_ac3dsp_init_x86(AC3DSPContext *c, int bit_exact)
+{
+    int mm_flags = av_get_cpu_flags();
+
+#if HAVE_YASM
+    if (mm_flags & AV_CPU_FLAG_MMX) {
+        c->ac3_exponent_min = ff_ac3_exponent_min_mmx;
+        c->ac3_max_msb_abs_int16 = ff_ac3_max_msb_abs_int16_mmx;
+        c->ac3_lshift_int16 = ff_ac3_lshift_int16_mmx;
+        c->ac3_rshift_int32 = ff_ac3_rshift_int32_mmx;
+    }
+    if (mm_flags & AV_CPU_FLAG_3DNOW && HAVE_AMD3DNOW) {
+        if (!bit_exact) {
+            c->float_to_fixed24 = ff_float_to_fixed24_3dnow;
+        }
+    }
+    if (mm_flags & AV_CPU_FLAG_MMX2 && HAVE_MMX2) {
+        c->ac3_exponent_min = ff_ac3_exponent_min_mmxext;
+        c->ac3_max_msb_abs_int16 = ff_ac3_max_msb_abs_int16_mmxext;
+    }
+    if (mm_flags & AV_CPU_FLAG_SSE && HAVE_SSE) {
+        c->float_to_fixed24 = ff_float_to_fixed24_sse;
+    }
+    if (mm_flags & AV_CPU_FLAG_SSE2 && HAVE_SSE) {
+        c->ac3_exponent_min = ff_ac3_exponent_min_sse2;
+        c->ac3_max_msb_abs_int16 = ff_ac3_max_msb_abs_int16_sse2;
+        c->float_to_fixed24 = ff_float_to_fixed24_sse2;
+        if (!(mm_flags & AV_CPU_FLAG_SSE2SLOW)) {
+            c->ac3_lshift_int16 = ff_ac3_lshift_int16_sse2;
+            c->ac3_rshift_int32 = ff_ac3_rshift_int32_sse2;
+        }
+    }
+    if (mm_flags & AV_CPU_FLAG_SSSE3 && HAVE_SSSE3) {
+        c->ac3_max_msb_abs_int16 = ff_ac3_max_msb_abs_int16_ssse3;
+    }
+#endif
+}
diff --git a/libavcodec/x86/cavsdsp_mmx.c b/libavcodec/x86/cavsdsp_mmx.c
index 638eaf7..3bc62ea 100644
--- a/libavcodec/x86/cavsdsp_mmx.c
+++ b/libavcodec/x86/cavsdsp_mmx.c
@@ -5,26 +5,28 @@
  * MMX-optimized DSP functions, based on H.264 optimizations by
  * Michael Niedermayer and Loren Merritt
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "libavutil/common.h"
+#include "libavutil/cpu.h"
 #include "libavutil/x86_cpu.h"
 #include "libavcodec/dsputil.h"
+#include "libavcodec/cavsdsp.h"
 #include "dsputil_mmx.h"
 
 /*****************************************************************************
@@ -118,7 +120,7 @@ static void cavs_idct8_add_mmx(uint8_t *dst, int16_t *block, int stride)
     for(i=0; i<2; i++){
         DECLARE_ALIGNED(8, uint64_t, tmp);
 
-        cavs_idct8_1d(block+4*i, ff_pw_4);
+        cavs_idct8_1d(block+4*i, ff_pw_4.a);
 
         __asm__ volatile(
             "psraw     $3, %%mm7  \n\t"
@@ -172,7 +174,7 @@ static void cavs_idct8_add_mmx(uint8_t *dst, int16_t *block, int stride)
         );
     }
 
-    add_pixels_clamped_mmx(b2, dst, stride);
+    ff_add_pixels_clamped_mmx(b2, dst, stride);
 }
 
 /*****************************************************************************
@@ -437,7 +439,7 @@ CAVS_MC(put_, 16,mmx2)
 CAVS_MC(avg_, 8, mmx2)
 CAVS_MC(avg_, 16,mmx2)
 
-void ff_cavsdsp_init_mmx2(DSPContext* c, AVCodecContext *avctx) {
+static void ff_cavsdsp_init_mmx2(CAVSDSPContext* c, AVCodecContext *avctx) {
 #define dspfunc(PFX, IDX, NUM) \
     c->PFX ## _pixels_tab[IDX][ 0] = ff_ ## PFX ## NUM ## _mc00_mmx2; \
     c->PFX ## _pixels_tab[IDX][ 2] = ff_ ## PFX ## NUM ## _mc20_mmx2; \
@@ -453,7 +455,7 @@ void ff_cavsdsp_init_mmx2(DSPContext* c, AVCodecContext *avctx) {
     c->cavs_idct8_add = cavs_idct8_add_mmx;
 }
 
-void ff_cavsdsp_init_3dnow(DSPContext* c, AVCodecContext *avctx) {
+static void ff_cavsdsp_init_3dnow(CAVSDSPContext* c, AVCodecContext *avctx) {
 #define dspfunc(PFX, IDX, NUM) \
     c->PFX ## _pixels_tab[IDX][ 0] = ff_ ## PFX ## NUM ## _mc00_mmx2; \
     c->PFX ## _pixels_tab[IDX][ 2] = ff_ ## PFX ## NUM ## _mc20_3dnow; \
@@ -468,3 +470,11 @@ void ff_cavsdsp_init_3dnow(DSPContext* c, AVCodecContext *avctx) {
 #undef dspfunc
     c->cavs_idct8_add = cavs_idct8_add_mmx;
 }
+
+void ff_cavsdsp_init_mmx(CAVSDSPContext *c, AVCodecContext *avctx)
+{
+    int mm_flags = av_get_cpu_flags();
+
+    if (mm_flags & AV_CPU_FLAG_MMX2)  ff_cavsdsp_init_mmx2 (c, avctx);
+    if (mm_flags & AV_CPU_FLAG_3DNOW) ff_cavsdsp_init_3dnow(c, avctx);
+}
diff --git a/libavcodec/x86/cpuid.c b/libavcodec/x86/cpuid.c
deleted file mode 100644
index 1ed4d2e..0000000
--- a/libavcodec/x86/cpuid.c
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * CPU detection code, extracted from mmx.h
- * (c)1997-99 by H. Dietz and R. Fisher
- * Converted to C and improved by Fabrice Bellard.
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-#include <stdlib.h>
-#include "libavutil/x86_cpu.h"
-#include "libavcodec/dsputil.h"
-
-#undef printf
-
-/* ebx saving is necessary for PIC. gcc seems unable to see it alone */
-#define cpuid(index,eax,ebx,ecx,edx)\
-    __asm__ volatile\
-        ("mov %%"REG_b", %%"REG_S"\n\t"\
-         "cpuid\n\t"\
-         "xchg %%"REG_b", %%"REG_S\
-         : "=a" (eax), "=S" (ebx),\
-           "=c" (ecx), "=d" (edx)\
-         : "0" (index));
-
-/* Function to test if multimedia instructions are supported...  */
-int mm_support(void)
-{
-    int rval = 0;
-    int eax, ebx, ecx, edx;
-    int max_std_level, max_ext_level, std_caps=0, ext_caps=0;
-
-#if ARCH_X86_32
-    x86_reg a, c;
-    __asm__ volatile (
-        /* See if CPUID instruction is supported ... */
-        /* ... Get copies of EFLAGS into eax and ecx */
-        "pushfl\n\t"
-        "pop %0\n\t"
-        "mov %0, %1\n\t"
-
-        /* ... Toggle the ID bit in one copy and store */
-        /*     to the EFLAGS reg */
-        "xor $0x200000, %0\n\t"
-        "push %0\n\t"
-        "popfl\n\t"
-
-        /* ... Get the (hopefully modified) EFLAGS */
-        "pushfl\n\t"
-        "pop %0\n\t"
-        : "=a" (a), "=c" (c)
-        :
-        : "cc"
-        );
-
-    if (a == c)
-        return 0; /* CPUID not supported */
-#endif
-
-    cpuid(0, max_std_level, ebx, ecx, edx);
-
-    if(max_std_level >= 1){
-        cpuid(1, eax, ebx, ecx, std_caps);
-        if (std_caps & (1<<23))
-            rval |= FF_MM_MMX;
-        if (std_caps & (1<<25))
-            rval |= FF_MM_MMX2
-#if HAVE_SSE
-                  | FF_MM_SSE;
-        if (std_caps & (1<<26))
-            rval |= FF_MM_SSE2;
-        if (ecx & 1)
-            rval |= FF_MM_SSE3;
-        if (ecx & 0x00000200 )
-            rval |= FF_MM_SSSE3;
-        if (ecx & 0x00080000 )
-            rval |= FF_MM_SSE4;
-        if (ecx & 0x00100000 )
-            rval |= FF_MM_SSE42;
-#endif
-                  ;
-    }
-
-    cpuid(0x80000000, max_ext_level, ebx, ecx, edx);
-
-    if(max_ext_level >= 0x80000001){
-        cpuid(0x80000001, eax, ebx, ecx, ext_caps);
-        if (ext_caps & (1<<31))
-            rval |= FF_MM_3DNOW;
-        if (ext_caps & (1<<30))
-            rval |= FF_MM_3DNOWEXT;
-        if (ext_caps & (1<<23))
-            rval |= FF_MM_MMX;
-        if (ext_caps & (1<<22))
-            rval |= FF_MM_MMX2;
-    }
-
-#if 0
-    av_log(NULL, AV_LOG_DEBUG, "%s%s%s%s%s%s%s%s%s%s\n",
-        (rval&FF_MM_MMX) ? "MMX ":"",
-        (rval&FF_MM_MMX2) ? "MMX2 ":"",
-        (rval&FF_MM_SSE) ? "SSE ":"",
-        (rval&FF_MM_SSE2) ? "SSE2 ":"",
-        (rval&FF_MM_SSE3) ? "SSE3 ":"",
-        (rval&FF_MM_SSSE3) ? "SSSE3 ":"",
-        (rval&FF_MM_SSE4) ? "SSE4.1 ":"",
-        (rval&FF_MM_SSE42) ? "SSE4.2 ":"",
-        (rval&FF_MM_3DNOW) ? "3DNow ":"",
-        (rval&FF_MM_3DNOWEXT) ? "3DNowExt ":"");
-#endif
-    return rval;
-}
-
-#ifdef TEST
-int main ( void )
-{
-    int mm_flags;
-    mm_flags = mm_support();
-    printf("mm_support = 0x%08X\n",mm_flags);
-    return 0;
-}
-#endif
diff --git a/libavcodec/x86/dct32_sse.c b/libavcodec/x86/dct32_sse.c
new file mode 100644
index 0000000..5303c6d
--- /dev/null
+++ b/libavcodec/x86/dct32_sse.c
@@ -0,0 +1,296 @@
+/*
+ * 32 point SSE-optimized DCT transform
+ * Copyright (c) 2010 Vitor Sessak
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <stdint.h>
+
+#include "libavutil/x86_cpu.h"
+#include "libavutil/mem.h"
+#include "libavcodec/dsputil.h"
+#include "fft.h"
+
+DECLARE_ALIGNED(16, static const float, b1)[] = {
+     0.500603,  0.505471,  0.515447,  0.531043,
+     0.553104,  0.582935,  0.622504,  0.674808,
+    -1.169440, -0.972568, -0.839350, -0.744536,
+   -10.190008, -3.407609, -2.057781, -1.484165,
+     0.502419,  0.522499,  0.566944,  0.646822,
+     0.788155,  1.060678,  1.722447,  5.101149,
+     0.509796,  0.601345,  0.899976,  2.562916,
+     1.000000,  1.000000,  1.306563,  0.541196,
+     1.000000,  0.707107,  1.000000, -0.707107
+};
+
+DECLARE_ALIGNED(16, static const int32_t, smask)[4] = {
+    0, 0, 0x80000000, 0x80000000
+};
+
+/* butterfly operator */
+#define BUTTERFLY(a,b,c,tmp)                            \
+    "movaps  %%" #a    ", %%" #tmp  "             \n\t" \
+    "subps   %%" #b    ", %%" #a    "             \n\t" \
+    "addps   %%" #tmp  ", %%" #b    "             \n\t" \
+    "mulps     " #c    ", %%" #a    "             \n\t"
+
+///* Same as BUTTERFLY when vectors a and b overlap */
+#define BUTTERFLY0(val, mask, cos, tmp, shuf)                            \
+    "movaps  %%" #val  ", %%" #tmp  "             \n\t"                  \
+    "shufps    " #shuf ", %%" #val  ",%%" #val "  \n\t"                  \
+    "xorps   %%" #mask ", %%" #tmp  "             \n\t" /* flip signs */ \
+    "addps   %%" #tmp  ", %%" #val  "             \n\t"                  \
+    "mulps   %%" #cos  ", %%" #val  "             \n\t"
+
+#define BUTTERFLY2(val, mask, cos, tmp) BUTTERFLY0(val, mask, cos, tmp, $0x1b)
+#define BUTTERFLY3(val, mask, cos, tmp) BUTTERFLY0(val, mask, cos, tmp, $0xb1)
+
+void ff_dct32_float_sse(FFTSample *out, const FFTSample *in)
+{
+    int32_t tmp1 = 0;
+    __asm__ volatile(
+        /* pass 1 */
+
+        "movaps    (%4), %%xmm0           \n\t"
+        "movaps 112(%4), %%xmm1           \n\t"
+        "shufps   $0x1b, %%xmm1, %%xmm1   \n\t"
+        BUTTERFLY(xmm0, xmm1, (%2), xmm3)
+
+        "movaps  64(%4), %%xmm7           \n\t"
+        "movaps  48(%4), %%xmm4           \n\t"
+        "shufps   $0x1b, %%xmm4, %%xmm4   \n\t"
+        BUTTERFLY(xmm7, xmm4, 48(%2), xmm3)
+
+
+        /* pass 2 */
+        "movaps  64(%2), %%xmm2           \n\t"
+        BUTTERFLY(xmm1, xmm4, %%xmm2, xmm3)
+        "movaps  %%xmm1, 48(%1)           \n\t"
+        "movaps  %%xmm4, (%1)             \n\t"
+
+        /* pass 1 */
+        "movaps  16(%4), %%xmm1           \n\t"
+        "movaps  96(%4), %%xmm6           \n\t"
+        "shufps   $0x1b, %%xmm6, %%xmm6   \n\t"
+        BUTTERFLY(xmm1, xmm6, 16(%2), xmm3)
+
+        "movaps  80(%4), %%xmm4           \n\t"
+        "movaps  32(%4), %%xmm5           \n\t"
+        "shufps   $0x1b, %%xmm5, %%xmm5   \n\t"
+        BUTTERFLY(xmm4, xmm5, 32(%2), xmm3)
+
+        /* pass 2 */
+        BUTTERFLY(xmm0, xmm7, %%xmm2, xmm3)
+
+        "movaps  80(%2), %%xmm2           \n\t"
+        BUTTERFLY(xmm6, xmm5, %%xmm2, xmm3)
+
+        BUTTERFLY(xmm1, xmm4, %%xmm2, xmm3)
+
+        /* pass 3 */
+        "movaps  96(%2), %%xmm2           \n\t"
+        "shufps   $0x1b, %%xmm1, %%xmm1   \n\t"
+        BUTTERFLY(xmm0, xmm1, %%xmm2, xmm3)
+        "movaps  %%xmm0, 112(%1)          \n\t"
+        "movaps  %%xmm1,  96(%1)          \n\t"
+
+        "movaps   0(%1), %%xmm0           \n\t"
+        "shufps   $0x1b, %%xmm5, %%xmm5   \n\t"
+        BUTTERFLY(xmm0, xmm5, %%xmm2, xmm3)
+
+        "movaps  48(%1), %%xmm1           \n\t"
+        "shufps   $0x1b, %%xmm6, %%xmm6   \n\t"
+        BUTTERFLY(xmm1, xmm6, %%xmm2, xmm3)
+        "movaps  %%xmm1,  48(%1)          \n\t"
+
+        "shufps   $0x1b, %%xmm4, %%xmm4   \n\t"
+        BUTTERFLY(xmm7, xmm4, %%xmm2, xmm3)
+
+        /* pass 4 */
+        "movaps    (%3), %%xmm3           \n\t"
+        "movaps 112(%2), %%xmm2           \n\t"
+
+        BUTTERFLY2(xmm5, xmm3, xmm2, xmm1)
+
+        BUTTERFLY2(xmm0, xmm3, xmm2, xmm1)
+        "movaps  %%xmm0, 16(%1)           \n\t"
+
+        BUTTERFLY2(xmm6, xmm3, xmm2, xmm1)
+        "movaps  %%xmm6, 32(%1)           \n\t"
+
+        "movaps  48(%1), %%xmm0           \n\t"
+        BUTTERFLY2(xmm0, xmm3, xmm2, xmm1)
+        "movaps  %%xmm0, 48(%1)           \n\t"
+
+        BUTTERFLY2(xmm4, xmm3, xmm2, xmm1)
+
+        BUTTERFLY2(xmm7, xmm3, xmm2, xmm1)
+
+        "movaps  96(%1), %%xmm6           \n\t"
+        BUTTERFLY2(xmm6, xmm3, xmm2, xmm1)
+
+        "movaps 112(%1), %%xmm0           \n\t"
+        BUTTERFLY2(xmm0, xmm3, xmm2, xmm1)
+
+        /* pass 5 */
+        "movaps 128(%2), %%xmm2           \n\t"
+        "shufps   $0xCC, %%xmm3,%%xmm3    \n\t"
+
+        BUTTERFLY3(xmm5, xmm3, xmm2, xmm1)
+        "movaps  %%xmm5, (%1)             \n\t"
+
+        "movaps  16(%1), %%xmm1           \n\t"
+        BUTTERFLY3(xmm1, xmm3, xmm2, xmm5)
+        "movaps  %%xmm1, 16(%1)           \n\t"
+
+        BUTTERFLY3(xmm4, xmm3, xmm2, xmm5)
+        "movaps  %%xmm4, 64(%1)           \n\t"
+
+        BUTTERFLY3(xmm7, xmm3, xmm2, xmm5)
+        "movaps  %%xmm7, 80(%1)           \n\t"
+
+        "movaps  32(%1), %%xmm5           \n\t"
+        BUTTERFLY3(xmm5, xmm3, xmm2, xmm7)
+        "movaps  %%xmm5, 32(%1)           \n\t"
+
+        "movaps  48(%1), %%xmm4           \n\t"
+        BUTTERFLY3(xmm4, xmm3, xmm2, xmm7)
+        "movaps  %%xmm4, 48(%1)           \n\t"
+
+        BUTTERFLY3(xmm6, xmm3, xmm2, xmm7)
+        "movaps  %%xmm6, 96(%1)           \n\t"
+
+        BUTTERFLY3(xmm0, xmm3, xmm2, xmm7)
+        "movaps  %%xmm0, 112(%1)          \n\t"
+
+
+        /* pass 6, no SIMD... */
+        "movss    56(%1),  %%xmm3           \n\t"
+        "movl      4(%1),      %0           \n\t"
+        "addss    60(%1),  %%xmm3           \n\t"
+        "movss    72(%1),  %%xmm7           \n\t"
+        "addss    %%xmm3,  %%xmm4           \n\t"
+        "movss    52(%1),  %%xmm2           \n\t"
+        "addss    %%xmm3,  %%xmm2           \n\t"
+        "movss    24(%1),  %%xmm3           \n\t"
+        "addss    28(%1),  %%xmm3           \n\t"
+        "addss    76(%1),  %%xmm7           \n\t"
+        "addss    %%xmm3,  %%xmm1           \n\t"
+        "addss    %%xmm4,  %%xmm5           \n\t"
+        "movss    %%xmm1,  16(%1)           \n\t"
+        "movss    20(%1),  %%xmm1           \n\t"
+        "addss    %%xmm3,  %%xmm1           \n\t"
+        "movss    40(%1),  %%xmm3           \n\t"
+        "movss    %%xmm1,  48(%1)           \n\t"
+        "addss    44(%1),  %%xmm3           \n\t"
+        "movss    20(%1),  %%xmm1           \n\t"
+        "addss    %%xmm3,  %%xmm4           \n\t"
+        "addss    %%xmm2,  %%xmm3           \n\t"
+        "addss    28(%1),  %%xmm1           \n\t"
+        "movss    %%xmm3,  40(%1)           \n\t"
+        "addss    36(%1),  %%xmm2           \n\t"
+        "movss     8(%1),  %%xmm3           \n\t"
+        "movss    %%xmm2,  56(%1)           \n\t"
+        "addss    12(%1),  %%xmm3           \n\t"
+        "movss    %%xmm5,   8(%1)           \n\t"
+        "movss    %%xmm3,  32(%1)           \n\t"
+        "movss    52(%1),  %%xmm2           \n\t"
+        "movss    80(%1),  %%xmm3           \n\t"
+        "movss   120(%1),  %%xmm5           \n\t"
+        "movss    %%xmm1,  80(%1)           \n\t"
+        "movss    %%xmm4,  24(%1)           \n\t"
+        "addss   124(%1),  %%xmm5           \n\t"
+        "movss    64(%1),  %%xmm1           \n\t"
+        "addss    60(%1),  %%xmm2           \n\t"
+        "addss    %%xmm5,  %%xmm0           \n\t"
+        "addss   116(%1),  %%xmm5           \n\t"
+        "movl         %0,  64(%1)           \n\t"
+        "addss    %%xmm0,  %%xmm6           \n\t"
+        "addss    %%xmm6,  %%xmm1           \n\t"
+        "movl     12(%1),      %0           \n\t"
+        "movss    %%xmm1,   4(%1)           \n\t"
+        "movss    88(%1),  %%xmm1           \n\t"
+        "movl         %0,  96(%1)           \n\t"
+        "addss    92(%1),  %%xmm1           \n\t"
+        "movss   104(%1),  %%xmm4           \n\t"
+        "movl     28(%1),      %0           \n\t"
+        "addss   108(%1),  %%xmm4           \n\t"
+        "addss    %%xmm4,  %%xmm0           \n\t"
+        "addss    %%xmm1,  %%xmm3           \n\t"
+        "addss    84(%1),  %%xmm1           \n\t"
+        "addss    %%xmm5,  %%xmm4           \n\t"
+        "addss    %%xmm3,  %%xmm6           \n\t"
+        "addss    %%xmm0,  %%xmm3           \n\t"
+        "addss    %%xmm7,  %%xmm0           \n\t"
+        "addss   100(%1),  %%xmm5           \n\t"
+        "addss    %%xmm4,  %%xmm7           \n\t"
+        "movl         %0, 112(%1)           \n\t"
+        "movss    %%xmm0,  28(%1)           \n\t"
+        "movss    36(%1),  %%xmm0           \n\t"
+        "movss    %%xmm7,  36(%1)           \n\t"
+        "addss    %%xmm1,  %%xmm4           \n\t"
+        "movss   116(%1),  %%xmm7           \n\t"
+        "addss    %%xmm2,  %%xmm0           \n\t"
+        "addss   124(%1),  %%xmm7           \n\t"
+        "movss    %%xmm0,  72(%1)           \n\t"
+        "movss    44(%1),  %%xmm0           \n\t"
+        "movss    %%xmm6,  12(%1)           \n\t"
+        "movss    %%xmm3,  20(%1)           \n\t"
+        "addss    %%xmm0,  %%xmm2           \n\t"
+        "movss    %%xmm4,  44(%1)           \n\t"
+        "movss    %%xmm2,  88(%1)           \n\t"
+        "addss    60(%1),  %%xmm0           \n\t"
+        "movl     60(%1),      %0           \n\t"
+        "movl         %0, 120(%1)           \n\t"
+        "movss    %%xmm0, 104(%1)           \n\t"
+        "addss    %%xmm5,  %%xmm1           \n\t"
+        "addss    68(%1),  %%xmm5           \n\t"
+        "movss    %%xmm1,  52(%1)           \n\t"
+        "movss    %%xmm5,  60(%1)           \n\t"
+        "movss    68(%1),  %%xmm1           \n\t"
+        "movss   100(%1),  %%xmm5           \n\t"
+        "addss    %%xmm7,  %%xmm5           \n\t"
+        "addss   108(%1),  %%xmm7           \n\t"
+        "addss    %%xmm5,  %%xmm1           \n\t"
+        "movss    84(%1),  %%xmm2           \n\t"
+        "addss    92(%1),  %%xmm2           \n\t"
+        "addss    %%xmm2,  %%xmm5           \n\t"
+        "movss    %%xmm1,  68(%1)           \n\t"
+        "addss    %%xmm7,  %%xmm2           \n\t"
+        "movss    76(%1),  %%xmm1           \n\t"
+        "movss    %%xmm2,  84(%1)           \n\t"
+        "movss    %%xmm5,  76(%1)           \n\t"
+        "movss   108(%1),  %%xmm2           \n\t"
+        "addss    %%xmm1,  %%xmm7           \n\t"
+        "addss   124(%1),  %%xmm2           \n\t"
+        "addss    %%xmm2,  %%xmm1           \n\t"
+        "addss    92(%1),  %%xmm2           \n\t"
+        "movss    %%xmm1, 100(%1)           \n\t"
+        "movss    %%xmm2, 108(%1)           \n\t"
+        "movss    92(%1),  %%xmm2           \n\t"
+        "movss    %%xmm7,  92(%1)           \n\t"
+        "addss   124(%1),  %%xmm2           \n\t"
+        "movss    %%xmm2, 116(%1)           \n\t"
+        :"+&r"(tmp1)
+        :"r"(out), "r"(b1), "r"(smask), "r"(in)
+        :XMM_CLOBBERS("%xmm0", "%xmm1", "%xmm2", "%xmm3",
+                      "%xmm4", "%xmm5", "%xmm6", "%xmm7",)
+         "memory"
+        );
+}
+
diff --git a/libavcodec/x86/deinterlace.asm b/libavcodec/x86/deinterlace.asm
new file mode 100644
index 0000000..4eb2c2d
--- /dev/null
+++ b/libavcodec/x86/deinterlace.asm
@@ -0,0 +1,83 @@
+;******************************************************************************
+;* MMX optimized deinterlacing functions
+;* Copyright (c) 2010 Vitor Sessak
+;* Copyright (c) 2002 Michael Niedermayer
+;*
+;* This file is part of Libav.
+;*
+;* Libav is free software; you can redistribute it and/or
+;* modify it under the terms of the GNU Lesser General Public
+;* License as published by the Free Software Foundation; either
+;* version 2.1 of the License, or (at your option) any later version.
+;*
+;* Libav is distributed in the hope that it will be useful,
+;* but WITHOUT ANY WARRANTY; without even the implied warranty of
+;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+;* Lesser General Public License for more details.
+;*
+;* You should have received a copy of the GNU Lesser General Public
+;* License along with Libav; if not, write to the Free Software
+;* 51, Inc., Foundation Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+;******************************************************************************
+
+%include "x86inc.asm"
+%include "x86util.asm"
+
+SECTION_RODATA
+
+cextern pw_4
+
+SECTION .text
+
+%macro DEINTERLACE 1
+%ifidn %1, inplace
+;void ff_deinterlace_line_inplace_mmx(const uint8_t *lum_m4, const uint8_t *lum_m3, const uint8_t *lum_m2, const uint8_t *lum_m1, const uint8_t *lum,  int size)
+cglobal deinterlace_line_inplace_mmx, 6,6,7,      lum_m4, lum_m3, lum_m2, lum_m1, lum, size
+%else
+;void ff_deinterlace_line_mmx(uint8_t *dst, const uint8_t *lum_m4, const uint8_t *lum_m3, const uint8_t *lum_m2, const uint8_t *lum_m1, const uint8_t *lum,  int size)
+cglobal deinterlace_line_mmx,         7,7,7, dst, lum_m4, lum_m3, lum_m2, lum_m1, lum, size
+%endif
+    pxor  mm7, mm7
+    movq  mm6, [pw_4]
+.nextrow
+    movd  mm0, [lum_m4q]
+    movd  mm1, [lum_m3q]
+    movd  mm2, [lum_m2q]
+%ifidn %1, inplace
+    movd [lum_m4q], mm2
+%endif
+    movd  mm3, [lum_m1q]
+    movd  mm4, [lumq]
+    punpcklbw mm0, mm7
+    punpcklbw mm1, mm7
+    punpcklbw mm2, mm7
+    punpcklbw mm3, mm7
+    punpcklbw mm4, mm7
+    paddw     mm1, mm3
+    psllw     mm2, 1
+    paddw     mm0, mm4
+    psllw     mm1, 2
+    paddw     mm2, mm6
+    paddw     mm1, mm2
+    psubusw   mm1, mm0
+    psrlw     mm1, 3
+    packuswb  mm1, mm7
+%ifidn %1, inplace
+    movd [lum_m2q], mm1
+%else
+    movd   [dstq], mm1
+    add       dstq, 4
+%endif
+    add    lum_m4q, 4
+    add    lum_m3q, 4
+    add    lum_m2q, 4
+    add    lum_m1q, 4
+    add       lumq, 4
+    sub      sized, 4
+    jg .nextrow
+    REP_RET
+%endmacro
+
+DEINTERLACE ""
+
+DEINTERLACE inplace
diff --git a/libavcodec/x86/dnxhd_mmx.c b/libavcodec/x86/dnxhd_mmx.c
index 59bcb39..f00ce9b 100644
--- a/libavcodec/x86/dnxhd_mmx.c
+++ b/libavcodec/x86/dnxhd_mmx.c
@@ -4,20 +4,20 @@
  *
  * VC-3 encoder funded by the British Broadcasting Corporation
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -27,16 +27,16 @@
 static void get_pixels_8x4_sym_sse2(DCTELEM *block, const uint8_t *pixels, int line_size)
 {
     __asm__ volatile(
-        "pxor %%xmm7,      %%xmm7       \n\t"
+        "pxor %%xmm5,      %%xmm5       \n\t"
         "movq (%0),        %%xmm0       \n\t"
         "add  %2,          %0           \n\t"
         "movq (%0),        %%xmm1       \n\t"
         "movq (%0, %2),    %%xmm2       \n\t"
         "movq (%0, %2,2),  %%xmm3       \n\t"
-        "punpcklbw %%xmm7, %%xmm0       \n\t"
-        "punpcklbw %%xmm7, %%xmm1       \n\t"
-        "punpcklbw %%xmm7, %%xmm2       \n\t"
-        "punpcklbw %%xmm7, %%xmm3       \n\t"
+        "punpcklbw %%xmm5, %%xmm0       \n\t"
+        "punpcklbw %%xmm5, %%xmm1       \n\t"
+        "punpcklbw %%xmm5, %%xmm2       \n\t"
+        "punpcklbw %%xmm5, %%xmm3       \n\t"
         "movdqa %%xmm0,      (%1)       \n\t"
         "movdqa %%xmm1,    16(%1)       \n\t"
         "movdqa %%xmm2,    32(%1)       \n\t"
@@ -52,7 +52,7 @@ static void get_pixels_8x4_sym_sse2(DCTELEM *block, const uint8_t *pixels, int l
 
 void ff_dnxhd_init_mmx(DNXHDEncContext *ctx)
 {
-    if (mm_flags & FF_MM_SSE2) {
+    if (av_get_cpu_flags() & AV_CPU_FLAG_SSE2) {
         ctx->get_pixels_8x4_sym = get_pixels_8x4_sym_sse2;
     }
 }
diff --git a/libavcodec/x86/dsputil_h264_template_mmx.c b/libavcodec/x86/dsputil_h264_template_mmx.c
deleted file mode 100644
index bc2379e..0000000
--- a/libavcodec/x86/dsputil_h264_template_mmx.c
+++ /dev/null
@@ -1,304 +0,0 @@
-/*
- * Copyright (c) 2005 Zoltan Hidvegi <hzoli -a- hzoli -d- com>,
- *                    Loren Merritt
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-/**
- * MMX optimized version of (put|avg)_h264_chroma_mc8.
- * H264_CHROMA_MC8_TMPL must be defined to the desired function name
- * H264_CHROMA_OP must be defined to empty for put and pavgb/pavgusb for avg
- * H264_CHROMA_MC8_MV0 must be defined to a (put|avg)_pixels8 function
- */
-static void H264_CHROMA_MC8_TMPL(uint8_t *dst/*align 8*/, uint8_t *src/*align 1*/, int stride, int h, int x, int y, const uint64_t *rnd_reg)
-{
-    DECLARE_ALIGNED(8, uint64_t, AA);
-    DECLARE_ALIGNED(8, uint64_t, DD);
-    int i;
-
-    if(y==0 && x==0) {
-        /* no filter needed */
-        H264_CHROMA_MC8_MV0(dst, src, stride, h);
-        return;
-    }
-
-    assert(x<8 && y<8 && x>=0 && y>=0);
-
-    if(y==0 || x==0)
-    {
-        /* 1 dimensional filter only */
-        const int dxy = x ? 1 : stride;
-
-        __asm__ volatile(
-            "movd %0, %%mm5\n\t"
-            "movq %1, %%mm4\n\t"
-            "movq %2, %%mm6\n\t"         /* mm6 = rnd >> 3 */
-            "punpcklwd %%mm5, %%mm5\n\t"
-            "punpckldq %%mm5, %%mm5\n\t" /* mm5 = B = x */
-            "pxor %%mm7, %%mm7\n\t"
-            "psubw %%mm5, %%mm4\n\t"     /* mm4 = A = 8-x */
-            :: "rm"(x+y), "m"(ff_pw_8), "m"(*(rnd_reg+1)));
-
-        for(i=0; i<h; i++) {
-            __asm__ volatile(
-                /* mm0 = src[0..7], mm1 = src[1..8] */
-                "movq %0, %%mm0\n\t"
-                "movq %1, %%mm2\n\t"
-                :: "m"(src[0]), "m"(src[dxy]));
-
-            __asm__ volatile(
-                /* [mm0,mm1] = A * src[0..7] */
-                /* [mm2,mm3] = B * src[1..8] */
-                "movq %%mm0, %%mm1\n\t"
-                "movq %%mm2, %%mm3\n\t"
-                "punpcklbw %%mm7, %%mm0\n\t"
-                "punpckhbw %%mm7, %%mm1\n\t"
-                "punpcklbw %%mm7, %%mm2\n\t"
-                "punpckhbw %%mm7, %%mm3\n\t"
-                "pmullw %%mm4, %%mm0\n\t"
-                "pmullw %%mm4, %%mm1\n\t"
-                "pmullw %%mm5, %%mm2\n\t"
-                "pmullw %%mm5, %%mm3\n\t"
-
-                /* dst[0..7] = (A * src[0..7] + B * src[1..8] + (rnd >> 3)) >> 3 */
-                "paddw %%mm6, %%mm0\n\t"
-                "paddw %%mm6, %%mm1\n\t"
-                "paddw %%mm2, %%mm0\n\t"
-                "paddw %%mm3, %%mm1\n\t"
-                "psrlw $3, %%mm0\n\t"
-                "psrlw $3, %%mm1\n\t"
-                "packuswb %%mm1, %%mm0\n\t"
-                H264_CHROMA_OP(%0, %%mm0)
-                "movq %%mm0, %0\n\t"
-                : "=m" (dst[0]));
-
-            src += stride;
-            dst += stride;
-        }
-        return;
-    }
-
-    /* general case, bilinear */
-    __asm__ volatile("movd %2, %%mm4\n\t"
-                 "movd %3, %%mm6\n\t"
-                 "punpcklwd %%mm4, %%mm4\n\t"
-                 "punpcklwd %%mm6, %%mm6\n\t"
-                 "punpckldq %%mm4, %%mm4\n\t" /* mm4 = x words */
-                 "punpckldq %%mm6, %%mm6\n\t" /* mm6 = y words */
-                 "movq %%mm4, %%mm5\n\t"
-                 "pmullw %%mm6, %%mm4\n\t"    /* mm4 = x * y */
-                 "psllw $3, %%mm5\n\t"
-                 "psllw $3, %%mm6\n\t"
-                 "movq %%mm5, %%mm7\n\t"
-                 "paddw %%mm6, %%mm7\n\t"
-                 "movq %%mm4, %1\n\t"         /* DD = x * y */
-                 "psubw %%mm4, %%mm5\n\t"     /* mm5 = B = 8x - xy */
-                 "psubw %%mm4, %%mm6\n\t"     /* mm6 = C = 8y - xy */
-                 "paddw %4, %%mm4\n\t"
-                 "psubw %%mm7, %%mm4\n\t"     /* mm4 = A = xy - (8x+8y) + 64 */
-                 "pxor %%mm7, %%mm7\n\t"
-                 "movq %%mm4, %0\n\t"
-                 : "=m" (AA), "=m" (DD) : "rm" (x), "rm" (y), "m" (ff_pw_64));
-
-    __asm__ volatile(
-        /* mm0 = src[0..7], mm1 = src[1..8] */
-        "movq %0, %%mm0\n\t"
-        "movq %1, %%mm1\n\t"
-        : : "m" (src[0]), "m" (src[1]));
-
-    for(i=0; i<h; i++) {
-        src += stride;
-
-        __asm__ volatile(
-            /* mm2 = A * src[0..3] + B * src[1..4] */
-            /* mm3 = A * src[4..7] + B * src[5..8] */
-            "movq %%mm0, %%mm2\n\t"
-            "movq %%mm1, %%mm3\n\t"
-            "punpckhbw %%mm7, %%mm0\n\t"
-            "punpcklbw %%mm7, %%mm1\n\t"
-            "punpcklbw %%mm7, %%mm2\n\t"
-            "punpckhbw %%mm7, %%mm3\n\t"
-            "pmullw %0, %%mm0\n\t"
-            "pmullw %0, %%mm2\n\t"
-            "pmullw %%mm5, %%mm1\n\t"
-            "pmullw %%mm5, %%mm3\n\t"
-            "paddw %%mm1, %%mm2\n\t"
-            "paddw %%mm0, %%mm3\n\t"
-            : : "m" (AA));
-
-        __asm__ volatile(
-            /* [mm2,mm3] += C * src[0..7] */
-            "movq %0, %%mm0\n\t"
-            "movq %%mm0, %%mm1\n\t"
-            "punpcklbw %%mm7, %%mm0\n\t"
-            "punpckhbw %%mm7, %%mm1\n\t"
-            "pmullw %%mm6, %%mm0\n\t"
-            "pmullw %%mm6, %%mm1\n\t"
-            "paddw %%mm0, %%mm2\n\t"
-            "paddw %%mm1, %%mm3\n\t"
-            : : "m" (src[0]));
-
-        __asm__ volatile(
-            /* [mm2,mm3] += D * src[1..8] */
-            "movq %1, %%mm1\n\t"
-            "movq %%mm1, %%mm0\n\t"
-            "movq %%mm1, %%mm4\n\t"
-            "punpcklbw %%mm7, %%mm0\n\t"
-            "punpckhbw %%mm7, %%mm4\n\t"
-            "pmullw %2, %%mm0\n\t"
-            "pmullw %2, %%mm4\n\t"
-            "paddw %%mm0, %%mm2\n\t"
-            "paddw %%mm4, %%mm3\n\t"
-            "movq %0, %%mm0\n\t"
-            : : "m" (src[0]), "m" (src[1]), "m" (DD));
-
-        __asm__ volatile(
-            /* dst[0..7] = ([mm2,mm3] + rnd) >> 6 */
-            "paddw %1, %%mm2\n\t"
-            "paddw %1, %%mm3\n\t"
-            "psrlw $6, %%mm2\n\t"
-            "psrlw $6, %%mm3\n\t"
-            "packuswb %%mm3, %%mm2\n\t"
-            H264_CHROMA_OP(%0, %%mm2)
-            "movq %%mm2, %0\n\t"
-            : "=m" (dst[0]) : "m" (*rnd_reg));
-        dst+= stride;
-    }
-}
-
-static void H264_CHROMA_MC4_TMPL(uint8_t *dst/*align 4*/, uint8_t *src/*align 1*/, int stride, int h, int x, int y, const uint64_t *rnd_reg)
-{
-    __asm__ volatile(
-        "pxor   %%mm7, %%mm7        \n\t"
-        "movd %5, %%mm2             \n\t"
-        "movd %6, %%mm3             \n\t"
-        "movq "MANGLE(ff_pw_8)", %%mm4\n\t"
-        "movq "MANGLE(ff_pw_8)", %%mm5\n\t"
-        "punpcklwd %%mm2, %%mm2     \n\t"
-        "punpcklwd %%mm3, %%mm3     \n\t"
-        "punpcklwd %%mm2, %%mm2     \n\t"
-        "punpcklwd %%mm3, %%mm3     \n\t"
-        "psubw %%mm2, %%mm4         \n\t"
-        "psubw %%mm3, %%mm5         \n\t"
-
-        "movd  (%1), %%mm0          \n\t"
-        "movd 1(%1), %%mm6          \n\t"
-        "add %3, %1                 \n\t"
-        "punpcklbw %%mm7, %%mm0     \n\t"
-        "punpcklbw %%mm7, %%mm6     \n\t"
-        "pmullw %%mm4, %%mm0        \n\t"
-        "pmullw %%mm2, %%mm6        \n\t"
-        "paddw %%mm0, %%mm6         \n\t"
-
-        "1:                         \n\t"
-        "movd  (%1), %%mm0          \n\t"
-        "movd 1(%1), %%mm1          \n\t"
-        "add %3, %1                 \n\t"
-        "punpcklbw %%mm7, %%mm0     \n\t"
-        "punpcklbw %%mm7, %%mm1     \n\t"
-        "pmullw %%mm4, %%mm0        \n\t"
-        "pmullw %%mm2, %%mm1        \n\t"
-        "paddw %%mm0, %%mm1         \n\t"
-        "movq %%mm1, %%mm0          \n\t"
-        "pmullw %%mm5, %%mm6        \n\t"
-        "pmullw %%mm3, %%mm1        \n\t"
-        "paddw %4, %%mm6            \n\t"
-        "paddw %%mm6, %%mm1         \n\t"
-        "psrlw $6, %%mm1            \n\t"
-        "packuswb %%mm1, %%mm1      \n\t"
-        H264_CHROMA_OP4((%0), %%mm1, %%mm6)
-        "movd %%mm1, (%0)           \n\t"
-        "add %3, %0                 \n\t"
-        "movd  (%1), %%mm6          \n\t"
-        "movd 1(%1), %%mm1          \n\t"
-        "add %3, %1                 \n\t"
-        "punpcklbw %%mm7, %%mm6     \n\t"
-        "punpcklbw %%mm7, %%mm1     \n\t"
-        "pmullw %%mm4, %%mm6        \n\t"
-        "pmullw %%mm2, %%mm1        \n\t"
-        "paddw %%mm6, %%mm1         \n\t"
-        "movq %%mm1, %%mm6          \n\t"
-        "pmullw %%mm5, %%mm0        \n\t"
-        "pmullw %%mm3, %%mm1        \n\t"
-        "paddw %4, %%mm0            \n\t"
-        "paddw %%mm0, %%mm1         \n\t"
-        "psrlw $6, %%mm1            \n\t"
-        "packuswb %%mm1, %%mm1      \n\t"
-        H264_CHROMA_OP4((%0), %%mm1, %%mm0)
-        "movd %%mm1, (%0)           \n\t"
-        "add %3, %0                 \n\t"
-        "sub $2, %2                 \n\t"
-        "jnz 1b                     \n\t"
-        : "+r"(dst), "+r"(src), "+r"(h)
-        : "r"((x86_reg)stride), "m"(*rnd_reg), "m"(x), "m"(y)
-    );
-}
-
-#ifdef H264_CHROMA_MC2_TMPL
-static void H264_CHROMA_MC2_TMPL(uint8_t *dst/*align 2*/, uint8_t *src/*align 1*/, int stride, int h, int x, int y)
-{
-    int tmp = ((1<<16)-1)*x + 8;
-    int CD= tmp*y;
-    int AB= (tmp<<3) - CD;
-    __asm__ volatile(
-        /* mm5 = {A,B,A,B} */
-        /* mm6 = {C,D,C,D} */
-        "movd %0, %%mm5\n\t"
-        "movd %1, %%mm6\n\t"
-        "punpckldq %%mm5, %%mm5\n\t"
-        "punpckldq %%mm6, %%mm6\n\t"
-        "pxor %%mm7, %%mm7\n\t"
-        /* mm0 = src[0,1,1,2] */
-        "movd %2, %%mm2\n\t"
-        "punpcklbw %%mm7, %%mm2\n\t"
-        "pshufw $0x94, %%mm2, %%mm2\n\t"
-        :: "r"(AB), "r"(CD), "m"(src[0]));
-
-
-    __asm__ volatile(
-        "1:\n\t"
-        "add %4, %1\n\t"
-        /* mm1 = A * src[0,1] + B * src[1,2] */
-        "movq    %%mm2, %%mm1\n\t"
-        "pmaddwd %%mm5, %%mm1\n\t"
-        /* mm0 = src[0,1,1,2] */
-        "movd (%1), %%mm0\n\t"
-        "punpcklbw %%mm7, %%mm0\n\t"
-        "pshufw $0x94, %%mm0, %%mm0\n\t"
-        /* mm1 += C * src[0,1] + D * src[1,2] */
-        "movq    %%mm0, %%mm2\n\t"
-        "pmaddwd %%mm6, %%mm0\n\t"
-        "paddw      %3, %%mm1\n\t"
-        "paddw   %%mm0, %%mm1\n\t"
-        /* dst[0,1] = pack((mm1 + 32) >> 6) */
-        "psrlw $6, %%mm1\n\t"
-        "packssdw %%mm7, %%mm1\n\t"
-        "packuswb %%mm7, %%mm1\n\t"
-        H264_CHROMA_OP4((%0), %%mm1, %%mm3)
-        "movd %%mm1, %%esi\n\t"
-        "movw %%si, (%0)\n\t"
-        "add %4, %0\n\t"
-        "sub $1, %2\n\t"
-        "jnz 1b\n\t"
-        : "+r" (dst), "+r"(src), "+r"(h)
-        : "m" (ff_pw_32), "r"((x86_reg)stride)
-        : "%esi");
-
-}
-#endif
-
diff --git a/libavcodec/x86/dsputil_h264_template_ssse3.c b/libavcodec/x86/dsputil_h264_template_ssse3.c
deleted file mode 100644
index e29e05e..0000000
--- a/libavcodec/x86/dsputil_h264_template_ssse3.c
+++ /dev/null
@@ -1,208 +0,0 @@
-/*
- * Copyright (c) 2008 Loren Merritt
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-/**
- * SSSE3 optimized version of (put|avg)_h264_chroma_mc8.
- * H264_CHROMA_MC8_TMPL must be defined to the desired function name
- * H264_CHROMA_MC8_MV0 must be defined to a (put|avg)_pixels8 function
- * AVG_OP must be defined to empty for put and the identify for avg
- */
-static void H264_CHROMA_MC8_TMPL(uint8_t *dst/*align 8*/, uint8_t *src/*align 1*/, int stride, int h, int x, int y, int rnd)
-{
-    if(y==0 && x==0) {
-        /* no filter needed */
-        H264_CHROMA_MC8_MV0(dst, src, stride, h);
-        return;
-    }
-
-    assert(x<8 && y<8 && x>=0 && y>=0);
-
-    if(y==0 || x==0)
-    {
-        /* 1 dimensional filter only */
-        __asm__ volatile(
-            "movd %0, %%xmm7 \n\t"
-            "movq %1, %%xmm6 \n\t"
-            "pshuflw $0, %%xmm7, %%xmm7 \n\t"
-            "movlhps %%xmm6, %%xmm6 \n\t"
-            "movlhps %%xmm7, %%xmm7 \n\t"
-            :: "r"(255*(x+y)+8), "m"(*(rnd?&ff_pw_4:&ff_pw_3))
-        );
-
-        if(x) {
-            __asm__ volatile(
-                "1: \n\t"
-                "movq (%1), %%xmm0 \n\t"
-                "movq 1(%1), %%xmm1 \n\t"
-                "movq (%1,%3), %%xmm2 \n\t"
-                "movq 1(%1,%3), %%xmm3 \n\t"
-                "punpcklbw %%xmm1, %%xmm0 \n\t"
-                "punpcklbw %%xmm3, %%xmm2 \n\t"
-                "pmaddubsw %%xmm7, %%xmm0 \n\t"
-                "pmaddubsw %%xmm7, %%xmm2 \n\t"
-         AVG_OP("movq (%0), %%xmm4 \n\t")
-         AVG_OP("movhps (%0,%3), %%xmm4 \n\t")
-                "paddw %%xmm6, %%xmm0 \n\t"
-                "paddw %%xmm6, %%xmm2 \n\t"
-                "psrlw $3, %%xmm0 \n\t"
-                "psrlw $3, %%xmm2 \n\t"
-                "packuswb %%xmm2, %%xmm0 \n\t"
-         AVG_OP("pavgb %%xmm4, %%xmm0 \n\t")
-                "movq %%xmm0, (%0) \n\t"
-                "movhps %%xmm0, (%0,%3) \n\t"
-                "sub $2, %2 \n\t"
-                "lea (%1,%3,2), %1 \n\t"
-                "lea (%0,%3,2), %0 \n\t"
-                "jg 1b \n\t"
-                :"+r"(dst), "+r"(src), "+r"(h)
-                :"r"((x86_reg)stride)
-            );
-        } else {
-            __asm__ volatile(
-                "1: \n\t"
-                "movq (%1), %%xmm0 \n\t"
-                "movq (%1,%3), %%xmm1 \n\t"
-                "movdqa %%xmm1, %%xmm2 \n\t"
-                "movq (%1,%3,2), %%xmm3 \n\t"
-                "punpcklbw %%xmm1, %%xmm0 \n\t"
-                "punpcklbw %%xmm3, %%xmm2 \n\t"
-                "pmaddubsw %%xmm7, %%xmm0 \n\t"
-                "pmaddubsw %%xmm7, %%xmm2 \n\t"
-         AVG_OP("movq (%0), %%xmm4 \n\t")
-         AVG_OP("movhps (%0,%3), %%xmm4 \n\t")
-                "paddw %%xmm6, %%xmm0 \n\t"
-                "paddw %%xmm6, %%xmm2 \n\t"
-                "psrlw $3, %%xmm0 \n\t"
-                "psrlw $3, %%xmm2 \n\t"
-                "packuswb %%xmm2, %%xmm0 \n\t"
-         AVG_OP("pavgb %%xmm4, %%xmm0 \n\t")
-                "movq %%xmm0, (%0) \n\t"
-                "movhps %%xmm0, (%0,%3) \n\t"
-                "sub $2, %2 \n\t"
-                "lea (%1,%3,2), %1 \n\t"
-                "lea (%0,%3,2), %0 \n\t"
-                "jg 1b \n\t"
-                :"+r"(dst), "+r"(src), "+r"(h)
-                :"r"((x86_reg)stride)
-            );
-        }
-        return;
-    }
-
-    /* general case, bilinear */
-    __asm__ volatile(
-        "movd %0, %%xmm7 \n\t"
-        "movd %1, %%xmm6 \n\t"
-        "movdqa %2, %%xmm5 \n\t"
-        "pshuflw $0, %%xmm7, %%xmm7 \n\t"
-        "pshuflw $0, %%xmm6, %%xmm6 \n\t"
-        "movlhps %%xmm7, %%xmm7 \n\t"
-        "movlhps %%xmm6, %%xmm6 \n\t"
-        :: "r"((x*255+8)*(8-y)), "r"((x*255+8)*y), "m"(*(rnd?&ff_pw_32:&ff_pw_28))
-    );
-
-    __asm__ volatile(
-        "movq (%1), %%xmm0 \n\t"
-        "movq 1(%1), %%xmm1 \n\t"
-        "punpcklbw %%xmm1, %%xmm0 \n\t"
-        "add %3, %1 \n\t"
-        "1: \n\t"
-        "movq (%1), %%xmm1 \n\t"
-        "movq 1(%1), %%xmm2 \n\t"
-        "movq (%1,%3), %%xmm3 \n\t"
-        "movq 1(%1,%3), %%xmm4 \n\t"
-        "lea (%1,%3,2), %1 \n\t"
-        "punpcklbw %%xmm2, %%xmm1 \n\t"
-        "punpcklbw %%xmm4, %%xmm3 \n\t"
-        "movdqa %%xmm1, %%xmm2 \n\t"
-        "movdqa %%xmm3, %%xmm4 \n\t"
-        "pmaddubsw %%xmm7, %%xmm0 \n\t"
-        "pmaddubsw %%xmm6, %%xmm1 \n\t"
-        "pmaddubsw %%xmm7, %%xmm2 \n\t"
-        "pmaddubsw %%xmm6, %%xmm3 \n\t"
-        "paddw %%xmm5, %%xmm0 \n\t"
-        "paddw %%xmm5, %%xmm2 \n\t"
-        "paddw %%xmm0, %%xmm1 \n\t"
-        "paddw %%xmm2, %%xmm3 \n\t"
-        "movdqa %%xmm4, %%xmm0 \n\t"
-        "psrlw $6, %%xmm1 \n\t"
-        "psrlw $6, %%xmm3 \n\t"
- AVG_OP("movq (%0), %%xmm2 \n\t")
- AVG_OP("movhps (%0,%3), %%xmm2 \n\t")
-        "packuswb %%xmm3, %%xmm1 \n\t"
- AVG_OP("pavgb %%xmm2, %%xmm1 \n\t")
-        "movq %%xmm1, (%0)\n\t"
-        "movhps %%xmm1, (%0,%3)\n\t"
-        "sub $2, %2 \n\t"
-        "lea (%0,%3,2), %0 \n\t"
-        "jg 1b \n\t"
-        :"+r"(dst), "+r"(src), "+r"(h)
-        :"r"((x86_reg)stride)
-    );
-}
-
-static void H264_CHROMA_MC4_TMPL(uint8_t *dst/*align 4*/, uint8_t *src/*align 1*/, int stride, int h, int x, int y)
-{
-    __asm__ volatile(
-        "movd %0, %%mm7 \n\t"
-        "movd %1, %%mm6 \n\t"
-        "movq %2, %%mm5 \n\t"
-        "pshufw $0, %%mm7, %%mm7 \n\t"
-        "pshufw $0, %%mm6, %%mm6 \n\t"
-        :: "r"((x*255+8)*(8-y)), "r"((x*255+8)*y), "m"(ff_pw_32)
-    );
-
-    __asm__ volatile(
-        "movd (%1), %%mm0 \n\t"
-        "punpcklbw 1(%1), %%mm0 \n\t"
-        "add %3, %1 \n\t"
-        "1: \n\t"
-        "movd (%1), %%mm1 \n\t"
-        "movd (%1,%3), %%mm3 \n\t"
-        "punpcklbw 1(%1), %%mm1 \n\t"
-        "punpcklbw 1(%1,%3), %%mm3 \n\t"
-        "lea (%1,%3,2), %1 \n\t"
-        "movq %%mm1, %%mm2 \n\t"
-        "movq %%mm3, %%mm4 \n\t"
-        "pmaddubsw %%mm7, %%mm0 \n\t"
-        "pmaddubsw %%mm6, %%mm1 \n\t"
-        "pmaddubsw %%mm7, %%mm2 \n\t"
-        "pmaddubsw %%mm6, %%mm3 \n\t"
-        "paddw %%mm5, %%mm0 \n\t"
-        "paddw %%mm5, %%mm2 \n\t"
-        "paddw %%mm0, %%mm1 \n\t"
-        "paddw %%mm2, %%mm3 \n\t"
-        "movq %%mm4, %%mm0 \n\t"
-        "psrlw $6, %%mm1 \n\t"
-        "psrlw $6, %%mm3 \n\t"
-        "packuswb %%mm1, %%mm1 \n\t"
-        "packuswb %%mm3, %%mm3 \n\t"
- AVG_OP("pavgb (%0), %%mm1 \n\t")
- AVG_OP("pavgb (%0,%3), %%mm3 \n\t")
-        "movd %%mm1, (%0)\n\t"
-        "movd %%mm3, (%0,%3)\n\t"
-        "sub $2, %2 \n\t"
-        "lea (%0,%3,2), %0 \n\t"
-        "jg 1b \n\t"
-        :"+r"(dst), "+r"(src), "+r"(h)
-        :"r"((x86_reg)stride)
-    );
-}
-
diff --git a/libavcodec/x86/dsputil_mmx.c b/libavcodec/x86/dsputil_mmx.c
index cc2f881..f98e6ae 100644
--- a/libavcodec/x86/dsputil_mmx.c
+++ b/libavcodec/x86/dsputil_mmx.c
@@ -3,42 +3,38 @@
  * Copyright (c) 2000, 2001 Fabrice Bellard
  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  *
  * MMX optimization by Nick Kurshev <nickols_k at mail.ru>
  */
 
+#include "libavutil/cpu.h"
 #include "libavutil/x86_cpu.h"
 #include "libavcodec/dsputil.h"
 #include "libavcodec/h264dsp.h"
 #include "libavcodec/mpegvideo.h"
 #include "libavcodec/simple_idct.h"
+#include "libavcodec/ac3dec.h"
 #include "dsputil_mmx.h"
-#include "vp3dsp_mmx.h"
-#include "vp3dsp_sse2.h"
-#include "vp6dsp_mmx.h"
-#include "vp6dsp_sse2.h"
 #include "idct_xvid.h"
 
 //#undef NDEBUG
 //#include <assert.h>
 
-int mm_flags; /* multimedia extension flags */
-
 /* pixel operations */
 DECLARE_ALIGNED(8,  const uint64_t, ff_bone) = 0x0101010101010101ULL;
 DECLARE_ALIGNED(8,  const uint64_t, ff_wtwo) = 0x0002000200020002ULL;
@@ -46,34 +42,46 @@ DECLARE_ALIGNED(8,  const uint64_t, ff_wtwo) = 0x0002000200020002ULL;
 DECLARE_ALIGNED(16, const uint64_t, ff_pdw_80000000)[2] =
 {0x8000000080000000ULL, 0x8000000080000000ULL};
 
-DECLARE_ALIGNED(8,  const uint64_t, ff_pw_3  ) = 0x0003000300030003ULL;
-DECLARE_ALIGNED(8,  const uint64_t, ff_pw_4  ) = 0x0004000400040004ULL;
+DECLARE_ALIGNED(8,  const uint64_t, ff_pw_1  ) = 0x0001000100010001ULL;
+DECLARE_ALIGNED(16, const xmm_reg,  ff_pw_3  ) = {0x0003000300030003ULL, 0x0003000300030003ULL};
+DECLARE_ALIGNED(16, const xmm_reg,  ff_pw_4  ) = {0x0004000400040004ULL, 0x0004000400040004ULL};
 DECLARE_ALIGNED(16, const xmm_reg,  ff_pw_5  ) = {0x0005000500050005ULL, 0x0005000500050005ULL};
 DECLARE_ALIGNED(16, const xmm_reg,  ff_pw_8  ) = {0x0008000800080008ULL, 0x0008000800080008ULL};
+DECLARE_ALIGNED(16, const xmm_reg,  ff_pw_9  ) = {0x0009000900090009ULL, 0x0009000900090009ULL};
 DECLARE_ALIGNED(8,  const uint64_t, ff_pw_15 ) = 0x000F000F000F000FULL;
 DECLARE_ALIGNED(16, const xmm_reg,  ff_pw_16 ) = {0x0010001000100010ULL, 0x0010001000100010ULL};
+DECLARE_ALIGNED(16, const xmm_reg,  ff_pw_17 ) = {0x0011001100110011ULL, 0x0011001100110011ULL};
+DECLARE_ALIGNED(16, const xmm_reg,  ff_pw_18 ) = {0x0012001200120012ULL, 0x0012001200120012ULL};
 DECLARE_ALIGNED(8,  const uint64_t, ff_pw_20 ) = 0x0014001400140014ULL;
+DECLARE_ALIGNED(16, const xmm_reg,  ff_pw_27 ) = {0x001B001B001B001BULL, 0x001B001B001B001BULL};
 DECLARE_ALIGNED(16, const xmm_reg,  ff_pw_28 ) = {0x001C001C001C001CULL, 0x001C001C001C001CULL};
 DECLARE_ALIGNED(16, const xmm_reg,  ff_pw_32 ) = {0x0020002000200020ULL, 0x0020002000200020ULL};
 DECLARE_ALIGNED(8,  const uint64_t, ff_pw_42 ) = 0x002A002A002A002AULL;
+DECLARE_ALIGNED(8,  const uint64_t, ff_pw_53 ) = 0x0035003500350035ULL;
+DECLARE_ALIGNED(16, const xmm_reg,  ff_pw_63 ) = {0x003F003F003F003FULL, 0x003F003F003F003FULL};
 DECLARE_ALIGNED(16, const xmm_reg,  ff_pw_64 ) = {0x0040004000400040ULL, 0x0040004000400040ULL};
 DECLARE_ALIGNED(8,  const uint64_t, ff_pw_96 ) = 0x0060006000600060ULL;
 DECLARE_ALIGNED(8,  const uint64_t, ff_pw_128) = 0x0080008000800080ULL;
 DECLARE_ALIGNED(8,  const uint64_t, ff_pw_255) = 0x00ff00ff00ff00ffULL;
 
-DECLARE_ALIGNED(8,  const uint64_t, ff_pb_1  ) = 0x0101010101010101ULL;
-DECLARE_ALIGNED(8,  const uint64_t, ff_pb_3  ) = 0x0303030303030303ULL;
+DECLARE_ALIGNED(16, const xmm_reg,  ff_pb_0  ) = {0x0000000000000000ULL, 0x0000000000000000ULL};
+DECLARE_ALIGNED(16, const xmm_reg,  ff_pb_1  ) = {0x0101010101010101ULL, 0x0101010101010101ULL};
+DECLARE_ALIGNED(16, const xmm_reg,  ff_pb_3  ) = {0x0303030303030303ULL, 0x0303030303030303ULL};
+DECLARE_ALIGNED(16, const xmm_reg,  ff_pb_4  ) = {0x0404040404040404ULL, 0x0404040404040404ULL};
 DECLARE_ALIGNED(8,  const uint64_t, ff_pb_7  ) = 0x0707070707070707ULL;
 DECLARE_ALIGNED(8,  const uint64_t, ff_pb_1F ) = 0x1F1F1F1F1F1F1F1FULL;
 DECLARE_ALIGNED(8,  const uint64_t, ff_pb_3F ) = 0x3F3F3F3F3F3F3F3FULL;
+DECLARE_ALIGNED(16, const xmm_reg,  ff_pb_80 ) = {0x8080808080808080ULL, 0x8080808080808080ULL};
 DECLARE_ALIGNED(8,  const uint64_t, ff_pb_81 ) = 0x8181818181818181ULL;
-DECLARE_ALIGNED(8,  const uint64_t, ff_pb_A1 ) = 0xA1A1A1A1A1A1A1A1ULL;
+DECLARE_ALIGNED(16, const xmm_reg,  ff_pb_A1 ) = {0xA1A1A1A1A1A1A1A1ULL, 0xA1A1A1A1A1A1A1A1ULL};
+DECLARE_ALIGNED(16, const xmm_reg,  ff_pb_F8 ) = {0xF8F8F8F8F8F8F8F8ULL, 0xF8F8F8F8F8F8F8F8ULL};
 DECLARE_ALIGNED(8,  const uint64_t, ff_pb_FC ) = 0xFCFCFCFCFCFCFCFCULL;
+DECLARE_ALIGNED(16, const xmm_reg,  ff_pb_FE ) = {0xFEFEFEFEFEFEFEFEULL, 0xFEFEFEFEFEFEFEFEULL};
 
 DECLARE_ALIGNED(16, const double, ff_pd_1)[2] = { 1.0, 1.0 };
 DECLARE_ALIGNED(16, const double, ff_pd_2)[2] = { 2.0, 2.0 };
 
-#define JUMPALIGN() __asm__ volatile (ASMALIGN(3)::)
+#define JUMPALIGN() __asm__ volatile (".p2align 3"::)
 #define MOVQ_ZERO(regd)  __asm__ volatile ("pxor %%" #regd ", %%" #regd ::)
 
 #define MOVQ_BFE(regd) \
@@ -223,7 +231,7 @@ DECLARE_ALIGNED(16, const double, ff_pd_2)[2] = { 2.0, 2.0 };
 /***********************************/
 /* standard MMX */
 
-void put_pixels_clamped_mmx(const DCTELEM *block, uint8_t *pixels, int line_size)
+void ff_put_pixels_clamped_mmx(const DCTELEM *block, uint8_t *pixels, int line_size)
 {
     const DCTELEM *p;
     uint8_t *pix;
@@ -278,9 +286,6 @@ void put_pixels_clamped_mmx(const DCTELEM *block, uint8_t *pixels, int line_size
             :"memory");
 }
 
-DECLARE_ASM_CONST(8, uint8_t, ff_vector128)[8] =
-  { 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80 };
-
 #define put_signed_pixels_clamped_mmx_half(off) \
             "movq    "#off"(%2), %%mm1          \n\t"\
             "movq 16+"#off"(%2), %%mm2          \n\t"\
@@ -299,13 +304,13 @@ DECLARE_ASM_CONST(8, uint8_t, ff_vector128)[8] =
             "movq %%mm3, (%0, %3, 2)            \n\t"\
             "movq %%mm4, (%0, %1)               \n\t"
 
-void put_signed_pixels_clamped_mmx(const DCTELEM *block, uint8_t *pixels, int line_size)
+void ff_put_signed_pixels_clamped_mmx(const DCTELEM *block, uint8_t *pixels, int line_size)
 {
     x86_reg line_skip = line_size;
     x86_reg line_skip3;
 
     __asm__ volatile (
-            "movq "MANGLE(ff_vector128)", %%mm0 \n\t"
+            "movq "MANGLE(ff_pb_80)", %%mm0 \n\t"
             "lea (%3, %3, 2), %1                \n\t"
             put_signed_pixels_clamped_mmx_half(0)
             "lea (%0, %3, 4), %0                \n\t"
@@ -315,7 +320,7 @@ void put_signed_pixels_clamped_mmx(const DCTELEM *block, uint8_t *pixels, int li
             :"memory");
 }
 
-void add_pixels_clamped_mmx(const DCTELEM *block, uint8_t *pixels, int line_size)
+void ff_add_pixels_clamped_mmx(const DCTELEM *block, uint8_t *pixels, int line_size)
 {
     const DCTELEM *p;
     uint8_t *pix;
@@ -360,7 +365,7 @@ static void put_pixels4_mmx(uint8_t *block, const uint8_t *pixels, int line_size
 {
     __asm__ volatile(
          "lea (%3, %3), %%"REG_a"       \n\t"
-         ASMALIGN(3)
+         ".p2align 3                    \n\t"
          "1:                            \n\t"
          "movd (%1), %%mm0              \n\t"
          "movd (%1, %3), %%mm1          \n\t"
@@ -386,7 +391,7 @@ static void put_pixels8_mmx(uint8_t *block, const uint8_t *pixels, int line_size
 {
     __asm__ volatile(
          "lea (%3, %3), %%"REG_a"       \n\t"
-         ASMALIGN(3)
+         ".p2align 3                    \n\t"
          "1:                            \n\t"
          "movq (%1), %%mm0              \n\t"
          "movq (%1, %3), %%mm1          \n\t"
@@ -412,7 +417,7 @@ static void put_pixels16_mmx(uint8_t *block, const uint8_t *pixels, int line_siz
 {
     __asm__ volatile(
          "lea (%3, %3), %%"REG_a"       \n\t"
-         ASMALIGN(3)
+         ".p2align 3                    \n\t"
          "1:                            \n\t"
          "movq (%1), %%mm0              \n\t"
          "movq 8(%1), %%mm4             \n\t"
@@ -606,7 +611,7 @@ static void add_hfyu_median_prediction_cmov(uint8_t *dst, const uint8_t *top, co
     __asm__ volatile(
         "mov    %7, %3 \n"
         "1: \n"
-        "movzx (%3,%4), %2 \n"
+        "movzbl (%3,%4), %2 \n"
         "mov    %2, %k3 \n"
         "sub   %b1, %b3 \n"
         "add   %b0, %b3 \n"
@@ -723,35 +728,6 @@ static void h263_v_loop_filter_mmx(uint8_t *src, int stride, int qscale){
     }
 }
 
-static inline void transpose4x4(uint8_t *dst, uint8_t *src, int dst_stride, int src_stride){
-    __asm__ volatile( //FIXME could save 1 instruction if done as 8x4 ...
-        "movd  %4, %%mm0                \n\t"
-        "movd  %5, %%mm1                \n\t"
-        "movd  %6, %%mm2                \n\t"
-        "movd  %7, %%mm3                \n\t"
-        "punpcklbw %%mm1, %%mm0         \n\t"
-        "punpcklbw %%mm3, %%mm2         \n\t"
-        "movq %%mm0, %%mm1              \n\t"
-        "punpcklwd %%mm2, %%mm0         \n\t"
-        "punpckhwd %%mm2, %%mm1         \n\t"
-        "movd  %%mm0, %0                \n\t"
-        "punpckhdq %%mm0, %%mm0         \n\t"
-        "movd  %%mm0, %1                \n\t"
-        "movd  %%mm1, %2                \n\t"
-        "punpckhdq %%mm1, %%mm1         \n\t"
-        "movd  %%mm1, %3                \n\t"
-
-        : "=m" (*(uint32_t*)(dst + 0*dst_stride)),
-          "=m" (*(uint32_t*)(dst + 1*dst_stride)),
-          "=m" (*(uint32_t*)(dst + 2*dst_stride)),
-          "=m" (*(uint32_t*)(dst + 3*dst_stride))
-        :  "m" (*(uint32_t*)(src + 0*src_stride)),
-           "m" (*(uint32_t*)(src + 1*src_stride)),
-           "m" (*(uint32_t*)(src + 2*src_stride)),
-           "m" (*(uint32_t*)(src + 3*src_stride))
-    );
-}
-
 static void h263_h_loop_filter_mmx(uint8_t *src, int stride, int qscale){
     if(CONFIG_H263_DECODER || CONFIG_H263_ENCODER) {
     const int strength= ff_h263_loop_filter_strength[qscale];
@@ -807,7 +783,7 @@ static void h263_h_loop_filter_mmx(uint8_t *src, int stride, int qscale){
 
 /* draw the edges of width 'w' of an image of size width, height
    this mmx version can only handle w==8 || w==16 */
-static void draw_edges_mmx(uint8_t *buf, int wrap, int width, int height, int w)
+static void draw_edges_mmx(uint8_t *buf, int wrap, int width, int height, int w, int sides)
 {
     uint8_t *ptr, *last_line;
     int i;
@@ -860,36 +836,43 @@ static void draw_edges_mmx(uint8_t *buf, int wrap, int width, int height, int w)
         );
     }
 
-    for(i=0;i<w;i+=4) {
-        /* top and bottom (and hopefully also the corners) */
-        ptr= buf - (i + 1) * wrap - w;
-        __asm__ volatile(
-                "1:                             \n\t"
-                "movq (%1, %0), %%mm0           \n\t"
-                "movq %%mm0, (%0)               \n\t"
-                "movq %%mm0, (%0, %2)           \n\t"
-                "movq %%mm0, (%0, %2, 2)        \n\t"
-                "movq %%mm0, (%0, %3)           \n\t"
-                "add $8, %0                     \n\t"
-                "cmp %4, %0                     \n\t"
-                " jb 1b                         \n\t"
-                : "+r" (ptr)
-                : "r" ((x86_reg)buf - (x86_reg)ptr - w), "r" ((x86_reg)-wrap), "r" ((x86_reg)-wrap*3), "r" (ptr+width+2*w)
-        );
-        ptr= last_line + (i + 1) * wrap - w;
-        __asm__ volatile(
-                "1:                             \n\t"
-                "movq (%1, %0), %%mm0           \n\t"
-                "movq %%mm0, (%0)               \n\t"
-                "movq %%mm0, (%0, %2)           \n\t"
-                "movq %%mm0, (%0, %2, 2)        \n\t"
-                "movq %%mm0, (%0, %3)           \n\t"
-                "add $8, %0                     \n\t"
-                "cmp %4, %0                     \n\t"
-                " jb 1b                         \n\t"
-                : "+r" (ptr)
-                : "r" ((x86_reg)last_line - (x86_reg)ptr - w), "r" ((x86_reg)wrap), "r" ((x86_reg)wrap*3), "r" (ptr+width+2*w)
-        );
+    /* top and bottom (and hopefully also the corners) */
+    if (sides&EDGE_TOP) {
+        for(i = 0; i < w; i += 4) {
+            ptr= buf - (i + 1) * wrap - w;
+            __asm__ volatile(
+                    "1:                             \n\t"
+                    "movq (%1, %0), %%mm0           \n\t"
+                    "movq %%mm0, (%0)               \n\t"
+                    "movq %%mm0, (%0, %2)           \n\t"
+                    "movq %%mm0, (%0, %2, 2)        \n\t"
+                    "movq %%mm0, (%0, %3)           \n\t"
+                    "add $8, %0                     \n\t"
+                    "cmp %4, %0                     \n\t"
+                    " jb 1b                         \n\t"
+                    : "+r" (ptr)
+                    : "r" ((x86_reg)buf - (x86_reg)ptr - w), "r" ((x86_reg)-wrap), "r" ((x86_reg)-wrap*3), "r" (ptr+width+2*w)
+            );
+        }
+    }
+
+    if (sides&EDGE_BOTTOM) {
+        for(i = 0; i < w; i += 4) {
+            ptr= last_line + (i + 1) * wrap - w;
+            __asm__ volatile(
+                    "1:                             \n\t"
+                    "movq (%1, %0), %%mm0           \n\t"
+                    "movq %%mm0, (%0)               \n\t"
+                    "movq %%mm0, (%0, %2)           \n\t"
+                    "movq %%mm0, (%0, %2, 2)        \n\t"
+                    "movq %%mm0, (%0, %3)           \n\t"
+                    "add $8, %0                     \n\t"
+                    "cmp %4, %0                     \n\t"
+                    " jb 1b                         \n\t"
+                    : "+r" (ptr)
+                    : "r" ((x86_reg)last_line - (x86_reg)ptr - w), "r" ((x86_reg)wrap), "r" ((x86_reg)wrap*3), "r" (ptr+width+2*w)
+            );
+        }
     }
 }
 
@@ -1685,8 +1668,80 @@ QPEL_2TAP(avg_,  8, 3dnow)
 static void just_return(void) { return; }
 #endif
 
-static void gmc_mmx(uint8_t *dst, uint8_t *src, int stride, int h, int ox, int oy,
-                    int dxx, int dxy, int dyx, int dyy, int shift, int r, int width, int height){
+#if HAVE_YASM
+typedef void emu_edge_core_func (uint8_t *buf, const uint8_t *src,
+                                 x86_reg linesize, x86_reg start_y,
+                                 x86_reg end_y, x86_reg block_h,
+                                 x86_reg start_x, x86_reg end_x,
+                                 x86_reg block_w);
+extern emu_edge_core_func ff_emu_edge_core_mmx;
+extern emu_edge_core_func ff_emu_edge_core_sse;
+
+static av_always_inline
+void emulated_edge_mc(uint8_t *buf, const uint8_t *src, int linesize,
+                      int block_w, int block_h,
+                      int src_x, int src_y, int w, int h,
+                      emu_edge_core_func *core_fn)
+{
+    int start_y, start_x, end_y, end_x, src_y_add=0;
+
+    if(src_y>= h){
+        src_y_add = h-1-src_y;
+        src_y=h-1;
+    }else if(src_y<=-block_h){
+        src_y_add = 1-block_h-src_y;
+        src_y=1-block_h;
+    }
+    if(src_x>= w){
+        src+= (w-1-src_x);
+        src_x=w-1;
+    }else if(src_x<=-block_w){
+        src+= (1-block_w-src_x);
+        src_x=1-block_w;
+    }
+
+    start_y= FFMAX(0, -src_y);
+    start_x= FFMAX(0, -src_x);
+    end_y= FFMIN(block_h, h-src_y);
+    end_x= FFMIN(block_w, w-src_x);
+    assert(start_x < end_x && block_w > 0);
+    assert(start_y < end_y && block_h > 0);
+
+    // fill in the to-be-copied part plus all above/below
+    src += (src_y_add+start_y)*linesize + start_x;
+    buf += start_x;
+    core_fn(buf, src, linesize, start_y, end_y, block_h, start_x, end_x, block_w);
+}
+
+#if ARCH_X86_32
+static av_noinline
+void emulated_edge_mc_mmx(uint8_t *buf, const uint8_t *src, int linesize,
+                          int block_w, int block_h,
+                          int src_x, int src_y, int w, int h)
+{
+    emulated_edge_mc(buf, src, linesize, block_w, block_h, src_x, src_y,
+                     w, h, &ff_emu_edge_core_mmx);
+}
+#endif
+static av_noinline
+void emulated_edge_mc_sse(uint8_t *buf, const uint8_t *src, int linesize,
+                          int block_w, int block_h,
+                          int src_x, int src_y, int w, int h)
+{
+    emulated_edge_mc(buf, src, linesize, block_w, block_h, src_x, src_y,
+                     w, h, &ff_emu_edge_core_sse);
+}
+#endif /* HAVE_YASM */
+
+typedef void emulated_edge_mc_func (uint8_t *dst, const uint8_t *src,
+                                    int linesize, int block_w, int block_h,
+                                    int src_x, int src_y, int w, int h);
+
+static av_always_inline
+void gmc(uint8_t *dst, uint8_t *src, int stride, int h, int ox, int oy,
+         int dxx, int dxy, int dyx, int dyy, int shift, int r, int width, int height,
+         emulated_edge_mc_func *emu_edge_fn)
+{
     const int w = 8;
     const int ix = ox>>(16+shift);
     const int iy = oy>>(16+shift);
@@ -1722,7 +1777,7 @@ static void gmc_mmx(uint8_t *dst, uint8_t *src, int stride, int h, int ox, int o
     if( (unsigned)ix >= width-w ||
         (unsigned)iy >= height-h )
     {
-        ff_emulated_edge_mc(edge_buf, src, stride, w+1, h+1, ix, iy, width, height);
+        emu_edge_fn(edge_buf, src, stride, w+1, h+1, ix, iy, width, height);
         src = edge_buf;
     }
 
@@ -1803,6 +1858,30 @@ static void gmc_mmx(uint8_t *dst, uint8_t *src, int stride, int h, int ox, int o
     }
 }
 
+#if HAVE_YASM
+#if ARCH_X86_32
+static void gmc_mmx(uint8_t *dst, uint8_t *src, int stride, int h, int ox, int oy,
+                    int dxx, int dxy, int dyx, int dyy, int shift, int r, int width, int height)
+{
+    gmc(dst, src, stride, h, ox, oy, dxx, dxy, dyx, dyy, shift, r,
+        width, height, &emulated_edge_mc_mmx);
+}
+#endif
+static void gmc_sse(uint8_t *dst, uint8_t *src, int stride, int h, int ox, int oy,
+                    int dxx, int dxy, int dyx, int dyy, int shift, int r, int width, int height)
+{
+    gmc(dst, src, stride, h, ox, oy, dxx, dxy, dyx, dyy, shift, r,
+        width, height, &emulated_edge_mc_sse);
+}
+#else
+static void gmc_mmx(uint8_t *dst, uint8_t *src, int stride, int h, int ox, int oy,
+                    int dxx, int dxy, int dyx, int dyy, int shift, int r, int width, int height)
+{
+    gmc(dst, src, stride, h, ox, oy, dxx, dxy, dyx, dyy, shift, r,
+        width, height, &ff_emulated_edge_mc);
+}
+#endif
+
 #define PREFETCH(name, op) \
 static void name(void *mem, int stride, int h){\
     const uint8_t *p= mem;\
@@ -1815,8 +1894,49 @@ PREFETCH(prefetch_mmx2,  prefetcht0)
 PREFETCH(prefetch_3dnow, prefetch)
 #undef PREFETCH
 
-#include "h264dsp_mmx.c"
-#include "rv40dsp_mmx.c"
+#include "h264_qpel_mmx.c"
+
+void ff_put_h264_chroma_mc8_mmx_rnd   (uint8_t *dst, uint8_t *src,
+                                       int stride, int h, int x, int y);
+void ff_put_rv40_chroma_mc8_mmx       (uint8_t *dst, uint8_t *src,
+                                       int stride, int h, int x, int y);
+void ff_avg_h264_chroma_mc8_mmx2_rnd  (uint8_t *dst, uint8_t *src,
+                                       int stride, int h, int x, int y);
+void ff_avg_rv40_chroma_mc8_mmx2      (uint8_t *dst, uint8_t *src,
+                                       int stride, int h, int x, int y);
+void ff_avg_h264_chroma_mc8_3dnow_rnd (uint8_t *dst, uint8_t *src,
+                                       int stride, int h, int x, int y);
+void ff_avg_rv40_chroma_mc8_3dnow     (uint8_t *dst, uint8_t *src,
+                                       int stride, int h, int x, int y);
+
+void ff_put_h264_chroma_mc4_mmx       (uint8_t *dst, uint8_t *src,
+                                       int stride, int h, int x, int y);
+void ff_put_rv40_chroma_mc4_mmx       (uint8_t *dst, uint8_t *src,
+                                       int stride, int h, int x, int y);
+void ff_avg_h264_chroma_mc4_mmx2      (uint8_t *dst, uint8_t *src,
+                                       int stride, int h, int x, int y);
+void ff_avg_rv40_chroma_mc4_mmx2      (uint8_t *dst, uint8_t *src,
+                                       int stride, int h, int x, int y);
+void ff_avg_h264_chroma_mc4_3dnow     (uint8_t *dst, uint8_t *src,
+                                       int stride, int h, int x, int y);
+void ff_avg_rv40_chroma_mc4_3dnow     (uint8_t *dst, uint8_t *src,
+                                       int stride, int h, int x, int y);
+
+void ff_put_h264_chroma_mc2_mmx2      (uint8_t *dst, uint8_t *src,
+                                       int stride, int h, int x, int y);
+void ff_avg_h264_chroma_mc2_mmx2      (uint8_t *dst, uint8_t *src,
+                                       int stride, int h, int x, int y);
+
+void ff_put_h264_chroma_mc8_ssse3_rnd (uint8_t *dst, uint8_t *src,
+                                       int stride, int h, int x, int y);
+void ff_put_h264_chroma_mc4_ssse3     (uint8_t *dst, uint8_t *src,
+                                       int stride, int h, int x, int y);
+
+void ff_avg_h264_chroma_mc8_ssse3_rnd (uint8_t *dst, uint8_t *src,
+                                       int stride, int h, int x, int y);
+void ff_avg_h264_chroma_mc4_ssse3     (uint8_t *dst, uint8_t *src,
+                                       int stride, int h, int x, int y);
+
 
 /* CAVS specific */
 void ff_put_cavs_qpel8_mc00_mmx2(uint8_t *dst, uint8_t *src, int stride) {
@@ -1846,43 +1966,43 @@ void ff_avg_vc1_mspel_mc00_mmx2(uint8_t *dst, const uint8_t *src, int stride, in
 static void ff_libmpeg2mmx_idct_put(uint8_t *dest, int line_size, DCTELEM *block)
 {
     ff_mmx_idct (block);
-    put_pixels_clamped_mmx(block, dest, line_size);
+    ff_put_pixels_clamped_mmx(block, dest, line_size);
 }
 static void ff_libmpeg2mmx_idct_add(uint8_t *dest, int line_size, DCTELEM *block)
 {
     ff_mmx_idct (block);
-    add_pixels_clamped_mmx(block, dest, line_size);
+    ff_add_pixels_clamped_mmx(block, dest, line_size);
 }
 static void ff_libmpeg2mmx2_idct_put(uint8_t *dest, int line_size, DCTELEM *block)
 {
     ff_mmxext_idct (block);
-    put_pixels_clamped_mmx(block, dest, line_size);
+    ff_put_pixels_clamped_mmx(block, dest, line_size);
 }
 static void ff_libmpeg2mmx2_idct_add(uint8_t *dest, int line_size, DCTELEM *block)
 {
     ff_mmxext_idct (block);
-    add_pixels_clamped_mmx(block, dest, line_size);
+    ff_add_pixels_clamped_mmx(block, dest, line_size);
 }
 #endif
 static void ff_idct_xvid_mmx_put(uint8_t *dest, int line_size, DCTELEM *block)
 {
     ff_idct_xvid_mmx (block);
-    put_pixels_clamped_mmx(block, dest, line_size);
+    ff_put_pixels_clamped_mmx(block, dest, line_size);
 }
 static void ff_idct_xvid_mmx_add(uint8_t *dest, int line_size, DCTELEM *block)
 {
     ff_idct_xvid_mmx (block);
-    add_pixels_clamped_mmx(block, dest, line_size);
+    ff_add_pixels_clamped_mmx(block, dest, line_size);
 }
 static void ff_idct_xvid_mmx2_put(uint8_t *dest, int line_size, DCTELEM *block)
 {
     ff_idct_xvid_mmx2 (block);
-    put_pixels_clamped_mmx(block, dest, line_size);
+    ff_put_pixels_clamped_mmx(block, dest, line_size);
 }
 static void ff_idct_xvid_mmx2_add(uint8_t *dest, int line_size, DCTELEM *block)
 {
     ff_idct_xvid_mmx2 (block);
-    add_pixels_clamped_mmx(block, dest, line_size);
+    ff_add_pixels_clamped_mmx(block, dest, line_size);
 }
 
 static void vorbis_inverse_coupling_3dnow(float *mag, float *ang, int blocksize)
@@ -1976,7 +2096,9 @@ static void vorbis_inverse_coupling_sse(float *mag, float *ang, int blocksize)
         "jl 1b \n"\
         :"+&r"(i)\
         :"r"(samples[0]+len), "r"(matrix)\
-        :"memory"\
+        :XMM_CLOBBERS("%xmm0", "%xmm1", "%xmm2", "%xmm3", \
+                      "%xmm4", "%xmm5", "%xmm6", "%xmm7",)\
+         "memory"\
     );
 
 #define MIX_MISC(stereo)\
@@ -1984,8 +2106,8 @@ static void vorbis_inverse_coupling_sse(float *mag, float *ang, int blocksize)
         "1: \n"\
         "movaps  (%3,%0), %%xmm0 \n"\
  stereo("movaps   %%xmm0, %%xmm1 \n")\
-        "mulps    %%xmm6, %%xmm0 \n"\
- stereo("mulps    %%xmm7, %%xmm1 \n")\
+        "mulps    %%xmm4, %%xmm0 \n"\
+ stereo("mulps    %%xmm5, %%xmm1 \n")\
         "lea 1024(%3,%0), %1 \n"\
         "mov %5, %2 \n"\
         "2: \n"\
@@ -2018,17 +2140,17 @@ static void ac3_downmix_sse(float (*samples)[256], float (*matrix)[2], int out_c
     } else if(in_ch == 5 && out_ch == 1 && matrix_cmp[0][0]==matrix_cmp[2][0] && matrix_cmp[3][0]==matrix_cmp[4][0]) {
         MIX5(IF1,IF0);
     } else {
-        DECLARE_ALIGNED(16, float, matrix_simd)[in_ch][2][4];
+        DECLARE_ALIGNED(16, float, matrix_simd)[AC3_MAX_CHANNELS][2][4];
         j = 2*in_ch*sizeof(float);
         __asm__ volatile(
             "1: \n"
             "sub $8, %0 \n"
-            "movss     (%2,%0), %%xmm6 \n"
-            "movss    4(%2,%0), %%xmm7 \n"
-            "shufps $0, %%xmm6, %%xmm6 \n"
-            "shufps $0, %%xmm7, %%xmm7 \n"
-            "movaps %%xmm6,   (%1,%0,4) \n"
-            "movaps %%xmm7, 16(%1,%0,4) \n"
+            "movss     (%2,%0), %%xmm4 \n"
+            "movss    4(%2,%0), %%xmm5 \n"
+            "shufps $0, %%xmm4, %%xmm4 \n"
+            "shufps $0, %%xmm5, %%xmm5 \n"
+            "movaps %%xmm4,   (%1,%0,4) \n"
+            "movaps %%xmm5, 16(%1,%0,4) \n"
             "jg 1b \n"
             :"+&r"(j)
             :"r"(matrix_simd), "r"(matrix)
@@ -2042,38 +2164,38 @@ static void ac3_downmix_sse(float (*samples)[256], float (*matrix)[2], int out_c
     }
 }
 
-static void vector_fmul_3dnow(float *dst, const float *src, int len){
+static void vector_fmul_3dnow(float *dst, const float *src0, const float *src1, int len){
     x86_reg i = (len-4)*4;
     __asm__ volatile(
         "1: \n\t"
-        "movq    (%1,%0), %%mm0 \n\t"
-        "movq   8(%1,%0), %%mm1 \n\t"
-        "pfmul   (%2,%0), %%mm0 \n\t"
-        "pfmul  8(%2,%0), %%mm1 \n\t"
+        "movq    (%2,%0), %%mm0 \n\t"
+        "movq   8(%2,%0), %%mm1 \n\t"
+        "pfmul   (%3,%0), %%mm0 \n\t"
+        "pfmul  8(%3,%0), %%mm1 \n\t"
         "movq   %%mm0,  (%1,%0) \n\t"
         "movq   %%mm1, 8(%1,%0) \n\t"
         "sub  $16, %0 \n\t"
         "jge 1b \n\t"
         "femms  \n\t"
         :"+r"(i)
-        :"r"(dst), "r"(src)
+        :"r"(dst), "r"(src0), "r"(src1)
         :"memory"
     );
 }
-static void vector_fmul_sse(float *dst, const float *src, int len){
+static void vector_fmul_sse(float *dst, const float *src0, const float *src1, int len){
     x86_reg i = (len-8)*4;
     __asm__ volatile(
         "1: \n\t"
-        "movaps    (%1,%0), %%xmm0 \n\t"
-        "movaps  16(%1,%0), %%xmm1 \n\t"
-        "mulps     (%2,%0), %%xmm0 \n\t"
-        "mulps   16(%2,%0), %%xmm1 \n\t"
+        "movaps    (%2,%0), %%xmm0 \n\t"
+        "movaps  16(%2,%0), %%xmm1 \n\t"
+        "mulps     (%3,%0), %%xmm0 \n\t"
+        "mulps   16(%3,%0), %%xmm1 \n\t"
         "movaps  %%xmm0,   (%1,%0) \n\t"
         "movaps  %%xmm1, 16(%1,%0) \n\t"
         "sub  $32, %0 \n\t"
         "jge 1b \n\t"
         :"+r"(i)
-        :"r"(dst), "r"(src)
+        :"r"(dst), "r"(src0), "r"(src1)
         :"memory"
     );
 }
@@ -2158,120 +2280,68 @@ static void vector_fmul_add_sse(float *dst, const float *src0, const float *src1
     );
 }
 
-static void vector_fmul_window_3dnow2(float *dst, const float *src0, const float *src1,
-                                      const float *win, float add_bias, int len){
 #if HAVE_6REGS
-    if(add_bias == 0){
-        x86_reg i = -len*4;
-        x86_reg j = len*4-8;
-        __asm__ volatile(
-            "1: \n"
-            "pswapd  (%5,%1), %%mm1 \n"
-            "movq    (%5,%0), %%mm0 \n"
-            "pswapd  (%4,%1), %%mm5 \n"
-            "movq    (%3,%0), %%mm4 \n"
-            "movq      %%mm0, %%mm2 \n"
-            "movq      %%mm1, %%mm3 \n"
-            "pfmul     %%mm4, %%mm2 \n" // src0[len+i]*win[len+i]
-            "pfmul     %%mm5, %%mm3 \n" // src1[    j]*win[len+j]
-            "pfmul     %%mm4, %%mm1 \n" // src0[len+i]*win[len+j]
-            "pfmul     %%mm5, %%mm0 \n" // src1[    j]*win[len+i]
-            "pfadd     %%mm3, %%mm2 \n"
-            "pfsub     %%mm0, %%mm1 \n"
-            "pswapd    %%mm2, %%mm2 \n"
-            "movq      %%mm1, (%2,%0) \n"
-            "movq      %%mm2, (%2,%1) \n"
-            "sub $8, %1 \n"
-            "add $8, %0 \n"
-            "jl 1b \n"
-            "femms \n"
-            :"+r"(i), "+r"(j)
-            :"r"(dst+len), "r"(src0+len), "r"(src1), "r"(win+len)
-        );
-    }else
-#endif
-        ff_vector_fmul_window_c(dst, src0, src1, win, add_bias, len);
-}
-
-static void vector_fmul_window_sse(float *dst, const float *src0, const float *src1,
-                                   const float *win, float add_bias, int len){
-#if HAVE_6REGS
-    if(add_bias == 0){
-        x86_reg i = -len*4;
-        x86_reg j = len*4-16;
-        __asm__ volatile(
-            "1: \n"
-            "movaps       (%5,%1), %%xmm1 \n"
-            "movaps       (%5,%0), %%xmm0 \n"
-            "movaps       (%4,%1), %%xmm5 \n"
-            "movaps       (%3,%0), %%xmm4 \n"
-            "shufps $0x1b, %%xmm1, %%xmm1 \n"
-            "shufps $0x1b, %%xmm5, %%xmm5 \n"
-            "movaps        %%xmm0, %%xmm2 \n"
-            "movaps        %%xmm1, %%xmm3 \n"
-            "mulps         %%xmm4, %%xmm2 \n" // src0[len+i]*win[len+i]
-            "mulps         %%xmm5, %%xmm3 \n" // src1[    j]*win[len+j]
-            "mulps         %%xmm4, %%xmm1 \n" // src0[len+i]*win[len+j]
-            "mulps         %%xmm5, %%xmm0 \n" // src1[    j]*win[len+i]
-            "addps         %%xmm3, %%xmm2 \n"
-            "subps         %%xmm0, %%xmm1 \n"
-            "shufps $0x1b, %%xmm2, %%xmm2 \n"
-            "movaps        %%xmm1, (%2,%0) \n"
-            "movaps        %%xmm2, (%2,%1) \n"
-            "sub $16, %1 \n"
-            "add $16, %0 \n"
-            "jl 1b \n"
-            :"+r"(i), "+r"(j)
-            :"r"(dst+len), "r"(src0+len), "r"(src1), "r"(win+len)
-        );
-    }else
-#endif
-        ff_vector_fmul_window_c(dst, src0, src1, win, add_bias, len);
-}
-
-static void int32_to_float_fmul_scalar_sse(float *dst, const int *src, float mul, int len)
-{
-    x86_reg i = -4*len;
+static void vector_fmul_window_3dnow2(float *dst, const float *src0, const float *src1,
+                                      const float *win, int len){
+    x86_reg i = -len*4;
+    x86_reg j = len*4-8;
     __asm__ volatile(
-        "movss  %3, %%xmm4 \n"
-        "shufps $0, %%xmm4, %%xmm4 \n"
         "1: \n"
-        "cvtpi2ps   (%2,%0), %%xmm0 \n"
-        "cvtpi2ps  8(%2,%0), %%xmm1 \n"
-        "cvtpi2ps 16(%2,%0), %%xmm2 \n"
-        "cvtpi2ps 24(%2,%0), %%xmm3 \n"
-        "movlhps  %%xmm1,    %%xmm0 \n"
-        "movlhps  %%xmm3,    %%xmm2 \n"
-        "mulps    %%xmm4,    %%xmm0 \n"
-        "mulps    %%xmm4,    %%xmm2 \n"
-        "movaps   %%xmm0,   (%1,%0) \n"
-        "movaps   %%xmm2, 16(%1,%0) \n"
-        "add $32, %0 \n"
+        "pswapd  (%5,%1), %%mm1 \n"
+        "movq    (%5,%0), %%mm0 \n"
+        "pswapd  (%4,%1), %%mm5 \n"
+        "movq    (%3,%0), %%mm4 \n"
+        "movq      %%mm0, %%mm2 \n"
+        "movq      %%mm1, %%mm3 \n"
+        "pfmul     %%mm4, %%mm2 \n" // src0[len+i]*win[len+i]
+        "pfmul     %%mm5, %%mm3 \n" // src1[    j]*win[len+j]
+        "pfmul     %%mm4, %%mm1 \n" // src0[len+i]*win[len+j]
+        "pfmul     %%mm5, %%mm0 \n" // src1[    j]*win[len+i]
+        "pfadd     %%mm3, %%mm2 \n"
+        "pfsub     %%mm0, %%mm1 \n"
+        "pswapd    %%mm2, %%mm2 \n"
+        "movq      %%mm1, (%2,%0) \n"
+        "movq      %%mm2, (%2,%1) \n"
+        "sub $8, %1 \n"
+        "add $8, %0 \n"
         "jl 1b \n"
-        :"+r"(i)
-        :"r"(dst+len), "r"(src+len), "m"(mul)
+        "femms \n"
+        :"+r"(i), "+r"(j)
+        :"r"(dst+len), "r"(src0+len), "r"(src1), "r"(win+len)
     );
 }
 
-static void int32_to_float_fmul_scalar_sse2(float *dst, const int *src, float mul, int len)
-{
-    x86_reg i = -4*len;
+static void vector_fmul_window_sse(float *dst, const float *src0, const float *src1,
+                                   const float *win, int len){
+    x86_reg i = -len*4;
+    x86_reg j = len*4-16;
     __asm__ volatile(
-        "movss  %3, %%xmm4 \n"
-        "shufps $0, %%xmm4, %%xmm4 \n"
         "1: \n"
-        "cvtdq2ps   (%2,%0), %%xmm0 \n"
-        "cvtdq2ps 16(%2,%0), %%xmm1 \n"
-        "mulps    %%xmm4,    %%xmm0 \n"
-        "mulps    %%xmm4,    %%xmm1 \n"
-        "movaps   %%xmm0,   (%1,%0) \n"
-        "movaps   %%xmm1, 16(%1,%0) \n"
-        "add $32, %0 \n"
+        "movaps       (%5,%1), %%xmm1 \n"
+        "movaps       (%5,%0), %%xmm0 \n"
+        "movaps       (%4,%1), %%xmm5 \n"
+        "movaps       (%3,%0), %%xmm4 \n"
+        "shufps $0x1b, %%xmm1, %%xmm1 \n"
+        "shufps $0x1b, %%xmm5, %%xmm5 \n"
+        "movaps        %%xmm0, %%xmm2 \n"
+        "movaps        %%xmm1, %%xmm3 \n"
+        "mulps         %%xmm4, %%xmm2 \n" // src0[len+i]*win[len+i]
+        "mulps         %%xmm5, %%xmm3 \n" // src1[    j]*win[len+j]
+        "mulps         %%xmm4, %%xmm1 \n" // src0[len+i]*win[len+j]
+        "mulps         %%xmm5, %%xmm0 \n" // src1[    j]*win[len+i]
+        "addps         %%xmm3, %%xmm2 \n"
+        "subps         %%xmm0, %%xmm1 \n"
+        "shufps $0x1b, %%xmm2, %%xmm2 \n"
+        "movaps        %%xmm1, (%2,%0) \n"
+        "movaps        %%xmm2, (%2,%1) \n"
+        "sub $16, %1 \n"
+        "add $16, %0 \n"
         "jl 1b \n"
-        :"+r"(i)
-        :"r"(dst+len), "r"(src+len), "m"(mul)
+        :"+r"(i), "+r"(j)
+        :"r"(dst+len), "r"(src0+len), "r"(src1), "r"(win+len)
     );
 }
+#endif /* HAVE_6REGS */
 
 static void vector_clipf_sse(float *dst, const float *src, float min, float max,
                              int len)
@@ -2307,198 +2377,50 @@ static void vector_clipf_sse(float *dst, const float *src, float min, float max,
     );
 }
 
-static void float_to_int16_3dnow(int16_t *dst, const float *src, long len){
-    x86_reg reglen = len;
-    // not bit-exact: pf2id uses different rounding than C and SSE
-    __asm__ volatile(
-        "add        %0          , %0        \n\t"
-        "lea         (%2,%0,2)  , %2        \n\t"
-        "add        %0          , %1        \n\t"
-        "neg        %0                      \n\t"
-        "1:                                 \n\t"
-        "pf2id       (%2,%0,2)  , %%mm0     \n\t"
-        "pf2id      8(%2,%0,2)  , %%mm1     \n\t"
-        "pf2id     16(%2,%0,2)  , %%mm2     \n\t"
-        "pf2id     24(%2,%0,2)  , %%mm3     \n\t"
-        "packssdw   %%mm1       , %%mm0     \n\t"
-        "packssdw   %%mm3       , %%mm2     \n\t"
-        "movq       %%mm0       ,  (%1,%0)  \n\t"
-        "movq       %%mm2       , 8(%1,%0)  \n\t"
-        "add        $16         , %0        \n\t"
-        " js 1b                             \n\t"
-        "femms                              \n\t"
-        :"+r"(reglen), "+r"(dst), "+r"(src)
-    );
-}
-static void float_to_int16_sse(int16_t *dst, const float *src, long len){
-    x86_reg reglen = len;
-    __asm__ volatile(
-        "add        %0          , %0        \n\t"
-        "lea         (%2,%0,2)  , %2        \n\t"
-        "add        %0          , %1        \n\t"
-        "neg        %0                      \n\t"
-        "1:                                 \n\t"
-        "cvtps2pi    (%2,%0,2)  , %%mm0     \n\t"
-        "cvtps2pi   8(%2,%0,2)  , %%mm1     \n\t"
-        "cvtps2pi  16(%2,%0,2)  , %%mm2     \n\t"
-        "cvtps2pi  24(%2,%0,2)  , %%mm3     \n\t"
-        "packssdw   %%mm1       , %%mm0     \n\t"
-        "packssdw   %%mm3       , %%mm2     \n\t"
-        "movq       %%mm0       ,  (%1,%0)  \n\t"
-        "movq       %%mm2       , 8(%1,%0)  \n\t"
-        "add        $16         , %0        \n\t"
-        " js 1b                             \n\t"
-        "emms                               \n\t"
-        :"+r"(reglen), "+r"(dst), "+r"(src)
-    );
-}
-
-static void float_to_int16_sse2(int16_t *dst, const float *src, long len){
-    x86_reg reglen = len;
-    __asm__ volatile(
-        "add        %0          , %0        \n\t"
-        "lea         (%2,%0,2)  , %2        \n\t"
-        "add        %0          , %1        \n\t"
-        "neg        %0                      \n\t"
-        "1:                                 \n\t"
-        "cvtps2dq    (%2,%0,2)  , %%xmm0    \n\t"
-        "cvtps2dq  16(%2,%0,2)  , %%xmm1    \n\t"
-        "packssdw   %%xmm1      , %%xmm0    \n\t"
-        "movdqa     %%xmm0      ,  (%1,%0)  \n\t"
-        "add        $16         , %0        \n\t"
-        " js 1b                             \n\t"
-        :"+r"(reglen), "+r"(dst), "+r"(src)
-    );
-}
+void ff_vp3_idct_mmx(int16_t *input_data);
+void ff_vp3_idct_put_mmx(uint8_t *dest, int line_size, DCTELEM *block);
+void ff_vp3_idct_add_mmx(uint8_t *dest, int line_size, DCTELEM *block);
+
+void ff_vp3_idct_dc_add_mmx2(uint8_t *dest, int line_size, const DCTELEM *block);
+
+void ff_vp3_v_loop_filter_mmx2(uint8_t *src, int stride, int *bounding_values);
+void ff_vp3_h_loop_filter_mmx2(uint8_t *src, int stride, int *bounding_values);
+
+void ff_vp3_idct_sse2(int16_t *input_data);
+void ff_vp3_idct_put_sse2(uint8_t *dest, int line_size, DCTELEM *block);
+void ff_vp3_idct_add_sse2(uint8_t *dest, int line_size, DCTELEM *block);
+
+int32_t ff_scalarproduct_int16_mmx2(const int16_t *v1, const int16_t *v2, int order, int shift);
+int32_t ff_scalarproduct_int16_sse2(const int16_t *v1, const int16_t *v2, int order, int shift);
+int32_t ff_scalarproduct_and_madd_int16_mmx2(int16_t *v1, const int16_t *v2, const int16_t *v3, int order, int mul);
+int32_t ff_scalarproduct_and_madd_int16_sse2(int16_t *v1, const int16_t *v2, const int16_t *v3, int order, int mul);
+int32_t ff_scalarproduct_and_madd_int16_ssse3(int16_t *v1, const int16_t *v2, const int16_t *v3, int order, int mul);
+
+void ff_apply_window_int16_mmxext    (int16_t *output, const int16_t *input,
+                                      const int16_t *window, unsigned int len);
+void ff_apply_window_int16_mmxext_ba (int16_t *output, const int16_t *input,
+                                      const int16_t *window, unsigned int len);
+void ff_apply_window_int16_sse2      (int16_t *output, const int16_t *input,
+                                      const int16_t *window, unsigned int len);
+void ff_apply_window_int16_sse2_ba   (int16_t *output, const int16_t *input,
+                                      const int16_t *window, unsigned int len);
+void ff_apply_window_int16_ssse3     (int16_t *output, const int16_t *input,
+                                      const int16_t *window, unsigned int len);
+void ff_apply_window_int16_ssse3_atom(int16_t *output, const int16_t *input,
+                                      const int16_t *window, unsigned int len);
 
-void ff_float_to_int16_interleave6_sse(int16_t *dst, const float **src, int len);
-void ff_float_to_int16_interleave6_3dnow(int16_t *dst, const float **src, int len);
-void ff_float_to_int16_interleave6_3dn2(int16_t *dst, const float **src, int len);
-int32_t ff_scalarproduct_int16_mmx2(int16_t *v1, int16_t *v2, int order, int shift);
-int32_t ff_scalarproduct_int16_sse2(int16_t *v1, int16_t *v2, int order, int shift);
-int32_t ff_scalarproduct_and_madd_int16_mmx2(int16_t *v1, int16_t *v2, int16_t *v3, int order, int mul);
-int32_t ff_scalarproduct_and_madd_int16_sse2(int16_t *v1, int16_t *v2, int16_t *v3, int order, int mul);
-int32_t ff_scalarproduct_and_madd_int16_ssse3(int16_t *v1, int16_t *v2, int16_t *v3, int order, int mul);
 void ff_add_hfyu_median_prediction_mmx2(uint8_t *dst, const uint8_t *top, const uint8_t *diff, int w, int *left, int *left_top);
 int  ff_add_hfyu_left_prediction_ssse3(uint8_t *dst, const uint8_t *src, int w, int left);
 int  ff_add_hfyu_left_prediction_sse4(uint8_t *dst, const uint8_t *src, int w, int left);
-void ff_x264_deblock_v_luma_sse2(uint8_t *pix, int stride, int alpha, int beta, int8_t *tc0);
-void ff_x264_deblock_h_luma_sse2(uint8_t *pix, int stride, int alpha, int beta, int8_t *tc0);
-void ff_x264_deblock_h_luma_intra_mmxext(uint8_t *pix, int stride, int alpha, int beta);
-void ff_x264_deblock_v_luma_intra_sse2(uint8_t *pix, int stride, int alpha, int beta);
-void ff_x264_deblock_h_luma_intra_sse2(uint8_t *pix, int stride, int alpha, int beta);
-
-#if HAVE_YASM && ARCH_X86_32
-void ff_x264_deblock_v8_luma_intra_mmxext(uint8_t *pix, int stride, int alpha, int beta);
-static void ff_x264_deblock_v_luma_intra_mmxext(uint8_t *pix, int stride, int alpha, int beta)
-{
-    ff_x264_deblock_v8_luma_intra_mmxext(pix+0, stride, alpha, beta);
-    ff_x264_deblock_v8_luma_intra_mmxext(pix+8, stride, alpha, beta);
-}
-#elif !HAVE_YASM
-#define ff_float_to_int16_interleave6_sse(a,b,c)   float_to_int16_interleave_misc_sse(a,b,c,6)
-#define ff_float_to_int16_interleave6_3dnow(a,b,c) float_to_int16_interleave_misc_3dnow(a,b,c,6)
-#define ff_float_to_int16_interleave6_3dn2(a,b,c)  float_to_int16_interleave_misc_3dnow(a,b,c,6)
-#endif
-#define ff_float_to_int16_interleave6_sse2 ff_float_to_int16_interleave6_sse
-
-#define FLOAT_TO_INT16_INTERLEAVE(cpu, body) \
-/* gcc pessimizes register allocation if this is in the same function as float_to_int16_interleave_sse2*/\
-static av_noinline void float_to_int16_interleave_misc_##cpu(int16_t *dst, const float **src, long len, int channels){\
-    DECLARE_ALIGNED(16, int16_t, tmp)[len];\
-    int i,j,c;\
-    for(c=0; c<channels; c++){\
-        float_to_int16_##cpu(tmp, src[c], len);\
-        for(i=0, j=c; i<len; i++, j+=channels)\
-            dst[j] = tmp[i];\
-    }\
-}\
-\
-static void float_to_int16_interleave_##cpu(int16_t *dst, const float **src, long len, int channels){\
-    if(channels==1)\
-        float_to_int16_##cpu(dst, src[0], len);\
-    else if(channels==2){\
-        x86_reg reglen = len; \
-        const float *src0 = src[0];\
-        const float *src1 = src[1];\
-        __asm__ volatile(\
-            "shl $2, %0 \n"\
-            "add %0, %1 \n"\
-            "add %0, %2 \n"\
-            "add %0, %3 \n"\
-            "neg %0 \n"\
-            body\
-            :"+r"(reglen), "+r"(dst), "+r"(src0), "+r"(src1)\
-        );\
-    }else if(channels==6){\
-        ff_float_to_int16_interleave6_##cpu(dst, src, len);\
-    }else\
-        float_to_int16_interleave_misc_##cpu(dst, src, len, channels);\
-}
-
-FLOAT_TO_INT16_INTERLEAVE(3dnow,
-    "1:                         \n"
-    "pf2id     (%2,%0), %%mm0   \n"
-    "pf2id    8(%2,%0), %%mm1   \n"
-    "pf2id     (%3,%0), %%mm2   \n"
-    "pf2id    8(%3,%0), %%mm3   \n"
-    "packssdw    %%mm1, %%mm0   \n"
-    "packssdw    %%mm3, %%mm2   \n"
-    "movq        %%mm0, %%mm1   \n"
-    "punpcklwd   %%mm2, %%mm0   \n"
-    "punpckhwd   %%mm2, %%mm1   \n"
-    "movq        %%mm0,  (%1,%0)\n"
-    "movq        %%mm1, 8(%1,%0)\n"
-    "add $16, %0                \n"
-    "js 1b                      \n"
-    "femms                      \n"
-)
-
-FLOAT_TO_INT16_INTERLEAVE(sse,
-    "1:                         \n"
-    "cvtps2pi  (%2,%0), %%mm0   \n"
-    "cvtps2pi 8(%2,%0), %%mm1   \n"
-    "cvtps2pi  (%3,%0), %%mm2   \n"
-    "cvtps2pi 8(%3,%0), %%mm3   \n"
-    "packssdw    %%mm1, %%mm0   \n"
-    "packssdw    %%mm3, %%mm2   \n"
-    "movq        %%mm0, %%mm1   \n"
-    "punpcklwd   %%mm2, %%mm0   \n"
-    "punpckhwd   %%mm2, %%mm1   \n"
-    "movq        %%mm0,  (%1,%0)\n"
-    "movq        %%mm1, 8(%1,%0)\n"
-    "add $16, %0                \n"
-    "js 1b                      \n"
-    "emms                       \n"
-)
-
-FLOAT_TO_INT16_INTERLEAVE(sse2,
-    "1:                         \n"
-    "cvtps2dq  (%2,%0), %%xmm0  \n"
-    "cvtps2dq  (%3,%0), %%xmm1  \n"
-    "packssdw   %%xmm1, %%xmm0  \n"
-    "movhlps    %%xmm0, %%xmm1  \n"
-    "punpcklwd  %%xmm1, %%xmm0  \n"
-    "movdqa     %%xmm0, (%1,%0) \n"
-    "add $16, %0                \n"
-    "js 1b                      \n"
-)
-
-static void float_to_int16_interleave_3dn2(int16_t *dst, const float **src, long len, int channels){
-    if(channels==6)
-        ff_float_to_int16_interleave6_3dn2(dst, src, len);
-    else
-        float_to_int16_interleave_3dnow(dst, src, len, channels);
-}
 
 float ff_scalarproduct_float_sse(const float *v1, const float *v2, int order);
 
 void dsputil_init_mmx(DSPContext* c, AVCodecContext *avctx)
 {
-    mm_flags = mm_support();
+    int mm_flags = av_get_cpu_flags();
 
     if (avctx->dsp_mask) {
-        if (avctx->dsp_mask & FF_MM_FORCE)
+        if (avctx->dsp_mask & AV_CPU_FLAG_FORCE)
             mm_flags |= (avctx->dsp_mask & 0xffff);
         else
             mm_flags &= ~(avctx->dsp_mask & 0xffff);
@@ -2506,20 +2428,20 @@ void dsputil_init_mmx(DSPContext* c, AVCodecContext *avctx)
 
 #if 0
     av_log(avctx, AV_LOG_INFO, "libavcodec: CPU flags:");
-    if (mm_flags & FF_MM_MMX)
+    if (mm_flags & AV_CPU_FLAG_MMX)
         av_log(avctx, AV_LOG_INFO, " mmx");
-    if (mm_flags & FF_MM_MMX2)
+    if (mm_flags & AV_CPU_FLAG_MMX2)
         av_log(avctx, AV_LOG_INFO, " mmx2");
-    if (mm_flags & FF_MM_3DNOW)
+    if (mm_flags & AV_CPU_FLAG_3DNOW)
         av_log(avctx, AV_LOG_INFO, " 3dnow");
-    if (mm_flags & FF_MM_SSE)
+    if (mm_flags & AV_CPU_FLAG_SSE)
         av_log(avctx, AV_LOG_INFO, " sse");
-    if (mm_flags & FF_MM_SSE2)
+    if (mm_flags & AV_CPU_FLAG_SSE2)
         av_log(avctx, AV_LOG_INFO, " sse2");
     av_log(avctx, AV_LOG_INFO, "\n");
 #endif
 
-    if (mm_flags & FF_MM_MMX) {
+    if (mm_flags & AV_CPU_FLAG_MMX) {
         const int idct_algo= avctx->idct_algo;
 
         if(avctx->lowres==0){
@@ -2530,7 +2452,7 @@ void dsputil_init_mmx(DSPContext* c, AVCodecContext *avctx)
                 c->idct_permutation_type= FF_SIMPLE_IDCT_PERM;
 #if CONFIG_GPL
             }else if(idct_algo==FF_IDCT_LIBMPEG2MMX){
-                if(mm_flags & FF_MM_MMX2){
+                if(mm_flags & AV_CPU_FLAG_MMX2){
                     c->idct_put= ff_libmpeg2mmx2_idct_put;
                     c->idct_add= ff_libmpeg2mmx2_idct_add;
                     c->idct    = ff_mmxext_idct;
@@ -2542,8 +2464,8 @@ void dsputil_init_mmx(DSPContext* c, AVCodecContext *avctx)
                 c->idct_permutation_type= FF_LIBMPEG2_IDCT_PERM;
 #endif
             }else if((CONFIG_VP3_DECODER || CONFIG_VP5_DECODER || CONFIG_VP6_DECODER) &&
-                     idct_algo==FF_IDCT_VP3){
-                if(mm_flags & FF_MM_SSE2){
+                     idct_algo==FF_IDCT_VP3 && HAVE_YASM){
+                if(mm_flags & AV_CPU_FLAG_SSE2){
                     c->idct_put= ff_vp3_idct_put_sse2;
                     c->idct_add= ff_vp3_idct_add_sse2;
                     c->idct    = ff_vp3_idct_sse2;
@@ -2557,12 +2479,12 @@ void dsputil_init_mmx(DSPContext* c, AVCodecContext *avctx)
             }else if(idct_algo==FF_IDCT_CAVS){
                     c->idct_permutation_type= FF_TRANSPOSE_IDCT_PERM;
             }else if(idct_algo==FF_IDCT_XVIDMMX){
-                if(mm_flags & FF_MM_SSE2){
+                if(mm_flags & AV_CPU_FLAG_SSE2){
                     c->idct_put= ff_idct_xvid_sse2_put;
                     c->idct_add= ff_idct_xvid_sse2_add;
                     c->idct    = ff_idct_xvid_sse2;
                     c->idct_permutation_type= FF_SSE2_IDCT_PERM;
-                }else if(mm_flags & FF_MM_MMX2){
+                }else if(mm_flags & AV_CPU_FLAG_MMX2){
                     c->idct_put= ff_idct_xvid_mmx2_put;
                     c->idct_add= ff_idct_xvid_mmx2_add;
                     c->idct    = ff_idct_xvid_mmx2;
@@ -2574,12 +2496,12 @@ void dsputil_init_mmx(DSPContext* c, AVCodecContext *avctx)
             }
         }
 
-        c->put_pixels_clamped = put_pixels_clamped_mmx;
-        c->put_signed_pixels_clamped = put_signed_pixels_clamped_mmx;
-        c->add_pixels_clamped = add_pixels_clamped_mmx;
+        c->put_pixels_clamped = ff_put_pixels_clamped_mmx;
+        c->put_signed_pixels_clamped = ff_put_signed_pixels_clamped_mmx;
+        c->add_pixels_clamped = ff_add_pixels_clamped_mmx;
         c->clear_block  = clear_block_mmx;
         c->clear_blocks = clear_blocks_mmx;
-        if ((mm_flags & FF_MM_SSE) &&
+        if ((mm_flags & AV_CPU_FLAG_SSE) &&
             !(CONFIG_MPEG_XVMC_DECODER && avctx->xvmc_acceleration > 1)){
             /* XvMCCreateBlocks() may not allocate 16-byte aligned blocks */
             c->clear_block  = clear_block_sse;
@@ -2601,7 +2523,12 @@ void dsputil_init_mmx(DSPContext* c, AVCodecContext *avctx)
         SET_HPEL_FUNCS(avg, 1, 8, mmx);
         SET_HPEL_FUNCS(avg_no_rnd, 1, 8, mmx);
 
+#if ARCH_X86_32 || !HAVE_YASM
         c->gmc= gmc_mmx;
+#endif
+#if ARCH_X86_32 && HAVE_YASM
+        c->emulated_edge_mc = emulated_edge_mc_mmx;
+#endif
 
         c->add_bytes= add_bytes_mmx;
         c->add_bytes_l2= add_bytes_l2_mmx;
@@ -2612,18 +2539,16 @@ void dsputil_init_mmx(DSPContext* c, AVCodecContext *avctx)
             c->h263_v_loop_filter= h263_v_loop_filter_mmx;
             c->h263_h_loop_filter= h263_h_loop_filter_mmx;
         }
-        c->put_h264_chroma_pixels_tab[0]= put_h264_chroma_mc8_mmx_rnd;
-        c->put_h264_chroma_pixels_tab[1]= put_h264_chroma_mc4_mmx;
-        c->put_no_rnd_vc1_chroma_pixels_tab[0]= put_vc1_chroma_mc8_mmx_nornd;
 
-        c->put_rv40_chroma_pixels_tab[0]= put_rv40_chroma_mc8_mmx;
-        c->put_rv40_chroma_pixels_tab[1]= put_rv40_chroma_mc4_mmx;
+#if HAVE_YASM
+        c->put_h264_chroma_pixels_tab[0]= ff_put_h264_chroma_mc8_mmx_rnd;
+        c->put_h264_chroma_pixels_tab[1]= ff_put_h264_chroma_mc4_mmx;
 
-        if (CONFIG_VP6_DECODER) {
-            c->vp6_filter_diag4 = ff_vp6_filter_diag4_mmx;
-        }
+        c->put_rv40_chroma_pixels_tab[0]= ff_put_rv40_chroma_mc8_mmx;
+        c->put_rv40_chroma_pixels_tab[1]= ff_put_rv40_chroma_mc4_mmx;
+#endif
 
-        if (mm_flags & FF_MM_MMX2) {
+        if (mm_flags & AV_CPU_FLAG_MMX2) {
             c->prefetch = prefetch_mmx2;
 
             c->put_pixels_tab[0][1] = put_pixels16_x2_mmx2;
@@ -2648,15 +2573,21 @@ void dsputil_init_mmx(DSPContext* c, AVCodecContext *avctx)
                 c->avg_pixels_tab[0][3] = avg_pixels16_xy2_mmx2;
                 c->avg_pixels_tab[1][3] = avg_pixels8_xy2_mmx2;
 
-                if (CONFIG_VP3_DECODER) {
+                if (CONFIG_VP3_DECODER && HAVE_YASM) {
                     c->vp3_v_loop_filter= ff_vp3_v_loop_filter_mmx2;
                     c->vp3_h_loop_filter= ff_vp3_h_loop_filter_mmx2;
                 }
             }
-            if (CONFIG_VP3_DECODER) {
+            if (CONFIG_VP3_DECODER && HAVE_YASM) {
                 c->vp3_idct_dc_add = ff_vp3_idct_dc_add_mmx2;
             }
 
+            if (CONFIG_VP3_DECODER
+                && (avctx->codec_id == CODEC_ID_VP3 || avctx->codec_id == CODEC_ID_THEORA)) {
+                c->put_no_rnd_pixels_tab[1][1] = put_no_rnd_pixels8_x2_exact_mmx2;
+                c->put_no_rnd_pixels_tab[1][2] = put_no_rnd_pixels8_y2_exact_mmx2;
+            }
+
 #define SET_QPEL_FUNCS(PFX, IDX, SIZE, CPU) \
             c->PFX ## _pixels_tab[IDX][ 0] = PFX ## SIZE ## _mc00_ ## CPU; \
             c->PFX ## _pixels_tab[IDX][ 1] = PFX ## SIZE ## _mc10_ ## CPU; \
@@ -2694,32 +2625,24 @@ void dsputil_init_mmx(DSPContext* c, AVCodecContext *avctx)
             SET_QPEL_FUNCS(avg_2tap_qpel, 0, 16, mmx2);
             SET_QPEL_FUNCS(avg_2tap_qpel, 1, 8, mmx2);
 
-            c->avg_rv40_chroma_pixels_tab[0]= avg_rv40_chroma_mc8_mmx2;
-            c->avg_rv40_chroma_pixels_tab[1]= avg_rv40_chroma_mc4_mmx2;
-
-            c->avg_no_rnd_vc1_chroma_pixels_tab[0]= avg_vc1_chroma_mc8_mmx2_nornd;
+#if HAVE_YASM
+            c->avg_rv40_chroma_pixels_tab[0]= ff_avg_rv40_chroma_mc8_mmx2;
+            c->avg_rv40_chroma_pixels_tab[1]= ff_avg_rv40_chroma_mc4_mmx2;
 
-            c->avg_h264_chroma_pixels_tab[0]= avg_h264_chroma_mc8_mmx2_rnd;
-            c->avg_h264_chroma_pixels_tab[1]= avg_h264_chroma_mc4_mmx2;
-            c->avg_h264_chroma_pixels_tab[2]= avg_h264_chroma_mc2_mmx2;
-            c->put_h264_chroma_pixels_tab[2]= put_h264_chroma_mc2_mmx2;
+            c->avg_h264_chroma_pixels_tab[0]= ff_avg_h264_chroma_mc8_mmx2_rnd;
+            c->avg_h264_chroma_pixels_tab[1]= ff_avg_h264_chroma_mc4_mmx2;
+            c->avg_h264_chroma_pixels_tab[2]= ff_avg_h264_chroma_mc2_mmx2;
+            c->put_h264_chroma_pixels_tab[2]= ff_put_h264_chroma_mc2_mmx2;
 
-#if HAVE_YASM
             c->add_hfyu_median_prediction = ff_add_hfyu_median_prediction_mmx2;
 #endif
 #if HAVE_7REGS && HAVE_TEN_OPERANDS
-            if( mm_flags&FF_MM_3DNOW )
+            if( mm_flags&AV_CPU_FLAG_3DNOW )
                 c->add_hfyu_median_prediction = add_hfyu_median_prediction_cmov;
 #endif
 
-            if (CONFIG_CAVS_DECODER)
-                ff_cavsdsp_init_mmx2(c, avctx);
-
-            if (CONFIG_VC1_DECODER)
-                ff_vc1dsp_init_mmx(c, avctx);
-
             c->add_png_paeth_prediction= add_png_paeth_prediction_mmx2;
-        } else if (mm_flags & FF_MM_3DNOW) {
+        } else if (mm_flags & AV_CPU_FLAG_3DNOW) {
             c->prefetch = prefetch_3dnow;
 
             c->put_pixels_tab[0][1] = put_pixels16_x2_3dnow;
@@ -2745,6 +2668,12 @@ void dsputil_init_mmx(DSPContext* c, AVCodecContext *avctx)
                 c->avg_pixels_tab[1][3] = avg_pixels8_xy2_3dnow;
             }
 
+            if (CONFIG_VP3_DECODER
+                && (avctx->codec_id == CODEC_ID_VP3 || avctx->codec_id == CODEC_ID_THEORA)) {
+                c->put_no_rnd_pixels_tab[1][1] = put_no_rnd_pixels8_x2_exact_3dnow;
+                c->put_no_rnd_pixels_tab[1][2] = put_no_rnd_pixels8_y2_exact_3dnow;
+            }
+
             SET_QPEL_FUNCS(put_qpel, 0, 16, 3dnow);
             SET_QPEL_FUNCS(put_qpel, 1, 8, 3dnow);
             SET_QPEL_FUNCS(put_no_rnd_qpel, 0, 16, 3dnow);
@@ -2764,14 +2693,13 @@ void dsputil_init_mmx(DSPContext* c, AVCodecContext *avctx)
             SET_QPEL_FUNCS(avg_2tap_qpel, 0, 16, 3dnow);
             SET_QPEL_FUNCS(avg_2tap_qpel, 1, 8, 3dnow);
 
-            c->avg_h264_chroma_pixels_tab[0]= avg_h264_chroma_mc8_3dnow_rnd;
-            c->avg_h264_chroma_pixels_tab[1]= avg_h264_chroma_mc4_3dnow;
-
-            c->avg_rv40_chroma_pixels_tab[0]= avg_rv40_chroma_mc8_3dnow;
-            c->avg_rv40_chroma_pixels_tab[1]= avg_rv40_chroma_mc4_3dnow;
+#if HAVE_YASM
+            c->avg_h264_chroma_pixels_tab[0]= ff_avg_h264_chroma_mc8_3dnow_rnd;
+            c->avg_h264_chroma_pixels_tab[1]= ff_avg_h264_chroma_mc4_3dnow;
 
-            if (CONFIG_CAVS_DECODER)
-                ff_cavsdsp_init_3dnow(c, avctx);
+            c->avg_rv40_chroma_pixels_tab[0]= ff_avg_rv40_chroma_mc8_3dnow;
+            c->avg_rv40_chroma_pixels_tab[1]= ff_avg_rv40_chroma_mc4_3dnow;
+#endif
         }
 
 
@@ -2780,13 +2708,14 @@ void dsputil_init_mmx(DSPContext* c, AVCodecContext *avctx)
             c->put_h264_qpel_pixels_tab[1][x+y*4] = put_h264_qpel8_mc##x##y##_##CPU;\
             c->avg_h264_qpel_pixels_tab[0][x+y*4] = avg_h264_qpel16_mc##x##y##_##CPU;\
             c->avg_h264_qpel_pixels_tab[1][x+y*4] = avg_h264_qpel8_mc##x##y##_##CPU;
-        if((mm_flags & FF_MM_SSE2) && !(mm_flags & FF_MM_3DNOW)){
+        if((mm_flags & AV_CPU_FLAG_SSE2) && !(mm_flags & AV_CPU_FLAG_3DNOW)){
             // these functions are slower than mmx on AMD, but faster on Intel
             c->put_pixels_tab[0][0] = put_pixels16_sse2;
+            c->put_no_rnd_pixels_tab[0][0] = put_pixels16_sse2;
             c->avg_pixels_tab[0][0] = avg_pixels16_sse2;
             H264_QPEL_FUNCS(0, 0, sse2);
         }
-        if(mm_flags & FF_MM_SSE2){
+        if(mm_flags & AV_CPU_FLAG_SSE2){
             H264_QPEL_FUNCS(0, 1, sse2);
             H264_QPEL_FUNCS(0, 2, sse2);
             H264_QPEL_FUNCS(0, 3, sse2);
@@ -2799,13 +2728,9 @@ void dsputil_init_mmx(DSPContext* c, AVCodecContext *avctx)
             H264_QPEL_FUNCS(3, 1, sse2);
             H264_QPEL_FUNCS(3, 2, sse2);
             H264_QPEL_FUNCS(3, 3, sse2);
-
-            if (CONFIG_VP6_DECODER) {
-                c->vp6_filter_diag4 = ff_vp6_filter_diag4_sse2;
-            }
         }
 #if HAVE_SSSE3
-        if(mm_flags & FF_MM_SSSE3){
+        if(mm_flags & AV_CPU_FLAG_SSSE3){
             H264_QPEL_FUNCS(1, 0, ssse3);
             H264_QPEL_FUNCS(1, 1, ssse3);
             H264_QPEL_FUNCS(1, 2, ssse3);
@@ -2818,70 +2743,84 @@ void dsputil_init_mmx(DSPContext* c, AVCodecContext *avctx)
             H264_QPEL_FUNCS(3, 1, ssse3);
             H264_QPEL_FUNCS(3, 2, ssse3);
             H264_QPEL_FUNCS(3, 3, ssse3);
-            c->put_no_rnd_vc1_chroma_pixels_tab[0]= put_vc1_chroma_mc8_ssse3_nornd;
-            c->avg_no_rnd_vc1_chroma_pixels_tab[0]= avg_vc1_chroma_mc8_ssse3_nornd;
-            c->put_h264_chroma_pixels_tab[0]= put_h264_chroma_mc8_ssse3_rnd;
-            c->avg_h264_chroma_pixels_tab[0]= avg_h264_chroma_mc8_ssse3_rnd;
-            c->put_h264_chroma_pixels_tab[1]= put_h264_chroma_mc4_ssse3;
-            c->avg_h264_chroma_pixels_tab[1]= avg_h264_chroma_mc4_ssse3;
             c->add_png_paeth_prediction= add_png_paeth_prediction_ssse3;
 #if HAVE_YASM
+            c->put_h264_chroma_pixels_tab[0]= ff_put_h264_chroma_mc8_ssse3_rnd;
+            c->avg_h264_chroma_pixels_tab[0]= ff_avg_h264_chroma_mc8_ssse3_rnd;
+            c->put_h264_chroma_pixels_tab[1]= ff_put_h264_chroma_mc4_ssse3;
+            c->avg_h264_chroma_pixels_tab[1]= ff_avg_h264_chroma_mc4_ssse3;
             c->add_hfyu_left_prediction = ff_add_hfyu_left_prediction_ssse3;
-            if (mm_flags & FF_MM_SSE4) // not really sse4, just slow on Conroe
+            if (mm_flags & AV_CPU_FLAG_SSE4) // not really sse4, just slow on Conroe
                 c->add_hfyu_left_prediction = ff_add_hfyu_left_prediction_sse4;
 #endif
         }
 #endif
 
-        if(mm_flags & FF_MM_3DNOW){
+        if(mm_flags & AV_CPU_FLAG_3DNOW){
             c->vorbis_inverse_coupling = vorbis_inverse_coupling_3dnow;
             c->vector_fmul = vector_fmul_3dnow;
-            if(!(avctx->flags & CODEC_FLAG_BITEXACT)){
-                c->float_to_int16 = float_to_int16_3dnow;
-                c->float_to_int16_interleave = float_to_int16_interleave_3dnow;
-            }
         }
-        if(mm_flags & FF_MM_3DNOWEXT){
+        if(mm_flags & AV_CPU_FLAG_3DNOWEXT){
             c->vector_fmul_reverse = vector_fmul_reverse_3dnow2;
+#if HAVE_6REGS
             c->vector_fmul_window = vector_fmul_window_3dnow2;
-            if(!(avctx->flags & CODEC_FLAG_BITEXACT)){
-                c->float_to_int16_interleave = float_to_int16_interleave_3dn2;
-            }
+#endif
         }
-        if(mm_flags & FF_MM_MMX2){
+        if(mm_flags & AV_CPU_FLAG_MMX2){
 #if HAVE_YASM
             c->scalarproduct_int16 = ff_scalarproduct_int16_mmx2;
             c->scalarproduct_and_madd_int16 = ff_scalarproduct_and_madd_int16_mmx2;
+            if (avctx->flags & CODEC_FLAG_BITEXACT) {
+                c->apply_window_int16 = ff_apply_window_int16_mmxext_ba;
+            } else {
+                c->apply_window_int16 = ff_apply_window_int16_mmxext;
+            }
 #endif
         }
-        if(mm_flags & FF_MM_SSE){
+        if(mm_flags & AV_CPU_FLAG_SSE){
             c->vorbis_inverse_coupling = vorbis_inverse_coupling_sse;
             c->ac3_downmix = ac3_downmix_sse;
             c->vector_fmul = vector_fmul_sse;
             c->vector_fmul_reverse = vector_fmul_reverse_sse;
             c->vector_fmul_add = vector_fmul_add_sse;
+#if HAVE_6REGS
             c->vector_fmul_window = vector_fmul_window_sse;
-            c->int32_to_float_fmul_scalar = int32_to_float_fmul_scalar_sse;
+#endif
             c->vector_clipf = vector_clipf_sse;
-            c->float_to_int16 = float_to_int16_sse;
-            c->float_to_int16_interleave = float_to_int16_interleave_sse;
 #if HAVE_YASM
             c->scalarproduct_float = ff_scalarproduct_float_sse;
 #endif
         }
-        if(mm_flags & FF_MM_3DNOW)
+        if(mm_flags & AV_CPU_FLAG_3DNOW)
             c->vector_fmul_add = vector_fmul_add_3dnow; // faster than sse
-        if(mm_flags & FF_MM_SSE2){
-            c->int32_to_float_fmul_scalar = int32_to_float_fmul_scalar_sse2;
-            c->float_to_int16 = float_to_int16_sse2;
-            c->float_to_int16_interleave = float_to_int16_interleave_sse2;
+        if(mm_flags & AV_CPU_FLAG_SSE2){
 #if HAVE_YASM
             c->scalarproduct_int16 = ff_scalarproduct_int16_sse2;
             c->scalarproduct_and_madd_int16 = ff_scalarproduct_and_madd_int16_sse2;
+            if (avctx->flags & CODEC_FLAG_BITEXACT) {
+                c->apply_window_int16 = ff_apply_window_int16_sse2_ba;
+            } else {
+                if (!(mm_flags & AV_CPU_FLAG_SSE2SLOW)) {
+                    c->apply_window_int16 = ff_apply_window_int16_sse2;
+                }
+            }
+
+            c->emulated_edge_mc = emulated_edge_mc_sse;
+            c->gmc= gmc_sse;
+#endif
+        }
+        if (mm_flags & AV_CPU_FLAG_SSSE3) {
+#if HAVE_YASM
+            if (mm_flags & AV_CPU_FLAG_ATOM) {
+                c->apply_window_int16 = ff_apply_window_int16_ssse3_atom;
+            } else {
+                c->apply_window_int16 = ff_apply_window_int16_ssse3;
+            }
+            if (!(mm_flags & (AV_CPU_FLAG_SSE42|AV_CPU_FLAG_3DNOW))) { // cachesplit
+                c->scalarproduct_and_madd_int16 = ff_scalarproduct_and_madd_int16_ssse3;
+            }
 #endif
         }
-        if((mm_flags & FF_MM_SSSE3) && !(mm_flags & (FF_MM_SSE42|FF_MM_3DNOW)) && HAVE_YASM) // cachesplit
-            c->scalarproduct_and_madd_int16 = ff_scalarproduct_and_madd_int16_ssse3;
     }
 
     if (CONFIG_ENCODERS)
@@ -2922,81 +2861,3 @@ void dsputil_init_mmx(DSPContext* c, AVCodecContext *avctx)
     //ff_idct = just_return;
 #endif
 }
-
-#if CONFIG_H264DSP
-void ff_h264dsp_init_x86(H264DSPContext *c)
-{
-    mm_flags = mm_support();
-
-    if (mm_flags & FF_MM_MMX) {
-        c->h264_idct_dc_add=
-        c->h264_idct_add= ff_h264_idct_add_mmx;
-        c->h264_idct8_dc_add=
-        c->h264_idct8_add= ff_h264_idct8_add_mmx;
-
-        c->h264_idct_add16     = ff_h264_idct_add16_mmx;
-        c->h264_idct8_add4     = ff_h264_idct8_add4_mmx;
-        c->h264_idct_add8      = ff_h264_idct_add8_mmx;
-        c->h264_idct_add16intra= ff_h264_idct_add16intra_mmx;
-
-        if (mm_flags & FF_MM_MMX2) {
-            c->h264_idct_dc_add= ff_h264_idct_dc_add_mmx2;
-            c->h264_idct8_dc_add= ff_h264_idct8_dc_add_mmx2;
-            c->h264_idct_add16     = ff_h264_idct_add16_mmx2;
-            c->h264_idct8_add4     = ff_h264_idct8_add4_mmx2;
-            c->h264_idct_add8      = ff_h264_idct_add8_mmx2;
-            c->h264_idct_add16intra= ff_h264_idct_add16intra_mmx2;
-
-            c->h264_v_loop_filter_luma= h264_v_loop_filter_luma_mmx2;
-            c->h264_h_loop_filter_luma= h264_h_loop_filter_luma_mmx2;
-            c->h264_v_loop_filter_chroma= h264_v_loop_filter_chroma_mmx2;
-            c->h264_h_loop_filter_chroma= h264_h_loop_filter_chroma_mmx2;
-            c->h264_v_loop_filter_chroma_intra= h264_v_loop_filter_chroma_intra_mmx2;
-            c->h264_h_loop_filter_chroma_intra= h264_h_loop_filter_chroma_intra_mmx2;
-            c->h264_loop_filter_strength= h264_loop_filter_strength_mmx2;
-
-            c->weight_h264_pixels_tab[0]= ff_h264_weight_16x16_mmx2;
-            c->weight_h264_pixels_tab[1]= ff_h264_weight_16x8_mmx2;
-            c->weight_h264_pixels_tab[2]= ff_h264_weight_8x16_mmx2;
-            c->weight_h264_pixels_tab[3]= ff_h264_weight_8x8_mmx2;
-            c->weight_h264_pixels_tab[4]= ff_h264_weight_8x4_mmx2;
-            c->weight_h264_pixels_tab[5]= ff_h264_weight_4x8_mmx2;
-            c->weight_h264_pixels_tab[6]= ff_h264_weight_4x4_mmx2;
-            c->weight_h264_pixels_tab[7]= ff_h264_weight_4x2_mmx2;
-
-            c->biweight_h264_pixels_tab[0]= ff_h264_biweight_16x16_mmx2;
-            c->biweight_h264_pixels_tab[1]= ff_h264_biweight_16x8_mmx2;
-            c->biweight_h264_pixels_tab[2]= ff_h264_biweight_8x16_mmx2;
-            c->biweight_h264_pixels_tab[3]= ff_h264_biweight_8x8_mmx2;
-            c->biweight_h264_pixels_tab[4]= ff_h264_biweight_8x4_mmx2;
-            c->biweight_h264_pixels_tab[5]= ff_h264_biweight_4x8_mmx2;
-            c->biweight_h264_pixels_tab[6]= ff_h264_biweight_4x4_mmx2;
-            c->biweight_h264_pixels_tab[7]= ff_h264_biweight_4x2_mmx2;
-        }
-        if(mm_flags & FF_MM_SSE2){
-            c->h264_idct8_add = ff_h264_idct8_add_sse2;
-            c->h264_idct8_add4= ff_h264_idct8_add4_sse2;
-        }
-
-#if CONFIG_GPL && HAVE_YASM
-        if (mm_flags & FF_MM_MMX2){
-#if ARCH_X86_32
-            c->h264_v_loop_filter_luma_intra = ff_x264_deblock_v_luma_intra_mmxext;
-            c->h264_h_loop_filter_luma_intra = ff_x264_deblock_h_luma_intra_mmxext;
-#endif
-            if( mm_flags&FF_MM_SSE2 ){
-#if ARCH_X86_64 || !defined(__ICC) || __ICC > 1110
-                c->h264_v_loop_filter_luma = ff_x264_deblock_v_luma_sse2;
-                c->h264_h_loop_filter_luma = ff_x264_deblock_h_luma_sse2;
-                c->h264_v_loop_filter_luma_intra = ff_x264_deblock_v_luma_intra_sse2;
-                c->h264_h_loop_filter_luma_intra = ff_x264_deblock_h_luma_intra_sse2;
-#endif
-                c->h264_idct_add16 = ff_h264_idct_add16_sse2;
-                c->h264_idct_add8  = ff_h264_idct_add8_sse2;
-                c->h264_idct_add16intra = ff_h264_idct_add16intra_sse2;
-            }
-        }
-#endif
-    }
-}
-#endif /* CONFIG_H264DSP */
diff --git a/libavcodec/x86/dsputil_mmx.h b/libavcodec/x86/dsputil_mmx.h
index 7d1bf7f..7ab55e7 100644
--- a/libavcodec/x86/dsputil_mmx.h
+++ b/libavcodec/x86/dsputil_mmx.h
@@ -2,20 +2,20 @@
  * MMX optimized DSP utils
  * Copyright (c) 2007  Aurelien Jacobs <aurel at gnuage.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -24,6 +24,7 @@
 
 #include <stdint.h>
 #include "libavcodec/dsputil.h"
+#include "libavutil/x86_cpu.h"
 
 typedef struct { uint64_t a, b; } xmm_reg;
 
@@ -32,29 +33,35 @@ extern const uint64_t ff_wtwo;
 
 extern const uint64_t ff_pdw_80000000[2];
 
-extern const uint64_t ff_pw_3;
-extern const uint64_t ff_pw_4;
+extern const xmm_reg  ff_pw_3;
+extern const xmm_reg  ff_pw_4;
 extern const xmm_reg  ff_pw_5;
 extern const xmm_reg  ff_pw_8;
 extern const uint64_t ff_pw_15;
 extern const xmm_reg  ff_pw_16;
+extern const xmm_reg  ff_pw_18;
 extern const uint64_t ff_pw_20;
+extern const xmm_reg  ff_pw_27;
 extern const xmm_reg  ff_pw_28;
 extern const xmm_reg  ff_pw_32;
 extern const uint64_t ff_pw_42;
+extern const uint64_t ff_pw_53;
+extern const xmm_reg  ff_pw_63;
 extern const xmm_reg  ff_pw_64;
 extern const uint64_t ff_pw_96;
 extern const uint64_t ff_pw_128;
 extern const uint64_t ff_pw_255;
 
-extern const uint64_t ff_pb_1;
-extern const uint64_t ff_pb_3;
+extern const xmm_reg  ff_pb_1;
+extern const xmm_reg  ff_pb_3;
 extern const uint64_t ff_pb_7;
 extern const uint64_t ff_pb_1F;
 extern const uint64_t ff_pb_3F;
 extern const uint64_t ff_pb_81;
-extern const uint64_t ff_pb_A1;
+extern const xmm_reg  ff_pb_A1;
+extern const xmm_reg  ff_pb_F8;
 extern const uint64_t ff_pb_FC;
+extern const xmm_reg  ff_pb_FE;
 
 extern const double ff_pd_1[2];
 extern const double ff_pd_2[2];
@@ -88,6 +95,34 @@ extern const double ff_pd_2[2];
     SBUTTERFLY(a,c,d,dq,q) /* a=aeim d=bfjn */\
     SBUTTERFLY(t,b,c,dq,q) /* t=cgko c=dhlp */
 
+static inline void transpose4x4(uint8_t *dst, uint8_t *src, x86_reg dst_stride, x86_reg src_stride){
+    __asm__ volatile( //FIXME could save 1 instruction if done as 8x4 ...
+        "movd  (%1), %%mm0              \n\t"
+        "add   %3, %1                   \n\t"
+        "movd  (%1), %%mm1              \n\t"
+        "movd  (%1,%3,1), %%mm2         \n\t"
+        "movd  (%1,%3,2), %%mm3         \n\t"
+        "punpcklbw %%mm1, %%mm0         \n\t"
+        "punpcklbw %%mm3, %%mm2         \n\t"
+        "movq %%mm0, %%mm1              \n\t"
+        "punpcklwd %%mm2, %%mm0         \n\t"
+        "punpckhwd %%mm2, %%mm1         \n\t"
+        "movd  %%mm0, (%0)              \n\t"
+        "add   %2, %0                   \n\t"
+        "punpckhdq %%mm0, %%mm0         \n\t"
+        "movd  %%mm0, (%0)              \n\t"
+        "movd  %%mm1, (%0,%2,1)         \n\t"
+        "punpckhdq %%mm1, %%mm1         \n\t"
+        "movd  %%mm1, (%0,%2,2)         \n\t"
+
+        :  "+&r" (dst),
+           "+&r" (src)
+        :  "r" (dst_stride),
+           "r" (src_stride)
+        :  "memory"
+    );
+}
+
 // e,f,g,h can be memory
 // out: a,d,t,c
 #define TRANSPOSE8x4(a,b,c,d,e,f,g,h,t)\
@@ -152,25 +187,32 @@ extern const double ff_pd_2[2];
 void dsputilenc_init_mmx(DSPContext* c, AVCodecContext *avctx);
 void dsputil_init_pix_mmx(DSPContext* c, AVCodecContext *avctx);
 
-void add_pixels_clamped_mmx(const DCTELEM *block, uint8_t *pixels, int line_size);
-void put_pixels_clamped_mmx(const DCTELEM *block, uint8_t *pixels, int line_size);
-void put_signed_pixels_clamped_mmx(const DCTELEM *block, uint8_t *pixels, int line_size);
+void ff_add_pixels_clamped_mmx(const DCTELEM *block, uint8_t *pixels, int line_size);
+void ff_put_pixels_clamped_mmx(const DCTELEM *block, uint8_t *pixels, int line_size);
+void ff_put_signed_pixels_clamped_mmx(const DCTELEM *block, uint8_t *pixels, int line_size);
 
-void ff_cavsdsp_init_mmx2(DSPContext* c, AVCodecContext *avctx);
-void ff_cavsdsp_init_3dnow(DSPContext* c, AVCodecContext *avctx);
 void ff_put_cavs_qpel8_mc00_mmx2(uint8_t *dst, uint8_t *src, int stride);
 void ff_avg_cavs_qpel8_mc00_mmx2(uint8_t *dst, uint8_t *src, int stride);
 void ff_put_cavs_qpel16_mc00_mmx2(uint8_t *dst, uint8_t *src, int stride);
 void ff_avg_cavs_qpel16_mc00_mmx2(uint8_t *dst, uint8_t *src, int stride);
 
-void ff_vc1dsp_init_mmx(DSPContext* dsp, AVCodecContext *avctx);
 void ff_put_vc1_mspel_mc00_mmx(uint8_t *dst, const uint8_t *src, int stride, int rnd);
 void ff_avg_vc1_mspel_mc00_mmx2(uint8_t *dst, const uint8_t *src, int stride, int rnd);
 
-void ff_lpc_compute_autocorr_sse2(const int32_t *data, int len, int lag,
-                                   double *autoc);
-
 void ff_mmx_idct(DCTELEM *block);
 void ff_mmxext_idct(DCTELEM *block);
 
+
+void ff_deinterlace_line_mmx(uint8_t *dst,
+                             const uint8_t *lum_m4, const uint8_t *lum_m3,
+                             const uint8_t *lum_m2, const uint8_t *lum_m1,
+                             const uint8_t *lum,
+                             int size);
+
+void ff_deinterlace_line_inplace_mmx(const uint8_t *lum_m4,
+                                     const uint8_t *lum_m3,
+                                     const uint8_t *lum_m2,
+                                     const uint8_t *lum_m1,
+                                     const uint8_t *lum, int size);
+
 #endif /* AVCODEC_X86_DSPUTIL_MMX_H */
diff --git a/libavcodec/x86/dsputil_mmx_avg_template.c b/libavcodec/x86/dsputil_mmx_avg_template.c
index 8220867..8b116b7 100644
--- a/libavcodec/x86/dsputil_mmx_avg_template.c
+++ b/libavcodec/x86/dsputil_mmx_avg_template.c
@@ -7,20 +7,20 @@
  * mostly rewritten by Michael Niedermayer <michaelni at gmx.at>
  * and improved by Zdenek Kabelac <kabi at users.sf.net>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -586,6 +586,49 @@ static void DEF(put_no_rnd_pixels8_x2)(uint8_t *block, const uint8_t *pixels, in
         :"%"REG_a, "memory");
 }
 
+static void DEF(put_no_rnd_pixels8_x2_exact)(uint8_t *block, const uint8_t *pixels, int line_size, int h)
+{
+    __asm__ volatile (
+        "pcmpeqb %%mm6, %%mm6           \n\t"
+        "1:                             \n\t"
+        "movq  (%1),     %%mm0          \n\t"
+        "movq  (%1, %3), %%mm2          \n\t"
+        "movq 1(%1),     %%mm1          \n\t"
+        "movq 1(%1, %3), %%mm3          \n\t"
+        "pxor  %%mm6, %%mm0             \n\t"
+        "pxor  %%mm6, %%mm2             \n\t"
+        "pxor  %%mm6, %%mm1             \n\t"
+        "pxor  %%mm6, %%mm3             \n\t"
+        PAVGB" %%mm1, %%mm0             \n\t"
+        PAVGB" %%mm3, %%mm2             \n\t"
+        "pxor  %%mm6, %%mm0             \n\t"
+        "pxor  %%mm6, %%mm2             \n\t"
+        "movq  %%mm0, (%2)              \n\t"
+        "movq  %%mm2, (%2, %3)          \n\t"
+        "movq  (%1, %3,2), %%mm0        \n\t"
+        "movq 1(%1, %3,2), %%mm1        \n\t"
+        "movq  (%1, %4),   %%mm2        \n\t"
+        "movq 1(%1, %4),   %%mm3        \n\t"
+        "pxor  %%mm6, %%mm0             \n\t"
+        "pxor  %%mm6, %%mm1             \n\t"
+        "pxor  %%mm6, %%mm2             \n\t"
+        "pxor  %%mm6, %%mm3             \n\t"
+        PAVGB" %%mm1, %%mm0             \n\t"
+        PAVGB" %%mm3, %%mm2             \n\t"
+        "pxor  %%mm6, %%mm0             \n\t"
+        "pxor  %%mm6, %%mm2             \n\t"
+        "movq  %%mm0, (%2, %3,2)        \n\t"
+        "movq  %%mm2, (%2, %4)          \n\t"
+        "lea   (%1, %3,4), %1           \n\t"
+        "lea   (%2, %3,4), %2           \n\t"
+        "subl  $4, %0                   \n\t"
+        "jg 1b                          \n\t"
+        : "+g"(h), "+r"(pixels), "+r"(block)
+        : "r" ((x86_reg)line_size), "r"((x86_reg)3*line_size)
+        : "memory"
+    );
+}
+
 static void DEF(put_pixels8_y2)(uint8_t *block, const uint8_t *pixels, int line_size, int h)
 {
     __asm__ volatile(
@@ -650,6 +693,44 @@ static void DEF(put_no_rnd_pixels8_y2)(uint8_t *block, const uint8_t *pixels, in
         :"%"REG_a, "memory");
 }
 
+static void DEF(put_no_rnd_pixels8_y2_exact)(uint8_t *block, const uint8_t *pixels, int line_size, int h)
+{
+    __asm__ volatile (
+        "movq     (%1), %%mm0           \n\t"
+        "pcmpeqb %%mm6, %%mm6           \n\t"
+        "add        %3, %1              \n\t"
+        "pxor    %%mm6, %%mm0           \n\t"
+        "1:                             \n\t"
+        "movq  (%1),     %%mm1          \n\t"
+        "movq  (%1, %3), %%mm2          \n\t"
+        "pxor  %%mm6, %%mm1             \n\t"
+        "pxor  %%mm6, %%mm2             \n\t"
+        PAVGB" %%mm1, %%mm0             \n\t"
+        PAVGB" %%mm2, %%mm1             \n\t"
+        "pxor  %%mm6, %%mm0             \n\t"
+        "pxor  %%mm6, %%mm1             \n\t"
+        "movq  %%mm0, (%2)              \n\t"
+        "movq  %%mm1, (%2, %3)          \n\t"
+        "movq  (%1, %3,2), %%mm1        \n\t"
+        "movq  (%1, %4),   %%mm0        \n\t"
+        "pxor  %%mm6, %%mm1             \n\t"
+        "pxor  %%mm6, %%mm0             \n\t"
+        PAVGB" %%mm1, %%mm2             \n\t"
+        PAVGB" %%mm0, %%mm1             \n\t"
+        "pxor  %%mm6, %%mm2             \n\t"
+        "pxor  %%mm6, %%mm1             \n\t"
+        "movq %%mm2, (%2, %3,2)         \n\t"
+        "movq %%mm1, (%2, %4)           \n\t"
+        "lea   (%1, %3,4), %1           \n\t"
+        "lea   (%2, %3,4), %2           \n\t"
+        "subl $4, %0                    \n\t"
+        "jg 1b                          \n\t"
+        :"+g"(h), "+r"(pixels), "+r" (block)
+        :"r" ((x86_reg)line_size), "r"((x86_reg)3*line_size)
+        :"memory"
+    );
+}
+
 static void DEF(avg_pixels8)(uint8_t *block, const uint8_t *pixels, int line_size, int h)
 {
     __asm__ volatile(
@@ -757,7 +838,7 @@ static void DEF(avg_pixels8_xy2)(uint8_t *block, const uint8_t *pixels, int line
         "lea (%3, %3), %%"REG_a"        \n\t"
         "movq (%1), %%mm0               \n\t"
         PAVGB" 1(%1), %%mm0             \n\t"
-         ASMALIGN(3)
+         ".p2align 3                    \n\t"
         "1:                             \n\t"
         "movq (%1, %%"REG_a"), %%mm2    \n\t"
         "movq (%1, %3), %%mm1           \n\t"
diff --git a/libavcodec/x86/dsputil_mmx_qns_template.c b/libavcodec/x86/dsputil_mmx_qns_template.c
index d2dbfc5..20a40a1 100644
--- a/libavcodec/x86/dsputil_mmx_qns_template.c
+++ b/libavcodec/x86/dsputil_mmx_qns_template.c
@@ -5,20 +5,20 @@
  * MMX optimization by Michael Niedermayer <michaelni at gmx.at>
  * 3DNow! and SSSE3 optimization by Zuxy Meng <zuxy.meng at gmail.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -37,7 +37,7 @@ static int DEF(try_8x8basis)(int16_t rem[64], int16_t weight[64], int16_t basis[
         "movd  %4, %%mm5                \n\t"
         "punpcklwd %%mm5, %%mm5         \n\t"
         "punpcklwd %%mm5, %%mm5         \n\t"
-        ASMALIGN(4)
+        ".p2align 4                     \n\t"
         "1:                             \n\t"
         "movq  (%1, %0), %%mm0          \n\t"
         "movq  8(%1, %0), %%mm1         \n\t"
@@ -77,7 +77,7 @@ static void DEF(add_8x8basis)(int16_t rem[64], int16_t basis[64], int scale)
                 "movd  %3, %%mm5        \n\t"
                 "punpcklwd %%mm5, %%mm5 \n\t"
                 "punpcklwd %%mm5, %%mm5 \n\t"
-                ASMALIGN(4)
+                ".p2align 4             \n\t"
                 "1:                     \n\t"
                 "movq  (%1, %0), %%mm0  \n\t"
                 "movq  8(%1, %0), %%mm1 \n\t"
diff --git a/libavcodec/x86/dsputil_mmx_rnd_template.c b/libavcodec/x86/dsputil_mmx_rnd_template.c
index 2fc1756..34a2c0b 100644
--- a/libavcodec/x86/dsputil_mmx_rnd_template.c
+++ b/libavcodec/x86/dsputil_mmx_rnd_template.c
@@ -7,20 +7,20 @@
  * mostly rewritten by Michael Niedermayer <michaelni at gmx.at>
  * and improved by Zdenek Kabelac <kabi at users.sf.net>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -30,7 +30,7 @@ static void DEF(put, pixels8_x2)(uint8_t *block, const uint8_t *pixels, int line
     MOVQ_BFE(mm6);
     __asm__ volatile(
         "lea    (%3, %3), %%"REG_a"     \n\t"
-        ASMALIGN(3)
+        ".p2align 3                     \n\t"
         "1:                             \n\t"
         "movq   (%1), %%mm0             \n\t"
         "movq   1(%1), %%mm1            \n\t"
@@ -71,7 +71,7 @@ static void av_unused DEF(put, pixels8_l2)(uint8_t *dst, uint8_t *src1, uint8_t
         "movq   %%mm4, (%3)             \n\t"
         "add    %5, %3                  \n\t"
         "decl   %0                      \n\t"
-        ASMALIGN(3)
+        ".p2align 3                     \n\t"
         "1:                             \n\t"
         "movq   (%1), %%mm0             \n\t"
         "movq   (%2), %%mm1             \n\t"
@@ -112,7 +112,7 @@ static void DEF(put, pixels16_x2)(uint8_t *block, const uint8_t *pixels, int lin
     MOVQ_BFE(mm6);
     __asm__ volatile(
         "lea        (%3, %3), %%"REG_a" \n\t"
-        ASMALIGN(3)
+        ".p2align 3                     \n\t"
         "1:                             \n\t"
         "movq   (%1), %%mm0             \n\t"
         "movq   1(%1), %%mm1            \n\t"
@@ -170,7 +170,7 @@ static void av_unused DEF(put, pixels16_l2)(uint8_t *dst, uint8_t *src1, uint8_t
         "movq   %%mm5, 8(%3)            \n\t"
         "add    %5, %3                  \n\t"
         "decl   %0                      \n\t"
-        ASMALIGN(3)
+        ".p2align 3                     \n\t"
         "1:                             \n\t"
         "movq   (%1), %%mm0             \n\t"
         "movq   (%2), %%mm1             \n\t"
@@ -208,7 +208,7 @@ static void DEF(put, pixels8_y2)(uint8_t *block, const uint8_t *pixels, int line
     __asm__ volatile(
         "lea (%3, %3), %%"REG_a"        \n\t"
         "movq (%1), %%mm0               \n\t"
-        ASMALIGN(3)
+        ".p2align 3                     \n\t"
         "1:                             \n\t"
         "movq   (%1, %3), %%mm1         \n\t"
         "movq   (%1, %%"REG_a"),%%mm2   \n\t"
@@ -248,7 +248,7 @@ static void DEF(put, pixels8_xy2)(uint8_t *block, const uint8_t *pixels, int lin
         "paddusw %%mm1, %%mm5           \n\t"
         "xor    %%"REG_a", %%"REG_a"    \n\t"
         "add    %3, %1                  \n\t"
-        ASMALIGN(3)
+        ".p2align 3                     \n\t"
         "1:                             \n\t"
         "movq   (%1, %%"REG_a"), %%mm0  \n\t"
         "movq   1(%1, %%"REG_a"), %%mm2 \n\t"
@@ -460,7 +460,7 @@ static void DEF(avg, pixels8_y2)(uint8_t *block, const uint8_t *pixels, int line
     __asm__ volatile(
         "lea    (%3, %3), %%"REG_a"     \n\t"
         "movq   (%1), %%mm0             \n\t"
-        ASMALIGN(3)
+        ".p2align 3                     \n\t"
         "1:                             \n\t"
         "movq   (%1, %3), %%mm1         \n\t"
         "movq   (%1, %%"REG_a"), %%mm2  \n\t"
@@ -511,7 +511,7 @@ static void DEF(avg, pixels8_xy2)(uint8_t *block, const uint8_t *pixels, int lin
         "paddusw %%mm1, %%mm5           \n\t"
         "xor    %%"REG_a", %%"REG_a"    \n\t"
         "add    %3, %1                  \n\t"
-        ASMALIGN(3)
+        ".p2align 3                     \n\t"
         "1:                             \n\t"
         "movq   (%1, %%"REG_a"), %%mm0  \n\t"
         "movq   1(%1, %%"REG_a"), %%mm2 \n\t"
diff --git a/libavcodec/x86/dsputil_yasm.asm b/libavcodec/x86/dsputil_yasm.asm
index e2478a4..f2c205b 100644
--- a/libavcodec/x86/dsputil_yasm.asm
+++ b/libavcodec/x86/dsputil_yasm.asm
@@ -2,20 +2,20 @@
 ;* MMX optimized DSP utils
 ;* Copyright (c) 2008 Loren Merritt
 ;*
-;* This file is part of FFmpeg.
+;* This file is part of Libav.
 ;*
-;* FFmpeg is free software; you can redistribute it and/or
+;* Libav is free software; you can redistribute it and/or
 ;* modify it under the terms of the GNU Lesser General Public
 ;* License as published by the Free Software Foundation; either
 ;* version 2.1 of the License, or (at your option) any later version.
 ;*
-;* FFmpeg is distributed in the hope that it will be useful,
+;* Libav is distributed in the hope that it will be useful,
 ;* but WITHOUT ANY WARRANTY; without even the implied warranty of
 ;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 ;* Lesser General Public License for more details.
 ;*
 ;* You should have received a copy of the GNU Lesser General Public
-;* License along with FFmpeg; if not, write to the Free Software
+;* License along with Libav; if not, write to the Free Software
 ;* 51, Inc., Foundation Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;******************************************************************************
 
@@ -27,78 +27,11 @@ pb_zzzzzzzz77777777: times 8 db -1
 pb_7: times 8 db 7
 pb_zzzz3333zzzzbbbb: db -1,-1,-1,-1,3,3,3,3,-1,-1,-1,-1,11,11,11,11
 pb_zz11zz55zz99zzdd: db -1,-1,1,1,-1,-1,5,5,-1,-1,9,9,-1,-1,13,13
+pb_revwords: db 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 0, 1
+pd_16384: times 4 dd 16384
 
 section .text align=16
 
-%macro PSWAPD_SSE 2
-    pshufw %1, %2, 0x4e
-%endmacro
-%macro PSWAPD_3DN1 2
-    movq  %1, %2
-    psrlq %1, 32
-    punpckldq %1, %2
-%endmacro
-
-%macro FLOAT_TO_INT16_INTERLEAVE6 1
-; void ff_float_to_int16_interleave6_sse(int16_t *dst, const float **src, int len)
-cglobal float_to_int16_interleave6_%1, 2,7,0, dst, src, src1, src2, src3, src4, src5
-%ifdef ARCH_X86_64
-    %define lend r10d
-    mov     lend, r2d
-%else
-    %define lend dword r2m
-%endif
-    mov src1q, [srcq+1*gprsize]
-    mov src2q, [srcq+2*gprsize]
-    mov src3q, [srcq+3*gprsize]
-    mov src4q, [srcq+4*gprsize]
-    mov src5q, [srcq+5*gprsize]
-    mov srcq,  [srcq]
-    sub src1q, srcq
-    sub src2q, srcq
-    sub src3q, srcq
-    sub src4q, srcq
-    sub src5q, srcq
-.loop:
-    cvtps2pi   mm0, [srcq]
-    cvtps2pi   mm1, [srcq+src1q]
-    cvtps2pi   mm2, [srcq+src2q]
-    cvtps2pi   mm3, [srcq+src3q]
-    cvtps2pi   mm4, [srcq+src4q]
-    cvtps2pi   mm5, [srcq+src5q]
-    packssdw   mm0, mm3
-    packssdw   mm1, mm4
-    packssdw   mm2, mm5
-    pswapd     mm3, mm0
-    punpcklwd  mm0, mm1
-    punpckhwd  mm1, mm2
-    punpcklwd  mm2, mm3
-    pswapd     mm3, mm0
-    punpckldq  mm0, mm2
-    punpckhdq  mm2, mm1
-    punpckldq  mm1, mm3
-    movq [dstq   ], mm0
-    movq [dstq+16], mm2
-    movq [dstq+ 8], mm1
-    add srcq, 8
-    add dstq, 24
-    sub lend, 2
-    jg .loop
-    emms
-    RET
-%endmacro ; FLOAT_TO_INT16_INTERLEAVE6
-
-%define pswapd PSWAPD_SSE
-FLOAT_TO_INT16_INTERLEAVE6 sse
-%define cvtps2pi pf2id
-%define pswapd PSWAPD_3DN1
-FLOAT_TO_INT16_INTERLEAVE6 3dnow
-%undef pswapd
-FLOAT_TO_INT16_INTERLEAVE6 3dn2
-%undef cvtps2pi
-
-
-
 %macro SCALARPRODUCT 1
 ; int scalarproduct_int16(int16_t *v1, int16_t *v2, int order, int shift)
 cglobal scalarproduct_int16_%1, 3,3,4, v1, v2, order, shift
@@ -271,8 +204,132 @@ SCALARPRODUCT_LOOP 0
     RET
 
 
+;-----------------------------------------------------------------------------
+; void ff_apply_window_int16(int16_t *output, const int16_t *input,
+;                            const int16_t *window, unsigned int len)
+;-----------------------------------------------------------------------------
+
+%macro REVERSE_WORDS_MMXEXT 1-2
+    pshufw   %1, %1, 0x1B
+%endmacro
+
+%macro REVERSE_WORDS_SSE2 1-2
+    pshuflw  %1, %1, 0x1B
+    pshufhw  %1, %1, 0x1B
+    pshufd   %1, %1, 0x4E
+%endmacro
+
+%macro REVERSE_WORDS_SSSE3 2
+    pshufb  %1, %2
+%endmacro
+
+; dst = (dst * src) >> 15
+; pmulhw cuts off the bottom bit, so we have to lshift by 1 and add it back
+; in from the pmullw result.
+%macro MUL16FIXED_MMXEXT 3 ; dst, src, temp
+    mova    %3, %1
+    pmulhw  %1, %2
+    pmullw  %3, %2
+    psrlw   %3, 15
+    psllw   %1, 1
+    por     %1, %3
+%endmacro
 
-; void ff_add_hfyu_median_prediction_mmx2(uint8_t *dst, const uint8_t *top, const uint8_t *diff, int w, int *left, int *left_top)
+; dst = ((dst * src) + (1<<14)) >> 15
+%macro MUL16FIXED_SSSE3 3 ; dst, src, unused
+    pmulhrsw   %1, %2
+%endmacro
+
+%macro APPLY_WINDOW_INT16 3 ; %1=instruction set, %2=mmxext/sse2 bit exact version, %3=has_ssse3
+cglobal apply_window_int16_%1, 4,5,6, output, input, window, offset, offset2
+    lea     offset2q, [offsetq-mmsize]
+%if %2
+    mova          m5, [pd_16384]
+%elifidn %1, ssse3
+    mova          m5, [pb_revwords]
+    ALIGN 16
+%endif
+.loop:
+%if %2
+    ; This version expands 16-bit to 32-bit, multiplies by the window,
+    ; adds 16384 for rounding, right shifts 15, then repacks back to words to
+    ; save to the output. The window is reversed for the second half.
+    mova          m3, [windowq+offset2q]
+    mova          m4, [ inputq+offset2q]
+    pxor          m0, m0
+    punpcklwd     m0, m3
+    punpcklwd     m1, m4
+    pmaddwd       m0, m1
+    paddd         m0, m5
+    psrad         m0, 15
+    pxor          m2, m2
+    punpckhwd     m2, m3
+    punpckhwd     m1, m4
+    pmaddwd       m2, m1
+    paddd         m2, m5
+    psrad         m2, 15
+    packssdw      m0, m2
+    mova  [outputq+offset2q], m0
+    REVERSE_WORDS m3
+    mova          m4, [ inputq+offsetq]
+    pxor          m0, m0
+    punpcklwd     m0, m3
+    punpcklwd     m1, m4
+    pmaddwd       m0, m1
+    paddd         m0, m5
+    psrad         m0, 15
+    pxor          m2, m2
+    punpckhwd     m2, m3
+    punpckhwd     m1, m4
+    pmaddwd       m2, m1
+    paddd         m2, m5
+    psrad         m2, 15
+    packssdw      m0, m2
+    mova  [outputq+offsetq], m0
+%elif %3
+    ; This version does the 16x16->16 multiplication in-place without expanding
+    ; to 32-bit. The ssse3 version is bit-identical.
+    mova          m0, [windowq+offset2q]
+    mova          m1, [ inputq+offset2q]
+    pmulhrsw      m1, m0
+    REVERSE_WORDS m0, m5
+    pmulhrsw      m0, [ inputq+offsetq ]
+    mova  [outputq+offset2q], m1
+    mova  [outputq+offsetq ], m0
+%else
+    ; This version does the 16x16->16 multiplication in-place without expanding
+    ; to 32-bit. The mmxext and sse2 versions do not use rounding, and
+    ; therefore are not bit-identical to the C version.
+    mova          m0, [windowq+offset2q]
+    mova          m1, [ inputq+offset2q]
+    mova          m2, [ inputq+offsetq ]
+    MUL16FIXED    m1, m0, m3
+    REVERSE_WORDS m0
+    MUL16FIXED    m2, m0, m3
+    mova  [outputq+offset2q], m1
+    mova  [outputq+offsetq ], m2
+%endif
+    add      offsetd, mmsize
+    sub     offset2d, mmsize
+    jae .loop
+    REP_RET
+%endmacro
+
+INIT_MMX
+%define REVERSE_WORDS REVERSE_WORDS_MMXEXT
+%define MUL16FIXED MUL16FIXED_MMXEXT
+APPLY_WINDOW_INT16 mmxext,     0, 0
+APPLY_WINDOW_INT16 mmxext_ba,  1, 0
+INIT_XMM
+%define REVERSE_WORDS REVERSE_WORDS_SSE2
+APPLY_WINDOW_INT16 sse2,       0, 0
+APPLY_WINDOW_INT16 sse2_ba,    1, 0
+APPLY_WINDOW_INT16 ssse3_atom, 0, 1
+%define REVERSE_WORDS REVERSE_WORDS_SSSE3
+APPLY_WINDOW_INT16 ssse3,      0, 1
+
+
+; void add_hfyu_median_prediction_mmx2(uint8_t *dst, const uint8_t *top, const uint8_t *diff, int w, int *left, int *left_top)
 cglobal add_hfyu_median_prediction_mmx2, 6,6,0, dst, top, diff, w, left, left_top
     movq    mm0, [topq]
     movq    mm2, mm0
@@ -370,23 +427,23 @@ cglobal add_hfyu_median_prediction_mmx2, 6,6,0, dst, top, diff, w, left, left_to
     RET
 %endmacro
 
-; int ff_add_hfyu_left_prediction(uint8_t *dst, const uint8_t *src, int w, int left)
+; int add_hfyu_left_prediction(uint8_t *dst, const uint8_t *src, int w, int left)
 INIT_MMX
 cglobal add_hfyu_left_prediction_ssse3, 3,3,7, dst, src, w, left
 .skip_prologue:
-    mova    m5, [pb_7 GLOBAL]
-    mova    m4, [pb_zzzz3333zzzzbbbb GLOBAL]
-    mova    m3, [pb_zz11zz55zz99zzdd GLOBAL]
+    mova    m5, [pb_7]
+    mova    m4, [pb_zzzz3333zzzzbbbb]
+    mova    m3, [pb_zz11zz55zz99zzdd]
     movd    m0, leftm
     psllq   m0, 56
     ADD_HFYU_LEFT_LOOP 1
 
 INIT_XMM
 cglobal add_hfyu_left_prediction_sse4, 3,3,7, dst, src, w, left
-    mova    m5, [pb_f GLOBAL]
-    mova    m6, [pb_zzzzzzzz77777777 GLOBAL]
-    mova    m4, [pb_zzzz3333zzzzbbbb GLOBAL]
-    mova    m3, [pb_zz11zz55zz99zzdd GLOBAL]
+    mova    m5, [pb_f]
+    mova    m6, [pb_zzzzzzzz77777777]
+    mova    m4, [pb_zzzz3333zzzzbbbb]
+    mova    m3, [pb_zz11zz55zz99zzdd]
     movd    m0, leftm
     pslldq  m0, 15
     test    srcq, 15
@@ -398,7 +455,7 @@ cglobal add_hfyu_left_prediction_sse4, 3,3,7, dst, src, w, left
     ADD_HFYU_LEFT_LOOP 0
 
 
-; float ff_scalarproduct_float_sse(const float *v1, const float *v2, int len)
+; float scalarproduct_float_sse(const float *v1, const float *v2, int len)
 cglobal scalarproduct_float_sse, 3,3,2, v1, v2, offset
     neg offsetq
     shl offsetq, 2
@@ -421,3 +478,573 @@ cglobal scalarproduct_float_sse, 3,3,2, v1, v2, offset
     fld     dword r0m
 %endif
     RET
+
+; extern void ff_emu_edge_core(uint8_t *buf, const uint8_t *src, x86_reg linesize,
+;                              x86_reg start_y, x86_reg end_y, x86_reg block_h,
+;                              x86_reg start_x, x86_reg end_x, x86_reg block_w);
+;
+; The actual function itself is below. It basically wraps a very simple
+; w = end_x - start_x
+; if (w) {
+;   if (w > 22) {
+;     jump to the slow loop functions
+;   } else {
+;     jump to the fast loop functions
+;   }
+; }
+;
+; ... and then the same for left/right extend also. See below for loop
+; function implementations. Fast are fixed-width, slow is variable-width
+
+%macro EMU_EDGE_FUNC 1
+%ifdef ARCH_X86_64
+%define w_reg r10
+cglobal emu_edge_core_%1, 6, 7, 1
+    mov        r11, r5          ; save block_h
+%else
+%define w_reg r6
+cglobal emu_edge_core_%1, 2, 7, 0
+    mov         r4, r4m         ; end_y
+    mov         r5, r5m         ; block_h
+%endif
+
+    ; start with vertical extend (top/bottom) and body pixel copy
+    mov      w_reg, r7m
+    sub      w_reg, r6m         ; w = start_x - end_x
+    sub         r5, r4
+%ifdef ARCH_X86_64
+    sub         r4, r3
+%else
+    sub         r4, dword r3m
+%endif
+    cmp      w_reg, 22
+    jg .slow_v_extend_loop
+%ifdef ARCH_X86_32
+    mov         r2, r2m         ; linesize
+%endif
+    sal      w_reg, 7           ; w * 128
+%ifdef PIC
+    lea        rax, [.emuedge_v_extend_1 - (.emuedge_v_extend_2 - .emuedge_v_extend_1)]
+    add      w_reg, rax
+%else
+    lea      w_reg, [.emuedge_v_extend_1 - (.emuedge_v_extend_2 - .emuedge_v_extend_1)+w_reg]
+%endif
+    call     w_reg              ; fast top extend, body copy and bottom extend
+.v_extend_end:
+
+    ; horizontal extend (left/right)
+    mov      w_reg, r6m         ; start_x
+    sub         r0, w_reg
+%ifdef ARCH_X86_64
+    mov         r3, r0          ; backup of buf+block_h*linesize
+    mov         r5, r11
+%else
+    mov        r0m, r0          ; backup of buf+block_h*linesize
+    mov         r5, r5m
+%endif
+    test     w_reg, w_reg
+    jz .right_extend
+    cmp      w_reg, 22
+    jg .slow_left_extend_loop
+    mov         r1, w_reg
+    dec      w_reg
+    ; FIXME we can do a if size == 1 here if that makes any speed difference, test me
+    sar      w_reg, 1
+    sal      w_reg, 6
+    ; r0=buf+block_h*linesize,r10(64)/r6(32)=start_x offset for funcs
+    ; r6(rax)/r3(ebx)=val,r2=linesize,r1=start_x,r5=block_h
+%ifdef PIC
+    lea        rax, [.emuedge_extend_left_2]
+    add      w_reg, rax
+%else
+    lea      w_reg, [.emuedge_extend_left_2+w_reg]
+%endif
+    call     w_reg
+
+    ; now r3(64)/r0(32)=buf,r2=linesize,r11/r5=block_h,r6/r3=val, r10/r6=end_x, r1=block_w
+.right_extend:
+%ifdef ARCH_X86_32
+    mov         r0, r0m
+    mov         r5, r5m
+%endif
+    mov      w_reg, r7m         ; end_x
+    mov         r1, r8m         ; block_w
+    mov         r4, r1
+    sub         r1, w_reg
+    jz .h_extend_end            ; if (end_x == block_w) goto h_extend_end
+    cmp         r1, 22
+    jg .slow_right_extend_loop
+    dec         r1
+    ; FIXME we can do a if size == 1 here if that makes any speed difference, test me
+    sar         r1, 1
+    sal         r1, 6
+%ifdef PIC
+    lea        rax, [.emuedge_extend_right_2]
+    add         r1, rax
+%else
+    lea         r1, [.emuedge_extend_right_2+r1]
+%endif
+    call        r1
+.h_extend_end:
+    RET
+
+%ifdef ARCH_X86_64
+%define vall  al
+%define valh  ah
+%define valw  ax
+%define valw2 r10w
+%define valw3 r3w
+%ifdef WIN64
+%define valw4 r4w
+%else ; unix64
+%define valw4 r3w
+%endif
+%define vald eax
+%else
+%define vall  bl
+%define valh  bh
+%define valw  bx
+%define valw2 r6w
+%define valw3 valw2
+%define valw4 valw3
+%define vald ebx
+%define stack_offset 0x14
+%endif
+
+%endmacro
+
+; macro to read/write a horizontal number of pixels (%2) to/from registers
+; on x86-64, - fills xmm0-15 for consecutive sets of 16 pixels
+;            - if (%2 & 15 == 8) fills the last 8 bytes into rax
+;            - else if (%2 & 8)  fills 8 bytes into mm0
+;            - if (%2 & 7 == 4)  fills the last 4 bytes into rax
+;            - else if (%2 & 4)  fills 4 bytes into mm0-1
+;            - if (%2 & 3 == 3)  fills 2 bytes into r10/r3, and 1 into eax
+;              (note that we're using r3 for body/bottom because it's a shorter
+;               opcode, and then the loop fits in 128 bytes)
+;            - else              fills remaining bytes into rax
+; on x86-32, - fills mm0-7 for consecutive sets of 8 pixels
+;            - if (%2 & 7 == 4)  fills 4 bytes into ebx
+;            - else if (%2 & 4)  fills 4 bytes into mm0-7
+;            - if (%2 & 3 == 3)  fills 2 bytes into r6, and 1 into ebx
+;            - else              fills remaining bytes into ebx
+; writing data out is in the same way
+%macro READ_NUM_BYTES 3
+%assign %%src_off 0 ; offset in source buffer
+%assign %%smidx   0 ; mmx register idx
+%assign %%sxidx   0 ; xmm register idx
+
+%ifnidn %3, mmx
+%rep %2/16
+    movdqu xmm %+ %%sxidx, [r1+%%src_off]
+%assign %%src_off %%src_off+16
+%assign %%sxidx   %%sxidx+1
+%endrep ; %2/16
+%endif ; !mmx
+
+%ifdef ARCH_X86_64
+%if (%2-%%src_off) == 8
+    mov           rax, [r1+%%src_off]
+%assign %%src_off %%src_off+8
+%endif ; (%2-%%src_off) == 8
+%endif ; x86-64
+
+%rep (%2-%%src_off)/8
+    movq    mm %+ %%smidx, [r1+%%src_off]
+%assign %%src_off %%src_off+8
+%assign %%smidx   %%smidx+1
+%endrep ; (%2-%%dst_off)/8
+
+%if (%2-%%src_off) == 4
+    mov          vald, [r1+%%src_off]
+%elif (%2-%%src_off) & 4
+    movd    mm %+ %%smidx, [r1+%%src_off]
+%assign %%src_off %%src_off+4
+%endif ; (%2-%%src_off) ==/& 4
+
+%if (%2-%%src_off) == 1
+    mov          vall, [r1+%%src_off]
+%elif (%2-%%src_off) == 2
+    mov          valw, [r1+%%src_off]
+%elif (%2-%%src_off) == 3
+%ifidn %1, top
+    mov         valw2, [r1+%%src_off]
+%elifidn %1, body
+    mov         valw3, [r1+%%src_off]
+%elifidn %1, bottom
+    mov         valw4, [r1+%%src_off]
+%endif ; %1 ==/!= top
+    mov          vall, [r1+%%src_off+2]
+%endif ; (%2-%%src_off) == 1/2/3
+%endmacro ; READ_NUM_BYTES
+
+%macro WRITE_NUM_BYTES 3
+%assign %%dst_off 0 ; offset in destination buffer
+%assign %%dmidx   0 ; mmx register idx
+%assign %%dxidx   0 ; xmm register idx
+
+%ifnidn %3, mmx
+%rep %2/16
+    movdqu [r0+%%dst_off], xmm %+ %%dxidx
+%assign %%dst_off %%dst_off+16
+%assign %%dxidx   %%dxidx+1
+%endrep ; %2/16
+%endif
+
+%ifdef ARCH_X86_64
+%if (%2-%%dst_off) == 8
+    mov    [r0+%%dst_off], rax
+%assign %%dst_off %%dst_off+8
+%endif ; (%2-%%dst_off) == 8
+%endif ; x86-64
+
+%rep (%2-%%dst_off)/8
+    movq   [r0+%%dst_off], mm %+ %%dmidx
+%assign %%dst_off %%dst_off+8
+%assign %%dmidx   %%dmidx+1
+%endrep ; (%2-%%dst_off)/8
+
+%if (%2-%%dst_off) == 4
+    mov    [r0+%%dst_off], vald
+%elif (%2-%%dst_off) & 4
+    movd   [r0+%%dst_off], mm %+ %%dmidx
+%assign %%dst_off %%dst_off+4
+%endif ; (%2-%%dst_off) ==/& 4
+
+%if (%2-%%dst_off) == 1
+    mov    [r0+%%dst_off], vall
+%elif (%2-%%dst_off) == 2
+    mov    [r0+%%dst_off], valw
+%elif (%2-%%dst_off) == 3
+%ifidn %1, top
+    mov    [r0+%%dst_off], valw2
+%elifidn %1, body
+    mov    [r0+%%dst_off], valw3
+%elifidn %1, bottom
+    mov    [r0+%%dst_off], valw4
+%endif ; %1 ==/!= top
+    mov  [r0+%%dst_off+2], vall
+%endif ; (%2-%%dst_off) == 1/2/3
+%endmacro ; WRITE_NUM_BYTES
+
+; vertical top/bottom extend and body copy fast loops
+; these are function pointers to set-width line copy functions, i.e.
+; they read a fixed number of pixels into set registers, and write
+; those out into the destination buffer
+; r0=buf,r1=src,r2=linesize,r3(64)/r3m(32)=start_x,r4=end_y,r5=block_h
+; r6(eax/64)/r3(ebx/32)=val_reg
+%macro VERTICAL_EXTEND 1
+%assign %%n 1
+%rep 22
+ALIGN 128
+.emuedge_v_extend_ %+ %%n:
+    ; extend pixels above body
+%ifdef ARCH_X86_64
+    test           r3 , r3                   ; if (!start_y)
+    jz .emuedge_copy_body_ %+ %%n %+ _loop   ;   goto body
+%else ; ARCH_X86_32
+    cmp      dword r3m, 0
+    je .emuedge_copy_body_ %+ %%n %+ _loop
+%endif ; ARCH_X86_64/32
+    READ_NUM_BYTES  top,    %%n, %1          ; read bytes
+.emuedge_extend_top_ %+ %%n %+ _loop:        ; do {
+    WRITE_NUM_BYTES top,    %%n, %1          ;   write bytes
+    add            r0 , r2                   ;   dst += linesize
+%ifdef ARCH_X86_64
+    dec            r3d
+%else ; ARCH_X86_32
+    dec      dword r3m
+%endif ; ARCH_X86_64/32
+    jnz .emuedge_extend_top_ %+ %%n %+ _loop ; } while (--start_y)
+
+    ; copy body pixels
+.emuedge_copy_body_ %+ %%n %+ _loop:         ; do {
+    READ_NUM_BYTES  body,   %%n, %1          ;   read bytes
+    WRITE_NUM_BYTES body,   %%n, %1          ;   write bytes
+    add            r0 , r2                   ;   dst += linesize
+    add            r1 , r2                   ;   src += linesize
+    dec            r4d
+    jnz .emuedge_copy_body_ %+ %%n %+ _loop  ; } while (--end_y)
+
+    ; copy bottom pixels
+    test           r5 , r5                   ; if (!block_h)
+    jz .emuedge_v_extend_end_ %+ %%n         ;   goto end
+    sub            r1 , r2                   ; src -= linesize
+    READ_NUM_BYTES  bottom, %%n, %1          ; read bytes
+.emuedge_extend_bottom_ %+ %%n %+ _loop:     ; do {
+    WRITE_NUM_BYTES bottom, %%n, %1          ;   write bytes
+    add            r0 , r2                   ;   dst += linesize
+    dec            r5d
+    jnz .emuedge_extend_bottom_ %+ %%n %+ _loop ; } while (--block_h)
+
+.emuedge_v_extend_end_ %+ %%n:
+%ifdef ARCH_X86_64
+    ret
+%else ; ARCH_X86_32
+    rep ret
+%endif ; ARCH_X86_64/32
+%assign %%n %%n+1
+%endrep
+%endmacro VERTICAL_EXTEND
+
+; left/right (horizontal) fast extend functions
+; these are essentially identical to the vertical extend ones above,
+; just left/right separated because number of pixels to extend is
+; obviously not the same on both sides.
+; for reading, pixels are placed in eax (x86-64) or ebx (x86-64) in the
+; lowest two bytes of the register (so val*0x0101), and are splatted
+; into each byte of mm0 as well if n_pixels >= 8
+
+%macro READ_V_PIXEL 3
+    mov        vall, %2
+    mov        valh, vall
+%if %1 >= 8
+    movd        mm0, vald
+%ifidn %3, mmx
+    punpcklwd   mm0, mm0
+    punpckldq   mm0, mm0
+%else ; !mmx
+    pshufw      mm0, mm0, 0
+%endif ; mmx
+%endif ; %1 >= 8
+%endmacro
+
+%macro WRITE_V_PIXEL 2
+%assign %%dst_off 0
+%rep %1/8
+    movq [%2+%%dst_off], mm0
+%assign %%dst_off %%dst_off+8
+%endrep
+%if %1 & 4
+%if %1 >= 8
+    movd [%2+%%dst_off], mm0
+%else ; %1 < 8
+    mov  [%2+%%dst_off]  , valw
+    mov  [%2+%%dst_off+2], valw
+%endif ; %1 >=/< 8
+%assign %%dst_off %%dst_off+4
+%endif ; %1 & 4
+%if %1&2
+    mov  [%2+%%dst_off], valw
+%endif ; %1 & 2
+%endmacro
+
+; r0=buf+block_h*linesize, r1=start_x, r2=linesize, r5=block_h, r6/r3=val
+%macro LEFT_EXTEND 1
+%assign %%n 2
+%rep 11
+ALIGN 64
+.emuedge_extend_left_ %+ %%n:          ; do {
+    sub         r0, r2                 ;   dst -= linesize
+    READ_V_PIXEL  %%n, [r0+r1], %1     ;   read pixels
+    WRITE_V_PIXEL %%n, r0              ;   write pixels
+    dec         r5
+    jnz .emuedge_extend_left_ %+ %%n   ; } while (--block_h)
+%ifdef ARCH_X86_64
+    ret
+%else ; ARCH_X86_32
+    rep ret
+%endif ; ARCH_X86_64/32
+%assign %%n %%n+2
+%endrep
+%endmacro ; LEFT_EXTEND
+
+; r3/r0=buf+block_h*linesize, r2=linesize, r11/r5=block_h, r0/r6=end_x, r6/r3=val
+%macro RIGHT_EXTEND 1
+%assign %%n 2
+%rep 11
+ALIGN 64
+.emuedge_extend_right_ %+ %%n:          ; do {
+%ifdef ARCH_X86_64
+    sub        r3, r2                   ;   dst -= linesize
+    READ_V_PIXEL  %%n, [r3+w_reg-1], %1 ;   read pixels
+    WRITE_V_PIXEL %%n, r3+r4-%%n        ;   write pixels
+    dec       r11
+%else ; ARCH_X86_32
+    sub        r0, r2                   ;   dst -= linesize
+    READ_V_PIXEL  %%n, [r0+w_reg-1], %1 ;   read pixels
+    WRITE_V_PIXEL %%n, r0+r4-%%n        ;   write pixels
+    dec     r5
+%endif ; ARCH_X86_64/32
+    jnz .emuedge_extend_right_ %+ %%n   ; } while (--block_h)
+%ifdef ARCH_X86_64
+    ret
+%else ; ARCH_X86_32
+    rep ret
+%endif ; ARCH_X86_64/32
+%assign %%n %%n+2
+%endrep
+
+%ifdef ARCH_X86_32
+%define stack_offset 0x10
+%endif
+%endmacro ; RIGHT_EXTEND
+
+; below follow the "slow" copy/extend functions, these act on a non-fixed
+; width specified in a register, and run a loop to copy the full amount
+; of bytes. They are optimized for copying of large amounts of pixels per
+; line, so they unconditionally splat data into mm registers to copy 8
+; bytes per loop iteration. It could be considered to use xmm for x86-64
+; also, but I haven't optimized this as much (i.e. FIXME)
+%macro V_COPY_NPX 4-5
+%if %0 == 4
+    test     w_reg, %4
+    jz .%1_skip_%4_px
+%else ; %0 == 5
+.%1_%4_px_loop:
+%endif
+    %3          %2, [r1+cnt_reg]
+    %3 [r0+cnt_reg], %2
+    add    cnt_reg, %4
+%if %0 == 5
+    sub      w_reg, %4
+    test     w_reg, %5
+    jnz .%1_%4_px_loop
+%endif
+.%1_skip_%4_px:
+%endmacro
+
+%macro V_COPY_ROW 3
+%ifidn %1, bottom
+    sub         r1, linesize
+%endif
+.%1_copy_loop:
+    xor    cnt_reg, cnt_reg
+%ifidn %3, mmx
+%define linesize r2m
+    V_COPY_NPX %1,  mm0, movq,    8, 0xFFFFFFF8
+%else ; !mmx
+    V_COPY_NPX %1, xmm0, movdqu, 16, 0xFFFFFFF0
+%ifdef ARCH_X86_64
+%define linesize r2
+    V_COPY_NPX %1, rax , mov,     8
+%else ; ARCH_X86_32
+%define linesize r2m
+    V_COPY_NPX %1,  mm0, movq,    8
+%endif ; ARCH_X86_64/32
+%endif ; mmx
+    V_COPY_NPX %1, vald, mov,     4
+    V_COPY_NPX %1, valw, mov,     2
+    V_COPY_NPX %1, vall, mov,     1
+    mov      w_reg, cnt_reg
+%ifidn %1, body
+    add         r1, linesize
+%endif
+    add         r0, linesize
+    dec         %2
+    jnz .%1_copy_loop
+%endmacro
+
+%macro SLOW_V_EXTEND 1
+.slow_v_extend_loop:
+; r0=buf,r1=src,r2(64)/r2m(32)=linesize,r3(64)/r3m(32)=start_x,r4=end_y,r5=block_h
+; r11(64)/r3(later-64)/r2(32)=cnt_reg,r6(64)/r3(32)=val_reg,r10(64)/r6(32)=w=end_x-start_x
+%ifdef ARCH_X86_64
+    push       r11              ; save old value of block_h
+    test        r3, r3
+%define cnt_reg r11
+    jz .do_body_copy            ; if (!start_y) goto do_body_copy
+    V_COPY_ROW top, r3, %1
+%else
+    cmp  dword r3m, 0
+%define cnt_reg r2
+    je .do_body_copy            ; if (!start_y) goto do_body_copy
+    V_COPY_ROW top, dword r3m, %1
+%endif
+
+.do_body_copy:
+    V_COPY_ROW body, r4, %1
+
+%ifdef ARCH_X86_64
+    pop        r11              ; restore old value of block_h
+%define cnt_reg r3
+%endif
+    test        r5, r5
+%ifdef ARCH_X86_64
+    jz .v_extend_end
+%else
+    jz .skip_bottom_extend
+%endif
+    V_COPY_ROW bottom, r5, %1
+%ifdef ARCH_X86_32
+.skip_bottom_extend:
+    mov         r2, r2m
+%endif
+    jmp .v_extend_end
+%endmacro
+
+%macro SLOW_LEFT_EXTEND 1
+.slow_left_extend_loop:
+; r0=buf+block_h*linesize,r2=linesize,r6(64)/r3(32)=val,r5=block_h,r4=cntr,r10/r6=start_x
+    mov         r4, 8
+    sub         r0, linesize
+    READ_V_PIXEL 8, [r0+w_reg], %1
+.left_extend_8px_loop:
+    movq [r0+r4-8], mm0
+    add         r4, 8
+    cmp         r4, w_reg
+    jle .left_extend_8px_loop
+    sub         r4, 8
+    cmp         r4, w_reg
+    jge .left_extend_loop_end
+.left_extend_2px_loop:
+    mov    [r0+r4], valw
+    add         r4, 2
+    cmp         r4, w_reg
+    jl .left_extend_2px_loop
+.left_extend_loop_end:
+    dec         r5
+    jnz .slow_left_extend_loop
+%ifdef ARCH_X86_32
+    mov         r2, r2m
+%endif
+    jmp .right_extend
+%endmacro
+
+%macro SLOW_RIGHT_EXTEND 1
+.slow_right_extend_loop:
+; r3(64)/r0(32)=buf+block_h*linesize,r2=linesize,r4=block_w,r11(64)/r5(32)=block_h,
+; r10(64)/r6(32)=end_x,r6/r3=val,r1=cntr
+%ifdef ARCH_X86_64
+%define buf_reg r3
+%define bh_reg r11
+%else
+%define buf_reg r0
+%define bh_reg r5
+%endif
+    lea         r1, [r4-8]
+    sub    buf_reg, linesize
+    READ_V_PIXEL 8, [buf_reg+w_reg-1], %1
+.right_extend_8px_loop:
+    movq [buf_reg+r1], mm0
+    sub         r1, 8
+    cmp         r1, w_reg
+    jge .right_extend_8px_loop
+    add         r1, 8
+    cmp         r1, w_reg
+    je .right_extend_loop_end
+.right_extend_2px_loop:
+    sub         r1, 2
+    mov [buf_reg+r1], valw
+    cmp         r1, w_reg
+    jg .right_extend_2px_loop
+.right_extend_loop_end:
+    dec         bh_reg
+    jnz .slow_right_extend_loop
+    jmp .h_extend_end
+%endmacro
+
+%macro emu_edge 1
+EMU_EDGE_FUNC     %1
+VERTICAL_EXTEND   %1
+LEFT_EXTEND       %1
+RIGHT_EXTEND      %1
+SLOW_V_EXTEND     %1
+SLOW_LEFT_EXTEND  %1
+SLOW_RIGHT_EXTEND %1
+%endmacro
+
+emu_edge sse
+%ifdef ARCH_X86_32
+emu_edge mmx
+%endif
diff --git a/libavcodec/x86/dsputilenc_mmx.c b/libavcodec/x86/dsputilenc_mmx.c
index f491111..0373891 100644
--- a/libavcodec/x86/dsputilenc_mmx.c
+++ b/libavcodec/x86/dsputilenc_mmx.c
@@ -3,25 +3,26 @@
  * Copyright (c) 2000, 2001 Fabrice Bellard
  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  *
  * MMX optimization by Nick Kurshev <nickols_k at mail.ru>
  */
 
+#include "libavutil/cpu.h"
 #include "libavutil/x86_cpu.h"
 #include "libavcodec/dsputil.h"
 #include "libavcodec/mpegvideo.h"
@@ -34,7 +35,7 @@ static void get_pixels_mmx(DCTELEM *block, const uint8_t *pixels, int line_size)
     __asm__ volatile(
         "mov $-128, %%"REG_a"           \n\t"
         "pxor %%mm7, %%mm7              \n\t"
-        ASMALIGN(4)
+        ".p2align 4                     \n\t"
         "1:                             \n\t"
         "movq (%0), %%mm0               \n\t"
         "movq (%0, %2), %%mm2           \n\t"
@@ -60,16 +61,16 @@ static void get_pixels_mmx(DCTELEM *block, const uint8_t *pixels, int line_size)
 static void get_pixels_sse2(DCTELEM *block, const uint8_t *pixels, int line_size)
 {
     __asm__ volatile(
-        "pxor %%xmm7,      %%xmm7         \n\t"
+        "pxor %%xmm4,      %%xmm4         \n\t"
         "movq (%0),        %%xmm0         \n\t"
         "movq (%0, %2),    %%xmm1         \n\t"
         "movq (%0, %2,2),  %%xmm2         \n\t"
         "movq (%0, %3),    %%xmm3         \n\t"
         "lea (%0,%2,4), %0                \n\t"
-        "punpcklbw %%xmm7, %%xmm0         \n\t"
-        "punpcklbw %%xmm7, %%xmm1         \n\t"
-        "punpcklbw %%xmm7, %%xmm2         \n\t"
-        "punpcklbw %%xmm7, %%xmm3         \n\t"
+        "punpcklbw %%xmm4, %%xmm0         \n\t"
+        "punpcklbw %%xmm4, %%xmm1         \n\t"
+        "punpcklbw %%xmm4, %%xmm2         \n\t"
+        "punpcklbw %%xmm4, %%xmm3         \n\t"
         "movdqa %%xmm0,      (%1)         \n\t"
         "movdqa %%xmm1,    16(%1)         \n\t"
         "movdqa %%xmm2,    32(%1)         \n\t"
@@ -78,10 +79,10 @@ static void get_pixels_sse2(DCTELEM *block, const uint8_t *pixels, int line_size
         "movq (%0, %2),    %%xmm1         \n\t"
         "movq (%0, %2,2),  %%xmm2         \n\t"
         "movq (%0, %3),    %%xmm3         \n\t"
-        "punpcklbw %%xmm7, %%xmm0         \n\t"
-        "punpcklbw %%xmm7, %%xmm1         \n\t"
-        "punpcklbw %%xmm7, %%xmm2         \n\t"
-        "punpcklbw %%xmm7, %%xmm3         \n\t"
+        "punpcklbw %%xmm4, %%xmm0         \n\t"
+        "punpcklbw %%xmm4, %%xmm1         \n\t"
+        "punpcklbw %%xmm4, %%xmm2         \n\t"
+        "punpcklbw %%xmm4, %%xmm3         \n\t"
         "movdqa %%xmm0,    64(%1)         \n\t"
         "movdqa %%xmm1,    80(%1)         \n\t"
         "movdqa %%xmm2,    96(%1)         \n\t"
@@ -96,7 +97,7 @@ static inline void diff_pixels_mmx(DCTELEM *block, const uint8_t *s1, const uint
     __asm__ volatile(
         "pxor %%mm7, %%mm7              \n\t"
         "mov $-128, %%"REG_a"           \n\t"
-        ASMALIGN(4)
+        ".p2align 4                     \n\t"
         "1:                             \n\t"
         "movq (%0), %%mm0               \n\t"
         "movq (%1), %%mm2               \n\t"
@@ -322,67 +323,7 @@ static int sse16_mmx(void *v, uint8_t * pix1, uint8_t * pix2, int line_size, int
     return tmp;
 }
 
-static int sse16_sse2(void *v, uint8_t * pix1, uint8_t * pix2, int line_size, int h) {
-    int tmp;
-  __asm__ volatile (
-      "shr $1,%2\n"
-      "pxor %%xmm0,%%xmm0\n"    /* mm0 = 0 */
-      "pxor %%xmm7,%%xmm7\n"    /* mm7 holds the sum */
-      "1:\n"
-      "movdqu (%0),%%xmm1\n"    /* mm1 = pix1[0][0-15] */
-      "movdqu (%1),%%xmm2\n"    /* mm2 = pix2[0][0-15] */
-      "movdqu (%0,%4),%%xmm3\n" /* mm3 = pix1[1][0-15] */
-      "movdqu (%1,%4),%%xmm4\n" /* mm4 = pix2[1][0-15] */
-
-      /* todo: mm1-mm2, mm3-mm4 */
-      /* algo: subtract mm1 from mm2 with saturation and vice versa */
-      /*       OR the results to get absolute difference */
-      "movdqa %%xmm1,%%xmm5\n"
-      "movdqa %%xmm3,%%xmm6\n"
-      "psubusb %%xmm2,%%xmm1\n"
-      "psubusb %%xmm4,%%xmm3\n"
-      "psubusb %%xmm5,%%xmm2\n"
-      "psubusb %%xmm6,%%xmm4\n"
-
-      "por %%xmm1,%%xmm2\n"
-      "por %%xmm3,%%xmm4\n"
-
-      /* now convert to 16-bit vectors so we can square them */
-      "movdqa %%xmm2,%%xmm1\n"
-      "movdqa %%xmm4,%%xmm3\n"
-
-      "punpckhbw %%xmm0,%%xmm2\n"
-      "punpckhbw %%xmm0,%%xmm4\n"
-      "punpcklbw %%xmm0,%%xmm1\n"  /* mm1 now spread over (mm1,mm2) */
-      "punpcklbw %%xmm0,%%xmm3\n"  /* mm4 now spread over (mm3,mm4) */
-
-      "pmaddwd %%xmm2,%%xmm2\n"
-      "pmaddwd %%xmm4,%%xmm4\n"
-      "pmaddwd %%xmm1,%%xmm1\n"
-      "pmaddwd %%xmm3,%%xmm3\n"
-
-      "lea (%0,%4,2), %0\n"        /* pix1 += 2*line_size */
-      "lea (%1,%4,2), %1\n"        /* pix2 += 2*line_size */
-
-      "paddd %%xmm2,%%xmm1\n"
-      "paddd %%xmm4,%%xmm3\n"
-      "paddd %%xmm1,%%xmm7\n"
-      "paddd %%xmm3,%%xmm7\n"
-
-      "decl %2\n"
-      "jnz 1b\n"
-
-      "movdqa %%xmm7,%%xmm1\n"
-      "psrldq $8, %%xmm7\n"        /* shift hi qword to lo */
-      "paddd %%xmm1,%%xmm7\n"
-      "movdqa %%xmm7,%%xmm1\n"
-      "psrldq $4, %%xmm7\n"        /* shift hi dword to lo */
-      "paddd %%xmm1,%%xmm7\n"
-      "movd %%xmm7,%3\n"
-      : "+r" (pix1), "+r" (pix2), "+r"(h), "=r"(tmp)
-      : "r" ((x86_reg)line_size));
-    return tmp;
-}
+int ff_sse16_sse2(void *v, uint8_t * pix1, uint8_t * pix2, int line_size, int h);
 
 static int hf_noise8_mmx(uint8_t * pix1, int line_size, int h) {
     int tmp;
@@ -938,55 +879,6 @@ static void sub_hfyu_median_prediction_mmx2(uint8_t *dst, const uint8_t *src1, c
     *left    = src2[w-1];
 }
 
-#define DIFF_PIXELS_1(m,a,t,p1,p2)\
-    "mov"#m" "#p1", "#a"              \n\t"\
-    "mov"#m" "#p2", "#t"              \n\t"\
-    "punpcklbw "#a", "#t"             \n\t"\
-    "punpcklbw "#a", "#a"             \n\t"\
-    "psubw     "#t", "#a"             \n\t"\
-
-#define DIFF_PIXELS_8(m0,m1,mm,p1,p2,stride,temp) {\
-    uint8_t *p1b=p1, *p2b=p2;\
-    __asm__ volatile(\
-        DIFF_PIXELS_1(m0, mm##0, mm##7, (%1), (%2))\
-        DIFF_PIXELS_1(m0, mm##1, mm##7, (%1,%3), (%2,%3))\
-        DIFF_PIXELS_1(m0, mm##2, mm##7, (%1,%3,2), (%2,%3,2))\
-        "add %4, %1                   \n\t"\
-        "add %4, %2                   \n\t"\
-        DIFF_PIXELS_1(m0, mm##3, mm##7, (%1), (%2))\
-        DIFF_PIXELS_1(m0, mm##4, mm##7, (%1,%3), (%2,%3))\
-        DIFF_PIXELS_1(m0, mm##5, mm##7, (%1,%3,2), (%2,%3,2))\
-        DIFF_PIXELS_1(m0, mm##6, mm##7, (%1,%4), (%2,%4))\
-        "mov"#m1" "#mm"0, %0          \n\t"\
-        DIFF_PIXELS_1(m0, mm##7, mm##0, (%1,%3,4), (%2,%3,4))\
-        "mov"#m1" %0, "#mm"0          \n\t"\
-        : "+m"(temp), "+r"(p1b), "+r"(p2b)\
-        : "r"((x86_reg)stride), "r"((x86_reg)stride*3)\
-    );\
-}
-    //the "+m"(temp) is needed as gcc 2.95 sometimes fails to compile "=m"(temp)
-
-#define DIFF_PIXELS_4x8(p1,p2,stride,temp) DIFF_PIXELS_8(d, q,   %%mm,  p1, p2, stride, temp)
-#define DIFF_PIXELS_8x8(p1,p2,stride,temp) DIFF_PIXELS_8(q, dqa, %%xmm, p1, p2, stride, temp)
-
-#define LBUTTERFLY2(a1,b1,a2,b2)\
-    "paddw " #b1 ", " #a1 "           \n\t"\
-    "paddw " #b2 ", " #a2 "           \n\t"\
-    "paddw " #b1 ", " #b1 "           \n\t"\
-    "paddw " #b2 ", " #b2 "           \n\t"\
-    "psubw " #a1 ", " #b1 "           \n\t"\
-    "psubw " #a2 ", " #b2 "           \n\t"
-
-#define HADAMARD8(m0, m1, m2, m3, m4, m5, m6, m7)\
-        LBUTTERFLY2(m0, m1, m2, m3)\
-        LBUTTERFLY2(m4, m5, m6, m7)\
-        LBUTTERFLY2(m0, m2, m1, m3)\
-        LBUTTERFLY2(m4, m6, m5, m7)\
-        LBUTTERFLY2(m0, m4, m1, m5)\
-        LBUTTERFLY2(m2, m6, m3, m7)\
-
-#define HADAMARD48 HADAMARD8(%%mm0, %%mm1, %%mm2, %%mm3, %%mm4, %%mm5, %%mm6, %%mm7)
-
 #define MMABS_MMX(a,z)\
     "pxor " #z ", " #z "              \n\t"\
     "pcmpgtw " #a ", " #z "           \n\t"\
@@ -1005,34 +897,6 @@ static void sub_hfyu_median_prediction_mmx2(uint8_t *dst, const uint8_t *src1, c
     MMABS(a,z)\
     "paddusw " #a ", " #sum "         \n\t"
 
-#define MMABS_SUM_8x8_NOSPILL\
-    MMABS(%%xmm0, %%xmm8)\
-    MMABS(%%xmm1, %%xmm9)\
-    MMABS_SUM(%%xmm2, %%xmm8, %%xmm0)\
-    MMABS_SUM(%%xmm3, %%xmm9, %%xmm1)\
-    MMABS_SUM(%%xmm4, %%xmm8, %%xmm0)\
-    MMABS_SUM(%%xmm5, %%xmm9, %%xmm1)\
-    MMABS_SUM(%%xmm6, %%xmm8, %%xmm0)\
-    MMABS_SUM(%%xmm7, %%xmm9, %%xmm1)\
-    "paddusw %%xmm1, %%xmm0           \n\t"
-
-#if ARCH_X86_64
-#define MMABS_SUM_8x8_SSE2 MMABS_SUM_8x8_NOSPILL
-#else
-#define MMABS_SUM_8x8_SSE2\
-    "movdqa %%xmm7, (%1)              \n\t"\
-    MMABS(%%xmm0, %%xmm7)\
-    MMABS(%%xmm1, %%xmm7)\
-    MMABS_SUM(%%xmm2, %%xmm7, %%xmm0)\
-    MMABS_SUM(%%xmm3, %%xmm7, %%xmm1)\
-    MMABS_SUM(%%xmm4, %%xmm7, %%xmm0)\
-    MMABS_SUM(%%xmm5, %%xmm7, %%xmm1)\
-    MMABS_SUM(%%xmm6, %%xmm7, %%xmm0)\
-    "movdqa (%1), %%xmm2              \n\t"\
-    MMABS_SUM(%%xmm2, %%xmm7, %%xmm1)\
-    "paddusw %%xmm1, %%xmm0           \n\t"
-#endif
-
 /* FIXME: HSUM_* saturates at 64k, while an 8x8 hadamard or dct block can get up to
  * about 100k on extreme inputs. But that's very unlikely to occur in natural video,
  * and it's even more unlikely to not have any alternative mvs/modes with lower cost. */
@@ -1061,133 +925,16 @@ static void sub_hfyu_median_prediction_mmx2(uint8_t *dst, const uint8_t *src1, c
     "paddusw "#t", "#a"               \n\t"\
     "movd "#a", "#dst"                \n\t"\
 
-#define HADAMARD8_DIFF_MMX(cpu) \
-static int hadamard8_diff_##cpu(void *s, uint8_t *src1, uint8_t *src2, int stride, int h){\
-    DECLARE_ALIGNED(8, uint64_t, temp)[13];\
-    int sum;\
-\
-    assert(h==8);\
-\
-    DIFF_PIXELS_4x8(src1, src2, stride, temp[0]);\
-\
-    __asm__ volatile(\
-        HADAMARD48\
-\
-        "movq %%mm7, 96(%1)             \n\t"\
-\
-        TRANSPOSE4(%%mm0, %%mm1, %%mm2, %%mm3, %%mm7)\
-        STORE4(8,  0(%1), %%mm0, %%mm3, %%mm7, %%mm2)\
-\
-        "movq 96(%1), %%mm7             \n\t"\
-        TRANSPOSE4(%%mm4, %%mm5, %%mm6, %%mm7, %%mm0)\
-        STORE4(8, 64(%1), %%mm4, %%mm7, %%mm0, %%mm6)\
-\
-        : "=r" (sum)\
-        : "r"(temp)\
-    );\
-\
-    DIFF_PIXELS_4x8(src1+4, src2+4, stride, temp[4]);\
-\
-    __asm__ volatile(\
-        HADAMARD48\
-\
-        "movq %%mm7, 96(%1)             \n\t"\
-\
-        TRANSPOSE4(%%mm0, %%mm1, %%mm2, %%mm3, %%mm7)\
-        STORE4(8, 32(%1), %%mm0, %%mm3, %%mm7, %%mm2)\
-\
-        "movq 96(%1), %%mm7             \n\t"\
-        TRANSPOSE4(%%mm4, %%mm5, %%mm6, %%mm7, %%mm0)\
-        "movq %%mm7, %%mm5              \n\t"/*FIXME remove*/\
-        "movq %%mm6, %%mm7              \n\t"\
-        "movq %%mm0, %%mm6              \n\t"\
-\
-        LOAD4(8, 64(%1), %%mm0, %%mm1, %%mm2, %%mm3)\
-\
-        HADAMARD48\
-        "movq %%mm7, 64(%1)             \n\t"\
-        MMABS(%%mm0, %%mm7)\
-        MMABS(%%mm1, %%mm7)\
-        MMABS_SUM(%%mm2, %%mm7, %%mm0)\
-        MMABS_SUM(%%mm3, %%mm7, %%mm1)\
-        MMABS_SUM(%%mm4, %%mm7, %%mm0)\
-        MMABS_SUM(%%mm5, %%mm7, %%mm1)\
-        MMABS_SUM(%%mm6, %%mm7, %%mm0)\
-        "movq 64(%1), %%mm2             \n\t"\
-        MMABS_SUM(%%mm2, %%mm7, %%mm1)\
-        "paddusw %%mm1, %%mm0           \n\t"\
-        "movq %%mm0, 64(%1)             \n\t"\
-\
-        LOAD4(8,  0(%1), %%mm0, %%mm1, %%mm2, %%mm3)\
-        LOAD4(8, 32(%1), %%mm4, %%mm5, %%mm6, %%mm7)\
-\
-        HADAMARD48\
-        "movq %%mm7, (%1)               \n\t"\
-        MMABS(%%mm0, %%mm7)\
-        MMABS(%%mm1, %%mm7)\
-        MMABS_SUM(%%mm2, %%mm7, %%mm0)\
-        MMABS_SUM(%%mm3, %%mm7, %%mm1)\
-        MMABS_SUM(%%mm4, %%mm7, %%mm0)\
-        MMABS_SUM(%%mm5, %%mm7, %%mm1)\
-        MMABS_SUM(%%mm6, %%mm7, %%mm0)\
-        "movq (%1), %%mm2               \n\t"\
-        MMABS_SUM(%%mm2, %%mm7, %%mm1)\
-        "paddusw 64(%1), %%mm0          \n\t"\
-        "paddusw %%mm1, %%mm0           \n\t"\
-\
-        HSUM(%%mm0, %%mm1, %0)\
-\
-        : "=r" (sum)\
-        : "r"(temp)\
-    );\
-    return sum&0xFFFF;\
-}\
-WRAPPER8_16_SQ(hadamard8_diff_##cpu, hadamard8_diff16_##cpu)
+#define hadamard_func(cpu) \
+int ff_hadamard8_diff_##cpu  (void *s, uint8_t *src1, uint8_t *src2, \
+                              int stride, int h); \
+int ff_hadamard8_diff16_##cpu(void *s, uint8_t *src1, uint8_t *src2, \
+                              int stride, int h);
 
-#define HADAMARD8_DIFF_SSE2(cpu) \
-static int hadamard8_diff_##cpu(void *s, uint8_t *src1, uint8_t *src2, int stride, int h){\
-    DECLARE_ALIGNED(16, uint64_t, temp)[4];\
-    int sum;\
-\
-    assert(h==8);\
-\
-    DIFF_PIXELS_8x8(src1, src2, stride, temp[0]);\
-\
-    __asm__ volatile(\
-        HADAMARD8(%%xmm0, %%xmm1, %%xmm2, %%xmm3, %%xmm4, %%xmm5, %%xmm6, %%xmm7)\
-        TRANSPOSE8(%%xmm0, %%xmm1, %%xmm2, %%xmm3, %%xmm4, %%xmm5, %%xmm6, %%xmm7, (%1))\
-        HADAMARD8(%%xmm0, %%xmm5, %%xmm7, %%xmm3, %%xmm6, %%xmm4, %%xmm2, %%xmm1)\
-        MMABS_SUM_8x8\
-        HSUM_SSE2(%%xmm0, %%xmm1, %0)\
-        : "=r" (sum)\
-        : "r"(temp)\
-    );\
-    return sum&0xFFFF;\
-}\
-WRAPPER8_16_SQ(hadamard8_diff_##cpu, hadamard8_diff16_##cpu)
-
-#define MMABS(a,z)         MMABS_MMX(a,z)
-#define HSUM(a,t,dst)      HSUM_MMX(a,t,dst)
-HADAMARD8_DIFF_MMX(mmx)
-#undef MMABS
-#undef HSUM
-
-#define MMABS(a,z)         MMABS_MMX2(a,z)
-#define MMABS_SUM_8x8      MMABS_SUM_8x8_SSE2
-#define HSUM(a,t,dst)      HSUM_MMX2(a,t,dst)
-HADAMARD8_DIFF_MMX(mmx2)
-HADAMARD8_DIFF_SSE2(sse2)
-#undef MMABS
-#undef MMABS_SUM_8x8
-#undef HSUM
-
-#if HAVE_SSSE3
-#define MMABS(a,z)         MMABS_SSSE3(a,z)
-#define MMABS_SUM_8x8      MMABS_SUM_8x8_NOSPILL
-HADAMARD8_DIFF_SSE2(ssse3)
-#undef MMABS
-#undef MMABS_SUM_8x8
-#endif
+hadamard_func(mmx)
+hadamard_func(mmx2)
+hadamard_func(sse2)
+hadamard_func(ssse3)
 
 #define DCT_SAD4(m,mm,o)\
     "mov"#m" "#o"+ 0(%1), "#mm"2      \n\t"\
@@ -1350,12 +1097,14 @@ static int ssd_int8_vs_int16_mmx(const int8_t *pix1, const int16_t *pix2, int si
 
 void dsputilenc_init_mmx(DSPContext* c, AVCodecContext *avctx)
 {
-    if (mm_flags & FF_MM_MMX) {
+    int mm_flags = av_get_cpu_flags();
+
+    if (mm_flags & AV_CPU_FLAG_MMX) {
         const int dct_algo = avctx->dct_algo;
         if(dct_algo==FF_DCT_AUTO || dct_algo==FF_DCT_MMX){
-            if(mm_flags & FF_MM_SSE2){
+            if(mm_flags & AV_CPU_FLAG_SSE2){
                 c->fdct = ff_fdct_sse2;
-            }else if(mm_flags & FF_MM_MMX2){
+            }else if(mm_flags & AV_CPU_FLAG_MMX2){
                 c->fdct = ff_fdct_mmx2;
             }else{
                 c->fdct = ff_fdct_mmx;
@@ -1369,11 +1118,13 @@ void dsputilenc_init_mmx(DSPContext* c, AVCodecContext *avctx)
         c->diff_bytes= diff_bytes_mmx;
         c->sum_abs_dctelem= sum_abs_dctelem_mmx;
 
-        c->hadamard8_diff[0]= hadamard8_diff16_mmx;
-        c->hadamard8_diff[1]= hadamard8_diff_mmx;
+#if HAVE_YASM
+        c->hadamard8_diff[0]= ff_hadamard8_diff16_mmx;
+        c->hadamard8_diff[1]= ff_hadamard8_diff_mmx;
+#endif
 
         c->pix_norm1 = pix_norm1_mmx;
-        c->sse[0] = (mm_flags & FF_MM_SSE2) ? sse16_sse2 : sse16_mmx;
+        c->sse[0] = (HAVE_YASM && mm_flags & AV_CPU_FLAG_SSE2) ? ff_sse16_sse2 : sse16_mmx;
           c->sse[1] = sse8_mmx;
         c->vsad[4]= vsad_intra16_mmx;
 
@@ -1391,10 +1142,12 @@ void dsputilenc_init_mmx(DSPContext* c, AVCodecContext *avctx)
         c->ssd_int8_vs_int16 = ssd_int8_vs_int16_mmx;
 
 
-        if (mm_flags & FF_MM_MMX2) {
+        if (mm_flags & AV_CPU_FLAG_MMX2) {
             c->sum_abs_dctelem= sum_abs_dctelem_mmx2;
-            c->hadamard8_diff[0]= hadamard8_diff16_mmx2;
-            c->hadamard8_diff[1]= hadamard8_diff_mmx2;
+#if HAVE_YASM
+            c->hadamard8_diff[0]= ff_hadamard8_diff16_mmx2;
+            c->hadamard8_diff[1]= ff_hadamard8_diff_mmx2;
+#endif
             c->vsad[4]= vsad_intra16_mmx2;
 
             if(!(avctx->flags & CODEC_FLAG_BITEXACT)){
@@ -1404,29 +1157,30 @@ void dsputilenc_init_mmx(DSPContext* c, AVCodecContext *avctx)
             c->sub_hfyu_median_prediction= sub_hfyu_median_prediction_mmx2;
         }
 
-        if(mm_flags & FF_MM_SSE2){
+        if(mm_flags & AV_CPU_FLAG_SSE2){
             c->get_pixels = get_pixels_sse2;
             c->sum_abs_dctelem= sum_abs_dctelem_sse2;
-            c->hadamard8_diff[0]= hadamard8_diff16_sse2;
-            c->hadamard8_diff[1]= hadamard8_diff_sse2;
-#if CONFIG_LPC
-            c->lpc_compute_autocorr = ff_lpc_compute_autocorr_sse2;
+#if HAVE_YASM && HAVE_ALIGNED_STACK
+            c->hadamard8_diff[0]= ff_hadamard8_diff16_sse2;
+            c->hadamard8_diff[1]= ff_hadamard8_diff_sse2;
 #endif
         }
 
 #if HAVE_SSSE3
-        if(mm_flags & FF_MM_SSSE3){
+        if(mm_flags & AV_CPU_FLAG_SSSE3){
             if(!(avctx->flags & CODEC_FLAG_BITEXACT)){
                 c->try_8x8basis= try_8x8basis_ssse3;
             }
             c->add_8x8basis= add_8x8basis_ssse3;
             c->sum_abs_dctelem= sum_abs_dctelem_ssse3;
-            c->hadamard8_diff[0]= hadamard8_diff16_ssse3;
-            c->hadamard8_diff[1]= hadamard8_diff_ssse3;
+#if HAVE_YASM && HAVE_ALIGNED_STACK
+            c->hadamard8_diff[0]= ff_hadamard8_diff16_ssse3;
+            c->hadamard8_diff[1]= ff_hadamard8_diff_ssse3;
+#endif
         }
 #endif
 
-        if(mm_flags & FF_MM_3DNOW){
+        if(mm_flags & AV_CPU_FLAG_3DNOW){
             if(!(avctx->flags & CODEC_FLAG_BITEXACT)){
                 c->try_8x8basis= try_8x8basis_3dnow;
             }
diff --git a/libavcodec/x86/dsputilenc_yasm.asm b/libavcodec/x86/dsputilenc_yasm.asm
new file mode 100644
index 0000000..eddfd36
--- /dev/null
+++ b/libavcodec/x86/dsputilenc_yasm.asm
@@ -0,0 +1,342 @@
+;*****************************************************************************
+;* MMX optimized DSP utils
+;*****************************************************************************
+;* Copyright (c) 2000, 2001 Fabrice Bellard
+;* Copyright (c) 2002-2004 Michael Niedermayer <michaelni at gmx.at>
+;*
+;* This file is part of Libav.
+;*
+;* Libav is free software; you can redistribute it and/or
+;* modify it under the terms of the GNU Lesser General Public
+;* License as published by the Free Software Foundation; either
+;* version 2.1 of the License, or (at your option) any later version.
+;*
+;* Libav is distributed in the hope that it will be useful,
+;* but WITHOUT ANY WARRANTY; without even the implied warranty of
+;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+;* Lesser General Public License for more details.
+;*
+;* You should have received a copy of the GNU Lesser General Public
+;* License along with Libav; if not, write to the Free Software
+;* 51, Inc., Foundation Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+;*****************************************************************************
+
+%include "x86inc.asm"
+%include "x86util.asm"
+
+SECTION .text
+
+%macro DIFF_PIXELS_1 4
+    movh            %1, %3
+    movh            %2, %4
+    punpcklbw       %2, %1
+    punpcklbw       %1, %1
+    psubw           %1, %2
+%endmacro
+
+; %1=uint8_t *pix1, %2=uint8_t *pix2, %3=static offset, %4=stride, %5=stride*3
+; %6=temporary storage location
+; this macro requires $mmsize stack space (aligned) on %6 (except on SSE+x86-64)
+%macro DIFF_PIXELS_8 6
+    DIFF_PIXELS_1   m0, m7, [%1     +%3], [%2     +%3]
+    DIFF_PIXELS_1   m1, m7, [%1+%4  +%3], [%2+%4  +%3]
+    DIFF_PIXELS_1   m2, m7, [%1+%4*2+%3], [%2+%4*2+%3]
+    add             %1, %5
+    add             %2, %5
+    DIFF_PIXELS_1   m3, m7, [%1     +%3], [%2     +%3]
+    DIFF_PIXELS_1   m4, m7, [%1+%4  +%3], [%2+%4  +%3]
+    DIFF_PIXELS_1   m5, m7, [%1+%4*2+%3], [%2+%4*2+%3]
+    DIFF_PIXELS_1   m6, m7, [%1+%5  +%3], [%2+%5  +%3]
+%ifdef m8
+    DIFF_PIXELS_1   m7, m8, [%1+%4*4+%3], [%2+%4*4+%3]
+%else
+    mova          [%6], m0
+    DIFF_PIXELS_1   m7, m0, [%1+%4*4+%3], [%2+%4*4+%3]
+    mova            m0, [%6]
+%endif
+    sub             %1, %5
+    sub             %2, %5
+%endmacro
+
+%macro HADAMARD8 0
+    SUMSUB_BADC       m0, m1, m2, m3
+    SUMSUB_BADC       m4, m5, m6, m7
+    SUMSUB_BADC       m0, m2, m1, m3
+    SUMSUB_BADC       m4, m6, m5, m7
+    SUMSUB_BADC       m0, m4, m1, m5
+    SUMSUB_BADC       m2, m6, m3, m7
+%endmacro
+
+%macro ABS1_SUM 3
+    ABS1            %1, %2
+    paddusw         %3, %1
+%endmacro
+
+%macro ABS2_SUM 6
+    ABS2            %1, %2, %3, %4
+    paddusw         %5, %1
+    paddusw         %6, %2
+%endmacro
+
+%macro ABS_SUM_8x8_64 1
+    ABS2            m0, m1, m8, m9
+    ABS2_SUM        m2, m3, m8, m9, m0, m1
+    ABS2_SUM        m4, m5, m8, m9, m0, m1
+    ABS2_SUM        m6, m7, m8, m9, m0, m1
+    paddusw         m0, m1
+%endmacro
+
+%macro ABS_SUM_8x8_32 1
+    mova          [%1], m7
+    ABS1            m0, m7
+    ABS1            m1, m7
+    ABS1_SUM        m2, m7, m0
+    ABS1_SUM        m3, m7, m1
+    ABS1_SUM        m4, m7, m0
+    ABS1_SUM        m5, m7, m1
+    ABS1_SUM        m6, m7, m0
+    mova            m2, [%1]
+    ABS1_SUM        m2, m7, m1
+    paddusw         m0, m1
+%endmacro
+
+; FIXME: HSUM_* saturates at 64k, while an 8x8 hadamard or dct block can get up to
+; about 100k on extreme inputs. But that's very unlikely to occur in natural video,
+; and it's even more unlikely to not have any alternative mvs/modes with lower cost.
+%macro HSUM_MMX 3
+    mova            %2, %1
+    psrlq           %1, 32
+    paddusw         %1, %2
+    mova            %2, %1
+    psrlq           %1, 16
+    paddusw         %1, %2
+    movd            %3, %1
+%endmacro
+
+%macro HSUM_MMX2 3
+    pshufw          %2, %1, 0xE
+    paddusw         %1, %2
+    pshufw          %2, %1, 0x1
+    paddusw         %1, %2
+    movd            %3, %1
+%endmacro
+
+%macro HSUM_SSE2 3
+    movhlps         %2, %1
+    paddusw         %1, %2
+    pshuflw         %2, %1, 0xE
+    paddusw         %1, %2
+    pshuflw         %2, %1, 0x1
+    paddusw         %1, %2
+    movd            %3, %1
+%endmacro
+
+%macro STORE4 5
+    mova [%1+mmsize*0], %2
+    mova [%1+mmsize*1], %3
+    mova [%1+mmsize*2], %4
+    mova [%1+mmsize*3], %5
+%endmacro
+
+%macro LOAD4 5
+    mova            %2, [%1+mmsize*0]
+    mova            %3, [%1+mmsize*1]
+    mova            %4, [%1+mmsize*2]
+    mova            %5, [%1+mmsize*3]
+%endmacro
+
+%macro hadamard8_16_wrapper 3
+cglobal hadamard8_diff_%1, 4, 4, %2
+%ifndef m8
+    %assign pad %3*mmsize-(4+stack_offset&(mmsize-1))
+    SUB            rsp, pad
+%endif
+    call hadamard8x8_diff_%1
+%ifndef m8
+    ADD            rsp, pad
+%endif
+    RET
+
+cglobal hadamard8_diff16_%1, 5, 6, %2
+%ifndef m8
+    %assign pad %3*mmsize-(4+stack_offset&(mmsize-1))
+    SUB            rsp, pad
+%endif
+
+    call hadamard8x8_diff_%1
+    mov            r5d, eax
+
+    add             r1, 8
+    add             r2, 8
+    call hadamard8x8_diff_%1
+    add            r5d, eax
+
+    cmp            r4d, 16
+    jne .done
+
+    lea             r1, [r1+r3*8-8]
+    lea             r2, [r2+r3*8-8]
+    call hadamard8x8_diff_%1
+    add            r5d, eax
+
+    add             r1, 8
+    add             r2, 8
+    call hadamard8x8_diff_%1
+    add            r5d, eax
+
+.done
+    mov            eax, r5d
+%ifndef m8
+    ADD            rsp, pad
+%endif
+    RET
+%endmacro
+
+%macro HADAMARD8_DIFF_MMX 1
+ALIGN 16
+; int hadamard8_diff_##cpu(void *s, uint8_t *src1, uint8_t *src2,
+;                          int stride, int h)
+; r0 = void *s = unused, int h = unused (always 8)
+; note how r1, r2 and r3 are not clobbered in this function, so 16x16
+; can simply call this 2x2x (and that's why we access rsp+gprsize
+; everywhere, which is rsp of calling func
+hadamard8x8_diff_%1:
+    lea                          r0, [r3*3]
+
+    ; first 4x8 pixels
+    DIFF_PIXELS_8                r1, r2,  0, r3, r0, rsp+gprsize+0x60
+    HADAMARD8
+    mova         [rsp+gprsize+0x60], m7
+    TRANSPOSE4x4W                 0,  1,  2,  3,  7
+    STORE4              rsp+gprsize, m0, m1, m2, m3
+    mova                         m7, [rsp+gprsize+0x60]
+    TRANSPOSE4x4W                 4,  5,  6,  7,  0
+    STORE4         rsp+gprsize+0x40, m4, m5, m6, m7
+
+    ; second 4x8 pixels
+    DIFF_PIXELS_8                r1, r2,  4, r3, r0, rsp+gprsize+0x60
+    HADAMARD8
+    mova         [rsp+gprsize+0x60], m7
+    TRANSPOSE4x4W                 0,  1,  2,  3,  7
+    STORE4         rsp+gprsize+0x20, m0, m1, m2, m3
+    mova                         m7, [rsp+gprsize+0x60]
+    TRANSPOSE4x4W                 4,  5,  6,  7,  0
+
+    LOAD4          rsp+gprsize+0x40, m0, m1, m2, m3
+    HADAMARD8
+    ABS_SUM_8x8_32 rsp+gprsize+0x60
+    mova         [rsp+gprsize+0x60], m0
+
+    LOAD4          rsp+gprsize     , m0, m1, m2, m3
+    LOAD4          rsp+gprsize+0x20, m4, m5, m6, m7
+    HADAMARD8
+    ABS_SUM_8x8_32 rsp+gprsize
+    paddusw                      m0, [rsp+gprsize+0x60]
+
+    HSUM                         m0, m1, eax
+    and                         rax, 0xFFFF
+    ret
+
+hadamard8_16_wrapper %1, 0, 14
+%endmacro
+
+%macro HADAMARD8_DIFF_SSE2 2
+hadamard8x8_diff_%1:
+    lea                          r0, [r3*3]
+    DIFF_PIXELS_8                r1, r2,  0, r3, r0, rsp+gprsize
+    HADAMARD8
+%ifdef ARCH_X86_64
+    TRANSPOSE8x8W                 0,  1,  2,  3,  4,  5,  6,  7,  8
+%else
+    TRANSPOSE8x8W                 0,  1,  2,  3,  4,  5,  6,  7, [rsp+gprsize], [rsp+mmsize+gprsize]
+%endif
+    HADAMARD8
+    ABS_SUM_8x8         rsp+gprsize
+    HSUM_SSE2                    m0, m1, eax
+    and                         eax, 0xFFFF
+    ret
+
+hadamard8_16_wrapper %1, %2, 3
+%endmacro
+
+INIT_MMX
+%define ABS1 ABS1_MMX
+%define HSUM HSUM_MMX
+HADAMARD8_DIFF_MMX mmx
+
+%define ABS1 ABS1_MMX2
+%define HSUM HSUM_MMX2
+HADAMARD8_DIFF_MMX mmx2
+
+INIT_XMM
+%define ABS2 ABS2_MMX2
+%ifdef ARCH_X86_64
+%define ABS_SUM_8x8 ABS_SUM_8x8_64
+%else
+%define ABS_SUM_8x8 ABS_SUM_8x8_32
+%endif
+HADAMARD8_DIFF_SSE2 sse2, 10
+
+%define ABS2        ABS2_SSSE3
+%define ABS_SUM_8x8 ABS_SUM_8x8_64
+HADAMARD8_DIFF_SSE2 ssse3, 9
+
+INIT_XMM
+; sse16_sse2(void *v, uint8_t * pix1, uint8_t * pix2, int line_size, int h)
+cglobal sse16_sse2, 5, 5, 8
+    shr      r4d, 1
+    pxor      m0, m0         ; mm0 = 0
+    pxor      m7, m7         ; mm7 holds the sum
+
+.next2lines ; FIXME why are these unaligned movs? pix1[] is aligned
+    movu      m1, [r1   ]    ; mm1 = pix1[0][0-15]
+    movu      m2, [r2   ]    ; mm2 = pix2[0][0-15]
+    movu      m3, [r1+r3]    ; mm3 = pix1[1][0-15]
+    movu      m4, [r2+r3]    ; mm4 = pix2[1][0-15]
+
+    ; todo: mm1-mm2, mm3-mm4
+    ; algo: subtract mm1 from mm2 with saturation and vice versa
+    ;       OR the result to get the absolute difference
+    mova      m5, m1
+    mova      m6, m3
+    psubusb   m1, m2
+    psubusb   m3, m4
+    psubusb   m2, m5
+    psubusb   m4, m6
+
+    por       m2, m1
+    por       m4, m3
+
+    ; now convert to 16-bit vectors so we can square them
+    mova      m1, m2
+    mova      m3, m4
+
+    punpckhbw m2, m0
+    punpckhbw m4, m0
+    punpcklbw m1, m0         ; mm1 not spread over (mm1,mm2)
+    punpcklbw m3, m0         ; mm4 not spread over (mm3,mm4)
+
+    pmaddwd   m2, m2
+    pmaddwd   m4, m4
+    pmaddwd   m1, m1
+    pmaddwd   m3, m3
+
+    lea       r1, [r1+r3*2]  ; pix1 += 2*line_size
+    lea       r2, [r2+r3*2]  ; pix2 += 2*line_size
+
+    paddd     m1, m2
+    paddd     m3, m4
+    paddd     m7, m1
+    paddd     m7, m3
+
+    dec       r4
+    jnz .next2lines
+
+    mova      m1, m7
+    psrldq    m7, 8          ; shift hi qword to lo
+    paddd     m7, m1
+    mova      m1, m7
+    psrldq    m7, 4          ; shift hi dword to lo
+    paddd     m7, m1
+    movd     eax, m7         ; return value
+    RET
diff --git a/libavcodec/x86/fdct_mmx.c b/libavcodec/x86/fdct_mmx.c
index 6e52285..f35a059 100644
--- a/libavcodec/x86/fdct_mmx.c
+++ b/libavcodec/x86/fdct_mmx.c
@@ -13,24 +13,25 @@
  * a page about fdct at http://www.geocities.com/ssavekar/dct.htm
  * Skal's fdct at http://skal.planet-d.net/coding/dct.html
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "libavutil/common.h"
+#include "libavutil/x86_cpu.h"
 #include "libavcodec/dsputil.h"
 
 //////////////////////////////////////////////////////////////////////
@@ -430,7 +431,10 @@ static av_always_inline void fdct_row_sse2(const int16_t *in, int16_t *out)
         FDCT_ROW_SSE2_H2(80,192)
         FDCT_ROW_SSE2(80)
         :
-        : "r" (in), "r" (tab_frw_01234567_sse2.tab_frw_01234567_sse2), "r" (fdct_r_row_sse2.fdct_r_row_sse2), "i" (SHIFT_FRW_ROW), "r" (out)
+        : "r" (in), "r" (tab_frw_01234567_sse2.tab_frw_01234567_sse2),
+          "r" (fdct_r_row_sse2.fdct_r_row_sse2), "i" (SHIFT_FRW_ROW), "r" (out)
+          XMM_CLOBBERS_ONLY("%xmm0", "%xmm1", "%xmm2", "%xmm3",
+                            "%xmm4", "%xmm5", "%xmm6", "%xmm7")
     );
 }
 
diff --git a/libavcodec/x86/fft.c b/libavcodec/x86/fft.c
index 2c46c63..2426a3d 100644
--- a/libavcodec/x86/fft.c
+++ b/libavcodec/x86/fft.c
@@ -1,40 +1,43 @@
 /*
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/cpu.h"
 #include "libavcodec/dsputil.h"
+#include "libavcodec/dct.h"
 #include "fft.h"
 
 av_cold void ff_fft_init_mmx(FFTContext *s)
 {
 #if HAVE_YASM
-    int has_vectors = mm_support();
-    if (has_vectors & FF_MM_SSE && HAVE_SSE) {
+    int has_vectors = av_get_cpu_flags();
+    if (has_vectors & AV_CPU_FLAG_SSE && HAVE_SSE) {
         /* SSE for P3/P4/K8 */
         s->imdct_calc  = ff_imdct_calc_sse;
         s->imdct_half  = ff_imdct_half_sse;
         s->fft_permute = ff_fft_permute_sse;
         s->fft_calc    = ff_fft_calc_sse;
-    } else if (has_vectors & FF_MM_3DNOWEXT && HAVE_AMD3DNOWEXT) {
+        s->fft_permutation = FF_FFT_PERM_SWAP_LSBS;
+    } else if (has_vectors & AV_CPU_FLAG_3DNOWEXT && HAVE_AMD3DNOWEXT) {
         /* 3DNowEx for K7 */
         s->imdct_calc = ff_imdct_calc_3dn2;
         s->imdct_half = ff_imdct_half_3dn2;
         s->fft_calc   = ff_fft_calc_3dn2;
-    } else if (has_vectors & FF_MM_3DNOW && HAVE_AMD3DNOW) {
+    } else if (has_vectors & AV_CPU_FLAG_3DNOW && HAVE_AMD3DNOW) {
         /* 3DNow! for K6-2/3 */
         s->imdct_calc = ff_imdct_calc_3dn;
         s->imdct_half = ff_imdct_half_3dn;
@@ -42,3 +45,13 @@ av_cold void ff_fft_init_mmx(FFTContext *s)
     }
 #endif
 }
+
+#if CONFIG_DCT
+av_cold void ff_dct_init_mmx(DCTContext *s)
+{
+    int has_vectors = av_get_cpu_flags();
+    if (has_vectors & AV_CPU_FLAG_SSE && HAVE_SSE)
+        s->dct32 = ff_dct32_float_sse;
+}
+#endif
+
diff --git a/libavcodec/x86/fft.h b/libavcodec/x86/fft.h
index 7ef5839..073d408 100644
--- a/libavcodec/x86/fft.h
+++ b/libavcodec/x86/fft.h
@@ -1,18 +1,18 @@
 /*
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -32,5 +32,6 @@ void ff_imdct_calc_3dn2(FFTContext *s, FFTSample *output, const FFTSample *input
 void ff_imdct_half_3dn2(FFTContext *s, FFTSample *output, const FFTSample *input);
 void ff_imdct_calc_sse(FFTContext *s, FFTSample *output, const FFTSample *input);
 void ff_imdct_half_sse(FFTContext *s, FFTSample *output, const FFTSample *input);
+void ff_dct32_float_sse(FFTSample *out, const FFTSample *in);
 
 #endif
diff --git a/libavcodec/x86/fft_3dn.c b/libavcodec/x86/fft_3dn.c
index 6f2e2e8..5a4d3ad 100644
--- a/libavcodec/x86/fft_3dn.c
+++ b/libavcodec/x86/fft_3dn.c
@@ -2,20 +2,20 @@
  * FFT/MDCT transform with 3DNow! optimizations
  * Copyright (c) 2008 Loren Merritt
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/x86/fft_3dn2.c b/libavcodec/x86/fft_3dn2.c
index b3bec46..05c0467 100644
--- a/libavcodec/x86/fft_3dn2.c
+++ b/libavcodec/x86/fft_3dn2.c
@@ -2,20 +2,20 @@
  * FFT/MDCT transform with Extended 3DNow! optimizations
  * Copyright (c) 2006-2008 Zuxy MENG Jie, Loren Merritt
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -56,7 +56,7 @@ void ff_fft_calc_3dn2(FFTContext *s, FFTComplex *z)
 void ff_imdct_half_3dn2(FFTContext *s, FFTSample *output, const FFTSample *input)
 {
     x86_reg j, k;
-    long n = 1 << s->mdct_bits;
+    long n = s->mdct_size;
     long n2 = n >> 1;
     long n4 = n >> 2;
     long n8 = n >> 3;
@@ -147,7 +147,7 @@ void ff_imdct_half_3dn2(FFTContext *s, FFTSample *output, const FFTSample *input
 void ff_imdct_calc_3dn2(FFTContext *s, FFTSample *output, const FFTSample *input)
 {
     x86_reg j, k;
-    long n = 1 << s->mdct_bits;
+    long n = s->mdct_size;
     long n4 = n >> 2;
 
     ff_imdct_half_3dn2(s, output+n4, input);
diff --git a/libavcodec/x86/fft_mmx.asm b/libavcodec/x86/fft_mmx.asm
index 9cb0ae1..e3829b8 100644
--- a/libavcodec/x86/fft_mmx.asm
+++ b/libavcodec/x86/fft_mmx.asm
@@ -2,20 +2,23 @@
 ;* FFT transform with SSE/3DNow optimizations
 ;* Copyright (c) 2008 Loren Merritt
 ;*
-;* This file is part of FFmpeg.
+;* This algorithm (though not any of the implementation details) is
+;* based on libdjbfft by D. J. Bernstein.
 ;*
-;* FFmpeg is free software; you can redistribute it and/or
+;* This file is part of Libav.
+;*
+;* Libav is free software; you can redistribute it and/or
 ;* modify it under the terms of the GNU Lesser General Public
 ;* License as published by the Free Software Foundation; either
 ;* version 2.1 of the License, or (at your option) any later version.
 ;*
-;* FFmpeg is distributed in the hope that it will be useful,
+;* Libav is distributed in the hope that it will be useful,
 ;* but WITHOUT ANY WARRANTY; without even the implied warranty of
 ;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 ;* Lesser General Public License for more details.
 ;*
 ;* You should have received a copy of the GNU Lesser General Public
-;* License along with FFmpeg; if not, write to the Free Software
+;* License along with Libav; if not, write to the Free Software
 ;* 51, Inc., Foundation Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;******************************************************************************
 
@@ -26,16 +29,34 @@
 
 %include "x86inc.asm"
 
+%ifdef ARCH_X86_64
+%define pointer resq
+%else
+%define pointer resd
+%endif
+
+struc FFTContext
+    .nbits:    resd 1
+    .reverse:  resd 1
+    .revtab:   pointer 1
+    .tmpbuf:   pointer 1
+    .mdctsize: resd 1
+    .mdctbits: resd 1
+    .tcos:     pointer 1
+    .tsin:     pointer 1
+endstruc
+
 SECTION_RODATA
 
 %define M_SQRT1_2 0.70710678118654752440
 ps_root2: times 4 dd M_SQRT1_2
 ps_root2mppm: dd -M_SQRT1_2, M_SQRT1_2, M_SQRT1_2, -M_SQRT1_2
+ps_p1p1m1p1: dd 0, 0, 1<<31, 0
 ps_m1p1: dd 1<<31, 0
 
 %assign i 16
 %rep 13
-cextern ff_cos_ %+ i
+cextern cos_ %+ i
 %assign i i<<1
 %endrep
 
@@ -64,7 +85,7 @@ section .text align=16
     mova     %5, %3
     pfsub    %3, %4
     pfadd    %5, %4 ; {t6,t5}
-    pxor     %3, [ps_m1p1 GLOBAL] ; {t8,t7}
+    pxor     %3, [ps_m1p1] ; {t8,t7}
     mova     %6, %1
     pswapd   %3, %3
     pfadd    %1, %5 ; {r0,i0}
@@ -75,54 +96,51 @@ section .text align=16
     SWAP     %3, %6
 %endmacro
 
-; in:  %1={r0,i0,r1,i1} %2={r2,i2,r3,i3}
+; in:  %1={r0,i0,r2,i2} %2={r1,i1,r3,i3}
 ; out: %1={r0,r1,r2,r3} %2={i0,i1,i2,i3}
 %macro T4_SSE 3
     mova     %3, %1
-    shufps   %1, %2, 0x64 ; {r0,i0,r3,i2}
-    shufps   %3, %2, 0xce ; {r1,i1,r2,i3}
+    addps    %1, %2       ; {t1,t2,t6,t5}
+    subps    %3, %2       ; {t3,t4,-t8,t7}
+    xorps    %3, [ps_p1p1m1p1]
     mova     %2, %1
-    addps    %1, %3       ; {t1,t2,t6,t5}
-    subps    %2, %3       ; {t3,t4,t8,t7}
+    shufps   %1, %3, 0x44 ; {t1,t2,t3,t4}
+    shufps   %2, %3, 0xbe ; {t6,t5,t7,t8}
     mova     %3, %1
-    shufps   %1, %2, 0x44 ; {t1,t2,t3,t4}
-    shufps   %3, %2, 0xbe ; {t6,t5,t7,t8}
+    addps    %1, %2       ; {r0,i0,r1,i1}
+    subps    %3, %2       ; {r2,i2,r3,i3}
     mova     %2, %1
-    addps    %1, %3       ; {r0,i0,r1,i1}
-    subps    %2, %3       ; {r2,i2,r3,i3}
-    mova     %3, %1
-    shufps   %1, %2, 0x88 ; {r0,r1,r2,r3}
-    shufps   %3, %2, 0xdd ; {i0,i1,i2,i3}
-    SWAP     %2, %3
+    shufps   %1, %3, 0x88 ; {r0,r1,r2,r3}
+    shufps   %2, %3, 0xdd ; {i0,i1,i2,i3}
 %endmacro
 
-%macro T8_SSE 6 ; r0,i0,r1,i1,t0,t1
-    mova     %5, %3
-    shufps   %3, %4, 0x44 ; {r4,i4,r6,i6}
-    shufps   %5, %4, 0xee ; {r5,i5,r7,i7}
+; in:  %1={r0,r1,r2,r3} %2={i0,i1,i2,i3} %3={r4,i4,r6,i6} %4={r5,i5,r7,i7}
+; out: %1={r0,r1,r2,r3} %2={i0,i1,i2,i3} %1={r4,r5,r6,r7} %2={i4,i5,i6,i7}
+%macro T8_SSE 6
     mova     %6, %3
-    subps    %3, %5       ; {r5,i5,r7,i7}
-    addps    %6, %5       ; {t1,t2,t3,t4}
-    mova     %5, %3
-    shufps   %5, %5, 0xb1 ; {i5,r5,i7,r7}
-    mulps    %3, [ps_root2mppm GLOBAL] ; {-r5,i5,r7,-i7}
-    mulps    %5, [ps_root2 GLOBAL]
-    addps    %3, %5       ; {t8,t7,ta,t9}
-    mova     %5, %6
+    subps    %3, %4       ; {r5,i5,r7,i7}
+    addps    %6, %4       ; {t1,t2,t3,t4}
+    mova     %4, %3
+    shufps   %4, %4, 0xb1 ; {i5,r5,i7,r7}
+    mulps    %3, [ps_root2mppm] ; {-r5,i5,r7,-i7}
+    mulps    %4, [ps_root2]
+    addps    %3, %4       ; {t8,t7,ta,t9}
+    mova     %4, %6
     shufps   %6, %3, 0x36 ; {t3,t2,t9,t8}
-    shufps   %5, %3, 0x9c ; {t1,t4,t7,ta}
+    shufps   %4, %3, 0x9c ; {t1,t4,t7,ta}
     mova     %3, %6
-    addps    %6, %5       ; {t1,t2,t9,ta}
-    subps    %3, %5       ; {t6,t5,tc,tb}
-    mova     %5, %6
+    addps    %6, %4       ; {t1,t2,t9,ta}
+    subps    %3, %4       ; {t6,t5,tc,tb}
+    mova     %4, %6
     shufps   %6, %3, 0xd8 ; {t1,t9,t5,tb}
-    shufps   %5, %3, 0x8d ; {t2,ta,t6,tc}
+    shufps   %4, %3, 0x8d ; {t2,ta,t6,tc}
     mova     %3, %1
-    mova     %4, %2
+    mova     %5, %2
     addps    %1, %6       ; {r0,r1,r2,r3}
-    addps    %2, %5       ; {i0,i1,i2,i3}
+    addps    %2, %4       ; {i0,i1,i2,i3}
     subps    %3, %6       ; {r4,r5,r6,r7}
-    subps    %4, %5       ; {i4,i5,i6,i7}
+    subps    %5, %4       ; {i4,i5,i6,i7}
+    SWAP     %4, %5
 %endmacro
 
 ; scheduled for cpu-bound sizes
@@ -134,9 +152,9 @@ IF%1 mova    m5, Z(5)
     mova     m1, %3 ; wim
     mova     m3, m5
     mulps    m2, m0 ; r2*wre
-IF%1 mova    m6, Z(6)
+IF%1 mova    m6, Z2(6)
     mulps    m3, m1 ; i2*wim
-IF%1 mova    m7, Z(7)
+IF%1 mova    m7, Z2(7)
     mulps    m4, m1 ; r2*wim
     mulps    m5, m0 ; i2*wre
     addps    m2, m3 ; r2*wre + i2*wim
@@ -163,14 +181,14 @@ IF%1 mova    m7, Z(7)
     mova     m4, m6
     subps    m6, m5 ; r3
     addps    m5, m4 ; r1
-    mova   Z(6), m6
+    mova  Z2(6), m6
     mova   Z(2), m5
     mova     m2, Z(3)
     addps    m3, m0 ; t6
     subps    m2, m1 ; i3
     mova     m7, Z(1)
     addps    m1, Z(3) ; i1
-    mova   Z(7), m2
+    mova  Z2(7), m2
     mova   Z(3), m1
     mova     m4, m7
     subps    m7, m3 ; i2
@@ -188,9 +206,9 @@ IF%1 mova    m7, Z(7)
     mova     m3, m5
     mova     m1, [wq+o1q] ; wim
     mulps    m2, m0 ; r2*wre
-    mova     m6, Z(6) ; r3
+    mova     m6, Z2(6) ; r3
     mulps    m3, m1 ; i2*wim
-    mova     m7, Z(7) ; i3
+    mova     m7, Z2(7) ; i3
     mulps    m4, m1 ; r2*wim
     mulps    m5, m0 ; i2*wre
     addps    m2, m3 ; r2*wre + i2*wim
@@ -217,14 +235,14 @@ IF%1 mova    m7, Z(7)
     mova     m4, m6
     subps    m6, m5 ; r3
     addps    m5, m4 ; r1
-IF%1 mova  Z(6), m6
+IF%1 mova Z2(6), m6
 IF%1 mova  Z(2), m5
     mova     m2, Z(3)
     addps    m3, m0 ; t6
     subps    m2, m1 ; i3
     mova     m7, Z(1)
     addps    m1, Z(3) ; i1
-IF%1 mova  Z(7), m2
+IF%1 mova Z2(7), m2
 IF%1 mova  Z(3), m1
     mova     m4, m7
     subps    m7, m3 ; i2
@@ -242,8 +260,8 @@ IF%1 mova  Z(1), m3
     mova     m2, Z(4)
     mova   Z(2), m5
     mova   Z(3), m4
-    mova   Z(6), m6
-    mova   Z(7), m0
+    mova  Z2(6), m6
+    mova  Z2(7), m0
     mova     m5, m1 ; r0
     mova     m4, m2 ; r2
     unpcklps m1, m3
@@ -267,6 +285,7 @@ INIT_XMM
 %define mova movaps
 
 %define Z(x) [r0+mmsize*x]
+%define Z2(x) [r0+mmsize*x]
 
 align 16
 fft4_sse:
@@ -306,10 +325,10 @@ fft16_sse:
     mova   Z(2), m2
     mova   Z(3), m3
     T4_SSE   m4, m5, m6
-    mova     m6, Z(6)
-    mova     m7, Z(7)
+    mova     m6, Z2(6)
+    mova     m7, Z2(7)
     T4_SSE   m6, m7, m0
-    PASS_SMALL 0, [ff_cos_16 GLOBAL], [ff_cos_16+16 GLOBAL]
+    PASS_SMALL 0, [cos_16], [cos_16+16]
     ret
 
 
@@ -338,19 +357,19 @@ fft8%1:
     T4_3DN   m0, m1, m2, m3, m4, m5
     mova   Z(0), m0
     mova   Z(2), m2
-    T2_3DN   m4, m5, Z(4), Z(5)
-    T2_3DN   m6, m7, Z(6), Z(7)
+    T2_3DN   m4, m5,  Z(4),  Z(5)
+    T2_3DN   m6, m7, Z2(6), Z2(7)
     pswapd   m0, m5
     pswapd   m2, m7
-    pxor     m0, [ps_m1p1 GLOBAL]
-    pxor     m2, [ps_m1p1 GLOBAL]
+    pxor     m0, [ps_m1p1]
+    pxor     m2, [ps_m1p1]
     pfsub    m5, m0
     pfadd    m7, m2
-    pfmul    m5, [ps_root2 GLOBAL]
-    pfmul    m7, [ps_root2 GLOBAL]
+    pfmul    m5, [ps_root2]
+    pfmul    m7, [ps_root2]
     T4_3DN   m1, m3, m5, m7, m0, m2
     mova   Z(5), m5
-    mova   Z(7), m7
+    mova  Z2(7), m7
     mova     m0, Z(0)
     mova     m2, Z(2)
     T4_3DN   m0, m2, m4, m6, m5, m7
@@ -360,12 +379,12 @@ fft8%1:
     mova   Z(1), m5
     mova   Z(2), m2
     mova   Z(3), m7
-    PUNPCK   m4, Z(5), m5
-    PUNPCK   m6, Z(7), m7
+    PUNPCK   m4,  Z(5), m5
+    PUNPCK   m6, Z2(7), m7
     mova   Z(4), m4
     mova   Z(5), m5
-    mova   Z(6), m6
-    mova   Z(7), m7
+    mova  Z2(6), m6
+    mova  Z2(7), m7
     ret
 %endmacro
 
@@ -385,7 +404,8 @@ FFT48_3DN _3dn2
 FFT48_3DN _3dn
 
 
-%define Z(x) [zq + o1q*(x&6)*((x/6)^1) + o3q*(x/6) + mmsize*(x&1)]
+%define Z(x) [zq + o1q*(x&6) + mmsize*(x&1)]
+%define Z2(x) [zq + o3q + mmsize*(x&1)]
 
 %macro DECL_PASS 2+ ; name, payload
 align 16
@@ -425,6 +445,16 @@ DECL_PASS pass_interleave_3dn, PASS_BIG 0
 %define SECTION_REL
 %endif
 
+%macro FFT_DISPATCH 2; clobbers 5 GPRs, 8 XMMs
+    lea r2, [dispatch_tab%1]
+    mov r2, [r2 + (%2q-2)*gprsize]
+%ifdef PIC
+    lea r3, [$$]
+    add r2, r3
+%endif
+    call r2
+%endmacro ; FFT_DISPATCH
+
 %macro DECL_FFT 2-3 ; nbits, cpu, suffix
 %xdefine list_of_fft fft4%2 SECTION_REL, fft8%2 SECTION_REL
 %if %1==5
@@ -445,7 +475,7 @@ fft %+ n %+ %3%2:
     add r0, n*2 - (n2&(-2<<%1))
     call fft %+ n4 %+ %2
     sub r0, n*6 + (n2&(-2<<%1))
-    lea r1, [ff_cos_ %+ n GLOBAL]
+    lea r1, [cos_ %+ n]
     mov r2d, n4/2
     jmp pass%3%2
 
@@ -461,13 +491,7 @@ section .text
 ; On x86_32, this function does the register saving and restoring for all of fft.
 ; The others pass args in registers and don't spill anything.
 cglobal fft_dispatch%3%2, 2,5,8, z, nbits
-    lea r2, [dispatch_tab%3%2 GLOBAL]
-    mov r2, [r2 + (nbitsq-2)*gprsize]
-%ifdef PIC
-    lea r3, [$$ GLOBAL]
-    add r2, r3
-%endif
-    call r2
+    FFT_DISPATCH %3%2, nbits
     RET
 %endmacro ; DECL_FFT
 
@@ -478,3 +502,165 @@ DECL_FFT 4, _3dn, _interleave
 DECL_FFT 4, _3dn2
 DECL_FFT 4, _3dn2, _interleave
 
+INIT_XMM
+%undef mulps
+%undef addps
+%undef subps
+%undef unpcklps
+%undef unpckhps
+
+%macro PREROTATER 5 ;-2*k, 2*k, input+n4, tcos+n8, tsin+n8
+    movaps   xmm0, [%3+%2*4]
+    movaps   xmm1, [%3+%1*4-0x10]
+    movaps   xmm2, xmm0
+    shufps   xmm0, xmm1, 0x88
+    shufps   xmm1, xmm2, 0x77
+    movlps   xmm4, [%4+%2*2]
+    movlps   xmm5, [%5+%2*2+0x0]
+    movhps   xmm4, [%4+%1*2-0x8]
+    movhps   xmm5, [%5+%1*2-0x8]
+    movaps   xmm2, xmm0
+    movaps   xmm3, xmm1
+    mulps    xmm0, xmm5
+    mulps    xmm1, xmm4
+    mulps    xmm2, xmm4
+    mulps    xmm3, xmm5
+    subps    xmm1, xmm0
+    addps    xmm2, xmm3
+    movaps   xmm0, xmm1
+    unpcklps xmm1, xmm2
+    unpckhps xmm0, xmm2
+%endmacro
+
+%macro CMUL 6 ;j, xmm0, xmm1, 3, 4, 5
+    movaps   xmm6, [%4+%1*2]
+    movaps   %2,   [%4+%1*2+0x10]
+    movaps   %3,   xmm6
+    movaps   xmm7, %2
+    mulps    xmm6, [%5+%1]
+    mulps    %2,   [%6+%1]
+    mulps    %3,   [%6+%1]
+    mulps    xmm7, [%5+%1]
+    subps    %2,   xmm6
+    addps    %3,   xmm7
+%endmacro
+
+%macro POSROTATESHUF 5 ;j, k, z+n8, tcos+n8, tsin+n8
+.post:
+    CMUL     %1,   xmm0, xmm1, %3, %4, %5
+    CMUL     %2,   xmm4, xmm5, %3, %4, %5
+    shufps   xmm1, xmm1, 0x1b
+    shufps   xmm5, xmm5, 0x1b
+    movaps   xmm6, xmm4
+    unpckhps xmm4, xmm1
+    unpcklps xmm6, xmm1
+    movaps   xmm2, xmm0
+    unpcklps xmm0, xmm5
+    unpckhps xmm2, xmm5
+    movaps   [%3+%2*2],      xmm6
+    movaps   [%3+%2*2+0x10], xmm4
+    movaps   [%3+%1*2],      xmm0
+    movaps   [%3+%1*2+0x10], xmm2
+    sub      %2,   0x10
+    add      %1,   0x10
+    jl       .post
+%endmacro
+
+cglobal imdct_half_sse, 3,7,8; FFTContext *s, FFTSample *output, const FFTSample *input
+%ifdef ARCH_X86_64
+%define rrevtab r10
+%define rtcos   r11
+%define rtsin   r12
+    push  r12
+    push  r13
+    push  r14
+%else
+%define rrevtab r6
+%define rtsin   r6
+%define rtcos   r5
+%endif
+    mov   r3d, [r0+FFTContext.mdctsize]
+    add   r2, r3
+    shr   r3, 1
+    mov   rtcos, [r0+FFTContext.tcos]
+    mov   rtsin, [r0+FFTContext.tsin]
+    add   rtcos, r3
+    add   rtsin, r3
+%ifndef ARCH_X86_64
+    push  rtcos
+    push  rtsin
+%endif
+    shr   r3, 1
+    mov   rrevtab, [r0+FFTContext.revtab]
+    add   rrevtab, r3
+%ifndef ARCH_X86_64
+    push  rrevtab
+%endif
+
+    sub   r3, 4
+%ifdef ARCH_X86_64
+    xor   r4, r4
+    sub   r4, r3
+%endif
+.pre:
+%ifndef ARCH_X86_64
+;unspill
+    xor   r4, r4
+    sub   r4, r3
+    mov   rtsin, [esp+4]
+    mov   rtcos, [esp+8]
+%endif
+
+    PREROTATER r4, r3, r2, rtcos, rtsin
+%ifdef ARCH_X86_64
+    movzx  r5,  word [rrevtab+r4-4]
+    movzx  r6,  word [rrevtab+r4-2]
+    movzx  r13, word [rrevtab+r3]
+    movzx  r14, word [rrevtab+r3+2]
+    movlps [r1+r5 *8], xmm0
+    movhps [r1+r6 *8], xmm0
+    movlps [r1+r13*8], xmm1
+    movhps [r1+r14*8], xmm1
+    add    r4, 4
+%else
+    mov    r6, [esp]
+    movzx  r5, word [r6+r4-4]
+    movzx  r4, word [r6+r4-2]
+    movlps [r1+r5*8], xmm0
+    movhps [r1+r4*8], xmm0
+    movzx  r5, word [r6+r3]
+    movzx  r4, word [r6+r3+2]
+    movlps [r1+r5*8], xmm1
+    movhps [r1+r4*8], xmm1
+%endif
+    sub    r3, 4
+    jns    .pre
+
+    mov  r5, r0
+    mov  r6, r1
+    mov  r0, r1
+    mov  r1d, [r5+FFTContext.nbits]
+
+    FFT_DISPATCH _sse, r1
+
+    mov  r0d, [r5+FFTContext.mdctsize]
+    add  r6, r0
+    shr  r0, 1
+%ifndef ARCH_X86_64
+%define rtcos r2
+%define rtsin r3
+    mov  rtcos, [esp+8]
+    mov  rtsin, [esp+4]
+%endif
+    neg  r0
+    mov  r1, -16
+    sub  r1, r0
+    POSROTATESHUF r0, r1, r6, rtcos, rtsin
+%ifdef ARCH_X86_64
+    pop  r14
+    pop  r13
+    pop  r12
+%else
+    add esp, 12
+%endif
+    RET
diff --git a/libavcodec/x86/fft_sse.c b/libavcodec/x86/fft_sse.c
index a4cce69..9de4e4c 100644
--- a/libavcodec/x86/fft_sse.c
+++ b/libavcodec/x86/fft_sse.c
@@ -2,20 +2,20 @@
  * FFT/MDCT transform with SSE optimizations
  * Copyright (c) 2008 Loren Merritt
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -23,7 +23,7 @@
 #include "libavcodec/dsputil.h"
 #include "fft.h"
 
-DECLARE_ALIGNED(16, static const int, m1m1m1m1)[4] =
+DECLARE_ASM_CONST(16, int, ff_m1m1m1m1)[4] =
     { 1 << 31, 1 << 31, 1 << 31, 1 << 31 };
 
 void ff_fft_dispatch_sse(FFTComplex *z, int nbits);
@@ -71,111 +71,10 @@ void ff_fft_permute_sse(FFTContext *s, FFTComplex *z)
     memcpy(z, s->tmp_buf, n*sizeof(FFTComplex));
 }
 
-void ff_imdct_half_sse(FFTContext *s, FFTSample *output, const FFTSample *input)
-{
-    av_unused x86_reg i, j, k, l;
-    long n = 1 << s->mdct_bits;
-    long n2 = n >> 1;
-    long n4 = n >> 2;
-    long n8 = n >> 3;
-    const uint16_t *revtab = s->revtab + n8;
-    const FFTSample *tcos = s->tcos;
-    const FFTSample *tsin = s->tsin;
-    FFTComplex *z = (FFTComplex *)output;
-
-    /* pre rotation */
-    for(k=n8-2; k>=0; k-=2) {
-        __asm__ volatile(
-            "movaps     (%2,%1,2), %%xmm0 \n" // { z[k].re,    z[k].im,    z[k+1].re,  z[k+1].im  }
-            "movaps  -16(%2,%0,2), %%xmm1 \n" // { z[-k-2].re, z[-k-2].im, z[-k-1].re, z[-k-1].im }
-            "movaps        %%xmm0, %%xmm2 \n"
-            "shufps $0x88, %%xmm1, %%xmm0 \n" // { z[k].re,    z[k+1].re,  z[-k-2].re, z[-k-1].re }
-            "shufps $0x77, %%xmm2, %%xmm1 \n" // { z[-k-1].im, z[-k-2].im, z[k+1].im,  z[k].im    }
-            "movlps       (%3,%1), %%xmm4 \n"
-            "movlps       (%4,%1), %%xmm5 \n"
-            "movhps     -8(%3,%0), %%xmm4 \n" // { cos[k],     cos[k+1],   cos[-k-2],  cos[-k-1]  }
-            "movhps     -8(%4,%0), %%xmm5 \n" // { sin[k],     sin[k+1],   sin[-k-2],  sin[-k-1]  }
-            "movaps        %%xmm0, %%xmm2 \n"
-            "movaps        %%xmm1, %%xmm3 \n"
-            "mulps         %%xmm5, %%xmm0 \n" // re*sin
-            "mulps         %%xmm4, %%xmm1 \n" // im*cos
-            "mulps         %%xmm4, %%xmm2 \n" // re*cos
-            "mulps         %%xmm5, %%xmm3 \n" // im*sin
-            "subps         %%xmm0, %%xmm1 \n" // -> re
-            "addps         %%xmm3, %%xmm2 \n" // -> im
-            "movaps        %%xmm1, %%xmm0 \n"
-            "unpcklps      %%xmm2, %%xmm1 \n" // { z[k],    z[k+1]  }
-            "unpckhps      %%xmm2, %%xmm0 \n" // { z[-k-2], z[-k-1] }
-            ::"r"(-4*k), "r"(4*k),
-              "r"(input+n4), "r"(tcos+n8), "r"(tsin+n8)
-        );
-#if ARCH_X86_64
-        // if we have enough regs, don't let gcc make the luts latency-bound
-        // but if not, latency is faster than spilling
-        __asm__("movlps %%xmm0, %0 \n"
-            "movhps %%xmm0, %1 \n"
-            "movlps %%xmm1, %2 \n"
-            "movhps %%xmm1, %3 \n"
-            :"=m"(z[revtab[-k-2]]),
-             "=m"(z[revtab[-k-1]]),
-             "=m"(z[revtab[ k  ]]),
-             "=m"(z[revtab[ k+1]])
-        );
-#else
-        __asm__("movlps %%xmm0, %0" :"=m"(z[revtab[-k-2]]));
-        __asm__("movhps %%xmm0, %0" :"=m"(z[revtab[-k-1]]));
-        __asm__("movlps %%xmm1, %0" :"=m"(z[revtab[ k  ]]));
-        __asm__("movhps %%xmm1, %0" :"=m"(z[revtab[ k+1]]));
-#endif
-    }
-
-    ff_fft_dispatch_sse(z, s->nbits);
-
-    /* post rotation + reinterleave + reorder */
-
-#define CMUL(j,xmm0,xmm1)\
-        "movaps   (%2,"#j",2), %%xmm6 \n"\
-        "movaps 16(%2,"#j",2), "#xmm0"\n"\
-        "movaps        %%xmm6, "#xmm1"\n"\
-        "movaps        "#xmm0",%%xmm7 \n"\
-        "mulps      (%3,"#j"), %%xmm6 \n"\
-        "mulps      (%4,"#j"), "#xmm0"\n"\
-        "mulps      (%4,"#j"), "#xmm1"\n"\
-        "mulps      (%3,"#j"), %%xmm7 \n"\
-        "subps         %%xmm6, "#xmm0"\n"\
-        "addps         %%xmm7, "#xmm1"\n"
-
-    j = -n2;
-    k = n2-16;
-    __asm__ volatile(
-        "1: \n"
-        CMUL(%0, %%xmm0, %%xmm1)
-        CMUL(%1, %%xmm4, %%xmm5)
-        "shufps    $0x1b, %%xmm1, %%xmm1 \n"
-        "shufps    $0x1b, %%xmm5, %%xmm5 \n"
-        "movaps   %%xmm4, %%xmm6 \n"
-        "unpckhps %%xmm1, %%xmm4 \n"
-        "unpcklps %%xmm1, %%xmm6 \n"
-        "movaps   %%xmm0, %%xmm2 \n"
-        "unpcklps %%xmm5, %%xmm0 \n"
-        "unpckhps %%xmm5, %%xmm2 \n"
-        "movaps   %%xmm6,   (%2,%1,2) \n"
-        "movaps   %%xmm4, 16(%2,%1,2) \n"
-        "movaps   %%xmm0,   (%2,%0,2) \n"
-        "movaps   %%xmm2, 16(%2,%0,2) \n"
-        "sub $16, %1 \n"
-        "add $16, %0 \n"
-        "jl 1b \n"
-        :"+&r"(j), "+&r"(k)
-        :"r"(z+n8), "r"(tcos+n8), "r"(tsin+n8)
-        :"memory"
-    );
-}
-
 void ff_imdct_calc_sse(FFTContext *s, FFTSample *output, const FFTSample *input)
 {
     x86_reg j, k;
-    long n = 1 << s->mdct_bits;
+    long n = s->mdct_size;
     long n4 = n >> 2;
 
     ff_imdct_half_sse(s, output+n4, input);
@@ -183,7 +82,7 @@ void ff_imdct_calc_sse(FFTContext *s, FFTSample *output, const FFTSample *input)
     j = -n;
     k = n-16;
     __asm__ volatile(
-        "movaps %4, %%xmm7 \n"
+        "movaps "MANGLE(ff_m1m1m1m1)", %%xmm7 \n"
         "1: \n"
         "movaps       (%2,%1), %%xmm0 \n"
         "movaps       (%3,%0), %%xmm1 \n"
@@ -196,8 +95,8 @@ void ff_imdct_calc_sse(FFTContext *s, FFTSample *output, const FFTSample *input)
         "add $16, %0 \n"
         "jl 1b \n"
         :"+r"(j), "+r"(k)
-        :"r"(output+n4), "r"(output+n4*3),
-         "m"(*m1m1m1m1)
+        :"r"(output+n4), "r"(output+n4*3)
+        XMM_CLOBBERS_ONLY("%xmm0", "%xmm1", "%xmm7")
     );
 }
 
diff --git a/libavcodec/x86/fmtconvert.asm b/libavcodec/x86/fmtconvert.asm
new file mode 100644
index 0000000..ddcbab4
--- /dev/null
+++ b/libavcodec/x86/fmtconvert.asm
@@ -0,0 +1,91 @@
+;******************************************************************************
+;* x86 optimized Format Conversion Utils
+;* Copyright (c) 2008 Loren Merritt
+;*
+;* This file is part of Libav.
+;*
+;* Libav is free software; you can redistribute it and/or
+;* modify it under the terms of the GNU Lesser General Public
+;* License as published by the Free Software Foundation; either
+;* version 2.1 of the License, or (at your option) any later version.
+;*
+;* Libav is distributed in the hope that it will be useful,
+;* but WITHOUT ANY WARRANTY; without even the implied warranty of
+;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+;* Lesser General Public License for more details.
+;*
+;* You should have received a copy of the GNU Lesser General Public
+;* License along with Libav; if not, write to the Free Software
+;* 51, Inc., Foundation Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+;******************************************************************************
+
+%include "x86inc.asm"
+
+section .text align=16
+
+%macro PSWAPD_SSE 2
+    pshufw %1, %2, 0x4e
+%endmacro
+%macro PSWAPD_3DN1 2
+    movq  %1, %2
+    psrlq %1, 32
+    punpckldq %1, %2
+%endmacro
+
+%macro FLOAT_TO_INT16_INTERLEAVE6 1
+; void float_to_int16_interleave6_sse(int16_t *dst, const float **src, int len)
+cglobal float_to_int16_interleave6_%1, 2,7,0, dst, src, src1, src2, src3, src4, src5
+%ifdef ARCH_X86_64
+    %define lend r10d
+    mov     lend, r2d
+%else
+    %define lend dword r2m
+%endif
+    mov src1q, [srcq+1*gprsize]
+    mov src2q, [srcq+2*gprsize]
+    mov src3q, [srcq+3*gprsize]
+    mov src4q, [srcq+4*gprsize]
+    mov src5q, [srcq+5*gprsize]
+    mov srcq,  [srcq]
+    sub src1q, srcq
+    sub src2q, srcq
+    sub src3q, srcq
+    sub src4q, srcq
+    sub src5q, srcq
+.loop:
+    cvtps2pi   mm0, [srcq]
+    cvtps2pi   mm1, [srcq+src1q]
+    cvtps2pi   mm2, [srcq+src2q]
+    cvtps2pi   mm3, [srcq+src3q]
+    cvtps2pi   mm4, [srcq+src4q]
+    cvtps2pi   mm5, [srcq+src5q]
+    packssdw   mm0, mm3
+    packssdw   mm1, mm4
+    packssdw   mm2, mm5
+    pswapd     mm3, mm0
+    punpcklwd  mm0, mm1
+    punpckhwd  mm1, mm2
+    punpcklwd  mm2, mm3
+    pswapd     mm3, mm0
+    punpckldq  mm0, mm2
+    punpckhdq  mm2, mm1
+    punpckldq  mm1, mm3
+    movq [dstq   ], mm0
+    movq [dstq+16], mm2
+    movq [dstq+ 8], mm1
+    add srcq, 8
+    add dstq, 24
+    sub lend, 2
+    jg .loop
+    emms
+    RET
+%endmacro ; FLOAT_TO_INT16_INTERLEAVE6
+
+%define pswapd PSWAPD_SSE
+FLOAT_TO_INT16_INTERLEAVE6 sse
+%define cvtps2pi pf2id
+%define pswapd PSWAPD_3DN1
+FLOAT_TO_INT16_INTERLEAVE6 3dnow
+%undef pswapd
+FLOAT_TO_INT16_INTERLEAVE6 3dn2
+%undef cvtps2pi
diff --git a/libavcodec/x86/fmtconvert_mmx.c b/libavcodec/x86/fmtconvert_mmx.c
new file mode 100644
index 0000000..847bd80
--- /dev/null
+++ b/libavcodec/x86/fmtconvert_mmx.c
@@ -0,0 +1,266 @@
+/*
+ * Format Conversion Utils
+ * Copyright (c) 2000, 2001 Fabrice Bellard
+ * Copyright (c) 2002-2004 Michael Niedermayer <michaelni at gmx.at>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * MMX optimization by Nick Kurshev <nickols_k at mail.ru>
+ */
+
+#include "libavutil/cpu.h"
+#include "libavutil/x86_cpu.h"
+#include "libavcodec/fmtconvert.h"
+
+static void int32_to_float_fmul_scalar_sse(float *dst, const int *src, float mul, int len)
+{
+    x86_reg i = -4*len;
+    __asm__ volatile(
+        "movss  %3, %%xmm4 \n"
+        "shufps $0, %%xmm4, %%xmm4 \n"
+        "1: \n"
+        "cvtpi2ps   (%2,%0), %%xmm0 \n"
+        "cvtpi2ps  8(%2,%0), %%xmm1 \n"
+        "cvtpi2ps 16(%2,%0), %%xmm2 \n"
+        "cvtpi2ps 24(%2,%0), %%xmm3 \n"
+        "movlhps  %%xmm1,    %%xmm0 \n"
+        "movlhps  %%xmm3,    %%xmm2 \n"
+        "mulps    %%xmm4,    %%xmm0 \n"
+        "mulps    %%xmm4,    %%xmm2 \n"
+        "movaps   %%xmm0,   (%1,%0) \n"
+        "movaps   %%xmm2, 16(%1,%0) \n"
+        "add $32, %0 \n"
+        "jl 1b \n"
+        :"+r"(i)
+        :"r"(dst+len), "r"(src+len), "m"(mul)
+    );
+}
+
+static void int32_to_float_fmul_scalar_sse2(float *dst, const int *src, float mul, int len)
+{
+    x86_reg i = -4*len;
+    __asm__ volatile(
+        "movss  %3, %%xmm4 \n"
+        "shufps $0, %%xmm4, %%xmm4 \n"
+        "1: \n"
+        "cvtdq2ps   (%2,%0), %%xmm0 \n"
+        "cvtdq2ps 16(%2,%0), %%xmm1 \n"
+        "mulps    %%xmm4,    %%xmm0 \n"
+        "mulps    %%xmm4,    %%xmm1 \n"
+        "movaps   %%xmm0,   (%1,%0) \n"
+        "movaps   %%xmm1, 16(%1,%0) \n"
+        "add $32, %0 \n"
+        "jl 1b \n"
+        :"+r"(i)
+        :"r"(dst+len), "r"(src+len), "m"(mul)
+    );
+}
+
+static void float_to_int16_3dnow(int16_t *dst, const float *src, long len){
+    x86_reg reglen = len;
+    // not bit-exact: pf2id uses different rounding than C and SSE
+    __asm__ volatile(
+        "add        %0          , %0        \n\t"
+        "lea         (%2,%0,2)  , %2        \n\t"
+        "add        %0          , %1        \n\t"
+        "neg        %0                      \n\t"
+        "1:                                 \n\t"
+        "pf2id       (%2,%0,2)  , %%mm0     \n\t"
+        "pf2id      8(%2,%0,2)  , %%mm1     \n\t"
+        "pf2id     16(%2,%0,2)  , %%mm2     \n\t"
+        "pf2id     24(%2,%0,2)  , %%mm3     \n\t"
+        "packssdw   %%mm1       , %%mm0     \n\t"
+        "packssdw   %%mm3       , %%mm2     \n\t"
+        "movq       %%mm0       ,  (%1,%0)  \n\t"
+        "movq       %%mm2       , 8(%1,%0)  \n\t"
+        "add        $16         , %0        \n\t"
+        " js 1b                             \n\t"
+        "femms                              \n\t"
+        :"+r"(reglen), "+r"(dst), "+r"(src)
+    );
+}
+
+static void float_to_int16_sse(int16_t *dst, const float *src, long len){
+    x86_reg reglen = len;
+    __asm__ volatile(
+        "add        %0          , %0        \n\t"
+        "lea         (%2,%0,2)  , %2        \n\t"
+        "add        %0          , %1        \n\t"
+        "neg        %0                      \n\t"
+        "1:                                 \n\t"
+        "cvtps2pi    (%2,%0,2)  , %%mm0     \n\t"
+        "cvtps2pi   8(%2,%0,2)  , %%mm1     \n\t"
+        "cvtps2pi  16(%2,%0,2)  , %%mm2     \n\t"
+        "cvtps2pi  24(%2,%0,2)  , %%mm3     \n\t"
+        "packssdw   %%mm1       , %%mm0     \n\t"
+        "packssdw   %%mm3       , %%mm2     \n\t"
+        "movq       %%mm0       ,  (%1,%0)  \n\t"
+        "movq       %%mm2       , 8(%1,%0)  \n\t"
+        "add        $16         , %0        \n\t"
+        " js 1b                             \n\t"
+        "emms                               \n\t"
+        :"+r"(reglen), "+r"(dst), "+r"(src)
+    );
+}
+
+static void float_to_int16_sse2(int16_t *dst, const float *src, long len){
+    x86_reg reglen = len;
+    __asm__ volatile(
+        "add        %0          , %0        \n\t"
+        "lea         (%2,%0,2)  , %2        \n\t"
+        "add        %0          , %1        \n\t"
+        "neg        %0                      \n\t"
+        "1:                                 \n\t"
+        "cvtps2dq    (%2,%0,2)  , %%xmm0    \n\t"
+        "cvtps2dq  16(%2,%0,2)  , %%xmm1    \n\t"
+        "packssdw   %%xmm1      , %%xmm0    \n\t"
+        "movdqa     %%xmm0      ,  (%1,%0)  \n\t"
+        "add        $16         , %0        \n\t"
+        " js 1b                             \n\t"
+        :"+r"(reglen), "+r"(dst), "+r"(src)
+    );
+}
+
+void ff_float_to_int16_interleave6_sse(int16_t *dst, const float **src, int len);
+void ff_float_to_int16_interleave6_3dnow(int16_t *dst, const float **src, int len);
+void ff_float_to_int16_interleave6_3dn2(int16_t *dst, const float **src, int len);
+
+#if !HAVE_YASM
+#define ff_float_to_int16_interleave6_sse(a,b,c)   float_to_int16_interleave_misc_sse(a,b,c,6)
+#define ff_float_to_int16_interleave6_3dnow(a,b,c) float_to_int16_interleave_misc_3dnow(a,b,c,6)
+#define ff_float_to_int16_interleave6_3dn2(a,b,c)  float_to_int16_interleave_misc_3dnow(a,b,c,6)
+#endif
+#define ff_float_to_int16_interleave6_sse2 ff_float_to_int16_interleave6_sse
+
+#define FLOAT_TO_INT16_INTERLEAVE(cpu, body) \
+/* gcc pessimizes register allocation if this is in the same function as float_to_int16_interleave_sse2*/\
+static av_noinline void float_to_int16_interleave_misc_##cpu(int16_t *dst, const float **src, long len, int channels){\
+    DECLARE_ALIGNED(16, int16_t, tmp)[len];\
+    int i,j,c;\
+    for(c=0; c<channels; c++){\
+        float_to_int16_##cpu(tmp, src[c], len);\
+        for(i=0, j=c; i<len; i++, j+=channels)\
+            dst[j] = tmp[i];\
+    }\
+}\
+\
+static void float_to_int16_interleave_##cpu(int16_t *dst, const float **src, long len, int channels){\
+    if(channels==1)\
+        float_to_int16_##cpu(dst, src[0], len);\
+    else if(channels==2){\
+        x86_reg reglen = len; \
+        const float *src0 = src[0];\
+        const float *src1 = src[1];\
+        __asm__ volatile(\
+            "shl $2, %0 \n"\
+            "add %0, %1 \n"\
+            "add %0, %2 \n"\
+            "add %0, %3 \n"\
+            "neg %0 \n"\
+            body\
+            :"+r"(reglen), "+r"(dst), "+r"(src0), "+r"(src1)\
+        );\
+    }else if(channels==6){\
+        ff_float_to_int16_interleave6_##cpu(dst, src, len);\
+    }else\
+        float_to_int16_interleave_misc_##cpu(dst, src, len, channels);\
+}
+
+FLOAT_TO_INT16_INTERLEAVE(3dnow,
+    "1:                         \n"
+    "pf2id     (%2,%0), %%mm0   \n"
+    "pf2id    8(%2,%0), %%mm1   \n"
+    "pf2id     (%3,%0), %%mm2   \n"
+    "pf2id    8(%3,%0), %%mm3   \n"
+    "packssdw    %%mm1, %%mm0   \n"
+    "packssdw    %%mm3, %%mm2   \n"
+    "movq        %%mm0, %%mm1   \n"
+    "punpcklwd   %%mm2, %%mm0   \n"
+    "punpckhwd   %%mm2, %%mm1   \n"
+    "movq        %%mm0,  (%1,%0)\n"
+    "movq        %%mm1, 8(%1,%0)\n"
+    "add $16, %0                \n"
+    "js 1b                      \n"
+    "femms                      \n"
+)
+
+FLOAT_TO_INT16_INTERLEAVE(sse,
+    "1:                         \n"
+    "cvtps2pi  (%2,%0), %%mm0   \n"
+    "cvtps2pi 8(%2,%0), %%mm1   \n"
+    "cvtps2pi  (%3,%0), %%mm2   \n"
+    "cvtps2pi 8(%3,%0), %%mm3   \n"
+    "packssdw    %%mm1, %%mm0   \n"
+    "packssdw    %%mm3, %%mm2   \n"
+    "movq        %%mm0, %%mm1   \n"
+    "punpcklwd   %%mm2, %%mm0   \n"
+    "punpckhwd   %%mm2, %%mm1   \n"
+    "movq        %%mm0,  (%1,%0)\n"
+    "movq        %%mm1, 8(%1,%0)\n"
+    "add $16, %0                \n"
+    "js 1b                      \n"
+    "emms                       \n"
+)
+
+FLOAT_TO_INT16_INTERLEAVE(sse2,
+    "1:                         \n"
+    "cvtps2dq  (%2,%0), %%xmm0  \n"
+    "cvtps2dq  (%3,%0), %%xmm1  \n"
+    "packssdw   %%xmm1, %%xmm0  \n"
+    "movhlps    %%xmm0, %%xmm1  \n"
+    "punpcklwd  %%xmm1, %%xmm0  \n"
+    "movdqa     %%xmm0, (%1,%0) \n"
+    "add $16, %0                \n"
+    "js 1b                      \n"
+)
+
+static void float_to_int16_interleave_3dn2(int16_t *dst, const float **src, long len, int channels){
+    if(channels==6)
+        ff_float_to_int16_interleave6_3dn2(dst, src, len);
+    else
+        float_to_int16_interleave_3dnow(dst, src, len, channels);
+}
+
+void ff_fmt_convert_init_x86(FmtConvertContext *c, AVCodecContext *avctx)
+{
+    int mm_flags = av_get_cpu_flags();
+
+    if (mm_flags & AV_CPU_FLAG_MMX) {
+
+        if(mm_flags & AV_CPU_FLAG_3DNOW){
+            if(!(avctx->flags & CODEC_FLAG_BITEXACT)){
+                c->float_to_int16 = float_to_int16_3dnow;
+                c->float_to_int16_interleave = float_to_int16_interleave_3dnow;
+            }
+        }
+        if(mm_flags & AV_CPU_FLAG_3DNOWEXT){
+            if(!(avctx->flags & CODEC_FLAG_BITEXACT)){
+                c->float_to_int16_interleave = float_to_int16_interleave_3dn2;
+            }
+        }
+        if(mm_flags & AV_CPU_FLAG_SSE){
+            c->int32_to_float_fmul_scalar = int32_to_float_fmul_scalar_sse;
+            c->float_to_int16 = float_to_int16_sse;
+            c->float_to_int16_interleave = float_to_int16_interleave_sse;
+        }
+        if(mm_flags & AV_CPU_FLAG_SSE2){
+            c->int32_to_float_fmul_scalar = int32_to_float_fmul_scalar_sse2;
+            c->float_to_int16 = float_to_int16_sse2;
+            c->float_to_int16_interleave = float_to_int16_interleave_sse2;
+        }
+    }
+}
diff --git a/libavcodec/x86/h264_chromamc.asm b/libavcodec/x86/h264_chromamc.asm
new file mode 100644
index 0000000..99faf44
--- /dev/null
+++ b/libavcodec/x86/h264_chromamc.asm
@@ -0,0 +1,669 @@
+;******************************************************************************
+;* MMX/SSSE3-optimized functions for H264 chroma MC
+;* Copyright (c) 2005 Zoltan Hidvegi <hzoli -a- hzoli -d- com>,
+;*               2005-2008 Loren Merritt
+;*
+;* This file is part of Libav.
+;*
+;* Libav is free software; you can redistribute it and/or
+;* modify it under the terms of the GNU Lesser General Public
+;* License as published by the Free Software Foundation; either
+;* version 2.1 of the License, or (at your option) any later version.
+;*
+;* Libav is distributed in the hope that it will be useful,
+;* but WITHOUT ANY WARRANTY; without even the implied warranty of
+;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+;* Lesser General Public License for more details.
+;*
+;* You should have received a copy of the GNU Lesser General Public
+;* License along with Libav; if not, write to the Free Software
+;* 51, Inc., Foundation Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+;******************************************************************************
+
+%include "x86inc.asm"
+%include "x86util.asm"
+
+SECTION_RODATA
+
+rnd_rv40_2d_tbl: times 4 dw  0
+                 times 4 dw 16
+                 times 4 dw 32
+                 times 4 dw 16
+                 times 4 dw 32
+                 times 4 dw 28
+                 times 4 dw 32
+                 times 4 dw 28
+                 times 4 dw  0
+                 times 4 dw 32
+                 times 4 dw 16
+                 times 4 dw 32
+                 times 4 dw 32
+                 times 4 dw 28
+                 times 4 dw 32
+                 times 4 dw 28
+rnd_rv40_1d_tbl: times 4 dw  0
+                 times 4 dw  2
+                 times 4 dw  4
+                 times 4 dw  2
+                 times 4 dw  4
+                 times 4 dw  3
+                 times 4 dw  4
+                 times 4 dw  3
+                 times 4 dw  0
+                 times 4 dw  4
+                 times 4 dw  2
+                 times 4 dw  4
+                 times 4 dw  4
+                 times 4 dw  3
+                 times 4 dw  4
+                 times 4 dw  3
+
+cextern pw_3
+cextern pw_4
+cextern pw_8
+cextern pw_28
+cextern pw_32
+cextern pw_64
+
+SECTION .text
+
+%macro mv0_pixels_mc8 0
+    lea           r4, [r2*2 ]
+.next4rows
+    movq         mm0, [r1   ]
+    movq         mm1, [r1+r2]
+    CHROMAMC_AVG mm0, [r0   ]
+    CHROMAMC_AVG mm1, [r0+r2]
+    movq     [r0   ], mm0
+    movq     [r0+r2], mm1
+    add           r0, r4
+    add           r1, r4
+    movq         mm0, [r1   ]
+    movq         mm1, [r1+r2]
+    CHROMAMC_AVG mm0, [r0   ]
+    CHROMAMC_AVG mm1, [r0+r2]
+    add           r1, r4
+    movq     [r0   ], mm0
+    movq     [r0+r2], mm1
+    add           r0, r4
+    sub          r3d, 4
+    jne .next4rows
+%endmacro
+
+%macro chroma_mc8_mmx_func 3
+; put/avg_h264_chroma_mc8_mmx_*(uint8_t *dst /*align 8*/, uint8_t *src /*align 1*/,
+;                              int stride, int h, int mx, int my)
+cglobal %1_%2_chroma_mc8_%3, 6, 7, 0
+%ifdef ARCH_X86_64
+    movsxd        r2, r2d
+%endif
+    mov          r6d, r5d
+    or           r6d, r4d
+    jne .at_least_one_non_zero
+    ; mx == 0 AND my == 0 - no filter needed
+    mv0_pixels_mc8
+    REP_RET
+
+.at_least_one_non_zero
+%ifidn %2, rv40
+%ifdef PIC
+%define rnd_1d_rv40 r11
+%define rnd_2d_rv40 r11
+%else ; no-PIC
+%define rnd_1d_rv40 rnd_rv40_1d_tbl
+%define rnd_2d_rv40 rnd_rv40_2d_tbl
+%endif
+%ifdef ARCH_X86_64
+    mov          r10, r5
+    and          r10, 6         ; &~1 for mx/my=[0,7]
+    lea          r10, [r10*4+r4]
+    sar         r10d, 1
+%define rnd_bias r10
+%define dest_reg r0
+%else ; x86-32
+    mov           r0, r5
+    and           r0, 6         ; &~1 for mx/my=[0,7]
+    lea           r0, [r0*4+r4]
+    sar          r0d, 1
+%define rnd_bias r0
+%define dest_reg r5
+%endif
+%else ; vc1, h264
+%define rnd_bias  0
+%define dest_reg r0
+%endif
+
+    test         r5d, r5d
+    mov           r6, 1
+    je .my_is_zero
+    test         r4d, r4d
+    mov           r6, r2        ; dxy = x ? 1 : stride
+    jne .both_non_zero
+.my_is_zero
+    ; mx == 0 XOR my == 0 - 1 dimensional filter only
+    or           r4d, r5d       ; x + y
+
+%ifidn %2, rv40
+%ifdef PIC
+    lea          r11, [rnd_rv40_1d_tbl]
+%endif
+%ifndef ARCH_X86_64
+    mov           r5, r0m
+%endif
+%endif
+
+    movd          m5, r4d
+    movq          m4, [pw_8]
+    movq          m6, [rnd_1d_%2+rnd_bias*8] ; mm6 = rnd >> 3
+    punpcklwd     m5, m5
+    punpckldq     m5, m5        ; mm5 = B = x
+    pxor          m7, m7
+    psubw         m4, m5        ; mm4 = A = 8-x
+
+.next1drow
+    movq          m0, [r1   ]   ; mm0 = src[0..7]
+    movq          m2, [r1+r6]   ; mm1 = src[1..8]
+
+    movq          m1, m0
+    movq          m3, m2
+    punpcklbw     m0, m7
+    punpckhbw     m1, m7
+    punpcklbw     m2, m7
+    punpckhbw     m3, m7
+    pmullw        m0, m4        ; [mm0,mm1] = A * src[0..7]
+    pmullw        m1, m4
+    pmullw        m2, m5        ; [mm2,mm3] = B * src[1..8]
+    pmullw        m3, m5
+
+    paddw         m0, m6
+    paddw         m1, m6
+    paddw         m0, m2
+    paddw         m1, m3
+    psrlw         m0, 3
+    psrlw         m1, 3
+    packuswb      m0, m1
+    CHROMAMC_AVG  m0, [dest_reg]
+    movq  [dest_reg], m0        ; dst[0..7] = (A * src[0..7] + B * src[1..8] + (rnd >> 3)) >> 3
+
+    add     dest_reg, r2
+    add           r1, r2
+    dec           r3d
+    jne .next1drow
+    REP_RET
+
+.both_non_zero ; general case, bilinear
+    movd          m4, r4d         ; x
+    movd          m6, r5d         ; y
+%ifidn %2, rv40
+%ifdef PIC
+    lea          r11, [rnd_rv40_2d_tbl]
+%endif
+%ifndef ARCH_X86_64
+    mov           r5, r0m
+%endif
+%endif
+    mov           r6, rsp         ; backup stack pointer
+    and          rsp, ~(mmsize-1) ; align stack
+    sub          rsp, 16          ; AA and DD
+
+    punpcklwd     m4, m4
+    punpcklwd     m6, m6
+    punpckldq     m4, m4          ; mm4 = x words
+    punpckldq     m6, m6          ; mm6 = y words
+    movq          m5, m4
+    pmullw        m4, m6          ; mm4 = x * y
+    psllw         m5, 3
+    psllw         m6, 3
+    movq          m7, m5
+    paddw         m7, m6
+    movq     [rsp+8], m4          ; DD = x * y
+    psubw         m5, m4          ; mm5 = B = 8x - xy
+    psubw         m6, m4          ; mm6 = C = 8y - xy
+    paddw         m4, [pw_64]
+    psubw         m4, m7          ; mm4 = A = xy - (8x+8y) + 64
+    pxor          m7, m7
+    movq     [rsp  ], m4
+
+    movq          m0, [r1  ]      ; mm0 = src[0..7]
+    movq          m1, [r1+1]      ; mm1 = src[1..8]
+.next2drow
+    add           r1, r2
+
+    movq          m2, m0
+    movq          m3, m1
+    punpckhbw     m0, m7
+    punpcklbw     m1, m7
+    punpcklbw     m2, m7
+    punpckhbw     m3, m7
+    pmullw        m0, [rsp]
+    pmullw        m2, [rsp]
+    pmullw        m1, m5
+    pmullw        m3, m5
+    paddw         m2, m1          ; mm2 = A * src[0..3] + B * src[1..4]
+    paddw         m3, m0          ; mm3 = A * src[4..7] + B * src[5..8]
+
+    movq          m0, [r1]
+    movq          m1, m0
+    punpcklbw     m0, m7
+    punpckhbw     m1, m7
+    pmullw        m0, m6
+    pmullw        m1, m6
+    paddw         m2, m0
+    paddw         m3, m1          ; [mm2,mm3] += C * src[0..7]
+
+    movq          m1, [r1+1]
+    movq          m0, m1
+    movq          m4, m1
+    punpcklbw     m0, m7
+    punpckhbw     m4, m7
+    pmullw        m0, [rsp+8]
+    pmullw        m4, [rsp+8]
+    paddw         m2, m0
+    paddw         m3, m4          ; [mm2,mm3] += D * src[1..8]
+    movq          m0, [r1]
+
+    paddw         m2, [rnd_2d_%2+rnd_bias*8]
+    paddw         m3, [rnd_2d_%2+rnd_bias*8]
+    psrlw         m2, 6
+    psrlw         m3, 6
+    packuswb      m2, m3
+    CHROMAMC_AVG  m2, [dest_reg]
+    movq  [dest_reg], m2          ; dst[0..7] = ([mm2,mm3] + rnd) >> 6
+
+    add     dest_reg, r2
+    dec          r3d
+    jne .next2drow
+    mov          rsp, r6          ; restore stack pointer
+    RET
+%endmacro
+
+%macro chroma_mc4_mmx_func 3
+cglobal %1_%2_chroma_mc4_%3, 6, 6, 0
+%ifdef ARCH_X86_64
+    movsxd        r2, r2d
+%endif
+    pxor          m7, m7
+    movd          m2, r4d         ; x
+    movd          m3, r5d         ; y
+    movq          m4, [pw_8]
+    movq          m5, [pw_8]
+    punpcklwd     m2, m2
+    punpcklwd     m3, m3
+    punpcklwd     m2, m2
+    punpcklwd     m3, m3
+    psubw         m4, m2
+    psubw         m5, m3
+
+%ifidn %2, rv40
+%ifdef PIC
+   lea           r11, [rnd_rv40_2d_tbl]
+%define rnd_2d_rv40 r11
+%else
+%define rnd_2d_rv40 rnd_rv40_2d_tbl
+%endif
+    and           r5, 6         ; &~1 for mx/my=[0,7]
+    lea           r5, [r5*4+r4]
+    sar          r5d, 1
+%define rnd_bias r5
+%else ; vc1, h264
+%define rnd_bias 0
+%endif
+
+    movd          m0, [r1  ]
+    movd          m6, [r1+1]
+    add           r1, r2
+    punpcklbw     m0, m7
+    punpcklbw     m6, m7
+    pmullw        m0, m4
+    pmullw        m6, m2
+    paddw         m6, m0
+
+.next2rows
+    movd          m0, [r1  ]
+    movd          m1, [r1+1]
+    add           r1, r2
+    punpcklbw     m0, m7
+    punpcklbw     m1, m7
+    pmullw        m0, m4
+    pmullw        m1, m2
+    paddw         m1, m0
+    movq          m0, m1
+
+    pmullw        m6, m5
+    pmullw        m1, m3
+    paddw         m6, [rnd_2d_%2+rnd_bias*8]
+    paddw         m1, m6
+    psrlw         m1, 6
+    packuswb      m1, m1
+    CHROMAMC_AVG4 m1, m6, [r0]
+    movd        [r0], m1
+    add           r0, r2
+
+    movd          m6, [r1  ]
+    movd          m1, [r1+1]
+    add           r1, r2
+    punpcklbw     m6, m7
+    punpcklbw     m1, m7
+    pmullw        m6, m4
+    pmullw        m1, m2
+    paddw         m1, m6
+    movq          m6, m1
+    pmullw        m0, m5
+    pmullw        m1, m3
+    paddw         m0, [rnd_2d_%2+rnd_bias*8]
+    paddw         m1, m0
+    psrlw         m1, 6
+    packuswb      m1, m1
+    CHROMAMC_AVG4 m1, m0, [r0]
+    movd        [r0], m1
+    add           r0, r2
+    sub          r3d, 2
+    jnz .next2rows
+    REP_RET
+%endmacro
+
+%macro chroma_mc2_mmx_func 3
+cglobal %1_%2_chroma_mc2_%3, 6, 7, 0
+%ifdef ARCH_X86_64
+    movsxd        r2, r2d
+%endif
+
+    mov          r6d, r4d
+    shl          r4d, 16
+    sub          r4d, r6d
+    add          r4d, 8
+    imul         r5d, r4d         ; x*y<<16 | y*(8-x)
+    shl          r4d, 3
+    sub          r4d, r5d         ; x*(8-y)<<16 | (8-x)*(8-y)
+
+    movd          m5, r4d
+    movd          m6, r5d
+    punpckldq     m5, m5          ; mm5 = {A,B,A,B}
+    punpckldq     m6, m6          ; mm6 = {C,D,C,D}
+    pxor          m7, m7
+    movd          m2, [r1]
+    punpcklbw     m2, m7
+    pshufw        m2, m2, 0x94    ; mm0 = src[0,1,1,2]
+
+.nextrow
+    add           r1, r2
+    movq          m1, m2
+    pmaddwd       m1, m5          ; mm1 = A * src[0,1] + B * src[1,2]
+    movd          m0, [r1]
+    punpcklbw     m0, m7
+    pshufw        m0, m0, 0x94    ; mm0 = src[0,1,1,2]
+    movq          m2, m0
+    pmaddwd       m0, m6
+    paddw         m1, [rnd_2d_%2]
+    paddw         m1, m0          ; mm1 += C * src[0,1] + D * src[1,2]
+    psrlw         m1, 6
+    packssdw      m1, m7
+    packuswb      m1, m7
+    CHROMAMC_AVG4 m1, m3, [r0]
+    movd         r5d, m1
+    mov         [r0], r5w
+    add           r0, r2
+    sub          r3d, 1
+    jnz .nextrow
+    REP_RET
+%endmacro
+
+%define rnd_1d_h264 pw_4
+%define rnd_2d_h264 pw_32
+%define rnd_1d_vc1  pw_3
+%define rnd_2d_vc1  pw_28
+
+%macro NOTHING 2-3
+%endmacro
+%macro DIRECT_AVG 2
+    PAVG          %1, %2
+%endmacro
+%macro COPY_AVG 3
+    movd          %2, %3
+    PAVG          %1, %2
+%endmacro
+
+INIT_MMX
+%define CHROMAMC_AVG  NOTHING
+%define CHROMAMC_AVG4 NOTHING
+chroma_mc8_mmx_func put, h264, mmx_rnd
+chroma_mc8_mmx_func put, vc1,  mmx_nornd
+chroma_mc8_mmx_func put, rv40, mmx
+chroma_mc4_mmx_func put, h264, mmx
+chroma_mc4_mmx_func put, rv40, mmx
+chroma_mc2_mmx_func put, h264, mmx2
+
+%define CHROMAMC_AVG  DIRECT_AVG
+%define CHROMAMC_AVG4 COPY_AVG
+%define PAVG          pavgb
+chroma_mc8_mmx_func avg, h264, mmx2_rnd
+chroma_mc8_mmx_func avg, vc1,  mmx2_nornd
+chroma_mc8_mmx_func avg, rv40, mmx2
+chroma_mc4_mmx_func avg, h264, mmx2
+chroma_mc4_mmx_func avg, rv40, mmx2
+chroma_mc2_mmx_func avg, h264, mmx2
+
+%define PAVG          pavgusb
+chroma_mc8_mmx_func avg, h264, 3dnow_rnd
+chroma_mc8_mmx_func avg, vc1,  3dnow_nornd
+chroma_mc8_mmx_func avg, rv40, 3dnow
+chroma_mc4_mmx_func avg, h264, 3dnow
+chroma_mc4_mmx_func avg, rv40, 3dnow
+
+%macro chroma_mc8_ssse3_func 3
+cglobal %1_%2_chroma_mc8_%3, 6, 7, 8
+%ifdef ARCH_X86_64
+    movsxd        r2, r2d
+%endif
+    mov          r6d, r5d
+    or           r6d, r4d
+    jne .at_least_one_non_zero
+    ; mx == 0 AND my == 0 - no filter needed
+    mv0_pixels_mc8
+    REP_RET
+
+.at_least_one_non_zero
+    test         r5d, r5d
+    je .my_is_zero
+    test         r4d, r4d
+    je .mx_is_zero
+
+    ; general case, bilinear
+    mov          r6d, r4d
+    shl          r4d, 8
+    sub           r4, r6
+    add           r4, 8           ; x*288+8 = x<<8 | (8-x)
+    mov           r6, 8
+    sub          r6d, r5d
+    imul          r6, r4          ; (8-y)*(x*255+8) = (8-y)*x<<8 | (8-y)*(8-x)
+    imul         r4d, r5d         ;    y *(x*255+8) =    y *x<<8 |    y *(8-x)
+
+    movd          m7, r6d
+    movd          m6, r4d
+    movdqa        m5, [rnd_2d_%2]
+    pshuflw       m7, m7, 0
+    pshuflw       m6, m6, 0
+    movlhps       m7, m7
+    movlhps       m6, m6
+
+    movq          m0, [r1     ]
+    movq          m1, [r1   +1]
+    punpcklbw     m0, m1
+    add           r1, r2
+.next2rows
+    movq          m1, [r1     ]
+    movq          m2, [r1   +1]
+    movq          m3, [r1+r2  ]
+    movq          m4, [r1+r2+1]
+    lea           r1, [r1+r2*2]
+    punpcklbw     m1, m2
+    punpcklbw     m3, m4
+    movdqa        m2, m1
+    movdqa        m4, m3
+    pmaddubsw     m0, m7
+    pmaddubsw     m1, m6
+    pmaddubsw     m2, m7
+    pmaddubsw     m3, m6
+    paddw         m0, m5
+    paddw         m2, m5
+    paddw         m1, m0
+    paddw         m3, m2
+    movdqa        m0, m4
+    psrlw         m1, 6
+    psrlw         m3, 6
+%ifidn %1, avg
+    movq          m2, [r0   ]
+    movhps        m2, [r0+r2]
+%endif
+    packuswb      m1, m3
+    CHROMAMC_AVG  m1, m2
+    movq     [r0   ], m1
+    movhps   [r0+r2], m1
+    sub          r3d, 2
+    lea           r0, [r0+r2*2]
+    jg .next2rows
+    REP_RET
+
+.my_is_zero
+    mov          r5d, r4d
+    shl          r4d, 8
+    add           r4, 8
+    sub           r4, r5          ; 255*x+8 = x<<8 | (8-x)
+    movd          m7, r4d
+    movdqa        m6, [rnd_1d_%2]
+    pshuflw       m7, m7, 0
+    movlhps       m7, m7
+
+.next2xrows
+    movq          m0, [r1     ]
+    movq          m1, [r1   +1]
+    movq          m2, [r1+r2  ]
+    movq          m3, [r1+r2+1]
+    punpcklbw     m0, m1
+    punpcklbw     m2, m3
+    pmaddubsw     m0, m7
+    pmaddubsw     m2, m7
+%ifidn %1, avg
+    movq          m4, [r0   ]
+    movhps        m4, [r0+r2]
+%endif
+    paddw         m0, m6
+    paddw         m2, m6
+    psrlw         m0, 3
+    psrlw         m2, 3
+    packuswb      m0, m2
+    CHROMAMC_AVG  m0, m4
+    movq     [r0   ], m0
+    movhps   [r0+r2], m0
+    sub          r3d, 2
+    lea           r0, [r0+r2*2]
+    lea           r1, [r1+r2*2]
+    jg .next2xrows
+    REP_RET
+
+.mx_is_zero
+    mov          r4d, r5d
+    shl          r5d, 8
+    add           r5, 8
+    sub           r5, r4          ; 255*y+8 = y<<8 | (8-y)
+    movd          m7, r5d
+    movdqa        m6, [rnd_1d_%2]
+    pshuflw       m7, m7, 0
+    movlhps       m7, m7
+
+.next2yrows
+    movq          m0, [r1     ]
+    movq          m1, [r1+r2  ]
+    movdqa        m2, m1
+    movq          m3, [r1+r2*2]
+    punpcklbw     m0, m1
+    punpcklbw     m2, m3
+    pmaddubsw     m0, m7
+    pmaddubsw     m2, m7
+%ifidn %1, avg
+    movq          m4, [r0   ]
+    movhps        m4, [r0+r2]
+%endif
+    paddw         m0, m6
+    paddw         m2, m6
+    psrlw         m0, 3
+    psrlw         m2, 3
+    packuswb      m0, m2
+    CHROMAMC_AVG  m0, m4
+    movq     [r0   ], m0
+    movhps   [r0+r2], m0
+    sub          r3d, 2
+    lea           r0, [r0+r2*2]
+    lea           r1, [r1+r2*2]
+    jg .next2yrows
+    REP_RET
+%endmacro
+
+%macro chroma_mc4_ssse3_func 3
+cglobal %1_%2_chroma_mc4_%3, 6, 7, 0
+%ifdef ARCH_X86_64
+    movsxd        r2, r2d
+%endif
+    mov           r6, r4
+    shl          r4d, 8
+    sub          r4d, r6d
+    add          r4d, 8           ; x*288+8
+    mov           r6, 8
+    sub          r6d, r5d
+    imul         r6d, r4d         ; (8-y)*(x*255+8) = (8-y)*x<<8 | (8-y)*(8-x)
+    imul         r4d, r5d         ;    y *(x*255+8) =    y *x<<8 |    y *(8-x)
+
+    movd          m7, r6d
+    movd          m6, r4d
+    movq          m5, [pw_32]
+    pshufw        m7, m7, 0
+    pshufw        m6, m6, 0
+
+    movd          m0, [r1     ]
+    punpcklbw     m0, [r1   +1]
+    add           r1, r2
+.next2rows
+    movd          m1, [r1     ]
+    movd          m3, [r1+r2  ]
+    punpcklbw     m1, [r1   +1]
+    punpcklbw     m3, [r1+r2+1]
+    lea           r1, [r1+r2*2]
+    movq          m2, m1
+    movq          m4, m3
+    pmaddubsw     m0, m7
+    pmaddubsw     m1, m6
+    pmaddubsw     m2, m7
+    pmaddubsw     m3, m6
+    paddw         m0, m5
+    paddw         m2, m5
+    paddw         m1, m0
+    paddw         m3, m2
+    movq          m0, m4
+    psrlw         m1, 6
+    psrlw         m3, 6
+    packuswb      m1, m1
+    packuswb      m3, m3
+    CHROMAMC_AVG  m1, [r0  ]
+    CHROMAMC_AVG  m3, [r0+r2]
+    movd     [r0   ], m1
+    movd     [r0+r2], m3
+    sub          r3d, 2
+    lea           r0, [r0+r2*2]
+    jg .next2rows
+    REP_RET
+%endmacro
+
+%define CHROMAMC_AVG NOTHING
+INIT_XMM
+chroma_mc8_ssse3_func put, h264, ssse3_rnd
+chroma_mc8_ssse3_func put, vc1,  ssse3_nornd
+INIT_MMX
+chroma_mc4_ssse3_func put, h264, ssse3
+
+%define CHROMAMC_AVG DIRECT_AVG
+%define PAVG         pavgb
+INIT_XMM
+chroma_mc8_ssse3_func avg, h264, ssse3_rnd
+chroma_mc8_ssse3_func avg, vc1,  ssse3_nornd
+INIT_MMX
+chroma_mc4_ssse3_func avg, h264, ssse3
diff --git a/libavcodec/x86/h264_deblock.asm b/libavcodec/x86/h264_deblock.asm
new file mode 100644
index 0000000..01778a4
--- /dev/null
+++ b/libavcodec/x86/h264_deblock.asm
@@ -0,0 +1,889 @@
+;*****************************************************************************
+;* MMX/SSE2-optimized H.264 deblocking code
+;*****************************************************************************
+;* Copyright (C) 2005-2008 x264 project
+;*
+;* Authors: Loren Merritt <lorenm at u.washington.edu>
+;*          Jason Garrett-Glaser <darkshikari at gmail.com>
+;*
+;* This file is part of Libav.
+;*
+;* Libav is free software; you can redistribute it and/or
+;* modify it under the terms of the GNU Lesser General Public
+;* License as published by the Free Software Foundation; either
+;* version 2.1 of the License, or (at your option) any later version.
+;*
+;* Libav is distributed in the hope that it will be useful,
+;* but WITHOUT ANY WARRANTY; without even the implied warranty of
+;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+;* Lesser General Public License for more details.
+;*
+;* You should have received a copy of the GNU Lesser General Public
+;* License along with Libav; if not, write to the Free Software
+;* 51, Inc., Foundation Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+;******************************************************************************
+
+%include "x86inc.asm"
+%include "x86util.asm"
+
+SECTION_RODATA
+
+cextern pb_0
+cextern pb_1
+cextern pb_3
+cextern pb_A1
+
+SECTION .text
+
+; expands to [base],...,[base+7*stride]
+%define PASS8ROWS(base, base3, stride, stride3) \
+    [base], [base+stride], [base+stride*2], [base3], \
+    [base3+stride], [base3+stride*2], [base3+stride3], [base3+stride*4]
+
+; in: 8 rows of 4 bytes in %1..%8
+; out: 4 rows of 8 bytes in m0..m3
+%macro TRANSPOSE4x8_LOAD 8
+    movd       m0, %1
+    movd       m2, %2
+    movd       m1, %3
+    movd       m3, %4
+    punpcklbw  m0, m2
+    punpcklbw  m1, m3
+    movq       m2, m0
+    punpcklwd  m0, m1
+    punpckhwd  m2, m1
+
+    movd       m4, %5
+    movd       m6, %6
+    movd       m5, %7
+    movd       m7, %8
+    punpcklbw  m4, m6
+    punpcklbw  m5, m7
+    movq       m6, m4
+    punpcklwd  m4, m5
+    punpckhwd  m6, m5
+
+    movq       m1, m0
+    movq       m3, m2
+    punpckldq  m0, m4
+    punpckhdq  m1, m4
+    punpckldq  m2, m6
+    punpckhdq  m3, m6
+%endmacro
+
+; in: 4 rows of 8 bytes in m0..m3
+; out: 8 rows of 4 bytes in %1..%8
+%macro TRANSPOSE8x4_STORE 8
+    movq       m4, m0
+    movq       m5, m1
+    movq       m6, m2
+    punpckhdq  m4, m4
+    punpckhdq  m5, m5
+    punpckhdq  m6, m6
+
+    punpcklbw  m0, m1
+    punpcklbw  m2, m3
+    movq       m1, m0
+    punpcklwd  m0, m2
+    punpckhwd  m1, m2
+    movd       %1, m0
+    punpckhdq  m0, m0
+    movd       %2, m0
+    movd       %3, m1
+    punpckhdq  m1, m1
+    movd       %4, m1
+
+    punpckhdq  m3, m3
+    punpcklbw  m4, m5
+    punpcklbw  m6, m3
+    movq       m5, m4
+    punpcklwd  m4, m6
+    punpckhwd  m5, m6
+    movd       %5, m4
+    punpckhdq  m4, m4
+    movd       %6, m4
+    movd       %7, m5
+    punpckhdq  m5, m5
+    movd       %8, m5
+%endmacro
+
+%macro SBUTTERFLY3 4
+    movq       %4, %2
+    punpckl%1  %2, %3
+    punpckh%1  %4, %3
+%endmacro
+
+; in: 8 rows of 8 (only the middle 6 pels are used) in %1..%8
+; out: 6 rows of 8 in [%9+0*16] .. [%9+5*16]
+%macro TRANSPOSE6x8_MEM 9
+    movq  m0, %1
+    movq  m1, %2
+    movq  m2, %3
+    movq  m3, %4
+    movq  m4, %5
+    movq  m5, %6
+    movq  m6, %7
+    SBUTTERFLY3 bw, m0, m1, m7
+    SBUTTERFLY3 bw, m2, m3, m1
+    SBUTTERFLY3 bw, m4, m5, m3
+    movq  [%9+0x10], m1
+    SBUTTERFLY3 bw, m6, %8, m5
+    SBUTTERFLY3 wd, m0, m2, m1
+    SBUTTERFLY3 wd, m4, m6, m2
+    punpckhdq m0, m4
+    movq  [%9+0x00], m0
+    SBUTTERFLY3 wd, m7, [%9+0x10], m6
+    SBUTTERFLY3 wd, m3, m5, m4
+    SBUTTERFLY3 dq, m7, m3, m0
+    SBUTTERFLY3 dq, m1, m2, m5
+    punpckldq m6, m4
+    movq  [%9+0x10], m1
+    movq  [%9+0x20], m5
+    movq  [%9+0x30], m7
+    movq  [%9+0x40], m0
+    movq  [%9+0x50], m6
+%endmacro
+
+; in: 8 rows of 8 in %1..%8
+; out: 8 rows of 8 in %9..%16
+%macro TRANSPOSE8x8_MEM 16
+    movq  m0, %1
+    movq  m1, %2
+    movq  m2, %3
+    movq  m3, %4
+    movq  m4, %5
+    movq  m5, %6
+    movq  m6, %7
+    SBUTTERFLY3 bw, m0, m1, m7
+    SBUTTERFLY3 bw, m2, m3, m1
+    SBUTTERFLY3 bw, m4, m5, m3
+    SBUTTERFLY3 bw, m6, %8, m5
+    movq  %9,  m3
+    SBUTTERFLY3 wd, m0, m2, m3
+    SBUTTERFLY3 wd, m4, m6, m2
+    SBUTTERFLY3 wd, m7, m1, m6
+    movq  %11, m2
+    movq  m2,  %9
+    SBUTTERFLY3 wd, m2, m5, m1
+    SBUTTERFLY3 dq, m0, m4, m5
+    SBUTTERFLY3 dq, m7, m2, m4
+    movq  %9,  m0
+    movq  %10, m5
+    movq  %13, m7
+    movq  %14, m4
+    SBUTTERFLY3 dq, m3, %11, m0
+    SBUTTERFLY3 dq, m6, m1, m5
+    movq  %11, m3
+    movq  %12, m0
+    movq  %15, m6
+    movq  %16, m5
+%endmacro
+
+; out: %4 = |%1-%2|>%3
+; clobbers: %5
+%macro DIFF_GT 5
+    mova    %5, %2
+    mova    %4, %1
+    psubusb %5, %1
+    psubusb %4, %2
+    por     %4, %5
+    psubusb %4, %3
+%endmacro
+
+; out: %4 = |%1-%2|>%3
+; clobbers: %5
+%macro DIFF_GT2 5
+    mova    %5, %2
+    mova    %4, %1
+    psubusb %5, %1
+    psubusb %4, %2
+    psubusb %5, %3
+    psubusb %4, %3
+    pcmpeqb %4, %5
+%endmacro
+
+%macro SPLATW 1
+%ifidn m0, xmm0
+    pshuflw  %1, %1, 0
+    punpcklqdq %1, %1
+%else
+    pshufw   %1, %1, 0
+%endif
+%endmacro
+
+; in: m0=p1 m1=p0 m2=q0 m3=q1 %1=alpha-1 %2=beta-1
+; out: m5=beta-1, m7=mask, %3=alpha-1
+; clobbers: m4,m6
+%macro LOAD_MASK 2-3
+    movd     m4, %1
+    movd     m5, %2
+    SPLATW   m4
+    SPLATW   m5
+    packuswb m4, m4  ; 16x alpha-1
+    packuswb m5, m5  ; 16x beta-1
+%if %0>2
+    mova     %3, m4
+%endif
+    DIFF_GT  m1, m2, m4, m7, m6 ; |p0-q0| > alpha-1
+    DIFF_GT  m0, m1, m5, m4, m6 ; |p1-p0| > beta-1
+    por      m7, m4
+    DIFF_GT  m3, m2, m5, m4, m6 ; |q1-q0| > beta-1
+    por      m7, m4
+    pxor     m6, m6
+    pcmpeqb  m7, m6
+%endmacro
+
+; in: m0=p1 m1=p0 m2=q0 m3=q1 m7=(tc&mask)
+; out: m1=p0' m2=q0'
+; clobbers: m0,3-6
+%macro DEBLOCK_P0_Q0 0
+    mova    m5, m1
+    pxor    m5, m2       ; p0^q0
+    pand    m5, [pb_1]   ; (p0^q0)&1
+    pcmpeqb m4, m4
+    pxor    m3, m4
+    pavgb   m3, m0       ; (p1 - q1 + 256)>>1
+    pavgb   m3, [pb_3]   ; (((p1 - q1 + 256)>>1)+4)>>1 = 64+2+(p1-q1)>>2
+    pxor    m4, m1
+    pavgb   m4, m2       ; (q0 - p0 + 256)>>1
+    pavgb   m3, m5
+    paddusb m3, m4       ; d+128+33
+    mova    m6, [pb_A1]
+    psubusb m6, m3
+    psubusb m3, [pb_A1]
+    pminub  m6, m7
+    pminub  m3, m7
+    psubusb m1, m6
+    psubusb m2, m3
+    paddusb m1, m3
+    paddusb m2, m6
+%endmacro
+
+; in: m1=p0 m2=q0
+;     %1=p1 %2=q2 %3=[q2] %4=[q1] %5=tc0 %6=tmp
+; out: [q1] = clip( (q2+((p0+q0+1)>>1))>>1, q1-tc0, q1+tc0 )
+; clobbers: q2, tmp, tc0
+%macro LUMA_Q1 6
+    mova    %6, m1
+    pavgb   %6, m2
+    pavgb   %2, %6       ; avg(p2,avg(p0,q0))
+    pxor    %6, %3
+    pand    %6, [pb_1]   ; (p2^avg(p0,q0))&1
+    psubusb %2, %6       ; (p2+((p0+q0+1)>>1))>>1
+    mova    %6, %1
+    psubusb %6, %5
+    paddusb %5, %1
+    pmaxub  %2, %6
+    pminub  %2, %5
+    mova    %4, %2
+%endmacro
+
+%ifdef ARCH_X86_64
+;-----------------------------------------------------------------------------
+; void x264_deblock_v_luma_sse2( uint8_t *pix, int stride, int alpha, int beta, int8_t *tc0 )
+;-----------------------------------------------------------------------------
+INIT_XMM
+cglobal x264_deblock_v_luma_sse2, 5,5,10
+    movd    m8, [r4] ; tc0
+    lea     r4, [r1*3]
+    dec     r2d        ; alpha-1
+    neg     r4
+    dec     r3d        ; beta-1
+    add     r4, r0     ; pix-3*stride
+
+    mova    m0, [r4+r1]   ; p1
+    mova    m1, [r4+2*r1] ; p0
+    mova    m2, [r0]      ; q0
+    mova    m3, [r0+r1]   ; q1
+    LOAD_MASK r2d, r3d
+
+    punpcklbw m8, m8
+    punpcklbw m8, m8 ; tc = 4x tc0[3], 4x tc0[2], 4x tc0[1], 4x tc0[0]
+    pcmpeqb m9, m9
+    pcmpeqb m9, m8
+    pandn   m9, m7
+    pand    m8, m9
+
+    movdqa  m3, [r4] ; p2
+    DIFF_GT2 m1, m3, m5, m6, m7 ; |p2-p0| > beta-1
+    pand    m6, m9
+    mova    m7, m8
+    psubb   m7, m6
+    pand    m6, m8
+    LUMA_Q1 m0, m3, [r4], [r4+r1], m6, m4
+
+    movdqa  m4, [r0+2*r1] ; q2
+    DIFF_GT2 m2, m4, m5, m6, m3 ; |q2-q0| > beta-1
+    pand    m6, m9
+    pand    m8, m6
+    psubb   m7, m6
+    mova    m3, [r0+r1]
+    LUMA_Q1 m3, m4, [r0+2*r1], [r0+r1], m8, m6
+
+    DEBLOCK_P0_Q0
+    mova    [r4+2*r1], m1
+    mova    [r0], m2
+    RET
+
+;-----------------------------------------------------------------------------
+; void x264_deblock_h_luma_sse2( uint8_t *pix, int stride, int alpha, int beta, int8_t *tc0 )
+;-----------------------------------------------------------------------------
+INIT_MMX
+cglobal x264_deblock_h_luma_sse2, 5,7
+    movsxd r10, r1d
+    lea    r11, [r10+r10*2]
+    lea    r6,  [r0-4]
+    lea    r5,  [r0-4+r11]
+%ifdef WIN64
+    sub    rsp, 0x98
+    %define pix_tmp rsp+0x30
+%else
+    sub    rsp, 0x68
+    %define pix_tmp rsp
+%endif
+
+    ; transpose 6x16 -> tmp space
+    TRANSPOSE6x8_MEM  PASS8ROWS(r6, r5, r10, r11), pix_tmp
+    lea    r6, [r6+r10*8]
+    lea    r5, [r5+r10*8]
+    TRANSPOSE6x8_MEM  PASS8ROWS(r6, r5, r10, r11), pix_tmp+8
+
+    ; vertical filter
+    ; alpha, beta, tc0 are still in r2d, r3d, r4
+    ; don't backup r6, r5, r10, r11 because x264_deblock_v_luma_sse2 doesn't use them
+    lea    r0, [pix_tmp+0x30]
+    mov    r1d, 0x10
+%ifdef WIN64
+    mov    [rsp+0x20], r4
+%endif
+    call   x264_deblock_v_luma_sse2
+
+    ; transpose 16x4 -> original space  (only the middle 4 rows were changed by the filter)
+    add    r6, 2
+    add    r5, 2
+    movq   m0, [pix_tmp+0x18]
+    movq   m1, [pix_tmp+0x28]
+    movq   m2, [pix_tmp+0x38]
+    movq   m3, [pix_tmp+0x48]
+    TRANSPOSE8x4_STORE  PASS8ROWS(r6, r5, r10, r11)
+
+    shl    r10, 3
+    sub    r6,  r10
+    sub    r5,  r10
+    shr    r10, 3
+    movq   m0, [pix_tmp+0x10]
+    movq   m1, [pix_tmp+0x20]
+    movq   m2, [pix_tmp+0x30]
+    movq   m3, [pix_tmp+0x40]
+    TRANSPOSE8x4_STORE  PASS8ROWS(r6, r5, r10, r11)
+
+%ifdef WIN64
+    add    rsp, 0x98
+%else
+    add    rsp, 0x68
+%endif
+    RET
+
+%else
+
+%macro DEBLOCK_LUMA 3
+;-----------------------------------------------------------------------------
+; void x264_deblock_v8_luma_mmxext( uint8_t *pix, int stride, int alpha, int beta, int8_t *tc0 )
+;-----------------------------------------------------------------------------
+cglobal x264_deblock_%2_luma_%1, 5,5
+    lea     r4, [r1*3]
+    dec     r2     ; alpha-1
+    neg     r4
+    dec     r3     ; beta-1
+    add     r4, r0 ; pix-3*stride
+    %assign pad 2*%3+12-(stack_offset&15)
+    SUB     esp, pad
+
+    mova    m0, [r4+r1]   ; p1
+    mova    m1, [r4+2*r1] ; p0
+    mova    m2, [r0]      ; q0
+    mova    m3, [r0+r1]   ; q1
+    LOAD_MASK r2, r3
+
+    mov     r3, r4mp
+    movd    m4, [r3] ; tc0
+    punpcklbw m4, m4
+    punpcklbw m4, m4 ; tc = 4x tc0[3], 4x tc0[2], 4x tc0[1], 4x tc0[0]
+    mova   [esp+%3], m4 ; tc
+    pcmpeqb m3, m3
+    pcmpgtb m4, m3
+    pand    m4, m7
+    mova   [esp], m4 ; mask
+
+    mova    m3, [r4] ; p2
+    DIFF_GT2 m1, m3, m5, m6, m7 ; |p2-p0| > beta-1
+    pand    m6, m4
+    pand    m4, [esp+%3] ; tc
+    mova    m7, m4
+    psubb   m7, m6
+    pand    m6, m4
+    LUMA_Q1 m0, m3, [r4], [r4+r1], m6, m4
+
+    mova    m4, [r0+2*r1] ; q2
+    DIFF_GT2 m2, m4, m5, m6, m3 ; |q2-q0| > beta-1
+    mova    m5, [esp] ; mask
+    pand    m6, m5
+    mova    m5, [esp+%3] ; tc
+    pand    m5, m6
+    psubb   m7, m6
+    mova    m3, [r0+r1]
+    LUMA_Q1 m3, m4, [r0+2*r1], [r0+r1], m5, m6
+
+    DEBLOCK_P0_Q0
+    mova    [r4+2*r1], m1
+    mova    [r0], m2
+    ADD     esp, pad
+    RET
+
+;-----------------------------------------------------------------------------
+; void x264_deblock_h_luma_mmxext( uint8_t *pix, int stride, int alpha, int beta, int8_t *tc0 )
+;-----------------------------------------------------------------------------
+INIT_MMX
+cglobal x264_deblock_h_luma_%1, 0,5
+    mov    r0, r0mp
+    mov    r3, r1m
+    lea    r4, [r3*3]
+    sub    r0, 4
+    lea    r1, [r0+r4]
+    %assign pad 0x78-(stack_offset&15)
+    SUB    esp, pad
+%define pix_tmp esp+12
+
+    ; transpose 6x16 -> tmp space
+    TRANSPOSE6x8_MEM  PASS8ROWS(r0, r1, r3, r4), pix_tmp
+    lea    r0, [r0+r3*8]
+    lea    r1, [r1+r3*8]
+    TRANSPOSE6x8_MEM  PASS8ROWS(r0, r1, r3, r4), pix_tmp+8
+
+    ; vertical filter
+    lea    r0, [pix_tmp+0x30]
+    PUSH   dword r4m
+    PUSH   dword r3m
+    PUSH   dword r2m
+    PUSH   dword 16
+    PUSH   dword r0
+    call   x264_deblock_%2_luma_%1
+%ifidn %2, v8
+    add    dword [esp   ], 8 ; pix_tmp+0x38
+    add    dword [esp+16], 2 ; tc0+2
+    call   x264_deblock_%2_luma_%1
+%endif
+    ADD    esp, 20
+
+    ; transpose 16x4 -> original space  (only the middle 4 rows were changed by the filter)
+    mov    r0, r0mp
+    sub    r0, 2
+    lea    r1, [r0+r4]
+
+    movq   m0, [pix_tmp+0x10]
+    movq   m1, [pix_tmp+0x20]
+    movq   m2, [pix_tmp+0x30]
+    movq   m3, [pix_tmp+0x40]
+    TRANSPOSE8x4_STORE  PASS8ROWS(r0, r1, r3, r4)
+
+    lea    r0, [r0+r3*8]
+    lea    r1, [r1+r3*8]
+    movq   m0, [pix_tmp+0x18]
+    movq   m1, [pix_tmp+0x28]
+    movq   m2, [pix_tmp+0x38]
+    movq   m3, [pix_tmp+0x48]
+    TRANSPOSE8x4_STORE  PASS8ROWS(r0, r1, r3, r4)
+
+    ADD    esp, pad
+    RET
+%endmacro ; DEBLOCK_LUMA
+
+INIT_MMX
+DEBLOCK_LUMA mmxext, v8, 8
+INIT_XMM
+DEBLOCK_LUMA sse2, v, 16
+
+%endif ; ARCH
+
+
+
+%macro LUMA_INTRA_P012 4 ; p0..p3 in memory
+    mova  t0, p2
+    mova  t1, p0
+    pavgb t0, p1
+    pavgb t1, q0
+    pavgb t0, t1 ; ((p2+p1+1)/2 + (p0+q0+1)/2 + 1)/2
+    mova  t5, t1
+    mova  t2, p2
+    mova  t3, p0
+    paddb t2, p1
+    paddb t3, q0
+    paddb t2, t3
+    mova  t3, t2
+    mova  t4, t2
+    psrlw t2, 1
+    pavgb t2, mpb_0
+    pxor  t2, t0
+    pand  t2, mpb_1
+    psubb t0, t2 ; p1' = (p2+p1+p0+q0+2)/4;
+
+    mova  t1, p2
+    mova  t2, p2
+    pavgb t1, q1
+    psubb t2, q1
+    paddb t3, t3
+    psubb t3, t2 ; p2+2*p1+2*p0+2*q0+q1
+    pand  t2, mpb_1
+    psubb t1, t2
+    pavgb t1, p1
+    pavgb t1, t5 ; (((p2+q1)/2 + p1+1)/2 + (p0+q0+1)/2 + 1)/2
+    psrlw t3, 2
+    pavgb t3, mpb_0
+    pxor  t3, t1
+    pand  t3, mpb_1
+    psubb t1, t3 ; p0'a = (p2+2*p1+2*p0+2*q0+q1+4)/8
+
+    mova  t3, p0
+    mova  t2, p0
+    pxor  t3, q1
+    pavgb t2, q1
+    pand  t3, mpb_1
+    psubb t2, t3
+    pavgb t2, p1 ; p0'b = (2*p1+p0+q0+2)/4
+
+    pxor  t1, t2
+    pxor  t2, p0
+    pand  t1, mask1p
+    pand  t2, mask0
+    pxor  t1, t2
+    pxor  t1, p0
+    mova  %1, t1 ; store p0
+
+    mova  t1, %4 ; p3
+    mova  t2, t1
+    pavgb t1, p2
+    paddb t2, p2
+    pavgb t1, t0 ; (p3+p2+1)/2 + (p2+p1+p0+q0+2)/4
+    paddb t2, t2
+    paddb t2, t4 ; 2*p3+3*p2+p1+p0+q0
+    psrlw t2, 2
+    pavgb t2, mpb_0
+    pxor  t2, t1
+    pand  t2, mpb_1
+    psubb t1, t2 ; p2' = (2*p3+3*p2+p1+p0+q0+4)/8
+
+    pxor  t0, p1
+    pxor  t1, p2
+    pand  t0, mask1p
+    pand  t1, mask1p
+    pxor  t0, p1
+    pxor  t1, p2
+    mova  %2, t0 ; store p1
+    mova  %3, t1 ; store p2
+%endmacro
+
+%macro LUMA_INTRA_SWAP_PQ 0
+    %define q1 m0
+    %define q0 m1
+    %define p0 m2
+    %define p1 m3
+    %define p2 q2
+    %define mask1p mask1q
+%endmacro
+
+%macro DEBLOCK_LUMA_INTRA 2
+    %define p1 m0
+    %define p0 m1
+    %define q0 m2
+    %define q1 m3
+    %define t0 m4
+    %define t1 m5
+    %define t2 m6
+    %define t3 m7
+%ifdef ARCH_X86_64
+    %define p2 m8
+    %define q2 m9
+    %define t4 m10
+    %define t5 m11
+    %define mask0 m12
+    %define mask1p m13
+    %define mask1q [rsp-24]
+    %define mpb_0 m14
+    %define mpb_1 m15
+%else
+    %define spill(x) [esp+16*x+((stack_offset+4)&15)]
+    %define p2 [r4+r1]
+    %define q2 [r0+2*r1]
+    %define t4 spill(0)
+    %define t5 spill(1)
+    %define mask0 spill(2)
+    %define mask1p spill(3)
+    %define mask1q spill(4)
+    %define mpb_0 [pb_0]
+    %define mpb_1 [pb_1]
+%endif
+
+;-----------------------------------------------------------------------------
+; void x264_deblock_v_luma_intra_sse2( uint8_t *pix, int stride, int alpha, int beta )
+;-----------------------------------------------------------------------------
+cglobal x264_deblock_%2_luma_intra_%1, 4,6,16
+%ifndef ARCH_X86_64
+    sub     esp, 0x60
+%endif
+    lea     r4, [r1*4]
+    lea     r5, [r1*3] ; 3*stride
+    dec     r2d        ; alpha-1
+    jl .end
+    neg     r4
+    dec     r3d        ; beta-1
+    jl .end
+    add     r4, r0     ; pix-4*stride
+    mova    p1, [r4+2*r1]
+    mova    p0, [r4+r5]
+    mova    q0, [r0]
+    mova    q1, [r0+r1]
+%ifdef ARCH_X86_64
+    pxor    mpb_0, mpb_0
+    mova    mpb_1, [pb_1]
+    LOAD_MASK r2d, r3d, t5 ; m5=beta-1, t5=alpha-1, m7=mask0
+    SWAP    7, 12 ; m12=mask0
+    pavgb   t5, mpb_0
+    pavgb   t5, mpb_1 ; alpha/4+1
+    movdqa  p2, [r4+r1]
+    movdqa  q2, [r0+2*r1]
+    DIFF_GT2 p0, q0, t5, t0, t3 ; t0 = |p0-q0| > alpha/4+1
+    DIFF_GT2 p0, p2, m5, t2, t5 ; mask1 = |p2-p0| > beta-1
+    DIFF_GT2 q0, q2, m5, t4, t5 ; t4 = |q2-q0| > beta-1
+    pand    t0, mask0
+    pand    t4, t0
+    pand    t2, t0
+    mova    mask1q, t4
+    mova    mask1p, t2
+%else
+    LOAD_MASK r2d, r3d, t5 ; m5=beta-1, t5=alpha-1, m7=mask0
+    mova    m4, t5
+    mova    mask0, m7
+    pavgb   m4, [pb_0]
+    pavgb   m4, [pb_1] ; alpha/4+1
+    DIFF_GT2 p0, q0, m4, m6, m7 ; m6 = |p0-q0| > alpha/4+1
+    pand    m6, mask0
+    DIFF_GT2 p0, p2, m5, m4, m7 ; m4 = |p2-p0| > beta-1
+    pand    m4, m6
+    mova    mask1p, m4
+    DIFF_GT2 q0, q2, m5, m4, m7 ; m4 = |q2-q0| > beta-1
+    pand    m4, m6
+    mova    mask1q, m4
+%endif
+    LUMA_INTRA_P012 [r4+r5], [r4+2*r1], [r4+r1], [r4]
+    LUMA_INTRA_SWAP_PQ
+    LUMA_INTRA_P012 [r0], [r0+r1], [r0+2*r1], [r0+r5]
+.end:
+%ifndef ARCH_X86_64
+    add     esp, 0x60
+%endif
+    RET
+
+INIT_MMX
+%ifdef ARCH_X86_64
+;-----------------------------------------------------------------------------
+; void x264_deblock_h_luma_intra_sse2( uint8_t *pix, int stride, int alpha, int beta )
+;-----------------------------------------------------------------------------
+cglobal x264_deblock_h_luma_intra_%1, 4,7
+    movsxd r10, r1d
+    lea    r11, [r10*3]
+    lea    r6,  [r0-4]
+    lea    r5,  [r0-4+r11]
+    sub    rsp, 0x88
+    %define pix_tmp rsp
+
+    ; transpose 8x16 -> tmp space
+    TRANSPOSE8x8_MEM  PASS8ROWS(r6, r5, r10, r11), PASS8ROWS(pix_tmp, pix_tmp+0x30, 0x10, 0x30)
+    lea    r6, [r6+r10*8]
+    lea    r5, [r5+r10*8]
+    TRANSPOSE8x8_MEM  PASS8ROWS(r6, r5, r10, r11), PASS8ROWS(pix_tmp+8, pix_tmp+0x38, 0x10, 0x30)
+
+    lea    r0,  [pix_tmp+0x40]
+    mov    r1,  0x10
+    call   x264_deblock_v_luma_intra_%1
+
+    ; transpose 16x6 -> original space (but we can't write only 6 pixels, so really 16x8)
+    lea    r5, [r6+r11]
+    TRANSPOSE8x8_MEM  PASS8ROWS(pix_tmp+8, pix_tmp+0x38, 0x10, 0x30), PASS8ROWS(r6, r5, r10, r11)
+    shl    r10, 3
+    sub    r6,  r10
+    sub    r5,  r10
+    shr    r10, 3
+    TRANSPOSE8x8_MEM  PASS8ROWS(pix_tmp, pix_tmp+0x30, 0x10, 0x30), PASS8ROWS(r6, r5, r10, r11)
+    add    rsp, 0x88
+    RET
+%else
+cglobal x264_deblock_h_luma_intra_%1, 2,4
+    lea    r3,  [r1*3]
+    sub    r0,  4
+    lea    r2,  [r0+r3]
+%assign pad 0x8c-(stack_offset&15)
+    SUB    rsp, pad
+    %define pix_tmp rsp
+
+    ; transpose 8x16 -> tmp space
+    TRANSPOSE8x8_MEM  PASS8ROWS(r0, r2, r1, r3), PASS8ROWS(pix_tmp, pix_tmp+0x30, 0x10, 0x30)
+    lea    r0,  [r0+r1*8]
+    lea    r2,  [r2+r1*8]
+    TRANSPOSE8x8_MEM  PASS8ROWS(r0, r2, r1, r3), PASS8ROWS(pix_tmp+8, pix_tmp+0x38, 0x10, 0x30)
+
+    lea    r0,  [pix_tmp+0x40]
+    PUSH   dword r3m
+    PUSH   dword r2m
+    PUSH   dword 16
+    PUSH   r0
+    call   x264_deblock_%2_luma_intra_%1
+%ifidn %2, v8
+    add    dword [rsp], 8 ; pix_tmp+8
+    call   x264_deblock_%2_luma_intra_%1
+%endif
+    ADD    esp, 16
+
+    mov    r1,  r1m
+    mov    r0,  r0mp
+    lea    r3,  [r1*3]
+    sub    r0,  4
+    lea    r2,  [r0+r3]
+    ; transpose 16x6 -> original space (but we can't write only 6 pixels, so really 16x8)
+    TRANSPOSE8x8_MEM  PASS8ROWS(pix_tmp, pix_tmp+0x30, 0x10, 0x30), PASS8ROWS(r0, r2, r1, r3)
+    lea    r0,  [r0+r1*8]
+    lea    r2,  [r2+r1*8]
+    TRANSPOSE8x8_MEM  PASS8ROWS(pix_tmp+8, pix_tmp+0x38, 0x10, 0x30), PASS8ROWS(r0, r2, r1, r3)
+    ADD    rsp, pad
+    RET
+%endif ; ARCH_X86_64
+%endmacro ; DEBLOCK_LUMA_INTRA
+
+INIT_XMM
+DEBLOCK_LUMA_INTRA sse2, v
+%ifndef ARCH_X86_64
+INIT_MMX
+DEBLOCK_LUMA_INTRA mmxext, v8
+%endif
+
+
+
+INIT_MMX
+
+%macro CHROMA_V_START 0
+    dec    r2d      ; alpha-1
+    dec    r3d      ; beta-1
+    mov    t5, r0
+    sub    t5, r1
+    sub    t5, r1
+%endmacro
+
+%macro CHROMA_H_START 0
+    dec    r2d
+    dec    r3d
+    sub    r0, 2
+    lea    t6, [r1*3]
+    mov    t5, r0
+    add    r0, t6
+%endmacro
+
+%define t5 r5
+%define t6 r6
+
+;-----------------------------------------------------------------------------
+; void x264_deblock_v_chroma( uint8_t *pix, int stride, int alpha, int beta, int8_t *tc0 )
+;-----------------------------------------------------------------------------
+cglobal x264_deblock_v_chroma_mmxext, 5,6
+    CHROMA_V_START
+    movq  m0, [t5]
+    movq  m1, [t5+r1]
+    movq  m2, [r0]
+    movq  m3, [r0+r1]
+    call x264_chroma_inter_body_mmxext
+    movq  [t5+r1], m1
+    movq  [r0], m2
+    RET
+
+;-----------------------------------------------------------------------------
+; void x264_deblock_h_chroma( uint8_t *pix, int stride, int alpha, int beta, int8_t *tc0 )
+;-----------------------------------------------------------------------------
+cglobal x264_deblock_h_chroma_mmxext, 5,7
+%ifdef ARCH_X86_64
+    %define buf0 [rsp-24]
+    %define buf1 [rsp-16]
+%else
+    %define buf0 r0m
+    %define buf1 r2m
+%endif
+    CHROMA_H_START
+    TRANSPOSE4x8_LOAD  PASS8ROWS(t5, r0, r1, t6)
+    movq  buf0, m0
+    movq  buf1, m3
+    call x264_chroma_inter_body_mmxext
+    movq  m0, buf0
+    movq  m3, buf1
+    TRANSPOSE8x4_STORE PASS8ROWS(t5, r0, r1, t6)
+    RET
+
+ALIGN 16
+x264_chroma_inter_body_mmxext:
+    LOAD_MASK  r2d, r3d
+    movd       m6, [r4] ; tc0
+    punpcklbw  m6, m6
+    pand       m7, m6
+    DEBLOCK_P0_Q0
+    ret
+
+
+
+; in: %1=p0 %2=p1 %3=q1
+; out: p0 = (p0 + q1 + 2*p1 + 2) >> 2
+%macro CHROMA_INTRA_P0 3
+    movq    m4, %1
+    pxor    m4, %3
+    pand    m4, [pb_1] ; m4 = (p0^q1)&1
+    pavgb   %1, %3
+    psubusb %1, m4
+    pavgb   %1, %2             ; dst = avg(p1, avg(p0,q1) - ((p0^q1)&1))
+%endmacro
+
+%define t5 r4
+%define t6 r5
+
+;-----------------------------------------------------------------------------
+; void x264_deblock_v_chroma_intra( uint8_t *pix, int stride, int alpha, int beta )
+;-----------------------------------------------------------------------------
+cglobal x264_deblock_v_chroma_intra_mmxext, 4,5
+    CHROMA_V_START
+    movq  m0, [t5]
+    movq  m1, [t5+r1]
+    movq  m2, [r0]
+    movq  m3, [r0+r1]
+    call x264_chroma_intra_body_mmxext
+    movq  [t5+r1], m1
+    movq  [r0], m2
+    RET
+
+;-----------------------------------------------------------------------------
+; void x264_deblock_h_chroma_intra( uint8_t *pix, int stride, int alpha, int beta )
+;-----------------------------------------------------------------------------
+cglobal x264_deblock_h_chroma_intra_mmxext, 4,6
+    CHROMA_H_START
+    TRANSPOSE4x8_LOAD  PASS8ROWS(t5, r0, r1, t6)
+    call x264_chroma_intra_body_mmxext
+    TRANSPOSE8x4_STORE PASS8ROWS(t5, r0, r1, t6)
+    RET
+
+ALIGN 16
+x264_chroma_intra_body_mmxext:
+    LOAD_MASK r2d, r3d
+    movq   m5, m1
+    movq   m6, m2
+    CHROMA_INTRA_P0  m1, m0, m3
+    CHROMA_INTRA_P0  m2, m3, m0
+    psubb  m1, m5
+    psubb  m2, m6
+    pand   m1, m7
+    pand   m2, m7
+    paddb  m1, m5
+    paddb  m2, m6
+    ret
diff --git a/libavcodec/x86/h264_deblock_sse2.asm b/libavcodec/x86/h264_deblock_sse2.asm
deleted file mode 100644
index bf45c7e..0000000
--- a/libavcodec/x86/h264_deblock_sse2.asm
+++ /dev/null
@@ -1,759 +0,0 @@
-;*****************************************************************************
-;* MMX/SSE2-optimized H.264 deblocking code
-;*****************************************************************************
-;* Copyright (C) 2005-2008 x264 project
-;*
-;* Authors: Loren Merritt <lorenm at u.washington.edu>
-;*
-;* This program is free software; you can redistribute it and/or modify
-;* it under the terms of the GNU General Public License as published by
-;* the Free Software Foundation; either version 2 of the License, or
-;* (at your option) any later version.
-;*
-;* This program is distributed in the hope that it will be useful,
-;* but WITHOUT ANY WARRANTY; without even the implied warranty of
-;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-;* GNU General Public License for more details.
-;*
-;* You should have received a copy of the GNU General Public License
-;* along with this program; if not, write to the Free Software
-;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111, USA.
-;*****************************************************************************
-
-%include "x86inc.asm"
-
-SECTION_RODATA
-pb_00: times 16 db 0x00
-pb_01: times 16 db 0x01
-pb_03: times 16 db 0x03
-pb_a1: times 16 db 0xa1
-
-SECTION .text
-
-; expands to [base],...,[base+7*stride]
-%define PASS8ROWS(base, base3, stride, stride3) \
-    [base], [base+stride], [base+stride*2], [base3], \
-    [base3+stride], [base3+stride*2], [base3+stride3], [base3+stride*4]
-
-; in: 8 rows of 4 bytes in %1..%8
-; out: 4 rows of 8 bytes in m0..m3
-%macro TRANSPOSE4x8_LOAD 8
-    movd       m0, %1
-    movd       m2, %2
-    movd       m1, %3
-    movd       m3, %4
-    punpcklbw  m0, m2
-    punpcklbw  m1, m3
-    movq       m2, m0
-    punpcklwd  m0, m1
-    punpckhwd  m2, m1
-
-    movd       m4, %5
-    movd       m6, %6
-    movd       m5, %7
-    movd       m7, %8
-    punpcklbw  m4, m6
-    punpcklbw  m5, m7
-    movq       m6, m4
-    punpcklwd  m4, m5
-    punpckhwd  m6, m5
-
-    movq       m1, m0
-    movq       m3, m2
-    punpckldq  m0, m4
-    punpckhdq  m1, m4
-    punpckldq  m2, m6
-    punpckhdq  m3, m6
-%endmacro
-
-; in: 4 rows of 8 bytes in m0..m3
-; out: 8 rows of 4 bytes in %1..%8
-%macro TRANSPOSE8x4_STORE 8
-    movq       m4, m0
-    movq       m5, m1
-    movq       m6, m2
-    punpckhdq  m4, m4
-    punpckhdq  m5, m5
-    punpckhdq  m6, m6
-
-    punpcklbw  m0, m1
-    punpcklbw  m2, m3
-    movq       m1, m0
-    punpcklwd  m0, m2
-    punpckhwd  m1, m2
-    movd       %1, m0
-    punpckhdq  m0, m0
-    movd       %2, m0
-    movd       %3, m1
-    punpckhdq  m1, m1
-    movd       %4, m1
-
-    punpckhdq  m3, m3
-    punpcklbw  m4, m5
-    punpcklbw  m6, m3
-    movq       m5, m4
-    punpcklwd  m4, m6
-    punpckhwd  m5, m6
-    movd       %5, m4
-    punpckhdq  m4, m4
-    movd       %6, m4
-    movd       %7, m5
-    punpckhdq  m5, m5
-    movd       %8, m5
-%endmacro
-
-%macro SBUTTERFLY 4
-    movq       %4, %2
-    punpckl%1  %2, %3
-    punpckh%1  %4, %3
-%endmacro
-
-; in: 8 rows of 8 (only the middle 6 pels are used) in %1..%8
-; out: 6 rows of 8 in [%9+0*16] .. [%9+5*16]
-%macro TRANSPOSE6x8_MEM 9
-    movq  m0, %1
-    movq  m1, %2
-    movq  m2, %3
-    movq  m3, %4
-    movq  m4, %5
-    movq  m5, %6
-    movq  m6, %7
-    SBUTTERFLY bw, m0, m1, m7
-    SBUTTERFLY bw, m2, m3, m1
-    SBUTTERFLY bw, m4, m5, m3
-    movq  [%9+0x10], m1
-    SBUTTERFLY bw, m6, %8, m5
-    SBUTTERFLY wd, m0, m2, m1
-    SBUTTERFLY wd, m4, m6, m2
-    punpckhdq m0, m4
-    movq  [%9+0x00], m0
-    SBUTTERFLY wd, m7, [%9+0x10], m6
-    SBUTTERFLY wd, m3, m5, m4
-    SBUTTERFLY dq, m7, m3, m0
-    SBUTTERFLY dq, m1, m2, m5
-    punpckldq m6, m4
-    movq  [%9+0x10], m1
-    movq  [%9+0x20], m5
-    movq  [%9+0x30], m7
-    movq  [%9+0x40], m0
-    movq  [%9+0x50], m6
-%endmacro
-
-; in: 8 rows of 8 in %1..%8
-; out: 8 rows of 8 in %9..%16
-%macro TRANSPOSE8x8_MEM 16
-    movq  m0, %1
-    movq  m1, %2
-    movq  m2, %3
-    movq  m3, %4
-    movq  m4, %5
-    movq  m5, %6
-    movq  m6, %7
-    SBUTTERFLY bw, m0, m1, m7
-    SBUTTERFLY bw, m2, m3, m1
-    SBUTTERFLY bw, m4, m5, m3
-    SBUTTERFLY bw, m6, %8, m5
-    movq  %9,  m3
-    SBUTTERFLY wd, m0, m2, m3
-    SBUTTERFLY wd, m4, m6, m2
-    SBUTTERFLY wd, m7, m1, m6
-    movq  %11, m2
-    movq  m2,  %9
-    SBUTTERFLY wd, m2, m5, m1
-    SBUTTERFLY dq, m0, m4, m5
-    SBUTTERFLY dq, m7, m2, m4
-    movq  %9,  m0
-    movq  %10, m5
-    movq  %13, m7
-    movq  %14, m4
-    SBUTTERFLY dq, m3, %11, m0
-    SBUTTERFLY dq, m6, m1, m5
-    movq  %11, m3
-    movq  %12, m0
-    movq  %15, m6
-    movq  %16, m5
-%endmacro
-
-; out: %4 = |%1-%2|>%3
-; clobbers: %5
-%macro DIFF_GT 5
-    mova    %5, %2
-    mova    %4, %1
-    psubusb %5, %1
-    psubusb %4, %2
-    por     %4, %5
-    psubusb %4, %3
-%endmacro
-
-; out: %4 = |%1-%2|>%3
-; clobbers: %5
-%macro DIFF_GT2 5
-    mova    %5, %2
-    mova    %4, %1
-    psubusb %5, %1
-    psubusb %4, %2
-    psubusb %5, %3
-    psubusb %4, %3
-    pcmpeqb %4, %5
-%endmacro
-
-%macro SPLATW 1
-%ifidn m0, xmm0
-    pshuflw  %1, %1, 0
-    punpcklqdq %1, %1
-%else
-    pshufw   %1, %1, 0
-%endif
-%endmacro
-
-; in: m0=p1 m1=p0 m2=q0 m3=q1 %1=alpha-1 %2=beta-1
-; out: m5=beta-1, m7=mask, %3=alpha-1
-; clobbers: m4,m6
-%macro LOAD_MASK 2-3
-    movd     m4, %1
-    movd     m5, %2
-    SPLATW   m4
-    SPLATW   m5
-    packuswb m4, m4  ; 16x alpha-1
-    packuswb m5, m5  ; 16x beta-1
-%if %0>2
-    mova     %3, m4
-%endif
-    DIFF_GT  m1, m2, m4, m7, m6 ; |p0-q0| > alpha-1
-    DIFF_GT  m0, m1, m5, m4, m6 ; |p1-p0| > beta-1
-    por      m7, m4
-    DIFF_GT  m3, m2, m5, m4, m6 ; |q1-q0| > beta-1
-    por      m7, m4
-    pxor     m6, m6
-    pcmpeqb  m7, m6
-%endmacro
-
-; in: m0=p1 m1=p0 m2=q0 m3=q1 m7=(tc&mask)
-; out: m1=p0' m2=q0'
-; clobbers: m0,3-6
-%macro DEBLOCK_P0_Q0 0
-    mova    m5, m1
-    pxor    m5, m2           ; p0^q0
-    pand    m5, [pb_01 GLOBAL] ; (p0^q0)&1
-    pcmpeqb m4, m4
-    pxor    m3, m4
-    pavgb   m3, m0           ; (p1 - q1 + 256)>>1
-    pavgb   m3, [pb_03 GLOBAL] ; (((p1 - q1 + 256)>>1)+4)>>1 = 64+2+(p1-q1)>>2
-    pxor    m4, m1
-    pavgb   m4, m2           ; (q0 - p0 + 256)>>1
-    pavgb   m3, m5
-    paddusb m3, m4           ; d+128+33
-    mova    m6, [pb_a1 GLOBAL]
-    psubusb m6, m3
-    psubusb m3, [pb_a1 GLOBAL]
-    pminub  m6, m7
-    pminub  m3, m7
-    psubusb m1, m6
-    psubusb m2, m3
-    paddusb m1, m3
-    paddusb m2, m6
-%endmacro
-
-; in: m1=p0 m2=q0
-;     %1=p1 %2=q2 %3=[q2] %4=[q1] %5=tc0 %6=tmp
-; out: [q1] = clip( (q2+((p0+q0+1)>>1))>>1, q1-tc0, q1+tc0 )
-; clobbers: q2, tmp, tc0
-%macro LUMA_Q1 6
-    mova    %6, m1
-    pavgb   %6, m2
-    pavgb   %2, %6             ; avg(p2,avg(p0,q0))
-    pxor    %6, %3
-    pand    %6, [pb_01 GLOBAL] ; (p2^avg(p0,q0))&1
-    psubusb %2, %6             ; (p2+((p0+q0+1)>>1))>>1
-    mova    %6, %1
-    psubusb %6, %5
-    paddusb %5, %1
-    pmaxub  %2, %6
-    pminub  %2, %5
-    mova    %4, %2
-%endmacro
-
-%ifdef ARCH_X86_64
-;-----------------------------------------------------------------------------
-; void x264_deblock_v_luma_sse2( uint8_t *pix, int stride, int alpha, int beta, int8_t *tc0 )
-;-----------------------------------------------------------------------------
-INIT_XMM
-cglobal x264_deblock_v_luma_sse2, 5,5,10
-    movd    m8, [r4] ; tc0
-    lea     r4, [r1*3]
-    dec     r2d        ; alpha-1
-    neg     r4
-    dec     r3d        ; beta-1
-    add     r4, r0     ; pix-3*stride
-
-    mova    m0, [r4+r1]   ; p1
-    mova    m1, [r4+2*r1] ; p0
-    mova    m2, [r0]      ; q0
-    mova    m3, [r0+r1]   ; q1
-    LOAD_MASK r2d, r3d
-
-    punpcklbw m8, m8
-    punpcklbw m8, m8 ; tc = 4x tc0[3], 4x tc0[2], 4x tc0[1], 4x tc0[0]
-    pcmpeqb m9, m9
-    pcmpeqb m9, m8
-    pandn   m9, m7
-    pand    m8, m9
-
-    movdqa  m3, [r4] ; p2
-    DIFF_GT2 m1, m3, m5, m6, m7 ; |p2-p0| > beta-1
-    pand    m6, m9
-    mova    m7, m8
-    psubb   m7, m6
-    pand    m6, m8
-    LUMA_Q1 m0, m3, [r4], [r4+r1], m6, m4
-
-    movdqa  m4, [r0+2*r1] ; q2
-    DIFF_GT2 m2, m4, m5, m6, m3 ; |q2-q0| > beta-1
-    pand    m6, m9
-    pand    m8, m6
-    psubb   m7, m6
-    mova    m3, [r0+r1]
-    LUMA_Q1 m3, m4, [r0+2*r1], [r0+r1], m8, m6
-
-    DEBLOCK_P0_Q0
-    mova    [r4+2*r1], m1
-    mova    [r0], m2
-    RET
-
-;-----------------------------------------------------------------------------
-; void x264_deblock_h_luma_sse2( uint8_t *pix, int stride, int alpha, int beta, int8_t *tc0 )
-;-----------------------------------------------------------------------------
-INIT_MMX
-cglobal x264_deblock_h_luma_sse2, 5,7
-    movsxd r10, r1d
-    lea    r11, [r10+r10*2]
-    lea    r6,  [r0-4]
-    lea    r5,  [r0-4+r11]
-%ifdef WIN64
-    sub    rsp, 0x98
-    %define pix_tmp rsp+0x30
-%else
-    sub    rsp, 0x68
-    %define pix_tmp rsp
-%endif
-
-    ; transpose 6x16 -> tmp space
-    TRANSPOSE6x8_MEM  PASS8ROWS(r6, r5, r10, r11), pix_tmp
-    lea    r6, [r6+r10*8]
-    lea    r5, [r5+r10*8]
-    TRANSPOSE6x8_MEM  PASS8ROWS(r6, r5, r10, r11), pix_tmp+8
-
-    ; vertical filter
-    ; alpha, beta, tc0 are still in r2d, r3d, r4
-    ; don't backup r6, r5, r10, r11 because x264_deblock_v_luma_sse2 doesn't use them
-    lea    r0, [pix_tmp+0x30]
-    mov    r1d, 0x10
-%ifdef WIN64
-    mov    [rsp+0x20], r4
-%endif
-    call   x264_deblock_v_luma_sse2
-
-    ; transpose 16x4 -> original space  (only the middle 4 rows were changed by the filter)
-    add    r6, 2
-    add    r5, 2
-    movq   m0, [pix_tmp+0x18]
-    movq   m1, [pix_tmp+0x28]
-    movq   m2, [pix_tmp+0x38]
-    movq   m3, [pix_tmp+0x48]
-    TRANSPOSE8x4_STORE  PASS8ROWS(r6, r5, r10, r11)
-
-    shl    r10, 3
-    sub    r6,  r10
-    sub    r5,  r10
-    shr    r10, 3
-    movq   m0, [pix_tmp+0x10]
-    movq   m1, [pix_tmp+0x20]
-    movq   m2, [pix_tmp+0x30]
-    movq   m3, [pix_tmp+0x40]
-    TRANSPOSE8x4_STORE  PASS8ROWS(r6, r5, r10, r11)
-
-%ifdef WIN64
-    add    rsp, 0x98
-%else
-    add    rsp, 0x68
-%endif
-    RET
-
-%else
-
-%macro DEBLOCK_LUMA 3
-;-----------------------------------------------------------------------------
-; void x264_deblock_v8_luma_mmxext( uint8_t *pix, int stride, int alpha, int beta, int8_t *tc0 )
-;-----------------------------------------------------------------------------
-cglobal x264_deblock_%2_luma_%1, 5,5
-    lea     r4, [r1*3]
-    dec     r2     ; alpha-1
-    neg     r4
-    dec     r3     ; beta-1
-    add     r4, r0 ; pix-3*stride
-    %assign pad 2*%3+12-(stack_offset&15)
-    SUB     esp, pad
-
-    mova    m0, [r4+r1]   ; p1
-    mova    m1, [r4+2*r1] ; p0
-    mova    m2, [r0]      ; q0
-    mova    m3, [r0+r1]   ; q1
-    LOAD_MASK r2, r3
-
-    mov     r3, r4mp
-    movd    m4, [r3] ; tc0
-    punpcklbw m4, m4
-    punpcklbw m4, m4 ; tc = 4x tc0[3], 4x tc0[2], 4x tc0[1], 4x tc0[0]
-    mova   [esp+%3], m4 ; tc
-    pcmpeqb m3, m3
-    pcmpgtb m4, m3
-    pand    m4, m7
-    mova   [esp], m4 ; mask
-
-    mova    m3, [r4] ; p2
-    DIFF_GT2 m1, m3, m5, m6, m7 ; |p2-p0| > beta-1
-    pand    m6, m4
-    pand    m4, [esp+%3] ; tc
-    mova    m7, m4
-    psubb   m7, m6
-    pand    m6, m4
-    LUMA_Q1 m0, m3, [r4], [r4+r1], m6, m4
-
-    mova    m4, [r0+2*r1] ; q2
-    DIFF_GT2 m2, m4, m5, m6, m3 ; |q2-q0| > beta-1
-    mova    m5, [esp] ; mask
-    pand    m6, m5
-    mova    m5, [esp+%3] ; tc
-    pand    m5, m6
-    psubb   m7, m6
-    mova    m3, [r0+r1]
-    LUMA_Q1 m3, m4, [r0+2*r1], [r0+r1], m5, m6
-
-    DEBLOCK_P0_Q0
-    mova    [r4+2*r1], m1
-    mova    [r0], m2
-    ADD     esp, pad
-    RET
-
-;-----------------------------------------------------------------------------
-; void x264_deblock_h_luma_mmxext( uint8_t *pix, int stride, int alpha, int beta, int8_t *tc0 )
-;-----------------------------------------------------------------------------
-INIT_MMX
-cglobal x264_deblock_h_luma_%1, 0,5
-    mov    r0, r0mp
-    mov    r3, r1m
-    lea    r4, [r3*3]
-    sub    r0, 4
-    lea    r1, [r0+r4]
-    %assign pad 0x78-(stack_offset&15)
-    SUB    esp, pad
-%define pix_tmp esp+12
-
-    ; transpose 6x16 -> tmp space
-    TRANSPOSE6x8_MEM  PASS8ROWS(r0, r1, r3, r4), pix_tmp
-    lea    r0, [r0+r3*8]
-    lea    r1, [r1+r3*8]
-    TRANSPOSE6x8_MEM  PASS8ROWS(r0, r1, r3, r4), pix_tmp+8
-
-    ; vertical filter
-    lea    r0, [pix_tmp+0x30]
-    PUSH   dword r4m
-    PUSH   dword r3m
-    PUSH   dword r2m
-    PUSH   dword 16
-    PUSH   dword r0
-    call   x264_deblock_%2_luma_%1
-%ifidn %2, v8
-    add    dword [esp   ], 8 ; pix_tmp+0x38
-    add    dword [esp+16], 2 ; tc0+2
-    call   x264_deblock_%2_luma_%1
-%endif
-    ADD    esp, 20
-
-    ; transpose 16x4 -> original space  (only the middle 4 rows were changed by the filter)
-    mov    r0, r0mp
-    sub    r0, 2
-    lea    r1, [r0+r4]
-
-    movq   m0, [pix_tmp+0x10]
-    movq   m1, [pix_tmp+0x20]
-    movq   m2, [pix_tmp+0x30]
-    movq   m3, [pix_tmp+0x40]
-    TRANSPOSE8x4_STORE  PASS8ROWS(r0, r1, r3, r4)
-
-    lea    r0, [r0+r3*8]
-    lea    r1, [r1+r3*8]
-    movq   m0, [pix_tmp+0x18]
-    movq   m1, [pix_tmp+0x28]
-    movq   m2, [pix_tmp+0x38]
-    movq   m3, [pix_tmp+0x48]
-    TRANSPOSE8x4_STORE  PASS8ROWS(r0, r1, r3, r4)
-
-    ADD    esp, pad
-    RET
-%endmacro ; DEBLOCK_LUMA
-
-INIT_XMM
-DEBLOCK_LUMA sse2, v, 16
-
-%endif ; ARCH
-
-
-
-%macro LUMA_INTRA_P012 4 ; p0..p3 in memory
-    mova  t0, p2
-    mova  t1, p0
-    pavgb t0, p1
-    pavgb t1, q0
-    pavgb t0, t1 ; ((p2+p1+1)/2 + (p0+q0+1)/2 + 1)/2
-    mova  t5, t1
-    mova  t2, p2
-    mova  t3, p0
-    paddb t2, p1
-    paddb t3, q0
-    paddb t2, t3
-    mova  t3, t2
-    mova  t4, t2
-    psrlw t2, 1
-    pavgb t2, mpb_00
-    pxor  t2, t0
-    pand  t2, mpb_01
-    psubb t0, t2 ; p1' = (p2+p1+p0+q0+2)/4;
-
-    mova  t1, p2
-    mova  t2, p2
-    pavgb t1, q1
-    psubb t2, q1
-    paddb t3, t3
-    psubb t3, t2 ; p2+2*p1+2*p0+2*q0+q1
-    pand  t2, mpb_01
-    psubb t1, t2
-    pavgb t1, p1
-    pavgb t1, t5 ; (((p2+q1)/2 + p1+1)/2 + (p0+q0+1)/2 + 1)/2
-    psrlw t3, 2
-    pavgb t3, mpb_00
-    pxor  t3, t1
-    pand  t3, mpb_01
-    psubb t1, t3 ; p0'a = (p2+2*p1+2*p0+2*q0+q1+4)/8
-
-    mova  t3, p0
-    mova  t2, p0
-    pxor  t3, q1
-    pavgb t2, q1
-    pand  t3, mpb_01
-    psubb t2, t3
-    pavgb t2, p1 ; p0'b = (2*p1+p0+q0+2)/4
-
-    pxor  t1, t2
-    pxor  t2, p0
-    pand  t1, mask1p
-    pand  t2, mask0
-    pxor  t1, t2
-    pxor  t1, p0
-    mova  %1, t1 ; store p0
-
-    mova  t1, %4 ; p3
-    mova  t2, t1
-    pavgb t1, p2
-    paddb t2, p2
-    pavgb t1, t0 ; (p3+p2+1)/2 + (p2+p1+p0+q0+2)/4
-    paddb t2, t2
-    paddb t2, t4 ; 2*p3+3*p2+p1+p0+q0
-    psrlw t2, 2
-    pavgb t2, mpb_00
-    pxor  t2, t1
-    pand  t2, mpb_01
-    psubb t1, t2 ; p2' = (2*p3+3*p2+p1+p0+q0+4)/8
-
-    pxor  t0, p1
-    pxor  t1, p2
-    pand  t0, mask1p
-    pand  t1, mask1p
-    pxor  t0, p1
-    pxor  t1, p2
-    mova  %2, t0 ; store p1
-    mova  %3, t1 ; store p2
-%endmacro
-
-%macro LUMA_INTRA_SWAP_PQ 0
-    %define q1 m0
-    %define q0 m1
-    %define p0 m2
-    %define p1 m3
-    %define p2 q2
-    %define mask1p mask1q
-%endmacro
-
-%macro DEBLOCK_LUMA_INTRA 2
-    %define p1 m0
-    %define p0 m1
-    %define q0 m2
-    %define q1 m3
-    %define t0 m4
-    %define t1 m5
-    %define t2 m6
-    %define t3 m7
-%ifdef ARCH_X86_64
-    %define p2 m8
-    %define q2 m9
-    %define t4 m10
-    %define t5 m11
-    %define mask0 m12
-    %define mask1p m13
-    %define mask1q [rsp-24]
-    %define mpb_00 m14
-    %define mpb_01 m15
-%else
-    %define spill(x) [esp+16*x+((stack_offset+4)&15)]
-    %define p2 [r4+r1]
-    %define q2 [r0+2*r1]
-    %define t4 spill(0)
-    %define t5 spill(1)
-    %define mask0 spill(2)
-    %define mask1p spill(3)
-    %define mask1q spill(4)
-    %define mpb_00 [pb_00 GLOBAL]
-    %define mpb_01 [pb_01 GLOBAL]
-%endif
-
-;-----------------------------------------------------------------------------
-; void x264_deblock_v_luma_intra_sse2( uint8_t *pix, int stride, int alpha, int beta )
-;-----------------------------------------------------------------------------
-cglobal x264_deblock_%2_luma_intra_%1, 4,6,16
-%ifndef ARCH_X86_64
-    sub     esp, 0x60
-%endif
-    lea     r4, [r1*4]
-    lea     r5, [r1*3] ; 3*stride
-    dec     r2d        ; alpha-1
-    jl .end
-    neg     r4
-    dec     r3d        ; beta-1
-    jl .end
-    add     r4, r0     ; pix-4*stride
-    mova    p1, [r4+2*r1]
-    mova    p0, [r4+r5]
-    mova    q0, [r0]
-    mova    q1, [r0+r1]
-%ifdef ARCH_X86_64
-    pxor    mpb_00, mpb_00
-    mova    mpb_01, [pb_01 GLOBAL]
-    LOAD_MASK r2d, r3d, t5 ; m5=beta-1, t5=alpha-1, m7=mask0
-    SWAP    7, 12 ; m12=mask0
-    pavgb   t5, mpb_00
-    pavgb   t5, mpb_01 ; alpha/4+1
-    movdqa  p2, [r4+r1]
-    movdqa  q2, [r0+2*r1]
-    DIFF_GT2 p0, q0, t5, t0, t3 ; t0 = |p0-q0| > alpha/4+1
-    DIFF_GT2 p0, p2, m5, t2, t5 ; mask1 = |p2-p0| > beta-1
-    DIFF_GT2 q0, q2, m5, t4, t5 ; t4 = |q2-q0| > beta-1
-    pand    t0, mask0
-    pand    t4, t0
-    pand    t2, t0
-    mova    mask1q, t4
-    mova    mask1p, t2
-%else
-    LOAD_MASK r2d, r3d, t5 ; m5=beta-1, t5=alpha-1, m7=mask0
-    mova    m4, t5
-    mova    mask0, m7
-    pavgb   m4, [pb_00 GLOBAL]
-    pavgb   m4, [pb_01 GLOBAL] ; alpha/4+1
-    DIFF_GT2 p0, q0, m4, m6, m7 ; m6 = |p0-q0| > alpha/4+1
-    pand    m6, mask0
-    DIFF_GT2 p0, p2, m5, m4, m7 ; m4 = |p2-p0| > beta-1
-    pand    m4, m6
-    mova    mask1p, m4
-    DIFF_GT2 q0, q2, m5, m4, m7 ; m4 = |q2-q0| > beta-1
-    pand    m4, m6
-    mova    mask1q, m4
-%endif
-    LUMA_INTRA_P012 [r4+r5], [r4+2*r1], [r4+r1], [r4]
-    LUMA_INTRA_SWAP_PQ
-    LUMA_INTRA_P012 [r0], [r0+r1], [r0+2*r1], [r0+r5]
-.end:
-%ifndef ARCH_X86_64
-    add     esp, 0x60
-%endif
-    RET
-
-INIT_MMX
-%ifdef ARCH_X86_64
-;-----------------------------------------------------------------------------
-; void x264_deblock_h_luma_intra_sse2( uint8_t *pix, int stride, int alpha, int beta )
-;-----------------------------------------------------------------------------
-cglobal x264_deblock_h_luma_intra_%1, 4,7
-    movsxd r10, r1d
-    lea    r11, [r10*3]
-    lea    r6,  [r0-4]
-    lea    r5,  [r0-4+r11]
-    sub    rsp, 0x88
-    %define pix_tmp rsp
-
-    ; transpose 8x16 -> tmp space
-    TRANSPOSE8x8_MEM  PASS8ROWS(r6, r5, r10, r11), PASS8ROWS(pix_tmp, pix_tmp+0x30, 0x10, 0x30)
-    lea    r6, [r6+r10*8]
-    lea    r5, [r5+r10*8]
-    TRANSPOSE8x8_MEM  PASS8ROWS(r6, r5, r10, r11), PASS8ROWS(pix_tmp+8, pix_tmp+0x38, 0x10, 0x30)
-
-    lea    r0,  [pix_tmp+0x40]
-    mov    r1,  0x10
-    call   x264_deblock_v_luma_intra_%1
-
-    ; transpose 16x6 -> original space (but we can't write only 6 pixels, so really 16x8)
-    lea    r5, [r6+r11]
-    TRANSPOSE8x8_MEM  PASS8ROWS(pix_tmp+8, pix_tmp+0x38, 0x10, 0x30), PASS8ROWS(r6, r5, r10, r11)
-    shl    r10, 3
-    sub    r6,  r10
-    sub    r5,  r10
-    shr    r10, 3
-    TRANSPOSE8x8_MEM  PASS8ROWS(pix_tmp, pix_tmp+0x30, 0x10, 0x30), PASS8ROWS(r6, r5, r10, r11)
-    add    rsp, 0x88
-    RET
-%else
-cglobal x264_deblock_h_luma_intra_%1, 2,4
-    lea    r3,  [r1*3]
-    sub    r0,  4
-    lea    r2,  [r0+r3]
-%assign pad 0x8c-(stack_offset&15)
-    SUB    rsp, pad
-    %define pix_tmp rsp
-
-    ; transpose 8x16 -> tmp space
-    TRANSPOSE8x8_MEM  PASS8ROWS(r0, r2, r1, r3), PASS8ROWS(pix_tmp, pix_tmp+0x30, 0x10, 0x30)
-    lea    r0,  [r0+r1*8]
-    lea    r2,  [r2+r1*8]
-    TRANSPOSE8x8_MEM  PASS8ROWS(r0, r2, r1, r3), PASS8ROWS(pix_tmp+8, pix_tmp+0x38, 0x10, 0x30)
-
-    lea    r0,  [pix_tmp+0x40]
-    PUSH   dword r3m
-    PUSH   dword r2m
-    PUSH   dword 16
-    PUSH   r0
-    call   x264_deblock_%2_luma_intra_%1
-%ifidn %2, v8
-    add    dword [rsp], 8 ; pix_tmp+8
-    call   x264_deblock_%2_luma_intra_%1
-%endif
-    ADD    esp, 16
-
-    mov    r1,  r1m
-    mov    r0,  r0mp
-    lea    r3,  [r1*3]
-    sub    r0,  4
-    lea    r2,  [r0+r3]
-    ; transpose 16x6 -> original space (but we can't write only 6 pixels, so really 16x8)
-    TRANSPOSE8x8_MEM  PASS8ROWS(pix_tmp, pix_tmp+0x30, 0x10, 0x30), PASS8ROWS(r0, r2, r1, r3)
-    lea    r0,  [r0+r1*8]
-    lea    r2,  [r2+r1*8]
-    TRANSPOSE8x8_MEM  PASS8ROWS(pix_tmp+8, pix_tmp+0x38, 0x10, 0x30), PASS8ROWS(r0, r2, r1, r3)
-    ADD    rsp, pad
-    RET
-%endif ; ARCH_X86_64
-%endmacro ; DEBLOCK_LUMA_INTRA
-
-INIT_XMM
-DEBLOCK_LUMA_INTRA sse2, v
-%ifndef ARCH_X86_64
-INIT_MMX
-DEBLOCK_LUMA_INTRA mmxext, v8
-%endif
diff --git a/libavcodec/x86/h264_i386.h b/libavcodec/x86/h264_i386.h
index 26c163b..c850dc2 100644
--- a/libavcodec/x86/h264_i386.h
+++ b/libavcodec/x86/h264_i386.h
@@ -2,20 +2,20 @@
  * H.26L/H.264/AVC/JVT/14496-10/... encoder/decoder
  * Copyright (c) 2003 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/x86/h264_idct.asm b/libavcodec/x86/h264_idct.asm
new file mode 100644
index 0000000..a1adb9e
--- /dev/null
+++ b/libavcodec/x86/h264_idct.asm
@@ -0,0 +1,1010 @@
+;*****************************************************************************
+;* MMX/SSE2-optimized H.264 iDCT
+;*****************************************************************************
+;* Copyright (C) 2004-2005 Michael Niedermayer, Loren Merritt
+;* Copyright (C) 2003-2008 x264 project
+;*
+;* Authors: Laurent Aimar <fenrir at via.ecp.fr>
+;*          Loren Merritt <lorenm at u.washington.edu>
+;*          Holger Lubitz <hal at duncan.ol.sub.de>
+;*          Min Chen <chenm001.163.com>
+;*
+;* This file is part of Libav.
+;*
+;* Libav is free software; you can redistribute it and/or
+;* modify it under the terms of the GNU Lesser General Public
+;* License as published by the Free Software Foundation; either
+;* version 2.1 of the License, or (at your option) any later version.
+;*
+;* Libav is distributed in the hope that it will be useful,
+;* but WITHOUT ANY WARRANTY; without even the implied warranty of
+;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+;* Lesser General Public License for more details.
+;*
+;* You should have received a copy of the GNU Lesser General Public
+;* License along with Libav; if not, write to the Free Software
+;* 51, Inc., Foundation Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+;*****************************************************************************
+
+%include "x86inc.asm"
+%include "x86util.asm"
+
+SECTION_RODATA
+
+; FIXME this table is a duplicate from h264data.h, and will be removed once the tables from, h264 have been split
+scan8_mem: db 4+1*8, 5+1*8, 4+2*8, 5+2*8
+           db 6+1*8, 7+1*8, 6+2*8, 7+2*8
+           db 4+3*8, 5+3*8, 4+4*8, 5+4*8
+           db 6+3*8, 7+3*8, 6+4*8, 7+4*8
+           db 1+1*8, 2+1*8
+           db 1+2*8, 2+2*8
+           db 1+4*8, 2+4*8
+           db 1+5*8, 2+5*8
+%ifdef PIC
+%define scan8 r11
+%else
+%define scan8 scan8_mem
+%endif
+
+cextern pw_32
+cextern pw_1
+
+SECTION .text
+
+; %1=uint8_t *dst, %2=int16_t *block, %3=int stride
+%macro IDCT4_ADD 3
+    ; Load dct coeffs
+    movq         m0, [%2]
+    movq         m1, [%2+8]
+    movq         m2, [%2+16]
+    movq         m3, [%2+24]
+
+    IDCT4_1D      0, 1, 2, 3, 4, 5
+    mova         m6, [pw_32]
+    TRANSPOSE4x4W 0, 1, 2, 3, 4
+    paddw        m0, m6
+    IDCT4_1D      0, 1, 2, 3, 4, 5
+    pxor         m7, m7
+
+    STORE_DIFFx2 m0, m1, m4, m5, m7, 6, %1, %3
+    lea          %1, [%1+%3*2]
+    STORE_DIFFx2 m2, m3, m4, m5, m7, 6, %1, %3
+%endmacro
+
+INIT_MMX
+; ff_h264_idct_add_mmx(uint8_t *dst, int16_t *block, int stride)
+cglobal h264_idct_add_mmx, 3, 3, 0
+    IDCT4_ADD    r0, r1, r2
+    RET
+
+%macro IDCT8_1D 2
+    mova         m4, m5
+    mova         m0, m1
+    psraw        m4, 1
+    psraw        m1, 1
+    paddw        m4, m5
+    paddw        m1, m0
+    paddw        m4, m7
+    paddw        m1, m5
+    psubw        m4, m0
+    paddw        m1, m3
+
+    psubw        m0, m3
+    psubw        m5, m3
+    paddw        m0, m7
+    psubw        m5, m7
+    psraw        m3, 1
+    psraw        m7, 1
+    psubw        m0, m3
+    psubw        m5, m7
+
+    mova         m3, m4
+    mova         m7, m1
+    psraw        m1, 2
+    psraw        m3, 2
+    paddw        m3, m0
+    psraw        m0, 2
+    paddw        m1, m5
+    psraw        m5, 2
+    psubw        m0, m4
+    psubw        m7, m5
+
+    mova         m4, m2
+    mova         m5, m6
+    psraw        m4, 1
+    psraw        m6, 1
+    psubw        m4, m5
+    paddw        m6, m2
+
+    mova         m2, %1
+    mova         m5, %2
+    SUMSUB_BA    m5, m2
+    SUMSUB_BA    m6, m5
+    SUMSUB_BA    m4, m2
+    SUMSUB_BA    m7, m6
+    SUMSUB_BA    m0, m4
+    SUMSUB_BA    m3, m2
+    SUMSUB_BA    m1, m5
+    SWAP          7, 6, 4, 5, 2, 3, 1, 0 ; 70315246 -> 01234567
+%endmacro
+
+%macro IDCT8_1D_FULL 1
+    mova         m7, [%1+112]
+    mova         m6, [%1+ 96]
+    mova         m5, [%1+ 80]
+    mova         m3, [%1+ 48]
+    mova         m2, [%1+ 32]
+    mova         m1, [%1+ 16]
+    IDCT8_1D   [%1], [%1+ 64]
+%endmacro
+
+; %1=int16_t *block, %2=int16_t *dstblock
+%macro IDCT8_ADD_MMX_START 2
+    IDCT8_1D_FULL %1
+    mova       [%1], m7
+    TRANSPOSE4x4W 0, 1, 2, 3, 7
+    mova         m7, [%1]
+    mova    [%2   ], m0
+    mova    [%2+16], m1
+    mova    [%2+32], m2
+    mova    [%2+48], m3
+    TRANSPOSE4x4W 4, 5, 6, 7, 3
+    mova    [%2+ 8], m4
+    mova    [%2+24], m5
+    mova    [%2+40], m6
+    mova    [%2+56], m7
+%endmacro
+
+; %1=uint8_t *dst, %2=int16_t *block, %3=int stride
+%macro IDCT8_ADD_MMX_END 3
+    IDCT8_1D_FULL %2
+    mova    [%2   ], m5
+    mova    [%2+16], m6
+    mova    [%2+32], m7
+
+    pxor         m7, m7
+    STORE_DIFFx2 m0, m1, m5, m6, m7, 6, %1, %3
+    lea          %1, [%1+%3*2]
+    STORE_DIFFx2 m2, m3, m5, m6, m7, 6, %1, %3
+    mova         m0, [%2   ]
+    mova         m1, [%2+16]
+    mova         m2, [%2+32]
+    lea          %1, [%1+%3*2]
+    STORE_DIFFx2 m4, m0, m5, m6, m7, 6, %1, %3
+    lea          %1, [%1+%3*2]
+    STORE_DIFFx2 m1, m2, m5, m6, m7, 6, %1, %3
+%endmacro
+
+INIT_MMX
+; ff_h264_idct8_add_mmx(uint8_t *dst, int16_t *block, int stride)
+cglobal h264_idct8_add_mmx, 3, 4, 0
+    %assign pad 128+4-(stack_offset&7)
+    SUB         rsp, pad
+
+    add   word [r1], 32
+    IDCT8_ADD_MMX_START r1  , rsp
+    IDCT8_ADD_MMX_START r1+8, rsp+64
+    lea          r3, [r0+4]
+    IDCT8_ADD_MMX_END   r0  , rsp,   r2
+    IDCT8_ADD_MMX_END   r3  , rsp+8, r2
+
+    ADD         rsp, pad
+    RET
+
+; %1=uint8_t *dst, %2=int16_t *block, %3=int stride
+%macro IDCT8_ADD_SSE 4
+    IDCT8_1D_FULL %2
+%ifdef ARCH_X86_64
+    TRANSPOSE8x8W 0, 1, 2, 3, 4, 5, 6, 7, 8
+%else
+    TRANSPOSE8x8W 0, 1, 2, 3, 4, 5, 6, 7, [%2], [%2+16]
+%endif
+    paddw        m0, [pw_32]
+
+%ifndef ARCH_X86_64
+    mova    [%2   ], m0
+    mova    [%2+16], m4
+    IDCT8_1D   [%2], [%2+ 16]
+    mova    [%2   ], m6
+    mova    [%2+16], m7
+%else
+    SWAP          0, 8
+    SWAP          4, 9
+    IDCT8_1D     m8, m9
+    SWAP          6, 8
+    SWAP          7, 9
+%endif
+
+    pxor         m7, m7
+    lea          %4, [%3*3]
+    STORE_DIFF   m0, m6, m7, [%1     ]
+    STORE_DIFF   m1, m6, m7, [%1+%3  ]
+    STORE_DIFF   m2, m6, m7, [%1+%3*2]
+    STORE_DIFF   m3, m6, m7, [%1+%4  ]
+%ifndef ARCH_X86_64
+    mova         m0, [%2   ]
+    mova         m1, [%2+16]
+%else
+    SWAP          0, 8
+    SWAP          1, 9
+%endif
+    lea          %1, [%1+%3*4]
+    STORE_DIFF   m4, m6, m7, [%1     ]
+    STORE_DIFF   m5, m6, m7, [%1+%3  ]
+    STORE_DIFF   m0, m6, m7, [%1+%3*2]
+    STORE_DIFF   m1, m6, m7, [%1+%4  ]
+%endmacro
+
+INIT_XMM
+; ff_h264_idct8_add_sse2(uint8_t *dst, int16_t *block, int stride)
+cglobal h264_idct8_add_sse2, 3, 4, 10
+    IDCT8_ADD_SSE r0, r1, r2, r3
+    RET
+
+%macro DC_ADD_MMX2_INIT 2-3
+%if %0 == 2
+    movsx        %1, word [%1]
+    add          %1, 32
+    sar          %1, 6
+    movd         m0, %1d
+    lea          %1, [%2*3]
+%else
+    add          %3, 32
+    sar          %3, 6
+    movd         m0, %3d
+    lea          %3, [%2*3]
+%endif
+    pshufw       m0, m0, 0
+    pxor         m1, m1
+    psubw        m1, m0
+    packuswb     m0, m0
+    packuswb     m1, m1
+%endmacro
+
+%macro DC_ADD_MMX2_OP 3-4
+    %1           m2, [%2     ]
+    %1           m3, [%2+%3  ]
+    %1           m4, [%2+%3*2]
+    %1           m5, [%2+%4  ]
+    paddusb      m2, m0
+    paddusb      m3, m0
+    paddusb      m4, m0
+    paddusb      m5, m0
+    psubusb      m2, m1
+    psubusb      m3, m1
+    psubusb      m4, m1
+    psubusb      m5, m1
+    %1    [%2     ], m2
+    %1    [%2+%3  ], m3
+    %1    [%2+%3*2], m4
+    %1    [%2+%4  ], m5
+%endmacro
+
+INIT_MMX
+; ff_h264_idct_dc_add_mmx2(uint8_t *dst, int16_t *block, int stride)
+cglobal h264_idct_dc_add_mmx2, 3, 3, 0
+    DC_ADD_MMX2_INIT r1, r2
+    DC_ADD_MMX2_OP movh, r0, r2, r1
+    RET
+
+; ff_h264_idct8_dc_add_mmx2(uint8_t *dst, int16_t *block, int stride)
+cglobal h264_idct8_dc_add_mmx2, 3, 3, 0
+    DC_ADD_MMX2_INIT r1, r2
+    DC_ADD_MMX2_OP mova, r0, r2, r1
+    lea          r0, [r0+r2*4]
+    DC_ADD_MMX2_OP mova, r0, r2, r1
+    RET
+
+; ff_h264_idct_add16_mmx(uint8_t *dst, const int *block_offset,
+;             DCTELEM *block, int stride, const uint8_t nnzc[6*8])
+cglobal h264_idct_add16_mmx, 5, 7, 0
+    xor          r5, r5
+%ifdef PIC
+    lea         r11, [scan8_mem]
+%endif
+.nextblock
+    movzx        r6, byte [scan8+r5]
+    movzx        r6, byte [r4+r6]
+    test         r6, r6
+    jz .skipblock
+    mov         r6d, dword [r1+r5*4]
+    lea          r6, [r0+r6]
+    IDCT4_ADD    r6, r2, r3
+.skipblock
+    inc          r5
+    add          r2, 32
+    cmp          r5, 16
+    jl .nextblock
+    REP_RET
+
+; ff_h264_idct8_add4_mmx(uint8_t *dst, const int *block_offset,
+;                        DCTELEM *block, int stride, const uint8_t nnzc[6*8])
+cglobal h264_idct8_add4_mmx, 5, 7, 0
+    %assign pad 128+4-(stack_offset&7)
+    SUB         rsp, pad
+
+    xor          r5, r5
+%ifdef PIC
+    lea         r11, [scan8_mem]
+%endif
+.nextblock
+    movzx        r6, byte [scan8+r5]
+    movzx        r6, byte [r4+r6]
+    test         r6, r6
+    jz .skipblock
+    mov         r6d, dword [r1+r5*4]
+    lea          r6, [r0+r6]
+    add   word [r2], 32
+    IDCT8_ADD_MMX_START r2  , rsp
+    IDCT8_ADD_MMX_START r2+8, rsp+64
+    IDCT8_ADD_MMX_END   r6  , rsp,   r3
+    mov         r6d, dword [r1+r5*4]
+    lea          r6, [r0+r6+4]
+    IDCT8_ADD_MMX_END   r6  , rsp+8, r3
+.skipblock
+    add          r5, 4
+    add          r2, 128
+    cmp          r5, 16
+    jl .nextblock
+    ADD         rsp, pad
+    RET
+
+; ff_h264_idct_add16_mmx2(uint8_t *dst, const int *block_offset,
+;                         DCTELEM *block, int stride, const uint8_t nnzc[6*8])
+cglobal h264_idct_add16_mmx2, 5, 7, 0
+    xor          r5, r5
+%ifdef PIC
+    lea         r11, [scan8_mem]
+%endif
+.nextblock
+    movzx        r6, byte [scan8+r5]
+    movzx        r6, byte [r4+r6]
+    test         r6, r6
+    jz .skipblock
+    cmp          r6, 1
+    jnz .no_dc
+    movsx        r6, word [r2]
+    test         r6, r6
+    jz .no_dc
+    DC_ADD_MMX2_INIT r2, r3, r6
+%ifdef ARCH_X86_64
+%define dst_reg  r10
+%define dst_regd r10d
+%else
+%define dst_reg  r1
+%define dst_regd r1d
+%endif
+    mov    dst_regd, dword [r1+r5*4]
+    lea     dst_reg, [r0+dst_reg]
+    DC_ADD_MMX2_OP movh, dst_reg, r3, r6
+%ifndef ARCH_X86_64
+    mov          r1, r1m
+%endif
+    inc          r5
+    add          r2, 32
+    cmp          r5, 16
+    jl .nextblock
+    REP_RET
+.no_dc
+    mov         r6d, dword [r1+r5*4]
+    lea          r6, [r0+r6]
+    IDCT4_ADD    r6, r2, r3
+.skipblock
+    inc          r5
+    add          r2, 32
+    cmp          r5, 16
+    jl .nextblock
+    REP_RET
+
+; ff_h264_idct_add16intra_mmx(uint8_t *dst, const int *block_offset,
+;                             DCTELEM *block, int stride, const uint8_t nnzc[6*8])
+cglobal h264_idct_add16intra_mmx, 5, 7, 0
+    xor          r5, r5
+%ifdef PIC
+    lea         r11, [scan8_mem]
+%endif
+.nextblock
+    movzx        r6, byte [scan8+r5]
+    movzx        r6, byte [r4+r6]
+    or          r6w, word [r2]
+    test         r6, r6
+    jz .skipblock
+    mov         r6d, dword [r1+r5*4]
+    lea          r6, [r0+r6]
+    IDCT4_ADD    r6, r2, r3
+.skipblock
+    inc          r5
+    add          r2, 32
+    cmp          r5, 16
+    jl .nextblock
+    REP_RET
+
+; ff_h264_idct_add16intra_mmx2(uint8_t *dst, const int *block_offset,
+;                              DCTELEM *block, int stride, const uint8_t nnzc[6*8])
+cglobal h264_idct_add16intra_mmx2, 5, 7, 0
+    xor          r5, r5
+%ifdef PIC
+    lea         r11, [scan8_mem]
+%endif
+.nextblock
+    movzx        r6, byte [scan8+r5]
+    movzx        r6, byte [r4+r6]
+    test         r6, r6
+    jz .try_dc
+    mov         r6d, dword [r1+r5*4]
+    lea          r6, [r0+r6]
+    IDCT4_ADD    r6, r2, r3
+    inc          r5
+    add          r2, 32
+    cmp          r5, 16
+    jl .nextblock
+    REP_RET
+.try_dc
+    movsx        r6, word [r2]
+    test         r6, r6
+    jz .skipblock
+    DC_ADD_MMX2_INIT r2, r3, r6
+%ifdef ARCH_X86_64
+%define dst_reg  r10
+%define dst_regd r10d
+%else
+%define dst_reg  r1
+%define dst_regd r1d
+%endif
+    mov    dst_regd, dword [r1+r5*4]
+    lea     dst_reg, [r0+dst_reg]
+    DC_ADD_MMX2_OP movh, dst_reg, r3, r6
+%ifndef ARCH_X86_64
+    mov          r1, r1m
+%endif
+.skipblock
+    inc          r5
+    add          r2, 32
+    cmp          r5, 16
+    jl .nextblock
+    REP_RET
+
+; ff_h264_idct8_add4_mmx2(uint8_t *dst, const int *block_offset,
+;                         DCTELEM *block, int stride, const uint8_t nnzc[6*8])
+cglobal h264_idct8_add4_mmx2, 5, 7, 0
+    %assign pad 128+4-(stack_offset&7)
+    SUB         rsp, pad
+
+    xor          r5, r5
+%ifdef PIC
+    lea         r11, [scan8_mem]
+%endif
+.nextblock
+    movzx        r6, byte [scan8+r5]
+    movzx        r6, byte [r4+r6]
+    test         r6, r6
+    jz .skipblock
+    cmp          r6, 1
+    jnz .no_dc
+    movsx        r6, word [r2]
+    test         r6, r6
+    jz .no_dc
+    DC_ADD_MMX2_INIT r2, r3, r6
+%ifdef ARCH_X86_64
+%define dst_reg  r10
+%define dst_regd r10d
+%else
+%define dst_reg  r1
+%define dst_regd r1d
+%endif
+    mov    dst_regd, dword [r1+r5*4]
+    lea     dst_reg, [r0+dst_reg]
+    DC_ADD_MMX2_OP mova, dst_reg, r3, r6
+    lea     dst_reg, [dst_reg+r3*4]
+    DC_ADD_MMX2_OP mova, dst_reg, r3, r6
+%ifndef ARCH_X86_64
+    mov          r1, r1m
+%endif
+    add          r5, 4
+    add          r2, 128
+    cmp          r5, 16
+    jl .nextblock
+
+    ADD         rsp, pad
+    RET
+.no_dc
+    mov         r6d, dword [r1+r5*4]
+    lea          r6, [r0+r6]
+    add   word [r2], 32
+    IDCT8_ADD_MMX_START r2  , rsp
+    IDCT8_ADD_MMX_START r2+8, rsp+64
+    IDCT8_ADD_MMX_END   r6  , rsp,   r3
+    mov         r6d, dword [r1+r5*4]
+    lea          r6, [r0+r6+4]
+    IDCT8_ADD_MMX_END   r6  , rsp+8, r3
+.skipblock
+    add          r5, 4
+    add          r2, 128
+    cmp          r5, 16
+    jl .nextblock
+
+    ADD         rsp, pad
+    RET
+
+INIT_XMM
+; ff_h264_idct8_add4_sse2(uint8_t *dst, const int *block_offset,
+;                         DCTELEM *block, int stride, const uint8_t nnzc[6*8])
+cglobal h264_idct8_add4_sse2, 5, 7, 10
+    xor          r5, r5
+%ifdef PIC
+    lea         r11, [scan8_mem]
+%endif
+.nextblock
+    movzx        r6, byte [scan8+r5]
+    movzx        r6, byte [r4+r6]
+    test         r6, r6
+    jz .skipblock
+    cmp          r6, 1
+    jnz .no_dc
+    movsx        r6, word [r2]
+    test         r6, r6
+    jz .no_dc
+INIT_MMX
+    DC_ADD_MMX2_INIT r2, r3, r6
+%ifdef ARCH_X86_64
+%define dst_reg  r10
+%define dst_regd r10d
+%else
+%define dst_reg  r1
+%define dst_regd r1d
+%endif
+    mov    dst_regd, dword [r1+r5*4]
+    lea     dst_reg, [r0+dst_reg]
+    DC_ADD_MMX2_OP mova, dst_reg, r3, r6
+    lea     dst_reg, [dst_reg+r3*4]
+    DC_ADD_MMX2_OP mova, dst_reg, r3, r6
+%ifndef ARCH_X86_64
+    mov          r1, r1m
+%endif
+    add          r5, 4
+    add          r2, 128
+    cmp          r5, 16
+    jl .nextblock
+    REP_RET
+.no_dc
+INIT_XMM
+    mov    dst_regd, dword [r1+r5*4]
+    lea     dst_reg, [r0+dst_reg]
+    IDCT8_ADD_SSE dst_reg, r2, r3, r6
+%ifndef ARCH_X86_64
+    mov          r1, r1m
+%endif
+.skipblock
+    add          r5, 4
+    add          r2, 128
+    cmp          r5, 16
+    jl .nextblock
+    REP_RET
+
+INIT_MMX
+h264_idct_add8_mmx_plane:
+.nextblock
+    movzx        r6, byte [scan8+r5]
+    movzx        r6, byte [r4+r6]
+    or          r6w, word [r2]
+    test         r6, r6
+    jz .skipblock
+%ifdef ARCH_X86_64
+    mov         r0d, dword [r1+r5*4]
+    add          r0, [r10]
+%else
+    mov          r0, r1m ; XXX r1m here is actually r0m of the calling func
+    mov          r0, [r0]
+    add          r0, dword [r1+r5*4]
+%endif
+    IDCT4_ADD    r0, r2, r3
+.skipblock
+    inc          r5
+    add          r2, 32
+    test         r5, 3
+    jnz .nextblock
+    rep ret
+
+; ff_h264_idct_add8_mmx(uint8_t **dest, const int *block_offset,
+;                       DCTELEM *block, int stride, const uint8_t nnzc[6*8])
+cglobal h264_idct_add8_mmx, 5, 7, 0
+    mov          r5, 16
+    add          r2, 512
+%ifdef PIC
+    lea         r11, [scan8_mem]
+%endif
+%ifdef ARCH_X86_64
+    mov         r10, r0
+%endif
+    call         h264_idct_add8_mmx_plane
+%ifdef ARCH_X86_64
+    add         r10, gprsize
+%else
+    add        r0mp, gprsize
+%endif
+    call         h264_idct_add8_mmx_plane
+    RET
+
+h264_idct_add8_mmx2_plane
+.nextblock
+    movzx        r6, byte [scan8+r5]
+    movzx        r6, byte [r4+r6]
+    test         r6, r6
+    jz .try_dc
+%ifdef ARCH_X86_64
+    mov         r0d, dword [r1+r5*4]
+    add          r0, [r10]
+%else
+    mov          r0, r1m ; XXX r1m here is actually r0m of the calling func
+    mov          r0, [r0]
+    add          r0, dword [r1+r5*4]
+%endif
+    IDCT4_ADD    r0, r2, r3
+    inc          r5
+    add          r2, 32
+    test         r5, 3
+    jnz .nextblock
+    rep ret
+.try_dc
+    movsx        r6, word [r2]
+    test         r6, r6
+    jz .skipblock
+    DC_ADD_MMX2_INIT r2, r3, r6
+%ifdef ARCH_X86_64
+    mov         r0d, dword [r1+r5*4]
+    add          r0, [r10]
+%else
+    mov          r0, r1m ; XXX r1m here is actually r0m of the calling func
+    mov          r0, [r0]
+    add          r0, dword [r1+r5*4]
+%endif
+    DC_ADD_MMX2_OP movh, r0, r3, r6
+.skipblock
+    inc          r5
+    add          r2, 32
+    test         r5, 3
+    jnz .nextblock
+    rep ret
+
+; ff_h264_idct_add8_mmx2(uint8_t **dest, const int *block_offset,
+;                        DCTELEM *block, int stride, const uint8_t nnzc[6*8])
+cglobal h264_idct_add8_mmx2, 5, 7, 0
+    mov          r5, 16
+    add          r2, 512
+%ifdef ARCH_X86_64
+    mov         r10, r0
+%endif
+%ifdef PIC
+    lea         r11, [scan8_mem]
+%endif
+    call h264_idct_add8_mmx2_plane
+%ifdef ARCH_X86_64
+    add         r10, gprsize
+%else
+    add        r0mp, gprsize
+%endif
+    call h264_idct_add8_mmx2_plane
+    RET
+
+INIT_MMX
+; r0 = uint8_t *dst, r2 = int16_t *block, r3 = int stride, r6=clobbered
+h264_idct_dc_add8_mmx2:
+    movd         m0, [r2   ]          ;  0 0 X D
+    punpcklwd    m0, [r2+32]          ;  x X d D
+    paddsw       m0, [pw_32]
+    psraw        m0, 6
+    punpcklwd    m0, m0               ;  d d D D
+    pxor         m1, m1               ;  0 0 0 0
+    psubw        m1, m0               ; -d-d-D-D
+    packuswb     m0, m1               ; -d-d-D-D d d D D
+    pshufw       m1, m0, 0xFA         ; -d-d-d-d-D-D-D-D
+    punpcklwd    m0, m0               ;  d d d d D D D D
+    lea          r6, [r3*3]
+    DC_ADD_MMX2_OP movq, r0, r3, r6
+    ret
+
+ALIGN 16
+INIT_XMM
+; r0 = uint8_t *dst (clobbered), r2 = int16_t *block, r3 = int stride
+x264_add8x4_idct_sse2:
+    movq   m0, [r2+ 0]
+    movq   m1, [r2+ 8]
+    movq   m2, [r2+16]
+    movq   m3, [r2+24]
+    movhps m0, [r2+32]
+    movhps m1, [r2+40]
+    movhps m2, [r2+48]
+    movhps m3, [r2+56]
+    IDCT4_1D 0,1,2,3,4,5
+    TRANSPOSE2x4x4W 0,1,2,3,4
+    paddw m0, [pw_32]
+    IDCT4_1D 0,1,2,3,4,5
+    pxor  m7, m7
+    STORE_DIFFx2 m0, m1, m4, m5, m7, 6, r0, r3
+    lea   r0, [r0+r3*2]
+    STORE_DIFFx2 m2, m3, m4, m5, m7, 6, r0, r3
+    ret
+
+%macro add16_sse2_cycle 2
+    movzx       r0, word [r4+%2]
+    test        r0, r0
+    jz .cycle%1end
+    mov        r0d, dword [r1+%1*8]
+%ifdef ARCH_X86_64
+    add         r0, r10
+%else
+    add         r0, r0m
+%endif
+    call        x264_add8x4_idct_sse2
+.cycle%1end
+%if %1 < 7
+    add         r2, 64
+%endif
+%endmacro
+
+; ff_h264_idct_add16_sse2(uint8_t *dst, const int *block_offset,
+;                         DCTELEM *block, int stride, const uint8_t nnzc[6*8])
+cglobal h264_idct_add16_sse2, 5, 5, 8
+%ifdef ARCH_X86_64
+    mov        r10, r0
+%endif
+    ; unrolling of the loop leads to an average performance gain of
+    ; 20-25%
+    add16_sse2_cycle 0, 0xc
+    add16_sse2_cycle 1, 0x14
+    add16_sse2_cycle 2, 0xe
+    add16_sse2_cycle 3, 0x16
+    add16_sse2_cycle 4, 0x1c
+    add16_sse2_cycle 5, 0x24
+    add16_sse2_cycle 6, 0x1e
+    add16_sse2_cycle 7, 0x26
+    RET
+
+%macro add16intra_sse2_cycle 2
+    movzx       r0, word [r4+%2]
+    test        r0, r0
+    jz .try%1dc
+    mov        r0d, dword [r1+%1*8]
+%ifdef ARCH_X86_64
+    add         r0, r10
+%else
+    add         r0, r0m
+%endif
+    call        x264_add8x4_idct_sse2
+    jmp .cycle%1end
+.try%1dc
+    movsx       r0, word [r2   ]
+    or         r0w, word [r2+32]
+    jz .cycle%1end
+    mov        r0d, dword [r1+%1*8]
+%ifdef ARCH_X86_64
+    add         r0, r10
+%else
+    add         r0, r0m
+%endif
+    call        h264_idct_dc_add8_mmx2
+.cycle%1end
+%if %1 < 7
+    add         r2, 64
+%endif
+%endmacro
+
+; ff_h264_idct_add16intra_sse2(uint8_t *dst, const int *block_offset,
+;                              DCTELEM *block, int stride, const uint8_t nnzc[6*8])
+cglobal h264_idct_add16intra_sse2, 5, 7, 8
+%ifdef ARCH_X86_64
+    mov        r10, r0
+%endif
+    add16intra_sse2_cycle 0, 0xc
+    add16intra_sse2_cycle 1, 0x14
+    add16intra_sse2_cycle 2, 0xe
+    add16intra_sse2_cycle 3, 0x16
+    add16intra_sse2_cycle 4, 0x1c
+    add16intra_sse2_cycle 5, 0x24
+    add16intra_sse2_cycle 6, 0x1e
+    add16intra_sse2_cycle 7, 0x26
+    RET
+
+%macro add8_sse2_cycle 2
+    movzx       r0, word [r4+%2]
+    test        r0, r0
+    jz .try%1dc
+%ifdef ARCH_X86_64
+    mov        r0d, dword [r1+%1*8+64]
+    add         r0, [r10]
+%else
+    mov         r0, r0m
+    mov         r0, [r0]
+    add         r0, dword [r1+%1*8+64]
+%endif
+    call        x264_add8x4_idct_sse2
+    jmp .cycle%1end
+.try%1dc
+    movsx       r0, word [r2   ]
+    or         r0w, word [r2+32]
+    jz .cycle%1end
+%ifdef ARCH_X86_64
+    mov        r0d, dword [r1+%1*8+64]
+    add         r0, [r10]
+%else
+    mov         r0, r0m
+    mov         r0, [r0]
+    add         r0, dword [r1+%1*8+64]
+%endif
+    call        h264_idct_dc_add8_mmx2
+.cycle%1end
+%if %1 < 3
+    add         r2, 64
+%endif
+%endmacro
+
+; ff_h264_idct_add8_sse2(uint8_t **dest, const int *block_offset,
+;                        DCTELEM *block, int stride, const uint8_t nnzc[6*8])
+cglobal h264_idct_add8_sse2, 5, 7, 8
+    add          r2, 512
+%ifdef ARCH_X86_64
+    mov         r10, r0
+%endif
+    add8_sse2_cycle 0, 0x09
+    add8_sse2_cycle 1, 0x11
+%ifdef ARCH_X86_64
+    add         r10, gprsize
+%else
+    add        r0mp, gprsize
+%endif
+    add8_sse2_cycle 2, 0x21
+    add8_sse2_cycle 3, 0x29
+    RET
+
+;void ff_h264_luma_dc_dequant_idct_mmx(DCTELEM *output, DCTELEM *input, int qmul)
+
+%macro WALSH4_1D 5
+    SUMSUB_BADC m%4, m%3, m%2, m%1, m%5
+    SUMSUB_BADC m%4, m%2, m%3, m%1, m%5
+    SWAP %1, %4, %3
+%endmacro
+
+%macro DEQUANT_MMX 3
+    mova        m7, [pw_1]
+    mova        m4, %1
+    punpcklwd   %1, m7
+    punpckhwd   m4, m7
+    mova        m5, %2
+    punpcklwd   %2, m7
+    punpckhwd   m5, m7
+    movd        m7, t3d
+    punpckldq   m7, m7
+    pmaddwd     %1, m7
+    pmaddwd     %2, m7
+    pmaddwd     m4, m7
+    pmaddwd     m5, m7
+    psrad       %1, %3
+    psrad       %2, %3
+    psrad       m4, %3
+    psrad       m5, %3
+    packssdw    %1, m4
+    packssdw    %2, m5
+%endmacro
+
+%macro STORE_WORDS_MMX 5
+    movd  t0d, %1
+    psrlq  %1, 32
+    movd  t1d, %1
+    mov [t2+%2*32], t0w
+    mov [t2+%4*32], t1w
+    shr   t0d, 16
+    shr   t1d, 16
+    mov [t2+%3*32], t0w
+    mov [t2+%5*32], t1w
+%endmacro
+
+%macro DEQUANT_STORE_MMX 1
+    DEQUANT_MMX m0, m1, %1
+    STORE_WORDS_MMX m0,  0,  1,  4,  5
+    STORE_WORDS_MMX m1,  2,  3,  6,  7
+
+    DEQUANT_MMX m2, m3, %1
+    STORE_WORDS_MMX m2,  8,  9, 12, 13
+    STORE_WORDS_MMX m3, 10, 11, 14, 15
+%endmacro
+
+%macro STORE_WORDS_SSE 9
+    movd  t0d, %1
+    psrldq  %1, 4
+    movd  t1d, %1
+    psrldq  %1, 4
+    mov [t2+%2*32], t0w
+    mov [t2+%4*32], t1w
+    shr   t0d, 16
+    shr   t1d, 16
+    mov [t2+%3*32], t0w
+    mov [t2+%5*32], t1w
+    movd  t0d, %1
+    psrldq  %1, 4
+    movd  t1d, %1
+    mov [t2+%6*32], t0w
+    mov [t2+%8*32], t1w
+    shr   t0d, 16
+    shr   t1d, 16
+    mov [t2+%7*32], t0w
+    mov [t2+%9*32], t1w
+%endmacro
+
+%macro DEQUANT_STORE_SSE2 1
+    movd      xmm4, t3d
+    movq      xmm5, [pw_1]
+    pshufd    xmm4, xmm4, 0
+    movq2dq   xmm0, m0
+    movq2dq   xmm1, m1
+    movq2dq   xmm2, m2
+    movq2dq   xmm3, m3
+    punpcklwd xmm0, xmm5
+    punpcklwd xmm1, xmm5
+    punpcklwd xmm2, xmm5
+    punpcklwd xmm3, xmm5
+    pmaddwd   xmm0, xmm4
+    pmaddwd   xmm1, xmm4
+    pmaddwd   xmm2, xmm4
+    pmaddwd   xmm3, xmm4
+    psrad     xmm0, %1
+    psrad     xmm1, %1
+    psrad     xmm2, %1
+    psrad     xmm3, %1
+    packssdw  xmm0, xmm1
+    packssdw  xmm2, xmm3
+    STORE_WORDS_SSE xmm0,  0,  1,  4,  5,  2,  3,  6,  7
+    STORE_WORDS_SSE xmm2,  8,  9, 12, 13, 10, 11, 14, 15
+%endmacro
+
+%macro IDCT_DC_DEQUANT 2
+cglobal h264_luma_dc_dequant_idct_%1, 3,4,%2
+    movq        m3, [r1+24]
+    movq        m2, [r1+16]
+    movq        m1, [r1+ 8]
+    movq        m0, [r1+ 0]
+    WALSH4_1D    0,1,2,3,4
+    TRANSPOSE4x4W 0,1,2,3,4
+    WALSH4_1D    0,1,2,3,4
+
+; shift, tmp, output, qmul
+%ifdef WIN64
+    DECLARE_REG_TMP 0,3,1,2
+    ; we can't avoid this, because r0 is the shift register (ecx) on win64
+    xchg        r0, t2
+%elifdef ARCH_X86_64
+    DECLARE_REG_TMP 3,1,0,2
+%else
+    DECLARE_REG_TMP 1,3,0,2
+%endif
+
+    cmp        t3d, 32767
+    jg .big_qmul
+    add        t3d, 128 << 16
+%ifidn %1,mmx
+    DEQUANT_STORE_MMX 8
+%else
+    DEQUANT_STORE_SSE2 8
+%endif
+    RET
+.big_qmul:
+    bsr        t0d, t3d
+    add        t3d, 128 << 16
+    mov        t1d, 7
+    cmp        t0d, t1d
+    cmovg      t0d, t1d
+    inc        t1d
+    shr        t3d, t0b
+    sub        t1d, t0d
+%ifidn %1,mmx
+    movd        m6, t1d
+    DEQUANT_STORE_MMX m6
+%else
+    movd      xmm6, t1d
+    DEQUANT_STORE_SSE2 xmm6
+%endif
+    RET
+%endmacro
+
+INIT_MMX
+IDCT_DC_DEQUANT mmx, 0
+IDCT_DC_DEQUANT sse2, 7
diff --git a/libavcodec/x86/h264_idct_sse2.asm b/libavcodec/x86/h264_idct_sse2.asm
deleted file mode 100644
index f8ee2b6..0000000
--- a/libavcodec/x86/h264_idct_sse2.asm
+++ /dev/null
@@ -1,54 +0,0 @@
-;*****************************************************************************
-;* SSE2-optimized H.264 iDCT
-;*****************************************************************************
-;* Copyright (C) 2003-2008 x264 project
-;*
-;* Authors: Laurent Aimar <fenrir at via.ecp.fr>
-;*          Loren Merritt <lorenm at u.washington.edu>
-;*          Holger Lubitz <hal at duncan.ol.sub.de>
-;*          Min Chen <chenm001.163.com>
-;*
-;* This program is free software; you can redistribute it and/or modify
-;* it under the terms of the GNU General Public License as published by
-;* the Free Software Foundation; either version 2 of the License, or
-;* (at your option) any later version.
-;*
-;* This program is distributed in the hope that it will be useful,
-;* but WITHOUT ANY WARRANTY; without even the implied warranty of
-;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-;* GNU General Public License for more details.
-;*
-;* You should have received a copy of the GNU General Public License
-;* along with this program; if not, write to the Free Software
-;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111, USA.
-;*****************************************************************************
-
-%include "x86inc.asm"
-%include "x86util.asm"
-
-SECTION_RODATA
-pw_32: times 8 dw 32
-
-SECTION .text
-
-INIT_XMM
-cglobal x264_add8x4_idct_sse2, 3,3,8
-    movq   m0, [r1+ 0]
-    movq   m1, [r1+ 8]
-    movq   m2, [r1+16]
-    movq   m3, [r1+24]
-    movhps m0, [r1+32]
-    movhps m1, [r1+40]
-    movhps m2, [r1+48]
-    movhps m3, [r1+56]
-    IDCT4_1D 0,1,2,3,4,5
-    TRANSPOSE2x4x4W 0,1,2,3,4
-    paddw m0, [pw_32 GLOBAL]
-    IDCT4_1D 0,1,2,3,4,5
-    pxor  m7, m7
-    STORE_DIFF  m0, m4, m7, [r0]
-    STORE_DIFF  m1, m4, m7, [r0+r2]
-    lea   r0, [r0+r2*2]
-    STORE_DIFF  m2, m4, m7, [r0]
-    STORE_DIFF  m3, m4, m7, [r0+r2]
-    RET
diff --git a/libavcodec/x86/h264_intrapred.asm b/libavcodec/x86/h264_intrapred.asm
new file mode 100644
index 0000000..1b18932
--- /dev/null
+++ b/libavcodec/x86/h264_intrapred.asm
@@ -0,0 +1,2789 @@
+;******************************************************************************
+;* H.264 intra prediction asm optimizations
+;* Copyright (c) 2010 Jason Garrett-Glaser
+;* Copyright (c) 2010 Holger Lubitz
+;* Copyright (c) 2010 Loren Merritt
+;* Copyright (c) 2010 Ronald S. Bultje
+;*
+;* This file is part of Libav.
+;*
+;* Libav is free software; you can redistribute it and/or
+;* modify it under the terms of the GNU Lesser General Public
+;* License as published by the Free Software Foundation; either
+;* version 2.1 of the License, or (at your option) any later version.
+;*
+;* Libav is distributed in the hope that it will be useful,
+;* but WITHOUT ANY WARRANTY; without even the implied warranty of
+;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+;* Lesser General Public License for more details.
+;*
+;* You should have received a copy of the GNU Lesser General Public
+;* License along with Libav; if not, write to the Free Software
+;* 51, Inc., Foundation Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+;******************************************************************************
+
+%include "x86inc.asm"
+%include "x86util.asm"
+
+SECTION_RODATA
+
+tm_shuf: times 8 db 0x03, 0x80
+pw_ff00: times 8 dw 0xff00
+plane_shuf:  db -8, -7, -6, -5, -4, -3, -2, -1
+             db  1,  2,  3,  4,  5,  6,  7,  8
+plane8_shuf: db -4, -3, -2, -1,  0,  0,  0,  0
+             db  1,  2,  3,  4,  0,  0,  0,  0
+pw_0to7:     dw  0,  1,  2,  3,  4,  5,  6,  7
+pw_1to8:     dw  1,  2,  3,  4,  5,  6,  7,  8
+pw_m8tom1:   dw -8, -7, -6, -5, -4, -3, -2, -1
+pw_m4to4:    dw -4, -3, -2, -1,  1,  2,  3,  4
+
+SECTION .text
+
+cextern pb_1
+cextern pb_3
+cextern pw_4
+cextern pw_5
+cextern pw_8
+cextern pw_16
+cextern pw_17
+cextern pw_32
+
+;-----------------------------------------------------------------------------
+; void pred16x16_vertical(uint8_t *src, int stride)
+;-----------------------------------------------------------------------------
+
+cglobal pred16x16_vertical_mmx, 2,3
+    sub   r0, r1
+    mov   r2, 8
+    movq mm0, [r0+0]
+    movq mm1, [r0+8]
+.loop:
+    movq [r0+r1*1+0], mm0
+    movq [r0+r1*1+8], mm1
+    movq [r0+r1*2+0], mm0
+    movq [r0+r1*2+8], mm1
+    lea   r0, [r0+r1*2]
+    dec   r2
+    jg .loop
+    REP_RET
+
+cglobal pred16x16_vertical_sse, 2,3
+    sub   r0, r1
+    mov   r2, 4
+    movaps xmm0, [r0]
+.loop:
+    movaps [r0+r1*1], xmm0
+    movaps [r0+r1*2], xmm0
+    lea   r0, [r0+r1*2]
+    movaps [r0+r1*1], xmm0
+    movaps [r0+r1*2], xmm0
+    lea   r0, [r0+r1*2]
+    dec   r2
+    jg .loop
+    REP_RET
+
+;-----------------------------------------------------------------------------
+; void pred16x16_horizontal(uint8_t *src, int stride)
+;-----------------------------------------------------------------------------
+
+%macro PRED16x16_H 1
+cglobal pred16x16_horizontal_%1, 2,3
+    mov       r2, 8
+%ifidn %1, ssse3
+    mova      m2, [pb_3]
+%endif
+.loop:
+    movd      m0, [r0+r1*0-4]
+    movd      m1, [r0+r1*1-4]
+
+%ifidn %1, ssse3
+    pshufb    m0, m2
+    pshufb    m1, m2
+%else
+    punpcklbw m0, m0
+    punpcklbw m1, m1
+%ifidn %1, mmxext
+    pshufw    m0, m0, 0xff
+    pshufw    m1, m1, 0xff
+%else
+    punpckhwd m0, m0
+    punpckhwd m1, m1
+    punpckhdq m0, m0
+    punpckhdq m1, m1
+%endif
+    mova [r0+r1*0+8], m0
+    mova [r0+r1*1+8], m1
+%endif
+
+    mova [r0+r1*0], m0
+    mova [r0+r1*1], m1
+    lea       r0, [r0+r1*2]
+    dec       r2
+    jg .loop
+    REP_RET
+%endmacro
+
+INIT_MMX
+PRED16x16_H mmx
+PRED16x16_H mmxext
+INIT_XMM
+PRED16x16_H ssse3
+
+;-----------------------------------------------------------------------------
+; void pred16x16_dc(uint8_t *src, int stride)
+;-----------------------------------------------------------------------------
+
+%macro PRED16x16_DC 1
+cglobal pred16x16_dc_%1, 2,7
+    mov       r4, r0
+    sub       r0, r1
+    pxor      mm0, mm0
+    pxor      mm1, mm1
+    psadbw    mm0, [r0+0]
+    psadbw    mm1, [r0+8]
+    dec        r0
+    movzx     r5d, byte [r0+r1*1]
+    paddw     mm0, mm1
+    movd      r6d, mm0
+    lea        r0, [r0+r1*2]
+%rep 7
+    movzx     r2d, byte [r0+r1*0]
+    movzx     r3d, byte [r0+r1*1]
+    add       r5d, r2d
+    add       r6d, r3d
+    lea        r0, [r0+r1*2]
+%endrep
+    movzx     r2d, byte [r0+r1*0]
+    add       r5d, r6d
+    lea       r2d, [r2+r5+16]
+    shr       r2d, 5
+%ifidn %1, mmxext
+    movd       m0, r2d
+    punpcklbw  m0, m0
+    pshufw     m0, m0, 0
+%elifidn %1, sse2
+    movd       m0, r2d
+    punpcklbw  m0, m0
+    pshuflw    m0, m0, 0
+    punpcklqdq m0, m0
+%elifidn %1, ssse3
+    pxor       m1, m1
+    movd       m0, r2d
+    pshufb     m0, m1
+%endif
+
+%if mmsize==8
+    mov       r3d, 8
+.loop:
+    mova [r4+r1*0+0], m0
+    mova [r4+r1*0+8], m0
+    mova [r4+r1*1+0], m0
+    mova [r4+r1*1+8], m0
+%else
+    mov       r3d, 4
+.loop:
+    mova [r4+r1*0], m0
+    mova [r4+r1*1], m0
+    lea   r4, [r4+r1*2]
+    mova [r4+r1*0], m0
+    mova [r4+r1*1], m0
+%endif
+    lea   r4, [r4+r1*2]
+    dec   r3d
+    jg .loop
+    REP_RET
+%endmacro
+
+INIT_MMX
+PRED16x16_DC mmxext
+INIT_XMM
+PRED16x16_DC   sse2
+PRED16x16_DC  ssse3
+
+;-----------------------------------------------------------------------------
+; void pred16x16_tm_vp8(uint8_t *src, int stride)
+;-----------------------------------------------------------------------------
+
+%macro PRED16x16_TM_MMX 1
+cglobal pred16x16_tm_vp8_%1, 2,5
+    sub        r0, r1
+    pxor      mm7, mm7
+    movq      mm0, [r0+0]
+    movq      mm2, [r0+8]
+    movq      mm1, mm0
+    movq      mm3, mm2
+    punpcklbw mm0, mm7
+    punpckhbw mm1, mm7
+    punpcklbw mm2, mm7
+    punpckhbw mm3, mm7
+    movzx     r3d, byte [r0-1]
+    mov       r4d, 16
+.loop:
+    movzx     r2d, byte [r0+r1-1]
+    sub       r2d, r3d
+    movd      mm4, r2d
+%ifidn %1, mmx
+    punpcklwd mm4, mm4
+    punpckldq mm4, mm4
+%else
+    pshufw    mm4, mm4, 0
+%endif
+    movq      mm5, mm4
+    movq      mm6, mm4
+    movq      mm7, mm4
+    paddw     mm4, mm0
+    paddw     mm5, mm1
+    paddw     mm6, mm2
+    paddw     mm7, mm3
+    packuswb  mm4, mm5
+    packuswb  mm6, mm7
+    movq [r0+r1+0], mm4
+    movq [r0+r1+8], mm6
+    add        r0, r1
+    dec       r4d
+    jg .loop
+    REP_RET
+%endmacro
+
+PRED16x16_TM_MMX mmx
+PRED16x16_TM_MMX mmxext
+
+cglobal pred16x16_tm_vp8_sse2, 2,6,6
+    sub          r0, r1
+    pxor       xmm2, xmm2
+    movdqa     xmm0, [r0]
+    movdqa     xmm1, xmm0
+    punpcklbw  xmm0, xmm2
+    punpckhbw  xmm1, xmm2
+    movzx       r4d, byte [r0-1]
+    mov         r5d, 8
+.loop:
+    movzx       r2d, byte [r0+r1*1-1]
+    movzx       r3d, byte [r0+r1*2-1]
+    sub         r2d, r4d
+    sub         r3d, r4d
+    movd       xmm2, r2d
+    movd       xmm4, r3d
+    pshuflw    xmm2, xmm2, 0
+    pshuflw    xmm4, xmm4, 0
+    punpcklqdq xmm2, xmm2
+    punpcklqdq xmm4, xmm4
+    movdqa     xmm3, xmm2
+    movdqa     xmm5, xmm4
+    paddw      xmm2, xmm0
+    paddw      xmm3, xmm1
+    paddw      xmm4, xmm0
+    paddw      xmm5, xmm1
+    packuswb   xmm2, xmm3
+    packuswb   xmm4, xmm5
+    movdqa [r0+r1*1], xmm2
+    movdqa [r0+r1*2], xmm4
+    lea          r0, [r0+r1*2]
+    dec         r5d
+    jg .loop
+    REP_RET
+
+;-----------------------------------------------------------------------------
+; void pred16x16_plane(uint8_t *src, int stride)
+;-----------------------------------------------------------------------------
+
+%macro H264_PRED16x16_PLANE 3
+cglobal pred16x16_plane_%3_%1, 2, 7, %2
+    mov          r2, r1           ; +stride
+    neg          r1               ; -stride
+
+    movh         m0, [r0+r1  -1]
+%if mmsize == 8
+    pxor         m4, m4
+    movh         m1, [r0+r1  +3 ]
+    movh         m2, [r0+r1  +8 ]
+    movh         m3, [r0+r1  +12]
+    punpcklbw    m0, m4
+    punpcklbw    m1, m4
+    punpcklbw    m2, m4
+    punpcklbw    m3, m4
+    pmullw       m0, [pw_m8tom1  ]
+    pmullw       m1, [pw_m8tom1+8]
+    pmullw       m2, [pw_1to8    ]
+    pmullw       m3, [pw_1to8  +8]
+    paddw        m0, m2
+    paddw        m1, m3
+%else ; mmsize == 16
+%ifidn %1, sse2
+    pxor         m2, m2
+    movh         m1, [r0+r1  +8]
+    punpcklbw    m0, m2
+    punpcklbw    m1, m2
+    pmullw       m0, [pw_m8tom1]
+    pmullw       m1, [pw_1to8]
+    paddw        m0, m1
+%else ; ssse3
+    movhps       m0, [r0+r1  +8]
+    pmaddubsw    m0, [plane_shuf] ; H coefficients
+%endif
+    movhlps      m1, m0
+%endif
+    paddw        m0, m1
+%ifidn %1, mmx
+    mova         m1, m0
+    psrlq        m1, 32
+%elifidn %1, mmx2
+    pshufw       m1, m0, 0xE
+%else ; mmsize == 16
+    pshuflw      m1, m0, 0xE
+%endif
+    paddw        m0, m1
+%ifidn %1, mmx
+    mova         m1, m0
+    psrlq        m1, 16
+%elifidn %1, mmx2
+    pshufw       m1, m0, 0x1
+%else
+    pshuflw      m1, m0, 0x1
+%endif
+    paddw        m0, m1           ; sum of H coefficients
+
+    lea          r4, [r0+r2*8-1]
+    lea          r3, [r0+r2*4-1]
+    add          r4, r2
+
+%ifdef ARCH_X86_64
+%define e_reg r11
+%else
+%define e_reg r0
+%endif
+
+    movzx     e_reg, byte [r3+r2*2   ]
+    movzx        r5, byte [r4+r1     ]
+    sub          r5, e_reg
+
+    movzx     e_reg, byte [r3+r2     ]
+    movzx        r6, byte [r4        ]
+    sub          r6, e_reg
+    lea          r5, [r5+r6*2]
+
+    movzx     e_reg, byte [r3+r1     ]
+    movzx        r6, byte [r4+r2*2   ]
+    sub          r6, e_reg
+    lea          r5, [r5+r6*4]
+
+    movzx     e_reg, byte [r3        ]
+%ifdef ARCH_X86_64
+    movzx       r10, byte [r4+r2     ]
+    sub         r10, e_reg
+%else
+    movzx        r6, byte [r4+r2     ]
+    sub          r6, e_reg
+    lea          r5, [r5+r6*4]
+    sub          r5, r6
+%endif
+
+    lea       e_reg, [r3+r1*4]
+    lea          r3, [r4+r2*4]
+
+    movzx        r4, byte [e_reg+r2  ]
+    movzx        r6, byte [r3        ]
+    sub          r6, r4
+%ifdef ARCH_X86_64
+    lea          r6, [r10+r6*2]
+    lea          r5, [r5+r6*2]
+    add          r5, r6
+%else
+    lea          r5, [r5+r6*4]
+    lea          r5, [r5+r6*2]
+%endif
+
+    movzx        r4, byte [e_reg     ]
+%ifdef ARCH_X86_64
+    movzx       r10, byte [r3   +r2  ]
+    sub         r10, r4
+    sub          r5, r10
+%else
+    movzx        r6, byte [r3   +r2  ]
+    sub          r6, r4
+    lea          r5, [r5+r6*8]
+    sub          r5, r6
+%endif
+
+    movzx        r4, byte [e_reg+r1  ]
+    movzx        r6, byte [r3   +r2*2]
+    sub          r6, r4
+%ifdef ARCH_X86_64
+    add          r6, r10
+%endif
+    lea          r5, [r5+r6*8]
+
+    movzx        r4, byte [e_reg+r2*2]
+    movzx        r6, byte [r3   +r1  ]
+    sub          r6, r4
+    lea          r5, [r5+r6*4]
+    add          r5, r6           ; sum of V coefficients
+
+%ifndef ARCH_X86_64
+    mov          r0, r0m
+%endif
+
+%ifidn %3, h264
+    lea          r5, [r5*5+32]
+    sar          r5, 6
+%elifidn %3, rv40
+    lea          r5, [r5*5]
+    sar          r5, 6
+%elifidn %3, svq3
+    test         r5, r5
+    lea          r6, [r5+3]
+    cmovs        r5, r6
+    sar          r5, 2            ; V/4
+    lea          r5, [r5*5]       ; 5*(V/4)
+    test         r5, r5
+    lea          r6, [r5+15]
+    cmovs        r5, r6
+    sar          r5, 4            ; (5*(V/4))/16
+%endif
+
+    movzx        r4, byte [r0+r1  +15]
+    movzx        r3, byte [r3+r2*2   ]
+    lea          r3, [r3+r4+1]
+    shl          r3, 4
+
+    movd        r1d, m0
+    movsx       r1d, r1w
+%ifnidn %3, svq3
+%ifidn %3, h264
+    lea         r1d, [r1d*5+32]
+%else ; rv40
+    lea         r1d, [r1d*5]
+%endif
+    sar         r1d, 6
+%else ; svq3
+    test        r1d, r1d
+    lea         r4d, [r1d+3]
+    cmovs       r1d, r4d
+    sar         r1d, 2           ; H/4
+    lea         r1d, [r1d*5]     ; 5*(H/4)
+    test        r1d, r1d
+    lea         r4d, [r1d+15]
+    cmovs       r1d, r4d
+    sar         r1d, 4           ; (5*(H/4))/16
+%endif
+    movd         m0, r1d
+
+    add         r1d, r5d
+    add         r3d, r1d
+    shl         r1d, 3
+    sub         r3d, r1d          ; a
+
+    movd         m1, r5d
+    movd         m3, r3d
+%ifidn %1, mmx
+    punpcklwd    m0, m0
+    punpcklwd    m1, m1
+    punpcklwd    m3, m3
+    punpckldq    m0, m0
+    punpckldq    m1, m1
+    punpckldq    m3, m3
+%elifidn %1, mmx2
+    pshufw       m0, m0, 0x0
+    pshufw       m1, m1, 0x0
+    pshufw       m3, m3, 0x0
+%else
+    pshuflw      m0, m0, 0x0
+    pshuflw      m1, m1, 0x0
+    pshuflw      m3, m3, 0x0
+    punpcklqdq   m0, m0           ; splat H (words)
+    punpcklqdq   m1, m1           ; splat V (words)
+    punpcklqdq   m3, m3           ; splat a (words)
+%endif
+%ifidn %3, svq3
+    SWAP          0, 1
+%endif
+    mova         m2, m0
+%if mmsize == 8
+    mova         m5, m0
+%endif
+    pmullw       m0, [pw_0to7]    ; 0*H, 1*H, ..., 7*H  (words)
+%if mmsize == 16
+    psllw        m2, 3
+%else
+    psllw        m5, 3
+    psllw        m2, 2
+    mova         m6, m5
+    paddw        m6, m2
+%endif
+    paddw        m0, m3           ; a + {0,1,2,3,4,5,6,7}*H
+    paddw        m2, m0           ; a + {8,9,10,11,12,13,14,15}*H
+%if mmsize == 8
+    paddw        m5, m0           ; a + {8,9,10,11}*H
+    paddw        m6, m0           ; a + {12,13,14,15}*H
+%endif
+
+    mov          r4, 8
+.loop
+    mova         m3, m0           ; b[0..7]
+    mova         m4, m2           ; b[8..15]
+    psraw        m3, 5
+    psraw        m4, 5
+    packuswb     m3, m4
+    mova       [r0], m3
+%if mmsize == 8
+    mova         m3, m5           ; b[8..11]
+    mova         m4, m6           ; b[12..15]
+    psraw        m3, 5
+    psraw        m4, 5
+    packuswb     m3, m4
+    mova     [r0+8], m3
+%endif
+    paddw        m0, m1
+    paddw        m2, m1
+%if mmsize == 8
+    paddw        m5, m1
+    paddw        m6, m1
+%endif
+
+    mova         m3, m0           ; b[0..7]
+    mova         m4, m2           ; b[8..15]
+    psraw        m3, 5
+    psraw        m4, 5
+    packuswb     m3, m4
+    mova    [r0+r2], m3
+%if mmsize == 8
+    mova         m3, m5           ; b[8..11]
+    mova         m4, m6           ; b[12..15]
+    psraw        m3, 5
+    psraw        m4, 5
+    packuswb     m3, m4
+    mova  [r0+r2+8], m3
+%endif
+    paddw        m0, m1
+    paddw        m2, m1
+%if mmsize == 8
+    paddw        m5, m1
+    paddw        m6, m1
+%endif
+
+    lea          r0, [r0+r2*2]
+    dec          r4
+    jg .loop
+    REP_RET
+%endmacro
+
+INIT_MMX
+H264_PRED16x16_PLANE mmx,   0, h264
+H264_PRED16x16_PLANE mmx,   0, rv40
+H264_PRED16x16_PLANE mmx,   0, svq3
+H264_PRED16x16_PLANE mmx2,  0, h264
+H264_PRED16x16_PLANE mmx2,  0, rv40
+H264_PRED16x16_PLANE mmx2,  0, svq3
+INIT_XMM
+H264_PRED16x16_PLANE sse2,  8, h264
+H264_PRED16x16_PLANE sse2,  8, rv40
+H264_PRED16x16_PLANE sse2,  8, svq3
+H264_PRED16x16_PLANE ssse3, 8, h264
+H264_PRED16x16_PLANE ssse3, 8, rv40
+H264_PRED16x16_PLANE ssse3, 8, svq3
+
+;-----------------------------------------------------------------------------
+; void pred8x8_plane(uint8_t *src, int stride)
+;-----------------------------------------------------------------------------
+
+%macro H264_PRED8x8_PLANE 2
+cglobal pred8x8_plane_%1, 2, 7, %2
+    mov          r2, r1           ; +stride
+    neg          r1               ; -stride
+
+    movd         m0, [r0+r1  -1]
+%if mmsize == 8
+    pxor         m2, m2
+    movh         m1, [r0+r1  +4 ]
+    punpcklbw    m0, m2
+    punpcklbw    m1, m2
+    pmullw       m0, [pw_m4to4]
+    pmullw       m1, [pw_m4to4+8]
+%else ; mmsize == 16
+%ifidn %1, sse2
+    pxor         m2, m2
+    movd         m1, [r0+r1  +4]
+    punpckldq    m0, m1
+    punpcklbw    m0, m2
+    pmullw       m0, [pw_m4to4]
+%else ; ssse3
+    movhps       m0, [r0+r1  +4]   ; this reads 4 bytes more than necessary
+    pmaddubsw    m0, [plane8_shuf] ; H coefficients
+%endif
+    movhlps      m1, m0
+%endif
+    paddw        m0, m1
+
+%ifnidn %1, ssse3
+%ifidn %1, mmx
+    mova         m1, m0
+    psrlq        m1, 32
+%elifidn %1, mmx2
+    pshufw       m1, m0, 0xE
+%else ; mmsize == 16
+    pshuflw      m1, m0, 0xE
+%endif
+    paddw        m0, m1
+%endif ; !ssse3
+
+%ifidn %1, mmx
+    mova         m1, m0
+    psrlq        m1, 16
+%elifidn %1, mmx2
+    pshufw       m1, m0, 0x1
+%else
+    pshuflw      m1, m0, 0x1
+%endif
+    paddw        m0, m1           ; sum of H coefficients
+
+    lea          r4, [r0+r2*4-1]
+    lea          r3, [r0     -1]
+    add          r4, r2
+
+%ifdef ARCH_X86_64
+%define e_reg r11
+%else
+%define e_reg r0
+%endif
+
+    movzx     e_reg, byte [r3+r2*2   ]
+    movzx        r5, byte [r4+r1     ]
+    sub          r5, e_reg
+
+    movzx     e_reg, byte [r3        ]
+%ifdef ARCH_X86_64
+    movzx       r10, byte [r4+r2     ]
+    sub         r10, e_reg
+    sub          r5, r10
+%else
+    movzx        r6, byte [r4+r2     ]
+    sub          r6, e_reg
+    lea          r5, [r5+r6*4]
+    sub          r5, r6
+%endif
+
+    movzx     e_reg, byte [r3+r1     ]
+    movzx        r6, byte [r4+r2*2   ]
+    sub          r6, e_reg
+%ifdef ARCH_X86_64
+    add          r6, r10
+%endif
+    lea          r5, [r5+r6*4]
+
+    movzx     e_reg, byte [r3+r2     ]
+    movzx        r6, byte [r4        ]
+    sub          r6, e_reg
+    lea          r6, [r5+r6*2]
+
+    lea          r5, [r6*9+16]
+    lea          r5, [r5+r6*8]
+    sar          r5, 5
+
+%ifndef ARCH_X86_64
+    mov          r0, r0m
+%endif
+
+    movzx        r3, byte [r4+r2*2  ]
+    movzx        r4, byte [r0+r1  +7]
+    lea          r3, [r3+r4+1]
+    shl          r3, 4
+    movd        r1d, m0
+    movsx       r1d, r1w
+    imul        r1d, 17
+    add         r1d, 16
+    sar         r1d, 5
+    movd         m0, r1d
+    add         r1d, r5d
+    sub         r3d, r1d
+    add         r1d, r1d
+    sub         r3d, r1d          ; a
+
+    movd         m1, r5d
+    movd         m3, r3d
+%ifidn %1, mmx
+    punpcklwd    m0, m0
+    punpcklwd    m1, m1
+    punpcklwd    m3, m3
+    punpckldq    m0, m0
+    punpckldq    m1, m1
+    punpckldq    m3, m3
+%elifidn %1, mmx2
+    pshufw       m0, m0, 0x0
+    pshufw       m1, m1, 0x0
+    pshufw       m3, m3, 0x0
+%else
+    pshuflw      m0, m0, 0x0
+    pshuflw      m1, m1, 0x0
+    pshuflw      m3, m3, 0x0
+    punpcklqdq   m0, m0           ; splat H (words)
+    punpcklqdq   m1, m1           ; splat V (words)
+    punpcklqdq   m3, m3           ; splat a (words)
+%endif
+%if mmsize == 8
+    mova         m2, m0
+%endif
+    pmullw       m0, [pw_0to7]    ; 0*H, 1*H, ..., 7*H  (words)
+    paddw        m0, m3           ; a + {0,1,2,3,4,5,6,7}*H
+%if mmsize == 8
+    psllw        m2, 2
+    paddw        m2, m0           ; a + {4,5,6,7}*H
+%endif
+
+    mov          r4, 4
+ALIGN 16
+.loop
+%if mmsize == 16
+    mova         m3, m0           ; b[0..7]
+    paddw        m0, m1
+    psraw        m3, 5
+    mova         m4, m0           ; V+b[0..7]
+    paddw        m0, m1
+    psraw        m4, 5
+    packuswb     m3, m4
+    movh       [r0], m3
+    movhps  [r0+r2], m3
+%else ; mmsize == 8
+    mova         m3, m0           ; b[0..3]
+    mova         m4, m2           ; b[4..7]
+    paddw        m0, m1
+    paddw        m2, m1
+    psraw        m3, 5
+    psraw        m4, 5
+    mova         m5, m0           ; V+b[0..3]
+    mova         m6, m2           ; V+b[4..7]
+    paddw        m0, m1
+    paddw        m2, m1
+    psraw        m5, 5
+    psraw        m6, 5
+    packuswb     m3, m4
+    packuswb     m5, m6
+    mova       [r0], m3
+    mova    [r0+r2], m5
+%endif
+
+    lea          r0, [r0+r2*2]
+    dec          r4
+    jg .loop
+    REP_RET
+%endmacro
+
+INIT_MMX
+H264_PRED8x8_PLANE mmx,   0
+H264_PRED8x8_PLANE mmx2,  0
+INIT_XMM
+H264_PRED8x8_PLANE sse2,  8
+H264_PRED8x8_PLANE ssse3, 8
+
+;-----------------------------------------------------------------------------
+; void pred8x8_vertical(uint8_t *src, int stride)
+;-----------------------------------------------------------------------------
+
+cglobal pred8x8_vertical_mmx, 2,2
+    sub    r0, r1
+    movq  mm0, [r0]
+%rep 3
+    movq [r0+r1*1], mm0
+    movq [r0+r1*2], mm0
+    lea    r0, [r0+r1*2]
+%endrep
+    movq [r0+r1*1], mm0
+    movq [r0+r1*2], mm0
+    RET
+
+;-----------------------------------------------------------------------------
+; void pred8x8_horizontal(uint8_t *src, int stride)
+;-----------------------------------------------------------------------------
+
+%macro PRED8x8_H 1
+cglobal pred8x8_horizontal_%1, 2,3
+    mov       r2, 4
+%ifidn %1, ssse3
+    mova      m2, [pb_3]
+%endif
+.loop:
+    movd      m0, [r0+r1*0-4]
+    movd      m1, [r0+r1*1-4]
+%ifidn %1, ssse3
+    pshufb    m0, m2
+    pshufb    m1, m2
+%else
+    punpcklbw m0, m0
+    punpcklbw m1, m1
+%ifidn %1, mmxext
+    pshufw    m0, m0, 0xff
+    pshufw    m1, m1, 0xff
+%else
+    punpckhwd m0, m0
+    punpckhwd m1, m1
+    punpckhdq m0, m0
+    punpckhdq m1, m1
+%endif
+%endif
+    mova [r0+r1*0], m0
+    mova [r0+r1*1], m1
+    lea       r0, [r0+r1*2]
+    dec       r2
+    jg .loop
+    REP_RET
+%endmacro
+
+INIT_MMX
+PRED8x8_H mmx
+PRED8x8_H mmxext
+PRED8x8_H ssse3
+
+;-----------------------------------------------------------------------------
+; void pred8x8_top_dc_mmxext(uint8_t *src, int stride)
+;-----------------------------------------------------------------------------
+%ifdef CONFIG_GPL
+cglobal pred8x8_top_dc_mmxext, 2,5
+    sub         r0, r1
+    movq       mm0, [r0]
+    pxor       mm1, mm1
+    pxor       mm2, mm2
+    lea         r2, [r0+r1*2]
+    punpckhbw  mm1, mm0
+    punpcklbw  mm0, mm2
+    psadbw     mm1, mm2        ; s1
+    lea         r3, [r2+r1*2]
+    psadbw     mm0, mm2        ; s0
+    psrlw      mm1, 1
+    psrlw      mm0, 1
+    pavgw      mm1, mm2
+    lea         r4, [r3+r1*2]
+    pavgw      mm0, mm2
+    pshufw     mm1, mm1, 0
+    pshufw     mm0, mm0, 0     ; dc0 (w)
+    packuswb   mm0, mm1        ; dc0,dc1 (b)
+    movq [r0+r1*1], mm0
+    movq [r0+r1*2], mm0
+    lea         r0, [r3+r1*2]
+    movq [r2+r1*1], mm0
+    movq [r2+r1*2], mm0
+    movq [r3+r1*1], mm0
+    movq [r3+r1*2], mm0
+    movq [r0+r1*1], mm0
+    movq [r0+r1*2], mm0
+    RET
+
+;-----------------------------------------------------------------------------
+; void pred8x8_dc_mmxext(uint8_t *src, int stride)
+;-----------------------------------------------------------------------------
+
+INIT_MMX
+cglobal pred8x8_dc_mmxext, 2,5
+    sub       r0, r1
+    pxor      m7, m7
+    movd      m0, [r0+0]
+    movd      m1, [r0+4]
+    psadbw    m0, m7            ; s0
+    mov       r4, r0
+    psadbw    m1, m7            ; s1
+
+    movzx    r2d, byte [r0+r1*1-1]
+    movzx    r3d, byte [r0+r1*2-1]
+    lea       r0, [r0+r1*2]
+    add      r2d, r3d
+    movzx    r3d, byte [r0+r1*1-1]
+    add      r2d, r3d
+    movzx    r3d, byte [r0+r1*2-1]
+    add      r2d, r3d
+    lea       r0, [r0+r1*2]
+    movd      m2, r2d            ; s2
+    movzx    r2d, byte [r0+r1*1-1]
+    movzx    r3d, byte [r0+r1*2-1]
+    lea       r0, [r0+r1*2]
+    add      r2d, r3d
+    movzx    r3d, byte [r0+r1*1-1]
+    add      r2d, r3d
+    movzx    r3d, byte [r0+r1*2-1]
+    add      r2d, r3d
+    movd      m3, r2d            ; s3
+
+    punpcklwd m0, m1
+    mov       r0, r4
+    punpcklwd m2, m3
+    punpckldq m0, m2            ; s0, s1, s2, s3
+    pshufw    m3, m0, 11110110b ; s2, s1, s3, s3
+    lea       r2, [r0+r1*2]
+    pshufw    m0, m0, 01110100b ; s0, s1, s3, s1
+    paddw     m0, m3
+    lea       r3, [r2+r1*2]
+    psrlw     m0, 2
+    pavgw     m0, m7            ; s0+s2, s1, s3, s1+s3
+    lea       r4, [r3+r1*2]
+    packuswb  m0, m0
+    punpcklbw m0, m0
+    movq      m1, m0
+    punpcklbw m0, m0
+    punpckhbw m1, m1
+    movq [r0+r1*1], m0
+    movq [r0+r1*2], m0
+    movq [r2+r1*1], m0
+    movq [r2+r1*2], m0
+    movq [r3+r1*1], m1
+    movq [r3+r1*2], m1
+    movq [r4+r1*1], m1
+    movq [r4+r1*2], m1
+    RET
+%endif
+
+;-----------------------------------------------------------------------------
+; void pred8x8_dc_rv40(uint8_t *src, int stride)
+;-----------------------------------------------------------------------------
+
+cglobal pred8x8_dc_rv40_mmxext, 2,7
+    mov       r4, r0
+    sub       r0, r1
+    pxor      mm0, mm0
+    psadbw    mm0, [r0]
+    dec        r0
+    movzx     r5d, byte [r0+r1*1]
+    movd      r6d, mm0
+    lea        r0, [r0+r1*2]
+%rep 3
+    movzx     r2d, byte [r0+r1*0]
+    movzx     r3d, byte [r0+r1*1]
+    add       r5d, r2d
+    add       r6d, r3d
+    lea        r0, [r0+r1*2]
+%endrep
+    movzx     r2d, byte [r0+r1*0]
+    add       r5d, r6d
+    lea       r2d, [r2+r5+8]
+    shr       r2d, 4
+    movd      mm0, r2d
+    punpcklbw mm0, mm0
+    pshufw    mm0, mm0, 0
+    mov       r3d, 4
+.loop:
+    movq [r4+r1*0], mm0
+    movq [r4+r1*1], mm0
+    lea   r4, [r4+r1*2]
+    dec   r3d
+    jg .loop
+    REP_RET
+
+;-----------------------------------------------------------------------------
+; void pred8x8_tm_vp8(uint8_t *src, int stride)
+;-----------------------------------------------------------------------------
+
+%macro PRED8x8_TM_MMX 1
+cglobal pred8x8_tm_vp8_%1, 2,6
+    sub        r0, r1
+    pxor      mm7, mm7
+    movq      mm0, [r0]
+    movq      mm1, mm0
+    punpcklbw mm0, mm7
+    punpckhbw mm1, mm7
+    movzx     r4d, byte [r0-1]
+    mov       r5d, 4
+.loop:
+    movzx     r2d, byte [r0+r1*1-1]
+    movzx     r3d, byte [r0+r1*2-1]
+    sub       r2d, r4d
+    sub       r3d, r4d
+    movd      mm2, r2d
+    movd      mm4, r3d
+%ifidn %1, mmx
+    punpcklwd mm2, mm2
+    punpcklwd mm4, mm4
+    punpckldq mm2, mm2
+    punpckldq mm4, mm4
+%else
+    pshufw    mm2, mm2, 0
+    pshufw    mm4, mm4, 0
+%endif
+    movq      mm3, mm2
+    movq      mm5, mm4
+    paddw     mm2, mm0
+    paddw     mm3, mm1
+    paddw     mm4, mm0
+    paddw     mm5, mm1
+    packuswb  mm2, mm3
+    packuswb  mm4, mm5
+    movq [r0+r1*1], mm2
+    movq [r0+r1*2], mm4
+    lea        r0, [r0+r1*2]
+    dec       r5d
+    jg .loop
+    REP_RET
+%endmacro
+
+PRED8x8_TM_MMX mmx
+PRED8x8_TM_MMX mmxext
+
+cglobal pred8x8_tm_vp8_sse2, 2,6,4
+    sub          r0, r1
+    pxor       xmm1, xmm1
+    movq       xmm0, [r0]
+    punpcklbw  xmm0, xmm1
+    movzx       r4d, byte [r0-1]
+    mov         r5d, 4
+.loop:
+    movzx       r2d, byte [r0+r1*1-1]
+    movzx       r3d, byte [r0+r1*2-1]
+    sub         r2d, r4d
+    sub         r3d, r4d
+    movd       xmm2, r2d
+    movd       xmm3, r3d
+    pshuflw    xmm2, xmm2, 0
+    pshuflw    xmm3, xmm3, 0
+    punpcklqdq xmm2, xmm2
+    punpcklqdq xmm3, xmm3
+    paddw      xmm2, xmm0
+    paddw      xmm3, xmm0
+    packuswb   xmm2, xmm3
+    movq   [r0+r1*1], xmm2
+    movhps [r0+r1*2], xmm2
+    lea          r0, [r0+r1*2]
+    dec         r5d
+    jg .loop
+    REP_RET
+
+cglobal pred8x8_tm_vp8_ssse3, 2,3,6
+    sub          r0, r1
+    movdqa     xmm4, [tm_shuf]
+    pxor       xmm1, xmm1
+    movq       xmm0, [r0]
+    punpcklbw  xmm0, xmm1
+    movd       xmm5, [r0-4]
+    pshufb     xmm5, xmm4
+    mov         r2d, 4
+.loop:
+    movd       xmm2, [r0+r1*1-4]
+    movd       xmm3, [r0+r1*2-4]
+    pshufb     xmm2, xmm4
+    pshufb     xmm3, xmm4
+    psubw      xmm2, xmm5
+    psubw      xmm3, xmm5
+    paddw      xmm2, xmm0
+    paddw      xmm3, xmm0
+    packuswb   xmm2, xmm3
+    movq   [r0+r1*1], xmm2
+    movhps [r0+r1*2], xmm2
+    lea          r0, [r0+r1*2]
+    dec         r2d
+    jg .loop
+    REP_RET
+
+; dest, left, right, src, tmp
+; output: %1 = (t[n-1] + t[n]*2 + t[n+1] + 2) >> 2
+%macro PRED4x4_LOWPASS 5
+    mova    %5, %2
+    pavgb   %2, %3
+    pxor    %3, %5
+    mova    %1, %4
+    pand    %3, [pb_1]
+    psubusb %2, %3
+    pavgb   %1, %2
+%endmacro
+
+;-----------------------------------------------------------------------------
+; void pred8x8l_top_dc(uint8_t *src, int has_topleft, int has_topright, int stride)
+;-----------------------------------------------------------------------------
+%ifdef CONFIG_GPL
+%macro PRED8x8L_TOP_DC 1
+cglobal pred8x8l_top_dc_%1, 4,4
+    sub          r0, r3
+    pxor        mm7, mm7
+    movq        mm0, [r0-8]
+    movq        mm3, [r0]
+    movq        mm1, [r0+8]
+    movq        mm2, mm3
+    movq        mm4, mm3
+    PALIGNR     mm2, mm0, 7, mm0
+    PALIGNR     mm1, mm4, 1, mm4
+    test         r1, r1 ; top_left
+    jz .fix_lt_2
+    test         r2, r2 ; top_right
+    jz .fix_tr_1
+    jmp .body
+.fix_lt_2:
+    movq        mm5, mm3
+    pxor        mm5, mm2
+    psllq       mm5, 56
+    psrlq       mm5, 56
+    pxor        mm2, mm5
+    test         r2, r2 ; top_right
+    jnz .body
+.fix_tr_1:
+    movq        mm5, mm3
+    pxor        mm5, mm1
+    psrlq       mm5, 56
+    psllq       mm5, 56
+    pxor        mm1, mm5
+.body
+    PRED4x4_LOWPASS mm0, mm2, mm1, mm3, mm5
+    psadbw   mm7, mm0
+    paddw    mm7, [pw_4]
+    psrlw    mm7, 3
+    pshufw   mm7, mm7, 0
+    packuswb mm7, mm7
+%rep 3
+    movq [r0+r3*1], mm7
+    movq [r0+r3*2], mm7
+    lea    r0, [r0+r3*2]
+%endrep
+    movq [r0+r3*1], mm7
+    movq [r0+r3*2], mm7
+    RET
+%endmacro
+
+INIT_MMX
+%define PALIGNR PALIGNR_MMX
+PRED8x8L_TOP_DC mmxext
+%define PALIGNR PALIGNR_SSSE3
+PRED8x8L_TOP_DC ssse3
+
+;-----------------------------------------------------------------------------
+;void pred8x8l_dc(uint8_t *src, int has_topleft, int has_topright, int stride)
+;-----------------------------------------------------------------------------
+
+%macro PRED8x8L_DC 1
+cglobal pred8x8l_dc_%1, 4,5
+    sub          r0, r3
+    lea          r4, [r0+r3*2]
+    movq        mm0, [r0+r3*1-8]
+    punpckhbw   mm0, [r0+r3*0-8]
+    movq        mm1, [r4+r3*1-8]
+    punpckhbw   mm1, [r0+r3*2-8]
+    mov          r4, r0
+    punpckhwd   mm1, mm0
+    lea          r0, [r0+r3*4]
+    movq        mm2, [r0+r3*1-8]
+    punpckhbw   mm2, [r0+r3*0-8]
+    lea          r0, [r0+r3*2]
+    movq        mm3, [r0+r3*1-8]
+    punpckhbw   mm3, [r0+r3*0-8]
+    punpckhwd   mm3, mm2
+    punpckhdq   mm3, mm1
+    lea          r0, [r0+r3*2]
+    movq        mm0, [r0+r3*0-8]
+    movq        mm1, [r4]
+    mov          r0, r4
+    movq        mm4, mm3
+    movq        mm2, mm3
+    PALIGNR     mm4, mm0, 7, mm0
+    PALIGNR     mm1, mm2, 1, mm2
+    test        r1, r1
+    jnz .do_left
+.fix_lt_1:
+    movq        mm5, mm3
+    pxor        mm5, mm4
+    psrlq       mm5, 56
+    psllq       mm5, 48
+    pxor        mm1, mm5
+    jmp .do_left
+.fix_lt_2:
+    movq        mm5, mm3
+    pxor        mm5, mm2
+    psllq       mm5, 56
+    psrlq       mm5, 56
+    pxor        mm2, mm5
+    test         r2, r2
+    jnz .body
+.fix_tr_1:
+    movq        mm5, mm3
+    pxor        mm5, mm1
+    psrlq       mm5, 56
+    psllq       mm5, 56
+    pxor        mm1, mm5
+    jmp .body
+.do_left:
+    movq        mm0, mm4
+    PRED4x4_LOWPASS mm2, mm1, mm4, mm3, mm5
+    movq        mm4, mm0
+    movq        mm7, mm2
+    PRED4x4_LOWPASS mm1, mm3, mm0, mm4, mm5
+    psllq       mm1, 56
+    PALIGNR     mm7, mm1, 7, mm3
+    movq        mm0, [r0-8]
+    movq        mm3, [r0]
+    movq        mm1, [r0+8]
+    movq        mm2, mm3
+    movq        mm4, mm3
+    PALIGNR     mm2, mm0, 7, mm0
+    PALIGNR     mm1, mm4, 1, mm4
+    test         r1, r1
+    jz .fix_lt_2
+    test         r2, r2
+    jz .fix_tr_1
+.body
+    lea          r1, [r0+r3*2]
+    PRED4x4_LOWPASS mm6, mm2, mm1, mm3, mm5
+    pxor        mm0, mm0
+    pxor        mm1, mm1
+    lea          r2, [r1+r3*2]
+    psadbw      mm0, mm7
+    psadbw      mm1, mm6
+    paddw       mm0, [pw_8]
+    paddw       mm0, mm1
+    lea          r4, [r2+r3*2]
+    psrlw       mm0, 4
+    pshufw      mm0, mm0, 0
+    packuswb    mm0, mm0
+    movq [r0+r3*1], mm0
+    movq [r0+r3*2], mm0
+    movq [r1+r3*1], mm0
+    movq [r1+r3*2], mm0
+    movq [r2+r3*1], mm0
+    movq [r2+r3*2], mm0
+    movq [r4+r3*1], mm0
+    movq [r4+r3*2], mm0
+    RET
+%endmacro
+INIT_MMX
+%define PALIGNR PALIGNR_MMX
+PRED8x8L_DC mmxext
+%define PALIGNR PALIGNR_SSSE3
+PRED8x8L_DC ssse3
+
+;-----------------------------------------------------------------------------
+; void pred8x8l_horizontal(uint8_t *src, int has_topleft, int has_topright, int stride)
+;-----------------------------------------------------------------------------
+
+%macro PRED8x8L_HORIZONTAL 1
+cglobal pred8x8l_horizontal_%1, 4,4
+    sub          r0, r3
+    lea          r2, [r0+r3*2]
+    movq        mm0, [r0+r3*1-8]
+    test         r1, r1
+    lea          r1, [r0+r3]
+    cmovnz       r1, r0
+    punpckhbw   mm0, [r1+r3*0-8]
+    movq        mm1, [r2+r3*1-8]
+    punpckhbw   mm1, [r0+r3*2-8]
+    mov          r2, r0
+    punpckhwd   mm1, mm0
+    lea          r0, [r0+r3*4]
+    movq        mm2, [r0+r3*1-8]
+    punpckhbw   mm2, [r0+r3*0-8]
+    lea          r0, [r0+r3*2]
+    movq        mm3, [r0+r3*1-8]
+    punpckhbw   mm3, [r0+r3*0-8]
+    punpckhwd   mm3, mm2
+    punpckhdq   mm3, mm1
+    lea          r0, [r0+r3*2]
+    movq        mm0, [r0+r3*0-8]
+    movq        mm1, [r1+r3*0-8]
+    mov          r0, r2
+    movq        mm4, mm3
+    movq        mm2, mm3
+    PALIGNR     mm4, mm0, 7, mm0
+    PALIGNR     mm1, mm2, 1, mm2
+    movq        mm0, mm4
+    PRED4x4_LOWPASS mm2, mm1, mm4, mm3, mm5
+    movq        mm4, mm0
+    movq        mm7, mm2
+    PRED4x4_LOWPASS mm1, mm3, mm0, mm4, mm5
+    psllq       mm1, 56
+    PALIGNR     mm7, mm1, 7, mm3
+    movq        mm3, mm7
+    lea         r1, [r0+r3*2]
+    movq       mm7, mm3
+    punpckhbw  mm3, mm3
+    punpcklbw  mm7, mm7
+    pshufw     mm0, mm3, 0xff
+    pshufw     mm1, mm3, 0xaa
+    lea         r2, [r1+r3*2]
+    pshufw     mm2, mm3, 0x55
+    pshufw     mm3, mm3, 0x00
+    pshufw     mm4, mm7, 0xff
+    pshufw     mm5, mm7, 0xaa
+    pshufw     mm6, mm7, 0x55
+    pshufw     mm7, mm7, 0x00
+    movq [r0+r3*1], mm0
+    movq [r0+r3*2], mm1
+    movq [r1+r3*1], mm2
+    movq [r1+r3*2], mm3
+    movq [r2+r3*1], mm4
+    movq [r2+r3*2], mm5
+    lea         r0, [r2+r3*2]
+    movq [r0+r3*1], mm6
+    movq [r0+r3*2], mm7
+    RET
+%endmacro
+
+INIT_MMX
+%define PALIGNR PALIGNR_MMX
+PRED8x8L_HORIZONTAL mmxext
+%define PALIGNR PALIGNR_SSSE3
+PRED8x8L_HORIZONTAL ssse3
+
+;-----------------------------------------------------------------------------
+; void pred8x8l_vertical(uint8_t *src, int has_topleft, int has_topright, int stride)
+;-----------------------------------------------------------------------------
+
+%macro PRED8x8L_VERTICAL 1
+cglobal pred8x8l_vertical_%1, 4,4
+    sub          r0, r3
+    movq        mm0, [r0-8]
+    movq        mm3, [r0]
+    movq        mm1, [r0+8]
+    movq        mm2, mm3
+    movq        mm4, mm3
+    PALIGNR     mm2, mm0, 7, mm0
+    PALIGNR     mm1, mm4, 1, mm4
+    test         r1, r1 ; top_left
+    jz .fix_lt_2
+    test         r2, r2 ; top_right
+    jz .fix_tr_1
+    jmp .body
+.fix_lt_2:
+    movq        mm5, mm3
+    pxor        mm5, mm2
+    psllq       mm5, 56
+    psrlq       mm5, 56
+    pxor        mm2, mm5
+    test         r2, r2 ; top_right
+    jnz .body
+.fix_tr_1:
+    movq        mm5, mm3
+    pxor        mm5, mm1
+    psrlq       mm5, 56
+    psllq       mm5, 56
+    pxor        mm1, mm5
+.body
+    PRED4x4_LOWPASS mm0, mm2, mm1, mm3, mm5
+%rep 3
+    movq [r0+r3*1], mm0
+    movq [r0+r3*2], mm0
+    lea    r0, [r0+r3*2]
+%endrep
+    movq [r0+r3*1], mm0
+    movq [r0+r3*2], mm0
+    RET
+%endmacro
+
+INIT_MMX
+%define PALIGNR PALIGNR_MMX
+PRED8x8L_VERTICAL mmxext
+%define PALIGNR PALIGNR_SSSE3
+PRED8x8L_VERTICAL ssse3
+
+;-----------------------------------------------------------------------------
+;void pred8x8l_down_left(uint8_t *src, int has_topleft, int has_topright, int stride)
+;-----------------------------------------------------------------------------
+
+INIT_MMX
+%define PALIGNR PALIGNR_MMX
+cglobal pred8x8l_down_left_mmxext, 4,5
+    sub          r0, r3
+    movq        mm0, [r0-8]
+    movq        mm3, [r0]
+    movq        mm1, [r0+8]
+    movq        mm2, mm3
+    movq        mm4, mm3
+    PALIGNR     mm2, mm0, 7, mm0
+    PALIGNR     mm1, mm4, 1, mm4
+    test         r1, r1
+    jz .fix_lt_2
+    test         r2, r2
+    jz .fix_tr_1
+    jmp .do_top
+.fix_lt_2:
+    movq        mm5, mm3
+    pxor        mm5, mm2
+    psllq       mm5, 56
+    psrlq       mm5, 56
+    pxor        mm2, mm5
+    test         r2, r2
+    jnz .do_top
+.fix_tr_1:
+    movq        mm5, mm3
+    pxor        mm5, mm1
+    psrlq       mm5, 56
+    psllq       mm5, 56
+    pxor        mm1, mm5
+    jmp .do_top
+.fix_tr_2:
+    punpckhbw   mm3, mm3
+    pshufw      mm1, mm3, 0xFF
+    jmp .do_topright
+.do_top:
+    PRED4x4_LOWPASS mm4, mm2, mm1, mm3, mm5
+    movq        mm7, mm4
+    test         r2, r2
+    jz .fix_tr_2
+    movq        mm0, [r0+8]
+    movq        mm5, mm0
+    movq        mm2, mm0
+    movq        mm4, mm0
+    psrlq       mm5, 56
+    PALIGNR     mm2, mm3, 7, mm3
+    PALIGNR     mm5, mm4, 1, mm4
+    PRED4x4_LOWPASS mm1, mm2, mm5, mm0, mm4
+.do_topright:
+    lea          r1, [r0+r3*2]
+    movq        mm6, mm1
+    psrlq       mm1, 56
+    movq        mm4, mm1
+    lea          r2, [r1+r3*2]
+    movq        mm2, mm6
+    PALIGNR     mm2, mm7, 1, mm0
+    movq        mm3, mm6
+    PALIGNR     mm3, mm7, 7, mm0
+    PALIGNR     mm4, mm6, 1, mm0
+    movq        mm5, mm7
+    movq        mm1, mm7
+    movq        mm7, mm6
+    lea          r4, [r2+r3*2]
+    psllq       mm1, 8
+    PRED4x4_LOWPASS mm0, mm1, mm2, mm5, mm6
+    PRED4x4_LOWPASS mm1, mm3, mm4, mm7, mm6
+    movq  [r4+r3*2], mm1
+    movq        mm2, mm0
+    psllq       mm1, 8
+    psrlq       mm2, 56
+    psllq       mm0, 8
+    por         mm1, mm2
+    movq  [r4+r3*1], mm1
+    movq        mm2, mm0
+    psllq       mm1, 8
+    psrlq       mm2, 56
+    psllq       mm0, 8
+    por         mm1, mm2
+    movq  [r2+r3*2], mm1
+    movq        mm2, mm0
+    psllq       mm1, 8
+    psrlq       mm2, 56
+    psllq       mm0, 8
+    por         mm1, mm2
+    movq  [r2+r3*1], mm1
+    movq        mm2, mm0
+    psllq       mm1, 8
+    psrlq       mm2, 56
+    psllq       mm0, 8
+    por         mm1, mm2
+    movq  [r1+r3*2], mm1
+    movq        mm2, mm0
+    psllq       mm1, 8
+    psrlq       mm2, 56
+    psllq       mm0, 8
+    por         mm1, mm2
+    movq  [r1+r3*1], mm1
+    movq        mm2, mm0
+    psllq       mm1, 8
+    psrlq       mm2, 56
+    psllq       mm0, 8
+    por         mm1, mm2
+    movq  [r0+r3*2], mm1
+    psllq       mm1, 8
+    psrlq       mm0, 56
+    por         mm1, mm0
+    movq  [r0+r3*1], mm1
+    RET
+
+%macro PRED8x8L_DOWN_LEFT 1
+cglobal pred8x8l_down_left_%1, 4,4
+    sub          r0, r3
+    movq        mm0, [r0-8]
+    movq        mm3, [r0]
+    movq        mm1, [r0+8]
+    movq        mm2, mm3
+    movq        mm4, mm3
+    PALIGNR     mm2, mm0, 7, mm0
+    PALIGNR     mm1, mm4, 1, mm4
+    test         r1, r1 ; top_left
+    jz .fix_lt_2
+    test         r2, r2 ; top_right
+    jz .fix_tr_1
+    jmp .do_top
+.fix_lt_2:
+    movq        mm5, mm3
+    pxor        mm5, mm2
+    psllq       mm5, 56
+    psrlq       mm5, 56
+    pxor        mm2, mm5
+    test         r2, r2 ; top_right
+    jnz .do_top
+.fix_tr_1:
+    movq        mm5, mm3
+    pxor        mm5, mm1
+    psrlq       mm5, 56
+    psllq       mm5, 56
+    pxor        mm1, mm5
+    jmp .do_top
+.fix_tr_2:
+    punpckhbw   mm3, mm3
+    pshufw      mm1, mm3, 0xFF
+    jmp .do_topright
+.do_top:
+    PRED4x4_LOWPASS mm4, mm2, mm1, mm3, mm5
+    movq2dq    xmm3, mm4
+    test         r2, r2 ; top_right
+    jz .fix_tr_2
+    movq        mm0, [r0+8]
+    movq        mm5, mm0
+    movq        mm2, mm0
+    movq        mm4, mm0
+    psrlq       mm5, 56
+    PALIGNR     mm2, mm3, 7, mm3
+    PALIGNR     mm5, mm4, 1, mm4
+    PRED4x4_LOWPASS mm1, mm2, mm5, mm0, mm4
+.do_topright:
+    movq2dq    xmm4, mm1
+    psrlq       mm1, 56
+    movq2dq    xmm5, mm1
+    lea         r1, [r0+r3*2]
+    pslldq    xmm4, 8
+    por       xmm3, xmm4
+    movdqa    xmm2, xmm3
+    psrldq    xmm2, 1
+    pslldq    xmm5, 15
+    por       xmm2, xmm5
+    lea         r2, [r1+r3*2]
+    movdqa    xmm1, xmm3
+    pslldq    xmm1, 1
+INIT_XMM
+    PRED4x4_LOWPASS xmm0, xmm1, xmm2, xmm3, xmm4
+    psrldq    xmm0, 1
+    movq [r0+r3*1], xmm0
+    psrldq    xmm0, 1
+    movq [r0+r3*2], xmm0
+    psrldq    xmm0, 1
+    lea         r0, [r2+r3*2]
+    movq [r1+r3*1], xmm0
+    psrldq    xmm0, 1
+    movq [r1+r3*2], xmm0
+    psrldq    xmm0, 1
+    movq [r2+r3*1], xmm0
+    psrldq    xmm0, 1
+    movq [r2+r3*2], xmm0
+    psrldq    xmm0, 1
+    movq [r0+r3*1], xmm0
+    psrldq    xmm0, 1
+    movq [r0+r3*2], xmm0
+    RET
+%endmacro
+
+INIT_MMX
+%define PALIGNR PALIGNR_MMX
+PRED8x8L_DOWN_LEFT sse2
+INIT_MMX
+%define PALIGNR PALIGNR_SSSE3
+PRED8x8L_DOWN_LEFT ssse3
+
+;-----------------------------------------------------------------------------
+;void pred8x8l_down_right_mmxext(uint8_t *src, int has_topleft, int has_topright, int stride)
+;-----------------------------------------------------------------------------
+
+INIT_MMX
+%define PALIGNR PALIGNR_MMX
+cglobal pred8x8l_down_right_mmxext, 4,5
+    sub          r0, r3
+    lea          r4, [r0+r3*2]
+    movq        mm0, [r0+r3*1-8]
+    punpckhbw   mm0, [r0+r3*0-8]
+    movq        mm1, [r4+r3*1-8]
+    punpckhbw   mm1, [r0+r3*2-8]
+    mov          r4, r0
+    punpckhwd   mm1, mm0
+    lea          r0, [r0+r3*4]
+    movq        mm2, [r0+r3*1-8]
+    punpckhbw   mm2, [r0+r3*0-8]
+    lea          r0, [r0+r3*2]
+    movq        mm3, [r0+r3*1-8]
+    punpckhbw   mm3, [r0+r3*0-8]
+    punpckhwd   mm3, mm2
+    punpckhdq   mm3, mm1
+    lea          r0, [r0+r3*2]
+    movq        mm0, [r0+r3*0-8]
+    movq        mm1, [r4]
+    mov          r0, r4
+    movq        mm4, mm3
+    movq        mm2, mm3
+    PALIGNR     mm4, mm0, 7, mm0
+    PALIGNR     mm1, mm2, 1, mm2
+    test        r1, r1 ; top_left
+    jz .fix_lt_1
+.do_left:
+    movq        mm0, mm4
+    PRED4x4_LOWPASS mm2, mm1, mm4, mm3, mm5
+    movq        mm4, mm0
+    movq        mm7, mm2
+    movq        mm6, mm2
+    PRED4x4_LOWPASS mm1, mm3, mm0, mm4, mm5
+    psllq       mm1, 56
+    PALIGNR     mm7, mm1, 7, mm3
+    movq        mm0, [r0-8]
+    movq        mm3, [r0]
+    movq        mm1, [r0+8]
+    movq        mm2, mm3
+    movq        mm4, mm3
+    PALIGNR     mm2, mm0, 7, mm0
+    PALIGNR     mm1, mm4, 1, mm4
+    test         r1, r1 ; top_left
+    jz .fix_lt_2
+    test         r2, r2 ; top_right
+    jz .fix_tr_1
+.do_top:
+    PRED4x4_LOWPASS mm4, mm2, mm1, mm3, mm5
+    movq        mm5, mm4
+    jmp .body
+.fix_lt_1:
+    movq        mm5, mm3
+    pxor        mm5, mm4
+    psrlq       mm5, 56
+    psllq       mm5, 48
+    pxor        mm1, mm5
+    jmp .do_left
+.fix_lt_2:
+    movq        mm5, mm3
+    pxor        mm5, mm2
+    psllq       mm5, 56
+    psrlq       mm5, 56
+    pxor        mm2, mm5
+    test         r2, r2 ; top_right
+    jnz .do_top
+.fix_tr_1:
+    movq        mm5, mm3
+    pxor        mm5, mm1
+    psrlq       mm5, 56
+    psllq       mm5, 56
+    pxor        mm1, mm5
+    jmp .do_top
+.body
+    lea         r1, [r0+r3*2]
+    movq       mm1, mm7
+    movq       mm7, mm5
+    movq       mm5, mm6
+    movq       mm2, mm7
+    lea         r2, [r1+r3*2]
+    PALIGNR    mm2, mm6, 1, mm0
+    movq       mm3, mm7
+    PALIGNR    mm3, mm6, 7, mm0
+    movq       mm4, mm7
+    lea         r4, [r2+r3*2]
+    psrlq      mm4, 8
+    PRED4x4_LOWPASS mm0, mm1, mm2, mm5, mm6
+    PRED4x4_LOWPASS mm1, mm3, mm4, mm7, mm6
+    movq [r4+r3*2], mm0
+    movq       mm2, mm1
+    psrlq      mm0, 8
+    psllq      mm2, 56
+    psrlq      mm1, 8
+    por        mm0, mm2
+    movq [r4+r3*1], mm0
+    movq       mm2, mm1
+    psrlq      mm0, 8
+    psllq      mm2, 56
+    psrlq      mm1, 8
+    por        mm0, mm2
+    movq [r2+r3*2], mm0
+    movq       mm2, mm1
+    psrlq      mm0, 8
+    psllq      mm2, 56
+    psrlq      mm1, 8
+    por        mm0, mm2
+    movq [r2+r3*1], mm0
+    movq       mm2, mm1
+    psrlq      mm0, 8
+    psllq      mm2, 56
+    psrlq      mm1, 8
+    por        mm0, mm2
+    movq [r1+r3*2], mm0
+    movq       mm2, mm1
+    psrlq      mm0, 8
+    psllq      mm2, 56
+    psrlq      mm1, 8
+    por        mm0, mm2
+    movq [r1+r3*1], mm0
+    movq       mm2, mm1
+    psrlq      mm0, 8
+    psllq      mm2, 56
+    psrlq      mm1, 8
+    por        mm0, mm2
+    movq [r0+r3*2], mm0
+    psrlq      mm0, 8
+    psllq      mm1, 56
+    por        mm0, mm1
+    movq [r0+r3*1], mm0
+    RET
+
+%macro PRED8x8L_DOWN_RIGHT 1
+cglobal pred8x8l_down_right_%1, 4,5
+    sub          r0, r3
+    lea          r4, [r0+r3*2]
+    movq        mm0, [r0+r3*1-8]
+    punpckhbw   mm0, [r0+r3*0-8]
+    movq        mm1, [r4+r3*1-8]
+    punpckhbw   mm1, [r0+r3*2-8]
+    mov          r4, r0
+    punpckhwd   mm1, mm0
+    lea          r0, [r0+r3*4]
+    movq        mm2, [r0+r3*1-8]
+    punpckhbw   mm2, [r0+r3*0-8]
+    lea          r0, [r0+r3*2]
+    movq        mm3, [r0+r3*1-8]
+    punpckhbw   mm3, [r0+r3*0-8]
+    punpckhwd   mm3, mm2
+    punpckhdq   mm3, mm1
+    lea          r0, [r0+r3*2]
+    movq        mm0, [r0+r3*0-8]
+    movq        mm1, [r4]
+    mov          r0, r4
+    movq        mm4, mm3
+    movq        mm2, mm3
+    PALIGNR     mm4, mm0, 7, mm0
+    PALIGNR     mm1, mm2, 1, mm2
+    test        r1, r1
+    jz .fix_lt_1
+    jmp .do_left
+.fix_lt_1:
+    movq        mm5, mm3
+    pxor        mm5, mm4
+    psrlq       mm5, 56
+    psllq       mm5, 48
+    pxor        mm1, mm5
+    jmp .do_left
+.fix_lt_2:
+    movq        mm5, mm3
+    pxor        mm5, mm2
+    psllq       mm5, 56
+    psrlq       mm5, 56
+    pxor        mm2, mm5
+    test         r2, r2
+    jnz .do_top
+.fix_tr_1:
+    movq        mm5, mm3
+    pxor        mm5, mm1
+    psrlq       mm5, 56
+    psllq       mm5, 56
+    pxor        mm1, mm5
+    jmp .do_top
+.do_left:
+    movq        mm0, mm4
+    PRED4x4_LOWPASS mm2, mm1, mm4, mm3, mm5
+    movq        mm4, mm0
+    movq        mm7, mm2
+    movq2dq    xmm3, mm2
+    PRED4x4_LOWPASS mm1, mm3, mm0, mm4, mm5
+    psllq       mm1, 56
+    PALIGNR     mm7, mm1, 7, mm3
+    movq2dq    xmm1, mm7
+    movq        mm0, [r0-8]
+    movq        mm3, [r0]
+    movq        mm1, [r0+8]
+    movq        mm2, mm3
+    movq        mm4, mm3
+    PALIGNR     mm2, mm0, 7, mm0
+    PALIGNR     mm1, mm4, 1, mm4
+    test         r1, r1
+    jz .fix_lt_2
+    test         r2, r2
+    jz .fix_tr_1
+.do_top:
+    PRED4x4_LOWPASS mm4, mm2, mm1, mm3, mm5
+    movq2dq   xmm4, mm4
+    lea         r1, [r0+r3*2]
+    movdqa    xmm0, xmm3
+    pslldq    xmm4, 8
+    por       xmm3, xmm4
+    lea         r2, [r1+r3*2]
+    pslldq    xmm4, 1
+    por       xmm1, xmm4
+    psrldq    xmm0, 7
+    pslldq    xmm0, 15
+    psrldq    xmm0, 7
+    por       xmm1, xmm0
+    lea         r0, [r2+r3*2]
+    movdqa    xmm2, xmm3
+    psrldq    xmm2, 1
+INIT_XMM
+    PRED4x4_LOWPASS xmm0, xmm1, xmm2, xmm3, xmm4
+    movdqa    xmm1, xmm0
+    psrldq    xmm1, 1
+    movq [r0+r3*2], xmm0
+    movq [r0+r3*1], xmm1
+    psrldq    xmm0, 2
+    psrldq    xmm1, 2
+    movq [r2+r3*2], xmm0
+    movq [r2+r3*1], xmm1
+    psrldq    xmm0, 2
+    psrldq    xmm1, 2
+    movq [r1+r3*2], xmm0
+    movq [r1+r3*1], xmm1
+    psrldq    xmm0, 2
+    psrldq    xmm1, 2
+    movq [r4+r3*2], xmm0
+    movq [r4+r3*1], xmm1
+    RET
+%endmacro
+
+INIT_MMX
+%define PALIGNR PALIGNR_MMX
+PRED8x8L_DOWN_RIGHT sse2
+INIT_MMX
+%define PALIGNR PALIGNR_SSSE3
+PRED8x8L_DOWN_RIGHT ssse3
+
+;-----------------------------------------------------------------------------
+; void pred8x8l_vertical_right(uint8_t *src, int has_topleft, int has_topright, int stride)
+;-----------------------------------------------------------------------------
+
+INIT_MMX
+%define PALIGNR PALIGNR_MMX
+cglobal pred8x8l_vertical_right_mmxext, 4,5
+    sub          r0, r3
+    lea          r4, [r0+r3*2]
+    movq        mm0, [r0+r3*1-8]
+    punpckhbw   mm0, [r0+r3*0-8]
+    movq        mm1, [r4+r3*1-8]
+    punpckhbw   mm1, [r0+r3*2-8]
+    mov          r4, r0
+    punpckhwd   mm1, mm0
+    lea          r0, [r0+r3*4]
+    movq        mm2, [r0+r3*1-8]
+    punpckhbw   mm2, [r0+r3*0-8]
+    lea          r0, [r0+r3*2]
+    movq        mm3, [r0+r3*1-8]
+    punpckhbw   mm3, [r0+r3*0-8]
+    punpckhwd   mm3, mm2
+    punpckhdq   mm3, mm1
+    lea          r0, [r0+r3*2]
+    movq        mm0, [r0+r3*0-8]
+    movq        mm1, [r4]
+    mov          r0, r4
+    movq        mm4, mm3
+    movq        mm2, mm3
+    PALIGNR     mm4, mm0, 7, mm0
+    PALIGNR     mm1, mm2, 1, mm2
+    test        r1, r1
+    jz .fix_lt_1
+    jmp .do_left
+.fix_lt_1:
+    movq        mm5, mm3
+    pxor        mm5, mm4
+    psrlq       mm5, 56
+    psllq       mm5, 48
+    pxor        mm1, mm5
+    jmp .do_left
+.fix_lt_2:
+    movq        mm5, mm3
+    pxor        mm5, mm2
+    psllq       mm5, 56
+    psrlq       mm5, 56
+    pxor        mm2, mm5
+    test         r2, r2
+    jnz .do_top
+.fix_tr_1:
+    movq        mm5, mm3
+    pxor        mm5, mm1
+    psrlq       mm5, 56
+    psllq       mm5, 56
+    pxor        mm1, mm5
+    jmp .do_top
+.do_left:
+    movq        mm0, mm4
+    PRED4x4_LOWPASS mm2, mm1, mm4, mm3, mm5
+    movq        mm7, mm2
+    movq        mm0, [r0-8]
+    movq        mm3, [r0]
+    movq        mm1, [r0+8]
+    movq        mm2, mm3
+    movq        mm4, mm3
+    PALIGNR     mm2, mm0, 7, mm0
+    PALIGNR     mm1, mm4, 1, mm4
+    test         r1, r1
+    jz .fix_lt_2
+    test         r2, r2
+    jz .fix_tr_1
+.do_top
+    PRED4x4_LOWPASS mm6, mm2, mm1, mm3, mm5
+    lea         r1, [r0+r3*2]
+    movq       mm2, mm6
+    movq       mm3, mm6
+    PALIGNR    mm3, mm7, 7, mm0
+    PALIGNR    mm6, mm7, 6, mm1
+    movq       mm4, mm3
+    pavgb      mm3, mm2
+    lea         r2, [r1+r3*2]
+    PRED4x4_LOWPASS mm0, mm6, mm2, mm4, mm5
+    movq [r0+r3*1], mm3
+    movq [r0+r3*2], mm0
+    movq       mm5, mm0
+    movq       mm6, mm3
+    movq       mm1, mm7
+    movq       mm2, mm1
+    psllq      mm2, 8
+    movq       mm3, mm1
+    psllq      mm3, 16
+    lea         r4, [r2+r3*2]
+    PRED4x4_LOWPASS mm0, mm1, mm3, mm2, mm4
+    PALIGNR    mm6, mm0, 7, mm2
+    movq [r1+r3*1], mm6
+    psllq      mm0, 8
+    PALIGNR    mm5, mm0, 7, mm1
+    movq [r1+r3*2], mm5
+    psllq      mm0, 8
+    PALIGNR    mm6, mm0, 7, mm2
+    movq [r2+r3*1], mm6
+    psllq      mm0, 8
+    PALIGNR    mm5, mm0, 7, mm1
+    movq [r2+r3*2], mm5
+    psllq      mm0, 8
+    PALIGNR    mm6, mm0, 7, mm2
+    movq [r4+r3*1], mm6
+    psllq      mm0, 8
+    PALIGNR    mm5, mm0, 7, mm1
+    movq [r4+r3*2], mm5
+    RET
+
+%macro PRED8x8L_VERTICAL_RIGHT 1
+cglobal pred8x8l_vertical_right_%1, 4,5,7
+    sub          r0, r3
+    lea          r4, [r0+r3*2]
+    movq        mm0, [r0+r3*1-8]
+    punpckhbw   mm0, [r0+r3*0-8]
+    movq        mm1, [r4+r3*1-8]
+    punpckhbw   mm1, [r0+r3*2-8]
+    mov          r4, r0
+    punpckhwd   mm1, mm0
+    lea          r0, [r0+r3*4]
+    movq        mm2, [r0+r3*1-8]
+    punpckhbw   mm2, [r0+r3*0-8]
+    lea          r0, [r0+r3*2]
+    movq        mm3, [r0+r3*1-8]
+    punpckhbw   mm3, [r0+r3*0-8]
+    punpckhwd   mm3, mm2
+    punpckhdq   mm3, mm1
+    lea          r0, [r0+r3*2]
+    movq        mm0, [r0+r3*0-8]
+    movq        mm1, [r4]
+    mov          r0, r4
+    movq        mm4, mm3
+    movq        mm2, mm3
+    PALIGNR     mm4, mm0, 7, mm0
+    PALIGNR     mm1, mm2, 1, mm2
+    test        r1, r1
+    jnz .do_left
+.fix_lt_1:
+    movq        mm5, mm3
+    pxor        mm5, mm4
+    psrlq       mm5, 56
+    psllq       mm5, 48
+    pxor        mm1, mm5
+    jmp .do_left
+.fix_lt_2:
+    movq        mm5, mm3
+    pxor        mm5, mm2
+    psllq       mm5, 56
+    psrlq       mm5, 56
+    pxor        mm2, mm5
+    test         r2, r2
+    jnz .do_top
+.fix_tr_1:
+    movq        mm5, mm3
+    pxor        mm5, mm1
+    psrlq       mm5, 56
+    psllq       mm5, 56
+    pxor        mm1, mm5
+    jmp .do_top
+.do_left:
+    movq        mm0, mm4
+    PRED4x4_LOWPASS mm2, mm1, mm4, mm3, mm5
+    movq2dq    xmm0, mm2
+    movq        mm0, [r0-8]
+    movq        mm3, [r0]
+    movq        mm1, [r0+8]
+    movq        mm2, mm3
+    movq        mm4, mm3
+    PALIGNR     mm2, mm0, 7, mm0
+    PALIGNR     mm1, mm4, 1, mm4
+    test         r1, r1
+    jz .fix_lt_2
+    test         r2, r2
+    jz .fix_tr_1
+.do_top
+    PRED4x4_LOWPASS mm6, mm2, mm1, mm3, mm5
+    lea           r1, [r0+r3*2]
+    movq2dq     xmm4, mm6
+    pslldq      xmm4, 8
+    por         xmm0, xmm4
+    movdqa      xmm6, [pw_ff00]
+    movdqa      xmm1, xmm0
+    lea           r2, [r1+r3*2]
+    movdqa      xmm2, xmm0
+    movdqa      xmm3, xmm0
+    pslldq      xmm0, 1
+    pslldq      xmm1, 2
+    pavgb       xmm2, xmm0
+INIT_XMM
+    PRED4x4_LOWPASS xmm4, xmm3, xmm1, xmm0, xmm5
+    pandn       xmm6, xmm4
+    movdqa      xmm5, xmm4
+    psrlw       xmm4, 8
+    packuswb    xmm6, xmm4
+    movhlps     xmm4, xmm6
+    movhps [r0+r3*2], xmm5
+    movhps [r0+r3*1], xmm2
+    psrldq      xmm5, 4
+    movss       xmm5, xmm6
+    psrldq      xmm2, 4
+    movss       xmm2, xmm4
+    lea           r0, [r2+r3*2]
+    psrldq      xmm5, 1
+    psrldq      xmm2, 1
+    movq        [r0+r3*2], xmm5
+    movq        [r0+r3*1], xmm2
+    psrldq      xmm5, 1
+    psrldq      xmm2, 1
+    movq        [r2+r3*2], xmm5
+    movq        [r2+r3*1], xmm2
+    psrldq      xmm5, 1
+    psrldq      xmm2, 1
+    movq        [r1+r3*2], xmm5
+    movq        [r1+r3*1], xmm2
+    RET
+%endmacro
+
+INIT_MMX
+%define PALIGNR PALIGNR_MMX
+PRED8x8L_VERTICAL_RIGHT sse2
+INIT_MMX
+%define PALIGNR PALIGNR_SSSE3
+PRED8x8L_VERTICAL_RIGHT ssse3
+
+;-----------------------------------------------------------------------------
+;void pred8x8l_vertical_left(uint8_t *src, int has_topleft, int has_topright, int stride)
+;-----------------------------------------------------------------------------
+
+%macro PRED8x8L_VERTICAL_LEFT 1
+cglobal pred8x8l_vertical_left_%1, 4,4
+    sub          r0, r3
+    movq        mm0, [r0-8]
+    movq        mm3, [r0]
+    movq        mm1, [r0+8]
+    movq        mm2, mm3
+    movq        mm4, mm3
+    PALIGNR     mm2, mm0, 7, mm0
+    PALIGNR     mm1, mm4, 1, mm4
+    test         r1, r1
+    jz .fix_lt_2
+    test         r2, r2
+    jz .fix_tr_1
+    jmp .do_top
+.fix_lt_2:
+    movq        mm5, mm3
+    pxor        mm5, mm2
+    psllq       mm5, 56
+    psrlq       mm5, 56
+    pxor        mm2, mm5
+    test         r2, r2
+    jnz .do_top
+.fix_tr_1:
+    movq        mm5, mm3
+    pxor        mm5, mm1
+    psrlq       mm5, 56
+    psllq       mm5, 56
+    pxor        mm1, mm5
+    jmp .do_top
+.fix_tr_2:
+    punpckhbw   mm3, mm3
+    pshufw      mm1, mm3, 0xFF
+    jmp .do_topright
+.do_top:
+    PRED4x4_LOWPASS mm4, mm2, mm1, mm3, mm5
+    movq2dq    xmm4, mm4
+    test         r2, r2
+    jz .fix_tr_2
+    movq        mm0, [r0+8]
+    movq        mm5, mm0
+    movq        mm2, mm0
+    movq        mm4, mm0
+    psrlq       mm5, 56
+    PALIGNR     mm2, mm3, 7, mm3
+    PALIGNR     mm5, mm4, 1, mm4
+    PRED4x4_LOWPASS mm1, mm2, mm5, mm0, mm4
+.do_topright:
+    movq2dq   xmm3, mm1
+    lea         r1, [r0+r3*2]
+    pslldq    xmm3, 8
+    por       xmm4, xmm3
+    movdqa    xmm2, xmm4
+    movdqa    xmm1, xmm4
+    movdqa    xmm3, xmm4
+    psrldq    xmm2, 1
+    pslldq    xmm1, 1
+    pavgb     xmm3, xmm2
+    lea         r2, [r1+r3*2]
+INIT_XMM
+    PRED4x4_LOWPASS xmm0, xmm1, xmm2, xmm4, xmm5
+    psrldq    xmm0, 1
+    movq [r0+r3*1], xmm3
+    movq [r0+r3*2], xmm0
+    lea         r0, [r2+r3*2]
+    psrldq    xmm3, 1
+    psrldq    xmm0, 1
+    movq [r1+r3*1], xmm3
+    movq [r1+r3*2], xmm0
+    psrldq    xmm3, 1
+    psrldq    xmm0, 1
+    movq [r2+r3*1], xmm3
+    movq [r2+r3*2], xmm0
+    psrldq    xmm3, 1
+    psrldq    xmm0, 1
+    movq [r0+r3*1], xmm3
+    movq [r0+r3*2], xmm0
+    RET
+%endmacro
+
+INIT_MMX
+%define PALIGNR PALIGNR_MMX
+PRED8x8L_VERTICAL_LEFT sse2
+%define PALIGNR PALIGNR_SSSE3
+INIT_MMX
+PRED8x8L_VERTICAL_LEFT ssse3
+
+;-----------------------------------------------------------------------------
+; void pred8x8l_horizontal_up(uint8_t *src, int has_topleft, int has_topright, int stride)
+;-----------------------------------------------------------------------------
+
+%macro PRED8x8L_HORIZONTAL_UP 1
+cglobal pred8x8l_horizontal_up_%1, 4,4
+    sub          r0, r3
+    lea          r2, [r0+r3*2]
+    movq        mm0, [r0+r3*1-8]
+    test         r1, r1
+    lea          r1, [r0+r3]
+    cmovnz       r1, r0
+    punpckhbw   mm0, [r1+r3*0-8]
+    movq        mm1, [r2+r3*1-8]
+    punpckhbw   mm1, [r0+r3*2-8]
+    mov          r2, r0
+    punpckhwd   mm1, mm0
+    lea          r0, [r0+r3*4]
+    movq        mm2, [r0+r3*1-8]
+    punpckhbw   mm2, [r0+r3*0-8]
+    lea          r0, [r0+r3*2]
+    movq        mm3, [r0+r3*1-8]
+    punpckhbw   mm3, [r0+r3*0-8]
+    punpckhwd   mm3, mm2
+    punpckhdq   mm3, mm1
+    lea          r0, [r0+r3*2]
+    movq        mm0, [r0+r3*0-8]
+    movq        mm1, [r1+r3*0-8]
+    mov          r0, r2
+    movq        mm4, mm3
+    movq        mm2, mm3
+    PALIGNR     mm4, mm0, 7, mm0
+    PALIGNR     mm1, mm2, 1, mm2
+    movq       mm0, mm4
+    PRED4x4_LOWPASS mm2, mm1, mm4, mm3, mm5
+    movq       mm4, mm0
+    movq       mm7, mm2
+    PRED4x4_LOWPASS mm1, mm3, mm0, mm4, mm5
+    psllq      mm1, 56
+    PALIGNR    mm7, mm1, 7, mm3
+    lea         r1, [r0+r3*2]
+    pshufw     mm0, mm7, 00011011b ; l6 l7 l4 l5 l2 l3 l0 l1
+    psllq      mm7, 56             ; l7 .. .. .. .. .. .. ..
+    movq       mm2, mm0
+    psllw      mm0, 8
+    psrlw      mm2, 8
+    por        mm2, mm0            ; l7 l6 l5 l4 l3 l2 l1 l0
+    movq       mm3, mm2
+    movq       mm4, mm2
+    movq       mm5, mm2
+    psrlq      mm2, 8
+    psrlq      mm3, 16
+    lea         r2, [r1+r3*2]
+    por        mm2, mm7            ; l7 l7 l6 l5 l4 l3 l2 l1
+    punpckhbw  mm7, mm7
+    por        mm3, mm7            ; l7 l7 l7 l6 l5 l4 l3 l2
+    pavgb      mm4, mm2
+    PRED4x4_LOWPASS mm1, mm3, mm5, mm2, mm6
+    movq       mm5, mm4
+    punpcklbw  mm4, mm1            ; p4 p3 p2 p1
+    punpckhbw  mm5, mm1            ; p8 p7 p6 p5
+    movq       mm6, mm5
+    movq       mm7, mm5
+    movq       mm0, mm5
+    PALIGNR    mm5, mm4, 2, mm1
+    pshufw     mm1, mm6, 11111001b
+    PALIGNR    mm6, mm4, 4, mm2
+    pshufw     mm2, mm7, 11111110b
+    PALIGNR    mm7, mm4, 6, mm3
+    pshufw     mm3, mm0, 11111111b
+    movq [r0+r3*1], mm4
+    movq [r0+r3*2], mm5
+    lea         r0, [r2+r3*2]
+    movq [r1+r3*1], mm6
+    movq [r1+r3*2], mm7
+    movq [r2+r3*1], mm0
+    movq [r2+r3*2], mm1
+    movq [r0+r3*1], mm2
+    movq [r0+r3*2], mm3
+    RET
+%endmacro
+
+INIT_MMX
+%define PALIGNR PALIGNR_MMX
+PRED8x8L_HORIZONTAL_UP mmxext
+%define PALIGNR PALIGNR_SSSE3
+PRED8x8L_HORIZONTAL_UP ssse3
+
+;-----------------------------------------------------------------------------
+;void pred8x8l_horizontal_down(uint8_t *src, int has_topleft, int has_topright, int stride)
+;-----------------------------------------------------------------------------
+
+INIT_MMX
+%define PALIGNR PALIGNR_MMX
+cglobal pred8x8l_horizontal_down_mmxext, 4,5
+    sub          r0, r3
+    lea          r4, [r0+r3*2]
+    movq        mm0, [r0+r3*1-8]
+    punpckhbw   mm0, [r0+r3*0-8]
+    movq        mm1, [r4+r3*1-8]
+    punpckhbw   mm1, [r0+r3*2-8]
+    mov          r4, r0
+    punpckhwd   mm1, mm0
+    lea          r0, [r0+r3*4]
+    movq        mm2, [r0+r3*1-8]
+    punpckhbw   mm2, [r0+r3*0-8]
+    lea          r0, [r0+r3*2]
+    movq        mm3, [r0+r3*1-8]
+    punpckhbw   mm3, [r0+r3*0-8]
+    punpckhwd   mm3, mm2
+    punpckhdq   mm3, mm1
+    lea          r0, [r0+r3*2]
+    movq        mm0, [r0+r3*0-8]
+    movq        mm1, [r4]
+    mov          r0, r4
+    movq        mm4, mm3
+    movq        mm2, mm3
+    PALIGNR     mm4, mm0, 7, mm0
+    PALIGNR     mm1, mm2, 1, mm2
+    test        r1, r1
+    jnz .do_left
+.fix_lt_1:
+    movq        mm5, mm3
+    pxor        mm5, mm4
+    psrlq       mm5, 56
+    psllq       mm5, 48
+    pxor        mm1, mm5
+    jmp .do_left
+.fix_lt_2:
+    movq        mm5, mm3
+    pxor        mm5, mm2
+    psllq       mm5, 56
+    psrlq       mm5, 56
+    pxor        mm2, mm5
+    test         r2, r2
+    jnz .do_top
+.fix_tr_1:
+    movq        mm5, mm3
+    pxor        mm5, mm1
+    psrlq       mm5, 56
+    psllq       mm5, 56
+    pxor        mm1, mm5
+    jmp .do_top
+.do_left:
+    movq        mm0, mm4
+    PRED4x4_LOWPASS mm2, mm1, mm4, mm3, mm5
+    movq        mm4, mm0
+    movq        mm7, mm2
+    movq        mm6, mm2
+    PRED4x4_LOWPASS mm1, mm3, mm0, mm4, mm5
+    psllq       mm1, 56
+    PALIGNR     mm7, mm1, 7, mm3
+    movq        mm0, [r0-8]
+    movq        mm3, [r0]
+    movq        mm1, [r0+8]
+    movq        mm2, mm3
+    movq        mm4, mm3
+    PALIGNR     mm2, mm0, 7, mm0
+    PALIGNR     mm1, mm4, 1, mm4
+    test         r1, r1
+    jz .fix_lt_2
+    test         r2, r2
+    jz .fix_tr_1
+.do_top:
+    PRED4x4_LOWPASS mm4, mm2, mm1, mm3, mm5
+    movq       mm5, mm4
+    lea         r1, [r0+r3*2]
+    psllq      mm7, 56
+    movq       mm2, mm5
+    movq       mm3, mm6
+    movq       mm4, mm2
+    PALIGNR    mm2, mm6, 7, mm5
+    PALIGNR    mm6, mm7, 7, mm0
+    lea         r2, [r1+r3*2]
+    PALIGNR    mm4, mm3, 1, mm7
+    movq       mm5, mm3
+    pavgb      mm3, mm6
+    PRED4x4_LOWPASS mm0, mm4, mm6, mm5, mm7
+    movq       mm4, mm2
+    movq       mm1, mm2
+    lea         r4, [r2+r3*2]
+    psrlq      mm4, 16
+    psrlq      mm1, 8
+    PRED4x4_LOWPASS mm6, mm4, mm2, mm1, mm5
+    movq       mm7, mm3
+    punpcklbw  mm3, mm0
+    punpckhbw  mm7, mm0
+    movq       mm1, mm7
+    movq       mm0, mm7
+    movq       mm4, mm7
+    movq [r4+r3*2], mm3
+    PALIGNR    mm7, mm3, 2, mm5
+    movq [r4+r3*1], mm7
+    PALIGNR    mm1, mm3, 4, mm5
+    movq [r2+r3*2], mm1
+    PALIGNR    mm0, mm3, 6, mm3
+    movq [r2+r3*1], mm0
+    movq       mm2, mm6
+    movq       mm3, mm6
+    movq [r1+r3*2], mm4
+    PALIGNR    mm6, mm4, 2, mm5
+    movq [r1+r3*1], mm6
+    PALIGNR    mm2, mm4, 4, mm5
+    movq [r0+r3*2], mm2
+    PALIGNR    mm3, mm4, 6, mm4
+    movq [r0+r3*1], mm3
+    RET
+
+%macro PRED8x8L_HORIZONTAL_DOWN 1
+cglobal pred8x8l_horizontal_down_%1, 4,5
+    sub          r0, r3
+    lea          r4, [r0+r3*2]
+    movq        mm0, [r0+r3*1-8]
+    punpckhbw   mm0, [r0+r3*0-8]
+    movq        mm1, [r4+r3*1-8]
+    punpckhbw   mm1, [r0+r3*2-8]
+    mov          r4, r0
+    punpckhwd   mm1, mm0
+    lea          r0, [r0+r3*4]
+    movq        mm2, [r0+r3*1-8]
+    punpckhbw   mm2, [r0+r3*0-8]
+    lea          r0, [r0+r3*2]
+    movq        mm3, [r0+r3*1-8]
+    punpckhbw   mm3, [r0+r3*0-8]
+    punpckhwd   mm3, mm2
+    punpckhdq   mm3, mm1
+    lea          r0, [r0+r3*2]
+    movq        mm0, [r0+r3*0-8]
+    movq        mm1, [r4]
+    mov          r0, r4
+    movq        mm4, mm3
+    movq        mm2, mm3
+    PALIGNR     mm4, mm0, 7, mm0
+    PALIGNR     mm1, mm2, 1, mm2
+    test        r1, r1
+    jnz .do_left
+.fix_lt_1:
+    movq        mm5, mm3
+    pxor        mm5, mm4
+    psrlq       mm5, 56
+    psllq       mm5, 48
+    pxor        mm1, mm5
+    jmp .do_left
+.fix_lt_2:
+    movq        mm5, mm3
+    pxor        mm5, mm2
+    psllq       mm5, 56
+    psrlq       mm5, 56
+    pxor        mm2, mm5
+    test         r2, r2
+    jnz .do_top
+.fix_tr_1:
+    movq        mm5, mm3
+    pxor        mm5, mm1
+    psrlq       mm5, 56
+    psllq       mm5, 56
+    pxor        mm1, mm5
+    jmp .do_top
+.fix_tr_2:
+    punpckhbw   mm3, mm3
+    pshufw      mm1, mm3, 0xFF
+    jmp .do_topright
+.do_left:
+    movq        mm0, mm4
+    PRED4x4_LOWPASS mm2, mm1, mm4, mm3, mm5
+    movq2dq    xmm0, mm2
+    pslldq     xmm0, 8
+    movq        mm4, mm0
+    PRED4x4_LOWPASS mm1, mm3, mm0, mm4, mm5
+    movq2dq    xmm2, mm1
+    pslldq     xmm2, 15
+    psrldq     xmm2, 8
+    por        xmm0, xmm2
+    movq        mm0, [r0-8]
+    movq        mm3, [r0]
+    movq        mm1, [r0+8]
+    movq        mm2, mm3
+    movq        mm4, mm3
+    PALIGNR     mm2, mm0, 7, mm0
+    PALIGNR     mm1, mm4, 1, mm4
+    test         r1, r1
+    jz .fix_lt_2
+    test         r2, r2
+    jz .fix_tr_1
+.do_top:
+    PRED4x4_LOWPASS mm4, mm2, mm1, mm3, mm5
+    movq2dq    xmm1, mm4
+    test         r2, r2
+    jz .fix_tr_2
+    movq        mm0, [r0+8]
+    movq        mm5, mm0
+    movq        mm2, mm0
+    movq        mm4, mm0
+    psrlq       mm5, 56
+    PALIGNR     mm2, mm3, 7, mm3
+    PALIGNR     mm5, mm4, 1, mm4
+    PRED4x4_LOWPASS mm1, mm2, mm5, mm0, mm4
+.do_topright:
+    movq2dq    xmm5, mm1
+    pslldq     xmm5, 8
+    por        xmm1, xmm5
+INIT_XMM
+    lea         r2, [r4+r3*2]
+    movdqa    xmm2, xmm1
+    movdqa    xmm3, xmm1
+    PALIGNR   xmm1, xmm0, 7, xmm4
+    PALIGNR   xmm2, xmm0, 9, xmm5
+    lea         r1, [r2+r3*2]
+    PALIGNR   xmm3, xmm0, 8, xmm0
+    movdqa    xmm4, xmm1
+    pavgb     xmm4, xmm3
+    lea         r0, [r1+r3*2]
+    PRED4x4_LOWPASS xmm0, xmm1, xmm2, xmm3, xmm5
+    punpcklbw xmm4, xmm0
+    movhlps   xmm0, xmm4
+    movq   [r0+r3*2], xmm4
+    movq   [r2+r3*2], xmm0
+    psrldq xmm4, 2
+    psrldq xmm0, 2
+    movq   [r0+r3*1], xmm4
+    movq   [r2+r3*1], xmm0
+    psrldq xmm4, 2
+    psrldq xmm0, 2
+    movq   [r1+r3*2], xmm4
+    movq   [r4+r3*2], xmm0
+    psrldq xmm4, 2
+    psrldq xmm0, 2
+    movq   [r1+r3*1], xmm4
+    movq   [r4+r3*1], xmm0
+    RET
+%endmacro
+
+INIT_MMX
+%define PALIGNR PALIGNR_MMX
+PRED8x8L_HORIZONTAL_DOWN sse2
+INIT_MMX
+%define PALIGNR PALIGNR_SSSE3
+PRED8x8L_HORIZONTAL_DOWN ssse3
+%endif
+
+;-----------------------------------------------------------------------------
+; void pred4x4_dc_mmxext(uint8_t *src, const uint8_t *topright, int stride)
+;-----------------------------------------------------------------------------
+
+cglobal pred4x4_dc_mmxext, 3,5
+    pxor   mm7, mm7
+    mov     r4, r0
+    sub     r0, r2
+    movd   mm0, [r0]
+    psadbw mm0, mm7
+    movzx  r1d, byte [r0+r2*1-1]
+    movd   r3d, mm0
+    add    r3d, r1d
+    movzx  r1d, byte [r0+r2*2-1]
+    lea     r0, [r0+r2*2]
+    add    r3d, r1d
+    movzx  r1d, byte [r0+r2*1-1]
+    add    r3d, r1d
+    movzx  r1d, byte [r0+r2*2-1]
+    add    r3d, r1d
+    add    r3d, 4
+    shr    r3d, 3
+    imul   r3d, 0x01010101
+    mov   [r4+r2*0], r3d
+    mov   [r0+r2*0], r3d
+    mov   [r0+r2*1], r3d
+    mov   [r0+r2*2], r3d
+    RET
+
+;-----------------------------------------------------------------------------
+; void pred4x4_tm_vp8_mmxext(uint8_t *src, const uint8_t *topright, int stride)
+;-----------------------------------------------------------------------------
+
+%macro PRED4x4_TM_MMX 1
+cglobal pred4x4_tm_vp8_%1, 3,6
+    sub        r0, r2
+    pxor      mm7, mm7
+    movd      mm0, [r0]
+    punpcklbw mm0, mm7
+    movzx     r4d, byte [r0-1]
+    mov       r5d, 2
+.loop:
+    movzx     r1d, byte [r0+r2*1-1]
+    movzx     r3d, byte [r0+r2*2-1]
+    sub       r1d, r4d
+    sub       r3d, r4d
+    movd      mm2, r1d
+    movd      mm4, r3d
+%ifidn %1, mmx
+    punpcklwd mm2, mm2
+    punpcklwd mm4, mm4
+    punpckldq mm2, mm2
+    punpckldq mm4, mm4
+%else
+    pshufw    mm2, mm2, 0
+    pshufw    mm4, mm4, 0
+%endif
+    paddw     mm2, mm0
+    paddw     mm4, mm0
+    packuswb  mm2, mm2
+    packuswb  mm4, mm4
+    movd [r0+r2*1], mm2
+    movd [r0+r2*2], mm4
+    lea        r0, [r0+r2*2]
+    dec       r5d
+    jg .loop
+    REP_RET
+%endmacro
+
+PRED4x4_TM_MMX mmx
+PRED4x4_TM_MMX mmxext
+
+cglobal pred4x4_tm_vp8_ssse3, 3,3
+    sub         r0, r2
+    movq       mm6, [tm_shuf]
+    pxor       mm1, mm1
+    movd       mm0, [r0]
+    punpcklbw  mm0, mm1
+    movd       mm7, [r0-4]
+    pshufb     mm7, mm6
+    lea         r1, [r0+r2*2]
+    movd       mm2, [r0+r2*1-4]
+    movd       mm3, [r0+r2*2-4]
+    movd       mm4, [r1+r2*1-4]
+    movd       mm5, [r1+r2*2-4]
+    pshufb     mm2, mm6
+    pshufb     mm3, mm6
+    pshufb     mm4, mm6
+    pshufb     mm5, mm6
+    psubw      mm2, mm7
+    psubw      mm3, mm7
+    psubw      mm4, mm7
+    psubw      mm5, mm7
+    paddw      mm2, mm0
+    paddw      mm3, mm0
+    paddw      mm4, mm0
+    paddw      mm5, mm0
+    packuswb   mm2, mm2
+    packuswb   mm3, mm3
+    packuswb   mm4, mm4
+    packuswb   mm5, mm5
+    movd [r0+r2*1], mm2
+    movd [r0+r2*2], mm3
+    movd [r1+r2*1], mm4
+    movd [r1+r2*2], mm5
+    RET
+
+;-----------------------------------------------------------------------------
+; void pred4x4_vertical_vp8_mmxext(uint8_t *src, const uint8_t *topright, int stride)
+;-----------------------------------------------------------------------------
+
+INIT_MMX
+cglobal pred4x4_vertical_vp8_mmxext, 3,3
+    sub       r0, r2
+    movd      m1, [r0-1]
+    movd      m0, [r0]
+    mova      m2, m0   ;t0 t1 t2 t3
+    punpckldq m0, [r1] ;t0 t1 t2 t3 t4 t5 t6 t7
+    lea       r1, [r0+r2*2]
+    psrlq     m0, 8    ;t1 t2 t3 t4
+    PRED4x4_LOWPASS m3, m1, m0, m2, m4
+    movd [r0+r2*1], m3
+    movd [r0+r2*2], m3
+    movd [r1+r2*1], m3
+    movd [r1+r2*2], m3
+    RET
+
+;-----------------------------------------------------------------------------
+; void pred4x4_down_left_mmxext(uint8_t *src, const uint8_t *topright, int stride)
+;-----------------------------------------------------------------------------
+%ifdef CONFIG_GPL
+INIT_MMX
+cglobal pred4x4_down_left_mmxext, 3,3
+    sub       r0, r2
+    movq      m1, [r0]
+    punpckldq m1, [r1]
+    movq      m2, m1
+    movq      m3, m1
+    movq      m4, m1
+    psllq     m1, 8
+    pxor      m2, m1
+    psrlq     m2, 8
+    pxor      m3, m2
+    PRED4x4_LOWPASS m0, m1, m3, m4, m5
+    lea       r1, [r0+r2*2]
+    psrlq     m0, 8
+    movd      [r0+r2*1], m0
+    psrlq     m0, 8
+    movd      [r0+r2*2], m0
+    psrlq     m0, 8
+    movd      [r1+r2*1], m0
+    psrlq     m0, 8
+    movd      [r1+r2*2], m0
+    RET
+
+;-----------------------------------------------------------------------------
+; void pred4x4_vertical_left_mmxext(uint8_t *src, const uint8_t *topright, int stride)
+;-----------------------------------------------------------------------------
+
+INIT_MMX
+cglobal pred4x4_vertical_left_mmxext, 3,3
+    sub       r0, r2
+    movq      m1, [r0]
+    punpckldq m1, [r1]
+    movq      m3, m1
+    movq      m2, m1
+    psrlq     m3, 8
+    psrlq     m2, 16
+    movq      m4, m3
+    pavgb     m4, m1
+    PRED4x4_LOWPASS m0, m1, m2, m3, m5
+    lea       r1, [r0+r2*2]
+    movh      [r0+r2*1], m4
+    movh      [r0+r2*2], m0
+    psrlq     m4, 8
+    psrlq     m0, 8
+    movh      [r1+r2*1], m4
+    movh      [r1+r2*2], m0
+    RET
+
+;-----------------------------------------------------------------------------
+; void pred4x4_horizontal_up_mmxext(uint8_t *src, const uint8_t *topright, int stride)
+;-----------------------------------------------------------------------------
+
+INIT_MMX
+cglobal pred4x4_horizontal_up_mmxext, 3,3
+    sub       r0, r2
+    lea       r1, [r0+r2*2]
+    movd      m0, [r0+r2*1-4]
+    punpcklbw m0, [r0+r2*2-4]
+    movd      m1, [r1+r2*1-4]
+    punpcklbw m1, [r1+r2*2-4]
+    punpckhwd m0, m1
+    movq      m1, m0
+    punpckhbw m1, m1
+    pshufw    m1, m1, 0xFF
+    punpckhdq m0, m1
+    movq      m2, m0
+    movq      m3, m0
+    movq      m7, m0
+    psrlq     m2, 16
+    psrlq     m3, 8
+    pavgb     m7, m3
+    PRED4x4_LOWPASS m4, m0, m2, m3, m5
+    punpcklbw m7, m4
+    movd    [r0+r2*1], m7
+    psrlq    m7, 16
+    movd    [r0+r2*2], m7
+    psrlq    m7, 16
+    movd    [r1+r2*1], m7
+    movd    [r1+r2*2], m1
+    RET
+
+;-----------------------------------------------------------------------------
+; void pred4x4_horizontal_down_mmxext(uint8_t *src, const uint8_t *topright, int stride)
+;-----------------------------------------------------------------------------
+
+INIT_MMX
+%define PALIGNR PALIGNR_MMX
+cglobal pred4x4_horizontal_down_mmxext, 3,3
+    sub       r0, r2
+    lea       r1, [r0+r2*2]
+    movh      m0, [r0-4]      ; lt ..
+    punpckldq m0, [r0]        ; t3 t2 t1 t0 lt .. .. ..
+    psllq     m0, 8           ; t2 t1 t0 lt .. .. .. ..
+    movd      m1, [r1+r2*2-4] ; l3
+    punpcklbw m1, [r1+r2*1-4] ; l2 l3
+    movd      m2, [r0+r2*2-4] ; l1
+    punpcklbw m2, [r0+r2*1-4] ; l0 l1
+    punpckhwd m1, m2          ; l0 l1 l2 l3
+    punpckhdq m1, m0          ; t2 t1 t0 lt l0 l1 l2 l3
+    movq      m0, m1
+    movq      m2, m1
+    movq      m5, m1
+    psrlq     m0, 16          ; .. .. t2 t1 t0 lt l0 l1
+    psrlq     m2, 8           ; .. t2 t1 t0 lt l0 l1 l2
+    pavgb     m5, m2
+    PRED4x4_LOWPASS m3, m1, m0, m2, m4
+    punpcklbw m5, m3
+    psrlq     m3, 32
+    PALIGNR   m3, m5, 6, m4
+    movh      [r1+r2*2], m5
+    psrlq     m5, 16
+    movh      [r1+r2*1], m5
+    psrlq     m5, 16
+    movh      [r0+r2*2], m5
+    movh      [r0+r2*1], m3
+    RET
+
+;-----------------------------------------------------------------------------
+; void pred4x4_vertical_right_mmxext(uint8_t *src, const uint8_t *topright, int stride)
+;-----------------------------------------------------------------------------
+
+INIT_MMX
+%define PALIGNR PALIGNR_MMX
+cglobal pred4x4_vertical_right_mmxext, 3,3
+    sub     r0, r2
+    lea     r1, [r0+r2*2]
+    movh    m0, [r0]                    ; ........t3t2t1t0
+    movq    m5, m0
+    PALIGNR m0, [r0-8], 7, m1           ; ......t3t2t1t0lt
+    pavgb   m5, m0
+    PALIGNR m0, [r0+r2*1-8], 7, m1      ; ....t3t2t1t0ltl0
+    movq    m1, m0
+    PALIGNR m0, [r0+r2*2-8], 7, m2      ; ..t3t2t1t0ltl0l1
+    movq    m2, m0
+    PALIGNR m0, [r1+r2*1-8], 7, m3      ; t3t2t1t0ltl0l1l2
+    PRED4x4_LOWPASS m3, m1, m0, m2, m4
+    movq    m1, m3
+    psrlq   m3, 16
+    psllq   m1, 48
+    movh    [r0+r2*1], m5
+    movh    [r0+r2*2], m3
+    PALIGNR m5, m1, 7, m2
+    psllq   m1, 8
+    movh    [r1+r2*1], m5
+    PALIGNR m3, m1, 7, m1
+    movh    [r1+r2*2], m3
+    RET
+
+;-----------------------------------------------------------------------------
+; void pred4x4_down_right_mmxext(uint8_t *src, const uint8_t *topright, int stride)
+;-----------------------------------------------------------------------------
+
+INIT_MMX
+%define PALIGNR PALIGNR_MMX
+cglobal pred4x4_down_right_mmxext, 3,3
+    sub       r0, r2
+    lea       r1, [r0+r2*2]
+    movq      m1, [r1-8]
+    movq      m2, [r0+r2*1-8]
+    punpckhbw m2, [r0-8]
+    movh      m3, [r0]
+    punpckhwd m1, m2
+    PALIGNR   m3, m1, 5, m1
+    movq      m1, m3
+    PALIGNR   m3, [r1+r2*1-8], 7, m4
+    movq      m2, m3
+    PALIGNR   m3, [r1+r2*2-8], 7, m4
+    PRED4x4_LOWPASS m0, m3, m1, m2, m4
+    movh      [r1+r2*2], m0
+    psrlq     m0, 8
+    movh      [r1+r2*1], m0
+    psrlq     m0, 8
+    movh      [r0+r2*2], m0
+    psrlq     m0, 8
+    movh      [r0+r2*1], m0
+    RET
+%endif
diff --git a/libavcodec/x86/h264_intrapred_init.c b/libavcodec/x86/h264_intrapred_init.c
new file mode 100644
index 0000000..4142cc1
--- /dev/null
+++ b/libavcodec/x86/h264_intrapred_init.c
@@ -0,0 +1,233 @@
+/*
+ * Copyright (c) 2010 Jason Garrett-Glaser
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "libavutil/cpu.h"
+#include "libavcodec/h264pred.h"
+
+void ff_pred16x16_vertical_mmx     (uint8_t *src, int stride);
+void ff_pred16x16_vertical_sse     (uint8_t *src, int stride);
+void ff_pred16x16_horizontal_mmx   (uint8_t *src, int stride);
+void ff_pred16x16_horizontal_mmxext(uint8_t *src, int stride);
+void ff_pred16x16_horizontal_ssse3 (uint8_t *src, int stride);
+void ff_pred16x16_dc_mmxext        (uint8_t *src, int stride);
+void ff_pred16x16_dc_sse2          (uint8_t *src, int stride);
+void ff_pred16x16_dc_ssse3         (uint8_t *src, int stride);
+void ff_pred16x16_plane_h264_mmx   (uint8_t *src, int stride);
+void ff_pred16x16_plane_h264_mmx2  (uint8_t *src, int stride);
+void ff_pred16x16_plane_h264_sse2  (uint8_t *src, int stride);
+void ff_pred16x16_plane_h264_ssse3 (uint8_t *src, int stride);
+void ff_pred16x16_plane_rv40_mmx   (uint8_t *src, int stride);
+void ff_pred16x16_plane_rv40_mmx2  (uint8_t *src, int stride);
+void ff_pred16x16_plane_rv40_sse2  (uint8_t *src, int stride);
+void ff_pred16x16_plane_rv40_ssse3 (uint8_t *src, int stride);
+void ff_pred16x16_plane_svq3_mmx   (uint8_t *src, int stride);
+void ff_pred16x16_plane_svq3_mmx2  (uint8_t *src, int stride);
+void ff_pred16x16_plane_svq3_sse2  (uint8_t *src, int stride);
+void ff_pred16x16_plane_svq3_ssse3 (uint8_t *src, int stride);
+void ff_pred16x16_tm_vp8_mmx       (uint8_t *src, int stride);
+void ff_pred16x16_tm_vp8_mmxext    (uint8_t *src, int stride);
+void ff_pred16x16_tm_vp8_sse2      (uint8_t *src, int stride);
+void ff_pred8x8_top_dc_mmxext      (uint8_t *src, int stride);
+void ff_pred8x8_dc_rv40_mmxext     (uint8_t *src, int stride);
+void ff_pred8x8_dc_mmxext          (uint8_t *src, int stride);
+void ff_pred8x8_vertical_mmx       (uint8_t *src, int stride);
+void ff_pred8x8_horizontal_mmx     (uint8_t *src, int stride);
+void ff_pred8x8_horizontal_mmxext  (uint8_t *src, int stride);
+void ff_pred8x8_horizontal_ssse3   (uint8_t *src, int stride);
+void ff_pred8x8_plane_mmx          (uint8_t *src, int stride);
+void ff_pred8x8_plane_mmx2         (uint8_t *src, int stride);
+void ff_pred8x8_plane_sse2         (uint8_t *src, int stride);
+void ff_pred8x8_plane_ssse3        (uint8_t *src, int stride);
+void ff_pred8x8_tm_vp8_mmx         (uint8_t *src, int stride);
+void ff_pred8x8_tm_vp8_mmxext      (uint8_t *src, int stride);
+void ff_pred8x8_tm_vp8_sse2        (uint8_t *src, int stride);
+void ff_pred8x8_tm_vp8_ssse3       (uint8_t *src, int stride);
+void ff_pred8x8l_top_dc_mmxext     (uint8_t *src, int has_topleft, int has_topright, int stride);
+void ff_pred8x8l_top_dc_ssse3      (uint8_t *src, int has_topleft, int has_topright, int stride);
+void ff_pred8x8l_dc_mmxext         (uint8_t *src, int has_topleft, int has_topright, int stride);
+void ff_pred8x8l_dc_ssse3          (uint8_t *src, int has_topleft, int has_topright, int stride);
+void ff_pred8x8l_horizontal_mmxext (uint8_t *src, int has_topleft, int has_topright, int stride);
+void ff_pred8x8l_horizontal_ssse3  (uint8_t *src, int has_topleft, int has_topright, int stride);
+void ff_pred8x8l_vertical_mmxext   (uint8_t *src, int has_topleft, int has_topright, int stride);
+void ff_pred8x8l_vertical_ssse3    (uint8_t *src, int has_topleft, int has_topright, int stride);
+void ff_pred8x8l_down_left_mmxext  (uint8_t *src, int has_topleft, int has_topright, int stride);
+void ff_pred8x8l_down_left_sse2    (uint8_t *src, int has_topleft, int has_topright, int stride);
+void ff_pred8x8l_down_left_ssse3   (uint8_t *src, int has_topleft, int has_topright, int stride);
+void ff_pred8x8l_down_right_mmxext (uint8_t *src, int has_topleft, int has_topright, int stride);
+void ff_pred8x8l_down_right_sse2   (uint8_t *src, int has_topleft, int has_topright, int stride);
+void ff_pred8x8l_down_right_ssse3  (uint8_t *src, int has_topleft, int has_topright, int stride);
+void ff_pred8x8l_vertical_right_mmxext(uint8_t *src, int has_topleft, int has_topright, int stride);
+void ff_pred8x8l_vertical_right_sse2(uint8_t *src, int has_topleft, int has_topright, int stride);
+void ff_pred8x8l_vertical_right_ssse3(uint8_t *src, int has_topleft, int has_topright, int stride);
+void ff_pred8x8l_vertical_left_sse2(uint8_t *src, int has_topleft, int has_topright, int stride);
+void ff_pred8x8l_vertical_left_ssse3(uint8_t *src, int has_topleft, int has_topright, int stride);
+void ff_pred8x8l_horizontal_up_mmxext(uint8_t *src, int has_topleft, int has_topright, int stride);
+void ff_pred8x8l_horizontal_up_ssse3(uint8_t *src, int has_topleft, int has_topright, int stride);
+void ff_pred8x8l_horizontal_down_mmxext(uint8_t *src, int has_topleft, int has_topright, int stride);
+void ff_pred8x8l_horizontal_down_sse2(uint8_t *src, int has_topleft, int has_topright, int stride);
+void ff_pred8x8l_horizontal_down_ssse3(uint8_t *src, int has_topleft, int has_topright, int stride);
+void ff_pred4x4_dc_mmxext          (uint8_t *src, const uint8_t *topright, int stride);
+void ff_pred4x4_down_left_mmxext   (uint8_t *src, const uint8_t *topright, int stride);
+void ff_pred4x4_down_right_mmxext  (uint8_t *src, const uint8_t *topright, int stride);
+void ff_pred4x4_vertical_left_mmxext(uint8_t *src, const uint8_t *topright, int stride);
+void ff_pred4x4_vertical_right_mmxext(uint8_t *src, const uint8_t *topright, int stride);
+void ff_pred4x4_horizontal_up_mmxext(uint8_t *src, const uint8_t *topright, int stride);
+void ff_pred4x4_horizontal_down_mmxext(uint8_t *src, const uint8_t *topright, int stride);
+void ff_pred4x4_tm_vp8_mmx         (uint8_t *src, const uint8_t *topright, int stride);
+void ff_pred4x4_tm_vp8_mmxext      (uint8_t *src, const uint8_t *topright, int stride);
+void ff_pred4x4_tm_vp8_ssse3       (uint8_t *src, const uint8_t *topright, int stride);
+void ff_pred4x4_vertical_vp8_mmxext(uint8_t *src, const uint8_t *topright, int stride);
+
+void ff_h264_pred_init_x86(H264PredContext *h, int codec_id)
+{
+    int mm_flags = av_get_cpu_flags();
+
+#if HAVE_YASM
+    if (mm_flags & AV_CPU_FLAG_MMX) {
+        h->pred16x16[VERT_PRED8x8] = ff_pred16x16_vertical_mmx;
+        h->pred16x16[HOR_PRED8x8 ] = ff_pred16x16_horizontal_mmx;
+        h->pred8x8  [VERT_PRED8x8] = ff_pred8x8_vertical_mmx;
+        h->pred8x8  [HOR_PRED8x8 ] = ff_pred8x8_horizontal_mmx;
+        if (codec_id == CODEC_ID_VP8) {
+            h->pred16x16[PLANE_PRED8x8] = ff_pred16x16_tm_vp8_mmx;
+            h->pred8x8  [PLANE_PRED8x8] = ff_pred8x8_tm_vp8_mmx;
+            h->pred4x4  [TM_VP8_PRED  ] = ff_pred4x4_tm_vp8_mmx;
+        } else {
+            h->pred8x8  [PLANE_PRED8x8] = ff_pred8x8_plane_mmx;
+            if (codec_id == CODEC_ID_SVQ3) {
+                h->pred16x16[PLANE_PRED8x8] = ff_pred16x16_plane_svq3_mmx;
+            } else if (codec_id == CODEC_ID_RV40) {
+                h->pred16x16[PLANE_PRED8x8] = ff_pred16x16_plane_rv40_mmx;
+            } else {
+                h->pred16x16[PLANE_PRED8x8] = ff_pred16x16_plane_h264_mmx;
+            }
+        }
+    }
+
+    if (mm_flags & AV_CPU_FLAG_MMX2) {
+        h->pred16x16[HOR_PRED8x8 ] = ff_pred16x16_horizontal_mmxext;
+        h->pred16x16[DC_PRED8x8  ] = ff_pred16x16_dc_mmxext;
+        h->pred8x8  [HOR_PRED8x8 ] = ff_pred8x8_horizontal_mmxext;
+#if CONFIG_GPL
+        h->pred8x8l [TOP_DC_PRED ] = ff_pred8x8l_top_dc_mmxext;
+        h->pred8x8l [DC_PRED     ] = ff_pred8x8l_dc_mmxext;
+        h->pred8x8l [HOR_PRED    ] = ff_pred8x8l_horizontal_mmxext;
+        h->pred8x8l [VERT_PRED   ] = ff_pred8x8l_vertical_mmxext;
+        h->pred8x8l [DIAG_DOWN_RIGHT_PRED] = ff_pred8x8l_down_right_mmxext;
+        h->pred8x8l [VERT_RIGHT_PRED     ] = ff_pred8x8l_vertical_right_mmxext;
+        h->pred8x8l [HOR_UP_PRED         ] = ff_pred8x8l_horizontal_up_mmxext;
+        h->pred8x8l [DIAG_DOWN_LEFT_PRED ] = ff_pred8x8l_down_left_mmxext;
+        h->pred8x8l [HOR_DOWN_PRED       ] = ff_pred8x8l_horizontal_down_mmxext;
+        h->pred4x4  [DIAG_DOWN_RIGHT_PRED] = ff_pred4x4_down_right_mmxext;
+        h->pred4x4  [VERT_RIGHT_PRED     ] = ff_pred4x4_vertical_right_mmxext;
+        h->pred4x4  [HOR_DOWN_PRED       ] = ff_pred4x4_horizontal_down_mmxext;
+#endif
+        h->pred4x4  [DC_PRED     ] = ff_pred4x4_dc_mmxext;
+#if CONFIG_GPL
+        if (codec_id == CODEC_ID_VP8 || codec_id == CODEC_ID_H264)
+            h->pred4x4  [DIAG_DOWN_LEFT_PRED ] = ff_pred4x4_down_left_mmxext;
+        if (codec_id == CODEC_ID_SVQ3 || codec_id == CODEC_ID_H264)
+            h->pred4x4  [VERT_LEFT_PRED      ] = ff_pred4x4_vertical_left_mmxext;
+        if (codec_id != CODEC_ID_RV40) {
+            h->pred4x4  [HOR_UP_PRED         ] = ff_pred4x4_horizontal_up_mmxext;
+        }
+        if (codec_id == CODEC_ID_SVQ3 || codec_id == CODEC_ID_H264) {
+            h->pred8x8  [TOP_DC_PRED8x8      ] = ff_pred8x8_top_dc_mmxext;
+            h->pred8x8  [DC_PRED8x8          ] = ff_pred8x8_dc_mmxext;
+        }
+#endif
+        if (codec_id == CODEC_ID_VP8) {
+            h->pred16x16[PLANE_PRED8x8] = ff_pred16x16_tm_vp8_mmxext;
+            h->pred8x8  [DC_PRED8x8   ] = ff_pred8x8_dc_rv40_mmxext;
+            h->pred8x8  [PLANE_PRED8x8] = ff_pred8x8_tm_vp8_mmxext;
+            h->pred4x4  [TM_VP8_PRED  ] = ff_pred4x4_tm_vp8_mmxext;
+            h->pred4x4  [VERT_PRED    ] = ff_pred4x4_vertical_vp8_mmxext;
+        } else {
+            h->pred8x8  [PLANE_PRED8x8] = ff_pred8x8_plane_mmx2;
+            if (codec_id == CODEC_ID_SVQ3) {
+                h->pred16x16[PLANE_PRED8x8] = ff_pred16x16_plane_svq3_mmx2;
+            } else if (codec_id == CODEC_ID_RV40) {
+                h->pred16x16[PLANE_PRED8x8] = ff_pred16x16_plane_rv40_mmx2;
+            } else {
+                h->pred16x16[PLANE_PRED8x8] = ff_pred16x16_plane_h264_mmx2;
+            }
+        }
+    }
+
+    if (mm_flags & AV_CPU_FLAG_SSE) {
+        h->pred16x16[VERT_PRED8x8] = ff_pred16x16_vertical_sse;
+    }
+
+    if (mm_flags & AV_CPU_FLAG_SSE2) {
+        h->pred16x16[DC_PRED8x8  ] = ff_pred16x16_dc_sse2;
+#if CONFIG_GPL
+        h->pred8x8l [DIAG_DOWN_LEFT_PRED ] = ff_pred8x8l_down_left_sse2;
+        h->pred8x8l [DIAG_DOWN_RIGHT_PRED] = ff_pred8x8l_down_right_sse2;
+        h->pred8x8l [VERT_RIGHT_PRED     ] = ff_pred8x8l_vertical_right_sse2;
+        h->pred8x8l [VERT_LEFT_PRED      ] = ff_pred8x8l_vertical_left_sse2;
+        h->pred8x8l [HOR_DOWN_PRED       ] = ff_pred8x8l_horizontal_down_sse2;
+#endif
+        if (codec_id == CODEC_ID_VP8) {
+            h->pred16x16[PLANE_PRED8x8] = ff_pred16x16_tm_vp8_sse2;
+            h->pred8x8  [PLANE_PRED8x8] = ff_pred8x8_tm_vp8_sse2;
+        } else {
+            h->pred8x8  [PLANE_PRED8x8] = ff_pred8x8_plane_sse2;
+            if (codec_id == CODEC_ID_SVQ3) {
+                h->pred16x16[PLANE_PRED8x8] = ff_pred16x16_plane_svq3_sse2;
+            } else if (codec_id == CODEC_ID_RV40) {
+                h->pred16x16[PLANE_PRED8x8] = ff_pred16x16_plane_rv40_sse2;
+            } else {
+                h->pred16x16[PLANE_PRED8x8] = ff_pred16x16_plane_h264_sse2;
+            }
+        }
+    }
+
+    if (mm_flags & AV_CPU_FLAG_SSSE3) {
+        h->pred16x16[HOR_PRED8x8 ] = ff_pred16x16_horizontal_ssse3;
+        h->pred16x16[DC_PRED8x8  ] = ff_pred16x16_dc_ssse3;
+        h->pred8x8  [HOR_PRED8x8 ] = ff_pred8x8_horizontal_ssse3;
+#if CONFIG_GPL
+        h->pred8x8l [TOP_DC_PRED ] = ff_pred8x8l_top_dc_ssse3;
+        h->pred8x8l [DC_PRED     ] = ff_pred8x8l_dc_ssse3;
+        h->pred8x8l [HOR_PRED    ] = ff_pred8x8l_horizontal_ssse3;
+        h->pred8x8l [VERT_PRED   ] = ff_pred8x8l_vertical_ssse3;
+        h->pred8x8l [DIAG_DOWN_LEFT_PRED ] = ff_pred8x8l_down_left_ssse3;
+        h->pred8x8l [DIAG_DOWN_RIGHT_PRED] = ff_pred8x8l_down_right_ssse3;
+        h->pred8x8l [VERT_RIGHT_PRED     ] = ff_pred8x8l_vertical_right_ssse3;
+        h->pred8x8l [VERT_LEFT_PRED      ] = ff_pred8x8l_vertical_left_ssse3;
+        h->pred8x8l [HOR_UP_PRED         ] = ff_pred8x8l_horizontal_up_ssse3;
+        h->pred8x8l [HOR_DOWN_PRED       ] = ff_pred8x8l_horizontal_down_ssse3;
+#endif
+        if (codec_id == CODEC_ID_VP8) {
+            h->pred8x8  [PLANE_PRED8x8] = ff_pred8x8_tm_vp8_ssse3;
+            h->pred4x4  [TM_VP8_PRED  ] = ff_pred4x4_tm_vp8_ssse3;
+        } else {
+            h->pred8x8  [PLANE_PRED8x8] = ff_pred8x8_plane_ssse3;
+            if (codec_id == CODEC_ID_SVQ3) {
+                h->pred16x16[PLANE_PRED8x8] = ff_pred16x16_plane_svq3_ssse3;
+            } else if (codec_id == CODEC_ID_RV40) {
+                h->pred16x16[PLANE_PRED8x8] = ff_pred16x16_plane_rv40_ssse3;
+            } else {
+                h->pred16x16[PLANE_PRED8x8] = ff_pred16x16_plane_h264_ssse3;
+            }
+        }
+    }
+#endif
+}
diff --git a/libavcodec/x86/h264_qpel_mmx.c b/libavcodec/x86/h264_qpel_mmx.c
new file mode 100644
index 0000000..066f794
--- /dev/null
+++ b/libavcodec/x86/h264_qpel_mmx.c
@@ -0,0 +1,1201 @@
+/*
+ * Copyright (c) 2004-2005 Michael Niedermayer, Loren Merritt
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "dsputil_mmx.h"
+
+/***********************************/
+/* motion compensation */
+
+#define QPEL_H264V_MM(A,B,C,D,E,F,OP,T,Z,d,q)\
+        "mov"#q" "#C", "#T"         \n\t"\
+        "mov"#d" (%0), "#F"         \n\t"\
+        "paddw "#D", "#T"           \n\t"\
+        "psllw $2, "#T"             \n\t"\
+        "psubw "#B", "#T"           \n\t"\
+        "psubw "#E", "#T"           \n\t"\
+        "punpcklbw "#Z", "#F"       \n\t"\
+        "pmullw "MANGLE(ff_pw_5)", "#T"\n\t"\
+        "paddw "MANGLE(ff_pw_16)", "#A"\n\t"\
+        "add %2, %0                 \n\t"\
+        "paddw "#F", "#A"           \n\t"\
+        "paddw "#A", "#T"           \n\t"\
+        "psraw $5, "#T"             \n\t"\
+        "packuswb "#T", "#T"        \n\t"\
+        OP(T, (%1), A, d)\
+        "add %3, %1                 \n\t"
+
+#define QPEL_H264HV_MM(A,B,C,D,E,F,OF,T,Z,d,q)\
+        "mov"#q" "#C", "#T"         \n\t"\
+        "mov"#d" (%0), "#F"         \n\t"\
+        "paddw "#D", "#T"           \n\t"\
+        "psllw $2, "#T"             \n\t"\
+        "paddw "MANGLE(ff_pw_16)", "#A"\n\t"\
+        "psubw "#B", "#T"           \n\t"\
+        "psubw "#E", "#T"           \n\t"\
+        "punpcklbw "#Z", "#F"       \n\t"\
+        "pmullw "MANGLE(ff_pw_5)", "#T"\n\t"\
+        "paddw "#F", "#A"           \n\t"\
+        "add %2, %0                 \n\t"\
+        "paddw "#A", "#T"           \n\t"\
+        "mov"#q" "#T", "#OF"(%1)    \n\t"
+
+#define QPEL_H264V(A,B,C,D,E,F,OP) QPEL_H264V_MM(A,B,C,D,E,F,OP,%%mm6,%%mm7,d,q)
+#define QPEL_H264HV(A,B,C,D,E,F,OF) QPEL_H264HV_MM(A,B,C,D,E,F,OF,%%mm6,%%mm7,d,q)
+#define QPEL_H264V_XMM(A,B,C,D,E,F,OP) QPEL_H264V_MM(A,B,C,D,E,F,OP,%%xmm6,%%xmm7,q,dqa)
+#define QPEL_H264HV_XMM(A,B,C,D,E,F,OF) QPEL_H264HV_MM(A,B,C,D,E,F,OF,%%xmm6,%%xmm7,q,dqa)
+
+
+#define QPEL_H264(OPNAME, OP, MMX)\
+static av_noinline void OPNAME ## h264_qpel4_h_lowpass_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride){\
+    int h=4;\
+\
+    __asm__ volatile(\
+        "pxor %%mm7, %%mm7          \n\t"\
+        "movq "MANGLE(ff_pw_5) ", %%mm4\n\t"\
+        "movq "MANGLE(ff_pw_16)", %%mm5\n\t"\
+        "1:                         \n\t"\
+        "movd  -1(%0), %%mm1        \n\t"\
+        "movd    (%0), %%mm2        \n\t"\
+        "movd   1(%0), %%mm3        \n\t"\
+        "movd   2(%0), %%mm0        \n\t"\
+        "punpcklbw %%mm7, %%mm1     \n\t"\
+        "punpcklbw %%mm7, %%mm2     \n\t"\
+        "punpcklbw %%mm7, %%mm3     \n\t"\
+        "punpcklbw %%mm7, %%mm0     \n\t"\
+        "paddw %%mm0, %%mm1         \n\t"\
+        "paddw %%mm3, %%mm2         \n\t"\
+        "movd  -2(%0), %%mm0        \n\t"\
+        "movd   3(%0), %%mm3        \n\t"\
+        "punpcklbw %%mm7, %%mm0     \n\t"\
+        "punpcklbw %%mm7, %%mm3     \n\t"\
+        "paddw %%mm3, %%mm0         \n\t"\
+        "psllw $2, %%mm2            \n\t"\
+        "psubw %%mm1, %%mm2         \n\t"\
+        "pmullw %%mm4, %%mm2        \n\t"\
+        "paddw %%mm5, %%mm0         \n\t"\
+        "paddw %%mm2, %%mm0         \n\t"\
+        "psraw $5, %%mm0            \n\t"\
+        "packuswb %%mm0, %%mm0      \n\t"\
+        OP(%%mm0, (%1),%%mm6, d)\
+        "add %3, %0                 \n\t"\
+        "add %4, %1                 \n\t"\
+        "decl %2                    \n\t"\
+        " jnz 1b                    \n\t"\
+        : "+a"(src), "+c"(dst), "+g"(h)\
+        : "d"((x86_reg)srcStride), "S"((x86_reg)dstStride)\
+        : "memory"\
+    );\
+}\
+static av_noinline void OPNAME ## h264_qpel4_h_lowpass_l2_ ## MMX(uint8_t *dst, uint8_t *src, uint8_t *src2, int dstStride, int src2Stride){\
+    int h=4;\
+    __asm__ volatile(\
+        "pxor %%mm7, %%mm7          \n\t"\
+        "movq %0, %%mm4             \n\t"\
+        "movq %1, %%mm5             \n\t"\
+        :: "m"(ff_pw_5), "m"(ff_pw_16)\
+    );\
+    do{\
+    __asm__ volatile(\
+        "movd  -1(%0), %%mm1        \n\t"\
+        "movd    (%0), %%mm2        \n\t"\
+        "movd   1(%0), %%mm3        \n\t"\
+        "movd   2(%0), %%mm0        \n\t"\
+        "punpcklbw %%mm7, %%mm1     \n\t"\
+        "punpcklbw %%mm7, %%mm2     \n\t"\
+        "punpcklbw %%mm7, %%mm3     \n\t"\
+        "punpcklbw %%mm7, %%mm0     \n\t"\
+        "paddw %%mm0, %%mm1         \n\t"\
+        "paddw %%mm3, %%mm2         \n\t"\
+        "movd  -2(%0), %%mm0        \n\t"\
+        "movd   3(%0), %%mm3        \n\t"\
+        "punpcklbw %%mm7, %%mm0     \n\t"\
+        "punpcklbw %%mm7, %%mm3     \n\t"\
+        "paddw %%mm3, %%mm0         \n\t"\
+        "psllw $2, %%mm2            \n\t"\
+        "psubw %%mm1, %%mm2         \n\t"\
+        "pmullw %%mm4, %%mm2        \n\t"\
+        "paddw %%mm5, %%mm0         \n\t"\
+        "paddw %%mm2, %%mm0         \n\t"\
+        "movd   (%2), %%mm3         \n\t"\
+        "psraw $5, %%mm0            \n\t"\
+        "packuswb %%mm0, %%mm0      \n\t"\
+        PAVGB" %%mm3, %%mm0         \n\t"\
+        OP(%%mm0, (%1),%%mm6, d)\
+        "add %4, %0                 \n\t"\
+        "add %4, %1                 \n\t"\
+        "add %3, %2                 \n\t"\
+        : "+a"(src), "+c"(dst), "+d"(src2)\
+        : "D"((x86_reg)src2Stride), "S"((x86_reg)dstStride)\
+        : "memory"\
+    );\
+    }while(--h);\
+}\
+static av_noinline void OPNAME ## h264_qpel4_v_lowpass_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride){\
+    src -= 2*srcStride;\
+    __asm__ volatile(\
+        "pxor %%mm7, %%mm7          \n\t"\
+        "movd (%0), %%mm0           \n\t"\
+        "add %2, %0                 \n\t"\
+        "movd (%0), %%mm1           \n\t"\
+        "add %2, %0                 \n\t"\
+        "movd (%0), %%mm2           \n\t"\
+        "add %2, %0                 \n\t"\
+        "movd (%0), %%mm3           \n\t"\
+        "add %2, %0                 \n\t"\
+        "movd (%0), %%mm4           \n\t"\
+        "add %2, %0                 \n\t"\
+        "punpcklbw %%mm7, %%mm0     \n\t"\
+        "punpcklbw %%mm7, %%mm1     \n\t"\
+        "punpcklbw %%mm7, %%mm2     \n\t"\
+        "punpcklbw %%mm7, %%mm3     \n\t"\
+        "punpcklbw %%mm7, %%mm4     \n\t"\
+        QPEL_H264V(%%mm0, %%mm1, %%mm2, %%mm3, %%mm4, %%mm5, OP)\
+        QPEL_H264V(%%mm1, %%mm2, %%mm3, %%mm4, %%mm5, %%mm0, OP)\
+        QPEL_H264V(%%mm2, %%mm3, %%mm4, %%mm5, %%mm0, %%mm1, OP)\
+        QPEL_H264V(%%mm3, %%mm4, %%mm5, %%mm0, %%mm1, %%mm2, OP)\
+         \
+        : "+a"(src), "+c"(dst)\
+        : "S"((x86_reg)srcStride), "D"((x86_reg)dstStride), "m"(ff_pw_5), "m"(ff_pw_16)\
+        : "memory"\
+    );\
+}\
+static av_noinline void OPNAME ## h264_qpel4_hv_lowpass_ ## MMX(uint8_t *dst, int16_t *tmp, uint8_t *src, int dstStride, int tmpStride, int srcStride){\
+    int h=4;\
+    int w=3;\
+    src -= 2*srcStride+2;\
+    while(w--){\
+        __asm__ volatile(\
+            "pxor %%mm7, %%mm7      \n\t"\
+            "movd (%0), %%mm0       \n\t"\
+            "add %2, %0             \n\t"\
+            "movd (%0), %%mm1       \n\t"\
+            "add %2, %0             \n\t"\
+            "movd (%0), %%mm2       \n\t"\
+            "add %2, %0             \n\t"\
+            "movd (%0), %%mm3       \n\t"\
+            "add %2, %0             \n\t"\
+            "movd (%0), %%mm4       \n\t"\
+            "add %2, %0             \n\t"\
+            "punpcklbw %%mm7, %%mm0 \n\t"\
+            "punpcklbw %%mm7, %%mm1 \n\t"\
+            "punpcklbw %%mm7, %%mm2 \n\t"\
+            "punpcklbw %%mm7, %%mm3 \n\t"\
+            "punpcklbw %%mm7, %%mm4 \n\t"\
+            QPEL_H264HV(%%mm0, %%mm1, %%mm2, %%mm3, %%mm4, %%mm5, 0*8*3)\
+            QPEL_H264HV(%%mm1, %%mm2, %%mm3, %%mm4, %%mm5, %%mm0, 1*8*3)\
+            QPEL_H264HV(%%mm2, %%mm3, %%mm4, %%mm5, %%mm0, %%mm1, 2*8*3)\
+            QPEL_H264HV(%%mm3, %%mm4, %%mm5, %%mm0, %%mm1, %%mm2, 3*8*3)\
+             \
+            : "+a"(src)\
+            : "c"(tmp), "S"((x86_reg)srcStride)\
+            : "memory"\
+        );\
+        tmp += 4;\
+        src += 4 - 9*srcStride;\
+    }\
+    tmp -= 3*4;\
+    __asm__ volatile(\
+        "1:                         \n\t"\
+        "movq     (%0), %%mm0       \n\t"\
+        "paddw  10(%0), %%mm0       \n\t"\
+        "movq    2(%0), %%mm1       \n\t"\
+        "paddw   8(%0), %%mm1       \n\t"\
+        "movq    4(%0), %%mm2       \n\t"\
+        "paddw   6(%0), %%mm2       \n\t"\
+        "psubw %%mm1, %%mm0         \n\t"/*a-b   (abccba)*/\
+        "psraw $2, %%mm0            \n\t"/*(a-b)/4 */\
+        "psubw %%mm1, %%mm0         \n\t"/*(a-b)/4-b */\
+        "paddsw %%mm2, %%mm0        \n\t"\
+        "psraw $2, %%mm0            \n\t"/*((a-b)/4-b+c)/4 */\
+        "paddw %%mm2, %%mm0         \n\t"/*(a-5*b+20*c)/16 */\
+        "psraw $6, %%mm0            \n\t"\
+        "packuswb %%mm0, %%mm0      \n\t"\
+        OP(%%mm0, (%1),%%mm7, d)\
+        "add $24, %0                \n\t"\
+        "add %3, %1                 \n\t"\
+        "decl %2                    \n\t"\
+        " jnz 1b                    \n\t"\
+        : "+a"(tmp), "+c"(dst), "+g"(h)\
+        : "S"((x86_reg)dstStride)\
+        : "memory"\
+    );\
+}\
+\
+static av_noinline void OPNAME ## h264_qpel8_h_lowpass_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride){\
+    int h=8;\
+    __asm__ volatile(\
+        "pxor %%mm7, %%mm7          \n\t"\
+        "movq "MANGLE(ff_pw_5)", %%mm6\n\t"\
+        "1:                         \n\t"\
+        "movq    (%0), %%mm0        \n\t"\
+        "movq   1(%0), %%mm2        \n\t"\
+        "movq %%mm0, %%mm1          \n\t"\
+        "movq %%mm2, %%mm3          \n\t"\
+        "punpcklbw %%mm7, %%mm0     \n\t"\
+        "punpckhbw %%mm7, %%mm1     \n\t"\
+        "punpcklbw %%mm7, %%mm2     \n\t"\
+        "punpckhbw %%mm7, %%mm3     \n\t"\
+        "paddw %%mm2, %%mm0         \n\t"\
+        "paddw %%mm3, %%mm1         \n\t"\
+        "psllw $2, %%mm0            \n\t"\
+        "psllw $2, %%mm1            \n\t"\
+        "movq   -1(%0), %%mm2       \n\t"\
+        "movq    2(%0), %%mm4       \n\t"\
+        "movq %%mm2, %%mm3          \n\t"\
+        "movq %%mm4, %%mm5          \n\t"\
+        "punpcklbw %%mm7, %%mm2     \n\t"\
+        "punpckhbw %%mm7, %%mm3     \n\t"\
+        "punpcklbw %%mm7, %%mm4     \n\t"\
+        "punpckhbw %%mm7, %%mm5     \n\t"\
+        "paddw %%mm4, %%mm2         \n\t"\
+        "paddw %%mm3, %%mm5         \n\t"\
+        "psubw %%mm2, %%mm0         \n\t"\
+        "psubw %%mm5, %%mm1         \n\t"\
+        "pmullw %%mm6, %%mm0        \n\t"\
+        "pmullw %%mm6, %%mm1        \n\t"\
+        "movd   -2(%0), %%mm2       \n\t"\
+        "movd    7(%0), %%mm5       \n\t"\
+        "punpcklbw %%mm7, %%mm2     \n\t"\
+        "punpcklbw %%mm7, %%mm5     \n\t"\
+        "paddw %%mm3, %%mm2         \n\t"\
+        "paddw %%mm5, %%mm4         \n\t"\
+        "movq "MANGLE(ff_pw_16)", %%mm5\n\t"\
+        "paddw %%mm5, %%mm2         \n\t"\
+        "paddw %%mm5, %%mm4         \n\t"\
+        "paddw %%mm2, %%mm0         \n\t"\
+        "paddw %%mm4, %%mm1         \n\t"\
+        "psraw $5, %%mm0            \n\t"\
+        "psraw $5, %%mm1            \n\t"\
+        "packuswb %%mm1, %%mm0      \n\t"\
+        OP(%%mm0, (%1),%%mm5, q)\
+        "add %3, %0                 \n\t"\
+        "add %4, %1                 \n\t"\
+        "decl %2                    \n\t"\
+        " jnz 1b                    \n\t"\
+        : "+a"(src), "+c"(dst), "+g"(h)\
+        : "d"((x86_reg)srcStride), "S"((x86_reg)dstStride)\
+        : "memory"\
+    );\
+}\
+\
+static av_noinline void OPNAME ## h264_qpel8_h_lowpass_l2_ ## MMX(uint8_t *dst, uint8_t *src, uint8_t *src2, int dstStride, int src2Stride){\
+    int h=8;\
+    __asm__ volatile(\
+        "pxor %%mm7, %%mm7          \n\t"\
+        "movq "MANGLE(ff_pw_5)", %%mm6\n\t"\
+        "1:                         \n\t"\
+        "movq    (%0), %%mm0        \n\t"\
+        "movq   1(%0), %%mm2        \n\t"\
+        "movq %%mm0, %%mm1          \n\t"\
+        "movq %%mm2, %%mm3          \n\t"\
+        "punpcklbw %%mm7, %%mm0     \n\t"\
+        "punpckhbw %%mm7, %%mm1     \n\t"\
+        "punpcklbw %%mm7, %%mm2     \n\t"\
+        "punpckhbw %%mm7, %%mm3     \n\t"\
+        "paddw %%mm2, %%mm0         \n\t"\
+        "paddw %%mm3, %%mm1         \n\t"\
+        "psllw $2, %%mm0            \n\t"\
+        "psllw $2, %%mm1            \n\t"\
+        "movq   -1(%0), %%mm2       \n\t"\
+        "movq    2(%0), %%mm4       \n\t"\
+        "movq %%mm2, %%mm3          \n\t"\
+        "movq %%mm4, %%mm5          \n\t"\
+        "punpcklbw %%mm7, %%mm2     \n\t"\
+        "punpckhbw %%mm7, %%mm3     \n\t"\
+        "punpcklbw %%mm7, %%mm4     \n\t"\
+        "punpckhbw %%mm7, %%mm5     \n\t"\
+        "paddw %%mm4, %%mm2         \n\t"\
+        "paddw %%mm3, %%mm5         \n\t"\
+        "psubw %%mm2, %%mm0         \n\t"\
+        "psubw %%mm5, %%mm1         \n\t"\
+        "pmullw %%mm6, %%mm0        \n\t"\
+        "pmullw %%mm6, %%mm1        \n\t"\
+        "movd   -2(%0), %%mm2       \n\t"\
+        "movd    7(%0), %%mm5       \n\t"\
+        "punpcklbw %%mm7, %%mm2     \n\t"\
+        "punpcklbw %%mm7, %%mm5     \n\t"\
+        "paddw %%mm3, %%mm2         \n\t"\
+        "paddw %%mm5, %%mm4         \n\t"\
+        "movq "MANGLE(ff_pw_16)", %%mm5\n\t"\
+        "paddw %%mm5, %%mm2         \n\t"\
+        "paddw %%mm5, %%mm4         \n\t"\
+        "paddw %%mm2, %%mm0         \n\t"\
+        "paddw %%mm4, %%mm1         \n\t"\
+        "psraw $5, %%mm0            \n\t"\
+        "psraw $5, %%mm1            \n\t"\
+        "movq (%2), %%mm4           \n\t"\
+        "packuswb %%mm1, %%mm0      \n\t"\
+        PAVGB" %%mm4, %%mm0         \n\t"\
+        OP(%%mm0, (%1),%%mm5, q)\
+        "add %5, %0                 \n\t"\
+        "add %5, %1                 \n\t"\
+        "add %4, %2                 \n\t"\
+        "decl %3                    \n\t"\
+        "jg 1b                      \n\t"\
+        : "+a"(src), "+c"(dst), "+d"(src2), "+g"(h)\
+        : "D"((x86_reg)src2Stride), "S"((x86_reg)dstStride)\
+        : "memory"\
+    );\
+}\
+\
+static av_noinline void OPNAME ## h264_qpel8or16_v_lowpass_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride, int h){\
+    int w= 2;\
+    src -= 2*srcStride;\
+    \
+    while(w--){\
+        __asm__ volatile(\
+            "pxor %%mm7, %%mm7          \n\t"\
+            "movd (%0), %%mm0           \n\t"\
+            "add %2, %0                 \n\t"\
+            "movd (%0), %%mm1           \n\t"\
+            "add %2, %0                 \n\t"\
+            "movd (%0), %%mm2           \n\t"\
+            "add %2, %0                 \n\t"\
+            "movd (%0), %%mm3           \n\t"\
+            "add %2, %0                 \n\t"\
+            "movd (%0), %%mm4           \n\t"\
+            "add %2, %0                 \n\t"\
+            "punpcklbw %%mm7, %%mm0     \n\t"\
+            "punpcklbw %%mm7, %%mm1     \n\t"\
+            "punpcklbw %%mm7, %%mm2     \n\t"\
+            "punpcklbw %%mm7, %%mm3     \n\t"\
+            "punpcklbw %%mm7, %%mm4     \n\t"\
+            QPEL_H264V(%%mm0, %%mm1, %%mm2, %%mm3, %%mm4, %%mm5, OP)\
+            QPEL_H264V(%%mm1, %%mm2, %%mm3, %%mm4, %%mm5, %%mm0, OP)\
+            QPEL_H264V(%%mm2, %%mm3, %%mm4, %%mm5, %%mm0, %%mm1, OP)\
+            QPEL_H264V(%%mm3, %%mm4, %%mm5, %%mm0, %%mm1, %%mm2, OP)\
+            QPEL_H264V(%%mm4, %%mm5, %%mm0, %%mm1, %%mm2, %%mm3, OP)\
+            QPEL_H264V(%%mm5, %%mm0, %%mm1, %%mm2, %%mm3, %%mm4, OP)\
+            QPEL_H264V(%%mm0, %%mm1, %%mm2, %%mm3, %%mm4, %%mm5, OP)\
+            QPEL_H264V(%%mm1, %%mm2, %%mm3, %%mm4, %%mm5, %%mm0, OP)\
+            "cmpl $16, %4               \n\t"\
+            "jne 2f                     \n\t"\
+            QPEL_H264V(%%mm2, %%mm3, %%mm4, %%mm5, %%mm0, %%mm1, OP)\
+            QPEL_H264V(%%mm3, %%mm4, %%mm5, %%mm0, %%mm1, %%mm2, OP)\
+            QPEL_H264V(%%mm4, %%mm5, %%mm0, %%mm1, %%mm2, %%mm3, OP)\
+            QPEL_H264V(%%mm5, %%mm0, %%mm1, %%mm2, %%mm3, %%mm4, OP)\
+            QPEL_H264V(%%mm0, %%mm1, %%mm2, %%mm3, %%mm4, %%mm5, OP)\
+            QPEL_H264V(%%mm1, %%mm2, %%mm3, %%mm4, %%mm5, %%mm0, OP)\
+            QPEL_H264V(%%mm2, %%mm3, %%mm4, %%mm5, %%mm0, %%mm1, OP)\
+            QPEL_H264V(%%mm3, %%mm4, %%mm5, %%mm0, %%mm1, %%mm2, OP)\
+            "2:                         \n\t"\
+            \
+            : "+a"(src), "+c"(dst)\
+            : "S"((x86_reg)srcStride), "D"((x86_reg)dstStride), "g"(h)\
+            : "memory"\
+        );\
+        src += 4-(h+5)*srcStride;\
+        dst += 4-h*dstStride;\
+    }\
+}\
+static av_always_inline void OPNAME ## h264_qpel8or16_hv1_lowpass_ ## MMX(int16_t *tmp, uint8_t *src, int tmpStride, int srcStride, int size){\
+    int w = (size+8)>>2;\
+    src -= 2*srcStride+2;\
+    while(w--){\
+        __asm__ volatile(\
+            "pxor %%mm7, %%mm7      \n\t"\
+            "movd (%0), %%mm0       \n\t"\
+            "add %2, %0             \n\t"\
+            "movd (%0), %%mm1       \n\t"\
+            "add %2, %0             \n\t"\
+            "movd (%0), %%mm2       \n\t"\
+            "add %2, %0             \n\t"\
+            "movd (%0), %%mm3       \n\t"\
+            "add %2, %0             \n\t"\
+            "movd (%0), %%mm4       \n\t"\
+            "add %2, %0             \n\t"\
+            "punpcklbw %%mm7, %%mm0 \n\t"\
+            "punpcklbw %%mm7, %%mm1 \n\t"\
+            "punpcklbw %%mm7, %%mm2 \n\t"\
+            "punpcklbw %%mm7, %%mm3 \n\t"\
+            "punpcklbw %%mm7, %%mm4 \n\t"\
+            QPEL_H264HV(%%mm0, %%mm1, %%mm2, %%mm3, %%mm4, %%mm5, 0*48)\
+            QPEL_H264HV(%%mm1, %%mm2, %%mm3, %%mm4, %%mm5, %%mm0, 1*48)\
+            QPEL_H264HV(%%mm2, %%mm3, %%mm4, %%mm5, %%mm0, %%mm1, 2*48)\
+            QPEL_H264HV(%%mm3, %%mm4, %%mm5, %%mm0, %%mm1, %%mm2, 3*48)\
+            QPEL_H264HV(%%mm4, %%mm5, %%mm0, %%mm1, %%mm2, %%mm3, 4*48)\
+            QPEL_H264HV(%%mm5, %%mm0, %%mm1, %%mm2, %%mm3, %%mm4, 5*48)\
+            QPEL_H264HV(%%mm0, %%mm1, %%mm2, %%mm3, %%mm4, %%mm5, 6*48)\
+            QPEL_H264HV(%%mm1, %%mm2, %%mm3, %%mm4, %%mm5, %%mm0, 7*48)\
+            "cmpl $16, %3           \n\t"\
+            "jne 2f                 \n\t"\
+            QPEL_H264HV(%%mm2, %%mm3, %%mm4, %%mm5, %%mm0, %%mm1,  8*48)\
+            QPEL_H264HV(%%mm3, %%mm4, %%mm5, %%mm0, %%mm1, %%mm2,  9*48)\
+            QPEL_H264HV(%%mm4, %%mm5, %%mm0, %%mm1, %%mm2, %%mm3, 10*48)\
+            QPEL_H264HV(%%mm5, %%mm0, %%mm1, %%mm2, %%mm3, %%mm4, 11*48)\
+            QPEL_H264HV(%%mm0, %%mm1, %%mm2, %%mm3, %%mm4, %%mm5, 12*48)\
+            QPEL_H264HV(%%mm1, %%mm2, %%mm3, %%mm4, %%mm5, %%mm0, 13*48)\
+            QPEL_H264HV(%%mm2, %%mm3, %%mm4, %%mm5, %%mm0, %%mm1, 14*48)\
+            QPEL_H264HV(%%mm3, %%mm4, %%mm5, %%mm0, %%mm1, %%mm2, 15*48)\
+            "2:                     \n\t"\
+            : "+a"(src)\
+            : "c"(tmp), "S"((x86_reg)srcStride), "g"(size)\
+            : "memory"\
+            );\
+        tmp += 4;\
+        src += 4 - (size+5)*srcStride;\
+    }\
+}\
+static av_always_inline void OPNAME ## h264_qpel8or16_hv2_lowpass_ ## MMX(uint8_t *dst, int16_t *tmp, int dstStride, int tmpStride, int size){\
+    int w = size>>4;\
+    do{\
+    int h = size;\
+    __asm__ volatile(\
+        "1:                         \n\t"\
+        "movq     (%0), %%mm0       \n\t"\
+        "movq    8(%0), %%mm3       \n\t"\
+        "movq    2(%0), %%mm1       \n\t"\
+        "movq   10(%0), %%mm4       \n\t"\
+        "paddw   %%mm4, %%mm0       \n\t"\
+        "paddw   %%mm3, %%mm1       \n\t"\
+        "paddw  18(%0), %%mm3       \n\t"\
+        "paddw  16(%0), %%mm4       \n\t"\
+        "movq    4(%0), %%mm2       \n\t"\
+        "movq   12(%0), %%mm5       \n\t"\
+        "paddw   6(%0), %%mm2       \n\t"\
+        "paddw  14(%0), %%mm5       \n\t"\
+        "psubw %%mm1, %%mm0         \n\t"\
+        "psubw %%mm4, %%mm3         \n\t"\
+        "psraw $2, %%mm0            \n\t"\
+        "psraw $2, %%mm3            \n\t"\
+        "psubw %%mm1, %%mm0         \n\t"\
+        "psubw %%mm4, %%mm3         \n\t"\
+        "paddsw %%mm2, %%mm0        \n\t"\
+        "paddsw %%mm5, %%mm3        \n\t"\
+        "psraw $2, %%mm0            \n\t"\
+        "psraw $2, %%mm3            \n\t"\
+        "paddw %%mm2, %%mm0         \n\t"\
+        "paddw %%mm5, %%mm3         \n\t"\
+        "psraw $6, %%mm0            \n\t"\
+        "psraw $6, %%mm3            \n\t"\
+        "packuswb %%mm3, %%mm0      \n\t"\
+        OP(%%mm0, (%1),%%mm7, q)\
+        "add $48, %0                \n\t"\
+        "add %3, %1                 \n\t"\
+        "decl %2                    \n\t"\
+        " jnz 1b                    \n\t"\
+        : "+a"(tmp), "+c"(dst), "+g"(h)\
+        : "S"((x86_reg)dstStride)\
+        : "memory"\
+    );\
+    tmp += 8 - size*24;\
+    dst += 8 - size*dstStride;\
+    }while(w--);\
+}\
+\
+static void OPNAME ## h264_qpel8_v_lowpass_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride){\
+    OPNAME ## h264_qpel8or16_v_lowpass_ ## MMX(dst  , src  , dstStride, srcStride, 8);\
+}\
+static av_noinline void OPNAME ## h264_qpel16_v_lowpass_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride){\
+    OPNAME ## h264_qpel8or16_v_lowpass_ ## MMX(dst  , src  , dstStride, srcStride, 16);\
+    OPNAME ## h264_qpel8or16_v_lowpass_ ## MMX(dst+8, src+8, dstStride, srcStride, 16);\
+}\
+\
+static void OPNAME ## h264_qpel16_h_lowpass_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride){\
+    OPNAME ## h264_qpel8_h_lowpass_ ## MMX(dst  , src  , dstStride, srcStride);\
+    OPNAME ## h264_qpel8_h_lowpass_ ## MMX(dst+8, src+8, dstStride, srcStride);\
+    src += 8*srcStride;\
+    dst += 8*dstStride;\
+    OPNAME ## h264_qpel8_h_lowpass_ ## MMX(dst  , src  , dstStride, srcStride);\
+    OPNAME ## h264_qpel8_h_lowpass_ ## MMX(dst+8, src+8, dstStride, srcStride);\
+}\
+\
+static av_noinline void OPNAME ## h264_qpel16_h_lowpass_l2_ ## MMX(uint8_t *dst, uint8_t *src, uint8_t *src2, int dstStride, int src2Stride){\
+    OPNAME ## h264_qpel8_h_lowpass_l2_ ## MMX(dst  , src  , src2  , dstStride, src2Stride);\
+    OPNAME ## h264_qpel8_h_lowpass_l2_ ## MMX(dst+8, src+8, src2+8, dstStride, src2Stride);\
+    src += 8*dstStride;\
+    dst += 8*dstStride;\
+    src2 += 8*src2Stride;\
+    OPNAME ## h264_qpel8_h_lowpass_l2_ ## MMX(dst  , src  , src2  , dstStride, src2Stride);\
+    OPNAME ## h264_qpel8_h_lowpass_l2_ ## MMX(dst+8, src+8, src2+8, dstStride, src2Stride);\
+}\
+\
+static av_noinline void OPNAME ## h264_qpel8or16_hv_lowpass_ ## MMX(uint8_t *dst, int16_t *tmp, uint8_t *src, int dstStride, int tmpStride, int srcStride, int size){\
+          put_h264_qpel8or16_hv1_lowpass_ ## MMX(tmp, src, tmpStride, srcStride, size);\
+    OPNAME ## h264_qpel8or16_hv2_lowpass_ ## MMX(dst, tmp, dstStride, tmpStride, size);\
+}\
+static void OPNAME ## h264_qpel8_hv_lowpass_ ## MMX(uint8_t *dst, int16_t *tmp, uint8_t *src, int dstStride, int tmpStride, int srcStride){\
+    OPNAME ## h264_qpel8or16_hv_lowpass_ ## MMX(dst  , tmp  , src  , dstStride, tmpStride, srcStride, 8);\
+}\
+\
+static void OPNAME ## h264_qpel16_hv_lowpass_ ## MMX(uint8_t *dst, int16_t *tmp, uint8_t *src, int dstStride, int tmpStride, int srcStride){\
+    OPNAME ## h264_qpel8or16_hv_lowpass_ ## MMX(dst  , tmp  , src  , dstStride, tmpStride, srcStride, 16);\
+}\
+\
+static av_noinline void OPNAME ## pixels4_l2_shift5_ ## MMX(uint8_t *dst, int16_t *src16, uint8_t *src8, int dstStride, int src8Stride, int h)\
+{\
+    __asm__ volatile(\
+        "movq      (%1), %%mm0          \n\t"\
+        "movq    24(%1), %%mm1          \n\t"\
+        "psraw      $5,  %%mm0          \n\t"\
+        "psraw      $5,  %%mm1          \n\t"\
+        "packuswb %%mm0, %%mm0          \n\t"\
+        "packuswb %%mm1, %%mm1          \n\t"\
+        PAVGB"     (%0), %%mm0          \n\t"\
+        PAVGB"  (%0,%3), %%mm1          \n\t"\
+        OP(%%mm0, (%2),    %%mm4, d)\
+        OP(%%mm1, (%2,%4), %%mm5, d)\
+        "lea  (%0,%3,2), %0             \n\t"\
+        "lea  (%2,%4,2), %2             \n\t"\
+        "movq    48(%1), %%mm0          \n\t"\
+        "movq    72(%1), %%mm1          \n\t"\
+        "psraw      $5,  %%mm0          \n\t"\
+        "psraw      $5,  %%mm1          \n\t"\
+        "packuswb %%mm0, %%mm0          \n\t"\
+        "packuswb %%mm1, %%mm1          \n\t"\
+        PAVGB"     (%0), %%mm0          \n\t"\
+        PAVGB"  (%0,%3), %%mm1          \n\t"\
+        OP(%%mm0, (%2),    %%mm4, d)\
+        OP(%%mm1, (%2,%4), %%mm5, d)\
+        :"+a"(src8), "+c"(src16), "+d"(dst)\
+        :"S"((x86_reg)src8Stride), "D"((x86_reg)dstStride)\
+        :"memory");\
+}\
+static av_noinline void OPNAME ## pixels8_l2_shift5_ ## MMX(uint8_t *dst, int16_t *src16, uint8_t *src8, int dstStride, int src8Stride, int h)\
+{\
+    do{\
+    __asm__ volatile(\
+        "movq      (%1), %%mm0          \n\t"\
+        "movq     8(%1), %%mm1          \n\t"\
+        "movq    48(%1), %%mm2          \n\t"\
+        "movq  8+48(%1), %%mm3          \n\t"\
+        "psraw      $5,  %%mm0          \n\t"\
+        "psraw      $5,  %%mm1          \n\t"\
+        "psraw      $5,  %%mm2          \n\t"\
+        "psraw      $5,  %%mm3          \n\t"\
+        "packuswb %%mm1, %%mm0          \n\t"\
+        "packuswb %%mm3, %%mm2          \n\t"\
+        PAVGB"     (%0), %%mm0          \n\t"\
+        PAVGB"  (%0,%3), %%mm2          \n\t"\
+        OP(%%mm0, (%2), %%mm5, q)\
+        OP(%%mm2, (%2,%4), %%mm5, q)\
+        ::"a"(src8), "c"(src16), "d"(dst),\
+          "r"((x86_reg)src8Stride), "r"((x86_reg)dstStride)\
+        :"memory");\
+        src8 += 2L*src8Stride;\
+        src16 += 48;\
+        dst += 2L*dstStride;\
+    }while(h-=2);\
+}\
+static void OPNAME ## pixels16_l2_shift5_ ## MMX(uint8_t *dst, int16_t *src16, uint8_t *src8, int dstStride, int src8Stride, int h)\
+{\
+    OPNAME ## pixels8_l2_shift5_ ## MMX(dst  , src16  , src8  , dstStride, src8Stride, h);\
+    OPNAME ## pixels8_l2_shift5_ ## MMX(dst+8, src16+8, src8+8, dstStride, src8Stride, h);\
+}\
+
+
+#if ARCH_X86_64
+#define QPEL_H264_H16_XMM(OPNAME, OP, MMX)\
+static av_noinline void OPNAME ## h264_qpel16_h_lowpass_l2_ ## MMX(uint8_t *dst, uint8_t *src, uint8_t *src2, int dstStride, int src2Stride){\
+    int h=16;\
+    __asm__ volatile(\
+        "pxor %%xmm15, %%xmm15      \n\t"\
+        "movdqa %6, %%xmm14         \n\t"\
+        "movdqa %7, %%xmm13         \n\t"\
+        "1:                         \n\t"\
+        "lddqu    6(%0), %%xmm1     \n\t"\
+        "lddqu   -2(%0), %%xmm7     \n\t"\
+        "movdqa  %%xmm1, %%xmm0     \n\t"\
+        "punpckhbw %%xmm15, %%xmm1  \n\t"\
+        "punpcklbw %%xmm15, %%xmm0  \n\t"\
+        "punpcklbw %%xmm15, %%xmm7  \n\t"\
+        "movdqa  %%xmm1, %%xmm2     \n\t"\
+        "movdqa  %%xmm0, %%xmm6     \n\t"\
+        "movdqa  %%xmm1, %%xmm3     \n\t"\
+        "movdqa  %%xmm0, %%xmm8     \n\t"\
+        "movdqa  %%xmm1, %%xmm4     \n\t"\
+        "movdqa  %%xmm0, %%xmm9     \n\t"\
+        "movdqa  %%xmm0, %%xmm12    \n\t"\
+        "movdqa  %%xmm1, %%xmm11    \n\t"\
+        "palignr $10,%%xmm0, %%xmm11\n\t"\
+        "palignr $10,%%xmm7, %%xmm12\n\t"\
+        "palignr $2, %%xmm0, %%xmm4 \n\t"\
+        "palignr $2, %%xmm7, %%xmm9 \n\t"\
+        "palignr $4, %%xmm0, %%xmm3 \n\t"\
+        "palignr $4, %%xmm7, %%xmm8 \n\t"\
+        "palignr $6, %%xmm0, %%xmm2 \n\t"\
+        "palignr $6, %%xmm7, %%xmm6 \n\t"\
+        "paddw   %%xmm0 ,%%xmm11    \n\t"\
+        "palignr $8, %%xmm0, %%xmm1 \n\t"\
+        "palignr $8, %%xmm7, %%xmm0 \n\t"\
+        "paddw   %%xmm12,%%xmm7     \n\t"\
+        "paddw   %%xmm3, %%xmm2     \n\t"\
+        "paddw   %%xmm8, %%xmm6     \n\t"\
+        "paddw   %%xmm4, %%xmm1     \n\t"\
+        "paddw   %%xmm9, %%xmm0     \n\t"\
+        "psllw   $2,     %%xmm2     \n\t"\
+        "psllw   $2,     %%xmm6     \n\t"\
+        "psubw   %%xmm1, %%xmm2     \n\t"\
+        "psubw   %%xmm0, %%xmm6     \n\t"\
+        "paddw   %%xmm13,%%xmm11    \n\t"\
+        "paddw   %%xmm13,%%xmm7     \n\t"\
+        "pmullw  %%xmm14,%%xmm2     \n\t"\
+        "pmullw  %%xmm14,%%xmm6     \n\t"\
+        "lddqu   (%2),   %%xmm3     \n\t"\
+        "paddw   %%xmm11,%%xmm2     \n\t"\
+        "paddw   %%xmm7, %%xmm6     \n\t"\
+        "psraw   $5,     %%xmm2     \n\t"\
+        "psraw   $5,     %%xmm6     \n\t"\
+        "packuswb %%xmm2,%%xmm6     \n\t"\
+        "pavgb   %%xmm3, %%xmm6     \n\t"\
+        OP(%%xmm6, (%1), %%xmm4, dqa)\
+        "add %5, %0                 \n\t"\
+        "add %5, %1                 \n\t"\
+        "add %4, %2                 \n\t"\
+        "decl %3                    \n\t"\
+        "jg 1b                      \n\t"\
+        : "+a"(src), "+c"(dst), "+d"(src2), "+g"(h)\
+        : "D"((x86_reg)src2Stride), "S"((x86_reg)dstStride),\
+          "m"(ff_pw_5), "m"(ff_pw_16)\
+        : XMM_CLOBBERS("%xmm0" , "%xmm1" , "%xmm2" , "%xmm3" , \
+                       "%xmm4" , "%xmm5" , "%xmm6" , "%xmm7" , \
+                       "%xmm8" , "%xmm9" , "%xmm10", "%xmm11", \
+                       "%xmm12", "%xmm13", "%xmm14", "%xmm15",)\
+          "memory"\
+    );\
+}
+#else // ARCH_X86_64
+#define QPEL_H264_H16_XMM(OPNAME, OP, MMX)\
+static av_noinline void OPNAME ## h264_qpel16_h_lowpass_l2_ ## MMX(uint8_t *dst, uint8_t *src, uint8_t *src2, int dstStride, int src2Stride){\
+    OPNAME ## h264_qpel8_h_lowpass_l2_ ## MMX(dst  , src  , src2  , dstStride, src2Stride);\
+    OPNAME ## h264_qpel8_h_lowpass_l2_ ## MMX(dst+8, src+8, src2+8, dstStride, src2Stride);\
+    src += 8*dstStride;\
+    dst += 8*dstStride;\
+    src2 += 8*src2Stride;\
+    OPNAME ## h264_qpel8_h_lowpass_l2_ ## MMX(dst  , src  , src2  , dstStride, src2Stride);\
+    OPNAME ## h264_qpel8_h_lowpass_l2_ ## MMX(dst+8, src+8, src2+8, dstStride, src2Stride);\
+}
+#endif // ARCH_X86_64
+
+#define QPEL_H264_H_XMM(OPNAME, OP, MMX)\
+static av_noinline void OPNAME ## h264_qpel8_h_lowpass_l2_ ## MMX(uint8_t *dst, uint8_t *src, uint8_t *src2, int dstStride, int src2Stride){\
+    int h=8;\
+    __asm__ volatile(\
+        "pxor %%xmm7, %%xmm7        \n\t"\
+        "movdqa "MANGLE(ff_pw_5)", %%xmm6\n\t"\
+        "1:                         \n\t"\
+        "lddqu   -2(%0), %%xmm1     \n\t"\
+        "movdqa  %%xmm1, %%xmm0     \n\t"\
+        "punpckhbw %%xmm7, %%xmm1   \n\t"\
+        "punpcklbw %%xmm7, %%xmm0   \n\t"\
+        "movdqa  %%xmm1, %%xmm2     \n\t"\
+        "movdqa  %%xmm1, %%xmm3     \n\t"\
+        "movdqa  %%xmm1, %%xmm4     \n\t"\
+        "movdqa  %%xmm1, %%xmm5     \n\t"\
+        "palignr $2, %%xmm0, %%xmm4 \n\t"\
+        "palignr $4, %%xmm0, %%xmm3 \n\t"\
+        "palignr $6, %%xmm0, %%xmm2 \n\t"\
+        "palignr $8, %%xmm0, %%xmm1 \n\t"\
+        "palignr $10,%%xmm0, %%xmm5 \n\t"\
+        "paddw   %%xmm5, %%xmm0     \n\t"\
+        "paddw   %%xmm3, %%xmm2     \n\t"\
+        "paddw   %%xmm4, %%xmm1     \n\t"\
+        "psllw   $2,     %%xmm2     \n\t"\
+        "movq    (%2),   %%xmm3     \n\t"\
+        "psubw   %%xmm1, %%xmm2     \n\t"\
+        "paddw "MANGLE(ff_pw_16)", %%xmm0\n\t"\
+        "pmullw  %%xmm6, %%xmm2     \n\t"\
+        "paddw   %%xmm0, %%xmm2     \n\t"\
+        "psraw   $5,     %%xmm2     \n\t"\
+        "packuswb %%xmm2, %%xmm2    \n\t"\
+        "pavgb   %%xmm3, %%xmm2     \n\t"\
+        OP(%%xmm2, (%1), %%xmm4, q)\
+        "add %5, %0                 \n\t"\
+        "add %5, %1                 \n\t"\
+        "add %4, %2                 \n\t"\
+        "decl %3                    \n\t"\
+        "jg 1b                      \n\t"\
+        : "+a"(src), "+c"(dst), "+d"(src2), "+g"(h)\
+        : "D"((x86_reg)src2Stride), "S"((x86_reg)dstStride)\
+        : XMM_CLOBBERS("%xmm0", "%xmm1", "%xmm2", "%xmm3", \
+                       "%xmm4", "%xmm5", "%xmm6", "%xmm7",)\
+          "memory"\
+    );\
+}\
+QPEL_H264_H16_XMM(OPNAME, OP, MMX)\
+\
+static av_noinline void OPNAME ## h264_qpel8_h_lowpass_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride){\
+    int h=8;\
+    __asm__ volatile(\
+        "pxor %%xmm7, %%xmm7        \n\t"\
+        "movdqa "MANGLE(ff_pw_5)", %%xmm6\n\t"\
+        "1:                         \n\t"\
+        "lddqu   -2(%0), %%xmm1     \n\t"\
+        "movdqa  %%xmm1, %%xmm0     \n\t"\
+        "punpckhbw %%xmm7, %%xmm1   \n\t"\
+        "punpcklbw %%xmm7, %%xmm0   \n\t"\
+        "movdqa  %%xmm1, %%xmm2     \n\t"\
+        "movdqa  %%xmm1, %%xmm3     \n\t"\
+        "movdqa  %%xmm1, %%xmm4     \n\t"\
+        "movdqa  %%xmm1, %%xmm5     \n\t"\
+        "palignr $2, %%xmm0, %%xmm4 \n\t"\
+        "palignr $4, %%xmm0, %%xmm3 \n\t"\
+        "palignr $6, %%xmm0, %%xmm2 \n\t"\
+        "palignr $8, %%xmm0, %%xmm1 \n\t"\
+        "palignr $10,%%xmm0, %%xmm5 \n\t"\
+        "paddw   %%xmm5, %%xmm0     \n\t"\
+        "paddw   %%xmm3, %%xmm2     \n\t"\
+        "paddw   %%xmm4, %%xmm1     \n\t"\
+        "psllw   $2,     %%xmm2     \n\t"\
+        "psubw   %%xmm1, %%xmm2     \n\t"\
+        "paddw   "MANGLE(ff_pw_16)", %%xmm0\n\t"\
+        "pmullw  %%xmm6, %%xmm2     \n\t"\
+        "paddw   %%xmm0, %%xmm2     \n\t"\
+        "psraw   $5,     %%xmm2     \n\t"\
+        "packuswb %%xmm2, %%xmm2    \n\t"\
+        OP(%%xmm2, (%1), %%xmm4, q)\
+        "add %3, %0                 \n\t"\
+        "add %4, %1                 \n\t"\
+        "decl %2                    \n\t"\
+        " jnz 1b                    \n\t"\
+        : "+a"(src), "+c"(dst), "+g"(h)\
+        : "D"((x86_reg)srcStride), "S"((x86_reg)dstStride)\
+        : XMM_CLOBBERS("%xmm0", "%xmm1", "%xmm2", "%xmm3", \
+                       "%xmm4", "%xmm5", "%xmm6", "%xmm7",)\
+          "memory"\
+    );\
+}\
+static void OPNAME ## h264_qpel16_h_lowpass_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride){\
+    OPNAME ## h264_qpel8_h_lowpass_ ## MMX(dst  , src  , dstStride, srcStride);\
+    OPNAME ## h264_qpel8_h_lowpass_ ## MMX(dst+8, src+8, dstStride, srcStride);\
+    src += 8*srcStride;\
+    dst += 8*dstStride;\
+    OPNAME ## h264_qpel8_h_lowpass_ ## MMX(dst  , src  , dstStride, srcStride);\
+    OPNAME ## h264_qpel8_h_lowpass_ ## MMX(dst+8, src+8, dstStride, srcStride);\
+}\
+
+#define QPEL_H264_V_XMM(OPNAME, OP, MMX)\
+static av_noinline void OPNAME ## h264_qpel8or16_v_lowpass_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride, int h){\
+    src -= 2*srcStride;\
+    \
+    __asm__ volatile(\
+        "pxor %%xmm7, %%xmm7        \n\t"\
+        "movq (%0), %%xmm0          \n\t"\
+        "add %2, %0                 \n\t"\
+        "movq (%0), %%xmm1          \n\t"\
+        "add %2, %0                 \n\t"\
+        "movq (%0), %%xmm2          \n\t"\
+        "add %2, %0                 \n\t"\
+        "movq (%0), %%xmm3          \n\t"\
+        "add %2, %0                 \n\t"\
+        "movq (%0), %%xmm4          \n\t"\
+        "add %2, %0                 \n\t"\
+        "punpcklbw %%xmm7, %%xmm0   \n\t"\
+        "punpcklbw %%xmm7, %%xmm1   \n\t"\
+        "punpcklbw %%xmm7, %%xmm2   \n\t"\
+        "punpcklbw %%xmm7, %%xmm3   \n\t"\
+        "punpcklbw %%xmm7, %%xmm4   \n\t"\
+        QPEL_H264V_XMM(%%xmm0, %%xmm1, %%xmm2, %%xmm3, %%xmm4, %%xmm5, OP)\
+        QPEL_H264V_XMM(%%xmm1, %%xmm2, %%xmm3, %%xmm4, %%xmm5, %%xmm0, OP)\
+        QPEL_H264V_XMM(%%xmm2, %%xmm3, %%xmm4, %%xmm5, %%xmm0, %%xmm1, OP)\
+        QPEL_H264V_XMM(%%xmm3, %%xmm4, %%xmm5, %%xmm0, %%xmm1, %%xmm2, OP)\
+        QPEL_H264V_XMM(%%xmm4, %%xmm5, %%xmm0, %%xmm1, %%xmm2, %%xmm3, OP)\
+        QPEL_H264V_XMM(%%xmm5, %%xmm0, %%xmm1, %%xmm2, %%xmm3, %%xmm4, OP)\
+        QPEL_H264V_XMM(%%xmm0, %%xmm1, %%xmm2, %%xmm3, %%xmm4, %%xmm5, OP)\
+        QPEL_H264V_XMM(%%xmm1, %%xmm2, %%xmm3, %%xmm4, %%xmm5, %%xmm0, OP)\
+        "cmpl $16, %4               \n\t"\
+        "jne 2f                     \n\t"\
+        QPEL_H264V_XMM(%%xmm2, %%xmm3, %%xmm4, %%xmm5, %%xmm0, %%xmm1, OP)\
+        QPEL_H264V_XMM(%%xmm3, %%xmm4, %%xmm5, %%xmm0, %%xmm1, %%xmm2, OP)\
+        QPEL_H264V_XMM(%%xmm4, %%xmm5, %%xmm0, %%xmm1, %%xmm2, %%xmm3, OP)\
+        QPEL_H264V_XMM(%%xmm5, %%xmm0, %%xmm1, %%xmm2, %%xmm3, %%xmm4, OP)\
+        QPEL_H264V_XMM(%%xmm0, %%xmm1, %%xmm2, %%xmm3, %%xmm4, %%xmm5, OP)\
+        QPEL_H264V_XMM(%%xmm1, %%xmm2, %%xmm3, %%xmm4, %%xmm5, %%xmm0, OP)\
+        QPEL_H264V_XMM(%%xmm2, %%xmm3, %%xmm4, %%xmm5, %%xmm0, %%xmm1, OP)\
+        QPEL_H264V_XMM(%%xmm3, %%xmm4, %%xmm5, %%xmm0, %%xmm1, %%xmm2, OP)\
+        "2:                          \n\t"\
+        \
+        : "+a"(src), "+c"(dst)\
+        : "S"((x86_reg)srcStride), "D"((x86_reg)dstStride), "g"(h)\
+        : XMM_CLOBBERS("%xmm0", "%xmm1", "%xmm2", "%xmm3", \
+                       "%xmm4", "%xmm5", "%xmm6", "%xmm7",)\
+          "memory"\
+    );\
+}\
+static void OPNAME ## h264_qpel8_v_lowpass_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride){\
+    OPNAME ## h264_qpel8or16_v_lowpass_ ## MMX(dst  , src  , dstStride, srcStride, 8);\
+}\
+static av_noinline void OPNAME ## h264_qpel16_v_lowpass_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride){\
+    OPNAME ## h264_qpel8or16_v_lowpass_ ## MMX(dst  , src  , dstStride, srcStride, 16);\
+    OPNAME ## h264_qpel8or16_v_lowpass_ ## MMX(dst+8, src+8, dstStride, srcStride, 16);\
+}
+
+static av_always_inline void put_h264_qpel8or16_hv1_lowpass_sse2(int16_t *tmp, uint8_t *src, int tmpStride, int srcStride, int size){
+    int w = (size+8)>>3;
+    src -= 2*srcStride+2;
+    while(w--){
+        __asm__ volatile(
+            "pxor %%xmm7, %%xmm7        \n\t"
+            "movq (%0), %%xmm0          \n\t"
+            "add %2, %0                 \n\t"
+            "movq (%0), %%xmm1          \n\t"
+            "add %2, %0                 \n\t"
+            "movq (%0), %%xmm2          \n\t"
+            "add %2, %0                 \n\t"
+            "movq (%0), %%xmm3          \n\t"
+            "add %2, %0                 \n\t"
+            "movq (%0), %%xmm4          \n\t"
+            "add %2, %0                 \n\t"
+            "punpcklbw %%xmm7, %%xmm0   \n\t"
+            "punpcklbw %%xmm7, %%xmm1   \n\t"
+            "punpcklbw %%xmm7, %%xmm2   \n\t"
+            "punpcklbw %%xmm7, %%xmm3   \n\t"
+            "punpcklbw %%xmm7, %%xmm4   \n\t"
+            QPEL_H264HV_XMM(%%xmm0, %%xmm1, %%xmm2, %%xmm3, %%xmm4, %%xmm5, 0*48)
+            QPEL_H264HV_XMM(%%xmm1, %%xmm2, %%xmm3, %%xmm4, %%xmm5, %%xmm0, 1*48)
+            QPEL_H264HV_XMM(%%xmm2, %%xmm3, %%xmm4, %%xmm5, %%xmm0, %%xmm1, 2*48)
+            QPEL_H264HV_XMM(%%xmm3, %%xmm4, %%xmm5, %%xmm0, %%xmm1, %%xmm2, 3*48)
+            QPEL_H264HV_XMM(%%xmm4, %%xmm5, %%xmm0, %%xmm1, %%xmm2, %%xmm3, 4*48)
+            QPEL_H264HV_XMM(%%xmm5, %%xmm0, %%xmm1, %%xmm2, %%xmm3, %%xmm4, 5*48)
+            QPEL_H264HV_XMM(%%xmm0, %%xmm1, %%xmm2, %%xmm3, %%xmm4, %%xmm5, 6*48)
+            QPEL_H264HV_XMM(%%xmm1, %%xmm2, %%xmm3, %%xmm4, %%xmm5, %%xmm0, 7*48)
+            "cmpl $16, %3               \n\t"
+            "jne 2f                     \n\t"
+            QPEL_H264HV_XMM(%%xmm2, %%xmm3, %%xmm4, %%xmm5, %%xmm0, %%xmm1,  8*48)
+            QPEL_H264HV_XMM(%%xmm3, %%xmm4, %%xmm5, %%xmm0, %%xmm1, %%xmm2,  9*48)
+            QPEL_H264HV_XMM(%%xmm4, %%xmm5, %%xmm0, %%xmm1, %%xmm2, %%xmm3, 10*48)
+            QPEL_H264HV_XMM(%%xmm5, %%xmm0, %%xmm1, %%xmm2, %%xmm3, %%xmm4, 11*48)
+            QPEL_H264HV_XMM(%%xmm0, %%xmm1, %%xmm2, %%xmm3, %%xmm4, %%xmm5, 12*48)
+            QPEL_H264HV_XMM(%%xmm1, %%xmm2, %%xmm3, %%xmm4, %%xmm5, %%xmm0, 13*48)
+            QPEL_H264HV_XMM(%%xmm2, %%xmm3, %%xmm4, %%xmm5, %%xmm0, %%xmm1, 14*48)
+            QPEL_H264HV_XMM(%%xmm3, %%xmm4, %%xmm5, %%xmm0, %%xmm1, %%xmm2, 15*48)
+            "2:                         \n\t"
+            : "+a"(src)
+            : "c"(tmp), "S"((x86_reg)srcStride), "g"(size)
+            : XMM_CLOBBERS("%xmm0", "%xmm1", "%xmm2", "%xmm3",
+                           "%xmm4", "%xmm5", "%xmm6", "%xmm7",)
+              "memory"
+        );
+        tmp += 8;
+        src += 8 - (size+5)*srcStride;
+    }
+}
+
+#define QPEL_H264_HV2_XMM(OPNAME, OP, MMX)\
+static av_always_inline void OPNAME ## h264_qpel8or16_hv2_lowpass_ ## MMX(uint8_t *dst, int16_t *tmp, int dstStride, int tmpStride, int size){\
+    int h = size;\
+    if(size == 16){\
+        __asm__ volatile(\
+            "1:                         \n\t"\
+            "movdqa 32(%0), %%xmm4      \n\t"\
+            "movdqa 16(%0), %%xmm5      \n\t"\
+            "movdqa   (%0), %%xmm7      \n\t"\
+            "movdqa %%xmm4, %%xmm3      \n\t"\
+            "movdqa %%xmm4, %%xmm2      \n\t"\
+            "movdqa %%xmm4, %%xmm1      \n\t"\
+            "movdqa %%xmm4, %%xmm0      \n\t"\
+            "palignr $10, %%xmm5, %%xmm0 \n\t"\
+            "palignr  $8, %%xmm5, %%xmm1 \n\t"\
+            "palignr  $6, %%xmm5, %%xmm2 \n\t"\
+            "palignr  $4, %%xmm5, %%xmm3 \n\t"\
+            "palignr  $2, %%xmm5, %%xmm4 \n\t"\
+            "paddw  %%xmm5, %%xmm0      \n\t"\
+            "paddw  %%xmm4, %%xmm1      \n\t"\
+            "paddw  %%xmm3, %%xmm2      \n\t"\
+            "movdqa %%xmm5, %%xmm6      \n\t"\
+            "movdqa %%xmm5, %%xmm4      \n\t"\
+            "movdqa %%xmm5, %%xmm3      \n\t"\
+            "palignr  $8, %%xmm7, %%xmm4 \n\t"\
+            "palignr  $2, %%xmm7, %%xmm6 \n\t"\
+            "palignr $10, %%xmm7, %%xmm3 \n\t"\
+            "paddw  %%xmm6, %%xmm4      \n\t"\
+            "movdqa %%xmm5, %%xmm6      \n\t"\
+            "palignr  $6, %%xmm7, %%xmm5 \n\t"\
+            "palignr  $4, %%xmm7, %%xmm6 \n\t"\
+            "paddw  %%xmm7, %%xmm3      \n\t"\
+            "paddw  %%xmm6, %%xmm5      \n\t"\
+            \
+            "psubw  %%xmm1, %%xmm0      \n\t"\
+            "psubw  %%xmm4, %%xmm3      \n\t"\
+            "psraw      $2, %%xmm0      \n\t"\
+            "psraw      $2, %%xmm3      \n\t"\
+            "psubw  %%xmm1, %%xmm0      \n\t"\
+            "psubw  %%xmm4, %%xmm3      \n\t"\
+            "paddw  %%xmm2, %%xmm0      \n\t"\
+            "paddw  %%xmm5, %%xmm3      \n\t"\
+            "psraw      $2, %%xmm0      \n\t"\
+            "psraw      $2, %%xmm3      \n\t"\
+            "paddw  %%xmm2, %%xmm0      \n\t"\
+            "paddw  %%xmm5, %%xmm3      \n\t"\
+            "psraw      $6, %%xmm0      \n\t"\
+            "psraw      $6, %%xmm3      \n\t"\
+            "packuswb %%xmm0, %%xmm3    \n\t"\
+            OP(%%xmm3, (%1), %%xmm7, dqa)\
+            "add $48, %0                \n\t"\
+            "add %3, %1                 \n\t"\
+            "decl %2                    \n\t"\
+            " jnz 1b                    \n\t"\
+            : "+a"(tmp), "+c"(dst), "+g"(h)\
+            : "S"((x86_reg)dstStride)\
+            : XMM_CLOBBERS("%xmm0", "%xmm1", "%xmm2", "%xmm3", \
+                           "%xmm4", "%xmm5", "%xmm6", "%xmm7",)\
+              "memory"\
+        );\
+    }else{\
+        __asm__ volatile(\
+            "1:                         \n\t"\
+            "movdqa 16(%0), %%xmm1      \n\t"\
+            "movdqa   (%0), %%xmm0      \n\t"\
+            "movdqa %%xmm1, %%xmm2      \n\t"\
+            "movdqa %%xmm1, %%xmm3      \n\t"\
+            "movdqa %%xmm1, %%xmm4      \n\t"\
+            "movdqa %%xmm1, %%xmm5      \n\t"\
+            "palignr $10, %%xmm0, %%xmm5 \n\t"\
+            "palignr  $8, %%xmm0, %%xmm4 \n\t"\
+            "palignr  $6, %%xmm0, %%xmm3 \n\t"\
+            "palignr  $4, %%xmm0, %%xmm2 \n\t"\
+            "palignr  $2, %%xmm0, %%xmm1 \n\t"\
+            "paddw  %%xmm5, %%xmm0      \n\t"\
+            "paddw  %%xmm4, %%xmm1      \n\t"\
+            "paddw  %%xmm3, %%xmm2      \n\t"\
+            "psubw  %%xmm1, %%xmm0      \n\t"\
+            "psraw      $2, %%xmm0      \n\t"\
+            "psubw  %%xmm1, %%xmm0      \n\t"\
+            "paddw  %%xmm2, %%xmm0      \n\t"\
+            "psraw      $2, %%xmm0      \n\t"\
+            "paddw  %%xmm2, %%xmm0      \n\t"\
+            "psraw      $6, %%xmm0      \n\t"\
+            "packuswb %%xmm0, %%xmm0    \n\t"\
+            OP(%%xmm0, (%1), %%xmm7, q)\
+            "add $48, %0                \n\t"\
+            "add %3, %1                 \n\t"\
+            "decl %2                    \n\t"\
+            " jnz 1b                    \n\t"\
+            : "+a"(tmp), "+c"(dst), "+g"(h)\
+            : "S"((x86_reg)dstStride)\
+            : XMM_CLOBBERS("%xmm0", "%xmm1", "%xmm2", "%xmm3", \
+                           "%xmm4", "%xmm5", "%xmm6", "%xmm7",)\
+              "memory"\
+        );\
+    }\
+}
+
+#define QPEL_H264_HV_XMM(OPNAME, OP, MMX)\
+static av_noinline void OPNAME ## h264_qpel8or16_hv_lowpass_ ## MMX(uint8_t *dst, int16_t *tmp, uint8_t *src, int dstStride, int tmpStride, int srcStride, int size){\
+          put_h264_qpel8or16_hv1_lowpass_sse2(tmp, src, tmpStride, srcStride, size);\
+    OPNAME ## h264_qpel8or16_hv2_lowpass_ ## MMX(dst, tmp, dstStride, tmpStride, size);\
+}\
+static void OPNAME ## h264_qpel8_hv_lowpass_ ## MMX(uint8_t *dst, int16_t *tmp, uint8_t *src, int dstStride, int tmpStride, int srcStride){\
+    OPNAME ## h264_qpel8or16_hv_lowpass_ ## MMX(dst, tmp, src, dstStride, tmpStride, srcStride, 8);\
+}\
+static void OPNAME ## h264_qpel16_hv_lowpass_ ## MMX(uint8_t *dst, int16_t *tmp, uint8_t *src, int dstStride, int tmpStride, int srcStride){\
+    OPNAME ## h264_qpel8or16_hv_lowpass_ ## MMX(dst, tmp, src, dstStride, tmpStride, srcStride, 16);\
+}\
+
+#define put_pixels8_l2_sse2 put_pixels8_l2_mmx2
+#define avg_pixels8_l2_sse2 avg_pixels8_l2_mmx2
+#define put_pixels16_l2_sse2 put_pixels16_l2_mmx2
+#define avg_pixels16_l2_sse2 avg_pixels16_l2_mmx2
+#define put_pixels8_l2_ssse3 put_pixels8_l2_mmx2
+#define avg_pixels8_l2_ssse3 avg_pixels8_l2_mmx2
+#define put_pixels16_l2_ssse3 put_pixels16_l2_mmx2
+#define avg_pixels16_l2_ssse3 avg_pixels16_l2_mmx2
+
+#define put_pixels8_l2_shift5_sse2 put_pixels8_l2_shift5_mmx2
+#define avg_pixels8_l2_shift5_sse2 avg_pixels8_l2_shift5_mmx2
+#define put_pixels16_l2_shift5_sse2 put_pixels16_l2_shift5_mmx2
+#define avg_pixels16_l2_shift5_sse2 avg_pixels16_l2_shift5_mmx2
+#define put_pixels8_l2_shift5_ssse3 put_pixels8_l2_shift5_mmx2
+#define avg_pixels8_l2_shift5_ssse3 avg_pixels8_l2_shift5_mmx2
+#define put_pixels16_l2_shift5_ssse3 put_pixels16_l2_shift5_mmx2
+#define avg_pixels16_l2_shift5_ssse3 avg_pixels16_l2_shift5_mmx2
+
+#define put_h264_qpel8_h_lowpass_l2_sse2 put_h264_qpel8_h_lowpass_l2_mmx2
+#define avg_h264_qpel8_h_lowpass_l2_sse2 avg_h264_qpel8_h_lowpass_l2_mmx2
+#define put_h264_qpel16_h_lowpass_l2_sse2 put_h264_qpel16_h_lowpass_l2_mmx2
+#define avg_h264_qpel16_h_lowpass_l2_sse2 avg_h264_qpel16_h_lowpass_l2_mmx2
+
+#define put_h264_qpel8_v_lowpass_ssse3 put_h264_qpel8_v_lowpass_sse2
+#define avg_h264_qpel8_v_lowpass_ssse3 avg_h264_qpel8_v_lowpass_sse2
+#define put_h264_qpel16_v_lowpass_ssse3 put_h264_qpel16_v_lowpass_sse2
+#define avg_h264_qpel16_v_lowpass_ssse3 avg_h264_qpel16_v_lowpass_sse2
+
+#define put_h264_qpel8or16_hv2_lowpass_sse2 put_h264_qpel8or16_hv2_lowpass_mmx2
+#define avg_h264_qpel8or16_hv2_lowpass_sse2 avg_h264_qpel8or16_hv2_lowpass_mmx2
+
+#define H264_MC(OPNAME, SIZE, MMX, ALIGN) \
+H264_MC_C(OPNAME, SIZE, MMX, ALIGN)\
+H264_MC_V(OPNAME, SIZE, MMX, ALIGN)\
+H264_MC_H(OPNAME, SIZE, MMX, ALIGN)\
+H264_MC_HV(OPNAME, SIZE, MMX, ALIGN)\
+
+static void put_h264_qpel16_mc00_sse2 (uint8_t *dst, uint8_t *src, int stride){
+    put_pixels16_sse2(dst, src, stride, 16);
+}
+static void avg_h264_qpel16_mc00_sse2 (uint8_t *dst, uint8_t *src, int stride){
+    avg_pixels16_sse2(dst, src, stride, 16);
+}
+#define put_h264_qpel8_mc00_sse2 put_h264_qpel8_mc00_mmx2
+#define avg_h264_qpel8_mc00_sse2 avg_h264_qpel8_mc00_mmx2
+
+#define H264_MC_C(OPNAME, SIZE, MMX, ALIGN) \
+static void OPNAME ## h264_qpel ## SIZE ## _mc00_ ## MMX (uint8_t *dst, uint8_t *src, int stride){\
+    OPNAME ## pixels ## SIZE ## _ ## MMX(dst, src, stride, SIZE);\
+}\
+
+#define H264_MC_H(OPNAME, SIZE, MMX, ALIGN) \
+static void OPNAME ## h264_qpel ## SIZE ## _mc10_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\
+    OPNAME ## h264_qpel ## SIZE ## _h_lowpass_l2_ ## MMX(dst, src, src, stride, stride);\
+}\
+\
+static void OPNAME ## h264_qpel ## SIZE ## _mc20_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\
+    OPNAME ## h264_qpel ## SIZE ## _h_lowpass_ ## MMX(dst, src, stride, stride);\
+}\
+\
+static void OPNAME ## h264_qpel ## SIZE ## _mc30_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\
+    OPNAME ## h264_qpel ## SIZE ## _h_lowpass_l2_ ## MMX(dst, src, src+1, stride, stride);\
+}\
+
+#define H264_MC_V(OPNAME, SIZE, MMX, ALIGN) \
+static void OPNAME ## h264_qpel ## SIZE ## _mc01_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\
+    DECLARE_ALIGNED(ALIGN, uint8_t, temp)[SIZE*SIZE];\
+    put_h264_qpel ## SIZE ## _v_lowpass_ ## MMX(temp, src, SIZE, stride);\
+    OPNAME ## pixels ## SIZE ## _l2_ ## MMX(dst, src, temp, stride, stride, SIZE);\
+}\
+\
+static void OPNAME ## h264_qpel ## SIZE ## _mc02_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\
+    OPNAME ## h264_qpel ## SIZE ## _v_lowpass_ ## MMX(dst, src, stride, stride);\
+}\
+\
+static void OPNAME ## h264_qpel ## SIZE ## _mc03_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\
+    DECLARE_ALIGNED(ALIGN, uint8_t, temp)[SIZE*SIZE];\
+    put_h264_qpel ## SIZE ## _v_lowpass_ ## MMX(temp, src, SIZE, stride);\
+    OPNAME ## pixels ## SIZE ## _l2_ ## MMX(dst, src+stride, temp, stride, stride, SIZE);\
+}\
+
+#define H264_MC_HV(OPNAME, SIZE, MMX, ALIGN) \
+static void OPNAME ## h264_qpel ## SIZE ## _mc11_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\
+    DECLARE_ALIGNED(ALIGN, uint8_t, temp)[SIZE*SIZE];\
+    put_h264_qpel ## SIZE ## _v_lowpass_ ## MMX(temp, src, SIZE, stride);\
+    OPNAME ## h264_qpel ## SIZE ## _h_lowpass_l2_ ## MMX(dst, src, temp, stride, SIZE);\
+}\
+\
+static void OPNAME ## h264_qpel ## SIZE ## _mc31_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\
+    DECLARE_ALIGNED(ALIGN, uint8_t, temp)[SIZE*SIZE];\
+    put_h264_qpel ## SIZE ## _v_lowpass_ ## MMX(temp, src+1, SIZE, stride);\
+    OPNAME ## h264_qpel ## SIZE ## _h_lowpass_l2_ ## MMX(dst, src, temp, stride, SIZE);\
+}\
+\
+static void OPNAME ## h264_qpel ## SIZE ## _mc13_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\
+    DECLARE_ALIGNED(ALIGN, uint8_t, temp)[SIZE*SIZE];\
+    put_h264_qpel ## SIZE ## _v_lowpass_ ## MMX(temp, src, SIZE, stride);\
+    OPNAME ## h264_qpel ## SIZE ## _h_lowpass_l2_ ## MMX(dst, src+stride, temp, stride, SIZE);\
+}\
+\
+static void OPNAME ## h264_qpel ## SIZE ## _mc33_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\
+    DECLARE_ALIGNED(ALIGN, uint8_t, temp)[SIZE*SIZE];\
+    put_h264_qpel ## SIZE ## _v_lowpass_ ## MMX(temp, src+1, SIZE, stride);\
+    OPNAME ## h264_qpel ## SIZE ## _h_lowpass_l2_ ## MMX(dst, src+stride, temp, stride, SIZE);\
+}\
+\
+static void OPNAME ## h264_qpel ## SIZE ## _mc22_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\
+    DECLARE_ALIGNED(ALIGN, uint16_t, temp)[SIZE*(SIZE<8?12:24)];\
+    OPNAME ## h264_qpel ## SIZE ## _hv_lowpass_ ## MMX(dst, temp, src, stride, SIZE, stride);\
+}\
+\
+static void OPNAME ## h264_qpel ## SIZE ## _mc21_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\
+    DECLARE_ALIGNED(ALIGN, uint8_t, temp)[SIZE*(SIZE<8?12:24)*2 + SIZE*SIZE];\
+    uint8_t * const halfHV= temp;\
+    int16_t * const halfV= (int16_t*)(temp + SIZE*SIZE);\
+    assert(((int)temp & 7) == 0);\
+    put_h264_qpel ## SIZE ## _hv_lowpass_ ## MMX(halfHV, halfV, src, SIZE, SIZE, stride);\
+    OPNAME ## h264_qpel ## SIZE ## _h_lowpass_l2_ ## MMX(dst, src, halfHV, stride, SIZE);\
+}\
+\
+static void OPNAME ## h264_qpel ## SIZE ## _mc23_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\
+    DECLARE_ALIGNED(ALIGN, uint8_t, temp)[SIZE*(SIZE<8?12:24)*2 + SIZE*SIZE];\
+    uint8_t * const halfHV= temp;\
+    int16_t * const halfV= (int16_t*)(temp + SIZE*SIZE);\
+    assert(((int)temp & 7) == 0);\
+    put_h264_qpel ## SIZE ## _hv_lowpass_ ## MMX(halfHV, halfV, src, SIZE, SIZE, stride);\
+    OPNAME ## h264_qpel ## SIZE ## _h_lowpass_l2_ ## MMX(dst, src+stride, halfHV, stride, SIZE);\
+}\
+\
+static void OPNAME ## h264_qpel ## SIZE ## _mc12_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\
+    DECLARE_ALIGNED(ALIGN, uint8_t, temp)[SIZE*(SIZE<8?12:24)*2 + SIZE*SIZE];\
+    uint8_t * const halfHV= temp;\
+    int16_t * const halfV= (int16_t*)(temp + SIZE*SIZE);\
+    assert(((int)temp & 7) == 0);\
+    put_h264_qpel ## SIZE ## _hv_lowpass_ ## MMX(halfHV, halfV, src, SIZE, SIZE, stride);\
+    OPNAME ## pixels ## SIZE ## _l2_shift5_ ## MMX(dst, halfV+2, halfHV, stride, SIZE, SIZE);\
+}\
+\
+static void OPNAME ## h264_qpel ## SIZE ## _mc32_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\
+    DECLARE_ALIGNED(ALIGN, uint8_t, temp)[SIZE*(SIZE<8?12:24)*2 + SIZE*SIZE];\
+    uint8_t * const halfHV= temp;\
+    int16_t * const halfV= (int16_t*)(temp + SIZE*SIZE);\
+    assert(((int)temp & 7) == 0);\
+    put_h264_qpel ## SIZE ## _hv_lowpass_ ## MMX(halfHV, halfV, src, SIZE, SIZE, stride);\
+    OPNAME ## pixels ## SIZE ## _l2_shift5_ ## MMX(dst, halfV+3, halfHV, stride, SIZE, SIZE);\
+}\
+
+#define H264_MC_4816(MMX)\
+H264_MC(put_, 4, MMX, 8)\
+H264_MC(put_, 8, MMX, 8)\
+H264_MC(put_, 16,MMX, 8)\
+H264_MC(avg_, 4, MMX, 8)\
+H264_MC(avg_, 8, MMX, 8)\
+H264_MC(avg_, 16,MMX, 8)\
+
+#define H264_MC_816(QPEL, XMM)\
+QPEL(put_, 8, XMM, 16)\
+QPEL(put_, 16,XMM, 16)\
+QPEL(avg_, 8, XMM, 16)\
+QPEL(avg_, 16,XMM, 16)\
+
+
+#define AVG_3DNOW_OP(a,b,temp, size) \
+"mov" #size " " #b ", " #temp "   \n\t"\
+"pavgusb " #temp ", " #a "        \n\t"\
+"mov" #size " " #a ", " #b "      \n\t"
+#define AVG_MMX2_OP(a,b,temp, size) \
+"mov" #size " " #b ", " #temp "   \n\t"\
+"pavgb " #temp ", " #a "          \n\t"\
+"mov" #size " " #a ", " #b "      \n\t"
+
+#define PAVGB "pavgusb"
+QPEL_H264(put_,       PUT_OP, 3dnow)
+QPEL_H264(avg_, AVG_3DNOW_OP, 3dnow)
+#undef PAVGB
+#define PAVGB "pavgb"
+QPEL_H264(put_,       PUT_OP, mmx2)
+QPEL_H264(avg_,  AVG_MMX2_OP, mmx2)
+QPEL_H264_V_XMM(put_,       PUT_OP, sse2)
+QPEL_H264_V_XMM(avg_,  AVG_MMX2_OP, sse2)
+QPEL_H264_HV_XMM(put_,       PUT_OP, sse2)
+QPEL_H264_HV_XMM(avg_,  AVG_MMX2_OP, sse2)
+#if HAVE_SSSE3
+QPEL_H264_H_XMM(put_,       PUT_OP, ssse3)
+QPEL_H264_H_XMM(avg_,  AVG_MMX2_OP, ssse3)
+QPEL_H264_HV2_XMM(put_,       PUT_OP, ssse3)
+QPEL_H264_HV2_XMM(avg_,  AVG_MMX2_OP, ssse3)
+QPEL_H264_HV_XMM(put_,       PUT_OP, ssse3)
+QPEL_H264_HV_XMM(avg_,  AVG_MMX2_OP, ssse3)
+#endif
+#undef PAVGB
+
+H264_MC_4816(3dnow)
+H264_MC_4816(mmx2)
+H264_MC_816(H264_MC_V, sse2)
+H264_MC_816(H264_MC_HV, sse2)
+#if HAVE_SSSE3
+H264_MC_816(H264_MC_H, ssse3)
+H264_MC_816(H264_MC_HV, ssse3)
+#endif
diff --git a/libavcodec/x86/h264_weight.asm b/libavcodec/x86/h264_weight.asm
new file mode 100644
index 0000000..05769fc
--- /dev/null
+++ b/libavcodec/x86/h264_weight.asm
@@ -0,0 +1,375 @@
+;*****************************************************************************
+;* SSE2-optimized weighted prediction code
+;*****************************************************************************
+;* Copyright (c) 2004-2005 Michael Niedermayer, Loren Merritt
+;* Copyright (C) 2010 Eli Friedman <eli.friedman at gmail.com>
+;*
+;* This file is part of Libav.
+;*
+;* Libav is free software; you can redistribute it and/or
+;* modify it under the terms of the GNU Lesser General Public
+;* License as published by the Free Software Foundation; either
+;* version 2.1 of the License, or (at your option) any later version.
+;*
+;* Libav is distributed in the hope that it will be useful,
+;* but WITHOUT ANY WARRANTY; without even the implied warranty of
+;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+;* Lesser General Public License for more details.
+;*
+;* You should have received a copy of the GNU Lesser General Public
+;* License along with Libav; if not, write to the Free Software
+;* 51, Inc., Foundation Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+;******************************************************************************
+
+%include "x86inc.asm"
+
+SECTION .text
+
+;-----------------------------------------------------------------------------
+; biweight pred:
+;
+; void h264_biweight_16x16_sse2(uint8_t *dst, uint8_t *src, int stride,
+;                               int log2_denom, int weightd, int weights,
+;                               int offset);
+; and
+; void h264_weight_16x16_sse2(uint8_t *dst, int stride,
+;                             int log2_denom, int weight,
+;                             int offset);
+;-----------------------------------------------------------------------------
+
+%macro WEIGHT_SETUP 0
+    add        r4, r4
+    inc        r4
+    movd       m3, r3d
+    movd       m5, r4d
+    movd       m6, r2d
+    pslld      m5, m6
+    psrld      m5, 1
+%if mmsize == 16
+    pshuflw    m3, m3, 0
+    pshuflw    m5, m5, 0
+    punpcklqdq m3, m3
+    punpcklqdq m5, m5
+%else
+    pshufw     m3, m3, 0
+    pshufw     m5, m5, 0
+%endif
+    pxor       m7, m7
+%endmacro
+
+%macro WEIGHT_OP 2
+    movh          m0, [r0+%1]
+    movh          m1, [r0+%2]
+    punpcklbw     m0, m7
+    punpcklbw     m1, m7
+    pmullw        m0, m3
+    pmullw        m1, m3
+    paddsw        m0, m5
+    paddsw        m1, m5
+    psraw         m0, m6
+    psraw         m1, m6
+    packuswb      m0, m1
+%endmacro
+
+%macro WEIGHT_FUNC_DBL_MM 1
+cglobal h264_weight_16x%1_mmx2, 5, 5, 0
+    WEIGHT_SETUP
+    mov        r2, %1
+%if %1 == 16
+.nextrow
+    WEIGHT_OP 0,  4
+    mova     [r0  ], m0
+    WEIGHT_OP 8, 12
+    mova     [r0+8], m0
+    add        r0, r1
+    dec        r2
+    jnz .nextrow
+    REP_RET
+%else
+    jmp mangle(ff_h264_weight_16x16_mmx2.nextrow)
+%endif
+%endmacro
+
+INIT_MMX
+WEIGHT_FUNC_DBL_MM 16
+WEIGHT_FUNC_DBL_MM  8
+
+%macro WEIGHT_FUNC_MM 4
+cglobal h264_weight_%1x%2_%4, 7, 7, %3
+    WEIGHT_SETUP
+    mov        r2, %2
+%if %2 == 16
+.nextrow
+    WEIGHT_OP 0, mmsize/2
+    mova     [r0], m0
+    add        r0, r1
+    dec        r2
+    jnz .nextrow
+    REP_RET
+%else
+    jmp mangle(ff_h264_weight_%1x16_%4.nextrow)
+%endif
+%endmacro
+
+INIT_MMX
+WEIGHT_FUNC_MM  8, 16,  0, mmx2
+WEIGHT_FUNC_MM  8,  8,  0, mmx2
+WEIGHT_FUNC_MM  8,  4,  0, mmx2
+INIT_XMM
+WEIGHT_FUNC_MM 16, 16,  8, sse2
+WEIGHT_FUNC_MM 16,  8,  8, sse2
+
+%macro WEIGHT_FUNC_HALF_MM 5
+cglobal h264_weight_%1x%2_%5, 5, 5, %4
+    WEIGHT_SETUP
+    mov        r2, %2/2
+    lea        r3, [r1*2]
+%if %2 == mmsize
+.nextrow
+    WEIGHT_OP 0, r1
+    movh     [r0], m0
+%if mmsize == 16
+    movhps   [r0+r1], m0
+%else
+    psrlq      m0, 32
+    movh     [r0+r1], m0
+%endif
+    add        r0, r3
+    dec        r2
+    jnz .nextrow
+    REP_RET
+%else
+    jmp mangle(ff_h264_weight_%1x%3_%5.nextrow)
+%endif
+%endmacro
+
+INIT_MMX
+WEIGHT_FUNC_HALF_MM 4,  8,  8, 0, mmx2
+WEIGHT_FUNC_HALF_MM 4,  4,  8, 0, mmx2
+WEIGHT_FUNC_HALF_MM 4,  2,  8, 0, mmx2
+INIT_XMM
+WEIGHT_FUNC_HALF_MM 8, 16, 16, 8, sse2
+WEIGHT_FUNC_HALF_MM 8,  8, 16, 8, sse2
+WEIGHT_FUNC_HALF_MM 8,  4, 16, 8, sse2
+
+%macro BIWEIGHT_SETUP 0
+    add        r6, 1
+    or         r6, 1
+    add        r3, 1
+    movd       m3, r4d
+    movd       m4, r5d
+    movd       m5, r6d
+    movd       m6, r3d
+    pslld      m5, m6
+    psrld      m5, 1
+%if mmsize == 16
+    pshuflw    m3, m3, 0
+    pshuflw    m4, m4, 0
+    pshuflw    m5, m5, 0
+    punpcklqdq m3, m3
+    punpcklqdq m4, m4
+    punpcklqdq m5, m5
+%else
+    pshufw     m3, m3, 0
+    pshufw     m4, m4, 0
+    pshufw     m5, m5, 0
+%endif
+    pxor       m7, m7
+%endmacro
+
+%macro BIWEIGHT_STEPA 3
+    movh       m%1, [r0+%3]
+    movh       m%2, [r1+%3]
+    punpcklbw  m%1, m7
+    punpcklbw  m%2, m7
+    pmullw     m%1, m3
+    pmullw     m%2, m4
+    paddsw     m%1, m%2
+%endmacro
+
+%macro BIWEIGHT_STEPB 0
+    paddsw     m0, m5
+    paddsw     m1, m5
+    psraw      m0, m6
+    psraw      m1, m6
+    packuswb   m0, m1
+%endmacro
+
+%macro BIWEIGHT_FUNC_DBL_MM 1
+cglobal h264_biweight_16x%1_mmx2, 7, 7, 0
+    BIWEIGHT_SETUP
+    mov        r3, %1
+%if %1 == 16
+.nextrow
+    BIWEIGHT_STEPA 0, 1, 0
+    BIWEIGHT_STEPA 1, 2, 4
+    BIWEIGHT_STEPB
+    mova       [r0], m0
+    BIWEIGHT_STEPA 0, 1, 8
+    BIWEIGHT_STEPA 1, 2, 12
+    BIWEIGHT_STEPB
+    mova     [r0+8], m0
+    add        r0, r2
+    add        r1, r2
+    dec        r3
+    jnz .nextrow
+    REP_RET
+%else
+    jmp mangle(ff_h264_biweight_16x16_mmx2.nextrow)
+%endif
+%endmacro
+
+INIT_MMX
+BIWEIGHT_FUNC_DBL_MM 16
+BIWEIGHT_FUNC_DBL_MM  8
+
+%macro BIWEIGHT_FUNC_MM 4
+cglobal h264_biweight_%1x%2_%4, 7, 7, %3
+    BIWEIGHT_SETUP
+    mov        r3, %2
+%if %2 == 16
+.nextrow
+    BIWEIGHT_STEPA 0, 1, 0
+    BIWEIGHT_STEPA 1, 2, mmsize/2
+    BIWEIGHT_STEPB
+    mova       [r0], m0
+    add        r0, r2
+    add        r1, r2
+    dec        r3
+    jnz .nextrow
+    REP_RET
+%else
+    jmp mangle(ff_h264_biweight_%1x16_%4.nextrow)
+%endif
+%endmacro
+
+INIT_MMX
+BIWEIGHT_FUNC_MM  8, 16,  0, mmx2
+BIWEIGHT_FUNC_MM  8,  8,  0, mmx2
+BIWEIGHT_FUNC_MM  8,  4,  0, mmx2
+INIT_XMM
+BIWEIGHT_FUNC_MM 16, 16,  8, sse2
+BIWEIGHT_FUNC_MM 16,  8,  8, sse2
+
+%macro BIWEIGHT_FUNC_HALF_MM 5
+cglobal h264_biweight_%1x%2_%5, 7, 7, %4
+    BIWEIGHT_SETUP
+    mov        r3, %2/2
+    lea        r4, [r2*2]
+%if %2 == mmsize
+.nextrow
+    BIWEIGHT_STEPA 0, 1, 0
+    BIWEIGHT_STEPA 1, 2, r2
+    BIWEIGHT_STEPB
+    movh       [r0], m0
+%if mmsize == 16
+    movhps     [r0+r2], m0
+%else
+    psrlq      m0, 32
+    movh       [r0+r2], m0
+%endif
+    add        r0, r4
+    add        r1, r4
+    dec        r3
+    jnz .nextrow
+    REP_RET
+%else
+    jmp mangle(ff_h264_biweight_%1x%3_%5.nextrow)
+%endif
+%endmacro
+
+INIT_MMX
+BIWEIGHT_FUNC_HALF_MM 4,  8,  8, 0, mmx2
+BIWEIGHT_FUNC_HALF_MM 4,  4,  8, 0, mmx2
+BIWEIGHT_FUNC_HALF_MM 4,  2,  8, 0, mmx2
+INIT_XMM
+BIWEIGHT_FUNC_HALF_MM 8, 16, 16, 8, sse2
+BIWEIGHT_FUNC_HALF_MM 8,  8, 16, 8, sse2
+BIWEIGHT_FUNC_HALF_MM 8,  4, 16, 8, sse2
+
+%macro BIWEIGHT_SSSE3_SETUP 0
+    add        r6, 1
+    or         r6, 1
+    add        r3, 1
+    movd       m4, r4d
+    movd       m0, r5d
+    movd       m5, r6d
+    movd       m6, r3d
+    pslld      m5, m6
+    psrld      m5, 1
+    punpcklbw  m4, m0
+    pshuflw    m4, m4, 0
+    pshuflw    m5, m5, 0
+    punpcklqdq m4, m4
+    punpcklqdq m5, m5
+%endmacro
+
+%macro BIWEIGHT_SSSE3_OP 0
+    pmaddubsw  m0, m4
+    pmaddubsw  m2, m4
+    paddsw     m0, m5
+    paddsw     m2, m5
+    psraw      m0, m6
+    psraw      m2, m6
+    packuswb   m0, m2
+%endmacro
+
+%macro BIWEIGHT_SSSE3_16 1
+cglobal h264_biweight_16x%1_ssse3, 7, 7, 8
+    BIWEIGHT_SSSE3_SETUP
+    mov        r3, %1
+
+%if %1 == 16
+.nextrow
+    movh       m0, [r0]
+    movh       m2, [r0+8]
+    movh       m3, [r1+8]
+    punpcklbw  m0, [r1]
+    punpcklbw  m2, m3
+    BIWEIGHT_SSSE3_OP
+    mova       [r0], m0
+    add        r0, r2
+    add        r1, r2
+    dec        r3
+    jnz .nextrow
+    REP_RET
+%else
+    jmp mangle(ff_h264_biweight_16x16_ssse3.nextrow)
+%endif
+%endmacro
+
+INIT_XMM
+BIWEIGHT_SSSE3_16 16
+BIWEIGHT_SSSE3_16  8
+
+%macro BIWEIGHT_SSSE3_8 1
+cglobal h264_biweight_8x%1_ssse3, 7, 7, 8
+    BIWEIGHT_SSSE3_SETUP
+    mov        r3, %1/2
+    lea        r4, [r2*2]
+
+%if %1 == 16
+.nextrow
+    movh       m0, [r0]
+    movh       m1, [r1]
+    movh       m2, [r0+r2]
+    movh       m3, [r1+r2]
+    punpcklbw  m0, m1
+    punpcklbw  m2, m3
+    BIWEIGHT_SSSE3_OP
+    movh       [r0], m0
+    movhps     [r0+r2], m0
+    add        r0, r4
+    add        r1, r4
+    dec        r3
+    jnz .nextrow
+    REP_RET
+%else
+    jmp mangle(ff_h264_biweight_8x16_ssse3.nextrow)
+%endif
+%endmacro
+
+INIT_XMM
+BIWEIGHT_SSSE3_8 16
+BIWEIGHT_SSSE3_8  8
+BIWEIGHT_SSSE3_8  4
diff --git a/libavcodec/x86/h264dsp_mmx.c b/libavcodec/x86/h264dsp_mmx.c
index fd16a02..9f004a5 100644
--- a/libavcodec/x86/h264dsp_mmx.c
+++ b/libavcodec/x86/h264dsp_mmx.c
@@ -1,800 +1,186 @@
 /*
  * Copyright (c) 2004-2005 Michael Niedermayer, Loren Merritt
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/cpu.h"
+#include "libavutil/x86_cpu.h"
+#include "libavcodec/h264dsp.h"
 #include "dsputil_mmx.h"
 
 DECLARE_ALIGNED(8, static const uint64_t, ff_pb_3_1  ) = 0x0103010301030103ULL;
-DECLARE_ALIGNED(8, static const uint64_t, ff_pb_7_3  ) = 0x0307030703070307ULL;
 
 /***********************************/
 /* IDCT */
 
-#define SUMSUB_BADC( a, b, c, d ) \
-    "paddw "#b", "#a" \n\t"\
-    "paddw "#d", "#c" \n\t"\
-    "paddw "#b", "#b" \n\t"\
-    "paddw "#d", "#d" \n\t"\
-    "psubw "#a", "#b" \n\t"\
-    "psubw "#c", "#d" \n\t"
-
-#define SUMSUBD2_AB( a, b, t ) \
-    "movq  "#b", "#t" \n\t"\
-    "psraw  $1 , "#b" \n\t"\
-    "paddw "#a", "#b" \n\t"\
-    "psraw  $1 , "#a" \n\t"\
-    "psubw "#t", "#a" \n\t"
-
-#define IDCT4_1D( s02, s13, d02, d13, t ) \
-    SUMSUB_BA  ( s02, d02 )\
-    SUMSUBD2_AB( s13, d13, t )\
-    SUMSUB_BADC( d13, s02, s13, d02 )
-
-#define STORE_DIFF_4P( p, t, z ) \
-    "psraw      $6,     "#p" \n\t"\
-    "movd       (%0),   "#t" \n\t"\
-    "punpcklbw "#z",    "#t" \n\t"\
-    "paddsw    "#t",    "#p" \n\t"\
-    "packuswb  "#z",    "#p" \n\t"\
-    "movd      "#p",    (%0) \n\t"
-
-static void ff_h264_idct_add_mmx(uint8_t *dst, int16_t *block, int stride)
-{
-    /* Load dct coeffs */
-    __asm__ volatile(
-        "movq   (%0), %%mm0 \n\t"
-        "movq  8(%0), %%mm1 \n\t"
-        "movq 16(%0), %%mm2 \n\t"
-        "movq 24(%0), %%mm3 \n\t"
-    :: "r"(block) );
-
-    __asm__ volatile(
-        /* mm1=s02+s13  mm2=s02-s13  mm4=d02+d13  mm0=d02-d13 */
-        IDCT4_1D( %%mm2, %%mm1, %%mm0, %%mm3, %%mm4 )
-
-        "movq      %0,    %%mm6 \n\t"
-        /* in: 1,4,0,2  out: 1,2,3,0 */
-        TRANSPOSE4( %%mm3, %%mm1, %%mm0, %%mm2, %%mm4 )
-
-        "paddw     %%mm6, %%mm3 \n\t"
-
-        /* mm2=s02+s13  mm3=s02-s13  mm4=d02+d13  mm1=d02-d13 */
-        IDCT4_1D( %%mm4, %%mm2, %%mm3, %%mm0, %%mm1 )
-
-        "pxor %%mm7, %%mm7    \n\t"
-    :: "m"(ff_pw_32));
-
-    __asm__ volatile(
-    STORE_DIFF_4P( %%mm0, %%mm1, %%mm7)
-        "add %1, %0             \n\t"
-    STORE_DIFF_4P( %%mm2, %%mm1, %%mm7)
-        "add %1, %0             \n\t"
-    STORE_DIFF_4P( %%mm3, %%mm1, %%mm7)
-        "add %1, %0             \n\t"
-    STORE_DIFF_4P( %%mm4, %%mm1, %%mm7)
-        : "+r"(dst)
-        : "r" ((x86_reg)stride)
-    );
-}
-
-static inline void h264_idct8_1d(int16_t *block)
-{
-    __asm__ volatile(
-        "movq 112(%0), %%mm7  \n\t"
-        "movq  80(%0), %%mm0  \n\t"
-        "movq  48(%0), %%mm3  \n\t"
-        "movq  16(%0), %%mm5  \n\t"
-
-        "movq   %%mm0, %%mm4  \n\t"
-        "movq   %%mm5, %%mm1  \n\t"
-        "psraw  $1,    %%mm4  \n\t"
-        "psraw  $1,    %%mm1  \n\t"
-        "paddw  %%mm0, %%mm4  \n\t"
-        "paddw  %%mm5, %%mm1  \n\t"
-        "paddw  %%mm7, %%mm4  \n\t"
-        "paddw  %%mm0, %%mm1  \n\t"
-        "psubw  %%mm5, %%mm4  \n\t"
-        "paddw  %%mm3, %%mm1  \n\t"
-
-        "psubw  %%mm3, %%mm5  \n\t"
-        "psubw  %%mm3, %%mm0  \n\t"
-        "paddw  %%mm7, %%mm5  \n\t"
-        "psubw  %%mm7, %%mm0  \n\t"
-        "psraw  $1,    %%mm3  \n\t"
-        "psraw  $1,    %%mm7  \n\t"
-        "psubw  %%mm3, %%mm5  \n\t"
-        "psubw  %%mm7, %%mm0  \n\t"
-
-        "movq   %%mm4, %%mm3  \n\t"
-        "movq   %%mm1, %%mm7  \n\t"
-        "psraw  $2,    %%mm1  \n\t"
-        "psraw  $2,    %%mm3  \n\t"
-        "paddw  %%mm5, %%mm3  \n\t"
-        "psraw  $2,    %%mm5  \n\t"
-        "paddw  %%mm0, %%mm1  \n\t"
-        "psraw  $2,    %%mm0  \n\t"
-        "psubw  %%mm4, %%mm5  \n\t"
-        "psubw  %%mm0, %%mm7  \n\t"
-
-        "movq  32(%0), %%mm2  \n\t"
-        "movq  96(%0), %%mm6  \n\t"
-        "movq   %%mm2, %%mm4  \n\t"
-        "movq   %%mm6, %%mm0  \n\t"
-        "psraw  $1,    %%mm4  \n\t"
-        "psraw  $1,    %%mm6  \n\t"
-        "psubw  %%mm0, %%mm4  \n\t"
-        "paddw  %%mm2, %%mm6  \n\t"
-
-        "movq    (%0), %%mm2  \n\t"
-        "movq  64(%0), %%mm0  \n\t"
-        SUMSUB_BA( %%mm0, %%mm2 )
-        SUMSUB_BA( %%mm6, %%mm0 )
-        SUMSUB_BA( %%mm4, %%mm2 )
-        SUMSUB_BA( %%mm7, %%mm6 )
-        SUMSUB_BA( %%mm5, %%mm4 )
-        SUMSUB_BA( %%mm3, %%mm2 )
-        SUMSUB_BA( %%mm1, %%mm0 )
-        :: "r"(block)
-    );
-}
-
-static void ff_h264_idct8_add_mmx(uint8_t *dst, int16_t *block, int stride)
-{
-    int i;
-    DECLARE_ALIGNED(8, int16_t, b2)[64];
-
-    block[0] += 32;
-
-    for(i=0; i<2; i++){
-        DECLARE_ALIGNED(8, uint64_t, tmp);
-
-        h264_idct8_1d(block+4*i);
-
-        __asm__ volatile(
-            "movq   %%mm7,    %0   \n\t"
-            TRANSPOSE4( %%mm0, %%mm2, %%mm4, %%mm6, %%mm7 )
-            "movq   %%mm0,  8(%1)  \n\t"
-            "movq   %%mm6, 24(%1)  \n\t"
-            "movq   %%mm7, 40(%1)  \n\t"
-            "movq   %%mm4, 56(%1)  \n\t"
-            "movq    %0,    %%mm7  \n\t"
-            TRANSPOSE4( %%mm7, %%mm5, %%mm3, %%mm1, %%mm0 )
-            "movq   %%mm7,   (%1)  \n\t"
-            "movq   %%mm1, 16(%1)  \n\t"
-            "movq   %%mm0, 32(%1)  \n\t"
-            "movq   %%mm3, 48(%1)  \n\t"
-            : "=m"(tmp)
-            : "r"(b2+32*i)
-            : "memory"
-        );
-    }
-
-    for(i=0; i<2; i++){
-        h264_idct8_1d(b2+4*i);
-
-        __asm__ volatile(
-            "psraw     $6, %%mm7  \n\t"
-            "psraw     $6, %%mm6  \n\t"
-            "psraw     $6, %%mm5  \n\t"
-            "psraw     $6, %%mm4  \n\t"
-            "psraw     $6, %%mm3  \n\t"
-            "psraw     $6, %%mm2  \n\t"
-            "psraw     $6, %%mm1  \n\t"
-            "psraw     $6, %%mm0  \n\t"
-
-            "movq   %%mm7,    (%0)  \n\t"
-            "movq   %%mm5,  16(%0)  \n\t"
-            "movq   %%mm3,  32(%0)  \n\t"
-            "movq   %%mm1,  48(%0)  \n\t"
-            "movq   %%mm0,  64(%0)  \n\t"
-            "movq   %%mm2,  80(%0)  \n\t"
-            "movq   %%mm4,  96(%0)  \n\t"
-            "movq   %%mm6, 112(%0)  \n\t"
-            :: "r"(b2+4*i)
-            : "memory"
-        );
-    }
-
-    add_pixels_clamped_mmx(b2, dst, stride);
-}
-
-#define STORE_DIFF_8P( p, d, t, z )\
-        "movq       "#d", "#t" \n"\
-        "psraw       $6,  "#p" \n"\
-        "punpcklbw  "#z", "#t" \n"\
-        "paddsw     "#t", "#p" \n"\
-        "packuswb   "#p", "#p" \n"\
-        "movq       "#p", "#d" \n"
-
-#define H264_IDCT8_1D_SSE2(a,b,c,d,e,f,g,h)\
-        "movdqa     "#c", "#a" \n"\
-        "movdqa     "#g", "#e" \n"\
-        "psraw       $1,  "#c" \n"\
-        "psraw       $1,  "#g" \n"\
-        "psubw      "#e", "#c" \n"\
-        "paddw      "#a", "#g" \n"\
-        "movdqa     "#b", "#e" \n"\
-        "psraw       $1,  "#e" \n"\
-        "paddw      "#b", "#e" \n"\
-        "paddw      "#d", "#e" \n"\
-        "paddw      "#f", "#e" \n"\
-        "movdqa     "#f", "#a" \n"\
-        "psraw       $1,  "#a" \n"\
-        "paddw      "#f", "#a" \n"\
-        "paddw      "#h", "#a" \n"\
-        "psubw      "#b", "#a" \n"\
-        "psubw      "#d", "#b" \n"\
-        "psubw      "#d", "#f" \n"\
-        "paddw      "#h", "#b" \n"\
-        "psubw      "#h", "#f" \n"\
-        "psraw       $1,  "#d" \n"\
-        "psraw       $1,  "#h" \n"\
-        "psubw      "#d", "#b" \n"\
-        "psubw      "#h", "#f" \n"\
-        "movdqa     "#e", "#d" \n"\
-        "movdqa     "#a", "#h" \n"\
-        "psraw       $2,  "#d" \n"\
-        "psraw       $2,  "#h" \n"\
-        "paddw      "#f", "#d" \n"\
-        "paddw      "#b", "#h" \n"\
-        "psraw       $2,  "#f" \n"\
-        "psraw       $2,  "#b" \n"\
-        "psubw      "#f", "#e" \n"\
-        "psubw      "#a", "#b" \n"\
-        "movdqa 0x00(%1), "#a" \n"\
-        "movdqa 0x40(%1), "#f" \n"\
-        SUMSUB_BA(f, a)\
-        SUMSUB_BA(g, f)\
-        SUMSUB_BA(c, a)\
-        SUMSUB_BA(e, g)\
-        SUMSUB_BA(b, c)\
-        SUMSUB_BA(h, a)\
-        SUMSUB_BA(d, f)
-
-static void ff_h264_idct8_add_sse2(uint8_t *dst, int16_t *block, int stride)
-{
-    __asm__ volatile(
-        "movdqa   0x10(%1), %%xmm1 \n"
-        "movdqa   0x20(%1), %%xmm2 \n"
-        "movdqa   0x30(%1), %%xmm3 \n"
-        "movdqa   0x50(%1), %%xmm5 \n"
-        "movdqa   0x60(%1), %%xmm6 \n"
-        "movdqa   0x70(%1), %%xmm7 \n"
-        H264_IDCT8_1D_SSE2(%%xmm0, %%xmm1, %%xmm2, %%xmm3, %%xmm4, %%xmm5, %%xmm6, %%xmm7)
-        TRANSPOSE8(%%xmm4, %%xmm1, %%xmm7, %%xmm3, %%xmm5, %%xmm0, %%xmm2, %%xmm6, (%1))
-        "paddw          %4, %%xmm4 \n"
-        "movdqa     %%xmm4, 0x00(%1) \n"
-        "movdqa     %%xmm2, 0x40(%1) \n"
-        H264_IDCT8_1D_SSE2(%%xmm4, %%xmm0, %%xmm6, %%xmm3, %%xmm2, %%xmm5, %%xmm7, %%xmm1)
-        "movdqa     %%xmm6, 0x60(%1) \n"
-        "movdqa     %%xmm7, 0x70(%1) \n"
-        "pxor       %%xmm7, %%xmm7 \n"
-        STORE_DIFF_8P(%%xmm2, (%0),      %%xmm6, %%xmm7)
-        STORE_DIFF_8P(%%xmm0, (%0,%2),   %%xmm6, %%xmm7)
-        STORE_DIFF_8P(%%xmm1, (%0,%2,2), %%xmm6, %%xmm7)
-        STORE_DIFF_8P(%%xmm3, (%0,%3),   %%xmm6, %%xmm7)
-        "lea     (%0,%2,4), %0 \n"
-        STORE_DIFF_8P(%%xmm5, (%0),      %%xmm6, %%xmm7)
-        STORE_DIFF_8P(%%xmm4, (%0,%2),   %%xmm6, %%xmm7)
-        "movdqa   0x60(%1), %%xmm0 \n"
-        "movdqa   0x70(%1), %%xmm1 \n"
-        STORE_DIFF_8P(%%xmm0, (%0,%2,2), %%xmm6, %%xmm7)
-        STORE_DIFF_8P(%%xmm1, (%0,%3),   %%xmm6, %%xmm7)
-        :"+r"(dst)
-        :"r"(block), "r"((x86_reg)stride), "r"((x86_reg)3L*stride), "m"(ff_pw_32)
-    );
-}
-
-static void ff_h264_idct_dc_add_mmx2(uint8_t *dst, int16_t *block, int stride)
-{
-    int dc = (block[0] + 32) >> 6;
-    __asm__ volatile(
-        "movd          %0, %%mm0 \n\t"
-        "pshufw $0, %%mm0, %%mm0 \n\t"
-        "pxor       %%mm1, %%mm1 \n\t"
-        "psubw      %%mm0, %%mm1 \n\t"
-        "packuswb   %%mm0, %%mm0 \n\t"
-        "packuswb   %%mm1, %%mm1 \n\t"
-        ::"r"(dc)
-    );
-    __asm__ volatile(
-        "movd          %0, %%mm2 \n\t"
-        "movd          %1, %%mm3 \n\t"
-        "movd          %2, %%mm4 \n\t"
-        "movd          %3, %%mm5 \n\t"
-        "paddusb    %%mm0, %%mm2 \n\t"
-        "paddusb    %%mm0, %%mm3 \n\t"
-        "paddusb    %%mm0, %%mm4 \n\t"
-        "paddusb    %%mm0, %%mm5 \n\t"
-        "psubusb    %%mm1, %%mm2 \n\t"
-        "psubusb    %%mm1, %%mm3 \n\t"
-        "psubusb    %%mm1, %%mm4 \n\t"
-        "psubusb    %%mm1, %%mm5 \n\t"
-        "movd       %%mm2, %0    \n\t"
-        "movd       %%mm3, %1    \n\t"
-        "movd       %%mm4, %2    \n\t"
-        "movd       %%mm5, %3    \n\t"
-        :"+m"(*(uint32_t*)(dst+0*stride)),
-         "+m"(*(uint32_t*)(dst+1*stride)),
-         "+m"(*(uint32_t*)(dst+2*stride)),
-         "+m"(*(uint32_t*)(dst+3*stride))
-    );
-}
-
-static void ff_h264_idct8_dc_add_mmx2(uint8_t *dst, int16_t *block, int stride)
-{
-    int dc = (block[0] + 32) >> 6;
-    int y;
-    __asm__ volatile(
-        "movd          %0, %%mm0 \n\t"
-        "pshufw $0, %%mm0, %%mm0 \n\t"
-        "pxor       %%mm1, %%mm1 \n\t"
-        "psubw      %%mm0, %%mm1 \n\t"
-        "packuswb   %%mm0, %%mm0 \n\t"
-        "packuswb   %%mm1, %%mm1 \n\t"
-        ::"r"(dc)
-    );
-    for(y=2; y--; dst += 4*stride){
-    __asm__ volatile(
-        "movq          %0, %%mm2 \n\t"
-        "movq          %1, %%mm3 \n\t"
-        "movq          %2, %%mm4 \n\t"
-        "movq          %3, %%mm5 \n\t"
-        "paddusb    %%mm0, %%mm2 \n\t"
-        "paddusb    %%mm0, %%mm3 \n\t"
-        "paddusb    %%mm0, %%mm4 \n\t"
-        "paddusb    %%mm0, %%mm5 \n\t"
-        "psubusb    %%mm1, %%mm2 \n\t"
-        "psubusb    %%mm1, %%mm3 \n\t"
-        "psubusb    %%mm1, %%mm4 \n\t"
-        "psubusb    %%mm1, %%mm5 \n\t"
-        "movq       %%mm2, %0    \n\t"
-        "movq       %%mm3, %1    \n\t"
-        "movq       %%mm4, %2    \n\t"
-        "movq       %%mm5, %3    \n\t"
-        :"+m"(*(uint64_t*)(dst+0*stride)),
-         "+m"(*(uint64_t*)(dst+1*stride)),
-         "+m"(*(uint64_t*)(dst+2*stride)),
-         "+m"(*(uint64_t*)(dst+3*stride))
-    );
-    }
-}
-
-//FIXME this table is a duplicate from h264data.h, and will be removed once the tables from, h264 have been split
-static const uint8_t scan8[16 + 2*4]={
- 4+1*8, 5+1*8, 4+2*8, 5+2*8,
- 6+1*8, 7+1*8, 6+2*8, 7+2*8,
- 4+3*8, 5+3*8, 4+4*8, 5+4*8,
- 6+3*8, 7+3*8, 6+4*8, 7+4*8,
- 1+1*8, 2+1*8,
- 1+2*8, 2+2*8,
- 1+4*8, 2+4*8,
- 1+5*8, 2+5*8,
-};
-
-static void ff_h264_idct_add16_mmx(uint8_t *dst, const int *block_offset, DCTELEM *block, int stride, const uint8_t nnzc[6*8]){
-    int i;
-    for(i=0; i<16; i++){
-        if(nnzc[ scan8[i] ])
-            ff_h264_idct_add_mmx(dst + block_offset[i], block + i*16, stride);
-    }
-}
-
-static void ff_h264_idct8_add4_mmx(uint8_t *dst, const int *block_offset, DCTELEM *block, int stride, const uint8_t nnzc[6*8]){
-    int i;
-    for(i=0; i<16; i+=4){
-        if(nnzc[ scan8[i] ])
-            ff_h264_idct8_add_mmx(dst + block_offset[i], block + i*16, stride);
-    }
-}
-
-
-static void ff_h264_idct_add16_mmx2(uint8_t *dst, const int *block_offset, DCTELEM *block, int stride, const uint8_t nnzc[6*8]){
-    int i;
-    for(i=0; i<16; i++){
-        int nnz = nnzc[ scan8[i] ];
-        if(nnz){
-            if(nnz==1 && block[i*16]) ff_h264_idct_dc_add_mmx2(dst + block_offset[i], block + i*16, stride);
-            else                      ff_h264_idct_add_mmx    (dst + block_offset[i], block + i*16, stride);
-        }
-    }
-}
-
-static void ff_h264_idct_add16intra_mmx(uint8_t *dst, const int *block_offset, DCTELEM *block, int stride, const uint8_t nnzc[6*8]){
-    int i;
-    for(i=0; i<16; i++){
-        if(nnzc[ scan8[i] ] || block[i*16])
-            ff_h264_idct_add_mmx(dst + block_offset[i], block + i*16, stride);
-    }
-}
-
-static void ff_h264_idct_add16intra_mmx2(uint8_t *dst, const int *block_offset, DCTELEM *block, int stride, const uint8_t nnzc[6*8]){
-    int i;
-    for(i=0; i<16; i++){
-        if(nnzc[ scan8[i] ]) ff_h264_idct_add_mmx    (dst + block_offset[i], block + i*16, stride);
-        else if(block[i*16]) ff_h264_idct_dc_add_mmx2(dst + block_offset[i], block + i*16, stride);
-    }
-}
-
-static void ff_h264_idct8_add4_mmx2(uint8_t *dst, const int *block_offset, DCTELEM *block, int stride, const uint8_t nnzc[6*8]){
-    int i;
-    for(i=0; i<16; i+=4){
-        int nnz = nnzc[ scan8[i] ];
-        if(nnz){
-            if(nnz==1 && block[i*16]) ff_h264_idct8_dc_add_mmx2(dst + block_offset[i], block + i*16, stride);
-            else                      ff_h264_idct8_add_mmx    (dst + block_offset[i], block + i*16, stride);
-        }
-    }
-}
-
-static void ff_h264_idct8_add4_sse2(uint8_t *dst, const int *block_offset, DCTELEM *block, int stride, const uint8_t nnzc[6*8]){
-    int i;
-    for(i=0; i<16; i+=4){
-        int nnz = nnzc[ scan8[i] ];
-        if(nnz){
-            if(nnz==1 && block[i*16]) ff_h264_idct8_dc_add_mmx2(dst + block_offset[i], block + i*16, stride);
-            else                      ff_h264_idct8_add_sse2   (dst + block_offset[i], block + i*16, stride);
-        }
-    }
-}
-
-static void ff_h264_idct_add8_mmx(uint8_t **dest, const int *block_offset, DCTELEM *block, int stride, const uint8_t nnzc[6*8]){
-    int i;
-    for(i=16; i<16+8; i++){
-        if(nnzc[ scan8[i] ] || block[i*16])
-            ff_h264_idct_add_mmx    (dest[(i&4)>>2] + block_offset[i], block + i*16, stride);
-    }
-}
-
-static void ff_h264_idct_add8_mmx2(uint8_t **dest, const int *block_offset, DCTELEM *block, int stride, const uint8_t nnzc[6*8]){
-    int i;
-    for(i=16; i<16+8; i++){
-        if(nnzc[ scan8[i] ])
-            ff_h264_idct_add_mmx    (dest[(i&4)>>2] + block_offset[i], block + i*16, stride);
-        else if(block[i*16])
-            ff_h264_idct_dc_add_mmx2(dest[(i&4)>>2] + block_offset[i], block + i*16, stride);
-    }
-}
-
-#if CONFIG_GPL && HAVE_YASM
-static void ff_h264_idct_dc_add8_mmx2(uint8_t *dst, int16_t *block, int stride)
-{
-    __asm__ volatile(
-        "movd             %0, %%mm0 \n\t"   //  0 0 X D
-        "punpcklwd        %1, %%mm0 \n\t"   //  x X d D
-        "paddsw           %2, %%mm0 \n\t"
-        "psraw            $6, %%mm0 \n\t"
-        "punpcklwd     %%mm0, %%mm0 \n\t"   //  d d D D
-        "pxor          %%mm1, %%mm1 \n\t"   //  0 0 0 0
-        "psubw         %%mm0, %%mm1 \n\t"   // -d-d-D-D
-        "packuswb      %%mm1, %%mm0 \n\t"   // -d-d-D-D d d D D
-        "pshufw $0xFA, %%mm0, %%mm1 \n\t"   // -d-d-d-d-D-D-D-D
-        "punpcklwd     %%mm0, %%mm0 \n\t"   //  d d d d D D D D
-        ::"m"(block[ 0]),
-          "m"(block[16]),
-          "m"(ff_pw_32)
-    );
-    __asm__ volatile(
-        "movq          %0, %%mm2 \n\t"
-        "movq          %1, %%mm3 \n\t"
-        "movq          %2, %%mm4 \n\t"
-        "movq          %3, %%mm5 \n\t"
-        "paddusb    %%mm0, %%mm2 \n\t"
-        "paddusb    %%mm0, %%mm3 \n\t"
-        "paddusb    %%mm0, %%mm4 \n\t"
-        "paddusb    %%mm0, %%mm5 \n\t"
-        "psubusb    %%mm1, %%mm2 \n\t"
-        "psubusb    %%mm1, %%mm3 \n\t"
-        "psubusb    %%mm1, %%mm4 \n\t"
-        "psubusb    %%mm1, %%mm5 \n\t"
-        "movq       %%mm2, %0    \n\t"
-        "movq       %%mm3, %1    \n\t"
-        "movq       %%mm4, %2    \n\t"
-        "movq       %%mm5, %3    \n\t"
-        :"+m"(*(uint64_t*)(dst+0*stride)),
-         "+m"(*(uint64_t*)(dst+1*stride)),
-         "+m"(*(uint64_t*)(dst+2*stride)),
-         "+m"(*(uint64_t*)(dst+3*stride))
-    );
-}
-
-extern void ff_x264_add8x4_idct_sse2(uint8_t *dst, int16_t *block, int stride);
-
-static void ff_h264_idct_add16_sse2(uint8_t *dst, const int *block_offset, DCTELEM *block, int stride, const uint8_t nnzc[6*8]){
-    int i;
-    for(i=0; i<16; i+=2)
-        if(nnzc[ scan8[i+0] ]|nnzc[ scan8[i+1] ])
-            ff_x264_add8x4_idct_sse2 (dst + block_offset[i], block + i*16, stride);
-}
-
-static void ff_h264_idct_add16intra_sse2(uint8_t *dst, const int *block_offset, DCTELEM *block, int stride, const uint8_t nnzc[6*8]){
-    int i;
-    for(i=0; i<16; i+=2){
-        if(nnzc[ scan8[i+0] ]|nnzc[ scan8[i+1] ])
-            ff_x264_add8x4_idct_sse2 (dst + block_offset[i], block + i*16, stride);
-        else if(block[i*16]|block[i*16+16])
-            ff_h264_idct_dc_add8_mmx2(dst + block_offset[i], block + i*16, stride);
-    }
-}
-
-static void ff_h264_idct_add8_sse2(uint8_t **dest, const int *block_offset, DCTELEM *block, int stride, const uint8_t nnzc[6*8]){
-    int i;
-    for(i=16; i<16+8; i+=2){
-        if(nnzc[ scan8[i+0] ]|nnzc[ scan8[i+1] ])
-            ff_x264_add8x4_idct_sse2 (dest[(i&4)>>2] + block_offset[i], block + i*16, stride);
-        else if(block[i*16]|block[i*16+16])
-            ff_h264_idct_dc_add8_mmx2(dest[(i&4)>>2] + block_offset[i], block + i*16, stride);
-    }
-}
-#endif
+void ff_h264_idct_add_mmx     (uint8_t *dst, int16_t *block, int stride);
+void ff_h264_idct8_add_mmx    (uint8_t *dst, int16_t *block, int stride);
+void ff_h264_idct8_add_sse2   (uint8_t *dst, int16_t *block, int stride);
+void ff_h264_idct_dc_add_mmx2 (uint8_t *dst, int16_t *block, int stride);
+void ff_h264_idct8_dc_add_mmx2(uint8_t *dst, int16_t *block, int stride);
+
+void ff_h264_idct_add16_mmx      (uint8_t *dst, const int *block_offset,
+                                  DCTELEM *block, int stride, const uint8_t nnzc[6*8]);
+void ff_h264_idct8_add4_mmx      (uint8_t *dst, const int *block_offset,
+                                  DCTELEM *block, int stride, const uint8_t nnzc[6*8]);
+void ff_h264_idct_add16_mmx2     (uint8_t *dst, const int *block_offset,
+                                  DCTELEM *block, int stride, const uint8_t nnzc[6*8]);
+void ff_h264_idct_add16intra_mmx (uint8_t *dst, const int *block_offset,
+                                  DCTELEM *block, int stride, const uint8_t nnzc[6*8]);
+void ff_h264_idct_add16intra_mmx2(uint8_t *dst, const int *block_offset,
+                                  DCTELEM *block, int stride, const uint8_t nnzc[6*8]);
+void ff_h264_idct8_add4_mmx2     (uint8_t *dst, const int *block_offset,
+                                  DCTELEM *block, int stride, const uint8_t nnzc[6*8]);
+void ff_h264_idct8_add4_sse2     (uint8_t *dst, const int *block_offset,
+                                  DCTELEM *block, int stride, const uint8_t nnzc[6*8]);
+void ff_h264_idct_add8_mmx       (uint8_t **dest, const int *block_offset,
+                                  DCTELEM *block, int stride, const uint8_t nnzc[6*8]);
+void ff_h264_idct_add8_mmx2      (uint8_t **dest, const int *block_offset,
+                                  DCTELEM *block, int stride, const uint8_t nnzc[6*8]);
+
+void ff_h264_idct_add16_sse2     (uint8_t *dst, const int *block_offset, DCTELEM *block,
+                                  int stride, const uint8_t nnzc[6*8]);
+void ff_h264_idct_add16intra_sse2(uint8_t *dst, const int *block_offset, DCTELEM *block,
+                                  int stride, const uint8_t nnzc[6*8]);
+void ff_h264_idct_add8_sse2      (uint8_t **dest, const int *block_offset, DCTELEM *block,
+                                  int stride, const uint8_t nnzc[6*8]);
+void ff_h264_luma_dc_dequant_idct_mmx (DCTELEM *output, DCTELEM *input, int qmul);
+void ff_h264_luma_dc_dequant_idct_sse2(DCTELEM *output, DCTELEM *input, int qmul);
 
 /***********************************/
 /* deblocking */
 
-// out: o = |x-y|>a
-// clobbers: t
-#define DIFF_GT_MMX(x,y,a,o,t)\
-    "movq     "#y", "#t"  \n\t"\
-    "movq     "#x", "#o"  \n\t"\
-    "psubusb  "#x", "#t"  \n\t"\
-    "psubusb  "#y", "#o"  \n\t"\
-    "por      "#t", "#o"  \n\t"\
-    "psubusb  "#a", "#o"  \n\t"
-
-// out: o = |x-y|>a
-// clobbers: t
-#define DIFF_GT2_MMX(x,y,a,o,t)\
-    "movq     "#y", "#t"  \n\t"\
-    "movq     "#x", "#o"  \n\t"\
-    "psubusb  "#x", "#t"  \n\t"\
-    "psubusb  "#y", "#o"  \n\t"\
-    "psubusb  "#a", "#t"  \n\t"\
-    "psubusb  "#a", "#o"  \n\t"\
-    "pcmpeqb  "#t", "#o"  \n\t"\
-
-// in: mm0=p1 mm1=p0 mm2=q0 mm3=q1
-// out: mm5=beta-1, mm7=mask
-// clobbers: mm4,mm6
-#define H264_DEBLOCK_MASK(alpha1, beta1) \
-    "pshufw $0, "#alpha1", %%mm4 \n\t"\
-    "pshufw $0, "#beta1 ", %%mm5 \n\t"\
-    "packuswb  %%mm4, %%mm4      \n\t"\
-    "packuswb  %%mm5, %%mm5      \n\t"\
-    DIFF_GT_MMX(%%mm1, %%mm2, %%mm4, %%mm7, %%mm6) /* |p0-q0| > alpha-1 */\
-    DIFF_GT_MMX(%%mm0, %%mm1, %%mm5, %%mm4, %%mm6) /* |p1-p0| > beta-1 */\
-    "por       %%mm4, %%mm7      \n\t"\
-    DIFF_GT_MMX(%%mm3, %%mm2, %%mm5, %%mm4, %%mm6) /* |q1-q0| > beta-1 */\
-    "por       %%mm4, %%mm7      \n\t"\
-    "pxor      %%mm6, %%mm6      \n\t"\
-    "pcmpeqb   %%mm6, %%mm7      \n\t"
-
-// in: mm0=p1 mm1=p0 mm2=q0 mm3=q1 mm7=(tc&mask)
-// out: mm1=p0' mm2=q0'
-// clobbers: mm0,3-6
-#define H264_DEBLOCK_P0_Q0(pb_01, pb_3f)\
-        "movq    %%mm1              , %%mm5 \n\t"\
-        "pxor    %%mm2              , %%mm5 \n\t" /* p0^q0*/\
-        "pand    "#pb_01"           , %%mm5 \n\t" /* (p0^q0)&1*/\
-        "pcmpeqb %%mm4              , %%mm4 \n\t"\
-        "pxor    %%mm4              , %%mm3 \n\t"\
-        "pavgb   %%mm0              , %%mm3 \n\t" /* (p1 - q1 + 256)>>1*/\
-        "pavgb   "MANGLE(ff_pb_3)"  , %%mm3 \n\t" /*(((p1 - q1 + 256)>>1)+4)>>1 = 64+2+(p1-q1)>>2*/\
-        "pxor    %%mm1              , %%mm4 \n\t"\
-        "pavgb   %%mm2              , %%mm4 \n\t" /* (q0 - p0 + 256)>>1*/\
-        "pavgb   %%mm5              , %%mm3 \n\t"\
-        "paddusb %%mm4              , %%mm3 \n\t" /* d+128+33*/\
-        "movq    "MANGLE(ff_pb_A1)" , %%mm6 \n\t"\
-        "psubusb %%mm3              , %%mm6 \n\t"\
-        "psubusb "MANGLE(ff_pb_A1)" , %%mm3 \n\t"\
-        "pminub  %%mm7              , %%mm6 \n\t"\
-        "pminub  %%mm7              , %%mm3 \n\t"\
-        "psubusb %%mm6              , %%mm1 \n\t"\
-        "psubusb %%mm3              , %%mm2 \n\t"\
-        "paddusb %%mm3              , %%mm1 \n\t"\
-        "paddusb %%mm6              , %%mm2 \n\t"
-
-// in: mm0=p1 mm1=p0 mm2=q0 mm3=q1 mm7=(tc&mask) %8=ff_bone
-// out: (q1addr) = av_clip( (q2+((p0+q0+1)>>1))>>1, q1-tc0, q1+tc0 )
-// clobbers: q2, tmp, tc0
-#define H264_DEBLOCK_Q1(p1, q2, q2addr, q1addr, tc0, tmp)\
-        "movq     %%mm1,  "#tmp"   \n\t"\
-        "pavgb    %%mm2,  "#tmp"   \n\t"\
-        "pavgb    "#tmp", "#q2"    \n\t" /* avg(p2,avg(p0,q0)) */\
-        "pxor   "q2addr", "#tmp"   \n\t"\
-        "pand     %9,     "#tmp"   \n\t" /* (p2^avg(p0,q0))&1 */\
-        "psubusb  "#tmp", "#q2"    \n\t" /* (p2+((p0+q0+1)>>1))>>1 */\
-        "movq     "#p1",  "#tmp"   \n\t"\
-        "psubusb  "#tc0", "#tmp"   \n\t"\
-        "paddusb  "#p1",  "#tc0"   \n\t"\
-        "pmaxub   "#tmp", "#q2"    \n\t"\
-        "pminub   "#tc0", "#q2"    \n\t"\
-        "movq     "#q2",  "q1addr" \n\t"
-
-static inline void h264_loop_filter_luma_mmx2(uint8_t *pix, int stride, int alpha1, int beta1, int8_t *tc0)
-{
-    DECLARE_ALIGNED(8, uint64_t, tmp0)[2];
-
-    __asm__ volatile(
-        "movq    (%2,%4), %%mm0    \n\t" //p1
-        "movq    (%2,%4,2), %%mm1  \n\t" //p0
-        "movq    (%3),    %%mm2    \n\t" //q0
-        "movq    (%3,%4), %%mm3    \n\t" //q1
-        H264_DEBLOCK_MASK(%7, %8)
-
-        "movd      %6,    %%mm4    \n\t"
-        "punpcklbw %%mm4, %%mm4    \n\t"
-        "punpcklwd %%mm4, %%mm4    \n\t"
-        "pcmpeqb   %%mm3, %%mm3    \n\t"
-        "movq      %%mm4, %%mm6    \n\t"
-        "pcmpgtb   %%mm3, %%mm4    \n\t"
-        "movq      %%mm6, %1       \n\t"
-        "pand      %%mm4, %%mm7    \n\t"
-        "movq      %%mm7, %0       \n\t"
-
-        /* filter p1 */
-        "movq     (%2),   %%mm3    \n\t" //p2
-        DIFF_GT2_MMX(%%mm1, %%mm3, %%mm5, %%mm6, %%mm4) // |p2-p0|>beta-1
-        "pand     %%mm7,  %%mm6    \n\t" // mask & |p2-p0|<beta
-        "pand     %1,     %%mm7    \n\t" // mask & tc0
-        "movq     %%mm7,  %%mm4    \n\t"
-        "psubb    %%mm6,  %%mm7    \n\t"
-        "pand     %%mm4,  %%mm6    \n\t" // mask & |p2-p0|<beta & tc0
-        H264_DEBLOCK_Q1(%%mm0, %%mm3, "(%2)", "(%2,%4)", %%mm6, %%mm4)
-
-        /* filter q1 */
-        "movq    (%3,%4,2), %%mm4  \n\t" //q2
-        DIFF_GT2_MMX(%%mm2, %%mm4, %%mm5, %%mm6, %%mm3) // |q2-q0|>beta-1
-        "pand     %0,     %%mm6    \n\t"
-        "movq     %1,     %%mm5    \n\t" // can be merged with the and below but is slower then
-        "pand     %%mm6,  %%mm5    \n\t"
-        "psubb    %%mm6,  %%mm7    \n\t"
-        "movq    (%3,%4), %%mm3    \n\t"
-        H264_DEBLOCK_Q1(%%mm3, %%mm4, "(%3,%4,2)", "(%3,%4)", %%mm5, %%mm6)
-
-        /* filter p0, q0 */
-        H264_DEBLOCK_P0_Q0(%9, unused)
-        "movq      %%mm1, (%2,%4,2) \n\t"
-        "movq      %%mm2, (%3)      \n\t"
-
-        : "=m"(tmp0[0]), "=m"(tmp0[1])
-        : "r"(pix-3*stride), "r"(pix), "r"((x86_reg)stride),
-          "m"(*tmp0/*unused*/), "m"(*(uint32_t*)tc0), "m"(alpha1), "m"(beta1),
-          "m"(ff_bone)
-    );
-}
-
-static void h264_v_loop_filter_luma_mmx2(uint8_t *pix, int stride, int alpha, int beta, int8_t *tc0)
-{
-    if((tc0[0] & tc0[1]) >= 0)
-        h264_loop_filter_luma_mmx2(pix, stride, alpha-1, beta-1, tc0);
-    if((tc0[2] & tc0[3]) >= 0)
-        h264_loop_filter_luma_mmx2(pix+8, stride, alpha-1, beta-1, tc0+2);
-}
-static void h264_h_loop_filter_luma_mmx2(uint8_t *pix, int stride, int alpha, int beta, int8_t *tc0)
-{
-    //FIXME: could cut some load/stores by merging transpose with filter
-    // also, it only needs to transpose 6x8
-    DECLARE_ALIGNED(8, uint8_t, trans)[8*8];
-    int i;
-    for(i=0; i<2; i++, pix+=8*stride, tc0+=2) {
-        if((tc0[0] & tc0[1]) < 0)
-            continue;
-        transpose4x4(trans,       pix-4,          8, stride);
-        transpose4x4(trans  +4*8, pix,            8, stride);
-        transpose4x4(trans+4,     pix-4+4*stride, 8, stride);
-        transpose4x4(trans+4+4*8, pix  +4*stride, 8, stride);
-        h264_loop_filter_luma_mmx2(trans+4*8, 8, alpha-1, beta-1, tc0);
-        transpose4x4(pix-2,          trans  +2*8, stride, 8);
-        transpose4x4(pix-2+4*stride, trans+4+2*8, stride, 8);
-    }
-}
-
-static inline void h264_loop_filter_chroma_mmx2(uint8_t *pix, int stride, int alpha1, int beta1, int8_t *tc0)
-{
-    __asm__ volatile(
-        "movq    (%0),    %%mm0     \n\t" //p1
-        "movq    (%0,%2), %%mm1     \n\t" //p0
-        "movq    (%1),    %%mm2     \n\t" //q0
-        "movq    (%1,%2), %%mm3     \n\t" //q1
-        H264_DEBLOCK_MASK(%4, %5)
-        "movd      %3,    %%mm6     \n\t"
-        "punpcklbw %%mm6, %%mm6     \n\t"
-        "pand      %%mm6, %%mm7     \n\t" // mm7 = tc&mask
-        H264_DEBLOCK_P0_Q0(%6, %7)
-        "movq      %%mm1, (%0,%2)   \n\t"
-        "movq      %%mm2, (%1)      \n\t"
-
-        :: "r"(pix-2*stride), "r"(pix), "r"((x86_reg)stride),
-           "r"(*(uint32_t*)tc0),
-           "m"(alpha1), "m"(beta1), "m"(ff_bone), "m"(ff_pb_3F)
-    );
-}
-
-static void h264_v_loop_filter_chroma_mmx2(uint8_t *pix, int stride, int alpha, int beta, int8_t *tc0)
-{
-    h264_loop_filter_chroma_mmx2(pix, stride, alpha-1, beta-1, tc0);
-}
-
-static void h264_h_loop_filter_chroma_mmx2(uint8_t *pix, int stride, int alpha, int beta, int8_t *tc0)
-{
-    //FIXME: could cut some load/stores by merging transpose with filter
-    DECLARE_ALIGNED(8, uint8_t, trans)[8*4];
-    transpose4x4(trans, pix-2, 8, stride);
-    transpose4x4(trans+4, pix-2+4*stride, 8, stride);
-    h264_loop_filter_chroma_mmx2(trans+2*8, 8, alpha-1, beta-1, tc0);
-    transpose4x4(pix-2, trans, stride, 8);
-    transpose4x4(pix-2+4*stride, trans+4, stride, 8);
-}
-
-// p0 = (p0 + q1 + 2*p1 + 2) >> 2
-#define H264_FILTER_CHROMA4(p0, p1, q1, one) \
-    "movq    "#p0", %%mm4  \n\t"\
-    "pxor    "#q1", %%mm4  \n\t"\
-    "pand   "#one", %%mm4  \n\t" /* mm4 = (p0^q1)&1 */\
-    "pavgb   "#q1", "#p0"  \n\t"\
-    "psubusb %%mm4, "#p0"  \n\t"\
-    "pavgb   "#p1", "#p0"  \n\t" /* dst = avg(p1, avg(p0,q1) - ((p0^q1)&1)) */\
-
-static inline void h264_loop_filter_chroma_intra_mmx2(uint8_t *pix, int stride, int alpha1, int beta1)
-{
-    __asm__ volatile(
-        "movq    (%0),    %%mm0     \n\t"
-        "movq    (%0,%2), %%mm1     \n\t"
-        "movq    (%1),    %%mm2     \n\t"
-        "movq    (%1,%2), %%mm3     \n\t"
-        H264_DEBLOCK_MASK(%3, %4)
-        "movq    %%mm1,   %%mm5     \n\t"
-        "movq    %%mm2,   %%mm6     \n\t"
-        H264_FILTER_CHROMA4(%%mm1, %%mm0, %%mm3, %5) //p0'
-        H264_FILTER_CHROMA4(%%mm2, %%mm3, %%mm0, %5) //q0'
-        "psubb   %%mm5,   %%mm1     \n\t"
-        "psubb   %%mm6,   %%mm2     \n\t"
-        "pand    %%mm7,   %%mm1     \n\t"
-        "pand    %%mm7,   %%mm2     \n\t"
-        "paddb   %%mm5,   %%mm1     \n\t"
-        "paddb   %%mm6,   %%mm2     \n\t"
-        "movq    %%mm1,   (%0,%2)   \n\t"
-        "movq    %%mm2,   (%1)      \n\t"
-        :: "r"(pix-2*stride), "r"(pix), "r"((x86_reg)stride),
-           "m"(alpha1), "m"(beta1), "m"(ff_bone)
-    );
-}
-
-static void h264_v_loop_filter_chroma_intra_mmx2(uint8_t *pix, int stride, int alpha, int beta)
-{
-    h264_loop_filter_chroma_intra_mmx2(pix, stride, alpha-1, beta-1);
-}
-
-static void h264_h_loop_filter_chroma_intra_mmx2(uint8_t *pix, int stride, int alpha, int beta)
-{
-    //FIXME: could cut some load/stores by merging transpose with filter
-    DECLARE_ALIGNED(8, uint8_t, trans)[8*4];
-    transpose4x4(trans, pix-2, 8, stride);
-    transpose4x4(trans+4, pix-2+4*stride, 8, stride);
-    h264_loop_filter_chroma_intra_mmx2(trans+2*8, 8, alpha-1, beta-1);
-    transpose4x4(pix-2, trans, stride, 8);
-    transpose4x4(pix-2+4*stride, trans+4, stride, 8);
-}
+#define h264_loop_filter_strength_iteration_mmx2(bS, nz, ref, mv, bidir, edges, step, mask_mv, dir, d_idx, mask_dir) \
+    do { \
+        x86_reg b_idx; \
+        mask_mv <<= 3; \
+        for( b_idx=0; b_idx<edges; b_idx+=step ) { \
+            if (!mask_dir) \
+            __asm__ volatile( \
+                    "pxor %%mm0, %%mm0 \n\t" \
+                    :: \
+            ); \
+            if(!(mask_mv & b_idx)) { \
+                if(bidir) { \
+                    __asm__ volatile( \
+                        "movd         %a3(%0,%2), %%mm2 \n" \
+                        "punpckldq    %a4(%0,%2), %%mm2 \n" /* { ref0[bn], ref1[bn] } */ \
+                        "pshufw $0x44, 12(%0,%2), %%mm0 \n" /* { ref0[b], ref0[b] } */ \
+                        "pshufw $0x44, 52(%0,%2), %%mm1 \n" /* { ref1[b], ref1[b] } */ \
+                        "pshufw $0x4E, %%mm2, %%mm3 \n" \
+                        "psubb         %%mm2, %%mm0 \n" /* { ref0[b]!=ref0[bn], ref0[b]!=ref1[bn] } */ \
+                        "psubb         %%mm3, %%mm1 \n" /* { ref1[b]!=ref1[bn], ref1[b]!=ref0[bn] } */ \
+ \
+                        "por           %%mm1, %%mm0 \n" \
+                        "movq   %a5(%1,%2,4), %%mm1 \n" \
+                        "movq   %a6(%1,%2,4), %%mm2 \n" \
+                        "movq          %%mm1, %%mm3 \n" \
+                        "movq          %%mm2, %%mm4 \n" \
+                        "psubw   48(%1,%2,4), %%mm1 \n" \
+                        "psubw   56(%1,%2,4), %%mm2 \n" \
+                        "psubw  208(%1,%2,4), %%mm3 \n" \
+                        "psubw  216(%1,%2,4), %%mm4 \n" \
+                        "packsswb      %%mm2, %%mm1 \n" \
+                        "packsswb      %%mm4, %%mm3 \n" \
+                        "paddb         %%mm6, %%mm1 \n" \
+                        "paddb         %%mm6, %%mm3 \n" \
+                        "psubusb       %%mm5, %%mm1 \n" /* abs(mv[b] - mv[bn]) >= limit */ \
+                        "psubusb       %%mm5, %%mm3 \n" \
+                        "packsswb      %%mm3, %%mm1 \n" \
+ \
+                        "por           %%mm1, %%mm0 \n" \
+                        "movq   %a7(%1,%2,4), %%mm1 \n" \
+                        "movq   %a8(%1,%2,4), %%mm2 \n" \
+                        "movq          %%mm1, %%mm3 \n" \
+                        "movq          %%mm2, %%mm4 \n" \
+                        "psubw   48(%1,%2,4), %%mm1 \n" \
+                        "psubw   56(%1,%2,4), %%mm2 \n" \
+                        "psubw  208(%1,%2,4), %%mm3 \n" \
+                        "psubw  216(%1,%2,4), %%mm4 \n" \
+                        "packsswb      %%mm2, %%mm1 \n" \
+                        "packsswb      %%mm4, %%mm3 \n" \
+                        "paddb         %%mm6, %%mm1 \n" \
+                        "paddb         %%mm6, %%mm3 \n" \
+                        "psubusb       %%mm5, %%mm1 \n" /* abs(mv[b] - mv[bn]) >= limit */ \
+                        "psubusb       %%mm5, %%mm3 \n" \
+                        "packsswb      %%mm3, %%mm1 \n" \
+ \
+                        "pshufw $0x4E, %%mm1, %%mm1 \n" \
+                        "por           %%mm1, %%mm0 \n" \
+                        "pshufw $0x4E, %%mm0, %%mm1 \n" \
+                        "pminub        %%mm1, %%mm0 \n" \
+                        ::"r"(ref), \
+                          "r"(mv), \
+                          "r"(b_idx), \
+                          "i"(d_idx+12), \
+                          "i"(d_idx+52), \
+                          "i"(d_idx*4+48), \
+                          "i"(d_idx*4+56), \
+                          "i"(d_idx*4+208), \
+                          "i"(d_idx*4+216) \
+                    ); \
+                } else { \
+                    __asm__ volatile( \
+                        "movd   12(%0,%2), %%mm0 \n" \
+                        "psubb %a3(%0,%2), %%mm0 \n" /* ref[b] != ref[bn] */ \
+                        "movq   48(%1,%2,4), %%mm1 \n" \
+                        "movq   56(%1,%2,4), %%mm2 \n" \
+                        "psubw %a4(%1,%2,4), %%mm1 \n" \
+                        "psubw %a5(%1,%2,4), %%mm2 \n" \
+                        "packsswb   %%mm2, %%mm1 \n" \
+                        "paddb      %%mm6, %%mm1 \n" \
+                        "psubusb    %%mm5, %%mm1 \n" /* abs(mv[b] - mv[bn]) >= limit */ \
+                        "packsswb   %%mm1, %%mm1 \n" \
+                        "por        %%mm1, %%mm0 \n" \
+                        ::"r"(ref), \
+                          "r"(mv), \
+                          "r"(b_idx), \
+                          "i"(d_idx+12), \
+                          "i"(d_idx*4+48), \
+                          "i"(d_idx*4+56) \
+                    ); \
+                } \
+            } \
+            __asm__ volatile( \
+                "movd 12(%0,%1), %%mm1 \n" \
+                "por %a2(%0,%1), %%mm1 \n" /* nnz[b] || nnz[bn] */ \
+                ::"r"(nnz), \
+                  "r"(b_idx), \
+                  "i"(d_idx+12) \
+            ); \
+            __asm__ volatile( \
+                "pminub    %%mm7, %%mm1 \n" \
+                "pminub    %%mm7, %%mm0 \n" \
+                "psllw        $1, %%mm1 \n" \
+                "pxor      %%mm2, %%mm2 \n" \
+                "pmaxub    %%mm0, %%mm1 \n" \
+                "punpcklbw %%mm2, %%mm1 \n" \
+                "movq      %%mm1, %a1(%0,%2) \n" \
+                ::"r"(bS), \
+                  "i"(32*dir), \
+                  "r"(b_idx) \
+                :"memory" \
+            ); \
+        } \
+    } while (0)
 
 static void h264_loop_filter_strength_mmx2( int16_t bS[2][4][4], uint8_t nnz[40], int8_t ref[2][40], int16_t mv[2][40][2],
                                             int bidir, int edges, int step, int mask_mv0, int mask_mv1, int field ) {
-    int dir;
     __asm__ volatile(
         "movq %0, %%mm7 \n"
         "movq %1, %%mm6 \n"
@@ -812,95 +198,11 @@ static void h264_loop_filter_strength_mmx2( int16_t bS[2][4][4], uint8_t nnz[40]
 
     // could do a special case for dir==0 && edges==1, but it only reduces the
     // average filter time by 1.2%
-    for( dir=1; dir>=0; dir-- ) {
-        const x86_reg d_idx = dir ? -8 : -1;
-        const int mask_mv = dir ? mask_mv1 : mask_mv0;
-        DECLARE_ALIGNED(8, const uint64_t, mask_dir) = dir ? 0 : 0xffffffffffffffffULL;
-        int b_idx, edge;
-        for( b_idx=12, edge=0; edge<edges; edge+=step, b_idx+=8*step ) {
-            __asm__ volatile(
-                "pand %0, %%mm0 \n\t"
-                ::"m"(mask_dir)
-            );
-            if(!(mask_mv & edge)) {
-                if(bidir) {
-                    __asm__ volatile(
-                        "movd         (%1,%0), %%mm2 \n"
-                        "punpckldq  40(%1,%0), %%mm2 \n" // { ref0[bn], ref1[bn] }
-                        "pshufw $0x44,   (%1), %%mm0 \n" // { ref0[b], ref0[b] }
-                        "pshufw $0x44, 40(%1), %%mm1 \n" // { ref1[b], ref1[b] }
-                        "pshufw $0x4E, %%mm2, %%mm3 \n"
-                        "psubb         %%mm2, %%mm0 \n" // { ref0[b]!=ref0[bn], ref0[b]!=ref1[bn] }
-                        "psubb         %%mm3, %%mm1 \n" // { ref1[b]!=ref1[bn], ref1[b]!=ref0[bn] }
-                        "1: \n"
-                        "por           %%mm1, %%mm0 \n"
-                        "movq      (%2,%0,4), %%mm1 \n"
-                        "movq     8(%2,%0,4), %%mm2 \n"
-                        "movq          %%mm1, %%mm3 \n"
-                        "movq          %%mm2, %%mm4 \n"
-                        "psubw          (%2), %%mm1 \n"
-                        "psubw         8(%2), %%mm2 \n"
-                        "psubw       160(%2), %%mm3 \n"
-                        "psubw       168(%2), %%mm4 \n"
-                        "packsswb      %%mm2, %%mm1 \n"
-                        "packsswb      %%mm4, %%mm3 \n"
-                        "paddb         %%mm6, %%mm1 \n"
-                        "paddb         %%mm6, %%mm3 \n"
-                        "psubusb       %%mm5, %%mm1 \n" // abs(mv[b] - mv[bn]) >= limit
-                        "psubusb       %%mm5, %%mm3 \n"
-                        "packsswb      %%mm3, %%mm1 \n"
-                        "add $40, %0 \n"
-                        "cmp $40, %0 \n"
-                        "jl 1b \n"
-                        "sub $80, %0 \n"
-                        "pshufw $0x4E, %%mm1, %%mm1 \n"
-                        "por           %%mm1, %%mm0 \n"
-                        "pshufw $0x4E, %%mm0, %%mm1 \n"
-                        "pminub        %%mm1, %%mm0 \n"
-                        ::"r"(d_idx),
-                          "r"(ref[0]+b_idx),
-                          "r"(mv[0]+b_idx)
-                    );
-                } else {
-                    __asm__ volatile(
-                        "movd        (%1), %%mm0 \n"
-                        "psubb    (%1,%0), %%mm0 \n" // ref[b] != ref[bn]
-                        "movq        (%2), %%mm1 \n"
-                        "movq       8(%2), %%mm2 \n"
-                        "psubw  (%2,%0,4), %%mm1 \n"
-                        "psubw 8(%2,%0,4), %%mm2 \n"
-                        "packsswb   %%mm2, %%mm1 \n"
-                        "paddb      %%mm6, %%mm1 \n"
-                        "psubusb    %%mm5, %%mm1 \n" // abs(mv[b] - mv[bn]) >= limit
-                        "packsswb   %%mm1, %%mm1 \n"
-                        "por        %%mm1, %%mm0 \n"
-                        ::"r"(d_idx),
-                          "r"(ref[0]+b_idx),
-                          "r"(mv[0]+b_idx)
-                    );
-                }
-            }
-            __asm__ volatile(
-                "movd %0, %%mm1 \n"
-                "por  %1, %%mm1 \n" // nnz[b] || nnz[bn]
-                ::"m"(nnz[b_idx]),
-                  "m"(nnz[b_idx+d_idx])
-            );
-            __asm__ volatile(
-                "pminub    %%mm7, %%mm1 \n"
-                "pminub    %%mm7, %%mm0 \n"
-                "psllw        $1, %%mm1 \n"
-                "pxor      %%mm2, %%mm2 \n"
-                "pmaxub    %%mm0, %%mm1 \n"
-                "punpcklbw %%mm2, %%mm1 \n"
-                "movq      %%mm1, %0    \n"
-                :"=m"(*bS[dir][edge])
-                ::"memory"
-            );
-        }
-        edges = 4;
-        step = 1;
-    }
+    step  <<= 3;
+    edges <<= 3;
+    h264_loop_filter_strength_iteration_mmx2(bS, nnz, ref, mv, bidir, edges, step, mask_mv1, 1, -8,  0);
+    h264_loop_filter_strength_iteration_mmx2(bS, nnz, ref, mv, bidir,    32,    8, mask_mv0, 0, -1, -1);
+
     __asm__ volatile(
         "movq   (%0), %%mm0 \n\t"
         "movq  8(%0), %%mm1 \n\t"
@@ -916,1409 +218,165 @@ static void h264_loop_filter_strength_mmx2( int16_t bS[2][4][4], uint8_t nnz[40]
     );
 }
 
-/***********************************/
-/* motion compensation */
-
-#define QPEL_H264V_MM(A,B,C,D,E,F,OP,T,Z,d,q)\
-        "mov"#q" "#C", "#T"         \n\t"\
-        "mov"#d" (%0), "#F"         \n\t"\
-        "paddw "#D", "#T"           \n\t"\
-        "psllw $2, "#T"             \n\t"\
-        "psubw "#B", "#T"           \n\t"\
-        "psubw "#E", "#T"           \n\t"\
-        "punpcklbw "#Z", "#F"       \n\t"\
-        "pmullw %4, "#T"            \n\t"\
-        "paddw %5, "#A"             \n\t"\
-        "add %2, %0                 \n\t"\
-        "paddw "#F", "#A"           \n\t"\
-        "paddw "#A", "#T"           \n\t"\
-        "psraw $5, "#T"             \n\t"\
-        "packuswb "#T", "#T"        \n\t"\
-        OP(T, (%1), A, d)\
-        "add %3, %1                 \n\t"
-
-#define QPEL_H264HV_MM(A,B,C,D,E,F,OF,T,Z,d,q)\
-        "mov"#q" "#C", "#T"         \n\t"\
-        "mov"#d" (%0), "#F"         \n\t"\
-        "paddw "#D", "#T"           \n\t"\
-        "psllw $2, "#T"             \n\t"\
-        "paddw %4, "#A"             \n\t"\
-        "psubw "#B", "#T"           \n\t"\
-        "psubw "#E", "#T"           \n\t"\
-        "punpcklbw "#Z", "#F"       \n\t"\
-        "pmullw %3, "#T"            \n\t"\
-        "paddw "#F", "#A"           \n\t"\
-        "add %2, %0                 \n\t"\
-        "paddw "#A", "#T"           \n\t"\
-        "mov"#q" "#T", "#OF"(%1)    \n\t"
-
-#define QPEL_H264V(A,B,C,D,E,F,OP) QPEL_H264V_MM(A,B,C,D,E,F,OP,%%mm6,%%mm7,d,q)
-#define QPEL_H264HV(A,B,C,D,E,F,OF) QPEL_H264HV_MM(A,B,C,D,E,F,OF,%%mm6,%%mm7,d,q)
-#define QPEL_H264V_XMM(A,B,C,D,E,F,OP) QPEL_H264V_MM(A,B,C,D,E,F,OP,%%xmm6,%%xmm7,q,dqa)
-#define QPEL_H264HV_XMM(A,B,C,D,E,F,OF) QPEL_H264HV_MM(A,B,C,D,E,F,OF,%%xmm6,%%xmm7,q,dqa)
-
-
-#define QPEL_H264(OPNAME, OP, MMX)\
-static av_noinline void OPNAME ## h264_qpel4_h_lowpass_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride){\
-    int h=4;\
-\
-    __asm__ volatile(\
-        "pxor %%mm7, %%mm7          \n\t"\
-        "movq "MANGLE(ff_pw_5) ", %%mm4\n\t"\
-        "movq "MANGLE(ff_pw_16)", %%mm5\n\t"\
-        "1:                         \n\t"\
-        "movd  -1(%0), %%mm1        \n\t"\
-        "movd    (%0), %%mm2        \n\t"\
-        "movd   1(%0), %%mm3        \n\t"\
-        "movd   2(%0), %%mm0        \n\t"\
-        "punpcklbw %%mm7, %%mm1     \n\t"\
-        "punpcklbw %%mm7, %%mm2     \n\t"\
-        "punpcklbw %%mm7, %%mm3     \n\t"\
-        "punpcklbw %%mm7, %%mm0     \n\t"\
-        "paddw %%mm0, %%mm1         \n\t"\
-        "paddw %%mm3, %%mm2         \n\t"\
-        "movd  -2(%0), %%mm0        \n\t"\
-        "movd   3(%0), %%mm3        \n\t"\
-        "punpcklbw %%mm7, %%mm0     \n\t"\
-        "punpcklbw %%mm7, %%mm3     \n\t"\
-        "paddw %%mm3, %%mm0         \n\t"\
-        "psllw $2, %%mm2            \n\t"\
-        "psubw %%mm1, %%mm2         \n\t"\
-        "pmullw %%mm4, %%mm2        \n\t"\
-        "paddw %%mm5, %%mm0         \n\t"\
-        "paddw %%mm2, %%mm0         \n\t"\
-        "psraw $5, %%mm0            \n\t"\
-        "packuswb %%mm0, %%mm0      \n\t"\
-        OP(%%mm0, (%1),%%mm6, d)\
-        "add %3, %0                 \n\t"\
-        "add %4, %1                 \n\t"\
-        "decl %2                    \n\t"\
-        " jnz 1b                    \n\t"\
-        : "+a"(src), "+c"(dst), "+g"(h)\
-        : "d"((x86_reg)srcStride), "S"((x86_reg)dstStride)\
-        : "memory"\
-    );\
-}\
-static av_noinline void OPNAME ## h264_qpel4_h_lowpass_l2_ ## MMX(uint8_t *dst, uint8_t *src, uint8_t *src2, int dstStride, int src2Stride){\
-    int h=4;\
-    __asm__ volatile(\
-        "pxor %%mm7, %%mm7          \n\t"\
-        "movq %0, %%mm4             \n\t"\
-        "movq %1, %%mm5             \n\t"\
-        :: "m"(ff_pw_5), "m"(ff_pw_16)\
-    );\
-    do{\
-    __asm__ volatile(\
-        "movd  -1(%0), %%mm1        \n\t"\
-        "movd    (%0), %%mm2        \n\t"\
-        "movd   1(%0), %%mm3        \n\t"\
-        "movd   2(%0), %%mm0        \n\t"\
-        "punpcklbw %%mm7, %%mm1     \n\t"\
-        "punpcklbw %%mm7, %%mm2     \n\t"\
-        "punpcklbw %%mm7, %%mm3     \n\t"\
-        "punpcklbw %%mm7, %%mm0     \n\t"\
-        "paddw %%mm0, %%mm1         \n\t"\
-        "paddw %%mm3, %%mm2         \n\t"\
-        "movd  -2(%0), %%mm0        \n\t"\
-        "movd   3(%0), %%mm3        \n\t"\
-        "punpcklbw %%mm7, %%mm0     \n\t"\
-        "punpcklbw %%mm7, %%mm3     \n\t"\
-        "paddw %%mm3, %%mm0         \n\t"\
-        "psllw $2, %%mm2            \n\t"\
-        "psubw %%mm1, %%mm2         \n\t"\
-        "pmullw %%mm4, %%mm2        \n\t"\
-        "paddw %%mm5, %%mm0         \n\t"\
-        "paddw %%mm2, %%mm0         \n\t"\
-        "movd   (%2), %%mm3         \n\t"\
-        "psraw $5, %%mm0            \n\t"\
-        "packuswb %%mm0, %%mm0      \n\t"\
-        PAVGB" %%mm3, %%mm0         \n\t"\
-        OP(%%mm0, (%1),%%mm6, d)\
-        "add %4, %0                 \n\t"\
-        "add %4, %1                 \n\t"\
-        "add %3, %2                 \n\t"\
-        : "+a"(src), "+c"(dst), "+d"(src2)\
-        : "D"((x86_reg)src2Stride), "S"((x86_reg)dstStride)\
-        : "memory"\
-    );\
-    }while(--h);\
-}\
-static av_noinline void OPNAME ## h264_qpel4_v_lowpass_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride){\
-    src -= 2*srcStride;\
-    __asm__ volatile(\
-        "pxor %%mm7, %%mm7          \n\t"\
-        "movd (%0), %%mm0           \n\t"\
-        "add %2, %0                 \n\t"\
-        "movd (%0), %%mm1           \n\t"\
-        "add %2, %0                 \n\t"\
-        "movd (%0), %%mm2           \n\t"\
-        "add %2, %0                 \n\t"\
-        "movd (%0), %%mm3           \n\t"\
-        "add %2, %0                 \n\t"\
-        "movd (%0), %%mm4           \n\t"\
-        "add %2, %0                 \n\t"\
-        "punpcklbw %%mm7, %%mm0     \n\t"\
-        "punpcklbw %%mm7, %%mm1     \n\t"\
-        "punpcklbw %%mm7, %%mm2     \n\t"\
-        "punpcklbw %%mm7, %%mm3     \n\t"\
-        "punpcklbw %%mm7, %%mm4     \n\t"\
-        QPEL_H264V(%%mm0, %%mm1, %%mm2, %%mm3, %%mm4, %%mm5, OP)\
-        QPEL_H264V(%%mm1, %%mm2, %%mm3, %%mm4, %%mm5, %%mm0, OP)\
-        QPEL_H264V(%%mm2, %%mm3, %%mm4, %%mm5, %%mm0, %%mm1, OP)\
-        QPEL_H264V(%%mm3, %%mm4, %%mm5, %%mm0, %%mm1, %%mm2, OP)\
-         \
-        : "+a"(src), "+c"(dst)\
-        : "S"((x86_reg)srcStride), "D"((x86_reg)dstStride), "m"(ff_pw_5), "m"(ff_pw_16)\
-        : "memory"\
-    );\
-}\
-static av_noinline void OPNAME ## h264_qpel4_hv_lowpass_ ## MMX(uint8_t *dst, int16_t *tmp, uint8_t *src, int dstStride, int tmpStride, int srcStride){\
-    int h=4;\
-    int w=3;\
-    src -= 2*srcStride+2;\
-    while(w--){\
-        __asm__ volatile(\
-            "pxor %%mm7, %%mm7      \n\t"\
-            "movd (%0), %%mm0       \n\t"\
-            "add %2, %0             \n\t"\
-            "movd (%0), %%mm1       \n\t"\
-            "add %2, %0             \n\t"\
-            "movd (%0), %%mm2       \n\t"\
-            "add %2, %0             \n\t"\
-            "movd (%0), %%mm3       \n\t"\
-            "add %2, %0             \n\t"\
-            "movd (%0), %%mm4       \n\t"\
-            "add %2, %0             \n\t"\
-            "punpcklbw %%mm7, %%mm0 \n\t"\
-            "punpcklbw %%mm7, %%mm1 \n\t"\
-            "punpcklbw %%mm7, %%mm2 \n\t"\
-            "punpcklbw %%mm7, %%mm3 \n\t"\
-            "punpcklbw %%mm7, %%mm4 \n\t"\
-            QPEL_H264HV(%%mm0, %%mm1, %%mm2, %%mm3, %%mm4, %%mm5, 0*8*3)\
-            QPEL_H264HV(%%mm1, %%mm2, %%mm3, %%mm4, %%mm5, %%mm0, 1*8*3)\
-            QPEL_H264HV(%%mm2, %%mm3, %%mm4, %%mm5, %%mm0, %%mm1, 2*8*3)\
-            QPEL_H264HV(%%mm3, %%mm4, %%mm5, %%mm0, %%mm1, %%mm2, 3*8*3)\
-             \
-            : "+a"(src)\
-            : "c"(tmp), "S"((x86_reg)srcStride), "m"(ff_pw_5), "m"(ff_pw_16)\
-            : "memory"\
-        );\
-        tmp += 4;\
-        src += 4 - 9*srcStride;\
-    }\
-    tmp -= 3*4;\
-    __asm__ volatile(\
-        "1:                         \n\t"\
-        "movq     (%0), %%mm0       \n\t"\
-        "paddw  10(%0), %%mm0       \n\t"\
-        "movq    2(%0), %%mm1       \n\t"\
-        "paddw   8(%0), %%mm1       \n\t"\
-        "movq    4(%0), %%mm2       \n\t"\
-        "paddw   6(%0), %%mm2       \n\t"\
-        "psubw %%mm1, %%mm0         \n\t"/*a-b   (abccba)*/\
-        "psraw $2, %%mm0            \n\t"/*(a-b)/4 */\
-        "psubw %%mm1, %%mm0         \n\t"/*(a-b)/4-b */\
-        "paddsw %%mm2, %%mm0        \n\t"\
-        "psraw $2, %%mm0            \n\t"/*((a-b)/4-b+c)/4 */\
-        "paddw %%mm2, %%mm0         \n\t"/*(a-5*b+20*c)/16 */\
-        "psraw $6, %%mm0            \n\t"\
-        "packuswb %%mm0, %%mm0      \n\t"\
-        OP(%%mm0, (%1),%%mm7, d)\
-        "add $24, %0                \n\t"\
-        "add %3, %1                 \n\t"\
-        "decl %2                    \n\t"\
-        " jnz 1b                    \n\t"\
-        : "+a"(tmp), "+c"(dst), "+g"(h)\
-        : "S"((x86_reg)dstStride)\
-        : "memory"\
-    );\
-}\
-\
-static av_noinline void OPNAME ## h264_qpel8_h_lowpass_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride){\
-    int h=8;\
-    __asm__ volatile(\
-        "pxor %%mm7, %%mm7          \n\t"\
-        "movq "MANGLE(ff_pw_5)", %%mm6\n\t"\
-        "1:                         \n\t"\
-        "movq    (%0), %%mm0        \n\t"\
-        "movq   1(%0), %%mm2        \n\t"\
-        "movq %%mm0, %%mm1          \n\t"\
-        "movq %%mm2, %%mm3          \n\t"\
-        "punpcklbw %%mm7, %%mm0     \n\t"\
-        "punpckhbw %%mm7, %%mm1     \n\t"\
-        "punpcklbw %%mm7, %%mm2     \n\t"\
-        "punpckhbw %%mm7, %%mm3     \n\t"\
-        "paddw %%mm2, %%mm0         \n\t"\
-        "paddw %%mm3, %%mm1         \n\t"\
-        "psllw $2, %%mm0            \n\t"\
-        "psllw $2, %%mm1            \n\t"\
-        "movq   -1(%0), %%mm2       \n\t"\
-        "movq    2(%0), %%mm4       \n\t"\
-        "movq %%mm2, %%mm3          \n\t"\
-        "movq %%mm4, %%mm5          \n\t"\
-        "punpcklbw %%mm7, %%mm2     \n\t"\
-        "punpckhbw %%mm7, %%mm3     \n\t"\
-        "punpcklbw %%mm7, %%mm4     \n\t"\
-        "punpckhbw %%mm7, %%mm5     \n\t"\
-        "paddw %%mm4, %%mm2         \n\t"\
-        "paddw %%mm3, %%mm5         \n\t"\
-        "psubw %%mm2, %%mm0         \n\t"\
-        "psubw %%mm5, %%mm1         \n\t"\
-        "pmullw %%mm6, %%mm0        \n\t"\
-        "pmullw %%mm6, %%mm1        \n\t"\
-        "movd   -2(%0), %%mm2       \n\t"\
-        "movd    7(%0), %%mm5       \n\t"\
-        "punpcklbw %%mm7, %%mm2     \n\t"\
-        "punpcklbw %%mm7, %%mm5     \n\t"\
-        "paddw %%mm3, %%mm2         \n\t"\
-        "paddw %%mm5, %%mm4         \n\t"\
-        "movq "MANGLE(ff_pw_16)", %%mm5\n\t"\
-        "paddw %%mm5, %%mm2         \n\t"\
-        "paddw %%mm5, %%mm4         \n\t"\
-        "paddw %%mm2, %%mm0         \n\t"\
-        "paddw %%mm4, %%mm1         \n\t"\
-        "psraw $5, %%mm0            \n\t"\
-        "psraw $5, %%mm1            \n\t"\
-        "packuswb %%mm1, %%mm0      \n\t"\
-        OP(%%mm0, (%1),%%mm5, q)\
-        "add %3, %0                 \n\t"\
-        "add %4, %1                 \n\t"\
-        "decl %2                    \n\t"\
-        " jnz 1b                    \n\t"\
-        : "+a"(src), "+c"(dst), "+g"(h)\
-        : "d"((x86_reg)srcStride), "S"((x86_reg)dstStride)\
-        : "memory"\
-    );\
-}\
-\
-static av_noinline void OPNAME ## h264_qpel8_h_lowpass_l2_ ## MMX(uint8_t *dst, uint8_t *src, uint8_t *src2, int dstStride, int src2Stride){\
-    int h=8;\
-    __asm__ volatile(\
-        "pxor %%mm7, %%mm7          \n\t"\
-        "movq %0, %%mm6             \n\t"\
-        :: "m"(ff_pw_5)\
-    );\
-    do{\
-    __asm__ volatile(\
-        "movq    (%0), %%mm0        \n\t"\
-        "movq   1(%0), %%mm2        \n\t"\
-        "movq %%mm0, %%mm1          \n\t"\
-        "movq %%mm2, %%mm3          \n\t"\
-        "punpcklbw %%mm7, %%mm0     \n\t"\
-        "punpckhbw %%mm7, %%mm1     \n\t"\
-        "punpcklbw %%mm7, %%mm2     \n\t"\
-        "punpckhbw %%mm7, %%mm3     \n\t"\
-        "paddw %%mm2, %%mm0         \n\t"\
-        "paddw %%mm3, %%mm1         \n\t"\
-        "psllw $2, %%mm0            \n\t"\
-        "psllw $2, %%mm1            \n\t"\
-        "movq   -1(%0), %%mm2       \n\t"\
-        "movq    2(%0), %%mm4       \n\t"\
-        "movq %%mm2, %%mm3          \n\t"\
-        "movq %%mm4, %%mm5          \n\t"\
-        "punpcklbw %%mm7, %%mm2     \n\t"\
-        "punpckhbw %%mm7, %%mm3     \n\t"\
-        "punpcklbw %%mm7, %%mm4     \n\t"\
-        "punpckhbw %%mm7, %%mm5     \n\t"\
-        "paddw %%mm4, %%mm2         \n\t"\
-        "paddw %%mm3, %%mm5         \n\t"\
-        "psubw %%mm2, %%mm0         \n\t"\
-        "psubw %%mm5, %%mm1         \n\t"\
-        "pmullw %%mm6, %%mm0        \n\t"\
-        "pmullw %%mm6, %%mm1        \n\t"\
-        "movd   -2(%0), %%mm2       \n\t"\
-        "movd    7(%0), %%mm5       \n\t"\
-        "punpcklbw %%mm7, %%mm2     \n\t"\
-        "punpcklbw %%mm7, %%mm5     \n\t"\
-        "paddw %%mm3, %%mm2         \n\t"\
-        "paddw %%mm5, %%mm4         \n\t"\
-        "movq %5, %%mm5             \n\t"\
-        "paddw %%mm5, %%mm2         \n\t"\
-        "paddw %%mm5, %%mm4         \n\t"\
-        "paddw %%mm2, %%mm0         \n\t"\
-        "paddw %%mm4, %%mm1         \n\t"\
-        "psraw $5, %%mm0            \n\t"\
-        "psraw $5, %%mm1            \n\t"\
-        "movq (%2), %%mm4           \n\t"\
-        "packuswb %%mm1, %%mm0      \n\t"\
-        PAVGB" %%mm4, %%mm0         \n\t"\
-        OP(%%mm0, (%1),%%mm5, q)\
-        "add %4, %0                 \n\t"\
-        "add %4, %1                 \n\t"\
-        "add %3, %2                 \n\t"\
-        : "+a"(src), "+c"(dst), "+d"(src2)\
-        : "D"((x86_reg)src2Stride), "S"((x86_reg)dstStride),\
-          "m"(ff_pw_16)\
-        : "memory"\
-    );\
-    }while(--h);\
-}\
-\
-static av_noinline void OPNAME ## h264_qpel8or16_v_lowpass_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride, int h){\
-    int w= 2;\
-    src -= 2*srcStride;\
-    \
-    while(w--){\
-      __asm__ volatile(\
-        "pxor %%mm7, %%mm7          \n\t"\
-        "movd (%0), %%mm0           \n\t"\
-        "add %2, %0                 \n\t"\
-        "movd (%0), %%mm1           \n\t"\
-        "add %2, %0                 \n\t"\
-        "movd (%0), %%mm2           \n\t"\
-        "add %2, %0                 \n\t"\
-        "movd (%0), %%mm3           \n\t"\
-        "add %2, %0                 \n\t"\
-        "movd (%0), %%mm4           \n\t"\
-        "add %2, %0                 \n\t"\
-        "punpcklbw %%mm7, %%mm0     \n\t"\
-        "punpcklbw %%mm7, %%mm1     \n\t"\
-        "punpcklbw %%mm7, %%mm2     \n\t"\
-        "punpcklbw %%mm7, %%mm3     \n\t"\
-        "punpcklbw %%mm7, %%mm4     \n\t"\
-        QPEL_H264V(%%mm0, %%mm1, %%mm2, %%mm3, %%mm4, %%mm5, OP)\
-        QPEL_H264V(%%mm1, %%mm2, %%mm3, %%mm4, %%mm5, %%mm0, OP)\
-        QPEL_H264V(%%mm2, %%mm3, %%mm4, %%mm5, %%mm0, %%mm1, OP)\
-        QPEL_H264V(%%mm3, %%mm4, %%mm5, %%mm0, %%mm1, %%mm2, OP)\
-        QPEL_H264V(%%mm4, %%mm5, %%mm0, %%mm1, %%mm2, %%mm3, OP)\
-        QPEL_H264V(%%mm5, %%mm0, %%mm1, %%mm2, %%mm3, %%mm4, OP)\
-        QPEL_H264V(%%mm0, %%mm1, %%mm2, %%mm3, %%mm4, %%mm5, OP)\
-        QPEL_H264V(%%mm1, %%mm2, %%mm3, %%mm4, %%mm5, %%mm0, OP)\
-         \
-        : "+a"(src), "+c"(dst)\
-        : "S"((x86_reg)srcStride), "D"((x86_reg)dstStride), "m"(ff_pw_5), "m"(ff_pw_16)\
-        : "memory"\
-     );\
-     if(h==16){\
-        __asm__ volatile(\
-            QPEL_H264V(%%mm2, %%mm3, %%mm4, %%mm5, %%mm0, %%mm1, OP)\
-            QPEL_H264V(%%mm3, %%mm4, %%mm5, %%mm0, %%mm1, %%mm2, OP)\
-            QPEL_H264V(%%mm4, %%mm5, %%mm0, %%mm1, %%mm2, %%mm3, OP)\
-            QPEL_H264V(%%mm5, %%mm0, %%mm1, %%mm2, %%mm3, %%mm4, OP)\
-            QPEL_H264V(%%mm0, %%mm1, %%mm2, %%mm3, %%mm4, %%mm5, OP)\
-            QPEL_H264V(%%mm1, %%mm2, %%mm3, %%mm4, %%mm5, %%mm0, OP)\
-            QPEL_H264V(%%mm2, %%mm3, %%mm4, %%mm5, %%mm0, %%mm1, OP)\
-            QPEL_H264V(%%mm3, %%mm4, %%mm5, %%mm0, %%mm1, %%mm2, OP)\
-            \
-           : "+a"(src), "+c"(dst)\
-           : "S"((x86_reg)srcStride), "D"((x86_reg)dstStride), "m"(ff_pw_5), "m"(ff_pw_16)\
-           : "memory"\
-        );\
-     }\
-     src += 4-(h+5)*srcStride;\
-     dst += 4-h*dstStride;\
-   }\
-}\
-static av_always_inline void OPNAME ## h264_qpel8or16_hv1_lowpass_ ## MMX(int16_t *tmp, uint8_t *src, int tmpStride, int srcStride, int size){\
-    int w = (size+8)>>2;\
-    src -= 2*srcStride+2;\
-    while(w--){\
-        __asm__ volatile(\
-            "pxor %%mm7, %%mm7      \n\t"\
-            "movd (%0), %%mm0       \n\t"\
-            "add %2, %0             \n\t"\
-            "movd (%0), %%mm1       \n\t"\
-            "add %2, %0             \n\t"\
-            "movd (%0), %%mm2       \n\t"\
-            "add %2, %0             \n\t"\
-            "movd (%0), %%mm3       \n\t"\
-            "add %2, %0             \n\t"\
-            "movd (%0), %%mm4       \n\t"\
-            "add %2, %0             \n\t"\
-            "punpcklbw %%mm7, %%mm0 \n\t"\
-            "punpcklbw %%mm7, %%mm1 \n\t"\
-            "punpcklbw %%mm7, %%mm2 \n\t"\
-            "punpcklbw %%mm7, %%mm3 \n\t"\
-            "punpcklbw %%mm7, %%mm4 \n\t"\
-            QPEL_H264HV(%%mm0, %%mm1, %%mm2, %%mm3, %%mm4, %%mm5, 0*48)\
-            QPEL_H264HV(%%mm1, %%mm2, %%mm3, %%mm4, %%mm5, %%mm0, 1*48)\
-            QPEL_H264HV(%%mm2, %%mm3, %%mm4, %%mm5, %%mm0, %%mm1, 2*48)\
-            QPEL_H264HV(%%mm3, %%mm4, %%mm5, %%mm0, %%mm1, %%mm2, 3*48)\
-            QPEL_H264HV(%%mm4, %%mm5, %%mm0, %%mm1, %%mm2, %%mm3, 4*48)\
-            QPEL_H264HV(%%mm5, %%mm0, %%mm1, %%mm2, %%mm3, %%mm4, 5*48)\
-            QPEL_H264HV(%%mm0, %%mm1, %%mm2, %%mm3, %%mm4, %%mm5, 6*48)\
-            QPEL_H264HV(%%mm1, %%mm2, %%mm3, %%mm4, %%mm5, %%mm0, 7*48)\
-            : "+a"(src)\
-            : "c"(tmp), "S"((x86_reg)srcStride), "m"(ff_pw_5), "m"(ff_pw_16)\
-            : "memory"\
-        );\
-        if(size==16){\
-            __asm__ volatile(\
-                QPEL_H264HV(%%mm2, %%mm3, %%mm4, %%mm5, %%mm0, %%mm1,  8*48)\
-                QPEL_H264HV(%%mm3, %%mm4, %%mm5, %%mm0, %%mm1, %%mm2,  9*48)\
-                QPEL_H264HV(%%mm4, %%mm5, %%mm0, %%mm1, %%mm2, %%mm3, 10*48)\
-                QPEL_H264HV(%%mm5, %%mm0, %%mm1, %%mm2, %%mm3, %%mm4, 11*48)\
-                QPEL_H264HV(%%mm0, %%mm1, %%mm2, %%mm3, %%mm4, %%mm5, 12*48)\
-                QPEL_H264HV(%%mm1, %%mm2, %%mm3, %%mm4, %%mm5, %%mm0, 13*48)\
-                QPEL_H264HV(%%mm2, %%mm3, %%mm4, %%mm5, %%mm0, %%mm1, 14*48)\
-                QPEL_H264HV(%%mm3, %%mm4, %%mm5, %%mm0, %%mm1, %%mm2, 15*48)\
-                : "+a"(src)\
-                : "c"(tmp), "S"((x86_reg)srcStride), "m"(ff_pw_5), "m"(ff_pw_16)\
-                : "memory"\
-            );\
-        }\
-        tmp += 4;\
-        src += 4 - (size+5)*srcStride;\
-    }\
-}\
-static av_always_inline void OPNAME ## h264_qpel8or16_hv2_lowpass_ ## MMX(uint8_t *dst, int16_t *tmp, int dstStride, int tmpStride, int size){\
-    int w = size>>4;\
-    do{\
-    int h = size;\
-    __asm__ volatile(\
-        "1:                         \n\t"\
-        "movq     (%0), %%mm0       \n\t"\
-        "movq    8(%0), %%mm3       \n\t"\
-        "movq    2(%0), %%mm1       \n\t"\
-        "movq   10(%0), %%mm4       \n\t"\
-        "paddw   %%mm4, %%mm0       \n\t"\
-        "paddw   %%mm3, %%mm1       \n\t"\
-        "paddw  18(%0), %%mm3       \n\t"\
-        "paddw  16(%0), %%mm4       \n\t"\
-        "movq    4(%0), %%mm2       \n\t"\
-        "movq   12(%0), %%mm5       \n\t"\
-        "paddw   6(%0), %%mm2       \n\t"\
-        "paddw  14(%0), %%mm5       \n\t"\
-        "psubw %%mm1, %%mm0         \n\t"\
-        "psubw %%mm4, %%mm3         \n\t"\
-        "psraw $2, %%mm0            \n\t"\
-        "psraw $2, %%mm3            \n\t"\
-        "psubw %%mm1, %%mm0         \n\t"\
-        "psubw %%mm4, %%mm3         \n\t"\
-        "paddsw %%mm2, %%mm0        \n\t"\
-        "paddsw %%mm5, %%mm3        \n\t"\
-        "psraw $2, %%mm0            \n\t"\
-        "psraw $2, %%mm3            \n\t"\
-        "paddw %%mm2, %%mm0         \n\t"\
-        "paddw %%mm5, %%mm3         \n\t"\
-        "psraw $6, %%mm0            \n\t"\
-        "psraw $6, %%mm3            \n\t"\
-        "packuswb %%mm3, %%mm0      \n\t"\
-        OP(%%mm0, (%1),%%mm7, q)\
-        "add $48, %0                \n\t"\
-        "add %3, %1                 \n\t"\
-        "decl %2                    \n\t"\
-        " jnz 1b                    \n\t"\
-        : "+a"(tmp), "+c"(dst), "+g"(h)\
-        : "S"((x86_reg)dstStride)\
-        : "memory"\
-    );\
-    tmp += 8 - size*24;\
-    dst += 8 - size*dstStride;\
-    }while(w--);\
-}\
-\
-static void OPNAME ## h264_qpel8_v_lowpass_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride){\
-    OPNAME ## h264_qpel8or16_v_lowpass_ ## MMX(dst  , src  , dstStride, srcStride, 8);\
-}\
-static av_noinline void OPNAME ## h264_qpel16_v_lowpass_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride){\
-    OPNAME ## h264_qpel8or16_v_lowpass_ ## MMX(dst  , src  , dstStride, srcStride, 16);\
-    OPNAME ## h264_qpel8or16_v_lowpass_ ## MMX(dst+8, src+8, dstStride, srcStride, 16);\
-}\
-\
-static void OPNAME ## h264_qpel16_h_lowpass_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride){\
-    OPNAME ## h264_qpel8_h_lowpass_ ## MMX(dst  , src  , dstStride, srcStride);\
-    OPNAME ## h264_qpel8_h_lowpass_ ## MMX(dst+8, src+8, dstStride, srcStride);\
-    src += 8*srcStride;\
-    dst += 8*dstStride;\
-    OPNAME ## h264_qpel8_h_lowpass_ ## MMX(dst  , src  , dstStride, srcStride);\
-    OPNAME ## h264_qpel8_h_lowpass_ ## MMX(dst+8, src+8, dstStride, srcStride);\
-}\
-\
-static av_noinline void OPNAME ## h264_qpel16_h_lowpass_l2_ ## MMX(uint8_t *dst, uint8_t *src, uint8_t *src2, int dstStride, int src2Stride){\
-    OPNAME ## h264_qpel8_h_lowpass_l2_ ## MMX(dst  , src  , src2  , dstStride, src2Stride);\
-    OPNAME ## h264_qpel8_h_lowpass_l2_ ## MMX(dst+8, src+8, src2+8, dstStride, src2Stride);\
-    src += 8*dstStride;\
-    dst += 8*dstStride;\
-    src2 += 8*src2Stride;\
-    OPNAME ## h264_qpel8_h_lowpass_l2_ ## MMX(dst  , src  , src2  , dstStride, src2Stride);\
-    OPNAME ## h264_qpel8_h_lowpass_l2_ ## MMX(dst+8, src+8, src2+8, dstStride, src2Stride);\
-}\
-\
-static av_noinline void OPNAME ## h264_qpel8or16_hv_lowpass_ ## MMX(uint8_t *dst, int16_t *tmp, uint8_t *src, int dstStride, int tmpStride, int srcStride, int size){\
-          put_h264_qpel8or16_hv1_lowpass_ ## MMX(tmp, src, tmpStride, srcStride, size);\
-    OPNAME ## h264_qpel8or16_hv2_lowpass_ ## MMX(dst, tmp, dstStride, tmpStride, size);\
-}\
-static void OPNAME ## h264_qpel8_hv_lowpass_ ## MMX(uint8_t *dst, int16_t *tmp, uint8_t *src, int dstStride, int tmpStride, int srcStride){\
-    OPNAME ## h264_qpel8or16_hv_lowpass_ ## MMX(dst  , tmp  , src  , dstStride, tmpStride, srcStride, 8);\
-}\
-\
-static void OPNAME ## h264_qpel16_hv_lowpass_ ## MMX(uint8_t *dst, int16_t *tmp, uint8_t *src, int dstStride, int tmpStride, int srcStride){\
-    OPNAME ## h264_qpel8or16_hv_lowpass_ ## MMX(dst  , tmp  , src  , dstStride, tmpStride, srcStride, 16);\
-}\
-\
-static av_noinline void OPNAME ## pixels4_l2_shift5_ ## MMX(uint8_t *dst, int16_t *src16, uint8_t *src8, int dstStride, int src8Stride, int h)\
-{\
-    __asm__ volatile(\
-        "movq      (%1), %%mm0          \n\t"\
-        "movq    24(%1), %%mm1          \n\t"\
-        "psraw      $5,  %%mm0          \n\t"\
-        "psraw      $5,  %%mm1          \n\t"\
-        "packuswb %%mm0, %%mm0          \n\t"\
-        "packuswb %%mm1, %%mm1          \n\t"\
-        PAVGB"     (%0), %%mm0          \n\t"\
-        PAVGB"  (%0,%3), %%mm1          \n\t"\
-        OP(%%mm0, (%2),    %%mm4, d)\
-        OP(%%mm1, (%2,%4), %%mm5, d)\
-        "lea  (%0,%3,2), %0             \n\t"\
-        "lea  (%2,%4,2), %2             \n\t"\
-        "movq    48(%1), %%mm0          \n\t"\
-        "movq    72(%1), %%mm1          \n\t"\
-        "psraw      $5,  %%mm0          \n\t"\
-        "psraw      $5,  %%mm1          \n\t"\
-        "packuswb %%mm0, %%mm0          \n\t"\
-        "packuswb %%mm1, %%mm1          \n\t"\
-        PAVGB"     (%0), %%mm0          \n\t"\
-        PAVGB"  (%0,%3), %%mm1          \n\t"\
-        OP(%%mm0, (%2),    %%mm4, d)\
-        OP(%%mm1, (%2,%4), %%mm5, d)\
-        :"+a"(src8), "+c"(src16), "+d"(dst)\
-        :"S"((x86_reg)src8Stride), "D"((x86_reg)dstStride)\
-        :"memory");\
-}\
-static av_noinline void OPNAME ## pixels8_l2_shift5_ ## MMX(uint8_t *dst, int16_t *src16, uint8_t *src8, int dstStride, int src8Stride, int h)\
-{\
-    do{\
-    __asm__ volatile(\
-        "movq      (%1), %%mm0          \n\t"\
-        "movq     8(%1), %%mm1          \n\t"\
-        "movq    48(%1), %%mm2          \n\t"\
-        "movq  8+48(%1), %%mm3          \n\t"\
-        "psraw      $5,  %%mm0          \n\t"\
-        "psraw      $5,  %%mm1          \n\t"\
-        "psraw      $5,  %%mm2          \n\t"\
-        "psraw      $5,  %%mm3          \n\t"\
-        "packuswb %%mm1, %%mm0          \n\t"\
-        "packuswb %%mm3, %%mm2          \n\t"\
-        PAVGB"     (%0), %%mm0          \n\t"\
-        PAVGB"  (%0,%3), %%mm2          \n\t"\
-        OP(%%mm0, (%2), %%mm5, q)\
-        OP(%%mm2, (%2,%4), %%mm5, q)\
-        ::"a"(src8), "c"(src16), "d"(dst),\
-          "r"((x86_reg)src8Stride), "r"((x86_reg)dstStride)\
-        :"memory");\
-        src8 += 2L*src8Stride;\
-        src16 += 48;\
-        dst += 2L*dstStride;\
-    }while(h-=2);\
-}\
-static void OPNAME ## pixels16_l2_shift5_ ## MMX(uint8_t *dst, int16_t *src16, uint8_t *src8, int dstStride, int src8Stride, int h)\
-{\
-    OPNAME ## pixels8_l2_shift5_ ## MMX(dst  , src16  , src8  , dstStride, src8Stride, h);\
-    OPNAME ## pixels8_l2_shift5_ ## MMX(dst+8, src16+8, src8+8, dstStride, src8Stride, h);\
-}\
-
-
-#if ARCH_X86_64
-#define QPEL_H264_H16_XMM(OPNAME, OP, MMX)\
-static av_noinline void OPNAME ## h264_qpel16_h_lowpass_l2_ ## MMX(uint8_t *dst, uint8_t *src, uint8_t *src2, int dstStride, int src2Stride){\
-    int h=16;\
-    __asm__ volatile(\
-        "pxor %%xmm15, %%xmm15      \n\t"\
-        "movdqa %6, %%xmm14         \n\t"\
-        "movdqa %7, %%xmm13         \n\t"\
-        "1:                         \n\t"\
-        "lddqu    6(%0), %%xmm1     \n\t"\
-        "lddqu   -2(%0), %%xmm7     \n\t"\
-        "movdqa  %%xmm1, %%xmm0     \n\t"\
-        "punpckhbw %%xmm15, %%xmm1  \n\t"\
-        "punpcklbw %%xmm15, %%xmm0  \n\t"\
-        "punpcklbw %%xmm15, %%xmm7  \n\t"\
-        "movdqa  %%xmm1, %%xmm2     \n\t"\
-        "movdqa  %%xmm0, %%xmm6     \n\t"\
-        "movdqa  %%xmm1, %%xmm3     \n\t"\
-        "movdqa  %%xmm0, %%xmm8     \n\t"\
-        "movdqa  %%xmm1, %%xmm4     \n\t"\
-        "movdqa  %%xmm0, %%xmm9     \n\t"\
-        "movdqa  %%xmm0, %%xmm12    \n\t"\
-        "movdqa  %%xmm1, %%xmm11    \n\t"\
-        "palignr $10,%%xmm0, %%xmm11\n\t"\
-        "palignr $10,%%xmm7, %%xmm12\n\t"\
-        "palignr $2, %%xmm0, %%xmm4 \n\t"\
-        "palignr $2, %%xmm7, %%xmm9 \n\t"\
-        "palignr $4, %%xmm0, %%xmm3 \n\t"\
-        "palignr $4, %%xmm7, %%xmm8 \n\t"\
-        "palignr $6, %%xmm0, %%xmm2 \n\t"\
-        "palignr $6, %%xmm7, %%xmm6 \n\t"\
-        "paddw   %%xmm0 ,%%xmm11    \n\t"\
-        "palignr $8, %%xmm0, %%xmm1 \n\t"\
-        "palignr $8, %%xmm7, %%xmm0 \n\t"\
-        "paddw   %%xmm12,%%xmm7     \n\t"\
-        "paddw   %%xmm3, %%xmm2     \n\t"\
-        "paddw   %%xmm8, %%xmm6     \n\t"\
-        "paddw   %%xmm4, %%xmm1     \n\t"\
-        "paddw   %%xmm9, %%xmm0     \n\t"\
-        "psllw   $2,     %%xmm2     \n\t"\
-        "psllw   $2,     %%xmm6     \n\t"\
-        "psubw   %%xmm1, %%xmm2     \n\t"\
-        "psubw   %%xmm0, %%xmm6     \n\t"\
-        "paddw   %%xmm13,%%xmm11    \n\t"\
-        "paddw   %%xmm13,%%xmm7     \n\t"\
-        "pmullw  %%xmm14,%%xmm2     \n\t"\
-        "pmullw  %%xmm14,%%xmm6     \n\t"\
-        "lddqu   (%2),   %%xmm3     \n\t"\
-        "paddw   %%xmm11,%%xmm2     \n\t"\
-        "paddw   %%xmm7, %%xmm6     \n\t"\
-        "psraw   $5,     %%xmm2     \n\t"\
-        "psraw   $5,     %%xmm6     \n\t"\
-        "packuswb %%xmm2,%%xmm6     \n\t"\
-        "pavgb   %%xmm3, %%xmm6     \n\t"\
-        OP(%%xmm6, (%1), %%xmm4, dqa)\
-        "add %5, %0                 \n\t"\
-        "add %5, %1                 \n\t"\
-        "add %4, %2                 \n\t"\
-        "decl %3                    \n\t"\
-        "jg 1b                      \n\t"\
-        : "+a"(src), "+c"(dst), "+d"(src2), "+g"(h)\
-        : "D"((x86_reg)src2Stride), "S"((x86_reg)dstStride),\
-          "m"(ff_pw_5), "m"(ff_pw_16)\
-        : "memory"\
-    );\
-}
-#else // ARCH_X86_64
-#define QPEL_H264_H16_XMM(OPNAME, OP, MMX)\
-static av_noinline void OPNAME ## h264_qpel16_h_lowpass_l2_ ## MMX(uint8_t *dst, uint8_t *src, uint8_t *src2, int dstStride, int src2Stride){\
-    OPNAME ## h264_qpel8_h_lowpass_l2_ ## MMX(dst  , src  , src2  , dstStride, src2Stride);\
-    OPNAME ## h264_qpel8_h_lowpass_l2_ ## MMX(dst+8, src+8, src2+8, dstStride, src2Stride);\
-    src += 8*dstStride;\
-    dst += 8*dstStride;\
-    src2 += 8*src2Stride;\
-    OPNAME ## h264_qpel8_h_lowpass_l2_ ## MMX(dst  , src  , src2  , dstStride, src2Stride);\
-    OPNAME ## h264_qpel8_h_lowpass_l2_ ## MMX(dst+8, src+8, src2+8, dstStride, src2Stride);\
-}
-#endif // ARCH_X86_64
-
-#define QPEL_H264_H_XMM(OPNAME, OP, MMX)\
-static av_noinline void OPNAME ## h264_qpel8_h_lowpass_l2_ ## MMX(uint8_t *dst, uint8_t *src, uint8_t *src2, int dstStride, int src2Stride){\
-    int h=8;\
-    __asm__ volatile(\
-        "pxor %%xmm7, %%xmm7        \n\t"\
-        "movdqa %0, %%xmm6          \n\t"\
-        :: "m"(ff_pw_5)\
-    );\
-    do{\
-    __asm__ volatile(\
-        "lddqu   -2(%0), %%xmm1     \n\t"\
-        "movdqa  %%xmm1, %%xmm0     \n\t"\
-        "punpckhbw %%xmm7, %%xmm1   \n\t"\
-        "punpcklbw %%xmm7, %%xmm0   \n\t"\
-        "movdqa  %%xmm1, %%xmm2     \n\t"\
-        "movdqa  %%xmm1, %%xmm3     \n\t"\
-        "movdqa  %%xmm1, %%xmm4     \n\t"\
-        "movdqa  %%xmm1, %%xmm5     \n\t"\
-        "palignr $2, %%xmm0, %%xmm4 \n\t"\
-        "palignr $4, %%xmm0, %%xmm3 \n\t"\
-        "palignr $6, %%xmm0, %%xmm2 \n\t"\
-        "palignr $8, %%xmm0, %%xmm1 \n\t"\
-        "palignr $10,%%xmm0, %%xmm5 \n\t"\
-        "paddw   %%xmm5, %%xmm0     \n\t"\
-        "paddw   %%xmm3, %%xmm2     \n\t"\
-        "paddw   %%xmm4, %%xmm1     \n\t"\
-        "psllw   $2,     %%xmm2     \n\t"\
-        "movq    (%2),   %%xmm3     \n\t"\
-        "psubw   %%xmm1, %%xmm2     \n\t"\
-        "paddw   %5,     %%xmm0     \n\t"\
-        "pmullw  %%xmm6, %%xmm2     \n\t"\
-        "paddw   %%xmm0, %%xmm2     \n\t"\
-        "psraw   $5,     %%xmm2     \n\t"\
-        "packuswb %%xmm2, %%xmm2    \n\t"\
-        "pavgb   %%xmm3, %%xmm2     \n\t"\
-        OP(%%xmm2, (%1), %%xmm4, q)\
-        "add %4, %0                 \n\t"\
-        "add %4, %1                 \n\t"\
-        "add %3, %2                 \n\t"\
-        : "+a"(src), "+c"(dst), "+d"(src2)\
-        : "D"((x86_reg)src2Stride), "S"((x86_reg)dstStride),\
-          "m"(ff_pw_16)\
-        : "memory"\
-    );\
-    }while(--h);\
-}\
-QPEL_H264_H16_XMM(OPNAME, OP, MMX)\
-\
-static av_noinline void OPNAME ## h264_qpel8_h_lowpass_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride){\
-    int h=8;\
-    __asm__ volatile(\
-        "pxor %%xmm7, %%xmm7        \n\t"\
-        "movdqa "MANGLE(ff_pw_5)", %%xmm6\n\t"\
-        "1:                         \n\t"\
-        "lddqu   -2(%0), %%xmm1     \n\t"\
-        "movdqa  %%xmm1, %%xmm0     \n\t"\
-        "punpckhbw %%xmm7, %%xmm1   \n\t"\
-        "punpcklbw %%xmm7, %%xmm0   \n\t"\
-        "movdqa  %%xmm1, %%xmm2     \n\t"\
-        "movdqa  %%xmm1, %%xmm3     \n\t"\
-        "movdqa  %%xmm1, %%xmm4     \n\t"\
-        "movdqa  %%xmm1, %%xmm5     \n\t"\
-        "palignr $2, %%xmm0, %%xmm4 \n\t"\
-        "palignr $4, %%xmm0, %%xmm3 \n\t"\
-        "palignr $6, %%xmm0, %%xmm2 \n\t"\
-        "palignr $8, %%xmm0, %%xmm1 \n\t"\
-        "palignr $10,%%xmm0, %%xmm5 \n\t"\
-        "paddw   %%xmm5, %%xmm0     \n\t"\
-        "paddw   %%xmm3, %%xmm2     \n\t"\
-        "paddw   %%xmm4, %%xmm1     \n\t"\
-        "psllw   $2,     %%xmm2     \n\t"\
-        "psubw   %%xmm1, %%xmm2     \n\t"\
-        "paddw   "MANGLE(ff_pw_16)", %%xmm0\n\t"\
-        "pmullw  %%xmm6, %%xmm2     \n\t"\
-        "paddw   %%xmm0, %%xmm2     \n\t"\
-        "psraw   $5,     %%xmm2     \n\t"\
-        "packuswb %%xmm2, %%xmm2    \n\t"\
-        OP(%%xmm2, (%1), %%xmm4, q)\
-        "add %3, %0                 \n\t"\
-        "add %4, %1                 \n\t"\
-        "decl %2                    \n\t"\
-        " jnz 1b                    \n\t"\
-        : "+a"(src), "+c"(dst), "+g"(h)\
-        : "D"((x86_reg)srcStride), "S"((x86_reg)dstStride)\
-        : "memory"\
-    );\
-}\
-static void OPNAME ## h264_qpel16_h_lowpass_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride){\
-    OPNAME ## h264_qpel8_h_lowpass_ ## MMX(dst  , src  , dstStride, srcStride);\
-    OPNAME ## h264_qpel8_h_lowpass_ ## MMX(dst+8, src+8, dstStride, srcStride);\
-    src += 8*srcStride;\
-    dst += 8*dstStride;\
-    OPNAME ## h264_qpel8_h_lowpass_ ## MMX(dst  , src  , dstStride, srcStride);\
-    OPNAME ## h264_qpel8_h_lowpass_ ## MMX(dst+8, src+8, dstStride, srcStride);\
-}\
-
-#define QPEL_H264_V_XMM(OPNAME, OP, MMX)\
-static av_noinline void OPNAME ## h264_qpel8or16_v_lowpass_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride, int h){\
-    src -= 2*srcStride;\
-    \
-    __asm__ volatile(\
-        "pxor %%xmm7, %%xmm7        \n\t"\
-        "movq (%0), %%xmm0          \n\t"\
-        "add %2, %0                 \n\t"\
-        "movq (%0), %%xmm1          \n\t"\
-        "add %2, %0                 \n\t"\
-        "movq (%0), %%xmm2          \n\t"\
-        "add %2, %0                 \n\t"\
-        "movq (%0), %%xmm3          \n\t"\
-        "add %2, %0                 \n\t"\
-        "movq (%0), %%xmm4          \n\t"\
-        "add %2, %0                 \n\t"\
-        "punpcklbw %%xmm7, %%xmm0   \n\t"\
-        "punpcklbw %%xmm7, %%xmm1   \n\t"\
-        "punpcklbw %%xmm7, %%xmm2   \n\t"\
-        "punpcklbw %%xmm7, %%xmm3   \n\t"\
-        "punpcklbw %%xmm7, %%xmm4   \n\t"\
-        QPEL_H264V_XMM(%%xmm0, %%xmm1, %%xmm2, %%xmm3, %%xmm4, %%xmm5, OP)\
-        QPEL_H264V_XMM(%%xmm1, %%xmm2, %%xmm3, %%xmm4, %%xmm5, %%xmm0, OP)\
-        QPEL_H264V_XMM(%%xmm2, %%xmm3, %%xmm4, %%xmm5, %%xmm0, %%xmm1, OP)\
-        QPEL_H264V_XMM(%%xmm3, %%xmm4, %%xmm5, %%xmm0, %%xmm1, %%xmm2, OP)\
-        QPEL_H264V_XMM(%%xmm4, %%xmm5, %%xmm0, %%xmm1, %%xmm2, %%xmm3, OP)\
-        QPEL_H264V_XMM(%%xmm5, %%xmm0, %%xmm1, %%xmm2, %%xmm3, %%xmm4, OP)\
-        QPEL_H264V_XMM(%%xmm0, %%xmm1, %%xmm2, %%xmm3, %%xmm4, %%xmm5, OP)\
-        QPEL_H264V_XMM(%%xmm1, %%xmm2, %%xmm3, %%xmm4, %%xmm5, %%xmm0, OP)\
-         \
-        : "+a"(src), "+c"(dst)\
-        : "S"((x86_reg)srcStride), "D"((x86_reg)dstStride), "m"(ff_pw_5), "m"(ff_pw_16)\
-        : "memory"\
-    );\
-    if(h==16){\
-        __asm__ volatile(\
-            QPEL_H264V_XMM(%%xmm2, %%xmm3, %%xmm4, %%xmm5, %%xmm0, %%xmm1, OP)\
-            QPEL_H264V_XMM(%%xmm3, %%xmm4, %%xmm5, %%xmm0, %%xmm1, %%xmm2, OP)\
-            QPEL_H264V_XMM(%%xmm4, %%xmm5, %%xmm0, %%xmm1, %%xmm2, %%xmm3, OP)\
-            QPEL_H264V_XMM(%%xmm5, %%xmm0, %%xmm1, %%xmm2, %%xmm3, %%xmm4, OP)\
-            QPEL_H264V_XMM(%%xmm0, %%xmm1, %%xmm2, %%xmm3, %%xmm4, %%xmm5, OP)\
-            QPEL_H264V_XMM(%%xmm1, %%xmm2, %%xmm3, %%xmm4, %%xmm5, %%xmm0, OP)\
-            QPEL_H264V_XMM(%%xmm2, %%xmm3, %%xmm4, %%xmm5, %%xmm0, %%xmm1, OP)\
-            QPEL_H264V_XMM(%%xmm3, %%xmm4, %%xmm5, %%xmm0, %%xmm1, %%xmm2, OP)\
-            \
-            : "+a"(src), "+c"(dst)\
-            : "S"((x86_reg)srcStride), "D"((x86_reg)dstStride), "m"(ff_pw_5), "m"(ff_pw_16)\
-            : "memory"\
-        );\
-    }\
-}\
-static void OPNAME ## h264_qpel8_v_lowpass_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride){\
-    OPNAME ## h264_qpel8or16_v_lowpass_ ## MMX(dst  , src  , dstStride, srcStride, 8);\
-}\
-static av_noinline void OPNAME ## h264_qpel16_v_lowpass_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride){\
-    OPNAME ## h264_qpel8or16_v_lowpass_ ## MMX(dst  , src  , dstStride, srcStride, 16);\
-    OPNAME ## h264_qpel8or16_v_lowpass_ ## MMX(dst+8, src+8, dstStride, srcStride, 16);\
-}
-
-static av_always_inline void put_h264_qpel8or16_hv1_lowpass_sse2(int16_t *tmp, uint8_t *src, int tmpStride, int srcStride, int size){
-    int w = (size+8)>>3;
-    src -= 2*srcStride+2;
-    while(w--){
-        __asm__ volatile(
-            "pxor %%xmm7, %%xmm7        \n\t"
-            "movq (%0), %%xmm0          \n\t"
-            "add %2, %0                 \n\t"
-            "movq (%0), %%xmm1          \n\t"
-            "add %2, %0                 \n\t"
-            "movq (%0), %%xmm2          \n\t"
-            "add %2, %0                 \n\t"
-            "movq (%0), %%xmm3          \n\t"
-            "add %2, %0                 \n\t"
-            "movq (%0), %%xmm4          \n\t"
-            "add %2, %0                 \n\t"
-            "punpcklbw %%xmm7, %%xmm0   \n\t"
-            "punpcklbw %%xmm7, %%xmm1   \n\t"
-            "punpcklbw %%xmm7, %%xmm2   \n\t"
-            "punpcklbw %%xmm7, %%xmm3   \n\t"
-            "punpcklbw %%xmm7, %%xmm4   \n\t"
-            QPEL_H264HV_XMM(%%xmm0, %%xmm1, %%xmm2, %%xmm3, %%xmm4, %%xmm5, 0*48)
-            QPEL_H264HV_XMM(%%xmm1, %%xmm2, %%xmm3, %%xmm4, %%xmm5, %%xmm0, 1*48)
-            QPEL_H264HV_XMM(%%xmm2, %%xmm3, %%xmm4, %%xmm5, %%xmm0, %%xmm1, 2*48)
-            QPEL_H264HV_XMM(%%xmm3, %%xmm4, %%xmm5, %%xmm0, %%xmm1, %%xmm2, 3*48)
-            QPEL_H264HV_XMM(%%xmm4, %%xmm5, %%xmm0, %%xmm1, %%xmm2, %%xmm3, 4*48)
-            QPEL_H264HV_XMM(%%xmm5, %%xmm0, %%xmm1, %%xmm2, %%xmm3, %%xmm4, 5*48)
-            QPEL_H264HV_XMM(%%xmm0, %%xmm1, %%xmm2, %%xmm3, %%xmm4, %%xmm5, 6*48)
-            QPEL_H264HV_XMM(%%xmm1, %%xmm2, %%xmm3, %%xmm4, %%xmm5, %%xmm0, 7*48)
-            : "+a"(src)
-            : "c"(tmp), "S"((x86_reg)srcStride), "m"(ff_pw_5), "m"(ff_pw_16)
-            : "memory"
-        );
-        if(size==16){
-            __asm__ volatile(
-                QPEL_H264HV_XMM(%%xmm2, %%xmm3, %%xmm4, %%xmm5, %%xmm0, %%xmm1,  8*48)
-                QPEL_H264HV_XMM(%%xmm3, %%xmm4, %%xmm5, %%xmm0, %%xmm1, %%xmm2,  9*48)
-                QPEL_H264HV_XMM(%%xmm4, %%xmm5, %%xmm0, %%xmm1, %%xmm2, %%xmm3, 10*48)
-                QPEL_H264HV_XMM(%%xmm5, %%xmm0, %%xmm1, %%xmm2, %%xmm3, %%xmm4, 11*48)
-                QPEL_H264HV_XMM(%%xmm0, %%xmm1, %%xmm2, %%xmm3, %%xmm4, %%xmm5, 12*48)
-                QPEL_H264HV_XMM(%%xmm1, %%xmm2, %%xmm3, %%xmm4, %%xmm5, %%xmm0, 13*48)
-                QPEL_H264HV_XMM(%%xmm2, %%xmm3, %%xmm4, %%xmm5, %%xmm0, %%xmm1, 14*48)
-                QPEL_H264HV_XMM(%%xmm3, %%xmm4, %%xmm5, %%xmm0, %%xmm1, %%xmm2, 15*48)
-                : "+a"(src)
-                : "c"(tmp), "S"((x86_reg)srcStride), "m"(ff_pw_5), "m"(ff_pw_16)
-                : "memory"
-            );
-        }
-        tmp += 8;
-        src += 8 - (size+5)*srcStride;
-    }
-}
-
-#define QPEL_H264_HV2_XMM(OPNAME, OP, MMX)\
-static av_always_inline void OPNAME ## h264_qpel8or16_hv2_lowpass_ ## MMX(uint8_t *dst, int16_t *tmp, int dstStride, int tmpStride, int size){\
-    int h = size;\
-    if(size == 16){\
-        __asm__ volatile(\
-            "1:                         \n\t"\
-            "movdqa 32(%0), %%xmm4      \n\t"\
-            "movdqa 16(%0), %%xmm5      \n\t"\
-            "movdqa   (%0), %%xmm7      \n\t"\
-            "movdqa %%xmm4, %%xmm3      \n\t"\
-            "movdqa %%xmm4, %%xmm2      \n\t"\
-            "movdqa %%xmm4, %%xmm1      \n\t"\
-            "movdqa %%xmm4, %%xmm0      \n\t"\
-            "palignr $10, %%xmm5, %%xmm0 \n\t"\
-            "palignr  $8, %%xmm5, %%xmm1 \n\t"\
-            "palignr  $6, %%xmm5, %%xmm2 \n\t"\
-            "palignr  $4, %%xmm5, %%xmm3 \n\t"\
-            "palignr  $2, %%xmm5, %%xmm4 \n\t"\
-            "paddw  %%xmm5, %%xmm0      \n\t"\
-            "paddw  %%xmm4, %%xmm1      \n\t"\
-            "paddw  %%xmm3, %%xmm2      \n\t"\
-            "movdqa %%xmm5, %%xmm6      \n\t"\
-            "movdqa %%xmm5, %%xmm4      \n\t"\
-            "movdqa %%xmm5, %%xmm3      \n\t"\
-            "palignr  $8, %%xmm7, %%xmm4 \n\t"\
-            "palignr  $2, %%xmm7, %%xmm6 \n\t"\
-            "palignr $10, %%xmm7, %%xmm3 \n\t"\
-            "paddw  %%xmm6, %%xmm4      \n\t"\
-            "movdqa %%xmm5, %%xmm6      \n\t"\
-            "palignr  $6, %%xmm7, %%xmm5 \n\t"\
-            "palignr  $4, %%xmm7, %%xmm6 \n\t"\
-            "paddw  %%xmm7, %%xmm3      \n\t"\
-            "paddw  %%xmm6, %%xmm5      \n\t"\
-            \
-            "psubw  %%xmm1, %%xmm0      \n\t"\
-            "psubw  %%xmm4, %%xmm3      \n\t"\
-            "psraw      $2, %%xmm0      \n\t"\
-            "psraw      $2, %%xmm3      \n\t"\
-            "psubw  %%xmm1, %%xmm0      \n\t"\
-            "psubw  %%xmm4, %%xmm3      \n\t"\
-            "paddw  %%xmm2, %%xmm0      \n\t"\
-            "paddw  %%xmm5, %%xmm3      \n\t"\
-            "psraw      $2, %%xmm0      \n\t"\
-            "psraw      $2, %%xmm3      \n\t"\
-            "paddw  %%xmm2, %%xmm0      \n\t"\
-            "paddw  %%xmm5, %%xmm3      \n\t"\
-            "psraw      $6, %%xmm0      \n\t"\
-            "psraw      $6, %%xmm3      \n\t"\
-            "packuswb %%xmm0, %%xmm3    \n\t"\
-            OP(%%xmm3, (%1), %%xmm7, dqa)\
-            "add $48, %0                \n\t"\
-            "add %3, %1                 \n\t"\
-            "decl %2                    \n\t"\
-            " jnz 1b                    \n\t"\
-            : "+a"(tmp), "+c"(dst), "+g"(h)\
-            : "S"((x86_reg)dstStride)\
-            : "memory"\
-        );\
-    }else{\
-        __asm__ volatile(\
-            "1:                         \n\t"\
-            "movdqa 16(%0), %%xmm1      \n\t"\
-            "movdqa   (%0), %%xmm0      \n\t"\
-            "movdqa %%xmm1, %%xmm2      \n\t"\
-            "movdqa %%xmm1, %%xmm3      \n\t"\
-            "movdqa %%xmm1, %%xmm4      \n\t"\
-            "movdqa %%xmm1, %%xmm5      \n\t"\
-            "palignr $10, %%xmm0, %%xmm5 \n\t"\
-            "palignr  $8, %%xmm0, %%xmm4 \n\t"\
-            "palignr  $6, %%xmm0, %%xmm3 \n\t"\
-            "palignr  $4, %%xmm0, %%xmm2 \n\t"\
-            "palignr  $2, %%xmm0, %%xmm1 \n\t"\
-            "paddw  %%xmm5, %%xmm0      \n\t"\
-            "paddw  %%xmm4, %%xmm1      \n\t"\
-            "paddw  %%xmm3, %%xmm2      \n\t"\
-            "psubw  %%xmm1, %%xmm0      \n\t"\
-            "psraw      $2, %%xmm0      \n\t"\
-            "psubw  %%xmm1, %%xmm0      \n\t"\
-            "paddw  %%xmm2, %%xmm0      \n\t"\
-            "psraw      $2, %%xmm0      \n\t"\
-            "paddw  %%xmm2, %%xmm0      \n\t"\
-            "psraw      $6, %%xmm0      \n\t"\
-            "packuswb %%xmm0, %%xmm0    \n\t"\
-            OP(%%xmm0, (%1), %%xmm7, q)\
-            "add $48, %0                \n\t"\
-            "add %3, %1                 \n\t"\
-            "decl %2                    \n\t"\
-            " jnz 1b                    \n\t"\
-            : "+a"(tmp), "+c"(dst), "+g"(h)\
-            : "S"((x86_reg)dstStride)\
-            : "memory"\
-        );\
-    }\
-}
-
-#define QPEL_H264_HV_XMM(OPNAME, OP, MMX)\
-static av_noinline void OPNAME ## h264_qpel8or16_hv_lowpass_ ## MMX(uint8_t *dst, int16_t *tmp, uint8_t *src, int dstStride, int tmpStride, int srcStride, int size){\
-          put_h264_qpel8or16_hv1_lowpass_sse2(tmp, src, tmpStride, srcStride, size);\
-    OPNAME ## h264_qpel8or16_hv2_lowpass_ ## MMX(dst, tmp, dstStride, tmpStride, size);\
-}\
-static void OPNAME ## h264_qpel8_hv_lowpass_ ## MMX(uint8_t *dst, int16_t *tmp, uint8_t *src, int dstStride, int tmpStride, int srcStride){\
-    OPNAME ## h264_qpel8or16_hv_lowpass_ ## MMX(dst, tmp, src, dstStride, tmpStride, srcStride, 8);\
-}\
-static void OPNAME ## h264_qpel16_hv_lowpass_ ## MMX(uint8_t *dst, int16_t *tmp, uint8_t *src, int dstStride, int tmpStride, int srcStride){\
-    OPNAME ## h264_qpel8or16_hv_lowpass_ ## MMX(dst, tmp, src, dstStride, tmpStride, srcStride, 16);\
-}\
-
-#define put_pixels8_l2_sse2 put_pixels8_l2_mmx2
-#define avg_pixels8_l2_sse2 avg_pixels8_l2_mmx2
-#define put_pixels16_l2_sse2 put_pixels16_l2_mmx2
-#define avg_pixels16_l2_sse2 avg_pixels16_l2_mmx2
-#define put_pixels8_l2_ssse3 put_pixels8_l2_mmx2
-#define avg_pixels8_l2_ssse3 avg_pixels8_l2_mmx2
-#define put_pixels16_l2_ssse3 put_pixels16_l2_mmx2
-#define avg_pixels16_l2_ssse3 avg_pixels16_l2_mmx2
-
-#define put_pixels8_l2_shift5_sse2 put_pixels8_l2_shift5_mmx2
-#define avg_pixels8_l2_shift5_sse2 avg_pixels8_l2_shift5_mmx2
-#define put_pixels16_l2_shift5_sse2 put_pixels16_l2_shift5_mmx2
-#define avg_pixels16_l2_shift5_sse2 avg_pixels16_l2_shift5_mmx2
-#define put_pixels8_l2_shift5_ssse3 put_pixels8_l2_shift5_mmx2
-#define avg_pixels8_l2_shift5_ssse3 avg_pixels8_l2_shift5_mmx2
-#define put_pixels16_l2_shift5_ssse3 put_pixels16_l2_shift5_mmx2
-#define avg_pixels16_l2_shift5_ssse3 avg_pixels16_l2_shift5_mmx2
-
-#define put_h264_qpel8_h_lowpass_l2_sse2 put_h264_qpel8_h_lowpass_l2_mmx2
-#define avg_h264_qpel8_h_lowpass_l2_sse2 avg_h264_qpel8_h_lowpass_l2_mmx2
-#define put_h264_qpel16_h_lowpass_l2_sse2 put_h264_qpel16_h_lowpass_l2_mmx2
-#define avg_h264_qpel16_h_lowpass_l2_sse2 avg_h264_qpel16_h_lowpass_l2_mmx2
+#define LF_FUNC(DIR, TYPE, OPT) \
+void ff_x264_deblock_ ## DIR ## _ ## TYPE ## _ ## OPT (uint8_t *pix, int stride, \
+                                               int alpha, int beta, int8_t *tc0);
+#define LF_IFUNC(DIR, TYPE, OPT) \
+void ff_x264_deblock_ ## DIR ## _ ## TYPE ## _ ## OPT (uint8_t *pix, int stride, \
+                                               int alpha, int beta);
 
-#define put_h264_qpel8_v_lowpass_ssse3 put_h264_qpel8_v_lowpass_sse2
-#define avg_h264_qpel8_v_lowpass_ssse3 avg_h264_qpel8_v_lowpass_sse2
-#define put_h264_qpel16_v_lowpass_ssse3 put_h264_qpel16_v_lowpass_sse2
-#define avg_h264_qpel16_v_lowpass_ssse3 avg_h264_qpel16_v_lowpass_sse2
+LF_FUNC (h,  chroma,       mmxext)
+LF_IFUNC(h,  chroma_intra, mmxext)
+LF_FUNC (v,  chroma,       mmxext)
+LF_IFUNC(v,  chroma_intra, mmxext)
 
-#define put_h264_qpel8or16_hv2_lowpass_sse2 put_h264_qpel8or16_hv2_lowpass_mmx2
-#define avg_h264_qpel8or16_hv2_lowpass_sse2 avg_h264_qpel8or16_hv2_lowpass_mmx2
-
-#define H264_MC(OPNAME, SIZE, MMX, ALIGN) \
-H264_MC_C(OPNAME, SIZE, MMX, ALIGN)\
-H264_MC_V(OPNAME, SIZE, MMX, ALIGN)\
-H264_MC_H(OPNAME, SIZE, MMX, ALIGN)\
-H264_MC_HV(OPNAME, SIZE, MMX, ALIGN)\
-
-static void put_h264_qpel16_mc00_sse2 (uint8_t *dst, uint8_t *src, int stride){
-    put_pixels16_sse2(dst, src, stride, 16);
-}
-static void avg_h264_qpel16_mc00_sse2 (uint8_t *dst, uint8_t *src, int stride){
-    avg_pixels16_sse2(dst, src, stride, 16);
-}
-#define put_h264_qpel8_mc00_sse2 put_h264_qpel8_mc00_mmx2
-#define avg_h264_qpel8_mc00_sse2 avg_h264_qpel8_mc00_mmx2
-
-#define H264_MC_C(OPNAME, SIZE, MMX, ALIGN) \
-static void OPNAME ## h264_qpel ## SIZE ## _mc00_ ## MMX (uint8_t *dst, uint8_t *src, int stride){\
-    OPNAME ## pixels ## SIZE ## _ ## MMX(dst, src, stride, SIZE);\
-}\
-
-#define H264_MC_H(OPNAME, SIZE, MMX, ALIGN) \
-static void OPNAME ## h264_qpel ## SIZE ## _mc10_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\
-    OPNAME ## h264_qpel ## SIZE ## _h_lowpass_l2_ ## MMX(dst, src, src, stride, stride);\
-}\
-\
-static void OPNAME ## h264_qpel ## SIZE ## _mc20_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\
-    OPNAME ## h264_qpel ## SIZE ## _h_lowpass_ ## MMX(dst, src, stride, stride);\
-}\
-\
-static void OPNAME ## h264_qpel ## SIZE ## _mc30_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\
-    OPNAME ## h264_qpel ## SIZE ## _h_lowpass_l2_ ## MMX(dst, src, src+1, stride, stride);\
-}\
-
-#define H264_MC_V(OPNAME, SIZE, MMX, ALIGN) \
-static void OPNAME ## h264_qpel ## SIZE ## _mc01_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\
-    DECLARE_ALIGNED(ALIGN, uint8_t, temp)[SIZE*SIZE];\
-    put_h264_qpel ## SIZE ## _v_lowpass_ ## MMX(temp, src, SIZE, stride);\
-    OPNAME ## pixels ## SIZE ## _l2_ ## MMX(dst, src, temp, stride, stride, SIZE);\
-}\
-\
-static void OPNAME ## h264_qpel ## SIZE ## _mc02_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\
-    OPNAME ## h264_qpel ## SIZE ## _v_lowpass_ ## MMX(dst, src, stride, stride);\
-}\
-\
-static void OPNAME ## h264_qpel ## SIZE ## _mc03_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\
-    DECLARE_ALIGNED(ALIGN, uint8_t, temp)[SIZE*SIZE];\
-    put_h264_qpel ## SIZE ## _v_lowpass_ ## MMX(temp, src, SIZE, stride);\
-    OPNAME ## pixels ## SIZE ## _l2_ ## MMX(dst, src+stride, temp, stride, stride, SIZE);\
-}\
-
-#define H264_MC_HV(OPNAME, SIZE, MMX, ALIGN) \
-static void OPNAME ## h264_qpel ## SIZE ## _mc11_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\
-    DECLARE_ALIGNED(ALIGN, uint8_t, temp)[SIZE*SIZE];\
-    put_h264_qpel ## SIZE ## _v_lowpass_ ## MMX(temp, src, SIZE, stride);\
-    OPNAME ## h264_qpel ## SIZE ## _h_lowpass_l2_ ## MMX(dst, src, temp, stride, SIZE);\
-}\
-\
-static void OPNAME ## h264_qpel ## SIZE ## _mc31_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\
-    DECLARE_ALIGNED(ALIGN, uint8_t, temp)[SIZE*SIZE];\
-    put_h264_qpel ## SIZE ## _v_lowpass_ ## MMX(temp, src+1, SIZE, stride);\
-    OPNAME ## h264_qpel ## SIZE ## _h_lowpass_l2_ ## MMX(dst, src, temp, stride, SIZE);\
-}\
-\
-static void OPNAME ## h264_qpel ## SIZE ## _mc13_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\
-    DECLARE_ALIGNED(ALIGN, uint8_t, temp)[SIZE*SIZE];\
-    put_h264_qpel ## SIZE ## _v_lowpass_ ## MMX(temp, src, SIZE, stride);\
-    OPNAME ## h264_qpel ## SIZE ## _h_lowpass_l2_ ## MMX(dst, src+stride, temp, stride, SIZE);\
-}\
-\
-static void OPNAME ## h264_qpel ## SIZE ## _mc33_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\
-    DECLARE_ALIGNED(ALIGN, uint8_t, temp)[SIZE*SIZE];\
-    put_h264_qpel ## SIZE ## _v_lowpass_ ## MMX(temp, src+1, SIZE, stride);\
-    OPNAME ## h264_qpel ## SIZE ## _h_lowpass_l2_ ## MMX(dst, src+stride, temp, stride, SIZE);\
-}\
-\
-static void OPNAME ## h264_qpel ## SIZE ## _mc22_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\
-    DECLARE_ALIGNED(ALIGN, uint16_t, temp)[SIZE*(SIZE<8?12:24)];\
-    OPNAME ## h264_qpel ## SIZE ## _hv_lowpass_ ## MMX(dst, temp, src, stride, SIZE, stride);\
-}\
-\
-static void OPNAME ## h264_qpel ## SIZE ## _mc21_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\
-    DECLARE_ALIGNED(ALIGN, uint8_t, temp)[SIZE*(SIZE<8?12:24)*2 + SIZE*SIZE];\
-    uint8_t * const halfHV= temp;\
-    int16_t * const halfV= (int16_t*)(temp + SIZE*SIZE);\
-    assert(((int)temp & 7) == 0);\
-    put_h264_qpel ## SIZE ## _hv_lowpass_ ## MMX(halfHV, halfV, src, SIZE, SIZE, stride);\
-    OPNAME ## h264_qpel ## SIZE ## _h_lowpass_l2_ ## MMX(dst, src, halfHV, stride, SIZE);\
-}\
-\
-static void OPNAME ## h264_qpel ## SIZE ## _mc23_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\
-    DECLARE_ALIGNED(ALIGN, uint8_t, temp)[SIZE*(SIZE<8?12:24)*2 + SIZE*SIZE];\
-    uint8_t * const halfHV= temp;\
-    int16_t * const halfV= (int16_t*)(temp + SIZE*SIZE);\
-    assert(((int)temp & 7) == 0);\
-    put_h264_qpel ## SIZE ## _hv_lowpass_ ## MMX(halfHV, halfV, src, SIZE, SIZE, stride);\
-    OPNAME ## h264_qpel ## SIZE ## _h_lowpass_l2_ ## MMX(dst, src+stride, halfHV, stride, SIZE);\
-}\
-\
-static void OPNAME ## h264_qpel ## SIZE ## _mc12_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\
-    DECLARE_ALIGNED(ALIGN, uint8_t, temp)[SIZE*(SIZE<8?12:24)*2 + SIZE*SIZE];\
-    uint8_t * const halfHV= temp;\
-    int16_t * const halfV= (int16_t*)(temp + SIZE*SIZE);\
-    assert(((int)temp & 7) == 0);\
-    put_h264_qpel ## SIZE ## _hv_lowpass_ ## MMX(halfHV, halfV, src, SIZE, SIZE, stride);\
-    OPNAME ## pixels ## SIZE ## _l2_shift5_ ## MMX(dst, halfV+2, halfHV, stride, SIZE, SIZE);\
-}\
-\
-static void OPNAME ## h264_qpel ## SIZE ## _mc32_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\
-    DECLARE_ALIGNED(ALIGN, uint8_t, temp)[SIZE*(SIZE<8?12:24)*2 + SIZE*SIZE];\
-    uint8_t * const halfHV= temp;\
-    int16_t * const halfV= (int16_t*)(temp + SIZE*SIZE);\
-    assert(((int)temp & 7) == 0);\
-    put_h264_qpel ## SIZE ## _hv_lowpass_ ## MMX(halfHV, halfV, src, SIZE, SIZE, stride);\
-    OPNAME ## pixels ## SIZE ## _l2_shift5_ ## MMX(dst, halfV+3, halfHV, stride, SIZE, SIZE);\
-}\
-
-#define H264_MC_4816(MMX)\
-H264_MC(put_, 4, MMX, 8)\
-H264_MC(put_, 8, MMX, 8)\
-H264_MC(put_, 16,MMX, 8)\
-H264_MC(avg_, 4, MMX, 8)\
-H264_MC(avg_, 8, MMX, 8)\
-H264_MC(avg_, 16,MMX, 8)\
-
-#define H264_MC_816(QPEL, XMM)\
-QPEL(put_, 8, XMM, 16)\
-QPEL(put_, 16,XMM, 16)\
-QPEL(avg_, 8, XMM, 16)\
-QPEL(avg_, 16,XMM, 16)\
-
-
-#define AVG_3DNOW_OP(a,b,temp, size) \
-"mov" #size " " #b ", " #temp "   \n\t"\
-"pavgusb " #temp ", " #a "        \n\t"\
-"mov" #size " " #a ", " #b "      \n\t"
-#define AVG_MMX2_OP(a,b,temp, size) \
-"mov" #size " " #b ", " #temp "   \n\t"\
-"pavgb " #temp ", " #a "          \n\t"\
-"mov" #size " " #a ", " #b "      \n\t"
-
-#define PAVGB "pavgusb"
-QPEL_H264(put_,       PUT_OP, 3dnow)
-QPEL_H264(avg_, AVG_3DNOW_OP, 3dnow)
-#undef PAVGB
-#define PAVGB "pavgb"
-QPEL_H264(put_,       PUT_OP, mmx2)
-QPEL_H264(avg_,  AVG_MMX2_OP, mmx2)
-QPEL_H264_V_XMM(put_,       PUT_OP, sse2)
-QPEL_H264_V_XMM(avg_,  AVG_MMX2_OP, sse2)
-QPEL_H264_HV_XMM(put_,       PUT_OP, sse2)
-QPEL_H264_HV_XMM(avg_,  AVG_MMX2_OP, sse2)
-#if HAVE_SSSE3
-QPEL_H264_H_XMM(put_,       PUT_OP, ssse3)
-QPEL_H264_H_XMM(avg_,  AVG_MMX2_OP, ssse3)
-QPEL_H264_HV2_XMM(put_,       PUT_OP, ssse3)
-QPEL_H264_HV2_XMM(avg_,  AVG_MMX2_OP, ssse3)
-QPEL_H264_HV_XMM(put_,       PUT_OP, ssse3)
-QPEL_H264_HV_XMM(avg_,  AVG_MMX2_OP, ssse3)
-#endif
-#undef PAVGB
-
-H264_MC_4816(3dnow)
-H264_MC_4816(mmx2)
-H264_MC_816(H264_MC_V, sse2)
-H264_MC_816(H264_MC_HV, sse2)
-#if HAVE_SSSE3
-H264_MC_816(H264_MC_H, ssse3)
-H264_MC_816(H264_MC_HV, ssse3)
-#endif
-
-/* rnd interleaved with rnd div 8, use p+1 to access rnd div 8 */
-DECLARE_ALIGNED(8, static const uint64_t, h264_rnd_reg)[4] = {
-    0x0020002000200020ULL, 0x0004000400040004ULL, 0x001C001C001C001CULL, 0x0003000300030003ULL
-};
-
-#define H264_CHROMA_OP(S,D)
-#define H264_CHROMA_OP4(S,D,T)
-#define H264_CHROMA_MC8_TMPL put_h264_chroma_generic_mc8_mmx
-#define H264_CHROMA_MC4_TMPL put_h264_chroma_generic_mc4_mmx
-#define H264_CHROMA_MC2_TMPL put_h264_chroma_mc2_mmx2
-#define H264_CHROMA_MC8_MV0 put_pixels8_mmx
-#include "dsputil_h264_template_mmx.c"
-
-static void put_h264_chroma_mc8_mmx_rnd(uint8_t *dst/*align 8*/, uint8_t *src/*align 1*/, int stride, int h, int x, int y)
-{
-    put_h264_chroma_generic_mc8_mmx(dst, src, stride, h, x, y, h264_rnd_reg);
-}
-static void put_vc1_chroma_mc8_mmx_nornd(uint8_t *dst/*align 8*/, uint8_t *src/*align 1*/, int stride, int h, int x, int y)
-{
-    put_h264_chroma_generic_mc8_mmx(dst, src, stride, h, x, y, h264_rnd_reg+2);
-}
-static void put_h264_chroma_mc4_mmx(uint8_t *dst/*align 8*/, uint8_t *src/*align 1*/, int stride, int h, int x, int y)
-{
-    put_h264_chroma_generic_mc4_mmx(dst, src, stride, h, x, y, h264_rnd_reg);
-}
-
-#undef H264_CHROMA_OP
-#undef H264_CHROMA_OP4
-#undef H264_CHROMA_MC8_TMPL
-#undef H264_CHROMA_MC4_TMPL
-#undef H264_CHROMA_MC2_TMPL
-#undef H264_CHROMA_MC8_MV0
-
-#define H264_CHROMA_OP(S,D) "pavgb " #S ", " #D " \n\t"
-#define H264_CHROMA_OP4(S,D,T) "movd  " #S ", " #T " \n\t"\
-                               "pavgb " #T ", " #D " \n\t"
-#define H264_CHROMA_MC8_TMPL avg_h264_chroma_generic_mc8_mmx2
-#define H264_CHROMA_MC4_TMPL avg_h264_chroma_generic_mc4_mmx2
-#define H264_CHROMA_MC2_TMPL avg_h264_chroma_mc2_mmx2
-#define H264_CHROMA_MC8_MV0 avg_pixels8_mmx2
-#include "dsputil_h264_template_mmx.c"
-static void avg_h264_chroma_mc8_mmx2_rnd(uint8_t *dst/*align 8*/, uint8_t *src/*align 1*/, int stride, int h, int x, int y)
-{
-    avg_h264_chroma_generic_mc8_mmx2(dst, src, stride, h, x, y, h264_rnd_reg);
-}
-static void avg_vc1_chroma_mc8_mmx2_nornd(uint8_t *dst/*align 8*/, uint8_t *src/*align 1*/, int stride, int h, int x, int y)
-{
-    avg_h264_chroma_generic_mc8_mmx2(dst, src, stride, h, x, y, h264_rnd_reg+2);
-}
-static void avg_h264_chroma_mc4_mmx2(uint8_t *dst/*align 8*/, uint8_t *src/*align 1*/, int stride, int h, int x, int y)
-{
-    avg_h264_chroma_generic_mc4_mmx2(dst, src, stride, h, x, y, h264_rnd_reg);
-}
-#undef H264_CHROMA_OP
-#undef H264_CHROMA_OP4
-#undef H264_CHROMA_MC8_TMPL
-#undef H264_CHROMA_MC4_TMPL
-#undef H264_CHROMA_MC2_TMPL
-#undef H264_CHROMA_MC8_MV0
-
-#define H264_CHROMA_OP(S,D) "pavgusb " #S ", " #D " \n\t"
-#define H264_CHROMA_OP4(S,D,T) "movd " #S ", " #T " \n\t"\
-                               "pavgusb " #T ", " #D " \n\t"
-#define H264_CHROMA_MC8_TMPL avg_h264_chroma_generic_mc8_3dnow
-#define H264_CHROMA_MC4_TMPL avg_h264_chroma_generic_mc4_3dnow
-#define H264_CHROMA_MC8_MV0 avg_pixels8_3dnow
-#include "dsputil_h264_template_mmx.c"
-static void avg_h264_chroma_mc8_3dnow_rnd(uint8_t *dst/*align 8*/, uint8_t *src/*align 1*/, int stride, int h, int x, int y)
-{
-    avg_h264_chroma_generic_mc8_3dnow(dst, src, stride, h, x, y, h264_rnd_reg);
-}
-static void avg_h264_chroma_mc4_3dnow(uint8_t *dst/*align 8*/, uint8_t *src/*align 1*/, int stride, int h, int x, int y)
-{
-    avg_h264_chroma_generic_mc4_3dnow(dst, src, stride, h, x, y, h264_rnd_reg);
-}
-#undef H264_CHROMA_OP
-#undef H264_CHROMA_OP4
-#undef H264_CHROMA_MC8_TMPL
-#undef H264_CHROMA_MC4_TMPL
-#undef H264_CHROMA_MC8_MV0
-
-#if HAVE_SSSE3
-#define AVG_OP(X)
-#undef H264_CHROMA_MC8_TMPL
-#undef H264_CHROMA_MC4_TMPL
-#define H264_CHROMA_MC8_TMPL put_h264_chroma_mc8_ssse3
-#define H264_CHROMA_MC4_TMPL put_h264_chroma_mc4_ssse3
-#define H264_CHROMA_MC8_MV0 put_pixels8_mmx
-#include "dsputil_h264_template_ssse3.c"
-static void put_h264_chroma_mc8_ssse3_rnd(uint8_t *dst/*align 8*/, uint8_t *src/*align 1*/, int stride, int h, int x, int y)
-{
-    put_h264_chroma_mc8_ssse3(dst, src, stride, h, x, y, 1);
-}
-static void put_vc1_chroma_mc8_ssse3_nornd(uint8_t *dst/*align 8*/, uint8_t *src/*align 1*/, int stride, int h, int x, int y)
-{
-    put_h264_chroma_mc8_ssse3(dst, src, stride, h, x, y, 0);
-}
-
-#undef AVG_OP
-#undef H264_CHROMA_MC8_TMPL
-#undef H264_CHROMA_MC4_TMPL
-#undef H264_CHROMA_MC8_MV0
-#define AVG_OP(X) X
-#define H264_CHROMA_MC8_TMPL avg_h264_chroma_mc8_ssse3
-#define H264_CHROMA_MC4_TMPL avg_h264_chroma_mc4_ssse3
-#define H264_CHROMA_MC8_MV0 avg_pixels8_mmx2
-#include "dsputil_h264_template_ssse3.c"
-static void avg_h264_chroma_mc8_ssse3_rnd(uint8_t *dst/*align 8*/, uint8_t *src/*align 1*/, int stride, int h, int x, int y)
+LF_FUNC (h,  luma,         mmxext)
+LF_IFUNC(h,  luma_intra,   mmxext)
+#if HAVE_YASM && ARCH_X86_32
+LF_FUNC (v8, luma,         mmxext)
+static void ff_x264_deblock_v_luma_mmxext(uint8_t *pix, int stride, int alpha, int beta, int8_t *tc0)
 {
-    avg_h264_chroma_mc8_ssse3(dst, src, stride, h, x, y, 1);
+    if((tc0[0] & tc0[1]) >= 0)
+        ff_x264_deblock_v8_luma_mmxext(pix+0, stride, alpha, beta, tc0);
+    if((tc0[2] & tc0[3]) >= 0)
+        ff_x264_deblock_v8_luma_mmxext(pix+8, stride, alpha, beta, tc0+2);
 }
-static void avg_vc1_chroma_mc8_ssse3_nornd(uint8_t *dst/*align 8*/, uint8_t *src/*align 1*/, int stride, int h, int x, int y)
+LF_IFUNC(v8, luma_intra,   mmxext)
+static void ff_x264_deblock_v_luma_intra_mmxext(uint8_t *pix, int stride, int alpha, int beta)
 {
-    avg_h264_chroma_mc8_ssse3(dst, src, stride, h, x, y, 0);
+    ff_x264_deblock_v8_luma_intra_mmxext(pix+0, stride, alpha, beta);
+    ff_x264_deblock_v8_luma_intra_mmxext(pix+8, stride, alpha, beta);
 }
-#undef AVG_OP
-#undef H264_CHROMA_MC8_TMPL
-#undef H264_CHROMA_MC4_TMPL
-#undef H264_CHROMA_MC8_MV0
 #endif
 
+LF_FUNC (h,  luma,         sse2)
+LF_IFUNC(h,  luma_intra,   sse2)
+LF_FUNC (v,  luma,         sse2)
+LF_IFUNC(v,  luma_intra,   sse2)
+
 /***********************************/
 /* weighted prediction */
 
-static inline void ff_h264_weight_WxH_mmx2(uint8_t *dst, int stride, int log2_denom, int weight, int offset, int w, int h)
+#define H264_WEIGHT(W, H, OPT) \
+void ff_h264_weight_ ## W ## x ## H ## _ ## OPT(uint8_t *dst, \
+    int stride, int log2_denom, int weight, int offset);
+
+#define H264_BIWEIGHT(W, H, OPT) \
+void ff_h264_biweight_ ## W ## x ## H ## _ ## OPT(uint8_t *dst, \
+    uint8_t *src, int stride, int log2_denom, int weightd, \
+    int weights, int offset);
+
+#define H264_BIWEIGHT_MMX(W,H) \
+H264_WEIGHT  (W, H, mmx2) \
+H264_BIWEIGHT(W, H, mmx2)
+
+#define H264_BIWEIGHT_MMX_SSE(W,H) \
+H264_BIWEIGHT_MMX(W, H) \
+H264_WEIGHT      (W, H, sse2) \
+H264_BIWEIGHT    (W, H, sse2) \
+H264_BIWEIGHT    (W, H, ssse3)
+
+H264_BIWEIGHT_MMX_SSE(16, 16)
+H264_BIWEIGHT_MMX_SSE(16,  8)
+H264_BIWEIGHT_MMX_SSE( 8, 16)
+H264_BIWEIGHT_MMX_SSE( 8,  8)
+H264_BIWEIGHT_MMX_SSE( 8,  4)
+H264_BIWEIGHT_MMX    ( 4,  8)
+H264_BIWEIGHT_MMX    ( 4,  4)
+H264_BIWEIGHT_MMX    ( 4,  2)
+
+void ff_h264dsp_init_x86(H264DSPContext *c)
 {
-    int x, y;
-    offset <<= log2_denom;
-    offset += (1 << log2_denom) >> 1;
-    __asm__ volatile(
-        "movd    %0, %%mm4        \n\t"
-        "movd    %1, %%mm5        \n\t"
-        "movd    %2, %%mm6        \n\t"
-        "pshufw  $0, %%mm4, %%mm4 \n\t"
-        "pshufw  $0, %%mm5, %%mm5 \n\t"
-        "pxor    %%mm7, %%mm7     \n\t"
-        :: "g"(weight), "g"(offset), "g"(log2_denom)
-    );
-    for(y=0; y<h; y+=2){
-        for(x=0; x<w; x+=4){
-            __asm__ volatile(
-                "movd      %0,    %%mm0 \n\t"
-                "movd      %1,    %%mm1 \n\t"
-                "punpcklbw %%mm7, %%mm0 \n\t"
-                "punpcklbw %%mm7, %%mm1 \n\t"
-                "pmullw    %%mm4, %%mm0 \n\t"
-                "pmullw    %%mm4, %%mm1 \n\t"
-                "paddsw    %%mm5, %%mm0 \n\t"
-                "paddsw    %%mm5, %%mm1 \n\t"
-                "psraw     %%mm6, %%mm0 \n\t"
-                "psraw     %%mm6, %%mm1 \n\t"
-                "packuswb  %%mm7, %%mm0 \n\t"
-                "packuswb  %%mm7, %%mm1 \n\t"
-                "movd      %%mm0, %0    \n\t"
-                "movd      %%mm1, %1    \n\t"
-                : "+m"(*(uint32_t*)(dst+x)),
-                  "+m"(*(uint32_t*)(dst+x+stride))
-            );
-        }
-        dst += 2*stride;
+    int mm_flags = av_get_cpu_flags();
+
+    if (mm_flags & AV_CPU_FLAG_MMX2) {
+        c->h264_loop_filter_strength= h264_loop_filter_strength_mmx2;
     }
-}
+#if HAVE_YASM
+    if (mm_flags & AV_CPU_FLAG_MMX) {
+        c->h264_idct_dc_add=
+        c->h264_idct_add= ff_h264_idct_add_mmx;
+        c->h264_idct8_dc_add=
+        c->h264_idct8_add= ff_h264_idct8_add_mmx;
+
+        c->h264_idct_add16     = ff_h264_idct_add16_mmx;
+        c->h264_idct8_add4     = ff_h264_idct8_add4_mmx;
+        c->h264_idct_add8      = ff_h264_idct_add8_mmx;
+        c->h264_idct_add16intra= ff_h264_idct_add16intra_mmx;
+        c->h264_luma_dc_dequant_idct= ff_h264_luma_dc_dequant_idct_mmx;
+
+        if (mm_flags & AV_CPU_FLAG_MMX2) {
+            c->h264_idct_dc_add= ff_h264_idct_dc_add_mmx2;
+            c->h264_idct8_dc_add= ff_h264_idct8_dc_add_mmx2;
+            c->h264_idct_add16     = ff_h264_idct_add16_mmx2;
+            c->h264_idct8_add4     = ff_h264_idct8_add4_mmx2;
+            c->h264_idct_add8      = ff_h264_idct_add8_mmx2;
+            c->h264_idct_add16intra= ff_h264_idct_add16intra_mmx2;
+
+            c->h264_v_loop_filter_chroma= ff_x264_deblock_v_chroma_mmxext;
+            c->h264_h_loop_filter_chroma= ff_x264_deblock_h_chroma_mmxext;
+            c->h264_v_loop_filter_chroma_intra= ff_x264_deblock_v_chroma_intra_mmxext;
+            c->h264_h_loop_filter_chroma_intra= ff_x264_deblock_h_chroma_intra_mmxext;
+#if ARCH_X86_32
+            c->h264_v_loop_filter_luma= ff_x264_deblock_v_luma_mmxext;
+            c->h264_h_loop_filter_luma= ff_x264_deblock_h_luma_mmxext;
+            c->h264_v_loop_filter_luma_intra = ff_x264_deblock_v_luma_intra_mmxext;
+            c->h264_h_loop_filter_luma_intra = ff_x264_deblock_h_luma_intra_mmxext;
+#endif
+            c->weight_h264_pixels_tab[0]= ff_h264_weight_16x16_mmx2;
+            c->weight_h264_pixels_tab[1]= ff_h264_weight_16x8_mmx2;
+            c->weight_h264_pixels_tab[2]= ff_h264_weight_8x16_mmx2;
+            c->weight_h264_pixels_tab[3]= ff_h264_weight_8x8_mmx2;
+            c->weight_h264_pixels_tab[4]= ff_h264_weight_8x4_mmx2;
+            c->weight_h264_pixels_tab[5]= ff_h264_weight_4x8_mmx2;
+            c->weight_h264_pixels_tab[6]= ff_h264_weight_4x4_mmx2;
+            c->weight_h264_pixels_tab[7]= ff_h264_weight_4x2_mmx2;
+
+            c->biweight_h264_pixels_tab[0]= ff_h264_biweight_16x16_mmx2;
+            c->biweight_h264_pixels_tab[1]= ff_h264_biweight_16x8_mmx2;
+            c->biweight_h264_pixels_tab[2]= ff_h264_biweight_8x16_mmx2;
+            c->biweight_h264_pixels_tab[3]= ff_h264_biweight_8x8_mmx2;
+            c->biweight_h264_pixels_tab[4]= ff_h264_biweight_8x4_mmx2;
+            c->biweight_h264_pixels_tab[5]= ff_h264_biweight_4x8_mmx2;
+            c->biweight_h264_pixels_tab[6]= ff_h264_biweight_4x4_mmx2;
+            c->biweight_h264_pixels_tab[7]= ff_h264_biweight_4x2_mmx2;
+
+            if (mm_flags&AV_CPU_FLAG_SSE2) {
+                c->h264_idct8_add = ff_h264_idct8_add_sse2;
+                c->h264_idct8_add4= ff_h264_idct8_add4_sse2;
+                c->h264_luma_dc_dequant_idct= ff_h264_luma_dc_dequant_idct_sse2;
+
+                c->weight_h264_pixels_tab[0]= ff_h264_weight_16x16_sse2;
+                c->weight_h264_pixels_tab[1]= ff_h264_weight_16x8_sse2;
+                c->weight_h264_pixels_tab[2]= ff_h264_weight_8x16_sse2;
+                c->weight_h264_pixels_tab[3]= ff_h264_weight_8x8_sse2;
+                c->weight_h264_pixels_tab[4]= ff_h264_weight_8x4_sse2;
+
+                c->biweight_h264_pixels_tab[0]= ff_h264_biweight_16x16_sse2;
+                c->biweight_h264_pixels_tab[1]= ff_h264_biweight_16x8_sse2;
+                c->biweight_h264_pixels_tab[2]= ff_h264_biweight_8x16_sse2;
+                c->biweight_h264_pixels_tab[3]= ff_h264_biweight_8x8_sse2;
+                c->biweight_h264_pixels_tab[4]= ff_h264_biweight_8x4_sse2;
+
+#if HAVE_ALIGNED_STACK
+                c->h264_v_loop_filter_luma = ff_x264_deblock_v_luma_sse2;
+                c->h264_h_loop_filter_luma = ff_x264_deblock_h_luma_sse2;
+                c->h264_v_loop_filter_luma_intra = ff_x264_deblock_v_luma_intra_sse2;
+                c->h264_h_loop_filter_luma_intra = ff_x264_deblock_h_luma_intra_sse2;
+#endif
 
-static inline void ff_h264_biweight_WxH_mmx2(uint8_t *dst, uint8_t *src, int stride, int log2_denom, int weightd, int weights, int offset, int w, int h)
-{
-    int x, y;
-    offset = ((offset + 1) | 1) << log2_denom;
-    __asm__ volatile(
-        "movd    %0, %%mm3        \n\t"
-        "movd    %1, %%mm4        \n\t"
-        "movd    %2, %%mm5        \n\t"
-        "movd    %3, %%mm6        \n\t"
-        "pshufw  $0, %%mm3, %%mm3 \n\t"
-        "pshufw  $0, %%mm4, %%mm4 \n\t"
-        "pshufw  $0, %%mm5, %%mm5 \n\t"
-        "pxor    %%mm7, %%mm7     \n\t"
-        :: "g"(weightd), "g"(weights), "g"(offset), "g"(log2_denom+1)
-    );
-    for(y=0; y<h; y++){
-        for(x=0; x<w; x+=4){
-            __asm__ volatile(
-                "movd      %0,    %%mm0 \n\t"
-                "movd      %1,    %%mm1 \n\t"
-                "punpcklbw %%mm7, %%mm0 \n\t"
-                "punpcklbw %%mm7, %%mm1 \n\t"
-                "pmullw    %%mm3, %%mm0 \n\t"
-                "pmullw    %%mm4, %%mm1 \n\t"
-                "paddsw    %%mm1, %%mm0 \n\t"
-                "paddsw    %%mm5, %%mm0 \n\t"
-                "psraw     %%mm6, %%mm0 \n\t"
-                "packuswb  %%mm0, %%mm0 \n\t"
-                "movd      %%mm0, %0    \n\t"
-                : "+m"(*(uint32_t*)(dst+x))
-                :  "m"(*(uint32_t*)(src+x))
-            );
+                c->h264_idct_add16 = ff_h264_idct_add16_sse2;
+                c->h264_idct_add8  = ff_h264_idct_add8_sse2;
+                c->h264_idct_add16intra = ff_h264_idct_add16intra_sse2;
+            }
+            if (mm_flags&AV_CPU_FLAG_SSSE3) {
+                c->biweight_h264_pixels_tab[0]= ff_h264_biweight_16x16_ssse3;
+                c->biweight_h264_pixels_tab[1]= ff_h264_biweight_16x8_ssse3;
+                c->biweight_h264_pixels_tab[2]= ff_h264_biweight_8x16_ssse3;
+                c->biweight_h264_pixels_tab[3]= ff_h264_biweight_8x8_ssse3;
+                c->biweight_h264_pixels_tab[4]= ff_h264_biweight_8x4_ssse3;
+            }
         }
-        src += stride;
-        dst += stride;
     }
+#endif
 }
-
-#define H264_WEIGHT(W,H) \
-static void ff_h264_biweight_ ## W ## x ## H ## _mmx2(uint8_t *dst, uint8_t *src, int stride, int log2_denom, int weightd, int weights, int offset){ \
-    ff_h264_biweight_WxH_mmx2(dst, src, stride, log2_denom, weightd, weights, offset, W, H); \
-} \
-static void ff_h264_weight_ ## W ## x ## H ## _mmx2(uint8_t *dst, int stride, int log2_denom, int weight, int offset){ \
-    ff_h264_weight_WxH_mmx2(dst, stride, log2_denom, weight, offset, W, H); \
-}
-
-H264_WEIGHT(16,16)
-H264_WEIGHT(16, 8)
-H264_WEIGHT( 8,16)
-H264_WEIGHT( 8, 8)
-H264_WEIGHT( 8, 4)
-H264_WEIGHT( 4, 8)
-H264_WEIGHT( 4, 4)
-H264_WEIGHT( 4, 2)
-
diff --git a/libavcodec/x86/idct_mmx.c b/libavcodec/x86/idct_mmx.c
index d6ab04e..57fa818 100644
--- a/libavcodec/x86/idct_mmx.c
+++ b/libavcodec/x86/idct_mmx.c
@@ -23,8 +23,8 @@
 #include "libavutil/common.h"
 #include "libavcodec/dsputil.h"
 
+#include "libavutil/x86_cpu.h"
 #include "dsputil_mmx.h"
-#include "mmx.h"
 
 #define ROW_SHIFT 11
 #define COL_SHIFT 6
@@ -87,104 +87,115 @@ static inline void idct_row (int16_t * row, int offset,
 static inline void mmxext_row_head (int16_t * const row, const int offset,
                                     const int16_t * const table)
 {
-    movq_m2r (*(row+offset), mm2);      /* mm2 = x6 x4 x2 x0 */
+    __asm__ volatile(
+        "movq     (%0), %%mm2        \n\t"  /* mm2 = x6 x4 x2 x0 */
 
-    movq_m2r (*(row+offset+4), mm5);    /* mm5 = x7 x5 x3 x1 */
-    movq_r2r (mm2, mm0);                /* mm0 = x6 x4 x2 x0 */
+        "movq    8(%0), %%mm5        \n\t"  /* mm5 = x7 x5 x3 x1 */
+        "movq    %%mm2, %%mm0        \n\t"  /* mm0 = x6 x4 x2 x0 */
 
-    movq_m2r (*table, mm3);             /* mm3 = -C2 -C4 C2 C4 */
-    movq_r2r (mm5, mm6);                /* mm6 = x7 x5 x3 x1 */
+        "movq     (%1), %%mm3        \n\t"  /* mm3 = -C2 -C4 C2 C4 */
+        "movq    %%mm5, %%mm6        \n\t"  /* mm6 = x7 x5 x3 x1 */
 
-    movq_m2r (*(table+4), mm4);         /* mm4 = C6 C4 C6 C4 */
-    pmaddwd_r2r (mm0, mm3);             /* mm3 = -C4*x4-C2*x6 C4*x0+C2*x2 */
+        "movq    8(%1), %%mm4        \n\t"  /* mm4 = C6 C4 C6 C4 */
+        "pmaddwd %%mm0, %%mm3        \n\t"  /* mm3 = -C4*x4-C2*x6 C4*x0+C2*x2 */
 
-    pshufw_r2r (mm2, mm2, 0x4e);        /* mm2 = x2 x0 x6 x4 */
+        "pshufw  $0x4e, %%mm2, %%mm2 \n\t"  /* mm2 = x2 x0 x6 x4 */
+        :: "r" ((row+offset)), "r" (table)
+    );
 }
 
 static inline void mmxext_row (const int16_t * const table,
                                const int32_t * const rounder)
 {
-    movq_m2r (*(table+8), mm1);         /* mm1 = -C5 -C1 C3 C1 */
-    pmaddwd_r2r (mm2, mm4);             /* mm4 = C4*x0+C6*x2 C4*x4+C6*x6 */
+    __asm__ volatile (
+        "movq    16(%0), %%mm1         \n\t" /* mm1 = -C5 -C1 C3 C1 */
+        "pmaddwd  %%mm2, %%mm4         \n\t" /* mm4 = C4*x0+C6*x2 C4*x4+C6*x6 */
 
-    pmaddwd_m2r (*(table+16), mm0);     /* mm0 = C4*x4-C6*x6 C4*x0-C6*x2 */
-    pshufw_r2r (mm6, mm6, 0x4e);        /* mm6 = x3 x1 x7 x5 */
+        "pmaddwd 32(%0), %%mm0         \n\t" /* mm0 = C4*x4-C6*x6 C4*x0-C6*x2 */
+        "pshufw   $0x4e, %%mm6, %%mm6  \n\t" /* mm6 = x3 x1 x7 x5 */
 
-    movq_m2r (*(table+12), mm7);        /* mm7 = -C7 C3 C7 C5 */
-    pmaddwd_r2r (mm5, mm1);             /* mm1 = -C1*x5-C5*x7 C1*x1+C3*x3 */
+        "movq    24(%0), %%mm7         \n\t" /* mm7 = -C7 C3 C7 C5 */
+        "pmaddwd  %%mm5, %%mm1         \n\t" /* mm1= -C1*x5-C5*x7 C1*x1+C3*x3 */
 
-    paddd_m2r (*rounder, mm3);          /* mm3 += rounder */
-    pmaddwd_r2r (mm6, mm7);             /* mm7 = C3*x1-C7*x3 C5*x5+C7*x7 */
+        "paddd     (%1), %%mm3         \n\t" /* mm3 += rounder */
+        "pmaddwd  %%mm6, %%mm7         \n\t" /* mm7 = C3*x1-C7*x3 C5*x5+C7*x7 */
 
-    pmaddwd_m2r (*(table+20), mm2);     /* mm2 = C4*x0-C2*x2 -C4*x4+C2*x6 */
-    paddd_r2r (mm4, mm3);               /* mm3 = a1 a0 + rounder */
+        "pmaddwd 40(%0), %%mm2         \n\t" /* mm2= C4*x0-C2*x2 -C4*x4+C2*x6 */
+        "paddd    %%mm4, %%mm3         \n\t" /* mm3 = a1 a0 + rounder */
 
-    pmaddwd_m2r (*(table+24), mm5);     /* mm5 = C3*x5-C1*x7 C5*x1-C1*x3 */
-    movq_r2r (mm3, mm4);                /* mm4 = a1 a0 + rounder */
+        "pmaddwd 48(%0), %%mm5         \n\t" /* mm5 = C3*x5-C1*x7 C5*x1-C1*x3 */
+        "movq     %%mm3, %%mm4         \n\t" /* mm4 = a1 a0 + rounder */
 
-    pmaddwd_m2r (*(table+28), mm6);     /* mm6 = C7*x1-C5*x3 C7*x5+C3*x7 */
-    paddd_r2r (mm7, mm1);               /* mm1 = b1 b0 */
+        "pmaddwd 56(%0), %%mm6         \n\t" /* mm6 = C7*x1-C5*x3 C7*x5+C3*x7 */
+        "paddd    %%mm7, %%mm1         \n\t" /* mm1 = b1 b0 */
 
-    paddd_m2r (*rounder, mm0);          /* mm0 += rounder */
-    psubd_r2r (mm1, mm3);               /* mm3 = a1-b1 a0-b0 + rounder */
+        "paddd     (%1), %%mm0         \n\t" /* mm0 += rounder */
+        "psubd    %%mm1, %%mm3         \n\t" /* mm3 = a1-b1 a0-b0 + rounder */
 
-    psrad_i2r (ROW_SHIFT, mm3);         /* mm3 = y6 y7 */
-    paddd_r2r (mm4, mm1);               /* mm1 = a1+b1 a0+b0 + rounder */
+        "psrad $" AV_STRINGIFY(ROW_SHIFT) ", %%mm3         \n\t" /* mm3 = y6 y7 */
+        "paddd    %%mm4, %%mm1         \n\t" /* mm1 = a1+b1 a0+b0 + rounder */
 
-    paddd_r2r (mm2, mm0);               /* mm0 = a3 a2 + rounder */
-    psrad_i2r (ROW_SHIFT, mm1);         /* mm1 = y1 y0 */
+        "paddd    %%mm2, %%mm0         \n\t" /* mm0 = a3 a2 + rounder */
+        "psrad $" AV_STRINGIFY(ROW_SHIFT) ", %%mm1         \n\t" /* mm1 = y1 y0 */
 
-    paddd_r2r (mm6, mm5);               /* mm5 = b3 b2 */
-    movq_r2r (mm0, mm4);                /* mm4 = a3 a2 + rounder */
+        "paddd    %%mm6, %%mm5         \n\t" /* mm5 = b3 b2 */
+        "movq     %%mm0, %%mm4         \n\t" /* mm4 = a3 a2 + rounder */
 
-    paddd_r2r (mm5, mm0);               /* mm0 = a3+b3 a2+b2 + rounder */
-    psubd_r2r (mm5, mm4);               /* mm4 = a3-b3 a2-b2 + rounder */
+        "paddd    %%mm5, %%mm0         \n\t" /* mm0 = a3+b3 a2+b2 + rounder */
+        "psubd    %%mm5, %%mm4         \n\t" /* mm4 = a3-b3 a2-b2 + rounder */
+        : : "r" (table), "r" (rounder));
 }
 
 static inline void mmxext_row_tail (int16_t * const row, const int store)
 {
-    psrad_i2r (ROW_SHIFT, mm0);         /* mm0 = y3 y2 */
+    __asm__ volatile (
+        "psrad $" AV_STRINGIFY(ROW_SHIFT) ", %%mm0        \n\t"  /* mm0 = y3 y2 */
 
-    psrad_i2r (ROW_SHIFT, mm4);         /* mm4 = y4 y5 */
+        "psrad $" AV_STRINGIFY(ROW_SHIFT) ", %%mm4  \n\t"  /* mm4 = y4 y5 */
 
-    packssdw_r2r (mm0, mm1);            /* mm1 = y3 y2 y1 y0 */
+        "packssdw %%mm0, %%mm1        \n\t"  /* mm1 = y3 y2 y1 y0 */
 
-    packssdw_r2r (mm3, mm4);            /* mm4 = y6 y7 y4 y5 */
+        "packssdw %%mm3, %%mm4        \n\t"  /* mm4 = y6 y7 y4 y5 */
 
-    movq_r2m (mm1, *(row+store));       /* save y3 y2 y1 y0 */
-    pshufw_r2r (mm4, mm4, 0xb1);        /* mm4 = y7 y6 y5 y4 */
+        "movq     %%mm1, (%0)         \n\t"  /* save y3 y2 y1 y0 */
+        "pshufw   $0xb1, %%mm4, %%mm4 \n\t"  /* mm4 = y7 y6 y5 y4 */
 
-    /* slot */
+        /* slot */
 
-    movq_r2m (mm4, *(row+store+4));     /* save y7 y6 y5 y4 */
+        "movq     %%mm4, 8(%0)        \n\t"  /* save y7 y6 y5 y4 */
+        :: "r" (row+store)
+        );
 }
 
 static inline void mmxext_row_mid (int16_t * const row, const int store,
                                    const int offset,
                                    const int16_t * const table)
 {
-    movq_m2r (*(row+offset), mm2);      /* mm2 = x6 x4 x2 x0 */
-    psrad_i2r (ROW_SHIFT, mm0);         /* mm0 = y3 y2 */
+    __asm__ volatile (
+        "movq     (%0,%1), %%mm2       \n\t" /* mm2 = x6 x4 x2 x0 */
+        "psrad $" AV_STRINGIFY(ROW_SHIFT) ", %%mm0 \n\t"   /* mm0 = y3 y2 */
 
-    movq_m2r (*(row+offset+4), mm5);    /* mm5 = x7 x5 x3 x1 */
-    psrad_i2r (ROW_SHIFT, mm4);         /* mm4 = y4 y5 */
+        "movq    8(%0,%1), %%mm5       \n\t" /* mm5 = x7 x5 x3 x1 */
+        "psrad $" AV_STRINGIFY(ROW_SHIFT) ", %%mm4 \n\t" /* mm4 = y4 y5 */
 
-    packssdw_r2r (mm0, mm1);            /* mm1 = y3 y2 y1 y0 */
-    movq_r2r (mm5, mm6);                /* mm6 = x7 x5 x3 x1 */
+        "packssdw   %%mm0, %%mm1       \n\t" /* mm1 = y3 y2 y1 y0 */
+        "movq       %%mm5, %%mm6       \n\t" /* mm6 = x7 x5 x3 x1 */
 
-    packssdw_r2r (mm3, mm4);            /* mm4 = y6 y7 y4 y5 */
-    movq_r2r (mm2, mm0);                /* mm0 = x6 x4 x2 x0 */
+        "packssdw   %%mm3, %%mm4       \n\t" /* mm4 = y6 y7 y4 y5 */
+        "movq       %%mm2, %%mm0       \n\t" /* mm0 = x6 x4 x2 x0 */
 
-    movq_r2m (mm1, *(row+store));       /* save y3 y2 y1 y0 */
-    pshufw_r2r (mm4, mm4, 0xb1);        /* mm4 = y7 y6 y5 y4 */
+        "movq       %%mm1, (%0,%2)     \n\t" /* save y3 y2 y1 y0 */
+        "pshufw     $0xb1, %%mm4, %%mm4\n\t" /* mm4 = y7 y6 y5 y4 */
 
-    movq_m2r (*table, mm3);             /* mm3 = -C2 -C4 C2 C4 */
-    movq_r2m (mm4, *(row+store+4));     /* save y7 y6 y5 y4 */
+        "movq        (%3), %%mm3       \n\t" /* mm3 = -C2 -C4 C2 C4 */
+        "movq       %%mm4, 8(%0,%2)    \n\t" /* save y7 y6 y5 y4 */
 
-    pmaddwd_r2r (mm0, mm3);             /* mm3 = -C4*x4-C2*x6 C4*x0+C2*x2 */
+        "pmaddwd    %%mm0, %%mm3       \n\t" /* mm3= -C4*x4-C2*x6 C4*x0+C2*x2 */
 
-    movq_m2r (*(table+4), mm4);         /* mm4 = C6 C4 C6 C4 */
-    pshufw_r2r (mm2, mm2, 0x4e);        /* mm2 = x2 x0 x6 x4 */
+        "movq       8(%3), %%mm4       \n\t" /* mm4 = C6 C4 C6 C4 */
+        "pshufw     $0x4e, %%mm2, %%mm2\n\t" /* mm2 = x2 x0 x6 x4 */
+        :: "r" (row), "r" ((x86_reg) (2*offset)), "r" ((x86_reg) (2*store)), "r" (table)
+        );
 }
 
 
@@ -202,119 +213,132 @@ static inline void mmxext_row_mid (int16_t * const row, const int store,
 static inline void mmx_row_head (int16_t * const row, const int offset,
                                  const int16_t * const table)
 {
-    movq_m2r (*(row+offset), mm2);      /* mm2 = x6 x4 x2 x0 */
+    __asm__ volatile (
+        "movq (%0), %%mm2       \n\t"    /* mm2 = x6 x4 x2 x0 */
 
-    movq_m2r (*(row+offset+4), mm5);    /* mm5 = x7 x5 x3 x1 */
-    movq_r2r (mm2, mm0);                /* mm0 = x6 x4 x2 x0 */
+        "movq 8(%0), %%mm5      \n\t"    /* mm5 = x7 x5 x3 x1 */
+        "movq %%mm2, %%mm0      \n\t"    /* mm0 = x6 x4 x2 x0 */
 
-    movq_m2r (*table, mm3);             /* mm3 = C6 C4 C2 C4 */
-    movq_r2r (mm5, mm6);                /* mm6 = x7 x5 x3 x1 */
+        "movq (%1), %%mm3       \n\t"    /* mm3 = C6 C4 C2 C4 */
+        "movq %%mm5, %%mm6      \n\t"    /* mm6 = x7 x5 x3 x1 */
 
-    punpckldq_r2r (mm0, mm0);           /* mm0 = x2 x0 x2 x0 */
+        "punpckldq %%mm0, %%mm0 \n\t"    /* mm0 = x2 x0 x2 x0 */
 
-    movq_m2r (*(table+4), mm4);         /* mm4 = -C2 -C4 C6 C4 */
-    pmaddwd_r2r (mm0, mm3);             /* mm3 = C4*x0+C6*x2 C4*x0+C2*x2 */
+        "movq 8(%1), %%mm4      \n\t"    /* mm4 = -C2 -C4 C6 C4 */
+        "pmaddwd %%mm0, %%mm3   \n\t"    /* mm3 = C4*x0+C6*x2 C4*x0+C2*x2 */
 
-    movq_m2r (*(table+8), mm1);         /* mm1 = -C7 C3 C3 C1 */
-    punpckhdq_r2r (mm2, mm2);           /* mm2 = x6 x4 x6 x4 */
+        "movq 16(%1), %%mm1     \n\t"    /* mm1 = -C7 C3 C3 C1 */
+        "punpckhdq %%mm2, %%mm2 \n\t"    /* mm2 = x6 x4 x6 x4 */
+        :: "r" ((row+offset)), "r" (table)
+        );
 }
 
 static inline void mmx_row (const int16_t * const table,
                             const int32_t * const rounder)
 {
-    pmaddwd_r2r (mm2, mm4);             /* mm4 = -C4*x4-C2*x6 C4*x4+C6*x6 */
-    punpckldq_r2r (mm5, mm5);           /* mm5 = x3 x1 x3 x1 */
+    __asm__ volatile (
+        "pmaddwd   %%mm2, %%mm4    \n\t"  /* mm4 = -C4*x4-C2*x6 C4*x4+C6*x6 */
+        "punpckldq %%mm5, %%mm5    \n\t"  /* mm5 = x3 x1 x3 x1 */
 
-    pmaddwd_m2r (*(table+16), mm0);     /* mm0 = C4*x0-C2*x2 C4*x0-C6*x2 */
-    punpckhdq_r2r (mm6, mm6);           /* mm6 = x7 x5 x7 x5 */
+        "pmaddwd  32(%0), %%mm0    \n\t"  /* mm0 = C4*x0-C2*x2 C4*x0-C6*x2 */
+        "punpckhdq %%mm6, %%mm6    \n\t"  /* mm6 = x7 x5 x7 x5 */
 
-    movq_m2r (*(table+12), mm7);        /* mm7 = -C5 -C1 C7 C5 */
-    pmaddwd_r2r (mm5, mm1);             /* mm1 = C3*x1-C7*x3 C1*x1+C3*x3 */
+        "movq     24(%0), %%mm7    \n\t"  /* mm7 = -C5 -C1 C7 C5 */
+        "pmaddwd   %%mm5, %%mm1    \n\t"  /* mm1 = C3*x1-C7*x3 C1*x1+C3*x3 */
 
-    paddd_m2r (*rounder, mm3);          /* mm3 += rounder */
-    pmaddwd_r2r (mm6, mm7);             /* mm7 = -C1*x5-C5*x7 C5*x5+C7*x7 */
+        "paddd      (%1), %%mm3    \n\t"  /* mm3 += rounder */
+        "pmaddwd   %%mm6, %%mm7    \n\t"  /* mm7 = -C1*x5-C5*x7 C5*x5+C7*x7 */
 
-    pmaddwd_m2r (*(table+20), mm2);     /* mm2 = C4*x4-C6*x6 -C4*x4+C2*x6 */
-    paddd_r2r (mm4, mm3);               /* mm3 = a1 a0 + rounder */
+        "pmaddwd  40(%0), %%mm2    \n\t"  /* mm2 = C4*x4-C6*x6 -C4*x4+C2*x6 */
+        "paddd     %%mm4, %%mm3    \n\t"  /* mm3 = a1 a0 + rounder */
 
-    pmaddwd_m2r (*(table+24), mm5);     /* mm5 = C7*x1-C5*x3 C5*x1-C1*x3 */
-    movq_r2r (mm3, mm4);                /* mm4 = a1 a0 + rounder */
+        "pmaddwd  48(%0), %%mm5    \n\t"  /* mm5 = C7*x1-C5*x3 C5*x1-C1*x3 */
+        "movq      %%mm3, %%mm4    \n\t"  /* mm4 = a1 a0 + rounder */
 
-    pmaddwd_m2r (*(table+28), mm6);     /* mm6 = C3*x5-C1*x7 C7*x5+C3*x7 */
-    paddd_r2r (mm7, mm1);               /* mm1 = b1 b0 */
+        "pmaddwd  56(%0), %%mm6    \n\t"  /* mm6 = C3*x5-C1*x7 C7*x5+C3*x7 */
+        "paddd     %%mm7, %%mm1    \n\t"  /* mm1 = b1 b0 */
 
-    paddd_m2r (*rounder, mm0);          /* mm0 += rounder */
-    psubd_r2r (mm1, mm3);               /* mm3 = a1-b1 a0-b0 + rounder */
+        "paddd      (%1), %%mm0    \n\t"  /* mm0 += rounder */
+        "psubd     %%mm1, %%mm3    \n\t"  /* mm3 = a1-b1 a0-b0 + rounder */
 
-    psrad_i2r (ROW_SHIFT, mm3);         /* mm3 = y6 y7 */
-    paddd_r2r (mm4, mm1);               /* mm1 = a1+b1 a0+b0 + rounder */
+        "psrad $" AV_STRINGIFY(ROW_SHIFT) ", %%mm3    \n\t"  /* mm3 = y6 y7 */
+        "paddd     %%mm4, %%mm1    \n\t"  /* mm1 = a1+b1 a0+b0 + rounder */
 
-    paddd_r2r (mm2, mm0);               /* mm0 = a3 a2 + rounder */
-    psrad_i2r (ROW_SHIFT, mm1);         /* mm1 = y1 y0 */
+        "paddd     %%mm2, %%mm0    \n\t"  /* mm0 = a3 a2 + rounder */
+        "psrad $" AV_STRINGIFY(ROW_SHIFT) ", %%mm1    \n\t"  /* mm1 = y1 y0 */
 
-    paddd_r2r (mm6, mm5);               /* mm5 = b3 b2 */
-    movq_r2r (mm0, mm7);                /* mm7 = a3 a2 + rounder */
+        "paddd     %%mm6, %%mm5    \n\t"  /* mm5 = b3 b2 */
+        "movq      %%mm0, %%mm7    \n\t"  /* mm7 = a3 a2 + rounder */
 
-    paddd_r2r (mm5, mm0);               /* mm0 = a3+b3 a2+b2 + rounder */
-    psubd_r2r (mm5, mm7);               /* mm7 = a3-b3 a2-b2 + rounder */
+        "paddd     %%mm5, %%mm0    \n\t"  /* mm0 = a3+b3 a2+b2 + rounder */
+        "psubd     %%mm5, %%mm7    \n\t"  /* mm7 = a3-b3 a2-b2 + rounder */
+        :: "r" (table), "r" (rounder)
+        );
 }
 
 static inline void mmx_row_tail (int16_t * const row, const int store)
 {
-    psrad_i2r (ROW_SHIFT, mm0);         /* mm0 = y3 y2 */
+    __asm__ volatile (
+        "psrad $" AV_STRINGIFY(ROW_SHIFT) ", %%mm0      \n\t" /* mm0 = y3 y2 */
 
-    psrad_i2r (ROW_SHIFT, mm7);         /* mm7 = y4 y5 */
+        "psrad $" AV_STRINGIFY(ROW_SHIFT) ", %%mm7      \n\t" /* mm7 = y4 y5 */
 
-    packssdw_r2r (mm0, mm1);            /* mm1 = y3 y2 y1 y0 */
+        "packssdw %%mm0, %%mm1 \n\t" /* mm1 = y3 y2 y1 y0 */
 
-    packssdw_r2r (mm3, mm7);            /* mm7 = y6 y7 y4 y5 */
+        "packssdw %%mm3, %%mm7 \n\t" /* mm7 = y6 y7 y4 y5 */
 
-    movq_r2m (mm1, *(row+store));       /* save y3 y2 y1 y0 */
-    movq_r2r (mm7, mm4);                /* mm4 = y6 y7 y4 y5 */
+        "movq %%mm1, (%0)      \n\t" /* save y3 y2 y1 y0 */
+        "movq %%mm7, %%mm4     \n\t" /* mm4 = y6 y7 y4 y5 */
 
-    pslld_i2r (16, mm7);                /* mm7 = y7 0 y5 0 */
+        "pslld $16, %%mm7      \n\t" /* mm7 = y7 0 y5 0 */
 
-    psrld_i2r (16, mm4);                /* mm4 = 0 y6 0 y4 */
+        "psrld $16, %%mm4      \n\t" /* mm4 = 0 y6 0 y4 */
 
-    por_r2r (mm4, mm7);                 /* mm7 = y7 y6 y5 y4 */
+        "por %%mm4, %%mm7      \n\t" /* mm7 = y7 y6 y5 y4 */
 
-    /* slot */
+        /* slot */
 
-    movq_r2m (mm7, *(row+store+4));     /* save y7 y6 y5 y4 */
+        "movq %%mm7, 8(%0)     \n\t" /* save y7 y6 y5 y4 */
+        :: "r" (row+store)
+        );
 }
 
 static inline void mmx_row_mid (int16_t * const row, const int store,
                                 const int offset, const int16_t * const table)
 {
-    movq_m2r (*(row+offset), mm2);      /* mm2 = x6 x4 x2 x0 */
-    psrad_i2r (ROW_SHIFT, mm0);         /* mm0 = y3 y2 */
 
-    movq_m2r (*(row+offset+4), mm5);    /* mm5 = x7 x5 x3 x1 */
-    psrad_i2r (ROW_SHIFT, mm7);         /* mm7 = y4 y5 */
+    __asm__ volatile (
+        "movq    (%0,%1), %%mm2    \n\t" /* mm2 = x6 x4 x2 x0 */
+        "psrad $" AV_STRINGIFY(ROW_SHIFT) ", %%mm0 \n\t" /* mm0 = y3 y2 */
 
-    packssdw_r2r (mm0, mm1);            /* mm1 = y3 y2 y1 y0 */
-    movq_r2r (mm5, mm6);                /* mm6 = x7 x5 x3 x1 */
+        "movq   8(%0,%1), %%mm5    \n\t" /* mm5 = x7 x5 x3 x1 */
+        "psrad $" AV_STRINGIFY(ROW_SHIFT) ", %%mm7 \n\t" /* mm7 = y4 y5 */
 
-    packssdw_r2r (mm3, mm7);            /* mm7 = y6 y7 y4 y5 */
-    movq_r2r (mm2, mm0);                /* mm0 = x6 x4 x2 x0 */
+        "packssdw  %%mm0, %%mm1    \n\t" /* mm1 = y3 y2 y1 y0 */
+        "movq      %%mm5, %%mm6    \n\t" /* mm6 = x7 x5 x3 x1 */
 
-    movq_r2m (mm1, *(row+store));       /* save y3 y2 y1 y0 */
-    movq_r2r (mm7, mm1);                /* mm1 = y6 y7 y4 y5 */
+        "packssdw  %%mm3, %%mm7    \n\t" /* mm7 = y6 y7 y4 y5 */
+        "movq      %%mm2, %%mm0    \n\t" /* mm0 = x6 x4 x2 x0 */
 
-    punpckldq_r2r (mm0, mm0);           /* mm0 = x2 x0 x2 x0 */
-    psrld_i2r (16, mm7);                /* mm7 = 0 y6 0 y4 */
+        "movq      %%mm1, (%0,%2)  \n\t" /* save y3 y2 y1 y0 */
+        "movq      %%mm7, %%mm1    \n\t" /* mm1 = y6 y7 y4 y5 */
 
-    movq_m2r (*table, mm3);             /* mm3 = C6 C4 C2 C4 */
-    pslld_i2r (16, mm1);                /* mm1 = y7 0 y5 0 */
+        "punpckldq %%mm0, %%mm0    \n\t" /* mm0 = x2 x0 x2 x0 */
+        "psrld       $16, %%mm7    \n\t" /* mm7 = 0 y6 0 y4 */
 
-    movq_m2r (*(table+4), mm4);         /* mm4 = -C2 -C4 C6 C4 */
-    por_r2r (mm1, mm7);                 /* mm7 = y7 y6 y5 y4 */
+        "movq       (%3), %%mm3    \n\t" /* mm3 = C6 C4 C2 C4 */
+        "pslld       $16, %%mm1    \n\t" /* mm1 = y7 0 y5 0 */
 
-    movq_m2r (*(table+8), mm1);         /* mm1 = -C7 C3 C3 C1 */
-    punpckhdq_r2r (mm2, mm2);           /* mm2 = x6 x4 x6 x4 */
+        "movq      8(%3), %%mm4    \n\t" /* mm4 = -C2 -C4 C6 C4 */
+        "por       %%mm1, %%mm7    \n\t" /* mm7 = y7 y6 y5 y4 */
 
-    movq_r2m (mm7, *(row+store+4));     /* save y7 y6 y5 y4 */
-    pmaddwd_r2r (mm0, mm3);             /* mm3 = C4*x0+C6*x2 C4*x0+C2*x2 */
+        "movq     16(%3), %%mm1    \n\t" /* mm1 = -C7 C3 C3 C1 */
+        "punpckhdq %%mm2, %%mm2    \n\t" /* mm2 = x6 x4 x6 x4 */
+
+        "movq      %%mm7, 8(%0,%2) \n\t" /* save y7 y6 y5 y4 */
+        "pmaddwd   %%mm0, %%mm3    \n\t" /* mm3 = C4*x0+C6*x2 C4*x0+C2*x2 */
+        : : "r" (row), "r" ((x86_reg) (2*offset)), "r" ((x86_reg) (2*store)), "r" (table)
+        );
 }
 
 
@@ -398,140 +422,145 @@ static inline void idct_col (int16_t * const col, const int offset)
 #define T3 43790
 #define C4 23170
 
-    DECLARE_ALIGNED(8, static const short, t1_vector)[] = {T1,T1,T1,T1};
-    DECLARE_ALIGNED(8, static const short, t2_vector)[] = {T2,T2,T2,T2};
-    DECLARE_ALIGNED(8, static const short, t3_vector)[] = {T3,T3,T3,T3};
-    DECLARE_ALIGNED(8, static const short, c4_vector)[] = {C4,C4,C4,C4};
+    DECLARE_ALIGNED(8, static const short, t1_vector)[] = {
+        T1,T1,T1,T1,
+        T2,T2,T2,T2,
+        T3,T3,T3,T3,
+        C4,C4,C4,C4
+    };
 
     /* column code adapted from Peter Gubanov */
     /* http://www.elecard.com/peter/idct.shtml */
 
-    movq_m2r (*t1_vector, mm0);         /* mm0 = T1 */
+    __asm__ volatile (
+        "movq      (%0), %%mm0    \n\t" /* mm0 = T1 */
 
-    movq_m2r (*(col+offset+1*8), mm1);  /* mm1 = x1 */
-    movq_r2r (mm0, mm2);                /* mm2 = T1 */
+        "movq   2*8(%1), %%mm1    \n\t" /* mm1 = x1 */
+        "movq     %%mm0, %%mm2    \n\t" /* mm2 = T1 */
 
-    movq_m2r (*(col+offset+7*8), mm4);  /* mm4 = x7 */
-    pmulhw_r2r (mm1, mm0);              /* mm0 = T1*x1 */
+        "movq 7*2*8(%1), %%mm4    \n\t" /* mm4 = x7 */
+        "pmulhw   %%mm1, %%mm0    \n\t" /* mm0 = T1*x1 */
 
-    movq_m2r (*t3_vector, mm5);         /* mm5 = T3 */
-    pmulhw_r2r (mm4, mm2);              /* mm2 = T1*x7 */
+        "movq    16(%0), %%mm5    \n\t" /* mm5 = T3 */
+        "pmulhw   %%mm4, %%mm2    \n\t" /* mm2 = T1*x7 */
 
-    movq_m2r (*(col+offset+5*8), mm6);  /* mm6 = x5 */
-    movq_r2r (mm5, mm7);                /* mm7 = T3-1 */
+        "movq 2*5*8(%1), %%mm6    \n\t" /* mm6 = x5 */
+        "movq     %%mm5, %%mm7    \n\t" /* mm7 = T3-1 */
 
-    movq_m2r (*(col+offset+3*8), mm3);  /* mm3 = x3 */
-    psubsw_r2r (mm4, mm0);              /* mm0 = v17 */
+        "movq 3*8*2(%1), %%mm3    \n\t" /* mm3 = x3 */
+        "psubsw   %%mm4, %%mm0    \n\t" /* mm0 = v17 */
 
-    movq_m2r (*t2_vector, mm4);         /* mm4 = T2 */
-    pmulhw_r2r (mm3, mm5);              /* mm5 = (T3-1)*x3 */
+        "movq     8(%0), %%mm4    \n\t" /* mm4 = T2 */
+        "pmulhw   %%mm3, %%mm5    \n\t" /* mm5 = (T3-1)*x3 */
 
-    paddsw_r2r (mm2, mm1);              /* mm1 = u17 */
-    pmulhw_r2r (mm6, mm7);              /* mm7 = (T3-1)*x5 */
+        "paddsw   %%mm2, %%mm1    \n\t" /* mm1 = u17 */
+        "pmulhw   %%mm6, %%mm7    \n\t" /* mm7 = (T3-1)*x5 */
 
-    /* slot */
+        /* slot */
 
-    movq_r2r (mm4, mm2);                /* mm2 = T2 */
-    paddsw_r2r (mm3, mm5);              /* mm5 = T3*x3 */
+        "movq     %%mm4, %%mm2    \n\t" /* mm2 = T2 */
+        "paddsw   %%mm3, %%mm5    \n\t" /* mm5 = T3*x3 */
 
-    pmulhw_m2r (*(col+offset+2*8), mm4);/* mm4 = T2*x2 */
-    paddsw_r2r (mm6, mm7);              /* mm7 = T3*x5 */
+        "pmulhw 2*8*2(%1), %%mm4  \n\t" /* mm4 = T2*x2 */
+        "paddsw   %%mm6, %%mm7    \n\t" /* mm7 = T3*x5 */
 
-    psubsw_r2r (mm6, mm5);              /* mm5 = v35 */
-    paddsw_r2r (mm3, mm7);              /* mm7 = u35 */
+        "psubsw   %%mm6, %%mm5    \n\t" /* mm5 = v35 */
+        "paddsw   %%mm3, %%mm7    \n\t" /* mm7 = u35 */
 
-    movq_m2r (*(col+offset+6*8), mm3);  /* mm3 = x6 */
-    movq_r2r (mm0, mm6);                /* mm6 = v17 */
+        "movq 6*8*2(%1), %%mm3    \n\t" /* mm3 = x6 */
+        "movq     %%mm0, %%mm6    \n\t" /* mm6 = v17 */
 
-    pmulhw_r2r (mm3, mm2);              /* mm2 = T2*x6 */
-    psubsw_r2r (mm5, mm0);              /* mm0 = b3 */
+        "pmulhw   %%mm3, %%mm2    \n\t" /* mm2 = T2*x6 */
+        "psubsw   %%mm5, %%mm0    \n\t" /* mm0 = b3 */
 
-    psubsw_r2r (mm3, mm4);              /* mm4 = v26 */
-    paddsw_r2r (mm6, mm5);              /* mm5 = v12 */
+        "psubsw   %%mm3, %%mm4    \n\t" /* mm4 = v26 */
+        "paddsw   %%mm6, %%mm5    \n\t" /* mm5 = v12 */
 
-    movq_r2m (mm0, *(col+offset+3*8));  /* save b3 in scratch0 */
-    movq_r2r (mm1, mm6);                /* mm6 = u17 */
+        "movq     %%mm0, 3*8*2(%1)\n\t" /* save b3 in scratch0 */
+        "movq     %%mm1, %%mm6    \n\t" /* mm6 = u17 */
 
-    paddsw_m2r (*(col+offset+2*8), mm2);/* mm2 = u26 */
-    paddsw_r2r (mm7, mm6);              /* mm6 = b0 */
+        "paddsw 2*8*2(%1), %%mm2  \n\t" /* mm2 = u26 */
+        "paddsw   %%mm7, %%mm6    \n\t" /* mm6 = b0 */
 
-    psubsw_r2r (mm7, mm1);              /* mm1 = u12 */
-    movq_r2r (mm1, mm7);                /* mm7 = u12 */
+        "psubsw   %%mm7, %%mm1    \n\t" /* mm1 = u12 */
+        "movq     %%mm1, %%mm7    \n\t" /* mm7 = u12 */
 
-    movq_m2r (*(col+offset+0*8), mm3);  /* mm3 = x0 */
-    paddsw_r2r (mm5, mm1);              /* mm1 = u12+v12 */
+        "movq   0*8(%1), %%mm3    \n\t" /* mm3 = x0 */
+        "paddsw   %%mm5, %%mm1    \n\t" /* mm1 = u12+v12 */
 
-    movq_m2r (*c4_vector, mm0);         /* mm0 = C4/2 */
-    psubsw_r2r (mm5, mm7);              /* mm7 = u12-v12 */
+        "movq    24(%0), %%mm0    \n\t" /* mm0 = C4/2 */
+        "psubsw   %%mm5, %%mm7    \n\t" /* mm7 = u12-v12 */
 
-    movq_r2m (mm6, *(col+offset+5*8));  /* save b0 in scratch1 */
-    pmulhw_r2r (mm0, mm1);              /* mm1 = b1/2 */
+        "movq     %%mm6, 5*8*2(%1)\n\t" /* save b0 in scratch1 */
+        "pmulhw   %%mm0, %%mm1    \n\t" /* mm1 = b1/2 */
 
-    movq_r2r (mm4, mm6);                /* mm6 = v26 */
-    pmulhw_r2r (mm0, mm7);              /* mm7 = b2/2 */
+        "movq     %%mm4, %%mm6    \n\t" /* mm6 = v26 */
+        "pmulhw   %%mm0, %%mm7    \n\t" /* mm7 = b2/2 */
 
-    movq_m2r (*(col+offset+4*8), mm5);  /* mm5 = x4 */
-    movq_r2r (mm3, mm0);                /* mm0 = x0 */
+        "movq 4*8*2(%1), %%mm5    \n\t" /* mm5 = x4 */
+        "movq     %%mm3, %%mm0    \n\t" /* mm0 = x0 */
 
-    psubsw_r2r (mm5, mm3);              /* mm3 = v04 */
-    paddsw_r2r (mm5, mm0);              /* mm0 = u04 */
+        "psubsw   %%mm5, %%mm3    \n\t" /* mm3 = v04 */
+        "paddsw   %%mm5, %%mm0    \n\t" /* mm0 = u04 */
 
-    paddsw_r2r (mm3, mm4);              /* mm4 = a1 */
-    movq_r2r (mm0, mm5);                /* mm5 = u04 */
+        "paddsw   %%mm3, %%mm4    \n\t" /* mm4 = a1 */
+        "movq     %%mm0, %%mm5    \n\t" /* mm5 = u04 */
 
-    psubsw_r2r (mm6, mm3);              /* mm3 = a2 */
-    paddsw_r2r (mm2, mm5);              /* mm5 = a0 */
+        "psubsw   %%mm6, %%mm3    \n\t" /* mm3 = a2 */
+        "paddsw   %%mm2, %%mm5    \n\t" /* mm5 = a0 */
 
-    paddsw_r2r (mm1, mm1);              /* mm1 = b1 */
-    psubsw_r2r (mm2, mm0);              /* mm0 = a3 */
+        "paddsw   %%mm1, %%mm1    \n\t" /* mm1 = b1 */
+        "psubsw   %%mm2, %%mm0    \n\t" /* mm0 = a3 */
 
-    paddsw_r2r (mm7, mm7);              /* mm7 = b2 */
-    movq_r2r (mm3, mm2);                /* mm2 = a2 */
+        "paddsw   %%mm7, %%mm7    \n\t" /* mm7 = b2 */
+        "movq     %%mm3, %%mm2    \n\t" /* mm2 = a2 */
 
-    movq_r2r (mm4, mm6);                /* mm6 = a1 */
-    paddsw_r2r (mm7, mm3);              /* mm3 = a2+b2 */
+        "movq     %%mm4, %%mm6    \n\t" /* mm6 = a1 */
+        "paddsw   %%mm7, %%mm3    \n\t" /* mm3 = a2+b2 */
 
-    psraw_i2r (COL_SHIFT, mm3);         /* mm3 = y2 */
-    paddsw_r2r (mm1, mm4);              /* mm4 = a1+b1 */
+        "psraw $" AV_STRINGIFY(COL_SHIFT) ", %%mm3\n\t" /* mm3 = y2 */
+        "paddsw   %%mm1, %%mm4\n\t" /* mm4 = a1+b1 */
 
-    psraw_i2r (COL_SHIFT, mm4);         /* mm4 = y1 */
-    psubsw_r2r (mm1, mm6);              /* mm6 = a1-b1 */
+        "psraw $" AV_STRINGIFY(COL_SHIFT) ", %%mm4\n\t" /* mm4 = y1 */
+        "psubsw   %%mm1, %%mm6    \n\t" /* mm6 = a1-b1 */
 
-    movq_m2r (*(col+offset+5*8), mm1);  /* mm1 = b0 */
-    psubsw_r2r (mm7, mm2);              /* mm2 = a2-b2 */
+        "movq 5*8*2(%1), %%mm1    \n\t" /* mm1 = b0 */
+        "psubsw   %%mm7, %%mm2    \n\t" /* mm2 = a2-b2 */
 
-    psraw_i2r (COL_SHIFT, mm6);         /* mm6 = y6 */
-    movq_r2r (mm5, mm7);                /* mm7 = a0 */
+        "psraw $" AV_STRINGIFY(COL_SHIFT) ", %%mm6\n\t" /* mm6 = y6 */
+        "movq     %%mm5, %%mm7    \n\t" /* mm7 = a0 */
 
-    movq_r2m (mm4, *(col+offset+1*8));  /* save y1 */
-    psraw_i2r (COL_SHIFT, mm2);         /* mm2 = y5 */
+        "movq     %%mm4, 1*8*2(%1)\n\t" /* save y1 */
+        "psraw $" AV_STRINGIFY(COL_SHIFT) ", %%mm2\n\t" /* mm2 = y5 */
 
-    movq_r2m (mm3, *(col+offset+2*8));  /* save y2 */
-    paddsw_r2r (mm1, mm5);              /* mm5 = a0+b0 */
+        "movq     %%mm3, 2*8*2(%1)\n\t" /* save y2 */
+        "paddsw   %%mm1, %%mm5    \n\t" /* mm5 = a0+b0 */
 
-    movq_m2r (*(col+offset+3*8), mm4);  /* mm4 = b3 */
-    psubsw_r2r (mm1, mm7);              /* mm7 = a0-b0 */
+        "movq 3*8*2(%1), %%mm4    \n\t" /* mm4 = b3 */
+        "psubsw   %%mm1, %%mm7    \n\t" /* mm7 = a0-b0 */
 
-    psraw_i2r (COL_SHIFT, mm5);         /* mm5 = y0 */
-    movq_r2r (mm0, mm3);                /* mm3 = a3 */
+        "psraw $" AV_STRINGIFY(COL_SHIFT) ", %%mm5\n\t" /* mm5 = y0 */
+        "movq     %%mm0, %%mm3    \n\t" /* mm3 = a3 */
 
-    movq_r2m (mm2, *(col+offset+5*8));  /* save y5 */
-    psubsw_r2r (mm4, mm3);              /* mm3 = a3-b3 */
+        "movq     %%mm2, 5*8*2(%1)\n\t" /* save y5 */
+        "psubsw   %%mm4, %%mm3    \n\t" /* mm3 = a3-b3 */
 
-    psraw_i2r (COL_SHIFT, mm7);         /* mm7 = y7 */
-    paddsw_r2r (mm0, mm4);              /* mm4 = a3+b3 */
+        "psraw $" AV_STRINGIFY(COL_SHIFT) ", %%mm7\n\t" /* mm7 = y7 */
+        "paddsw   %%mm0, %%mm4    \n\t" /* mm4 = a3+b3 */
 
-    movq_r2m (mm5, *(col+offset+0*8));  /* save y0 */
-    psraw_i2r (COL_SHIFT, mm3);         /* mm3 = y4 */
+        "movq     %%mm5, 0*8*2(%1)\n\t" /* save y0 */
+        "psraw $" AV_STRINGIFY(COL_SHIFT) ", %%mm3\n\t" /* mm3 = y4 */
 
-    movq_r2m (mm6, *(col+offset+6*8));  /* save y6 */
-    psraw_i2r (COL_SHIFT, mm4);         /* mm4 = y3 */
+        "movq     %%mm6, 6*8*2(%1)\n\t" /* save y6 */
+        "psraw $" AV_STRINGIFY(COL_SHIFT) ", %%mm4\n\t" /* mm4 = y3 */
 
-    movq_r2m (mm7, *(col+offset+7*8));  /* save y7 */
+        "movq     %%mm7, 7*8*2(%1)\n\t" /* save y7 */
 
-    movq_r2m (mm3, *(col+offset+4*8));  /* save y4 */
+        "movq     %%mm3, 4*8*2(%1)\n\t" /* save y4 */
 
-    movq_r2m (mm4, *(col+offset+3*8));  /* save y3 */
+        "movq     %%mm4, 3*8*2(%1)\n\t" /* save y3 */
+        :: "r" (t1_vector), "r" (col+offset)
+        );
 
 #undef T1
 #undef T2
diff --git a/libavcodec/x86/idct_mmx_xvid.c b/libavcodec/x86/idct_mmx_xvid.c
index 466cf75..3055205 100644
--- a/libavcodec/x86/idct_mmx_xvid.c
+++ b/libavcodec/x86/idct_mmx_xvid.c
@@ -22,20 +22,20 @@
  *
  * conversion to gcc syntax by Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public License
- * along with FFmpeg; if not, write to the Free Software Foundation,
+ * along with Libav; if not, write to the Free Software Foundation,
  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/x86/idct_sse2_xvid.c b/libavcodec/x86/idct_sse2_xvid.c
index fc670e2..4b6885f 100644
--- a/libavcodec/x86/idct_sse2_xvid.c
+++ b/libavcodec/x86/idct_sse2_xvid.c
@@ -9,7 +9,7 @@
  *
  * Originally from dct/x86_asm/fdct_sse2_skal.asm in Xvid.
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
  * Vertical pass is an implementation of the scheme:
  *  Loeffler C., Ligtenberg A., and Moschytz C.S.:
@@ -23,22 +23,23 @@
  *
  * More details at http://skal.planet-d.net/coding/dct.html
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public License
- * along with FFmpeg; if not, write to the Free Software Foundation,
+ * along with Libav; if not, write to the Free Software Foundation,
  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "libavcodec/dsputil.h"
+#include "libavutil/x86_cpu.h"
 #include "idct_xvid.h"
 #include "dsputil_mmx.h"
 
@@ -355,7 +356,7 @@ inline void ff_idct_xvid_sse2(short *block)
     TEST_TWO_ROWS("5*16(%0)", "6*16(%0)", "%%eax", "%%edx", CLEAR_ODD(ROW5), CLEAR_EVEN(ROW6))
     TEST_ONE_ROW("7*16(%0)", "%%esi", CLEAR_ODD(ROW7))
     iLLM_HEAD
-    ASMALIGN(4)
+    ".p2align 4 \n\t"
     JNZ("%%ecx", "2f")
     JNZ("%%eax", "3f")
     JNZ("%%edx", "4f")
@@ -379,17 +380,24 @@ inline void ff_idct_xvid_sse2(short *block)
     "6:                                                          \n\t"
     : "+r"(block)
     :
-    : "%eax", "%ecx", "%edx", "%esi", "memory");
+    : XMM_CLOBBERS("%xmm0" , "%xmm1" , "%xmm2" , "%xmm3" ,
+                   "%xmm4" , "%xmm5" , "%xmm6" , "%xmm7" ,)
+#if ARCH_X86_64
+      XMM_CLOBBERS("%xmm8" , "%xmm9" , "%xmm10", "%xmm11",
+                   "%xmm12", "%xmm13", "%xmm14",)
+#endif
+      "%eax", "%ecx", "%edx", "%esi", "memory"
+    );
 }
 
 void ff_idct_xvid_sse2_put(uint8_t *dest, int line_size, short *block)
 {
     ff_idct_xvid_sse2(block);
-    put_pixels_clamped_mmx(block, dest, line_size);
+    ff_put_pixels_clamped_mmx(block, dest, line_size);
 }
 
 void ff_idct_xvid_sse2_add(uint8_t *dest, int line_size, short *block)
 {
     ff_idct_xvid_sse2(block);
-    add_pixels_clamped_mmx(block, dest, line_size);
+    ff_add_pixels_clamped_mmx(block, dest, line_size);
 }
diff --git a/libavcodec/x86/idct_xvid.h b/libavcodec/x86/idct_xvid.h
index 5fdc20d..1ff039d 100644
--- a/libavcodec/x86/idct_xvid.h
+++ b/libavcodec/x86/idct_xvid.h
@@ -1,20 +1,20 @@
 /*
  * XVID MPEG-4 VIDEO CODEC
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/x86/lpc_mmx.c b/libavcodec/x86/lpc_mmx.c
index 2ef5fa6..d41c19b 100644
--- a/libavcodec/x86/lpc_mmx.c
+++ b/libavcodec/x86/lpc_mmx.c
@@ -2,43 +2,44 @@
  * MMX optimized LPC DSP utils
  * Copyright (c) 2007 Loren Merritt
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "libavutil/x86_cpu.h"
-#include "dsputil_mmx.h"
+#include "libavutil/cpu.h"
+#include "libavcodec/lpc.h"
 
-static void apply_welch_window_sse2(const int32_t *data, int len, double *w_data)
+static void lpc_apply_welch_window_sse2(const int32_t *data, int len,
+                                        double *w_data)
 {
     double c = 2.0 / (len-1.0);
     int n2 = len>>1;
     x86_reg i = -n2*sizeof(int32_t);
     x86_reg j =  n2*sizeof(int32_t);
     __asm__ volatile(
-        "movsd   %0,     %%xmm7                \n\t"
+        "movsd   %4,     %%xmm7                \n\t"
         "movapd  "MANGLE(ff_pd_1)", %%xmm6     \n\t"
         "movapd  "MANGLE(ff_pd_2)", %%xmm5     \n\t"
         "movlhps %%xmm7, %%xmm7                \n\t"
         "subpd   %%xmm5, %%xmm7                \n\t"
         "addsd   %%xmm6, %%xmm7                \n\t"
-        ::"m"(c)
-    );
+        "test    $1,     %5                    \n\t"
+        "jz      2f                            \n\t"
 #define WELCH(MOVPD, offset)\
-    __asm__ volatile(\
         "1:                                    \n\t"\
         "movapd   %%xmm7,  %%xmm1              \n\t"\
         "mulpd    %%xmm1,  %%xmm1              \n\t"\
@@ -55,31 +56,27 @@ static void apply_welch_window_sse2(const int32_t *data, int len, double *w_data
         "sub      $8,      %1                  \n\t"\
         "add      $8,      %0                  \n\t"\
         "jl 1b                                 \n\t"\
-        :"+&r"(i), "+&r"(j)\
-        :"r"(w_data+n2), "r"(data+n2)\
-    );
-    if(len&1)
+
         WELCH("movupd", -1)
-    else
+        "jmp 3f                                \n\t"
+        "2:                                    \n\t"
         WELCH("movapd", -2)
+        "3:                                    \n\t"
+        :"+&r"(i), "+&r"(j)
+        :"r"(w_data+n2), "r"(data+n2), "m"(c), "r"(len)
+         XMM_CLOBBERS_ONLY("%xmm0", "%xmm1", "%xmm2", "%xmm3",
+                                    "%xmm5", "%xmm6", "%xmm7")
+    );
 #undef WELCH
 }
 
-void ff_lpc_compute_autocorr_sse2(const int32_t *data, int len, int lag,
-                                   double *autoc)
+static void lpc_compute_autocorr_sse2(const double *data, int len, int lag,
+                                      double *autoc)
 {
-    double tmp[len + lag + 2];
-    double *data1 = tmp + lag;
     int j;
 
-    if((x86_reg)data1 & 15)
-        data1++;
-
-    apply_welch_window_sse2(data, len, data1);
-
-    for(j=0; j<lag; j++)
-        data1[j-lag]= 0.0;
-    data1[len] = 0.0;
+    if((x86_reg)data & 15)
+        data++;
 
     for(j=0; j<lag; j+=2){
         x86_reg i = -len*sizeof(double);
@@ -110,7 +107,7 @@ void ff_lpc_compute_autocorr_sse2(const int32_t *data, int len, int lag,
                 "movsd     %%xmm1,  8(%1)           \n\t"
                 "movsd     %%xmm2, 16(%1)           \n\t"
                 :"+&r"(i)
-                :"r"(autoc+j), "r"(data1+len), "r"(data1+len-j)
+                :"r"(autoc+j), "r"(data+len), "r"(data+len-j)
                 :"memory"
             );
         } else {
@@ -133,8 +130,18 @@ void ff_lpc_compute_autocorr_sse2(const int32_t *data, int len, int lag,
                 "movsd     %%xmm0, %1               \n\t"
                 "movsd     %%xmm1, %2               \n\t"
                 :"+&r"(i), "=m"(autoc[j]), "=m"(autoc[j+1])
-                :"r"(data1+len), "r"(data1+len-j)
+                :"r"(data+len), "r"(data+len-j)
             );
         }
     }
 }
+
+av_cold void ff_lpc_init_x86(LPCContext *c)
+{
+    int mm_flags = av_get_cpu_flags();
+
+    if (mm_flags & (AV_CPU_FLAG_SSE2|AV_CPU_FLAG_SSE2SLOW)) {
+        c->lpc_apply_welch_window = lpc_apply_welch_window_sse2;
+        c->lpc_compute_autocorr   = lpc_compute_autocorr_sse2;
+    }
+}
diff --git a/libavcodec/x86/mathops.h b/libavcodec/x86/mathops.h
index 5949dfe..50b0283 100644
--- a/libavcodec/x86/mathops.h
+++ b/libavcodec/x86/mathops.h
@@ -2,20 +2,20 @@
  * simple math operations
  * Copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at> et al
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -26,24 +26,45 @@
 #include "libavutil/common.h"
 
 #if ARCH_X86_32
-#define MULL(ra, rb, shift) \
-        ({ int rt, dummy; __asm__ (\
-            "imull %3               \n\t"\
-            "shrdl %4, %%edx, %%eax \n\t"\
-            : "=a"(rt), "=d"(dummy)\
-            : "a" ((int)(ra)), "rm" ((int)(rb)), "i"(shift));\
-         rt; })
 
-#define MULH(ra, rb) \
-    ({ int rt, dummy;\
-     __asm__ ("imull %3\n\t" : "=d"(rt), "=a"(dummy): "a" ((int)(ra)), "rm" ((int)(rb)));\
-     rt; })
+#define MULL MULL
+static av_always_inline av_const int MULL(int a, int b, unsigned shift)
+{
+    int rt, dummy;
+    __asm__ (
+        "imull %3               \n\t"
+        "shrdl %4, %%edx, %%eax \n\t"
+        :"=a"(rt), "=d"(dummy)
+        :"a"(a), "rm"(b), "ci"((uint8_t)shift)
+    );
+    return rt;
+}
 
-#define MUL64(ra, rb) \
-    ({ int64_t rt;\
-     __asm__ ("imull %2\n\t" : "=A"(rt) : "a" ((int)(ra)), "g" ((int)(rb)));\
-     rt; })
-#endif
+#define MULH MULH
+static av_always_inline av_const int MULH(int a, int b)
+{
+    int rt, dummy;
+    __asm__ (
+        "imull %3"
+        :"=d"(rt), "=a"(dummy)
+        :"a"(a), "rm"(b)
+    );
+    return rt;
+}
+
+#define MUL64 MUL64
+static av_always_inline av_const int64_t MUL64(int a, int b)
+{
+    int64_t rt;
+    __asm__ (
+        "imull %2"
+        :"=A"(rt)
+        :"a"(a), "rm"(b)
+    );
+    return rt;
+}
+
+#endif /* ARCH_X86_32 */
 
 #if HAVE_CMOV
 /* median of 3 */
diff --git a/libavcodec/x86/mlpdsp.c b/libavcodec/x86/mlpdsp.c
index 486a927..333dc56 100644
--- a/libavcodec/x86/mlpdsp.c
+++ b/libavcodec/x86/mlpdsp.c
@@ -2,20 +2,20 @@
  * MLP DSP functions x86-optimized
  * Copyright (c) 2009 Ramiro Polla
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/x86/mmx.h b/libavcodec/x86/mmx.h
deleted file mode 100644
index d7a76bb..0000000
--- a/libavcodec/x86/mmx.h
+++ /dev/null
@@ -1,267 +0,0 @@
-/*
- * mmx.h
- * Copyright (C) 1997-2001 H. Dietz and R. Fisher
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-#ifndef AVCODEC_X86_MMX_H
-#define AVCODEC_X86_MMX_H
-
-#warning Everything in this header is deprecated, use plain __asm__()! New code using this header will be rejected.
-
-
-#define         mmx_i2r(op,imm,reg) \
-        __asm__ volatile (#op " %0, %%" #reg \
-                              : /* nothing */ \
-                              : "i" (imm) )
-
-#define         mmx_m2r(op,mem,reg) \
-        __asm__ volatile (#op " %0, %%" #reg \
-                              : /* nothing */ \
-                              : "m" (mem))
-
-#define         mmx_r2m(op,reg,mem) \
-        __asm__ volatile (#op " %%" #reg ", %0" \
-                              : "=m" (mem) \
-                              : /* nothing */ )
-
-#define         mmx_r2r(op,regs,regd) \
-        __asm__ volatile (#op " %" #regs ", %" #regd)
-
-
-#define         emms() __asm__ volatile ("emms")
-
-#define         movd_m2r(var,reg)           mmx_m2r (movd, var, reg)
-#define         movd_r2m(reg,var)           mmx_r2m (movd, reg, var)
-#define         movd_r2r(regs,regd)         mmx_r2r (movd, regs, regd)
-
-#define         movq_m2r(var,reg)           mmx_m2r (movq, var, reg)
-#define         movq_r2m(reg,var)           mmx_r2m (movq, reg, var)
-#define         movq_r2r(regs,regd)         mmx_r2r (movq, regs, regd)
-
-#define         packssdw_m2r(var,reg)       mmx_m2r (packssdw, var, reg)
-#define         packssdw_r2r(regs,regd)     mmx_r2r (packssdw, regs, regd)
-#define         packsswb_m2r(var,reg)       mmx_m2r (packsswb, var, reg)
-#define         packsswb_r2r(regs,regd)     mmx_r2r (packsswb, regs, regd)
-
-#define         packuswb_m2r(var,reg)       mmx_m2r (packuswb, var, reg)
-#define         packuswb_r2r(regs,regd)     mmx_r2r (packuswb, regs, regd)
-
-#define         paddb_m2r(var,reg)          mmx_m2r (paddb, var, reg)
-#define         paddb_r2r(regs,regd)        mmx_r2r (paddb, regs, regd)
-#define         paddd_m2r(var,reg)          mmx_m2r (paddd, var, reg)
-#define         paddd_r2r(regs,regd)        mmx_r2r (paddd, regs, regd)
-#define         paddw_m2r(var,reg)          mmx_m2r (paddw, var, reg)
-#define         paddw_r2r(regs,regd)        mmx_r2r (paddw, regs, regd)
-
-#define         paddsb_m2r(var,reg)         mmx_m2r (paddsb, var, reg)
-#define         paddsb_r2r(regs,regd)       mmx_r2r (paddsb, regs, regd)
-#define         paddsw_m2r(var,reg)         mmx_m2r (paddsw, var, reg)
-#define         paddsw_r2r(regs,regd)       mmx_r2r (paddsw, regs, regd)
-
-#define         paddusb_m2r(var,reg)        mmx_m2r (paddusb, var, reg)
-#define         paddusb_r2r(regs,regd)      mmx_r2r (paddusb, regs, regd)
-#define         paddusw_m2r(var,reg)        mmx_m2r (paddusw, var, reg)
-#define         paddusw_r2r(regs,regd)      mmx_r2r (paddusw, regs, regd)
-
-#define         pand_m2r(var,reg)           mmx_m2r (pand, var, reg)
-#define         pand_r2r(regs,regd)         mmx_r2r (pand, regs, regd)
-
-#define         pandn_m2r(var,reg)          mmx_m2r (pandn, var, reg)
-#define         pandn_r2r(regs,regd)        mmx_r2r (pandn, regs, regd)
-
-#define         pcmpeqb_m2r(var,reg)        mmx_m2r (pcmpeqb, var, reg)
-#define         pcmpeqb_r2r(regs,regd)      mmx_r2r (pcmpeqb, regs, regd)
-#define         pcmpeqd_m2r(var,reg)        mmx_m2r (pcmpeqd, var, reg)
-#define         pcmpeqd_r2r(regs,regd)      mmx_r2r (pcmpeqd, regs, regd)
-#define         pcmpeqw_m2r(var,reg)        mmx_m2r (pcmpeqw, var, reg)
-#define         pcmpeqw_r2r(regs,regd)      mmx_r2r (pcmpeqw, regs, regd)
-
-#define         pcmpgtb_m2r(var,reg)        mmx_m2r (pcmpgtb, var, reg)
-#define         pcmpgtb_r2r(regs,regd)      mmx_r2r (pcmpgtb, regs, regd)
-#define         pcmpgtd_m2r(var,reg)        mmx_m2r (pcmpgtd, var, reg)
-#define         pcmpgtd_r2r(regs,regd)      mmx_r2r (pcmpgtd, regs, regd)
-#define         pcmpgtw_m2r(var,reg)        mmx_m2r (pcmpgtw, var, reg)
-#define         pcmpgtw_r2r(regs,regd)      mmx_r2r (pcmpgtw, regs, regd)
-
-#define         pmaddwd_m2r(var,reg)        mmx_m2r (pmaddwd, var, reg)
-#define         pmaddwd_r2r(regs,regd)      mmx_r2r (pmaddwd, regs, regd)
-
-#define         pmulhw_m2r(var,reg)         mmx_m2r (pmulhw, var, reg)
-#define         pmulhw_r2r(regs,regd)       mmx_r2r (pmulhw, regs, regd)
-
-#define         pmullw_m2r(var,reg)         mmx_m2r (pmullw, var, reg)
-#define         pmullw_r2r(regs,regd)       mmx_r2r (pmullw, regs, regd)
-
-#define         por_m2r(var,reg)            mmx_m2r (por, var, reg)
-#define         por_r2r(regs,regd)          mmx_r2r (por, regs, regd)
-
-#define         pslld_i2r(imm,reg)          mmx_i2r (pslld, imm, reg)
-#define         pslld_m2r(var,reg)          mmx_m2r (pslld, var, reg)
-#define         pslld_r2r(regs,regd)        mmx_r2r (pslld, regs, regd)
-#define         psllq_i2r(imm,reg)          mmx_i2r (psllq, imm, reg)
-#define         psllq_m2r(var,reg)          mmx_m2r (psllq, var, reg)
-#define         psllq_r2r(regs,regd)        mmx_r2r (psllq, regs, regd)
-#define         psllw_i2r(imm,reg)          mmx_i2r (psllw, imm, reg)
-#define         psllw_m2r(var,reg)          mmx_m2r (psllw, var, reg)
-#define         psllw_r2r(regs,regd)        mmx_r2r (psllw, regs, regd)
-
-#define         psrad_i2r(imm,reg)          mmx_i2r (psrad, imm, reg)
-#define         psrad_m2r(var,reg)          mmx_m2r (psrad, var, reg)
-#define         psrad_r2r(regs,regd)        mmx_r2r (psrad, regs, regd)
-#define         psraw_i2r(imm,reg)          mmx_i2r (psraw, imm, reg)
-#define         psraw_m2r(var,reg)          mmx_m2r (psraw, var, reg)
-#define         psraw_r2r(regs,regd)        mmx_r2r (psraw, regs, regd)
-
-#define         psrld_i2r(imm,reg)          mmx_i2r (psrld, imm, reg)
-#define         psrld_m2r(var,reg)          mmx_m2r (psrld, var, reg)
-#define         psrld_r2r(regs,regd)        mmx_r2r (psrld, regs, regd)
-#define         psrlq_i2r(imm,reg)          mmx_i2r (psrlq, imm, reg)
-#define         psrlq_m2r(var,reg)          mmx_m2r (psrlq, var, reg)
-#define         psrlq_r2r(regs,regd)        mmx_r2r (psrlq, regs, regd)
-#define         psrlw_i2r(imm,reg)          mmx_i2r (psrlw, imm, reg)
-#define         psrlw_m2r(var,reg)          mmx_m2r (psrlw, var, reg)
-#define         psrlw_r2r(regs,regd)        mmx_r2r (psrlw, regs, regd)
-
-#define         psubb_m2r(var,reg)          mmx_m2r (psubb, var, reg)
-#define         psubb_r2r(regs,regd)        mmx_r2r (psubb, regs, regd)
-#define         psubd_m2r(var,reg)          mmx_m2r (psubd, var, reg)
-#define         psubd_r2r(regs,regd)        mmx_r2r (psubd, regs, regd)
-#define         psubw_m2r(var,reg)          mmx_m2r (psubw, var, reg)
-#define         psubw_r2r(regs,regd)        mmx_r2r (psubw, regs, regd)
-
-#define         psubsb_m2r(var,reg)         mmx_m2r (psubsb, var, reg)
-#define         psubsb_r2r(regs,regd)       mmx_r2r (psubsb, regs, regd)
-#define         psubsw_m2r(var,reg)         mmx_m2r (psubsw, var, reg)
-#define         psubsw_r2r(regs,regd)       mmx_r2r (psubsw, regs, regd)
-
-#define         psubusb_m2r(var,reg)        mmx_m2r (psubusb, var, reg)
-#define         psubusb_r2r(regs,regd)      mmx_r2r (psubusb, regs, regd)
-#define         psubusw_m2r(var,reg)        mmx_m2r (psubusw, var, reg)
-#define         psubusw_r2r(regs,regd)      mmx_r2r (psubusw, regs, regd)
-
-#define         punpckhbw_m2r(var,reg)      mmx_m2r (punpckhbw, var, reg)
-#define         punpckhbw_r2r(regs,regd)    mmx_r2r (punpckhbw, regs, regd)
-#define         punpckhdq_m2r(var,reg)      mmx_m2r (punpckhdq, var, reg)
-#define         punpckhdq_r2r(regs,regd)    mmx_r2r (punpckhdq, regs, regd)
-#define         punpckhwd_m2r(var,reg)      mmx_m2r (punpckhwd, var, reg)
-#define         punpckhwd_r2r(regs,regd)    mmx_r2r (punpckhwd, regs, regd)
-
-#define         punpcklbw_m2r(var,reg)      mmx_m2r (punpcklbw, var, reg)
-#define         punpcklbw_r2r(regs,regd)    mmx_r2r (punpcklbw, regs, regd)
-#define         punpckldq_m2r(var,reg)      mmx_m2r (punpckldq, var, reg)
-#define         punpckldq_r2r(regs,regd)    mmx_r2r (punpckldq, regs, regd)
-#define         punpcklwd_m2r(var,reg)      mmx_m2r (punpcklwd, var, reg)
-#define         punpcklwd_r2r(regs,regd)    mmx_r2r (punpcklwd, regs, regd)
-
-#define         pxor_m2r(var,reg)           mmx_m2r (pxor, var, reg)
-#define         pxor_r2r(regs,regd)         mmx_r2r (pxor, regs, regd)
-
-
-/* 3DNOW extensions */
-
-#define         pavgusb_m2r(var,reg)        mmx_m2r (pavgusb, var, reg)
-#define         pavgusb_r2r(regs,regd)      mmx_r2r (pavgusb, regs, regd)
-
-
-/* AMD MMX extensions - also available in intel SSE */
-
-
-#define         mmx_m2ri(op,mem,reg,imm) \
-        __asm__ volatile (#op " %1, %0, %%" #reg \
-                              : /* nothing */ \
-                              : "m" (mem), "i" (imm))
-#define         mmx_r2ri(op,regs,regd,imm) \
-        __asm__ volatile (#op " %0, %%" #regs ", %%" #regd \
-                              : /* nothing */ \
-                              : "i" (imm) )
-
-#define         mmx_fetch(mem,hint) \
-        __asm__ volatile ("prefetch" #hint " %0" \
-                              : /* nothing */ \
-                              : "m" (mem))
-
-
-#define         maskmovq(regs,maskreg)      mmx_r2ri (maskmovq, regs, maskreg)
-
-#define         movntq_r2m(mmreg,var)       mmx_r2m (movntq, mmreg, var)
-
-#define         pavgb_m2r(var,reg)          mmx_m2r (pavgb, var, reg)
-#define         pavgb_r2r(regs,regd)        mmx_r2r (pavgb, regs, regd)
-#define         pavgw_m2r(var,reg)          mmx_m2r (pavgw, var, reg)
-#define         pavgw_r2r(regs,regd)        mmx_r2r (pavgw, regs, regd)
-
-#define         pextrw_r2r(mmreg,reg,imm)   mmx_r2ri (pextrw, mmreg, reg, imm)
-
-#define         pinsrw_r2r(reg,mmreg,imm)   mmx_r2ri (pinsrw, reg, mmreg, imm)
-
-#define         pmaxsw_m2r(var,reg)         mmx_m2r (pmaxsw, var, reg)
-#define         pmaxsw_r2r(regs,regd)       mmx_r2r (pmaxsw, regs, regd)
-
-#define         pmaxub_m2r(var,reg)         mmx_m2r (pmaxub, var, reg)
-#define         pmaxub_r2r(regs,regd)       mmx_r2r (pmaxub, regs, regd)
-
-#define         pminsw_m2r(var,reg)         mmx_m2r (pminsw, var, reg)
-#define         pminsw_r2r(regs,regd)       mmx_r2r (pminsw, regs, regd)
-
-#define         pminub_m2r(var,reg)         mmx_m2r (pminub, var, reg)
-#define         pminub_r2r(regs,regd)       mmx_r2r (pminub, regs, regd)
-
-#define         pmovmskb(mmreg,reg) \
-        __asm__ volatile ("movmskps %" #mmreg ", %" #reg)
-
-#define         pmulhuw_m2r(var,reg)        mmx_m2r (pmulhuw, var, reg)
-#define         pmulhuw_r2r(regs,regd)      mmx_r2r (pmulhuw, regs, regd)
-
-#define         prefetcht0(mem)             mmx_fetch (mem, t0)
-#define         prefetcht1(mem)             mmx_fetch (mem, t1)
-#define         prefetcht2(mem)             mmx_fetch (mem, t2)
-#define         prefetchnta(mem)            mmx_fetch (mem, nta)
-
-#define         psadbw_m2r(var,reg)         mmx_m2r (psadbw, var, reg)
-#define         psadbw_r2r(regs,regd)       mmx_r2r (psadbw, regs, regd)
-
-#define         pshufw_m2r(var,reg,imm)     mmx_m2ri(pshufw, var, reg, imm)
-#define         pshufw_r2r(regs,regd,imm)   mmx_r2ri(pshufw, regs, regd, imm)
-
-#define         sfence() __asm__ volatile ("sfence\n\t")
-
-/* SSE2 */
-#define         pshufhw_m2r(var,reg,imm)    mmx_m2ri(pshufhw, var, reg, imm)
-#define         pshufhw_r2r(regs,regd,imm)  mmx_r2ri(pshufhw, regs, regd, imm)
-#define         pshuflw_m2r(var,reg,imm)    mmx_m2ri(pshuflw, var, reg, imm)
-#define         pshuflw_r2r(regs,regd,imm)  mmx_r2ri(pshuflw, regs, regd, imm)
-
-#define         pshufd_r2r(regs,regd,imm)   mmx_r2ri(pshufd, regs, regd, imm)
-
-#define         movdqa_m2r(var,reg)         mmx_m2r (movdqa, var, reg)
-#define         movdqa_r2m(reg,var)         mmx_r2m (movdqa, reg, var)
-#define         movdqa_r2r(regs,regd)       mmx_r2r (movdqa, regs, regd)
-#define         movdqu_m2r(var,reg)         mmx_m2r (movdqu, var, reg)
-#define         movdqu_r2m(reg,var)         mmx_r2m (movdqu, reg, var)
-#define         movdqu_r2r(regs,regd)       mmx_r2r (movdqu, regs, regd)
-
-#define         pmullw_r2m(reg,var)         mmx_r2m (pmullw, reg, var)
-
-#define         pslldq_i2r(imm,reg)         mmx_i2r (pslldq, imm, reg)
-#define         psrldq_i2r(imm,reg)         mmx_i2r (psrldq, imm, reg)
-
-#define         punpcklqdq_r2r(regs,regd)   mmx_r2r (punpcklqdq, regs, regd)
-#define         punpckhqdq_r2r(regs,regd)   mmx_r2r (punpckhqdq, regs, regd)
-
-
-#endif /* AVCODEC_X86_MMX_H */
diff --git a/libavcodec/x86/motion_est_mmx.c b/libavcodec/x86/motion_est_mmx.c
index 0272410..948af98 100644
--- a/libavcodec/x86/motion_est_mmx.c
+++ b/libavcodec/x86/motion_est_mmx.c
@@ -5,20 +5,20 @@
  *
  * mostly by Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -38,7 +38,7 @@ static inline void sad8_1_mmx(uint8_t *blk1, uint8_t *blk2, int stride, int h)
 {
     x86_reg len= -(stride*h);
     __asm__ volatile(
-        ASMALIGN(4)
+        ".p2align 4                     \n\t"
         "1:                             \n\t"
         "movq (%1, %%"REG_a"), %%mm0    \n\t"
         "movq (%2, %%"REG_a"), %%mm2    \n\t"
@@ -73,7 +73,7 @@ static inline void sad8_1_mmx(uint8_t *blk1, uint8_t *blk2, int stride, int h)
 static inline void sad8_1_mmx2(uint8_t *blk1, uint8_t *blk2, int stride, int h)
 {
     __asm__ volatile(
-        ASMALIGN(4)
+        ".p2align 4                     \n\t"
         "1:                             \n\t"
         "movq (%1), %%mm0               \n\t"
         "movq (%1, %3), %%mm1           \n\t"
@@ -94,35 +94,32 @@ static int sad16_sse2(void *v, uint8_t *blk2, uint8_t *blk1, int stride, int h)
 {
     int ret;
     __asm__ volatile(
-        "pxor %%xmm6, %%xmm6            \n\t"
-        ASMALIGN(4)
+        "pxor %%xmm2, %%xmm2            \n\t"
+        ".p2align 4                     \n\t"
         "1:                             \n\t"
         "movdqu (%1), %%xmm0            \n\t"
-        "movdqu (%1, %3), %%xmm1        \n\t"
+        "movdqu (%1, %4), %%xmm1        \n\t"
         "psadbw (%2), %%xmm0            \n\t"
-        "psadbw (%2, %3), %%xmm1        \n\t"
-        "paddw %%xmm0, %%xmm6           \n\t"
-        "paddw %%xmm1, %%xmm6           \n\t"
-        "lea (%1,%3,2), %1              \n\t"
-        "lea (%2,%3,2), %2              \n\t"
+        "psadbw (%2, %4), %%xmm1        \n\t"
+        "paddw %%xmm0, %%xmm2           \n\t"
+        "paddw %%xmm1, %%xmm2           \n\t"
+        "lea (%1,%4,2), %1              \n\t"
+        "lea (%2,%4,2), %2              \n\t"
         "sub $2, %0                     \n\t"
         " jg 1b                         \n\t"
-        : "+r" (h), "+r" (blk1), "+r" (blk2)
+        "movhlps %%xmm2, %%xmm0         \n\t"
+        "paddw   %%xmm0, %%xmm2         \n\t"
+        "movd    %%xmm2, %3             \n\t"
+        : "+r" (h), "+r" (blk1), "+r" (blk2), "=r"(ret)
         : "r" ((x86_reg)stride)
     );
-    __asm__ volatile(
-        "movhlps %%xmm6, %%xmm0         \n\t"
-        "paddw   %%xmm0, %%xmm6         \n\t"
-        "movd    %%xmm6, %0             \n\t"
-        : "=r"(ret)
-    );
     return ret;
 }
 
 static inline void sad8_x2a_mmx2(uint8_t *blk1, uint8_t *blk2, int stride, int h)
 {
     __asm__ volatile(
-        ASMALIGN(4)
+        ".p2align 4                     \n\t"
         "1:                             \n\t"
         "movq (%1), %%mm0               \n\t"
         "movq (%1, %3), %%mm1           \n\t"
@@ -146,7 +143,7 @@ static inline void sad8_y2a_mmx2(uint8_t *blk1, uint8_t *blk2, int stride, int h
     __asm__ volatile(
         "movq (%1), %%mm0               \n\t"
         "add %3, %1                     \n\t"
-        ASMALIGN(4)
+        ".p2align 4                     \n\t"
         "1:                             \n\t"
         "movq (%1), %%mm1               \n\t"
         "movq (%1, %3), %%mm2           \n\t"
@@ -173,7 +170,7 @@ static inline void sad8_4_mmx2(uint8_t *blk1, uint8_t *blk2, int stride, int h)
         "movq (%1), %%mm0               \n\t"
         "pavgb 1(%1), %%mm0             \n\t"
         "add %3, %1                     \n\t"
-        ASMALIGN(4)
+        ".p2align 4                     \n\t"
         "1:                             \n\t"
         "movq (%1), %%mm1               \n\t"
         "movq (%1,%3), %%mm2            \n\t"
@@ -200,7 +197,7 @@ static inline void sad8_2_mmx(uint8_t *blk1a, uint8_t *blk1b, uint8_t *blk2, int
 {
     x86_reg len= -(stride*h);
     __asm__ volatile(
-        ASMALIGN(4)
+        ".p2align 4                     \n\t"
         "1:                             \n\t"
         "movq (%1, %%"REG_a"), %%mm0    \n\t"
         "movq (%2, %%"REG_a"), %%mm1    \n\t"
@@ -248,7 +245,7 @@ static inline void sad8_4_mmx(uint8_t *blk1, uint8_t *blk2, int stride, int h)
         "punpckhbw %%mm7, %%mm3         \n\t"
         "paddw %%mm2, %%mm0             \n\t"
         "paddw %%mm3, %%mm1             \n\t"
-        ASMALIGN(4)
+        ".p2align 4                     \n\t"
         "1:                             \n\t"
         "movq (%2, %%"REG_a"), %%mm2    \n\t"
         "movq 1(%2, %%"REG_a"), %%mm4   \n\t"
@@ -427,7 +424,9 @@ PIX_SAD(mmx2)
 
 void dsputil_init_pix_mmx(DSPContext* c, AVCodecContext *avctx)
 {
-    if (mm_flags & FF_MM_MMX) {
+    int mm_flags = av_get_cpu_flags();
+
+    if (mm_flags & AV_CPU_FLAG_MMX) {
         c->pix_abs[0][0] = sad16_mmx;
         c->pix_abs[0][1] = sad16_x2_mmx;
         c->pix_abs[0][2] = sad16_y2_mmx;
@@ -440,7 +439,7 @@ void dsputil_init_pix_mmx(DSPContext* c, AVCodecContext *avctx)
         c->sad[0]= sad16_mmx;
         c->sad[1]= sad8_mmx;
     }
-    if (mm_flags & FF_MM_MMX2) {
+    if (mm_flags & AV_CPU_FLAG_MMX2) {
         c->pix_abs[0][0] = sad16_mmx2;
         c->pix_abs[1][0] = sad8_mmx2;
 
@@ -456,7 +455,7 @@ void dsputil_init_pix_mmx(DSPContext* c, AVCodecContext *avctx)
             c->pix_abs[1][3] = sad8_xy2_mmx2;
         }
     }
-    if ((mm_flags & FF_MM_SSE2) && !(mm_flags & FF_MM_3DNOW) && avctx->codec_id != CODEC_ID_SNOW) {
+    if ((mm_flags & AV_CPU_FLAG_SSE2) && !(mm_flags & AV_CPU_FLAG_3DNOW) && avctx->codec_id != CODEC_ID_SNOW) {
         c->sad[0]= sad16_sse2;
     }
 }
diff --git a/libavcodec/x86/mpegaudiodec_mmx.c b/libavcodec/x86/mpegaudiodec_mmx.c
new file mode 100644
index 0000000..ce5b7d6
--- /dev/null
+++ b/libavcodec/x86/mpegaudiodec_mmx.c
@@ -0,0 +1,158 @@
+/*
+ * MMX optimized MP3 decoding functions
+ * Copyright (c) 2010 Vitor Sessak
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "libavutil/cpu.h"
+#include "libavutil/x86_cpu.h"
+
+#define CONFIG_FLOAT 1
+#include "libavcodec/mpegaudio.h"
+
+#define MACS(rt, ra, rb) rt+=(ra)*(rb)
+#define MLSS(rt, ra, rb) rt-=(ra)*(rb)
+
+#define SUM8(op, sum, w, p)               \
+{                                         \
+    op(sum, (w)[0 * 64], (p)[0 * 64]);    \
+    op(sum, (w)[1 * 64], (p)[1 * 64]);    \
+    op(sum, (w)[2 * 64], (p)[2 * 64]);    \
+    op(sum, (w)[3 * 64], (p)[3 * 64]);    \
+    op(sum, (w)[4 * 64], (p)[4 * 64]);    \
+    op(sum, (w)[5 * 64], (p)[5 * 64]);    \
+    op(sum, (w)[6 * 64], (p)[6 * 64]);    \
+    op(sum, (w)[7 * 64], (p)[7 * 64]);    \
+}
+
+static void apply_window(const float *buf, const float *win1,
+                         const float *win2, float *sum1, float *sum2, int len)
+{
+    x86_reg count = - 4*len;
+    const float *win1a = win1+len;
+    const float *win2a = win2+len;
+    const float *bufa  = buf+len;
+    float *sum1a = sum1+len;
+    float *sum2a = sum2+len;
+
+
+#define MULT(a, b)                                 \
+    "movaps " #a "(%1,%0), %%xmm1           \n\t"  \
+    "movaps " #a "(%3,%0), %%xmm2           \n\t"  \
+    "mulps         %%xmm2, %%xmm1           \n\t"  \
+    "subps         %%xmm1, %%xmm0           \n\t"  \
+    "mulps  " #b "(%2,%0), %%xmm2           \n\t"  \
+    "subps         %%xmm2, %%xmm4           \n\t"  \
+
+    __asm__ volatile(
+            "1:                                   \n\t"
+            "xorps       %%xmm0, %%xmm0           \n\t"
+            "xorps       %%xmm4, %%xmm4           \n\t"
+
+            MULT(   0,   0)
+            MULT( 256,  64)
+            MULT( 512, 128)
+            MULT( 768, 192)
+            MULT(1024, 256)
+            MULT(1280, 320)
+            MULT(1536, 384)
+            MULT(1792, 448)
+
+            "movaps      %%xmm0, (%4,%0)          \n\t"
+            "movaps      %%xmm4, (%5,%0)          \n\t"
+            "add            $16,  %0              \n\t"
+            "jl              1b                   \n\t"
+            :"+&r"(count)
+            :"r"(win1a), "r"(win2a), "r"(bufa), "r"(sum1a), "r"(sum2a)
+            );
+
+#undef MULT
+}
+
+static void apply_window_mp3(float *in, float *win, int *unused, float *out,
+                             int incr)
+{
+    LOCAL_ALIGNED_16(float, suma, [17]);
+    LOCAL_ALIGNED_16(float, sumb, [17]);
+    LOCAL_ALIGNED_16(float, sumc, [17]);
+    LOCAL_ALIGNED_16(float, sumd, [17]);
+
+    float sum;
+
+    /* copy to avoid wrap */
+    memcpy(in + 512, in, 32 * sizeof(*in));
+
+    apply_window(in + 16, win     , win + 512, suma, sumc, 16);
+    apply_window(in + 32, win + 48, win + 640, sumb, sumd, 16);
+
+    SUM8(MACS, suma[0], win + 32, in + 48);
+
+    sumc[ 0] = 0;
+    sumb[16] = 0;
+    sumd[16] = 0;
+
+#define SUMS(suma, sumb, sumc, sumd, out1, out2)               \
+            "movups " #sumd "(%4),       %%xmm0          \n\t" \
+            "shufps         $0x1b,       %%xmm0, %%xmm0  \n\t" \
+            "subps  " #suma "(%1),       %%xmm0          \n\t" \
+            "movaps        %%xmm0," #out1 "(%0)          \n\t" \
+\
+            "movups " #sumc "(%3),       %%xmm0          \n\t" \
+            "shufps         $0x1b,       %%xmm0, %%xmm0  \n\t" \
+            "addps  " #sumb "(%2),       %%xmm0          \n\t" \
+            "movaps        %%xmm0," #out2 "(%0)          \n\t"
+
+    if (incr == 1) {
+        __asm__ volatile(
+            SUMS( 0, 48,  4, 52,  0, 112)
+            SUMS(16, 32, 20, 36, 16,  96)
+            SUMS(32, 16, 36, 20, 32,  80)
+            SUMS(48,  0, 52,  4, 48,  64)
+
+            :"+&r"(out)
+            :"r"(&suma[0]), "r"(&sumb[0]), "r"(&sumc[0]), "r"(&sumd[0])
+            :"memory"
+            );
+        out += 16*incr;
+    } else {
+        int j;
+        float *out2 = out + 32 * incr;
+        out[0  ]  = -suma[   0];
+        out += incr;
+        out2 -= incr;
+        for(j=1;j<16;j++) {
+            *out  = -suma[   j] + sumd[16-j];
+            *out2 =  sumb[16-j] + sumc[   j];
+            out  += incr;
+            out2 -= incr;
+        }
+    }
+
+    sum = 0;
+    SUM8(MLSS, sum, win + 16 + 32, in + 32);
+    *out = sum;
+}
+
+void ff_mpegaudiodec_init_mmx(MPADecodeContext *s)
+{
+    int mm_flags = av_get_cpu_flags();
+
+    if (mm_flags & AV_CPU_FLAG_SSE2) {
+        s->apply_window_mp3 = apply_window_mp3;
+    }
+}
diff --git a/libavcodec/x86/mpegvideo_mmx.c b/libavcodec/x86/mpegvideo_mmx.c
index 5deb68d..7dd9a66 100644
--- a/libavcodec/x86/mpegvideo_mmx.c
+++ b/libavcodec/x86/mpegvideo_mmx.c
@@ -5,23 +5,24 @@
  * Optimized for ia32 CPUs by Nick Kurshev <nickols_k at mail.ru>
  * h263, mpeg1, mpeg2 dequantizer & draw_edges by Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/cpu.h"
 #include "libavutil/x86_cpu.h"
 #include "libavcodec/avcodec.h"
 #include "libavcodec/dsputil.h"
@@ -65,7 +66,7 @@ __asm__ volatile(
                 "packssdw %%mm5, %%mm5          \n\t"
                 "psubw %%mm5, %%mm7             \n\t"
                 "pxor %%mm4, %%mm4              \n\t"
-                ASMALIGN(4)
+                ".p2align 4                     \n\t"
                 "1:                             \n\t"
                 "movq (%0, %3), %%mm0           \n\t"
                 "movq 8(%0, %3), %%mm1          \n\t"
@@ -128,7 +129,7 @@ __asm__ volatile(
                 "packssdw %%mm5, %%mm5          \n\t"
                 "psubw %%mm5, %%mm7             \n\t"
                 "pxor %%mm4, %%mm4              \n\t"
-                ASMALIGN(4)
+                ".p2align 4                     \n\t"
                 "1:                             \n\t"
                 "movq (%0, %3), %%mm0           \n\t"
                 "movq 8(%0, %3), %%mm1          \n\t"
@@ -221,7 +222,7 @@ __asm__ volatile(
                 "packssdw %%mm6, %%mm6          \n\t"
                 "packssdw %%mm6, %%mm6          \n\t"
                 "mov %3, %%"REG_a"              \n\t"
-                ASMALIGN(4)
+                ".p2align 4                     \n\t"
                 "1:                             \n\t"
                 "movq (%0, %%"REG_a"), %%mm0    \n\t"
                 "movq 8(%0, %%"REG_a"), %%mm1   \n\t"
@@ -284,7 +285,7 @@ __asm__ volatile(
                 "packssdw %%mm6, %%mm6          \n\t"
                 "packssdw %%mm6, %%mm6          \n\t"
                 "mov %3, %%"REG_a"              \n\t"
-                ASMALIGN(4)
+                ".p2align 4                     \n\t"
                 "1:                             \n\t"
                 "movq (%0, %%"REG_a"), %%mm0    \n\t"
                 "movq 8(%0, %%"REG_a"), %%mm1   \n\t"
@@ -356,7 +357,7 @@ __asm__ volatile(
                 "packssdw %%mm6, %%mm6          \n\t"
                 "packssdw %%mm6, %%mm6          \n\t"
                 "mov %3, %%"REG_a"              \n\t"
-                ASMALIGN(4)
+                ".p2align 4                     \n\t"
                 "1:                             \n\t"
                 "movq (%0, %%"REG_a"), %%mm0    \n\t"
                 "movq 8(%0, %%"REG_a"), %%mm1   \n\t"
@@ -417,7 +418,7 @@ __asm__ volatile(
                 "packssdw %%mm6, %%mm6          \n\t"
                 "packssdw %%mm6, %%mm6          \n\t"
                 "mov %3, %%"REG_a"              \n\t"
-                ASMALIGN(4)
+                ".p2align 4                     \n\t"
                 "1:                             \n\t"
                 "movq (%0, %%"REG_a"), %%mm0    \n\t"
                 "movq 8(%0, %%"REG_a"), %%mm1   \n\t"
@@ -580,6 +581,8 @@ static void  denoise_dct_sse2(MpegEncContext *s, DCTELEM *block){
             " jb 1b                             \n\t"
         : "+r" (block), "+r" (sum), "+r" (offset)
         : "r"(block+64)
+          XMM_CLOBBERS_ONLY("%xmm0", "%xmm1", "%xmm2", "%xmm3",
+                            "%xmm4", "%xmm5", "%xmm6", "%xmm7")
     );
 }
 
@@ -625,7 +628,9 @@ static void  denoise_dct_sse2(MpegEncContext *s, DCTELEM *block){
 
 void MPV_common_init_mmx(MpegEncContext *s)
 {
-    if (mm_flags & FF_MM_MMX) {
+    int mm_flags = av_get_cpu_flags();
+
+    if (mm_flags & AV_CPU_FLAG_MMX) {
         const int dct_algo = s->avctx->dct_algo;
 
         s->dct_unquantize_h263_intra = dct_unquantize_h263_intra_mmx;
@@ -636,7 +641,7 @@ void MPV_common_init_mmx(MpegEncContext *s)
             s->dct_unquantize_mpeg2_intra = dct_unquantize_mpeg2_intra_mmx;
         s->dct_unquantize_mpeg2_inter = dct_unquantize_mpeg2_inter_mmx;
 
-        if (mm_flags & FF_MM_SSE2) {
+        if (mm_flags & AV_CPU_FLAG_SSE2) {
             s->denoise_dct= denoise_dct_sse2;
         } else {
                 s->denoise_dct= denoise_dct_mmx;
@@ -644,13 +649,13 @@ void MPV_common_init_mmx(MpegEncContext *s)
 
         if(dct_algo==FF_DCT_AUTO || dct_algo==FF_DCT_MMX){
 #if HAVE_SSSE3
-            if(mm_flags & FF_MM_SSSE3){
+            if(mm_flags & AV_CPU_FLAG_SSSE3){
                 s->dct_quantize= dct_quantize_SSSE3;
             } else
 #endif
-            if(mm_flags & FF_MM_SSE2){
+            if(mm_flags & AV_CPU_FLAG_SSE2){
                 s->dct_quantize= dct_quantize_SSE2;
-            } else if(mm_flags & FF_MM_MMX2){
+            } else if(mm_flags & AV_CPU_FLAG_MMX2){
                 s->dct_quantize= dct_quantize_MMX2;
             } else {
                 s->dct_quantize= dct_quantize_MMX;
diff --git a/libavcodec/x86/mpegvideo_mmx_template.c b/libavcodec/x86/mpegvideo_mmx_template.c
index 0d92792..ddda07a 100644
--- a/libavcodec/x86/mpegvideo_mmx_template.c
+++ b/libavcodec/x86/mpegvideo_mmx_template.c
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2002 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -158,7 +158,7 @@ static int RENAME(dct_quantize)(MpegEncContext *s,
             "pxor "MM"6, "MM"6                  \n\t"
             "psubw (%3), "MM"6                  \n\t" // -bias[0]
             "mov $-128, %%"REG_a"               \n\t"
-            ASMALIGN(4)
+            ".p2align 4                         \n\t"
             "1:                                 \n\t"
             MOVQ" (%1, %%"REG_a"), "MM"0        \n\t" // block[i]
             SAVE_SIGN(MM"1", MM"0")                   // ABS(block[i])
@@ -180,6 +180,8 @@ static int RENAME(dct_quantize)(MpegEncContext *s,
             : "+a" (last_non_zero_p1)
             : "r" (block+64), "r" (qmat), "r" (bias),
               "r" (inv_zigzag_direct16+64), "r" (temp_block+64)
+              XMM_CLOBBERS_ONLY("%xmm0", "%xmm1", "%xmm2", "%xmm3",
+                                "%xmm4", "%xmm5", "%xmm6", "%xmm7")
         );
     }else{ // FMT_H263
         __asm__ volatile(
@@ -188,7 +190,7 @@ static int RENAME(dct_quantize)(MpegEncContext *s,
             "pxor "MM"7, "MM"7                  \n\t" // 0
             "pxor "MM"4, "MM"4                  \n\t" // 0
             "mov $-128, %%"REG_a"               \n\t"
-            ASMALIGN(4)
+            ".p2align 4                         \n\t"
             "1:                                 \n\t"
             MOVQ" (%1, %%"REG_a"), "MM"0        \n\t" // block[i]
             SAVE_SIGN(MM"1", MM"0")                   // ABS(block[i])
@@ -212,6 +214,8 @@ static int RENAME(dct_quantize)(MpegEncContext *s,
             : "+a" (last_non_zero_p1)
             : "r" (block+64), "r" (qmat+64), "r" (bias+64),
               "r" (inv_zigzag_direct16+64), "r" (temp_block+64)
+              XMM_CLOBBERS_ONLY("%xmm0", "%xmm1", "%xmm2", "%xmm3",
+                                "%xmm4", "%xmm5", "%xmm6", "%xmm7")
         );
     }
     __asm__ volatile(
diff --git a/libavcodec/x86/rv40dsp_mmx.c b/libavcodec/x86/rv40dsp_mmx.c
deleted file mode 100644
index 2b154c0..0000000
--- a/libavcodec/x86/rv40dsp_mmx.c
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (c) 2008 Konstantin Shishkov, Mathieu Velten
- *
- * MMX-optimized DSP functions for RV40, based on H.264 optimizations by
- * Michael Niedermayer and Loren Merritt
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-#include "dsputil_mmx.h"
-
-/* bias interleaved with bias div 8, use p+1 to access bias div 8 */
-DECLARE_ALIGNED(8, static const uint64_t, rv40_bias_reg)[4][8] = {
-    { 0x0000000000000000ULL, 0x0000000000000000ULL, 0x0010001000100010ULL, 0x0002000200020002ULL,
-      0x0020002000200020ULL, 0x0004000400040004ULL, 0x0010001000100010ULL, 0x0002000200020002ULL },
-    { 0x0020002000200020ULL, 0x0004000400040004ULL, 0x001C001C001C001CULL, 0x0003000300030003ULL,
-      0x0020002000200020ULL, 0x0004000400040004ULL, 0x001C001C001C001CULL, 0x0003000300030003ULL },
-    { 0x0000000000000000ULL, 0x0000000000000000ULL, 0x0020002000200020ULL, 0x0004000400040004ULL,
-      0x0010001000100010ULL, 0x0002000200020002ULL, 0x0020002000200020ULL, 0x0004000400040004ULL },
-    { 0x0020002000200020ULL, 0x0004000400040004ULL, 0x001C001C001C001CULL, 0x0003000300030003ULL,
-      0x0020002000200020ULL, 0x0004000400040004ULL, 0x001C001C001C001CULL, 0x0003000300030003ULL }
-};
-
-static void put_rv40_chroma_mc8_mmx(uint8_t *dst/*align 8*/, uint8_t *src/*align 1*/, int stride, int h, int x, int y)
-{
-    put_h264_chroma_generic_mc8_mmx(dst, src, stride, h, x, y, &rv40_bias_reg[y>>1][x&(~1)]);
-}
-static void put_rv40_chroma_mc4_mmx(uint8_t *dst/*align 8*/, uint8_t *src/*align 1*/, int stride, int h, int x, int y)
-{
-    put_h264_chroma_generic_mc4_mmx(dst, src, stride, h, x, y, &rv40_bias_reg[y>>1][x&(~1)]);
-}
-static void avg_rv40_chroma_mc8_mmx2(uint8_t *dst/*align 8*/, uint8_t *src/*align 1*/, int stride, int h, int x, int y)
-{
-    avg_h264_chroma_generic_mc8_mmx2(dst, src, stride, h, x, y, &rv40_bias_reg[y>>1][x&(~1)]);
-}
-static void avg_rv40_chroma_mc4_mmx2(uint8_t *dst/*align 8*/, uint8_t *src/*align 1*/, int stride, int h, int x, int y)
-{
-    avg_h264_chroma_generic_mc4_mmx2(dst, src, stride, h, x, y, &rv40_bias_reg[y>>1][x&(~1)]);
-}
-static void avg_rv40_chroma_mc8_3dnow(uint8_t *dst/*align 8*/, uint8_t *src/*align 1*/, int stride, int h, int x, int y)
-{
-    avg_h264_chroma_generic_mc8_3dnow(dst, src, stride, h, x, y, &rv40_bias_reg[y>>1][x&(~1)]);
-}
-static void avg_rv40_chroma_mc4_3dnow(uint8_t *dst/*align 8*/, uint8_t *src/*align 1*/, int stride, int h, int x, int y)
-{
-    avg_h264_chroma_generic_mc4_3dnow(dst, src, stride, h, x, y, &rv40_bias_reg[y>>1][x&(~1)]);
-}
diff --git a/libavcodec/x86/simple_idct_mmx.c b/libavcodec/x86/simple_idct_mmx.c
index 5ea4c84..d78ae6b 100644
--- a/libavcodec/x86/simple_idct_mmx.c
+++ b/libavcodec/x86/simple_idct_mmx.c
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2001, 2002 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #include "libavcodec/dsputil.h"
@@ -789,7 +789,7 @@ IDCT(  16(%1), 80(%1), 48(%1), 112(%1),  8(%0), 20)
 IDCT(  24(%1), 88(%1), 56(%1), 120(%1), 12(%0), 20)
         "jmp 9f                         \n\t"
 
-        "#" ASMALIGN(4)                      \
+        "# .p2align 4                   \n\t"\
         "4:                             \n\t"
 Z_COND_IDCT(  64(%0), 72(%0), 80(%0), 88(%0), 64(%1),paddd (%2), 11, 6f)
 Z_COND_IDCT(  96(%0),104(%0),112(%0),120(%0), 96(%1),paddd (%2), 11, 5f)
@@ -864,7 +864,7 @@ IDCT(  16(%1), 80(%1), 48(%1), 112(%1),  8(%0), 20)
 IDCT(  24(%1), 88(%1), 56(%1), 120(%1), 12(%0), 20)
         "jmp 9f                         \n\t"
 
-        "#" ASMALIGN(4)                      \
+        "# .p2align 4                   \n\t"\
         "6:                             \n\t"
 Z_COND_IDCT(  96(%0),104(%0),112(%0),120(%0), 96(%1),paddd (%2), 11, 7f)
 
@@ -930,7 +930,7 @@ IDCT(  16(%1), 80(%1), 48(%1), 112(%1),  8(%0), 20)
 IDCT(  24(%1), 88(%1), 56(%1), 120(%1), 12(%0), 20)
         "jmp 9f                         \n\t"
 
-        "#" ASMALIGN(4)                      \
+        "# .p2align 4                   \n\t"\
         "2:                             \n\t"
 Z_COND_IDCT(  96(%0),104(%0),112(%0),120(%0), 96(%1),paddd (%2), 11, 3f)
 
@@ -1007,7 +1007,7 @@ IDCT(  16(%1), 80(%1), 48(%1), 112(%1),  8(%0), 20)
 IDCT(  24(%1), 88(%1), 56(%1), 120(%1), 12(%0), 20)
         "jmp 9f                         \n\t"
 
-        "#" ASMALIGN(4)                      \
+        "# .p2align 4                   \n\t"\
         "3:                             \n\t"
 #undef IDCT
 #define IDCT(src0, src4, src1, src5, dst, shift) \
@@ -1071,7 +1071,7 @@ IDCT(  16(%1), 80(%1), 48(%1), 112(%1),  8(%0), 20)
 IDCT(  24(%1), 88(%1), 56(%1), 120(%1), 12(%0), 20)
         "jmp 9f                         \n\t"
 
-        "#" ASMALIGN(4)                      \
+        "# .p2align 4                   \n\t"\
         "5:                             \n\t"
 #undef IDCT
 #define IDCT(src0, src4, src1, src5, dst, shift) \
@@ -1136,7 +1136,7 @@ IDCT(  16(%1), 80(%1), 48(%1), 112(%1),  8(%0), 20)
         "jmp 9f                         \n\t"
 
 
-        "#" ASMALIGN(4)                      \
+        "# .p2align 4                   \n\t"\
         "1:                             \n\t"
 #undef IDCT
 #define IDCT(src0, src4, src1, src5, dst, shift) \
@@ -1210,7 +1210,7 @@ IDCT(  24(%1), 88(%1), 56(%1), 120(%1), 12(%0), 20)
         "jmp 9f                         \n\t"
 
 
-        "#" ASMALIGN(4)
+        "# .p2align 4                   \n\t"
         "7:                             \n\t"
 #undef IDCT
 #define IDCT(src0, src4, src1, src5, dst, shift) \
@@ -1287,10 +1287,10 @@ void ff_simple_idct_mmx(int16_t *block)
 void ff_simple_idct_put_mmx(uint8_t *dest, int line_size, DCTELEM *block)
 {
     idct(block);
-    put_pixels_clamped_mmx(block, dest, line_size);
+    ff_put_pixels_clamped_mmx(block, dest, line_size);
 }
 void ff_simple_idct_add_mmx(uint8_t *dest, int line_size, DCTELEM *block)
 {
     idct(block);
-    add_pixels_clamped_mmx(block, dest, line_size);
+    ff_add_pixels_clamped_mmx(block, dest, line_size);
 }
diff --git a/libavcodec/x86/snowdsp_mmx.c b/libavcodec/x86/snowdsp_mmx.c
index 263f0bb..3e6bc99 100644
--- a/libavcodec/x86/snowdsp_mmx.c
+++ b/libavcodec/x86/snowdsp_mmx.c
@@ -2,23 +2,24 @@
  * MMX and SSE2 optimized snow DSP utils
  * Copyright (c) 2005-2006 Robert Edele <yartrebo at earthlink.net>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/cpu.h"
 #include "libavutil/x86_cpu.h"
 #include "libavcodec/avcodec.h"
 #include "libavcodec/snow.h"
@@ -811,7 +812,7 @@ snow_inner_add_yblock_sse2_end_16
              "add %%"REG_c", "PTR_SIZE"*2(%%"REG_a");\n\t"\
              "add %%"REG_c", "PTR_SIZE"*1(%%"REG_a");\n\t"\
              "add %%"REG_c", (%%"REG_a")     \n\t"\
-             "add $"PTR_SIZE"*1, %1          \n\t"\
+             "add"OPSIZE " $"PTR_SIZE"*1, %1 \n\t"\
              "add %%"REG_c", %0              \n\t"\
              "dec %2                         \n\t"\
              "jnz 1b                         \n\t"\
@@ -874,10 +875,10 @@ static void ff_snow_inner_add_yblock_mmx(const uint8_t *obmc, const int obmc_str
 
 void ff_dwt_init_x86(DWTContext *c)
 {
-    mm_flags = mm_support();
+    int mm_flags = av_get_cpu_flags();
 
-    if (mm_flags & FF_MM_MMX) {
-        if(mm_flags & FF_MM_SSE2 & 0){
+    if (mm_flags & AV_CPU_FLAG_MMX) {
+        if(mm_flags & AV_CPU_FLAG_SSE2 & 0){
             c->horizontal_compose97i = ff_snow_horizontal_compose97i_sse2;
 #if HAVE_7REGS
             c->vertical_compose97i = ff_snow_vertical_compose97i_sse2;
@@ -885,7 +886,7 @@ void ff_dwt_init_x86(DWTContext *c)
             c->inner_add_yblock = ff_snow_inner_add_yblock_sse2;
         }
         else{
-            if(mm_flags & FF_MM_MMX2){
+            if(mm_flags & AV_CPU_FLAG_MMX2){
             c->horizontal_compose97i = ff_snow_horizontal_compose97i_mmx;
 #if HAVE_7REGS
             c->vertical_compose97i = ff_snow_vertical_compose97i_mmx;
diff --git a/libavcodec/x86/vc1dsp_mmx.c b/libavcodec/x86/vc1dsp_mmx.c
index e0b1f5b..a525aee 100644
--- a/libavcodec/x86/vc1dsp_mmx.c
+++ b/libavcodec/x86/vc1dsp_mmx.c
@@ -24,9 +24,11 @@
  * OTHER DEALINGS IN THE SOFTWARE.
  */
 
+#include "libavutil/cpu.h"
 #include "libavutil/x86_cpu.h"
 #include "libavcodec/dsputil.h"
 #include "dsputil_mmx.h"
+#include "libavcodec/vc1dsp.h"
 
 #define OP_PUT(S,D)
 #define OP_AVG(S,D) "pavgb " #S ", " #D " \n\t"
@@ -73,8 +75,6 @@
     "movq      %%mm"#R1", "#OFF"(%1)   \n\t"    \
     "add       %2, %0                  \n\t"
 
-DECLARE_ALIGNED(16, const uint64_t, ff_pw_9) = 0x0009000900090009ULL;
-
 /** Sacrifying mm6 allows to pipeline loads from src */
 static void vc1_put_ver_16b_shift2_mmx(int16_t *dst,
                                        const uint8_t *src, x86_reg stride,
@@ -215,13 +215,6 @@ VC1_SHIFT2(OP_PUT, put_)
 VC1_SHIFT2(OP_AVG, avg_)
 
 /**
- * Filter coefficients made global to allow access by all 1 or 3 quarter shift
- * interpolation functions.
- */
-DECLARE_ASM_CONST(16, uint64_t, ff_pw_53) = 0x0035003500350035ULL;
-DECLARE_ASM_CONST(16, uint64_t, ff_pw_18) = 0x0012001200120012ULL;
-
-/**
  * Core of the 1/4 and 3/4 shift bicubic interpolation.
  *
  * @param UNPACK  Macro unpacking arguments from 8 to 16bits (can be empty).
@@ -283,7 +276,7 @@ vc1_put_ver_16b_ ## NAME ## _mmx(int16_t *dst, const uint8_t *src,      \
         LOAD_ROUNDER_MMX("%5")                                          \
         "movq      "MANGLE(ff_pw_53)", %%mm5\n\t"                       \
         "movq      "MANGLE(ff_pw_18)", %%mm6\n\t"                       \
-        ASMALIGN(3)                                                     \
+        ".p2align 3                \n\t"                                \
         "1:                        \n\t"                                \
         MSPEL_FILTER13_CORE(DO_UNPACK, "movd  1", A1, A2, A3, A4)       \
         NORMALIZE_MMX("%6")                                             \
@@ -339,7 +332,7 @@ OPNAME ## vc1_hor_16b_ ## NAME ## _mmx(uint8_t *dst, x86_reg stride,    \
         LOAD_ROUNDER_MMX("%4")                                          \
         "movq      "MANGLE(ff_pw_18)", %%mm6   \n\t"                    \
         "movq      "MANGLE(ff_pw_53)", %%mm5   \n\t"                    \
-        ASMALIGN(3)                                                     \
+        ".p2align 3                \n\t"                                \
         "1:                        \n\t"                                \
         MSPEL_FILTER13_CORE(DONT_UNPACK, "movq 2", A1, A2, A3, A4)      \
         NORMALIZE_MMX("$7")                                             \
@@ -377,7 +370,7 @@ OPNAME ## vc1_## NAME ## _mmx(uint8_t *dst, const uint8_t *src,         \
         LOAD_ROUNDER_MMX("%6")                                          \
         "movq      "MANGLE(ff_pw_53)", %%mm5       \n\t"                \
         "movq      "MANGLE(ff_pw_18)", %%mm6       \n\t"                \
-        ASMALIGN(3)                                                     \
+        ".p2align 3                \n\t"                                \
         "1:                        \n\t"                                \
         MSPEL_FILTER13_CORE(DO_UNPACK, "movd   1", A1, A2, A3, A4)      \
         NORMALIZE_MMX("$6")                                             \
@@ -411,7 +404,7 @@ typedef void (*vc1_mspel_mc_filter_hor_16bits)(uint8_t *dst, x86_reg dst_stride,
 typedef void (*vc1_mspel_mc_filter_8bits)(uint8_t *dst, const uint8_t *src, x86_reg stride, int rnd, x86_reg offset);
 
 /**
- * Interpolates fractional pel values by applying proper vertical then
+ * Interpolate fractional pel values by applying proper vertical then
  * horizontal filter.
  *
  * @param  dst     Destination buffer for interpolated pels.
@@ -689,30 +682,78 @@ static void vc1_inv_trans_8x8_dc_mmx2(uint8_t *dest, int linesize, DCTELEM *bloc
     );
 }
 
-void ff_vc1dsp_init_mmx(DSPContext* dsp, AVCodecContext *avctx) {
-    mm_flags = mm_support();
+#define LOOP_FILTER(EXT) \
+void ff_vc1_v_loop_filter4_ ## EXT(uint8_t *src, int stride, int pq); \
+void ff_vc1_h_loop_filter4_ ## EXT(uint8_t *src, int stride, int pq); \
+void ff_vc1_v_loop_filter8_ ## EXT(uint8_t *src, int stride, int pq); \
+void ff_vc1_h_loop_filter8_ ## EXT(uint8_t *src, int stride, int pq); \
+\
+static void vc1_v_loop_filter16_ ## EXT(uint8_t *src, int stride, int pq) \
+{ \
+    ff_vc1_v_loop_filter8_ ## EXT(src,   stride, pq); \
+    ff_vc1_v_loop_filter8_ ## EXT(src+8, stride, pq); \
+} \
+\
+static void vc1_h_loop_filter16_ ## EXT(uint8_t *src, int stride, int pq) \
+{ \
+    ff_vc1_h_loop_filter8_ ## EXT(src,          stride, pq); \
+    ff_vc1_h_loop_filter8_ ## EXT(src+8*stride, stride, pq); \
+}
+
+#if HAVE_YASM
+LOOP_FILTER(mmx)
+LOOP_FILTER(mmx2)
+LOOP_FILTER(sse2)
+LOOP_FILTER(ssse3)
 
-    dsp->put_vc1_mspel_pixels_tab[ 0] = ff_put_vc1_mspel_mc00_mmx;
-    dsp->put_vc1_mspel_pixels_tab[ 4] = put_vc1_mspel_mc01_mmx;
-    dsp->put_vc1_mspel_pixels_tab[ 8] = put_vc1_mspel_mc02_mmx;
-    dsp->put_vc1_mspel_pixels_tab[12] = put_vc1_mspel_mc03_mmx;
+void ff_vc1_h_loop_filter8_sse4(uint8_t *src, int stride, int pq);
+
+static void vc1_h_loop_filter16_sse4(uint8_t *src, int stride, int pq)
+{
+    ff_vc1_h_loop_filter8_sse4(src,          stride, pq);
+    ff_vc1_h_loop_filter8_sse4(src+8*stride, stride, pq);
+}
 
-    dsp->put_vc1_mspel_pixels_tab[ 1] = put_vc1_mspel_mc10_mmx;
-    dsp->put_vc1_mspel_pixels_tab[ 5] = put_vc1_mspel_mc11_mmx;
-    dsp->put_vc1_mspel_pixels_tab[ 9] = put_vc1_mspel_mc12_mmx;
-    dsp->put_vc1_mspel_pixels_tab[13] = put_vc1_mspel_mc13_mmx;
+#endif
 
-    dsp->put_vc1_mspel_pixels_tab[ 2] = put_vc1_mspel_mc20_mmx;
-    dsp->put_vc1_mspel_pixels_tab[ 6] = put_vc1_mspel_mc21_mmx;
-    dsp->put_vc1_mspel_pixels_tab[10] = put_vc1_mspel_mc22_mmx;
-    dsp->put_vc1_mspel_pixels_tab[14] = put_vc1_mspel_mc23_mmx;
+void ff_put_vc1_chroma_mc8_mmx_nornd  (uint8_t *dst, uint8_t *src,
+                                       int stride, int h, int x, int y);
+void ff_avg_vc1_chroma_mc8_mmx2_nornd (uint8_t *dst, uint8_t *src,
+                                       int stride, int h, int x, int y);
+void ff_avg_vc1_chroma_mc8_3dnow_nornd(uint8_t *dst, uint8_t *src,
+                                       int stride, int h, int x, int y);
+void ff_put_vc1_chroma_mc8_ssse3_nornd(uint8_t *dst, uint8_t *src,
+                                       int stride, int h, int x, int y);
+void ff_avg_vc1_chroma_mc8_ssse3_nornd(uint8_t *dst, uint8_t *src,
+                                       int stride, int h, int x, int y);
 
-    dsp->put_vc1_mspel_pixels_tab[ 3] = put_vc1_mspel_mc30_mmx;
-    dsp->put_vc1_mspel_pixels_tab[ 7] = put_vc1_mspel_mc31_mmx;
-    dsp->put_vc1_mspel_pixels_tab[11] = put_vc1_mspel_mc32_mmx;
-    dsp->put_vc1_mspel_pixels_tab[15] = put_vc1_mspel_mc33_mmx;
+void ff_vc1dsp_init_mmx(VC1DSPContext *dsp)
+{
+    int mm_flags = av_get_cpu_flags();
+
+    if (mm_flags & AV_CPU_FLAG_MMX) {
+        dsp->put_vc1_mspel_pixels_tab[ 0] = ff_put_vc1_mspel_mc00_mmx;
+        dsp->put_vc1_mspel_pixels_tab[ 4] = put_vc1_mspel_mc01_mmx;
+        dsp->put_vc1_mspel_pixels_tab[ 8] = put_vc1_mspel_mc02_mmx;
+        dsp->put_vc1_mspel_pixels_tab[12] = put_vc1_mspel_mc03_mmx;
+
+        dsp->put_vc1_mspel_pixels_tab[ 1] = put_vc1_mspel_mc10_mmx;
+        dsp->put_vc1_mspel_pixels_tab[ 5] = put_vc1_mspel_mc11_mmx;
+        dsp->put_vc1_mspel_pixels_tab[ 9] = put_vc1_mspel_mc12_mmx;
+        dsp->put_vc1_mspel_pixels_tab[13] = put_vc1_mspel_mc13_mmx;
+
+        dsp->put_vc1_mspel_pixels_tab[ 2] = put_vc1_mspel_mc20_mmx;
+        dsp->put_vc1_mspel_pixels_tab[ 6] = put_vc1_mspel_mc21_mmx;
+        dsp->put_vc1_mspel_pixels_tab[10] = put_vc1_mspel_mc22_mmx;
+        dsp->put_vc1_mspel_pixels_tab[14] = put_vc1_mspel_mc23_mmx;
+
+        dsp->put_vc1_mspel_pixels_tab[ 3] = put_vc1_mspel_mc30_mmx;
+        dsp->put_vc1_mspel_pixels_tab[ 7] = put_vc1_mspel_mc31_mmx;
+        dsp->put_vc1_mspel_pixels_tab[11] = put_vc1_mspel_mc32_mmx;
+        dsp->put_vc1_mspel_pixels_tab[15] = put_vc1_mspel_mc33_mmx;
+    }
 
-    if (mm_flags & FF_MM_MMX2){
+    if (mm_flags & AV_CPU_FLAG_MMX2){
         dsp->avg_vc1_mspel_pixels_tab[ 0] = ff_avg_vc1_mspel_mc00_mmx2;
         dsp->avg_vc1_mspel_pixels_tab[ 4] = avg_vc1_mspel_mc01_mmx2;
         dsp->avg_vc1_mspel_pixels_tab[ 8] = avg_vc1_mspel_mc02_mmx2;
@@ -738,4 +779,42 @@ void ff_vc1dsp_init_mmx(DSPContext* dsp, AVCodecContext *avctx) {
         dsp->vc1_inv_trans_8x4_dc = vc1_inv_trans_8x4_dc_mmx2;
         dsp->vc1_inv_trans_4x4_dc = vc1_inv_trans_4x4_dc_mmx2;
     }
+
+#define ASSIGN_LF(EXT) \
+        dsp->vc1_v_loop_filter4  = ff_vc1_v_loop_filter4_ ## EXT; \
+        dsp->vc1_h_loop_filter4  = ff_vc1_h_loop_filter4_ ## EXT; \
+        dsp->vc1_v_loop_filter8  = ff_vc1_v_loop_filter8_ ## EXT; \
+        dsp->vc1_h_loop_filter8  = ff_vc1_h_loop_filter8_ ## EXT; \
+        dsp->vc1_v_loop_filter16 = vc1_v_loop_filter16_ ## EXT; \
+        dsp->vc1_h_loop_filter16 = vc1_h_loop_filter16_ ## EXT
+
+#if HAVE_YASM
+    if (mm_flags & AV_CPU_FLAG_MMX) {
+        ASSIGN_LF(mmx);
+        dsp->put_no_rnd_vc1_chroma_pixels_tab[0]= ff_put_vc1_chroma_mc8_mmx_nornd;
+    }
+    return;
+    if (mm_flags & AV_CPU_FLAG_MMX2) {
+        ASSIGN_LF(mmx2);
+        dsp->avg_no_rnd_vc1_chroma_pixels_tab[0]= ff_avg_vc1_chroma_mc8_mmx2_nornd;
+    } else if (mm_flags & AV_CPU_FLAG_3DNOW) {
+        dsp->avg_no_rnd_vc1_chroma_pixels_tab[0]= ff_avg_vc1_chroma_mc8_3dnow_nornd;
+    }
+
+    if (mm_flags & AV_CPU_FLAG_SSE2) {
+        dsp->vc1_v_loop_filter8  = ff_vc1_v_loop_filter8_sse2;
+        dsp->vc1_h_loop_filter8  = ff_vc1_h_loop_filter8_sse2;
+        dsp->vc1_v_loop_filter16 = vc1_v_loop_filter16_sse2;
+        dsp->vc1_h_loop_filter16 = vc1_h_loop_filter16_sse2;
+    }
+    if (mm_flags & AV_CPU_FLAG_SSSE3) {
+        ASSIGN_LF(ssse3);
+        dsp->put_no_rnd_vc1_chroma_pixels_tab[0]= ff_put_vc1_chroma_mc8_ssse3_nornd;
+        dsp->avg_no_rnd_vc1_chroma_pixels_tab[0]= ff_avg_vc1_chroma_mc8_ssse3_nornd;
+    }
+    if (mm_flags & AV_CPU_FLAG_SSE4) {
+        dsp->vc1_h_loop_filter8  = ff_vc1_h_loop_filter8_sse4;
+        dsp->vc1_h_loop_filter16 = vc1_h_loop_filter16_sse4;
+    }
+#endif
 }
diff --git a/libavcodec/x86/vc1dsp_yasm.asm b/libavcodec/x86/vc1dsp_yasm.asm
new file mode 100644
index 0000000..0bd5a3b
--- /dev/null
+++ b/libavcodec/x86/vc1dsp_yasm.asm
@@ -0,0 +1,330 @@
+;******************************************************************************
+;* VC1 deblocking optimizations
+;* Copyright (c) 2009 David Conrad
+;*
+;* This file is part of Libav.
+;*
+;* Libav is free software; you can redistribute it and/or
+;* modify it under the terms of the GNU Lesser General Public
+;* License as published by the Free Software Foundation; either
+;* version 2.1 of the License, or (at your option) any later version.
+;*
+;* Libav is distributed in the hope that it will be useful,
+;* but WITHOUT ANY WARRANTY; without even the implied warranty of
+;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+;* Lesser General Public License for more details.
+;*
+;* You should have received a copy of the GNU Lesser General Public
+;* License along with Libav; if not, write to the Free Software
+;* 51, Inc., Foundation Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+;******************************************************************************
+
+%include "x86inc.asm"
+%include "x86util.asm"
+
+cextern pw_4
+cextern pw_5
+
+section .text
+
+; dst_low, dst_high (src), zero
+; zero-extends one vector from 8 to 16 bits
+%macro UNPACK_8TO16 4
+    mova      m%2, m%3
+    punpckh%1 m%3, m%4
+    punpckl%1 m%2, m%4
+%endmacro
+
+%macro STORE_4_WORDS_MMX 6
+    movd  %6d, %5
+%if mmsize==16
+    psrldq %5, 4
+%else
+    psrlq  %5, 32
+%endif
+    mov    %1, %6w
+    shr    %6, 16
+    mov    %2, %6w
+    movd  %6d, %5
+    mov    %3, %6w
+    shr    %6, 16
+    mov    %4, %6w
+%endmacro
+
+%macro STORE_4_WORDS_SSE4 6
+    pextrw %1, %5, %6+0
+    pextrw %2, %5, %6+1
+    pextrw %3, %5, %6+2
+    pextrw %4, %5, %6+3
+%endmacro
+
+; in:  p1 p0 q0 q1, clobbers p0
+; out: p1 = (2*(p1 - q1) - 5*(p0 - q0) + 4) >> 3
+%macro VC1_LOOP_FILTER_A0 4
+    psubw  %1, %4
+    psubw  %2, %3
+    paddw  %1, %1
+    pmullw %2, [pw_5]
+    psubw  %1, %2
+    paddw  %1, [pw_4]
+    psraw  %1, 3
+%endmacro
+
+; in: p0 q0 a0 a1 a2
+;     m0 m1 m7 m6 m5
+; %1: size
+; out: m0=p0' m1=q0'
+%macro VC1_FILTER 1
+    PABSW   m4, m7
+    PABSW   m3, m6
+    PABSW   m2, m5
+    mova    m6, m4
+    pminsw  m3, m2
+    pcmpgtw m6, m3  ; if (a2 < a0 || a1 < a0)
+    psubw   m3, m4
+    pmullw  m3, [pw_5]   ; 5*(a3 - a0)
+    PABSW   m2, m3
+    psraw   m2, 3   ; abs(d/8)
+    pxor    m7, m3  ; d_sign ^= a0_sign
+
+    pxor    m5, m5
+    movd    m3, r2d
+%if %1 > 4
+    punpcklbw m3, m3
+%endif
+    punpcklbw m3, m5
+    pcmpgtw m3, m4  ; if (a0 < pq)
+    pand    m6, m3
+
+    mova    m3, m0
+    psubw   m3, m1
+    PABSW   m4, m3
+    psraw   m4, 1
+    pxor    m3, m7  ; d_sign ^ clip_sign
+    psraw   m3, 15
+    pminsw  m2, m4  ; min(d, clip)
+    pcmpgtw m4, m5
+    pand    m6, m4  ; filt3 (C return value)
+
+; each set of 4 pixels is not filtered if the 3rd is not
+%if mmsize==16
+    pshuflw m4, m6, 0xaa
+%if %1 > 4
+    pshufhw m4, m4, 0xaa
+%endif
+%else
+    pshufw  m4, m6, 0xaa
+%endif
+    pandn   m3, m4
+    pand    m2, m6
+    pand    m3, m2  ; d final
+
+    PSIGNW  m3, m7
+    psubw   m0, m3
+    paddw   m1, m3
+    packuswb m0, m0
+    packuswb m1, m1
+%endmacro
+
+; 1st param: size of filter
+; 2nd param: mov suffix equivalent to the filter size
+%macro VC1_V_LOOP_FILTER 2
+    pxor      m5, m5
+    mov%2     m6, [r4]
+    mov%2     m4, [r4+r1]
+    mov%2     m7, [r4+2*r1]
+    mov%2     m0, [r4+r3]
+    punpcklbw m6, m5
+    punpcklbw m4, m5
+    punpcklbw m7, m5
+    punpcklbw m0, m5
+
+    VC1_LOOP_FILTER_A0 m6, m4, m7, m0
+    mov%2     m1, [r0]
+    mov%2     m2, [r0+r1]
+    punpcklbw m1, m5
+    punpcklbw m2, m5
+    mova      m4, m0
+    VC1_LOOP_FILTER_A0 m7, m4, m1, m2
+    mov%2     m3, [r0+2*r1]
+    mov%2     m4, [r0+r3]
+    punpcklbw m3, m5
+    punpcklbw m4, m5
+    mova      m5, m1
+    VC1_LOOP_FILTER_A0 m5, m2, m3, m4
+
+    VC1_FILTER %1
+    mov%2 [r4+r3], m0
+    mov%2 [r0],    m1
+%endmacro
+
+; 1st param: size of filter
+;     NOTE: UNPACK_8TO16 this number of 8 bit numbers are in half a register
+; 2nd (optional) param: temp register to use for storing words
+%macro VC1_H_LOOP_FILTER 1-2
+%if %1 == 4
+    movq      m0, [r0     -4]
+    movq      m1, [r0+  r1-4]
+    movq      m2, [r0+2*r1-4]
+    movq      m3, [r0+  r3-4]
+    TRANSPOSE4x4B 0, 1, 2, 3, 4
+%else
+    movq      m0, [r0     -4]
+    movq      m4, [r0+  r1-4]
+    movq      m1, [r0+2*r1-4]
+    movq      m5, [r0+  r3-4]
+    movq      m2, [r4     -4]
+    movq      m6, [r4+  r1-4]
+    movq      m3, [r4+2*r1-4]
+    movq      m7, [r4+  r3-4]
+    punpcklbw m0, m4
+    punpcklbw m1, m5
+    punpcklbw m2, m6
+    punpcklbw m3, m7
+    TRANSPOSE4x4W 0, 1, 2, 3, 4
+%endif
+    pxor      m5, m5
+
+    UNPACK_8TO16 bw, 6, 0, 5
+    UNPACK_8TO16 bw, 7, 1, 5
+    VC1_LOOP_FILTER_A0 m6, m0, m7, m1
+    UNPACK_8TO16 bw, 4, 2, 5
+    mova    m0, m1                      ; m0 = p0
+    VC1_LOOP_FILTER_A0 m7, m1, m4, m2
+    UNPACK_8TO16 bw, 1, 3, 5
+    mova    m5, m4
+    VC1_LOOP_FILTER_A0 m5, m2, m1, m3
+    SWAP 1, 4                           ; m1 = q0
+
+    VC1_FILTER %1
+    punpcklbw m0, m1
+%if %0 > 1
+    STORE_4_WORDS_MMX [r0-1], [r0+r1-1], [r0+2*r1-1], [r0+r3-1], m0, %2
+%if %1 > 4
+    psrldq m0, 4
+    STORE_4_WORDS_MMX [r4-1], [r4+r1-1], [r4+2*r1-1], [r4+r3-1], m0, %2
+%endif
+%else
+    STORE_4_WORDS_SSE4 [r0-1], [r0+r1-1], [r0+2*r1-1], [r0+r3-1], m0, 0
+    STORE_4_WORDS_SSE4 [r4-1], [r4+r1-1], [r4+2*r1-1], [r4+r3-1], m0, 4
+%endif
+%endmacro
+
+
+%macro START_V_FILTER 0
+    mov  r4, r0
+    lea  r3, [4*r1]
+    sub  r4, r3
+    lea  r3, [r1+2*r1]
+    imul r2, 0x01010101
+%endmacro
+
+%macro START_H_FILTER 1
+    lea  r3, [r1+2*r1]
+%if %1 > 4
+    lea  r4, [r0+4*r1]
+%endif
+    imul r2, 0x01010101
+%endmacro
+
+; I dont know why the sign extension is needed...
+%macro PSIGNW_SRA_MMX 2
+    psraw %2, 15
+    PSIGNW_MMX %1, %2
+%endmacro
+
+
+%macro VC1_LF_MMX 1
+INIT_MMX
+cglobal vc1_v_loop_filter_internal_%1
+    VC1_V_LOOP_FILTER 4, d
+    ret
+
+cglobal vc1_h_loop_filter_internal_%1
+    VC1_H_LOOP_FILTER 4, r4
+    ret
+
+; void ff_vc1_v_loop_filter4_mmx2(uint8_t *src, int stride, int pq)
+cglobal vc1_v_loop_filter4_%1, 3,5,0
+    START_V_FILTER
+    call vc1_v_loop_filter_internal_%1
+    RET
+
+; void ff_vc1_h_loop_filter4_mmx2(uint8_t *src, int stride, int pq)
+cglobal vc1_h_loop_filter4_%1, 3,5,0
+    START_H_FILTER 4
+    call vc1_h_loop_filter_internal_%1
+    RET
+
+; void ff_vc1_v_loop_filter8_mmx2(uint8_t *src, int stride, int pq)
+cglobal vc1_v_loop_filter8_%1, 3,5,0
+    START_V_FILTER
+    call vc1_v_loop_filter_internal_%1
+    add  r4, 4
+    add  r0, 4
+    call vc1_v_loop_filter_internal_%1
+    RET
+
+; void ff_vc1_h_loop_filter8_mmx2(uint8_t *src, int stride, int pq)
+cglobal vc1_h_loop_filter8_%1, 3,5,0
+    START_H_FILTER 4
+    call vc1_h_loop_filter_internal_%1
+    lea  r0, [r0+4*r1]
+    call vc1_h_loop_filter_internal_%1
+    RET
+%endmacro
+
+%define PABSW PABSW_MMX
+%define PSIGNW PSIGNW_SRA_MMX
+VC1_LF_MMX mmx
+
+%define PABSW PABSW_MMX2
+VC1_LF_MMX mmx2
+
+INIT_XMM
+; void ff_vc1_v_loop_filter8_sse2(uint8_t *src, int stride, int pq)
+cglobal vc1_v_loop_filter8_sse2, 3,5,8
+    START_V_FILTER
+    VC1_V_LOOP_FILTER 8, q
+    RET
+
+; void ff_vc1_h_loop_filter8_sse2(uint8_t *src, int stride, int pq)
+cglobal vc1_h_loop_filter8_sse2, 3,6,8
+    START_H_FILTER 8
+    VC1_H_LOOP_FILTER 8, r5
+    RET
+
+%define PABSW PABSW_SSSE3
+%define PSIGNW PSIGNW_SSSE3
+
+INIT_MMX
+; void ff_vc1_v_loop_filter4_ssse3(uint8_t *src, int stride, int pq)
+cglobal vc1_v_loop_filter4_ssse3, 3,5,0
+    START_V_FILTER
+    VC1_V_LOOP_FILTER 4, d
+    RET
+
+; void ff_vc1_h_loop_filter4_ssse3(uint8_t *src, int stride, int pq)
+cglobal vc1_h_loop_filter4_ssse3, 3,5,0
+    START_H_FILTER 4
+    VC1_H_LOOP_FILTER 4, r4
+    RET
+
+INIT_XMM
+; void ff_vc1_v_loop_filter8_ssse3(uint8_t *src, int stride, int pq)
+cglobal vc1_v_loop_filter8_ssse3, 3,5,8
+    START_V_FILTER
+    VC1_V_LOOP_FILTER 8, q
+    RET
+
+; void ff_vc1_h_loop_filter8_ssse3(uint8_t *src, int stride, int pq)
+cglobal vc1_h_loop_filter8_ssse3, 3,6,8
+    START_H_FILTER 8
+    VC1_H_LOOP_FILTER 8, r5
+    RET
+
+; void ff_vc1_h_loop_filter8_sse4(uint8_t *src, int stride, int pq)
+cglobal vc1_h_loop_filter8_sse4, 3,5,8
+    START_H_FILTER 8
+    VC1_H_LOOP_FILTER 8
+    RET
diff --git a/libavcodec/x86/vp3dsp.asm b/libavcodec/x86/vp3dsp.asm
new file mode 100644
index 0000000..0fe65de
--- /dev/null
+++ b/libavcodec/x86/vp3dsp.asm
@@ -0,0 +1,618 @@
+;******************************************************************************
+;* MMX/SSE2-optimized functions for the VP3 decoder
+;* Copyright (c) 2007 Aurelien Jacobs <aurel at gnuage.org>
+;*
+;* This file is part of Libav.
+;*
+;* Libav is free software; you can redistribute it and/or
+;* modify it under the terms of the GNU Lesser General Public
+;* License as published by the Free Software Foundation; either
+;* version 2.1 of the License, or (at your option) any later version.
+;*
+;* Libav is distributed in the hope that it will be useful,
+;* but WITHOUT ANY WARRANTY; without even the implied warranty of
+;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+;* Lesser General Public License for more details.
+;*
+;* You should have received a copy of the GNU Lesser General Public
+;* License along with Libav; if not, write to the Free Software
+;* 51, Inc., Foundation Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+;******************************************************************************
+
+%include "x86inc.asm"
+%include "x86util.asm"
+
+; MMX-optimized functions cribbed from the original VP3 source code.
+
+SECTION_RODATA
+
+vp3_idct_data: times 8 dw 64277
+               times 8 dw 60547
+               times 8 dw 54491
+               times 8 dw 46341
+               times 8 dw 36410
+               times 8 dw 25080
+               times 8 dw 12785
+
+cextern pb_1
+cextern pb_3
+cextern pb_7
+cextern pb_1F
+cextern pb_81
+
+cextern pw_8
+
+cextern put_signed_pixels_clamped_mmx
+cextern add_pixels_clamped_mmx
+
+SECTION .text
+
+; this is off by one or two for some cases when filter_limit is greater than 63
+; in:  p0 in mm6, p1 in mm4, p2 in mm2, p3 in mm1
+; out: p1 in mm4, p2 in mm3
+%macro VP3_LOOP_FILTER 0
+    movq          m7, m6
+    pand          m6, [pb_7]    ; p0&7
+    psrlw         m7, 3
+    pand          m7, [pb_1F]   ; p0>>3
+    movq          m3, m2        ; p2
+    pxor          m2, m4
+    pand          m2, [pb_1]    ; (p2^p1)&1
+    movq          m5, m2
+    paddb         m2, m2
+    paddb         m2, m5        ; 3*(p2^p1)&1
+    paddb         m2, m6        ; extra bits lost in shifts
+    pcmpeqb       m0, m0
+    pxor          m1, m0        ; 255 - p3
+    pavgb         m1, m2        ; (256 - p3 + extrabits) >> 1
+    pxor          m0, m4        ; 255 - p1
+    pavgb         m0, m3        ; (256 + p2-p1) >> 1
+    paddb         m1, [pb_3]
+    pavgb         m1, m0        ; 128+2+(   p2-p1  - p3) >> 2
+    pavgb         m1, m0        ; 128+1+(3*(p2-p1) - p3) >> 3
+    paddusb       m7, m1        ; d+128+1
+    movq          m6, [pb_81]
+    psubusb       m6, m7
+    psubusb       m7, [pb_81]
+
+    movq          m5, [r2+516]  ; flim
+    pminub        m6, m5
+    pminub        m7, m5
+    movq          m0, m6
+    movq          m1, m7
+    paddb         m6, m6
+    paddb         m7, m7
+    pminub        m6, m5
+    pminub        m7, m5
+    psubb         m6, m0
+    psubb         m7, m1
+    paddusb       m4, m7
+    psubusb       m4, m6
+    psubusb       m3, m7
+    paddusb       m3, m6
+%endmacro
+
+%macro STORE_4_WORDS 1
+    movd         r2d, %1
+    mov  [r0     -1], r2w
+    psrlq         %1, 32
+    shr           r2, 16
+    mov  [r0+r1  -1], r2w
+    movd         r2d, %1
+    mov  [r0+r1*2-1], r2w
+    shr           r2, 16
+    mov  [r0+r3  -1], r2w
+%endmacro
+
+INIT_MMX
+cglobal vp3_v_loop_filter_mmx2, 3, 4
+%ifdef ARCH_X86_64
+    movsxd        r1, r1d
+%endif
+    mov           r3, r1
+    neg           r1
+    movq          m6, [r0+r1*2]
+    movq          m4, [r0+r1  ]
+    movq          m2, [r0     ]
+    movq          m1, [r0+r3  ]
+
+    VP3_LOOP_FILTER
+
+    movq     [r0+r1], m4
+    movq     [r0   ], m3
+    RET
+
+cglobal vp3_h_loop_filter_mmx2, 3, 4
+%ifdef ARCH_X86_64
+    movsxd        r1, r1d
+%endif
+    lea           r3, [r1*3]
+
+    movd          m6, [r0     -2]
+    movd          m4, [r0+r1  -2]
+    movd          m2, [r0+r1*2-2]
+    movd          m1, [r0+r3  -2]
+    lea           r0, [r0+r1*4  ]
+    punpcklbw     m6, [r0     -2]
+    punpcklbw     m4, [r0+r1  -2]
+    punpcklbw     m2, [r0+r1*2-2]
+    punpcklbw     m1, [r0+r3  -2]
+    sub           r0, r3
+    sub           r0, r1
+
+    TRANSPOSE4x4B  6, 4, 2, 1, 0
+    VP3_LOOP_FILTER
+    SBUTTERFLY    bw, 4, 3, 5
+
+    STORE_4_WORDS m4
+    lea           r0, [r0+r1*4  ]
+    STORE_4_WORDS m3
+    RET
+
+; from original comments: The Macro does IDct on 4 1-D Dcts
+%macro BeginIDCT 0
+    movq          m2, I(3)
+    movq          m6, C(3)
+    movq          m4, m2
+    movq          m7, J(5)
+    pmulhw        m4, m6        ; r4 = c3*i3 - i3
+    movq          m1, C(5)
+    pmulhw        m6, m7        ; r6 = c3*i5 - i5
+    movq          m5, m1
+    pmulhw        m1, m2        ; r1 = c5*i3 - i3
+    movq          m3, I(1)
+    pmulhw        m5, m7        ; r5 = c5*i5 - i5
+    movq          m0, C(1)
+    paddw         m4, m2        ; r4 = c3*i3
+    paddw         m6, m7        ; r6 = c3*i5
+    paddw         m2, m1        ; r2 = c5*i3
+    movq          m1, J(7)
+    paddw         m7, m5        ; r7 = c5*i5
+    movq          m5, m0        ; r5 = c1
+    pmulhw        m0, m3        ; r0 = c1*i1 - i1
+    paddsw        m4, m7        ; r4 = C = c3*i3 + c5*i5
+    pmulhw        m5, m1        ; r5 = c1*i7 - i7
+    movq          m7, C(7)
+    psubsw        m6, m2        ; r6 = D = c3*i5 - c5*i3
+    paddw         m0, m3        ; r0 = c1*i1
+    pmulhw        m3, m7        ; r3 = c7*i1
+    movq          m2, I(2)
+    pmulhw        m7, m1        ; r7 = c7*i7
+    paddw         m5, m1        ; r5 = c1*i7
+    movq          m1, m2        ; r1 = i2
+    pmulhw        m2, C(2)      ; r2 = c2*i2 - i2
+    psubsw        m3, m5        ; r3 = B = c7*i1 - c1*i7
+    movq          m5, J(6)
+    paddsw        m0, m7        ; r0 = A = c1*i1 + c7*i7
+    movq          m7, m5        ; r7 = i6
+    psubsw        m0, m4        ; r0 = A - C
+    pmulhw        m5, C(2)      ; r5 = c2*i6 - i6
+    paddw         m2, m1        ; r2 = c2*i2
+    pmulhw        m1, C(6)      ; r1 = c6*i2
+    paddsw        m4, m4        ; r4 = C + C
+    paddsw        m4, m0        ; r4 = C. = A + C
+    psubsw        m3, m6        ; r3 = B - D
+    paddw         m5, m7        ; r5 = c2*i6
+    paddsw        m6, m6        ; r6 = D + D
+    pmulhw        m7, C(6)      ; r7 = c6*i6
+    paddsw        m6, m3        ; r6 = D. = B + D
+    movq        I(1), m4        ; save C. at I(1)
+    psubsw        m1, m5        ; r1 = H = c6*i2 - c2*i6
+    movq          m4, C(4)
+    movq          m5, m3        ; r5 = B - D
+    pmulhw        m3, m4        ; r3 = (c4 - 1) * (B - D)
+    paddsw        m7, m2        ; r3 = (c4 - 1) * (B - D)
+    movq        I(2), m6        ; save D. at I(2)
+    movq          m2, m0        ; r2 = A - C
+    movq          m6, I(0)
+    pmulhw        m0, m4        ; r0 = (c4 - 1) * (A - C)
+    paddw         m5, m3        ; r5 = B. = c4 * (B - D)
+    movq          m3, J(4)
+    psubsw        m5, m1        ; r5 = B.. = B. - H
+    paddw         m2, m0        ; r0 = A. = c4 * (A - C)
+    psubsw        m6, m3        ; r6 = i0 - i4
+    movq          m0, m6
+    pmulhw        m6, m4        ; r6 = (c4 - 1) * (i0 - i4)
+    paddsw        m3, m3        ; r3 = i4 + i4
+    paddsw        m1, m1        ; r1 = H + H
+    paddsw        m3, m0        ; r3 = i0 + i4
+    paddsw        m1, m5        ; r1 = H. = B + H
+    pmulhw        m4, m3        ; r4 = (c4 - 1) * (i0 + i4)
+    paddsw        m6, m0        ; r6 = F = c4 * (i0 - i4)
+    psubsw        m6, m2        ; r6 = F. = F - A.
+    paddsw        m2, m2        ; r2 = A. + A.
+    movq          m0, I(1)      ; r0 = C.
+    paddsw        m2, m6        ; r2 = A.. = F + A.
+    paddw         m4, m3        ; r4 = E = c4 * (i0 + i4)
+    psubsw        m2, m1        ; r2 = R2 = A.. - H.
+%endmacro
+
+; RowIDCT gets ready to transpose
+%macro RowIDCT 0
+    BeginIDCT
+    movq          m3, I(2)      ; r3 = D.
+    psubsw        m4, m7        ; r4 = E. = E - G
+    paddsw        m1, m1        ; r1 = H. + H.
+    paddsw        m7, m7        ; r7 = G + G
+    paddsw        m1, m2        ; r1 = R1 = A.. + H.
+    paddsw        m7, m4        ; r1 = R1 = A.. + H.
+    psubsw        m4, m3        ; r4 = R4 = E. - D.
+    paddsw        m3, m3
+    psubsw        m6, m5        ; r6 = R6 = F. - B..
+    paddsw        m5, m5
+    paddsw        m3, m4        ; r3 = R3 = E. + D.
+    paddsw        m5, m6        ; r5 = R5 = F. + B..
+    psubsw        m7, m0        ; r7 = R7 = G. - C.
+    paddsw        m0, m0
+    movq        I(1), m1        ; save R1
+    paddsw        m0, m7        ; r0 = R0 = G. + C.
+%endmacro
+
+; Column IDCT normalizes and stores final results
+%macro ColumnIDCT 0
+    BeginIDCT
+    paddsw        m2, OC_8      ; adjust R2 (and R1) for shift
+    paddsw        m1, m1        ; r1 = H. + H.
+    paddsw        m1, m2        ; r1 = R1 = A.. + H.
+    psraw         m2, 4         ; r2 = NR2
+    psubsw        m4, m7        ; r4 = E. = E - G
+    psraw         m1, 4         ; r1 = NR2
+    movq          m3, I(2)      ; r3 = D.
+    paddsw        m7, m7        ; r7 = G + G
+    movq        I(2), m2        ; store NR2 at I2
+    paddsw        m7, m4        ; r7 = G. = E + G
+    movq        I(1), m1        ; store NR1 at I1
+    psubsw        m4, m3        ; r4 = R4 = E. - D.
+    paddsw        m4, OC_8      ; adjust R4 (and R3) for shift
+    paddsw        m3, m3        ; r3 = D. + D.
+    paddsw        m3, m4        ; r3 = R3 = E. + D.
+    psraw         m4, 4         ; r4 = NR4
+    psubsw        m6, m5        ; r6 = R6 = F. - B..
+    psraw         m3, 4         ; r3 = NR3
+    paddsw        m6, OC_8      ; adjust R6 (and R5) for shift
+    paddsw        m5, m5        ; r5 = B.. + B..
+    paddsw        m5, m6        ; r5 = R5 = F. + B..
+    psraw         m6, 4         ; r6 = NR6
+    movq        J(4), m4        ; store NR4 at J4
+    psraw         m5, 4         ; r5 = NR5
+    movq        I(3), m3        ; store NR3 at I3
+    psubsw        m7, m0        ; r7 = R7 = G. - C.
+    paddsw        m7, OC_8      ; adjust R7 (and R0) for shift
+    paddsw        m0, m0        ; r0 = C. + C.
+    paddsw        m0, m7        ; r0 = R0 = G. + C.
+    psraw         m7, 4         ; r7 = NR7
+    movq        J(6), m6        ; store NR6 at J6
+    psraw         m0, 4         ; r0 = NR0
+    movq        J(5), m5        ; store NR5 at J5
+    movq        J(7), m7        ; store NR7 at J7
+    movq        I(0), m0        ; store NR0 at I0
+%endmacro
+
+; Following macro does two 4x4 transposes in place.
+;
+; At entry (we assume):
+;
+;   r0 = a3 a2 a1 a0
+;   I(1) = b3 b2 b1 b0
+;   r2 = c3 c2 c1 c0
+;   r3 = d3 d2 d1 d0
+;
+;   r4 = e3 e2 e1 e0
+;   r5 = f3 f2 f1 f0
+;   r6 = g3 g2 g1 g0
+;   r7 = h3 h2 h1 h0
+;
+; At exit, we have:
+;
+;   I(0) = d0 c0 b0 a0
+;   I(1) = d1 c1 b1 a1
+;   I(2) = d2 c2 b2 a2
+;   I(3) = d3 c3 b3 a3
+;
+;   J(4) = h0 g0 f0 e0
+;   J(5) = h1 g1 f1 e1
+;   J(6) = h2 g2 f2 e2
+;   J(7) = h3 g3 f3 e3
+;
+;  I(0) I(1) I(2) I(3)  is the transpose of r0 I(1) r2 r3.
+;  J(4) J(5) J(6) J(7)  is the transpose of r4 r5 r6 r7.
+;
+;  Since r1 is free at entry, we calculate the Js first.
+%macro Transpose 0
+    movq          m1, m4        ; r1 = e3 e2 e1 e0
+    punpcklwd     m4, m5        ; r4 = f1 e1 f0 e0
+    movq        I(0), m0        ; save a3 a2 a1 a0
+    punpckhwd     m1, m5        ; r1 = f3 e3 f2 e2
+    movq          m0, m6        ; r0 = g3 g2 g1 g0
+    punpcklwd     m6, m7        ; r6 = h1 g1 h0 g0
+    movq          m5, m4        ; r5 = f1 e1 f0 e0
+    punpckldq     m4, m6        ; r4 = h0 g0 f0 e0 = R4
+    punpckhdq     m5, m6        ; r5 = h1 g1 f1 e1 = R5
+    movq          m6, m1        ; r6 = f3 e3 f2 e2
+    movq        J(4), m4
+    punpckhwd     m0, m7        ; r0 = h3 g3 h2 g2
+    movq        J(5), m5
+    punpckhdq     m6, m0        ; r6 = h3 g3 f3 e3 = R7
+    movq          m4, I(0)      ; r4 = a3 a2 a1 a0
+    punpckldq     m1, m0        ; r1 = h2 g2 f2 e2 = R6
+    movq          m5, I(1)      ; r5 = b3 b2 b1 b0
+    movq          m0, m4        ; r0 = a3 a2 a1 a0
+    movq        J(7), m6
+    punpcklwd     m0, m5        ; r0 = b1 a1 b0 a0
+    movq        J(6), m1
+    punpckhwd     m4, m5        ; r4 = b3 a3 b2 a2
+    movq          m5, m2        ; r5 = c3 c2 c1 c0
+    punpcklwd     m2, m3        ; r2 = d1 c1 d0 c0
+    movq          m1, m0        ; r1 = b1 a1 b0 a0
+    punpckldq     m0, m2        ; r0 = d0 c0 b0 a0 = R0
+    punpckhdq     m1, m2        ; r1 = d1 c1 b1 a1 = R1
+    movq          m2, m4        ; r2 = b3 a3 b2 a2
+    movq        I(0), m0
+    punpckhwd     m5, m3        ; r5 = d3 c3 d2 c2
+    movq        I(1), m1
+    punpckhdq     m4, m5        ; r4 = d3 c3 b3 a3 = R3
+    punpckldq     m2, m5        ; r2 = d2 c2 b2 a2 = R2
+    movq        I(3), m4
+    movq        I(2), m2
+%endmacro
+
+%macro VP3_IDCT_mmx 1
+    ; eax = quantized input
+    ; ebx = dequantizer matrix
+    ; ecx = IDCT constants
+    ;  M(I) = ecx + MaskOffset(0) + I * 8
+    ;  C(I) = ecx + CosineOffset(32) + (I-1) * 8
+    ; edx = output
+    ; r0..r7 = mm0..mm7
+%define OC_8 [pw_8]
+%define C(x) [vp3_idct_data+16*(x-1)]
+
+    ; at this point, function has completed dequantization + dezigzag +
+    ; partial transposition; now do the idct itself
+%define I(x) [%1+16* x     ]
+%define J(x) [%1+16*(x-4)+8]
+    RowIDCT
+    Transpose
+
+%define I(x) [%1+16* x   +64]
+%define J(x) [%1+16*(x-4)+72]
+    RowIDCT
+    Transpose
+
+%define I(x) [%1+16*x]
+%define J(x) [%1+16*x]
+    ColumnIDCT
+
+%define I(x) [%1+16*x+8]
+%define J(x) [%1+16*x+8]
+    ColumnIDCT
+%endmacro
+
+%macro VP3_1D_IDCT_SSE2 0
+    movdqa        m2, I(3)      ; xmm2 = i3
+    movdqa        m6, C(3)      ; xmm6 = c3
+    movdqa        m4, m2        ; xmm4 = i3
+    movdqa        m7, I(5)      ; xmm7 = i5
+    pmulhw        m4, m6        ; xmm4 = c3 * i3 - i3
+    movdqa        m1, C(5)      ; xmm1 = c5
+    pmulhw        m6, m7        ; xmm6 = c3 * i5 - i5
+    movdqa        m5, m1        ; xmm5 = c5
+    pmulhw        m1, m2        ; xmm1 = c5 * i3 - i3
+    movdqa        m3, I(1)      ; xmm3 = i1
+    pmulhw        m5, m7        ; xmm5 = c5 * i5 - i5
+    movdqa        m0, C(1)      ; xmm0 = c1
+    paddw         m4, m2        ; xmm4 = c3 * i3
+    paddw         m6, m7        ; xmm6 = c3 * i5
+    paddw         m2, m1        ; xmm2 = c5 * i3
+    movdqa        m1, I(7)      ; xmm1 = i7
+    paddw         m7, m5        ; xmm7 = c5 * i5
+    movdqa        m5, m0        ; xmm5 = c1
+    pmulhw        m0, m3        ; xmm0 = c1 * i1 - i1
+    paddsw        m4, m7        ; xmm4 = c3 * i3 + c5 * i5 = C
+    pmulhw        m5, m1        ; xmm5 = c1 * i7 - i7
+    movdqa        m7, C(7)      ; xmm7 = c7
+    psubsw        m6, m2        ; xmm6 = c3 * i5 - c5 * i3 = D
+    paddw         m0, m3        ; xmm0 = c1 * i1
+    pmulhw        m3, m7        ; xmm3 = c7 * i1
+    movdqa        m2, I(2)      ; xmm2 = i2
+    pmulhw        m7, m1        ; xmm7 = c7 * i7
+    paddw         m5, m1        ; xmm5 = c1 * i7
+    movdqa        m1, m2        ; xmm1 = i2
+    pmulhw        m2, C(2)      ; xmm2 = i2 * c2 -i2
+    psubsw        m3, m5        ; xmm3 = c7 * i1 - c1 * i7 = B
+    movdqa        m5, I(6)      ; xmm5 = i6
+    paddsw        m0, m7        ; xmm0 = c1 * i1 + c7 * i7 = A
+    movdqa        m7, m5        ; xmm7 = i6
+    psubsw        m0, m4        ; xmm0 = A - C
+    pmulhw        m5, C(2)      ; xmm5 = c2 * i6 - i6
+    paddw         m2, m1        ; xmm2 = i2 * c2
+    pmulhw        m1, C(6)      ; xmm1 = c6 * i2
+    paddsw        m4, m4        ; xmm4 = C + C
+    paddsw        m4, m0        ; xmm4 = A + C = C.
+    psubsw        m3, m6        ; xmm3 = B - D
+    paddw         m5, m7        ; xmm5 = c2 * i6
+    paddsw        m6, m6        ; xmm6 = D + D
+    pmulhw        m7, C(6)      ; xmm7 = c6 * i6
+    paddsw        m6, m3        ; xmm6 = B + D = D.
+    movdqa      I(1), m4        ; Save C. at I(1)
+    psubsw        m1, m5        ; xmm1 = c6 * i2 - c2 * i6 = H
+    movdqa        m4, C(4)      ; xmm4 = C4
+    movdqa        m5, m3        ; xmm5 = B - D
+    pmulhw        m3, m4        ; xmm3 = ( c4 -1 ) * ( B - D )
+    paddsw        m7, m2        ; xmm7 = c2 * i2 + c6 * i6 = G
+    movdqa      I(2), m6        ; save D. at I(2)
+    movdqa        m2, m0        ; xmm2 = A - C
+    movdqa        m6, I(0)      ; xmm6 = i0
+    pmulhw        m0, m4        ; xmm0 = ( c4 - 1 ) * ( A - C ) = A.
+    paddw         m5, m3        ; xmm5 = c4 * ( B - D ) = B.
+    movdqa        m3, I(4)      ; xmm3 = i4
+    psubsw        m5, m1        ; xmm5 = B. - H = B..
+    paddw         m2, m0        ; xmm2 = c4 * ( A - C) = A.
+    psubsw        m6, m3        ; xmm6 = i0 - i4
+    movdqa        m0, m6        ; xmm0 = i0 - i4
+    pmulhw        m6, m4        ; xmm6 = (c4 - 1) * (i0 - i4) = F
+    paddsw        m3, m3        ; xmm3 = i4 + i4
+    paddsw        m1, m1        ; xmm1 = H + H
+    paddsw        m3, m0        ; xmm3 = i0 + i4
+    paddsw        m1, m5        ; xmm1 = B. + H = H.
+    pmulhw        m4, m3        ; xmm4 = ( c4 - 1 ) * ( i0 + i4 )
+    paddw         m6, m0        ; xmm6 = c4 * ( i0 - i4 )
+    psubsw        m6, m2        ; xmm6 = F - A. = F.
+    paddsw        m2, m2        ; xmm2 = A. + A.
+    movdqa        m0, I(1)      ; Load        C. from I(1)
+    paddsw        m2, m6        ; xmm2 = F + A. = A..
+    paddw         m4, m3        ; xmm4 = c4 * ( i0 + i4 ) = 3
+    psubsw        m2, m1        ; xmm2 = A.. - H. = R2
+    ADD(m2)                     ; Adjust R2 and R1 before shifting
+    paddsw        m1, m1        ; xmm1 = H. + H.
+    paddsw        m1, m2        ; xmm1 = A.. + H. = R1
+    SHIFT(m2)                   ; xmm2 = op2
+    psubsw        m4, m7        ; xmm4 = E - G = E.
+    SHIFT(m1)                   ; xmm1 = op1
+    movdqa        m3, I(2)      ; Load D. from I(2)
+    paddsw        m7, m7        ; xmm7 = G + G
+    paddsw        m7, m4        ; xmm7 = E + G = G.
+    psubsw        m4, m3        ; xmm4 = E. - D. = R4
+    ADD(m4)                     ; Adjust R4 and R3 before shifting
+    paddsw        m3, m3        ; xmm3 = D. + D.
+    paddsw        m3, m4        ; xmm3 = E. + D. = R3
+    SHIFT(m4)                   ; xmm4 = op4
+    psubsw        m6, m5        ; xmm6 = F. - B..= R6
+    SHIFT(m3)                   ; xmm3 = op3
+    ADD(m6)                     ; Adjust R6 and R5 before shifting
+    paddsw        m5, m5        ; xmm5 = B.. + B..
+    paddsw        m5, m6        ; xmm5 = F. + B.. = R5
+    SHIFT(m6)                   ; xmm6 = op6
+    SHIFT(m5)                   ; xmm5 = op5
+    psubsw        m7, m0        ; xmm7 = G. - C. = R7
+    ADD(m7)                     ; Adjust R7 and R0 before shifting
+    paddsw        m0, m0        ; xmm0 = C. + C.
+    paddsw        m0, m7        ; xmm0 = G. + C.
+    SHIFT(m7)                   ; xmm7 = op7
+    SHIFT(m0)                   ; xmm0 = op0
+%endmacro
+
+%macro PUT_BLOCK 8
+    movdqa      O(0), m%1
+    movdqa      O(1), m%2
+    movdqa      O(2), m%3
+    movdqa      O(3), m%4
+    movdqa      O(4), m%5
+    movdqa      O(5), m%6
+    movdqa      O(6), m%7
+    movdqa      O(7), m%8
+%endmacro
+
+%macro VP3_IDCT_sse2 1
+%define I(x) [%1+16*x]
+%define O(x) [%1+16*x]
+%define C(x) [vp3_idct_data+16*(x-1)]
+%define SHIFT(x)
+%define ADD(x)
+        VP3_1D_IDCT_SSE2
+%ifdef ARCH_X86_64
+        TRANSPOSE8x8W 0, 1, 2, 3, 4, 5, 6, 7, 8
+%else
+        TRANSPOSE8x8W 0, 1, 2, 3, 4, 5, 6, 7, [%1], [%1+16]
+%endif
+        PUT_BLOCK 0, 1, 2, 3, 4, 5, 6, 7
+
+%define SHIFT(x) psraw  x, 4
+%define ADD(x)   paddsw x, [pw_8]
+        VP3_1D_IDCT_SSE2
+        PUT_BLOCK 0, 1, 2, 3, 4, 5, 6, 7
+%endmacro
+
+%macro vp3_idct_funcs 3
+cglobal vp3_idct_%1, 1, 1, %2
+    VP3_IDCT_%1   r0
+    RET
+
+cglobal vp3_idct_put_%1, 3, %3, %2
+    VP3_IDCT_%1   r2
+%ifdef ARCH_X86_64
+    mov           r3, r2
+    mov           r2, r1
+    mov           r1, r0
+    mov           r0, r3
+%else
+    mov          r0m, r2
+    mov          r1m, r0
+    mov          r2m, r1
+%endif
+%ifdef WIN64
+    call put_signed_pixels_clamped_mmx
+    RET
+%else
+    jmp put_signed_pixels_clamped_mmx
+%endif
+
+cglobal vp3_idct_add_%1, 3, %3, %2
+    VP3_IDCT_%1   r2
+%ifdef ARCH_X86_64
+    mov           r3, r2
+    mov           r2, r1
+    mov           r1, r0
+    mov           r0, r3
+%else
+    mov          r0m, r2
+    mov          r1m, r0
+    mov          r2m, r1
+%endif
+%ifdef WIN64
+    call add_pixels_clamped_mmx
+    RET
+%else
+    jmp add_pixels_clamped_mmx
+%endif
+%endmacro
+
+%ifdef ARCH_X86_64
+%define REGS 4
+%else
+%define REGS 3
+%endif
+INIT_MMX
+vp3_idct_funcs mmx,  0, REGS
+INIT_XMM
+vp3_idct_funcs sse2, 9, REGS
+%undef REGS
+
+%macro DC_ADD 0
+    movq          m2, [r0     ]
+    movq          m3, [r0+r1  ]
+    paddusb       m2, m0
+    movq          m4, [r0+r1*2]
+    paddusb       m3, m0
+    movq          m5, [r0+r3  ]
+    paddusb       m4, m0
+    paddusb       m5, m0
+    psubusb       m2, m1
+    psubusb       m3, m1
+    movq   [r0     ], m2
+    psubusb       m4, m1
+    movq   [r0+r1  ], m3
+    psubusb       m5, m1
+    movq   [r0+r1*2], m4
+    movq   [r0+r3  ], m5
+%endmacro
+
+INIT_MMX
+cglobal vp3_idct_dc_add_mmx2, 3, 4
+%ifdef ARCH_X86_64
+    movsxd        r1, r1d
+%endif
+    lea           r3, [r1*3]
+    movsx         r2, word [r2]
+    add           r2, 15
+    sar           r2, 5
+    movd          m0, r2d
+    pshufw        m0, m0, 0x0
+    pxor          m1, m1
+    psubw         m1, m0
+    packuswb      m0, m0
+    packuswb      m1, m1
+    DC_ADD
+    lea           r0, [r0+r1*4]
+    DC_ADD
+    RET
diff --git a/libavcodec/x86/vp3dsp_mmx.c b/libavcodec/x86/vp3dsp_mmx.c
deleted file mode 100644
index 44a8477..0000000
--- a/libavcodec/x86/vp3dsp_mmx.c
+++ /dev/null
@@ -1,438 +0,0 @@
-/*
- * Copyright (C) 2004 the ffmpeg project
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-/**
- * @file
- * MMX-optimized functions cribbed from the original VP3 source code.
- */
-
-#include "libavutil/x86_cpu.h"
-#include "libavcodec/dsputil.h"
-#include "dsputil_mmx.h"
-#include "vp3dsp_mmx.h"
-
-extern const uint16_t ff_vp3_idct_data[];
-
-// this is off by one or two for some cases when filter_limit is greater than 63
-// in:  p0 in mm6, p1 in mm4, p2 in mm2, p3 in mm1
-// out: p1 in mm4, p2 in mm3
-#define VP3_LOOP_FILTER(flim) \
-    "movq       %%mm6, %%mm7 \n\t" \
-    "pand    "MANGLE(ff_pb_7 )", %%mm6 \n\t" /* p0&7 */ \
-    "psrlw         $3, %%mm7 \n\t" \
-    "pand    "MANGLE(ff_pb_1F)", %%mm7 \n\t" /* p0>>3 */ \
-    "movq       %%mm2, %%mm3 \n\t" /* mm3 = p2 */ \
-    "pxor       %%mm4, %%mm2 \n\t" \
-    "pand    "MANGLE(ff_pb_1 )", %%mm2 \n\t" /* (p2^p1)&1 */ \
-    "movq       %%mm2, %%mm5 \n\t" \
-    "paddb      %%mm2, %%mm2 \n\t" \
-    "paddb      %%mm5, %%mm2 \n\t" /* 3*(p2^p1)&1 */ \
-    "paddb      %%mm6, %%mm2 \n\t" /* extra bits lost in shifts */ \
-    "pcmpeqb    %%mm0, %%mm0 \n\t" \
-    "pxor       %%mm0, %%mm1 \n\t" /* 255 - p3 */ \
-    "pavgb      %%mm2, %%mm1 \n\t" /* (256 - p3 + extrabits) >> 1 */ \
-    "pxor       %%mm4, %%mm0 \n\t" /* 255 - p1 */ \
-    "pavgb      %%mm3, %%mm0 \n\t" /* (256 + p2-p1) >> 1 */ \
-    "paddb   "MANGLE(ff_pb_3 )", %%mm1 \n\t" \
-    "pavgb      %%mm0, %%mm1 \n\t" /* 128+2+(   p2-p1  - p3) >> 2 */ \
-    "pavgb      %%mm0, %%mm1 \n\t" /* 128+1+(3*(p2-p1) - p3) >> 3 */ \
-    "paddusb    %%mm1, %%mm7 \n\t" /* d+128+1 */ \
-    "movq    "MANGLE(ff_pb_81)", %%mm6 \n\t" \
-    "psubusb    %%mm7, %%mm6 \n\t" \
-    "psubusb "MANGLE(ff_pb_81)", %%mm7 \n\t" \
-\
-    "movq     "#flim", %%mm5 \n\t" \
-    "pminub     %%mm5, %%mm6 \n\t" \
-    "pminub     %%mm5, %%mm7 \n\t" \
-    "movq       %%mm6, %%mm0 \n\t" \
-    "movq       %%mm7, %%mm1 \n\t" \
-    "paddb      %%mm6, %%mm6 \n\t" \
-    "paddb      %%mm7, %%mm7 \n\t" \
-    "pminub     %%mm5, %%mm6 \n\t" \
-    "pminub     %%mm5, %%mm7 \n\t" \
-    "psubb      %%mm0, %%mm6 \n\t" \
-    "psubb      %%mm1, %%mm7 \n\t" \
-    "paddusb    %%mm7, %%mm4 \n\t" \
-    "psubusb    %%mm6, %%mm4 \n\t" \
-    "psubusb    %%mm7, %%mm3 \n\t" \
-    "paddusb    %%mm6, %%mm3 \n\t"
-
-#define STORE_4_WORDS(dst0, dst1, dst2, dst3, mm) \
-    "movd "#mm", %0        \n\t" \
-    "movw   %w0, -1"#dst0" \n\t" \
-    "psrlq  $32, "#mm"     \n\t" \
-    "shr    $16, %0        \n\t" \
-    "movw   %w0, -1"#dst1" \n\t" \
-    "movd "#mm", %0        \n\t" \
-    "movw   %w0, -1"#dst2" \n\t" \
-    "shr    $16, %0        \n\t" \
-    "movw   %w0, -1"#dst3" \n\t"
-
-void ff_vp3_v_loop_filter_mmx2(uint8_t *src, int stride, int *bounding_values)
-{
-    __asm__ volatile(
-        "movq          %0, %%mm6 \n\t"
-        "movq          %1, %%mm4 \n\t"
-        "movq          %2, %%mm2 \n\t"
-        "movq          %3, %%mm1 \n\t"
-
-        VP3_LOOP_FILTER(%4)
-
-        "movq       %%mm4, %1    \n\t"
-        "movq       %%mm3, %2    \n\t"
-
-        : "+m" (*(uint64_t*)(src - 2*stride)),
-          "+m" (*(uint64_t*)(src - 1*stride)),
-          "+m" (*(uint64_t*)(src + 0*stride)),
-          "+m" (*(uint64_t*)(src + 1*stride))
-        : "m"(*(uint64_t*)(bounding_values+129))
-    );
-}
-
-void ff_vp3_h_loop_filter_mmx2(uint8_t *src, int stride, int *bounding_values)
-{
-    x86_reg tmp;
-
-    __asm__ volatile(
-        "movd -2(%1),      %%mm6 \n\t"
-        "movd -2(%1,%3),   %%mm0 \n\t"
-        "movd -2(%1,%3,2), %%mm1 \n\t"
-        "movd -2(%1,%4),   %%mm4 \n\t"
-
-        TRANSPOSE8x4(%%mm6, %%mm0, %%mm1, %%mm4, -2(%2), -2(%2,%3), -2(%2,%3,2), -2(%2,%4), %%mm2)
-        VP3_LOOP_FILTER(%5)
-        SBUTTERFLY(%%mm4, %%mm3, %%mm5, bw, q)
-
-        STORE_4_WORDS((%1), (%1,%3), (%1,%3,2), (%1,%4), %%mm4)
-        STORE_4_WORDS((%2), (%2,%3), (%2,%3,2), (%2,%4), %%mm5)
-
-        : "=&r"(tmp)
-        : "r"(src), "r"(src+4*stride), "r"((x86_reg)stride), "r"((x86_reg)3*stride),
-          "m"(*(uint64_t*)(bounding_values+129))
-        : "memory"
-    );
-}
-
-/* from original comments: The Macro does IDct on 4 1-D Dcts */
-#define BeginIDCT() \
-    "movq   "I(3)", %%mm2 \n\t" \
-    "movq   "C(3)", %%mm6 \n\t" \
-    "movq    %%mm2, %%mm4 \n\t" \
-    "movq   "J(5)", %%mm7 \n\t" \
-    "pmulhw  %%mm6, %%mm4 \n\t"    /* r4 = c3*i3 - i3 */ \
-    "movq   "C(5)", %%mm1 \n\t" \
-    "pmulhw  %%mm7, %%mm6 \n\t"    /* r6 = c3*i5 - i5 */ \
-    "movq    %%mm1, %%mm5 \n\t" \
-    "pmulhw  %%mm2, %%mm1 \n\t"    /* r1 = c5*i3 - i3 */ \
-    "movq   "I(1)", %%mm3 \n\t" \
-    "pmulhw  %%mm7, %%mm5 \n\t"    /* r5 = c5*i5 - i5 */ \
-    "movq   "C(1)", %%mm0 \n\t" \
-    "paddw   %%mm2, %%mm4 \n\t"    /* r4 = c3*i3 */ \
-    "paddw   %%mm7, %%mm6 \n\t"    /* r6 = c3*i5 */ \
-    "paddw   %%mm1, %%mm2 \n\t"    /* r2 = c5*i3 */ \
-    "movq   "J(7)", %%mm1 \n\t" \
-    "paddw   %%mm5, %%mm7 \n\t"    /* r7 = c5*i5 */ \
-    "movq    %%mm0, %%mm5 \n\t"    /* r5 = c1 */ \
-    "pmulhw  %%mm3, %%mm0 \n\t"    /* r0 = c1*i1 - i1 */ \
-    "paddsw  %%mm7, %%mm4 \n\t"    /* r4 = C = c3*i3 + c5*i5 */ \
-    "pmulhw  %%mm1, %%mm5 \n\t"    /* r5 = c1*i7 - i7 */ \
-    "movq   "C(7)", %%mm7 \n\t" \
-    "psubsw  %%mm2, %%mm6 \n\t"    /* r6 = D = c3*i5 - c5*i3 */ \
-    "paddw   %%mm3, %%mm0 \n\t"    /* r0 = c1*i1 */ \
-    "pmulhw  %%mm7, %%mm3 \n\t"    /* r3 = c7*i1 */ \
-    "movq   "I(2)", %%mm2 \n\t" \
-    "pmulhw  %%mm1, %%mm7 \n\t"    /* r7 = c7*i7 */ \
-    "paddw   %%mm1, %%mm5 \n\t"    /* r5 = c1*i7 */ \
-    "movq    %%mm2, %%mm1 \n\t"    /* r1 = i2 */ \
-    "pmulhw "C(2)", %%mm2 \n\t"    /* r2 = c2*i2 - i2 */ \
-    "psubsw  %%mm5, %%mm3 \n\t"    /* r3 = B = c7*i1 - c1*i7 */ \
-    "movq   "J(6)", %%mm5 \n\t" \
-    "paddsw  %%mm7, %%mm0 \n\t"    /* r0 = A = c1*i1 + c7*i7 */ \
-    "movq    %%mm5, %%mm7 \n\t"    /* r7 = i6 */ \
-    "psubsw  %%mm4, %%mm0 \n\t"    /* r0 = A - C */ \
-    "pmulhw "C(2)", %%mm5 \n\t"    /* r5 = c2*i6 - i6 */ \
-    "paddw   %%mm1, %%mm2 \n\t"    /* r2 = c2*i2 */ \
-    "pmulhw "C(6)", %%mm1 \n\t"    /* r1 = c6*i2 */ \
-    "paddsw  %%mm4, %%mm4 \n\t"    /* r4 = C + C */ \
-    "paddsw  %%mm0, %%mm4 \n\t"    /* r4 = C. = A + C */ \
-    "psubsw  %%mm6, %%mm3 \n\t"    /* r3 = B - D */ \
-    "paddw   %%mm7, %%mm5 \n\t"    /* r5 = c2*i6 */ \
-    "paddsw  %%mm6, %%mm6 \n\t"    /* r6 = D + D */ \
-    "pmulhw "C(6)", %%mm7 \n\t"    /* r7 = c6*i6 */ \
-    "paddsw  %%mm3, %%mm6 \n\t"    /* r6 = D. = B + D */ \
-    "movq    %%mm4, "I(1)"\n\t"    /* save C. at I(1) */ \
-    "psubsw  %%mm5, %%mm1 \n\t"    /* r1 = H = c6*i2 - c2*i6 */ \
-    "movq   "C(4)", %%mm4 \n\t" \
-    "movq    %%mm3, %%mm5 \n\t"    /* r5 = B - D */ \
-    "pmulhw  %%mm4, %%mm3 \n\t"    /* r3 = (c4 - 1) * (B - D) */ \
-    "paddsw  %%mm2, %%mm7 \n\t"    /* r3 = (c4 - 1) * (B - D) */ \
-    "movq    %%mm6, "I(2)"\n\t"    /* save D. at I(2) */ \
-    "movq    %%mm0, %%mm2 \n\t"    /* r2 = A - C */ \
-    "movq   "I(0)", %%mm6 \n\t" \
-    "pmulhw  %%mm4, %%mm0 \n\t"    /* r0 = (c4 - 1) * (A - C) */ \
-    "paddw   %%mm3, %%mm5 \n\t"    /* r5 = B. = c4 * (B - D) */ \
-    "movq   "J(4)", %%mm3 \n\t" \
-    "psubsw  %%mm1, %%mm5 \n\t"    /* r5 = B.. = B. - H */ \
-    "paddw   %%mm0, %%mm2 \n\t"    /* r0 = A. = c4 * (A - C) */ \
-    "psubsw  %%mm3, %%mm6 \n\t"    /* r6 = i0 - i4 */ \
-    "movq    %%mm6, %%mm0 \n\t" \
-    "pmulhw  %%mm4, %%mm6 \n\t"    /* r6 = (c4 - 1) * (i0 - i4) */ \
-    "paddsw  %%mm3, %%mm3 \n\t"    /* r3 = i4 + i4 */ \
-    "paddsw  %%mm1, %%mm1 \n\t"    /* r1 = H + H */ \
-    "paddsw  %%mm0, %%mm3 \n\t"    /* r3 = i0 + i4 */ \
-    "paddsw  %%mm5, %%mm1 \n\t"    /* r1 = H. = B + H */ \
-    "pmulhw  %%mm3, %%mm4 \n\t"    /* r4 = (c4 - 1) * (i0 + i4) */ \
-    "paddsw  %%mm0, %%mm6 \n\t"    /* r6 = F = c4 * (i0 - i4) */ \
-    "psubsw  %%mm2, %%mm6 \n\t"    /* r6 = F. = F - A. */ \
-    "paddsw  %%mm2, %%mm2 \n\t"    /* r2 = A. + A. */ \
-    "movq   "I(1)", %%mm0 \n\t"    /* r0 = C. */ \
-    "paddsw  %%mm6, %%mm2 \n\t"    /* r2 = A.. = F + A. */ \
-    "paddw   %%mm3, %%mm4 \n\t"    /* r4 = E = c4 * (i0 + i4) */ \
-    "psubsw  %%mm1, %%mm2 \n\t"    /* r2 = R2 = A.. - H. */
-
-/* RowIDCT gets ready to transpose */
-#define RowIDCT() \
-    BeginIDCT() \
-    "movq   "I(2)", %%mm3 \n\t"    /* r3 = D. */ \
-    "psubsw  %%mm7, %%mm4 \n\t"    /* r4 = E. = E - G */ \
-    "paddsw  %%mm1, %%mm1 \n\t"    /* r1 = H. + H. */ \
-    "paddsw  %%mm7, %%mm7 \n\t"    /* r7 = G + G */ \
-    "paddsw  %%mm2, %%mm1 \n\t"    /* r1 = R1 = A.. + H. */ \
-    "paddsw  %%mm4, %%mm7 \n\t"    /* r1 = R1 = A.. + H. */ \
-    "psubsw  %%mm3, %%mm4 \n\t"    /* r4 = R4 = E. - D. */ \
-    "paddsw  %%mm3, %%mm3 \n\t" \
-    "psubsw  %%mm5, %%mm6 \n\t"    /* r6 = R6 = F. - B.. */ \
-    "paddsw  %%mm5, %%mm5 \n\t" \
-    "paddsw  %%mm4, %%mm3 \n\t"    /* r3 = R3 = E. + D. */ \
-    "paddsw  %%mm6, %%mm5 \n\t"    /* r5 = R5 = F. + B.. */ \
-    "psubsw  %%mm0, %%mm7 \n\t"    /* r7 = R7 = G. - C. */ \
-    "paddsw  %%mm0, %%mm0 \n\t" \
-    "movq    %%mm1, "I(1)"\n\t"    /* save R1 */ \
-    "paddsw  %%mm7, %%mm0 \n\t"    /* r0 = R0 = G. + C. */
-
-/* Column IDCT normalizes and stores final results */
-#define ColumnIDCT() \
-    BeginIDCT() \
-    "paddsw "OC_8", %%mm2 \n\t"    /* adjust R2 (and R1) for shift */ \
-    "paddsw  %%mm1, %%mm1 \n\t"    /* r1 = H. + H. */ \
-    "paddsw  %%mm2, %%mm1 \n\t"    /* r1 = R1 = A.. + H. */ \
-    "psraw      $4, %%mm2 \n\t"    /* r2 = NR2 */ \
-    "psubsw  %%mm7, %%mm4 \n\t"    /* r4 = E. = E - G */ \
-    "psraw      $4, %%mm1 \n\t"    /* r1 = NR1 */ \
-    "movq   "I(2)", %%mm3 \n\t"    /* r3 = D. */ \
-    "paddsw  %%mm7, %%mm7 \n\t"    /* r7 = G + G */ \
-    "movq    %%mm2, "I(2)"\n\t"    /* store NR2 at I2 */ \
-    "paddsw  %%mm4, %%mm7 \n\t"    /* r7 = G. = E + G */ \
-    "movq    %%mm1, "I(1)"\n\t"    /* store NR1 at I1 */ \
-    "psubsw  %%mm3, %%mm4 \n\t"    /* r4 = R4 = E. - D. */ \
-    "paddsw "OC_8", %%mm4 \n\t"    /* adjust R4 (and R3) for shift */ \
-    "paddsw  %%mm3, %%mm3 \n\t"    /* r3 = D. + D. */ \
-    "paddsw  %%mm4, %%mm3 \n\t"    /* r3 = R3 = E. + D. */ \
-    "psraw      $4, %%mm4 \n\t"    /* r4 = NR4 */ \
-    "psubsw  %%mm5, %%mm6 \n\t"    /* r6 = R6 = F. - B.. */ \
-    "psraw      $4, %%mm3 \n\t"    /* r3 = NR3 */ \
-    "paddsw "OC_8", %%mm6 \n\t"    /* adjust R6 (and R5) for shift */ \
-    "paddsw  %%mm5, %%mm5 \n\t"    /* r5 = B.. + B.. */ \
-    "paddsw  %%mm6, %%mm5 \n\t"    /* r5 = R5 = F. + B.. */ \
-    "psraw      $4, %%mm6 \n\t"    /* r6 = NR6 */ \
-    "movq    %%mm4, "J(4)"\n\t"    /* store NR4 at J4 */ \
-    "psraw      $4, %%mm5 \n\t"    /* r5 = NR5 */ \
-    "movq    %%mm3, "I(3)"\n\t"    /* store NR3 at I3 */ \
-    "psubsw  %%mm0, %%mm7 \n\t"    /* r7 = R7 = G. - C. */ \
-    "paddsw "OC_8", %%mm7 \n\t"    /* adjust R7 (and R0) for shift */ \
-    "paddsw  %%mm0, %%mm0 \n\t"    /* r0 = C. + C. */ \
-    "paddsw  %%mm7, %%mm0 \n\t"    /* r0 = R0 = G. + C. */ \
-    "psraw      $4, %%mm7 \n\t"    /* r7 = NR7 */ \
-    "movq    %%mm6, "J(6)"\n\t"    /* store NR6 at J6 */ \
-    "psraw      $4, %%mm0 \n\t"    /* r0 = NR0 */ \
-    "movq    %%mm5, "J(5)"\n\t"    /* store NR5 at J5 */ \
-    "movq    %%mm7, "J(7)"\n\t"    /* store NR7 at J7 */ \
-    "movq    %%mm0, "I(0)"\n\t"    /* store NR0 at I0 */
-
-/* Following macro does two 4x4 transposes in place.
-
-  At entry (we assume):
-
-    r0 = a3 a2 a1 a0
-    I(1) = b3 b2 b1 b0
-    r2 = c3 c2 c1 c0
-    r3 = d3 d2 d1 d0
-
-    r4 = e3 e2 e1 e0
-    r5 = f3 f2 f1 f0
-    r6 = g3 g2 g1 g0
-    r7 = h3 h2 h1 h0
-
-  At exit, we have:
-
-    I(0) = d0 c0 b0 a0
-    I(1) = d1 c1 b1 a1
-    I(2) = d2 c2 b2 a2
-    I(3) = d3 c3 b3 a3
-
-    J(4) = h0 g0 f0 e0
-    J(5) = h1 g1 f1 e1
-    J(6) = h2 g2 f2 e2
-    J(7) = h3 g3 f3 e3
-
-   I(0) I(1) I(2) I(3)  is the transpose of r0 I(1) r2 r3.
-   J(4) J(5) J(6) J(7)  is the transpose of r4 r5 r6 r7.
-
-   Since r1 is free at entry, we calculate the Js first. */
-#define Transpose() \
-    "movq       %%mm4, %%mm1 \n\t"    /* r1 = e3 e2 e1 e0 */ \
-    "punpcklwd  %%mm5, %%mm4 \n\t"    /* r4 = f1 e1 f0 e0 */ \
-    "movq       %%mm0, "I(0)"\n\t"    /* save a3 a2 a1 a0 */ \
-    "punpckhwd  %%mm5, %%mm1 \n\t"    /* r1 = f3 e3 f2 e2 */ \
-    "movq       %%mm6, %%mm0 \n\t"    /* r0 = g3 g2 g1 g0 */ \
-    "punpcklwd  %%mm7, %%mm6 \n\t"    /* r6 = h1 g1 h0 g0 */ \
-    "movq       %%mm4, %%mm5 \n\t"    /* r5 = f1 e1 f0 e0 */ \
-    "punpckldq  %%mm6, %%mm4 \n\t"    /* r4 = h0 g0 f0 e0 = R4 */ \
-    "punpckhdq  %%mm6, %%mm5 \n\t"    /* r5 = h1 g1 f1 e1 = R5 */ \
-    "movq       %%mm1, %%mm6 \n\t"    /* r6 = f3 e3 f2 e2 */ \
-    "movq       %%mm4, "J(4)"\n\t" \
-    "punpckhwd  %%mm7, %%mm0 \n\t"    /* r0 = h3 g3 h2 g2 */ \
-    "movq       %%mm5, "J(5)"\n\t" \
-    "punpckhdq  %%mm0, %%mm6 \n\t"    /* r6 = h3 g3 f3 e3 = R7 */ \
-    "movq      "I(0)", %%mm4 \n\t"    /* r4 = a3 a2 a1 a0 */ \
-    "punpckldq  %%mm0, %%mm1 \n\t"    /* r1 = h2 g2 f2 e2 = R6 */ \
-    "movq      "I(1)", %%mm5 \n\t"    /* r5 = b3 b2 b1 b0 */ \
-    "movq       %%mm4, %%mm0 \n\t"    /* r0 = a3 a2 a1 a0 */ \
-    "movq       %%mm6, "J(7)"\n\t" \
-    "punpcklwd  %%mm5, %%mm0 \n\t"    /* r0 = b1 a1 b0 a0 */ \
-    "movq       %%mm1, "J(6)"\n\t" \
-    "punpckhwd  %%mm5, %%mm4 \n\t"    /* r4 = b3 a3 b2 a2 */ \
-    "movq       %%mm2, %%mm5 \n\t"    /* r5 = c3 c2 c1 c0 */ \
-    "punpcklwd  %%mm3, %%mm2 \n\t"    /* r2 = d1 c1 d0 c0 */ \
-    "movq       %%mm0, %%mm1 \n\t"    /* r1 = b1 a1 b0 a0 */ \
-    "punpckldq  %%mm2, %%mm0 \n\t"    /* r0 = d0 c0 b0 a0 = R0 */ \
-    "punpckhdq  %%mm2, %%mm1 \n\t"    /* r1 = d1 c1 b1 a1 = R1 */ \
-    "movq       %%mm4, %%mm2 \n\t"    /* r2 = b3 a3 b2 a2 */ \
-    "movq       %%mm0, "I(0)"\n\t" \
-    "punpckhwd  %%mm3, %%mm5 \n\t"    /* r5 = d3 c3 d2 c2 */ \
-    "movq       %%mm1, "I(1)"\n\t" \
-    "punpckhdq  %%mm5, %%mm4 \n\t"    /* r4 = d3 c3 b3 a3 = R3 */ \
-    "punpckldq  %%mm5, %%mm2 \n\t"    /* r2 = d2 c2 b2 a2 = R2 */ \
-    "movq       %%mm4, "I(3)"\n\t" \
-    "movq       %%mm2, "I(2)"\n\t"
-
-void ff_vp3_idct_mmx(int16_t *output_data)
-{
-    /* eax = quantized input
-     * ebx = dequantizer matrix
-     * ecx = IDCT constants
-     *  M(I) = ecx + MaskOffset(0) + I * 8
-     *  C(I) = ecx + CosineOffset(32) + (I-1) * 8
-     * edx = output
-     * r0..r7 = mm0..mm7
-     */
-
-#define C(x) AV_STRINGIFY(16*(x-1))"(%1)"
-#define OC_8 "%2"
-
-    /* at this point, function has completed dequantization + dezigzag +
-     * partial transposition; now do the idct itself */
-#define I(x) AV_STRINGIFY(16* x       )"(%0)"
-#define J(x) AV_STRINGIFY(16*(x-4) + 8)"(%0)"
-
-    __asm__ volatile (
-        RowIDCT()
-        Transpose()
-
-#undef I
-#undef J
-#define I(x) AV_STRINGIFY(16* x    + 64)"(%0)"
-#define J(x) AV_STRINGIFY(16*(x-4) + 72)"(%0)"
-
-        RowIDCT()
-        Transpose()
-
-#undef I
-#undef J
-#define I(x) AV_STRINGIFY(16*x)"(%0)"
-#define J(x) AV_STRINGIFY(16*x)"(%0)"
-
-        ColumnIDCT()
-
-#undef I
-#undef J
-#define I(x) AV_STRINGIFY(16*x + 8)"(%0)"
-#define J(x) AV_STRINGIFY(16*x + 8)"(%0)"
-
-        ColumnIDCT()
-        :: "r"(output_data), "r"(ff_vp3_idct_data), "m"(ff_pw_8)
-    );
-#undef I
-#undef J
-
-}
-
-void ff_vp3_idct_put_mmx(uint8_t *dest, int line_size, DCTELEM *block)
-{
-    ff_vp3_idct_mmx(block);
-    put_signed_pixels_clamped_mmx(block, dest, line_size);
-}
-
-void ff_vp3_idct_add_mmx(uint8_t *dest, int line_size, DCTELEM *block)
-{
-    ff_vp3_idct_mmx(block);
-    add_pixels_clamped_mmx(block, dest, line_size);
-}
-
-void ff_vp3_idct_dc_add_mmx2(uint8_t *dest, int linesize, const DCTELEM *block)
-{
-    int dc = block[0];
-    dc = (46341*dc)>>16;
-    dc = (46341*dc + (8<<16))>>20;
-
-    __asm__ volatile(
-        "movd          %3, %%mm0 \n\t"
-        "pshufw $0, %%mm0, %%mm0 \n\t"
-        "pxor       %%mm1, %%mm1 \n\t"
-        "psubw      %%mm0, %%mm1 \n\t"
-        "packuswb   %%mm0, %%mm0 \n\t"
-        "packuswb   %%mm1, %%mm1 \n\t"
-
-#define DC_ADD \
-        "movq        (%0), %%mm2 \n\t" \
-        "movq     (%0,%1), %%mm3 \n\t" \
-        "paddusb    %%mm0, %%mm2 \n\t" \
-        "movq   (%0,%1,2), %%mm4 \n\t" \
-        "paddusb    %%mm0, %%mm3 \n\t" \
-        "movq     (%0,%2), %%mm5 \n\t" \
-        "paddusb    %%mm0, %%mm4 \n\t" \
-        "paddusb    %%mm0, %%mm5 \n\t" \
-        "psubusb    %%mm1, %%mm2 \n\t" \
-        "psubusb    %%mm1, %%mm3 \n\t" \
-        "movq       %%mm2, (%0)  \n\t" \
-        "psubusb    %%mm1, %%mm4 \n\t" \
-        "movq       %%mm3, (%0,%1) \n\t" \
-        "psubusb    %%mm1, %%mm5 \n\t" \
-        "movq       %%mm4, (%0,%1,2) \n\t" \
-        "movq       %%mm5, (%0,%2) \n\t"
-
-        DC_ADD
-        "lea    (%0,%1,4), %0 \n\t"
-        DC_ADD
-
-        : "+r"(dest)
-        : "r"((x86_reg)linesize), "r"((x86_reg)3*linesize), "r"(dc)
-    );
-}
diff --git a/libavcodec/x86/vp3dsp_mmx.h b/libavcodec/x86/vp3dsp_mmx.h
deleted file mode 100644
index e0ebf0b..0000000
--- a/libavcodec/x86/vp3dsp_mmx.h
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * vp3dsp MMX function declarations
- * Copyright (c) 2007 Aurelien Jacobs <aurel at gnuage.org>
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-#ifndef AVCODEC_X86_VP3DSP_MMX_H
-#define AVCODEC_X86_VP3DSP_MMX_H
-
-#include <stdint.h>
-#include "libavcodec/dsputil.h"
-
-void ff_vp3_idct_mmx(int16_t *data);
-void ff_vp3_idct_put_mmx(uint8_t *dest, int line_size, DCTELEM *block);
-void ff_vp3_idct_add_mmx(uint8_t *dest, int line_size, DCTELEM *block);
-void ff_vp3_idct_dc_add_mmx2(uint8_t *dest, int line_size, const DCTELEM *block);
-
-void ff_vp3_v_loop_filter_mmx2(uint8_t *src, int stride, int *bounding_values);
-void ff_vp3_h_loop_filter_mmx2(uint8_t *src, int stride, int *bounding_values);
-
-#endif /* AVCODEC_X86_VP3DSP_MMX_H */
diff --git a/libavcodec/x86/vp3dsp_sse2.c b/libavcodec/x86/vp3dsp_sse2.c
deleted file mode 100644
index e0ebd42..0000000
--- a/libavcodec/x86/vp3dsp_sse2.c
+++ /dev/null
@@ -1,187 +0,0 @@
-/*
- * Copyright (C) 2004 the ffmpeg project
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-/**
- * @file
- * SSE2-optimized functions cribbed from the original VP3 source code.
- */
-
-#include "libavcodec/dsputil.h"
-#include "dsputil_mmx.h"
-#include "vp3dsp_sse2.h"
-
-DECLARE_ALIGNED(16, const uint16_t, ff_vp3_idct_data)[7 * 8] =
-{
-    64277,64277,64277,64277,64277,64277,64277,64277,
-    60547,60547,60547,60547,60547,60547,60547,60547,
-    54491,54491,54491,54491,54491,54491,54491,54491,
-    46341,46341,46341,46341,46341,46341,46341,46341,
-    36410,36410,36410,36410,36410,36410,36410,36410,
-    25080,25080,25080,25080,25080,25080,25080,25080,
-    12785,12785,12785,12785,12785,12785,12785,12785
-};
-
-
-#define VP3_1D_IDCT_SSE2(ADD, SHIFT) \
-    "movdqa "I(3)", %%xmm2 \n\t"     /* xmm2 = i3 */ \
-    "movdqa "C(3)", %%xmm6 \n\t"     /* xmm6 = c3 */ \
-    "movdqa %%xmm2, %%xmm4 \n\t"     /* xmm4 = i3 */ \
-    "movdqa "I(5)", %%xmm7 \n\t"     /* xmm7 = i5 */ \
-    "pmulhw %%xmm6, %%xmm4 \n\t"     /* xmm4 = c3 * i3 - i3 */ \
-    "movdqa "C(5)", %%xmm1 \n\t"     /* xmm1 = c5 */ \
-    "pmulhw %%xmm7, %%xmm6 \n\t"     /* xmm6 = c3 * i5 - i5 */ \
-    "movdqa %%xmm1, %%xmm5 \n\t"     /* xmm5 = c5 */ \
-    "pmulhw %%xmm2, %%xmm1 \n\t"     /* xmm1 = c5 * i3 - i3 */ \
-    "movdqa "I(1)", %%xmm3 \n\t"     /* xmm3 = i1 */ \
-    "pmulhw %%xmm7, %%xmm5 \n\t"     /* xmm5 = c5 * i5 - i5 */ \
-    "movdqa "C(1)", %%xmm0 \n\t"     /* xmm0 = c1 */ \
-    "paddw  %%xmm2, %%xmm4 \n\t"     /* xmm4 = c3 * i3 */ \
-    "paddw  %%xmm7, %%xmm6 \n\t"     /* xmm6 = c3 * i5 */ \
-    "paddw  %%xmm1, %%xmm2 \n\t"     /* xmm2 = c5 * i3 */ \
-    "movdqa "I(7)", %%xmm1 \n\t"     /* xmm1 = i7 */ \
-    "paddw  %%xmm5, %%xmm7 \n\t"     /* xmm7 = c5 * i5 */ \
-    "movdqa %%xmm0, %%xmm5 \n\t"     /* xmm5 = c1 */ \
-    "pmulhw %%xmm3, %%xmm0 \n\t"     /* xmm0 = c1 * i1 - i1 */ \
-    "paddsw %%xmm7, %%xmm4 \n\t"     /* xmm4 = c3 * i3 + c5 * i5 = C */ \
-    "pmulhw %%xmm1, %%xmm5 \n\t"     /* xmm5 = c1 * i7 - i7 */ \
-    "movdqa "C(7)", %%xmm7 \n\t"     /* xmm7 = c7 */ \
-    "psubsw %%xmm2, %%xmm6 \n\t"     /* xmm6 = c3 * i5 - c5 * i3 = D */ \
-    "paddw  %%xmm3, %%xmm0 \n\t"     /* xmm0 = c1 * i1 */ \
-    "pmulhw %%xmm7, %%xmm3 \n\t"     /* xmm3 = c7 * i1 */ \
-    "movdqa "I(2)", %%xmm2 \n\t"     /* xmm2 = i2 */ \
-    "pmulhw %%xmm1, %%xmm7 \n\t"     /* xmm7 = c7 * i7 */ \
-    "paddw  %%xmm1, %%xmm5 \n\t"     /* xmm5 = c1 * i7 */ \
-    "movdqa %%xmm2, %%xmm1 \n\t"     /* xmm1 = i2 */ \
-    "pmulhw "C(2)", %%xmm2 \n\t"     /* xmm2 = i2 * c2 -i2 */ \
-    "psubsw %%xmm5, %%xmm3 \n\t"     /* xmm3 = c7 * i1 - c1 * i7 = B */ \
-    "movdqa "I(6)", %%xmm5 \n\t"     /* xmm5 = i6 */ \
-    "paddsw %%xmm7, %%xmm0 \n\t"     /* xmm0 = c1 * i1 + c7 * i7 = A */ \
-    "movdqa %%xmm5, %%xmm7 \n\t"     /* xmm7 = i6 */ \
-    "psubsw %%xmm4, %%xmm0 \n\t"     /* xmm0 = A - C */ \
-    "pmulhw "C(2)", %%xmm5 \n\t"     /* xmm5 = c2 * i6 - i6 */ \
-    "paddw  %%xmm1, %%xmm2 \n\t"     /* xmm2 = i2 * c2 */ \
-    "pmulhw "C(6)", %%xmm1 \n\t"     /* xmm1 = c6 * i2 */ \
-    "paddsw %%xmm4, %%xmm4 \n\t"     /* xmm4 = C + C */ \
-    "paddsw %%xmm0, %%xmm4 \n\t"     /* xmm4 = A + C = C. */ \
-    "psubsw %%xmm6, %%xmm3 \n\t"     /* xmm3 = B - D */ \
-    "paddw  %%xmm7, %%xmm5 \n\t"     /* xmm5 = c2 * i6 */ \
-    "paddsw %%xmm6, %%xmm6 \n\t"     /* xmm6 = D + D */ \
-    "pmulhw "C(6)", %%xmm7 \n\t"     /* xmm7 = c6 * i6 */ \
-    "paddsw %%xmm3, %%xmm6 \n\t"     /* xmm6 = B + D = D. */ \
-    "movdqa %%xmm4, "I(1)" \n\t"     /* Save C. at I(1) */ \
-    "psubsw %%xmm5, %%xmm1 \n\t"     /* xmm1 = c6 * i2 - c2 * i6 = H */ \
-    "movdqa "C(4)", %%xmm4 \n\t"     /* xmm4 = c4 */ \
-    "movdqa %%xmm3, %%xmm5 \n\t"     /* xmm5 = B - D */ \
-    "pmulhw %%xmm4, %%xmm3 \n\t"     /* xmm3 = ( c4 -1 ) * ( B - D ) */ \
-    "paddsw %%xmm2, %%xmm7 \n\t"     /* xmm7 = c2 * i2 + c6 * i6 = G */ \
-    "movdqa %%xmm6, "I(2)" \n\t"     /* Save D. at I(2) */ \
-    "movdqa %%xmm0, %%xmm2 \n\t"     /* xmm2 = A - C */ \
-    "movdqa "I(0)", %%xmm6 \n\t"     /* xmm6 = i0 */ \
-    "pmulhw %%xmm4, %%xmm0 \n\t"     /* xmm0 = ( c4 - 1 ) * ( A - C ) = A. */ \
-    "paddw  %%xmm3, %%xmm5 \n\t"     /* xmm5 = c4 * ( B - D ) = B. */ \
-    "movdqa "I(4)", %%xmm3 \n\t"     /* xmm3 = i4 */ \
-    "psubsw %%xmm1, %%xmm5 \n\t"     /* xmm5 = B. - H = B.. */ \
-    "paddw  %%xmm0, %%xmm2 \n\t"     /* xmm2 = c4 * ( A - C) = A. */ \
-    "psubsw %%xmm3, %%xmm6 \n\t"     /* xmm6 = i0 - i4 */ \
-    "movdqa %%xmm6, %%xmm0 \n\t"     /* xmm0 = i0 - i4 */ \
-    "pmulhw %%xmm4, %%xmm6 \n\t"     /* xmm6 = (c4 - 1) * (i0 - i4) = F */ \
-    "paddsw %%xmm3, %%xmm3 \n\t"     /* xmm3 = i4 + i4 */ \
-    "paddsw %%xmm1, %%xmm1 \n\t"     /* xmm1 = H + H */ \
-    "paddsw %%xmm0, %%xmm3 \n\t"     /* xmm3 = i0 + i4 */ \
-    "paddsw %%xmm5, %%xmm1 \n\t"     /* xmm1 = B. + H = H. */ \
-    "pmulhw %%xmm3, %%xmm4 \n\t"     /* xmm4 = ( c4 - 1 ) * ( i0 + i4 )  */ \
-    "paddw  %%xmm0, %%xmm6 \n\t"     /* xmm6 = c4 * ( i0 - i4 ) */ \
-    "psubsw %%xmm2, %%xmm6 \n\t"     /* xmm6 = F - A. = F. */ \
-    "paddsw %%xmm2, %%xmm2 \n\t"     /* xmm2 = A. + A. */ \
-    "movdqa "I(1)", %%xmm0 \n\t"     /* Load        C. from I(1) */ \
-    "paddsw %%xmm6, %%xmm2 \n\t"     /* xmm2 = F + A. = A.. */ \
-    "paddw  %%xmm3, %%xmm4 \n\t"     /* xmm4 = c4 * ( i0 + i4 ) = 3 */ \
-    "psubsw %%xmm1, %%xmm2 \n\t"     /* xmm2 = A.. - H. = R2 */ \
-    ADD(%%xmm2)                      /* Adjust R2 and R1 before shifting */ \
-    "paddsw %%xmm1, %%xmm1 \n\t"     /* xmm1 = H. + H. */ \
-    "paddsw %%xmm2, %%xmm1 \n\t"     /* xmm1 = A.. + H. = R1 */ \
-    SHIFT(%%xmm2)                    /* xmm2 = op2 */ \
-    "psubsw %%xmm7, %%xmm4 \n\t"     /* xmm4 = E - G = E. */ \
-    SHIFT(%%xmm1)                    /* xmm1 = op1 */ \
-    "movdqa "I(2)", %%xmm3 \n\t"     /* Load D. from I(2) */ \
-    "paddsw %%xmm7, %%xmm7 \n\t"     /* xmm7 = G + G */ \
-    "paddsw %%xmm4, %%xmm7 \n\t"     /* xmm7 = E + G = G. */ \
-    "psubsw %%xmm3, %%xmm4 \n\t"     /* xmm4 = E. - D. = R4 */ \
-    ADD(%%xmm4)                      /* Adjust R4 and R3 before shifting */ \
-    "paddsw %%xmm3, %%xmm3 \n\t"     /* xmm3 = D. + D. */ \
-    "paddsw %%xmm4, %%xmm3 \n\t"     /* xmm3 = E. + D. = R3 */ \
-    SHIFT(%%xmm4)                    /* xmm4 = op4 */ \
-    "psubsw %%xmm5, %%xmm6 \n\t"     /* xmm6 = F. - B..= R6 */ \
-    SHIFT(%%xmm3)                    /* xmm3 = op3 */ \
-    ADD(%%xmm6)                      /* Adjust R6 and R5 before shifting */ \
-    "paddsw %%xmm5, %%xmm5 \n\t"     /* xmm5 = B.. + B.. */ \
-    "paddsw %%xmm6, %%xmm5 \n\t"     /* xmm5 = F. + B.. = R5 */ \
-    SHIFT(%%xmm6)                    /* xmm6 = op6 */ \
-    SHIFT(%%xmm5)                    /* xmm5 = op5 */ \
-    "psubsw %%xmm0, %%xmm7 \n\t"     /* xmm7 = G. - C. = R7 */ \
-    ADD(%%xmm7)                      /* Adjust R7 and R0 before shifting */ \
-    "paddsw %%xmm0, %%xmm0 \n\t"     /* xmm0 = C. + C. */ \
-    "paddsw %%xmm7, %%xmm0 \n\t"     /* xmm0 = G. + C. */ \
-    SHIFT(%%xmm7)                    /* xmm7 = op7 */ \
-    SHIFT(%%xmm0)                    /* xmm0 = op0 */
-
-#define PUT_BLOCK(r0, r1, r2, r3, r4, r5, r6, r7) \
-    "movdqa " #r0 ", " O(0) "\n\t" \
-    "movdqa " #r1 ", " O(1) "\n\t" \
-    "movdqa " #r2 ", " O(2) "\n\t" \
-    "movdqa " #r3 ", " O(3) "\n\t" \
-    "movdqa " #r4 ", " O(4) "\n\t" \
-    "movdqa " #r5 ", " O(5) "\n\t" \
-    "movdqa " #r6 ", " O(6) "\n\t" \
-    "movdqa " #r7 ", " O(7) "\n\t"
-
-#define NOP(xmm)
-#define SHIFT4(xmm) "psraw  $4, "#xmm"\n\t"
-#define ADD8(xmm)   "paddsw %2, "#xmm"\n\t"
-
-void ff_vp3_idct_sse2(int16_t *input_data)
-{
-#define I(x) AV_STRINGIFY(16*x)"(%0)"
-#define O(x) I(x)
-#define C(x) AV_STRINGIFY(16*(x-1))"(%1)"
-
-    __asm__ volatile (
-        VP3_1D_IDCT_SSE2(NOP, NOP)
-
-        TRANSPOSE8(%%xmm0, %%xmm1, %%xmm2, %%xmm3, %%xmm4, %%xmm5, %%xmm6, %%xmm7, (%0))
-        PUT_BLOCK(%%xmm0, %%xmm5, %%xmm7, %%xmm3, %%xmm6, %%xmm4, %%xmm2, %%xmm1)
-
-        VP3_1D_IDCT_SSE2(ADD8, SHIFT4)
-        PUT_BLOCK(%%xmm0, %%xmm1, %%xmm2, %%xmm3, %%xmm4, %%xmm5, %%xmm6, %%xmm7)
-        :: "r"(input_data), "r"(ff_vp3_idct_data), "m"(ff_pw_8)
-    );
-}
-
-void ff_vp3_idct_put_sse2(uint8_t *dest, int line_size, DCTELEM *block)
-{
-    ff_vp3_idct_sse2(block);
-    put_signed_pixels_clamped_mmx(block, dest, line_size);
-}
-
-void ff_vp3_idct_add_sse2(uint8_t *dest, int line_size, DCTELEM *block)
-{
-    ff_vp3_idct_sse2(block);
-    add_pixels_clamped_mmx(block, dest, line_size);
-}
diff --git a/libavcodec/x86/vp3dsp_sse2.h b/libavcodec/x86/vp3dsp_sse2.h
deleted file mode 100644
index 9094620..0000000
--- a/libavcodec/x86/vp3dsp_sse2.h
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * vp3dsp SSE2 function declarations
- * Copyright (c) 2007 Aurelien Jacobs <aurel at gnuage.org>
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-#ifndef AVCODEC_X86_VP3DSP_SSE2_H
-#define AVCODEC_X86_VP3DSP_SSE2_H
-
-#include "libavcodec/dsputil.h"
-
-void ff_vp3_idct_sse2(int16_t *input_data);
-void ff_vp3_idct_put_sse2(uint8_t *dest, int line_size, DCTELEM *block);
-void ff_vp3_idct_add_sse2(uint8_t *dest, int line_size, DCTELEM *block);
-
-#endif /* AVCODEC_X86_VP3DSP_SSE2_H */
diff --git a/libavcodec/x86/vp56_arith.h b/libavcodec/x86/vp56_arith.h
new file mode 100644
index 0000000..be2dd30
--- /dev/null
+++ b/libavcodec/x86/vp56_arith.h
@@ -0,0 +1,54 @@
+/**
+ * VP5 and VP6 compatible video decoder (arith decoder)
+ *
+ * Copyright (C) 2006  Aurelien Jacobs <aurel at gnuage.org>
+ * Copyright (C) 2010  Eli Friedman
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_X86_VP56_ARITH_H
+#define AVCODEC_X86_VP56_ARITH_H
+
+#if HAVE_FAST_CMOV
+#define vp56_rac_get_prob vp56_rac_get_prob
+static av_always_inline int vp56_rac_get_prob(VP56RangeCoder *c, uint8_t prob)
+{
+    unsigned int code_word = vp56_rac_renorm(c);
+    unsigned int high = c->high;
+    unsigned int low = 1 + (((high - 1) * prob) >> 8);
+    unsigned int low_shift = low << 16;
+    int bit = 0;
+
+    __asm__(
+        "subl  %4, %1      \n\t"
+        "subl  %3, %2      \n\t"
+        "leal (%2, %3), %3 \n\t"
+        "setae %b0         \n\t"
+        "cmovb %4, %1      \n\t"
+        "cmovb %3, %2      \n\t"
+        : "+q"(bit), "+r"(high), "+r"(code_word), "+r"(low_shift)
+        : "r"(low)
+    );
+
+    c->high      = high;
+    c->code_word = code_word;
+    return bit;
+}
+#endif
+
+#endif /* AVCODEC_X86_VP56_ARITH_H */
diff --git a/libavcodec/x86/vp56dsp.asm b/libavcodec/x86/vp56dsp.asm
new file mode 100644
index 0000000..1cc62a6
--- /dev/null
+++ b/libavcodec/x86/vp56dsp.asm
@@ -0,0 +1,173 @@
+;******************************************************************************
+;* MMX/SSE2-optimized functions for the VP6 decoder
+;* Copyright (C) 2009  Sebastien Lucas <sebastien.lucas at gmail.com>
+;* Copyright (C) 2009  Zuxy Meng <zuxy.meng at gmail.com>
+;*
+;* This file is part of Libav.
+;*
+;* Libav is free software; you can redistribute it and/or
+;* modify it under the terms of the GNU Lesser General Public
+;* License as published by the Free Software Foundation; either
+;* version 2.1 of the License, or (at your option) any later version.
+;*
+;* Libav is distributed in the hope that it will be useful,
+;* but WITHOUT ANY WARRANTY; without even the implied warranty of
+;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+;* Lesser General Public License for more details.
+;*
+;* You should have received a copy of the GNU Lesser General Public
+;* License along with Libav; if not, write to the Free Software
+;* 51, Inc., Foundation Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+;******************************************************************************
+
+%include "x86inc.asm"
+%include "x86util.asm"
+
+cextern pw_64
+
+SECTION .text
+
+%macro DIAG4_MMX 6
+    movq          m0, [%1+%2]
+    movq          m1, [%1+%3]
+    movq          m3, m0
+    movq          m4, m1
+    punpcklbw     m0, m7
+    punpcklbw     m1, m7
+    punpckhbw     m3, m7
+    punpckhbw     m4, m7
+    pmullw        m0, [rsp+8*11] ; src[x-8 ] * biweight [0]
+    pmullw        m1, [rsp+8*12] ; src[x   ] * biweight [1]
+    pmullw        m3, [rsp+8*11] ; src[x-8 ] * biweight [0]
+    pmullw        m4, [rsp+8*12] ; src[x   ] * biweight [1]
+    paddw         m0, m1
+    paddw         m3, m4
+    movq          m1, [%1+%4]
+    movq          m2, [%1+%5]
+    movq          m4, m1
+    movq          m5, m2
+    punpcklbw     m1, m7
+    punpcklbw     m2, m7
+    punpckhbw     m4, m7
+    punpckhbw     m5, m7
+    pmullw        m1, [rsp+8*13] ; src[x+8 ] * biweight [2]
+    pmullw        m2, [rsp+8*14] ; src[x+16] * biweight [3]
+    pmullw        m4, [rsp+8*13] ; src[x+8 ] * biweight [2]
+    pmullw        m5, [rsp+8*14] ; src[x+16] * biweight [3]
+    paddw         m1, m2
+    paddw         m4, m5
+    paddsw        m0, m1
+    paddsw        m3, m4
+    paddsw        m0, m6         ; Add 64
+    paddsw        m3, m6         ; Add 64
+    psraw         m0, 7
+    psraw         m3, 7
+    packuswb      m0, m3
+    movq        [%6], m0
+%endmacro
+
+%macro DIAG4_SSE2 6
+    movq          m0, [%1+%2]
+    movq          m1, [%1+%3]
+    punpcklbw     m0, m7
+    punpcklbw     m1, m7
+    pmullw        m0, m4         ; src[x-8 ] * biweight [0]
+    pmullw        m1, m5         ; src[x   ] * biweight [1]
+    paddw         m0, m1
+    movq          m1, [%1+%4]
+    movq          m2, [%1+%5]
+    punpcklbw     m1, m7
+    punpcklbw     m2, m7
+    pmullw        m1, m6         ; src[x+8 ] * biweight [2]
+    pmullw        m2, m3         ; src[x+16] * biweight [3]
+    paddw         m1, m2
+    paddsw        m0, m1
+    paddsw        m0, [pw_64]    ; Add 64
+    psraw         m0, 7
+    packuswb      m0, m0
+    movq        [%6], m0
+%endmacro
+
+%macro SPLAT4REGS_MMX 0
+    movq         m5, m3
+    punpcklwd    m3, m3
+    movq         m4, m3
+    punpckldq    m3, m3
+    punpckhdq    m4, m4
+    punpckhwd    m5, m5
+    movq         m2, m5
+    punpckhdq    m2, m2
+    punpckldq    m5, m5
+    movq [rsp+8*11], m3
+    movq [rsp+8*12], m4
+    movq [rsp+8*13], m5
+    movq [rsp+8*14], m2
+%endmacro
+
+%macro SPLAT4REGS_SSE2 0
+    pshuflw      m4, m3, 0x0
+    pshuflw      m5, m3, 0x55
+    pshuflw      m6, m3, 0xAA
+    pshuflw      m3, m3, 0xFF
+    punpcklqdq   m4, m4
+    punpcklqdq   m5, m5
+    punpcklqdq   m6, m6
+    punpcklqdq   m3, m3
+%endmacro
+
+%macro vp6_filter_diag4 2
+; void ff_vp6_filter_diag4_<opt>(uint8_t *dst, uint8_t *src, int stride,
+;                                const int16_t h_weight[4], const int16_t v_weights[4])
+cglobal vp6_filter_diag4_%1, 5, 7, %2
+    mov          r5, rsp         ; backup stack pointer
+    and         rsp, ~(mmsize-1) ; align stack
+%ifidn %1, sse2
+    sub         rsp, 8*11
+%else
+    sub         rsp, 8*15
+    movq         m6, [pw_64]
+%endif
+%ifdef ARCH_X86_64
+    movsxd       r2, r2d
+%endif
+
+    sub          r1, r2
+
+    pxor         m7, m7
+    movq         m3, [r3]
+    SPLAT4REGS
+
+    mov          r3, rsp
+    mov          r6, 11
+.nextrow
+    DIAG4        r1, -1, 0, 1, 2, r3
+    add          r3, 8
+    add          r1, r2
+    dec          r6
+    jnz .nextrow
+
+    movq         m3, [r4]
+    SPLAT4REGS
+
+    lea          r3, [rsp+8]
+    mov          r6, 8
+.nextcol
+    DIAG4        r3, -8, 0, 8, 16, r0
+    add          r3, 8
+    add          r0, r2
+    dec          r6
+    jnz .nextcol
+
+    mov         rsp, r5          ; restore stack pointer
+    RET
+%endmacro
+
+INIT_MMX
+%define DIAG4      DIAG4_MMX
+%define SPLAT4REGS SPLAT4REGS_MMX
+vp6_filter_diag4 mmx,  0
+
+INIT_XMM
+%define DIAG4      DIAG4_SSE2
+%define SPLAT4REGS SPLAT4REGS_SSE2
+vp6_filter_diag4 sse2, 8
diff --git a/libavcodec/x86/vp56dsp_init.c b/libavcodec/x86/vp56dsp_init.c
new file mode 100644
index 0000000..2989281
--- /dev/null
+++ b/libavcodec/x86/vp56dsp_init.c
@@ -0,0 +1,48 @@
+/*
+ * VP6 MMX/SSE2 optimizations
+ * Copyright (C) 2009  Sebastien Lucas <sebastien.lucas at gmail.com>
+ * Copyright (C) 2009  Zuxy Meng <zuxy.meng at gmail.com>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "libavutil/cpu.h"
+#include "libavutil/x86_cpu.h"
+#include "libavcodec/dsputil.h"
+#include "libavcodec/vp56dsp.h"
+
+void ff_vp6_filter_diag4_mmx(uint8_t *dst, uint8_t *src, int stride,
+                             const int16_t *h_weights,const int16_t *v_weights);
+void ff_vp6_filter_diag4_sse2(uint8_t *dst, uint8_t *src, int stride,
+                              const int16_t *h_weights,const int16_t *v_weights);
+
+av_cold void ff_vp56dsp_init_x86(VP56DSPContext* c, enum CodecID codec)
+{
+#if HAVE_YASM
+    int mm_flags = av_get_cpu_flags();
+
+    if (CONFIG_VP6_DECODER && codec == CODEC_ID_VP6) {
+        if (mm_flags & AV_CPU_FLAG_MMX) {
+            c->vp6_filter_diag4 = ff_vp6_filter_diag4_mmx;
+        }
+
+        if (mm_flags & AV_CPU_FLAG_SSE2) {
+            c->vp6_filter_diag4 = ff_vp6_filter_diag4_sse2;
+        }
+    }
+#endif
+}
diff --git a/libavcodec/x86/vp6dsp_mmx.c b/libavcodec/x86/vp6dsp_mmx.c
deleted file mode 100644
index 905b3a7..0000000
--- a/libavcodec/x86/vp6dsp_mmx.c
+++ /dev/null
@@ -1,108 +0,0 @@
-/**
- * @file
- * MMX-optimized functions for the VP6 decoder
- *
- * Copyright (C) 2009  Sebastien Lucas <sebastien.lucas at gmail.com>
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-#include "libavutil/x86_cpu.h"
-#include "libavcodec/dsputil.h"
-#include "dsputil_mmx.h"
-#include "vp6dsp_mmx.h"
-
-
-#define DIAG4_MMX(in1,in2,in3,in4)                                            \
-    "movq  "#in1"(%0), %%mm0             \n\t"                                \
-    "movq  "#in2"(%0), %%mm1             \n\t"                                \
-    "movq       %%mm0, %%mm3             \n\t"                                \
-    "movq       %%mm1, %%mm4             \n\t"                                \
-    "punpcklbw  %%mm7, %%mm0             \n\t"                                \
-    "punpcklbw  %%mm7, %%mm1             \n\t"                                \
-    "punpckhbw  %%mm7, %%mm3             \n\t"                                \
-    "punpckhbw  %%mm7, %%mm4             \n\t"                                \
-    "pmullw     0(%2), %%mm0             \n\t" /* src[x-8 ] * biweight [0] */ \
-    "pmullw     8(%2), %%mm1             \n\t" /* src[x   ] * biweight [1] */ \
-    "pmullw     0(%2), %%mm3             \n\t" /* src[x-8 ] * biweight [0] */ \
-    "pmullw     8(%2), %%mm4             \n\t" /* src[x   ] * biweight [1] */ \
-    "paddw      %%mm1, %%mm0             \n\t"                                \
-    "paddw      %%mm4, %%mm3             \n\t"                                \
-    "movq  "#in3"(%0), %%mm1             \n\t"                                \
-    "movq  "#in4"(%0), %%mm2             \n\t"                                \
-    "movq       %%mm1, %%mm4             \n\t"                                \
-    "movq       %%mm2, %%mm5             \n\t"                                \
-    "punpcklbw  %%mm7, %%mm1             \n\t"                                \
-    "punpcklbw  %%mm7, %%mm2             \n\t"                                \
-    "punpckhbw  %%mm7, %%mm4             \n\t"                                \
-    "punpckhbw  %%mm7, %%mm5             \n\t"                                \
-    "pmullw    16(%2), %%mm1             \n\t" /* src[x+8 ] * biweight [2] */ \
-    "pmullw    24(%2), %%mm2             \n\t" /* src[x+16] * biweight [3] */ \
-    "pmullw    16(%2), %%mm4             \n\t" /* src[x+8 ] * biweight [2] */ \
-    "pmullw    24(%2), %%mm5             \n\t" /* src[x+16] * biweight [3] */ \
-    "paddw      %%mm2, %%mm1             \n\t"                                \
-    "paddw      %%mm5, %%mm4             \n\t"                                \
-    "paddsw     %%mm1, %%mm0             \n\t"                                \
-    "paddsw     %%mm4, %%mm3             \n\t"                                \
-    "paddsw     %%mm6, %%mm0             \n\t" /* Add 64 */                   \
-    "paddsw     %%mm6, %%mm3             \n\t" /* Add 64 */                   \
-    "psraw         $7, %%mm0             \n\t"                                \
-    "psraw         $7, %%mm3             \n\t"                                \
-    "packuswb   %%mm3, %%mm0             \n\t"                                \
-    "movq       %%mm0,  (%1)             \n\t"
-
-void ff_vp6_filter_diag4_mmx(uint8_t *dst, uint8_t *src, int stride,
-                             const int16_t *h_weights, const int16_t *v_weights)
-{
-    uint8_t tmp[8*11], *t = tmp;
-    int16_t weights[4*4];
-    int i;
-    src -= stride;
-
-    for (i=0; i<4*4; i++)
-        weights[i] = h_weights[i>>2];
-
-    __asm__ volatile(
-    "pxor %%mm7, %%mm7                   \n\t"
-    "movq "MANGLE(ff_pw_64)", %%mm6      \n\t"
-    "1:                                  \n\t"
-    DIAG4_MMX(-1,0,1,2)
-    "add  $8, %1                         \n\t"
-    "add  %3, %0                         \n\t"
-    "decl %4                             \n\t"
-    "jnz 1b                              \n\t"
-    : "+r"(src), "+r"(t)
-    : "r"(weights), "r"((x86_reg)stride), "r"(11)
-    : "memory");
-
-    t = tmp + 8;
-    for (i=0; i<4*4; i++)
-        weights[i] = v_weights[i>>2];
-
-    __asm__ volatile(
-    "pxor %%mm7, %%mm7                   \n\t"
-    "movq "MANGLE(ff_pw_64)", %%mm6      \n\t"
-    "1:                                  \n\t"
-    DIAG4_MMX(-8,0,8,16)
-    "add  $8, %0                         \n\t"
-    "add  %3, %1                         \n\t"
-    "decl %4                             \n\t"
-    "jnz 1b                              \n\t"
-    : "+r"(t), "+r"(dst)
-    : "r"(weights), "r"((x86_reg)stride), "r"(8)
-    : "memory");
-}
diff --git a/libavcodec/x86/vp6dsp_mmx.h b/libavcodec/x86/vp6dsp_mmx.h
deleted file mode 100644
index 743bc43..0000000
--- a/libavcodec/x86/vp6dsp_mmx.h
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * vp6dsp MMX function declarations
- * Copyright (c) 2009  Sebastien Lucas <sebastien.lucas at gmail.com>
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-#ifndef AVCODEC_X86_VP6DSP_MMX_H
-#define AVCODEC_X86_VP6DSP_MMX_H
-
-#include <stdint.h>
-
-void ff_vp6_filter_diag4_mmx(uint8_t *dst, uint8_t *src, int stride,
-                             const int16_t *h_weights,const int16_t *v_weights);
-
-#endif /* AVCODEC_X86_VP6DSP_MMX_H */
diff --git a/libavcodec/x86/vp6dsp_sse2.c b/libavcodec/x86/vp6dsp_sse2.c
deleted file mode 100644
index bfd733a..0000000
--- a/libavcodec/x86/vp6dsp_sse2.c
+++ /dev/null
@@ -1,98 +0,0 @@
-/**
- * @file
- * SSE2-optimized functions for the VP6 decoder
- *
- * Copyright (C) 2009  Zuxy Meng <zuxy.meng at gmail.com>
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-#include "libavutil/x86_cpu.h"
-#include "libavcodec/dsputil.h"
-#include "dsputil_mmx.h"
-#include "vp6dsp_sse2.h"
-
-#define DIAG4_SSE2(in1,in2,in3,in4)                                           \
-    "movq  "#in1"(%0), %%xmm0            \n\t"                                \
-    "movq  "#in2"(%0), %%xmm1            \n\t"                                \
-    "punpcklbw %%xmm7, %%xmm0            \n\t"                                \
-    "punpcklbw %%xmm7, %%xmm1            \n\t"                                \
-    "pmullw    %%xmm4, %%xmm0            \n\t" /* src[x-8 ] * biweight [0] */ \
-    "pmullw    %%xmm5, %%xmm1            \n\t" /* src[x   ] * biweight [1] */ \
-    "paddw     %%xmm1, %%xmm0            \n\t"                                \
-    "movq  "#in3"(%0), %%xmm1            \n\t"                                \
-    "movq  "#in4"(%0), %%xmm2            \n\t"                                \
-    "punpcklbw %%xmm7, %%xmm1            \n\t"                                \
-    "punpcklbw %%xmm7, %%xmm2            \n\t"                                \
-    "pmullw    %%xmm6, %%xmm1            \n\t" /* src[x+8 ] * biweight [2] */ \
-    "pmullw    %%xmm3, %%xmm2            \n\t" /* src[x+16] * biweight [3] */ \
-    "paddw     %%xmm2, %%xmm1            \n\t"                                \
-    "paddsw     %%xmm1, %%xmm0           \n\t"                                \
-    "paddsw "MANGLE(ff_pw_64)", %%xmm0   \n\t" /* Add 64 */                   \
-    "psraw         $7, %%xmm0            \n\t"                                \
-    "packuswb  %%xmm0, %%xmm0            \n\t"                                \
-    "movq      %%xmm0,   (%1)            \n\t"                                \
-
-void ff_vp6_filter_diag4_sse2(uint8_t *dst, uint8_t *src, int stride,
-                              const int16_t *h_weights,const int16_t *v_weights)
-{
-    uint8_t tmp[8*11], *t = tmp;
-    src -= stride;
-
-    __asm__ volatile(
-    "pxor           %%xmm7, %%xmm7       \n\t"
-    "movq               %4, %%xmm3       \n\t"
-    "pshuflw    $0, %%xmm3, %%xmm4       \n\t"
-    "punpcklqdq     %%xmm4, %%xmm4       \n\t"
-    "pshuflw   $85, %%xmm3, %%xmm5       \n\t"
-    "punpcklqdq     %%xmm5, %%xmm5       \n\t"
-    "pshuflw  $170, %%xmm3, %%xmm6       \n\t"
-    "punpcklqdq     %%xmm6, %%xmm6       \n\t"
-    "pshuflw  $255, %%xmm3, %%xmm3       \n\t"
-    "punpcklqdq     %%xmm3, %%xmm3       \n\t"
-    "1:                                  \n\t"
-    DIAG4_SSE2(-1,0,1,2)
-    "add  $8, %1                         \n\t"
-    "add  %2, %0                         \n\t"
-    "decl %3                             \n\t"
-    "jnz 1b                              \n\t"
-    : "+r"(src), "+r"(t)
-    : "g"((x86_reg)stride), "r"(11), "m"(*(const int64_t*)h_weights)
-    : "memory");
-
-    t = tmp + 8;
-
-    __asm__ volatile(
-    "movq               %4, %%xmm3       \n\t"
-    "pshuflw    $0, %%xmm3, %%xmm4       \n\t"
-    "punpcklqdq     %%xmm4, %%xmm4       \n\t"
-    "pshuflw   $85, %%xmm3, %%xmm5       \n\t"
-    "punpcklqdq     %%xmm5, %%xmm5       \n\t"
-    "pshuflw  $170, %%xmm3, %%xmm6       \n\t"
-    "punpcklqdq     %%xmm6, %%xmm6       \n\t"
-    "pshuflw  $255, %%xmm3, %%xmm3       \n\t"
-    "punpcklqdq     %%xmm3, %%xmm3       \n\t"
-    "1:                                  \n\t"
-    DIAG4_SSE2(-8,0,8,16)
-    "add  $8, %0                         \n\t"
-    "add  %2, %1                         \n\t"
-    "decl %3                             \n\t"
-    "jnz 1b                              \n\t"
-    : "+r"(t), "+r"(dst)
-    : "g"((x86_reg)stride), "r"(8), "m"(*(const int64_t*)v_weights)
-    : "memory");
-}
diff --git a/libavcodec/x86/vp6dsp_sse2.h b/libavcodec/x86/vp6dsp_sse2.h
deleted file mode 100644
index a30089a..0000000
--- a/libavcodec/x86/vp6dsp_sse2.h
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * vp6dsp SSE2 function declarations
- * Copyright (c) 2009  Zuxy Meng <zuxy.meng at gmail.com>
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-#ifndef AVCODEC_X86_VP6DSP_SSE2_H
-#define AVCODEC_X86_VP6DSP_SSE2_H
-
-#include <stdint.h>
-
-void ff_vp6_filter_diag4_sse2(uint8_t *dst, uint8_t *src, int stride,
-                             const int16_t *h_weights,const int16_t *v_weights);
-
-#endif /* AVCODEC_X86_VP6DSP_SSE2_H */
diff --git a/libavcodec/x86/vp8dsp-init.c b/libavcodec/x86/vp8dsp-init.c
new file mode 100644
index 0000000..8b27b0d
--- /dev/null
+++ b/libavcodec/x86/vp8dsp-init.c
@@ -0,0 +1,402 @@
+/*
+ * VP8 DSP functions x86-optimized
+ * Copyright (c) 2010 Ronald S. Bultje <rsbultje at gmail.com>
+ * Copyright (c) 2010 Jason Garrett-Glaser <darkshikari at gmail.com>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "libavutil/cpu.h"
+#include "libavutil/x86_cpu.h"
+#include "libavcodec/vp8dsp.h"
+
+#if HAVE_YASM
+
+/*
+ * MC functions
+ */
+extern void ff_put_vp8_epel4_h4_mmxext(uint8_t *dst, int dststride,
+                                       uint8_t *src, int srcstride,
+                                       int height, int mx, int my);
+extern void ff_put_vp8_epel4_h6_mmxext(uint8_t *dst, int dststride,
+                                       uint8_t *src, int srcstride,
+                                       int height, int mx, int my);
+extern void ff_put_vp8_epel4_v4_mmxext(uint8_t *dst, int dststride,
+                                       uint8_t *src, int srcstride,
+                                       int height, int mx, int my);
+extern void ff_put_vp8_epel4_v6_mmxext(uint8_t *dst, int dststride,
+                                       uint8_t *src, int srcstride,
+                                       int height, int mx, int my);
+
+extern void ff_put_vp8_epel8_h4_sse2  (uint8_t *dst, int dststride,
+                                       uint8_t *src, int srcstride,
+                                       int height, int mx, int my);
+extern void ff_put_vp8_epel8_h6_sse2  (uint8_t *dst, int dststride,
+                                       uint8_t *src, int srcstride,
+                                       int height, int mx, int my);
+extern void ff_put_vp8_epel8_v4_sse2  (uint8_t *dst, int dststride,
+                                       uint8_t *src, int srcstride,
+                                       int height, int mx, int my);
+extern void ff_put_vp8_epel8_v6_sse2  (uint8_t *dst, int dststride,
+                                       uint8_t *src, int srcstride,
+                                       int height, int mx, int my);
+
+extern void ff_put_vp8_epel4_h4_ssse3 (uint8_t *dst, int dststride,
+                                       uint8_t *src, int srcstride,
+                                       int height, int mx, int my);
+extern void ff_put_vp8_epel4_h6_ssse3 (uint8_t *dst, int dststride,
+                                       uint8_t *src, int srcstride,
+                                       int height, int mx, int my);
+extern void ff_put_vp8_epel4_v4_ssse3 (uint8_t *dst, int dststride,
+                                       uint8_t *src, int srcstride,
+                                       int height, int mx, int my);
+extern void ff_put_vp8_epel4_v6_ssse3 (uint8_t *dst, int dststride,
+                                       uint8_t *src, int srcstride,
+                                       int height, int mx, int my);
+extern void ff_put_vp8_epel8_h4_ssse3 (uint8_t *dst, int dststride,
+                                       uint8_t *src, int srcstride,
+                                       int height, int mx, int my);
+extern void ff_put_vp8_epel8_h6_ssse3 (uint8_t *dst, int dststride,
+                                       uint8_t *src, int srcstride,
+                                       int height, int mx, int my);
+extern void ff_put_vp8_epel8_v4_ssse3 (uint8_t *dst, int dststride,
+                                       uint8_t *src, int srcstride,
+                                       int height, int mx, int my);
+extern void ff_put_vp8_epel8_v6_ssse3 (uint8_t *dst, int dststride,
+                                       uint8_t *src, int srcstride,
+                                       int height, int mx, int my);
+
+extern void ff_put_vp8_bilinear4_h_mmxext(uint8_t *dst, int dststride,
+                                          uint8_t *src, int srcstride,
+                                          int height, int mx, int my);
+extern void ff_put_vp8_bilinear8_h_sse2  (uint8_t *dst, int dststride,
+                                          uint8_t *src, int srcstride,
+                                          int height, int mx, int my);
+extern void ff_put_vp8_bilinear4_h_ssse3 (uint8_t *dst, int dststride,
+                                          uint8_t *src, int srcstride,
+                                          int height, int mx, int my);
+extern void ff_put_vp8_bilinear8_h_ssse3 (uint8_t *dst, int dststride,
+                                          uint8_t *src, int srcstride,
+                                          int height, int mx, int my);
+
+extern void ff_put_vp8_bilinear4_v_mmxext(uint8_t *dst, int dststride,
+                                          uint8_t *src, int srcstride,
+                                          int height, int mx, int my);
+extern void ff_put_vp8_bilinear8_v_sse2  (uint8_t *dst, int dststride,
+                                          uint8_t *src, int srcstride,
+                                          int height, int mx, int my);
+extern void ff_put_vp8_bilinear4_v_ssse3 (uint8_t *dst, int dststride,
+                                          uint8_t *src, int srcstride,
+                                          int height, int mx, int my);
+extern void ff_put_vp8_bilinear8_v_ssse3 (uint8_t *dst, int dststride,
+                                          uint8_t *src, int srcstride,
+                                          int height, int mx, int my);
+
+
+extern void ff_put_vp8_pixels8_mmx (uint8_t *dst, int dststride,
+                                    uint8_t *src, int srcstride,
+                                    int height, int mx, int my);
+extern void ff_put_vp8_pixels16_mmx(uint8_t *dst, int dststride,
+                                    uint8_t *src, int srcstride,
+                                    int height, int mx, int my);
+extern void ff_put_vp8_pixels16_sse(uint8_t *dst, int dststride,
+                                    uint8_t *src, int srcstride,
+                                    int height, int mx, int my);
+
+#define TAP_W16(OPT, FILTERTYPE, TAPTYPE) \
+static void ff_put_vp8_ ## FILTERTYPE ## 16_ ## TAPTYPE ## _ ## OPT( \
+    uint8_t *dst,  int dststride, uint8_t *src, \
+    int srcstride, int height, int mx, int my) \
+{ \
+    ff_put_vp8_ ## FILTERTYPE ## 8_ ## TAPTYPE ## _ ## OPT( \
+        dst,     dststride, src,     srcstride, height, mx, my); \
+    ff_put_vp8_ ## FILTERTYPE ## 8_ ## TAPTYPE ## _ ## OPT( \
+        dst + 8, dststride, src + 8, srcstride, height, mx, my); \
+}
+#define TAP_W8(OPT, FILTERTYPE, TAPTYPE) \
+static void ff_put_vp8_ ## FILTERTYPE ## 8_ ## TAPTYPE ## _ ## OPT( \
+    uint8_t *dst,  int dststride, uint8_t *src, \
+    int srcstride, int height, int mx, int my) \
+{ \
+    ff_put_vp8_ ## FILTERTYPE ## 4_ ## TAPTYPE ## _ ## OPT( \
+        dst,     dststride, src,     srcstride, height, mx, my); \
+    ff_put_vp8_ ## FILTERTYPE ## 4_ ## TAPTYPE ## _ ## OPT( \
+        dst + 4, dststride, src + 4, srcstride, height, mx, my); \
+}
+
+TAP_W8 (mmxext, epel, h4)
+TAP_W8 (mmxext, epel, h6)
+TAP_W16(mmxext, epel, h6)
+TAP_W8 (mmxext, epel, v4)
+TAP_W8 (mmxext, epel, v6)
+TAP_W16(mmxext, epel, v6)
+TAP_W8 (mmxext, bilinear, h)
+TAP_W16(mmxext, bilinear, h)
+TAP_W8 (mmxext, bilinear, v)
+TAP_W16(mmxext, bilinear, v)
+
+TAP_W16(sse2,   epel, h6)
+TAP_W16(sse2,   epel, v6)
+TAP_W16(sse2,   bilinear, h)
+TAP_W16(sse2,   bilinear, v)
+
+TAP_W16(ssse3,  epel, h6)
+TAP_W16(ssse3,  epel, v6)
+TAP_W16(ssse3,  bilinear, h)
+TAP_W16(ssse3,  bilinear, v)
+
+#define HVTAP(OPT, ALIGN, TAPNUMX, TAPNUMY, SIZE, MAXHEIGHT) \
+static void ff_put_vp8_epel ## SIZE ## _h ## TAPNUMX ## v ## TAPNUMY ## _ ## OPT( \
+    uint8_t *dst, int dststride, uint8_t *src, \
+    int srcstride, int height, int mx, int my) \
+{ \
+    DECLARE_ALIGNED(ALIGN, uint8_t, tmp)[SIZE * (MAXHEIGHT + TAPNUMY - 1)]; \
+    uint8_t *tmpptr = tmp + SIZE * (TAPNUMY / 2 - 1); \
+    src -= srcstride * (TAPNUMY / 2 - 1); \
+    ff_put_vp8_epel ## SIZE ## _h ## TAPNUMX ## _ ## OPT( \
+        tmp, SIZE,      src,    srcstride, height + TAPNUMY - 1, mx, my); \
+    ff_put_vp8_epel ## SIZE ## _v ## TAPNUMY ## _ ## OPT( \
+        dst, dststride, tmpptr, SIZE,      height,               mx, my); \
+}
+
+#define HVTAPMMX(x, y) \
+HVTAP(mmxext, 8, x, y,  4,  8) \
+HVTAP(mmxext, 8, x, y,  8, 16)
+
+HVTAPMMX(4, 4)
+HVTAPMMX(4, 6)
+HVTAPMMX(6, 4)
+HVTAPMMX(6, 6)
+HVTAP(mmxext, 8, 6, 6, 16, 16)
+
+#define HVTAPSSE2(x, y, w) \
+HVTAP(sse2,  16, x, y, w, 16) \
+HVTAP(ssse3, 16, x, y, w, 16)
+
+HVTAPSSE2(4, 4, 8)
+HVTAPSSE2(4, 6, 8)
+HVTAPSSE2(6, 4, 8)
+HVTAPSSE2(6, 6, 8)
+HVTAPSSE2(6, 6, 16)
+
+HVTAP(ssse3, 16, 4, 4, 4, 8)
+HVTAP(ssse3, 16, 4, 6, 4, 8)
+HVTAP(ssse3, 16, 6, 4, 4, 8)
+HVTAP(ssse3, 16, 6, 6, 4, 8)
+
+#define HVBILIN(OPT, ALIGN, SIZE, MAXHEIGHT) \
+static void ff_put_vp8_bilinear ## SIZE ## _hv_ ## OPT( \
+    uint8_t *dst, int dststride, uint8_t *src, \
+    int srcstride, int height, int mx, int my) \
+{ \
+    DECLARE_ALIGNED(ALIGN, uint8_t, tmp)[SIZE * (MAXHEIGHT + 2)]; \
+    ff_put_vp8_bilinear ## SIZE ## _h_ ## OPT( \
+        tmp, SIZE,      src, srcstride, height + 1, mx, my); \
+    ff_put_vp8_bilinear ## SIZE ## _v_ ## OPT( \
+        dst, dststride, tmp, SIZE,      height,     mx, my); \
+}
+
+HVBILIN(mmxext, 8,  4,  8)
+HVBILIN(mmxext, 8,  8, 16)
+HVBILIN(mmxext, 8, 16, 16)
+HVBILIN(sse2,   8,  8, 16)
+HVBILIN(sse2,   8, 16, 16)
+HVBILIN(ssse3,  8,  4,  8)
+HVBILIN(ssse3,  8,  8, 16)
+HVBILIN(ssse3,  8, 16, 16)
+
+extern void ff_vp8_idct_dc_add_mmx(uint8_t *dst, DCTELEM block[16], int stride);
+extern void ff_vp8_idct_dc_add_sse4(uint8_t *dst, DCTELEM block[16], int stride);
+extern void ff_vp8_idct_dc_add4y_mmx(uint8_t *dst, DCTELEM block[4][16], int stride);
+extern void ff_vp8_idct_dc_add4y_sse2(uint8_t *dst, DCTELEM block[4][16], int stride);
+extern void ff_vp8_idct_dc_add4uv_mmx(uint8_t *dst, DCTELEM block[2][16], int stride);
+extern void ff_vp8_luma_dc_wht_mmx(DCTELEM block[4][4][16], DCTELEM dc[16]);
+extern void ff_vp8_luma_dc_wht_sse(DCTELEM block[4][4][16], DCTELEM dc[16]);
+extern void ff_vp8_idct_add_mmx(uint8_t *dst, DCTELEM block[16], int stride);
+extern void ff_vp8_idct_add_sse(uint8_t *dst, DCTELEM block[16], int stride);
+
+#define DECLARE_LOOP_FILTER(NAME)\
+extern void ff_vp8_v_loop_filter_simple_ ## NAME(uint8_t *dst, int stride, int flim);\
+extern void ff_vp8_h_loop_filter_simple_ ## NAME(uint8_t *dst, int stride, int flim);\
+extern void ff_vp8_v_loop_filter16y_inner_ ## NAME (uint8_t *dst, int stride,\
+                                                    int e, int i, int hvt);\
+extern void ff_vp8_h_loop_filter16y_inner_ ## NAME (uint8_t *dst, int stride,\
+                                                    int e, int i, int hvt);\
+extern void ff_vp8_v_loop_filter8uv_inner_ ## NAME (uint8_t *dstU, uint8_t *dstV,\
+                                                    int s, int e, int i, int hvt);\
+extern void ff_vp8_h_loop_filter8uv_inner_ ## NAME (uint8_t *dstU, uint8_t *dstV,\
+                                                    int s, int e, int i, int hvt);\
+extern void ff_vp8_v_loop_filter16y_mbedge_ ## NAME(uint8_t *dst, int stride,\
+                                                    int e, int i, int hvt);\
+extern void ff_vp8_h_loop_filter16y_mbedge_ ## NAME(uint8_t *dst, int stride,\
+                                                    int e, int i, int hvt);\
+extern void ff_vp8_v_loop_filter8uv_mbedge_ ## NAME(uint8_t *dstU, uint8_t *dstV,\
+                                                    int s, int e, int i, int hvt);\
+extern void ff_vp8_h_loop_filter8uv_mbedge_ ## NAME(uint8_t *dstU, uint8_t *dstV,\
+                                                    int s, int e, int i, int hvt);
+
+DECLARE_LOOP_FILTER(mmx)
+DECLARE_LOOP_FILTER(mmxext)
+DECLARE_LOOP_FILTER(sse2)
+DECLARE_LOOP_FILTER(ssse3)
+DECLARE_LOOP_FILTER(sse4)
+
+#endif
+
+#define VP8_LUMA_MC_FUNC(IDX, SIZE, OPT) \
+    c->put_vp8_epel_pixels_tab[IDX][0][2] = ff_put_vp8_epel ## SIZE ## _h6_ ## OPT; \
+    c->put_vp8_epel_pixels_tab[IDX][2][0] = ff_put_vp8_epel ## SIZE ## _v6_ ## OPT; \
+    c->put_vp8_epel_pixels_tab[IDX][2][2] = ff_put_vp8_epel ## SIZE ## _h6v6_ ## OPT
+
+#define VP8_MC_FUNC(IDX, SIZE, OPT) \
+    c->put_vp8_epel_pixels_tab[IDX][0][1] = ff_put_vp8_epel ## SIZE ## _h4_ ## OPT; \
+    c->put_vp8_epel_pixels_tab[IDX][1][0] = ff_put_vp8_epel ## SIZE ## _v4_ ## OPT; \
+    c->put_vp8_epel_pixels_tab[IDX][1][1] = ff_put_vp8_epel ## SIZE ## _h4v4_ ## OPT; \
+    c->put_vp8_epel_pixels_tab[IDX][1][2] = ff_put_vp8_epel ## SIZE ## _h6v4_ ## OPT; \
+    c->put_vp8_epel_pixels_tab[IDX][2][1] = ff_put_vp8_epel ## SIZE ## _h4v6_ ## OPT; \
+    VP8_LUMA_MC_FUNC(IDX, SIZE, OPT)
+
+#define VP8_BILINEAR_MC_FUNC(IDX, SIZE, OPT) \
+    c->put_vp8_bilinear_pixels_tab[IDX][0][1] = ff_put_vp8_bilinear ## SIZE ## _h_ ## OPT; \
+    c->put_vp8_bilinear_pixels_tab[IDX][0][2] = ff_put_vp8_bilinear ## SIZE ## _h_ ## OPT; \
+    c->put_vp8_bilinear_pixels_tab[IDX][1][0] = ff_put_vp8_bilinear ## SIZE ## _v_ ## OPT; \
+    c->put_vp8_bilinear_pixels_tab[IDX][1][1] = ff_put_vp8_bilinear ## SIZE ## _hv_ ## OPT; \
+    c->put_vp8_bilinear_pixels_tab[IDX][1][2] = ff_put_vp8_bilinear ## SIZE ## _hv_ ## OPT; \
+    c->put_vp8_bilinear_pixels_tab[IDX][2][0] = ff_put_vp8_bilinear ## SIZE ## _v_ ## OPT; \
+    c->put_vp8_bilinear_pixels_tab[IDX][2][1] = ff_put_vp8_bilinear ## SIZE ## _hv_ ## OPT; \
+    c->put_vp8_bilinear_pixels_tab[IDX][2][2] = ff_put_vp8_bilinear ## SIZE ## _hv_ ## OPT
+
+
+av_cold void ff_vp8dsp_init_x86(VP8DSPContext* c)
+{
+    int mm_flags = av_get_cpu_flags();
+
+#if HAVE_YASM
+    if (mm_flags & AV_CPU_FLAG_MMX) {
+        c->vp8_idct_dc_add    = ff_vp8_idct_dc_add_mmx;
+        c->vp8_idct_dc_add4y  = ff_vp8_idct_dc_add4y_mmx;
+        c->vp8_idct_dc_add4uv = ff_vp8_idct_dc_add4uv_mmx;
+        c->vp8_idct_add       = ff_vp8_idct_add_mmx;
+        c->vp8_luma_dc_wht    = ff_vp8_luma_dc_wht_mmx;
+        c->put_vp8_epel_pixels_tab[0][0][0]     =
+        c->put_vp8_bilinear_pixels_tab[0][0][0] = ff_put_vp8_pixels16_mmx;
+        c->put_vp8_epel_pixels_tab[1][0][0]     =
+        c->put_vp8_bilinear_pixels_tab[1][0][0] = ff_put_vp8_pixels8_mmx;
+
+        c->vp8_v_loop_filter_simple = ff_vp8_v_loop_filter_simple_mmx;
+        c->vp8_h_loop_filter_simple = ff_vp8_h_loop_filter_simple_mmx;
+
+        c->vp8_v_loop_filter16y_inner = ff_vp8_v_loop_filter16y_inner_mmx;
+        c->vp8_h_loop_filter16y_inner = ff_vp8_h_loop_filter16y_inner_mmx;
+        c->vp8_v_loop_filter8uv_inner = ff_vp8_v_loop_filter8uv_inner_mmx;
+        c->vp8_h_loop_filter8uv_inner = ff_vp8_h_loop_filter8uv_inner_mmx;
+
+        c->vp8_v_loop_filter16y       = ff_vp8_v_loop_filter16y_mbedge_mmx;
+        c->vp8_h_loop_filter16y       = ff_vp8_h_loop_filter16y_mbedge_mmx;
+        c->vp8_v_loop_filter8uv       = ff_vp8_v_loop_filter8uv_mbedge_mmx;
+        c->vp8_h_loop_filter8uv       = ff_vp8_h_loop_filter8uv_mbedge_mmx;
+    }
+
+    /* note that 4-tap width=16 functions are missing because w=16
+     * is only used for luma, and luma is always a copy or sixtap. */
+    if (mm_flags & AV_CPU_FLAG_MMX2) {
+        VP8_LUMA_MC_FUNC(0, 16, mmxext);
+        VP8_MC_FUNC(1, 8, mmxext);
+        VP8_MC_FUNC(2, 4, mmxext);
+        VP8_BILINEAR_MC_FUNC(0, 16, mmxext);
+        VP8_BILINEAR_MC_FUNC(1, 8, mmxext);
+        VP8_BILINEAR_MC_FUNC(2, 4, mmxext);
+
+        c->vp8_v_loop_filter_simple = ff_vp8_v_loop_filter_simple_mmxext;
+        c->vp8_h_loop_filter_simple = ff_vp8_h_loop_filter_simple_mmxext;
+
+        c->vp8_v_loop_filter16y_inner = ff_vp8_v_loop_filter16y_inner_mmxext;
+        c->vp8_h_loop_filter16y_inner = ff_vp8_h_loop_filter16y_inner_mmxext;
+        c->vp8_v_loop_filter8uv_inner = ff_vp8_v_loop_filter8uv_inner_mmxext;
+        c->vp8_h_loop_filter8uv_inner = ff_vp8_h_loop_filter8uv_inner_mmxext;
+
+        c->vp8_v_loop_filter16y       = ff_vp8_v_loop_filter16y_mbedge_mmxext;
+        c->vp8_h_loop_filter16y       = ff_vp8_h_loop_filter16y_mbedge_mmxext;
+        c->vp8_v_loop_filter8uv       = ff_vp8_v_loop_filter8uv_mbedge_mmxext;
+        c->vp8_h_loop_filter8uv       = ff_vp8_h_loop_filter8uv_mbedge_mmxext;
+    }
+
+    if (mm_flags & AV_CPU_FLAG_SSE) {
+        c->vp8_idct_add                         = ff_vp8_idct_add_sse;
+        c->vp8_luma_dc_wht                      = ff_vp8_luma_dc_wht_sse;
+        c->put_vp8_epel_pixels_tab[0][0][0]     =
+        c->put_vp8_bilinear_pixels_tab[0][0][0] = ff_put_vp8_pixels16_sse;
+    }
+
+    if (mm_flags & (AV_CPU_FLAG_SSE2|AV_CPU_FLAG_SSE2SLOW)) {
+        VP8_LUMA_MC_FUNC(0, 16, sse2);
+        VP8_MC_FUNC(1, 8, sse2);
+        VP8_BILINEAR_MC_FUNC(0, 16, sse2);
+        VP8_BILINEAR_MC_FUNC(1, 8, sse2);
+
+        c->vp8_v_loop_filter_simple = ff_vp8_v_loop_filter_simple_sse2;
+
+        c->vp8_v_loop_filter16y_inner = ff_vp8_v_loop_filter16y_inner_sse2;
+        c->vp8_v_loop_filter8uv_inner = ff_vp8_v_loop_filter8uv_inner_sse2;
+
+        c->vp8_v_loop_filter16y       = ff_vp8_v_loop_filter16y_mbedge_sse2;
+        c->vp8_v_loop_filter8uv       = ff_vp8_v_loop_filter8uv_mbedge_sse2;
+    }
+
+    if (mm_flags & AV_CPU_FLAG_SSE2) {
+        c->vp8_idct_dc_add4y          = ff_vp8_idct_dc_add4y_sse2;
+
+        c->vp8_h_loop_filter_simple = ff_vp8_h_loop_filter_simple_sse2;
+
+        c->vp8_h_loop_filter16y_inner = ff_vp8_h_loop_filter16y_inner_sse2;
+        c->vp8_h_loop_filter8uv_inner = ff_vp8_h_loop_filter8uv_inner_sse2;
+
+        c->vp8_h_loop_filter16y       = ff_vp8_h_loop_filter16y_mbedge_sse2;
+        c->vp8_h_loop_filter8uv       = ff_vp8_h_loop_filter8uv_mbedge_sse2;
+    }
+
+    if (mm_flags & AV_CPU_FLAG_SSSE3) {
+        VP8_LUMA_MC_FUNC(0, 16, ssse3);
+        VP8_MC_FUNC(1, 8, ssse3);
+        VP8_MC_FUNC(2, 4, ssse3);
+        VP8_BILINEAR_MC_FUNC(0, 16, ssse3);
+        VP8_BILINEAR_MC_FUNC(1, 8, ssse3);
+        VP8_BILINEAR_MC_FUNC(2, 4, ssse3);
+
+        c->vp8_v_loop_filter_simple = ff_vp8_v_loop_filter_simple_ssse3;
+        c->vp8_h_loop_filter_simple = ff_vp8_h_loop_filter_simple_ssse3;
+
+        c->vp8_v_loop_filter16y_inner = ff_vp8_v_loop_filter16y_inner_ssse3;
+        c->vp8_h_loop_filter16y_inner = ff_vp8_h_loop_filter16y_inner_ssse3;
+        c->vp8_v_loop_filter8uv_inner = ff_vp8_v_loop_filter8uv_inner_ssse3;
+        c->vp8_h_loop_filter8uv_inner = ff_vp8_h_loop_filter8uv_inner_ssse3;
+
+        c->vp8_v_loop_filter16y       = ff_vp8_v_loop_filter16y_mbedge_ssse3;
+        c->vp8_h_loop_filter16y       = ff_vp8_h_loop_filter16y_mbedge_ssse3;
+        c->vp8_v_loop_filter8uv       = ff_vp8_v_loop_filter8uv_mbedge_ssse3;
+        c->vp8_h_loop_filter8uv       = ff_vp8_h_loop_filter8uv_mbedge_ssse3;
+    }
+
+    if (mm_flags & AV_CPU_FLAG_SSE4) {
+        c->vp8_idct_dc_add                  = ff_vp8_idct_dc_add_sse4;
+
+        c->vp8_h_loop_filter_simple   = ff_vp8_h_loop_filter_simple_sse4;
+        c->vp8_h_loop_filter16y       = ff_vp8_h_loop_filter16y_mbedge_sse4;
+        c->vp8_h_loop_filter8uv       = ff_vp8_h_loop_filter8uv_mbedge_sse4;
+    }
+#endif
+}
diff --git a/libavcodec/x86/vp8dsp.asm b/libavcodec/x86/vp8dsp.asm
new file mode 100644
index 0000000..12e592f
--- /dev/null
+++ b/libavcodec/x86/vp8dsp.asm
@@ -0,0 +1,2858 @@
+;******************************************************************************
+;* VP8 MMXEXT optimizations
+;* Copyright (c) 2010 Ronald S. Bultje <rsbultje at gmail.com>
+;* Copyright (c) 2010 Jason Garrett-Glaser <darkshikari at gmail.com>
+;*
+;* This file is part of Libav.
+;*
+;* Libav is free software; you can redistribute it and/or
+;* modify it under the terms of the GNU Lesser General Public
+;* License as published by the Free Software Foundation; either
+;* version 2.1 of the License, or (at your option) any later version.
+;*
+;* Libav is distributed in the hope that it will be useful,
+;* but WITHOUT ANY WARRANTY; without even the implied warranty of
+;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+;* Lesser General Public License for more details.
+;*
+;* You should have received a copy of the GNU Lesser General Public
+;* License along with Libav; if not, write to the Free Software
+;* 51, Inc., Foundation Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+;******************************************************************************
+
+%include "x86inc.asm"
+%include "x86util.asm"
+
+SECTION_RODATA
+
+fourtap_filter_hw_m: times 4 dw  -6, 123
+                     times 4 dw  12,  -1
+                     times 4 dw  -9,  93
+                     times 4 dw  50,  -6
+                     times 4 dw  -6,  50
+                     times 4 dw  93,  -9
+                     times 4 dw  -1,  12
+                     times 4 dw 123,  -6
+
+sixtap_filter_hw_m:  times 4 dw   2, -11
+                     times 4 dw 108,  36
+                     times 4 dw  -8,   1
+                     times 4 dw   3, -16
+                     times 4 dw  77,  77
+                     times 4 dw -16,   3
+                     times 4 dw   1,  -8
+                     times 4 dw  36, 108
+                     times 4 dw -11,   2
+
+fourtap_filter_hb_m: times 8 db  -6, 123
+                     times 8 db  12,  -1
+                     times 8 db  -9,  93
+                     times 8 db  50,  -6
+                     times 8 db  -6,  50
+                     times 8 db  93,  -9
+                     times 8 db  -1,  12
+                     times 8 db 123,  -6
+
+sixtap_filter_hb_m:  times 8 db   2,   1
+                     times 8 db -11, 108
+                     times 8 db  36,  -8
+                     times 8 db   3,   3
+                     times 8 db -16,  77
+                     times 8 db  77, -16
+                     times 8 db   1,   2
+                     times 8 db  -8,  36
+                     times 8 db 108, -11
+
+fourtap_filter_v_m:  times 8 dw  -6
+                     times 8 dw 123
+                     times 8 dw  12
+                     times 8 dw  -1
+                     times 8 dw  -9
+                     times 8 dw  93
+                     times 8 dw  50
+                     times 8 dw  -6
+                     times 8 dw  -6
+                     times 8 dw  50
+                     times 8 dw  93
+                     times 8 dw  -9
+                     times 8 dw  -1
+                     times 8 dw  12
+                     times 8 dw 123
+                     times 8 dw  -6
+
+sixtap_filter_v_m:   times 8 dw   2
+                     times 8 dw -11
+                     times 8 dw 108
+                     times 8 dw  36
+                     times 8 dw  -8
+                     times 8 dw   1
+                     times 8 dw   3
+                     times 8 dw -16
+                     times 8 dw  77
+                     times 8 dw  77
+                     times 8 dw -16
+                     times 8 dw   3
+                     times 8 dw   1
+                     times 8 dw  -8
+                     times 8 dw  36
+                     times 8 dw 108
+                     times 8 dw -11
+                     times 8 dw   2
+
+bilinear_filter_vw_m: times 8 dw 1
+                      times 8 dw 2
+                      times 8 dw 3
+                      times 8 dw 4
+                      times 8 dw 5
+                      times 8 dw 6
+                      times 8 dw 7
+
+bilinear_filter_vb_m: times 8 db 7, 1
+                      times 8 db 6, 2
+                      times 8 db 5, 3
+                      times 8 db 4, 4
+                      times 8 db 3, 5
+                      times 8 db 2, 6
+                      times 8 db 1, 7
+
+%ifdef PIC
+%define fourtap_filter_hw    r11
+%define sixtap_filter_hw     r11
+%define fourtap_filter_hb    r11
+%define sixtap_filter_hb     r11
+%define fourtap_filter_v     r11
+%define sixtap_filter_v      r11
+%define bilinear_filter_vw   r11
+%define bilinear_filter_vb   r11
+%else
+%define fourtap_filter_hw fourtap_filter_hw_m
+%define sixtap_filter_hw  sixtap_filter_hw_m
+%define fourtap_filter_hb fourtap_filter_hb_m
+%define sixtap_filter_hb  sixtap_filter_hb_m
+%define fourtap_filter_v  fourtap_filter_v_m
+%define sixtap_filter_v   sixtap_filter_v_m
+%define bilinear_filter_vw bilinear_filter_vw_m
+%define bilinear_filter_vb bilinear_filter_vb_m
+%endif
+
+filter_h2_shuf:  db 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5,  6, 6,  7,  7,  8
+filter_h4_shuf:  db 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7,  8, 8,  9,  9, 10
+
+filter_h6_shuf1: db 0, 5, 1, 6, 2, 7, 3, 8, 4, 9, 5, 10, 6, 11,  7, 12
+filter_h6_shuf2: db 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,  7, 7,  8,  8,  9
+filter_h6_shuf3: db 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8,  9, 9, 10, 10, 11
+
+pw_20091: times 4 dw 20091
+pw_17734: times 4 dw 17734
+
+pb_27_63: times 8 db 27, 63
+pb_18_63: times 8 db 18, 63
+pb_9_63:  times 8 db  9, 63
+
+cextern pb_1
+cextern pw_3
+cextern pb_3
+cextern pw_4
+cextern pb_4
+cextern pw_9
+cextern pw_18
+cextern pw_27
+cextern pw_63
+cextern pw_64
+cextern pb_80
+cextern pb_F8
+cextern pb_FE
+
+SECTION .text
+
+;-----------------------------------------------------------------------------
+; subpel MC functions:
+;
+; void put_vp8_epel<size>_h<htap>v<vtap>_<opt>(uint8_t *dst, int deststride,
+;                                              uint8_t *src, int srcstride,
+;                                              int height,   int mx, int my);
+;-----------------------------------------------------------------------------
+
+%macro FILTER_SSSE3 3
+cglobal put_vp8_epel%1_h6_ssse3, 6, 6, %2
+    lea      r5d, [r5*3]
+    mova      m3, [filter_h6_shuf2]
+    mova      m4, [filter_h6_shuf3]
+%ifdef PIC
+    lea      r11, [sixtap_filter_hb_m]
+%endif
+    mova      m5, [sixtap_filter_hb+r5*8-48] ; set up 6tap filter in bytes
+    mova      m6, [sixtap_filter_hb+r5*8-32]
+    mova      m7, [sixtap_filter_hb+r5*8-16]
+
+.nextrow
+    movu      m0, [r2-2]
+    mova      m1, m0
+    mova      m2, m0
+%ifidn %1, 4
+; For epel4, we need 9 bytes, but only 8 get loaded; to compensate, do the
+; shuffle with a memory operand
+    punpcklbw m0, [r2+3]
+%else
+    pshufb    m0, [filter_h6_shuf1]
+%endif
+    pshufb    m1, m3
+    pshufb    m2, m4
+    pmaddubsw m0, m5
+    pmaddubsw m1, m6
+    pmaddubsw m2, m7
+    paddsw    m0, m1
+    paddsw    m0, m2
+    paddsw    m0, [pw_64]
+    psraw     m0, 7
+    packuswb  m0, m0
+    movh    [r0], m0        ; store
+
+    ; go to next line
+    add       r0, r1
+    add       r2, r3
+    dec      r4d            ; next row
+    jg .nextrow
+    REP_RET
+
+cglobal put_vp8_epel%1_h4_ssse3, 6, 6, %3
+    shl      r5d, 4
+    mova      m2, [pw_64]
+    mova      m3, [filter_h2_shuf]
+    mova      m4, [filter_h4_shuf]
+%ifdef PIC
+    lea      r11, [fourtap_filter_hb_m]
+%endif
+    mova      m5, [fourtap_filter_hb+r5-16] ; set up 4tap filter in bytes
+    mova      m6, [fourtap_filter_hb+r5]
+
+.nextrow
+    movu      m0, [r2-1]
+    mova      m1, m0
+    pshufb    m0, m3
+    pshufb    m1, m4
+    pmaddubsw m0, m5
+    pmaddubsw m1, m6
+    paddsw    m0, m2
+    paddsw    m0, m1
+    psraw     m0, 7
+    packuswb  m0, m0
+    movh    [r0], m0        ; store
+
+    ; go to next line
+    add       r0, r1
+    add       r2, r3
+    dec      r4d            ; next row
+    jg .nextrow
+    REP_RET
+
+cglobal put_vp8_epel%1_v4_ssse3, 7, 7, %2
+    shl      r6d, 4
+%ifdef PIC
+    lea      r11, [fourtap_filter_hb_m]
+%endif
+    mova      m5, [fourtap_filter_hb+r6-16]
+    mova      m6, [fourtap_filter_hb+r6]
+    mova      m7, [pw_64]
+
+    ; read 3 lines
+    sub       r2, r3
+    movh      m0, [r2]
+    movh      m1, [r2+  r3]
+    movh      m2, [r2+2*r3]
+    add       r2, r3
+
+.nextrow
+    movh      m3, [r2+2*r3]                ; read new row
+    mova      m4, m0
+    mova      m0, m1
+    punpcklbw m4, m1
+    mova      m1, m2
+    punpcklbw m2, m3
+    pmaddubsw m4, m5
+    pmaddubsw m2, m6
+    paddsw    m4, m2
+    mova      m2, m3
+    paddsw    m4, m7
+    psraw     m4, 7
+    packuswb  m4, m4
+    movh    [r0], m4
+
+    ; go to next line
+    add        r0, r1
+    add        r2, r3
+    dec       r4d                          ; next row
+    jg .nextrow
+    REP_RET
+
+cglobal put_vp8_epel%1_v6_ssse3, 7, 7, %2
+    lea      r6d, [r6*3]
+%ifdef PIC
+    lea      r11, [sixtap_filter_hb_m]
+%endif
+    lea       r6, [sixtap_filter_hb+r6*8]
+
+    ; read 5 lines
+    sub       r2, r3
+    sub       r2, r3
+    movh      m0, [r2]
+    movh      m1, [r2+r3]
+    movh      m2, [r2+r3*2]
+    lea       r2, [r2+r3*2]
+    add       r2, r3
+    movh      m3, [r2]
+    movh      m4, [r2+r3]
+
+.nextrow
+    movh      m5, [r2+2*r3]                ; read new row
+    mova      m6, m0
+    punpcklbw m6, m5
+    mova      m0, m1
+    punpcklbw m1, m2
+    mova      m7, m3
+    punpcklbw m7, m4
+    pmaddubsw m6, [r6-48]
+    pmaddubsw m1, [r6-32]
+    pmaddubsw m7, [r6-16]
+    paddsw    m6, m1
+    paddsw    m6, m7
+    mova      m1, m2
+    paddsw    m6, [pw_64]
+    mova      m2, m3
+    psraw     m6, 7
+    mova      m3, m4
+    packuswb  m6, m6
+    mova      m4, m5
+    movh    [r0], m6
+
+    ; go to next line
+    add        r0, r1
+    add        r2, r3
+    dec       r4d                          ; next row
+    jg .nextrow
+    REP_RET
+%endmacro
+
+INIT_MMX
+FILTER_SSSE3 4, 0, 0
+INIT_XMM
+FILTER_SSSE3 8, 8, 7
+
+; 4x4 block, H-only 4-tap filter
+cglobal put_vp8_epel4_h4_mmxext, 6, 6
+    shl       r5d, 4
+%ifdef PIC
+    lea       r11, [fourtap_filter_hw_m]
+%endif
+    movq      mm4, [fourtap_filter_hw+r5-16] ; set up 4tap filter in words
+    movq      mm5, [fourtap_filter_hw+r5]
+    movq      mm7, [pw_64]
+    pxor      mm6, mm6
+
+.nextrow
+    movq      mm1, [r2-1]                  ; (ABCDEFGH) load 8 horizontal pixels
+
+    ; first set of 2 pixels
+    movq      mm2, mm1                     ; byte ABCD..
+    punpcklbw mm1, mm6                     ; byte->word ABCD
+    pshufw    mm0, mm2, 9                  ; byte CDEF..
+    punpcklbw mm0, mm6                     ; byte->word CDEF
+    pshufw    mm3, mm1, 0x94               ; word ABBC
+    pshufw    mm1, mm0, 0x94               ; word CDDE
+    pmaddwd   mm3, mm4                     ; multiply 2px with F0/F1
+    movq      mm0, mm1                     ; backup for second set of pixels
+    pmaddwd   mm1, mm5                     ; multiply 2px with F2/F3
+    paddd     mm3, mm1                     ; finish 1st 2px
+
+    ; second set of 2 pixels, use backup of above
+    punpckhbw mm2, mm6                     ; byte->word EFGH
+    pmaddwd   mm0, mm4                     ; multiply backed up 2px with F0/F1
+    pshufw    mm1, mm2, 0x94               ; word EFFG
+    pmaddwd   mm1, mm5                     ; multiply 2px with F2/F3
+    paddd     mm0, mm1                     ; finish 2nd 2px
+
+    ; merge two sets of 2 pixels into one set of 4, round/clip/store
+    packssdw  mm3, mm0                     ; merge dword->word (4px)
+    paddsw    mm3, mm7                     ; rounding
+    psraw     mm3, 7
+    packuswb  mm3, mm6                     ; clip and word->bytes
+    movd     [r0], mm3                     ; store
+
+    ; go to next line
+    add        r0, r1
+    add        r2, r3
+    dec       r4d                          ; next row
+    jg .nextrow
+    REP_RET
+
+; 4x4 block, H-only 6-tap filter
+cglobal put_vp8_epel4_h6_mmxext, 6, 6
+    lea       r5d, [r5*3]
+%ifdef PIC
+    lea       r11, [sixtap_filter_hw_m]
+%endif
+    movq      mm4, [sixtap_filter_hw+r5*8-48] ; set up 4tap filter in words
+    movq      mm5, [sixtap_filter_hw+r5*8-32]
+    movq      mm6, [sixtap_filter_hw+r5*8-16]
+    movq      mm7, [pw_64]
+    pxor      mm3, mm3
+
+.nextrow
+    movq      mm1, [r2-2]                  ; (ABCDEFGH) load 8 horizontal pixels
+
+    ; first set of 2 pixels
+    movq      mm2, mm1                     ; byte ABCD..
+    punpcklbw mm1, mm3                     ; byte->word ABCD
+    pshufw    mm0, mm2, 0x9                ; byte CDEF..
+    punpckhbw mm2, mm3                     ; byte->word EFGH
+    punpcklbw mm0, mm3                     ; byte->word CDEF
+    pshufw    mm1, mm1, 0x94               ; word ABBC
+    pshufw    mm2, mm2, 0x94               ; word EFFG
+    pmaddwd   mm1, mm4                     ; multiply 2px with F0/F1
+    pshufw    mm3, mm0, 0x94               ; word CDDE
+    movq      mm0, mm3                     ; backup for second set of pixels
+    pmaddwd   mm3, mm5                     ; multiply 2px with F2/F3
+    paddd     mm1, mm3                     ; add to 1st 2px cache
+    movq      mm3, mm2                     ; backup for second set of pixels
+    pmaddwd   mm2, mm6                     ; multiply 2px with F4/F5
+    paddd     mm1, mm2                     ; finish 1st 2px
+
+    ; second set of 2 pixels, use backup of above
+    movd      mm2, [r2+3]                  ; byte FGHI (prevent overreads)
+    pmaddwd   mm0, mm4                     ; multiply 1st backed up 2px with F0/F1
+    pmaddwd   mm3, mm5                     ; multiply 2nd backed up 2px with F2/F3
+    paddd     mm0, mm3                     ; add to 2nd 2px cache
+    pxor      mm3, mm3
+    punpcklbw mm2, mm3                     ; byte->word FGHI
+    pshufw    mm2, mm2, 0xE9               ; word GHHI
+    pmaddwd   mm2, mm6                     ; multiply 2px with F4/F5
+    paddd     mm0, mm2                     ; finish 2nd 2px
+
+    ; merge two sets of 2 pixels into one set of 4, round/clip/store
+    packssdw  mm1, mm0                     ; merge dword->word (4px)
+    paddsw    mm1, mm7                     ; rounding
+    psraw     mm1, 7
+    packuswb  mm1, mm3                     ; clip and word->bytes
+    movd     [r0], mm1                     ; store
+
+    ; go to next line
+    add        r0, r1
+    add        r2, r3
+    dec       r4d                          ; next row
+    jg .nextrow
+    REP_RET
+
+INIT_XMM
+cglobal put_vp8_epel8_h4_sse2, 6, 6, 10
+    shl      r5d, 5
+%ifdef PIC
+    lea      r11, [fourtap_filter_v_m]
+%endif
+    lea       r5, [fourtap_filter_v+r5-32]
+    pxor      m7, m7
+    mova      m4, [pw_64]
+    mova      m5, [r5+ 0]
+    mova      m6, [r5+16]
+%ifdef m8
+    mova      m8, [r5+32]
+    mova      m9, [r5+48]
+%endif
+.nextrow
+    movq      m0, [r2-1]
+    movq      m1, [r2-0]
+    movq      m2, [r2+1]
+    movq      m3, [r2+2]
+    punpcklbw m0, m7
+    punpcklbw m1, m7
+    punpcklbw m2, m7
+    punpcklbw m3, m7
+    pmullw    m0, m5
+    pmullw    m1, m6
+%ifdef m8
+    pmullw    m2, m8
+    pmullw    m3, m9
+%else
+    pmullw    m2, [r5+32]
+    pmullw    m3, [r5+48]
+%endif
+    paddsw    m0, m1
+    paddsw    m2, m3
+    paddsw    m0, m2
+    paddsw    m0, m4
+    psraw     m0, 7
+    packuswb  m0, m7
+    movh    [r0], m0        ; store
+
+    ; go to next line
+    add       r0, r1
+    add       r2, r3
+    dec      r4d            ; next row
+    jg .nextrow
+    REP_RET
+
+cglobal put_vp8_epel8_h6_sse2, 6, 6, 14
+    lea      r5d, [r5*3]
+    shl      r5d, 4
+%ifdef PIC
+    lea      r11, [sixtap_filter_v_m]
+%endif
+    lea       r5, [sixtap_filter_v+r5-96]
+    pxor      m7, m7
+    mova      m6, [pw_64]
+%ifdef m8
+    mova      m8, [r5+ 0]
+    mova      m9, [r5+16]
+    mova     m10, [r5+32]
+    mova     m11, [r5+48]
+    mova     m12, [r5+64]
+    mova     m13, [r5+80]
+%endif
+.nextrow
+    movq      m0, [r2-2]
+    movq      m1, [r2-1]
+    movq      m2, [r2-0]
+    movq      m3, [r2+1]
+    movq      m4, [r2+2]
+    movq      m5, [r2+3]
+    punpcklbw m0, m7
+    punpcklbw m1, m7
+    punpcklbw m2, m7
+    punpcklbw m3, m7
+    punpcklbw m4, m7
+    punpcklbw m5, m7
+%ifdef m8
+    pmullw    m0, m8
+    pmullw    m1, m9
+    pmullw    m2, m10
+    pmullw    m3, m11
+    pmullw    m4, m12
+    pmullw    m5, m13
+%else
+    pmullw    m0, [r5+ 0]
+    pmullw    m1, [r5+16]
+    pmullw    m2, [r5+32]
+    pmullw    m3, [r5+48]
+    pmullw    m4, [r5+64]
+    pmullw    m5, [r5+80]
+%endif
+    paddsw    m1, m4
+    paddsw    m0, m5
+    paddsw    m1, m2
+    paddsw    m0, m3
+    paddsw    m0, m1
+    paddsw    m0, m6
+    psraw     m0, 7
+    packuswb  m0, m7
+    movh    [r0], m0        ; store
+
+    ; go to next line
+    add       r0, r1
+    add       r2, r3
+    dec      r4d            ; next row
+    jg .nextrow
+    REP_RET
+
+%macro FILTER_V 3
+; 4x4 block, V-only 4-tap filter
+cglobal put_vp8_epel%2_v4_%1, 7, 7, %3
+    shl      r6d, 5
+%ifdef PIC
+    lea      r11, [fourtap_filter_v_m]
+%endif
+    lea       r6, [fourtap_filter_v+r6-32]
+    mova      m6, [pw_64]
+    pxor      m7, m7
+    mova      m5, [r6+48]
+
+    ; read 3 lines
+    sub       r2, r3
+    movh      m0, [r2]
+    movh      m1, [r2+  r3]
+    movh      m2, [r2+2*r3]
+    add       r2, r3
+    punpcklbw m0, m7
+    punpcklbw m1, m7
+    punpcklbw m2, m7
+
+.nextrow
+    ; first calculate negative taps (to prevent losing positive overflows)
+    movh      m4, [r2+2*r3]                ; read new row
+    punpcklbw m4, m7
+    mova      m3, m4
+    pmullw    m0, [r6+0]
+    pmullw    m4, m5
+    paddsw    m4, m0
+
+    ; then calculate positive taps
+    mova      m0, m1
+    pmullw    m1, [r6+16]
+    paddsw    m4, m1
+    mova      m1, m2
+    pmullw    m2, [r6+32]
+    paddsw    m4, m2
+    mova      m2, m3
+
+    ; round/clip/store
+    paddsw    m4, m6
+    psraw     m4, 7
+    packuswb  m4, m7
+    movh    [r0], m4
+
+    ; go to next line
+    add       r0, r1
+    add       r2, r3
+    dec      r4d                           ; next row
+    jg .nextrow
+    REP_RET
+
+
+; 4x4 block, V-only 6-tap filter
+cglobal put_vp8_epel%2_v6_%1, 7, 7, %3
+    shl      r6d, 4
+    lea       r6, [r6*3]
+%ifdef PIC
+    lea      r11, [sixtap_filter_v_m]
+%endif
+    lea       r6, [sixtap_filter_v+r6-96]
+    pxor      m7, m7
+
+    ; read 5 lines
+    sub       r2, r3
+    sub       r2, r3
+    movh      m0, [r2]
+    movh      m1, [r2+r3]
+    movh      m2, [r2+r3*2]
+    lea       r2, [r2+r3*2]
+    add       r2, r3
+    movh      m3, [r2]
+    movh      m4, [r2+r3]
+    punpcklbw m0, m7
+    punpcklbw m1, m7
+    punpcklbw m2, m7
+    punpcklbw m3, m7
+    punpcklbw m4, m7
+
+.nextrow
+    ; first calculate negative taps (to prevent losing positive overflows)
+    mova      m5, m1
+    pmullw    m5, [r6+16]
+    mova      m6, m4
+    pmullw    m6, [r6+64]
+    paddsw    m6, m5
+
+    ; then calculate positive taps
+    movh      m5, [r2+2*r3]                ; read new row
+    punpcklbw m5, m7
+    pmullw    m0, [r6+0]
+    paddsw    m6, m0
+    mova      m0, m1
+    mova      m1, m2
+    pmullw    m2, [r6+32]
+    paddsw    m6, m2
+    mova      m2, m3
+    pmullw    m3, [r6+48]
+    paddsw    m6, m3
+    mova      m3, m4
+    mova      m4, m5
+    pmullw    m5, [r6+80]
+    paddsw    m6, m5
+
+    ; round/clip/store
+    paddsw    m6, [pw_64]
+    psraw     m6, 7
+    packuswb  m6, m7
+    movh    [r0], m6
+
+    ; go to next line
+    add       r0, r1
+    add       r2, r3
+    dec      r4d                           ; next row
+    jg .nextrow
+    REP_RET
+%endmacro
+
+INIT_MMX
+FILTER_V mmxext, 4, 0
+INIT_XMM
+FILTER_V sse2,   8, 8
+
+%macro FILTER_BILINEAR 3
+cglobal put_vp8_bilinear%2_v_%1, 7,7,%3
+    mov      r5d, 8*16
+    shl      r6d, 4
+    sub      r5d, r6d
+%ifdef PIC
+    lea      r11, [bilinear_filter_vw_m]
+%endif
+    pxor      m6, m6
+    mova      m4, [bilinear_filter_vw+r5-16]
+    mova      m5, [bilinear_filter_vw+r6-16]
+.nextrow
+    movh      m0, [r2+r3*0]
+    movh      m1, [r2+r3*1]
+    movh      m3, [r2+r3*2]
+    punpcklbw m0, m6
+    punpcklbw m1, m6
+    punpcklbw m3, m6
+    mova      m2, m1
+    pmullw    m0, m4
+    pmullw    m1, m5
+    pmullw    m2, m4
+    pmullw    m3, m5
+    paddsw    m0, m1
+    paddsw    m2, m3
+    psraw     m0, 2
+    psraw     m2, 2
+    pavgw     m0, m6
+    pavgw     m2, m6
+%ifidn %1, mmxext
+    packuswb  m0, m0
+    packuswb  m2, m2
+    movh [r0+r1*0], m0
+    movh [r0+r1*1], m2
+%else
+    packuswb  m0, m2
+    movh   [r0+r1*0], m0
+    movhps [r0+r1*1], m0
+%endif
+
+    lea       r0, [r0+r1*2]
+    lea       r2, [r2+r3*2]
+    sub      r4d, 2
+    jg .nextrow
+    REP_RET
+
+cglobal put_vp8_bilinear%2_h_%1, 7,7,%3
+    mov      r6d, 8*16
+    shl      r5d, 4
+    sub      r6d, r5d
+%ifdef PIC
+    lea      r11, [bilinear_filter_vw_m]
+%endif
+    pxor      m6, m6
+    mova      m4, [bilinear_filter_vw+r6-16]
+    mova      m5, [bilinear_filter_vw+r5-16]
+.nextrow
+    movh      m0, [r2+r3*0+0]
+    movh      m1, [r2+r3*0+1]
+    movh      m2, [r2+r3*1+0]
+    movh      m3, [r2+r3*1+1]
+    punpcklbw m0, m6
+    punpcklbw m1, m6
+    punpcklbw m2, m6
+    punpcklbw m3, m6
+    pmullw    m0, m4
+    pmullw    m1, m5
+    pmullw    m2, m4
+    pmullw    m3, m5
+    paddsw    m0, m1
+    paddsw    m2, m3
+    psraw     m0, 2
+    psraw     m2, 2
+    pavgw     m0, m6
+    pavgw     m2, m6
+%ifidn %1, mmxext
+    packuswb  m0, m0
+    packuswb  m2, m2
+    movh [r0+r1*0], m0
+    movh [r0+r1*1], m2
+%else
+    packuswb  m0, m2
+    movh   [r0+r1*0], m0
+    movhps [r0+r1*1], m0
+%endif
+
+    lea       r0, [r0+r1*2]
+    lea       r2, [r2+r3*2]
+    sub      r4d, 2
+    jg .nextrow
+    REP_RET
+%endmacro
+
+INIT_MMX
+FILTER_BILINEAR mmxext, 4, 0
+INIT_XMM
+FILTER_BILINEAR   sse2, 8, 7
+
+%macro FILTER_BILINEAR_SSSE3 1
+cglobal put_vp8_bilinear%1_v_ssse3, 7,7
+    shl      r6d, 4
+%ifdef PIC
+    lea      r11, [bilinear_filter_vb_m]
+%endif
+    pxor      m4, m4
+    mova      m3, [bilinear_filter_vb+r6-16]
+.nextrow
+    movh      m0, [r2+r3*0]
+    movh      m1, [r2+r3*1]
+    movh      m2, [r2+r3*2]
+    punpcklbw m0, m1
+    punpcklbw m1, m2
+    pmaddubsw m0, m3
+    pmaddubsw m1, m3
+    psraw     m0, 2
+    psraw     m1, 2
+    pavgw     m0, m4
+    pavgw     m1, m4
+%if mmsize==8
+    packuswb  m0, m0
+    packuswb  m1, m1
+    movh [r0+r1*0], m0
+    movh [r0+r1*1], m1
+%else
+    packuswb  m0, m1
+    movh   [r0+r1*0], m0
+    movhps [r0+r1*1], m0
+%endif
+
+    lea       r0, [r0+r1*2]
+    lea       r2, [r2+r3*2]
+    sub      r4d, 2
+    jg .nextrow
+    REP_RET
+
+cglobal put_vp8_bilinear%1_h_ssse3, 7,7
+    shl      r5d, 4
+%ifdef PIC
+    lea      r11, [bilinear_filter_vb_m]
+%endif
+    pxor      m4, m4
+    mova      m2, [filter_h2_shuf]
+    mova      m3, [bilinear_filter_vb+r5-16]
+.nextrow
+    movu      m0, [r2+r3*0]
+    movu      m1, [r2+r3*1]
+    pshufb    m0, m2
+    pshufb    m1, m2
+    pmaddubsw m0, m3
+    pmaddubsw m1, m3
+    psraw     m0, 2
+    psraw     m1, 2
+    pavgw     m0, m4
+    pavgw     m1, m4
+%if mmsize==8
+    packuswb  m0, m0
+    packuswb  m1, m1
+    movh [r0+r1*0], m0
+    movh [r0+r1*1], m1
+%else
+    packuswb  m0, m1
+    movh   [r0+r1*0], m0
+    movhps [r0+r1*1], m0
+%endif
+
+    lea       r0, [r0+r1*2]
+    lea       r2, [r2+r3*2]
+    sub      r4d, 2
+    jg .nextrow
+    REP_RET
+%endmacro
+
+INIT_MMX
+FILTER_BILINEAR_SSSE3 4
+INIT_XMM
+FILTER_BILINEAR_SSSE3 8
+
+cglobal put_vp8_pixels8_mmx, 5,5
+.nextrow:
+    movq  mm0, [r2+r3*0]
+    movq  mm1, [r2+r3*1]
+    lea    r2, [r2+r3*2]
+    movq [r0+r1*0], mm0
+    movq [r0+r1*1], mm1
+    lea    r0, [r0+r1*2]
+    sub   r4d, 2
+    jg .nextrow
+    REP_RET
+
+cglobal put_vp8_pixels16_mmx, 5,5
+.nextrow:
+    movq  mm0, [r2+r3*0+0]
+    movq  mm1, [r2+r3*0+8]
+    movq  mm2, [r2+r3*1+0]
+    movq  mm3, [r2+r3*1+8]
+    lea    r2, [r2+r3*2]
+    movq [r0+r1*0+0], mm0
+    movq [r0+r1*0+8], mm1
+    movq [r0+r1*1+0], mm2
+    movq [r0+r1*1+8], mm3
+    lea    r0, [r0+r1*2]
+    sub   r4d, 2
+    jg .nextrow
+    REP_RET
+
+cglobal put_vp8_pixels16_sse, 5,5,2
+.nextrow:
+    movups xmm0, [r2+r3*0]
+    movups xmm1, [r2+r3*1]
+    lea     r2, [r2+r3*2]
+    movaps [r0+r1*0], xmm0
+    movaps [r0+r1*1], xmm1
+    lea     r0, [r0+r1*2]
+    sub    r4d, 2
+    jg .nextrow
+    REP_RET
+
+;-----------------------------------------------------------------------------
+; void vp8_idct_dc_add_<opt>(uint8_t *dst, DCTELEM block[16], int stride);
+;-----------------------------------------------------------------------------
+
+%macro ADD_DC 4
+    %4        m2, [r0+%3]
+    %4        m3, [r0+r2+%3]
+    %4        m4, [r1+%3]
+    %4        m5, [r1+r2+%3]
+    paddusb   m2, %1
+    paddusb   m3, %1
+    paddusb   m4, %1
+    paddusb   m5, %1
+    psubusb   m2, %2
+    psubusb   m3, %2
+    psubusb   m4, %2
+    psubusb   m5, %2
+    %4    [r0+%3], m2
+    %4 [r0+r2+%3], m3
+    %4    [r1+%3], m4
+    %4 [r1+r2+%3], m5
+%endmacro
+
+INIT_MMX
+cglobal vp8_idct_dc_add_mmx, 3, 3
+    ; load data
+    movd       m0, [r1]
+
+    ; calculate DC
+    paddw      m0, [pw_4]
+    pxor       m1, m1
+    psraw      m0, 3
+    movd      [r1], m1
+    psubw      m1, m0
+    packuswb   m0, m0
+    packuswb   m1, m1
+    punpcklbw  m0, m0
+    punpcklbw  m1, m1
+    punpcklwd  m0, m0
+    punpcklwd  m1, m1
+
+    ; add DC
+    lea        r1, [r0+r2*2]
+    ADD_DC     m0, m1, 0, movh
+    RET
+
+INIT_XMM
+cglobal vp8_idct_dc_add_sse4, 3, 3, 6
+    ; load data
+    movd       m0, [r1]
+    pxor       m1, m1
+
+    ; calculate DC
+    paddw      m0, [pw_4]
+    movd     [r1], m1
+    lea        r1, [r0+r2*2]
+    movd       m2, [r0]
+    movd       m3, [r0+r2]
+    movd       m4, [r1]
+    movd       m5, [r1+r2]
+    psraw      m0, 3
+    pshuflw    m0, m0, 0
+    punpcklqdq m0, m0
+    punpckldq  m2, m3
+    punpckldq  m4, m5
+    punpcklbw  m2, m1
+    punpcklbw  m4, m1
+    paddw      m2, m0
+    paddw      m4, m0
+    packuswb   m2, m4
+    movd      [r0], m2
+    pextrd [r0+r2], m2, 1
+    pextrd    [r1], m2, 2
+    pextrd [r1+r2], m2, 3
+    RET
+
+;-----------------------------------------------------------------------------
+; void vp8_idct_dc_add4y_<opt>(uint8_t *dst, DCTELEM block[4][16], int stride);
+;-----------------------------------------------------------------------------
+
+INIT_MMX
+cglobal vp8_idct_dc_add4y_mmx, 3, 3
+    ; load data
+    movd      m0, [r1+32*0] ; A
+    movd      m1, [r1+32*2] ; C
+    punpcklwd m0, [r1+32*1] ; A B
+    punpcklwd m1, [r1+32*3] ; C D
+    punpckldq m0, m1        ; A B C D
+    pxor      m6, m6
+
+    ; calculate DC
+    paddw     m0, [pw_4]
+    movd [r1+32*0], m6
+    movd [r1+32*1], m6
+    movd [r1+32*2], m6
+    movd [r1+32*3], m6
+    psraw     m0, 3
+    psubw     m6, m0
+    packuswb  m0, m0
+    packuswb  m6, m6
+    punpcklbw m0, m0 ; AABBCCDD
+    punpcklbw m6, m6 ; AABBCCDD
+    movq      m1, m0
+    movq      m7, m6
+    punpcklbw m0, m0 ; AAAABBBB
+    punpckhbw m1, m1 ; CCCCDDDD
+    punpcklbw m6, m6 ; AAAABBBB
+    punpckhbw m7, m7 ; CCCCDDDD
+
+    ; add DC
+    lea       r1, [r0+r2*2]
+    ADD_DC    m0, m6, 0, mova
+    ADD_DC    m1, m7, 8, mova
+    RET
+
+INIT_XMM
+cglobal vp8_idct_dc_add4y_sse2, 3, 3, 6
+    ; load data
+    movd      m0, [r1+32*0] ; A
+    movd      m1, [r1+32*2] ; C
+    punpcklwd m0, [r1+32*1] ; A B
+    punpcklwd m1, [r1+32*3] ; C D
+    punpckldq m0, m1        ; A B C D
+    pxor      m1, m1
+
+    ; calculate DC
+    paddw     m0, [pw_4]
+    movd [r1+32*0], m1
+    movd [r1+32*1], m1
+    movd [r1+32*2], m1
+    movd [r1+32*3], m1
+    psraw     m0, 3
+    psubw     m1, m0
+    packuswb  m0, m0
+    packuswb  m1, m1
+    punpcklbw m0, m0
+    punpcklbw m1, m1
+    punpcklbw m0, m0
+    punpcklbw m1, m1
+
+    ; add DC
+    lea       r1, [r0+r2*2]
+    ADD_DC    m0, m1, 0, mova
+    RET
+
+;-----------------------------------------------------------------------------
+; void vp8_idct_dc_add4uv_<opt>(uint8_t *dst, DCTELEM block[4][16], int stride);
+;-----------------------------------------------------------------------------
+
+INIT_MMX
+cglobal vp8_idct_dc_add4uv_mmx, 3, 3
+    ; load data
+    movd      m0, [r1+32*0] ; A
+    movd      m1, [r1+32*2] ; C
+    punpcklwd m0, [r1+32*1] ; A B
+    punpcklwd m1, [r1+32*3] ; C D
+    punpckldq m0, m1        ; A B C D
+    pxor      m6, m6
+
+    ; calculate DC
+    paddw     m0, [pw_4]
+    movd [r1+32*0], m6
+    movd [r1+32*1], m6
+    movd [r1+32*2], m6
+    movd [r1+32*3], m6
+    psraw     m0, 3
+    psubw     m6, m0
+    packuswb  m0, m0
+    packuswb  m6, m6
+    punpcklbw m0, m0 ; AABBCCDD
+    punpcklbw m6, m6 ; AABBCCDD
+    movq      m1, m0
+    movq      m7, m6
+    punpcklbw m0, m0 ; AAAABBBB
+    punpckhbw m1, m1 ; CCCCDDDD
+    punpcklbw m6, m6 ; AAAABBBB
+    punpckhbw m7, m7 ; CCCCDDDD
+
+    ; add DC
+    lea       r1, [r0+r2*2]
+    ADD_DC    m0, m6, 0, mova
+    lea       r0, [r0+r2*4]
+    lea       r1, [r1+r2*4]
+    ADD_DC    m1, m7, 0, mova
+    RET
+
+;-----------------------------------------------------------------------------
+; void vp8_idct_add_<opt>(uint8_t *dst, DCTELEM block[16], int stride);
+;-----------------------------------------------------------------------------
+
+; calculate %1=mul_35468(%1)-mul_20091(%2); %2=mul_20091(%1)+mul_35468(%2)
+;           this macro assumes that m6/m7 have words for 20091/17734 loaded
+%macro VP8_MULTIPLY_SUMSUB 4
+    mova      %3, %1
+    mova      %4, %2
+    pmulhw    %3, m6 ;20091(1)
+    pmulhw    %4, m6 ;20091(2)
+    paddw     %3, %1
+    paddw     %4, %2
+    paddw     %1, %1
+    paddw     %2, %2
+    pmulhw    %1, m7 ;35468(1)
+    pmulhw    %2, m7 ;35468(2)
+    psubw     %1, %4
+    paddw     %2, %3
+%endmacro
+
+; calculate x0=%1+%3; x1=%1-%3
+;           x2=mul_35468(%2)-mul_20091(%4); x3=mul_20091(%2)+mul_35468(%4)
+;           %1=x0+x3 (tmp0); %2=x1+x2 (tmp1); %3=x1-x2 (tmp2); %4=x0-x3 (tmp3)
+;           %5/%6 are temporary registers
+;           we assume m6/m7 have constant words 20091/17734 loaded in them
+%macro VP8_IDCT_TRANSFORM4x4_1D 6
+    SUMSUB_BA           m%3, m%1, m%5     ;t0, t1
+    VP8_MULTIPLY_SUMSUB m%2, m%4, m%5,m%6 ;t2, t3
+    SUMSUB_BA           m%4, m%3, m%5     ;tmp0, tmp3
+    SUMSUB_BA           m%2, m%1, m%5     ;tmp1, tmp2
+    SWAP                 %4,  %1
+    SWAP                 %4,  %3
+%endmacro
+
+INIT_MMX
+%macro VP8_IDCT_ADD 1
+cglobal vp8_idct_add_%1, 3, 3
+    ; load block data
+    movq         m0, [r1+ 0]
+    movq         m1, [r1+ 8]
+    movq         m2, [r1+16]
+    movq         m3, [r1+24]
+    movq         m6, [pw_20091]
+    movq         m7, [pw_17734]
+%ifidn %1, sse
+    xorps      xmm0, xmm0
+    movaps  [r1+ 0], xmm0
+    movaps  [r1+16], xmm0
+%else
+    pxor         m4, m4
+    movq    [r1+ 0], m4
+    movq    [r1+ 8], m4
+    movq    [r1+16], m4
+    movq    [r1+24], m4
+%endif
+
+    ; actual IDCT
+    VP8_IDCT_TRANSFORM4x4_1D 0, 1, 2, 3, 4, 5
+    TRANSPOSE4x4W            0, 1, 2, 3, 4
+    paddw        m0, [pw_4]
+    VP8_IDCT_TRANSFORM4x4_1D 0, 1, 2, 3, 4, 5
+    TRANSPOSE4x4W            0, 1, 2, 3, 4
+
+    ; store
+    pxor         m4, m4
+    lea          r1, [r0+2*r2]
+    STORE_DIFFx2 m0, m1, m6, m7, m4, 3, r0, r2
+    STORE_DIFFx2 m2, m3, m6, m7, m4, 3, r1, r2
+
+    RET
+%endmacro
+
+VP8_IDCT_ADD mmx
+VP8_IDCT_ADD sse
+
+;-----------------------------------------------------------------------------
+; void vp8_luma_dc_wht_mmxext(DCTELEM block[4][4][16], DCTELEM dc[16])
+;-----------------------------------------------------------------------------
+
+%macro SCATTER_WHT 3
+    movd  r1d, m%1
+    movd  r2d, m%2
+    mov [r0+2*16*(0+%3)], r1w
+    mov [r0+2*16*(1+%3)], r2w
+    shr   r1d, 16
+    shr   r2d, 16
+    psrlq m%1, 32
+    psrlq m%2, 32
+    mov [r0+2*16*(4+%3)], r1w
+    mov [r0+2*16*(5+%3)], r2w
+    movd  r1d, m%1
+    movd  r2d, m%2
+    mov [r0+2*16*(8+%3)], r1w
+    mov [r0+2*16*(9+%3)], r2w
+    shr   r1d, 16
+    shr   r2d, 16
+    mov [r0+2*16*(12+%3)], r1w
+    mov [r0+2*16*(13+%3)], r2w
+%endmacro
+
+%macro HADAMARD4_1D 4
+    SUMSUB_BADC m%2, m%1, m%4, m%3
+    SUMSUB_BADC m%4, m%2, m%3, m%1
+    SWAP %1, %4, %3
+%endmacro
+
+%macro VP8_DC_WHT 1
+cglobal vp8_luma_dc_wht_%1, 2,3
+    movq          m0, [r1]
+    movq          m1, [r1+8]
+    movq          m2, [r1+16]
+    movq          m3, [r1+24]
+%ifidn %1, sse
+    xorps      xmm0, xmm0
+    movaps  [r1+ 0], xmm0
+    movaps  [r1+16], xmm0
+%else
+    pxor         m4, m4
+    movq    [r1+ 0], m4
+    movq    [r1+ 8], m4
+    movq    [r1+16], m4
+    movq    [r1+24], m4
+%endif
+    HADAMARD4_1D  0, 1, 2, 3
+    TRANSPOSE4x4W 0, 1, 2, 3, 4
+    paddw         m0, [pw_3]
+    HADAMARD4_1D  0, 1, 2, 3
+    psraw         m0, 3
+    psraw         m1, 3
+    psraw         m2, 3
+    psraw         m3, 3
+    SCATTER_WHT   0, 1, 0
+    SCATTER_WHT   2, 3, 2
+    RET
+%endmacro
+
+INIT_MMX
+VP8_DC_WHT mmx
+VP8_DC_WHT sse
+
+;-----------------------------------------------------------------------------
+; void vp8_h/v_loop_filter_simple_<opt>(uint8_t *dst, int stride, int flim);
+;-----------------------------------------------------------------------------
+
+; macro called with 7 mm register indexes as argument, and 4 regular registers
+;
+; first 4 mm registers will carry the transposed pixel data
+; the other three are scratchspace (one would be sufficient, but this allows
+; for more spreading/pipelining and thus faster execution on OOE CPUs)
+;
+; first two regular registers are buf+4*stride and buf+5*stride
+; third is -stride, fourth is +stride
+%macro READ_8x4_INTERLEAVED 11
+    ; interleave 8 (A-H) rows of 4 pixels each
+    movd          m%1, [%8+%10*4]   ; A0-3
+    movd          m%5, [%9+%10*4]   ; B0-3
+    movd          m%2, [%8+%10*2]   ; C0-3
+    movd          m%6, [%8+%10]     ; D0-3
+    movd          m%3, [%8]         ; E0-3
+    movd          m%7, [%9]         ; F0-3
+    movd          m%4, [%9+%11]     ; G0-3
+    punpcklbw     m%1, m%5          ; A/B interleaved
+    movd          m%5, [%9+%11*2]   ; H0-3
+    punpcklbw     m%2, m%6          ; C/D interleaved
+    punpcklbw     m%3, m%7          ; E/F interleaved
+    punpcklbw     m%4, m%5          ; G/H interleaved
+%endmacro
+
+; macro called with 7 mm register indexes as argument, and 5 regular registers
+; first 11 mean the same as READ_8x4_TRANSPOSED above
+; fifth regular register is scratchspace to reach the bottom 8 rows, it
+; will be set to second regular register + 8*stride at the end
+%macro READ_16x4_INTERLEAVED 12
+    ; transpose 16 (A-P) rows of 4 pixels each
+    lea           %12, [r0+8*r2]
+
+    ; read (and interleave) those addressable by %8 (=r0), A/C/D/E/I/K/L/M
+    movd          m%1, [%8+%10*4]   ; A0-3
+    movd          m%3, [%12+%10*4]  ; I0-3
+    movd          m%2, [%8+%10*2]   ; C0-3
+    movd          m%4, [%12+%10*2]  ; K0-3
+    movd          m%6, [%8+%10]     ; D0-3
+    movd          m%5, [%12+%10]    ; L0-3
+    movd          m%7, [%12]        ; M0-3
+    add           %12, %11
+    punpcklbw     m%1, m%3          ; A/I
+    movd          m%3, [%8]         ; E0-3
+    punpcklbw     m%2, m%4          ; C/K
+    punpcklbw     m%6, m%5          ; D/L
+    punpcklbw     m%3, m%7          ; E/M
+    punpcklbw     m%2, m%6          ; C/D/K/L interleaved
+
+    ; read (and interleave) those addressable by %9 (=r4), B/F/G/H/J/N/O/P
+    movd         m%5, [%9+%10*4]   ; B0-3
+    movd         m%4, [%12+%10*4]  ; J0-3
+    movd         m%7, [%9]         ; F0-3
+    movd         m%6, [%12]        ; N0-3
+    punpcklbw    m%5, m%4          ; B/J
+    punpcklbw    m%7, m%6          ; F/N
+    punpcklbw    m%1, m%5          ; A/B/I/J interleaved
+    punpcklbw    m%3, m%7          ; E/F/M/N interleaved
+    movd         m%4, [%9+%11]     ; G0-3
+    movd         m%6, [%12+%11]    ; O0-3
+    movd         m%5, [%9+%11*2]   ; H0-3
+    movd         m%7, [%12+%11*2]  ; P0-3
+    punpcklbw    m%4, m%6          ; G/O
+    punpcklbw    m%5, m%7          ; H/P
+    punpcklbw    m%4, m%5          ; G/H/O/P interleaved
+%endmacro
+
+; write 4 mm registers of 2 dwords each
+; first four arguments are mm register indexes containing source data
+; last four are registers containing buf+4*stride, buf+5*stride,
+; -stride and +stride
+%macro WRITE_4x2D 8
+    ; write out (2 dwords per register)
+    movd    [%5+%7*4], m%1
+    movd    [%5+%7*2], m%2
+    movd         [%5], m%3
+    movd      [%6+%8], m%4
+    punpckhdq     m%1, m%1
+    punpckhdq     m%2, m%2
+    punpckhdq     m%3, m%3
+    punpckhdq     m%4, m%4
+    movd    [%6+%7*4], m%1
+    movd      [%5+%7], m%2
+    movd         [%6], m%3
+    movd    [%6+%8*2], m%4
+%endmacro
+
+; write 4 xmm registers of 4 dwords each
+; arguments same as WRITE_2x4D, but with an extra register, so that the 5 regular
+; registers contain buf+4*stride, buf+5*stride, buf+12*stride, -stride and +stride
+; we add 1*stride to the third regular registry in the process
+; the 10th argument is 16 if it's a Y filter (i.e. all regular registers cover the
+; same memory region), or 8 if they cover two separate buffers (third one points to
+; a different memory region than the first two), allowing for more optimal code for
+; the 16-width case
+%macro WRITE_4x4D 10
+    ; write out (4 dwords per register), start with dwords zero
+    movd    [%5+%8*4], m%1
+    movd         [%5], m%2
+    movd    [%7+%8*4], m%3
+    movd         [%7], m%4
+
+    ; store dwords 1
+    psrldq        m%1, 4
+    psrldq        m%2, 4
+    psrldq        m%3, 4
+    psrldq        m%4, 4
+    movd    [%6+%8*4], m%1
+    movd         [%6], m%2
+%if %10 == 16
+    movd    [%6+%9*4], m%3
+%endif
+    movd      [%7+%9], m%4
+
+    ; write dwords 2
+    psrldq        m%1, 4
+    psrldq        m%2, 4
+%if %10 == 8
+    movd    [%5+%8*2], m%1
+    movd          %5d, m%3
+%endif
+    psrldq        m%3, 4
+    psrldq        m%4, 4
+%if %10 == 16
+    movd    [%5+%8*2], m%1
+%endif
+    movd      [%6+%9], m%2
+    movd    [%7+%8*2], m%3
+    movd    [%7+%9*2], m%4
+    add            %7, %9
+
+    ; store dwords 3
+    psrldq        m%1, 4
+    psrldq        m%2, 4
+    psrldq        m%3, 4
+    psrldq        m%4, 4
+%if %10 == 8
+    mov     [%7+%8*4], %5d
+    movd    [%6+%8*2], m%1
+%else
+    movd      [%5+%8], m%1
+%endif
+    movd    [%6+%9*2], m%2
+    movd    [%7+%8*2], m%3
+    movd    [%7+%9*2], m%4
+%endmacro
+
+; write 4 or 8 words in the mmx/xmm registers as 8 lines
+; 1 and 2 are the registers to write, this can be the same (for SSE2)
+; for pre-SSE4:
+; 3 is a general-purpose register that we will clobber
+; for SSE4:
+; 3 is a pointer to the destination's 5th line
+; 4 is a pointer to the destination's 4th line
+; 5/6 is -stride and +stride
+%macro WRITE_2x4W 6
+    movd            %3d, %1
+    punpckhdq        %1, %1
+    mov       [%4+%5*4], %3w
+    shr              %3, 16
+    add              %4, %6
+    mov       [%4+%5*4], %3w
+
+    movd            %3d, %1
+    add              %4, %5
+    mov       [%4+%5*2], %3w
+    shr              %3, 16
+    mov       [%4+%5  ], %3w
+
+    movd            %3d, %2
+    punpckhdq        %2, %2
+    mov       [%4     ], %3w
+    shr              %3, 16
+    mov       [%4+%6  ], %3w
+
+    movd            %3d, %2
+    add              %4, %6
+    mov       [%4+%6  ], %3w
+    shr              %3, 16
+    mov       [%4+%6*2], %3w
+    add              %4, %5
+%endmacro
+
+%macro WRITE_8W_SSE2 5
+    movd            %2d, %1
+    psrldq           %1, 4
+    mov       [%3+%4*4], %2w
+    shr              %2, 16
+    add              %3, %5
+    mov       [%3+%4*4], %2w
+
+    movd            %2d, %1
+    psrldq           %1, 4
+    add              %3, %4
+    mov       [%3+%4*2], %2w
+    shr              %2, 16
+    mov       [%3+%4  ], %2w
+
+    movd            %2d, %1
+    psrldq           %1, 4
+    mov       [%3     ], %2w
+    shr              %2, 16
+    mov       [%3+%5  ], %2w
+
+    movd            %2d, %1
+    add              %3, %5
+    mov       [%3+%5  ], %2w
+    shr              %2, 16
+    mov       [%3+%5*2], %2w
+%endmacro
+
+%macro WRITE_8W_SSE4 5
+    pextrw    [%3+%4*4], %1, 0
+    pextrw    [%2+%4*4], %1, 1
+    pextrw    [%3+%4*2], %1, 2
+    pextrw    [%3+%4  ], %1, 3
+    pextrw    [%3     ], %1, 4
+    pextrw    [%2     ], %1, 5
+    pextrw    [%2+%5  ], %1, 6
+    pextrw    [%2+%5*2], %1, 7
+%endmacro
+
+%macro SPLATB_REG_MMX 2-3
+    movd           %1, %2d
+    punpcklbw      %1, %1
+    punpcklwd      %1, %1
+    punpckldq      %1, %1
+%endmacro
+
+%macro SPLATB_REG_MMXEXT 2-3
+    movd           %1, %2d
+    punpcklbw      %1, %1
+    pshufw         %1, %1, 0x0
+%endmacro
+
+%macro SPLATB_REG_SSE2 2-3
+    movd           %1, %2d
+    punpcklbw      %1, %1
+    pshuflw        %1, %1, 0x0
+    punpcklqdq     %1, %1
+%endmacro
+
+%macro SPLATB_REG_SSSE3 3
+    movd           %1, %2d
+    pshufb         %1, %3
+%endmacro
+
+%macro SIMPLE_LOOPFILTER 4
+cglobal vp8_%2_loop_filter_simple_%1, 3, %3, %4
+%if mmsize == 8 ; mmx/mmxext
+    mov            r3, 2
+%endif
+%ifnidn %1, sse2
+%if mmsize == 16
+    pxor           m0, m0
+%endif
+%endif
+    SPLATB_REG     m7, r2, m0       ; splat "flim" into register
+
+    ; set up indexes to address 4 rows
+    mov            r2, r1
+    neg            r1
+%ifidn %2, h
+    lea            r0, [r0+4*r2-2]
+%endif
+
+%if mmsize == 8 ; mmx / mmxext
+.next8px
+%endif
+%ifidn %2, v
+    ; read 4 half/full rows of pixels
+    mova           m0, [r0+r1*2]    ; p1
+    mova           m1, [r0+r1]      ; p0
+    mova           m2, [r0]         ; q0
+    mova           m3, [r0+r2]      ; q1
+%else ; h
+    lea            r4, [r0+r2]
+
+%if mmsize == 8 ; mmx/mmxext
+    READ_8x4_INTERLEAVED  0, 1, 2, 3, 4, 5, 6, r0, r4, r1, r2
+%else ; sse2
+    READ_16x4_INTERLEAVED 0, 1, 2, 3, 4, 5, 6, r0, r4, r1, r2, r3
+%endif
+    TRANSPOSE4x4W         0, 1, 2, 3, 4
+%endif
+
+    ; simple_limit
+    mova           m5, m2           ; m5=backup of q0
+    mova           m6, m1           ; m6=backup of p0
+    psubusb        m1, m2           ; p0-q0
+    psubusb        m2, m6           ; q0-p0
+    por            m1, m2           ; FFABS(p0-q0)
+    paddusb        m1, m1           ; m1=FFABS(p0-q0)*2
+
+    mova           m4, m3
+    mova           m2, m0
+    psubusb        m3, m0           ; q1-p1
+    psubusb        m0, m4           ; p1-q1
+    por            m3, m0           ; FFABS(p1-q1)
+    mova           m0, [pb_80]
+    pxor           m2, m0
+    pxor           m4, m0
+    psubsb         m2, m4           ; m2=p1-q1 (signed) backup for below
+    pand           m3, [pb_FE]
+    psrlq          m3, 1            ; m3=FFABS(p1-q1)/2, this can be used signed
+    paddusb        m3, m1
+    psubusb        m3, m7
+    pxor           m1, m1
+    pcmpeqb        m3, m1           ; abs(p0-q0)*2+abs(p1-q1)/2<=flim mask(0xff/0x0)
+
+    ; filter_common (use m2/p1-q1, m4=q0, m6=p0, m5/q0-p0 and m3/mask)
+    mova           m4, m5
+    pxor           m5, m0
+    pxor           m0, m6
+    psubsb         m5, m0           ; q0-p0 (signed)
+    paddsb         m2, m5
+    paddsb         m2, m5
+    paddsb         m2, m5           ; a=(p1-q1) + 3*(q0-p0)
+    pand           m2, m3           ; apply filter mask (m3)
+
+    mova           m3, [pb_F8]
+    mova           m1, m2
+    paddsb         m2, [pb_4]       ; f1<<3=a+4
+    paddsb         m1, [pb_3]       ; f2<<3=a+3
+    pand           m2, m3
+    pand           m1, m3           ; cache f2<<3
+
+    pxor           m0, m0
+    pxor           m3, m3
+    pcmpgtb        m0, m2           ; which values are <0?
+    psubb          m3, m2           ; -f1<<3
+    psrlq          m2, 3            ; +f1
+    psrlq          m3, 3            ; -f1
+    pand           m3, m0
+    pandn          m0, m2
+    psubusb        m4, m0
+    paddusb        m4, m3           ; q0-f1
+
+    pxor           m0, m0
+    pxor           m3, m3
+    pcmpgtb        m0, m1           ; which values are <0?
+    psubb          m3, m1           ; -f2<<3
+    psrlq          m1, 3            ; +f2
+    psrlq          m3, 3            ; -f2
+    pand           m3, m0
+    pandn          m0, m1
+    paddusb        m6, m0
+    psubusb        m6, m3           ; p0+f2
+
+    ; store
+%ifidn %2, v
+    mova         [r0], m4
+    mova      [r0+r1], m6
+%else ; h
+    inc           r0
+    SBUTTERFLY    bw, 6, 4, 0
+
+%if mmsize == 16 ; sse2
+%ifidn %1, sse4
+    inc            r4
+%endif
+    WRITE_8W       m6, r4, r0, r1, r2
+    lea            r4, [r3+r1+1]
+%ifidn %1, sse4
+    inc            r3
+%endif
+    WRITE_8W       m4, r3, r4, r1, r2
+%else ; mmx/mmxext
+    WRITE_2x4W     m6, m4, r4, r0, r1, r2
+%endif
+%endif
+
+%if mmsize == 8 ; mmx/mmxext
+    ; next 8 pixels
+%ifidn %2, v
+    add            r0, 8            ; advance 8 cols = pixels
+%else ; h
+    lea            r0, [r0+r2*8-1]  ; advance 8 rows = lines
+%endif
+    dec            r3
+    jg .next8px
+    REP_RET
+%else ; sse2
+    RET
+%endif
+%endmacro
+
+INIT_MMX
+%define SPLATB_REG SPLATB_REG_MMX
+SIMPLE_LOOPFILTER mmx,    v, 4, 0
+SIMPLE_LOOPFILTER mmx,    h, 5, 0
+%define SPLATB_REG SPLATB_REG_MMXEXT
+SIMPLE_LOOPFILTER mmxext, v, 4, 0
+SIMPLE_LOOPFILTER mmxext, h, 5, 0
+INIT_XMM
+%define SPLATB_REG SPLATB_REG_SSE2
+%define WRITE_8W   WRITE_8W_SSE2
+SIMPLE_LOOPFILTER sse2,   v, 3, 8
+SIMPLE_LOOPFILTER sse2,   h, 5, 8
+%define SPLATB_REG SPLATB_REG_SSSE3
+SIMPLE_LOOPFILTER ssse3,  v, 3, 8
+SIMPLE_LOOPFILTER ssse3,  h, 5, 8
+%define WRITE_8W   WRITE_8W_SSE4
+SIMPLE_LOOPFILTER sse4,   h, 5, 8
+
+;-----------------------------------------------------------------------------
+; void vp8_h/v_loop_filter<size>_inner_<opt>(uint8_t *dst, [uint8_t *v,] int stride,
+;                                            int flimE, int flimI, int hev_thr);
+;-----------------------------------------------------------------------------
+
+%macro INNER_LOOPFILTER 5
+%if %4 == 8 ; chroma
+cglobal vp8_%2_loop_filter8uv_inner_%1, 6, %3, %5
+%define dst8_reg    r1
+%define mstride_reg r2
+%define E_reg       r3
+%define I_reg       r4
+%define hev_thr_reg r5
+%else ; luma
+cglobal vp8_%2_loop_filter16y_inner_%1, 5, %3, %5
+%define mstride_reg r1
+%define E_reg       r2
+%define I_reg       r3
+%define hev_thr_reg r4
+%ifdef m8 ; x86-64, sse2
+%define dst8_reg    r4
+%elif mmsize == 16 ; x86-32, sse2
+%define dst8_reg    r5
+%else ; x86-32, mmx/mmxext
+%define cnt_reg     r5
+%endif
+%endif
+%define dst_reg     r0
+%define stride_reg  E_reg
+%define dst2_reg    I_reg
+%ifndef m8
+%define stack_reg   hev_thr_reg
+%endif
+
+%ifnidn %1, sse2
+%if mmsize == 16
+    pxor             m7, m7
+%endif
+%endif
+
+%ifndef m8 ; mmx/mmxext or sse2 on x86-32
+    ; splat function arguments
+    SPLATB_REG       m0, E_reg, m7   ; E
+    SPLATB_REG       m1, I_reg, m7   ; I
+    SPLATB_REG       m2, hev_thr_reg, m7 ; hev_thresh
+
+    ; align stack
+    mov       stack_reg, rsp         ; backup stack pointer
+    and             rsp, ~(mmsize-1) ; align stack
+%ifidn %2, v
+    sub             rsp, mmsize * 4  ; stack layout: [0]=E, [1]=I, [2]=hev_thr
+                                     ;               [3]=hev() result
+%else ; h
+    sub             rsp, mmsize * 5  ; extra storage space for transposes
+%endif
+
+%define flim_E   [rsp]
+%define flim_I   [rsp+mmsize]
+%define hev_thr  [rsp+mmsize*2]
+%define mask_res [rsp+mmsize*3]
+%define p0backup [rsp+mmsize*3]
+%define q0backup [rsp+mmsize*4]
+
+    mova         flim_E, m0
+    mova         flim_I, m1
+    mova        hev_thr, m2
+
+%else ; sse2 on x86-64
+
+%define flim_E   m9
+%define flim_I   m10
+%define hev_thr  m11
+%define mask_res m12
+%define p0backup m12
+%define q0backup m8
+
+    ; splat function arguments
+    SPLATB_REG   flim_E, E_reg, m7   ; E
+    SPLATB_REG   flim_I, I_reg, m7   ; I
+    SPLATB_REG  hev_thr, hev_thr_reg, m7 ; hev_thresh
+%endif
+
+%if mmsize == 8 && %4 == 16 ; mmx/mmxext
+    mov         cnt_reg, 2
+%endif
+    mov      stride_reg, mstride_reg
+    neg     mstride_reg
+%ifidn %2, h
+    lea         dst_reg, [dst_reg + stride_reg*4-4]
+%if %4 == 8
+    lea        dst8_reg, [dst8_reg+ stride_reg*4-4]
+%endif
+%endif
+
+%if mmsize == 8
+.next8px
+%endif
+    ; read
+    lea        dst2_reg, [dst_reg + stride_reg]
+%ifidn %2, v
+%if %4 == 8 && mmsize == 16
+%define movrow movh
+%else
+%define movrow mova
+%endif
+    movrow           m0, [dst_reg +mstride_reg*4] ; p3
+    movrow           m1, [dst2_reg+mstride_reg*4] ; p2
+    movrow           m2, [dst_reg +mstride_reg*2] ; p1
+    movrow           m5, [dst2_reg]               ; q1
+    movrow           m6, [dst2_reg+ stride_reg]   ; q2
+    movrow           m7, [dst2_reg+ stride_reg*2] ; q3
+%if mmsize == 16 && %4 == 8
+    movhps           m0, [dst8_reg+mstride_reg*4]
+    movhps           m2, [dst8_reg+mstride_reg*2]
+    add        dst8_reg, stride_reg
+    movhps           m1, [dst8_reg+mstride_reg*4]
+    movhps           m5, [dst8_reg]
+    movhps           m6, [dst8_reg+ stride_reg]
+    movhps           m7, [dst8_reg+ stride_reg*2]
+    add        dst8_reg, mstride_reg
+%endif
+%elif mmsize == 8 ; mmx/mmxext (h)
+    ; read 8 rows of 8px each
+    movu             m0, [dst_reg +mstride_reg*4]
+    movu             m1, [dst2_reg+mstride_reg*4]
+    movu             m2, [dst_reg +mstride_reg*2]
+    movu             m3, [dst_reg +mstride_reg]
+    movu             m4, [dst_reg]
+    movu             m5, [dst2_reg]
+    movu             m6, [dst2_reg+ stride_reg]
+
+    ; 8x8 transpose
+    TRANSPOSE4x4B     0, 1, 2, 3, 7
+    mova       q0backup, m1
+    movu             m7, [dst2_reg+ stride_reg*2]
+    TRANSPOSE4x4B     4, 5, 6, 7, 1
+    SBUTTERFLY       dq, 0, 4, 1     ; p3/p2
+    SBUTTERFLY       dq, 2, 6, 1     ; q0/q1
+    SBUTTERFLY       dq, 3, 7, 1     ; q2/q3
+    mova             m1, q0backup
+    mova       q0backup, m2          ; store q0
+    SBUTTERFLY       dq, 1, 5, 2     ; p1/p0
+    mova       p0backup, m5          ; store p0
+    SWAP              1, 4
+    SWAP              2, 4
+    SWAP              6, 3
+    SWAP              5, 3
+%else ; sse2 (h)
+%if %4 == 16
+    lea        dst8_reg, [dst_reg + stride_reg*8]
+%endif
+
+    ; read 16 rows of 8px each, interleave
+    movh             m0, [dst_reg +mstride_reg*4]
+    movh             m1, [dst8_reg+mstride_reg*4]
+    movh             m2, [dst_reg +mstride_reg*2]
+    movh             m5, [dst8_reg+mstride_reg*2]
+    movh             m3, [dst_reg +mstride_reg]
+    movh             m6, [dst8_reg+mstride_reg]
+    movh             m4, [dst_reg]
+    movh             m7, [dst8_reg]
+    punpcklbw        m0, m1          ; A/I
+    punpcklbw        m2, m5          ; C/K
+    punpcklbw        m3, m6          ; D/L
+    punpcklbw        m4, m7          ; E/M
+
+    add        dst8_reg, stride_reg
+    movh             m1, [dst2_reg+mstride_reg*4]
+    movh             m6, [dst8_reg+mstride_reg*4]
+    movh             m5, [dst2_reg]
+    movh             m7, [dst8_reg]
+    punpcklbw        m1, m6          ; B/J
+    punpcklbw        m5, m7          ; F/N
+    movh             m6, [dst2_reg+ stride_reg]
+    movh             m7, [dst8_reg+ stride_reg]
+    punpcklbw        m6, m7          ; G/O
+
+    ; 8x16 transpose
+    TRANSPOSE4x4B     0, 1, 2, 3, 7
+%ifdef m8
+    SWAP              1, 8
+%else
+    mova       q0backup, m1
+%endif
+    movh             m7, [dst2_reg+ stride_reg*2]
+    movh             m1, [dst8_reg+ stride_reg*2]
+    punpcklbw        m7, m1          ; H/P
+    TRANSPOSE4x4B     4, 5, 6, 7, 1
+    SBUTTERFLY       dq, 0, 4, 1     ; p3/p2
+    SBUTTERFLY       dq, 2, 6, 1     ; q0/q1
+    SBUTTERFLY       dq, 3, 7, 1     ; q2/q3
+%ifdef m8
+    SWAP              1, 8
+    SWAP              2, 8
+%else
+    mova             m1, q0backup
+    mova       q0backup, m2          ; store q0
+%endif
+    SBUTTERFLY       dq, 1, 5, 2     ; p1/p0
+%ifdef m12
+    SWAP              5, 12
+%else
+    mova       p0backup, m5          ; store p0
+%endif
+    SWAP              1, 4
+    SWAP              2, 4
+    SWAP              6, 3
+    SWAP              5, 3
+%endif
+
+    ; normal_limit for p3-p2, p2-p1, q3-q2 and q2-q1
+    mova             m4, m1
+    SWAP              4, 1
+    psubusb          m4, m0          ; p2-p3
+    psubusb          m0, m1          ; p3-p2
+    por              m0, m4          ; abs(p3-p2)
+
+    mova             m4, m2
+    SWAP              4, 2
+    psubusb          m4, m1          ; p1-p2
+    psubusb          m1, m2          ; p2-p1
+    por              m1, m4          ; abs(p2-p1)
+
+    mova             m4, m6
+    SWAP              4, 6
+    psubusb          m4, m7          ; q2-q3
+    psubusb          m7, m6          ; q3-q2
+    por              m7, m4          ; abs(q3-q2)
+
+    mova             m4, m5
+    SWAP              4, 5
+    psubusb          m4, m6          ; q1-q2
+    psubusb          m6, m5          ; q2-q1
+    por              m6, m4          ; abs(q2-q1)
+
+%ifidn %1, mmx
+    mova             m4, flim_I
+    pxor             m3, m3
+    psubusb          m0, m4
+    psubusb          m1, m4
+    psubusb          m7, m4
+    psubusb          m6, m4
+    pcmpeqb          m0, m3          ; abs(p3-p2) <= I
+    pcmpeqb          m1, m3          ; abs(p2-p1) <= I
+    pcmpeqb          m7, m3          ; abs(q3-q2) <= I
+    pcmpeqb          m6, m3          ; abs(q2-q1) <= I
+    pand             m0, m1
+    pand             m7, m6
+    pand             m0, m7
+%else ; mmxext/sse2
+    pmaxub           m0, m1
+    pmaxub           m6, m7
+    pmaxub           m0, m6
+%endif
+
+    ; normal_limit and high_edge_variance for p1-p0, q1-q0
+    SWAP              7, 3           ; now m7 is zero
+%ifidn %2, v
+    movrow           m3, [dst_reg +mstride_reg] ; p0
+%if mmsize == 16 && %4 == 8
+    movhps           m3, [dst8_reg+mstride_reg]
+%endif
+%elifdef m12
+    SWAP              3, 12
+%else
+    mova             m3, p0backup
+%endif
+
+    mova             m1, m2
+    SWAP              1, 2
+    mova             m6, m3
+    SWAP              3, 6
+    psubusb          m1, m3          ; p1-p0
+    psubusb          m6, m2          ; p0-p1
+    por              m1, m6          ; abs(p1-p0)
+%ifidn %1, mmx
+    mova             m6, m1
+    psubusb          m1, m4
+    psubusb          m6, hev_thr
+    pcmpeqb          m1, m7          ; abs(p1-p0) <= I
+    pcmpeqb          m6, m7          ; abs(p1-p0) <= hev_thresh
+    pand             m0, m1
+    mova       mask_res, m6
+%else ; mmxext/sse2
+    pmaxub           m0, m1          ; max_I
+    SWAP              1, 4           ; max_hev_thresh
+%endif
+
+    SWAP              6, 4           ; now m6 is I
+%ifidn %2, v
+    movrow           m4, [dst_reg]   ; q0
+%if mmsize == 16 && %4 == 8
+    movhps           m4, [dst8_reg]
+%endif
+%elifdef m8
+    SWAP              4, 8
+%else
+    mova             m4, q0backup
+%endif
+    mova             m1, m4
+    SWAP              1, 4
+    mova             m7, m5
+    SWAP              7, 5
+    psubusb          m1, m5          ; q0-q1
+    psubusb          m7, m4          ; q1-q0
+    por              m1, m7          ; abs(q1-q0)
+%ifidn %1, mmx
+    mova             m7, m1
+    psubusb          m1, m6
+    psubusb          m7, hev_thr
+    pxor             m6, m6
+    pcmpeqb          m1, m6          ; abs(q1-q0) <= I
+    pcmpeqb          m7, m6          ; abs(q1-q0) <= hev_thresh
+    mova             m6, mask_res
+    pand             m0, m1          ; abs([pq][321]-[pq][210]) <= I
+    pand             m6, m7
+%else ; mmxext/sse2
+    pxor             m7, m7
+    pmaxub           m0, m1
+    pmaxub           m6, m1
+    psubusb          m0, flim_I
+    psubusb          m6, hev_thr
+    pcmpeqb          m0, m7          ; max(abs(..)) <= I
+    pcmpeqb          m6, m7          ; !(max(abs..) > thresh)
+%endif
+%ifdef m12
+    SWAP              6, 12
+%else
+    mova       mask_res, m6          ; !(abs(p1-p0) > hev_t || abs(q1-q0) > hev_t)
+%endif
+
+    ; simple_limit
+    mova             m1, m3
+    SWAP              1, 3
+    mova             m6, m4          ; keep copies of p0/q0 around for later use
+    SWAP              6, 4
+    psubusb          m1, m4          ; p0-q0
+    psubusb          m6, m3          ; q0-p0
+    por              m1, m6          ; abs(q0-p0)
+    paddusb          m1, m1          ; m1=2*abs(q0-p0)
+
+    mova             m7, m2
+    SWAP              7, 2
+    mova             m6, m5
+    SWAP              6, 5
+    psubusb          m7, m5          ; p1-q1
+    psubusb          m6, m2          ; q1-p1
+    por              m7, m6          ; abs(q1-p1)
+    pxor             m6, m6
+    pand             m7, [pb_FE]
+    psrlq            m7, 1           ; abs(q1-p1)/2
+    paddusb          m7, m1          ; abs(q0-p0)*2+abs(q1-p1)/2
+    psubusb          m7, flim_E
+    pcmpeqb          m7, m6          ; abs(q0-p0)*2+abs(q1-p1)/2 <= E
+    pand             m0, m7          ; normal_limit result
+
+    ; filter_common; at this point, m2-m5=p1-q1 and m0 is filter_mask
+%ifdef m8 ; x86-64 && sse2
+    mova             m8, [pb_80]
+%define pb_80_var m8
+%else ; x86-32 or mmx/mmxext
+%define pb_80_var [pb_80]
+%endif
+    mova             m1, m4
+    mova             m7, m3
+    pxor             m1, pb_80_var
+    pxor             m7, pb_80_var
+    psubsb           m1, m7          ; (signed) q0-p0
+    mova             m6, m2
+    mova             m7, m5
+    pxor             m6, pb_80_var
+    pxor             m7, pb_80_var
+    psubsb           m6, m7          ; (signed) p1-q1
+    mova             m7, mask_res
+    pandn            m7, m6
+    paddsb           m7, m1
+    paddsb           m7, m1
+    paddsb           m7, m1          ; 3*(q0-p0)+is4tap?(p1-q1)
+
+    pand             m7, m0
+    mova             m1, [pb_F8]
+    mova             m6, m7
+    paddsb           m7, [pb_3]
+    paddsb           m6, [pb_4]
+    pand             m7, m1
+    pand             m6, m1
+
+    pxor             m1, m1
+    pxor             m0, m0
+    pcmpgtb          m1, m7
+    psubb            m0, m7
+    psrlq            m7, 3           ; +f2
+    psrlq            m0, 3           ; -f2
+    pand             m0, m1
+    pandn            m1, m7
+    psubusb          m3, m0
+    paddusb          m3, m1          ; p0+f2
+
+    pxor             m1, m1
+    pxor             m0, m0
+    pcmpgtb          m0, m6
+    psubb            m1, m6
+    psrlq            m6, 3           ; +f1
+    psrlq            m1, 3           ; -f1
+    pand             m1, m0
+    pandn            m0, m6
+    psubusb          m4, m0
+    paddusb          m4, m1          ; q0-f1
+
+%ifdef m12
+    SWAP              6, 12
+%else
+    mova             m6, mask_res
+%endif
+%ifidn %1, mmx
+    mova             m7, [pb_1]
+%else ; mmxext/sse2
+    pxor             m7, m7
+%endif
+    pand             m0, m6
+    pand             m1, m6
+%ifidn %1, mmx
+    paddusb          m0, m7
+    pand             m1, [pb_FE]
+    pandn            m7, m0
+    psrlq            m1, 1
+    psrlq            m7, 1
+    SWAP              0, 7
+%else ; mmxext/sse2
+    psubusb          m1, [pb_1]
+    pavgb            m0, m7          ; a
+    pavgb            m1, m7          ; -a
+%endif
+    psubusb          m5, m0
+    psubusb          m2, m1
+    paddusb          m5, m1          ; q1-a
+    paddusb          m2, m0          ; p1+a
+
+    ; store
+%ifidn %2, v
+    movrow [dst_reg +mstride_reg*2], m2
+    movrow [dst_reg +mstride_reg  ], m3
+    movrow    [dst_reg], m4
+    movrow [dst_reg + stride_reg  ], m5
+%if mmsize == 16 && %4 == 8
+    movhps [dst8_reg+mstride_reg*2], m2
+    movhps [dst8_reg+mstride_reg  ], m3
+    movhps   [dst8_reg], m4
+    movhps [dst8_reg+ stride_reg  ], m5
+%endif
+%else ; h
+    add         dst_reg, 2
+    add        dst2_reg, 2
+
+    ; 4x8/16 transpose
+    TRANSPOSE4x4B     2, 3, 4, 5, 6
+
+%if mmsize == 8 ; mmx/mmxext (h)
+    WRITE_4x2D        2, 3, 4, 5, dst_reg, dst2_reg, mstride_reg, stride_reg
+%else ; sse2 (h)
+    lea        dst8_reg, [dst8_reg+mstride_reg+2]
+    WRITE_4x4D        2, 3, 4, 5, dst_reg, dst2_reg, dst8_reg, mstride_reg, stride_reg, %4
+%endif
+%endif
+
+%if mmsize == 8
+%if %4 == 8 ; chroma
+%ifidn %2, h
+    sub         dst_reg, 2
+%endif
+    cmp         dst_reg, dst8_reg
+    mov         dst_reg, dst8_reg
+    jnz .next8px
+%else
+%ifidn %2, h
+    lea         dst_reg, [dst_reg + stride_reg*8-2]
+%else ; v
+    add         dst_reg, 8
+%endif
+    dec         cnt_reg
+    jg .next8px
+%endif
+%endif
+
+%ifndef m8 ; sse2 on x86-32 or mmx/mmxext
+    mov             rsp, stack_reg   ; restore stack pointer
+%endif
+    RET
+%endmacro
+
+INIT_MMX
+%define SPLATB_REG SPLATB_REG_MMX
+INNER_LOOPFILTER mmx,    v, 6, 16, 0
+INNER_LOOPFILTER mmx,    h, 6, 16, 0
+INNER_LOOPFILTER mmx,    v, 6,  8, 0
+INNER_LOOPFILTER mmx,    h, 6,  8, 0
+
+%define SPLATB_REG SPLATB_REG_MMXEXT
+INNER_LOOPFILTER mmxext, v, 6, 16, 0
+INNER_LOOPFILTER mmxext, h, 6, 16, 0
+INNER_LOOPFILTER mmxext, v, 6,  8, 0
+INNER_LOOPFILTER mmxext, h, 6,  8, 0
+
+INIT_XMM
+%define SPLATB_REG SPLATB_REG_SSE2
+INNER_LOOPFILTER sse2,   v, 5, 16, 13
+%ifdef m8
+INNER_LOOPFILTER sse2,   h, 5, 16, 13
+%else
+INNER_LOOPFILTER sse2,   h, 6, 16, 13
+%endif
+INNER_LOOPFILTER sse2,   v, 6,  8, 13
+INNER_LOOPFILTER sse2,   h, 6,  8, 13
+
+%define SPLATB_REG SPLATB_REG_SSSE3
+INNER_LOOPFILTER ssse3,  v, 5, 16, 13
+%ifdef m8
+INNER_LOOPFILTER ssse3,  h, 5, 16, 13
+%else
+INNER_LOOPFILTER ssse3,  h, 6, 16, 13
+%endif
+INNER_LOOPFILTER ssse3,  v, 6,  8, 13
+INNER_LOOPFILTER ssse3,  h, 6,  8, 13
+
+;-----------------------------------------------------------------------------
+; void vp8_h/v_loop_filter<size>_mbedge_<opt>(uint8_t *dst, [uint8_t *v,] int stride,
+;                                            int flimE, int flimI, int hev_thr);
+;-----------------------------------------------------------------------------
+
+%macro MBEDGE_LOOPFILTER 5
+%if %4 == 8 ; chroma
+cglobal vp8_%2_loop_filter8uv_mbedge_%1, 6, %3, %5
+%define dst8_reg    r1
+%define mstride_reg r2
+%define E_reg       r3
+%define I_reg       r4
+%define hev_thr_reg r5
+%else ; luma
+cglobal vp8_%2_loop_filter16y_mbedge_%1, 5, %3, %5
+%define mstride_reg r1
+%define E_reg       r2
+%define I_reg       r3
+%define hev_thr_reg r4
+%ifdef m8 ; x86-64, sse2
+%define dst8_reg    r4
+%elif mmsize == 16 ; x86-32, sse2
+%define dst8_reg    r5
+%else ; x86-32, mmx/mmxext
+%define cnt_reg     r5
+%endif
+%endif
+%define dst_reg     r0
+%define stride_reg  E_reg
+%define dst2_reg    I_reg
+%ifndef m8
+%define stack_reg   hev_thr_reg
+%endif
+
+%define ssse3_or_higher 0
+%ifnidn %1, sse2
+%if mmsize == 16
+%define ssse3_or_higher 1
+%endif
+%endif
+
+%if ssse3_or_higher
+    pxor             m7, m7
+%endif
+
+%ifndef m8 ; mmx/mmxext or sse2 on x86-32
+    ; splat function arguments
+    SPLATB_REG       m0, E_reg, m7   ; E
+    SPLATB_REG       m1, I_reg, m7   ; I
+    SPLATB_REG       m2, hev_thr_reg, m7 ; hev_thresh
+
+    ; align stack
+    mov       stack_reg, rsp         ; backup stack pointer
+    and             rsp, ~(mmsize-1) ; align stack
+%if mmsize == 16
+    sub             rsp, mmsize * 7
+%else
+    sub             rsp, mmsize * 8  ; stack layout: [0]=E, [1]=I, [2]=hev_thr
+                                     ;               [3]=hev() result
+                                     ;               [4]=filter tmp result
+                                     ;               [5]/[6] = p2/q2 backup
+                                     ;               [7]=lim_res sign result
+%endif
+
+%define flim_E   [rsp]
+%define flim_I   [rsp+mmsize]
+%define hev_thr  [rsp+mmsize*2]
+%define mask_res [rsp+mmsize*3]
+%define lim_res  [rsp+mmsize*4]
+%define p0backup [rsp+mmsize*3]
+%define q0backup [rsp+mmsize*4]
+%define p2backup [rsp+mmsize*5]
+%define q2backup [rsp+mmsize*6]
+%if mmsize == 16
+%define lim_sign [rsp]
+%else
+%define lim_sign [rsp+mmsize*7]
+%endif
+
+    mova         flim_E, m0
+    mova         flim_I, m1
+    mova        hev_thr, m2
+
+%else ; sse2 on x86-64
+
+%define flim_E   m9
+%define flim_I   m10
+%define hev_thr  m11
+%define mask_res m12
+%define lim_res  m8
+%define p0backup m12
+%define q0backup m8
+%define p2backup m13
+%define q2backup m14
+%define lim_sign m9
+
+    ; splat function arguments
+    SPLATB_REG   flim_E, E_reg, m7   ; E
+    SPLATB_REG   flim_I, I_reg, m7   ; I
+    SPLATB_REG  hev_thr, hev_thr_reg, m7 ; hev_thresh
+%endif
+
+%if mmsize == 8 && %4 == 16 ; mmx/mmxext
+    mov         cnt_reg, 2
+%endif
+    mov      stride_reg, mstride_reg
+    neg     mstride_reg
+%ifidn %2, h
+    lea         dst_reg, [dst_reg + stride_reg*4-4]
+%if %4 == 8
+    lea        dst8_reg, [dst8_reg+ stride_reg*4-4]
+%endif
+%endif
+
+%if mmsize == 8
+.next8px
+%endif
+    ; read
+    lea        dst2_reg, [dst_reg + stride_reg]
+%ifidn %2, v
+%if %4 == 8 && mmsize == 16
+%define movrow movh
+%else
+%define movrow mova
+%endif
+    movrow           m0, [dst_reg +mstride_reg*4] ; p3
+    movrow           m1, [dst2_reg+mstride_reg*4] ; p2
+    movrow           m2, [dst_reg +mstride_reg*2] ; p1
+    movrow           m5, [dst2_reg]               ; q1
+    movrow           m6, [dst2_reg+ stride_reg]   ; q2
+    movrow           m7, [dst2_reg+ stride_reg*2] ; q3
+%if mmsize == 16 && %4 == 8
+    movhps           m0, [dst8_reg+mstride_reg*4]
+    movhps           m2, [dst8_reg+mstride_reg*2]
+    add        dst8_reg, stride_reg
+    movhps           m1, [dst8_reg+mstride_reg*4]
+    movhps           m5, [dst8_reg]
+    movhps           m6, [dst8_reg+ stride_reg]
+    movhps           m7, [dst8_reg+ stride_reg*2]
+    add        dst8_reg, mstride_reg
+%endif
+%elif mmsize == 8 ; mmx/mmxext (h)
+    ; read 8 rows of 8px each
+    movu             m0, [dst_reg +mstride_reg*4]
+    movu             m1, [dst2_reg+mstride_reg*4]
+    movu             m2, [dst_reg +mstride_reg*2]
+    movu             m3, [dst_reg +mstride_reg]
+    movu             m4, [dst_reg]
+    movu             m5, [dst2_reg]
+    movu             m6, [dst2_reg+ stride_reg]
+
+    ; 8x8 transpose
+    TRANSPOSE4x4B     0, 1, 2, 3, 7
+    mova       q0backup, m1
+    movu             m7, [dst2_reg+ stride_reg*2]
+    TRANSPOSE4x4B     4, 5, 6, 7, 1
+    SBUTTERFLY       dq, 0, 4, 1     ; p3/p2
+    SBUTTERFLY       dq, 2, 6, 1     ; q0/q1
+    SBUTTERFLY       dq, 3, 7, 1     ; q2/q3
+    mova             m1, q0backup
+    mova       q0backup, m2          ; store q0
+    SBUTTERFLY       dq, 1, 5, 2     ; p1/p0
+    mova       p0backup, m5          ; store p0
+    SWAP              1, 4
+    SWAP              2, 4
+    SWAP              6, 3
+    SWAP              5, 3
+%else ; sse2 (h)
+%if %4 == 16
+    lea        dst8_reg, [dst_reg + stride_reg*8]
+%endif
+
+    ; read 16 rows of 8px each, interleave
+    movh             m0, [dst_reg +mstride_reg*4]
+    movh             m1, [dst8_reg+mstride_reg*4]
+    movh             m2, [dst_reg +mstride_reg*2]
+    movh             m5, [dst8_reg+mstride_reg*2]
+    movh             m3, [dst_reg +mstride_reg]
+    movh             m6, [dst8_reg+mstride_reg]
+    movh             m4, [dst_reg]
+    movh             m7, [dst8_reg]
+    punpcklbw        m0, m1          ; A/I
+    punpcklbw        m2, m5          ; C/K
+    punpcklbw        m3, m6          ; D/L
+    punpcklbw        m4, m7          ; E/M
+
+    add        dst8_reg, stride_reg
+    movh             m1, [dst2_reg+mstride_reg*4]
+    movh             m6, [dst8_reg+mstride_reg*4]
+    movh             m5, [dst2_reg]
+    movh             m7, [dst8_reg]
+    punpcklbw        m1, m6          ; B/J
+    punpcklbw        m5, m7          ; F/N
+    movh             m6, [dst2_reg+ stride_reg]
+    movh             m7, [dst8_reg+ stride_reg]
+    punpcklbw        m6, m7          ; G/O
+
+    ; 8x16 transpose
+    TRANSPOSE4x4B     0, 1, 2, 3, 7
+%ifdef m8
+    SWAP              1, 8
+%else
+    mova       q0backup, m1
+%endif
+    movh             m7, [dst2_reg+ stride_reg*2]
+    movh             m1, [dst8_reg+ stride_reg*2]
+    punpcklbw        m7, m1          ; H/P
+    TRANSPOSE4x4B     4, 5, 6, 7, 1
+    SBUTTERFLY       dq, 0, 4, 1     ; p3/p2
+    SBUTTERFLY       dq, 2, 6, 1     ; q0/q1
+    SBUTTERFLY       dq, 3, 7, 1     ; q2/q3
+%ifdef m8
+    SWAP              1, 8
+    SWAP              2, 8
+%else
+    mova             m1, q0backup
+    mova       q0backup, m2          ; store q0
+%endif
+    SBUTTERFLY       dq, 1, 5, 2     ; p1/p0
+%ifdef m12
+    SWAP              5, 12
+%else
+    mova       p0backup, m5          ; store p0
+%endif
+    SWAP              1, 4
+    SWAP              2, 4
+    SWAP              6, 3
+    SWAP              5, 3
+%endif
+
+    ; normal_limit for p3-p2, p2-p1, q3-q2 and q2-q1
+    mova             m4, m1
+    SWAP              4, 1
+    psubusb          m4, m0          ; p2-p3
+    psubusb          m0, m1          ; p3-p2
+    por              m0, m4          ; abs(p3-p2)
+
+    mova             m4, m2
+    SWAP              4, 2
+    psubusb          m4, m1          ; p1-p2
+    mova       p2backup, m1
+    psubusb          m1, m2          ; p2-p1
+    por              m1, m4          ; abs(p2-p1)
+
+    mova             m4, m6
+    SWAP              4, 6
+    psubusb          m4, m7          ; q2-q3
+    psubusb          m7, m6          ; q3-q2
+    por              m7, m4          ; abs(q3-q2)
+
+    mova             m4, m5
+    SWAP              4, 5
+    psubusb          m4, m6          ; q1-q2
+    mova       q2backup, m6
+    psubusb          m6, m5          ; q2-q1
+    por              m6, m4          ; abs(q2-q1)
+
+%ifidn %1, mmx
+    mova             m4, flim_I
+    pxor             m3, m3
+    psubusb          m0, m4
+    psubusb          m1, m4
+    psubusb          m7, m4
+    psubusb          m6, m4
+    pcmpeqb          m0, m3          ; abs(p3-p2) <= I
+    pcmpeqb          m1, m3          ; abs(p2-p1) <= I
+    pcmpeqb          m7, m3          ; abs(q3-q2) <= I
+    pcmpeqb          m6, m3          ; abs(q2-q1) <= I
+    pand             m0, m1
+    pand             m7, m6
+    pand             m0, m7
+%else ; mmxext/sse2
+    pmaxub           m0, m1
+    pmaxub           m6, m7
+    pmaxub           m0, m6
+%endif
+
+    ; normal_limit and high_edge_variance for p1-p0, q1-q0
+    SWAP              7, 3           ; now m7 is zero
+%ifidn %2, v
+    movrow           m3, [dst_reg +mstride_reg] ; p0
+%if mmsize == 16 && %4 == 8
+    movhps           m3, [dst8_reg+mstride_reg]
+%endif
+%elifdef m12
+    SWAP              3, 12
+%else
+    mova             m3, p0backup
+%endif
+
+    mova             m1, m2
+    SWAP              1, 2
+    mova             m6, m3
+    SWAP              3, 6
+    psubusb          m1, m3          ; p1-p0
+    psubusb          m6, m2          ; p0-p1
+    por              m1, m6          ; abs(p1-p0)
+%ifidn %1, mmx
+    mova             m6, m1
+    psubusb          m1, m4
+    psubusb          m6, hev_thr
+    pcmpeqb          m1, m7          ; abs(p1-p0) <= I
+    pcmpeqb          m6, m7          ; abs(p1-p0) <= hev_thresh
+    pand             m0, m1
+    mova       mask_res, m6
+%else ; mmxext/sse2
+    pmaxub           m0, m1          ; max_I
+    SWAP              1, 4           ; max_hev_thresh
+%endif
+
+    SWAP              6, 4           ; now m6 is I
+%ifidn %2, v
+    movrow           m4, [dst_reg]   ; q0
+%if mmsize == 16 && %4 == 8
+    movhps           m4, [dst8_reg]
+%endif
+%elifdef m8
+    SWAP              4, 8
+%else
+    mova             m4, q0backup
+%endif
+    mova             m1, m4
+    SWAP              1, 4
+    mova             m7, m5
+    SWAP              7, 5
+    psubusb          m1, m5          ; q0-q1
+    psubusb          m7, m4          ; q1-q0
+    por              m1, m7          ; abs(q1-q0)
+%ifidn %1, mmx
+    mova             m7, m1
+    psubusb          m1, m6
+    psubusb          m7, hev_thr
+    pxor             m6, m6
+    pcmpeqb          m1, m6          ; abs(q1-q0) <= I
+    pcmpeqb          m7, m6          ; abs(q1-q0) <= hev_thresh
+    mova             m6, mask_res
+    pand             m0, m1          ; abs([pq][321]-[pq][210]) <= I
+    pand             m6, m7
+%else ; mmxext/sse2
+    pxor             m7, m7
+    pmaxub           m0, m1
+    pmaxub           m6, m1
+    psubusb          m0, flim_I
+    psubusb          m6, hev_thr
+    pcmpeqb          m0, m7          ; max(abs(..)) <= I
+    pcmpeqb          m6, m7          ; !(max(abs..) > thresh)
+%endif
+%ifdef m12
+    SWAP              6, 12
+%else
+    mova       mask_res, m6          ; !(abs(p1-p0) > hev_t || abs(q1-q0) > hev_t)
+%endif
+
+    ; simple_limit
+    mova             m1, m3
+    SWAP              1, 3
+    mova             m6, m4          ; keep copies of p0/q0 around for later use
+    SWAP              6, 4
+    psubusb          m1, m4          ; p0-q0
+    psubusb          m6, m3          ; q0-p0
+    por              m1, m6          ; abs(q0-p0)
+    paddusb          m1, m1          ; m1=2*abs(q0-p0)
+
+    mova             m7, m2
+    SWAP              7, 2
+    mova             m6, m5
+    SWAP              6, 5
+    psubusb          m7, m5          ; p1-q1
+    psubusb          m6, m2          ; q1-p1
+    por              m7, m6          ; abs(q1-p1)
+    pxor             m6, m6
+    pand             m7, [pb_FE]
+    psrlq            m7, 1           ; abs(q1-p1)/2
+    paddusb          m7, m1          ; abs(q0-p0)*2+abs(q1-p1)/2
+    psubusb          m7, flim_E
+    pcmpeqb          m7, m6          ; abs(q0-p0)*2+abs(q1-p1)/2 <= E
+    pand             m0, m7          ; normal_limit result
+
+    ; filter_common; at this point, m2-m5=p1-q1 and m0 is filter_mask
+%ifdef m8 ; x86-64 && sse2
+    mova             m8, [pb_80]
+%define pb_80_var m8
+%else ; x86-32 or mmx/mmxext
+%define pb_80_var [pb_80]
+%endif
+    mova             m1, m4
+    mova             m7, m3
+    pxor             m1, pb_80_var
+    pxor             m7, pb_80_var
+    psubsb           m1, m7          ; (signed) q0-p0
+    mova             m6, m2
+    mova             m7, m5
+    pxor             m6, pb_80_var
+    pxor             m7, pb_80_var
+    psubsb           m6, m7          ; (signed) p1-q1
+    mova             m7, mask_res
+    paddsb           m6, m1
+    paddsb           m6, m1
+    paddsb           m6, m1
+    pand             m6, m0
+%ifdef m8
+    mova        lim_res, m6          ; 3*(qp-p0)+(p1-q1) masked for filter_mbedge
+    pand        lim_res, m7
+%else
+    mova             m0, m6
+    pand             m0, m7
+    mova        lim_res, m0
+%endif
+    pandn            m7, m6          ; 3*(q0-p0)+(p1-q1) masked for filter_common
+
+    mova             m1, [pb_F8]
+    mova             m6, m7
+    paddsb           m7, [pb_3]
+    paddsb           m6, [pb_4]
+    pand             m7, m1
+    pand             m6, m1
+
+    pxor             m1, m1
+    pxor             m0, m0
+    pcmpgtb          m1, m7
+    psubb            m0, m7
+    psrlq            m7, 3           ; +f2
+    psrlq            m0, 3           ; -f2
+    pand             m0, m1
+    pandn            m1, m7
+    psubusb          m3, m0
+    paddusb          m3, m1          ; p0+f2
+
+    pxor             m1, m1
+    pxor             m0, m0
+    pcmpgtb          m0, m6
+    psubb            m1, m6
+    psrlq            m6, 3           ; +f1
+    psrlq            m1, 3           ; -f1
+    pand             m1, m0
+    pandn            m0, m6
+    psubusb          m4, m0
+    paddusb          m4, m1          ; q0-f1
+
+    ; filter_mbedge (m2-m5 = p1-q1; lim_res carries w)
+%if ssse3_or_higher
+    mova             m7, [pb_1]
+%else
+    mova             m7, [pw_63]
+%endif
+%ifdef m8
+    SWAP              1, 8
+%else
+    mova             m1, lim_res
+%endif
+    pxor             m0, m0
+    mova             m6, m1
+    pcmpgtb          m0, m1         ; which are negative
+%if ssse3_or_higher
+    punpcklbw        m6, m7         ; interleave with "1" for rounding
+    punpckhbw        m1, m7
+%else
+    punpcklbw        m6, m0         ; signed byte->word
+    punpckhbw        m1, m0
+%endif
+    mova       lim_sign, m0
+%if ssse3_or_higher
+    mova             m7, [pb_27_63]
+%ifndef m8
+    mova        lim_res, m1
+%endif
+%ifdef m10
+    SWAP              0, 10         ; don't lose lim_sign copy
+%endif
+    mova             m0, m7
+    pmaddubsw        m7, m6
+    SWAP              6, 7
+    pmaddubsw        m0, m1
+    SWAP              1, 0
+%ifdef m10
+    SWAP              0, 10
+%else
+    mova             m0, lim_sign
+%endif
+%else
+    mova       mask_res, m6         ; backup for later in filter
+    mova        lim_res, m1
+    pmullw          m6, [pw_27]
+    pmullw          m1, [pw_27]
+    paddw           m6, m7
+    paddw           m1, m7
+%endif
+    psraw           m6, 7
+    psraw           m1, 7
+    packsswb        m6, m1          ; a0
+    pxor            m1, m1
+    psubb           m1, m6
+    pand            m1, m0          ; -a0
+    pandn           m0, m6          ; +a0
+%if ssse3_or_higher
+    mova            m6, [pb_18_63]  ; pipelining
+%endif
+    psubusb         m3, m1
+    paddusb         m4, m1
+    paddusb         m3, m0          ; p0+a0
+    psubusb         m4, m0          ; q0-a0
+
+%if ssse3_or_higher
+    SWAP             6, 7
+%ifdef m10
+    SWAP             1, 10
+%else
+    mova            m1, lim_res
+%endif
+    mova            m0, m7
+    pmaddubsw       m7, m6
+    SWAP             6, 7
+    pmaddubsw       m0, m1
+    SWAP             1, 0
+%ifdef m10
+    SWAP             0, 10
+%endif
+    mova            m0, lim_sign
+%else
+    mova            m6, mask_res
+    mova            m1, lim_res
+    pmullw          m6, [pw_18]
+    pmullw          m1, [pw_18]
+    paddw           m6, m7
+    paddw           m1, m7
+%endif
+    mova            m0, lim_sign
+    psraw           m6, 7
+    psraw           m1, 7
+    packsswb        m6, m1          ; a1
+    pxor            m1, m1
+    psubb           m1, m6
+    pand            m1, m0          ; -a1
+    pandn           m0, m6          ; +a1
+%if ssse3_or_higher
+    mova            m6, [pb_9_63]
+%endif
+    psubusb         m2, m1
+    paddusb         m5, m1
+    paddusb         m2, m0          ; p1+a1
+    psubusb         m5, m0          ; q1-a1
+
+%if ssse3_or_higher
+    SWAP             6, 7
+%ifdef m10
+    SWAP             1, 10
+%else
+    mova            m1, lim_res
+%endif
+    mova            m0, m7
+    pmaddubsw       m7, m6
+    SWAP             6, 7
+    pmaddubsw       m0, m1
+    SWAP             1, 0
+%else
+%ifdef m8
+    SWAP             6, 12
+    SWAP             1, 8
+%else
+    mova            m6, mask_res
+    mova            m1, lim_res
+%endif
+    pmullw          m6, [pw_9]
+    pmullw          m1, [pw_9]
+    paddw           m6, m7
+    paddw           m1, m7
+%endif
+%ifdef m9
+    SWAP             7, 9
+%else
+    mova            m7, lim_sign
+%endif
+    psraw           m6, 7
+    psraw           m1, 7
+    packsswb        m6, m1          ; a1
+    pxor            m0, m0
+    psubb           m0, m6
+    pand            m0, m7          ; -a1
+    pandn           m7, m6          ; +a1
+%ifdef m8
+    SWAP             1, 13
+    SWAP             6, 14
+%else
+    mova            m1, p2backup
+    mova            m6, q2backup
+%endif
+    psubusb         m1, m0
+    paddusb         m6, m0
+    paddusb         m1, m7          ; p1+a1
+    psubusb         m6, m7          ; q1-a1
+
+    ; store
+%ifidn %2, v
+    movrow [dst2_reg+mstride_reg*4], m1
+    movrow [dst_reg +mstride_reg*2], m2
+    movrow [dst_reg +mstride_reg  ], m3
+    movrow    [dst_reg], m4
+    movrow   [dst2_reg], m5
+    movrow [dst2_reg+ stride_reg  ], m6
+%if mmsize == 16 && %4 == 8
+    add        dst8_reg, mstride_reg
+    movhps [dst8_reg+mstride_reg*2], m1
+    movhps [dst8_reg+mstride_reg  ], m2
+    movhps   [dst8_reg], m3
+    add        dst8_reg, stride_reg
+    movhps   [dst8_reg], m4
+    movhps [dst8_reg+ stride_reg  ], m5
+    movhps [dst8_reg+ stride_reg*2], m6
+%endif
+%else ; h
+    inc         dst_reg
+    inc        dst2_reg
+
+    ; 4x8/16 transpose
+    TRANSPOSE4x4B     1, 2, 3, 4, 0
+    SBUTTERFLY       bw, 5, 6, 0
+
+%if mmsize == 8 ; mmx/mmxext (h)
+    WRITE_4x2D        1, 2, 3, 4, dst_reg, dst2_reg, mstride_reg, stride_reg
+    add         dst_reg, 4
+    WRITE_2x4W       m5, m6, dst2_reg, dst_reg, mstride_reg, stride_reg
+%else ; sse2 (h)
+    lea        dst8_reg, [dst8_reg+mstride_reg+1]
+    WRITE_4x4D        1, 2, 3, 4, dst_reg, dst2_reg, dst8_reg, mstride_reg, stride_reg, %4
+    lea         dst_reg, [dst2_reg+mstride_reg+4]
+    lea        dst8_reg, [dst8_reg+mstride_reg+4]
+%ifidn %1, sse4
+    add        dst2_reg, 4
+%endif
+    WRITE_8W         m5, dst2_reg, dst_reg,  mstride_reg, stride_reg
+%ifidn %1, sse4
+    lea        dst2_reg, [dst8_reg+ stride_reg]
+%endif
+    WRITE_8W         m6, dst2_reg, dst8_reg, mstride_reg, stride_reg
+%endif
+%endif
+
+%if mmsize == 8
+%if %4 == 8 ; chroma
+%ifidn %2, h
+    sub         dst_reg, 5
+%endif
+    cmp         dst_reg, dst8_reg
+    mov         dst_reg, dst8_reg
+    jnz .next8px
+%else
+%ifidn %2, h
+    lea         dst_reg, [dst_reg + stride_reg*8-5]
+%else ; v
+    add         dst_reg, 8
+%endif
+    dec         cnt_reg
+    jg .next8px
+%endif
+%endif
+
+%ifndef m8 ; sse2 on x86-32 or mmx/mmxext
+    mov             rsp, stack_reg   ; restore stack pointer
+%endif
+    RET
+%endmacro
+
+INIT_MMX
+%define SPLATB_REG SPLATB_REG_MMX
+MBEDGE_LOOPFILTER mmx,    v, 6, 16, 0
+MBEDGE_LOOPFILTER mmx,    h, 6, 16, 0
+MBEDGE_LOOPFILTER mmx,    v, 6,  8, 0
+MBEDGE_LOOPFILTER mmx,    h, 6,  8, 0
+
+%define SPLATB_REG SPLATB_REG_MMXEXT
+MBEDGE_LOOPFILTER mmxext, v, 6, 16, 0
+MBEDGE_LOOPFILTER mmxext, h, 6, 16, 0
+MBEDGE_LOOPFILTER mmxext, v, 6,  8, 0
+MBEDGE_LOOPFILTER mmxext, h, 6,  8, 0
+
+INIT_XMM
+%define SPLATB_REG SPLATB_REG_SSE2
+%define WRITE_8W   WRITE_8W_SSE2
+MBEDGE_LOOPFILTER sse2,   v, 5, 16, 15
+%ifdef m8
+MBEDGE_LOOPFILTER sse2,   h, 5, 16, 15
+%else
+MBEDGE_LOOPFILTER sse2,   h, 6, 16, 15
+%endif
+MBEDGE_LOOPFILTER sse2,   v, 6,  8, 15
+MBEDGE_LOOPFILTER sse2,   h, 6,  8, 15
+
+%define SPLATB_REG SPLATB_REG_SSSE3
+MBEDGE_LOOPFILTER ssse3,  v, 5, 16, 15
+%ifdef m8
+MBEDGE_LOOPFILTER ssse3,  h, 5, 16, 15
+%else
+MBEDGE_LOOPFILTER ssse3,  h, 6, 16, 15
+%endif
+MBEDGE_LOOPFILTER ssse3,  v, 6,  8, 15
+MBEDGE_LOOPFILTER ssse3,  h, 6,  8, 15
+
+%define WRITE_8W   WRITE_8W_SSE4
+%ifdef m8
+MBEDGE_LOOPFILTER sse4,   h, 5, 16, 15
+%else
+MBEDGE_LOOPFILTER sse4,   h, 6, 16, 15
+%endif
+MBEDGE_LOOPFILTER sse4,   h, 6,  8, 15
diff --git a/libavcodec/x86/x86inc.asm b/libavcodec/x86/x86inc.asm
index c29ef3e..b7d1774 100644
--- a/libavcodec/x86/x86inc.asm
+++ b/libavcodec/x86/x86inc.asm
@@ -1,25 +1,39 @@
 ;*****************************************************************************
 ;* x86inc.asm
 ;*****************************************************************************
-;* Copyright (C) 2005-2008 Loren Merritt <lorenm at u.washington.edu>
+;* Copyright (C) 2005-2008 x264 project
 ;*
-;* This file is part of FFmpeg.
+;* Authors: Loren Merritt <lorenm at u.washington.edu>
+;*          Anton Mitrofanov <BugMaster at narod.ru>
 ;*
-;* FFmpeg is free software; you can redistribute it and/or
-;* modify it under the terms of the GNU Lesser General Public
-;* License as published by the Free Software Foundation; either
-;* version 2.1 of the License, or (at your option) any later version.
+;* Permission to use, copy, modify, and/or distribute this software for any
+;* purpose with or without fee is hereby granted, provided that the above
+;* copyright notice and this permission notice appear in all copies.
 ;*
-;* FFmpeg is distributed in the hope that it will be useful,
-;* but WITHOUT ANY WARRANTY; without even the implied warranty of
-;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-;* Lesser General Public License for more details.
-;*
-;* You should have received a copy of the GNU Lesser General Public
-;* License along with FFmpeg; if not, write to the Free Software
-;* 51, Inc., Foundation Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+;* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+;* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+;* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+;* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+;* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+;* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+;* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 ;*****************************************************************************
 
+; This is a header file for the x264ASM assembly language, which uses
+; NASM/YASM syntax combined with a large number of macros to provide easy
+; abstraction between different calling conventions (x86_32, win64, linux64).
+; It also has various other useful features to simplify writing the kind of
+; DSP functions that are most often used in x264.
+
+; Unlike the rest of x264, this file is available under an ISC license, as it
+; has significant usefulness outside of x264 and we want it to be available
+; to the largest audience possible.  Of course, if you modify it for your own
+; purposes to add a new feature, we strongly encourage contributing a patch
+; as this feature might be useful for others as well.  Send patches or ideas
+; to x264-devel at videolan.org .
+
+%define program_name ff
+
 %ifdef ARCH_X86_64
     %ifidn __OUTPUT_FORMAT__,win32
         %define WIN64
@@ -28,6 +42,12 @@
     %endif
 %endif
 
+%ifdef PREFIX
+    %define mangle(x) _ %+ x
+%else
+    %define mangle(x) x
+%endif
+
 ; FIXME: All of the 64bit asm functions that take a stride as an argument
 ; via register, assume that the high dword of that register is filled with 0.
 ; This is true in practice (since we never do any 64bit arithmetic on strides,
@@ -47,28 +67,16 @@
     %endif
 %endmacro
 
-; PIC support macros.
-; x86_64 can't fit 64bit address literals in most instruction types,
-; so shared objects (under the assumption that they might be anywhere
-; in memory) must use an address mode that does fit.
-; So all accesses to global variables must use this macro, e.g.
-;     mov eax, [foo GLOBAL]
-; instead of
-;     mov eax, [foo]
-;
-; x86_32 doesn't require PIC.
-; Some distros prefer shared objects to be PIC, but nothing breaks if
-; the code contains a few textrels, so we'll skip that complexity.
-
 %ifdef WIN64
     %define PIC
 %elifndef ARCH_X86_64
+; x86_32 doesn't require PIC.
+; Some distros prefer shared objects to be PIC, but nothing breaks if
+; the code contains a few textrels, so we'll skip that complexity.
     %undef PIC
 %endif
 %ifdef PIC
-    %define GLOBAL wrt rip
-%else
-    %define GLOBAL
+    default rel
 %endif
 
 ; Macros to eliminate most code duplication between x86_32 and x86_64:
@@ -163,7 +171,7 @@ DECLARE_REG_SIZE bp, bpl
     %endrep
 %endmacro
 
-DECLARE_REG_TMP_SIZE 0,1,2,3,4,5,6,7
+DECLARE_REG_TMP_SIZE 0,1,2,3,4,5,6,7,8,9
 
 %ifdef ARCH_X86_64
     %define gprsize 8
@@ -259,21 +267,25 @@ DECLARE_REG 6, rax, eax, ax,  al,  [rsp + stack_offset + 56]
     %endif
 %endmacro
 
-%macro PROLOGUE 2-4+ ; #args, #regs, #xmm_regs, arg_names...
+%macro PROLOGUE 2-4+ 0 ; #args, #regs, #xmm_regs, arg_names...
     ASSERT %2 >= %1
     %assign regs_used %2
     ASSERT regs_used <= 7
-    %if %0 > 2
-        %assign xmm_regs_used %3
-    %else
-        %assign xmm_regs_used 0
-    %endif
-    ASSERT xmm_regs_used <= 16
     %if regs_used > 4
         push r4
         push r5
         %assign stack_offset stack_offset+16
     %endif
+    WIN64_SPILL_XMM %3
+    LOAD_IF_USED 4, %1
+    LOAD_IF_USED 5, %1
+    LOAD_IF_USED 6, %1
+    DEFINE_ARGS %4
+%endmacro
+
+%macro WIN64_SPILL_XMM 1
+    %assign xmm_regs_used %1
+    ASSERT xmm_regs_used <= 16
     %if xmm_regs_used > 6
         sub rsp, (xmm_regs_used-6)*16+16
         %assign stack_offset stack_offset+(xmm_regs_used-6)*16+16
@@ -283,13 +295,9 @@ DECLARE_REG 6, rax, eax, ax,  al,  [rsp + stack_offset + 56]
             movdqa [rsp + (%%i-6)*16+8], xmm %+ %%i
         %endrep
     %endif
-    LOAD_IF_USED 4, %1
-    LOAD_IF_USED 5, %1
-    LOAD_IF_USED 6, %1
-    DEFINE_ARGS %4
 %endmacro
 
-%macro RESTORE_XMM_INTERNAL 1
+%macro WIN64_RESTORE_XMM_INTERNAL 1
     %if xmm_regs_used > 6
         %assign %%i xmm_regs_used
         %rep (xmm_regs_used-6)
@@ -300,14 +308,14 @@ DECLARE_REG 6, rax, eax, ax,  al,  [rsp + stack_offset + 56]
     %endif
 %endmacro
 
-%macro RESTORE_XMM 1
-    RESTORE_XMM_INTERNAL %1
+%macro WIN64_RESTORE_XMM 1
+    WIN64_RESTORE_XMM_INTERNAL %1
     %assign stack_offset stack_offset-(xmm_regs_used-6)*16+16
     %assign xmm_regs_used 0
 %endmacro
 
 %macro RET 0
-    RESTORE_XMM_INTERNAL rsp
+    WIN64_RESTORE_XMM_INTERNAL rsp
     %if regs_used > 4
         pop r5
         pop r4
@@ -388,7 +396,7 @@ DECLARE_REG 6, ebp, ebp, bp, null, [esp + stack_offset + 28]
     %endif
 %endmacro
 
-%macro PROLOGUE 2-4+ ; #args, #regs, arg_names...
+%macro PROLOGUE 2-4+ ; #args, #regs, #xmm_regs, arg_names...
     ASSERT %2 >= %1
     %assign regs_used %2
     ASSERT regs_used <= 7
@@ -424,6 +432,13 @@ DECLARE_REG 6, ebp, ebp, bp, null, [esp + stack_offset + 28]
 
 %endif ;======================================================================
 
+%ifndef WIN64
+%macro WIN64_SPILL_XMM 1
+%endmacro
+%macro WIN64_RESTORE_XMM 1
+%endmacro
+%endif
+
 
 
 ;=============================================================================
@@ -434,10 +449,7 @@ DECLARE_REG 6, ebp, ebp, bp, null, [esp + stack_offset + 28]
 
 ; Symbol prefix for C linkage
 %macro cglobal 1-2+
-    %xdefine %1 ff_%1
-    %ifdef PREFIX
-        %xdefine %1 _ %+ %1
-    %endif
+    %xdefine %1 mangle(program_name %+ _ %+ %1)
     %xdefine %1.skip_prologue %1 %+ .skip_prologue
     %ifidn __OUTPUT_FORMAT__,elf
         global %1:function hidden
@@ -454,21 +466,28 @@ DECLARE_REG 6, ebp, ebp, bp, null, [esp + stack_offset + 28]
 %endmacro
 
 %macro cextern 1
-    %ifdef PREFIX
-        %xdefine %1 _%1
-    %endif
+    %xdefine %1 mangle(program_name %+ _ %+ %1)
     extern %1
 %endmacro
 
+;like cextern, but without the prefix
+%macro cextern_naked 1
+    %xdefine %1 mangle(%1)
+    extern %1
+%endmacro
+
+%macro const 2+
+    %xdefine %1 mangle(program_name %+ _ %+ %1)
+    global %1
+    %1: %2
+%endmacro
+
 ; This is needed for ELF, otherwise the GNU linker assumes the stack is
 ; executable by default.
 %ifidn __OUTPUT_FORMAT__,elf
 SECTION .note.GNU-stack noalloc noexec nowrite progbits
 %endif
 
-%assign FENC_STRIDE 16
-%assign FDEC_STRIDE 32
-
 ; merge mmx and sse*
 
 %macro CAT_XDEFINE 3
@@ -486,7 +505,7 @@ SECTION .note.GNU-stack noalloc noexec nowrite progbits
     %define mova movq
     %define movu movq
     %define movh movd
-    %define movnt movntq
+    %define movnta movntq
     %assign %%i 0
     %rep 8
     CAT_XDEFINE m, %%i, mm %+ %%i
@@ -510,7 +529,7 @@ SECTION .note.GNU-stack noalloc noexec nowrite progbits
     %define mova movdqa
     %define movu movdqu
     %define movh movq
-    %define movnt movntdq
+    %define movnta movntdq
     %assign %%i 0
     %rep num_mmregs
     CAT_XDEFINE m, %%i, xmm %+ %%i
@@ -575,7 +594,10 @@ INIT_MMX
 %endrep
 %endmacro
 
-%macro SAVE_MM_PERMUTATION 1
+; If SAVE_MM_PERMUTATION is placed at the end of a function and given the
+; function name, then any later calls to that function will automatically
+; load the permutation, so values can be returned in mmregs.
+%macro SAVE_MM_PERMUTATION 1 ; name to save as
     %assign %%i 0
     %rep num_mmregs
     CAT_XDEFINE %1_m, %%i, m %+ %%i
@@ -583,7 +605,7 @@ INIT_MMX
     %endrep
 %endmacro
 
-%macro LOAD_MM_PERMUTATION 1
+%macro LOAD_MM_PERMUTATION 1 ; name to load from
     %assign %%i 0
     %rep num_mmregs
     CAT_XDEFINE m, %%i, %1_m %+ %%i
@@ -599,7 +621,7 @@ INIT_MMX
     %endif
 %endmacro
 
-;Substitutions that reduce instruction size but are functionally equivalent
+; Substitutions that reduce instruction size but are functionally equivalent
 %macro add 2
     %ifnum %2
         %if %2==128
diff --git a/libavcodec/x86/x86util.asm b/libavcodec/x86/x86util.asm
index f3e0e2d..f731616 100644
--- a/libavcodec/x86/x86util.asm
+++ b/libavcodec/x86/x86util.asm
@@ -1,22 +1,27 @@
 ;*****************************************************************************
 ;* x86util.asm
 ;*****************************************************************************
-;* Copyright (C) 2008 Loren Merritt <lorenm at u.washington.edu>
+;* Copyright (C) 2008-2010 x264 project
 ;*
-;* This program is free software; you can redistribute it and/or modify
-;* it under the terms of the GNU General Public License as published by
-;* the Free Software Foundation; either version 2 of the License, or
-;* (at your option) any later version.
+;* Authors: Loren Merritt <lorenm at u.washington.edu>
+;*          Holger Lubitz <holger at lubitz.org>
 ;*
-;* This program is distributed in the hope that it will be useful,
+;* This file is part of Libav.
+;*
+;* Libav is free software; you can redistribute it and/or
+;* modify it under the terms of the GNU Lesser General Public
+;* License as published by the Free Software Foundation; either
+;* version 2.1 of the License, or (at your option) any later version.
+;*
+;* Libav is distributed in the hope that it will be useful,
 ;* but WITHOUT ANY WARRANTY; without even the implied warranty of
-;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-;* GNU General Public License for more details.
+;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+;* Lesser General Public License for more details.
 ;*
-;* You should have received a copy of the GNU General Public License
-;* along with this program; if not, write to the Free Software
-;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111, USA.
-;*****************************************************************************
+;* You should have received a copy of the GNU Lesser General Public
+;* License along with Libav; if not, write to the Free Software
+;* 51, Inc., Foundation Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+;******************************************************************************
 
 %macro SBUTTERFLY 4
     mova      m%4, m%2
@@ -25,6 +30,21 @@
     SWAP %3, %4
 %endmacro
 
+%macro SBUTTERFLY2 4
+    mova      m%4, m%2
+    punpckh%1 m%2, m%3
+    punpckl%1 m%4, m%3
+    SWAP %2, %4, %3
+%endmacro
+
+%macro TRANSPOSE4x4B 5
+    SBUTTERFLY bw, %1, %2, %5
+    SBUTTERFLY bw, %3, %4, %5
+    SBUTTERFLY wd, %1, %3, %5
+    SBUTTERFLY wd, %2, %4, %5
+    SWAP %2, %3
+%endmacro
+
 %macro TRANSPOSE4x4W 5
     SBUTTERFLY wd, %1, %2, %5
     SBUTTERFLY wd, %3, %4, %5
@@ -99,13 +119,59 @@
 %endif
 %endmacro
 
+; PABSW macros assume %1 != %2, while ABS1/2 macros work in-place
+%macro PABSW_MMX 2
+    pxor       %1, %1
+    pcmpgtw    %1, %2
+    pxor       %2, %1
+    psubw      %2, %1
+    SWAP       %1, %2
+%endmacro
+
+%macro PSIGNW_MMX 2
+    pxor       %1, %2
+    psubw      %1, %2
+%endmacro
+
+%macro PABSW_MMX2 2
+    pxor    %1, %1
+    psubw   %1, %2
+    pmaxsw  %1, %2
+%endmacro
+
+%macro PABSW_SSSE3 2
+    pabsw      %1, %2
+%endmacro
+
+%macro PSIGNW_SSSE3 2
+    psignw     %1, %2
+%endmacro
+
 %macro ABS1_MMX 2    ; a, tmp
+    pxor       %2, %2
+    pcmpgtw    %2, %1
+    pxor       %1, %2
+    psubw      %1, %2
+%endmacro
+
+%macro ABS2_MMX 4    ; a, b, tmp0, tmp1
+    pxor       %3, %3
+    pxor       %4, %4
+    pcmpgtw    %3, %1
+    pcmpgtw    %4, %2
+    pxor       %1, %3
+    pxor       %2, %4
+    psubw      %1, %3
+    psubw      %2, %4
+%endmacro
+
+%macro ABS1_MMX2 2   ; a, tmp
     pxor    %2, %2
     psubw   %2, %1
     pmaxsw  %1, %2
 %endmacro
 
-%macro ABS2_MMX 4    ; a, b, tmp0, tmp1
+%macro ABS2_MMX2 4   ; a, b, tmp0, tmp1
     pxor    %3, %3
     pxor    %4, %4
     psubw   %3, %1
@@ -123,14 +189,40 @@
     pabsw   %2, %2
 %endmacro
 
-%define ABS1 ABS1_MMX
-%define ABS2 ABS2_MMX
+%macro ABSB_MMX 2
+    pxor    %2, %2
+    psubb   %2, %1
+    pminub  %1, %2
+%endmacro
+
+%macro ABSB2_MMX 4
+    pxor    %3, %3
+    pxor    %4, %4
+    psubb   %3, %1
+    psubb   %4, %2
+    pminub  %1, %3
+    pminub  %2, %4
+%endmacro
+
+%macro ABSB_SSSE3 2
+    pabsb   %1, %1
+%endmacro
+
+%macro ABSB2_SSSE3 4
+    pabsb   %1, %1
+    pabsb   %2, %2
+%endmacro
 
 %macro ABS4 6
     ABS2 %1, %2, %5, %6
     ABS2 %3, %4, %5, %6
 %endmacro
 
+%define ABS1 ABS1_MMX
+%define ABS2 ABS2_MMX
+%define ABSB ABSB_MMX
+%define ABSB2 ABSB2_MMX
+
 %macro SPLATB_MMX 3
     movd      %1, [%2-3] ;to avoid crossing a cacheline
     punpcklbw %1, %1
@@ -205,165 +297,6 @@
 %endif
 %endmacro
 
-%macro HADAMARD4_V 4+
-    SUMSUB_BADC %1, %2, %3, %4
-    SUMSUB_BADC %1, %3, %2, %4
-%endmacro
-
-%macro HADAMARD8_V 8+
-    SUMSUB_BADC %1, %2, %3, %4
-    SUMSUB_BADC %5, %6, %7, %8
-    SUMSUB_BADC %1, %3, %2, %4
-    SUMSUB_BADC %5, %7, %6, %8
-    SUMSUB_BADC %1, %5, %2, %6
-    SUMSUB_BADC %3, %7, %4, %8
-%endmacro
-
-%macro TRANS_SSE2 5-6
-; TRANSPOSE2x2
-; %1: transpose width (d/q) - use SBUTTERFLY qdq for dq
-; %2: ord/unord (for compat with sse4, unused)
-; %3/%4: source regs
-; %5/%6: tmp regs
-%ifidn %1, d
-%define mask [mask_10 GLOBAL]
-%define shift 16
-%elifidn %1, q
-%define mask [mask_1100 GLOBAL]
-%define shift 32
-%endif
-%if %0==6 ; less dependency if we have two tmp
-    mova   m%5, mask   ; ff00
-    mova   m%6, m%4    ; x5x4
-    psll%1 m%4, shift  ; x4..
-    pand   m%6, m%5    ; x5..
-    pandn  m%5, m%3    ; ..x0
-    psrl%1 m%3, shift  ; ..x1
-    por    m%4, m%5    ; x4x0
-    por    m%3, m%6    ; x5x1
-%else ; more dependency, one insn less. sometimes faster, sometimes not
-    mova   m%5, m%4    ; x5x4
-    psll%1 m%4, shift  ; x4..
-    pxor   m%4, m%3    ; (x4^x1)x0
-    pand   m%4, mask   ; (x4^x1)..
-    pxor   m%3, m%4    ; x4x0
-    psrl%1 m%4, shift  ; ..(x1^x4)
-    pxor   m%5, m%4    ; x5x1
-    SWAP   %4, %3, %5
-%endif
-%endmacro
-
-%macro TRANS_SSE4 5-6 ; see above
-%ifidn %1, d
-    mova   m%5, m%3
-%ifidn %2, ord
-    psrl%1 m%3, 16
-%endif
-    pblendw m%3, m%4, 10101010b
-    psll%1 m%4, 16
-%ifidn %2, ord
-    pblendw m%4, m%5, 01010101b
-%else
-    psrl%1 m%5, 16
-    por    m%4, m%5
-%endif
-%elifidn %1, q
-    mova   m%5, m%3
-    shufps m%3, m%4, 10001000b
-    shufps m%5, m%4, 11011101b
-    SWAP   %4, %5
-%endif
-%endmacro
-
-%macro HADAMARD 5-6
-; %1=distance in words (0 for vertical pass, 1/2/4 for horizontal passes)
-; %2=sumsub/max/amax (sum and diff / maximum / maximum of absolutes)
-; %3/%4: regs
-; %5(%6): tmpregs
-%if %1!=0 ; have to reorder stuff for horizontal op
-    %ifidn %2, sumsub
-         %define ORDER ord
-         ; sumsub needs order because a-b != b-a unless a=b
-    %else
-         %define ORDER unord
-         ; if we just max, order doesn't matter (allows pblendw+or in sse4)
-    %endif
-    %if %1==1
-         TRANS d, ORDER, %3, %4, %5, %6
-    %elif %1==2
-         %if mmsize==8
-             SBUTTERFLY dq, %3, %4, %5
-         %else
-             TRANS q, ORDER, %3, %4, %5, %6
-         %endif
-    %elif %1==4
-         SBUTTERFLY qdq, %3, %4, %5
-    %endif
-%endif
-%ifidn %2, sumsub
-    SUMSUB_BA m%3, m%4, m%5
-%else
-    %ifidn %2, amax
-        %if %0==6
-            ABS2 m%3, m%4, m%5, m%6
-        %else
-            ABS1 m%3, m%5
-            ABS1 m%4, m%5
-        %endif
-    %endif
-    pmaxsw m%3, m%4
-%endif
-%endmacro
-
-
-%macro HADAMARD2_2D 6-7 sumsub
-    HADAMARD 0, sumsub, %1, %2, %5
-    HADAMARD 0, sumsub, %3, %4, %5
-    SBUTTERFLY %6, %1, %2, %5
-%ifnum %7
-    HADAMARD 0, amax, %1, %2, %5, %7
-%else
-    HADAMARD 0, %7, %1, %2, %5
-%endif
-    SBUTTERFLY %6, %3, %4, %5
-%ifnum %7
-    HADAMARD 0, amax, %3, %4, %5, %7
-%else
-    HADAMARD 0, %7, %3, %4, %5
-%endif
-%endmacro
-
-%macro HADAMARD4_2D 5-6 sumsub
-    HADAMARD2_2D %1, %2, %3, %4, %5, wd
-    HADAMARD2_2D %1, %3, %2, %4, %5, dq, %6
-    SWAP %2, %3
-%endmacro
-
-%macro HADAMARD4_2D_SSE 5-6 sumsub
-    HADAMARD  0, sumsub, %1, %2, %5 ; 1st V row 0 + 1
-    HADAMARD  0, sumsub, %3, %4, %5 ; 1st V row 2 + 3
-    SBUTTERFLY   wd, %1, %2, %5     ; %1: m0 1+0 %2: m1 1+0
-    SBUTTERFLY   wd, %3, %4, %5     ; %3: m0 3+2 %4: m1 3+2
-    HADAMARD2_2D %1, %3, %2, %4, %5, dq
-    SBUTTERFLY  qdq, %1, %2, %5
-    HADAMARD  0, %6, %1, %2, %5     ; 2nd H m1/m0 row 0+1
-    SBUTTERFLY  qdq, %3, %4, %5
-    HADAMARD  0, %6, %3, %4, %5     ; 2nd H m1/m0 row 2+3
-%endmacro
-
-%macro HADAMARD8_2D 9-10 sumsub
-    HADAMARD2_2D %1, %2, %3, %4, %9, wd
-    HADAMARD2_2D %5, %6, %7, %8, %9, wd
-    HADAMARD2_2D %1, %3, %2, %4, %9, dq
-    HADAMARD2_2D %5, %7, %6, %8, %9, dq
-    HADAMARD2_2D %1, %5, %3, %7, %9, qdq, %10
-    HADAMARD2_2D %2, %6, %4, %8, %9, qdq, %10
-%ifnidn %10, amax
-    SWAP %2, %5
-    SWAP %4, %7
-%endif
-%endmacro
-
 %macro SUMSUB2_AB 3
     mova    %3, %1
     paddw   %1, %1
@@ -383,10 +316,10 @@
 %macro SUMSUBD2_AB 4
     mova    %4, %1
     mova    %3, %2
-    psraw   %2, 1
-    psraw   %1, 1
-    paddw   %2, %4
-    psubw   %1, %3
+    psraw   %2, 1  ; %2: %2>>1
+    psraw   %1, 1  ; %1: %1>>1
+    paddw   %2, %4 ; %2: %2>>1+%1
+    psubw   %1, %3 ; %1: %1>>1-%2
 %endmacro
 
 %macro DCT4_1D 5
@@ -407,16 +340,27 @@
 %macro IDCT4_1D 5-6
 %ifnum %5
     SUMSUBD2_AB m%2, m%4, m%6, m%5
+    ; %2: %2>>1-%4 %4: %2+%4>>1
     SUMSUB_BA   m%3, m%1, m%6
+    ; %3: %1+%3 %1: %1-%3
     SUMSUB_BADC m%4, m%3, m%2, m%1, m%6
+    ; %4: %1+%3 + (%2+%4>>1)
+    ; %3: %1+%3 - (%2+%4>>1)
+    ; %2: %1-%3 + (%2>>1-%4)
+    ; %1: %1-%3 - (%2>>1-%4)
 %else
     SUMSUBD2_AB m%2, m%4, [%5], [%5+16]
     SUMSUB_BA   m%3, m%1
     SUMSUB_BADC m%4, m%3, m%2, m%1
 %endif
     SWAP %1, %4, %3
+    ; %1: %1+%3 + (%2+%4>>1) row0
+    ; %2: %1-%3 + (%2>>1-%4) row1
+    ; %3: %1-%3 - (%2>>1-%4) row2
+    ; %4: %1+%3 - (%2+%4>>1) row3
 %endmacro
 
+
 %macro LOAD_DIFF 5
 %ifidn %3, none
     movh       %1, %4
@@ -433,32 +377,6 @@
 %endif
 %endmacro
 
-%macro LOAD_DIFF8x4_SSE2 8
-    LOAD_DIFF  m%1, m%5, m%6, [%7+%1*FENC_STRIDE], [%8+%1*FDEC_STRIDE]
-    LOAD_DIFF  m%2, m%5, m%6, [%7+%2*FENC_STRIDE], [%8+%2*FDEC_STRIDE]
-    LOAD_DIFF  m%3, m%5, m%6, [%7+%3*FENC_STRIDE], [%8+%3*FDEC_STRIDE]
-    LOAD_DIFF  m%4, m%5, m%6, [%7+%4*FENC_STRIDE], [%8+%4*FDEC_STRIDE]
-%endmacro
-
-%macro LOAD_DIFF8x4_SSSE3 8 ; 4x dst, 1x tmp, 1x mul, 2x ptr
-    movh       m%2, [%8+%1*FDEC_STRIDE]
-    movh       m%1, [%7+%1*FENC_STRIDE]
-    punpcklbw  m%1, m%2
-    movh       m%3, [%8+%2*FDEC_STRIDE]
-    movh       m%2, [%7+%2*FENC_STRIDE]
-    punpcklbw  m%2, m%3
-    movh       m%4, [%8+%3*FDEC_STRIDE]
-    movh       m%3, [%7+%3*FENC_STRIDE]
-    punpcklbw  m%3, m%4
-    movh       m%5, [%8+%4*FDEC_STRIDE]
-    movh       m%4, [%7+%4*FENC_STRIDE]
-    punpcklbw  m%4, m%5
-    pmaddubsw  m%1, m%6
-    pmaddubsw  m%2, m%6
-    pmaddubsw  m%3, m%6
-    pmaddubsw  m%4, m%6
-%endmacro
-
 %macro STORE_DCT 6
     movq   [%5+%6+ 0], m%1
     movq   [%5+%6+ 8], m%2
@@ -470,17 +388,6 @@
     movhps [%5+%6+56], m%4
 %endmacro
 
-%macro STORE_IDCT 4
-    movhps [r0-4*FDEC_STRIDE], %1
-    movh   [r0-3*FDEC_STRIDE], %1
-    movhps [r0-2*FDEC_STRIDE], %2
-    movh   [r0-1*FDEC_STRIDE], %2
-    movhps [r0+0*FDEC_STRIDE], %3
-    movh   [r0+1*FDEC_STRIDE], %3
-    movhps [r0+2*FDEC_STRIDE], %4
-    movh   [r0+3*FDEC_STRIDE], %4
-%endmacro
-
 %macro LOAD_DIFF_8x4P 7-10 r0,r2,0 ; 4x dest, 2x temp, 2x pointer, increment?
     LOAD_DIFF m%1, m%5, m%7, [%8],      [%9]
     LOAD_DIFF m%2, m%6, m%7, [%8+r1],   [%9+r3]
@@ -513,3 +420,27 @@
     movh       %4, %1
 %endmacro
 
+%macro STORE_DIFFx2 8 ; add1, add2, reg1, reg2, zero, shift, source, stride
+    movh       %3, [%7]
+    movh       %4, [%7+%8]
+    punpcklbw  %3, %5
+    punpcklbw  %4, %5
+    psraw      %1, %6
+    psraw      %2, %6
+    paddw      %3, %1
+    paddw      %4, %2
+    packuswb   %3, %5
+    packuswb   %4, %5
+    movh     [%7], %3
+    movh  [%7+%8], %4
+%endmacro
+
+%macro PMINUB_MMX 3 ; dst, src, tmp
+    mova     %3, %1
+    psubusb  %3, %2
+    psubb    %1, %3
+%endmacro
+
+%macro PMINUB_MMXEXT 3 ; dst, src, ignored
+    pminub   %1, %2
+%endmacro
diff --git a/libavcodec/xan.c b/libavcodec/xan.c
index 3f6aa8c..876a9a5 100644
--- a/libavcodec/xan.c
+++ b/libavcodec/xan.c
@@ -2,20 +2,20 @@
  * Wing Commander/Xan Video Decoder
  * Copyright (C) 2003 the ffmpeg project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -40,6 +40,15 @@
 // for av_memcpy_backptr
 #include "libavutil/lzo.h"
 
+#define RUNTIME_GAMMA 0
+
+#define VGA__TAG MKTAG('V', 'G', 'A', ' ')
+#define PALT_TAG MKTAG('P', 'A', 'L', 'T')
+#define SHOT_TAG MKTAG('S', 'H', 'O', 'T')
+#define PALETTE_COUNT 256
+#define PALETTE_SIZE (PALETTE_COUNT * 3)
+#define PALETTES_MAX 256
+
 typedef struct XanContext {
 
     AVCodecContext *avctx;
@@ -55,6 +64,10 @@ typedef struct XanContext {
     unsigned char *buffer2;
     int buffer2_size;
 
+    unsigned *palettes;
+    int palettes_count;
+    int cur_palette;
+
     int frame_size;
 
 } XanContext;
@@ -66,23 +79,17 @@ static av_cold int xan_decode_init(AVCodecContext *avctx)
     s->avctx = avctx;
     s->frame_size = 0;
 
-    if ((avctx->codec->id == CODEC_ID_XAN_WC3) &&
-        (s->avctx->palctrl == NULL)) {
-        av_log(avctx, AV_LOG_ERROR, " WC3 Xan video: palette expected.\n");
-        return -1;
-    }
-
     avctx->pix_fmt = PIX_FMT_PAL8;
 
     s->buffer1_size = avctx->width * avctx->height;
     s->buffer1 = av_malloc(s->buffer1_size);
     if (!s->buffer1)
-        return -1;
+        return AVERROR(ENOMEM);
     s->buffer2_size = avctx->width * avctx->height;
     s->buffer2 = av_malloc(s->buffer2_size + 130);
     if (!s->buffer2) {
         av_freep(&s->buffer1);
-        return -1;
+        return AVERROR(ENOMEM);
     }
 
     return 0;
@@ -351,39 +358,166 @@ static void xan_wc3_decode_frame(XanContext *s) {
     }
 }
 
-static void xan_wc4_decode_frame(XanContext *s) {
+#if RUNTIME_GAMMA
+static inline unsigned mul(unsigned a, unsigned b)
+{
+    return (a * b) >> 16;
 }
 
+static inline unsigned pow4(unsigned a)
+{
+    unsigned square = mul(a, a);
+    return mul(square, square);
+}
+
+static inline unsigned pow5(unsigned a)
+{
+    return mul(pow4(a), a);
+}
+
+static uint8_t gamma_corr(uint8_t in) {
+    unsigned lo, hi = 0xff40, target;
+    int i = 15;
+    in = (in << 2) | (in >> 6);
+    /*  equivalent float code:
+    if (in >= 252)
+        return 253;
+    return round(pow(in / 256.0, 0.8) * 256);
+    */
+    lo = target = in << 8;
+    do {
+        unsigned mid = (lo + hi) >> 1;
+        unsigned pow = pow5(mid);
+        if (pow > target) hi = mid;
+        else lo = mid;
+    } while (--i);
+    return (pow4((lo + hi) >> 1) + 0x80) >> 8;
+}
+#else
+/**
+ * This is a gamma correction that xan3 applies to all palette entries.
+ *
+ * There is a peculiarity, namely that the values are clamped to 253 -
+ * it seems likely that this table was calculated by a buggy fixed-point
+ * implementation, the one above under RUNTIME_GAMMA behaves like this for
+ * example.
+ * The exponent value of 0.8 can be explained by this as well, since 0.8 = 4/5
+ * and thus pow(x, 0.8) is still easy to calculate.
+ * Also, the input values are first rotated to the left by 2.
+ */
+static const uint8_t gamma_lookup[256] = {
+    0x00, 0x09, 0x10, 0x16, 0x1C, 0x21, 0x27, 0x2C,
+    0x31, 0x35, 0x3A, 0x3F, 0x43, 0x48, 0x4C, 0x50,
+    0x54, 0x59, 0x5D, 0x61, 0x65, 0x69, 0x6D, 0x71,
+    0x75, 0x79, 0x7D, 0x80, 0x84, 0x88, 0x8C, 0x8F,
+    0x93, 0x97, 0x9A, 0x9E, 0xA2, 0xA5, 0xA9, 0xAC,
+    0xB0, 0xB3, 0xB7, 0xBA, 0xBE, 0xC1, 0xC5, 0xC8,
+    0xCB, 0xCF, 0xD2, 0xD5, 0xD9, 0xDC, 0xDF, 0xE3,
+    0xE6, 0xE9, 0xED, 0xF0, 0xF3, 0xF6, 0xFA, 0xFD,
+    0x03, 0x0B, 0x12, 0x18, 0x1D, 0x23, 0x28, 0x2D,
+    0x32, 0x36, 0x3B, 0x40, 0x44, 0x49, 0x4D, 0x51,
+    0x56, 0x5A, 0x5E, 0x62, 0x66, 0x6A, 0x6E, 0x72,
+    0x76, 0x7A, 0x7D, 0x81, 0x85, 0x89, 0x8D, 0x90,
+    0x94, 0x98, 0x9B, 0x9F, 0xA2, 0xA6, 0xAA, 0xAD,
+    0xB1, 0xB4, 0xB8, 0xBB, 0xBF, 0xC2, 0xC5, 0xC9,
+    0xCC, 0xD0, 0xD3, 0xD6, 0xDA, 0xDD, 0xE0, 0xE4,
+    0xE7, 0xEA, 0xED, 0xF1, 0xF4, 0xF7, 0xFA, 0xFD,
+    0x05, 0x0D, 0x13, 0x19, 0x1F, 0x24, 0x29, 0x2E,
+    0x33, 0x38, 0x3C, 0x41, 0x45, 0x4A, 0x4E, 0x52,
+    0x57, 0x5B, 0x5F, 0x63, 0x67, 0x6B, 0x6F, 0x73,
+    0x77, 0x7B, 0x7E, 0x82, 0x86, 0x8A, 0x8D, 0x91,
+    0x95, 0x99, 0x9C, 0xA0, 0xA3, 0xA7, 0xAA, 0xAE,
+    0xB2, 0xB5, 0xB9, 0xBC, 0xBF, 0xC3, 0xC6, 0xCA,
+    0xCD, 0xD0, 0xD4, 0xD7, 0xDA, 0xDE, 0xE1, 0xE4,
+    0xE8, 0xEB, 0xEE, 0xF1, 0xF5, 0xF8, 0xFB, 0xFD,
+    0x07, 0x0E, 0x15, 0x1A, 0x20, 0x25, 0x2A, 0x2F,
+    0x34, 0x39, 0x3D, 0x42, 0x46, 0x4B, 0x4F, 0x53,
+    0x58, 0x5C, 0x60, 0x64, 0x68, 0x6C, 0x70, 0x74,
+    0x78, 0x7C, 0x7F, 0x83, 0x87, 0x8B, 0x8E, 0x92,
+    0x96, 0x99, 0x9D, 0xA1, 0xA4, 0xA8, 0xAB, 0xAF,
+    0xB2, 0xB6, 0xB9, 0xBD, 0xC0, 0xC4, 0xC7, 0xCB,
+    0xCE, 0xD1, 0xD5, 0xD8, 0xDB, 0xDF, 0xE2, 0xE5,
+    0xE9, 0xEC, 0xEF, 0xF2, 0xF6, 0xF9, 0xFC, 0xFD
+};
+#endif
+
 static int xan_decode_frame(AVCodecContext *avctx,
                             void *data, int *data_size,
                             AVPacket *avpkt)
 {
     const uint8_t *buf = avpkt->data;
-    int buf_size = avpkt->size;
+    int ret, buf_size = avpkt->size;
     XanContext *s = avctx->priv_data;
-    AVPaletteControl *palette_control = avctx->palctrl;
 
-    if (avctx->get_buffer(avctx, &s->current_frame)) {
-        av_log(s->avctx, AV_LOG_ERROR, "  Xan Video: get_buffer() failed\n");
-        return -1;
+    if (avctx->codec->id == CODEC_ID_XAN_WC3) {
+        const uint8_t *buf_end = buf + buf_size;
+        int tag = 0;
+        while (buf_end - buf > 8 && tag != VGA__TAG) {
+            unsigned *tmpptr;
+            uint32_t new_pal;
+            int size;
+            int i;
+            tag  = bytestream_get_le32(&buf);
+            size = bytestream_get_be32(&buf);
+            size = FFMIN(size, buf_end - buf);
+            switch (tag) {
+            case PALT_TAG:
+                if (size < PALETTE_SIZE)
+                    return AVERROR_INVALIDDATA;
+                if (s->palettes_count >= PALETTES_MAX)
+                    return AVERROR_INVALIDDATA;
+                tmpptr = av_realloc(s->palettes, (s->palettes_count + 1) * AVPALETTE_SIZE);
+                if (!tmpptr)
+                    return AVERROR(ENOMEM);
+                s->palettes = tmpptr;
+                tmpptr += s->palettes_count * AVPALETTE_COUNT;
+                for (i = 0; i < PALETTE_COUNT; i++) {
+#if RUNTIME_GAMMA
+                    int r = gamma_corr(*buf++);
+                    int g = gamma_corr(*buf++);
+                    int b = gamma_corr(*buf++);
+#else
+                    int r = gamma_lookup[*buf++];
+                    int g = gamma_lookup[*buf++];
+                    int b = gamma_lookup[*buf++];
+#endif
+                    *tmpptr++ = (r << 16) | (g << 8) | b;
+                }
+                s->palettes_count++;
+                break;
+            case SHOT_TAG:
+                if (size < 4)
+                    return AVERROR_INVALIDDATA;
+                new_pal = bytestream_get_le32(&buf);
+                if (new_pal < s->palettes_count) {
+                    s->cur_palette = new_pal;
+                } else
+                    av_log(avctx, AV_LOG_ERROR, "Invalid palette selected\n");
+                break;
+            case VGA__TAG:
+                break;
+            default:
+                buf += size;
+                break;
+            }
+        }
+        buf_size = buf_end - buf;
+    }
+    if ((ret = avctx->get_buffer(avctx, &s->current_frame))) {
+        av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
+        return ret;
     }
     s->current_frame.reference = 3;
 
     if (!s->frame_size)
         s->frame_size = s->current_frame.linesize[0] * s->avctx->height;
 
-    palette_control->palette_changed = 0;
-    memcpy(s->current_frame.data[1], palette_control->palette,
-           AVPALETTE_SIZE);
-    s->current_frame.palette_has_changed = 1;
+    memcpy(s->current_frame.data[1], s->palettes + s->cur_palette * AVPALETTE_COUNT, AVPALETTE_SIZE);
 
     s->buf = buf;
     s->size = buf_size;
 
-    if (avctx->codec->id == CODEC_ID_XAN_WC3)
-        xan_wc3_decode_frame(s);
-    else if (avctx->codec->id == CODEC_ID_XAN_WC4)
-        xan_wc4_decode_frame(s);
+    xan_wc3_decode_frame(s);
 
     /* release the last frame if it is allocated */
     if (s->last_frame.data[0])
@@ -411,11 +545,12 @@ static av_cold int xan_decode_end(AVCodecContext *avctx)
 
     av_freep(&s->buffer1);
     av_freep(&s->buffer2);
+    av_freep(&s->palettes);
 
     return 0;
 }
 
-AVCodec xan_wc3_decoder = {
+AVCodec ff_xan_wc3_decoder = {
     "xan_wc3",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_XAN_WC3,
@@ -428,17 +563,3 @@ AVCodec xan_wc3_decoder = {
     .long_name = NULL_IF_CONFIG_SMALL("Wing Commander III / Xan"),
 };
 
-/*
-AVCodec xan_wc4_decoder = {
-    "xan_wc4",
-    AVMEDIA_TYPE_VIDEO,
-    CODEC_ID_XAN_WC4,
-    sizeof(XanContext),
-    xan_decode_init,
-    NULL,
-    xan_decode_end,
-    xan_decode_frame,
-    CODEC_CAP_DR1,
-    .long_name = NULL_IF_CONFIG_SMALL("Wing Commander IV / Xxan"),
-};
-*/
diff --git a/libavcodec/xiph.c b/libavcodec/xiph.c
index 2f4f25c..0bcfd45 100644
--- a/libavcodec/xiph.c
+++ b/libavcodec/xiph.c
@@ -1,20 +1,20 @@
 /*
- * Copyright (C) 2007  FFmpeg Project
+ * Copyright (C) 2007  Libav Project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/xiph.h b/libavcodec/xiph.h
index 60f4a95..da18c9c 100644
--- a/libavcodec/xiph.h
+++ b/libavcodec/xiph.h
@@ -1,20 +1,20 @@
 /*
- * Copyright (C) 2007  FFmpeg Project
+ * Copyright (C) 2007  Libav Project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -24,7 +24,7 @@
 #include "libavutil/common.h"
 
 /**
- * Splits a single extradata buffer into the three headers that most
+ * Split a single extradata buffer into the three headers that most
  * Xiph codecs use. (e.g. Theora and Vorbis)
  * Works both with Matroska's packing and lavc's packing.
  *
diff --git a/libavcodec/xl.c b/libavcodec/xl.c
index f7d025e..c7093aa 100644
--- a/libavcodec/xl.c
+++ b/libavcodec/xl.c
@@ -2,20 +2,20 @@
  * Miro VideoXL codec
  * Copyright (c) 2004 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -138,7 +138,7 @@ static av_cold int decode_end(AVCodecContext *avctx){
     return 0;
 }
 
-AVCodec xl_decoder = {
+AVCodec ff_xl_decoder = {
     "xl",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_VIXL,
diff --git a/libavcodec/xsubdec.c b/libavcodec/xsubdec.c
index 0055ebb..097cbc6 100644
--- a/libavcodec/xsubdec.c
+++ b/libavcodec/xsubdec.c
@@ -2,22 +2,23 @@
  * XSUB subtitle decoder
  * Copyright (c) 2007 Reimar Döffinger
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
+#include "libavutil/imgutils.h"
 #include "avcodec.h"
 #include "get_bits.h"
 #include "bytestream.h"
@@ -76,7 +77,7 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *data_size,
     // read header
     w = bytestream_get_le16(&buf);
     h = bytestream_get_le16(&buf);
-    if (avcodec_check_dimensions(avctx, w, h) < 0)
+    if (av_image_check_size(w, h, 0, avctx) < 0)
         return -1;
     x = bytestream_get_le16(&buf);
     y = bytestream_get_le16(&buf);
@@ -130,7 +131,7 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *data_size,
     return buf_size;
 }
 
-AVCodec xsub_decoder = {
+AVCodec ff_xsub_decoder = {
     "xsub",
     AVMEDIA_TYPE_SUBTITLE,
     CODEC_ID_XSUB,
diff --git a/libavcodec/xsubenc.c b/libavcodec/xsubenc.c
index 903cbd2..87dc75c 100644
--- a/libavcodec/xsubenc.c
+++ b/libavcodec/xsubenc.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2005 DivX, Inc.
  * Copyright (c) 2009 Bjorn Axelsson
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -35,7 +35,7 @@
 #define PADDING_COLOR 0
 
 /**
- * Encodes a single color run. At most 16 bits will be used.
+ * Encode a single color run. At most 16 bits will be used.
  * \param len   length of the run, values > 255 mean "until end of line", may not be < 0.
  * \param color color to encode, only the lowest two bits are used and all others must be 0.
  */
@@ -49,7 +49,7 @@ static void put_xsub_rle(PutBitContext *pb, int len, int color)
 }
 
 /**
- * Encodes a 4-color bitmap with XSUB rle.
+ * Encode a 4-color bitmap with XSUB rle.
  *
  * The encoded bitmap may be wider than the source bitmap due to padding.
  */
@@ -210,7 +210,7 @@ static av_cold int xsub_encoder_init(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec xsub_encoder = {
+AVCodec ff_xsub_encoder = {
     "xsub",
     AVMEDIA_TYPE_SUBTITLE,
     CODEC_ID_XSUB,
diff --git a/libavcodec/xvmc.h b/libavcodec/xvmc.h
index 01f84b2..6e18a88 100644
--- a/libavcodec/xvmc.h
+++ b/libavcodec/xvmc.h
@@ -1,20 +1,20 @@
 /*
  * Copyright (C) 2003 Ivan Kalvachev
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -71,7 +71,7 @@ struct xvmc_pix_fmt {
     */
     int             allocated_data_blocks;
 
-    /** Indicates that the hardware would interpret data_blocks as IDCT
+    /** Indicate that the hardware would interpret data_blocks as IDCT
         coefficients and perform IDCT on them.
         - application - set during initialization
         - libavcodec  - unchanged
diff --git a/libavcodec/xvmc_internal.h b/libavcodec/xvmc_internal.h
index 9bb8909..7a4e908 100644
--- a/libavcodec/xvmc_internal.h
+++ b/libavcodec/xvmc_internal.h
@@ -1,20 +1,20 @@
 /*
  * XVideo Motion Compensation internal functions
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavcodec/xxan.c b/libavcodec/xxan.c
new file mode 100644
index 0000000..28c868d
--- /dev/null
+++ b/libavcodec/xxan.c
@@ -0,0 +1,429 @@
+/*
+ * Wing Commander/Xan Video Decoder
+ * Copyright (C) 2011 Konstantin Shishkov
+ * based on work by Mike Melanson
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "avcodec.h"
+#include "libavutil/intreadwrite.h"
+#include "bytestream.h"
+#define ALT_BITSTREAM_READER_LE
+#include "get_bits.h"
+// for av_memcpy_backptr
+#include "libavutil/lzo.h"
+
+typedef struct XanContext {
+    AVCodecContext *avctx;
+    AVFrame pic;
+
+    uint8_t *y_buffer;
+    uint8_t *scratch_buffer;
+    int     buffer_size;
+} XanContext;
+
+static av_cold int xan_decode_init(AVCodecContext *avctx)
+{
+    XanContext *s = avctx->priv_data;
+
+    s->avctx = avctx;
+
+    avctx->pix_fmt = PIX_FMT_YUV420P;
+
+    s->buffer_size = avctx->width * avctx->height;
+    s->y_buffer = av_malloc(s->buffer_size);
+    if (!s->y_buffer)
+        return AVERROR(ENOMEM);
+    s->scratch_buffer = av_malloc(s->buffer_size + 130);
+    if (!s->scratch_buffer) {
+        av_freep(&s->y_buffer);
+        return AVERROR(ENOMEM);
+    }
+
+    return 0;
+}
+
+static int xan_unpack_luma(const uint8_t *src, const int src_size,
+                           uint8_t *dst, const int dst_size)
+{
+   int tree_size, eof;
+   const uint8_t *tree;
+   int bits, mask;
+   int tree_root, node;
+   const uint8_t *dst_end = dst + dst_size;
+   const uint8_t *src_end = src + src_size;
+
+   tree_size = *src++;
+   eof       = *src++;
+   tree      = src - eof * 2 - 2;
+   tree_root = eof + tree_size;
+   src += tree_size * 2;
+
+   node = tree_root;
+   bits = *src++;
+   mask = 0x80;
+   for (;;) {
+       int bit = !!(bits & mask);
+       mask >>= 1;
+       node = tree[node*2 + bit];
+       if (node == eof)
+           break;
+       if (node < eof) {
+           *dst++ = node;
+           if (dst > dst_end)
+               break;
+           node = tree_root;
+       }
+       if (!mask) {
+           bits = *src++;
+           if (src > src_end)
+               break;
+           mask = 0x80;
+       }
+   }
+   return dst != dst_end;
+}
+
+/* almost the same as in xan_wc3 decoder */
+static int xan_unpack(uint8_t *dest, const int dest_len,
+                      const uint8_t *src, const int src_len)
+{
+    uint8_t opcode;
+    int size;
+    uint8_t *orig_dest = dest;
+    const uint8_t *src_end = src + src_len;
+    const uint8_t *dest_end = dest + dest_len;
+
+    while (dest < dest_end) {
+        opcode = *src++;
+
+        if (opcode < 0xe0) {
+            int size2, back;
+            if ((opcode & 0x80) == 0) {
+                size  = opcode & 3;
+                back  = ((opcode & 0x60) << 3) + *src++ + 1;
+                size2 = ((opcode & 0x1c) >> 2) + 3;
+            } else if ((opcode & 0x40) == 0) {
+                size  = *src >> 6;
+                back  = (bytestream_get_be16(&src) & 0x3fff) + 1;
+                size2 = (opcode & 0x3f) + 4;
+            } else {
+                size  = opcode & 3;
+                back  = ((opcode & 0x10) << 12) + bytestream_get_be16(&src) + 1;
+                size2 = ((opcode & 0x0c) <<  6) + *src++ + 5;
+                if (size + size2 > dest_end - dest)
+                    break;
+            }
+            if (src + size > src_end || dest + size + size2 > dest_end)
+                return -1;
+            bytestream_get_buffer(&src, dest, size);
+            dest += size;
+            av_memcpy_backptr(dest, back, size2);
+            dest += size2;
+        } else {
+            int finish = opcode >= 0xfc;
+
+            size = finish ? opcode & 3 : ((opcode & 0x1f) << 2) + 4;
+            if (src + size > src_end || dest + size > dest_end)
+                return -1;
+            bytestream_get_buffer(&src, dest, size);
+            dest += size;
+            if (finish)
+                break;
+        }
+    }
+    return dest - orig_dest;
+}
+
+static int xan_decode_chroma(AVCodecContext *avctx, AVPacket *avpkt)
+{
+    const uint8_t *buf = avpkt->data;
+    XanContext *s = avctx->priv_data;
+    uint8_t *U, *V;
+    unsigned chroma_off;
+    int val, uval, vval;
+    int i, j;
+    const uint8_t *src, *src_end;
+    const uint8_t *table;
+    int mode, offset, dec_size;
+
+    chroma_off = AV_RL32(buf + 4);
+    if (!chroma_off)
+        return 0;
+    if (chroma_off + 10 >= avpkt->size) {
+        av_log(avctx, AV_LOG_ERROR, "Invalid chroma block position\n");
+        return -1;
+    }
+    src    = avpkt->data + 4 + chroma_off;
+    table  = src + 2;
+    mode   = bytestream_get_le16(&src);
+    offset = bytestream_get_le16(&src) * 2;
+
+    if (src - avpkt->data >= avpkt->size - offset) {
+        av_log(avctx, AV_LOG_ERROR, "Invalid chroma block offset\n");
+        return -1;
+    }
+
+    memset(s->scratch_buffer, 0, s->buffer_size);
+    dec_size = xan_unpack(s->scratch_buffer, s->buffer_size, src + offset,
+                          avpkt->size - offset - (src - avpkt->data));
+    if (dec_size < 0) {
+        av_log(avctx, AV_LOG_ERROR, "Chroma unpacking failed\n");
+        return -1;
+    }
+
+    U = s->pic.data[1];
+    V = s->pic.data[2];
+    src     = s->scratch_buffer;
+    src_end = src + dec_size;
+    if (mode) {
+        for (j = 0; j < avctx->height >> 1; j++) {
+            for (i = 0; i < avctx->width >> 1; i++) {
+                val = *src++;
+                if (val) {
+                    val  = AV_RL16(table + (val << 1));
+                    uval = (val >> 3) & 0xF8;
+                    vval = (val >> 8) & 0xF8;
+                    U[i] = uval | (uval >> 5);
+                    V[i] = vval | (vval >> 5);
+                }
+                if (src == src_end)
+                    return 0;
+            }
+            U += s->pic.linesize[1];
+            V += s->pic.linesize[2];
+        }
+    } else {
+        uint8_t *U2 = U + s->pic.linesize[1];
+        uint8_t *V2 = V + s->pic.linesize[2];
+
+        for (j = 0; j < avctx->height >> 2; j++) {
+            for (i = 0; i < avctx->width >> 1; i += 2) {
+                val = *src++;
+                if (val) {
+                    val  = AV_RL16(table + (val << 1));
+                    uval = (val >> 3) & 0xF8;
+                    vval = (val >> 8) & 0xF8;
+                    U[i] = U[i+1] = U2[i] = U2[i+1] = uval | (uval >> 5);
+                    V[i] = V[i+1] = V2[i] = V2[i+1] = vval | (vval >> 5);
+                }
+            }
+            U  += s->pic.linesize[1] * 2;
+            V  += s->pic.linesize[2] * 2;
+            U2 += s->pic.linesize[1] * 2;
+            V2 += s->pic.linesize[2] * 2;
+        }
+    }
+
+    return 0;
+}
+
+static int xan_decode_frame_type0(AVCodecContext *avctx, AVPacket *avpkt)
+{
+    const uint8_t *buf = avpkt->data;
+    XanContext *s = avctx->priv_data;
+    uint8_t *ybuf, *prev_buf, *src = s->scratch_buffer;
+    unsigned  chroma_off, corr_off;
+    int cur, last, size;
+    int i, j;
+    int ret;
+
+    corr_off   = AV_RL32(buf + 8);
+    chroma_off = AV_RL32(buf + 4);
+
+    if ((ret = xan_decode_chroma(avctx, avpkt)) != 0)
+        return ret;
+
+    size = avpkt->size - 4;
+    if (corr_off >= avpkt->size) {
+        av_log(avctx, AV_LOG_WARNING, "Ignoring invalid correction block position\n");
+        corr_off = 0;
+    }
+    if (corr_off)
+        size = corr_off;
+    if (chroma_off)
+        size = FFMIN(size, chroma_off);
+    ret = xan_unpack_luma(buf + 12, size, src, s->buffer_size >> 1);
+    if (ret) {
+        av_log(avctx, AV_LOG_ERROR, "Luma decoding failed\n");
+        return ret;
+    }
+
+    ybuf = s->y_buffer;
+    last = *src++;
+    ybuf[0] = last << 1;
+    for (j = 1; j < avctx->width - 1; j += 2) {
+        cur = (last + *src++) & 0x1F;
+        ybuf[j]   = last + cur;
+        ybuf[j+1] = cur << 1;
+        last = cur;
+    }
+    ybuf[j]  = last << 1;
+    prev_buf = ybuf;
+    ybuf += avctx->width;
+
+    for (i = 1; i < avctx->height; i++) {
+        last = ((prev_buf[0] >> 1) + *src++) & 0x1F;
+        ybuf[0] = last << 1;
+        for (j = 1; j < avctx->width - 1; j += 2) {
+            cur = ((prev_buf[j + 1] >> 1) + *src++) & 0x1F;
+            ybuf[j]   = last + cur;
+            ybuf[j+1] = cur << 1;
+            last = cur;
+        }
+        ybuf[j] = last << 1;
+        prev_buf = ybuf;
+        ybuf += avctx->width;
+    }
+
+    if (corr_off) {
+        int corr_end, dec_size;
+
+        corr_end = avpkt->size;
+        if (chroma_off > corr_off)
+            corr_end = chroma_off;
+        dec_size = xan_unpack(s->scratch_buffer, s->buffer_size,
+                              avpkt->data + 8 + corr_off,
+                              corr_end - corr_off);
+        if (dec_size < 0)
+            dec_size = 0;
+        for (i = 0; i < dec_size; i++)
+            s->y_buffer[i*2+1] = (s->y_buffer[i*2+1] + (s->scratch_buffer[i] << 1)) & 0x3F;
+    }
+
+    src  = s->y_buffer;
+    ybuf = s->pic.data[0];
+    for (j = 0; j < avctx->height; j++) {
+        for (i = 0; i < avctx->width; i++)
+            ybuf[i] = (src[i] << 2) | (src[i] >> 3);
+        src  += avctx->width;
+        ybuf += s->pic.linesize[0];
+    }
+
+    return 0;
+}
+
+static int xan_decode_frame_type1(AVCodecContext *avctx, AVPacket *avpkt)
+{
+    const uint8_t *buf = avpkt->data;
+    XanContext *s = avctx->priv_data;
+    uint8_t *ybuf, *src = s->scratch_buffer;
+    int cur, last;
+    int i, j;
+    int ret;
+
+    if ((ret = xan_decode_chroma(avctx, avpkt)) != 0)
+        return ret;
+
+    ret = xan_unpack_luma(buf + 16, avpkt->size - 16, src,
+                          s->buffer_size >> 1);
+    if (ret) {
+        av_log(avctx, AV_LOG_ERROR, "Luma decoding failed\n");
+        return ret;
+    }
+
+    ybuf = s->y_buffer;
+    for (i = 0; i < avctx->height; i++) {
+        last = (ybuf[0] + (*src++ << 1)) & 0x3F;
+        ybuf[0] = last;
+        for (j = 1; j < avctx->width - 1; j += 2) {
+            cur = (ybuf[j + 1] + (*src++ << 1)) & 0x3F;
+            ybuf[j]   = (last + cur) >> 1;
+            ybuf[j+1] = cur;
+            last = cur;
+        }
+        ybuf[j] = last;
+        ybuf += avctx->width;
+    }
+
+    src = s->y_buffer;
+    ybuf = s->pic.data[0];
+    for (j = 0; j < avctx->height; j++) {
+        for (i = 0; i < avctx->width; i++)
+            ybuf[i] = (src[i] << 2) | (src[i] >> 3);
+        src  += avctx->width;
+        ybuf += s->pic.linesize[0];
+    }
+
+    return 0;
+}
+
+static int xan_decode_frame(AVCodecContext *avctx,
+                            void *data, int *data_size,
+                            AVPacket *avpkt)
+{
+    XanContext *s = avctx->priv_data;
+    int ftype;
+    int ret;
+
+    s->pic.reference = 1;
+    s->pic.buffer_hints = FF_BUFFER_HINTS_VALID |
+                          FF_BUFFER_HINTS_PRESERVE |
+                          FF_BUFFER_HINTS_REUSABLE;
+    if ((ret = avctx->reget_buffer(avctx, &s->pic))) {
+        av_log(s->avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
+        return ret;
+    }
+
+    ftype = AV_RL32(avpkt->data);
+    switch (ftype) {
+    case 0:
+        ret = xan_decode_frame_type0(avctx, avpkt);
+        break;
+    case 1:
+        ret = xan_decode_frame_type1(avctx, avpkt);
+        break;
+    default:
+        av_log(avctx, AV_LOG_ERROR, "Unknown frame type %d\n", ftype);
+        return -1;
+    }
+    if (ret)
+        return ret;
+
+    *data_size = sizeof(AVFrame);
+    *(AVFrame*)data = s->pic;
+
+    return avpkt->size;
+}
+
+static av_cold int xan_decode_end(AVCodecContext *avctx)
+{
+    XanContext *s = avctx->priv_data;
+
+    if (s->pic.data[0])
+        avctx->release_buffer(avctx, &s->pic);
+
+    av_freep(&s->y_buffer);
+    av_freep(&s->scratch_buffer);
+
+    return 0;
+}
+
+AVCodec ff_xan_wc4_decoder = {
+    "xan_wc4",
+    AVMEDIA_TYPE_VIDEO,
+    CODEC_ID_XAN_WC4,
+    sizeof(XanContext),
+    xan_decode_init,
+    NULL,
+    xan_decode_end,
+    xan_decode_frame,
+    CODEC_CAP_DR1,
+    .long_name = NULL_IF_CONFIG_SMALL("Wing Commander IV / Xxan"),
+};
+
diff --git a/libavcodec/yop.c b/libavcodec/yop.c
index 1eb76b1..1f1314b 100644
--- a/libavcodec/yop.c
+++ b/libavcodec/yop.c
@@ -6,24 +6,25 @@
  * derived from the code by
  * Copyright (C) 2009 Thomas P. Higdon <thomas.p.higdon at gmail.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "libavutil/intreadwrite.h"
+#include "libavutil/imgutils.h"
 
 #include "avcodec.h"
 #include "get_bits.h"
@@ -84,7 +85,7 @@ static av_cold int yop_decode_init(AVCodecContext *avctx)
     s->avctx = avctx;
 
     if (avctx->width & 1 || avctx->height & 1 ||
-        avcodec_check_dimensions(avctx, avctx->width, avctx->height) < 0) {
+        av_image_check_size(avctx->width, avctx->height, 0, avctx) < 0) {
         av_log(avctx, AV_LOG_ERROR, "YOP has invalid dimensions\n");
         return -1;
     }
@@ -114,7 +115,7 @@ static av_cold int yop_decode_close(AVCodecContext *avctx)
 }
 
 /**
- * Paints a macroblock using the pattern in paint_lut.
+ * Paint a macroblock using the pattern in paint_lut.
  * @param s codec context
  * @param tag the tag that was in the nibble
  */
@@ -130,7 +131,7 @@ static void yop_paint_block(YopDecContext *s, int tag)
 }
 
 /**
- * Copies a previously painted macroblock to the current_block.
+ * Copy a previously painted macroblock to the current_block.
  * @param copy_tag the tag that was in the nibble
  */
 static int yop_copy_previous_block(YopDecContext *s, int copy_tag)
@@ -155,7 +156,7 @@ static int yop_copy_previous_block(YopDecContext *s, int copy_tag)
 }
 
 /**
- * Returns the next nibble in sequence, consuming a new byte on the input
+ * Return the next nibble in sequence, consuming a new byte on the input
  * only if necessary.
  */
 static uint8_t yop_get_next_nibble(YopDecContext *s)
@@ -173,7 +174,7 @@ static uint8_t yop_get_next_nibble(YopDecContext *s)
 }
 
 /**
- * Takes s->dstptr to the next macroblock in sequence.
+ * Take s->dstptr to the next macroblock in sequence.
  */
 static void yop_next_macroblock(YopDecContext *s)
 {
@@ -247,7 +248,7 @@ static int yop_decode_frame(AVCodecContext *avctx, void *data, int *data_size,
     return avpkt->size;
 }
 
-AVCodec yop_decoder = {
+AVCodec ff_yop_decoder = {
     "yop",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_YOP,
diff --git a/libavcodec/zmbv.c b/libavcodec/zmbv.c
index 8af8c84..eec7025 100644
--- a/libavcodec/zmbv.c
+++ b/libavcodec/zmbv.c
@@ -2,20 +2,20 @@
  * Zip Motion Blocks Video (ZMBV) decoder
  * Copyright (c) 2006 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -397,7 +397,6 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPac
     const uint8_t *buf = avpkt->data;
     int buf_size = avpkt->size;
     ZmbvContext * const c = avctx->priv_data;
-    uint8_t *outptr;
     int zret = Z_OK; // Zlib return code
     int len = buf_size;
     int hi_ver, lo_ver;
@@ -412,8 +411,6 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPac
         return -1;
     }
 
-    outptr = c->pic.data[0]; // Output image pointer
-
     /* parse header */
     c->flags = buf[0];
     buf++; len--;
@@ -653,7 +650,7 @@ static av_cold int decode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec zmbv_decoder = {
+AVCodec ff_zmbv_decoder = {
     "zmbv",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_ZMBV,
diff --git a/libavcodec/zmbvenc.c b/libavcodec/zmbvenc.c
index 95f2906..9caa6b8 100644
--- a/libavcodec/zmbvenc.c
+++ b/libavcodec/zmbvenc.c
@@ -2,20 +2,20 @@
  * Zip Motion Blocks Video (ZMBV) encoder
  * Copyright (c) 2006 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -323,7 +323,7 @@ static av_cold int encode_end(AVCodecContext *avctx)
     return 0;
 }
 
-AVCodec zmbv_encoder = {
+AVCodec ff_zmbv_encoder = {
     "zmbv",
     AVMEDIA_TYPE_VIDEO,
     CODEC_ID_ZMBV,
diff --git a/libavdevice/Makefile b/libavdevice/Makefile
index a0c3858..5cfc5e8 100644
--- a/libavdevice/Makefile
+++ b/libavdevice/Makefile
@@ -14,9 +14,12 @@ OBJS-$(CONFIG_ALSA_OUTDEV)               += alsa-audio-common.o \
                                             alsa-audio-enc.o
 OBJS-$(CONFIG_BKTR_INDEV)                += bktr.o
 OBJS-$(CONFIG_DV1394_INDEV)              += dv1394.o
+OBJS-$(CONFIG_FBDEV_INDEV)               += fbdev.o
 OBJS-$(CONFIG_JACK_INDEV)                += jack_audio.o
 OBJS-$(CONFIG_OSS_INDEV)                 += oss_audio.o
 OBJS-$(CONFIG_OSS_OUTDEV)                += oss_audio.o
+OBJS-$(CONFIG_SNDIO_INDEV)               += sndio_common.o sndio_dec.o
+OBJS-$(CONFIG_SNDIO_OUTDEV)              += sndio_common.o sndio_enc.o
 OBJS-$(CONFIG_V4L2_INDEV)                += v4l2.o
 OBJS-$(CONFIG_V4L_INDEV)                 += v4l.o
 OBJS-$(CONFIG_VFWCAP_INDEV)              += vfwcap.o
@@ -25,9 +28,7 @@ OBJS-$(CONFIG_X11_GRAB_DEVICE_INDEV)     += x11grab.o
 # external libraries
 OBJS-$(CONFIG_LIBDC1394_INDEV)           += libdc1394.o
 
-OBJS-$(CONFIG_AUDIO_BEOS_INDEV)          += beosaudio.o
-OBJS-$(CONFIG_AUDIO_BEOS_OUTDEV)         += beosaudio.o
-
 SKIPHEADERS-$(HAVE_ALSA_ASOUNDLIB_H)     += alsa-audio.h
+SKIPHEADERS-$(HAVE_SNDIO_H)              += sndio_common.h
 
 include $(SUBDIR)../subdir.mak
diff --git a/libavdevice/alldevices.c b/libavdevice/alldevices.c
index e7a9a5e..0e2cf6d 100644
--- a/libavdevice/alldevices.c
+++ b/libavdevice/alldevices.c
@@ -1,20 +1,20 @@
 /*
  * Register all the grabbing devices.
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -23,11 +23,11 @@
 #include "avdevice.h"
 
 #define REGISTER_OUTDEV(X,x) { \
-          extern AVOutputFormat x##_muxer; \
-          if(CONFIG_##X##_OUTDEV)  av_register_output_format(&x##_muxer); }
+          extern AVOutputFormat ff_##x##_muxer; \
+          if(CONFIG_##X##_OUTDEV)  av_register_output_format(&ff_##x##_muxer); }
 #define REGISTER_INDEV(X,x) { \
-          extern AVInputFormat x##_demuxer; \
-          if(CONFIG_##X##_INDEV)   av_register_input_format(&x##_demuxer); }
+          extern AVInputFormat ff_##x##_demuxer; \
+          if(CONFIG_##X##_INDEV)   av_register_input_format(&ff_##x##_demuxer); }
 #define REGISTER_INOUTDEV(X,x)  REGISTER_OUTDEV(X,x); REGISTER_INDEV(X,x)
 
 void avdevice_register_all(void)
@@ -40,11 +40,12 @@ void avdevice_register_all(void)
 
     /* devices */
     REGISTER_INOUTDEV (ALSA, alsa);
-    REGISTER_INOUTDEV (AUDIO_BEOS, audio_beos);
     REGISTER_INDEV    (BKTR, bktr);
     REGISTER_INDEV    (DV1394, dv1394);
+    REGISTER_INDEV    (FBDEV, fbdev);
     REGISTER_INDEV    (JACK, jack);
     REGISTER_INOUTDEV (OSS, oss);
+    REGISTER_INOUTDEV (SNDIO, sndio);
     REGISTER_INDEV    (V4L2, v4l2);
     REGISTER_INDEV    (V4L, v4l);
     REGISTER_INDEV    (VFWCAP, vfwcap);
diff --git a/libavdevice/alsa-audio-common.c b/libavdevice/alsa-audio-common.c
index 38cb0de..ff6c9f8 100644
--- a/libavdevice/alsa-audio-common.c
+++ b/libavdevice/alsa-audio-common.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2007 Luca Abeni ( lucabe72 email it )
  * Copyright (c) 2007 Benoit Fouet ( benoit fouet free fr )
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavdevice/alsa-audio-dec.c b/libavdevice/alsa-audio-dec.c
index f1dd29b..c467fc0 100644
--- a/libavdevice/alsa-audio-dec.c
+++ b/libavdevice/alsa-audio-dec.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2007 Luca Abeni ( lucabe72 email it )
  * Copyright (c) 2007 Benoit Fouet ( benoit fouet free fr )
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -163,7 +163,7 @@ static int audio_read_packet(AVFormatContext *s1, AVPacket *pkt)
     return 0;
 }
 
-AVInputFormat alsa_demuxer = {
+AVInputFormat ff_alsa_demuxer = {
     "alsa",
     NULL_IF_CONFIG_SMALL("ALSA audio input"),
     sizeof(AlsaData),
diff --git a/libavdevice/alsa-audio-enc.c b/libavdevice/alsa-audio-enc.c
index 7c07bf7..ebe598c 100644
--- a/libavdevice/alsa-audio-enc.c
+++ b/libavdevice/alsa-audio-enc.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2007 Luca Abeni ( lucabe72 email it )
  * Copyright (c) 2007 Benoit Fouet ( benoit fouet free fr )
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -93,7 +93,7 @@ static int audio_write_packet(AVFormatContext *s1, AVPacket *pkt)
     return 0;
 }
 
-AVOutputFormat alsa_muxer = {
+AVOutputFormat ff_alsa_muxer = {
     "alsa",
     NULL_IF_CONFIG_SMALL("ALSA audio output"),
     "",
diff --git a/libavdevice/alsa-audio.h b/libavdevice/alsa-audio.h
index 9a8a089..7a1b018 100644
--- a/libavdevice/alsa-audio.h
+++ b/libavdevice/alsa-audio.h
@@ -3,20 +3,20 @@
  * Copyright (c) 2007 Luca Abeni ( lucabe72 email it )
  * Copyright (c) 2007 Benoit Fouet ( benoit fouet free fr )
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -37,11 +37,7 @@
 /* XXX: we make the assumption that the soundcard accepts this format */
 /* XXX: find better solution with "preinit" method, needed also in
         other formats */
-#if HAVE_BIGENDIAN
-#define DEFAULT_CODEC_ID CODEC_ID_PCM_S16BE
-#else
-#define DEFAULT_CODEC_ID CODEC_ID_PCM_S16LE
-#endif
+#define DEFAULT_CODEC_ID AV_NE(CODEC_ID_PCM_S16BE, CODEC_ID_PCM_S16LE)
 
 typedef struct {
     snd_pcm_t *h;
@@ -50,7 +46,7 @@ typedef struct {
 } AlsaData;
 
 /**
- * Opens an ALSA PCM.
+ * Open an ALSA PCM.
  *
  * @param s media file handle
  * @param mode either SND_PCM_STREAM_CAPTURE or SND_PCM_STREAM_PLAYBACK
@@ -68,7 +64,7 @@ int ff_alsa_open(AVFormatContext *s, snd_pcm_stream_t mode,
                  int channels, enum CodecID *codec_id);
 
 /**
- * Closes the ALSA PCM.
+ * Close the ALSA PCM.
  *
  * @param s1 media file handle
  *
@@ -77,7 +73,7 @@ int ff_alsa_open(AVFormatContext *s, snd_pcm_stream_t mode,
 int ff_alsa_close(AVFormatContext *s1);
 
 /**
- * Tries to recover from ALSA buffer underrun.
+ * Try to recover from ALSA buffer underrun.
  *
  * @param s1 media file handle
  * @param err error code reported by the previous ALSA call
diff --git a/libavdevice/avdevice.c b/libavdevice/avdevice.c
index 3d67b4b..4813a3d 100644
--- a/libavdevice/avdevice.c
+++ b/libavdevice/avdevice.c
@@ -1,18 +1,18 @@
 /*
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,11 +25,11 @@ unsigned avdevice_version(void)
 
 const char * avdevice_configuration(void)
 {
-    return FFMPEG_CONFIGURATION;
+    return LIBAV_CONFIGURATION;
 }
 
 const char * avdevice_license(void)
 {
 #define LICENSE_PREFIX "libavdevice license: "
-    return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1;
+    return LICENSE_PREFIX LIBAV_LICENSE + sizeof(LICENSE_PREFIX) - 1;
 }
diff --git a/libavdevice/avdevice.h b/libavdevice/avdevice.h
index dcd835c..d1e321b 100644
--- a/libavdevice/avdevice.h
+++ b/libavdevice/avdevice.h
@@ -1,18 +1,18 @@
 /*
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -21,8 +21,8 @@
 
 #include "libavutil/avutil.h"
 
-#define LIBAVDEVICE_VERSION_MAJOR 52
-#define LIBAVDEVICE_VERSION_MINOR  2
+#define LIBAVDEVICE_VERSION_MAJOR 53
+#define LIBAVDEVICE_VERSION_MINOR  0
 #define LIBAVDEVICE_VERSION_MICRO  0
 
 #define LIBAVDEVICE_VERSION_INT AV_VERSION_INT(LIBAVDEVICE_VERSION_MAJOR, \
@@ -34,17 +34,17 @@
 #define LIBAVDEVICE_BUILD       LIBAVDEVICE_VERSION_INT
 
 /**
- * Returns the LIBAVDEVICE_VERSION_INT constant.
+ * Return the LIBAVDEVICE_VERSION_INT constant.
  */
 unsigned avdevice_version(void);
 
 /**
- * Returns the libavdevice build-time configuration.
+ * Return the libavdevice build-time configuration.
  */
 const char *avdevice_configuration(void);
 
 /**
- * Returns the libavdevice license.
+ * Return the libavdevice license.
  */
 const char *avdevice_license(void);
 
diff --git a/libavdevice/beosaudio.cpp b/libavdevice/beosaudio.cpp
deleted file mode 100644
index 9f32571..0000000
--- a/libavdevice/beosaudio.cpp
+++ /dev/null
@@ -1,467 +0,0 @@
-/*
- * BeOS audio play interface
- * Copyright (c) 2000, 2001 Fabrice Bellard
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-#include <signal.h>
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#include <unistd.h>
-#include <sys/time.h>
-
-#include <Application.h>
-#include <SoundPlayer.h>
-
-extern "C" {
-#include "libavformat/avformat.h"
-}
-
-#if HAVE_BSOUNDRECORDER
-#include <SoundRecorder.h>
-using namespace BPrivate::Media::Experimental;
-#endif
-
-/* enable performance checks */
-//#define PERF_CHECK
-
-/* enable Media Kit latency checks */
-//#define LATENCY_CHECK
-
-#define AUDIO_BLOCK_SIZE 4096
-#define AUDIO_BLOCK_COUNT 8
-
-#define AUDIO_BUFFER_SIZE (AUDIO_BLOCK_SIZE*AUDIO_BLOCK_COUNT)
-
-typedef struct {
-    int fd; // UNUSED
-    int sample_rate;
-    int channels;
-    int frame_size; /* in bytes ! */
-    CodecID codec_id;
-    uint8_t buffer[AUDIO_BUFFER_SIZE];
-    int buffer_ptr;
-    /* ring buffer */
-    sem_id input_sem;
-    int input_index;
-    sem_id output_sem;
-    int output_index;
-    BSoundPlayer *player;
-#if HAVE_BSOUNDRECORDER
-    BSoundRecorder *recorder;
-#endif
-    int has_quit; /* signal callbacks not to wait */
-    volatile bigtime_t starve_time;
-} AudioData;
-
-static thread_id main_thid;
-static thread_id bapp_thid;
-static int own_BApp_created = 0;
-static int refcount = 0;
-
-/* create the BApplication and Run() it */
-static int32 bapp_thread(void *arg)
-{
-    new BApplication("application/x-vnd.ffmpeg");
-    own_BApp_created = 1;
-    be_app->Run();
-    /* kill the process group */
-//    kill(0, SIGINT);
-//    kill(main_thid, SIGHUP);
-    return B_OK;
-}
-
-/* create the BApplication only if needed */
-static void create_bapp_if_needed(void)
-{
-    if (refcount++ == 0) {
-        /* needed by libmedia */
-        if (be_app == NULL) {
-            bapp_thid = spawn_thread(bapp_thread, "ffmpeg BApplication", B_NORMAL_PRIORITY, NULL);
-            resume_thread(bapp_thid);
-            while (!own_BApp_created)
-                snooze(50000);
-        }
-    }
-}
-
-static void destroy_bapp_if_needed(void)
-{
-    if (--refcount == 0 && own_BApp_created) {
-        be_app->Lock();
-        be_app->Quit();
-        be_app = NULL;
-    }
-}
-
-/* called back by BSoundPlayer */
-static void audioplay_callback(void *cookie, void *buffer, size_t bufferSize, const media_raw_audio_format &format)
-{
-    AudioData *s;
-    size_t len, amount;
-    unsigned char *buf = (unsigned char *)buffer;
-
-    s = (AudioData *)cookie;
-    if (s->has_quit)
-        return;
-    while (bufferSize > 0) {
-#ifdef PERF_CHECK
-        bigtime_t t;
-        t = system_time();
-#endif
-        len = MIN(AUDIO_BLOCK_SIZE, bufferSize);
-        if (acquire_sem_etc(s->output_sem, len, B_CAN_INTERRUPT, 0LL) < B_OK) {
-            s->has_quit = 1;
-            s->player->SetHasData(false);
-            return;
-        }
-        amount = MIN(len, (AUDIO_BUFFER_SIZE - s->output_index));
-        memcpy(buf, &s->buffer[s->output_index], amount);
-        s->output_index += amount;
-        if (s->output_index >= AUDIO_BUFFER_SIZE) {
-            s->output_index %= AUDIO_BUFFER_SIZE;
-            memcpy(buf + amount, &s->buffer[s->output_index], len - amount);
-            s->output_index += len-amount;
-            s->output_index %= AUDIO_BUFFER_SIZE;
-        }
-        release_sem_etc(s->input_sem, len, 0);
-#ifdef PERF_CHECK
-        t = system_time() - t;
-        s->starve_time = MAX(s->starve_time, t);
-#endif
-        buf += len;
-        bufferSize -= len;
-    }
-}
-
-#if HAVE_BSOUNDRECORDER
-/* called back by BSoundRecorder */
-static void audiorecord_callback(void *cookie, bigtime_t timestamp, void *buffer, size_t bufferSize, const media_multi_audio_format &format)
-{
-    AudioData *s;
-    size_t len, amount;
-    unsigned char *buf = (unsigned char *)buffer;
-
-    s = (AudioData *)cookie;
-    if (s->has_quit)
-        return;
-
-    while (bufferSize > 0) {
-        len = MIN(bufferSize, AUDIO_BLOCK_SIZE);
-        //printf("acquire_sem(input, %d)\n", len);
-        if (acquire_sem_etc(s->input_sem, len, B_CAN_INTERRUPT, 0LL) < B_OK) {
-            s->has_quit = 1;
-            return;
-        }
-        amount = MIN(len, (AUDIO_BUFFER_SIZE - s->input_index));
-        memcpy(&s->buffer[s->input_index], buf, amount);
-        s->input_index += amount;
-        if (s->input_index >= AUDIO_BUFFER_SIZE) {
-            s->input_index %= AUDIO_BUFFER_SIZE;
-            memcpy(&s->buffer[s->input_index], buf + amount, len - amount);
-            s->input_index += len - amount;
-        }
-        release_sem_etc(s->output_sem, len, 0);
-        //printf("release_sem(output, %d)\n", len);
-        buf += len;
-        bufferSize -= len;
-    }
-}
-#endif
-
-static int audio_open(AudioData *s, int is_output, const char *audio_device)
-{
-    int p[2];
-    int ret;
-    media_raw_audio_format format;
-    media_multi_audio_format iformat;
-
-#if !HAVE_BSOUNDRECORDER
-    if (!is_output)
-        return AVERROR(EIO); /* not for now */
-#endif
-    s->input_sem = create_sem(AUDIO_BUFFER_SIZE, "ffmpeg_ringbuffer_input");
-    if (s->input_sem < B_OK)
-        return AVERROR(EIO);
-    s->output_sem = create_sem(0, "ffmpeg_ringbuffer_output");
-    if (s->output_sem < B_OK) {
-        delete_sem(s->input_sem);
-        return AVERROR(EIO);
-    }
-    s->input_index = 0;
-    s->output_index = 0;
-    create_bapp_if_needed();
-    s->frame_size = AUDIO_BLOCK_SIZE;
-    /* bump up the priority (avoid realtime though) */
-    set_thread_priority(find_thread(NULL), B_DISPLAY_PRIORITY+1);
-#if HAVE_BSOUNDRECORDER
-    if (!is_output) {
-        bool wait_for_input = false;
-        if (audio_device && !strcmp(audio_device, "wait:"))
-            wait_for_input = true;
-        s->recorder = new BSoundRecorder(&iformat, wait_for_input, "ffmpeg input", audiorecord_callback);
-        if (wait_for_input && (s->recorder->InitCheck() == B_OK)) {
-            s->recorder->WaitForIncomingConnection(&iformat);
-        }
-        if (s->recorder->InitCheck() != B_OK || iformat.format != media_raw_audio_format::B_AUDIO_SHORT) {
-            delete s->recorder;
-            s->recorder = NULL;
-            if (s->input_sem)
-                delete_sem(s->input_sem);
-            if (s->output_sem)
-                delete_sem(s->output_sem);
-            return AVERROR(EIO);
-        }
-        s->codec_id = (iformat.byte_order == B_MEDIA_LITTLE_ENDIAN)?CODEC_ID_PCM_S16LE:CODEC_ID_PCM_S16BE;
-        s->channels = iformat.channel_count;
-        s->sample_rate = (int)iformat.frame_rate;
-        s->frame_size = iformat.buffer_size;
-        s->recorder->SetCookie(s);
-        s->recorder->SetVolume(1.0);
-        s->recorder->Start();
-        return 0;
-    }
-#endif
-    format = media_raw_audio_format::wildcard;
-    format.format = media_raw_audio_format::B_AUDIO_SHORT;
-    format.byte_order = B_HOST_IS_LENDIAN ? B_MEDIA_LITTLE_ENDIAN : B_MEDIA_BIG_ENDIAN;
-    format.channel_count = s->channels;
-    format.buffer_size = s->frame_size;
-    format.frame_rate = s->sample_rate;
-    s->player = new BSoundPlayer(&format, "ffmpeg output", audioplay_callback);
-    if (s->player->InitCheck() != B_OK) {
-        delete s->player;
-        s->player = NULL;
-        if (s->input_sem)
-            delete_sem(s->input_sem);
-        if (s->output_sem)
-            delete_sem(s->output_sem);
-        return AVERROR(EIO);
-    }
-    s->player->SetCookie(s);
-    s->player->SetVolume(1.0);
-    s->player->Start();
-    s->player->SetHasData(true);
-    return 0;
-}
-
-static int audio_close(AudioData *s)
-{
-    if (s->input_sem)
-        delete_sem(s->input_sem);
-    if (s->output_sem)
-        delete_sem(s->output_sem);
-    s->has_quit = 1;
-    if (s->player) {
-        s->player->Stop();
-    }
-    if (s->player)
-        delete s->player;
-#if HAVE_BSOUNDRECORDER
-    if (s->recorder)
-        delete s->recorder;
-#endif
-    destroy_bapp_if_needed();
-    return 0;
-}
-
-/* sound output support */
-static int audio_write_header(AVFormatContext *s1)
-{
-    AudioData *s = (AudioData *)s1->priv_data;
-    AVStream *st;
-    int ret;
-
-    st = s1->streams[0];
-    s->sample_rate = st->codec->sample_rate;
-    s->channels = st->codec->channels;
-    ret = audio_open(s, 1, NULL);
-    if (ret < 0)
-        return AVERROR(EIO);
-    return 0;
-}
-
-static int audio_write_packet(AVFormatContext *s1, AVPacket *pkt)
-{
-    AudioData *s = (AudioData *)s1->priv_data;
-    int len, ret;
-    const uint8_t *buf = pkt->data;
-    int size = pkt->size;
-#ifdef LATENCY_CHECK
-bigtime_t lat1, lat2;
-lat1 = s->player->Latency();
-#endif
-#ifdef PERF_CHECK
-    bigtime_t t = s->starve_time;
-    s->starve_time = 0;
-    printf("starve_time: %lld    \n", t);
-#endif
-    while (size > 0) {
-        int amount;
-        len = MIN(size, AUDIO_BLOCK_SIZE);
-        if (acquire_sem_etc(s->input_sem, len, B_CAN_INTERRUPT, 0LL) < B_OK)
-            return AVERROR(EIO);
-        amount = MIN(len, (AUDIO_BUFFER_SIZE - s->input_index));
-        memcpy(&s->buffer[s->input_index], buf, amount);
-        s->input_index += amount;
-        if (s->input_index >= AUDIO_BUFFER_SIZE) {
-            s->input_index %= AUDIO_BUFFER_SIZE;
-            memcpy(&s->buffer[s->input_index], buf + amount, len - amount);
-            s->input_index += len - amount;
-        }
-        release_sem_etc(s->output_sem, len, 0);
-        buf += len;
-        size -= len;
-    }
-#ifdef LATENCY_CHECK
-lat2 = s->player->Latency();
-printf("#### BSoundPlayer::Latency(): before= %lld, after= %lld\n", lat1, lat2);
-#endif
-    return 0;
-}
-
-static int audio_write_trailer(AVFormatContext *s1)
-{
-    AudioData *s = (AudioData *)s1->priv_data;
-
-    audio_close(s);
-    return 0;
-}
-
-/* grab support */
-
-static int audio_read_header(AVFormatContext *s1, AVFormatParameters *ap)
-{
-    AudioData *s = (AudioData *)s1->priv_data;
-    AVStream *st;
-    int ret;
-
-    if (!ap || ap->sample_rate <= 0 || ap->channels <= 0)
-        return -1;
-
-    st = av_new_stream(s1, 0);
-    if (!st) {
-        return AVERROR(ENOMEM);
-    }
-    s->sample_rate = ap->sample_rate;
-    s->channels = ap->channels;
-
-    ret = audio_open(s, 0, s1->filename);
-    if (ret < 0) {
-        av_free(st);
-        return AVERROR(EIO);
-    }
-    /* take real parameters */
-    st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
-    st->codec->codec_id = s->codec_id;
-    st->codec->sample_rate = s->sample_rate;
-    st->codec->channels = s->channels;
-    return 0;
-    av_set_pts_info(st, 48, 1, 1000000);  /* 48 bits pts in us */
-}
-
-static int audio_read_packet(AVFormatContext *s1, AVPacket *pkt)
-{
-    AudioData *s = (AudioData *)s1->priv_data;
-    int size;
-    size_t len, amount;
-    unsigned char *buf;
-    status_t err;
-
-    if (av_new_packet(pkt, s->frame_size) < 0)
-        return AVERROR(EIO);
-    buf = (unsigned char *)pkt->data;
-    size = pkt->size;
-    while (size > 0) {
-        len = MIN(AUDIO_BLOCK_SIZE, size);
-        //printf("acquire_sem(output, %d)\n", len);
-        while ((err=acquire_sem_etc(s->output_sem, len, B_CAN_INTERRUPT, 0LL)) == B_INTERRUPTED);
-        if (err < B_OK) {
-            av_free_packet(pkt);
-            return AVERROR(EIO);
-        }
-        amount = MIN(len, (AUDIO_BUFFER_SIZE - s->output_index));
-        memcpy(buf, &s->buffer[s->output_index], amount);
-        s->output_index += amount;
-        if (s->output_index >= AUDIO_BUFFER_SIZE) {
-            s->output_index %= AUDIO_BUFFER_SIZE;
-            memcpy(buf + amount, &s->buffer[s->output_index], len - amount);
-            s->output_index += len-amount;
-            s->output_index %= AUDIO_BUFFER_SIZE;
-        }
-        release_sem_etc(s->input_sem, len, 0);
-        //printf("release_sem(input, %d)\n", len);
-        buf += len;
-        size -= len;
-    }
-    //XXX: add pts info
-    return 0;
-}
-
-static int audio_read_close(AVFormatContext *s1)
-{
-    AudioData *s = (AudioData *)s1->priv_data;
-
-    audio_close(s);
-    return 0;
-}
-
-static AVInputFormat audio_beos_demuxer = {
-    "audio_beos",
-    NULL_IF_CONFIG_SMALL("audio grab and output"),
-    sizeof(AudioData),
-    NULL,
-    audio_read_header,
-    audio_read_packet,
-    audio_read_close,
-    NULL,
-    NULL,
-    AVFMT_NOFILE,
-};
-
-AVOutputFormat audio_beos_muxer = {
-    "audio_beos",
-    NULL_IF_CONFIG_SMALL("audio grab and output"),
-    "",
-    "",
-    sizeof(AudioData),
-#if HAVE_BIGENDIAN
-    CODEC_ID_PCM_S16BE,
-#else
-    CODEC_ID_PCM_S16LE,
-#endif
-    CODEC_ID_NONE,
-    audio_write_header,
-    audio_write_packet,
-    audio_write_trailer,
-    AVFMT_NOFILE,
-};
-
-extern "C" {
-
-int audio_init(void)
-{
-    main_thid = find_thread(NULL);
-    av_register_input_format(&audio_beos_demuxer);
-    av_register_output_format(&audio_beos_muxer);
-    return 0;
-}
-
-} // "C"
-
diff --git a/libavdevice/bktr.c b/libavdevice/bktr.c
index afb94b6..3e705a0 100644
--- a/libavdevice/bktr.c
+++ b/libavdevice/bktr.c
@@ -7,20 +7,20 @@
  * and
  *           simple_grab.c Copyright (c) 1999 Roger Hardiman
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -314,7 +314,7 @@ static int grab_read_close(AVFormatContext *s1)
     return 0;
 }
 
-AVInputFormat bktr_demuxer = {
+AVInputFormat ff_bktr_demuxer = {
     "bktr",
     NULL_IF_CONFIG_SMALL("video grab"),
     sizeof(VideoData),
diff --git a/libavdevice/dv1394.c b/libavdevice/dv1394.c
index a55fa97..70f928e 100644
--- a/libavdevice/dv1394.c
+++ b/libavdevice/dv1394.c
@@ -2,20 +2,20 @@
  * Linux DV1394 interface
  * Copyright (c) 2003 Max Krasnyansky <maxk at qualcomm.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -227,7 +227,7 @@ static int dv1394_close(AVFormatContext * context)
     return 0;
 }
 
-AVInputFormat dv1394_demuxer = {
+AVInputFormat ff_dv1394_demuxer = {
     .name           = "dv1394",
     .long_name      = NULL_IF_CONFIG_SMALL("DV1394 A/V grab"),
     .priv_data_size = sizeof(struct dv1394_data),
diff --git a/libavdevice/dv1394.h b/libavdevice/dv1394.h
index 00706f7..5ccc68a 100644
--- a/libavdevice/dv1394.h
+++ b/libavdevice/dv1394.h
@@ -8,20 +8,20 @@
  *   Copyright (C)1999,2000 Sebastien Rougeaux <sebastien.rougeaux at anu.edu.au>
  *                          Peter Schlaile <udbz at rz.uni-karlsruhe.de>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavdevice/fbdev.c b/libavdevice/fbdev.c
new file mode 100644
index 0000000..6b03be4
--- /dev/null
+++ b/libavdevice/fbdev.c
@@ -0,0 +1,250 @@
+/*
+ * Copyright (c) 2011 Stefano Sabatini
+ * Copyright (c) 2009 Giliard B. de Freitas <giliarde at gmail.com>
+ * Copyright (C) 2002 Gunnar Monell <gmo at linux.nu>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * Linux framebuffer input device,
+ * inspired by code from fbgrab.c by Gunnar Monell.
+ * See also http://linux-fbdev.sourceforge.net/.
+ */
+
+/* #define DEBUG */
+
+#include <unistd.h>
+#include <fcntl.h>
+#include <sys/ioctl.h>
+#include <sys/time.h>
+#include <sys/mman.h>
+#include <time.h>
+#include <linux/fb.h>
+
+#include "libavutil/mem.h"
+#include "libavutil/pixdesc.h"
+#include "libavformat/avformat.h"
+
+struct rgb_pixfmt_map_entry {
+    int bits_per_pixel;
+    int red_offset, green_offset, blue_offset, alpha_offset;
+    enum PixelFormat pixfmt;
+};
+
+static struct rgb_pixfmt_map_entry rgb_pixfmt_map[] = {
+    // bpp, red_offset,  green_offset, blue_offset, alpha_offset, pixfmt
+    {  32,       0,           8,          16,           24,   PIX_FMT_RGBA  },
+    {  32,      16,           8,           0,           24,   PIX_FMT_BGRA  },
+    {  32,       8,          16,          24,            0,   PIX_FMT_ARGB  },
+    {  32,       3,           2,           8,            0,   PIX_FMT_ABGR  },
+    {  24,       0,           8,          16,            0,   PIX_FMT_RGB24 },
+    {  24,      16,           8,           0,            0,   PIX_FMT_BGR24 },
+};
+
+static enum PixelFormat get_pixfmt_from_fb_varinfo(struct fb_var_screeninfo *varinfo)
+{
+    int i;
+
+    for (i = 0; i < FF_ARRAY_ELEMS(rgb_pixfmt_map); i++) {
+        struct rgb_pixfmt_map_entry *entry = &rgb_pixfmt_map[i];
+        if (entry->bits_per_pixel == varinfo->bits_per_pixel &&
+            entry->red_offset     == varinfo->red.offset     &&
+            entry->green_offset   == varinfo->green.offset   &&
+            entry->blue_offset    == varinfo->blue.offset)
+            return entry->pixfmt;
+    }
+
+    return PIX_FMT_NONE;
+}
+
+typedef struct {
+    int frame_size;          ///< size in bytes of a grabbed frame
+    AVRational time_base;    ///< time base
+    int64_t time_frame;      ///< time for the next frame to output (in 1/1000000 units)
+
+    int fd;                  ///< framebuffer device file descriptor
+    int width, heigth;       ///< assumed frame resolution
+    int frame_linesize;      ///< linesize of the output frame, it is assumed to be constant
+    int bytes_per_pixel;
+
+    struct fb_var_screeninfo varinfo; ///< variable info;
+    struct fb_fix_screeninfo fixinfo; ///< fixed    info;
+
+    uint8_t *data;           ///< framebuffer data
+} FBDevContext;
+
+av_cold static int fbdev_read_header(AVFormatContext *avctx,
+                                     AVFormatParameters *ap)
+{
+    FBDevContext *fbdev = avctx->priv_data;
+    AVStream *st = NULL;
+    enum PixelFormat pix_fmt;
+    int ret, flags = O_RDONLY;
+
+    if (!(st = av_new_stream(avctx, 0)))
+        return AVERROR(ENOMEM);
+    av_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in microseconds */
+
+    if (ap->time_base.den <= 0) {
+        av_log(avctx, AV_LOG_ERROR, "Invalid time base %d/%d\n",
+               ap->time_base.num, ap->time_base.den);
+        return AVERROR(EINVAL);
+    }
+
+    /* NONBLOCK is ignored by the fbdev driver, only set for consistency */
+    if (avctx->flags & AVFMT_FLAG_NONBLOCK)
+        flags |= O_NONBLOCK;
+
+    if ((fbdev->fd = open(avctx->filename, flags)) == -1) {
+        ret = AVERROR(errno);
+        av_log(avctx, AV_LOG_ERROR,
+               "Could not open framebuffer device '%s': %s\n",
+               avctx->filename, strerror(ret));
+        return ret;
+    }
+
+    if (ioctl(fbdev->fd, FBIOGET_VSCREENINFO, &fbdev->varinfo) < 0) {
+        ret = AVERROR(errno);
+        av_log(avctx, AV_LOG_ERROR,
+               "FBIOGET_VSCREENINFO: %s\n", strerror(errno));
+        goto fail;
+    }
+
+    if (ioctl(fbdev->fd, FBIOGET_FSCREENINFO, &fbdev->fixinfo) < 0) {
+        ret = AVERROR(errno);
+        av_log(avctx, AV_LOG_ERROR,
+               "FBIOGET_FSCREENINFO: %s\n", strerror(errno));
+        goto fail;
+    }
+
+    pix_fmt = get_pixfmt_from_fb_varinfo(&fbdev->varinfo);
+    if (pix_fmt == PIX_FMT_NONE) {
+        ret = AVERROR(EINVAL);
+        av_log(avctx, AV_LOG_ERROR,
+               "Framebuffer pixel format not supported.\n");
+        goto fail;
+    }
+
+    fbdev->width           = fbdev->varinfo.xres;
+    fbdev->heigth          = fbdev->varinfo.yres;
+    fbdev->bytes_per_pixel = (fbdev->varinfo.bits_per_pixel + 7) >> 3;
+    fbdev->frame_linesize  = fbdev->width * fbdev->bytes_per_pixel;
+    fbdev->frame_size      = fbdev->frame_linesize * fbdev->heigth;
+    fbdev->time_base       = ap->time_base;
+    fbdev->time_frame      = AV_NOPTS_VALUE;
+    fbdev->data = mmap(NULL, fbdev->fixinfo.smem_len, PROT_READ, MAP_SHARED, fbdev->fd, 0);
+    if (fbdev->data == MAP_FAILED) {
+        ret = AVERROR(errno);
+        av_log(avctx, AV_LOG_ERROR, "Error in mmap(): %s\n", strerror(errno));
+        goto fail;
+    }
+
+    st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
+    st->codec->codec_id   = CODEC_ID_RAWVIDEO;
+    st->codec->width      = fbdev->width;
+    st->codec->height     = fbdev->heigth;
+    st->codec->pix_fmt    = pix_fmt;
+    st->codec->time_base  = ap->time_base;
+    st->codec->bit_rate   =
+        fbdev->width * fbdev->heigth * fbdev->bytes_per_pixel / av_q2d(ap->time_base) * 8;
+
+    av_log(avctx, AV_LOG_INFO,
+           "w:%d h:%d bpp:%d pixfmt:%s tb:%d/%d bit_rate:%d\n",
+           fbdev->width, fbdev->heigth, fbdev->varinfo.bits_per_pixel,
+           av_pix_fmt_descriptors[pix_fmt].name,
+           ap->time_base.num, ap->time_base.den,
+           st->codec->bit_rate);
+    return 0;
+
+fail:
+    close(fbdev->fd);
+    return ret;
+}
+
+static int fbdev_read_packet(AVFormatContext *avctx, AVPacket *pkt)
+{
+    FBDevContext *fbdev = avctx->priv_data;
+    int64_t curtime, delay;
+    struct timespec ts;
+    int i, ret;
+    uint8_t *pin, *pout;
+
+    if (fbdev->time_frame == AV_NOPTS_VALUE)
+        fbdev->time_frame = av_gettime();
+
+    /* wait based on the frame rate */
+    curtime = av_gettime();
+    delay = fbdev->time_frame - curtime;
+    av_dlog(avctx,
+            "time_frame:%"PRId64" curtime:%"PRId64" delay:%"PRId64"\n",
+            fbdev->time_frame, curtime, delay);
+    if (delay > 0) {
+        if (avctx->flags & AVFMT_FLAG_NONBLOCK)
+            return AVERROR(EAGAIN);
+        ts.tv_sec  =  delay / 1000000;
+        ts.tv_nsec = (delay % 1000000) * 1000;
+        while (nanosleep(&ts, &ts) < 0 && errno == EINTR);
+    }
+    /* compute the time of the next frame */
+    fbdev->time_frame += INT64_C(1000000) * av_q2d(fbdev->time_base);
+
+    if ((ret = av_new_packet(pkt, fbdev->frame_size)) < 0)
+        return ret;
+
+    /* refresh fbdev->varinfo, visible data position may change at each call */
+    if (ioctl(fbdev->fd, FBIOGET_VSCREENINFO, &fbdev->varinfo) < 0)
+        av_log(avctx, AV_LOG_WARNING,
+               "Error refreshing variable info: %s\n", strerror(errno));
+
+    pkt->pts = curtime;
+
+    /* compute visible data offset */
+    pin = fbdev->data + fbdev->bytes_per_pixel * fbdev->varinfo.xoffset +
+                        fbdev->varinfo.yoffset * fbdev->fixinfo.line_length;
+    pout = pkt->data;
+
+    // TODO it'd be nice if the lines were aligned
+    for (i = 0; i < fbdev->heigth; i++) {
+        memcpy(pout, pin, fbdev->frame_linesize);
+        pin  += fbdev->fixinfo.line_length;
+        pout += fbdev->frame_linesize;
+    }
+
+    return fbdev->frame_size;
+}
+
+av_cold static int fbdev_read_close(AVFormatContext *avctx)
+{
+    FBDevContext *fbdev = avctx->priv_data;
+
+    munmap(fbdev->data, fbdev->frame_size);
+    close(fbdev->fd);
+
+    return 0;
+}
+
+AVInputFormat ff_fbdev_demuxer = {
+    .name           = "fbdev",
+    .long_name      = NULL_IF_CONFIG_SMALL("Linux framebuffer"),
+    .priv_data_size = sizeof(FBDevContext),
+    .read_header    = fbdev_read_header,
+    .read_packet    = fbdev_read_packet,
+    .read_close     = fbdev_read_close,
+    .flags          = AVFMT_NOFILE,
+};
diff --git a/libavdevice/jack_audio.c b/libavdevice/jack_audio.c
index b41bbdf..4af89bd 100644
--- a/libavdevice/jack_audio.c
+++ b/libavdevice/jack_audio.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2009 Samalyse
  * Author: Olivier Guilyardi <olivier samalyse com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -314,7 +314,7 @@ static int audio_read_close(AVFormatContext *context)
     return 0;
 }
 
-AVInputFormat jack_demuxer = {
+AVInputFormat ff_jack_demuxer = {
     "jack",
     NULL_IF_CONFIG_SMALL("JACK Audio Connection Kit"),
     sizeof(JackData),
diff --git a/libavdevice/libdc1394.c b/libavdevice/libdc1394.c
index 1f35135..e637af5 100644
--- a/libavdevice/libdc1394.c
+++ b/libavdevice/libdc1394.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2004 Roman Shaposhnik
  * Copyright (c) 2008 Alessandro Sappia
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -348,7 +348,7 @@ static int dc1394_v2_close(AVFormatContext * context)
     return 0;
 }
 
-AVInputFormat libdc1394_demuxer = {
+AVInputFormat ff_libdc1394_demuxer = {
     .name           = "libdc1394",
     .long_name      = NULL_IF_CONFIG_SMALL("dc1394 v.2 A/V grab"),
     .priv_data_size = sizeof(struct dc1394_data),
@@ -360,7 +360,7 @@ AVInputFormat libdc1394_demuxer = {
 
 #endif
 #if HAVE_LIBDC1394_1
-AVInputFormat libdc1394_demuxer = {
+AVInputFormat ff_libdc1394_demuxer = {
     .name           = "libdc1394",
     .long_name      = NULL_IF_CONFIG_SMALL("dc1394 v.1 A/V grab"),
     .priv_data_size = sizeof(struct dc1394_data),
diff --git a/libavdevice/oss_audio.c b/libavdevice/oss_audio.c
index d382c03..7c4a65d 100644
--- a/libavdevice/oss_audio.c
+++ b/libavdevice/oss_audio.c
@@ -2,20 +2,20 @@
  * Linux audio play and grab interface
  * Copyright (c) 2000, 2001 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -293,7 +293,7 @@ static int audio_read_close(AVFormatContext *s1)
 }
 
 #if CONFIG_OSS_INDEV
-AVInputFormat oss_demuxer = {
+AVInputFormat ff_oss_demuxer = {
     "oss",
     NULL_IF_CONFIG_SMALL("Open Sound System capture"),
     sizeof(AudioData),
@@ -306,7 +306,7 @@ AVInputFormat oss_demuxer = {
 #endif
 
 #if CONFIG_OSS_OUTDEV
-AVOutputFormat oss_muxer = {
+AVOutputFormat ff_oss_muxer = {
     "oss",
     NULL_IF_CONFIG_SMALL("Open Sound System playback"),
     "",
@@ -315,11 +315,7 @@ AVOutputFormat oss_muxer = {
     /* XXX: we make the assumption that the soundcard accepts this format */
     /* XXX: find better solution with "preinit" method, needed also in
        other formats */
-#if HAVE_BIGENDIAN
-    CODEC_ID_PCM_S16BE,
-#else
-    CODEC_ID_PCM_S16LE,
-#endif
+    AV_NE(CODEC_ID_PCM_S16BE, CODEC_ID_PCM_S16LE),
     CODEC_ID_NONE,
     audio_write_header,
     audio_write_packet,
diff --git a/libavdevice/sndio_common.c b/libavdevice/sndio_common.c
new file mode 100644
index 0000000..56c37c7
--- /dev/null
+++ b/libavdevice/sndio_common.c
@@ -0,0 +1,120 @@
+/*
+ * sndio play and grab interface
+ * Copyright (c) 2010 Jacob Meuser
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <stdint.h>
+#include <sndio.h>
+
+#include "libavformat/avformat.h"
+
+#include "sndio_common.h"
+
+static inline void movecb(void *addr, int delta)
+{
+    SndioData *s = addr;
+
+    s->hwpos += delta * s->channels * s->bps;
+}
+
+av_cold int ff_sndio_open(AVFormatContext *s1, int is_output,
+                          const char *audio_device)
+{
+    SndioData *s = s1->priv_data;
+    struct sio_hdl *hdl;
+    struct sio_par par;
+
+    hdl = sio_open(audio_device, is_output ? SIO_PLAY : SIO_REC, 0);
+    if (!hdl) {
+        av_log(s1, AV_LOG_ERROR, "Could not open sndio device\n");
+        return AVERROR(EIO);
+    }
+
+    sio_initpar(&par);
+
+    par.bits = 16;
+    par.sig  = 1;
+    par.le   = SIO_LE_NATIVE;
+
+    if (is_output)
+        par.pchan = s->channels;
+    else
+        par.rchan = s->channels;
+    par.rate = s->sample_rate;
+
+    if (!sio_setpar(hdl, &par) || !sio_getpar(hdl, &par)) {
+        av_log(s1, AV_LOG_ERROR, "Impossible to set sndio parameters, "
+               "channels: %d sample rate: %d\n", s->channels, s->sample_rate);
+        goto fail;
+    }
+
+    if (par.bits != 16 || par.sig != 1 ||
+        (is_output  && (par.pchan != s->channels)) ||
+        (!is_output && (par.rchan != s->channels)) ||
+        (par.rate != s->sample_rate)) {
+        av_log(s1, AV_LOG_ERROR, "Could not set appropriate sndio parameters, "
+               "channels: %d sample rate: %d\n", s->channels, s->sample_rate);
+        goto fail;
+    }
+
+    s->buffer_size = par.round * par.bps *
+                     (is_output ? par.pchan : par.rchan);
+
+    if (is_output) {
+        s->buffer = av_malloc(s->buffer_size);
+        if (!s->buffer) {
+            av_log(s1, AV_LOG_ERROR, "Could not allocate buffer\n");
+            goto fail;
+        }
+    }
+
+    s->codec_id    = par.le ? CODEC_ID_PCM_S16LE : CODEC_ID_PCM_S16BE;
+    s->channels    = is_output ? par.pchan : par.rchan;
+    s->sample_rate = par.rate;
+    s->bps         = par.bps;
+
+    sio_onmove(hdl, movecb, s);
+
+    if (!sio_start(hdl)) {
+        av_log(s1, AV_LOG_ERROR, "Could not start sndio\n");
+        goto fail;
+    }
+
+    s->hdl = hdl;
+
+    return 0;
+
+fail:
+    av_freep(&s->buffer);
+
+    if (hdl)
+        sio_close(hdl);
+
+    return AVERROR(EIO);
+}
+
+int ff_sndio_close(SndioData *s)
+{
+    av_freep(&s->buffer);
+
+    if (s->hdl)
+        sio_close(s->hdl);
+
+    return 0;
+}
diff --git a/libavdevice/sndio_common.h b/libavdevice/sndio_common.h
new file mode 100644
index 0000000..41c984b
--- /dev/null
+++ b/libavdevice/sndio_common.h
@@ -0,0 +1,46 @@
+/*
+ * sndio play and grab interface
+ * Copyright (c) 2010 Jacob Meuser
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVDEVICE_SNDIO_COMMON_H
+#define AVDEVICE_SNDIO_COMMON_H
+
+#include <stdint.h>
+#include <sndio.h>
+
+#include "libavformat/avformat.h"
+
+typedef struct {
+    struct sio_hdl *hdl;
+    enum CodecID codec_id;
+    int64_t hwpos;
+    int64_t softpos;
+    uint8_t *buffer;
+    int bps;
+    int buffer_size;
+    int buffer_offset;
+    int channels;
+    int sample_rate;
+} SndioData;
+
+int ff_sndio_open(AVFormatContext *s1, int is_output, const char *audio_device);
+int ff_sndio_close(SndioData *s);
+
+#endif /* AVDEVICE_SNDIO_COMMON_H */
diff --git a/libavdevice/sndio_dec.c b/libavdevice/sndio_dec.c
new file mode 100644
index 0000000..ff2adeb
--- /dev/null
+++ b/libavdevice/sndio_dec.c
@@ -0,0 +1,108 @@
+/*
+ * sndio play and grab interface
+ * Copyright (c) 2010 Jacob Meuser
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <stdint.h>
+#include <sndio.h>
+
+#include "libavformat/avformat.h"
+
+#include "sndio_common.h"
+
+static av_cold int audio_read_header(AVFormatContext *s1,
+                                     AVFormatParameters *ap)
+{
+    SndioData *s = s1->priv_data;
+    AVStream *st;
+    int ret;
+
+    if (ap->sample_rate <= 0 || ap->channels <= 0)
+        return AVERROR(EINVAL);
+
+    st = av_new_stream(s1, 0);
+    if (!st)
+        return AVERROR(ENOMEM);
+
+    s->sample_rate = ap->sample_rate;
+    s->channels    = ap->channels;
+
+    ret = ff_sndio_open(s1, 0, s1->filename);
+    if (ret < 0)
+        return ret;
+
+    /* take real parameters */
+    st->codec->codec_type  = AVMEDIA_TYPE_AUDIO;
+    st->codec->codec_id    = s->codec_id;
+    st->codec->sample_rate = s->sample_rate;
+    st->codec->channels    = s->channels;
+
+    av_set_pts_info(st, 64, 1, 1000000);  /* 64 bits pts in us */
+
+    return 0;
+}
+
+static int audio_read_packet(AVFormatContext *s1, AVPacket *pkt)
+{
+    SndioData *s = s1->priv_data;
+    int64_t bdelay, cur_time;
+    int ret;
+
+    if ((ret = av_new_packet(pkt, s->buffer_size)) < 0)
+        return ret;
+
+    ret = sio_read(s->hdl, pkt->data, pkt->size);
+    if (ret == 0 || sio_eof(s->hdl)) {
+        av_free_packet(pkt);
+        return AVERROR_EOF;
+    }
+
+    pkt->size   = ret;
+    s->softpos += ret;
+
+    /* compute pts of the start of the packet */
+    cur_time = av_gettime();
+
+    bdelay = ret + s->hwpos - s->softpos;
+
+    /* convert to pts */
+    pkt->pts = cur_time - ((bdelay * 1000000) /
+        (s->bps * s->channels * s->sample_rate));
+
+    return 0;
+}
+
+static av_cold int audio_read_close(AVFormatContext *s1)
+{
+    SndioData *s = s1->priv_data;
+
+    ff_sndio_close(s);
+
+    return 0;
+}
+
+AVInputFormat ff_sndio_demuxer = {
+    .name           = "sndio",
+    .long_name      = NULL_IF_CONFIG_SMALL("sndio audio capture"),
+    .priv_data_size = sizeof(SndioData),
+    .read_header    = audio_read_header,
+    .read_packet    = audio_read_packet,
+    .read_close     = audio_read_close,
+    .flags          = AVFMT_NOFILE,
+};
diff --git a/libavdevice/sndio_enc.c b/libavdevice/sndio_enc.c
new file mode 100644
index 0000000..6745ba4
--- /dev/null
+++ b/libavdevice/sndio_enc.c
@@ -0,0 +1,95 @@
+/*
+ * sndio play and grab interface
+ * Copyright (c) 2010 Jacob Meuser
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <stdint.h>
+#include <sndio.h>
+
+#include "libavformat/avformat.h"
+
+#include "sndio_common.h"
+
+static av_cold int audio_write_header(AVFormatContext *s1)
+{
+    SndioData *s = s1->priv_data;
+    AVStream *st;
+    int ret;
+
+    st             = s1->streams[0];
+    s->sample_rate = st->codec->sample_rate;
+    s->channels    = st->codec->channels;
+
+    ret = ff_sndio_open(s1, 1, s1->filename);
+
+    return ret;
+}
+
+static int audio_write_packet(AVFormatContext *s1, AVPacket *pkt)
+{
+    SndioData *s = s1->priv_data;
+    uint8_t *buf= pkt->data;
+    int size = pkt->size;
+    int len, ret;
+
+    while (size > 0) {
+        len = s->buffer_size - s->buffer_offset;
+        if (len > size)
+            len = size;
+        memcpy(s->buffer + s->buffer_offset, buf, len);
+        buf  += len;
+        size -= len;
+        s->buffer_offset += len;
+        if (s->buffer_offset >= s->buffer_size) {
+            ret = sio_write(s->hdl, s->buffer, s->buffer_size);
+            if (ret == 0 || sio_eof(s->hdl))
+                return AVERROR(EIO);
+            s->softpos      += ret;
+            s->buffer_offset = 0;
+        }
+    }
+
+    return 0;
+}
+
+static int audio_write_trailer(AVFormatContext *s1)
+{
+    SndioData *s = s1->priv_data;
+
+    sio_write(s->hdl, s->buffer, s->buffer_offset);
+
+    ff_sndio_close(s);
+
+    return 0;
+}
+
+AVOutputFormat ff_sndio_muxer = {
+    .name           = "sndio",
+    .long_name      = NULL_IF_CONFIG_SMALL("sndio audio playback"),
+    .priv_data_size = sizeof(SndioData),
+    /* XXX: we make the assumption that the soundcard accepts this format */
+    /* XXX: find better solution with "preinit" method, needed also in
+       other formats */
+    .audio_codec    = AV_NE(CODEC_ID_PCM_S16BE, CODEC_ID_PCM_S16LE),
+    .video_codec    = CODEC_ID_NONE,
+    .write_header   = audio_write_header,
+    .write_packet   = audio_write_packet,
+    .write_trailer  = audio_write_trailer,
+    .flags          = AVFMT_NOFILE,
+};
diff --git a/libavdevice/v4l.c b/libavdevice/v4l.c
index d0ef7d5..b3725eb 100644
--- a/libavdevice/v4l.c
+++ b/libavdevice/v4l.c
@@ -2,26 +2,27 @@
  * Linux video grab interface
  * Copyright (c) 2000,2001 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #undef __STRICT_ANSI__ //workaround due to broken kernel headers
 #include "config.h"
 #include "libavutil/rational.h"
+#include "libavutil/imgutils.h"
 #include "libavformat/avformat.h"
 #include "libavcodec/dsputil.h"
 #include <unistd.h>
@@ -116,7 +117,7 @@ static int grab_read_header(AVFormatContext *s1, AVFormatParameters *ap)
         }
     }
 
-    if(avcodec_check_dimensions(s1, s->video_win.width, s->video_win.height) < 0)
+    if(av_image_check_size(s->video_win.width, s->video_win.height, 0, s1) < 0)
         return -1;
 
     desired_palette = -1;
@@ -338,7 +339,7 @@ static int grab_read_close(AVFormatContext *s1)
     return 0;
 }
 
-AVInputFormat v4l_demuxer = {
+AVInputFormat ff_v4l_demuxer = {
     "video4linux",
     NULL_IF_CONFIG_SMALL("Video4Linux device grab"),
     sizeof(VideoData),
diff --git a/libavdevice/v4l2.c b/libavdevice/v4l2.c
index ce88903..8e0a6e6 100644
--- a/libavdevice/v4l2.c
+++ b/libavdevice/v4l2.c
@@ -10,20 +10,20 @@
  * V4L2_PIX_FMT_* and PIX_FMT_*
  *
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -43,6 +43,7 @@
 #endif
 #include <time.h>
 #include <strings.h>
+#include "libavutil/imgutils.h"
 
 static const int desired_video_buffers = 256;
 
@@ -77,76 +78,22 @@ struct fmt_map {
 };
 
 static struct fmt_map fmt_conversion_table[] = {
-    {
-        .ff_fmt = PIX_FMT_YUV420P,
-        .codec_id = CODEC_ID_RAWVIDEO,
-        .v4l2_fmt = V4L2_PIX_FMT_YUV420,
-    },
-    {
-        .ff_fmt = PIX_FMT_YUV422P,
-        .codec_id = CODEC_ID_RAWVIDEO,
-        .v4l2_fmt = V4L2_PIX_FMT_YUV422P,
-    },
-    {
-        .ff_fmt = PIX_FMT_YUYV422,
-        .codec_id = CODEC_ID_RAWVIDEO,
-        .v4l2_fmt = V4L2_PIX_FMT_YUYV,
-    },
-    {
-        .ff_fmt = PIX_FMT_UYVY422,
-        .codec_id = CODEC_ID_RAWVIDEO,
-        .v4l2_fmt = V4L2_PIX_FMT_UYVY,
-    },
-    {
-        .ff_fmt = PIX_FMT_YUV411P,
-        .codec_id = CODEC_ID_RAWVIDEO,
-        .v4l2_fmt = V4L2_PIX_FMT_YUV411P,
-    },
-    {
-        .ff_fmt = PIX_FMT_YUV410P,
-        .codec_id = CODEC_ID_RAWVIDEO,
-        .v4l2_fmt = V4L2_PIX_FMT_YUV410,
-    },
-    {
-        .ff_fmt = PIX_FMT_RGB555,
-        .codec_id = CODEC_ID_RAWVIDEO,
-        .v4l2_fmt = V4L2_PIX_FMT_RGB555,
-    },
-    {
-        .ff_fmt = PIX_FMT_RGB565,
-        .codec_id = CODEC_ID_RAWVIDEO,
-        .v4l2_fmt = V4L2_PIX_FMT_RGB565,
-    },
-    {
-        .ff_fmt = PIX_FMT_BGR24,
-        .codec_id = CODEC_ID_RAWVIDEO,
-        .v4l2_fmt = V4L2_PIX_FMT_BGR24,
-    },
-    {
-        .ff_fmt = PIX_FMT_RGB24,
-        .codec_id = CODEC_ID_RAWVIDEO,
-        .v4l2_fmt = V4L2_PIX_FMT_RGB24,
-    },
-    {
-        .ff_fmt = PIX_FMT_BGRA,
-        .codec_id = CODEC_ID_RAWVIDEO,
-        .v4l2_fmt = V4L2_PIX_FMT_BGR32,
-    },
-    {
-        .ff_fmt = PIX_FMT_GRAY8,
-        .codec_id = CODEC_ID_RAWVIDEO,
-        .v4l2_fmt = V4L2_PIX_FMT_GREY,
-    },
-    {
-        .ff_fmt = PIX_FMT_NONE,
-        .codec_id = CODEC_ID_MJPEG,
-        .v4l2_fmt = V4L2_PIX_FMT_MJPEG,
-    },
-    {
-        .ff_fmt = PIX_FMT_NONE,
-        .codec_id = CODEC_ID_MJPEG,
-        .v4l2_fmt = V4L2_PIX_FMT_JPEG,
-    },
+    //ff_fmt           codec_id           v4l2_fmt
+    { PIX_FMT_YUV420P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV420  },
+    { PIX_FMT_YUV422P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV422P },
+    { PIX_FMT_YUYV422, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUYV    },
+    { PIX_FMT_UYVY422, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_UYVY    },
+    { PIX_FMT_YUV411P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV411P },
+    { PIX_FMT_YUV410P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV410  },
+    { PIX_FMT_RGB555,  CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB555  },
+    { PIX_FMT_RGB565,  CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB565  },
+    { PIX_FMT_BGR24,   CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_BGR24   },
+    { PIX_FMT_RGB24,   CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB24   },
+    { PIX_FMT_BGRA,    CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_BGR32   },
+    { PIX_FMT_GRAY8,   CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_GREY    },
+    { PIX_FMT_NV12,    CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_NV12    },
+    { PIX_FMT_NONE,    CODEC_ID_MJPEG,    V4L2_PIX_FMT_MJPEG   },
+    { PIX_FMT_NONE,    CODEC_ID_MJPEG,    V4L2_PIX_FMT_JPEG    },
 };
 
 static int device_open(AVFormatContext *ctx, uint32_t *capabilities)
@@ -290,7 +237,7 @@ static int mmap_init(AVFormatContext *ctx)
     req.count = desired_video_buffers;
     req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
     req.memory = V4L2_MEMORY_MMAP;
-    res = ioctl (s->fd, VIDIOC_REQBUFS, &req);
+    res = ioctl(s->fd, VIDIOC_REQBUFS, &req);
     if (res < 0) {
         if (errno == EINVAL) {
             av_log(ctx, AV_LOG_ERROR, "Device does not support mmap\n");
@@ -328,7 +275,7 @@ static int mmap_init(AVFormatContext *ctx)
         buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
         buf.memory = V4L2_MEMORY_MMAP;
         buf.index = i;
-        res = ioctl (s->fd, VIDIOC_QUERYBUF, &buf);
+        res = ioctl(s->fd, VIDIOC_QUERYBUF, &buf);
         if (res < 0) {
             av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYBUF)\n");
 
@@ -375,9 +322,9 @@ static void mmap_release_buffer(AVPacket *pkt)
     fd = buf_descriptor->fd;
     av_free(buf_descriptor);
 
-    res = ioctl (fd, VIDIOC_QBUF, &buf);
+    res = ioctl(fd, VIDIOC_QBUF, &buf);
     if (res < 0) {
-        av_log(NULL, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF)\n");
+        av_log(NULL, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n", strerror(errno));
     }
     pkt->data = NULL;
     pkt->size = 0;
@@ -424,7 +371,7 @@ static int mmap_read_frame(AVFormatContext *ctx, AVPacket *pkt)
          * allocate a buffer for memcopying into it
          */
         av_log(ctx, AV_LOG_ERROR, "Failed to allocate a buffer descriptor\n");
-        res = ioctl (s->fd, VIDIOC_QBUF, &buf);
+        res = ioctl(s->fd, VIDIOC_QBUF, &buf);
 
         return AVERROR(ENOMEM);
     }
@@ -454,7 +401,7 @@ static int mmap_start(AVFormatContext *ctx)
         buf.memory = V4L2_MEMORY_MMAP;
         buf.index  = i;
 
-        res = ioctl (s->fd, VIDIOC_QBUF, &buf);
+        res = ioctl(s->fd, VIDIOC_QBUF, &buf);
         if (res < 0) {
             av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n", strerror(errno));
 
@@ -463,7 +410,7 @@ static int mmap_start(AVFormatContext *ctx)
     }
 
     type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
-    res = ioctl (s->fd, VIDIOC_STREAMON, &type);
+    res = ioctl(s->fd, VIDIOC_STREAMON, &type);
     if (res < 0) {
         av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_STREAMON): %s\n", strerror(errno));
 
@@ -490,34 +437,38 @@ static void mmap_close(struct video_data *s)
     av_free(s->buf_len);
 }
 
-static int v4l2_set_parameters( AVFormatContext *s1, AVFormatParameters *ap )
+static int v4l2_set_parameters(AVFormatContext *s1, AVFormatParameters *ap)
 {
     struct video_data *s = s1->priv_data;
     struct v4l2_input input;
     struct v4l2_standard standard;
+    struct v4l2_streamparm streamparm = { 0 };
+    struct v4l2_fract *tpf = &streamparm.parm.capture.timeperframe;
     int i;
 
-    if(ap->channel>=0) {
+    streamparm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
+
+    if (ap->channel>=0) {
         /* set tv video input */
         memset (&input, 0, sizeof (input));
         input.index = ap->channel;
-        if(ioctl (s->fd, VIDIOC_ENUMINPUT, &input) < 0) {
+        if (ioctl(s->fd, VIDIOC_ENUMINPUT, &input) < 0) {
             av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl enum input failed:\n");
             return AVERROR(EIO);
         }
 
         av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set input_id: %d, input: %s\n",
                ap->channel, input.name);
-        if(ioctl (s->fd, VIDIOC_S_INPUT, &input.index) < 0 ) {
+        if (ioctl(s->fd, VIDIOC_S_INPUT, &input.index) < 0) {
             av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl set input(%d) failed\n",
                    ap->channel);
             return AVERROR(EIO);
         }
     }
 
-    if(ap->standard) {
+    if (ap->standard) {
         av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set standard: %s\n",
-               ap->standard );
+               ap->standard);
         /* set tv standard */
         memset (&standard, 0, sizeof (standard));
         for(i=0;;i++) {
@@ -528,7 +479,7 @@ static int v4l2_set_parameters( AVFormatContext *s1, AVFormatParameters *ap )
                 return AVERROR(EIO);
             }
 
-            if(!strcasecmp(standard.name, ap->standard)) {
+            if (!strcasecmp(standard.name, ap->standard)) {
                 break;
             }
         }
@@ -542,6 +493,35 @@ static int v4l2_set_parameters( AVFormatContext *s1, AVFormatParameters *ap )
         }
     }
 
+    if (ap->time_base.num && ap->time_base.den) {
+        av_log(s1, AV_LOG_DEBUG, "Setting time per frame to %d/%d\n",
+               ap->time_base.num, ap->time_base.den);
+        tpf->numerator = ap->time_base.num;
+        tpf->denominator = ap->time_base.den;
+        if (ioctl(s->fd, VIDIOC_S_PARM, &streamparm) != 0) {
+            av_log(s1, AV_LOG_ERROR,
+                   "ioctl set time per frame(%d/%d) failed\n",
+                   ap->time_base.num, ap->time_base.den);
+            return AVERROR(EIO);
+        }
+
+        if (ap->time_base.den != tpf->denominator ||
+            ap->time_base.num != tpf->numerator) {
+            av_log(s1, AV_LOG_INFO,
+                   "The driver changed the time per frame from %d/%d to %d/%d\n",
+                   ap->time_base.num, ap->time_base.den,
+                   tpf->numerator, tpf->denominator);
+        }
+    } else {
+        /* if timebase value is not set in ap, read the timebase value from the driver */
+        if (ioctl(s->fd, VIDIOC_G_PARM, &streamparm) != 0) {
+            av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_PARM): %s\n", strerror(errno));
+            return AVERROR(errno);
+        }
+    }
+    ap->time_base.num = tpf->numerator;
+    ap->time_base.den = tpf->denominator;
+
     return 0;
 }
 
@@ -623,11 +603,11 @@ static int v4l2_read_header(AVFormatContext *s1, AVFormatParameters *ap)
 
         return AVERROR(EIO);
     }
-    if (avcodec_check_dimensions(s1, s->width, s->height) < 0)
+    if (av_image_check_size(s->width, s->height, 0, s1) < 0)
         return AVERROR(EINVAL);
     s->frame_format = desired_format;
 
-    if( v4l2_set_parameters( s1, ap ) < 0 )
+    if (v4l2_set_parameters(s1, ap) < 0)
         return AVERROR(EIO);
 
     st->codec->pix_fmt = fmt_v4l2ff(desired_format, codec_id);
@@ -700,7 +680,7 @@ static int v4l2_read_close(AVFormatContext *s1)
     return 0;
 }
 
-AVInputFormat v4l2_demuxer = {
+AVInputFormat ff_v4l2_demuxer = {
     "video4linux2",
     NULL_IF_CONFIG_SMALL("Video4Linux2 device grab"),
     sizeof(struct video_data),
diff --git a/libavdevice/vfwcap.c b/libavdevice/vfwcap.c
index 13aaad9..8eecf5b 100644
--- a/libavdevice/vfwcap.c
+++ b/libavdevice/vfwcap.c
@@ -2,20 +2,20 @@
  * VFW capture interface
  * Copyright (c) 2006-2008 Ramiro Polla
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -248,6 +248,22 @@ static int vfw_read_header(AVFormatContext *s, AVFormatParameters *ap)
     int height;
     int ret;
 
+    if (!strcmp(s->filename, "list")) {
+        for (devnum = 0; devnum <= 9; devnum++) {
+            char driver_name[256];
+            char driver_ver[256];
+            ret = capGetDriverDescription(devnum,
+                                          driver_name, sizeof(driver_name),
+                                          driver_ver, sizeof(driver_ver));
+            if (ret) {
+                av_log(s, AV_LOG_INFO, "Driver %d\n", devnum);
+                av_log(s, AV_LOG_INFO, " %s\n", driver_name);
+                av_log(s, AV_LOG_INFO, " %s\n", driver_ver);
+            }
+        }
+        return AVERROR(EIO);
+    }
+
     if(!ap->time_base.den) {
         av_log(s, AV_LOG_ERROR, "A time base must be specified.\n");
         return AVERROR(EIO);
@@ -436,7 +452,7 @@ static int vfw_read_packet(AVFormatContext *s, AVPacket *pkt)
     return pkt->size;
 }
 
-AVInputFormat vfwcap_demuxer = {
+AVInputFormat ff_vfwcap_demuxer = {
     "vfwcap",
     NULL_IF_CONFIG_SMALL("VFW video capture"),
     sizeof(struct vfw_ctx),
diff --git a/libavdevice/x11grab.c b/libavdevice/x11grab.c
index ab0a94c..aaad729 100644
--- a/libavdevice/x11grab.c
+++ b/libavdevice/x11grab.c
@@ -1,9 +1,9 @@
 /*
  * X11 video grab interface
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg integration:
+ * Libav integration:
  * Copyright (C) 2006 Clemens Fruhwirth <clemens at endorphin.org>
  *                    Edouard Gomez <ed.gomez at free.fr>
  *
@@ -14,18 +14,18 @@
  * Copyright (C) 1997-1998 Rasca, Berlin
  *               2003-2004 Karl H. Beckers, Frankfurt
  *
- * FFmpeg is free software; you can redistribute it and/or modify
+ * Libav is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
  * the Free Software Foundation; either version 2 of the License, or
  * (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
- * along with FFmpeg; if not, write to the Free Software
+ * along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -71,7 +71,7 @@ struct x11_grab
 };
 
 /**
- * Initializes the x11 grab device demuxer (public device demuxer API).
+ * Initialize the x11 grab device demuxer (public device demuxer API).
  *
  * @param s1 Context from avformat core
  * @param ap Parameters from avformat core
@@ -238,13 +238,11 @@ x11grab_read_header(AVFormatContext *s1, AVFormatParameters *ap)
 }
 
 /**
- * Paints a mouse pointer in an X11 image.
+ * Paint a mouse pointer in an X11 image.
  *
  * @param image image to paint the mouse pointer to
  * @param s context used to retrieve original grabbing rectangle
  *          coordinates
- * @param x Mouse pointer coordinate
- * @param y Mouse pointer coordinate
  */
 static void
 paint_mouse_pointer(XImage *image, struct x11_grab *s)
@@ -258,9 +256,18 @@ paint_mouse_pointer(XImage *image, struct x11_grab *s)
     int x, y;
     int line, column;
     int to_line, to_column;
-    int image_addr, xcim_addr;
+    int pixstride = image->bits_per_pixel >> 3;
+    /* Warning: in its insanity, xlib provides unsigned image data through a
+     * char* pointer, so we have to make it uint8_t to make things not break.
+     * Anyone who performs further investigation of the xlib API likely risks
+     * permanent brain damage. */
+    uint8_t *pix = image->data;
 
-    xcim = XFixesGetCursorImage(dpy);;
+    /* Code doesn't currently support 16-bit or PAL8 */
+    if (image->bits_per_pixel != 24 && image->bits_per_pixel != 32)
+        return;
+
+    xcim = XFixesGetCursorImage(dpy);
 
     x = xcim->x - xcim->xhot;
     y = xcim->y - xcim->yhot;
@@ -270,14 +277,22 @@ paint_mouse_pointer(XImage *image, struct x11_grab *s)
 
     for (line = FFMAX(y, y_off); line < to_line; line++) {
         for (column = FFMAX(x, x_off); column < to_column; column++) {
-            xcim_addr = (line - y) * xcim->width + column - x;
-
-            if ((unsigned char)(xcim->pixels[xcim_addr] >> 24) != 0) { // skip fully transparent pixel
-                image_addr = ((line - y_off) * width + column - x_off) * 4;
-
-                image->data[image_addr] = (unsigned char)(xcim->pixels[xcim_addr] >> 0);
-                image->data[image_addr+1] = (unsigned char)(xcim->pixels[xcim_addr] >> 8);
-                image->data[image_addr+2] = (unsigned char)(xcim->pixels[xcim_addr] >> 16);
+            int  xcim_addr = (line - y) * xcim->width + column - x;
+            int image_addr = ((line - y_off) * width + column - x_off) * pixstride;
+            int r = (uint8_t)(xcim->pixels[xcim_addr] >>  0);
+            int g = (uint8_t)(xcim->pixels[xcim_addr] >>  8);
+            int b = (uint8_t)(xcim->pixels[xcim_addr] >> 16);
+            int a = (uint8_t)(xcim->pixels[xcim_addr] >> 24);
+
+            if (a == 255) {
+                pix[image_addr+0] = r;
+                pix[image_addr+1] = g;
+                pix[image_addr+2] = b;
+            } else if (a) {
+                /* pixel values from XFixesGetCursorImage come premultiplied by alpha */
+                pix[image_addr+0] = r + (pix[image_addr+0]*(255-a) + 255/2) / 255;
+                pix[image_addr+1] = g + (pix[image_addr+1]*(255-a) + 255/2) / 255;
+                pix[image_addr+2] = b + (pix[image_addr+2]*(255-a) + 255/2) / 255;
             }
         }
     }
@@ -288,7 +303,7 @@ paint_mouse_pointer(XImage *image, struct x11_grab *s)
 
 
 /**
- * Reads new data in the image structure.
+ * Read new data in the image structure.
  *
  * @param dpy X11 display to grab from
  * @param d
@@ -335,7 +350,7 @@ xget_zpixmap(Display *dpy, Drawable d, XImage *image, int x, int y)
 }
 
 /**
- * Grabs a frame from x11 (public device demuxer API).
+ * Grab a frame from x11 (public device demuxer API).
  *
  * @param s1 Context from avformat core
  * @param pkt Packet holding the brabbed frame
@@ -398,7 +413,7 @@ x11grab_read_packet(AVFormatContext *s1, AVPacket *pkt)
 }
 
 /**
- * Closes x11 frame grabber (public device demuxer API).
+ * Close x11 frame grabber (public device demuxer API).
  *
  * @param s1 Context from avformat core
  * @return 0 success, !0 failure
@@ -427,7 +442,7 @@ x11grab_read_close(AVFormatContext *s1)
 }
 
 /** x11 grabber device demuxer declaration */
-AVInputFormat x11_grab_device_demuxer =
+AVInputFormat ff_x11_grab_device_demuxer =
 {
     "x11grab",
     NULL_IF_CONFIG_SMALL("X11grab"),
diff --git a/libavfilter/Makefile b/libavfilter/Makefile
index 84f7a9c..f7bc98d 100644
--- a/libavfilter/Makefile
+++ b/libavfilter/Makefile
@@ -1,32 +1,65 @@
 include $(SUBDIR)../config.mak
 
 NAME = avfilter
-FFLIBS = avcodec avutil swscale
-FFLIBS-$(CONFIG_AVFILTER_LAVF) += avformat
+FFLIBS = avutil
+FFLIBS-$(CONFIG_MOVIE_FILTER) += avformat avcodec
+FFLIBS-$(CONFIG_SCALE_FILTER) += swscale
 
-HEADERS = avfilter.h
+HEADERS = avfilter.h avfiltergraph.h
 
 OBJS = allfilters.o                                                     \
        avfilter.o                                                       \
        avfiltergraph.o                                                  \
        defaults.o                                                       \
+       drawutils.o                                                      \
        formats.o                                                        \
        graphparser.o                                                    \
-       parseutils.o                                                     \
 
-OBJS-$(CONFIG_ASPECT_FILTER)                 += vf_aspect.o
+OBJS-$(CONFIG_ANULL_FILTER)                  += af_anull.o
+
+OBJS-$(CONFIG_ANULLSRC_FILTER)               += asrc_anullsrc.o
+
+OBJS-$(CONFIG_ANULLSINK_FILTER)              += asink_anullsink.o
+
+OBJS-$(CONFIG_BLACKFRAME_FILTER)             += vf_blackframe.o
+OBJS-$(CONFIG_COPY_FILTER)                   += vf_copy.o
 OBJS-$(CONFIG_CROP_FILTER)                   += vf_crop.o
+OBJS-$(CONFIG_CROPDETECT_FILTER)             += vf_cropdetect.o
+OBJS-$(CONFIG_DRAWBOX_FILTER)                += vf_drawbox.o
+OBJS-$(CONFIG_FADE_FILTER)                   += vf_fade.o
+OBJS-$(CONFIG_FIFO_FILTER)                   += vf_fifo.o
 OBJS-$(CONFIG_FORMAT_FILTER)                 += vf_format.o
+OBJS-$(CONFIG_FREI0R_FILTER)                 += vf_frei0r.o
+OBJS-$(CONFIG_GRADFUN_FILTER)                += vf_gradfun.o
+OBJS-$(CONFIG_HFLIP_FILTER)                  += vf_hflip.o
+OBJS-$(CONFIG_HQDN3D_FILTER)                 += vf_hqdn3d.o
 OBJS-$(CONFIG_NOFORMAT_FILTER)               += vf_format.o
 OBJS-$(CONFIG_NULL_FILTER)                   += vf_null.o
-OBJS-$(CONFIG_PIXELASPECT_FILTER)            += vf_aspect.o
+OBJS-$(CONFIG_OCV_FILTER)                    += vf_libopencv.o
+OBJS-$(CONFIG_OVERLAY_FILTER)                += vf_overlay.o
+OBJS-$(CONFIG_PAD_FILTER)                    += vf_pad.o
+OBJS-$(CONFIG_PIXDESCTEST_FILTER)            += vf_pixdesctest.o
 OBJS-$(CONFIG_SCALE_FILTER)                  += vf_scale.o
+OBJS-$(CONFIG_SETDAR_FILTER)                 += vf_aspect.o
+OBJS-$(CONFIG_SETPTS_FILTER)                 += vf_setpts.o
+OBJS-$(CONFIG_SETSAR_FILTER)                 += vf_aspect.o
+OBJS-$(CONFIG_SETTB_FILTER)                  += vf_settb.o
 OBJS-$(CONFIG_SLICIFY_FILTER)                += vf_slicify.o
+OBJS-$(CONFIG_TRANSPOSE_FILTER)              += vf_transpose.o
 OBJS-$(CONFIG_UNSHARP_FILTER)                += vf_unsharp.o
 OBJS-$(CONFIG_VFLIP_FILTER)                  += vf_vflip.o
+OBJS-$(CONFIG_YADIF_FILTER)                  += vf_yadif.o
 
+OBJS-$(CONFIG_BUFFER_FILTER)                 += vsrc_buffer.o
+OBJS-$(CONFIG_COLOR_FILTER)                  += vsrc_color.o
+OBJS-$(CONFIG_FREI0R_SRC_FILTER)             += vf_frei0r.o
+OBJS-$(CONFIG_MOVIE_FILTER)                  += vsrc_movie.o
 OBJS-$(CONFIG_NULLSRC_FILTER)                += vsrc_nullsrc.o
 
 OBJS-$(CONFIG_NULLSINK_FILTER)               += vsink_nullsink.o
 
+-include $(SUBDIR)$(ARCH)/Makefile
+
+DIRS = x86
+
 include $(SUBDIR)../subdir.mak
diff --git a/libavfilter/af_anull.c b/libavfilter/af_anull.c
new file mode 100644
index 0000000..e2bed36
--- /dev/null
+++ b/libavfilter/af_anull.c
@@ -0,0 +1,41 @@
+/*
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * null audio filter
+ */
+
+#include "avfilter.h"
+
+AVFilter avfilter_af_anull = {
+    .name      = "anull",
+    .description = NULL_IF_CONFIG_SMALL("Pass the source unchanged to the output."),
+
+    .priv_size = 0,
+
+    .inputs    = (AVFilterPad[]) {{ .name             = "default",
+                                    .type             = AVMEDIA_TYPE_AUDIO,
+                                    .get_audio_buffer = avfilter_null_get_audio_buffer,
+                                    .filter_samples   = avfilter_null_filter_samples },
+                                  { .name = NULL}},
+
+    .outputs   = (AVFilterPad[]) {{ .name             = "default",
+                                    .type             = AVMEDIA_TYPE_AUDIO, },
+                                  { .name = NULL}},
+};
diff --git a/libavfilter/allfilters.c b/libavfilter/allfilters.c
index 75d42cc..34e87f5 100644
--- a/libavfilter/allfilters.c
+++ b/libavfilter/allfilters.c
@@ -1,21 +1,21 @@
 /*
  * filter registration
- * copyright (c) 2008 Vitor Sessak
+ * Copyright (c) 2008 Vitor Sessak
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -34,17 +34,45 @@ void avfilter_register_all(void)
         return;
     initialized = 1;
 
-    REGISTER_FILTER (ASPECT,      aspect,      vf);
+    REGISTER_FILTER (ANULL,       anull,       af);
+
+    REGISTER_FILTER (ANULLSRC,    anullsrc,    asrc);
+
+    REGISTER_FILTER (ANULLSINK,   anullsink,   asink);
+
+    REGISTER_FILTER (BLACKFRAME,  blackframe,  vf);
+    REGISTER_FILTER (COPY,        copy,        vf);
     REGISTER_FILTER (CROP,        crop,        vf);
+    REGISTER_FILTER (CROPDETECT,  cropdetect,  vf);
+    REGISTER_FILTER (DRAWBOX,     drawbox,     vf);
+    REGISTER_FILTER (FADE,        fade,        vf);
+    REGISTER_FILTER (FIFO,        fifo,        vf);
     REGISTER_FILTER (FORMAT,      format,      vf);
+    REGISTER_FILTER (FREI0R,      frei0r,      vf);
+    REGISTER_FILTER (GRADFUN,     gradfun,     vf);
+    REGISTER_FILTER (HFLIP,       hflip,       vf);
+    REGISTER_FILTER (HQDN3D,      hqdn3d,      vf);
     REGISTER_FILTER (NOFORMAT,    noformat,    vf);
     REGISTER_FILTER (NULL,        null,        vf);
-    REGISTER_FILTER (PIXELASPECT, pixelaspect, vf);
+    REGISTER_FILTER (OCV,         ocv,         vf);
+    REGISTER_FILTER (OVERLAY,     overlay,     vf);
+    REGISTER_FILTER (PAD,         pad,         vf);
+    REGISTER_FILTER (PIXDESCTEST, pixdesctest, vf);
     REGISTER_FILTER (SCALE,       scale,       vf);
+    REGISTER_FILTER (SETDAR,      setdar,      vf);
+    REGISTER_FILTER (SETPTS,      setpts,      vf);
+    REGISTER_FILTER (SETSAR,      setsar,      vf);
+    REGISTER_FILTER (SETTB,       settb,       vf);
     REGISTER_FILTER (SLICIFY,     slicify,     vf);
+    REGISTER_FILTER (TRANSPOSE,   transpose,   vf);
     REGISTER_FILTER (UNSHARP,     unsharp,     vf);
     REGISTER_FILTER (VFLIP,       vflip,       vf);
+    REGISTER_FILTER (YADIF,       yadif,       vf);
 
+    REGISTER_FILTER (BUFFER,      buffer,      vsrc);
+    REGISTER_FILTER (COLOR,       color,       vsrc);
+    REGISTER_FILTER (FREI0R,      frei0r_src,  vsrc);
+    REGISTER_FILTER (MOVIE,       movie,       vsrc);
     REGISTER_FILTER (NULLSRC,     nullsrc,     vsrc);
 
     REGISTER_FILTER (NULLSINK,    nullsink,    vsink);
diff --git a/libavfilter/asink_anullsink.c b/libavfilter/asink_anullsink.c
new file mode 100644
index 0000000..3a505e7
--- /dev/null
+++ b/libavfilter/asink_anullsink.c
@@ -0,0 +1,38 @@
+/*
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "avfilter.h"
+
+static void null_filter_samples(AVFilterLink *link, AVFilterBufferRef *samplesref) { }
+
+AVFilter avfilter_asink_anullsink = {
+    .name        = "anullsink",
+    .description = NULL_IF_CONFIG_SMALL("Do absolutely nothing with the input audio."),
+
+    .priv_size = 0,
+
+    .inputs    = (AVFilterPad[]) {
+        {
+            .name            = "default",
+            .type            = AVMEDIA_TYPE_AUDIO,
+            .filter_samples  = null_filter_samples,
+        },
+        { .name = NULL},
+    },
+    .outputs   = (AVFilterPad[]) {{ .name = NULL }},
+};
diff --git a/libavfilter/asrc_anullsrc.c b/libavfilter/asrc_anullsrc.c
new file mode 100644
index 0000000..dd671c5
--- /dev/null
+++ b/libavfilter/asrc_anullsrc.c
@@ -0,0 +1,96 @@
+/*
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * null audio source
+ */
+
+#include "avfilter.h"
+#include "libavutil/audioconvert.h"
+
+typedef struct {
+    int64_t channel_layout;
+    int64_t sample_rate;
+} ANullContext;
+
+static int init(AVFilterContext *ctx, const char *args, void *opaque)
+{
+    ANullContext *priv = ctx->priv;
+    char channel_layout_str[128] = "";
+
+    priv->sample_rate = 44100;
+    priv->channel_layout = AV_CH_LAYOUT_STEREO;
+
+    if (args)
+        sscanf(args, "%"PRId64":%s", &priv->sample_rate, channel_layout_str);
+
+    if (priv->sample_rate < 0) {
+        av_log(ctx, AV_LOG_ERROR, "Invalid negative sample rate: %"PRId64"\n", priv->sample_rate);
+        return AVERROR(EINVAL);
+    }
+
+    if (*channel_layout_str)
+        if (!(priv->channel_layout = av_get_channel_layout(channel_layout_str))
+            && sscanf(channel_layout_str, "%"PRId64, &priv->channel_layout) != 1) {
+            av_log(ctx, AV_LOG_ERROR, "Invalid value '%s' for channel layout\n",
+                   channel_layout_str);
+            return AVERROR(EINVAL);
+        }
+
+    return 0;
+}
+
+static int config_props(AVFilterLink *outlink)
+{
+    ANullContext *priv = outlink->src->priv;
+    char buf[128];
+    int chans_nb;
+
+    outlink->sample_rate = priv->sample_rate;
+    outlink->channel_layout = priv->channel_layout;
+
+    chans_nb = av_get_channel_layout_nb_channels(priv->channel_layout);
+    av_get_channel_layout_string(buf, sizeof(buf), chans_nb, priv->channel_layout);
+    av_log(outlink->src, AV_LOG_INFO,
+           "sample_rate:%"PRId64 " channel_layout:%"PRId64 " channel_layout_description:'%s'\n",
+           priv->sample_rate, priv->channel_layout, buf);
+
+    return 0;
+}
+
+static int request_frame(AVFilterLink *link)
+{
+    return -1;
+}
+
+AVFilter avfilter_asrc_anullsrc = {
+    .name        = "anullsrc",
+    .description = NULL_IF_CONFIG_SMALL("Null audio source, never return audio frames."),
+
+    .init        = init,
+    .priv_size   = sizeof(ANullContext),
+
+    .inputs      = (AVFilterPad[]) {{ .name = NULL}},
+
+    .outputs     = (AVFilterPad[]) {{ .name = "default",
+                                      .type = AVMEDIA_TYPE_AUDIO,
+                                      .config_props = config_props,
+                                      .request_frame = request_frame, },
+                                    { .name = NULL}},
+};
diff --git a/libavfilter/avfilter.c b/libavfilter/avfilter.c
index 3ed59d7..135b9ff 100644
--- a/libavfilter/avfilter.c
+++ b/libavfilter/avfilter.c
@@ -1,29 +1,32 @@
 /*
  * filter layer
- * copyright (c) 2007 Bobby Bingham
+ * Copyright (c) 2007 Bobby Bingham
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 /* #define DEBUG */
 
-#include "libavcodec/imgconvert.h"
 #include "libavutil/pixdesc.h"
+#include "libavutil/rational.h"
+#include "libavutil/audioconvert.h"
+#include "libavutil/imgutils.h"
 #include "avfilter.h"
+#include "internal.h"
 
 unsigned avfilter_version(void) {
     return LIBAVFILTER_VERSION_INT;
@@ -31,32 +34,49 @@ unsigned avfilter_version(void) {
 
 const char *avfilter_configuration(void)
 {
-    return FFMPEG_CONFIGURATION;
+    return LIBAV_CONFIGURATION;
 }
 
 const char *avfilter_license(void)
 {
 #define LICENSE_PREFIX "libavfilter license: "
-    return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1;
+    return LICENSE_PREFIX LIBAV_LICENSE + sizeof(LICENSE_PREFIX) - 1;
 }
 
-/** helper macros to get the in/out pad on the dst/src filter */
-#define link_dpad(link)     link->dst-> input_pads[link->dstpad]
-#define link_spad(link)     link->src->output_pads[link->srcpad]
-
-AVFilterPicRef *avfilter_ref_pic(AVFilterPicRef *ref, int pmask)
+AVFilterBufferRef *avfilter_ref_buffer(AVFilterBufferRef *ref, int pmask)
 {
-    AVFilterPicRef *ret = av_malloc(sizeof(AVFilterPicRef));
+    AVFilterBufferRef *ret = av_malloc(sizeof(AVFilterBufferRef));
+    if (!ret)
+        return NULL;
     *ret = *ref;
+    if (ref->type == AVMEDIA_TYPE_VIDEO) {
+        ret->video = av_malloc(sizeof(AVFilterBufferRefVideoProps));
+        if (!ret->video) {
+            av_free(ret);
+            return NULL;
+        }
+        *ret->video = *ref->video;
+    } else if (ref->type == AVMEDIA_TYPE_AUDIO) {
+        ret->audio = av_malloc(sizeof(AVFilterBufferRefAudioProps));
+        if (!ret->audio) {
+            av_free(ret);
+            return NULL;
+        }
+        *ret->audio = *ref->audio;
+    }
     ret->perms &= pmask;
-    ret->pic->refcount ++;
+    ret->buf->refcount ++;
     return ret;
 }
 
-void avfilter_unref_pic(AVFilterPicRef *ref)
+void avfilter_unref_buffer(AVFilterBufferRef *ref)
 {
-    if(!(--ref->pic->refcount))
-        ref->pic->free(ref->pic);
+    if (!ref)
+        return;
+    if (!(--ref->buf->refcount))
+        ref->buf->free(ref->buf);
+    av_free(ref->video);
+    av_free(ref->audio);
     av_free(ref);
 }
 
@@ -75,10 +95,10 @@ void avfilter_insert_pad(unsigned idx, unsigned *count, size_t padidx_off,
     memcpy(*pads+idx, newpad, sizeof(AVFilterPad));
     (*links)[idx] = NULL;
 
-    (*count) ++;
-    for(i = idx+1; i < *count; i ++)
-        if(*links[i])
-            (*(unsigned *)((uint8_t *) *links[i] + padidx_off)) ++;
+    (*count)++;
+    for (i = idx+1; i < *count; i++)
+        if (*links[i])
+            (*(unsigned *)((uint8_t *) *links[i] + padidx_off))++;
 }
 
 int avfilter_link(AVFilterContext *src, unsigned srcpad,
@@ -86,46 +106,58 @@ int avfilter_link(AVFilterContext *src, unsigned srcpad,
 {
     AVFilterLink *link;
 
-    if(src->output_count <= srcpad || dst->input_count <= dstpad ||
-       src->outputs[srcpad]        || dst->inputs[dstpad])
+    if (src->output_count <= srcpad || dst->input_count <= dstpad ||
+        src->outputs[srcpad]        || dst->inputs[dstpad])
         return -1;
 
+    if (src->output_pads[srcpad].type != dst->input_pads[dstpad].type) {
+        av_log(src, AV_LOG_ERROR,
+               "Media type mismatch between the '%s' filter output pad %d and the '%s' filter input pad %d\n",
+               src->name, srcpad, dst->name, dstpad);
+        return AVERROR(EINVAL);
+    }
+
     src->outputs[srcpad] =
     dst-> inputs[dstpad] = link = av_mallocz(sizeof(AVFilterLink));
 
     link->src     = src;
     link->dst     = dst;
-    link->srcpad  = srcpad;
-    link->dstpad  = dstpad;
-    link->format  = PIX_FMT_NONE;
+    link->srcpad  = &src->output_pads[srcpad];
+    link->dstpad  = &dst->input_pads[dstpad];
+    link->type    = src->output_pads[srcpad].type;
+    assert(PIX_FMT_NONE == -1 && AV_SAMPLE_FMT_NONE == -1);
+    link->format  = -1;
 
     return 0;
 }
 
 int avfilter_insert_filter(AVFilterLink *link, AVFilterContext *filt,
-                           unsigned in, unsigned out)
+                           unsigned filt_srcpad_idx, unsigned filt_dstpad_idx)
 {
+    int ret;
+    unsigned dstpad_idx = link->dstpad - link->dst->input_pads;
+
     av_log(link->dst, AV_LOG_INFO, "auto-inserting filter '%s' "
            "between the filter '%s' and the filter '%s'\n",
            filt->name, link->src->name, link->dst->name);
 
-    link->dst->inputs[link->dstpad] = NULL;
-    if(avfilter_link(filt, out, link->dst, link->dstpad)) {
+    link->dst->inputs[dstpad_idx] = NULL;
+    if ((ret = avfilter_link(filt, filt_dstpad_idx, link->dst, dstpad_idx)) < 0) {
         /* failed to link output filter to new filter */
-        link->dst->inputs[link->dstpad] = link;
-        return -1;
+        link->dst->inputs[dstpad_idx] = link;
+        return ret;
     }
 
     /* re-hookup the link to the new destination filter we inserted */
     link->dst = filt;
-    link->dstpad = in;
-    filt->inputs[in] = link;
+    link->dstpad = &filt->input_pads[filt_srcpad_idx];
+    filt->inputs[filt_srcpad_idx] = link;
 
-    /* if any information on supported colorspaces already exists on the
+    /* if any information on supported media formats already exists on the
      * link, we need to preserve that */
-    if(link->out_formats)
+    if (link->out_formats)
         avfilter_formats_changeref(&link->out_formats,
-                                   &filt->outputs[out]->out_formats);
+                                   &filt->outputs[filt_dstpad_idx]->out_formats);
 
     return 0;
 }
@@ -134,13 +166,14 @@ int avfilter_config_links(AVFilterContext *filter)
 {
     int (*config_link)(AVFilterLink *);
     unsigned i;
+    int ret;
 
-    for(i = 0; i < filter->input_count; i ++) {
+    for (i = 0; i < filter->input_count; i ++) {
         AVFilterLink *link = filter->inputs[i];
 
-        if(!link) continue;
+        if (!link) continue;
 
-        switch(link->init_state) {
+        switch (link->init_state) {
         case AVLINK_INIT:
             continue;
         case AVLINK_STARTINIT:
@@ -149,17 +182,31 @@ int avfilter_config_links(AVFilterContext *filter)
         case AVLINK_UNINIT:
             link->init_state = AVLINK_STARTINIT;
 
-            if(avfilter_config_links(link->src))
-                return -1;
+            if ((ret = avfilter_config_links(link->src)) < 0)
+                return ret;
 
-            if(!(config_link = link_spad(link).config_props))
+            if (!(config_link = link->srcpad->config_props))
                 config_link  = avfilter_default_config_output_link;
-            if(config_link(link))
-                return -1;
+            if ((ret = config_link(link)) < 0)
+                return ret;
 
-            if((config_link = link_dpad(link).config_props))
-                if(config_link(link))
-                    return -1;
+            if (link->time_base.num == 0 && link->time_base.den == 0)
+                link->time_base = link->src && link->src->input_count ?
+                    link->src->inputs[0]->time_base : AV_TIME_BASE_Q;
+
+            if (link->sample_aspect_ratio.num == 0 && link->sample_aspect_ratio.den == 0)
+                link->sample_aspect_ratio = link->src->input_count ?
+                    link->src->inputs[0]->sample_aspect_ratio : (AVRational){1,1};
+
+            if (link->sample_rate == 0 && link->src && link->src->input_count)
+                link->sample_rate = link->src->inputs[0]->sample_rate;
+
+            if (link->channel_layout == 0 && link->src && link->src->input_count)
+                link->channel_layout = link->src->inputs[0]->channel_layout;
+
+            if ((config_link = link->dstpad->config_props))
+                if ((ret = config_link(link)) < 0)
+                    return ret;
 
             link->init_state = AVLINK_INIT;
         }
@@ -168,69 +215,173 @@ int avfilter_config_links(AVFilterContext *filter)
     return 0;
 }
 
-static void dprintf_picref(void *ctx, AVFilterPicRef *picref, int end)
+static char *ff_get_ref_perms_string(char *buf, size_t buf_size, int perms)
 {
-    dprintf(ctx,
-            "picref[%p data[%p, %p, %p, %p] linesize[%d, %d, %d, %d] pts:%"PRId64" pos:%"PRId64" a:%d/%d s:%dx%d]%s",
-            picref,
-            picref->data    [0], picref->data    [1], picref->data    [2], picref->data    [3],
-            picref->linesize[0], picref->linesize[1], picref->linesize[2], picref->linesize[3],
-            picref->pts, picref->pos,
-            picref->pixel_aspect.num, picref->pixel_aspect.den, picref->w, picref->h,
-            end ? "\n" : "");
+    snprintf(buf, buf_size, "%s%s%s%s%s%s",
+             perms & AV_PERM_READ      ? "r" : "",
+             perms & AV_PERM_WRITE     ? "w" : "",
+             perms & AV_PERM_PRESERVE  ? "p" : "",
+             perms & AV_PERM_REUSE     ? "u" : "",
+             perms & AV_PERM_REUSE2    ? "U" : "",
+             perms & AV_PERM_NEG_LINESIZES ? "n" : "");
+    return buf;
 }
 
-static void dprintf_link(void *ctx, AVFilterLink *link, int end)
+static void ff_dlog_ref(void *ctx, AVFilterBufferRef *ref, int end)
 {
-    dprintf(ctx,
-            "link[%p s:%dx%d fmt:%-16s %-16s->%-16s]%s",
-            link, link->w, link->h,
-            av_pix_fmt_descriptors[link->format].name,
-            link->src ? link->src->filter->name : "",
-            link->dst ? link->dst->filter->name : "",
-            end ? "\n" : "");
+    av_unused char buf[16];
+    av_dlog(ctx,
+            "ref[%p buf:%p refcount:%d perms:%s data:%p linesize[%d, %d, %d, %d] pts:%"PRId64" pos:%"PRId64,
+            ref, ref->buf, ref->buf->refcount, ff_get_ref_perms_string(buf, sizeof(buf), ref->perms), ref->data[0],
+            ref->linesize[0], ref->linesize[1], ref->linesize[2], ref->linesize[3],
+            ref->pts, ref->pos);
+
+    if (ref->video) {
+        av_dlog(ctx, " a:%d/%d s:%dx%d i:%c",
+                ref->video->pixel_aspect.num, ref->video->pixel_aspect.den,
+                ref->video->w, ref->video->h,
+                !ref->video->interlaced     ? 'P' :         /* Progressive  */
+                ref->video->top_field_first ? 'T' : 'B');   /* Top / Bottom */
+    }
+    if (ref->audio) {
+        av_dlog(ctx, " cl:%"PRId64"d sn:%d s:%d sr:%d p:%d",
+                ref->audio->channel_layout,
+                ref->audio->nb_samples,
+                ref->audio->size,
+                ref->audio->sample_rate,
+                ref->audio->planar);
+    }
+
+    av_dlog(ctx, "]%s", end ? "\n" : "");
 }
 
-#define DPRINTF_START(ctx, func) dprintf(NULL, "%-16s: ", #func)
+static void ff_dlog_link(void *ctx, AVFilterLink *link, int end)
+{
+    if (link->type == AVMEDIA_TYPE_VIDEO) {
+        av_dlog(ctx,
+                "link[%p s:%dx%d fmt:%-16s %-16s->%-16s]%s",
+                link, link->w, link->h,
+                av_pix_fmt_descriptors[link->format].name,
+                link->src ? link->src->filter->name : "",
+                link->dst ? link->dst->filter->name : "",
+                end ? "\n" : "");
+    } else {
+        char buf[128];
+        av_get_channel_layout_string(buf, sizeof(buf), -1, link->channel_layout);
+
+        av_dlog(ctx,
+                "link[%p r:%"PRId64" cl:%s fmt:%-16s %-16s->%-16s]%s",
+                link, link->sample_rate, buf,
+                av_get_sample_fmt_name(link->format),
+                link->src ? link->src->filter->name : "",
+                link->dst ? link->dst->filter->name : "",
+                end ? "\n" : "");
+    }
+}
+
+#define FF_DPRINTF_START(ctx, func) av_dlog(NULL, "%-16s: ", #func)
 
-AVFilterPicRef *avfilter_get_video_buffer(AVFilterLink *link, int perms, int w, int h)
+AVFilterBufferRef *avfilter_get_video_buffer(AVFilterLink *link, int perms, int w, int h)
 {
-    AVFilterPicRef *ret = NULL;
+    AVFilterBufferRef *ret = NULL;
 
-    DPRINTF_START(NULL, get_video_buffer); dprintf_link(NULL, link, 0); dprintf(NULL, " perms:%d w:%d h:%d\n", perms, w, h);
+    av_unused char buf[16];
+    FF_DPRINTF_START(NULL, get_video_buffer); ff_dlog_link(NULL, link, 0);
+    av_dlog(NULL, " perms:%s w:%d h:%d\n", ff_get_ref_perms_string(buf, sizeof(buf), perms), w, h);
 
-    if(link_dpad(link).get_video_buffer)
-        ret = link_dpad(link).get_video_buffer(link, perms, w, h);
+    if (link->dstpad->get_video_buffer)
+        ret = link->dstpad->get_video_buffer(link, perms, w, h);
 
-    if(!ret)
+    if (!ret)
         ret = avfilter_default_get_video_buffer(link, perms, w, h);
 
-    DPRINTF_START(NULL, get_video_buffer); dprintf_link(NULL, link, 0); dprintf(NULL, " returning "); dprintf_picref(NULL, ret, 1);
+    if (ret)
+        ret->type = AVMEDIA_TYPE_VIDEO;
+
+    FF_DPRINTF_START(NULL, get_video_buffer); ff_dlog_link(NULL, link, 0); av_dlog(NULL, " returning "); ff_dlog_ref(NULL, ret, 1);
+
+    return ret;
+}
+
+AVFilterBufferRef *
+avfilter_get_video_buffer_ref_from_arrays(uint8_t *data[4], int linesize[4], int perms,
+                                          int w, int h, enum PixelFormat format)
+{
+    AVFilterBuffer *pic = av_mallocz(sizeof(AVFilterBuffer));
+    AVFilterBufferRef *picref = av_mallocz(sizeof(AVFilterBufferRef));
+
+    if (!pic || !picref)
+        goto fail;
+
+    picref->buf = pic;
+    picref->buf->free = ff_avfilter_default_free_buffer;
+    if (!(picref->video = av_mallocz(sizeof(AVFilterBufferRefVideoProps))))
+        goto fail;
+
+    pic->w = picref->video->w = w;
+    pic->h = picref->video->h = h;
+
+    /* make sure the buffer gets read permission or it's useless for output */
+    picref->perms = perms | AV_PERM_READ;
+
+    pic->refcount = 1;
+    picref->type = AVMEDIA_TYPE_VIDEO;
+    pic->format = picref->format = format;
+
+    memcpy(pic->data,        data,          sizeof(pic->data));
+    memcpy(pic->linesize,    linesize,      sizeof(pic->linesize));
+    memcpy(picref->data,     pic->data,     sizeof(picref->data));
+    memcpy(picref->linesize, pic->linesize, sizeof(picref->linesize));
+
+    return picref;
+
+fail:
+    if (picref && picref->video)
+        av_free(picref->video);
+    av_free(picref);
+    av_free(pic);
+    return NULL;
+}
+
+AVFilterBufferRef *avfilter_get_audio_buffer(AVFilterLink *link, int perms,
+                                             enum AVSampleFormat sample_fmt, int size,
+                                             int64_t channel_layout, int planar)
+{
+    AVFilterBufferRef *ret = NULL;
+
+    if (link->dstpad->get_audio_buffer)
+        ret = link->dstpad->get_audio_buffer(link, perms, sample_fmt, size, channel_layout, planar);
+
+    if (!ret)
+        ret = avfilter_default_get_audio_buffer(link, perms, sample_fmt, size, channel_layout, planar);
+
+    if (ret)
+        ret->type = AVMEDIA_TYPE_AUDIO;
 
     return ret;
 }
 
 int avfilter_request_frame(AVFilterLink *link)
 {
-    DPRINTF_START(NULL, request_frame); dprintf_link(NULL, link, 1);
+    FF_DPRINTF_START(NULL, request_frame); ff_dlog_link(NULL, link, 1);
 
-    if(link_spad(link).request_frame)
-        return link_spad(link).request_frame(link);
-    else if(link->src->inputs[0])
+    if (link->srcpad->request_frame)
+        return link->srcpad->request_frame(link);
+    else if (link->src->inputs[0])
         return avfilter_request_frame(link->src->inputs[0]);
     else return -1;
 }
 
 int avfilter_poll_frame(AVFilterLink *link)
 {
-    int i, min=INT_MAX;
+    int i, min = INT_MAX;
 
-    if(link_spad(link).poll_frame)
-        return link_spad(link).poll_frame(link);
+    if (link->srcpad->poll_frame)
+        return link->srcpad->poll_frame(link);
 
-    for (i=0; i<link->src->input_count; i++) {
+    for (i = 0; i < link->src->input_count; i++) {
         int val;
-        if(!link->src->inputs[i])
+        if (!link->src->inputs[i])
             return -1;
         val = avfilter_poll_frame(link->src->inputs[i]);
         min = FFMIN(min, val);
@@ -241,54 +392,51 @@ int avfilter_poll_frame(AVFilterLink *link)
 
 /* XXX: should we do the duplicating of the picture ref here, instead of
  * forcing the source filter to do it? */
-void avfilter_start_frame(AVFilterLink *link, AVFilterPicRef *picref)
+void avfilter_start_frame(AVFilterLink *link, AVFilterBufferRef *picref)
 {
-    void (*start_frame)(AVFilterLink *, AVFilterPicRef *);
-    AVFilterPad *dst = &link_dpad(link);
+    void (*start_frame)(AVFilterLink *, AVFilterBufferRef *);
+    AVFilterPad *dst = link->dstpad;
+    int perms = picref->perms;
 
-    DPRINTF_START(NULL, start_frame); dprintf_link(NULL, link, 0); dprintf(NULL, " "); dprintf_picref(NULL, picref, 1);
+    FF_DPRINTF_START(NULL, start_frame); ff_dlog_link(NULL, link, 0); av_dlog(NULL, " "); ff_dlog_ref(NULL, picref, 1);
 
-    if(!(start_frame = dst->start_frame))
+    if (!(start_frame = dst->start_frame))
         start_frame = avfilter_default_start_frame;
 
+    if (picref->linesize[0] < 0)
+        perms |= AV_PERM_NEG_LINESIZES;
     /* prepare to copy the picture if it has insufficient permissions */
-    if((dst->min_perms & picref->perms) != dst->min_perms ||
-        dst->rej_perms & picref->perms) {
-        /*
-        av_log(link->dst, AV_LOG_INFO,
+    if ((dst->min_perms & perms) != dst->min_perms || dst->rej_perms & perms) {
+        av_log(link->dst, AV_LOG_DEBUG,
                 "frame copy needed (have perms %x, need %x, reject %x)\n",
                 picref->perms,
-                link_dpad(link).min_perms, link_dpad(link).rej_perms);
-        */
-
-        link->cur_pic = avfilter_default_get_video_buffer(link, dst->min_perms, link->w, link->h);
-        link->srcpic = picref;
-        link->cur_pic->pts = link->srcpic->pts;
-        link->cur_pic->pos = link->srcpic->pos;
-        link->cur_pic->pixel_aspect = link->srcpic->pixel_aspect;
+                link->dstpad->min_perms, link->dstpad->rej_perms);
+
+        link->cur_buf = avfilter_get_video_buffer(link, dst->min_perms, link->w, link->h);
+        link->src_buf = picref;
+        avfilter_copy_buffer_ref_props(link->cur_buf, link->src_buf);
     }
     else
-        link->cur_pic = picref;
+        link->cur_buf = picref;
 
-    start_frame(link, link->cur_pic);
+    start_frame(link, link->cur_buf);
 }
 
 void avfilter_end_frame(AVFilterLink *link)
 {
     void (*end_frame)(AVFilterLink *);
 
-    if(!(end_frame = link_dpad(link).end_frame))
+    if (!(end_frame = link->dstpad->end_frame))
         end_frame = avfilter_default_end_frame;
 
     end_frame(link);
 
     /* unreference the source picture if we're feeding the destination filter
      * a copied version dues to permission issues */
-    if(link->srcpic) {
-        avfilter_unref_pic(link->srcpic);
-        link->srcpic = NULL;
+    if (link->src_buf) {
+        avfilter_unref_buffer(link->src_buf);
+        link->src_buf = NULL;
     }
-
 }
 
 void avfilter_draw_slice(AVFilterLink *link, int y, int h, int slice_dir)
@@ -297,41 +445,77 @@ void avfilter_draw_slice(AVFilterLink *link, int y, int h, int slice_dir)
     int i, j, vsub;
     void (*draw_slice)(AVFilterLink *, int, int, int);
 
-    DPRINTF_START(NULL, draw_slice); dprintf_link(NULL, link, 0); dprintf(NULL, " y:%d h:%d dir:%d\n", y, h, slice_dir);
+    FF_DPRINTF_START(NULL, draw_slice); ff_dlog_link(NULL, link, 0); av_dlog(NULL, " y:%d h:%d dir:%d\n", y, h, slice_dir);
 
     /* copy the slice if needed for permission reasons */
-    if(link->srcpic) {
+    if (link->src_buf) {
         vsub = av_pix_fmt_descriptors[link->format].log2_chroma_h;
 
-        for(i = 0; i < 4; i ++) {
-            if(link->srcpic->data[i]) {
-                src[i] = link->srcpic-> data[i] +
-                    (y >> (i==0 ? 0 : vsub)) * link->srcpic-> linesize[i];
-                dst[i] = link->cur_pic->data[i] +
-                    (y >> (i==0 ? 0 : vsub)) * link->cur_pic->linesize[i];
+        for (i = 0; i < 4; i++) {
+            if (link->src_buf->data[i]) {
+                src[i] = link->src_buf-> data[i] +
+                    (y >> (i==1 || i==2 ? vsub : 0)) * link->src_buf-> linesize[i];
+                dst[i] = link->cur_buf->data[i] +
+                    (y >> (i==1 || i==2 ? vsub : 0)) * link->cur_buf->linesize[i];
             } else
                 src[i] = dst[i] = NULL;
         }
 
-        for(i = 0; i < 4; i ++) {
+        for (i = 0; i < 4; i++) {
             int planew =
-                ff_get_plane_bytewidth(link->format, link->cur_pic->w, i);
+                av_image_get_linesize(link->format, link->cur_buf->video->w, i);
 
-            if(!src[i]) continue;
+            if (!src[i]) continue;
 
-            for(j = 0; j < h >> (i==0 ? 0 : vsub); j ++) {
+            for (j = 0; j < h >> (i==1 || i==2 ? vsub : 0); j++) {
                 memcpy(dst[i], src[i], planew);
-                src[i] += link->srcpic ->linesize[i];
-                dst[i] += link->cur_pic->linesize[i];
+                src[i] += link->src_buf->linesize[i];
+                dst[i] += link->cur_buf->linesize[i];
             }
         }
     }
 
-    if(!(draw_slice = link_dpad(link).draw_slice))
+    if (!(draw_slice = link->dstpad->draw_slice))
         draw_slice = avfilter_default_draw_slice;
     draw_slice(link, y, h, slice_dir);
 }
 
+void avfilter_filter_samples(AVFilterLink *link, AVFilterBufferRef *samplesref)
+{
+    void (*filter_samples)(AVFilterLink *, AVFilterBufferRef *);
+    AVFilterPad *dst = link->dstpad;
+
+    FF_DPRINTF_START(NULL, filter_samples); ff_dlog_link(NULL, link, 1);
+
+    if (!(filter_samples = dst->filter_samples))
+        filter_samples = avfilter_default_filter_samples;
+
+    /* prepare to copy the samples if the buffer has insufficient permissions */
+    if ((dst->min_perms & samplesref->perms) != dst->min_perms ||
+        dst->rej_perms & samplesref->perms) {
+
+        av_log(link->dst, AV_LOG_DEBUG,
+               "Copying audio data in avfilter (have perms %x, need %x, reject %x)\n",
+               samplesref->perms, link->dstpad->min_perms, link->dstpad->rej_perms);
+
+        link->cur_buf = avfilter_default_get_audio_buffer(link, dst->min_perms,
+                                                          samplesref->format,
+                                                          samplesref->audio->size,
+                                                          samplesref->audio->channel_layout,
+                                                          samplesref->audio->planar);
+        link->cur_buf->pts                = samplesref->pts;
+        link->cur_buf->audio->sample_rate = samplesref->audio->sample_rate;
+
+        /* Copy actual data into new samples buffer */
+        memcpy(link->cur_buf->data[0], samplesref->data[0], samplesref->audio->size);
+
+        avfilter_unref_buffer(samplesref);
+    } else
+        link->cur_buf = samplesref;
+
+    filter_samples(link, link->cur_buf);
+}
+
 #define MAX_REGISTERED_AVFILTERS_NB 64
 
 static AVFilter *registered_avfilters[MAX_REGISTERED_AVFILTERS_NB + 1];
@@ -390,12 +574,13 @@ static const AVClass avfilter_class = {
     LIBAVUTIL_VERSION_INT,
 };
 
-AVFilterContext *avfilter_open(AVFilter *filter, const char *inst_name)
+int avfilter_open(AVFilterContext **filter_ctx, AVFilter *filter, const char *inst_name)
 {
     AVFilterContext *ret;
+    *filter_ctx = NULL;
 
     if (!filter)
-        return 0;
+        return AVERROR(EINVAL);
 
     ret = av_mallocz(sizeof(AVFilterContext));
 
@@ -418,25 +603,35 @@ AVFilterContext *avfilter_open(AVFilter *filter, const char *inst_name)
         ret->outputs      = av_mallocz(sizeof(AVFilterLink*) * ret->output_count);
     }
 
-    return ret;
+    *filter_ctx = ret;
+    return 0;
 }
 
-void avfilter_destroy(AVFilterContext *filter)
+void avfilter_free(AVFilterContext *filter)
 {
     int i;
+    AVFilterLink *link;
 
-    if(filter->filter->uninit)
+    if (filter->filter->uninit)
         filter->filter->uninit(filter);
 
-    for(i = 0; i < filter->input_count; i ++) {
-        if(filter->inputs[i])
-            filter->inputs[i]->src->outputs[filter->inputs[i]->srcpad] = NULL;
-        av_freep(&filter->inputs[i]);
+    for (i = 0; i < filter->input_count; i++) {
+        if ((link = filter->inputs[i])) {
+            if (link->src)
+                link->src->outputs[link->srcpad - link->src->output_pads] = NULL;
+            avfilter_formats_unref(&link->in_formats);
+            avfilter_formats_unref(&link->out_formats);
+        }
+        av_freep(&link);
     }
-    for(i = 0; i < filter->output_count; i ++) {
-        if(filter->outputs[i])
-            filter->outputs[i]->dst->inputs[filter->outputs[i]->dstpad] = NULL;
-        av_freep(&filter->outputs[i]);
+    for (i = 0; i < filter->output_count; i++) {
+        if ((link = filter->outputs[i])) {
+            if (link->dst)
+                link->dst->inputs[link->dstpad - link->dst->input_pads] = NULL;
+            avfilter_formats_unref(&link->in_formats);
+            avfilter_formats_unref(&link->out_formats);
+        }
+        av_freep(&link);
     }
 
     av_freep(&filter->name);
@@ -452,7 +647,7 @@ int avfilter_init_filter(AVFilterContext *filter, const char *args, void *opaque
 {
     int ret=0;
 
-    if(filter->filter->init)
+    if (filter->filter->init)
         ret = filter->filter->init(filter, args, opaque);
     return ret;
 }
diff --git a/libavfilter/avfilter.h b/libavfilter/avfilter.h
index 214b8d4..7505c2e 100644
--- a/libavfilter/avfilter.h
+++ b/libavfilter/avfilter.h
@@ -1,21 +1,21 @@
 /*
  * filter layer
- * copyright (c) 2007 Bobby Bingham
+ * Copyright (c) 2007 Bobby Bingham
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -23,9 +23,10 @@
 #define AVFILTER_AVFILTER_H
 
 #include "libavutil/avutil.h"
+#include "libavutil/samplefmt.h"
 
-#define LIBAVFILTER_VERSION_MAJOR  1
-#define LIBAVFILTER_VERSION_MINOR 19
+#define LIBAVFILTER_VERSION_MAJOR  2
+#define LIBAVFILTER_VERSION_MINOR  0
 #define LIBAVFILTER_VERSION_MICRO  0
 
 #define LIBAVFILTER_VERSION_INT AV_VERSION_INT(LIBAVFILTER_VERSION_MAJOR, \
@@ -37,20 +38,19 @@
 #define LIBAVFILTER_BUILD       LIBAVFILTER_VERSION_INT
 
 #include <stddef.h>
-#include "libavcodec/avcodec.h"
 
 /**
- * Returns the LIBAVFILTER_VERSION_INT constant.
+ * Return the LIBAVFILTER_VERSION_INT constant.
  */
 unsigned avfilter_version(void);
 
 /**
- * Returns the libavfilter build-time configuration.
+ * Return the libavfilter build-time configuration.
  */
 const char *avfilter_configuration(void);
 
 /**
- * Returns the libavfilter license.
+ * Return the libavfilter license.
  */
 const char *avfilter_license(void);
 
@@ -59,80 +59,126 @@ typedef struct AVFilterContext AVFilterContext;
 typedef struct AVFilterLink    AVFilterLink;
 typedef struct AVFilterPad     AVFilterPad;
 
-/* TODO: look for other flags which may be useful in this structure (interlace
- * flags, etc)
- */
 /**
- * A reference-counted picture data type used by the filter system. Filters
+ * A reference-counted buffer data type used by the filter system. Filters
  * should not store pointers to this structure directly, but instead use the
- * AVFilterPicRef structure below.
+ * AVFilterBufferRef structure below.
  */
-typedef struct AVFilterPic
-{
-    uint8_t *data[4];           ///< picture data for each plane
-    int linesize[4];            ///< number of bytes per line
-    enum PixelFormat format;    ///< colorspace
+typedef struct AVFilterBuffer {
+    uint8_t *data[8];           ///< buffer data for each plane/channel
+    int linesize[8];            ///< number of bytes per line
 
-    unsigned refcount;          ///< number of references to this image
+    unsigned refcount;          ///< number of references to this buffer
 
     /** private data to be used by a custom free function */
     void *priv;
     /**
-     * A pointer to the function to deallocate this image if the default
+     * A pointer to the function to deallocate this buffer if the default
      * function is not sufficient. This could, for example, add the memory
      * back into a memory pool to be reused later without the overhead of
      * reallocating it from scratch.
      */
-    void (*free)(struct AVFilterPic *pic);
+    void (*free)(struct AVFilterBuffer *buf);
+
+    int format;                 ///< media format
+    int w, h;                   ///< width and height of the allocated buffer
+} AVFilterBuffer;
+
+#define AV_PERM_READ     0x01   ///< can read from the buffer
+#define AV_PERM_WRITE    0x02   ///< can write to the buffer
+#define AV_PERM_PRESERVE 0x04   ///< nobody else can overwrite the buffer
+#define AV_PERM_REUSE    0x08   ///< can output the buffer multiple times, with the same contents each time
+#define AV_PERM_REUSE2   0x10   ///< can output the buffer multiple times, modified each time
+#define AV_PERM_NEG_LINESIZES 0x20  ///< the buffer requested can have negative linesizes
 
-    int w, h;                  ///< width and height of the allocated buffer
-} AVFilterPic;
+/**
+ * Audio specific properties in a reference to an AVFilterBuffer. Since
+ * AVFilterBufferRef is common to different media formats, audio specific
+ * per reference properties must be separated out.
+ */
+typedef struct AVFilterBufferRefAudioProps {
+    int64_t channel_layout;     ///< channel layout of audio buffer
+    int nb_samples;             ///< number of audio samples
+    int size;                   ///< audio buffer size
+    uint32_t sample_rate;       ///< audio buffer sample rate
+    int planar;                 ///< audio buffer - planar or packed
+} AVFilterBufferRefAudioProps;
 
 /**
- * A reference to an AVFilterPic. Since filters can manipulate the origin of
- * a picture to, for example, crop image without any memcpy, the picture origin
+ * Video specific properties in a reference to an AVFilterBuffer. Since
+ * AVFilterBufferRef is common to different media formats, video specific
+ * per reference properties must be separated out.
+ */
+typedef struct AVFilterBufferRefVideoProps {
+    int w;                      ///< image width
+    int h;                      ///< image height
+    AVRational pixel_aspect;    ///< pixel aspect ratio
+    int interlaced;             ///< is frame interlaced
+    int top_field_first;        ///< field order
+} AVFilterBufferRefVideoProps;
+
+/**
+ * A reference to an AVFilterBuffer. Since filters can manipulate the origin of
+ * a buffer to, for example, crop image without any memcpy, the buffer origin
  * and dimensions are per-reference properties. Linesize is also useful for
  * image flipping, frame to field filters, etc, and so is also per-reference.
  *
  * TODO: add anything necessary for frame reordering
  */
-typedef struct AVFilterPicRef
-{
-    AVFilterPic *pic;           ///< the picture that this is a reference to
-    uint8_t *data[4];           ///< picture data for each plane
-    int linesize[4];            ///< number of bytes per line
-    int w;                      ///< image width
-    int h;                      ///< image height
+typedef struct AVFilterBufferRef {
+    AVFilterBuffer *buf;        ///< the buffer that this is a reference to
+    uint8_t *data[8];           ///< picture/audio data for each plane
+    int linesize[8];            ///< number of bytes per line
+    int format;                 ///< media format
 
-    int64_t pts;                ///< presentation timestamp in units of 1/AV_TIME_BASE
+    /**
+     * presentation timestamp. The time unit may change during
+     * filtering, as it is specified in the link and the filter code
+     * may need to rescale the PTS accordingly.
+     */
+    int64_t pts;
     int64_t pos;                ///< byte position in stream, -1 if unknown
 
-    AVRational pixel_aspect;    ///< pixel aspect ratio
+    int perms;                  ///< permissions, see the AV_PERM_* flags
 
-    int perms;                  ///< permissions
-#define AV_PERM_READ     0x01   ///< can read from the buffer
-#define AV_PERM_WRITE    0x02   ///< can write to the buffer
-#define AV_PERM_PRESERVE 0x04   ///< nobody else can overwrite the buffer
-#define AV_PERM_REUSE    0x08   ///< can output the buffer multiple times, with the same contents each time
-#define AV_PERM_REUSE2   0x10   ///< can output the buffer multiple times, modified each time
-} AVFilterPicRef;
+    enum AVMediaType type;      ///< media type of buffer data
+    AVFilterBufferRefVideoProps *video; ///< video buffer specific properties
+    AVFilterBufferRefAudioProps *audio; ///< audio buffer specific properties
+} AVFilterBufferRef;
+
+/**
+ * Copy properties of src to dst, without copying the actual data
+ */
+static inline void avfilter_copy_buffer_ref_props(AVFilterBufferRef *dst, AVFilterBufferRef *src)
+{
+    // copy common properties
+    dst->pts             = src->pts;
+    dst->pos             = src->pos;
+
+    switch (src->type) {
+    case AVMEDIA_TYPE_VIDEO: *dst->video = *src->video; break;
+    case AVMEDIA_TYPE_AUDIO: *dst->audio = *src->audio; break;
+    }
+}
 
 /**
- * Adds a new reference to a picture.
- * @param ref   an existing reference to the picture
+ * Add a new reference to a buffer.
+ *
+ * @param ref   an existing reference to the buffer
  * @param pmask a bitmask containing the allowable permissions in the new
  *              reference
- * @return      a new reference to the picture with the same properties as the
+ * @return      a new reference to the buffer with the same properties as the
  *              old, excluding any permissions denied by pmask
  */
-AVFilterPicRef *avfilter_ref_pic(AVFilterPicRef *ref, int pmask);
+AVFilterBufferRef *avfilter_ref_buffer(AVFilterBufferRef *ref, int pmask);
 
 /**
- * Removes a reference to a picture. If this is the last reference to the
- * picture, the picture itself is also automatically freed.
- * @param ref reference to the picture
+ * Remove a reference to a buffer. If this is the last reference to the
+ * buffer, the buffer itself is also automatically freed.
+ *
+ * @param ref reference to the buffer, may be NULL
  */
-void avfilter_unref_pic(AVFilterPicRef *ref);
+void avfilter_unref_buffer(AVFilterBufferRef *ref);
 
 /**
  * A list of supported formats for one end of a filter link. This is used
@@ -174,41 +220,40 @@ void avfilter_unref_pic(AVFilterPicRef *ref);
  * get updated as well. Therefore, we have the format list structure store a
  * pointer to each of the pointers to itself.
  */
-typedef struct AVFilterFormats AVFilterFormats;
-struct AVFilterFormats
-{
+typedef struct AVFilterFormats {
     unsigned format_count;      ///< number of formats
-    enum PixelFormat *formats;  ///< list of pixel formats
+    int *formats;               ///< list of media formats
 
     unsigned refcount;          ///< number of references to this list
-    AVFilterFormats ***refs;    ///< references to this list
-};
+    struct AVFilterFormats ***refs; ///< references to this list
+}  AVFilterFormats;
 
 /**
- * Creates a list of supported formats. This is intended for use in
+ * Create a list of supported formats. This is intended for use in
  * AVFilter->query_formats().
- * @param pix_fmt list of pixel formats, terminated by PIX_FMT_NONE
+ *
+ * @param fmts list of media formats, terminated by -1
  * @return the format list, with no existing references
  */
-AVFilterFormats *avfilter_make_format_list(const enum PixelFormat *pix_fmts);
+AVFilterFormats *avfilter_make_format_list(const int *fmts);
 
 /**
- * Adds pix_fmt to the list of pixel formats contained in *avff.
+ * Add fmt to the list of media formats contained in *avff.
  * If *avff is NULL the function allocates the filter formats struct
  * and puts its pointer in *avff.
  *
  * @return a non negative value in case of success, or a negative
  * value corresponding to an AVERROR code in case of error
  */
-int avfilter_add_colorspace(AVFilterFormats **avff, enum PixelFormat pix_fmt);
+int avfilter_add_format(AVFilterFormats **avff, int fmt);
 
 /**
- * Returns a list of all colorspaces supported by FFmpeg.
+ * Return a list of all formats supported by Libav for the given media type.
  */
-AVFilterFormats *avfilter_all_colorspaces(void);
+AVFilterFormats *avfilter_all_formats(enum AVMediaType type);
 
 /**
- * Returns a format list which contains the intersection of the formats of
+ * Return a format list which contains the intersection of the formats of
  * a and b. Also, all the references of a, all the references of b, and
  * a and b themselves will be deallocated.
  *
@@ -218,7 +263,7 @@ AVFilterFormats *avfilter_all_colorspaces(void);
 AVFilterFormats *avfilter_merge_formats(AVFilterFormats *a, AVFilterFormats *b);
 
 /**
- * Adds *ref as a new reference to formats.
+ * Add *ref as a new reference to formats.
  * That is the pointers will point like in the ascii art below:
  *   ________
  *  |formats |<--------.
@@ -232,7 +277,7 @@ AVFilterFormats *avfilter_merge_formats(AVFilterFormats *a, AVFilterFormats *b);
 void avfilter_formats_ref(AVFilterFormats *formats, AVFilterFormats **ref);
 
 /**
- * If *ref is non-NULL, removes *ref as a reference to the format list
+ * If *ref is non-NULL, remove *ref as a reference to the format list
  * it currently points to, deallocates that list if this was the last
  * reference, and sets *ref to NULL.
  *
@@ -267,8 +312,7 @@ void avfilter_formats_changeref(AVFilterFormats **oldref,
 /**
  * A filter pad used for either input or output.
  */
-struct AVFilterPad
-{
+struct AVFilterPad {
     /**
      * Pad name. The name is unique among inputs and among outputs, but an
      * input may have the same name as an output. This may be NULL if this
@@ -309,15 +353,25 @@ struct AVFilterPad
      *
      * Input video pads only.
      */
-    void (*start_frame)(AVFilterLink *link, AVFilterPicRef *picref);
+    void (*start_frame)(AVFilterLink *link, AVFilterBufferRef *picref);
 
     /**
-     * Callback function to get a buffer. If NULL, the filter system will
+     * Callback function to get a video buffer. If NULL, the filter system will
      * use avfilter_default_get_video_buffer().
      *
      * Input video pads only.
      */
-    AVFilterPicRef *(*get_video_buffer)(AVFilterLink *link, int perms, int w, int h);
+    AVFilterBufferRef *(*get_video_buffer)(AVFilterLink *link, int perms, int w, int h);
+
+    /**
+     * Callback function to get an audio buffer. If NULL, the filter system will
+     * use avfilter_default_get_audio_buffer().
+     *
+     * Input audio pads only.
+     */
+    AVFilterBufferRef *(*get_audio_buffer)(AVFilterLink *link, int perms,
+                                           enum AVSampleFormat sample_fmt, int size,
+                                           int64_t channel_layout, int planar);
 
     /**
      * Callback called after the slices of a frame are completely sent. If
@@ -337,8 +391,16 @@ struct AVFilterPad
     void (*draw_slice)(AVFilterLink *link, int y, int height, int slice_dir);
 
     /**
+     * Samples filtering callback. This is where a filter receives audio data
+     * and should do its processing.
+     *
+     * Input audio pads only.
+     */
+    void (*filter_samples)(AVFilterLink *link, AVFilterBufferRef *samplesref);
+
+    /**
      * Frame poll callback. This returns the number of immediately available
-     * frames. It should return a positive value if the next request_frame()
+     * samples. It should return a positive value if the next request_frame()
      * is guaranteed to return one frame (with no delay).
      *
      * Defaults to just calling the source poll_frame() method.
@@ -374,29 +436,44 @@ struct AVFilterPad
 };
 
 /** default handler for start_frame() for video inputs */
-void avfilter_default_start_frame(AVFilterLink *link, AVFilterPicRef *picref);
+void avfilter_default_start_frame(AVFilterLink *link, AVFilterBufferRef *picref);
+
 /** default handler for draw_slice() for video inputs */
 void avfilter_default_draw_slice(AVFilterLink *link, int y, int h, int slice_dir);
+
 /** default handler for end_frame() for video inputs */
 void avfilter_default_end_frame(AVFilterLink *link);
-/** default handler for config_props() for video outputs */
+
+/** default handler for filter_samples() for audio inputs */
+void avfilter_default_filter_samples(AVFilterLink *link, AVFilterBufferRef *samplesref);
+
+/** default handler for config_props() for audio/video outputs */
 int avfilter_default_config_output_link(AVFilterLink *link);
-/** default handler for config_props() for video inputs */
+
+/** default handler for config_props() for audio/video inputs */
 int avfilter_default_config_input_link (AVFilterLink *link);
+
 /** default handler for get_video_buffer() for video inputs */
-AVFilterPicRef *avfilter_default_get_video_buffer(AVFilterLink *link,
-                                                  int perms, int w, int h);
+AVFilterBufferRef *avfilter_default_get_video_buffer(AVFilterLink *link,
+                                                     int perms, int w, int h);
+
+/** default handler for get_audio_buffer() for audio inputs */
+AVFilterBufferRef *avfilter_default_get_audio_buffer(AVFilterLink *link, int perms,
+                                                     enum AVSampleFormat sample_fmt, int size,
+                                                     int64_t channel_layout, int planar);
+
 /**
  * A helper for query_formats() which sets all links to the same list of
  * formats. If there are no links hooked to this filter, the list of formats is
  * freed.
  */
 void avfilter_set_common_formats(AVFilterContext *ctx, AVFilterFormats *formats);
+
 /** Default handler for query_formats() */
 int avfilter_default_query_formats(AVFilterContext *ctx);
 
 /** start_frame() handler for filters which simply pass video along */
-void avfilter_null_start_frame(AVFilterLink *link, AVFilterPicRef *picref);
+void avfilter_null_start_frame(AVFilterLink *link, AVFilterBufferRef *picref);
 
 /** draw_slice() handler for filters which simply pass video along */
 void avfilter_null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir);
@@ -404,16 +481,23 @@ void avfilter_null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir);
 /** end_frame() handler for filters which simply pass video along */
 void avfilter_null_end_frame(AVFilterLink *link);
 
+/** filter_samples() handler for filters which simply pass audio along */
+void avfilter_null_filter_samples(AVFilterLink *link, AVFilterBufferRef *samplesref);
+
 /** get_video_buffer() handler for filters which simply pass video along */
-AVFilterPicRef *avfilter_null_get_video_buffer(AVFilterLink *link,
+AVFilterBufferRef *avfilter_null_get_video_buffer(AVFilterLink *link,
                                                   int perms, int w, int h);
 
+/** get_audio_buffer() handler for filters which simply pass audio along */
+AVFilterBufferRef *avfilter_null_get_audio_buffer(AVFilterLink *link, int perms,
+                                                  enum AVSampleFormat sample_fmt, int size,
+                                                  int64_t channel_layout, int planar);
+
 /**
  * Filter definition. This defines the pads a filter contains, and all the
  * callback functions used to interact with the filter.
  */
-typedef struct AVFilter
-{
+typedef struct AVFilter {
     const char *name;         ///< filter name
 
     int priv_size;      ///< size of private data to allocate for the filter
@@ -428,7 +512,7 @@ typedef struct AVFilter
 
     /**
      * Filter uninitialization function. Should deallocate any memory held
-     * by the filter, release any picture references, etc. This does not need
+     * by the filter, release any buffer references, etc. This does not need
      * to deallocate the AVFilterContext->priv memory itself.
      */
     void (*uninit)(AVFilterContext *ctx);
@@ -454,8 +538,7 @@ typedef struct AVFilter
 } AVFilter;
 
 /** An instance of a filter */
-struct AVFilterContext
-{
+struct AVFilterContext {
     const AVClass *av_class;              ///< needed for av_log()
 
     AVFilter *filter;               ///< the AVFilter of which this is an instance
@@ -480,13 +563,12 @@ struct AVFilterContext
  * which have been negotiated and agreed upon between the filter, such as
  * image dimensions, format, etc.
  */
-struct AVFilterLink
-{
+struct AVFilterLink {
     AVFilterContext *src;       ///< source filter
-    unsigned int srcpad;        ///< index of the output pad on the source filter
+    AVFilterPad *srcpad;        ///< output pad on the source filter
 
     AVFilterContext *dst;       ///< dest filter
-    unsigned int dstpad;        ///< index of the input pad on the dest filter
+    AVFilterPad *dstpad;        ///< input pad on the dest filter
 
     /** stage of the initialization of the link properties (dimensions, etc) */
     enum {
@@ -495,9 +577,17 @@ struct AVFilterLink
         AVLINK_INIT             ///< complete
     } init_state;
 
+    enum AVMediaType type;      ///< filter media type
+
+    /* These parameters apply only to video */
     int w;                      ///< agreed upon image width
     int h;                      ///< agreed upon image height
-    enum PixelFormat format;    ///< agreed upon image colorspace
+    AVRational sample_aspect_ratio; ///< agreed upon sample aspect ratio
+    /* These two parameters apply only to audio */
+    int64_t channel_layout;     ///< channel layout of current buffer (see libavutil/audioconvert.h)
+    int64_t sample_rate;        ///< samples per second
+
+    int format;                 ///< agreed upon media format
 
     /**
      * Lists of formats supported by the input and output filters respectively.
@@ -508,20 +598,30 @@ struct AVFilterLink
     AVFilterFormats *out_formats;
 
     /**
-     * The picture reference currently being sent across the link by the source
+     * The buffer reference currently being sent across the link by the source
      * filter. This is used internally by the filter system to allow
-     * automatic copying of pictures which do not have sufficient permissions
+     * automatic copying of buffers which do not have sufficient permissions
      * for the destination. This should not be accessed directly by the
      * filters.
      */
-    AVFilterPicRef *srcpic;
+    AVFilterBufferRef *src_buf;
+
+    AVFilterBufferRef *cur_buf;
+    AVFilterBufferRef *out_buf;
 
-    AVFilterPicRef *cur_pic;
-    AVFilterPicRef *outpic;
+    /**
+     * Define the time base used by the PTS of the frames/samples
+     * which will pass through this link.
+     * During the configuration stage, each filter is supposed to
+     * change only the output timebase, while the timebase of the
+     * input link is assumed to be an unchangeable property.
+     */
+    AVRational time_base;
 };
 
 /**
- * Links two filters together.
+ * Link two filters together.
+ *
  * @param src    the source filter
  * @param srcpad index of the output pad on the source filter
  * @param dst    the destination filter
@@ -532,34 +632,70 @@ int avfilter_link(AVFilterContext *src, unsigned srcpad,
                   AVFilterContext *dst, unsigned dstpad);
 
 /**
- * Negotiates the colorspace, dimensions, etc of all inputs to a filter.
+ * Negotiate the media format, dimensions, etc of all inputs to a filter.
+ *
  * @param filter the filter to negotiate the properties for its inputs
  * @return       zero on successful negotiation
  */
 int avfilter_config_links(AVFilterContext *filter);
 
 /**
- * Requests a picture buffer with a specific set of permissions.
- * @param link  the output link to the filter from which the picture will
+ * Request a picture buffer with a specific set of permissions.
+ *
+ * @param link  the output link to the filter from which the buffer will
  *              be requested
  * @param perms the required access permissions
  * @param w     the minimum width of the buffer to allocate
  * @param h     the minimum height of the buffer to allocate
- * @return      A reference to the picture. This must be unreferenced with
- *              avfilter_unref_pic when you are finished with it.
+ * @return      A reference to the buffer. This must be unreferenced with
+ *              avfilter_unref_buffer when you are finished with it.
  */
-AVFilterPicRef *avfilter_get_video_buffer(AVFilterLink *link, int perms,
+AVFilterBufferRef *avfilter_get_video_buffer(AVFilterLink *link, int perms,
                                           int w, int h);
 
 /**
- * Requests an input frame from the filter at the other end of the link.
+ * Create a buffer reference wrapped around an already allocated image
+ * buffer.
+ *
+ * @param data pointers to the planes of the image to reference
+ * @param linesize linesizes for the planes of the image to reference
+ * @param perms the required access permissions
+ * @param w the width of the image specified by the data and linesize arrays
+ * @param h the height of the image specified by the data and linesize arrays
+ * @param format the pixel format of the image specified by the data and linesize arrays
+ */
+AVFilterBufferRef *
+avfilter_get_video_buffer_ref_from_arrays(uint8_t *data[4], int linesize[4], int perms,
+                                          int w, int h, enum PixelFormat format);
+
+/**
+ * Request an audio samples buffer with a specific set of permissions.
+ *
+ * @param link           the output link to the filter from which the buffer will
+ *                       be requested
+ * @param perms          the required access permissions
+ * @param sample_fmt     the format of each sample in the buffer to allocate
+ * @param size           the buffer size in bytes
+ * @param channel_layout the number and type of channels per sample in the buffer to allocate
+ * @param planar         audio data layout - planar or packed
+ * @return               A reference to the samples. This must be unreferenced with
+ *                       avfilter_unref_buffer when you are finished with it.
+ */
+AVFilterBufferRef *avfilter_get_audio_buffer(AVFilterLink *link, int perms,
+                                             enum AVSampleFormat sample_fmt, int size,
+                                             int64_t channel_layout, int planar);
+
+/**
+ * Request an input frame from the filter at the other end of the link.
+ *
  * @param link the input link
  * @return     zero on success
  */
 int avfilter_request_frame(AVFilterLink *link);
 
 /**
- * Polls a frame from the filter chain.
+ * Poll a frame from the filter chain.
+ *
  * @param  link the input link
  * @return the number of immediately available frames, a negative
  * number in case of error
@@ -567,23 +703,25 @@ int avfilter_request_frame(AVFilterLink *link);
 int avfilter_poll_frame(AVFilterLink *link);
 
 /**
- * Notifies the next filter of the start of a frame.
+ * Notifie the next filter of the start of a frame.
+ *
  * @param link   the output link the frame will be sent over
  * @param picref A reference to the frame about to be sent. The data for this
  *               frame need only be valid once draw_slice() is called for that
  *               portion. The receiving filter will free this reference when
  *               it no longer needs it.
  */
-void avfilter_start_frame(AVFilterLink *link, AVFilterPicRef *picref);
+void avfilter_start_frame(AVFilterLink *link, AVFilterBufferRef *picref);
 
 /**
- * Notifies the next filter that the current frame has finished.
+ * Notifie the next filter that the current frame has finished.
+ *
  * @param link the output link the frame was sent over
  */
 void avfilter_end_frame(AVFilterLink *link);
 
 /**
- * Sends a slice to the next filter.
+ * Send a slice to the next filter.
  *
  * Slices have to be provided in sequential order, either in
  * top-bottom or bottom-top order. If slices are provided in
@@ -599,17 +737,28 @@ void avfilter_end_frame(AVFilterLink *link);
  */
 void avfilter_draw_slice(AVFilterLink *link, int y, int h, int slice_dir);
 
-/** Initializes the filter system. Registers all builtin filters. */
+/**
+ * Send a buffer of audio samples to the next filter.
+ *
+ * @param link       the output link over which the audio samples are being sent
+ * @param samplesref a reference to the buffer of audio samples being sent. The
+ *                   receiving filter will free this reference when it no longer
+ *                   needs it or pass it on to the next filter.
+ */
+void avfilter_filter_samples(AVFilterLink *link, AVFilterBufferRef *samplesref);
+
+/** Initialize the filter system. Register all builtin filters. */
 void avfilter_register_all(void);
 
-/** Uninitializes the filter system. Unregisters all filters. */
+/** Uninitialize the filter system. Unregister all filters. */
 void avfilter_uninit(void);
 
 /**
- * Registers a filter. This is only needed if you plan to use
+ * Register a filter. This is only needed if you plan to use
  * avfilter_get_by_name later to lookup the AVFilter structure by name. A
  * filter can still by instantiated with avfilter_open even if it is not
  * registered.
+ *
  * @param filter the filter to register
  * @return 0 if the registration was succesfull, a negative value
  * otherwise
@@ -617,7 +766,8 @@ void avfilter_uninit(void);
 int avfilter_register(AVFilter *filter);
 
 /**
- * Gets a filter definition matching the given name.
+ * Get a filter definition matching the given name.
+ *
  * @param name the filter name to find
  * @return     the filter definition, if any matching one is registered.
  *             NULL if none found.
@@ -633,15 +783,19 @@ AVFilter *avfilter_get_by_name(const char *name);
 AVFilter **av_filter_next(AVFilter **filter);
 
 /**
- * Creates a filter instance.
+ * Create a filter instance.
+ *
+ * @param filter_ctx put here a pointer to the created filter context
+ * on success, NULL on failure
  * @param filter    the filter to create an instance of
  * @param inst_name Name to give to the new instance. Can be NULL for none.
- * @return          Pointer to the new instance on success. NULL on failure.
+ * @return >= 0 in case of success, a negative error code otherwise
  */
-AVFilterContext *avfilter_open(AVFilter *filter, const char *inst_name);
+int avfilter_open(AVFilterContext **filter_ctx, AVFilter *filter, const char *inst_name);
 
 /**
- * Initializes a filter.
+ * Initialize a filter.
+ *
  * @param filter the filter to initialize
  * @param args   A string of parameters to use when initializing the filter.
  *               The format and meaning of this string varies by filter.
@@ -652,24 +806,27 @@ AVFilterContext *avfilter_open(AVFilter *filter, const char *inst_name);
 int avfilter_init_filter(AVFilterContext *filter, const char *args, void *opaque);
 
 /**
- * Destroys a filter.
- * @param filter the filter to destroy
+ * Free a filter context.
+ *
+ * @param filter the filter to free
  */
-void avfilter_destroy(AVFilterContext *filter);
+void avfilter_free(AVFilterContext *filter);
 
 /**
- * Inserts a filter in the middle of an existing link.
+ * Insert a filter in the middle of an existing link.
+ *
  * @param link the link into which the filter should be inserted
  * @param filt the filter to be inserted
- * @param in   the input pad on the filter to connect
- * @param out  the output pad on the filter to connect
+ * @param filt_srcpad_idx the input pad on the filter to connect
+ * @param filt_dstpad_idx the output pad on the filter to connect
  * @return     zero on success
  */
 int avfilter_insert_filter(AVFilterLink *link, AVFilterContext *filt,
-                           unsigned in, unsigned out);
+                           unsigned filt_srcpad_idx, unsigned filt_dstpad_idx);
 
 /**
- * Inserts a new pad.
+ * Insert a new pad.
+ *
  * @param idx Insertion point. Pad is inserted at the end if this point
  *            is beyond the end of the list of pads.
  * @param count Pointer to the number of pads in the list
@@ -684,7 +841,7 @@ void avfilter_insert_pad(unsigned idx, unsigned *count, size_t padidx_off,
                          AVFilterPad **pads, AVFilterLink ***links,
                          AVFilterPad *newpad);
 
-/** Inserts a new input pad for the filter. */
+/** Insert a new input pad for the filter. */
 static inline void avfilter_insert_inpad(AVFilterContext *f, unsigned index,
                                          AVFilterPad *p)
 {
@@ -692,7 +849,7 @@ static inline void avfilter_insert_inpad(AVFilterContext *f, unsigned index,
                         &f->input_pads, &f->inputs, p);
 }
 
-/** Inserts a new output pad for the filter. */
+/** Insert a new output pad for the filter. */
 static inline void avfilter_insert_outpad(AVFilterContext *f, unsigned index,
                                           AVFilterPad *p)
 {
diff --git a/libavfilter/avfiltergraph.c b/libavfilter/avfiltergraph.c
index 9ad6536..b503c36 100644
--- a/libavfilter/avfiltergraph.c
+++ b/libavfilter/avfiltergraph.c
@@ -1,22 +1,22 @@
 /*
  * filter graphs
- * copyright (c) 2008 Vitor Sessak
- * copyright (c) 2007 Bobby Bingham
+ * Copyright (c) 2008 Vitor Sessak
+ * Copyright (c) 2007 Bobby Bingham
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,13 +25,22 @@
 
 #include "avfilter.h"
 #include "avfiltergraph.h"
+#include "internal.h"
 
-void avfilter_graph_destroy(AVFilterGraph *graph)
+AVFilterGraph *avfilter_graph_alloc(void)
 {
-    for(; graph->filter_count > 0; graph->filter_count --)
-        avfilter_destroy(graph->filters[graph->filter_count - 1]);
-    av_freep(&graph->scale_sws_opts);
-    av_freep(&graph->filters);
+    return av_mallocz(sizeof(AVFilterGraph));
+}
+
+void avfilter_graph_free(AVFilterGraph **graph)
+{
+    if (!*graph)
+        return;
+    for (; (*graph)->filter_count > 0; (*graph)->filter_count--)
+        avfilter_free((*graph)->filters[(*graph)->filter_count - 1]);
+    av_freep(&(*graph)->scale_sws_opts);
+    av_freep(&(*graph)->filters);
+    av_freep(graph);
 }
 
 int avfilter_graph_add_filter(AVFilterGraph *graph, AVFilterContext *filter)
@@ -47,12 +56,33 @@ int avfilter_graph_add_filter(AVFilterGraph *graph, AVFilterContext *filter)
     return 0;
 }
 
-int avfilter_graph_check_validity(AVFilterGraph *graph, AVClass *log_ctx)
+int avfilter_graph_create_filter(AVFilterContext **filt_ctx, AVFilter *filt,
+                                 const char *name, const char *args, void *opaque,
+                                 AVFilterGraph *graph_ctx)
+{
+    int ret;
+
+    if ((ret = avfilter_open(filt_ctx, filt, name)) < 0)
+        goto fail;
+    if ((ret = avfilter_init_filter(*filt_ctx, args, opaque)) < 0)
+        goto fail;
+    if ((ret = avfilter_graph_add_filter(graph_ctx, *filt_ctx)) < 0)
+        goto fail;
+    return 0;
+
+fail:
+    if (*filt_ctx)
+        avfilter_free(*filt_ctx);
+    *filt_ctx = NULL;
+    return ret;
+}
+
+int ff_avfilter_graph_check_validity(AVFilterGraph *graph, AVClass *log_ctx)
 {
     AVFilterContext *filt;
     int i, j;
 
-    for (i=0; i < graph->filter_count; i++) {
+    for (i = 0; i < graph->filter_count; i++) {
         filt = graph->filters[i];
 
         for (j = 0; j < filt->input_count; j++) {
@@ -77,7 +107,7 @@ int avfilter_graph_check_validity(AVFilterGraph *graph, AVClass *log_ctx)
     return 0;
 }
 
-int avfilter_graph_config_links(AVFilterGraph *graph, AVClass *log_ctx)
+int ff_avfilter_graph_config_links(AVFilterGraph *graph, AVClass *log_ctx)
 {
     AVFilterContext *filt;
     int i, ret;
@@ -98,8 +128,8 @@ AVFilterContext *avfilter_graph_get_filter(AVFilterGraph *graph, char *name)
 {
     int i;
 
-    for(i = 0; i < graph->filter_count; i ++)
-        if(graph->filters[i]->name && !strcmp(name, graph->filters[i]->name))
+    for (i = 0; i < graph->filter_count; i++)
+        if (graph->filters[i]->name && !strcmp(name, graph->filters[i]->name))
             return graph->filters[i];
 
     return NULL;
@@ -107,44 +137,38 @@ AVFilterContext *avfilter_graph_get_filter(AVFilterGraph *graph, char *name)
 
 static int query_formats(AVFilterGraph *graph, AVClass *log_ctx)
 {
-    int i, j;
+    int i, j, ret;
     int scaler_count = 0;
     char inst_name[30];
 
-    /* ask all the sub-filters for their supported colorspaces */
-    for(i = 0; i < graph->filter_count; i ++) {
-        if(graph->filters[i]->filter->query_formats)
+    /* ask all the sub-filters for their supported media formats */
+    for (i = 0; i < graph->filter_count; i++) {
+        if (graph->filters[i]->filter->query_formats)
             graph->filters[i]->filter->query_formats(graph->filters[i]);
         else
             avfilter_default_query_formats(graph->filters[i]);
     }
 
     /* go through and merge as many format lists as possible */
-    for(i = 0; i < graph->filter_count; i ++) {
+    for (i = 0; i < graph->filter_count; i++) {
         AVFilterContext *filter = graph->filters[i];
 
-        for(j = 0; j < filter->input_count; j ++) {
+        for (j = 0; j < filter->input_count; j++) {
             AVFilterLink *link = filter->inputs[j];
-            if(link && link->in_formats != link->out_formats) {
-                if(!avfilter_merge_formats(link->in_formats,
-                                           link->out_formats)) {
+            if (link && link->in_formats != link->out_formats) {
+                if (!avfilter_merge_formats(link->in_formats,
+                                            link->out_formats)) {
                     AVFilterContext *scale;
                     char scale_args[256];
                     /* couldn't merge format lists. auto-insert scale filter */
                     snprintf(inst_name, sizeof(inst_name), "auto-inserted scaler %d",
                              scaler_count++);
-                    scale =
-                        avfilter_open(avfilter_get_by_name("scale"),inst_name);
-
                     snprintf(scale_args, sizeof(scale_args), "0:0:%s", graph->scale_sws_opts);
-                    if(!scale || scale->filter->init(scale, scale_args, NULL) ||
-                                 avfilter_insert_filter(link, scale, 0, 0)) {
-                        avfilter_destroy(scale);
-                        return -1;
-                    }
-
-                    if (avfilter_graph_add_filter(graph, scale) < 0)
-                        return -1;
+                    if ((ret = avfilter_graph_create_filter(&scale, avfilter_get_by_name("scale"),
+                                                            inst_name, scale_args, NULL, graph)) < 0)
+                        return ret;
+                    if ((ret = avfilter_insert_filter(link, scale, 0, 0)) < 0)
+                        return ret;
 
                     scale->filter->query_formats(scale);
                     if (((link = scale-> inputs[0]) &&
@@ -166,7 +190,7 @@ static int query_formats(AVFilterGraph *graph, AVClass *log_ctx)
 
 static void pick_format(AVFilterLink *link)
 {
-    if(!link || !link->in_formats)
+    if (!link || !link->in_formats)
         return;
 
     link->in_formats->format_count = 1;
@@ -180,26 +204,39 @@ static void pick_formats(AVFilterGraph *graph)
 {
     int i, j;
 
-    for(i = 0; i < graph->filter_count; i ++) {
+    for (i = 0; i < graph->filter_count; i++) {
         AVFilterContext *filter = graph->filters[i];
 
-        for(j = 0; j < filter->input_count; j ++)
+        for (j = 0; j < filter->input_count; j++)
             pick_format(filter->inputs[j]);
-        for(j = 0; j < filter->output_count; j ++)
+        for (j = 0; j < filter->output_count; j++)
             pick_format(filter->outputs[j]);
     }
 }
 
-int avfilter_graph_config_formats(AVFilterGraph *graph, AVClass *log_ctx)
+int ff_avfilter_graph_config_formats(AVFilterGraph *graph, AVClass *log_ctx)
 {
     /* find supported formats from sub-filters, and merge along links */
-    if(query_formats(graph, log_ctx))
+    if (query_formats(graph, log_ctx))
         return -1;
 
     /* Once everything is merged, it's possible that we'll still have
-     * multiple valid colorspace choices. We pick the first one. */
+     * multiple valid media format choices. We pick the first one. */
     pick_formats(graph);
 
     return 0;
 }
 
+int avfilter_graph_config(AVFilterGraph *graphctx, AVClass *log_ctx)
+{
+    int ret;
+
+    if ((ret = ff_avfilter_graph_check_validity(graphctx, log_ctx)))
+        return ret;
+    if ((ret = ff_avfilter_graph_config_formats(graphctx, log_ctx)))
+        return ret;
+    if ((ret = ff_avfilter_graph_config_links(graphctx, log_ctx)))
+        return ret;
+
+    return 0;
+}
diff --git a/libavfilter/avfiltergraph.h b/libavfilter/avfiltergraph.h
index 1640795..801e501 100644
--- a/libavfilter/avfiltergraph.h
+++ b/libavfilter/avfiltergraph.h
@@ -2,20 +2,20 @@
  * Filter graphs
  * copyright (c) 2007 Bobby Bingham
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -32,7 +32,12 @@ typedef struct AVFilterGraph {
 } AVFilterGraph;
 
 /**
- * Gets a filter instance with name name from graph.
+ * Allocate a filter graph.
+ */
+AVFilterGraph *avfilter_graph_alloc(void);
+
+/**
+ * Get a filter instance with name name from graph.
  *
  * @return the pointer to the found filter instance or NULL if it
  * cannot be found.
@@ -40,38 +45,79 @@ typedef struct AVFilterGraph {
 AVFilterContext *avfilter_graph_get_filter(AVFilterGraph *graph, char *name);
 
 /**
- * Adds an existing filter instance to a filter graph.
+ * Add an existing filter instance to a filter graph.
  *
- * @param graph  the filter graph
+ * @param graphctx  the filter graph
  * @param filter the filter to be added
  */
 int avfilter_graph_add_filter(AVFilterGraph *graphctx, AVFilterContext *filter);
 
 /**
- * Checks for the validity of graph.
+ * Create and add a filter instance into an existing graph.
+ * The filter instance is created from the filter filt and inited
+ * with the parameters args and opaque.
  *
- * A graph is considered valid if all its input and output pads are
- * connected.
+ * In case of success put in *filt_ctx the pointer to the created
+ * filter instance, otherwise set *filt_ctx to NULL.
  *
- * @return 0 in case of success, a negative value otherwise
+ * @param name the instance name to give to the created filter instance
+ * @param graph_ctx the filter graph
+ * @return a negative AVERROR error code in case of failure, a non
+ * negative value otherwise
  */
-int avfilter_graph_check_validity(AVFilterGraph *graphctx, AVClass *log_ctx);
+int avfilter_graph_create_filter(AVFilterContext **filt_ctx, AVFilter *filt,
+                                 const char *name, const char *args, void *opaque,
+                                 AVFilterGraph *graph_ctx);
 
 /**
- * Configures all the links of graphctx.
+ * Check validity and configure all the links and formats in the graph.
  *
- * @return 0 in case of success, a negative value otherwise
+ * @param graphctx the filter graph
+ * @param log_ctx context used for logging
+ * @return 0 in case of success, a negative AVERROR code otherwise
  */
-int avfilter_graph_config_links(AVFilterGraph *graphctx, AVClass *log_ctx);
+int avfilter_graph_config(AVFilterGraph *graphctx, AVClass *log_ctx);
 
 /**
- * Configures the formats of all the links in the graph.
+ * Free a graph, destroy its links, and set *graph to NULL.
+ * If *graph is NULL, do nothing.
  */
-int avfilter_graph_config_formats(AVFilterGraph *graphctx, AVClass *log_ctx);
+void avfilter_graph_free(AVFilterGraph **graph);
 
 /**
- * Frees a graph and destroys its links.
+ * A linked-list of the inputs/outputs of the filter chain.
+ *
+ * This is mainly useful for avfilter_graph_parse(), since this
+ * function may accept a description of a graph with not connected
+ * input/output pads. This struct specifies, per each not connected
+ * pad contained in the graph, the filter context and the pad index
+ * required for establishing a link.
+ */
+typedef struct AVFilterInOut {
+    /** unique name for this input/output in the list */
+    char *name;
+
+    /** filter context associated to this input/output */
+    AVFilterContext *filter_ctx;
+
+    /** index of the filt_ctx pad to use for linking */
+    int pad_idx;
+
+    /** next input/input in the list, NULL if this is the last */
+    struct AVFilterInOut *next;
+} AVFilterInOut;
+
+/**
+ * Add a graph described by a string to a graph.
+ *
+ * @param graph   the filter graph where to link the parsed graph context
+ * @param filters string to be parsed
+ * @param inputs  linked list to the inputs of the graph
+ * @param outputs linked list to the outputs of the graph
+ * @return zero on success, a negative AVERROR code on error
  */
-void avfilter_graph_destroy(AVFilterGraph *graph);
+int avfilter_graph_parse(AVFilterGraph *graph, const char *filters,
+                         AVFilterInOut *inputs, AVFilterInOut *outputs,
+                         AVClass *log_ctx);
 
 #endif  /* AVFILTER_AVFILTERGRAPH_H */
diff --git a/libavfilter/defaults.c b/libavfilter/defaults.c
index afa0f66..146f1c7 100644
--- a/libavfilter/defaults.c
+++ b/libavfilter/defaults.c
@@ -1,113 +1,203 @@
 /*
  * Filter layer - default implementations
- * copyright (c) 2007 Bobby Bingham
+ * Copyright (c) 2007 Bobby Bingham
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
-#include "libavcodec/imgconvert.h"
+#include "libavutil/audioconvert.h"
+#include "libavutil/imgutils.h"
+#include "libavutil/samplefmt.h"
 #include "avfilter.h"
+#include "internal.h"
 
 /* TODO: buffer pool.  see comment for avfilter_default_get_video_buffer() */
-static void avfilter_default_free_video_buffer(AVFilterPic *pic)
+void ff_avfilter_default_free_buffer(AVFilterBuffer *ptr)
 {
-    av_free(pic->data[0]);
-    av_free(pic);
+    av_free(ptr->data[0]);
+    av_free(ptr);
 }
 
 /* TODO: set the buffer's priv member to a context structure for the whole
  * filter chain.  This will allow for a buffer pool instead of the constant
  * alloc & free cycle currently implemented. */
-AVFilterPicRef *avfilter_default_get_video_buffer(AVFilterLink *link, int perms, int w, int h)
+AVFilterBufferRef *avfilter_default_get_video_buffer(AVFilterLink *link, int perms, int w, int h)
 {
-    AVFilterPic *pic = av_mallocz(sizeof(AVFilterPic));
-    AVFilterPicRef *ref = av_mallocz(sizeof(AVFilterPicRef));
-    int i, tempsize;
+    int linesize[4];
+    uint8_t *data[4];
+    AVFilterBufferRef *picref = NULL;
+
+    // +2 is needed for swscaler, +16 to be SIMD-friendly
+    if (av_image_alloc(data, linesize, w, h, link->format, 16) < 0)
+        return NULL;
+
+    picref = avfilter_get_video_buffer_ref_from_arrays(data, linesize,
+                                                       perms, w, h, link->format);
+    if (!picref) {
+        av_free(data[0]);
+        return NULL;
+    }
+
+    return picref;
+}
+
+AVFilterBufferRef *avfilter_default_get_audio_buffer(AVFilterLink *link, int perms,
+                                                     enum AVSampleFormat sample_fmt, int size,
+                                                     int64_t channel_layout, int planar)
+{
+    AVFilterBuffer *samples = av_mallocz(sizeof(AVFilterBuffer));
+    AVFilterBufferRef *ref = NULL;
+    int i, sample_size, chans_nb, bufsize, per_channel_size, step_size = 0;
     char *buf;
 
-    ref->pic   = pic;
-    ref->w     = pic->w = w;
-    ref->h     = pic->h = h;
+    if (!samples || !(ref = av_mallocz(sizeof(AVFilterBufferRef))))
+        goto fail;
+
+    ref->buf                   = samples;
+    ref->format                = sample_fmt;
+
+    ref->audio = av_mallocz(sizeof(AVFilterBufferRefAudioProps));
+    if (!ref->audio)
+        goto fail;
+
+    ref->audio->channel_layout = channel_layout;
+    ref->audio->size           = size;
+    ref->audio->planar         = planar;
 
     /* make sure the buffer gets read permission or it's useless for output */
     ref->perms = perms | AV_PERM_READ;
 
-    pic->refcount = 1;
-    pic->format   = link->format;
-    pic->free     = avfilter_default_free_video_buffer;
-    ff_fill_linesize((AVPicture *)pic, pic->format, ref->w);
+    samples->refcount   = 1;
+    samples->free       = ff_avfilter_default_free_buffer;
+
+    sample_size = av_get_bits_per_sample_fmt(sample_fmt) >>3;
+    chans_nb = av_get_channel_layout_nb_channels(channel_layout);
+
+    per_channel_size = size/chans_nb;
+    ref->audio->nb_samples = per_channel_size/sample_size;
 
-    for (i=0; i<4;i++)
-        pic->linesize[i] = FFALIGN(pic->linesize[i], 16);
+    /* Set the number of bytes to traverse to reach next sample of a particular channel:
+     * For planar, this is simply the sample size.
+     * For packed, this is the number of samples * sample_size.
+     */
+    for (i = 0; i < chans_nb; i++)
+        samples->linesize[i] = planar > 0 ? per_channel_size : sample_size;
+    memset(&samples->linesize[chans_nb], 0, (8-chans_nb) * sizeof(samples->linesize[0]));
+
+    /* Calculate total buffer size, round to multiple of 16 to be SIMD friendly */
+    bufsize = (size + 15)&~15;
+    buf = av_malloc(bufsize);
+    if (!buf)
+        goto fail;
+
+    /* For planar, set the start point of each channel's data within the buffer
+     * For packed, set the start point of the entire buffer only
+     */
+    samples->data[0] = buf;
+    if (buf && planar) {
+        for (i = 1; i < chans_nb; i++) {
+            step_size += per_channel_size;
+            samples->data[i] = buf + step_size;
+        }
+    } else {
+        for (i = 1; i < chans_nb; i++)
+            samples->data[i] = buf;
+    }
 
-    tempsize = ff_fill_pointer((AVPicture *)pic, NULL, pic->format, ref->h);
-    buf = av_malloc(tempsize);
-    ff_fill_pointer((AVPicture *)pic, buf, pic->format, ref->h);
+    memset(&samples->data[chans_nb], 0, (8-chans_nb) * sizeof(samples->data[0]));
 
-    memcpy(ref->data,     pic->data,     sizeof(pic->data));
-    memcpy(ref->linesize, pic->linesize, sizeof(pic->linesize));
+    memcpy(ref->data,     samples->data,     sizeof(ref->data));
+    memcpy(ref->linesize, samples->linesize, sizeof(ref->linesize));
 
     return ref;
+
+fail:
+    if (ref)
+        av_free(ref->audio);
+    av_free(ref);
+    av_free(samples);
+    return NULL;
 }
 
-void avfilter_default_start_frame(AVFilterLink *link, AVFilterPicRef *picref)
+void avfilter_default_start_frame(AVFilterLink *inlink, AVFilterBufferRef *picref)
 {
-    AVFilterLink *out = NULL;
+    AVFilterLink *outlink = NULL;
 
-    if(link->dst->output_count)
-        out = link->dst->outputs[0];
+    if (inlink->dst->output_count)
+        outlink = inlink->dst->outputs[0];
 
-    if(out) {
-        out->outpic      = avfilter_get_video_buffer(out, AV_PERM_WRITE, out->w, out->h);
-        out->outpic->pts = picref->pts;
-        out->outpic->pos = picref->pos;
-        out->outpic->pixel_aspect = picref->pixel_aspect;
-        avfilter_start_frame(out, avfilter_ref_pic(out->outpic, ~0));
+    if (outlink) {
+        outlink->out_buf = avfilter_get_video_buffer(outlink, AV_PERM_WRITE, outlink->w, outlink->h);
+        avfilter_copy_buffer_ref_props(outlink->out_buf, picref);
+        avfilter_start_frame(outlink, avfilter_ref_buffer(outlink->out_buf, ~0));
     }
 }
 
-void avfilter_default_draw_slice(AVFilterLink *link, int y, int h, int slice_dir)
+void avfilter_default_draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir)
 {
-    AVFilterLink *out = NULL;
+    AVFilterLink *outlink = NULL;
 
-    if(link->dst->output_count)
-        out = link->dst->outputs[0];
+    if (inlink->dst->output_count)
+        outlink = inlink->dst->outputs[0];
 
-    if(out)
-        avfilter_draw_slice(out, y, h, slice_dir);
+    if (outlink)
+        avfilter_draw_slice(outlink, y, h, slice_dir);
 }
 
-void avfilter_default_end_frame(AVFilterLink *link)
+void avfilter_default_end_frame(AVFilterLink *inlink)
 {
-    AVFilterLink *out = NULL;
+    AVFilterLink *outlink = NULL;
 
-    if(link->dst->output_count)
-        out = link->dst->outputs[0];
+    if (inlink->dst->output_count)
+        outlink = inlink->dst->outputs[0];
 
-    avfilter_unref_pic(link->cur_pic);
-    link->cur_pic = NULL;
+    avfilter_unref_buffer(inlink->cur_buf);
+    inlink->cur_buf = NULL;
 
-    if(out) {
-        if(out->outpic) {
-            avfilter_unref_pic(out->outpic);
-            out->outpic = NULL;
+    if (outlink) {
+        if (outlink->out_buf) {
+            avfilter_unref_buffer(outlink->out_buf);
+            outlink->out_buf = NULL;
         }
-        avfilter_end_frame(out);
+        avfilter_end_frame(outlink);
+    }
+}
+
+/* FIXME: samplesref is same as link->cur_buf. Need to consider removing the redundant parameter. */
+void avfilter_default_filter_samples(AVFilterLink *inlink, AVFilterBufferRef *samplesref)
+{
+    AVFilterLink *outlink = NULL;
+
+    if (inlink->dst->output_count)
+        outlink = inlink->dst->outputs[0];
+
+    if (outlink) {
+        outlink->out_buf = avfilter_default_get_audio_buffer(inlink, AV_PERM_WRITE, samplesref->format,
+                                                             samplesref->audio->size,
+                                                             samplesref->audio->channel_layout,
+                                                             samplesref->audio->planar);
+        outlink->out_buf->pts                = samplesref->pts;
+        outlink->out_buf->audio->sample_rate = samplesref->audio->sample_rate;
+        avfilter_filter_samples(outlink, avfilter_ref_buffer(outlink->out_buf, ~0));
+        avfilter_unref_buffer(outlink->out_buf);
+        outlink->out_buf = NULL;
     }
+    avfilter_unref_buffer(samplesref);
+    inlink->cur_buf = NULL;
 }
 
 /**
@@ -115,9 +205,15 @@ void avfilter_default_end_frame(AVFilterLink *link)
  * the implementation of one input one output video filters */
 int avfilter_default_config_output_link(AVFilterLink *link)
 {
-    if(link->src->input_count && link->src->inputs[0]) {
-        link->w = link->src->inputs[0]->w;
-        link->h = link->src->inputs[0]->h;
+    if (link->src->input_count && link->src->inputs[0]) {
+        if (link->type == AVMEDIA_TYPE_VIDEO) {
+            link->w = link->src->inputs[0]->w;
+            link->h = link->src->inputs[0]->h;
+            link->time_base = link->src->inputs[0]->time_base;
+        } else if (link->type == AVMEDIA_TYPE_AUDIO) {
+            link->channel_layout = link->src->inputs[0]->channel_layout;
+            link->sample_rate    = link->src->inputs[0]->sample_rate;
+        }
     } else {
         /* XXX: any non-simple filter which would cause this branch to be taken
          * really should implement its own config_props() for this link. */
@@ -139,20 +235,20 @@ void avfilter_set_common_formats(AVFilterContext *ctx, AVFilterFormats *formats)
 {
     int count = 0, i;
 
-    for(i = 0; i < ctx->input_count; i ++) {
-        if(ctx->inputs[i]) {
+    for (i = 0; i < ctx->input_count; i++) {
+        if (ctx->inputs[i]) {
             avfilter_formats_ref(formats, &ctx->inputs[i]->out_formats);
-            count ++;
+            count++;
         }
     }
-    for(i = 0; i < ctx->output_count; i ++) {
-        if(ctx->outputs[i]) {
+    for (i = 0; i < ctx->output_count; i++) {
+        if (ctx->outputs[i]) {
             avfilter_formats_ref(formats, &ctx->outputs[i]->in_formats);
-            count ++;
+            count++;
         }
     }
 
-    if(!count) {
+    if (!count) {
         av_free(formats->formats);
         av_free(formats->refs);
         av_free(formats);
@@ -161,11 +257,15 @@ void avfilter_set_common_formats(AVFilterContext *ctx, AVFilterFormats *formats)
 
 int avfilter_default_query_formats(AVFilterContext *ctx)
 {
-    avfilter_set_common_formats(ctx, avfilter_all_colorspaces());
+    enum AVMediaType type = ctx->inputs  && ctx->inputs [0] ? ctx->inputs [0]->type :
+                            ctx->outputs && ctx->outputs[0] ? ctx->outputs[0]->type :
+                            AVMEDIA_TYPE_VIDEO;
+
+    avfilter_set_common_formats(ctx, avfilter_all_formats(type));
     return 0;
 }
 
-void avfilter_null_start_frame(AVFilterLink *link, AVFilterPicRef *picref)
+void avfilter_null_start_frame(AVFilterLink *link, AVFilterBufferRef *picref)
 {
     avfilter_start_frame(link->dst->outputs[0], picref);
 }
@@ -180,8 +280,21 @@ void avfilter_null_end_frame(AVFilterLink *link)
     avfilter_end_frame(link->dst->outputs[0]);
 }
 
-AVFilterPicRef *avfilter_null_get_video_buffer(AVFilterLink *link, int perms, int w, int h)
+void avfilter_null_filter_samples(AVFilterLink *link, AVFilterBufferRef *samplesref)
+{
+    avfilter_filter_samples(link->dst->outputs[0], samplesref);
+}
+
+AVFilterBufferRef *avfilter_null_get_video_buffer(AVFilterLink *link, int perms, int w, int h)
 {
     return avfilter_get_video_buffer(link->dst->outputs[0], perms, w, h);
 }
 
+AVFilterBufferRef *avfilter_null_get_audio_buffer(AVFilterLink *link, int perms,
+                                                  enum AVSampleFormat sample_fmt, int size,
+                                                  int64_t channel_layout, int packed)
+{
+    return avfilter_get_audio_buffer(link->dst->outputs[0], perms, sample_fmt,
+                                     size, channel_layout, packed);
+}
+
diff --git a/libavfilter/drawutils.c b/libavfilter/drawutils.c
new file mode 100644
index 0000000..6aaf5c5
--- /dev/null
+++ b/libavfilter/drawutils.c
@@ -0,0 +1,117 @@
+/*
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "libavutil/avutil.h"
+#include "libavutil/colorspace.h"
+#include "libavutil/pixdesc.h"
+#include "drawutils.h"
+
+enum { RED = 0, GREEN, BLUE, ALPHA };
+
+int ff_fill_line_with_color(uint8_t *line[4], int pixel_step[4], int w, uint8_t dst_color[4],
+                            enum PixelFormat pix_fmt, uint8_t rgba_color[4],
+                            int *is_packed_rgba, uint8_t rgba_map_ptr[4])
+{
+    uint8_t rgba_map[4] = {0};
+    int i;
+    const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[pix_fmt];
+    int hsub = pix_desc->log2_chroma_w;
+
+    *is_packed_rgba = 1;
+    switch (pix_fmt) {
+    case PIX_FMT_ARGB:  rgba_map[ALPHA] = 0; rgba_map[RED  ] = 1; rgba_map[GREEN] = 2; rgba_map[BLUE ] = 3; break;
+    case PIX_FMT_ABGR:  rgba_map[ALPHA] = 0; rgba_map[BLUE ] = 1; rgba_map[GREEN] = 2; rgba_map[RED  ] = 3; break;
+    case PIX_FMT_RGBA:
+    case PIX_FMT_RGB24: rgba_map[RED  ] = 0; rgba_map[GREEN] = 1; rgba_map[BLUE ] = 2; rgba_map[ALPHA] = 3; break;
+    case PIX_FMT_BGRA:
+    case PIX_FMT_BGR24: rgba_map[BLUE ] = 0; rgba_map[GREEN] = 1; rgba_map[RED  ] = 2; rgba_map[ALPHA] = 3; break;
+    default:
+        *is_packed_rgba = 0;
+    }
+
+    if (*is_packed_rgba) {
+        pixel_step[0] = (av_get_bits_per_pixel(pix_desc))>>3;
+        for (i = 0; i < 4; i++)
+            dst_color[rgba_map[i]] = rgba_color[i];
+
+        line[0] = av_malloc(w * pixel_step[0]);
+        for (i = 0; i < w; i++)
+            memcpy(line[0] + i * pixel_step[0], dst_color, pixel_step[0]);
+        if (rgba_map_ptr)
+            memcpy(rgba_map_ptr, rgba_map, sizeof(rgba_map[0]) * 4);
+    } else {
+        int plane;
+
+        dst_color[0] = RGB_TO_Y_CCIR(rgba_color[0], rgba_color[1], rgba_color[2]);
+        dst_color[1] = RGB_TO_U_CCIR(rgba_color[0], rgba_color[1], rgba_color[2], 0);
+        dst_color[2] = RGB_TO_V_CCIR(rgba_color[0], rgba_color[1], rgba_color[2], 0);
+        dst_color[3] = rgba_color[3];
+
+        for (plane = 0; plane < 4; plane++) {
+            int line_size;
+            int hsub1 = (plane == 1 || plane == 2) ? hsub : 0;
+
+            pixel_step[plane] = 1;
+            line_size = (w >> hsub1) * pixel_step[plane];
+            line[plane] = av_malloc(line_size);
+            memset(line[plane], dst_color[plane], line_size);
+        }
+    }
+
+    return 0;
+}
+
+void ff_draw_rectangle(uint8_t *dst[4], int dst_linesize[4],
+                       uint8_t *src[4], int pixelstep[4],
+                       int hsub, int vsub, int x, int y, int w, int h)
+{
+    int i, plane;
+    uint8_t *p;
+
+    for (plane = 0; plane < 4 && dst[plane]; plane++) {
+        int hsub1 = plane == 1 || plane == 2 ? hsub : 0;
+        int vsub1 = plane == 1 || plane == 2 ? vsub : 0;
+
+        p = dst[plane] + (y >> vsub1) * dst_linesize[plane];
+        for (i = 0; i < (h >> vsub1); i++) {
+            memcpy(p + (x >> hsub1) * pixelstep[plane],
+                   src[plane], (w >> hsub1) * pixelstep[plane]);
+            p += dst_linesize[plane];
+        }
+    }
+}
+
+void ff_copy_rectangle(uint8_t *dst[4], int dst_linesize[4],
+                       uint8_t *src[4], int src_linesize[4], int pixelstep[4],
+                       int hsub, int vsub, int x, int y, int y2, int w, int h)
+{
+    int i, plane;
+    uint8_t *p;
+
+    for (plane = 0; plane < 4 && dst[plane]; plane++) {
+        int hsub1 = plane == 1 || plane == 2 ? hsub : 0;
+        int vsub1 = plane == 1 || plane == 2 ? vsub : 0;
+
+        p = dst[plane] + (y >> vsub1) * dst_linesize[plane];
+        for (i = 0; i < (h >> vsub1); i++) {
+            memcpy(p + (x >> hsub1) * pixelstep[plane],
+                   src[plane] + src_linesize[plane]*(i+(y2>>vsub1)), (w >> hsub1) * pixelstep[plane]);
+            p += dst_linesize[plane];
+        }
+    }
+}
diff --git a/libavfilter/drawutils.h b/libavfilter/drawutils.h
new file mode 100644
index 0000000..7b11c06
--- /dev/null
+++ b/libavfilter/drawutils.h
@@ -0,0 +1,43 @@
+/*
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVFILTER_DRAWUTILS_H
+#define AVFILTER_DRAWUTILS_H
+
+/**
+ * @file
+ * misc drawing utilities
+ */
+
+#include <stdint.h>
+#include "libavutil/pixfmt.h"
+
+int ff_fill_line_with_color(uint8_t *line[4], int pixel_step[4], int w,
+                            uint8_t dst_color[4],
+                            enum PixelFormat pix_fmt, uint8_t rgba_color[4],
+                            int *is_packed_rgba, uint8_t rgba_map[4]);
+
+void ff_draw_rectangle(uint8_t *dst[4], int dst_linesize[4],
+                       uint8_t *src[4], int pixelstep[4],
+                       int hsub, int vsub, int x, int y, int w, int h);
+
+void ff_copy_rectangle(uint8_t *dst[4], int dst_linesize[4],
+                       uint8_t *src[4], int src_linesize[4], int pixelstep[4],
+                       int hsub, int vsub, int x, int y, int y2, int w, int h);
+
+#endif /* AVFILTER_DRAWUTILS_H */
diff --git a/libavfilter/formats.c b/libavfilter/formats.c
index 2a9bdb0..bb7b921 100644
--- a/libavfilter/formats.c
+++ b/libavfilter/formats.c
@@ -1,21 +1,21 @@
 /*
  * Filter layer - format negotiation
- * copyright (c) 2007 Bobby Bingham
+ * Copyright (c) 2007 Bobby Bingham
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -70,47 +70,50 @@ AVFilterFormats *avfilter_merge_formats(AVFilterFormats *a, AVFilterFormats *b)
     return ret;
 }
 
-AVFilterFormats *avfilter_make_format_list(const enum PixelFormat *pix_fmts)
+AVFilterFormats *avfilter_make_format_list(const int *fmts)
 {
     AVFilterFormats *formats;
     int count;
 
-    for (count = 0; pix_fmts[count] != PIX_FMT_NONE; count++)
+    for (count = 0; fmts[count] != -1; count++)
         ;
 
     formats               = av_mallocz(sizeof(AVFilterFormats));
     formats->formats      = av_malloc(sizeof(*formats->formats) * count);
     formats->format_count = count;
-    memcpy(formats->formats, pix_fmts, sizeof(*formats->formats) * count);
+    memcpy(formats->formats, fmts, sizeof(*formats->formats) * count);
 
     return formats;
 }
 
-int avfilter_add_colorspace(AVFilterFormats **avff, enum PixelFormat pix_fmt)
+int avfilter_add_format(AVFilterFormats **avff, int fmt)
 {
-    enum PixelFormat *pix_fmts;
+    int *fmts;
 
     if (!(*avff) && !(*avff = av_mallocz(sizeof(AVFilterFormats))))
         return AVERROR(ENOMEM);
 
-    pix_fmts = av_realloc((*avff)->formats,
-                          sizeof((*avff)->formats) * ((*avff)->format_count+1));
-    if (!pix_fmts)
+    fmts = av_realloc((*avff)->formats,
+                      sizeof((*avff)->formats) * ((*avff)->format_count+1));
+    if (!fmts)
         return AVERROR(ENOMEM);
 
-    (*avff)->formats = pix_fmts;
-    (*avff)->formats[(*avff)->format_count++] = pix_fmt;
+    (*avff)->formats = fmts;
+    (*avff)->formats[(*avff)->format_count++] = fmt;
     return 0;
 }
 
-AVFilterFormats *avfilter_all_colorspaces(void)
+AVFilterFormats *avfilter_all_formats(enum AVMediaType type)
 {
     AVFilterFormats *ret = NULL;
-    enum PixelFormat pix_fmt;
-
-    for (pix_fmt = 0; pix_fmt < PIX_FMT_NB; pix_fmt++)
-        if (!(av_pix_fmt_descriptors[pix_fmt].flags & PIX_FMT_HWACCEL))
-            avfilter_add_colorspace(&ret, pix_fmt);
+    int fmt;
+    int num_formats = type == AVMEDIA_TYPE_VIDEO ? PIX_FMT_NB    :
+                      type == AVMEDIA_TYPE_AUDIO ? AV_SAMPLE_FMT_NB : 0;
+
+    for (fmt = 0; fmt < num_formats; fmt++)
+        if ((type != AVMEDIA_TYPE_VIDEO) ||
+            (type == AVMEDIA_TYPE_VIDEO && !(av_pix_fmt_descriptors[fmt].flags & PIX_FMT_HWACCEL)))
+            avfilter_add_format(&ret, fmt);
 
     return ret;
 }
diff --git a/libavfilter/gradfun.h b/libavfilter/gradfun.h
new file mode 100644
index 0000000..6b192a3
--- /dev/null
+++ b/libavfilter/gradfun.h
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2010 Nolan Lum <nol888 at gmail.com>
+ * Copyright (c) 2009 Loren Merritt <lorenm at u.washignton.edu>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVFILTER_GRADFUN_H
+#define AVFILTER_GRADFUN_H
+
+#include "avfilter.h"
+
+/// Holds instance-specific information for gradfun.
+typedef struct {
+    int thresh;    ///< threshold for gradient algorithm
+    int radius;    ///< blur radius
+    int chroma_w;  ///< width of the chroma planes
+    int chroma_h;  ///< weight of the chroma planes
+    int chroma_r;  ///< blur radius for the chroma planes
+    uint16_t *buf; ///< holds image data for blur algorithm passed into filter.
+    /// DSP functions.
+    void (*filter_line) (uint8_t *dst, uint8_t *src, uint16_t *dc, int width, int thresh, const uint16_t *dithers);
+    void (*blur_line) (uint16_t *dc, uint16_t *buf, uint16_t *buf1, uint8_t *src, int src_linesize, int width);
+} GradFunContext;
+
+void ff_gradfun_filter_line_c(uint8_t *dst, uint8_t *src, uint16_t *dc, int width, int thresh, const uint16_t *dithers);
+void ff_gradfun_blur_line_c(uint16_t *dc, uint16_t *buf, uint16_t *buf1, uint8_t *src, int src_linesize, int width);
+
+void ff_gradfun_filter_line_mmx2(uint8_t *dst, uint8_t *src, uint16_t *dc, int width, int thresh, const uint16_t *dithers);
+void ff_gradfun_filter_line_ssse3(uint8_t *dst, uint8_t *src, uint16_t *dc, int width, int thresh, const uint16_t *dithers);
+
+void ff_gradfun_blur_line_sse2(uint16_t *dc, uint16_t *buf, uint16_t *buf1, uint8_t *src, int src_linesize, int width);
+
+#endif /* AVFILTER_GRADFUN_H */
diff --git a/libavfilter/graphparser.c b/libavfilter/graphparser.c
index c4a3bdf..dddb0a2 100644
--- a/libavfilter/graphparser.c
+++ b/libavfilter/graphparser.c
@@ -1,53 +1,59 @@
 /*
  * filter graph parser
- * copyright (c) 2008 Vitor Sessak
- * copyright (c) 2007 Bobby Bingham
+ * Copyright (c) 2008 Vitor Sessak
+ * Copyright (c) 2007 Bobby Bingham
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include <ctype.h>
 #include <string.h>
 
-#include "graphparser.h"
+#include "libavutil/avstring.h"
 #include "avfilter.h"
 #include "avfiltergraph.h"
-#include "parseutils.h"
 
 #define WHITESPACES " \n\t"
 
+/**
+ * Link two filters together.
+ *
+ * @see avfilter_link()
+ */
 static int link_filter(AVFilterContext *src, int srcpad,
                        AVFilterContext *dst, int dstpad,
                        AVClass *log_ctx)
 {
-    if(avfilter_link(src, srcpad, dst, dstpad)) {
+    int ret;
+    if ((ret = avfilter_link(src, srcpad, dst, dstpad))) {
         av_log(log_ctx, AV_LOG_ERROR,
-               "cannot create the link %s:%d -> %s:%d\n",
+               "Cannot create the link %s:%d -> %s:%d\n",
                src->filter->name, srcpad, dst->filter->name, dstpad);
-        return -1;
+        return ret;
     }
 
     return 0;
 }
 
 /**
- * Parse "[linkname]"
- * @param name a pointer (that need to be free'd after use) to the name between
- *        parenthesis
+ * Parse the name of a link, which has the format "[linkname]".
+ *
+ * @return a pointer (that need to be freed after use) to the name
+ * between parenthesis
  */
 static char *parse_link_name(const char **buf, AVClass *log_ctx)
 {
@@ -57,13 +63,13 @@ static char *parse_link_name(const char **buf, AVClass *log_ctx)
 
     name = av_get_token(buf, "]");
 
-    if(!name[0]) {
+    if (!name[0]) {
         av_log(log_ctx, AV_LOG_ERROR,
                "Bad (empty?) label found in the following: \"%s\".\n", start);
         goto fail;
     }
 
-    if(*(*buf)++ != ']') {
+    if (*(*buf)++ != ']') {
         av_log(log_ctx, AV_LOG_ERROR,
                "Mismatched '[' found in the following: \"%s\".\n", start);
     fail:
@@ -73,62 +79,90 @@ static char *parse_link_name(const char **buf, AVClass *log_ctx)
     return name;
 }
 
-static AVFilterContext *create_filter(AVFilterGraph *ctx, int index,
-                                      const char *filt_name, const char *args,
-                                      AVClass *log_ctx)
+/**
+ * Create an instance of a filter, initialize and insert it in the
+ * filtergraph in *ctx.
+ *
+ * @param ctx the filtergraph context
+ * @param put here a filter context in case of successful creation and configuration, NULL otherwise.
+ * @param index an index which is supposed to be unique for each filter instance added to the filtergraph
+ * @param filt_name the name of the filter to create
+ * @param args the arguments provided to the filter during its initialization
+ * @param log_ctx the log context to use
+ * @return 0 in case of success, a negative AVERROR code otherwise
+ */
+static int create_filter(AVFilterContext **filt_ctx, AVFilterGraph *ctx, int index,
+                         const char *filt_name, const char *args, AVClass *log_ctx)
 {
-    AVFilterContext *filt_ctx;
-
     AVFilter *filt;
     char inst_name[30];
+    char tmp_args[256];
+    int ret;
 
-    snprintf(inst_name, sizeof(inst_name), "Parsed filter %d", index);
+    snprintf(inst_name, sizeof(inst_name), "Parsed filter %d %s", index, filt_name);
 
     filt = avfilter_get_by_name(filt_name);
 
-    if(!filt) {
+    if (!filt) {
         av_log(log_ctx, AV_LOG_ERROR,
-               "no such filter: '%s'\n", filt_name);
-        return NULL;
+               "No such filter: '%s'\n", filt_name);
+        return AVERROR(EINVAL);
     }
 
-    filt_ctx = avfilter_open(filt, inst_name);
-    if(!filt_ctx) {
+    ret = avfilter_open(filt_ctx, filt, inst_name);
+    if (!*filt_ctx) {
         av_log(log_ctx, AV_LOG_ERROR,
-               "error creating filter '%s'\n", filt_name);
-        return NULL;
+               "Error creating filter '%s'\n", filt_name);
+        return ret;
     }
 
-    if(avfilter_graph_add_filter(ctx, filt_ctx) < 0) {
-        avfilter_destroy(filt_ctx);
-        return NULL;
+    if ((ret = avfilter_graph_add_filter(ctx, *filt_ctx)) < 0) {
+        avfilter_free(*filt_ctx);
+        return ret;
     }
 
-    if(avfilter_init_filter(filt_ctx, args, NULL)) {
+    if (!strcmp(filt_name, "scale") && !strstr(args, "flags")) {
+        snprintf(tmp_args, sizeof(tmp_args), "%s:%s",
+                 args, ctx->scale_sws_opts);
+        args = tmp_args;
+    }
+
+    if ((ret = avfilter_init_filter(*filt_ctx, args, NULL)) < 0) {
         av_log(log_ctx, AV_LOG_ERROR,
-               "error initializing filter '%s' with args '%s'\n", filt_name, args);
-        return NULL;
+               "Error initializing filter '%s' with args '%s'\n", filt_name, args);
+        return ret;
     }
 
-    return filt_ctx;
+    return 0;
 }
 
 /**
- * Parse "filter=params"
+ * Parse a string of the form FILTER_NAME[=PARAMS], and create a
+ * corresponding filter instance which is added to graph with
+ * create_filter().
+ *
+ * @param filt_ctx put here a pointer to the created filter context on
+ * success, NULL otherwise
+ * @param buf pointer to the buffer to parse, *buf will be updated to
+ * point to the char next after the parsed string
+ * @param index an index which is assigned to the created filter
+ * instance, and which is supposed to be unique for each filter
+ * instance added to the filtergraph
+ * @return 0 in case of success, a negative AVERROR code otherwise
  */
-static AVFilterContext *parse_filter(const char **buf, AVFilterGraph *graph,
-                                     int index, AVClass *log_ctx)
+static int parse_filter(AVFilterContext **filt_ctx, const char **buf, AVFilterGraph *graph,
+                        int index, AVClass *log_ctx)
 {
     char *opts = NULL;
     char *name = av_get_token(buf, "=,;[\n");
-    AVFilterContext *ret;
+    int ret;
 
-    if(**buf == '=') {
+    if (**buf == '=') {
         (*buf)++;
         opts = av_get_token(buf, "[],;\n");
     }
 
-    ret = create_filter(graph, index, name, opts, log_ctx);
+    ret = create_filter(filt_ctx, graph, index, name, opts, log_ctx);
     av_free(name);
     av_free(opts);
     return ret;
@@ -136,7 +170,7 @@ static AVFilterContext *parse_filter(const char **buf, AVFilterGraph *graph,
 
 static void free_inout(AVFilterInOut *head)
 {
-    while(head) {
+    while (head) {
         AVFilterInOut *next = head->next;
         av_free(head->name);
         av_free(head);
@@ -148,12 +182,12 @@ static AVFilterInOut *extract_inout(const char *label, AVFilterInOut **links)
 {
     AVFilterInOut *ret;
 
-    while(*links && strcmp((*links)->name, label))
+    while (*links && strcmp((*links)->name, label))
         links = &((*links)->next);
 
     ret = *links;
 
-    if(ret)
+    if (ret)
         *links = ret->next;
 
     return ret;
@@ -165,46 +199,48 @@ static void insert_inout(AVFilterInOut **inouts, AVFilterInOut *element)
     *inouts = element;
 }
 
-static int link_filter_inouts(AVFilterContext *filter,
+static int link_filter_inouts(AVFilterContext *filt_ctx,
                               AVFilterInOut **curr_inputs,
                               AVFilterInOut **open_inputs, AVClass *log_ctx)
 {
-    int pad = filter->input_count;
+    int pad = filt_ctx->input_count, ret;
 
-    while(pad--) {
+    while (pad--) {
         AVFilterInOut *p = *curr_inputs;
-        if(!p) {
+        if (!p) {
             av_log(log_ctx, AV_LOG_ERROR,
                    "Not enough inputs specified for the \"%s\" filter.\n",
-                   filter->filter->name);
-            return -1;
+                   filt_ctx->filter->name);
+            return AVERROR(EINVAL);
         }
 
         *curr_inputs = (*curr_inputs)->next;
 
-        if(p->filter) {
-            if(link_filter(p->filter, p->pad_idx, filter, pad, log_ctx))
-                return -1;
+        if (p->filter_ctx) {
+            if ((ret = link_filter(p->filter_ctx, p->pad_idx, filt_ctx, pad, log_ctx)) < 0)
+                return ret;
             av_free(p->name);
             av_free(p);
         } else {
-            p->filter = filter;
+            p->filter_ctx = filt_ctx;
             p->pad_idx = pad;
             insert_inout(open_inputs, p);
         }
     }
 
-    if(*curr_inputs) {
+    if (*curr_inputs) {
         av_log(log_ctx, AV_LOG_ERROR,
                "Too many inputs specified for the \"%s\" filter.\n",
-               filter->filter->name);
-        return -1;
+               filt_ctx->filter->name);
+        return AVERROR(EINVAL);
     }
 
-    pad = filter->output_count;
-    while(pad--) {
+    pad = filt_ctx->output_count;
+    while (pad--) {
         AVFilterInOut *currlinkn = av_mallocz(sizeof(AVFilterInOut));
-        currlinkn->filter  = filter;
+        if (!currlinkn)
+            return AVERROR(ENOMEM);
+        currlinkn->filter_ctx  = filt_ctx;
         currlinkn->pad_idx = pad;
         insert_inout(curr_inputs, currlinkn);
     }
@@ -217,21 +253,22 @@ static int parse_inputs(const char **buf, AVFilterInOut **curr_inputs,
 {
     int pad = 0;
 
-    while(**buf == '[') {
+    while (**buf == '[') {
         char *name = parse_link_name(buf, log_ctx);
         AVFilterInOut *match;
 
-        if(!name)
-            return -1;
+        if (!name)
+            return AVERROR(EINVAL);
 
         /* First check if the label is not in the open_outputs list */
         match = extract_inout(name, open_outputs);
 
-        if(match) {
+        if (match) {
             av_free(name);
         } else {
             /* Not in the list, so add it as an input */
-            match = av_mallocz(sizeof(AVFilterInOut));
+            if (!(match = av_mallocz(sizeof(AVFilterInOut))))
+                return AVERROR(ENOMEM);
             match->name    = name;
             match->pad_idx = pad;
         }
@@ -249,25 +286,31 @@ static int parse_outputs(const char **buf, AVFilterInOut **curr_inputs,
                          AVFilterInOut **open_inputs,
                          AVFilterInOut **open_outputs, AVClass *log_ctx)
 {
-    int pad = 0;
+    int ret, pad = 0;
 
-    while(**buf == '[') {
+    while (**buf == '[') {
         char *name = parse_link_name(buf, log_ctx);
         AVFilterInOut *match;
 
         AVFilterInOut *input = *curr_inputs;
+        if (!input) {
+            av_log(log_ctx, AV_LOG_ERROR,
+                   "No output pad can be associated to link label '%s'.\n",
+                   name);
+            return AVERROR(EINVAL);
+        }
         *curr_inputs = (*curr_inputs)->next;
 
-        if(!name)
-            return -1;
+        if (!name)
+            return AVERROR(EINVAL);
 
         /* First check if the label is not in the open_inputs list */
         match = extract_inout(name, open_inputs);
 
-        if(match) {
-            if(link_filter(input->filter, input->pad_idx,
-                           match->filter, match->pad_idx, log_ctx) < 0)
-                return -1;
+        if (match) {
+            if ((ret = link_filter(input->filter_ctx, input->pad_idx,
+                                   match->filter_ctx, match->pad_idx, log_ctx)) < 0)
+                return ret;
             av_free(match->name);
             av_free(name);
             av_free(match);
@@ -288,70 +331,73 @@ int avfilter_graph_parse(AVFilterGraph *graph, const char *filters,
                          AVFilterInOut *open_inputs,
                          AVFilterInOut *open_outputs, AVClass *log_ctx)
 {
-    int index = 0;
+    int index = 0, ret;
     char chr = 0;
 
     AVFilterInOut *curr_inputs = NULL;
 
     do {
         AVFilterContext *filter;
+        const char *filterchain = filters;
         filters += strspn(filters, WHITESPACES);
 
-        if(parse_inputs(&filters, &curr_inputs, &open_outputs, log_ctx) < 0)
+        if ((ret = parse_inputs(&filters, &curr_inputs, &open_outputs, log_ctx)) < 0)
             goto fail;
 
-        filter = parse_filter(&filters, graph, index, log_ctx);
-
-        if(!filter)
+        if ((ret = parse_filter(&filter, &filters, graph, index, log_ctx)) < 0)
             goto fail;
 
-        if(filter->input_count == 1 && !curr_inputs && !index) {
+        if (filter->input_count == 1 && !curr_inputs && !index) {
             /* First input can be omitted if it is "[in]" */
             const char *tmp = "[in]";
-            if(parse_inputs(&tmp, &curr_inputs, &open_outputs, log_ctx) < 0)
+            if ((ret = parse_inputs(&tmp, &curr_inputs, &open_outputs, log_ctx)) < 0)
                 goto fail;
         }
 
-        if(link_filter_inouts(filter, &curr_inputs, &open_inputs, log_ctx) < 0)
+        if ((ret = link_filter_inouts(filter, &curr_inputs, &open_inputs, log_ctx)) < 0)
             goto fail;
 
-        if(parse_outputs(&filters, &curr_inputs, &open_inputs, &open_outputs,
-                         log_ctx) < 0)
+        if ((ret = parse_outputs(&filters, &curr_inputs, &open_inputs, &open_outputs,
+                                 log_ctx)) < 0)
             goto fail;
 
         filters += strspn(filters, WHITESPACES);
         chr = *filters++;
 
-        if(chr == ';' && curr_inputs) {
+        if (chr == ';' && curr_inputs) {
             av_log(log_ctx, AV_LOG_ERROR,
-                   "Could not find a output to link when parsing \"%s\"\n",
-                   filters - 1);
+                   "Invalid filterchain containing an unlabelled output pad: \"%s\"\n",
+                   filterchain);
+            ret = AVERROR(EINVAL);
             goto fail;
         }
         index++;
-    } while(chr == ',' || chr == ';');
+    } while (chr == ',' || chr == ';');
 
     if (chr) {
         av_log(log_ctx, AV_LOG_ERROR,
                "Unable to parse graph description substring: \"%s\"\n",
                filters - 1);
+        ret = AVERROR(EINVAL);
         goto fail;
     }
 
-    if(open_inputs && !strcmp(open_inputs->name, "out") && curr_inputs) {
+    if (open_inputs && !strcmp(open_inputs->name, "out") && curr_inputs) {
         /* Last output can be omitted if it is "[out]" */
         const char *tmp = "[out]";
-        if(parse_outputs(&tmp, &curr_inputs, &open_inputs,
-                         &open_outputs, log_ctx) < 0)
+        if ((ret = parse_outputs(&tmp, &curr_inputs, &open_inputs, &open_outputs,
+                                 log_ctx)) < 0)
             goto fail;
     }
 
     return 0;
 
  fail:
-    avfilter_graph_destroy(graph);
+    for (; graph->filter_count > 0; graph->filter_count--)
+        avfilter_free(graph->filters[graph->filter_count - 1]);
+    av_freep(&graph->filters);
     free_inout(open_inputs);
     free_inout(open_outputs);
     free_inout(curr_inputs);
-    return -1;
+    return ret;
 }
diff --git a/libavfilter/graphparser.h b/libavfilter/graphparser.h
deleted file mode 100644
index e69f295..0000000
--- a/libavfilter/graphparser.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Filter graph parser
- * copyright (c) 2007 Bobby Bingham
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-#ifndef AVFILTER_GRAPHPARSER_H
-#define AVFILTER_GRAPHPARSER_H
-
-#include "avfilter.h"
-#include "avfiltergraph.h"
-
-/**
- * A linked-list of the inputs/outputs of the filter chain.
- */
-typedef struct AVFilterInOut {
-    char *name;
-    AVFilterContext *filter;
-    int pad_idx;
-
-    struct AVFilterInOut *next;
-} AVFilterInOut;
-
-/**
- * Adds a graph described by a string to a graph.
- *
- * @param graph   the filter graph where to link the parsed graph context
- * @param filters string to be parsed
- * @param inputs  linked list to the inputs of the graph
- * @param outputs linked list to the outputs of the graph
- * @return        zero on success, -1 on error
- */
-int avfilter_graph_parse(AVFilterGraph *graph, const char *filters,
-                         AVFilterInOut *inputs, AVFilterInOut *outputs,
-                         AVClass *log_ctx);
-
-#endif  /* AVFILTER_GRAPHPARSER_H */
diff --git a/libavfilter/internal.h b/libavfilter/internal.h
new file mode 100644
index 0000000..0406a0d
--- /dev/null
+++ b/libavfilter/internal.h
@@ -0,0 +1,55 @@
+/*
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVFILTER_INTERNAL_H
+#define AVFILTER_INTERNAL_H
+
+/**
+ * @file
+ * internal API functions
+ */
+
+#include "avfilter.h"
+#include "avfiltergraph.h"
+
+/**
+ * Check for the validity of graph.
+ *
+ * A graph is considered valid if all its input and output pads are
+ * connected.
+ *
+ * @return 0 in case of success, a negative value otherwise
+ */
+int ff_avfilter_graph_check_validity(AVFilterGraph *graphctx, AVClass *log_ctx);
+
+/**
+ * Configure all the links of graphctx.
+ *
+ * @return 0 in case of success, a negative value otherwise
+ */
+int ff_avfilter_graph_config_links(AVFilterGraph *graphctx, AVClass *log_ctx);
+
+/**
+ * Configure the formats of all the links in the graph.
+ */
+int ff_avfilter_graph_config_formats(AVFilterGraph *graphctx, AVClass *log_ctx);
+
+/** default handler for freeing audio/video buffer when there are no references left */
+void ff_avfilter_default_free_buffer(AVFilterBuffer *buf);
+
+#endif  /* AVFILTER_INTERNAL_H */
diff --git a/libavfilter/parseutils.c b/libavfilter/parseutils.c
deleted file mode 100644
index 222ac73..0000000
--- a/libavfilter/parseutils.c
+++ /dev/null
@@ -1,475 +0,0 @@
-/*
- * copyright (c) 2009 Stefano Sabatini
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-/**
- * @file
- * parsing utils
- */
-
-#include <strings.h>
-#include "libavutil/avutil.h"
-#include "libavutil/random_seed.h"
-#include "parseutils.h"
-
-#define WHITESPACES " \n\t"
-
-char *av_get_token(const char **buf, const char *term)
-{
-    char *out = av_malloc(strlen(*buf) + 1);
-    char *ret= out, *end= out;
-    const char *p = *buf;
-    p += strspn(p, WHITESPACES);
-
-    while(*p && !strspn(p, term)) {
-        char c = *p++;
-        if(c == '\\' && *p){
-            *out++ = *p++;
-            end= out;
-        }else if(c == '\''){
-            while(*p && *p != '\'')
-                *out++ = *p++;
-            if(*p){
-                p++;
-                end= out;
-            }
-        }else{
-            *out++ = c;
-        }
-    }
-
-    do{
-        *out-- = 0;
-    }while(out >= end && strspn(out, WHITESPACES));
-
-    *buf = p;
-
-    return ret;
-}
-
-typedef struct {
-    const char *name;            ///< a string representing the name of the color
-    uint8_t     rgba_color[4];   ///< RGBA values for the color
-} ColorEntry;
-
-static ColorEntry color_table[] = {
-    { "AliceBlue",            { 0xF0, 0xF8, 0xFF } },
-    { "AntiqueWhite",         { 0xFA, 0xEB, 0xD7 } },
-    { "Aqua",                 { 0x00, 0xFF, 0xFF } },
-    { "Aquamarine",           { 0x7F, 0xFF, 0xD4 } },
-    { "Azure",                { 0xF0, 0xFF, 0xFF } },
-    { "Beige",                { 0xF5, 0xF5, 0xDC } },
-    { "Bisque",               { 0xFF, 0xE4, 0xC4 } },
-    { "Black",                { 0x00, 0x00, 0x00 } },
-    { "BlanchedAlmond",       { 0xFF, 0xEB, 0xCD } },
-    { "Blue",                 { 0x00, 0x00, 0xFF } },
-    { "BlueViolet",           { 0x8A, 0x2B, 0xE2 } },
-    { "Brown",                { 0xA5, 0x2A, 0x2A } },
-    { "BurlyWood",            { 0xDE, 0xB8, 0x87 } },
-    { "CadetBlue",            { 0x5F, 0x9E, 0xA0 } },
-    { "Chartreuse",           { 0x7F, 0xFF, 0x00 } },
-    { "Chocolate",            { 0xD2, 0x69, 0x1E } },
-    { "Coral",                { 0xFF, 0x7F, 0x50 } },
-    { "CornflowerBlue",       { 0x64, 0x95, 0xED } },
-    { "Cornsilk",             { 0xFF, 0xF8, 0xDC } },
-    { "Crimson",              { 0xDC, 0x14, 0x3C } },
-    { "Cyan",                 { 0x00, 0xFF, 0xFF } },
-    { "DarkBlue",             { 0x00, 0x00, 0x8B } },
-    { "DarkCyan",             { 0x00, 0x8B, 0x8B } },
-    { "DarkGoldenRod",        { 0xB8, 0x86, 0x0B } },
-    { "DarkGray",             { 0xA9, 0xA9, 0xA9 } },
-    { "DarkGreen",            { 0x00, 0x64, 0x00 } },
-    { "DarkKhaki",            { 0xBD, 0xB7, 0x6B } },
-    { "DarkMagenta",          { 0x8B, 0x00, 0x8B } },
-    { "DarkOliveGreen",       { 0x55, 0x6B, 0x2F } },
-    { "Darkorange",           { 0xFF, 0x8C, 0x00 } },
-    { "DarkOrchid",           { 0x99, 0x32, 0xCC } },
-    { "DarkRed",              { 0x8B, 0x00, 0x00 } },
-    { "DarkSalmon",           { 0xE9, 0x96, 0x7A } },
-    { "DarkSeaGreen",         { 0x8F, 0xBC, 0x8F } },
-    { "DarkSlateBlue",        { 0x48, 0x3D, 0x8B } },
-    { "DarkSlateGray",        { 0x2F, 0x4F, 0x4F } },
-    { "DarkTurquoise",        { 0x00, 0xCE, 0xD1 } },
-    { "DarkViolet",           { 0x94, 0x00, 0xD3 } },
-    { "DeepPink",             { 0xFF, 0x14, 0x93 } },
-    { "DeepSkyBlue",          { 0x00, 0xBF, 0xFF } },
-    { "DimGray",              { 0x69, 0x69, 0x69 } },
-    { "DodgerBlue",           { 0x1E, 0x90, 0xFF } },
-    { "FireBrick",            { 0xB2, 0x22, 0x22 } },
-    { "FloralWhite",          { 0xFF, 0xFA, 0xF0 } },
-    { "ForestGreen",          { 0x22, 0x8B, 0x22 } },
-    { "Fuchsia",              { 0xFF, 0x00, 0xFF } },
-    { "Gainsboro",            { 0xDC, 0xDC, 0xDC } },
-    { "GhostWhite",           { 0xF8, 0xF8, 0xFF } },
-    { "Gold",                 { 0xFF, 0xD7, 0x00 } },
-    { "GoldenRod",            { 0xDA, 0xA5, 0x20 } },
-    { "Gray",                 { 0x80, 0x80, 0x80 } },
-    { "Green",                { 0x00, 0x80, 0x00 } },
-    { "GreenYellow",          { 0xAD, 0xFF, 0x2F } },
-    { "HoneyDew",             { 0xF0, 0xFF, 0xF0 } },
-    { "HotPink",              { 0xFF, 0x69, 0xB4 } },
-    { "IndianRed",            { 0xCD, 0x5C, 0x5C } },
-    { "Indigo",               { 0x4B, 0x00, 0x82 } },
-    { "Ivory",                { 0xFF, 0xFF, 0xF0 } },
-    { "Khaki",                { 0xF0, 0xE6, 0x8C } },
-    { "Lavender",             { 0xE6, 0xE6, 0xFA } },
-    { "LavenderBlush",        { 0xFF, 0xF0, 0xF5 } },
-    { "LawnGreen",            { 0x7C, 0xFC, 0x00 } },
-    { "LemonChiffon",         { 0xFF, 0xFA, 0xCD } },
-    { "LightBlue",            { 0xAD, 0xD8, 0xE6 } },
-    { "LightCoral",           { 0xF0, 0x80, 0x80 } },
-    { "LightCyan",            { 0xE0, 0xFF, 0xFF } },
-    { "LightGoldenRodYellow", { 0xFA, 0xFA, 0xD2 } },
-    { "LightGrey",            { 0xD3, 0xD3, 0xD3 } },
-    { "LightGreen",           { 0x90, 0xEE, 0x90 } },
-    { "LightPink",            { 0xFF, 0xB6, 0xC1 } },
-    { "LightSalmon",          { 0xFF, 0xA0, 0x7A } },
-    { "LightSeaGreen",        { 0x20, 0xB2, 0xAA } },
-    { "LightSkyBlue",         { 0x87, 0xCE, 0xFA } },
-    { "LightSlateGray",       { 0x77, 0x88, 0x99 } },
-    { "LightSteelBlue",       { 0xB0, 0xC4, 0xDE } },
-    { "LightYellow",          { 0xFF, 0xFF, 0xE0 } },
-    { "Lime",                 { 0x00, 0xFF, 0x00 } },
-    { "LimeGreen",            { 0x32, 0xCD, 0x32 } },
-    { "Linen",                { 0xFA, 0xF0, 0xE6 } },
-    { "Magenta",              { 0xFF, 0x00, 0xFF } },
-    { "Maroon",               { 0x80, 0x00, 0x00 } },
-    { "MediumAquaMarine",     { 0x66, 0xCD, 0xAA } },
-    { "MediumBlue",           { 0x00, 0x00, 0xCD } },
-    { "MediumOrchid",         { 0xBA, 0x55, 0xD3 } },
-    { "MediumPurple",         { 0x93, 0x70, 0xD8 } },
-    { "MediumSeaGreen",       { 0x3C, 0xB3, 0x71 } },
-    { "MediumSlateBlue",      { 0x7B, 0x68, 0xEE } },
-    { "MediumSpringGreen",    { 0x00, 0xFA, 0x9A } },
-    { "MediumTurquoise",      { 0x48, 0xD1, 0xCC } },
-    { "MediumVioletRed",      { 0xC7, 0x15, 0x85 } },
-    { "MidnightBlue",         { 0x19, 0x19, 0x70 } },
-    { "MintCream",            { 0xF5, 0xFF, 0xFA } },
-    { "MistyRose",            { 0xFF, 0xE4, 0xE1 } },
-    { "Moccasin",             { 0xFF, 0xE4, 0xB5 } },
-    { "NavajoWhite",          { 0xFF, 0xDE, 0xAD } },
-    { "Navy",                 { 0x00, 0x00, 0x80 } },
-    { "OldLace",              { 0xFD, 0xF5, 0xE6 } },
-    { "Olive",                { 0x80, 0x80, 0x00 } },
-    { "OliveDrab",            { 0x6B, 0x8E, 0x23 } },
-    { "Orange",               { 0xFF, 0xA5, 0x00 } },
-    { "OrangeRed",            { 0xFF, 0x45, 0x00 } },
-    { "Orchid",               { 0xDA, 0x70, 0xD6 } },
-    { "PaleGoldenRod",        { 0xEE, 0xE8, 0xAA } },
-    { "PaleGreen",            { 0x98, 0xFB, 0x98 } },
-    { "PaleTurquoise",        { 0xAF, 0xEE, 0xEE } },
-    { "PaleVioletRed",        { 0xD8, 0x70, 0x93 } },
-    { "PapayaWhip",           { 0xFF, 0xEF, 0xD5 } },
-    { "PeachPuff",            { 0xFF, 0xDA, 0xB9 } },
-    { "Peru",                 { 0xCD, 0x85, 0x3F } },
-    { "Pink",                 { 0xFF, 0xC0, 0xCB } },
-    { "Plum",                 { 0xDD, 0xA0, 0xDD } },
-    { "PowderBlue",           { 0xB0, 0xE0, 0xE6 } },
-    { "Purple",               { 0x80, 0x00, 0x80 } },
-    { "Red",                  { 0xFF, 0x00, 0x00 } },
-    { "RosyBrown",            { 0xBC, 0x8F, 0x8F } },
-    { "RoyalBlue",            { 0x41, 0x69, 0xE1 } },
-    { "SaddleBrown",          { 0x8B, 0x45, 0x13 } },
-    { "Salmon",               { 0xFA, 0x80, 0x72 } },
-    { "SandyBrown",           { 0xF4, 0xA4, 0x60 } },
-    { "SeaGreen",             { 0x2E, 0x8B, 0x57 } },
-    { "SeaShell",             { 0xFF, 0xF5, 0xEE } },
-    { "Sienna",               { 0xA0, 0x52, 0x2D } },
-    { "Silver",               { 0xC0, 0xC0, 0xC0 } },
-    { "SkyBlue",              { 0x87, 0xCE, 0xEB } },
-    { "SlateBlue",            { 0x6A, 0x5A, 0xCD } },
-    { "SlateGray",            { 0x70, 0x80, 0x90 } },
-    { "Snow",                 { 0xFF, 0xFA, 0xFA } },
-    { "SpringGreen",          { 0x00, 0xFF, 0x7F } },
-    { "SteelBlue",            { 0x46, 0x82, 0xB4 } },
-    { "Tan",                  { 0xD2, 0xB4, 0x8C } },
-    { "Teal",                 { 0x00, 0x80, 0x80 } },
-    { "Thistle",              { 0xD8, 0xBF, 0xD8 } },
-    { "Tomato",               { 0xFF, 0x63, 0x47 } },
-    { "Turquoise",            { 0x40, 0xE0, 0xD0 } },
-    { "Violet",               { 0xEE, 0x82, 0xEE } },
-    { "Wheat",                { 0xF5, 0xDE, 0xB3 } },
-    { "White",                { 0xFF, 0xFF, 0xFF } },
-    { "WhiteSmoke",           { 0xF5, 0xF5, 0xF5 } },
-    { "Yellow",               { 0xFF, 0xFF, 0x00 } },
-    { "YellowGreen",          { 0x9A, 0xCD, 0x32 } },
-};
-
-static int color_table_compare(const void *lhs, const void *rhs)
-{
-    return strcasecmp(lhs, ((const ColorEntry *)rhs)->name);
-}
-
-int av_parse_color(uint8_t *rgba_color, const char *color_string, void *log_ctx)
-{
-    if (!strcasecmp(color_string, "random") || !strcasecmp(color_string, "bikeshed")) {
-        int rgba = ff_random_get_seed();
-        rgba_color[0] = rgba >> 24;
-        rgba_color[1] = rgba >> 16;
-        rgba_color[2] = rgba >> 8;
-        rgba_color[3] = rgba;
-    } else
-    if (!strncmp(color_string, "0x", 2)) {
-        char *tail;
-        int len = strlen(color_string);
-        unsigned int rgba = strtoul(color_string, &tail, 16);
-
-        if (*tail || (len != 8 && len != 10)) {
-            av_log(log_ctx, AV_LOG_ERROR, "Invalid 0xRRGGBB[AA] color string: '%s'\n", color_string);
-            return -1;
-        }
-        if (len == 10) {
-            rgba_color[3] = rgba;
-            rgba >>= 8;
-        }
-        rgba_color[0] = rgba >> 16;
-        rgba_color[1] = rgba >> 8;
-        rgba_color[2] = rgba;
-    } else {
-        const ColorEntry *entry = bsearch(color_string,
-                                          color_table,
-                                          FF_ARRAY_ELEMS(color_table),
-                                          sizeof(ColorEntry),
-                                          color_table_compare);
-        if (!entry) {
-            av_log(log_ctx, AV_LOG_ERROR, "Cannot find color '%s'\n", color_string);
-            return -1;
-        }
-        memcpy(rgba_color, entry->rgba_color, 4);
-    }
-
-    return 0;
-}
-
-/**
- * Stores the value in the field in ctx that is named like key.
- * ctx must be an AVClass context, storing is done using AVOptions.
- *
- * @param buf the string to parse, buf will be updated to point at the
- * separator just after the parsed key/value pair
- * @param key_val_sep a 0-terminated list of characters used to
- * separate key from value
- * @param pairs_sep a 0-terminated list of characters used to separate
- * two pairs from each other
- * @return 0 if the key/value pair has been successfully parsed and
- * set, or a negative value corresponding to an AVERROR code in case
- * of error:
- * AVERROR(EINVAL) if the key/value pair cannot be parsed,
- * the error code issued by av_set_string3() if the key/value pair
- * cannot be set
- */
-static int parse_key_value_pair(void *ctx, const char **buf,
-                                const char *key_val_sep, const char *pairs_sep)
-{
-    char *key = av_get_token(buf, key_val_sep);
-    char *val;
-    int ret;
-
-    if (*key && strspn(*buf, key_val_sep)) {
-        (*buf)++;
-        val = av_get_token(buf, pairs_sep);
-    } else {
-        av_log(ctx, AV_LOG_ERROR, "Missing key or no key/value separator found after key '%s'\n", key);
-        av_free(key);
-        return AVERROR(EINVAL);
-    }
-
-    av_log(ctx, AV_LOG_DEBUG, "Setting value '%s' for key '%s'\n", val, key);
-
-    ret = av_set_string3(ctx, key, val, 1, NULL);
-    if (ret == AVERROR(ENOENT))
-        av_log(ctx, AV_LOG_ERROR, "Key '%s' not found.\n", key);
-
-    av_free(key);
-    av_free(val);
-    return ret;
-}
-
-int av_set_options_string(void *ctx, const char *opts,
-                          const char *key_val_sep, const char *pairs_sep)
-{
-    int ret, count = 0;
-
-    while (*opts) {
-        if ((ret = parse_key_value_pair(ctx, &opts, key_val_sep, pairs_sep)) < 0)
-            return ret;
-        count++;
-
-        if (*opts)
-            opts++;
-    }
-
-    return count;
-}
-
-#ifdef TEST
-
-#undef printf
-
-typedef struct TestContext
-{
-    const AVClass *class;
-    int num;
-    int toggle;
-    char *string;
-    int flags;
-    AVRational rational;
-} TestContext;
-
-#define OFFSET(x) offsetof(TestContext, x)
-
-#define TEST_FLAG_COOL 01
-#define TEST_FLAG_LAME 02
-#define TEST_FLAG_MU   04
-
-static const AVOption test_options[]= {
-{"num",      "set num",        OFFSET(num),      FF_OPT_TYPE_INT,      0,              0,        100                 },
-{"toggle",   "set toggle",     OFFSET(toggle),   FF_OPT_TYPE_INT,      0,              0,        1                   },
-{"rational", "set rational",   OFFSET(rational), FF_OPT_TYPE_RATIONAL, 0,              0,        10                  },
-{"string",   "set string",     OFFSET(string),   FF_OPT_TYPE_STRING,   0,              CHAR_MIN, CHAR_MAX            },
-{"flags",    "set flags",      OFFSET(flags),    FF_OPT_TYPE_FLAGS,    0,              0,        INT_MAX, 0, "flags" },
-{"cool",     "set cool flag ", 0,                FF_OPT_TYPE_CONST,    TEST_FLAG_COOL, INT_MIN,  INT_MAX, 0, "flags" },
-{"lame",     "set lame flag ", 0,                FF_OPT_TYPE_CONST,    TEST_FLAG_LAME, INT_MIN,  INT_MAX, 0, "flags" },
-{"mu",       "set mu flag ",   0,                FF_OPT_TYPE_CONST,    TEST_FLAG_MU,   INT_MIN,  INT_MAX, 0, "flags" },
-{NULL},
-};
-
-static const char *test_get_name(void *ctx)
-{
-    return "test";
-}
-
-static const AVClass test_class = {
-    "TestContext",
-    test_get_name,
-    test_options
-};
-
-int main(void)
-{
-    int i;
-
-    const char *strings[] = {
-        "''",
-        "",
-        ":",
-        "\\",
-        "'",
-        "    ''    :",
-        "    ''  ''  :",
-        "foo   '' :",
-        "'foo'",
-        "foo     ",
-        "foo\\",
-        "foo':  blah:blah",
-        "foo\\:  blah:blah",
-        "foo\'",
-        "'foo :  '  :blahblah",
-        "\\ :blah",
-        "     foo",
-        "      foo       ",
-        "      foo     \\ ",
-        "foo ':blah",
-        " foo   bar    :   blahblah",
-        "\\f\\o\\o",
-        "'foo : \\ \\  '   : blahblah",
-        "'\\fo\\o:': blahblah",
-        "\\'fo\\o\\:':  foo  '  :blahblah"
-    };
-
-    for (i=0; i < FF_ARRAY_ELEMS(strings); i++) {
-        const char *p= strings[i];
-        printf("|%s|", p);
-        printf(" -> |%s|", av_get_token(&p, ":"));
-        printf(" + |%s|\n", p);
-    }
-
-    printf("\nTesting av_parse_color()\n");
-    {
-        uint8_t rgba[4];
-        const char *color_names[] = {
-            "bikeshed",
-            "RaNdOm",
-            "foo",
-            "red",
-            "Red ",
-            "RED",
-            "Violet",
-            "Yellow",
-            "Red",
-            "0x000000",
-            "0x0000000",
-            "0xff000000",
-            "0x3e34ff",
-            "0x3e34ffaa",
-            "0xffXXee",
-            "0xfoobar",
-            "0xffffeeeeeeee",
-        };
-
-        av_log_set_level(AV_LOG_DEBUG);
-
-        for (int i = 0;  i < FF_ARRAY_ELEMS(color_names); i++) {
-            if (av_parse_color(rgba, color_names[i], NULL) >= 0)
-                printf("%s -> R(%d) G(%d) B(%d) A(%d)\n", color_names[i], rgba[0], rgba[1], rgba[2], rgba[3]);
-        }
-    }
-
-    printf("\nTesting av_set_options_string()\n");
-    {
-        TestContext test_ctx;
-        const char *options[] = {
-            "",
-            ":",
-            "=",
-            "foo=:",
-            ":=foo",
-            "=foo",
-            "foo=",
-            "foo",
-            "foo=val",
-            "foo==val",
-            "toggle=:",
-            "string=:",
-            "toggle=1 : foo",
-            "toggle=100",
-            "toggle==1",
-            "flags=+mu-lame : num=42: toggle=0",
-            "num=42 : string=blahblah",
-            "rational=0 : rational=1/2 : rational=1/-1",
-            "rational=-1/0",
-        };
-
-        test_ctx.class = &test_class;
-        av_opt_set_defaults2(&test_ctx, 0, 0);
-        test_ctx.string = av_strdup("default");
-
-        av_log_set_level(AV_LOG_DEBUG);
-
-        for (i=0; i < FF_ARRAY_ELEMS(options); i++) {
-            av_log(&test_ctx, AV_LOG_DEBUG, "Setting options string '%s'\n", options[i]);
-            if (av_set_options_string(&test_ctx, options[i], "=", ":") < 0)
-                av_log(&test_ctx, AV_LOG_ERROR, "Error setting options string: '%s'\n", options[i]);
-            printf("\n");
-        }
-    }
-
-    return 0;
-}
-
-#endif
diff --git a/libavfilter/parseutils.h b/libavfilter/parseutils.h
deleted file mode 100644
index b5b494e..0000000
--- a/libavfilter/parseutils.h
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * copyright (c) 2009 Stefano Sabatini
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-/**
- * @file
- * parsing utils
- */
-
-#ifndef AVFILTER_PARSEUTILS_H
-#define AVFILTER_PARSEUTILS_H
-
-#include "libavcodec/opt.h"
-
-/**
- * Unescapes the given string until a non escaped terminating char,
- * and returns the token corresponding to the unescaped string.
- *
- * The normal \ and ' escaping is supported. Leading and trailing
- * whitespaces are removed.
- *
- * @param term a 0-terminated list of terminating chars
- * @param buf the buffer to parse, buf will be updated to point to the
- * terminating char
- * @return the malloced unescaped string, which must be av_freed by
- * the user
- */
-char *av_get_token(const char **buf, const char *term);
-
-/**
- * Puts the RGBA values that correspond to color_string in rgba_color.
- *
- * @param color_string a string specifying a color. It can be the name of
- * a color (case insensitive match) or a 0xRRGGBB[AA] sequence.
- * The string "random" will result in a random color.
- * @return >= 0 in case of success, a negative value in case of
- * failure (for example if color_string cannot be parsed).
- */
-int av_parse_color(uint8_t *rgba_color, const char *color_string, void *log_ctx);
-
-/**
- * Parses the key/value pairs list in opts. For each key/value pair
- * found, stores the value in the field in ctx that is named like the
- * key. ctx must be an AVClass context, storing is done using
- * AVOptions.
- *
- * @param key_val_sep a 0-terminated list of characters used to
- * separate key from value
- * @param pairs_sep a 0-terminated list of characters used to separate
- * two pairs from each other
- * @return the number of successfully set key/value pairs, or a negative
- * value corresponding to an AVERROR code in case of error:
- * AVERROR(EINVAL) if opts cannot be parsed,
- * the error code issued by av_set_string3() if a key/value pair
- * cannot be set
- */
-int av_set_options_string(void *ctx, const char *opts,
-                          const char *key_val_sep, const char *pairs_sep);
-
-#endif  /* AVFILTER_PARSEUTILS_H */
diff --git a/libavfilter/vf_aspect.c b/libavfilter/vf_aspect.c
index 2627722..8f52d90 100644
--- a/libavfilter/vf_aspect.c
+++ b/libavfilter/vf_aspect.c
@@ -1,27 +1,26 @@
 /*
- * Aspect ratio modification video filter
  * Copyright (c) 2010 Bobby Bingham
 
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 /**
  * @file
- * aspect ratio modification video filter
+ * aspect ratio modification video filters
  */
 
 #include "avfilter.h"
@@ -35,51 +34,63 @@ static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
     AspectContext *aspect = ctx->priv;
     double  ratio;
     int64_t gcd;
+    char c = 0;
 
-    if(args) {
-        if(sscanf(args, "%d:%d", &aspect->aspect.num, &aspect->aspect.den) < 2) {
-            if(sscanf(args, "%lf", &ratio) < 1)
-                return -1;
-            aspect->aspect = av_d2q(ratio, 100);
-        } else {
-            gcd = av_gcd(FFABS(aspect->aspect.num), FFABS(aspect->aspect.den));
-            if(gcd) {
-                aspect->aspect.num /= gcd;
-                aspect->aspect.den /= gcd;
-            }
+    if (args) {
+        if (sscanf(args, "%d:%d%c", &aspect->aspect.num, &aspect->aspect.den, &c) != 2)
+            if (sscanf(args, "%lf%c", &ratio, &c) == 1)
+                aspect->aspect = av_d2q(ratio, 100);
+
+        if (c || aspect->aspect.num <= 0 || aspect->aspect.den <= 0) {
+            av_log(ctx, AV_LOG_ERROR,
+                   "Invalid string '%s' for aspect ratio.\n", args);
+            return AVERROR(EINVAL);
+        }
+
+        gcd = av_gcd(FFABS(aspect->aspect.num), FFABS(aspect->aspect.den));
+        if (gcd) {
+            aspect->aspect.num /= gcd;
+            aspect->aspect.den /= gcd;
         }
     }
 
-    if(aspect->aspect.den == 0)
+    if (aspect->aspect.den == 0)
         aspect->aspect = (AVRational) {0, 1};
 
+    av_log(ctx, AV_LOG_INFO, "a:%d/%d\n", aspect->aspect.num, aspect->aspect.den);
     return 0;
 }
 
-static void start_frame(AVFilterLink *link, AVFilterPicRef *picref)
+static void start_frame(AVFilterLink *link, AVFilterBufferRef *picref)
 {
     AspectContext *aspect = link->dst->priv;
 
-    picref->pixel_aspect = aspect->aspect;
+    picref->video->pixel_aspect = aspect->aspect;
     avfilter_start_frame(link->dst->outputs[0], picref);
 }
 
-#if CONFIG_ASPECT_FILTER
-/* for aspect filter, convert from frame aspect ratio to pixel aspect ratio */
-static int frameaspect_config_props(AVFilterLink *inlink)
+#if CONFIG_SETDAR_FILTER
+/* for setdar filter, convert from frame aspect ratio to pixel aspect ratio */
+static int setdar_config_props(AVFilterLink *inlink)
 {
     AspectContext *aspect = inlink->dst->priv;
+    AVRational dar = aspect->aspect;
 
     av_reduce(&aspect->aspect.num, &aspect->aspect.den,
                aspect->aspect.num * inlink->h,
                aspect->aspect.den * inlink->w, 100);
 
+    av_log(inlink->dst, AV_LOG_INFO, "w:%d h:%d -> dar:%d/%d par:%d/%d\n",
+           inlink->w, inlink->h, dar.num, dar.den, aspect->aspect.num, aspect->aspect.den);
+
+    inlink->sample_aspect_ratio = aspect->aspect;
+
     return 0;
 }
 
-AVFilter avfilter_vf_aspect = {
-    .name      = "aspect",
-    .description = NULL_IF_CONFIG_SMALL("Set the frame aspect ratio."),
+AVFilter avfilter_vf_setdar = {
+    .name      = "setdar",
+    .description = NULL_IF_CONFIG_SMALL("Set the frame display aspect ratio."),
 
     .init      = init,
 
@@ -87,7 +98,7 @@ AVFilter avfilter_vf_aspect = {
 
     .inputs    = (AVFilterPad[]) {{ .name             = "default",
                                     .type             = AVMEDIA_TYPE_VIDEO,
-                                    .config_props     = frameaspect_config_props,
+                                    .config_props     = setdar_config_props,
                                     .get_video_buffer = avfilter_null_get_video_buffer,
                                     .start_frame      = start_frame,
                                     .end_frame        = avfilter_null_end_frame },
@@ -97,12 +108,22 @@ AVFilter avfilter_vf_aspect = {
                                     .type             = AVMEDIA_TYPE_VIDEO, },
                                   { .name = NULL}},
 };
-#endif /* CONFIG_ASPECT_FILTER */
+#endif /* CONFIG_SETDAR_FILTER */
+
+#if CONFIG_SETSAR_FILTER
+/* for setdar filter, convert from frame aspect ratio to pixel aspect ratio */
+static int setsar_config_props(AVFilterLink *inlink)
+{
+    AspectContext *aspect = inlink->dst->priv;
+
+    inlink->sample_aspect_ratio = aspect->aspect;
+
+    return 0;
+}
 
-#if CONFIG_PIXELASPECT_FILTER
-AVFilter avfilter_vf_pixelaspect = {
-    .name      = "pixelaspect",
-    .description = NULL_IF_CONFIG_SMALL("Set the pixel aspect ratio."),
+AVFilter avfilter_vf_setsar = {
+    .name      = "setsar",
+    .description = NULL_IF_CONFIG_SMALL("Set the pixel sample aspect ratio."),
 
     .init      = init,
 
@@ -110,6 +131,7 @@ AVFilter avfilter_vf_pixelaspect = {
 
     .inputs    = (AVFilterPad[]) {{ .name             = "default",
                                     .type             = AVMEDIA_TYPE_VIDEO,
+                                    .config_props     = setsar_config_props,
                                     .get_video_buffer = avfilter_null_get_video_buffer,
                                     .start_frame      = start_frame,
                                     .end_frame        = avfilter_null_end_frame },
@@ -119,5 +141,5 @@ AVFilter avfilter_vf_pixelaspect = {
                                     .type             = AVMEDIA_TYPE_VIDEO, },
                                   { .name = NULL}},
 };
-#endif /* CONFIG_PIXELASPECT_FILTER */
+#endif /* CONFIG_SETSAR_FILTER */
 
diff --git a/libavfilter/vf_blackframe.c b/libavfilter/vf_blackframe.c
new file mode 100644
index 0000000..770eec9
--- /dev/null
+++ b/libavfilter/vf_blackframe.c
@@ -0,0 +1,129 @@
+/*
+ * Copyright (c) 2010 Stefano Sabatini
+ * Copyright (c) 2006 Ivo van Poorten
+ * Copyright (c) 2006 Julian Hall
+ * Copyright (c) 2002-2003 Brian J. Murrell
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with Libav; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+
+/**
+ * @file
+ * Search for black frames to detect scene transitions.
+ * Ported from MPlayer libmpcodecs/vf_blackframe.c.
+ */
+
+#include "avfilter.h"
+
+typedef struct {
+    unsigned int bamount; ///< black amount
+    unsigned int bthresh; ///< black threshold
+    unsigned int frame;   ///< frame number
+    unsigned int nblack;  ///< number of black pixels counted so far
+} BlackFrameContext;
+
+static int query_formats(AVFilterContext *ctx)
+{
+    static const enum PixelFormat pix_fmts[] = {
+        PIX_FMT_YUV410P, PIX_FMT_YUV420P, PIX_FMT_GRAY8, PIX_FMT_NV12,
+        PIX_FMT_NV21, PIX_FMT_YUV444P, PIX_FMT_YUV422P, PIX_FMT_YUV411P,
+        PIX_FMT_NONE
+    };
+
+    avfilter_set_common_formats(ctx, avfilter_make_format_list(pix_fmts));
+    return 0;
+}
+
+static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
+{
+    BlackFrameContext *blackframe = ctx->priv;
+
+    blackframe->bamount = 98;
+    blackframe->bthresh = 32;
+    blackframe->nblack = 0;
+    blackframe->frame = 0;
+
+    if (args)
+        sscanf(args, "%u:%u", &blackframe->bamount, &blackframe->bthresh);
+
+    av_log(ctx, AV_LOG_INFO, "bamount:%u bthresh:%u\n",
+           blackframe->bamount, blackframe->bthresh);
+
+    if (blackframe->bamount > 100 || blackframe->bthresh > 255) {
+        av_log(ctx, AV_LOG_ERROR, "Too big value for bamount (max is 100) or bthresh (max is 255)\n");
+        return AVERROR(EINVAL);
+    }
+
+    return 0;
+}
+
+static void draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir)
+{
+    AVFilterContext *ctx = inlink->dst;
+    BlackFrameContext *blackframe = ctx->priv;
+    AVFilterBufferRef *picref = inlink->cur_buf;
+    int x, i;
+    uint8_t *p = picref->data[0] + y * picref->linesize[0];
+
+    for (i = 0; i < h; i++) {
+        for (x = 0; x < inlink->w; x++)
+            blackframe->nblack += p[x] < blackframe->bthresh;
+        p += picref->linesize[0];
+    }
+
+    avfilter_draw_slice(ctx->outputs[0], y, h, slice_dir);
+}
+
+static void end_frame(AVFilterLink *inlink)
+{
+    AVFilterContext *ctx = inlink->dst;
+    BlackFrameContext *blackframe = ctx->priv;
+    AVFilterBufferRef *picref = inlink->cur_buf;
+    int pblack = 0;
+
+    pblack = blackframe->nblack * 100 / (inlink->w * inlink->h);
+    if (pblack >= blackframe->bamount)
+        av_log(ctx, AV_LOG_INFO, "frame:%u pblack:%u pos:%"PRId64" pts:%"PRId64" t:%f\n",
+               blackframe->frame, pblack, picref->pos, picref->pts,
+               picref->pts == AV_NOPTS_VALUE ? -1 : picref->pts * av_q2d(inlink->time_base));
+
+    blackframe->frame++;
+    blackframe->nblack = 0;
+    avfilter_end_frame(inlink->dst->outputs[0]);
+}
+
+AVFilter avfilter_vf_blackframe = {
+    .name        = "blackframe",
+    .description = NULL_IF_CONFIG_SMALL("Detect frames that are (almost) black."),
+
+    .priv_size = sizeof(BlackFrameContext),
+    .init      = init,
+
+    .query_formats = query_formats,
+
+    .inputs    = (AVFilterPad[]) {{ .name = "default",
+                                    .type             = AVMEDIA_TYPE_VIDEO,
+                                    .draw_slice       = draw_slice,
+                                    .get_video_buffer = avfilter_null_get_video_buffer,
+                                    .start_frame      = avfilter_null_start_frame,
+                                    .end_frame        = end_frame, },
+                                  { .name = NULL}},
+
+    .outputs   = (AVFilterPad[]) {{ .name             = "default",
+                                    .type             = AVMEDIA_TYPE_VIDEO },
+                                  { .name = NULL}},
+};
diff --git a/libavfilter/vf_copy.c b/libavfilter/vf_copy.c
new file mode 100644
index 0000000..705ad1e
--- /dev/null
+++ b/libavfilter/vf_copy.c
@@ -0,0 +1,40 @@
+/*
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * copy video filter
+ */
+
+#include "avfilter.h"
+
+AVFilter avfilter_vf_copy = {
+    .name      = "copy",
+    .description = NULL_IF_CONFIG_SMALL("Copy the input video unchanged to the output."),
+
+    .inputs    = (AVFilterPad[]) {{ .name             = "default",
+                                    .type             = AVMEDIA_TYPE_VIDEO,
+                                    .get_video_buffer = avfilter_null_get_video_buffer,
+                                    .start_frame      = avfilter_null_start_frame,
+                                    .end_frame        = avfilter_null_end_frame,
+                                    .rej_perms        = ~0 },
+                                  { .name = NULL}},
+    .outputs   = (AVFilterPad[]) {{ .name             = "default",
+                                    .type             = AVMEDIA_TYPE_VIDEO, },
+                                  { .name = NULL}},
+};
diff --git a/libavfilter/vf_crop.c b/libavfilter/vf_crop.c
index 204adcf..105c390 100644
--- a/libavfilter/vf_crop.c
+++ b/libavfilter/vf_crop.c
@@ -1,20 +1,20 @@
 /*
- * copyright (c) 2007 Bobby Bingham
+ * Copyright (c) 2007 Bobby Bingham
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -23,8 +23,45 @@
  * video crop filter
  */
 
+/* #define DEBUG */
+
 #include "avfilter.h"
-#include "libavutil/pixdesc.h"
+#include "libavutil/eval.h"
+#include "libavutil/avstring.h"
+#include "libavutil/libm.h"
+#include "libavutil/imgutils.h"
+
+static const char *var_names[] = {
+    "E",
+    "PHI",
+    "PI",
+    "in_w", "iw",   ///< width  of the input video
+    "in_h", "ih",   ///< height of the input video
+    "out_w", "ow",  ///< width  of the cropped video
+    "out_h", "oh",  ///< height of the cropped video
+    "x",
+    "y",
+    "n",            ///< number of frame
+    "pos",          ///< position in the file
+    "t",            ///< timestamp expressed in seconds
+    NULL
+};
+
+enum var_name {
+    VAR_E,
+    VAR_PHI,
+    VAR_PI,
+    VAR_IN_W,  VAR_IW,
+    VAR_IN_H,  VAR_IH,
+    VAR_OUT_W, VAR_OW,
+    VAR_OUT_H, VAR_OH,
+    VAR_X,
+    VAR_Y,
+    VAR_N,
+    VAR_POS,
+    VAR_T,
+    VAR_VARS_NB
+};
 
 typedef struct {
     int  x;             ///< x offset of the non-cropped area with respect to the input area
@@ -32,8 +69,11 @@ typedef struct {
     int  w;             ///< width of the cropped area
     int  h;             ///< height of the cropped area
 
-    int bpp;            ///< bits per pixel
+    int max_step[4];    ///< max pixel step for each plane, expressed as a number of bytes
     int hsub, vsub;     ///< chroma subsampling
+    char x_expr[256], y_expr[256], ow_expr[256], oh_expr[256];
+    AVExpr *x_pexpr, *y_pexpr;  /* parsed expressions for x and y */
+    double var_values[VAR_VARS_NB];
 } CropContext;
 
 static int query_formats(AVFilterContext *ctx)
@@ -72,78 +112,117 @@ static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
 {
     CropContext *crop = ctx->priv;
 
+    av_strlcpy(crop->ow_expr, "iw", sizeof(crop->ow_expr));
+    av_strlcpy(crop->oh_expr, "ih", sizeof(crop->oh_expr));
+    av_strlcpy(crop->x_expr, "(in_w-out_w)/2", sizeof(crop->x_expr));
+    av_strlcpy(crop->y_expr, "(in_h-out_h)/2", sizeof(crop->y_expr));
+
     if (args)
-        sscanf(args, "%d:%d:%d:%d", &crop->x, &crop->y, &crop->w, &crop->h);
+        sscanf(args, "%255[^:]:%255[^:]:%255[^:]:%255[^:]", crop->ow_expr, crop->oh_expr, crop->x_expr, crop->y_expr);
 
     return 0;
 }
 
-static int config_input(AVFilterLink *link)
+static av_cold void uninit(AVFilterContext *ctx)
 {
-    AVFilterContext *ctx = link->dst;
     CropContext *crop = ctx->priv;
 
-    switch (link->format) {
-    case PIX_FMT_RGB48BE:
-    case PIX_FMT_RGB48LE:
-        crop->bpp = 48;
-        break;
-    case PIX_FMT_ARGB:
-    case PIX_FMT_RGBA:
-    case PIX_FMT_ABGR:
-    case PIX_FMT_BGRA:
-        crop->bpp = 32;
-        break;
-    case PIX_FMT_RGB24:
-    case PIX_FMT_BGR24:
-        crop->bpp = 24;
-        break;
-    case PIX_FMT_RGB565BE:
-    case PIX_FMT_RGB565LE:
-    case PIX_FMT_RGB555BE:
-    case PIX_FMT_RGB555LE:
-    case PIX_FMT_BGR565BE:
-    case PIX_FMT_BGR565LE:
-    case PIX_FMT_BGR555BE:
-    case PIX_FMT_BGR555LE:
-    case PIX_FMT_GRAY16BE:
-    case PIX_FMT_GRAY16LE:
-    case PIX_FMT_YUV420P16LE:
-    case PIX_FMT_YUV420P16BE:
-    case PIX_FMT_YUV422P16LE:
-    case PIX_FMT_YUV422P16BE:
-    case PIX_FMT_YUV444P16LE:
-    case PIX_FMT_YUV444P16BE:
-        crop->bpp = 16;
-        break;
-    default:
-        crop->bpp = 8;
-    }
+    av_expr_free(crop->x_pexpr); crop->x_pexpr = NULL;
+    av_expr_free(crop->y_pexpr); crop->y_pexpr = NULL;
+}
 
-    avcodec_get_chroma_sub_sample(link->format, &crop->hsub, &crop->vsub);
+static inline int normalize_double(int *n, double d)
+{
+    int ret = 0;
 
-    if (crop->w == 0)
-        crop->w = link->w - crop->x;
-    if (crop->h == 0)
-        crop->h = link->h - crop->y;
+    if (isnan(d)) {
+        ret = AVERROR(EINVAL);
+    } else if (d > INT_MAX || d < INT_MIN) {
+        *n = d > INT_MAX ? INT_MAX : INT_MIN;
+        ret = AVERROR(EINVAL);
+    } else
+        *n = round(d);
 
-    crop->x &= ~((1 << crop->hsub) - 1);
-    crop->y &= ~((1 << crop->vsub) - 1);
+    return ret;
+}
+
+static int config_input(AVFilterLink *link)
+{
+    AVFilterContext *ctx = link->dst;
+    CropContext *crop = ctx->priv;
+    const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[link->format];
+    int ret;
+    const char *expr;
+    double res;
+
+    crop->var_values[VAR_E]     = M_E;
+    crop->var_values[VAR_PHI]   = M_PHI;
+    crop->var_values[VAR_PI]    = M_PI;
+    crop->var_values[VAR_IN_W]  = crop->var_values[VAR_IW] = ctx->inputs[0]->w;
+    crop->var_values[VAR_IN_H]  = crop->var_values[VAR_IH] = ctx->inputs[0]->h;
+    crop->var_values[VAR_X]     = NAN;
+    crop->var_values[VAR_Y]     = NAN;
+    crop->var_values[VAR_OUT_W] = crop->var_values[VAR_OW] = NAN;
+    crop->var_values[VAR_OUT_H] = crop->var_values[VAR_OH] = NAN;
+    crop->var_values[VAR_N]     = 0;
+    crop->var_values[VAR_T]     = NAN;
+    crop->var_values[VAR_POS]   = NAN;
+
+    av_image_fill_max_pixsteps(crop->max_step, NULL, pix_desc);
+    crop->hsub = av_pix_fmt_descriptors[link->format].log2_chroma_w;
+    crop->vsub = av_pix_fmt_descriptors[link->format].log2_chroma_h;
+
+    if ((ret = av_expr_parse_and_eval(&res, (expr = crop->ow_expr),
+                                      var_names, crop->var_values,
+                                      NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0) goto fail_expr;
+    crop->var_values[VAR_OUT_W] = crop->var_values[VAR_OW] = res;
+    if ((ret = av_expr_parse_and_eval(&res, (expr = crop->oh_expr),
+                                      var_names, crop->var_values,
+                                      NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0) goto fail_expr;
+    crop->var_values[VAR_OUT_H] = crop->var_values[VAR_OH] = res;
+    /* evaluate again ow as it may depend on oh */
+    if ((ret = av_expr_parse_and_eval(&res, (expr = crop->ow_expr),
+                                      var_names, crop->var_values,
+                                      NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0) goto fail_expr;
+    crop->var_values[VAR_OUT_W] = crop->var_values[VAR_OW] = res;
+    if (normalize_double(&crop->w, crop->var_values[VAR_OUT_W]) < 0 ||
+        normalize_double(&crop->h, crop->var_values[VAR_OUT_H]) < 0) {
+        av_log(ctx, AV_LOG_ERROR,
+               "Too big value or invalid expression for out_w/ow or out_h/oh. "
+               "Maybe the expression for out_w:'%s' or for out_h:'%s' is self-referencing.\n",
+               crop->ow_expr, crop->oh_expr);
+        return AVERROR(EINVAL);
+    }
+    crop->w &= ~((1 << crop->hsub) - 1);
+    crop->h &= ~((1 << crop->vsub) - 1);
+
+    if ((ret = av_expr_parse(&crop->x_pexpr, crop->x_expr, var_names,
+                             NULL, NULL, NULL, NULL, 0, ctx)) < 0 ||
+        (ret = av_expr_parse(&crop->y_pexpr, crop->y_expr, var_names,
+                             NULL, NULL, NULL, NULL, 0, ctx)) < 0)
+        return AVERROR(EINVAL);
 
-    av_log(link->dst, AV_LOG_INFO, "x:%d y:%d w:%d h:%d\n",
-           crop->x, crop->y, crop->w, crop->h);
+    av_log(ctx, AV_LOG_INFO, "w:%d h:%d -> w:%d h:%d\n",
+           link->w, link->h, crop->w, crop->h);
 
-    if (crop->x <  0 || crop->y <  0                    ||
-        crop->w <= 0 || crop->h <= 0                    ||
-        (unsigned)crop->x + (unsigned)crop->w > link->w ||
-        (unsigned)crop->y + (unsigned)crop->h > link->h) {
+    if (crop->w <= 0 || crop->h <= 0 ||
+        crop->w > link->w || crop->h > link->h) {
         av_log(ctx, AV_LOG_ERROR,
-               "Output area %d:%d:%d:%d not within the input area 0:0:%d:%d or zero-sized\n",
-               crop->x, crop->y, crop->w, crop->h, link->w, link->h);
-        return -1;
+               "Invalid too big or non positive size for width '%d' or height '%d'\n",
+               crop->w, crop->h);
+        return AVERROR(EINVAL);
     }
 
+    /* set default, required in the case the first computed value for x/y is NAN */
+    crop->x = (link->w - crop->w) / 2;
+    crop->y = (link->h - crop->h) / 2;
+    crop->x &= ~((1 << crop->hsub) - 1);
+    crop->y &= ~((1 << crop->vsub) - 1);
     return 0;
+
+fail_expr:
+    av_log(NULL, AV_LOG_ERROR, "Error when evaluating the expression '%s'\n", expr);
+    return ret;
 }
 
 static int config_output(AVFilterLink *link)
@@ -156,23 +235,48 @@ static int config_output(AVFilterLink *link)
     return 0;
 }
 
-static void start_frame(AVFilterLink *link, AVFilterPicRef *picref)
+static void start_frame(AVFilterLink *link, AVFilterBufferRef *picref)
 {
-    CropContext *crop = link->dst->priv;
-    AVFilterPicRef *ref2 = avfilter_ref_pic(picref, ~0);
+    AVFilterContext *ctx = link->dst;
+    CropContext *crop = ctx->priv;
+    AVFilterBufferRef *ref2;
     int i;
 
-    ref2->w        = crop->w;
-    ref2->h        = crop->h;
+    ref2 = avfilter_ref_buffer(picref, ~0);
+    ref2->video->w = crop->w;
+    ref2->video->h = crop->h;
+
+    crop->var_values[VAR_T] = picref->pts == AV_NOPTS_VALUE ?
+        NAN : picref->pts * av_q2d(link->time_base);
+    crop->var_values[VAR_POS] = picref->pos == -1 ? NAN : picref->pos;
+    crop->var_values[VAR_X] = av_expr_eval(crop->x_pexpr, crop->var_values, NULL);
+    crop->var_values[VAR_Y] = av_expr_eval(crop->y_pexpr, crop->var_values, NULL);
+    crop->var_values[VAR_X] = av_expr_eval(crop->x_pexpr, crop->var_values, NULL);
+
+    normalize_double(&crop->x, crop->var_values[VAR_X]);
+    normalize_double(&crop->y, crop->var_values[VAR_Y]);
+
+    if (crop->x < 0) crop->x = 0;
+    if (crop->y < 0) crop->y = 0;
+    if ((unsigned)crop->x + (unsigned)crop->w > link->w) crop->x = link->w - crop->w;
+    if ((unsigned)crop->y + (unsigned)crop->h > link->h) crop->y = link->h - crop->h;
+    crop->x &= ~((1 << crop->hsub) - 1);
+    crop->y &= ~((1 << crop->vsub) - 1);
+
+#ifdef DEBUG
+    av_log(ctx, AV_LOG_DEBUG,
+           "n:%d t:%f x:%d y:%d x+w:%d y+h:%d\n",
+           (int)crop->var_values[VAR_N], crop->var_values[VAR_T], crop->x, crop->y, crop->x+crop->w, crop->y+crop->h);
+#endif
 
     ref2->data[0] += crop->y * ref2->linesize[0];
-    ref2->data[0] += (crop->x * crop->bpp) >> 3;
+    ref2->data[0] += crop->x * crop->max_step[0];
 
     if (!(av_pix_fmt_descriptors[link->format].flags & PIX_FMT_PAL)) {
         for (i = 1; i < 3; i ++) {
             if (ref2->data[i]) {
                 ref2->data[i] += (crop->y >> crop->vsub) * ref2->linesize[i];
-                ref2->data[i] += ((crop->x * crop->bpp) >> 3) >> crop->hsub;
+                ref2->data[i] += (crop->x * crop->max_step[i]) >> crop->hsub;
             }
         }
     }
@@ -180,7 +284,7 @@ static void start_frame(AVFilterLink *link, AVFilterPicRef *picref)
     /* alpha plane */
     if (ref2->data[3]) {
         ref2->data[3] += crop->y * ref2->linesize[3];
-        ref2->data[3] += (crop->x * crop->bpp) >> 3;
+        ref2->data[3] += crop->x * crop->max_step[3];
     }
 
     avfilter_start_frame(link->dst->outputs[0], ref2);
@@ -204,19 +308,30 @@ static void draw_slice(AVFilterLink *link, int y, int h, int slice_dir)
     avfilter_draw_slice(ctx->outputs[0], y - crop->y, h, slice_dir);
 }
 
+static void end_frame(AVFilterLink *link)
+{
+    CropContext *crop = link->dst->priv;
+
+    crop->var_values[VAR_N] += 1.0;
+    avfilter_unref_buffer(link->cur_buf);
+    avfilter_end_frame(link->dst->outputs[0]);
+}
+
 AVFilter avfilter_vf_crop = {
     .name      = "crop",
-    .description = NULL_IF_CONFIG_SMALL("Crop the input video to x:y:width:height."),
+    .description = NULL_IF_CONFIG_SMALL("Crop the input video to width:height:x:y."),
 
     .priv_size = sizeof(CropContext),
 
     .query_formats = query_formats,
     .init          = init,
+    .uninit        = uninit,
 
     .inputs    = (AVFilterPad[]) {{ .name             = "default",
                                     .type             = AVMEDIA_TYPE_VIDEO,
                                     .start_frame      = start_frame,
                                     .draw_slice       = draw_slice,
+                                    .end_frame        = end_frame,
                                     .get_video_buffer = avfilter_null_get_video_buffer,
                                     .config_props     = config_input, },
                                   { .name = NULL}},
diff --git a/libavfilter/vf_cropdetect.c b/libavfilter/vf_cropdetect.c
new file mode 100644
index 0000000..34b5dc9
--- /dev/null
+++ b/libavfilter/vf_cropdetect.c
@@ -0,0 +1,214 @@
+/*
+ * Copyright (c) 2002 A'rpi
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with Libav; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+
+/**
+ * @file
+ * border detection filter
+ * Ported from MPlayer libmpcodecs/vf_cropdetect.c.
+ */
+
+#include "libavutil/imgutils.h"
+#include "avfilter.h"
+
+typedef struct {
+    int x1, y1, x2, y2;
+    int limit;
+    int round;
+    int reset_count;
+    int frame_nb;
+    int max_pixsteps[4];
+} CropDetectContext;
+
+static int query_formats(AVFilterContext *ctx)
+{
+    static const enum PixelFormat pix_fmts[] = {
+        PIX_FMT_YUV420P, PIX_FMT_YUVJ420P,
+        PIX_FMT_YUV422P, PIX_FMT_YUVJ422P,
+        PIX_FMT_YUV444P, PIX_FMT_YUVJ444P,
+        PIX_FMT_YUV411P, PIX_FMT_GRAY8,
+        PIX_FMT_NV12,    PIX_FMT_NV21,
+        PIX_FMT_NONE
+    };
+
+    avfilter_set_common_formats(ctx, avfilter_make_format_list(pix_fmts));
+    return 0;
+}
+
+static int checkline(void *ctx, const unsigned char *src, int stride, int len, int bpp)
+{
+    int total = 0;
+    int div = len;
+
+    switch (bpp) {
+    case 1:
+        while (--len >= 0) {
+            total += src[0];
+            src += stride;
+        }
+        break;
+    case 3:
+    case 4:
+        while (--len >= 0) {
+            total += src[0] + src[1] + src[2];
+            src += stride;
+        }
+        div *= 3;
+        break;
+    }
+    total /= div;
+
+    av_log(ctx, AV_LOG_DEBUG, "total:%d\n", total);
+    return total;
+}
+
+static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
+{
+    CropDetectContext *cd = ctx->priv;
+
+    cd->limit = 24;
+    cd->round = 0;
+    cd->reset_count = 0;
+    cd->frame_nb = -2;
+
+    if (args)
+        sscanf(args, "%d:%d:%d", &cd->limit, &cd->round, &cd->reset_count);
+
+    av_log(ctx, AV_LOG_INFO, "limit:%d round:%d reset_count:%d\n",
+           cd->limit, cd->round, cd->reset_count);
+
+    return 0;
+}
+
+static int config_input(AVFilterLink *inlink)
+{
+    AVFilterContext *ctx = inlink->dst;
+    CropDetectContext *cd = ctx->priv;
+
+    av_image_fill_max_pixsteps(cd->max_pixsteps, NULL,
+                               &av_pix_fmt_descriptors[inlink->format]);
+
+    cd->x1 = inlink->w - 1;
+    cd->y1 = inlink->h - 1;
+    cd->x2 = 0;
+    cd->y2 = 0;
+
+    return 0;
+}
+
+static void end_frame(AVFilterLink *inlink)
+{
+    AVFilterContext *ctx = inlink->dst;
+    CropDetectContext *cd = ctx->priv;
+    AVFilterBufferRef *picref = inlink->cur_buf;
+    int bpp = cd->max_pixsteps[0];
+    int w, h, x, y, shrink_by;
+
+    // ignore first 2 frames - they may be empty
+    if (++cd->frame_nb > 0) {
+        // Reset the crop area every reset_count frames, if reset_count is > 0
+        if (cd->reset_count > 0 && cd->frame_nb > cd->reset_count) {
+            cd->x1 = picref->video->w-1;
+            cd->y1 = picref->video->h-1;
+            cd->x2 = 0;
+            cd->y2 = 0;
+            cd->frame_nb = 1;
+        }
+
+        for (y = 0; y < cd->y1; y++) {
+            if (checkline(ctx, picref->data[0] + picref->linesize[0] * y, bpp, picref->video->w, bpp) > cd->limit) {
+                cd->y1 = y;
+                break;
+            }
+        }
+
+        for (y = picref->video->h-1; y > cd->y2; y--) {
+            if (checkline(ctx, picref->data[0] + picref->linesize[0] * y, bpp, picref->video->w, bpp) > cd->limit) {
+                cd->y2 = y;
+                break;
+            }
+        }
+
+        for (y = 0; y < cd->x1; y++) {
+            if (checkline(ctx, picref->data[0] + bpp*y, picref->linesize[0], picref->video->h, bpp) > cd->limit) {
+                cd->x1 = y;
+                break;
+            }
+        }
+
+        for (y = picref->video->w-1; y > cd->x2; y--) {
+            if (checkline(ctx, picref->data[0] + bpp*y, picref->linesize[0], picref->video->h, bpp) > cd->limit) {
+                cd->x2 = y;
+                break;
+            }
+        }
+
+        // round x and y (up), important for yuv colorspaces
+        // make sure they stay rounded!
+        x = (cd->x1+1) & ~1;
+        y = (cd->y1+1) & ~1;
+
+        w = cd->x2 - x + 1;
+        h = cd->y2 - y + 1;
+
+        // w and h must be divisible by 2 as well because of yuv
+        // colorspace problems.
+        if (cd->round <= 1)
+            cd->round = 16;
+        if (cd->round % 2)
+            cd->round *= 2;
+
+        shrink_by = w % cd->round;
+        w -= shrink_by;
+        x += (shrink_by/2 + 1) & ~1;
+
+        shrink_by = h % cd->round;
+        h -= shrink_by;
+        y += (shrink_by/2 + 1) & ~1;
+
+        av_log(ctx, AV_LOG_INFO,
+               "x1:%d x2:%d y1:%d y2:%d w:%d h:%d x:%d y:%d pos:%"PRId64" pts:%"PRId64" t:%f crop=%d:%d:%d:%d\n",
+               cd->x1, cd->x2, cd->y1, cd->y2, w, h, x, y, picref->pos, picref->pts,
+               picref->pts == AV_NOPTS_VALUE ? -1 : picref->pts * av_q2d(inlink->time_base),
+               w, h, x, y);
+    }
+
+    avfilter_end_frame(inlink->dst->outputs[0]);
+}
+
+AVFilter avfilter_vf_cropdetect = {
+    .name        = "cropdetect",
+    .description = NULL_IF_CONFIG_SMALL("Auto-detect crop size."),
+
+    .priv_size = sizeof(CropDetectContext),
+    .init      = init,
+
+    .query_formats = query_formats,
+
+    .inputs    = (AVFilterPad[]) {{ .name = "default",
+                                    .type             = AVMEDIA_TYPE_VIDEO,
+                                    .config_props     = config_input,
+                                    .get_video_buffer = avfilter_null_get_video_buffer,
+                                    .start_frame      = avfilter_null_start_frame,
+                                    .end_frame        = end_frame, },
+                                  { .name = NULL}},
+
+    .outputs   = (AVFilterPad[]) {{ .name             = "default",
+                                    .type             = AVMEDIA_TYPE_VIDEO },
+                                  { .name = NULL}},
+};
diff --git a/libavfilter/vf_drawbox.c b/libavfilter/vf_drawbox.c
new file mode 100644
index 0000000..37c48c5
--- /dev/null
+++ b/libavfilter/vf_drawbox.c
@@ -0,0 +1,143 @@
+/*
+ * Copyright (c) 2008 Affine Systems, Inc (Michael Sullivan, Bobby Impollonia)
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * Box drawing filter. Also a nice template for a filter that needs to
+ * write in the input frame.
+ */
+
+#include "libavutil/colorspace.h"
+#include "libavutil/pixdesc.h"
+#include "libavutil/parseutils.h"
+#include "avfilter.h"
+
+enum { Y, U, V, A };
+
+typedef struct {
+    int x, y, w, h;
+    unsigned char yuv_color[4];
+    int vsub, hsub;   //< chroma subsampling
+} DrawBoxContext;
+
+static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
+{
+    DrawBoxContext *drawbox= ctx->priv;
+    char color_str[1024] = "black";
+    uint8_t rgba_color[4];
+
+    drawbox->x = drawbox->y = drawbox->w = drawbox->h = 0;
+
+    if (args)
+        sscanf(args, "%d:%d:%d:%d:%s",
+               &drawbox->x, &drawbox->y, &drawbox->w, &drawbox->h, color_str);
+
+    if (av_parse_color(rgba_color, color_str, -1, ctx) < 0)
+        return AVERROR(EINVAL);
+
+    drawbox->yuv_color[Y] = RGB_TO_Y_CCIR(rgba_color[0], rgba_color[1], rgba_color[2]);
+    drawbox->yuv_color[U] = RGB_TO_U_CCIR(rgba_color[0], rgba_color[1], rgba_color[2], 0);
+    drawbox->yuv_color[V] = RGB_TO_V_CCIR(rgba_color[0], rgba_color[1], rgba_color[2], 0);
+    drawbox->yuv_color[A] = rgba_color[3];
+
+    return 0;
+}
+
+static int query_formats(AVFilterContext *ctx)
+{
+    enum PixelFormat pix_fmts[] = {
+        PIX_FMT_YUV444P,  PIX_FMT_YUV422P,  PIX_FMT_YUV420P,
+        PIX_FMT_YUV411P,  PIX_FMT_YUV410P,
+        PIX_FMT_YUVJ444P, PIX_FMT_YUVJ422P, PIX_FMT_YUVJ420P,
+        PIX_FMT_YUV440P,  PIX_FMT_YUVJ440P,
+        PIX_FMT_NONE
+    };
+
+    avfilter_set_common_formats(ctx, avfilter_make_format_list(pix_fmts));
+    return 0;
+}
+
+static int config_input(AVFilterLink *inlink)
+{
+    DrawBoxContext *drawbox = inlink->dst->priv;
+
+    drawbox->hsub = av_pix_fmt_descriptors[inlink->format].log2_chroma_w;
+    drawbox->vsub = av_pix_fmt_descriptors[inlink->format].log2_chroma_h;
+
+    if (drawbox->w == 0) drawbox->w = inlink->w;
+    if (drawbox->h == 0) drawbox->h = inlink->h;
+
+    av_log(inlink->dst, AV_LOG_INFO, "x:%d y:%d w:%d h:%d color:0x%02X%02X%02X%02X\n",
+           drawbox->w, drawbox->y, drawbox->w, drawbox->h,
+           drawbox->yuv_color[Y], drawbox->yuv_color[U], drawbox->yuv_color[V], drawbox->yuv_color[A]);
+
+    return 0;
+}
+
+static void draw_slice(AVFilterLink *inlink, int y0, int h, int slice_dir)
+{
+    DrawBoxContext *drawbox = inlink->dst->priv;
+    int plane, x, y, xb = drawbox->x, yb = drawbox->y;
+    unsigned char *row[4];
+    AVFilterBufferRef *picref = inlink->cur_buf;
+
+    for (y = FFMAX(yb, y0); y < (y0 + h) && y < (yb + drawbox->h); y++) {
+        row[0] = picref->data[0] + y * picref->linesize[0];
+
+        for (plane = 1; plane < 3; plane++)
+            row[plane] = picref->data[plane] +
+                picref->linesize[plane] * (y >> drawbox->vsub);
+
+        for (x = FFMAX(xb, 0); x < (xb + drawbox->w) && x < picref->video->w; x++) {
+            double alpha = (double)drawbox->yuv_color[A] / 255;
+
+            if ((y - yb < 3) || (yb + drawbox->h - y < 4) ||
+                (x - xb < 3) || (xb + drawbox->w - x < 4)) {
+                row[0][x                 ] = (1 - alpha) * row[0][x                 ] + alpha * drawbox->yuv_color[Y];
+                row[1][x >> drawbox->hsub] = (1 - alpha) * row[1][x >> drawbox->hsub] + alpha * drawbox->yuv_color[U];
+                row[2][x >> drawbox->hsub] = (1 - alpha) * row[2][x >> drawbox->hsub] + alpha * drawbox->yuv_color[V];
+            }
+        }
+    }
+
+    avfilter_draw_slice(inlink->dst->outputs[0], y0, h, 1);
+}
+
+AVFilter avfilter_vf_drawbox = {
+    .name      = "drawbox",
+    .description = NULL_IF_CONFIG_SMALL("Draw a colored box on the input video."),
+    .priv_size = sizeof(DrawBoxContext),
+    .init      = init,
+
+    .query_formats   = query_formats,
+    .inputs    = (AVFilterPad[]) {{ .name             = "default",
+                                    .type             = AVMEDIA_TYPE_VIDEO,
+                                    .config_props     = config_input,
+                                    .get_video_buffer = avfilter_null_get_video_buffer,
+                                    .start_frame      = avfilter_null_start_frame,
+                                    .draw_slice       = draw_slice,
+                                    .end_frame        = avfilter_null_end_frame,
+                                    .min_perms        = AV_PERM_WRITE | AV_PERM_READ,
+                                    .rej_perms        = AV_PERM_PRESERVE },
+                                  { .name = NULL}},
+    .outputs   = (AVFilterPad[]) {{ .name             = "default",
+                                    .type             = AVMEDIA_TYPE_VIDEO, },
+                                  { .name = NULL}},
+};
diff --git a/libavfilter/vf_fade.c b/libavfilter/vf_fade.c
new file mode 100644
index 0000000..b3cccbd
--- /dev/null
+++ b/libavfilter/vf_fade.c
@@ -0,0 +1,170 @@
+/*
+ * Copyright (c) 2010 Brandon Mintern
+ * Copyright (c) 2007 Bobby Bingham
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * video fade filter
+ * based heavily on vf_negate.c by Bobby Bingham
+ */
+
+#include "libavutil/pixdesc.h"
+#include "avfilter.h"
+
+typedef struct {
+    int factor, fade_per_frame;
+    unsigned int frame_index, start_frame, stop_frame;
+    int hsub, vsub, bpp;
+} FadeContext;
+
+static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
+{
+    FadeContext *fade = ctx->priv;
+    unsigned int nb_frames;
+    char in_out[4];
+
+    if (!args ||
+        sscanf(args, " %3[^:]:%u:%u", in_out, &fade->start_frame, &nb_frames) != 3) {
+        av_log(ctx, AV_LOG_ERROR,
+               "Expected 3 arguments '(in|out):#:#':'%s'\n", args);
+        return AVERROR(EINVAL);
+    }
+
+    nb_frames = nb_frames ? nb_frames : 1;
+    fade->fade_per_frame = (1 << 16) / nb_frames;
+    if (!strcmp(in_out, "in"))
+        fade->factor = 0;
+    else if (!strcmp(in_out, "out")) {
+        fade->fade_per_frame = -fade->fade_per_frame;
+        fade->factor = (1 << 16);
+    } else {
+        av_log(ctx, AV_LOG_ERROR,
+               "first argument must be 'in' or 'out':'%s'\n", in_out);
+        return AVERROR(EINVAL);
+    }
+    fade->stop_frame = fade->start_frame + nb_frames;
+
+    av_log(ctx, AV_LOG_INFO,
+           "type:%s start_frame:%d nb_frames:%d\n",
+           in_out, fade->start_frame, nb_frames);
+    return 0;
+}
+
+static int query_formats(AVFilterContext *ctx)
+{
+    const static enum PixelFormat pix_fmts[] = {
+        PIX_FMT_YUV444P,  PIX_FMT_YUV422P,  PIX_FMT_YUV420P,
+        PIX_FMT_YUV411P,  PIX_FMT_YUV410P,
+        PIX_FMT_YUVJ444P, PIX_FMT_YUVJ422P, PIX_FMT_YUVJ420P,
+        PIX_FMT_YUV440P,  PIX_FMT_YUVJ440P,
+        PIX_FMT_RGB24,    PIX_FMT_BGR24,
+        PIX_FMT_NONE
+    };
+
+    avfilter_set_common_formats(ctx, avfilter_make_format_list(pix_fmts));
+    return 0;
+}
+
+static int config_props(AVFilterLink *inlink)
+{
+    FadeContext *fade = inlink->dst->priv;
+    const AVPixFmtDescriptor *pixdesc = &av_pix_fmt_descriptors[inlink->format];
+
+    fade->hsub = pixdesc->log2_chroma_w;
+    fade->vsub = pixdesc->log2_chroma_h;
+
+    fade->bpp = av_get_bits_per_pixel(pixdesc) >> 3;
+    return 0;
+}
+
+static void draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir)
+{
+    FadeContext *fade = inlink->dst->priv;
+    AVFilterBufferRef *outpic = inlink->cur_buf;
+    uint8_t *p;
+    int i, j, plane;
+
+    if (fade->factor < 65536) {
+        /* luma or rgb plane */
+        for (i = 0; i < h; i++) {
+            p = outpic->data[0] + (y+i) * outpic->linesize[0];
+            for (j = 0; j < inlink->w * fade->bpp; j++) {
+                /* fade->factor is using 16 lower-order bits for decimal
+                 * places. 32768 = 1 << 15, it is an integer representation
+                 * of 0.5 and is for rounding. */
+                *p = (*p * fade->factor + 32768) >> 16;
+                p++;
+            }
+        }
+
+        if (outpic->data[0] && outpic->data[1]) {
+            /* chroma planes */
+            for (plane = 1; plane < 3; plane++) {
+                for (i = 0; i < h; i++) {
+                    p = outpic->data[plane] + ((y+i) >> fade->vsub) * outpic->linesize[plane];
+                    for (j = 0; j < inlink->w >> fade->hsub; j++) {
+                        /* 8421367 = ((128 << 1) + 1) << 15. It is an integer
+                         * representation of 128.5. The .5 is for rounding
+                         * purposes. */
+                        *p = ((*p - 128) * fade->factor + 8421367) >> 16;
+                        p++;
+                    }
+                }
+            }
+        }
+    }
+
+    avfilter_draw_slice(inlink->dst->outputs[0], y, h, slice_dir);
+}
+
+static void end_frame(AVFilterLink *inlink)
+{
+    FadeContext *fade = inlink->dst->priv;
+
+    avfilter_end_frame(inlink->dst->outputs[0]);
+
+    if (fade->frame_index >= fade->start_frame &&
+        fade->frame_index <= fade->stop_frame)
+        fade->factor += fade->fade_per_frame;
+    fade->factor = av_clip_uint16(fade->factor);
+    fade->frame_index++;
+}
+
+AVFilter avfilter_vf_fade = {
+    .name          = "fade",
+    .description   = NULL_IF_CONFIG_SMALL("Fade in/out input video"),
+    .init          = init,
+    .priv_size     = sizeof(FadeContext),
+    .query_formats = query_formats,
+
+    .inputs    = (AVFilterPad[]) {{ .name            = "default",
+                                    .type            = AVMEDIA_TYPE_VIDEO,
+                                    .config_props    = config_props,
+                                    .get_video_buffer = avfilter_null_get_video_buffer,
+                                    .start_frame      = avfilter_null_start_frame,
+                                    .draw_slice      = draw_slice,
+                                    .end_frame       = end_frame,
+                                    .min_perms       = AV_PERM_READ | AV_PERM_WRITE,
+                                    .rej_perms       = AV_PERM_PRESERVE, },
+                                  { .name = NULL}},
+    .outputs   = (AVFilterPad[]) {{ .name            = "default",
+                                    .type            = AVMEDIA_TYPE_VIDEO, },
+                                  { .name = NULL}},
+};
diff --git a/libavfilter/vf_fifo.c b/libavfilter/vf_fifo.c
new file mode 100644
index 0000000..836cce2
--- /dev/null
+++ b/libavfilter/vf_fifo.c
@@ -0,0 +1,119 @@
+/*
+ * Copyright (c) 2007 Bobby Bingham
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * FIFO buffering video filter
+ */
+
+#include "avfilter.h"
+
+typedef struct BufPic {
+    AVFilterBufferRef *picref;
+    struct BufPic     *next;
+} BufPic;
+
+typedef struct {
+    BufPic  root;
+    BufPic *last;   ///< last buffered picture
+} FifoContext;
+
+static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
+{
+    FifoContext *fifo = ctx->priv;
+    fifo->last = &fifo->root;
+
+    av_log(ctx, AV_LOG_INFO, "\n");
+    return 0;
+}
+
+static av_cold void uninit(AVFilterContext *ctx)
+{
+    FifoContext *fifo = ctx->priv;
+    BufPic *pic, *tmp;
+
+    for (pic = fifo->root.next; pic; pic = tmp) {
+        tmp = pic->next;
+        avfilter_unref_buffer(pic->picref);
+        av_free(pic);
+    }
+}
+
+static void start_frame(AVFilterLink *inlink, AVFilterBufferRef *picref)
+{
+    FifoContext *fifo = inlink->dst->priv;
+
+    fifo->last->next = av_mallocz(sizeof(BufPic));
+    fifo->last = fifo->last->next;
+    fifo->last->picref = picref;
+}
+
+static void end_frame(AVFilterLink *inlink) { }
+
+static void draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir) { }
+
+static int request_frame(AVFilterLink *outlink)
+{
+    FifoContext *fifo = outlink->src->priv;
+    BufPic *tmp;
+    int ret;
+
+    if (!fifo->root.next) {
+        if ((ret = avfilter_request_frame(outlink->src->inputs[0]) < 0))
+            return ret;
+    }
+
+    /* by doing this, we give ownership of the reference to the next filter,
+     * so we don't have to worry about dereferencing it ourselves. */
+    avfilter_start_frame(outlink, fifo->root.next->picref);
+    avfilter_draw_slice (outlink, 0, outlink->h, 1);
+    avfilter_end_frame  (outlink);
+
+    if (fifo->last == fifo->root.next)
+        fifo->last = &fifo->root;
+    tmp = fifo->root.next->next;
+    av_free(fifo->root.next);
+    fifo->root.next = tmp;
+
+    return 0;
+}
+
+AVFilter avfilter_vf_fifo = {
+    .name      = "fifo",
+    .description = NULL_IF_CONFIG_SMALL("Buffer input images and send them when they are requested."),
+
+    .init      = init,
+    .uninit    = uninit,
+
+    .priv_size = sizeof(FifoContext),
+
+    .inputs    = (AVFilterPad[]) {{ .name            = "default",
+                                    .type            = AVMEDIA_TYPE_VIDEO,
+                                    .get_video_buffer= avfilter_null_get_video_buffer,
+                                    .start_frame     = start_frame,
+                                    .draw_slice      = draw_slice,
+                                    .end_frame       = end_frame,
+                                    .rej_perms       = AV_PERM_REUSE2, },
+                                  { .name = NULL}},
+    .outputs   = (AVFilterPad[]) {{ .name            = "default",
+                                    .type            = AVMEDIA_TYPE_VIDEO,
+                                    .request_frame   = request_frame, },
+                                  { .name = NULL}},
+};
diff --git a/libavfilter/vf_format.c b/libavfilter/vf_format.c
index 36b7d33..0b0d094 100644
--- a/libavfilter/vf_format.c
+++ b/libavfilter/vf_format.c
@@ -1,20 +1,20 @@
 /*
- * copyright (c) 2007 Bobby Bingham
+ * Copyright (c) 2007 Bobby Bingham
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -94,7 +94,7 @@ static int query_formats_format(AVFilterContext *ctx)
 
 AVFilter avfilter_vf_format = {
     .name      = "format",
-    .description = "Convert the input video to one of the specified pixel formats.",
+    .description = NULL_IF_CONFIG_SMALL("Convert the input video to one of the specified pixel formats."),
 
     .init      = init,
 
@@ -124,7 +124,7 @@ static int query_formats_noformat(AVFilterContext *ctx)
 
 AVFilter avfilter_vf_noformat = {
     .name      = "noformat",
-    .description = "Force libavfilter not to use any of the specified pixel formats for the input to the next filter.",
+    .description = NULL_IF_CONFIG_SMALL("Force libavfilter not to use any of the specified pixel formats for the input to the next filter."),
 
     .init      = init,
 
diff --git a/libavfilter/vf_frei0r.c b/libavfilter/vf_frei0r.c
new file mode 100644
index 0000000..48683f4
--- /dev/null
+++ b/libavfilter/vf_frei0r.c
@@ -0,0 +1,464 @@
+/*
+ * Copyright (c) 2010 Stefano Sabatini
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * frei0r wrapper
+ */
+
+/* #define DEBUG */
+
+#include <dlfcn.h>
+#include <frei0r.h>
+#include "libavutil/avstring.h"
+#include "libavutil/imgutils.h"
+#include "libavutil/parseutils.h"
+#include "avfilter.h"
+
+typedef f0r_instance_t (*f0r_construct_f)(unsigned int width, unsigned int height);
+typedef void (*f0r_destruct_f)(f0r_instance_t instance);
+typedef void (*f0r_deinit_f)(void);
+typedef int (*f0r_init_f)(void);
+typedef void (*f0r_get_plugin_info_f)(f0r_plugin_info_t *info);
+typedef void (*f0r_get_param_info_f)(f0r_param_info_t *info, int param_index);
+typedef void (*f0r_update_f)(f0r_instance_t instance, double time, const uint32_t *inframe, uint32_t *outframe);
+typedef void (*f0r_update2_f)(f0r_instance_t instance, double time, const uint32_t *inframe1, const uint32_t *inframe2, const uint32_t *inframe3, uint32_t *outframe);
+typedef void (*f0r_set_param_value_f)(f0r_instance_t instance, f0r_param_t param, int param_index);
+typedef void (*f0r_get_param_value_f)(f0r_instance_t instance, f0r_param_t param, int param_index);
+
+typedef struct Frei0rContext {
+    f0r_update_f update;
+    void *dl_handle;            /* dynamic library handle   */
+    f0r_instance_t instance;
+    f0r_plugin_info_t plugin_info;
+
+    f0r_get_param_info_f  get_param_info;
+    f0r_get_param_value_f get_param_value;
+    f0r_set_param_value_f set_param_value;
+    f0r_construct_f       construct;
+    f0r_destruct_f        destruct;
+    f0r_deinit_f          deinit;
+    char params[256];
+
+    /* only used by the source */
+    int w, h;
+    AVRational time_base;
+    uint64_t pts;
+} Frei0rContext;
+
+static void *load_sym(AVFilterContext *ctx, const char *sym_name)
+{
+    Frei0rContext *frei0r = ctx->priv;
+    void *sym = dlsym(frei0r->dl_handle, sym_name);
+    if (!sym)
+        av_log(ctx, AV_LOG_ERROR, "Could not find symbol '%s' in loaded module\n", sym_name);
+    return sym;
+}
+
+static int set_param(AVFilterContext *ctx, f0r_param_info_t info, int index, char *param)
+{
+    Frei0rContext *frei0r = ctx->priv;
+    union {
+        double d;
+        f0r_param_color_t col;
+        f0r_param_position_t pos;
+    } val;
+    char *tail;
+    uint8_t rgba[4];
+
+    switch (info.type) {
+    case F0R_PARAM_BOOL:
+        if      (!strcmp(param, "y")) val.d = 1.0;
+        else if (!strcmp(param, "n")) val.d = 0.0;
+        else goto fail;
+        break;
+
+    case F0R_PARAM_DOUBLE:
+        val.d = strtod(param, &tail);
+        if (*tail || val.d == HUGE_VAL)
+            goto fail;
+        break;
+
+    case F0R_PARAM_COLOR:
+        if (sscanf(param, "%f/%f/%f", &val.col.r, &val.col.g, &val.col.b) != 3) {
+            if (av_parse_color(rgba, param, -1, ctx) < 0)
+                goto fail;
+            val.col.r = rgba[0] / 255.0;
+            val.col.g = rgba[1] / 255.0;
+            val.col.b = rgba[2] / 255.0;
+        }
+        break;
+
+    case F0R_PARAM_POSITION:
+        if (sscanf(param, "%lf/%lf", &val.pos.x, &val.pos.y) != 2)
+            goto fail;
+        break;
+    }
+
+    frei0r->set_param_value(frei0r->instance, &val, index);
+    return 0;
+
+fail:
+    av_log(ctx, AV_LOG_ERROR, "Invalid value '%s' for parameter '%s'\n",
+           param, info.name);
+    return AVERROR(EINVAL);
+}
+
+static int set_params(AVFilterContext *ctx, const char *params)
+{
+    Frei0rContext *frei0r = ctx->priv;
+    int i;
+
+    for (i = 0; i < frei0r->plugin_info.num_params; i++) {
+        f0r_param_info_t info;
+        char *param;
+        int ret;
+
+        frei0r->get_param_info(&info, i);
+
+        if (*params) {
+            if (!(param = av_get_token(&params, ":")))
+                return AVERROR(ENOMEM);
+            params++;               /* skip ':' */
+            ret = set_param(ctx, info, i, param);
+            av_free(param);
+            if (ret < 0)
+                return ret;
+        }
+
+        av_log(ctx, AV_LOG_INFO,
+               "idx:%d name:'%s' type:%s explanation:'%s' ",
+               i, info.name,
+               info.type == F0R_PARAM_BOOL     ? "bool"     :
+               info.type == F0R_PARAM_DOUBLE   ? "double"   :
+               info.type == F0R_PARAM_COLOR    ? "color"    :
+               info.type == F0R_PARAM_POSITION ? "position" :
+               info.type == F0R_PARAM_STRING   ? "string"   : "unknown",
+               info.explanation);
+
+#ifdef DEBUG
+        av_log(ctx, AV_LOG_INFO, "value:");
+        switch (info.type) {
+            void *v;
+            double d;
+            char s[128];
+            f0r_param_color_t col;
+            f0r_param_position_t pos;
+
+        case F0R_PARAM_BOOL:
+            v = &d;
+            frei0r->get_param_value(frei0r->instance, v, i);
+            av_log(ctx, AV_LOG_INFO, "%s", d >= 0.5 && d <= 1.0 ? "y" : "n");
+            break;
+        case F0R_PARAM_DOUBLE:
+            v = &d;
+            frei0r->get_param_value(frei0r->instance, v, i);
+            av_log(ctx, AV_LOG_INFO, "%f", d);
+            break;
+        case F0R_PARAM_COLOR:
+            v = &col;
+            frei0r->get_param_value(frei0r->instance, v, i);
+            av_log(ctx, AV_LOG_INFO, "%f/%f/%f", col.r, col.g, col.b);
+            break;
+        case F0R_PARAM_POSITION:
+            v = &pos;
+            frei0r->get_param_value(frei0r->instance, v, i);
+            av_log(ctx, AV_LOG_INFO, "%lf/%lf", pos.x, pos.y);
+            break;
+        default: /* F0R_PARAM_STRING */
+            v = s;
+            frei0r->get_param_value(frei0r->instance, v, i);
+            av_log(ctx, AV_LOG_INFO, "'%s'\n", s);
+            break;
+        }
+#endif
+        av_log(ctx, AV_LOG_INFO, "\n");
+    }
+
+    return 0;
+}
+
+static void *load_path(AVFilterContext *ctx, const char *prefix, const char *name)
+{
+    char path[1024];
+
+    snprintf(path, sizeof(path), "%s%s%s", prefix, name, SLIBSUF);
+    av_log(ctx, AV_LOG_DEBUG, "Looking for frei0r effect in '%s'\n", path);
+    return dlopen(path, RTLD_NOW|RTLD_LOCAL);
+}
+
+static av_cold int frei0r_init(AVFilterContext *ctx,
+                               const char *dl_name, int type)
+{
+    Frei0rContext *frei0r = ctx->priv;
+    f0r_init_f            f0r_init;
+    f0r_get_plugin_info_f f0r_get_plugin_info;
+    f0r_plugin_info_t *pi;
+    char *path;
+
+    /* see: http://piksel.org/frei0r/1.2/spec/1.2/spec/group__pluglocations.html */
+    if ((path = av_strdup(getenv("FREI0R_PATH")))) {
+        char *p, *ptr = NULL;
+        for (p = path; p = strtok_r(p, ":", &ptr); p = NULL)
+            if (frei0r->dl_handle = load_path(ctx, p, dl_name))
+                break;
+        av_free(path);
+    }
+    if (!frei0r->dl_handle && (path = getenv("HOME"))) {
+        char prefix[1024];
+        snprintf(prefix, sizeof(prefix), "%s/.frei0r-1/lib/", path);
+        frei0r->dl_handle = load_path(ctx, prefix, dl_name);
+    }
+    if (!frei0r->dl_handle)
+        frei0r->dl_handle = load_path(ctx, "/usr/local/lib/frei0r-1/", dl_name);
+    if (!frei0r->dl_handle)
+        frei0r->dl_handle = load_path(ctx, "/usr/lib/frei0r-1/", dl_name);
+    if (!frei0r->dl_handle) {
+        av_log(ctx, AV_LOG_ERROR, "Could not find module '%s'\n", dl_name);
+        return AVERROR(EINVAL);
+    }
+
+    if (!(f0r_init                = load_sym(ctx, "f0r_init"           )) ||
+        !(f0r_get_plugin_info     = load_sym(ctx, "f0r_get_plugin_info")) ||
+        !(frei0r->get_param_info  = load_sym(ctx, "f0r_get_param_info" )) ||
+        !(frei0r->get_param_value = load_sym(ctx, "f0r_get_param_value")) ||
+        !(frei0r->set_param_value = load_sym(ctx, "f0r_set_param_value")) ||
+        !(frei0r->update          = load_sym(ctx, "f0r_update"         )) ||
+        !(frei0r->construct       = load_sym(ctx, "f0r_construct"      )) ||
+        !(frei0r->destruct        = load_sym(ctx, "f0r_destruct"       )) ||
+        !(frei0r->deinit          = load_sym(ctx, "f0r_deinit"         )))
+        return AVERROR(EINVAL);
+
+    if (f0r_init() < 0) {
+        av_log(ctx, AV_LOG_ERROR, "Could not init the frei0r module");
+        return AVERROR(EINVAL);
+    }
+
+    f0r_get_plugin_info(&frei0r->plugin_info);
+    pi = &frei0r->plugin_info;
+    if (pi->plugin_type != type) {
+        av_log(ctx, AV_LOG_ERROR,
+               "Invalid type '%s' for the plugin\n",
+               pi->plugin_type == F0R_PLUGIN_TYPE_FILTER ? "filter" :
+               pi->plugin_type == F0R_PLUGIN_TYPE_SOURCE ? "source" :
+               pi->plugin_type == F0R_PLUGIN_TYPE_MIXER2 ? "mixer2" :
+               pi->plugin_type == F0R_PLUGIN_TYPE_MIXER3 ? "mixer3" : "unknown");
+        return AVERROR(EINVAL);
+    }
+
+    av_log(ctx, AV_LOG_INFO,
+           "name:%s author:'%s' explanation:'%s' color_model:%s "
+           "frei0r_version:%d version:%d.%d num_params:%d\n",
+           pi->name, pi->author, pi->explanation,
+           pi->color_model == F0R_COLOR_MODEL_BGRA8888 ? "bgra8888" :
+           pi->color_model == F0R_COLOR_MODEL_RGBA8888 ? "rgba8888" :
+           pi->color_model == F0R_COLOR_MODEL_PACKED32 ? "packed32" : "unknown",
+           pi->frei0r_version, pi->major_version, pi->minor_version, pi->num_params);
+
+    return 0;
+}
+
+static av_cold int filter_init(AVFilterContext *ctx, const char *args, void *opaque)
+{
+    Frei0rContext *frei0r = ctx->priv;
+    char dl_name[1024], c;
+    *frei0r->params = 0;
+
+    if (args)
+        sscanf(args, "%1023[^:=]%c%255c", dl_name, &c, frei0r->params);
+
+    return frei0r_init(ctx, dl_name, F0R_PLUGIN_TYPE_FILTER);
+}
+
+static av_cold void uninit(AVFilterContext *ctx)
+{
+    Frei0rContext *frei0r = ctx->priv;
+
+    if (frei0r->destruct && frei0r->instance)
+        frei0r->destruct(frei0r->instance);
+    if (frei0r->deinit)
+        frei0r->deinit();
+    if (frei0r->dl_handle)
+        dlclose(frei0r->dl_handle);
+
+    memset(frei0r, 0, sizeof(*frei0r));
+}
+
+static int config_input_props(AVFilterLink *inlink)
+{
+    AVFilterContext *ctx = inlink->dst;
+    Frei0rContext *frei0r = ctx->priv;
+
+    if (!(frei0r->instance = frei0r->construct(inlink->w, inlink->h))) {
+        av_log(ctx, AV_LOG_ERROR, "Impossible to load frei0r instance");
+        return AVERROR(EINVAL);
+    }
+
+    return set_params(ctx, frei0r->params);
+}
+
+static int query_formats(AVFilterContext *ctx)
+{
+    Frei0rContext *frei0r = ctx->priv;
+    AVFilterFormats *formats = NULL;
+
+    if        (frei0r->plugin_info.color_model == F0R_COLOR_MODEL_BGRA8888) {
+        avfilter_add_format(&formats, PIX_FMT_BGRA);
+    } else if (frei0r->plugin_info.color_model == F0R_COLOR_MODEL_RGBA8888) {
+        avfilter_add_format(&formats, PIX_FMT_RGBA);
+    } else {                                   /* F0R_COLOR_MODEL_PACKED32 */
+        static const enum PixelFormat pix_fmts[] = {
+            PIX_FMT_BGRA, PIX_FMT_ARGB, PIX_FMT_ABGR, PIX_FMT_ARGB, PIX_FMT_NONE
+        };
+        formats = avfilter_make_format_list(pix_fmts);
+    }
+
+    if (!formats)
+        return AVERROR(ENOMEM);
+
+    avfilter_set_common_formats(ctx, formats);
+    return 0;
+}
+
+static void null_draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir) { }
+
+static void end_frame(AVFilterLink *inlink)
+{
+    Frei0rContext *frei0r = inlink->dst->priv;
+    AVFilterLink *outlink = inlink->dst->outputs[0];
+    AVFilterBufferRef  *inpicref =  inlink->cur_buf;
+    AVFilterBufferRef *outpicref = outlink->out_buf;
+
+    frei0r->update(frei0r->instance, inpicref->pts * av_q2d(inlink->time_base) * 1000,
+                   (const uint32_t *)inpicref->data[0],
+                   (uint32_t *)outpicref->data[0]);
+    avfilter_unref_buffer(inpicref);
+    avfilter_draw_slice(outlink, 0, outlink->h, 1);
+    avfilter_end_frame(outlink);
+    avfilter_unref_buffer(outpicref);
+}
+
+AVFilter avfilter_vf_frei0r = {
+    .name      = "frei0r",
+    .description = NULL_IF_CONFIG_SMALL("Apply a frei0r effect."),
+
+    .query_formats = query_formats,
+    .init = filter_init,
+    .uninit = uninit,
+
+    .priv_size = sizeof(Frei0rContext),
+
+    .inputs    = (AVFilterPad[]) {{ .name             = "default",
+                                    .type             = AVMEDIA_TYPE_VIDEO,
+                                    .draw_slice       = null_draw_slice,
+                                    .config_props     = config_input_props,
+                                    .end_frame        = end_frame,
+                                    .min_perms        = AV_PERM_READ },
+                                  { .name = NULL}},
+
+    .outputs   = (AVFilterPad[]) {{ .name             = "default",
+                                    .type             = AVMEDIA_TYPE_VIDEO, },
+                                  { .name = NULL}},
+};
+
+static av_cold int source_init(AVFilterContext *ctx, const char *args, void *opaque)
+{
+    Frei0rContext *frei0r = ctx->priv;
+    char dl_name[1024], c;
+    char frame_size[128] = "";
+    char frame_rate[128] = "";
+    AVRational frame_rate_q;
+
+    memset(frei0r->params, 0, sizeof(frei0r->params));
+
+    if (args)
+        sscanf(args, "%127[^:]:%127[^:]:%1023[^:=]%c%255c",
+               frame_size, frame_rate, dl_name, &c, frei0r->params);
+
+    if (av_parse_video_size(&frei0r->w, &frei0r->h, frame_size) < 0) {
+        av_log(ctx, AV_LOG_ERROR, "Invalid frame size: '%s'\n", frame_size);
+        return AVERROR(EINVAL);
+    }
+
+    if (av_parse_video_rate(&frame_rate_q, frame_rate) < 0 ||
+        frame_rate_q.den <= 0 || frame_rate_q.num <= 0) {
+        av_log(ctx, AV_LOG_ERROR, "Invalid frame rate: '%s'\n", frame_rate);
+        return AVERROR(EINVAL);
+    }
+    frei0r->time_base.num = frame_rate_q.den;
+    frei0r->time_base.den = frame_rate_q.num;
+
+    return frei0r_init(ctx, dl_name, F0R_PLUGIN_TYPE_SOURCE);
+}
+
+static int source_config_props(AVFilterLink *outlink)
+{
+    AVFilterContext *ctx = outlink->src;
+    Frei0rContext *frei0r = ctx->priv;
+
+    if (av_image_check_size(frei0r->w, frei0r->h, 0, ctx) < 0)
+        return AVERROR(EINVAL);
+    outlink->w = frei0r->w;
+    outlink->h = frei0r->h;
+    outlink->time_base = frei0r->time_base;
+
+    if (!(frei0r->instance = frei0r->construct(outlink->w, outlink->h))) {
+        av_log(ctx, AV_LOG_ERROR, "Impossible to load frei0r instance");
+        return AVERROR(EINVAL);
+    }
+
+    return set_params(ctx, frei0r->params);
+}
+
+static int source_request_frame(AVFilterLink *outlink)
+{
+    Frei0rContext *frei0r = outlink->src->priv;
+    AVFilterBufferRef *picref = avfilter_get_video_buffer(outlink, AV_PERM_WRITE, outlink->w, outlink->h);
+    picref->video->pixel_aspect = (AVRational) {1, 1};
+    picref->pts = frei0r->pts++;
+    picref->pos = -1;
+
+    avfilter_start_frame(outlink, avfilter_ref_buffer(picref, ~0));
+    frei0r->update(frei0r->instance, av_rescale_q(picref->pts, frei0r->time_base, (AVRational){1,1000}),
+                   NULL, (uint32_t *)picref->data[0]);
+    avfilter_draw_slice(outlink, 0, outlink->h, 1);
+    avfilter_end_frame(outlink);
+    avfilter_unref_buffer(picref);
+
+    return 0;
+}
+
+AVFilter avfilter_vsrc_frei0r_src = {
+    .name        = "frei0r_src",
+    .description = NULL_IF_CONFIG_SMALL("Generate a frei0r source."),
+
+    .priv_size = sizeof(Frei0rContext),
+    .init      = source_init,
+    .uninit    = uninit,
+
+    .query_formats = query_formats,
+
+    .inputs    = (AVFilterPad[]) {{ .name = NULL}},
+
+    .outputs   = (AVFilterPad[]) {{ .name            = "default",
+                                    .type            = AVMEDIA_TYPE_VIDEO,
+                                    .request_frame   = source_request_frame,
+                                    .config_props    = source_config_props },
+                                  { .name = NULL}},
+};
diff --git a/libavfilter/vf_gradfun.c b/libavfilter/vf_gradfun.c
new file mode 100644
index 0000000..c6663c4
--- /dev/null
+++ b/libavfilter/vf_gradfun.c
@@ -0,0 +1,254 @@
+/*
+ * Copyright (c) 2010 Nolan Lum <nol888 at gmail.com>
+ * Copyright (c) 2009 Loren Merritt <lorenm at u.washignton.edu>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * gradfun debanding filter, ported from MPlayer
+ * libmpcodecs/vf_gradfun.c
+ *
+ * Apply a boxblur debanding algorithm (based on the gradfun2db
+ * Avisynth filter by prunedtree).
+ * Foreach pixel, if it's within threshold of the blurred value, make it closer.
+ * So now we have a smoothed and higher bitdepth version of all the shallow
+ * gradients, while leaving detailed areas untouched.
+ * Dither it back to 8bit.
+ */
+
+#include "libavutil/imgutils.h"
+#include "libavutil/cpu.h"
+#include "libavutil/pixdesc.h"
+#include "avfilter.h"
+#include "gradfun.h"
+
+DECLARE_ALIGNED(16, static const uint16_t, dither)[8][8] = {
+    {0x00,0x60,0x18,0x78,0x06,0x66,0x1E,0x7E},
+    {0x40,0x20,0x58,0x38,0x46,0x26,0x5E,0x3E},
+    {0x10,0x70,0x08,0x68,0x16,0x76,0x0E,0x6E},
+    {0x50,0x30,0x48,0x28,0x56,0x36,0x4E,0x2E},
+    {0x04,0x64,0x1C,0x7C,0x02,0x62,0x1A,0x7A},
+    {0x44,0x24,0x5C,0x3C,0x42,0x22,0x5A,0x3A},
+    {0x14,0x74,0x0C,0x6C,0x12,0x72,0x0A,0x6A},
+    {0x54,0x34,0x4C,0x2C,0x52,0x32,0x4A,0x2A},
+};
+
+void ff_gradfun_filter_line_c(uint8_t *dst, uint8_t *src, uint16_t *dc, int width, int thresh, const uint16_t *dithers)
+{
+    int x;
+    for (x = 0; x < width; x++, dc += x & 1) {
+        int pix = src[x] << 7;
+        int delta = dc[0] - pix;
+        int m = abs(delta) * thresh >> 16;
+        m = FFMAX(0, 127 - m);
+        m = m * m * delta >> 14;
+        pix += m + dithers[x & 7];
+        dst[x] = av_clip_uint8(pix >> 7);
+    }
+}
+
+void ff_gradfun_blur_line_c(uint16_t *dc, uint16_t *buf, uint16_t *buf1, uint8_t *src, int src_linesize, int width)
+{
+    int x, v, old;
+    for (x = 0; x < width; x++) {
+        v = buf1[x] + src[2 * x] + src[2 * x + 1] + src[2 * x + src_linesize] + src[2 * x + 1 + src_linesize];
+        old = buf[x];
+        buf[x] = v;
+        dc[x] = v - old;
+    }
+}
+
+static void filter(GradFunContext *ctx, uint8_t *dst, uint8_t *src, int width, int height, int dst_linesize, int src_linesize, int r)
+{
+    int bstride = FFALIGN(width, 16) / 2;
+    int y;
+    uint32_t dc_factor = (1 << 21) / (r * r);
+    uint16_t *dc = ctx->buf + 16;
+    uint16_t *buf = ctx->buf + bstride + 32;
+    int thresh = ctx->thresh;
+
+    memset(dc, 0, (bstride + 16) * sizeof(*buf));
+    for (y = 0; y < r; y++)
+        ctx->blur_line(dc, buf + y * bstride, buf + (y - 1) * bstride, src + 2 * y * src_linesize, src_linesize, width / 2);
+    for (;;) {
+        if (y < height - r) {
+            int mod = ((y + r) / 2) % r;
+            uint16_t *buf0 = buf + mod * bstride;
+            uint16_t *buf1 = buf + (mod ? mod - 1 : r - 1) * bstride;
+            int x, v;
+            ctx->blur_line(dc, buf0, buf1, src + (y + r) * src_linesize, src_linesize, width / 2);
+            for (x = v = 0; x < r; x++)
+                v += dc[x];
+            for (; x < width / 2; x++) {
+                v += dc[x] - dc[x-r];
+                dc[x-r] = v * dc_factor >> 16;
+            }
+            for (; x < (width + r + 1) / 2; x++)
+                dc[x-r] = v * dc_factor >> 16;
+            for (x = -r / 2; x < 0; x++)
+                dc[x] = dc[0];
+        }
+        if (y == r) {
+            for (y = 0; y < r; y++)
+                ctx->filter_line(dst + y * dst_linesize, src + y * src_linesize, dc - r / 2, width, thresh, dither[y & 7]);
+        }
+        ctx->filter_line(dst + y * dst_linesize, src + y * src_linesize, dc - r / 2, width, thresh, dither[y & 7]);
+        if (++y >= height) break;
+        ctx->filter_line(dst + y * dst_linesize, src + y * src_linesize, dc - r / 2, width, thresh, dither[y & 7]);
+        if (++y >= height) break;
+    }
+}
+
+static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
+{
+    GradFunContext *gf = ctx->priv;
+    float thresh = 1.2;
+    int radius = 16;
+    av_unused int cpu_flags = av_get_cpu_flags();
+
+    if (args)
+        sscanf(args, "%f:%d", &thresh, &radius);
+
+    thresh = av_clipf(thresh, 0.51, 255);
+    gf->thresh = (1 << 15) / thresh;
+    gf->radius = av_clip((radius + 1) & ~1, 4, 32);
+
+    gf->blur_line = ff_gradfun_blur_line_c;
+    gf->filter_line = ff_gradfun_filter_line_c;
+
+    if (HAVE_MMX && cpu_flags & AV_CPU_FLAG_MMX2)
+        gf->filter_line = ff_gradfun_filter_line_mmx2;
+    if (HAVE_SSSE3 && cpu_flags & AV_CPU_FLAG_SSSE3)
+        gf->filter_line = ff_gradfun_filter_line_ssse3;
+    if (HAVE_SSE && cpu_flags & AV_CPU_FLAG_SSE2)
+        gf->blur_line = ff_gradfun_blur_line_sse2;
+
+    av_log(ctx, AV_LOG_INFO, "threshold:%.2f radius:%d\n", thresh, gf->radius);
+
+    return 0;
+}
+
+static av_cold void uninit(AVFilterContext *ctx)
+{
+    GradFunContext *gf = ctx->priv;
+    av_freep(&gf->buf);
+}
+
+static int query_formats(AVFilterContext *ctx)
+{
+    static const enum PixelFormat pix_fmts[] = {
+        PIX_FMT_YUV410P,            PIX_FMT_YUV420P,
+        PIX_FMT_GRAY8,              PIX_FMT_NV12,
+        PIX_FMT_NV21,               PIX_FMT_YUV444P,
+        PIX_FMT_YUV422P,            PIX_FMT_YUV411P,
+        PIX_FMT_NONE
+    };
+
+    avfilter_set_common_formats(ctx, avfilter_make_format_list(pix_fmts));
+
+    return 0;
+}
+
+static int config_input(AVFilterLink *inlink)
+{
+    GradFunContext *gf = inlink->dst->priv;
+    int hsub = av_pix_fmt_descriptors[inlink->format].log2_chroma_w;
+    int vsub = av_pix_fmt_descriptors[inlink->format].log2_chroma_h;
+
+    gf->buf = av_mallocz((FFALIGN(inlink->w, 16) * (gf->radius + 1) / 2 + 32) * sizeof(uint16_t));
+    if (!gf->buf)
+        return AVERROR(ENOMEM);
+
+    gf->chroma_w = -((-inlink->w) >> hsub);
+    gf->chroma_h = -((-inlink->h) >> vsub);
+    gf->chroma_r = av_clip(((((gf->radius >> hsub) + (gf->radius >> vsub)) / 2 ) + 1) & ~1, 4, 32);
+
+    return 0;
+}
+
+static void start_frame(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
+{
+    AVFilterLink *outlink = inlink->dst->outputs[0];
+    AVFilterBufferRef *outpicref;
+
+    if (inpicref->perms & AV_PERM_PRESERVE) {
+        outpicref = avfilter_get_video_buffer(outlink, AV_PERM_WRITE, outlink->w, outlink->h);
+        avfilter_copy_buffer_ref_props(outpicref, inpicref);
+        outpicref->video->w = outlink->w;
+        outpicref->video->h = outlink->h;
+    } else
+        outpicref = inpicref;
+
+    outlink->out_buf = outpicref;
+    avfilter_start_frame(outlink, avfilter_ref_buffer(outpicref, ~0));
+}
+
+static void null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir) { }
+
+static void end_frame(AVFilterLink *inlink)
+{
+    GradFunContext *gf = inlink->dst->priv;
+    AVFilterBufferRef *inpic = inlink->cur_buf;
+    AVFilterLink *outlink = inlink->dst->outputs[0];
+    AVFilterBufferRef *outpic = outlink->out_buf;
+    int p;
+
+    for (p = 0; p < 4 && inpic->data[p]; p++) {
+        int w = inlink->w;
+        int h = inlink->h;
+        int r = gf->radius;
+        if (p) {
+            w = gf->chroma_w;
+            h = gf->chroma_h;
+            r = gf->chroma_r;
+        }
+
+        if (FFMIN(w, h) > 2 * r)
+            filter(gf, outpic->data[p], inpic->data[p], w, h, outpic->linesize[p], inpic->linesize[p], r);
+        else if (outpic->data[p] != inpic->data[p])
+            av_image_copy_plane(outpic->data[p], outpic->linesize[p], inpic->data[p], inpic->linesize[p], w, h);
+    }
+
+    avfilter_draw_slice(outlink, 0, inlink->h, 1);
+    avfilter_end_frame(outlink);
+    avfilter_unref_buffer(inpic);
+    if (outpic != inpic)
+        avfilter_unref_buffer(outpic);
+}
+
+AVFilter avfilter_vf_gradfun = {
+    .name          = "gradfun",
+    .description   = NULL_IF_CONFIG_SMALL("Debands video quickly using gradients."),
+    .priv_size     = sizeof(GradFunContext),
+    .init          = init,
+    .uninit        = uninit,
+    .query_formats = query_formats,
+
+    .inputs    = (AVFilterPad[]) {{ .name             = "default",
+                                    .type             = AVMEDIA_TYPE_VIDEO,
+                                    .config_props     = config_input,
+                                    .start_frame      = start_frame,
+                                    .draw_slice       = null_draw_slice,
+                                    .end_frame        = end_frame,
+                                    .min_perms        = AV_PERM_READ, },
+                                  { .name = NULL}},
+    .outputs   = (AVFilterPad[]) {{ .name             = "default",
+                                    .type             = AVMEDIA_TYPE_VIDEO, },
+                                  { .name = NULL}},
+};
diff --git a/libavfilter/vf_hflip.c b/libavfilter/vf_hflip.c
new file mode 100644
index 0000000..a232d26
--- /dev/null
+++ b/libavfilter/vf_hflip.c
@@ -0,0 +1,161 @@
+/*
+ * Copyright (c) 2007 Benoit Fouet
+ * Copyright (c) 2010 Stefano Sabatini
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * horizontal flip filter
+ */
+
+#include "avfilter.h"
+#include "libavutil/pixdesc.h"
+#include "libavutil/intreadwrite.h"
+#include "libavutil/imgutils.h"
+
+typedef struct {
+    int max_step[4];    ///< max pixel step for each plane, expressed as a number of bytes
+    int hsub, vsub;     ///< chroma subsampling
+} FlipContext;
+
+static int query_formats(AVFilterContext *ctx)
+{
+    static const enum PixelFormat pix_fmts[] = {
+        PIX_FMT_RGB48BE,      PIX_FMT_RGB48LE,
+        PIX_FMT_ARGB,         PIX_FMT_RGBA,
+        PIX_FMT_ABGR,         PIX_FMT_BGRA,
+        PIX_FMT_RGB24,        PIX_FMT_BGR24,
+        PIX_FMT_RGB565BE,     PIX_FMT_RGB565LE,
+        PIX_FMT_RGB555BE,     PIX_FMT_RGB555LE,
+        PIX_FMT_BGR565BE,     PIX_FMT_BGR565LE,
+        PIX_FMT_BGR555BE,     PIX_FMT_BGR555LE,
+        PIX_FMT_GRAY16BE,     PIX_FMT_GRAY16LE,
+        PIX_FMT_YUV420P16LE,  PIX_FMT_YUV420P16BE,
+        PIX_FMT_YUV422P16LE,  PIX_FMT_YUV422P16BE,
+        PIX_FMT_YUV444P16LE,  PIX_FMT_YUV444P16BE,
+        PIX_FMT_YUV444P,      PIX_FMT_YUV422P,
+        PIX_FMT_YUV420P,      PIX_FMT_YUV411P,
+        PIX_FMT_YUV410P,      PIX_FMT_YUV440P,
+        PIX_FMT_YUVJ444P,     PIX_FMT_YUVJ422P,
+        PIX_FMT_YUVJ420P,     PIX_FMT_YUVJ440P,
+        PIX_FMT_YUVA420P,
+        PIX_FMT_RGB8,         PIX_FMT_BGR8,
+        PIX_FMT_RGB4_BYTE,    PIX_FMT_BGR4_BYTE,
+        PIX_FMT_PAL8,         PIX_FMT_GRAY8,
+        PIX_FMT_NONE
+    };
+
+    avfilter_set_common_formats(ctx, avfilter_make_format_list(pix_fmts));
+    return 0;
+}
+
+static int config_props(AVFilterLink *inlink)
+{
+    FlipContext *flip = inlink->dst->priv;
+    const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[inlink->format];
+
+    av_image_fill_max_pixsteps(flip->max_step, NULL, pix_desc);
+    flip->hsub = av_pix_fmt_descriptors[inlink->format].log2_chroma_w;
+    flip->vsub = av_pix_fmt_descriptors[inlink->format].log2_chroma_h;
+
+    return 0;
+}
+
+static void draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir)
+{
+    FlipContext *flip = inlink->dst->priv;
+    AVFilterBufferRef *inpic  = inlink->cur_buf;
+    AVFilterBufferRef *outpic = inlink->dst->outputs[0]->out_buf;
+    uint8_t *inrow, *outrow;
+    int i, j, plane, step, hsub, vsub;
+
+    for (plane = 0; plane < 4 && inpic->data[plane]; plane++) {
+        step = flip->max_step[plane];
+        hsub = (plane == 1 || plane == 2) ? flip->hsub : 0;
+        vsub = (plane == 1 || plane == 2) ? flip->vsub : 0;
+
+        outrow = outpic->data[plane] + (y>>vsub) * outpic->linesize[plane];
+        inrow  = inpic ->data[plane] + (y>>vsub) * inpic ->linesize[plane] + ((inlink->w >> hsub) - 1) * step;
+        for (i = 0; i < h>>vsub; i++) {
+            switch (step) {
+            case 1:
+            {
+                for (j = 0; j < (inlink->w >> hsub); j++)
+                    outrow[j] = inrow[-j];
+            }
+            break;
+
+            case 2:
+            {
+                uint16_t *outrow16 = (uint16_t *)outrow;
+                uint16_t * inrow16 = (uint16_t *) inrow;
+                for (j = 0; j < (inlink->w >> hsub); j++)
+                    outrow16[j] = inrow16[-j];
+            }
+            break;
+
+            case 3:
+            {
+                uint8_t *in  =  inrow;
+                uint8_t *out = outrow;
+                for (j = 0; j < (inlink->w >> hsub); j++, out += 3, in -= 3) {
+                    int32_t v = AV_RB24(in);
+                    AV_WB24(out, v);
+                }
+            }
+            break;
+
+            case 4:
+            {
+                uint32_t *outrow32 = (uint32_t *)outrow;
+                uint32_t * inrow32 = (uint32_t *) inrow;
+                for (j = 0; j < (inlink->w >> hsub); j++)
+                    outrow32[j] = inrow32[-j];
+            }
+            break;
+
+            default:
+                for (j = 0; j < (inlink->w >> hsub); j++)
+                    memcpy(outrow + j*step, inrow - j*step, step);
+            }
+
+            inrow  += inpic ->linesize[plane];
+            outrow += outpic->linesize[plane];
+        }
+    }
+
+    avfilter_draw_slice(inlink->dst->outputs[0], y, h, slice_dir);
+}
+
+AVFilter avfilter_vf_hflip = {
+    .name      = "hflip",
+    .description = NULL_IF_CONFIG_SMALL("Horizontally flip the input video."),
+    .priv_size = sizeof(FlipContext),
+    .query_formats = query_formats,
+
+    .inputs    = (AVFilterPad[]) {{ .name            = "default",
+                                    .type            = AVMEDIA_TYPE_VIDEO,
+                                    .draw_slice      = draw_slice,
+                                    .config_props    = config_props,
+                                    .min_perms       = AV_PERM_READ, },
+                                  { .name = NULL}},
+    .outputs   = (AVFilterPad[]) {{ .name            = "default",
+                                    .type            = AVMEDIA_TYPE_VIDEO, },
+                                  { .name = NULL}},
+};
diff --git a/libavfilter/vf_hqdn3d.c b/libavfilter/vf_hqdn3d.c
new file mode 100644
index 0000000..2e9a895
--- /dev/null
+++ b/libavfilter/vf_hqdn3d.c
@@ -0,0 +1,345 @@
+/*
+ * Copyright (c) 2003 Daniel Moreno <comac AT comac DOT darktech DOT org>
+ * Copyright (c) 2010 Baptiste Coudurier
+ *
+ * This file is part of Libav, ported from MPlayer.
+ *
+ * Libav is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with Libav; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+
+/**
+ * @file
+ * high quality 3d video denoiser, ported from MPlayer
+ * libmpcodecs/vf_hqdn3d.c.
+ */
+
+#include "libavutil/pixdesc.h"
+#include "avfilter.h"
+
+typedef struct {
+    int Coefs[4][512*16];
+    unsigned int *Line;
+    unsigned short *Frame[3];
+    int hsub, vsub;
+} HQDN3DContext;
+
+static inline unsigned int LowPassMul(unsigned int PrevMul, unsigned int CurrMul, int *Coef)
+{
+    //    int dMul= (PrevMul&0xFFFFFF)-(CurrMul&0xFFFFFF);
+    int dMul= PrevMul-CurrMul;
+    unsigned int d=((dMul+0x10007FF)>>12);
+    return CurrMul + Coef[d];
+}
+
+static void deNoiseTemporal(unsigned char *FrameSrc,
+                            unsigned char *FrameDest,
+                            unsigned short *FrameAnt,
+                            int W, int H, int sStride, int dStride,
+                            int *Temporal)
+{
+    long X, Y;
+    unsigned int PixelDst;
+
+    for (Y = 0; Y < H; Y++) {
+        for (X = 0; X < W; X++) {
+            PixelDst = LowPassMul(FrameAnt[X]<<8, FrameSrc[X]<<16, Temporal);
+            FrameAnt[X] = ((PixelDst+0x1000007F)>>8);
+            FrameDest[X]= ((PixelDst+0x10007FFF)>>16);
+        }
+        FrameSrc  += sStride;
+        FrameDest += dStride;
+        FrameAnt += W;
+    }
+}
+
+static void deNoiseSpacial(unsigned char *Frame,
+                           unsigned char *FrameDest,
+                           unsigned int *LineAnt,
+                           int W, int H, int sStride, int dStride,
+                           int *Horizontal, int *Vertical)
+{
+    long X, Y;
+    long sLineOffs = 0, dLineOffs = 0;
+    unsigned int PixelAnt;
+    unsigned int PixelDst;
+
+    /* First pixel has no left nor top neighbor. */
+    PixelDst = LineAnt[0] = PixelAnt = Frame[0]<<16;
+    FrameDest[0]= ((PixelDst+0x10007FFF)>>16);
+
+    /* First line has no top neighbor, only left. */
+    for (X = 1; X < W; X++) {
+        PixelDst = LineAnt[X] = LowPassMul(PixelAnt, Frame[X]<<16, Horizontal);
+        FrameDest[X]= ((PixelDst+0x10007FFF)>>16);
+    }
+
+    for (Y = 1; Y < H; Y++) {
+        unsigned int PixelAnt;
+        sLineOffs += sStride, dLineOffs += dStride;
+        /* First pixel on each line doesn't have previous pixel */
+        PixelAnt = Frame[sLineOffs]<<16;
+        PixelDst = LineAnt[0] = LowPassMul(LineAnt[0], PixelAnt, Vertical);
+        FrameDest[dLineOffs]= ((PixelDst+0x10007FFF)>>16);
+
+        for (X = 1; X < W; X++) {
+            unsigned int PixelDst;
+            /* The rest are normal */
+            PixelAnt = LowPassMul(PixelAnt, Frame[sLineOffs+X]<<16, Horizontal);
+            PixelDst = LineAnt[X] = LowPassMul(LineAnt[X], PixelAnt, Vertical);
+            FrameDest[dLineOffs+X]= ((PixelDst+0x10007FFF)>>16);
+        }
+    }
+}
+
+static void deNoise(unsigned char *Frame,
+                    unsigned char *FrameDest,
+                    unsigned int *LineAnt,
+                    unsigned short **FrameAntPtr,
+                    int W, int H, int sStride, int dStride,
+                    int *Horizontal, int *Vertical, int *Temporal)
+{
+    long X, Y;
+    long sLineOffs = 0, dLineOffs = 0;
+    unsigned int PixelAnt;
+    unsigned int PixelDst;
+    unsigned short* FrameAnt=(*FrameAntPtr);
+
+    if (!FrameAnt) {
+        (*FrameAntPtr) = FrameAnt = av_malloc(W*H*sizeof(unsigned short));
+        for (Y = 0; Y < H; Y++) {
+            unsigned short* dst=&FrameAnt[Y*W];
+            unsigned char* src=Frame+Y*sStride;
+            for (X = 0; X < W; X++) dst[X]=src[X]<<8;
+        }
+    }
+
+    if (!Horizontal[0] && !Vertical[0]) {
+        deNoiseTemporal(Frame, FrameDest, FrameAnt,
+                        W, H, sStride, dStride, Temporal);
+        return;
+    }
+    if (!Temporal[0]) {
+        deNoiseSpacial(Frame, FrameDest, LineAnt,
+                       W, H, sStride, dStride, Horizontal, Vertical);
+        return;
+    }
+
+    /* First pixel has no left nor top neighbor. Only previous frame */
+    LineAnt[0] = PixelAnt = Frame[0]<<16;
+    PixelDst = LowPassMul(FrameAnt[0]<<8, PixelAnt, Temporal);
+    FrameAnt[0] = ((PixelDst+0x1000007F)>>8);
+    FrameDest[0]= ((PixelDst+0x10007FFF)>>16);
+
+    /* First line has no top neighbor. Only left one for each pixel and
+     * last frame */
+    for (X = 1; X < W; X++) {
+        LineAnt[X] = PixelAnt = LowPassMul(PixelAnt, Frame[X]<<16, Horizontal);
+        PixelDst = LowPassMul(FrameAnt[X]<<8, PixelAnt, Temporal);
+        FrameAnt[X] = ((PixelDst+0x1000007F)>>8);
+        FrameDest[X]= ((PixelDst+0x10007FFF)>>16);
+    }
+
+    for (Y = 1; Y < H; Y++) {
+        unsigned int PixelAnt;
+        unsigned short* LinePrev=&FrameAnt[Y*W];
+        sLineOffs += sStride, dLineOffs += dStride;
+        /* First pixel on each line doesn't have previous pixel */
+        PixelAnt = Frame[sLineOffs]<<16;
+        LineAnt[0] = LowPassMul(LineAnt[0], PixelAnt, Vertical);
+        PixelDst = LowPassMul(LinePrev[0]<<8, LineAnt[0], Temporal);
+        LinePrev[0] = ((PixelDst+0x1000007F)>>8);
+        FrameDest[dLineOffs]= ((PixelDst+0x10007FFF)>>16);
+
+        for (X = 1; X < W; X++) {
+            unsigned int PixelDst;
+            /* The rest are normal */
+            PixelAnt = LowPassMul(PixelAnt, Frame[sLineOffs+X]<<16, Horizontal);
+            LineAnt[X] = LowPassMul(LineAnt[X], PixelAnt, Vertical);
+            PixelDst = LowPassMul(LinePrev[X]<<8, LineAnt[X], Temporal);
+            LinePrev[X] = ((PixelDst+0x1000007F)>>8);
+            FrameDest[dLineOffs+X]= ((PixelDst+0x10007FFF)>>16);
+        }
+    }
+}
+
+static void PrecalcCoefs(int *Ct, double Dist25)
+{
+    int i;
+    double Gamma, Simil, C;
+
+    Gamma = log(0.25) / log(1.0 - Dist25/255.0 - 0.00001);
+
+    for (i = -255*16; i <= 255*16; i++) {
+        Simil = 1.0 - FFABS(i) / (16*255.0);
+        C = pow(Simil, Gamma) * 65536.0 * i / 16.0;
+        Ct[16*256+i] = lrint(C);
+    }
+
+    Ct[0] = !!Dist25;
+}
+
+#define PARAM1_DEFAULT 4.0
+#define PARAM2_DEFAULT 3.0
+#define PARAM3_DEFAULT 6.0
+
+static int init(AVFilterContext *ctx, const char *args, void *opaque)
+{
+    HQDN3DContext *hqdn3d = ctx->priv;
+    double LumSpac, LumTmp, ChromSpac, ChromTmp;
+    double Param1, Param2, Param3, Param4;
+
+    LumSpac   = PARAM1_DEFAULT;
+    ChromSpac = PARAM2_DEFAULT;
+    LumTmp    = PARAM3_DEFAULT;
+    ChromTmp  = LumTmp * ChromSpac / LumSpac;
+
+    if (args) {
+        switch (sscanf(args, "%lf:%lf:%lf:%lf",
+                       &Param1, &Param2, &Param3, &Param4)) {
+        case 1:
+            LumSpac   = Param1;
+            ChromSpac = PARAM2_DEFAULT * Param1 / PARAM1_DEFAULT;
+            LumTmp    = PARAM3_DEFAULT * Param1 / PARAM1_DEFAULT;
+            ChromTmp  = LumTmp * ChromSpac / LumSpac;
+            break;
+        case 2:
+            LumSpac   = Param1;
+            ChromSpac = Param2;
+            LumTmp    = PARAM3_DEFAULT * Param1 / PARAM1_DEFAULT;
+            ChromTmp  = LumTmp * ChromSpac / LumSpac;
+            break;
+        case 3:
+            LumSpac   = Param1;
+            ChromSpac = Param2;
+            LumTmp    = Param3;
+            ChromTmp  = LumTmp * ChromSpac / LumSpac;
+            break;
+        case 4:
+            LumSpac   = Param1;
+            ChromSpac = Param2;
+            LumTmp    = Param3;
+            ChromTmp  = Param4;
+            break;
+        }
+    }
+
+    av_log(ctx, AV_LOG_INFO, "ls:%lf cs:%lf lt:%lf ct:%lf\n",
+           LumSpac, ChromSpac, LumTmp, ChromTmp);
+    if (LumSpac < 0 || ChromSpac < 0 || isnan(ChromTmp)) {
+        av_log(ctx, AV_LOG_ERROR,
+               "Invalid negative value for luma or chroma spatial strength, "
+               "or resulting value for chroma temporal strength is nan.\n");
+        return AVERROR(EINVAL);
+    }
+
+    PrecalcCoefs(hqdn3d->Coefs[0], LumSpac);
+    PrecalcCoefs(hqdn3d->Coefs[1], LumTmp);
+    PrecalcCoefs(hqdn3d->Coefs[2], ChromSpac);
+    PrecalcCoefs(hqdn3d->Coefs[3], ChromTmp);
+
+    return 0;
+}
+
+static void uninit(AVFilterContext *ctx)
+{
+    HQDN3DContext *hqdn3d = ctx->priv;
+
+    av_freep(&hqdn3d->Line);
+    av_freep(&hqdn3d->Frame[0]);
+    av_freep(&hqdn3d->Frame[1]);
+    av_freep(&hqdn3d->Frame[2]);
+}
+
+static int query_formats(AVFilterContext *ctx)
+{
+    static const enum PixelFormat pix_fmts[] = {
+        PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_YUV411P, PIX_FMT_NONE
+    };
+
+    avfilter_set_common_formats(ctx, avfilter_make_format_list(pix_fmts));
+
+    return 0;
+}
+
+static int config_input(AVFilterLink *inlink)
+{
+    HQDN3DContext *hqdn3d = inlink->dst->priv;
+
+    hqdn3d->hsub = av_pix_fmt_descriptors[inlink->format].log2_chroma_w;
+    hqdn3d->vsub = av_pix_fmt_descriptors[inlink->format].log2_chroma_h;
+
+    hqdn3d->Line = av_malloc(inlink->w * sizeof(*hqdn3d->Line));
+    if (!hqdn3d->Line)
+        return AVERROR(ENOMEM);
+
+    return 0;
+}
+
+static void null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir) { }
+
+static void end_frame(AVFilterLink *inlink)
+{
+    HQDN3DContext *hqdn3d = inlink->dst->priv;
+    AVFilterLink *outlink = inlink->dst->outputs[0];
+    AVFilterBufferRef *inpic  = inlink ->cur_buf;
+    AVFilterBufferRef *outpic = outlink->out_buf;
+    int cw = inpic->video->w >> hqdn3d->hsub;
+    int ch = inpic->video->h >> hqdn3d->vsub;
+
+    deNoise(inpic->data[0], outpic->data[0],
+            hqdn3d->Line, &hqdn3d->Frame[0], inpic->video->w, inpic->video->h,
+            inpic->linesize[0], outpic->linesize[0],
+            hqdn3d->Coefs[0],
+            hqdn3d->Coefs[0],
+            hqdn3d->Coefs[1]);
+    deNoise(inpic->data[1], outpic->data[1],
+            hqdn3d->Line, &hqdn3d->Frame[1], cw, ch,
+            inpic->linesize[1], outpic->linesize[1],
+            hqdn3d->Coefs[2],
+            hqdn3d->Coefs[2],
+            hqdn3d->Coefs[3]);
+    deNoise(inpic->data[2], outpic->data[2],
+            hqdn3d->Line, &hqdn3d->Frame[2], cw, ch,
+            inpic->linesize[2], outpic->linesize[2],
+            hqdn3d->Coefs[2],
+            hqdn3d->Coefs[2],
+            hqdn3d->Coefs[3]);
+
+    avfilter_draw_slice(outlink, 0, inpic->video->h, 1);
+    avfilter_end_frame(outlink);
+    avfilter_unref_buffer(inpic);
+    avfilter_unref_buffer(outpic);
+}
+
+AVFilter avfilter_vf_hqdn3d = {
+    .name          = "hqdn3d",
+    .description   = NULL_IF_CONFIG_SMALL("Apply a High Quality 3D Denoiser."),
+
+    .priv_size     = sizeof(HQDN3DContext),
+    .init          = init,
+    .uninit        = uninit,
+    .query_formats = query_formats,
+
+    .inputs    = (AVFilterPad[]) {{ .name             = "default",
+                                    .type             = AVMEDIA_TYPE_VIDEO,
+                                    .draw_slice       = null_draw_slice,
+                                    .config_props     = config_input,
+                                    .end_frame        = end_frame },
+                                  { .name = NULL}},
+
+    .outputs   = (AVFilterPad[]) {{ .name             = "default",
+                                    .type             = AVMEDIA_TYPE_VIDEO },
+                                  { .name = NULL}},
+};
diff --git a/libavfilter/vf_libopencv.c b/libavfilter/vf_libopencv.c
new file mode 100644
index 0000000..509b1d9
--- /dev/null
+++ b/libavfilter/vf_libopencv.c
@@ -0,0 +1,392 @@
+/*
+ * Copyright (c) 2010 Stefano Sabatini
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * libopencv wrapper functions
+ */
+
+/* #define DEBUG */
+
+#include <opencv/cv.h>
+#include <opencv/cxtypes.h>
+#include "libavutil/avstring.h"
+#include "libavutil/file.h"
+#include "avfilter.h"
+
+static void fill_iplimage_from_picref(IplImage *img, const AVFilterBufferRef *picref, enum PixelFormat pixfmt)
+{
+    IplImage *tmpimg;
+    int depth, channels_nb;
+
+    if      (pixfmt == PIX_FMT_GRAY8) { depth = IPL_DEPTH_8U;  channels_nb = 1; }
+    else if (pixfmt == PIX_FMT_BGRA)  { depth = IPL_DEPTH_8U;  channels_nb = 4; }
+    else if (pixfmt == PIX_FMT_BGR24) { depth = IPL_DEPTH_8U;  channels_nb = 3; }
+    else return;
+
+    tmpimg = cvCreateImageHeader((CvSize){picref->video->w, picref->video->h}, depth, channels_nb);
+    *img = *tmpimg;
+    img->imageData = img->imageDataOrigin = picref->data[0];
+    img->dataOrder = IPL_DATA_ORDER_PIXEL;
+    img->origin    = IPL_ORIGIN_TL;
+    img->widthStep = picref->linesize[0];
+}
+
+static void fill_picref_from_iplimage(AVFilterBufferRef *picref, const IplImage *img, enum PixelFormat pixfmt)
+{
+    picref->linesize[0] = img->widthStep;
+    picref->data[0]     = img->imageData;
+}
+
+static int query_formats(AVFilterContext *ctx)
+{
+    static const enum PixelFormat pix_fmts[] = {
+        PIX_FMT_BGR24, PIX_FMT_BGRA, PIX_FMT_GRAY8, PIX_FMT_NONE
+    };
+
+    avfilter_set_common_formats(ctx, avfilter_make_format_list(pix_fmts));
+    return 0;
+}
+
+static void null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir) { }
+
+typedef struct {
+    const char *name;
+    int (*init)(AVFilterContext *ctx, const char *args, void *opaque);
+    void (*uninit)(AVFilterContext *ctx);
+    void (*end_frame_filter)(AVFilterContext *ctx, IplImage *inimg, IplImage *outimg);
+    void *priv;
+} OCVContext;
+
+typedef struct {
+    int type;
+    int    param1, param2;
+    double param3, param4;
+} SmoothContext;
+
+static av_cold int smooth_init(AVFilterContext *ctx, const char *args, void *opaque)
+{
+    OCVContext *ocv = ctx->priv;
+    SmoothContext *smooth = ocv->priv;
+    char type_str[128] = "gaussian";
+
+    smooth->param1 = 3;
+    smooth->param2 = 0;
+    smooth->param3 = 0.0;
+    smooth->param4 = 0.0;
+
+    if (args)
+        sscanf(args, "%127[^:]:%d:%d:%lf:%lf", type_str, &smooth->param1, &smooth->param2, &smooth->param3, &smooth->param4);
+
+    if      (!strcmp(type_str, "blur"         )) smooth->type = CV_BLUR;
+    else if (!strcmp(type_str, "blur_no_scale")) smooth->type = CV_BLUR_NO_SCALE;
+    else if (!strcmp(type_str, "median"       )) smooth->type = CV_MEDIAN;
+    else if (!strcmp(type_str, "gaussian"     )) smooth->type = CV_GAUSSIAN;
+    else if (!strcmp(type_str, "bilateral"    )) smooth->type = CV_BILATERAL;
+    else {
+        av_log(ctx, AV_LOG_ERROR, "Smoothing type '%s' unknown\n.", type_str);
+        return AVERROR(EINVAL);
+    }
+
+    if (smooth->param1 < 0 || !(smooth->param1%2)) {
+        av_log(ctx, AV_LOG_ERROR,
+               "Invalid value '%d' for param1, it has to be a positive odd number\n",
+               smooth->param1);
+        return AVERROR(EINVAL);
+    }
+    if ((smooth->type == CV_BLUR || smooth->type == CV_BLUR_NO_SCALE || smooth->type == CV_GAUSSIAN) &&
+        (smooth->param2 < 0 || (smooth->param2 && !(smooth->param2%2)))) {
+        av_log(ctx, AV_LOG_ERROR,
+               "Invalid value '%d' for param2, it has to be zero or a positive odd number\n",
+               smooth->param2);
+        return AVERROR(EINVAL);
+    }
+
+    av_log(ctx, AV_LOG_INFO, "type:%s param1:%d param2:%d param3:%f param4:%f\n",
+           type_str, smooth->param1, smooth->param2, smooth->param3, smooth->param4);
+    return 0;
+}
+
+static void smooth_end_frame_filter(AVFilterContext *ctx, IplImage *inimg, IplImage *outimg)
+{
+    OCVContext *ocv = ctx->priv;
+    SmoothContext *smooth = ocv->priv;
+    cvSmooth(inimg, outimg, smooth->type, smooth->param1, smooth->param2, smooth->param3, smooth->param4);
+}
+
+static int read_shape_from_file(int *cols, int *rows, int **values, const char *filename,
+                                void *log_ctx)
+{
+    uint8_t *buf, *p, *pend;
+    size_t size;
+    int ret, i, j, w;
+
+    if ((ret = av_file_map(filename, &buf, &size, 0, log_ctx)) < 0)
+        return ret;
+
+    /* prescan file to get the number of lines and the maximum width */
+    w = 0;
+    for (i = 0; i < size; i++) {
+        if (buf[i] == '\n') {
+            if (*rows == INT_MAX) {
+                av_log(log_ctx, AV_LOG_ERROR, "Overflow on the number of rows in the file\n");
+                return AVERROR_INVALIDDATA;
+            }
+            ++(*rows);
+            *cols = FFMAX(*cols, w);
+            w = 0;
+        } else if (w == INT_MAX) {
+            av_log(log_ctx, AV_LOG_ERROR, "Overflow on the number of columns in the file\n");
+            return AVERROR_INVALIDDATA;
+        }
+        w++;
+    }
+    if (*rows > (FF_INTERNAL_MEM_TYPE_MAX_VALUE / (sizeof(int)) / *cols)) {
+        av_log(log_ctx, AV_LOG_ERROR, "File with size %dx%d is too big\n",
+               *rows, *cols);
+        return AVERROR_INVALIDDATA;
+    }
+    if (!(*values = av_mallocz(sizeof(int) * *rows * *cols)))
+        return AVERROR(ENOMEM);
+
+    /* fill *values */
+    p    = buf;
+    pend = buf + size-1;
+    for (i = 0; i < *rows; i++) {
+        for (j = 0;; j++) {
+            if (p > pend || *p == '\n') {
+                p++;
+                break;
+            } else
+                (*values)[*cols*i + j] = !!isgraph(*(p++));
+        }
+    }
+    av_file_unmap(buf, size);
+
+#ifdef DEBUG
+    {
+        char *line;
+        if (!(line = av_malloc(*cols + 1)))
+            return AVERROR(ENOMEM);
+        for (i = 0; i < *rows; i++) {
+            for (j = 0; j < *cols; j++)
+                line[j] = (*values)[i * *cols + j] ? '@' : ' ';
+            line[j] = 0;
+            av_log(log_ctx, AV_LOG_DEBUG, "%3d: %s\n", i, line);
+        }
+        av_free(line);
+    }
+#endif
+
+    return 0;
+}
+
+static int parse_iplconvkernel(IplConvKernel **kernel, char *buf, void *log_ctx)
+{
+    char shape_filename[128] = "", shape_str[32] = "rect";
+    int cols = 0, rows = 0, anchor_x = 0, anchor_y = 0, shape = CV_SHAPE_RECT;
+    int *values = NULL, ret;
+
+    sscanf(buf, "%dx%d+%dx%d/%32[^=]=%127s", &cols, &rows, &anchor_x, &anchor_y, shape_str, shape_filename);
+
+    if      (!strcmp(shape_str, "rect"   )) shape = CV_SHAPE_RECT;
+    else if (!strcmp(shape_str, "cross"  )) shape = CV_SHAPE_CROSS;
+    else if (!strcmp(shape_str, "ellipse")) shape = CV_SHAPE_ELLIPSE;
+    else if (!strcmp(shape_str, "custom" )) {
+        shape = CV_SHAPE_CUSTOM;
+        if ((ret = read_shape_from_file(&cols, &rows, &values, shape_filename, log_ctx)) < 0)
+            return ret;
+    } else {
+        av_log(log_ctx, AV_LOG_ERROR,
+               "Shape unspecified or type '%s' unknown\n.", shape_str);
+        return AVERROR(EINVAL);
+    }
+
+    if (rows <= 0 || cols <= 0) {
+        av_log(log_ctx, AV_LOG_ERROR,
+               "Invalid non-positive values for shape size %dx%d\n", cols, rows);
+        return AVERROR(EINVAL);
+    }
+
+    if (anchor_x < 0 || anchor_y < 0 || anchor_x >= cols || anchor_y >= rows) {
+        av_log(log_ctx, AV_LOG_ERROR,
+               "Shape anchor %dx%d is not inside the rectangle with size %dx%d.\n",
+               anchor_x, anchor_y, cols, rows);
+        return AVERROR(EINVAL);
+    }
+
+    *kernel = cvCreateStructuringElementEx(cols, rows, anchor_x, anchor_y, shape, values);
+    av_freep(&values);
+    if (!*kernel)
+        return AVERROR(ENOMEM);
+
+    av_log(log_ctx, AV_LOG_INFO, "Structuring element: w:%d h:%d x:%d y:%d shape:%s\n",
+           rows, cols, anchor_x, anchor_y, shape_str);
+    return 0;
+}
+
+typedef struct {
+    int nb_iterations;
+    IplConvKernel *kernel;
+} DilateContext;
+
+static av_cold int dilate_init(AVFilterContext *ctx, const char *args, void *opaque)
+{
+    OCVContext *ocv = ctx->priv;
+    DilateContext *dilate = ocv->priv;
+    char default_kernel_str[] = "3x3+0x0/rect";
+    char *kernel_str;
+    const char *buf = args;
+    int ret;
+
+    dilate->nb_iterations = 1;
+
+    if (args)
+        kernel_str = av_get_token(&buf, ":");
+    if ((ret = parse_iplconvkernel(&dilate->kernel,
+                                   *kernel_str ? kernel_str : default_kernel_str,
+                                   ctx)) < 0)
+        return ret;
+    av_free(kernel_str);
+
+    sscanf(buf, ":%d", &dilate->nb_iterations);
+    av_log(ctx, AV_LOG_INFO, "iterations_nb:%d\n", dilate->nb_iterations);
+    if (dilate->nb_iterations <= 0) {
+        av_log(ctx, AV_LOG_ERROR, "Invalid non-positive value '%d' for nb_iterations\n",
+               dilate->nb_iterations);
+        return AVERROR(EINVAL);
+    }
+    return 0;
+}
+
+static av_cold void dilate_uninit(AVFilterContext *ctx)
+{
+    OCVContext *ocv = ctx->priv;
+    DilateContext *dilate = ocv->priv;
+
+    cvReleaseStructuringElement(&dilate->kernel);
+}
+
+static void dilate_end_frame_filter(AVFilterContext *ctx, IplImage *inimg, IplImage *outimg)
+{
+    OCVContext *ocv = ctx->priv;
+    DilateContext *dilate = ocv->priv;
+    cvDilate(inimg, outimg, dilate->kernel, dilate->nb_iterations);
+}
+
+static void erode_end_frame_filter(AVFilterContext *ctx, IplImage *inimg, IplImage *outimg)
+{
+    OCVContext *ocv = ctx->priv;
+    DilateContext *dilate = ocv->priv;
+    cvErode(inimg, outimg, dilate->kernel, dilate->nb_iterations);
+}
+
+typedef struct {
+    const char *name;
+    size_t priv_size;
+    int  (*init)(AVFilterContext *ctx, const char *args, void *opaque);
+    void (*uninit)(AVFilterContext *ctx);
+    void (*end_frame_filter)(AVFilterContext *ctx, IplImage *inimg, IplImage *outimg);
+} OCVFilterEntry;
+
+static OCVFilterEntry ocv_filter_entries[] = {
+    { "dilate", sizeof(DilateContext), dilate_init, dilate_uninit, dilate_end_frame_filter },
+    { "erode",  sizeof(DilateContext), dilate_init, dilate_uninit, erode_end_frame_filter  },
+    { "smooth", sizeof(SmoothContext), smooth_init, NULL, smooth_end_frame_filter },
+};
+
+static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
+{
+    OCVContext *ocv = ctx->priv;
+    char name[128], priv_args[1024];
+    int i;
+    char c;
+
+    sscanf(args, "%127[^=:]%c%1023s", name, &c, priv_args);
+
+    for (i = 0; i < FF_ARRAY_ELEMS(ocv_filter_entries); i++) {
+        OCVFilterEntry *entry = &ocv_filter_entries[i];
+        if (!strcmp(name, entry->name)) {
+            ocv->name             = entry->name;
+            ocv->init             = entry->init;
+            ocv->uninit           = entry->uninit;
+            ocv->end_frame_filter = entry->end_frame_filter;
+
+            if (!(ocv->priv = av_mallocz(entry->priv_size)))
+                return AVERROR(ENOMEM);
+            return ocv->init(ctx, priv_args, opaque);
+        }
+    }
+
+    av_log(ctx, AV_LOG_ERROR, "No libopencv filter named '%s'\n", name);
+    return AVERROR(EINVAL);
+}
+
+static av_cold void uninit(AVFilterContext *ctx)
+{
+    OCVContext *ocv = ctx->priv;
+
+    if (ocv->uninit)
+        ocv->uninit(ctx);
+    av_free(ocv->priv);
+    memset(ocv, 0, sizeof(*ocv));
+}
+
+static void end_frame(AVFilterLink *inlink)
+{
+    AVFilterContext *ctx = inlink->dst;
+    OCVContext *ocv = ctx->priv;
+    AVFilterLink *outlink= inlink->dst->outputs[0];
+    AVFilterBufferRef *inpicref  = inlink ->cur_buf;
+    AVFilterBufferRef *outpicref = outlink->out_buf;
+    IplImage inimg, outimg;
+
+    fill_iplimage_from_picref(&inimg , inpicref , inlink->format);
+    fill_iplimage_from_picref(&outimg, outpicref, inlink->format);
+    ocv->end_frame_filter(ctx, &inimg, &outimg);
+    fill_picref_from_iplimage(outpicref, &outimg, inlink->format);
+
+    avfilter_unref_buffer(inpicref);
+    avfilter_draw_slice(outlink, 0, outlink->h, 1);
+    avfilter_end_frame(outlink);
+    avfilter_unref_buffer(outpicref);
+}
+
+AVFilter avfilter_vf_ocv = {
+    .name        = "ocv",
+    .description = NULL_IF_CONFIG_SMALL("Apply transform using libopencv."),
+
+    .priv_size = sizeof(OCVContext),
+
+    .query_formats = query_formats,
+    .init = init,
+    .uninit = uninit,
+
+    .inputs    = (AVFilterPad[]) {{ .name             = "default",
+                                    .type             = AVMEDIA_TYPE_VIDEO,
+                                    .draw_slice       = null_draw_slice,
+                                    .end_frame        = end_frame,
+                                    .min_perms        = AV_PERM_READ },
+                                  { .name = NULL}},
+
+    .outputs   = (AVFilterPad[]) {{ .name             = "default",
+                                    .type             = AVMEDIA_TYPE_VIDEO, },
+                                  { .name = NULL}},
+};
diff --git a/libavfilter/vf_null.c b/libavfilter/vf_null.c
index 989cd86..8414c5f 100644
--- a/libavfilter/vf_null.c
+++ b/libavfilter/vf_null.c
@@ -1,18 +1,18 @@
 /*
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavfilter/vf_overlay.c b/libavfilter/vf_overlay.c
new file mode 100644
index 0000000..c8bdf51
--- /dev/null
+++ b/libavfilter/vf_overlay.c
@@ -0,0 +1,380 @@
+/*
+ * Copyright (c) 2010 Stefano Sabatini
+ * Copyright (c) 2010 Baptiste Coudurier
+ * Copyright (c) 2007 Bobby Bingham
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * overlay one video on top of another
+ */
+
+#include "avfilter.h"
+#include "libavutil/eval.h"
+#include "libavutil/avstring.h"
+#include "libavutil/pixdesc.h"
+#include "libavutil/imgutils.h"
+#include "internal.h"
+
+static const char *var_names[] = {
+    "E",
+    "PHI",
+    "PI",
+    "main_w",    "W", ///< width  of the main    video
+    "main_h",    "H", ///< height of the main    video
+    "overlay_w", "w", ///< width  of the overlay video
+    "overlay_h", "h", ///< height of the overlay video
+    NULL
+};
+
+enum var_name {
+    VAR_E,
+    VAR_PHI,
+    VAR_PI,
+    VAR_MAIN_W,    VAR_MW,
+    VAR_MAIN_H,    VAR_MH,
+    VAR_OVERLAY_W, VAR_OW,
+    VAR_OVERLAY_H, VAR_OH,
+    VAR_VARS_NB
+};
+
+#define MAIN    0
+#define OVERLAY 1
+
+typedef struct {
+    int x, y;                   ///< position of overlayed picture
+
+    AVFilterBufferRef *overpicref;
+
+    int max_plane_step[4];      ///< steps per pixel for each plane
+    int hsub, vsub;             ///< chroma subsampling values
+
+    char x_expr[256], y_expr[256];
+} OverlayContext;
+
+static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
+{
+    OverlayContext *over = ctx->priv;
+
+    av_strlcpy(over->x_expr, "0", sizeof(over->x_expr));
+    av_strlcpy(over->y_expr, "0", sizeof(over->y_expr));
+
+    if (args)
+        sscanf(args, "%255[^:]:%255[^:]", over->x_expr, over->y_expr);
+
+    return 0;
+}
+
+static av_cold void uninit(AVFilterContext *ctx)
+{
+    OverlayContext *over = ctx->priv;
+
+    if (over->overpicref)
+        avfilter_unref_buffer(over->overpicref);
+}
+
+static int query_formats(AVFilterContext *ctx)
+{
+    const enum PixelFormat inout_pix_fmts[] = { PIX_FMT_YUV420P,  PIX_FMT_NONE };
+    const enum PixelFormat blend_pix_fmts[] = { PIX_FMT_YUVA420P, PIX_FMT_NONE };
+    AVFilterFormats *inout_formats = avfilter_make_format_list(inout_pix_fmts);
+    AVFilterFormats *blend_formats = avfilter_make_format_list(blend_pix_fmts);
+
+    avfilter_formats_ref(inout_formats, &ctx->inputs [MAIN   ]->out_formats);
+    avfilter_formats_ref(blend_formats, &ctx->inputs [OVERLAY]->out_formats);
+    avfilter_formats_ref(inout_formats, &ctx->outputs[MAIN   ]->in_formats );
+
+    return 0;
+}
+
+static int config_input_main(AVFilterLink *inlink)
+{
+    OverlayContext *over = inlink->dst->priv;
+    const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[inlink->format];
+
+    av_image_fill_max_pixsteps(over->max_plane_step, NULL, pix_desc);
+    over->hsub = pix_desc->log2_chroma_w;
+    over->vsub = pix_desc->log2_chroma_h;
+
+    return 0;
+}
+
+static int config_input_overlay(AVFilterLink *inlink)
+{
+    AVFilterContext *ctx  = inlink->dst;
+    OverlayContext  *over = inlink->dst->priv;
+    char *expr;
+    double var_values[VAR_VARS_NB], res;
+    int ret;
+
+    /* Finish the configuration by evaluating the expressions
+       now when both inputs are configured. */
+    var_values[VAR_E  ] = M_E;
+    var_values[VAR_PHI] = M_PHI;
+    var_values[VAR_PI ] = M_PI;
+
+    var_values[VAR_MAIN_W   ] = var_values[VAR_MW] = ctx->inputs[MAIN   ]->w;
+    var_values[VAR_MAIN_H   ] = var_values[VAR_MH] = ctx->inputs[MAIN   ]->h;
+    var_values[VAR_OVERLAY_W] = var_values[VAR_OW] = ctx->inputs[OVERLAY]->w;
+    var_values[VAR_OVERLAY_H] = var_values[VAR_OH] = ctx->inputs[OVERLAY]->h;
+
+    if ((ret = av_expr_parse_and_eval(&res, (expr = over->x_expr), var_names, var_values,
+                                      NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
+        goto fail;
+    over->x = res;
+    if ((ret = av_expr_parse_and_eval(&res, (expr = over->y_expr), var_names, var_values,
+                                      NULL, NULL, NULL, NULL, NULL, 0, ctx)))
+        goto fail;
+    over->y = res;
+    /* x may depend on y */
+    if ((ret = av_expr_parse_and_eval(&res, (expr = over->x_expr), var_names, var_values,
+                                      NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
+        goto fail;
+    over->x = res;
+
+    av_log(ctx, AV_LOG_INFO,
+           "main w:%d h:%d fmt:%s overlay x:%d y:%d w:%d h:%d fmt:%s\n",
+           ctx->inputs[MAIN]->w, ctx->inputs[MAIN]->h,
+           av_pix_fmt_descriptors[ctx->inputs[MAIN]->format].name,
+           over->x, over->y,
+           ctx->inputs[OVERLAY]->w, ctx->inputs[OVERLAY]->h,
+           av_pix_fmt_descriptors[ctx->inputs[OVERLAY]->format].name);
+
+    if (over->x < 0 || over->y < 0 ||
+        over->x + var_values[VAR_OVERLAY_W] > var_values[VAR_MAIN_W] ||
+        over->y + var_values[VAR_OVERLAY_H] > var_values[VAR_MAIN_H]) {
+        av_log(ctx, AV_LOG_ERROR,
+               "Overlay area (%d,%d)<->(%d,%d) not within the main area (0,0)<->(%d,%d) or zero-sized\n",
+               over->x, over->y,
+               (int)(over->x + var_values[VAR_OVERLAY_W]),
+               (int)(over->y + var_values[VAR_OVERLAY_H]),
+               (int)var_values[VAR_MAIN_W], (int)var_values[VAR_MAIN_H]);
+        return AVERROR(EINVAL);
+    }
+    return 0;
+
+fail:
+    av_log(NULL, AV_LOG_ERROR,
+           "Error when evaluating the expression '%s'\n", expr);
+    return ret;
+}
+
+static int config_output(AVFilterLink *outlink)
+{
+    AVFilterContext *ctx = outlink->src;
+    int exact;
+    // common timebase computation:
+    AVRational tb1 = ctx->inputs[MAIN   ]->time_base;
+    AVRational tb2 = ctx->inputs[OVERLAY]->time_base;
+    AVRational *tb = &ctx->outputs[0]->time_base;
+    exact = av_reduce(&tb->num, &tb->den,
+                      av_gcd((int64_t)tb1.num * tb2.den,
+                             (int64_t)tb2.num * tb1.den),
+                      (int64_t)tb1.den * tb2.den, INT_MAX);
+    av_log(ctx, AV_LOG_INFO,
+           "main_tb:%d/%d overlay_tb:%d/%d -> tb:%d/%d exact:%d\n",
+           tb1.num, tb1.den, tb2.num, tb2.den, tb->num, tb->den, exact);
+    if (!exact)
+        av_log(ctx, AV_LOG_WARNING,
+               "Timestamp conversion inexact, timestamp information loss may occurr\n");
+
+    outlink->w = ctx->inputs[MAIN]->w;
+    outlink->h = ctx->inputs[MAIN]->h;
+
+    return 0;
+}
+
+static AVFilterBufferRef *get_video_buffer(AVFilterLink *link, int perms, int w, int h)
+{
+    return avfilter_get_video_buffer(link->dst->outputs[0], perms, w, h);
+}
+
+static void start_frame(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
+{
+    AVFilterBufferRef *outpicref = avfilter_ref_buffer(inpicref, ~0);
+    AVFilterContext *ctx = inlink->dst;
+    OverlayContext *over = ctx->priv;
+
+    inlink->dst->outputs[0]->out_buf = outpicref;
+    outpicref->pts = av_rescale_q(outpicref->pts, ctx->inputs[MAIN]->time_base,
+                                  ctx->outputs[0]->time_base);
+
+    if (!over->overpicref || over->overpicref->pts < outpicref->pts) {
+        AVFilterBufferRef *old = over->overpicref;
+        over->overpicref = NULL;
+        avfilter_request_frame(ctx->inputs[OVERLAY]);
+        if (over->overpicref) {
+            if (old)
+                avfilter_unref_buffer(old);
+        } else
+            over->overpicref = old;
+    }
+
+    avfilter_start_frame(inlink->dst->outputs[0], outpicref);
+}
+
+static void start_frame_overlay(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
+{
+    AVFilterContext *ctx = inlink->dst;
+    OverlayContext *over = ctx->priv;
+
+    over->overpicref = inpicref;
+    over->overpicref->pts = av_rescale_q(inpicref->pts, ctx->inputs[OVERLAY]->time_base,
+                                         ctx->outputs[0]->time_base);
+}
+
+static void blend_slice(AVFilterContext *ctx,
+                        AVFilterBufferRef *dst, AVFilterBufferRef *src,
+                        int x, int y, int w, int h,
+                        int slice_y, int slice_w, int slice_h)
+{
+    OverlayContext *over = ctx->priv;
+    int i, j, k;
+    int width, height;
+    int overlay_end_y = y+h;
+    int slice_end_y = slice_y+slice_h;
+    int end_y, start_y;
+
+    width = FFMIN(slice_w - x, w);
+    end_y = FFMIN(slice_end_y, overlay_end_y);
+    start_y = FFMAX(y, slice_y);
+    height = end_y - start_y;
+
+    if (dst->format == PIX_FMT_BGR24 || dst->format == PIX_FMT_RGB24) {
+        uint8_t *dp = dst->data[0] + x * 3 + start_y * dst->linesize[0];
+        uint8_t *sp = src->data[0];
+        int b = dst->format == PIX_FMT_BGR24 ? 2 : 0;
+        int r = dst->format == PIX_FMT_BGR24 ? 0 : 2;
+        if (slice_y > y)
+            sp += (slice_y - y) * src->linesize[0];
+        for (i = 0; i < height; i++) {
+            uint8_t *d = dp, *s = sp;
+            for (j = 0; j < width; j++) {
+                d[r] = (d[r] * (0xff - s[3]) + s[0] * s[3] + 128) >> 8;
+                d[1] = (d[1] * (0xff - s[3]) + s[1] * s[3] + 128) >> 8;
+                d[b] = (d[b] * (0xff - s[3]) + s[2] * s[3] + 128) >> 8;
+                d += 3;
+                s += 4;
+            }
+            dp += dst->linesize[0];
+            sp += src->linesize[0];
+        }
+    } else {
+        for (i = 0; i < 3; i++) {
+            int hsub = i ? over->hsub : 0;
+            int vsub = i ? over->vsub : 0;
+            uint8_t *dp = dst->data[i] + (x >> hsub) +
+                (start_y >> vsub) * dst->linesize[i];
+            uint8_t *sp = src->data[i];
+            uint8_t *ap = src->data[3];
+            int wp = FFALIGN(width, 1<<hsub) >> hsub;
+            int hp = FFALIGN(height, 1<<vsub) >> vsub;
+            if (slice_y > y) {
+                sp += ((slice_y - y) >> vsub) * src->linesize[i];
+                ap += (slice_y - y) * src->linesize[3];
+            }
+            for (j = 0; j < hp; j++) {
+                uint8_t *d = dp, *s = sp, *a = ap;
+                for (k = 0; k < wp; k++) {
+                    // average alpha for color components, improve quality
+                    int alpha_v, alpha_h, alpha;
+                    if (hsub && vsub && j+1 < hp && k+1 < wp) {
+                        alpha = (a[0] + a[src->linesize[3]] +
+                                 a[1] + a[src->linesize[3]+1]) >> 2;
+                    } else if (hsub || vsub) {
+                        alpha_h = hsub && k+1 < wp ?
+                            (a[0] + a[1]) >> 1 : a[0];
+                        alpha_v = vsub && j+1 < hp ?
+                            (a[0] + a[src->linesize[3]]) >> 1 : a[0];
+                        alpha = (alpha_v + alpha_h) >> 1;
+                    } else
+                        alpha = a[0];
+                    *d = (*d * (0xff - alpha) + *s++ * alpha + 128) >> 8;
+                    d++;
+                    a += 1 << hsub;
+                }
+                dp += dst->linesize[i];
+                sp += src->linesize[i];
+                ap += (1 << vsub) * src->linesize[3];
+            }
+        }
+    }
+}
+
+static void draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir)
+{
+    AVFilterContext *ctx = inlink->dst;
+    AVFilterLink *outlink = ctx->outputs[0];
+    AVFilterBufferRef *outpicref = outlink->out_buf;
+    OverlayContext *over = ctx->priv;
+
+    if (over->overpicref &&
+        !(over->x >= outpicref->video->w || over->y >= outpicref->video->h ||
+          y+h < over->y || y >= over->y + over->overpicref->video->h)) {
+        blend_slice(ctx, outpicref, over->overpicref, over->x, over->y,
+                    over->overpicref->video->w, over->overpicref->video->h,
+                    y, outpicref->video->w, h);
+    }
+    avfilter_draw_slice(outlink, y, h, slice_dir);
+}
+
+static void end_frame(AVFilterLink *inlink)
+{
+    avfilter_end_frame(inlink->dst->outputs[0]);
+    avfilter_unref_buffer(inlink->cur_buf);
+}
+
+static void null_draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir) { }
+
+static void null_end_frame(AVFilterLink *inlink) { }
+
+AVFilter avfilter_vf_overlay = {
+    .name      = "overlay",
+    .description = NULL_IF_CONFIG_SMALL("Overlay a video source on top of the input."),
+
+    .init      = init,
+    .uninit    = uninit,
+
+    .priv_size = sizeof(OverlayContext),
+
+    .query_formats = query_formats,
+
+    .inputs    = (AVFilterPad[]) {{ .name            = "main",
+                                    .type            = AVMEDIA_TYPE_VIDEO,
+                                    .start_frame     = start_frame,
+                                    .get_video_buffer= get_video_buffer,
+                                    .config_props    = config_input_main,
+                                    .draw_slice      = draw_slice,
+                                    .end_frame       = end_frame,
+                                    .min_perms       = AV_PERM_READ,
+                                    .rej_perms       = AV_PERM_REUSE2|AV_PERM_PRESERVE, },
+                                  { .name            = "overlay",
+                                    .type            = AVMEDIA_TYPE_VIDEO,
+                                    .start_frame     = start_frame_overlay,
+                                    .config_props    = config_input_overlay,
+                                    .draw_slice      = null_draw_slice,
+                                    .end_frame       = null_end_frame,
+                                    .min_perms       = AV_PERM_READ,
+                                    .rej_perms       = AV_PERM_REUSE2, },
+                                  { .name = NULL}},
+    .outputs   = (AVFilterPad[]) {{ .name            = "default",
+                                    .type            = AVMEDIA_TYPE_VIDEO,
+                                    .config_props    = config_output, },
+                                  { .name = NULL}},
+};
diff --git a/libavfilter/vf_pad.c b/libavfilter/vf_pad.c
new file mode 100644
index 0000000..4f8e645
--- /dev/null
+++ b/libavfilter/vf_pad.c
@@ -0,0 +1,330 @@
+/*
+ * Copyright (c) 2008 vmrsss
+ * Copyright (c) 2009 Stefano Sabatini
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * video padding filter and color source
+ */
+
+#include "avfilter.h"
+#include "libavutil/pixdesc.h"
+#include "libavutil/colorspace.h"
+#include "libavutil/avassert.h"
+#include "libavutil/imgutils.h"
+#include "libavutil/parseutils.h"
+#include "drawutils.h"
+
+static int query_formats(AVFilterContext *ctx)
+{
+    static const enum PixelFormat pix_fmts[] = {
+        PIX_FMT_ARGB,         PIX_FMT_RGBA,
+        PIX_FMT_ABGR,         PIX_FMT_BGRA,
+        PIX_FMT_RGB24,        PIX_FMT_BGR24,
+
+        PIX_FMT_YUV444P,      PIX_FMT_YUV422P,
+        PIX_FMT_YUV420P,      PIX_FMT_YUV411P,
+        PIX_FMT_YUV410P,      PIX_FMT_YUV440P,
+        PIX_FMT_YUVJ444P,     PIX_FMT_YUVJ422P,
+        PIX_FMT_YUVJ420P,     PIX_FMT_YUVJ440P,
+        PIX_FMT_YUVA420P,
+
+        PIX_FMT_NONE
+    };
+
+    avfilter_set_common_formats(ctx, avfilter_make_format_list(pix_fmts));
+    return 0;
+}
+
+typedef struct {
+    int w, h;               ///< output dimensions, a value of 0 will result in the input size
+    int x, y;               ///< offsets of the input area with respect to the padded area
+    int in_w, in_h;         ///< width and height for the padded input video, which has to be aligned to the chroma values in order to avoid chroma issues
+
+    uint8_t color[4];       ///< color expressed either in YUVA or RGBA colorspace for the padding area
+    uint8_t *line[4];
+    int      line_step[4];
+    int hsub, vsub;         ///< chroma subsampling values
+    int needs_copy;
+} PadContext;
+
+static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
+{
+    PadContext *pad = ctx->priv;
+    char color_string[128] = "black";
+
+    if (args)
+        sscanf(args, "%d:%d:%d:%d:%s", &pad->w, &pad->h, &pad->x, &pad->y, color_string);
+
+    if (av_parse_color(pad->color, color_string, -1, ctx) < 0)
+        return AVERROR(EINVAL);
+
+    /* sanity check params */
+    if (pad->w < 0 || pad->h < 0) {
+        av_log(ctx, AV_LOG_ERROR, "Negative size values are not acceptable.\n");
+        return AVERROR(EINVAL);
+    }
+
+    return 0;
+}
+
+static av_cold void uninit(AVFilterContext *ctx)
+{
+    PadContext *pad = ctx->priv;
+    int i;
+
+    for (i = 0; i < 4; i++) {
+        av_freep(&pad->line[i]);
+        pad->line_step[i] = 0;
+    }
+}
+
+static int config_input(AVFilterLink *inlink)
+{
+    AVFilterContext *ctx = inlink->dst;
+    PadContext *pad = ctx->priv;
+    const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[inlink->format];
+    uint8_t rgba_color[4];
+    int is_packed_rgba;
+
+    pad->hsub = pix_desc->log2_chroma_w;
+    pad->vsub = pix_desc->log2_chroma_h;
+
+    if (!pad->w)
+        pad->w = inlink->w;
+    if (!pad->h)
+        pad->h = inlink->h;
+
+    pad->w &= ~((1 << pad->hsub) - 1);
+    pad->h &= ~((1 << pad->vsub) - 1);
+    pad->x &= ~((1 << pad->hsub) - 1);
+    pad->y &= ~((1 << pad->vsub) - 1);
+
+    pad->in_w = inlink->w & ~((1 << pad->hsub) - 1);
+    pad->in_h = inlink->h & ~((1 << pad->vsub) - 1);
+
+    memcpy(rgba_color, pad->color, sizeof(rgba_color));
+    ff_fill_line_with_color(pad->line, pad->line_step, pad->w, pad->color,
+                            inlink->format, rgba_color, &is_packed_rgba, NULL);
+
+    av_log(ctx, AV_LOG_INFO, "w:%d h:%d -> w:%d h:%d x:%d y:%d color:0x%02X%02X%02X%02X[%s]\n",
+           inlink->w, inlink->h, pad->w, pad->h, pad->x, pad->y,
+           pad->color[0], pad->color[1], pad->color[2], pad->color[3],
+           is_packed_rgba ? "rgba" : "yuva");
+
+    if (pad->x <  0 || pad->y <  0                      ||
+        pad->w <= 0 || pad->h <= 0                      ||
+        (unsigned)pad->x + (unsigned)inlink->w > pad->w ||
+        (unsigned)pad->y + (unsigned)inlink->h > pad->h) {
+        av_log(ctx, AV_LOG_ERROR,
+               "Input area %d:%d:%d:%d not within the padded area 0:0:%d:%d or zero-sized\n",
+               pad->x, pad->y, pad->x + inlink->w, pad->y + inlink->h, pad->w, pad->h);
+        return AVERROR(EINVAL);
+    }
+
+    return 0;
+}
+
+static int config_output(AVFilterLink *outlink)
+{
+    PadContext *pad = outlink->src->priv;
+
+    outlink->w = pad->w;
+    outlink->h = pad->h;
+    return 0;
+}
+
+static AVFilterBufferRef *get_video_buffer(AVFilterLink *inlink, int perms, int w, int h)
+{
+    PadContext *pad = inlink->dst->priv;
+
+    AVFilterBufferRef *picref = avfilter_get_video_buffer(inlink->dst->outputs[0], perms,
+                                                       w + (pad->w - pad->in_w),
+                                                       h + (pad->h - pad->in_h));
+    int plane;
+
+    picref->video->w = w;
+    picref->video->h = h;
+
+    for (plane = 0; plane < 4 && picref->data[plane]; plane++) {
+        int hsub = (plane == 1 || plane == 2) ? pad->hsub : 0;
+        int vsub = (plane == 1 || plane == 2) ? pad->vsub : 0;
+
+        picref->data[plane] += (pad->x >> hsub) * pad->line_step[plane] +
+            (pad->y >> vsub) * picref->linesize[plane];
+    }
+
+    return picref;
+}
+
+static int does_clip(PadContext *pad, AVFilterBufferRef *outpicref, int plane, int hsub, int vsub, int x, int y)
+{
+    int64_t x_in_buf, y_in_buf;
+
+    x_in_buf =  outpicref->data[plane] - outpicref->buf->data[plane]
+             +  (x >> hsub) * pad      ->line_step[plane]
+             +  (y >> vsub) * outpicref->linesize [plane];
+
+    if(x_in_buf < 0 || x_in_buf % pad->line_step[plane])
+        return 1;
+    x_in_buf /= pad->line_step[plane];
+
+    av_assert0(outpicref->buf->linesize[plane]>0); //while reference can use negative linesize the main buffer should not
+
+    y_in_buf = x_in_buf / outpicref->buf->linesize[plane];
+    x_in_buf %= outpicref->buf->linesize[plane];
+
+    if(   y_in_buf<<vsub >= outpicref->buf->h
+       || x_in_buf<<hsub >= outpicref->buf->w)
+        return 1;
+    return 0;
+}
+
+static void start_frame(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
+{
+    PadContext *pad = inlink->dst->priv;
+    AVFilterBufferRef *outpicref = avfilter_ref_buffer(inpicref, ~0);
+    int plane;
+
+    for (plane = 0; plane < 4 && outpicref->data[plane]; plane++) {
+        int hsub = (plane == 1 || plane == 2) ? pad->hsub : 0;
+        int vsub = (plane == 1 || plane == 2) ? pad->vsub : 0;
+
+        av_assert0(outpicref->buf->w>0 && outpicref->buf->h>0);
+
+        if(outpicref->format != outpicref->buf->format) //unsupported currently
+            break;
+
+        outpicref->data[plane] -=   (pad->x  >> hsub) * pad      ->line_step[plane]
+                                  + (pad->y  >> vsub) * outpicref->linesize [plane];
+
+        if(   does_clip(pad, outpicref, plane, hsub, vsub, 0, 0)
+           || does_clip(pad, outpicref, plane, hsub, vsub, 0, pad->h-1)
+           || does_clip(pad, outpicref, plane, hsub, vsub, pad->w-1, 0)
+           || does_clip(pad, outpicref, plane, hsub, vsub, pad->w-1, pad->h-1)
+          )
+            break;
+    }
+    pad->needs_copy= plane < 4 && outpicref->data[plane];
+    if(pad->needs_copy){
+        av_log(inlink->dst, AV_LOG_DEBUG, "Direct padding impossible allocating new frame\n");
+        avfilter_unref_buffer(outpicref);
+        outpicref = avfilter_get_video_buffer(inlink->dst->outputs[0], AV_PERM_WRITE | AV_PERM_NEG_LINESIZES,
+                                                       FFMAX(inlink->w, pad->w),
+                                                       FFMAX(inlink->h, pad->h));
+        avfilter_copy_buffer_ref_props(outpicref, inpicref);
+    }
+
+    inlink->dst->outputs[0]->out_buf = outpicref;
+
+    outpicref->video->w = pad->w;
+    outpicref->video->h = pad->h;
+
+    avfilter_start_frame(inlink->dst->outputs[0], outpicref);
+}
+
+static void end_frame(AVFilterLink *link)
+{
+    avfilter_end_frame(link->dst->outputs[0]);
+    avfilter_unref_buffer(link->cur_buf);
+}
+
+static void draw_send_bar_slice(AVFilterLink *link, int y, int h, int slice_dir, int before_slice)
+{
+    PadContext *pad = link->dst->priv;
+    int bar_y, bar_h = 0;
+
+    if        (slice_dir * before_slice ==  1 && y == pad->y) {
+        /* top bar */
+        bar_y = 0;
+        bar_h = pad->y;
+    } else if (slice_dir * before_slice == -1 && (y + h) == (pad->y + pad->in_h)) {
+        /* bottom bar */
+        bar_y = pad->y + pad->in_h;
+        bar_h = pad->h - pad->in_h - pad->y;
+    }
+
+    if (bar_h) {
+        ff_draw_rectangle(link->dst->outputs[0]->out_buf->data,
+                          link->dst->outputs[0]->out_buf->linesize,
+                          pad->line, pad->line_step, pad->hsub, pad->vsub,
+                          0, bar_y, pad->w, bar_h);
+        avfilter_draw_slice(link->dst->outputs[0], bar_y, bar_h, slice_dir);
+    }
+}
+
+static void draw_slice(AVFilterLink *link, int y, int h, int slice_dir)
+{
+    PadContext *pad = link->dst->priv;
+    AVFilterBufferRef *outpic = link->dst->outputs[0]->out_buf;
+    AVFilterBufferRef *inpic = link->cur_buf;
+
+    y += pad->y;
+
+    y &= ~((1 << pad->vsub) - 1);
+    h &= ~((1 << pad->vsub) - 1);
+
+    if (!h)
+        return;
+    draw_send_bar_slice(link, y, h, slice_dir, 1);
+
+    /* left border */
+    ff_draw_rectangle(outpic->data, outpic->linesize, pad->line, pad->line_step,
+                      pad->hsub, pad->vsub, 0, y, pad->x, h);
+
+    if(pad->needs_copy){
+        ff_copy_rectangle(outpic->data, outpic->linesize,
+                          inpic->data, inpic->linesize, pad->line_step,
+                          pad->hsub, pad->vsub,
+                          pad->x, y, y-pad->y, inpic->video->w, h);
+    }
+
+    /* right border */
+    ff_draw_rectangle(outpic->data, outpic->linesize,
+                      pad->line, pad->line_step, pad->hsub, pad->vsub,
+                      pad->x + pad->in_w, y, pad->w - pad->x - pad->in_w, h);
+    avfilter_draw_slice(link->dst->outputs[0], y, h, slice_dir);
+
+    draw_send_bar_slice(link, y, h, slice_dir, -1);
+}
+
+AVFilter avfilter_vf_pad = {
+    .name          = "pad",
+    .description   = NULL_IF_CONFIG_SMALL("Pad input image to width:height[:x:y[:color]] (default x and y: 0, default color: black)."),
+
+    .priv_size     = sizeof(PadContext),
+    .init          = init,
+    .uninit        = uninit,
+    .query_formats = query_formats,
+
+    .inputs    = (AVFilterPad[]) {{ .name             = "default",
+                                    .type             = AVMEDIA_TYPE_VIDEO,
+                                    .config_props     = config_input,
+                                    .get_video_buffer = get_video_buffer,
+                                    .start_frame      = start_frame,
+                                    .draw_slice       = draw_slice,
+                                    .end_frame        = end_frame, },
+                                  { .name = NULL}},
+
+    .outputs   = (AVFilterPad[]) {{ .name             = "default",
+                                    .type             = AVMEDIA_TYPE_VIDEO,
+                                    .config_props     = config_output, },
+                                  { .name = NULL}},
+};
diff --git a/libavfilter/vf_pixdesctest.c b/libavfilter/vf_pixdesctest.c
new file mode 100644
index 0000000..344f664
--- /dev/null
+++ b/libavfilter/vf_pixdesctest.c
@@ -0,0 +1,129 @@
+/*
+ * Copyright (c) 2009 Stefano Sabatini
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * pixdesc test filter
+ */
+
+#include "libavutil/pixdesc.h"
+#include "avfilter.h"
+
+typedef struct {
+    const AVPixFmtDescriptor *pix_desc;
+    uint16_t *line;
+} PixdescTestContext;
+
+static av_cold void uninit(AVFilterContext *ctx)
+{
+    PixdescTestContext *priv = ctx->priv;
+    av_freep(&priv->line);
+}
+
+static int config_props(AVFilterLink *inlink)
+{
+    PixdescTestContext *priv = inlink->dst->priv;
+
+    priv->pix_desc = &av_pix_fmt_descriptors[inlink->format];
+
+    if (!(priv->line = av_malloc(sizeof(*priv->line) * inlink->w)))
+        return AVERROR(ENOMEM);
+
+    return 0;
+}
+
+static void start_frame(AVFilterLink *inlink, AVFilterBufferRef *picref)
+{
+    PixdescTestContext *priv = inlink->dst->priv;
+    AVFilterLink *outlink    = inlink->dst->outputs[0];
+    AVFilterBufferRef *outpicref;
+    int i;
+
+    outlink->out_buf = avfilter_get_video_buffer(outlink, AV_PERM_WRITE,
+                                                outlink->w, outlink->h);
+    outpicref = outlink->out_buf;
+    avfilter_copy_buffer_ref_props(outpicref, picref);
+
+    for (i = 0; i < 4; i++) {
+        int h = outlink->h;
+        h = i == 1 || i == 2 ? h>>priv->pix_desc->log2_chroma_h : h;
+        if (outpicref->data[i]) {
+            uint8_t *data = outpicref->data[i] +
+                (outpicref->linesize[i] > 0 ? 0 : outpicref->linesize[i] * (h-1));
+            memset(data, 0, FFABS(outpicref->linesize[i]) * h);
+        }
+    }
+
+    /* copy palette */
+    if (priv->pix_desc->flags & PIX_FMT_PAL)
+        memcpy(outpicref->data[1], outpicref->data[1], 256*4);
+
+    avfilter_start_frame(outlink, avfilter_ref_buffer(outpicref, ~0));
+}
+
+static void draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir)
+{
+    PixdescTestContext *priv = inlink->dst->priv;
+    AVFilterBufferRef *inpic    = inlink->cur_buf;
+    AVFilterBufferRef *outpic   = inlink->dst->outputs[0]->out_buf;
+    int i, c, w = inlink->w;
+
+    for (c = 0; c < priv->pix_desc->nb_components; c++) {
+        int w1 = c == 1 || c == 2 ? w>>priv->pix_desc->log2_chroma_w : w;
+        int h1 = c == 1 || c == 2 ? h>>priv->pix_desc->log2_chroma_h : h;
+        int y1 = c == 1 || c == 2 ? y>>priv->pix_desc->log2_chroma_h : y;
+
+        for (i = y1; i < y1 + h1; i++) {
+            av_read_image_line(priv->line,
+                               inpic->data,
+                               inpic->linesize,
+                               priv->pix_desc,
+                               0, i, c, w1, 0);
+
+            av_write_image_line(priv->line,
+                                outpic->data,
+                                outpic->linesize,
+                                priv->pix_desc,
+                                0, i, c, w1);
+        }
+    }
+
+    avfilter_draw_slice(inlink->dst->outputs[0], y, h, slice_dir);
+}
+
+AVFilter avfilter_vf_pixdesctest = {
+    .name        = "pixdesctest",
+    .description = NULL_IF_CONFIG_SMALL("Test pixel format definitions."),
+
+    .priv_size = sizeof(PixdescTestContext),
+    .uninit    = uninit,
+
+    .inputs    = (AVFilterPad[]) {{ .name            = "default",
+                                    .type            = AVMEDIA_TYPE_VIDEO,
+                                    .start_frame     = start_frame,
+                                    .draw_slice      = draw_slice,
+                                    .config_props    = config_props,
+                                    .min_perms       = AV_PERM_READ, },
+                                  { .name = NULL}},
+
+    .outputs   = (AVFilterPad[]) {{ .name            = "default",
+                                    .type            = AVMEDIA_TYPE_VIDEO, },
+                                  { .name = NULL}},
+};
diff --git a/libavfilter/vf_scale.c b/libavfilter/vf_scale.c
index a6b50ac..b2b0b63 100644
--- a/libavfilter/vf_scale.c
+++ b/libavfilter/vf_scale.c
@@ -1,20 +1,20 @@
 /*
- * copyright (c) 2007 Bobby Bingham
+ * Copyright (c) 2007 Bobby Bingham
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -36,6 +36,7 @@ typedef struct {
      *  -1 = keep original aspect
      */
     int w, h;
+    unsigned int flags;         ///sws flags
 
     int hsub, vsub;             ///< chroma subsampling
     int slice_y;                ///< top of current output slice
@@ -45,14 +46,19 @@ typedef struct {
 static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
 {
     ScaleContext *scale = ctx->priv;
+    const char *p;
 
-    if (args)
+    scale->flags = SWS_BILINEAR;
+    if (args) {
         sscanf(args, "%d:%d", &scale->w, &scale->h);
+        p = strstr(args,"flags=");
+        if (p) scale->flags = strtoul(p+6, NULL, 0);
+    }
 
     /* sanity check params */
     if (scale->w <  -1 || scale->h <  -1) {
         av_log(ctx, AV_LOG_ERROR, "Size values less than -1 are not acceptable.\n");
-        return -1;
+        return AVERROR(EINVAL);
     }
     if (scale->w == -1 && scale->h == -1)
         scale->w = scale->h = 0;
@@ -77,7 +83,7 @@ static int query_formats(AVFilterContext *ctx)
         formats = NULL;
         for (pix_fmt = 0; pix_fmt < PIX_FMT_NB; pix_fmt++)
             if (   sws_isSupportedInput(pix_fmt)
-                && (ret = avfilter_add_colorspace(&formats, pix_fmt)) < 0) {
+                && (ret = avfilter_add_format(&formats, pix_fmt)) < 0) {
                 avfilter_formats_unref(&formats);
                 return ret;
             }
@@ -87,7 +93,7 @@ static int query_formats(AVFilterContext *ctx)
         formats = NULL;
         for (pix_fmt = 0; pix_fmt < PIX_FMT_NB; pix_fmt++)
             if (    sws_isSupportedOutput(pix_fmt)
-                && (ret = avfilter_add_colorspace(&formats, pix_fmt)) < 0) {
+                && (ret = avfilter_add_format(&formats, pix_fmt)) < 0) {
                 avfilter_formats_unref(&formats);
                 return ret;
             }
@@ -122,47 +128,53 @@ static int config_props(AVFilterLink *outlink)
     outlink->h = h;
 
     /* TODO: make algorithm configurable */
-    scale->sws = sws_getContext(inlink ->w, inlink ->h, inlink ->format,
-                                outlink->w, outlink->h, outlink->format,
-                                SWS_BILINEAR, NULL, NULL, NULL);
-
-    av_log(ctx, AV_LOG_INFO, "w:%d h:%d fmt:%s\n",
-           outlink->w, outlink->h, av_pix_fmt_descriptors[outlink->format].name);
+    av_log(ctx, AV_LOG_INFO, "w:%d h:%d fmt:%s -> w:%d h:%d fmt:%s flags:0x%0x\n",
+           inlink ->w, inlink ->h, av_pix_fmt_descriptors[ inlink->format].name,
+           outlink->w, outlink->h, av_pix_fmt_descriptors[outlink->format].name,
+           scale->flags);
 
     scale->input_is_pal = av_pix_fmt_descriptors[inlink->format].flags & PIX_FMT_PAL;
 
-    return !scale->sws;
+    scale->sws = sws_getContext(inlink ->w, inlink ->h, inlink ->format,
+                                outlink->w, outlink->h, outlink->format,
+                                scale->flags, NULL, NULL, NULL);
+    if (!scale->sws)
+        return AVERROR(EINVAL);
+
+    return 0;
 }
 
-static void start_frame(AVFilterLink *link, AVFilterPicRef *picref)
+static void start_frame(AVFilterLink *link, AVFilterBufferRef *picref)
 {
     ScaleContext *scale = link->dst->priv;
     AVFilterLink *outlink = link->dst->outputs[0];
-    AVFilterPicRef *outpicref;
+    AVFilterBufferRef *outpicref;
 
     scale->hsub = av_pix_fmt_descriptors[link->format].log2_chroma_w;
     scale->vsub = av_pix_fmt_descriptors[link->format].log2_chroma_h;
 
     outpicref = avfilter_get_video_buffer(outlink, AV_PERM_WRITE, outlink->w, outlink->h);
-    outpicref->pts = picref->pts;
-    outpicref->pos = picref->pos;
-    outlink->outpic = outpicref;
+    avfilter_copy_buffer_ref_props(outpicref, picref);
+    outpicref->video->w = outlink->w;
+    outpicref->video->h = outlink->h;
+
+    outlink->out_buf = outpicref;
 
-    av_reduce(&outpicref->pixel_aspect.num, &outpicref->pixel_aspect.den,
-              (int64_t)picref->pixel_aspect.num * outlink->h * link->w,
-              (int64_t)picref->pixel_aspect.den * outlink->w * link->h,
+    av_reduce(&outpicref->video->pixel_aspect.num, &outpicref->video->pixel_aspect.den,
+              (int64_t)picref->video->pixel_aspect.num * outlink->h * link->w,
+              (int64_t)picref->video->pixel_aspect.den * outlink->w * link->h,
               INT_MAX);
 
     scale->slice_y = 0;
-    avfilter_start_frame(outlink, avfilter_ref_pic(outpicref, ~0));
+    avfilter_start_frame(outlink, avfilter_ref_buffer(outpicref, ~0));
 }
 
 static void draw_slice(AVFilterLink *link, int y, int h, int slice_dir)
 {
     ScaleContext *scale = link->dst->priv;
     int out_h;
-    AVFilterPicRef *cur_pic = link->cur_pic;
-    uint8_t *data[4];
+    AVFilterBufferRef *cur_pic = link->cur_buf;
+    const uint8_t *data[4];
 
     if (scale->slice_y == 0 && slice_dir == -1)
         scale->slice_y = link->dst->outputs[0]->h;
@@ -175,8 +187,8 @@ static void draw_slice(AVFilterLink *link, int y, int h, int slice_dir)
     data[3] = cur_pic->data[3] +  y               * cur_pic->linesize[3];
 
     out_h = sws_scale(scale->sws, data, cur_pic->linesize, y, h,
-                      link->dst->outputs[0]->outpic->data,
-                      link->dst->outputs[0]->outpic->linesize);
+                      link->dst->outputs[0]->out_buf->data,
+                      link->dst->outputs[0]->out_buf->linesize);
 
     if (slice_dir == -1)
         scale->slice_y -= out_h;
@@ -187,7 +199,7 @@ static void draw_slice(AVFilterLink *link, int y, int h, int slice_dir)
 
 AVFilter avfilter_vf_scale = {
     .name      = "scale",
-    .description = "Scale the input video to width:height size and/or convert the image format.",
+    .description = NULL_IF_CONFIG_SMALL("Scale the input video to width:height size and/or convert the image format."),
 
     .init      = init,
     .uninit    = uninit,
diff --git a/libavfilter/vf_setpts.c b/libavfilter/vf_setpts.c
new file mode 100644
index 0000000..bece373
--- /dev/null
+++ b/libavfilter/vf_setpts.c
@@ -0,0 +1,157 @@
+/*
+ * Copyright (c) 2010 Stefano Sabatini
+ * Copyright (c) 2008 Victor Paesa
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * video presentation timestamp (PTS) modification filter
+ */
+
+/* #define DEBUG */
+
+#include "libavutil/eval.h"
+#include "avfilter.h"
+
+static const char *var_names[] = {
+    "E",           ///< Euler number
+    "INTERLACED",  ///< tell if the current frame is interlaced
+    "N",           ///< frame number (starting at zero)
+    "PHI",         ///< golden ratio
+    "PI",          ///< greek pi
+    "POS",         ///< original position in the file of the frame
+    "PREV_INPTS",  ///< previous  input PTS
+    "PREV_OUTPTS", ///< previous output PTS
+    "PTS",         ///< original pts in the file of the frame
+    "STARTPTS",   ///< PTS at start of movie
+    "TB",          ///< timebase
+    NULL
+};
+
+enum var_name {
+    VAR_E,
+    VAR_INTERLACED,
+    VAR_N,
+    VAR_PHI,
+    VAR_PI,
+    VAR_POS,
+    VAR_PREV_INPTS,
+    VAR_PREV_OUTPTS,
+    VAR_PTS,
+    VAR_STARTPTS,
+    VAR_TB,
+    VAR_VARS_NB
+};
+
+typedef struct {
+    AVExpr *expr;
+    double var_values[VAR_VARS_NB];
+} SetPTSContext;
+
+static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
+{
+    SetPTSContext *setpts = ctx->priv;
+    int ret;
+
+    if ((ret = av_expr_parse(&setpts->expr, args ? args : "PTS",
+                             var_names, NULL, NULL, NULL, NULL, 0, ctx)) < 0) {
+        av_log(ctx, AV_LOG_ERROR, "Error while parsing expression '%s'\n", args);
+        return ret;
+    }
+
+    setpts->var_values[VAR_E          ] = M_E;
+    setpts->var_values[VAR_N          ] = 0.0;
+    setpts->var_values[VAR_PHI        ] = M_PHI;
+    setpts->var_values[VAR_PI         ] = M_PI;
+    setpts->var_values[VAR_PREV_INPTS ] = NAN;
+    setpts->var_values[VAR_PREV_OUTPTS] = NAN;
+    setpts->var_values[VAR_STARTPTS   ] = NAN;
+    return 0;
+}
+
+static int config_input(AVFilterLink *inlink)
+{
+    SetPTSContext *setpts = inlink->dst->priv;
+
+    setpts->var_values[VAR_TB] = av_q2d(inlink->time_base);
+
+    av_log(inlink->src, AV_LOG_INFO, "TB:%f\n", setpts->var_values[VAR_TB]);
+    return 0;
+}
+
+#define D2TS(d)  (isnan(d) ? AV_NOPTS_VALUE : (int64_t)(d))
+#define TS2D(ts) ((ts) == AV_NOPTS_VALUE ? NAN : (double)(ts))
+
+static void start_frame(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
+{
+    SetPTSContext *setpts = inlink->dst->priv;
+    double d;
+    AVFilterBufferRef *outpicref = avfilter_ref_buffer(inpicref, ~0);
+
+    if (isnan(setpts->var_values[VAR_STARTPTS]))
+        setpts->var_values[VAR_STARTPTS] = TS2D(inpicref->pts);
+
+    setpts->var_values[VAR_INTERLACED] = inpicref->video->interlaced;
+    setpts->var_values[VAR_PTS       ] = TS2D(inpicref->pts);
+    setpts->var_values[VAR_POS       ] = inpicref->pos == -1 ? NAN : inpicref->pos;
+
+    d = av_expr_eval(setpts->expr, setpts->var_values, NULL);
+    outpicref->pts = D2TS(d);
+
+#ifdef DEBUG
+    av_log(inlink->dst, AV_LOG_DEBUG,
+           "n:%"PRId64" interlaced:%d pos:%"PRId64" pts:%"PRId64" t:%f -> pts:%"PRId64" t:%f\n",
+           (int64_t)setpts->var_values[VAR_N],
+           (int)setpts->var_values[VAR_INTERLACED],
+           inpicref ->pos,
+           inpicref ->pts, inpicref ->pts * av_q2d(inlink->time_base),
+           outpicref->pts, outpicref->pts * av_q2d(inlink->time_base));
+#endif
+
+    setpts->var_values[VAR_N] += 1.0;
+    setpts->var_values[VAR_PREV_INPTS ] = TS2D(inpicref ->pts);
+    setpts->var_values[VAR_PREV_OUTPTS] = TS2D(outpicref->pts);
+    avfilter_start_frame(inlink->dst->outputs[0], outpicref);
+}
+
+static av_cold void uninit(AVFilterContext *ctx)
+{
+    SetPTSContext *setpts = ctx->priv;
+    av_expr_free(setpts->expr);
+    setpts->expr = NULL;
+}
+
+AVFilter avfilter_vf_setpts = {
+    .name      = "setpts",
+    .description = NULL_IF_CONFIG_SMALL("Set PTS for the output video frame."),
+    .init      = init,
+    .uninit    = uninit,
+
+    .priv_size = sizeof(SetPTSContext),
+
+    .inputs    = (AVFilterPad[]) {{ .name             = "default",
+                                    .type             = AVMEDIA_TYPE_VIDEO,
+                                    .get_video_buffer = avfilter_null_get_video_buffer,
+                                    .config_props     = config_input,
+                                    .start_frame      = start_frame, },
+                                  { .name = NULL }},
+    .outputs   = (AVFilterPad[]) {{ .name             = "default",
+                                    .type             = AVMEDIA_TYPE_VIDEO, },
+                                  { .name = NULL}},
+};
diff --git a/libavfilter/vf_settb.c b/libavfilter/vf_settb.c
new file mode 100644
index 0000000..9575483
--- /dev/null
+++ b/libavfilter/vf_settb.c
@@ -0,0 +1,141 @@
+/*
+ * Copyright (c) 2010 Stefano Sabatini
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * Set timebase for the output link.
+ */
+
+#include "libavutil/avstring.h"
+#include "libavutil/eval.h"
+#include "libavutil/rational.h"
+#include "avfilter.h"
+#include "internal.h"
+
+static const char *var_names[] = {
+    "E",
+    "PHI",
+    "PI",
+    "AVTB",   /* default timebase 1/AV_TIME_BASE */
+    "intb",   /* input timebase */
+    NULL
+};
+
+enum var_name {
+    VAR_E,
+    VAR_PHI,
+    VAR_PI,
+    VAR_AVTB,
+    VAR_INTB,
+    VAR_VARS_NB
+};
+
+typedef struct {
+    char tb_expr[256];
+    double var_values[VAR_VARS_NB];
+} SetTBContext;
+
+static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
+{
+    SetTBContext *settb = ctx->priv;
+    av_strlcpy(settb->tb_expr, "intb", sizeof(settb->tb_expr));
+
+    if (args)
+        sscanf(args, "%255[^:]", settb->tb_expr);
+
+    return 0;
+}
+
+static int config_output_props(AVFilterLink *outlink)
+{
+    AVFilterContext *ctx = outlink->src;
+    SetTBContext *settb = ctx->priv;
+    AVFilterLink *inlink = ctx->inputs[0];
+    AVRational time_base;
+    int ret;
+    double res;
+
+    settb->var_values[VAR_E]    = M_E;
+    settb->var_values[VAR_PHI]  = M_PHI;
+    settb->var_values[VAR_PI]   = M_PI;
+    settb->var_values[VAR_AVTB] = av_q2d(AV_TIME_BASE_Q);
+    settb->var_values[VAR_INTB] = av_q2d(inlink->time_base);
+
+    outlink->w = inlink->w;
+    outlink->h = inlink->h;
+
+    if ((ret = av_expr_parse_and_eval(&res, settb->tb_expr, var_names, settb->var_values,
+                                      NULL, NULL, NULL, NULL, NULL, 0, NULL)) < 0) {
+        av_log(ctx, AV_LOG_ERROR, "Invalid expression '%s' for timebase.\n", settb->tb_expr);
+        return ret;
+    }
+    time_base = av_d2q(res, INT_MAX);
+    if (time_base.num <= 0 || time_base.den <= 0) {
+        av_log(ctx, AV_LOG_ERROR,
+               "Invalid non-positive values for the timebase num:%d or den:%d.\n",
+               time_base.num, time_base.den);
+        return AVERROR(EINVAL);
+    }
+
+    outlink->time_base = time_base;
+    av_log(outlink->src, AV_LOG_INFO, "tb:%d/%d -> tb:%d/%d\n",
+           inlink ->time_base.num, inlink ->time_base.den,
+           outlink->time_base.num, outlink->time_base.den);
+
+    return 0;
+}
+
+static void start_frame(AVFilterLink *inlink, AVFilterBufferRef *picref)
+{
+    AVFilterContext *ctx = inlink->dst;
+    AVFilterLink *outlink = ctx->outputs[0];
+    AVFilterBufferRef *picref2 = picref;
+
+    if (av_cmp_q(inlink->time_base, outlink->time_base)) {
+        picref2 = avfilter_ref_buffer(picref, ~0);
+        picref2->pts = av_rescale_q(picref->pts, inlink->time_base, outlink->time_base);
+        av_log(ctx, AV_LOG_DEBUG, "tb:%d/%d pts:%"PRId64" -> tb:%d/%d pts:%"PRId64"\n",
+               inlink ->time_base.num, inlink ->time_base.den, picref ->pts,
+               outlink->time_base.num, outlink->time_base.den, picref2->pts);
+        avfilter_unref_buffer(picref);
+    }
+
+    avfilter_start_frame(outlink, picref2);
+}
+
+AVFilter avfilter_vf_settb = {
+    .name      = "settb",
+    .description = NULL_IF_CONFIG_SMALL("Set timebase for the output link."),
+    .init      = init,
+
+    .priv_size = sizeof(SetTBContext),
+
+    .inputs    = (AVFilterPad[]) {{ .name             = "default",
+                                    .type             = AVMEDIA_TYPE_VIDEO,
+                                    .get_video_buffer = avfilter_null_get_video_buffer,
+                                    .start_frame      = start_frame,
+                                    .end_frame        = avfilter_null_end_frame },
+                                  { .name = NULL }},
+
+    .outputs   = (AVFilterPad[]) {{ .name            = "default",
+                                    .type            = AVMEDIA_TYPE_VIDEO,
+                                    .config_props    = config_output_props, },
+                                  { .name = NULL}},
+};
diff --git a/libavfilter/vf_slicify.c b/libavfilter/vf_slicify.c
index 35e05da..cc56fe8 100644
--- a/libavfilter/vf_slicify.c
+++ b/libavfilter/vf_slicify.c
@@ -1,20 +1,20 @@
 /*
- * copyright (c) 2007 Bobby Bingham
+ * Copyright (c) 2007 Bobby Bingham
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -57,7 +57,7 @@ static int config_props(AVFilterLink *link)
     return 0;
 }
 
-static void start_frame(AVFilterLink *link, AVFilterPicRef *picref)
+static void start_frame(AVFilterLink *link, AVFilterBufferRef *picref)
 {
     SliceContext *slice = link->dst->priv;
 
@@ -97,7 +97,7 @@ static void draw_slice(AVFilterLink *link, int y, int h, int slice_dir)
 
 AVFilter avfilter_vf_slicify = {
     .name      = "slicify",
-    .description = "Pass the images of input video on to next video filter as multiple slices.",
+    .description = NULL_IF_CONFIG_SMALL("Pass the images of input video on to next video filter as multiple slices."),
 
     .init      = init,
 
diff --git a/libavfilter/vf_transpose.c b/libavfilter/vf_transpose.c
new file mode 100644
index 0000000..a0ec67c
--- /dev/null
+++ b/libavfilter/vf_transpose.c
@@ -0,0 +1,217 @@
+/*
+ * Copyright (c) 2010 Stefano Sabatini
+ * Copyright (c) 2008 Vitor Sessak
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * transposition filter
+ * Based on MPlayer libmpcodecs/vf_rotate.c.
+ */
+
+#include "libavutil/intreadwrite.h"
+#include "libavutil/pixdesc.h"
+#include "libavutil/imgutils.h"
+#include "avfilter.h"
+
+typedef struct {
+    int hsub, vsub;
+    int pixsteps[4];
+
+    /* 0    Rotate by 90 degrees counterclockwise and vflip. */
+    /* 1    Rotate by 90 degrees clockwise.                  */
+    /* 2    Rotate by 90 degrees counterclockwise.           */
+    /* 3    Rotate by 90 degrees clockwise and vflip.        */
+    int dir;
+} TransContext;
+
+static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
+{
+    TransContext *trans = ctx->priv;
+    trans->dir = 0;
+
+    if (args)
+        sscanf(args, "%d", &trans->dir);
+
+    if (trans->dir < 0 || trans->dir > 3) {
+        av_log(ctx, AV_LOG_ERROR, "Invalid value %d not between 0 and 3.\n",
+               trans->dir);
+        return AVERROR(EINVAL);
+    }
+    return 0;
+}
+
+static int query_formats(AVFilterContext *ctx)
+{
+    enum PixelFormat pix_fmts[] = {
+        PIX_FMT_ARGB,         PIX_FMT_RGBA,
+        PIX_FMT_ABGR,         PIX_FMT_BGRA,
+        PIX_FMT_RGB24,        PIX_FMT_BGR24,
+        PIX_FMT_RGB565BE,     PIX_FMT_RGB565LE,
+        PIX_FMT_RGB555BE,     PIX_FMT_RGB555LE,
+        PIX_FMT_BGR565BE,     PIX_FMT_BGR565LE,
+        PIX_FMT_BGR555BE,     PIX_FMT_BGR555LE,
+        PIX_FMT_GRAY16BE,     PIX_FMT_GRAY16LE,
+        PIX_FMT_YUV420P16LE,  PIX_FMT_YUV420P16BE,
+        PIX_FMT_YUV422P16LE,  PIX_FMT_YUV422P16BE,
+        PIX_FMT_YUV444P16LE,  PIX_FMT_YUV444P16BE,
+        PIX_FMT_NV12,         PIX_FMT_NV21,
+        PIX_FMT_RGB8,         PIX_FMT_BGR8,
+        PIX_FMT_RGB4_BYTE,    PIX_FMT_BGR4_BYTE,
+        PIX_FMT_YUV444P,      PIX_FMT_YUV422P,
+        PIX_FMT_YUV420P,      PIX_FMT_YUVJ420P,
+        PIX_FMT_YUV411P,      PIX_FMT_YUV410P,
+        PIX_FMT_YUVJ444P,     PIX_FMT_YUVJ422P,
+        PIX_FMT_YUV440P,      PIX_FMT_YUVJ440P,
+        PIX_FMT_YUVA420P,     PIX_FMT_GRAY8,
+        PIX_FMT_NONE
+    };
+
+    avfilter_set_common_formats(ctx, avfilter_make_format_list(pix_fmts));
+    return 0;
+}
+
+static int config_props_output(AVFilterLink *outlink)
+{
+    AVFilterContext *ctx = outlink->src;
+    TransContext *trans = ctx->priv;
+    AVFilterLink *inlink = ctx->inputs[0];
+    const AVPixFmtDescriptor *pixdesc = &av_pix_fmt_descriptors[outlink->format];
+
+    trans->hsub = av_pix_fmt_descriptors[inlink->format].log2_chroma_w;
+    trans->vsub = av_pix_fmt_descriptors[inlink->format].log2_chroma_h;
+
+    av_image_fill_max_pixsteps(trans->pixsteps, NULL, pixdesc);
+
+    outlink->w = inlink->h;
+    outlink->h = inlink->w;
+
+    if (inlink->sample_aspect_ratio.num){
+        outlink->sample_aspect_ratio = av_div_q((AVRational){1,1}, inlink->sample_aspect_ratio);
+    } else
+        outlink->sample_aspect_ratio = inlink->sample_aspect_ratio;
+
+    av_log(ctx, AV_LOG_INFO, "w:%d h:%d dir:%d -> w:%d h:%d rotation:%s vflip:%d\n",
+           inlink->w, inlink->h, trans->dir, outlink->w, outlink->h,
+           trans->dir == 1 || trans->dir == 3 ? "clockwise" : "counterclockwise",
+           trans->dir == 0 || trans->dir == 3);
+    return 0;
+}
+
+static void start_frame(AVFilterLink *inlink, AVFilterBufferRef *picref)
+{
+    AVFilterLink *outlink = inlink->dst->outputs[0];
+
+    outlink->out_buf = avfilter_get_video_buffer(outlink, AV_PERM_WRITE,
+                                                 outlink->w, outlink->h);
+    outlink->out_buf->pts = picref->pts;
+
+    if (picref->video->pixel_aspect.num == 0) {
+        outlink->out_buf->video->pixel_aspect = picref->video->pixel_aspect;
+    } else {
+        outlink->out_buf->video->pixel_aspect.num = picref->video->pixel_aspect.den;
+        outlink->out_buf->video->pixel_aspect.den = picref->video->pixel_aspect.num;
+    }
+
+    avfilter_start_frame(outlink, avfilter_ref_buffer(outlink->out_buf, ~0));
+}
+
+static void end_frame(AVFilterLink *inlink)
+{
+    TransContext *trans = inlink->dst->priv;
+    AVFilterBufferRef *inpic  = inlink->cur_buf;
+    AVFilterBufferRef *outpic = inlink->dst->outputs[0]->out_buf;
+    AVFilterLink *outlink = inlink->dst->outputs[0];
+    int plane;
+
+    for (plane = 0; outpic->data[plane]; plane++) {
+        int hsub = plane == 1 || plane == 2 ? trans->hsub : 0;
+        int vsub = plane == 1 || plane == 2 ? trans->vsub : 0;
+        int pixstep = trans->pixsteps[plane];
+        int inh  = inpic->video->h>>vsub;
+        int outw = outpic->video->w>>hsub;
+        int outh = outpic->video->h>>vsub;
+        uint8_t *out, *in;
+        int outlinesize, inlinesize;
+        int x, y;
+
+        out = outpic->data[plane]; outlinesize = outpic->linesize[plane];
+        in  = inpic ->data[plane]; inlinesize  = inpic ->linesize[plane];
+
+        if (trans->dir&1) {
+            in +=  inpic->linesize[plane] * (inh-1);
+            inlinesize *= -1;
+        }
+
+        if (trans->dir&2) {
+            out += outpic->linesize[plane] * (outh-1);
+            outlinesize *= -1;
+        }
+
+        for (y = 0; y < outh; y++) {
+            switch (pixstep) {
+            case 1:
+                for (x = 0; x < outw; x++)
+                    out[x] = in[x*inlinesize + y];
+                break;
+            case 2:
+                for (x = 0; x < outw; x++)
+                    *((uint16_t *)(out + 2*x)) = *((uint16_t *)(in + x*inlinesize + y*2));
+                break;
+            case 3:
+                for (x = 0; x < outw; x++) {
+                    int32_t v = AV_RB24(in + x*inlinesize + y*3);
+                    AV_WB24(out + 3*x, v);
+                }
+                break;
+            case 4:
+                for (x = 0; x < outw; x++)
+                    *((uint32_t *)(out + 4*x)) = *((uint32_t *)(in + x*inlinesize + y*4));
+                break;
+            }
+            out += outlinesize;
+        }
+    }
+
+    avfilter_unref_buffer(inpic);
+    avfilter_draw_slice(outlink, 0, outpic->video->h, 1);
+    avfilter_end_frame(outlink);
+    avfilter_unref_buffer(outpic);
+}
+
+AVFilter avfilter_vf_transpose = {
+    .name      = "transpose",
+    .description = NULL_IF_CONFIG_SMALL("Transpose input video."),
+
+    .init = init,
+    .priv_size = sizeof(TransContext),
+
+    .query_formats = query_formats,
+
+    .inputs    = (AVFilterPad[]) {{ .name            = "default",
+                                    .type            = AVMEDIA_TYPE_VIDEO,
+                                    .start_frame     = start_frame,
+                                    .end_frame       = end_frame,
+                                    .min_perms       = AV_PERM_READ, },
+                                  { .name = NULL}},
+    .outputs   = (AVFilterPad[]) {{ .name            = "default",
+                                    .config_props    = config_props_output,
+                                    .type            = AVMEDIA_TYPE_VIDEO, },
+                                  { .name = NULL}},
+};
diff --git a/libavfilter/vf_unsharp.c b/libavfilter/vf_unsharp.c
index 78a6d7c..274b13c 100644
--- a/libavfilter/vf_unsharp.c
+++ b/libavfilter/vf_unsharp.c
@@ -1,29 +1,29 @@
 /*
- * Ported to FFmpeg from MPlayer libmpcodecs/unsharp.c
- * Original copyright (C) 2002 Remi Guyomarch <rguyom at pobox.com>
- * Port copyright (C) 2010 Daniel G. Taylor <dan at programmer-art.org>
+ * Original copyright (c) 2002 Remi Guyomarch <rguyom at pobox.com>
+ * Port copyright (c) 2010 Daniel G. Taylor <dan at programmer-art.org>
  * Relicensed to the LGPL with permission from Remi Guyomarch.
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 /**
  * @file
- * blur / sharpen filter
+ * blur / sharpen filter, ported to Libav from MPlayer
+ * libmpcodecs/unsharp.c.
  *
  * This code is based on:
  *
@@ -83,9 +83,9 @@ static void unsharpen(uint8_t *dst, uint8_t *src, int dst_stride, int src_stride
     for (y = 0; y < 2 * fp->steps_y; y++)
         memset(sc[y], 0, sizeof(sc[y][0]) * (width + 2 * fp->steps_x));
 
-    for (y =- fp->steps_y; y < height + fp->steps_y; y++) {
+    for (y = -fp->steps_y; y < height + fp->steps_y; y++) {
         memset(sr, 0, sizeof(sr[0]) * (2 * fp->steps_x - 1));
-        for (x =- fp->steps_x; x < width + fp->steps_x; x++) {
+        for (x = -fp->steps_x; x < width + fp->steps_x; x++) {
             tmp1 = x <= 0 ? src[0] : x >= width ? src[width-1] : src[x];
             for (z = 0; z < fp->steps_x * 2; z += 2) {
                 tmp2 = sr[z + 0] + tmp1; sr[z + 0] = tmp1;
@@ -133,6 +133,14 @@ static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
         sscanf(args, "%d:%d:%lf:%d:%d:%lf", &lmsize_x, &lmsize_y, &lamount,
                                             &cmsize_x, &cmsize_y, &camount);
 
+    if ((lamount && (lmsize_x < 2 || lmsize_y < 2)) ||
+        (camount && (cmsize_x < 2 || cmsize_y < 2))) {
+        av_log(ctx, AV_LOG_ERROR,
+               "Invalid value <2 for lmsize_x:%d or lmsize_y:%d or cmsize_x:%d or cmsize_y:%d\n",
+               lmsize_x, lmsize_y, cmsize_x, cmsize_y);
+        return AVERROR(EINVAL);
+    }
+
     set_filter_param(&unsharp->luma,   lmsize_x, lmsize_y, lamount);
     set_filter_param(&unsharp->chroma, cmsize_x, cmsize_y, camount);
 
@@ -195,17 +203,17 @@ static av_cold void uninit(AVFilterContext *ctx)
 static void end_frame(AVFilterLink *link)
 {
     UnsharpContext *unsharp = link->dst->priv;
-    AVFilterPicRef *in  = link->cur_pic;
-    AVFilterPicRef *out = link->dst->outputs[0]->outpic;
+    AVFilterBufferRef *in  = link->cur_buf;
+    AVFilterBufferRef *out = link->dst->outputs[0]->out_buf;
 
     unsharpen(out->data[0], in->data[0], out->linesize[0], in->linesize[0], link->w,            link->h,             &unsharp->luma);
     unsharpen(out->data[1], in->data[1], out->linesize[1], in->linesize[1], CHROMA_WIDTH(link), CHROMA_HEIGHT(link), &unsharp->chroma);
     unsharpen(out->data[2], in->data[2], out->linesize[2], in->linesize[2], CHROMA_WIDTH(link), CHROMA_HEIGHT(link), &unsharp->chroma);
 
-    avfilter_unref_pic(in);
+    avfilter_unref_buffer(in);
     avfilter_draw_slice(link->dst->outputs[0], 0, link->h, 1);
     avfilter_end_frame(link->dst->outputs[0]);
-    avfilter_unref_pic(out);
+    avfilter_unref_buffer(out);
 }
 
 static void draw_slice(AVFilterLink *link, int y, int h, int slice_dir)
diff --git a/libavfilter/vf_vflip.c b/libavfilter/vf_vflip.c
index 0dfcb35..09ba303 100644
--- a/libavfilter/vf_vflip.c
+++ b/libavfilter/vf_vflip.c
@@ -1,20 +1,20 @@
 /*
- * copyright (c) 2007 Bobby Bingham
+ * Copyright (c) 2007 Bobby Bingham
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -39,15 +39,17 @@ static int config_input(AVFilterLink *link)
     return 0;
 }
 
-static AVFilterPicRef *get_video_buffer(AVFilterLink *link, int perms,
+static AVFilterBufferRef *get_video_buffer(AVFilterLink *link, int perms,
                                         int w, int h)
 {
     FlipContext *flip = link->dst->priv;
+    AVFilterBufferRef *picref;
     int i;
 
-    AVFilterPicRef *picref = avfilter_get_video_buffer(link->dst->outputs[0],
-                                                       perms, w, h);
+    if (!(perms & AV_PERM_NEG_LINESIZES))
+        return avfilter_default_get_video_buffer(link, perms, w, h);
 
+    picref = avfilter_get_video_buffer(link->dst->outputs[0], perms, w, h);
     for (i = 0; i < 4; i ++) {
         int vsub = i == 1 || i == 2 ? flip->vsub : 0;
 
@@ -60,21 +62,22 @@ static AVFilterPicRef *get_video_buffer(AVFilterLink *link, int perms,
     return picref;
 }
 
-static void start_frame(AVFilterLink *link, AVFilterPicRef *picref)
+static void start_frame(AVFilterLink *link, AVFilterBufferRef *inpicref)
 {
     FlipContext *flip = link->dst->priv;
+    AVFilterBufferRef *outpicref = avfilter_ref_buffer(inpicref, ~0);
     int i;
 
     for (i = 0; i < 4; i ++) {
         int vsub = i == 1 || i == 2 ? flip->vsub : 0;
 
-        if (picref->data[i]) {
-            picref->data[i] += ((link->h >> vsub)-1) * picref->linesize[i];
-            picref->linesize[i] = -picref->linesize[i];
+        if (outpicref->data[i]) {
+            outpicref->data[i] += ((link->h >> vsub)-1) * outpicref->linesize[i];
+            outpicref->linesize[i] = -outpicref->linesize[i];
         }
     }
 
-    avfilter_start_frame(link->dst->outputs[0], picref);
+    avfilter_start_frame(link->dst->outputs[0], outpicref);
 }
 
 static void draw_slice(AVFilterLink *link, int y, int h, int slice_dir)
@@ -95,7 +98,6 @@ AVFilter avfilter_vf_vflip = {
                                     .get_video_buffer = get_video_buffer,
                                     .start_frame      = start_frame,
                                     .draw_slice       = draw_slice,
-                                    .end_frame        = avfilter_null_end_frame,
                                     .config_props     = config_input, },
                                   { .name = NULL}},
     .outputs   = (AVFilterPad[]) {{ .name             = "default",
diff --git a/libavfilter/vf_yadif.c b/libavfilter/vf_yadif.c
new file mode 100644
index 0000000..176349a
--- /dev/null
+++ b/libavfilter/vf_yadif.c
@@ -0,0 +1,351 @@
+/*
+ * Copyright (C) 2006-2010 Michael Niedermayer <michaelni at gmx.at>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with Libav; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+
+#include "libavutil/cpu.h"
+#include "libavutil/common.h"
+#include "avfilter.h"
+#include "yadif.h"
+
+#undef NDEBUG
+#include <assert.h>
+
+typedef struct {
+    /**
+     * 0: send 1 frame for each frame
+     * 1: send 1 frame for each field
+     * 2: like 0 but skips spatial interlacing check
+     * 3: like 1 but skips spatial interlacing check
+     */
+    int mode;
+
+    /**
+     *  0: bottom field first
+     *  1: top field first
+     * -1: auto-detection
+     */
+    int parity;
+
+    int frame_pending;
+
+    AVFilterBufferRef *cur;
+    AVFilterBufferRef *next;
+    AVFilterBufferRef *prev;
+    AVFilterBufferRef *out;
+    void (*filter_line)(uint8_t *dst,
+                        uint8_t *prev, uint8_t *cur, uint8_t *next,
+                        int w, int prefs, int mrefs, int parity, int mode);
+} YADIFContext;
+
+static void filter_line_c(uint8_t *dst,
+                          uint8_t *prev, uint8_t *cur, uint8_t *next,
+                          int w, int prefs, int mrefs, int parity, int mode)
+{
+    int x;
+    uint8_t *prev2 = parity ? prev : cur ;
+    uint8_t *next2 = parity ? cur  : next;
+    for (x = 0;  x < w; x++) {
+        int c = cur[mrefs];
+        int d = (prev2[0] + next2[0])>>1;
+        int e = cur[prefs];
+        int temporal_diff0 = FFABS(prev2[0] - next2[0]);
+        int temporal_diff1 =(FFABS(prev[mrefs] - c) + FFABS(prev[prefs] - e) )>>1;
+        int temporal_diff2 =(FFABS(next[mrefs] - c) + FFABS(next[prefs] - e) )>>1;
+        int diff = FFMAX3(temporal_diff0>>1, temporal_diff1, temporal_diff2);
+        int spatial_pred = (c+e)>>1;
+        int spatial_score = FFABS(cur[mrefs-1] - cur[prefs-1]) + FFABS(c-e)
+                          + FFABS(cur[mrefs+1] - cur[prefs+1]) - 1;
+
+#define CHECK(j)\
+    {   int score = FFABS(cur[mrefs-1+(j)] - cur[prefs-1-(j)])\
+                  + FFABS(cur[mrefs  +(j)] - cur[prefs  -(j)])\
+                  + FFABS(cur[mrefs+1+(j)] - cur[prefs+1-(j)]);\
+        if (score < spatial_score) {\
+            spatial_score= score;\
+            spatial_pred= (cur[mrefs  +(j)] + cur[prefs  -(j)])>>1;\
+
+        CHECK(-1) CHECK(-2) }} }}
+        CHECK( 1) CHECK( 2) }} }}
+
+        if (mode < 2) {
+            int b = (prev2[2*mrefs] + next2[2*mrefs])>>1;
+            int f = (prev2[2*prefs] + next2[2*prefs])>>1;
+#if 0
+            int a = cur[-3*refs];
+            int g = cur[+3*refs];
+            int max = FFMAX3(d-e, d-c, FFMIN3(FFMAX(b-c,f-e),FFMAX(b-c,b-a),FFMAX(f-g,f-e)) );
+            int min = FFMIN3(d-e, d-c, FFMAX3(FFMIN(b-c,f-e),FFMIN(b-c,b-a),FFMIN(f-g,f-e)) );
+#else
+            int max = FFMAX3(d-e, d-c, FFMIN(b-c, f-e));
+            int min = FFMIN3(d-e, d-c, FFMAX(b-c, f-e));
+#endif
+
+            diff = FFMAX3(diff, min, -max);
+        }
+
+        if (spatial_pred > d + diff)
+           spatial_pred = d + diff;
+        else if (spatial_pred < d - diff)
+           spatial_pred = d - diff;
+
+        dst[0] = spatial_pred;
+
+        dst++;
+        cur++;
+        prev++;
+        next++;
+        prev2++;
+        next2++;
+    }
+}
+
+static void filter(AVFilterContext *ctx, AVFilterBufferRef *dstpic,
+                   int parity, int tff)
+{
+    YADIFContext *yadif = ctx->priv;
+    int y, i;
+
+    for (i = 0; i < 3; i++) {
+        int is_chroma = !!i;
+        int w = dstpic->video->w >> is_chroma;
+        int h = dstpic->video->h >> is_chroma;
+        int refs = yadif->cur->linesize[i];
+
+        for (y = 0; y < h; y++) {
+            if ((y ^ parity) & 1) {
+                uint8_t *prev = &yadif->prev->data[i][y*refs];
+                uint8_t *cur  = &yadif->cur ->data[i][y*refs];
+                uint8_t *next = &yadif->next->data[i][y*refs];
+                uint8_t *dst  = &dstpic->data[i][y*dstpic->linesize[i]];
+                int     mode  = y==1 || y+2==h ? 2 : yadif->mode;
+                yadif->filter_line(dst, prev, cur, next, w, y+1<h ? refs : -refs, y ? -refs : refs, parity ^ tff, mode);
+            } else {
+                memcpy(&dstpic->data[i][y*dstpic->linesize[i]],
+                       &yadif->cur->data[i][y*refs], w);
+            }
+        }
+    }
+#if HAVE_MMX
+    __asm__ volatile("emms \n\t" : : : "memory");
+#endif
+}
+
+static AVFilterBufferRef *get_video_buffer(AVFilterLink *link, int perms, int w, int h)
+{
+    AVFilterBufferRef *picref;
+    int width = FFALIGN(w, 32);
+    int height= FFALIGN(h+6, 32);
+    int i;
+
+    picref = avfilter_default_get_video_buffer(link, perms, width, height);
+
+    picref->video->w = w;
+    picref->video->h = h;
+
+    for (i = 0; i < 3; i++)
+        picref->data[i] += 3 * picref->linesize[i];
+
+    return picref;
+}
+
+static void return_frame(AVFilterContext *ctx, int is_second)
+{
+    YADIFContext *yadif = ctx->priv;
+    AVFilterLink *link= ctx->outputs[0];
+    int tff;
+
+    if (yadif->parity == -1) {
+        tff = yadif->cur->video->interlaced ?
+            yadif->cur->video->top_field_first : 1;
+    } else {
+        tff = yadif->parity^1;
+    }
+
+    if (is_second)
+        yadif->out = avfilter_get_video_buffer(link, AV_PERM_WRITE | AV_PERM_PRESERVE |
+                                               AV_PERM_REUSE, link->w, link->h);
+
+    filter(ctx, yadif->out, tff ^ !is_second, tff);
+
+    if (is_second) {
+        if (yadif->next->pts != AV_NOPTS_VALUE &&
+            yadif->cur->pts != AV_NOPTS_VALUE) {
+            yadif->out->pts =
+                (yadif->next->pts&yadif->cur->pts) +
+                ((yadif->next->pts^yadif->cur->pts)>>1);
+        } else {
+            yadif->out->pts = AV_NOPTS_VALUE;
+        }
+        avfilter_start_frame(ctx->outputs[0], yadif->out);
+    }
+    avfilter_draw_slice(ctx->outputs[0], 0, link->h, 1);
+    avfilter_end_frame(ctx->outputs[0]);
+
+    yadif->frame_pending = (yadif->mode&1) && !is_second;
+}
+
+static void start_frame(AVFilterLink *link, AVFilterBufferRef *picref)
+{
+    AVFilterContext *ctx = link->dst;
+    YADIFContext *yadif = ctx->priv;
+
+    if (yadif->frame_pending)
+        return_frame(ctx, 1);
+
+    if (yadif->prev)
+        avfilter_unref_buffer(yadif->prev);
+    yadif->prev = yadif->cur;
+    yadif->cur  = yadif->next;
+    yadif->next = picref;
+
+    if (!yadif->cur)
+        return;
+
+    if (!yadif->prev)
+        yadif->prev = avfilter_ref_buffer(yadif->cur, AV_PERM_READ);
+
+    yadif->out = avfilter_get_video_buffer(ctx->outputs[0], AV_PERM_WRITE | AV_PERM_PRESERVE |
+                                       AV_PERM_REUSE, link->w, link->h);
+
+    avfilter_copy_buffer_ref_props(yadif->out, yadif->cur);
+    yadif->out->video->interlaced = 0;
+    avfilter_start_frame(ctx->outputs[0], yadif->out);
+}
+
+static void end_frame(AVFilterLink *link)
+{
+    AVFilterContext *ctx = link->dst;
+    YADIFContext *yadif = ctx->priv;
+
+    if (!yadif->out)
+        return;
+
+    return_frame(ctx, 0);
+}
+
+static int request_frame(AVFilterLink *link)
+{
+    AVFilterContext *ctx = link->src;
+    YADIFContext *yadif = ctx->priv;
+
+    if (yadif->frame_pending) {
+        return_frame(ctx, 1);
+        return 0;
+    }
+
+    do {
+        int ret;
+
+        if ((ret = avfilter_request_frame(link->src->inputs[0])))
+            return ret;
+    } while (!yadif->cur);
+
+    return 0;
+}
+
+static int poll_frame(AVFilterLink *link)
+{
+    YADIFContext *yadif = link->src->priv;
+    int ret, val;
+
+    if (yadif->frame_pending)
+        return 1;
+
+    val = avfilter_poll_frame(link->src->inputs[0]);
+
+    if (val==1 && !yadif->next) { //FIXME change API to not requre this red tape
+        if ((ret = avfilter_request_frame(link->src->inputs[0])) < 0)
+            return ret;
+        val = avfilter_poll_frame(link->src->inputs[0]);
+    }
+    assert(yadif->next);
+
+    return val * ((yadif->mode&1)+1);
+}
+
+static av_cold void uninit(AVFilterContext *ctx)
+{
+    YADIFContext *yadif = ctx->priv;
+
+    if (yadif->prev) avfilter_unref_buffer(yadif->prev);
+    if (yadif->cur ) avfilter_unref_buffer(yadif->cur );
+    if (yadif->next) avfilter_unref_buffer(yadif->next);
+}
+
+static int query_formats(AVFilterContext *ctx)
+{
+    static const enum PixelFormat pix_fmts[] = {
+        PIX_FMT_YUV420P,
+        PIX_FMT_GRAY8,
+        PIX_FMT_NONE
+    };
+
+    avfilter_set_common_formats(ctx, avfilter_make_format_list(pix_fmts));
+
+    return 0;
+}
+
+static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
+{
+    YADIFContext *yadif = ctx->priv;
+    av_unused int cpu_flags = av_get_cpu_flags();
+
+    yadif->mode = 0;
+    yadif->parity = -1;
+
+    if (args) sscanf(args, "%d:%d", &yadif->mode, &yadif->parity);
+
+    yadif->filter_line = filter_line_c;
+    if (HAVE_SSSE3 && cpu_flags & AV_CPU_FLAG_SSSE3)
+        yadif->filter_line = ff_yadif_filter_line_ssse3;
+    else if (HAVE_SSE && cpu_flags & AV_CPU_FLAG_SSE2)
+        yadif->filter_line = ff_yadif_filter_line_sse2;
+    else if (HAVE_MMX && cpu_flags & AV_CPU_FLAG_MMX)
+        yadif->filter_line = ff_yadif_filter_line_mmx;
+
+    av_log(ctx, AV_LOG_INFO, "mode:%d parity:%d\n", yadif->mode, yadif->parity);
+
+    return 0;
+}
+
+static void null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir) { }
+
+AVFilter avfilter_vf_yadif = {
+    .name          = "yadif",
+    .description   = NULL_IF_CONFIG_SMALL("Deinterlace the input image"),
+
+    .priv_size     = sizeof(YADIFContext),
+    .init          = init,
+    .uninit        = uninit,
+    .query_formats = query_formats,
+
+    .inputs    = (AVFilterPad[]) {{ .name             = "default",
+                                    .type             = AVMEDIA_TYPE_VIDEO,
+                                    .start_frame      = start_frame,
+                                    .get_video_buffer = get_video_buffer,
+                                    .draw_slice       = null_draw_slice,
+                                    .end_frame        = end_frame, },
+                                  { .name = NULL}},
+
+    .outputs   = (AVFilterPad[]) {{ .name             = "default",
+                                    .type             = AVMEDIA_TYPE_VIDEO,
+                                    .poll_frame       = poll_frame,
+                                    .request_frame    = request_frame, },
+                                  { .name = NULL}},
+};
diff --git a/libavfilter/vsink_nullsink.c b/libavfilter/vsink_nullsink.c
index d11912f..bdfcb8a 100644
--- a/libavfilter/vsink_nullsink.c
+++ b/libavfilter/vsink_nullsink.c
@@ -1,24 +1,24 @@
 /*
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "avfilter.h"
 
-static void start_frame(AVFilterLink *link, AVFilterPicRef *picref)
+static void start_frame(AVFilterLink *link, AVFilterBufferRef *picref)
 {
 }
 
@@ -28,7 +28,7 @@ static void end_frame(AVFilterLink *link)
 
 AVFilter avfilter_vsink_nullsink = {
     .name        = "nullsink",
-    .description = "Do absolutely nothing with the input video.",
+    .description = NULL_IF_CONFIG_SMALL("Do absolutely nothing with the input video."),
 
     .priv_size = 0,
 
diff --git a/libavfilter/vsrc_buffer.c b/libavfilter/vsrc_buffer.c
new file mode 100644
index 0000000..93f2367
--- /dev/null
+++ b/libavfilter/vsrc_buffer.c
@@ -0,0 +1,164 @@
+/*
+ * Copyright (c) 2008 Vitor Sessak
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * memory buffer source filter
+ */
+
+#include "avfilter.h"
+#include "vsrc_buffer.h"
+#include "libavutil/imgutils.h"
+
+typedef struct {
+    int64_t           pts;
+    AVFrame           frame;
+    int               has_frame;
+    int               h, w;
+    enum PixelFormat  pix_fmt;
+    AVRational        time_base;     ///< time_base to set in the output link
+    AVRational        pixel_aspect;
+} BufferSourceContext;
+
+int av_vsrc_buffer_add_frame(AVFilterContext *buffer_filter, AVFrame *frame,
+                             int64_t pts, AVRational pixel_aspect)
+{
+    BufferSourceContext *c = buffer_filter->priv;
+
+    if (c->has_frame) {
+        av_log(buffer_filter, AV_LOG_ERROR,
+               "Buffering several frames is not supported. "
+               "Please consume all available frames before adding a new one.\n"
+            );
+        //return -1;
+    }
+
+    memcpy(c->frame.data    , frame->data    , sizeof(frame->data));
+    memcpy(c->frame.linesize, frame->linesize, sizeof(frame->linesize));
+    c->frame.interlaced_frame= frame->interlaced_frame;
+    c->frame.top_field_first = frame->top_field_first;
+    c->pts = pts;
+    c->pixel_aspect = pixel_aspect;
+    c->has_frame = 1;
+
+    return 0;
+}
+
+static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
+{
+    BufferSourceContext *c = ctx->priv;
+    char pix_fmt_str[128];
+    int n = 0;
+
+    if (!args ||
+        (n = sscanf(args, "%d:%d:%127[^:]:%d:%d", &c->w, &c->h, pix_fmt_str, &c->time_base.num, &c->time_base.den)) != 5) {
+        av_log(ctx, AV_LOG_ERROR, "Expected 5 arguments, but only %d found in '%s'\n", n, args);
+        return AVERROR(EINVAL);
+    }
+    if ((c->pix_fmt = av_get_pix_fmt(pix_fmt_str)) == PIX_FMT_NONE) {
+        char *tail;
+        c->pix_fmt = strtol(pix_fmt_str, &tail, 10);
+        if (*tail || c->pix_fmt < 0 || c->pix_fmt >= PIX_FMT_NB) {
+            av_log(ctx, AV_LOG_ERROR, "Invalid pixel format string '%s'\n", pix_fmt_str);
+            return AVERROR(EINVAL);
+        }
+    }
+
+    av_log(ctx, AV_LOG_INFO, "w:%d h:%d pixfmt:%s\n", c->w, c->h, av_pix_fmt_descriptors[c->pix_fmt].name);
+    return 0;
+}
+
+static int query_formats(AVFilterContext *ctx)
+{
+    BufferSourceContext *c = ctx->priv;
+    enum PixelFormat pix_fmts[] = { c->pix_fmt, PIX_FMT_NONE };
+
+    avfilter_set_common_formats(ctx, avfilter_make_format_list(pix_fmts));
+    return 0;
+}
+
+static int config_props(AVFilterLink *link)
+{
+    BufferSourceContext *c = link->src->priv;
+
+    link->w = c->w;
+    link->h = c->h;
+    link->time_base = c->time_base;
+
+    return 0;
+}
+
+static int request_frame(AVFilterLink *link)
+{
+    BufferSourceContext *c = link->src->priv;
+    AVFilterBufferRef *picref;
+
+    if (!c->has_frame) {
+        av_log(link->src, AV_LOG_ERROR,
+               "request_frame() called with no available frame!\n");
+        //return -1;
+    }
+
+    /* This picture will be needed unmodified later for decoding the next
+     * frame */
+    picref = avfilter_get_video_buffer(link, AV_PERM_WRITE | AV_PERM_PRESERVE |
+                                       AV_PERM_REUSE2,
+                                       link->w, link->h);
+
+    av_image_copy(picref->data, picref->linesize,
+                  c->frame.data, c->frame.linesize,
+                  picref->format, link->w, link->h);
+
+    picref->pts                    = c->pts;
+    picref->video->pixel_aspect    = c->pixel_aspect;
+    picref->video->interlaced      = c->frame.interlaced_frame;
+    picref->video->top_field_first = c->frame.top_field_first;
+    avfilter_start_frame(link, avfilter_ref_buffer(picref, ~0));
+    avfilter_draw_slice(link, 0, link->h, 1);
+    avfilter_end_frame(link);
+    avfilter_unref_buffer(picref);
+
+    c->has_frame = 0;
+
+    return 0;
+}
+
+static int poll_frame(AVFilterLink *link)
+{
+    BufferSourceContext *c = link->src->priv;
+    return !!(c->has_frame);
+}
+
+AVFilter avfilter_vsrc_buffer = {
+    .name      = "buffer",
+    .description = NULL_IF_CONFIG_SMALL("Buffer video frames, and make them accessible to the filterchain."),
+    .priv_size = sizeof(BufferSourceContext),
+    .query_formats = query_formats,
+
+    .init      = init,
+
+    .inputs    = (AVFilterPad[]) {{ .name = NULL }},
+    .outputs   = (AVFilterPad[]) {{ .name            = "default",
+                                    .type            = AVMEDIA_TYPE_VIDEO,
+                                    .request_frame   = request_frame,
+                                    .poll_frame      = poll_frame,
+                                    .config_props    = config_props, },
+                                  { .name = NULL}},
+};
diff --git a/libavfilter/vsrc_buffer.h b/libavfilter/vsrc_buffer.h
new file mode 100644
index 0000000..c7fc382
--- /dev/null
+++ b/libavfilter/vsrc_buffer.h
@@ -0,0 +1,27 @@
+/*
+ * Memory buffer source filter
+ * Copyright (c) 2008 Vitor Sessak
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "libavcodec/avcodec.h" /* AVFrame */
+#include "avfilter.h"
+
+int av_vsrc_buffer_add_frame(AVFilterContext *buffer_filter, AVFrame *frame,
+                             int64_t pts, AVRational pixel_aspect);
+
diff --git a/libavfilter/vsrc_color.c b/libavfilter/vsrc_color.c
new file mode 100644
index 0000000..6d41c8a
--- /dev/null
+++ b/libavfilter/vsrc_color.c
@@ -0,0 +1,167 @@
+/*
+ * Copyright (c) 2010 Stefano Sabatini
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "avfilter.h"
+#include "libavutil/pixdesc.h"
+#include "libavutil/colorspace.h"
+#include "libavutil/imgutils.h"
+#include "libavutil/parseutils.h"
+#include "drawutils.h"
+
+typedef struct {
+    int w, h;
+    uint8_t color[4];
+    AVRational time_base;
+    uint8_t *line[4];
+    int      line_step[4];
+    int hsub, vsub;         ///< chroma subsampling values
+    uint64_t pts;
+} ColorContext;
+
+static av_cold int color_init(AVFilterContext *ctx, const char *args, void *opaque)
+{
+    ColorContext *color = ctx->priv;
+    char color_string[128] = "black";
+    char frame_size  [128] = "320x240";
+    char frame_rate  [128] = "25";
+    AVRational frame_rate_q;
+    int ret;
+
+    if (args)
+        sscanf(args, "%127[^:]:%127[^:]:%127s", color_string, frame_size, frame_rate);
+
+    if (av_parse_video_size(&color->w, &color->h, frame_size) < 0) {
+        av_log(ctx, AV_LOG_ERROR, "Invalid frame size: %s\n", frame_size);
+        return AVERROR(EINVAL);
+    }
+
+    if (av_parse_video_rate(&frame_rate_q, frame_rate) < 0 ||
+        frame_rate_q.den <= 0 || frame_rate_q.num <= 0) {
+        av_log(ctx, AV_LOG_ERROR, "Invalid frame rate: %s\n", frame_rate);
+        return AVERROR(EINVAL);
+    }
+    color->time_base.num = frame_rate_q.den;
+    color->time_base.den = frame_rate_q.num;
+
+    if ((ret = av_parse_color(color->color, color_string, -1, ctx)) < 0)
+        return ret;
+
+    return 0;
+}
+
+static av_cold void color_uninit(AVFilterContext *ctx)
+{
+    ColorContext *color = ctx->priv;
+    int i;
+
+    for (i = 0; i < 4; i++) {
+        av_freep(&color->line[i]);
+        color->line_step[i] = 0;
+    }
+}
+
+static int query_formats(AVFilterContext *ctx)
+{
+    static const enum PixelFormat pix_fmts[] = {
+        PIX_FMT_ARGB,         PIX_FMT_RGBA,
+        PIX_FMT_ABGR,         PIX_FMT_BGRA,
+        PIX_FMT_RGB24,        PIX_FMT_BGR24,
+
+        PIX_FMT_YUV444P,      PIX_FMT_YUV422P,
+        PIX_FMT_YUV420P,      PIX_FMT_YUV411P,
+        PIX_FMT_YUV410P,      PIX_FMT_YUV440P,
+        PIX_FMT_YUVJ444P,     PIX_FMT_YUVJ422P,
+        PIX_FMT_YUVJ420P,     PIX_FMT_YUVJ440P,
+        PIX_FMT_YUVA420P,
+
+        PIX_FMT_NONE
+    };
+
+    avfilter_set_common_formats(ctx, avfilter_make_format_list(pix_fmts));
+    return 0;
+}
+
+static int color_config_props(AVFilterLink *inlink)
+{
+    AVFilterContext *ctx = inlink->src;
+    ColorContext *color = ctx->priv;
+    uint8_t rgba_color[4];
+    int is_packed_rgba;
+    const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[inlink->format];
+
+    color->hsub = pix_desc->log2_chroma_w;
+    color->vsub = pix_desc->log2_chroma_h;
+
+    color->w &= ~((1 << color->hsub) - 1);
+    color->h &= ~((1 << color->vsub) - 1);
+    if (av_image_check_size(color->w, color->h, 0, ctx) < 0)
+        return AVERROR(EINVAL);
+
+    memcpy(rgba_color, color->color, sizeof(rgba_color));
+    ff_fill_line_with_color(color->line, color->line_step, color->w, color->color,
+                            inlink->format, rgba_color, &is_packed_rgba, NULL);
+
+    av_log(ctx, AV_LOG_INFO, "w:%d h:%d r:%d/%d color:0x%02x%02x%02x%02x[%s]\n",
+           color->w, color->h, color->time_base.den, color->time_base.num,
+           color->color[0], color->color[1], color->color[2], color->color[3],
+           is_packed_rgba ? "rgba" : "yuva");
+    inlink->w = color->w;
+    inlink->h = color->h;
+
+    return 0;
+}
+
+static int color_request_frame(AVFilterLink *link)
+{
+    ColorContext *color = link->src->priv;
+    AVFilterBufferRef *picref = avfilter_get_video_buffer(link, AV_PERM_WRITE, color->w, color->h);
+    picref->video->pixel_aspect = (AVRational) {1, 1};
+    picref->pts                 = av_rescale_q(color->pts++, color->time_base, AV_TIME_BASE_Q);
+    picref->pos                 = 0;
+
+    avfilter_start_frame(link, avfilter_ref_buffer(picref, ~0));
+    ff_draw_rectangle(picref->data, picref->linesize,
+                      color->line, color->line_step, color->hsub, color->vsub,
+                      0, 0, color->w, color->h);
+    avfilter_draw_slice(link, 0, color->h, 1);
+    avfilter_end_frame(link);
+    avfilter_unref_buffer(picref);
+
+    return 0;
+}
+
+AVFilter avfilter_vsrc_color = {
+    .name        = "color",
+    .description = NULL_IF_CONFIG_SMALL("Provide an uniformly colored input, syntax is: [color[:size[:rate]]]"),
+
+    .priv_size = sizeof(ColorContext),
+    .init      = color_init,
+    .uninit    = color_uninit,
+
+    .query_formats = query_formats,
+
+    .inputs    = (AVFilterPad[]) {{ .name = NULL}},
+
+    .outputs   = (AVFilterPad[]) {{ .name            = "default",
+                                    .type            = AVMEDIA_TYPE_VIDEO,
+                                    .request_frame   = color_request_frame,
+                                    .config_props    = color_config_props },
+                                  { .name = NULL}},
+};
diff --git a/libavfilter/vsrc_movie.c b/libavfilter/vsrc_movie.c
new file mode 100644
index 0000000..25bbd47
--- /dev/null
+++ b/libavfilter/vsrc_movie.c
@@ -0,0 +1,311 @@
+/*
+ * Copyright (c) 2010 Stefano Sabatini
+ * Copyright (c) 2008 Victor Paesa
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * movie video source
+ *
+ * @todo use direct rendering (no allocation of a new frame)
+ * @todo support a PTS correction mechanism
+ * @todo support more than one output stream
+ */
+
+/* #define DEBUG */
+
+#include <float.h>
+#include "libavutil/avstring.h"
+#include "libavutil/opt.h"
+#include "libavutil/imgutils.h"
+#include "libavformat/avformat.h"
+#include "avfilter.h"
+
+typedef struct {
+    const AVClass *class;
+    int64_t seek_point;   ///< seekpoint in microseconds
+    double seek_point_d;
+    char *format_name;
+    char *file_name;
+    int stream_index;
+
+    AVFormatContext *format_ctx;
+    AVCodecContext *codec_ctx;
+    int is_done;
+    AVFrame *frame;   ///< video frame to store the decoded images in
+
+    int w, h;
+    AVFilterBufferRef *picref;
+} MovieContext;
+
+#define OFFSET(x) offsetof(MovieContext, x)
+
+static const AVOption movie_options[]= {
+{"format_name",  "set format name",         OFFSET(format_name),  FF_OPT_TYPE_STRING, 0,  CHAR_MIN, CHAR_MAX },
+{"f",            "set format name",         OFFSET(format_name),  FF_OPT_TYPE_STRING, 0,  CHAR_MIN, CHAR_MAX },
+{"stream_index", "set stream index",        OFFSET(stream_index), FF_OPT_TYPE_INT,   -1,  -1,       INT_MAX  },
+{"si",           "set stream index",        OFFSET(stream_index), FF_OPT_TYPE_INT,   -1,  -1,       INT_MAX  },
+{"seek_point",   "set seekpoint (seconds)", OFFSET(seek_point_d), FF_OPT_TYPE_DOUBLE, 0,  0,        (INT64_MAX-1) / 1000000 },
+{"sp",           "set seekpoint (seconds)", OFFSET(seek_point_d), FF_OPT_TYPE_DOUBLE, 0,  0,        (INT64_MAX-1) / 1000000 },
+{NULL},
+};
+
+static const char *movie_get_name(void *ctx)
+{
+    return "movie";
+}
+
+static const AVClass movie_class = {
+    "MovieContext",
+    movie_get_name,
+    movie_options
+};
+
+static int movie_init(AVFilterContext *ctx)
+{
+    MovieContext *movie = ctx->priv;
+    AVInputFormat *iformat = NULL;
+    AVCodec *codec;
+    int ret;
+    int64_t timestamp;
+
+    av_register_all();
+
+    // Try to find the movie format (container)
+    iformat = movie->format_name ? av_find_input_format(movie->format_name) : NULL;
+
+    movie->format_ctx = NULL;
+    if ((ret = av_open_input_file(&movie->format_ctx, movie->file_name, iformat, 0, NULL)) < 0) {
+        av_log(ctx, AV_LOG_ERROR,
+               "Failed to av_open_input_file '%s'\n", movie->file_name);
+        return ret;
+    }
+    if ((ret = av_find_stream_info(movie->format_ctx)) < 0)
+        av_log(ctx, AV_LOG_WARNING, "Failed to find stream info\n");
+
+    // if seeking requested, we execute it
+    if (movie->seek_point > 0) {
+        timestamp = movie->seek_point;
+        // add the stream start time, should it exist
+        if (movie->format_ctx->start_time != AV_NOPTS_VALUE) {
+            if (timestamp > INT64_MAX - movie->format_ctx->start_time) {
+                av_log(ctx, AV_LOG_ERROR,
+                       "%s: seek value overflow with start_time:%"PRId64" seek_point:%"PRId64"\n",
+                       movie->file_name, movie->format_ctx->start_time, movie->seek_point);
+                return AVERROR(EINVAL);
+            }
+            timestamp += movie->format_ctx->start_time;
+        }
+        if ((ret = av_seek_frame(movie->format_ctx, -1, timestamp, AVSEEK_FLAG_BACKWARD)) < 0) {
+            av_log(ctx, AV_LOG_ERROR, "%s: could not seek to position %"PRId64"\n",
+                   movie->file_name, timestamp);
+            return ret;
+        }
+    }
+
+    /* select the video stream */
+    if ((ret = av_find_best_stream(movie->format_ctx, AVMEDIA_TYPE_VIDEO,
+                                   movie->stream_index, -1, NULL, 0)) < 0) {
+        av_log(ctx, AV_LOG_ERROR, "No video stream with index '%d' found\n",
+               movie->stream_index);
+        return ret;
+    }
+    movie->stream_index = ret;
+    movie->codec_ctx = movie->format_ctx->streams[movie->stream_index]->codec;
+
+    /*
+     * So now we've got a pointer to the so-called codec context for our video
+     * stream, but we still have to find the actual codec and open it.
+     */
+    codec = avcodec_find_decoder(movie->codec_ctx->codec_id);
+    if (!codec) {
+        av_log(ctx, AV_LOG_ERROR, "Failed to find any codec\n");
+        return AVERROR(EINVAL);
+    }
+
+    if ((ret = avcodec_open(movie->codec_ctx, codec)) < 0) {
+        av_log(ctx, AV_LOG_ERROR, "Failed to open codec\n");
+        return ret;
+    }
+
+    if (!(movie->frame = avcodec_alloc_frame()) ) {
+        av_log(ctx, AV_LOG_ERROR, "Failed to alloc frame\n");
+        return AVERROR(ENOMEM);
+    }
+
+    movie->w = movie->codec_ctx->width;
+    movie->h = movie->codec_ctx->height;
+
+    av_log(ctx, AV_LOG_INFO, "seek_point:%lld format_name:%s file_name:%s stream_index:%d\n",
+           movie->seek_point, movie->format_name, movie->file_name,
+           movie->stream_index);
+
+    return 0;
+}
+
+static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
+{
+    MovieContext *movie = ctx->priv;
+    int ret;
+    movie->class = &movie_class;
+    av_opt_set_defaults2(movie, 0, 0);
+
+    if (args)
+        movie->file_name = av_get_token(&args, ":");
+    if (!movie->file_name || !*movie->file_name) {
+        av_log(ctx, AV_LOG_ERROR, "No filename provided!\n");
+        return AVERROR(EINVAL);
+    }
+
+    if (*args++ == ':' && (ret = av_set_options_string(movie, args, "=", ":")) < 0) {
+        av_log(ctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
+        return ret;
+    }
+
+    movie->seek_point = movie->seek_point_d * 1000000 + 0.5;
+
+    return movie_init(ctx);
+}
+
+static av_cold void uninit(AVFilterContext *ctx)
+{
+    MovieContext *movie = ctx->priv;
+
+    av_free(movie->file_name);
+    av_free(movie->format_name);
+    if (movie->codec_ctx)
+        avcodec_close(movie->codec_ctx);
+    if (movie->format_ctx)
+        av_close_input_file(movie->format_ctx);
+    avfilter_unref_buffer(movie->picref);
+    av_freep(&movie->frame);
+}
+
+static int query_formats(AVFilterContext *ctx)
+{
+    MovieContext *movie = ctx->priv;
+    enum PixelFormat pix_fmts[] = { movie->codec_ctx->pix_fmt, PIX_FMT_NONE };
+
+    avfilter_set_common_formats(ctx, avfilter_make_format_list(pix_fmts));
+    return 0;
+}
+
+static int config_output_props(AVFilterLink *outlink)
+{
+    MovieContext *movie = outlink->src->priv;
+
+    outlink->w = movie->w;
+    outlink->h = movie->h;
+    outlink->time_base = movie->format_ctx->streams[movie->stream_index]->time_base;
+
+    return 0;
+}
+
+static int movie_get_frame(AVFilterLink *outlink)
+{
+    MovieContext *movie = outlink->src->priv;
+    AVPacket pkt;
+    int ret, frame_decoded;
+    AVStream *st = movie->format_ctx->streams[movie->stream_index];
+
+    if (movie->is_done == 1)
+        return 0;
+
+    while ((ret = av_read_frame(movie->format_ctx, &pkt)) >= 0) {
+        // Is this a packet from the video stream?
+        if (pkt.stream_index == movie->stream_index) {
+            movie->codec_ctx->reordered_opaque = pkt.pos;
+            avcodec_decode_video2(movie->codec_ctx, movie->frame, &frame_decoded, &pkt);
+
+            if (frame_decoded) {
+                /* FIXME: avoid the memcpy */
+                movie->picref = avfilter_get_video_buffer(outlink, AV_PERM_WRITE | AV_PERM_PRESERVE |
+                                                          AV_PERM_REUSE2, outlink->w, outlink->h);
+                av_image_copy(movie->picref->data, movie->picref->linesize,
+                              movie->frame->data,  movie->frame->linesize,
+                              movie->picref->format, outlink->w, outlink->h);
+
+                /* FIXME: use a PTS correction mechanism as that in
+                 * ffplay.c when some API will be available for that */
+                /* use pkt_dts if pkt_pts is not available */
+                movie->picref->pts = movie->frame->pkt_pts == AV_NOPTS_VALUE ?
+                    movie->frame->pkt_dts : movie->frame->pkt_pts;
+
+                movie->picref->pos                    = movie->frame->reordered_opaque;
+                movie->picref->video->pixel_aspect = st->sample_aspect_ratio.num ?
+                    st->sample_aspect_ratio : movie->codec_ctx->sample_aspect_ratio;
+                movie->picref->video->interlaced      = movie->frame->interlaced_frame;
+                movie->picref->video->top_field_first = movie->frame->top_field_first;
+                av_dlog(outlink->src,
+                        "movie_get_frame(): file:'%s' pts:%"PRId64" time:%lf pos:%"PRId64" aspect:%d/%d\n",
+                        movie->file_name, movie->picref->pts,
+                        (double)movie->picref->pts * av_q2d(st->time_base),
+                        movie->picref->pos,
+                        movie->picref->video->pixel_aspect.num, movie->picref->video->pixel_aspect.den);
+                // We got it. Free the packet since we are returning
+                av_free_packet(&pkt);
+
+                return 0;
+            }
+        }
+        // Free the packet that was allocated by av_read_frame
+        av_free_packet(&pkt);
+    }
+
+    // On multi-frame source we should stop the mixing process when
+    // the movie source does not have more frames
+    if (ret == AVERROR_EOF)
+        movie->is_done = 1;
+    return ret;
+}
+
+static int request_frame(AVFilterLink *outlink)
+{
+    AVFilterBufferRef *outpicref;
+    MovieContext *movie = outlink->src->priv;
+    int ret;
+
+    if (movie->is_done)
+        return AVERROR_EOF;
+    if ((ret = movie_get_frame(outlink)) < 0)
+        return ret;
+
+    outpicref = avfilter_ref_buffer(movie->picref, ~0);
+    avfilter_start_frame(outlink, outpicref);
+    avfilter_draw_slice(outlink, 0, outlink->h, 1);
+    avfilter_end_frame(outlink);
+
+    return 0;
+}
+
+AVFilter avfilter_vsrc_movie = {
+    .name          = "movie",
+    .description   = NULL_IF_CONFIG_SMALL("Read from a movie source."),
+    .priv_size     = sizeof(MovieContext),
+    .init          = init,
+    .uninit        = uninit,
+    .query_formats = query_formats,
+
+    .inputs    = (AVFilterPad[]) {{ .name = NULL }},
+    .outputs   = (AVFilterPad[]) {{ .name            = "default",
+                                    .type            = AVMEDIA_TYPE_VIDEO,
+                                    .request_frame   = request_frame,
+                                    .config_props    = config_output_props, },
+                                  { .name = NULL}},
+};
diff --git a/libavfilter/vsrc_nullsrc.c b/libavfilter/vsrc_nullsrc.c
index 4356199..629de78 100644
--- a/libavfilter/vsrc_nullsrc.c
+++ b/libavfilter/vsrc_nullsrc.c
@@ -1,18 +1,18 @@
 /*
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -21,10 +21,31 @@
  * null video source
  */
 
+#include "libavutil/avstring.h"
+#include "libavutil/eval.h"
+#include "libavutil/parseutils.h"
 #include "avfilter.h"
 
+static const char *var_names[] = {
+    "E",
+    "PHI",
+    "PI",
+    "AVTB",   /* default timebase 1/AV_TIME_BASE */
+    NULL
+};
+
+enum var_name {
+    VAR_E,
+    VAR_PHI,
+    VAR_PI,
+    VAR_AVTB,
+    VAR_VARS_NB
+};
+
 typedef struct {
     int w, h;
+    char tb_expr[256];
+    double var_values[VAR_VARS_NB];
 } NullContext;
 
 static int init(AVFilterContext *ctx, const char *args, void *opaque)
@@ -33,13 +54,14 @@ static int init(AVFilterContext *ctx, const char *args, void *opaque)
 
     priv->w = 352;
     priv->h = 288;
+    av_strlcpy(priv->tb_expr, "AVTB", sizeof(priv->tb_expr));
 
     if (args)
-        sscanf(args, "%d:%d", &priv->w, &priv->h);
+        sscanf(args, "%d:%d:%255[^:]", &priv->w, &priv->h, priv->tb_expr);
 
     if (priv->w <= 0 || priv->h <= 0) {
         av_log(ctx, AV_LOG_ERROR, "Non-positive size values are not acceptable.\n");
-        return -1;
+        return AVERROR(EINVAL);
     }
 
     return 0;
@@ -47,12 +69,36 @@ static int init(AVFilterContext *ctx, const char *args, void *opaque)
 
 static int config_props(AVFilterLink *outlink)
 {
-    NullContext *priv = outlink->src->priv;
+    AVFilterContext *ctx = outlink->src;
+    NullContext *priv = ctx->priv;
+    AVRational tb;
+    int ret;
+    double res;
+
+    priv->var_values[VAR_E]    = M_E;
+    priv->var_values[VAR_PHI]  = M_PHI;
+    priv->var_values[VAR_PI]   = M_PI;
+    priv->var_values[VAR_AVTB] = av_q2d(AV_TIME_BASE_Q);
+
+    if ((ret = av_expr_parse_and_eval(&res, priv->tb_expr, var_names, priv->var_values,
+                                      NULL, NULL, NULL, NULL, NULL, 0, NULL)) < 0) {
+        av_log(ctx, AV_LOG_ERROR, "Invalid expression '%s' for timebase.\n", priv->tb_expr);
+        return ret;
+    }
+    tb = av_d2q(res, INT_MAX);
+    if (tb.num <= 0 || tb.den <= 0) {
+        av_log(ctx, AV_LOG_ERROR,
+               "Invalid non-positive value for the timebase %d/%d.\n",
+               tb.num, tb.den);
+        return AVERROR(EINVAL);
+    }
 
     outlink->w = priv->w;
     outlink->h = priv->h;
+    outlink->time_base = tb;
 
-    av_log(outlink->src, AV_LOG_INFO, "w:%d h:%d\n", priv->w, priv->h);
+    av_log(outlink->src, AV_LOG_INFO, "w:%d h:%d tb:%d/%d\n", priv->w, priv->h,
+           tb.num, tb.den);
 
     return 0;
 }
@@ -64,7 +110,7 @@ static int request_frame(AVFilterLink *link)
 
 AVFilter avfilter_vsrc_nullsrc = {
     .name        = "nullsrc",
-    .description = "Null video source, never return images.",
+    .description = NULL_IF_CONFIG_SMALL("Null video source, never return images."),
 
     .init       = init,
     .priv_size = sizeof(NullContext),
diff --git a/libavfilter/x86/Makefile b/libavfilter/x86/Makefile
new file mode 100644
index 0000000..e98693d
--- /dev/null
+++ b/libavfilter/x86/Makefile
@@ -0,0 +1,2 @@
+MMX-OBJS-$(CONFIG_YADIF_FILTER)              += x86/yadif.o
+MMX-OBJS-$(CONFIG_GRADFUN_FILTER)            += x86/gradfun.o
diff --git a/libavfilter/x86/gradfun.c b/libavfilter/x86/gradfun.c
new file mode 100644
index 0000000..c9ade82
--- /dev/null
+++ b/libavfilter/x86/gradfun.c
@@ -0,0 +1,162 @@
+/*
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with Libav; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+
+#include "libavutil/cpu.h"
+#include "libavutil/x86_cpu.h"
+#include "libavfilter/gradfun.h"
+
+DECLARE_ALIGNED(16, static const uint16_t, pw_7f)[8] = {0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F};
+DECLARE_ALIGNED(16, static const uint16_t, pw_ff)[8] = {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF};
+
+void ff_gradfun_filter_line_mmx2(uint8_t *dst, uint8_t *src, uint16_t *dc, int width, int thresh, const uint16_t *dithers)
+{
+#if HAVE_MMX
+    intptr_t x;
+    if (width & 3) {
+        x = width & ~3;
+        ff_gradfun_filter_line_c(dst + x, src + x, dc + x / 2, width - x, thresh, dithers);
+        width = x;
+    }
+    x = -width;
+    __asm__ volatile(
+        "movd          %4, %%mm5 \n"
+        "pxor       %%mm7, %%mm7 \n"
+        "pshufw $0, %%mm5, %%mm5 \n"
+        "movq          %6, %%mm6 \n"
+        "movq          %5, %%mm4 \n"
+        "1: \n"
+        "movd     (%2,%0), %%mm0 \n"
+        "movd     (%3,%0), %%mm1 \n"
+        "punpcklbw  %%mm7, %%mm0 \n"
+        "punpcklwd  %%mm1, %%mm1 \n"
+        "psllw         $7, %%mm0 \n"
+        "pxor       %%mm2, %%mm2 \n"
+        "psubw      %%mm0, %%mm1 \n" // delta = dc - pix
+        "psubw      %%mm1, %%mm2 \n"
+        "pmaxsw     %%mm1, %%mm2 \n"
+        "pmulhuw    %%mm5, %%mm2 \n" // m = abs(delta) * thresh >> 16
+        "psubw      %%mm6, %%mm2 \n"
+        "pminsw     %%mm7, %%mm2 \n" // m = -max(0, 127-m)
+        "pmullw     %%mm2, %%mm2 \n"
+        "paddw      %%mm4, %%mm0 \n" // pix += dither
+        "pmulhw     %%mm2, %%mm1 \n"
+        "psllw         $2, %%mm1 \n" // m = m*m*delta >> 14
+        "paddw      %%mm1, %%mm0 \n" // pix += m
+        "psraw         $7, %%mm0 \n"
+        "packuswb   %%mm0, %%mm0 \n"
+        "movd       %%mm0, (%1,%0) \n" // dst = clip(pix>>7)
+        "add           $4, %0 \n"
+        "jl 1b \n"
+        "emms \n"
+        :"+r"(x)
+        :"r"(dst+width), "r"(src+width), "r"(dc+width/2),
+         "rm"(thresh), "m"(*dithers), "m"(*pw_7f)
+        :"memory"
+    );
+#endif
+}
+
+void ff_gradfun_filter_line_ssse3(uint8_t *dst, uint8_t *src, uint16_t *dc, int width, int thresh, const uint16_t *dithers)
+{
+#if HAVE_SSSE3
+    intptr_t x;
+    if (width & 7) {
+        // could be 10% faster if I somehow eliminated this
+        x = width & ~7;
+        ff_gradfun_filter_line_c(dst + x, src + x, dc + x / 2, width - x, thresh, dithers);
+        width = x;
+    }
+    x = -width;
+    __asm__ volatile(
+        "movd           %4, %%xmm5 \n"
+        "pxor       %%xmm7, %%xmm7 \n"
+        "pshuflw $0,%%xmm5, %%xmm5 \n"
+        "movdqa         %6, %%xmm6 \n"
+        "punpcklqdq %%xmm5, %%xmm5 \n"
+        "movdqa         %5, %%xmm4 \n"
+        "1: \n"
+        "movq      (%2,%0), %%xmm0 \n"
+        "movq      (%3,%0), %%xmm1 \n"
+        "punpcklbw  %%xmm7, %%xmm0 \n"
+        "punpcklwd  %%xmm1, %%xmm1 \n"
+        "psllw          $7, %%xmm0 \n"
+        "psubw      %%xmm0, %%xmm1 \n" // delta = dc - pix
+        "pabsw      %%xmm1, %%xmm2 \n"
+        "pmulhuw    %%xmm5, %%xmm2 \n" // m = abs(delta) * thresh >> 16
+        "psubw      %%xmm6, %%xmm2 \n"
+        "pminsw     %%xmm7, %%xmm2 \n" // m = -max(0, 127-m)
+        "pmullw     %%xmm2, %%xmm2 \n"
+        "psllw          $1, %%xmm2 \n"
+        "paddw      %%xmm4, %%xmm0 \n" // pix += dither
+        "pmulhrsw   %%xmm2, %%xmm1 \n" // m = m*m*delta >> 14
+        "paddw      %%xmm1, %%xmm0 \n" // pix += m
+        "psraw          $7, %%xmm0 \n"
+        "packuswb   %%xmm0, %%xmm0 \n"
+        "movq       %%xmm0, (%1,%0) \n" // dst = clip(pix>>7)
+        "add            $8, %0 \n"
+        "jl 1b \n"
+        :"+&r"(x)
+        :"r"(dst+width), "r"(src+width), "r"(dc+width/2),
+         "rm"(thresh), "m"(*dithers), "m"(*pw_7f)
+        :"memory"
+    );
+#endif // HAVE_SSSE3
+}
+
+void ff_gradfun_blur_line_sse2(uint16_t *dc, uint16_t *buf, uint16_t *buf1, uint8_t *src, int src_linesize, int width)
+{
+#if HAVE_SSE
+#define BLURV(load)\
+    intptr_t x = -2*width;\
+    __asm__ volatile(\
+        "movdqa %6, %%xmm7 \n"\
+        "1: \n"\
+        load"   (%4,%0), %%xmm0 \n"\
+        load"   (%5,%0), %%xmm1 \n"\
+        "movdqa  %%xmm0, %%xmm2 \n"\
+        "movdqa  %%xmm1, %%xmm3 \n"\
+        "psrlw       $8, %%xmm0 \n"\
+        "psrlw       $8, %%xmm1 \n"\
+        "pand    %%xmm7, %%xmm2 \n"\
+        "pand    %%xmm7, %%xmm3 \n"\
+        "paddw   %%xmm1, %%xmm0 \n"\
+        "paddw   %%xmm3, %%xmm2 \n"\
+        "paddw   %%xmm2, %%xmm0 \n"\
+        "paddw  (%2,%0), %%xmm0 \n"\
+        "movdqa (%1,%0), %%xmm1 \n"\
+        "movdqa  %%xmm0, (%1,%0) \n"\
+        "psubw   %%xmm1, %%xmm0 \n"\
+        "movdqa  %%xmm0, (%3,%0) \n"\
+        "add        $16, %0 \n"\
+        "jl 1b \n"\
+        :"+&r"(x)\
+        :"r"(buf+width),\
+         "r"(buf1+width),\
+         "r"(dc+width),\
+         "r"(src+width*2),\
+         "r"(src+width*2+src_linesize),\
+         "m"(*pw_ff)\
+        :"memory"\
+    );
+    if (((intptr_t) src | src_linesize) & 15) {
+        BLURV("movdqu");
+    } else {
+        BLURV("movdqa");
+    }
+#endif // HAVE_SSE
+}
diff --git a/libavfilter/x86/yadif.c b/libavfilter/x86/yadif.c
new file mode 100644
index 0000000..7cd7e19
--- /dev/null
+++ b/libavfilter/x86/yadif.c
@@ -0,0 +1,49 @@
+/*
+ * Copyright (C) 2006 Michael Niedermayer <michaelni at gmx.at>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with Libav; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+
+#include "libavutil/cpu.h"
+#include "libavutil/x86_cpu.h"
+#include "libavcodec/x86/dsputil_mmx.h"
+#include "libavfilter/yadif.h"
+
+DECLARE_ASM_CONST(16, const xmm_reg, pb_1) = {0x0101010101010101ULL, 0x0101010101010101ULL};
+DECLARE_ASM_CONST(16, const xmm_reg, pw_1) = {0x0001000100010001ULL, 0x0001000100010001ULL};
+
+#if HAVE_SSSE3
+#define COMPILE_TEMPLATE_SSE 1
+#define COMPILE_TEMPLATE_SSSE3 1
+#undef RENAME
+#define RENAME(a) a ## _ssse3
+#include "yadif_template.c"
+#undef COMPILE_TEMPLATE_SSSE3
+#endif
+
+#if HAVE_SSE
+#undef RENAME
+#define RENAME(a) a ## _sse2
+#include "yadif_template.c"
+#undef COMPILE_TEMPLATE_SSE
+#endif
+
+#if HAVE_MMX
+#undef RENAME
+#define RENAME(a) a ## _mmx
+#include "yadif_template.c"
+#endif
diff --git a/libavfilter/x86/yadif_template.c b/libavfilter/x86/yadif_template.c
new file mode 100644
index 0000000..962a7c7
--- /dev/null
+++ b/libavfilter/x86/yadif_template.c
@@ -0,0 +1,268 @@
+/*
+ * Copyright (C) 2006 Michael Niedermayer <michaelni at gmx.at>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with Libav; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+
+#ifdef COMPILE_TEMPLATE_SSE
+#define MM "%%xmm"
+#define MOV  "movq"
+#define MOVQ "movdqa"
+#define MOVQU "movdqu"
+#define STEP 8
+#define LOAD(mem,dst) \
+            MOV"       "mem", "dst" \n\t"\
+            "punpcklbw "MM"7, "dst" \n\t"
+#define PSRL1(reg) "psrldq $1, "reg" \n\t"
+#define PSRL2(reg) "psrldq $2, "reg" \n\t"
+#define PSHUF(src,dst) "movdqa "dst", "src" \n\t"\
+                       "psrldq $2, "src"     \n\t"
+#else
+#define MM "%%mm"
+#define MOV  "movd"
+#define MOVQ "movq"
+#define MOVQU "movq"
+#define STEP 4
+#define LOAD(mem,dst) \
+            MOV"       "mem", "dst" \n\t"\
+            "punpcklbw "MM"7, "dst" \n\t"
+#define PSRL1(reg) "psrlq $8, "reg" \n\t"
+#define PSRL2(reg) "psrlq $16, "reg" \n\t"
+#define PSHUF(src,dst) "pshufw $9, "dst", "src" \n\t"
+#endif
+
+#ifdef COMPILE_TEMPLATE_SSSE3
+#define PABS(tmp,dst) \
+            "pabsw     "dst", "dst" \n\t"
+#else
+#define PABS(tmp,dst) \
+            "pxor     "tmp", "tmp" \n\t"\
+            "psubw    "dst", "tmp" \n\t"\
+            "pmaxsw   "tmp", "dst" \n\t"
+#endif
+
+#define CHECK(pj,mj) \
+            MOVQU" "#pj"(%[cur],%[mrefs]), "MM"2 \n\t" /* cur[x-refs-1+j] */\
+            MOVQU" "#mj"(%[cur],%[prefs]), "MM"3 \n\t" /* cur[x+refs-1-j] */\
+            MOVQ"      "MM"2, "MM"4 \n\t"\
+            MOVQ"      "MM"2, "MM"5 \n\t"\
+            "pxor      "MM"3, "MM"4 \n\t"\
+            "pavgb     "MM"3, "MM"5 \n\t"\
+            "pand     "MANGLE(pb_1)", "MM"4 \n\t"\
+            "psubusb   "MM"4, "MM"5 \n\t"\
+            PSRL1(MM"5")                 \
+            "punpcklbw "MM"7, "MM"5 \n\t" /* (cur[x-refs+j] + cur[x+refs-j])>>1 */\
+            MOVQ"      "MM"2, "MM"4 \n\t"\
+            "psubusb   "MM"3, "MM"2 \n\t"\
+            "psubusb   "MM"4, "MM"3 \n\t"\
+            "pmaxub    "MM"3, "MM"2 \n\t"\
+            MOVQ"      "MM"2, "MM"3 \n\t"\
+            MOVQ"      "MM"2, "MM"4 \n\t" /* ABS(cur[x-refs-1+j] - cur[x+refs-1-j]) */\
+            PSRL1(MM"3")                  /* ABS(cur[x-refs  +j] - cur[x+refs  -j]) */\
+            PSRL2(MM"4")                  /* ABS(cur[x-refs+1+j] - cur[x+refs+1-j]) */\
+            "punpcklbw "MM"7, "MM"2 \n\t"\
+            "punpcklbw "MM"7, "MM"3 \n\t"\
+            "punpcklbw "MM"7, "MM"4 \n\t"\
+            "paddw     "MM"3, "MM"2 \n\t"\
+            "paddw     "MM"4, "MM"2 \n\t" /* score */
+
+#define CHECK1 \
+            MOVQ"      "MM"0, "MM"3 \n\t"\
+            "pcmpgtw   "MM"2, "MM"3 \n\t" /* if(score < spatial_score) */\
+            "pminsw    "MM"2, "MM"0 \n\t" /* spatial_score= score; */\
+            MOVQ"      "MM"3, "MM"6 \n\t"\
+            "pand      "MM"3, "MM"5 \n\t"\
+            "pandn     "MM"1, "MM"3 \n\t"\
+            "por       "MM"5, "MM"3 \n\t"\
+            MOVQ"      "MM"3, "MM"1 \n\t" /* spatial_pred= (cur[x-refs+j] + cur[x+refs-j])>>1; */
+
+#define CHECK2 /* pretend not to have checked dir=2 if dir=1 was bad.\
+                  hurts both quality and speed, but matches the C version. */\
+            "paddw    "MANGLE(pw_1)", "MM"6 \n\t"\
+            "psllw     $14,   "MM"6 \n\t"\
+            "paddsw    "MM"6, "MM"2 \n\t"\
+            MOVQ"      "MM"0, "MM"3 \n\t"\
+            "pcmpgtw   "MM"2, "MM"3 \n\t"\
+            "pminsw    "MM"2, "MM"0 \n\t"\
+            "pand      "MM"3, "MM"5 \n\t"\
+            "pandn     "MM"1, "MM"3 \n\t"\
+            "por       "MM"5, "MM"3 \n\t"\
+            MOVQ"      "MM"3, "MM"1 \n\t"
+
+void RENAME(ff_yadif_filter_line)(uint8_t *dst,
+                                  uint8_t *prev, uint8_t *cur, uint8_t *next,
+                                  int w, int prefs, int mrefs, int parity, int mode)
+{
+    DECLARE_ALIGNED(16, uint8_t, tmp0[16]);
+    DECLARE_ALIGNED(16, uint8_t, tmp1[16]);
+    DECLARE_ALIGNED(16, uint8_t, tmp2[16]);
+    DECLARE_ALIGNED(16, uint8_t, tmp3[16]);
+    int x;
+
+#define FILTER\
+    for(x=0; x<w; x+=STEP){\
+        __asm__ volatile(\
+            "pxor      "MM"7, "MM"7 \n\t"\
+            LOAD("(%[cur],%[mrefs])", MM"0") /* c = cur[x-refs] */\
+            LOAD("(%[cur],%[prefs])", MM"1") /* e = cur[x+refs] */\
+            LOAD("(%["prev2"])", MM"2") /* prev2[x] */\
+            LOAD("(%["next2"])", MM"3") /* next2[x] */\
+            MOVQ"      "MM"3, "MM"4 \n\t"\
+            "paddw     "MM"2, "MM"3 \n\t"\
+            "psraw     $1,    "MM"3 \n\t" /* d = (prev2[x] + next2[x])>>1 */\
+            MOVQ"      "MM"0, %[tmp0] \n\t" /* c */\
+            MOVQ"      "MM"3, %[tmp1] \n\t" /* d */\
+            MOVQ"      "MM"1, %[tmp2] \n\t" /* e */\
+            "psubw     "MM"4, "MM"2 \n\t"\
+            PABS(      MM"4", MM"2") /* temporal_diff0 */\
+            LOAD("(%[prev],%[mrefs])", MM"3") /* prev[x-refs] */\
+            LOAD("(%[prev],%[prefs])", MM"4") /* prev[x+refs] */\
+            "psubw     "MM"0, "MM"3 \n\t"\
+            "psubw     "MM"1, "MM"4 \n\t"\
+            PABS(      MM"5", MM"3")\
+            PABS(      MM"5", MM"4")\
+            "paddw     "MM"4, "MM"3 \n\t" /* temporal_diff1 */\
+            "psrlw     $1,    "MM"2 \n\t"\
+            "psrlw     $1,    "MM"3 \n\t"\
+            "pmaxsw    "MM"3, "MM"2 \n\t"\
+            LOAD("(%[next],%[mrefs])", MM"3") /* next[x-refs] */\
+            LOAD("(%[next],%[prefs])", MM"4") /* next[x+refs] */\
+            "psubw     "MM"0, "MM"3 \n\t"\
+            "psubw     "MM"1, "MM"4 \n\t"\
+            PABS(      MM"5", MM"3")\
+            PABS(      MM"5", MM"4")\
+            "paddw     "MM"4, "MM"3 \n\t" /* temporal_diff2 */\
+            "psrlw     $1,    "MM"3 \n\t"\
+            "pmaxsw    "MM"3, "MM"2 \n\t"\
+            MOVQ"      "MM"2, %[tmp3] \n\t" /* diff */\
+\
+            "paddw     "MM"0, "MM"1 \n\t"\
+            "paddw     "MM"0, "MM"0 \n\t"\
+            "psubw     "MM"1, "MM"0 \n\t"\
+            "psrlw     $1,    "MM"1 \n\t" /* spatial_pred */\
+            PABS(      MM"2", MM"0")      /* ABS(c-e) */\
+\
+            MOVQU" -1(%[cur],%[mrefs]), "MM"2 \n\t" /* cur[x-refs-1] */\
+            MOVQU" -1(%[cur],%[prefs]), "MM"3 \n\t" /* cur[x+refs-1] */\
+            MOVQ"      "MM"2, "MM"4 \n\t"\
+            "psubusb   "MM"3, "MM"2 \n\t"\
+            "psubusb   "MM"4, "MM"3 \n\t"\
+            "pmaxub    "MM"3, "MM"2 \n\t"\
+            PSHUF(MM"3", MM"2") \
+            "punpcklbw "MM"7, "MM"2 \n\t" /* ABS(cur[x-refs-1] - cur[x+refs-1]) */\
+            "punpcklbw "MM"7, "MM"3 \n\t" /* ABS(cur[x-refs+1] - cur[x+refs+1]) */\
+            "paddw     "MM"2, "MM"0 \n\t"\
+            "paddw     "MM"3, "MM"0 \n\t"\
+            "psubw    "MANGLE(pw_1)", "MM"0 \n\t" /* spatial_score */\
+\
+            CHECK(-2,0)\
+            CHECK1\
+            CHECK(-3,1)\
+            CHECK2\
+            CHECK(0,-2)\
+            CHECK1\
+            CHECK(1,-3)\
+            CHECK2\
+\
+            /* if(p->mode<2) ... */\
+            MOVQ"    %[tmp3], "MM"6 \n\t" /* diff */\
+            "cmpl      $2, %[mode] \n\t"\
+            "jge       1f \n\t"\
+            LOAD("(%["prev2"],%[mrefs],2)", MM"2") /* prev2[x-2*refs] */\
+            LOAD("(%["next2"],%[mrefs],2)", MM"4") /* next2[x-2*refs] */\
+            LOAD("(%["prev2"],%[prefs],2)", MM"3") /* prev2[x+2*refs] */\
+            LOAD("(%["next2"],%[prefs],2)", MM"5") /* next2[x+2*refs] */\
+            "paddw     "MM"4, "MM"2 \n\t"\
+            "paddw     "MM"5, "MM"3 \n\t"\
+            "psrlw     $1,    "MM"2 \n\t" /* b */\
+            "psrlw     $1,    "MM"3 \n\t" /* f */\
+            MOVQ"    %[tmp0], "MM"4 \n\t" /* c */\
+            MOVQ"    %[tmp1], "MM"5 \n\t" /* d */\
+            MOVQ"    %[tmp2], "MM"7 \n\t" /* e */\
+            "psubw     "MM"4, "MM"2 \n\t" /* b-c */\
+            "psubw     "MM"7, "MM"3 \n\t" /* f-e */\
+            MOVQ"      "MM"5, "MM"0 \n\t"\
+            "psubw     "MM"4, "MM"5 \n\t" /* d-c */\
+            "psubw     "MM"7, "MM"0 \n\t" /* d-e */\
+            MOVQ"      "MM"2, "MM"4 \n\t"\
+            "pminsw    "MM"3, "MM"2 \n\t"\
+            "pmaxsw    "MM"4, "MM"3 \n\t"\
+            "pmaxsw    "MM"5, "MM"2 \n\t"\
+            "pminsw    "MM"5, "MM"3 \n\t"\
+            "pmaxsw    "MM"0, "MM"2 \n\t" /* max */\
+            "pminsw    "MM"0, "MM"3 \n\t" /* min */\
+            "pxor      "MM"4, "MM"4 \n\t"\
+            "pmaxsw    "MM"3, "MM"6 \n\t"\
+            "psubw     "MM"2, "MM"4 \n\t" /* -max */\
+            "pmaxsw    "MM"4, "MM"6 \n\t" /* diff= MAX3(diff, min, -max); */\
+            "1: \n\t"\
+\
+            MOVQ"    %[tmp1], "MM"2 \n\t" /* d */\
+            MOVQ"      "MM"2, "MM"3 \n\t"\
+            "psubw     "MM"6, "MM"2 \n\t" /* d-diff */\
+            "paddw     "MM"6, "MM"3 \n\t" /* d+diff */\
+            "pmaxsw    "MM"2, "MM"1 \n\t"\
+            "pminsw    "MM"3, "MM"1 \n\t" /* d = clip(spatial_pred, d-diff, d+diff); */\
+            "packuswb  "MM"1, "MM"1 \n\t"\
+\
+            :[tmp0]"=m"(tmp0),\
+             [tmp1]"=m"(tmp1),\
+             [tmp2]"=m"(tmp2),\
+             [tmp3]"=m"(tmp3)\
+            :[prev] "r"(prev),\
+             [cur]  "r"(cur),\
+             [next] "r"(next),\
+             [prefs]"r"((x86_reg)prefs),\
+             [mrefs]"r"((x86_reg)mrefs),\
+             [mode] "g"(mode)\
+        );\
+        __asm__ volatile(MOV" "MM"1, %0" :"=m"(*dst));\
+        dst += STEP;\
+        prev+= STEP;\
+        cur += STEP;\
+        next+= STEP;\
+    }
+
+    if (parity) {
+#define prev2 "prev"
+#define next2 "cur"
+        FILTER
+#undef prev2
+#undef next2
+    } else {
+#define prev2 "cur"
+#define next2 "next"
+        FILTER
+#undef prev2
+#undef next2
+    }
+}
+#undef STEP
+#undef MM
+#undef MOV
+#undef MOVQ
+#undef MOVQU
+#undef PSHUF
+#undef PSRL1
+#undef PSRL2
+#undef LOAD
+#undef PABS
+#undef CHECK
+#undef CHECK1
+#undef CHECK2
+#undef FILTER
+
diff --git a/libavfilter/yadif.h b/libavfilter/yadif.h
new file mode 100644
index 0000000..d658b68
--- /dev/null
+++ b/libavfilter/yadif.h
@@ -0,0 +1,36 @@
+/*
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with Libav; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+
+#ifndef AVFILTER_YADIF_H
+#define AVFILTER_YADIF_H
+
+#include "avfilter.h"
+
+void ff_yadif_filter_line_mmx(uint8_t *dst,
+                              uint8_t *prev, uint8_t *cur, uint8_t *next,
+                              int w, int prefs, int mrefs, int parity, int mode);
+
+void ff_yadif_filter_line_sse2(uint8_t *dst,
+                               uint8_t *prev, uint8_t *cur, uint8_t *next,
+                               int w, int prefs, int mrefs, int parity, int mode);
+
+void ff_yadif_filter_line_ssse3(uint8_t *dst,
+                                uint8_t *prev, uint8_t *cur, uint8_t *next,
+                                int w, int prefs, int mrefs, int parity, int mode);
+
+#endif /* AVFILTER_YADIF_H */
diff --git a/libavformat/4xm.c b/libavformat/4xm.c
index a697f8d..ff0baae 100644
--- a/libavformat/4xm.c
+++ b/libavformat/4xm.c
@@ -2,20 +2,20 @@
  * 4X Technologies .4xm File Demuxer (no muxer)
  * Copyright (c) 2003  The ffmpeg Project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -54,11 +54,11 @@
 #define strk_SIZE 0x28
 
 #define GET_LIST_HEADER() \
-    fourcc_tag = get_le32(pb); \
-    size = get_le32(pb); \
+    fourcc_tag = avio_rl32(pb); \
+    size = avio_rl32(pb); \
     if (fourcc_tag != LIST_TAG) \
         return AVERROR_INVALIDDATA; \
-    fourcc_tag = get_le32(pb);
+    fourcc_tag = avio_rl32(pb);
 
 typedef struct AudioTrack {
     int sample_rate;
@@ -92,7 +92,7 @@ static int fourxm_probe(AVProbeData *p)
 static int fourxm_read_header(AVFormatContext *s,
                               AVFormatParameters *ap)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     unsigned int fourcc_tag;
     unsigned int size;
     int header_size;
@@ -106,7 +106,7 @@ static int fourxm_read_header(AVFormatContext *s,
     fourxm->fps = 1.0;
 
     /* skip the first 3 32-bit numbers */
-    url_fseek(pb, 12, SEEK_CUR);
+    avio_skip(pb, 12);
 
     /* check for LIST-HEAD */
     GET_LIST_HEADER();
@@ -118,7 +118,7 @@ static int fourxm_read_header(AVFormatContext *s,
     header = av_malloc(header_size);
     if (!header)
         return AVERROR(ENOMEM);
-    if (get_buffer(pb, header, header_size) != header_size){
+    if (avio_read(pb, header, header_size) != header_size){
         av_free(header);
         return AVERROR(EIO);
     }
@@ -185,6 +185,13 @@ static int fourxm_read_header(AVFormatContext *s,
             fourxm->tracks[current_track].sample_rate = AV_RL32(&header[i + 40]);
             fourxm->tracks[current_track].bits        = AV_RL32(&header[i + 44]);
             fourxm->tracks[current_track].audio_pts   = 0;
+            if(   fourxm->tracks[current_track].channels    <= 0
+               || fourxm->tracks[current_track].sample_rate <= 0
+               || fourxm->tracks[current_track].bits        <  0){
+                av_log(s, AV_LOG_ERROR, "audio header invalid\n");
+                ret= -1;
+                goto fail;
+            }
             i += 8 + size;
 
             /* allocate a new AVStream */
@@ -237,7 +244,7 @@ static int fourxm_read_packet(AVFormatContext *s,
                               AVPacket *pkt)
 {
     FourxmDemuxContext *fourxm = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     unsigned int fourcc_tag;
     unsigned int size, out_size;
     int ret = 0;
@@ -248,11 +255,11 @@ static int fourxm_read_packet(AVFormatContext *s,
 
     while (!packet_read) {
 
-        if ((ret = get_buffer(s->pb, header, 8)) < 0)
+        if ((ret = avio_read(s->pb, header, 8)) < 0)
             return ret;
         fourcc_tag = AV_RL32(&header[0]);
         size = AV_RL32(&header[4]);
-        if (url_feof(pb))
+        if (pb->eof_reached)
             return AVERROR(EIO);
         switch (fourcc_tag) {
 
@@ -261,7 +268,7 @@ static int fourxm_read_packet(AVFormatContext *s,
             fourxm->video_pts ++;
 
             /* skip the LIST-* tag and move on to the next fourcc */
-            get_le32(pb);
+            avio_rl32(pb);
             break;
 
         case ifrm_TAG:
@@ -276,9 +283,9 @@ static int fourxm_read_packet(AVFormatContext *s,
                 return AVERROR(EIO);
             pkt->stream_index = fourxm->video_stream_index;
             pkt->pts = fourxm->video_pts;
-            pkt->pos = url_ftell(s->pb);
+            pkt->pos = avio_tell(s->pb);
             memcpy(pkt->data, header, 8);
-            ret = get_buffer(s->pb, &pkt->data[8], size);
+            ret = avio_read(s->pb, &pkt->data[8], size);
 
             if (ret < 0){
                 av_free_packet(pkt);
@@ -287,11 +294,11 @@ static int fourxm_read_packet(AVFormatContext *s,
             break;
 
         case snd__TAG:
-            track_number = get_le32(pb);
-            out_size= get_le32(pb);
+            track_number = avio_rl32(pb);
+            out_size= avio_rl32(pb);
             size-=8;
 
-            if (track_number < fourxm->track_count) {
+            if (track_number < fourxm->track_count && fourxm->tracks[track_number].channels>0) {
                 ret= av_get_packet(s->pb, pkt, size);
                 if(ret<0)
                     return AVERROR(EIO);
@@ -315,12 +322,12 @@ static int fourxm_read_packet(AVFormatContext *s,
                 fourxm->tracks[track_number].audio_pts += audio_frame_count;
 
             } else {
-                url_fseek(pb, size, SEEK_CUR);
+                avio_skip(pb, size);
             }
             break;
 
         default:
-            url_fseek(pb, size, SEEK_CUR);
+            avio_skip(pb, size);
             break;
         }
     }
@@ -336,7 +343,7 @@ static int fourxm_read_close(AVFormatContext *s)
     return 0;
 }
 
-AVInputFormat fourxm_demuxer = {
+AVInputFormat ff_fourxm_demuxer = {
     "4xm",
     NULL_IF_CONFIG_SMALL("4X Technologies format"),
     sizeof(FourxmDemuxContext),
diff --git a/libavformat/Makefile b/libavformat/Makefile
index 7a2d00f..0bf2633 100644
--- a/libavformat/Makefile
+++ b/libavformat/Makefile
@@ -3,10 +3,12 @@ include $(SUBDIR)../config.mak
 NAME = avformat
 FFLIBS = avcodec avutil
 
-HEADERS = avformat.h avio.h
+HEADERS = avformat.h avio.h version.h
 
 OBJS = allformats.o         \
        cutils.o             \
+       id3v1.o              \
+       id3v2.o              \
        metadata.o           \
        metadata_compat.o    \
        options.o            \
@@ -16,24 +18,26 @@ OBJS = allformats.o         \
        utils.o              \
 
 # muxers/demuxers
-OBJS-$(CONFIG_AAC_DEMUXER)               += raw.o id3v1.o id3v2.o
-OBJS-$(CONFIG_AC3_DEMUXER)               += raw.o
-OBJS-$(CONFIG_AC3_MUXER)                 += raw.o
+OBJS-$(CONFIG_A64_MUXER)                 += a64.o
+OBJS-$(CONFIG_AAC_DEMUXER)               += aacdec.o rawdec.o
+OBJS-$(CONFIG_AC3_DEMUXER)               += ac3dec.o rawdec.o
+OBJS-$(CONFIG_AC3_MUXER)                 += rawenc.o
 OBJS-$(CONFIG_ADTS_MUXER)                += adtsenc.o
-OBJS-$(CONFIG_AEA_DEMUXER)               += aea.o raw.o
-OBJS-$(CONFIG_AIFF_DEMUXER)              += aiffdec.o riff.o raw.o
+OBJS-$(CONFIG_AEA_DEMUXER)               += aea.o pcm.o
+OBJS-$(CONFIG_AIFF_DEMUXER)              += aiffdec.o riff.o pcm.o
 OBJS-$(CONFIG_AIFF_MUXER)                += aiffenc.o riff.o
 OBJS-$(CONFIG_AMR_DEMUXER)               += amr.o
 OBJS-$(CONFIG_AMR_MUXER)                 += amr.o
 OBJS-$(CONFIG_ANM_DEMUXER)               += anm.o
 OBJS-$(CONFIG_APC_DEMUXER)               += apc.o
 OBJS-$(CONFIG_APE_DEMUXER)               += ape.o apetag.o
+OBJS-$(CONFIG_APPLEHTTP_DEMUXER)         += applehttp.o
 OBJS-$(CONFIG_ASF_DEMUXER)               += asfdec.o asf.o asfcrypt.o \
                                             riff.o avlanguage.o
 OBJS-$(CONFIG_ASF_MUXER)                 += asfenc.o asf.o riff.o
 OBJS-$(CONFIG_ASS_DEMUXER)               += assdec.o
 OBJS-$(CONFIG_ASS_MUXER)                 += assenc.o
-OBJS-$(CONFIG_AU_DEMUXER)                += au.o raw.o
+OBJS-$(CONFIG_AU_DEMUXER)                += au.o pcm.o
 OBJS-$(CONFIG_AU_MUXER)                  += au.o
 OBJS-$(CONFIG_AVI_DEMUXER)               += avidec.o riff.o avi.o
 OBJS-$(CONFIG_AVI_MUXER)                 += avienc.o riff.o avi.o
@@ -45,31 +49,35 @@ OBJS-$(CONFIG_BFI_DEMUXER)               += bfi.o
 OBJS-$(CONFIG_BINK_DEMUXER)              += bink.o
 OBJS-$(CONFIG_C93_DEMUXER)               += c93.o vocdec.o voc.o
 OBJS-$(CONFIG_CAF_DEMUXER)               += cafdec.o caf.o mov.o riff.o isom.o
-OBJS-$(CONFIG_CAVSVIDEO_DEMUXER)         += raw.o
+OBJS-$(CONFIG_CAVSVIDEO_DEMUXER)         += cavsvideodec.o rawdec.o
+OBJS-$(CONFIG_CAVSVIDEO_MUXER)           += rawenc.o
 OBJS-$(CONFIG_CDG_DEMUXER)               += cdg.o
 OBJS-$(CONFIG_CRC_MUXER)                 += crcenc.o
 OBJS-$(CONFIG_DAUD_DEMUXER)              += daud.o
 OBJS-$(CONFIG_DAUD_MUXER)                += daud.o
-OBJS-$(CONFIG_DIRAC_DEMUXER)             += raw.o
-OBJS-$(CONFIG_DIRAC_MUXER)               += raw.o
-OBJS-$(CONFIG_DNXHD_DEMUXER)             += raw.o
-OBJS-$(CONFIG_DNXHD_MUXER)               += raw.o
+OBJS-$(CONFIG_DFA_DEMUXER)               += dfa.o
+OBJS-$(CONFIG_DIRAC_DEMUXER)             += diracdec.o rawdec.o
+OBJS-$(CONFIG_DIRAC_MUXER)               += rawenc.o
+OBJS-$(CONFIG_DNXHD_DEMUXER)             += dnxhddec.o rawdec.o
+OBJS-$(CONFIG_DNXHD_MUXER)               += rawenc.o
 OBJS-$(CONFIG_DSICIN_DEMUXER)            += dsicin.o
-OBJS-$(CONFIG_DTS_DEMUXER)               += raw.o id3v2.o
-OBJS-$(CONFIG_DTS_MUXER)                 += raw.o
+OBJS-$(CONFIG_DTS_DEMUXER)               += dtsdec.o rawdec.o
+OBJS-$(CONFIG_DTS_MUXER)                 += rawenc.o
 OBJS-$(CONFIG_DV_DEMUXER)                += dv.o
 OBJS-$(CONFIG_DV_MUXER)                  += dvenc.o
 OBJS-$(CONFIG_DXA_DEMUXER)               += dxa.o riff.o
 OBJS-$(CONFIG_EA_CDATA_DEMUXER)          += eacdata.o
 OBJS-$(CONFIG_EA_DEMUXER)                += electronicarts.o
-OBJS-$(CONFIG_EAC3_DEMUXER)              += raw.o id3v2.o
-OBJS-$(CONFIG_EAC3_MUXER)                += raw.o
+OBJS-$(CONFIG_EAC3_DEMUXER)              += ac3dec.o rawdec.o
+OBJS-$(CONFIG_EAC3_MUXER)                += rawenc.o
 OBJS-$(CONFIG_FFM_DEMUXER)               += ffmdec.o
 OBJS-$(CONFIG_FFM_MUXER)                 += ffmenc.o
+OBJS-$(CONFIG_FFMETADATA_DEMUXER)        += ffmetadec.o
+OBJS-$(CONFIG_FFMETADATA_MUXER)          += ffmetaenc.o
 OBJS-$(CONFIG_FILMSTRIP_DEMUXER)         += filmstripdec.o
 OBJS-$(CONFIG_FILMSTRIP_MUXER)           += filmstripenc.o
-OBJS-$(CONFIG_FLAC_DEMUXER)              += flacdec.o raw.o id3v1.o \
-                                            id3v2.o oggparsevorbis.o \
+OBJS-$(CONFIG_FLAC_DEMUXER)              += flacdec.o rawdec.o \
+                                            oggparsevorbis.o \
                                             vorbiscomment.o
 OBJS-$(CONFIG_FLAC_MUXER)                += flacenc.o flacenc_header.o \
                                             vorbiscomment.o
@@ -78,68 +86,78 @@ OBJS-$(CONFIG_FLV_DEMUXER)               += flvdec.o
 OBJS-$(CONFIG_FLV_MUXER)                 += flvenc.o avc.o
 OBJS-$(CONFIG_FOURXM_DEMUXER)            += 4xm.o
 OBJS-$(CONFIG_FRAMECRC_MUXER)            += framecrcenc.o
+OBJS-$(CONFIG_FRAMEMD5_MUXER)            += md5enc.o
 OBJS-$(CONFIG_GIF_MUXER)                 += gif.o
-OBJS-$(CONFIG_GSM_DEMUXER)               += raw.o id3v2.o
+OBJS-$(CONFIG_GSM_DEMUXER)               += rawdec.o
 OBJS-$(CONFIG_GXF_DEMUXER)               += gxf.o
 OBJS-$(CONFIG_GXF_MUXER)                 += gxfenc.o audiointerleave.o
-OBJS-$(CONFIG_H261_DEMUXER)              += raw.o
-OBJS-$(CONFIG_H261_MUXER)                += raw.o
-OBJS-$(CONFIG_H263_DEMUXER)              += raw.o
-OBJS-$(CONFIG_H263_MUXER)                += raw.o
-OBJS-$(CONFIG_H264_DEMUXER)              += raw.o
-OBJS-$(CONFIG_H264_MUXER)                += raw.o
+OBJS-$(CONFIG_G722_DEMUXER)              += rawdec.o
+OBJS-$(CONFIG_G722_MUXER)                += rawenc.o
+OBJS-$(CONFIG_H261_DEMUXER)              += h261dec.o rawdec.o
+OBJS-$(CONFIG_H261_MUXER)                += rawenc.o
+OBJS-$(CONFIG_H263_DEMUXER)              += h263dec.o rawdec.o
+OBJS-$(CONFIG_H263_MUXER)                += rawenc.o
+OBJS-$(CONFIG_H264_DEMUXER)              += h264dec.o rawdec.o
+OBJS-$(CONFIG_H264_MUXER)                += rawenc.o
 OBJS-$(CONFIG_IDCIN_DEMUXER)             += idcin.o
 OBJS-$(CONFIG_IFF_DEMUXER)               += iff.o
 OBJS-$(CONFIG_IMAGE2_DEMUXER)            += img2.o
 OBJS-$(CONFIG_IMAGE2_MUXER)              += img2.o
 OBJS-$(CONFIG_IMAGE2PIPE_DEMUXER)        += img2.o
 OBJS-$(CONFIG_IMAGE2PIPE_MUXER)          += img2.o
-OBJS-$(CONFIG_INGENIENT_DEMUXER)         += raw.o
+OBJS-$(CONFIG_INGENIENT_DEMUXER)         += ingenientdec.o rawdec.o
 OBJS-$(CONFIG_IPMOVIE_DEMUXER)           += ipmovie.o
 OBJS-$(CONFIG_ISS_DEMUXER)               += iss.o
 OBJS-$(CONFIG_IV8_DEMUXER)               += iv8.o
+OBJS-$(CONFIG_IVF_DEMUXER)               += ivfdec.o riff.o
+OBJS-$(CONFIG_IVF_MUXER)                 += ivfenc.o
+OBJS-$(CONFIG_JV_DEMUXER)                += jvdec.o
 OBJS-$(CONFIG_LMLM4_DEMUXER)             += lmlm4.o
-OBJS-$(CONFIG_M4V_DEMUXER)               += raw.o
-OBJS-$(CONFIG_M4V_MUXER)                 += raw.o
+OBJS-$(CONFIG_LXF_DEMUXER)               += lxfdec.o
+OBJS-$(CONFIG_M4V_DEMUXER)               += m4vdec.o rawdec.o
+OBJS-$(CONFIG_M4V_MUXER)                 += rawenc.o
 OBJS-$(CONFIG_MATROSKA_DEMUXER)          += matroskadec.o matroska.o \
                                             riff.o isom.o rmdec.o rm.o
 OBJS-$(CONFIG_MATROSKA_MUXER)            += matroskaenc.o matroska.o \
                                             riff.o isom.o avc.o \
-                                            flacenc_header.o
-OBJS-$(CONFIG_MJPEG_DEMUXER)             += raw.o
-OBJS-$(CONFIG_MJPEG_MUXER)               += raw.o
-OBJS-$(CONFIG_MLP_DEMUXER)               += raw.o id3v2.o
-OBJS-$(CONFIG_MLP_MUXER)                 += raw.o
+                                            flacenc_header.o avlanguage.o
+OBJS-$(CONFIG_MD5_MUXER)                 += md5enc.o
+OBJS-$(CONFIG_MJPEG_DEMUXER)             += rawdec.o
+OBJS-$(CONFIG_MJPEG_MUXER)               += rawenc.o
+OBJS-$(CONFIG_MLP_DEMUXER)               += rawdec.o
+OBJS-$(CONFIG_MLP_MUXER)                 += rawenc.o
 OBJS-$(CONFIG_MM_DEMUXER)                += mm.o
-OBJS-$(CONFIG_MMF_DEMUXER)               += mmf.o raw.o
+OBJS-$(CONFIG_MMF_DEMUXER)               += mmf.o pcm.o
 OBJS-$(CONFIG_MMF_MUXER)                 += mmf.o riff.o
 OBJS-$(CONFIG_MOV_DEMUXER)               += mov.o riff.o isom.o
-OBJS-$(CONFIG_MOV_MUXER)                 += movenc.o riff.o isom.o avc.o movenchint.o
-OBJS-$(CONFIG_MP2_MUXER)                 += mp3.o id3v1.o
-OBJS-$(CONFIG_MP3_DEMUXER)               += mp3.o id3v1.o id3v2.o
-OBJS-$(CONFIG_MP3_MUXER)                 += mp3.o id3v1.o id3v2.o
-OBJS-$(CONFIG_MPC_DEMUXER)               += mpc.o id3v1.o id3v2.o apetag.o
+OBJS-$(CONFIG_MOV_MUXER)                 += movenc.o riff.o isom.o avc.o \
+                                            movenchint.o rtpenc_chain.o
+OBJS-$(CONFIG_MP2_MUXER)                 += mp3enc.o rawenc.o
+OBJS-$(CONFIG_MP3_DEMUXER)               += mp3dec.o
+OBJS-$(CONFIG_MP3_MUXER)                 += mp3enc.o rawenc.o
+OBJS-$(CONFIG_MPC_DEMUXER)               += mpc.o apetag.o
 OBJS-$(CONFIG_MPC8_DEMUXER)              += mpc8.o
 OBJS-$(CONFIG_MPEG1SYSTEM_MUXER)         += mpegenc.o
 OBJS-$(CONFIG_MPEG1VCD_MUXER)            += mpegenc.o
 OBJS-$(CONFIG_MPEG2DVD_MUXER)            += mpegenc.o
 OBJS-$(CONFIG_MPEG2VOB_MUXER)            += mpegenc.o
 OBJS-$(CONFIG_MPEG2SVCD_MUXER)           += mpegenc.o
-OBJS-$(CONFIG_MPEG1VIDEO_MUXER)          += raw.o
-OBJS-$(CONFIG_MPEG2VIDEO_MUXER)          += raw.o
+OBJS-$(CONFIG_MPEG1VIDEO_MUXER)          += rawenc.o
+OBJS-$(CONFIG_MPEG2VIDEO_MUXER)          += rawenc.o
 OBJS-$(CONFIG_MPEGPS_DEMUXER)            += mpeg.o
-OBJS-$(CONFIG_MPEGTS_DEMUXER)            += mpegts.o
+OBJS-$(CONFIG_MPEGTS_DEMUXER)            += mpegts.o isom.o
 OBJS-$(CONFIG_MPEGTS_MUXER)              += mpegtsenc.o adtsenc.o
-OBJS-$(CONFIG_MPEGVIDEO_DEMUXER)         += raw.o
+OBJS-$(CONFIG_MPEGVIDEO_DEMUXER)         += mpegvideodec.o rawdec.o
 OBJS-$(CONFIG_MPJPEG_MUXER)              += mpjpeg.o
 OBJS-$(CONFIG_MSNWC_TCP_DEMUXER)         += msnwc_tcp.o
 OBJS-$(CONFIG_MTV_DEMUXER)               += mtv.o
 OBJS-$(CONFIG_MVI_DEMUXER)               += mvi.o
 OBJS-$(CONFIG_MXF_DEMUXER)               += mxfdec.o mxf.o
 OBJS-$(CONFIG_MXF_MUXER)                 += mxfenc.o mxf.o audiointerleave.o
+OBJS-$(CONFIG_MXG_DEMUXER)               += mxg.o
 OBJS-$(CONFIG_NC_DEMUXER)                += ncdec.o
 OBJS-$(CONFIG_NSV_DEMUXER)               += nsvdec.o
-OBJS-$(CONFIG_NULL_MUXER)                += raw.o
+OBJS-$(CONFIG_NULL_MUXER)                += nullenc.o
 OBJS-$(CONFIG_NUT_DEMUXER)               += nutdec.o nut.o riff.o
 OBJS-$(CONFIG_NUT_MUXER)                 += nutenc.o nut.o riff.o
 OBJS-$(CONFIG_NUV_DEMUXER)               += nuv.o riff.o
@@ -155,57 +173,59 @@ OBJS-$(CONFIG_OGG_DEMUXER)               += oggdec.o         \
                                             vorbiscomment.o
 OBJS-$(CONFIG_OGG_MUXER)                 += oggenc.o \
                                             vorbiscomment.o
-OBJS-$(CONFIG_OMA_DEMUXER)               += oma.o raw.o
-OBJS-$(CONFIG_PCM_ALAW_DEMUXER)          += raw.o
-OBJS-$(CONFIG_PCM_ALAW_MUXER)            += raw.o
-OBJS-$(CONFIG_PCM_F32BE_DEMUXER)         += raw.o
-OBJS-$(CONFIG_PCM_F32BE_MUXER)           += raw.o
-OBJS-$(CONFIG_PCM_F32LE_DEMUXER)         += raw.o
-OBJS-$(CONFIG_PCM_F32LE_MUXER)           += raw.o
-OBJS-$(CONFIG_PCM_F64BE_DEMUXER)         += raw.o
-OBJS-$(CONFIG_PCM_F64BE_MUXER)           += raw.o
-OBJS-$(CONFIG_PCM_F64LE_DEMUXER)         += raw.o
-OBJS-$(CONFIG_PCM_F64LE_MUXER)           += raw.o
-OBJS-$(CONFIG_PCM_MULAW_DEMUXER)         += raw.o
-OBJS-$(CONFIG_PCM_MULAW_MUXER)           += raw.o
-OBJS-$(CONFIG_PCM_S16BE_DEMUXER)         += raw.o
-OBJS-$(CONFIG_PCM_S16BE_MUXER)           += raw.o
-OBJS-$(CONFIG_PCM_S16LE_DEMUXER)         += raw.o
-OBJS-$(CONFIG_PCM_S16LE_MUXER)           += raw.o
-OBJS-$(CONFIG_PCM_S24BE_DEMUXER)         += raw.o
-OBJS-$(CONFIG_PCM_S24BE_MUXER)           += raw.o
-OBJS-$(CONFIG_PCM_S24LE_DEMUXER)         += raw.o
-OBJS-$(CONFIG_PCM_S24LE_MUXER)           += raw.o
-OBJS-$(CONFIG_PCM_S32BE_DEMUXER)         += raw.o
-OBJS-$(CONFIG_PCM_S32BE_MUXER)           += raw.o
-OBJS-$(CONFIG_PCM_S32LE_DEMUXER)         += raw.o
-OBJS-$(CONFIG_PCM_S32LE_MUXER)           += raw.o
-OBJS-$(CONFIG_PCM_S8_DEMUXER)            += raw.o
-OBJS-$(CONFIG_PCM_S8_MUXER)              += raw.o
-OBJS-$(CONFIG_PCM_U16BE_DEMUXER)         += raw.o
-OBJS-$(CONFIG_PCM_U16BE_MUXER)           += raw.o
-OBJS-$(CONFIG_PCM_U16LE_DEMUXER)         += raw.o
-OBJS-$(CONFIG_PCM_U16LE_MUXER)           += raw.o
-OBJS-$(CONFIG_PCM_U24BE_DEMUXER)         += raw.o
-OBJS-$(CONFIG_PCM_U24BE_MUXER)           += raw.o
-OBJS-$(CONFIG_PCM_U24LE_DEMUXER)         += raw.o
-OBJS-$(CONFIG_PCM_U24LE_MUXER)           += raw.o
-OBJS-$(CONFIG_PCM_U32BE_DEMUXER)         += raw.o
-OBJS-$(CONFIG_PCM_U32BE_MUXER)           += raw.o
-OBJS-$(CONFIG_PCM_U32LE_DEMUXER)         += raw.o
-OBJS-$(CONFIG_PCM_U32LE_MUXER)           += raw.o
-OBJS-$(CONFIG_PCM_U8_DEMUXER)            += raw.o
-OBJS-$(CONFIG_PCM_U8_MUXER)              += raw.o
+OBJS-$(CONFIG_OMA_DEMUXER)               += oma.o pcm.o
+OBJS-$(CONFIG_PCM_ALAW_DEMUXER)          += pcmdec.o pcm.o rawdec.o
+OBJS-$(CONFIG_PCM_ALAW_MUXER)            += pcmenc.o rawenc.o
+OBJS-$(CONFIG_PCM_F32BE_DEMUXER)         += pcmdec.o pcm.o rawdec.o
+OBJS-$(CONFIG_PCM_F32BE_MUXER)           += pcmenc.o rawenc.o
+OBJS-$(CONFIG_PCM_F32LE_DEMUXER)         += pcmdec.o pcm.o rawdec.o
+OBJS-$(CONFIG_PCM_F32LE_MUXER)           += pcmenc.o rawenc.o
+OBJS-$(CONFIG_PCM_F64BE_DEMUXER)         += pcmdec.o pcm.o rawdec.o
+OBJS-$(CONFIG_PCM_F64BE_MUXER)           += pcmenc.o rawenc.o
+OBJS-$(CONFIG_PCM_F64LE_DEMUXER)         += pcmdec.o pcm.o rawdec.o
+OBJS-$(CONFIG_PCM_F64LE_MUXER)           += pcmenc.o rawenc.o
+OBJS-$(CONFIG_PCM_MULAW_DEMUXER)         += pcmdec.o pcm.o rawdec.o
+OBJS-$(CONFIG_PCM_MULAW_MUXER)           += pcmenc.o rawenc.o
+OBJS-$(CONFIG_PCM_S16BE_DEMUXER)         += pcmdec.o pcm.o rawdec.o
+OBJS-$(CONFIG_PCM_S16BE_MUXER)           += pcmenc.o rawenc.o
+OBJS-$(CONFIG_PCM_S16LE_DEMUXER)         += pcmdec.o pcm.o rawdec.o
+OBJS-$(CONFIG_PCM_S16LE_MUXER)           += pcmenc.o rawenc.o
+OBJS-$(CONFIG_PCM_S24BE_DEMUXER)         += pcmdec.o pcm.o rawdec.o
+OBJS-$(CONFIG_PCM_S24BE_MUXER)           += pcmenc.o rawenc.o
+OBJS-$(CONFIG_PCM_S24LE_DEMUXER)         += pcmdec.o pcm.o rawdec.o
+OBJS-$(CONFIG_PCM_S24LE_MUXER)           += pcmenc.o rawenc.o
+OBJS-$(CONFIG_PCM_S32BE_DEMUXER)         += pcmdec.o pcm.o rawdec.o
+OBJS-$(CONFIG_PCM_S32BE_MUXER)           += pcmenc.o rawenc.o
+OBJS-$(CONFIG_PCM_S32LE_DEMUXER)         += pcmdec.o pcm.o rawdec.o
+OBJS-$(CONFIG_PCM_S32LE_MUXER)           += pcmenc.o rawenc.o
+OBJS-$(CONFIG_PCM_S8_DEMUXER)            += pcmdec.o pcm.o rawdec.o
+OBJS-$(CONFIG_PCM_S8_MUXER)              += pcmenc.o rawenc.o
+OBJS-$(CONFIG_PCM_U16BE_DEMUXER)         += pcmdec.o pcm.o rawdec.o
+OBJS-$(CONFIG_PCM_U16BE_MUXER)           += pcmenc.o rawenc.o
+OBJS-$(CONFIG_PCM_U16LE_DEMUXER)         += pcmdec.o pcm.o rawdec.o
+OBJS-$(CONFIG_PCM_U16LE_MUXER)           += pcmenc.o rawenc.o
+OBJS-$(CONFIG_PCM_U24BE_DEMUXER)         += pcmdec.o pcm.o rawdec.o
+OBJS-$(CONFIG_PCM_U24BE_MUXER)           += pcmenc.o rawenc.o
+OBJS-$(CONFIG_PCM_U24LE_DEMUXER)         += pcmdec.o pcm.o rawdec.o
+OBJS-$(CONFIG_PCM_U24LE_MUXER)           += pcmenc.o rawenc.o
+OBJS-$(CONFIG_PCM_U32BE_DEMUXER)         += pcmdec.o pcm.o rawdec.o
+OBJS-$(CONFIG_PCM_U32BE_MUXER)           += pcmenc.o rawenc.o
+OBJS-$(CONFIG_PCM_U32LE_DEMUXER)         += pcmdec.o pcm.o rawdec.o
+OBJS-$(CONFIG_PCM_U32LE_MUXER)           += pcmenc.o rawenc.o
+OBJS-$(CONFIG_PCM_U8_DEMUXER)            += pcmdec.o pcm.o rawdec.o
+OBJS-$(CONFIG_PCM_U8_MUXER)              += pcmenc.o rawenc.o
 OBJS-$(CONFIG_PVA_DEMUXER)               += pva.o
 OBJS-$(CONFIG_QCP_DEMUXER)               += qcp.o
 OBJS-$(CONFIG_R3D_DEMUXER)               += r3d.o
-OBJS-$(CONFIG_RAWVIDEO_DEMUXER)          += raw.o
-OBJS-$(CONFIG_RAWVIDEO_MUXER)            += raw.o
+OBJS-$(CONFIG_RAWVIDEO_DEMUXER)          += rawvideodec.o rawdec.o
+OBJS-$(CONFIG_RAWVIDEO_MUXER)            += rawenc.o
 OBJS-$(CONFIG_RL2_DEMUXER)               += rl2.o
 OBJS-$(CONFIG_RM_DEMUXER)                += rmdec.o rm.o
 OBJS-$(CONFIG_RM_MUXER)                  += rmenc.o rm.o
-OBJS-$(CONFIG_ROQ_DEMUXER)               += idroq.o
-OBJS-$(CONFIG_ROQ_MUXER)                 += raw.o
+OBJS-$(CONFIG_ROQ_DEMUXER)               += idroqdec.o
+OBJS-$(CONFIG_ROQ_MUXER)                 += idroqenc.o rawenc.o
+OBJS-$(CONFIG_RSO_DEMUXER)               += rsodec.o rso.o pcm.o
+OBJS-$(CONFIG_RSO_MUXER)                 += rsoenc.o rso.o
 OBJS-$(CONFIG_RPL_DEMUXER)               += rpl.o
 OBJS-$(CONFIG_RTP_MUXER)                 += rtp.o         \
                                             rtpenc_aac.o     \
@@ -214,54 +234,72 @@ OBJS-$(CONFIG_RTP_MUXER)                 += rtp.o         \
                                             rtpenc_mpv.o     \
                                             rtpenc.o      \
                                             rtpenc_h264.o \
+                                            rtpenc_vp8.o  \
+                                            rtpenc_xiph.o \
                                             avc.o
-OBJS-$(CONFIG_RTSP_DEMUXER)              += rtsp.o httpauth.o
-OBJS-$(CONFIG_RTSP_MUXER)                += rtsp.o rtspenc.o httpauth.o
-OBJS-$(CONFIG_SDP_DEMUXER)               += rtsp.o        \
-                                            rdt.o         \
+OBJS-$(CONFIG_RTPDEC)                    += rdt.o         \
                                             rtp.o         \
                                             rtpdec.o      \
                                             rtpdec_amr.o  \
                                             rtpdec_asf.o  \
                                             rtpdec_h263.o \
                                             rtpdec_h264.o \
+                                            rtpdec_latm.o \
+                                            rtpdec_mpeg4.o \
+                                            rtpdec_qcelp.o \
+                                            rtpdec_qdm2.o \
+                                            rtpdec_qt.o   \
+                                            rtpdec_svq3.o \
+                                            rtpdec_vp8.o  \
                                             rtpdec_xiph.o
+OBJS-$(CONFIG_RTSP_DEMUXER)              += rtsp.o rtspdec.o httpauth.o
+OBJS-$(CONFIG_RTSP_MUXER)                += rtsp.o rtspenc.o httpauth.o \
+                                            rtpenc_chain.o
+OBJS-$(CONFIG_SAP_DEMUXER)               += sapdec.o
+OBJS-$(CONFIG_SAP_MUXER)                 += sapenc.o rtpenc_chain.o
+OBJS-$(CONFIG_SDP_DEMUXER)               += rtsp.o
 OBJS-$(CONFIG_SEGAFILM_DEMUXER)          += segafilm.o
-OBJS-$(CONFIG_SHORTEN_DEMUXER)           += raw.o id3v2.o
+OBJS-$(CONFIG_SHORTEN_DEMUXER)           += rawdec.o
 OBJS-$(CONFIG_SIFF_DEMUXER)              += siff.o
 OBJS-$(CONFIG_SMACKER_DEMUXER)           += smacker.o
-OBJS-$(CONFIG_SOL_DEMUXER)               += sol.o raw.o
-OBJS-$(CONFIG_SOX_DEMUXER)               += soxdec.o raw.o
+OBJS-$(CONFIG_SOL_DEMUXER)               += sol.o pcm.o
+OBJS-$(CONFIG_SOX_DEMUXER)               += soxdec.o pcm.o
 OBJS-$(CONFIG_SOX_MUXER)                 += soxenc.o
-OBJS-$(CONFIG_SPDIF_MUXER)               += spdif.o
+OBJS-$(CONFIG_SPDIF_DEMUXER)             += spdif.o spdifdec.o
+OBJS-$(CONFIG_SPDIF_MUXER)               += spdif.o spdifenc.o
+OBJS-$(CONFIG_SRT_DEMUXER)               += srtdec.o
+OBJS-$(CONFIG_SRT_MUXER)                 += rawenc.o
 OBJS-$(CONFIG_STR_DEMUXER)               += psxstr.o
 OBJS-$(CONFIG_SWF_DEMUXER)               += swfdec.o
 OBJS-$(CONFIG_SWF_MUXER)                 += swfenc.o
 OBJS-$(CONFIG_THP_DEMUXER)               += thp.o
 OBJS-$(CONFIG_TIERTEXSEQ_DEMUXER)        += tiertexseq.o
 OBJS-$(CONFIG_TMV_DEMUXER)               += tmv.o
-OBJS-$(CONFIG_TRUEHD_DEMUXER)            += raw.o id3v2.o
-OBJS-$(CONFIG_TRUEHD_MUXER)              += raw.o
-OBJS-$(CONFIG_TTA_DEMUXER)               += tta.o id3v1.o id3v2.o
+OBJS-$(CONFIG_TRUEHD_DEMUXER)            += rawdec.o
+OBJS-$(CONFIG_TRUEHD_MUXER)              += rawenc.o
+OBJS-$(CONFIG_TTA_DEMUXER)               += tta.o
+OBJS-$(CONFIG_TTY_DEMUXER)               += tty.o sauce.o
 OBJS-$(CONFIG_TXD_DEMUXER)               += txd.o
-OBJS-$(CONFIG_VC1_DEMUXER)               += raw.o
+OBJS-$(CONFIG_VC1_DEMUXER)               += rawdec.o
 OBJS-$(CONFIG_VC1T_DEMUXER)              += vc1test.o
 OBJS-$(CONFIG_VC1T_MUXER)                += vc1testenc.o
 OBJS-$(CONFIG_VMD_DEMUXER)               += sierravmd.o
 OBJS-$(CONFIG_VOC_DEMUXER)               += vocdec.o voc.o
 OBJS-$(CONFIG_VOC_MUXER)                 += vocenc.o voc.o
 OBJS-$(CONFIG_VQF_DEMUXER)               += vqf.o
-OBJS-$(CONFIG_W64_DEMUXER)               += wav.o riff.o raw.o
-OBJS-$(CONFIG_WAV_DEMUXER)               += wav.o riff.o raw.o
+OBJS-$(CONFIG_W64_DEMUXER)               += wav.o riff.o pcm.o
+OBJS-$(CONFIG_WAV_DEMUXER)               += wav.o riff.o pcm.o
 OBJS-$(CONFIG_WAV_MUXER)                 += wav.o riff.o
 OBJS-$(CONFIG_WC3_DEMUXER)               += wc3movie.o
 OBJS-$(CONFIG_WEBM_MUXER)                += matroskaenc.o matroska.o \
                                             riff.o isom.o avc.o \
-                                            flacenc_header.o
+                                            flacenc_header.o avlanguage.o
 OBJS-$(CONFIG_WSAUD_DEMUXER)             += westwood.o
 OBJS-$(CONFIG_WSVQA_DEMUXER)             += westwood.o
-OBJS-$(CONFIG_WV_DEMUXER)                += wv.o apetag.o id3v1.o
+OBJS-$(CONFIG_WTV_DEMUXER)               += wtv.o asf.o asfdec.o mpegts.o riff.o
+OBJS-$(CONFIG_WV_DEMUXER)                += wv.o apetag.o
 OBJS-$(CONFIG_XA_DEMUXER)                += xa.o
+OBJS-$(CONFIG_XWMA_DEMUXER)              += xwma.o riff.o
 OBJS-$(CONFIG_YOP_DEMUXER)               += yop.o
 OBJS-$(CONFIG_YUV4MPEGPIPE_MUXER)        += yuv4mpeg.o
 OBJS-$(CONFIG_YUV4MPEGPIPE_DEMUXER)      += yuv4mpeg.o
@@ -273,9 +311,14 @@ OBJS-$(CONFIG_LIBNUT_MUXER)              += libnut.o riff.o
 # protocols I/O
 OBJS+= avio.o aviobuf.o
 
+OBJS-$(CONFIG_APPLEHTTP_PROTOCOL)        += applehttpproto.o
+OBJS-$(CONFIG_CONCAT_PROTOCOL)           += concat.o
 OBJS-$(CONFIG_FILE_PROTOCOL)             += file.o
 OBJS-$(CONFIG_GOPHER_PROTOCOL)           += gopher.o
 OBJS-$(CONFIG_HTTP_PROTOCOL)             += http.o httpauth.o
+OBJS-$(CONFIG_MMSH_PROTOCOL)             += mmsh.o mms.o asf.o
+OBJS-$(CONFIG_MMST_PROTOCOL)             += mmst.o mms.o asf.o
+OBJS-$(CONFIG_MD5_PROTOCOL)              += md5proto.o
 OBJS-$(CONFIG_PIPE_PROTOCOL)             += file.o
 
 # external or internal rtmp
@@ -286,7 +329,6 @@ OBJS-$(CONFIG_RTMP_PROTOCOL)             += $(RTMP-OBJS-yes)
 OBJS-$(CONFIG_RTP_PROTOCOL)              += rtpproto.o
 OBJS-$(CONFIG_TCP_PROTOCOL)              += tcp.o
 OBJS-$(CONFIG_UDP_PROTOCOL)              += udp.o
-OBJS-$(CONFIG_CONCAT_PROTOCOL)           += concat.o
 
 # libavdevice dependencies
 OBJS-$(CONFIG_JACK_INDEV)                += timefilter.o
diff --git a/libavformat/a64.c b/libavformat/a64.c
new file mode 100644
index 0000000..0e5576b
--- /dev/null
+++ b/libavformat/a64.c
@@ -0,0 +1,177 @@
+/*
+ * a64 muxer
+ * Copyright (c) 2009 Tobias Bindhammer
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "libavcodec/avcodec.h"
+#include "libavcodec/a64enc.h"
+#include "libavcodec/bytestream.h"
+#include "avformat.h"
+
+typedef struct A64MuxerContext {
+    int interleaved;
+    AVPacket prev_pkt;
+    int prev_frame_count;
+} A64MuxerContext;
+
+static int a64_write_header(struct AVFormatContext *s)
+{
+    AVCodecContext *avctx = s->streams[0]->codec;
+    A64MuxerContext *c = s->priv_data;
+    uint8_t header[5] = {
+        0x00, //load
+        0x40, //address
+        0x00, //mode
+        0x00, //charset_lifetime (multi only)
+        0x00  //fps in 50/fps;
+    };
+    c->interleaved = 0;
+    switch (avctx->codec->id) {
+    case CODEC_ID_A64_MULTI:
+        header[2] = 0x00;
+        header[3] = AV_RB32(avctx->extradata+0);
+        header[4] = 2;
+        break;
+    case CODEC_ID_A64_MULTI5:
+        header[2] = 0x01;
+        header[3] = AV_RB32(avctx->extradata+0);
+        header[4] = 3;
+        break;
+    default:
+        return AVERROR(EINVAL);
+        break;
+    }
+    avio_write(s->pb, header, 2);
+    c->prev_pkt.size = 0;
+    c->prev_frame_count = 0;
+    return 0;
+}
+
+static int a64_write_packet(struct AVFormatContext *s, AVPacket *pkt)
+{
+    AVCodecContext *avctx = s->streams[0]->codec;
+    A64MuxerContext *c = s->priv_data;
+    int i, j;
+    int ch_chunksize;
+    int lifetime;
+    int frame_count;
+    int charset_size;
+    int frame_size;
+    int num_frames;
+
+    /* fetch values from extradata */
+    switch (avctx->codec->id) {
+    case CODEC_ID_A64_MULTI:
+    case CODEC_ID_A64_MULTI5:
+        if(c->interleaved) {
+            /* Write interleaved, means we insert chunks of the future charset before each current frame.
+             * Reason: if we load 1 charset + corresponding frames in one block on c64, we need to store
+             * them first and then display frame by frame to keep in sync. Thus we would read and write
+             * the data for colram from/to ram first and waste too much time. If we interleave and send the
+             * charset beforehand, we assemble a new charset chunk by chunk, write current screen data to
+             * screen-ram to be displayed and decode the colram directly to colram-location $d800 during
+             * the overscan, while reading directly from source.
+             * This is the only way so far, to achieve 25fps on c64 */
+            if(avctx->extradata) {
+                /* fetch values from extradata */
+                lifetime     = AV_RB32(avctx->extradata + 0);
+                frame_count  = AV_RB32(avctx->extradata + 4);
+                charset_size = AV_RB32(avctx->extradata + 8);
+                frame_size   = AV_RB32(avctx->extradata + 12);
+
+                /* TODO: sanity checks? */
+            } else {
+                av_log(avctx, AV_LOG_ERROR, "extradata not set\n");
+                return AVERROR(EINVAL);
+            }
+
+            ch_chunksize=charset_size/lifetime;
+            /* TODO: check if charset/size is % lifetime, but maybe check in codec */
+
+            if(pkt->data) num_frames = lifetime;
+            else num_frames = c->prev_frame_count;
+
+            for(i = 0; i < num_frames; i++) {
+                if(pkt->data) {
+                    /* if available, put newest charset chunk into buffer */
+                    avio_write(s->pb, pkt->data + ch_chunksize * i, ch_chunksize);
+                } else {
+                    /* a bit ugly, but is there an alternative to put many zeros? */
+                    for(j = 0; j < ch_chunksize; j++) avio_w8(s->pb, 0);
+                }
+
+                if(c->prev_pkt.data) {
+                    /* put frame (screen + colram) from last packet into buffer */
+                    avio_write(s->pb, c->prev_pkt.data + charset_size + frame_size * i, frame_size);
+                } else {
+                    /* a bit ugly, but is there an alternative to put many zeros? */
+                    for(j = 0; j < frame_size; j++) avio_w8(s->pb, 0);
+                }
+            }
+
+            /* backup current packet for next turn */
+            if(pkt->data) {
+                /* no backup packet yet? create one! */
+                if(!c->prev_pkt.data) av_new_packet(&c->prev_pkt, pkt->size);
+                /* we have a packet and data is big enough, reuse it */
+                if(c->prev_pkt.data && c->prev_pkt.size >= pkt->size) {
+                    memcpy(c->prev_pkt.data, pkt->data, pkt->size);
+                    c->prev_pkt.size = pkt->size;
+                } else {
+                    av_log(avctx, AV_LOG_ERROR, "Too less memory for prev_pkt.\n");
+                    return AVERROR(ENOMEM);
+                }
+            }
+
+            c->prev_frame_count = frame_count;
+            break;
+        }
+        default:
+            /* Write things as is. Nice for self-contained frames from non-multicolor modes or if played
+             * directly from ram and not from a streaming device (rrnet/mmc) */
+            if(pkt) avio_write(s->pb, pkt->data, pkt->size);
+        break;
+    }
+
+    avio_flush(s->pb);
+    return 0;
+}
+
+static int a64_write_trailer(struct AVFormatContext *s)
+{
+    A64MuxerContext *c = s->priv_data;
+    AVPacket pkt = {0};
+    /* need to flush last packet? */
+    if(c->interleaved) a64_write_packet(s, &pkt);
+    /* discard backed up packet */
+    if(c->prev_pkt.data) av_destruct_packet(&c->prev_pkt);
+    return 0;
+}
+
+AVOutputFormat ff_a64_muxer = {
+    .name = "a64",
+    .long_name = NULL_IF_CONFIG_SMALL("a64 - video for Commodore 64"),
+    .mime_type = NULL,
+    .extensions = "a64, A64",
+    .priv_data_size = sizeof (A64Context),
+    .video_codec = CODEC_ID_A64_MULTI,
+    a64_write_header,
+    a64_write_packet,
+    a64_write_trailer
+};
diff --git a/libavformat/aacdec.c b/libavformat/aacdec.c
new file mode 100644
index 0000000..0dc1c5c
--- /dev/null
+++ b/libavformat/aacdec.c
@@ -0,0 +1,94 @@
+/*
+ * raw ADTS AAC demuxer
+ * Copyright (c) 2008 Michael Niedermayer <michaelni at gmx.at>
+ * Copyright (c) 2009 Robert Swain ( rob opendot cl )
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "libavutil/intreadwrite.h"
+#include "avformat.h"
+#include "rawdec.h"
+#include "id3v1.h"
+
+
+static int adts_aac_probe(AVProbeData *p)
+{
+    int max_frames = 0, first_frames = 0;
+    int fsize, frames;
+    uint8_t *buf0 = p->buf;
+    uint8_t *buf2;
+    uint8_t *buf;
+    uint8_t *end = buf0 + p->buf_size - 7;
+
+    buf = buf0;
+
+    for(; buf < end; buf= buf2+1) {
+        buf2 = buf;
+
+        for(frames = 0; buf2 < end; frames++) {
+            uint32_t header = AV_RB16(buf2);
+            if((header&0xFFF6) != 0xFFF0)
+                break;
+            fsize = (AV_RB32(buf2+3)>>13) & 0x8FFF;
+            if(fsize < 7)
+                break;
+            buf2 += fsize;
+        }
+        max_frames = FFMAX(max_frames, frames);
+        if(buf == buf0)
+            first_frames= frames;
+    }
+    if   (first_frames>=3) return AVPROBE_SCORE_MAX/2+1;
+    else if(max_frames>500)return AVPROBE_SCORE_MAX/2;
+    else if(max_frames>=3) return AVPROBE_SCORE_MAX/4;
+    else if(max_frames>=1) return 1;
+    else                   return 0;
+}
+
+static int adts_aac_read_header(AVFormatContext *s,
+                                AVFormatParameters *ap)
+{
+    AVStream *st;
+
+    st = av_new_stream(s, 0);
+    if (!st)
+        return AVERROR(ENOMEM);
+
+    st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
+    st->codec->codec_id = s->iformat->value;
+    st->need_parsing = AVSTREAM_PARSE_FULL;
+
+    ff_id3v1_read(s);
+
+    //LCM of all possible ADTS sample rates
+    av_set_pts_info(st, 64, 1, 28224000);
+
+    return 0;
+}
+
+AVInputFormat ff_aac_demuxer = {
+    "aac",
+    NULL_IF_CONFIG_SMALL("raw ADTS AAC"),
+    0,
+    adts_aac_probe,
+    adts_aac_read_header,
+    ff_raw_read_partial_packet,
+    .flags= AVFMT_GENERIC_INDEX,
+    .extensions = "aac",
+    .value = CODEC_ID_AAC,
+};
diff --git a/libavformat/ac3dec.c b/libavformat/ac3dec.c
new file mode 100644
index 0000000..7ed0102
--- /dev/null
+++ b/libavformat/ac3dec.c
@@ -0,0 +1,103 @@
+/*
+ * RAW AC-3 and E-AC-3 demuxer
+ * Copyright (c) 2007 Justin Ruggles <justin.ruggles at gmail.com>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "libavutil/crc.h"
+#include "libavcodec/ac3_parser.h"
+#include "avformat.h"
+#include "rawdec.h"
+
+static int ac3_eac3_probe(AVProbeData *p, enum CodecID expected_codec_id)
+{
+    int max_frames, first_frames = 0, frames;
+    uint8_t *buf, *buf2, *end;
+    AC3HeaderInfo hdr;
+    GetBitContext gbc;
+    enum CodecID codec_id = CODEC_ID_AC3;
+
+    max_frames = 0;
+    buf = p->buf;
+    end = buf + p->buf_size;
+
+    for(; buf < end; buf++) {
+        buf2 = buf;
+
+        for(frames = 0; buf2 < end; frames++) {
+            init_get_bits(&gbc, buf2, 54);
+            if(ff_ac3_parse_header(&gbc, &hdr) < 0)
+                break;
+            if(buf2 + hdr.frame_size > end ||
+               av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0, buf2 + 2, hdr.frame_size - 2))
+                break;
+            if (hdr.bitstream_id > 10)
+                codec_id = CODEC_ID_EAC3;
+            buf2 += hdr.frame_size;
+        }
+        max_frames = FFMAX(max_frames, frames);
+        if(buf == p->buf)
+            first_frames = frames;
+    }
+    if(codec_id != expected_codec_id) return 0;
+    // keep this in sync with mp3 probe, both need to avoid
+    // issues with MPEG-files!
+    if   (first_frames>=4) return AVPROBE_SCORE_MAX/2+1;
+    else if(max_frames>500)return AVPROBE_SCORE_MAX/2;
+    else if(max_frames>=4) return AVPROBE_SCORE_MAX/4;
+    else if(max_frames>=1) return 1;
+    else                   return 0;
+}
+
+#if CONFIG_AC3_DEMUXER
+static int ac3_probe(AVProbeData *p)
+{
+    return ac3_eac3_probe(p, CODEC_ID_AC3);
+}
+
+AVInputFormat ff_ac3_demuxer = {
+    "ac3",
+    NULL_IF_CONFIG_SMALL("raw AC-3"),
+    0,
+    ac3_probe,
+    ff_raw_audio_read_header,
+    ff_raw_read_partial_packet,
+    .flags= AVFMT_GENERIC_INDEX,
+    .extensions = "ac3",
+    .value = CODEC_ID_AC3,
+};
+#endif
+
+#if CONFIG_EAC3_DEMUXER
+static int eac3_probe(AVProbeData *p)
+{
+    return ac3_eac3_probe(p, CODEC_ID_EAC3);
+}
+
+AVInputFormat ff_eac3_demuxer = {
+    "eac3",
+    NULL_IF_CONFIG_SMALL("raw E-AC-3"),
+    0,
+    eac3_probe,
+    ff_raw_audio_read_header,
+    ff_raw_read_partial_packet,
+    .flags= AVFMT_GENERIC_INDEX,
+    .extensions = "eac3",
+    .value = CODEC_ID_EAC3,
+};
+#endif
diff --git a/libavformat/adts.h b/libavformat/adts.h
index 1da57be..78b42c7 100644
--- a/libavformat/adts.h
+++ b/libavformat/adts.h
@@ -3,20 +3,20 @@
  * Copyright (c) 2006 Baptiste Coudurier <baptiste.coudurier at smartjog.com>
  *                    Mans Rullgard <mans at mansr.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavformat/adtsenc.c b/libavformat/adtsenc.c
index ecc8dc4..e858a81 100644
--- a/libavformat/adtsenc.c
+++ b/libavformat/adtsenc.c
@@ -3,26 +3,27 @@
  * Copyright (c) 2006 Baptiste Coudurier <baptiste.coudurier at smartjog.com>
  *                    Mans Rullgard <mans at mansr.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "libavcodec/get_bits.h"
 #include "libavcodec/put_bits.h"
 #include "libavcodec/avcodec.h"
+#include "libavcodec/mpeg4audio.h"
 #include "avformat.h"
 #include "adts.h"
 
@@ -30,11 +31,17 @@ int ff_adts_decode_extradata(AVFormatContext *s, ADTSContext *adts, uint8_t *buf
 {
     GetBitContext gb;
     PutBitContext pb;
+    MPEG4AudioConfig m4ac;
+    int off;
 
     init_get_bits(&gb, buf, size * 8);
-    adts->objecttype = get_bits(&gb, 5) - 1;
-    adts->sample_rate_index = get_bits(&gb, 4);
-    adts->channel_conf = get_bits(&gb, 4);
+    off = ff_mpeg4audio_get_config(&m4ac, buf, size);
+    if (off < 0)
+        return off;
+    skip_bits_long(&gb, off);
+    adts->objecttype        = m4ac.object_type - 1;
+    adts->sample_rate_index = m4ac.sampling_index;
+    adts->channel_conf      = m4ac.chan_config;
 
     if (adts->objecttype > 3U) {
         av_log(s, AV_LOG_ERROR, "MPEG-4 AOT %d is not allowed in ADTS\n", adts->objecttype+1);
@@ -52,10 +59,6 @@ int ff_adts_decode_extradata(AVFormatContext *s, ADTSContext *adts, uint8_t *buf
         av_log(s, AV_LOG_ERROR, "Scalable configurations are not allowed in ADTS\n");
         return -1;
     }
-    if (get_bits(&gb, 1)) {
-        av_log_missing_feature(s, "Signaled SBR or PS", 0);
-        return -1;
-    }
     if (!adts->channel_conf) {
         init_put_bits(&pb, adts->pce_data, MAX_PCE_SIZE);
 
@@ -74,7 +77,7 @@ static int adts_write_header(AVFormatContext *s)
     ADTSContext *adts = s->priv_data;
     AVCodecContext *avc = s->streams[0]->codec;
 
-    if(avc->extradata_size > 0 &&
+    if (avc->extradata_size > 0 &&
             ff_adts_decode_extradata(s, adts, avc->extradata, avc->extradata_size) < 0)
         return -1;
 
@@ -115,26 +118,26 @@ int ff_adts_write_frame_header(ADTSContext *ctx,
 static int adts_write_packet(AVFormatContext *s, AVPacket *pkt)
 {
     ADTSContext *adts = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     uint8_t buf[ADTS_HEADER_SIZE];
 
     if (!pkt->size)
         return 0;
-    if(adts->write_adts) {
+    if (adts->write_adts) {
         ff_adts_write_frame_header(adts, buf, pkt->size, adts->pce_size);
-        put_buffer(pb, buf, ADTS_HEADER_SIZE);
-        if(adts->pce_size) {
-            put_buffer(pb, adts->pce_data, adts->pce_size);
+        avio_write(pb, buf, ADTS_HEADER_SIZE);
+        if (adts->pce_size) {
+            avio_write(pb, adts->pce_data, adts->pce_size);
             adts->pce_size = 0;
         }
     }
-    put_buffer(pb, pkt->data, pkt->size);
-    put_flush_packet(pb);
+    avio_write(pb, pkt->data, pkt->size);
+    avio_flush(pb);
 
     return 0;
 }
 
-AVOutputFormat adts_muxer = {
+AVOutputFormat ff_adts_muxer = {
     "adts",
     NULL_IF_CONFIG_SMALL("ADTS AAC"),
     "audio/aac",
diff --git a/libavformat/aea.c b/libavformat/aea.c
index 518995c..c6dfbb1 100644
--- a/libavformat/aea.c
+++ b/libavformat/aea.c
@@ -3,26 +3,27 @@
  *
  * Copyright (c) 2009 Benjamin Larsson
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "avformat.h"
-#include "raw.h"
+#include "pcm.h"
 #include "libavutil/intreadwrite.h"
+#include "libavutil/audioconvert.h"
 
 #define AT1_SU_SIZE     212
 
@@ -61,9 +62,9 @@ static int aea_read_header(AVFormatContext *s,
         return AVERROR(ENOMEM);
 
     /* Parse the amount of channels and skip to pos 2048(0x800) */
-    url_fskip(s->pb, 264);
-    st->codec->channels = get_byte(s->pb);
-    url_fskip(s->pb, 1783);
+    avio_skip(s->pb, 264);
+    st->codec->channels = avio_r8(s->pb);
+    avio_skip(s->pb, 1783);
 
 
     st->codec->codec_type     = AVMEDIA_TYPE_AUDIO;
@@ -76,7 +77,7 @@ static int aea_read_header(AVFormatContext *s,
         return -1;
     }
 
-    st->codec->channel_layout = (st->codec->channels == 1) ? CH_LAYOUT_MONO : CH_LAYOUT_STEREO;
+    st->codec->channel_layout = (st->codec->channels == 1) ? AV_CH_LAYOUT_MONO : AV_CH_LAYOUT_STEREO;
 
     st->codec->block_align = AT1_SU_SIZE * st->codec->channels;
     return 0;
@@ -93,7 +94,7 @@ static int aea_read_packet(AVFormatContext *s, AVPacket *pkt)
     return ret;
 }
 
-AVInputFormat aea_demuxer = {
+AVInputFormat ff_aea_demuxer = {
     "aea",
     NULL_IF_CONFIG_SMALL("MD STUDIO audio"),
     0,
diff --git a/libavformat/aiff.h b/libavformat/aiff.h
index 047f81d..cd2bd25 100644
--- a/libavformat/aiff.h
+++ b/libavformat/aiff.h
@@ -2,20 +2,20 @@
  * AIFF/AIFF-C muxer/demuxer common header
  * Copyright (c) 2006  Patrick Guimond
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavformat/aiffdec.c b/libavformat/aiffdec.c
index f72af00..8678f9b 100644
--- a/libavformat/aiffdec.c
+++ b/libavformat/aiffdec.c
@@ -2,26 +2,26 @@
  * AIFF/AIFF-C demuxer
  * Copyright (c) 2006  Patrick Guimond
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "libavutil/intfloat_readwrite.h"
 #include "avformat.h"
-#include "raw.h"
+#include "pcm.h"
 #include "aiff.h"
 
 #define AIFF                    0
@@ -47,15 +47,15 @@ static enum CodecID aiff_codec_get_id(int bps)
 }
 
 /* returns the size of the found tag */
-static int get_tag(ByteIOContext *pb, uint32_t * tag)
+static int get_tag(AVIOContext *pb, uint32_t * tag)
 {
     int size;
 
-    if (url_feof(pb))
+    if (pb->eof_reached)
         return AVERROR(EIO);
 
-    *tag = get_le32(pb);
-    size = get_be32(pb);
+    *tag = avio_rl32(pb);
+    size = avio_rb32(pb);
 
     if (size < 0)
         size = 0x7fffffff;
@@ -70,11 +70,11 @@ static void get_meta(AVFormatContext *s, const char *key, int size)
     int res;
 
     if (!str) {
-        url_fskip(s->pb, size);
+        avio_skip(s->pb, size);
         return;
     }
 
-    res = get_buffer(s->pb, str, size);
+    res = avio_read(s->pb, str, size);
     if (res < 0)
         return;
 
@@ -83,7 +83,7 @@ static void get_meta(AVFormatContext *s, const char *key, int size)
 }
 
 /* Returns the number of sound data frames or negative on error */
-static unsigned int get_aiff_header(ByteIOContext *pb, AVCodecContext *codec,
+static unsigned int get_aiff_header(AVIOContext *pb, AVCodecContext *codec,
                              int size, unsigned version)
 {
     AVExtFloat ext;
@@ -93,18 +93,18 @@ static unsigned int get_aiff_header(ByteIOContext *pb, AVCodecContext *codec,
     if (size & 1)
         size++;
     codec->codec_type = AVMEDIA_TYPE_AUDIO;
-    codec->channels = get_be16(pb);
-    num_frames = get_be32(pb);
-    codec->bits_per_coded_sample = get_be16(pb);
+    codec->channels = avio_rb16(pb);
+    num_frames = avio_rb32(pb);
+    codec->bits_per_coded_sample = avio_rb16(pb);
 
-    get_buffer(pb, (uint8_t*)&ext, sizeof(ext));/* Sample rate is in */
+    avio_read(pb, (uint8_t*)&ext, sizeof(ext));/* Sample rate is in */
     sample_rate = av_ext2dbl(ext);          /* 80 bits BE IEEE extended float */
     codec->sample_rate = sample_rate;
     size -= 18;
 
     /* Got an AIFF-C? */
     if (version == AIFF_C_VERSION1) {
-        codec->codec_tag = get_le32(pb);
+        codec->codec_tag = avio_rl32(pb);
         codec->codec_id  = ff_codec_get_id(ff_codec_aiff_tags, codec->codec_tag);
 
         switch (codec->codec_id) {
@@ -152,7 +152,7 @@ static unsigned int get_aiff_header(ByteIOContext *pb, AVCodecContext *codec,
 
     /* Chunk is over */
     if (size)
-        url_fseek(pb, size, SEEK_CUR);
+        avio_skip(pb, size);
 
     return num_frames;
 }
@@ -177,7 +177,7 @@ static int aiff_read_header(AVFormatContext *s,
     int64_t offset = 0;
     uint32_t tag;
     unsigned version = AIFF_C_VERSION1;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVStream * st;
     AIFFInputContext *aiff = s->priv_data;
 
@@ -187,7 +187,7 @@ static int aiff_read_header(AVFormatContext *s,
         return AVERROR_INVALIDDATA;
 
     /* AIFF data type */
-    tag = get_le32(pb);
+    tag = avio_rl32(pb);
     if (tag == MKTAG('A', 'I', 'F', 'F'))       /* Got an AIFF file */
         version = AIFF;
     else if (tag != MKTAG('A', 'I', 'F', 'C'))  /* An AIFF-C file then */
@@ -217,7 +217,7 @@ static int aiff_read_header(AVFormatContext *s,
                 goto got_sound;
             break;
         case MKTAG('F', 'V', 'E', 'R'):     /* Version chunk */
-            version = get_be32(pb);
+            version = avio_rb32(pb);
             break;
         case MKTAG('N', 'A', 'M', 'E'):     /* Sample name chunk */
             get_meta(s, "title"    , size);
@@ -232,17 +232,17 @@ static int aiff_read_header(AVFormatContext *s,
             get_meta(s, "comment"  , size);
             break;
         case MKTAG('S', 'S', 'N', 'D'):     /* Sampled sound chunk */
-            aiff->data_end = url_ftell(pb) + size;
-            offset = get_be32(pb);      /* Offset of sound data */
-            get_be32(pb);               /* BlockSize... don't care */
-            offset += url_ftell(pb);    /* Compute absolute data offset */
+            aiff->data_end = avio_tell(pb) + size;
+            offset = avio_rb32(pb);      /* Offset of sound data */
+            avio_rb32(pb);               /* BlockSize... don't care */
+            offset += avio_tell(pb);    /* Compute absolute data offset */
             if (st->codec->block_align)    /* Assume COMM already parsed */
                 goto got_sound;
-            if (url_is_streamed(pb)) {
+            if (!pb->seekable) {
                 av_log(s, AV_LOG_ERROR, "file is not seekable\n");
                 return -1;
             }
-            url_fskip(pb, size - 8);
+            avio_skip(pb, size - 8);
             break;
         case MKTAG('w', 'a', 'v', 'e'):
             if ((uint64_t)size > (1<<30))
@@ -251,12 +251,12 @@ static int aiff_read_header(AVFormatContext *s,
             if (!st->codec->extradata)
                 return AVERROR(ENOMEM);
             st->codec->extradata_size = size;
-            get_buffer(pb, st->codec->extradata, size);
+            avio_read(pb, st->codec->extradata, size);
             break;
         default: /* Jump */
             if (size & 1)   /* Always even aligned */
                 size++;
-            url_fskip (pb, size);
+            avio_skip(pb, size);
         }
     }
 
@@ -276,7 +276,7 @@ got_sound:
         st->nb_frames * st->codec->frame_size : st->nb_frames;
 
     /* Position the stream at the first block */
-    url_fseek(pb, offset, SEEK_SET);
+    avio_seek(pb, offset, SEEK_SET);
 
     return 0;
 }
@@ -292,7 +292,7 @@ static int aiff_read_packet(AVFormatContext *s,
     int res, size;
 
     /* calculate size of remaining data */
-    max_size = aiff->data_end - url_ftell(s->pb);
+    max_size = aiff->data_end - avio_tell(s->pb);
     if (max_size <= 0)
         return AVERROR_EOF;
 
@@ -311,7 +311,7 @@ static int aiff_read_packet(AVFormatContext *s,
     return 0;
 }
 
-AVInputFormat aiff_demuxer = {
+AVInputFormat ff_aiff_demuxer = {
     "aiff",
     NULL_IF_CONFIG_SMALL("Audio IFF"),
     sizeof(AIFFInputContext),
diff --git a/libavformat/aiffenc.c b/libavformat/aiffenc.c
index e3c6a0b..3bdb4f4 100644
--- a/libavformat/aiffenc.c
+++ b/libavformat/aiffenc.c
@@ -2,25 +2,26 @@
  * AIFF/AIFF-C muxer
  * Copyright (c) 2006  Patrick Guimond
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "avformat.h"
 #include "aiff.h"
+#include "avio_internal.h"
 
 typedef struct {
     int64_t form;
@@ -31,7 +32,7 @@ typedef struct {
 static int aiff_write_header(AVFormatContext *s)
 {
     AIFFOutputContext *aiff = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVCodecContext *enc = s->streams[0]->codec;
     AVExtFloat sample_rate;
     int aifc = 0;
@@ -43,10 +44,10 @@ static int aiff_write_header(AVFormatContext *s)
         aifc = 1;
 
     /* FORM AIFF header */
-    put_tag(pb, "FORM");
-    aiff->form = url_ftell(pb);
-    put_be32(pb, 0);                    /* file length */
-    put_tag(pb, aifc ? "AIFC" : "AIFF");
+    ffio_wfourcc(pb, "FORM");
+    aiff->form = avio_tell(pb);
+    avio_wb32(pb, 0);                    /* file length */
+    ffio_wfourcc(pb, aifc ? "AIFC" : "AIFF");
 
     if (aifc) { // compressed audio
         enc->bits_per_coded_sample = 16;
@@ -55,18 +56,18 @@ static int aiff_write_header(AVFormatContext *s)
             return -1;
         }
         /* Version chunk */
-        put_tag(pb, "FVER");
-        put_be32(pb, 4);
-        put_be32(pb, 0xA2805140);
+        ffio_wfourcc(pb, "FVER");
+        avio_wb32(pb, 4);
+        avio_wb32(pb, 0xA2805140);
     }
 
     /* Common chunk */
-    put_tag(pb, "COMM");
-    put_be32(pb, aifc ? 24 : 18); /* size */
-    put_be16(pb, enc->channels);  /* Number of channels */
+    ffio_wfourcc(pb, "COMM");
+    avio_wb32(pb, aifc ? 24 : 18); /* size */
+    avio_wb16(pb, enc->channels);  /* Number of channels */
 
-    aiff->frames = url_ftell(pb);
-    put_be32(pb, 0);              /* Number of frames */
+    aiff->frames = avio_tell(pb);
+    avio_wb32(pb, 0);              /* Number of frames */
 
     if (!enc->bits_per_coded_sample)
         enc->bits_per_coded_sample = av_get_bits_per_sample(enc->codec_id);
@@ -77,75 +78,75 @@ static int aiff_write_header(AVFormatContext *s)
     if (!enc->block_align)
         enc->block_align = (enc->bits_per_coded_sample * enc->channels) >> 3;
 
-    put_be16(pb, enc->bits_per_coded_sample); /* Sample size */
+    avio_wb16(pb, enc->bits_per_coded_sample); /* Sample size */
 
     sample_rate = av_dbl2ext((double)enc->sample_rate);
-    put_buffer(pb, (uint8_t*)&sample_rate, sizeof(sample_rate));
+    avio_write(pb, (uint8_t*)&sample_rate, sizeof(sample_rate));
 
     if (aifc) {
-        put_le32(pb, enc->codec_tag);
-        put_be16(pb, 0);
+        avio_wl32(pb, enc->codec_tag);
+        avio_wb16(pb, 0);
     }
 
     /* Sound data chunk */
-    put_tag(pb, "SSND");
-    aiff->ssnd = url_ftell(pb);         /* Sound chunk size */
-    put_be32(pb, 0);                    /* Sound samples data size */
-    put_be32(pb, 0);                    /* Data offset */
-    put_be32(pb, 0);                    /* Block-size (block align) */
+    ffio_wfourcc(pb, "SSND");
+    aiff->ssnd = avio_tell(pb);         /* Sound chunk size */
+    avio_wb32(pb, 0);                    /* Sound samples data size */
+    avio_wb32(pb, 0);                    /* Data offset */
+    avio_wb32(pb, 0);                    /* Block-size (block align) */
 
     av_set_pts_info(s->streams[0], 64, 1, s->streams[0]->codec->sample_rate);
 
     /* Data is starting here */
-    put_flush_packet(pb);
+    avio_flush(pb);
 
     return 0;
 }
 
 static int aiff_write_packet(AVFormatContext *s, AVPacket *pkt)
 {
-    ByteIOContext *pb = s->pb;
-    put_buffer(pb, pkt->data, pkt->size);
+    AVIOContext *pb = s->pb;
+    avio_write(pb, pkt->data, pkt->size);
     return 0;
 }
 
 static int aiff_write_trailer(AVFormatContext *s)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AIFFOutputContext *aiff = s->priv_data;
     AVCodecContext *enc = s->streams[0]->codec;
 
     /* Chunks sizes must be even */
     int64_t file_size, end_size;
-    end_size = file_size = url_ftell(pb);
+    end_size = file_size = avio_tell(pb);
     if (file_size & 1) {
-        put_byte(pb, 0);
+        avio_w8(pb, 0);
         end_size++;
     }
 
-    if (!url_is_streamed(s->pb)) {
+    if (s->pb->seekable) {
         /* File length */
-        url_fseek(pb, aiff->form, SEEK_SET);
-        put_be32(pb, file_size - aiff->form - 4);
+        avio_seek(pb, aiff->form, SEEK_SET);
+        avio_wb32(pb, file_size - aiff->form - 4);
 
         /* Number of sample frames */
-        url_fseek(pb, aiff->frames, SEEK_SET);
-        put_be32(pb, (file_size-aiff->ssnd-12)/enc->block_align);
+        avio_seek(pb, aiff->frames, SEEK_SET);
+        avio_wb32(pb, (file_size-aiff->ssnd-12)/enc->block_align);
 
         /* Sound Data chunk size */
-        url_fseek(pb, aiff->ssnd, SEEK_SET);
-        put_be32(pb, file_size - aiff->ssnd - 4);
+        avio_seek(pb, aiff->ssnd, SEEK_SET);
+        avio_wb32(pb, file_size - aiff->ssnd - 4);
 
         /* return to the end */
-        url_fseek(pb, end_size, SEEK_SET);
+        avio_seek(pb, end_size, SEEK_SET);
 
-        put_flush_packet(pb);
+        avio_flush(pb);
     }
 
     return 0;
 }
 
-AVOutputFormat aiff_muxer = {
+AVOutputFormat ff_aiff_muxer = {
     "aiff",
     NULL_IF_CONFIG_SMALL("Audio IFF"),
     "audio/aiff",
diff --git a/libavformat/allformats.c b/libavformat/allformats.c
index 27a9555..931947d 100644
--- a/libavformat/allformats.c
+++ b/libavformat/allformats.c
@@ -2,39 +2,40 @@
  * Register all the formats and protocols
  * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #include "avformat.h"
 #include "rtp.h"
 #include "rdt.h"
+#include "url.h"
 
 #define REGISTER_MUXER(X,x) { \
-    extern AVOutputFormat x##_muxer; \
-    if(CONFIG_##X##_MUXER) av_register_output_format(&x##_muxer); }
+    extern AVOutputFormat ff_##x##_muxer; \
+    if(CONFIG_##X##_MUXER) av_register_output_format(&ff_##x##_muxer); }
 
 #define REGISTER_DEMUXER(X,x) { \
-    extern AVInputFormat x##_demuxer; \
-    if(CONFIG_##X##_DEMUXER) av_register_input_format(&x##_demuxer); }
+    extern AVInputFormat ff_##x##_demuxer; \
+    if(CONFIG_##X##_DEMUXER) av_register_input_format(&ff_##x##_demuxer); }
 
 #define REGISTER_MUXDEMUX(X,x)  REGISTER_MUXER(X,x); REGISTER_DEMUXER(X,x)
 
 #define REGISTER_PROTOCOL(X,x) { \
-    extern URLProtocol x##_protocol; \
-    if(CONFIG_##X##_PROTOCOL) av_register_protocol(&x##_protocol); }
+    extern URLProtocol ff_##x##_protocol; \
+    if(CONFIG_##X##_PROTOCOL) ffurl_register_protocol(&ff_##x##_protocol, sizeof(ff_##x##_protocol)); }
 
 void av_register_all(void)
 {
@@ -47,6 +48,7 @@ void av_register_all(void)
     avcodec_register_all();
 
     /* (de)muxers */
+    REGISTER_MUXER    (A64, a64);
     REGISTER_DEMUXER  (AAC, aac);
     REGISTER_MUXDEMUX (AC3, ac3);
     REGISTER_MUXER    (ADTS, adts);
@@ -56,6 +58,7 @@ void av_register_all(void)
     REGISTER_DEMUXER  (ANM, anm);
     REGISTER_DEMUXER  (APC, apc);
     REGISTER_DEMUXER  (APE, ape);
+    REGISTER_DEMUXER  (APPLEHTTP, applehttp);
     REGISTER_MUXDEMUX (ASF, asf);
     REGISTER_MUXDEMUX (ASS, ass);
     REGISTER_MUXER    (ASF_STREAM, asf_stream);
@@ -69,10 +72,11 @@ void av_register_all(void)
     REGISTER_DEMUXER  (BINK, bink);
     REGISTER_DEMUXER  (C93, c93);
     REGISTER_DEMUXER  (CAF, caf);
-    REGISTER_DEMUXER  (CAVSVIDEO, cavsvideo);
+    REGISTER_MUXDEMUX (CAVSVIDEO, cavsvideo);
     REGISTER_DEMUXER  (CDG, cdg);
     REGISTER_MUXER    (CRC, crc);
     REGISTER_MUXDEMUX (DAUD, daud);
+    REGISTER_DEMUXER  (DFA, dfa);
     REGISTER_MUXDEMUX (DIRAC, dirac);
     REGISTER_MUXDEMUX (DNXHD, dnxhd);
     REGISTER_DEMUXER  (DSICIN, dsicin);
@@ -83,12 +87,15 @@ void av_register_all(void)
     REGISTER_DEMUXER  (EA_CDATA, ea_cdata);
     REGISTER_MUXDEMUX (EAC3, eac3);
     REGISTER_MUXDEMUX (FFM, ffm);
+    REGISTER_MUXDEMUX (FFMETADATA, ffmetadata);
     REGISTER_MUXDEMUX (FILMSTRIP, filmstrip);
     REGISTER_MUXDEMUX (FLAC, flac);
     REGISTER_DEMUXER  (FLIC, flic);
     REGISTER_MUXDEMUX (FLV, flv);
     REGISTER_DEMUXER  (FOURXM, fourxm);
     REGISTER_MUXER    (FRAMECRC, framecrc);
+    REGISTER_MUXER    (FRAMEMD5, framemd5);
+    REGISTER_MUXDEMUX (G722, g722);
     REGISTER_MUXER    (GIF, gif);
     REGISTER_DEMUXER  (GSM, gsm);
     REGISTER_MUXDEMUX (GXF, gxf);
@@ -104,8 +111,12 @@ void av_register_all(void)
     REGISTER_MUXER    (IPOD, ipod);
     REGISTER_DEMUXER  (ISS, iss);
     REGISTER_DEMUXER  (IV8, iv8);
+    REGISTER_MUXDEMUX (IVF, ivf);
+    REGISTER_DEMUXER  (JV, jv);
     REGISTER_DEMUXER  (LMLM4, lmlm4);
+    REGISTER_DEMUXER  (LXF, lxf);
     REGISTER_MUXDEMUX (M4V, m4v);
+    REGISTER_MUXER    (MD5, md5);
     REGISTER_MUXDEMUX (MATROSKA, matroska);
     REGISTER_MUXER    (MATROSKA_AUDIO, matroska_audio);
     REGISTER_MUXDEMUX (MJPEG, mjpeg);
@@ -135,6 +146,7 @@ void av_register_all(void)
     REGISTER_DEMUXER  (MVI, mvi);
     REGISTER_MUXDEMUX (MXF, mxf);
     REGISTER_MUXER    (MXF_D10, mxf_d10);
+    REGISTER_DEMUXER  (MXG, mxg);
     REGISTER_DEMUXER  (NC, nc);
     REGISTER_DEMUXER  (NSV, nsv);
     REGISTER_MUXER    (NULL, null);
@@ -171,10 +183,12 @@ void av_register_all(void)
     REGISTER_MUXDEMUX (RM, rm);
     REGISTER_MUXDEMUX (ROQ, roq);
     REGISTER_DEMUXER  (RPL, rpl);
-    REGISTER_MUXER    (RTP, rtp);
+    REGISTER_MUXDEMUX (RSO, rso);
+    REGISTER_MUXDEMUX (RTP, rtp);
     REGISTER_MUXDEMUX (RTSP, rtsp);
+    REGISTER_MUXDEMUX (SAP, sap);
     REGISTER_DEMUXER  (SDP, sdp);
-#if CONFIG_SDP_DEMUXER
+#if CONFIG_RTPDEC
     av_register_rtp_dynamic_payload_handlers();
     av_register_rdt_dynamic_payload_handlers();
 #endif
@@ -184,7 +198,8 @@ void av_register_all(void)
     REGISTER_DEMUXER  (SMACKER, smacker);
     REGISTER_DEMUXER  (SOL, sol);
     REGISTER_MUXDEMUX (SOX, sox);
-    REGISTER_MUXER    (SPDIF, spdif);
+    REGISTER_MUXDEMUX (SPDIF, spdif);
+    REGISTER_MUXDEMUX (SRT, srt);
     REGISTER_DEMUXER  (STR, str);
     REGISTER_MUXDEMUX (SWF, swf);
     REGISTER_MUXER    (TG2, tg2);
@@ -195,6 +210,7 @@ void av_register_all(void)
     REGISTER_MUXDEMUX (TRUEHD, truehd);
     REGISTER_DEMUXER  (TTA, tta);
     REGISTER_DEMUXER  (TXD, txd);
+    REGISTER_DEMUXER  (TTY, tty);
     REGISTER_DEMUXER  (VC1, vc1);
     REGISTER_MUXDEMUX (VC1T, vc1t);
     REGISTER_DEMUXER  (VMD, vmd);
@@ -206,8 +222,10 @@ void av_register_all(void)
     REGISTER_MUXER    (WEBM, webm);
     REGISTER_DEMUXER  (WSAUD, wsaud);
     REGISTER_DEMUXER  (WSVQA, wsvqa);
+    REGISTER_DEMUXER  (WTV, wtv);
     REGISTER_DEMUXER  (WV, wv);
     REGISTER_DEMUXER  (XA, xa);
+    REGISTER_DEMUXER  (XWMA, xwma);
     REGISTER_DEMUXER  (YOP, yop);
     REGISTER_MUXDEMUX (YUV4MPEGPIPE, yuv4mpegpipe);
 
@@ -215,9 +233,14 @@ void av_register_all(void)
     REGISTER_MUXDEMUX (LIBNUT, libnut);
 
     /* protocols */
+    REGISTER_PROTOCOL (APPLEHTTP, applehttp);
+    REGISTER_PROTOCOL (CONCAT, concat);
     REGISTER_PROTOCOL (FILE, file);
     REGISTER_PROTOCOL (GOPHER, gopher);
     REGISTER_PROTOCOL (HTTP, http);
+    REGISTER_PROTOCOL (MMSH, mmsh);
+    REGISTER_PROTOCOL (MMST, mmst);
+    REGISTER_PROTOCOL (MD5,  md5);
     REGISTER_PROTOCOL (PIPE, pipe);
     REGISTER_PROTOCOL (RTMP, rtmp);
 #if CONFIG_LIBRTMP
@@ -229,5 +252,4 @@ void av_register_all(void)
     REGISTER_PROTOCOL (RTP, rtp);
     REGISTER_PROTOCOL (TCP, tcp);
     REGISTER_PROTOCOL (UDP, udp);
-    REGISTER_PROTOCOL (CONCAT, concat);
 }
diff --git a/libavformat/amr.c b/libavformat/amr.c
index d16b4c0..260bd6a 100644
--- a/libavformat/amr.c
+++ b/libavformat/amr.c
@@ -2,20 +2,20 @@
  * amr file format
  * Copyright (c) 2001 ffmpeg project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -33,31 +33,31 @@ static const char AMRWB_header [] = "#!AMR-WB\n";
 #if CONFIG_AMR_MUXER
 static int amr_write_header(AVFormatContext *s)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVCodecContext *enc = s->streams[0]->codec;
 
     s->priv_data = NULL;
 
     if (enc->codec_id == CODEC_ID_AMR_NB)
     {
-        put_tag(pb, AMR_header);       /* magic number */
+        avio_write(pb, AMR_header,   sizeof(AMR_header)   - 1); /* magic number */
     }
     else if(enc->codec_id == CODEC_ID_AMR_WB)
     {
-        put_tag(pb, AMRWB_header);       /* magic number */
+        avio_write(pb, AMRWB_header, sizeof(AMRWB_header) - 1); /* magic number */
     }
     else
     {
         return -1;
     }
-    put_flush_packet(pb);
+    avio_flush(pb);
     return 0;
 }
 
 static int amr_write_packet(AVFormatContext *s, AVPacket *pkt)
 {
-    put_buffer(s->pb, pkt->data, pkt->size);
-    put_flush_packet(s->pb);
+    avio_write(s->pb, pkt->data, pkt->size);
+    avio_flush(s->pb);
     return 0;
 }
 #endif /* CONFIG_AMR_MUXER */
@@ -78,11 +78,11 @@ static int amr_probe(AVProbeData *p)
 static int amr_read_header(AVFormatContext *s,
                            AVFormatParameters *ap)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVStream *st;
     uint8_t header[9];
 
-    get_buffer(pb, header, 6);
+    avio_read(pb, header, 6);
 
     st = av_new_stream(s, 0);
     if (!st)
@@ -91,7 +91,7 @@ static int amr_read_header(AVFormatContext *s,
     }
     if(memcmp(header,AMR_header,6)!=0)
     {
-        get_buffer(pb, header+6, 3);
+        avio_read(pb, header+6, 3);
         if(memcmp(header,AMRWB_header,9)!=0)
         {
             return -1;
@@ -100,12 +100,14 @@ static int amr_read_header(AVFormatContext *s,
         st->codec->codec_tag = MKTAG('s', 'a', 'w', 'b');
         st->codec->codec_id = CODEC_ID_AMR_WB;
         st->codec->sample_rate = 16000;
+        st->codec->frame_size = 320;
     }
     else
     {
         st->codec->codec_tag = MKTAG('s', 'a', 'm', 'r');
         st->codec->codec_id = CODEC_ID_AMR_NB;
         st->codec->sample_rate = 8000;
+        st->codec->frame_size = 160;
     }
     st->codec->channels = 1;
     st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
@@ -119,14 +121,15 @@ static int amr_read_packet(AVFormatContext *s,
 {
     AVCodecContext *enc = s->streams[0]->codec;
     int read, size = 0, toc, mode;
+    int64_t pos = avio_tell(s->pb);
 
-    if (url_feof(s->pb))
+    if (s->pb->eof_reached)
     {
         return AVERROR(EIO);
     }
 
 //FIXME this is wrong, this should rather be in a AVParset
-    toc=get_byte(s->pb);
+    toc=avio_r8(s->pb);
     mode = (toc >> 3) & 0x0F;
 
     if (enc->codec_id == CODEC_ID_AMR_NB)
@@ -151,11 +154,14 @@ static int amr_read_packet(AVFormatContext *s,
         return AVERROR(EIO);
     }
 
+    /* Both AMR formats have 50 frames per second */
+    s->streams[0]->codec->bit_rate = size*8*50;
+
     pkt->stream_index = 0;
-    pkt->pos= url_ftell(s->pb);
+    pkt->pos = pos;
     pkt->data[0]=toc;
     pkt->duration= enc->codec_id == CODEC_ID_AMR_NB ? 160 : 320;
-    read = get_buffer(s->pb, pkt->data+1, size-1);
+    read = avio_read(s->pb, pkt->data+1, size-1);
 
     if (read != size-1)
     {
@@ -167,7 +173,7 @@ static int amr_read_packet(AVFormatContext *s,
 }
 
 #if CONFIG_AMR_DEMUXER
-AVInputFormat amr_demuxer = {
+AVInputFormat ff_amr_demuxer = {
     "amr",
     NULL_IF_CONFIG_SMALL("3GPP AMR file format"),
     0, /*priv_data_size*/
@@ -175,11 +181,12 @@ AVInputFormat amr_demuxer = {
     amr_read_header,
     amr_read_packet,
     NULL,
+    .flags = AVFMT_GENERIC_INDEX,
 };
 #endif
 
 #if CONFIG_AMR_MUXER
-AVOutputFormat amr_muxer = {
+AVOutputFormat ff_amr_muxer = {
     "amr",
     NULL_IF_CONFIG_SMALL("3GPP AMR file format"),
     "audio/amr",
diff --git a/libavformat/anm.c b/libavformat/anm.c
index ba77e18..4d1b5f7 100644
--- a/libavformat/anm.c
+++ b/libavformat/anm.c
@@ -2,20 +2,20 @@
  * Deluxe Paint Animation demuxer
  * Copyright (c) 2009 Peter Ross
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -34,13 +34,13 @@ typedef struct {
 } Page;
 
 typedef struct {
-    unsigned int nb_pages;    /** total pages in file */
-    unsigned int nb_records;  /** total records in file */
+    unsigned int nb_pages;    /**< total pages in file */
+    unsigned int nb_records;  /**< total records in file */
     int page_table_offset;
-#define MAX_PAGES  256        /** Deluxe Paint hardcoded value */
-    Page pt[MAX_PAGES];       /** page table */
-    int page;                 /** current page (or AVERROR_xxx code) */
-    int record;               /** current record (with in page) */
+#define MAX_PAGES  256        /**< Deluxe Paint hardcoded value */
+    Page pt[MAX_PAGES];       /**< page table */
+    int page;                 /**< current page (or AVERROR_xxx code) */
+    int record;               /**< current record (with in page) */
 } AnmDemuxContext;
 
 #define LPF_TAG  MKTAG('L','P','F',' ')
@@ -79,21 +79,21 @@ static int read_header(AVFormatContext *s,
                        AVFormatParameters *ap)
 {
     AnmDemuxContext *anm = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVStream *st;
     int i, ret;
 
-    url_fskip(pb, 4); /* magic number */
-    if (get_le16(pb) != MAX_PAGES) {
+    avio_skip(pb, 4); /* magic number */
+    if (avio_rl16(pb) != MAX_PAGES) {
         av_log_ask_for_sample(s, "max_pages != " AV_STRINGIFY(MAX_PAGES) "\n");
         return AVERROR_INVALIDDATA;
     }
 
-    anm->nb_pages   = get_le16(pb);
-    anm->nb_records = get_le32(pb);
-    url_fskip(pb, 2); /* max records per page */
-    anm->page_table_offset = get_le16(pb);
-    if (get_le32(pb) != ANIM_TAG)
+    anm->nb_pages   = avio_rl16(pb);
+    anm->nb_records = avio_rl32(pb);
+    avio_skip(pb, 2); /* max records per page */
+    anm->page_table_offset = avio_rl16(pb);
+    if (avio_rl32(pb) != ANIM_TAG)
         return AVERROR_INVALIDDATA;
 
     /* video stream */
@@ -103,33 +103,33 @@ static int read_header(AVFormatContext *s,
     st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
     st->codec->codec_id   = CODEC_ID_ANM;
     st->codec->codec_tag  = 0; /* no fourcc */
-    st->codec->width      = get_le16(pb);
-    st->codec->height     = get_le16(pb);
-    if (get_byte(pb) != 0)
+    st->codec->width      = avio_rl16(pb);
+    st->codec->height     = avio_rl16(pb);
+    if (avio_r8(pb) != 0)
         goto invalid;
-    url_fskip(pb, 1); /* frame rate multiplier info */
+    avio_skip(pb, 1); /* frame rate multiplier info */
 
     /* ignore last delta record (used for looping) */
-    if (get_byte(pb))  /* has_last_delta */
+    if (avio_r8(pb))  /* has_last_delta */
         anm->nb_records = FFMAX(anm->nb_records - 1, 0);
 
-    url_fskip(pb, 1); /* last_delta_valid */
+    avio_skip(pb, 1); /* last_delta_valid */
 
-    if (get_byte(pb) != 0)
+    if (avio_r8(pb) != 0)
         goto invalid;
 
-    if (get_byte(pb) != 1)
+    if (avio_r8(pb) != 1)
         goto invalid;
 
-    url_fskip(pb, 1); /* other recs per frame */
+    avio_skip(pb, 1); /* other recs per frame */
 
-    if (get_byte(pb) != 1)
+    if (avio_r8(pb) != 1)
         goto invalid;
 
-    url_fskip(pb, 32); /* record_types */
-    st->nb_frames = get_le32(pb);
-    av_set_pts_info(st, 64, 1, get_le16(pb));
-    url_fskip(pb, 58);
+    avio_skip(pb, 32); /* record_types */
+    st->nb_frames = avio_rl32(pb);
+    av_set_pts_info(st, 64, 1, avio_rl16(pb));
+    avio_skip(pb, 58);
 
     /* color cycling and palette data */
     st->codec->extradata_size = 16*8 + 4*256;
@@ -138,20 +138,20 @@ static int read_header(AVFormatContext *s,
         ret = AVERROR(ENOMEM);
         goto close_and_return;
     }
-    ret = get_buffer(pb, st->codec->extradata, st->codec->extradata_size);
+    ret = avio_read(pb, st->codec->extradata, st->codec->extradata_size);
     if (ret < 0)
         goto close_and_return;
 
     /* read page table */
-    ret = url_fseek(pb, anm->page_table_offset, SEEK_SET);
+    ret = avio_seek(pb, anm->page_table_offset, SEEK_SET);
     if (ret < 0)
         goto close_and_return;
 
     for (i = 0; i < MAX_PAGES; i++) {
         Page *p = &anm->pt[i];
-        p->base_record = get_le16(pb);
-        p->nb_records  = get_le16(pb);
-        p->size        = get_le16(pb);
+        p->base_record = avio_rl16(pb);
+        p->nb_records  = avio_rl16(pb);
+        p->size        = avio_rl16(pb);
     }
 
     /* find page of first frame */
@@ -177,11 +177,11 @@ static int read_packet(AVFormatContext *s,
                        AVPacket *pkt)
 {
     AnmDemuxContext *anm = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     Page *p;
     int tmp, record_size;
 
-    if (url_feof(s->pb))
+    if (s->pb->eof_reached)
         return AVERROR(EIO);
 
     if (anm->page < 0)
@@ -192,8 +192,8 @@ repeat:
 
     /* parse page header */
     if (anm->record < 0) {
-        url_fseek(pb, anm->page_table_offset + MAX_PAGES*6 + (anm->page<<16), SEEK_SET);
-        url_fskip(pb, 8 + 2*p->nb_records);
+        avio_seek(pb, anm->page_table_offset + MAX_PAGES*6 + (anm->page<<16), SEEK_SET);
+        avio_skip(pb, 8 + 2*p->nb_records);
         anm->record = 0;
     }
 
@@ -208,11 +208,11 @@ repeat:
     }
 
     /* fetch record size */
-    tmp = url_ftell(pb);
-    url_fseek(pb, anm->page_table_offset + MAX_PAGES*6 + (anm->page<<16) +
+    tmp = avio_tell(pb);
+    avio_seek(pb, anm->page_table_offset + MAX_PAGES*6 + (anm->page<<16) +
               8 + anm->record * 2, SEEK_SET);
-    record_size = get_le16(pb);
-    url_fseek(pb, tmp, SEEK_SET);
+    record_size = avio_rl16(pb);
+    avio_seek(pb, tmp, SEEK_SET);
 
     /* fetch record */
     pkt->size = av_get_packet(s->pb, pkt, record_size);
@@ -225,7 +225,7 @@ repeat:
     return 0;
 }
 
-AVInputFormat anm_demuxer = {
+AVInputFormat ff_anm_demuxer = {
     "anm",
     NULL_IF_CONFIG_SMALL("Deluxe Paint Animation"),
     sizeof(AnmDemuxContext),
diff --git a/libavformat/apc.c b/libavformat/apc.c
index 9b4a8ad..40c6f0c 100644
--- a/libavformat/apc.c
+++ b/libavformat/apc.c
@@ -2,20 +2,20 @@
  * CRYO APC audio format demuxer
  * Copyright (c) 2007 Anssi Hannula <anssi.hannula at gmail.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -32,12 +32,12 @@ static int apc_probe(AVProbeData *p)
 
 static int apc_read_header(AVFormatContext *s, AVFormatParameters *ap)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVStream *st;
 
-    get_le32(pb); /* CRYO */
-    get_le32(pb); /* _APC */
-    get_le32(pb); /* 1.20 */
+    avio_rl32(pb); /* CRYO */
+    avio_rl32(pb); /* _APC */
+    avio_rl32(pb); /* 1.20 */
 
     st = av_new_stream(s, 0);
     if (!st)
@@ -46,8 +46,8 @@ static int apc_read_header(AVFormatContext *s, AVFormatParameters *ap)
     st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
     st->codec->codec_id = CODEC_ID_ADPCM_IMA_WS;
 
-    get_le32(pb); /* number of samples */
-    st->codec->sample_rate = get_le32(pb);
+    avio_rl32(pb); /* number of samples */
+    st->codec->sample_rate = avio_rl32(pb);
 
     st->codec->extradata_size = 2 * 4;
     st->codec->extradata = av_malloc(st->codec->extradata_size +
@@ -56,10 +56,10 @@ static int apc_read_header(AVFormatContext *s, AVFormatParameters *ap)
         return AVERROR(ENOMEM);
 
     /* initial predictor values for adpcm decoder */
-    get_buffer(pb, st->codec->extradata, 2 * 4);
+    avio_read(pb, st->codec->extradata, 2 * 4);
 
     st->codec->channels = 1;
-    if (get_le32(pb))
+    if (avio_rl32(pb))
         st->codec->channels = 2;
 
     st->codec->bits_per_coded_sample = 4;
@@ -80,7 +80,7 @@ static int apc_read_packet(AVFormatContext *s, AVPacket *pkt)
     return 0;
 }
 
-AVInputFormat apc_demuxer = {
+AVInputFormat ff_apc_demuxer = {
     "apc",
     NULL_IF_CONFIG_SMALL("CRYO APC format"),
     0,
diff --git a/libavformat/ape.c b/libavformat/ape.c
index 91acf72..956036d 100644
--- a/libavformat/ape.c
+++ b/libavformat/ape.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2007 Benjamin Zores <ben at geexbox.org>
  *  based upon libdemac from Dave Chapman.
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -151,7 +151,7 @@ static void ape_dumpinfo(AVFormatContext * s, APEContext * ape_ctx)
 
 static int ape_read_header(AVFormatContext * s, AVFormatParameters * ap)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     APEContext *ape = s->priv_data;
     AVStream *st;
     uint32_t tag;
@@ -162,11 +162,11 @@ static int ape_read_header(AVFormatContext * s, AVFormatParameters * ap)
     /* TODO: Skip any leading junk such as id3v2 tags */
     ape->junklength = 0;
 
-    tag = get_le32(pb);
+    tag = avio_rl32(pb);
     if (tag != MKTAG('M', 'A', 'C', ' '))
         return -1;
 
-    ape->fileversion = get_le16(pb);
+    ape->fileversion = avio_rl16(pb);
 
     if (ape->fileversion < APE_MIN_VERSION || ape->fileversion > APE_MAX_VERSION) {
         av_log(s, AV_LOG_ERROR, "Unsupported file version - %d.%02d\n", ape->fileversion / 1000, (ape->fileversion % 1000) / 10);
@@ -174,50 +174,50 @@ static int ape_read_header(AVFormatContext * s, AVFormatParameters * ap)
     }
 
     if (ape->fileversion >= 3980) {
-        ape->padding1             = get_le16(pb);
-        ape->descriptorlength     = get_le32(pb);
-        ape->headerlength         = get_le32(pb);
-        ape->seektablelength      = get_le32(pb);
-        ape->wavheaderlength      = get_le32(pb);
-        ape->audiodatalength      = get_le32(pb);
-        ape->audiodatalength_high = get_le32(pb);
-        ape->wavtaillength        = get_le32(pb);
-        get_buffer(pb, ape->md5, 16);
+        ape->padding1             = avio_rl16(pb);
+        ape->descriptorlength     = avio_rl32(pb);
+        ape->headerlength         = avio_rl32(pb);
+        ape->seektablelength      = avio_rl32(pb);
+        ape->wavheaderlength      = avio_rl32(pb);
+        ape->audiodatalength      = avio_rl32(pb);
+        ape->audiodatalength_high = avio_rl32(pb);
+        ape->wavtaillength        = avio_rl32(pb);
+        avio_read(pb, ape->md5, 16);
 
         /* Skip any unknown bytes at the end of the descriptor.
            This is for future compatibility */
         if (ape->descriptorlength > 52)
-            url_fseek(pb, ape->descriptorlength - 52, SEEK_CUR);
+            avio_skip(pb, ape->descriptorlength - 52);
 
         /* Read header data */
-        ape->compressiontype      = get_le16(pb);
-        ape->formatflags          = get_le16(pb);
-        ape->blocksperframe       = get_le32(pb);
-        ape->finalframeblocks     = get_le32(pb);
-        ape->totalframes          = get_le32(pb);
-        ape->bps                  = get_le16(pb);
-        ape->channels             = get_le16(pb);
-        ape->samplerate           = get_le32(pb);
+        ape->compressiontype      = avio_rl16(pb);
+        ape->formatflags          = avio_rl16(pb);
+        ape->blocksperframe       = avio_rl32(pb);
+        ape->finalframeblocks     = avio_rl32(pb);
+        ape->totalframes          = avio_rl32(pb);
+        ape->bps                  = avio_rl16(pb);
+        ape->channels             = avio_rl16(pb);
+        ape->samplerate           = avio_rl32(pb);
     } else {
         ape->descriptorlength = 0;
         ape->headerlength = 32;
 
-        ape->compressiontype      = get_le16(pb);
-        ape->formatflags          = get_le16(pb);
-        ape->channels             = get_le16(pb);
-        ape->samplerate           = get_le32(pb);
-        ape->wavheaderlength      = get_le32(pb);
-        ape->wavtaillength        = get_le32(pb);
-        ape->totalframes          = get_le32(pb);
-        ape->finalframeblocks     = get_le32(pb);
+        ape->compressiontype      = avio_rl16(pb);
+        ape->formatflags          = avio_rl16(pb);
+        ape->channels             = avio_rl16(pb);
+        ape->samplerate           = avio_rl32(pb);
+        ape->wavheaderlength      = avio_rl32(pb);
+        ape->wavtaillength        = avio_rl32(pb);
+        ape->totalframes          = avio_rl32(pb);
+        ape->finalframeblocks     = avio_rl32(pb);
 
         if (ape->formatflags & MAC_FORMAT_FLAG_HAS_PEAK_LEVEL) {
-            url_fseek(pb, 4, SEEK_CUR); /* Skip the peak level */
+            avio_skip(pb, 4); /* Skip the peak level */
             ape->headerlength += 4;
         }
 
         if (ape->formatflags & MAC_FORMAT_FLAG_HAS_SEEK_ELEMENTS) {
-            ape->seektablelength = get_le32(pb);
+            ape->seektablelength = avio_rl32(pb);
             ape->headerlength += 4;
             ape->seektablelength *= sizeof(int32_t);
         } else
@@ -239,13 +239,22 @@ static int ape_read_header(AVFormatContext * s, AVFormatParameters * ap)
 
         /* Skip any stored wav header */
         if (!(ape->formatflags & MAC_FORMAT_FLAG_CREATE_WAV_HEADER))
-            url_fskip(pb, ape->wavheaderlength);
+            avio_skip(pb, ape->wavheaderlength);
     }
 
+    if(!ape->totalframes){
+        av_log(s, AV_LOG_ERROR, "No frames in the file!\n");
+        return AVERROR(EINVAL);
+    }
     if(ape->totalframes > UINT_MAX / sizeof(APEFrame)){
         av_log(s, AV_LOG_ERROR, "Too many frames: %d\n", ape->totalframes);
         return -1;
     }
+    if (ape->seektablelength && (ape->seektablelength / sizeof(*ape->seektable)) < ape->totalframes) {
+        av_log(s, AV_LOG_ERROR, "Number of seek entries is less than number of frames: %d vs. %d\n",
+               ape->seektablelength / sizeof(*ape->seektable), ape->totalframes);
+        return AVERROR_INVALIDDATA;
+    }
     ape->frames       = av_malloc(ape->totalframes * sizeof(APEFrame));
     if(!ape->frames)
         return AVERROR(ENOMEM);
@@ -260,7 +269,7 @@ static int ape_read_header(AVFormatContext * s, AVFormatParameters * ap)
     if (ape->seektablelength > 0) {
         ape->seektable = av_malloc(ape->seektablelength);
         for (i = 0; i < ape->seektablelength / sizeof(uint32_t); i++)
-            ape->seektable[i] = get_le32(pb);
+            ape->seektable[i] = avio_rl32(pb);
     }
 
     ape->frames[0].pos     = ape->firstframe;
@@ -287,9 +296,9 @@ static int ape_read_header(AVFormatContext * s, AVFormatParameters * ap)
     ape_dumpinfo(s, ape);
 
     /* try to read APE tags */
-    if (!url_is_streamed(pb)) {
+    if (pb->seekable) {
         ff_ape_parse_tag(s);
-        url_fseek(pb, 0, SEEK_SET);
+        avio_seek(pb, 0, SEEK_SET);
     }
 
     av_log(s, AV_LOG_DEBUG, "Decoding file - v%d.%02d, compression level %d\n", ape->fileversion / 1000, (ape->fileversion % 1000) / 10, ape->compressiontype);
@@ -337,12 +346,12 @@ static int ape_read_packet(AVFormatContext * s, AVPacket * pkt)
     APEContext *ape = s->priv_data;
     uint32_t extra_size = 8;
 
-    if (url_feof(s->pb))
+    if (s->pb->eof_reached)
         return AVERROR(EIO);
     if (ape->currentframe > ape->totalframes)
         return AVERROR(EIO);
 
-    url_fseek (s->pb, ape->frames[ape->currentframe].pos, SEEK_SET);
+    avio_seek (s->pb, ape->frames[ape->currentframe].pos, SEEK_SET);
 
     /* Calculate how many blocks there are in this frame */
     if (ape->currentframe == (ape->totalframes - 1))
@@ -355,7 +364,7 @@ static int ape_read_packet(AVFormatContext * s, AVPacket * pkt)
 
     AV_WL32(pkt->data    , nblocks);
     AV_WL32(pkt->data + 4, ape->frames[ape->currentframe].skip);
-    ret = get_buffer(s->pb, pkt->data + extra_size, ape->frames[ape->currentframe].size);
+    ret = avio_read(s->pb, pkt->data + extra_size, ape->frames[ape->currentframe].size);
 
     pkt->pts = ape->frames[ape->currentframe].pts;
     pkt->stream_index = 0;
@@ -391,7 +400,7 @@ static int ape_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp
     return 0;
 }
 
-AVInputFormat ape_demuxer = {
+AVInputFormat ff_ape_demuxer = {
     "ape",
     NULL_IF_CONFIG_SMALL("Monkey's Audio"),
     sizeof(APEContext),
diff --git a/libavformat/apetag.c b/libavformat/apetag.c
index d30c132..b8a460a 100644
--- a/libavformat/apetag.c
+++ b/libavformat/apetag.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2007 Benjamin Zores <ben at geexbox.org>
  *  based upon libdemac from Dave Chapman.
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -33,15 +33,15 @@
 
 static int ape_tag_read_field(AVFormatContext *s)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     uint8_t key[1024], *value;
     uint32_t size, flags;
     int i, c;
 
-    size = get_le32(pb);  /* field size */
-    flags = get_le32(pb); /* field flags */
+    size = avio_rl32(pb);  /* field size */
+    flags = avio_rl32(pb); /* field flags */
     for (i = 0; i < sizeof(key) - 1; i++) {
-        c = get_byte(pb);
+        c = avio_r8(pb);
         if (c < 0x20 || c > 0x7E)
             break;
         else
@@ -57,7 +57,7 @@ static int ape_tag_read_field(AVFormatContext *s)
     value = av_malloc(size+1);
     if (!value)
         return AVERROR(ENOMEM);
-    get_buffer(pb, value, size);
+    avio_read(pb, value, size);
     value[size] = 0;
     av_metadata_set2(&s->metadata, key, value, AV_METADATA_DONT_STRDUP_VAL);
     return 0;
@@ -65,8 +65,8 @@ static int ape_tag_read_field(AVFormatContext *s)
 
 void ff_ape_parse_tag(AVFormatContext *s)
 {
-    ByteIOContext *pb = s->pb;
-    int file_size = url_fsize(pb);
+    AVIOContext *pb = s->pb;
+    int file_size = avio_size(pb);
     uint32_t val, fields, tag_bytes;
     uint8_t buf[8];
     int i;
@@ -74,38 +74,38 @@ void ff_ape_parse_tag(AVFormatContext *s)
     if (file_size < APE_TAG_FOOTER_BYTES)
         return;
 
-    url_fseek(pb, file_size - APE_TAG_FOOTER_BYTES, SEEK_SET);
+    avio_seek(pb, file_size - APE_TAG_FOOTER_BYTES, SEEK_SET);
 
-    get_buffer(pb, buf, 8);    /* APETAGEX */
+    avio_read(pb, buf, 8);     /* APETAGEX */
     if (strncmp(buf, "APETAGEX", 8)) {
         return;
     }
 
-    val = get_le32(pb);        /* APE tag version */
+    val = avio_rl32(pb);       /* APE tag version */
     if (val > APE_TAG_VERSION) {
         av_log(s, AV_LOG_ERROR, "Unsupported tag version. (>=%d)\n", APE_TAG_VERSION);
         return;
     }
 
-    tag_bytes = get_le32(pb);  /* tag size */
+    tag_bytes = avio_rl32(pb); /* tag size */
     if (tag_bytes - APE_TAG_FOOTER_BYTES > (1024 * 1024 * 16)) {
         av_log(s, AV_LOG_ERROR, "Tag size is way too big\n");
         return;
     }
 
-    fields = get_le32(pb);     /* number of fields */
+    fields = avio_rl32(pb);    /* number of fields */
     if (fields > 65536) {
         av_log(s, AV_LOG_ERROR, "Too many tag fields (%d)\n", fields);
         return;
     }
 
-    val = get_le32(pb);        /* flags */
+    val = avio_rl32(pb);       /* flags */
     if (val & APE_TAG_FLAG_IS_HEADER) {
         av_log(s, AV_LOG_ERROR, "APE Tag is a header\n");
         return;
     }
 
-    url_fseek(pb, file_size - tag_bytes, SEEK_SET);
+    avio_seek(pb, file_size - tag_bytes, SEEK_SET);
 
     for (i=0; i<fields; i++)
         if (ape_tag_read_field(s) < 0) break;
diff --git a/libavformat/apetag.h b/libavformat/apetag.h
index 8aaef68..9a39d02 100644
--- a/libavformat/apetag.h
+++ b/libavformat/apetag.h
@@ -3,20 +3,20 @@
  * Copyright (c) 2007 Benjamin Zores <ben at geexbox.org>
  *  based upon libdemac from Dave Chapman.
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavformat/applehttp.c b/libavformat/applehttp.c
new file mode 100644
index 0000000..35759be
--- /dev/null
+++ b/libavformat/applehttp.c
@@ -0,0 +1,566 @@
+/*
+ * Apple HTTP Live Streaming demuxer
+ * Copyright (c) 2010 Martin Storsjo
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * Apple HTTP Live Streaming demuxer
+ * http://tools.ietf.org/html/draft-pantos-http-live-streaming
+ */
+
+#define _XOPEN_SOURCE 600
+#include "libavutil/avstring.h"
+#include "avformat.h"
+#include "internal.h"
+#include <unistd.h>
+#include "avio_internal.h"
+#include "url.h"
+
+#define INITIAL_BUFFER_SIZE 32768
+
+/*
+ * An apple http stream consists of a playlist with media segment files,
+ * played sequentially. There may be several playlists with the same
+ * video content, in different bandwidth variants, that are played in
+ * parallel (preferrably only one bandwidth variant at a time). In this case,
+ * the user supplied the url to a main playlist that only lists the variant
+ * playlists.
+ *
+ * If the main playlist doesn't point at any variants, we still create
+ * one anonymous toplevel variant for this, to maintain the structure.
+ */
+
+struct segment {
+    int duration;
+    char url[MAX_URL_SIZE];
+};
+
+/*
+ * Each variant has its own demuxer. If it currently is active,
+ * it has an open AVIOContext too, and potentially an AVPacket
+ * containing the next packet from this stream.
+ */
+struct variant {
+    int bandwidth;
+    char url[MAX_URL_SIZE];
+    AVIOContext pb;
+    uint8_t* read_buffer;
+    URLContext *input;
+    AVFormatContext *parent;
+    int index;
+    AVFormatContext *ctx;
+    AVPacket pkt;
+    int stream_offset;
+
+    int finished;
+    int target_duration;
+    int start_seq_no;
+    int n_segments;
+    struct segment **segments;
+    int needed, cur_needed;
+    int cur_seq_no;
+    int64_t last_load_time;
+};
+
+typedef struct AppleHTTPContext {
+    int n_variants;
+    struct variant **variants;
+    int cur_seq_no;
+    int end_of_segment;
+    int first_packet;
+} AppleHTTPContext;
+
+static int read_chomp_line(AVIOContext *s, char *buf, int maxlen)
+{
+    int len = ff_get_line(s, buf, maxlen);
+    while (len > 0 && isspace(buf[len - 1]))
+        buf[--len] = '\0';
+    return len;
+}
+
+static void free_segment_list(struct variant *var)
+{
+    int i;
+    for (i = 0; i < var->n_segments; i++)
+        av_free(var->segments[i]);
+    av_freep(&var->segments);
+    var->n_segments = 0;
+}
+
+static void free_variant_list(AppleHTTPContext *c)
+{
+    int i;
+    for (i = 0; i < c->n_variants; i++) {
+        struct variant *var = c->variants[i];
+        free_segment_list(var);
+        av_free_packet(&var->pkt);
+        av_free(var->pb.buffer);
+        if (var->input)
+            ffurl_close(var->input);
+        if (var->ctx) {
+            var->ctx->pb = NULL;
+            av_close_input_file(var->ctx);
+        }
+        av_free(var);
+    }
+    av_freep(&c->variants);
+    c->n_variants = 0;
+}
+
+/*
+ * Used to reset a statically allocated AVPacket to a clean slate,
+ * containing no data.
+ */
+static void reset_packet(AVPacket *pkt)
+{
+    av_init_packet(pkt);
+    pkt->data = NULL;
+}
+
+static struct variant *new_variant(AppleHTTPContext *c, int bandwidth,
+                                   const char *url, const char *base)
+{
+    struct variant *var = av_mallocz(sizeof(struct variant));
+    if (!var)
+        return NULL;
+    reset_packet(&var->pkt);
+    var->bandwidth = bandwidth;
+    ff_make_absolute_url(var->url, sizeof(var->url), base, url);
+    dynarray_add(&c->variants, &c->n_variants, var);
+    return var;
+}
+
+struct variant_info {
+    char bandwidth[20];
+};
+
+static void handle_variant_args(struct variant_info *info, const char *key,
+                                int key_len, char **dest, int *dest_len)
+{
+    if (!strncmp(key, "BANDWIDTH=", key_len)) {
+        *dest     =        info->bandwidth;
+        *dest_len = sizeof(info->bandwidth);
+    }
+}
+
+static int parse_playlist(AppleHTTPContext *c, const char *url,
+                          struct variant *var, AVIOContext *in)
+{
+    int ret = 0, duration = 0, is_segment = 0, is_variant = 0, bandwidth = 0;
+    char line[1024];
+    const char *ptr;
+    int close_in = 0;
+
+    if (!in) {
+        close_in = 1;
+        if ((ret = avio_open(&in, url, AVIO_RDONLY)) < 0)
+            return ret;
+    }
+
+    read_chomp_line(in, line, sizeof(line));
+    if (strcmp(line, "#EXTM3U")) {
+        ret = AVERROR_INVALIDDATA;
+        goto fail;
+    }
+
+    if (var) {
+        free_segment_list(var);
+        var->finished = 0;
+    }
+    while (!in->eof_reached) {
+        read_chomp_line(in, line, sizeof(line));
+        if (av_strstart(line, "#EXT-X-STREAM-INF:", &ptr)) {
+            struct variant_info info = {{0}};
+            is_variant = 1;
+            ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_variant_args,
+                               &info);
+            bandwidth = atoi(info.bandwidth);
+        } else if (av_strstart(line, "#EXT-X-TARGETDURATION:", &ptr)) {
+            if (!var) {
+                var = new_variant(c, 0, url, NULL);
+                if (!var) {
+                    ret = AVERROR(ENOMEM);
+                    goto fail;
+                }
+            }
+            var->target_duration = atoi(ptr);
+        } else if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {
+            if (!var) {
+                var = new_variant(c, 0, url, NULL);
+                if (!var) {
+                    ret = AVERROR(ENOMEM);
+                    goto fail;
+                }
+            }
+            var->start_seq_no = atoi(ptr);
+        } else if (av_strstart(line, "#EXT-X-ENDLIST", &ptr)) {
+            if (var)
+                var->finished = 1;
+        } else if (av_strstart(line, "#EXTINF:", &ptr)) {
+            is_segment = 1;
+            duration   = atoi(ptr);
+        } else if (av_strstart(line, "#", NULL)) {
+            continue;
+        } else if (line[0]) {
+            if (is_variant) {
+                if (!new_variant(c, bandwidth, line, url)) {
+                    ret = AVERROR(ENOMEM);
+                    goto fail;
+                }
+                is_variant = 0;
+                bandwidth  = 0;
+            }
+            if (is_segment) {
+                struct segment *seg;
+                if (!var) {
+                    var = new_variant(c, 0, url, NULL);
+                    if (!var) {
+                        ret = AVERROR(ENOMEM);
+                        goto fail;
+                    }
+                }
+                seg = av_malloc(sizeof(struct segment));
+                if (!seg) {
+                    ret = AVERROR(ENOMEM);
+                    goto fail;
+                }
+                seg->duration = duration;
+                ff_make_absolute_url(seg->url, sizeof(seg->url), url, line);
+                dynarray_add(&var->segments, &var->n_segments, seg);
+                is_segment = 0;
+            }
+        }
+    }
+    if (var)
+        var->last_load_time = av_gettime();
+
+fail:
+    if (close_in)
+        avio_close(in);
+    return ret;
+}
+
+static int read_data(void *opaque, uint8_t *buf, int buf_size)
+{
+    struct variant *v = opaque;
+    AppleHTTPContext *c = v->parent->priv_data;
+    int ret, i;
+
+restart:
+    if (!v->input) {
+reload:
+        /* If this is a live stream and target_duration has elapsed since
+         * the last playlist reload, reload the variant playlists now. */
+        if (!v->finished &&
+            av_gettime() - v->last_load_time >= v->target_duration*1000000 &&
+            (ret = parse_playlist(c, v->url, v, NULL)) < 0)
+                return ret;
+        if (v->cur_seq_no < v->start_seq_no) {
+            av_log(NULL, AV_LOG_WARNING,
+                   "skipping %d segments ahead, expired from playlists\n",
+                   v->start_seq_no - v->cur_seq_no);
+            v->cur_seq_no = v->start_seq_no;
+        }
+        if (v->cur_seq_no >= v->start_seq_no + v->n_segments) {
+            if (v->finished)
+                return AVERROR_EOF;
+            while (av_gettime() - v->last_load_time <
+                   v->target_duration*1000000) {
+                if (url_interrupt_cb())
+                    return AVERROR_EXIT;
+                usleep(100*1000);
+            }
+            /* Enough time has elapsed since the last reload */
+            goto reload;
+        }
+
+        ret = ffurl_open(&v->input,
+                         v->segments[v->cur_seq_no - v->start_seq_no]->url,
+                         AVIO_RDONLY);
+        if (ret < 0)
+            return ret;
+    }
+    ret = ffurl_read(v->input, buf, buf_size);
+    if (ret > 0)
+        return ret;
+    if (ret < 0 && ret != AVERROR_EOF)
+        return ret;
+    ffurl_close(v->input);
+    v->input = NULL;
+    v->cur_seq_no++;
+
+    c->end_of_segment = 1;
+    c->cur_seq_no = v->cur_seq_no;
+
+    if (v->ctx) {
+        v->needed = 0;
+        for (i = v->stream_offset; i < v->stream_offset + v->ctx->nb_streams;
+             i++) {
+            if (v->parent->streams[i]->discard < AVDISCARD_ALL)
+                v->needed = 1;
+        }
+    }
+    if (!v->needed) {
+        av_log(v->parent, AV_LOG_INFO, "No longer receiving variant %d\n",
+               v->index);
+        return AVERROR_EOF;
+    }
+    goto restart;
+}
+
+static int applehttp_read_header(AVFormatContext *s, AVFormatParameters *ap)
+{
+    AppleHTTPContext *c = s->priv_data;
+    int ret = 0, i, j, stream_offset = 0;
+
+    if ((ret = parse_playlist(c, s->filename, NULL, s->pb)) < 0)
+        goto fail;
+
+    if (c->n_variants == 0) {
+        av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
+        ret = AVERROR_EOF;
+        goto fail;
+    }
+    /* If the playlist only contained variants, parse each individual
+     * variant playlist. */
+    if (c->n_variants > 1 || c->variants[0]->n_segments == 0) {
+        for (i = 0; i < c->n_variants; i++) {
+            struct variant *v = c->variants[i];
+            if ((ret = parse_playlist(c, v->url, v, NULL)) < 0)
+                goto fail;
+        }
+    }
+
+    if (c->variants[0]->n_segments == 0) {
+        av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
+        ret = AVERROR_EOF;
+        goto fail;
+    }
+
+    /* If this isn't a live stream, calculate the total duration of the
+     * stream. */
+    if (c->variants[0]->finished) {
+        int64_t duration = 0;
+        for (i = 0; i < c->variants[0]->n_segments; i++)
+            duration += c->variants[0]->segments[i]->duration;
+        s->duration = duration * AV_TIME_BASE;
+    }
+
+    /* Open the demuxer for each variant */
+    for (i = 0; i < c->n_variants; i++) {
+        struct variant *v = c->variants[i];
+        AVInputFormat *in_fmt = NULL;
+        if (v->n_segments == 0)
+            continue;
+
+        v->index  = i;
+        v->needed = 1;
+        v->parent = s;
+
+        /* If this is a live stream with more than 3 segments, start at the
+         * third last segment. */
+        v->cur_seq_no = v->start_seq_no;
+        if (!v->finished && v->n_segments > 3)
+            v->cur_seq_no = v->start_seq_no + v->n_segments - 3;
+
+        v->read_buffer = av_malloc(INITIAL_BUFFER_SIZE);
+        ffio_init_context(&v->pb, v->read_buffer, INITIAL_BUFFER_SIZE, 0, v,
+                          read_data, NULL, NULL);
+        v->pb.seekable = 0;
+        ret = av_probe_input_buffer(&v->pb, &in_fmt, v->segments[0]->url,
+                                    NULL, 0, 0);
+        if (ret < 0)
+            goto fail;
+        ret = av_open_input_stream(&v->ctx, &v->pb, v->segments[0]->url,
+                                   in_fmt, NULL);
+        if (ret < 0)
+            goto fail;
+        v->stream_offset = stream_offset;
+        /* Create new AVStreams for each stream in this variant */
+        for (j = 0; j < v->ctx->nb_streams; j++) {
+            AVStream *st = av_new_stream(s, i);
+            if (!st) {
+                ret = AVERROR(ENOMEM);
+                goto fail;
+            }
+            avcodec_copy_context(st->codec, v->ctx->streams[j]->codec);
+        }
+        stream_offset += v->ctx->nb_streams;
+    }
+
+    c->first_packet = 1;
+
+    return 0;
+fail:
+    free_variant_list(c);
+    return ret;
+}
+
+static int recheck_discard_flags(AVFormatContext *s, int first)
+{
+    AppleHTTPContext *c = s->priv_data;
+    int i, changed = 0;
+
+    /* Check if any new streams are needed */
+    for (i = 0; i < c->n_variants; i++)
+        c->variants[i]->cur_needed = 0;;
+
+    for (i = 0; i < s->nb_streams; i++) {
+        AVStream *st = s->streams[i];
+        struct variant *var = c->variants[s->streams[i]->id];
+        if (st->discard < AVDISCARD_ALL)
+            var->cur_needed = 1;
+    }
+    for (i = 0; i < c->n_variants; i++) {
+        struct variant *v = c->variants[i];
+        if (v->cur_needed && !v->needed) {
+            v->needed = 1;
+            changed = 1;
+            v->cur_seq_no = c->cur_seq_no;
+            v->pb.eof_reached = 0;
+            av_log(s, AV_LOG_INFO, "Now receiving variant %d\n", i);
+        } else if (first && !v->cur_needed && v->needed) {
+            if (v->input)
+                ffurl_close(v->input);
+            v->input = NULL;
+            v->needed = 0;
+            changed = 1;
+            av_log(s, AV_LOG_INFO, "No longer receiving variant %d\n", i);
+        }
+    }
+    return changed;
+}
+
+static int applehttp_read_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    AppleHTTPContext *c = s->priv_data;
+    int ret, i, minvariant = -1;
+
+    if (c->first_packet) {
+        recheck_discard_flags(s, 1);
+        c->first_packet = 0;
+    }
+
+start:
+    c->end_of_segment = 0;
+    for (i = 0; i < c->n_variants; i++) {
+        struct variant *var = c->variants[i];
+        /* Make sure we've got one buffered packet from each open variant
+         * stream */
+        if (var->needed && !var->pkt.data) {
+            ret = av_read_frame(var->ctx, &var->pkt);
+            if (ret < 0) {
+                if (!var->pb.eof_reached)
+                    return ret;
+                reset_packet(&var->pkt);
+            }
+        }
+        /* Check if this stream has the packet with the lowest dts */
+        if (var->pkt.data) {
+            if (minvariant < 0 ||
+                var->pkt.dts < c->variants[minvariant]->pkt.dts)
+                minvariant = i;
+        }
+    }
+    if (c->end_of_segment) {
+        if (recheck_discard_flags(s, 0))
+            goto start;
+    }
+    /* If we got a packet, return it */
+    if (minvariant >= 0) {
+        *pkt = c->variants[minvariant]->pkt;
+        pkt->stream_index += c->variants[minvariant]->stream_offset;
+        reset_packet(&c->variants[minvariant]->pkt);
+        return 0;
+    }
+    return AVERROR_EOF;
+}
+
+static int applehttp_close(AVFormatContext *s)
+{
+    AppleHTTPContext *c = s->priv_data;
+
+    free_variant_list(c);
+    return 0;
+}
+
+static int applehttp_read_seek(AVFormatContext *s, int stream_index,
+                               int64_t timestamp, int flags)
+{
+    AppleHTTPContext *c = s->priv_data;
+    int i, j, ret;
+
+    if ((flags & AVSEEK_FLAG_BYTE) || !c->variants[0]->finished)
+        return AVERROR(ENOSYS);
+
+    timestamp = av_rescale_rnd(timestamp, 1, stream_index >= 0 ?
+                               s->streams[stream_index]->time_base.den :
+                               AV_TIME_BASE, flags & AVSEEK_FLAG_BACKWARD ?
+                               AV_ROUND_DOWN : AV_ROUND_UP);
+    ret = AVERROR(EIO);
+    for (i = 0; i < c->n_variants; i++) {
+        /* Reset reading */
+        struct variant *var = c->variants[i];
+        int64_t pos = 0;
+        if (var->input) {
+            ffurl_close(var->input);
+            var->input = NULL;
+        }
+        av_free_packet(&var->pkt);
+        reset_packet(&var->pkt);
+        var->pb.eof_reached = 0;
+
+        /* Locate the segment that contains the target timestamp */
+        for (j = 0; j < var->n_segments; j++) {
+            if (timestamp >= pos &&
+                timestamp < pos + var->segments[j]->duration) {
+                var->cur_seq_no = var->start_seq_no + j;
+                ret = 0;
+                break;
+            }
+            pos += var->segments[j]->duration;
+        }
+    }
+    return ret;
+}
+
+static int applehttp_probe(AVProbeData *p)
+{
+    /* Require #EXTM3U at the start, and either one of the ones below
+     * somewhere for a proper match. */
+    if (strncmp(p->buf, "#EXTM3U", 7))
+        return 0;
+    if (strstr(p->buf, "#EXT-X-STREAM-INF:")     ||
+        strstr(p->buf, "#EXT-X-TARGETDURATION:") ||
+        strstr(p->buf, "#EXT-X-MEDIA-SEQUENCE:"))
+        return AVPROBE_SCORE_MAX;
+    return 0;
+}
+
+AVInputFormat ff_applehttp_demuxer = {
+    "applehttp",
+    NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming format"),
+    sizeof(AppleHTTPContext),
+    applehttp_probe,
+    applehttp_read_header,
+    applehttp_read_packet,
+    applehttp_close,
+    applehttp_read_seek,
+};
diff --git a/libavformat/applehttpproto.c b/libavformat/applehttpproto.c
new file mode 100644
index 0000000..8842bd4
--- /dev/null
+++ b/libavformat/applehttpproto.c
@@ -0,0 +1,306 @@
+/*
+ * Apple HTTP Live Streaming Protocol Handler
+ * Copyright (c) 2010 Martin Storsjo
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * Apple HTTP Live Streaming Protocol Handler
+ * http://tools.ietf.org/html/draft-pantos-http-live-streaming
+ */
+
+#define _XOPEN_SOURCE 600
+#include "libavutil/avstring.h"
+#include "avformat.h"
+#include "internal.h"
+#include "url.h"
+#include <unistd.h>
+
+/*
+ * An apple http stream consists of a playlist with media segment files,
+ * played sequentially. There may be several playlists with the same
+ * video content, in different bandwidth variants, that are played in
+ * parallel (preferrably only one bandwidth variant at a time). In this case,
+ * the user supplied the url to a main playlist that only lists the variant
+ * playlists.
+ *
+ * If the main playlist doesn't point at any variants, we still create
+ * one anonymous toplevel variant for this, to maintain the structure.
+ */
+
+struct segment {
+    int duration;
+    char url[MAX_URL_SIZE];
+};
+
+struct variant {
+    int bandwidth;
+    char url[MAX_URL_SIZE];
+};
+
+typedef struct AppleHTTPContext {
+    char playlisturl[MAX_URL_SIZE];
+    int target_duration;
+    int start_seq_no;
+    int finished;
+    int n_segments;
+    struct segment **segments;
+    int n_variants;
+    struct variant **variants;
+    int cur_seq_no;
+    URLContext *seg_hd;
+    int64_t last_load_time;
+} AppleHTTPContext;
+
+static int read_chomp_line(AVIOContext *s, char *buf, int maxlen)
+{
+    int len = ff_get_line(s, buf, maxlen);
+    while (len > 0 && isspace(buf[len - 1]))
+        buf[--len] = '\0';
+    return len;
+}
+
+static void free_segment_list(AppleHTTPContext *s)
+{
+    int i;
+    for (i = 0; i < s->n_segments; i++)
+        av_free(s->segments[i]);
+    av_freep(&s->segments);
+    s->n_segments = 0;
+}
+
+static void free_variant_list(AppleHTTPContext *s)
+{
+    int i;
+    for (i = 0; i < s->n_variants; i++)
+        av_free(s->variants[i]);
+    av_freep(&s->variants);
+    s->n_variants = 0;
+}
+
+struct variant_info {
+    char bandwidth[20];
+};
+
+static void handle_variant_args(struct variant_info *info, const char *key,
+                                int key_len, char **dest, int *dest_len)
+{
+    if (!strncmp(key, "BANDWIDTH=", key_len)) {
+        *dest     =        info->bandwidth;
+        *dest_len = sizeof(info->bandwidth);
+    }
+}
+
+static int parse_playlist(URLContext *h, const char *url)
+{
+    AppleHTTPContext *s = h->priv_data;
+    AVIOContext *in;
+    int ret = 0, duration = 0, is_segment = 0, is_variant = 0, bandwidth = 0;
+    char line[1024];
+    const char *ptr;
+
+    if ((ret = avio_open(&in, url, AVIO_RDONLY)) < 0)
+        return ret;
+
+    read_chomp_line(in, line, sizeof(line));
+    if (strcmp(line, "#EXTM3U"))
+        return AVERROR_INVALIDDATA;
+
+    free_segment_list(s);
+    s->finished = 0;
+    while (!in->eof_reached) {
+        read_chomp_line(in, line, sizeof(line));
+        if (av_strstart(line, "#EXT-X-STREAM-INF:", &ptr)) {
+            struct variant_info info = {{0}};
+            is_variant = 1;
+            ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_variant_args,
+                               &info);
+            bandwidth = atoi(info.bandwidth);
+        } else if (av_strstart(line, "#EXT-X-TARGETDURATION:", &ptr)) {
+            s->target_duration = atoi(ptr);
+        } else if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {
+            s->start_seq_no = atoi(ptr);
+        } else if (av_strstart(line, "#EXT-X-ENDLIST", &ptr)) {
+            s->finished = 1;
+        } else if (av_strstart(line, "#EXTINF:", &ptr)) {
+            is_segment = 1;
+            duration = atoi(ptr);
+        } else if (av_strstart(line, "#", NULL)) {
+            continue;
+        } else if (line[0]) {
+            if (is_segment) {
+                struct segment *seg = av_malloc(sizeof(struct segment));
+                if (!seg) {
+                    ret = AVERROR(ENOMEM);
+                    goto fail;
+                }
+                seg->duration = duration;
+                ff_make_absolute_url(seg->url, sizeof(seg->url), url, line);
+                dynarray_add(&s->segments, &s->n_segments, seg);
+                is_segment = 0;
+            } else if (is_variant) {
+                struct variant *var = av_malloc(sizeof(struct variant));
+                if (!var) {
+                    ret = AVERROR(ENOMEM);
+                    goto fail;
+                }
+                var->bandwidth = bandwidth;
+                ff_make_absolute_url(var->url, sizeof(var->url), url, line);
+                dynarray_add(&s->variants, &s->n_variants, var);
+                is_variant = 0;
+            }
+        }
+    }
+    s->last_load_time = av_gettime();
+
+fail:
+    avio_close(in);
+    return ret;
+}
+
+static int applehttp_open(URLContext *h, const char *uri, int flags)
+{
+    AppleHTTPContext *s;
+    int ret, i;
+    const char *nested_url;
+
+    if (flags & (AVIO_WRONLY | AVIO_RDWR))
+        return AVERROR(ENOSYS);
+
+    s = av_mallocz(sizeof(AppleHTTPContext));
+    if (!s)
+        return AVERROR(ENOMEM);
+    h->priv_data = s;
+    h->is_streamed = 1;
+
+    if (av_strstart(uri, "applehttp+", &nested_url)) {
+        av_strlcpy(s->playlisturl, nested_url, sizeof(s->playlisturl));
+    } else if (av_strstart(uri, "applehttp://", &nested_url)) {
+        av_strlcpy(s->playlisturl, "http://", sizeof(s->playlisturl));
+        av_strlcat(s->playlisturl, nested_url, sizeof(s->playlisturl));
+    } else {
+        av_log(NULL, AV_LOG_ERROR, "Unsupported url %s\n", uri);
+        ret = AVERROR(EINVAL);
+        goto fail;
+    }
+
+    if ((ret = parse_playlist(h, s->playlisturl)) < 0)
+        goto fail;
+
+    if (s->n_segments == 0 && s->n_variants > 0) {
+        int max_bandwidth = 0, maxvar = -1;
+        for (i = 0; i < s->n_variants; i++) {
+            if (s->variants[i]->bandwidth > max_bandwidth || i == 0) {
+                max_bandwidth = s->variants[i]->bandwidth;
+                maxvar = i;
+            }
+        }
+        av_strlcpy(s->playlisturl, s->variants[maxvar]->url,
+                   sizeof(s->playlisturl));
+        if ((ret = parse_playlist(h, s->playlisturl)) < 0)
+            goto fail;
+    }
+
+    if (s->n_segments == 0) {
+        av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
+        ret = AVERROR(EIO);
+        goto fail;
+    }
+    s->cur_seq_no = s->start_seq_no;
+    if (!s->finished && s->n_segments >= 3)
+        s->cur_seq_no = s->start_seq_no + s->n_segments - 3;
+
+    return 0;
+
+fail:
+    av_free(s);
+    return ret;
+}
+
+static int applehttp_read(URLContext *h, uint8_t *buf, int size)
+{
+    AppleHTTPContext *s = h->priv_data;
+    const char *url;
+    int ret;
+
+start:
+    if (s->seg_hd) {
+        ret = ffurl_read(s->seg_hd, buf, size);
+        if (ret > 0)
+            return ret;
+    }
+    if (s->seg_hd) {
+        ffurl_close(s->seg_hd);
+        s->seg_hd = NULL;
+        s->cur_seq_no++;
+    }
+retry:
+    if (!s->finished) {
+        int64_t now = av_gettime();
+        if (now - s->last_load_time >= s->target_duration*1000000)
+            if ((ret = parse_playlist(h, s->playlisturl)) < 0)
+                return ret;
+    }
+    if (s->cur_seq_no < s->start_seq_no) {
+        av_log(NULL, AV_LOG_WARNING,
+               "skipping %d segments ahead, expired from playlist\n",
+               s->start_seq_no - s->cur_seq_no);
+        s->cur_seq_no = s->start_seq_no;
+    }
+    if (s->cur_seq_no - s->start_seq_no >= s->n_segments) {
+        if (s->finished)
+            return AVERROR_EOF;
+        while (av_gettime() - s->last_load_time < s->target_duration*1000000) {
+            if (url_interrupt_cb())
+                return AVERROR_EXIT;
+            usleep(100*1000);
+        }
+        goto retry;
+    }
+    url = s->segments[s->cur_seq_no - s->start_seq_no]->url,
+    av_log(NULL, AV_LOG_DEBUG, "opening %s\n", url);
+    ret = ffurl_open(&s->seg_hd, url, AVIO_RDONLY);
+    if (ret < 0) {
+        if (url_interrupt_cb())
+            return AVERROR_EXIT;
+        av_log(NULL, AV_LOG_WARNING, "Unable to open %s\n", url);
+        s->cur_seq_no++;
+        goto retry;
+    }
+    goto start;
+}
+
+static int applehttp_close(URLContext *h)
+{
+    AppleHTTPContext *s = h->priv_data;
+
+    free_segment_list(s);
+    free_variant_list(s);
+    ffurl_close(s->seg_hd);
+    av_free(s);
+    return 0;
+}
+
+URLProtocol ff_applehttp_protocol = {
+    .name      = "applehttp",
+    .url_open  = applehttp_open,
+    .url_read  = applehttp_read,
+    .url_close = applehttp_close,
+    .flags     = URL_PROTOCOL_FLAG_NESTED_SCHEME,
+};
diff --git a/libavformat/asf.c b/libavformat/asf.c
index e25ac03..cc2833d 100644
--- a/libavformat/asf.c
+++ b/libavformat/asf.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2000, 2001 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -55,6 +55,10 @@ const ff_asf_guid ff_asf_video_stream = {
     0xC0, 0xEF, 0x19, 0xBC, 0x4D, 0x5B, 0xCF, 0x11, 0xA8, 0xFD, 0x00, 0x80, 0x5F, 0x5C, 0x44, 0x2B
 };
 
+const ff_asf_guid ff_asf_jfif_media = {
+    0x00, 0xE1, 0x1B, 0xB6, 0x4E, 0x5B, 0xCF, 0x11, 0xA8, 0xFD, 0x00, 0x80, 0x5F, 0x5C, 0x44, 0x2B
+};
+
 const ff_asf_guid ff_asf_video_conceal_none = {
     0x00, 0x57, 0xFB, 0x20, 0x55, 0x5B, 0xCF, 0x11, 0xA8, 0xFD, 0x00, 0x80, 0x5F, 0x5C, 0x44, 0x2B
 };
@@ -149,23 +153,8 @@ const AVMetadataConv ff_asf_metadata_conv[] = {
     { "WM/Tool"            , "encoder"     },
     { "WM/TrackNumber"     , "track"       },
     { "WM/Track"           , "track"       },
+    { "WM/MediaStationCallSign", "service_provider" },
+    { "WM/MediaStationName", "service_name" },
 //  { "Year"               , "date"        }, TODO: conversion year<->date
     { 0 }
 };
-
-int ff_put_str16_nolen(ByteIOContext *s, const char *tag)
-{
-    const uint8_t *q = tag;
-    int ret = 0;
-
-    while (*q) {
-        uint32_t ch;
-        uint16_t tmp;
-
-        GET_UTF8(ch, *q++, break;)
-        PUT_UTF16(ch, tmp, put_le16(s, tmp);ret += 2;)
-    }
-    put_le16(s, 0);
-    ret += 2;
-    return ret;
-}
diff --git a/libavformat/asf.h b/libavformat/asf.h
index 85e54cc..b72445d 100644
--- a/libavformat/asf.h
+++ b/libavformat/asf.h
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2000, 2001 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -44,6 +44,8 @@ typedef struct {
 
     uint16_t stream_language_index;
 
+    int      palette_changed;
+    uint32_t palette[256];
 } ASFStream;
 
 typedef uint8_t ff_asf_guid[16];
@@ -79,64 +81,6 @@ typedef struct {
     uint16_t packet_count;
 } ASFIndex;
 
-
-typedef struct {
-    uint32_t seqno;
-    int is_streamed;
-    int asfid2avid[128];                 ///< conversion table from asf ID 2 AVStream ID
-    ASFStream streams[128];              ///< it's max number and it's not that big
-    uint32_t stream_bitrates[128];       ///< max number of streams, bitrate for each (for streaming)
-    char stream_languages[128][6];       ///< max number of streams, language for each (RFC1766, e.g. en-US)
-    /* non streamed additonnal info */
-    uint64_t nb_packets;                 ///< how many packets are there in the file, invalid if broadcasting
-    int64_t duration;                    ///< in 100ns units
-    /* packet filling */
-    unsigned char multi_payloads_present;
-    int packet_size_left;
-    int packet_timestamp_start;
-    int packet_timestamp_end;
-    unsigned int packet_nb_payloads;
-    int packet_nb_frames;
-    uint8_t packet_buf[PACKET_SIZE];
-    ByteIOContext pb;
-    /* only for reading */
-    uint64_t data_offset;                ///< beginning of the first data packet
-    uint64_t data_object_offset;         ///< data object offset (excl. GUID & size)
-    uint64_t data_object_size;           ///< size of the data object
-    int index_read;
-
-    ASFMainHeader hdr;
-
-    int packet_flags;
-    int packet_property;
-    int packet_timestamp;
-    int packet_segsizetype;
-    int packet_segments;
-    int packet_seq;
-    int packet_replic_size;
-    int packet_key_frame;
-    int packet_padsize;
-    unsigned int packet_frag_offset;
-    unsigned int packet_frag_size;
-    int64_t packet_frag_timestamp;
-    int packet_multi_size;
-    int packet_obj_size;
-    int packet_time_delta;
-    int packet_time_start;
-    int64_t packet_pos;
-
-    int stream_index;
-
-
-    int64_t last_indexed_pts;
-    ASFIndex* index_ptr;
-    uint32_t nb_index_count;
-    uint32_t nb_index_memory_alloc;
-    uint16_t maximum_packet;
-
-    ASFStream* asf_st;                   ///< currently decoded stream
-} ASFContext;
-
 extern const ff_asf_guid ff_asf_header;
 extern const ff_asf_guid ff_asf_file_header;
 extern const ff_asf_guid ff_asf_stream_header;
@@ -145,6 +89,7 @@ extern const ff_asf_guid ff_asf_audio_stream;
 extern const ff_asf_guid ff_asf_audio_conceal_none;
 extern const ff_asf_guid ff_asf_audio_conceal_spread;
 extern const ff_asf_guid ff_asf_video_stream;
+extern const ff_asf_guid ff_asf_jfif_media;
 extern const ff_asf_guid ff_asf_video_conceal_none;
 extern const ff_asf_guid ff_asf_command_stream;
 extern const ff_asf_guid ff_asf_comment_header;
@@ -228,7 +173,13 @@ extern const AVMetadataConv ff_asf_metadata_conv[];
 
 #define ASF_PL_FLAG_KEY_FRAME 0x80 //1000 0000
 
-extern AVInputFormat asf_demuxer;
-int ff_put_str16_nolen(ByteIOContext *s, const char *tag);
+extern AVInputFormat ff_asf_demuxer;
+
+static av_always_inline int ff_guidcmp(const void *g1, const void *g2)
+{
+    return memcmp(g1, g2, sizeof(ff_asf_guid));
+}
+
+void ff_get_guid(AVIOContext *s, ff_asf_guid *g);
 
 #endif /* AVFORMAT_ASF_H */
diff --git a/libavformat/asfcrypt.c b/libavformat/asfcrypt.c
index 09e9af6..52cfc17 100644
--- a/libavformat/asfcrypt.c
+++ b/libavformat/asfcrypt.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2007 Reimar Doeffinger
  * This is a rewrite of code contained in freeme/freeme2
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -139,7 +139,7 @@ void ff_asfcrypt_dec(const uint8_t key[20], uint8_t *data, int len) {
     struct AVDES des;
     struct AVRC4 rc4;
     int num_qwords = len >> 3;
-    uint64_t *qwords = (uint64_t *)data;
+    uint8_t *qwords = data;
     uint64_t rc4buff[8];
     uint64_t packetkey;
     uint32_t ms_keys[12];
@@ -156,7 +156,7 @@ void ff_asfcrypt_dec(const uint8_t key[20], uint8_t *data, int len) {
     av_rc4_crypt(&rc4, (uint8_t *)rc4buff, NULL, sizeof(rc4buff), NULL, 1);
     multiswap_init((uint8_t *)rc4buff, ms_keys);
 
-    packetkey = qwords[num_qwords - 1];
+    packetkey = AV_RN64(&qwords[num_qwords*8 - 8]);
     packetkey ^= rc4buff[7];
     av_des_init(&des, key + 12, 64, 1);
     av_des_crypt(&des, (uint8_t *)&packetkey, (uint8_t *)&packetkey, 1, NULL, 1);
@@ -166,11 +166,11 @@ void ff_asfcrypt_dec(const uint8_t key[20], uint8_t *data, int len) {
     av_rc4_crypt(&rc4, data, data, len, NULL, 1);
 
     ms_state = 0;
-    for (i = 0; i < num_qwords - 1; i++, qwords++)
+    for (i = 0; i < num_qwords - 1; i++, qwords += 8)
         ms_state = multiswap_enc(ms_keys, ms_state, AV_RL64(qwords));
     multiswap_invert_keys(ms_keys);
     packetkey = (packetkey << 32) | (packetkey >> 32);
-    packetkey = le2me_64(packetkey);
+    packetkey = av_le2ne64(packetkey);
     packetkey = multiswap_dec(ms_keys, ms_state, packetkey);
     AV_WL64(qwords, packetkey);
 }
diff --git a/libavformat/asfcrypt.h b/libavformat/asfcrypt.h
index 8b80d63..53388b4 100644
--- a/libavformat/asfcrypt.h
+++ b/libavformat/asfcrypt.h
@@ -2,20 +2,20 @@
  * ASF decryption
  * Copyright (c) 2007 Reimar Doeffinger
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavformat/asfdec.c b/libavformat/asfdec.c
index 8aea8c7..8dc5291 100644
--- a/libavformat/asfdec.c
+++ b/libavformat/asfdec.c
@@ -2,20 +2,20 @@
  * ASF compatible demuxer
  * Copyright (c) 2000, 2001 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,16 +25,56 @@
 #include "libavutil/avstring.h"
 #include "libavcodec/mpegaudio.h"
 #include "avformat.h"
+#include "avio_internal.h"
 #include "riff.h"
 #include "asf.h"
 #include "asfcrypt.h"
 #include "avlanguage.h"
 
-void ff_mms_set_stream_selection(URLContext *h, AVFormatContext *format);
+typedef struct {
+    int asfid2avid[128];                 ///< conversion table from asf ID 2 AVStream ID
+    ASFStream streams[128];              ///< it's max number and it's not that big
+    uint32_t stream_bitrates[128];       ///< max number of streams, bitrate for each (for streaming)
+    AVRational dar[128];
+    char stream_languages[128][6];       ///< max number of streams, language for each (RFC1766, e.g. en-US)
+    /* non streamed additonnal info */
+    /* packet filling */
+    int packet_size_left;
+    /* only for reading */
+    uint64_t data_offset;                ///< beginning of the first data packet
+    uint64_t data_object_offset;         ///< data object offset (excl. GUID & size)
+    uint64_t data_object_size;           ///< size of the data object
+    int index_read;
+
+    ASFMainHeader hdr;
+
+    int packet_flags;
+    int packet_property;
+    int packet_timestamp;
+    int packet_segsizetype;
+    int packet_segments;
+    int packet_seq;
+    int packet_replic_size;
+    int packet_key_frame;
+    int packet_padsize;
+    unsigned int packet_frag_offset;
+    unsigned int packet_frag_size;
+    int64_t packet_frag_timestamp;
+    int packet_multi_size;
+    int packet_obj_size;
+    int packet_time_delta;
+    int packet_time_start;
+    int64_t packet_pos;
+
+    int stream_index;
+
+    ASFStream* asf_st;                   ///< currently decoded stream
+} ASFContext;
 
 #undef NDEBUG
 #include <assert.h>
 
+#define ASF_MAX_STREAMS 127
 #define FRAME_HEADER_SIZE 17
 // Fix Me! FRAME_HEADER_SIZE may be different.
 
@@ -48,15 +88,10 @@ static const ff_asf_guid stream_bitrate_guid = { /* (http://get.to/sdp) */
 /**********************************/
 /* decoding */
 
-static int guidcmp(const void *g1, const void *g2)
-{
-    return memcmp(g1, g2, sizeof(ff_asf_guid));
-}
-
 #ifdef DEBUG
 #define PRINT_IF_GUID(g,cmp) \
-if (!guidcmp(g, &cmp)) \
-    dprintf(NULL, "(GUID: %s) ", #cmp)
+if (!ff_guidcmp(g, &cmp)) \
+    av_dlog(NULL, "(GUID: %s) ", #cmp)
 
 static void print_guid(const ff_asf_guid *g)
 {
@@ -86,70 +121,37 @@ static void print_guid(const ff_asf_guid *g)
     else PRINT_IF_GUID(g, stream_bitrate_guid);
     else PRINT_IF_GUID(g, ff_asf_language_guid);
     else
-        dprintf(NULL, "(GUID: unknown) ");
+        av_dlog(NULL, "(GUID: unknown) ");
     for(i=0;i<16;i++)
-        dprintf(NULL, " 0x%02x,", (*g)[i]);
-    dprintf(NULL, "}\n");
+        av_dlog(NULL, " 0x%02x,", (*g)[i]);
+    av_dlog(NULL, "}\n");
 }
 #undef PRINT_IF_GUID
 #else
 #define print_guid(g)
 #endif
 
-static void get_guid(ByteIOContext *s, ff_asf_guid *g)
+void ff_get_guid(AVIOContext *s, ff_asf_guid *g)
 {
     assert(sizeof(*g) == 16);
-    get_buffer(s, *g, sizeof(*g));
-}
-
-#if 0
-static void get_str16(ByteIOContext *pb, char *buf, int buf_size)
-{
-    int len, c;
-    char *q;
-
-    len = get_le16(pb);
-    q = buf;
-    while (len > 0) {
-        c = get_le16(pb);
-        if ((q - buf) < buf_size - 1)
-            *q++ = c;
-        len--;
-    }
-    *q = '\0';
-}
-#endif
-
-static void get_str16_nolen(ByteIOContext *pb, int len, char *buf, int buf_size)
-{
-    char* q = buf;
-    while (len > 1) {
-        uint8_t tmp;
-        uint32_t ch;
-
-        GET_UTF16(ch, (len -= 2) >= 0 ? get_le16(pb) : 0, break;)
-        PUT_UTF8(ch, tmp, if (q - buf < buf_size - 1) *q++ = tmp;)
-    }
-    if (len > 0)
-        url_fskip(pb, len);
-    *q = '\0';
+    avio_read(s, *g, sizeof(*g));
 }
 
 static int asf_probe(AVProbeData *pd)
 {
     /* check file header */
-    if (!guidcmp(pd->buf, &ff_asf_header))
+    if (!ff_guidcmp(pd->buf, &ff_asf_header))
         return AVPROBE_SCORE_MAX;
     else
         return 0;
 }
 
-static int get_value(ByteIOContext *pb, int type){
+static int get_value(AVIOContext *pb, int type){
     switch(type){
-        case 2: return get_le32(pb);
-        case 3: return get_le32(pb);
-        case 4: return get_le64(pb);
-        case 5: return get_le16(pb);
+        case 2: return avio_rl32(pb);
+        case 3: return avio_rl32(pb);
+        case 4: return avio_rl64(pb);
+        case 5: return avio_rl16(pb);
         default:return INT_MIN;
     }
 }
@@ -157,61 +159,451 @@ static int get_value(ByteIOContext *pb, int type){
 static void get_tag(AVFormatContext *s, const char *key, int type, int len)
 {
     char *value;
+    int64_t off = avio_tell(s->pb);
 
     if ((unsigned)len >= (UINT_MAX - 1)/2)
         return;
 
     value = av_malloc(2*len+1);
     if (!value)
-        return;
+        goto finish;
 
     if (type == 0) {         // UTF16-LE
-        get_str16_nolen(s->pb, len, value, 2*len + 1);
+        avio_get_str16le(s->pb, len, value, 2*len + 1);
     } else if (type > 1 && type <= 5) {  // boolean or DWORD or QWORD or WORD
         uint64_t num = get_value(s->pb, type);
         snprintf(value, len, "%"PRIu64, num);
     } else {
-        url_fskip(s->pb, len);
-        av_freep(&value);
         av_log(s, AV_LOG_DEBUG, "Unsupported value type %d in tag %s.\n", type, key);
-        return;
+        goto finish;
     }
-    av_metadata_set2(&s->metadata, key, value, 0);
+    if (*value)
+        av_metadata_set2(&s->metadata, key, value, 0);
+finish:
     av_freep(&value);
+    avio_seek(s->pb, off + len, SEEK_SET);
 }
 
-static int asf_read_header(AVFormatContext *s, AVFormatParameters *ap)
+static int asf_read_file_properties(AVFormatContext *s, int64_t size)
 {
     ASFContext *asf = s->priv_data;
-    ff_asf_guid g;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
+
+    ff_get_guid(pb, &asf->hdr.guid);
+    asf->hdr.file_size          = avio_rl64(pb);
+    asf->hdr.create_time        = avio_rl64(pb);
+    avio_rl64(pb);                               /* number of packets */
+    asf->hdr.play_time          = avio_rl64(pb);
+    asf->hdr.send_time          = avio_rl64(pb);
+    asf->hdr.preroll            = avio_rl32(pb);
+    asf->hdr.ignore             = avio_rl32(pb);
+    asf->hdr.flags              = avio_rl32(pb);
+    asf->hdr.min_pktsize        = avio_rl32(pb);
+    asf->hdr.max_pktsize        = avio_rl32(pb);
+    asf->hdr.max_bitrate        = avio_rl32(pb);
+    s->packet_size = asf->hdr.max_pktsize;
+
+    return 0;
+}
+
+static int asf_read_stream_properties(AVFormatContext *s, int64_t size)
+{
+    ASFContext *asf = s->priv_data;
+    AVIOContext *pb = s->pb;
     AVStream *st;
     ASFStream *asf_st;
-    int size, i;
-    int64_t gsize;
-    AVRational dar[128];
-    uint32_t bitrate[128];
+    ff_asf_guid g;
+    enum AVMediaType type;
+    int type_specific_size, sizeX;
+    uint64_t total_size;
+    unsigned int tag1;
+    int64_t pos1, pos2, start_time;
+    int test_for_ext_stream_audio, is_dvr_ms_audio=0;
+
+    if (s->nb_streams == ASF_MAX_STREAMS) {
+        av_log(s, AV_LOG_ERROR, "too many streams\n");
+        return AVERROR(EINVAL);
+    }
+
+    pos1 = avio_tell(pb);
+
+    st = av_new_stream(s, 0);
+    if (!st)
+        return AVERROR(ENOMEM);
+    av_set_pts_info(st, 32, 1, 1000); /* 32 bit pts in ms */
+    asf_st = av_mallocz(sizeof(ASFStream));
+    if (!asf_st)
+        return AVERROR(ENOMEM);
+    st->priv_data = asf_st;
+    st->start_time = 0;
+    start_time = asf->hdr.preroll;
 
-    memset(dar, 0, sizeof(dar));
-    memset(bitrate, 0, sizeof(bitrate));
+    asf_st->stream_language_index = 128; // invalid stream index means no language info
 
-    get_guid(pb, &g);
-    if (guidcmp(&g, &ff_asf_header))
+    if(!(asf->hdr.flags & 0x01)) { // if we aren't streaming...
+        st->duration = asf->hdr.play_time /
+            (10000000 / 1000) - start_time;
+    }
+    ff_get_guid(pb, &g);
+
+    test_for_ext_stream_audio = 0;
+    if (!ff_guidcmp(&g, &ff_asf_audio_stream)) {
+        type = AVMEDIA_TYPE_AUDIO;
+    } else if (!ff_guidcmp(&g, &ff_asf_video_stream)) {
+        type = AVMEDIA_TYPE_VIDEO;
+    } else if (!ff_guidcmp(&g, &ff_asf_jfif_media)) {
+        type = AVMEDIA_TYPE_VIDEO;
+        st->codec->codec_id = CODEC_ID_MJPEG;
+    } else if (!ff_guidcmp(&g, &ff_asf_command_stream)) {
+        type = AVMEDIA_TYPE_DATA;
+    } else if (!ff_guidcmp(&g, &ff_asf_ext_stream_embed_stream_header)) {
+        test_for_ext_stream_audio = 1;
+        type = AVMEDIA_TYPE_UNKNOWN;
+    } else {
         return -1;
-    get_le64(pb);
-    get_le32(pb);
-    get_byte(pb);
-    get_byte(pb);
+    }
+    ff_get_guid(pb, &g);
+    total_size = avio_rl64(pb);
+    type_specific_size = avio_rl32(pb);
+    avio_rl32(pb);
+    st->id = avio_rl16(pb) & 0x7f; /* stream id */
+    // mapping of asf ID to AV stream ID;
+    asf->asfid2avid[st->id] = s->nb_streams - 1;
+
+    avio_rl32(pb);
+
+    if (test_for_ext_stream_audio) {
+        ff_get_guid(pb, &g);
+        if (!ff_guidcmp(&g, &ff_asf_ext_stream_audio_stream)) {
+            type = AVMEDIA_TYPE_AUDIO;
+            is_dvr_ms_audio=1;
+            ff_get_guid(pb, &g);
+            avio_rl32(pb);
+            avio_rl32(pb);
+            avio_rl32(pb);
+            ff_get_guid(pb, &g);
+            avio_rl32(pb);
+        }
+    }
+
+    st->codec->codec_type = type;
+    if (type == AVMEDIA_TYPE_AUDIO) {
+        int ret = ff_get_wav_header(pb, st->codec, type_specific_size);
+        if (ret < 0)
+            return ret;
+        if (is_dvr_ms_audio) {
+            // codec_id and codec_tag are unreliable in dvr_ms
+            // files. Set them later by probing stream.
+            st->codec->codec_id = CODEC_ID_PROBE;
+            st->codec->codec_tag = 0;
+        }
+        if (st->codec->codec_id == CODEC_ID_AAC) {
+            st->need_parsing = AVSTREAM_PARSE_NONE;
+        } else {
+            st->need_parsing = AVSTREAM_PARSE_FULL;
+        }
+        /* We have to init the frame size at some point .... */
+        pos2 = avio_tell(pb);
+        if (size >= (pos2 + 8 - pos1 + 24)) {
+            asf_st->ds_span = avio_r8(pb);
+            asf_st->ds_packet_size = avio_rl16(pb);
+            asf_st->ds_chunk_size = avio_rl16(pb);
+            avio_rl16(pb); //ds_data_size
+            avio_r8(pb);   //ds_silence_data
+        }
+        //printf("Descrambling: ps:%d cs:%d ds:%d s:%d  sd:%d\n",
+        //       asf_st->ds_packet_size, asf_st->ds_chunk_size,
+        //       asf_st->ds_data_size, asf_st->ds_span, asf_st->ds_silence_data);
+        if (asf_st->ds_span > 1) {
+            if (!asf_st->ds_chunk_size
+                    || (asf_st->ds_packet_size/asf_st->ds_chunk_size <= 1)
+                    || asf_st->ds_packet_size % asf_st->ds_chunk_size)
+                asf_st->ds_span = 0; // disable descrambling
+        }
+        switch (st->codec->codec_id) {
+            case CODEC_ID_MP3:
+                st->codec->frame_size = MPA_FRAME_SIZE;
+                break;
+            case CODEC_ID_PCM_S16LE:
+            case CODEC_ID_PCM_S16BE:
+            case CODEC_ID_PCM_U16LE:
+            case CODEC_ID_PCM_U16BE:
+            case CODEC_ID_PCM_S8:
+            case CODEC_ID_PCM_U8:
+            case CODEC_ID_PCM_ALAW:
+            case CODEC_ID_PCM_MULAW:
+                st->codec->frame_size = 1;
+                break;
+            default:
+                /* This is probably wrong, but it prevents a crash later */
+                st->codec->frame_size = 1;
+                break;
+        }
+    } else if (type == AVMEDIA_TYPE_VIDEO &&
+            size - (avio_tell(pb) - pos1 + 24) >= 51) {
+        avio_rl32(pb);
+        avio_rl32(pb);
+        avio_r8(pb);
+        avio_rl16(pb);        /* size */
+        sizeX= avio_rl32(pb); /* size */
+        st->codec->width = avio_rl32(pb);
+        st->codec->height = avio_rl32(pb);
+        /* not available for asf */
+        avio_rl16(pb); /* panes */
+        st->codec->bits_per_coded_sample = avio_rl16(pb); /* depth */
+        tag1 = avio_rl32(pb);
+        avio_skip(pb, 20);
+        //                av_log(s, AV_LOG_DEBUG, "size:%d tsize:%d sizeX:%d\n", size, total_size, sizeX);
+        if (sizeX > 40) {
+            st->codec->extradata_size = sizeX - 40;
+            st->codec->extradata = av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
+            avio_read(pb, st->codec->extradata, st->codec->extradata_size);
+        }
+
+        /* Extract palette from extradata if bpp <= 8 */
+        /* This code assumes that extradata contains only palette */
+        /* This is true for all paletted codecs implemented in ffmpeg */
+        if (st->codec->extradata_size && (st->codec->bits_per_coded_sample <= 8)) {
+            int av_unused i;
+#if HAVE_BIGENDIAN
+            for (i = 0; i < FFMIN(st->codec->extradata_size, AVPALETTE_SIZE)/4; i++)
+                asf_st->palette[i] = av_bswap32(((uint32_t*)st->codec->extradata)[i]);
+#else
+            memcpy(asf_st->palette, st->codec->extradata,
+                   FFMIN(st->codec->extradata_size, AVPALETTE_SIZE));
+#endif
+            asf_st->palette_changed = 1;
+        }
+
+        st->codec->codec_tag = tag1;
+        st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags, tag1);
+        if(tag1 == MKTAG('D', 'V', 'R', ' ')){
+            st->need_parsing = AVSTREAM_PARSE_FULL;
+            // issue658 containse wrong w/h and MS even puts a fake seq header with wrong w/h in extradata while a correct one is in te stream. maximum lameness
+            st->codec->width  =
+                st->codec->height = 0;
+            av_freep(&st->codec->extradata);
+            st->codec->extradata_size=0;
+        }
+        if(st->codec->codec_id == CODEC_ID_H264)
+            st->need_parsing = AVSTREAM_PARSE_FULL_ONCE;
+    }
+    pos2 = avio_tell(pb);
+    avio_skip(pb, size - (pos2 - pos1 + 24));
+
+    return 0;
+}
+
+static int asf_read_ext_stream_properties(AVFormatContext *s, int64_t size)
+{
+    ASFContext *asf = s->priv_data;
+    AVIOContext *pb = s->pb;
+    ff_asf_guid g;
+    int ext_len, payload_ext_ct, stream_ct, i;
+    uint32_t ext_d, leak_rate, stream_num;
+    unsigned int stream_languageid_index;
+
+    avio_rl64(pb); // starttime
+    avio_rl64(pb); // endtime
+    leak_rate = avio_rl32(pb); // leak-datarate
+    avio_rl32(pb); // bucket-datasize
+    avio_rl32(pb); // init-bucket-fullness
+    avio_rl32(pb); // alt-leak-datarate
+    avio_rl32(pb); // alt-bucket-datasize
+    avio_rl32(pb); // alt-init-bucket-fullness
+    avio_rl32(pb); // max-object-size
+    avio_rl32(pb); // flags (reliable,seekable,no_cleanpoints?,resend-live-cleanpoints, rest of bits reserved)
+    stream_num = avio_rl16(pb); // stream-num
+
+    stream_languageid_index = avio_rl16(pb); // stream-language-id-index
+    if (stream_num < 128)
+        asf->streams[stream_num].stream_language_index = stream_languageid_index;
+
+    avio_rl64(pb); // avg frametime in 100ns units
+    stream_ct = avio_rl16(pb); //stream-name-count
+    payload_ext_ct = avio_rl16(pb); //payload-extension-system-count
+
+    if (stream_num < 128)
+        asf->stream_bitrates[stream_num] = leak_rate;
+
+    for (i=0; i<stream_ct; i++){
+        avio_rl16(pb);
+        ext_len = avio_rl16(pb);
+        avio_skip(pb, ext_len);
+    }
+
+    for (i=0; i<payload_ext_ct; i++){
+        ff_get_guid(pb, &g);
+        ext_d=avio_rl16(pb);
+        ext_len=avio_rl32(pb);
+        avio_skip(pb, ext_len);
+    }
+
+    return 0;
+}
+
+static int asf_read_content_desc(AVFormatContext *s, int64_t size)
+{
+    AVIOContext *pb = s->pb;
+    int len1, len2, len3, len4, len5;
+
+    len1 = avio_rl16(pb);
+    len2 = avio_rl16(pb);
+    len3 = avio_rl16(pb);
+    len4 = avio_rl16(pb);
+    len5 = avio_rl16(pb);
+    get_tag(s, "title"    , 0, len1);
+    get_tag(s, "author"   , 0, len2);
+    get_tag(s, "copyright", 0, len3);
+    get_tag(s, "comment"  , 0, len4);
+    avio_skip(pb, len5);
+
+    return 0;
+}
+
+static int asf_read_ext_content_desc(AVFormatContext *s, int64_t size)
+{
+    AVIOContext *pb = s->pb;
+    ASFContext *asf = s->priv_data;
+    int desc_count, i, ret;
+
+    desc_count = avio_rl16(pb);
+    for(i=0;i<desc_count;i++) {
+        int name_len,value_type,value_len;
+        char name[1024];
+
+        name_len = avio_rl16(pb);
+        if (name_len%2)     // must be even, broken lavf versions wrote len-1
+            name_len += 1;
+        if ((ret = avio_get_str16le(pb, name_len, name, sizeof(name))) < name_len)
+            avio_skip(pb, name_len - ret);
+        value_type = avio_rl16(pb);
+        value_len  = avio_rl16(pb);
+        if (!value_type && value_len%2)
+            value_len += 1;
+        /**
+         * My sample has that stream set to 0 maybe that mean the container.
+         * Asf stream count start at 1. I am using 0 to the container value since it's unused
+         */
+        if (!strcmp(name, "AspectRatioX")){
+            asf->dar[0].num= get_value(s->pb, value_type);
+        } else if(!strcmp(name, "AspectRatioY")){
+            asf->dar[0].den= get_value(s->pb, value_type);
+        } else
+            get_tag(s, name, value_type, value_len);
+    }
+
+    return 0;
+}
+
+static int asf_read_language_list(AVFormatContext *s, int64_t size)
+{
+    AVIOContext *pb = s->pb;
+    ASFContext *asf = s->priv_data;
+    int j, ret;
+    int stream_count = avio_rl16(pb);
+    for(j = 0; j < stream_count; j++) {
+        char lang[6];
+        unsigned int lang_len = avio_r8(pb);
+        if ((ret = avio_get_str16le(pb, lang_len, lang, sizeof(lang))) < lang_len)
+            avio_skip(pb, lang_len - ret);
+        if (j < 128)
+            av_strlcpy(asf->stream_languages[j], lang, sizeof(*asf->stream_languages));
+    }
+
+    return 0;
+}
+
+static int asf_read_metadata(AVFormatContext *s, int64_t size)
+{
+    AVIOContext *pb = s->pb;
+    ASFContext *asf = s->priv_data;
+    int n, stream_num, name_len, value_len, value_type, value_num;
+    int ret, i;
+    n = avio_rl16(pb);
+
+    for(i=0;i<n;i++) {
+        char name[1024];
+
+        avio_rl16(pb); //lang_list_index
+        stream_num= avio_rl16(pb);
+        name_len=   avio_rl16(pb);
+        value_type= avio_rl16(pb);
+        value_len=  avio_rl32(pb);
+
+        if ((ret = avio_get_str16le(pb, name_len, name, sizeof(name))) < name_len)
+            avio_skip(pb, name_len - ret);
+        //av_log(s, AV_LOG_ERROR, "%d %d %d %d %d <%s>\n", i, stream_num, name_len, value_type, value_len, name);
+        value_num= avio_rl16(pb);//we should use get_value() here but it does not work 2 is le16 here but le32 elsewhere
+        avio_skip(pb, value_len - 2);
+
+        if(stream_num<128){
+            if     (!strcmp(name, "AspectRatioX")) asf->dar[stream_num].num= value_num;
+            else if(!strcmp(name, "AspectRatioY")) asf->dar[stream_num].den= value_num;
+        }
+    }
+
+    return 0;
+}
+
+static int asf_read_marker(AVFormatContext *s, int64_t size)
+{
+    AVIOContext *pb = s->pb;
+    int i, count, name_len, ret;
+    char name[1024];
+
+    avio_rl64(pb);            // reserved 16 bytes
+    avio_rl64(pb);            // ...
+    count = avio_rl32(pb);    // markers count
+    avio_rl16(pb);            // reserved 2 bytes
+    name_len = avio_rl16(pb); // name length
+    for(i=0;i<name_len;i++){
+        avio_r8(pb); // skip the name
+    }
+
+    for(i=0;i<count;i++){
+        int64_t pres_time;
+        int name_len;
+
+        avio_rl64(pb);             // offset, 8 bytes
+        pres_time = avio_rl64(pb); // presentation time
+        avio_rl16(pb);             // entry length
+        avio_rl32(pb);             // send time
+        avio_rl32(pb);             // flags
+        name_len = avio_rl32(pb);  // name length
+        if ((ret = avio_get_str16le(pb, name_len * 2, name, sizeof(name))) < name_len)
+            avio_skip(pb, name_len - ret);
+        ff_new_chapter(s, i, (AVRational){1, 10000000}, pres_time, AV_NOPTS_VALUE, name );
+    }
+
+    return 0;
+}
+
+static int asf_read_header(AVFormatContext *s, AVFormatParameters *ap)
+{
+    ASFContext *asf = s->priv_data;
+    ff_asf_guid g;
+    AVIOContext *pb = s->pb;
+    int i;
+    int64_t gsize;
+
+    ff_get_guid(pb, &g);
+    if (ff_guidcmp(&g, &ff_asf_header))
+        return -1;
+    avio_rl64(pb);
+    avio_rl32(pb);
+    avio_r8(pb);
+    avio_r8(pb);
     memset(&asf->asfid2avid, -1, sizeof(asf->asfid2avid));
     for(;;) {
-        uint64_t gpos= url_ftell(pb);
-        get_guid(pb, &g);
-        gsize = get_le64(pb);
-        dprintf(s, "%08"PRIx64": ", gpos);
+        uint64_t gpos= avio_tell(pb);
+        ff_get_guid(pb, &g);
+        gsize = avio_rl64(pb);
+        av_dlog(s, "%08"PRIx64": ", gpos);
         print_guid(&g);
-        dprintf(s, "  size=0x%"PRIx64"\n", gsize);
-        if (!guidcmp(&g, &ff_asf_data_header)) {
-            asf->data_object_offset = url_ftell(pb);
+        av_dlog(s, "  size=0x%"PRIx64"\n", gsize);
+        if (!ff_guidcmp(&g, &ff_asf_data_header)) {
+            asf->data_object_offset = avio_tell(pb);
             // if not streaming, gsize is not unlimited (how?), and there is enough space in the file..
             if (!(asf->hdr.flags & 0x01) && gsize >= 100) {
                 asf->data_object_size = gsize - 24;
@@ -222,381 +614,56 @@ static int asf_read_header(AVFormatContext *s, AVFormatParameters *ap)
         }
         if (gsize < 24)
             return -1;
-        if (!guidcmp(&g, &ff_asf_file_header)) {
-            get_guid(pb, &asf->hdr.guid);
-            asf->hdr.file_size          = get_le64(pb);
-            asf->hdr.create_time        = get_le64(pb);
-            asf->nb_packets             = get_le64(pb);
-            asf->hdr.play_time          = get_le64(pb);
-            asf->hdr.send_time          = get_le64(pb);
-            asf->hdr.preroll            = get_le32(pb);
-            asf->hdr.ignore             = get_le32(pb);
-            asf->hdr.flags              = get_le32(pb);
-            asf->hdr.min_pktsize        = get_le32(pb);
-            asf->hdr.max_pktsize        = get_le32(pb);
-            asf->hdr.max_bitrate        = get_le32(pb);
-            s->packet_size = asf->hdr.max_pktsize;
-        } else if (!guidcmp(&g, &ff_asf_stream_header)) {
-            enum AVMediaType type;
-            int type_specific_size, sizeX;
-            uint64_t total_size;
-            unsigned int tag1;
-            int64_t pos1, pos2, start_time;
-            int test_for_ext_stream_audio, is_dvr_ms_audio=0;
-
-            pos1 = url_ftell(pb);
-
-            st = av_new_stream(s, 0);
-            if (!st)
-                return AVERROR(ENOMEM);
-            av_set_pts_info(st, 32, 1, 1000); /* 32 bit pts in ms */
-            asf_st = av_mallocz(sizeof(ASFStream));
-            if (!asf_st)
-                return AVERROR(ENOMEM);
-            st->priv_data = asf_st;
-            start_time = asf->hdr.preroll;
-
-            asf_st->stream_language_index = 128; // invalid stream index means no language info
-
-            if(!(asf->hdr.flags & 0x01)) { // if we aren't streaming...
-                st->duration = asf->hdr.play_time /
-                    (10000000 / 1000) - start_time;
-            }
-            get_guid(pb, &g);
-
-            test_for_ext_stream_audio = 0;
-            if (!guidcmp(&g, &ff_asf_audio_stream)) {
-                type = AVMEDIA_TYPE_AUDIO;
-            } else if (!guidcmp(&g, &ff_asf_video_stream)) {
-                type = AVMEDIA_TYPE_VIDEO;
-            } else if (!guidcmp(&g, &ff_asf_command_stream)) {
-                type = AVMEDIA_TYPE_DATA;
-            } else if (!guidcmp(&g, &ff_asf_ext_stream_embed_stream_header)) {
-                test_for_ext_stream_audio = 1;
-                type = AVMEDIA_TYPE_UNKNOWN;
-            } else {
-                return -1;
-            }
-            get_guid(pb, &g);
-            total_size = get_le64(pb);
-            type_specific_size = get_le32(pb);
-            get_le32(pb);
-            st->id = get_le16(pb) & 0x7f; /* stream id */
-            // mapping of asf ID to AV stream ID;
-            asf->asfid2avid[st->id] = s->nb_streams - 1;
-
-            get_le32(pb);
-
-            if (test_for_ext_stream_audio) {
-                get_guid(pb, &g);
-                if (!guidcmp(&g, &ff_asf_ext_stream_audio_stream)) {
-                    type = AVMEDIA_TYPE_AUDIO;
-                    is_dvr_ms_audio=1;
-                    get_guid(pb, &g);
-                    get_le32(pb);
-                    get_le32(pb);
-                    get_le32(pb);
-                    get_guid(pb, &g);
-                    get_le32(pb);
-                }
-            }
-
-            st->codec->codec_type = type;
-            if (type == AVMEDIA_TYPE_AUDIO) {
-                ff_get_wav_header(pb, st->codec, type_specific_size);
-                if (is_dvr_ms_audio) {
-                    // codec_id and codec_tag are unreliable in dvr_ms
-                    // files. Set them later by probing stream.
-                    st->codec->codec_id = CODEC_ID_PROBE;
-                    st->codec->codec_tag = 0;
-                }
-                if (st->codec->codec_id == CODEC_ID_AAC) {
-                    st->need_parsing = AVSTREAM_PARSE_NONE;
-                } else {
-                    st->need_parsing = AVSTREAM_PARSE_FULL;
-                }
-                /* We have to init the frame size at some point .... */
-                pos2 = url_ftell(pb);
-                if (gsize >= (pos2 + 8 - pos1 + 24)) {
-                    asf_st->ds_span = get_byte(pb);
-                    asf_st->ds_packet_size = get_le16(pb);
-                    asf_st->ds_chunk_size = get_le16(pb);
-                    get_le16(pb); //ds_data_size
-                    get_byte(pb); //ds_silence_data
-                }
-                //printf("Descrambling: ps:%d cs:%d ds:%d s:%d  sd:%d\n",
-                //       asf_st->ds_packet_size, asf_st->ds_chunk_size,
-                //       asf_st->ds_data_size, asf_st->ds_span, asf_st->ds_silence_data);
-                if (asf_st->ds_span > 1) {
-                    if (!asf_st->ds_chunk_size
-                        || (asf_st->ds_packet_size/asf_st->ds_chunk_size <= 1)
-                        || asf_st->ds_packet_size % asf_st->ds_chunk_size)
-                        asf_st->ds_span = 0; // disable descrambling
-                }
-                switch (st->codec->codec_id) {
-                case CODEC_ID_MP3:
-                    st->codec->frame_size = MPA_FRAME_SIZE;
-                    break;
-                case CODEC_ID_PCM_S16LE:
-                case CODEC_ID_PCM_S16BE:
-                case CODEC_ID_PCM_U16LE:
-                case CODEC_ID_PCM_U16BE:
-                case CODEC_ID_PCM_S8:
-                case CODEC_ID_PCM_U8:
-                case CODEC_ID_PCM_ALAW:
-                case CODEC_ID_PCM_MULAW:
-                    st->codec->frame_size = 1;
-                    break;
-                default:
-                    /* This is probably wrong, but it prevents a crash later */
-                    st->codec->frame_size = 1;
-                    break;
-                }
-            } else if (type == AVMEDIA_TYPE_VIDEO) {
-                get_le32(pb);
-                get_le32(pb);
-                get_byte(pb);
-                size = get_le16(pb); /* size */
-                sizeX= get_le32(pb); /* size */
-                st->codec->width = get_le32(pb);
-                st->codec->height = get_le32(pb);
-                /* not available for asf */
-                get_le16(pb); /* panes */
-                st->codec->bits_per_coded_sample = get_le16(pb); /* depth */
-                tag1 = get_le32(pb);
-                url_fskip(pb, 20);
-//                av_log(s, AV_LOG_DEBUG, "size:%d tsize:%d sizeX:%d\n", size, total_size, sizeX);
-                size= sizeX;
-                if (size > 40) {
-                    st->codec->extradata_size = size - 40;
-                    st->codec->extradata = av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
-                    get_buffer(pb, st->codec->extradata, st->codec->extradata_size);
-                }
-
-                /* Extract palette from extradata if bpp <= 8 */
-                /* This code assumes that extradata contains only palette */
-                /* This is true for all paletted codecs implemented in ffmpeg */
-                if (st->codec->extradata_size && (st->codec->bits_per_coded_sample <= 8)) {
-                    st->codec->palctrl = av_mallocz(sizeof(AVPaletteControl));
-#if HAVE_BIGENDIAN
-                    for (i = 0; i < FFMIN(st->codec->extradata_size, AVPALETTE_SIZE)/4; i++)
-                        st->codec->palctrl->palette[i] = bswap_32(((uint32_t*)st->codec->extradata)[i]);
-#else
-                    memcpy(st->codec->palctrl->palette, st->codec->extradata,
-                           FFMIN(st->codec->extradata_size, AVPALETTE_SIZE));
-#endif
-                    st->codec->palctrl->palette_changed = 1;
-                }
-
-                st->codec->codec_tag = tag1;
-                st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags, tag1);
-                if(tag1 == MKTAG('D', 'V', 'R', ' '))
-                    st->need_parsing = AVSTREAM_PARSE_FULL;
-            }
-            pos2 = url_ftell(pb);
-            url_fskip(pb, gsize - (pos2 - pos1 + 24));
-        } else if (!guidcmp(&g, &ff_asf_comment_header)) {
-            int len1, len2, len3, len4, len5;
-
-            len1 = get_le16(pb);
-            len2 = get_le16(pb);
-            len3 = get_le16(pb);
-            len4 = get_le16(pb);
-            len5 = get_le16(pb);
-            get_tag(s, "title"    , 0, len1);
-            get_tag(s, "author"   , 0, len2);
-            get_tag(s, "copyright", 0, len3);
-            get_tag(s, "comment"  , 0, len4);
-            url_fskip(pb, len5);
-        } else if (!guidcmp(&g, &stream_bitrate_guid)) {
-            int stream_count = get_le16(pb);
-            int j;
-
-//            av_log(s, AV_LOG_ERROR, "stream bitrate properties\n");
-//            av_log(s, AV_LOG_ERROR, "streams %d\n", streams);
-            for(j = 0; j < stream_count; j++) {
-                int flags, bitrate, stream_id;
-
-                flags= get_le16(pb);
-                bitrate= get_le32(pb);
-                stream_id= (flags & 0x7f);
-//                av_log(s, AV_LOG_ERROR, "flags: 0x%x stream id %d, bitrate %d\n", flags, stream_id, bitrate);
-                asf->stream_bitrates[stream_id]= bitrate;
-            }
-        } else if (!guidcmp(&g, &ff_asf_language_guid)) {
-            int j;
-            int stream_count = get_le16(pb);
-            for(j = 0; j < stream_count; j++) {
-                char lang[6];
-                unsigned int lang_len = get_byte(pb);
-                get_str16_nolen(pb, lang_len, lang, sizeof(lang));
-                if (j < 128)
-                    av_strlcpy(asf->stream_languages[j], lang, sizeof(*asf->stream_languages));
-            }
-        } else if (!guidcmp(&g, &ff_asf_extended_content_header)) {
-            int desc_count, i;
-
-            desc_count = get_le16(pb);
-            for(i=0;i<desc_count;i++) {
-                    int name_len,value_type,value_len;
-                    char name[1024];
-
-                    name_len = get_le16(pb);
-                    if (name_len%2)     // must be even, broken lavf versions wrote len-1
-                        name_len += 1;
-                    get_str16_nolen(pb, name_len, name, sizeof(name));
-                    value_type = get_le16(pb);
-                    value_len  = get_le16(pb);
-                    if (!value_type && value_len%2)
-                        value_len += 1;
-                    get_tag(s, name, value_type, value_len);
-            }
-        } else if (!guidcmp(&g, &ff_asf_metadata_header)) {
-            int n, stream_num, name_len, value_len, value_type, value_num;
-            n = get_le16(pb);
-
-            for(i=0;i<n;i++) {
-                char name[1024];
-
-                get_le16(pb); //lang_list_index
-                stream_num= get_le16(pb);
-                name_len=   get_le16(pb);
-                value_type= get_le16(pb);
-                value_len=  get_le32(pb);
-
-                get_str16_nolen(pb, name_len, name, sizeof(name));
-//av_log(s, AV_LOG_ERROR, "%d %d %d %d %d <%s>\n", i, stream_num, name_len, value_type, value_len, name);
-                value_num= get_le16(pb);//we should use get_value() here but it does not work 2 is le16 here but le32 elsewhere
-                url_fskip(pb, value_len - 2);
-
-                if(stream_num<128){
-                    if     (!strcmp(name, "AspectRatioX")) dar[stream_num].num= value_num;
-                    else if(!strcmp(name, "AspectRatioY")) dar[stream_num].den= value_num;
-                }
-            }
-        } else if (!guidcmp(&g, &ff_asf_ext_stream_header)) {
-            int ext_len, payload_ext_ct, stream_ct;
-            uint32_t ext_d, leak_rate, stream_num;
-            unsigned int stream_languageid_index;
-
-            get_le64(pb); // starttime
-            get_le64(pb); // endtime
-            leak_rate = get_le32(pb); // leak-datarate
-            get_le32(pb); // bucket-datasize
-            get_le32(pb); // init-bucket-fullness
-            get_le32(pb); // alt-leak-datarate
-            get_le32(pb); // alt-bucket-datasize
-            get_le32(pb); // alt-init-bucket-fullness
-            get_le32(pb); // max-object-size
-            get_le32(pb); // flags (reliable,seekable,no_cleanpoints?,resend-live-cleanpoints, rest of bits reserved)
-            stream_num = get_le16(pb); // stream-num
-
-            stream_languageid_index = get_le16(pb); // stream-language-id-index
-            if (stream_num < 128)
-                asf->streams[stream_num].stream_language_index = stream_languageid_index;
-
-            get_le64(pb); // avg frametime in 100ns units
-            stream_ct = get_le16(pb); //stream-name-count
-            payload_ext_ct = get_le16(pb); //payload-extension-system-count
-
-            if (stream_num < 128)
-                bitrate[stream_num] = leak_rate;
-
-            for (i=0; i<stream_ct; i++){
-                get_le16(pb);
-                ext_len = get_le16(pb);
-                url_fseek(pb, ext_len, SEEK_CUR);
-            }
-
-            for (i=0; i<payload_ext_ct; i++){
-                get_guid(pb, &g);
-                ext_d=get_le16(pb);
-                ext_len=get_le32(pb);
-                url_fseek(pb, ext_len, SEEK_CUR);
-            }
+        if (!ff_guidcmp(&g, &ff_asf_file_header)) {
+            asf_read_file_properties(s, gsize);
+        } else if (!ff_guidcmp(&g, &ff_asf_stream_header)) {
+            asf_read_stream_properties(s, gsize);
+        } else if (!ff_guidcmp(&g, &ff_asf_comment_header)) {
+            asf_read_content_desc(s, gsize);
+        } else if (!ff_guidcmp(&g, &ff_asf_language_guid)) {
+            asf_read_language_list(s, gsize);
+        } else if (!ff_guidcmp(&g, &ff_asf_extended_content_header)) {
+            asf_read_ext_content_desc(s, gsize);
+        } else if (!ff_guidcmp(&g, &ff_asf_metadata_header)) {
+            asf_read_metadata(s, gsize);
+        } else if (!ff_guidcmp(&g, &ff_asf_ext_stream_header)) {
+            asf_read_ext_stream_properties(s, gsize);
 
             // there could be a optional stream properties object to follow
             // if so the next iteration will pick it up
-        } else if (!guidcmp(&g, &ff_asf_head1_guid)) {
+            continue;
+        } else if (!ff_guidcmp(&g, &ff_asf_head1_guid)) {
             int v1, v2;
-            get_guid(pb, &g);
-            v1 = get_le32(pb);
-            v2 = get_le16(pb);
-        } else if (!guidcmp(&g, &ff_asf_marker_header)) {
-            int i, count, name_len;
-            char name[1024];
-
-            get_le64(pb);            // reserved 16 bytes
-            get_le64(pb);            // ...
-            count = get_le32(pb);    // markers count
-            get_le16(pb);            // reserved 2 bytes
-            name_len = get_le16(pb); // name length
-            for(i=0;i<name_len;i++){
-                get_byte(pb); // skip the name
-            }
-
-            for(i=0;i<count;i++){
-                int64_t pres_time;
-                int name_len;
-
-                get_le64(pb);             // offset, 8 bytes
-                pres_time = get_le64(pb); // presentation time
-                get_le16(pb);             // entry length
-                get_le32(pb);             // send time
-                get_le32(pb);             // flags
-                name_len = get_le32(pb);  // name length
-                get_str16_nolen(pb, name_len * 2, name, sizeof(name));
-                ff_new_chapter(s, i, (AVRational){1, 10000000}, pres_time, AV_NOPTS_VALUE, name );
-            }
-#if 0
-        } else if (!guidcmp(&g, &ff_asf_codec_comment_header)) {
-            int len, v1, n, num;
-            char str[256], *q;
-            char tag[16];
-
-            get_guid(pb, &g);
-            print_guid(&g);
-
-            n = get_le32(pb);
-            for(i=0;i<n;i++) {
-                num = get_le16(pb); /* stream number */
-                get_str16(pb, str, sizeof(str));
-                get_str16(pb, str, sizeof(str));
-                len = get_le16(pb);
-                q = tag;
-                while (len > 0) {
-                    v1 = get_byte(pb);
-                    if ((q - tag) < sizeof(tag) - 1)
-                        *q++ = v1;
-                    len--;
-                }
-                *q = '\0';
-            }
-#endif
-        } else if (url_feof(pb)) {
+            ff_get_guid(pb, &g);
+            v1 = avio_rl32(pb);
+            v2 = avio_rl16(pb);
+            continue;
+        } else if (!ff_guidcmp(&g, &ff_asf_marker_header)) {
+            asf_read_marker(s, gsize);
+        } else if (pb->eof_reached) {
             return -1;
         } else {
             if (!s->keylen) {
-                if (!guidcmp(&g, &ff_asf_content_encryption)) {
+                if (!ff_guidcmp(&g, &ff_asf_content_encryption)) {
                     av_log(s, AV_LOG_WARNING, "DRM protected stream detected, decoding will likely fail!\n");
-                } else if (!guidcmp(&g, &ff_asf_ext_content_encryption)) {
+                } else if (!ff_guidcmp(&g, &ff_asf_ext_content_encryption)) {
                     av_log(s, AV_LOG_WARNING, "Ext DRM protected stream detected, decoding will likely fail!\n");
-                } else if (!guidcmp(&g, &ff_asf_digital_signature)) {
+                } else if (!ff_guidcmp(&g, &ff_asf_digital_signature)) {
                     av_log(s, AV_LOG_WARNING, "Digital signature detected, decoding will likely fail!\n");
                 }
             }
         }
-        if(url_ftell(pb) != gpos + gsize)
-            av_log(s, AV_LOG_DEBUG, "gpos mismatch our pos=%"PRIu64", end=%"PRIu64"\n", url_ftell(pb)-gpos, gsize);
-        url_fseek(pb, gpos + gsize, SEEK_SET);
+        if(avio_tell(pb) != gpos + gsize)
+            av_log(s, AV_LOG_DEBUG, "gpos mismatch our pos=%"PRIu64", end=%"PRIu64"\n", avio_tell(pb)-gpos, gsize);
+        avio_seek(pb, gpos + gsize, SEEK_SET);
     }
-    get_guid(pb, &g);
-    get_le64(pb);
-    get_byte(pb);
-    get_byte(pb);
-    if (url_feof(pb))
+    ff_get_guid(pb, &g);
+    avio_rl64(pb);
+    avio_r8(pb);
+    avio_r8(pb);
+    if (pb->eof_reached)
         return -1;
-    asf->data_offset = url_ftell(pb);
+    asf->data_offset = avio_tell(pb);
     asf->packet_size_left = 0;
 
 
@@ -605,12 +672,17 @@ static int asf_read_header(AVFormatContext *s, AVFormatParameters *ap)
         if(stream_num>=0){
             AVStream *st = s->streams[stream_num];
             if (!st->codec->bit_rate)
-                st->codec->bit_rate = bitrate[i];
-            if (dar[i].num > 0 && dar[i].den > 0)
+                st->codec->bit_rate = asf->stream_bitrates[i];
+            if (asf->dar[i].num > 0 && asf->dar[i].den > 0){
                 av_reduce(&st->sample_aspect_ratio.num,
                           &st->sample_aspect_ratio.den,
-                          dar[i].num, dar[i].den, INT_MAX);
-//av_log(s, AV_LOG_ERROR, "dar %d:%d sar=%d:%d\n", dar[i].num, dar[i].den, st->sample_aspect_ratio.num, st->sample_aspect_ratio.den);
+                          asf->dar[i].num, asf->dar[i].den, INT_MAX);
+            } else if ((asf->dar[0].num > 0) && (asf->dar[0].den > 0) && (st->codec->codec_type==AVMEDIA_TYPE_VIDEO)) // Use ASF container value if the stream doesn't AR set.
+                av_reduce(&st->sample_aspect_ratio.num,
+                          &st->sample_aspect_ratio.den,
+                          asf->dar[0].num, asf->dar[0].den, INT_MAX);
+
+//av_log(s, AV_LOG_INFO, "i=%d, st->codec->codec_type:%d, dar %d:%d sar=%d:%d\n", i, st->codec->codec_type, dar[i].num, dar[i].den, st->sample_aspect_ratio.num, st->sample_aspect_ratio.den);
 
             // copy and convert language codes to the frontend
             if (asf->streams[i].stream_language_index < 128) {
@@ -625,15 +697,17 @@ static int asf_read_header(AVFormatContext *s, AVFormatParameters *ap)
         }
     }
 
+    ff_metadata_conv(&s->metadata, NULL, ff_asf_metadata_conv);
+
     return 0;
 }
 
 #define DO_2BITS(bits, var, defval) \
     switch (bits & 3) \
     { \
-    case 3: var = get_le32(pb); rsize += 4; break; \
-    case 2: var = get_le16(pb); rsize += 2; break; \
-    case 1: var = get_byte(pb); rsize++; break; \
+    case 3: var = avio_rl32(pb); rsize += 4; break; \
+    case 2: var = avio_rl16(pb); rsize += 2; break; \
+    case 1: var = avio_r8(pb);   rsize++; break; \
     default: var = defval; break; \
     }
 
@@ -643,7 +717,7 @@ static int asf_read_header(AVFormatContext *s, AVFormatParameters *ap)
  * @param pb context to read data from
  * @return 0 on success, <0 on error
  */
-static int ff_asf_get_packet(AVFormatContext *s, ByteIOContext *pb)
+static int ff_asf_get_packet(AVFormatContext *s, AVIOContext *pb)
 {
     ASFContext *asf = s->priv_data;
     uint32_t packet_length, padsize;
@@ -653,12 +727,12 @@ static int ff_asf_get_packet(AVFormatContext *s, ByteIOContext *pb)
     // if we do not know packet size, allow skipping up to 32 kB
     off= 32768;
     if (s->packet_size > 0)
-        off= (url_ftell(pb) - s->data_offset) % s->packet_size + 3;
+        off= (avio_tell(pb) - s->data_offset) % s->packet_size + 3;
 
     c=d=e=-1;
     while(off-- > 0){
         c=d; d=e;
-        e= get_byte(pb);
+        e= avio_r8(pb);
         if(c == 0x82 && !d && !e)
             break;
     }
@@ -670,22 +744,22 @@ static int ff_asf_get_packet(AVFormatContext *s, ByteIOContext *pb)
          * imply complete -EAGAIN handling support at random positions in
          * the stream.
          */
-        if (url_ferror(pb) == AVERROR(EAGAIN))
+        if (pb->error == AVERROR(EAGAIN))
             return AVERROR(EAGAIN);
-        if (!url_feof(pb))
-            av_log(s, AV_LOG_ERROR, "ff asf bad header %x  at:%"PRId64"\n", c, url_ftell(pb));
+        if (!pb->eof_reached)
+            av_log(s, AV_LOG_ERROR, "ff asf bad header %x  at:%"PRId64"\n", c, avio_tell(pb));
     }
     if ((c & 0x8f) == 0x82) {
         if (d || e) {
-            if (!url_feof(pb))
+            if (!pb->eof_reached)
                 av_log(s, AV_LOG_ERROR, "ff asf bad non zero\n");
             return -1;
         }
-        c= get_byte(pb);
-        d= get_byte(pb);
+        c= avio_r8(pb);
+        d= avio_r8(pb);
         rsize+=3;
     }else{
-        url_fseek(pb, -1, SEEK_CUR); //FIXME
+        avio_seek(pb, -1, SEEK_CUR); //FIXME
     }
 
     asf->packet_flags    = c;
@@ -697,20 +771,20 @@ static int ff_asf_get_packet(AVFormatContext *s, ByteIOContext *pb)
 
     //the following checks prevent overflows and infinite loops
     if(!packet_length || packet_length >= (1U<<29)){
-        av_log(s, AV_LOG_ERROR, "invalid packet_length %d at:%"PRId64"\n", packet_length, url_ftell(pb));
+        av_log(s, AV_LOG_ERROR, "invalid packet_length %d at:%"PRId64"\n", packet_length, avio_tell(pb));
         return -1;
     }
     if(padsize >= packet_length){
-        av_log(s, AV_LOG_ERROR, "invalid padsize %d at:%"PRId64"\n", padsize, url_ftell(pb));
+        av_log(s, AV_LOG_ERROR, "invalid padsize %d at:%"PRId64"\n", padsize, avio_tell(pb));
         return -1;
     }
 
-    asf->packet_timestamp = get_le32(pb);
-    get_le16(pb); /* duration */
+    asf->packet_timestamp = avio_rl32(pb);
+    avio_rl16(pb); /* duration */
     // rsize has at least 11 bytes which have to be present
 
     if (asf->packet_flags & 0x01) {
-        asf->packet_segsizetype = get_byte(pb); rsize++;
+        asf->packet_segsizetype = avio_r8(pb); rsize++;
         asf->packet_segments = asf->packet_segsizetype & 0x3f;
     } else {
         asf->packet_segments = 1;
@@ -720,7 +794,7 @@ static int ff_asf_get_packet(AVFormatContext *s, ByteIOContext *pb)
     if (packet_length < asf->hdr.min_pktsize)
         padsize += asf->hdr.min_pktsize - packet_length;
     asf->packet_padsize = padsize;
-    dprintf(s, "packet: size=%d padsize=%d  left=%d\n", s->packet_size, asf->packet_padsize, asf->packet_size_left);
+    av_dlog(s, "packet: size=%d padsize=%d  left=%d\n", s->packet_size, asf->packet_padsize, asf->packet_size_left);
     return 0;
 }
 
@@ -728,10 +802,10 @@ static int ff_asf_get_packet(AVFormatContext *s, ByteIOContext *pb)
  *
  * @return <0 if error
  */
-static int asf_read_frame_header(AVFormatContext *s, ByteIOContext *pb){
+static int asf_read_frame_header(AVFormatContext *s, AVIOContext *pb){
     ASFContext *asf = s->priv_data;
     int rsize = 1;
-    int num = get_byte(pb);
+    int num = avio_r8(pb);
     int64_t ts0, ts1;
 
     asf->packet_segments--;
@@ -743,26 +817,26 @@ static int asf_read_frame_header(AVFormatContext *s, ByteIOContext *pb){
     DO_2BITS(asf->packet_property, asf->packet_replic_size, 0);
 //printf("key:%d stream:%d seq:%d offset:%d replic_size:%d\n", asf->packet_key_frame, asf->stream_index, asf->packet_seq, //asf->packet_frag_offset, asf->packet_replic_size);
     if (asf->packet_replic_size >= 8) {
-        asf->packet_obj_size = get_le32(pb);
+        asf->packet_obj_size = avio_rl32(pb);
         if(asf->packet_obj_size >= (1<<24) || asf->packet_obj_size <= 0){
             av_log(s, AV_LOG_ERROR, "packet_obj_size invalid\n");
             return -1;
         }
-        asf->packet_frag_timestamp = get_le32(pb); // timestamp
+        asf->packet_frag_timestamp = avio_rl32(pb); // timestamp
         if(asf->packet_replic_size >= 8+38+4){
 //            for(i=0; i<asf->packet_replic_size-8; i++)
-//                av_log(s, AV_LOG_DEBUG, "%02X ",get_byte(pb));
+//                av_log(s, AV_LOG_DEBUG, "%02X ",avio_r8(pb));
 //            av_log(s, AV_LOG_DEBUG, "\n");
-            url_fskip(pb, 10);
-            ts0= get_le64(pb);
-            ts1= get_le64(pb);
-            url_fskip(pb, 12);
-            get_le32(pb);
-            url_fskip(pb, asf->packet_replic_size - 8 - 38 - 4);
+            avio_skip(pb, 10);
+            ts0= avio_rl64(pb);
+            ts1= avio_rl64(pb);
+            avio_skip(pb, 12);
+            avio_rl32(pb);
+            avio_skip(pb, asf->packet_replic_size - 8 - 38 - 4);
             if(ts0!= -1) asf->packet_frag_timestamp= ts0/10000;
             else         asf->packet_frag_timestamp= AV_NOPTS_VALUE;
         }else
-            url_fskip(pb, asf->packet_replic_size - 8);
+            avio_skip(pb, asf->packet_replic_size - 8);
         rsize += asf->packet_replic_size; // FIXME - check validity
     } else if (asf->packet_replic_size==1){
         // multipacket - frag_offset is beginning timestamp
@@ -770,7 +844,7 @@ static int asf_read_frame_header(AVFormatContext *s, ByteIOContext *pb){
         asf->packet_frag_offset = 0;
         asf->packet_frag_timestamp = asf->packet_timestamp;
 
-        asf->packet_time_delta = get_byte(pb);
+        asf->packet_time_delta = avio_r8(pb);
         rsize++;
     }else if(asf->packet_replic_size!=0){
         av_log(s, AV_LOG_ERROR, "unexpected packet_replic_size of %d\n", asf->packet_replic_size);
@@ -807,23 +881,24 @@ static int asf_read_frame_header(AVFormatContext *s, ByteIOContext *pb){
  * @return 0 if data was stored in pkt, <0 on error or 1 if more ASF
  *          packets need to be loaded (through asf_get_packet())
  */
-static int ff_asf_parse_packet(AVFormatContext *s, ByteIOContext *pb, AVPacket *pkt)
+static int ff_asf_parse_packet(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
 {
     ASFContext *asf = s->priv_data;
     ASFStream *asf_st = 0;
     for (;;) {
-        if(url_feof(pb))
+        int ret;
+        if(pb->eof_reached)
             return AVERROR_EOF;
         if (asf->packet_size_left < FRAME_HEADER_SIZE
             || asf->packet_segments < 1) {
             //asf->packet_size_left <= asf->packet_padsize) {
             int ret = asf->packet_size_left + asf->packet_padsize;
-            //printf("PacketLeftSize:%d  Pad:%d Pos:%"PRId64"\n", asf->packet_size_left, asf->packet_padsize, url_ftell(pb));
+            //printf("PacketLeftSize:%d  Pad:%d Pos:%"PRId64"\n", asf->packet_size_left, asf->packet_padsize, avio_tell(pb));
             assert(ret>=0);
             /* fail safe */
-            url_fskip(pb, ret);
+            avio_skip(pb, ret);
 
-            asf->packet_pos= url_ftell(pb);
+            asf->packet_pos= avio_tell(pb);
             if (asf->data_object_size != (uint64_t)-1 &&
                 (asf->packet_pos - asf->data_object_offset >= asf->data_object_size))
                 return AVERROR_EOF; /* Do not exceed the size of the data object */
@@ -840,7 +915,7 @@ static int ff_asf_parse_packet(AVFormatContext *s, ByteIOContext *pb, AVPacket *
                 ) {
                 asf->packet_time_start = 0;
                 /* unhandled packet (should not happen) */
-                url_fskip(pb, asf->packet_frag_size);
+                avio_skip(pb, asf->packet_frag_size);
                 asf->packet_size_left -= asf->packet_frag_size;
                 if(asf->stream_index < 0)
                     av_log(s, AV_LOG_ERROR, "ff asf skip %d (unknown stream)\n", asf->packet_frag_size);
@@ -854,13 +929,13 @@ static int ff_asf_parse_packet(AVFormatContext *s, ByteIOContext *pb, AVPacket *
             // frag_offset is here used as the beginning timestamp
             asf->packet_frag_timestamp = asf->packet_time_start;
             asf->packet_time_start += asf->packet_time_delta;
-            asf->packet_obj_size = asf->packet_frag_size = get_byte(pb);
+            asf->packet_obj_size = asf->packet_frag_size = avio_r8(pb);
             asf->packet_size_left--;
             asf->packet_multi_size--;
             if (asf->packet_multi_size < asf->packet_obj_size)
             {
                 asf->packet_time_start = 0;
-                url_fskip(pb, asf->packet_multi_size);
+                avio_skip(pb, asf->packet_multi_size);
                 asf->packet_size_left -= asf->packet_multi_size;
                 continue;
             }
@@ -886,10 +961,21 @@ static int ff_asf_parse_packet(AVFormatContext *s, ByteIOContext *pb, AVPacket *
             /* new packet */
             av_new_packet(&asf_st->pkt, asf->packet_obj_size);
             asf_st->seq = asf->packet_seq;
-            asf_st->pkt.dts = asf->packet_frag_timestamp;
+            asf_st->pkt.dts = asf->packet_frag_timestamp - asf->hdr.preroll;
             asf_st->pkt.stream_index = asf->stream_index;
             asf_st->pkt.pos =
             asf_st->packet_pos= asf->packet_pos;
+            if (asf_st->pkt.data && asf_st->palette_changed) {
+                uint8_t *pal;
+                pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE,
+                                              AVPALETTE_SIZE);
+                if (!pal) {
+                    av_log(s, AV_LOG_ERROR, "Cannot append palette to packet\n");
+                } else {
+                    memcpy(pal, asf_st->palette, AVPALETTE_SIZE);
+                    asf_st->palette_changed = 0;
+                }
+            }
 //printf("new packet: stream:%d key:%d packet_key:%d audio:%d size:%d\n",
 //asf->stream_index, asf->packet_key_frame, asf_st->pkt.flags & AV_PKT_FLAG_KEY,
 //s->streams[asf->stream_index]->codec->codec_type == AVMEDIA_TYPE_AUDIO, asf->packet_obj_size);
@@ -914,12 +1000,26 @@ static int ff_asf_parse_packet(AVFormatContext *s, ByteIOContext *pb, AVPacket *
             continue;
         }
 
-        get_buffer(pb, asf_st->pkt.data + asf->packet_frag_offset,
-                   asf->packet_frag_size);
+        ret = avio_read(pb, asf_st->pkt.data + asf->packet_frag_offset,
+                         asf->packet_frag_size);
+        if (ret != asf->packet_frag_size) {
+            if (ret < 0 || asf->packet_frag_offset + ret == 0)
+                return ret < 0 ? ret : AVERROR_EOF;
+            if (asf_st->ds_span > 1) {
+                // scrambling, we can either drop it completely or fill the remainder
+                // TODO: should we fill the whole packet instead of just the current
+                // fragment?
+                memset(asf_st->pkt.data + asf->packet_frag_offset + ret, 0,
+                       asf->packet_frag_size - ret);
+                ret = asf->packet_frag_size;
+            } else
+                // no scrambling, so we can return partial packets
+                av_shrink_packet(&asf_st->pkt, asf->packet_frag_offset + ret);
+        }
         if (s->key && s->keylen == 20)
             ff_asfcrypt_dec(s->key, asf_st->pkt.data + asf->packet_frag_offset,
-                            asf->packet_frag_size);
-        asf_st->frag_offset += asf->packet_frag_size;
+                            ret);
+        asf_st->frag_offset += ret;
         /* test if whole packet is read */
         if (asf_st->frag_offset == asf_st->pkt.size) {
             //workaround for macroshit radio DVR-MS files
@@ -941,9 +1041,10 @@ static int ff_asf_parse_packet(AVFormatContext *s, ByteIOContext *pb, AVPacket *
                     av_log(s, AV_LOG_ERROR, "pkt.size != ds_packet_size * ds_span (%d %d %d)\n", asf_st->pkt.size, asf_st->ds_packet_size, asf_st->ds_span);
               }else{
                 /* packet descrambling */
-                uint8_t *newdata = av_malloc(asf_st->pkt.size);
+                uint8_t *newdata = av_malloc(asf_st->pkt.size + FF_INPUT_BUFFER_PADDING_SIZE);
                 if (newdata) {
                     int offset = 0;
+                    memset(newdata + asf_st->pkt.size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
                     while (offset < asf_st->pkt.size) {
                         int off = offset / asf_st->ds_chunk_size;
                         int row = off / asf_st->ds_span;
@@ -1001,7 +1102,6 @@ static void asf_reset_header(AVFormatContext *s)
     ASFStream *asf_st;
     int i;
 
-    asf->packet_nb_frames = 0;
     asf->packet_size_left = 0;
     asf->packet_segments = 0;
     asf->packet_flags = 0;
@@ -1032,13 +1132,8 @@ static void asf_reset_header(AVFormatContext *s)
 
 static int asf_read_close(AVFormatContext *s)
 {
-    int i;
-
     asf_reset_header(s);
-    for(i=0;i<s->nb_streams;i++) {
-        AVStream *st = s->streams[i];
-        av_free(st->codec->palctrl);
-    }
+
     return 0;
 }
 
@@ -1049,7 +1144,7 @@ static int64_t asf_read_pts(AVFormatContext *s, int stream_index, int64_t *ppos,
     int64_t pts;
     int64_t pos= *ppos;
     int i;
-    int64_t start_pos[s->nb_streams];
+    int64_t start_pos[ASF_MAX_STREAMS];
 
     for(i=0; i<s->nb_streams; i++){
         start_pos[i]= pos;
@@ -1058,7 +1153,7 @@ static int64_t asf_read_pts(AVFormatContext *s, int stream_index, int64_t *ppos,
     if (s->packet_size > 0)
         pos= (pos+s->packet_size-1-s->data_offset)/s->packet_size*s->packet_size+ s->data_offset;
     *ppos= pos;
-    url_fseek(s->pb, pos, SEEK_SET);
+    avio_seek(s->pb, pos, SEEK_SET);
 
 //printf("asf_read_pts\n");
     asf_reset_header(s);
@@ -1097,36 +1192,49 @@ static void asf_build_simple_index(AVFormatContext *s, int stream_index)
 {
     ff_asf_guid g;
     ASFContext *asf = s->priv_data;
-    int64_t current_pos= url_ftell(s->pb);
+    int64_t current_pos= avio_tell(s->pb);
     int i;
 
-    url_fseek(s->pb, asf->data_object_offset + asf->data_object_size, SEEK_SET);
-    get_guid(s->pb, &g);
-    if (!guidcmp(&g, &index_guid)) {
+    avio_seek(s->pb, asf->data_object_offset + asf->data_object_size, SEEK_SET);
+    ff_get_guid(s->pb, &g);
+
+    /* the data object can be followed by other top-level objects,
+       skip them until the simple index object is reached */
+    while (ff_guidcmp(&g, &index_guid)) {
+        int64_t gsize= avio_rl64(s->pb);
+        if (gsize < 24 || s->pb->eof_reached) {
+            avio_seek(s->pb, current_pos, SEEK_SET);
+            return;
+        }
+        avio_skip(s->pb, gsize-24);
+        ff_get_guid(s->pb, &g);
+    }
+
+    {
         int64_t itime, last_pos=-1;
         int pct, ict;
-        int64_t av_unused gsize= get_le64(s->pb);
-        get_guid(s->pb, &g);
-        itime=get_le64(s->pb);
-        pct=get_le32(s->pb);
-        ict=get_le32(s->pb);
+        int64_t av_unused gsize= avio_rl64(s->pb);
+        ff_get_guid(s->pb, &g);
+        itime=avio_rl64(s->pb);
+        pct=avio_rl32(s->pb);
+        ict=avio_rl32(s->pb);
         av_log(s, AV_LOG_DEBUG, "itime:0x%"PRIx64", pct:%d, ict:%d\n",itime,pct,ict);
 
         for (i=0;i<ict;i++){
-            int pktnum=get_le32(s->pb);
-            int pktct =get_le16(s->pb);
+            int pktnum=avio_rl32(s->pb);
+            int pktct =avio_rl16(s->pb);
             int64_t pos      = s->data_offset + s->packet_size*(int64_t)pktnum;
-            int64_t index_pts= av_rescale(itime, i, 10000);
+            int64_t index_pts= FFMAX(av_rescale(itime, i, 10000) - asf->hdr.preroll, 0);
 
             if(pos != last_pos){
-            av_log(s, AV_LOG_DEBUG, "pktnum:%d, pktct:%d\n", pktnum, pktct);
+            av_log(s, AV_LOG_DEBUG, "pktnum:%d, pktct:%d  pts: %"PRId64"\n", pktnum, pktct, index_pts);
             av_add_index_entry(s->streams[stream_index], pos, index_pts, s->packet_size, 0, AVINDEX_KEYFRAME);
             last_pos=pos;
             }
         }
         asf->index_read= 1;
     }
-    url_fseek(s->pb, current_pos, SEEK_SET);
+    avio_seek(s->pb, current_pos, SEEK_SET);
 }
 
 static int asf_read_seek(AVFormatContext *s, int stream_index, int64_t pts, int flags)
@@ -1141,7 +1249,7 @@ static int asf_read_seek(AVFormatContext *s, int stream_index, int64_t pts, int
 
     /* Try using the protocol's read_seek if available */
     if(s->pb) {
-        int ret = av_url_read_fseek(s->pb, stream_index, pts, flags);
+        int ret = avio_seek_time(s->pb, stream_index, pts, flags);
         if(ret >= 0)
             asf_reset_header(s);
         if (ret != AVERROR(ENOSYS))
@@ -1164,10 +1272,10 @@ static int asf_read_seek(AVFormatContext *s, int stream_index, int64_t pts, int
 
     // various attempts to find key frame have failed so far
     //    asf_reset_header(s);
-    //    url_fseek(s->pb, pos, SEEK_SET);
+    //    avio_seek(s->pb, pos, SEEK_SET);
     //    key_pos = pos;
     //     for(i=0;i<16;i++){
-    //         pos = url_ftell(s->pb);
+    //         pos = avio_tell(s->pb);
     //         if (av_read_frame(s, &pkt) < 0){
     //             av_log(s, AV_LOG_INFO, "seek failed\n");
     //             return -1;
@@ -1185,13 +1293,13 @@ static int asf_read_seek(AVFormatContext *s, int stream_index, int64_t pts, int
 
         /* do the seek */
         av_log(s, AV_LOG_DEBUG, "SEEKTO: %"PRId64"\n", pos);
-        url_fseek(s->pb, pos, SEEK_SET);
+        avio_seek(s->pb, pos, SEEK_SET);
     }
     asf_reset_header(s);
     return 0;
 }
 
-AVInputFormat asf_demuxer = {
+AVInputFormat ff_asf_demuxer = {
     "asf",
     NULL_IF_CONFIG_SMALL("ASF format"),
     sizeof(ASFContext),
@@ -1201,5 +1309,4 @@ AVInputFormat asf_demuxer = {
     asf_read_close,
     asf_read_seek,
     asf_read_pts,
-    .metadata_conv = ff_asf_metadata_conv,
 };
diff --git a/libavformat/asfenc.c b/libavformat/asfenc.c
index 9f8d69a..f9cc609 100644
--- a/libavformat/asfenc.c
+++ b/libavformat/asfenc.c
@@ -2,26 +2,27 @@
  * ASF muxer
  * Copyright (c) 2000, 2001 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #include "avformat.h"
 #include "metadata.h"
 #include "riff.h"
 #include "asf.h"
+#include "avio_internal.h"
 
 #undef NDEBUG
 #include <assert.h>
@@ -188,6 +189,31 @@
                 2*PAYLOAD_HEADER_SIZE_MULTIPLE_PAYLOADS \
                 )
 
+typedef struct {
+    uint32_t seqno;
+    int is_streamed;
+    ASFStream streams[128];              ///< it's max number and it's not that big
+    /* non streamed additonnal info */
+    uint64_t nb_packets;                 ///< how many packets are there in the file, invalid if broadcasting
+    int64_t duration;                    ///< in 100ns units
+    /* packet filling */
+    unsigned char multi_payloads_present;
+    int packet_size_left;
+    int packet_timestamp_start;
+    int packet_timestamp_end;
+    unsigned int packet_nb_payloads;
+    uint8_t packet_buf[PACKET_SIZE];
+    AVIOContext pb;
+    /* only for reading */
+    uint64_t data_offset;                ///< beginning of the first data packet
+
+    int64_t last_indexed_pts;
+    ASFIndex* index_ptr;
+    uint32_t nb_index_count;
+    uint32_t nb_index_memory_alloc;
+    uint16_t maximum_packet;
+} ASFContext;
+
 static const AVCodecTag codec_asf_bmp_tags[] = {
     { CODEC_ID_MPEG4, MKTAG('M', 'P', '4', 'S') },
     { CODEC_ID_MPEG4, MKTAG('M', '4', 'S', '2') },
@@ -197,61 +223,61 @@ static const AVCodecTag codec_asf_bmp_tags[] = {
 
 #define PREROLL_TIME 3100
 
-static void put_guid(ByteIOContext *s, const ff_asf_guid *g)
+static void put_guid(AVIOContext *s, const ff_asf_guid *g)
 {
     assert(sizeof(*g) == 16);
-    put_buffer(s, *g, sizeof(*g));
+    avio_write(s, *g, sizeof(*g));
 }
 
-static void put_str16(ByteIOContext *s, const char *tag)
+static void put_str16(AVIOContext *s, const char *tag)
 {
     int len;
     uint8_t *pb;
-    ByteIOContext *dyn_buf;
-    if (url_open_dyn_buf(&dyn_buf) < 0)
+    AVIOContext *dyn_buf;
+    if (avio_open_dyn_buf(&dyn_buf) < 0)
         return;
 
-    ff_put_str16_nolen(dyn_buf, tag);
-    len = url_close_dyn_buf(dyn_buf, &pb);
-    put_le16(s, len);
-    put_buffer(s, pb, len);
+    avio_put_str16le(dyn_buf, tag);
+    len = avio_close_dyn_buf(dyn_buf, &pb);
+    avio_wl16(s, len);
+    avio_write(s, pb, len);
     av_freep(&pb);
 }
 
-static int64_t put_header(ByteIOContext *pb, const ff_asf_guid *g)
+static int64_t put_header(AVIOContext *pb, const ff_asf_guid *g)
 {
     int64_t pos;
 
-    pos = url_ftell(pb);
+    pos = avio_tell(pb);
     put_guid(pb, g);
-    put_le64(pb, 24);
+    avio_wl64(pb, 24);
     return pos;
 }
 
 /* update header size */
-static void end_header(ByteIOContext *pb, int64_t pos)
+static void end_header(AVIOContext *pb, int64_t pos)
 {
     int64_t pos1;
 
-    pos1 = url_ftell(pb);
-    url_fseek(pb, pos + 16, SEEK_SET);
-    put_le64(pb, pos1 - pos);
-    url_fseek(pb, pos1, SEEK_SET);
+    pos1 = avio_tell(pb);
+    avio_seek(pb, pos + 16, SEEK_SET);
+    avio_wl64(pb, pos1 - pos);
+    avio_seek(pb, pos1, SEEK_SET);
 }
 
 /* write an asf chunk (only used in streaming case) */
 static void put_chunk(AVFormatContext *s, int type, int payload_length, int flags)
 {
     ASFContext *asf = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int length;
 
     length = payload_length + 8;
-    put_le16(pb, type);
-    put_le16(pb, length);    //size
-    put_le32(pb, asf->seqno);//sequence number
-    put_le16(pb, flags); /* unknown bytes */
-    put_le16(pb, length);    //size_confirm
+    avio_wl16(pb, type);
+    avio_wl16(pb, length);    //size
+    avio_wl32(pb, asf->seqno);//sequence number
+    avio_wl16(pb, flags); /* unknown bytes */
+    avio_wl16(pb, length);    //size_confirm
     asf->seqno++;
 }
 
@@ -269,7 +295,7 @@ static int64_t unix_to_file_time(int ti)
 static int asf_write_header1(AVFormatContext *s, int64_t file_size, int64_t data_chunk_size)
 {
     ASFContext *asf = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVMetadataTag *tags[5];
     int header_size, n, extra_size, extra_size2, wav_extra_size, file_time;
     int has_title;
@@ -279,6 +305,8 @@ static int asf_write_header1(AVFormatContext *s, int64_t file_size, int64_t data
     int bit_rate;
     int64_t duration;
 
+    ff_metadata_conv(&s->metadata, ff_asf_metadata_conv, NULL);
+
     tags[0] = av_metadata_get(s->metadata, "title"    , NULL, 0);
     tags[1] = av_metadata_get(s->metadata, "author"   , NULL, 0);
     tags[2] = av_metadata_get(s->metadata, "copyright", NULL, 0);
@@ -303,62 +331,62 @@ static int asf_write_header1(AVFormatContext *s, int64_t file_size, int64_t data
     }
 
     put_guid(pb, &ff_asf_header);
-    put_le64(pb, -1); /* header length, will be patched after */
-    put_le32(pb, 3 + has_title + !!metadata_count + s->nb_streams); /* number of chunks in header */
-    put_byte(pb, 1); /* ??? */
-    put_byte(pb, 2); /* ??? */
+    avio_wl64(pb, -1); /* header length, will be patched after */
+    avio_wl32(pb, 3 + has_title + !!metadata_count + s->nb_streams); /* number of chunks in header */
+    avio_w8(pb, 1); /* ??? */
+    avio_w8(pb, 2); /* ??? */
 
     /* file header */
-    header_offset = url_ftell(pb);
+    header_offset = avio_tell(pb);
     hpos = put_header(pb, &ff_asf_file_header);
     put_guid(pb, &ff_asf_my_guid);
-    put_le64(pb, file_size);
+    avio_wl64(pb, file_size);
     file_time = 0;
-    put_le64(pb, unix_to_file_time(file_time));
-    put_le64(pb, asf->nb_packets); /* number of packets */
-    put_le64(pb, duration); /* end time stamp (in 100ns units) */
-    put_le64(pb, asf->duration); /* duration (in 100ns units) */
-    put_le64(pb, PREROLL_TIME); /* start time stamp */
-    put_le32(pb, (asf->is_streamed || url_is_streamed(pb)) ? 3 : 2); /* ??? */
-    put_le32(pb, s->packet_size); /* packet size */
-    put_le32(pb, s->packet_size); /* packet size */
-    put_le32(pb, bit_rate); /* Nominal data rate in bps */
+    avio_wl64(pb, unix_to_file_time(file_time));
+    avio_wl64(pb, asf->nb_packets); /* number of packets */
+    avio_wl64(pb, duration); /* end time stamp (in 100ns units) */
+    avio_wl64(pb, asf->duration); /* duration (in 100ns units) */
+    avio_wl64(pb, PREROLL_TIME); /* start time stamp */
+    avio_wl32(pb, (asf->is_streamed || !pb->seekable ) ? 3 : 2); /* ??? */
+    avio_wl32(pb, s->packet_size); /* packet size */
+    avio_wl32(pb, s->packet_size); /* packet size */
+    avio_wl32(pb, bit_rate); /* Nominal data rate in bps */
     end_header(pb, hpos);
 
     /* unknown headers */
     hpos = put_header(pb, &ff_asf_head1_guid);
     put_guid(pb, &ff_asf_head2_guid);
-    put_le32(pb, 6);
-    put_le16(pb, 0);
+    avio_wl32(pb, 6);
+    avio_wl16(pb, 0);
     end_header(pb, hpos);
 
     /* title and other infos */
     if (has_title) {
         int len;
         uint8_t *buf;
-        ByteIOContext *dyn_buf;
+        AVIOContext *dyn_buf;
 
-        if (url_open_dyn_buf(&dyn_buf) < 0)
+        if (avio_open_dyn_buf(&dyn_buf) < 0)
             return AVERROR(ENOMEM);
 
         hpos = put_header(pb, &ff_asf_comment_header);
 
         for (n = 0; n < FF_ARRAY_ELEMS(tags); n++) {
-            len = tags[n] ? ff_put_str16_nolen(dyn_buf, tags[n]->value) : 0;
-            put_le16(pb, len);
+            len = tags[n] ? avio_put_str16le(dyn_buf, tags[n]->value) : 0;
+            avio_wl16(pb, len);
         }
-        len = url_close_dyn_buf(dyn_buf, &buf);
-        put_buffer(pb, buf, len);
+        len = avio_close_dyn_buf(dyn_buf, &buf);
+        avio_write(pb, buf, len);
         av_freep(&buf);
         end_header(pb, hpos);
     }
     if (metadata_count) {
         AVMetadataTag *tag = NULL;
         hpos = put_header(pb, &ff_asf_extended_content_header);
-        put_le16(pb, metadata_count);
+        avio_wl16(pb, metadata_count);
         while ((tag = av_metadata_get(s->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX))) {
             put_str16(pb, tag->key);
-            put_le16(pb, 0);
+            avio_wl16(pb, 0);
             put_str16(pb, tag->value);
         }
         end_header(pb, hpos);
@@ -396,45 +424,45 @@ static int asf_write_header1(AVFormatContext *s, int64_t file_size, int64_t data
             put_guid(pb, &ff_asf_video_stream);
             put_guid(pb, &ff_asf_video_conceal_none);
         }
-        put_le64(pb, 0); /* ??? */
-        es_pos = url_ftell(pb);
-        put_le32(pb, extra_size); /* wav header len */
-        put_le32(pb, extra_size2); /* additional data len */
-        put_le16(pb, n + 1); /* stream number */
-        put_le32(pb, 0); /* ??? */
+        avio_wl64(pb, 0); /* ??? */
+        es_pos = avio_tell(pb);
+        avio_wl32(pb, extra_size); /* wav header len */
+        avio_wl32(pb, extra_size2); /* additional data len */
+        avio_wl16(pb, n + 1); /* stream number */
+        avio_wl32(pb, 0); /* ??? */
 
         if (enc->codec_type == AVMEDIA_TYPE_AUDIO) {
             /* WAVEFORMATEX header */
             int wavsize = ff_put_wav_header(pb, enc);
             if ((enc->codec_id != CODEC_ID_MP3) && (enc->codec_id != CODEC_ID_MP2) && (enc->codec_id != CODEC_ID_ADPCM_IMA_WAV) && (enc->extradata_size==0)) {
                 wavsize += 2;
-                put_le16(pb, 0);
+                avio_wl16(pb, 0);
             }
 
             if (wavsize < 0)
                 return -1;
             if (wavsize != extra_size) {
-                cur_pos = url_ftell(pb);
-                url_fseek(pb, es_pos, SEEK_SET);
-                put_le32(pb, wavsize); /* wav header len */
-                url_fseek(pb, cur_pos, SEEK_SET);
+                cur_pos = avio_tell(pb);
+                avio_seek(pb, es_pos, SEEK_SET);
+                avio_wl32(pb, wavsize); /* wav header len */
+                avio_seek(pb, cur_pos, SEEK_SET);
             }
             /* ERROR Correction */
-            put_byte(pb, 0x01);
+            avio_w8(pb, 0x01);
             if(enc->codec_id == CODEC_ID_ADPCM_G726 || !enc->block_align){
-                put_le16(pb, 0x0190);
-                put_le16(pb, 0x0190);
+                avio_wl16(pb, 0x0190);
+                avio_wl16(pb, 0x0190);
             }else{
-                put_le16(pb, enc->block_align);
-                put_le16(pb, enc->block_align);
+                avio_wl16(pb, enc->block_align);
+                avio_wl16(pb, enc->block_align);
             }
-            put_le16(pb, 0x01);
-            put_byte(pb, 0x00);
+            avio_wl16(pb, 0x01);
+            avio_w8(pb, 0x00);
         } else {
-            put_le32(pb, enc->width);
-            put_le32(pb, enc->height);
-            put_byte(pb, 2); /* ??? */
-            put_le16(pb, 40 + enc->extradata_size); /* size */
+            avio_wl32(pb, enc->width);
+            avio_wl32(pb, enc->height);
+            avio_w8(pb, 2); /* ??? */
+            avio_wl16(pb, 40 + enc->extradata_size); /* size */
 
             /* BITMAPINFOHEADER header */
             ff_put_bmp_header(pb, enc, ff_codec_bmp_tags, 1);
@@ -446,49 +474,49 @@ static int asf_write_header1(AVFormatContext *s, int64_t file_size, int64_t data
 
     hpos = put_header(pb, &ff_asf_codec_comment_header);
     put_guid(pb, &ff_asf_codec_comment1_header);
-    put_le32(pb, s->nb_streams);
+    avio_wl32(pb, s->nb_streams);
     for(n=0;n<s->nb_streams;n++) {
         AVCodec *p;
         const char *desc;
         int len;
         uint8_t *buf;
-        ByteIOContext *dyn_buf;
+        AVIOContext *dyn_buf;
 
         enc = s->streams[n]->codec;
         p = avcodec_find_encoder(enc->codec_id);
 
         if(enc->codec_type == AVMEDIA_TYPE_AUDIO)
-            put_le16(pb, 2);
+            avio_wl16(pb, 2);
         else if(enc->codec_type == AVMEDIA_TYPE_VIDEO)
-            put_le16(pb, 1);
+            avio_wl16(pb, 1);
         else
-            put_le16(pb, -1);
+            avio_wl16(pb, -1);
 
         if(enc->codec_id == CODEC_ID_WMAV2)
             desc = "Windows Media Audio V8";
         else
             desc = p ? p->name : enc->codec_name;
 
-        if ( url_open_dyn_buf(&dyn_buf) < 0)
+        if ( avio_open_dyn_buf(&dyn_buf) < 0)
             return AVERROR(ENOMEM);
 
-        ff_put_str16_nolen(dyn_buf, desc);
-        len = url_close_dyn_buf(dyn_buf, &buf);
-        put_le16(pb, len / 2); // "number of characters" = length in bytes / 2
+        avio_put_str16le(dyn_buf, desc);
+        len = avio_close_dyn_buf(dyn_buf, &buf);
+        avio_wl16(pb, len / 2); // "number of characters" = length in bytes / 2
 
-        put_buffer(pb, buf, len);
+        avio_write(pb, buf, len);
         av_freep(&buf);
 
-        put_le16(pb, 0); /* no parameters */
+        avio_wl16(pb, 0); /* no parameters */
 
 
         /* id */
         if (enc->codec_type == AVMEDIA_TYPE_AUDIO) {
-            put_le16(pb, 2);
-            put_le16(pb, enc->codec_tag);
+            avio_wl16(pb, 2);
+            avio_wl16(pb, enc->codec_tag);
         } else {
-            put_le16(pb, 4);
-            put_le32(pb, enc->codec_tag);
+            avio_wl16(pb, 4);
+            avio_wl32(pb, enc->codec_tag);
         }
         if(!enc->codec_tag)
             return -1;
@@ -497,31 +525,31 @@ static int asf_write_header1(AVFormatContext *s, int64_t file_size, int64_t data
 
     /* patch the header size fields */
 
-    cur_pos = url_ftell(pb);
+    cur_pos = avio_tell(pb);
     header_size = cur_pos - header_offset;
     if (asf->is_streamed) {
         header_size += 8 + 30 + 50;
 
-        url_fseek(pb, header_offset - 10 - 30, SEEK_SET);
-        put_le16(pb, header_size);
-        url_fseek(pb, header_offset - 2 - 30, SEEK_SET);
-        put_le16(pb, header_size);
+        avio_seek(pb, header_offset - 10 - 30, SEEK_SET);
+        avio_wl16(pb, header_size);
+        avio_seek(pb, header_offset - 2 - 30, SEEK_SET);
+        avio_wl16(pb, header_size);
 
         header_size -= 8 + 30 + 50;
     }
     header_size += 24 + 6;
-    url_fseek(pb, header_offset - 14, SEEK_SET);
-    put_le64(pb, header_size);
-    url_fseek(pb, cur_pos, SEEK_SET);
+    avio_seek(pb, header_offset - 14, SEEK_SET);
+    avio_wl64(pb, header_size);
+    avio_seek(pb, cur_pos, SEEK_SET);
 
     /* movie chunk, followed by packets of packet_size */
     asf->data_offset = cur_pos;
     put_guid(pb, &ff_asf_data_header);
-    put_le64(pb, data_chunk_size);
+    avio_wl64(pb, data_chunk_size);
     put_guid(pb, &ff_asf_my_guid);
-    put_le64(pb, asf->nb_packets); /* nb packets */
-    put_byte(pb, 1); /* ??? */
-    put_byte(pb, 1); /* ??? */
+    avio_wl64(pb, asf->nb_packets); /* nb packets */
+    avio_w8(pb, 1); /* ??? */
+    avio_w8(pb, 1); /* ??? */
     return 0;
 }
 
@@ -546,12 +574,12 @@ static int asf_write_header(AVFormatContext *s)
         return -1;
     }
 
-    put_flush_packet(s->pb);
+    avio_flush(s->pb);
 
     asf->packet_nb_payloads = 0;
     asf->packet_timestamp_start = -1;
     asf->packet_timestamp_end = -1;
-    init_put_byte(&asf->pb, asf->packet_buf, s->packet_size, 1,
+    ffio_init_context(&asf->pb, asf->packet_buf, s->packet_size, 1,
                   NULL, NULL, NULL, NULL);
 
     return 0;
@@ -575,9 +603,9 @@ static int put_payload_parsing_info(
             )
 {
     ASFContext *asf = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int ppi_size, i;
-    int64_t start= url_ftell(pb);
+    int64_t start= avio_tell(pb);
 
     int iLengthTypeFlags = ASF_PPI_LENGTH_TYPE_FLAGS;
 
@@ -586,9 +614,9 @@ static int put_payload_parsing_info(
         padsize--;
     assert(padsize>=0);
 
-    put_byte(pb, ASF_PACKET_ERROR_CORRECTION_FLAGS);
+    avio_w8(pb, ASF_PACKET_ERROR_CORRECTION_FLAGS);
     for (i = 0; i < ASF_PACKET_ERROR_CORRECTION_DATA_SIZE; i++){
-        put_byte(pb, 0x0);
+        avio_w8(pb, 0x0);
     }
 
     if (asf->multi_payloads_present)
@@ -600,21 +628,21 @@ static int put_payload_parsing_info(
         else
             iLengthTypeFlags |= ASF_PPI_FLAG_PADDING_LENGTH_FIELD_IS_WORD;
     }
-    put_byte(pb, iLengthTypeFlags);
+    avio_w8(pb, iLengthTypeFlags);
 
-    put_byte(pb, ASF_PPI_PROPERTY_FLAGS);
+    avio_w8(pb, ASF_PPI_PROPERTY_FLAGS);
 
     if (iLengthTypeFlags & ASF_PPI_FLAG_PADDING_LENGTH_FIELD_IS_WORD)
-        put_le16(pb, padsize - 2);
+        avio_wl16(pb, padsize - 2);
     if (iLengthTypeFlags & ASF_PPI_FLAG_PADDING_LENGTH_FIELD_IS_BYTE)
-        put_byte(pb, padsize - 1);
+        avio_w8(pb, padsize - 1);
 
-    put_le32(pb, sendtime);
-    put_le16(pb, duration);
+    avio_wl32(pb, sendtime);
+    avio_wl16(pb, duration);
     if (asf->multi_payloads_present)
-        put_byte(pb, nb_payloads | ASF_PAYLOAD_FLAGS);
+        avio_w8(pb, nb_payloads | ASF_PAYLOAD_FLAGS);
 
-    ppi_size = url_ftell(pb) - start;
+    ppi_size = avio_tell(pb) - start;
 
     return ppi_size;
 }
@@ -642,14 +670,14 @@ static void flush_packet(AVFormatContext *s)
     assert(packet_hdr_size <= asf->packet_size_left);
     memset(asf->packet_buf + packet_filled_size, 0, asf->packet_size_left);
 
-    put_buffer(s->pb, asf->packet_buf, s->packet_size - packet_hdr_size);
+    avio_write(s->pb, asf->packet_buf, s->packet_size - packet_hdr_size);
 
-    put_flush_packet(s->pb);
+    avio_flush(s->pb);
     asf->nb_packets++;
     asf->packet_nb_payloads = 0;
     asf->packet_timestamp_start = -1;
     asf->packet_timestamp_end = -1;
-    init_put_byte(&asf->pb, asf->packet_buf, s->packet_size, 1,
+    ffio_init_context(&asf->pb, asf->packet_buf, s->packet_size, 1,
                   NULL, NULL, NULL, NULL);
 }
 
@@ -664,29 +692,29 @@ static void put_payload_header(
             )
 {
     ASFContext *asf = s->priv_data;
-    ByteIOContext *pb = &asf->pb;
+    AVIOContext *pb = &asf->pb;
     int val;
 
     val = stream->num;
     if (flags & AV_PKT_FLAG_KEY)
         val |= ASF_PL_FLAG_KEY_FRAME;
-    put_byte(pb, val);
+    avio_w8(pb, val);
 
-    put_byte(pb, stream->seq);  //Media object number
-    put_le32(pb, m_obj_offset); //Offset Into Media Object
+    avio_w8(pb, stream->seq);  //Media object number
+    avio_wl32(pb, m_obj_offset); //Offset Into Media Object
 
     // Replicated Data shall be at least 8 bytes long.
     // The first 4 bytes of data shall contain the
     // Size of the Media Object that the payload belongs to.
     // The next 4 bytes of data shall contain the
     // Presentation Time for the media object that the payload belongs to.
-    put_byte(pb, ASF_PAYLOAD_REPLICATED_DATA_LENGTH);
+    avio_w8(pb, ASF_PAYLOAD_REPLICATED_DATA_LENGTH);
 
-    put_le32(pb, m_obj_size);       //Replicated Data - Media Object Size
-    put_le32(pb, presentation_time);//Replicated Data - Presentation Time
+    avio_wl32(pb, m_obj_size);       //Replicated Data - Media Object Size
+    avio_wl32(pb, presentation_time);//Replicated Data - Presentation Time
 
     if (asf->multi_payloads_present){
-        put_le16(pb, payload_len);   //payload length
+        avio_wl16(pb, payload_len);   //payload length
     }
 }
 
@@ -734,7 +762,7 @@ static void put_frame(
                 payload_len = frag_len1 - 2;  //additional byte need to put padding length
 
             put_payload_header(s, stream, timestamp+PREROLL_TIME, m_obj_size, m_obj_offset, payload_len, flags);
-            put_buffer(&asf->pb, buf, payload_len);
+            avio_write(&asf->pb, buf, payload_len);
 
             if (asf->multi_payloads_present)
                 asf->packet_size_left -= (payload_len + PAYLOAD_HEADER_SIZE_MULTIPLE_PAYLOADS);
@@ -805,18 +833,18 @@ static int asf_write_packet(AVFormatContext *s, AVPacket *pkt)
 //
 static int asf_write_index(AVFormatContext *s, ASFIndex *index, uint16_t max, uint32_t count)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int i;
 
     put_guid(pb, &ff_asf_simple_index_header);
-    put_le64(pb, 24 + 16 + 8 + 4 + 4 + (4 + 2)*count);
+    avio_wl64(pb, 24 + 16 + 8 + 4 + 4 + (4 + 2)*count);
     put_guid(pb, &ff_asf_my_guid);
-    put_le64(pb, ASF_INDEXED_INTERVAL);
-    put_le32(pb, max);
-    put_le32(pb, count);
+    avio_wl64(pb, ASF_INDEXED_INTERVAL);
+    avio_wl32(pb, max);
+    avio_wl32(pb, count);
     for(i=0; i<count; i++) {
-        put_le32(pb, index[i].packet_number);
-        put_le16(pb, index[i].packet_count);
+        avio_wl32(pb, index[i].packet_number);
+        avio_wl16(pb, index[i].packet_count);
     }
 
     return 0;
@@ -832,28 +860,28 @@ static int asf_write_trailer(AVFormatContext *s)
         flush_packet(s);
 
     /* write index */
-    data_size = url_ftell(s->pb);
+    data_size = avio_tell(s->pb);
     if ((!asf->is_streamed) && (asf->nb_index_count != 0)) {
         asf_write_index(s, asf->index_ptr, asf->maximum_packet, asf->nb_index_count);
     }
-    put_flush_packet(s->pb);
+    avio_flush(s->pb);
 
-    if (asf->is_streamed || url_is_streamed(s->pb)) {
+    if (asf->is_streamed || !s->pb->seekable) {
         put_chunk(s, 0x4524, 0, 0); /* end of stream */
     } else {
         /* rewrite an updated header */
-        file_size = url_ftell(s->pb);
-        url_fseek(s->pb, 0, SEEK_SET);
+        file_size = avio_tell(s->pb);
+        avio_seek(s->pb, 0, SEEK_SET);
         asf_write_header1(s, file_size, data_size - asf->data_offset);
     }
 
-    put_flush_packet(s->pb);
+    avio_flush(s->pb);
     av_free(asf->index_ptr);
     return 0;
 }
 
 #if CONFIG_ASF_MUXER
-AVOutputFormat asf_muxer = {
+AVOutputFormat ff_asf_muxer = {
     "asf",
     NULL_IF_CONFIG_SMALL("ASF format"),
     "video/x-ms-asf",
@@ -870,12 +898,11 @@ AVOutputFormat asf_muxer = {
     asf_write_trailer,
     .flags = AVFMT_GLOBALHEADER,
     .codec_tag= (const AVCodecTag* const []){codec_asf_bmp_tags, ff_codec_bmp_tags, ff_codec_wav_tags, 0},
-    .metadata_conv = ff_asf_metadata_conv,
 };
 #endif
 
 #if CONFIG_ASF_STREAM_MUXER
-AVOutputFormat asf_stream_muxer = {
+AVOutputFormat ff_asf_stream_muxer = {
     "asf_stream",
     NULL_IF_CONFIG_SMALL("ASF format"),
     "video/x-ms-asf",
@@ -892,6 +919,5 @@ AVOutputFormat asf_stream_muxer = {
     asf_write_trailer,
     .flags = AVFMT_GLOBALHEADER,
     .codec_tag= (const AVCodecTag* const []){codec_asf_bmp_tags, ff_codec_bmp_tags, ff_codec_wav_tags, 0},
-    .metadata_conv = ff_asf_metadata_conv,
 };
 #endif //CONFIG_ASF_STREAM_MUXER
diff --git a/libavformat/assdec.c b/libavformat/assdec.c
index 5f8e0b9..b270200 100644
--- a/libavformat/assdec.c
+++ b/libavformat/assdec.c
@@ -2,24 +2,25 @@
  * SSA/ASS demuxer
  * Copyright (c) 2008 Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "avformat.h"
+#include "internal.h"
 
 #define MAX_LINESIZE 2000
 
@@ -30,20 +31,6 @@ typedef struct ASSContext{
     unsigned int event_index;
 }ASSContext;
 
-static void get_line(ByteIOContext *s, char *buf, int maxlen)
-{
-    int i = 0;
-    char c;
-
-    do{
-        c = get_byte(s);
-        if (i < maxlen-1)
-            buf[i++] = c;
-    }while(c != '\n' && c);
-
-    buf[i] = 0;
-}
-
 static int probe(AVProbeData *p)
 {
     const char *header= "[Script Info]";
@@ -87,9 +74,9 @@ static int event_cmp(uint8_t **a, uint8_t **b)
 
 static int read_header(AVFormatContext *s, AVFormatParameters *ap)
 {
-    int i, header_remaining;
+    int i, len, header_remaining;
     ASSContext *ass = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVStream *st;
     int allocated[2]={0};
     uint8_t *p, **dst[2]={0};
@@ -105,10 +92,10 @@ static int read_header(AVFormatContext *s, AVFormatParameters *ap)
     header_remaining= INT_MAX;
     dst[0] = &st->codec->extradata;
     dst[1] = &ass->event_buffer;
-    while(!url_feof(pb)){
+    while(!pb->eof_reached){
         uint8_t line[MAX_LINESIZE];
 
-        get_line(pb, line, sizeof(line));
+        len = ff_get_line(pb, line, sizeof(line));
 
         if(!memcmp(line, "[Events]", 8))
             header_remaining= 2;
@@ -124,8 +111,8 @@ static int read_header(AVFormatContext *s, AVFormatParameters *ap)
         if(!p)
             goto fail;
         *(dst[i])= p;
-        memcpy(p + pos[i], line, strlen(line)+1);
-        pos[i] += strlen(line);
+        memcpy(p + pos[i], line, len+1);
+        pos[i] += len;
         if(i) ass->event_count++;
         else  header_remaining--;
     }
@@ -175,13 +162,53 @@ static int read_packet(AVFormatContext *s, AVPacket *pkt)
     return 0;
 }
 
-AVInputFormat ass_demuxer = {
-    "ass",
-    NULL_IF_CONFIG_SMALL("SSA/ASS format"),
-    sizeof(ASSContext),
-    probe,
-    read_header,
-    read_packet,
-    read_close,
-//    read_seek,
+static int read_seek2(AVFormatContext *s, int stream_index,
+                      int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
+{
+    ASSContext *ass = s->priv_data;
+
+    if (flags & AVSEEK_FLAG_BYTE) {
+        return AVERROR(ENOSYS);
+    } else if (flags & AVSEEK_FLAG_FRAME) {
+        if (ts < 0 || ts >= ass->event_count)
+            return AVERROR(ERANGE);
+        ass->event_index = ts;
+    } else {
+        int i, idx = -1;
+        int64_t min_ts_diff = INT64_MAX;
+        if (stream_index == -1) {
+            AVRational time_base = s->streams[0]->time_base;
+            ts = av_rescale_q(ts, AV_TIME_BASE_Q, time_base);
+            min_ts = av_rescale_rnd(min_ts, time_base.den,
+                                    time_base.num * (int64_t)AV_TIME_BASE,
+                                    AV_ROUND_UP);
+            max_ts = av_rescale_rnd(max_ts, time_base.den,
+                                    time_base.num * (int64_t)AV_TIME_BASE,
+                                    AV_ROUND_DOWN);
+        }
+        /* TODO: ass->event[] is sorted by pts so we could do a binary search */
+        for (i=0; i<ass->event_count; i++) {
+            int64_t pts = get_pts(ass->event[i]);
+            int64_t ts_diff = FFABS(pts - ts);
+            if (pts >= min_ts && pts <= max_ts && ts_diff < min_ts_diff) {
+                min_ts_diff = ts_diff;
+                idx = i;
+            }
+        }
+        if (idx < 0)
+            return AVERROR(ERANGE);
+        ass->event_index = idx;
+    }
+    return 0;
+}
+
+AVInputFormat ff_ass_demuxer = {
+    .name           = "ass",
+    .long_name      = NULL_IF_CONFIG_SMALL("Advanced SubStation Alpha subtitle format"),
+    .priv_data_size = sizeof(ASSContext),
+    .read_probe     = probe,
+    .read_header    = read_header,
+    .read_packet    = read_packet,
+    .read_close     = read_close,
+    .read_seek2     = read_seek2,
 };
diff --git a/libavformat/assenc.c b/libavformat/assenc.c
index d1b93e8..c53af16 100644
--- a/libavformat/assenc.c
+++ b/libavformat/assenc.c
@@ -2,20 +2,20 @@
  * SSA/ASS muxer
  * Copyright (c) 2008 Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -42,7 +42,7 @@ static int write_header(AVFormatContext *s)
         if(!end) end= avctx->extradata + avctx->extradata_size;
         else     end++;
 
-        put_buffer(s->pb, p, end-p);
+        avio_write(s->pb, p, end-p);
         ass->extra_index += end-p;
 
         if(last && !memcmp(last, "[Events]", 8))
@@ -50,16 +50,16 @@ static int write_header(AVFormatContext *s)
         last=p;
     }
 
-    put_flush_packet(s->pb);
+    avio_flush(s->pb);
 
     return 0;
 }
 
 static int write_packet(AVFormatContext *s, AVPacket *pkt)
 {
-    put_buffer(s->pb, pkt->data, pkt->size);
+    avio_write(s->pb, pkt->data, pkt->size);
 
-    put_flush_packet(s->pb);
+    avio_flush(s->pb);
 
     return 0;
 }
@@ -69,24 +69,23 @@ static int write_trailer(AVFormatContext *s)
     ASSContext *ass = s->priv_data;
     AVCodecContext *avctx= s->streams[0]->codec;
 
-    put_buffer(s->pb, avctx->extradata      + ass->extra_index,
+    avio_write(s->pb, avctx->extradata      + ass->extra_index,
                       avctx->extradata_size - ass->extra_index);
 
-    put_flush_packet(s->pb);
+    avio_flush(s->pb);
 
     return 0;
 }
 
-AVOutputFormat ass_muxer = {
-    "ass",
-    NULL_IF_CONFIG_SMALL("SSA/ASS format"),
-    NULL,
-    "ass,ssa",
-    sizeof(ASSContext),
-    CODEC_ID_NONE,
-    CODEC_ID_NONE,
-    write_header,
-    write_packet,
-    write_trailer,
-    .flags = AVFMT_GLOBALHEADER | AVFMT_NOTIMESTAMPS
+AVOutputFormat ff_ass_muxer = {
+    .name           = "ass",
+    .long_name      = NULL_IF_CONFIG_SMALL("Advanced SubStation Alpha subtitle format"),
+    .mime_type      = "text/x-ssa",
+    .extensions     = "ass,ssa",
+    .priv_data_size = sizeof(ASSContext),
+    .subtitle_codec = CODEC_ID_SSA,
+    .write_header   = write_header,
+    .write_packet   = write_packet,
+    .write_trailer  = write_trailer,
+    .flags          = AVFMT_GLOBALHEADER | AVFMT_NOTIMESTAMPS,
 };
diff --git a/libavformat/au.c b/libavformat/au.c
index f8f718d..6cffe1c 100644
--- a/libavformat/au.c
+++ b/libavformat/au.c
@@ -2,20 +2,20 @@
  * AU muxer and demuxer
  * Copyright (c) 2001 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -28,7 +28,8 @@
  */
 
 #include "avformat.h"
-#include "raw.h"
+#include "avio_internal.h"
+#include "pcm.h"
 #include "riff.h"
 
 /* if we don't know the size in advance */
@@ -49,22 +50,22 @@ static const AVCodecTag codec_au_tags[] = {
 
 #if CONFIG_AU_MUXER
 /* AUDIO_FILE header */
-static int put_au_header(ByteIOContext *pb, AVCodecContext *enc)
+static int put_au_header(AVIOContext *pb, AVCodecContext *enc)
 {
     if(!enc->codec_tag)
         return -1;
-    put_tag(pb, ".snd");       /* magic number */
-    put_be32(pb, 24);           /* header size */
-    put_be32(pb, AU_UNKNOWN_SIZE); /* data size */
-    put_be32(pb, (uint32_t)enc->codec_tag);     /* codec ID */
-    put_be32(pb, enc->sample_rate);
-    put_be32(pb, (uint32_t)enc->channels);
+    ffio_wfourcc(pb, ".snd");    /* magic number */
+    avio_wb32(pb, 24);           /* header size */
+    avio_wb32(pb, AU_UNKNOWN_SIZE); /* data size */
+    avio_wb32(pb, (uint32_t)enc->codec_tag);     /* codec ID */
+    avio_wb32(pb, enc->sample_rate);
+    avio_wb32(pb, (uint32_t)enc->channels);
     return 0;
 }
 
 static int au_write_header(AVFormatContext *s)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
 
     s->priv_data = NULL;
 
@@ -73,32 +74,32 @@ static int au_write_header(AVFormatContext *s)
         return -1;
     }
 
-    put_flush_packet(pb);
+    avio_flush(pb);
 
     return 0;
 }
 
 static int au_write_packet(AVFormatContext *s, AVPacket *pkt)
 {
-    ByteIOContext *pb = s->pb;
-    put_buffer(pb, pkt->data, pkt->size);
+    AVIOContext *pb = s->pb;
+    avio_write(pb, pkt->data, pkt->size);
     return 0;
 }
 
 static int au_write_trailer(AVFormatContext *s)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int64_t file_size;
 
-    if (!url_is_streamed(s->pb)) {
+    if (s->pb->seekable) {
 
         /* update file size */
-        file_size = url_ftell(pb);
-        url_fseek(pb, 8, SEEK_SET);
-        put_be32(pb, (uint32_t)(file_size - 24));
-        url_fseek(pb, file_size, SEEK_SET);
+        file_size = avio_tell(pb);
+        avio_seek(pb, 8, SEEK_SET);
+        avio_wb32(pb, (uint32_t)(file_size - 24));
+        avio_seek(pb, file_size, SEEK_SET);
 
-        put_flush_packet(pb);
+        avio_flush(pb);
     }
 
     return 0;
@@ -121,27 +122,32 @@ static int au_read_header(AVFormatContext *s,
 {
     int size;
     unsigned int tag;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     unsigned int id, channels, rate;
     enum CodecID codec;
     AVStream *st;
 
     /* check ".snd" header */
-    tag = get_le32(pb);
+    tag = avio_rl32(pb);
     if (tag != MKTAG('.', 's', 'n', 'd'))
         return -1;
-    size = get_be32(pb); /* header size */
-    get_be32(pb); /* data size */
+    size = avio_rb32(pb); /* header size */
+    avio_rb32(pb); /* data size */
 
-    id = get_be32(pb);
-    rate = get_be32(pb);
-    channels = get_be32(pb);
+    id = avio_rb32(pb);
+    rate = avio_rb32(pb);
+    channels = avio_rb32(pb);
 
     codec = ff_codec_get_id(codec_au_tags, id);
 
+    if (!av_get_bits_per_sample(codec)) {
+        av_log_ask_for_sample(s, "could not determine bits per sample\n");
+        return AVERROR_INVALIDDATA;
+    }
+
     if (size >= 24) {
         /* skip unused data */
-        url_fseek(pb, size - 24, SEEK_CUR);
+        avio_skip(pb, size - 24);
     }
 
     /* now we are ready: build format streams */
@@ -178,7 +184,7 @@ static int au_read_packet(AVFormatContext *s,
 }
 
 #if CONFIG_AU_DEMUXER
-AVInputFormat au_demuxer = {
+AVInputFormat ff_au_demuxer = {
     "au",
     NULL_IF_CONFIG_SMALL("SUN AU format"),
     0,
@@ -192,7 +198,7 @@ AVInputFormat au_demuxer = {
 #endif
 
 #if CONFIG_AU_MUXER
-AVOutputFormat au_muxer = {
+AVOutputFormat ff_au_muxer = {
     "au",
     NULL_IF_CONFIG_SMALL("SUN AU format"),
     "audio/basic",
diff --git a/libavformat/audiointerleave.c b/libavformat/audiointerleave.c
index 3c235c0..e4cb1b8 100644
--- a/libavformat/audiointerleave.c
+++ b/libavformat/audiointerleave.c
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavformat/audiointerleave.h b/libavformat/audiointerleave.h
index c948c36..af29629 100644
--- a/libavformat/audiointerleave.h
+++ b/libavformat/audiointerleave.h
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -39,7 +39,6 @@ typedef struct {
 int ff_audio_interleave_init(AVFormatContext *s, const int *samples_per_frame, AVRational time_base);
 void ff_audio_interleave_close(AVFormatContext *s);
 
-int ff_interleave_compare_dts(AVFormatContext *s, AVPacket *next, AVPacket *pkt);
 /**
  * Rechunk audio PCM packets per AudioInterleaveContext->samples_per_frame
  * and interleave them correctly.
diff --git a/libavformat/avc.c b/libavformat/avc.c
index 7c99196..70a05ec 100644
--- a/libavformat/avc.c
+++ b/libavformat/avc.c
@@ -2,20 +2,20 @@
  * AVC helper functions for muxers
  * Copyright (c) 2006 Baptiste Coudurier <baptiste.coudurier at smartjog.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -67,7 +67,7 @@ const uint8_t *ff_avc_find_startcode(const uint8_t *p, const uint8_t *end){
     return out;
 }
 
-int ff_avc_parse_nal_units(ByteIOContext *pb, const uint8_t *buf_in, int size)
+int ff_avc_parse_nal_units(AVIOContext *pb, const uint8_t *buf_in, int size)
 {
     const uint8_t *p = buf_in;
     const uint8_t *end = p + size;
@@ -78,8 +78,8 @@ int ff_avc_parse_nal_units(ByteIOContext *pb, const uint8_t *buf_in, int size)
     while (nal_start < end) {
         while(!*(nal_start++));
         nal_end = ff_avc_find_startcode(nal_start, end);
-        put_be32(pb, nal_end - nal_start);
-        put_buffer(pb, nal_start, nal_end - nal_start);
+        avio_wb32(pb, nal_end - nal_start);
+        avio_write(pb, nal_start, nal_end - nal_start);
         size += 4 + nal_end - nal_start;
         nal_start = nal_end;
     }
@@ -88,19 +88,19 @@ int ff_avc_parse_nal_units(ByteIOContext *pb, const uint8_t *buf_in, int size)
 
 int ff_avc_parse_nal_units_buf(const uint8_t *buf_in, uint8_t **buf, int *size)
 {
-    ByteIOContext *pb;
-    int ret = url_open_dyn_buf(&pb);
+    AVIOContext *pb;
+    int ret = avio_open_dyn_buf(&pb);
     if(ret < 0)
         return ret;
 
     ff_avc_parse_nal_units(pb, buf_in, *size);
 
     av_freep(buf);
-    *size = url_close_dyn_buf(pb, buf);
+    *size = avio_close_dyn_buf(pb, buf);
     return 0;
 }
 
-int ff_isom_write_avcc(ByteIOContext *pb, const uint8_t *data, int len)
+int ff_isom_write_avcc(AVIOContext *pb, const uint8_t *data, int len)
 {
     if (len > 6) {
         /* check for h264 start code */
@@ -134,21 +134,21 @@ int ff_isom_write_avcc(ByteIOContext *pb, const uint8_t *data, int len)
             assert(sps);
             assert(pps);
 
-            put_byte(pb, 1); /* version */
-            put_byte(pb, sps[1]); /* profile */
-            put_byte(pb, sps[2]); /* profile compat */
-            put_byte(pb, sps[3]); /* level */
-            put_byte(pb, 0xff); /* 6 bits reserved (111111) + 2 bits nal size length - 1 (11) */
-            put_byte(pb, 0xe1); /* 3 bits reserved (111) + 5 bits number of sps (00001) */
-
-            put_be16(pb, sps_size);
-            put_buffer(pb, sps, sps_size);
-            put_byte(pb, 1); /* number of pps */
-            put_be16(pb, pps_size);
-            put_buffer(pb, pps, pps_size);
+            avio_w8(pb, 1); /* version */
+            avio_w8(pb, sps[1]); /* profile */
+            avio_w8(pb, sps[2]); /* profile compat */
+            avio_w8(pb, sps[3]); /* level */
+            avio_w8(pb, 0xff); /* 6 bits reserved (111111) + 2 bits nal size length - 1 (11) */
+            avio_w8(pb, 0xe1); /* 3 bits reserved (111) + 5 bits number of sps (00001) */
+
+            avio_wb16(pb, sps_size);
+            avio_write(pb, sps, sps_size);
+            avio_w8(pb, 1); /* number of pps */
+            avio_wb16(pb, pps_size);
+            avio_write(pb, pps, pps_size);
             av_free(start);
         } else {
-            put_buffer(pb, data, len);
+            avio_write(pb, data, len);
         }
     }
     return 0;
diff --git a/libavformat/avc.h b/libavformat/avc.h
index 2deb77d..5612212 100644
--- a/libavformat/avc.h
+++ b/libavformat/avc.h
@@ -2,20 +2,20 @@
  * AVC helper functions for muxers
  * Copyright (c) 2008 Aurelien Jacobs <aurel at gnuage.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,9 +25,9 @@
 #include <stdint.h>
 #include "avio.h"
 
-int ff_avc_parse_nal_units(ByteIOContext *s, const uint8_t *buf, int size);
+int ff_avc_parse_nal_units(AVIOContext *s, const uint8_t *buf, int size);
 int ff_avc_parse_nal_units_buf(const uint8_t *buf_in, uint8_t **buf, int *size);
-int ff_isom_write_avcc(ByteIOContext *pb, const uint8_t *data, int len);
+int ff_isom_write_avcc(AVIOContext *pb, const uint8_t *data, int len);
 const uint8_t *ff_avc_find_startcode(const uint8_t *p, const uint8_t *end);
 
 #endif /* AVFORMAT_AVC_H */
diff --git a/libavformat/avformat.h b/libavformat/avformat.h
index 0e93376..55808f1 100644
--- a/libavformat/avformat.h
+++ b/libavformat/avformat.h
@@ -1,39 +1,26 @@
 /*
  * copyright (c) 2001 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #ifndef AVFORMAT_AVFORMAT_H
 #define AVFORMAT_AVFORMAT_H
 
-#define LIBAVFORMAT_VERSION_MAJOR 52
-#define LIBAVFORMAT_VERSION_MINOR 64
-#define LIBAVFORMAT_VERSION_MICRO  2
-
-#define LIBAVFORMAT_VERSION_INT AV_VERSION_INT(LIBAVFORMAT_VERSION_MAJOR, \
-                                               LIBAVFORMAT_VERSION_MINOR, \
-                                               LIBAVFORMAT_VERSION_MICRO)
-#define LIBAVFORMAT_VERSION     AV_VERSION(LIBAVFORMAT_VERSION_MAJOR,   \
-                                           LIBAVFORMAT_VERSION_MINOR,   \
-                                           LIBAVFORMAT_VERSION_MICRO)
-#define LIBAVFORMAT_BUILD       LIBAVFORMAT_VERSION_INT
-
-#define LIBAVFORMAT_IDENT       "Lavf" AV_STRINGIFY(LIBAVFORMAT_VERSION)
 
 /**
  * I return the LIBAVFORMAT_VERSION_INT constant.  You got
@@ -42,12 +29,12 @@
 unsigned avformat_version(void);
 
 /**
- * Returns the libavformat build-time configuration.
+ * Return the libavformat build-time configuration.
  */
 const char *avformat_configuration(void);
 
 /**
- * Returns the libavformat license.
+ * Return the libavformat license.
  */
 const char *avformat_license(void);
 
@@ -56,6 +43,7 @@ const char *avformat_license(void);
 #include "libavcodec/avcodec.h"
 
 #include "avio.h"
+#include "libavformat/version.h"
 
 struct AVFormatContext;
 
@@ -63,7 +51,7 @@ struct AVFormatContext;
 /*
  * Public Metadata API.
  * The metadata API allows libavformat to export metadata tags to a client
- * application using a sequence of key/value pairs. Like all strings in FFmpeg,
+ * application using a sequence of key/value pairs. Like all strings in Libav,
  * metadata must be stored as UTF-8 encoded Unicode. Note that metadata
  * exported by demuxers isn't checked to be valid UTF-8 in most cases.
  * Important concepts to keep in mind:
@@ -87,10 +75,9 @@ struct AVFormatContext;
  *       sorting will have '-sort' appended. E.g. artist="The Beatles",
  *       artist-sort="Beatles, The".
  *
- * 4. Tag names are normally exported exactly as stored in the container to
- *    allow lossless remuxing to the same format. For container-independent
- *    handling of metadata, av_metadata_conv() can convert it to ffmpeg generic
- *    format. Follows a list of generic tag names:
+ * 4. Demuxers attempt to export metadata in a generic format, however tags
+ *    with no generic equivalents are left as they are stored in the container.
+ *    Follows a list of generic tag names:
  *
  * album        -- name of the set this work belongs to
  * album_artist -- main creator of the set/album, if different from artist.
@@ -99,6 +86,7 @@ struct AVFormatContext;
  * comment      -- any additional description of the file.
  * composer     -- who composed the work, if different from artist.
  * copyright    -- name of copyright holder.
+ * creation_time-- date when the file was created, preferably in ISO 8601.
  * date         -- date when the work was created, preferably in ISO 8601.
  * disc         -- number of a subset, e.g. disc in a multi-disc collection.
  * encoder      -- name/settings of the software/hardware that produced the file.
@@ -106,11 +94,14 @@ struct AVFormatContext;
  * filename     -- original name of the file.
  * genre        -- <self-evident>.
  * language     -- main language in which the work is performed, preferably
- *                 in ISO 639-2 format.
+ *                 in ISO 639-2 format. Multiple languages can be specified by
+ *                 separating them with commas.
  * performer    -- artist who performed the work, if different from artist.
  *                 E.g for "Also sprach Zarathustra", artist would be "Richard
  *                 Strauss" and performer "London Philharmonic Orchestra".
  * publisher    -- name of the label/publisher.
+ * service_name     -- name of the service in broadcasting (channel name).
+ * service_provider -- name of the service provider in broadcasting.
  * title        -- name of the work.
  * track        -- number of this work in the set, can be in form current/total.
  */
@@ -127,10 +118,13 @@ typedef struct {
 }AVMetadataTag;
 
 typedef struct AVMetadata AVMetadata;
+#if FF_API_OLD_METADATA2
 typedef struct AVMetadataConv AVMetadataConv;
+#endif
 
 /**
- * Gets a metadata element with matching key.
+ * Get a metadata element with matching key.
+ *
  * @param prev Set to the previous matching element to find the next.
  *             If set to NULL the first matching element is returned.
  * @param flags Allows case as well as suffix-insensitive comparisons.
@@ -139,11 +133,14 @@ typedef struct AVMetadataConv AVMetadataConv;
 AVMetadataTag *
 av_metadata_get(AVMetadata *m, const char *key, const AVMetadataTag *prev, int flags);
 
-#if LIBAVFORMAT_VERSION_MAJOR == 52
+#if FF_API_OLD_METADATA
 /**
- * Sets the given tag in m, overwriting an existing tag.
- * @param key tag key to add to m (will be av_strduped)
- * @param value tag value to add to m (will be av_strduped)
+ * Set the given tag in *pm, overwriting an existing tag.
+ *
+ * @param pm pointer to a pointer to a metadata struct. If *pm is NULL
+ * a metadata struct is allocated and put in *pm.
+ * @param key tag key to add to *pm (will be av_strduped)
+ * @param value tag value to add to *pm (will be av_strduped)
  * @return >= 0 on success otherwise an error code <0
  * @deprecated Use av_metadata_set2() instead.
  */
@@ -151,25 +148,37 @@ attribute_deprecated int av_metadata_set(AVMetadata **pm, const char *key, const
 #endif
 
 /**
- * Sets the given tag in m, overwriting an existing tag.
- * @param key tag key to add to m (will be av_strduped depending on flags)
- * @param value tag value to add to m (will be av_strduped depending on flags)
+ * Set the given tag in *pm, overwriting an existing tag.
+ *
+ * @param pm pointer to a pointer to a metadata struct. If *pm is NULL
+ * a metadata struct is allocated and put in *pm.
+ * @param key tag key to add to *pm (will be av_strduped depending on flags)
+ * @param value tag value to add to *pm (will be av_strduped depending on flags).
+ *        Passing a NULL value will cause an existing tag to be deleted.
  * @return >= 0 on success otherwise an error code <0
  */
 int av_metadata_set2(AVMetadata **pm, const char *key, const char *value, int flags);
 
+#if FF_API_OLD_METADATA2
+/**
+ * This function is provided for compatibility reason and currently does nothing.
+ */
+attribute_deprecated void av_metadata_conv(struct AVFormatContext *ctx, const AVMetadataConv *d_conv,
+                                                                        const AVMetadataConv *s_conv);
+#endif
+
 /**
- * Converts all the metadata sets from ctx according to the source and
- * destination conversion tables. If one of the tables is NULL, then
- * tags are converted to/from ffmpeg generic tag names.
- * @param d_conv destination tags format conversion table
- * @param s_conv source tags format conversion table
+ * Copy metadata from one AVMetadata struct into another.
+ * @param dst pointer to a pointer to a AVMetadata struct. If *dst is NULL,
+ *            this function will allocate a struct for you and put it in *dst
+ * @param src pointer to source AVMetadata struct
+ * @param flags flags to use when setting metadata in *dst
+ * @note metadata is read using the AV_METADATA_IGNORE_SUFFIX flag
  */
-void av_metadata_conv(struct AVFormatContext *ctx,const AVMetadataConv *d_conv,
-                                                  const AVMetadataConv *s_conv);
+void av_metadata_copy(AVMetadata **dst, AVMetadata *src, int flags);
 
 /**
- * Frees all the memory allocated for an AVMetadata struct.
+ * Free all the memory allocated for an AVMetadata struct.
  */
 void av_metadata_free(AVMetadata **m);
 
@@ -178,16 +187,31 @@ void av_metadata_free(AVMetadata **m);
 
 
 /**
- * Allocates and reads the payload of a packet and initializes its
+ * Allocate and read the payload of a packet and initialize its
  * fields with default values.
  *
  * @param pkt packet
  * @param size desired payload size
  * @return >0 (read size) if OK, AVERROR_xxx otherwise
  */
-int av_get_packet(ByteIOContext *s, AVPacket *pkt, int size);
+int av_get_packet(AVIOContext *s, AVPacket *pkt, int size);
 
 
+/**
+ * Read data and append it to the current content of the AVPacket.
+ * If pkt->size is 0 this is identical to av_get_packet.
+ * Note that this uses av_grow_packet and thus involves a realloc
+ * which is inefficient. Thus this function should only be used
+ * when there is no reasonable way to know (an upper bound of)
+ * the final size.
+ *
+ * @param pkt packet
+ * @param size amount of data to read
+ * @return >0 (read size) if OK, AVERROR_xxx otherwise, previous data
+ *         will not be lost even if an error occurs.
+ */
+int av_append_packet(AVIOContext *s, AVPacket *pkt, int size);
+
 /*************************************************/
 /* fractional numbers for exact pts handling */
 
@@ -204,7 +228,9 @@ typedef struct AVFrac {
 
 struct AVCodecTag;
 
-/** This structure contains the data a format has to probe a file. */
+/**
+ * This structure contains the data a format has to probe a file.
+ */
 typedef struct AVProbeData {
     const char *filename;
     unsigned char *buf; /**< Buffer must have AVPROBE_PADDING_SIZE of extra allocated bytes filled with zero. */
@@ -230,13 +256,13 @@ typedef struct AVFormatParameters {
     unsigned int initial_pause:1;       /**< Do not begin to play the stream
                                             immediately (RTSP only). */
     unsigned int prealloced_context:1;
-#if LIBAVFORMAT_VERSION_INT < (53<<16)
-    enum CodecID video_codec_id;
-    enum CodecID audio_codec_id;
+#if FF_API_PARAMETERS_CODEC_ID
+    attribute_deprecated enum CodecID video_codec_id;
+    attribute_deprecated enum CodecID audio_codec_id;
 #endif
 } AVFormatParameters;
 
-//! Demuxer will use url_fopen, no opened file should be provided by the caller.
+//! Demuxer will use avio_open, no opened file should be provided by the caller.
 #define AVFMT_NOFILE        0x0001
 #define AVFMT_NEEDNUMBER    0x0002 /**< Needs '%d' in filename. */
 #define AVFMT_SHOW_IDS      0x0008 /**< Show format stream IDs numbers. */
@@ -245,9 +271,10 @@ typedef struct AVFormatParameters {
 #define AVFMT_GLOBALHEADER  0x0040 /**< Format wants global header. */
 #define AVFMT_NOTIMESTAMPS  0x0080 /**< Format does not need / have any timestamps. */
 #define AVFMT_GENERIC_INDEX 0x0100 /**< Use generic index building code. */
-#define AVFMT_TS_DISCONT    0x0200 /**< Format allows timestamp discontinuities. */
+#define AVFMT_TS_DISCONT    0x0200 /**< Format allows timestamp discontinuities. Note, muxers always require valid (monotone) timestamps */
 #define AVFMT_VARIABLE_FPS  0x0400 /**< Format allows variable fps. */
 #define AVFMT_NODIMENSIONS  0x0800 /**< Format does not need width/height */
+#define AVFMT_NOSTREAMS     0x1000 /**< Format does not require any streams */
 
 typedef struct AVOutputFormat {
     const char *name;
@@ -259,7 +286,9 @@ typedef struct AVOutputFormat {
     const char *long_name;
     const char *mime_type;
     const char *extensions; /**< comma-separated filename extensions */
-    /** size of private data so that it can be allocated in the wrapper */
+    /**
+     * size of private data so that it can be allocated in the wrapper
+     */
     int priv_data_size;
     /* output support */
     enum CodecID audio_codec; /**< default audio codec */
@@ -267,9 +296,15 @@ typedef struct AVOutputFormat {
     int (*write_header)(struct AVFormatContext *);
     int (*write_packet)(struct AVFormatContext *, AVPacket *pkt);
     int (*write_trailer)(struct AVFormatContext *);
-    /** can use flags: AVFMT_NOFILE, AVFMT_NEEDNUMBER, AVFMT_GLOBALHEADER */
+    /**
+     * can use flags: AVFMT_NOFILE, AVFMT_NEEDNUMBER, AVFMT_RAWPICTURE,
+     * AVFMT_GLOBALHEADER, AVFMT_NOTIMESTAMPS, AVFMT_VARIABLE_FPS,
+     * AVFMT_NODIMENSIONS, AVFMT_NOSTREAMS
+     */
     int flags;
-    /** Currently only used to set pixel format if not YUV420P. */
+    /**
+     * Currently only used to set pixel format if not YUV420P.
+     */
     int (*set_parameters)(struct AVFormatContext *, AVFormatParameters *);
     int (*interleave_packet)(struct AVFormatContext *, AVPacket *out,
                              AVPacket *in, int flush);
@@ -282,46 +317,69 @@ typedef struct AVOutputFormat {
 
     enum CodecID subtitle_codec; /**< default subtitle codec */
 
+#if FF_API_OLD_METADATA2
     const AVMetadataConv *metadata_conv;
+#endif
+
+    const AVClass *priv_class; ///< AVClass for the private context
 
     /* private fields */
     struct AVOutputFormat *next;
 } AVOutputFormat;
 
 typedef struct AVInputFormat {
+    /**
+     * A comma separated list of short names for the format. New names
+     * may be appended with a minor bump.
+     */
     const char *name;
+
     /**
      * Descriptive name for the format, meant to be more human-readable
      * than name. You should use the NULL_IF_CONFIG_SMALL() macro
      * to define it.
      */
     const char *long_name;
-    /** Size of private data so that it can be allocated in the wrapper. */
+
+    /**
+     * Size of private data so that it can be allocated in the wrapper.
+     */
     int priv_data_size;
+
     /**
      * Tell if a given file has a chance of being parsed as this format.
      * The buffer provided is guaranteed to be AVPROBE_PADDING_SIZE bytes
      * big so you do not have to check for that unless you need more.
      */
     int (*read_probe)(AVProbeData *);
-    /** Read the format header and initialize the AVFormatContext
-       structure. Return 0 if OK. 'ap' if non-NULL contains
-       additional parameters. Only used in raw format right
-       now. 'av_new_stream' should be called to create new streams.  */
+
+    /**
+     * Read the format header and initialize the AVFormatContext
+     * structure. Return 0 if OK. 'ap' if non-NULL contains
+     * additional parameters. Only used in raw format right
+     * now. 'av_new_stream' should be called to create new streams.
+     */
     int (*read_header)(struct AVFormatContext *,
                        AVFormatParameters *ap);
-    /** Read one packet and put it in 'pkt'. pts and flags are also
-       set. 'av_new_stream' can be called only if the flag
-       AVFMTCTX_NOHEADER is used.
-       @return 0 on success, < 0 on error.
-               When returning an error, pkt must not have been allocated
-               or must be freed before returning */
+
+    /**
+     * Read one packet and put it in 'pkt'. pts and flags are also
+     * set. 'av_new_stream' can be called only if the flag
+     * AVFMTCTX_NOHEADER is used and only in the calling thread (not in a
+     * background thread).
+     * @return 0 on success, < 0 on error.
+     *         When returning an error, pkt must not have been allocated
+     *         or must be freed before returning
+     */
     int (*read_packet)(struct AVFormatContext *, AVPacket *pkt);
-    /** Close the stream. The AVFormatContext and AVStreams are not
-       freed by this function */
+
+    /**
+     * Close the stream. The AVFormatContext and AVStreams are not
+     * freed by this function
+     */
     int (*read_close)(struct AVFormatContext *);
 
-#if LIBAVFORMAT_VERSION_MAJOR < 53
+#if FF_API_READ_SEEK
     /**
      * Seek to a given timestamp relative to the frames in
      * stream component stream_index.
@@ -330,8 +388,8 @@ typedef struct AVInputFormat {
      *              match is available.
      * @return >= 0 on success (but not necessarily the new offset)
      */
-    int (*read_seek)(struct AVFormatContext *,
-                     int stream_index, int64_t timestamp, int flags);
+    attribute_deprecated int (*read_seek)(struct AVFormatContext *,
+                                          int stream_index, int64_t timestamp, int flags);
 #endif
     /**
      * Gets the next timestamp in stream[stream_index].time_base units.
@@ -339,34 +397,49 @@ typedef struct AVInputFormat {
      */
     int64_t (*read_timestamp)(struct AVFormatContext *s, int stream_index,
                               int64_t *pos, int64_t pos_limit);
-    /** Can use flags: AVFMT_NOFILE, AVFMT_NEEDNUMBER. */
+
+    /**
+     * Can use flags: AVFMT_NOFILE, AVFMT_NEEDNUMBER.
+     */
     int flags;
-    /** If extensions are defined, then no probe is done. You should
-       usually not use extension format guessing because it is not
-       reliable enough */
+
+    /**
+     * If extensions are defined, then no probe is done. You should
+     * usually not use extension format guessing because it is not
+     * reliable enough
+     */
     const char *extensions;
-    /** General purpose read-only value that the format can use. */
+
+    /**
+     * General purpose read-only value that the format can use.
+     */
     int value;
 
-    /** Starts/resumes playing - only meaningful if using a network-based format
-       (RTSP). */
+    /**
+     * Start/resume playing - only meaningful if using a network-based format
+     * (RTSP).
+     */
     int (*read_play)(struct AVFormatContext *);
 
-    /** Pauses playing - only meaningful if using a network-based format
-       (RTSP). */
+    /**
+     * Pause playing - only meaningful if using a network-based format
+     * (RTSP).
+     */
     int (*read_pause)(struct AVFormatContext *);
 
     const struct AVCodecTag * const *codec_tag;
 
     /**
-     * Seeks to timestamp ts.
+     * Seek to timestamp ts.
      * Seeking will be done so that the point from which all active streams
      * can be presented successfully will be closest to ts and within min/max_ts.
      * Active streams are all streams that have AVStream.discard < AVDISCARD_ALL.
      */
     int (*read_seek2)(struct AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags);
 
+#if FF_API_OLD_METADATA2
     const AVMetadataConv *metadata_conv;
+#endif
 
     /* private fields */
     struct AVInputFormat *next;
@@ -377,6 +450,7 @@ enum AVStreamParseType {
     AVSTREAM_PARSE_FULL,       /**< full parsing and repack */
     AVSTREAM_PARSE_HEADERS,    /**< Only parse headers, do not repack. */
     AVSTREAM_PARSE_TIMESTAMPS, /**< full parsing and interpolation of timestamps for frames not starting on a packet boundary */
+    AVSTREAM_PARSE_FULL_ONCE,  /**< full parsing and repack of the first frame only, only implemented for H.264 currently */
 };
 
 typedef struct AVIndexEntry {
@@ -396,6 +470,16 @@ typedef struct AVIndexEntry {
 #define AV_DISPOSITION_KARAOKE   0x0020
 
 /**
+ * Track should be used during playback by default.
+ * Useful for subtitle track that should be displayed
+ * even when user did not explicitly ask for subtitles.
+ */
+#define AV_DISPOSITION_FORCED    0x0040
+#define AV_DISPOSITION_HEARING_IMPAIRED  0x0080  /**< stream for hearing impaired audiences */
+#define AV_DISPOSITION_VISUAL_IMPAIRED   0x0100  /**< stream for visual impaired audiences */
+#define AV_DISPOSITION_CLEAN_EFFECTS     0x0200  /**< stream without voice */
+
+/**
  * Stream structure.
  * New fields can be added to the end with minor version bumps.
  * Removal, reordering and changes to existing fields require a major
@@ -419,32 +503,40 @@ typedef struct AVStream {
 
     /* internal data used in av_find_stream_info() */
     int64_t first_dts;
-    /** encoding: pts generation when outputting stream */
+
+    /**
+     * encoding: pts generation when outputting stream
+     */
     struct AVFrac pts;
 
     /**
      * This is the fundamental unit of time (in seconds) in terms
      * of which frame timestamps are represented. For fixed-fps content,
      * time base should be 1/framerate and timestamp increments should be 1.
+     * decoding: set by libavformat
+     * encoding: set by libavformat in av_write_header
      */
     AVRational time_base;
     int pts_wrap_bits; /**< number of bits in pts (used for wrapping control) */
     /* ffmpeg.c private use */
     int stream_copy; /**< If set, just copy stream. */
     enum AVDiscard discard; ///< Selects which packets can be discarded at will and do not need to be demuxed.
+
     //FIXME move stuff to a flags field?
-    /** Quality, as it has been removed from AVCodecContext and put in AVVideoFrame.
-     * MN: dunno if that is the right place for it */
+    /**
+     * Quality, as it has been removed from AVCodecContext and put in AVVideoFrame.
+     * MN: dunno if that is the right place for it
+     */
     float quality;
+
     /**
      * Decoding: pts of the first frame of the stream, in stream time base.
      * Only set this if you are absolutely 100% sure that the value you set
      * it to really is the pts of the first frame.
      * This may be undefined (AV_NOPTS_VALUE).
-     * @note The ASF header does NOT contain a correct start_time the ASF
-     * demuxer must NOT set this.
      */
     int64_t start_time;
+
     /**
      * Decoding: duration of the stream, in stream time base.
      * If a source file does not specify a duration, but does specify
@@ -452,8 +544,8 @@ typedef struct AVStream {
      */
     int64_t duration;
 
-#if LIBAVFORMAT_VERSION_INT < (53<<16)
-    char language[4]; /** ISO 639-2/B 3-letter language code (empty string if undefined) */
+#if FF_API_OLD_METADATA
+    attribute_deprecated char language[4]; /**< ISO 639-2/B 3-letter language code (empty string if undefined) */
 #endif
 
     /* av_read_frame() support */
@@ -471,10 +563,12 @@ typedef struct AVStream {
 
     int64_t nb_frames;                 ///< number of frames in this stream if known or 0
 
-#if LIBAVFORMAT_VERSION_INT < (53<<16)
-    int64_t unused[4+1];
+#if FF_API_LAVF_UNUSED
+    attribute_deprecated int64_t unused[4+1];
+#endif
 
-    char *filename; /**< source filename of the stream */
+#if FF_API_OLD_METADATA
+    attribute_deprecated char *filename; /**< source filename of the stream */
 #endif
 
     int disposition; /**< AV_DISPOSITION_* bit field */
@@ -492,7 +586,8 @@ typedef struct AVStream {
 
     AVMetadata *metadata;
 
-    /* av_read_frame() support */
+    /* Intended mostly for av_read_frame() support. Not supposed to be used by */
+    /* external applications; try to use something else if at all possible.    */
     const uint8_t *cur_ptr;
     int cur_len;
     AVPacket cur_pkt;
@@ -529,6 +624,18 @@ typedef struct AVStream {
      * Number of frames that have been demuxed during av_find_stream_info()
      */
     int codec_info_nb_frames;
+
+    /**
+     * Stream informations used internally by av_find_stream_info()
+     */
+#define MAX_STD_TIMEBASES (60*12+5)
+    struct {
+        int64_t last_dts;
+        int64_t duration_gcd;
+        int duration_count;
+        double duration_error[MAX_STD_TIMEBASES];
+        int64_t codec_info_duration;
+    } *info;
 } AVStream;
 
 #define AV_PROGRAM_RUNNING 1
@@ -541,9 +648,9 @@ typedef struct AVStream {
  */
 typedef struct AVProgram {
     int            id;
-#if LIBAVFORMAT_VERSION_INT < (53<<16)
-    char           *provider_name; ///< network name for DVB streams
-    char           *name;          ///< service name for DVB streams
+#if FF_API_OLD_METADATA
+    attribute_deprecated char           *provider_name; ///< network name for DVB streams
+    attribute_deprecated char           *name;          ///< service name for DVB streams
 #endif
     int            flags;
     enum AVDiscard discard;        ///< selects which program to discard and which to feed to the caller
@@ -559,16 +666,14 @@ typedef struct AVChapter {
     int id;                 ///< unique ID to identify the chapter
     AVRational time_base;   ///< time base in which the start/end timestamps are specified
     int64_t start, end;     ///< chapter start/end time in time_base units
-#if LIBAVFORMAT_VERSION_INT < (53<<16)
-    char *title;            ///< chapter title
+#if FF_API_OLD_METADATA
+    attribute_deprecated char *title;            ///< chapter title
 #endif
     AVMetadata *metadata;
 } AVChapter;
 
-#if LIBAVFORMAT_VERSION_MAJOR < 53
+#if FF_API_MAX_STREAMS
 #define MAX_STREAMS 20
-#else
-#define MAX_STREAMS 100
 #endif
 
 /**
@@ -584,57 +689,76 @@ typedef struct AVFormatContext {
     struct AVInputFormat *iformat;
     struct AVOutputFormat *oformat;
     void *priv_data;
-    ByteIOContext *pb;
+    AVIOContext *pb;
     unsigned int nb_streams;
+#if FF_API_MAX_STREAMS
     AVStream *streams[MAX_STREAMS];
+#else
+    AVStream **streams;
+#endif
     char filename[1024]; /**< input or output filename */
     /* stream info */
     int64_t timestamp;
-#if LIBAVFORMAT_VERSION_INT < (53<<16)
-    char title[512];
-    char author[512];
-    char copyright[512];
-    char comment[512];
-    char album[512];
-    int year;  /**< ID3 year, 0 if none */
-    int track; /**< track number, 0 if none */
-    char genre[32]; /**< ID3 genre */
+#if FF_API_OLD_METADATA
+    attribute_deprecated char title[512];
+    attribute_deprecated char author[512];
+    attribute_deprecated char copyright[512];
+    attribute_deprecated char comment[512];
+    attribute_deprecated char album[512];
+    attribute_deprecated int year;  /**< ID3 year, 0 if none */
+    attribute_deprecated int track; /**< track number, 0 if none */
+    attribute_deprecated char genre[32]; /**< ID3 genre */
 #endif
 
     int ctx_flags; /**< Format-specific flags, see AVFMTCTX_xx */
     /* private data for pts handling (do not modify directly). */
-    /** This buffer is only needed when packets were already buffered but
-       not decoded, for example to get the codec parameters in MPEG
-       streams. */
+    /**
+     * This buffer is only needed when packets were already buffered but
+     * not decoded, for example to get the codec parameters in MPEG
+     * streams.
+     */
     struct AVPacketList *packet_buffer;
 
-    /** Decoding: position of the first frame of the component, in
-       AV_TIME_BASE fractional seconds. NEVER set this value directly:
-       It is deduced from the AVStream values.  */
+    /**
+     * Decoding: position of the first frame of the component, in
+     * AV_TIME_BASE fractional seconds. NEVER set this value directly:
+     * It is deduced from the AVStream values.
+     */
     int64_t start_time;
-    /** Decoding: duration of the stream, in AV_TIME_BASE fractional
-       seconds. Only set this value if you know none of the individual stream
-       durations and also dont set any of them. This is deduced from the
-       AVStream values if not set.  */
+
+    /**
+     * Decoding: duration of the stream, in AV_TIME_BASE fractional
+     * seconds. Only set this value if you know none of the individual stream
+     * durations and also dont set any of them. This is deduced from the
+     * AVStream values if not set.
+     */
     int64_t duration;
-    /** decoding: total file size, 0 if unknown */
+
+    /**
+     * decoding: total file size, 0 if unknown
+     */
     int64_t file_size;
-    /** Decoding: total stream bitrate in bit/s, 0 if not
-       available. Never set it directly if the file_size and the
-       duration are known as FFmpeg can compute it automatically. */
+
+    /**
+     * Decoding: total stream bitrate in bit/s, 0 if not
+     * available. Never set it directly if the file_size and the
+     * duration are known as Libav can compute it automatically.
+     */
     int bit_rate;
 
     /* av_read_frame() support */
     AVStream *cur_st;
-#if LIBAVFORMAT_VERSION_INT < (53<<16)
+#if FF_API_LAVF_UNUSED
     const uint8_t *cur_ptr_deprecated;
     int cur_len_deprecated;
     AVPacket cur_pkt_deprecated;
 #endif
 
     /* av_seek_frame() support */
-    int64_t data_offset; /** offset of the first packet */
-    int index_built;
+    int64_t data_offset; /**< offset of the first packet */
+#if FF_API_INDEX_BUILT
+    attribute_deprecated int index_built;
+#endif
 
     int mux_rate;
     unsigned int packet_size;
@@ -643,7 +767,9 @@ typedef struct AVFormatContext {
 
 #define AVFMT_NOOUTPUTLOOP -1
 #define AVFMT_INFINITEOUTPUTLOOP 0
-    /** number of times to loop output in formats that support it */
+    /**
+     * number of times to loop output in formats that support it
+     */
     int loop_output;
 
     int flags;
@@ -656,7 +782,10 @@ typedef struct AVFormatContext {
 #define AVFMT_FLAG_RTP_HINT     0x0040 ///< Add RTP hinting to the output file
 
     int loop_input;
-    /** decoding: size of data to probe; encoding: unused. */
+
+    /**
+     * decoding: size of data to probe; encoding: unused.
+     */
     unsigned int probesize;
 
     /**
@@ -676,11 +805,13 @@ typedef struct AVFormatContext {
      * Demuxing: Set by user.
      */
     enum CodecID video_codec_id;
+
     /**
      * Forced audio codec_id.
      * Demuxing: Set by user.
      */
     enum CodecID audio_codec_id;
+
     /**
      * Forced subtitle codec_id.
      * Demuxing: Set by user.
@@ -749,9 +880,9 @@ typedef struct AVPacketList {
     struct AVPacketList *next;
 } AVPacketList;
 
-#if LIBAVFORMAT_VERSION_INT < (53<<16)
-extern AVInputFormat *first_iformat;
-extern AVOutputFormat *first_oformat;
+#if FF_API_FIRST_FORMAT
+attribute_deprecated extern AVInputFormat *first_iformat;
+attribute_deprecated extern AVOutputFormat *first_oformat;
 #endif
 
 /**
@@ -768,7 +899,9 @@ AVInputFormat  *av_iformat_next(AVInputFormat  *f);
  */
 AVOutputFormat *av_oformat_next(AVOutputFormat *f);
 
-enum CodecID av_guess_image2_codec(const char *filename);
+#if FF_API_GUESS_IMG2_CODEC
+attribute_deprecated enum CodecID av_guess_image2_codec(const char *filename);
+#endif
 
 /* XXX: Use automatic init with either ELF sections or C file parser */
 /* modules. */
@@ -776,7 +909,7 @@ enum CodecID av_guess_image2_codec(const char *filename);
 /* utils.c */
 void av_register_input_format(AVInputFormat *format);
 void av_register_output_format(AVOutputFormat *format);
-#if LIBAVFORMAT_VERSION_MAJOR < 53
+#if FF_API_GUESS_FORMAT
 attribute_deprecated AVOutputFormat *guess_stream_format(const char *short_name,
                                     const char *filename,
                                     const char *mime_type);
@@ -790,8 +923,8 @@ attribute_deprecated AVOutputFormat *guess_format(const char *short_name,
 #endif
 
 /**
- * Returns the output format in the list of registered output formats
- * which best matches the provided parameters, or returns NULL if
+ * Return the output format in the list of registered output formats
+ * which best matches the provided parameters, or return NULL if
  * there is no match.
  *
  * @param short_name if non-NULL checks if short_name matches with the
@@ -806,25 +939,25 @@ AVOutputFormat *av_guess_format(const char *short_name,
                                 const char *mime_type);
 
 /**
- * Guesses the codec ID based upon muxer and filename.
+ * Guess the codec ID based upon muxer and filename.
  */
 enum CodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name,
                             const char *filename, const char *mime_type,
                             enum AVMediaType type);
 
 /**
- * Sends a nice hexadecimal dump of a buffer to the specified file stream.
+ * Send a nice hexadecimal dump of a buffer to the specified file stream.
  *
  * @param f The file stream pointer where the dump should be sent to.
  * @param buf buffer
  * @param size buffer size
  *
- * @see av_hex_dump_log, av_pkt_dump, av_pkt_dump_log
+ * @see av_hex_dump_log, av_pkt_dump2, av_pkt_dump_log2
  */
 void av_hex_dump(FILE *f, uint8_t *buf, int size);
 
 /**
- * Sends a nice hexadecimal dump of a buffer to the log.
+ * Send a nice hexadecimal dump of a buffer to the log.
  *
  * @param avcl A pointer to an arbitrary struct of which the first field is a
  * pointer to an AVClass struct.
@@ -833,21 +966,23 @@ void av_hex_dump(FILE *f, uint8_t *buf, int size);
  * @param buf buffer
  * @param size buffer size
  *
- * @see av_hex_dump, av_pkt_dump, av_pkt_dump_log
+ * @see av_hex_dump, av_pkt_dump2, av_pkt_dump_log2
  */
 void av_hex_dump_log(void *avcl, int level, uint8_t *buf, int size);
 
 /**
- * Sends a nice dump of a packet to the specified file stream.
+ * Send a nice dump of a packet to the specified file stream.
  *
  * @param f The file stream pointer where the dump should be sent to.
  * @param pkt packet to dump
  * @param dump_payload True if the payload must be displayed, too.
+ * @param st AVStream that the packet belongs to
  */
-void av_pkt_dump(FILE *f, AVPacket *pkt, int dump_payload);
+void av_pkt_dump2(FILE *f, AVPacket *pkt, int dump_payload, AVStream *st);
+
 
 /**
- * Sends a nice dump of a packet to the log.
+ * Send a nice dump of a packet to the log.
  *
  * @param avcl A pointer to an arbitrary struct of which the first field is a
  * pointer to an AVClass struct.
@@ -855,11 +990,19 @@ void av_pkt_dump(FILE *f, AVPacket *pkt, int dump_payload);
  * higher importance.
  * @param pkt packet to dump
  * @param dump_payload True if the payload must be displayed, too.
+ * @param st AVStream that the packet belongs to
  */
-void av_pkt_dump_log(void *avcl, int level, AVPacket *pkt, int dump_payload);
+void av_pkt_dump_log2(void *avcl, int level, AVPacket *pkt, int dump_payload,
+                      AVStream *st);
+
+#if FF_API_PKT_DUMP
+attribute_deprecated void av_pkt_dump(FILE *f, AVPacket *pkt, int dump_payload);
+attribute_deprecated void av_pkt_dump_log(void *avcl, int level, AVPacket *pkt,
+                                          int dump_payload);
+#endif
 
 /**
- * Initializes libavformat and registers all the muxers, demuxers and
+ * Initialize libavformat and register all the muxers, demuxers and
  * protocols. If you do not call this function, then you can select
  * exactly which formats you want to support.
  *
@@ -869,19 +1012,33 @@ void av_pkt_dump_log(void *avcl, int level, AVPacket *pkt, int dump_payload);
  */
 void av_register_all(void);
 
-/** codec tag <-> codec id */
+/**
+ * Get the CodecID for the given codec tag tag.
+ * If no codec id is found returns CODEC_ID_NONE.
+ *
+ * @param tags list of supported codec_id-codec_tag pairs, as stored
+ * in AVInputFormat.codec_tag and AVOutputFormat.codec_tag
+ */
 enum CodecID av_codec_get_id(const struct AVCodecTag * const *tags, unsigned int tag);
+
+/**
+ * Get the codec tag for the given codec id id.
+ * If no codec tag is found returns 0.
+ *
+ * @param tags list of supported codec_id-codec_tag pairs, as stored
+ * in AVInputFormat.codec_tag and AVOutputFormat.codec_tag
+ */
 unsigned int av_codec_get_tag(const struct AVCodecTag * const *tags, enum CodecID id);
 
 /* media file input */
 
 /**
- * Finds AVInputFormat based on the short name of the input format.
+ * Find AVInputFormat based on the short name of the input format.
  */
 AVInputFormat *av_find_input_format(const char *short_name);
 
 /**
- * Guesses the file format.
+ * Guess the file format.
  *
  * @param is_opened Whether the file is already opened; determines whether
  *                  demuxers with or without AVFMT_NOFILE are probed.
@@ -889,7 +1046,7 @@ AVInputFormat *av_find_input_format(const char *short_name);
 AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened);
 
 /**
- * Guesses the file format.
+ * Guess the file format.
  *
  * @param is_opened Whether the file is already opened; determines whether
  *                  demuxers with or without AVFMT_NOFILE are probed.
@@ -902,15 +1059,34 @@ AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened);
 AVInputFormat *av_probe_input_format2(AVProbeData *pd, int is_opened, int *score_max);
 
 /**
- * Allocates all the structures needed to read an input stream.
+ * Probe a bytestream to determine the input format. Each time a probe returns
+ * with a score that is too low, the probe buffer size is increased and another
+ * attempt is made. When the maximum probe size is reached, the input format
+ * with the highest score is returned.
+ *
+ * @param pb the bytestream to probe
+ * @param fmt the input format is put here
+ * @param filename the filename of the stream
+ * @param logctx the log context
+ * @param offset the offset within the bytestream to probe from
+ * @param max_probe_size the maximum probe buffer size (zero for default)
+ * @return 0 in case of success, a negative value corresponding to an
+ * AVERROR code otherwise
+ */
+int av_probe_input_buffer(AVIOContext *pb, AVInputFormat **fmt,
+                          const char *filename, void *logctx,
+                          unsigned int offset, unsigned int max_probe_size);
+
+/**
+ * Allocate all the structures needed to read an input stream.
  *        This does not open the needed codecs for decoding the stream[s].
  */
 int av_open_input_stream(AVFormatContext **ic_ptr,
-                         ByteIOContext *pb, const char *filename,
+                         AVIOContext *pb, const char *filename,
                          AVInputFormat *fmt, AVFormatParameters *ap);
 
 /**
- * Opens a media file as input. The codecs are not opened. Only the file
+ * Open a media file as input. The codecs are not opened. Only the file
  * header (if present) is read.
  *
  * @param ic_ptr The opened media file handle is put here.
@@ -926,7 +1102,7 @@ int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
                        int buf_size,
                        AVFormatParameters *ap);
 
-#if LIBAVFORMAT_VERSION_MAJOR < 53
+#if FF_API_ALLOC_FORMAT_CONTEXT
 /**
  * @deprecated Use avformat_alloc_context() instead.
  */
@@ -934,14 +1110,14 @@ attribute_deprecated AVFormatContext *av_alloc_format_context(void);
 #endif
 
 /**
- * Allocates an AVFormatContext.
- * Can be freed with av_free() but do not forget to free everything you
- * explicitly allocated as well!
+ * Allocate an AVFormatContext.
+ * avformat_free_context() can be used to free the context and everything
+ * allocated by the framework within it.
  */
 AVFormatContext *avformat_alloc_context(void);
 
 /**
- * Reads packets of a media file to get stream information. This
+ * Read packets of a media file to get stream information. This
  * is useful for file formats with no headers such as MPEG. This
  * function also computes the real framerate in case of MPEG-2 repeat
  * frame mode.
@@ -956,7 +1132,38 @@ AVFormatContext *avformat_alloc_context(void);
 int av_find_stream_info(AVFormatContext *ic);
 
 /**
- * Reads a transport packet from a media file.
+ * Find the "best" stream in the file.
+ * The best stream is determined according to various heuristics as the most
+ * likely to be what the user expects.
+ * If the decoder parameter is non-NULL, av_find_best_stream will find the
+ * default decoder for the stream's codec; streams for which no decoder can
+ * be found are ignored.
+ *
+ * @param ic                media file handle
+ * @param type              stream type: video, audio, subtitles, etc.
+ * @param wanted_stream_nb  user-requested stream number,
+ *                          or -1 for automatic selection
+ * @param related_stream    try to find a stream related (eg. in the same
+ *                          program) to this one, or -1 if none
+ * @param decoder_ret       if non-NULL, returns the decoder for the
+ *                          selected stream
+ * @param flags             flags; none are currently defined
+ * @return  the non-negative stream number in case of success,
+ *          AVERROR_STREAM_NOT_FOUND if no stream with the requested type
+ *          could be found,
+ *          AVERROR_DECODER_NOT_FOUND if streams were found but no decoder
+ * @note  If av_find_best_stream returns successfully and decoder_ret is not
+ *        NULL, then *decoder_ret is guaranteed to be set to a valid AVCodec.
+ */
+int av_find_best_stream(AVFormatContext *ic,
+                        enum AVMediaType type,
+                        int wanted_stream_nb,
+                        int related_stream,
+                        AVCodec **decoder_ret,
+                        int flags);
+
+/**
+ * Read a transport packet from a media file.
  *
  * This function is obsolete and should never be used.
  * Use av_read_frame() instead.
@@ -968,7 +1175,12 @@ int av_find_stream_info(AVFormatContext *ic);
 int av_read_packet(AVFormatContext *s, AVPacket *pkt);
 
 /**
- * Returns the next frame of a stream.
+ * Return the next frame of a stream.
+ * This function returns what is stored in the file, and does not validate
+ * that what is there are valid frames for the decoder. It will split what is
+ * stored in the file into frames and return one for each call. It will not
+ * omit invalid data between valid frames so as to give the decoder the maximum
+ * information possible for decoding.
  *
  * The returned packet is valid
  * until the next av_read_frame() or until av_close_input_file() and
@@ -989,7 +1201,7 @@ int av_read_packet(AVFormatContext *s, AVPacket *pkt);
 int av_read_frame(AVFormatContext *s, AVPacket *pkt);
 
 /**
- * Seeks to the keyframe at timestamp.
+ * Seek to the keyframe at timestamp.
  * 'timestamp' in 'stream_index'.
  * @param stream_index If stream_index is (-1), a default
  * stream is selected, and timestamp is automatically converted
@@ -1003,7 +1215,7 @@ int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp,
                   int flags);
 
 /**
- * Seeks to timestamp ts.
+ * Seek to timestamp ts.
  * Seeking will be done so that the point from which all active streams
  * can be presented successfully will be closest to ts and within min/max_ts.
  * Active streams are all streams that have AVStream.discard < AVDISCARD_ALL.
@@ -1024,40 +1236,46 @@ int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp,
  * @param flags flags
  * @return >=0 on success, error code otherwise
  *
- * @NOTE This is part of the new seek API which is still under construction.
+ * @note This is part of the new seek API which is still under construction.
  *       Thus do not use this yet. It may change at any time, do not expect
  *       ABI compatibility yet!
  */
 int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags);
 
 /**
- * Starts playing a network-based stream (e.g. RTSP stream) at the
+ * Start playing a network-based stream (e.g. RTSP stream) at the
  * current position.
  */
 int av_read_play(AVFormatContext *s);
 
 /**
- * Pauses a network-based stream (e.g. RTSP stream).
+ * Pause a network-based stream (e.g. RTSP stream).
  *
  * Use av_read_play() to resume it.
  */
 int av_read_pause(AVFormatContext *s);
 
 /**
- * Frees a AVFormatContext allocated by av_open_input_stream.
+ * Free a AVFormatContext allocated by av_open_input_stream.
  * @param s context to free
  */
 void av_close_input_stream(AVFormatContext *s);
 
 /**
- * Closes a media file (but not its codecs).
+ * Close a media file (but not its codecs).
  *
  * @param s media file handle
  */
 void av_close_input_file(AVFormatContext *s);
 
 /**
- * Adds a new stream to a media file.
+ * Free an AVFormatContext and all its streams.
+ * @param s context to free
+ */
+void avformat_free_context(AVFormatContext *s);
+
+/**
+ * Add a new stream to a media file.
  *
  * Can only be called in the read_header() function. If the flag
  * AVFMTCTX_NOHEADER is in the format context, then new streams
@@ -1070,23 +1288,8 @@ AVStream *av_new_stream(AVFormatContext *s, int id);
 AVProgram *av_new_program(AVFormatContext *s, int id);
 
 /**
- * Adds a new chapter.
- * This function is NOT part of the public API
- * and should ONLY be used by demuxers.
- *
- * @param s media file handle
- * @param id unique ID for this chapter
- * @param start chapter start time in time_base units
- * @param end chapter end time in time_base units
- * @param title chapter title
- *
- * @return AVChapter or NULL on error
- */
-AVChapter *ff_new_chapter(AVFormatContext *s, int id, AVRational time_base,
-                          int64_t start, int64_t end, const char *title);
-
-/**
- * Sets the pts for a given stream.
+ * Set the pts for a given stream. If the new values would be invalid
+ * (<= 0), it leaves the AVStream unchanged.
  *
  * @param s stream
  * @param pts_wrap_bits number of bits effectively used by the pts
@@ -1105,7 +1308,7 @@ void av_set_pts_info(AVStream *s, int pts_wrap_bits,
 int av_find_default_stream_index(AVFormatContext *s);
 
 /**
- * Gets the index for a specific timestamp.
+ * Get the index for a specific timestamp.
  * @param flags if AVSEEK_FLAG_BACKWARD then the returned index will correspond
  *                 to the timestamp which is <= the requested one, if backward
  *                 is 0, then it will be >=
@@ -1115,16 +1318,7 @@ int av_find_default_stream_index(AVFormatContext *s);
 int av_index_search_timestamp(AVStream *st, int64_t timestamp, int flags);
 
 /**
- * Ensures the index uses less memory than the maximum specified in
- * AVFormatContext.max_index_size by discarding entries if it grows
- * too large.
- * This function is not part of the public API and should only be called
- * by demuxers.
- */
-void ff_reduce_index(AVFormatContext *s, int stream_index);
-
-/**
- * Adds an index entry into a sorted list. Updates the entry if the list
+ * Add an index entry into a sorted list. Update the entry if the list
  * already contains it.
  *
  * @param timestamp timestamp in the time base of the given stream
@@ -1133,8 +1327,8 @@ int av_add_index_entry(AVStream *st, int64_t pos, int64_t timestamp,
                        int size, int distance, int flags);
 
 /**
- * Does a binary search using av_index_search_timestamp() and
- * AVCodec.read_timestamp().
+ * Perform a binary search using av_index_search_timestamp() and
+ * AVInputFormat.read_timestamp().
  * This is not supposed to be called directly by a user application,
  * but by demuxers.
  * @param target_ts target timestamp in the time base of the given stream
@@ -1144,7 +1338,7 @@ int av_seek_frame_binary(AVFormatContext *s, int stream_index,
                          int64_t target_ts, int flags);
 
 /**
- * Updates cur_dts of all streams based on the given timestamp and AVStream.
+ * Update cur_dts of all streams based on the given timestamp and AVStream.
  *
  * Stream ref_st unchanged, others set cur_dts in their native time base.
  * Only needed for timestamp wrapping or if (dts not set and pts!=dts).
@@ -1154,7 +1348,7 @@ int av_seek_frame_binary(AVFormatContext *s, int stream_index,
 void av_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp);
 
 /**
- * Does a binary search using read_timestamp().
+ * Perform a binary search using read_timestamp().
  * This is not supposed to be called directly by a user application,
  * but by demuxers.
  * @param target_ts target timestamp in the time base of the given stream
@@ -1167,12 +1361,42 @@ int64_t av_gen_search(AVFormatContext *s, int stream_index,
                       int flags, int64_t *ts_ret,
                       int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t ));
 
-/** media file output */
+/**
+ * media file output
+ */
 int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap);
 
 /**
- * Allocates the stream private data and writes the stream header to an
+ * Split a URL string into components.
+ *
+ * The pointers to buffers for storing individual components may be null,
+ * in order to ignore that component. Buffers for components not found are
+ * set to empty strings. If the port is not found, it is set to a negative
+ * value.
+ *
+ * @param proto the buffer for the protocol
+ * @param proto_size the size of the proto buffer
+ * @param authorization the buffer for the authorization
+ * @param authorization_size the size of the authorization buffer
+ * @param hostname the buffer for the host name
+ * @param hostname_size the size of the hostname buffer
+ * @param port_ptr a pointer to store the port number in
+ * @param path the buffer for the path
+ * @param path_size the size of the path buffer
+ * @param url the URL to split
+ */
+void av_url_split(char *proto,         int proto_size,
+                  char *authorization, int authorization_size,
+                  char *hostname,      int hostname_size,
+                  int *port_ptr,
+                  char *path,          int path_size,
+                  const char *url);
+
+/**
+ * Allocate the stream private data and write the stream header to an
  * output media file.
+ * @note: this sets stream time-bases, if possible to stream->codec->time_base
+ * but for some formats it might also be some other time base
  *
  * @param s media file handle
  * @return 0 if OK, AVERROR_xxx on error
@@ -1180,7 +1404,7 @@ int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap);
 int av_write_header(AVFormatContext *s);
 
 /**
- * Writes a packet to an output media file.
+ * Write a packet to an output media file.
  *
  * The packet shall contain one audio or video frame.
  * The packet must be correctly interleaved according to the container
@@ -1194,7 +1418,7 @@ int av_write_header(AVFormatContext *s);
 int av_write_frame(AVFormatContext *s, AVPacket *pkt);
 
 /**
- * Writes a packet to an output media file ensuring correct interleaving.
+ * Write a packet to an output media file ensuring correct interleaving.
  *
  * The packet must contain one audio or video frame.
  * If the packets are already correctly interleaved, the application should
@@ -1211,7 +1435,7 @@ int av_write_frame(AVFormatContext *s, AVPacket *pkt);
 int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt);
 
 /**
- * Interleaves a packet per dts in an output media file.
+ * Interleave a packet per dts in an output media file.
  *
  * Packets with pkt->destruct == av_destruct_packet will be freed inside this
  * function, so they cannot be used after it. Note that calling av_free_packet()
@@ -1219,7 +1443,7 @@ int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt);
  *
  * @param s media file handle
  * @param out the interleaved packet will be output here
- * @param in the input packet
+ * @param pkt the input packet
  * @param flush 1 if no further packets are available as input and all
  *              remaining packets should be output
  * @return 1 if a packet was output, 0 if no packet could be output,
@@ -1229,7 +1453,7 @@ int av_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out,
                                  AVPacket *pkt, int flush);
 
 /**
- * Writes the stream trailer to an output media file and frees the
+ * Write the stream trailer to an output media file and free the
  * file private data.
  *
  * May only be called after a successful call to av_write_header.
@@ -1239,74 +1463,60 @@ int av_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out,
  */
 int av_write_trailer(AVFormatContext *s);
 
-void dump_format(AVFormatContext *ic,
-                 int index,
-                 const char *url,
-                 int is_output);
+#if FF_API_DUMP_FORMAT
+attribute_deprecated void dump_format(AVFormatContext *ic,
+                                      int index,
+                                      const char *url,
+                                      int is_output);
+#endif
+
+void av_dump_format(AVFormatContext *ic,
+                    int index,
+                    const char *url,
+                    int is_output);
 
-#if LIBAVFORMAT_VERSION_MAJOR < 53
+#if FF_API_PARSE_FRAME_PARAM
 /**
- * Parses width and height out of string str.
+ * Parse width and height out of string str.
  * @deprecated Use av_parse_video_frame_size instead.
  */
 attribute_deprecated int parse_image_size(int *width_ptr, int *height_ptr,
                                           const char *str);
 
 /**
- * Converts framerate from a string to a fraction.
+ * Convert framerate from a string to a fraction.
  * @deprecated Use av_parse_video_frame_rate instead.
  */
 attribute_deprecated int parse_frame_rate(int *frame_rate, int *frame_rate_base,
                                           const char *arg);
 #endif
 
+#if FF_API_PARSE_DATE
 /**
- * Parses datestr and returns a corresponding number of microseconds.
+ * Parse datestr and return a corresponding number of microseconds.
+ *
  * @param datestr String representing a date or a duration.
- * - If a date the syntax is:
- * @code
- *  [{YYYY-MM-DD|YYYYMMDD}]{T| }{HH[:MM[:SS[.m...]]][Z]|HH[MM[SS[.m...]]][Z]}
- * @endcode
- * Time is local time unless Z is appended, in which case it is
- * interpreted as UTC.
- * If the year-month-day part is not specified it takes the current
- * year-month-day.
- * Returns the number of microseconds since 1st of January, 1970 up to
- * the time of the parsed date or INT64_MIN if datestr cannot be
- * successfully parsed.
- * - If a duration the syntax is:
- * @code
- *  [-]HH[:MM[:SS[.m...]]]
- *  [-]S+[.m...]
- * @endcode
- * Returns the number of microseconds contained in a time interval
- * with the specified duration or INT64_MIN if datestr cannot be
- * successfully parsed.
- * @param duration Flag which tells how to interpret datestr, if
- * not zero datestr is interpreted as a duration, otherwise as a
- * date.
+ * See av_parse_time() for the syntax of the provided string.
+ * @deprecated in favor of av_parse_time()
  */
+attribute_deprecated
 int64_t parse_date(const char *datestr, int duration);
+#endif
 
-/** Gets the current time in microseconds. */
+/**
+ * Get the current time in microseconds.
+ */
 int64_t av_gettime(void);
 
-/* ffm-specific for ffserver */
-#define FFM_PACKET_SIZE 4096
-int64_t ffm_read_write_index(int fd);
-int ffm_write_write_index(int fd, int64_t pos);
-void ffm_set_write_index(AVFormatContext *s, int64_t pos, int64_t file_size);
-
+#if FF_API_FIND_INFO_TAG
 /**
- * Attempts to find a specific tag in a URL.
- *
- * syntax: '?tag1=val1&tag2=val2...'. Little URL decoding is done.
- * Return 1 if found.
+ * @deprecated use av_find_info_tag in libavutil instead.
  */
-int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info);
+attribute_deprecated int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info);
+#endif
 
 /**
- * Returns in 'buf' the path with '%d' replaced by a number.
+ * Return in 'buf' the path with '%d' replaced by a number.
  *
  * Also handles the '%0nd' format where 'n' is the total number
  * of digits and '%%'.
@@ -1321,7 +1531,7 @@ int av_get_frame_filename(char *buf, int buf_size,
                           const char *path, int number);
 
 /**
- * Checks whether filename actually is a numbered sequence generator.
+ * Check whether filename actually is a numbered sequence generator.
  *
  * @param filename possible numbered sequence string
  * @return 1 if a valid numbered sequence string, 0 otherwise
@@ -1329,7 +1539,7 @@ int av_get_frame_filename(char *buf, int buf_size,
 int av_filename_number_test(const char *filename);
 
 /**
- * Generates an SDP for an RTP session.
+ * Generate an SDP for an RTP session.
  *
  * @param ac array of AVFormatContexts describing the RTP streams. If the
  *           array is composed by only one context, such context can contain
@@ -1337,15 +1547,19 @@ int av_filename_number_test(const char *filename);
  *           all the contexts in the array (an AVCodecContext per RTP stream)
  *           must contain only one AVStream.
  * @param n_files number of AVCodecContexts contained in ac
- * @param buff buffer where the SDP will be stored (must be allocated by
- *             the caller)
+ * @param buf buffer where the SDP will be stored (must be allocated by
+ *            the caller)
  * @param size the size of the buffer
  * @return 0 if OK, AVERROR_xxx on error
  */
-int avf_sdp_create(AVFormatContext *ac[], int n_files, char *buff, int size);
+int av_sdp_create(AVFormatContext *ac[], int n_files, char *buf, int size);
+
+#if FF_API_SDP_CREATE
+attribute_deprecated int avf_sdp_create(AVFormatContext *ac[], int n_files, char *buff, int size);
+#endif
 
 /**
- * Returns a positive value if the given filename has one of the given
+ * Return a positive value if the given filename has one of the given
  * extensions, 0 otherwise.
  *
  * @param extensions a comma-separated list of filename extensions
diff --git a/libavformat/avi.c b/libavformat/avi.c
index 705ad03..9f36b27 100644
--- a/libavformat/avi.c
+++ b/libavformat/avi.c
@@ -2,20 +2,20 @@
  * AVI common data
  * Copyright (c) 2010 Anton Khirnov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavformat/avi.h b/libavformat/avi.h
index f345c14..05e0297 100644
--- a/libavformat/avi.h
+++ b/libavformat/avi.h
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2001 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -32,6 +32,7 @@
 
 #define AVI_MAX_RIFF_SIZE       0x40000000LL
 #define AVI_MASTER_INDEX_SIZE   256
+#define AVI_MAX_STREAM_COUNT    100
 
 /* index flags */
 #define AVIIF_INDEX             0x10
diff --git a/libavformat/avidec.c b/libavformat/avidec.c
index 485c4eb..43d72ce 100644
--- a/libavformat/avidec.c
+++ b/libavformat/avidec.c
@@ -2,26 +2,27 @@
  * AVI demuxer
  * Copyright (c) 2001 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 //#define DEBUG
 //#define DEBUG_SEEK
 
+#include <strings.h>
 #include "libavutil/intreadwrite.h"
 #include "libavutil/bswap.h"
 #include "avformat.h"
@@ -48,6 +49,11 @@ typedef struct AVIStream {
     int prefix_count;
     uint32_t pal[256];
     int has_pal;
+    int dshow_block_align;            ///< block align variable used to emulate bugs in the MS dshow demuxer
+
+    AVFormatContext *sub_ctx;
+    AVPacket sub_pkt;
+    uint8_t *sub_buffer;
 } AVIStream;
 
 typedef struct {
@@ -61,6 +67,8 @@ typedef struct {
     int non_interleaved;
     int stream_index;
     DVDemuxContext* dv_demux;
+    int odml_depth;
+#define MAX_ODML_DEPTH 1000
 } AVIContext;
 
 static const char avi_headers[][8] = {
@@ -75,29 +83,34 @@ static const char avi_headers[][8] = {
 static int avi_load_index(AVFormatContext *s);
 static int guess_ni_flag(AVFormatContext *s);
 
-#ifdef DEBUG
-static void print_tag(const char *str, unsigned int tag, int size)
-{
-    dprintf(NULL, "%s: tag=%c%c%c%c size=0x%x\n",
-           str, tag & 0xff,
-           (tag >> 8) & 0xff,
-           (tag >> 16) & 0xff,
-           (tag >> 24) & 0xff,
-           size);
+#define print_tag(str, tag, size)                       \
+    av_dlog(NULL, "%s: tag=%c%c%c%c size=0x%x\n",       \
+           str, tag & 0xff,                             \
+           (tag >> 8) & 0xff,                           \
+           (tag >> 16) & 0xff,                          \
+           (tag >> 24) & 0xff,                          \
+           size)
+
+static inline int get_duration(AVIStream *ast, int len){
+    if(ast->sample_size){
+        return len;
+    }else if (ast->dshow_block_align){
+        return (len + ast->dshow_block_align - 1)/ast->dshow_block_align;
+    }else
+        return 1;
 }
-#endif
 
-static int get_riff(AVFormatContext *s, ByteIOContext *pb)
+static int get_riff(AVFormatContext *s, AVIOContext *pb)
 {
     AVIContext *avi = s->priv_data;
     char header[8];
     int i;
 
     /* check RIFF header */
-    get_buffer(pb, header, 4);
-    avi->riff_end = get_le32(pb);   /* RIFF chunk size */
-    avi->riff_end += url_ftell(pb); /* RIFF chunk end */
-    get_buffer(pb, header+4, 4);
+    avio_read(pb, header, 4);
+    avi->riff_end = avio_rl32(pb);  /* RIFF chunk size */
+    avi->riff_end += avio_tell(pb); /* RIFF chunk end */
+    avio_read(pb, header+4, 4);
 
     for(i=0; avi_headers[i][0]; i++)
         if(!memcmp(header, avi_headers[i], 8))
@@ -113,19 +126,19 @@ static int get_riff(AVFormatContext *s, ByteIOContext *pb)
 
 static int read_braindead_odml_indx(AVFormatContext *s, int frame_num){
     AVIContext *avi = s->priv_data;
-    ByteIOContext *pb = s->pb;
-    int longs_pre_entry= get_le16(pb);
-    int index_sub_type = get_byte(pb);
-    int index_type     = get_byte(pb);
-    int entries_in_use = get_le32(pb);
-    int chunk_id       = get_le32(pb);
-    int64_t base       = get_le64(pb);
+    AVIOContext *pb = s->pb;
+    int longs_pre_entry= avio_rl16(pb);
+    int index_sub_type = avio_r8(pb);
+    int index_type     = avio_r8(pb);
+    int entries_in_use = avio_rl32(pb);
+    int chunk_id       = avio_rl32(pb);
+    int64_t base       = avio_rl64(pb);
     int stream_id= 10*((chunk_id&0xFF) - '0') + (((chunk_id>>8)&0xFF) - '0');
     AVStream *st;
     AVIStream *ast;
     int i;
     int64_t last_pos= -1;
-    int64_t filesize= url_fsize(s->pb);
+    int64_t filesize= avio_size(s->pb);
 
 #ifdef DEBUG_SEEK
     av_log(s, AV_LOG_ERROR, "longs_pre_entry:%d index_type:%d entries_in_use:%d chunk_id:%X base:%16"PRIX64"\n",
@@ -140,7 +153,7 @@ static int read_braindead_odml_indx(AVFormatContext *s, int frame_num){
     if(index_sub_type)
         return -1;
 
-    get_le32(pb);
+    avio_rl32(pb);
 
     if(index_type && longs_pre_entry != 2)
         return -1;
@@ -157,15 +170,15 @@ static int read_braindead_odml_indx(AVFormatContext *s, int frame_num){
 
     for(i=0; i<entries_in_use; i++){
         if(index_type){
-            int64_t pos= get_le32(pb) + base - 8;
-            int len    = get_le32(pb);
+            int64_t pos= avio_rl32(pb) + base - 8;
+            int len    = avio_rl32(pb);
             int key= len >= 0;
             len &= 0x7FFFFFFF;
 
 #ifdef DEBUG_SEEK
             av_log(s, AV_LOG_ERROR, "pos:%"PRId64", len:%X\n", pos, len);
 #endif
-            if(url_feof(pb))
+            if(pb->eof_reached)
                 return -1;
 
             if(last_pos == pos || pos == base - 8)
@@ -173,28 +186,32 @@ static int read_braindead_odml_indx(AVFormatContext *s, int frame_num){
             if(last_pos != pos && (len || !ast->sample_size))
                 av_add_index_entry(st, pos, ast->cum_len, len, 0, key ? AVINDEX_KEYFRAME : 0);
 
-            if(ast->sample_size)
-                ast->cum_len += len;
-            else
-                ast->cum_len ++;
+            ast->cum_len += get_duration(ast, len);
             last_pos= pos;
         }else{
             int64_t offset, pos;
             int duration;
-            offset = get_le64(pb);
-            get_le32(pb);       /* size */
-            duration = get_le32(pb);
+            offset = avio_rl64(pb);
+            avio_rl32(pb);       /* size */
+            duration = avio_rl32(pb);
 
-            if(url_feof(pb))
+            if(pb->eof_reached)
                 return -1;
 
-            pos = url_ftell(pb);
+            pos = avio_tell(pb);
+
+            if(avi->odml_depth > MAX_ODML_DEPTH){
+                av_log(s, AV_LOG_ERROR, "Too deeply nested ODML indexes\n");
+                return -1;
+            }
 
-            url_fseek(pb, offset+8, SEEK_SET);
+            avio_seek(pb, offset+8, SEEK_SET);
+            avi->odml_depth++;
             read_braindead_odml_indx(s, frame_num);
+            avi->odml_depth--;
             frame_num += duration;
 
-            url_fseek(pb, pos, SEEK_SET);
+            avio_seek(pb, pos, SEEK_SET);
         }
     }
     avi->index_loaded=1;
@@ -229,7 +246,7 @@ static void clean_index(AVFormatContext *s){
 
 static int avi_read_tag(AVFormatContext *s, AVStream *st, uint32_t tag, uint32_t size)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     char key[5] = {0}, *value;
 
     size += (size & 1);
@@ -239,32 +256,86 @@ static int avi_read_tag(AVFormatContext *s, AVStream *st, uint32_t tag, uint32_t
     value = av_malloc(size+1);
     if (!value)
         return -1;
-    get_buffer(pb, value, size);
+    avio_read(pb, value, size);
     value[size]=0;
 
     AV_WL32(key, tag);
 
-    if(st)
-        return av_metadata_set2(&st->metadata, key, value,
-                                    AV_METADATA_DONT_STRDUP_VAL);
-    else
-    return av_metadata_set2(&s->metadata, key, value,
-                                  AV_METADATA_DONT_STRDUP_VAL);
+    return av_metadata_set2(st ? &st->metadata : &s->metadata, key, value,
+                            AV_METADATA_DONT_STRDUP_VAL);
 }
 
 static void avi_read_info(AVFormatContext *s, uint64_t end)
 {
-    while (url_ftell(s->pb) < end) {
-        uint32_t tag  = get_le32(s->pb);
-        uint32_t size = get_le32(s->pb);
+    while (avio_tell(s->pb) < end) {
+        uint32_t tag  = avio_rl32(s->pb);
+        uint32_t size = avio_rl32(s->pb);
         avi_read_tag(s, NULL, tag, size);
     }
 }
 
+static const char months[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
+                                    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
+
+static void avi_metadata_creation_time(AVMetadata **metadata, char *date)
+{
+    char month[4], time[9], buffer[64];
+    int i, day, year;
+    /* parse standard AVI date format (ie. "Mon Mar 10 15:04:43 2003") */
+    if (sscanf(date, "%*3s%*[ ]%3s%*[ ]%2d%*[ ]%8s%*[ ]%4d",
+               month, &day, time, &year) == 4) {
+        for (i=0; i<12; i++)
+            if (!strcasecmp(month, months[i])) {
+                snprintf(buffer, sizeof(buffer), "%.4d-%.2d-%.2d %s",
+                         year, i+1, day, time);
+                av_metadata_set2(metadata, "creation_time", buffer, 0);
+            }
+    } else if (date[4] == '/' && date[7] == '/') {
+        date[4] = date[7] = '-';
+        av_metadata_set2(metadata, "creation_time", date, 0);
+    }
+}
+
+static void avi_read_nikon(AVFormatContext *s, uint64_t end)
+{
+    while (avio_tell(s->pb) < end) {
+        uint32_t tag  = avio_rl32(s->pb);
+        uint32_t size = avio_rl32(s->pb);
+        switch (tag) {
+        case MKTAG('n', 'c', 't', 'g'): {  /* Nikon Tags */
+            uint64_t tag_end = avio_tell(s->pb) + size;
+            while (avio_tell(s->pb) < tag_end) {
+                uint16_t tag  = avio_rl16(s->pb);
+                uint16_t size = avio_rl16(s->pb);
+                const char *name = NULL;
+                char buffer[64] = {0};
+                size -= avio_read(s->pb, buffer,
+                                   FFMIN(size, sizeof(buffer)-1));
+                switch (tag) {
+                case 0x03:  name = "maker";  break;
+                case 0x04:  name = "model";  break;
+                case 0x13:  name = "creation_time";
+                    if (buffer[4] == ':' && buffer[7] == ':')
+                        buffer[4] = buffer[7] = '-';
+                    break;
+                }
+                if (name)
+                    av_metadata_set2(&s->metadata, name, buffer, 0);
+                avio_skip(s->pb, size);
+            }
+            break;
+        }
+        default:
+            avio_skip(s->pb, size);
+            break;
+        }
+    }
+}
+
 static int avi_read_header(AVFormatContext *s, AVFormatParameters *ap)
 {
     AVIContext *avi = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     unsigned int tag, tag1, handler;
     int codec_type, stream_index, frame_period, bit_rate;
     unsigned int size;
@@ -274,13 +345,14 @@ static int avi_read_header(AVFormatContext *s, AVFormatParameters *ap)
     int avih_width=0, avih_height=0;
     int amv_file_format=0;
     uint64_t list_end = 0;
+    int ret;
 
     avi->stream_index= -1;
 
     if (get_riff(s, pb) < 0)
         return -1;
 
-    avi->fsize = url_fsize(pb);
+    avi->fsize = avio_size(pb);
     if(avi->fsize<=0)
         avi->fsize= avi->riff_end == 8 ? INT64_MAX : avi->riff_end;
 
@@ -289,63 +361,72 @@ static int avi_read_header(AVFormatContext *s, AVFormatParameters *ap)
     codec_type = -1;
     frame_period = 0;
     for(;;) {
-        if (url_feof(pb))
+        if (pb->eof_reached)
             goto fail;
-        tag = get_le32(pb);
-        size = get_le32(pb);
-#ifdef DEBUG
+        tag = avio_rl32(pb);
+        size = avio_rl32(pb);
+
         print_tag("tag", tag, size);
-#endif
 
         switch(tag) {
         case MKTAG('L', 'I', 'S', 'T'):
-            list_end = url_ftell(pb) + size;
+            list_end = avio_tell(pb) + size;
             /* Ignored, except at start of video packets. */
-            tag1 = get_le32(pb);
-#ifdef DEBUG
+            tag1 = avio_rl32(pb);
+
             print_tag("list", tag1, 0);
-#endif
+
             if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
-                avi->movi_list = url_ftell(pb) - 4;
+                avi->movi_list = avio_tell(pb) - 4;
                 if(size) avi->movi_end = avi->movi_list + size + (size & 1);
-                else     avi->movi_end = url_fsize(pb);
-                dprintf(NULL, "movi end=%"PRIx64"\n", avi->movi_end);
+                else     avi->movi_end = avio_size(pb);
+                av_dlog(NULL, "movi end=%"PRIx64"\n", avi->movi_end);
                 goto end_of_header;
             }
             else if (tag1 == MKTAG('I', 'N', 'F', 'O'))
                 avi_read_info(s, list_end);
+            else if (tag1 == MKTAG('n', 'c', 'd', 't'))
+                avi_read_nikon(s, list_end);
 
             break;
+        case MKTAG('I', 'D', 'I', 'T'): {
+            unsigned char date[64] = {0};
+            size += (size & 1);
+            size -= avio_read(pb, date, FFMIN(size, sizeof(date)-1));
+            avio_skip(pb, size);
+            avi_metadata_creation_time(&s->metadata, date);
+            break;
+        }
         case MKTAG('d', 'm', 'l', 'h'):
             avi->is_odml = 1;
-            url_fskip(pb, size + (size & 1));
+            avio_skip(pb, size + (size & 1));
             break;
         case MKTAG('a', 'm', 'v', 'h'):
             amv_file_format=1;
         case MKTAG('a', 'v', 'i', 'h'):
             /* AVI header */
             /* using frame_period is bad idea */
-            frame_period = get_le32(pb);
-            bit_rate = get_le32(pb) * 8;
-            get_le32(pb);
-            avi->non_interleaved |= get_le32(pb) & AVIF_MUSTUSEINDEX;
-
-            url_fskip(pb, 2 * 4);
-            get_le32(pb);
-            get_le32(pb);
-            avih_width=get_le32(pb);
-            avih_height=get_le32(pb);
-
-            url_fskip(pb, size - 10 * 4);
+            frame_period = avio_rl32(pb);
+            bit_rate = avio_rl32(pb) * 8;
+            avio_rl32(pb);
+            avi->non_interleaved |= avio_rl32(pb) & AVIF_MUSTUSEINDEX;
+
+            avio_skip(pb, 2 * 4);
+            avio_rl32(pb);
+            avio_rl32(pb);
+            avih_width=avio_rl32(pb);
+            avih_height=avio_rl32(pb);
+
+            avio_skip(pb, size - 10 * 4);
             break;
         case MKTAG('s', 't', 'r', 'h'):
             /* stream header */
 
-            tag1 = get_le32(pb);
-            handler = get_le32(pb); /* codec tag */
+            tag1 = avio_rl32(pb);
+            handler = avio_rl32(pb); /* codec tag */
 
             if(tag1 == MKTAG('p', 'a', 'd', 's')){
-                url_fskip(pb, size - 8);
+                avio_skip(pb, size - 8);
                 break;
             }else{
                 stream_index++;
@@ -361,9 +442,8 @@ static int avi_read_header(AVFormatContext *s, AVFormatParameters *ap)
             if(amv_file_format)
                 tag1 = stream_index ? MKTAG('a','u','d','s') : MKTAG('v','i','d','s');
 
-#ifdef DEBUG
             print_tag("strh", tag1, -1);
-#endif
+
             if(tag1 == MKTAG('i', 'a', 'v', 's') || tag1 == MKTAG('i', 'v', 'a', 's')){
                 int64_t dv_dur;
 
@@ -381,6 +461,7 @@ static int avi_read_header(AVFormatContext *s, AVFormatParameters *ap)
 
                 ast = s->streams[0]->priv_data;
                 av_freep(&s->streams[0]->codec->extradata);
+                av_freep(&s->streams[0]->codec);
                 av_freep(&s->streams[0]);
                 s->nb_streams = 0;
                 if (CONFIG_DV_DEMUXER) {
@@ -389,12 +470,12 @@ static int avi_read_header(AVFormatContext *s, AVFormatParameters *ap)
                         goto fail;
                 }
                 s->streams[0]->priv_data = ast;
-                url_fskip(pb, 3 * 4);
-                ast->scale = get_le32(pb);
-                ast->rate = get_le32(pb);
-                url_fskip(pb, 4);  /* start time */
+                avio_skip(pb, 3 * 4);
+                ast->scale = avio_rl32(pb);
+                ast->rate = avio_rl32(pb);
+                avio_skip(pb, 4);  /* start time */
 
-                dv_dur = get_le32(pb);
+                dv_dur = avio_rl32(pb);
                 if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
                     dv_dur *= AV_TIME_BASE;
                     s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
@@ -405,19 +486,19 @@ static int avi_read_header(AVFormatContext *s, AVFormatParameters *ap)
                  */
 
                 stream_index = s->nb_streams - 1;
-                url_fskip(pb, size - 9*4);
+                avio_skip(pb, size - 9*4);
                 break;
             }
 
             assert(stream_index < s->nb_streams);
             st->codec->stream_codec_tag= handler;
 
-            get_le32(pb); /* flags */
-            get_le16(pb); /* priority */
-            get_le16(pb); /* language */
-            get_le32(pb); /* initial frame */
-            ast->scale = get_le32(pb);
-            ast->rate = get_le32(pb);
+            avio_rl32(pb); /* flags */
+            avio_rl16(pb); /* priority */
+            avio_rl16(pb); /* language */
+            avio_rl32(pb); /* initial frame */
+            ast->scale = avio_rl32(pb);
+            ast->rate = avio_rl32(pb);
             if(!(ast->scale && ast->rate)){
                 av_log(s, AV_LOG_WARNING, "scale/rate is %u/%u which is invalid. (This file has been generated by broken software.)\n", ast->scale, ast->rate);
                 if(frame_period){
@@ -430,13 +511,13 @@ static int avi_read_header(AVFormatContext *s, AVFormatParameters *ap)
             }
             av_set_pts_info(st, 64, ast->scale, ast->rate);
 
-            ast->cum_len=get_le32(pb); /* start */
-            st->nb_frames = get_le32(pb);
+            ast->cum_len=avio_rl32(pb); /* start */
+            st->nb_frames = avio_rl32(pb);
 
             st->start_time = 0;
-            get_le32(pb); /* buffer size */
-            get_le32(pb); /* quality */
-            ast->sample_size = get_le32(pb); /* sample ssize */
+            avio_rl32(pb); /* buffer size */
+            avio_rl32(pb); /* quality */
+            ast->sample_size = avio_rl32(pb); /* sample ssize */
             ast->cum_len *= FFMAX(1, ast->sample_size);
 //            av_log(s, AV_LOG_DEBUG, "%d %d %d %d\n", ast->rate, ast->scale, ast->start, ast->sample_size);
 
@@ -450,8 +531,7 @@ static int avi_read_header(AVFormatContext *s, AVFormatParameters *ap)
                 codec_type = AVMEDIA_TYPE_AUDIO;
                 break;
             case MKTAG('t', 'x', 't', 's'):
-                //FIXME
-                codec_type = AVMEDIA_TYPE_DATA; //AVMEDIA_TYPE_SUB ?  FIXME
+                codec_type = AVMEDIA_TYPE_SUBTITLE;
                 break;
             case MKTAG('d', 'a', 't', 's'):
                 codec_type = AVMEDIA_TYPE_DATA;
@@ -463,14 +543,14 @@ static int avi_read_header(AVFormatContext *s, AVFormatParameters *ap)
             if(ast->sample_size == 0)
                 st->duration = st->nb_frames;
             ast->frame_offset= ast->cum_len;
-            url_fskip(pb, size - 12 * 4);
+            avio_skip(pb, size - 12 * 4);
             break;
         case MKTAG('s', 't', 'r', 'f'):
             /* stream header */
             if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
-                url_fskip(pb, size);
+                avio_skip(pb, size);
             } else {
-                uint64_t cur_pos = url_ftell(pb);
+                uint64_t cur_pos = avio_tell(pb);
                 if (cur_pos < list_end)
                     size = FFMIN(size, list_end - cur_pos);
                 st = s->streams[stream_index];
@@ -481,20 +561,10 @@ static int avi_read_header(AVFormatContext *s, AVFormatParameters *ap)
                         st->codec->height=avih_height;
                         st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
                         st->codec->codec_id = CODEC_ID_AMV;
-                        url_fskip(pb, size);
+                        avio_skip(pb, size);
                         break;
                     }
-                    get_le32(pb); /* size */
-                    st->codec->width = get_le32(pb);
-                    st->codec->height = (int32_t)get_le32(pb);
-                    get_le16(pb); /* panes */
-                    st->codec->bits_per_coded_sample= get_le16(pb); /* depth */
-                    tag1 = get_le32(pb);
-                    get_le32(pb); /* ImageSize */
-                    get_le32(pb); /* XPelsPerMeter */
-                    get_le32(pb); /* YPelsPerMeter */
-                    get_le32(pb); /* ClrUsed */
-                    get_le32(pb); /* ClrImportant */
+                    tag1 = ff_get_bmp_header(pb, st);
 
                     if (tag1 == MKTAG('D', 'X', 'S', 'B') || tag1 == MKTAG('D','X','S','A')) {
                         st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
@@ -510,30 +580,28 @@ static int avi_read_header(AVFormatContext *s, AVFormatParameters *ap)
                             st->codec->extradata_size= 0;
                             return AVERROR(ENOMEM);
                         }
-                        get_buffer(pb, st->codec->extradata, st->codec->extradata_size);
+                        avio_read(pb, st->codec->extradata, st->codec->extradata_size);
                     }
 
                     if(st->codec->extradata_size & 1) //FIXME check if the encoder really did this correctly
-                        get_byte(pb);
+                        avio_r8(pb);
 
                     /* Extract palette from extradata if bpp <= 8. */
                     /* This code assumes that extradata contains only palette. */
-                    /* This is true for all paletted codecs implemented in FFmpeg. */
+                    /* This is true for all paletted codecs implemented in Libav. */
                     if (st->codec->extradata_size && (st->codec->bits_per_coded_sample <= 8)) {
-                        st->codec->palctrl = av_mallocz(sizeof(AVPaletteControl));
 #if HAVE_BIGENDIAN
                         for (i = 0; i < FFMIN(st->codec->extradata_size, AVPALETTE_SIZE)/4; i++)
-                            st->codec->palctrl->palette[i] = bswap_32(((uint32_t*)st->codec->extradata)[i]);
+                            ast->pal[i] = av_bswap32(((uint32_t*)st->codec->extradata)[i]);
 #else
-                        memcpy(st->codec->palctrl->palette, st->codec->extradata,
+                        memcpy(ast->pal, st->codec->extradata,
                                FFMIN(st->codec->extradata_size, AVPALETTE_SIZE));
 #endif
-                        st->codec->palctrl->palette_changed = 1;
+                        ast->has_pal = 1;
                     }
 
-#ifdef DEBUG
                     print_tag("video", tag1, 0);
-#endif
+
                     st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
                     st->codec->codec_tag = tag1;
                     st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags, tag1);
@@ -552,16 +620,19 @@ static int avi_read_header(AVFormatContext *s, AVFormatParameters *ap)
                     }
                     st->codec->height= FFABS(st->codec->height);
 
-//                    url_fskip(pb, size - 5 * 4);
+//                    avio_skip(pb, size - 5 * 4);
                     break;
                 case AVMEDIA_TYPE_AUDIO:
-                    ff_get_wav_header(pb, st->codec, size);
+                    ret = ff_get_wav_header(pb, st->codec, size);
+                    if (ret < 0)
+                        return ret;
+                    ast->dshow_block_align= st->codec->block_align;
                     if(ast->sample_size && st->codec->block_align && ast->sample_size != st->codec->block_align){
                         av_log(s, AV_LOG_WARNING, "sample size (%d) != block align (%d)\n", ast->sample_size, st->codec->block_align);
                         ast->sample_size= st->codec->block_align;
                     }
                     if (size&1) /* 2-aligned (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
-                        url_fskip(pb, 1);
+                        avio_skip(pb, 1);
                     /* Force parsing as several audio frames can be in
                      * one packet and timestamps refer to packet start. */
                     st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
@@ -576,41 +647,47 @@ static int avi_read_header(AVFormatContext *s, AVFormatParameters *ap)
                         st->codec->codec_id  = CODEC_ID_XAN_DPCM;
                         st->codec->codec_tag = 0;
                     }
-                    if (amv_file_format)
+                    if (amv_file_format){
                         st->codec->codec_id  = CODEC_ID_ADPCM_IMA_AMV;
+                        ast->dshow_block_align = 0;
+                    }
+                    break;
+                case AVMEDIA_TYPE_SUBTITLE:
+                    st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
+                    st->codec->codec_id   = CODEC_ID_PROBE;
                     break;
                 default:
                     st->codec->codec_type = AVMEDIA_TYPE_DATA;
                     st->codec->codec_id= CODEC_ID_NONE;
                     st->codec->codec_tag= 0;
-                    url_fskip(pb, size);
+                    avio_skip(pb, size);
                     break;
                 }
             }
             break;
         case MKTAG('i', 'n', 'd', 'x'):
-            i= url_ftell(pb);
-            if(!url_is_streamed(pb) && !(s->flags & AVFMT_FLAG_IGNIDX)){
+            i= avio_tell(pb);
+            if(pb->seekable && !(s->flags & AVFMT_FLAG_IGNIDX)){
                 read_braindead_odml_indx(s, 0);
             }
-            url_fseek(pb, i+size, SEEK_SET);
+            avio_seek(pb, i+size, SEEK_SET);
             break;
         case MKTAG('v', 'p', 'r', 'p'):
             if(stream_index < (unsigned)s->nb_streams && size > 9*4){
                 AVRational active, active_aspect;
 
                 st = s->streams[stream_index];
-                get_le32(pb);
-                get_le32(pb);
-                get_le32(pb);
-                get_le32(pb);
-                get_le32(pb);
-
-                active_aspect.den= get_le16(pb);
-                active_aspect.num= get_le16(pb);
-                active.num       = get_le32(pb);
-                active.den       = get_le32(pb);
-                get_le32(pb); //nbFieldsPerFrame
+                avio_rl32(pb);
+                avio_rl32(pb);
+                avio_rl32(pb);
+                avio_rl32(pb);
+                avio_rl32(pb);
+
+                active_aspect.den= avio_rl16(pb);
+                active_aspect.num= avio_rl16(pb);
+                active.num       = avio_rl32(pb);
+                active.den       = avio_rl32(pb);
+                avio_rl32(pb); //nbFieldsPerFrame
 
                 if(active_aspect.num && active_aspect.den && active.num && active.den){
                     st->sample_aspect_ratio= av_div_q(active_aspect, active);
@@ -618,7 +695,7 @@ static int avi_read_header(AVFormatContext *s, AVFormatParameters *ap)
                 }
                 size -= 9*4;
             }
-            url_fseek(pb, size, SEEK_CUR);
+            avio_skip(pb, size);
             break;
         case MKTAG('s', 't', 'r', 'n'):
             if(s->nb_streams){
@@ -629,13 +706,13 @@ static int avi_read_header(AVFormatContext *s, AVFormatParameters *ap)
             if(size > 1000000){
                 av_log(s, AV_LOG_ERROR, "Something went wrong during header parsing, "
                                         "I will ignore it and try to continue anyway.\n");
-                avi->movi_list = url_ftell(pb) - 4;
-                avi->movi_end  = url_fsize(pb);
+                avi->movi_list = avio_tell(pb) - 4;
+                avi->movi_end  = avio_size(pb);
                 goto end_of_header;
             }
             /* skip tag */
             size += (size & 1);
-            url_fskip(pb, size);
+            avio_skip(pb, size);
             break;
         }
     }
@@ -646,7 +723,7 @@ static int avi_read_header(AVFormatContext *s, AVFormatParameters *ap)
         return -1;
     }
 
-    if(!avi->index_loaded && !url_is_streamed(pb))
+    if(!avi->index_loaded && pb->seekable)
         avi_load_index(s);
     avi->index_loaded = 1;
     avi->non_interleaved |= guess_ni_flag(s);
@@ -665,9 +742,88 @@ static int avi_read_header(AVFormatContext *s, AVFormatParameters *ap)
         clean_index(s);
     }
 
+    ff_metadata_conv_ctx(s, NULL, ff_avi_metadata_conv);
+
+    return 0;
+}
+
+static int read_gab2_sub(AVStream *st, AVPacket *pkt) {
+    if (!strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data+5) == 2) {
+        uint8_t desc[256];
+        int score = AVPROBE_SCORE_MAX / 2, ret;
+        AVIStream *ast = st->priv_data;
+        AVInputFormat *sub_demuxer;
+        AVRational time_base;
+        AVIOContext *pb = avio_alloc_context( pkt->data + 7,
+                                              pkt->size - 7,
+                                              0, NULL, NULL, NULL, NULL);
+        AVProbeData pd;
+        unsigned int desc_len = avio_rl32(pb);
+
+        if (desc_len > pb->buf_end - pb->buf_ptr)
+            goto error;
+
+        ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
+        avio_skip(pb, desc_len - ret);
+        if (*desc)
+            av_metadata_set2(&st->metadata, "title", desc, 0);
+
+        avio_rl16(pb);   /* flags? */
+        avio_rl32(pb);   /* data size */
+
+        pd = (AVProbeData) { .buf = pb->buf_ptr, .buf_size = pb->buf_end - pb->buf_ptr };
+        if (!(sub_demuxer = av_probe_input_format2(&pd, 1, &score)))
+            goto error;
+
+        if (!av_open_input_stream(&ast->sub_ctx, pb, "", sub_demuxer, NULL)) {
+            av_read_packet(ast->sub_ctx, &ast->sub_pkt);
+            *st->codec = *ast->sub_ctx->streams[0]->codec;
+            ast->sub_ctx->streams[0]->codec->extradata = NULL;
+            time_base = ast->sub_ctx->streams[0]->time_base;
+            av_set_pts_info(st, 64, time_base.num, time_base.den);
+        }
+        ast->sub_buffer = pkt->data;
+        memset(pkt, 0, sizeof(*pkt));
+        return 1;
+error:
+        av_freep(&pb);
+    }
     return 0;
 }
 
+static AVStream *get_subtitle_pkt(AVFormatContext *s, AVStream *next_st,
+                                  AVPacket *pkt)
+{
+    AVIStream *ast, *next_ast = next_st->priv_data;
+    int64_t ts, next_ts, ts_min = INT64_MAX;
+    AVStream *st, *sub_st = NULL;
+    int i;
+
+    next_ts = av_rescale_q(next_ast->frame_offset, next_st->time_base,
+                           AV_TIME_BASE_Q);
+
+    for (i=0; i<s->nb_streams; i++) {
+        st  = s->streams[i];
+        ast = st->priv_data;
+        if (st->discard < AVDISCARD_ALL && ast && ast->sub_pkt.data) {
+            ts = av_rescale_q(ast->sub_pkt.dts, st->time_base, AV_TIME_BASE_Q);
+            if (ts <= next_ts && ts < ts_min) {
+                ts_min = ts;
+                sub_st = st;
+            }
+        }
+    }
+
+    if (sub_st) {
+        ast = sub_st->priv_data;
+        *pkt = ast->sub_pkt;
+        pkt->stream_index = sub_st->index;
+        if (av_read_packet(ast->sub_ctx, &ast->sub_pkt) < 0)
+            ast->sub_pkt.data = NULL;
+    }
+    return sub_st;
+}
+
 static int get_stream_idx(int *d){
     if(    d[0] >= '0' && d[0] <= '9'
         && d[1] >= '0' && d[1] <= '9'){
@@ -680,7 +836,7 @@ static int get_stream_idx(int *d){
 static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
 {
     AVIContext *avi = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int n, d[8];
     unsigned int size;
     int64_t i, sync;
@@ -738,7 +894,7 @@ static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
         if(i>=0){
             int64_t pos= best_st->index_entries[i].pos;
             pos += best_ast->packet_size - best_ast->remaining;
-            url_fseek(s->pb, pos + 8, SEEK_SET);
+            avio_seek(s->pb, pos + 8, SEEK_SET);
 //        av_log(s, AV_LOG_DEBUG, "pos=%"PRId64"\n", pos);
 
             assert(best_ast->remaining <= best_ast->packet_size);
@@ -756,6 +912,9 @@ resync:
         AVIStream *ast= st->priv_data;
         int size, err;
 
+        if(get_subtitle_pkt(s, st, pkt))
+            return 0;
+
         if(ast->sample_size <= 1) // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
             size= INT_MAX;
         else if(ast->sample_size < 32)
@@ -766,20 +925,20 @@ resync:
 
         if(size > ast->remaining)
             size= ast->remaining;
-        avi->last_pkt_pos= url_ftell(pb);
+        avi->last_pkt_pos= avio_tell(pb);
         err= av_get_packet(pb, pkt, size);
         if(err<0)
             return err;
 
         if(ast->has_pal && pkt->data && pkt->size<(unsigned)INT_MAX/2){
-            void *ptr= av_realloc(pkt->data, pkt->size + 4*256 + FF_INPUT_BUFFER_PADDING_SIZE);
-            if(ptr){
-            ast->has_pal=0;
-            pkt->size += 4*256;
-            pkt->data= ptr;
-                memcpy(pkt->data + pkt->size - 4*256, ast->pal, 4*256);
-            }else
-                av_log(s, AV_LOG_ERROR, "Failed to append palette\n");
+            uint8_t *pal;
+            pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
+            if(!pal){
+                av_log(s, AV_LOG_ERROR, "Failed to allocate data for palette\n");
+            }else{
+                memcpy(pal, ast->pal, AVPALETTE_SIZE);
+                ast->has_pal = 0;
+            }
         }
 
         if (CONFIG_DV_DEMUXER && avi->dv_demux) {
@@ -788,6 +947,14 @@ resync:
                                     pkt->data, pkt->size);
             pkt->destruct = dstr;
             pkt->flags |= AV_PKT_FLAG_KEY;
+            if (size < 0)
+                av_free_packet(pkt);
+        } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE
+                   && !st->codec->codec_tag && read_gab2_sub(st, pkt)) {
+            ast->frame_offset++;
+            avi->stream_index = -1;
+            ast->remaining = 0;
+            goto resync;
         } else {
             /* XXX: How to handle B-frames in AVI? */
             pkt->dts = ast->frame_offset;
@@ -812,10 +979,7 @@ resync:
             } else {
                 pkt->flags |= AV_PKT_FLAG_KEY;
             }
-            if(ast->sample_size)
-                ast->frame_offset += pkt->size;
-            else
-                ast->frame_offset++;
+            ast->frame_offset += get_duration(ast, pkt->size);
         }
         ast->remaining -= size;
         if(!ast->remaining){
@@ -827,12 +991,12 @@ resync:
     }
 
     memset(d, -1, sizeof(int)*8);
-    for(i=sync=url_ftell(pb); !url_feof(pb); i++) {
+    for(i=sync=avio_tell(pb); !pb->eof_reached; i++) {
         int j;
 
         for(j=0; j<7; j++)
             d[j]= d[j+1];
-        d[7]= get_byte(pb);
+        d[7]= avio_r8(pb);
 
         size= d[4] + (d[5]<<8) + (d[6]<<16) + (d[7]<<24);
 
@@ -846,14 +1010,14 @@ resync:
         //parse JUNK
            ||(d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K')
            ||(d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')){
-            url_fskip(pb, size);
+            avio_skip(pb, size);
 //av_log(s, AV_LOG_DEBUG, "SKIP\n");
             goto resync;
         }
 
         //parse stray LIST
         if(d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T'){
-            url_fskip(pb, 4);
+            avio_skip(pb, 4);
             goto resync;
         }
 
@@ -864,7 +1028,7 @@ resync:
 
         //detect ##ix chunk and skip
         if(d[2] == 'i' && d[3] == 'x' && n < s->nb_streams){
-            url_fskip(pb, size);
+            avio_skip(pb, size);
             goto resync;
         }
 
@@ -897,20 +1061,19 @@ resync:
             if(   (st->discard >= AVDISCARD_DEFAULT && size==0)
                /*|| (st->discard >= AVDISCARD_NONKEY && !(pkt->flags & AV_PKT_FLAG_KEY))*/ //FIXME needs a little reordering
                || st->discard >= AVDISCARD_ALL){
-                if(ast->sample_size) ast->frame_offset += size;
-                else                 ast->frame_offset++;
-                url_fskip(pb, size);
+                ast->frame_offset += get_duration(ast, size);
+                avio_skip(pb, size);
                 goto resync;
             }
 
             if (d[2] == 'p' && d[3] == 'c' && size<=4*256+4) {
-                int k = get_byte(pb);
-                int last = (k + get_byte(pb) - 1) & 0xFF;
+                int k = avio_r8(pb);
+                int last = (k + avio_r8(pb) - 1) & 0xFF;
 
-                get_le16(pb); //flags
+                avio_rl16(pb); //flags
 
                 for (; k <= last; k++)
-                    ast->pal[k] = get_be32(pb)>>8;// b + (g << 8) + (r << 16);
+                    ast->pal[k] = avio_rb32(pb)>>8;// b + (g << 8) + (r << 16);
                 ast->has_pal= 1;
                 goto resync;
             } else if(   ((ast->prefix_count<5 || sync+9 > i) && d[2]<128 && d[3]<128) ||
@@ -931,7 +1094,7 @@ resync:
                 ast->remaining= size;
 
                 if(size || !ast->sample_size){
-                    uint64_t pos= url_ftell(pb) - 8;
+                    uint64_t pos= avio_tell(pb) - 8;
                     if(!st->index_entries || !st->nb_index_entries || st->index_entries[st->nb_index_entries - 1].pos < pos){
                         av_add_index_entry(st, pos, ast->frame_offset, size, 0, AVINDEX_KEYFRAME);
                     }
@@ -949,7 +1112,7 @@ resync:
 static int avi_read_idx1(AVFormatContext *s, int size)
 {
     AVIContext *avi = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int nb_index_entries, i;
     AVStream *st;
     AVIStream *ast;
@@ -962,10 +1125,10 @@ static int avi_read_idx1(AVFormatContext *s, int size)
 
     /* Read the entries and sort them in each stream component. */
     for(i = 0; i < nb_index_entries; i++) {
-        tag = get_le32(pb);
-        flags = get_le32(pb);
-        pos = get_le32(pb);
-        len = get_le32(pb);
+        tag = avio_rl32(pb);
+        flags = avio_rl32(pb);
+        pos = avio_rl32(pb);
+        len = avio_rl32(pb);
 #if defined(DEBUG_SEEK)
         av_log(s, AV_LOG_DEBUG, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
                i, tag, flags, pos, len);
@@ -984,17 +1147,14 @@ static int avi_read_idx1(AVFormatContext *s, int size)
 #if defined(DEBUG_SEEK)
         av_log(s, AV_LOG_DEBUG, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
 #endif
-        if(url_feof(pb))
+        if(pb->eof_reached)
             return -1;
 
         if(last_pos == pos)
             avi->non_interleaved= 1;
         else if(len || !ast->sample_size)
             av_add_index_entry(st, pos, ast->cum_len, len, 0, (flags&AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
-        if(ast->sample_size)
-            ast->cum_len += len;
-        else
-            ast->cum_len ++;
+        ast->cum_len += get_duration(ast, len);
         last_pos= pos;
     }
     return 0;
@@ -1004,7 +1164,7 @@ static int guess_ni_flag(AVFormatContext *s){
     int i;
     int64_t last_start=0;
     int64_t first_end= INT64_MAX;
-    int64_t oldpos= url_ftell(s->pb);
+    int64_t oldpos= avio_tell(s->pb);
 
     for(i=0; i<s->nb_streams; i++){
         AVStream *st = s->streams[i];
@@ -1016,8 +1176,8 @@ static int guess_ni_flag(AVFormatContext *s){
 
         if(n >= 2){
             int64_t pos= st->index_entries[0].pos;
-            url_fseek(s->pb, pos + 4, SEEK_SET);
-            size= get_le32(s->pb);
+            avio_seek(s->pb, pos + 4, SEEK_SET);
+            size= avio_rl32(s->pb);
             if(pos + size > st->index_entries[1].pos)
                 last_start= INT64_MAX;
         }
@@ -1027,28 +1187,28 @@ static int guess_ni_flag(AVFormatContext *s){
         if(st->index_entries[n-1].pos < first_end)
             first_end= st->index_entries[n-1].pos;
     }
-    url_fseek(s->pb, oldpos, SEEK_SET);
+    avio_seek(s->pb, oldpos, SEEK_SET);
     return last_start > first_end;
 }
 
 static int avi_load_index(AVFormatContext *s)
 {
     AVIContext *avi = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     uint32_t tag, size;
-    int64_t pos= url_ftell(pb);
+    int64_t pos= avio_tell(pb);
     int ret = -1;
 
-    if (url_fseek(pb, avi->movi_end, SEEK_SET) < 0)
+    if (avio_seek(pb, avi->movi_end, SEEK_SET) < 0)
         goto the_end; // maybe truncated file
 #ifdef DEBUG_SEEK
     printf("movi_end=0x%"PRIx64"\n", avi->movi_end);
 #endif
     for(;;) {
-        if (url_feof(pb))
+        if (pb->eof_reached)
             break;
-        tag = get_le32(pb);
-        size = get_le32(pb);
+        tag = avio_rl32(pb);
+        size = avio_rl32(pb);
 #ifdef DEBUG_SEEK
         printf("tag=%c%c%c%c size=0x%x\n",
                tag & 0xff,
@@ -1067,16 +1227,26 @@ static int avi_load_index(AVFormatContext *s)
         default:
         skip:
             size += (size & 1);
-            if (url_fseek(pb, size, SEEK_CUR) < 0)
+            if (avio_skip(pb, size) < 0)
                 goto the_end; // something is wrong here
             break;
         }
     }
  the_end:
-    url_fseek(pb, pos, SEEK_SET);
+    avio_seek(pb, pos, SEEK_SET);
     return ret;
 }
 
+static void seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp)
+{
+    AVIStream *ast2 = st2->priv_data;
+    int64_t ts2 = av_rescale_q(timestamp, st->time_base, st2->time_base);
+    av_free_packet(&ast2->sub_pkt);
+    if (avformat_seek_file(ast2->sub_ctx, 0, INT64_MIN, ts2, ts2, 0) >= 0 ||
+        avformat_seek_file(ast2->sub_ctx, 0, ts2, ts2, INT64_MAX, 0) >= 0)
+        av_read_packet(ast2->sub_ctx, &ast2->sub_pkt);
+}
+
 static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
 {
     AVIContext *avi = s->priv_data;
@@ -1114,7 +1284,7 @@ static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp
         /* DV demux so it can synthesize correct timestamps.        */
         dv_offset_reset(avi->dv_demux, timestamp);
 
-        url_fseek(s->pb, pos, SEEK_SET);
+        avio_seek(s->pb, pos, SEEK_SET);
         avi->stream_index= -1;
         return 0;
     }
@@ -1126,6 +1296,11 @@ static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp
         ast2->packet_size=
         ast2->remaining= 0;
 
+        if (ast2->sub_ctx) {
+            seek_subtitle(st, st2, timestamp);
+            continue;
+        }
+
         if (st2->nb_index_entries <= 0)
             continue;
 
@@ -1151,7 +1326,7 @@ static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp
     }
 
     /* do the seek */
-    url_fseek(s->pb, pos, SEEK_SET);
+    avio_seek(s->pb, pos, SEEK_SET);
     avi->stream_index= -1;
     return 0;
 }
@@ -1163,11 +1338,18 @@ static int avi_read_close(AVFormatContext *s)
 
     for(i=0;i<s->nb_streams;i++) {
         AVStream *st = s->streams[i];
-        av_free(st->codec->palctrl);
+        AVIStream *ast = st->priv_data;
+        if (ast) {
+            if (ast->sub_ctx) {
+                av_freep(&ast->sub_ctx->pb);
+                av_close_input_stream(ast->sub_ctx);
+            }
+            av_free(ast->sub_buffer);
+            av_free_packet(&ast->sub_pkt);
+        }
     }
 
-    if (avi->dv_demux)
-        av_free(avi->dv_demux);
+    av_free(avi->dv_demux);
 
     return 0;
 }
@@ -1185,7 +1367,7 @@ static int avi_probe(AVProbeData *p)
     return 0;
 }
 
-AVInputFormat avi_demuxer = {
+AVInputFormat ff_avi_demuxer = {
     "avi",
     NULL_IF_CONFIG_SMALL("AVI format"),
     sizeof(AVIContext),
@@ -1194,5 +1376,4 @@ AVInputFormat avi_demuxer = {
     avi_read_packet,
     avi_read_close,
     avi_read_seek,
-    .metadata_conv = ff_avi_metadata_conv,
 };
diff --git a/libavformat/avienc.c b/libavformat/avienc.c
index b4a31ec..1b6f645 100644
--- a/libavformat/avienc.c
+++ b/libavformat/avienc.c
@@ -2,24 +2,25 @@
  * AVI muxer
  * Copyright (c) 2000 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #include "avformat.h"
 #include "avi.h"
+#include "avio_internal.h"
 #include "riff.h"
 #include "libavutil/intreadwrite.h"
 
@@ -63,7 +64,7 @@ static inline AVIIentry* avi_get_ientry(AVIIndex* idx, int ent_id)
     return &idx->cluster[cl][id];
 }
 
-static int64_t avi_start_new_riff(AVFormatContext *s, ByteIOContext *pb,
+static int64_t avi_start_new_riff(AVFormatContext *s, AVIOContext *pb,
                                   const char* riff_tag, const char* list_tag)
 {
     AVIContext *avi= s->priv_data;
@@ -77,16 +78,16 @@ static int64_t avi_start_new_riff(AVFormatContext *s, ByteIOContext *pb,
     }
 
     avi->riff_start = ff_start_tag(pb, "RIFF");
-    put_tag(pb, riff_tag);
+    ffio_wfourcc(pb, riff_tag);
     loff = ff_start_tag(pb, "LIST");
-    put_tag(pb, list_tag);
+    ffio_wfourcc(pb, list_tag);
     return loff;
 }
 
 static char* avi_stream2fourcc(char* tag, int index, enum AVMediaType type)
 {
-    tag[0] = '0';
-    tag[1] = '0' + index;
+    tag[0] = '0' + index/10;
+    tag[1] = '0' + index%10;
     if (type == AVMEDIA_TYPE_VIDEO) {
         tag[2] = 'd';
         tag[3] = 'c';
@@ -102,49 +103,49 @@ static char* avi_stream2fourcc(char* tag, int index, enum AVMediaType type)
     return tag;
 }
 
-static void avi_write_info_tag(ByteIOContext *pb, const char *tag, const char *str)
+static void avi_write_info_tag(AVIOContext *pb, const char *tag, const char *str)
 {
     int len = strlen(str);
     if (len > 0) {
         len++;
-        put_tag(pb, tag);
-        put_le32(pb, len);
-        put_strz(pb, str);
+        ffio_wfourcc(pb, tag);
+        avio_wl32(pb, len);
+        avio_put_str(pb, str);
         if (len & 1)
-            put_byte(pb, 0);
+            avio_w8(pb, 0);
     }
 }
 
 static int avi_write_counters(AVFormatContext* s, int riff_id)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVIContext *avi = s->priv_data;
     int n, au_byterate, au_ssize, au_scale, nb_frames = 0;
     int64_t file_size;
     AVCodecContext* stream;
 
-    file_size = url_ftell(pb);
+    file_size = avio_tell(pb);
     for(n = 0; n < s->nb_streams; n++) {
         AVIStream *avist= s->streams[n]->priv_data;
 
         assert(avist->frames_hdr_strm);
         stream = s->streams[n]->codec;
-        url_fseek(pb, avist->frames_hdr_strm, SEEK_SET);
+        avio_seek(pb, avist->frames_hdr_strm, SEEK_SET);
         ff_parse_specific_params(stream, &au_byterate, &au_ssize, &au_scale);
         if(au_ssize == 0) {
-            put_le32(pb, avist->packet_count);
+            avio_wl32(pb, avist->packet_count);
         } else {
-            put_le32(pb, avist->audio_strm_length / au_ssize);
+            avio_wl32(pb, avist->audio_strm_length / au_ssize);
         }
         if(stream->codec_type == AVMEDIA_TYPE_VIDEO)
             nb_frames = FFMAX(nb_frames, avist->packet_count);
     }
     if(riff_id == 1) {
         assert(avi->frames_hdr_all);
-        url_fseek(pb, avi->frames_hdr_all, SEEK_SET);
-        put_le32(pb, nb_frames);
+        avio_seek(pb, avi->frames_hdr_all, SEEK_SET);
+        avio_wl32(pb, nb_frames);
     }
-    url_fseek(pb, file_size, SEEK_SET);
+    avio_seek(pb, file_size, SEEK_SET);
 
     return 0;
 }
@@ -152,12 +153,18 @@ static int avi_write_counters(AVFormatContext* s, int riff_id)
 static int avi_write_header(AVFormatContext *s)
 {
     AVIContext *avi = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int bitrate, n, i, nb_frames, au_byterate, au_ssize, au_scale;
     AVCodecContext *stream, *video_enc;
     int64_t list1, list2, strh, strf;
     AVMetadataTag *t = NULL;
 
+    if (s->nb_streams > AVI_MAX_STREAM_COUNT) {
+        av_log(s, AV_LOG_ERROR, "AVI does not support >%d streams\n",
+               AVI_MAX_STREAM_COUNT);
+        return -1;
+    }
+
     for(n=0;n<s->nb_streams;n++) {
         s->streams[n]->priv_data= av_mallocz(sizeof(AVIStream));
         if(!s->streams[n]->priv_data)
@@ -169,8 +176,8 @@ static int avi_write_header(AVFormatContext *s)
     list1 = avi_start_new_riff(s, pb, "AVI ", "hdrl");
 
     /* avi header */
-    put_tag(pb, "avih");
-    put_le32(pb, 14 * 4);
+    ffio_wfourcc(pb, "avih");
+    avio_wl32(pb, 14 * 4);
     bitrate = 0;
 
     video_enc = NULL;
@@ -184,38 +191,38 @@ static int avi_write_header(AVFormatContext *s)
     nb_frames = 0;
 
     if(video_enc){
-        put_le32(pb, (uint32_t)(INT64_C(1000000) * video_enc->time_base.num / video_enc->time_base.den));
+        avio_wl32(pb, (uint32_t)(INT64_C(1000000) * video_enc->time_base.num / video_enc->time_base.den));
     } else {
-        put_le32(pb, 0);
+        avio_wl32(pb, 0);
     }
-    put_le32(pb, bitrate / 8); /* XXX: not quite exact */
-    put_le32(pb, 0); /* padding */
-    if (url_is_streamed(pb))
-        put_le32(pb, AVIF_TRUSTCKTYPE | AVIF_ISINTERLEAVED); /* flags */
+    avio_wl32(pb, bitrate / 8); /* XXX: not quite exact */
+    avio_wl32(pb, 0); /* padding */
+    if (!pb->seekable)
+        avio_wl32(pb, AVIF_TRUSTCKTYPE | AVIF_ISINTERLEAVED); /* flags */
     else
-        put_le32(pb, AVIF_TRUSTCKTYPE | AVIF_HASINDEX | AVIF_ISINTERLEAVED); /* flags */
-    avi->frames_hdr_all = url_ftell(pb); /* remember this offset to fill later */
-    put_le32(pb, nb_frames); /* nb frames, filled later */
-    put_le32(pb, 0); /* initial frame */
-    put_le32(pb, s->nb_streams); /* nb streams */
-    put_le32(pb, 1024 * 1024); /* suggested buffer size */
+        avio_wl32(pb, AVIF_TRUSTCKTYPE | AVIF_HASINDEX | AVIF_ISINTERLEAVED); /* flags */
+    avi->frames_hdr_all = avio_tell(pb); /* remember this offset to fill later */
+    avio_wl32(pb, nb_frames); /* nb frames, filled later */
+    avio_wl32(pb, 0); /* initial frame */
+    avio_wl32(pb, s->nb_streams); /* nb streams */
+    avio_wl32(pb, 1024 * 1024); /* suggested buffer size */
     if(video_enc){
-        put_le32(pb, video_enc->width);
-        put_le32(pb, video_enc->height);
+        avio_wl32(pb, video_enc->width);
+        avio_wl32(pb, video_enc->height);
     } else {
-        put_le32(pb, 0);
-        put_le32(pb, 0);
+        avio_wl32(pb, 0);
+        avio_wl32(pb, 0);
     }
-    put_le32(pb, 0); /* reserved */
-    put_le32(pb, 0); /* reserved */
-    put_le32(pb, 0); /* reserved */
-    put_le32(pb, 0); /* reserved */
+    avio_wl32(pb, 0); /* reserved */
+    avio_wl32(pb, 0); /* reserved */
+    avio_wl32(pb, 0); /* reserved */
+    avio_wl32(pb, 0); /* reserved */
 
     /* stream list */
     for(i=0;i<n;i++) {
         AVIStream *avist= s->streams[i]->priv_data;
         list2 = ff_start_tag(pb, "LIST");
-        put_tag(pb, "strl");
+        ffio_wfourcc(pb, "strl");
 
         stream = s->streams[i]->codec;
 
@@ -225,47 +232,50 @@ static int avi_write_header(AVFormatContext *s)
         case AVMEDIA_TYPE_SUBTITLE:
             // XSUB subtitles behave like video tracks, other subtitles
             // are not (yet) supported.
-            if (stream->codec_id != CODEC_ID_XSUB) break;
-        case AVMEDIA_TYPE_VIDEO: put_tag(pb, "vids"); break;
-        case AVMEDIA_TYPE_AUDIO: put_tag(pb, "auds"); break;
-//        case AVMEDIA_TYPE_TEXT : put_tag(pb, "txts"); break;
-        case AVMEDIA_TYPE_DATA : put_tag(pb, "dats"); break;
+            if (stream->codec_id != CODEC_ID_XSUB) {
+                av_log(s, AV_LOG_ERROR, "Subtitle streams other than DivX XSUB are not supported by the AVI muxer.\n");
+                return AVERROR_PATCHWELCOME;
+            }
+        case AVMEDIA_TYPE_VIDEO: ffio_wfourcc(pb, "vids"); break;
+        case AVMEDIA_TYPE_AUDIO: ffio_wfourcc(pb, "auds"); break;
+//      case AVMEDIA_TYPE_TEXT : ffio_wfourcc(pb, "txts"); break;
+        case AVMEDIA_TYPE_DATA : ffio_wfourcc(pb, "dats"); break;
         }
         if(stream->codec_type == AVMEDIA_TYPE_VIDEO ||
            stream->codec_id == CODEC_ID_XSUB)
-            put_le32(pb, stream->codec_tag);
+            avio_wl32(pb, stream->codec_tag);
         else
-            put_le32(pb, 1);
-        put_le32(pb, 0); /* flags */
-        put_le16(pb, 0); /* priority */
-        put_le16(pb, 0); /* language */
-        put_le32(pb, 0); /* initial frame */
+            avio_wl32(pb, 1);
+        avio_wl32(pb, 0); /* flags */
+        avio_wl16(pb, 0); /* priority */
+        avio_wl16(pb, 0); /* language */
+        avio_wl32(pb, 0); /* initial frame */
 
         ff_parse_specific_params(stream, &au_byterate, &au_ssize, &au_scale);
 
-        put_le32(pb, au_scale); /* scale */
-        put_le32(pb, au_byterate); /* rate */
+        avio_wl32(pb, au_scale); /* scale */
+        avio_wl32(pb, au_byterate); /* rate */
         av_set_pts_info(s->streams[i], 64, au_scale, au_byterate);
 
-        put_le32(pb, 0); /* start */
-        avist->frames_hdr_strm = url_ftell(pb); /* remember this offset to fill later */
-        if (url_is_streamed(pb))
-            put_le32(pb, AVI_MAX_RIFF_SIZE); /* FIXME: this may be broken, but who cares */
+        avio_wl32(pb, 0); /* start */
+        avist->frames_hdr_strm = avio_tell(pb); /* remember this offset to fill later */
+        if (!pb->seekable)
+            avio_wl32(pb, AVI_MAX_RIFF_SIZE); /* FIXME: this may be broken, but who cares */
         else
-            put_le32(pb, 0); /* length, XXX: filled later */
+            avio_wl32(pb, 0); /* length, XXX: filled later */
 
         /* suggested buffer size */ //FIXME set at the end to largest chunk
         if(stream->codec_type == AVMEDIA_TYPE_VIDEO)
-            put_le32(pb, 1024 * 1024);
+            avio_wl32(pb, 1024 * 1024);
         else if(stream->codec_type == AVMEDIA_TYPE_AUDIO)
-            put_le32(pb, 12 * 1024);
+            avio_wl32(pb, 12 * 1024);
         else
-            put_le32(pb, 0);
-        put_le32(pb, -1); /* quality */
-        put_le32(pb, au_ssize); /* sample size */
-        put_le32(pb, 0);
-        put_le16(pb, stream->width);
-        put_le16(pb, stream->height);
+            avio_wl32(pb, 0);
+        avio_wl32(pb, -1); /* quality */
+        avio_wl32(pb, au_ssize); /* sample size */
+        avio_wl32(pb, 0);
+        avio_wl16(pb, stream->width);
+        avio_wl16(pb, stream->height);
         ff_end_tag(pb, strh);
 
       if(stream->codec_type != AVMEDIA_TYPE_DATA){
@@ -287,18 +297,13 @@ static int avi_write_header(AVFormatContext *s)
             return -1;
         }
         ff_end_tag(pb, strf);
-        if ((t = av_metadata_get(s->streams[i]->metadata, "strn", NULL, 0))) {
-            avi_write_info_tag(s->pb, t->key, t->value);
-            t = NULL;
-        }
-        //FIXME a limitation of metadata conversion system
-        else if ((t = av_metadata_get(s->streams[i]->metadata, "INAM", NULL, 0))) {
+        if ((t = av_metadata_get(s->streams[i]->metadata, "title", NULL, 0))) {
             avi_write_info_tag(s->pb, "strn", t->value);
             t = NULL;
         }
       }
 
-        if (!url_is_streamed(pb)) {
+        if (pb->seekable) {
             unsigned char tag[5];
             int j;
 
@@ -309,16 +314,16 @@ static int avi_write_header(AVFormatContext *s)
              */
             avist->indexes.entry = avist->indexes.ents_allocated = 0;
             avist->indexes.indx_start = ff_start_tag(pb, "JUNK");
-            put_le16(pb, 4);        /* wLongsPerEntry */
-            put_byte(pb, 0);        /* bIndexSubType (0 == frame index) */
-            put_byte(pb, 0);        /* bIndexType (0 == AVI_INDEX_OF_INDEXES) */
-            put_le32(pb, 0);        /* nEntriesInUse (will fill out later on) */
-            put_tag(pb, avi_stream2fourcc(&tag[0], i, stream->codec_type));
+            avio_wl16(pb, 4);        /* wLongsPerEntry */
+            avio_w8(pb, 0);          /* bIndexSubType (0 == frame index) */
+            avio_w8(pb, 0);          /* bIndexType (0 == AVI_INDEX_OF_INDEXES) */
+            avio_wl32(pb, 0);        /* nEntriesInUse (will fill out later on) */
+            ffio_wfourcc(pb, avi_stream2fourcc(tag, i, stream->codec_type));
                                     /* dwChunkId */
-            put_le64(pb, 0);        /* dwReserved[3]
-            put_le32(pb, 0);           Must be 0.    */
+            avio_wl64(pb, 0);        /* dwReserved[3]
+            avio_wl32(pb, 0);           Must be 0.    */
             for (j=0; j < AVI_MASTER_INDEX_SIZE * 2; j++)
-                 put_le64(pb, 0);
+                 avio_wl64(pb, 0);
             ff_end_tag(pb, avist->indexes.indx_start);
         }
 
@@ -331,47 +336,48 @@ static int avi_write_header(AVFormatContext *s)
             int num, den;
             av_reduce(&num, &den, dar.num, dar.den, 0xFFFF);
 
-            put_le32(pb, 0); //video format  = unknown
-            put_le32(pb, 0); //video standard= unknown
-            put_le32(pb, lrintf(1.0/av_q2d(stream->time_base)));
-            put_le32(pb, stream->width );
-            put_le32(pb, stream->height);
-            put_le16(pb, den);
-            put_le16(pb, num);
-            put_le32(pb, stream->width );
-            put_le32(pb, stream->height);
-            put_le32(pb, 1); //progressive FIXME
-
-            put_le32(pb, stream->height);
-            put_le32(pb, stream->width );
-            put_le32(pb, stream->height);
-            put_le32(pb, stream->width );
-            put_le32(pb, 0);
-            put_le32(pb, 0);
-
-            put_le32(pb, 0);
-            put_le32(pb, 0);
+            avio_wl32(pb, 0); //video format  = unknown
+            avio_wl32(pb, 0); //video standard= unknown
+            avio_wl32(pb, lrintf(1.0/av_q2d(stream->time_base)));
+            avio_wl32(pb, stream->width );
+            avio_wl32(pb, stream->height);
+            avio_wl16(pb, den);
+            avio_wl16(pb, num);
+            avio_wl32(pb, stream->width );
+            avio_wl32(pb, stream->height);
+            avio_wl32(pb, 1); //progressive FIXME
+
+            avio_wl32(pb, stream->height);
+            avio_wl32(pb, stream->width );
+            avio_wl32(pb, stream->height);
+            avio_wl32(pb, stream->width );
+            avio_wl32(pb, 0);
+            avio_wl32(pb, 0);
+
+            avio_wl32(pb, 0);
+            avio_wl32(pb, 0);
             ff_end_tag(pb, vprp);
         }
 
         ff_end_tag(pb, list2);
     }
 
-    if (!url_is_streamed(pb)) {
+    if (pb->seekable) {
         /* AVI could become an OpenDML one, if it grows beyond 2Gb range */
         avi->odml_list = ff_start_tag(pb, "JUNK");
-        put_tag(pb, "odml");
-        put_tag(pb, "dmlh");
-        put_le32(pb, 248);
+        ffio_wfourcc(pb, "odml");
+        ffio_wfourcc(pb, "dmlh");
+        avio_wl32(pb, 248);
         for (i = 0; i < 248; i+= 4)
-             put_le32(pb, 0);
+             avio_wl32(pb, 0);
         ff_end_tag(pb, avi->odml_list);
     }
 
     ff_end_tag(pb, list1);
 
     list2 = ff_start_tag(pb, "LIST");
-    put_tag(pb, "INFO");
+    ffio_wfourcc(pb, "INFO");
+    ff_metadata_conv(&s->metadata, ff_avi_metadata_conv, NULL);
     for (i = 0; *ff_avi_tags[i]; i++) {
         if ((t = av_metadata_get(s->metadata, ff_avi_tags[i], NULL, AV_METADATA_MATCH_CASE)))
             avi_write_info_tag(s->pb, t->key, t->value);
@@ -381,26 +387,26 @@ static int avi_write_header(AVFormatContext *s)
     /* some padding for easier tag editing */
     list2 = ff_start_tag(pb, "JUNK");
     for (i = 0; i < 1016; i += 4)
-        put_le32(pb, 0);
+        avio_wl32(pb, 0);
     ff_end_tag(pb, list2);
 
     avi->movi_list = ff_start_tag(pb, "LIST");
-    put_tag(pb, "movi");
+    ffio_wfourcc(pb, "movi");
 
-    put_flush_packet(pb);
+    avio_flush(pb);
 
     return 0;
 }
 
 static int avi_write_ix(AVFormatContext *s)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVIContext *avi = s->priv_data;
     char tag[5];
     char ix_tag[] = "ix00";
     int i, j;
 
-    assert(!url_is_streamed(pb));
+    assert(pb->seekable);
 
     if (avi->riff_id > AVI_MASTER_INDEX_SIZE)
         return -1;
@@ -409,56 +415,56 @@ static int avi_write_ix(AVFormatContext *s)
         AVIStream *avist= s->streams[i]->priv_data;
          int64_t ix, pos;
 
-         avi_stream2fourcc(&tag[0], i, s->streams[i]->codec->codec_type);
+         avi_stream2fourcc(tag, i, s->streams[i]->codec->codec_type);
          ix_tag[3] = '0' + i;
 
          /* Writing AVI OpenDML leaf index chunk */
-         ix = url_ftell(pb);
-         put_tag(pb, &ix_tag[0]);     /* ix?? */
-         put_le32(pb, avist->indexes.entry * 8 + 24);
+         ix = avio_tell(pb);
+         ffio_wfourcc(pb, ix_tag);     /* ix?? */
+         avio_wl32(pb, avist->indexes.entry * 8 + 24);
                                       /* chunk size */
-         put_le16(pb, 2);             /* wLongsPerEntry */
-         put_byte(pb, 0);             /* bIndexSubType (0 == frame index) */
-         put_byte(pb, 1);             /* bIndexType (1 == AVI_INDEX_OF_CHUNKS) */
-         put_le32(pb, avist->indexes.entry);
+         avio_wl16(pb, 2);             /* wLongsPerEntry */
+         avio_w8(pb, 0);             /* bIndexSubType (0 == frame index) */
+         avio_w8(pb, 1);             /* bIndexType (1 == AVI_INDEX_OF_CHUNKS) */
+         avio_wl32(pb, avist->indexes.entry);
                                       /* nEntriesInUse */
-         put_tag(pb, &tag[0]);        /* dwChunkId */
-         put_le64(pb, avi->movi_list);/* qwBaseOffset */
-         put_le32(pb, 0);             /* dwReserved_3 (must be 0) */
+         ffio_wfourcc(pb, tag);        /* dwChunkId */
+         avio_wl64(pb, avi->movi_list);/* qwBaseOffset */
+         avio_wl32(pb, 0);             /* dwReserved_3 (must be 0) */
 
          for (j=0; j<avist->indexes.entry; j++) {
              AVIIentry* ie = avi_get_ientry(&avist->indexes, j);
-             put_le32(pb, ie->pos + 8);
-             put_le32(pb, ((uint32_t)ie->len & ~0x80000000) |
+             avio_wl32(pb, ie->pos + 8);
+             avio_wl32(pb, ((uint32_t)ie->len & ~0x80000000) |
                           (ie->flags & 0x10 ? 0 : 0x80000000));
          }
-         put_flush_packet(pb);
-         pos = url_ftell(pb);
+         avio_flush(pb);
+         pos = avio_tell(pb);
 
          /* Updating one entry in the AVI OpenDML master index */
-         url_fseek(pb, avist->indexes.indx_start - 8, SEEK_SET);
-         put_tag(pb, "indx");                 /* enabling this entry */
-         url_fskip(pb, 8);
-         put_le32(pb, avi->riff_id);          /* nEntriesInUse */
-         url_fskip(pb, 16*avi->riff_id);
-         put_le64(pb, ix);                    /* qwOffset */
-         put_le32(pb, pos - ix);              /* dwSize */
-         put_le32(pb, avist->indexes.entry); /* dwDuration */
-
-         url_fseek(pb, pos, SEEK_SET);
+         avio_seek(pb, avist->indexes.indx_start - 8, SEEK_SET);
+         ffio_wfourcc(pb, "indx");            /* enabling this entry */
+         avio_skip(pb, 8);
+         avio_wl32(pb, avi->riff_id);         /* nEntriesInUse */
+         avio_skip(pb, 16*avi->riff_id);
+         avio_wl64(pb, ix);                   /* qwOffset */
+         avio_wl32(pb, pos - ix);             /* dwSize */
+         avio_wl32(pb, avist->indexes.entry); /* dwDuration */
+
+         avio_seek(pb, pos, SEEK_SET);
     }
     return 0;
 }
 
 static int avi_write_idx1(AVFormatContext *s)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVIContext *avi = s->priv_data;
     int64_t idx_chunk;
     int i;
     char tag[5];
 
-    if (!url_is_streamed(pb)) {
+    if (pb->seekable) {
         AVIStream *avist;
         AVIIentry* ie = 0, *tie;
         int empty, stream_id = -1;
@@ -485,12 +491,12 @@ static int avi_write_idx1(AVFormatContext *s)
             }
             if (!empty) {
                 avist= s->streams[stream_id]->priv_data;
-                avi_stream2fourcc(&tag[0], stream_id,
+                avi_stream2fourcc(tag, stream_id,
                                   s->streams[stream_id]->codec->codec_type);
-                put_tag(pb, &tag[0]);
-                put_le32(pb, ie->flags);
-                put_le32(pb, ie->pos);
-                put_le32(pb, ie->len);
+                ffio_wfourcc(pb, tag);
+                avio_wl32(pb, ie->flags);
+                avio_wl32(pb, ie->pos);
+                avio_wl32(pb, ie->len);
                 avist->entry++;
             }
         } while (!empty);
@@ -504,7 +510,7 @@ static int avi_write_idx1(AVFormatContext *s)
 static int avi_write_packet(AVFormatContext *s, AVPacket *pkt)
 {
     AVIContext *avi = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     unsigned char tag[5];
     unsigned int flags=0;
     const int stream_index= pkt->stream_index;
@@ -526,8 +532,8 @@ static int avi_write_packet(AVFormatContext *s, AVPacket *pkt)
     avist->packet_count++;
 
     // Make sure to put an OpenDML chunk when the file size exceeds the limits
-    if (!url_is_streamed(pb) &&
-        (url_ftell(pb) - avi->riff_start > AVI_MAX_RIFF_SIZE)) {
+    if (pb->seekable &&
+        (avio_tell(pb) - avi->riff_start > AVI_MAX_RIFF_SIZE)) {
 
         avi_write_ix(s);
         ff_end_tag(pb, avi->movi_list);
@@ -539,14 +545,14 @@ static int avi_write_packet(AVFormatContext *s, AVPacket *pkt)
         avi->movi_list = avi_start_new_riff(s, pb, "AVIX", "movi");
     }
 
-    avi_stream2fourcc(&tag[0], stream_index, enc->codec_type);
+    avi_stream2fourcc(tag, stream_index, enc->codec_type);
     if(pkt->flags&AV_PKT_FLAG_KEY)
         flags = 0x10;
     if (enc->codec_type == AVMEDIA_TYPE_AUDIO) {
        avist->audio_strm_length += size;
     }
 
-    if (!url_is_streamed(s->pb)) {
+    if (s->pb->seekable) {
         AVIIndex* idx = &avist->indexes;
         int cl = idx->entry / AVI_INDEX_CLUSTER_SIZE;
         int id = idx->entry % AVI_INDEX_CLUSTER_SIZE;
@@ -561,30 +567,30 @@ static int avi_write_packet(AVFormatContext *s, AVPacket *pkt)
         }
 
         idx->cluster[cl][id].flags = flags;
-        idx->cluster[cl][id].pos = url_ftell(pb) - avi->movi_list;
+        idx->cluster[cl][id].pos = avio_tell(pb) - avi->movi_list;
         idx->cluster[cl][id].len = size;
         idx->entry++;
     }
 
-    put_buffer(pb, tag, 4);
-    put_le32(pb, size);
-    put_buffer(pb, pkt->data, size);
+    avio_write(pb, tag, 4);
+    avio_wl32(pb, size);
+    avio_write(pb, pkt->data, size);
     if (size & 1)
-        put_byte(pb, 0);
+        avio_w8(pb, 0);
 
-    put_flush_packet(pb);
+    avio_flush(pb);
     return 0;
 }
 
 static int avi_write_trailer(AVFormatContext *s)
 {
     AVIContext *avi = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int res = 0;
     int i, j, n, nb_frames;
     int64_t file_size;
 
-    if (!url_is_streamed(pb)){
+    if (pb->seekable){
         if (avi->riff_id == 1) {
             ff_end_tag(pb, avi->movi_list);
             res = avi_write_idx1(s);
@@ -594,10 +600,10 @@ static int avi_write_trailer(AVFormatContext *s)
             ff_end_tag(pb, avi->movi_list);
             ff_end_tag(pb, avi->riff_start);
 
-            file_size = url_ftell(pb);
-            url_fseek(pb, avi->odml_list - 8, SEEK_SET);
-            put_tag(pb, "LIST"); /* Making this AVI OpenDML one */
-            url_fskip(pb, 16);
+            file_size = avio_tell(pb);
+            avio_seek(pb, avi->odml_list - 8, SEEK_SET);
+            ffio_wfourcc(pb, "LIST"); /* Making this AVI OpenDML one */
+            avio_skip(pb, 16);
 
             for (n=nb_frames=0;n<s->nb_streams;n++) {
                 AVCodecContext *stream = s->streams[n]->codec;
@@ -612,13 +618,13 @@ static int avi_write_trailer(AVFormatContext *s)
                     }
                 }
             }
-            put_le32(pb, nb_frames);
-            url_fseek(pb, file_size, SEEK_SET);
+            avio_wl32(pb, nb_frames);
+            avio_seek(pb, file_size, SEEK_SET);
 
             avi_write_counters(s, avi->riff_id);
         }
     }
-    put_flush_packet(pb);
+    avio_flush(pb);
 
     for (i=0; i<s->nb_streams; i++) {
          AVIStream *avist= s->streams[i]->priv_data;
@@ -631,7 +637,7 @@ static int avi_write_trailer(AVFormatContext *s)
     return res;
 }
 
-AVOutputFormat avi_muxer = {
+AVOutputFormat ff_avi_muxer = {
     "avi",
     NULL_IF_CONFIG_SMALL("AVI format"),
     "video/x-msvideo",
@@ -644,5 +650,4 @@ AVOutputFormat avi_muxer = {
     avi_write_trailer,
     .codec_tag= (const AVCodecTag* const []){ff_codec_bmp_tags, ff_codec_wav_tags, 0},
     .flags= AVFMT_VARIABLE_FPS,
-    .metadata_conv = ff_avi_metadata_conv,
 };
diff --git a/libavformat/avio.c b/libavformat/avio.c
index 48399d0..cb923a7 100644
--- a/libavformat/avio.c
+++ b/libavformat/avio.c
@@ -2,20 +2,20 @@
  * Unbuffered io for ffmpeg system
  * Copyright (c) 2001 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -23,14 +23,15 @@
 #define _XOPEN_SOURCE 600
 #include <unistd.h>
 #include "libavutil/avstring.h"
-#include "libavcodec/opt.h"
+#include "libavutil/opt.h"
 #include "os_support.h"
 #include "avformat.h"
 #if CONFIG_NETWORK
 #include "network.h"
 #endif
+#include "url.h"
 
-#if LIBAVFORMAT_VERSION_MAJOR >= 53
+#if FF_API_URL_CLASS
 /** @name Logging context. */
 /*@{*/
 static const char *urlcontext_to_name(void *ptr)
@@ -48,17 +49,34 @@ static const AVClass urlcontext_class =
 static int default_interrupt_cb(void);
 
 URLProtocol *first_protocol = NULL;
-URLInterruptCB *url_interrupt_cb = default_interrupt_cb;
+int (*url_interrupt_cb)(void) = default_interrupt_cb;
 
+#if FF_API_OLD_AVIO
 URLProtocol *av_protocol_next(URLProtocol *p)
 {
     if(p) return p->next;
     else  return first_protocol;
 }
+#endif
 
-int av_register_protocol(URLProtocol *protocol)
+const char *avio_enum_protocols(void **opaque, int output)
+{
+    URLProtocol **p = opaque;
+    *p = *p ? (*p)->next : first_protocol;
+    if (!*p) return NULL;
+    if ((output && (*p)->url_write) || (!output && (*p)->url_read))
+        return (*p)->name;
+    return avio_enum_protocols(opaque, output);
+}
+
+int ffurl_register_protocol(URLProtocol *protocol, int size)
 {
     URLProtocol **p;
+    if (size < sizeof(URLProtocol)) {
+        URLProtocol* temp = av_mallocz(sizeof(URLProtocol));
+        memcpy(temp, protocol, size);
+        protocol = temp;
+    }
     p = &first_protocol;
     while (*p != NULL) p = &(*p)->next;
     *p = protocol;
@@ -66,15 +84,31 @@ int av_register_protocol(URLProtocol *protocol)
     return 0;
 }
 
-#if LIBAVFORMAT_VERSION_MAJOR < 53
+#if FF_API_REGISTER_PROTOCOL
+/* The layout of URLProtocol as of when major was bumped to 52 */
+struct URLProtocol_compat {
+    const char *name;
+    int (*url_open)(URLContext *h, const char *filename, int flags);
+    int (*url_read)(URLContext *h, unsigned char *buf, int size);
+    int (*url_write)(URLContext *h, unsigned char *buf, int size);
+    int64_t (*url_seek)(URLContext *h, int64_t pos, int whence);
+    int (*url_close)(URLContext *h);
+    struct URLProtocol *next;
+};
+
+int av_register_protocol(URLProtocol *protocol)
+{
+    return ffurl_register_protocol(protocol, sizeof(struct URLProtocol_compat));
+}
+
 int register_protocol(URLProtocol *protocol)
 {
-    return av_register_protocol(protocol);
+    return ffurl_register_protocol(protocol, sizeof(struct URLProtocol_compat));
 }
 #endif
 
-int url_open_protocol (URLContext **puc, struct URLProtocol *up,
-                       const char *filename, int flags)
+static int url_alloc_for_protocol (URLContext **puc, struct URLProtocol *up,
+                                   const char *filename, int flags)
 {
     URLContext *uc;
     int err;
@@ -88,7 +122,7 @@ int url_open_protocol (URLContext **puc, struct URLProtocol *up,
         err = AVERROR(ENOMEM);
         goto fail;
     }
-#if LIBAVFORMAT_VERSION_MAJOR >= 53
+#if FF_API_URL_CLASS
     uc->av_class = &urlcontext_class;
 #endif
     uc->filename = (char *) &uc[1];
@@ -97,17 +131,14 @@ int url_open_protocol (URLContext **puc, struct URLProtocol *up,
     uc->flags = flags;
     uc->is_streamed = 0; /* default = not streamed */
     uc->max_packet_size = 0; /* default: stream file */
-    err = up->url_open(uc, filename, flags);
-    if (err < 0) {
-        av_free(uc);
-        goto fail;
+    if (up->priv_data_size) {
+        uc->priv_data = av_mallocz(up->priv_data_size);
+        if (up->priv_data_class) {
+            *(const AVClass**)uc->priv_data = up->priv_data_class;
+            av_opt_set_defaults(uc->priv_data);
+        }
     }
 
-    //We must be careful here as url_seek() could be slow, for example for http
-    if(   (flags & (URL_WRONLY | URL_RDWR))
-       || !strcmp(up->name, "file"))
-        if(!uc->is_streamed && url_seek(uc, 0, SEEK_SET) < 0)
-            uc->is_streamed= 1;
     *puc = uc;
     return 0;
  fail:
@@ -118,57 +149,154 @@ int url_open_protocol (URLContext **puc, struct URLProtocol *up,
     return err;
 }
 
+int ffurl_connect(URLContext* uc)
+{
+    int err = uc->prot->url_open(uc, uc->filename, uc->flags);
+    if (err)
+        return err;
+    uc->is_connected = 1;
+    //We must be careful here as ffurl_seek() could be slow, for example for http
+    if(   (uc->flags & (AVIO_WRONLY | AVIO_RDWR))
+       || !strcmp(uc->prot->name, "file"))
+        if(!uc->is_streamed && ffurl_seek(uc, 0, SEEK_SET) < 0)
+            uc->is_streamed= 1;
+    return 0;
+}
+
+#if FF_API_OLD_AVIO
+int url_open_protocol (URLContext **puc, struct URLProtocol *up,
+                       const char *filename, int flags)
+{
+    int ret;
+
+    ret = url_alloc_for_protocol(puc, up, filename, flags);
+    if (ret)
+        goto fail;
+    ret = ffurl_connect(*puc);
+    if (!ret)
+        return 0;
+ fail:
+    ffurl_close(*puc);
+    *puc = NULL;
+    return ret;
+}
+int url_alloc(URLContext **puc, const char *filename, int flags)
+{
+    return ffurl_alloc(puc, filename, flags);
+}
+int url_connect(URLContext* uc)
+{
+    return ffurl_connect(uc);
+}
 int url_open(URLContext **puc, const char *filename, int flags)
 {
+    return ffurl_open(puc, filename, flags);
+}
+int url_read(URLContext *h, unsigned char *buf, int size)
+{
+    return ffurl_read(h, buf, size);
+}
+int url_read_complete(URLContext *h, unsigned char *buf, int size)
+{
+    return ffurl_read_complete(h, buf, size);
+}
+int url_write(URLContext *h, const unsigned char *buf, int size)
+{
+    return ffurl_write(h, buf, size);
+}
+int64_t url_seek(URLContext *h, int64_t pos, int whence)
+{
+    return ffurl_seek(h, pos, whence);
+}
+int url_close(URLContext *h)
+{
+    return ffurl_close(h);
+}
+int64_t url_filesize(URLContext *h)
+{
+    return ffurl_size(h);
+}
+int url_get_file_handle(URLContext *h)
+{
+    return ffurl_get_file_handle(h);
+}
+int url_get_max_packet_size(URLContext *h)
+{
+    return h->max_packet_size;
+}
+void url_get_filename(URLContext *h, char *buf, int buf_size)
+{
+    av_strlcpy(buf, h->filename, buf_size);
+}
+void url_set_interrupt_cb(URLInterruptCB *interrupt_cb)
+{
+    avio_set_interrupt_cb(interrupt_cb);
+}
+int av_register_protocol2(URLProtocol *protocol, int size)
+{
+    return ffurl_register_protocol(protocol, size);
+}
+#endif
+
+#define URL_SCHEME_CHARS                        \
+    "abcdefghijklmnopqrstuvwxyz"                \
+    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"                \
+    "0123456789+-."
+
+int ffurl_alloc(URLContext **puc, const char *filename, int flags)
+{
     URLProtocol *up;
-    const char *p;
-    char proto_str[128], *q;
-
-    p = filename;
-    q = proto_str;
-    while (*p != '\0' && *p != ':') {
-        /* protocols can only contain alphabetic chars */
-        if (!isalpha(*p))
-            goto file_proto;
-        if ((q - proto_str) < sizeof(proto_str) - 1)
-            *q++ = *p;
-        p++;
-    }
-    /* if the protocol has length 1, we consider it is a dos drive */
-    if (*p == '\0' || is_dos_path(filename)) {
-    file_proto:
+    char proto_str[128], proto_nested[128], *ptr;
+    size_t proto_len = strspn(filename, URL_SCHEME_CHARS);
+
+    if (filename[proto_len] != ':' || is_dos_path(filename))
         strcpy(proto_str, "file");
-    } else {
-        *q = '\0';
-    }
+    else
+        av_strlcpy(proto_str, filename, FFMIN(proto_len+1, sizeof(proto_str)));
+
+    av_strlcpy(proto_nested, proto_str, sizeof(proto_nested));
+    if ((ptr = strchr(proto_nested, '+')))
+        *ptr = '\0';
 
     up = first_protocol;
     while (up != NULL) {
         if (!strcmp(proto_str, up->name))
-            return url_open_protocol (puc, up, filename, flags);
+            return url_alloc_for_protocol (puc, up, filename, flags);
+        if (up->flags & URL_PROTOCOL_FLAG_NESTED_SCHEME &&
+            !strcmp(proto_nested, up->name))
+            return url_alloc_for_protocol (puc, up, filename, flags);
         up = up->next;
     }
     *puc = NULL;
     return AVERROR(ENOENT);
 }
 
-int url_read(URLContext *h, unsigned char *buf, int size)
+int ffurl_open(URLContext **puc, const char *filename, int flags)
 {
-    int ret;
-    if (h->flags & URL_WRONLY)
-        return AVERROR(EIO);
-    ret = h->prot->url_read(h, buf, size);
+    int ret = ffurl_alloc(puc, filename, flags);
+    if (ret)
+        return ret;
+    ret = ffurl_connect(*puc);
+    if (!ret)
+        return 0;
+    ffurl_close(*puc);
+    *puc = NULL;
     return ret;
 }
 
-int url_read_complete(URLContext *h, unsigned char *buf, int size)
+static inline int retry_transfer_wrapper(URLContext *h, unsigned char *buf, int size, int size_min,
+                                         int (*transfer_func)(URLContext *h, unsigned char *buf, int size))
 {
     int ret, len;
     int fast_retries = 5;
 
     len = 0;
-    while (len < size) {
-        ret = url_read(h, buf+len, size-len);
+    while (len < size_min) {
+        ret = transfer_func(h, buf+len, size-len);
+        if (ret == AVERROR(EINTR))
+            continue;
+        if (h->flags & AVIO_FLAG_NONBLOCK)
+            return ret;
         if (ret == AVERROR(EAGAIN)) {
             ret = 0;
             if (fast_retries)
@@ -180,23 +308,38 @@ int url_read_complete(URLContext *h, unsigned char *buf, int size)
         if (ret)
            fast_retries = FFMAX(fast_retries, 2);
         len += ret;
+        if (url_interrupt_cb())
+            return AVERROR_EXIT;
     }
     return len;
 }
 
-int url_write(URLContext *h, unsigned char *buf, int size)
+int ffurl_read(URLContext *h, unsigned char *buf, int size)
 {
-    int ret;
-    if (!(h->flags & (URL_WRONLY | URL_RDWR)))
+    if (h->flags & AVIO_WRONLY)
+        return AVERROR(EIO);
+    return retry_transfer_wrapper(h, buf, size, 1, h->prot->url_read);
+}
+
+int ffurl_read_complete(URLContext *h, unsigned char *buf, int size)
+{
+    if (h->flags & AVIO_WRONLY)
+        return AVERROR(EIO);
+    return retry_transfer_wrapper(h, buf, size, size, h->prot->url_read);
+}
+
+int ffurl_write(URLContext *h, const unsigned char *buf, int size)
+{
+    if (!(h->flags & (AVIO_WRONLY | AVIO_RDWR)))
         return AVERROR(EIO);
     /* avoid sending too big packets */
     if (h->max_packet_size && size > h->max_packet_size)
         return AVERROR(EIO);
-    ret = h->prot->url_write(h, buf, size);
-    return ret;
+
+    return retry_transfer_wrapper(h, buf, size, size, h->prot->url_write);
 }
 
-int64_t url_seek(URLContext *h, int64_t pos, int whence)
+int64_t ffurl_seek(URLContext *h, int64_t pos, int whence)
 {
     int64_t ret;
 
@@ -206,74 +349,87 @@ int64_t url_seek(URLContext *h, int64_t pos, int whence)
     return ret;
 }
 
-int url_close(URLContext *h)
+int ffurl_close(URLContext *h)
 {
     int ret = 0;
-    if (!h) return 0; /* can happen when url_open fails */
+    if (!h) return 0; /* can happen when ffurl_open fails */
 
-    if (h->prot->url_close)
+    if (h->is_connected && h->prot->url_close)
         ret = h->prot->url_close(h);
 #if CONFIG_NETWORK
     ff_network_close();
 #endif
+    if (h->prot->priv_data_size)
+        av_free(h->priv_data);
     av_free(h);
     return ret;
 }
 
+#if FF_API_OLD_AVIO
 int url_exist(const char *filename)
 {
     URLContext *h;
-    if (url_open(&h, filename, URL_RDONLY) < 0)
+    if (ffurl_open(&h, filename, AVIO_RDONLY) < 0)
         return 0;
-    url_close(h);
+    ffurl_close(h);
     return 1;
 }
+#endif
 
-int64_t url_filesize(URLContext *h)
+int avio_check(const char *url, int flags)
+{
+    URLContext *h;
+    int ret = ffurl_alloc(&h, url, flags);
+    if (ret)
+        return ret;
+
+    if (h->prot->url_check) {
+        ret = h->prot->url_check(h, flags);
+    } else {
+        ret = ffurl_connect(h);
+        if (ret >= 0)
+            ret = flags;
+    }
+
+    ffurl_close(h);
+    return ret;
+}
+
+int64_t ffurl_size(URLContext *h)
 {
     int64_t pos, size;
 
-    size= url_seek(h, 0, AVSEEK_SIZE);
+    size= ffurl_seek(h, 0, AVSEEK_SIZE);
     if(size<0){
-        pos = url_seek(h, 0, SEEK_CUR);
-        if ((size = url_seek(h, -1, SEEK_END)) < 0)
+        pos = ffurl_seek(h, 0, SEEK_CUR);
+        if ((size = ffurl_seek(h, -1, SEEK_END)) < 0)
             return size;
         size++;
-        url_seek(h, pos, SEEK_SET);
+        ffurl_seek(h, pos, SEEK_SET);
     }
     return size;
 }
 
-int url_get_file_handle(URLContext *h)
+int ffurl_get_file_handle(URLContext *h)
 {
     if (!h->prot->url_get_file_handle)
         return -1;
     return h->prot->url_get_file_handle(h);
 }
 
-int url_get_max_packet_size(URLContext *h)
-{
-    return h->max_packet_size;
-}
-
-void url_get_filename(URLContext *h, char *buf, int buf_size)
-{
-    av_strlcpy(buf, h->filename, buf_size);
-}
-
-
 static int default_interrupt_cb(void)
 {
     return 0;
 }
 
-void url_set_interrupt_cb(URLInterruptCB *interrupt_cb)
+void avio_set_interrupt_cb(int (*interrupt_cb)(void))
 {
     if (!interrupt_cb)
         interrupt_cb = default_interrupt_cb;
     url_interrupt_cb = interrupt_cb;
 }
 
+#if FF_API_OLD_AVIO
 int av_url_read_pause(URLContext *h, int pause)
 {
     if (!h->prot->url_read_pause)
@@ -288,3 +444,4 @@ int64_t av_url_read_seek(URLContext *h,
         return AVERROR(ENOSYS);
     return h->prot->url_read_seek(h, stream_index, timestamp, flags);
 }
+#endif
diff --git a/libavformat/avio.h b/libavformat/avio.h
index 9ffe935..f4674a4 100644
--- a/libavformat/avio.h
+++ b/libavformat/avio.h
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2001 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #ifndef AVFORMAT_AVIO_H
@@ -22,27 +22,86 @@
 
 /**
  * @file
- * unbuffered I/O operations
- *
- * @warning This file has to be considered an internal but installed
- * header, so it should not be directly included in your projects.
+ * Buffered I/O operations
  */
 
 #include <stdint.h>
 
 #include "libavutil/common.h"
+#include "libavutil/log.h"
+
+#include "libavformat/version.h"
+
+
+#define AVIO_SEEKABLE_NORMAL 0x0001 /**< Seeking works like for a local file */
+
+/**
+ * Bytestream IO Context.
+ * New fields can be added to the end with minor version bumps.
+ * Removal, reordering and changes to existing fields require a major
+ * version bump.
+ * sizeof(AVIOContext) must not be used outside libav*.
+ *
+ * @note None of the function pointers in AVIOContext should be called
+ *       directly, they should only be set by the client application
+ *       when implementing custom I/O. Normally these are set to the
+ *       function pointers specified in avio_alloc_context()
+ */
+typedef struct {
+    unsigned char *buffer;  /**< Start of the buffer. */
+    int buffer_size;        /**< Maximum buffer size */
+    unsigned char *buf_ptr; /**< Current position in the buffer */
+    unsigned char *buf_end; /**< End of the data, may be less than
+                                 buffer+buffer_size if the read function returned
+                                 less data than requested, e.g. for streams where
+                                 no more data has been received yet. */
+    void *opaque;           /**< A private pointer, passed to the read/write/seek/...
+                                 functions. */
+    int (*read_packet)(void *opaque, uint8_t *buf, int buf_size);
+    int (*write_packet)(void *opaque, uint8_t *buf, int buf_size);
+    int64_t (*seek)(void *opaque, int64_t offset, int whence);
+    int64_t pos;            /**< position in the file of the current buffer */
+    int must_flush;         /**< true if the next seek should flush */
+    int eof_reached;        /**< true if eof reached */
+    int write_flag;         /**< true if open for writing */
+#if FF_API_OLD_AVIO
+    attribute_deprecated int is_streamed;
+#endif
+    int max_packet_size;
+    unsigned long checksum;
+    unsigned char *checksum_ptr;
+    unsigned long (*update_checksum)(unsigned long checksum, const uint8_t *buf, unsigned int size);
+    int error;              /**< contains the error code or 0 if no error happened */
+    /**
+     * Pause or resume playback for network streaming protocols - e.g. MMS.
+     */
+    int (*read_pause)(void *opaque, int pause);
+    /**
+     * Seek to a given timestamp in stream with the specified stream_index.
+     * Needed for some network streaming protocols which don't support seeking
+     * to byte position.
+     */
+    int64_t (*read_seek)(void *opaque, int stream_index,
+                         int64_t timestamp, int flags);
+    /**
+     * A combination of AVIO_SEEKABLE_ flags or 0 when the stream is not seekable.
+     */
+    int seekable;
+} AVIOContext;
 
 /* unbuffered I/O */
 
+#if FF_API_OLD_AVIO
 /**
  * URL Context.
  * New fields can be added to the end with minor version bumps.
  * Removal, reordering and changes to existing fields require a major
  * version bump.
  * sizeof(URLContext) must not be used outside libav*.
+ * @deprecated This struct will be made private
  */
 typedef struct URLContext {
-#if LIBAVFORMAT_VERSION_MAJOR >= 53
+#if FF_API_URL_CLASS
     const AVClass *av_class; ///< information for av_log(). Set by url_open().
 #endif
     struct URLProtocol *prot;
@@ -51,253 +110,302 @@ typedef struct URLContext {
     int max_packet_size;  /**< if non zero, the stream is packetized with this max packet size */
     void *priv_data;
     char *filename; /**< specified URL */
+    int is_connected;
 } URLContext;
 
+#define URL_PROTOCOL_FLAG_NESTED_SCHEME 1 /*< The protocol name can be the first part of a nested protocol scheme */
+
+/**
+ * @deprecated This struct is to be made private. Use the higher-level
+ *             AVIOContext-based API instead.
+ */
+typedef struct URLProtocol {
+    const char *name;
+    int (*url_open)(URLContext *h, const char *url, int flags);
+    int (*url_read)(URLContext *h, unsigned char *buf, int size);
+    int (*url_write)(URLContext *h, const unsigned char *buf, int size);
+    int64_t (*url_seek)(URLContext *h, int64_t pos, int whence);
+    int (*url_close)(URLContext *h);
+    struct URLProtocol *next;
+    int (*url_read_pause)(URLContext *h, int pause);
+    int64_t (*url_read_seek)(URLContext *h, int stream_index,
+                             int64_t timestamp, int flags);
+    int (*url_get_file_handle)(URLContext *h);
+    int priv_data_size;
+    const AVClass *priv_data_class;
+    int flags;
+    int (*url_check)(URLContext *h, int mask);
+} URLProtocol;
+
 typedef struct URLPollEntry {
     URLContext *handle;
     int events;
     int revents;
 } URLPollEntry;
 
-#define URL_RDONLY 0
-#define URL_WRONLY 1
-#define URL_RDWR   2
-
-typedef int URLInterruptCB(void);
+/* not implemented */
+attribute_deprecated int url_poll(URLPollEntry *poll_table, int n, int timeout);
 
 /**
- * Creates an URLContext for accessing to the resource indicated by
- * url, and opens it using the URLProtocol up.
- *
- * @param puc pointer to the location where, in case of success, the
- * function puts the pointer to the created URLContext
- * @param flags flags which control how the resource indicated by url
- * is to be opened
- * @return 0 in case of success, a negative value corresponding to an
- * AVERROR code in case of failure
+ * @defgroup open_modes URL open modes
+ * The flags argument to url_open and cosins must be one of the following
+ * constants, optionally ORed with other flags.
+ * @{
  */
-int url_open_protocol (URLContext **puc, struct URLProtocol *up,
-                       const char *url, int flags);
-
+#define URL_RDONLY 0  /**< read-only */
+#define URL_WRONLY 1  /**< write-only */
+#define URL_RDWR   2  /**< read-write */
 /**
- * Creates an URLContext for accessing to the resource indicated by
- * url, and opens it.
- *
- * @param puc pointer to the location where, in case of success, the
- * function puts the pointer to the created URLContext
- * @param flags flags which control how the resource indicated by url
- * is to be opened
- * @return 0 in case of success, a negative value corresponding to an
- * AVERROR code in case of failure
+ * @}
  */
-int url_open(URLContext **h, const char *url, int flags);
 
 /**
- * Reads up to size bytes from the resource accessed by h, and stores
- * the read bytes in buf.
- *
- * @return The number of bytes actually read, or a negative value
- * corresponding to an AVERROR code in case of error. A value of zero
- * indicates that it is not possible to read more from the accessed
- * resource (except if the value of the size argument is also zero).
+ * Use non-blocking mode.
+ * If this flag is set, operations on the context will return
+ * AVERROR(EAGAIN) if they can not be performed immediately.
+ * If this flag is not set, operations on the context will never return
+ * AVERROR(EAGAIN).
+ * Note that this flag does not affect the opening/connecting of the
+ * context. Connecting a protocol will always block if necessary (e.g. on
+ * network protocols) but never hang (e.g. on busy devices).
+ * Warning: non-blocking protocols is work-in-progress; this flag may be
+ * silently ignored.
  */
-int url_read(URLContext *h, unsigned char *buf, int size);
+#define URL_FLAG_NONBLOCK 4
+
+typedef int URLInterruptCB(void);
+extern URLInterruptCB *url_interrupt_cb;
 
 /**
- * Read as many bytes as possible (up to size), calling the
- * read function multiple times if necessary.
- * Will also retry if the read function returns AVERROR(EAGAIN).
- * This makes special short-read handling in applications
- * unnecessary, if the return value is < size then it is
- * certain there was either an error or the end of file was reached.
+ * @defgroup old_url_funcs Old url_* functions
+ * @deprecated use the buffered API based on AVIOContext instead
+ * @{
+ */
+attribute_deprecated int url_open_protocol (URLContext **puc, struct URLProtocol *up,
+                                            const char *url, int flags);
+attribute_deprecated int url_alloc(URLContext **h, const char *url, int flags);
+attribute_deprecated int url_connect(URLContext *h);
+attribute_deprecated int url_open(URLContext **h, const char *url, int flags);
+attribute_deprecated int url_read(URLContext *h, unsigned char *buf, int size);
+attribute_deprecated int url_read_complete(URLContext *h, unsigned char *buf, int size);
+attribute_deprecated int url_write(URLContext *h, const unsigned char *buf, int size);
+attribute_deprecated int64_t url_seek(URLContext *h, int64_t pos, int whence);
+attribute_deprecated int url_close(URLContext *h);
+attribute_deprecated int64_t url_filesize(URLContext *h);
+attribute_deprecated int url_get_file_handle(URLContext *h);
+attribute_deprecated int url_get_max_packet_size(URLContext *h);
+attribute_deprecated void url_get_filename(URLContext *h, char *buf, int buf_size);
+attribute_deprecated int av_url_read_pause(URLContext *h, int pause);
+attribute_deprecated int64_t av_url_read_seek(URLContext *h, int stream_index,
+                                              int64_t timestamp, int flags);
+attribute_deprecated void url_set_interrupt_cb(int (*interrupt_cb)(void));
+/**
+ * If protocol is NULL, returns the first registered protocol,
+ * if protocol is non-NULL, returns the next registered protocol after protocol,
+ * or NULL if protocol is the last one.
  */
-int url_read_complete(URLContext *h, unsigned char *buf, int size);
-int url_write(URLContext *h, unsigned char *buf, int size);
-
+attribute_deprecated URLProtocol *av_protocol_next(URLProtocol *p);
 /**
- * Changes the position that will be used by the next read/write
- * operation on the resource accessed by h.
+ * Register the URLProtocol protocol.
  *
- * @param pos specifies the new position to set
- * @param whence specifies how pos should be interpreted, it must be
- * one of SEEK_SET (seek from the beginning), SEEK_CUR (seek from the
- * current position), SEEK_END (seek from the end), or AVSEEK_SIZE
- * (return the filesize of the requested resource, pos is ignored).
- * @return a negative value corresponding to an AVERROR code in case
- * of failure, or the resulting file position, measured in bytes from
- * the beginning of the file. You can use this feature together with
- * SEEK_CUR to read the current file position.
+ * @param size the size of the URLProtocol struct referenced
+ */
+attribute_deprecated int av_register_protocol2(URLProtocol *protocol, int size);
+/**
+ * @}
  */
-int64_t url_seek(URLContext *h, int64_t pos, int whence);
+
+
+typedef attribute_deprecated AVIOContext ByteIOContext;
+
+attribute_deprecated int init_put_byte(AVIOContext *s,
+                  unsigned char *buffer,
+                  int buffer_size,
+                  int write_flag,
+                  void *opaque,
+                  int (*read_packet)(void *opaque, uint8_t *buf, int buf_size),
+                  int (*write_packet)(void *opaque, uint8_t *buf, int buf_size),
+                  int64_t (*seek)(void *opaque, int64_t offset, int whence));
+attribute_deprecated AVIOContext *av_alloc_put_byte(
+                  unsigned char *buffer,
+                  int buffer_size,
+                  int write_flag,
+                  void *opaque,
+                  int (*read_packet)(void *opaque, uint8_t *buf, int buf_size),
+                  int (*write_packet)(void *opaque, uint8_t *buf, int buf_size),
+                  int64_t (*seek)(void *opaque, int64_t offset, int whence));
 
 /**
- * Closes the resource accessed by the URLContext h, and frees the
- * memory used by it.
- *
- * @return a negative value if an error condition occurred, 0
- * otherwise
+ * @defgroup old_avio_funcs Old put_/get_*() functions
+ * @deprecated use the avio_ -prefixed functions instead.
+ * @{
+ */
+attribute_deprecated int          get_buffer(AVIOContext *s, unsigned char *buf, int size);
+attribute_deprecated int          get_partial_buffer(AVIOContext *s, unsigned char *buf, int size);
+attribute_deprecated int          get_byte(AVIOContext *s);
+attribute_deprecated unsigned int get_le16(AVIOContext *s);
+attribute_deprecated unsigned int get_le24(AVIOContext *s);
+attribute_deprecated unsigned int get_le32(AVIOContext *s);
+attribute_deprecated uint64_t     get_le64(AVIOContext *s);
+attribute_deprecated unsigned int get_be16(AVIOContext *s);
+attribute_deprecated unsigned int get_be24(AVIOContext *s);
+attribute_deprecated unsigned int get_be32(AVIOContext *s);
+attribute_deprecated uint64_t     get_be64(AVIOContext *s);
+
+attribute_deprecated void         put_byte(AVIOContext *s, int b);
+attribute_deprecated void         put_nbyte(AVIOContext *s, int b, int count);
+attribute_deprecated void         put_buffer(AVIOContext *s, const unsigned char *buf, int size);
+attribute_deprecated void         put_le64(AVIOContext *s, uint64_t val);
+attribute_deprecated void         put_be64(AVIOContext *s, uint64_t val);
+attribute_deprecated void         put_le32(AVIOContext *s, unsigned int val);
+attribute_deprecated void         put_be32(AVIOContext *s, unsigned int val);
+attribute_deprecated void         put_le24(AVIOContext *s, unsigned int val);
+attribute_deprecated void         put_be24(AVIOContext *s, unsigned int val);
+attribute_deprecated void         put_le16(AVIOContext *s, unsigned int val);
+attribute_deprecated void         put_be16(AVIOContext *s, unsigned int val);
+attribute_deprecated void         put_tag(AVIOContext *s, const char *tag);
+/**
+ * @}
+ */
+
+attribute_deprecated int     av_url_read_fpause(AVIOContext *h,    int pause);
+attribute_deprecated int64_t av_url_read_fseek (AVIOContext *h,    int stream_index,
+                                                int64_t timestamp, int flags);
+
+/**
+ * @defgroup old_url_f_funcs Old url_f* functions
+ * @deprecated use the avio_ -prefixed functions instead.
+ * @{
+ */
+attribute_deprecated int url_fopen( AVIOContext **s, const char *url, int flags);
+attribute_deprecated int url_fclose(AVIOContext *s);
+attribute_deprecated int64_t url_fseek(AVIOContext *s, int64_t offset, int whence);
+attribute_deprecated int url_fskip(AVIOContext *s, int64_t offset);
+attribute_deprecated int64_t url_ftell(AVIOContext *s);
+attribute_deprecated int64_t url_fsize(AVIOContext *s);
+#define URL_EOF (-1)
+attribute_deprecated int url_fgetc(AVIOContext *s);
+attribute_deprecated int url_setbufsize(AVIOContext *s, int buf_size);
+#ifdef __GNUC__
+attribute_deprecated int url_fprintf(AVIOContext *s, const char *fmt, ...) __attribute__ ((__format__ (__printf__, 2, 3)));
+#else
+attribute_deprecated int url_fprintf(AVIOContext *s, const char *fmt, ...);
+#endif
+attribute_deprecated void put_flush_packet(AVIOContext *s);
+attribute_deprecated int url_open_dyn_buf(AVIOContext **s);
+attribute_deprecated int url_open_dyn_packet_buf(AVIOContext **s, int max_packet_size);
+attribute_deprecated int url_close_dyn_buf(AVIOContext *s, uint8_t **pbuffer);
+attribute_deprecated int url_fdopen(AVIOContext **s, URLContext *h);
+/**
+ * @}
  */
-int url_close(URLContext *h);
 
 /**
- * Returns a non-zero value if the resource indicated by url
- * exists, 0 otherwise.
+ * @deprecated use AVIOContext.eof_reached
  */
-int url_exist(const char *url);
+attribute_deprecated int url_feof(AVIOContext *s);
+attribute_deprecated int url_ferror(AVIOContext *s);
 
-int64_t url_filesize(URLContext *h);
+attribute_deprecated int udp_set_remote_url(URLContext *h, const char *uri);
+attribute_deprecated int udp_get_local_port(URLContext *h);
 
+attribute_deprecated void init_checksum(AVIOContext *s,
+                   unsigned long (*update_checksum)(unsigned long c, const uint8_t *p, unsigned int len),
+                   unsigned long checksum);
+attribute_deprecated unsigned long get_checksum(AVIOContext *s);
+attribute_deprecated void put_strz(AVIOContext *s, const char *buf);
+/** @note unlike fgets, the EOL character is not returned and a whole
+    line is parsed. return NULL if first char read was EOF */
+attribute_deprecated char *url_fgets(AVIOContext *s, char *buf, int buf_size);
 /**
- * Return the file descriptor associated with this URL. For RTP, this
- * will return only the RTP file descriptor, not the RTCP file descriptor.
- * To get both, use rtp_get_file_handles().
- *
- * @return the file descriptor associated with this URL, or <0 on error.
+ * @deprecated use avio_get_str instead
  */
-int url_get_file_handle(URLContext *h);
-
+attribute_deprecated char *get_strz(AVIOContext *s, char *buf, int maxlen);
 /**
- * Return the maximum packet size associated to packetized file
- * handle. If the file is not packetized (stream like HTTP or file on
- * disk), then 0 is returned.
- *
- * @param h file handle
- * @return maximum packet size in bytes
+ * @deprecated Use AVIOContext.seekable field directly.
  */
-int url_get_max_packet_size(URLContext *h);
-void url_get_filename(URLContext *h, char *buf, int buf_size);
+attribute_deprecated static inline int url_is_streamed(AVIOContext *s)
+{
+    return !s->seekable;
+}
+attribute_deprecated URLContext *url_fileno(AVIOContext *s);
 
 /**
- * The callback is called in blocking functions to test regulary if
- * asynchronous interruption is needed. AVERROR(EINTR) is returned
- * in this case by the interrupted function. 'NULL' means no interrupt
- * callback is given.
+ * @deprecated use AVIOContext.max_packet_size directly.
  */
-void url_set_interrupt_cb(URLInterruptCB *interrupt_cb);
+attribute_deprecated int url_fget_max_packet_size(AVIOContext *s);
 
-/* not implemented */
-int url_poll(URLPollEntry *poll_table, int n, int timeout);
+attribute_deprecated int url_open_buf(AVIOContext **s, uint8_t *buf, int buf_size, int flags);
 
-/**
- * Pause and resume playing - only meaningful if using a network streaming
- * protocol (e.g. MMS).
- * @param pause 1 for pause, 0 for resume
- */
-int av_url_read_pause(URLContext *h, int pause);
+/** return the written or read size */
+attribute_deprecated int url_close_buf(AVIOContext *s);
 
 /**
- * Seek to a given timestamp relative to some component stream.
- * Only meaningful if using a network streaming protocol (e.g. MMS.).
- * @param stream_index The stream index that the timestamp is relative to.
- *        If stream_index is (-1) the timestamp should be in AV_TIME_BASE
- *        units from the beginning of the presentation.
- *        If a stream_index >= 0 is used and the protocol does not support
- *        seeking based on component streams, the call will fail with ENOTSUP.
- * @param timestamp timestamp in AVStream.time_base units
- *        or if there is no stream specified then in AV_TIME_BASE units.
- * @param flags Optional combination of AVSEEK_FLAG_BACKWARD, AVSEEK_FLAG_BYTE
- *        and AVSEEK_FLAG_ANY. The protocol may silently ignore
- *        AVSEEK_FLAG_BACKWARD and AVSEEK_FLAG_ANY, but AVSEEK_FLAG_BYTE will
- *        fail with ENOTSUP if used and not supported.
- * @return >= 0 on success
- * @see AVInputFormat::read_seek
+ * Return a non-zero value if the resource indicated by url
+ * exists, 0 otherwise.
+ * @deprecated Use avio_check instead.
  */
-int64_t av_url_read_seek(URLContext *h, int stream_index,
-                         int64_t timestamp, int flags);
+attribute_deprecated int url_exist(const char *url);
+#endif // FF_API_OLD_AVIO
 
 /**
- * Passing this as the "whence" parameter to a seek function causes it to
- * return the filesize without seeking anywhere. Supporting this is optional.
- * If it is not supported then the seek function will return <0.
+ * Return AVIO_* access flags corresponding to the access permissions
+ * of the resource in url, or a negative value corresponding to an
+ * AVERROR code in case of failure. The returned access flags are
+ * masked by the value in flags.
+ *
+ * @note This function is intrinsically unsafe, in the sense that the
+ * checked resource may change its existence or permission status from
+ * one call to another. Thus you should not trust the returned value,
+ * unless you are sure that no other processes are accessing the
+ * checked resource.
+ *
+ * @note This function is slightly broken until next major bump
+ *       because of AVIO_RDONLY == 0. Don't use it until then.
  */
-#define AVSEEK_SIZE 0x10000
+int avio_check(const char *url, int flags);
 
 /**
- * Oring this flag as into the "whence" parameter to a seek function causes it to
- * seek by any means (like reopening and linear reading) or other normally unreasonble
- * means that can be extreemly slow.
- * This may be ignored by the seek code.
+ * The callback is called in blocking functions to test regulary if
+ * asynchronous interruption is needed. AVERROR_EXIT is returned
+ * in this case by the interrupted function. 'NULL' means no interrupt
+ * callback is given.
  */
-#define AVSEEK_FORCE 0x20000
-
-typedef struct URLProtocol {
-    const char *name;
-    int (*url_open)(URLContext *h, const char *url, int flags);
-    int (*url_read)(URLContext *h, unsigned char *buf, int size);
-    int (*url_write)(URLContext *h, unsigned char *buf, int size);
-    int64_t (*url_seek)(URLContext *h, int64_t pos, int whence);
-    int (*url_close)(URLContext *h);
-    struct URLProtocol *next;
-    int (*url_read_pause)(URLContext *h, int pause);
-    int64_t (*url_read_seek)(URLContext *h, int stream_index,
-                             int64_t timestamp, int flags);
-    int (*url_get_file_handle)(URLContext *h);
-} URLProtocol;
+void avio_set_interrupt_cb(int (*interrupt_cb)(void));
 
-#if LIBAVFORMAT_VERSION_MAJOR < 53
+#if FF_API_REGISTER_PROTOCOL
 extern URLProtocol *first_protocol;
 #endif
 
-extern URLInterruptCB *url_interrupt_cb;
-
-/**
- * If protocol is NULL, returns the first registered protocol,
- * if protocol is non-NULL, returns the next registered protocol after protocol,
- * or NULL if protocol is the last one.
- */
-URLProtocol *av_protocol_next(URLProtocol *p);
-
-#if LIBAVFORMAT_VERSION_MAJOR < 53
+#if FF_API_REGISTER_PROTOCOL
 /**
  * @deprecated Use av_register_protocol() instead.
  */
 attribute_deprecated int register_protocol(URLProtocol *protocol);
-#endif
 
 /**
- * Registers the URLProtocol protocol.
+ * @deprecated Use av_register_protocol2() instead.
  */
-int av_register_protocol(URLProtocol *protocol);
+attribute_deprecated int av_register_protocol(URLProtocol *protocol);
+#endif
 
 /**
- * Bytestream IO Context.
- * New fields can be added to the end with minor version bumps.
- * Removal, reordering and changes to existing fields require a major
- * version bump.
- * sizeof(ByteIOContext) must not be used outside libav*.
+ * Allocate and initialize an AVIOContext for buffered I/O. It must be later
+ * freed with av_free().
+ *
+ * @param buffer Memory block for input/output operations via AVIOContext.
+ * @param buffer_size The buffer size is very important for performance.
+ *        For protocols with fixed blocksize it should be set to this blocksize.
+ *        For others a typical size is a cache page, e.g. 4kb.
+ * @param write_flag Set to 1 if the buffer should be writable, 0 otherwise.
+ * @param opaque An opaque pointer to user-specific data.
+ * @param read_packet  A function for refilling the buffer, may be NULL.
+ * @param write_packet A function for writing the buffer contents, may be NULL.
+ * @param seek A function for seeking to specified byte position, may be NULL.
+ *
+ * @return Allocated AVIOContext or NULL on failure.
  */
-typedef struct {
-    unsigned char *buffer;
-    int buffer_size;
-    unsigned char *buf_ptr, *buf_end;
-    void *opaque;
-    int (*read_packet)(void *opaque, uint8_t *buf, int buf_size);
-    int (*write_packet)(void *opaque, uint8_t *buf, int buf_size);
-    int64_t (*seek)(void *opaque, int64_t offset, int whence);
-    int64_t pos; /**< position in the file of the current buffer */
-    int must_flush; /**< true if the next seek should flush */
-    int eof_reached; /**< true if eof reached */
-    int write_flag;  /**< true if open for writing */
-    int is_streamed;
-    int max_packet_size;
-    unsigned long checksum;
-    unsigned char *checksum_ptr;
-    unsigned long (*update_checksum)(unsigned long checksum, const uint8_t *buf, unsigned int size);
-    int error;         ///< contains the error code or 0 if no error happened
-    int (*read_pause)(void *opaque, int pause);
-    int64_t (*read_seek)(void *opaque, int stream_index,
-                         int64_t timestamp, int flags);
-} ByteIOContext;
-
-int init_put_byte(ByteIOContext *s,
-                  unsigned char *buffer,
-                  int buffer_size,
-                  int write_flag,
-                  void *opaque,
-                  int (*read_packet)(void *opaque, uint8_t *buf, int buf_size),
-                  int (*write_packet)(void *opaque, uint8_t *buf, int buf_size),
-                  int64_t (*seek)(void *opaque, int64_t offset, int whence));
-ByteIOContext *av_alloc_put_byte(
+AVIOContext *avio_alloc_context(
                   unsigned char *buffer,
                   int buffer_size,
                   int write_flag,
@@ -306,179 +414,201 @@ ByteIOContext *av_alloc_put_byte(
                   int (*write_packet)(void *opaque, uint8_t *buf, int buf_size),
                   int64_t (*seek)(void *opaque, int64_t offset, int whence));
 
-void put_byte(ByteIOContext *s, int b);
-void put_buffer(ByteIOContext *s, const unsigned char *buf, int size);
-void put_le64(ByteIOContext *s, uint64_t val);
-void put_be64(ByteIOContext *s, uint64_t val);
-void put_le32(ByteIOContext *s, unsigned int val);
-void put_be32(ByteIOContext *s, unsigned int val);
-void put_le24(ByteIOContext *s, unsigned int val);
-void put_be24(ByteIOContext *s, unsigned int val);
-void put_le16(ByteIOContext *s, unsigned int val);
-void put_be16(ByteIOContext *s, unsigned int val);
-void put_tag(ByteIOContext *s, const char *tag);
-
-void put_strz(ByteIOContext *s, const char *buf);
+void avio_w8(AVIOContext *s, int b);
+void avio_write(AVIOContext *s, const unsigned char *buf, int size);
+void avio_wl64(AVIOContext *s, uint64_t val);
+void avio_wb64(AVIOContext *s, uint64_t val);
+void avio_wl32(AVIOContext *s, unsigned int val);
+void avio_wb32(AVIOContext *s, unsigned int val);
+void avio_wl24(AVIOContext *s, unsigned int val);
+void avio_wb24(AVIOContext *s, unsigned int val);
+void avio_wl16(AVIOContext *s, unsigned int val);
+void avio_wb16(AVIOContext *s, unsigned int val);
 
 /**
- * fseek() equivalent for ByteIOContext.
- * @return new position or AVERROR.
+ * Write a NULL-terminated string.
+ * @return number of bytes written.
  */
-int64_t url_fseek(ByteIOContext *s, int64_t offset, int whence);
+int avio_put_str(AVIOContext *s, const char *str);
 
 /**
- * Skip given number of bytes forward.
- * @param offset number of bytes
+ * Convert an UTF-8 string to UTF-16LE and write it.
+ * @return number of bytes written.
  */
-void url_fskip(ByteIOContext *s, int64_t offset);
+int avio_put_str16le(AVIOContext *s, const char *str);
 
 /**
- * ftell() equivalent for ByteIOContext.
- * @return position or AVERROR.
+ * Passing this as the "whence" parameter to a seek function causes it to
+ * return the filesize without seeking anywhere. Supporting this is optional.
+ * If it is not supported then the seek function will return <0.
  */
-int64_t url_ftell(ByteIOContext *s);
+#define AVSEEK_SIZE 0x10000
 
 /**
- * Gets the filesize.
- * @return filesize or AVERROR
+ * Oring this flag as into the "whence" parameter to a seek function causes it to
+ * seek by any means (like reopening and linear reading) or other normally unreasonble
+ * means that can be extreemly slow.
+ * This may be ignored by the seek code.
  */
-int64_t url_fsize(ByteIOContext *s);
+#define AVSEEK_FORCE 0x20000
 
 /**
- * feof() equivalent for ByteIOContext.
- * @return non zero if and only if end of file
+ * fseek() equivalent for AVIOContext.
+ * @return new position or AVERROR.
  */
-int url_feof(ByteIOContext *s);
+int64_t avio_seek(AVIOContext *s, int64_t offset, int whence);
 
-int url_ferror(ByteIOContext *s);
+/**
+ * Skip given number of bytes forward
+ * @return new position or AVERROR.
+ */
+static av_always_inline int64_t avio_skip(AVIOContext *s, int64_t offset)
+{
+    return avio_seek(s, offset, SEEK_CUR);
+}
 
-int av_url_read_fpause(ByteIOContext *h, int pause);
-int64_t av_url_read_fseek(ByteIOContext *h, int stream_index,
-                          int64_t timestamp, int flags);
+/**
+ * ftell() equivalent for AVIOContext.
+ * @return position or AVERROR.
+ */
+static av_always_inline int64_t avio_tell(AVIOContext *s)
+{
+    return avio_seek(s, 0, SEEK_CUR);
+}
 
-#define URL_EOF (-1)
-/** @note return URL_EOF (-1) if EOF */
-int url_fgetc(ByteIOContext *s);
+/**
+ * Get the filesize.
+ * @return filesize or AVERROR
+ */
+int64_t avio_size(AVIOContext *s);
 
 /** @warning currently size is limited */
 #ifdef __GNUC__
-int url_fprintf(ByteIOContext *s, const char *fmt, ...) __attribute__ ((__format__ (__printf__, 2, 3)));
+int avio_printf(AVIOContext *s, const char *fmt, ...) __attribute__ ((__format__ (__printf__, 2, 3)));
 #else
-int url_fprintf(ByteIOContext *s, const char *fmt, ...);
+int avio_printf(AVIOContext *s, const char *fmt, ...);
 #endif
 
-/** @note unlike fgets, the EOL character is not returned and a whole
-    line is parsed. return NULL if first char read was EOF */
-char *url_fgets(ByteIOContext *s, char *buf, int buf_size);
-
-void put_flush_packet(ByteIOContext *s);
+void avio_flush(AVIOContext *s);
 
 
 /**
- * Reads size bytes from ByteIOContext into buf.
+ * Read size bytes from AVIOContext into buf.
  * @return number of bytes read or AVERROR
  */
-int get_buffer(ByteIOContext *s, unsigned char *buf, int size);
+int avio_read(AVIOContext *s, unsigned char *buf, int size);
 
 /**
- * Reads size bytes from ByteIOContext into buf.
- * This reads at most 1 packet. If that is not enough fewer bytes will be
- * returned.
- * @return number of bytes read or AVERROR
+ * @defgroup avio_read Functions for reading from AVIOContext.
+ * @{
+ *
+ * @note return 0 if EOF, so you cannot use it if EOF handling is
+ *       necessary
+ */
+int          avio_r8  (AVIOContext *s);
+unsigned int avio_rl16(AVIOContext *s);
+unsigned int avio_rl24(AVIOContext *s);
+unsigned int avio_rl32(AVIOContext *s);
+uint64_t     avio_rl64(AVIOContext *s);
+unsigned int avio_rb16(AVIOContext *s);
+unsigned int avio_rb24(AVIOContext *s);
+unsigned int avio_rb32(AVIOContext *s);
+uint64_t     avio_rb64(AVIOContext *s);
+/**
+ * @}
  */
-int get_partial_buffer(ByteIOContext *s, unsigned char *buf, int size);
-
-/** @note return 0 if EOF, so you cannot use it if EOF handling is
-    necessary */
-int get_byte(ByteIOContext *s);
-unsigned int get_le24(ByteIOContext *s);
-unsigned int get_le32(ByteIOContext *s);
-uint64_t get_le64(ByteIOContext *s);
-unsigned int get_le16(ByteIOContext *s);
-
-char *get_strz(ByteIOContext *s, char *buf, int maxlen);
-unsigned int get_be16(ByteIOContext *s);
-unsigned int get_be24(ByteIOContext *s);
-unsigned int get_be32(ByteIOContext *s);
-uint64_t get_be64(ByteIOContext *s);
-
-uint64_t ff_get_v(ByteIOContext *bc);
-
-static inline int url_is_streamed(ByteIOContext *s)
-{
-    return s->is_streamed;
-}
 
 /**
- * Creates and initializes a ByteIOContext for accessing the
- * resource referenced by the URLContext h.
- * @note When the URLContext h has been opened in read+write mode, the
- * ByteIOContext can be used only for writing.
+ * Read a string from pb into buf. The reading will terminate when either
+ * a NULL character was encountered, maxlen bytes have been read, or nothing
+ * more can be read from pb. The result is guaranteed to be NULL-terminated, it
+ * will be truncated if buf is too small.
+ * Note that the string is not interpreted or validated in any way, it
+ * might get truncated in the middle of a sequence for multi-byte encodings.
  *
- * @param s Used to return the pointer to the created ByteIOContext.
- * In case of failure the pointed to value is set to NULL.
- * @return 0 in case of success, a negative value corresponding to an
- * AVERROR code in case of failure
+ * @return number of bytes read (is always <= maxlen).
+ * If reading ends on EOF or error, the return value will be one more than
+ * bytes actually read.
  */
-int url_fdopen(ByteIOContext **s, URLContext *h);
+int avio_get_str(AVIOContext *pb, int maxlen, char *buf, int buflen);
 
-/** @warning must be called before any I/O */
-int url_setbufsize(ByteIOContext *s, int buf_size);
-#if LIBAVFORMAT_VERSION_MAJOR < 53
+/**
+ * Read a UTF-16 string from pb and convert it to UTF-8.
+ * The reading will terminate when either a null or invalid character was
+ * encountered or maxlen bytes have been read.
+ * @return number of bytes read (is always <= maxlen)
+ */
+int avio_get_str16le(AVIOContext *pb, int maxlen, char *buf, int buflen);
+int avio_get_str16be(AVIOContext *pb, int maxlen, char *buf, int buflen);
+
+
+#if FF_API_URL_RESETBUF
 /** Reset the buffer for reading or writing.
  * @note Will drop any data currently in the buffer without transmitting it.
  * @param flags URL_RDONLY to set up the buffer for reading, or URL_WRONLY
  *        to set up the buffer for writing. */
-int url_resetbuf(ByteIOContext *s, int flags);
+int url_resetbuf(AVIOContext *s, int flags);
 #endif
 
 /**
- * Rewinds the ByteIOContext using the specified buffer containing the first buf_size bytes of the file.
- * Used after probing to avoid seeking.
- * Joins buf and s->buffer, taking any overlap into consideration.
- * @note s->buffer must overlap with buf or they can't be joined and the function fails
- * @note This function is NOT part of the public API
- *
- * @param s The read-only ByteIOContext to rewind
- * @param buf The probe buffer containing the first buf_size bytes of the file
- * @param buf_size The size of buf
- * @return 0 in case of success, a negative value corresponding to an
- * AVERROR code in case of failure
+ * @defgroup open_modes URL open modes
+ * The flags argument to avio_open must be one of the following
+ * constants, optionally ORed with other flags.
+ * @{
+ */
+#if LIBAVFORMAT_VERSION_MAJOR < 53
+#define AVIO_RDONLY 0  /**< read-only */
+#define AVIO_WRONLY 1  /**< write-only */
+#define AVIO_RDWR   2  /**< read-write */
+#else
+#define AVIO_RDONLY 1  /**< read-only */
+#define AVIO_WRONLY 2  /**< write-only */
+#define AVIO_RDWR   4  /**< read-write */
+#endif
+/**
+ * @}
+ */
+
+/**
+ * Use non-blocking mode.
+ * If this flag is set, operations on the context will return
+ * AVERROR(EAGAIN) if they can not be performed immediately.
+ * If this flag is not set, operations on the context will never return
+ * AVERROR(EAGAIN).
+ * Note that this flag does not affect the opening/connecting of the
+ * context. Connecting a protocol will always block if necessary (e.g. on
+ * network protocols) but never hang (e.g. on busy devices).
+ * Warning: non-blocking protocols is work-in-progress; this flag may be
+ * silently ignored.
  */
-int ff_rewind_with_probe_data(ByteIOContext *s, unsigned char *buf, int buf_size);
+#if LIBAVFORMAT_VERSION_MAJOR < 53
+#define AVIO_FLAG_NONBLOCK 4
+#else
+#define AVIO_FLAG_NONBLOCK 8
+#endif
 
 /**
- * Creates and initializes a ByteIOContext for accessing the
+ * Create and initialize a AVIOContext for accessing the
  * resource indicated by url.
  * @note When the resource indicated by url has been opened in
- * read+write mode, the ByteIOContext can be used only for writing.
+ * read+write mode, the AVIOContext can be used only for writing.
  *
- * @param s Used to return the pointer to the created ByteIOContext.
+ * @param s Used to return the pointer to the created AVIOContext.
  * In case of failure the pointed to value is set to NULL.
  * @param flags flags which control how the resource indicated by url
  * is to be opened
  * @return 0 in case of success, a negative value corresponding to an
  * AVERROR code in case of failure
  */
-int url_fopen(ByteIOContext **s, const char *url, int flags);
-
-int url_fclose(ByteIOContext *s);
-URLContext *url_fileno(ByteIOContext *s);
+int avio_open(AVIOContext **s, const char *url, int flags);
 
 /**
- * Return the maximum packet size associated to packetized buffered file
- * handle. If the file is not packetized (stream like http or file on
- * disk), then 0 is returned.
+ * Close the resource accessed by the AVIOContext s and free it.
+ * This function can only be used if s was opened by avio_open().
  *
- * @param s buffered file handle
- * @return maximum packet size in bytes
+ * @return 0 on success, an AVERROR < 0 on error.
  */
-int url_fget_max_packet_size(ByteIOContext *s);
-
-int url_open_buf(ByteIOContext **s, uint8_t *buf, int buf_size, int flags);
-
-/** return the written or read size */
-int url_close_buf(ByteIOContext *s);
+int avio_close(AVIOContext *s);
 
 /**
  * Open a write only memory stream.
@@ -486,40 +616,61 @@ int url_close_buf(ByteIOContext *s);
  * @param s new IO context
  * @return zero if no error.
  */
-int url_open_dyn_buf(ByteIOContext **s);
-
-/**
- * Open a write only packetized memory stream with a maximum packet
- * size of 'max_packet_size'.  The stream is stored in a memory buffer
- * with a big endian 4 byte header giving the packet size in bytes.
- *
- * @param s new IO context
- * @param max_packet_size maximum packet size (must be > 0)
- * @return zero if no error.
- */
-int url_open_dyn_packet_buf(ByteIOContext **s, int max_packet_size);
+int avio_open_dyn_buf(AVIOContext **s);
 
 /**
  * Return the written size and a pointer to the buffer. The buffer
- *  must be freed with av_free().
+ * must be freed with av_free().
+ * Padding of FF_INPUT_BUFFER_PADDING_SIZE is added to the buffer.
+ *
  * @param s IO context
  * @param pbuffer pointer to a byte buffer
  * @return the length of the byte buffer
  */
-int url_close_dyn_buf(ByteIOContext *s, uint8_t **pbuffer);
+int avio_close_dyn_buf(AVIOContext *s, uint8_t **pbuffer);
 
-unsigned long ff_crc04C11DB7_update(unsigned long checksum, const uint8_t *buf,
-                                    unsigned int len);
-unsigned long get_checksum(ByteIOContext *s);
-void init_checksum(ByteIOContext *s,
-                   unsigned long (*update_checksum)(unsigned long c, const uint8_t *p, unsigned int len),
-                   unsigned long checksum);
-
-/* udp.c */
-int udp_set_remote_url(URLContext *h, const char *uri);
-int udp_get_local_port(URLContext *h);
-#if (LIBAVFORMAT_VERSION_MAJOR <= 52)
+#if FF_API_UDP_GET_FILE
 int udp_get_file_handle(URLContext *h);
 #endif
 
+/**
+ * Iterate through names of available protocols.
+ *
+ * @param opaque A private pointer representing current protocol.
+ *        It must be a pointer to NULL on first iteration and will
+ *        be updated by successive calls to avio_enum_protocols.
+ * @param output If set to 1, iterate over output protocols,
+ *               otherwise over input protocols.
+ *
+ * @return A static string containing the name of current protocol or NULL
+ */
+const char *avio_enum_protocols(void **opaque, int output);
+
+/**
+ * Pause and resume playing - only meaningful if using a network streaming
+ * protocol (e.g. MMS).
+ * @param pause 1 for pause, 0 for resume
+ */
+int     avio_pause(AVIOContext *h, int pause);
+
+/**
+ * Seek to a given timestamp relative to some component stream.
+ * Only meaningful if using a network streaming protocol (e.g. MMS.).
+ * @param stream_index The stream index that the timestamp is relative to.
+ *        If stream_index is (-1) the timestamp should be in AV_TIME_BASE
+ *        units from the beginning of the presentation.
+ *        If a stream_index >= 0 is used and the protocol does not support
+ *        seeking based on component streams, the call will fail with ENOTSUP.
+ * @param timestamp timestamp in AVStream.time_base units
+ *        or if there is no stream specified then in AV_TIME_BASE units.
+ * @param flags Optional combination of AVSEEK_FLAG_BACKWARD, AVSEEK_FLAG_BYTE
+ *        and AVSEEK_FLAG_ANY. The protocol may silently ignore
+ *        AVSEEK_FLAG_BACKWARD and AVSEEK_FLAG_ANY, but AVSEEK_FLAG_BYTE will
+ *        fail with ENOTSUP if used and not supported.
+ * @return >= 0 on success
+ * @see AVInputFormat::read_seek
+ */
+int64_t avio_seek_time(AVIOContext *h, int stream_index,
+                       int64_t timestamp, int flags);
+
 #endif /* AVFORMAT_AVIO_H */
diff --git a/libavformat/avio_internal.h b/libavformat/avio_internal.h
new file mode 100644
index 0000000..6630aaf
--- /dev/null
+++ b/libavformat/avio_internal.h
@@ -0,0 +1,101 @@
+/*
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVFORMAT_AVIO_INTERNAL_H
+#define AVFORMAT_AVIO_INTERNAL_H
+
+#include "avio.h"
+#include "url.h"
+
+int ffio_init_context(AVIOContext *s,
+                  unsigned char *buffer,
+                  int buffer_size,
+                  int write_flag,
+                  void *opaque,
+                  int (*read_packet)(void *opaque, uint8_t *buf, int buf_size),
+                  int (*write_packet)(void *opaque, uint8_t *buf, int buf_size),
+                  int64_t (*seek)(void *opaque, int64_t offset, int whence));
+
+
+/**
+ * Read size bytes from AVIOContext into buf.
+ * This reads at most 1 packet. If that is not enough fewer bytes will be
+ * returned.
+ * @return number of bytes read or AVERROR
+ */
+int ffio_read_partial(AVIOContext *s, unsigned char *buf, int size);
+
+void ffio_fill(AVIOContext *s, int b, int count);
+
+static av_always_inline void ffio_wfourcc(AVIOContext *pb, const uint8_t *s)
+{
+    avio_wl32(pb, MKTAG(s[0], s[1], s[2], s[3]));
+}
+
+/**
+ * Rewind the AVIOContext using the specified buffer containing the first buf_size bytes of the file.
+ * Used after probing to avoid seeking.
+ * Joins buf and s->buffer, taking any overlap into consideration.
+ * @note s->buffer must overlap with buf or they can't be joined and the function fails
+ *
+ * @param s The read-only AVIOContext to rewind
+ * @param buf The probe buffer containing the first buf_size bytes of the file
+ * @param buf_size The size of buf
+ * @return 0 in case of success, a negative value corresponding to an
+ * AVERROR code in case of failure
+ */
+int ffio_rewind_with_probe_data(AVIOContext *s, unsigned char *buf, int buf_size);
+
+uint64_t ffio_read_varlen(AVIOContext *bc);
+
+/** @warning must be called before any I/O */
+int ffio_set_buf_size(AVIOContext *s, int buf_size);
+
+void ffio_init_checksum(AVIOContext *s,
+                        unsigned long (*update_checksum)(unsigned long c, const uint8_t *p, unsigned int len),
+                        unsigned long checksum);
+unsigned long ffio_get_checksum(AVIOContext *s);
+unsigned long ff_crc04C11DB7_update(unsigned long checksum, const uint8_t *buf,
+                                    unsigned int len);
+
+/**
+ * Open a write only packetized memory stream with a maximum packet
+ * size of 'max_packet_size'.  The stream is stored in a memory buffer
+ * with a big endian 4 byte header giving the packet size in bytes.
+ *
+ * @param s new IO context
+ * @param max_packet_size maximum packet size (must be > 0)
+ * @return zero if no error.
+ */
+int ffio_open_dyn_packet_buf(AVIOContext **s, int max_packet_size);
+
+/**
+ * Create and initialize a AVIOContext for accessing the
+ * resource referenced by the URLContext h.
+ * @note When the URLContext h has been opened in read+write mode, the
+ * AVIOContext can be used only for writing.
+ *
+ * @param s Used to return the pointer to the created AVIOContext.
+ * In case of failure the pointed to value is set to NULL.
+ * @return 0 in case of success, a negative value corresponding to an
+ * AVERROR code in case of failure
+ */
+int ffio_fdopen(AVIOContext **s, URLContext *h);
+
+#endif // AVFORMAT_AVIO_INTERNAL_H
diff --git a/libavformat/aviobuf.c b/libavformat/aviobuf.c
index 8684903..cde5f26 100644
--- a/libavformat/aviobuf.c
+++ b/libavformat/aviobuf.c
@@ -2,20 +2,20 @@
  * Buffered I/O for ffmpeg system
  * Copyright (c) 2000,2001 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -23,16 +23,26 @@
 #include "libavutil/intreadwrite.h"
 #include "avformat.h"
 #include "avio.h"
+#include "avio_internal.h"
+#include "internal.h"
+#include "url.h"
 #include <stdarg.h>
 
 #define IO_BUFFER_SIZE 32768
 
-static void fill_buffer(ByteIOContext *s);
-#if LIBAVFORMAT_VERSION_MAJOR >= 53
-static int url_resetbuf(ByteIOContext *s, int flags);
+/**
+ * Do seeks within this distance ahead of the current buffer by skipping
+ * data instead of calling the protocol seek function, for seekable
+ * protocols.
+ */
+#define SHORT_SEEK_THRESHOLD 4096
+
+static void fill_buffer(AVIOContext *s);
+#if !FF_API_URL_RESETBUF
+static int url_resetbuf(AVIOContext *s, int flags);
 #endif
 
-int init_put_byte(ByteIOContext *s,
+int ffio_init_context(AVIOContext *s,
                   unsigned char *buffer,
                   int buffer_size,
                   int write_flag,
@@ -45,7 +55,7 @@ int init_put_byte(ByteIOContext *s,
     s->buffer_size = buffer_size;
     s->buf_ptr = buffer;
     s->opaque = opaque;
-    url_resetbuf(s, write_flag ? URL_WRONLY : URL_RDONLY);
+    url_resetbuf(s, write_flag ? AVIO_WRONLY : AVIO_RDONLY);
     s->write_packet = write_packet;
     s->read_packet = read_packet;
     s->seek = seek;
@@ -53,7 +63,10 @@ int init_put_byte(ByteIOContext *s,
     s->must_flush = 0;
     s->eof_reached = 0;
     s->error = 0;
+#if FF_API_OLD_AVIO
     s->is_streamed = 0;
+#endif
+    s->seekable = AVIO_SEEKABLE_NORMAL;
     s->max_packet_size = 0;
     s->update_checksum= NULL;
     if(!read_packet && !write_flag){
@@ -65,7 +78,8 @@ int init_put_byte(ByteIOContext *s,
     return 0;
 }
 
-ByteIOContext *av_alloc_put_byte(
+#if FF_API_OLD_AVIO
+int init_put_byte(AVIOContext *s,
                   unsigned char *buffer,
                   int buffer_size,
                   int write_flag,
@@ -74,13 +88,39 @@ ByteIOContext *av_alloc_put_byte(
                   int (*write_packet)(void *opaque, uint8_t *buf, int buf_size),
                   int64_t (*seek)(void *opaque, int64_t offset, int whence))
 {
-    ByteIOContext *s = av_mallocz(sizeof(ByteIOContext));
-    init_put_byte(s, buffer, buffer_size, write_flag, opaque,
+    return ffio_init_context(s, buffer, buffer_size, write_flag, opaque,
+                                read_packet, write_packet, seek);
+}
+AVIOContext *av_alloc_put_byte(
+                  unsigned char *buffer,
+                  int buffer_size,
+                  int write_flag,
+                  void *opaque,
+                  int (*read_packet)(void *opaque, uint8_t *buf, int buf_size),
+                  int (*write_packet)(void *opaque, uint8_t *buf, int buf_size),
+                  int64_t (*seek)(void *opaque, int64_t offset, int whence))
+{
+    return avio_alloc_context(buffer, buffer_size, write_flag, opaque,
+                              read_packet, write_packet, seek);
+}
+#endif
+
+AVIOContext *avio_alloc_context(
+                  unsigned char *buffer,
+                  int buffer_size,
+                  int write_flag,
+                  void *opaque,
+                  int (*read_packet)(void *opaque, uint8_t *buf, int buf_size),
+                  int (*write_packet)(void *opaque, uint8_t *buf, int buf_size),
+                  int64_t (*seek)(void *opaque, int64_t offset, int whence))
+{
+    AVIOContext *s = av_mallocz(sizeof(AVIOContext));
+    ffio_init_context(s, buffer, buffer_size, write_flag, opaque,
                   read_packet, write_packet, seek);
     return s;
 }
 
-static void flush_buffer(ByteIOContext *s)
+static void flush_buffer(AVIOContext *s)
 {
     if (s->buf_ptr > s->buffer) {
         if (s->write_packet && !s->error){
@@ -98,14 +138,28 @@ static void flush_buffer(ByteIOContext *s)
     s->buf_ptr = s->buffer;
 }
 
-void put_byte(ByteIOContext *s, int b)
+void avio_w8(AVIOContext *s, int b)
 {
     *(s->buf_ptr)++ = b;
     if (s->buf_ptr >= s->buf_end)
         flush_buffer(s);
 }
 
-void put_buffer(ByteIOContext *s, const unsigned char *buf, int size)
+void ffio_fill(AVIOContext *s, int b, int count)
+{
+    while (count > 0) {
+        int len = FFMIN(s->buf_end - s->buf_ptr, count);
+        memset(s->buf_ptr, b, len);
+        s->buf_ptr += len;
+
+        if (s->buf_ptr >= s->buf_end)
+            flush_buffer(s);
+
+        count -= len;
+    }
+}
+
+void avio_write(AVIOContext *s, const unsigned char *buf, int size)
 {
     while (size > 0) {
         int len = FFMIN(s->buf_end - s->buf_ptr, size);
@@ -120,13 +174,13 @@ void put_buffer(ByteIOContext *s, const unsigned char *buf, int size)
     }
 }
 
-void put_flush_packet(ByteIOContext *s)
+void avio_flush(AVIOContext *s)
 {
     flush_buffer(s);
     s->must_flush = 0;
 }
 
-int64_t url_fseek(ByteIOContext *s, int64_t offset, int whence)
+int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
 {
     int64_t offset1;
     int64_t pos;
@@ -152,7 +206,9 @@ int64_t url_fseek(ByteIOContext *s, int64_t offset, int whence)
         offset1 >= 0 && offset1 <= (s->buf_end - s->buffer)) {
         /* can do the seek inside the buffer */
         s->buf_ptr = s->buffer + offset1;
-    } else if(s->is_streamed && !s->write_flag && offset1 >= 0 &&
+    } else if ((!s->seekable ||
+               offset1 <= s->buf_end + SHORT_SEEK_THRESHOLD - s->buffer) &&
+               !s->write_flag && offset1 >= 0 &&
               (whence != SEEK_END || force)) {
         while(s->pos < offset && !s->eof_reached)
             fill_buffer(s);
@@ -181,17 +237,20 @@ int64_t url_fseek(ByteIOContext *s, int64_t offset, int whence)
     return offset;
 }
 
-void url_fskip(ByteIOContext *s, int64_t offset)
+#if FF_API_OLD_AVIO
+int url_fskip(AVIOContext *s, int64_t offset)
 {
-    url_fseek(s, offset, SEEK_CUR);
+    int64_t ret = avio_seek(s, offset, SEEK_CUR);
+    return ret < 0 ? ret : 0;
 }
 
-int64_t url_ftell(ByteIOContext *s)
+int64_t url_ftell(AVIOContext *s)
 {
-    return url_fseek(s, 0, SEEK_CUR);
+    return avio_seek(s, 0, SEEK_CUR);
 }
+#endif
 
-int64_t url_fsize(ByteIOContext *s)
+int64_t avio_size(AVIOContext *s)
 {
     int64_t size;
 
@@ -210,97 +269,274 @@ int64_t url_fsize(ByteIOContext *s)
     return size;
 }
 
-int url_feof(ByteIOContext *s)
+#if FF_API_OLD_AVIO
+int url_feof(AVIOContext *s)
 {
     if(!s)
         return 0;
     return s->eof_reached;
 }
 
-int url_ferror(ByteIOContext *s)
+int url_ferror(AVIOContext *s)
 {
     if(!s)
         return 0;
     return s->error;
 }
+#endif
 
-void put_le32(ByteIOContext *s, unsigned int val)
+void avio_wl32(AVIOContext *s, unsigned int val)
 {
-    put_byte(s, val);
-    put_byte(s, val >> 8);
-    put_byte(s, val >> 16);
-    put_byte(s, val >> 24);
+    avio_w8(s, val);
+    avio_w8(s, val >> 8);
+    avio_w8(s, val >> 16);
+    avio_w8(s, val >> 24);
 }
 
-void put_be32(ByteIOContext *s, unsigned int val)
+void avio_wb32(AVIOContext *s, unsigned int val)
 {
-    put_byte(s, val >> 24);
-    put_byte(s, val >> 16);
-    put_byte(s, val >> 8);
-    put_byte(s, val);
+    avio_w8(s, val >> 24);
+    avio_w8(s, val >> 16);
+    avio_w8(s, val >> 8);
+    avio_w8(s, val);
 }
 
-void put_strz(ByteIOContext *s, const char *str)
+#if FF_API_OLD_AVIO
+void put_strz(AVIOContext *s, const char *str)
 {
-    if (str)
-        put_buffer(s, (const unsigned char *) str, strlen(str) + 1);
-    else
-        put_byte(s, 0);
+    avio_put_str(s, str);
+}
+
+#define GET(name, type) \
+    type get_be ##name(AVIOContext *s) \
+{\
+    return avio_rb ##name(s);\
+}\
+    type get_le ##name(AVIOContext *s) \
+{\
+    return avio_rl ##name(s);\
+}
+
+GET(16, unsigned int)
+GET(24, unsigned int)
+GET(32, unsigned int)
+GET(64, uint64_t)
+
+#undef GET
+
+#define PUT(name, type ) \
+    void put_le ##name(AVIOContext *s, type val)\
+{\
+        avio_wl ##name(s, val);\
+}\
+    void put_be ##name(AVIOContext *s, type val)\
+{\
+        avio_wb ##name(s, val);\
+}
+
+PUT(16, unsigned int)
+PUT(24, unsigned int)
+PUT(32, unsigned int)
+PUT(64, uint64_t)
+#undef PUT
+
+int get_byte(AVIOContext *s)
+{
+   return avio_r8(s);
+}
+int get_buffer(AVIOContext *s, unsigned char *buf, int size)
+{
+    return avio_read(s, buf, size);
+}
+int get_partial_buffer(AVIOContext *s, unsigned char *buf, int size)
+{
+    return ffio_read_partial(s, buf, size);
+}
+void put_byte(AVIOContext *s, int val)
+{
+    avio_w8(s, val);
+}
+void put_buffer(AVIOContext *s, const unsigned char *buf, int size)
+{
+    avio_write(s, buf, size);
+}
+void put_nbyte(AVIOContext *s, int b, int count)
+{
+    ffio_fill(s, b, count);
+}
+
+int url_fopen(AVIOContext **s, const char *filename, int flags)
+{
+    return avio_open(s, filename, flags);
+}
+int url_fclose(AVIOContext *s)
+{
+    return avio_close(s);
+}
+int64_t url_fseek(AVIOContext *s, int64_t offset, int whence)
+{
+    return avio_seek(s, offset, whence);
+}
+int64_t url_fsize(AVIOContext *s)
+{
+    return avio_size(s);
+}
+int url_setbufsize(AVIOContext *s, int buf_size)
+{
+    return ffio_set_buf_size(s, buf_size);
+}
+int url_fprintf(AVIOContext *s, const char *fmt, ...)
+{
+    va_list ap;
+    char buf[4096];
+    int ret;
+
+    va_start(ap, fmt);
+    ret = vsnprintf(buf, sizeof(buf), fmt, ap);
+    va_end(ap);
+    avio_write(s, buf, strlen(buf));
+    return ret;
+}
+void put_flush_packet(AVIOContext *s)
+{
+    avio_flush(s);
+}
+int av_url_read_fpause(AVIOContext *s, int pause)
+{
+    return avio_pause(s, pause);
+}
+int64_t av_url_read_fseek(AVIOContext *s, int stream_index,
+                         int64_t timestamp, int flags)
+{
+    return avio_seek_time(s, stream_index, timestamp, flags);
+}
+void init_checksum(AVIOContext *s,
+                   unsigned long (*update_checksum)(unsigned long c, const uint8_t *p, unsigned int len),
+                   unsigned long checksum)
+{
+    ffio_init_checksum(s, update_checksum, checksum);
+}
+unsigned long get_checksum(AVIOContext *s)
+{
+    return ffio_get_checksum(s);
+}
+int url_open_dyn_buf(AVIOContext **s)
+{
+    return avio_open_dyn_buf(s);
+}
+int url_open_dyn_packet_buf(AVIOContext **s, int max_packet_size)
+{
+    return ffio_open_dyn_packet_buf(s, max_packet_size);
+}
+int url_close_dyn_buf(AVIOContext *s, uint8_t **pbuffer)
+{
+    return avio_close_dyn_buf(s, pbuffer);
 }
+int url_fdopen(AVIOContext **s, URLContext *h)
+{
+    return ffio_fdopen(s, h);
+}
+#endif
 
-void put_le64(ByteIOContext *s, uint64_t val)
+int avio_put_str(AVIOContext *s, const char *str)
 {
-    put_le32(s, (uint32_t)(val & 0xffffffff));
-    put_le32(s, (uint32_t)(val >> 32));
+    int len = 1;
+    if (str) {
+        len += strlen(str);
+        avio_write(s, (const unsigned char *) str, len);
+    } else
+        avio_w8(s, 0);
+    return len;
 }
 
-void put_be64(ByteIOContext *s, uint64_t val)
+int avio_put_str16le(AVIOContext *s, const char *str)
 {
-    put_be32(s, (uint32_t)(val >> 32));
-    put_be32(s, (uint32_t)(val & 0xffffffff));
+    const uint8_t *q = str;
+    int ret = 0;
+
+    while (*q) {
+        uint32_t ch;
+        uint16_t tmp;
+
+        GET_UTF8(ch, *q++, break;)
+        PUT_UTF16(ch, tmp, avio_wl16(s, tmp);ret += 2;)
+    }
+    avio_wl16(s, 0);
+    ret += 2;
+    return ret;
 }
 
-void put_le16(ByteIOContext *s, unsigned int val)
+int ff_get_v_length(uint64_t val){
+    int i=1;
+
+    while(val>>=7)
+        i++;
+
+    return i;
+}
+
+void ff_put_v(AVIOContext *bc, uint64_t val){
+    int i= ff_get_v_length(val);
+
+    while(--i>0)
+        avio_w8(bc, 128 | (val>>(7*i)));
+
+    avio_w8(bc, val&127);
+}
+
+void avio_wl64(AVIOContext *s, uint64_t val)
+{
+    avio_wl32(s, (uint32_t)(val & 0xffffffff));
+    avio_wl32(s, (uint32_t)(val >> 32));
+}
+
+void avio_wb64(AVIOContext *s, uint64_t val)
+{
+    avio_wb32(s, (uint32_t)(val >> 32));
+    avio_wb32(s, (uint32_t)(val & 0xffffffff));
+}
+
+void avio_wl16(AVIOContext *s, unsigned int val)
 {
-    put_byte(s, val);
-    put_byte(s, val >> 8);
+    avio_w8(s, val);
+    avio_w8(s, val >> 8);
 }
 
-void put_be16(ByteIOContext *s, unsigned int val)
+void avio_wb16(AVIOContext *s, unsigned int val)
 {
-    put_byte(s, val >> 8);
-    put_byte(s, val);
+    avio_w8(s, val >> 8);
+    avio_w8(s, val);
 }
 
-void put_le24(ByteIOContext *s, unsigned int val)
+void avio_wl24(AVIOContext *s, unsigned int val)
 {
-    put_le16(s, val & 0xffff);
-    put_byte(s, val >> 16);
+    avio_wl16(s, val & 0xffff);
+    avio_w8(s, val >> 16);
 }
 
-void put_be24(ByteIOContext *s, unsigned int val)
+void avio_wb24(AVIOContext *s, unsigned int val)
 {
-    put_be16(s, val >> 8);
-    put_byte(s, val);
+    avio_wb16(s, val >> 8);
+    avio_w8(s, val);
 }
 
-void put_tag(ByteIOContext *s, const char *tag)
+#if FF_API_OLD_AVIO
+void put_tag(AVIOContext *s, const char *tag)
 {
     while (*tag) {
-        put_byte(s, *tag++);
+        avio_w8(s, *tag++);
     }
 }
+#endif
 
 /* Input stream */
 
-static void fill_buffer(ByteIOContext *s)
+static void fill_buffer(AVIOContext *s)
 {
-    uint8_t *dst= !s->max_packet_size && s->buf_end - s->buffer < s->buffer_size ? s->buf_ptr : s->buffer;
+    uint8_t *dst= !s->max_packet_size && s->buf_end - s->buffer < s->buffer_size ? s->buf_end : s->buffer;
     int len= s->buffer_size - (dst - s->buffer);
     int max_buffer_size = s->max_packet_size ? s->max_packet_size : IO_BUFFER_SIZE;
 
-    assert(s->buf_ptr == s->buf_end);
-
     /* no need to do anything if EOF already reached */
     if (s->eof_reached)
         return;
@@ -313,7 +549,7 @@ static void fill_buffer(ByteIOContext *s)
 
     /* make buffer smaller in case it ended up large after probing */
     if (s->buffer_size > max_buffer_size) {
-        url_setbufsize(s, max_buffer_size);
+        ffio_set_buf_size(s, max_buffer_size);
 
         s->checksum_ptr = dst = s->buffer;
         len = s->buffer_size;
@@ -342,14 +578,14 @@ unsigned long ff_crc04C11DB7_update(unsigned long checksum, const uint8_t *buf,
     return av_crc(av_crc_get_table(AV_CRC_32_IEEE), checksum, buf, len);
 }
 
-unsigned long get_checksum(ByteIOContext *s)
+unsigned long ffio_get_checksum(AVIOContext *s)
 {
     s->checksum= s->update_checksum(s->checksum, s->checksum_ptr, s->buf_ptr - s->checksum_ptr);
     s->update_checksum= NULL;
     return s->checksum;
 }
 
-void init_checksum(ByteIOContext *s,
+void ffio_init_checksum(AVIOContext *s,
                    unsigned long (*update_checksum)(unsigned long c, const uint8_t *p, unsigned int len),
                    unsigned long checksum)
 {
@@ -361,33 +597,27 @@ void init_checksum(ByteIOContext *s,
 }
 
 /* XXX: put an inline version */
-int get_byte(ByteIOContext *s)
+int avio_r8(AVIOContext *s)
 {
-    if (s->buf_ptr < s->buf_end) {
-        return *s->buf_ptr++;
-    } else {
+    if (s->buf_ptr >= s->buf_end)
         fill_buffer(s);
-        if (s->buf_ptr < s->buf_end)
-            return *s->buf_ptr++;
-        else
-            return 0;
-    }
+    if (s->buf_ptr < s->buf_end)
+        return *s->buf_ptr++;
+    return 0;
 }
 
-int url_fgetc(ByteIOContext *s)
+#if FF_API_OLD_AVIO
+int url_fgetc(AVIOContext *s)
 {
-    if (s->buf_ptr < s->buf_end) {
-        return *s->buf_ptr++;
-    } else {
+    if (s->buf_ptr >= s->buf_end)
         fill_buffer(s);
-        if (s->buf_ptr < s->buf_end)
-            return *s->buf_ptr++;
-        else
-            return URL_EOF;
-    }
+    if (s->buf_ptr < s->buf_end)
+        return *s->buf_ptr++;
+    return URL_EOF;
 }
+#endif
 
-int get_buffer(ByteIOContext *s, unsigned char *buf, int size)
+int avio_read(AVIOContext *s, unsigned char *buf, int size)
 {
     int len, size1;
 
@@ -428,13 +658,13 @@ int get_buffer(ByteIOContext *s, unsigned char *buf, int size)
         }
     }
     if (size1 == size) {
-        if (url_ferror(s)) return url_ferror(s);
-        if (url_feof(s))   return AVERROR_EOF;
+        if (s->error)         return s->error;
+        if (s->eof_reached)   return AVERROR_EOF;
     }
     return size1 - size;
 }
 
-int get_partial_buffer(ByteIOContext *s, unsigned char *buf, int size)
+int ffio_read_partial(AVIOContext *s, unsigned char *buf, int size)
 {
     int len;
 
@@ -451,107 +681,154 @@ int get_partial_buffer(ByteIOContext *s, unsigned char *buf, int size)
     memcpy(buf, s->buf_ptr, len);
     s->buf_ptr += len;
     if (!len) {
-        if (url_ferror(s)) return url_ferror(s);
-        if (url_feof(s))   return AVERROR_EOF;
+        if (s->error)         return s->error;
+        if (s->eof_reached)   return AVERROR_EOF;
     }
     return len;
 }
 
-unsigned int get_le16(ByteIOContext *s)
+unsigned int avio_rl16(AVIOContext *s)
 {
     unsigned int val;
-    val = get_byte(s);
-    val |= get_byte(s) << 8;
+    val = avio_r8(s);
+    val |= avio_r8(s) << 8;
     return val;
 }
 
-unsigned int get_le24(ByteIOContext *s)
+unsigned int avio_rl24(AVIOContext *s)
 {
     unsigned int val;
-    val = get_le16(s);
-    val |= get_byte(s) << 16;
+    val = avio_rl16(s);
+    val |= avio_r8(s) << 16;
     return val;
 }
 
-unsigned int get_le32(ByteIOContext *s)
+unsigned int avio_rl32(AVIOContext *s)
 {
     unsigned int val;
-    val = get_le16(s);
-    val |= get_le16(s) << 16;
+    val = avio_rl16(s);
+    val |= avio_rl16(s) << 16;
     return val;
 }
 
-uint64_t get_le64(ByteIOContext *s)
+uint64_t avio_rl64(AVIOContext *s)
 {
     uint64_t val;
-    val = (uint64_t)get_le32(s);
-    val |= (uint64_t)get_le32(s) << 32;
+    val = (uint64_t)avio_rl32(s);
+    val |= (uint64_t)avio_rl32(s) << 32;
     return val;
 }
 
-unsigned int get_be16(ByteIOContext *s)
+unsigned int avio_rb16(AVIOContext *s)
 {
     unsigned int val;
-    val = get_byte(s) << 8;
-    val |= get_byte(s);
+    val = avio_r8(s) << 8;
+    val |= avio_r8(s);
     return val;
 }
 
-unsigned int get_be24(ByteIOContext *s)
+unsigned int avio_rb24(AVIOContext *s)
 {
     unsigned int val;
-    val = get_be16(s) << 8;
-    val |= get_byte(s);
+    val = avio_rb16(s) << 8;
+    val |= avio_r8(s);
     return val;
 }
-unsigned int get_be32(ByteIOContext *s)
+unsigned int avio_rb32(AVIOContext *s)
 {
     unsigned int val;
-    val = get_be16(s) << 16;
-    val |= get_be16(s);
+    val = avio_rb16(s) << 16;
+    val |= avio_rb16(s);
     return val;
 }
 
-char *get_strz(ByteIOContext *s, char *buf, int maxlen)
+#if FF_API_OLD_AVIO
+char *get_strz(AVIOContext *s, char *buf, int maxlen)
+{
+    avio_get_str(s, INT_MAX, buf, maxlen);
+    return buf;
+}
+#endif
+
+int ff_get_line(AVIOContext *s, char *buf, int maxlen)
 {
     int i = 0;
     char c;
 
-    while ((c = get_byte(s))) {
-        if (i < maxlen-1)
+    do {
+        c = avio_r8(s);
+        if (c && i < maxlen-1)
             buf[i++] = c;
-    }
+    } while (c != '\n' && c);
 
-    buf[i] = 0; /* Ensure null terminated, but may be truncated */
+    buf[i] = 0;
+    return i;
+}
 
-    return buf;
+int avio_get_str(AVIOContext *s, int maxlen, char *buf, int buflen)
+{
+    int i;
+
+    // reserve 1 byte for terminating 0
+    buflen = FFMIN(buflen - 1, maxlen);
+    for (i = 0; i < buflen; i++)
+        if (!(buf[i] = avio_r8(s)))
+            return i + 1;
+    if (buflen)
+        buf[i] = 0;
+    for (; i < maxlen; i++)
+        if (!avio_r8(s))
+            return i + 1;
+    return maxlen;
 }
 
-uint64_t get_be64(ByteIOContext *s)
+#define GET_STR16(type, read) \
+    int avio_get_str16 ##type(AVIOContext *pb, int maxlen, char *buf, int buflen)\
+{\
+    char* q = buf;\
+    int ret = 0;\
+    while (ret + 1 < maxlen) {\
+        uint8_t tmp;\
+        uint32_t ch;\
+        GET_UTF16(ch, (ret += 2) <= maxlen ? read(pb) : 0, break;)\
+        if (!ch)\
+            break;\
+        PUT_UTF8(ch, tmp, if (q - buf < buflen - 1) *q++ = tmp;)\
+    }\
+    *q = 0;\
+    return ret;\
+}\
+
+GET_STR16(le, avio_rl16)
+GET_STR16(be, avio_rb16)
+
+#undef GET_STR16
+
+uint64_t avio_rb64(AVIOContext *s)
 {
     uint64_t val;
-    val = (uint64_t)get_be32(s) << 32;
-    val |= (uint64_t)get_be32(s);
+    val = (uint64_t)avio_rb32(s) << 32;
+    val |= (uint64_t)avio_rb32(s);
     return val;
 }
 
-uint64_t ff_get_v(ByteIOContext *bc){
+uint64_t ffio_read_varlen(AVIOContext *bc){
     uint64_t val = 0;
     int tmp;
 
     do{
-        tmp = get_byte(bc);
+        tmp = avio_r8(bc);
         val= (val<<7) + (tmp&127);
     }while(tmp&128);
     return val;
 }
 
-int url_fdopen(ByteIOContext **s, URLContext *h)
+int ffio_fdopen(AVIOContext **s, URLContext *h)
 {
     uint8_t *buffer;
     int buffer_size, max_packet_size;
 
-    max_packet_size = url_get_max_packet_size(h);
+    max_packet_size = h->max_packet_size;
     if (max_packet_size) {
         buffer_size = max_packet_size; /* no need to bufferize more than one packet */
     } else {
@@ -561,20 +838,23 @@ int url_fdopen(ByteIOContext **s, URLContext *h)
     if (!buffer)
         return AVERROR(ENOMEM);
 
-    *s = av_mallocz(sizeof(ByteIOContext));
+    *s = av_mallocz(sizeof(AVIOContext));
     if(!*s) {
         av_free(buffer);
         return AVERROR(ENOMEM);
     }
 
-    if (init_put_byte(*s, buffer, buffer_size,
-                      (h->flags & URL_WRONLY || h->flags & URL_RDWR), h,
-                      url_read, url_write, url_seek) < 0) {
+    if (ffio_init_context(*s, buffer, buffer_size,
+                      (h->flags & AVIO_WRONLY || h->flags & AVIO_RDWR), h,
+                      ffurl_read, ffurl_write, ffurl_seek) < 0) {
         av_free(buffer);
         av_freep(s);
         return AVERROR(EIO);
     }
+#if FF_API_OLD_AVIO
     (*s)->is_streamed = h->is_streamed;
+#endif
+    (*s)->seekable = h->is_streamed ? 0 : AVIO_SEEKABLE_NORMAL;
     (*s)->max_packet_size = max_packet_size;
     if(h->prot) {
         (*s)->read_pause = (int (*)(void *, int))h->prot->url_read_pause;
@@ -583,7 +863,7 @@ int url_fdopen(ByteIOContext **s, URLContext *h)
     return 0;
 }
 
-int url_setbufsize(ByteIOContext *s, int buf_size)
+int ffio_set_buf_size(AVIOContext *s, int buf_size)
 {
     uint8_t *buffer;
     buffer = av_malloc(buf_size);
@@ -594,25 +874,24 @@ int url_setbufsize(ByteIOContext *s, int buf_size)
     s->buffer = buffer;
     s->buffer_size = buf_size;
     s->buf_ptr = buffer;
-    url_resetbuf(s, s->write_flag ? URL_WRONLY : URL_RDONLY);
+    url_resetbuf(s, s->write_flag ? AVIO_WRONLY : AVIO_RDONLY);
     return 0;
 }
 
-#if LIBAVFORMAT_VERSION_MAJOR < 53
-int url_resetbuf(ByteIOContext *s, int flags)
+#if FF_API_URL_RESETBUF
+int url_resetbuf(AVIOContext *s, int flags)
 #else
-static int url_resetbuf(ByteIOContext *s, int flags)
+static int url_resetbuf(AVIOContext *s, int flags)
 #endif
 {
-#if LIBAVFORMAT_VERSION_MAJOR < 53
-    URLContext *h = s->opaque;
-    if ((flags & URL_RDWR) || (h && h->flags != flags && !h->flags & URL_RDWR))
+#if FF_API_URL_RESETBUF
+    if (flags & AVIO_RDWR)
         return AVERROR(EINVAL);
 #else
-    assert(flags == URL_WRONLY || flags == URL_RDONLY);
+    assert(flags == AVIO_WRONLY || flags == AVIO_RDONLY);
 #endif
 
-    if (flags & URL_WRONLY) {
+    if (flags & AVIO_WRONLY) {
         s->buf_end = s->buffer + s->buffer_size;
         s->write_flag = 1;
     } else {
@@ -622,11 +901,11 @@ static int url_resetbuf(ByteIOContext *s, int flags)
     return 0;
 }
 
-int ff_rewind_with_probe_data(ByteIOContext *s, unsigned char *buf, int buf_size)
+int ffio_rewind_with_probe_data(AVIOContext *s, unsigned char *buf, int buf_size)
 {
     int64_t buffer_start;
     int buffer_size;
-    int overlap, new_size;
+    int overlap, new_size, alloc_size;
 
     if (s->write_flag)
         return AVERROR(EINVAL);
@@ -640,17 +919,20 @@ int ff_rewind_with_probe_data(ByteIOContext *s, unsigned char *buf, int buf_size
     overlap = buf_size - buffer_start;
     new_size = buf_size + buffer_size - overlap;
 
-    if (new_size > buf_size) {
-        if (!(buf = av_realloc(buf, new_size)))
+    alloc_size = FFMAX(s->buffer_size, new_size);
+    if (alloc_size > buf_size)
+        if (!(buf = av_realloc(buf, alloc_size)))
             return AVERROR(ENOMEM);
 
+    if (new_size > buf_size) {
         memcpy(buf + buf_size, s->buffer + overlap, buffer_size - overlap);
         buf_size = new_size;
     }
 
     av_free(s->buffer);
     s->buf_ptr = s->buffer = buf;
-    s->pos = s->buffer_size = buf_size;
+    s->buffer_size = alloc_size;
+    s->pos = buf_size;
     s->buf_end = s->buf_ptr + buf_size;
     s->eof_reached = 0;
     s->must_flush = 0;
@@ -658,38 +940,39 @@ int ff_rewind_with_probe_data(ByteIOContext *s, unsigned char *buf, int buf_size
     return 0;
 }
 
-int url_fopen(ByteIOContext **s, const char *filename, int flags)
+int avio_open(AVIOContext **s, const char *filename, int flags)
 {
     URLContext *h;
     int err;
 
-    err = url_open(&h, filename, flags);
+    err = ffurl_open(&h, filename, flags);
     if (err < 0)
         return err;
-    err = url_fdopen(s, h);
+    err = ffio_fdopen(s, h);
     if (err < 0) {
-        url_close(h);
+        ffurl_close(h);
         return err;
     }
     return 0;
 }
 
-int url_fclose(ByteIOContext *s)
+int avio_close(AVIOContext *s)
 {
     URLContext *h = s->opaque;
 
     av_free(s->buffer);
     av_free(s);
-    return url_close(h);
+    return ffurl_close(h);
 }
 
-URLContext *url_fileno(ByteIOContext *s)
+#if FF_API_OLD_AVIO
+URLContext *url_fileno(AVIOContext *s)
 {
     return s->opaque;
 }
+#endif
 
-#if CONFIG_MUXERS
-int url_fprintf(ByteIOContext *s, const char *fmt, ...)
+int avio_printf(AVIOContext *s, const char *fmt, ...)
 {
     va_list ap;
     char buf[4096];
@@ -698,46 +981,47 @@ int url_fprintf(ByteIOContext *s, const char *fmt, ...)
     va_start(ap, fmt);
     ret = vsnprintf(buf, sizeof(buf), fmt, ap);
     va_end(ap);
-    put_buffer(s, buf, strlen(buf));
+    avio_write(s, buf, strlen(buf));
     return ret;
 }
-#endif //CONFIG_MUXERS
 
-char *url_fgets(ByteIOContext *s, char *buf, int buf_size)
+#if FF_API_OLD_AVIO
+char *url_fgets(AVIOContext *s, char *buf, int buf_size)
 {
     int c;
     char *q;
 
-    c = url_fgetc(s);
-    if (c == EOF)
+    c = avio_r8(s);
+    if (s->eof_reached)
         return NULL;
     q = buf;
     for(;;) {
-        if (c == EOF || c == '\n')
+        if (s->eof_reached || c == '\n')
             break;
         if ((q - buf) < buf_size - 1)
             *q++ = c;
-        c = url_fgetc(s);
+        c = avio_r8(s);
     }
     if (buf_size > 0)
         *q = '\0';
     return buf;
 }
 
-int url_fget_max_packet_size(ByteIOContext *s)
+int url_fget_max_packet_size(AVIOContext *s)
 {
     return s->max_packet_size;
 }
+#endif
 
-int av_url_read_fpause(ByteIOContext *s, int pause)
+int avio_pause(AVIOContext *s, int pause)
 {
     if (!s->read_pause)
         return AVERROR(ENOSYS);
     return s->read_pause(s->opaque, pause);
 }
 
-int64_t av_url_read_fseek(ByteIOContext *s, int stream_index,
-                          int64_t timestamp, int flags)
+int64_t avio_seek_time(AVIOContext *s, int stream_index,
+                       int64_t timestamp, int flags)
 {
     URLContext *h = s->opaque;
     int64_t ret;
@@ -756,29 +1040,28 @@ int64_t av_url_read_fseek(ByteIOContext *s, int stream_index,
     return ret;
 }
 
-/* url_open_dyn_buf and url_close_dyn_buf are used in rtp.c to send a response
- * back to the server even if CONFIG_MUXERS is false. */
-#if CONFIG_MUXERS || CONFIG_NETWORK
 /* buffer handling */
-int url_open_buf(ByteIOContext **s, uint8_t *buf, int buf_size, int flags)
+#if FF_API_OLD_AVIO
+int url_open_buf(AVIOContext **s, uint8_t *buf, int buf_size, int flags)
 {
     int ret;
-    *s = av_mallocz(sizeof(ByteIOContext));
+    *s = av_mallocz(sizeof(AVIOContext));
     if(!*s)
         return AVERROR(ENOMEM);
-    ret = init_put_byte(*s, buf, buf_size,
-                        (flags & URL_WRONLY || flags & URL_RDWR),
+    ret = ffio_init_context(*s, buf, buf_size,
+                        (flags & AVIO_WRONLY || flags & AVIO_RDWR),
                         NULL, NULL, NULL, NULL);
     if(ret != 0)
         av_freep(s);
     return ret;
 }
 
-int url_close_buf(ByteIOContext *s)
+int url_close_buf(AVIOContext *s)
 {
-    put_flush_packet(s);
+    avio_flush(s);
     return s->buf_ptr - s->buffer;
 }
+#endif
 
 /* output in a dynamic buffer */
 
@@ -848,10 +1131,9 @@ static int64_t dyn_buf_seek(void *opaque, int64_t offset, int whence)
     return 0;
 }
 
-static int url_open_dyn_buf_internal(ByteIOContext **s, int max_packet_size)
+static int url_open_dyn_buf_internal(AVIOContext **s, int max_packet_size)
 {
     DynBuffer *d;
-    int ret;
     unsigned io_buffer_size = max_packet_size ? max_packet_size : 1024;
 
     if(sizeof(DynBuffer) + io_buffer_size < io_buffer_size)
@@ -859,48 +1141,48 @@ static int url_open_dyn_buf_internal(ByteIOContext **s, int max_packet_size)
     d = av_mallocz(sizeof(DynBuffer) + io_buffer_size);
     if (!d)
         return AVERROR(ENOMEM);
-    *s = av_mallocz(sizeof(ByteIOContext));
+    d->io_buffer_size = io_buffer_size;
+    *s = avio_alloc_context(d->io_buffer, d->io_buffer_size, 1, d, NULL,
+                            max_packet_size ? dyn_packet_buf_write : dyn_buf_write,
+                            max_packet_size ? NULL : dyn_buf_seek);
     if(!*s) {
         av_free(d);
         return AVERROR(ENOMEM);
     }
-    d->io_buffer_size = io_buffer_size;
-    ret = init_put_byte(*s, d->io_buffer, io_buffer_size,
-                        1, d, NULL,
-                        max_packet_size ? dyn_packet_buf_write : dyn_buf_write,
-                        max_packet_size ? NULL : dyn_buf_seek);
-    if (ret == 0) {
-        (*s)->max_packet_size = max_packet_size;
-    } else {
-        av_free(d);
-        av_freep(s);
-    }
-    return ret;
+    (*s)->max_packet_size = max_packet_size;
+    return 0;
 }
 
-int url_open_dyn_buf(ByteIOContext **s)
+int avio_open_dyn_buf(AVIOContext **s)
 {
     return url_open_dyn_buf_internal(s, 0);
 }
 
-int url_open_dyn_packet_buf(ByteIOContext **s, int max_packet_size)
+int ffio_open_dyn_packet_buf(AVIOContext **s, int max_packet_size)
 {
     if (max_packet_size <= 0)
         return -1;
     return url_open_dyn_buf_internal(s, max_packet_size);
 }
 
-int url_close_dyn_buf(ByteIOContext *s, uint8_t **pbuffer)
+int avio_close_dyn_buf(AVIOContext *s, uint8_t **pbuffer)
 {
     DynBuffer *d = s->opaque;
     int size;
+    static const char padbuf[FF_INPUT_BUFFER_PADDING_SIZE] = {0};
+    int padding = 0;
+
+    /* don't attempt to pad fixed-size packet buffers */
+    if (!s->max_packet_size) {
+        avio_write(s, padbuf, sizeof(padbuf));
+        padding = FF_INPUT_BUFFER_PADDING_SIZE;
+    }
 
-    put_flush_packet(s);
+    avio_flush(s);
 
     *pbuffer = d->buffer;
     size = d->size;
     av_free(d);
     av_free(s);
-    return size;
+    return size - padding;
 }
-#endif /* CONFIG_MUXERS || CONFIG_NETWORK */
diff --git a/libavformat/avisynth.c b/libavformat/avisynth.c
index e2a8a3c..5e6f6bf 100644
--- a/libavformat/avisynth.c
+++ b/libavformat/avisynth.c
@@ -2,20 +2,20 @@
  * AVISynth support for ffmpeg system
  * Copyright (c) 2006 DivX, Inc.
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -207,7 +207,7 @@ static int avisynth_read_seek(AVFormatContext *s, int stream_index, int64_t pts,
   return 0;
 }
 
-AVInputFormat avisynth_demuxer = {
+AVInputFormat ff_avisynth_demuxer = {
   "avs",
   NULL_IF_CONFIG_SMALL("AVISynth"),
   sizeof(AVISynthContext),
diff --git a/libavformat/avlanguage.c b/libavformat/avlanguage.c
index 525bf07..787382e 100644
--- a/libavformat/avlanguage.c
+++ b/libavformat/avlanguage.c
@@ -1,20 +1,20 @@
 /*
  * Cyril Comparon, Larbi Joubala, Resonate-MP4 2009
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavformat/avlanguage.h b/libavformat/avlanguage.h
index eac0031..2ec3e2d 100644
--- a/libavformat/avlanguage.h
+++ b/libavformat/avlanguage.h
@@ -1,20 +1,20 @@
 /*
  * Cyril Comparon, Larbi Joubala, Resonate-MP4 2009
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -31,8 +31,8 @@ enum AVLangCodespace {
 };
 
 /**
- * Converts a language code to a target codespace. The source codespace is guessed.
- * Returns NULL if the provided lang is null or invalid.
+ * Convert a language code to a target codespace. The source codespace is guessed.
+ * @return NULL if the provided lang is null or invalid.
  */
 const char *av_convert_lang_to(const char *lang, enum AVLangCodespace target_codespace);
 
diff --git a/libavformat/avs.c b/libavformat/avs.c
index caf3a89..bd9b31d 100644
--- a/libavformat/avs.c
+++ b/libavformat/avs.c
@@ -2,20 +2,20 @@
  * AVS demuxer.
  * Copyright (c) 2006  Aurelien Jacobs <aurel at gnuage.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -61,12 +61,12 @@ static int avs_read_header(AVFormatContext * s, AVFormatParameters * ap)
 
     s->ctx_flags |= AVFMTCTX_NOHEADER;
 
-    url_fskip(s->pb, 4);
-    avs->width = get_le16(s->pb);
-    avs->height = get_le16(s->pb);
-    avs->bits_per_sample = get_le16(s->pb);
-    avs->fps = get_le16(s->pb);
-    avs->nb_frames = get_le32(s->pb);
+    avio_skip(s->pb, 4);
+    avs->width = avio_rl16(s->pb);
+    avs->height = avio_rl16(s->pb);
+    avs->bits_per_sample = avio_rl16(s->pb);
+    avs->fps = avio_rl16(s->pb);
+    avs->nb_frames = avio_rl32(s->pb);
     avs->remaining_frame_size = 0;
     avs->remaining_audio_size = 0;
 
@@ -104,7 +104,7 @@ avs_read_video_packet(AVFormatContext * s, AVPacket * pkt,
     pkt->data[palette_size + 1] = type;
     pkt->data[palette_size + 2] = size & 0xFF;
     pkt->data[palette_size + 3] = (size >> 8) & 0xFF;
-    ret = get_buffer(s->pb, pkt->data + palette_size + 4, size - 4) + 4;
+    ret = avio_read(s->pb, pkt->data + palette_size + 4, size - 4) + 4;
     if (ret < size) {
         av_free_packet(pkt);
         return AVERROR(EIO);
@@ -123,9 +123,9 @@ static int avs_read_audio_packet(AVFormatContext * s, AVPacket * pkt)
     AvsFormat *avs = s->priv_data;
     int ret, size;
 
-    size = url_ftell(s->pb);
+    size = avio_tell(s->pb);
     ret = voc_get_packet(s, pkt, avs->st_audio, avs->remaining_audio_size);
-    size = url_ftell(s->pb) - size;
+    size = avio_tell(s->pb) - size;
     avs->remaining_audio_size -= size;
 
     if (ret == AVERROR(EIO))
@@ -154,20 +154,20 @@ static int avs_read_packet(AVFormatContext * s, AVPacket * pkt)
 
     while (1) {
         if (avs->remaining_frame_size <= 0) {
-            if (!get_le16(s->pb))    /* found EOF */
+            if (!avio_rl16(s->pb))    /* found EOF */
                 return AVERROR(EIO);
-            avs->remaining_frame_size = get_le16(s->pb) - 4;
+            avs->remaining_frame_size = avio_rl16(s->pb) - 4;
         }
 
         while (avs->remaining_frame_size > 0) {
-            sub_type = get_byte(s->pb);
-            type = get_byte(s->pb);
-            size = get_le16(s->pb);
+            sub_type = avio_r8(s->pb);
+            type = avio_r8(s->pb);
+            size = avio_rl16(s->pb);
             avs->remaining_frame_size -= size;
 
             switch (type) {
             case AVS_PALETTE:
-                ret = get_buffer(s->pb, palette, size - 4);
+                ret = avio_read(s->pb, palette, size - 4);
                 if (ret < size - 4)
                     return AVERROR(EIO);
                 palette_size = size;
@@ -204,7 +204,7 @@ static int avs_read_packet(AVFormatContext * s, AVPacket * pkt)
                 break;
 
             default:
-                url_fskip(s->pb, size - 4);
+                avio_skip(s->pb, size - 4);
             }
         }
     }
@@ -215,7 +215,7 @@ static int avs_read_close(AVFormatContext * s)
     return 0;
 }
 
-AVInputFormat avs_demuxer = {
+AVInputFormat ff_avs_demuxer = {
     "avs",
     NULL_IF_CONFIG_SMALL("AVS format"),
     sizeof(AvsFormat),
diff --git a/libavformat/bethsoftvid.c b/libavformat/bethsoftvid.c
index 4f9d1c1..01e6f55 100644
--- a/libavformat/bethsoftvid.c
+++ b/libavformat/bethsoftvid.c
@@ -2,20 +2,20 @@
  * Bethsoft VID format Demuxer
  * Copyright (c) 2007 Nicholas Tung
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -60,15 +60,15 @@ static int vid_read_header(AVFormatContext *s,
                             AVFormatParameters *ap)
 {
     BVID_DemuxContext *vid = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVStream *stream;
 
     /* load main header. Contents:
     *    bytes: 'V' 'I' 'D'
     *    int16s: always_512, nframes, width, height, delay, always_14
     */
-    url_fseek(pb, 5, SEEK_CUR);
-    vid->nframes = get_le16(pb);
+    avio_skip(pb, 5);
+    vid->nframes = avio_rl16(pb);
 
     stream = av_new_stream(s, 0);
     if (!stream)
@@ -76,11 +76,11 @@ static int vid_read_header(AVFormatContext *s,
     av_set_pts_info(stream, 32, 1, 60);     // 16 ms increments, i.e. 60 fps
     stream->codec->codec_type = AVMEDIA_TYPE_VIDEO;
     stream->codec->codec_id = CODEC_ID_BETHSOFTVID;
-    stream->codec->width = get_le16(pb);
-    stream->codec->height = get_le16(pb);
+    stream->codec->width = avio_rl16(pb);
+    stream->codec->height = avio_rl16(pb);
     stream->codec->pix_fmt = PIX_FMT_PAL8;
-    vid->bethsoft_global_delay = get_le16(pb);
-    get_le16(pb);
+    vid->bethsoft_global_delay = avio_rl16(pb);
+    avio_rl16(pb);
 
     // done with video codec, set up audio codec
     stream = av_new_stream(s, 0);
@@ -97,7 +97,7 @@ static int vid_read_header(AVFormatContext *s,
 }
 
 #define BUFFER_PADDING_SIZE 1000
-static int read_frame(BVID_DemuxContext *vid, ByteIOContext *pb, AVPacket *pkt,
+static int read_frame(BVID_DemuxContext *vid, AVIOContext *pb, AVPacket *pkt,
                       uint8_t block_type, AVFormatContext *s, int npixels)
 {
     uint8_t * vidbuf_start = NULL;
@@ -112,16 +112,16 @@ static int read_frame(BVID_DemuxContext *vid, ByteIOContext *pb, AVPacket *pkt,
         return AVERROR(ENOMEM);
 
     // save the file position for the packet, include block type
-    position = url_ftell(pb) - 1;
+    position = avio_tell(pb) - 1;
 
     vidbuf_start[vidbuf_nbytes++] = block_type;
 
     // get the video delay (next int16), and set the presentation time
-    vid->video_pts += vid->bethsoft_global_delay + get_le16(pb);
+    vid->video_pts += vid->bethsoft_global_delay + avio_rl16(pb);
 
     // set the y offset if it exists (decoder header data should be in data section)
     if(block_type == VIDEO_YOFF_P_FRAME){
-        if(get_buffer(pb, &vidbuf_start[vidbuf_nbytes], 2) != 2)
+        if(avio_read(pb, &vidbuf_start[vidbuf_nbytes], 2) != 2)
             goto fail;
         vidbuf_nbytes += 2;
     }
@@ -131,22 +131,22 @@ static int read_frame(BVID_DemuxContext *vid, ByteIOContext *pb, AVPacket *pkt,
         if(!vidbuf_start)
             return AVERROR(ENOMEM);
 
-        code = get_byte(pb);
+        code = avio_r8(pb);
         vidbuf_start[vidbuf_nbytes++] = code;
 
         if(code >= 0x80){ // rle sequence
             if(block_type == VIDEO_I_FRAME)
-                vidbuf_start[vidbuf_nbytes++] = get_byte(pb);
+                vidbuf_start[vidbuf_nbytes++] = avio_r8(pb);
         } else if(code){ // plain sequence
-            if(get_buffer(pb, &vidbuf_start[vidbuf_nbytes], code) != code)
+            if(avio_read(pb, &vidbuf_start[vidbuf_nbytes], code) != code)
                 goto fail;
             vidbuf_nbytes += code;
         }
         bytes_copied += code & 0x7F;
         if(bytes_copied == npixels){ // sometimes no stop character is given, need to keep track of bytes copied
             // may contain a 0 byte even if read all pixels
-            if(get_byte(pb))
-                url_fseek(pb, -1, SEEK_CUR);
+            if(avio_r8(pb))
+                avio_seek(pb, -1, SEEK_CUR);
             break;
         }
         if(bytes_copied > npixels)
@@ -174,18 +174,18 @@ static int vid_read_packet(AVFormatContext *s,
                            AVPacket *pkt)
 {
     BVID_DemuxContext *vid = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     unsigned char block_type;
     int audio_length;
     int ret_value;
 
-    if(vid->is_finished || url_feof(pb))
+    if(vid->is_finished || pb->eof_reached)
         return AVERROR(EIO);
 
-    block_type = get_byte(pb);
+    block_type = avio_r8(pb);
     switch(block_type){
         case PALETTE_BLOCK:
-            url_fseek(pb, -1, SEEK_CUR);     // include block type
+            avio_seek(pb, -1, SEEK_CUR);     // include block type
             ret_value = av_get_packet(pb, pkt, 3 * 256 + 1);
             if(ret_value != 3 * 256 + 1){
                 av_free_packet(pkt);
@@ -195,12 +195,12 @@ static int vid_read_packet(AVFormatContext *s,
             return ret_value;
 
         case FIRST_AUDIO_BLOCK:
-            get_le16(pb);
+            avio_rl16(pb);
             // soundblaster DAC used for sample rate, as on specification page (link above)
-            s->streams[1]->codec->sample_rate = 1000000 / (256 - get_byte(pb));
+            s->streams[1]->codec->sample_rate = 1000000 / (256 - avio_r8(pb));
             s->streams[1]->codec->bit_rate = s->streams[1]->codec->channels * s->streams[1]->codec->sample_rate * s->streams[1]->codec->bits_per_coded_sample;
         case AUDIO_BLOCK:
-            audio_length = get_le16(pb);
+            audio_length = avio_rl16(pb);
             ret_value = av_get_packet(pb, pkt, audio_length);
             pkt->stream_index = 1;
             return ret_value != audio_length ? AVERROR(EIO) : ret_value;
@@ -224,7 +224,7 @@ static int vid_read_packet(AVFormatContext *s,
     return 0;
 }
 
-AVInputFormat bethsoftvid_demuxer = {
+AVInputFormat ff_bethsoftvid_demuxer = {
     "bethsoftvid",
     NULL_IF_CONFIG_SMALL("Bethesda Softworks VID format"),
     sizeof(BVID_DemuxContext),
diff --git a/libavformat/bfi.c b/libavformat/bfi.c
index 94014a4..bc26d47 100644
--- a/libavformat/bfi.c
+++ b/libavformat/bfi.c
@@ -2,20 +2,20 @@
  * Brute Force & Ignorance (BFI) demuxer
  * Copyright (c) 2008 Sisir Koppaka
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -49,7 +49,7 @@ static int bfi_probe(AVProbeData * p)
 static int bfi_read_header(AVFormatContext * s, AVFormatParameters * ap)
 {
     BFIContext *bfi = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVStream *vstream;
     AVStream *astream;
     int fps, chunk_header;
@@ -65,25 +65,25 @@ static int bfi_read_header(AVFormatContext * s, AVFormatParameters * ap)
         return AVERROR(ENOMEM);
 
     /* Set the total number of frames. */
-    url_fskip(pb, 8);
-    chunk_header           = get_le32(pb);
-    bfi->nframes           = get_le32(pb);
-    get_le32(pb);
-    get_le32(pb);
-    get_le32(pb);
-    fps                    = get_le32(pb);
-    url_fskip(pb, 12);
-    vstream->codec->width  = get_le32(pb);
-    vstream->codec->height = get_le32(pb);
+    avio_skip(pb, 8);
+    chunk_header           = avio_rl32(pb);
+    bfi->nframes           = avio_rl32(pb);
+    avio_rl32(pb);
+    avio_rl32(pb);
+    avio_rl32(pb);
+    fps                    = avio_rl32(pb);
+    avio_skip(pb, 12);
+    vstream->codec->width  = avio_rl32(pb);
+    vstream->codec->height = avio_rl32(pb);
 
     /*Load the palette to extradata */
-    url_fskip(pb, 8);
+    avio_skip(pb, 8);
     vstream->codec->extradata      = av_malloc(768);
     vstream->codec->extradata_size = 768;
-    get_buffer(pb, vstream->codec->extradata,
+    avio_read(pb, vstream->codec->extradata,
                vstream->codec->extradata_size);
 
-    astream->codec->sample_rate = get_le32(pb);
+    astream->codec->sample_rate = avio_rl32(pb);
 
     /* Set up the video codec... */
     av_set_pts_info(vstream, 32, 1, fps);
@@ -98,7 +98,7 @@ static int bfi_read_header(AVFormatContext * s, AVFormatParameters * ap)
     astream->codec->bits_per_coded_sample = 8;
     astream->codec->bit_rate        =
         astream->codec->sample_rate * astream->codec->bits_per_coded_sample;
-    url_fseek(pb, chunk_header - 3, SEEK_SET);
+    avio_seek(pb, chunk_header - 3, SEEK_SET);
     av_set_pts_info(astream, 64, 1, astream->codec->sample_rate);
     return 0;
 }
@@ -107,9 +107,9 @@ static int bfi_read_header(AVFormatContext * s, AVFormatParameters * ap)
 static int bfi_read_packet(AVFormatContext * s, AVPacket * pkt)
 {
     BFIContext *bfi = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int ret, audio_offset, video_offset, chunk_size, audio_size = 0;
-    if (bfi->nframes == 0 || url_feof(pb)) {
+    if (bfi->nframes == 0 || pb->eof_reached) {
         return AVERROR(EIO);
     }
 
@@ -117,16 +117,16 @@ static int bfi_read_packet(AVFormatContext * s, AVPacket * pkt)
     if (!bfi->avflag) {
         uint32_t state = 0;
         while(state != MKTAG('S','A','V','I')){
-            if (url_feof(pb))
+            if (pb->eof_reached)
                 return AVERROR(EIO);
-            state = 256*state + get_byte(pb);
+            state = 256*state + avio_r8(pb);
         }
         /* Now that the chunk's location is confirmed, we proceed... */
-        chunk_size      = get_le32(pb);
-        get_le32(pb);
-        audio_offset    = get_le32(pb);
-        get_le32(pb);
-        video_offset    = get_le32(pb);
+        chunk_size      = avio_rl32(pb);
+        avio_rl32(pb);
+        audio_offset    = avio_rl32(pb);
+        avio_rl32(pb);
+        video_offset    = avio_rl32(pb);
         audio_size      = video_offset - audio_offset;
         bfi->video_size = chunk_size - video_offset;
 
@@ -158,7 +158,7 @@ static int bfi_read_packet(AVFormatContext * s, AVPacket * pkt)
     return ret;
 }
 
-AVInputFormat bfi_demuxer = {
+AVInputFormat ff_bfi_demuxer = {
     "bfi",
     NULL_IF_CONFIG_SMALL("Brute Force & Ignorance"),
     sizeof(BFIContext),
diff --git a/libavformat/bink.c b/libavformat/bink.c
index afa629f..76b457c 100644
--- a/libavformat/bink.c
+++ b/libavformat/bink.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2008-2010 Peter Ross (pross at xvid.org)
  * Copyright (c) 2009 Daniel Verkamp (daniel at drv.nu)
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -70,7 +70,7 @@ static int probe(AVProbeData *p)
 static int read_header(AVFormatContext *s, AVFormatParameters *ap)
 {
     BinkDemuxContext *bink = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     uint32_t fps_num, fps_den;
     AVStream *vst, *ast;
     unsigned int i;
@@ -82,29 +82,29 @@ static int read_header(AVFormatContext *s, AVFormatParameters *ap)
     if (!vst)
         return AVERROR(ENOMEM);
 
-    vst->codec->codec_tag = get_le32(pb);
+    vst->codec->codec_tag = avio_rl32(pb);
 
-    bink->file_size = get_le32(pb) + 8;
-    vst->duration   = get_le32(pb);
+    bink->file_size = avio_rl32(pb) + 8;
+    vst->duration   = avio_rl32(pb);
 
     if (vst->duration > 1000000) {
         av_log(s, AV_LOG_ERROR, "invalid header: more than 1000000 frames\n");
         return AVERROR(EIO);
     }
 
-    if (get_le32(pb) > bink->file_size) {
+    if (avio_rl32(pb) > bink->file_size) {
         av_log(s, AV_LOG_ERROR,
                "invalid header: largest frame size greater than file size\n");
         return AVERROR(EIO);
     }
 
-    url_fskip(pb, 4);
+    avio_skip(pb, 4);
 
-    vst->codec->width  = get_le32(pb);
-    vst->codec->height = get_le32(pb);
+    vst->codec->width  = avio_rl32(pb);
+    vst->codec->height = avio_rl32(pb);
 
-    fps_num = get_le32(pb);
-    fps_den = get_le32(pb);
+    fps_num = avio_rl32(pb);
+    fps_den = avio_rl32(pb);
     if (fps_num == 0 || fps_den == 0) {
         av_log(s, AV_LOG_ERROR, "invalid header: invalid fps (%d/%d)\n", fps_num, fps_den);
         return AVERROR(EIO);
@@ -115,9 +115,9 @@ static int read_header(AVFormatContext *s, AVFormatParameters *ap)
     vst->codec->codec_id   = CODEC_ID_BINKVIDEO;
     vst->codec->extradata  = av_mallocz(4 + FF_INPUT_BUFFER_PADDING_SIZE);
     vst->codec->extradata_size = 4;
-    get_buffer(pb, vst->codec->extradata, 4);
+    avio_read(pb, vst->codec->extradata, 4);
 
-    bink->num_audio_tracks = get_le32(pb);
+    bink->num_audio_tracks = avio_rl32(pb);
 
     if (bink->num_audio_tracks > BINK_MAX_AUDIO_TRACKS) {
         av_log(s, AV_LOG_ERROR,
@@ -127,34 +127,35 @@ static int read_header(AVFormatContext *s, AVFormatParameters *ap)
     }
 
     if (bink->num_audio_tracks) {
-        url_fskip(pb, 4 * bink->num_audio_tracks);
+        avio_skip(pb, 4 * bink->num_audio_tracks);
 
         for (i = 0; i < bink->num_audio_tracks; i++) {
             ast = av_new_stream(s, 1);
             if (!ast)
                 return AVERROR(ENOMEM);
             ast->codec->codec_type  = AVMEDIA_TYPE_AUDIO;
-            ast->codec->codec_tag   = 0;
-            ast->codec->sample_rate = get_le16(pb);
+            ast->codec->codec_tag   = vst->codec->codec_tag;
+            ast->codec->sample_rate = avio_rl16(pb);
             av_set_pts_info(ast, 64, 1, ast->codec->sample_rate);
-            flags = get_le16(pb);
+            flags = avio_rl16(pb);
             ast->codec->codec_id = flags & BINK_AUD_USEDCT ?
                                    CODEC_ID_BINKAUDIO_DCT : CODEC_ID_BINKAUDIO_RDFT;
             ast->codec->channels = flags & BINK_AUD_STEREO ? 2 : 1;
         }
 
-        url_fskip(pb, 4 * bink->num_audio_tracks);
+        for (i = 0; i < bink->num_audio_tracks; i++)
+            s->streams[i + 1]->id = avio_rl32(pb);
     }
 
     /* frame index table */
-    next_pos = get_le32(pb);
+    next_pos = avio_rl32(pb);
     for (i = 0; i < vst->duration; i++) {
         pos = next_pos;
         if (i == vst->duration - 1) {
             next_pos = bink->file_size;
             keyframe = 0;
         } else {
-            next_pos = get_le32(pb);
+            next_pos = avio_rl32(pb);
             keyframe = pos & 1;
         }
         pos &= ~1;
@@ -168,7 +169,7 @@ static int read_header(AVFormatContext *s, AVFormatParameters *ap)
                            keyframe ? AVINDEX_KEYFRAME : 0);
     }
 
-    url_fskip(pb, 4);
+    avio_skip(pb, 4);
 
     bink->current_track = -1;
     return 0;
@@ -177,7 +178,7 @@ static int read_header(AVFormatContext *s, AVFormatParameters *ap)
 static int read_packet(AVFormatContext *s, AVPacket *pkt)
 {
     BinkDemuxContext *bink = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int ret;
 
     if (bink->current_track < 0) {
@@ -201,7 +202,7 @@ static int read_packet(AVFormatContext *s, AVPacket *pkt)
     }
 
     while (bink->current_track < bink->num_audio_tracks) {
-        uint32_t audio_size = get_le32(pb);
+        uint32_t audio_size = avio_rl32(pb);
         if (audio_size > bink->remain_packet_size - 4) {
             av_log(s, AV_LOG_ERROR,
                    "frame %"PRId64": audio size in header (%u) > size of packet left (%u)\n",
@@ -224,7 +225,7 @@ static int read_packet(AVFormatContext *s, AVPacket *pkt)
                     AV_RL32(pkt->data) / (2 * s->streams[bink->current_track]->codec->channels);
             return 0;
         } else {
-            url_fseek(pb, audio_size, SEEK_CUR);
+            avio_skip(pb, audio_size);
         }
     }
 
@@ -246,18 +247,18 @@ static int read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, in
     BinkDemuxContext *bink = s->priv_data;
     AVStream *vst = s->streams[0];
 
-    if (url_is_streamed(s->pb))
+    if (!s->pb->seekable)
         return -1;
 
     /* seek to the first frame */
-    url_fseek(s->pb, vst->index_entries[0].pos, SEEK_SET);
+    avio_seek(s->pb, vst->index_entries[0].pos, SEEK_SET);
     bink->video_pts = 0;
     memset(bink->audio_pts, 0, sizeof(bink->audio_pts));
     bink->current_track = -1;
     return 0;
 }
 
-AVInputFormat bink_demuxer = {
+AVInputFormat ff_bink_demuxer = {
     "bink",
     NULL_IF_CONFIG_SMALL("Bink"),
     sizeof(BinkDemuxContext),
diff --git a/libavformat/c93.c b/libavformat/c93.c
index 033b36b..097565a 100644
--- a/libavformat/c93.c
+++ b/libavformat/c93.c
@@ -2,20 +2,20 @@
  * Interplay C93 demuxer
  * Copyright (c) 2007 Anssi Hannula <anssi.hannula at gmail.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -60,15 +60,15 @@ static int read_header(AVFormatContext *s,
                            AVFormatParameters *ap)
 {
     AVStream *video;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     C93DemuxContext *c93 = s->priv_data;
     int i;
     int framecount = 0;
 
     for (i = 0; i < 512; i++) {
-        c93->block_records[i].index = get_le16(pb);
-        c93->block_records[i].length = get_byte(pb);
-        c93->block_records[i].frames = get_byte(pb);
+        c93->block_records[i].index = avio_rl16(pb);
+        c93->block_records[i].length = avio_r8(pb);
+        c93->block_records[i].frames = avio_r8(pb);
         if (c93->block_records[i].frames > 32) {
             av_log(s, AV_LOG_ERROR, "too many frames in block\n");
             return AVERROR_INVALIDDATA;
@@ -89,7 +89,7 @@ static int read_header(AVFormatContext *s,
     video->codec->height = 192;
     /* 4:3 320x200 with 8 empty lines */
     video->sample_aspect_ratio = (AVRational) { 5, 6 };
-    video->time_base = (AVRational) { 2, 25 };
+    av_set_pts_info(video, 64, 2, 25);
     video->nb_frames = framecount;
     video->duration = framecount;
     video->start_time = 0;
@@ -105,7 +105,7 @@ static int read_header(AVFormatContext *s,
 
 static int read_packet(AVFormatContext *s, AVPacket *pkt)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     C93DemuxContext *c93 = s->priv_data;
     C93BlockRecord *br = &c93->block_records[c93->current_block];
     int datasize;
@@ -114,7 +114,7 @@ static int read_packet(AVFormatContext *s, AVPacket *pkt)
     if (c93->next_pkt_is_audio) {
         c93->current_frame++;
         c93->next_pkt_is_audio = 0;
-        datasize = get_le16(pb);
+        datasize = avio_rl16(pb);
         if (datasize > 42) {
             if (!c93->audio) {
                 c93->audio = av_new_stream(s, 1);
@@ -122,7 +122,7 @@ static int read_packet(AVFormatContext *s, AVPacket *pkt)
                     return AVERROR(ENOMEM);
                 c93->audio->codec->codec_type = AVMEDIA_TYPE_AUDIO;
             }
-            url_fskip(pb, 26); /* VOC header */
+            avio_skip(pb, 26); /* VOC header */
             ret = voc_get_packet(s, pkt, c93->audio, datasize - 26);
             if (ret > 0) {
                 pkt->stream_index = 1;
@@ -140,15 +140,15 @@ static int read_packet(AVFormatContext *s, AVPacket *pkt)
     }
 
     if (c93->current_frame == 0) {
-        url_fseek(pb, br->index * 2048, SEEK_SET);
+        avio_seek(pb, br->index * 2048, SEEK_SET);
         for (i = 0; i < 32; i++) {
-            c93->frame_offsets[i] = get_le32(pb);
+            c93->frame_offsets[i] = avio_rl32(pb);
         }
     }
 
-    url_fseek(pb,br->index * 2048 +
+    avio_seek(pb,br->index * 2048 +
             c93->frame_offsets[c93->current_frame], SEEK_SET);
-    datasize = get_le16(pb); /* video frame size */
+    datasize = avio_rl16(pb); /* video frame size */
 
     ret = av_new_packet(pkt, datasize + 768 + 1);
     if (ret < 0)
@@ -156,13 +156,13 @@ static int read_packet(AVFormatContext *s, AVPacket *pkt)
     pkt->data[0] = 0;
     pkt->size = datasize + 1;
 
-    ret = get_buffer(pb, pkt->data + 1, datasize);
+    ret = avio_read(pb, pkt->data + 1, datasize);
     if (ret < datasize) {
         ret = AVERROR(EIO);
         goto fail;
     }
 
-    datasize = get_le16(pb); /* palette size */
+    datasize = avio_rl16(pb); /* palette size */
     if (datasize) {
         if (datasize != 768) {
             av_log(s, AV_LOG_ERROR, "invalid palette size %u\n", datasize);
@@ -170,7 +170,7 @@ static int read_packet(AVFormatContext *s, AVPacket *pkt)
             goto fail;
         }
         pkt->data[0] |= C93_HAS_PALETTE;
-        ret = get_buffer(pb, pkt->data + pkt->size, datasize);
+        ret = avio_read(pb, pkt->data + pkt->size, datasize);
         if (ret < datasize) {
             ret = AVERROR(EIO);
             goto fail;
@@ -192,7 +192,7 @@ static int read_packet(AVFormatContext *s, AVPacket *pkt)
     return ret;
 }
 
-AVInputFormat c93_demuxer = {
+AVInputFormat ff_c93_demuxer = {
     "c93",
     NULL_IF_CONFIG_SMALL("Interplay C93"),
     sizeof(C93DemuxContext),
diff --git a/libavformat/caf.c b/libavformat/caf.c
index a814ab0..c204c90 100644
--- a/libavformat/caf.c
+++ b/libavformat/caf.c
@@ -2,20 +2,20 @@
  * CAF common code
  * Copyright (c) 2007  Justin Ruggles
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,7 +25,7 @@
  */
 
 #include "avformat.h"
-#include "riff.h"
+#include "internal.h"
 #include "caf.h"
 
 /**
diff --git a/libavformat/caf.h b/libavformat/caf.h
index e1f93a6..7ca4dc5 100644
--- a/libavformat/caf.h
+++ b/libavformat/caf.h
@@ -2,20 +2,20 @@
  * CAF common code
  * Copyright (c) 2007  Justin Ruggles
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -27,7 +27,7 @@
 #ifndef AVFORMAT_CAF_H
 #define AVFORMAT_CAF_H
 
-#include "riff.h"
+#include "internal.h"
 
 extern const AVCodecTag ff_codec_caf_tags[];
 
diff --git a/libavformat/cafdec.c b/libavformat/cafdec.c
index c020579..c720c34 100644
--- a/libavformat/cafdec.c
+++ b/libavformat/cafdec.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2007 Justin Ruggles
  * Copyright (c) 2009 Peter Ross
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -53,7 +53,7 @@ static int probe(AVProbeData *p)
 /** Read audio description chunk */
 static int read_desc_chunk(AVFormatContext *s)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     CaffContext *caf  = s->priv_data;
     AVStream *st;
     int flags;
@@ -65,14 +65,14 @@ static int read_desc_chunk(AVFormatContext *s)
 
     /* parse format description */
     st->codec->codec_type  = AVMEDIA_TYPE_AUDIO;
-    st->codec->sample_rate = av_int2dbl(get_be64(pb));
-    st->codec->codec_tag   = get_be32(pb);
-    flags = get_be32(pb);
-    caf->bytes_per_packet  = get_be32(pb);
+    st->codec->sample_rate = av_int2dbl(avio_rb64(pb));
+    st->codec->codec_tag   = avio_rb32(pb);
+    flags = avio_rb32(pb);
+    caf->bytes_per_packet  = avio_rb32(pb);
     st->codec->block_align = caf->bytes_per_packet;
-    caf->frames_per_packet = get_be32(pb);
-    st->codec->channels    = get_be32(pb);
-    st->codec->bits_per_coded_sample = get_be32(pb);
+    caf->frames_per_packet = avio_rb32(pb);
+    st->codec->channels    = avio_rb32(pb);
+    st->codec->bits_per_coded_sample = avio_rb32(pb);
 
     /* calculate bit rate for constant size packets */
     if (caf->frames_per_packet > 0 && caf->bytes_per_packet > 0) {
@@ -93,7 +93,7 @@ static int read_desc_chunk(AVFormatContext *s)
 /** Read magic cookie chunk */
 static int read_kuki_chunk(AVFormatContext *s, int64_t size)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVStream *st      = s->streams[0];
 
     if (size < 0 || size > INT_MAX - FF_INPUT_BUFFER_PADDING_SIZE)
@@ -106,20 +106,35 @@ static int read_kuki_chunk(AVFormatContext *s, int64_t size)
         int strt, skip;
         MOVAtom atom;
 
-        strt = url_ftell(pb);
+        strt = avio_tell(pb);
         ff_mov_read_esds(s, pb, atom);
-        skip = size - (url_ftell(pb) - strt);
+        skip = size - (avio_tell(pb) - strt);
         if (skip < 0 || !st->codec->extradata ||
             st->codec->codec_id != CODEC_ID_AAC) {
             av_log(s, AV_LOG_ERROR, "invalid AAC magic cookie\n");
             return AVERROR_INVALIDDATA;
         }
-        url_fskip(pb, skip);
+        avio_skip(pb, skip);
+    } else if (st->codec->codec_id == CODEC_ID_ALAC) {
+#define ALAC_PREAMBLE 12
+#define ALAC_HEADER   36
+        if (size < ALAC_PREAMBLE + ALAC_HEADER) {
+            av_log(s, AV_LOG_ERROR, "invalid ALAC magic cookie\n");
+            avio_skip(pb, size);
+            return AVERROR_INVALIDDATA;
+        }
+        avio_skip(pb, ALAC_PREAMBLE);
+        st->codec->extradata = av_mallocz(ALAC_HEADER + FF_INPUT_BUFFER_PADDING_SIZE);
+        if (!st->codec->extradata)
+            return AVERROR(ENOMEM);
+        avio_read(pb, st->codec->extradata, ALAC_HEADER);
+        st->codec->extradata_size = ALAC_HEADER;
+        avio_skip(pb, size - ALAC_PREAMBLE - ALAC_HEADER);
     } else {
         st->codec->extradata = av_mallocz(size + FF_INPUT_BUFFER_PADDING_SIZE);
         if (!st->codec->extradata)
             return AVERROR(ENOMEM);
-        get_buffer(pb, st->codec->extradata, size);
+        avio_read(pb, st->codec->extradata, size);
         st->codec->extradata_size = size;
     }
 
@@ -129,21 +144,21 @@ static int read_kuki_chunk(AVFormatContext *s, int64_t size)
 /** Read packet table chunk */
 static int read_pakt_chunk(AVFormatContext *s, int64_t size)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVStream *st      = s->streams[0];
     CaffContext *caf  = s->priv_data;
     int64_t pos = 0, ccount;
     int num_packets, i;
 
-    ccount = url_ftell(pb);
+    ccount = avio_tell(pb);
 
-    num_packets = get_be64(pb);
+    num_packets = avio_rb64(pb);
     if (num_packets < 0 || INT32_MAX / sizeof(AVIndexEntry) < num_packets)
         return AVERROR_INVALIDDATA;
 
-    st->nb_frames  = get_be64(pb); /* valid frames */
-    st->nb_frames += get_be32(pb); /* priming frames */
-    st->nb_frames += get_be32(pb); /* remainder frames */
+    st->nb_frames  = avio_rb64(pb); /* valid frames */
+    st->nb_frames += avio_rb32(pb); /* priming frames */
+    st->nb_frames += avio_rb32(pb); /* remainder frames */
 
     st->duration = 0;
     for (i = 0; i < num_packets; i++) {
@@ -152,7 +167,7 @@ static int read_pakt_chunk(AVFormatContext *s, int64_t size)
         st->duration += caf->frames_per_packet ? caf->frames_per_packet : ff_mp4_read_descr_len(pb);
     }
 
-    if (url_ftell(pb) - ccount != size) {
+    if (avio_tell(pb) - ccount != size) {
         av_log(s, AV_LOG_ERROR, "error reading packet table\n");
         return -1;
     }
@@ -164,14 +179,14 @@ static int read_pakt_chunk(AVFormatContext *s, int64_t size)
 /** Read information chunk */
 static void read_info_chunk(AVFormatContext *s, int64_t size)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     unsigned int i;
-    unsigned int nb_entries = get_be32(pb);
+    unsigned int nb_entries = avio_rb32(pb);
     for (i = 0; i < nb_entries; i++) {
         char key[32];
         char value[1024];
-        get_strz(pb, key, sizeof(key));
-        get_strz(pb, value, sizeof(value));
+        avio_get_str(pb, INT_MAX, key,   sizeof(key));
+        avio_get_str(pb, INT_MAX, value, sizeof(value));
         av_metadata_set2(&s->metadata, key, value, 0);
     }
 }
@@ -179,21 +194,21 @@ static void read_info_chunk(AVFormatContext *s, int64_t size)
 static int read_header(AVFormatContext *s,
                        AVFormatParameters *ap)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     CaffContext *caf  = s->priv_data;
     AVStream *st;
     uint32_t tag = 0;
     int found_data, ret;
     int64_t size;
 
-    url_fskip(pb, 8); /* magic, version, file flags */
+    avio_skip(pb, 8); /* magic, version, file flags */
 
     /* audio description chunk */
-    if (get_be32(pb) != MKBETAG('d','e','s','c')) {
+    if (avio_rb32(pb) != MKBETAG('d','e','s','c')) {
         av_log(s, AV_LOG_ERROR, "desc chunk not present\n");
         return AVERROR_INVALIDDATA;
     }
-    size = get_be64(pb);
+    size = avio_rb64(pb);
     if (size != 32)
         return AVERROR_INVALIDDATA;
 
@@ -204,25 +219,25 @@ static int read_header(AVFormatContext *s,
 
     /* parse each chunk */
     found_data = 0;
-    while (!url_feof(pb)) {
+    while (!pb->eof_reached) {
 
         /* stop at data chunk if seeking is not supported or
            data chunk size is unknown */
-        if (found_data && (caf->data_size < 0 || url_is_streamed(pb)))
+        if (found_data && (caf->data_size < 0 || !pb->seekable))
             break;
 
-        tag  = get_be32(pb);
-        size = get_be64(pb);
-        if (url_feof(pb))
+        tag  = avio_rb32(pb);
+        size = avio_rb64(pb);
+        if (pb->eof_reached)
             break;
 
         switch (tag) {
         case MKBETAG('d','a','t','a'):
-            url_fskip(pb, 4); /* edit count */
-            caf->data_start = url_ftell(pb);
+            avio_skip(pb, 4); /* edit count */
+            caf->data_start = avio_tell(pb);
             caf->data_size  = size < 0 ? -1 : size - 4;
-            if (caf->data_size > 0 && !url_is_streamed(pb))
-                url_fskip(pb, caf->data_size);
+            if (caf->data_size > 0 && pb->seekable)
+                avio_skip(pb, caf->data_size);
             found_data = 1;
             break;
 
@@ -250,7 +265,7 @@ static int read_header(AVFormatContext *s,
         case MKBETAG('f','r','e','e'):
             if (size < 0)
                 return AVERROR_INVALIDDATA;
-            url_fskip(pb, size);
+            avio_skip(pb, size);
             break;
         }
     }
@@ -269,7 +284,7 @@ static int read_header(AVFormatContext *s,
                                 "block size or frame size are variable.\n");
         return AVERROR_INVALIDDATA;
     }
-    s->file_size = url_fsize(pb);
+    s->file_size = avio_size(pb);
     s->file_size = FFMAX(0, s->file_size);
 
     av_set_pts_info(st, 64, 1, st->codec->sample_rate);
@@ -277,7 +292,7 @@ static int read_header(AVFormatContext *s,
 
     /* position the stream at the start of data */
     if (caf->data_size >= 0)
-        url_fseek(pb, caf->data_start, SEEK_SET);
+        avio_seek(pb, caf->data_start, SEEK_SET);
 
     return 0;
 }
@@ -286,18 +301,18 @@ static int read_header(AVFormatContext *s,
 
 static int read_packet(AVFormatContext *s, AVPacket *pkt)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVStream *st      = s->streams[0];
     CaffContext *caf  = s->priv_data;
     int res, pkt_size = 0, pkt_frames = 0;
     int64_t left      = CAF_MAX_PKT_SIZE;
 
-    if (url_feof(pb))
+    if (pb->eof_reached)
         return AVERROR(EIO);
 
     /* don't read past end of data chunk */
     if (caf->data_size > 0) {
-        left = (caf->data_start + caf->data_size) - url_ftell(pb);
+        left = (caf->data_start + caf->data_size) - avio_tell(pb);
         if (left <= 0)
             return AVERROR(EIO);
     }
@@ -362,11 +377,11 @@ static int read_seek(AVFormatContext *s, int stream_index,
         return -1;
     }
 
-    url_fseek(s->pb, pos + caf->data_start, SEEK_SET);
+    avio_seek(s->pb, pos + caf->data_start, SEEK_SET);
     return 0;
 }
 
-AVInputFormat caf_demuxer = {
+AVInputFormat ff_caf_demuxer = {
     "caf",
     NULL_IF_CONFIG_SMALL("Apple Core Audio Format"),
     sizeof(CaffContext),
diff --git a/libavformat/cavsvideodec.c b/libavformat/cavsvideodec.c
new file mode 100644
index 0000000..f58c56f
--- /dev/null
+++ b/libavformat/cavsvideodec.c
@@ -0,0 +1,77 @@
+/*
+ * RAW Chinese AVS video demuxer
+ * Copyright (c) 2009  Stefan Gehrer <stefan.gehrer at gmx.de>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "avformat.h"
+#include "rawdec.h"
+
+#define CAVS_SEQ_START_CODE       0x000001b0
+#define CAVS_PIC_I_START_CODE     0x000001b3
+#define CAVS_UNDEF_START_CODE     0x000001b4
+#define CAVS_PIC_PB_START_CODE    0x000001b6
+#define CAVS_VIDEO_EDIT_CODE      0x000001b7
+#define CAVS_PROFILE_JIZHUN       0x20
+
+static int cavsvideo_probe(AVProbeData *p)
+{
+    uint32_t code= -1;
+    int pic=0, seq=0, slice_pos = 0;
+    int i;
+
+    for(i=0; i<p->buf_size; i++){
+        code = (code<<8) + p->buf[i];
+        if ((code & 0xffffff00) == 0x100) {
+            if(code < CAVS_SEQ_START_CODE) {
+                /* slices have to be consecutive */
+                if(code < slice_pos)
+                    return 0;
+                slice_pos = code;
+            } else {
+                slice_pos = 0;
+            }
+            if (code == CAVS_SEQ_START_CODE) {
+                seq++;
+                /* check for the only currently supported profile */
+                if(p->buf[i+1] != CAVS_PROFILE_JIZHUN)
+                    return 0;
+            } else if ((code == CAVS_PIC_I_START_CODE) ||
+                       (code == CAVS_PIC_PB_START_CODE)) {
+                pic++;
+            } else if ((code == CAVS_UNDEF_START_CODE) ||
+                       (code >  CAVS_VIDEO_EDIT_CODE)) {
+                return 0;
+            }
+        }
+    }
+    if(seq && seq*9<=pic*10)
+        return AVPROBE_SCORE_MAX/2;
+    return 0;
+}
+
+AVInputFormat ff_cavsvideo_demuxer = {
+    "cavsvideo",
+    NULL_IF_CONFIG_SMALL("raw Chinese AVS video"),
+    0,
+    cavsvideo_probe,
+    ff_raw_video_read_header,
+    ff_raw_read_partial_packet,
+    .flags= AVFMT_GENERIC_INDEX,
+    .value = CODEC_ID_CAVS,
+};
diff --git a/libavformat/cdg.c b/libavformat/cdg.c
index 2f4fb27..b47a20e 100644
--- a/libavformat/cdg.c
+++ b/libavformat/cdg.c
@@ -2,20 +2,20 @@
  * CD Graphics Demuxer
  * Copyright (c) 2009 Michael Tison
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -38,7 +38,7 @@ static int read_header(AVFormatContext *s, AVFormatParameters *ap)
     /// 75 sectors/sec * 4 packets/sector = 300 packets/sec
     av_set_pts_info(vst, 32, 1, 300);
 
-    ret = url_fsize(s->pb);
+    ret = avio_size(s->pb);
     if (ret > 0)
         vst->duration = (ret * vst->time_base.den) / (CDG_PACKET_SIZE * 300);
 
@@ -55,7 +55,7 @@ static int read_packet(AVFormatContext *s, AVPacket *pkt)
     return ret;
 }
 
-AVInputFormat cdg_demuxer = {
+AVInputFormat ff_cdg_demuxer = {
     "cdg",
     NULL_IF_CONFIG_SMALL("CD Graphics Format"),
     0,
diff --git a/libavformat/concat.c b/libavformat/concat.c
index 3a19d0a..da9bee2 100644
--- a/libavformat/concat.c
+++ b/libavformat/concat.c
@@ -4,26 +4,27 @@
  * Copyright (c) 2007 Wolfram Gloger
  * Copyright (c) 2010 Michele Orrù
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "avformat.h"
 #include "libavutil/avstring.h"
 #include "libavutil/mem.h"
+#include "url.h"
 
 #define AV_CAT_SEPARATOR "|"
 
@@ -46,7 +47,7 @@ static av_cold int concat_close(URLContext *h)
     struct concat_nodes *nodes = data->nodes;
 
     for (i = 0; i != data->length; i++)
-        err |= url_close(nodes[i].uc);
+        err |= ffurl_close(nodes[i].uc);
 
     av_freep(&data->nodes);
     av_freep(&h->priv_data);
@@ -100,12 +101,12 @@ static av_cold int concat_open(URLContext *h, const char *uri, int flags)
         uri += len + strspn(uri+len, AV_CAT_SEPARATOR);
 
         /* creating URLContext */
-        if ((err = url_open(&uc, node_uri, flags)) < 0)
+        if ((err = ffurl_open(&uc, node_uri, flags)) < 0)
             break;
 
         /* creating size */
-        if ((size = url_filesize(uc)) < 0) {
-            url_close(uc);
+        if ((size = ffurl_size(uc)) < 0) {
+            ffurl_close(uc);
             err = AVERROR(ENOSYS);
             break;
         }
@@ -135,12 +136,12 @@ static int concat_read(URLContext *h, unsigned char *buf, int size)
     size_t i = data->current;
 
     while (size > 0) {
-        result = url_read(nodes[i].uc, buf, size);
+        result = ffurl_read(nodes[i].uc, buf, size);
         if (result < 0)
             return total ? total : result;
         if (!result)
             if (i + 1 == data->length ||
-                url_seek(nodes[++i].uc, 0, SEEK_SET) < 0)
+                ffurl_seek(nodes[++i].uc, 0, SEEK_SET) < 0)
                 break;
         total += result;
         buf   += result;
@@ -168,7 +169,7 @@ static int64_t concat_seek(URLContext *h, int64_t pos, int whence)
         /* get the absolute position */
         for (i = 0; i != data->current; i++)
             pos += nodes[i].size;
-        pos += url_seek(nodes[i].uc, 0, SEEK_CUR);
+        pos += ffurl_seek(nodes[i].uc, 0, SEEK_CUR);
         whence = SEEK_SET;
         /* fall through with the absolute position */
     case SEEK_SET:
@@ -179,7 +180,7 @@ static int64_t concat_seek(URLContext *h, int64_t pos, int whence)
         return AVERROR(EINVAL);
     }
 
-    result = url_seek(nodes[i].uc, pos, whence);
+    result = ffurl_seek(nodes[i].uc, pos, whence);
     if (result >= 0) {
         data->current = i;
         while (i)
@@ -188,11 +189,10 @@ static int64_t concat_seek(URLContext *h, int64_t pos, int whence)
     return result;
 }
 
-URLProtocol concat_protocol = {
-    "concat",
-    concat_open,
-    concat_read,
-    NULL,
-    concat_seek,
-    concat_close,
+URLProtocol ff_concat_protocol = {
+    .name      = "concat",
+    .url_open  = concat_open,
+    .url_read  = concat_read,
+    .url_seek  = concat_seek,
+    .url_close = concat_close,
 };
diff --git a/libavformat/crcenc.c b/libavformat/crcenc.c
index b343464..55c99d9 100644
--- a/libavformat/crcenc.c
+++ b/libavformat/crcenc.c
@@ -2,20 +2,20 @@
  * CRC encoder (for codec/format testing)
  * Copyright (c) 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -49,12 +49,12 @@ static int crc_write_trailer(struct AVFormatContext *s)
     char buf[64];
 
     snprintf(buf, sizeof(buf), "CRC=0x%08x\n", crc->crcval);
-    put_buffer(s->pb, buf, strlen(buf));
-    put_flush_packet(s->pb);
+    avio_write(s->pb, buf, strlen(buf));
+    avio_flush(s->pb);
     return 0;
 }
 
-AVOutputFormat crc_muxer = {
+AVOutputFormat ff_crc_muxer = {
     "crc",
     NULL_IF_CONFIG_SMALL("CRC testing format"),
     NULL,
diff --git a/libavformat/cutils.c b/libavformat/cutils.c
index 5092d99..092aa8a 100644
--- a/libavformat/cutils.c
+++ b/libavformat/cutils.c
@@ -2,20 +2,20 @@
  * Various simple utilities for ffmpeg system
  * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #include "avformat.h"
@@ -24,6 +24,7 @@
 /* add one element to a dynamic array */
 void ff_dynarray_add(intptr_t **tab_ptr, int *nb_ptr, intptr_t elem)
 {
+    /* see similar ffmpeg.c:grow_array() */
     int nb, nb_alloc;
     intptr_t *tab;
 
@@ -41,25 +42,6 @@ void ff_dynarray_add(intptr_t **tab_ptr, int *nb_ptr, intptr_t elem)
     *nb_ptr = nb;
 }
 
-time_t mktimegm(struct tm *tm)
-{
-    time_t t;
-
-    int y = tm->tm_year + 1900, m = tm->tm_mon + 1, d = tm->tm_mday;
-
-    if (m < 3) {
-        m += 12;
-        y--;
-    }
-
-    t = 86400 *
-        (d + (153 * m - 457) / 5 + 365 * y + y / 4 - y / 100 + y / 400 - 719469);
-
-    t += 3600 * tm->tm_hour + 60 * tm->tm_min + tm->tm_sec;
-
-    return t;
-}
-
 #define ISLEAP(y) (((y) % 4 == 0) && (((y) % 100) != 0 || ((y) % 400) == 0))
 #define LEAPS_COUNT(y) ((y)/4 - (y)/100 + (y)/400)
 
@@ -94,94 +76,3 @@ struct tm *brktimegm(time_t secs, struct tm *tm)
 
     return tm;
 }
-
-/* get a positive number between n_min and n_max, for a maximum length
-   of len_max. Return -1 if error. */
-static int date_get_num(const char **pp,
-                        int n_min, int n_max, int len_max)
-{
-    int i, val, c;
-    const char *p;
-
-    p = *pp;
-    val = 0;
-    for(i = 0; i < len_max; i++) {
-        c = *p;
-        if (!isdigit(c))
-            break;
-        val = (val * 10) + c - '0';
-        p++;
-    }
-    /* no number read ? */
-    if (p == *pp)
-        return -1;
-    if (val < n_min || val > n_max)
-        return -1;
-    *pp = p;
-    return val;
-}
-
-/* small strptime for ffmpeg */
-const char *small_strptime(const char *p, const char *fmt,
-                           struct tm *dt)
-{
-    int c, val;
-
-    for(;;) {
-        c = *fmt++;
-        if (c == '\0') {
-            return p;
-        } else if (c == '%') {
-            c = *fmt++;
-            switch(c) {
-            case 'H':
-                val = date_get_num(&p, 0, 23, 2);
-                if (val == -1)
-                    return NULL;
-                dt->tm_hour = val;
-                break;
-            case 'M':
-                val = date_get_num(&p, 0, 59, 2);
-                if (val == -1)
-                    return NULL;
-                dt->tm_min = val;
-                break;
-            case 'S':
-                val = date_get_num(&p, 0, 59, 2);
-                if (val == -1)
-                    return NULL;
-                dt->tm_sec = val;
-                break;
-            case 'Y':
-                val = date_get_num(&p, 0, 9999, 4);
-                if (val == -1)
-                    return NULL;
-                dt->tm_year = val - 1900;
-                break;
-            case 'm':
-                val = date_get_num(&p, 1, 12, 2);
-                if (val == -1)
-                    return NULL;
-                dt->tm_mon = val - 1;
-                break;
-            case 'd':
-                val = date_get_num(&p, 1, 31, 2);
-                if (val == -1)
-                    return NULL;
-                dt->tm_mday = val;
-                break;
-            case '%':
-                goto match;
-            default:
-                return NULL;
-            }
-        } else {
-        match:
-            if (c != *p)
-                return NULL;
-            p++;
-        }
-    }
-    return p;
-}
-
diff --git a/libavformat/daud.c b/libavformat/daud.c
index 9b0e008..1b3cfcf 100644
--- a/libavformat/daud.c
+++ b/libavformat/daud.c
@@ -2,20 +2,20 @@
  * D-Cinema audio demuxer
  * Copyright (c) 2005 Reimar Döffinger
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #include "avformat.h"
@@ -36,12 +36,12 @@ static int daud_header(AVFormatContext *s, AVFormatParameters *ap) {
 }
 
 static int daud_packet(AVFormatContext *s, AVPacket *pkt) {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int ret, size;
-    if (url_feof(pb))
+    if (pb->eof_reached)
         return AVERROR(EIO);
-    size = get_be16(pb);
-    get_be16(pb); // unknown
+    size = avio_rb16(pb);
+    avio_rb16(pb); // unknown
     ret = av_get_packet(pb, pkt, size);
     pkt->stream_index = 0;
     return ret;
@@ -57,15 +57,20 @@ static int daud_write_header(struct AVFormatContext *s)
 
 static int daud_write_packet(struct AVFormatContext *s, AVPacket *pkt)
 {
-    put_be16(s->pb, pkt->size);
-    put_be16(s->pb, 0x8010); // unknown
-    put_buffer(s->pb, pkt->data, pkt->size);
-    put_flush_packet(s->pb);
+    if (pkt->size > 65535) {
+        av_log(s, AV_LOG_ERROR,
+               "Packet size too large for s302m. (%d > 65535)\n", pkt->size);
+        return -1;
+    }
+    avio_wb16(s->pb, pkt->size);
+    avio_wb16(s->pb, 0x8010); // unknown
+    avio_write(s->pb, pkt->data, pkt->size);
+    avio_flush(s->pb);
     return 0;
 }
 
 #if CONFIG_DAUD_DEMUXER
-AVInputFormat daud_demuxer = {
+AVInputFormat ff_daud_demuxer = {
     "daud",
     NULL_IF_CONFIG_SMALL("D-Cinema audio format"),
     0,
@@ -79,7 +84,7 @@ AVInputFormat daud_demuxer = {
 #endif
 
 #if CONFIG_DAUD_MUXER
-AVOutputFormat daud_muxer =
+AVOutputFormat ff_daud_muxer =
 {
     "daud",
     NULL_IF_CONFIG_SMALL("D-Cinema audio format"),
diff --git a/libavformat/dfa.c b/libavformat/dfa.c
new file mode 100644
index 0000000..8108535
--- /dev/null
+++ b/libavformat/dfa.c
@@ -0,0 +1,119 @@
+/*
+ * Chronomaster DFA Format Demuxer
+ * Copyright (c) 2011 Konstantin Shishkov
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "libavutil/intreadwrite.h"
+#include "avformat.h"
+
+static int dfa_probe(AVProbeData *p)
+{
+    if (p->buf_size < 4 || AV_RL32(p->buf) != MKTAG('D', 'F', 'I', 'A'))
+        return 0;
+
+    return AVPROBE_SCORE_MAX;
+}
+
+static int dfa_read_header(AVFormatContext *s,
+                           AVFormatParameters *ap)
+{
+    AVIOContext *pb = s->pb;
+    AVStream *st;
+    int frames;
+    uint32_t mspf;
+
+    if (avio_rl32(pb) != MKTAG('D', 'F', 'I', 'A')) {
+        av_log(s, AV_LOG_ERROR, "Invalid magic for DFA\n");
+        return AVERROR_INVALIDDATA;
+    }
+    avio_skip(pb, 2); // unused
+    frames = avio_rl16(pb);
+
+    st = av_new_stream(s, 0);
+    if (!st)
+        return AVERROR(ENOMEM);
+
+    st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
+    st->codec->codec_id   = CODEC_ID_DFA;
+    st->codec->width      = avio_rl16(pb);
+    st->codec->height     = avio_rl16(pb);
+    mspf = avio_rl32(pb);
+    if (!mspf) {
+        av_log(s, AV_LOG_WARNING, "Zero FPS reported, defaulting to 10\n");
+        mspf = 100;
+    }
+    av_set_pts_info(st, 24, mspf, 1000);
+    avio_skip(pb, 128 - 16); // padding
+    st->duration = frames;
+
+    return 0;
+}
+
+static int dfa_read_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    AVIOContext *pb = s->pb;
+    uint32_t frame_size;
+    int ret, first = 1;
+
+    if (pb->eof_reached)
+        return AVERROR_EOF;
+
+    if (av_get_packet(pb, pkt, 12) != 12)
+        return AVERROR(EIO);
+    while (!pb->eof_reached) {
+        if (!first) {
+            ret = av_append_packet(pb, pkt, 12);
+            if (ret < 0) {
+                av_free_packet(pkt);
+                return ret;
+            }
+        } else
+            first = 0;
+        frame_size = AV_RL32(pkt->data + pkt->size - 8);
+        if (frame_size > INT_MAX - 4) {
+            av_log(s, AV_LOG_ERROR, "Too large chunk size: %d\n", frame_size);
+            return AVERROR(EIO);
+        }
+        if (AV_RL32(pkt->data + pkt->size - 12) == MKTAG('E', 'O', 'F', 'R')) {
+            if (frame_size) {
+                av_log(s, AV_LOG_WARNING, "skipping %d bytes of end-of-frame marker chunk\n",
+                       frame_size);
+                avio_skip(pb, frame_size);
+            }
+            return 0;
+        }
+        ret = av_append_packet(pb, pkt, frame_size);
+        if (ret < 0) {
+            av_free_packet(pkt);
+            return ret;
+        }
+    }
+
+    return 0;
+}
+
+AVInputFormat ff_dfa_demuxer = {
+    "dfa",
+    NULL_IF_CONFIG_SMALL("Chronomaster DFA"),
+    0,
+    dfa_probe,
+    dfa_read_header,
+    dfa_read_packet,
+    .flags = AVFMT_GENERIC_INDEX,
+};
diff --git a/libavformat/diracdec.c b/libavformat/diracdec.c
new file mode 100644
index 0000000..b0cb3bf
--- /dev/null
+++ b/libavformat/diracdec.c
@@ -0,0 +1,43 @@
+/*
+ * RAW Dirac demuxer
+ * Copyright (c) 2007 Marco Gerards <marco at gnu.org>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "libavutil/intreadwrite.h"
+#include "avformat.h"
+#include "rawdec.h"
+
+static int dirac_probe(AVProbeData *p)
+{
+    if (AV_RL32(p->buf) == MKTAG('B', 'B', 'C', 'D'))
+        return AVPROBE_SCORE_MAX;
+    else
+        return 0;
+}
+
+AVInputFormat ff_dirac_demuxer = {
+    "dirac",
+    NULL_IF_CONFIG_SMALL("raw Dirac"),
+    0,
+    dirac_probe,
+    ff_raw_video_read_header,
+    ff_raw_read_partial_packet,
+    .flags= AVFMT_GENERIC_INDEX,
+    .value = CODEC_ID_DIRAC,
+};
diff --git a/libavformat/dnxhddec.c b/libavformat/dnxhddec.c
new file mode 100644
index 0000000..df5d2e3
--- /dev/null
+++ b/libavformat/dnxhddec.c
@@ -0,0 +1,54 @@
+/*
+ * RAW DNxHD (SMPTE VC-3) demuxer
+ * Copyright (c) 2008 Baptiste Coudurier <baptiste.coudurier at gmail.com>
+ * Copyright (c) 2009 Reimar Döffinger <Reimar.Doeffinger at gmx.de>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "libavutil/intreadwrite.h"
+#include "avformat.h"
+#include "rawdec.h"
+
+static int dnxhd_probe(AVProbeData *p)
+{
+    static const uint8_t header[] = {0x00,0x00,0x02,0x80,0x01};
+    int w, h, compression_id;
+    if (p->buf_size < 0x2c)
+        return 0;
+    if (memcmp(p->buf, header, 5))
+        return 0;
+    h = AV_RB16(p->buf + 0x18);
+    w = AV_RB16(p->buf + 0x1a);
+    if (!w || !h)
+        return 0;
+    compression_id = AV_RB32(p->buf + 0x28);
+    if (compression_id < 1237 || compression_id > 1253)
+        return 0;
+    return AVPROBE_SCORE_MAX;
+}
+
+AVInputFormat ff_dnxhd_demuxer = {
+    "dnxhd",
+    NULL_IF_CONFIG_SMALL("raw DNxHD (SMPTE VC-3)"),
+    0,
+    dnxhd_probe,
+    ff_raw_video_read_header,
+    ff_raw_read_partial_packet,
+    .flags= AVFMT_GENERIC_INDEX,
+    .value = CODEC_ID_DNXHD,
+};
diff --git a/libavformat/dsicin.c b/libavformat/dsicin.c
index af5e2d9..d02de46 100644
--- a/libavformat/dsicin.c
+++ b/libavformat/dsicin.c
@@ -2,20 +2,20 @@
  * Delphine Software International CIN File Demuxer
  * Copyright (c) 2006 Gregory Montoir (cyx at users.sourceforge.net)
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -70,19 +70,19 @@ static int cin_probe(AVProbeData *p)
     return AVPROBE_SCORE_MAX;
 }
 
-static int cin_read_file_header(CinDemuxContext *cin, ByteIOContext *pb) {
+static int cin_read_file_header(CinDemuxContext *cin, AVIOContext *pb) {
     CinFileHeader *hdr = &cin->file_header;
 
-    if (get_le32(pb) != 0x55AA0000)
+    if (avio_rl32(pb) != 0x55AA0000)
         return AVERROR_INVALIDDATA;
 
-    hdr->video_frame_size   = get_le32(pb);
-    hdr->video_frame_width  = get_le16(pb);
-    hdr->video_frame_height = get_le16(pb);
-    hdr->audio_frequency    = get_le32(pb);
-    hdr->audio_bits         = get_byte(pb);
-    hdr->audio_stereo       = get_byte(pb);
-    hdr->audio_frame_size   = get_le16(pb);
+    hdr->video_frame_size   = avio_rl32(pb);
+    hdr->video_frame_width  = avio_rl16(pb);
+    hdr->video_frame_height = avio_rl16(pb);
+    hdr->audio_frequency    = avio_rl32(pb);
+    hdr->audio_bits         = avio_r8(pb);
+    hdr->audio_stereo       = avio_r8(pb);
+    hdr->audio_frame_size   = avio_rl16(pb);
 
     if (hdr->audio_frequency != 22050 || hdr->audio_bits != 16 || hdr->audio_stereo != 0)
         return AVERROR_INVALIDDATA;
@@ -95,7 +95,7 @@ static int cin_read_header(AVFormatContext *s, AVFormatParameters *ap)
     int rc;
     CinDemuxContext *cin = s->priv_data;
     CinFileHeader *hdr = &cin->file_header;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVStream *st;
 
     rc = cin_read_file_header(cin, pb);
@@ -138,19 +138,19 @@ static int cin_read_header(AVFormatContext *s, AVFormatParameters *ap)
     return 0;
 }
 
-static int cin_read_frame_header(CinDemuxContext *cin, ByteIOContext *pb) {
+static int cin_read_frame_header(CinDemuxContext *cin, AVIOContext *pb) {
     CinFrameHeader *hdr = &cin->frame_header;
 
-    hdr->video_frame_type = get_byte(pb);
-    hdr->audio_frame_type = get_byte(pb);
-    hdr->pal_colors_count = get_le16(pb);
-    hdr->video_frame_size = get_le32(pb);
-    hdr->audio_frame_size = get_le32(pb);
+    hdr->video_frame_type = avio_r8(pb);
+    hdr->audio_frame_type = avio_r8(pb);
+    hdr->pal_colors_count = avio_rl16(pb);
+    hdr->video_frame_size = avio_rl32(pb);
+    hdr->audio_frame_size = avio_rl32(pb);
 
-    if (url_feof(pb) || url_ferror(pb))
+    if (pb->eof_reached || pb->error)
         return AVERROR(EIO);
 
-    if (get_le32(pb) != 0xAA55AA55)
+    if (avio_rl32(pb) != 0xAA55AA55)
         return AVERROR_INVALIDDATA;
 
     return 0;
@@ -159,7 +159,7 @@ static int cin_read_frame_header(CinDemuxContext *cin, ByteIOContext *pb) {
 static int cin_read_packet(AVFormatContext *s, AVPacket *pkt)
 {
     CinDemuxContext *cin = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     CinFrameHeader *hdr = &cin->frame_header;
     int rc, palette_type, pkt_size;
     int ret;
@@ -191,7 +191,7 @@ static int cin_read_packet(AVFormatContext *s, AVPacket *pkt)
         pkt->data[2] = hdr->pal_colors_count >> 8;
         pkt->data[3] = hdr->video_frame_type;
 
-        ret = get_buffer(pb, &pkt->data[4], pkt_size);
+        ret = avio_read(pb, &pkt->data[4], pkt_size);
         if (ret < 0) {
             av_free_packet(pkt);
             return ret;
@@ -216,7 +216,7 @@ static int cin_read_packet(AVFormatContext *s, AVPacket *pkt)
     return 0;
 }
 
-AVInputFormat dsicin_demuxer = {
+AVInputFormat ff_dsicin_demuxer = {
     "dsicin",
     NULL_IF_CONFIG_SMALL("Delphine Software International CIN format"),
     sizeof(CinDemuxContext),
diff --git a/libavformat/dtsdec.c b/libavformat/dtsdec.c
new file mode 100644
index 0000000..943f6a5
--- /dev/null
+++ b/libavformat/dtsdec.c
@@ -0,0 +1,78 @@
+/*
+ * RAW DTS demuxer
+ * Copyright (c) 2008 Benjamin Larsson
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "libavcodec/bytestream.h"
+#include "avformat.h"
+#include "rawdec.h"
+
+#define DCA_MARKER_14B_BE 0x1FFFE800
+#define DCA_MARKER_14B_LE 0xFF1F00E8
+#define DCA_MARKER_RAW_BE 0x7FFE8001
+#define DCA_MARKER_RAW_LE 0xFE7F0180
+
+static int dts_probe(AVProbeData *p)
+{
+    const uint8_t *buf, *bufp;
+    uint32_t state = -1;
+    int markers[3] = {0};
+    int sum, max;
+
+    buf = p->buf;
+
+    for(; buf < (p->buf+p->buf_size)-2; buf+=2) {
+        bufp = buf;
+        state = (state << 16) | bytestream_get_be16(&bufp);
+
+        /* regular bitstream */
+        if (state == DCA_MARKER_RAW_BE || state == DCA_MARKER_RAW_LE)
+            markers[0]++;
+
+        /* 14 bits big-endian bitstream */
+        if (state == DCA_MARKER_14B_BE)
+            if ((bytestream_get_be16(&bufp) & 0xFFF0) == 0x07F0)
+                markers[1]++;
+
+        /* 14 bits little-endian bitstream */
+        if (state == DCA_MARKER_14B_LE)
+            if ((bytestream_get_be16(&bufp) & 0xF0FF) == 0xF007)
+                markers[2]++;
+    }
+    sum = markers[0] + markers[1] + markers[2];
+    max = markers[1] > markers[0];
+    max = markers[2] > markers[max] ? 2 : max;
+    if (markers[max] > 3 && p->buf_size / markers[max] < 32*1024 &&
+        markers[max] * 4 > sum * 3)
+        return AVPROBE_SCORE_MAX/2+1;
+
+    return 0;
+}
+
+AVInputFormat ff_dts_demuxer = {
+    "dts",
+    NULL_IF_CONFIG_SMALL("raw DTS"),
+    0,
+    dts_probe,
+    ff_raw_audio_read_header,
+    ff_raw_read_partial_packet,
+    .flags= AVFMT_GENERIC_INDEX,
+    .extensions = "dts",
+    .value = CODEC_ID_DTS,
+};
diff --git a/libavformat/dv.c b/libavformat/dv.c
index b6f9c6a..4b41e0a 100644
--- a/libavformat/dv.c
+++ b/libavformat/dv.c
@@ -12,20 +12,20 @@
  * Copyright (c) 2006 Daniel Maas <dmaas at maasdigital.com>
  * Funded by BBC Research & Development
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #include <time.h>
@@ -370,7 +370,7 @@ static int64_t dv_frame_offset(AVFormatContext *s, DVDemuxContext *c,
     // FIXME: sys may be wrong if last dv_read_packet() failed (buffer is junk)
     const DVprofile* sys = ff_dv_codec_profile(c->vst->codec);
     int64_t offset;
-    int64_t size = url_fsize(s->pb);
+    int64_t size = avio_size(s->pb) - s->data_offset;
     int64_t max_offset = ((size-1) / sys->frame_size) * sys->frame_size;
 
     offset = sys->frame_size * timestamp;
@@ -378,7 +378,7 @@ static int64_t dv_frame_offset(AVFormatContext *s, DVDemuxContext *c,
     if (size >= 0 && offset > max_offset) offset = max_offset;
     else if (offset < 0) offset = 0;
 
-    return offset;
+    return offset + s->data_offset;
 }
 
 void dv_offset_reset(DVDemuxContext *c, int64_t frame_offset)
@@ -410,25 +410,25 @@ static int dv_read_header(AVFormatContext *s,
     if (!c->dv_demux)
         return -1;
 
-    state = get_be32(s->pb);
+    state = avio_rb32(s->pb);
     while ((state & 0xffffff7f) != 0x1f07003f) {
-        if (url_feof(s->pb)) {
+        if (s->pb->eof_reached) {
             av_log(s, AV_LOG_ERROR, "Cannot find DV header.\n");
             return -1;
         }
         if (state == 0x003f0700 || state == 0xff3f0700)
-            marker_pos = url_ftell(s->pb);
-        if (state == 0xff3f0701 && url_ftell(s->pb) - marker_pos == 80) {
-            url_fseek(s->pb, -163, SEEK_CUR);
-            state = get_be32(s->pb);
+            marker_pos = avio_tell(s->pb);
+        if (state == 0xff3f0701 && avio_tell(s->pb) - marker_pos == 80) {
+            avio_seek(s->pb, -163, SEEK_CUR);
+            state = avio_rb32(s->pb);
             break;
         }
-        state = (state << 8) | get_byte(s->pb);
+        state = (state << 8) | avio_r8(s->pb);
     }
     AV_WB32(c->buf, state);
 
-    if (get_buffer(s->pb, c->buf + 4, DV_PROFILE_BYTES - 4) <= 0 ||
-        url_fseek(s->pb, -DV_PROFILE_BYTES, SEEK_CUR) < 0)
+    if (avio_read(s->pb, c->buf + 4, DV_PROFILE_BYTES - 4) <= 0 ||
+        avio_seek(s->pb, -DV_PROFILE_BYTES, SEEK_CUR) < 0)
         return AVERROR(EIO);
 
     c->dv_demux->sys = ff_dv_frame_profile(c->dv_demux->sys, c->buf, DV_PROFILE_BYTES);
@@ -455,7 +455,7 @@ static int dv_read_packet(AVFormatContext *s, AVPacket *pkt)
         if (!c->dv_demux->sys)
             return AVERROR(EIO);
         size = c->dv_demux->sys->frame_size;
-        if (get_buffer(s->pb, c->buf, size) <= 0)
+        if (avio_read(s->pb, c->buf, size) <= 0)
             return AVERROR(EIO);
 
         size = dv_produce_packet(c->dv_demux, pkt, c->buf, size);
@@ -473,7 +473,7 @@ static int dv_read_seek(AVFormatContext *s, int stream_index,
 
     dv_offset_reset(c, offset / c->sys->frame_size);
 
-    offset = url_fseek(s->pb, offset, SEEK_SET);
+    offset = avio_seek(s->pb, offset, SEEK_SET);
     return (offset < 0) ? offset : 0;
 }
 
@@ -518,7 +518,7 @@ static int dv_probe(AVProbeData *p)
 }
 
 #if CONFIG_DV_DEMUXER
-AVInputFormat dv_demuxer = {
+AVInputFormat ff_dv_demuxer = {
     "dv",
     NULL_IF_CONFIG_SMALL("DV video format"),
     sizeof(RawDVContext),
diff --git a/libavformat/dv.h b/libavformat/dv.h
index ae16bef..650699d 100644
--- a/libavformat/dv.h
+++ b/libavformat/dv.h
@@ -8,20 +8,20 @@
  * Raw DV format
  * Copyright (c) 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -37,8 +37,5 @@ int dv_produce_packet(DVDemuxContext*, AVPacket*, uint8_t*, int);
 void dv_offset_reset(DVDemuxContext *c, int64_t frame_offset);
 
 typedef struct DVMuxContext DVMuxContext;
-DVMuxContext* dv_init_mux(AVFormatContext* s);
-int dv_assemble_frame(DVMuxContext *c, AVStream*, uint8_t*, int, uint8_t**);
-void dv_delete_mux(DVMuxContext*);
 
 #endif /* AVFORMAT_DV_H */
diff --git a/libavformat/dvenc.c b/libavformat/dvenc.c
index 0176ac9..537581a 100644
--- a/libavformat/dvenc.c
+++ b/libavformat/dvenc.c
@@ -11,20 +11,20 @@
  * 50 Mbps (DVCPRO50) support
  * Copyright (c) 2006 Daniel Maas <dmaas at maasdigital.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #include <time.h>
@@ -232,8 +232,8 @@ static void dv_inject_metadata(DVMuxContext *c, uint8_t* frame)
  * The following 3 functions constitute our interface to the world
  */
 
-int dv_assemble_frame(DVMuxContext *c, AVStream* st,
-                      uint8_t* data, int data_size, uint8_t** frame)
+static int dv_assemble_frame(DVMuxContext *c, AVStream* st,
+                             uint8_t* data, int data_size, uint8_t** frame)
 {
     int i, reqasize;
 
@@ -285,7 +285,7 @@ int dv_assemble_frame(DVMuxContext *c, AVStream* st,
     return 0;
 }
 
-DVMuxContext* dv_init_mux(AVFormatContext* s)
+static DVMuxContext* dv_init_mux(AVFormatContext* s)
 {
     DVMuxContext *c = s->priv_data;
     AVStream *vst = NULL;
@@ -354,14 +354,13 @@ bail_out:
     return NULL;
 }
 
-void dv_delete_mux(DVMuxContext *c)
+static void dv_delete_mux(DVMuxContext *c)
 {
     int i;
     for (i=0; i < c->n_ast; i++)
         av_fifo_free(c->audio_data[i]);
 }
 
-#if CONFIG_DV_MUXER
 static int dv_write_header(AVFormatContext *s)
 {
     if (!dv_init_mux(s)) {
@@ -382,8 +381,8 @@ static int dv_write_packet(struct AVFormatContext *s, AVPacket *pkt)
     fsize = dv_assemble_frame(s->priv_data, s->streams[pkt->stream_index],
                               pkt->data, pkt->size, &frame);
     if (fsize > 0) {
-        put_buffer(s->pb, frame, fsize);
-        put_flush_packet(s->pb);
+        avio_write(s->pb, frame, fsize);
+        avio_flush(s->pb);
     }
     return 0;
 }
@@ -400,7 +399,7 @@ static int dv_write_trailer(struct AVFormatContext *s)
     return 0;
 }
 
-AVOutputFormat dv_muxer = {
+AVOutputFormat ff_dv_muxer = {
     "dv",
     NULL_IF_CONFIG_SMALL("DV video format"),
     NULL,
@@ -412,4 +411,3 @@ AVOutputFormat dv_muxer = {
     dv_write_packet,
     dv_write_trailer,
 };
-#endif /* CONFIG_DV_MUXER */
diff --git a/libavformat/dxa.c b/libavformat/dxa.c
index c00c917..1e1d505 100644
--- a/libavformat/dxa.c
+++ b/libavformat/dxa.c
@@ -2,20 +2,20 @@
  * DXA demuxer
  * Copyright (c) 2007 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -52,7 +52,7 @@ static int dxa_probe(AVProbeData *p)
 
 static int dxa_read_header(AVFormatContext *s, AVFormatParameters *ap)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     DXAContext *c = s->priv_data;
     AVStream *st, *ast;
     uint32_t tag;
@@ -60,18 +60,19 @@ static int dxa_read_header(AVFormatContext *s, AVFormatParameters *ap)
     int w, h;
     int num, den;
     int flags;
+    int ret;
 
-    tag = get_le32(pb);
+    tag = avio_rl32(pb);
     if (tag != MKTAG('D', 'E', 'X', 'A'))
         return -1;
-    flags = get_byte(pb);
-    c->frames = get_be16(pb);
+    flags = avio_r8(pb);
+    c->frames = avio_rb16(pb);
     if(!c->frames){
         av_log(s, AV_LOG_ERROR, "File contains no frames ???\n");
         return -1;
     }
 
-    fps = get_be32(pb);
+    fps = avio_rb32(pb);
     if(fps > 0){
         den = 1000;
         num = fps;
@@ -82,8 +83,8 @@ static int dxa_read_header(AVFormatContext *s, AVFormatParameters *ap)
         den = 10;
         num = 1;
     }
-    w = get_be16(pb);
-    h = get_be16(pb);
+    w = avio_rb16(pb);
+    h = avio_rb16(pb);
     c->has_sound = 0;
 
     st = av_new_stream(s, 0);
@@ -91,31 +92,33 @@ static int dxa_read_header(AVFormatContext *s, AVFormatParameters *ap)
         return -1;
 
     // Parse WAV data header
-    if(get_le32(pb) == MKTAG('W', 'A', 'V', 'E')){
+    if(avio_rl32(pb) == MKTAG('W', 'A', 'V', 'E')){
         uint32_t size, fsize;
         c->has_sound = 1;
-        size = get_be32(pb);
-        c->vidpos = url_ftell(pb) + size;
-        url_fskip(pb, 16);
-        fsize = get_le32(pb);
+        size = avio_rb32(pb);
+        c->vidpos = avio_tell(pb) + size;
+        avio_skip(pb, 16);
+        fsize = avio_rl32(pb);
 
         ast = av_new_stream(s, 0);
         if (!ast)
             return -1;
-        ff_get_wav_header(pb, ast->codec, fsize);
+        ret = ff_get_wav_header(pb, ast->codec, fsize);
+        if (ret < 0)
+            return ret;
         // find 'data' chunk
-        while(url_ftell(pb) < c->vidpos && !url_feof(pb)){
-            tag = get_le32(pb);
-            fsize = get_le32(pb);
+        while(avio_tell(pb) < c->vidpos && !pb->eof_reached){
+            tag = avio_rl32(pb);
+            fsize = avio_rl32(pb);
             if(tag == MKTAG('d', 'a', 't', 'a')) break;
-            url_fskip(pb, fsize);
+            avio_skip(pb, fsize);
         }
         c->bpc = (fsize + c->frames - 1) / c->frames;
         if(ast->codec->block_align)
             c->bpc = ((c->bpc + ast->codec->block_align - 1) / ast->codec->block_align) * ast->codec->block_align;
         c->bytes_left = fsize;
-        c->wavpos = url_ftell(pb);
-        url_fseek(pb, c->vidpos, SEEK_SET);
+        c->wavpos = avio_tell(pb);
+        avio_seek(pb, c->vidpos, SEEK_SET);
     }
 
     /* now we are ready: build format streams */
@@ -133,7 +136,7 @@ static int dxa_read_header(AVFormatContext *s, AVFormatParameters *ap)
         st->codec->height >>= 1;
     }
     c->readvid = !c->has_sound;
-    c->vidpos  = url_ftell(pb);
+    c->vidpos  = avio_tell(pb);
     s->start_time = 0;
     s->duration = (int64_t)c->frames * AV_TIME_BASE * num / den;
     av_log(s, AV_LOG_DEBUG, "%d frame(s)\n",c->frames);
@@ -151,19 +154,19 @@ static int dxa_read_packet(AVFormatContext *s, AVPacket *pkt)
 
     if(!c->readvid && c->has_sound && c->bytes_left){
         c->readvid = 1;
-        url_fseek(s->pb, c->wavpos, SEEK_SET);
+        avio_seek(s->pb, c->wavpos, SEEK_SET);
         size = FFMIN(c->bytes_left, c->bpc);
         ret = av_get_packet(s->pb, pkt, size);
         pkt->stream_index = 1;
         if(ret != size)
             return AVERROR(EIO);
         c->bytes_left -= size;
-        c->wavpos = url_ftell(s->pb);
+        c->wavpos = avio_tell(s->pb);
         return 0;
     }
-    url_fseek(s->pb, c->vidpos, SEEK_SET);
-    while(!url_feof(s->pb) && c->frames){
-        get_buffer(s->pb, buf, 4);
+    avio_seek(s->pb, c->vidpos, SEEK_SET);
+    while(!s->pb->eof_reached && c->frames){
+        avio_read(s->pb, buf, 4);
         switch(AV_RL32(buf)){
         case MKTAG('N', 'U', 'L', 'L'):
             if(av_new_packet(pkt, 4 + pal_size) < 0)
@@ -172,16 +175,16 @@ static int dxa_read_packet(AVFormatContext *s, AVPacket *pkt)
             if(pal_size) memcpy(pkt->data, pal, pal_size);
             memcpy(pkt->data + pal_size, buf, 4);
             c->frames--;
-            c->vidpos = url_ftell(s->pb);
+            c->vidpos = avio_tell(s->pb);
             c->readvid = 0;
             return 0;
         case MKTAG('C', 'M', 'A', 'P'):
             pal_size = 768+4;
             memcpy(pal, buf, 4);
-            get_buffer(s->pb, pal + 4, 768);
+            avio_read(s->pb, pal + 4, 768);
             break;
         case MKTAG('F', 'R', 'A', 'M'):
-            get_buffer(s->pb, buf + 4, DXA_EXTRA_SIZE - 4);
+            avio_read(s->pb, buf + 4, DXA_EXTRA_SIZE - 4);
             size = AV_RB32(buf + 5);
             if(size > 0xFFFFFF){
                 av_log(s, AV_LOG_ERROR, "Frame size is too big: %d\n", size);
@@ -190,7 +193,7 @@ static int dxa_read_packet(AVFormatContext *s, AVPacket *pkt)
             if(av_new_packet(pkt, size + DXA_EXTRA_SIZE + pal_size) < 0)
                 return AVERROR(ENOMEM);
             memcpy(pkt->data + pal_size, buf, DXA_EXTRA_SIZE);
-            ret = get_buffer(s->pb, pkt->data + DXA_EXTRA_SIZE + pal_size, size);
+            ret = avio_read(s->pb, pkt->data + DXA_EXTRA_SIZE + pal_size, size);
             if(ret != size){
                 av_free_packet(pkt);
                 return AVERROR(EIO);
@@ -198,7 +201,7 @@ static int dxa_read_packet(AVFormatContext *s, AVPacket *pkt)
             if(pal_size) memcpy(pkt->data, pal, pal_size);
             pkt->stream_index = 0;
             c->frames--;
-            c->vidpos = url_ftell(s->pb);
+            c->vidpos = avio_tell(s->pb);
             c->readvid = 0;
             return 0;
         default:
@@ -209,7 +212,7 @@ static int dxa_read_packet(AVFormatContext *s, AVPacket *pkt)
     return AVERROR(EIO);
 }
 
-AVInputFormat dxa_demuxer = {
+AVInputFormat ff_dxa_demuxer = {
     "dxa",
     NULL_IF_CONFIG_SMALL("DXA"),
     sizeof(DXAContext),
diff --git a/libavformat/eacdata.c b/libavformat/eacdata.c
index 32c3343..5c89559 100644
--- a/libavformat/eacdata.c
+++ b/libavformat/eacdata.c
@@ -2,20 +2,20 @@
  * Electronic Arts .cdata file Demuxer
  * Copyright (c) 2007 Peter Ross
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -47,11 +47,11 @@ static int cdata_probe(AVProbeData *p)
 static int cdata_read_header(AVFormatContext *s, AVFormatParameters *ap)
 {
     CdataDemuxContext *cdata = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     unsigned int sample_rate, header;
     AVStream *st;
 
-    header = get_be16(pb);
+    header = avio_rb16(pb);
     switch (header) {
         case 0x0400: cdata->channels = 1; break;
         case 0x0404: cdata->channels = 2; break;
@@ -61,8 +61,8 @@ static int cdata_read_header(AVFormatContext *s, AVFormatParameters *ap)
             return -1;
     };
 
-    sample_rate = get_be16(pb);
-    url_fskip(pb, 12);
+    sample_rate = avio_rb16(pb);
+    avio_skip(pb, 12);
 
     st = av_new_stream(s, 0);
     if (!st)
@@ -90,7 +90,7 @@ static int cdata_read_packet(AVFormatContext *s, AVPacket *pkt)
     return 0;
 }
 
-AVInputFormat ea_cdata_demuxer = {
+AVInputFormat ff_ea_cdata_demuxer = {
     "ea_cdata",
     NULL_IF_CONFIG_SMALL("Electronic Arts cdata"),
     sizeof(CdataDemuxContext),
diff --git a/libavformat/electronicarts.c b/libavformat/electronicarts.c
index 86d7f91..06689dd 100644
--- a/libavformat/electronicarts.c
+++ b/libavformat/electronicarts.c
@@ -2,20 +2,20 @@
  * Copyright (c) 2004  The ffmpeg Project
  * Copyright (c) 2006-2008 Peter Ross
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -77,16 +77,16 @@ typedef struct EaDemuxContext {
     int num_samples;
 } EaDemuxContext;
 
-static uint32_t read_arbitary(ByteIOContext *pb) {
+static uint32_t read_arbitary(AVIOContext *pb) {
     uint8_t size, byte;
     int i;
     uint32_t word;
 
-    size = get_byte(pb);
+    size = avio_r8(pb);
 
     word = 0;
     for (i = 0; i < size; i++) {
-        byte = get_byte(pb);
+        byte = avio_r8(pb);
         word <<= 8;
         word |= byte;
     }
@@ -102,25 +102,25 @@ static int process_audio_header_elements(AVFormatContext *s)
 {
     int inHeader = 1;
     EaDemuxContext *ea = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int compression_type = -1, revision = -1, revision2 = -1;
 
     ea->bytes = 2;
     ea->sample_rate = -1;
     ea->num_channels = 1;
 
-    while (inHeader) {
+    while (!pb->eof_reached && inHeader) {
         int inSubheader;
         uint8_t byte;
-        byte = get_byte(pb);
+        byte = avio_r8(pb);
 
         switch (byte) {
         case 0xFD:
             av_log (s, AV_LOG_DEBUG, "entered audio subheader\n");
             inSubheader = 1;
-            while (inSubheader) {
+            while (!pb->eof_reached && inSubheader) {
                 uint8_t subbyte;
-                subbyte = get_byte(pb);
+                subbyte = avio_r8(pb);
 
                 switch (subbyte) {
                 case 0x80:
@@ -215,14 +215,14 @@ static int process_audio_header_elements(AVFormatContext *s)
 static int process_audio_header_eacs(AVFormatContext *s)
 {
     EaDemuxContext *ea = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int compression_type;
 
-    ea->sample_rate  = ea->big_endian ? get_be32(pb) : get_le32(pb);
-    ea->bytes        = get_byte(pb);   /* 1=8-bit, 2=16-bit */
-    ea->num_channels = get_byte(pb);
-    compression_type = get_byte(pb);
-    url_fskip(pb, 13);
+    ea->sample_rate  = ea->big_endian ? avio_rb32(pb) : avio_rl32(pb);
+    ea->bytes        = avio_r8(pb);   /* 1=8-bit, 2=16-bit */
+    ea->num_channels = avio_r8(pb);
+    compression_type = avio_r8(pb);
+    avio_skip(pb, 13);
 
     switch (compression_type) {
     case 0:
@@ -247,11 +247,11 @@ static int process_audio_header_eacs(AVFormatContext *s)
 static int process_audio_header_sead(AVFormatContext *s)
 {
     EaDemuxContext *ea = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
 
-    ea->sample_rate  = get_le32(pb);
-    ea->bytes        = get_le32(pb);  /* 1=8-bit, 2=16-bit */
-    ea->num_channels = get_le32(pb);
+    ea->sample_rate  = avio_rl32(pb);
+    ea->bytes        = avio_rl32(pb);  /* 1=8-bit, 2=16-bit */
+    ea->num_channels = avio_rl32(pb);
     ea->audio_codec  = CODEC_ID_ADPCM_IMA_EA_SEAD;
 
     return 1;
@@ -260,10 +260,10 @@ static int process_audio_header_sead(AVFormatContext *s)
 static int process_video_header_mdec(AVFormatContext *s)
 {
     EaDemuxContext *ea = s->priv_data;
-    ByteIOContext *pb = s->pb;
-    url_fskip(pb, 4);
-    ea->width  = get_le16(pb);
-    ea->height = get_le16(pb);
+    AVIOContext *pb = s->pb;
+    avio_skip(pb, 4);
+    ea->width  = avio_rl16(pb);
+    ea->height = avio_rl16(pb);
     ea->time_base = (AVRational){1,15};
     ea->video_codec = CODEC_ID_MDEC;
     return 1;
@@ -272,11 +272,11 @@ static int process_video_header_mdec(AVFormatContext *s)
 static int process_video_header_vp6(AVFormatContext *s)
 {
     EaDemuxContext *ea = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
 
-    url_fskip(pb, 16);
-    ea->time_base.den = get_le32(pb);
-    ea->time_base.num = get_le32(pb);
+    avio_skip(pb, 16);
+    ea->time_base.den = avio_rl32(pb);
+    ea->time_base.num = avio_rl32(pb);
     ea->video_codec = CODEC_ID_VP6;
 
     return 1;
@@ -289,23 +289,23 @@ static int process_video_header_vp6(AVFormatContext *s)
 static int process_ea_header(AVFormatContext *s) {
     uint32_t blockid, size = 0;
     EaDemuxContext *ea = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int i;
 
     for (i=0; i<5 && (!ea->audio_codec || !ea->video_codec); i++) {
-        unsigned int startpos = url_ftell(pb);
+        unsigned int startpos = avio_tell(pb);
         int err = 0;
 
-        blockid = get_le32(pb);
-        size = get_le32(pb);
+        blockid = avio_rl32(pb);
+        size = avio_rl32(pb);
         if (i == 0)
             ea->big_endian = size > 0x000FFFFF;
         if (ea->big_endian)
-            size = bswap_32(size);
+            size = av_bswap32(size);
 
         switch (blockid) {
             case ISNh_TAG:
-                if (get_le32(pb) != EACS_TAG) {
+                if (avio_rl32(pb) != EACS_TAG) {
                     av_log (s, AV_LOG_ERROR, "unknown 1SNh headerid\n");
                     return 0;
                 }
@@ -314,9 +314,9 @@ static int process_ea_header(AVFormatContext *s) {
 
             case SCHl_TAG :
             case SHEN_TAG :
-                blockid = get_le32(pb);
+                blockid = avio_rl32(pb);
                 if (blockid == GSTR_TAG) {
-                    url_fskip(pb, 4);
+                    avio_skip(pb, 4);
                 } else if ((blockid & 0xFFFF)!=PT00_TAG) {
                     av_log (s, AV_LOG_ERROR, "unknown SCHl headerid\n");
                     return 0;
@@ -369,10 +369,10 @@ static int process_ea_header(AVFormatContext *s) {
             return err;
         }
 
-        url_fseek(pb, startpos + size, SEEK_SET);
+        avio_seek(pb, startpos + size, SEEK_SET);
     }
 
-    url_fseek(pb, 0, SEEK_SET);
+    avio_seek(pb, 0, SEEK_SET);
 
     return 1;
 }
@@ -423,6 +423,17 @@ static int ea_read_header(AVFormatContext *s,
     }
 
     if (ea->audio_codec) {
+        if (ea->num_channels <= 0) {
+            av_log(s, AV_LOG_WARNING, "Unsupported number of channels: %d\n", ea->num_channels);
+            ea->audio_codec = 0;
+            return 1;
+        }
+        if (ea->sample_rate <= 0) {
+            av_log(s, AV_LOG_ERROR, "Unsupported sample rate: %d\n", ea->sample_rate);
+            ea->audio_codec = 0;
+            return 1;
+        }
+
         /* initialize the audio decoder stream */
         st = av_new_stream(s, 0);
         if (!st)
@@ -448,7 +459,7 @@ static int ea_read_packet(AVFormatContext *s,
                           AVPacket *pkt)
 {
     EaDemuxContext *ea = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int ret = 0;
     int packet_read = 0;
     unsigned int chunk_type, chunk_size;
@@ -456,26 +467,26 @@ static int ea_read_packet(AVFormatContext *s,
     int av_uninit(num_samples);
 
     while (!packet_read) {
-        chunk_type = get_le32(pb);
-        chunk_size = (ea->big_endian ? get_be32(pb) : get_le32(pb)) - 8;
+        chunk_type = avio_rl32(pb);
+        chunk_size = (ea->big_endian ? avio_rb32(pb) : avio_rl32(pb)) - 8;
 
         switch (chunk_type) {
         /* audio data */
         case ISNh_TAG:
             /* header chunk also contains data; skip over the header portion*/
-            url_fskip(pb, 32);
+            avio_skip(pb, 32);
             chunk_size -= 32;
         case ISNd_TAG:
         case SCDl_TAG:
         case SNDC_TAG:
         case SDEN_TAG:
             if (!ea->audio_codec) {
-                url_fskip(pb, chunk_size);
+                avio_skip(pb, chunk_size);
                 break;
             } else if (ea->audio_codec == CODEC_ID_PCM_S16LE_PLANAR ||
                        ea->audio_codec == CODEC_ID_MP3) {
-                num_samples = get_le32(pb);
-                url_fskip(pb, 8);
+                num_samples = avio_rl32(pb);
+                avio_skip(pb, 8);
                 chunk_size -= 12;
             }
             ret = av_get_packet(pb, pkt, chunk_size);
@@ -525,12 +536,12 @@ static int ea_read_packet(AVFormatContext *s,
         case fVGT_TAG:
         case MADm_TAG:
         case MADe_TAG:
-            url_fseek(pb, -8, SEEK_CUR);     // include chunk preamble
+            avio_seek(pb, -8, SEEK_CUR);     // include chunk preamble
             chunk_size += 8;
             goto get_video_packet;
 
         case mTCD_TAG:
-            url_fseek(pb, 8, SEEK_CUR);  // skip ea dct header
+            avio_skip(pb, 8);  // skip ea dct header
             chunk_size -= 8;
             goto get_video_packet;
 
@@ -549,7 +560,7 @@ get_video_packet:
             break;
 
         default:
-            url_fseek(pb, chunk_size, SEEK_CUR);
+            avio_skip(pb, chunk_size);
             break;
         }
     }
@@ -557,7 +568,7 @@ get_video_packet:
     return ret;
 }
 
-AVInputFormat ea_demuxer = {
+AVInputFormat ff_ea_demuxer = {
     "ea",
     NULL_IF_CONFIG_SMALL("Electronic Arts Multimedia Format"),
     sizeof(EaDemuxContext),
diff --git a/libavformat/ffm.h b/libavformat/ffm.h
index 05d6eb1..89a14a5 100644
--- a/libavformat/ffm.h
+++ b/libavformat/ffm.h
@@ -2,20 +2,20 @@
  * FFM (ffserver live feed) common header
  * Copyright (c) 2001 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -28,6 +28,7 @@
 
 /* The FFM file is made of blocks of fixed size */
 #define FFM_HEADER_SIZE 14
+#define FFM_PACKET_SIZE 4096
 #define PACKET_ID       0x666d
 
 /* each packet contains frames (which can span several packets */
@@ -55,4 +56,8 @@ typedef struct FFMContext {
     uint8_t packet[FFM_PACKET_SIZE];
 } FFMContext;
 
+int64_t ffm_read_write_index(int fd);
+int ffm_write_write_index(int fd, int64_t pos);
+void ffm_set_write_index(AVFormatContext *s, int64_t pos, int64_t file_size);
+
 #endif /* AVFORMAT_FFM_H */
diff --git a/libavformat/ffmdec.c b/libavformat/ffmdec.c
index b2a4bc2..6cd2b51 100644
--- a/libavformat/ffmdec.c
+++ b/libavformat/ffmdec.c
@@ -2,20 +2,20 @@
  * FFM (ffserver live feed) demuxer
  * Copyright (c) 2001 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -65,7 +65,7 @@ static int ffm_is_avail_data(AVFormatContext *s, int size)
     len = ffm->packet_end - ffm->packet_ptr;
     if (size <= len)
         return 1;
-    pos = url_ftell(s->pb);
+    pos = avio_tell(s->pb);
     if (!ffm->write_index) {
         if (pos == ffm->file_size)
             return AVERROR_EOF;
@@ -91,11 +91,11 @@ static int ffm_resync(AVFormatContext *s, int state)
 {
     av_log(s, AV_LOG_ERROR, "resyncing\n");
     while (state != PACKET_ID) {
-        if (url_feof(s->pb)) {
+        if (s->pb->eof_reached) {
             av_log(s, AV_LOG_ERROR, "cannot find FFM syncword\n");
             return -1;
         }
-        state = (state << 8) | get_byte(s->pb);
+        state = (state << 8) | avio_r8(s->pb);
     }
     return 0;
 }
@@ -105,7 +105,7 @@ static int ffm_read_data(AVFormatContext *s,
                          uint8_t *buf, int size, int header)
 {
     FFMContext *ffm = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int len, fill_size, size1, frame_offset, id;
 
     size1 = size;
@@ -117,17 +117,17 @@ static int ffm_read_data(AVFormatContext *s,
         if (len > size)
             len = size;
         if (len == 0) {
-            if (url_ftell(pb) == ffm->file_size)
-                url_fseek(pb, ffm->packet_size, SEEK_SET);
+            if (avio_tell(pb) == ffm->file_size)
+                avio_seek(pb, ffm->packet_size, SEEK_SET);
     retry_read:
-            id = get_be16(pb); /* PACKET_ID */
+            id = avio_rb16(pb); /* PACKET_ID */
             if (id != PACKET_ID)
                 if (ffm_resync(s, id) < 0)
                     return -1;
-            fill_size = get_be16(pb);
-            ffm->dts = get_be64(pb);
-            frame_offset = get_be16(pb);
-            get_buffer(pb, ffm->packet, ffm->packet_size - FFM_HEADER_SIZE);
+            fill_size = avio_rb16(pb);
+            ffm->dts = avio_rb64(pb);
+            frame_offset = avio_rb16(pb);
+            avio_read(pb, ffm->packet, ffm->packet_size - FFM_HEADER_SIZE);
             ffm->packet_end = ffm->packet + (ffm->packet_size - FFM_HEADER_SIZE - fill_size);
             if (ffm->packet_end < ffm->packet || frame_offset < 0)
                 return -1;
@@ -136,8 +136,8 @@ static int ffm_read_data(AVFormatContext *s,
             if (ffm->first_packet || (frame_offset & 0x8000)) {
                 if (!frame_offset) {
                     /* This packet has no frame headers in it */
-                    if (url_ftell(pb) >= ffm->packet_size * 3) {
-                        url_fseek(pb, -ffm->packet_size * 2, SEEK_CUR);
+                    if (avio_tell(pb) >= ffm->packet_size * 3) {
+                        avio_seek(pb, -ffm->packet_size * 2, SEEK_CUR);
                         goto retry_read;
                     }
                     /* This is bad, we cannot find a valid frame header */
@@ -170,7 +170,7 @@ static int ffm_read_data(AVFormatContext *s,
 static void ffm_seek1(AVFormatContext *s, int64_t pos1)
 {
     FFMContext *ffm = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int64_t pos;
 
     pos = FFMIN(pos1, ffm->file_size - FFM_PACKET_SIZE);
@@ -178,17 +178,17 @@ static void ffm_seek1(AVFormatContext *s, int64_t pos1)
 #ifdef DEBUG_SEEK
     av_log(s, AV_LOG_DEBUG, "seek to %"PRIx64" -> %"PRIx64"\n", pos1, pos);
 #endif
-    url_fseek(pb, pos, SEEK_SET);
+    avio_seek(pb, pos, SEEK_SET);
 }
 
 static int64_t get_dts(AVFormatContext *s, int64_t pos)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int64_t dts;
 
     ffm_seek1(s, pos);
-    url_fskip(pb, 4);
-    dts = get_be64(pb);
+    avio_skip(pb, 4);
+    dts = avio_rb64(pb);
 #ifdef DEBUG_SEEK
     av_log(s, AV_LOG_DEBUG, "dts=%0.6f\n", dts / 1000000.0);
 #endif
@@ -198,12 +198,12 @@ static int64_t get_dts(AVFormatContext *s, int64_t pos)
 static void adjust_write_index(AVFormatContext *s)
 {
     FFMContext *ffm = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int64_t pts;
     //int64_t orig_write_index = ffm->write_index;
     int64_t pos_min, pos_max;
     int64_t pts_start;
-    int64_t ptr = url_ftell(pb);
+    int64_t ptr = avio_tell(pb);
 
 
     pos_min = 0;
@@ -248,7 +248,18 @@ static void adjust_write_index(AVFormatContext *s)
     //printf("pts range %0.6f - %0.6f\n", get_dts(s, 0) / 1000000. , get_dts(s, ffm->file_size - 2 * FFM_PACKET_SIZE) / 1000000. );
 
  end:
-    url_fseek(pb, ptr, SEEK_SET);
+    avio_seek(pb, ptr, SEEK_SET);
+}
+
+
+static int ffm_close(AVFormatContext *s)
+{
+    int i;
+
+    for (i = 0; i < s->nb_streams; i++)
+        av_freep(&s->streams[i]->codec->rc_eq);
+
+    return 0;
 }
 
 
@@ -256,30 +267,30 @@ static int ffm_read_header(AVFormatContext *s, AVFormatParameters *ap)
 {
     FFMContext *ffm = s->priv_data;
     AVStream *st;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVCodecContext *codec;
     int i, nb_streams;
     uint32_t tag;
 
     /* header */
-    tag = get_le32(pb);
+    tag = avio_rl32(pb);
     if (tag != MKTAG('F', 'F', 'M', '1'))
         goto fail;
-    ffm->packet_size = get_be32(pb);
+    ffm->packet_size = avio_rb32(pb);
     if (ffm->packet_size != FFM_PACKET_SIZE)
         goto fail;
-    ffm->write_index = get_be64(pb);
+    ffm->write_index = avio_rb64(pb);
     /* get also filesize */
-    if (!url_is_streamed(pb)) {
-        ffm->file_size = url_fsize(pb);
+    if (pb->seekable) {
+        ffm->file_size = avio_size(pb);
         if (ffm->write_index)
             adjust_write_index(s);
     } else {
         ffm->file_size = (UINT64_C(1) << 63) - 1;
     }
 
-    nb_streams = get_be32(pb);
-    get_be32(pb); /* total bitrate */
+    nb_streams = avio_rb32(pb);
+    avio_rb32(pb); /* total bitrate */
     /* read each stream */
     for(i=0;i<nb_streams;i++) {
         char rc_eq_buf[128];
@@ -292,85 +303,86 @@ static int ffm_read_header(AVFormatContext *s, AVFormatParameters *ap)
 
         codec = st->codec;
         /* generic info */
-        codec->codec_id = get_be32(pb);
-        codec->codec_type = get_byte(pb); /* codec_type */
-        codec->bit_rate = get_be32(pb);
-        st->quality = get_be32(pb);
-        codec->flags = get_be32(pb);
-        codec->flags2 = get_be32(pb);
-        codec->debug = get_be32(pb);
+        codec->codec_id = avio_rb32(pb);
+        codec->codec_type = avio_r8(pb); /* codec_type */
+        codec->bit_rate = avio_rb32(pb);
+        st->quality = avio_rb32(pb);
+        codec->flags = avio_rb32(pb);
+        codec->flags2 = avio_rb32(pb);
+        codec->debug = avio_rb32(pb);
         /* specific info */
         switch(codec->codec_type) {
         case AVMEDIA_TYPE_VIDEO:
-            codec->time_base.num = get_be32(pb);
-            codec->time_base.den = get_be32(pb);
-            codec->width = get_be16(pb);
-            codec->height = get_be16(pb);
-            codec->gop_size = get_be16(pb);
-            codec->pix_fmt = get_be32(pb);
-            codec->qmin = get_byte(pb);
-            codec->qmax = get_byte(pb);
-            codec->max_qdiff = get_byte(pb);
-            codec->qcompress = get_be16(pb) / 10000.0;
-            codec->qblur = get_be16(pb) / 10000.0;
-            codec->bit_rate_tolerance = get_be32(pb);
-            codec->rc_eq = av_strdup(get_strz(pb, rc_eq_buf, sizeof(rc_eq_buf)));
-            codec->rc_max_rate = get_be32(pb);
-            codec->rc_min_rate = get_be32(pb);
-            codec->rc_buffer_size = get_be32(pb);
-            codec->i_quant_factor = av_int2dbl(get_be64(pb));
-            codec->b_quant_factor = av_int2dbl(get_be64(pb));
-            codec->i_quant_offset = av_int2dbl(get_be64(pb));
-            codec->b_quant_offset = av_int2dbl(get_be64(pb));
-            codec->dct_algo = get_be32(pb);
-            codec->strict_std_compliance = get_be32(pb);
-            codec->max_b_frames = get_be32(pb);
-            codec->luma_elim_threshold = get_be32(pb);
-            codec->chroma_elim_threshold = get_be32(pb);
-            codec->mpeg_quant = get_be32(pb);
-            codec->intra_dc_precision = get_be32(pb);
-            codec->me_method = get_be32(pb);
-            codec->mb_decision = get_be32(pb);
-            codec->nsse_weight = get_be32(pb);
-            codec->frame_skip_cmp = get_be32(pb);
-            codec->rc_buffer_aggressivity = av_int2dbl(get_be64(pb));
-            codec->codec_tag = get_be32(pb);
-            codec->thread_count = get_byte(pb);
-            codec->coder_type = get_be32(pb);
-            codec->me_cmp = get_be32(pb);
-            codec->partitions = get_be32(pb);
-            codec->me_subpel_quality = get_be32(pb);
-            codec->me_range = get_be32(pb);
-            codec->keyint_min = get_be32(pb);
-            codec->scenechange_threshold = get_be32(pb);
-            codec->b_frame_strategy = get_be32(pb);
-            codec->qcompress = av_int2dbl(get_be64(pb));
-            codec->qblur = av_int2dbl(get_be64(pb));
-            codec->max_qdiff = get_be32(pb);
-            codec->refs = get_be32(pb);
-            codec->directpred = get_be32(pb);
+            codec->time_base.num = avio_rb32(pb);
+            codec->time_base.den = avio_rb32(pb);
+            codec->width = avio_rb16(pb);
+            codec->height = avio_rb16(pb);
+            codec->gop_size = avio_rb16(pb);
+            codec->pix_fmt = avio_rb32(pb);
+            codec->qmin = avio_r8(pb);
+            codec->qmax = avio_r8(pb);
+            codec->max_qdiff = avio_r8(pb);
+            codec->qcompress = avio_rb16(pb) / 10000.0;
+            codec->qblur = avio_rb16(pb) / 10000.0;
+            codec->bit_rate_tolerance = avio_rb32(pb);
+            avio_get_str(pb, INT_MAX, rc_eq_buf, sizeof(rc_eq_buf));
+            codec->rc_eq = av_strdup(rc_eq_buf);
+            codec->rc_max_rate = avio_rb32(pb);
+            codec->rc_min_rate = avio_rb32(pb);
+            codec->rc_buffer_size = avio_rb32(pb);
+            codec->i_quant_factor = av_int2dbl(avio_rb64(pb));
+            codec->b_quant_factor = av_int2dbl(avio_rb64(pb));
+            codec->i_quant_offset = av_int2dbl(avio_rb64(pb));
+            codec->b_quant_offset = av_int2dbl(avio_rb64(pb));
+            codec->dct_algo = avio_rb32(pb);
+            codec->strict_std_compliance = avio_rb32(pb);
+            codec->max_b_frames = avio_rb32(pb);
+            codec->luma_elim_threshold = avio_rb32(pb);
+            codec->chroma_elim_threshold = avio_rb32(pb);
+            codec->mpeg_quant = avio_rb32(pb);
+            codec->intra_dc_precision = avio_rb32(pb);
+            codec->me_method = avio_rb32(pb);
+            codec->mb_decision = avio_rb32(pb);
+            codec->nsse_weight = avio_rb32(pb);
+            codec->frame_skip_cmp = avio_rb32(pb);
+            codec->rc_buffer_aggressivity = av_int2dbl(avio_rb64(pb));
+            codec->codec_tag = avio_rb32(pb);
+            codec->thread_count = avio_r8(pb);
+            codec->coder_type = avio_rb32(pb);
+            codec->me_cmp = avio_rb32(pb);
+            codec->partitions = avio_rb32(pb);
+            codec->me_subpel_quality = avio_rb32(pb);
+            codec->me_range = avio_rb32(pb);
+            codec->keyint_min = avio_rb32(pb);
+            codec->scenechange_threshold = avio_rb32(pb);
+            codec->b_frame_strategy = avio_rb32(pb);
+            codec->qcompress = av_int2dbl(avio_rb64(pb));
+            codec->qblur = av_int2dbl(avio_rb64(pb));
+            codec->max_qdiff = avio_rb32(pb);
+            codec->refs = avio_rb32(pb);
+            codec->directpred = avio_rb32(pb);
             break;
         case AVMEDIA_TYPE_AUDIO:
-            codec->sample_rate = get_be32(pb);
-            codec->channels = get_le16(pb);
-            codec->frame_size = get_le16(pb);
-            codec->sample_fmt = (int16_t) get_le16(pb);
+            codec->sample_rate = avio_rb32(pb);
+            codec->channels = avio_rl16(pb);
+            codec->frame_size = avio_rl16(pb);
+            codec->sample_fmt = (int16_t) avio_rl16(pb);
             break;
         default:
             goto fail;
         }
         if (codec->flags & CODEC_FLAG_GLOBAL_HEADER) {
-            codec->extradata_size = get_be32(pb);
+            codec->extradata_size = avio_rb32(pb);
             codec->extradata = av_malloc(codec->extradata_size);
             if (!codec->extradata)
                 return AVERROR(ENOMEM);
-            get_buffer(pb, codec->extradata, codec->extradata_size);
+            avio_read(pb, codec->extradata, codec->extradata_size);
         }
     }
 
     /* get until end of block reached */
-    while ((url_ftell(pb) % ffm->packet_size) != 0)
-        get_byte(pb);
+    while ((avio_tell(pb) % ffm->packet_size) != 0)
+        avio_r8(pb);
 
     /* init packet demux */
     ffm->packet_ptr = ffm->packet;
@@ -381,12 +393,7 @@ static int ffm_read_header(AVFormatContext *s, AVFormatParameters *ap)
     ffm->first_packet = 1;
     return 0;
  fail:
-    for(i=0;i<s->nb_streams;i++) {
-        st = s->streams[i];
-        if (st) {
-            av_free(st);
-        }
-    }
+    ffm_close(s);
     return -1;
 }
 
@@ -402,8 +409,8 @@ static int ffm_read_packet(AVFormatContext *s, AVPacket *pkt)
         if ((ret = ffm_is_avail_data(s, FRAME_HEADER_SIZE+4)) < 0)
             return ret;
 
-        dprintf(s, "pos=%08"PRIx64" spos=%"PRIx64", write_index=%"PRIx64" size=%"PRIx64"\n",
-               url_ftell(s->pb), s->pb->pos, ffm->write_index, ffm->file_size);
+        av_dlog(s, "pos=%08"PRIx64" spos=%"PRIx64", write_index=%"PRIx64" size=%"PRIx64"\n",
+               avio_tell(s->pb), s->pb->pos, ffm->write_index, ffm->file_size);
         if (ffm_read_data(s, ffm->header, FRAME_HEADER_SIZE, 1) !=
             FRAME_HEADER_SIZE)
             return -1;
@@ -430,7 +437,7 @@ static int ffm_read_packet(AVFormatContext *s, AVPacket *pkt)
             ffm->read_state = READ_HEADER;
             return -1;
         }
-        pkt->pos = url_ftell(s->pb);
+        pkt->pos = avio_tell(s->pb);
         if (ffm->header[1] & FLAG_KEY_FRAME)
             pkt->flags |= AV_PKT_FLAG_KEY;
 
@@ -512,17 +519,7 @@ static int ffm_probe(AVProbeData *p)
     return 0;
 }
 
-static int ffm_close(AVFormatContext *s)
-{
-    int i;
-
-    for (i = 0; i < s->nb_streams; i++)
-        av_freep(&s->streams[i]->codec->rc_eq);
-
-    return 0;
-}
-
-AVInputFormat ffm_demuxer = {
+AVInputFormat ff_ffm_demuxer = {
     "ffm",
     NULL_IF_CONFIG_SMALL("FFM (FFserver live feed) format"),
     sizeof(FFMContext),
diff --git a/libavformat/ffmenc.c b/libavformat/ffmenc.c
index c5c59db..71d93e5 100644
--- a/libavformat/ffmenc.c
+++ b/libavformat/ffmenc.c
@@ -2,20 +2,20 @@
  * FFM (ffserver live feed) muxer
  * Copyright (c) 2001 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -27,24 +27,24 @@ static void flush_packet(AVFormatContext *s)
 {
     FFMContext *ffm = s->priv_data;
     int fill_size, h;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
 
     fill_size = ffm->packet_end - ffm->packet_ptr;
     memset(ffm->packet_ptr, 0, fill_size);
 
-    if (url_ftell(pb) % ffm->packet_size)
+    if (avio_tell(pb) % ffm->packet_size)
         av_abort();
 
     /* put header */
-    put_be16(pb, PACKET_ID);
-    put_be16(pb, fill_size);
-    put_be64(pb, ffm->dts);
+    avio_wb16(pb, PACKET_ID);
+    avio_wb16(pb, fill_size);
+    avio_wb64(pb, ffm->dts);
     h = ffm->frame_offset;
     if (ffm->first_packet)
         h |= 0x8000;
-    put_be16(pb, h);
-    put_buffer(pb, ffm->packet, ffm->packet_end - ffm->packet);
-    put_flush_packet(pb);
+    avio_wb16(pb, h);
+    avio_write(pb, ffm->packet, ffm->packet_end - ffm->packet);
+    avio_flush(pb);
 
     /* prepare next packet */
     ffm->frame_offset = 0; /* no key frame */
@@ -84,24 +84,24 @@ static int ffm_write_header(AVFormatContext *s)
 {
     FFMContext *ffm = s->priv_data;
     AVStream *st;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVCodecContext *codec;
     int bit_rate, i;
 
     ffm->packet_size = FFM_PACKET_SIZE;
 
     /* header */
-    put_le32(pb, MKTAG('F', 'F', 'M', '1'));
-    put_be32(pb, ffm->packet_size);
-    put_be64(pb, 0); /* current write position */
+    avio_wl32(pb, MKTAG('F', 'F', 'M', '1'));
+    avio_wb32(pb, ffm->packet_size);
+    avio_wb64(pb, 0); /* current write position */
 
-    put_be32(pb, s->nb_streams);
+    avio_wb32(pb, s->nb_streams);
     bit_rate = 0;
     for(i=0;i<s->nb_streams;i++) {
         st = s->streams[i];
         bit_rate += st->codec->bit_rate;
     }
-    put_be32(pb, bit_rate);
+    avio_wb32(pb, bit_rate);
 
     /* list of streams */
     for(i=0;i<s->nb_streams;i++) {
@@ -110,84 +110,84 @@ static int ffm_write_header(AVFormatContext *s)
 
         codec = st->codec;
         /* generic info */
-        put_be32(pb, codec->codec_id);
-        put_byte(pb, codec->codec_type);
-        put_be32(pb, codec->bit_rate);
-        put_be32(pb, st->quality);
-        put_be32(pb, codec->flags);
-        put_be32(pb, codec->flags2);
-        put_be32(pb, codec->debug);
+        avio_wb32(pb, codec->codec_id);
+        avio_w8(pb, codec->codec_type);
+        avio_wb32(pb, codec->bit_rate);
+        avio_wb32(pb, st->quality);
+        avio_wb32(pb, codec->flags);
+        avio_wb32(pb, codec->flags2);
+        avio_wb32(pb, codec->debug);
         /* specific info */
         switch(codec->codec_type) {
         case AVMEDIA_TYPE_VIDEO:
-            put_be32(pb, codec->time_base.num);
-            put_be32(pb, codec->time_base.den);
-            put_be16(pb, codec->width);
-            put_be16(pb, codec->height);
-            put_be16(pb, codec->gop_size);
-            put_be32(pb, codec->pix_fmt);
-            put_byte(pb, codec->qmin);
-            put_byte(pb, codec->qmax);
-            put_byte(pb, codec->max_qdiff);
-            put_be16(pb, (int) (codec->qcompress * 10000.0));
-            put_be16(pb, (int) (codec->qblur * 10000.0));
-            put_be32(pb, codec->bit_rate_tolerance);
-            put_strz(pb, codec->rc_eq ? codec->rc_eq : "tex^qComp");
-            put_be32(pb, codec->rc_max_rate);
-            put_be32(pb, codec->rc_min_rate);
-            put_be32(pb, codec->rc_buffer_size);
-            put_be64(pb, av_dbl2int(codec->i_quant_factor));
-            put_be64(pb, av_dbl2int(codec->b_quant_factor));
-            put_be64(pb, av_dbl2int(codec->i_quant_offset));
-            put_be64(pb, av_dbl2int(codec->b_quant_offset));
-            put_be32(pb, codec->dct_algo);
-            put_be32(pb, codec->strict_std_compliance);
-            put_be32(pb, codec->max_b_frames);
-            put_be32(pb, codec->luma_elim_threshold);
-            put_be32(pb, codec->chroma_elim_threshold);
-            put_be32(pb, codec->mpeg_quant);
-            put_be32(pb, codec->intra_dc_precision);
-            put_be32(pb, codec->me_method);
-            put_be32(pb, codec->mb_decision);
-            put_be32(pb, codec->nsse_weight);
-            put_be32(pb, codec->frame_skip_cmp);
-            put_be64(pb, av_dbl2int(codec->rc_buffer_aggressivity));
-            put_be32(pb, codec->codec_tag);
-            put_byte(pb, codec->thread_count);
-            put_be32(pb, codec->coder_type);
-            put_be32(pb, codec->me_cmp);
-            put_be32(pb, codec->partitions);
-            put_be32(pb, codec->me_subpel_quality);
-            put_be32(pb, codec->me_range);
-            put_be32(pb, codec->keyint_min);
-            put_be32(pb, codec->scenechange_threshold);
-            put_be32(pb, codec->b_frame_strategy);
-            put_be64(pb, av_dbl2int(codec->qcompress));
-            put_be64(pb, av_dbl2int(codec->qblur));
-            put_be32(pb, codec->max_qdiff);
-            put_be32(pb, codec->refs);
-            put_be32(pb, codec->directpred);
+            avio_wb32(pb, codec->time_base.num);
+            avio_wb32(pb, codec->time_base.den);
+            avio_wb16(pb, codec->width);
+            avio_wb16(pb, codec->height);
+            avio_wb16(pb, codec->gop_size);
+            avio_wb32(pb, codec->pix_fmt);
+            avio_w8(pb, codec->qmin);
+            avio_w8(pb, codec->qmax);
+            avio_w8(pb, codec->max_qdiff);
+            avio_wb16(pb, (int) (codec->qcompress * 10000.0));
+            avio_wb16(pb, (int) (codec->qblur * 10000.0));
+            avio_wb32(pb, codec->bit_rate_tolerance);
+            avio_put_str(pb, codec->rc_eq ? codec->rc_eq : "tex^qComp");
+            avio_wb32(pb, codec->rc_max_rate);
+            avio_wb32(pb, codec->rc_min_rate);
+            avio_wb32(pb, codec->rc_buffer_size);
+            avio_wb64(pb, av_dbl2int(codec->i_quant_factor));
+            avio_wb64(pb, av_dbl2int(codec->b_quant_factor));
+            avio_wb64(pb, av_dbl2int(codec->i_quant_offset));
+            avio_wb64(pb, av_dbl2int(codec->b_quant_offset));
+            avio_wb32(pb, codec->dct_algo);
+            avio_wb32(pb, codec->strict_std_compliance);
+            avio_wb32(pb, codec->max_b_frames);
+            avio_wb32(pb, codec->luma_elim_threshold);
+            avio_wb32(pb, codec->chroma_elim_threshold);
+            avio_wb32(pb, codec->mpeg_quant);
+            avio_wb32(pb, codec->intra_dc_precision);
+            avio_wb32(pb, codec->me_method);
+            avio_wb32(pb, codec->mb_decision);
+            avio_wb32(pb, codec->nsse_weight);
+            avio_wb32(pb, codec->frame_skip_cmp);
+            avio_wb64(pb, av_dbl2int(codec->rc_buffer_aggressivity));
+            avio_wb32(pb, codec->codec_tag);
+            avio_w8(pb, codec->thread_count);
+            avio_wb32(pb, codec->coder_type);
+            avio_wb32(pb, codec->me_cmp);
+            avio_wb32(pb, codec->partitions);
+            avio_wb32(pb, codec->me_subpel_quality);
+            avio_wb32(pb, codec->me_range);
+            avio_wb32(pb, codec->keyint_min);
+            avio_wb32(pb, codec->scenechange_threshold);
+            avio_wb32(pb, codec->b_frame_strategy);
+            avio_wb64(pb, av_dbl2int(codec->qcompress));
+            avio_wb64(pb, av_dbl2int(codec->qblur));
+            avio_wb32(pb, codec->max_qdiff);
+            avio_wb32(pb, codec->refs);
+            avio_wb32(pb, codec->directpred);
             break;
         case AVMEDIA_TYPE_AUDIO:
-            put_be32(pb, codec->sample_rate);
-            put_le16(pb, codec->channels);
-            put_le16(pb, codec->frame_size);
-            put_le16(pb, codec->sample_fmt);
+            avio_wb32(pb, codec->sample_rate);
+            avio_wl16(pb, codec->channels);
+            avio_wl16(pb, codec->frame_size);
+            avio_wl16(pb, codec->sample_fmt);
             break;
         default:
             return -1;
         }
         if (codec->flags & CODEC_FLAG_GLOBAL_HEADER) {
-            put_be32(pb, codec->extradata_size);
-            put_buffer(pb, codec->extradata, codec->extradata_size);
+            avio_wb32(pb, codec->extradata_size);
+            avio_write(pb, codec->extradata, codec->extradata_size);
         }
     }
 
     /* flush until end of block reached */
-    while ((url_ftell(pb) % ffm->packet_size) != 0)
-        put_byte(pb, 0);
+    while ((avio_tell(pb) % ffm->packet_size) != 0)
+        avio_w8(pb, 0);
 
-    put_flush_packet(pb);
+    avio_flush(pb);
 
     /* init packet mux */
     ffm->packet_ptr = ffm->packet;
@@ -228,19 +228,19 @@ static int ffm_write_packet(AVFormatContext *s, AVPacket *pkt)
 
 static int ffm_write_trailer(AVFormatContext *s)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     FFMContext *ffm = s->priv_data;
 
     /* flush packets */
     if (ffm->packet_ptr > ffm->packet)
         flush_packet(s);
 
-    put_flush_packet(pb);
+    avio_flush(pb);
 
     return 0;
 }
 
-AVOutputFormat ffm_muxer = {
+AVOutputFormat ff_ffm_muxer = {
     "ffm",
     NULL_IF_CONFIG_SMALL("FFM (FFserver live feed) format"),
     "",
diff --git a/libavformat/ffmeta.h b/libavformat/ffmeta.h
new file mode 100644
index 0000000..bce272a
--- /dev/null
+++ b/libavformat/ffmeta.h
@@ -0,0 +1,29 @@
+/*
+ * Common data for metadata muxer/demuxer
+ * Copyright (c) 2010 Anton Khirnov
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVFORMAT_META_H
+#define AVFORMAT_META_H
+
+#define ID_STRING  ";FFMETADATA"
+#define ID_CHAPTER "[CHAPTER]"
+#define ID_STREAM  "[STREAM]"
+
+#endif /* AVFORMAT_META_H */
diff --git a/libavformat/ffmetadec.c b/libavformat/ffmetadec.c
new file mode 100644
index 0000000..6915b60
--- /dev/null
+++ b/libavformat/ffmetadec.c
@@ -0,0 +1,173 @@
+/*
+ * Metadata demuxer
+ * Copyright (c) 2010 Anton Khirnov
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "avformat.h"
+#include "ffmeta.h"
+#include "internal.h"
+
+static int probe(AVProbeData *p)
+{
+    if(!memcmp(p->buf, ID_STRING, strlen(ID_STRING)))
+        return AVPROBE_SCORE_MAX;
+    return 0;
+}
+
+static void get_line(AVIOContext *s, uint8_t *buf, int size)
+{
+    do {
+        uint8_t c;
+        int i = 0;
+
+        while ((c = avio_r8(s))) {
+            if (c == '\\') {
+                if (i < size - 1)
+                    buf[i++] = c;
+                c = avio_r8(s);
+            } else if (c == '\n')
+                break;
+
+            if (i < size - 1)
+                buf[i++] = c;
+        }
+        buf[i] = 0;
+    } while (!s->eof_reached && (buf[0] == ';' || buf[0] == '#' || buf[0] == 0));
+}
+
+static AVChapter *read_chapter(AVFormatContext *s)
+{
+    uint8_t line[256];
+    int64_t start, end;
+    AVRational tb = {1, 1e9};
+
+    get_line(s->pb, line, sizeof(line));
+
+    if (sscanf(line, "TIMEBASE=%d/%d", &tb.num, &tb.den))
+        get_line(s->pb, line, sizeof(line));
+    if (!sscanf(line, "START=%"SCNd64, &start)) {
+        av_log(s, AV_LOG_ERROR, "Expected chapter start timestamp, found %s.\n", line);
+        start = (s->nb_chapters && s->chapters[s->nb_chapters - 1]->end != AV_NOPTS_VALUE) ?
+                 s->chapters[s->nb_chapters - 1]->end : 0;
+    } else
+        get_line(s->pb, line, sizeof(line));
+
+    if (!sscanf(line, "END=%"SCNd64, &end)) {
+        av_log(s, AV_LOG_ERROR, "Expected chapter end timestamp, found %s.\n", line);
+        end = AV_NOPTS_VALUE;
+    }
+
+    return ff_new_chapter(s, s->nb_chapters, tb, start, end, NULL);
+}
+
+static uint8_t *unescape(uint8_t *buf, int size)
+{
+    uint8_t *ret = av_malloc(size + 1);
+    uint8_t *p1  = ret, *p2 = buf;
+
+    if (!ret)
+        return NULL;
+
+    while (p2 < buf + size) {
+        if (*p2 == '\\')
+            p2++;
+        *p1++ = *p2++;
+    }
+    *p1 = 0;
+    return ret;
+}
+
+static int read_tag(uint8_t *line, AVMetadata **m)
+{
+    uint8_t *key, *value, *p = line;
+
+    /* find first not escaped '=' */
+    while (1) {
+        if (*p == '=')
+            break;
+        else if (*p == '\\')
+            p++;
+
+        if (*p++)
+            continue;
+
+        return 0;
+    }
+
+    if (!(key = unescape(line, p - line)))
+        return AVERROR(ENOMEM);
+    if (!(value = unescape(p + 1, strlen(p + 1)))) {
+        av_free(key);
+        return AVERROR(ENOMEM);
+    }
+
+    av_metadata_set2(m, key, value, AV_METADATA_DONT_STRDUP_KEY | AV_METADATA_DONT_STRDUP_VAL);
+    return 0;
+}
+
+static int read_header(AVFormatContext *s, AVFormatParameters *ap)
+{
+    AVMetadata **m = &s->metadata;
+    uint8_t line[1024];
+
+    while(!s->pb->eof_reached) {
+        get_line(s->pb, line, sizeof(line));
+
+        if (!memcmp(line, ID_STREAM, strlen(ID_STREAM))) {
+            AVStream *st = av_new_stream(s, 0);
+
+            if (!st)
+                return -1;
+
+            st->codec->codec_type = AVMEDIA_TYPE_DATA;
+            st->codec->codec_id   = CODEC_ID_FFMETADATA;
+
+            m = &st->metadata;
+        } else if (!memcmp(line, ID_CHAPTER, strlen(ID_CHAPTER))) {
+            AVChapter *ch = read_chapter(s);
+
+            if (!ch)
+                return -1;
+
+            m = &ch->metadata;
+        } else
+            read_tag(line, m);
+    }
+
+    s->start_time = 0;
+    if (s->nb_chapters)
+        s->duration = av_rescale_q(s->chapters[s->nb_chapters - 1]->end,
+                                   s->chapters[s->nb_chapters - 1]->time_base,
+                                   AV_TIME_BASE_Q);
+
+    return 0;
+}
+
+static int read_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    return AVERROR_EOF;
+}
+
+AVInputFormat ff_ffmetadata_demuxer = {
+    .name        = "ffmetadata",
+    .long_name   = NULL_IF_CONFIG_SMALL("FFmpeg metadata in text format"),
+    .read_probe  = probe,
+    .read_header = read_header,
+    .read_packet = read_packet,
+};
diff --git a/libavformat/ffmetaenc.c b/libavformat/ffmetaenc.c
new file mode 100644
index 0000000..178da59
--- /dev/null
+++ b/libavformat/ffmetaenc.c
@@ -0,0 +1,100 @@
+/*
+ * Metadata muxer
+ * Copyright (c) 2010 Anton Khirnov
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <inttypes.h>
+
+#include "avformat.h"
+#include "ffmeta.h"
+
+
+static void write_escape_str(AVIOContext *s, const uint8_t *str)
+{
+    const uint8_t *p = str;
+
+    while (*p) {
+        if (*p == '#' || *p == ';' || *p == '=' || *p == '\\' || *p == '\n')
+            avio_w8(s, '\\');
+        avio_w8(s, *p);
+        p++;
+    }
+}
+
+static void write_tags(AVIOContext *s, AVMetadata *m)
+{
+    AVMetadataTag *t = NULL;
+    while ((t = av_metadata_get(m, "", t, AV_METADATA_IGNORE_SUFFIX))) {
+        write_escape_str(s, t->key);
+        avio_w8(s, '=');
+        write_escape_str(s, t->value);
+        avio_w8(s, '\n');
+    }
+}
+
+static int write_header(AVFormatContext *s)
+{
+    avio_write(s->pb, ID_STRING, sizeof(ID_STRING) - 1);
+    avio_w8(s->pb, '1');          // version
+    avio_w8(s->pb, '\n');
+    avio_flush(s->pb);
+    return 0;
+}
+
+static int write_trailer(AVFormatContext *s)
+{
+    int i;
+
+    write_tags(s->pb, s->metadata);
+
+    for (i = 0; i < s->nb_streams; i++) {
+        avio_write(s->pb, ID_STREAM, sizeof(ID_STREAM) - 1);
+        avio_w8(s->pb, '\n');
+        write_tags(s->pb, s->streams[i]->metadata);
+    }
+
+    for (i = 0; i < s->nb_chapters; i++) {
+        AVChapter *ch = s->chapters[i];
+        avio_write(s->pb, ID_CHAPTER, sizeof(ID_CHAPTER) - 1);
+        avio_w8(s->pb, '\n');
+        avio_printf(s->pb, "TIMEBASE=%d/%d\n", ch->time_base.num, ch->time_base.den);
+        avio_printf(s->pb, "START=%"PRId64"\n", ch->start);
+        avio_printf(s->pb, "END=%"PRId64"\n",   ch->end);
+        write_tags(s->pb, ch->metadata);
+    }
+
+    avio_flush(s->pb);
+
+    return 0;
+}
+
+static int write_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    return 0;
+}
+
+AVOutputFormat ff_ffmetadata_muxer = {
+    .name          = "ffmetadata",
+    .long_name     = NULL_IF_CONFIG_SMALL("FFmpeg metadata in text format"),
+    .extensions    = "ffmeta",
+    .write_header  = write_header,
+    .write_packet  = write_packet,
+    .write_trailer = write_trailer,
+    .flags         = AVFMT_NOTIMESTAMPS | AVFMT_NOSTREAMS,
+};
diff --git a/libavformat/file.c b/libavformat/file.c
index 8873d5f..1dcb2c8 100644
--- a/libavformat/file.c
+++ b/libavformat/file.c
@@ -2,20 +2,20 @@
  * Buffered file io for ffmpeg system
  * Copyright (c) 2001 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -27,13 +27,32 @@
 #endif
 #include <unistd.h>
 #include <sys/stat.h>
-#include <sys/time.h>
 #include <stdlib.h>
 #include "os_support.h"
+#include "url.h"
 
 
 /* standard file protocol */
 
+static int file_read(URLContext *h, unsigned char *buf, int size)
+{
+    int fd = (intptr_t) h->priv_data;
+    return read(fd, buf, size);
+}
+
+static int file_write(URLContext *h, const unsigned char *buf, int size)
+{
+    int fd = (intptr_t) h->priv_data;
+    return write(fd, buf, size);
+}
+
+static int file_get_handle(URLContext *h)
+{
+    return (intptr_t) h->priv_data;
+}
+
+#if CONFIG_FILE_PROTOCOL
+
 static int file_open(URLContext *h, const char *filename, int flags)
 {
     int access;
@@ -41,9 +60,9 @@ static int file_open(URLContext *h, const char *filename, int flags)
 
     av_strstart(filename, "file:", &filename);
 
-    if (flags & URL_RDWR) {
+    if (flags & AVIO_RDWR) {
         access = O_CREAT | O_TRUNC | O_RDWR;
-    } else if (flags & URL_WRONLY) {
+    } else if (flags & AVIO_WRONLY) {
         access = O_CREAT | O_TRUNC | O_WRONLY;
     } else {
         access = O_RDONLY;
@@ -58,18 +77,6 @@ static int file_open(URLContext *h, const char *filename, int flags)
     return 0;
 }
 
-static int file_read(URLContext *h, unsigned char *buf, int size)
-{
-    int fd = (intptr_t) h->priv_data;
-    return read(fd, buf, size);
-}
-
-static int file_write(URLContext *h, unsigned char *buf, int size)
-{
-    int fd = (intptr_t) h->priv_data;
-    return write(fd, buf, size);
-}
-
 /* XXX: use llseek */
 static int64_t file_seek(URLContext *h, int64_t pos, int whence)
 {
@@ -88,22 +95,34 @@ static int file_close(URLContext *h)
     return close(fd);
 }
 
-static int file_get_handle(URLContext *h)
+static int file_check(URLContext *h, int mask)
 {
-    return (intptr_t) h->priv_data;
+    struct stat st;
+    int ret = stat(h->filename, &st);
+    if (ret < 0)
+        return AVERROR(errno);
+
+    ret |= st.st_mode&S_IRUSR ? mask&AVIO_RDONLY : 0;
+    ret |= st.st_mode&S_IWUSR ? mask&AVIO_WRONLY : 0;
+    ret |= st.st_mode&S_IWUSR && st.st_mode&S_IRUSR ? mask&AVIO_RDWR : 0;
+
+    return ret;
 }
 
-URLProtocol file_protocol = {
-    "file",
-    file_open,
-    file_read,
-    file_write,
-    file_seek,
-    file_close,
+URLProtocol ff_file_protocol = {
+    .name                = "file",
+    .url_open            = file_open,
+    .url_read            = file_read,
+    .url_write           = file_write,
+    .url_seek            = file_seek,
+    .url_close           = file_close,
     .url_get_file_handle = file_get_handle,
+    .url_check           = file_check,
 };
 
-/* pipe protocol */
+#endif /* CONFIG_FILE_PROTOCOL */
+
+#if CONFIG_PIPE_PROTOCOL
 
 static int pipe_open(URLContext *h, const char *filename, int flags)
 {
@@ -113,7 +132,7 @@ static int pipe_open(URLContext *h, const char *filename, int flags)
 
     fd = strtol(filename, &final, 10);
     if((filename == final) || *final ) {/* No digits found, or something like 10ab */
-        if (flags & URL_WRONLY) {
+        if (flags & AVIO_WRONLY) {
             fd = 1;
         } else {
             fd = 0;
@@ -127,10 +146,13 @@ static int pipe_open(URLContext *h, const char *filename, int flags)
     return 0;
 }
 
-URLProtocol pipe_protocol = {
-    "pipe",
-    pipe_open,
-    file_read,
-    file_write,
+URLProtocol ff_pipe_protocol = {
+    .name                = "pipe",
+    .url_open            = pipe_open,
+    .url_read            = file_read,
+    .url_write           = file_write,
     .url_get_file_handle = file_get_handle,
+    .url_check           = file_check,
 };
+
+#endif /* CONFIG_PIPE_PROTOCOL */
diff --git a/libavformat/filmstripdec.c b/libavformat/filmstripdec.c
index 0442fc3..095bf9e 100644
--- a/libavformat/filmstripdec.c
+++ b/libavformat/filmstripdec.c
@@ -2,20 +2,20 @@
  * Adobe Filmstrip demuxer
  * Copyright (c) 2010 Peter Ross
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -37,14 +37,14 @@ static int read_header(AVFormatContext *s,
                        AVFormatParameters *ap)
 {
     FilmstripDemuxContext *film = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVStream *st;
 
-    if (url_is_streamed(s->pb))
+    if (!s->pb->seekable)
         return AVERROR(EIO);
 
-    url_fseek(pb, url_fsize(pb) - 36, SEEK_SET);
-    if (get_be32(pb) != RAND_TAG) {
+    avio_seek(pb, avio_size(pb) - 36, SEEK_SET);
+    if (avio_rb32(pb) != RAND_TAG) {
         av_log(s, AV_LOG_ERROR, "magic number not found");
         return AVERROR_INVALIDDATA;
     }
@@ -53,23 +53,23 @@ static int read_header(AVFormatContext *s,
     if (!st)
         return AVERROR(ENOMEM);
 
-    st->nb_frames = get_be32(pb);
-    if (get_be16(pb) != 0) {
+    st->nb_frames = avio_rb32(pb);
+    if (avio_rb16(pb) != 0) {
         av_log_ask_for_sample(s, "unsupported packing method\n");
         return AVERROR_INVALIDDATA;
     }
 
-    url_fskip(pb, 2);
+    avio_skip(pb, 2);
     st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
     st->codec->codec_id   = CODEC_ID_RAWVIDEO;
     st->codec->pix_fmt    = PIX_FMT_RGBA;
     st->codec->codec_tag  = 0; /* no fourcc */
-    st->codec->width      = get_be16(pb);
-    st->codec->height     = get_be16(pb);
-    film->leading         = get_be16(pb);
-    av_set_pts_info(st, 64, 1, get_be16(pb));
+    st->codec->width      = avio_rb16(pb);
+    st->codec->height     = avio_rb16(pb);
+    film->leading         = avio_rb16(pb);
+    av_set_pts_info(st, 64, 1, avio_rb16(pb));
 
-    url_fseek(pb, 0, SEEK_SET);
+    avio_seek(pb, 0, SEEK_SET);
 
     return 0;
 }
@@ -80,11 +80,11 @@ static int read_packet(AVFormatContext *s,
     FilmstripDemuxContext *film = s->priv_data;
     AVStream *st = s->streams[0];
 
-    if (url_feof(s->pb))
+    if (s->pb->eof_reached)
         return AVERROR(EIO);
-    pkt->dts = url_ftell(s->pb) / (st->codec->width * (st->codec->height + film->leading) * 4);
+    pkt->dts = avio_tell(s->pb) / (st->codec->width * (st->codec->height + film->leading) * 4);
     pkt->size = av_get_packet(s->pb, pkt, st->codec->width * st->codec->height * 4);
-    url_fskip(s->pb, st->codec->width * film->leading * 4);
+    avio_skip(s->pb, st->codec->width * film->leading * 4);
     if (pkt->size < 0)
         return pkt->size;
     pkt->flags |= AV_PKT_FLAG_KEY;
@@ -94,11 +94,11 @@ static int read_packet(AVFormatContext *s,
 static int read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
 {
     AVStream *st = s->streams[stream_index];
-    url_fseek(s->pb, FFMAX(timestamp, 0) * st->codec->width * st->codec->height * 4, SEEK_SET);
+    avio_seek(s->pb, FFMAX(timestamp, 0) * st->codec->width * st->codec->height * 4, SEEK_SET);
     return 0;
 }
 
-AVInputFormat filmstrip_demuxer = {
+AVInputFormat ff_filmstrip_demuxer = {
     "filmstrip",
     NULL_IF_CONFIG_SMALL("Adobe Filmstrip"),
     sizeof(FilmstripDemuxContext),
diff --git a/libavformat/filmstripenc.c b/libavformat/filmstripenc.c
index 4e10c28..21f4755 100644
--- a/libavformat/filmstripenc.c
+++ b/libavformat/filmstripenc.c
@@ -2,20 +2,20 @@
  * Adobe Filmstrip muxer
  * Copyright (c) 2010 Peter Ross
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -45,7 +45,7 @@ static int write_header(AVFormatContext *s)
 static int write_packet(AVFormatContext *s, AVPacket *pkt)
 {
     FilmstripMuxContext *film = s->priv_data;
-    put_buffer(s->pb, pkt->data, pkt->size);
+    avio_write(s->pb, pkt->data, pkt->size);
     film->nb_frames++;
     return 0;
 }
@@ -53,25 +53,25 @@ static int write_packet(AVFormatContext *s, AVPacket *pkt)
 static int write_trailer(AVFormatContext *s)
 {
     FilmstripMuxContext *film = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVStream *st = s->streams[0];
     int i;
 
-    put_be32(pb, RAND_TAG);
-    put_be32(pb, film->nb_frames);
-    put_be16(pb, 0);  // packing method
-    put_be16(pb, 0);  // reserved
-    put_be16(pb, st->codec->width);
-    put_be16(pb, st->codec->height);
-    put_be16(pb, 0);  // leading
-    put_be16(pb, 1/av_q2d(st->codec->time_base));
+    avio_wb32(pb, RAND_TAG);
+    avio_wb32(pb, film->nb_frames);
+    avio_wb16(pb, 0);  // packing method
+    avio_wb16(pb, 0);  // reserved
+    avio_wb16(pb, st->codec->width);
+    avio_wb16(pb, st->codec->height);
+    avio_wb16(pb, 0);  // leading
+    avio_wb16(pb, 1/av_q2d(st->codec->time_base));
     for (i = 0; i < 16; i++)
-        put_byte(pb, 0x00);  // reserved
-    put_flush_packet(pb);
+        avio_w8(pb, 0x00);  // reserved
+    avio_flush(pb);
     return 0;
 }
 
-AVOutputFormat filmstrip_muxer = {
+AVOutputFormat ff_filmstrip_muxer = {
     "filmstrip",
     NULL_IF_CONFIG_SMALL("Adobe Filmstrip"),
     NULL,
diff --git a/libavformat/flacdec.c b/libavformat/flacdec.c
index 2ceef96..02452b4 100644
--- a/libavformat/flacdec.c
+++ b/libavformat/flacdec.c
@@ -2,34 +2,32 @@
  * Raw FLAC demuxer
  * Copyright (c) 2001 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "libavcodec/flac.h"
 #include "avformat.h"
-#include "raw.h"
-#include "id3v2.h"
+#include "rawdec.h"
 #include "oggdec.h"
 #include "vorbiscomment.h"
 
 static int flac_read_header(AVFormatContext *s,
                              AVFormatParameters *ap)
 {
-    uint8_t buf[ID3v2_HEADER_SIZE];
     int ret, metadata_last=0, metadata_type, metadata_size, found_streaminfo=0;
     uint8_t header[4];
     uint8_t *buffer=NULL;
@@ -41,24 +39,15 @@ static int flac_read_header(AVFormatContext *s,
     st->need_parsing = AVSTREAM_PARSE_FULL;
     /* the parameters will be extracted from the compressed bitstream */
 
-    /* skip ID3v2 header if found */
-    ret = get_buffer(s->pb, buf, ID3v2_HEADER_SIZE);
-    if (ret == ID3v2_HEADER_SIZE && ff_id3v2_match(buf)) {
-        int len = ff_id3v2_tag_len(buf);
-        url_fseek(s->pb, len - ID3v2_HEADER_SIZE, SEEK_CUR);
-    } else {
-        url_fseek(s->pb, 0, SEEK_SET);
-    }
-
     /* if fLaC marker is not found, assume there is no header */
-    if (get_le32(s->pb) != MKTAG('f','L','a','C')) {
-        url_fseek(s->pb, -4, SEEK_CUR);
+    if (avio_rl32(s->pb) != MKTAG('f','L','a','C')) {
+        avio_seek(s->pb, -4, SEEK_CUR);
         return 0;
     }
 
     /* process metadata blocks */
-    while (!url_feof(s->pb) && !metadata_last) {
-        get_buffer(s->pb, header, 4);
+    while (!s->pb->eof_reached && !metadata_last) {
+        avio_read(s->pb, header, 4);
         ff_flac_parse_block_header(header, &metadata_last, &metadata_type,
                                    &metadata_size);
         switch (metadata_type) {
@@ -69,14 +58,14 @@ static int flac_read_header(AVFormatContext *s,
             if (!buffer) {
                 return AVERROR(ENOMEM);
             }
-            if (get_buffer(s->pb, buffer, metadata_size) != metadata_size) {
+            if (avio_read(s->pb, buffer, metadata_size) != metadata_size) {
                 av_freep(&buffer);
                 return AVERROR(EIO);
             }
             break;
         /* skip metadata block for unsupported types */
         default:
-            ret = url_fseek(s->pb, metadata_size, SEEK_CUR);
+            ret = avio_skip(s->pb, metadata_size);
             if (ret < 0)
                 return ret;
         }
@@ -130,14 +119,11 @@ static int flac_probe(AVProbeData *p)
     uint8_t *bufptr = p->buf;
     uint8_t *end    = p->buf + p->buf_size;
 
-    if(ff_id3v2_match(bufptr))
-        bufptr += ff_id3v2_tag_len(bufptr);
-
     if(bufptr > end-4 || memcmp(bufptr, "fLaC", 4)) return 0;
     else                                            return AVPROBE_SCORE_MAX/2;
 }
 
-AVInputFormat flac_demuxer = {
+AVInputFormat ff_flac_demuxer = {
     "flac",
     NULL_IF_CONFIG_SMALL("raw FLAC"),
     0,
@@ -147,5 +133,4 @@ AVInputFormat flac_demuxer = {
     .flags= AVFMT_GENERIC_INDEX,
     .extensions = "flac",
     .value = CODEC_ID_FLAC,
-    .metadata_conv = ff_vorbiscomment_metadata_conv,
 };
diff --git a/libavformat/flacenc.c b/libavformat/flacenc.c
index 91a080f..38c3265 100644
--- a/libavformat/flacenc.c
+++ b/libavformat/flacenc.c
@@ -2,20 +2,20 @@
  * raw FLAC muxer
  * Copyright (c) 2006-2009 Justin Ruggles
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -27,26 +27,28 @@
 #include "libavcodec/bytestream.h"
 
 
-static int flac_write_block_padding(ByteIOContext *pb, unsigned int n_padding_bytes,
+static int flac_write_block_padding(AVIOContext *pb, unsigned int n_padding_bytes,
                                     int last_block)
 {
-    put_byte(pb, last_block ? 0x81 : 0x01);
-    put_be24(pb, n_padding_bytes);
+    avio_w8(pb, last_block ? 0x81 : 0x01);
+    avio_wb24(pb, n_padding_bytes);
     while (n_padding_bytes > 0) {
-        put_byte(pb, 0);
+        avio_w8(pb, 0);
         n_padding_bytes--;
     }
     return 0;
 }
 
-static int flac_write_block_comment(ByteIOContext *pb, AVMetadata *m,
+static int flac_write_block_comment(AVIOContext *pb, AVMetadata **m,
                                     int last_block, int bitexact)
 {
     const char *vendor = bitexact ? "ffmpeg" : LIBAVFORMAT_IDENT;
     unsigned int len, count;
     uint8_t *p, *p0;
 
-    len = ff_vorbiscomment_length(m, vendor, &count);
+    ff_metadata_conv(m, ff_vorbiscomment_metadata_conv, NULL);
+
+    len = ff_vorbiscomment_length(*m, vendor, &count);
     p0 = av_malloc(len+4);
     if (!p0)
         return AVERROR(ENOMEM);
@@ -56,7 +58,7 @@ static int flac_write_block_comment(ByteIOContext *pb, AVMetadata *m,
     bytestream_put_be24(&p, len);
     ff_vorbiscomment_write(&p, m, vendor, count);
 
-    put_buffer(pb, p0, len+4);
+    avio_write(pb, p0, len+4);
     av_freep(&p0);
     p = NULL;
 
@@ -72,7 +74,7 @@ static int flac_write_header(struct AVFormatContext *s)
     if (ret)
         return ret;
 
-    ret = flac_write_block_comment(s->pb, s->metadata, 0,
+    ret = flac_write_block_comment(s->pb, &s->metadata, 0,
                                    codec->flags & CODEC_FLAG_BITEXACT);
     if (ret)
         return ret;
@@ -88,7 +90,7 @@ static int flac_write_header(struct AVFormatContext *s)
 
 static int flac_write_trailer(struct AVFormatContext *s)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     uint8_t *streaminfo;
     enum FLACExtradataFormat format;
     int64_t file_size;
@@ -96,13 +98,13 @@ static int flac_write_trailer(struct AVFormatContext *s)
     if (!ff_flac_is_extradata_valid(s->streams[0]->codec, &format, &streaminfo))
         return -1;
 
-    if (!url_is_streamed(pb)) {
+    if (pb->seekable) {
         /* rewrite the STREAMINFO header block data */
-        file_size = url_ftell(pb);
-        url_fseek(pb, 8, SEEK_SET);
-        put_buffer(pb, streaminfo, FLAC_STREAMINFO_SIZE);
-        url_fseek(pb, file_size, SEEK_SET);
-        put_flush_packet(pb);
+        file_size = avio_tell(pb);
+        avio_seek(pb, 8, SEEK_SET);
+        avio_write(pb, streaminfo, FLAC_STREAMINFO_SIZE);
+        avio_seek(pb, file_size, SEEK_SET);
+        avio_flush(pb);
     } else {
         av_log(s, AV_LOG_WARNING, "unable to rewrite FLAC header.\n");
     }
@@ -111,12 +113,12 @@ static int flac_write_trailer(struct AVFormatContext *s)
 
 static int flac_write_packet(struct AVFormatContext *s, AVPacket *pkt)
 {
-    put_buffer(s->pb, pkt->data, pkt->size);
-    put_flush_packet(s->pb);
+    avio_write(s->pb, pkt->data, pkt->size);
+    avio_flush(s->pb);
     return 0;
 }
 
-AVOutputFormat flac_muxer = {
+AVOutputFormat ff_flac_muxer = {
     "flac",
     NULL_IF_CONFIG_SMALL("raw FLAC"),
     "audio/x-flac",
@@ -128,5 +130,4 @@ AVOutputFormat flac_muxer = {
     flac_write_packet,
     flac_write_trailer,
     .flags= AVFMT_NOTIMESTAMPS,
-    .metadata_conv = ff_vorbiscomment_metadata_conv,
 };
diff --git a/libavformat/flacenc.h b/libavformat/flacenc.h
index 8ad1c26..2edda67 100644
--- a/libavformat/flacenc.h
+++ b/libavformat/flacenc.h
@@ -2,20 +2,20 @@
  * raw FLAC muxer
  * Copyright (C) 2009 Justin Ruggles
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -26,7 +26,7 @@
 #include "libavcodec/bytestream.h"
 #include "avformat.h"
 
-int ff_flac_write_header(ByteIOContext *pb, AVCodecContext *codec,
+int ff_flac_write_header(AVIOContext *pb, AVCodecContext *codec,
                          int last_block);
 
 #endif /* AVFORMAT_FLACENC_H */
diff --git a/libavformat/flacenc_header.c b/libavformat/flacenc_header.c
index 92a129a..90c5a77 100644
--- a/libavformat/flacenc_header.c
+++ b/libavformat/flacenc_header.c
@@ -2,20 +2,20 @@
  * raw FLAC muxer
  * Copyright (C) 2009 Justin Ruggles
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -24,7 +24,7 @@
 #include "avformat.h"
 #include "flacenc.h"
 
-int ff_flac_write_header(ByteIOContext *pb, AVCodecContext *codec,
+int ff_flac_write_header(AVIOContext *pb, AVCodecContext *codec,
                          int last_block)
 {
     uint8_t header[8] = {
@@ -39,11 +39,11 @@ int ff_flac_write_header(ByteIOContext *pb, AVCodecContext *codec,
 
     /* write "fLaC" stream marker and first metadata block header if needed */
     if (format == FLAC_EXTRADATA_FORMAT_STREAMINFO) {
-        put_buffer(pb, header, 8);
+        avio_write(pb, header, 8);
     }
 
     /* write STREAMINFO or full header */
-    put_buffer(pb, codec->extradata, codec->extradata_size);
+    avio_write(pb, codec->extradata, codec->extradata_size);
 
     return 0;
 }
diff --git a/libavformat/flic.c b/libavformat/flic.c
index 27145db..fcdf4c8 100644
--- a/libavformat/flic.c
+++ b/libavformat/flic.c
@@ -2,20 +2,20 @@
  * FLI/FLC Animation File Demuxer
  * Copyright (c) 2003 The ffmpeg Project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -32,6 +32,7 @@
  */
 
 #include "libavutil/intreadwrite.h"
+#include "libavutil/audioconvert.h"
 #include "avformat.h"
 
 #define FLIC_FILE_MAGIC_1 0xAF11
@@ -85,7 +86,7 @@ static int flic_read_header(AVFormatContext *s,
                             AVFormatParameters *ap)
 {
     FlicDemuxContext *flic = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     unsigned char header[FLIC_HEADER_SIZE];
     AVStream *st, *ast;
     int speed;
@@ -95,7 +96,7 @@ static int flic_read_header(AVFormatContext *s,
     flic->frame_number = 0;
 
     /* load the whole header and pull out the width and height */
-    if (get_buffer(pb, header, FLIC_HEADER_SIZE) != FLIC_HEADER_SIZE)
+    if (avio_read(pb, header, FLIC_HEADER_SIZE) != FLIC_HEADER_SIZE)
         return AVERROR(EIO);
 
     magic_number = AV_RL16(&header[4]);
@@ -116,7 +117,7 @@ static int flic_read_header(AVFormatContext *s,
 
     if (!st->codec->width || !st->codec->height) {
         /* Ugly hack needed for the following sample: */
-        /* http://samples.mplayerhq.hu/fli-flc/fli-bugs/specular.flc */
+        /* http://samples.libav.org/fli-flc/fli-bugs/specular.flc */
         av_log(s, AV_LOG_WARNING,
                "File with no specified width/height. Trying 640x480.\n");
         st->codec->width  = 640;
@@ -129,12 +130,12 @@ static int flic_read_header(AVFormatContext *s,
     memcpy(st->codec->extradata, header, FLIC_HEADER_SIZE);
 
     /* peek at the preamble to detect TFTD videos - they seem to always start with an audio chunk */
-    if (get_buffer(pb, preamble, FLIC_PREAMBLE_SIZE) != FLIC_PREAMBLE_SIZE) {
+    if (avio_read(pb, preamble, FLIC_PREAMBLE_SIZE) != FLIC_PREAMBLE_SIZE) {
         av_log(s, AV_LOG_ERROR, "Failed to peek at preamble\n");
         return AVERROR(EIO);
     }
 
-    url_fseek(pb, -FLIC_PREAMBLE_SIZE, SEEK_CUR);
+    avio_seek(pb, -FLIC_PREAMBLE_SIZE, SEEK_CUR);
 
     /* Time to figure out the framerate:
      * If the first preamble's magic number is 0xAAAA then this file is from
@@ -152,15 +153,15 @@ static int flic_read_header(AVFormatContext *s,
 
         /* all audio frames are the same size, so use the size of the first chunk for block_align */
         ast->codec->block_align = AV_RL32(&preamble[0]);
-        ast->codec->codec_type = CODEC_TYPE_AUDIO;
+        ast->codec->codec_type = AVMEDIA_TYPE_AUDIO;
         ast->codec->codec_id = CODEC_ID_PCM_U8;
         ast->codec->codec_tag = 0;
         ast->codec->sample_rate = FLIC_TFTD_SAMPLE_RATE;
         ast->codec->channels = 1;
-        ast->codec->sample_fmt = SAMPLE_FMT_U8;
+        ast->codec->sample_fmt = AV_SAMPLE_FMT_U8;
         ast->codec->bit_rate = st->codec->sample_rate * 8;
         ast->codec->bits_per_coded_sample = 8;
-        ast->codec->channel_layout = CH_LAYOUT_MONO;
+        ast->codec->channel_layout = AV_CH_LAYOUT_MONO;
         ast->codec->extradata_size = 0;
 
         /* Since the header information is incorrect we have to figure out the
@@ -172,7 +173,7 @@ static int flic_read_header(AVFormatContext *s,
         av_set_pts_info(st, 64, FLIC_MC_SPEED, 70);
 
         /* rewind the stream since the first chunk is at offset 12 */
-        url_fseek(pb, 12, SEEK_SET);
+        avio_seek(pb, 12, SEEK_SET);
 
         /* send over abbreviated FLIC header chunk */
         av_free(st->codec->extradata);
@@ -197,7 +198,7 @@ static int flic_read_packet(AVFormatContext *s,
                             AVPacket *pkt)
 {
     FlicDemuxContext *flic = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int packet_read = 0;
     unsigned int size;
     int magic;
@@ -206,7 +207,7 @@ static int flic_read_packet(AVFormatContext *s,
 
     while (!packet_read) {
 
-        if ((ret = get_buffer(pb, preamble, FLIC_PREAMBLE_SIZE)) !=
+        if ((ret = avio_read(pb, preamble, FLIC_PREAMBLE_SIZE)) !=
             FLIC_PREAMBLE_SIZE) {
             ret = AVERROR(EIO);
             break;
@@ -222,9 +223,9 @@ static int flic_read_packet(AVFormatContext *s,
             }
             pkt->stream_index = flic->video_stream_index;
             pkt->pts = flic->frame_number++;
-            pkt->pos = url_ftell(pb);
+            pkt->pos = avio_tell(pb);
             memcpy(pkt->data, preamble, FLIC_PREAMBLE_SIZE);
-            ret = get_buffer(pb, pkt->data + FLIC_PREAMBLE_SIZE,
+            ret = avio_read(pb, pkt->data + FLIC_PREAMBLE_SIZE,
                 size - FLIC_PREAMBLE_SIZE);
             if (ret != size - FLIC_PREAMBLE_SIZE) {
                 av_free_packet(pkt);
@@ -238,11 +239,11 @@ static int flic_read_packet(AVFormatContext *s,
             }
 
             /* skip useless 10B sub-header (yes, it's not accounted for in the chunk header) */
-            url_fseek(pb, 10, SEEK_CUR);
+            avio_skip(pb, 10);
 
             pkt->stream_index = flic->audio_stream_index;
-            pkt->pos = url_ftell(pb);
-            ret = get_buffer(pb, pkt->data, size);
+            pkt->pos = avio_tell(pb);
+            ret = avio_read(pb, pkt->data, size);
 
             if (ret != size) {
                 av_free_packet(pkt);
@@ -252,14 +253,14 @@ static int flic_read_packet(AVFormatContext *s,
             packet_read = 1;
         } else {
             /* not interested in this chunk */
-            url_fseek(pb, size - 6, SEEK_CUR);
+            avio_skip(pb, size - 6);
         }
     }
 
     return ret;
 }
 
-AVInputFormat flic_demuxer = {
+AVInputFormat ff_flic_demuxer = {
     "flic",
     NULL_IF_CONFIG_SMALL("FLI/FLC/FLX animation format"),
     sizeof(FlicDemuxContext),
diff --git a/libavformat/flv.h b/libavformat/flv.h
index 55266a1..c86e20a 100644
--- a/libavformat/flv.h
+++ b/libavformat/flv.h
@@ -2,22 +2,22 @@
  * @file
  * FLV common header
  *
- * Copyright (c) 2006 The FFmpeg Project
+ * Copyright (c) 2006 The Libav Project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -75,6 +75,7 @@ enum {
     FLV_CODECID_ADPCM                = 1 << FLV_AUDIO_CODECID_OFFSET,
     FLV_CODECID_MP3                  = 2 << FLV_AUDIO_CODECID_OFFSET,
     FLV_CODECID_PCM_LE               = 3 << FLV_AUDIO_CODECID_OFFSET,
+    FLV_CODECID_NELLYMOSER_16KHZ_MONO = 4 << FLV_AUDIO_CODECID_OFFSET,
     FLV_CODECID_NELLYMOSER_8KHZ_MONO = 5 << FLV_AUDIO_CODECID_OFFSET,
     FLV_CODECID_NELLYMOSER           = 6 << FLV_AUDIO_CODECID_OFFSET,
     FLV_CODECID_AAC                  = 10<< FLV_AUDIO_CODECID_OFFSET,
diff --git a/libavformat/flvdec.c b/libavformat/flvdec.c
index fcdf214..e7ec0b1 100644
--- a/libavformat/flvdec.c
+++ b/libavformat/flvdec.c
@@ -1,26 +1,26 @@
 /*
  * FLV demuxer
- * Copyright (c) 2003 The FFmpeg Project
+ * Copyright (c) 2003 The Libav Project
  *
  * This demuxer will generate a 1 byte extradata for VP6F content.
  * It is composed of:
  *  - upper 4bits: difference between encoded width and visible width
  *  - lower 4bits: difference between encoded height and visible height
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -28,8 +28,13 @@
 #include "libavcodec/bytestream.h"
 #include "libavcodec/mpeg4audio.h"
 #include "avformat.h"
+#include "avio_internal.h"
 #include "flv.h"
 
+#define KEYFRAMES_TAG            "keyframes"
+#define KEYFRAMES_TIMESTAMP_TAG  "times"
+#define KEYFRAMES_BYTEOFFSET_TAG "filepositions"
+
 typedef struct {
     int wrong_dts; ///< wrong dts due to negative cts
 } FLVContext;
@@ -68,6 +73,12 @@ static void flv_set_audio_codec(AVFormatContext *s, AVStream *astream, int flv_c
         case FLV_CODECID_MP3  : acodec->codec_id = CODEC_ID_MP3      ; astream->need_parsing = AVSTREAM_PARSE_FULL; break;
         case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
             acodec->sample_rate = 8000; //in case metadata does not otherwise declare samplerate
+            acodec->codec_id = CODEC_ID_NELLYMOSER;
+            break;
+        case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
+            acodec->sample_rate = 16000;
+            acodec->codec_id = CODEC_ID_NELLYMOSER;
+            break;
         case FLV_CODECID_NELLYMOSER:
             acodec->codec_id = CODEC_ID_NELLYMOSER;
             break;
@@ -91,7 +102,7 @@ static int flv_set_video_codec(AVFormatContext *s, AVStream *vstream, int flv_co
                 vcodec->extradata_size = 1;
                 vcodec->extradata = av_malloc(1);
             }
-            vcodec->extradata[0] = get_byte(s->pb);
+            vcodec->extradata[0] = avio_r8(s->pb);
             return 1; // 1 byte body size adjustment for flv_read_packet()
         case FLV_CODECID_H264:
             vcodec->codec_id = CODEC_ID_H264;
@@ -104,23 +115,91 @@ static int flv_set_video_codec(AVFormatContext *s, AVStream *vstream, int flv_co
     return 0;
 }
 
-static int amf_get_string(ByteIOContext *ioc, char *buffer, int buffsize) {
-    int length = get_be16(ioc);
+static int amf_get_string(AVIOContext *ioc, char *buffer, int buffsize) {
+    int length = avio_rb16(ioc);
     if(length >= buffsize) {
-        url_fskip(ioc, length);
+        avio_skip(ioc, length);
         return -1;
     }
 
-    get_buffer(ioc, buffer, length);
+    avio_read(ioc, buffer, length);
 
     buffer[length] = '\0';
 
     return length;
 }
 
+static int parse_keyframes_index(AVFormatContext *s, AVIOContext *ioc, AVStream *vstream, int64_t max_pos) {
+    unsigned int arraylen = 0, timeslen = 0, fileposlen = 0, i;
+    double num_val;
+    char str_val[256];
+    int64_t *times = NULL;
+    int64_t *filepositions = NULL;
+    int ret = AVERROR(ENOSYS);
+    int64_t initial_pos = avio_tell(ioc);
+
+    while (avio_tell(ioc) < max_pos - 2 && amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
+        int64_t* current_array;
+
+        // Expect array object in context
+        if (avio_r8(ioc) != AMF_DATA_TYPE_ARRAY)
+            break;
+
+        arraylen = avio_rb32(ioc);
+        /*
+         * Expect only 'times' or 'filepositions' sub-arrays in other case refuse to use such metadata
+         * for indexing
+         */
+        if (!strcmp(KEYFRAMES_TIMESTAMP_TAG, str_val) && !times) {
+            if (!(times = av_mallocz(sizeof(*times) * arraylen))) {
+                ret = AVERROR(ENOMEM);
+                goto finish;
+            }
+            timeslen = arraylen;
+            current_array = times;
+        } else if (!strcmp(KEYFRAMES_BYTEOFFSET_TAG, str_val) && !filepositions) {
+            if (!(filepositions = av_mallocz(sizeof(*filepositions) * arraylen))) {
+                ret = AVERROR(ENOMEM);
+                goto finish;
+            }
+            fileposlen = arraylen;
+            current_array = filepositions;
+        } else // unexpected metatag inside keyframes, will not use such metadata for indexing
+            break;
+
+        for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++) {
+            if (avio_r8(ioc) != AMF_DATA_TYPE_NUMBER)
+                goto finish;
+            num_val = av_int2dbl(avio_rb64(ioc));
+            current_array[i] = num_val;
+        }
+        if (times && filepositions) {
+            // All done, exiting at a position allowing amf_parse_object
+            // to finish parsing the object
+            ret = 0;
+            break;
+        }
+    }
+
+    if (timeslen == fileposlen)
+         for(i = 0; i < arraylen; i++)
+             av_add_index_entry(vstream, filepositions[i], times[i]*1000, 0, 0, AVINDEX_KEYFRAME);
+    else
+        av_log(s, AV_LOG_WARNING, "Invalid keyframes object, skipping.\n");
+
+finish:
+    av_freep(&times);
+    av_freep(&filepositions);
+    // If we got unexpected data, but successfully reset back to
+    // the start pos, the caller can continue parsing
+    if (ret < 0 && avio_seek(ioc, initial_pos, SEEK_SET) > 0)
+        return 0;
+    return ret;
+}
+
 static int amf_parse_object(AVFormatContext *s, AVStream *astream, AVStream *vstream, const char *key, int64_t max_pos, int depth) {
     AVCodecContext *acodec, *vcodec;
-    ByteIOContext *ioc;
+    AVIOContext *ioc;
     AMFDataType amf_type;
     char str_val[256];
     double num_val;
@@ -128,13 +207,13 @@ static int amf_parse_object(AVFormatContext *s, AVStream *astream, AVStream *vst
     num_val = 0;
     ioc = s->pb;
 
-    amf_type = get_byte(ioc);
+    amf_type = avio_r8(ioc);
 
     switch(amf_type) {
         case AMF_DATA_TYPE_NUMBER:
-            num_val = av_int2dbl(get_be64(ioc)); break;
+            num_val = av_int2dbl(avio_rb64(ioc)); break;
         case AMF_DATA_TYPE_BOOL:
-            num_val = get_byte(ioc); break;
+            num_val = avio_r8(ioc); break;
         case AMF_DATA_TYPE_STRING:
             if(amf_get_string(ioc, str_val, sizeof(str_val)) < 0)
                 return -1;
@@ -142,12 +221,16 @@ static int amf_parse_object(AVFormatContext *s, AVStream *astream, AVStream *vst
         case AMF_DATA_TYPE_OBJECT: {
             unsigned int keylen;
 
-            while(url_ftell(ioc) < max_pos - 2 && (keylen = get_be16(ioc))) {
-                url_fskip(ioc, keylen); //skip key string
+            if (key && !strcmp(KEYFRAMES_TAG, key) && depth == 1)
+                if (parse_keyframes_index(s, ioc, vstream, max_pos) < 0)
+                    return -1;
+
+            while(avio_tell(ioc) < max_pos - 2 && (keylen = avio_rb16(ioc))) {
+                avio_skip(ioc, keylen); //skip key string
                 if(amf_parse_object(s, NULL, NULL, NULL, max_pos, depth + 1) < 0)
                     return -1; //if we couldn't skip, bomb out.
             }
-            if(get_byte(ioc) != AMF_END_OF_OBJECT)
+            if(avio_r8(ioc) != AMF_END_OF_OBJECT)
                 return -1;
         }
             break;
@@ -156,27 +239,27 @@ static int amf_parse_object(AVFormatContext *s, AVStream *astream, AVStream *vst
         case AMF_DATA_TYPE_UNSUPPORTED:
             break; //these take up no additional space
         case AMF_DATA_TYPE_MIXEDARRAY:
-            url_fskip(ioc, 4); //skip 32-bit max array index
-            while(url_ftell(ioc) < max_pos - 2 && amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
+            avio_skip(ioc, 4); //skip 32-bit max array index
+            while(avio_tell(ioc) < max_pos - 2 && amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
                 //this is the only case in which we would want a nested parse to not skip over the object
                 if(amf_parse_object(s, astream, vstream, str_val, max_pos, depth + 1) < 0)
                     return -1;
             }
-            if(get_byte(ioc) != AMF_END_OF_OBJECT)
+            if(avio_r8(ioc) != AMF_END_OF_OBJECT)
                 return -1;
             break;
         case AMF_DATA_TYPE_ARRAY: {
             unsigned int arraylen, i;
 
-            arraylen = get_be32(ioc);
-            for(i = 0; i < arraylen && url_ftell(ioc) < max_pos - 1; i++) {
+            arraylen = avio_rb32(ioc);
+            for(i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++) {
                 if(amf_parse_object(s, NULL, NULL, NULL, max_pos, depth + 1) < 0)
                     return -1; //if we couldn't skip, bomb out.
             }
         }
             break;
         case AMF_DATA_TYPE_DATE:
-            url_fskip(ioc, 8 + 2); //timestamp (double) and UTC offset (int16)
+            avio_skip(ioc, 8 + 2); //timestamp (double) and UTC offset (int16)
             break;
         default: //unsupported type, we couldn't skip
             return -1;
@@ -207,7 +290,7 @@ static int amf_parse_object(AVFormatContext *s, AVStream *astream, AVStream *vst
 static int flv_read_metabody(AVFormatContext *s, int64_t next_pos) {
     AMFDataType type;
     AVStream *stream, *astream, *vstream;
-    ByteIOContext *ioc;
+    AVIOContext *ioc;
     int i;
     char buffer[11]; //only needs to hold the string "onMetaData". Anything longer is something we don't want.
 
@@ -216,7 +299,7 @@ static int flv_read_metabody(AVFormatContext *s, int64_t next_pos) {
     ioc = s->pb;
 
     //first object needs to be "onMetaData" string
-    type = get_byte(ioc);
+    type = avio_r8(ioc);
     if(type != AMF_DATA_TYPE_STRING || amf_get_string(ioc, buffer, sizeof(buffer)) < 0 || strcmp(buffer, "onMetaData"))
         return -1;
 
@@ -248,8 +331,8 @@ static int flv_read_header(AVFormatContext *s,
 {
     int offset, flags;
 
-    url_fskip(s->pb, 4);
-    flags = get_byte(s->pb);
+    avio_skip(s->pb, 4);
+    flags = avio_r8(s->pb);
     /* old flvtool cleared this field */
     /* FIXME: better fix needed */
     if (!flags) {
@@ -270,9 +353,9 @@ static int flv_read_header(AVFormatContext *s,
             return AVERROR(ENOMEM);
     }
 
-    offset = get_be32(s->pb);
-    url_fseek(s->pb, offset, SEEK_SET);
-    url_fskip(s->pb, 4);
+    offset = avio_rb32(s->pb);
+    avio_seek(s->pb, offset, SEEK_SET);
+    avio_skip(s->pb, 4);
 
     s->start_time = 0;
 
@@ -286,7 +369,7 @@ static int flv_get_extradata(AVFormatContext *s, AVStream *st, int size)
     if (!st->codec->extradata)
         return AVERROR(ENOMEM);
     st->codec->extradata_size = size;
-    get_buffer(s->pb, st->codec->extradata, st->codec->extradata_size);
+    avio_read(s->pb, st->codec->extradata, st->codec->extradata_size);
     return 0;
 }
 
@@ -298,30 +381,30 @@ static int flv_read_packet(AVFormatContext *s, AVPacket *pkt)
     int64_t dts, pts = AV_NOPTS_VALUE;
     AVStream *st = NULL;
 
- for(;;url_fskip(s->pb, 4)){ /* pkt size is repeated at end. skip it */
-    pos = url_ftell(s->pb);
-    type = get_byte(s->pb);
-    size = get_be24(s->pb);
-    dts = get_be24(s->pb);
-    dts |= get_byte(s->pb) << 24;
+ for(;;avio_skip(s->pb, 4)){ /* pkt size is repeated at end. skip it */
+    pos = avio_tell(s->pb);
+    type = avio_r8(s->pb);
+    size = avio_rb24(s->pb);
+    dts = avio_rb24(s->pb);
+    dts |= avio_r8(s->pb) << 24;
 //    av_log(s, AV_LOG_DEBUG, "type:%d, size:%d, dts:%d\n", type, size, dts);
-    if (url_feof(s->pb))
+    if (s->pb->eof_reached)
         return AVERROR_EOF;
-    url_fskip(s->pb, 3); /* stream id, always 0 */
+    avio_skip(s->pb, 3); /* stream id, always 0 */
     flags = 0;
 
     if(size == 0)
         continue;
 
-    next= size + url_ftell(s->pb);
+    next= size + avio_tell(s->pb);
 
     if (type == FLV_TAG_TYPE_AUDIO) {
         is_audio=1;
-        flags = get_byte(s->pb);
+        flags = avio_r8(s->pb);
         size--;
     } else if (type == FLV_TAG_TYPE_VIDEO) {
         is_audio=0;
-        flags = get_byte(s->pb);
+        flags = avio_r8(s->pb);
         size--;
         if ((flags & 0xf0) == 0x50) /* video info / command frame */
             goto skip;
@@ -331,7 +414,7 @@ static int flv_read_packet(AVFormatContext *s, AVPacket *pkt)
         else /* skip packet */
             av_log(s, AV_LOG_DEBUG, "skipping flv packet: type %d, size %d, flags %d\n", type, size, flags);
     skip:
-        url_fseek(s->pb, next, SEEK_SET);
+        avio_seek(s->pb, next, SEEK_SET);
         continue;
     }
 
@@ -355,7 +438,7 @@ static int flv_read_packet(AVFormatContext *s, AVPacket *pkt)
        ||(st->discard >= AVDISCARD_BIDIR  &&  ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_DISP_INTER && !is_audio))
        || st->discard >= AVDISCARD_ALL
        ){
-        url_fseek(s->pb, next, SEEK_SET);
+        avio_seek(s->pb, next, SEEK_SET);
         continue;
     }
     if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY)
@@ -364,19 +447,19 @@ static int flv_read_packet(AVFormatContext *s, AVPacket *pkt)
  }
 
     // if not streamed and no duration from metadata then seek to end to find the duration from the timestamps
-    if(!url_is_streamed(s->pb) && (!s->duration || s->duration==AV_NOPTS_VALUE)){
+    if(s->pb->seekable && (!s->duration || s->duration==AV_NOPTS_VALUE)){
         int size;
-        const int64_t pos= url_ftell(s->pb);
-        const int64_t fsize= url_fsize(s->pb);
-        url_fseek(s->pb, fsize-4, SEEK_SET);
-        size= get_be32(s->pb);
-        url_fseek(s->pb, fsize-3-size, SEEK_SET);
-        if(size == get_be24(s->pb) + 11){
-            uint32_t ts = get_be24(s->pb);
-            ts |= get_byte(s->pb) << 24;
+        const int64_t pos= avio_tell(s->pb);
+        const int64_t fsize= avio_size(s->pb);
+        avio_seek(s->pb, fsize-4, SEEK_SET);
+        size= avio_rb32(s->pb);
+        avio_seek(s->pb, fsize-3-size, SEEK_SET);
+        if(size == avio_rb24(s->pb) + 11){
+            uint32_t ts = avio_rb24(s->pb);
+            ts |= avio_r8(s->pb) << 24;
             s->duration = ts * (int64_t)AV_TIME_BASE / 1000;
         }
-        url_fseek(s->pb, pos, SEEK_SET);
+        avio_seek(s->pb, pos, SEEK_SET);
     }
 
     if(is_audio){
@@ -394,10 +477,10 @@ static int flv_read_packet(AVFormatContext *s, AVPacket *pkt)
 
     if (st->codec->codec_id == CODEC_ID_AAC ||
         st->codec->codec_id == CODEC_ID_H264) {
-        int type = get_byte(s->pb);
+        int type = avio_r8(s->pb);
         size--;
         if (st->codec->codec_id == CODEC_ID_H264) {
-            int32_t cts = (get_be24(s->pb)+0xff800000)^0xff800000; // sign extension
+            int32_t cts = (avio_rb24(s->pb)+0xff800000)^0xff800000; // sign extension
             pts = dts + cts;
             if (cts < 0) { // dts are wrong
                 flv->wrong_dts = 1;
@@ -414,8 +497,11 @@ static int flv_read_packet(AVFormatContext *s, AVPacket *pkt)
                 ff_mpeg4audio_get_config(&cfg, st->codec->extradata,
                                          st->codec->extradata_size);
                 st->codec->channels = cfg.channels;
-                st->codec->sample_rate = cfg.sample_rate;
-                dprintf(s, "mp4a config channels %d sample rate %d\n",
+                if (cfg.ext_sample_rate)
+                    st->codec->sample_rate = cfg.ext_sample_rate;
+                else
+                    st->codec->sample_rate = cfg.sample_rate;
+                av_dlog(s, "mp4a config channels %d sample rate %d\n",
                         st->codec->channels, st->codec->sample_rate);
             }
 
@@ -445,14 +531,14 @@ static int flv_read_packet(AVFormatContext *s, AVPacket *pkt)
         pkt->flags |= AV_PKT_FLAG_KEY;
 
 leave:
-    url_fskip(s->pb, 4);
+    avio_skip(s->pb, 4);
     return ret;
 }
 
 static int flv_read_seek(AVFormatContext *s, int stream_index,
     int64_t ts, int flags)
 {
-    return av_url_read_fseek(s->pb, stream_index, ts, flags);
+    return avio_seek_time(s->pb, stream_index, ts, flags);
 }
 
 #if 0 /* don't know enough to implement this */
@@ -463,7 +549,7 @@ static int flv_read_seek2(AVFormatContext *s, int stream_index,
 
     if (ts - min_ts > (uint64_t)(max_ts - ts)) flags |= AVSEEK_FLAG_BACKWARD;
 
-    if (url_is_streamed(s->pb)) {
+    if (!s->pb->seekable) {
         if (stream_index < 0) {
             stream_index = av_find_default_stream_index(s);
             if (stream_index < 0)
@@ -473,7 +559,7 @@ static int flv_read_seek2(AVFormatContext *s, int stream_index,
             ts = av_rescale_rnd(ts, 1000, AV_TIME_BASE,
                 flags & AVSEEK_FLAG_BACKWARD ? AV_ROUND_DOWN : AV_ROUND_UP);
         }
-        ret = av_url_read_fseek(s->pb, stream_index, ts, flags);
+        ret = avio_seek_time(s->pb, stream_index, ts, flags);
     }
 
     if (ret == AVERROR(ENOSYS))
@@ -482,7 +568,7 @@ static int flv_read_seek2(AVFormatContext *s, int stream_index,
 }
 #endif
 
-AVInputFormat flv_demuxer = {
+AVInputFormat ff_flv_demuxer = {
     "flv",
     NULL_IF_CONFIG_SMALL("FLV format"),
     sizeof(FLVContext),
diff --git a/libavformat/flvenc.c b/libavformat/flvenc.c
index c351117..b8ae113 100644
--- a/libavformat/flvenc.c
+++ b/libavformat/flvenc.c
@@ -1,27 +1,28 @@
 /*
  * FLV muxer
- * Copyright (c) 2003 The FFmpeg Project
+ * Copyright (c) 2003 The Libav Project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #include "avformat.h"
 #include "flv.h"
-#include "riff.h"
+#include "internal.h"
 #include "avc.h"
+#include "metadata.h"
 
 #undef NDEBUG
 #include <assert.h>
@@ -54,6 +55,7 @@ typedef struct FLVContext {
     int64_t filesize_offset;
     int64_t duration;
     int delay; ///< first dts delay for AVC
+    int64_t last_video_ts;
 } FLVContext;
 
 static int get_audio_flags(AVCodecContext *enc){
@@ -137,32 +139,45 @@ static int get_audio_flags(AVCodecContext *enc){
     return flags;
 }
 
-static void put_amf_string(ByteIOContext *pb, const char *str)
+static void put_amf_string(AVIOContext *pb, const char *str)
 {
     size_t len = strlen(str);
-    put_be16(pb, len);
-    put_buffer(pb, str, len);
+    avio_wb16(pb, len);
+    avio_write(pb, str, len);
 }
 
-static void put_amf_double(ByteIOContext *pb, double d)
+static void put_avc_eos_tag(AVIOContext *pb, unsigned ts) {
+    avio_w8(pb, FLV_TAG_TYPE_VIDEO);
+    avio_wb24(pb, 5);  /* Tag Data Size */
+    avio_wb24(pb, ts);  /* lower 24 bits of timestamp in ms*/
+    avio_w8(pb, (ts >> 24) & 0x7F);  /* MSB of ts in ms*/
+    avio_wb24(pb, 0);  /* StreamId = 0 */
+    avio_w8(pb, 23);  /* ub[4] FrameType = 1, ub[4] CodecId = 7 */
+    avio_w8(pb, 2);  /* AVC end of sequence */
+    avio_wb24(pb, 0);  /* Always 0 for AVC EOS. */
+    avio_wb32(pb, 16);  /* Size of FLV tag */
+}
+
+static void put_amf_double(AVIOContext *pb, double d)
 {
-    put_byte(pb, AMF_DATA_TYPE_NUMBER);
-    put_be64(pb, av_dbl2int(d));
+    avio_w8(pb, AMF_DATA_TYPE_NUMBER);
+    avio_wb64(pb, av_dbl2int(d));
 }
 
-static void put_amf_bool(ByteIOContext *pb, int b) {
-    put_byte(pb, AMF_DATA_TYPE_BOOL);
-    put_byte(pb, !!b);
+static void put_amf_bool(AVIOContext *pb, int b) {
+    avio_w8(pb, AMF_DATA_TYPE_BOOL);
+    avio_w8(pb, !!b);
 }
 
 static int flv_write_header(AVFormatContext *s)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     FLVContext *flv = s->priv_data;
     AVCodecContext *audio_enc = NULL, *video_enc = NULL;
     int i;
     double framerate = 0.0;
     int metadata_size_pos, data_size;
+    AVMetadataTag *tag = NULL;
 
     for(i=0; i<s->nb_streams; i++){
         AVCodecContext *enc = s->streams[i]->codec;
@@ -184,43 +199,45 @@ static int flv_write_header(AVFormatContext *s)
         }
         av_set_pts_info(s->streams[i], 32, 1, 1000); /* 32 bit pts in ms */
     }
-    put_tag(pb,"FLV");
-    put_byte(pb,1);
-    put_byte(pb,   FLV_HEADER_FLAG_HASAUDIO * !!audio_enc
+    avio_write(pb, "FLV", 3);
+    avio_w8(pb,1);
+    avio_w8(pb,   FLV_HEADER_FLAG_HASAUDIO * !!audio_enc
                  + FLV_HEADER_FLAG_HASVIDEO * !!video_enc);
-    put_be32(pb,9);
-    put_be32(pb,0);
+    avio_wb32(pb,9);
+    avio_wb32(pb,0);
 
     for(i=0; i<s->nb_streams; i++){
         if(s->streams[i]->codec->codec_tag == 5){
-            put_byte(pb,8); // message type
-            put_be24(pb,0); // include flags
-            put_be24(pb,0); // time stamp
-            put_be32(pb,0); // reserved
-            put_be32(pb,11); // size
+            avio_w8(pb,8); // message type
+            avio_wb24(pb,0); // include flags
+            avio_wb24(pb,0); // time stamp
+            avio_wb32(pb,0); // reserved
+            avio_wb32(pb,11); // size
             flv->reserved=5;
         }
     }
 
+    flv->last_video_ts = -1;
+
     /* write meta_tag */
-    put_byte(pb, 18);         // tag type META
-    metadata_size_pos= url_ftell(pb);
-    put_be24(pb, 0);          // size of data part (sum of all parts below)
-    put_be24(pb, 0);          // time stamp
-    put_be32(pb, 0);          // reserved
+    avio_w8(pb, 18);         // tag type META
+    metadata_size_pos= avio_tell(pb);
+    avio_wb24(pb, 0);          // size of data part (sum of all parts below)
+    avio_wb24(pb, 0);          // time stamp
+    avio_wb32(pb, 0);          // reserved
 
     /* now data of data_size size */
 
     /* first event name as a string */
-    put_byte(pb, AMF_DATA_TYPE_STRING);
+    avio_w8(pb, AMF_DATA_TYPE_STRING);
     put_amf_string(pb, "onMetaData"); // 12 bytes
 
     /* mixed array (hash) with size and string/type/data tuples */
-    put_byte(pb, AMF_DATA_TYPE_MIXEDARRAY);
-    put_be32(pb, 5*!!video_enc + 5*!!audio_enc + 2); // +2 for duration and file size
+    avio_w8(pb, AMF_DATA_TYPE_MIXEDARRAY);
+    avio_wb32(pb, 5*!!video_enc + 5*!!audio_enc + 2); // +2 for duration and file size
 
     put_amf_string(pb, "duration");
-    flv->duration_offset= url_ftell(pb);
+    flv->duration_offset= avio_tell(pb);
     put_amf_double(pb, s->duration / AV_TIME_BASE); // fill in the guessed duration, it'll be corrected later if incorrect
 
     if(video_enc){
@@ -257,46 +274,52 @@ static int flv_write_header(AVFormatContext *s)
         put_amf_double(pb, audio_enc->codec_tag);
     }
 
+    while ((tag = av_metadata_get(s->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX))) {
+        put_amf_string(pb, tag->key);
+        avio_w8(pb, AMF_DATA_TYPE_STRING);
+        put_amf_string(pb, tag->value);
+    }
+
     put_amf_string(pb, "filesize");
-    flv->filesize_offset= url_ftell(pb);
+    flv->filesize_offset= avio_tell(pb);
     put_amf_double(pb, 0); // delayed write
 
     put_amf_string(pb, "");
-    put_byte(pb, AMF_END_OF_OBJECT);
+    avio_w8(pb, AMF_END_OF_OBJECT);
 
     /* write total size of tag */
-    data_size= url_ftell(pb) - metadata_size_pos - 10;
-    url_fseek(pb, metadata_size_pos, SEEK_SET);
-    put_be24(pb, data_size);
-    url_fseek(pb, data_size + 10 - 3, SEEK_CUR);
-    put_be32(pb, data_size + 11);
+    data_size= avio_tell(pb) - metadata_size_pos - 10;
+    avio_seek(pb, metadata_size_pos, SEEK_SET);
+    avio_wb24(pb, data_size);
+    avio_skip(pb, data_size + 10 - 3);
+    avio_wb32(pb, data_size + 11);
 
     for (i = 0; i < s->nb_streams; i++) {
         AVCodecContext *enc = s->streams[i]->codec;
         if (enc->codec_id == CODEC_ID_AAC || enc->codec_id == CODEC_ID_H264) {
             int64_t pos;
-            put_byte(pb, enc->codec_type == AVMEDIA_TYPE_VIDEO ?
+            avio_w8(pb, enc->codec_type == AVMEDIA_TYPE_VIDEO ?
                      FLV_TAG_TYPE_VIDEO : FLV_TAG_TYPE_AUDIO);
-            put_be24(pb, 0); // size patched later
-            put_be24(pb, 0); // ts
-            put_byte(pb, 0); // ts ext
-            put_be24(pb, 0); // streamid
-            pos = url_ftell(pb);
+            avio_wb24(pb, 0); // size patched later
+            avio_wb24(pb, 0); // ts
+            avio_w8(pb, 0); // ts ext
+            avio_wb24(pb, 0); // streamid
+            pos = avio_tell(pb);
             if (enc->codec_id == CODEC_ID_AAC) {
-                put_byte(pb, get_audio_flags(enc));
-                put_byte(pb, 0); // AAC sequence header
-                put_buffer(pb, enc->extradata, enc->extradata_size);
+                avio_w8(pb, get_audio_flags(enc));
+                avio_w8(pb, 0); // AAC sequence header
+                avio_write(pb, enc->extradata, enc->extradata_size);
             } else {
-                put_byte(pb, enc->codec_tag | FLV_FRAME_KEY); // flags
-                put_byte(pb, 0); // AVC sequence header
-                put_be24(pb, 0); // composition time
+                avio_w8(pb, enc->codec_tag | FLV_FRAME_KEY); // flags
+                avio_w8(pb, 0); // AVC sequence header
+                avio_wb24(pb, 0); // composition time
                 ff_isom_write_avcc(pb, enc->extradata, enc->extradata_size);
             }
-            data_size = url_ftell(pb) - pos;
-            url_fseek(pb, -data_size - 10, SEEK_CUR);
-            put_be24(pb, data_size);
-            url_fseek(pb, data_size + 10 - 3, SEEK_CUR);
-            put_be32(pb, data_size + 11); // previous tag size
+            data_size = avio_tell(pb) - pos;
+            avio_seek(pb, -data_size - 10, SEEK_CUR);
+            avio_wb24(pb, data_size);
+            avio_skip(pb, data_size + 10 - 3);
+            avio_wb32(pb, data_size + 11); // previous tag size
         }
     }
 
@@ -307,24 +330,34 @@ static int flv_write_trailer(AVFormatContext *s)
 {
     int64_t file_size;
 
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     FLVContext *flv = s->priv_data;
+    int i;
 
-    file_size = url_ftell(pb);
+    /* Add EOS tag */
+    for (i = 0; i < s->nb_streams; i++) {
+        AVCodecContext *enc = s->streams[i]->codec;
+        if (enc->codec_type == AVMEDIA_TYPE_VIDEO &&
+                enc->codec_id == CODEC_ID_H264) {
+            put_avc_eos_tag(pb, flv->last_video_ts);
+        }
+    }
+
+    file_size = avio_tell(pb);
 
     /* update informations */
-    url_fseek(pb, flv->duration_offset, SEEK_SET);
+    avio_seek(pb, flv->duration_offset, SEEK_SET);
     put_amf_double(pb, flv->duration / (double)1000);
-    url_fseek(pb, flv->filesize_offset, SEEK_SET);
+    avio_seek(pb, flv->filesize_offset, SEEK_SET);
     put_amf_double(pb, file_size);
 
-    url_fseek(pb, file_size, SEEK_SET);
+    avio_seek(pb, file_size, SEEK_SET);
     return 0;
 }
 
 static int flv_write_packet(AVFormatContext *s, AVPacket *pkt)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVCodecContext *enc = s->streams[pkt->stream_index]->codec;
     FLVContext *flv = s->priv_data;
     unsigned ts;
@@ -343,7 +376,7 @@ static int flv_write_packet(AVFormatContext *s, AVPacket *pkt)
         flags_size= 1;
 
     if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
-        put_byte(pb, FLV_TAG_TYPE_VIDEO);
+        avio_w8(pb, FLV_TAG_TYPE_VIDEO);
 
         flags = enc->codec_tag;
         if(flags == 0) {
@@ -358,7 +391,7 @@ static int flv_write_packet(AVFormatContext *s, AVPacket *pkt)
 
         assert(size);
 
-        put_byte(pb, FLV_TAG_TYPE_AUDIO);
+        avio_w8(pb, FLV_TAG_TYPE_AUDIO);
     }
 
     if (enc->codec_id == CODEC_ID_H264) {
@@ -372,35 +405,39 @@ static int flv_write_packet(AVFormatContext *s, AVPacket *pkt)
     }
 
     ts = pkt->dts + flv->delay; // add delay to force positive dts
-    put_be24(pb,size + flags_size);
-    put_be24(pb,ts);
-    put_byte(pb,(ts >> 24) & 0x7F); // timestamps are 32bits _signed_
-    put_be24(pb,flv->reserved);
-    put_byte(pb,flags);
+    if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
+        if (flv->last_video_ts < ts)
+            flv->last_video_ts = ts;
+    }
+    avio_wb24(pb,size + flags_size);
+    avio_wb24(pb,ts);
+    avio_w8(pb,(ts >> 24) & 0x7F); // timestamps are 32bits _signed_
+    avio_wb24(pb,flv->reserved);
+    avio_w8(pb,flags);
     if (enc->codec_id == CODEC_ID_VP6)
-        put_byte(pb,0);
+        avio_w8(pb,0);
     if (enc->codec_id == CODEC_ID_VP6F)
-        put_byte(pb, enc->extradata_size ? enc->extradata[0] : 0);
+        avio_w8(pb, enc->extradata_size ? enc->extradata[0] : 0);
     else if (enc->codec_id == CODEC_ID_AAC)
-        put_byte(pb,1); // AAC raw
+        avio_w8(pb,1); // AAC raw
     else if (enc->codec_id == CODEC_ID_H264) {
-        put_byte(pb,1); // AVC NALU
-        put_be24(pb,pkt->pts - pkt->dts);
+        avio_w8(pb,1); // AVC NALU
+        avio_wb24(pb,pkt->pts - pkt->dts);
     }
 
-    put_buffer(pb, data ? data : pkt->data, size);
+    avio_write(pb, data ? data : pkt->data, size);
 
-    put_be32(pb,size+flags_size+11); // previous tag size
+    avio_wb32(pb,size+flags_size+11); // previous tag size
     flv->duration = FFMAX(flv->duration, pkt->pts + flv->delay + pkt->duration);
 
-    put_flush_packet(pb);
+    avio_flush(pb);
 
     av_free(data);
 
     return 0;
 }
 
-AVOutputFormat flv_muxer = {
+AVOutputFormat ff_flv_muxer = {
     "flv",
     NULL_IF_CONFIG_SMALL("FLV format"),
     "video/x-flv",
diff --git a/libavformat/framecrcenc.c b/libavformat/framecrcenc.c
index f59a0c8..2bd3f54 100644
--- a/libavformat/framecrcenc.c
+++ b/libavformat/framecrcenc.c
@@ -2,20 +2,20 @@
  * frame CRC encoder (for codec/format testing)
  * Copyright (c) 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -28,12 +28,12 @@ static int framecrc_write_packet(struct AVFormatContext *s, AVPacket *pkt)
     char buf[256];
 
     snprintf(buf, sizeof(buf), "%d, %"PRId64", %d, 0x%08x\n", pkt->stream_index, pkt->dts, pkt->size, crc);
-    put_buffer(s->pb, buf, strlen(buf));
-    put_flush_packet(s->pb);
+    avio_write(s->pb, buf, strlen(buf));
+    avio_flush(s->pb);
     return 0;
 }
 
-AVOutputFormat framecrc_muxer = {
+AVOutputFormat ff_framecrc_muxer = {
     "framecrc",
     NULL_IF_CONFIG_SMALL("framecrc testing format"),
     NULL,
diff --git a/libavformat/gif.c b/libavformat/gif.c
index 4741915..dfd2ec1 100644
--- a/libavformat/gif.c
+++ b/libavformat/gif.c
@@ -2,20 +2,20 @@
  * Animated GIF muxer
  * Copyright (c) 2000 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -107,33 +107,33 @@ static const rgb_triplet gif_clut[216] = {
 };
 
 /* GIF header */
-static int gif_image_write_header(ByteIOContext *pb,
+static int gif_image_write_header(AVIOContext *pb,
                                   int width, int height, int loop_count,
                                   uint32_t *palette)
 {
     int i;
     unsigned int v;
 
-    put_tag(pb, "GIF");
-    put_tag(pb, "89a");
-    put_le16(pb, width);
-    put_le16(pb, height);
+    avio_write(pb, "GIF", 3);
+    avio_write(pb, "89a", 3);
+    avio_wl16(pb, width);
+    avio_wl16(pb, height);
 
-    put_byte(pb, 0xf7); /* flags: global clut, 256 entries */
-    put_byte(pb, 0x1f); /* background color index */
-    put_byte(pb, 0); /* aspect ratio */
+    avio_w8(pb, 0xf7); /* flags: global clut, 256 entries */
+    avio_w8(pb, 0x1f); /* background color index */
+    avio_w8(pb, 0);    /* aspect ratio */
 
     /* the global palette */
     if (!palette) {
-        put_buffer(pb, (const unsigned char *)gif_clut, 216*3);
+        avio_write(pb, (const unsigned char *)gif_clut, 216*3);
         for(i=0;i<((256-216)*3);i++)
-            put_byte(pb, 0);
+            avio_w8(pb, 0);
     } else {
         for(i=0;i<256;i++) {
             v = palette[i];
-            put_byte(pb, (v >> 16) & 0xff);
-            put_byte(pb, (v >> 8) & 0xff);
-            put_byte(pb, (v) & 0xff);
+            avio_w8(pb, (v >> 16) & 0xff);
+            avio_w8(pb, (v >> 8) & 0xff);
+            avio_w8(pb, (v) & 0xff);
         }
     }
 
@@ -159,14 +159,14 @@ static int gif_image_write_header(ByteIOContext *pb,
     /* application extension header */
 #ifdef GIF_ADD_APP_HEADER
     if (loop_count >= 0 && loop_count <= 65535) {
-    put_byte(pb, 0x21);
-    put_byte(pb, 0xff);
-    put_byte(pb, 0x0b);
-        put_tag(pb, "NETSCAPE2.0");  // bytes 4 to 14
-        put_byte(pb, 0x03); // byte 15
-        put_byte(pb, 0x01); // byte 16
-        put_le16(pb, (uint16_t)loop_count);
-        put_byte(pb, 0x00); // byte 19
+    avio_w8(pb, 0x21);
+    avio_w8(pb, 0xff);
+    avio_w8(pb, 0x0b);
+        avio_write(pb, "NETSCAPE2.0", sizeof("NETSCAPE2.0") - 1);  // bytes 4 to 14
+        avio_w8(pb, 0x03); // byte 15
+        avio_w8(pb, 0x01); // byte 16
+        avio_wl16(pb, (uint16_t)loop_count);
+        avio_w8(pb, 0x00); // byte 19
     }
 #endif
     return 0;
@@ -179,7 +179,7 @@ static inline unsigned char gif_clut_index(uint8_t r, uint8_t g, uint8_t b)
 }
 
 
-static int gif_image_write_image(ByteIOContext *pb,
+static int gif_image_write_image(AVIOContext *pb,
                                  int x1, int y1, int width, int height,
                                  const uint8_t *buf, int linesize, int pix_fmt)
 {
@@ -189,15 +189,15 @@ static int gif_image_write_image(ByteIOContext *pb,
     const uint8_t *ptr;
     /* image block */
 
-    put_byte(pb, 0x2c);
-    put_le16(pb, x1);
-    put_le16(pb, y1);
-    put_le16(pb, width);
-    put_le16(pb, height);
-    put_byte(pb, 0x00); /* flags */
+    avio_w8(pb, 0x2c);
+    avio_wl16(pb, x1);
+    avio_wl16(pb, y1);
+    avio_wl16(pb, width);
+    avio_wl16(pb, height);
+    avio_w8(pb, 0x00); /* flags */
     /* no local clut */
 
-    put_byte(pb, 0x08);
+    avio_w8(pb, 0x08);
 
     left= width * height;
 
@@ -233,13 +233,13 @@ static int gif_image_write_image(ByteIOContext *pb,
             flush_put_bits(&p);
         }
         if(put_bits_ptr(&p) - p.buf > 0) {
-            put_byte(pb, put_bits_ptr(&p) - p.buf); /* byte count of the packet */
-            put_buffer(pb, p.buf, put_bits_ptr(&p) - p.buf); /* the actual buffer */
+            avio_w8(pb, put_bits_ptr(&p) - p.buf); /* byte count of the packet */
+            avio_write(pb, p.buf, put_bits_ptr(&p) - p.buf); /* the actual buffer */
             p.buf_ptr = p.buf; /* dequeue the bytes off the bitstream */
         }
         left-=GIF_CHUNKS;
     }
-    put_byte(pb, 0x00); /* end of image block */
+    avio_w8(pb, 0x00); /* end of image block */
 
     return 0;
 }
@@ -252,7 +252,7 @@ typedef struct {
 static int gif_write_header(AVFormatContext *s)
 {
     GIFContext *gif = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVCodecContext *enc, *video_enc;
     int i, width, height, loop_count /*, rate*/;
 
@@ -287,23 +287,23 @@ static int gif_write_header(AVFormatContext *s)
 
     gif_image_write_header(pb, width, height, loop_count, NULL);
 
-    put_flush_packet(s->pb);
+    avio_flush(s->pb);
     return 0;
 }
 
 static int gif_write_video(AVFormatContext *s,
                            AVCodecContext *enc, const uint8_t *buf, int size)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     GIFContext *gif = s->priv_data;
     int jiffies;
     int64_t delay;
 
     /* graphic control extension block */
-    put_byte(pb, 0x21);
-    put_byte(pb, 0xf9);
-    put_byte(pb, 0x04); /* block size */
-    put_byte(pb, 0x04); /* flags */
+    avio_w8(pb, 0x21);
+    avio_w8(pb, 0xf9);
+    avio_w8(pb, 0x04); /* block size */
+    avio_w8(pb, 0x04); /* flags */
 
     /* 1 jiffy is 1/70 s */
     /* the delay_time field indicates the number of jiffies - 1 */
@@ -314,15 +314,15 @@ static int gif_write_video(AVFormatContext *s,
     /* XXX: don't even remember if I really use it for now */
     jiffies = (70*enc->time_base.num/enc->time_base.den) - 1;
 
-    put_le16(pb, jiffies);
+    avio_wl16(pb, jiffies);
 
-    put_byte(pb, 0x1f); /* transparent color index */
-    put_byte(pb, 0x00);
+    avio_w8(pb, 0x1f); /* transparent color index */
+    avio_w8(pb, 0x00);
 
     gif_image_write_image(pb, 0, 0, enc->width, enc->height,
                           buf, enc->width * 3, PIX_FMT_RGB24);
 
-    put_flush_packet(s->pb);
+    avio_flush(s->pb);
     return 0;
 }
 
@@ -337,14 +337,14 @@ static int gif_write_packet(AVFormatContext *s, AVPacket *pkt)
 
 static int gif_write_trailer(AVFormatContext *s)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
 
-    put_byte(pb, 0x3b);
-    put_flush_packet(s->pb);
+    avio_w8(pb, 0x3b);
+    avio_flush(s->pb);
     return 0;
 }
 
-AVOutputFormat gif_muxer = {
+AVOutputFormat ff_gif_muxer = {
     "gif",
     NULL_IF_CONFIG_SMALL("GIF Animation"),
     "image/gif",
diff --git a/libavformat/gopher.c b/libavformat/gopher.c
index f5bb4a3..cfc07e7 100644
--- a/libavformat/gopher.c
+++ b/libavformat/gopher.c
@@ -5,20 +5,20 @@
  *
  * based on libavformat/http.c, Copyright (c) 2000, 2001 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -26,15 +26,16 @@
 #include "avformat.h"
 #include "internal.h"
 #include "network.h"
+#include "url.h"
 
 typedef struct {
     URLContext *hd;
 } GopherContext;
 
-static int gopher_write(URLContext *h, uint8_t *buf, int size)
+static int gopher_write(URLContext *h, const uint8_t *buf, int size)
 {
     GopherContext *s = h->priv_data;
-    return url_write(s->hd, buf, size);
+    return ffurl_write(s->hd, buf, size);
 }
 
 static int gopher_connect(URLContext *h, const char *path)
@@ -68,7 +69,7 @@ static int gopher_close(URLContext *h)
 {
     GopherContext *s = h->priv_data;
     if (s->hd) {
-        url_close(s->hd);
+        ffurl_close(s->hd);
         s->hd = NULL;
     }
     av_freep(&h->priv_data);
@@ -90,7 +91,7 @@ static int gopher_open(URLContext *h, const char *uri, int flags)
     h->priv_data = s;
 
     /* needed in any case to build the host string */
-    ff_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
+    av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
                  path, sizeof(path), uri);
 
     if (port < 0)
@@ -99,7 +100,7 @@ static int gopher_open(URLContext *h, const char *uri, int flags)
     ff_url_join(buf, sizeof(buf), "tcp", NULL, hostname, port, NULL);
 
     s->hd = NULL;
-    err = url_open(&s->hd, buf, URL_RDWR);
+    err = ffurl_open(&s->hd, buf, AVIO_RDWR);
     if (err < 0)
         goto fail;
 
@@ -114,16 +115,15 @@ static int gopher_open(URLContext *h, const char *uri, int flags)
 static int gopher_read(URLContext *h, uint8_t *buf, int size)
 {
     GopherContext *s = h->priv_data;
-    int len = url_read(s->hd, buf, size);
+    int len = ffurl_read(s->hd, buf, size);
     return len;
 }
 
 
-URLProtocol gopher_protocol = {
-    "gopher",
-    gopher_open,
-    gopher_read,
-    gopher_write,
-    NULL, /*seek*/
-    gopher_close,
+URLProtocol ff_gopher_protocol = {
+    .name      = "gopher",
+    .url_open  = gopher_open,
+    .url_read  = gopher_read,
+    .url_write = gopher_write,
+    .url_close = gopher_close,
 };
diff --git a/libavformat/gxf.c b/libavformat/gxf.c
index ea8a2ff..74d925f 100644
--- a/libavformat/gxf.c
+++ b/libavformat/gxf.c
@@ -2,25 +2,26 @@
  * GXF demuxer.
  * Copyright (c) 2006 Reimar Doeffinger
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "libavutil/common.h"
 #include "avformat.h"
+#include "internal.h"
 #include "gxf.h"
 
 struct gxf_stream_info {
@@ -32,26 +33,26 @@ struct gxf_stream_info {
 
 /**
  * \brief parses a packet header, extracting type and length
- * \param pb ByteIOContext to read header from
+ * \param pb AVIOContext to read header from
  * \param type detected packet type is stored here
  * \param length detected packet length, excluding header is stored here
  * \return 0 if header not found or contains invalid data, 1 otherwise
  */
-static int parse_packet_header(ByteIOContext *pb, GXFPktType *type, int *length) {
-    if (get_be32(pb))
+static int parse_packet_header(AVIOContext *pb, GXFPktType *type, int *length) {
+    if (avio_rb32(pb))
         return 0;
-    if (get_byte(pb) != 1)
+    if (avio_r8(pb) != 1)
         return 0;
-    *type = get_byte(pb);
-    *length = get_be32(pb);
+    *type = avio_r8(pb);
+    *length = avio_rb32(pb);
     if ((*length >> 24) || *length < 16)
         return 0;
     *length -= 16;
-    if (get_be32(pb))
+    if (avio_rb32(pb))
         return 0;
-    if (get_byte(pb) != 0xe1)
+    if (avio_r8(pb) != 0xe1)
         return 0;
-    if (get_byte(pb) != 0xe2)
+    if (avio_r8(pb) != 0xe2)
         return 0;
     return 1;
 }
@@ -71,16 +72,15 @@ static int gxf_probe(AVProbeData *p) {
 /**
  * \brief gets the stream index for the track with the specified id, creates new
  *        stream if not found
- * \param stream id of stream to find / add
+ * \param id     id of stream to find / add
  * \param format stream format identifier
  */
 static int get_sindex(AVFormatContext *s, int id, int format) {
     int i;
     AVStream *st = NULL;
-    for (i = 0; i < s->nb_streams; i++) {
-        if (s->streams[i]->id == id)
-            return i;
-    }
+    i = ff_find_stream_index(s, id);
+    if (i >= 0)
+        return i;
     st = av_new_stream(s, id);
     if (!st)
         return AVERROR(ENOMEM);
@@ -157,24 +157,24 @@ static int get_sindex(AVFormatContext *s, int id, int format) {
  * \param len length of tag section, will be adjusted to contain remaining bytes
  * \param si struct to store collected information into
  */
-static void gxf_material_tags(ByteIOContext *pb, int *len, struct gxf_stream_info *si) {
+static void gxf_material_tags(AVIOContext *pb, int *len, struct gxf_stream_info *si) {
     si->first_field = AV_NOPTS_VALUE;
     si->last_field = AV_NOPTS_VALUE;
     while (*len >= 2) {
-        GXFMatTag tag = get_byte(pb);
-        int tlen = get_byte(pb);
+        GXFMatTag tag = avio_r8(pb);
+        int tlen = avio_r8(pb);
         *len -= 2;
         if (tlen > *len)
             return;
         *len -= tlen;
         if (tlen == 4) {
-            uint32_t value = get_be32(pb);
+            uint32_t value = avio_rb32(pb);
             if (tag == MAT_FIRST_FIELD)
                 si->first_field = value;
             else if (tag == MAT_LAST_FIELD)
                 si->last_field = value;
         } else
-            url_fskip(pb, tlen);
+            avio_skip(pb, tlen);
     }
 }
 
@@ -191,7 +191,7 @@ static AVRational fps_tag2avr(int32_t fps) {
 
 /**
  * \brief convert UMF attributes flags to AVRational fps
- * \param fps fps value from flags
+ * \param flags UMF flags to convert
  * \return fps as AVRational, or 0 / 0 if unknown
  */
 static AVRational fps_umf2avr(uint32_t flags) {
@@ -206,24 +206,24 @@ static AVRational fps_umf2avr(uint32_t flags) {
  * \param len length of tag section, will be adjusted to contain remaining bytes
  * \param si struct to store collected information into
  */
-static void gxf_track_tags(ByteIOContext *pb, int *len, struct gxf_stream_info *si) {
+static void gxf_track_tags(AVIOContext *pb, int *len, struct gxf_stream_info *si) {
     si->frames_per_second = (AVRational){0, 0};
     si->fields_per_frame = 0;
     while (*len >= 2) {
-        GXFTrackTag tag = get_byte(pb);
-        int tlen = get_byte(pb);
+        GXFTrackTag tag = avio_r8(pb);
+        int tlen = avio_r8(pb);
         *len -= 2;
         if (tlen > *len)
             return;
         *len -= tlen;
         if (tlen == 4) {
-            uint32_t value = get_be32(pb);
+            uint32_t value = avio_rb32(pb);
             if (tag == TRACK_FPS)
                 si->frames_per_second = fps_tag2avr(value);
             else if (tag == TRACK_FPF && (value == 1 || value == 2))
                 si->fields_per_frame = value;
         } else
-            url_fskip(pb, tlen);
+            avio_skip(pb, tlen);
     }
 }
 
@@ -231,31 +231,35 @@ static void gxf_track_tags(ByteIOContext *pb, int *len, struct gxf_stream_info *
  * \brief read index from FLT packet into stream 0 av_index
  */
 static void gxf_read_index(AVFormatContext *s, int pkt_len) {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVStream *st = s->streams[0];
-    uint32_t fields_per_map = get_le32(pb);
-    uint32_t map_cnt = get_le32(pb);
+    uint32_t fields_per_map = avio_rl32(pb);
+    uint32_t map_cnt = avio_rl32(pb);
     int i;
     pkt_len -= 8;
+    if (s->flags & AVFMT_FLAG_IGNIDX) {
+        avio_skip(pb, pkt_len);
+        return;
+    }
     if (map_cnt > 1000) {
         av_log(s, AV_LOG_ERROR, "too many index entries %u (%x)\n", map_cnt, map_cnt);
         map_cnt = 1000;
     }
     if (pkt_len < 4 * map_cnt) {
         av_log(s, AV_LOG_ERROR, "invalid index length\n");
-        url_fskip(pb, pkt_len);
+        avio_skip(pb, pkt_len);
         return;
     }
     pkt_len -= 4 * map_cnt;
     av_add_index_entry(st, 0, 0, 0, 0, 0);
     for (i = 0; i < map_cnt; i++)
-        av_add_index_entry(st, (uint64_t)get_le32(pb) * 1024,
+        av_add_index_entry(st, (uint64_t)avio_rl32(pb) * 1024,
                            i * (uint64_t)fields_per_map + 1, 0, 0, 0);
-    url_fskip(pb, pkt_len);
+    avio_skip(pb, pkt_len);
 }
 
 static int gxf_header(AVFormatContext *s, AVFormatParameters *ap) {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     GXFPktType pkt_type;
     int map_len;
     int len;
@@ -267,21 +271,21 @@ static int gxf_header(AVFormatContext *s, AVFormatParameters *ap) {
         return 0;
     }
     map_len -= 2;
-    if (get_byte(pb) != 0x0e0 || get_byte(pb) != 0xff) {
+    if (avio_r8(pb) != 0x0e0 || avio_r8(pb) != 0xff) {
         av_log(s, AV_LOG_ERROR, "unknown version or invalid map preamble\n");
         return 0;
     }
     map_len -= 2;
-    len = get_be16(pb); // length of material data section
+    len = avio_rb16(pb); // length of material data section
     if (len > map_len) {
         av_log(s, AV_LOG_ERROR, "material data longer than map data\n");
         return 0;
     }
     map_len -= len;
     gxf_material_tags(pb, &len, &si);
-    url_fskip(pb, len);
+    avio_skip(pb, len);
     map_len -= 2;
-    len = get_be16(pb); // length of track description
+    len = avio_rb16(pb); // length of track description
     if (len > map_len) {
         av_log(s, AV_LOG_ERROR, "track description longer than map data\n");
         return 0;
@@ -292,12 +296,12 @@ static int gxf_header(AVFormatContext *s, AVFormatParameters *ap) {
         AVStream *st;
         int idx;
         len -= 4;
-        track_type = get_byte(pb);
-        track_id = get_byte(pb);
-        track_len = get_be16(pb);
+        track_type = avio_r8(pb);
+        track_id = avio_r8(pb);
+        track_len = avio_rb16(pb);
         len -= track_len;
         gxf_track_tags(pb, &track_len, &si);
-        url_fskip(pb, track_len);
+        avio_skip(pb, track_len);
         if (!(track_type & 0x80)) {
            av_log(s, AV_LOG_ERROR, "invalid track type %x\n", track_type);
            continue;
@@ -322,7 +326,7 @@ static int gxf_header(AVFormatContext *s, AVFormatParameters *ap) {
     if (len < 0)
         av_log(s, AV_LOG_ERROR, "invalid track description length specified\n");
     if (map_len)
-        url_fskip(pb, map_len);
+        avio_skip(pb, map_len);
     if (!parse_packet_header(pb, &pkt_type, &len)) {
         av_log(s, AV_LOG_ERROR, "sync lost in header\n");
         return -1;
@@ -338,9 +342,9 @@ static int gxf_header(AVFormatContext *s, AVFormatParameters *ap) {
         if (len >= 0x39) {
             AVRational fps;
             len -= 0x39;
-            url_fskip(pb, 5); // preamble
-            url_fskip(pb, 0x30); // payload description
-            fps = fps_umf2avr(get_le32(pb));
+            avio_skip(pb, 5); // preamble
+            avio_skip(pb, 0x30); // payload description
+            fps = fps_umf2avr(avio_rl32(pb));
             if (!main_timebase.num || !main_timebase.den) {
                 // this may not always be correct, but simply the best we can get
                 main_timebase.num = fps.den;
@@ -350,7 +354,7 @@ static int gxf_header(AVFormatContext *s, AVFormatParameters *ap) {
             av_log(s, AV_LOG_INFO, "UMF packet too short\n");
     } else
         av_log(s, AV_LOG_INFO, "UMF packet missing\n");
-    url_fskip(pb, len);
+    avio_skip(pb, len);
     // set a fallback value, 60000/1001 is specified for audio-only files
     // so use that regardless of why we do not know the video frame rate.
     if (!main_timebase.num || !main_timebase.den)
@@ -364,9 +368,9 @@ static int gxf_header(AVFormatContext *s, AVFormatParameters *ap) {
 
 #define READ_ONE() \
     { \
-        if (!max_interval-- || url_feof(pb)) \
+        if (!max_interval-- || pb->eof_reached) \
             goto out; \
-        tmp = tmp << 8 | get_byte(pb); \
+        tmp = tmp << 8 | avio_r8(pb); \
     }
 
 /**
@@ -383,46 +387,48 @@ static int64_t gxf_resync_media(AVFormatContext *s, uint64_t max_interval, int t
     int cur_track;
     int64_t cur_timestamp = AV_NOPTS_VALUE;
     int len;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     GXFPktType type;
-    tmp = get_be32(pb);
+    tmp = avio_rb32(pb);
 start:
     while (tmp)
         READ_ONE();
     READ_ONE();
     if (tmp != 1)
         goto start;
-    last_pos = url_ftell(pb);
-    url_fseek(pb, -5, SEEK_CUR);
+    last_pos = avio_tell(pb);
+    if (avio_seek(pb, -5, SEEK_CUR) < 0)
+        goto out;
     if (!parse_packet_header(pb, &type, &len) || type != PKT_MEDIA) {
-        url_fseek(pb, last_pos, SEEK_SET);
+        if (avio_seek(pb, last_pos, SEEK_SET) < 0)
+            goto out;
         goto start;
     }
-    get_byte(pb);
-    cur_track = get_byte(pb);
-    cur_timestamp = get_be32(pb);
-    last_found_pos = url_ftell(pb) - 16 - 6;
+    avio_r8(pb);
+    cur_track = avio_r8(pb);
+    cur_timestamp = avio_rb32(pb);
+    last_found_pos = avio_tell(pb) - 16 - 6;
     if ((track >= 0 && track != cur_track) || (timestamp >= 0 && timestamp > cur_timestamp)) {
-        url_fseek(pb, last_pos, SEEK_SET);
-        goto start;
+        if (avio_seek(pb, last_pos, SEEK_SET) >= 0)
+            goto start;
     }
 out:
     if (last_found_pos)
-        url_fseek(pb, last_found_pos, SEEK_SET);
+        avio_seek(pb, last_found_pos, SEEK_SET);
     return cur_timestamp;
 }
 
 static int gxf_packet(AVFormatContext *s, AVPacket *pkt) {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     GXFPktType pkt_type;
     int pkt_len;
-    while (!url_feof(pb)) {
+    while (!pb->eof_reached) {
         AVStream *st;
         int track_type, track_id, ret;
         int field_nr, field_info, skip = 0;
         int stream_index;
         if (!parse_packet_header(pb, &pkt_type, &pkt_len)) {
-            if (!url_feof(pb))
+            if (!pb->eof_reached)
                 av_log(s, AV_LOG_ERROR, "sync lost\n");
             return -1;
         }
@@ -431,7 +437,7 @@ static int gxf_packet(AVFormatContext *s, AVPacket *pkt) {
             continue;
         }
         if (pkt_type != PKT_MEDIA) {
-            url_fskip(pb, pkt_len);
+            avio_skip(pb, pkt_len);
             continue;
         }
         if (pkt_len < 16) {
@@ -439,24 +445,24 @@ static int gxf_packet(AVFormatContext *s, AVPacket *pkt) {
             continue;
         }
         pkt_len -= 16;
-        track_type = get_byte(pb);
-        track_id = get_byte(pb);
+        track_type = avio_r8(pb);
+        track_id = avio_r8(pb);
         stream_index = get_sindex(s, track_id, track_type);
         if (stream_index < 0)
             return stream_index;
         st = s->streams[stream_index];
-        field_nr = get_be32(pb);
-        field_info = get_be32(pb);
-        get_be32(pb); // "timeline" field number
-        get_byte(pb); // flags
-        get_byte(pb); // reserved
+        field_nr = avio_rb32(pb);
+        field_info = avio_rb32(pb);
+        avio_rb32(pb); // "timeline" field number
+        avio_r8(pb); // flags
+        avio_r8(pb); // reserved
         if (st->codec->codec_id == CODEC_ID_PCM_S24LE ||
             st->codec->codec_id == CODEC_ID_PCM_S16LE) {
             int first = field_info >> 16;
             int last  = field_info & 0xffff; // last is exclusive
             int bps = av_get_bits_per_sample(st->codec->codec_id)>>3;
             if (first <= last && last*bps <= pkt_len) {
-                url_fskip(pb, first*bps);
+                avio_skip(pb, first*bps);
                 skip = pkt_len - last*bps;
                 pkt_len = (last-first)*bps;
             } else
@@ -464,7 +470,7 @@ static int gxf_packet(AVFormatContext *s, AVPacket *pkt) {
         }
         ret = av_get_packet(pb, pkt, pkt_len);
         if (skip)
-            url_fskip(pb, skip);
+            avio_skip(pb, skip);
         pkt->stream_index = stream_index;
         pkt->dts = field_nr;
         return ret;
@@ -473,6 +479,7 @@ static int gxf_packet(AVFormatContext *s, AVPacket *pkt) {
 }
 
 static int gxf_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags) {
+    int res = 0;
     uint64_t pos;
     uint64_t maxlen = 100 * 1024 * 1024;
     AVStream *st = s->streams[0];
@@ -488,7 +495,9 @@ static int gxf_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int
     if (idx < st->nb_index_entries - 2)
         maxlen = st->index_entries[idx + 2].pos - pos;
     maxlen = FFMAX(maxlen, 200 * 1024);
-    url_fseek(s->pb, pos, SEEK_SET);
+    res = avio_seek(s->pb, pos, SEEK_SET);
+    if (res < 0)
+        return res;
     found = gxf_resync_media(s, maxlen, -1, timestamp);
     if (FFABS(found - timestamp) > 4)
         return -1;
@@ -497,15 +506,16 @@ static int gxf_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int
 
 static int64_t gxf_read_timestamp(AVFormatContext *s, int stream_index,
                                   int64_t *pos, int64_t pos_limit) {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int64_t res;
-    url_fseek(pb, *pos, SEEK_SET);
+    if (avio_seek(pb, *pos, SEEK_SET) < 0)
+        return AV_NOPTS_VALUE;
     res = gxf_resync_media(s, pos_limit - *pos, -1, -1);
-    *pos = url_ftell(pb);
+    *pos = avio_tell(pb);
     return res;
 }
 
-AVInputFormat gxf_demuxer = {
+AVInputFormat ff_gxf_demuxer = {
     "gxf",
     NULL_IF_CONFIG_SMALL("GXF format"),
     0,
diff --git a/libavformat/gxf.h b/libavformat/gxf.h
index dcdcdef..c1ac399 100644
--- a/libavformat/gxf.h
+++ b/libavformat/gxf.h
@@ -2,20 +2,20 @@
  * GXF demuxer
  * copyright (c) 2006 Reimar Doeffinger
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavformat/gxfenc.c b/libavformat/gxfenc.c
index a6f4b72..585e0ee 100644
--- a/libavformat/gxfenc.c
+++ b/libavformat/gxfenc.c
@@ -2,20 +2,20 @@
  * GXF muxer.
  * Copyright (c) 2006 SmartJog S.A., Baptiste Coudurier <baptiste dot coudurier at smartjog dot com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -113,53 +113,53 @@ static int gxf_find_lines_index(AVStream *st)
     return -1;
 }
 
-static void gxf_write_padding(ByteIOContext *pb, int64_t to_pad)
+static void gxf_write_padding(AVIOContext *pb, int64_t to_pad)
 {
     for (; to_pad > 0; to_pad--) {
-        put_byte(pb, 0);
+        avio_w8(pb, 0);
     }
 }
 
-static int64_t updatePacketSize(ByteIOContext *pb, int64_t pos)
+static int64_t updatePacketSize(AVIOContext *pb, int64_t pos)
 {
     int64_t curpos;
     int size;
 
-    size = url_ftell(pb) - pos;
+    size = avio_tell(pb) - pos;
     if (size % 4) {
         gxf_write_padding(pb, 4 - size % 4);
-        size = url_ftell(pb) - pos;
+        size = avio_tell(pb) - pos;
     }
-    curpos = url_ftell(pb);
-    url_fseek(pb, pos + 6, SEEK_SET);
-    put_be32(pb, size);
-    url_fseek(pb, curpos, SEEK_SET);
+    curpos = avio_tell(pb);
+    avio_seek(pb, pos + 6, SEEK_SET);
+    avio_wb32(pb, size);
+    avio_seek(pb, curpos, SEEK_SET);
     return curpos - pos;
 }
 
-static int64_t updateSize(ByteIOContext *pb, int64_t pos)
+static int64_t updateSize(AVIOContext *pb, int64_t pos)
 {
     int64_t curpos;
 
-    curpos = url_ftell(pb);
-    url_fseek(pb, pos, SEEK_SET);
-    put_be16(pb, curpos - pos - 2);
-    url_fseek(pb, curpos, SEEK_SET);
+    curpos = avio_tell(pb);
+    avio_seek(pb, pos, SEEK_SET);
+    avio_wb16(pb, curpos - pos - 2);
+    avio_seek(pb, curpos, SEEK_SET);
     return curpos - pos;
 }
 
-static void gxf_write_packet_header(ByteIOContext *pb, GXFPktType type)
+static void gxf_write_packet_header(AVIOContext *pb, GXFPktType type)
 {
-    put_be32(pb, 0); /* packet leader for synchro */
-    put_byte(pb, 1);
-    put_byte(pb, type); /* map packet */
-    put_be32(pb, 0); /* size */
-    put_be32(pb, 0); /* reserved */
-    put_byte(pb, 0xE1); /* trailer 1 */
-    put_byte(pb, 0xE2); /* trailer 2 */
+    avio_wb32(pb, 0);  /* packet leader for synchro */
+    avio_w8(pb, 1);
+    avio_w8(pb, type); /* map packet */
+    avio_wb32(pb, 0);  /* size */
+    avio_wb32(pb, 0);  /* reserved */
+    avio_w8(pb, 0xE1); /* trailer 1 */
+    avio_w8(pb, 0xE2); /* trailer 2 */
 }
 
-static int gxf_write_mpeg_auxiliary(ByteIOContext *pb, AVStream *st)
+static int gxf_write_mpeg_auxiliary(AVIOContext *pb, AVStream *st)
 {
     GXFStreamContext *sc = st->priv_data;
     char buffer[1024];
@@ -190,76 +190,76 @@ static int gxf_write_mpeg_auxiliary(ByteIOContext *pb, AVStream *st)
                     "Pix 0\nCf %d\nCg %d\nSl %d\nnl16 %d\nVi 1\nf1 1\n",
                     (float)st->codec->bit_rate, sc->p_per_gop, sc->b_per_i_or_p,
                     st->codec->pix_fmt == PIX_FMT_YUV422P ? 2 : 1, sc->first_gop_closed == 1,
-                    starting_line, st->codec->height / 16);
-    put_byte(pb, TRACK_MPG_AUX);
-    put_byte(pb, size + 1);
-    put_buffer(pb, (uint8_t *)buffer, size + 1);
+                    starting_line, (st->codec->height + 15) / 16);
+    avio_w8(pb, TRACK_MPG_AUX);
+    avio_w8(pb, size + 1);
+    avio_write(pb, (uint8_t *)buffer, size + 1);
     return size + 3;
 }
 
-static int gxf_write_timecode_auxiliary(ByteIOContext *pb, GXFStreamContext *sc)
+static int gxf_write_timecode_auxiliary(AVIOContext *pb, GXFStreamContext *sc)
 {
-    put_byte(pb, 0); /* fields */
-    put_byte(pb, 0);  /* seconds */
-    put_byte(pb, 0); /* minutes */
-    put_byte(pb, 0); /* flags + hours */
+    avio_w8(pb, 0); /* fields */
+    avio_w8(pb, 0); /* seconds */
+    avio_w8(pb, 0); /* minutes */
+    avio_w8(pb, 0); /* flags + hours */
     /* reserved */
-    put_be32(pb, 0);
+    avio_wb32(pb, 0);
     return 8;
 }
 
 static int gxf_write_track_description(AVFormatContext *s, GXFStreamContext *sc, int index)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int64_t pos;
     int mpeg = sc->track_type == 4 || sc->track_type == 9;
 
     /* track description section */
-    put_byte(pb, sc->media_type + 0x80);
-    put_byte(pb, index + 0xC0);
+    avio_w8(pb, sc->media_type + 0x80);
+    avio_w8(pb, index + 0xC0);
 
-    pos = url_ftell(pb);
-    put_be16(pb, 0); /* size */
+    pos = avio_tell(pb);
+    avio_wb16(pb, 0); /* size */
 
     /* media file name */
-    put_byte(pb, TRACK_NAME);
-    put_byte(pb, strlen(ES_NAME_PATTERN) + 3);
-    put_tag(pb, ES_NAME_PATTERN);
-    put_be16(pb, sc->media_info);
-    put_byte(pb, 0);
+    avio_w8(pb, TRACK_NAME);
+    avio_w8(pb, strlen(ES_NAME_PATTERN) + 3);
+    avio_write(pb, ES_NAME_PATTERN, sizeof(ES_NAME_PATTERN) - 1);
+    avio_wb16(pb, sc->media_info);
+    avio_w8(pb, 0);
 
     if (!mpeg) {
         /* auxiliary information */
-        put_byte(pb, TRACK_AUX);
-        put_byte(pb, 8);
+        avio_w8(pb, TRACK_AUX);
+        avio_w8(pb, 8);
         if (sc->track_type == 3)
             gxf_write_timecode_auxiliary(pb, sc);
         else
-            put_le64(pb, 0);
+            avio_wl64(pb, 0);
     }
 
     /* file system version */
-    put_byte(pb, TRACK_VER);
-    put_byte(pb, 4);
-    put_be32(pb, 0);
+    avio_w8(pb, TRACK_VER);
+    avio_w8(pb, 4);
+    avio_wb32(pb, 0);
 
     if (mpeg)
         gxf_write_mpeg_auxiliary(pb, s->streams[index]);
 
     /* frame rate */
-    put_byte(pb, TRACK_FPS);
-    put_byte(pb, 4);
-    put_be32(pb, sc->frame_rate_index);
+    avio_w8(pb, TRACK_FPS);
+    avio_w8(pb, 4);
+    avio_wb32(pb, sc->frame_rate_index);
 
     /* lines per frame */
-    put_byte(pb, TRACK_LINES);
-    put_byte(pb, 4);
-    put_be32(pb, sc->lines_index);
+    avio_w8(pb, TRACK_LINES);
+    avio_w8(pb, 4);
+    avio_wb32(pb, sc->lines_index);
 
     /* fields per frame */
-    put_byte(pb, TRACK_FPF);
-    put_byte(pb, 4);
-    put_be32(pb, sc->fields);
+    avio_w8(pb, TRACK_FPF);
+    avio_w8(pb, 4);
+    avio_wb32(pb, sc->fields);
 
     return updateSize(pb, pos);
 }
@@ -267,47 +267,50 @@ static int gxf_write_track_description(AVFormatContext *s, GXFStreamContext *sc,
 static int gxf_write_material_data_section(AVFormatContext *s)
 {
     GXFContext *gxf = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int64_t pos;
+    int len;
     const char *filename = strrchr(s->filename, '/');
 
-    pos = url_ftell(pb);
-    put_be16(pb, 0); /* size */
+    pos = avio_tell(pb);
+    avio_wb16(pb, 0); /* size */
 
     /* name */
     if (filename)
         filename++;
     else
         filename = s->filename;
-    put_byte(pb, MAT_NAME);
-    put_byte(pb, strlen(SERVER_PATH) + strlen(filename) + 1);
-    put_tag(pb, SERVER_PATH);
-    put_tag(pb, filename);
-    put_byte(pb, 0);
+    len = strlen(filename);
+
+    avio_w8(pb, MAT_NAME);
+    avio_w8(pb, strlen(SERVER_PATH) + len + 1);
+    avio_write(pb, SERVER_PATH, sizeof(SERVER_PATH) - 1);
+    avio_write(pb, filename, len);
+    avio_w8(pb, 0);
 
     /* first field */
-    put_byte(pb, MAT_FIRST_FIELD);
-    put_byte(pb, 4);
-    put_be32(pb, 0);
+    avio_w8(pb, MAT_FIRST_FIELD);
+    avio_w8(pb, 4);
+    avio_wb32(pb, 0);
 
     /* last field */
-    put_byte(pb, MAT_LAST_FIELD);
-    put_byte(pb, 4);
-    put_be32(pb, gxf->nb_fields);
+    avio_w8(pb, MAT_LAST_FIELD);
+    avio_w8(pb, 4);
+    avio_wb32(pb, gxf->nb_fields);
 
     /* reserved */
-    put_byte(pb, MAT_MARK_IN);
-    put_byte(pb, 4);
-    put_be32(pb, 0);
+    avio_w8(pb, MAT_MARK_IN);
+    avio_w8(pb, 4);
+    avio_wb32(pb, 0);
 
-    put_byte(pb, MAT_MARK_OUT);
-    put_byte(pb, 4);
-    put_be32(pb, gxf->nb_fields);
+    avio_w8(pb, MAT_MARK_OUT);
+    avio_w8(pb, 4);
+    avio_wb32(pb, gxf->nb_fields);
 
     /* estimated size */
-    put_byte(pb, MAT_SIZE);
-    put_byte(pb, 4);
-    put_be32(pb, url_fsize(pb) / 1024);
+    avio_w8(pb, MAT_SIZE);
+    avio_w8(pb, 4);
+    avio_wb32(pb, avio_size(pb) / 1024);
 
     return updateSize(pb, pos);
 }
@@ -315,12 +318,12 @@ static int gxf_write_material_data_section(AVFormatContext *s)
 static int gxf_write_track_description_section(AVFormatContext *s)
 {
     GXFContext *gxf = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int64_t pos;
     int i;
 
-    pos = url_ftell(pb);
-    put_be16(pb, 0); /* size */
+    pos = avio_tell(pb);
+    avio_wb16(pb, 0); /* size */
     for (i = 0; i < s->nb_streams; ++i)
         gxf_write_track_description(s, s->streams[i]->priv_data, i);
 
@@ -332,8 +335,8 @@ static int gxf_write_track_description_section(AVFormatContext *s)
 static int gxf_write_map_packet(AVFormatContext *s, int rewrite)
 {
     GXFContext *gxf = s->priv_data;
-    ByteIOContext *pb = s->pb;
-    int64_t pos = url_ftell(pb);
+    AVIOContext *pb = s->pb;
+    int64_t pos = avio_tell(pb);
 
     if (!rewrite) {
         if (!(gxf->map_offsets_nb % 30)) {
@@ -350,8 +353,8 @@ static int gxf_write_map_packet(AVFormatContext *s, int rewrite)
     gxf_write_packet_header(pb, PKT_MAP);
 
     /* preamble */
-    put_byte(pb, 0xE0); /* version */
-    put_byte(pb, 0xFF); /* reserved */
+    avio_w8(pb, 0xE0); /* version */
+    avio_w8(pb, 0xFF); /* reserved */
 
     gxf_write_material_data_section(s);
     gxf_write_track_description_section(s);
@@ -362,24 +365,24 @@ static int gxf_write_map_packet(AVFormatContext *s, int rewrite)
 static int gxf_write_flt_packet(AVFormatContext *s)
 {
     GXFContext *gxf = s->priv_data;
-    ByteIOContext *pb = s->pb;
-    int64_t pos = url_ftell(pb);
+    AVIOContext *pb = s->pb;
+    int64_t pos = avio_tell(pb);
     int fields_per_flt = (gxf->nb_fields+1) / 1000 + 1;
-    int flt_entries = gxf->nb_fields / fields_per_flt - 1;
+    int flt_entries = gxf->nb_fields / fields_per_flt;
     int i = 0;
 
     gxf_write_packet_header(pb, PKT_FLT);
 
-    put_le32(pb, fields_per_flt); /* number of fields */
-    put_le32(pb, flt_entries); /* number of active flt entries */
+    avio_wl32(pb, fields_per_flt); /* number of fields */
+    avio_wl32(pb, flt_entries); /* number of active flt entries */
 
     if (gxf->flt_entries) {
         for (i = 0; i < flt_entries; i++)
-            put_le32(pb, gxf->flt_entries[(i*fields_per_flt)>>1]);
+            avio_wl32(pb, gxf->flt_entries[(i*fields_per_flt)>>1]);
     }
 
     for (; i < 1000; i++)
-        put_le32(pb, 0);
+        avio_wl32(pb, 0);
 
     return updatePacketSize(pb, pos);
 }
@@ -387,7 +390,7 @@ static int gxf_write_flt_packet(AVFormatContext *s)
 static int gxf_write_umf_material_description(AVFormatContext *s)
 {
     GXFContext *gxf = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int timecode_base = gxf->time_base.den == 60000 ? 60 : 50;
 
     // XXX drop frame
@@ -397,128 +400,128 @@ static int gxf_write_umf_material_description(AVFormatContext *s)
         gxf->nb_fields /  timecode_base % 60         <<  8 | // seconds
         gxf->nb_fields %  timecode_base;                     // fields
 
-    put_le32(pb, gxf->flags);
-    put_le32(pb, gxf->nb_fields); /* length of the longest track */
-    put_le32(pb, gxf->nb_fields); /* length of the shortest track */
-    put_le32(pb, 0); /* mark in */
-    put_le32(pb, gxf->nb_fields); /* mark out */
-    put_le32(pb, 0); /* timecode mark in */
-    put_le32(pb, timecode); /* timecode mark out */
-    put_le64(pb, s->timestamp); /* modification time */
-    put_le64(pb, s->timestamp); /* creation time */
-    put_le16(pb, 0); /* reserved */
-    put_le16(pb, 0); /* reserved */
-    put_le16(pb, gxf->audio_tracks);
-    put_le16(pb, 1); /* timecode track count */
-    put_le16(pb, 0); /* reserved */
-    put_le16(pb, gxf->mpeg_tracks);
+    avio_wl32(pb, gxf->flags);
+    avio_wl32(pb, gxf->nb_fields); /* length of the longest track */
+    avio_wl32(pb, gxf->nb_fields); /* length of the shortest track */
+    avio_wl32(pb, 0); /* mark in */
+    avio_wl32(pb, gxf->nb_fields); /* mark out */
+    avio_wl32(pb, 0); /* timecode mark in */
+    avio_wl32(pb, timecode); /* timecode mark out */
+    avio_wl64(pb, s->timestamp); /* modification time */
+    avio_wl64(pb, s->timestamp); /* creation time */
+    avio_wl16(pb, 0); /* reserved */
+    avio_wl16(pb, 0); /* reserved */
+    avio_wl16(pb, gxf->audio_tracks);
+    avio_wl16(pb, 1); /* timecode track count */
+    avio_wl16(pb, 0); /* reserved */
+    avio_wl16(pb, gxf->mpeg_tracks);
     return 48;
 }
 
 static int gxf_write_umf_payload(AVFormatContext *s)
 {
     GXFContext *gxf = s->priv_data;
-    ByteIOContext *pb = s->pb;
-
-    put_le32(pb, gxf->umf_length); /* total length of the umf data */
-    put_le32(pb, 3); /* version */
-    put_le32(pb, s->nb_streams+1);
-    put_le32(pb, gxf->umf_track_offset); /* umf track section offset */
-    put_le32(pb, gxf->umf_track_size);
-    put_le32(pb, s->nb_streams+1);
-    put_le32(pb, gxf->umf_media_offset);
-    put_le32(pb, gxf->umf_media_size);
-    put_le32(pb, gxf->umf_length); /* user data offset */
-    put_le32(pb, 0); /* user data size */
-    put_le32(pb, 0); /* reserved */
-    put_le32(pb, 0); /* reserved */
+    AVIOContext *pb = s->pb;
+
+    avio_wl32(pb, gxf->umf_length); /* total length of the umf data */
+    avio_wl32(pb, 3); /* version */
+    avio_wl32(pb, s->nb_streams+1);
+    avio_wl32(pb, gxf->umf_track_offset); /* umf track section offset */
+    avio_wl32(pb, gxf->umf_track_size);
+    avio_wl32(pb, s->nb_streams+1);
+    avio_wl32(pb, gxf->umf_media_offset);
+    avio_wl32(pb, gxf->umf_media_size);
+    avio_wl32(pb, gxf->umf_length); /* user data offset */
+    avio_wl32(pb, 0); /* user data size */
+    avio_wl32(pb, 0); /* reserved */
+    avio_wl32(pb, 0); /* reserved */
     return 48;
 }
 
 static int gxf_write_umf_track_description(AVFormatContext *s)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     GXFContext *gxf = s->priv_data;
-    int64_t pos = url_ftell(pb);
+    int64_t pos = avio_tell(pb);
     int i;
 
     gxf->umf_track_offset = pos - gxf->umf_start_offset;
     for (i = 0; i < s->nb_streams; ++i) {
         GXFStreamContext *sc = s->streams[i]->priv_data;
-        put_le16(pb, sc->media_info);
-        put_le16(pb, 1);
+        avio_wl16(pb, sc->media_info);
+        avio_wl16(pb, 1);
     }
 
-    put_le16(pb, gxf->timecode_track.media_info);
-    put_le16(pb, 1);
+    avio_wl16(pb, gxf->timecode_track.media_info);
+    avio_wl16(pb, 1);
 
-    return url_ftell(pb) - pos;
+    return avio_tell(pb) - pos;
 }
 
-static int gxf_write_umf_media_mpeg(ByteIOContext *pb, AVStream *st)
+static int gxf_write_umf_media_mpeg(AVIOContext *pb, AVStream *st)
 {
     GXFStreamContext *sc = st->priv_data;
 
     if (st->codec->pix_fmt == PIX_FMT_YUV422P)
-        put_le32(pb, 2);
+        avio_wl32(pb, 2);
     else
-        put_le32(pb, 1); /* default to 420 */
-    put_le32(pb, sc->first_gop_closed == 1); /* closed = 1, open = 0, unknown = 255 */
-    put_le32(pb, 3); /* top = 1, bottom = 2, frame = 3, unknown = 0 */
-    put_le32(pb, 1); /* I picture per GOP */
-    put_le32(pb, sc->p_per_gop);
-    put_le32(pb, sc->b_per_i_or_p);
+        avio_wl32(pb, 1); /* default to 420 */
+    avio_wl32(pb, sc->first_gop_closed == 1); /* closed = 1, open = 0, unknown = 255 */
+    avio_wl32(pb, 3); /* top = 1, bottom = 2, frame = 3, unknown = 0 */
+    avio_wl32(pb, 1); /* I picture per GOP */
+    avio_wl32(pb, sc->p_per_gop);
+    avio_wl32(pb, sc->b_per_i_or_p);
     if (st->codec->codec_id == CODEC_ID_MPEG2VIDEO)
-        put_le32(pb, 2);
+        avio_wl32(pb, 2);
     else if (st->codec->codec_id == CODEC_ID_MPEG1VIDEO)
-        put_le32(pb, 1);
+        avio_wl32(pb, 1);
     else
-        put_le32(pb, 0);
-    put_le32(pb, 0); /* reserved */
+        avio_wl32(pb, 0);
+    avio_wl32(pb, 0); /* reserved */
     return 32;
 }
 
-static int gxf_write_umf_media_timecode(ByteIOContext *pb, GXFStreamContext *sc)
+static int gxf_write_umf_media_timecode(AVIOContext *pb, GXFStreamContext *sc)
 {
-    put_le32(pb, 1); /* non drop frame */
-    put_le32(pb, 0); /* reserved */
-    put_le32(pb, 0); /* reserved */
-    put_le32(pb, 0); /* reserved */
-    put_le32(pb, 0); /* reserved */
-    put_le32(pb, 0); /* reserved */
-    put_le32(pb, 0); /* reserved */
-    put_le32(pb, 0); /* reserved */
+    avio_wl32(pb, 1); /* non drop frame */
+    avio_wl32(pb, 0); /* reserved */
+    avio_wl32(pb, 0); /* reserved */
+    avio_wl32(pb, 0); /* reserved */
+    avio_wl32(pb, 0); /* reserved */
+    avio_wl32(pb, 0); /* reserved */
+    avio_wl32(pb, 0); /* reserved */
+    avio_wl32(pb, 0); /* reserved */
     return 32;
 }
 
-static int gxf_write_umf_media_dv(ByteIOContext *pb, GXFStreamContext *sc)
+static int gxf_write_umf_media_dv(AVIOContext *pb, GXFStreamContext *sc)
 {
     int i;
 
     for (i = 0; i < 8; i++) {
-        put_be32(pb, 0);
+        avio_wb32(pb, 0);
     }
     return 32;
 }
 
-static int gxf_write_umf_media_audio(ByteIOContext *pb, GXFStreamContext *sc)
+static int gxf_write_umf_media_audio(AVIOContext *pb, GXFStreamContext *sc)
 {
-    put_le64(pb, av_dbl2int(1)); /* sound level to begin to */
-    put_le64(pb, av_dbl2int(1)); /* sound level to begin to */
-    put_le32(pb, 0); /* number of fields over which to ramp up sound level */
-    put_le32(pb, 0); /* number of fields over which to ramp down sound level */
-    put_le32(pb, 0); /* reserved */
-    put_le32(pb, 0); /* reserved */
+    avio_wl64(pb, av_dbl2int(1)); /* sound level to begin to */
+    avio_wl64(pb, av_dbl2int(1)); /* sound level to begin to */
+    avio_wl32(pb, 0); /* number of fields over which to ramp up sound level */
+    avio_wl32(pb, 0); /* number of fields over which to ramp down sound level */
+    avio_wl32(pb, 0); /* reserved */
+    avio_wl32(pb, 0); /* reserved */
     return 32;
 }
 
 #if 0
-static int gxf_write_umf_media_mjpeg(ByteIOContext *pb, GXFStreamContext *sc)
+static int gxf_write_umf_media_mjpeg(AVIOContext *pb, GXFStreamContext *sc)
 {
-    put_be64(pb, 0); /* FIXME FLOAT max chroma quant level */
-    put_be64(pb, 0); /* FIXME FLOAT max luma quant level */
-    put_be64(pb, 0); /* FIXME FLOAT min chroma quant level */
-    put_be64(pb, 0); /* FIXME FLOAT min luma quant level */
+    avio_wb64(pb, 0); /* FIXME FLOAT max chroma quant level */
+    avio_wb64(pb, 0); /* FIXME FLOAT max luma quant level */
+    avio_wb64(pb, 0); /* FIXME FLOAT min chroma quant level */
+    avio_wb64(pb, 0); /* FIXME FLOAT min luma quant level */
     return 32;
 }
 #endif
@@ -526,11 +529,11 @@ static int gxf_write_umf_media_mjpeg(ByteIOContext *pb, GXFStreamContext *sc)
 static int gxf_write_umf_media_description(AVFormatContext *s)
 {
     GXFContext *gxf = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int64_t pos;
     int i, j;
 
-    pos = url_ftell(pb);
+    pos = avio_tell(pb);
     gxf->umf_media_offset = pos - gxf->umf_start_offset;
     for (i = 0; i <= s->nb_streams; ++i) {
         GXFStreamContext *sc;
@@ -541,29 +544,30 @@ static int gxf_write_umf_media_description(AVFormatContext *s)
         else
             sc = s->streams[i]->priv_data;
 
-        startpos = url_ftell(pb);
-        put_le16(pb, 0); /* length */
-        put_le16(pb, sc->media_info);
-        put_le16(pb, 0); /* reserved */
-        put_le16(pb, 0); /* reserved */
-        put_le32(pb, gxf->nb_fields);
-        put_le32(pb, 0); /* attributes rw, ro */
-        put_le32(pb, 0); /* mark in */
-        put_le32(pb, gxf->nb_fields); /* mark out */
-        put_buffer(pb, ES_NAME_PATTERN, sizeof(ES_NAME_PATTERN));
-        put_be16(pb, sc->media_info);
-        for (j = sizeof(ES_NAME_PATTERN)+2; j < 88; j++)
-            put_byte(pb, 0);
-        put_le32(pb, sc->track_type);
-        put_le32(pb, sc->sample_rate);
-        put_le32(pb, sc->sample_size);
-        put_le32(pb, 0); /* reserved */
+        startpos = avio_tell(pb);
+        avio_wl16(pb, 0); /* length */
+        avio_wl16(pb, sc->media_info);
+        avio_wl16(pb, 0); /* reserved */
+        avio_wl16(pb, 0); /* reserved */
+        avio_wl32(pb, gxf->nb_fields);
+        avio_wl32(pb, 0); /* attributes rw, ro */
+        avio_wl32(pb, 0); /* mark in */
+        avio_wl32(pb, gxf->nb_fields); /* mark out */
+        avio_write(pb, ES_NAME_PATTERN, strlen(ES_NAME_PATTERN));
+        avio_wb16(pb, sc->media_info);
+        for (j = strlen(ES_NAME_PATTERN)+2; j < 88; j++)
+            avio_w8(pb, 0);
+        avio_wl32(pb, sc->track_type);
+        avio_wl32(pb, sc->sample_rate);
+        avio_wl32(pb, sc->sample_size);
+        avio_wl32(pb, 0); /* reserved */
 
         if (sc == &gxf->timecode_track)
             gxf_write_umf_media_timecode(pb, sc); /* 8 0bytes */
         else {
             AVStream *st = s->streams[i];
             switch (st->codec->codec_id) {
+            case CODEC_ID_MPEG1VIDEO:
             case CODEC_ID_MPEG2VIDEO:
                 gxf_write_umf_media_mpeg(pb, st);
                 break;
@@ -576,32 +580,32 @@ static int gxf_write_umf_media_description(AVFormatContext *s)
             }
         }
 
-        curpos = url_ftell(pb);
-        url_fseek(pb, startpos, SEEK_SET);
-        put_le16(pb, curpos - startpos);
-        url_fseek(pb, curpos, SEEK_SET);
+        curpos = avio_tell(pb);
+        avio_seek(pb, startpos, SEEK_SET);
+        avio_wl16(pb, curpos - startpos);
+        avio_seek(pb, curpos, SEEK_SET);
     }
-    return url_ftell(pb) - pos;
+    return avio_tell(pb) - pos;
 }
 
 static int gxf_write_umf_packet(AVFormatContext *s)
 {
     GXFContext *gxf = s->priv_data;
-    ByteIOContext *pb = s->pb;
-    int64_t pos = url_ftell(pb);
+    AVIOContext *pb = s->pb;
+    int64_t pos = avio_tell(pb);
 
     gxf_write_packet_header(pb, PKT_UMF);
 
     /* preamble */
-    put_byte(pb, 3); /* first and last (only) packet */
-    put_be32(pb, gxf->umf_length); /* data length */
+    avio_w8(pb, 3); /* first and last (only) packet */
+    avio_wb32(pb, gxf->umf_length); /* data length */
 
-    gxf->umf_start_offset = url_ftell(pb);
+    gxf->umf_start_offset = avio_tell(pb);
     gxf_write_umf_payload(s);
     gxf_write_umf_material_description(s);
     gxf->umf_track_size = gxf_write_umf_track_description(s);
     gxf->umf_media_size = gxf_write_umf_media_description(s);
-    gxf->umf_length = url_ftell(pb) - gxf->umf_start_offset;
+    gxf->umf_length = avio_tell(pb) - gxf->umf_start_offset;
     return updatePacketSize(pb, pos);
 }
 
@@ -624,13 +628,13 @@ static void gxf_init_timecode_track(GXFStreamContext *sc, GXFStreamContext *vsc)
 
 static int gxf_write_header(AVFormatContext *s)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     GXFContext *gxf = s->priv_data;
     GXFStreamContext *vsc = NULL;
     uint8_t tracks[255] = {0};
     int i, media_info = 0;
 
-    if (url_is_streamed(pb)) {
+    if (!pb->seekable) {
         av_log(s, AV_LOG_ERROR, "gxf muxer does not support streamed output, patch welcome");
         return -1;
     }
@@ -678,12 +682,16 @@ static int gxf_write_header(AVFormatContext *s)
                 sc->sample_rate = 60;
                 gxf->flags |= 0x00000080;
                 gxf->time_base = (AVRational){ 1001, 60000 };
-            } else { /* assume PAL */
+            } else if (st->codec->height == 576 || st->codec->height == 608) { /* PAL or PAL+VBI */
                 sc->frame_rate_index = 6;
                 sc->media_type++;
                 sc->sample_rate = 50;
                 gxf->flags |= 0x00000040;
                 gxf->time_base = (AVRational){ 1, 50 };
+            } else {
+                av_log(s, AV_LOG_ERROR, "unsupported video resolution, "
+                       "gxf muxer only accepts PAL or NTSC resolutions currently\n");
+                return -1;
             }
             av_set_pts_info(st, 64, gxf->time_base.num, gxf->time_base.den);
             if (gxf_find_lines_index(st) < 0)
@@ -745,13 +753,13 @@ static int gxf_write_header(AVFormatContext *s)
 
     gxf->packet_count = 3;
 
-    put_flush_packet(pb);
+    avio_flush(pb);
     return 0;
 }
 
-static int gxf_write_eos_packet(ByteIOContext *pb)
+static int gxf_write_eos_packet(AVIOContext *pb)
 {
-    int64_t pos = url_ftell(pb);
+    int64_t pos = avio_tell(pb);
 
     gxf_write_packet_header(pb, PKT_EOS);
     return updatePacketSize(pb, pos);
@@ -760,28 +768,28 @@ static int gxf_write_eos_packet(ByteIOContext *pb)
 static int gxf_write_trailer(AVFormatContext *s)
 {
     GXFContext *gxf = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int64_t end;
     int i;
 
     ff_audio_interleave_close(s);
 
     gxf_write_eos_packet(pb);
-    end = url_ftell(pb);
-    url_fseek(pb, 0, SEEK_SET);
+    end = avio_tell(pb);
+    avio_seek(pb, 0, SEEK_SET);
     /* overwrite map, flt and umf packets with new values */
     gxf_write_map_packet(s, 1);
     gxf_write_flt_packet(s);
     gxf_write_umf_packet(s);
-    put_flush_packet(pb);
+    avio_flush(pb);
     /* update duration in all map packets */
     for (i = 1; i < gxf->map_offsets_nb; i++) {
-        url_fseek(pb, gxf->map_offsets[i], SEEK_SET);
+        avio_seek(pb, gxf->map_offsets[i], SEEK_SET);
         gxf_write_map_packet(s, 1);
-        put_flush_packet(pb);
+        avio_flush(pb);
     }
 
-    url_fseek(pb, end, SEEK_SET);
+    avio_seek(pb, end, SEEK_SET);
 
     av_freep(&gxf->flt_entries);
     av_freep(&gxf->map_offsets);
@@ -804,7 +812,7 @@ static int gxf_parse_mpeg_frame(GXFStreamContext *sc, const uint8_t *buf, int si
 static int gxf_write_media_preamble(AVFormatContext *s, AVPacket *pkt, int size)
 {
     GXFContext *gxf = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVStream *st = s->streams[pkt->stream_index];
     GXFStreamContext *sc = st->priv_data;
     unsigned field_nb;
@@ -818,43 +826,44 @@ static int gxf_write_media_preamble(AVFormatContext *s, AVPacket *pkt, int size)
                                   (int64_t)48000*gxf->time_base.num, AV_ROUND_UP);
     }
 
-    put_byte(pb, sc->media_type);
-    put_byte(pb, st->index);
-    put_be32(pb, field_nb);
+    avio_w8(pb, sc->media_type);
+    avio_w8(pb, st->index);
+    avio_wb32(pb, field_nb);
     if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
-        put_be16(pb, 0);
-        put_be16(pb, size / 2);
+        avio_wb16(pb, 0);
+        avio_wb16(pb, size / 2);
     } else if (st->codec->codec_id == CODEC_ID_MPEG2VIDEO) {
         int frame_type = gxf_parse_mpeg_frame(sc, pkt->data, pkt->size);
         if (frame_type == FF_I_TYPE) {
-            put_byte(pb, 0x0d);
+            avio_w8(pb, 0x0d);
             sc->iframes++;
         } else if (frame_type == FF_B_TYPE) {
-            put_byte(pb, 0x0f);
+            avio_w8(pb, 0x0f);
             sc->bframes++;
         } else {
-            put_byte(pb, 0x0e);
+            avio_w8(pb, 0x0e);
             sc->pframes++;
         }
-        put_be24(pb, size);
+        avio_wb24(pb, size);
     } else if (st->codec->codec_id == CODEC_ID_DVVIDEO) {
-        put_byte(pb, size / 4096);
-        put_be24(pb, 0);
+        avio_w8(pb, size / 4096);
+        avio_wb24(pb, 0);
     } else
-        put_be32(pb, size);
-    put_be32(pb, field_nb);
-    put_byte(pb, 1); /* flags */
-    put_byte(pb, 0); /* reserved */
+        avio_wb32(pb, size);
+    avio_wb32(pb, field_nb);
+    avio_w8(pb, 1); /* flags */
+    avio_w8(pb, 0); /* reserved */
     return 16;
 }
 
 static int gxf_write_packet(AVFormatContext *s, AVPacket *pkt)
 {
     GXFContext *gxf = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVStream *st = s->streams[pkt->stream_index];
-    int64_t pos = url_ftell(pb);
+    int64_t pos = avio_tell(pb);
     int padding = 0;
+    int packet_start_offset = avio_tell(pb) / 1024;
 
     gxf_write_packet_header(pb, PKT_MEDIA);
     if (st->codec->codec_id == CODEC_ID_MPEG2VIDEO && pkt->size % 4) /* MPEG-2 frames must be padded */
@@ -862,7 +871,7 @@ static int gxf_write_packet(AVFormatContext *s, AVPacket *pkt)
     else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
         padding = GXF_AUDIO_PACKET_SIZE - pkt->size;
     gxf_write_media_preamble(s, pkt, pkt->size + padding);
-    put_buffer(pb, pkt->data, pkt->size);
+    avio_write(pb, pkt->data, pkt->size);
     gxf_write_padding(pb, padding);
 
     if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
@@ -874,7 +883,7 @@ static int gxf_write_packet(AVFormatContext *s, AVPacket *pkt)
                 return -1;
             }
         }
-        gxf->flt_entries[gxf->flt_entries_nb++] = url_ftell(pb) / 1024;
+        gxf->flt_entries[gxf->flt_entries_nb++] = packet_start_offset;
         gxf->nb_fields += 2; // count fields
     }
 
@@ -886,7 +895,7 @@ static int gxf_write_packet(AVFormatContext *s, AVPacket *pkt)
         gxf->packet_count = 0;
     }
 
-    put_flush_packet(pb);
+    avio_flush(pb);
 
     return 0;
 }
@@ -921,7 +930,7 @@ static int gxf_interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *pk
                                av_interleave_packet_per_dts, gxf_compare_field_nb);
 }
 
-AVOutputFormat gxf_muxer = {
+AVOutputFormat ff_gxf_muxer = {
     "gxf",
     NULL_IF_CONFIG_SMALL("GXF format"),
     NULL,
diff --git a/libavformat/h261dec.c b/libavformat/h261dec.c
new file mode 100644
index 0000000..8d9c5fa
--- /dev/null
+++ b/libavformat/h261dec.c
@@ -0,0 +1,75 @@
+/*
+ * RAW H.261 video demuxer
+ * Copyright (c) 2009 Michael Niedermayer <michaelni at gmx.at>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "libavcodec/get_bits.h"
+#include "avformat.h"
+#include "rawdec.h"
+
+static int h261_probe(AVProbeData *p)
+{
+    uint32_t code= -1;
+    int i;
+    int valid_psc=0;
+    int invalid_psc=0;
+    int next_gn=0;
+    int src_fmt=0;
+    GetBitContext gb;
+
+    init_get_bits(&gb, p->buf, p->buf_size*8);
+
+    for(i=0; i<p->buf_size*8; i++){
+        if ((code & 0x01ff0000) || !(code & 0xff00)) {
+            code = (code<<8) + get_bits(&gb, 8);
+            i += 7;
+        } else
+            code = (code<<1) + get_bits1(&gb);
+        if ((code & 0xffff0000) == 0x10000) {
+            int gn= (code>>12)&0xf;
+            if(!gn)
+                src_fmt= code&8;
+            if(gn != next_gn) invalid_psc++;
+            else              valid_psc++;
+
+            if(src_fmt){ // CIF
+                next_gn= (gn+1     )%13;
+            }else{       //QCIF
+                next_gn= (gn+1+!!gn)% 7;
+            }
+        }
+    }
+    if(valid_psc > 2*invalid_psc + 6){
+        return 50;
+    }else if(valid_psc > 2*invalid_psc + 2)
+        return 25;
+    return 0;
+}
+
+AVInputFormat ff_h261_demuxer = {
+    "h261",
+    NULL_IF_CONFIG_SMALL("raw H.261"),
+    0,
+    h261_probe,
+    ff_raw_video_read_header,
+    ff_raw_read_partial_packet,
+    .flags= AVFMT_GENERIC_INDEX,
+    .extensions = "h261",
+    .value = CODEC_ID_H261,
+};
diff --git a/libavformat/h263dec.c b/libavformat/h263dec.c
new file mode 100644
index 0000000..5eda7af
--- /dev/null
+++ b/libavformat/h263dec.c
@@ -0,0 +1,77 @@
+/*
+ * RAW H.263 video demuxer
+ * Copyright (c) 2009 Michael Niedermayer <michaelni at gmx.at>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "avformat.h"
+#include "rawdec.h"
+
+static int h263_probe(AVProbeData *p)
+{
+    uint64_t code= -1;
+    int i;
+    int valid_psc=0;
+    int invalid_psc=0;
+    int res_change=0;
+    int src_fmt, last_src_fmt=-1;
+    int last_gn=0;
+
+    for(i=0; i<p->buf_size; i++){
+        code = (code<<8) + p->buf[i];
+        if ((code & 0xfffffc0000) == 0x800000) {
+            src_fmt= (code>>2)&3;
+            if(   src_fmt != last_src_fmt
+               && last_src_fmt>0 && last_src_fmt<6
+               && src_fmt<6)
+                res_change++;
+
+            if((code&0x300)==0x200 && src_fmt){
+                valid_psc++;
+                last_gn=0;
+            }else
+                invalid_psc++;
+            last_src_fmt= src_fmt;
+        } else if((code & 0xffff800000) == 0x800000) {
+            int gn= (code>>(23-5)) & 0x1F;
+            if(gn<last_gn){
+                invalid_psc++;
+            }else
+                last_gn= gn;
+        }
+    }
+//av_log(NULL, AV_LOG_ERROR, "h263_probe: psc:%d invalid:%d res_change:%d\n", valid_psc, invalid_psc, res_change);
+//h263_probe: psc:3 invalid:0 res_change:0 (1588/recent_ffmpeg_parses_mpg_incorrectly.mpg)
+    if(valid_psc > 2*invalid_psc + 2*res_change + 3){
+        return 50;
+    }else if(valid_psc > 2*invalid_psc)
+        return 25;
+    return 0;
+}
+
+AVInputFormat ff_h263_demuxer = {
+    "h263",
+    NULL_IF_CONFIG_SMALL("raw H.263"),
+    0,
+    h263_probe,
+    ff_raw_video_read_header,
+    ff_raw_read_partial_packet,
+    .flags= AVFMT_GENERIC_INDEX,
+//    .extensions = "h263", //FIXME remove after writing mpeg4_probe
+    .value = CODEC_ID_H263,
+};
diff --git a/libavformat/h264dec.c b/libavformat/h264dec.c
new file mode 100644
index 0000000..268492c
--- /dev/null
+++ b/libavformat/h264dec.c
@@ -0,0 +1,80 @@
+/*
+ * RAW H.264 video demuxer
+ * Copyright (c) 2008 Michael Niedermayer <michaelni at gmx.at>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "avformat.h"
+#include "rawdec.h"
+
+static int h264_probe(AVProbeData *p)
+{
+    uint32_t code= -1;
+    int sps=0, pps=0, idr=0, res=0, sli=0;
+    int i;
+
+    for(i=0; i<p->buf_size; i++){
+        code = (code<<8) + p->buf[i];
+        if ((code & 0xffffff00) == 0x100) {
+            int ref_idc= (code>>5)&3;
+            int type   = code & 0x1F;
+            static const int8_t ref_zero[32]={
+                2, 0, 0, 0, 0,-1, 1,-1,
+               -1, 1, 1, 1, 1,-1, 2, 2,
+                2, 2, 2, 0, 2, 2, 2, 2,
+                2, 2, 2, 2, 2, 2, 2, 2
+            };
+
+            if(code & 0x80) //forbidden bit
+                return 0;
+
+            if(ref_zero[type] == 1 && ref_idc)
+                return 0;
+            if(ref_zero[type] ==-1 && !ref_idc)
+                return 0;
+            if(ref_zero[type] == 2)
+                res++;
+
+            switch(type){
+            case     1:   sli++; break;
+            case     5:   idr++; break;
+            case     7:
+                if(p->buf[i+2]&0x0F)
+                    return 0;
+                sps++;
+                break;
+            case     8:   pps++; break;
+            }
+        }
+    }
+    if(sps && pps && (idr||sli>3) && res<(sps+pps+idr))
+        return AVPROBE_SCORE_MAX/2+1; // +1 for .mpg
+    return 0;
+}
+
+AVInputFormat ff_h264_demuxer = {
+    "h264",
+    NULL_IF_CONFIG_SMALL("raw H.264 video format"),
+    0,
+    h264_probe,
+    ff_raw_video_read_header,
+    ff_raw_read_partial_packet,
+    .flags= AVFMT_GENERIC_INDEX,
+    .extensions = "h26l,h264,264", //FIXME remove after writing mpeg4_probe
+    .value = CODEC_ID_H264,
+};
diff --git a/libavformat/http.c b/libavformat/http.c
index e697578..bcfce80 100644
--- a/libavformat/http.c
+++ b/libavformat/http.c
@@ -2,20 +2,20 @@
  * HTTP protocol for ffmpeg client
  * Copyright (c) 2000, 2001 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,32 +25,66 @@
 #include <strings.h>
 #include "internal.h"
 #include "network.h"
+#include "http.h"
 #include "os_support.h"
 #include "httpauth.h"
+#include "url.h"
+#include "libavutil/opt.h"
 
 /* XXX: POST protocol is not completely implemented because ffmpeg uses
    only a subset of it. */
 
 /* used for protocol handling */
 #define BUFFER_SIZE 1024
-#define URL_SIZE    4096
 #define MAX_REDIRECTS 8
 
 typedef struct {
+    const AVClass *class;
     URLContext *hd;
     unsigned char buffer[BUFFER_SIZE], *buf_ptr, *buf_end;
     int line_count;
     int http_code;
     int64_t chunksize;      /**< Used if "Transfer-Encoding: chunked" otherwise -1. */
     int64_t off, filesize;
-    char location[URL_SIZE];
+    char location[MAX_URL_SIZE];
     HTTPAuthState auth_state;
+    unsigned char headers[BUFFER_SIZE];
+    int willclose;          /**< Set if the server correctly handles Connection: close and will close the connection after feeding us the content. */
 } HTTPContext;
 
+#define OFFSET(x) offsetof(HTTPContext, x)
+static const AVOption options[] = {
+{"chunksize", "use chunked transfer-encoding for posts, -1 disables it, 0 enables it", OFFSET(chunksize), FF_OPT_TYPE_INT64, 0, -1, 0 }, /* Default to 0, for chunked POSTs */
+{NULL}
+};
+static const AVClass httpcontext_class = {
+    "HTTP", av_default_item_name, options, LIBAVUTIL_VERSION_INT
+};
+
 static int http_connect(URLContext *h, const char *path, const char *hoststr,
                         const char *auth, int *new_location);
-static int http_write(URLContext *h, uint8_t *buf, int size);
 
+void ff_http_set_headers(URLContext *h, const char *headers)
+{
+    HTTPContext *s = h->priv_data;
+    int len = strlen(headers);
+
+    if (len && strcmp("\r\n", headers + len - 2))
+        av_log(NULL, AV_LOG_ERROR, "No trailing CRLF found in HTTP header.\n");
+
+    av_strlcpy(s->headers, headers, sizeof(s->headers));
+}
+
+void ff_http_set_chunked_transfer_encoding(URLContext *h, int is_chunked)
+{
+    ((HTTPContext*)h->priv_data)->chunksize = is_chunked ? 0 : -1;
+}
+
+void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
+{
+    memcpy(&((HTTPContext*)dest->priv_data)->auth_state,
+           &((HTTPContext*)src->priv_data)->auth_state, sizeof(HTTPAuthState));
+}
 
 /* return non zero if error */
 static int http_open_cnx(URLContext *h)
@@ -72,12 +106,12 @@ static int http_open_cnx(URLContext *h)
     /* fill the dest addr */
  redo:
     /* needed in any case to build the host string */
-    ff_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
+    av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
                  path1, sizeof(path1), s->location);
     ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
 
     if (use_proxy) {
-        ff_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
+        av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
                      NULL, 0, proxy_path);
         path = s->location;
     } else {
@@ -90,7 +124,7 @@ static int http_open_cnx(URLContext *h)
         port = 80;
 
     ff_url_join(buf, sizeof(buf), "tcp", NULL, hostname, port, NULL);
-    err = url_open(&hd, buf, URL_RDWR);
+    err = ffurl_open(&hd, buf, AVIO_RDWR);
     if (err < 0)
         goto fail;
 
@@ -100,14 +134,15 @@ static int http_open_cnx(URLContext *h)
         goto fail;
     if (s->http_code == 401) {
         if (cur_auth_type == HTTP_AUTH_NONE && s->auth_state.auth_type != HTTP_AUTH_NONE) {
-            url_close(hd);
+            ffurl_close(hd);
             goto redo;
         } else
             goto fail;
     }
-    if ((s->http_code == 302 || s->http_code == 303) && location_changed == 1) {
+    if ((s->http_code == 301 || s->http_code == 302 || s->http_code == 303 || s->http_code == 307)
+        && location_changed == 1) {
         /* url moved, get next */
-        url_close(hd);
+        ffurl_close(hd);
         if (redirects++ >= MAX_REDIRECTS)
             return AVERROR(EIO);
         location_changed = 0;
@@ -116,38 +151,27 @@ static int http_open_cnx(URLContext *h)
     return 0;
  fail:
     if (hd)
-        url_close(hd);
+        ffurl_close(hd);
+    s->hd = NULL;
     return AVERROR(EIO);
 }
 
 static int http_open(URLContext *h, const char *uri, int flags)
 {
-    HTTPContext *s;
-    int ret;
+    HTTPContext *s = h->priv_data;
 
     h->is_streamed = 1;
 
-    s = av_malloc(sizeof(HTTPContext));
-    if (!s) {
-        return AVERROR(ENOMEM);
-    }
-    h->priv_data = s;
     s->filesize = -1;
-    s->chunksize = -1;
-    s->off = 0;
-    memset(&s->auth_state, 0, sizeof(s->auth_state));
-    av_strlcpy(s->location, uri, URL_SIZE);
+    av_strlcpy(s->location, uri, sizeof(s->location));
 
-    ret = http_open_cnx(h);
-    if (ret != 0)
-        av_free (s);
-    return ret;
+    return http_open_cnx(h);
 }
 static int http_getc(HTTPContext *s)
 {
     int len;
     if (s->buf_ptr >= s->buf_end) {
-        len = url_read(s->hd, s->buffer, BUFFER_SIZE);
+        len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
         if (len < 0) {
             return AVERROR(EIO);
         } else if (len == 0) {
@@ -188,7 +212,7 @@ static int process_line(URLContext *h, char *line, int line_count,
                         int *new_location)
 {
     HTTPContext *s = h->priv_data;
-    char *tag, *p;
+    char *tag, *p, *end;
 
     /* end of header */
     if (line[0] == '\0')
@@ -200,14 +224,18 @@ static int process_line(URLContext *h, char *line, int line_count,
             p++;
         while (isspace(*p))
             p++;
-        s->http_code = strtol(p, NULL, 10);
+        s->http_code = strtol(p, &end, 10);
 
-        dprintf(NULL, "http_code=%d\n", s->http_code);
+        av_dlog(NULL, "http_code=%d\n", s->http_code);
 
         /* error codes are 4xx and 5xx, but regard 401 as a success, so we
          * don't abort until all headers have been parsed. */
-        if (s->http_code >= 400 && s->http_code < 600 && s->http_code != 401)
+        if (s->http_code >= 400 && s->http_code < 600 && s->http_code != 401) {
+            end += strspn(end, SPACE_CHARS);
+            av_log(NULL, AV_LOG_WARNING, "HTTP error %d %s\n",
+                   s->http_code, end);
             return -1;
+        }
     } else {
         while (*p != '\0' && *p != ':')
             p++;
@@ -219,12 +247,12 @@ static int process_line(URLContext *h, char *line, int line_count,
         p++;
         while (isspace(*p))
             p++;
-        if (!strcmp(tag, "Location")) {
+        if (!strcasecmp(tag, "Location")) {
             strcpy(s->location, p);
             *new_location = 1;
-        } else if (!strcmp (tag, "Content-Length") && s->filesize == -1) {
+        } else if (!strcasecmp (tag, "Content-Length") && s->filesize == -1) {
             s->filesize = atoll(p);
-        } else if (!strcmp (tag, "Content-Range")) {
+        } else if (!strcasecmp (tag, "Content-Range")) {
             /* "bytes $from-$to/$document_size" */
             const char *slash;
             if (!strncmp (p, "bytes ", 6)) {
@@ -234,52 +262,78 @@ static int process_line(URLContext *h, char *line, int line_count,
                     s->filesize = atoll(slash+1);
             }
             h->is_streamed = 0; /* we _can_ in fact seek */
-        } else if (!strcmp (tag, "Transfer-Encoding") && !strncasecmp(p, "chunked", 7)) {
+        } else if (!strcasecmp (tag, "Transfer-Encoding") && !strncasecmp(p, "chunked", 7)) {
             s->filesize = -1;
             s->chunksize = 0;
-        } else if (!strcmp (tag, "WWW-Authenticate")) {
+        } else if (!strcasecmp (tag, "WWW-Authenticate")) {
             ff_http_auth_handle_header(&s->auth_state, tag, p);
-        } else if (!strcmp (tag, "Authentication-Info")) {
+        } else if (!strcasecmp (tag, "Authentication-Info")) {
             ff_http_auth_handle_header(&s->auth_state, tag, p);
+        } else if (!strcasecmp (tag, "Connection")) {
+            if (!strcmp(p, "close"))
+                s->willclose = 1;
         }
     }
     return 1;
 }
 
+static inline int has_header(const char *str, const char *header)
+{
+    /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
+    return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
+}
+
 static int http_connect(URLContext *h, const char *path, const char *hoststr,
                         const char *auth, int *new_location)
 {
     HTTPContext *s = h->priv_data;
     int post, err;
     char line[1024];
+    char headers[1024] = "";
     char *authstr = NULL;
     int64_t off = s->off;
+    int len = 0;
 
 
     /* send http header */
-    post = h->flags & URL_WRONLY;
+    post = h->flags & AVIO_WRONLY;
     authstr = ff_http_auth_create_response(&s->auth_state, auth, path,
                                         post ? "POST" : "GET");
+
+    /* set default headers if needed */
+    if (!has_header(s->headers, "\r\nUser-Agent: "))
+       len += av_strlcatf(headers + len, sizeof(headers) - len,
+                          "User-Agent: %s\r\n", LIBAVFORMAT_IDENT);
+    if (!has_header(s->headers, "\r\nAccept: "))
+        len += av_strlcpy(headers + len, "Accept: */*\r\n",
+                          sizeof(headers) - len);
+    if (!has_header(s->headers, "\r\nRange: "))
+        len += av_strlcatf(headers + len, sizeof(headers) - len,
+                           "Range: bytes=%"PRId64"-\r\n", s->off);
+    if (!has_header(s->headers, "\r\nConnection: "))
+        len += av_strlcpy(headers + len, "Connection: close\r\n",
+                          sizeof(headers)-len);
+    if (!has_header(s->headers, "\r\nHost: "))
+        len += av_strlcatf(headers + len, sizeof(headers) - len,
+                           "Host: %s\r\n", hoststr);
+
+    /* now add in custom headers */
+    av_strlcpy(headers+len, s->headers, sizeof(headers)-len);
+
     snprintf(s->buffer, sizeof(s->buffer),
              "%s %s HTTP/1.1\r\n"
-             "User-Agent: %s\r\n"
-             "Accept: */*\r\n"
-             "Range: bytes=%"PRId64"-\r\n"
-             "Host: %s\r\n"
              "%s"
-             "Connection: close\r\n"
+             "%s"
              "%s"
              "\r\n",
              post ? "POST" : "GET",
              path,
-             LIBAVFORMAT_IDENT,
-             s->off,
-             hoststr,
-             authstr ? authstr : "",
-             post ? "Transfer-Encoding: chunked\r\n" : "");
+             post && s->chunksize >= 0 ? "Transfer-Encoding: chunked\r\n" : "",
+             headers,
+             authstr ? authstr : "");
 
     av_freep(&authstr);
-    if (http_write(h, s->buffer, strlen(s->buffer)) < 0)
+    if (ffurl_write(s->hd, s->buffer, strlen(s->buffer)) < 0)
         return AVERROR(EIO);
 
     /* init input buffer */
@@ -288,18 +342,22 @@ static int http_connect(URLContext *h, const char *path, const char *hoststr,
     s->line_count = 0;
     s->off = 0;
     s->filesize = -1;
+    s->willclose = 0;
     if (post) {
-        /* always use chunked encoding for upload data */
-        s->chunksize = 0;
+        /* Pretend that it did work. We didn't read any header yet, since
+         * we've still to send the POST data, but the code calling this
+         * function will check http_code after we return. */
+        s->http_code = 200;
         return 0;
     }
+    s->chunksize = -1;
 
     /* wait for header */
     for(;;) {
         if (http_get_line(s, line, sizeof(line)) < 0)
             return AVERROR(EIO);
 
-        dprintf(NULL, "header='%s'\n", line);
+        av_dlog(NULL, "header='%s'\n", line);
 
         err = process_line(h, line, s->line_count, new_location);
         if (err < 0)
@@ -330,7 +388,7 @@ static int http_read(URLContext *h, uint8_t *buf, int size)
 
                 s->chunksize = strtoll(line, NULL, 16);
 
-                dprintf(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
+                av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
 
                 if (!s->chunksize)
                     return 0;
@@ -347,7 +405,9 @@ static int http_read(URLContext *h, uint8_t *buf, int size)
         memcpy(buf, s->buf_ptr, len);
         s->buf_ptr += len;
     } else {
-        len = url_read(s->hd, buf, size);
+        if (!s->willclose && s->filesize >= 0 && s->off >= s->filesize)
+            return AVERROR_EOF;
+        len = ffurl_read(s->hd, buf, size);
     }
     if (len > 0) {
         s->off += len;
@@ -358,16 +418,16 @@ static int http_read(URLContext *h, uint8_t *buf, int size)
 }
 
 /* used only when posting data */
-static int http_write(URLContext *h, uint8_t *buf, int size)
+static int http_write(URLContext *h, const uint8_t *buf, int size)
 {
-    char temp[11];  /* 32-bit hex + CRLF + nul */
+    char temp[11] = "";  /* 32-bit hex + CRLF + nul */
     int ret;
     char crlf[] = "\r\n";
     HTTPContext *s = h->priv_data;
 
     if (s->chunksize == -1) {
-        /* headers are sent without any special encoding */
-        return url_write(s->hd, buf, size);
+        /* non-chunked data is sent without any special encoding */
+        return ffurl_write(s->hd, buf, size);
     }
 
     /* silently ignore zero-size data since chunk encoding that would
@@ -376,9 +436,9 @@ static int http_write(URLContext *h, uint8_t *buf, int size)
         /* upload data using chunked encoding */
         snprintf(temp, sizeof(temp), "%x\r\n", size);
 
-        if ((ret = url_write(s->hd, temp, strlen(temp))) < 0 ||
-            (ret = url_write(s->hd, buf, size)) < 0 ||
-            (ret = url_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
+        if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
+            (ret = ffurl_write(s->hd, buf, size)) < 0 ||
+            (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
             return ret;
     }
     return size;
@@ -391,13 +451,13 @@ static int http_close(URLContext *h)
     HTTPContext *s = h->priv_data;
 
     /* signal end of chunked encoding if used */
-    if ((h->flags & URL_WRONLY) && s->chunksize != -1) {
-        ret = url_write(s->hd, footer, sizeof(footer) - 1);
+    if ((h->flags & AVIO_WRONLY) && s->chunksize != -1) {
+        ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
         ret = ret > 0 ? 0 : ret;
     }
 
-    url_close(s->hd);
-    av_free(s);
+    if (s->hd)
+        ffurl_close(s->hd);
     return ret;
 }
 
@@ -433,7 +493,7 @@ static int64_t http_seek(URLContext *h, int64_t off, int whence)
         s->off = old_off;
         return -1;
     }
-    url_close(old_hd);
+    ffurl_close(old_hd);
     return off;
 }
 
@@ -441,15 +501,17 @@ static int
 http_get_file_handle(URLContext *h)
 {
     HTTPContext *s = h->priv_data;
-    return url_get_file_handle(s->hd);
+    return ffurl_get_file_handle(s->hd);
 }
 
-URLProtocol http_protocol = {
-    "http",
-    http_open,
-    http_read,
-    http_write,
-    http_seek,
-    http_close,
+URLProtocol ff_http_protocol = {
+    .name                = "http",
+    .url_open            = http_open,
+    .url_read            = http_read,
+    .url_write           = http_write,
+    .url_seek            = http_seek,
+    .url_close           = http_close,
     .url_get_file_handle = http_get_file_handle,
+    .priv_data_size      = sizeof(HTTPContext),
+    .priv_data_class     = &httpcontext_class,
 };
diff --git a/libavformat/http.h b/libavformat/http.h
new file mode 100644
index 0000000..c5ff5e1
--- /dev/null
+++ b/libavformat/http.h
@@ -0,0 +1,64 @@
+/*
+ * HTTP definitions
+ * Copyright (c) 2010 Josh Allmann
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVFORMAT_HTTP_H
+#define AVFORMAT_HTTP_H
+
+#include "url.h"
+
+/**
+ * Set custom HTTP headers.
+ * A trailing CRLF ("\r\n") is required for custom headers.
+ * Passing in an empty header string ("\0") will reset to defaults.
+ *
+ * The following headers can be overriden by custom values,
+ * otherwise they will be set to their defaults.
+ *  -User-Agent
+ *  -Accept
+ *  -Range
+ *  -Host
+ *  -Connection
+ *
+ * @param h URL context for this HTTP connection
+ * @param headers the custom headers to set
+ */
+void ff_http_set_headers(URLContext *h, const char *headers);
+
+/**
+ * Enable or disable chunked transfer encoding. (default is enabled)
+ *
+ * @param h URL context for this HTTP connection
+ * @param is_chunked 0 to disable chunking, nonzero otherwise.
+ */
+void ff_http_set_chunked_transfer_encoding(URLContext *h, int is_chunked);
+
+/**
+ * Initialize the authentication state based on another HTTP URLContext.
+ * This can be used to pre-initialize the authentication parameters if
+ * they are known beforehand, to avoid having to do an initial failing
+ * request just to get the parameters.
+ *
+ * @param dest URL context whose authentication state gets updated
+ * @param src URL context whose authentication state gets copied
+ */
+void ff_http_init_auth_state(URLContext *dest, const URLContext *src);
+
+#endif /* AVFORMAT_HTTP_H */
diff --git a/libavformat/httpauth.c b/libavformat/httpauth.c
index cef2756..1dda1ac 100644
--- a/libavformat/httpauth.c
+++ b/libavformat/httpauth.c
@@ -2,20 +2,20 @@
  * HTTP authentication
  * Copyright (c) 2010 Martin Storsjo
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -28,62 +28,6 @@
 #include "avformat.h"
 #include <ctype.h>
 
-static void parse_key_value(const char *params,
-                            void (*callback_get_buf)(HTTPAuthState *state,
-                            const char *key, int key_len,
-                            char **dest, int *dest_len), HTTPAuthState *state)
-{
-    const char *ptr = params;
-
-    /* Parse key=value pairs. */
-    for (;;) {
-        const char *key;
-        char *dest = NULL, *dest_end;
-        int key_len, dest_len = 0;
-
-        /* Skip whitespace and potential commas. */
-        while (*ptr && (isspace(*ptr) || *ptr == ','))
-            ptr++;
-        if (!*ptr)
-            break;
-
-        key = ptr;
-
-        if (!(ptr = strchr(key, '=')))
-            break;
-        ptr++;
-        key_len = ptr - key;
-
-        callback_get_buf(state, key, key_len, &dest, &dest_len);
-        dest_end = dest + dest_len - 1;
-
-        if (*ptr == '\"') {
-            ptr++;
-            while (*ptr && *ptr != '\"') {
-                if (*ptr == '\\') {
-                    if (!ptr[1])
-                        break;
-                    if (dest && dest < dest_end)
-                        *dest++ = ptr[1];
-                    ptr += 2;
-                } else {
-                    if (dest && dest < dest_end)
-                        *dest++ = *ptr;
-                    ptr++;
-                }
-            }
-            if (*ptr == '\"')
-                ptr++;
-        } else {
-            for (; *ptr && !(isspace(*ptr) || *ptr == ','); ptr++)
-                if (dest && dest < dest_end)
-                    *dest++ = *ptr;
-        }
-        if (dest)
-            *dest = 0;
-    }
-}
-
 static void handle_basic_params(HTTPAuthState *state, const char *key,
                                 int key_len, char **dest, int *dest_len)
 {
@@ -149,18 +93,21 @@ void ff_http_auth_handle_header(HTTPAuthState *state, const char *key,
             state->auth_type <= HTTP_AUTH_BASIC) {
             state->auth_type = HTTP_AUTH_BASIC;
             state->realm[0] = 0;
-            parse_key_value(p, handle_basic_params, state);
+            ff_parse_key_value(p, (ff_parse_key_val_cb) handle_basic_params,
+                               state);
         } else if (av_stristart(value, "Digest ", &p) &&
                    state->auth_type <= HTTP_AUTH_DIGEST) {
             state->auth_type = HTTP_AUTH_DIGEST;
             memset(&state->digest_params, 0, sizeof(DigestParams));
             state->realm[0] = 0;
-            parse_key_value(p, handle_digest_params, state);
+            ff_parse_key_value(p, (ff_parse_key_val_cb) handle_digest_params,
+                               state);
             choose_qop(state->digest_params.qop,
                        sizeof(state->digest_params.qop));
         }
     } else if (!strcmp(key, "Authentication-Info")) {
-        parse_key_value(value, handle_digest_update, state);
+        ff_parse_key_value(value, (ff_parse_key_val_cb) handle_digest_update,
+                           state);
     }
 }
 
@@ -200,7 +147,7 @@ static char *make_digest_auth(HTTPAuthState *state, const char *username,
 
     /* Generate a client nonce. */
     for (i = 0; i < 2; i++)
-        cnonce_buf[i] = ff_random_get_seed();
+        cnonce_buf[i] = av_get_random_seed();
     ff_data_to_hex(cnonce, (const uint8_t*) cnonce_buf, sizeof(cnonce_buf), 1);
     cnonce[2*sizeof(cnonce_buf)] = 0;
 
@@ -294,7 +241,7 @@ char *ff_http_auth_create_response(HTTPAuthState *state, const char *auth,
         return NULL;
 
     if (state->auth_type == HTTP_AUTH_BASIC) {
-        int auth_b64_len = (strlen(auth) + 2) / 3 * 4 + 1;
+        int auth_b64_len = AV_BASE64_SIZE(strlen(auth));
         int len = auth_b64_len + 30;
         char *ptr;
         authstr = av_malloc(len);
@@ -303,7 +250,7 @@ char *ff_http_auth_create_response(HTTPAuthState *state, const char *auth,
         snprintf(authstr, len, "Authorization: Basic ");
         ptr = authstr + strlen(authstr);
         av_base64_encode(ptr, auth_b64_len, auth, strlen(auth));
-        av_strlcat(ptr, "\r\n", len);
+        av_strlcat(ptr, "\r\n", len - (ptr - authstr));
     } else if (state->auth_type == HTTP_AUTH_DIGEST) {
         char *username = av_strdup(auth), *password;
 
diff --git a/libavformat/httpauth.h b/libavformat/httpauth.h
index ebab3fc..d2a4a55 100644
--- a/libavformat/httpauth.h
+++ b/libavformat/httpauth.h
@@ -2,20 +2,20 @@
  * HTTP authentication
  * Copyright (c) 2010 Martin Storsjo
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavformat/id3v1.c b/libavformat/id3v1.c
index c72fca4..d296ebb 100644
--- a/libavformat/id3v1.c
+++ b/libavformat/id3v1.c
@@ -2,26 +2,25 @@
  * ID3v1 header parser
  * Copyright (c) 2003 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "id3v1.h"
 #include "libavcodec/avcodec.h"
-#include "libavutil/avstring.h"
 
 const char * const ff_id3v1_genre_str[ID3v1_GENRE_MAX + 1] = {
       [0] = "Blues",
@@ -202,6 +201,7 @@ static void get_string(AVFormatContext *s, const char *key,
  */
 static int parse_tag(AVFormatContext *s, const uint8_t *buf)
 {
+    char str[5];
     int genre;
 
     if (!(buf[0] == 'T' &&
@@ -213,8 +213,10 @@ static int parse_tag(AVFormatContext *s, const uint8_t *buf)
     get_string(s, "album",   buf + 63, 30);
     get_string(s, "date",    buf + 93,  4);
     get_string(s, "comment", buf + 97, 30);
-    if (buf[125] == 0 && buf[126] != 0)
-        av_metadata_set2(&s->metadata, "track", av_d2str(buf[126]), AV_METADATA_DONT_STRDUP_VAL);
+    if (buf[125] == 0 && buf[126] != 0) {
+        snprintf(str, sizeof(str), "%d", buf[126]);
+        av_metadata_set2(&s->metadata, "track", str, 0);
+    }
     genre = buf[127];
     if (genre <= ID3v1_GENRE_MAX)
         av_metadata_set2(&s->metadata, "genre", ff_id3v1_genre_str[genre], 0);
@@ -223,19 +225,20 @@ static int parse_tag(AVFormatContext *s, const uint8_t *buf)
 
 void ff_id3v1_read(AVFormatContext *s)
 {
-    int ret, filesize;
+    int ret;
     uint8_t buf[ID3v1_TAG_SIZE];
+    int64_t filesize, position = avio_tell(s->pb);
 
-    if (!url_is_streamed(s->pb)) {
+    if (s->pb->seekable) {
         /* XXX: change that */
-        filesize = url_fsize(s->pb);
+        filesize = avio_size(s->pb);
         if (filesize > 128) {
-            url_fseek(s->pb, filesize - 128, SEEK_SET);
-            ret = get_buffer(s->pb, buf, ID3v1_TAG_SIZE);
+            avio_seek(s->pb, filesize - 128, SEEK_SET);
+            ret = avio_read(s->pb, buf, ID3v1_TAG_SIZE);
             if (ret == ID3v1_TAG_SIZE) {
                 parse_tag(s, buf);
             }
-            url_fseek(s->pb, 0, SEEK_SET);
+            avio_seek(s->pb, position, SEEK_SET);
         }
     }
 }
diff --git a/libavformat/id3v1.h b/libavformat/id3v1.h
index 8eb58be..4842f16 100644
--- a/libavformat/id3v1.h
+++ b/libavformat/id3v1.h
@@ -2,20 +2,20 @@
  * ID3v1 header parser
  * Copyright (c) 2003 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavformat/id3v2.c b/libavformat/id3v2.c
index 6fa11db..4fecffe 100644
--- a/libavformat/id3v2.c
+++ b/libavformat/id3v2.c
@@ -2,32 +2,35 @@
  * ID3v2 header parser
  * Copyright (c) 2003 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "id3v2.h"
 #include "id3v1.h"
 #include "libavutil/avstring.h"
+#include "libavutil/intreadwrite.h"
+#include "metadata.h"
+#include "avio_internal.h"
 
-int ff_id3v2_match(const uint8_t *buf)
+int ff_id3v2_match(const uint8_t *buf, const char * magic)
 {
-    return  buf[0]         ==  'I' &&
-            buf[1]         ==  'D' &&
-            buf[2]         ==  '3' &&
+    return  buf[0]         == magic[0] &&
+            buf[1]         == magic[1] &&
+            buf[2]         == magic[2] &&
             buf[3]         != 0xff &&
             buf[4]         != 0xff &&
            (buf[6] & 0x80) ==    0 &&
@@ -48,41 +51,21 @@ int ff_id3v2_tag_len(const uint8_t * buf)
     return len;
 }
 
-void ff_id3v2_read(AVFormatContext *s)
-{
-    int len, ret;
-    uint8_t buf[ID3v2_HEADER_SIZE];
-
-    ret = get_buffer(s->pb, buf, ID3v2_HEADER_SIZE);
-    if (ret != ID3v2_HEADER_SIZE)
-        return;
-    if (ff_id3v2_match(buf)) {
-        /* parse ID3v2 header */
-        len = ((buf[6] & 0x7f) << 21) |
-            ((buf[7] & 0x7f) << 14) |
-            ((buf[8] & 0x7f) << 7) |
-            (buf[9] & 0x7f);
-        ff_id3v2_parse(s, len, buf[3], buf[5]);
-    } else {
-        url_fseek(s->pb, 0, SEEK_SET);
-    }
-}
-
-static unsigned int get_size(ByteIOContext *s, int len)
+static unsigned int get_size(AVIOContext *s, int len)
 {
     int v = 0;
     while (len--)
-        v = (v << 7) + (get_byte(s) & 0x7F);
+        v = (v << 7) + (avio_r8(s) & 0x7F);
     return v;
 }
 
-static void read_ttag(AVFormatContext *s, int taglen, const char *key)
+static void read_ttag(AVFormatContext *s, AVIOContext *pb, int taglen, const char *key)
 {
     char *q, dst[512];
     const char *val = NULL;
     int len, dstlen = sizeof(dst) - 1;
     unsigned genre;
-    unsigned int (*get)(ByteIOContext*) = get_be16;
+    unsigned int (*get)(AVIOContext*) = avio_rb16;
 
     dst[0] = 0;
     if (taglen < 1)
@@ -90,22 +73,22 @@ static void read_ttag(AVFormatContext *s, int taglen, const char *key)
 
     taglen--; /* account for encoding type byte */
 
-    switch (get_byte(s->pb)) { /* encoding type */
+    switch (avio_r8(pb)) { /* encoding type */
 
-    case 0:  /* ISO-8859-1 (0 - 255 maps directly into unicode) */
+    case ID3v2_ENCODING_ISO8859:
         q = dst;
         while (taglen-- && q - dst < dstlen - 7) {
             uint8_t tmp;
-            PUT_UTF8(get_byte(s->pb), tmp, *q++ = tmp;)
+            PUT_UTF8(avio_r8(pb), tmp, *q++ = tmp;)
         }
         *q = 0;
         break;
 
-    case 1:  /* UTF-16 with BOM */
+    case ID3v2_ENCODING_UTF16BOM:
         taglen -= 2;
-        switch (get_be16(s->pb)) {
+        switch (avio_rb16(pb)) {
         case 0xfffe:
-            get = get_le16;
+            get = avio_rl16;
         case 0xfeff:
             break;
         default:
@@ -114,25 +97,25 @@ static void read_ttag(AVFormatContext *s, int taglen, const char *key)
         }
         // fall-through
 
-    case 2:  /* UTF-16BE without BOM */
+    case ID3v2_ENCODING_UTF16BE:
         q = dst;
         while (taglen > 1 && q - dst < dstlen - 7) {
             uint32_t ch;
             uint8_t tmp;
 
-            GET_UTF16(ch, ((taglen -= 2) >= 0 ? get(s->pb) : 0), break;)
+            GET_UTF16(ch, ((taglen -= 2) >= 0 ? get(pb) : 0), break;)
             PUT_UTF8(ch, tmp, *q++ = tmp;)
         }
         *q = 0;
         break;
 
-    case 3:  /* UTF-8 */
+    case ID3v2_ENCODING_UTF8:
         len = FFMIN(taglen, dstlen);
-        get_buffer(s->pb, dst, len);
+        avio_read(pb, dst, len);
         dst[len] = 0;
         break;
     default:
-        av_log(s, AV_LOG_WARNING, "Unknown encoding in tag %s\n.", key);
+        av_log(s, AV_LOG_WARNING, "Unknown encoding in tag %s.\n", key);
     }
 
     if (!(strcmp(key, "TCON") && strcmp(key, "TCO"))
@@ -150,16 +133,65 @@ static void read_ttag(AVFormatContext *s, int taglen, const char *key)
         val = dst;
 
     if (val)
-        av_metadata_set2(&s->metadata, key, val, 0);
+        av_metadata_set2(&s->metadata, key, val, AV_METADATA_DONT_OVERWRITE);
+}
+
+static int is_number(const char *str)
+{
+    while (*str >= '0' && *str <= '9') str++;
+    return !*str;
 }
 
-void ff_id3v2_parse(AVFormatContext *s, int len, uint8_t version, uint8_t flags)
+static AVMetadataTag* get_date_tag(AVMetadata *m, const char *tag)
 {
-    int isv34, tlen;
+    AVMetadataTag *t;
+    if ((t = av_metadata_get(m, tag, NULL, AV_METADATA_MATCH_CASE)) &&
+        strlen(t->value) == 4 && is_number(t->value))
+        return t;
+    return NULL;
+}
+
+static void merge_date(AVMetadata **m)
+{
+    AVMetadataTag *t;
+    char date[17] = {0};      // YYYY-MM-DD hh:mm
+
+    if (!(t = get_date_tag(*m, "TYER")) &&
+        !(t = get_date_tag(*m, "TYE")))
+        return;
+    av_strlcpy(date, t->value, 5);
+    av_metadata_set2(m, "TYER", NULL, 0);
+    av_metadata_set2(m, "TYE",  NULL, 0);
+
+    if (!(t = get_date_tag(*m, "TDAT")) &&
+        !(t = get_date_tag(*m, "TDA")))
+        goto finish;
+    snprintf(date + 4, sizeof(date) - 4, "-%.2s-%.2s", t->value + 2, t->value);
+    av_metadata_set2(m, "TDAT", NULL, 0);
+    av_metadata_set2(m, "TDA",  NULL, 0);
+
+    if (!(t = get_date_tag(*m, "TIME")) &&
+        !(t = get_date_tag(*m, "TIM")))
+        goto finish;
+    snprintf(date + 10, sizeof(date) - 10, " %.2s:%.2s", t->value, t->value + 2);
+    av_metadata_set2(m, "TIME", NULL, 0);
+    av_metadata_set2(m, "TIM",  NULL, 0);
+
+finish:
+    if (date[0])
+        av_metadata_set2(m, "date", date, 0);
+}
+
+static void ff_id3v2_parse(AVFormatContext *s, int len, uint8_t version, uint8_t flags)
+{
+    int isv34, tlen, unsync;
     char tag[5];
-    int64_t next;
+    int64_t next, end = avio_tell(s->pb) + len;
     int taghdrlen;
-    const char *reason;
+    const char *reason = NULL;
+    AVIOContext pb;
+    unsigned char *buffer = NULL;
+    int buffer_size = 0;
 
     switch (version) {
     case 2:
@@ -182,92 +214,169 @@ void ff_id3v2_parse(AVFormatContext *s, int len, uint8_t version, uint8_t flags)
         goto error;
     }
 
-    if (flags & 0x80) {
-        reason = "unsynchronization";
-        goto error;
-    }
+    unsync = flags & 0x80;
 
     if (isv34 && flags & 0x40) /* Extended header present, just skip over it */
-        url_fskip(s->pb, get_size(s->pb, 4));
+        avio_skip(s->pb, get_size(s->pb, 4));
 
     while (len >= taghdrlen) {
+        unsigned int tflags;
+        int tunsync = 0;
+
         if (isv34) {
-            get_buffer(s->pb, tag, 4);
+            avio_read(s->pb, tag, 4);
             tag[4] = 0;
             if(version==3){
-                tlen = get_be32(s->pb);
+                tlen = avio_rb32(s->pb);
             }else
                 tlen = get_size(s->pb, 4);
-            get_be16(s->pb); /* flags */
+            tflags = avio_rb16(s->pb);
+            tunsync = tflags & ID3v2_FLAG_UNSYNCH;
         } else {
-            get_buffer(s->pb, tag, 3);
+            avio_read(s->pb, tag, 3);
             tag[3] = 0;
-            tlen = get_be24(s->pb);
+            tlen = avio_rb24(s->pb);
         }
-        len -= taghdrlen + tlen;
-
-        if (len < 0)
+        if (tlen < 0 || tlen > len - taghdrlen) {
+            av_log(s, AV_LOG_WARNING, "Invalid size in frame %s, skipping the rest of tag.\n", tag);
             break;
+        }
+        len -= taghdrlen + tlen;
+        next = avio_tell(s->pb) + tlen;
 
-        next = url_ftell(s->pb) + tlen;
+        if (tflags & ID3v2_FLAG_DATALEN) {
+            avio_rb32(s->pb);
+            tlen -= 4;
+        }
 
-        if (tag[0] == 'T')
-            read_ttag(s, tlen, tag);
+        if (tflags & (ID3v2_FLAG_ENCRYPTION | ID3v2_FLAG_COMPRESSION)) {
+            av_log(s, AV_LOG_WARNING, "Skipping encrypted/compressed ID3v2 frame %s.\n", tag);
+            avio_skip(s->pb, tlen);
+        } else if (tag[0] == 'T') {
+            if (unsync || tunsync) {
+                int i, j;
+                av_fast_malloc(&buffer, &buffer_size, tlen);
+                for (i = 0, j = 0; i < tlen; i++, j++) {
+                    buffer[j] = avio_r8(s->pb);
+                    if (j > 0 && !buffer[j] && buffer[j - 1] == 0xff) {
+                        /* Unsynchronised byte, skip it */
+                        j--;
+                    }
+                }
+                ffio_init_context(&pb, buffer, j, 0, NULL, NULL, NULL, NULL);
+                read_ttag(s, &pb, j, tag);
+            } else {
+                read_ttag(s, s->pb, tlen, tag);
+            }
+        }
         else if (!tag[0]) {
             if (tag[1])
                 av_log(s, AV_LOG_WARNING, "invalid frame id, assuming padding");
-            url_fskip(s->pb, len);
+            avio_skip(s->pb, tlen);
             break;
         }
         /* Skip to end of tag */
-        url_fseek(s->pb, next, SEEK_SET);
+        avio_seek(s->pb, next, SEEK_SET);
     }
 
     if (version == 4 && flags & 0x10) /* Footer preset, always 10 bytes, skip over it */
-        url_fskip(s->pb, 10);
-    return;
+        end += 10;
 
   error:
-    av_log(s, AV_LOG_INFO, "ID3v2.%d tag skipped, cannot handle %s\n", version, reason);
-    url_fskip(s->pb, len);
+    if (reason)
+        av_log(s, AV_LOG_INFO, "ID3v2.%d tag skipped, cannot handle %s\n", version, reason);
+    avio_seek(s->pb, end, SEEK_SET);
+    av_free(buffer);
+    return;
 }
 
-const AVMetadataConv ff_id3v2_metadata_conv[] = {
+void ff_id3v2_read(AVFormatContext *s, const char *magic)
+{
+    int len, ret;
+    uint8_t buf[ID3v2_HEADER_SIZE];
+    int     found_header;
+    int64_t off;
+
+    do {
+        /* save the current offset in case there's nothing to read/skip */
+        off = avio_tell(s->pb);
+        ret = avio_read(s->pb, buf, ID3v2_HEADER_SIZE);
+        if (ret != ID3v2_HEADER_SIZE)
+            break;
+            found_header = ff_id3v2_match(buf, magic);
+            if (found_header) {
+            /* parse ID3v2 header */
+            len = ((buf[6] & 0x7f) << 21) |
+                  ((buf[7] & 0x7f) << 14) |
+                  ((buf[8] & 0x7f) << 7) |
+                   (buf[9] & 0x7f);
+            ff_id3v2_parse(s, len, buf[3], buf[5]);
+        } else {
+            avio_seek(s->pb, off, SEEK_SET);
+        }
+    } while (found_header);
+    ff_metadata_conv(&s->metadata, NULL, ff_id3v2_34_metadata_conv);
+    ff_metadata_conv(&s->metadata, NULL, ff_id3v2_2_metadata_conv);
+    ff_metadata_conv(&s->metadata, NULL, ff_id3v2_4_metadata_conv);
+    merge_date(&s->metadata);
+}
+
+const AVMetadataConv ff_id3v2_34_metadata_conv[] = {
     { "TALB", "album"},
-    { "TAL",  "album"},
     { "TCOM", "composer"},
     { "TCON", "genre"},
-    { "TCO",  "genre"},
     { "TCOP", "copyright"},
-    { "TDRL", "date"},
-    { "TDRC", "date"},
     { "TENC", "encoded_by"},
-    { "TEN",  "encoded_by"},
     { "TIT2", "title"},
-    { "TT2",  "title"},
     { "TLAN", "language"},
     { "TPE1", "artist"},
-    { "TP1",  "artist"},
     { "TPE2", "album_artist"},
-    { "TP2",  "album_artist"},
     { "TPE3", "performer"},
-    { "TP3",  "performer"},
     { "TPOS", "disc"},
     { "TPUB", "publisher"},
     { "TRCK", "track"},
-    { "TRK",  "track"},
+    { "TSSE", "encoder"},
+    { 0 }
+};
+
+const AVMetadataConv ff_id3v2_4_metadata_conv[] = {
+    { "TDRL", "date"},
+    { "TDRC", "date"},
+    { "TDEN", "creation_time"},
     { "TSOA", "album-sort"},
     { "TSOP", "artist-sort"},
     { "TSOT", "title-sort"},
-    { "TSSE", "encoder"},
     { 0 }
 };
 
+const AVMetadataConv ff_id3v2_2_metadata_conv[] = {
+    { "TAL",  "album"},
+    { "TCO",  "genre"},
+    { "TT2",  "title"},
+    { "TEN",  "encoded_by"},
+    { "TP1",  "artist"},
+    { "TP2",  "album_artist"},
+    { "TP3",  "performer"},
+    { "TRK",  "track"},
+    { 0 }
+};
+
+
 const char ff_id3v2_tags[][4] = {
-   "TALB", "TBPM", "TCOM", "TCON", "TCOP", "TDEN", "TDLY", "TDOR", "TDRC",
-   "TDRL", "TDTG", "TENC", "TEXT", "TFLT", "TIPL", "TIT1", "TIT2", "TIT3",
-   "TKEY", "TLAN", "TLEN", "TMCL", "TMED", "TMOO", "TOAL", "TOFN", "TOLY",
-   "TOPE", "TOWN", "TPE1", "TPE2", "TPE3", "TPE4", "TPOS", "TPRO", "TPUB",
-   "TRCK", "TRSN", "TRSO", "TSOA", "TSOP", "TSOT", "TSRC", "TSSE", "TSST",
+   "TALB", "TBPM", "TCOM", "TCON", "TCOP", "TDLY", "TENC", "TEXT",
+   "TFLT", "TIT1", "TIT2", "TIT3", "TKEY", "TLAN", "TLEN", "TMED",
+   "TOAL", "TOFN", "TOLY", "TOPE", "TOWN", "TPE1", "TPE2", "TPE3",
+   "TPE4", "TPOS", "TPUB", "TRCK", "TRSN", "TRSO", "TSRC", "TSSE",
+   { 0 },
+};
+
+const char ff_id3v2_4_tags[][4] = {
+   "TDEN", "TDOR", "TDRC", "TDRL", "TDTG", "TIPL", "TMCL", "TMOO",
+   "TPRO", "TSOA", "TSOP", "TSOT", "TSST",
+   { 0 },
+};
+
+const char ff_id3v2_3_tags[][4] = {
+   "TDAT", "TIME", "TORY", "TRDA", "TSIZ", "TYER",
    { 0 },
 };
diff --git a/libavformat/id3v2.h b/libavformat/id3v2.h
index 70030d2..3e0e65a 100644
--- a/libavformat/id3v2.h
+++ b/libavformat/id3v2.h
@@ -2,20 +2,20 @@
  * ID3v2 header parser
  * Copyright (c) 2003 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -29,35 +29,61 @@
 #define ID3v2_HEADER_SIZE 10
 
 /**
- * Detects ID3v2 Header.
- * @buf must be ID3v2_HEADER_SIZE byte long
+ * Default magic bytes for ID3v2 header: "ID3"
  */
-int ff_id3v2_match(const uint8_t *buf);
+#define ID3v2_DEFAULT_MAGIC "ID3"
+
+#define ID3v2_FLAG_DATALEN     0x0001
+#define ID3v2_FLAG_UNSYNCH     0x0002
+#define ID3v2_FLAG_ENCRYPTION  0x0004
+#define ID3v2_FLAG_COMPRESSION 0x0008
+
+enum ID3v2Encoding {
+    ID3v2_ENCODING_ISO8859  = 0,
+    ID3v2_ENCODING_UTF16BOM = 1,
+    ID3v2_ENCODING_UTF16BE  = 2,
+    ID3v2_ENCODING_UTF8     = 3,
+};
 
 /**
- * Gets the length of an ID3v2 tag.
- * @buf must be ID3v2_HEADER_SIZE bytes long and point to the start of an
- * already detected ID3v2 tag
+ * Detect ID3v2 Header.
+ * @param buf   must be ID3v2_HEADER_SIZE byte long
+ * @param magic magic bytes to identify the header, machine byte order.
+ * If in doubt, use ID3v2_DEFAULT_MAGIC.
  */
-int ff_id3v2_tag_len(const uint8_t *buf);
+int ff_id3v2_match(const uint8_t *buf, const char *magic);
 
 /**
- * ID3v2 parser
- * Handles ID3v2.2, 2.3 and 2.4.
+ * Get the length of an ID3v2 tag.
+ * @param buf must be ID3v2_HEADER_SIZE bytes long and point to the start of an
+ * already detected ID3v2 tag
  */
-void ff_id3v2_parse(AVFormatContext *s, int len, uint8_t version, uint8_t flags);
+int ff_id3v2_tag_len(const uint8_t *buf);
 
 /**
  * Read an ID3v2 tag
  */
-void ff_id3v2_read(AVFormatContext *s);
+void ff_id3v2_read(AVFormatContext *s, const char *magic);
 
-extern const AVMetadataConv ff_id3v2_metadata_conv[];
+extern const AVMetadataConv ff_id3v2_34_metadata_conv[];
+extern const AVMetadataConv ff_id3v2_4_metadata_conv[];
+extern const AVMetadataConv ff_id3v2_2_metadata_conv[];
 
 /**
- * A list of ID3v2.4 text information frames.
+ * A list of text information frames allowed in both ID3 v2.3 and v2.4
  * http://www.id3.org/id3v2.4.0-frames
+ * http://www.id3.org/id3v2.4.0-changes
  */
 extern const char ff_id3v2_tags[][4];
 
+/**
+ * ID3v2.4-only text information frames.
+ */
+extern const char ff_id3v2_4_tags[][4];
+
+/**
+ * ID3v2.3-only text information frames.
+ */
+extern const char ff_id3v2_3_tags[][4];
+
 #endif /* AVFORMAT_ID3V2_H */
diff --git a/libavformat/idcin.c b/libavformat/idcin.c
index cd4ebf8..04ae687 100644
--- a/libavformat/idcin.c
+++ b/libavformat/idcin.c
@@ -2,20 +2,20 @@
  * id Quake II CIN File Demuxer
  * Copyright (c) 2003 The ffmpeg Project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -86,8 +86,6 @@ typedef struct IdcinDemuxContext {
     int audio_present;
 
     int64_t pts;
-
-    AVPaletteControl palctrl;
 } IdcinDemuxContext;
 
 static int idcin_probe(AVProbeData *p)
@@ -142,18 +140,18 @@ static int idcin_probe(AVProbeData *p)
 static int idcin_read_header(AVFormatContext *s,
                              AVFormatParameters *ap)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     IdcinDemuxContext *idcin = s->priv_data;
     AVStream *st;
     unsigned int width, height;
     unsigned int sample_rate, bytes_per_sample, channels;
 
     /* get the 5 header parameters */
-    width = get_le32(pb);
-    height = get_le32(pb);
-    sample_rate = get_le32(pb);
-    bytes_per_sample = get_le32(pb);
-    channels = get_le32(pb);
+    width = avio_rl32(pb);
+    height = avio_rl32(pb);
+    sample_rate = avio_rl32(pb);
+    bytes_per_sample = avio_rl32(pb);
+    channels = avio_rl32(pb);
 
     st = av_new_stream(s, 0);
     if (!st)
@@ -169,11 +167,9 @@ static int idcin_read_header(AVFormatContext *s,
     /* load up the Huffman tables into extradata */
     st->codec->extradata_size = HUFFMAN_TABLE_SIZE;
     st->codec->extradata = av_malloc(HUFFMAN_TABLE_SIZE);
-    if (get_buffer(pb, st->codec->extradata, HUFFMAN_TABLE_SIZE) !=
+    if (avio_read(pb, st->codec->extradata, HUFFMAN_TABLE_SIZE) !=
         HUFFMAN_TABLE_SIZE)
         return AVERROR(EIO);
-    /* save a reference in order to transport the palette */
-    st->codec->palctrl = &idcin->palctrl;
 
     /* if sample rate is 0, assume no audio */
     if (sample_rate) {
@@ -221,23 +217,23 @@ static int idcin_read_packet(AVFormatContext *s,
     unsigned int command;
     unsigned int chunk_size;
     IdcinDemuxContext *idcin = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int i;
     int palette_scale;
     unsigned char r, g, b;
     unsigned char palette_buffer[768];
+    uint32_t palette[256];
 
-    if (url_feof(s->pb))
+    if (s->pb->eof_reached)
         return AVERROR(EIO);
 
     if (idcin->next_chunk_is_video) {
-        command = get_le32(pb);
+        command = avio_rl32(pb);
         if (command == 2) {
             return AVERROR(EIO);
         } else if (command == 1) {
             /* trigger a palette change */
-            idcin->palctrl.palette_changed = 1;
-            if (get_buffer(pb, palette_buffer, 768) != 768)
+            if (avio_read(pb, palette_buffer, 768) != 768)
                 return AVERROR(EIO);
             /* scale the palette as necessary */
             palette_scale = 2;
@@ -251,17 +247,26 @@ static int idcin_read_packet(AVFormatContext *s,
                 r = palette_buffer[i * 3    ] << palette_scale;
                 g = palette_buffer[i * 3 + 1] << palette_scale;
                 b = palette_buffer[i * 3 + 2] << palette_scale;
-                idcin->palctrl.palette[i] = (r << 16) | (g << 8) | (b);
+                palette[i] = (r << 16) | (g << 8) | (b);
             }
         }
 
-        chunk_size = get_le32(pb);
+        chunk_size = avio_rl32(pb);
         /* skip the number of decoded bytes (always equal to width * height) */
-        url_fseek(pb, 4, SEEK_CUR);
+        avio_skip(pb, 4);
         chunk_size -= 4;
         ret= av_get_packet(pb, pkt, chunk_size);
         if (ret < 0)
             return ret;
+        if (command == 1) {
+            uint8_t *pal;
+
+            pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE,
+                                          AVPALETTE_SIZE);
+            if (ret < 0)
+                return ret;
+            memcpy(pal, palette, AVPALETTE_SIZE);
+        }
         pkt->stream_index = idcin->video_stream_index;
         pkt->pts = idcin->pts;
     } else {
@@ -286,7 +291,7 @@ static int idcin_read_packet(AVFormatContext *s,
     return ret;
 }
 
-AVInputFormat idcin_demuxer = {
+AVInputFormat ff_idcin_demuxer = {
     "idcin",
     NULL_IF_CONFIG_SMALL("id Cinematic format"),
     sizeof(IdcinDemuxContext),
diff --git a/libavformat/idroq.c b/libavformat/idroq.c
deleted file mode 100644
index 6b036d9..0000000
--- a/libavformat/idroq.c
+++ /dev/null
@@ -1,226 +0,0 @@
-/*
- * id RoQ (.roq) File Demuxer
- * Copyright (c) 2003 The ffmpeg Project
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-/**
- * @file
- * id RoQ format file demuxer
- * by Mike Melanson (melanson at pcisys.net)
- * for more information on the .roq file format, visit:
- *   http://www.csse.monash.edu.au/~timf/
- */
-
-#include "libavutil/intreadwrite.h"
-#include "avformat.h"
-
-#define RoQ_MAGIC_NUMBER 0x1084
-#define RoQ_CHUNK_PREAMBLE_SIZE 8
-#define RoQ_AUDIO_SAMPLE_RATE 22050
-#define RoQ_CHUNKS_TO_SCAN 30
-
-#define RoQ_INFO           0x1001
-#define RoQ_QUAD_CODEBOOK  0x1002
-#define RoQ_QUAD_VQ        0x1011
-#define RoQ_SOUND_MONO     0x1020
-#define RoQ_SOUND_STEREO   0x1021
-
-typedef struct RoqDemuxContext {
-
-    int width;
-    int height;
-    int audio_channels;
-
-    int video_stream_index;
-    int audio_stream_index;
-
-    int64_t video_pts;
-    unsigned int audio_frame_count;
-
-} RoqDemuxContext;
-
-static int roq_probe(AVProbeData *p)
-{
-    if ((AV_RL16(&p->buf[0]) != RoQ_MAGIC_NUMBER) ||
-        (AV_RL32(&p->buf[2]) != 0xFFFFFFFF))
-        return 0;
-
-    return AVPROBE_SCORE_MAX;
-}
-
-static int roq_read_header(AVFormatContext *s,
-                           AVFormatParameters *ap)
-{
-    RoqDemuxContext *roq = s->priv_data;
-    ByteIOContext *pb = s->pb;
-    int framerate;
-    AVStream *st;
-    unsigned char preamble[RoQ_CHUNK_PREAMBLE_SIZE];
-
-    /* get the main header */
-    if (get_buffer(pb, preamble, RoQ_CHUNK_PREAMBLE_SIZE) !=
-        RoQ_CHUNK_PREAMBLE_SIZE)
-        return AVERROR(EIO);
-    framerate = AV_RL16(&preamble[6]);
-
-    /* init private context parameters */
-    roq->width = roq->height = roq->audio_channels = roq->video_pts =
-    roq->audio_frame_count = 0;
-    roq->audio_stream_index = -1;
-
-    st = av_new_stream(s, 0);
-    if (!st)
-        return AVERROR(ENOMEM);
-    av_set_pts_info(st, 63, 1, framerate);
-    roq->video_stream_index = st->index;
-    st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
-    st->codec->codec_id = CODEC_ID_ROQ;
-    st->codec->codec_tag = 0;  /* no fourcc */
-
-    return 0;
-}
-
-static int roq_read_packet(AVFormatContext *s,
-                           AVPacket *pkt)
-{
-    RoqDemuxContext *roq = s->priv_data;
-    ByteIOContext *pb = s->pb;
-    int ret = 0;
-    unsigned int chunk_size;
-    unsigned int chunk_type;
-    unsigned int codebook_size;
-    unsigned char preamble[RoQ_CHUNK_PREAMBLE_SIZE];
-    int packet_read = 0;
-    int64_t codebook_offset;
-
-    while (!packet_read) {
-
-        if (url_feof(s->pb))
-            return AVERROR(EIO);
-
-        /* get the next chunk preamble */
-        if ((ret = get_buffer(pb, preamble, RoQ_CHUNK_PREAMBLE_SIZE)) !=
-            RoQ_CHUNK_PREAMBLE_SIZE)
-            return AVERROR(EIO);
-
-        chunk_type = AV_RL16(&preamble[0]);
-        chunk_size = AV_RL32(&preamble[2]);
-        if(chunk_size > INT_MAX)
-            return AVERROR_INVALIDDATA;
-
-        switch (chunk_type) {
-
-        case RoQ_INFO:
-            if (!roq->width || !roq->height) {
-                AVStream *st = s->streams[roq->video_stream_index];
-                if (get_buffer(pb, preamble, RoQ_CHUNK_PREAMBLE_SIZE) != RoQ_CHUNK_PREAMBLE_SIZE)
-                    return AVERROR(EIO);
-                st->codec->width  = roq->width  = AV_RL16(preamble);
-                st->codec->height = roq->height = AV_RL16(preamble + 2);
-                break;
-            }
-            /* don't care about this chunk anymore */
-            url_fseek(pb, RoQ_CHUNK_PREAMBLE_SIZE, SEEK_CUR);
-            break;
-
-        case RoQ_QUAD_CODEBOOK:
-            /* packet needs to contain both this codebook and next VQ chunk */
-            codebook_offset = url_ftell(pb) - RoQ_CHUNK_PREAMBLE_SIZE;
-            codebook_size = chunk_size;
-            url_fseek(pb, codebook_size, SEEK_CUR);
-            if (get_buffer(pb, preamble, RoQ_CHUNK_PREAMBLE_SIZE) !=
-                RoQ_CHUNK_PREAMBLE_SIZE)
-                return AVERROR(EIO);
-            chunk_size = AV_RL32(&preamble[2]) + RoQ_CHUNK_PREAMBLE_SIZE * 2 +
-                codebook_size;
-
-            /* rewind */
-            url_fseek(pb, codebook_offset, SEEK_SET);
-
-            /* load up the packet */
-            ret= av_get_packet(pb, pkt, chunk_size);
-            if (ret != chunk_size)
-                return AVERROR(EIO);
-            pkt->stream_index = roq->video_stream_index;
-            pkt->pts = roq->video_pts++;
-
-            packet_read = 1;
-            break;
-
-        case RoQ_SOUND_MONO:
-        case RoQ_SOUND_STEREO:
-            if (roq->audio_stream_index == -1) {
-                AVStream *st = av_new_stream(s, 1);
-                if (!st)
-                    return AVERROR(ENOMEM);
-                av_set_pts_info(st, 32, 1, RoQ_AUDIO_SAMPLE_RATE);
-                roq->audio_stream_index = st->index;
-                st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
-                st->codec->codec_id = CODEC_ID_ROQ_DPCM;
-                st->codec->codec_tag = 0;  /* no tag */
-                st->codec->channels = roq->audio_channels = chunk_type == RoQ_SOUND_STEREO ? 2 : 1;
-                st->codec->sample_rate = RoQ_AUDIO_SAMPLE_RATE;
-                st->codec->bits_per_coded_sample = 16;
-                st->codec->bit_rate = st->codec->channels * st->codec->sample_rate *
-                    st->codec->bits_per_coded_sample;
-                st->codec->block_align = st->codec->channels * st->codec->bits_per_coded_sample;
-            }
-        case RoQ_QUAD_VQ:
-            /* load up the packet */
-            if (av_new_packet(pkt, chunk_size + RoQ_CHUNK_PREAMBLE_SIZE))
-                return AVERROR(EIO);
-            /* copy over preamble */
-            memcpy(pkt->data, preamble, RoQ_CHUNK_PREAMBLE_SIZE);
-
-            if (chunk_type == RoQ_QUAD_VQ) {
-                pkt->stream_index = roq->video_stream_index;
-                pkt->pts = roq->video_pts++;
-            } else {
-                pkt->stream_index = roq->audio_stream_index;
-                pkt->pts = roq->audio_frame_count;
-                roq->audio_frame_count += (chunk_size / roq->audio_channels);
-            }
-
-            pkt->pos= url_ftell(pb);
-            ret = get_buffer(pb, pkt->data + RoQ_CHUNK_PREAMBLE_SIZE,
-                chunk_size);
-            if (ret != chunk_size)
-                ret = AVERROR(EIO);
-
-            packet_read = 1;
-            break;
-
-        default:
-            av_log(s, AV_LOG_ERROR, "  unknown RoQ chunk (%04X)\n", chunk_type);
-            return AVERROR_INVALIDDATA;
-            break;
-        }
-    }
-
-    return ret;
-}
-
-AVInputFormat roq_demuxer = {
-    "RoQ",
-    NULL_IF_CONFIG_SMALL("id RoQ format"),
-    sizeof(RoqDemuxContext),
-    roq_probe,
-    roq_read_header,
-    roq_read_packet,
-};
diff --git a/libavformat/idroqdec.c b/libavformat/idroqdec.c
new file mode 100644
index 0000000..8e991c5
--- /dev/null
+++ b/libavformat/idroqdec.c
@@ -0,0 +1,226 @@
+/*
+ * id RoQ (.roq) File Demuxer
+ * Copyright (c) 2003 The ffmpeg Project
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * id RoQ format file demuxer
+ * by Mike Melanson (melanson at pcisys.net)
+ * for more information on the .roq file format, visit:
+ *   http://www.csse.monash.edu.au/~timf/
+ */
+
+#include "libavutil/intreadwrite.h"
+#include "avformat.h"
+
+#define RoQ_MAGIC_NUMBER 0x1084
+#define RoQ_CHUNK_PREAMBLE_SIZE 8
+#define RoQ_AUDIO_SAMPLE_RATE 22050
+#define RoQ_CHUNKS_TO_SCAN 30
+
+#define RoQ_INFO           0x1001
+#define RoQ_QUAD_CODEBOOK  0x1002
+#define RoQ_QUAD_VQ        0x1011
+#define RoQ_SOUND_MONO     0x1020
+#define RoQ_SOUND_STEREO   0x1021
+
+typedef struct RoqDemuxContext {
+
+    int width;
+    int height;
+    int audio_channels;
+
+    int video_stream_index;
+    int audio_stream_index;
+
+    int64_t video_pts;
+    unsigned int audio_frame_count;
+
+} RoqDemuxContext;
+
+static int roq_probe(AVProbeData *p)
+{
+    if ((AV_RL16(&p->buf[0]) != RoQ_MAGIC_NUMBER) ||
+        (AV_RL32(&p->buf[2]) != 0xFFFFFFFF))
+        return 0;
+
+    return AVPROBE_SCORE_MAX;
+}
+
+static int roq_read_header(AVFormatContext *s,
+                           AVFormatParameters *ap)
+{
+    RoqDemuxContext *roq = s->priv_data;
+    AVIOContext *pb = s->pb;
+    int framerate;
+    AVStream *st;
+    unsigned char preamble[RoQ_CHUNK_PREAMBLE_SIZE];
+
+    /* get the main header */
+    if (avio_read(pb, preamble, RoQ_CHUNK_PREAMBLE_SIZE) !=
+        RoQ_CHUNK_PREAMBLE_SIZE)
+        return AVERROR(EIO);
+    framerate = AV_RL16(&preamble[6]);
+
+    /* init private context parameters */
+    roq->width = roq->height = roq->audio_channels = roq->video_pts =
+    roq->audio_frame_count = 0;
+    roq->audio_stream_index = -1;
+
+    st = av_new_stream(s, 0);
+    if (!st)
+        return AVERROR(ENOMEM);
+    av_set_pts_info(st, 63, 1, framerate);
+    roq->video_stream_index = st->index;
+    st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
+    st->codec->codec_id = CODEC_ID_ROQ;
+    st->codec->codec_tag = 0;  /* no fourcc */
+
+    return 0;
+}
+
+static int roq_read_packet(AVFormatContext *s,
+                           AVPacket *pkt)
+{
+    RoqDemuxContext *roq = s->priv_data;
+    AVIOContext *pb = s->pb;
+    int ret = 0;
+    unsigned int chunk_size;
+    unsigned int chunk_type;
+    unsigned int codebook_size;
+    unsigned char preamble[RoQ_CHUNK_PREAMBLE_SIZE];
+    int packet_read = 0;
+    int64_t codebook_offset;
+
+    while (!packet_read) {
+
+        if (s->pb->eof_reached)
+            return AVERROR(EIO);
+
+        /* get the next chunk preamble */
+        if ((ret = avio_read(pb, preamble, RoQ_CHUNK_PREAMBLE_SIZE)) !=
+            RoQ_CHUNK_PREAMBLE_SIZE)
+            return AVERROR(EIO);
+
+        chunk_type = AV_RL16(&preamble[0]);
+        chunk_size = AV_RL32(&preamble[2]);
+        if(chunk_size > INT_MAX)
+            return AVERROR_INVALIDDATA;
+
+        switch (chunk_type) {
+
+        case RoQ_INFO:
+            if (!roq->width || !roq->height) {
+                AVStream *st = s->streams[roq->video_stream_index];
+                if (avio_read(pb, preamble, RoQ_CHUNK_PREAMBLE_SIZE) != RoQ_CHUNK_PREAMBLE_SIZE)
+                    return AVERROR(EIO);
+                st->codec->width  = roq->width  = AV_RL16(preamble);
+                st->codec->height = roq->height = AV_RL16(preamble + 2);
+                break;
+            }
+            /* don't care about this chunk anymore */
+            avio_skip(pb, RoQ_CHUNK_PREAMBLE_SIZE);
+            break;
+
+        case RoQ_QUAD_CODEBOOK:
+            /* packet needs to contain both this codebook and next VQ chunk */
+            codebook_offset = avio_tell(pb) - RoQ_CHUNK_PREAMBLE_SIZE;
+            codebook_size = chunk_size;
+            avio_skip(pb, codebook_size);
+            if (avio_read(pb, preamble, RoQ_CHUNK_PREAMBLE_SIZE) !=
+                RoQ_CHUNK_PREAMBLE_SIZE)
+                return AVERROR(EIO);
+            chunk_size = AV_RL32(&preamble[2]) + RoQ_CHUNK_PREAMBLE_SIZE * 2 +
+                codebook_size;
+
+            /* rewind */
+            avio_seek(pb, codebook_offset, SEEK_SET);
+
+            /* load up the packet */
+            ret= av_get_packet(pb, pkt, chunk_size);
+            if (ret != chunk_size)
+                return AVERROR(EIO);
+            pkt->stream_index = roq->video_stream_index;
+            pkt->pts = roq->video_pts++;
+
+            packet_read = 1;
+            break;
+
+        case RoQ_SOUND_MONO:
+        case RoQ_SOUND_STEREO:
+            if (roq->audio_stream_index == -1) {
+                AVStream *st = av_new_stream(s, 1);
+                if (!st)
+                    return AVERROR(ENOMEM);
+                av_set_pts_info(st, 32, 1, RoQ_AUDIO_SAMPLE_RATE);
+                roq->audio_stream_index = st->index;
+                st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
+                st->codec->codec_id = CODEC_ID_ROQ_DPCM;
+                st->codec->codec_tag = 0;  /* no tag */
+                st->codec->channels = roq->audio_channels = chunk_type == RoQ_SOUND_STEREO ? 2 : 1;
+                st->codec->sample_rate = RoQ_AUDIO_SAMPLE_RATE;
+                st->codec->bits_per_coded_sample = 16;
+                st->codec->bit_rate = st->codec->channels * st->codec->sample_rate *
+                    st->codec->bits_per_coded_sample;
+                st->codec->block_align = st->codec->channels * st->codec->bits_per_coded_sample;
+            }
+        case RoQ_QUAD_VQ:
+            /* load up the packet */
+            if (av_new_packet(pkt, chunk_size + RoQ_CHUNK_PREAMBLE_SIZE))
+                return AVERROR(EIO);
+            /* copy over preamble */
+            memcpy(pkt->data, preamble, RoQ_CHUNK_PREAMBLE_SIZE);
+
+            if (chunk_type == RoQ_QUAD_VQ) {
+                pkt->stream_index = roq->video_stream_index;
+                pkt->pts = roq->video_pts++;
+            } else {
+                pkt->stream_index = roq->audio_stream_index;
+                pkt->pts = roq->audio_frame_count;
+                roq->audio_frame_count += (chunk_size / roq->audio_channels);
+            }
+
+            pkt->pos= avio_tell(pb);
+            ret = avio_read(pb, pkt->data + RoQ_CHUNK_PREAMBLE_SIZE,
+                chunk_size);
+            if (ret != chunk_size)
+                ret = AVERROR(EIO);
+
+            packet_read = 1;
+            break;
+
+        default:
+            av_log(s, AV_LOG_ERROR, "  unknown RoQ chunk (%04X)\n", chunk_type);
+            return AVERROR_INVALIDDATA;
+            break;
+        }
+    }
+
+    return ret;
+}
+
+AVInputFormat ff_roq_demuxer = {
+    "RoQ",
+    NULL_IF_CONFIG_SMALL("id RoQ format"),
+    sizeof(RoqDemuxContext),
+    roq_probe,
+    roq_read_header,
+    roq_read_packet,
+};
diff --git a/libavformat/idroqenc.c b/libavformat/idroqenc.c
new file mode 100644
index 0000000..688d58d
--- /dev/null
+++ b/libavformat/idroqenc.c
@@ -0,0 +1,49 @@
+/*
+ * id RoQ (.roq) File muxer
+ * Copyright (c) 2007 Vitor Sessak
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "avformat.h"
+#include "rawenc.h"
+
+
+static int roq_write_header(struct AVFormatContext *s)
+{
+    static const uint8_t header[] = {
+        0x84, 0x10, 0xFF, 0xFF, 0xFF, 0xFF, 0x1E, 0x00
+    };
+
+    avio_write(s->pb, header, 8);
+    avio_flush(s->pb);
+
+    return 0;
+}
+
+AVOutputFormat ff_roq_muxer =
+{
+    "RoQ",
+    NULL_IF_CONFIG_SMALL("raw id RoQ format"),
+    NULL,
+    "roq",
+    0,
+    CODEC_ID_ROQ_DPCM,
+    CODEC_ID_ROQ,
+    roq_write_header,
+    ff_raw_write_packet,
+};
diff --git a/libavformat/iff.c b/libavformat/iff.c
index db74b8d..f9b5a77 100644
--- a/libavformat/iff.c
+++ b/libavformat/iff.c
@@ -4,20 +4,20 @@
  * Copyright (c) 2010 Peter Ross <pross at xvid.org>
  * Copyright (c) 2010 Sebastian Vater <cdgs.basty at googlemail.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -30,7 +30,6 @@
  */
 
 #include "libavutil/intreadwrite.h"
-#include "libavcodec/iff.h"
 #include "avformat.h"
 
 #define ID_8SVX       MKTAG('8','S','V','X')
@@ -92,6 +91,25 @@ static void interleave_stereo(const uint8_t *src, uint8_t *dest, int size)
     }
 }
 
+/* Metadata string read */
+static int get_metadata(AVFormatContext *s,
+                        const char *const tag,
+                        const unsigned data_size)
+{
+    uint8_t *buf = ((data_size + 1) == 0) ? NULL : av_malloc(data_size + 1);
+
+    if (!buf)
+        return AVERROR(ENOMEM);
+
+    if (avio_read(s->pb, buf, data_size) < 0) {
+        av_free(buf);
+        return AVERROR(EIO);
+    }
+    buf[data_size] = 0;
+    av_metadata_set2(&s->metadata, tag, buf, AV_METADATA_DONT_STRDUP_VAL);
+    return 0;
+}
+
 static int iff_probe(AVProbeData *p)
 {
     const uint8_t *d = p->buf;
@@ -106,26 +124,27 @@ static int iff_read_header(AVFormatContext *s,
                            AVFormatParameters *ap)
 {
     IffDemuxContext *iff = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVStream *st;
     uint32_t chunk_id, data_size;
     int compression = -1;
-    char *buf;
 
     st = av_new_stream(s, 0);
     if (!st)
         return AVERROR(ENOMEM);
 
     st->codec->channels = 1;
-    url_fskip(pb, 8);
+    avio_skip(pb, 8);
     // codec_tag used by ByteRun1 decoder to distinguish progressive (PBM) and interlaced (ILBM) content
-    st->codec->codec_tag = get_le32(pb);
+    st->codec->codec_tag = avio_rl32(pb);
 
-    while(!url_feof(pb)) {
+    while(!pb->eof_reached) {
         uint64_t orig_pos;
-        chunk_id = get_le32(pb);
-        data_size = get_be32(pb);
-        orig_pos = url_ftell(pb);
+        int res;
+        const char *metadata_tag = NULL;
+        chunk_id = avio_rl32(pb);
+        data_size = avio_rb32(pb);
+        orig_pos = avio_tell(pb);
 
         switch(chunk_id) {
         case ID_VHDR:
@@ -133,23 +152,23 @@ static int iff_read_header(AVFormatContext *s,
 
             if (data_size < 14)
                 return AVERROR_INVALIDDATA;
-            url_fskip(pb, 12);
-            st->codec->sample_rate = get_be16(pb);
+            avio_skip(pb, 12);
+            st->codec->sample_rate = avio_rb16(pb);
             if (data_size >= 16) {
-                url_fskip(pb, 1);
-                compression        = get_byte(pb);
+                avio_skip(pb, 1);
+                compression        = avio_r8(pb);
             }
             break;
 
         case ID_BODY:
-            iff->body_pos = url_ftell(pb);
+            iff->body_pos = avio_tell(pb);
             iff->body_size = data_size;
             break;
 
         case ID_CHAN:
             if (data_size < 4)
                 return AVERROR_INVALIDDATA;
-            st->codec->channels = (get_be32(pb) < 6) ? 1 : 2;
+            st->codec->channels = (avio_rb32(pb) < 6) ? 1 : 2;
             break;
 
         case ID_CMAP:
@@ -157,7 +176,7 @@ static int iff_read_header(AVFormatContext *s,
             st->codec->extradata      = av_malloc(data_size);
             if (!st->codec->extradata)
                 return AVERROR(ENOMEM);
-            if (get_buffer(pb, st->codec->extradata, data_size) < 0)
+            if (avio_read(pb, st->codec->extradata, data_size) < 0)
                 return AVERROR(EIO);
             break;
 
@@ -165,35 +184,49 @@ static int iff_read_header(AVFormatContext *s,
             st->codec->codec_type            = AVMEDIA_TYPE_VIDEO;
             if (data_size <= 8)
                 return AVERROR_INVALIDDATA;
-            st->codec->width                 = get_be16(pb);
-            st->codec->height                = get_be16(pb);
-            url_fskip(pb, 4); // x, y offset
-            st->codec->bits_per_coded_sample = get_byte(pb);
+            st->codec->width                 = avio_rb16(pb);
+            st->codec->height                = avio_rb16(pb);
+            avio_skip(pb, 4); // x, y offset
+            st->codec->bits_per_coded_sample = avio_r8(pb);
             if (data_size >= 11) {
-                url_fskip(pb, 1); // masking
-                compression                  = get_byte(pb);
+                avio_skip(pb, 1); // masking
+                compression                  = avio_r8(pb);
             }
             if (data_size >= 16) {
-                url_fskip(pb, 3); // paddding, transparent
-                st->sample_aspect_ratio.num  = get_byte(pb);
-                st->sample_aspect_ratio.den  = get_byte(pb);
+                avio_skip(pb, 3); // paddding, transparent
+                st->sample_aspect_ratio.num  = avio_r8(pb);
+                st->sample_aspect_ratio.den  = avio_r8(pb);
             }
             break;
 
         case ID_ANNO:
-            buf = av_malloc(data_size + 1);
-            if (!buf)
-                break;
-            get_buffer(pb, buf, data_size);
-            buf[data_size] = 0;
-            av_metadata_set2(&s->metadata, "comment", buf, AV_METADATA_DONT_STRDUP_VAL);
+        case ID_TEXT:
+            metadata_tag = "comment";
+            break;
+
+        case ID_AUTH:
+            metadata_tag = "artist";
+            break;
+
+        case ID_COPYRIGHT:
+            metadata_tag = "copyright";
+            break;
+
+        case ID_NAME:
+            metadata_tag = "title";
             break;
         }
 
-        url_fskip(pb, data_size - (url_ftell(pb) - orig_pos) + (data_size & 1));
+        if (metadata_tag) {
+            if ((res = get_metadata(s, metadata_tag, data_size)) < 0) {
+                av_log(s, AV_LOG_ERROR, "cannot allocate metadata tag %s!", metadata_tag);
+                return res;
+            }
+        }
+        avio_skip(pb, data_size - (avio_tell(pb) - orig_pos) + (data_size & 1));
     }
 
-    url_fseek(pb, iff->body_pos, SEEK_SET);
+    avio_seek(pb, iff->body_pos, SEEK_SET);
 
     switch(st->codec->codec_type) {
     case AVMEDIA_TYPE_AUDIO:
@@ -210,7 +243,7 @@ static int iff_read_header(AVFormatContext *s,
             st->codec->codec_id = CODEC_ID_8SVX_EXP;
             break;
         default:
-            av_log(s, AV_LOG_ERROR, "iff: unknown compression method\n");
+            av_log(s, AV_LOG_ERROR, "unknown compression method\n");
             return -1;
         }
 
@@ -222,13 +255,7 @@ static int iff_read_header(AVFormatContext *s,
     case AVMEDIA_TYPE_VIDEO:
         switch (compression) {
         case BITMAP_RAW:
-            if (st->codec->codec_tag == ID_ILBM) {
-                st->codec->codec_id = CODEC_ID_IFF_ILBM;
-            } else {
-                st->codec->codec_id = CODEC_ID_RAWVIDEO;
-                st->codec->pix_fmt  = PIX_FMT_PAL8;
-                st->codec->codec_tag = 0;
-            }
+            st->codec->codec_id = CODEC_ID_IFF_ILBM;
             break;
         case BITMAP_BYTERUN1:
             st->codec->codec_id = CODEC_ID_IFF_BYTERUN1;
@@ -249,35 +276,23 @@ static int iff_read_packet(AVFormatContext *s,
                            AVPacket *pkt)
 {
     IffDemuxContext *iff = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVStream *st = s->streams[0];
     int ret;
 
     if(iff->sent_bytes >= iff->body_size)
         return AVERROR(EIO);
 
-    if(s->streams[0]->codec->channels == 2) {
+    if(st->codec->channels == 2) {
         uint8_t sample_buffer[PACKET_SIZE];
 
-        ret = get_buffer(pb, sample_buffer, PACKET_SIZE);
+        ret = avio_read(pb, sample_buffer, PACKET_SIZE);
         if(av_new_packet(pkt, PACKET_SIZE) < 0) {
-            av_log(s, AV_LOG_ERROR, "iff: cannot allocate packet \n");
+            av_log(s, AV_LOG_ERROR, "cannot allocate packet\n");
             return AVERROR(ENOMEM);
         }
         interleave_stereo(sample_buffer, pkt->data, PACKET_SIZE);
-    } else if (s->streams[0]->codec->codec_id == CODEC_ID_RAWVIDEO) {
-        if(av_new_packet(pkt, iff->body_size + AVPALETTE_SIZE) < 0) {
-            return AVERROR(ENOMEM);
-        }
-
-        ret = ff_cmap_read_palette(st->codec, (uint32_t*)(pkt->data + iff->body_size));
-        if (ret < 0)
-            return ret;
-        av_freep(&st->codec->extradata);
-        st->codec->extradata_size = 0;
-
-        ret = get_buffer(pb, pkt->data, iff->body_size);
-    } else if (s->streams[0]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
+    } else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
         ret = av_get_packet(pb, pkt, iff->body_size);
     } else {
         ret = av_get_packet(pb, pkt, PACKET_SIZE);
@@ -286,20 +301,20 @@ static int iff_read_packet(AVFormatContext *s,
     if(iff->sent_bytes == 0)
         pkt->flags |= AV_PKT_FLAG_KEY;
 
-    if(s->streams[0]->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
+    if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
         iff->sent_bytes += PACKET_SIZE;
     } else {
         iff->sent_bytes = iff->body_size;
     }
     pkt->stream_index = 0;
-    if(s->streams[0]->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
+    if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
         pkt->pts = iff->audio_frame_count;
-        iff->audio_frame_count += ret / s->streams[0]->codec->channels;
+        iff->audio_frame_count += ret / st->codec->channels;
     }
     return ret;
 }
 
-AVInputFormat iff_demuxer = {
+AVInputFormat ff_iff_demuxer = {
     "IFF",
     NULL_IF_CONFIG_SMALL("IFF format"),
     sizeof(IffDemuxContext),
diff --git a/libavformat/img2.c b/libavformat/img2.c
index 85bee97..2b5d63b 100644
--- a/libavformat/img2.c
+++ b/libavformat/img2.c
@@ -3,26 +3,28 @@
  * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
  * Copyright (c) 2004 Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "libavutil/intreadwrite.h"
 #include "libavutil/avstring.h"
 #include "avformat.h"
+#include "avio_internal.h"
+#include "internal.h"
 #include <strings.h>
 
 typedef struct {
@@ -73,6 +75,7 @@ static const IdStrMap img_tags[] = {
     { CODEC_ID_SUNRAST   , "sunras"},
     { CODEC_ID_JPEG2000  , "jp2"},
     { CODEC_ID_DPX       , "dpx"},
+    { CODEC_ID_PICTOR    , "pic"},
     { CODEC_ID_NONE      , NULL}
 };
 
@@ -170,7 +173,7 @@ static int find_image_range(int *pfirst_index, int *plast_index,
 }
 
 
-static int image_probe(AVProbeData *p)
+static int read_probe(AVProbeData *p)
 {
     if (p->filename && av_str2id(img_tags, p->filename)) {
         if (av_filename_number_test(p->filename))
@@ -181,11 +184,18 @@ static int image_probe(AVProbeData *p)
     return 0;
 }
 
+enum CodecID ff_guess_image2_codec(const char *filename)
+{
+    return av_str2id(img_tags, filename);
+}
+
+#if FF_API_GUESS_IMG2_CODEC
 enum CodecID av_guess_image2_codec(const char *filename){
     return av_str2id(img_tags, filename);
 }
+#endif
 
-static int img_read_header(AVFormatContext *s1, AVFormatParameters *ap)
+static int read_header(AVFormatContext *s1, AVFormatParameters *ap)
 {
     VideoData *s = s1->priv_data;
     int first_index, last_index;
@@ -248,13 +258,13 @@ static int img_read_header(AVFormatContext *s1, AVFormatParameters *ap)
     return 0;
 }
 
-static int img_read_packet(AVFormatContext *s1, AVPacket *pkt)
+static int read_packet(AVFormatContext *s1, AVPacket *pkt)
 {
     VideoData *s = s1->priv_data;
     char filename[1024];
     int i;
     int size[3]={0}, ret[3]={0};
-    ByteIOContext *f[3];
+    AVIOContext *f[3];
     AVCodecContext *codec= s1->streams[0]->codec;
 
     if (!s->is_pipe) {
@@ -268,13 +278,13 @@ static int img_read_packet(AVFormatContext *s1, AVPacket *pkt)
                                   s->path, s->img_number)<0 && s->img_number > 1)
             return AVERROR(EIO);
         for(i=0; i<3; i++){
-            if (url_fopen(&f[i], filename, URL_RDONLY) < 0) {
+            if (avio_open(&f[i], filename, AVIO_RDONLY) < 0) {
                 if(i==1)
                     break;
                 av_log(s1, AV_LOG_ERROR, "Could not open file : %s\n",filename);
                 return AVERROR(EIO);
             }
-            size[i]= url_fsize(f[i]);
+            size[i]= avio_size(f[i]);
 
             if(codec->codec_id != CODEC_ID_RAWVIDEO)
                 break;
@@ -285,7 +295,7 @@ static int img_read_packet(AVFormatContext *s1, AVPacket *pkt)
             infer_size(&codec->width, &codec->height, size[0]);
     } else {
         f[0] = s1->pb;
-        if (url_feof(f[0]))
+        if (f[0]->eof_reached)
             return AVERROR(EIO);
         size[0]= 4096;
     }
@@ -297,9 +307,9 @@ static int img_read_packet(AVFormatContext *s1, AVPacket *pkt)
     pkt->size= 0;
     for(i=0; i<3; i++){
         if(size[i]){
-            ret[i]= get_buffer(f[i], pkt->data + pkt->size, size[i]);
+            ret[i]= avio_read(f[i], pkt->data + pkt->size, size[i]);
             if (!s->is_pipe)
-                url_fclose(f[i]);
+                avio_close(f[i]);
             if(ret[i]>0)
                 pkt->size += ret[i];
         }
@@ -319,7 +329,7 @@ static int img_read_packet(AVFormatContext *s1, AVPacket *pkt)
 /******************************************************/
 /* image output */
 
-static int img_write_header(AVFormatContext *s)
+static int write_header(AVFormatContext *s)
 {
     VideoData *img = s->priv_data;
 
@@ -335,10 +345,10 @@ static int img_write_header(AVFormatContext *s)
     return 0;
 }
 
-static int img_write_packet(AVFormatContext *s, AVPacket *pkt)
+static int write_packet(AVFormatContext *s, AVPacket *pkt)
 {
     VideoData *img = s->priv_data;
-    ByteIOContext *pb[3];
+    AVIOContext *pb[3];
     char filename[1024];
     AVCodecContext *codec= s->streams[ pkt->stream_index ]->codec;
     int i;
@@ -346,11 +356,13 @@ static int img_write_packet(AVFormatContext *s, AVPacket *pkt)
     if (!img->is_pipe) {
         if (av_get_frame_filename(filename, sizeof(filename),
                                   img->path, img->img_number) < 0 && img->img_number>1) {
-            av_log(s, AV_LOG_ERROR, "Could not get frame filename from pattern\n");
+            av_log(s, AV_LOG_ERROR,
+                   "Could not get frame filename number %d from pattern '%s'\n",
+                   img->img_number, img->path);
             return AVERROR(EIO);
         }
         for(i=0; i<3; i++){
-            if (url_fopen(&pb[i], filename, URL_WRONLY) < 0) {
+            if (avio_open(&pb[i], filename, AVIO_WRONLY) < 0) {
                 av_log(s, AV_LOG_ERROR, "Could not open file : %s\n",filename);
                 return AVERROR(EIO);
             }
@@ -365,13 +377,13 @@ static int img_write_packet(AVFormatContext *s, AVPacket *pkt)
 
     if(codec->codec_id == CODEC_ID_RAWVIDEO){
         int ysize = codec->width * codec->height;
-        put_buffer(pb[0], pkt->data        , ysize);
-        put_buffer(pb[1], pkt->data + ysize, (pkt->size - ysize)/2);
-        put_buffer(pb[2], pkt->data + ysize +(pkt->size - ysize)/2, (pkt->size - ysize)/2);
-        put_flush_packet(pb[1]);
-        put_flush_packet(pb[2]);
-        url_fclose(pb[1]);
-        url_fclose(pb[2]);
+        avio_write(pb[0], pkt->data        , ysize);
+        avio_write(pb[1], pkt->data + ysize, (pkt->size - ysize)/2);
+        avio_write(pb[2], pkt->data + ysize +(pkt->size - ysize)/2, (pkt->size - ysize)/2);
+        avio_flush(pb[1]);
+        avio_flush(pb[2]);
+        avio_close(pb[1]);
+        avio_close(pb[2]);
     }else{
         if(av_str2id(img_tags, s->filename) == CODEC_ID_JPEG2000){
             AVStream *st = s->streams[0];
@@ -379,15 +391,15 @@ static int img_write_packet(AVFormatContext *s, AVPacket *pkt)
                AV_RL32(st->codec->extradata+4) == MKTAG('j','p','2','h')){
                 if(pkt->size < 8 || AV_RL32(pkt->data+4) != MKTAG('j','p','2','c'))
                     goto error;
-                put_be32(pb[0], 12);
-                put_tag (pb[0], "jP  ");
-                put_be32(pb[0], 0x0D0A870A); // signature
-                put_be32(pb[0], 20);
-                put_tag (pb[0], "ftyp");
-                put_tag (pb[0], "jp2 ");
-                put_be32(pb[0], 0);
-                put_tag (pb[0], "jp2 ");
-                put_buffer(pb[0], st->codec->extradata, st->codec->extradata_size);
+                avio_wb32(pb[0], 12);
+                ffio_wfourcc(pb[0], "jP  ");
+                avio_wb32(pb[0], 0x0D0A870A); // signature
+                avio_wb32(pb[0], 20);
+                ffio_wfourcc(pb[0], "ftyp");
+                ffio_wfourcc(pb[0], "jp2 ");
+                avio_wb32(pb[0], 0);
+                ffio_wfourcc(pb[0], "jp2 ");
+                avio_write(pb[0], st->codec->extradata, st->codec->extradata_size);
             }else if(pkt->size < 8 ||
                      (!st->codec->extradata_size &&
                       AV_RL32(pkt->data+4) != MKTAG('j','P',' ',' '))){ // signature
@@ -396,11 +408,11 @@ static int img_write_packet(AVFormatContext *s, AVPacket *pkt)
                 return -1;
             }
         }
-        put_buffer(pb[0], pkt->data, pkt->size);
+        avio_write(pb[0], pkt->data, pkt->size);
     }
-    put_flush_packet(pb[0]);
+    avio_flush(pb[0]);
     if (!img->is_pipe) {
-        url_fclose(pb[0]);
+        avio_close(pb[0]);
     }
 
     img->img_number++;
@@ -411,57 +423,48 @@ static int img_write_packet(AVFormatContext *s, AVPacket *pkt)
 
 /* input */
 #if CONFIG_IMAGE2_DEMUXER
-AVInputFormat image2_demuxer = {
-    "image2",
-    NULL_IF_CONFIG_SMALL("image2 sequence"),
-    sizeof(VideoData),
-    image_probe,
-    img_read_header,
-    img_read_packet,
-    NULL,
-    NULL,
-    NULL,
-    AVFMT_NOFILE,
+AVInputFormat ff_image2_demuxer = {
+    .name           = "image2",
+    .long_name      = NULL_IF_CONFIG_SMALL("image2 sequence"),
+    .priv_data_size = sizeof(VideoData),
+    .read_probe     = read_probe,
+    .read_header    = read_header,
+    .read_packet    = read_packet,
+    .flags          = AVFMT_NOFILE,
 };
 #endif
 #if CONFIG_IMAGE2PIPE_DEMUXER
-AVInputFormat image2pipe_demuxer = {
-    "image2pipe",
-    NULL_IF_CONFIG_SMALL("piped image2 sequence"),
-    sizeof(VideoData),
-    NULL, /* no probe */
-    img_read_header,
-    img_read_packet,
+AVInputFormat ff_image2pipe_demuxer = {
+    .name           = "image2pipe",
+    .long_name      = NULL_IF_CONFIG_SMALL("piped image2 sequence"),
+    .priv_data_size = sizeof(VideoData),
+    .read_header    = read_header,
+    .read_packet    = read_packet,
 };
 #endif
 
 /* output */
 #if CONFIG_IMAGE2_MUXER
-AVOutputFormat image2_muxer = {
-    "image2",
-    NULL_IF_CONFIG_SMALL("image2 sequence"),
-    "",
-    "bmp,jpeg,jpg,ljpg,pam,pbm,pcx,pgm,pgmyuv,png,ppm,sgi,tif,tiff,jp2",
-    sizeof(VideoData),
-    CODEC_ID_NONE,
-    CODEC_ID_MJPEG,
-    img_write_header,
-    img_write_packet,
-    NULL,
-    .flags= AVFMT_NOTIMESTAMPS | AVFMT_NODIMENSIONS | AVFMT_NOFILE
+AVOutputFormat ff_image2_muxer = {
+    .name           = "image2",
+    .long_name      = NULL_IF_CONFIG_SMALL("image2 sequence"),
+    .extensions     = "bmp,jpeg,jpg,ljpg,pam,pbm,pcx,pgm,pgmyuv,png,"
+                      "ppm,sgi,tga,tif,tiff,jp2",
+    .priv_data_size = sizeof(VideoData),
+    .video_codec    = CODEC_ID_MJPEG,
+    .write_header   = write_header,
+    .write_packet   = write_packet,
+    .flags          = AVFMT_NOTIMESTAMPS | AVFMT_NODIMENSIONS | AVFMT_NOFILE
 };
 #endif
 #if CONFIG_IMAGE2PIPE_MUXER
-AVOutputFormat image2pipe_muxer = {
-    "image2pipe",
-    NULL_IF_CONFIG_SMALL("piped image2 sequence"),
-    "",
-    "",
-    sizeof(VideoData),
-    CODEC_ID_NONE,
-    CODEC_ID_MJPEG,
-    img_write_header,
-    img_write_packet,
-    .flags= AVFMT_NOTIMESTAMPS | AVFMT_NODIMENSIONS
+AVOutputFormat ff_image2pipe_muxer = {
+    .name           = "image2pipe",
+    .long_name      = NULL_IF_CONFIG_SMALL("piped image2 sequence"),
+    .priv_data_size = sizeof(VideoData),
+    .video_codec    = CODEC_ID_MJPEG,
+    .write_header   = write_header,
+    .write_packet   = write_packet,
+    .flags          = AVFMT_NOTIMESTAMPS | AVFMT_NODIMENSIONS
 };
 #endif
diff --git a/libavformat/ingenientdec.c b/libavformat/ingenientdec.c
new file mode 100644
index 0000000..7407a04
--- /dev/null
+++ b/libavformat/ingenientdec.c
@@ -0,0 +1,71 @@
+/*
+ * RAW Ingenient MJPEG demuxer
+ * Copyright (c) 2005 Alex Beregszaszi
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "avformat.h"
+#include "rawdec.h"
+
+// http://www.artificis.hu/files/texts/ingenient.txt
+static int ingenient_read_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    int ret, size, w, h, unk1, unk2;
+
+    if (avio_rl32(s->pb) != MKTAG('M', 'J', 'P', 'G'))
+        return AVERROR(EIO); // FIXME
+
+    size = avio_rl32(s->pb);
+
+    w = avio_rl16(s->pb);
+    h = avio_rl16(s->pb);
+
+    avio_skip(s->pb, 8); // zero + size (padded?)
+    avio_skip(s->pb, 2);
+    unk1 = avio_rl16(s->pb);
+    unk2 = avio_rl16(s->pb);
+    avio_skip(s->pb, 22); // ASCII timestamp
+
+    av_log(s, AV_LOG_DEBUG, "Ingenient packet: size=%d, width=%d, height=%d, unk1=%d unk2=%d\n",
+        size, w, h, unk1, unk2);
+
+    if (av_new_packet(pkt, size) < 0)
+        return AVERROR(ENOMEM);
+
+    pkt->pos = avio_tell(s->pb);
+    pkt->stream_index = 0;
+    ret = avio_read(s->pb, pkt->data, size);
+    if (ret < 0) {
+        av_free_packet(pkt);
+        return ret;
+    }
+    pkt->size = ret;
+    return ret;
+}
+
+AVInputFormat ff_ingenient_demuxer = {
+    "ingenient",
+    NULL_IF_CONFIG_SMALL("raw Ingenient MJPEG"),
+    0,
+    NULL,
+    ff_raw_video_read_header,
+    ingenient_read_packet,
+    .flags= AVFMT_GENERIC_INDEX,
+    .extensions = "cgi", // FIXME
+    .value = CODEC_ID_MJPEG,
+};
diff --git a/libavformat/internal.h b/libavformat/internal.h
index a395c2f..9bc2340 100644
--- a/libavformat/internal.h
+++ b/libavformat/internal.h
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2001 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -24,6 +24,13 @@
 #include <stdint.h>
 #include "avformat.h"
 
+#define MAX_URL_SIZE 4096
+
+typedef struct AVCodecTag {
+    enum CodecID id;
+    unsigned int tag;
+} AVCodecTag;
+
 void ff_dynarray_add(intptr_t **tab_ptr, int *nb_ptr, intptr_t elem);
 
 #ifdef __GNUC__
@@ -41,13 +48,20 @@ do {\
 } while(0)
 #endif
 
-time_t mktimegm(struct tm *tm);
 struct tm *brktimegm(time_t secs, struct tm *tm);
-const char *small_strptime(const char *p, const char *fmt,
-                           struct tm *dt);
 
 char *ff_data_to_hex(char *buf, const uint8_t *src, int size, int lowercase);
 
+/**
+ * Parse a string of hexadecimal strings. Any space between the hexadecimal
+ * digits is ignored.
+ *
+ * @param data if non-null, the parsed data is written to this pointer
+ * @param p the string to parse
+ * @return the number of bytes written (or to be written, if data is null)
+ */
+int ff_hex_to_data(uint8_t *data, const char *p);
+
 void ff_program_add_stream_index(AVFormatContext *ac, int progid, unsigned int idx);
 
 /**
@@ -62,49 +76,12 @@ void ff_read_frame_flush(AVFormatContext *s);
 #define NTP_OFFSET 2208988800ULL
 #define NTP_OFFSET_US (NTP_OFFSET * 1000000ULL)
 
-/** Gets the current time since NTP epoch in microseconds. */
+/** Get the current time since NTP epoch in microseconds. */
 uint64_t ff_ntp_time(void);
 
+#if FF_API_URL_SPLIT
 /**
- * Probes a bytestream to determine the input format. Each time a probe returns
- * with a score that is too low, the probe buffer size is increased and another
- * attempt is made. When the maximum probe size is reached, the input format
- * with the highest score is returned.
- *
- * @param pb the bytestream to probe, it may be closed and opened again
- * @param fmt the input format is put here
- * @param filename the filename of the stream
- * @param logctx the log context
- * @param offset the offset within the bytestream to probe from
- * @param max_probe_size the maximum probe buffer size (zero for default)
- * @return 0 in case of success, a negative value corresponding to an
- * AVERROR code otherwise
- */
-int ff_probe_input_buffer(ByteIOContext **pb, AVInputFormat **fmt,
-                          const char *filename, void *logctx,
-                          unsigned int offset, unsigned int max_probe_size);
-
-/**
- * Splits a URL string into components. To reassemble components back into
- * a URL, use ff_url_join instead of using snprintf directly.
- *
- * The pointers to buffers for storing individual components may be null,
- * in order to ignore that component. Buffers for components not found are
- * set to empty strings. If the port isn't found, it is set to a negative
- * value.
- *
- * @see ff_url_join
- *
- * @param proto the buffer for the protocol
- * @param proto_size the size of the proto buffer
- * @param authorization the buffer for the authorization
- * @param authorization_size the size of the authorization buffer
- * @param hostname the buffer for the host name
- * @param hostname_size the size of the hostname buffer
- * @param port_ptr a pointer to store the port number in
- * @param path the buffer for the path
- * @param path_size the size of the path buffer
- * @param url the URL to split
+ * @deprecated use av_url_split() instead
  */
 void ff_url_split(char *proto, int proto_size,
                   char *authorization, int authorization_size,
@@ -112,21 +89,23 @@ void ff_url_split(char *proto, int proto_size,
                   int *port_ptr,
                   char *path, int path_size,
                   const char *url);
+#endif
 
 /**
- * Assembles a URL string from components. This is the reverse operation
- * of ff_url_split.
+ * Assemble a URL string from components. This is the reverse operation
+ * of av_url_split.
  *
  * Note, this requires networking to be initialized, so the caller must
  * ensure ff_network_init has been called.
  *
- * @see ff_url_split
+ * @see av_url_split
  *
  * @param str the buffer to fill with the url
  * @param size the size of the str buffer
  * @param proto the protocol identifier, if null, the separator
  *              after the identifier is left out, too
- * @param authorization an optional authorization string, may be null
+ * @param authorization an optional authorization string, may be null.
+ *                      An empty string is treated the same as a null string.
  * @param hostname the host name string
  * @param port the port number, left out from the string if negative
  * @param fmt a generic format string for everything to add after the
@@ -138,7 +117,7 @@ int ff_url_join(char *str, int size, const char *proto,
                 int port, const char *fmt, ...);
 
 /**
- * Appends the media-specific SDP fragment for the media stream c
+ * Append the media-specific SDP fragment for the media stream c
  * to the buffer buff.
  *
  * Note, the buffer needs to be initialized, since it is appended to
@@ -148,10 +127,129 @@ int ff_url_join(char *str, int size, const char *proto,
  * @param size the size of the buff buffer
  * @param c the AVCodecContext of the media to describe
  * @param dest_addr the destination address of the media stream, may be NULL
+ * @param dest_type the destination address type, may be NULL
  * @param port the destination port of the media stream, 0 if unknown
  * @param ttl the time to live of the stream, 0 if not multicast
  */
 void ff_sdp_write_media(char *buff, int size, AVCodecContext *c,
-                        const char *dest_addr, int port, int ttl);
+                        const char *dest_addr, const char *dest_type,
+                        int port, int ttl);
+
+/**
+ * Write a packet to another muxer than the one the user originally
+ * intended. Useful when chaining muxers, where one muxer internally
+ * writes a received packet to another muxer.
+ *
+ * @param dst the muxer to write the packet to
+ * @param dst_stream the stream index within dst to write the packet to
+ * @param pkt the packet to be written
+ * @param src the muxer the packet originally was intended for
+ * @return the value av_write_frame returned
+ */
+int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
+                     AVFormatContext *src);
+
+/**
+ * Get the length in bytes which is needed to store val as v.
+ */
+int ff_get_v_length(uint64_t val);
+
+/**
+ * Put val using a variable number of bytes.
+ */
+void ff_put_v(AVIOContext *bc, uint64_t val);
+
+/**
+ * Read a whole line of text from AVIOContext. Stop reading after reaching
+ * either a \n, a \0 or EOF. The returned string is always \0 terminated,
+ * and may be truncated if the buffer is too small.
+ *
+ * @param s the read-only AVIOContext
+ * @param buf buffer to store the read line
+ * @param maxlen size of the buffer
+ * @return the length of the string written in the buffer, not including the
+ *         final \0
+ */
+int ff_get_line(AVIOContext *s, char *buf, int maxlen);
+
+#define SPACE_CHARS " \t\r\n"
+
+/**
+ * Callback function type for ff_parse_key_value.
+ *
+ * @param key a pointer to the key
+ * @param key_len the number of bytes that belong to the key, including the '='
+ *                char
+ * @param dest return the destination pointer for the value in *dest, may
+ *             be null to ignore the value
+ * @param dest_len the length of the *dest buffer
+ */
+typedef void (*ff_parse_key_val_cb)(void *context, const char *key,
+                                    int key_len, char **dest, int *dest_len);
+/**
+ * Parse a string with comma-separated key=value pairs. The value strings
+ * may be quoted and may contain escaped characters within quoted strings.
+ *
+ * @param str the string to parse
+ * @param callback_get_buf function that returns where to store the
+ *                         unescaped value string.
+ * @param context the opaque context pointer to pass to callback_get_buf
+ */
+void ff_parse_key_value(const char *str, ff_parse_key_val_cb callback_get_buf,
+                        void *context);
+
+/**
+ * Find stream index based on format-specific stream ID
+ * @return stream index, or < 0 on error
+ */
+int ff_find_stream_index(AVFormatContext *s, int id);
+
+/**
+ * Internal version of av_index_search_timestamp
+ */
+int ff_index_search_timestamp(const AVIndexEntry *entries, int nb_entries,
+                              int64_t wanted_timestamp, int flags);
+
+/**
+ * Internal version of av_add_index_entry
+ */
+int ff_add_index_entry(AVIndexEntry **index_entries,
+                       int *nb_index_entries,
+                       unsigned int *index_entries_allocated_size,
+                       int64_t pos, int64_t timestamp, int size, int distance, int flags);
+
+/**
+ * Add a new chapter.
+ *
+ * @param s media file handle
+ * @param id unique ID for this chapter
+ * @param start chapter start time in time_base units
+ * @param end chapter end time in time_base units
+ * @param title chapter title
+ *
+ * @return AVChapter or NULL on error
+ */
+AVChapter *ff_new_chapter(AVFormatContext *s, int id, AVRational time_base,
+                          int64_t start, int64_t end, const char *title);
+
+/**
+ * Ensure the index uses less memory than the maximum specified in
+ * AVFormatContext.max_index_size by discarding entries if it grows
+ * too large.
+ */
+void ff_reduce_index(AVFormatContext *s, int stream_index);
+
+/*
+ * Convert a relative url into an absolute url, given a base url.
+ *
+ * @param buf the buffer where output absolute url is written
+ * @param size the size of buf
+ * @param base the base url, may be equal to buf.
+ * @param rel the new url, which is interpreted relative to base
+ */
+void ff_make_absolute_url(char *buf, int size, const char *base,
+                          const char *rel);
+
+enum CodecID ff_guess_image2_codec(const char *filename);
 
 #endif /* AVFORMAT_INTERNAL_H */
diff --git a/libavformat/ipmovie.c b/libavformat/ipmovie.c
index 372a926..e3215d3 100644
--- a/libavformat/ipmovie.c
+++ b/libavformat/ipmovie.c
@@ -2,20 +2,20 @@
  * Interplay MVE File Demuxer
  * Copyright (c) 2003 The ffmpeg Project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -97,6 +97,8 @@ typedef struct IPMVEContext {
     unsigned int video_width;
     unsigned int video_height;
     int64_t video_pts;
+    uint32_t     palette[256];
+    int          has_palette;
 
     unsigned int audio_bits;
     unsigned int audio_channels;
@@ -116,11 +118,9 @@ typedef struct IPMVEContext {
 
     int64_t next_chunk_offset;
 
-    AVPaletteControl palette_control;
-
 } IPMVEContext;
 
-static int load_ipmovie_packet(IPMVEContext *s, ByteIOContext *pb,
+static int load_ipmovie_packet(IPMVEContext *s, AVIOContext *pb,
     AVPacket *pkt) {
 
     int chunk_type;
@@ -133,7 +133,7 @@ static int load_ipmovie_packet(IPMVEContext *s, ByteIOContext *pb,
             s->audio_chunk_size -= 6;
         }
 
-        url_fseek(pb, s->audio_chunk_offset, SEEK_SET);
+        avio_seek(pb, s->audio_chunk_offset, SEEK_SET);
         s->audio_chunk_offset = 0;
 
         if (s->audio_chunk_size != av_get_packet(pb, pkt, s->audio_chunk_size))
@@ -162,20 +162,31 @@ static int load_ipmovie_packet(IPMVEContext *s, ByteIOContext *pb,
         if (av_new_packet(pkt, s->decode_map_chunk_size + s->video_chunk_size))
             return CHUNK_NOMEM;
 
+        if (s->has_palette) {
+            uint8_t *pal;
+
+            pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE,
+                                          AVPALETTE_SIZE);
+            if (pal) {
+                memcpy(pal, s->palette, AVPALETTE_SIZE);
+                s->has_palette = 0;
+            }
+        }
+
         pkt->pos= s->decode_map_chunk_offset;
-        url_fseek(pb, s->decode_map_chunk_offset, SEEK_SET);
+        avio_seek(pb, s->decode_map_chunk_offset, SEEK_SET);
         s->decode_map_chunk_offset = 0;
 
-        if (get_buffer(pb, pkt->data, s->decode_map_chunk_size) !=
+        if (avio_read(pb, pkt->data, s->decode_map_chunk_size) !=
             s->decode_map_chunk_size) {
             av_free_packet(pkt);
             return CHUNK_EOF;
         }
 
-        url_fseek(pb, s->video_chunk_offset, SEEK_SET);
+        avio_seek(pb, s->video_chunk_offset, SEEK_SET);
         s->video_chunk_offset = 0;
 
-        if (get_buffer(pb, pkt->data + s->decode_map_chunk_size,
+        if (avio_read(pb, pkt->data + s->decode_map_chunk_size,
             s->video_chunk_size) != s->video_chunk_size) {
             av_free_packet(pkt);
             return CHUNK_EOF;
@@ -193,7 +204,7 @@ static int load_ipmovie_packet(IPMVEContext *s, ByteIOContext *pb,
 
     } else {
 
-        url_fseek(pb, s->next_chunk_offset, SEEK_SET);
+        avio_seek(pb, s->next_chunk_offset, SEEK_SET);
         chunk_type = CHUNK_DONE;
 
     }
@@ -203,7 +214,7 @@ static int load_ipmovie_packet(IPMVEContext *s, ByteIOContext *pb,
 
 /* This function loads and processes a single chunk in an IP movie file.
  * It returns the type of chunk that was processed. */
-static int process_ipmovie_chunk(IPMVEContext *s, ByteIOContext *pb,
+static int process_ipmovie_chunk(IPMVEContext *s, AVIOContext *pb,
     AVPacket *pkt)
 {
     unsigned char chunk_preamble[CHUNK_PREAMBLE_SIZE];
@@ -225,9 +236,9 @@ static int process_ipmovie_chunk(IPMVEContext *s, ByteIOContext *pb,
         return chunk_type;
 
     /* read the next chunk, wherever the file happens to be pointing */
-    if (url_feof(pb))
+    if (pb->eof_reached)
         return CHUNK_EOF;
-    if (get_buffer(pb, chunk_preamble, CHUNK_PREAMBLE_SIZE) !=
+    if (avio_read(pb, chunk_preamble, CHUNK_PREAMBLE_SIZE) !=
         CHUNK_PREAMBLE_SIZE)
         return CHUNK_BAD;
     chunk_size = AV_RL16(&chunk_preamble[0]);
@@ -271,11 +282,11 @@ static int process_ipmovie_chunk(IPMVEContext *s, ByteIOContext *pb,
     while ((chunk_size > 0) && (chunk_type != CHUNK_BAD)) {
 
         /* read the next chunk, wherever the file happens to be pointing */
-       if (url_feof(pb)) {
+        if (pb->eof_reached) {
             chunk_type = CHUNK_EOF;
             break;
         }
-        if (get_buffer(pb, opcode_preamble, CHUNK_PREAMBLE_SIZE) !=
+        if (avio_read(pb, opcode_preamble, CHUNK_PREAMBLE_SIZE) !=
             CHUNK_PREAMBLE_SIZE) {
             chunk_type = CHUNK_BAD;
             break;
@@ -299,12 +310,12 @@ static int process_ipmovie_chunk(IPMVEContext *s, ByteIOContext *pb,
 
         case OPCODE_END_OF_STREAM:
             debug_ipmovie("end of stream\n");
-            url_fseek(pb, opcode_size, SEEK_CUR);
+            avio_skip(pb, opcode_size);
             break;
 
         case OPCODE_END_OF_CHUNK:
             debug_ipmovie("end of chunk\n");
-            url_fseek(pb, opcode_size, SEEK_CUR);
+            avio_skip(pb, opcode_size);
             break;
 
         case OPCODE_CREATE_TIMER:
@@ -314,7 +325,7 @@ static int process_ipmovie_chunk(IPMVEContext *s, ByteIOContext *pb,
                 chunk_type = CHUNK_BAD;
                 break;
             }
-            if (get_buffer(pb, scratch, opcode_size) !=
+            if (avio_read(pb, scratch, opcode_size) !=
                 opcode_size) {
                 chunk_type = CHUNK_BAD;
                 break;
@@ -331,7 +342,7 @@ static int process_ipmovie_chunk(IPMVEContext *s, ByteIOContext *pb,
                 chunk_type = CHUNK_BAD;
                 break;
             }
-            if (get_buffer(pb, scratch, opcode_size) !=
+            if (avio_read(pb, scratch, opcode_size) !=
                 opcode_size) {
                 chunk_type = CHUNK_BAD;
                 break;
@@ -359,7 +370,7 @@ static int process_ipmovie_chunk(IPMVEContext *s, ByteIOContext *pb,
 
         case OPCODE_START_STOP_AUDIO:
             debug_ipmovie("start/stop audio\n");
-            url_fseek(pb, opcode_size, SEEK_CUR);
+            avio_skip(pb, opcode_size);
             break;
 
         case OPCODE_INIT_VIDEO_BUFFERS:
@@ -369,7 +380,7 @@ static int process_ipmovie_chunk(IPMVEContext *s, ByteIOContext *pb,
                 chunk_type = CHUNK_BAD;
                 break;
             }
-            if (get_buffer(pb, scratch, opcode_size) !=
+            if (avio_read(pb, scratch, opcode_size) !=
                 opcode_size) {
                 chunk_type = CHUNK_BAD;
                 break;
@@ -393,36 +404,36 @@ static int process_ipmovie_chunk(IPMVEContext *s, ByteIOContext *pb,
         case OPCODE_UNKNOWN_14:
         case OPCODE_UNKNOWN_15:
             debug_ipmovie("unknown (but documented) opcode %02X\n", opcode_type);
-            url_fseek(pb, opcode_size, SEEK_CUR);
+            avio_skip(pb, opcode_size);
             break;
 
         case OPCODE_SEND_BUFFER:
             debug_ipmovie("send buffer\n");
-            url_fseek(pb, opcode_size, SEEK_CUR);
+            avio_skip(pb, opcode_size);
             break;
 
         case OPCODE_AUDIO_FRAME:
             debug_ipmovie("audio frame\n");
 
             /* log position and move on for now */
-            s->audio_chunk_offset = url_ftell(pb);
+            s->audio_chunk_offset = avio_tell(pb);
             s->audio_chunk_size = opcode_size;
-            url_fseek(pb, opcode_size, SEEK_CUR);
+            avio_skip(pb, opcode_size);
             break;
 
         case OPCODE_SILENCE_FRAME:
             debug_ipmovie("silence frame\n");
-            url_fseek(pb, opcode_size, SEEK_CUR);
+            avio_skip(pb, opcode_size);
             break;
 
         case OPCODE_INIT_VIDEO_MODE:
             debug_ipmovie("initialize video mode\n");
-            url_fseek(pb, opcode_size, SEEK_CUR);
+            avio_skip(pb, opcode_size);
             break;
 
         case OPCODE_CREATE_GRADIENT:
             debug_ipmovie("create gradient\n");
-            url_fseek(pb, opcode_size, SEEK_CUR);
+            avio_skip(pb, opcode_size);
             break;
 
         case OPCODE_SET_PALETTE:
@@ -434,7 +445,7 @@ static int process_ipmovie_chunk(IPMVEContext *s, ByteIOContext *pb,
                 chunk_type = CHUNK_BAD;
                 break;
             }
-            if (get_buffer(pb, scratch, opcode_size) != opcode_size) {
+            if (avio_read(pb, scratch, opcode_size) != opcode_size) {
                 chunk_type = CHUNK_BAD;
                 break;
             }
@@ -456,33 +467,32 @@ static int process_ipmovie_chunk(IPMVEContext *s, ByteIOContext *pb,
                 r = scratch[j++] * 4;
                 g = scratch[j++] * 4;
                 b = scratch[j++] * 4;
-                s->palette_control.palette[i] = (r << 16) | (g << 8) | (b);
+                s->palette[i] = (r << 16) | (g << 8) | (b);
             }
-            /* indicate a palette change */
-            s->palette_control.palette_changed = 1;
+            s->has_palette = 1;
             break;
 
         case OPCODE_SET_PALETTE_COMPRESSED:
             debug_ipmovie("set palette compressed\n");
-            url_fseek(pb, opcode_size, SEEK_CUR);
+            avio_skip(pb, opcode_size);
             break;
 
         case OPCODE_SET_DECODING_MAP:
             debug_ipmovie("set decoding map\n");
 
             /* log position and move on for now */
-            s->decode_map_chunk_offset = url_ftell(pb);
+            s->decode_map_chunk_offset = avio_tell(pb);
             s->decode_map_chunk_size = opcode_size;
-            url_fseek(pb, opcode_size, SEEK_CUR);
+            avio_skip(pb, opcode_size);
             break;
 
         case OPCODE_VIDEO_DATA:
             debug_ipmovie("set video data\n");
 
             /* log position and move on for now */
-            s->video_chunk_offset = url_ftell(pb);
+            s->video_chunk_offset = avio_tell(pb);
             s->video_chunk_size = opcode_size;
-            url_fseek(pb, opcode_size, SEEK_CUR);
+            avio_skip(pb, opcode_size);
             break;
 
         default:
@@ -494,7 +504,7 @@ static int process_ipmovie_chunk(IPMVEContext *s, ByteIOContext *pb,
     }
 
     /* make a note of where the stream is sitting */
-    s->next_chunk_offset = url_ftell(pb);
+    s->next_chunk_offset = avio_tell(pb);
 
     /* dispatch the first of any pending packets */
     if ((chunk_type == CHUNK_VIDEO) || (chunk_type == CHUNK_AUDIO_ONLY))
@@ -521,18 +531,18 @@ static int ipmovie_read_header(AVFormatContext *s,
                                AVFormatParameters *ap)
 {
     IPMVEContext *ipmovie = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVPacket pkt;
     AVStream *st;
     unsigned char chunk_preamble[CHUNK_PREAMBLE_SIZE];
     int chunk_type;
     uint8_t signature_buffer[sizeof(signature)];
 
-    get_buffer(pb, signature_buffer, sizeof(signature_buffer));
+    avio_read(pb, signature_buffer, sizeof(signature_buffer));
     while (memcmp(signature_buffer, signature, sizeof(signature))) {
         memmove(signature_buffer, signature_buffer + 1, sizeof(signature_buffer) - 1);
-        signature_buffer[sizeof(signature_buffer) - 1] = get_byte(pb);
-        if (url_feof(pb))
+        signature_buffer[sizeof(signature_buffer) - 1] = avio_r8(pb);
+        if (pb->eof_reached)
             return AVERROR_EOF;
     }
     /* initialize private context members */
@@ -541,7 +551,7 @@ static int ipmovie_read_header(AVFormatContext *s,
     ipmovie->decode_map_chunk_offset = 0;
 
     /* on the first read, this will position the stream at the first chunk */
-    ipmovie->next_chunk_offset = url_ftell(pb) + 4;
+    ipmovie->next_chunk_offset = avio_tell(pb) + 4;
 
     /* process the first chunk which should be CHUNK_INIT_VIDEO */
     if (process_ipmovie_chunk(ipmovie, pb, &pkt) != CHUNK_INIT_VIDEO)
@@ -549,11 +559,11 @@ static int ipmovie_read_header(AVFormatContext *s,
 
     /* peek ahead to the next chunk-- if it is an init audio chunk, process
      * it; if it is the first video chunk, this is a silent file */
-    if (get_buffer(pb, chunk_preamble, CHUNK_PREAMBLE_SIZE) !=
+    if (avio_read(pb, chunk_preamble, CHUNK_PREAMBLE_SIZE) !=
         CHUNK_PREAMBLE_SIZE)
         return AVERROR(EIO);
     chunk_type = AV_RL16(&chunk_preamble[2]);
-    url_fseek(pb, -CHUNK_PREAMBLE_SIZE, SEEK_CUR);
+    avio_seek(pb, -CHUNK_PREAMBLE_SIZE, SEEK_CUR);
 
     if (chunk_type == CHUNK_VIDEO)
         ipmovie->audio_type = CODEC_ID_NONE;  /* no audio */
@@ -573,9 +583,6 @@ static int ipmovie_read_header(AVFormatContext *s,
     st->codec->height = ipmovie->video_height;
     st->codec->bits_per_coded_sample = ipmovie->video_bpp;
 
-    /* palette considerations */
-    st->codec->palctrl = &ipmovie->palette_control;
-
     if (ipmovie->audio_type) {
         st = av_new_stream(s, 0);
         if (!st)
@@ -602,7 +609,7 @@ static int ipmovie_read_packet(AVFormatContext *s,
                                AVPacket *pkt)
 {
     IPMVEContext *ipmovie = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int ret;
 
     ret = process_ipmovie_chunk(ipmovie, pb, pkt);
@@ -620,7 +627,7 @@ static int ipmovie_read_packet(AVFormatContext *s,
     return ret;
 }
 
-AVInputFormat ipmovie_demuxer = {
+AVInputFormat ff_ipmovie_demuxer = {
     "ipmovie",
     NULL_IF_CONFIG_SMALL("Interplay MVE format"),
     sizeof(IPMVEContext),
diff --git a/libavformat/isom.c b/libavformat/isom.c
index a6e67e2..c65f931 100644
--- a/libavformat/isom.c
+++ b/libavformat/isom.c
@@ -4,26 +4,31 @@
  * Copyright (c) 2002 Francois Revol <revol at free.fr>
  * Copyright (c) 2006 Baptiste Coudurier <baptiste.coudurier at free.fr>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+//#define DEBUG
+
 #include "avformat.h"
-#include "riff.h"
+#include "internal.h"
 #include "isom.h"
+#include "riff.h"
+#include "libavcodec/mpeg4audio.h"
+#include "libavcodec/mpegaudiodata.h"
 
 /* http://www.mp4ra.org */
 /* ordered by muxing preference */
@@ -67,6 +72,17 @@ const AVCodecTag codec_movvideo_tags[] = {
     { CODEC_ID_RAWVIDEO, MKTAG('2', 'v', 'u', 'y') }, /* UNCOMPRESSED 8BIT 4:2:2 */
     { CODEC_ID_RAWVIDEO, MKTAG('y', 'u', 'v', 's') }, /* same as 2vuy but byte swapped */
 
+    { CODEC_ID_RAWVIDEO, MKTAG('L', '5', '5', '5') },
+    { CODEC_ID_RAWVIDEO, MKTAG('L', '5', '6', '5') },
+    { CODEC_ID_RAWVIDEO, MKTAG('B', '5', '6', '5') },
+    { CODEC_ID_RAWVIDEO, MKTAG('2', '4', 'B', 'G') },
+    { CODEC_ID_RAWVIDEO, MKTAG('B', 'G', 'R', 'A') },
+    { CODEC_ID_RAWVIDEO, MKTAG('R', 'G', 'B', 'A') },
+    { CODEC_ID_RAWVIDEO, MKTAG('A', 'B', 'G', 'R') },
+    { CODEC_ID_RAWVIDEO, MKTAG('b', '1', '6', 'g') },
+    { CODEC_ID_RAWVIDEO, MKTAG('b', '4', '8', 'r') },
+
+    { CODEC_ID_R10K,   MKTAG('R', '1', '0', 'k') }, /* UNCOMPRESSED 10BIT RGB */
     { CODEC_ID_R210,   MKTAG('r', '2', '1', '0') }, /* UNCOMPRESSED 10BIT RGB */
     { CODEC_ID_V210,   MKTAG('v', '2', '1', '0') }, /* UNCOMPRESSED 10BIT 4:2:2 */
 
@@ -118,9 +134,15 @@ const AVCodecTag codec_movvideo_tags[] = {
     { CODEC_ID_RAWVIDEO, MKTAG('W', 'R', 'A', 'W') },
 
     { CODEC_ID_H264, MKTAG('a', 'v', 'c', '1') }, /* AVC-1/H.264 */
+    { CODEC_ID_H264, MKTAG('a', 'i', '5', '5') }, /* AVC Intra  50 / 1080 interlace */
+    { CODEC_ID_H264, MKTAG('a', 'i', '5', 'q') }, /* AVC Intra  50 /  720 */
+    { CODEC_ID_H264, MKTAG('a', 'i', '1', '5') }, /* AVC Intra 100 / 1080 interlace */
+    { CODEC_ID_H264, MKTAG('a', 'i', '1', 'q') }, /* AVC Intra 100 /  720 */
+    { CODEC_ID_H264, MKTAG('a', 'i', '1', '2') }, /* AVC Intra 100 / 1080 */
 
+    { CODEC_ID_MPEG1VIDEO, MKTAG('m', '1', 'v', '1') }, /* Apple MPEG-1 Camcorder */
     { CODEC_ID_MPEG1VIDEO, MKTAG('m', 'p', 'e', 'g') }, /* MPEG */
-    { CODEC_ID_MPEG1VIDEO, MKTAG('m', '1', 'v', '1') },
+    { CODEC_ID_MPEG2VIDEO, MKTAG('m', '2', 'v', '1') }, /* Apple MPEG-2 Camcorder */
     { CODEC_ID_MPEG2VIDEO, MKTAG('h', 'd', 'v', '1') }, /* MPEG2 HDV 720p30 */
     { CODEC_ID_MPEG2VIDEO, MKTAG('h', 'd', 'v', '2') }, /* MPEG2 HDV 1080i60 */
     { CODEC_ID_MPEG2VIDEO, MKTAG('h', 'd', 'v', '3') }, /* MPEG2 HDV 1080i50 */
@@ -134,6 +156,8 @@ const AVCodecTag codec_movvideo_tags[] = {
     { CODEC_ID_MPEG2VIDEO, MKTAG('m', 'x', '4', 'p') }, /* MPEG2 IMX PAL 625/50 40mb/s produced by FCP */
     { CODEC_ID_MPEG2VIDEO, MKTAG('m', 'x', '3', 'n') }, /* MPEG2 IMX NTSC 525/60 30mb/s produced by FCP */
     { CODEC_ID_MPEG2VIDEO, MKTAG('m', 'x', '3', 'p') }, /* MPEG2 IMX PAL 625/50 30mb/s produced by FCP */
+    { CODEC_ID_MPEG2VIDEO, MKTAG('x', 'd', '5', '4') }, /* XDCAM HD422 720p24 CBR */
+    { CODEC_ID_MPEG2VIDEO, MKTAG('x', 'd', '5', '5') }, /* XDCAM HD422 720p25 CBR */
     { CODEC_ID_MPEG2VIDEO, MKTAG('x', 'd', '5', '9') }, /* XDCAM HD422 720p60 CBR */
     { CODEC_ID_MPEG2VIDEO, MKTAG('x', 'd', '5', 'a') }, /* XDCAM HD422 720p50 CBR */
     { CODEC_ID_MPEG2VIDEO, MKTAG('x', 'd', '5', 'b') }, /* XDCAM HD422 1080i60 CBR */
@@ -157,7 +181,6 @@ const AVCodecTag codec_movvideo_tags[] = {
     { CODEC_ID_MPEG2VIDEO, MKTAG('x', 'd', 'v', 'e') }, /* XDCAM EX 1080p25 VBR */
     { CODEC_ID_MPEG2VIDEO, MKTAG('x', 'd', 'v', 'f') }, /* XDCAM EX 1080p30 VBR */
     { CODEC_ID_MPEG2VIDEO, MKTAG('A', 'V', 'm', 'p') }, /* AVID IMX PAL */
-    { CODEC_ID_MPEG2VIDEO, MKTAG('m', '2', 'v', '1') },
 
     { CODEC_ID_JPEG2000, MKTAG('m', 'j', 'p', '2') }, /* JPEG 2000 produced by FCP */
 
@@ -176,6 +199,12 @@ const AVCodecTag codec_movvideo_tags[] = {
     { CODEC_ID_SGI,   MKTAG('s', 'g', 'i', ' ') }, /* SGI  */
     { CODEC_ID_DPX,   MKTAG('d', 'p', 'x', ' ') }, /* DPX */
 
+    { CODEC_ID_PRORES, MKTAG('a', 'p', 'c', 'h') }, /* Apple ProRes 422 High Quality */
+    { CODEC_ID_PRORES, MKTAG('a', 'p', 'c', 'n') }, /* Apple ProRes 422 Standard Definition */
+    { CODEC_ID_PRORES, MKTAG('a', 'p', 'c', 's') }, /* Apple ProRes 422 LT */
+    { CODEC_ID_PRORES, MKTAG('a', 'p', 'c', 'o') }, /* Apple ProRes 422 Proxy */
+    { CODEC_ID_PRORES, MKTAG('a', 'p', '4', 'h') }, /* Apple ProRes 4444 */
+
     { CODEC_ID_NONE, 0 },
 };
 
@@ -224,6 +253,7 @@ const AVCodecTag codec_movaudio_tags[] = {
     { CODEC_ID_QCELP, MKTAG('Q','c','l','q') },
     { CODEC_ID_QCELP, MKTAG('s','q','c','p') }, /* ISO Media fourcc */
 
+    { CODEC_ID_QDMC, MKTAG('Q', 'D', 'M', 'C') }, /* QDMC */
     { CODEC_ID_QDM2, MKTAG('Q', 'D', 'M', '2') }, /* QDM2 */
 
     { CODEC_ID_DVAUDIO, MKTAG('v', 'd', 'v', 'a') },
@@ -314,3 +344,79 @@ int ff_mov_lang_to_iso639(unsigned code, char to[4])
     memcpy(to, mov_mdhd_language_map[code], 4);
     return 1;
 }
+
+int ff_mp4_read_descr_len(AVIOContext *pb)
+{
+    int len = 0;
+    int count = 4;
+    while (count--) {
+        int c = avio_r8(pb);
+        len = (len << 7) | (c & 0x7f);
+        if (!(c & 0x80))
+            break;
+    }
+    return len;
+}
+
+int ff_mp4_read_descr(AVFormatContext *fc, AVIOContext *pb, int *tag)
+{
+    int len;
+    *tag = avio_r8(pb);
+    len = ff_mp4_read_descr_len(pb);
+    av_dlog(fc, "MPEG4 description: tag=0x%02x len=%d\n", *tag, len);
+    return len;
+}
+
+static const AVCodecTag mp4_audio_types[] = {
+    { CODEC_ID_MP3ON4, AOT_PS   }, /* old mp3on4 draft */
+    { CODEC_ID_MP3ON4, AOT_L1   }, /* layer 1 */
+    { CODEC_ID_MP3ON4, AOT_L2   }, /* layer 2 */
+    { CODEC_ID_MP3ON4, AOT_L3   }, /* layer 3 */
+    { CODEC_ID_MP4ALS, AOT_ALS  }, /* MPEG-4 ALS */
+    { CODEC_ID_NONE,   AOT_NULL },
+};
+
+int ff_mp4_read_dec_config_descr(AVFormatContext *fc, AVStream *st, AVIOContext *pb)
+{
+    int len, tag;
+    int object_type_id = avio_r8(pb);
+    avio_r8(pb); /* stream type */
+    avio_rb24(pb); /* buffer size db */
+    avio_rb32(pb); /* max bitrate */
+    avio_rb32(pb); /* avg bitrate */
+
+    st->codec->codec_id= ff_codec_get_id(ff_mp4_obj_type, object_type_id);
+    av_dlog(fc, "esds object type id 0x%02x\n", object_type_id);
+    len = ff_mp4_read_descr(fc, pb, &tag);
+    if (tag == MP4DecSpecificDescrTag) {
+        av_dlog(fc, "Specific MPEG4 header len=%d\n", len);
+        if((uint64_t)len > (1<<30))
+            return -1;
+        av_free(st->codec->extradata);
+        st->codec->extradata = av_mallocz(len + FF_INPUT_BUFFER_PADDING_SIZE);
+        if (!st->codec->extradata)
+            return AVERROR(ENOMEM);
+        avio_read(pb, st->codec->extradata, len);
+        st->codec->extradata_size = len;
+        if (st->codec->codec_id == CODEC_ID_AAC) {
+            MPEG4AudioConfig cfg;
+            ff_mpeg4audio_get_config(&cfg, st->codec->extradata,
+                                     st->codec->extradata_size);
+            st->codec->channels = cfg.channels;
+            if (cfg.object_type == 29 && cfg.sampling_index < 3) // old mp3on4
+                st->codec->sample_rate = ff_mpa_freq_tab[cfg.sampling_index];
+            else if (cfg.ext_sample_rate)
+                st->codec->sample_rate = cfg.ext_sample_rate;
+            else
+                st->codec->sample_rate = cfg.sample_rate;
+            av_dlog(fc, "mp4a config channels %d obj %d ext obj %d "
+                    "sample rate %d ext sample rate %d\n", st->codec->channels,
+                    cfg.object_type, cfg.ext_object_type,
+                    cfg.sample_rate, cfg.ext_sample_rate);
+            if (!(st->codec->codec_id = ff_codec_get_id(mp4_audio_types,
+                                                        cfg.object_type)))
+                st->codec->codec_id = CODEC_ID_AAC;
+        }
+    }
+    return 0;
+}
diff --git a/libavformat/isom.h b/libavformat/isom.h
index 92997a7..48e0bcf 100644
--- a/libavformat/isom.h
+++ b/libavformat/isom.h
@@ -4,20 +4,20 @@
  * copyright (c) 2002 Francois Revol <revol at free.fr>
  * copyright (c) 2006 Baptiste Coudurier <baptiste.coudurier at free.fr>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,7 +25,7 @@
 #define AVFORMAT_ISOM_H
 
 #include "avio.h"
-#include "riff.h"
+#include "internal.h"
 #include "dv.h"
 
 /* isom.c */
@@ -88,7 +88,7 @@ typedef struct {
 } MOVTrackExt;
 
 typedef struct MOVStreamContext {
-    ByteIOContext *pb;
+    AVIOContext *pb;
     int ffindex;          ///< AVStream index
     int next_chunk;
     unsigned int chunk_count;
@@ -123,6 +123,8 @@ typedef struct MOVStreamContext {
     int width;            ///< tkhd width
     int height;           ///< tkhd height
     int dts_shift;        ///< dts shift when ctts is negative
+    uint32_t palette[256];
+    int has_palette;
 } MOVStreamContext;
 
 typedef struct MOVContext {
@@ -141,8 +143,18 @@ typedef struct MOVContext {
     int chapter_track;
 } MOVContext;
 
-int ff_mp4_read_descr_len(ByteIOContext *pb);
-int ff_mov_read_esds(AVFormatContext *fc, ByteIOContext *pb, MOVAtom atom);
+int ff_mp4_read_descr_len(AVIOContext *pb);
+int ff_mp4_read_descr(AVFormatContext *fc, AVIOContext *pb, int *tag);
+int ff_mp4_read_dec_config_descr(AVFormatContext *fc, AVStream *st, AVIOContext *pb);
+
+#define MP4IODescrTag                   0x02
+#define MP4ESDescrTag                   0x03
+#define MP4DecConfigDescrTag            0x04
+#define MP4DecSpecificDescrTag          0x05
+
+int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb, MOVAtom atom);
 enum CodecID ff_mov_get_lpcm_codec_id(int bps, int flags);
 
+int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries);
+
 #endif /* AVFORMAT_ISOM_H */
diff --git a/libavformat/iss.c b/libavformat/iss.c
index 156af97..fe5203d 100644
--- a/libavformat/iss.c
+++ b/libavformat/iss.c
@@ -2,20 +2,20 @@
  * ISS (.iss) file demuxer
  * Copyright (c) 2008 Jaikrishnan Menon <realityman at gmx.net>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -39,12 +39,12 @@ typedef struct {
     int sample_start_pos;
 } IssDemuxContext;
 
-static void get_token(ByteIOContext *s, char *buf, int maxlen)
+static void get_token(AVIOContext *s, char *buf, int maxlen)
 {
     int i = 0;
     char c;
 
-    while ((c = get_byte(s))) {
+    while ((c = avio_r8(s))) {
         if(c == ' ')
             break;
         if (i < maxlen-1)
@@ -52,7 +52,7 @@ static void get_token(ByteIOContext *s, char *buf, int maxlen)
     }
 
     if(!c)
-        get_byte(s);
+        avio_r8(s);
 
     buf[i] = 0; /* Ensure null terminated, but may be truncated */
 }
@@ -68,7 +68,7 @@ static int iss_probe(AVProbeData *p)
 static av_cold int iss_read_header(AVFormatContext *s, AVFormatParameters *ap)
 {
     IssDemuxContext *iss = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVStream *st;
     char token[MAX_TOKEN_SIZE];
     int stereo, rate_divisor;
@@ -87,7 +87,7 @@ static av_cold int iss_read_header(AVFormatContext *s, AVFormatParameters *ap)
     get_token(pb, token, sizeof(token)); //Version ID
     get_token(pb, token, sizeof(token)); //Size
 
-    iss->sample_start_pos = url_ftell(pb);
+    iss->sample_start_pos = avio_tell(pb);
 
     st = av_new_stream(s, 0);
     if (!st)
@@ -116,13 +116,13 @@ static int iss_read_packet(AVFormatContext *s, AVPacket *pkt)
         return AVERROR(EIO);
 
     pkt->stream_index = 0;
-    pkt->pts = url_ftell(s->pb) - iss->sample_start_pos;
+    pkt->pts = avio_tell(s->pb) - iss->sample_start_pos;
     if(s->streams[0]->codec->channels > 0)
         pkt->pts /= s->streams[0]->codec->channels*2;
     return 0;
 }
 
-AVInputFormat iss_demuxer = {
+AVInputFormat ff_iss_demuxer = {
     "ISS",
     NULL_IF_CONFIG_SMALL("Funcom ISS format"),
     sizeof(IssDemuxContext),
diff --git a/libavformat/iv8.c b/libavformat/iv8.c
index 00ddcd4..22e60cf 100644
--- a/libavformat/iv8.c
+++ b/libavformat/iv8.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2009 Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -57,20 +57,20 @@ static int read_packet(AVFormatContext *s, AVPacket *pkt)
 {
     int ret, size, pts, type;
 retry:
-    type= get_be16(s->pb); // 257 or 258
-    size= get_be16(s->pb);
+    type= avio_rb16(s->pb); // 257 or 258
+    size= avio_rb16(s->pb);
 
-    get_be16(s->pb); //some flags, 0x80 indicates end of frame
-    get_be16(s->pb); //packet number
-    pts=get_be32(s->pb);
-    get_be32(s->pb); //6A 13 E3 88
+    avio_rb16(s->pb); //some flags, 0x80 indicates end of frame
+    avio_rb16(s->pb); //packet number
+    pts=avio_rb32(s->pb);
+    avio_rb32(s->pb); //6A 13 E3 88
 
     size -= 12;
     if(size<1)
         return -1;
 
     if(type==258){
-        url_fskip(s->pb, size);
+        avio_skip(s->pb, size);
         goto retry;
     }
 
@@ -84,7 +84,7 @@ retry:
     return ret;
 }
 
-AVInputFormat iv8_demuxer = {
+AVInputFormat ff_iv8_demuxer = {
     "iv8",
     NULL_IF_CONFIG_SMALL("A format generated by IndigoVision 8000 video server"),
     0,
diff --git a/libavformat/ivfdec.c b/libavformat/ivfdec.c
new file mode 100644
index 0000000..3901731
--- /dev/null
+++ b/libavformat/ivfdec.c
@@ -0,0 +1,91 @@
+/*
+ * Copyright (c) 2010 David Conrad
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "avformat.h"
+#include "riff.h"
+#include "libavutil/intreadwrite.h"
+
+static int probe(AVProbeData *p)
+{
+    if (AV_RL32(p->buf) == MKTAG('D','K','I','F')
+        && !AV_RL16(p->buf+4) && AV_RL16(p->buf+6) == 32)
+        return AVPROBE_SCORE_MAX-2;
+
+    return 0;
+}
+
+static int read_header(AVFormatContext *s, AVFormatParameters *ap)
+{
+    AVStream *st;
+    AVRational time_base;
+
+    avio_rl32(s->pb); // DKIF
+    avio_rl16(s->pb); // version
+    avio_rl16(s->pb); // header size
+
+    st = av_new_stream(s, 0);
+    if (!st)
+        return AVERROR(ENOMEM);
+
+
+    st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
+    st->codec->codec_tag  = avio_rl32(s->pb);
+    st->codec->codec_id   = ff_codec_get_id(ff_codec_bmp_tags, st->codec->codec_tag);
+    st->codec->width      = avio_rl16(s->pb);
+    st->codec->height     = avio_rl16(s->pb);
+    time_base.den         = avio_rl32(s->pb);
+    time_base.num         = avio_rl32(s->pb);
+    st->duration          = avio_rl64(s->pb);
+
+    st->need_parsing      = AVSTREAM_PARSE_HEADERS;
+
+    if (!time_base.den || !time_base.num) {
+        av_log(s, AV_LOG_ERROR, "Invalid frame rate\n");
+        return AVERROR_INVALIDDATA;
+    }
+
+    av_set_pts_info(st, 64, time_base.num, time_base.den);
+
+    return 0;
+}
+
+static int read_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    int ret, size = avio_rl32(s->pb);
+    int64_t   pts = avio_rl64(s->pb);
+
+    ret = av_get_packet(s->pb, pkt, size);
+    pkt->stream_index = 0;
+    pkt->pts          = pts;
+    pkt->pos         -= 12;
+
+    return ret;
+}
+
+AVInputFormat ff_ivf_demuxer = {
+    "ivf",
+    NULL_IF_CONFIG_SMALL("On2 IVF"),
+    0,
+    probe,
+    read_header,
+    read_packet,
+    .flags= AVFMT_GENERIC_INDEX,
+    .codec_tag = (const AVCodecTag*[]){ff_codec_bmp_tags, 0},
+};
diff --git a/libavformat/ivfenc.c b/libavformat/ivfenc.c
new file mode 100644
index 0000000..55ce586
--- /dev/null
+++ b/libavformat/ivfenc.c
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) 2010 Reimar Döffinger
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+#include "avformat.h"
+#include "libavutil/intreadwrite.h"
+
+static int ivf_write_header(AVFormatContext *s)
+{
+    AVCodecContext *ctx;
+    AVIOContext *pb = s->pb;
+
+    if (s->nb_streams != 1) {
+        av_log(s, AV_LOG_ERROR, "Format supports only exactly one video stream\n");
+        return AVERROR(EINVAL);
+    }
+    ctx = s->streams[0]->codec;
+    if (ctx->codec_type != AVMEDIA_TYPE_VIDEO || ctx->codec_id != CODEC_ID_VP8) {
+        av_log(s, AV_LOG_ERROR, "Currently only VP8 is supported!\n");
+        return AVERROR(EINVAL);
+    }
+    avio_write(pb, "DKIF", 4);
+    avio_wl16(pb, 0); // version
+    avio_wl16(pb, 32); // header length
+    avio_wl32(pb, ctx->codec_tag ? ctx->codec_tag : AV_RL32("VP80"));
+    avio_wl16(pb, ctx->width);
+    avio_wl16(pb, ctx->height);
+    avio_wl32(pb, s->streams[0]->time_base.den);
+    avio_wl32(pb, s->streams[0]->time_base.num);
+    avio_wl64(pb, s->streams[0]->duration); // TODO: duration or number of frames?!?
+
+    return 0;
+}
+
+static int ivf_write_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    AVIOContext *pb = s->pb;
+    avio_wl32(pb, pkt->size);
+    avio_wl64(pb, pkt->pts);
+    avio_write(pb, pkt->data, pkt->size);
+    avio_flush(pb);
+
+    return 0;
+}
+
+AVOutputFormat ff_ivf_muxer = {
+    .name = "ivf",
+    .long_name = NULL_IF_CONFIG_SMALL("On2 IVF"),
+    .extensions = "ivf",
+    .audio_codec = CODEC_ID_NONE,
+    .video_codec = CODEC_ID_VP8,
+    .write_header = ivf_write_header,
+    .write_packet = ivf_write_packet,
+};
diff --git a/libavformat/jvdec.c b/libavformat/jvdec.c
new file mode 100644
index 0000000..d4008f7
--- /dev/null
+++ b/libavformat/jvdec.c
@@ -0,0 +1,225 @@
+/*
+ * Bitmap Brothers JV demuxer
+ * Copyright (c) 2005, 2011 Peter Ross <pross at xvid.org>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * Bitmap Brothers JV demuxer
+ * @author Peter Ross <pross at xvid.org>
+ */
+
+#include "libavutil/intreadwrite.h"
+#include "avformat.h"
+
+#define JV_PREAMBLE_SIZE 5
+
+typedef struct {
+    int audio_size;    /** audio packet size (bytes) */
+    int video_size;    /** video packet size (bytes) */
+    int palette_size;  /** palette size (bytes) */
+    int video_type;    /** per-frame video compression type */
+} JVFrame;
+
+typedef struct {
+    JVFrame *frames;
+    enum {
+        JV_AUDIO = 0,
+        JV_VIDEO,
+        JV_PADDING
+    } state;
+    int64_t pts;
+} JVDemuxContext;
+
+#define MAGIC " Compression by John M Phillips Copyright (C) 1995 The Bitmap Brothers Ltd."
+
+static int read_probe(AVProbeData *pd)
+{
+    if (pd->buf[0] == 'J' && pd->buf[1] == 'V' &&
+        !memcmp(pd->buf + 4, MAGIC, FFMIN(strlen(MAGIC), pd->buf_size - 4)))
+        return AVPROBE_SCORE_MAX;
+    return 0;
+}
+
+static int read_header(AVFormatContext *s,
+                       AVFormatParameters *ap)
+{
+    JVDemuxContext *jv = s->priv_data;
+    AVIOContext *pb = s->pb;
+    AVStream *vst, *ast;
+    int64_t audio_pts = 0;
+    int64_t offset;
+    int i;
+
+    avio_skip(pb, 80);
+
+    ast = av_new_stream(s, 0);
+    vst = av_new_stream(s, 1);
+    if (!ast || !vst)
+        return AVERROR(ENOMEM);
+
+    vst->codec->codec_type  = AVMEDIA_TYPE_VIDEO;
+    vst->codec->codec_id    = CODEC_ID_JV;
+    vst->codec->codec_tag   = 0; /* no fourcc */
+    vst->codec->width       = avio_rl16(pb);
+    vst->codec->height      = avio_rl16(pb);
+    vst->nb_frames          =
+    ast->nb_index_entries   = avio_rl16(pb);
+    av_set_pts_info(vst, 64, avio_rl16(pb), 1000);
+
+    avio_skip(pb, 4);
+
+    ast->codec->codec_type  = AVMEDIA_TYPE_AUDIO;
+    ast->codec->codec_id    = CODEC_ID_PCM_U8;
+    ast->codec->codec_tag   = 0; /* no fourcc */
+    ast->codec->sample_rate = avio_rl16(pb);
+    ast->codec->channels    = 1;
+    av_set_pts_info(ast, 64, 1, ast->codec->sample_rate);
+
+    avio_skip(pb, 10);
+
+    ast->index_entries = av_malloc(ast->nb_index_entries * sizeof(*ast->index_entries));
+    if (!ast->index_entries)
+        return AVERROR(ENOMEM);
+
+    jv->frames = av_malloc(ast->nb_index_entries * sizeof(JVFrame));
+    if (!jv->frames)
+        return AVERROR(ENOMEM);
+
+    offset = 0x68 + ast->nb_index_entries * 16;
+    for(i = 0; i < ast->nb_index_entries; i++) {
+        AVIndexEntry *e   = ast->index_entries + i;
+        JVFrame      *jvf = jv->frames + i;
+
+        /* total frame size including audio, video, palette data and padding */
+        e->size         = avio_rl32(pb);
+        e->timestamp    = i;
+        e->pos          = offset;
+        offset         += e->size;
+
+        jvf->audio_size = avio_rl32(pb);
+        jvf->video_size = avio_rl32(pb);
+        jvf->palette_size = avio_r8(pb) ? 768 : 0;
+        jvf->video_size = FFMIN(FFMAX(jvf->video_size, 0),
+                                INT_MAX - JV_PREAMBLE_SIZE - jvf->palette_size);
+        if (avio_r8(pb))
+             av_log(s, AV_LOG_WARNING, "unsupported audio codec\n");
+        jvf->video_type = avio_r8(pb);
+        avio_skip(pb, 1);
+
+        e->timestamp = jvf->audio_size ? audio_pts : AV_NOPTS_VALUE;
+        audio_pts += jvf->audio_size;
+
+        e->flags = jvf->video_type != 1 ? AVINDEX_KEYFRAME : 0;
+    }
+
+    jv->state = JV_AUDIO;
+    return 0;
+}
+
+static int read_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    JVDemuxContext *jv = s->priv_data;
+    AVIOContext *pb = s->pb;
+    AVStream *ast = s->streams[0];
+
+    while (!s->pb->eof_reached && jv->pts < ast->nb_index_entries) {
+        const AVIndexEntry *e   = ast->index_entries + jv->pts;
+        const JVFrame      *jvf = jv->frames + jv->pts;
+
+        switch(jv->state) {
+        case JV_AUDIO:
+            jv->state++;
+            if (jvf->audio_size ) {
+                if (av_get_packet(s->pb, pkt, jvf->audio_size) < 0)
+                    return AVERROR(ENOMEM);
+                pkt->stream_index = 0;
+                pkt->pts          = e->timestamp;
+                pkt->flags       |= AV_PKT_FLAG_KEY;
+                return 0;
+            }
+        case JV_VIDEO:
+            jv->state++;
+            if (jvf->video_size || jvf->palette_size) {
+                int size = jvf->video_size + jvf->palette_size;
+                if (av_new_packet(pkt, size + JV_PREAMBLE_SIZE))
+                    return AVERROR(ENOMEM);
+
+                AV_WL32(pkt->data, jvf->video_size);
+                pkt->data[4]      = jvf->video_type;
+                if (avio_read(pb, pkt->data + JV_PREAMBLE_SIZE, size) < 0)
+                    return AVERROR(EIO);
+
+                pkt->size         = size + JV_PREAMBLE_SIZE;
+                pkt->stream_index = 1;
+                pkt->pts          = jv->pts;
+                if (jvf->video_type != 1)
+                    pkt->flags |= AV_PKT_FLAG_KEY;
+                return 0;
+            }
+        case JV_PADDING:
+            avio_skip(pb, FFMAX(e->size - jvf->audio_size - jvf->video_size
+                                        - jvf->palette_size, 0));
+            jv->state = JV_AUDIO;
+            jv->pts++;
+        }
+    }
+
+    return AVERROR(EIO);
+}
+
+static int read_seek(AVFormatContext *s, int stream_index,
+                     int64_t ts, int flags)
+{
+    JVDemuxContext *jv = s->priv_data;
+    AVStream *ast = s->streams[0];
+    int i;
+
+    if (flags & (AVSEEK_FLAG_BYTE|AVSEEK_FLAG_FRAME))
+        return AVERROR(ENOSYS);
+
+    switch(stream_index) {
+    case 0:
+        i = av_index_search_timestamp(ast, ts, flags);
+        break;
+    case 1:
+        i = ts;
+        break;
+    default:
+        return 0;
+    }
+
+    if (i < 0 || i >= ast->nb_index_entries)
+        return 0;
+
+    jv->state = JV_AUDIO;
+    jv->pts   = i;
+    avio_seek(s->pb, ast->index_entries[i].pos, SEEK_SET);
+    return 0;
+}
+
+AVInputFormat ff_jv_demuxer = {
+    .name           = "jv",
+    .long_name      = NULL_IF_CONFIG_SMALL("Bitmap Brothers JV"),
+    .priv_data_size = sizeof(JVDemuxContext),
+    .read_probe     = read_probe,
+    .read_header    = read_header,
+    .read_packet    = read_packet,
+    .read_seek      = read_seek,
+};
diff --git a/libavformat/libavformat.v b/libavformat/libavformat.v
index da2311e..0ec1c3c 100644
--- a/libavformat/libavformat.v
+++ b/libavformat/libavformat.v
@@ -1,3 +1,7 @@
 LIBAVFORMAT_$MAJOR {
         global: *;
+        local:
+                ff_*_demuxer;
+                ff_*_muxer;
+                ff_*_protocol;
 };
diff --git a/libavformat/libnut.c b/libavformat/libnut.c
index 4543df7..76a621a 100644
--- a/libavformat/libnut.c
+++ b/libavformat/libnut.c
@@ -2,20 +2,20 @@
  * NUT (de)muxing via libnut
  * copyright (c) 2006 Oded Shimon <ods15 at ods15.dyndns.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -46,15 +46,15 @@ static const AVCodecTag nut_tags[] = {
 
 #if CONFIG_LIBNUT_MUXER
 static int av_write(void * h, size_t len, const uint8_t * buf) {
-    ByteIOContext * bc = h;
-    put_buffer(bc, buf, len);
-    //put_flush_packet(bc);
+    AVIOContext * bc = h;
+    avio_write(bc, buf, len);
+    //avio_flush(bc);
     return len;
 }
 
 static int nut_write_header(AVFormatContext * avf) {
     NUTContext * priv = avf->priv_data;
-    ByteIOContext * bc = avf->pb;
+    AVIOContext * bc = avf->pb;
     nut_muxer_opts_tt mopts = {
         .output = {
             .priv = bc,
@@ -137,12 +137,12 @@ static int nut_write_packet(AVFormatContext * avf, AVPacket * pkt) {
 }
 
 static int nut_write_trailer(AVFormatContext * avf) {
-    ByteIOContext * bc = avf->pb;
+    AVIOContext * bc = avf->pb;
     NUTContext * priv = avf->priv_data;
     int i;
 
     nut_muxer_uninit_reorder(priv->nut);
-    put_flush_packet(bc);
+    avio_flush(bc);
 
     for(i = 0; priv->s[i].type != -1; i++ ) av_freep(&priv->s[i].fourcc);
     av_freep(&priv->s);
@@ -150,7 +150,7 @@ static int nut_write_trailer(AVFormatContext * avf) {
     return 0;
 }
 
-AVOutputFormat libnut_muxer = {
+AVOutputFormat ff_libnut_muxer = {
     "libnut",
     "nut format",
     "video/x-nut",
@@ -172,22 +172,22 @@ static int nut_probe(AVProbeData *p) {
 }
 
 static size_t av_read(void * h, size_t len, uint8_t * buf) {
-    ByteIOContext * bc = h;
-    return get_buffer(bc, buf, len);
+    AVIOContext * bc = h;
+    return avio_read(bc, buf, len);
 }
 
 static off_t av_seek(void * h, long long pos, int whence) {
-    ByteIOContext * bc = h;
+    AVIOContext * bc = h;
     if (whence == SEEK_END) {
-        pos = url_fsize(bc) + pos;
+        pos = avio_size(bc) + pos;
         whence = SEEK_SET;
     }
-    return url_fseek(bc, pos, whence);
+    return avio_seek(bc, pos, whence);
 }
 
 static int nut_read_header(AVFormatContext * avf, AVFormatParameters * ap) {
     NUTContext * priv = avf->priv_data;
-    ByteIOContext * bc = avf->pb;
+    AVIOContext * bc = avf->pb;
     nut_demuxer_opts_tt dopts = {
         .input = {
             .priv = bc,
@@ -272,7 +272,7 @@ static int nut_read_packet(AVFormatContext * avf, AVPacket * pkt) {
     if (pd.flags & NUT_FLAG_KEY) pkt->flags |= AV_PKT_FLAG_KEY;
     pkt->pts = pd.pts;
     pkt->stream_index = pd.stream;
-    pkt->pos = url_ftell(avf->pb);
+    pkt->pos = avio_tell(avf->pb);
 
     ret = nut_read_frame(priv->nut, &pd.len, pkt->data);
 
@@ -297,7 +297,7 @@ static int nut_read_close(AVFormatContext *s) {
     return 0;
 }
 
-AVInputFormat libnut_demuxer = {
+AVInputFormat ff_libnut_demuxer = {
     "libnut",
     NULL_IF_CONFIG_SMALL("NUT format"),
     sizeof(NUTContext),
diff --git a/libavformat/librtmp.c b/libavformat/librtmp.c
index d765102..db5cc98 100644
--- a/libavformat/librtmp.c
+++ b/libavformat/librtmp.c
@@ -2,20 +2,20 @@
  * RTMP network protocol
  * Copyright (c) 2010 Howard Chu
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,6 +25,7 @@
  */
 
 #include "avformat.h"
+#include "url.h"
 
 #include <librtmp/rtmp.h>
 #include <librtmp/log.h>
@@ -55,7 +56,7 @@ static int rtmp_close(URLContext *s)
 }
 
 /**
- * Opens RTMP connection and verifies that the stream can be played.
+ * Open RTMP connection and verify that the stream can be played.
  *
  * URL syntax: rtmp://server[:port][/app][/playpath][ keyword=value]...
  *             where 'app' is first one or two directories in the path
@@ -93,8 +94,8 @@ static int rtmp_open(URLContext *s, const char *uri, int flags)
         goto fail;
     }
 
-    if (flags & URL_WRONLY)
-        r->Link.protocol |= RTMP_FEATURE_WRITE;
+    if (flags & AVIO_WRONLY)
+        RTMP_EnableWrite(r);
 
     if (!RTMP_Connect(r, NULL) || !RTMP_ConnectStream(r, 0)) {
         rc = -1;
@@ -109,7 +110,7 @@ fail:
     return rc;
 }
 
-static int rtmp_write(URLContext *s, uint8_t *buf, int size)
+static int rtmp_write(URLContext *s, const uint8_t *buf, int size)
 {
     RTMP *r = s->priv_data;
 
@@ -127,10 +128,7 @@ static int rtmp_read_pause(URLContext *s, int pause)
 {
     RTMP *r = s->priv_data;
 
-    if (pause)
-        r->m_pauseStamp =
-            r->m_channelTimestamp[r->m_mediaChannel];
-    if (!RTMP_SendPause(r, pause, r->m_pauseStamp))
+    if (!RTMP_Pause(r, pause))
         return -1;
     return 0;
 }
@@ -157,70 +155,60 @@ static int rtmp_get_file_handle(URLContext *s)
 {
     RTMP *r = s->priv_data;
 
-    return r->m_sb.sb_socket;
+    return RTMP_Socket(r);
 }
 
-URLProtocol rtmp_protocol = {
-    "rtmp",
-    rtmp_open,
-    rtmp_read,
-    rtmp_write,
-    NULL,                   /* seek */
-    rtmp_close,
-    NULL,                   /* next */
-    rtmp_read_pause,
-    rtmp_read_seek,
-    rtmp_get_file_handle
+URLProtocol ff_rtmp_protocol = {
+    .name                = "rtmp",
+    .url_open            = rtmp_open,
+    .url_read            = rtmp_read,
+    .url_write           = rtmp_write,
+    .url_close           = rtmp_close,
+    .url_read_pause      = rtmp_read_pause,
+    .url_read_seek       = rtmp_read_seek,
+    .url_get_file_handle = rtmp_get_file_handle
 };
 
-URLProtocol rtmpt_protocol = {
-    "rtmpt",
-    rtmp_open,
-    rtmp_read,
-    rtmp_write,
-    NULL,                   /* seek */
-    rtmp_close,
-    NULL,                   /* next */
-    rtmp_read_pause,
-    rtmp_read_seek,
-    rtmp_get_file_handle
+URLProtocol ff_rtmpt_protocol = {
+    .name                = "rtmpt",
+    .url_open            = rtmp_open,
+    .url_read            = rtmp_read,
+    .url_write           = rtmp_write,
+    .url_close           = rtmp_close,
+    .url_read_pause      = rtmp_read_pause,
+    .url_read_seek       = rtmp_read_seek,
+    .url_get_file_handle = rtmp_get_file_handle
 };
 
-URLProtocol rtmpe_protocol = {
-    "rtmpe",
-    rtmp_open,
-    rtmp_read,
-    rtmp_write,
-    NULL,                   /* seek */
-    rtmp_close,
-    NULL,                   /* next */
-    rtmp_read_pause,
-    rtmp_read_seek,
-    rtmp_get_file_handle
+URLProtocol ff_rtmpe_protocol = {
+    .name                = "rtmpe",
+    .url_open            = rtmp_open,
+    .url_read            = rtmp_read,
+    .url_write           = rtmp_write,
+    .url_close           = rtmp_close,
+    .url_read_pause      = rtmp_read_pause,
+    .url_read_seek       = rtmp_read_seek,
+    .url_get_file_handle = rtmp_get_file_handle
 };
 
-URLProtocol rtmpte_protocol = {
-    "rtmpte",
-    rtmp_open,
-    rtmp_read,
-    rtmp_write,
-    NULL,                   /* seek */
-    rtmp_close,
-    NULL,                   /* next */
-    rtmp_read_pause,
-    rtmp_read_seek,
-    rtmp_get_file_handle
+URLProtocol ff_rtmpte_protocol = {
+    .name                = "rtmpte",
+    .url_open            = rtmp_open,
+    .url_read            = rtmp_read,
+    .url_write           = rtmp_write,
+    .url_close           = rtmp_close,
+    .url_read_pause      = rtmp_read_pause,
+    .url_read_seek       = rtmp_read_seek,
+    .url_get_file_handle = rtmp_get_file_handle
 };
 
-URLProtocol rtmps_protocol = {
-    "rtmps",
-    rtmp_open,
-    rtmp_read,
-    rtmp_write,
-    NULL,                   /* seek */
-    rtmp_close,
-    NULL,                   /* next */
-    rtmp_read_pause,
-    rtmp_read_seek,
-    rtmp_get_file_handle
+URLProtocol ff_rtmps_protocol = {
+    .name                = "rtmps",
+    .url_open            = rtmp_open,
+    .url_read            = rtmp_read,
+    .url_write           = rtmp_write,
+    .url_close           = rtmp_close,
+    .url_read_pause      = rtmp_read_pause,
+    .url_read_seek       = rtmp_read_seek,
+    .url_get_file_handle = rtmp_get_file_handle
 };
diff --git a/libavformat/lmlm4.c b/libavformat/lmlm4.c
index c1397fb..eafc1b6 100644
--- a/libavformat/lmlm4.c
+++ b/libavformat/lmlm4.c
@@ -5,20 +5,20 @@
  * Due to a lack of sample files, only files with one channel are supported.
  * u-law and ADPCM audio are unsupported for the same reason.
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -78,13 +78,13 @@ static int lmlm4_read_header(AVFormatContext *s, AVFormatParameters *ap) {
 }
 
 static int lmlm4_read_packet(AVFormatContext *s, AVPacket *pkt) {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int ret;
     unsigned int frame_type, packet_size, padding, frame_size;
 
-    get_be16(pb);                       /* channel number */
-    frame_type  = get_be16(pb);
-    packet_size = get_be32(pb);
+    avio_rb16(pb);                       /* channel number */
+    frame_type  = avio_rb16(pb);
+    packet_size = avio_rb32(pb);
     padding     = -packet_size & 511;
     frame_size  = packet_size - 8;
 
@@ -100,7 +100,7 @@ static int lmlm4_read_packet(AVFormatContext *s, AVPacket *pkt) {
     if ((ret = av_get_packet(pb, pkt, frame_size)) <= 0)
         return AVERROR(EIO);
 
-    url_fskip(pb, padding);
+    avio_skip(pb, padding);
 
     switch (frame_type) {
         case LMLM4_I_FRAME:
@@ -117,7 +117,7 @@ static int lmlm4_read_packet(AVFormatContext *s, AVPacket *pkt) {
     return ret;
 }
 
-AVInputFormat lmlm4_demuxer = {
+AVInputFormat ff_lmlm4_demuxer = {
     "lmlm4",
     NULL_IF_CONFIG_SMALL("lmlm4 raw format"),
     0,
diff --git a/libavformat/lxfdec.c b/libavformat/lxfdec.c
new file mode 100644
index 0000000..0f7e426
--- /dev/null
+++ b/libavformat/lxfdec.c
@@ -0,0 +1,348 @@
+/*
+ * LXF demuxer
+ * Copyright (c) 2010 Tomas Härdin
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "libavutil/intreadwrite.h"
+#include "avformat.h"
+#include "riff.h"
+
+#define LXF_PACKET_HEADER_SIZE  60
+#define LXF_HEADER_DATA_SIZE    120
+#define LXF_IDENT               "LEITCH\0"
+#define LXF_IDENT_LENGTH        8
+#define LXF_SAMPLERATE          48000
+#define LXF_MAX_AUDIO_PACKET    (8008*15*4) ///< 15-channel 32-bit NTSC audio frame
+
+static const AVCodecTag lxf_tags[] = {
+    { CODEC_ID_MJPEG,       0 },
+    { CODEC_ID_MPEG1VIDEO,  1 },
+    { CODEC_ID_MPEG2VIDEO,  2 },    //MpMl, 4:2:0
+    { CODEC_ID_MPEG2VIDEO,  3 },    //MpPl, 4:2:2
+    { CODEC_ID_DVVIDEO,     4 },    //DV25
+    { CODEC_ID_DVVIDEO,     5 },    //DVCPRO
+    { CODEC_ID_DVVIDEO,     6 },    //DVCPRO50
+    { CODEC_ID_RAWVIDEO,    7 },    //PIX_FMT_ARGB, where alpha is used for chroma keying
+    { CODEC_ID_RAWVIDEO,    8 },    //16-bit chroma key
+    { CODEC_ID_MPEG2VIDEO,  9 },    //4:2:2 CBP ("Constrained Bytes per Gop")
+    { CODEC_ID_NONE,        0 },
+};
+
+typedef struct {
+    int channels;                       ///< number of audio channels. zero means no audio
+    uint8_t temp[LXF_MAX_AUDIO_PACKET]; ///< temp buffer for de-planarizing the audio data
+    int frame_number;                   ///< current video frame
+} LXFDemuxContext;
+
+static int lxf_probe(AVProbeData *p)
+{
+    if (!memcmp(p->buf, LXF_IDENT, LXF_IDENT_LENGTH))
+        return AVPROBE_SCORE_MAX;
+
+    return 0;
+}
+
+/**
+ * Verify the checksum of an LXF packet header
+ *
+ * @param[in] header the packet header to check
+ * @return zero if the checksum is OK, non-zero otherwise
+ */
+static int check_checksum(const uint8_t *header)
+{
+    int x;
+    uint32_t sum = 0;
+
+    for (x = 0; x < LXF_PACKET_HEADER_SIZE; x += 4)
+        sum += AV_RL32(&header[x]);
+
+    return sum;
+}
+
+/**
+ * Read input until we find the next ident. If found, copy it to the header buffer
+ *
+ * @param[out] header where to copy the ident to
+ * @return 0 if an ident was found, < 0 on I/O error
+ */
+static int sync(AVFormatContext *s, uint8_t *header)
+{
+    uint8_t buf[LXF_IDENT_LENGTH];
+    int ret;
+
+    if ((ret = avio_read(s->pb, buf, LXF_IDENT_LENGTH)) != LXF_IDENT_LENGTH)
+        return ret < 0 ? ret : AVERROR_EOF;
+
+    while (memcmp(buf, LXF_IDENT, LXF_IDENT_LENGTH)) {
+        if (s->pb->eof_reached)
+            return AVERROR_EOF;
+
+        memmove(buf, &buf[1], LXF_IDENT_LENGTH-1);
+        buf[LXF_IDENT_LENGTH-1] = avio_r8(s->pb);
+    }
+
+    memcpy(header, LXF_IDENT, LXF_IDENT_LENGTH);
+
+    return 0;
+}
+
+/**
+ * Read and checksum the next packet header
+ *
+ * @param[out] header the read packet header
+ * @param[out] format context dependent format information
+ * @return the size of the payload following the header or < 0 on failure
+ */
+static int get_packet_header(AVFormatContext *s, uint8_t *header, uint32_t *format)
+{
+    AVIOContext   *pb  = s->pb;
+    int track_size, samples, ret;
+    AVStream *st;
+
+    //find and read the ident
+    if ((ret = sync(s, header)) < 0)
+        return ret;
+
+    //read the rest of the packet header
+    if ((ret = avio_read(pb, header + LXF_IDENT_LENGTH,
+                          LXF_PACKET_HEADER_SIZE - LXF_IDENT_LENGTH)) !=
+                          LXF_PACKET_HEADER_SIZE - LXF_IDENT_LENGTH) {
+        return ret < 0 ? ret : AVERROR_EOF;
+    }
+
+    if (check_checksum(header))
+        av_log(s, AV_LOG_ERROR, "checksum error\n");
+
+    *format = AV_RL32(&header[32]);
+    ret     = AV_RL32(&header[36]);
+
+    //type
+    switch (AV_RL32(&header[16])) {
+    case 0:
+        //video
+        //skip VBI data and metadata
+        avio_skip(pb, (int64_t)(uint32_t)AV_RL32(&header[44]) +
+                      (int64_t)(uint32_t)AV_RL32(&header[52]));
+        break;
+    case 1:
+        //audio
+        if (!(st = s->streams[1])) {
+            av_log(s, AV_LOG_INFO, "got audio packet, but no audio stream present\n");
+            break;
+        }
+
+        //set codec based on specified audio bitdepth
+        //we only support tightly packed 16-, 20-, 24- and 32-bit PCM at the moment
+        *format                          = AV_RL32(&header[40]);
+        st->codec->bits_per_coded_sample = (*format >> 6) & 0x3F;
+
+        if (st->codec->bits_per_coded_sample != (*format & 0x3F)) {
+            av_log(s, AV_LOG_WARNING, "only tightly packed PCM currently supported\n");
+            return AVERROR_PATCHWELCOME;
+        }
+
+        switch (st->codec->bits_per_coded_sample) {
+        case 16: st->codec->codec_id = CODEC_ID_PCM_S16LE; break;
+        case 20: st->codec->codec_id = CODEC_ID_PCM_LXF;   break;
+        case 24: st->codec->codec_id = CODEC_ID_PCM_S24LE; break;
+        case 32: st->codec->codec_id = CODEC_ID_PCM_S32LE; break;
+        default:
+            av_log(s, AV_LOG_WARNING,
+                   "only 16-, 20-, 24- and 32-bit PCM currently supported\n");
+            return AVERROR_PATCHWELCOME;
+        }
+
+        track_size = AV_RL32(&header[48]);
+        samples = track_size * 8 / st->codec->bits_per_coded_sample;
+
+        //use audio packet size to determine video standard
+        //for NTSC we have one 8008-sample audio frame per five video frames
+        if (samples == LXF_SAMPLERATE * 5005 / 30000) {
+            av_set_pts_info(s->streams[0], 64, 1001, 30000);
+        } else {
+            //assume PAL, but warn if we don't have 1920 samples
+            if (samples != LXF_SAMPLERATE / 25)
+                av_log(s, AV_LOG_WARNING,
+                       "video doesn't seem to be PAL or NTSC. guessing PAL\n");
+
+            av_set_pts_info(s->streams[0], 64, 1, 25);
+        }
+
+        //TODO: warning if track mask != (1 << channels) - 1?
+        ret = av_popcount(AV_RL32(&header[44])) * track_size;
+
+        break;
+    default:
+        break;
+    }
+
+    return ret;
+}
+
+static int lxf_read_header(AVFormatContext *s, AVFormatParameters *ap)
+{
+    LXFDemuxContext *lxf = s->priv_data;
+    AVIOContext   *pb  = s->pb;
+    uint8_t header[LXF_PACKET_HEADER_SIZE], header_data[LXF_HEADER_DATA_SIZE];
+    int ret;
+    AVStream *st;
+    uint32_t format, video_params, disk_params;
+    uint16_t record_date, expiration_date;
+
+    if ((ret = get_packet_header(s, header, &format)) < 0)
+        return ret;
+
+    if (ret != LXF_HEADER_DATA_SIZE) {
+        av_log(s, AV_LOG_ERROR, "expected %d B size header, got %d\n",
+               LXF_HEADER_DATA_SIZE, ret);
+        return AVERROR_INVALIDDATA;
+    }
+
+    if ((ret = avio_read(pb, header_data, LXF_HEADER_DATA_SIZE)) != LXF_HEADER_DATA_SIZE)
+        return ret < 0 ? ret : AVERROR_EOF;
+
+    if (!(st = av_new_stream(s, 0)))
+        return AVERROR(ENOMEM);
+
+    st->duration          = AV_RL32(&header_data[32]);
+    video_params          = AV_RL32(&header_data[40]);
+    record_date           = AV_RL16(&header_data[56]);
+    expiration_date       = AV_RL16(&header_data[58]);
+    disk_params           = AV_RL32(&header_data[116]);
+
+    st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
+    st->codec->bit_rate   = 1000000 * ((video_params >> 14) & 0xFF);
+    st->codec->codec_tag  = video_params & 0xF;
+    st->codec->codec_id   = ff_codec_get_id(lxf_tags, st->codec->codec_tag);
+
+    av_log(s, AV_LOG_DEBUG, "record: %x = %i-%02i-%02i\n",
+           record_date, 1900 + (record_date & 0x7F), (record_date >> 7) & 0xF,
+           (record_date >> 11) & 0x1F);
+
+    av_log(s, AV_LOG_DEBUG, "expire: %x = %i-%02i-%02i\n",
+           expiration_date, 1900 + (expiration_date & 0x7F), (expiration_date >> 7) & 0xF,
+           (expiration_date >> 11) & 0x1F);
+
+    if ((video_params >> 22) & 1)
+        av_log(s, AV_LOG_WARNING, "VBI data not yet supported\n");
+
+    if ((lxf->channels = (disk_params >> 2) & 0xF)) {
+        if (!(st = av_new_stream(s, 1)))
+            return AVERROR(ENOMEM);
+
+        st->codec->codec_type  = AVMEDIA_TYPE_AUDIO;
+        st->codec->sample_rate = LXF_SAMPLERATE;
+        st->codec->channels    = lxf->channels;
+
+        av_set_pts_info(st, 64, 1, st->codec->sample_rate);
+    }
+
+    if (format == 1) {
+        //skip extended field data
+        avio_skip(s->pb, (uint32_t)AV_RL32(&header[40]));
+    }
+
+    return 0;
+}
+
+/**
+ * De-planerize the PCM data in lxf->temp
+ * FIXME: remove this once support for planar audio is added to libavcodec
+ *
+ * @param[out] out where to write the de-planerized data to
+ * @param[in] bytes the total size of the PCM data
+ */
+static void deplanarize(LXFDemuxContext *lxf, AVStream *ast, uint8_t *out, int bytes)
+{
+    int x, y, z, i, bytes_per_sample = ast->codec->bits_per_coded_sample >> 3;
+
+    for (z = i = 0; z < lxf->channels; z++)
+        for (y = 0; y < bytes / bytes_per_sample / lxf->channels; y++)
+            for (x = 0; x < bytes_per_sample; x++, i++)
+                out[x + bytes_per_sample*(z + y*lxf->channels)] = lxf->temp[i];
+}
+
+static int lxf_read_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    LXFDemuxContext *lxf = s->priv_data;
+    AVIOContext   *pb  = s->pb;
+    uint8_t header[LXF_PACKET_HEADER_SIZE], *buf;
+    AVStream *ast = NULL;
+    uint32_t stream, format;
+    int ret, ret2;
+
+    if ((ret = get_packet_header(s, header, &format)) < 0)
+        return ret;
+
+    stream = AV_RL32(&header[16]);
+
+    if (stream > 1) {
+        av_log(s, AV_LOG_WARNING, "got packet with illegal stream index %u\n", stream);
+        return AVERROR(EAGAIN);
+    }
+
+    if (stream == 1 && !(ast = s->streams[1])) {
+        av_log(s, AV_LOG_ERROR, "got audio packet without having an audio stream\n");
+        return AVERROR_INVALIDDATA;
+    }
+
+    //make sure the data fits in the de-planerization buffer
+    if (ast && ret > LXF_MAX_AUDIO_PACKET) {
+        av_log(s, AV_LOG_ERROR, "audio packet too large (%i > %i)\n",
+            ret, LXF_MAX_AUDIO_PACKET);
+        return AVERROR_INVALIDDATA;
+    }
+
+    if ((ret2 = av_new_packet(pkt, ret)) < 0)
+        return ret2;
+
+    //read non-20-bit audio data into lxf->temp so we can deplanarize it
+    buf = ast && ast->codec->codec_id != CODEC_ID_PCM_LXF ? lxf->temp : pkt->data;
+
+    if ((ret2 = avio_read(pb, buf, ret)) != ret) {
+        av_free_packet(pkt);
+        return ret2 < 0 ? ret2 : AVERROR_EOF;
+    }
+
+    pkt->stream_index = stream;
+
+    if (ast) {
+        if(ast->codec->codec_id != CODEC_ID_PCM_LXF)
+            deplanarize(lxf, ast, pkt->data, ret);
+    } else {
+        //picture type (0 = closed I, 1 = open I, 2 = P, 3 = B)
+        if (((format >> 22) & 0x3) < 2)
+            pkt->flags |= AV_PKT_FLAG_KEY;
+
+        pkt->dts = lxf->frame_number++;
+    }
+
+    return ret;
+}
+
+AVInputFormat ff_lxf_demuxer = {
+    .name           = "lxf",
+    .long_name      = NULL_IF_CONFIG_SMALL("VR native stream format (LXF)"),
+    .priv_data_size = sizeof(LXFDemuxContext),
+    .read_probe     = lxf_probe,
+    .read_header    = lxf_read_header,
+    .read_packet    = lxf_read_packet,
+    .codec_tag      = (const AVCodecTag* const []){lxf_tags, 0},
+};
+
diff --git a/libavformat/m4vdec.c b/libavformat/m4vdec.c
new file mode 100644
index 0000000..3463901
--- /dev/null
+++ b/libavformat/m4vdec.c
@@ -0,0 +1,62 @@
+/*
+ * RAW MPEG-4 video demuxer
+ * Copyright (c) 2006  Thijs Vermeir <thijs.vermeir at barco.com>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "avformat.h"
+#include "rawdec.h"
+
+#define VISUAL_OBJECT_START_CODE       0x000001b5
+#define VOP_START_CODE                 0x000001b6
+
+static int mpeg4video_probe(AVProbeData *probe_packet)
+{
+    uint32_t temp_buffer= -1;
+    int VO=0, VOL=0, VOP = 0, VISO = 0, res=0;
+    int i;
+
+    for(i=0; i<probe_packet->buf_size; i++){
+        temp_buffer = (temp_buffer<<8) + probe_packet->buf[i];
+        if ((temp_buffer & 0xffffff00) != 0x100)
+            continue;
+
+        if (temp_buffer == VOP_START_CODE)                         VOP++;
+        else if (temp_buffer == VISUAL_OBJECT_START_CODE)          VISO++;
+        else if (temp_buffer < 0x120)                              VO++;
+        else if (temp_buffer < 0x130)                              VOL++;
+        else if (   !(0x1AF < temp_buffer && temp_buffer < 0x1B7)
+                 && !(0x1B9 < temp_buffer && temp_buffer < 0x1C4)) res++;
+    }
+
+    if (VOP >= VISO && VOP >= VOL && VO >= VOL && VOL > 0 && res==0)
+        return AVPROBE_SCORE_MAX/2;
+    return 0;
+}
+
+AVInputFormat ff_m4v_demuxer = {
+    "m4v",
+    NULL_IF_CONFIG_SMALL("raw MPEG-4 video format"),
+    0,
+    mpeg4video_probe, /** probing for MPEG-4 data */
+    ff_raw_video_read_header,
+    ff_raw_read_partial_packet,
+    .flags= AVFMT_GENERIC_INDEX,
+    .extensions = "m4v",
+    .value = CODEC_ID_MPEG4,
+};
diff --git a/libavformat/matroska.c b/libavformat/matroska.c
index dac4735..b448af2 100644
--- a/libavformat/matroska.c
+++ b/libavformat/matroska.c
@@ -2,20 +2,20 @@
  * Matroska common data
  * Copyright (c) 2003-2004 The ffmpeg Project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -52,6 +52,7 @@ const CodecTags ff_mkv_codec_tags[]={
     {"A_WAVPACK4"       , CODEC_ID_WAVPACK},
 
     {"S_TEXT/UTF8"      , CODEC_ID_TEXT},
+    {"S_TEXT/UTF8"      , CODEC_ID_SRT},
     {"S_TEXT/ASCII"     , CODEC_ID_TEXT},
     {"S_TEXT/ASS"       , CODEC_ID_SSA},
     {"S_TEXT/SSA"       , CODEC_ID_SSA},
diff --git a/libavformat/matroska.h b/libavformat/matroska.h
index 40ab3a7..45d9747 100644
--- a/libavformat/matroska.h
+++ b/libavformat/matroska.h
@@ -2,20 +2,20 @@
  * Matroska constants
  * Copyright (c) 2003-2004 The ffmpeg Project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -148,7 +148,8 @@
 #define MATROSKA_ID_TAGNAME             0x45A3
 #define MATROSKA_ID_TAGSTRING           0x4487
 #define MATROSKA_ID_TAGLANG             0x447A
-#define MATROSKA_ID_TAGDEFAULT          0x44B4
+#define MATROSKA_ID_TAGDEFAULT          0x4484
+#define MATROSKA_ID_TAGDEFAULT_BUG      0x44B4
 #define MATROSKA_ID_TAGTARGETS          0x63C0
 #define MATROSKA_ID_TAGTARGETS_TYPE       0x63CA
 #define MATROSKA_ID_TAGTARGETS_TYPEVALUE  0x68CA
diff --git a/libavformat/matroskadec.c b/libavformat/matroskadec.c
index e254a31..19c7ca6 100644
--- a/libavformat/matroskadec.c
+++ b/libavformat/matroskadec.c
@@ -1,21 +1,21 @@
 /*
  * Matroska file demuxer
- * Copyright (c) 2003-2008 The FFmpeg Project
+ * Copyright (c) 2003-2008 The Libav Project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -31,6 +31,7 @@
 #include <stdio.h>
 #include "avformat.h"
 #include "internal.h"
+#include "avio_internal.h"
 /* For ff_codec_get_id(). */
 #include "riff.h"
 #include "isom.h"
@@ -58,6 +59,7 @@ typedef enum {
     EBML_NEST,
     EBML_PASS,
     EBML_STOP,
+    EBML_TYPE_COUNT
 } EbmlType;
 
 typedef const struct EbmlSyntax {
@@ -139,6 +141,7 @@ typedef struct {
     double time_scale;
     uint64_t default_duration;
     uint64_t flag_default;
+    uint64_t flag_forced;
     MatroskaTrackVideo video;
     MatroskaTrackAudio audio;
     EbmlList encodings;
@@ -214,6 +217,7 @@ typedef struct {
     int num_levels;
     MatroskaLevel levels[EBML_MAX_DEPTH];
     int level_up;
+    uint32_t current_id;
 
     uint64_t time_scale;
     double   duration;
@@ -234,7 +238,6 @@ typedef struct {
     AVPacket *prev_pkt;
 
     int done;
-    int has_cluster_id;
 
     /* What to skip before effectively reading a packet. */
     int skip_to_keyframe;
@@ -336,11 +339,11 @@ static EbmlSyntax matroska_track[] = {
     { MATROSKA_ID_TRACKDEFAULTDURATION, EBML_UINT, 0, offsetof(MatroskaTrack,default_duration) },
     { MATROSKA_ID_TRACKTIMECODESCALE,   EBML_FLOAT,0, offsetof(MatroskaTrack,time_scale), {.f=1.0} },
     { MATROSKA_ID_TRACKFLAGDEFAULT,     EBML_UINT, 0, offsetof(MatroskaTrack,flag_default), {.u=1} },
+    { MATROSKA_ID_TRACKFLAGFORCED,      EBML_UINT, 0, offsetof(MatroskaTrack,flag_forced), {.u=0} },
     { MATROSKA_ID_TRACKVIDEO,           EBML_NEST, 0, offsetof(MatroskaTrack,video), {.n=matroska_track_video} },
     { MATROSKA_ID_TRACKAUDIO,           EBML_NEST, 0, offsetof(MatroskaTrack,audio), {.n=matroska_track_audio} },
     { MATROSKA_ID_TRACKCONTENTENCODINGS,EBML_NEST, 0, 0, {.n=matroska_track_encodings} },
     { MATROSKA_ID_TRACKFLAGENABLED,     EBML_NONE },
-    { MATROSKA_ID_TRACKFLAGFORCED,      EBML_NONE },
     { MATROSKA_ID_TRACKFLAGLACING,      EBML_NONE },
     { MATROSKA_ID_CODECNAME,            EBML_NONE },
     { MATROSKA_ID_CODECDECODEALL,       EBML_NONE },
@@ -426,6 +429,7 @@ static EbmlSyntax matroska_simpletag[] = {
     { MATROSKA_ID_TAGSTRING,          EBML_UTF8, 0, offsetof(MatroskaTag,string) },
     { MATROSKA_ID_TAGLANG,            EBML_STR,  0, offsetof(MatroskaTag,lang), {.s="und"} },
     { MATROSKA_ID_TAGDEFAULT,         EBML_UINT, 0, offsetof(MatroskaTag,def) },
+    { MATROSKA_ID_TAGDEFAULT_BUG,     EBML_UINT, 0, offsetof(MatroskaTag,def) },
     { MATROSKA_ID_SIMPLETAG,          EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTag,sub), {.n=matroska_simpletag} },
     { 0 }
 };
@@ -469,7 +473,7 @@ static EbmlSyntax matroska_segment[] = {
     { MATROSKA_ID_CUES,           EBML_NEST, 0, 0, {.n=matroska_index      } },
     { MATROSKA_ID_TAGS,           EBML_NEST, 0, 0, {.n=matroska_tags       } },
     { MATROSKA_ID_SEEKHEAD,       EBML_NEST, 0, 0, {.n=matroska_seekhead   } },
-    { MATROSKA_ID_CLUSTER,        EBML_STOP, 0, offsetof(MatroskaDemuxContext,has_cluster_id) },
+    { MATROSKA_ID_CLUSTER,        EBML_STOP },
     { 0 }
 };
 
@@ -512,12 +516,12 @@ static const char *matroska_doctypes[] = { "matroska", "webm" };
  */
 static int ebml_level_end(MatroskaDemuxContext *matroska)
 {
-    ByteIOContext *pb = matroska->ctx->pb;
-    int64_t pos = url_ftell(pb);
+    AVIOContext *pb = matroska->ctx->pb;
+    int64_t pos = avio_tell(pb);
 
     if (matroska->num_levels > 0) {
         MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
-        if (pos - level->start >= level->length) {
+        if (pos - level->start >= level->length || matroska->current_id) {
             matroska->num_levels--;
             return 1;
         }
@@ -533,19 +537,19 @@ static int ebml_level_end(MatroskaDemuxContext *matroska)
  * number.
  * Returns: number of bytes read, < 0 on error
  */
-static int ebml_read_num(MatroskaDemuxContext *matroska, ByteIOContext *pb,
+static int ebml_read_num(MatroskaDemuxContext *matroska, AVIOContext *pb,
                          int max_size, uint64_t *number)
 {
-    int len_mask = 0x80, read = 1, n = 1;
-    int64_t total = 0;
+    int read = 1, n = 1;
+    uint64_t total = 0;
 
-    /* The first byte tells us the length in bytes - get_byte() can normally
+    /* The first byte tells us the length in bytes - avio_r8() can normally
      * return 0, but since that's not a valid first ebmlID byte, we can
      * use it safely here to catch EOS. */
-    if (!(total = get_byte(pb))) {
+    if (!(total = avio_r8(pb))) {
         /* we might encounter EOS here */
-        if (!url_feof(pb)) {
-            int64_t pos = url_ftell(pb);
+        if (!pb->eof_reached) {
+            int64_t pos = avio_tell(pb);
             av_log(matroska->ctx, AV_LOG_ERROR,
                    "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
                    pos, pos);
@@ -554,12 +558,9 @@ static int ebml_read_num(MatroskaDemuxContext *matroska, ByteIOContext *pb,
     }
 
     /* get the length of the EBML number */
-    while (read <= max_size && !(total & len_mask)) {
-        read++;
-        len_mask >>= 1;
-    }
+    read = 8 - ff_log2_tab[total];
     if (read > max_size) {
-        int64_t pos = url_ftell(pb) - 1;
+        int64_t pos = avio_tell(pb) - 1;
         av_log(matroska->ctx, AV_LOG_ERROR,
                "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
                (uint8_t) total, pos, pos);
@@ -567,30 +568,44 @@ static int ebml_read_num(MatroskaDemuxContext *matroska, ByteIOContext *pb,
     }
 
     /* read out length */
-    total &= ~len_mask;
+    total ^= 1 << ff_log2_tab[total];
     while (n++ < read)
-        total = (total << 8) | get_byte(pb);
+        total = (total << 8) | avio_r8(pb);
 
     *number = total;
 
     return read;
 }
 
+/**
+ * Read a EBML length value.
+ * This needs special handling for the "unknown length" case which has multiple
+ * encodings.
+ */
+static int ebml_read_length(MatroskaDemuxContext *matroska, AVIOContext *pb,
+                            uint64_t *number)
+{
+    int res = ebml_read_num(matroska, pb, 8, number);
+    if (res > 0 && *number + 1 == 1ULL << (7 * res))
+        *number = 0xffffffffffffffULL;
+    return res;
+}
+
 /*
  * Read the next element as an unsigned int.
  * 0 is success, < 0 is failure.
  */
-static int ebml_read_uint(ByteIOContext *pb, int size, uint64_t *num)
+static int ebml_read_uint(AVIOContext *pb, int size, uint64_t *num)
 {
     int n = 0;
 
-    if (size < 1 || size > 8)
+    if (size > 8)
         return AVERROR_INVALIDDATA;
 
     /* big-endian ordering; build up number */
     *num = 0;
     while (n++ < size)
-        *num = (*num << 8) | get_byte(pb);
+        *num = (*num << 8) | avio_r8(pb);
 
     return 0;
 }
@@ -599,12 +614,14 @@ static int ebml_read_uint(ByteIOContext *pb, int size, uint64_t *num)
  * Read the next element as a float.
  * 0 is success, < 0 is failure.
  */
-static int ebml_read_float(ByteIOContext *pb, int size, double *num)
+static int ebml_read_float(AVIOContext *pb, int size, double *num)
 {
-    if (size == 4) {
-        *num= av_int2flt(get_be32(pb));
+    if (size == 0) {
+        *num = 0;
+    } else if (size == 4) {
+        *num= av_int2flt(avio_rb32(pb));
     } else if(size==8){
-        *num= av_int2dbl(get_be64(pb));
+        *num= av_int2dbl(avio_rb64(pb));
     } else
         return AVERROR_INVALIDDATA;
 
@@ -615,15 +632,15 @@ static int ebml_read_float(ByteIOContext *pb, int size, double *num)
  * Read the next element as an ASCII string.
  * 0 is success, < 0 is failure.
  */
-static int ebml_read_ascii(ByteIOContext *pb, int size, char **str)
+static int ebml_read_ascii(AVIOContext *pb, int size, char **str)
 {
     av_free(*str);
     /* EBML strings are usually not 0-terminated, so we allocate one
      * byte more, read the string and NULL-terminate it ourselves. */
     if (!(*str = av_malloc(size + 1)))
         return AVERROR(ENOMEM);
-    if (get_buffer(pb, (uint8_t *) *str, size) != size) {
-        av_free(*str);
+    if (avio_read(pb, (uint8_t *) *str, size) != size) {
+        av_freep(str);
         return AVERROR(EIO);
     }
     (*str)[size] = '\0';
@@ -635,16 +652,18 @@ static int ebml_read_ascii(ByteIOContext *pb, int size, char **str)
  * Read the next element as binary data.
  * 0 is success, < 0 is failure.
  */
-static int ebml_read_binary(ByteIOContext *pb, int length, EbmlBin *bin)
+static int ebml_read_binary(AVIOContext *pb, int length, EbmlBin *bin)
 {
     av_free(bin->data);
     if (!(bin->data = av_malloc(length)))
         return AVERROR(ENOMEM);
 
     bin->size = length;
-    bin->pos  = url_ftell(pb);
-    if (get_buffer(pb, bin->data, length) != length)
+    bin->pos  = avio_tell(pb);
+    if (avio_read(pb, bin->data, length) != length) {
+        av_freep(&bin->data);
         return AVERROR(EIO);
+    }
 
     return 0;
 }
@@ -654,9 +673,9 @@ static int ebml_read_binary(ByteIOContext *pb, int length, EbmlBin *bin)
  * are supposed to be sub-elements which can be read separately.
  * 0 is success, < 0 is failure.
  */
-static int ebml_read_master(MatroskaDemuxContext *matroska, int length)
+static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
 {
-    ByteIOContext *pb = matroska->ctx->pb;
+    AVIOContext *pb = matroska->ctx->pb;
     MatroskaLevel *level;
 
     if (matroska->num_levels >= EBML_MAX_DEPTH) {
@@ -666,7 +685,7 @@ static int ebml_read_master(MatroskaDemuxContext *matroska, int length)
     }
 
     level = &matroska->levels[matroska->num_levels++];
-    level->start = url_ftell(pb);
+    level->start = avio_tell(pb);
     level->length = length;
 
     return 0;
@@ -679,9 +698,9 @@ static int ebml_read_master(MatroskaDemuxContext *matroska, int length)
 static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
                                  uint8_t *data, uint32_t size, uint64_t *num)
 {
-    ByteIOContext pb;
-    init_put_byte(&pb, data, size, 0, NULL, NULL, NULL, NULL);
-    return ebml_read_num(matroska, &pb, 8, num);
+    AVIOContext pb;
+    ffio_init_context(&pb, data, size, 0, NULL, NULL, NULL, NULL);
+    return ebml_read_num(matroska, &pb, FFMIN(size, 8), num);
 }
 
 /*
@@ -713,6 +732,10 @@ static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
     for (i=0; syntax[i].id; i++)
         if (id == syntax[i].id)
             break;
+    if (!syntax[i].id && id == MATROSKA_ID_CLUSTER &&
+        matroska->num_levels > 0 &&
+        matroska->levels[matroska->num_levels-1].length == 0xffffffffffffff)
+        return 0;  // we reached the end of an unknown size cluster
     if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32)
         av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
     return ebml_parse_elem(matroska, &syntax[i], data);
@@ -721,10 +744,14 @@ static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
 static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
                       void *data)
 {
-    uint64_t id;
-    int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
-    id |= 1 << 7*res;
-    return res < 0 ? res : ebml_parse_id(matroska, syntax, id, data);
+    if (!matroska->current_id) {
+        uint64_t id;
+        int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
+        if (res < 0)
+            return res;
+        matroska->current_id = id | 1 << 7*res;
+    }
+    return ebml_parse_id(matroska, syntax, matroska->current_id, data);
 }
 
 static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
@@ -755,7 +782,17 @@ static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
                            EbmlSyntax *syntax, void *data)
 {
-    ByteIOContext *pb = matroska->ctx->pb;
+    static const uint64_t max_lengths[EBML_TYPE_COUNT] = {
+        [EBML_UINT]  = 8,
+        [EBML_FLOAT] = 8,
+        // max. 16 MB for strings
+        [EBML_STR]   = 0x1000000,
+        [EBML_UTF8]  = 0x1000000,
+        // max. 256 MB for binary data
+        [EBML_BIN]   = 0x10000000,
+        // no limits for anything else
+    };
+    AVIOContext *pb = matroska->ctx->pb;
     uint32_t id = syntax->id;
     uint64_t length;
     int res;
@@ -769,9 +806,17 @@ static int ebml_parse_elem(MatroskaDemuxContext *matroska,
         list->nb_elem++;
     }
 
-    if (syntax->type != EBML_PASS && syntax->type != EBML_STOP)
-        if ((res = ebml_read_num(matroska, pb, 8, &length)) < 0)
+    if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
+        matroska->current_id = 0;
+        if ((res = ebml_read_length(matroska, pb, &length)) < 0)
             return res;
+        if (max_lengths[syntax->type] && length > max_lengths[syntax->type]) {
+            av_log(matroska->ctx, AV_LOG_ERROR,
+                   "Invalid length 0x%"PRIx64" > 0x%"PRIx64" for syntax element %i\n",
+                   length, max_lengths[syntax->type], syntax->type);
+            return AVERROR_INVALIDDATA;
+        }
+    }
 
     switch (syntax->type) {
     case EBML_UINT:  res = ebml_read_uint  (pb, length, data);  break;
@@ -782,11 +827,11 @@ static int ebml_parse_elem(MatroskaDemuxContext *matroska,
     case EBML_NEST:  if ((res=ebml_read_master(matroska, length)) < 0)
                          return res;
                      if (id == MATROSKA_ID_SEGMENT)
-                         matroska->segment_start = url_ftell(matroska->ctx->pb);
+                         matroska->segment_start = avio_tell(matroska->ctx->pb);
                      return ebml_parse_nest(matroska, syntax->def.n, data);
     case EBML_PASS:  return ebml_parse_id(matroska, syntax->def.n, id, data);
-    case EBML_STOP:  *(int *)data = 1;      return 1;
-    default:         return url_fseek(pb,length,SEEK_CUR)<0 ? AVERROR(EIO) : 0;
+    case EBML_STOP:  return 1;
+    default:         return avio_skip(pb,length)<0 ? AVERROR(EIO) : 0;
     }
     if (res == AVERROR_INVALIDDATA)
         av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
@@ -887,6 +932,9 @@ static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
     int result = 0;
     int olen;
 
+    if (pkt_size >= 10000000)
+        return -1;
+
     switch (encodings[0].compression.algo) {
     case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
         return encodings[0].compression.settings.size;
@@ -1003,6 +1051,11 @@ static void matroska_convert_tag(AVFormatContext *s, EbmlList *list,
 
     for (i=0; i < list->nb_elem; i++) {
         const char *lang = strcmp(tags[i].lang, "und") ? tags[i].lang : NULL;
+
+        if (!tags[i].name) {
+            av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
+            continue;
+        }
         if (prefix)  snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
         else         av_strlcpy(key, tags[i].name, sizeof(key));
         if (tags[i].def || !lang) {
@@ -1018,6 +1071,7 @@ static void matroska_convert_tag(AVFormatContext *s, EbmlList *list,
                 matroska_convert_tag(s, &tags[i].sub, metadata, key);
         }
     }
+    ff_metadata_conv(metadata, NULL, ff_mkv_metadata_conv);
 }
 
 static void matroska_convert_tags(AVFormatContext *s)
@@ -1057,10 +1111,16 @@ static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
     EbmlList *seekhead_list = &matroska->seekhead;
     MatroskaSeekhead *seekhead = seekhead_list->elem;
     uint32_t level_up = matroska->level_up;
-    int64_t before_pos = url_ftell(matroska->ctx->pb);
+    int64_t before_pos = avio_tell(matroska->ctx->pb);
+    uint32_t saved_id = matroska->current_id;
     MatroskaLevel level;
     int i;
 
+    // we should not do any seeking in the streaming case
+    if (!matroska->ctx->pb->seekable ||
+        (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
+        return;
+
     for (i=0; i<seekhead_list->nb_elem; i++) {
         int64_t offset = seekhead[i].pos + matroska->segment_start;
 
@@ -1070,7 +1130,7 @@ static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
             continue;
 
         /* seek */
-        if (url_fseek(matroska->ctx->pb, offset, SEEK_SET) != offset)
+        if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) != offset)
             continue;
 
         /* We don't want to lose our seekhead level, so we add
@@ -1086,6 +1146,7 @@ static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
         level.length = (uint64_t)-1;
         matroska->levels[matroska->num_levels] = level;
         matroska->num_levels++;
+        matroska->current_id = 0;
 
         ebml_parse(matroska, matroska_segment, matroska);
 
@@ -1098,8 +1159,9 @@ static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
     }
 
     /* seek back */
-    url_fseek(matroska->ctx->pb, before_pos, SEEK_SET);
+    avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
     matroska->level_up = level_up;
+    matroska->current_id = saved_id;
 }
 
 static int matroska_aac_profile(char *codec_id)
@@ -1137,7 +1199,7 @@ static int matroska_read_header(AVFormatContext *s, AVFormatParameters *ap)
     uint64_t max_start = 0;
     Ebml ebml = { 0 };
     AVStream *st;
-    int i, j;
+    int i, j, res;
 
     matroska->ctx = s;
 
@@ -1158,14 +1220,15 @@ static int matroska_read_header(AVFormatContext *s, AVFormatParameters *ap)
     if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
         av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
     }
-    av_metadata_set2(&s->metadata, "doctype", ebml.doctype, 0);
     ebml_free(ebml_syntax, &ebml);
 
     /* The next thing is a segment. */
-    if (ebml_parse(matroska, matroska_segments, matroska) < 0)
-        return -1;
+    if ((res = ebml_parse(matroska, matroska_segments, matroska)) < 0)
+        return res;
     matroska_execute_seekhead(matroska);
 
+    if (!matroska->time_scale)
+        matroska->time_scale = 1000000;
     if (matroska->duration)
         matroska->ctx->duration = matroska->duration * matroska->time_scale
                                   * 1000 / AV_TIME_BASE;
@@ -1180,7 +1243,7 @@ static int matroska_read_header(AVFormatContext *s, AVFormatParameters *ap)
         uint8_t *extradata = NULL;
         int extradata_size = 0;
         int extradata_offset = 0;
-        ByteIOContext b;
+        AVIOContext b;
 
         /* Apply some sanity checks. */
         if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
@@ -1266,9 +1329,12 @@ static int matroska_read_header(AVFormatContext *s, AVFormatParameters *ap)
         } else if (!strcmp(track->codec_id, "A_MS/ACM")
                    && track->codec_priv.size >= 14
                    && track->codec_priv.data != NULL) {
-            init_put_byte(&b, track->codec_priv.data, track->codec_priv.size,
-                          URL_RDONLY, NULL, NULL, NULL, NULL);
-            ff_get_wav_header(&b, st->codec, track->codec_priv.size);
+            int ret;
+            ffio_init_context(&b, track->codec_priv.data, track->codec_priv.size,
+                          AVIO_RDONLY, NULL, NULL, NULL, NULL);
+            ret = ff_get_wav_header(&b, st->codec, track->codec_priv.size);
+            if (ret < 0)
+                return ret;
             codec_id = st->codec->codec_id;
             extradata_offset = FFMIN(track->codec_priv.size, 18);
         } else if (!strcmp(track->codec_id, "V_QUICKTIME")
@@ -1311,14 +1377,14 @@ static int matroska_read_header(AVFormatContext *s, AVFormatParameters *ap)
             extradata = av_mallocz(extradata_size);
             if (extradata == NULL)
                 return AVERROR(ENOMEM);
-            init_put_byte(&b, extradata, extradata_size, 1,
+            ffio_init_context(&b, extradata, extradata_size, 1,
                           NULL, NULL, NULL, NULL);
-            put_buffer(&b, "TTA1", 4);
-            put_le16(&b, 1);
-            put_le16(&b, track->audio.channels);
-            put_le16(&b, track->audio.bitdepth);
-            put_le32(&b, track->audio.out_samplerate);
-            put_le32(&b, matroska->ctx->duration * track->audio.out_samplerate);
+            avio_write(&b, "TTA1", 4);
+            avio_wl16(&b, 1);
+            avio_wl16(&b, track->audio.channels);
+            avio_wl16(&b, track->audio.bitdepth);
+            avio_wl32(&b, track->audio.out_samplerate);
+            avio_wl32(&b, matroska->ctx->duration * track->audio.out_samplerate);
         } else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
                    codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
             extradata_offset = 26;
@@ -1328,15 +1394,15 @@ static int matroska_read_header(AVFormatContext *s, AVFormatParameters *ap)
         } else if (codec_id == CODEC_ID_RA_288 || codec_id == CODEC_ID_COOK ||
                    codec_id == CODEC_ID_ATRAC3 || codec_id == CODEC_ID_SIPR) {
             int flavor;
-            init_put_byte(&b, track->codec_priv.data,track->codec_priv.size,
+            ffio_init_context(&b, track->codec_priv.data,track->codec_priv.size,
                           0, NULL, NULL, NULL, NULL);
-            url_fskip(&b, 22);
-            flavor                       = get_be16(&b);
-            track->audio.coded_framesize = get_be32(&b);
-            url_fskip(&b, 12);
-            track->audio.sub_packet_h    = get_be16(&b);
-            track->audio.frame_size      = get_be16(&b);
-            track->audio.sub_packet_size = get_be16(&b);
+            avio_skip(&b, 22);
+            flavor                       = avio_rb16(&b);
+            track->audio.coded_framesize = avio_rb32(&b);
+            avio_skip(&b, 12);
+            track->audio.sub_packet_h    = avio_rb16(&b);
+            track->audio.frame_size      = avio_rb16(&b);
+            track->audio.sub_packet_size = avio_rb16(&b);
             track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
             if (codec_id == CODEC_ID_RA_288) {
                 st->codec->block_align = track->audio.coded_framesize;
@@ -1369,6 +1435,8 @@ static int matroska_read_header(AVFormatContext *s, AVFormatParameters *ap)
 
         if (track->flag_default)
             st->disposition |= AV_DISPOSITION_DEFAULT;
+        if (track->flag_forced)
+            st->disposition |= AV_DISPOSITION_FORCED;
 
         if (track->default_duration)
             av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
@@ -1706,7 +1774,7 @@ static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
                 int offset = 0, pkt_size = lace_size[n];
                 uint8_t *pkt_data = data;
 
-                if (lace_size[n] > size) {
+                if (pkt_size > size) {
                     av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n");
                     break;
                 }
@@ -1751,7 +1819,8 @@ static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
                 if (matroska->prev_pkt &&
                     timecode != AV_NOPTS_VALUE &&
                     matroska->prev_pkt->pts == timecode &&
-                    matroska->prev_pkt->stream_index == st->index)
+                    matroska->prev_pkt->stream_index == st->index &&
+                    st->codec->codec_id == CODEC_ID_SSA)
                     matroska_merge_packets(matroska->prev_pkt, pkt);
                 else {
                     dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
@@ -1776,22 +1845,18 @@ static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
     EbmlList *blocks_list;
     MatroskaBlock *blocks;
     int i, res;
-    int64_t pos = url_ftell(matroska->ctx->pb);
+    int64_t pos = avio_tell(matroska->ctx->pb);
     matroska->prev_pkt = NULL;
-    if (matroska->has_cluster_id){
-        /* For the first cluster we parse, its ID was already read as
-           part of matroska_read_header(), so don't read it again */
-        res = ebml_parse_id(matroska, matroska_clusters,
-                            MATROSKA_ID_CLUSTER, &cluster);
+    if (matroska->current_id)
         pos -= 4;  /* sizeof the ID which was already read */
-        matroska->has_cluster_id = 0;
-    } else
-        res = ebml_parse(matroska, matroska_clusters, &cluster);
+    res = ebml_parse(matroska, matroska_clusters, &cluster);
     blocks_list = &cluster.blocks;
     blocks = blocks_list->elem;
     for (i=0; i<blocks_list->nb_elem; i++)
-        if (blocks[i].bin.size > 0) {
+        if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
             int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
+            if (!blocks[i].non_simple)
+                blocks[i].duration = AV_NOPTS_VALUE;
             res=matroska_parse_block(matroska,
                                      blocks[i].bin.data, blocks[i].bin.size,
                                      blocks[i].bin.pos,  cluster.timecode,
@@ -1829,7 +1894,7 @@ static int matroska_read_seek(AVFormatContext *s, int stream_index,
     timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
 
     if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
-        url_fseek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
+        avio_seek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
         while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
             matroska_clear_queue(matroska);
             if (matroska_parse_cluster(matroska) < 0)
@@ -1854,7 +1919,7 @@ static int matroska_read_seek(AVFormatContext *s, int stream_index,
         }
     }
 
-    url_fseek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
+    avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
     matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
     matroska->skip_to_timecode = st->index_entries[index].timestamp;
     matroska->done = 0;
@@ -1878,14 +1943,13 @@ static int matroska_read_close(AVFormatContext *s)
     return 0;
 }
 
-AVInputFormat matroska_demuxer = {
-    "matroska",
-    NULL_IF_CONFIG_SMALL("Matroska file format"),
+AVInputFormat ff_matroska_demuxer = {
+    "matroska,webm",
+    NULL_IF_CONFIG_SMALL("Matroska/WebM file format"),
     sizeof(MatroskaDemuxContext),
     matroska_probe,
     matroska_read_header,
     matroska_read_packet,
     matroska_read_close,
     matroska_read_seek,
-    .metadata_conv = ff_mkv_metadata_conv,
 };
diff --git a/libavformat/matroskaenc.c b/libavformat/matroskaenc.c
index c004bd6..c0427f9 100644
--- a/libavformat/matroskaenc.c
+++ b/libavformat/matroskaenc.c
@@ -2,20 +2,20 @@
  * Matroska muxer
  * Copyright (c) 2007 David Conrad
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,10 +25,14 @@
 #include "matroska.h"
 #include "avc.h"
 #include "flacenc.h"
+#include "avlanguage.h"
+#include "libavutil/samplefmt.h"
 #include "libavutil/intreadwrite.h"
-#include "libavutil/md5.h"
+#include "libavutil/random_seed.h"
+#include "libavutil/lfg.h"
 #include "libavcodec/xiph.h"
 #include "libavcodec/mpeg4audio.h"
+#include <strings.h>
 
 typedef struct ebml_master {
     int64_t         pos;                ///< absolute offset in the file where the master's elements start
@@ -70,21 +74,20 @@ typedef struct {
 
 typedef struct MatroskaMuxContext {
     int             mode;
-    ByteIOContext   *dyn_bc;
+    AVIOContext   *dyn_bc;
     ebml_master     segment;
     int64_t         segment_offset;
-    int64_t         segment_uid;
     ebml_master     cluster;
     int64_t         cluster_pos;        ///< file offset of the current cluster
     int64_t         cluster_pts;
     int64_t         duration_offset;
     int64_t         duration;
     mkv_seekhead    *main_seekhead;
-    mkv_seekhead    *cluster_seekhead;
     mkv_cues        *cues;
     mkv_track       *tracks;
 
-    struct AVMD5    *md5_ctx;
+    unsigned int    audio_buffer_size;
+    AVPacket        cur_audio_pkt;
 } MatroskaMuxContext;
 
 
@@ -105,11 +108,11 @@ static int ebml_id_size(unsigned int id)
     return (av_log2(id+1)-1)/7+1;
 }
 
-static void put_ebml_id(ByteIOContext *pb, unsigned int id)
+static void put_ebml_id(AVIOContext *pb, unsigned int id)
 {
     int i = ebml_id_size(id);
     while (i--)
-        put_byte(pb, id >> (i*8));
+        avio_w8(pb, id >> (i*8));
 }
 
 /**
@@ -117,12 +120,12 @@ static void put_ebml_id(ByteIOContext *pb, unsigned int id)
  *
  * @param bytes The number of bytes the size should occupy (maximum: 8).
  */
-static void put_ebml_size_unknown(ByteIOContext *pb, int bytes)
+static void put_ebml_size_unknown(AVIOContext *pb, int bytes)
 {
     assert(bytes <= 8);
-    put_byte(pb, 0x1ff >> bytes);
+    avio_w8(pb, 0x1ff >> bytes);
     while (--bytes)
-        put_byte(pb, 0xff);
+        avio_w8(pb, 0xff);
 }
 
 /**
@@ -141,7 +144,7 @@ static int ebml_num_size(uint64_t num)
  * @param bytes The number of bytes that need to be used to write the number.
  *              If zero, any number of bytes can be used.
  */
-static void put_ebml_num(ByteIOContext *pb, uint64_t num, int bytes)
+static void put_ebml_num(AVIOContext *pb, uint64_t num, int bytes)
 {
     int i, needed_bytes = ebml_num_size(num);
 
@@ -157,10 +160,10 @@ static void put_ebml_num(ByteIOContext *pb, uint64_t num, int bytes)
 
     num |= 1ULL << bytes*7;
     for (i = bytes - 1; i >= 0; i--)
-        put_byte(pb, num >> i*8);
+        avio_w8(pb, num >> i*8);
 }
 
-static void put_ebml_uint(ByteIOContext *pb, unsigned int elementid, uint64_t val)
+static void put_ebml_uint(AVIOContext *pb, unsigned int elementid, uint64_t val)
 {
     int i, bytes = 1;
     uint64_t tmp = val;
@@ -169,38 +172,38 @@ static void put_ebml_uint(ByteIOContext *pb, unsigned int elementid, uint64_t va
     put_ebml_id(pb, elementid);
     put_ebml_num(pb, bytes, 0);
     for (i = bytes - 1; i >= 0; i--)
-        put_byte(pb, val >> i*8);
+        avio_w8(pb, val >> i*8);
 }
 
-static void put_ebml_float(ByteIOContext *pb, unsigned int elementid, double val)
+static void put_ebml_float(AVIOContext *pb, unsigned int elementid, double val)
 {
     put_ebml_id(pb, elementid);
     put_ebml_num(pb, 8, 0);
-    put_be64(pb, av_dbl2int(val));
+    avio_wb64(pb, av_dbl2int(val));
 }
 
-static void put_ebml_binary(ByteIOContext *pb, unsigned int elementid,
-                            const uint8_t *buf, int size)
+static void put_ebml_binary(AVIOContext *pb, unsigned int elementid,
+                            const void *buf, int size)
 {
     put_ebml_id(pb, elementid);
     put_ebml_num(pb, size, 0);
-    put_buffer(pb, buf, size);
+    avio_write(pb, buf, size);
 }
 
-static void put_ebml_string(ByteIOContext *pb, unsigned int elementid, const char *str)
+static void put_ebml_string(AVIOContext *pb, unsigned int elementid, const char *str)
 {
     put_ebml_binary(pb, elementid, str, strlen(str));
 }
 
 /**
- * Writes a void element of a given size. Useful for reserving space in
+ * Write a void element of a given size. Useful for reserving space in
  * the file to be written to later.
  *
  * @param size The number of bytes to reserve, which must be at least 2.
  */
-static void put_ebml_void(ByteIOContext *pb, uint64_t size)
+static void put_ebml_void(AVIOContext *pb, uint64_t size)
 {
-    int64_t currentpos = url_ftell(pb);
+    int64_t currentpos = avio_tell(pb);
 
     assert(size >= 2);
 
@@ -212,34 +215,34 @@ static void put_ebml_void(ByteIOContext *pb, uint64_t size)
         put_ebml_num(pb, size-1, 0);
     else
         put_ebml_num(pb, size-9, 8);
-    while(url_ftell(pb) < currentpos + size)
-        put_byte(pb, 0);
+    while(avio_tell(pb) < currentpos + size)
+        avio_w8(pb, 0);
 }
 
-static ebml_master start_ebml_master(ByteIOContext *pb, unsigned int elementid, uint64_t expectedsize)
+static ebml_master start_ebml_master(AVIOContext *pb, unsigned int elementid, uint64_t expectedsize)
 {
     int bytes = expectedsize ? ebml_num_size(expectedsize) : 8;
     put_ebml_id(pb, elementid);
     put_ebml_size_unknown(pb, bytes);
-    return (ebml_master){ url_ftell(pb), bytes };
+    return (ebml_master){ avio_tell(pb), bytes };
 }
 
-static void end_ebml_master(ByteIOContext *pb, ebml_master master)
+static void end_ebml_master(AVIOContext *pb, ebml_master master)
 {
-    int64_t pos = url_ftell(pb);
+    int64_t pos = avio_tell(pb);
 
-    if (url_fseek(pb, master.pos - master.sizebytes, SEEK_SET) < 0)
+    if (avio_seek(pb, master.pos - master.sizebytes, SEEK_SET) < 0)
         return;
     put_ebml_num(pb, pos - master.pos, master.sizebytes);
-    url_fseek(pb, pos, SEEK_SET);
+    avio_seek(pb, pos, SEEK_SET);
 }
 
-static void put_xiph_size(ByteIOContext *pb, int size)
+static void put_xiph_size(AVIOContext *pb, int size)
 {
     int i;
     for (i = 0; i < size / 255; i++)
-        put_byte(pb, 255);
-    put_byte(pb, size % 255);
+        avio_w8(pb, 255);
+    avio_w8(pb, size % 255);
 }
 
 /**
@@ -253,7 +256,7 @@ static void put_xiph_size(ByteIOContext *pb, int size)
  * @param numelements The maximum number of elements that will be indexed
  *                    by this seek head, 0 if unlimited.
  */
-static mkv_seekhead * mkv_start_seekhead(ByteIOContext *pb, int64_t segment_offset, int numelements)
+static mkv_seekhead * mkv_start_seekhead(AVIOContext *pb, int64_t segment_offset, int numelements)
 {
     mkv_seekhead *new_seekhead = av_mallocz(sizeof(mkv_seekhead));
     if (new_seekhead == NULL)
@@ -262,7 +265,7 @@ static mkv_seekhead * mkv_start_seekhead(ByteIOContext *pb, int64_t segment_offs
     new_seekhead->segment_offset = segment_offset;
 
     if (numelements > 0) {
-        new_seekhead->filepos = url_ftell(pb);
+        new_seekhead->filepos = avio_tell(pb);
         // 21 bytes max for a seek entry, 10 bytes max for the SeekHead ID
         // and size, and 3 bytes to guarantee that an EBML void element
         // will fit afterwards
@@ -301,16 +304,16 @@ static int mkv_add_seekhead_entry(mkv_seekhead *seekhead, unsigned int elementid
  * @return The file offset where the seekhead was written,
  * -1 if an error occurred.
  */
-static int64_t mkv_write_seekhead(ByteIOContext *pb, mkv_seekhead *seekhead)
+static int64_t mkv_write_seekhead(AVIOContext *pb, mkv_seekhead *seekhead)
 {
     ebml_master metaseek, seekentry;
     int64_t currentpos;
     int i;
 
-    currentpos = url_ftell(pb);
+    currentpos = avio_tell(pb);
 
     if (seekhead->reserved_size > 0)
-        if (url_fseek(pb, seekhead->filepos, SEEK_SET) < 0)
+        if (avio_seek(pb, seekhead->filepos, SEEK_SET) < 0)
             return -1;
 
     metaseek = start_ebml_master(pb, MATROSKA_ID_SEEKHEAD, seekhead->reserved_size);
@@ -329,9 +332,9 @@ static int64_t mkv_write_seekhead(ByteIOContext *pb, mkv_seekhead *seekhead)
     end_ebml_master(pb, metaseek);
 
     if (seekhead->reserved_size > 0) {
-        uint64_t remaining = seekhead->filepos + seekhead->reserved_size - url_ftell(pb);
+        uint64_t remaining = seekhead->filepos + seekhead->reserved_size - avio_tell(pb);
         put_ebml_void(pb, remaining);
-        url_fseek(pb, currentpos, SEEK_SET);
+        avio_seek(pb, currentpos, SEEK_SET);
 
         currentpos = seekhead->filepos;
     }
@@ -370,13 +373,13 @@ static int mkv_add_cuepoint(mkv_cues *cues, int stream, int64_t ts, int64_t clus
     return 0;
 }
 
-static int64_t mkv_write_cues(ByteIOContext *pb, mkv_cues *cues, int num_tracks)
+static int64_t mkv_write_cues(AVIOContext *pb, mkv_cues *cues, int num_tracks)
 {
     ebml_master cues_element;
     int64_t currentpos;
     int i, j;
 
-    currentpos = url_ftell(pb);
+    currentpos = avio_tell(pb);
     cues_element = start_ebml_master(pb, MATROSKA_ID_CUES, 0);
 
     for (i = 0; i < cues->num_entries; i++) {
@@ -405,7 +408,7 @@ static int64_t mkv_write_cues(ByteIOContext *pb, mkv_cues *cues, int num_tracks)
     return currentpos;
 }
 
-static int put_xiph_codecpriv(AVFormatContext *s, ByteIOContext *pb, AVCodecContext *codec)
+static int put_xiph_codecpriv(AVFormatContext *s, AVIOContext *pb, AVCodecContext *codec)
 {
     uint8_t *header_start[3];
     int header_len[3];
@@ -423,50 +426,36 @@ static int put_xiph_codecpriv(AVFormatContext *s, ByteIOContext *pb, AVCodecCont
         return -1;
     }
 
-    put_byte(pb, 2);                    // number packets - 1
+    avio_w8(pb, 2);                    // number packets - 1
     for (j = 0; j < 2; j++) {
         put_xiph_size(pb, header_len[j]);
     }
     for (j = 0; j < 3; j++)
-        put_buffer(pb, header_start[j], header_len[j]);
+        avio_write(pb, header_start[j], header_len[j]);
 
     return 0;
 }
 
 static void get_aac_sample_rates(AVFormatContext *s, AVCodecContext *codec, int *sample_rate, int *output_sample_rate)
 {
-    int sri;
+    MPEG4AudioConfig mp4ac;
 
-    if (codec->extradata_size < 2) {
-        av_log(s, AV_LOG_WARNING, "No AAC extradata, unable to determine samplerate.\n");
+    if (ff_mpeg4audio_get_config(&mp4ac, codec->extradata, codec->extradata_size) < 0) {
+        av_log(s, AV_LOG_WARNING, "Error parsing AAC extradata, unable to determine samplerate.\n");
         return;
     }
 
-    sri = ((codec->extradata[0] << 1) & 0xE) | (codec->extradata[1] >> 7);
-    if (sri > 12) {
-        av_log(s, AV_LOG_WARNING, "AAC samplerate index out of bounds\n");
-        return;
-    }
-    *sample_rate = ff_mpeg4audio_sample_rates[sri];
-
-    // if sbr, get output sample rate as well
-    if (codec->extradata_size == 5) {
-        sri = (codec->extradata[4] >> 3) & 0xF;
-        if (sri > 12) {
-            av_log(s, AV_LOG_WARNING, "AAC output samplerate index out of bounds\n");
-            return;
-        }
-        *output_sample_rate = ff_mpeg4audio_sample_rates[sri];
-    }
+    *sample_rate        = mp4ac.sample_rate;
+    *output_sample_rate = mp4ac.ext_sample_rate;
 }
 
-static int mkv_write_codecprivate(AVFormatContext *s, ByteIOContext *pb, AVCodecContext *codec, int native_id, int qt_id)
+static int mkv_write_codecprivate(AVFormatContext *s, AVIOContext *pb, AVCodecContext *codec, int native_id, int qt_id)
 {
-    ByteIOContext *dyn_cp;
+    AVIOContext *dyn_cp;
     uint8_t *codecpriv;
     int ret, codecpriv_size;
 
-    ret = url_open_dyn_buf(&dyn_cp);
+    ret = avio_open_dyn_buf(&dyn_cp);
     if(ret < 0)
         return ret;
 
@@ -478,13 +467,13 @@ static int mkv_write_codecprivate(AVFormatContext *s, ByteIOContext *pb, AVCodec
         else if (codec->codec_id == CODEC_ID_H264)
             ret = ff_isom_write_avcc(dyn_cp, codec->extradata, codec->extradata_size);
         else if (codec->extradata_size)
-            put_buffer(dyn_cp, codec->extradata, codec->extradata_size);
+            avio_write(dyn_cp, codec->extradata, codec->extradata_size);
     } else if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
         if (qt_id) {
             if (!codec->codec_tag)
                 codec->codec_tag = ff_codec_get_tag(codec_movvideo_tags, codec->codec_id);
             if (codec->extradata_size)
-                put_buffer(dyn_cp, codec->extradata, codec->extradata_size);
+                avio_write(dyn_cp, codec->extradata, codec->extradata_size);
         } else {
             if (!codec->codec_tag)
                 codec->codec_tag = ff_codec_get_tag(ff_codec_bmp_tags, codec->codec_id);
@@ -509,7 +498,7 @@ static int mkv_write_codecprivate(AVFormatContext *s, ByteIOContext *pb, AVCodec
         ff_put_wav_header(dyn_cp, codec);
     }
 
-    codecpriv_size = url_close_dyn_buf(dyn_cp, &codecpriv);
+    codecpriv_size = avio_close_dyn_buf(dyn_cp, &codecpriv);
     if (codecpriv_size)
         put_ebml_binary(pb, MATROSKA_ID_CODECPRIVATE, codecpriv, codecpriv_size);
     av_free(codecpriv);
@@ -519,11 +508,11 @@ static int mkv_write_codecprivate(AVFormatContext *s, ByteIOContext *pb, AVCodec
 static int mkv_write_tracks(AVFormatContext *s)
 {
     MatroskaMuxContext *mkv = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     ebml_master tracks;
     int i, j, ret;
 
-    ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TRACKS, url_ftell(pb));
+    ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TRACKS, avio_tell(pb));
     if (ret < 0) return ret;
 
     tracks = start_ebml_master(pb, MATROSKA_ID_TRACKS, 0);
@@ -539,7 +528,7 @@ static int mkv_write_tracks(AVFormatContext *s)
         AVMetadataTag *tag;
 
         if (!bit_depth)
-            bit_depth = av_get_bits_per_sample_format(codec->sample_fmt);
+            bit_depth = av_get_bits_per_sample_fmt(codec->sample_fmt);
 
         if (codec->codec_id == CODEC_ID_AAC)
             get_aac_sample_rates(s, codec, &sample_rate, &output_sample_rate);
@@ -603,6 +592,7 @@ static int mkv_write_tracks(AVFormatContext *s)
                     int d_width = codec->width*av_q2d(st->sample_aspect_ratio);
                     put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH , d_width);
                     put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, codec->height);
+                    put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYUNIT, 3);
                 }
                 end_ebml_master(pb, subinfo);
                 break;
@@ -646,7 +636,7 @@ static int mkv_write_tracks(AVFormatContext *s)
 static int mkv_write_chapters(AVFormatContext *s)
 {
     MatroskaMuxContext *mkv = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     ebml_master chapters, editionentry;
     AVRational scale = {1, 1E9};
     int i, ret;
@@ -654,7 +644,7 @@ static int mkv_write_chapters(AVFormatContext *s)
     if (!s->nb_chapters)
         return 0;
 
-    ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CHAPTERS, url_ftell(pb));
+    ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CHAPTERS, avio_tell(pb));
     if (ret < 0) return ret;
 
     chapters     = start_ebml_master(pb, MATROSKA_ID_CHAPTERS    , 0);
@@ -687,20 +677,116 @@ static int mkv_write_chapters(AVFormatContext *s)
     return 0;
 }
 
+static void mkv_write_simpletag(AVIOContext *pb, AVMetadataTag *t)
+{
+    uint8_t *key = av_strdup(t->key);
+    uint8_t *p   = key;
+    const uint8_t *lang = NULL;
+    ebml_master tag;
+
+    if ((p = strrchr(p, '-')) &&
+        (lang = av_convert_lang_to(p + 1, AV_LANG_ISO639_2_BIBL)))
+        *p = 0;
+
+    p = key;
+    while (*p) {
+        if (*p == ' ')
+            *p = '_';
+        else if (*p >= 'a' && *p <= 'z')
+            *p -= 'a' - 'A';
+        p++;
+    }
+
+    tag = start_ebml_master(pb, MATROSKA_ID_SIMPLETAG, 0);
+    put_ebml_string(pb, MATROSKA_ID_TAGNAME, key);
+    if (lang)
+        put_ebml_string(pb, MATROSKA_ID_TAGLANG, lang);
+    put_ebml_string(pb, MATROSKA_ID_TAGSTRING, t->value);
+    end_ebml_master(pb, tag);
+
+    av_freep(&key);
+}
+
+static int mkv_write_tag(AVFormatContext *s, AVMetadata *m, unsigned int elementid,
+                         unsigned int uid, ebml_master *tags)
+{
+    MatroskaMuxContext *mkv = s->priv_data;
+    ebml_master tag, targets;
+    AVMetadataTag *t = NULL;
+    int ret;
+
+    if (!tags->pos) {
+        ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TAGS, avio_tell(s->pb));
+        if (ret < 0) return ret;
+
+        *tags = start_ebml_master(s->pb, MATROSKA_ID_TAGS, 0);
+    }
+
+    tag     = start_ebml_master(s->pb, MATROSKA_ID_TAG,        0);
+    targets = start_ebml_master(s->pb, MATROSKA_ID_TAGTARGETS, 0);
+    if (elementid)
+        put_ebml_uint(s->pb, elementid, uid);
+    end_ebml_master(s->pb, targets);
+
+    while ((t = av_metadata_get(m, "", t, AV_METADATA_IGNORE_SUFFIX)))
+        if (strcasecmp(t->key, "title"))
+            mkv_write_simpletag(s->pb, t);
+
+    end_ebml_master(s->pb, tag);
+    return 0;
+}
+
+static int mkv_write_tags(AVFormatContext *s)
+{
+    ebml_master tags = {0};
+    int i, ret;
+
+    ff_metadata_conv_ctx(s, ff_mkv_metadata_conv, NULL);
+
+    if (av_metadata_get(s->metadata, "", NULL, AV_METADATA_IGNORE_SUFFIX)) {
+        ret = mkv_write_tag(s, s->metadata, 0, 0, &tags);
+        if (ret < 0) return ret;
+    }
+
+    for (i = 0; i < s->nb_streams; i++) {
+        AVStream *st = s->streams[i];
+
+        if (!av_metadata_get(st->metadata, "", 0, AV_METADATA_IGNORE_SUFFIX))
+            continue;
+
+        ret = mkv_write_tag(s, st->metadata, MATROSKA_ID_TAGTARGETS_TRACKUID, i + 1, &tags);
+        if (ret < 0) return ret;
+    }
+
+    for (i = 0; i < s->nb_chapters; i++) {
+        AVChapter *ch = s->chapters[i];
+
+        if (!av_metadata_get(ch->metadata, "", NULL, AV_METADATA_IGNORE_SUFFIX))
+            continue;
+
+        ret = mkv_write_tag(s, ch->metadata, MATROSKA_ID_TAGTARGETS_CHAPTERUID, ch->id, &tags);
+        if (ret < 0) return ret;
+    }
+
+    if (tags.pos)
+        end_ebml_master(s->pb, tags);
+    return 0;
+}
+
 static int mkv_write_header(AVFormatContext *s)
 {
     MatroskaMuxContext *mkv = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     ebml_master ebml_header, segment_info;
     AVMetadataTag *tag;
-    int ret;
+    int ret, i;
 
     if (!strcmp(s->oformat->name, "webm")) mkv->mode = MODE_WEBM;
     else                                   mkv->mode = MODE_MATROSKAv2;
 
-    mkv->md5_ctx = av_mallocz(av_md5_size);
-    av_md5_init(mkv->md5_ctx);
     mkv->tracks = av_mallocz(s->nb_streams * sizeof(*mkv->tracks));
+    if (!mkv->tracks)
+        return AVERROR(ENOMEM);
 
     ebml_header = start_ebml_master(pb, EBML_ID_HEADER, 0);
     put_ebml_uint   (pb, EBML_ID_EBMLVERSION        ,           1);
@@ -713,7 +799,7 @@ static int mkv_write_header(AVFormatContext *s)
     end_ebml_master(pb, ebml_header);
 
     mkv->segment = start_ebml_master(pb, MATROSKA_ID_SEGMENT, 0);
-    mkv->segment_offset = url_ftell(pb);
+    mkv->segment_offset = avio_tell(pb);
 
     // we write 2 seek heads - one at the end of the file to point to each
     // cluster, and one at the beginning to point to all other level one
@@ -721,11 +807,10 @@ static int mkv_write_header(AVFormatContext *s)
     // isn't more than 10 elements if we only write one of each other
     // currently defined level 1 element
     mkv->main_seekhead    = mkv_start_seekhead(pb, mkv->segment_offset, 10);
-    mkv->cluster_seekhead = mkv_start_seekhead(pb, mkv->segment_offset, 0);
-    if (mkv->main_seekhead == NULL || mkv->cluster_seekhead == NULL)
+    if (!mkv->main_seekhead)
         return AVERROR(ENOMEM);
 
-    ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_INFO, url_ftell(pb));
+    ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_INFO, avio_tell(pb));
     if (ret < 0) return ret;
 
     segment_info = start_ebml_master(pb, MATROSKA_ID_INFO, 0);
@@ -733,17 +818,22 @@ static int mkv_write_header(AVFormatContext *s)
     if ((tag = av_metadata_get(s->metadata, "title", NULL, 0)))
         put_ebml_string(pb, MATROSKA_ID_TITLE, tag->value);
     if (!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
+        uint32_t segment_uid[4];
+        AVLFG lfg;
+
+        av_lfg_init(&lfg, av_get_random_seed());
+
+        for (i = 0; i < 4; i++)
+            segment_uid[i] = av_lfg_get(&lfg);
+
         put_ebml_string(pb, MATROSKA_ID_MUXINGAPP , LIBAVFORMAT_IDENT);
         put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, LIBAVFORMAT_IDENT);
-
-        // reserve space to write the segment UID later
-        mkv->segment_uid = url_ftell(pb);
-        put_ebml_void(pb, 19);
+        put_ebml_binary(pb, MATROSKA_ID_SEGMENTUID, segment_uid, 16);
     }
 
     // reserve space for the duration
     mkv->duration = 0;
-    mkv->duration_offset = url_ftell(pb);
+    mkv->duration_offset = avio_tell(pb);
     put_ebml_void(pb, 11);                  // assumes double-precision float to be written
     end_ebml_master(pb, segment_info);
 
@@ -753,16 +843,23 @@ static int mkv_write_header(AVFormatContext *s)
     if (mkv->mode != MODE_WEBM) {
         ret = mkv_write_chapters(s);
         if (ret < 0) return ret;
+
+        ret = mkv_write_tags(s);
+        if (ret < 0) return ret;
     }
 
-    if (url_is_streamed(s->pb))
+    if (!s->pb->seekable)
         mkv_write_seekhead(pb, mkv->main_seekhead);
 
     mkv->cues = mkv_start_cues(mkv->segment_offset);
     if (mkv->cues == NULL)
         return AVERROR(ENOMEM);
 
-    put_flush_packet(pb);
+    av_init_packet(&mkv->cur_audio_pkt);
+    mkv->cur_audio_pkt.size = 0;
+    mkv->audio_buffer_size  = 0;
+
+    avio_flush(pb);
     return 0;
 }
 
@@ -790,7 +887,7 @@ static int ass_get_duration(const uint8_t *p)
     return end - start;
 }
 
-static int mkv_write_ass_blocks(AVFormatContext *s, ByteIOContext *pb, AVPacket *pkt)
+static int mkv_write_ass_blocks(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
 {
     MatroskaMuxContext *mkv = s->priv_data;
     int i, layer = 0, max_duration = 0, size, line_size, data_size = pkt->size;
@@ -817,14 +914,14 @@ static int mkv_write_ass_blocks(AVFormatContext *s, ByteIOContext *pb, AVPacket
 
         av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
                "pts %" PRId64 ", duration %d\n",
-               url_ftell(pb), size, pkt->pts, duration);
+               avio_tell(pb), size, pkt->pts, duration);
         blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, mkv_blockgroup_size(size));
         put_ebml_id(pb, MATROSKA_ID_BLOCK);
         put_ebml_num(pb, size+4, 0);
-        put_byte(pb, 0x80 | (pkt->stream_index + 1));     // this assumes stream_index is less than 126
-        put_be16(pb, pkt->pts - mkv->cluster_pts);
-        put_byte(pb, 0);
-        put_buffer(pb, buffer, size);
+        avio_w8(pb, 0x80 | (pkt->stream_index + 1));     // this assumes stream_index is less than 126
+        avio_wb16(pb, pkt->pts - mkv->cluster_pts);
+        avio_w8(pb, 0);
+        avio_write(pb, buffer, size);
         put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
         end_ebml_master(pb, blockgroup);
 
@@ -835,7 +932,7 @@ static int mkv_write_ass_blocks(AVFormatContext *s, ByteIOContext *pb, AVPacket
     return max_duration;
 }
 
-static void mkv_write_block(AVFormatContext *s, ByteIOContext *pb,
+static void mkv_write_block(AVFormatContext *s, AVIOContext *pb,
                             unsigned int blockid, AVPacket *pkt, int flags)
 {
     MatroskaMuxContext *mkv = s->priv_data;
@@ -846,7 +943,7 @@ static void mkv_write_block(AVFormatContext *s, ByteIOContext *pb,
 
     av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
            "pts %" PRId64 ", dts %" PRId64 ", duration %d, flags %d\n",
-           url_ftell(pb), pkt->size, pkt->pts, pkt->dts, pkt->duration, flags);
+           avio_tell(pb), pkt->size, pkt->pts, pkt->dts, pkt->duration, flags);
     if (codec->codec_id == CODEC_ID_H264 && codec->extradata_size > 0 &&
         (AV_RB24(codec->extradata) == 1 || AV_RB32(codec->extradata) == 1))
         ff_avc_parse_nal_units_buf(pkt->data, &data, &size);
@@ -854,14 +951,49 @@ static void mkv_write_block(AVFormatContext *s, ByteIOContext *pb,
         data = pkt->data;
     put_ebml_id(pb, blockid);
     put_ebml_num(pb, size+4, 0);
-    put_byte(pb, 0x80 | (pkt->stream_index + 1));     // this assumes stream_index is less than 126
-    put_be16(pb, ts - mkv->cluster_pts);
-    put_byte(pb, flags);
-    put_buffer(pb, data, size);
+    avio_w8(pb, 0x80 | (pkt->stream_index + 1));     // this assumes stream_index is less than 126
+    avio_wb16(pb, ts - mkv->cluster_pts);
+    avio_w8(pb, flags);
+    avio_write(pb, data, size);
     if (data != pkt->data)
         av_free(data);
 }
 
+static int srt_get_duration(uint8_t **buf)
+{
+    int i, duration = 0;
+
+    for (i=0; i<2 && !duration; i++) {
+        int s_hour, s_min, s_sec, s_hsec, e_hour, e_min, e_sec, e_hsec;
+        if (sscanf(*buf, "%d:%2d:%2d%*1[,.]%3d --> %d:%2d:%2d%*1[,.]%3d",
+                   &s_hour, &s_min, &s_sec, &s_hsec,
+                   &e_hour, &e_min, &e_sec, &e_hsec) == 8) {
+            s_min  +=   60*s_hour;      e_min  +=   60*e_hour;
+            s_sec  +=   60*s_min;       e_sec  +=   60*e_min;
+            s_hsec += 1000*s_sec;       e_hsec += 1000*e_sec;
+            duration = e_hsec - s_hsec;
+        }
+        *buf += strcspn(*buf, "\n") + 1;
+    }
+    return duration;
+}
+
+static int mkv_write_srt_blocks(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
+{
+    ebml_master blockgroup;
+    AVPacket pkt2 = *pkt;
+    int64_t duration = srt_get_duration(&pkt2.data);
+    pkt2.size -= pkt2.data - pkt->data;
+
+    blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
+                                   mkv_blockgroup_size(pkt2.size));
+    mkv_write_block(s, pb, MATROSKA_ID_BLOCK, &pkt2, 0);
+    put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
+    end_ebml_master(pb, blockgroup);
+
+    return duration;
+}
+
 static void mkv_flush_dynbuf(AVFormatContext *s)
 {
     MatroskaMuxContext *mkv = s->priv_data;
@@ -871,16 +1003,16 @@ static void mkv_flush_dynbuf(AVFormatContext *s)
     if (!mkv->dyn_bc)
         return;
 
-    bufsize = url_close_dyn_buf(mkv->dyn_bc, &dyn_buf);
-    put_buffer(s->pb, dyn_buf, bufsize);
+    bufsize = avio_close_dyn_buf(mkv->dyn_bc, &dyn_buf);
+    avio_write(s->pb, dyn_buf, bufsize);
     av_free(dyn_buf);
     mkv->dyn_bc = NULL;
 }
 
-static int mkv_write_packet(AVFormatContext *s, AVPacket *pkt)
+static int mkv_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
 {
     MatroskaMuxContext *mkv = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
     int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
     int duration = pkt->duration;
@@ -892,27 +1024,25 @@ static int mkv_write_packet(AVFormatContext *s, AVPacket *pkt)
         return AVERROR(EINVAL);
     }
 
-    if (url_is_streamed(s->pb)) {
+    if (!s->pb->seekable) {
         if (!mkv->dyn_bc)
-            url_open_dyn_buf(&mkv->dyn_bc);
+            avio_open_dyn_buf(&mkv->dyn_bc);
         pb = mkv->dyn_bc;
     }
 
     if (!mkv->cluster_pos) {
-        ret = mkv_add_seekhead_entry(mkv->cluster_seekhead, MATROSKA_ID_CLUSTER, url_ftell(pb));
-        if (ret < 0) return ret;
-
-        mkv->cluster_pos = url_ftell(s->pb);
+        mkv->cluster_pos = avio_tell(s->pb);
         mkv->cluster = start_ebml_master(pb, MATROSKA_ID_CLUSTER, 0);
         put_ebml_uint(pb, MATROSKA_ID_CLUSTERTIMECODE, FFMAX(0, ts));
         mkv->cluster_pts = FFMAX(0, ts);
-        av_md5_update(mkv->md5_ctx, pkt->data, FFMIN(200, pkt->size));
     }
 
     if (codec->codec_type != AVMEDIA_TYPE_SUBTITLE) {
         mkv_write_block(s, pb, MATROSKA_ID_SIMPLEBLOCK, pkt, keyframe << 7);
     } else if (codec->codec_id == CODEC_ID_SSA) {
         duration = mkv_write_ass_blocks(s, pb, pkt);
+    } else if (codec->codec_id == CODEC_ID_SRT) {
+        duration = mkv_write_srt_blocks(s, pb, pkt);
     } else {
         ebml_master blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, mkv_blockgroup_size(pkt->size));
         duration = pkt->convergence_duration;
@@ -926,28 +1056,82 @@ static int mkv_write_packet(AVFormatContext *s, AVPacket *pkt)
         if (ret < 0) return ret;
     }
 
-    // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming
-    if ((url_is_streamed(s->pb) && (url_ftell(pb) > 32*1024 || ts > mkv->cluster_pts + 1000))
-        ||  url_ftell(pb) > mkv->cluster_pos + 5*1024*1024 || ts > mkv->cluster_pts + 5000) {
+    mkv->duration = FFMAX(mkv->duration, ts + duration);
+    return 0;
+}
+
+static int mkv_copy_packet(MatroskaMuxContext *mkv, const AVPacket *pkt)
+{
+    uint8_t *data           = mkv->cur_audio_pkt.data;
+    mkv->cur_audio_pkt      = *pkt;
+    mkv->cur_audio_pkt.data = av_fast_realloc(data, &mkv->audio_buffer_size, pkt->size);
+    if (!mkv->cur_audio_pkt.data)
+        return AVERROR(ENOMEM);
+
+    memcpy(mkv->cur_audio_pkt.data, pkt->data, pkt->size);
+    mkv->cur_audio_pkt.size = pkt->size;
+    return 0;
+}
+
+static int mkv_write_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    MatroskaMuxContext *mkv = s->priv_data;
+    AVIOContext *pb = s->pb->seekable ? s->pb : mkv->dyn_bc;
+    AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
+    int ret, keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
+    int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
+    int cluster_size = avio_tell(pb) - (s->pb->seekable ? mkv->cluster_pos : 0);
+
+    // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
+    // after 4k and on a keyframe
+    if (mkv->cluster_pos &&
+        ((!s->pb->seekable && (cluster_size > 32*1024 || ts > mkv->cluster_pts + 1000))
+         ||                      cluster_size > 5*1024*1024 || ts > mkv->cluster_pts + 5000
+         || (codec->codec_type == AVMEDIA_TYPE_VIDEO && keyframe && cluster_size > 4*1024))) {
         av_log(s, AV_LOG_DEBUG, "Starting new cluster at offset %" PRIu64
-               " bytes, pts %" PRIu64 "\n", url_ftell(pb), ts);
+               " bytes, pts %" PRIu64 "\n", avio_tell(pb), ts);
         end_ebml_master(pb, mkv->cluster);
         mkv->cluster_pos = 0;
         if (mkv->dyn_bc)
             mkv_flush_dynbuf(s);
     }
 
-    mkv->duration = FFMAX(mkv->duration, ts + duration);
-    return 0;
+    // check if we have an audio packet cached
+    if (mkv->cur_audio_pkt.size > 0) {
+        ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);
+        mkv->cur_audio_pkt.size = 0;
+        if (ret < 0) {
+            av_log(s, AV_LOG_ERROR, "Could not write cached audio packet ret:%d\n", ret);
+            return ret;
+        }
+    }
+
+    // buffer an audio packet to ensure the packet containing the video
+    // keyframe's timecode is contained in the same cluster for WebM
+    if (codec->codec_type == AVMEDIA_TYPE_AUDIO)
+        ret = mkv_copy_packet(mkv, pkt);
+    else
+        ret = mkv_write_packet_internal(s, pkt);
+    return ret;
 }
 
 static int mkv_write_trailer(AVFormatContext *s)
 {
     MatroskaMuxContext *mkv = s->priv_data;
-    ByteIOContext *pb = s->pb;
-    int64_t currentpos, second_seekhead, cuespos;
+    AVIOContext *pb = s->pb;
+    int64_t currentpos, cuespos;
     int ret;
 
+    // check if we have an audio packet cached
+    if (mkv->cur_audio_pkt.size > 0) {
+        ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);
+        mkv->cur_audio_pkt.size = 0;
+        if (ret < 0) {
+            av_log(s, AV_LOG_ERROR, "Could not write cached audio packet ret:%d\n", ret);
+            return ret;
+        }
+    }
+
     if (mkv->dyn_bc) {
         end_ebml_master(mkv->dyn_bc, mkv->cluster);
         mkv_flush_dynbuf(s);
@@ -955,43 +1139,34 @@ static int mkv_write_trailer(AVFormatContext *s)
         end_ebml_master(pb, mkv->cluster);
     }
 
-    if (!url_is_streamed(pb)) {
-        cuespos = mkv_write_cues(pb, mkv->cues, s->nb_streams);
-        second_seekhead = mkv_write_seekhead(pb, mkv->cluster_seekhead);
+    if (pb->seekable) {
+        if (mkv->cues->num_entries) {
+            cuespos = mkv_write_cues(pb, mkv->cues, s->nb_streams);
 
-        ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CUES    , cuespos);
-        if (ret < 0) return ret;
-        if (second_seekhead >= 0) {
-            ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_SEEKHEAD, second_seekhead);
+            ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CUES, cuespos);
             if (ret < 0) return ret;
         }
+
         mkv_write_seekhead(pb, mkv->main_seekhead);
 
         // update the duration
         av_log(s, AV_LOG_DEBUG, "end duration = %" PRIu64 "\n", mkv->duration);
-        currentpos = url_ftell(pb);
-        url_fseek(pb, mkv->duration_offset, SEEK_SET);
+        currentpos = avio_tell(pb);
+        avio_seek(pb, mkv->duration_offset, SEEK_SET);
         put_ebml_float(pb, MATROSKA_ID_DURATION, mkv->duration);
 
-        // write the md5sum of some frames as the segment UID
-        if (!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
-            uint8_t segment_uid[16];
-            av_md5_final(mkv->md5_ctx, segment_uid);
-            url_fseek(pb, mkv->segment_uid, SEEK_SET);
-            put_ebml_binary(pb, MATROSKA_ID_SEGMENTUID, segment_uid, 16);
-        }
-        url_fseek(pb, currentpos, SEEK_SET);
+        avio_seek(pb, currentpos, SEEK_SET);
     }
 
     end_ebml_master(pb, mkv->segment);
-    av_free(mkv->md5_ctx);
     av_free(mkv->tracks);
-    put_flush_packet(pb);
+    av_destruct_packet(&mkv->cur_audio_pkt);
+    avio_flush(pb);
     return 0;
 }
 
 #if CONFIG_MATROSKA_MUXER
-AVOutputFormat matroska_muxer = {
+AVOutputFormat ff_matroska_muxer = {
     "matroska",
     NULL_IF_CONFIG_SMALL("Matroska file format"),
     "video/x-matroska",
@@ -1009,7 +1184,7 @@ AVOutputFormat matroska_muxer = {
 #endif
 
 #if CONFIG_WEBM_MUXER
-AVOutputFormat webm_muxer = {
+AVOutputFormat ff_webm_muxer = {
     "webm",
     NULL_IF_CONFIG_SMALL("WebM file format"),
     "video/webm",
@@ -1025,7 +1200,7 @@ AVOutputFormat webm_muxer = {
 #endif
 
 #if CONFIG_MATROSKA_AUDIO_MUXER
-AVOutputFormat matroska_audio_muxer = {
+AVOutputFormat ff_matroska_audio_muxer = {
     "matroska",
     NULL_IF_CONFIG_SMALL("Matroska file format"),
     "audio/x-matroska",
diff --git a/libavformat/md5enc.c b/libavformat/md5enc.c
new file mode 100644
index 0000000..3b7d0ea
--- /dev/null
+++ b/libavformat/md5enc.c
@@ -0,0 +1,110 @@
+/*
+ * MD5 encoder (for codec/format testing)
+ * Copyright (c) 2009 Reimar Döffinger, based on crcenc (c) 2002 Fabrice Bellard
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "libavutil/md5.h"
+#include "avformat.h"
+
+#define PRIVSIZE 512
+
+static void md5_finish(struct AVFormatContext *s, char *buf)
+{
+    uint8_t md5[16];
+    int i, offset = strlen(buf);
+    av_md5_final(s->priv_data, md5);
+    for (i = 0; i < sizeof(md5); i++) {
+        snprintf(buf + offset, 3, "%02"PRIx8, md5[i]);
+        offset += 2;
+    }
+    buf[offset] = '\n';
+    buf[offset+1] = 0;
+
+    avio_write(s->pb, buf, strlen(buf));
+    avio_flush(s->pb);
+}
+
+#if CONFIG_MD5_MUXER
+static int write_header(struct AVFormatContext *s)
+{
+    if (PRIVSIZE < av_md5_size) {
+        av_log(s, AV_LOG_ERROR, "Insuffient size for md5 context\n");
+        return -1;
+    }
+    av_md5_init(s->priv_data);
+    return 0;
+}
+
+static int write_packet(struct AVFormatContext *s, AVPacket *pkt)
+{
+    av_md5_update(s->priv_data, pkt->data, pkt->size);
+    return 0;
+}
+
+static int write_trailer(struct AVFormatContext *s)
+{
+    char buf[64] = "MD5=";
+
+    md5_finish(s, buf);
+    return 0;
+}
+
+AVOutputFormat ff_md5_muxer = {
+    "md5",
+    NULL_IF_CONFIG_SMALL("MD5 testing format"),
+    NULL,
+    "",
+    PRIVSIZE,
+    CODEC_ID_PCM_S16LE,
+    CODEC_ID_RAWVIDEO,
+    write_header,
+    write_packet,
+    write_trailer,
+};
+#endif
+
+#if CONFIG_FRAMEMD5_MUXER
+static int framemd5_write_packet(struct AVFormatContext *s, AVPacket *pkt)
+{
+    char buf[256];
+    if (PRIVSIZE < av_md5_size) {
+        av_log(s, AV_LOG_ERROR, "Insuffient size for md5 context\n");
+        return -1;
+    }
+    av_md5_init(s->priv_data);
+    av_md5_update(s->priv_data, pkt->data, pkt->size);
+
+    snprintf(buf, sizeof(buf) - 64, "%d, %"PRId64", %d, ", pkt->stream_index, pkt->dts, pkt->size);
+    md5_finish(s, buf);
+    return 0;
+}
+
+AVOutputFormat ff_framemd5_muxer = {
+    "framemd5",
+    NULL_IF_CONFIG_SMALL("Per-frame MD5 testing format"),
+    NULL,
+    "",
+    PRIVSIZE,
+    CODEC_ID_PCM_S16LE,
+    CODEC_ID_RAWVIDEO,
+    NULL,
+    framemd5_write_packet,
+    NULL,
+};
+#endif
diff --git a/libavformat/md5proto.c b/libavformat/md5proto.c
new file mode 100644
index 0000000..8b811ec
--- /dev/null
+++ b/libavformat/md5proto.c
@@ -0,0 +1,93 @@
+/*
+ * Copyright (c) 2010 Mans Rullgard
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <stdio.h>
+#include "libavutil/avstring.h"
+#include "libavutil/md5.h"
+#include "libavutil/mem.h"
+#include "libavutil/error.h"
+#include "avformat.h"
+#include "avio.h"
+#include "url.h"
+
+#define PRIV_SIZE 128
+
+static int md5_open(URLContext *h, const char *filename, int flags)
+{
+    if (PRIV_SIZE < av_md5_size) {
+        av_log(NULL, AV_LOG_ERROR, "Insuffient size for MD5 context\n");
+        return -1;
+    }
+
+    if (flags != AVIO_WRONLY)
+        return AVERROR(EINVAL);
+
+    av_md5_init(h->priv_data);
+
+    return 0;
+}
+
+static int md5_write(URLContext *h, const unsigned char *buf, int size)
+{
+    av_md5_update(h->priv_data, buf, size);
+    return size;
+}
+
+static int md5_close(URLContext *h)
+{
+    const char *filename = h->filename;
+    uint8_t md5[16], buf[64];
+    URLContext *out;
+    int i, err = 0;
+
+    av_md5_final(h->priv_data, md5);
+    for (i = 0; i < sizeof(md5); i++)
+        snprintf(buf + i*2, 3, "%02x", md5[i]);
+    buf[i*2] = '\n';
+
+    av_strstart(filename, "md5:", &filename);
+
+    if (*filename) {
+        err = ffurl_open(&out, filename, AVIO_WRONLY);
+        if (err)
+            return err;
+        err = ffurl_write(out, buf, i*2+1);
+        ffurl_close(out);
+    } else {
+        if (fwrite(buf, 1, i*2+1, stdout) < i*2+1)
+            err = AVERROR(errno);
+    }
+
+    return err;
+}
+
+static int md5_get_handle(URLContext *h)
+{
+    return (intptr_t)h->priv_data;
+}
+
+URLProtocol ff_md5_protocol = {
+    .name                = "md5",
+    .url_open            = md5_open,
+    .url_write           = md5_write,
+    .url_close           = md5_close,
+    .url_get_file_handle = md5_get_handle,
+    .priv_data_size      = PRIV_SIZE,
+};
diff --git a/libavformat/metadata.c b/libavformat/metadata.c
index ff7ffe9..36a9342 100644
--- a/libavformat/metadata.c
+++ b/libavformat/metadata.c
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2009 Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -49,7 +49,7 @@ av_metadata_get(AVMetadata *m, const char *key, const AVMetadataTag *prev, int f
 int av_metadata_set2(AVMetadata **pm, const char *key, const char *value, int flags)
 {
     AVMetadata *m= *pm;
-    AVMetadataTag *tag= av_metadata_get(m, key, NULL, AV_METADATA_MATCH_CASE);
+    AVMetadataTag *tag= av_metadata_get(m, key, NULL, flags);
 
     if(!m)
         m=*pm= av_mallocz(sizeof(*m));
@@ -86,13 +86,21 @@ int av_metadata_set2(AVMetadata **pm, const char *key, const char *value, int fl
     return 0;
 }
 
-#if LIBAVFORMAT_VERSION_MAJOR == 52
+#if FF_API_OLD_METADATA
 int av_metadata_set(AVMetadata **pm, const char *key, const char *value)
 {
     return av_metadata_set2(pm, key, value, 0);
 }
 #endif
 
+#if FF_API_OLD_METADATA2
+void av_metadata_conv(AVFormatContext *ctx, const AVMetadataConv *d_conv,
+                                            const AVMetadataConv *s_conv)
+{
+    return;
+}
+#endif
+
 void av_metadata_free(AVMetadata **pm)
 {
     AVMetadata *m= *pm;
@@ -107,8 +115,8 @@ void av_metadata_free(AVMetadata **pm)
     av_freep(pm);
 }
 
-void metadata_conv(AVMetadata **pm, const AVMetadataConv *d_conv,
-                                           const AVMetadataConv *s_conv)
+void ff_metadata_conv(AVMetadata **pm, const AVMetadataConv *d_conv,
+                                       const AVMetadataConv *s_conv)
 {
     /* TODO: use binary search to look up the two conversion tables
        if the tables are getting big enough that it would matter speed wise */
@@ -117,37 +125,46 @@ void metadata_conv(AVMetadata **pm, const AVMetadataConv *d_conv,
     AVMetadata *dst = NULL;
     const char *key;
 
+    if (d_conv == s_conv)
+        return;
+
     while((mtag=av_metadata_get(*pm, "", mtag, AV_METADATA_IGNORE_SUFFIX))) {
         key = mtag->key;
-        if (s_conv != d_conv) {
-            if (s_conv)
-                for (sc=s_conv; sc->native; sc++)
-                    if (!strcasecmp(key, sc->native)) {
-                        key = sc->generic;
-                        break;
-                    }
-            if (d_conv)
-                for (dc=d_conv; dc->native; dc++)
-                    if (!strcasecmp(key, dc->generic)) {
-                        key = dc->native;
-                        break;
-                    }
-        }
+        if (s_conv)
+            for (sc=s_conv; sc->native; sc++)
+                if (!strcasecmp(key, sc->native)) {
+                    key = sc->generic;
+                    break;
+                }
+        if (d_conv)
+            for (dc=d_conv; dc->native; dc++)
+                if (!strcasecmp(key, dc->generic)) {
+                    key = dc->native;
+                    break;
+                }
         av_metadata_set2(&dst, key, mtag->value, 0);
     }
     av_metadata_free(pm);
     *pm = dst;
 }
 
-void av_metadata_conv(AVFormatContext *ctx, const AVMetadataConv *d_conv,
-                                            const AVMetadataConv *s_conv)
+void ff_metadata_conv_ctx(AVFormatContext *ctx, const AVMetadataConv *d_conv,
+                                                const AVMetadataConv *s_conv)
 {
     int i;
-    metadata_conv(&ctx->metadata, d_conv, s_conv);
+    ff_metadata_conv(&ctx->metadata, d_conv, s_conv);
     for (i=0; i<ctx->nb_streams ; i++)
-        metadata_conv(&ctx->streams [i]->metadata, d_conv, s_conv);
+        ff_metadata_conv(&ctx->streams [i]->metadata, d_conv, s_conv);
     for (i=0; i<ctx->nb_chapters; i++)
-        metadata_conv(&ctx->chapters[i]->metadata, d_conv, s_conv);
+        ff_metadata_conv(&ctx->chapters[i]->metadata, d_conv, s_conv);
     for (i=0; i<ctx->nb_programs; i++)
-        metadata_conv(&ctx->programs[i]->metadata, d_conv, s_conv);
+        ff_metadata_conv(&ctx->programs[i]->metadata, d_conv, s_conv);
+}
+
+void av_metadata_copy(AVMetadata **dst, AVMetadata *src, int flags)
+{
+    AVMetadataTag *t = NULL;
+
+    while ((t = av_metadata_get(src, "", t, AV_METADATA_IGNORE_SUFFIX)))
+        av_metadata_set2(dst, t->key, t->value, flags);
 }
diff --git a/libavformat/metadata.h b/libavformat/metadata.h
index fe7130e..43eace8 100644
--- a/libavformat/metadata.h
+++ b/libavformat/metadata.h
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2009 Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -39,13 +39,18 @@ struct AVMetadataConv{
     const char *native;
     const char *generic;
 };
+#if !FF_API_OLD_METADATA2
+typedef struct AVMetadataConv AVMetadataConv;
+#endif
 
-#if LIBAVFORMAT_VERSION_MAJOR < 53
+#if FF_API_OLD_METADATA
 void ff_metadata_demux_compat(AVFormatContext *s);
 void ff_metadata_mux_compat(AVFormatContext *s);
 #endif
 
-void metadata_conv(AVMetadata **pm, const AVMetadataConv *d_conv,
-                                    const AVMetadataConv *s_conv);
+void ff_metadata_conv(AVMetadata **pm, const AVMetadataConv *d_conv,
+                                       const AVMetadataConv *s_conv);
+void ff_metadata_conv_ctx(AVFormatContext *ctx, const AVMetadataConv *d_conv,
+                                                const AVMetadataConv *s_conv);
 
 #endif /* AVFORMAT_METADATA_H */
diff --git a/libavformat/metadata_compat.c b/libavformat/metadata_compat.c
index ac99c05..bb73258 100644
--- a/libavformat/metadata_compat.c
+++ b/libavformat/metadata_compat.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2009  Aurelien Jacobs <aurel at gnuage.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -23,7 +23,7 @@
 #include "metadata.h"
 #include "libavutil/avstring.h"
 
-#if LIBAVFORMAT_VERSION_MAJOR < 53
+#if FF_API_OLD_METADATA
 
 #define SIZE_OFFSET(x) sizeof(((AVFormatContext*)0)->x),offsetof(AVFormatContext,x)
 
@@ -108,10 +108,11 @@ void ff_metadata_demux_compat(AVFormatContext *ctx)
 
 
 #define FILL_METADATA(s, key, value) {                                        \
-    if (value && *value && !av_metadata_get(s->metadata, #key, NULL, 0))      \
+    if (!av_metadata_get(s->metadata, #key, NULL, 0))                         \
         av_metadata_set2(&s->metadata, #key, value, 0);                       \
     }
-#define FILL_METADATA_STR(s, key)  FILL_METADATA(s, key, s->key)
+#define FILL_METADATA_STR(s, key) {                                           \
+    if (s->key && *s->key)  FILL_METADATA(s, key, s->key); }
 #define FILL_METADATA_INT(s, key) {                                           \
     char number[10];                                                          \
     snprintf(number, sizeof(number), "%d", s->key);                           \
@@ -144,4 +145,4 @@ void ff_metadata_mux_compat(AVFormatContext *ctx)
     }
 }
 
-#endif /* LIBAVFORMAT_VERSION_MAJOR < 53 */
+#endif /* FF_API_OLD_METADATA */
diff --git a/libavformat/mm.c b/libavformat/mm.c
index cb0917a..bea6161 100644
--- a/libavformat/mm.c
+++ b/libavformat/mm.c
@@ -2,20 +2,20 @@
  * American Laser Games MM Format Demuxer
  * Copyright (c) 2006 Peter Ross
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -84,25 +84,25 @@ static int read_header(AVFormatContext *s,
                            AVFormatParameters *ap)
 {
     MmDemuxContext *mm = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVStream *st;
 
     unsigned int type, length;
     unsigned int frame_rate, width, height;
 
-    type = get_le16(pb);
-    length = get_le32(pb);
+    type = avio_rl16(pb);
+    length = avio_rl32(pb);
 
     if (type != MM_TYPE_HEADER)
         return AVERROR_INVALIDDATA;
 
     /* read header */
-    get_le16(pb);   /* total number of chunks */
-    frame_rate = get_le16(pb);
-    get_le16(pb);   /* ibm-pc video bios mode */
-    width = get_le16(pb);
-    height = get_le16(pb);
-    url_fseek(pb, length - 10, SEEK_CUR);  /* unknown data */
+    avio_rl16(pb);   /* total number of chunks */
+    frame_rate = avio_rl16(pb);
+    avio_rl16(pb);   /* ibm-pc video bios mode */
+    width = avio_rl16(pb);
+    height = avio_rl16(pb);
+    avio_skip(pb, length - 10);  /* unknown data */
 
     /* video stream */
     st = av_new_stream(s, 0);
@@ -137,13 +137,13 @@ static int read_packet(AVFormatContext *s,
                            AVPacket *pkt)
 {
     MmDemuxContext *mm = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     unsigned char preamble[MM_PREAMBLE_SIZE];
     unsigned int type, length;
 
     while(1) {
 
-        if (get_buffer(pb, preamble, MM_PREAMBLE_SIZE) != MM_PREAMBLE_SIZE) {
+        if (avio_read(pb, preamble, MM_PREAMBLE_SIZE) != MM_PREAMBLE_SIZE) {
             return AVERROR(EIO);
         }
 
@@ -162,7 +162,7 @@ static int read_packet(AVFormatContext *s,
             if (av_new_packet(pkt, length + MM_PREAMBLE_SIZE))
                 return AVERROR(ENOMEM);
             memcpy(pkt->data, preamble, MM_PREAMBLE_SIZE);
-            if (get_buffer(pb, pkt->data + MM_PREAMBLE_SIZE, length) != length)
+            if (avio_read(pb, pkt->data + MM_PREAMBLE_SIZE, length) != length)
                 return AVERROR(EIO);
             pkt->size = length + MM_PREAMBLE_SIZE;
             pkt->stream_index = 0;
@@ -181,14 +181,14 @@ static int read_packet(AVFormatContext *s,
 
         default :
             av_log(s, AV_LOG_INFO, "unknown chunk type 0x%x\n", type);
-            url_fseek(pb, length, SEEK_CUR);
+            avio_skip(pb, length);
         }
     }
 
     return 0;
 }
 
-AVInputFormat mm_demuxer = {
+AVInputFormat ff_mm_demuxer = {
     "mm",
     NULL_IF_CONFIG_SMALL("American Laser Games MM format"),
     sizeof(MmDemuxContext),
diff --git a/libavformat/mmf.c b/libavformat/mmf.c
index 540407f..ec99c2d 100644
--- a/libavformat/mmf.c
+++ b/libavformat/mmf.c
@@ -2,24 +2,25 @@
  * Yamaha SMAF format
  * Copyright (c) 2005 Vidar Madsen
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #include "avformat.h"
-#include "raw.h"
+#include "avio_internal.h"
+#include "pcm.h"
 #include "riff.h"
 
 typedef struct {
@@ -47,20 +48,20 @@ static int mmf_rate_code(int rate)
 }
 
 /* Copy of end_tag() from avienc.c, but for big-endian chunk size */
-static void end_tag_be(ByteIOContext *pb, int64_t start)
+static void end_tag_be(AVIOContext *pb, int64_t start)
 {
     int64_t pos;
 
-    pos = url_ftell(pb);
-    url_fseek(pb, start - 4, SEEK_SET);
-    put_be32(pb, (uint32_t)(pos - start));
-    url_fseek(pb, pos, SEEK_SET);
+    pos = avio_tell(pb);
+    avio_seek(pb, start - 4, SEEK_SET);
+    avio_wb32(pb, (uint32_t)(pos - start));
+    avio_seek(pb, pos, SEEK_SET);
 }
 
 static int mmf_write_header(AVFormatContext *s)
 {
     MMFContext *mmf = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int64_t pos;
     int rate;
 
@@ -70,96 +71,96 @@ static int mmf_write_header(AVFormatContext *s)
         return -1;
     }
 
-    put_tag(pb, "MMMD");
-    put_be32(pb, 0);
+    ffio_wfourcc(pb, "MMMD");
+    avio_wb32(pb, 0);
     pos = ff_start_tag(pb, "CNTI");
-    put_byte(pb, 0); /* class */
-    put_byte(pb, 0); /* type */
-    put_byte(pb, 0); /* code type */
-    put_byte(pb, 0); /* status */
-    put_byte(pb, 0); /* counts */
-    put_tag(pb, "VN:libavcodec,"); /* metadata ("ST:songtitle,VN:version,...") */
+    avio_w8(pb, 0); /* class */
+    avio_w8(pb, 0); /* type */
+    avio_w8(pb, 0); /* code type */
+    avio_w8(pb, 0); /* status */
+    avio_w8(pb, 0); /* counts */
+    avio_write(pb, "VN:libavcodec,", sizeof("VN:libavcodec,") -1); /* metadata ("ST:songtitle,VN:version,...") */
     end_tag_be(pb, pos);
 
-    put_buffer(pb, "ATR\x00", 4);
-    put_be32(pb, 0);
-    mmf->atrpos = url_ftell(pb);
-    put_byte(pb, 0); /* format type */
-    put_byte(pb, 0); /* sequence type */
-    put_byte(pb, (0 << 7) | (1 << 4) | rate); /* (channel << 7) | (format << 4) | rate */
-    put_byte(pb, 0); /* wave base bit */
-    put_byte(pb, 2); /* time base d */
-    put_byte(pb, 2); /* time base g */
-
-    put_tag(pb, "Atsq");
-    put_be32(pb, 16);
-    mmf->atsqpos = url_ftell(pb);
+    avio_write(pb, "ATR\x00", 4);
+    avio_wb32(pb, 0);
+    mmf->atrpos = avio_tell(pb);
+    avio_w8(pb, 0); /* format type */
+    avio_w8(pb, 0); /* sequence type */
+    avio_w8(pb, (0 << 7) | (1 << 4) | rate); /* (channel << 7) | (format << 4) | rate */
+    avio_w8(pb, 0); /* wave base bit */
+    avio_w8(pb, 2); /* time base d */
+    avio_w8(pb, 2); /* time base g */
+
+    ffio_wfourcc(pb, "Atsq");
+    avio_wb32(pb, 16);
+    mmf->atsqpos = avio_tell(pb);
     /* Will be filled on close */
-    put_buffer(pb, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 16);
+    avio_write(pb, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 16);
 
     mmf->awapos = ff_start_tag(pb, "Awa\x01");
 
     av_set_pts_info(s->streams[0], 64, 1, s->streams[0]->codec->sample_rate);
 
-    put_flush_packet(pb);
+    avio_flush(pb);
 
     return 0;
 }
 
 static int mmf_write_packet(AVFormatContext *s, AVPacket *pkt)
 {
-    ByteIOContext *pb = s->pb;
-    put_buffer(pb, pkt->data, pkt->size);
+    AVIOContext *pb = s->pb;
+    avio_write(pb, pkt->data, pkt->size);
     return 0;
 }
 
 /* Write a variable-length symbol */
-static void put_varlength(ByteIOContext *pb, int val)
+static void put_varlength(AVIOContext *pb, int val)
 {
     if(val < 128)
-        put_byte(pb, val);
+        avio_w8(pb, val);
     else {
         val -= 128;
-        put_byte(pb, 0x80 | val >> 7);
-        put_byte(pb, 0x7f & val);
+        avio_w8(pb, 0x80 | val >> 7);
+        avio_w8(pb, 0x7f & val);
     }
 }
 
 static int mmf_write_trailer(AVFormatContext *s)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     MMFContext *mmf = s->priv_data;
     int64_t pos, size;
     int gatetime;
 
-    if (!url_is_streamed(s->pb)) {
+    if (s->pb->seekable) {
         /* Fill in length fields */
         end_tag_be(pb, mmf->awapos);
         end_tag_be(pb, mmf->atrpos);
         end_tag_be(pb, 8);
 
-        pos = url_ftell(pb);
+        pos = avio_tell(pb);
         size = pos - mmf->awapos;
 
         /* Fill Atsq chunk */
-        url_fseek(pb, mmf->atsqpos, SEEK_SET);
+        avio_seek(pb, mmf->atsqpos, SEEK_SET);
 
         /* "play wav" */
-        put_byte(pb, 0); /* start time */
-        put_byte(pb, 1); /* (channel << 6) | wavenum */
+        avio_w8(pb, 0); /* start time */
+        avio_w8(pb, 1); /* (channel << 6) | wavenum */
         gatetime = size * 500 / s->streams[0]->codec->sample_rate;
         put_varlength(pb, gatetime); /* duration */
 
         /* "nop" */
         put_varlength(pb, gatetime); /* start time */
-        put_buffer(pb, "\xff\x00", 2); /* nop */
+        avio_write(pb, "\xff\x00", 2); /* nop */
 
         /* "end of sequence" */
-        put_buffer(pb, "\x00\x00\x00\x00", 4);
+        avio_write(pb, "\x00\x00\x00\x00", 4);
 
-        url_fseek(pb, pos, SEEK_SET);
+        avio_seek(pb, pos, SEEK_SET);
 
-        put_flush_packet(pb);
+        avio_flush(pb);
     }
     return 0;
 }
@@ -183,20 +184,20 @@ static int mmf_read_header(AVFormatContext *s,
 {
     MMFContext *mmf = s->priv_data;
     unsigned int tag;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVStream *st;
     int64_t file_size, size;
     int rate, params;
 
-    tag = get_le32(pb);
+    tag = avio_rl32(pb);
     if (tag != MKTAG('M', 'M', 'M', 'D'))
         return -1;
-    file_size = get_be32(pb);
+    file_size = avio_rb32(pb);
 
     /* Skip some unused chunks that may or may not be present */
-    for(;; url_fseek(pb, size, SEEK_CUR)) {
-        tag = get_le32(pb);
-        size = get_be32(pb);
+    for(;; avio_skip(pb, size)) {
+        tag = avio_rl32(pb);
+        size = avio_rb32(pb);
         if(tag == MKTAG('C','N','T','I')) continue;
         if(tag == MKTAG('O','P','D','A')) continue;
         break;
@@ -212,22 +213,22 @@ static int mmf_read_header(AVFormatContext *s,
         return -1;
     }
 
-    get_byte(pb); /* format type */
-    get_byte(pb); /* sequence type */
-    params = get_byte(pb); /* (channel << 7) | (format << 4) | rate */
+    avio_r8(pb); /* format type */
+    avio_r8(pb); /* sequence type */
+    params = avio_r8(pb); /* (channel << 7) | (format << 4) | rate */
     rate = mmf_rate(params & 0x0f);
     if(rate  < 0) {
         av_log(s, AV_LOG_ERROR, "Invalid sample rate\n");
         return -1;
     }
-    get_byte(pb); /* wave base bit */
-    get_byte(pb); /* time base d */
-    get_byte(pb); /* time base g */
+    avio_r8(pb); /* wave base bit */
+    avio_r8(pb); /* time base d */
+    avio_r8(pb); /* time base g */
 
     /* Skip some unused chunks that may or may not be present */
-    for(;; url_fseek(pb, size, SEEK_CUR)) {
-        tag = get_le32(pb);
-        size = get_be32(pb);
+    for(;; avio_skip(pb, size)) {
+        tag = avio_rl32(pb);
+        size = avio_rb32(pb);
         if(tag == MKTAG('A','t','s','q')) continue;
         if(tag == MKTAG('A','s','p','I')) continue;
         break;
@@ -265,7 +266,7 @@ static int mmf_read_packet(AVFormatContext *s,
     AVStream *st;
     int ret, size;
 
-    if (url_feof(s->pb))
+    if (s->pb->eof_reached)
         return AVERROR(EIO);
     st = s->streams[0];
 
@@ -280,7 +281,7 @@ static int mmf_read_packet(AVFormatContext *s,
         return AVERROR(EIO);
     pkt->stream_index = 0;
 
-    ret = get_buffer(s->pb, pkt->data, pkt->size);
+    ret = avio_read(s->pb, pkt->data, pkt->size);
     if (ret < 0)
         av_free_packet(pkt);
 
@@ -291,7 +292,7 @@ static int mmf_read_packet(AVFormatContext *s,
 }
 
 #if CONFIG_MMF_DEMUXER
-AVInputFormat mmf_demuxer = {
+AVInputFormat ff_mmf_demuxer = {
     "mmf",
     NULL_IF_CONFIG_SMALL("Yamaha SMAF"),
     sizeof(MMFContext),
@@ -303,7 +304,7 @@ AVInputFormat mmf_demuxer = {
 };
 #endif
 #if CONFIG_MMF_MUXER
-AVOutputFormat mmf_muxer = {
+AVOutputFormat ff_mmf_muxer = {
     "mmf",
     NULL_IF_CONFIG_SMALL("Yamaha SMAF"),
     "application/vnd.smaf",
diff --git a/libavformat/mms.c b/libavformat/mms.c
new file mode 100644
index 0000000..5796663
--- /dev/null
+++ b/libavformat/mms.c
@@ -0,0 +1,153 @@
+/*
+ * MMS protocol common definitions.
+ * Copyright (c) 2006,2007 Ryan Martell
+ * Copyright (c) 2007 Björn Axelsson
+ * Copyright (c) 2010 Zhentan Feng <spyfeng at gmail dot com>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+#include "mms.h"
+#include "asf.h"
+#include "libavutil/intreadwrite.h"
+
+#if FF_API_MAX_STREAMS
+#define MMS_MAX_STREAMS MAX_STREAMS
+#else
+#define MMS_MAX_STREAMS 256    /**< arbitrary sanity check value */
+#endif
+
+int ff_mms_read_header(MMSContext *mms, uint8_t *buf, const int size)
+{
+    char *pos;
+    int size_to_copy;
+    int remaining_size = mms->asf_header_size - mms->asf_header_read_size;
+    size_to_copy = FFMIN(size, remaining_size);
+    pos = mms->asf_header + mms->asf_header_read_size;
+    memcpy(buf, pos, size_to_copy);
+    if (mms->asf_header_read_size == mms->asf_header_size) {
+        av_freep(&mms->asf_header); // which contains asf header
+    }
+    mms->asf_header_read_size += size_to_copy;
+    return size_to_copy;
+}
+
+int ff_mms_read_data(MMSContext *mms, uint8_t *buf, const int size)
+{
+    int read_size;
+    read_size = FFMIN(size, mms->remaining_in_len);
+    memcpy(buf, mms->read_in_ptr, read_size);
+    mms->remaining_in_len -= read_size;
+    mms->read_in_ptr      += read_size;
+    return read_size;
+}
+
+int ff_mms_asf_header_parser(MMSContext *mms)
+{
+    uint8_t *p = mms->asf_header;
+    uint8_t *end;
+    int flags, stream_id;
+    mms->stream_num = 0;
+
+    if (mms->asf_header_size < sizeof(ff_asf_guid) * 2 + 22 ||
+        memcmp(p, ff_asf_header, sizeof(ff_asf_guid))) {
+        av_log(NULL, AV_LOG_ERROR,
+               "Corrupt stream (invalid ASF header, size=%d)\n",
+               mms->asf_header_size);
+        return AVERROR_INVALIDDATA;
+    }
+
+    end = mms->asf_header + mms->asf_header_size;
+
+    p += sizeof(ff_asf_guid) + 14;
+    while(end - p >= sizeof(ff_asf_guid) + 8) {
+        uint64_t chunksize;
+        if (!memcmp(p, ff_asf_data_header, sizeof(ff_asf_guid))) {
+            chunksize = 50; // see Reference [2] section 5.1
+        } else {
+            chunksize = AV_RL64(p + sizeof(ff_asf_guid));
+        }
+        if (!chunksize || chunksize > end - p) {
+            av_log(NULL, AV_LOG_ERROR,
+                   "Corrupt stream (header chunksize %"PRId64" is invalid)\n",
+                   chunksize);
+            return AVERROR_INVALIDDATA;
+        }
+        if (!memcmp(p, ff_asf_file_header, sizeof(ff_asf_guid))) {
+            /* read packet size */
+            if (end - p > sizeof(ff_asf_guid) * 2 + 68) {
+                mms->asf_packet_len = AV_RL32(p + sizeof(ff_asf_guid) * 2 + 64);
+                if (mms->asf_packet_len <= 0 || mms->asf_packet_len > sizeof(mms->in_buffer)) {
+                    av_log(NULL, AV_LOG_ERROR,
+                           "Corrupt stream (too large pkt_len %d)\n",
+                           mms->asf_packet_len);
+                    return AVERROR_INVALIDDATA;
+                }
+            }
+        } else if (!memcmp(p, ff_asf_stream_header, sizeof(ff_asf_guid))) {
+            flags     = AV_RL16(p + sizeof(ff_asf_guid)*3 + 24);
+            stream_id = flags & 0x7F;
+            //The second condition is for checking CS_PKT_STREAM_ID_REQUEST packet size,
+            //we can calcuate the packet size by stream_num.
+            //Please see function send_stream_selection_request().
+            if (mms->stream_num < MMS_MAX_STREAMS &&
+                    46 + mms->stream_num * 6 < sizeof(mms->out_buffer)) {
+                mms->streams = av_fast_realloc(mms->streams,
+                                   &mms->nb_streams_allocated,
+                                   (mms->stream_num + 1) * sizeof(MMSStream));
+                mms->streams[mms->stream_num].id = stream_id;
+                mms->stream_num++;
+            } else {
+                av_log(NULL, AV_LOG_ERROR,
+                       "Corrupt stream (too many A/V streams)\n");
+                return AVERROR_INVALIDDATA;
+            }
+        } else if (!memcmp(p, ff_asf_ext_stream_header, sizeof(ff_asf_guid))) {
+            if (end - p >= 88) {
+                int stream_count = AV_RL16(p + 84), ext_len_count = AV_RL16(p + 86);
+                uint64_t skip_bytes = 88;
+                while (stream_count--) {
+                    if (end - p < skip_bytes + 4) {
+                        av_log(NULL, AV_LOG_ERROR,
+                               "Corrupt stream (next stream name length is not in the buffer)\n");
+                        return AVERROR_INVALIDDATA;
+                    }
+                    skip_bytes += 4 + AV_RL16(p + skip_bytes + 2);
+                }
+                while (ext_len_count--) {
+                    if (end - p < skip_bytes + 22) {
+                        av_log(NULL, AV_LOG_ERROR,
+                               "Corrupt stream (next extension system info length is not in the buffer)\n");
+                        return AVERROR_INVALIDDATA;
+                    }
+                    skip_bytes += 22 + AV_RL32(p + skip_bytes + 18);
+                }
+                if (end - p < skip_bytes) {
+                    av_log(NULL, AV_LOG_ERROR,
+                           "Corrupt stream (the last extension system info length is invalid)\n");
+                    return AVERROR_INVALIDDATA;
+                }
+                if (chunksize - skip_bytes > 24)
+                    chunksize = skip_bytes;
+            }
+        } else if (!memcmp(p, ff_asf_head1_guid, sizeof(ff_asf_guid))) {
+            chunksize = 46; // see references [2] section 3.4. This should be set 46.
+        }
+        p += chunksize;
+    }
+
+    return 0;
+}
diff --git a/libavformat/mms.h b/libavformat/mms.h
new file mode 100644
index 0000000..12e9ef0
--- /dev/null
+++ b/libavformat/mms.h
@@ -0,0 +1,63 @@
+/*
+ * MMS protocol common definitions.
+ * Copyright (c) 2010 Zhentan Feng <spyfeng at gmail dot com>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+#ifndef AVFORMAT_MMS_H
+#define AVFORMAT_MMS_H
+
+#include "url.h"
+
+typedef struct {
+    int id;
+}MMSStream;
+
+typedef struct {
+    URLContext *mms_hd;                  ///< TCP connection handle
+    MMSStream *streams;
+
+    /** Buffer for outgoing packets. */
+    /*@{*/
+    uint8_t *write_out_ptr;              ///< Pointer for writting the buffer.
+    uint8_t out_buffer[512];            ///< Buffer for outgoing packet.
+    /*@}*/
+
+    /** Buffer for incoming packets. */
+    /*@{*/
+    uint8_t in_buffer[65536];            ///< Buffer for incoming packets.
+    uint8_t *read_in_ptr;                ///< Pointer for reading from incoming buffer.
+    int remaining_in_len;                ///< Reading length from incoming buffer.
+    /*@}*/
+
+    /** Internal handling of the ASF header */
+    /*@{*/
+    uint8_t *asf_header;                 ///< Stored ASF header.
+    int asf_header_size;                 ///< Size of stored ASF header.
+    int header_parsed;                   ///< The header has been received and parsed.
+    int asf_packet_len;
+    int asf_header_read_size;
+    /*@}*/
+
+    int stream_num;                      ///< stream numbers.
+    unsigned int nb_streams_allocated;   ///< allocated size of streams
+} MMSContext;
+
+int ff_mms_asf_header_parser(MMSContext * mms);
+int ff_mms_read_data(MMSContext *mms, uint8_t *buf, const int size);
+int ff_mms_read_header(MMSContext * mms, uint8_t * buf, const int size);
+#endif
diff --git a/libavformat/mmsh.c b/libavformat/mmsh.c
new file mode 100644
index 0000000..1b9b494
--- /dev/null
+++ b/libavformat/mmsh.c
@@ -0,0 +1,370 @@
+/*
+ * MMS protocol over HTTP
+ * Copyright (c) 2010 Zhentan Feng <spyfeng at gmail dot com>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/*
+ * Reference
+ * Windows Media HTTP Streaming Protocol.
+ * http://msdn.microsoft.com/en-us/library/cc251059(PROT.10).aspx
+ */
+
+#include <string.h>
+#include "libavutil/intreadwrite.h"
+#include "libavutil/avstring.h"
+#include "libavformat/internal.h"
+#include "mms.h"
+#include "asf.h"
+#include "http.h"
+#include "url.h"
+
+#define CHUNK_HEADER_LENGTH 4   // 2bytes chunk type and 2bytes chunk length.
+#define EXT_HEADER_LENGTH   8   // 4bytes sequence, 2bytes useless and 2bytes chunk length.
+
+// see Ref 2.2.1.8
+#define USERAGENT  "User-Agent: NSPlayer/4.1.0.3856\r\n"
+// see Ref 2.2.1.4.33
+// the guid value can be changed to any valid value.
+#define CLIENTGUID "Pragma: xClientGUID={c77e7400-738a-11d2-9add-0020af0a3278}\r\n"
+
+// see Ref 2.2.3 for packet type define:
+// chunk type contains 2 fields: Frame and PacketID.
+// Frame is 0x24 or 0xA4(rarely), different PacketID indicates different packet type.
+typedef enum {
+    CHUNK_TYPE_DATA          = 0x4424,
+    CHUNK_TYPE_ASF_HEADER    = 0x4824,
+    CHUNK_TYPE_END           = 0x4524,
+    CHUNK_TYPE_STREAM_CHANGE = 0x4324,
+} ChunkType;
+
+typedef struct {
+    MMSContext mms;
+    int request_seq;  ///< request packet sequence
+    int chunk_seq;    ///< data packet sequence
+} MMSHContext;
+
+static int mmsh_close(URLContext *h)
+{
+    MMSHContext *mmsh = (MMSHContext *)h->priv_data;
+    MMSContext *mms   = &mmsh->mms;
+    if (mms->mms_hd)
+        ffurl_close(mms->mms_hd);
+    av_free(mms->streams);
+    av_free(mms->asf_header);
+    av_freep(&h->priv_data);
+    return 0;
+}
+
+static ChunkType get_chunk_header(MMSHContext *mmsh, int *len)
+{
+    MMSContext *mms = &mmsh->mms;
+    uint8_t chunk_header[CHUNK_HEADER_LENGTH];
+    uint8_t ext_header[EXT_HEADER_LENGTH];
+    ChunkType chunk_type;
+    int chunk_len, res, ext_header_len;
+
+    res = ffurl_read_complete(mms->mms_hd, chunk_header, CHUNK_HEADER_LENGTH);
+    if (res != CHUNK_HEADER_LENGTH) {
+        av_log(NULL, AV_LOG_ERROR, "Read data packet header failed!\n");
+        return AVERROR(EIO);
+    }
+    chunk_type = AV_RL16(chunk_header);
+    chunk_len  = AV_RL16(chunk_header + 2);
+
+    switch (chunk_type) {
+    case CHUNK_TYPE_END:
+    case CHUNK_TYPE_STREAM_CHANGE:
+        ext_header_len = 4;
+        break;
+    case CHUNK_TYPE_ASF_HEADER:
+    case CHUNK_TYPE_DATA:
+        ext_header_len = 8;
+        break;
+    default:
+        av_log(NULL, AV_LOG_ERROR, "Strange chunk type %d\n", chunk_type);
+        return AVERROR_INVALIDDATA;
+    }
+
+    res = ffurl_read_complete(mms->mms_hd, ext_header, ext_header_len);
+    if (res != ext_header_len) {
+        av_log(NULL, AV_LOG_ERROR, "Read ext header failed!\n");
+        return AVERROR(EIO);
+    }
+    *len = chunk_len - ext_header_len;
+    if (chunk_type == CHUNK_TYPE_END || chunk_type == CHUNK_TYPE_DATA)
+        mmsh->chunk_seq = AV_RL32(ext_header);
+    return chunk_type;
+}
+
+static int read_data_packet(MMSHContext *mmsh, const int len)
+{
+    MMSContext *mms   = &mmsh->mms;
+    int res;
+    if (len > sizeof(mms->in_buffer)) {
+        av_log(NULL, AV_LOG_ERROR,
+               "Data packet length %d exceeds the in_buffer size %zu\n",
+               len, sizeof(mms->in_buffer));
+        return AVERROR(EIO);
+    }
+    res = ffurl_read_complete(mms->mms_hd, mms->in_buffer, len);
+    av_dlog(NULL, "Data packet len = %d\n", len);
+    if (res != len) {
+        av_log(NULL, AV_LOG_ERROR, "Read data packet failed!\n");
+        return AVERROR(EIO);
+    }
+    if (len > mms->asf_packet_len) {
+        av_log(NULL, AV_LOG_ERROR,
+               "Chunk length %d exceed packet length %d\n",len, mms->asf_packet_len);
+        return AVERROR_INVALIDDATA;
+    } else {
+        memset(mms->in_buffer + len, 0, mms->asf_packet_len - len); // padding
+    }
+    mms->read_in_ptr      = mms->in_buffer;
+    mms->remaining_in_len = mms->asf_packet_len;
+    return 0;
+}
+
+static int get_http_header_data(MMSHContext *mmsh)
+{
+    MMSContext *mms = &mmsh->mms;
+    int res, len;
+    ChunkType chunk_type;
+
+    for (;;) {
+        len = 0;
+        res = chunk_type = get_chunk_header(mmsh, &len);
+        if (res < 0) {
+            return res;
+        } else if (chunk_type == CHUNK_TYPE_ASF_HEADER){
+            // get asf header and stored it
+            if (!mms->header_parsed) {
+                if (mms->asf_header) {
+                    if (len != mms->asf_header_size) {
+                        mms->asf_header_size = len;
+                        av_dlog(NULL, "Header len changed from %d to %d\n",
+                                mms->asf_header_size, len);
+                        av_freep(&mms->asf_header);
+                    }
+                }
+                mms->asf_header = av_mallocz(len);
+                if (!mms->asf_header) {
+                    return AVERROR(ENOMEM);
+                }
+                mms->asf_header_size = len;
+            }
+            if (len > mms->asf_header_size) {
+                av_log(NULL, AV_LOG_ERROR,
+                       "Asf header packet len = %d exceed the asf header buf size %d\n",
+                       len, mms->asf_header_size);
+                return AVERROR(EIO);
+            }
+            res = ffurl_read_complete(mms->mms_hd, mms->asf_header, len);
+            if (res != len) {
+                av_log(NULL, AV_LOG_ERROR,
+                       "Recv asf header data len %d != expected len %d\n", res, len);
+                return AVERROR(EIO);
+            }
+            mms->asf_header_size = len;
+            if (!mms->header_parsed) {
+                res = ff_mms_asf_header_parser(mms);
+                mms->header_parsed = 1;
+                return res;
+            }
+        } else if (chunk_type == CHUNK_TYPE_DATA) {
+            // read data packet and do padding
+            return read_data_packet(mmsh, len);
+        } else {
+            if (len) {
+                if (len > sizeof(mms->in_buffer)) {
+                    av_log(NULL, AV_LOG_ERROR,
+                           "Other packet len = %d exceed the in_buffer size %zu\n",
+                           len, sizeof(mms->in_buffer));
+                    return AVERROR(EIO);
+                }
+                res = ffurl_read_complete(mms->mms_hd, mms->in_buffer, len);
+                if (res != len) {
+                    av_log(NULL, AV_LOG_ERROR, "Read other chunk type data failed!\n");
+                    return AVERROR(EIO);
+                } else {
+                    av_dlog(NULL, "Skip chunk type %d \n", chunk_type);
+                    continue;
+                }
+            }
+        }
+    }
+    return 0;
+}
+
+static int mmsh_open(URLContext *h, const char *uri, int flags)
+{
+    int i, port, err;
+    char httpname[256], path[256], host[128], location[1024];
+    char *stream_selection = NULL;
+    char headers[1024];
+    MMSHContext *mmsh;
+    MMSContext *mms;
+
+    mmsh = h->priv_data = av_mallocz(sizeof(MMSHContext));
+    if (!h->priv_data)
+        return AVERROR(ENOMEM);
+    mmsh->request_seq = h->is_streamed = 1;
+    mms = &mmsh->mms;
+    av_strlcpy(location, uri, sizeof(location));
+
+    av_url_split(NULL, 0, NULL, 0,
+        host, sizeof(host), &port, path, sizeof(path), location);
+    if (port<0)
+        port = 80; // default mmsh protocol port
+    ff_url_join(httpname, sizeof(httpname), "http", NULL, host, port, path);
+
+    if (ffurl_alloc(&mms->mms_hd, httpname, AVIO_RDONLY) < 0) {
+        return AVERROR(EIO);
+    }
+
+    snprintf(headers, sizeof(headers),
+             "Accept: */*\r\n"
+             USERAGENT
+             "Host: %s:%d\r\n"
+             "Pragma: no-cache,rate=1.000000,stream-time=0,"
+             "stream-offset=0:0,request-context=%u,max-duration=0\r\n"
+             CLIENTGUID
+             "Connection: Close\r\n\r\n",
+             host, port, mmsh->request_seq++);
+    ff_http_set_headers(mms->mms_hd, headers);
+
+    err = ffurl_connect(mms->mms_hd);
+    if (err) {
+        goto fail;
+    }
+    err = get_http_header_data(mmsh);
+    if (err) {
+        av_log(NULL, AV_LOG_ERROR, "Get http header data failed!\n");
+        goto fail;
+    }
+
+    // close the socket and then reopen it for sending the second play request.
+    ffurl_close(mms->mms_hd);
+    memset(headers, 0, sizeof(headers));
+    if (ffurl_alloc(&mms->mms_hd, httpname, AVIO_RDONLY) < 0) {
+        return AVERROR(EIO);
+    }
+    stream_selection = av_mallocz(mms->stream_num * 19 + 1);
+    if (!stream_selection)
+        return AVERROR(ENOMEM);
+    for (i = 0; i < mms->stream_num; i++) {
+        char tmp[20];
+        err = snprintf(tmp, sizeof(tmp), "ffff:%d:0 ", mms->streams[i].id);
+        if (err < 0)
+            goto fail;
+        av_strlcat(stream_selection, tmp, mms->stream_num * 19 + 1);
+    }
+    // send play request
+    err = snprintf(headers, sizeof(headers),
+                   "Accept: */*\r\n"
+                   USERAGENT
+                   "Host: %s:%d\r\n"
+                   "Pragma: no-cache,rate=1.000000,request-context=%u\r\n"
+                   "Pragma: xPlayStrm=1\r\n"
+                   CLIENTGUID
+                   "Pragma: stream-switch-count=%d\r\n"
+                   "Pragma: stream-switch-entry=%s\r\n"
+                   "Connection: Close\r\n\r\n",
+                   host, port, mmsh->request_seq++, mms->stream_num, stream_selection);
+    av_freep(&stream_selection);
+    if (err < 0) {
+        av_log(NULL, AV_LOG_ERROR, "Build play request failed!\n");
+        goto fail;
+    }
+    av_dlog(NULL, "out_buffer is %s", headers);
+    ff_http_set_headers(mms->mms_hd, headers);
+
+    err = ffurl_connect(mms->mms_hd);
+    if (err) {
+          goto fail;
+    }
+
+    err = get_http_header_data(mmsh);
+    if (err) {
+        av_log(NULL, AV_LOG_ERROR, "Get http header data failed!\n");
+        goto fail;
+    }
+
+    av_dlog(NULL, "Connection successfully open\n");
+    return 0;
+fail:
+    av_freep(&stream_selection);
+    mmsh_close(h);
+    av_dlog(NULL, "Connection failed with error %d\n", err);
+    return err;
+}
+
+static int handle_chunk_type(MMSHContext *mmsh)
+{
+    MMSContext *mms = &mmsh->mms;
+    int res, len = 0;
+    ChunkType chunk_type;
+    chunk_type = get_chunk_header(mmsh, &len);
+
+    switch (chunk_type) {
+    case CHUNK_TYPE_END:
+        mmsh->chunk_seq = 0;
+        av_log(NULL, AV_LOG_ERROR, "Stream ended!\n");
+        return AVERROR(EIO);
+    case CHUNK_TYPE_STREAM_CHANGE:
+        mms->header_parsed = 0;
+        if (res = get_http_header_data(mmsh)) {
+            av_log(NULL, AV_LOG_ERROR,"Stream changed! Failed to get new header!\n");
+            return res;
+        }
+        break;
+    case CHUNK_TYPE_DATA:
+        return read_data_packet(mmsh, len);
+    default:
+        av_log(NULL, AV_LOG_ERROR, "Recv other type packet %d\n", chunk_type);
+        return AVERROR_INVALIDDATA;
+    }
+    return 0;
+}
+
+static int mmsh_read(URLContext *h, uint8_t *buf, int size)
+{
+    int res = 0;
+    MMSHContext *mmsh = h->priv_data;
+    MMSContext *mms   = &mmsh->mms;
+    do {
+        if (mms->asf_header_read_size < mms->asf_header_size) {
+            // copy asf header into buffer
+            res = ff_mms_read_header(mms, buf, size);
+        } else {
+            if (!mms->remaining_in_len && (res = handle_chunk_type(mmsh)))
+                return res;
+            res = ff_mms_read_data(mms, buf, size);
+        }
+    } while (!res);
+    return res;
+}
+
+URLProtocol ff_mmsh_protocol = {
+    .name      = "mmsh",
+    .url_open  = mmsh_open,
+    .url_read  = mmsh_read,
+    .url_write = NULL,
+    .url_seek  = NULL,
+    .url_close = mmsh_close,
+};
diff --git a/libavformat/mmst.c b/libavformat/mmst.c
new file mode 100644
index 0000000..a3f2609
--- /dev/null
+++ b/libavformat/mmst.c
@@ -0,0 +1,630 @@
+/*
+ * MMS protocol over TCP
+ * Copyright (c) 2006,2007 Ryan Martell
+ * Copyright (c) 2007 Björn Axelsson
+ * Copyright (c) 2010 Zhentan Feng <spyfeng at gmail dot com>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/* References
+ * MMS protocol specification:
+ *  [1]http://msdn.microsoft.com/en-us/library/cc234711(PROT.10).aspx
+ * ASF specification. Revision 01.20.03.
+ *  [2]http://msdn.microsoft.com/en-us/library/bb643323.aspx
+ */
+
+#include "avformat.h"
+#include "mms.h"
+#include "internal.h"
+#include "avio_internal.h"
+#include "libavutil/intreadwrite.h"
+#include "libavcodec/bytestream.h"
+#include "network.h"
+#include "url.h"
+
+#define LOCAL_ADDRESS 0xc0a80081    // FIXME get and use correct local ip address.
+#define LOCAL_PORT    1037          // as above.
+/** Client to server packet types. */
+typedef enum {
+    CS_PKT_INITIAL                  = 0x01,
+    CS_PKT_PROTOCOL_SELECT          = 0x02,
+    CS_PKT_MEDIA_FILE_REQUEST       = 0x05,
+    CS_PKT_START_FROM_PKT_ID        = 0x07,
+    CS_PKT_STREAM_PAUSE             = 0x09,
+    CS_PKT_STREAM_CLOSE             = 0x0d,
+    CS_PKT_MEDIA_HEADER_REQUEST     = 0x15,
+    CS_PKT_TIMING_DATA_REQUEST      = 0x18,
+    CS_PKT_USER_PASSWORD            = 0x1a,
+    CS_PKT_KEEPALIVE                = 0x1b,
+    CS_PKT_STREAM_ID_REQUEST        = 0x33,
+} MMSCSPacketType;
+
+/** Server to client packet types. */
+typedef enum {
+    /** Control packets. */
+    /*@{*/
+    SC_PKT_CLIENT_ACCEPTED          = 0x01,
+    SC_PKT_PROTOCOL_ACCEPTED        = 0x02,
+    SC_PKT_PROTOCOL_FAILED          = 0x03,
+    SC_PKT_MEDIA_PKT_FOLLOWS        = 0x05,
+    SC_PKT_MEDIA_FILE_DETAILS       = 0x06,
+    SC_PKT_HEADER_REQUEST_ACCEPTED  = 0x11,
+    SC_PKT_TIMING_TEST_REPLY        = 0x15,
+    SC_PKT_PASSWORD_REQUIRED        = 0x1a,
+    SC_PKT_KEEPALIVE                = 0x1b,
+    SC_PKT_STREAM_STOPPED           = 0x1e,
+    SC_PKT_STREAM_CHANGING          = 0x20,
+    SC_PKT_STREAM_ID_ACCEPTED       = 0x21,
+    /*@}*/
+
+    /** Pseudo packets. */
+    /*@{*/
+    SC_PKT_CANCEL                   = -1,
+    SC_PKT_NO_DATA                  = -2,
+    /*@}*/
+
+    /** Data packets. */
+    /*@{*/
+    SC_PKT_ASF_HEADER               = 0x010000,// make it bigger than 0xFF in case of
+    SC_PKT_ASF_MEDIA                = 0x010001,// receiving false data packets.
+    /*@}*/
+} MMSSCPacketType;
+
+typedef struct {
+    MMSContext  mms;
+    int outgoing_packet_seq;             ///< Outgoing packet sequence number.
+    char path[256];                      ///< Path of the resource being asked for.
+    char host[128];                      ///< Host of the resources.
+    int incoming_packet_seq;             ///< Incoming packet sequence number.
+    int incoming_flags;                  ///< Incoming packet flags.
+    int packet_id;                       ///< Identifier for packets in the current stream.
+    unsigned int header_packet_id;       ///< default is 2.
+} MMSTContext;
+
+/** Create MMST command packet header */
+static void start_command_packet(MMSTContext *mmst, MMSCSPacketType packet_type)
+{
+    MMSContext *mms    = &mmst->mms;
+    mms->write_out_ptr = mms->out_buffer;
+
+    bytestream_put_le32(&mms->write_out_ptr, 1); // start sequence
+    bytestream_put_le32(&mms->write_out_ptr, 0xb00bface);
+    bytestream_put_le32(&mms->write_out_ptr, 0); // Length starts from after the protocol type bytes
+    bytestream_put_le32(&mms->write_out_ptr, MKTAG('M','M','S',' '));
+    bytestream_put_le32(&mms->write_out_ptr, 0);
+    bytestream_put_le32(&mms->write_out_ptr, mmst->outgoing_packet_seq++);
+    bytestream_put_le64(&mms->write_out_ptr, 0); // timestamp
+    bytestream_put_le32(&mms->write_out_ptr, 0);
+    bytestream_put_le16(&mms->write_out_ptr, packet_type);
+    bytestream_put_le16(&mms->write_out_ptr, 3); // direction to server
+}
+
+/** Add prefixes to MMST command packet. */
+static void insert_command_prefixes(MMSContext *mms,
+        uint32_t prefix1, uint32_t prefix2)
+{
+    bytestream_put_le32(&mms->write_out_ptr, prefix1); // first prefix
+    bytestream_put_le32(&mms->write_out_ptr, prefix2); // second prefix
+}
+
+/** Send a prepared MMST command packet. */
+static int send_command_packet(MMSTContext *mmst)
+{
+    MMSContext *mms  = &mmst->mms;
+    int len= mms->write_out_ptr - mms->out_buffer;
+    int exact_length = FFALIGN(len, 8);
+    int first_length= exact_length - 16;
+    int len8= first_length/8;
+    int write_result;
+
+    // update packet length fields.
+    AV_WL32(mms->out_buffer + 8, first_length);
+    AV_WL32(mms->out_buffer + 16, len8);
+    AV_WL32(mms->out_buffer + 32, len8-2);
+    memset(mms->write_out_ptr, 0, exact_length - len);
+
+    // write it out.
+    write_result= ffurl_write(mms->mms_hd, mms->out_buffer, exact_length);
+    if(write_result != exact_length) {
+        av_log(NULL, AV_LOG_ERROR,
+               "Failed to write data of length %d: %d (%s)\n",
+               exact_length, write_result,
+               write_result < 0 ? strerror(write_result) :
+                   "The server closed the connection");
+        return AVERROR(EIO);
+    }
+
+    return 0;
+}
+
+static void mms_put_utf16(MMSContext *mms, uint8_t *src)
+{
+    AVIOContext bic;
+    int size = mms->write_out_ptr - mms->out_buffer;
+    int len;
+    ffio_init_context(&bic, mms->write_out_ptr,
+            sizeof(mms->out_buffer) - size, 1, NULL, NULL, NULL, NULL);
+
+    len = avio_put_str16le(&bic, src);
+    mms->write_out_ptr += len;
+}
+
+static int send_time_test_data(MMSTContext *mmst)
+{
+    start_command_packet(mmst, CS_PKT_TIMING_DATA_REQUEST);
+    insert_command_prefixes(&mmst->mms, 0x00f0f0f0, 0x0004000b);
+    return send_command_packet(mmst);
+}
+
+static int send_protocol_select(MMSTContext *mmst)
+{
+    char data_string[256];
+    MMSContext *mms = &mmst->mms;
+
+    start_command_packet(mmst, CS_PKT_PROTOCOL_SELECT);
+    insert_command_prefixes(mms, 0, 0xffffffff);
+    bytestream_put_le32(&mms->write_out_ptr, 0);          // maxFunnelBytes
+    bytestream_put_le32(&mms->write_out_ptr, 0x00989680); // maxbitRate
+    bytestream_put_le32(&mms->write_out_ptr, 2);          // funnelMode
+    snprintf(data_string, sizeof(data_string), "\\\\%d.%d.%d.%d\\%s\\%d",
+            (LOCAL_ADDRESS>>24)&0xff,
+            (LOCAL_ADDRESS>>16)&0xff,
+            (LOCAL_ADDRESS>>8)&0xff,
+            LOCAL_ADDRESS&0xff,
+            "TCP",                                        // or UDP
+            LOCAL_PORT);
+
+    mms_put_utf16(mms, data_string);
+    return send_command_packet(mmst);
+}
+
+static int send_media_file_request(MMSTContext *mmst)
+{
+    MMSContext *mms = &mmst->mms;
+    start_command_packet(mmst, CS_PKT_MEDIA_FILE_REQUEST);
+    insert_command_prefixes(mms, 1, 0xffffffff);
+    bytestream_put_le32(&mms->write_out_ptr, 0);
+    bytestream_put_le32(&mms->write_out_ptr, 0);
+    mms_put_utf16(mms, mmst->path + 1); // +1 for skip "/"
+
+    return send_command_packet(mmst);
+}
+
+static void handle_packet_stream_changing_type(MMSTContext *mmst)
+{
+    MMSContext *mms = &mmst->mms;
+    av_dlog(NULL, "Stream changing!\n");
+
+    // 40 is the packet header size, 7 is the prefix size.
+    mmst->header_packet_id= AV_RL32(mms->in_buffer + 40 + 7);
+    av_dlog(NULL, "Changed header prefix to 0x%x", mmst->header_packet_id);
+}
+
+static int send_keepalive_packet(MMSTContext *mmst)
+{
+    // respond to a keepalive with a keepalive...
+    start_command_packet(mmst, CS_PKT_KEEPALIVE);
+    insert_command_prefixes(&mmst->mms, 1, 0x100FFFF);
+    return send_command_packet(mmst);
+}
+
+/** Pad media packets smaller than max_packet_size and/or adjust read position
+  * after a seek. */
+static void pad_media_packet(MMSContext *mms)
+{
+    if(mms->remaining_in_len<mms->asf_packet_len) {
+        int padding_size = mms->asf_packet_len - mms->remaining_in_len;
+        memset(mms->in_buffer + mms->remaining_in_len, 0, padding_size);
+        mms->remaining_in_len += padding_size;
+    }
+}
+
+/** Read incoming MMST media, header or command packet. */
+static MMSSCPacketType get_tcp_server_response(MMSTContext *mmst)
+{
+    int read_result;
+    MMSSCPacketType packet_type= -1;
+    MMSContext *mms = &mmst->mms;
+    for(;;) {
+        read_result = ffurl_read_complete(mms->mms_hd, mms->in_buffer, 8);
+        if (read_result != 8) {
+            if(read_result < 0) {
+                av_log(NULL, AV_LOG_ERROR,
+                       "Error reading packet header: %d (%s)\n",
+                       read_result, strerror(read_result));
+                packet_type = SC_PKT_CANCEL;
+            } else {
+                av_log(NULL, AV_LOG_ERROR,
+                       "The server closed the connection\n");
+                packet_type = SC_PKT_NO_DATA;
+            }
+            return packet_type;
+        }
+
+        // handle command packet.
+        if(AV_RL32(mms->in_buffer + 4)==0xb00bface) {
+            int length_remaining, hr;
+
+            mmst->incoming_flags= mms->in_buffer[3];
+            read_result= ffurl_read_complete(mms->mms_hd, mms->in_buffer+8, 4);
+            if(read_result != 4) {
+                av_log(NULL, AV_LOG_ERROR,
+                       "Reading command packet length failed: %d (%s)\n",
+                       read_result,
+                       read_result < 0 ? strerror(read_result) :
+                           "The server closed the connection");
+                return read_result < 0 ? read_result : AVERROR(EIO);
+            }
+
+            length_remaining= AV_RL32(mms->in_buffer+8) + 4;
+            av_dlog(NULL, "Length remaining is %d\n", length_remaining);
+            // read the rest of the packet.
+            if (length_remaining < 0
+                || length_remaining > sizeof(mms->in_buffer) - 12) {
+                av_log(NULL, AV_LOG_ERROR,
+                       "Incoming packet length %d exceeds bufsize %zu\n",
+                       length_remaining, sizeof(mms->in_buffer) - 12);
+                return AVERROR_INVALIDDATA;
+            }
+            read_result = ffurl_read_complete(mms->mms_hd, mms->in_buffer + 12,
+                                            length_remaining) ;
+            if (read_result != length_remaining) {
+                av_log(NULL, AV_LOG_ERROR,
+                       "Reading pkt data (length=%d) failed: %d (%s)\n",
+                       length_remaining, read_result,
+                       read_result < 0 ? strerror(read_result) :
+                           "The server closed the connection");
+                return read_result < 0 ? read_result : AVERROR(EIO);
+            }
+            packet_type= AV_RL16(mms->in_buffer+36);
+            if (read_result >= 44 && (hr = AV_RL32(mms->in_buffer + 40))) {
+                av_log(NULL, AV_LOG_ERROR,
+                       "Server sent a message with packet type 0x%x and error status code 0x%08x\n", packet_type, hr);
+                return AVERROR(EINVAL);
+            }
+        } else {
+            int length_remaining;
+            int packet_id_type;
+            int tmp;
+
+            // note we cache the first 8 bytes,
+            // then fill up the buffer with the others
+            tmp                       = AV_RL16(mms->in_buffer + 6);
+            length_remaining          = (tmp - 8) & 0xffff;
+            mmst->incoming_packet_seq = AV_RL32(mms->in_buffer);
+            packet_id_type            = mms->in_buffer[4];
+            mmst->incoming_flags      = mms->in_buffer[5];
+
+            if (length_remaining < 0
+                || length_remaining > sizeof(mms->in_buffer) - 8) {
+                av_log(NULL, AV_LOG_ERROR,
+                       "Data length %d is invalid or too large (max=%zu)\n",
+                       length_remaining, sizeof(mms->in_buffer));
+                return AVERROR_INVALIDDATA;
+            }
+            mms->remaining_in_len    = length_remaining;
+            mms->read_in_ptr         = mms->in_buffer;
+            read_result= ffurl_read_complete(mms->mms_hd, mms->in_buffer, length_remaining);
+            if(read_result != length_remaining) {
+                av_log(NULL, AV_LOG_ERROR,
+                       "Failed to read packet data of size %d: %d (%s)\n",
+                       length_remaining, read_result,
+                       read_result < 0 ? strerror(read_result) :
+                           "The server closed the connection");
+                return read_result < 0 ? read_result : AVERROR(EIO);
+            }
+
+            // if we successfully read everything.
+            if(packet_id_type == mmst->header_packet_id) {
+                packet_type = SC_PKT_ASF_HEADER;
+                // Store the asf header
+                if(!mms->header_parsed) {
+                    void *p = av_realloc(mms->asf_header,
+                                  mms->asf_header_size + mms->remaining_in_len);
+                    if (!p) {
+                        av_freep(&mms->asf_header);
+                        return AVERROR(ENOMEM);
+                    }
+                    mms->asf_header = p;
+                    memcpy(mms->asf_header + mms->asf_header_size,
+                           mms->read_in_ptr, mms->remaining_in_len);
+                    mms->asf_header_size += mms->remaining_in_len;
+                }
+                // 0x04 means asf header is sent in multiple packets.
+                if (mmst->incoming_flags == 0x04)
+                    continue;
+            } else if(packet_id_type == mmst->packet_id) {
+                packet_type = SC_PKT_ASF_MEDIA;
+            } else {
+                av_dlog(NULL, "packet id type %d is old.", packet_id_type);
+                continue;
+            }
+        }
+
+        // preprocess some packet type
+        if(packet_type == SC_PKT_KEEPALIVE) {
+            send_keepalive_packet(mmst);
+            continue;
+        } else if(packet_type == SC_PKT_STREAM_CHANGING) {
+            handle_packet_stream_changing_type(mmst);
+        } else if(packet_type == SC_PKT_ASF_MEDIA) {
+            pad_media_packet(mms);
+        }
+        return packet_type;
+    }
+}
+
+static int mms_safe_send_recv(MMSTContext *mmst,
+                              int (*send_fun)(MMSTContext *mmst),
+                              const MMSSCPacketType expect_type)
+{
+    MMSSCPacketType type;
+    if(send_fun) {
+        int ret = send_fun(mmst);
+        if (ret < 0) {
+            av_dlog(NULL, "Send Packet error before expecting recv packet %d\n", expect_type);
+            return ret;
+        }
+    }
+
+    if ((type = get_tcp_server_response(mmst)) != expect_type) {
+        av_log(NULL, AV_LOG_ERROR,
+               "Corrupt stream (unexpected packet type 0x%x, expected 0x%x)\n",
+               type, expect_type);
+        return AVERROR_INVALIDDATA;
+    } else {
+        return 0;
+    }
+}
+
+static int send_media_header_request(MMSTContext *mmst)
+{
+    MMSContext *mms = &mmst->mms;
+    start_command_packet(mmst, CS_PKT_MEDIA_HEADER_REQUEST);
+    insert_command_prefixes(mms, 1, 0);
+    bytestream_put_le32(&mms->write_out_ptr, 0);
+    bytestream_put_le32(&mms->write_out_ptr, 0x00800000);
+    bytestream_put_le32(&mms->write_out_ptr, 0xffffffff);
+    bytestream_put_le32(&mms->write_out_ptr, 0);
+    bytestream_put_le32(&mms->write_out_ptr, 0);
+    bytestream_put_le32(&mms->write_out_ptr, 0);
+
+    // the media preroll value in milliseconds?
+    bytestream_put_le32(&mms->write_out_ptr, 0);
+    bytestream_put_le32(&mms->write_out_ptr, 0x40AC2000);
+    bytestream_put_le32(&mms->write_out_ptr, 2);
+    bytestream_put_le32(&mms->write_out_ptr, 0);
+
+    return send_command_packet(mmst);
+}
+
+/** Send the initial handshake. */
+static int send_startup_packet(MMSTContext *mmst)
+{
+    char data_string[256];
+    MMSContext *mms = &mmst->mms;
+    // SubscriberName is defined in MS specification linked below.
+    // The guid value can be any valid value.
+    // http://download.microsoft.com/
+    // download/9/5/E/95EF66AF-9026-4BB0-A41D-A4F81802D92C/%5BMS-WMSP%5D.pdf
+    snprintf(data_string, sizeof(data_string),
+            "NSPlayer/7.0.0.1956; {%s}; Host: %s",
+            "7E667F5D-A661-495E-A512-F55686DDA178", mmst->host);
+
+    start_command_packet(mmst, CS_PKT_INITIAL);
+    insert_command_prefixes(mms, 0, 0x0004000b);
+    bytestream_put_le32(&mms->write_out_ptr, 0x0003001c);
+    mms_put_utf16(mms, data_string);
+    return send_command_packet(mmst);
+}
+
+/** Send MMST stream selection command based on the AVStream->discard values. */
+static int send_stream_selection_request(MMSTContext *mmst)
+{
+    int i;
+    MMSContext *mms = &mmst->mms;
+    //  send the streams we want back...
+    start_command_packet(mmst, CS_PKT_STREAM_ID_REQUEST);
+    bytestream_put_le32(&mms->write_out_ptr, mms->stream_num);         // stream nums
+    for(i= 0; i<mms->stream_num; i++) {
+        bytestream_put_le16(&mms->write_out_ptr, 0xffff);              // flags
+        bytestream_put_le16(&mms->write_out_ptr, mms->streams[i].id);  // stream id
+        bytestream_put_le16(&mms->write_out_ptr, 0);                   // selection
+    }
+    return send_command_packet(mmst);
+}
+
+static int send_close_packet(MMSTContext *mmst)
+{
+    start_command_packet(mmst, CS_PKT_STREAM_CLOSE);
+    insert_command_prefixes(&mmst->mms, 1, 1);
+
+    return send_command_packet(mmst);
+}
+
+/** Close the MMSH/MMST connection */
+static int mms_close(URLContext *h)
+{
+    MMSTContext *mmst = (MMSTContext *)h->priv_data;
+    MMSContext *mms   = &mmst->mms;
+    if(mms->mms_hd) {
+        send_close_packet(mmst);
+        ffurl_close(mms->mms_hd);
+    }
+
+    /* free all separately allocated pointers in mms */
+    av_free(mms->streams);
+    av_free(mms->asf_header);
+    av_freep(&h->priv_data);
+
+    return 0;
+}
+
+static int send_media_packet_request(MMSTContext *mmst)
+{
+    MMSContext *mms = &mmst->mms;
+    start_command_packet(mmst, CS_PKT_START_FROM_PKT_ID);
+    insert_command_prefixes(mms, 1, 0x0001FFFF);
+    bytestream_put_le64(&mms->write_out_ptr, 0);          // seek timestamp
+    bytestream_put_le32(&mms->write_out_ptr, 0xffffffff); // unknown
+    bytestream_put_le32(&mms->write_out_ptr, 0xffffffff); // packet offset
+    bytestream_put_byte(&mms->write_out_ptr, 0xff);       // max stream time limit
+    bytestream_put_byte(&mms->write_out_ptr, 0xff);       // max stream time limit
+    bytestream_put_byte(&mms->write_out_ptr, 0xff);       // max stream time limit
+    bytestream_put_byte(&mms->write_out_ptr, 0x00);       // stream time limit flag
+
+    mmst->packet_id++;                                     // new packet_id
+    bytestream_put_le32(&mms->write_out_ptr, mmst->packet_id);
+    return send_command_packet(mmst);
+}
+
+
+static void clear_stream_buffers(MMSContext *mms)
+{
+    mms->remaining_in_len = 0;
+    mms->read_in_ptr      = mms->in_buffer;
+}
+
+static int mms_open(URLContext *h, const char *uri, int flags)
+{
+    MMSTContext *mmst;
+    MMSContext *mms;
+    int port, err;
+    char tcpname[256];
+
+    h->is_streamed = 1;
+    mmst = h->priv_data = av_mallocz(sizeof(MMSTContext));
+    if (!h->priv_data)
+        return AVERROR(ENOMEM);
+    mms = &mmst->mms;
+
+    // only for MMS over TCP, so set proto = NULL
+    av_url_split(NULL, 0, NULL, 0,
+            mmst->host, sizeof(mmst->host), &port, mmst->path,
+            sizeof(mmst->path), uri);
+
+    if(port<0)
+        port = 1755; // defaut mms protocol port
+
+    // establish tcp connection.
+    ff_url_join(tcpname, sizeof(tcpname), "tcp", NULL, mmst->host, port, NULL);
+    err = ffurl_open(&mms->mms_hd, tcpname, AVIO_RDWR);
+    if (err)
+        goto fail;
+
+    mmst->packet_id        = 3;          // default, initial value.
+    mmst->header_packet_id = 2;          // default, initial value.
+    err = mms_safe_send_recv(mmst, send_startup_packet, SC_PKT_CLIENT_ACCEPTED);
+    if (err)
+        goto fail;
+    err = mms_safe_send_recv(mmst, send_time_test_data, SC_PKT_TIMING_TEST_REPLY);
+    if (err)
+        goto fail;
+    err = mms_safe_send_recv(mmst, send_protocol_select, SC_PKT_PROTOCOL_ACCEPTED);
+    if (err)
+        goto fail;
+    err = mms_safe_send_recv(mmst, send_media_file_request, SC_PKT_MEDIA_FILE_DETAILS);
+    if (err)
+        goto fail;
+    err = mms_safe_send_recv(mmst, send_media_header_request, SC_PKT_HEADER_REQUEST_ACCEPTED);
+    if (err)
+        goto fail;
+    err = mms_safe_send_recv(mmst, NULL, SC_PKT_ASF_HEADER);
+    if (err)
+        goto fail;
+    if((mmst->incoming_flags != 0X08) && (mmst->incoming_flags != 0X0C)) {
+        av_log(NULL, AV_LOG_ERROR,
+               "The server does not support MMST (try MMSH or RTSP)\n");
+        err = AVERROR(EINVAL);
+        goto fail;
+    }
+    err = ff_mms_asf_header_parser(mms);
+    if (err) {
+        av_dlog(NULL, "asf header parsed failed!\n");
+        goto fail;
+    }
+    mms->header_parsed = 1;
+
+    if (!mms->asf_packet_len || !mms->stream_num)
+        goto fail;
+
+    clear_stream_buffers(mms);
+    err = mms_safe_send_recv(mmst, send_stream_selection_request, SC_PKT_STREAM_ID_ACCEPTED);
+    if (err)
+        goto fail;
+    // send media packet request
+    err = mms_safe_send_recv(mmst, send_media_packet_request, SC_PKT_MEDIA_PKT_FOLLOWS);
+    if (err) {
+        goto fail;
+    }
+    av_dlog(NULL, "Leaving open (success)\n");
+    return 0;
+fail:
+    mms_close(h);
+    av_dlog(NULL, "Leaving open (failure: %d)\n", err);
+    return err;
+}
+
+/** Read ASF data through the protocol. */
+static int mms_read(URLContext *h, uint8_t *buf, int size)
+{
+    /* TODO: see tcp.c:tcp_read() about a possible timeout scheme */
+    MMSTContext *mmst = h->priv_data;
+    MMSContext *mms   = &mmst->mms;
+    int result = 0;
+
+    do {
+        if(mms->asf_header_read_size < mms->asf_header_size) {
+            /* Read from ASF header buffer */
+            result = ff_mms_read_header(mms, buf, size);
+        } else if(mms->remaining_in_len) {
+            /* Read remaining packet data to buffer.
+             * the result can not be zero because remaining_in_len is positive.*/
+            result = ff_mms_read_data(mms, buf, size);
+        } else {
+            /* Read from network */
+            int err = mms_safe_send_recv(mmst, NULL, SC_PKT_ASF_MEDIA);
+            if (err == 0) {
+                if(mms->remaining_in_len>mms->asf_packet_len) {
+                    av_log(NULL, AV_LOG_ERROR,
+                           "Incoming pktlen %d is larger than ASF pktsize %d\n",
+                           mms->remaining_in_len, mms->asf_packet_len);
+                    result= AVERROR(EIO);
+                } else {
+                    // copy the data to the packet buffer.
+                    result = ff_mms_read_data(mms, buf, size);
+                    if (result == 0) {
+                        av_dlog(NULL, "read asf media paket size is zero!\n");
+                        break;
+                    }
+                }
+            } else {
+                av_dlog(NULL, "read packet error!\n");
+                break;
+            }
+        }
+    } while(!result); // only return one packet.
+    return result;
+}
+
+URLProtocol ff_mmst_protocol = {
+    .name      = "mmst",
+    .url_open  = mms_open,
+    .url_read  = mms_read,
+    .url_close = mms_close,
+};
diff --git a/libavformat/mov.c b/libavformat/mov.c
index 2edd27e..bd8cf03 100644
--- a/libavformat/mov.c
+++ b/libavformat/mov.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2001 Fabrice Bellard
  * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -29,10 +29,9 @@
 #include "libavutil/intreadwrite.h"
 #include "libavutil/avstring.h"
 #include "avformat.h"
+#include "avio_internal.h"
 #include "riff.h"
 #include "isom.h"
-#include "libavcodec/mpeg4audio.h"
-#include "libavcodec/mpegaudiodata.h"
 #include "libavcodec/get_bits.h"
 
 #if CONFIG_ZLIB
@@ -75,20 +74,20 @@
 /* links atom IDs to parse functions */
 typedef struct MOVParseTableEntry {
     uint32_t type;
-    int (*parse)(MOVContext *ctx, ByteIOContext *pb, MOVAtom atom);
+    int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
 } MOVParseTableEntry;
 
 static const MOVParseTableEntry mov_default_parse_table[];
 
-static int mov_metadata_trkn(MOVContext *c, ByteIOContext *pb, unsigned len)
+static int mov_metadata_trkn(MOVContext *c, AVIOContext *pb, unsigned len)
 {
     char buf[16];
 
-    get_be16(pb); // unknown
-    snprintf(buf, sizeof(buf), "%d", get_be16(pb));
+    avio_rb16(pb); // unknown
+    snprintf(buf, sizeof(buf), "%d", avio_rb16(pb));
     av_metadata_set2(&c->fc->metadata, "track", buf, 0);
 
-    get_be16(pb); // total tracks
+    avio_rb16(pb); // total tracks
 
     return 0;
 }
@@ -112,7 +111,7 @@ static const uint32_t mac_to_unicode[128] = {
     0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
 };
 
-static int mov_read_mac_string(MOVContext *c, ByteIOContext *pb, int len,
+static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
                                char *dst, int dstlen)
 {
     char *p = dst;
@@ -120,7 +119,7 @@ static int mov_read_mac_string(MOVContext *c, ByteIOContext *pb, int len,
     int i;
 
     for (i = 0; i < len; i++) {
-        uint8_t t, c = get_byte(pb);
+        uint8_t t, c = avio_r8(pb);
         if (c < 0x80 && p < end)
             *p++ = c;
         else
@@ -130,7 +129,7 @@ static int mov_read_mac_string(MOVContext *c, ByteIOContext *pb, int len,
     return p - dst;
 }
 
-static int mov_read_udta_string(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
+static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 {
 #ifdef MOV_EXPORT_ALL_METADATA
     char tmp_key[5];
@@ -139,7 +138,7 @@ static int mov_read_udta_string(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     const char *key = NULL;
     uint16_t str_size, langcode = 0;
     uint32_t data_type = 0;
-    int (*parse)(MOVContext*, ByteIOContext*, unsigned) = NULL;
+    int (*parse)(MOVContext*, AVIOContext*, unsigned) = NULL;
 
     switch (atom.type) {
     case MKTAG(0xa9,'n','a','m'): key = "title";     break;
@@ -154,6 +153,7 @@ static int mov_read_udta_string(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     case MKTAG(0xa9,'d','a','y'): key = "date";      break;
     case MKTAG(0xa9,'g','e','n'): key = "genre";     break;
     case MKTAG(0xa9,'t','o','o'):
+    case MKTAG(0xa9,'s','w','r'): key = "encoder";   break;
     case MKTAG(0xa9,'e','n','c'): key = "encoder";   break;
     case MKTAG( 'd','e','s','c'): key = "description";break;
     case MKTAG( 'l','d','e','s'): key = "synopsis";  break;
@@ -165,17 +165,17 @@ static int mov_read_udta_string(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     }
 
     if (c->itunes_metadata && atom.size > 8) {
-        int data_size = get_be32(pb);
-        int tag = get_le32(pb);
+        int data_size = avio_rb32(pb);
+        int tag = avio_rl32(pb);
         if (tag == MKTAG('d','a','t','a')) {
-            data_type = get_be32(pb); // type
-            get_be32(pb); // unknown
+            data_type = avio_rb32(pb); // type
+            avio_rb32(pb); // unknown
             str_size = data_size - 16;
             atom.size -= 16;
         } else return 0;
     } else if (atom.size > 4 && key && !c->itunes_metadata) {
-        str_size = get_be16(pb); // string length
-        langcode = get_be16(pb);
+        str_size = avio_rb16(pb); // string length
+        langcode = avio_rb16(pb);
         ff_mov_lang_to_iso639(langcode, language);
         atom.size -= 4;
     } else
@@ -201,7 +201,7 @@ static int mov_read_udta_string(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
         if (data_type == 3 || (data_type == 0 && langcode < 0x800)) { // MAC Encoded
             mov_read_mac_string(c, pb, str_size, str, sizeof(str));
         } else {
-            get_buffer(pb, str, str_size);
+            avio_read(pb, str, str_size);
             str[str_size] = 0;
         }
         av_metadata_set2(&c->fc->metadata, key, str, 0);
@@ -219,37 +219,39 @@ static int mov_read_udta_string(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     return 0;
 }
 
-static int mov_read_chpl(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
+static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 {
     int64_t start;
-    int i, nb_chapters, str_len;
+    int i, nb_chapters, str_len, version;
     char str[256+1];
 
     if ((atom.size -= 5) < 0)
         return 0;
 
-    get_be32(pb); // version + flags
-    get_be32(pb); // ???
-    nb_chapters = get_byte(pb);
+    version = avio_r8(pb);
+    avio_rb24(pb);
+    if (version)
+        avio_rb32(pb); // ???
+    nb_chapters = avio_r8(pb);
 
     for (i = 0; i < nb_chapters; i++) {
         if (atom.size < 9)
             return 0;
 
-        start = get_be64(pb);
-        str_len = get_byte(pb);
+        start = avio_rb64(pb);
+        str_len = avio_r8(pb);
 
         if ((atom.size -= 9+str_len) < 0)
             return 0;
 
-        get_buffer(pb, str, str_len);
+        avio_read(pb, str, str_len);
         str[str_len] = 0;
         ff_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
     }
     return 0;
 }
 
-static int mov_read_default(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
+static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 {
     int64_t total_size = 0;
     MOVAtom a;
@@ -257,19 +259,19 @@ static int mov_read_default(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 
     if (atom.size < 0)
         atom.size = INT64_MAX;
-    while (total_size + 8 < atom.size && !url_feof(pb)) {
-        int (*parse)(MOVContext*, ByteIOContext*, MOVAtom) = NULL;
+    while (total_size + 8 < atom.size && !pb->eof_reached) {
+        int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
         a.size = atom.size;
         a.type=0;
         if(atom.size >= 8) {
-            a.size = get_be32(pb);
-            a.type = get_le32(pb);
+            a.size = avio_rb32(pb);
+            a.type = avio_rl32(pb);
         }
+        av_dlog(c->fc, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
+                a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
         total_size += 8;
-        dprintf(c->fc, "type: %08x  %.4s  sz: %"PRIx64"  %"PRIx64"   %"PRIx64"\n",
-                a.type, (char*)&a.type, a.size, atom.size, total_size);
         if (a.size == 1) { /* 64 bit extended size */
-            a.size = get_be64(pb) - 8;
+            a.size = avio_rb64(pb) - 8;
             total_size += 8;
         }
         if (a.size == 0) {
@@ -294,31 +296,31 @@ static int mov_read_default(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
             parse = mov_read_udta_string;
 
         if (!parse) { /* skip leaf atoms data */
-            url_fskip(pb, a.size);
+            avio_skip(pb, a.size);
         } else {
-            int64_t start_pos = url_ftell(pb);
+            int64_t start_pos = avio_tell(pb);
             int64_t left;
             int err = parse(c, pb, a);
             if (err < 0)
                 return err;
             if (c->found_moov && c->found_mdat &&
-                (url_is_streamed(pb) || start_pos + a.size == url_fsize(pb)))
+                (!pb->seekable || start_pos + a.size == avio_size(pb)))
                 return 0;
-            left = a.size - url_ftell(pb) + start_pos;
+            left = a.size - avio_tell(pb) + start_pos;
             if (left > 0) /* skip garbage at atom end */
-                url_fskip(pb, left);
+                avio_skip(pb, left);
         }
 
         total_size += a.size;
     }
 
     if (total_size < atom.size && atom.size < 0x7ffff)
-        url_fskip(pb, atom.size - total_size);
+        avio_skip(pb, atom.size - total_size);
 
     return 0;
 }
 
-static int mov_read_dref(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
+static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 {
     AVStream *st;
     MOVStreamContext *sc;
@@ -329,8 +331,8 @@ static int mov_read_dref(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     st = c->fc->streams[c->fc->nb_streams-1];
     sc = st->priv_data;
 
-    get_be32(pb); // version + flags
-    entries = get_be32(pb);
+    avio_rb32(pb); // version + flags
+    entries = avio_rb32(pb);
     if (entries >= UINT_MAX / sizeof(*sc->drefs))
         return -1;
     sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
@@ -340,47 +342,50 @@ static int mov_read_dref(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 
     for (i = 0; i < sc->drefs_count; i++) {
         MOVDref *dref = &sc->drefs[i];
-        uint32_t size = get_be32(pb);
-        int64_t next = url_ftell(pb) + size - 4;
+        uint32_t size = avio_rb32(pb);
+        int64_t next = avio_tell(pb) + size - 4;
 
-        dref->type = get_le32(pb);
-        get_be32(pb); // version + flags
-        dprintf(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
+        if (size < 12)
+            return -1;
+
+        dref->type = avio_rl32(pb);
+        avio_rb32(pb); // version + flags
+        av_dlog(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
 
         if (dref->type == MKTAG('a','l','i','s') && size > 150) {
             /* macintosh alias record */
             uint16_t volume_len, len;
             int16_t type;
 
-            url_fskip(pb, 10);
+            avio_skip(pb, 10);
 
-            volume_len = get_byte(pb);
+            volume_len = avio_r8(pb);
             volume_len = FFMIN(volume_len, 27);
-            get_buffer(pb, dref->volume, 27);
+            avio_read(pb, dref->volume, 27);
             dref->volume[volume_len] = 0;
             av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
 
-            url_fskip(pb, 12);
+            avio_skip(pb, 12);
 
-            len = get_byte(pb);
+            len = avio_r8(pb);
             len = FFMIN(len, 63);
-            get_buffer(pb, dref->filename, 63);
+            avio_read(pb, dref->filename, 63);
             dref->filename[len] = 0;
             av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
 
-            url_fskip(pb, 16);
+            avio_skip(pb, 16);
 
             /* read next level up_from_alias/down_to_target */
-            dref->nlvl_from = get_be16(pb);
-            dref->nlvl_to   = get_be16(pb);
+            dref->nlvl_from = avio_rb16(pb);
+            dref->nlvl_to   = avio_rb16(pb);
             av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
                    dref->nlvl_from, dref->nlvl_to);
 
-            url_fskip(pb, 16);
+            avio_skip(pb, 16);
 
-            for (type = 0; type != -1 && url_ftell(pb) < next; ) {
-                type = get_be16(pb);
-                len = get_be16(pb);
+            for (type = 0; type != -1 && avio_tell(pb) < next; ) {
+                type = avio_rb16(pb);
+                len = avio_rb16(pb);
                 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
                 if (len&1)
                     len += 1;
@@ -389,7 +394,7 @@ static int mov_read_dref(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
                     dref->path = av_mallocz(len+1);
                     if (!dref->path)
                         return AVERROR(ENOMEM);
-                    get_buffer(pb, dref->path, len);
+                    avio_read(pb, dref->path, len);
                     if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
                         len -= volume_len;
                         memmove(dref->path, dref->path+volume_len, len);
@@ -404,22 +409,22 @@ static int mov_read_dref(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
                     dref->dir = av_malloc(len+1);
                     if (!dref->dir)
                         return AVERROR(ENOMEM);
-                    get_buffer(pb, dref->dir, len);
+                    avio_read(pb, dref->dir, len);
                     dref->dir[len] = 0;
                     for (j = 0; j < len; j++)
                         if (dref->dir[j] == ':')
                             dref->dir[j] = '/';
                     av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
                 } else
-                    url_fskip(pb, len);
+                    avio_skip(pb, len);
             }
         }
-        url_fseek(pb, next, SEEK_SET);
+        avio_seek(pb, next, SEEK_SET);
     }
     return 0;
 }
 
-static int mov_read_hdlr(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
+static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 {
     AVStream *st;
     uint32_t type;
@@ -430,15 +435,15 @@ static int mov_read_hdlr(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 
     st = c->fc->streams[c->fc->nb_streams-1];
 
-    get_byte(pb); /* version */
-    get_be24(pb); /* flags */
+    avio_r8(pb); /* version */
+    avio_rb24(pb); /* flags */
 
     /* component type */
-    ctype = get_le32(pb);
-    type = get_le32(pb); /* component subtype */
+    ctype = avio_rl32(pb);
+    type = avio_rl32(pb); /* component subtype */
 
-    dprintf(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
-    dprintf(c->fc, "stype= %.4s\n", (char*)&type);
+    av_dlog(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
+    av_dlog(c->fc, "stype= %.4s\n", (char*)&type);
 
     if     (type == MKTAG('v','i','d','e'))
         st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
@@ -449,49 +454,14 @@ static int mov_read_hdlr(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     else if(type == MKTAG('s','u','b','p'))
         st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
 
-    get_be32(pb); /* component  manufacture */
-    get_be32(pb); /* component flags */
-    get_be32(pb); /* component flags mask */
+    avio_rb32(pb); /* component  manufacture */
+    avio_rb32(pb); /* component flags */
+    avio_rb32(pb); /* component flags mask */
 
     return 0;
 }
 
-int ff_mp4_read_descr_len(ByteIOContext *pb)
-{
-    int len = 0;
-    int count = 4;
-    while (count--) {
-        int c = get_byte(pb);
-        len = (len << 7) | (c & 0x7f);
-        if (!(c & 0x80))
-            break;
-    }
-    return len;
-}
-
-static int mp4_read_descr(AVFormatContext *fc, ByteIOContext *pb, int *tag)
-{
-    int len;
-    *tag = get_byte(pb);
-    len = ff_mp4_read_descr_len(pb);
-    dprintf(fc, "MPEG4 description: tag=0x%02x len=%d\n", *tag, len);
-    return len;
-}
-
-#define MP4ESDescrTag                   0x03
-#define MP4DecConfigDescrTag            0x04
-#define MP4DecSpecificDescrTag          0x05
-
-static const AVCodecTag mp4_audio_types[] = {
-    { CODEC_ID_MP3ON4, AOT_PS   }, /* old mp3on4 draft */
-    { CODEC_ID_MP3ON4, AOT_L1   }, /* layer 1 */
-    { CODEC_ID_MP3ON4, AOT_L2   }, /* layer 2 */
-    { CODEC_ID_MP3ON4, AOT_L3   }, /* layer 3 */
-    { CODEC_ID_MP4ALS, AOT_ALS  }, /* MPEG-4 ALS */
-    { CODEC_ID_NONE,   AOT_NULL },
-};
-
-int ff_mov_read_esds(AVFormatContext *fc, ByteIOContext *pb, MOVAtom atom)
+int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb, MOVAtom atom)
 {
     AVStream *st;
     int tag, len;
@@ -500,77 +470,63 @@ int ff_mov_read_esds(AVFormatContext *fc, ByteIOContext *pb, MOVAtom atom)
         return 0;
     st = fc->streams[fc->nb_streams-1];
 
-    get_be32(pb); /* version + flags */
-    len = mp4_read_descr(fc, pb, &tag);
+    avio_rb32(pb); /* version + flags */
+    len = ff_mp4_read_descr(fc, pb, &tag);
     if (tag == MP4ESDescrTag) {
-        get_be16(pb); /* ID */
-        get_byte(pb); /* priority */
+        avio_rb16(pb); /* ID */
+        avio_r8(pb); /* priority */
     } else
-        get_be16(pb); /* ID */
-
-    len = mp4_read_descr(fc, pb, &tag);
-    if (tag == MP4DecConfigDescrTag) {
-        int object_type_id = get_byte(pb);
-        get_byte(pb); /* stream type */
-        get_be24(pb); /* buffer size db */
-        get_be32(pb); /* max bitrate */
-        get_be32(pb); /* avg bitrate */
-
-        st->codec->codec_id= ff_codec_get_id(ff_mp4_obj_type, object_type_id);
-        dprintf(fc, "esds object type id 0x%02x\n", object_type_id);
-        len = mp4_read_descr(fc, pb, &tag);
-        if (tag == MP4DecSpecificDescrTag) {
-            dprintf(fc, "Specific MPEG4 header len=%d\n", len);
-            if((uint64_t)len > (1<<30))
-                return -1;
-            st->codec->extradata = av_mallocz(len + FF_INPUT_BUFFER_PADDING_SIZE);
-            if (!st->codec->extradata)
-                return AVERROR(ENOMEM);
-            get_buffer(pb, st->codec->extradata, len);
-            st->codec->extradata_size = len;
-            if (st->codec->codec_id == CODEC_ID_AAC) {
-                MPEG4AudioConfig cfg;
-                ff_mpeg4audio_get_config(&cfg, st->codec->extradata,
-                                         st->codec->extradata_size);
-                st->codec->channels = cfg.channels;
-                if (cfg.object_type == 29 && cfg.sampling_index < 3) // old mp3on4
-                    st->codec->sample_rate = ff_mpa_freq_tab[cfg.sampling_index];
-                else
-                    st->codec->sample_rate = cfg.sample_rate; // ext sample rate ?
-                dprintf(fc, "mp4a config channels %d obj %d ext obj %d "
-                        "sample rate %d ext sample rate %d\n", st->codec->channels,
-                        cfg.object_type, cfg.ext_object_type,
-                        cfg.sample_rate, cfg.ext_sample_rate);
-                if (!(st->codec->codec_id = ff_codec_get_id(mp4_audio_types,
-                                                            cfg.object_type)))
-                    st->codec->codec_id = CODEC_ID_AAC;
-            }
-        }
-    }
+        avio_rb16(pb); /* ID */
+
+    len = ff_mp4_read_descr(fc, pb, &tag);
+    if (tag == MP4DecConfigDescrTag)
+        ff_mp4_read_dec_config_descr(fc, st, pb);
     return 0;
 }
 
-static int mov_read_esds(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
+static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 {
     return ff_mov_read_esds(c->fc, pb, atom);
 }
 
-static int mov_read_pasp(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
+static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 {
-    const int num = get_be32(pb);
-    const int den = get_be32(pb);
     AVStream *st;
+    int ac3info, acmod, lfeon, bsmod;
 
     if (c->fc->nb_streams < 1)
         return 0;
     st = c->fc->streams[c->fc->nb_streams-1];
 
-    if (den != 0) {
-        if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
-            (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num))
-            av_log(c->fc, AV_LOG_WARNING,
-                   "sample aspect ratio already set to %d:%d, overriding by 'pasp' atom\n",
-                   st->sample_aspect_ratio.num, st->sample_aspect_ratio.den);
+    ac3info = avio_rb24(pb);
+    bsmod = (ac3info >> 14) & 0x7;
+    acmod = (ac3info >> 11) & 0x7;
+    lfeon = (ac3info >> 10) & 0x1;
+    st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
+    st->codec->audio_service_type = bsmod;
+    if (st->codec->channels > 1 && bsmod == 0x7)
+        st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
+
+    return 0;
+}
+
+static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
+{
+    const int num = avio_rb32(pb);
+    const int den = avio_rb32(pb);
+    AVStream *st;
+
+    if (c->fc->nb_streams < 1)
+        return 0;
+    st = c->fc->streams[c->fc->nb_streams-1];
+
+    if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
+        (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
+        av_log(c->fc, AV_LOG_WARNING,
+               "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
+               st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
+               num, den);
+    } else if (den != 0) {
         st->sample_aspect_ratio.num = num;
         st->sample_aspect_ratio.den = den;
     }
@@ -578,7 +534,7 @@ static int mov_read_pasp(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 }
 
 /* this atom contains actual media data */
-static int mov_read_mdat(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
+static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 {
     if(atom.size == 0) /* wrong one (MP4) */
         return 0;
@@ -587,7 +543,7 @@ static int mov_read_mdat(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 }
 
 /* read major brand, minor version and compatible brands and store them as metadata */
-static int mov_read_ftyp(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
+static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 {
     uint32_t minor_ver;
     int comp_brand_size;
@@ -595,12 +551,12 @@ static int mov_read_ftyp(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     char* comp_brands_str;
     uint8_t type[5] = {0};
 
-    get_buffer(pb, type, 4);
+    avio_read(pb, type, 4);
     if (strcmp(type, "qt  "))
         c->isom = 1;
     av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
     av_metadata_set2(&c->fc->metadata, "major_brand", type, 0);
-    minor_ver = get_be32(pb); /* minor version */
+    minor_ver = avio_rb32(pb); /* minor version */
     snprintf(minor_ver_str, sizeof(minor_ver_str), "%d", minor_ver);
     av_metadata_set2(&c->fc->metadata, "minor_version", minor_ver_str, 0);
 
@@ -610,7 +566,7 @@ static int mov_read_ftyp(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
     if (!comp_brands_str)
         return AVERROR(ENOMEM);
-    get_buffer(pb, comp_brands_str, comp_brand_size);
+    avio_read(pb, comp_brands_str, comp_brand_size);
     comp_brands_str[comp_brand_size] = 0;
     av_metadata_set2(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
     av_freep(&comp_brands_str);
@@ -619,7 +575,7 @@ static int mov_read_ftyp(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 }
 
 /* this atom should contain all header atoms */
-static int mov_read_moov(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
+static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 {
     if (mov_read_default(c, pb, atom) < 0)
         return -1;
@@ -629,87 +585,104 @@ static int mov_read_moov(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     return 0; /* now go for mdat */
 }
 
-static int mov_read_moof(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
+static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 {
-    c->fragment.moof_offset = url_ftell(pb) - 8;
-    dprintf(c->fc, "moof offset %llx\n", c->fragment.moof_offset);
+    c->fragment.moof_offset = avio_tell(pb) - 8;
+    av_dlog(c->fc, "moof offset %llx\n", c->fragment.moof_offset);
     return mov_read_default(c, pb, atom);
 }
 
-static int mov_read_mdhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
+static void mov_metadata_creation_time(AVMetadata **metadata, time_t time)
+{
+    char buffer[32];
+    if (time) {
+        struct tm *ptm;
+        time -= 2082844800;  /* seconds between 1904-01-01 and Epoch */
+        ptm = gmtime(&time);
+        if (!ptm) return;
+        strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm);
+        av_metadata_set2(metadata, "creation_time", buffer, 0);
+    }
+}
+
+static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 {
     AVStream *st;
     MOVStreamContext *sc;
     int version;
     char language[4] = {0};
     unsigned lang;
+    time_t creation_time;
 
     if (c->fc->nb_streams < 1)
         return 0;
     st = c->fc->streams[c->fc->nb_streams-1];
     sc = st->priv_data;
 
-    version = get_byte(pb);
+    version = avio_r8(pb);
     if (version > 1)
         return -1; /* unsupported */
 
-    get_be24(pb); /* flags */
+    avio_rb24(pb); /* flags */
     if (version == 1) {
-        get_be64(pb);
-        get_be64(pb);
+        creation_time = avio_rb64(pb);
+        avio_rb64(pb);
     } else {
-        get_be32(pb); /* creation time */
-        get_be32(pb); /* modification time */
+        creation_time = avio_rb32(pb);
+        avio_rb32(pb); /* modification time */
     }
+    mov_metadata_creation_time(&st->metadata, creation_time);
 
-    sc->time_scale = get_be32(pb);
-    st->duration = (version == 1) ? get_be64(pb) : get_be32(pb); /* duration */
+    sc->time_scale = avio_rb32(pb);
+    st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
 
-    lang = get_be16(pb); /* language */
+    lang = avio_rb16(pb); /* language */
     if (ff_mov_lang_to_iso639(lang, language))
         av_metadata_set2(&st->metadata, "language", language, 0);
-    get_be16(pb); /* quality */
+    avio_rb16(pb); /* quality */
 
     return 0;
 }
 
-static int mov_read_mvhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
+static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 {
-    int version = get_byte(pb); /* version */
-    get_be24(pb); /* flags */
+    time_t creation_time;
+    int version = avio_r8(pb); /* version */
+    avio_rb24(pb); /* flags */
 
     if (version == 1) {
-        get_be64(pb);
-        get_be64(pb);
+        creation_time = avio_rb64(pb);
+        avio_rb64(pb);
     } else {
-        get_be32(pb); /* creation time */
-        get_be32(pb); /* modification time */
+        creation_time = avio_rb32(pb);
+        avio_rb32(pb); /* modification time */
     }
-    c->time_scale = get_be32(pb); /* time scale */
+    mov_metadata_creation_time(&c->fc->metadata, creation_time);
+    c->time_scale = avio_rb32(pb); /* time scale */
 
-    dprintf(c->fc, "time scale = %i\n", c->time_scale);
+    av_dlog(c->fc, "time scale = %i\n", c->time_scale);
 
-    c->duration = (version == 1) ? get_be64(pb) : get_be32(pb); /* duration */
-    get_be32(pb); /* preferred scale */
+    c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
+    avio_rb32(pb); /* preferred scale */
 
-    get_be16(pb); /* preferred volume */
+    avio_rb16(pb); /* preferred volume */
 
-    url_fskip(pb, 10); /* reserved */
+    avio_skip(pb, 10); /* reserved */
 
-    url_fskip(pb, 36); /* display matrix */
+    avio_skip(pb, 36); /* display matrix */
 
-    get_be32(pb); /* preview time */
-    get_be32(pb); /* preview duration */
-    get_be32(pb); /* poster time */
-    get_be32(pb); /* selection time */
-    get_be32(pb); /* selection duration */
-    get_be32(pb); /* current time */
-    get_be32(pb); /* next track ID */
+    avio_rb32(pb); /* preview time */
+    avio_rb32(pb); /* preview duration */
+    avio_rb32(pb); /* poster time */
+    avio_rb32(pb); /* selection time */
+    avio_rb32(pb); /* selection duration */
+    avio_rb32(pb); /* current time */
+    avio_rb32(pb); /* next track ID */
 
     return 0;
 }
 
-static int mov_read_smi(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
+static int mov_read_smi(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 {
     AVStream *st;
 
@@ -728,12 +701,12 @@ static int mov_read_smi(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
         return AVERROR(ENOMEM);
     st->codec->extradata_size = 0x5a + atom.size;
     memcpy(st->codec->extradata, "SVQ3", 4); // fake
-    get_buffer(pb, st->codec->extradata + 0x5a, atom.size);
-    dprintf(c->fc, "Reading SMI %"PRId64"  %s\n", atom.size, st->codec->extradata + 0x5a);
+    avio_read(pb, st->codec->extradata + 0x5a, atom.size);
+    av_dlog(c->fc, "Reading SMI %"PRId64"  %s\n", atom.size, st->codec->extradata + 0x5a);
     return 0;
 }
 
-static int mov_read_enda(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
+static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 {
     AVStream *st;
     int little_endian;
@@ -742,8 +715,8 @@ static int mov_read_enda(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
         return 0;
     st = c->fc->streams[c->fc->nb_streams-1];
 
-    little_endian = get_be16(pb);
-    dprintf(c->fc, "enda %d\n", little_endian);
+    little_endian = avio_rb16(pb);
+    av_dlog(c->fc, "enda %d\n", little_endian);
     if (little_endian == 1) {
         switch (st->codec->codec_id) {
         case CODEC_ID_PCM_S24BE:
@@ -766,7 +739,7 @@ static int mov_read_enda(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 }
 
 /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
-static int mov_read_extradata(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
+static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 {
     AVStream *st;
     uint64_t size;
@@ -786,11 +759,11 @@ static int mov_read_extradata(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
     AV_WB32(       buf    , atom.size + 8);
     AV_WL32(       buf + 4, atom.type);
-    get_buffer(pb, buf + 8, atom.size);
+    avio_read(pb, buf + 8, atom.size);
     return 0;
 }
 
-static int mov_read_wave(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
+static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 {
     AVStream *st;
 
@@ -801,19 +774,19 @@ static int mov_read_wave(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     if((uint64_t)atom.size > (1<<30))
         return -1;
 
-    if (st->codec->codec_id == CODEC_ID_QDM2) {
-        // pass all frma atom to codec, needed at least for QDM2
+    if (st->codec->codec_id == CODEC_ID_QDM2 || st->codec->codec_id == CODEC_ID_QDMC) {
+        // pass all frma atom to codec, needed at least for QDMC and QDM2
         av_free(st->codec->extradata);
         st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
         if (!st->codec->extradata)
             return AVERROR(ENOMEM);
         st->codec->extradata_size = atom.size;
-        get_buffer(pb, st->codec->extradata, atom.size);
+        avio_read(pb, st->codec->extradata, atom.size);
     } else if (atom.size > 8) { /* to read frma, esds atoms */
         if (mov_read_default(c, pb, atom) < 0)
             return -1;
     } else
-        url_fskip(pb, atom.size);
+        avio_skip(pb, atom.size);
     return 0;
 }
 
@@ -821,7 +794,7 @@ static int mov_read_wave(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  * This function reads atom content and puts data in extradata without tag
  * nor size unlike mov_read_extradata.
  */
-static int mov_read_glbl(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
+static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 {
     AVStream *st;
 
@@ -837,7 +810,7 @@ static int mov_read_glbl(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     if (!st->codec->extradata)
         return AVERROR(ENOMEM);
     st->codec->extradata_size = atom.size;
-    get_buffer(pb, st->codec->extradata, atom.size);
+    avio_read(pb, st->codec->extradata, atom.size);
     return 0;
 }
 
@@ -846,7 +819,7 @@ static int mov_read_glbl(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  * but can have extradata appended at the end after the 40 bytes belonging
  * to the struct.
  */
-static int mov_read_strf(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
+static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 {
     AVStream *st;
 
@@ -864,12 +837,12 @@ static int mov_read_strf(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     if (!st->codec->extradata)
         return AVERROR(ENOMEM);
     st->codec->extradata_size = atom.size - 40;
-    url_fskip(pb, 40);
-    get_buffer(pb, st->codec->extradata, atom.size - 40);
+    avio_skip(pb, 40);
+    avio_read(pb, st->codec->extradata, atom.size - 40);
     return 0;
 }
 
-static int mov_read_stco(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
+static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 {
     AVStream *st;
     MOVStreamContext *sc;
@@ -880,10 +853,10 @@ static int mov_read_stco(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     st = c->fc->streams[c->fc->nb_streams-1];
     sc = st->priv_data;
 
-    get_byte(pb); /* version */
-    get_be24(pb); /* flags */
+    avio_r8(pb); /* version */
+    avio_rb24(pb); /* flags */
 
-    entries = get_be32(pb);
+    entries = avio_rb32(pb);
 
     if(entries >= UINT_MAX/sizeof(int64_t))
         return -1;
@@ -895,10 +868,10 @@ static int mov_read_stco(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 
     if      (atom.type == MKTAG('s','t','c','o'))
         for(i=0; i<entries; i++)
-            sc->chunk_offsets[i] = get_be32(pb);
+            sc->chunk_offsets[i] = avio_rb32(pb);
     else if (atom.type == MKTAG('c','o','6','4'))
         for(i=0; i<entries; i++)
-            sc->chunk_offsets[i] = get_be64(pb);
+            sc->chunk_offsets[i] = avio_rb64(pb);
     else
         return -1;
 
@@ -940,35 +913,30 @@ enum CodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
     return CODEC_ID_NONE;
 }
 
-static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
+int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
 {
     AVStream *st;
     MOVStreamContext *sc;
-    int j, entries, pseudo_stream_id;
+    int j, pseudo_stream_id;
 
     if (c->fc->nb_streams < 1)
         return 0;
     st = c->fc->streams[c->fc->nb_streams-1];
     sc = st->priv_data;
 
-    get_byte(pb); /* version */
-    get_be24(pb); /* flags */
-
-    entries = get_be32(pb);
-
     for(pseudo_stream_id=0; pseudo_stream_id<entries; pseudo_stream_id++) {
         //Parsing Sample description table
         enum CodecID id;
         int dref_id = 1;
-        MOVAtom a = { 0 };
-        int64_t start_pos = url_ftell(pb);
-        int size = get_be32(pb); /* size */
-        uint32_t format = get_le32(pb); /* data format */
+        MOVAtom a = { AV_RL32("stsd") };
+        int64_t start_pos = avio_tell(pb);
+        int size = avio_rb32(pb); /* size */
+        uint32_t format = avio_rl32(pb); /* data format */
 
         if (size >= 16) {
-            get_be32(pb); /* reserved */
-            get_be16(pb); /* reserved */
-            dref_id = get_be16(pb);
+            avio_rb32(pb); /* reserved */
+            avio_rb16(pb); /* reserved */
+            dref_id = avio_rb16(pb);
         }
 
         if (st->codec->codec_tag &&
@@ -979,17 +947,21 @@ static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
             /* Multiple fourcc, we skip JPEG. This is not correct, we should
              * export it as a separate AVStream but this needs a few changes
              * in the MOV demuxer, patch welcome. */
+        multiple_stsd:
             av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
-            url_fskip(pb, size - (url_ftell(pb) - start_pos));
+            avio_skip(pb, size - (avio_tell(pb) - start_pos));
             continue;
         }
+        /* we cannot demux concatenated h264 streams because of different extradata */
+        if (st->codec->codec_tag && st->codec->codec_tag == AV_RL32("avc1"))
+            goto multiple_stsd;
         sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
         sc->dref_id= dref_id;
 
         st->codec->codec_tag = format;
         id = ff_codec_get_id(codec_movaudio_tags, format);
         if (id<=0 && ((format&0xFFFF) == 'm'+('s'<<8) || (format&0xFFFF) == 'T'+('S'<<8)))
-            id = ff_codec_get_id(ff_codec_wav_tags, bswap_32(format)&0xFFFF);
+            id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format)&0xFFFF);
 
         if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
             st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
@@ -1007,7 +979,7 @@ static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
             }
         }
 
-        dprintf(c->fc, "size=%d 4CC= %c%c%c%c codec_type=%d\n", size,
+        av_dlog(c->fc, "size=%d 4CC= %c%c%c%c codec_type=%d\n", size,
                 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
                 (format >> 24) & 0xff, st->codec->codec_type);
 
@@ -1016,33 +988,33 @@ static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
             int color_greyscale;
 
             st->codec->codec_id = id;
-            get_be16(pb); /* version */
-            get_be16(pb); /* revision level */
-            get_be32(pb); /* vendor */
-            get_be32(pb); /* temporal quality */
-            get_be32(pb); /* spatial quality */
+            avio_rb16(pb); /* version */
+            avio_rb16(pb); /* revision level */
+            avio_rb32(pb); /* vendor */
+            avio_rb32(pb); /* temporal quality */
+            avio_rb32(pb); /* spatial quality */
 
-            st->codec->width = get_be16(pb); /* width */
-            st->codec->height = get_be16(pb); /* height */
+            st->codec->width = avio_rb16(pb); /* width */
+            st->codec->height = avio_rb16(pb); /* height */
 
-            get_be32(pb); /* horiz resolution */
-            get_be32(pb); /* vert resolution */
-            get_be32(pb); /* data size, always 0 */
-            get_be16(pb); /* frames per samples */
+            avio_rb32(pb); /* horiz resolution */
+            avio_rb32(pb); /* vert resolution */
+            avio_rb32(pb); /* data size, always 0 */
+            avio_rb16(pb); /* frames per samples */
 
-            len = get_byte(pb); /* codec name, pascal string */
+            len = avio_r8(pb); /* codec name, pascal string */
             if (len > 31)
                 len = 31;
             mov_read_mac_string(c, pb, len, st->codec->codec_name, 32);
             if (len < 31)
-                url_fskip(pb, 31 - len);
+                avio_skip(pb, 31 - len);
             /* codec_tag YV12 triggers an UV swap in rawdec.c */
             if (!memcmp(st->codec->codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25))
                 st->codec->codec_tag=MKTAG('I', '4', '2', '0');
 
-            st->codec->bits_per_coded_sample = get_be16(pb); /* depth */
-            st->codec->color_table_id = get_be16(pb); /* colortable id */
-            dprintf(c->fc, "depth %d, ctab id %d\n",
+            st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
+            st->codec->color_table_id = avio_rb16(pb); /* colortable id */
+            av_dlog(c->fc, "depth %d, ctab id %d\n",
                    st->codec->bits_per_coded_sample, st->codec->color_table_id);
             /* figure out the palette situation */
             color_depth = st->codec->bits_per_coded_sample & 0x1F;
@@ -1055,7 +1027,6 @@ static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
                 unsigned int color_start, color_count, color_end;
                 unsigned char r, g, b;
 
-                st->codec->palctrl = av_malloc(sizeof(*st->codec->palctrl));
                 if (color_greyscale) {
                     int color_index, color_dec;
                     /* compute the greyscale palette */
@@ -1065,7 +1036,7 @@ static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
                     color_dec = 256 / (color_count - 1);
                     for (j = 0; j < color_count; j++) {
                         r = g = b = color_index;
-                        st->codec->palctrl->palette[j] =
+                        sc->palette[j] =
                             (r << 16) | (g << 8) | (b);
                         color_index -= color_dec;
                         if (color_index < 0)
@@ -1086,69 +1057,69 @@ static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
                         r = color_table[j * 3 + 0];
                         g = color_table[j * 3 + 1];
                         b = color_table[j * 3 + 2];
-                        st->codec->palctrl->palette[j] =
+                        sc->palette[j] =
                             (r << 16) | (g << 8) | (b);
                     }
                 } else {
                     /* load the palette from the file */
-                    color_start = get_be32(pb);
-                    color_count = get_be16(pb);
-                    color_end = get_be16(pb);
+                    color_start = avio_rb32(pb);
+                    color_count = avio_rb16(pb);
+                    color_end = avio_rb16(pb);
                     if ((color_start <= 255) &&
                         (color_end <= 255)) {
                         for (j = color_start; j <= color_end; j++) {
                             /* each R, G, or B component is 16 bits;
                              * only use the top 8 bits; skip alpha bytes
                              * up front */
-                            get_byte(pb);
-                            get_byte(pb);
-                            r = get_byte(pb);
-                            get_byte(pb);
-                            g = get_byte(pb);
-                            get_byte(pb);
-                            b = get_byte(pb);
-                            get_byte(pb);
-                            st->codec->palctrl->palette[j] =
+                            avio_r8(pb);
+                            avio_r8(pb);
+                            r = avio_r8(pb);
+                            avio_r8(pb);
+                            g = avio_r8(pb);
+                            avio_r8(pb);
+                            b = avio_r8(pb);
+                            avio_r8(pb);
+                            sc->palette[j] =
                                 (r << 16) | (g << 8) | (b);
                         }
                     }
                 }
-                st->codec->palctrl->palette_changed = 1;
+                sc->has_palette = 1;
             }
         } else if(st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
             int bits_per_sample, flags;
-            uint16_t version = get_be16(pb);
+            uint16_t version = avio_rb16(pb);
 
             st->codec->codec_id = id;
-            get_be16(pb); /* revision level */
-            get_be32(pb); /* vendor */
+            avio_rb16(pb); /* revision level */
+            avio_rb32(pb); /* vendor */
 
-            st->codec->channels = get_be16(pb);             /* channel count */
-            dprintf(c->fc, "audio channels %d\n", st->codec->channels);
-            st->codec->bits_per_coded_sample = get_be16(pb);      /* sample size */
+            st->codec->channels = avio_rb16(pb);             /* channel count */
+            av_dlog(c->fc, "audio channels %d\n", st->codec->channels);
+            st->codec->bits_per_coded_sample = avio_rb16(pb);      /* sample size */
 
-            sc->audio_cid = get_be16(pb);
-            get_be16(pb); /* packet size = 0 */
+            sc->audio_cid = avio_rb16(pb);
+            avio_rb16(pb); /* packet size = 0 */
 
-            st->codec->sample_rate = ((get_be32(pb) >> 16));
+            st->codec->sample_rate = ((avio_rb32(pb) >> 16));
 
             //Read QT version 1 fields. In version 0 these do not exist.
-            dprintf(c->fc, "version =%d, isom =%d\n",version,c->isom);
+            av_dlog(c->fc, "version =%d, isom =%d\n",version,c->isom);
             if(!c->isom) {
                 if(version==1) {
-                    sc->samples_per_frame = get_be32(pb);
-                    get_be32(pb); /* bytes per packet */
-                    sc->bytes_per_frame = get_be32(pb);
-                    get_be32(pb); /* bytes per sample */
+                    sc->samples_per_frame = avio_rb32(pb);
+                    avio_rb32(pb); /* bytes per packet */
+                    sc->bytes_per_frame = avio_rb32(pb);
+                    avio_rb32(pb); /* bytes per sample */
                 } else if(version==2) {
-                    get_be32(pb); /* sizeof struct only */
-                    st->codec->sample_rate = av_int2dbl(get_be64(pb)); /* float 64 */
-                    st->codec->channels = get_be32(pb);
-                    get_be32(pb); /* always 0x7F000000 */
-                    st->codec->bits_per_coded_sample = get_be32(pb); /* bits per channel if sound is uncompressed */
-                    flags = get_be32(pb); /* lpcm format specific flag */
-                    sc->bytes_per_frame = get_be32(pb); /* bytes per audio packet if constant */
-                    sc->samples_per_frame = get_be32(pb); /* lpcm frames per audio packet if constant */
+                    avio_rb32(pb); /* sizeof struct only */
+                    st->codec->sample_rate = av_int2dbl(avio_rb64(pb)); /* float 64 */
+                    st->codec->channels = avio_rb32(pb);
+                    avio_rb32(pb); /* always 0x7F000000 */
+                    st->codec->bits_per_coded_sample = avio_rb32(pb); /* bits per channel if sound is uncompressed */
+                    flags = avio_rb32(pb); /* lpcm format specific flag */
+                    sc->bytes_per_frame = avio_rb32(pb); /* bytes per audio packet if constant */
+                    sc->samples_per_frame = avio_rb32(pb); /* lpcm frames per audio packet if constant */
                     if (format == MKTAG('l','p','c','m'))
                         st->codec->codec_id = ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample, flags);
                 }
@@ -1198,7 +1169,7 @@ static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
         } else if(st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
             // ttxt stsd contains display flags, justification, background
             // color, fonts, and default styles, so fake an atom to read it
-            MOVAtom fake_atom = { .size = size - (url_ftell(pb) - start_pos) };
+            MOVAtom fake_atom = { .size = size - (avio_tell(pb) - start_pos) };
             if (format != AV_RL32("mp4s")) // mp4s contains a regular esds atom
                 mov_read_glbl(c, pb, fake_atom);
             st->codec->codec_id= id;
@@ -1206,15 +1177,15 @@ static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
             st->codec->height = sc->height;
         } else {
             /* other codec type, just skip (rtp, mp4s, tmcd ...) */
-            url_fskip(pb, size - (url_ftell(pb) - start_pos));
+            avio_skip(pb, size - (avio_tell(pb) - start_pos));
         }
         /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
-        a.size = size - (url_ftell(pb) - start_pos);
+        a.size = size - (avio_tell(pb) - start_pos);
         if (a.size > 8) {
             if (mov_read_default(c, pb, a) < 0)
                 return -1;
         } else if (a.size > 0)
-            url_fskip(pb, a.size);
+            avio_skip(pb, a.size);
     }
 
     if(st->codec->codec_type==AVMEDIA_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1)
@@ -1260,12 +1231,14 @@ static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     case CODEC_ID_GSM:
     case CODEC_ID_ADPCM_MS:
     case CODEC_ID_ADPCM_IMA_WAV:
+        st->codec->frame_size = sc->samples_per_frame;
         st->codec->block_align = sc->bytes_per_frame;
         break;
     case CODEC_ID_ALAC:
         if (st->codec->extradata_size == 36) {
             st->codec->frame_size = AV_RB32(st->codec->extradata+12);
             st->codec->channels   = AV_RB8 (st->codec->extradata+21);
+            st->codec->sample_rate = AV_RB32(st->codec->extradata+32);
         }
         break;
     default:
@@ -1275,7 +1248,18 @@ static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     return 0;
 }
 
-static int mov_read_stsc(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
+static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
+{
+    int entries;
+
+    avio_r8(pb); /* version */
+    avio_rb24(pb); /* flags */
+    entries = avio_rb32(pb);
+
+    return ff_mov_read_stsd_entries(c, pb, entries);
+}
+
+static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 {
     AVStream *st;
     MOVStreamContext *sc;
@@ -1286,12 +1270,12 @@ static int mov_read_stsc(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     st = c->fc->streams[c->fc->nb_streams-1];
     sc = st->priv_data;
 
-    get_byte(pb); /* version */
-    get_be24(pb); /* flags */
+    avio_r8(pb); /* version */
+    avio_rb24(pb); /* flags */
 
-    entries = get_be32(pb);
+    entries = avio_rb32(pb);
 
-    dprintf(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
+    av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
 
     if(entries >= UINT_MAX / sizeof(*sc->stsc_data))
         return -1;
@@ -1301,14 +1285,14 @@ static int mov_read_stsc(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     sc->stsc_count = entries;
 
     for(i=0; i<entries; i++) {
-        sc->stsc_data[i].first = get_be32(pb);
-        sc->stsc_data[i].count = get_be32(pb);
-        sc->stsc_data[i].id = get_be32(pb);
+        sc->stsc_data[i].first = avio_rb32(pb);
+        sc->stsc_data[i].count = avio_rb32(pb);
+        sc->stsc_data[i].id = avio_rb32(pb);
     }
     return 0;
 }
 
-static int mov_read_stps(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
+static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 {
     AVStream *st;
     MOVStreamContext *sc;
@@ -1319,9 +1303,9 @@ static int mov_read_stps(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     st = c->fc->streams[c->fc->nb_streams-1];
     sc = st->priv_data;
 
-    get_be32(pb); // version + flags
+    avio_rb32(pb); // version + flags
 
-    entries = get_be32(pb);
+    entries = avio_rb32(pb);
     if (entries >= UINT_MAX / sizeof(*sc->stps_data))
         return -1;
     sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
@@ -1330,14 +1314,14 @@ static int mov_read_stps(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     sc->stps_count = entries;
 
     for (i = 0; i < entries; i++) {
-        sc->stps_data[i] = get_be32(pb);
-        //dprintf(c->fc, "stps %d\n", sc->stps_data[i]);
+        sc->stps_data[i] = avio_rb32(pb);
+        //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
     }
 
     return 0;
 }
 
-static int mov_read_stss(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
+static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 {
     AVStream *st;
     MOVStreamContext *sc;
@@ -1348,12 +1332,12 @@ static int mov_read_stss(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     st = c->fc->streams[c->fc->nb_streams-1];
     sc = st->priv_data;
 
-    get_byte(pb); /* version */
-    get_be24(pb); /* flags */
+    avio_r8(pb); /* version */
+    avio_rb24(pb); /* flags */
 
-    entries = get_be32(pb);
+    entries = avio_rb32(pb);
 
-    dprintf(c->fc, "keyframe_count = %d\n", entries);
+    av_dlog(c->fc, "keyframe_count = %d\n", entries);
 
     if(entries >= UINT_MAX / sizeof(int))
         return -1;
@@ -1363,13 +1347,13 @@ static int mov_read_stss(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     sc->keyframe_count = entries;
 
     for(i=0; i<entries; i++) {
-        sc->keyframes[i] = get_be32(pb);
-        //dprintf(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
+        sc->keyframes[i] = avio_rb32(pb);
+        //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
     }
     return 0;
 }
 
-static int mov_read_stsz(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
+static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 {
     AVStream *st;
     MOVStreamContext *sc;
@@ -1382,22 +1366,22 @@ static int mov_read_stsz(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     st = c->fc->streams[c->fc->nb_streams-1];
     sc = st->priv_data;
 
-    get_byte(pb); /* version */
-    get_be24(pb); /* flags */
+    avio_r8(pb); /* version */
+    avio_rb24(pb); /* flags */
 
     if (atom.type == MKTAG('s','t','s','z')) {
-        sample_size = get_be32(pb);
+        sample_size = avio_rb32(pb);
         if (!sc->sample_size) /* do not overwrite value computed in stsd */
             sc->sample_size = sample_size;
         field_size = 32;
     } else {
         sample_size = 0;
-        get_be24(pb); /* reserved */
-        field_size = get_byte(pb);
+        avio_rb24(pb); /* reserved */
+        field_size = avio_r8(pb);
     }
-    entries = get_be32(pb);
+    entries = avio_rb32(pb);
 
-    dprintf(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
+    av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
 
     sc->sample_count = entries;
     if (sample_size)
@@ -1422,7 +1406,7 @@ static int mov_read_stsz(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
         return AVERROR(ENOMEM);
     }
 
-    if (get_buffer(pb, buf, num_bytes) < num_bytes) {
+    if (avio_read(pb, buf, num_bytes) < num_bytes) {
         av_freep(&sc->sample_sizes);
         av_free(buf);
         return -1;
@@ -1437,7 +1421,7 @@ static int mov_read_stsz(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     return 0;
 }
 
-static int mov_read_stts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
+static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 {
     AVStream *st;
     MOVStreamContext *sc;
@@ -1450,11 +1434,11 @@ static int mov_read_stts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     st = c->fc->streams[c->fc->nb_streams-1];
     sc = st->priv_data;
 
-    get_byte(pb); /* version */
-    get_be24(pb); /* flags */
-    entries = get_be32(pb);
+    avio_r8(pb); /* version */
+    avio_rb24(pb); /* flags */
+    entries = avio_rb32(pb);
 
-    dprintf(c->fc, "track[%i].stts.entries = %i\n", c->fc->nb_streams-1, entries);
+    av_dlog(c->fc, "track[%i].stts.entries = %i\n", c->fc->nb_streams-1, entries);
 
     if(entries >= UINT_MAX / sizeof(*sc->stts_data))
         return -1;
@@ -1467,12 +1451,12 @@ static int mov_read_stts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
         int sample_duration;
         int sample_count;
 
-        sample_count=get_be32(pb);
-        sample_duration = get_be32(pb);
+        sample_count=avio_rb32(pb);
+        sample_duration = avio_rb32(pb);
         sc->stts_data[i].count= sample_count;
         sc->stts_data[i].duration= sample_duration;
 
-        dprintf(c->fc, "sample_count=%d, sample_duration=%d\n",sample_count,sample_duration);
+        av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",sample_count,sample_duration);
 
         duration+=(int64_t)sample_duration*sample_count;
         total_sample_count+=sample_count;
@@ -1484,7 +1468,7 @@ static int mov_read_stts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     return 0;
 }
 
-static int mov_read_ctts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
+static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 {
     AVStream *st;
     MOVStreamContext *sc;
@@ -1495,11 +1479,11 @@ static int mov_read_ctts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     st = c->fc->streams[c->fc->nb_streams-1];
     sc = st->priv_data;
 
-    get_byte(pb); /* version */
-    get_be24(pb); /* flags */
-    entries = get_be32(pb);
+    avio_r8(pb); /* version */
+    avio_rb24(pb); /* flags */
+    entries = avio_rb32(pb);
 
-    dprintf(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
+    av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
 
     if(entries >= UINT_MAX / sizeof(*sc->ctts_data))
         return -1;
@@ -1509,8 +1493,8 @@ static int mov_read_ctts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     sc->ctts_count = entries;
 
     for(i=0; i<entries; i++) {
-        int count    =get_be32(pb);
-        int duration =get_be32(pb);
+        int count    =avio_rb32(pb);
+        int duration =avio_rb32(pb);
 
         sc->ctts_data[i].count   = count;
         sc->ctts_data[i].duration= duration;
@@ -1518,7 +1502,7 @@ static int mov_read_ctts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
             sc->dts_shift = FFMAX(sc->dts_shift, -duration);
     }
 
-    dprintf(c->fc, "dts shift %d\n", sc->dts_shift);
+    av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
 
     return 0;
 }
@@ -1536,10 +1520,11 @@ static void mov_build_index(MOVContext *mov, AVStream *st)
     uint64_t stream_size = 0;
 
     /* adjust first dts according to edit list */
-    if (sc->time_offset) {
+    if (sc->time_offset && mov->time_scale > 0) {
         int rescaled = sc->time_offset < 0 ? av_rescale(sc->time_offset, sc->time_scale, mov->time_scale) : sc->time_offset;
         current_dts = -rescaled;
-        if (sc->ctts_data && sc->ctts_data[0].duration / sc->stts_data[0].duration > 16) {
+        if (sc->ctts_data && sc->stts_data &&
+            sc->ctts_data[0].duration / sc->stts_data[0].duration > 16) {
             /* more than 16 frames delay, dts are likely wrong
                this happens with files created by iMovie */
             sc->wrong_dts = 1;
@@ -1567,7 +1552,7 @@ static void mov_build_index(MOVContext *mov, AVStream *st)
 
         for (i = 0; i < sc->chunk_count; i++) {
             current_offset = sc->chunk_offsets[i];
-            if (stsc_index + 1 < sc->stsc_count &&
+            while (stsc_index + 1 < sc->stsc_count &&
                 i + 1 == sc->stsc_data[stsc_index + 1].first)
                 stsc_index++;
             for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
@@ -1597,7 +1582,7 @@ static void mov_build_index(MOVContext *mov, AVStream *st)
                     e->size = sample_size;
                     e->min_distance = distance;
                     e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
-                    dprintf(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
+                    av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
                             "size %d, distance %d, keyframe %d\n", st->index, current_sample,
                             current_offset, current_dts, sample_size, distance, keyframe);
                 }
@@ -1645,7 +1630,7 @@ static void mov_build_index(MOVContext *mov, AVStream *st)
             total += chunk_count * count;
         }
 
-        dprintf(mov->fc, "chunk count %d\n", total);
+        av_dlog(mov->fc, "chunk count %d\n", total);
         if (total >= UINT_MAX / sizeof(*st->index_entries))
             return;
         st->index_entries = av_malloc(total*sizeof(*st->index_entries));
@@ -1689,7 +1674,7 @@ static void mov_build_index(MOVContext *mov, AVStream *st)
                 e->size = size;
                 e->min_distance = 0;
                 e->flags = AVINDEX_KEYFRAME;
-                dprintf(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
+                av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
                         "size %d, duration %d\n", st->index, i, current_offset, current_dts,
                         size, samples);
 
@@ -1701,7 +1686,7 @@ static void mov_build_index(MOVContext *mov, AVStream *st)
     }
 }
 
-static int mov_open_dref(ByteIOContext **pb, char *src, MOVDref *ref)
+static int mov_open_dref(AVIOContext **pb, char *src, MOVDref *ref)
 {
     /* try relative path, we do not try the absolute because it can leak information about our
        system to an attacker */
@@ -1736,15 +1721,15 @@ static int mov_open_dref(ByteIOContext **pb, char *src, MOVDref *ref)
 
             av_strlcat(filename, ref->path + l + 1, 1024);
 
-            if (!url_fopen(pb, filename, URL_RDONLY))
+            if (!avio_open(pb, filename, AVIO_RDONLY))
                 return 0;
         }
     }
 
     return AVERROR(ENOENT);
-};
+}
 
-static int mov_read_trak(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
+static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 {
     AVStream *st;
     MOVStreamContext *sc;
@@ -1770,10 +1755,10 @@ static int mov_read_trak(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
         return 0;
     }
 
-    if (!sc->time_scale) {
+    if (sc->time_scale <= 0) {
         av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
         sc->time_scale = c->time_scale;
-        if (!sc->time_scale)
+        if (sc->time_scale <= 0)
             sc->time_scale = 1;
     }
 
@@ -1783,7 +1768,7 @@ static int mov_read_trak(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
         !st->codec->frame_size && sc->stts_count == 1) {
         st->codec->frame_size = av_rescale(sc->stts_data[0].duration,
                                            st->codec->sample_rate, sc->time_scale);
-        dprintf(c->fc, "frame size %d\n", st->codec->frame_size);
+        av_dlog(c->fc, "frame size %d\n", st->codec->frame_size);
     }
 
     mov_build_index(c, st);
@@ -1800,17 +1785,18 @@ static int mov_read_trak(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
         sc->pb = c->fc->pb;
 
     if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
-        if (st->codec->width != sc->width || st->codec->height != sc->height) {
-            AVRational r = av_d2q(((double)st->codec->height * sc->width) /
-                                  ((double)st->codec->width * sc->height), INT_MAX);
-            if (st->sample_aspect_ratio.num)
-                st->sample_aspect_ratio = av_mul_q(st->sample_aspect_ratio, r);
-            else
-                st->sample_aspect_ratio = r;
+        if (!st->sample_aspect_ratio.num &&
+            (st->codec->width != sc->width || st->codec->height != sc->height)) {
+            st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
+                                             ((double)st->codec->width * sc->height), INT_MAX);
         }
 
         av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
                   sc->time_scale*st->nb_frames, st->duration, INT_MAX);
+
+        if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
+            av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
+                      sc->time_scale, sc->stts_data[0].duration, INT_MAX);
     }
 
     switch (st->codec->codec_id) {
@@ -1842,7 +1828,7 @@ static int mov_read_trak(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     return 0;
 }
 
-static int mov_read_ilst(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
+static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 {
     int ret;
     c->itunes_metadata = 1;
@@ -1851,13 +1837,13 @@ static int mov_read_ilst(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     return ret;
 }
 
-static int mov_read_meta(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
+static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 {
     while (atom.size > 8) {
-        uint32_t tag = get_le32(pb);
+        uint32_t tag = avio_rl32(pb);
         atom.size -= 4;
         if (tag == MKTAG('h','d','l','r')) {
-            url_fseek(pb, -8, SEEK_CUR);
+            avio_seek(pb, -8, SEEK_CUR);
             atom.size += 8;
             return mov_read_default(c, pb, atom);
         }
@@ -1865,7 +1851,7 @@ static int mov_read_meta(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     return 0;
 }
 
-static int mov_read_tkhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
+static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 {
     int i;
     int width;
@@ -1881,8 +1867,8 @@ static int mov_read_tkhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     st = c->fc->streams[c->fc->nb_streams-1];
     sc = st->priv_data;
 
-    version = get_byte(pb);
-    get_be24(pb); /* flags */
+    version = avio_r8(pb);
+    avio_rb24(pb); /* flags */
     /*
     MOV_TRACK_ENABLED 0x0001
     MOV_TRACK_IN_MOVIE 0x0002
@@ -1891,36 +1877,36 @@ static int mov_read_tkhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     */
 
     if (version == 1) {
-        get_be64(pb);
-        get_be64(pb);
+        avio_rb64(pb);
+        avio_rb64(pb);
     } else {
-        get_be32(pb); /* creation time */
-        get_be32(pb); /* modification time */
+        avio_rb32(pb); /* creation time */
+        avio_rb32(pb); /* modification time */
     }
-    st->id = (int)get_be32(pb); /* track id (NOT 0 !)*/
-    get_be32(pb); /* reserved */
+    st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
+    avio_rb32(pb); /* reserved */
 
     /* highlevel (considering edits) duration in movie timebase */
-    (version == 1) ? get_be64(pb) : get_be32(pb);
-    get_be32(pb); /* reserved */
-    get_be32(pb); /* reserved */
+    (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
+    avio_rb32(pb); /* reserved */
+    avio_rb32(pb); /* reserved */
 
-    get_be16(pb); /* layer */
-    get_be16(pb); /* alternate group */
-    get_be16(pb); /* volume */
-    get_be16(pb); /* reserved */
+    avio_rb16(pb); /* layer */
+    avio_rb16(pb); /* alternate group */
+    avio_rb16(pb); /* volume */
+    avio_rb16(pb); /* reserved */
 
     //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
     // they're kept in fixed point format through all calculations
     // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
     for (i = 0; i < 3; i++) {
-        display_matrix[i][0] = get_be32(pb);   // 16.16 fixed point
-        display_matrix[i][1] = get_be32(pb);   // 16.16 fixed point
-        get_be32(pb);           // 2.30 fixed point (not used)
+        display_matrix[i][0] = avio_rb32(pb);   // 16.16 fixed point
+        display_matrix[i][1] = avio_rb32(pb);   // 16.16 fixed point
+        avio_rb32(pb);           // 2.30 fixed point (not used)
     }
 
-    width = get_be32(pb);       // 16.16 fixed point track width
-    height = get_be32(pb);      // 16.16 fixed point track height
+    width = avio_rb32(pb);       // 16.16 fixed point track width
+    height = avio_rb32(pb);      // 16.16 fixed point track height
     sc->width = width >> 16;
     sc->height = height >> 16;
 
@@ -1948,16 +1934,16 @@ static int mov_read_tkhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     return 0;
 }
 
-static int mov_read_tfhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
+static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 {
     MOVFragment *frag = &c->fragment;
     MOVTrackExt *trex = NULL;
     int flags, track_id, i;
 
-    get_byte(pb); /* version */
-    flags = get_be24(pb);
+    avio_r8(pb); /* version */
+    flags = avio_rb24(pb);
 
-    track_id = get_be32(pb);
+    track_id = avio_rb32(pb);
     if (!track_id)
         return -1;
     frag->track_id = track_id;
@@ -1971,25 +1957,25 @@ static int mov_read_tfhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
         return -1;
     }
 
-    if (flags & 0x01) frag->base_data_offset = get_be64(pb);
+    if (flags & 0x01) frag->base_data_offset = avio_rb64(pb);
     else              frag->base_data_offset = frag->moof_offset;
-    if (flags & 0x02) frag->stsd_id          = get_be32(pb);
+    if (flags & 0x02) frag->stsd_id          = avio_rb32(pb);
     else              frag->stsd_id          = trex->stsd_id;
 
-    frag->duration = flags & 0x08 ? get_be32(pb) : trex->duration;
-    frag->size     = flags & 0x10 ? get_be32(pb) : trex->size;
-    frag->flags    = flags & 0x20 ? get_be32(pb) : trex->flags;
-    dprintf(c->fc, "frag flags 0x%x\n", frag->flags);
+    frag->duration = flags & 0x08 ? avio_rb32(pb) : trex->duration;
+    frag->size     = flags & 0x10 ? avio_rb32(pb) : trex->size;
+    frag->flags    = flags & 0x20 ? avio_rb32(pb) : trex->flags;
+    av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
     return 0;
 }
 
-static int mov_read_chap(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
+static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 {
-    c->chapter_track = get_be32(pb);
+    c->chapter_track = avio_rb32(pb);
     return 0;
 }
 
-static int mov_read_trex(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
+static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 {
     MOVTrackExt *trex;
 
@@ -2000,17 +1986,17 @@ static int mov_read_trex(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
         return AVERROR(ENOMEM);
     c->trex_data = trex;
     trex = &c->trex_data[c->trex_count++];
-    get_byte(pb); /* version */
-    get_be24(pb); /* flags */
-    trex->track_id = get_be32(pb);
-    trex->stsd_id  = get_be32(pb);
-    trex->duration = get_be32(pb);
-    trex->size     = get_be32(pb);
-    trex->flags    = get_be32(pb);
+    avio_r8(pb); /* version */
+    avio_rb24(pb); /* flags */
+    trex->track_id = avio_rb32(pb);
+    trex->stsd_id  = avio_rb32(pb);
+    trex->duration = avio_rb32(pb);
+    trex->size     = avio_rb32(pb);
+    trex->flags    = avio_rb32(pb);
     return 0;
 }
 
-static int mov_read_trun(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
+static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 {
     MOVFragment *frag = &c->fragment;
     AVStream *st = NULL;
@@ -2034,12 +2020,12 @@ static int mov_read_trun(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     sc = st->priv_data;
     if (sc->pseudo_stream_id+1 != frag->stsd_id)
         return 0;
-    get_byte(pb); /* version */
-    flags = get_be24(pb);
-    entries = get_be32(pb);
-    dprintf(c->fc, "flags 0x%x entries %d\n", flags, entries);
-    if (flags & 0x001) data_offset        = get_be32(pb);
-    if (flags & 0x004) first_sample_flags = get_be32(pb);
+    avio_r8(pb); /* version */
+    flags = avio_rb24(pb);
+    entries = avio_rb32(pb);
+    av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
+    if (flags & 0x001) data_offset        = avio_rb32(pb);
+    if (flags & 0x004) first_sample_flags = avio_rb32(pb);
     if (flags & 0x800) {
         MOVStts *ctts_data;
         if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
@@ -2053,19 +2039,19 @@ static int mov_read_trun(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     dts = st->duration;
     offset = frag->base_data_offset + data_offset;
     distance = 0;
-    dprintf(c->fc, "first sample flags 0x%x\n", first_sample_flags);
+    av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
     for (i = 0; i < entries; i++) {
         unsigned sample_size = frag->size;
         int sample_flags = i ? frag->flags : first_sample_flags;
         unsigned sample_duration = frag->duration;
         int keyframe;
 
-        if (flags & 0x100) sample_duration = get_be32(pb);
-        if (flags & 0x200) sample_size     = get_be32(pb);
-        if (flags & 0x400) sample_flags    = get_be32(pb);
+        if (flags & 0x100) sample_duration = avio_rb32(pb);
+        if (flags & 0x200) sample_size     = avio_rb32(pb);
+        if (flags & 0x400) sample_flags    = avio_rb32(pb);
         if (flags & 0x800) {
             sc->ctts_data[sc->ctts_count].count = 1;
-            sc->ctts_data[sc->ctts_count].duration = get_be32(pb);
+            sc->ctts_data[sc->ctts_count].duration = avio_rb32(pb);
             sc->ctts_count++;
         }
         if ((keyframe = st->codec->codec_type == AVMEDIA_TYPE_AUDIO ||
@@ -2073,7 +2059,7 @@ static int mov_read_trun(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
             distance = 0;
         av_add_index_entry(st, offset, dts, sample_size, distance,
                            keyframe ? AVINDEX_KEYFRAME : 0);
-        dprintf(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
+        av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
                 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
                 offset, dts, sample_size, distance, keyframe);
         distance++;
@@ -2088,46 +2074,46 @@ static int mov_read_trun(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
 /* like the files created with Adobe Premiere 5.0, for samples see */
 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
-static int mov_read_wide(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
+static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 {
     int err;
 
     if (atom.size < 8)
         return 0; /* continue */
-    if (get_be32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
-        url_fskip(pb, atom.size - 4);
+    if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
+        avio_skip(pb, atom.size - 4);
         return 0;
     }
-    atom.type = get_le32(pb);
+    atom.type = avio_rl32(pb);
     atom.size -= 8;
     if (atom.type != MKTAG('m','d','a','t')) {
-        url_fskip(pb, atom.size);
+        avio_skip(pb, atom.size);
         return 0;
     }
     err = mov_read_mdat(c, pb, atom);
     return err;
 }
 
-static int mov_read_cmov(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
+static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 {
 #if CONFIG_ZLIB
-    ByteIOContext ctx;
+    AVIOContext ctx;
     uint8_t *cmov_data;
     uint8_t *moov_data; /* uncompressed data */
     long cmov_len, moov_len;
     int ret = -1;
 
-    get_be32(pb); /* dcom atom */
-    if (get_le32(pb) != MKTAG('d','c','o','m'))
+    avio_rb32(pb); /* dcom atom */
+    if (avio_rl32(pb) != MKTAG('d','c','o','m'))
         return -1;
-    if (get_le32(pb) != MKTAG('z','l','i','b')) {
+    if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
         av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
         return -1;
     }
-    get_be32(pb); /* cmvd atom */
-    if (get_le32(pb) != MKTAG('c','m','v','d'))
+    avio_rb32(pb); /* cmvd atom */
+    if (avio_rl32(pb) != MKTAG('c','m','v','d'))
         return -1;
-    moov_len = get_be32(pb); /* uncompressed size */
+    moov_len = avio_rb32(pb); /* uncompressed size */
     cmov_len = atom.size - 6 * 4;
 
     cmov_data = av_malloc(cmov_len);
@@ -2138,10 +2124,10 @@ static int mov_read_cmov(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
         av_free(cmov_data);
         return AVERROR(ENOMEM);
     }
-    get_buffer(pb, cmov_data, cmov_len);
+    avio_read(pb, cmov_data, cmov_len);
     if(uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
         goto free_and_return;
-    if(init_put_byte(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
+    if(ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
         goto free_and_return;
     atom.type = MKTAG('m','o','o','v');
     atom.size = moov_len;
@@ -2160,7 +2146,7 @@ free_and_return:
 }
 
 /* edit list atom */
-static int mov_read_elst(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
+static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 {
     MOVStreamContext *sc;
     int i, edit_count;
@@ -2169,18 +2155,18 @@ static int mov_read_elst(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
         return 0;
     sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
 
-    get_byte(pb); /* version */
-    get_be24(pb); /* flags */
-    edit_count = get_be32(pb); /* entries */
+    avio_r8(pb); /* version */
+    avio_rb24(pb); /* flags */
+    edit_count = avio_rb32(pb); /* entries */
 
     if((uint64_t)edit_count*12+8 > atom.size)
         return -1;
 
     for(i=0; i<edit_count; i++){
         int time;
-        int duration = get_be32(pb); /* Track duration */
-        time = get_be32(pb); /* Media time */
-        get_be32(pb); /* Media rate */
+        int duration = avio_rb32(pb); /* Track duration */
+        time = avio_rb32(pb); /* Media time */
+        avio_rb32(pb); /* Media rate */
         if (i == 0 && time >= -1) {
             sc->time_offset = time != -1 ? time : -duration;
         }
@@ -2190,7 +2176,7 @@ static int mov_read_elst(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
         av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
                "a/v desync might occur, patch welcome\n");
 
-    dprintf(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
+    av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
     return 0;
 }
 
@@ -2244,6 +2230,7 @@ static const MOVParseTableEntry mov_default_parse_table[] = {
 { MKTAG('u','d','t','a'), mov_read_default },
 { MKTAG('w','a','v','e'), mov_read_wave },
 { MKTAG('e','s','d','s'), mov_read_esds },
+{ MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
 { MKTAG('c','m','o','v'), mov_read_cmov },
 { 0, NULL }
@@ -2301,8 +2288,7 @@ static void mov_read_chapters(AVFormatContext *s)
     AVStream *st = NULL;
     MOVStreamContext *sc;
     int64_t cur_pos;
-    uint8_t *title = NULL;
-    int i, len, i8, i16;
+    int i;
 
     for (i = 0; i < s->nb_streams; i++)
         if (s->streams[i]->id == mov->chapter_track) {
@@ -2316,62 +2302,59 @@ static void mov_read_chapters(AVFormatContext *s)
 
     st->discard = AVDISCARD_ALL;
     sc = st->priv_data;
-    cur_pos = url_ftell(sc->pb);
+    cur_pos = avio_tell(sc->pb);
 
     for (i = 0; i < st->nb_index_entries; i++) {
         AVIndexEntry *sample = &st->index_entries[i];
         int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
+        uint8_t *title;
+        uint16_t ch;
+        int len, title_len;
 
-        if (url_fseek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
+        if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
             av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
             goto finish;
         }
 
-        title = av_malloc(sample->size+2);
-        get_buffer(sc->pb, title, sample->size);
-
         // the first two bytes are the length of the title
-        len = AV_RB16(title);
+        len = avio_rb16(sc->pb);
         if (len > sample->size-2)
             continue;
+        title_len = 2*len + 1;
+        if (!(title = av_mallocz(title_len)))
+            goto finish;
 
         // The samples could theoretically be in any encoding if there's an encd
         // atom following, but in practice are only utf-8 or utf-16, distinguished
         // instead by the presence of a BOM
-        if (AV_RB16(title+2) == 0xfeff) {
-            uint8_t *utf8 = av_malloc(2*len+3);
-
-            i8 = i16 = 0;
-            while (i16 < len) {
-                uint32_t ch;
-                uint8_t tmp;
-                GET_UTF16(ch, i16 < len ? AV_RB16(title + (i16+=2)) : 0, break;)
-                PUT_UTF8(ch, tmp, if (i8 < 2*len) utf8[2+i8++] = tmp;)
-            }
-            utf8[2+i8] = 0;
-            av_freep(&title);
-            title = utf8;
+        ch = avio_rb16(sc->pb);
+        if (ch == 0xfeff)
+            avio_get_str16be(sc->pb, len, title, title_len);
+        else if (ch == 0xfffe)
+            avio_get_str16le(sc->pb, len, title, title_len);
+        else {
+            AV_WB16(title, ch);
+            avio_get_str(sc->pb, len - 2, title + 2, title_len - 2);
         }
 
-        ff_new_chapter(s, i, st->time_base, sample->timestamp, end, title+2);
+        ff_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
         av_freep(&title);
     }
 finish:
-    av_free(title);
-    url_fseek(sc->pb, cur_pos, SEEK_SET);
+    avio_seek(sc->pb, cur_pos, SEEK_SET);
 }
 
 static int mov_read_header(AVFormatContext *s, AVFormatParameters *ap)
 {
     MOVContext *mov = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int err;
-    MOVAtom atom = { 0 };
+    MOVAtom atom = { AV_RL32("root") };
 
     mov->fc = s;
     /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
-    if(!url_is_streamed(pb))
-        atom.size = url_fsize(pb);
+    if(pb->seekable)
+        atom.size = avio_size(pb);
     else
         atom.size = INT64_MAX;
 
@@ -2384,9 +2367,9 @@ static int mov_read_header(AVFormatContext *s, AVFormatParameters *ap)
         av_log(s, AV_LOG_ERROR, "moov atom not found\n");
         return -1;
     }
-    dprintf(mov->fc, "on_parse_exit_offset=%lld\n", url_ftell(pb));
+    av_dlog(mov->fc, "on_parse_exit_offset=%lld\n", avio_tell(pb));
 
-    if (!url_is_streamed(pb) && mov->chapter_track > 0)
+    if (pb->seekable && mov->chapter_track > 0)
         mov_read_chapters(s);
 
     return 0;
@@ -2403,9 +2386,9 @@ static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
         if (msc->pb && msc->current_sample < avst->nb_index_entries) {
             AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
             int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
-            dprintf(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
-            if (!sample || (url_is_streamed(s->pb) && current_sample->pos < sample->pos) ||
-                (!url_is_streamed(s->pb) &&
+            av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
+            if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
+                (s->pb->seekable &&
                  ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
                  ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
                   (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
@@ -2429,11 +2412,11 @@ static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
     sample = mov_find_next_sample(s, &st);
     if (!sample) {
         mov->found_mdat = 0;
-        if (!url_is_streamed(s->pb) ||
-            mov_read_default(mov, s->pb, (MOVAtom){ 0, INT64_MAX }) < 0 ||
-            url_feof(s->pb))
+        if (s->pb->seekable||
+            mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
+            s->pb->eof_reached)
             return AVERROR_EOF;
-        dprintf(s, "read fragments, offset 0x%llx\n", url_ftell(s->pb));
+        av_dlog(s, "read fragments, offset 0x%llx\n", avio_tell(s->pb));
         goto retry;
     }
     sc = st->priv_data;
@@ -2441,7 +2424,7 @@ static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
     sc->current_sample++;
 
     if (st->discard != AVDISCARD_ALL) {
-        if (url_fseek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
+        if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
             av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
                    sc->ffindex, sample->pos);
             return -1;
@@ -2449,6 +2432,17 @@ static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
         ret = av_get_packet(sc->pb, pkt, sample->size);
         if (ret < 0)
             return ret;
+        if (sc->has_palette) {
+            uint8_t *pal;
+
+            pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
+            if (!pal) {
+                av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
+            } else {
+                memcpy(pal, sc->palette, AVPALETTE_SIZE);
+                sc->has_palette = 0;
+            }
+        }
 #if CONFIG_DV_DEMUXER
         if (mov->dv_demux && sc->dv_audio_container) {
             dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size);
@@ -2484,7 +2478,7 @@ static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
         goto retry;
     pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
     pkt->pos = sample->pos;
-    dprintf(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
+    av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
             pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
     return 0;
 }
@@ -2496,11 +2490,13 @@ static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp,
     int i;
 
     sample = av_index_search_timestamp(st, timestamp, flags);
-    dprintf(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
+    av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
+    if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
+        sample = 0;
     if (sample < 0) /* not sure what to do */
         return -1;
     sc->current_sample = sample;
-    dprintf(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
+    av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
     /* adjust ctts index */
     if (sc->ctts_data) {
         time_sample = 0;
@@ -2564,7 +2560,7 @@ static int mov_read_close(AVFormatContext *s)
         }
         av_freep(&sc->drefs);
         if (sc->pb && sc->pb != s->pb)
-            url_fclose(sc->pb);
+            avio_close(sc->pb);
 
         av_freep(&st->codec->palctrl);
     }
@@ -2583,7 +2579,7 @@ static int mov_read_close(AVFormatContext *s)
     return 0;
 }
 
-AVInputFormat mov_demuxer = {
+AVInputFormat ff_mov_demuxer = {
     "mov,mp4,m4a,3gp,3g2,mj2",
     NULL_IF_CONFIG_SMALL("QuickTime/MPEG-4/Motion JPEG 2000 format"),
     sizeof(MOVContext),
diff --git a/libavformat/movenc.c b/libavformat/movenc.c
index 00f6990..0458844 100644
--- a/libavformat/movenc.c
+++ b/libavformat/movenc.c
@@ -4,25 +4,26 @@
  * Copyright (c) 2004 Gildas Bazin <gbazin at videolan dot org>
  * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "movenc.h"
 #include "avformat.h"
+#include "avio_internal.h"
 #include "riff.h"
 #include "avio.h"
 #include "isom.h"
@@ -36,49 +37,49 @@
 #include <assert.h>
 
 //FIXME support 64 bit variant with wide placeholders
-static int64_t updateSize(ByteIOContext *pb, int64_t pos)
+static int64_t updateSize(AVIOContext *pb, int64_t pos)
 {
-    int64_t curpos = url_ftell(pb);
-    url_fseek(pb, pos, SEEK_SET);
-    put_be32(pb, curpos - pos); /* rewrite size */
-    url_fseek(pb, curpos, SEEK_SET);
+    int64_t curpos = avio_tell(pb);
+    avio_seek(pb, pos, SEEK_SET);
+    avio_wb32(pb, curpos - pos); /* rewrite size */
+    avio_seek(pb, curpos, SEEK_SET);
 
     return curpos - pos;
 }
 
 /* Chunk offset atom */
-static int mov_write_stco_tag(ByteIOContext *pb, MOVTrack *track)
+static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track)
 {
     int i;
     int mode64 = 0; //   use 32 bit size variant if possible
-    int64_t pos = url_ftell(pb);
-    put_be32(pb, 0); /* size */
+    int64_t pos = avio_tell(pb);
+    avio_wb32(pb, 0); /* size */
     if (pos > UINT32_MAX) {
         mode64 = 1;
-        put_tag(pb, "co64");
+        ffio_wfourcc(pb, "co64");
     } else
-        put_tag(pb, "stco");
-    put_be32(pb, 0); /* version & flags */
-    put_be32(pb, track->entry); /* entry count */
+        ffio_wfourcc(pb, "stco");
+    avio_wb32(pb, 0); /* version & flags */
+    avio_wb32(pb, track->entry); /* entry count */
     for (i=0; i<track->entry; i++) {
         if(mode64 == 1)
-            put_be64(pb, track->cluster[i].pos);
+            avio_wb64(pb, track->cluster[i].pos);
         else
-            put_be32(pb, track->cluster[i].pos);
+            avio_wb32(pb, track->cluster[i].pos);
     }
     return updateSize(pb, pos);
 }
 
 /* Sample size atom */
-static int mov_write_stsz_tag(ByteIOContext *pb, MOVTrack *track)
+static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track)
 {
     int equalChunks = 1;
     int i, j, entries = 0, tst = -1, oldtst = -1;
 
-    int64_t pos = url_ftell(pb);
-    put_be32(pb, 0); /* size */
-    put_tag(pb, "stsz");
-    put_be32(pb, 0); /* version & flags */
+    int64_t pos = avio_tell(pb);
+    avio_wb32(pb, 0); /* size */
+    ffio_wfourcc(pb, "stsz");
+    avio_wb32(pb, 0); /* version & flags */
 
     for (i=0; i<track->entry; i++) {
         tst = track->cluster[i].size/track->cluster[i].entries;
@@ -90,15 +91,15 @@ static int mov_write_stsz_tag(ByteIOContext *pb, MOVTrack *track)
     }
     if (equalChunks) {
         int sSize = track->cluster[0].size/track->cluster[0].entries;
-        put_be32(pb, sSize); // sample size
-        put_be32(pb, entries); // sample count
+        avio_wb32(pb, sSize); // sample size
+        avio_wb32(pb, entries); // sample count
     }
     else {
-        put_be32(pb, 0); // sample size
-        put_be32(pb, entries); // sample count
+        avio_wb32(pb, 0); // sample size
+        avio_wb32(pb, entries); // sample count
         for (i=0; i<track->entry; i++) {
             for (j=0; j<track->cluster[i].entries; j++) {
-                put_be32(pb, track->cluster[i].size /
+                avio_wb32(pb, track->cluster[i].size /
                          track->cluster[i].entries);
             }
         }
@@ -107,74 +108,74 @@ static int mov_write_stsz_tag(ByteIOContext *pb, MOVTrack *track)
 }
 
 /* Sample to chunk atom */
-static int mov_write_stsc_tag(ByteIOContext *pb, MOVTrack *track)
+static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track)
 {
     int index = 0, oldval = -1, i;
     int64_t entryPos, curpos;
 
-    int64_t pos = url_ftell(pb);
-    put_be32(pb, 0); /* size */
-    put_tag(pb, "stsc");
-    put_be32(pb, 0); // version & flags
-    entryPos = url_ftell(pb);
-    put_be32(pb, track->entry); // entry count
+    int64_t pos = avio_tell(pb);
+    avio_wb32(pb, 0); /* size */
+    ffio_wfourcc(pb, "stsc");
+    avio_wb32(pb, 0); // version & flags
+    entryPos = avio_tell(pb);
+    avio_wb32(pb, track->entry); // entry count
     for (i=0; i<track->entry; i++) {
         if(oldval != track->cluster[i].samplesInChunk)
         {
-            put_be32(pb, i+1); // first chunk
-            put_be32(pb, track->cluster[i].samplesInChunk); // samples per chunk
-            put_be32(pb, 0x1); // sample description index
+            avio_wb32(pb, i+1); // first chunk
+            avio_wb32(pb, track->cluster[i].samplesInChunk); // samples per chunk
+            avio_wb32(pb, 0x1); // sample description index
             oldval = track->cluster[i].samplesInChunk;
             index++;
         }
     }
-    curpos = url_ftell(pb);
-    url_fseek(pb, entryPos, SEEK_SET);
-    put_be32(pb, index); // rewrite size
-    url_fseek(pb, curpos, SEEK_SET);
+    curpos = avio_tell(pb);
+    avio_seek(pb, entryPos, SEEK_SET);
+    avio_wb32(pb, index); // rewrite size
+    avio_seek(pb, curpos, SEEK_SET);
 
     return updateSize(pb, pos);
 }
 
 /* Sync sample atom */
-static int mov_write_stss_tag(ByteIOContext *pb, MOVTrack *track, uint32_t flag)
+static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag)
 {
     int64_t curpos, entryPos;
     int i, index = 0;
-    int64_t pos = url_ftell(pb);
-    put_be32(pb, 0); // size
-    put_tag(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps");
-    put_be32(pb, 0); // version & flags
-    entryPos = url_ftell(pb);
-    put_be32(pb, track->entry); // entry count
+    int64_t pos = avio_tell(pb);
+    avio_wb32(pb, 0); // size
+    ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps");
+    avio_wb32(pb, 0); // version & flags
+    entryPos = avio_tell(pb);
+    avio_wb32(pb, track->entry); // entry count
     for (i=0; i<track->entry; i++) {
         if (track->cluster[i].flags & flag) {
-            put_be32(pb, i+1);
+            avio_wb32(pb, i+1);
             index++;
         }
     }
-    curpos = url_ftell(pb);
-    url_fseek(pb, entryPos, SEEK_SET);
-    put_be32(pb, index); // rewrite size
-    url_fseek(pb, curpos, SEEK_SET);
+    curpos = avio_tell(pb);
+    avio_seek(pb, entryPos, SEEK_SET);
+    avio_wb32(pb, index); // rewrite size
+    avio_seek(pb, curpos, SEEK_SET);
     return updateSize(pb, pos);
 }
 
-static int mov_write_amr_tag(ByteIOContext *pb, MOVTrack *track)
+static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track)
 {
-    put_be32(pb, 0x11); /* size */
-    if (track->mode == MODE_MOV) put_tag(pb, "samr");
-    else                         put_tag(pb, "damr");
-    put_tag(pb, "FFMP");
-    put_byte(pb, 0); /* decoder version */
+    avio_wb32(pb, 0x11); /* size */
+    if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr");
+    else                         ffio_wfourcc(pb, "damr");
+    ffio_wfourcc(pb, "FFMP");
+    avio_w8(pb, 0); /* decoder version */
 
-    put_be16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
-    put_byte(pb, 0x00); /* Mode change period (no restriction) */
-    put_byte(pb, 0x01); /* Frames per sample */
+    avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
+    avio_w8(pb, 0x00); /* Mode change period (no restriction) */
+    avio_w8(pb, 0x01); /* Frames per sample */
     return 0x11;
 }
 
-static int mov_write_ac3_tag(ByteIOContext *pb, MOVTrack *track)
+static int mov_write_ac3_tag(AVIOContext *pb, MOVTrack *track)
 {
     GetBitContext gbc;
     PutBitContext pbc;
@@ -184,8 +185,8 @@ static int mov_write_ac3_tag(ByteIOContext *pb, MOVTrack *track)
     if (track->vosLen < 7)
         return -1;
 
-    put_be32(pb, 11);
-    put_tag(pb, "dac3");
+    avio_wb32(pb, 11);
+    ffio_wfourcc(pb, "dac3");
 
     init_get_bits(&gbc, track->vosData+4, track->vosLen-4);
     fscod      = get_bits(&gbc, 2);
@@ -213,7 +214,7 @@ static int mov_write_ac3_tag(ByteIOContext *pb, MOVTrack *track)
     put_bits(&pbc, 5, 0); // reserved
 
     flush_put_bits(&pbc);
-    put_buffer(pb, buf, sizeof(buf));
+    avio_write(pb, buf, sizeof(buf));
 
     return 11;
 }
@@ -222,17 +223,17 @@ static int mov_write_ac3_tag(ByteIOContext *pb, MOVTrack *track)
  * This function writes extradata "as is".
  * Extradata must be formated like a valid atom (with size and tag)
  */
-static int mov_write_extradata_tag(ByteIOContext *pb, MOVTrack *track)
+static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track)
 {
-    put_buffer(pb, track->enc->extradata, track->enc->extradata_size);
+    avio_write(pb, track->enc->extradata, track->enc->extradata_size);
     return track->enc->extradata_size;
 }
 
-static int mov_write_enda_tag(ByteIOContext *pb)
+static int mov_write_enda_tag(AVIOContext *pb)
 {
-    put_be32(pb, 10);
-    put_tag(pb, "enda");
-    put_be16(pb, 1); /* little endian */
+    avio_wb32(pb, 10);
+    ffio_wfourcc(pb, "enda");
+    avio_wb16(pb, 1); /* little endian */
     return 10;
 }
 
@@ -243,29 +244,29 @@ static unsigned int descrLength(unsigned int len)
     return len + 1 + i;
 }
 
-static void putDescr(ByteIOContext *pb, int tag, unsigned int size)
+static void putDescr(AVIOContext *pb, int tag, unsigned int size)
 {
     int i= descrLength(size) - size - 2;
-    put_byte(pb, tag);
+    avio_w8(pb, tag);
     for(; i>0; i--)
-        put_byte(pb, (size>>(7*i)) | 0x80);
-    put_byte(pb, size & 0x7F);
+        avio_w8(pb, (size>>(7*i)) | 0x80);
+    avio_w8(pb, size & 0x7F);
 }
 
-static int mov_write_esds_tag(ByteIOContext *pb, MOVTrack *track) // Basic
+static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic
 {
-    int64_t pos = url_ftell(pb);
+    int64_t pos = avio_tell(pb);
     int decoderSpecificInfoLen = track->vosLen ? descrLength(track->vosLen):0;
 
-    put_be32(pb, 0); // size
-    put_tag(pb, "esds");
-    put_be32(pb, 0); // Version
+    avio_wb32(pb, 0); // size
+    ffio_wfourcc(pb, "esds");
+    avio_wb32(pb, 0); // Version
 
     // ES descriptor
     putDescr(pb, 0x03, 3 + descrLength(13 + decoderSpecificInfoLen) +
              descrLength(1));
-    put_be16(pb, track->trackID);
-    put_byte(pb, 0x00); // flags (= no flags)
+    avio_wb16(pb, track->trackID);
+    avio_w8(pb, 0x00); // flags (= no flags)
 
     // DecoderConfig descriptor
     putDescr(pb, 0x04, 13 + decoderSpecificInfoLen);
@@ -274,35 +275,35 @@ static int mov_write_esds_tag(ByteIOContext *pb, MOVTrack *track) // Basic
     if ((track->enc->codec_id == CODEC_ID_MP2 ||
          track->enc->codec_id == CODEC_ID_MP3) &&
         track->enc->sample_rate > 24000)
-        put_byte(pb, 0x6B); // 11172-3
+        avio_w8(pb, 0x6B); // 11172-3
     else
-        put_byte(pb, ff_codec_get_tag(ff_mp4_obj_type, track->enc->codec_id));
+        avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->enc->codec_id));
 
     // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
     // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
     if(track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
-        put_byte(pb, 0x15); // flags (= Audiostream)
+        avio_w8(pb, 0x15); // flags (= Audiostream)
     else
-        put_byte(pb, 0x11); // flags (= Visualstream)
+        avio_w8(pb, 0x11); // flags (= Visualstream)
 
-    put_byte(pb,  track->enc->rc_buffer_size>>(3+16));    // Buffersize DB (24 bits)
-    put_be16(pb, (track->enc->rc_buffer_size>>3)&0xFFFF); // Buffersize DB
+    avio_w8(pb,  track->enc->rc_buffer_size>>(3+16));      // Buffersize DB (24 bits)
+    avio_wb16(pb, (track->enc->rc_buffer_size>>3)&0xFFFF); // Buffersize DB
 
-    put_be32(pb, FFMAX(track->enc->bit_rate, track->enc->rc_max_rate)); // maxbitrate (FIXME should be max rate in any 1 sec window)
+    avio_wb32(pb, FFMAX(track->enc->bit_rate, track->enc->rc_max_rate)); // maxbitrate (FIXME should be max rate in any 1 sec window)
     if(track->enc->rc_max_rate != track->enc->rc_min_rate || track->enc->rc_min_rate==0)
-        put_be32(pb, 0); // vbr
+        avio_wb32(pb, 0); // vbr
     else
-        put_be32(pb, track->enc->rc_max_rate); // avg bitrate
+        avio_wb32(pb, track->enc->rc_max_rate); // avg bitrate
 
     if (track->vosLen) {
         // DecoderSpecific info descriptor
         putDescr(pb, 0x05, track->vosLen);
-        put_buffer(pb, track->vosData, track->vosLen);
+        avio_write(pb, track->vosData, track->vosLen);
     }
 
     // SL descriptor
     putDescr(pb, 0x06, 1);
-    put_byte(pb, 0x02);
+    avio_w8(pb, 0x02);
     return updateSize(pb, pos);
 }
 
@@ -314,22 +315,32 @@ static int mov_pcm_le_gt16(enum CodecID codec_id)
            codec_id == CODEC_ID_PCM_F64LE;
 }
 
-static int mov_write_wave_tag(ByteIOContext *pb, MOVTrack *track)
+static int mov_write_ms_tag(AVIOContext *pb, MOVTrack *track)
 {
-    int64_t pos = url_ftell(pb);
+    int64_t pos = avio_tell(pb);
+    avio_wb32(pb, 0);
+    avio_wl32(pb, track->tag); // store it byteswapped
+    track->enc->codec_tag = av_bswap16(track->tag >> 16);
+    ff_put_wav_header(pb, track->enc);
+    return updateSize(pb, pos);
+}
+
+static int mov_write_wave_tag(AVIOContext *pb, MOVTrack *track)
+{
+    int64_t pos = avio_tell(pb);
 
-    put_be32(pb, 0);     /* size */
-    put_tag(pb, "wave");
+    avio_wb32(pb, 0);     /* size */
+    ffio_wfourcc(pb, "wave");
 
-    put_be32(pb, 12);    /* size */
-    put_tag(pb, "frma");
-    put_le32(pb, track->tag);
+    avio_wb32(pb, 12);    /* size */
+    ffio_wfourcc(pb, "frma");
+    avio_wl32(pb, track->tag);
 
     if (track->enc->codec_id == CODEC_ID_AAC) {
         /* useless atom needed by mplayer, ipod, not needed by quicktime */
-        put_be32(pb, 12); /* size */
-        put_tag(pb, "mp4a");
-        put_be32(pb, 0);
+        avio_wb32(pb, 12); /* size */
+        ffio_wfourcc(pb, "mp4a");
+        avio_wb32(pb, 0);
         mov_write_esds_tag(pb, track);
     } else if (mov_pcm_le_gt16(track->enc->codec_id)) {
         mov_write_enda_tag(pb);
@@ -339,19 +350,22 @@ static int mov_write_wave_tag(ByteIOContext *pb, MOVTrack *track)
         mov_write_ac3_tag(pb, track);
     } else if (track->enc->codec_id == CODEC_ID_ALAC) {
         mov_write_extradata_tag(pb, track);
+    } else if (track->enc->codec_id == CODEC_ID_ADPCM_MS ||
+               track->enc->codec_id == CODEC_ID_ADPCM_IMA_WAV) {
+        mov_write_ms_tag(pb, track);
     }
 
-    put_be32(pb, 8);     /* size */
-    put_be32(pb, 0);     /* null tag */
+    avio_wb32(pb, 8);     /* size */
+    avio_wb32(pb, 0);     /* null tag */
 
     return updateSize(pb, pos);
 }
 
-static int mov_write_glbl_tag(ByteIOContext *pb, MOVTrack *track)
+static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track)
 {
-    put_be32(pb, track->vosLen+8);
-    put_tag(pb, "glbl");
-    put_buffer(pb, track->vosData, track->vosLen);
+    avio_wb32(pb, track->vosLen+8);
+    ffio_wfourcc(pb, "glbl");
+    avio_write(pb, track->vosData, track->vosLen);
     return 8+track->vosLen;
 }
 
@@ -384,9 +398,9 @@ static int mov_get_lpcm_flags(enum CodecID codec_id)
     }
 }
 
-static int mov_write_audio_tag(ByteIOContext *pb, MOVTrack *track)
+static int mov_write_audio_tag(AVIOContext *pb, MOVTrack *track)
 {
-    int64_t pos = url_ftell(pb);
+    int64_t pos = avio_tell(pb);
     int version = 0;
     uint32_t tag = track->tag;
 
@@ -395,61 +409,63 @@ static int mov_write_audio_tag(ByteIOContext *pb, MOVTrack *track)
             if (mov_get_lpcm_flags(track->enc->codec_id))
                 tag = AV_RL32("lpcm");
             version = 2;
-        } else if (track->audio_vbr || mov_pcm_le_gt16(track->enc->codec_id)) {
+        } else if (track->audio_vbr || mov_pcm_le_gt16(track->enc->codec_id) ||
+                   track->enc->codec_id == CODEC_ID_ADPCM_MS ||
+                   track->enc->codec_id == CODEC_ID_ADPCM_IMA_WAV) {
             version = 1;
         }
     }
 
-    put_be32(pb, 0); /* size */
-    put_le32(pb, tag); // store it byteswapped
-    put_be32(pb, 0); /* Reserved */
-    put_be16(pb, 0); /* Reserved */
-    put_be16(pb, 1); /* Data-reference index, XXX  == 1 */
+    avio_wb32(pb, 0); /* size */
+    avio_wl32(pb, tag); // store it byteswapped
+    avio_wb32(pb, 0); /* Reserved */
+    avio_wb16(pb, 0); /* Reserved */
+    avio_wb16(pb, 1); /* Data-reference index, XXX  == 1 */
 
     /* SoundDescription */
-    put_be16(pb, version); /* Version */
-    put_be16(pb, 0); /* Revision level */
-    put_be32(pb, 0); /* Reserved */
+    avio_wb16(pb, version); /* Version */
+    avio_wb16(pb, 0); /* Revision level */
+    avio_wb32(pb, 0); /* Reserved */
 
     if (version == 2) {
-        put_be16(pb, 3);
-        put_be16(pb, 16);
-        put_be16(pb, 0xfffe);
-        put_be16(pb, 0);
-        put_be32(pb, 0x00010000);
-        put_be32(pb, 72);
-        put_be64(pb, av_dbl2int(track->timescale));
-        put_be32(pb, track->enc->channels);
-        put_be32(pb, 0x7F000000);
-        put_be32(pb, av_get_bits_per_sample(track->enc->codec_id));
-        put_be32(pb, mov_get_lpcm_flags(track->enc->codec_id));
-        put_be32(pb, track->sampleSize);
-        put_be32(pb, track->enc->frame_size);
+        avio_wb16(pb, 3);
+        avio_wb16(pb, 16);
+        avio_wb16(pb, 0xfffe);
+        avio_wb16(pb, 0);
+        avio_wb32(pb, 0x00010000);
+        avio_wb32(pb, 72);
+        avio_wb64(pb, av_dbl2int(track->timescale));
+        avio_wb32(pb, track->enc->channels);
+        avio_wb32(pb, 0x7F000000);
+        avio_wb32(pb, av_get_bits_per_sample(track->enc->codec_id));
+        avio_wb32(pb, mov_get_lpcm_flags(track->enc->codec_id));
+        avio_wb32(pb, track->sampleSize);
+        avio_wb32(pb, track->enc->frame_size);
     } else {
         if (track->mode == MODE_MOV) {
-            put_be16(pb, track->enc->channels);
+            avio_wb16(pb, track->enc->channels);
             if (track->enc->codec_id == CODEC_ID_PCM_U8 ||
                 track->enc->codec_id == CODEC_ID_PCM_S8)
-                put_be16(pb, 8); /* bits per sample */
+                avio_wb16(pb, 8); /* bits per sample */
             else
-                put_be16(pb, 16);
-            put_be16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
+                avio_wb16(pb, 16);
+            avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
         } else { /* reserved for mp4/3gp */
-            put_be16(pb, 2);
-            put_be16(pb, 16);
-            put_be16(pb, 0);
+            avio_wb16(pb, 2);
+            avio_wb16(pb, 16);
+            avio_wb16(pb, 0);
         }
 
-        put_be16(pb, 0); /* packet size (= 0) */
-        put_be16(pb, track->timescale); /* Time scale */
-        put_be16(pb, 0); /* Reserved */
+        avio_wb16(pb, 0); /* packet size (= 0) */
+        avio_wb16(pb, track->timescale); /* Time scale */
+        avio_wb16(pb, 0); /* Reserved */
     }
 
     if(version == 1) { /* SoundDescription V1 extended info */
-        put_be32(pb, track->enc->frame_size); /* Samples per packet */
-        put_be32(pb, track->sampleSize / track->enc->channels); /* Bytes per packet */
-        put_be32(pb, track->sampleSize); /* Bytes per frame */
-        put_be32(pb, 2); /* Bytes per sample */
+        avio_wb32(pb, track->enc->frame_size); /* Samples per packet */
+        avio_wb32(pb, track->sampleSize / track->enc->channels); /* Bytes per packet */
+        avio_wb32(pb, track->sampleSize); /* Bytes per frame */
+        avio_wb32(pb, 2); /* Bytes per sample */
     }
 
     if(track->mode == MODE_MOV &&
@@ -457,6 +473,8 @@ static int mov_write_audio_tag(ByteIOContext *pb, MOVTrack *track)
         track->enc->codec_id == CODEC_ID_AC3 ||
         track->enc->codec_id == CODEC_ID_AMR_NB ||
         track->enc->codec_id == CODEC_ID_ALAC ||
+        track->enc->codec_id == CODEC_ID_ADPCM_MS ||
+        track->enc->codec_id == CODEC_ID_ADPCM_IMA_WAV ||
         mov_pcm_le_gt16(track->enc->codec_id)))
         mov_write_wave_tag(pb, track);
     else if(track->tag == MKTAG('m','p','4','a'))
@@ -473,86 +491,86 @@ static int mov_write_audio_tag(ByteIOContext *pb, MOVTrack *track)
     return updateSize(pb, pos);
 }
 
-static int mov_write_d263_tag(ByteIOContext *pb)
+static int mov_write_d263_tag(AVIOContext *pb)
 {
-    put_be32(pb, 0xf); /* size */
-    put_tag(pb, "d263");
-    put_tag(pb, "FFMP");
-    put_byte(pb, 0); /* decoder version */
+    avio_wb32(pb, 0xf); /* size */
+    ffio_wfourcc(pb, "d263");
+    ffio_wfourcc(pb, "FFMP");
+    avio_w8(pb, 0); /* decoder version */
     /* FIXME use AVCodecContext level/profile, when encoder will set values */
-    put_byte(pb, 0xa); /* level */
-    put_byte(pb, 0); /* profile */
+    avio_w8(pb, 0xa); /* level */
+    avio_w8(pb, 0); /* profile */
     return 0xf;
 }
 
 /* TODO: No idea about these values */
-static int mov_write_svq3_tag(ByteIOContext *pb)
-{
-    put_be32(pb, 0x15);
-    put_tag(pb, "SMI ");
-    put_tag(pb, "SEQH");
-    put_be32(pb, 0x5);
-    put_be32(pb, 0xe2c0211d);
-    put_be32(pb, 0xc0000000);
-    put_byte(pb, 0);
+static int mov_write_svq3_tag(AVIOContext *pb)
+{
+    avio_wb32(pb, 0x15);
+    ffio_wfourcc(pb, "SMI ");
+    ffio_wfourcc(pb, "SEQH");
+    avio_wb32(pb, 0x5);
+    avio_wb32(pb, 0xe2c0211d);
+    avio_wb32(pb, 0xc0000000);
+    avio_w8(pb, 0);
     return 0x15;
 }
 
-static int mov_write_avcc_tag(ByteIOContext *pb, MOVTrack *track)
+static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track)
 {
-    int64_t pos = url_ftell(pb);
+    int64_t pos = avio_tell(pb);
 
-    put_be32(pb, 0);
-    put_tag(pb, "avcC");
+    avio_wb32(pb, 0);
+    ffio_wfourcc(pb, "avcC");
     ff_isom_write_avcc(pb, track->vosData, track->vosLen);
     return updateSize(pb, pos);
 }
 
 /* also used by all avid codecs (dv, imx, meridien) and their variants */
-static int mov_write_avid_tag(ByteIOContext *pb, MOVTrack *track)
+static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
 {
     int i;
-    put_be32(pb, 24); /* size */
-    put_tag(pb, "ACLR");
-    put_tag(pb, "ACLR");
-    put_tag(pb, "0001");
-    put_be32(pb, 1); /* yuv 1 / rgb 2 ? */
-    put_be32(pb, 0); /* unknown */
-
-    put_be32(pb, 24); /* size */
-    put_tag(pb, "APRG");
-    put_tag(pb, "APRG");
-    put_tag(pb, "0001");
-    put_be32(pb, 1); /* unknown */
-    put_be32(pb, 0); /* unknown */
-
-    put_be32(pb, 120); /* size */
-    put_tag(pb, "ARES");
-    put_tag(pb, "ARES");
-    put_tag(pb, "0001");
-    put_be32(pb, AV_RB32(track->vosData + 0x28)); /* dnxhd cid, some id ? */
-    put_be32(pb, track->enc->width);
+    avio_wb32(pb, 24); /* size */
+    ffio_wfourcc(pb, "ACLR");
+    ffio_wfourcc(pb, "ACLR");
+    ffio_wfourcc(pb, "0001");
+    avio_wb32(pb, 1); /* yuv 1 / rgb 2 ? */
+    avio_wb32(pb, 0); /* unknown */
+
+    avio_wb32(pb, 24); /* size */
+    ffio_wfourcc(pb, "APRG");
+    ffio_wfourcc(pb, "APRG");
+    ffio_wfourcc(pb, "0001");
+    avio_wb32(pb, 1); /* unknown */
+    avio_wb32(pb, 0); /* unknown */
+
+    avio_wb32(pb, 120); /* size */
+    ffio_wfourcc(pb, "ARES");
+    ffio_wfourcc(pb, "ARES");
+    ffio_wfourcc(pb, "0001");
+    avio_wb32(pb, AV_RB32(track->vosData + 0x28)); /* dnxhd cid, some id ? */
+    avio_wb32(pb, track->enc->width);
     /* values below are based on samples created with quicktime and avid codecs */
     if (track->vosData[5] & 2) { // interlaced
-        put_be32(pb, track->enc->height/2);
-        put_be32(pb, 2); /* unknown */
-        put_be32(pb, 0); /* unknown */
-        put_be32(pb, 4); /* unknown */
+        avio_wb32(pb, track->enc->height/2);
+        avio_wb32(pb, 2); /* unknown */
+        avio_wb32(pb, 0); /* unknown */
+        avio_wb32(pb, 4); /* unknown */
     } else {
-        put_be32(pb, track->enc->height);
-        put_be32(pb, 1); /* unknown */
-        put_be32(pb, 0); /* unknown */
+        avio_wb32(pb, track->enc->height);
+        avio_wb32(pb, 1); /* unknown */
+        avio_wb32(pb, 0); /* unknown */
         if (track->enc->height == 1080)
-            put_be32(pb, 5); /* unknown */
+            avio_wb32(pb, 5); /* unknown */
         else
-            put_be32(pb, 6); /* unknown */
+            avio_wb32(pb, 6); /* unknown */
     }
     /* padding */
     for (i = 0; i < 10; i++)
-        put_be64(pb, 0);
+        avio_wb64(pb, 0);
 
     /* extra padding for stsd needed */
-    put_be32(pb, 0);
+    avio_wb32(pb, 0);
     return 0;
 }
 
@@ -605,12 +623,23 @@ static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
 {
     int tag;
 
-    if (track->enc->height == 480) /* NTSC */
-        if  (track->enc->pix_fmt == PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
-        else                                         tag = MKTAG('d','v','c',' ');
-    else if (track->enc->pix_fmt == PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
-    else if (track->enc->pix_fmt == PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
-    else                                             tag = MKTAG('d','v','p','p');
+    if (track->enc->width == 720) /* SD */
+        if (track->enc->height == 480) /* NTSC */
+            if  (track->enc->pix_fmt == PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
+            else                                         tag = MKTAG('d','v','c',' ');
+        else if (track->enc->pix_fmt == PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
+        else if (track->enc->pix_fmt == PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
+        else                                             tag = MKTAG('d','v','p','p');
+    else if (track->enc->height == 720) /* HD 720 line */
+        if  (track->enc->time_base.den == 50)            tag = MKTAG('d','v','h','q');
+        else                                             tag = MKTAG('d','v','h','p');
+    else if (track->enc->height == 1080) /* HD 1080 line */
+        if  (track->enc->time_base.den == 25)            tag = MKTAG('d','v','h','5');
+        else                                             tag = MKTAG('d','v','h','6');
+    else {
+        av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
+        return 0;
+    }
 
     return tag;
 }
@@ -622,15 +651,18 @@ static const struct {
 } mov_pix_fmt_tags[] = {
     { PIX_FMT_YUYV422, MKTAG('y','u','v','s'),  0 },
     { PIX_FMT_UYVY422, MKTAG('2','v','u','y'),  0 },
-    { PIX_FMT_BGR555,  MKTAG('r','a','w',' '), 16 },
+    { PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
     { PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
     { PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
     { PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
+    { PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
     { PIX_FMT_RGB24,   MKTAG('r','a','w',' '), 24 },
     { PIX_FMT_BGR24,   MKTAG('2','4','B','G'), 24 },
     { PIX_FMT_ARGB,    MKTAG('r','a','w',' '), 32 },
     { PIX_FMT_BGRA,    MKTAG('B','G','R','A'), 32 },
     { PIX_FMT_RGBA,    MKTAG('R','G','B','A'), 32 },
+    { PIX_FMT_ABGR,    MKTAG('A','B','G','R'), 32 },
+    { PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
 };
 
 static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
@@ -654,8 +686,9 @@ static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
     int tag = track->enc->codec_tag;
 
     if (!tag || (track->enc->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
-                 (tag == MKTAG('d','v','c','p') ||
+                 (track->enc->codec_id == CODEC_ID_DVVIDEO ||
                   track->enc->codec_id == CODEC_ID_RAWVIDEO ||
+                  track->enc->codec_id == CODEC_ID_H263 ||
                   av_get_bits_per_sample(track->enc->codec_id)))) { // pcm audio
         if (track->enc->codec_id == CODEC_ID_DVVIDEO)
             tag = mov_get_dv_codec_tag(s, track);
@@ -717,79 +750,92 @@ static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
  * Needed to make file play in iPods running newest firmware
  * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
  */
-static int mov_write_uuid_tag_ipod(ByteIOContext *pb)
-{
-    put_be32(pb, 28);
-    put_tag(pb, "uuid");
-    put_be32(pb, 0x6b6840f2);
-    put_be32(pb, 0x5f244fc5);
-    put_be32(pb, 0xba39a51b);
-    put_be32(pb, 0xcf0323f3);
-    put_be32(pb, 0x0);
+static int mov_write_uuid_tag_ipod(AVIOContext *pb)
+{
+    avio_wb32(pb, 28);
+    ffio_wfourcc(pb, "uuid");
+    avio_wb32(pb, 0x6b6840f2);
+    avio_wb32(pb, 0x5f244fc5);
+    avio_wb32(pb, 0xba39a51b);
+    avio_wb32(pb, 0xcf0323f3);
+    avio_wb32(pb, 0x0);
     return 28;
 }
 
-static int mov_write_subtitle_tag(ByteIOContext *pb, MOVTrack *track)
+static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
 {
-    int64_t pos = url_ftell(pb);
-    put_be32(pb, 0);    /* size */
-    put_le32(pb, track->tag); // store it byteswapped
-    put_be32(pb, 0);    /* Reserved */
-    put_be16(pb, 0);    /* Reserved */
-    put_be16(pb, 1);    /* Data-reference index */
+    int64_t pos = avio_tell(pb);
+    avio_wb32(pb, 0);    /* size */
+    avio_wl32(pb, track->tag); // store it byteswapped
+    avio_wb32(pb, 0);    /* Reserved */
+    avio_wb16(pb, 0);    /* Reserved */
+    avio_wb16(pb, 1);    /* Data-reference index */
 
     if (track->enc->extradata_size)
-        put_buffer(pb, track->enc->extradata, track->enc->extradata_size);
+        avio_write(pb, track->enc->extradata, track->enc->extradata_size);
 
     return updateSize(pb, pos);
 }
 
-static int mov_write_video_tag(ByteIOContext *pb, MOVTrack *track)
+static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
+{
+    AVRational sar;
+    av_reduce(&sar.num, &sar.den, track->enc->sample_aspect_ratio.num,
+              track->enc->sample_aspect_ratio.den, INT_MAX);
+
+    avio_wb32(pb, 16);
+    ffio_wfourcc(pb, "pasp");
+    avio_wb32(pb, sar.num);
+    avio_wb32(pb, sar.den);
+    return 16;
+}
+
+static int mov_write_video_tag(AVIOContext *pb, MOVTrack *track)
 {
-    int64_t pos = url_ftell(pb);
+    int64_t pos = avio_tell(pb);
     char compressor_name[32];
 
-    put_be32(pb, 0); /* size */
-    put_le32(pb, track->tag); // store it byteswapped
-    put_be32(pb, 0); /* Reserved */
-    put_be16(pb, 0); /* Reserved */
-    put_be16(pb, 1); /* Data-reference index */
+    avio_wb32(pb, 0); /* size */
+    avio_wl32(pb, track->tag); // store it byteswapped
+    avio_wb32(pb, 0); /* Reserved */
+    avio_wb16(pb, 0); /* Reserved */
+    avio_wb16(pb, 1); /* Data-reference index */
 
-    put_be16(pb, 0); /* Codec stream version */
-    put_be16(pb, 0); /* Codec stream revision (=0) */
+    avio_wb16(pb, 0); /* Codec stream version */
+    avio_wb16(pb, 0); /* Codec stream revision (=0) */
     if (track->mode == MODE_MOV) {
-        put_tag(pb, "FFMP"); /* Vendor */
+        ffio_wfourcc(pb, "FFMP"); /* Vendor */
         if(track->enc->codec_id == CODEC_ID_RAWVIDEO) {
-            put_be32(pb, 0); /* Temporal Quality */
-            put_be32(pb, 0x400); /* Spatial Quality = lossless*/
+            avio_wb32(pb, 0); /* Temporal Quality */
+            avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
         } else {
-            put_be32(pb, 0x200); /* Temporal Quality = normal */
-            put_be32(pb, 0x200); /* Spatial Quality = normal */
+            avio_wb32(pb, 0x200); /* Temporal Quality = normal */
+            avio_wb32(pb, 0x200); /* Spatial Quality = normal */
         }
     } else {
-        put_be32(pb, 0); /* Reserved */
-        put_be32(pb, 0); /* Reserved */
-        put_be32(pb, 0); /* Reserved */
+        avio_wb32(pb, 0); /* Reserved */
+        avio_wb32(pb, 0); /* Reserved */
+        avio_wb32(pb, 0); /* Reserved */
     }
-    put_be16(pb, track->enc->width); /* Video width */
-    put_be16(pb, track->height); /* Video height */
-    put_be32(pb, 0x00480000); /* Horizontal resolution 72dpi */
-    put_be32(pb, 0x00480000); /* Vertical resolution 72dpi */
-    put_be32(pb, 0); /* Data size (= 0) */
-    put_be16(pb, 1); /* Frame count (= 1) */
+    avio_wb16(pb, track->enc->width); /* Video width */
+    avio_wb16(pb, track->height); /* Video height */
+    avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
+    avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
+    avio_wb32(pb, 0); /* Data size (= 0) */
+    avio_wb16(pb, 1); /* Frame count (= 1) */
 
     memset(compressor_name,0,32);
     /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
     if (track->mode == MODE_MOV && track->enc->codec && track->enc->codec->name)
         strncpy(compressor_name,track->enc->codec->name,31);
-    put_byte(pb, strlen(compressor_name));
-    put_buffer(pb, compressor_name, 31);
+    avio_w8(pb, strlen(compressor_name));
+    avio_write(pb, compressor_name, 31);
 
     if (track->mode == MODE_MOV && track->enc->bits_per_coded_sample)
-        put_be16(pb, track->enc->bits_per_coded_sample);
+        avio_wb16(pb, track->enc->bits_per_coded_sample);
     else
-        put_be16(pb, 0x18); /* Reserved */
-    put_be16(pb, 0xffff); /* Reserved */
+        avio_wb16(pb, 0x18); /* Reserved */
+    avio_wb16(pb, 0xffff); /* Reserved */
     if(track->tag == MKTAG('m','p','4','v'))
         mov_write_esds_tag(pb, track);
     else if(track->enc->codec_id == CODEC_ID_H263)
@@ -805,36 +851,41 @@ static int mov_write_video_tag(ByteIOContext *pb, MOVTrack *track)
     } else if(track->vosLen > 0)
         mov_write_glbl_tag(pb, track);
 
+    if (track->enc->sample_aspect_ratio.den && track->enc->sample_aspect_ratio.num &&
+        track->enc->sample_aspect_ratio.den != track->enc->sample_aspect_ratio.num) {
+        mov_write_pasp_tag(pb, track);
+    }
+
     return updateSize(pb, pos);
 }
 
-static int mov_write_rtp_tag(ByteIOContext *pb, MOVTrack *track)
+static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
 {
-    int64_t pos = url_ftell(pb);
-    put_be32(pb, 0); /* size */
-    put_tag(pb, "rtp ");
-    put_be32(pb, 0); /* Reserved */
-    put_be16(pb, 0); /* Reserved */
-    put_be16(pb, 1); /* Data-reference index */
+    int64_t pos = avio_tell(pb);
+    avio_wb32(pb, 0); /* size */
+    ffio_wfourcc(pb, "rtp ");
+    avio_wb32(pb, 0); /* Reserved */
+    avio_wb16(pb, 0); /* Reserved */
+    avio_wb16(pb, 1); /* Data-reference index */
 
-    put_be16(pb, 1); /* Hint track version */
-    put_be16(pb, 1); /* Highest compatible version */
-    put_be32(pb, track->max_packet_size); /* Max packet size */
+    avio_wb16(pb, 1); /* Hint track version */
+    avio_wb16(pb, 1); /* Highest compatible version */
+    avio_wb32(pb, track->max_packet_size); /* Max packet size */
 
-    put_be32(pb, 12); /* size */
-    put_tag(pb, "tims");
-    put_be32(pb, track->timescale);
+    avio_wb32(pb, 12); /* size */
+    ffio_wfourcc(pb, "tims");
+    avio_wb32(pb, track->timescale);
 
     return updateSize(pb, pos);
 }
 
-static int mov_write_stsd_tag(ByteIOContext *pb, MOVTrack *track)
+static int mov_write_stsd_tag(AVIOContext *pb, MOVTrack *track)
 {
-    int64_t pos = url_ftell(pb);
-    put_be32(pb, 0); /* size */
-    put_tag(pb, "stsd");
-    put_be32(pb, 0); /* version & flags */
-    put_be32(pb, 1); /* entry count */
+    int64_t pos = avio_tell(pb);
+    avio_wb32(pb, 0); /* size */
+    ffio_wfourcc(pb, "stsd");
+    avio_wb32(pb, 0); /* version & flags */
+    avio_wb32(pb, 1); /* entry count */
     if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO)
         mov_write_video_tag(pb, track);
     else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
@@ -846,7 +897,7 @@ static int mov_write_stsd_tag(ByteIOContext *pb, MOVTrack *track)
     return updateSize(pb, pos);
 }
 
-static int mov_write_ctts_tag(ByteIOContext *pb, MOVTrack *track)
+static int mov_write_ctts_tag(AVIOContext *pb, MOVTrack *track)
 {
     MOVStts *ctts_entries;
     uint32_t entries = 0;
@@ -867,20 +918,20 @@ static int mov_write_ctts_tag(ByteIOContext *pb, MOVTrack *track)
     }
     entries++; /* last one */
     atom_size = 16 + (entries * 8);
-    put_be32(pb, atom_size); /* size */
-    put_tag(pb, "ctts");
-    put_be32(pb, 0); /* version & flags */
-    put_be32(pb, entries); /* entry count */
+    avio_wb32(pb, atom_size); /* size */
+    ffio_wfourcc(pb, "ctts");
+    avio_wb32(pb, 0); /* version & flags */
+    avio_wb32(pb, entries); /* entry count */
     for (i=0; i<entries; i++) {
-        put_be32(pb, ctts_entries[i].count);
-        put_be32(pb, ctts_entries[i].duration);
+        avio_wb32(pb, ctts_entries[i].count);
+        avio_wb32(pb, ctts_entries[i].duration);
     }
     av_free(ctts_entries);
     return atom_size;
 }
 
 /* Time to sample atom */
-static int mov_write_stts_tag(ByteIOContext *pb, MOVTrack *track)
+static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
 {
     MOVStts *stts_entries;
     uint32_t entries = -1;
@@ -909,37 +960,37 @@ static int mov_write_stts_tag(ByteIOContext *pb, MOVTrack *track)
         entries++; /* last one */
     }
     atom_size = 16 + (entries * 8);
-    put_be32(pb, atom_size); /* size */
-    put_tag(pb, "stts");
-    put_be32(pb, 0); /* version & flags */
-    put_be32(pb, entries); /* entry count */
+    avio_wb32(pb, atom_size); /* size */
+    ffio_wfourcc(pb, "stts");
+    avio_wb32(pb, 0); /* version & flags */
+    avio_wb32(pb, entries); /* entry count */
     for (i=0; i<entries; i++) {
-        put_be32(pb, stts_entries[i].count);
-        put_be32(pb, stts_entries[i].duration);
+        avio_wb32(pb, stts_entries[i].count);
+        avio_wb32(pb, stts_entries[i].duration);
     }
     av_free(stts_entries);
     return atom_size;
 }
 
-static int mov_write_dref_tag(ByteIOContext *pb)
+static int mov_write_dref_tag(AVIOContext *pb)
 {
-    put_be32(pb, 28); /* size */
-    put_tag(pb, "dref");
-    put_be32(pb, 0); /* version & flags */
-    put_be32(pb, 1); /* entry count */
+    avio_wb32(pb, 28); /* size */
+    ffio_wfourcc(pb, "dref");
+    avio_wb32(pb, 0); /* version & flags */
+    avio_wb32(pb, 1); /* entry count */
 
-    put_be32(pb, 0xc); /* size */
-    put_tag(pb, "url ");
-    put_be32(pb, 1); /* version & flags */
+    avio_wb32(pb, 0xc); /* size */
+    ffio_wfourcc(pb, "url ");
+    avio_wb32(pb, 1); /* version & flags */
 
     return 28;
 }
 
-static int mov_write_stbl_tag(ByteIOContext *pb, MOVTrack *track)
+static int mov_write_stbl_tag(AVIOContext *pb, MOVTrack *track)
 {
-    int64_t pos = url_ftell(pb);
-    put_be32(pb, 0); /* size */
-    put_tag(pb, "stbl");
+    int64_t pos = avio_tell(pb);
+    avio_wb32(pb, 0); /* size */
+    ffio_wfourcc(pb, "stbl");
     mov_write_stsd_tag(pb, track);
     mov_write_stts_tag(pb, track);
     if ((track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||
@@ -957,62 +1008,62 @@ static int mov_write_stbl_tag(ByteIOContext *pb, MOVTrack *track)
     return updateSize(pb, pos);
 }
 
-static int mov_write_dinf_tag(ByteIOContext *pb)
+static int mov_write_dinf_tag(AVIOContext *pb)
 {
-    int64_t pos = url_ftell(pb);
-    put_be32(pb, 0); /* size */
-    put_tag(pb, "dinf");
+    int64_t pos = avio_tell(pb);
+    avio_wb32(pb, 0); /* size */
+    ffio_wfourcc(pb, "dinf");
     mov_write_dref_tag(pb);
     return updateSize(pb, pos);
 }
 
-static int mov_write_nmhd_tag(ByteIOContext *pb)
+static int mov_write_nmhd_tag(AVIOContext *pb)
 {
-    put_be32(pb, 12);
-    put_tag(pb, "nmhd");
-    put_be32(pb, 0);
+    avio_wb32(pb, 12);
+    ffio_wfourcc(pb, "nmhd");
+    avio_wb32(pb, 0);
     return 12;
 }
 
-static int mov_write_gmhd_tag(ByteIOContext *pb)
+static int mov_write_gmhd_tag(AVIOContext *pb)
 {
-    put_be32(pb, 0x20);   /* size */
-    put_tag(pb, "gmhd");
-    put_be32(pb, 0x18);   /* gmin size */
-    put_tag(pb, "gmin");  /* generic media info */
-    put_be32(pb, 0);      /* version & flags */
-    put_be16(pb, 0x40);   /* graphics mode = */
-    put_be16(pb, 0x8000); /* opColor (r?) */
-    put_be16(pb, 0x8000); /* opColor (g?) */
-    put_be16(pb, 0x8000); /* opColor (b?) */
-    put_be16(pb, 0);      /* balance */
-    put_be16(pb, 0);      /* reserved */
+    avio_wb32(pb, 0x20);   /* size */
+    ffio_wfourcc(pb, "gmhd");
+    avio_wb32(pb, 0x18);   /* gmin size */
+    ffio_wfourcc(pb, "gmin");/* generic media info */
+    avio_wb32(pb, 0);      /* version & flags */
+    avio_wb16(pb, 0x40);   /* graphics mode = */
+    avio_wb16(pb, 0x8000); /* opColor (r?) */
+    avio_wb16(pb, 0x8000); /* opColor (g?) */
+    avio_wb16(pb, 0x8000); /* opColor (b?) */
+    avio_wb16(pb, 0);      /* balance */
+    avio_wb16(pb, 0);      /* reserved */
     return 0x20;
 }
 
-static int mov_write_smhd_tag(ByteIOContext *pb)
+static int mov_write_smhd_tag(AVIOContext *pb)
 {
-    put_be32(pb, 16); /* size */
-    put_tag(pb, "smhd");
-    put_be32(pb, 0); /* version & flags */
-    put_be16(pb, 0); /* reserved (balance, normally = 0) */
-    put_be16(pb, 0); /* reserved */
+    avio_wb32(pb, 16); /* size */
+    ffio_wfourcc(pb, "smhd");
+    avio_wb32(pb, 0); /* version & flags */
+    avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
+    avio_wb16(pb, 0); /* reserved */
     return 16;
 }
 
-static int mov_write_vmhd_tag(ByteIOContext *pb)
+static int mov_write_vmhd_tag(AVIOContext *pb)
 {
-    put_be32(pb, 0x14); /* size (always 0x14) */
-    put_tag(pb, "vmhd");
-    put_be32(pb, 0x01); /* version & flags */
-    put_be64(pb, 0); /* reserved (graphics mode = copy) */
+    avio_wb32(pb, 0x14); /* size (always 0x14) */
+    ffio_wfourcc(pb, "vmhd");
+    avio_wb32(pb, 0x01); /* version & flags */
+    avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
     return 0x14;
 }
 
-static int mov_write_hdlr_tag(ByteIOContext *pb, MOVTrack *track)
+static int mov_write_hdlr_tag(AVIOContext *pb, MOVTrack *track)
 {
     const char *hdlr, *descr = NULL, *hdlr_type = NULL;
-    int64_t pos = url_ftell(pb);
+    int64_t pos = avio_tell(pb);
 
     if (!track) { /* no media --> data handler */
         hdlr = "dhlr";
@@ -1036,42 +1087,42 @@ static int mov_write_hdlr_tag(ByteIOContext *pb, MOVTrack *track)
         }
     }
 
-    put_be32(pb, 0); /* size */
-    put_tag(pb, "hdlr");
-    put_be32(pb, 0); /* Version & flags */
-    put_buffer(pb, hdlr, 4); /* handler */
-    put_tag(pb, hdlr_type); /* handler type */
-    put_be32(pb ,0); /* reserved */
-    put_be32(pb ,0); /* reserved */
-    put_be32(pb ,0); /* reserved */
+    avio_wb32(pb, 0); /* size */
+    ffio_wfourcc(pb, "hdlr");
+    avio_wb32(pb, 0); /* Version & flags */
+    avio_write(pb, hdlr, 4); /* handler */
+    ffio_wfourcc(pb, hdlr_type); /* handler type */
+    avio_wb32(pb ,0); /* reserved */
+    avio_wb32(pb ,0); /* reserved */
+    avio_wb32(pb ,0); /* reserved */
     if (!track || track->mode == MODE_MOV)
-        put_byte(pb, strlen(descr)); /* pascal string */
-    put_buffer(pb, descr, strlen(descr)); /* handler description */
+        avio_w8(pb, strlen(descr)); /* pascal string */
+    avio_write(pb, descr, strlen(descr)); /* handler description */
     if (track && track->mode != MODE_MOV)
-        put_byte(pb, 0); /* c string */
+        avio_w8(pb, 0); /* c string */
     return updateSize(pb, pos);
 }
 
-static int mov_write_hmhd_tag(ByteIOContext *pb)
+static int mov_write_hmhd_tag(AVIOContext *pb)
 {
     /* This atom must be present, but leaving the values at zero
      * seems harmless. */
-    put_be32(pb, 28); /* size */
-    put_tag(pb, "hmhd");
-    put_be32(pb, 0); /* version, flags */
-    put_be16(pb, 0); /* maxPDUsize */
-    put_be16(pb, 0); /* avgPDUsize */
-    put_be32(pb, 0); /* maxbitrate */
-    put_be32(pb, 0); /* avgbitrate */
-    put_be32(pb, 0); /* reserved */
+    avio_wb32(pb, 28); /* size */
+    ffio_wfourcc(pb, "hmhd");
+    avio_wb32(pb, 0); /* version, flags */
+    avio_wb16(pb, 0); /* maxPDUsize */
+    avio_wb16(pb, 0); /* avgPDUsize */
+    avio_wb32(pb, 0); /* maxbitrate */
+    avio_wb32(pb, 0); /* avgbitrate */
+    avio_wb32(pb, 0); /* reserved */
     return 28;
 }
 
-static int mov_write_minf_tag(ByteIOContext *pb, MOVTrack *track)
+static int mov_write_minf_tag(AVIOContext *pb, MOVTrack *track)
 {
-    int64_t pos = url_ftell(pb);
-    put_be32(pb, 0); /* size */
-    put_tag(pb, "minf");
+    int64_t pos = avio_tell(pb);
+    avio_wb32(pb, 0); /* size */
+    ffio_wfourcc(pb, "minf");
     if(track->enc->codec_type == AVMEDIA_TYPE_VIDEO)
         mov_write_vmhd_tag(pb);
     else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
@@ -1089,25 +1140,25 @@ static int mov_write_minf_tag(ByteIOContext *pb, MOVTrack *track)
     return updateSize(pb, pos);
 }
 
-static int mov_write_mdhd_tag(ByteIOContext *pb, MOVTrack *track)
+static int mov_write_mdhd_tag(AVIOContext *pb, MOVTrack *track)
 {
     int version = track->trackDuration < INT32_MAX ? 0 : 1;
 
-    (version == 1) ? put_be32(pb, 44) : put_be32(pb, 32); /* size */
-    put_tag(pb, "mdhd");
-    put_byte(pb, version);
-    put_be24(pb, 0); /* flags */
+    (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
+    ffio_wfourcc(pb, "mdhd");
+    avio_w8(pb, version);
+    avio_wb24(pb, 0); /* flags */
     if (version == 1) {
-        put_be64(pb, track->time);
-        put_be64(pb, track->time);
+        avio_wb64(pb, track->time);
+        avio_wb64(pb, track->time);
     } else {
-        put_be32(pb, track->time); /* creation time */
-        put_be32(pb, track->time); /* modification time */
+        avio_wb32(pb, track->time); /* creation time */
+        avio_wb32(pb, track->time); /* modification time */
     }
-    put_be32(pb, track->timescale); /* time scale (sample rate for audio) */
-    (version == 1) ? put_be64(pb, track->trackDuration) : put_be32(pb, track->trackDuration); /* duration */
-    put_be16(pb, track->language); /* language */
-    put_be16(pb, 0); /* reserved (quality) */
+    avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
+    (version == 1) ? avio_wb64(pb, track->trackDuration) : avio_wb32(pb, track->trackDuration); /* duration */
+    avio_wb16(pb, track->language); /* language */
+    avio_wb16(pb, 0); /* reserved (quality) */
 
     if(version!=0 && track->mode == MODE_MOV){
         av_log(NULL, AV_LOG_ERROR,
@@ -1119,147 +1170,177 @@ static int mov_write_mdhd_tag(ByteIOContext *pb, MOVTrack *track)
     return 32;
 }
 
-static int mov_write_mdia_tag(ByteIOContext *pb, MOVTrack *track)
+static int mov_write_mdia_tag(AVIOContext *pb, MOVTrack *track)
 {
-    int64_t pos = url_ftell(pb);
-    put_be32(pb, 0); /* size */
-    put_tag(pb, "mdia");
+    int64_t pos = avio_tell(pb);
+    avio_wb32(pb, 0); /* size */
+    ffio_wfourcc(pb, "mdia");
     mov_write_mdhd_tag(pb, track);
     mov_write_hdlr_tag(pb, track);
     mov_write_minf_tag(pb, track);
     return updateSize(pb, pos);
 }
 
-static int mov_write_tkhd_tag(ByteIOContext *pb, MOVTrack *track, AVStream *st)
+static int mov_write_tkhd_tag(AVIOContext *pb, MOVTrack *track, AVStream *st)
 {
     int64_t duration = av_rescale_rnd(track->trackDuration, MOV_TIMESCALE,
                                       track->timescale, AV_ROUND_UP);
     int version = duration < INT32_MAX ? 0 : 1;
 
-    (version == 1) ? put_be32(pb, 104) : put_be32(pb, 92); /* size */
-    put_tag(pb, "tkhd");
-    put_byte(pb, version);
-    put_be24(pb, 0xf); /* flags (track enabled) */
+    (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
+    ffio_wfourcc(pb, "tkhd");
+    avio_w8(pb, version);
+    avio_wb24(pb, 0xf); /* flags (track enabled) */
     if (version == 1) {
-        put_be64(pb, track->time);
-        put_be64(pb, track->time);
+        avio_wb64(pb, track->time);
+        avio_wb64(pb, track->time);
     } else {
-        put_be32(pb, track->time); /* creation time */
-        put_be32(pb, track->time); /* modification time */
+        avio_wb32(pb, track->time); /* creation time */
+        avio_wb32(pb, track->time); /* modification time */
     }
-    put_be32(pb, track->trackID); /* track-id */
-    put_be32(pb, 0); /* reserved */
-    (version == 1) ? put_be64(pb, duration) : put_be32(pb, duration);
+    avio_wb32(pb, track->trackID); /* track-id */
+    avio_wb32(pb, 0); /* reserved */
+    (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
 
-    put_be32(pb, 0); /* reserved */
-    put_be32(pb, 0); /* reserved */
-    put_be32(pb, 0x0); /* reserved (Layer & Alternate group) */
+    avio_wb32(pb, 0); /* reserved */
+    avio_wb32(pb, 0); /* reserved */
+    avio_wb32(pb, 0x0); /* reserved (Layer & Alternate group) */
     /* Volume, only for audio */
     if(track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
-        put_be16(pb, 0x0100);
+        avio_wb16(pb, 0x0100);
     else
-        put_be16(pb, 0);
-    put_be16(pb, 0); /* reserved */
+        avio_wb16(pb, 0);
+    avio_wb16(pb, 0); /* reserved */
 
     /* Matrix structure */
-    put_be32(pb, 0x00010000); /* reserved */
-    put_be32(pb, 0x0); /* reserved */
-    put_be32(pb, 0x0); /* reserved */
-    put_be32(pb, 0x0); /* reserved */
-    put_be32(pb, 0x00010000); /* reserved */
-    put_be32(pb, 0x0); /* reserved */
-    put_be32(pb, 0x0); /* reserved */
-    put_be32(pb, 0x0); /* reserved */
-    put_be32(pb, 0x40000000); /* reserved */
+    avio_wb32(pb, 0x00010000); /* reserved */
+    avio_wb32(pb, 0x0); /* reserved */
+    avio_wb32(pb, 0x0); /* reserved */
+    avio_wb32(pb, 0x0); /* reserved */
+    avio_wb32(pb, 0x00010000); /* reserved */
+    avio_wb32(pb, 0x0); /* reserved */
+    avio_wb32(pb, 0x0); /* reserved */
+    avio_wb32(pb, 0x0); /* reserved */
+    avio_wb32(pb, 0x40000000); /* reserved */
 
     /* Track width and height, for visual only */
     if(st && (track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||
               track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
-        double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
-        if(!sample_aspect_ratio || track->height != track->enc->height)
-            sample_aspect_ratio = 1;
-        put_be32(pb, sample_aspect_ratio * track->enc->width*0x10000);
-        put_be32(pb, track->height*0x10000);
+        if(track->mode == MODE_MOV) {
+            avio_wb32(pb, track->enc->width << 16);
+            avio_wb32(pb, track->height << 16);
+        } else {
+            double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
+            if(!sample_aspect_ratio || track->height != track->enc->height)
+                sample_aspect_ratio = 1;
+            avio_wb32(pb, sample_aspect_ratio * track->enc->width*0x10000);
+            avio_wb32(pb, track->height*0x10000);
+        }
     }
     else {
-        put_be32(pb, 0);
-        put_be32(pb, 0);
+        avio_wb32(pb, 0);
+        avio_wb32(pb, 0);
     }
     return 0x5c;
 }
 
+static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
+{
+    int32_t width = av_rescale(track->enc->sample_aspect_ratio.num, track->enc->width,
+                               track->enc->sample_aspect_ratio.den);
+
+    int64_t pos = avio_tell(pb);
+
+    avio_wb32(pb, 0); /* size */
+    ffio_wfourcc(pb, "tapt");
+
+    avio_wb32(pb, 20);
+    ffio_wfourcc(pb, "clef");
+    avio_wb32(pb, 0);
+    avio_wb32(pb, width << 16);
+    avio_wb32(pb, track->enc->height << 16);
+
+    avio_wb32(pb, 20);
+    ffio_wfourcc(pb, "enof");
+    avio_wb32(pb, 0);
+    avio_wb32(pb, track->enc->width << 16);
+    avio_wb32(pb, track->enc->height << 16);
+
+    return updateSize(pb, pos);
+};
+
 // This box seems important for the psp playback ... without it the movie seems to hang
-static int mov_write_edts_tag(ByteIOContext *pb, MOVTrack *track)
+static int mov_write_edts_tag(AVIOContext *pb, MOVTrack *track)
 {
-    put_be32(pb, 0x24); /* size  */
-    put_tag(pb, "edts");
-    put_be32(pb, 0x1c); /* size  */
-    put_tag(pb, "elst");
-    put_be32(pb, 0x0);
-    put_be32(pb, 0x1);
+    avio_wb32(pb, 0x24); /* size  */
+    ffio_wfourcc(pb, "edts");
+    avio_wb32(pb, 0x1c); /* size  */
+    ffio_wfourcc(pb, "elst");
+    avio_wb32(pb, 0x0);
+    avio_wb32(pb, 0x1);
 
     /* duration   ... doesn't seem to effect psp */
-    put_be32(pb, av_rescale_rnd(track->trackDuration, MOV_TIMESCALE,
+    avio_wb32(pb, av_rescale_rnd(track->trackDuration, MOV_TIMESCALE,
                                 track->timescale, AV_ROUND_UP));
 
-    put_be32(pb, track->cluster[0].cts); /* first pts is cts since dts is 0 */
-    put_be32(pb, 0x00010000);
+    avio_wb32(pb, track->cluster[0].cts); /* first pts is cts since dts is 0 */
+    avio_wb32(pb, 0x00010000);
     return 0x24;
 }
 
-static int mov_write_tref_tag(ByteIOContext *pb, MOVTrack *track)
+static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
 {
-    put_be32(pb, 20);   // size
-    put_tag(pb, "tref");
-    put_be32(pb, 12);   // size (subatom)
-    put_le32(pb, track->tref_tag);
-    put_be32(pb, track->tref_id);
+    avio_wb32(pb, 20);   // size
+    ffio_wfourcc(pb, "tref");
+    avio_wb32(pb, 12);   // size (subatom)
+    avio_wl32(pb, track->tref_tag);
+    avio_wb32(pb, track->tref_id);
     return 20;
 }
 
 // goes at the end of each track!  ... Critical for PSP playback ("Incompatible data" without it)
-static int mov_write_uuid_tag_psp(ByteIOContext *pb, MOVTrack *mov)
-{
-    put_be32(pb, 0x34); /* size ... reports as 28 in mp4box! */
-    put_tag(pb, "uuid");
-    put_tag(pb, "USMT");
-    put_be32(pb, 0x21d24fce);
-    put_be32(pb, 0xbb88695c);
-    put_be32(pb, 0xfac9c740);
-    put_be32(pb, 0x1c);     // another size here!
-    put_tag(pb, "MTDT");
-    put_be32(pb, 0x00010012);
-    put_be32(pb, 0x0a);
-    put_be32(pb, 0x55c40000);
-    put_be32(pb, 0x1);
-    put_be32(pb, 0x0);
+static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
+{
+    avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
+    ffio_wfourcc(pb, "uuid");
+    ffio_wfourcc(pb, "USMT");
+    avio_wb32(pb, 0x21d24fce);
+    avio_wb32(pb, 0xbb88695c);
+    avio_wb32(pb, 0xfac9c740);
+    avio_wb32(pb, 0x1c);     // another size here!
+    ffio_wfourcc(pb, "MTDT");
+    avio_wb32(pb, 0x00010012);
+    avio_wb32(pb, 0x0a);
+    avio_wb32(pb, 0x55c40000);
+    avio_wb32(pb, 0x1);
+    avio_wb32(pb, 0x0);
     return 0x34;
 }
 
-static int mov_write_udta_sdp(ByteIOContext *pb, AVCodecContext *ctx, int index)
+static int mov_write_udta_sdp(AVIOContext *pb, AVCodecContext *ctx, int index)
 {
     char buf[1000] = "";
     int len;
 
-    ff_sdp_write_media(buf, sizeof(buf), ctx, NULL, 0, 0);
+    ff_sdp_write_media(buf, sizeof(buf), ctx, NULL, NULL, 0, 0);
     av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", index);
     len = strlen(buf);
 
-    put_be32(pb, len + 24);
-    put_tag (pb, "udta");
-    put_be32(pb, len + 16);
-    put_tag (pb, "hnti");
-    put_be32(pb, len + 8);
-    put_tag (pb, "sdp ");
-    put_buffer(pb, buf, len);
+    avio_wb32(pb, len + 24);
+    ffio_wfourcc(pb, "udta");
+    avio_wb32(pb, len + 16);
+    ffio_wfourcc(pb, "hnti");
+    avio_wb32(pb, len + 8);
+    ffio_wfourcc(pb, "sdp ");
+    avio_write(pb, buf, len);
     return len + 24;
 }
 
-static int mov_write_trak_tag(ByteIOContext *pb, MOVTrack *track, AVStream *st)
+static int mov_write_trak_tag(AVIOContext *pb, MOVTrack *track, AVStream *st)
 {
-    int64_t pos = url_ftell(pb);
-    put_be32(pb, 0); /* size */
-    put_tag(pb, "trak");
+    int64_t pos = avio_tell(pb);
+    avio_wb32(pb, 0); /* size */
+    ffio_wfourcc(pb, "trak");
     mov_write_tkhd_tag(pb, track, st);
     if (track->mode == MODE_PSP || track->flags & MOV_TRACK_CTTS)
         mov_write_edts_tag(pb, track);  // PSP Movies require edts box
@@ -1270,26 +1351,31 @@ static int mov_write_trak_tag(ByteIOContext *pb, MOVTrack *track, AVStream *st)
         mov_write_uuid_tag_psp(pb,track);  // PSP Movies require this uuid box
     if (track->tag == MKTAG('r','t','p',' '))
         mov_write_udta_sdp(pb, track->rtp_ctx->streams[0]->codec, track->trackID);
+    if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO && track->mode == MODE_MOV) {
+        double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
+        if (0.0 != sample_aspect_ratio && 1.0 != sample_aspect_ratio)
+            mov_write_tapt_tag(pb, track);
+    };
     return updateSize(pb, pos);
 }
 
 #if 0
 /* TODO: Not sorted out, but not necessary either */
-static int mov_write_iods_tag(ByteIOContext *pb, MOVMuxContext *mov)
-{
-    put_be32(pb, 0x15); /* size */
-    put_tag(pb, "iods");
-    put_be32(pb, 0);    /* version & flags */
-    put_be16(pb, 0x1007);
-    put_byte(pb, 0);
-    put_be16(pb, 0x4fff);
-    put_be16(pb, 0xfffe);
-    put_be16(pb, 0x01ff);
+static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
+{
+    avio_wb32(pb, 0x15); /* size */
+    ffio_wfourcc(pb, "iods");
+    avio_wb32(pb, 0);    /* version & flags */
+    avio_wb16(pb, 0x1007);
+    avio_w8(pb, 0);
+    avio_wb16(pb, 0x4fff);
+    avio_wb16(pb, 0xfffe);
+    avio_wb16(pb, 0x01ff);
     return 0x15;
 }
 #endif
 
-static int mov_write_mvhd_tag(ByteIOContext *pb, MOVMuxContext *mov)
+static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
 {
     int maxTrackID = 1, i;
     int64_t maxTrackLenTemp, maxTrackLen = 0;
@@ -1309,96 +1395,96 @@ static int mov_write_mvhd_tag(ByteIOContext *pb, MOVMuxContext *mov)
     }
 
     version = maxTrackLen < UINT32_MAX ? 0 : 1;
-    (version == 1) ? put_be32(pb, 120) : put_be32(pb, 108); /* size */
-    put_tag(pb, "mvhd");
-    put_byte(pb, version);
-    put_be24(pb, 0); /* flags */
+    (version == 1) ? avio_wb32(pb, 120) : avio_wb32(pb, 108); /* size */
+    ffio_wfourcc(pb, "mvhd");
+    avio_w8(pb, version);
+    avio_wb24(pb, 0); /* flags */
     if (version == 1) {
-        put_be64(pb, mov->time);
-        put_be64(pb, mov->time);
+        avio_wb64(pb, mov->time);
+        avio_wb64(pb, mov->time);
     } else {
-        put_be32(pb, mov->time); /* creation time */
-        put_be32(pb, mov->time); /* modification time */
+        avio_wb32(pb, mov->time); /* creation time */
+        avio_wb32(pb, mov->time); /* modification time */
     }
-    put_be32(pb, MOV_TIMESCALE);
-    (version == 1) ? put_be64(pb, maxTrackLen) : put_be32(pb, maxTrackLen); /* duration of longest track */
+    avio_wb32(pb, MOV_TIMESCALE);
+    (version == 1) ? avio_wb64(pb, maxTrackLen) : avio_wb32(pb, maxTrackLen); /* duration of longest track */
 
-    put_be32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
-    put_be16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
-    put_be16(pb, 0); /* reserved */
-    put_be32(pb, 0); /* reserved */
-    put_be32(pb, 0); /* reserved */
+    avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
+    avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
+    avio_wb16(pb, 0); /* reserved */
+    avio_wb32(pb, 0); /* reserved */
+    avio_wb32(pb, 0); /* reserved */
 
     /* Matrix structure */
-    put_be32(pb, 0x00010000); /* reserved */
-    put_be32(pb, 0x0); /* reserved */
-    put_be32(pb, 0x0); /* reserved */
-    put_be32(pb, 0x0); /* reserved */
-    put_be32(pb, 0x00010000); /* reserved */
-    put_be32(pb, 0x0); /* reserved */
-    put_be32(pb, 0x0); /* reserved */
-    put_be32(pb, 0x0); /* reserved */
-    put_be32(pb, 0x40000000); /* reserved */
-
-    put_be32(pb, 0); /* reserved (preview time) */
-    put_be32(pb, 0); /* reserved (preview duration) */
-    put_be32(pb, 0); /* reserved (poster time) */
-    put_be32(pb, 0); /* reserved (selection time) */
-    put_be32(pb, 0); /* reserved (selection duration) */
-    put_be32(pb, 0); /* reserved (current time) */
-    put_be32(pb, maxTrackID+1); /* Next track id */
+    avio_wb32(pb, 0x00010000); /* reserved */
+    avio_wb32(pb, 0x0); /* reserved */
+    avio_wb32(pb, 0x0); /* reserved */
+    avio_wb32(pb, 0x0); /* reserved */
+    avio_wb32(pb, 0x00010000); /* reserved */
+    avio_wb32(pb, 0x0); /* reserved */
+    avio_wb32(pb, 0x0); /* reserved */
+    avio_wb32(pb, 0x0); /* reserved */
+    avio_wb32(pb, 0x40000000); /* reserved */
+
+    avio_wb32(pb, 0); /* reserved (preview time) */
+    avio_wb32(pb, 0); /* reserved (preview duration) */
+    avio_wb32(pb, 0); /* reserved (poster time) */
+    avio_wb32(pb, 0); /* reserved (selection time) */
+    avio_wb32(pb, 0); /* reserved (selection duration) */
+    avio_wb32(pb, 0); /* reserved (current time) */
+    avio_wb32(pb, maxTrackID+1); /* Next track id */
     return 0x6c;
 }
 
-static int mov_write_itunes_hdlr_tag(ByteIOContext *pb, MOVMuxContext *mov,
+static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
                                      AVFormatContext *s)
 {
-    put_be32(pb, 33); /* size */
-    put_tag(pb, "hdlr");
-    put_be32(pb, 0);
-    put_be32(pb, 0);
-    put_tag(pb, "mdir");
-    put_tag(pb, "appl");
-    put_be32(pb, 0);
-    put_be32(pb, 0);
-    put_byte(pb, 0);
+    avio_wb32(pb, 33); /* size */
+    ffio_wfourcc(pb, "hdlr");
+    avio_wb32(pb, 0);
+    avio_wb32(pb, 0);
+    ffio_wfourcc(pb, "mdir");
+    ffio_wfourcc(pb, "appl");
+    avio_wb32(pb, 0);
+    avio_wb32(pb, 0);
+    avio_w8(pb, 0);
     return 33;
 }
 
 /* helper function to write a data tag with the specified string as data */
-static int mov_write_string_data_tag(ByteIOContext *pb, const char *data, int lang, int long_style)
+static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
 {
     if(long_style){
         int size = 16 + strlen(data);
-        put_be32(pb, size); /* size */
-        put_tag(pb, "data");
-        put_be32(pb, 1);
-        put_be32(pb, 0);
-        put_buffer(pb, data, strlen(data));
+        avio_wb32(pb, size); /* size */
+        ffio_wfourcc(pb, "data");
+        avio_wb32(pb, 1);
+        avio_wb32(pb, 0);
+        avio_write(pb, data, strlen(data));
         return size;
     }else{
         if (!lang)
             lang = ff_mov_iso639_to_lang("und", 1);
-        put_be16(pb, strlen(data)); /* string length */
-        put_be16(pb, lang);
-        put_buffer(pb, data, strlen(data));
+        avio_wb16(pb, strlen(data)); /* string length */
+        avio_wb16(pb, lang);
+        avio_write(pb, data, strlen(data));
         return strlen(data) + 4;
     }
 }
 
-static int mov_write_string_tag(ByteIOContext *pb, const char *name, const char *value, int lang, int long_style){
+static int mov_write_string_tag(AVIOContext *pb, const char *name, const char *value, int lang, int long_style){
     int size = 0;
     if (value && value[0]) {
-        int64_t pos = url_ftell(pb);
-        put_be32(pb, 0); /* size */
-        put_tag(pb, name);
+        int64_t pos = avio_tell(pb);
+        avio_wb32(pb, 0); /* size */
+        ffio_wfourcc(pb, name);
         mov_write_string_data_tag(pb, value, lang, long_style);
         size= updateSize(pb, pos);
     }
     return size;
 }
 
-static int mov_write_string_metadata(AVFormatContext *s, ByteIOContext *pb,
+static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
                                      const char *name, const char *tag,
                                      int long_style)
 {
@@ -1423,34 +1509,34 @@ static int mov_write_string_metadata(AVFormatContext *s, ByteIOContext *pb,
 }
 
 /* iTunes track number */
-static int mov_write_trkn_tag(ByteIOContext *pb, MOVMuxContext *mov,
+static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
                               AVFormatContext *s)
 {
     AVMetadataTag *t = av_metadata_get(s->metadata, "track", NULL, 0);
     int size = 0, track = t ? atoi(t->value) : 0;
     if (track) {
-        put_be32(pb, 32); /* size */
-        put_tag(pb, "trkn");
-            put_be32(pb, 24); /* size */
-            put_tag(pb, "data");
-            put_be32(pb, 0);        // 8 bytes empty
-            put_be32(pb, 0);
-            put_be16(pb, 0);        // empty
-            put_be16(pb, track);    // track number
-            put_be16(pb, 0);        // total track number
-            put_be16(pb, 0);        // empty
+        avio_wb32(pb, 32); /* size */
+        ffio_wfourcc(pb, "trkn");
+            avio_wb32(pb, 24); /* size */
+            ffio_wfourcc(pb, "data");
+            avio_wb32(pb, 0);        // 8 bytes empty
+            avio_wb32(pb, 0);
+            avio_wb16(pb, 0);        // empty
+            avio_wb16(pb, track);    // track number
+            avio_wb16(pb, 0);        // total track number
+            avio_wb16(pb, 0);        // empty
         size = 32;
     }
     return size;
 }
 
 /* iTunes meta data list */
-static int mov_write_ilst_tag(ByteIOContext *pb, MOVMuxContext *mov,
+static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
                               AVFormatContext *s)
 {
-    int64_t pos = url_ftell(pb);
-    put_be32(pb, 0); /* size */
-    put_tag(pb, "ilst");
+    int64_t pos = avio_tell(pb);
+    avio_wb32(pb, 0); /* size */
+    ffio_wfourcc(pb, "ilst");
     mov_write_string_metadata(s, pb, "\251nam", "title"    , 1);
     mov_write_string_metadata(s, pb, "\251ART", "artist"   , 1);
     mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
@@ -1473,14 +1559,14 @@ static int mov_write_ilst_tag(ByteIOContext *pb, MOVMuxContext *mov,
 }
 
 /* iTunes meta data tag */
-static int mov_write_meta_tag(ByteIOContext *pb, MOVMuxContext *mov,
+static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
                               AVFormatContext *s)
 {
     int size = 0;
-    int64_t pos = url_ftell(pb);
-    put_be32(pb, 0); /* size */
-    put_tag(pb, "meta");
-    put_be32(pb, 0);
+    int64_t pos = avio_tell(pb);
+    avio_wb32(pb, 0); /* size */
+    ffio_wfourcc(pb, "meta");
+    avio_wb32(pb, 0);
     mov_write_itunes_hdlr_tag(pb, mov, s);
     mov_write_ilst_tag(pb, mov, s);
     size = updateSize(pb, pos);
@@ -1498,14 +1584,14 @@ static int utf8len(const uint8_t *b)
     return len;
 }
 
-static int ascii_to_wc(ByteIOContext *pb, const uint8_t *b)
+static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
 {
     int val;
     while(*b){
         GET_UTF8(val, *b++, return -1;)
-        put_be16(pb, val);
+        avio_wb16(pb, val);
     }
-    put_be16(pb, 0x00);
+    avio_wb16(pb, 0x00);
     return 0;
 }
 
@@ -1514,58 +1600,58 @@ static uint16_t language_code(const char *str)
     return (((str[0]-0x60) & 0x1F) << 10) + (((str[1]-0x60) & 0x1F) << 5) + ((str[2]-0x60) & 0x1F);
 }
 
-static int mov_write_3gp_udta_tag(ByteIOContext *pb, AVFormatContext *s,
+static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
                                   const char *tag, const char *str)
 {
-    int64_t pos = url_ftell(pb);
+    int64_t pos = avio_tell(pb);
     AVMetadataTag *t = av_metadata_get(s->metadata, str, NULL, 0);
     if (!t || !utf8len(t->value))
         return 0;
-    put_be32(pb, 0);   /* size */
-    put_tag (pb, tag); /* type */
-    put_be32(pb, 0);   /* version + flags */
+    avio_wb32(pb, 0);   /* size */
+    ffio_wfourcc(pb, tag); /* type */
+    avio_wb32(pb, 0);   /* version + flags */
     if (!strcmp(tag, "yrrc"))
-        put_be16(pb, atoi(t->value));
+        avio_wb16(pb, atoi(t->value));
     else {
-        put_be16(pb, language_code("eng")); /* language */
-        put_buffer(pb, t->value, strlen(t->value)+1); /* UTF8 string value */
+        avio_wb16(pb, language_code("eng")); /* language */
+        avio_write(pb, t->value, strlen(t->value)+1); /* UTF8 string value */
         if (!strcmp(tag, "albm") &&
-            (t = av_metadata_get(s->metadata, "date", NULL, 0)))
-            put_byte(pb, atoi(t->value));
+            (t = av_metadata_get(s->metadata, "track", NULL, 0)))
+            avio_w8(pb, atoi(t->value));
     }
     return updateSize(pb, pos);
 }
 
-static int mov_write_chpl_tag(ByteIOContext *pb, AVFormatContext *s)
+static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
 {
-    int64_t pos = url_ftell(pb);
+    int64_t pos = avio_tell(pb);
     int i, nb_chapters = FFMIN(s->nb_chapters, 255);
 
-    put_be32(pb, 0);            // size
-    put_tag (pb, "chpl");
-    put_be32(pb, 0x01000000);   // version + flags
-    put_be32(pb, 0);            // unknown
-    put_byte(pb, nb_chapters);
+    avio_wb32(pb, 0);            // size
+    ffio_wfourcc(pb, "chpl");
+    avio_wb32(pb, 0x01000000);   // version + flags
+    avio_wb32(pb, 0);            // unknown
+    avio_w8(pb, nb_chapters);
 
     for (i = 0; i < nb_chapters; i++) {
         AVChapter *c = s->chapters[i];
         AVMetadataTag *t;
-        put_be64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
+        avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
 
         if ((t = av_metadata_get(c->metadata, "title", NULL, 0))) {
             int len = FFMIN(strlen(t->value), 255);
-            put_byte(pb, len);
-            put_buffer(pb, t->value, len);
+            avio_w8(pb, len);
+            avio_write(pb, t->value, len);
         } else
-            put_byte(pb, 0);
+            avio_w8(pb, 0);
     }
     return updateSize(pb, pos);
 }
 
-static int mov_write_udta_tag(ByteIOContext *pb, MOVMuxContext *mov,
+static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
                               AVFormatContext *s)
 {
-    ByteIOContext *pb_buf;
+    AVIOContext *pb_buf;
     int i, ret, size;
     uint8_t *buf;
 
@@ -1574,7 +1660,7 @@ static int mov_write_udta_tag(ByteIOContext *pb, MOVMuxContext *mov,
             return 0;
         }
 
-    ret = url_open_dyn_buf(&pb_buf);
+    ret = avio_open_dyn_buf(&pb_buf);
     if(ret < 0)
         return ret;
 
@@ -1588,11 +1674,12 @@ static int mov_write_udta_tag(ByteIOContext *pb, MOVMuxContext *mov,
             mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
             mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
         } else if (mov->mode == MODE_MOV) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4
+            mov_write_string_metadata(s, pb_buf, "\251ART", "artist"     , 0);
             mov_write_string_metadata(s, pb_buf, "\251nam", "title"      , 0);
             mov_write_string_metadata(s, pb_buf, "\251aut", "author"     , 0);
             mov_write_string_metadata(s, pb_buf, "\251alb", "album"      , 0);
             mov_write_string_metadata(s, pb_buf, "\251day", "date"       , 0);
-            mov_write_string_tag(pb_buf, "\251enc", LIBAVFORMAT_IDENT, 0, 0);
+            mov_write_string_metadata(s, pb_buf, "\251swr", "encoder"    , 0);
             mov_write_string_metadata(s, pb_buf, "\251des", "comment"    , 0);
             mov_write_string_metadata(s, pb_buf, "\251gen", "genre"      , 0);
             mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright"  , 0);
@@ -1604,54 +1691,54 @@ static int mov_write_udta_tag(ByteIOContext *pb, MOVMuxContext *mov,
         if (s->nb_chapters)
             mov_write_chpl_tag(pb_buf, s);
 
-    if ((size = url_close_dyn_buf(pb_buf, &buf)) > 0) {
-        put_be32(pb, size+8);
-        put_tag(pb, "udta");
-        put_buffer(pb, buf, size);
-        av_free(buf);
+    if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
+        avio_wb32(pb, size+8);
+        ffio_wfourcc(pb, "udta");
+        avio_write(pb, buf, size);
     }
+    av_free(buf);
 
     return 0;
 }
 
-static void mov_write_psp_udta_tag(ByteIOContext *pb,
+static void mov_write_psp_udta_tag(AVIOContext *pb,
                                   const char *str, const char *lang, int type)
 {
     int len = utf8len(str)+1;
     if(len<=0)
         return;
-    put_be16(pb, len*2+10);            /* size */
-    put_be32(pb, type);                /* type */
-    put_be16(pb, language_code(lang)); /* language */
-    put_be16(pb, 0x01);                /* ? */
+    avio_wb16(pb, len*2+10);            /* size */
+    avio_wb32(pb, type);                /* type */
+    avio_wb16(pb, language_code(lang)); /* language */
+    avio_wb16(pb, 0x01);                /* ? */
     ascii_to_wc(pb, str);
 }
 
-static int mov_write_uuidusmt_tag(ByteIOContext *pb, AVFormatContext *s)
+static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
 {
     AVMetadataTag *title = av_metadata_get(s->metadata, "title", NULL, 0);
     int64_t pos, pos2;
 
     if (title) {
-        pos = url_ftell(pb);
-        put_be32(pb, 0); /* size placeholder*/
-        put_tag(pb, "uuid");
-        put_tag(pb, "USMT");
-        put_be32(pb, 0x21d24fce); /* 96 bit UUID */
-        put_be32(pb, 0xbb88695c);
-        put_be32(pb, 0xfac9c740);
-
-        pos2 = url_ftell(pb);
-        put_be32(pb, 0); /* size placeholder*/
-        put_tag(pb, "MTDT");
-        put_be16(pb, 4);
+        pos = avio_tell(pb);
+        avio_wb32(pb, 0); /* size placeholder*/
+        ffio_wfourcc(pb, "uuid");
+        ffio_wfourcc(pb, "USMT");
+        avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
+        avio_wb32(pb, 0xbb88695c);
+        avio_wb32(pb, 0xfac9c740);
+
+        pos2 = avio_tell(pb);
+        avio_wb32(pb, 0); /* size placeholder*/
+        ffio_wfourcc(pb, "MTDT");
+        avio_wb16(pb, 4);
 
         // ?
-        put_be16(pb, 0x0C);                 /* size */
-        put_be32(pb, 0x0B);                 /* type */
-        put_be16(pb, language_code("und")); /* language */
-        put_be16(pb, 0x0);                  /* ? */
-        put_be16(pb, 0x021C);               /* data */
+        avio_wb16(pb, 0x0C);                 /* size */
+        avio_wb32(pb, 0x0B);                 /* type */
+        avio_wb16(pb, language_code("und")); /* language */
+        avio_wb16(pb, 0x0);                  /* ? */
+        avio_wb16(pb, 0x021C);               /* data */
 
         mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT,      "eng", 0x04);
         mov_write_psp_udta_tag(pb, title->value,          "eng", 0x01);
@@ -1665,13 +1752,13 @@ static int mov_write_uuidusmt_tag(ByteIOContext *pb, AVFormatContext *s)
     return 0;
 }
 
-static int mov_write_moov_tag(ByteIOContext *pb, MOVMuxContext *mov,
+static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
                               AVFormatContext *s)
 {
     int i;
-    int64_t pos = url_ftell(pb);
-    put_be32(pb, 0); /* size placeholder*/
-    put_tag(pb, "moov");
+    int64_t pos = avio_tell(pb);
+    avio_wb32(pb, 0); /* size placeholder*/
+    ffio_wfourcc(pb, "moov");
 
     for (i=0; i<mov->nb_streams; i++) {
         if(mov->tracks[i].entry <= 0) continue;
@@ -1709,22 +1796,22 @@ static int mov_write_moov_tag(ByteIOContext *pb, MOVMuxContext *mov,
     return updateSize(pb, pos);
 }
 
-static int mov_write_mdat_tag(ByteIOContext *pb, MOVMuxContext *mov)
+static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
 {
-    put_be32(pb, 8);    // placeholder for extended size field (64 bit)
-    put_tag(pb, mov->mode == MODE_MOV ? "wide" : "free");
+    avio_wb32(pb, 8);    // placeholder for extended size field (64 bit)
+    ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
 
-    mov->mdat_pos = url_ftell(pb);
-    put_be32(pb, 0); /* size placeholder*/
-    put_tag(pb, "mdat");
+    mov->mdat_pos = avio_tell(pb);
+    avio_wb32(pb, 0); /* size placeholder*/
+    ffio_wfourcc(pb, "mdat");
     return 0;
 }
 
 /* TODO: This needs to be more general */
-static int mov_write_ftyp_tag(ByteIOContext *pb, AVFormatContext *s)
+static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
 {
     MOVMuxContext *mov = s->priv_data;
-    int64_t pos = url_ftell(pb);
+    int64_t pos = avio_tell(pb);
     int has_h264 = 0, has_video = 0;
     int minor = 0x200;
     int i;
@@ -1737,47 +1824,47 @@ static int mov_write_ftyp_tag(ByteIOContext *pb, AVFormatContext *s)
             has_h264 = 1;
     }
 
-    put_be32(pb, 0); /* size */
-    put_tag(pb, "ftyp");
+    avio_wb32(pb, 0); /* size */
+    ffio_wfourcc(pb, "ftyp");
 
     if (mov->mode == MODE_3GP) {
-        put_tag(pb, has_h264 ? "3gp6"  : "3gp4");
+        ffio_wfourcc(pb, has_h264 ? "3gp6"  : "3gp4");
         minor =     has_h264 ?   0x100 :   0x200;
     } else if (mov->mode & MODE_3G2) {
-        put_tag(pb, has_h264 ? "3g2b"  : "3g2a");
+        ffio_wfourcc(pb, has_h264 ? "3g2b"  : "3g2a");
         minor =     has_h264 ? 0x20000 : 0x10000;
     }else if (mov->mode == MODE_PSP)
-        put_tag(pb, "MSNV");
+        ffio_wfourcc(pb, "MSNV");
     else if (mov->mode == MODE_MP4)
-        put_tag(pb, "isom");
+        ffio_wfourcc(pb, "isom");
     else if (mov->mode == MODE_IPOD)
-        put_tag(pb, has_video ? "M4V ":"M4A ");
+        ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
     else
-        put_tag(pb, "qt  ");
+        ffio_wfourcc(pb, "qt  ");
 
-    put_be32(pb, minor);
+    avio_wb32(pb, minor);
 
     if(mov->mode == MODE_MOV)
-        put_tag(pb, "qt  ");
+        ffio_wfourcc(pb, "qt  ");
     else{
-        put_tag(pb, "isom");
-        put_tag(pb, "iso2");
+        ffio_wfourcc(pb, "isom");
+        ffio_wfourcc(pb, "iso2");
         if(has_h264)
-            put_tag(pb, "avc1");
+            ffio_wfourcc(pb, "avc1");
     }
 
     if (mov->mode == MODE_3GP)
-        put_tag(pb, has_h264 ? "3gp6":"3gp4");
+        ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
     else if (mov->mode & MODE_3G2)
-        put_tag(pb, has_h264 ? "3g2b":"3g2a");
+        ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
     else if (mov->mode == MODE_PSP)
-        put_tag(pb, "MSNV");
+        ffio_wfourcc(pb, "MSNV");
     else if (mov->mode == MODE_MP4)
-        put_tag(pb, "mp41");
+        ffio_wfourcc(pb, "mp41");
     return updateSize(pb, pos);
 }
 
-static void mov_write_uuidprof_tag(ByteIOContext *pb, AVFormatContext *s)
+static void mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
 {
     AVCodecContext *VideoCodec = s->streams[0]->codec;
     AVCodecContext *AudioCodec = s->streams[1]->codec;
@@ -1786,56 +1873,56 @@ static void mov_write_uuidprof_tag(ByteIOContext *pb, AVFormatContext *s)
     int audio_kbitrate= AudioCodec->bit_rate / 1000;
     int video_kbitrate= FFMIN(VideoCodec->bit_rate / 1000, 800 - audio_kbitrate);
 
-    put_be32(pb, 0x94); /* size */
-    put_tag(pb, "uuid");
-    put_tag(pb, "PROF");
-
-    put_be32(pb, 0x21d24fce); /* 96 bit UUID */
-    put_be32(pb, 0xbb88695c);
-    put_be32(pb, 0xfac9c740);
-
-    put_be32(pb, 0x0);  /* ? */
-    put_be32(pb, 0x3);  /* 3 sections ? */
-
-    put_be32(pb, 0x14); /* size */
-    put_tag(pb, "FPRF");
-    put_be32(pb, 0x0);  /* ? */
-    put_be32(pb, 0x0);  /* ? */
-    put_be32(pb, 0x0);  /* ? */
-
-    put_be32(pb, 0x2c);  /* size */
-    put_tag(pb, "APRF");   /* audio */
-    put_be32(pb, 0x0);
-    put_be32(pb, 0x2);   /* TrackID */
-    put_tag(pb, "mp4a");
-    put_be32(pb, 0x20f);
-    put_be32(pb, 0x0);
-    put_be32(pb, audio_kbitrate);
-    put_be32(pb, audio_kbitrate);
-    put_be32(pb, AudioRate);
-    put_be32(pb, AudioCodec->channels);
-
-    put_be32(pb, 0x34);  /* size */
-    put_tag(pb, "VPRF");   /* video */
-    put_be32(pb, 0x0);
-    put_be32(pb, 0x1);    /* TrackID */
+    avio_wb32(pb, 0x94); /* size */
+    ffio_wfourcc(pb, "uuid");
+    ffio_wfourcc(pb, "PROF");
+
+    avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
+    avio_wb32(pb, 0xbb88695c);
+    avio_wb32(pb, 0xfac9c740);
+
+    avio_wb32(pb, 0x0);  /* ? */
+    avio_wb32(pb, 0x3);  /* 3 sections ? */
+
+    avio_wb32(pb, 0x14); /* size */
+    ffio_wfourcc(pb, "FPRF");
+    avio_wb32(pb, 0x0);  /* ? */
+    avio_wb32(pb, 0x0);  /* ? */
+    avio_wb32(pb, 0x0);  /* ? */
+
+    avio_wb32(pb, 0x2c);  /* size */
+    ffio_wfourcc(pb, "APRF");/* audio */
+    avio_wb32(pb, 0x0);
+    avio_wb32(pb, 0x2);   /* TrackID */
+    ffio_wfourcc(pb, "mp4a");
+    avio_wb32(pb, 0x20f);
+    avio_wb32(pb, 0x0);
+    avio_wb32(pb, audio_kbitrate);
+    avio_wb32(pb, audio_kbitrate);
+    avio_wb32(pb, AudioRate);
+    avio_wb32(pb, AudioCodec->channels);
+
+    avio_wb32(pb, 0x34);  /* size */
+    ffio_wfourcc(pb, "VPRF");   /* video */
+    avio_wb32(pb, 0x0);
+    avio_wb32(pb, 0x1);    /* TrackID */
     if (VideoCodec->codec_id == CODEC_ID_H264) {
-        put_tag(pb, "avc1");
-        put_be16(pb, 0x014D);
-        put_be16(pb, 0x0015);
+        ffio_wfourcc(pb, "avc1");
+        avio_wb16(pb, 0x014D);
+        avio_wb16(pb, 0x0015);
     } else {
-        put_tag(pb, "mp4v");
-        put_be16(pb, 0x0000);
-        put_be16(pb, 0x0103);
+        ffio_wfourcc(pb, "mp4v");
+        avio_wb16(pb, 0x0000);
+        avio_wb16(pb, 0x0103);
     }
-    put_be32(pb, 0x0);
-    put_be32(pb, video_kbitrate);
-    put_be32(pb, video_kbitrate);
-    put_be32(pb, FrameRate);
-    put_be32(pb, FrameRate);
-    put_be16(pb, VideoCodec->width);
-    put_be16(pb, VideoCodec->height);
-    put_be32(pb, 0x010001); /* ? */
+    avio_wb32(pb, 0x0);
+    avio_wb32(pb, video_kbitrate);
+    avio_wb32(pb, video_kbitrate);
+    avio_wb32(pb, FrameRate);
+    avio_wb32(pb, FrameRate);
+    avio_wb16(pb, VideoCodec->width);
+    avio_wb16(pb, VideoCodec->height);
+    avio_wb32(pb, 0x010001); /* ? */
 }
 
 static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
@@ -1862,13 +1949,13 @@ static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
 int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
 {
     MOVMuxContext *mov = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     MOVTrack *trk = &mov->tracks[pkt->stream_index];
     AVCodecContext *enc = trk->enc;
     unsigned int samplesInChunk = 0;
     int size= pkt->size;
 
-    if (url_is_streamed(s->pb)) return 0; /* Can't handle that */
+    if (!s->pb->seekable) return 0; /* Can't handle that */
     if (!size) return 0; /* Discard 0 sized packets */
 
     if (enc->codec_id == CODEC_ID_AMR_NB) {
@@ -1885,6 +1972,9 @@ int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
             av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
             return -1;
         }
+    } else if (enc->codec_id == CODEC_ID_ADPCM_MS ||
+               enc->codec_id == CODEC_ID_ADPCM_IMA_WAV) {
+        samplesInChunk = enc->frame_size;
     } else if (trk->sampleSize)
         samplesInChunk = size/trk->sampleSize;
     else
@@ -1902,7 +1992,7 @@ int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
         /* nal reformating needed */
         size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
     } else {
-        put_buffer(pb, pkt->data, size);
+        avio_write(pb, pkt->data, size);
     }
 
     if ((enc->codec_id == CODEC_ID_DNXHD ||
@@ -1921,7 +2011,7 @@ int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
             return -1;
     }
 
-    trk->cluster[trk->entry].pos = url_ftell(pb) - size;
+    trk->cluster[trk->entry].pos = avio_tell(pb) - size;
     trk->cluster[trk->entry].samplesInChunk = samplesInChunk;
     trk->cluster[trk->entry].size = size;
     trk->cluster[trk->entry].entries = samplesInChunk;
@@ -1937,7 +2027,8 @@ int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
     trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
     trk->cluster[trk->entry].flags = 0;
     if (pkt->flags & AV_PKT_FLAG_KEY) {
-        if (mov->mode == MODE_MOV && enc->codec_id == CODEC_ID_MPEG2VIDEO) {
+        if (mov->mode == MODE_MOV && enc->codec_id == CODEC_ID_MPEG2VIDEO &&
+            trk->entry > 0) { // force sync sample for the first key frame
             mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
             if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
                 trk->flags |= MOV_TRACK_STPS;
@@ -1951,7 +2042,7 @@ int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
     trk->sampleCount += samplesInChunk;
     mov->mdat_size += size;
 
-    put_flush_packet(pb);
+    avio_flush(pb);
 
     if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
         ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry);
@@ -1995,11 +2086,11 @@ static void mov_create_chapter_track(AVFormatContext *s, int tracknum)
 
 static int mov_write_header(AVFormatContext *s)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     MOVMuxContext *mov = s->priv_data;
     int i, hint_track = 0;
 
-    if (url_is_streamed(s->pb)) {
+    if (!s->pb->seekable) {
         av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
         return -1;
     }
@@ -2084,6 +2175,13 @@ static int mov_write_header(AVFormatContext *s)
             if(!st->codec->frame_size && !av_get_bits_per_sample(st->codec->codec_id)) {
                 av_log(s, AV_LOG_ERROR, "track %d: codec frame size is not set\n", i);
                 goto error;
+            }else if(st->codec->codec_id == CODEC_ID_ADPCM_MS ||
+                     st->codec->codec_id == CODEC_ID_ADPCM_IMA_WAV){
+                if (!st->codec->block_align) {
+                    av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
+                    goto error;
+                }
+                track->sampleSize = st->codec->block_align;
             }else if(st->codec->frame_size > 1){ /* assume compressed audio */
                 track->audio_vbr = 1;
             }else{
@@ -2129,7 +2227,7 @@ static int mov_write_header(AVFormatContext *s)
         }
     }
 
-    put_flush_packet(pb);
+    avio_flush(pb);
 
     return 0;
  error:
@@ -2140,24 +2238,24 @@ static int mov_write_header(AVFormatContext *s)
 static int mov_write_trailer(AVFormatContext *s)
 {
     MOVMuxContext *mov = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int res = 0;
     int i;
 
-    int64_t moov_pos = url_ftell(pb);
+    int64_t moov_pos = avio_tell(pb);
 
     /* Write size of mdat tag */
     if (mov->mdat_size+8 <= UINT32_MAX) {
-        url_fseek(pb, mov->mdat_pos, SEEK_SET);
-        put_be32(pb, mov->mdat_size+8);
+        avio_seek(pb, mov->mdat_pos, SEEK_SET);
+        avio_wb32(pb, mov->mdat_size+8);
     } else {
         /* overwrite 'wide' placeholder atom */
-        url_fseek(pb, mov->mdat_pos - 8, SEEK_SET);
-        put_be32(pb, 1); /* special value: real atom size will be 64 bit value after tag field */
-        put_tag(pb, "mdat");
-        put_be64(pb, mov->mdat_size+16);
+        avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
+        avio_wb32(pb, 1); /* special value: real atom size will be 64 bit value after tag field */
+        ffio_wfourcc(pb, "mdat");
+        avio_wb64(pb, mov->mdat_size+16);
     }
-    url_fseek(pb, moov_pos, SEEK_SET);
+    avio_seek(pb, moov_pos, SEEK_SET);
 
     mov_write_moov_tag(pb, mov, s);
 
@@ -2173,7 +2271,7 @@ static int mov_write_trailer(AVFormatContext *s)
 
     }
 
-    put_flush_packet(pb);
+    avio_flush(pb);
 
     av_freep(&mov->tracks);
 
@@ -2181,7 +2279,7 @@ static int mov_write_trailer(AVFormatContext *s)
 }
 
 #if CONFIG_MOV_MUXER
-AVOutputFormat mov_muxer = {
+AVOutputFormat ff_mov_muxer = {
     "mov",
     NULL_IF_CONFIG_SMALL("MOV format"),
     NULL,
@@ -2192,12 +2290,12 @@ AVOutputFormat mov_muxer = {
     mov_write_header,
     ff_mov_write_packet,
     mov_write_trailer,
-    .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
+    .flags = AVFMT_GLOBALHEADER,
     .codec_tag = (const AVCodecTag* const []){codec_movvideo_tags, codec_movaudio_tags, 0},
 };
 #endif
 #if CONFIG_TGP_MUXER
-AVOutputFormat tgp_muxer = {
+AVOutputFormat ff_tgp_muxer = {
     "3gp",
     NULL_IF_CONFIG_SMALL("3GP format"),
     NULL,
@@ -2213,7 +2311,7 @@ AVOutputFormat tgp_muxer = {
 };
 #endif
 #if CONFIG_MP4_MUXER
-AVOutputFormat mp4_muxer = {
+AVOutputFormat ff_mp4_muxer = {
     "mp4",
     NULL_IF_CONFIG_SMALL("MP4 format"),
     "application/mp4",
@@ -2224,12 +2322,12 @@ AVOutputFormat mp4_muxer = {
     mov_write_header,
     ff_mov_write_packet,
     mov_write_trailer,
-    .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
+    .flags = AVFMT_GLOBALHEADER,
     .codec_tag = (const AVCodecTag* const []){ff_mp4_obj_type, 0},
 };
 #endif
 #if CONFIG_PSP_MUXER
-AVOutputFormat psp_muxer = {
+AVOutputFormat ff_psp_muxer = {
     "psp",
     NULL_IF_CONFIG_SMALL("PSP MP4 format"),
     NULL,
@@ -2245,7 +2343,7 @@ AVOutputFormat psp_muxer = {
 };
 #endif
 #if CONFIG_TG2_MUXER
-AVOutputFormat tg2_muxer = {
+AVOutputFormat ff_tg2_muxer = {
     "3g2",
     NULL_IF_CONFIG_SMALL("3GP2 format"),
     NULL,
@@ -2261,7 +2359,7 @@ AVOutputFormat tg2_muxer = {
 };
 #endif
 #if CONFIG_IPOD_MUXER
-AVOutputFormat ipod_muxer = {
+AVOutputFormat ff_ipod_muxer = {
     "ipod",
     NULL_IF_CONFIG_SMALL("iPod H.264 MP4 format"),
     "application/mp4",
diff --git a/libavformat/movenc.h b/libavformat/movenc.h
index 182c5ed..0cc1eb8 100644
--- a/libavformat/movenc.h
+++ b/libavformat/movenc.h
@@ -4,20 +4,20 @@
  * Copyright (c) 2004 Gildas Bazin <gbazin at videolan dot org>
  * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavformat/movenchint.c b/libavformat/movenchint.c
index d90ac67..6157146 100644
--- a/libavformat/movenchint.c
+++ b/libavformat/movenchint.c
@@ -2,25 +2,28 @@
  * MOV, 3GP, MP4 muxer RTP hinting
  * Copyright (c) 2010 Martin Storsjo
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "movenc.h"
 #include "libavutil/intreadwrite.h"
+#include "internal.h"
+#include "rtpenc_chain.h"
+#include "avio_internal.h"
 
 int ff_mov_init_hinting(AVFormatContext *s, int index, int src_index)
 {
@@ -29,44 +32,20 @@ int ff_mov_init_hinting(AVFormatContext *s, int index, int src_index)
     MOVTrack *src_track = &mov->tracks[src_index];
     AVStream *src_st    = s->streams[src_index];
     int ret = AVERROR(ENOMEM);
-    AVOutputFormat *rtp_format = av_guess_format("rtp", NULL, NULL);
 
     track->tag = MKTAG('r','t','p',' ');
     track->src_track = src_index;
 
-    if (!rtp_format) {
-        ret = AVERROR(ENOENT);
-        goto fail;
-    }
-
     track->enc = avcodec_alloc_context();
     if (!track->enc)
         goto fail;
     track->enc->codec_type = AVMEDIA_TYPE_DATA;
     track->enc->codec_tag  = track->tag;
 
-    track->rtp_ctx = avformat_alloc_context();
+    track->rtp_ctx = ff_rtp_chain_mux_open(s, src_st, NULL,
+                                           RTP_MAX_PACKET_SIZE);
     if (!track->rtp_ctx)
         goto fail;
-    track->rtp_ctx->oformat = rtp_format;
-    if (!av_new_stream(track->rtp_ctx, 0))
-        goto fail;
-
-    /* Copy stream parameters */
-    track->rtp_ctx->streams[0]->sample_aspect_ratio =
-                        src_st->sample_aspect_ratio;
-
-    /* Remove the allocated codec context, link to the original one
-     * instead, to give the rtp muxer access to codec parameters. */
-    av_free(track->rtp_ctx->streams[0]->codec);
-    track->rtp_ctx->streams[0]->codec = src_st->codec;
-
-    if ((ret = url_open_dyn_packet_buf(&track->rtp_ctx->pb,
-                                       RTP_MAX_PACKET_SIZE)) < 0)
-        goto fail;
-    ret = av_write_header(track->rtp_ctx);
-    if (ret)
-        goto fail;
 
     /* Copy the RTP AVStream timebase back to the hint AVStream */
     track->timescale = track->rtp_ctx->streams[0]->time_base.den;
@@ -78,22 +57,8 @@ int ff_mov_init_hinting(AVFormatContext *s, int index, int src_index)
 fail:
     av_log(s, AV_LOG_WARNING,
            "Unable to initialize hinting of stream %d\n", src_index);
-    if (track->rtp_ctx && track->rtp_ctx->pb) {
-        uint8_t *buf;
-        url_close_dyn_buf(track->rtp_ctx->pb, &buf);
-        av_free(buf);
-    }
-    if (track->rtp_ctx && track->rtp_ctx->streams[0]) {
-        av_metadata_free(&track->rtp_ctx->streams[0]->metadata);
-        av_free(track->rtp_ctx->streams[0]);
-    }
-    if (track->rtp_ctx) {
-        av_metadata_free(&track->rtp_ctx->metadata);
-        av_free(track->rtp_ctx->priv_data);
-        av_freep(&track->rtp_ctx);
-    }
     av_freep(&track->enc);
-    /* Set a default timescale, to avoid crashes in dump_format */
+    /* Set a default timescale, to avoid crashes in av_dump_format */
     track->timescale = 90000;
     return ret;
 }
@@ -281,40 +246,40 @@ static int find_sample_match(const uint8_t *data, int len,
 }
 
 static void output_immediate(const uint8_t *data, int size,
-                             ByteIOContext *out, int *entries)
+                             AVIOContext *out, int *entries)
 {
     while (size > 0) {
         int len = size;
         if (len > 14)
             len = 14;
-        put_byte(out, 1); /* immediate constructor */
-        put_byte(out, len); /* amount of valid data */
-        put_buffer(out, data, len);
+        avio_w8(out, 1); /* immediate constructor */
+        avio_w8(out, len); /* amount of valid data */
+        avio_write(out, data, len);
         data += len;
         size -= len;
 
         for (; len < 14; len++)
-            put_byte(out, 0);
+            avio_w8(out, 0);
 
         (*entries)++;
     }
 }
 
-static void output_match(ByteIOContext *out, int match_sample,
+static void output_match(AVIOContext *out, int match_sample,
                          int match_offset, int match_len, int *entries)
 {
-    put_byte(out, 2); /* sample constructor */
-    put_byte(out, 0); /* track reference */
-    put_be16(out, match_len);
-    put_be32(out, match_sample);
-    put_be32(out, match_offset);
-    put_be16(out, 1); /* bytes per block */
-    put_be16(out, 1); /* samples per block */
+    avio_w8(out, 2); /* sample constructor */
+    avio_w8(out, 0); /* track reference */
+    avio_wb16(out, match_len);
+    avio_wb32(out, match_sample);
+    avio_wb32(out, match_offset);
+    avio_wb16(out, 1); /* bytes per block */
+    avio_wb16(out, 1); /* samples per block */
     (*entries)++;
 }
 
 static void describe_payload(const uint8_t *data, int size,
-                             ByteIOContext *out, int *entries,
+                             AVIOContext *out, int *entries,
                              HintSampleQueue *queue)
 {
     /* Describe the payload using different constructors */
@@ -345,17 +310,17 @@ static void describe_payload(const uint8_t *data, int size,
  * @param pts pointer where the timestamp for the written RTP hint is stored
  * @return the number of RTP packets in the written hint
  */
-static int write_hint_packets(ByteIOContext *out, const uint8_t *data,
+static int write_hint_packets(AVIOContext *out, const uint8_t *data,
                               int size, MOVTrack *trk, int64_t *pts)
 {
     int64_t curpos;
     int64_t count_pos, entries_pos;
     int count = 0, entries;
 
-    count_pos = url_ftell(out);
+    count_pos = avio_tell(out);
     /* RTPsample header */
-    put_be16(out, 0); /* packet count */
-    put_be16(out, 0); /* reserved */
+    avio_wb16(out, 0); /* packet count */
+    avio_wb16(out, 0); /* reserved */
 
     while (size > 4) {
         uint32_t packet_len = AV_RB32(data);
@@ -390,12 +355,12 @@ static int write_hint_packets(ByteIOContext *out, const uint8_t *data,
 
         count++;
         /* RTPpacket header */
-        put_be32(out, 0); /* relative_time */
-        put_buffer(out, data, 2); /* RTP header */
-        put_be16(out, seq); /* RTPsequenceseed */
-        put_be16(out, 0); /* reserved + flags */
-        entries_pos = url_ftell(out);
-        put_be16(out, 0); /* entry count */
+        avio_wb32(out, 0); /* relative_time */
+        avio_write(out, data, 2); /* RTP header */
+        avio_wb16(out, seq); /* RTPsequenceseed */
+        avio_wb16(out, 0); /* reserved + flags */
+        entries_pos = avio_tell(out);
+        avio_wb16(out, 0); /* entry count */
 
         data += 12;
         size -= 12;
@@ -407,16 +372,16 @@ static int write_hint_packets(ByteIOContext *out, const uint8_t *data,
         data += packet_len;
         size -= packet_len;
 
-        curpos = url_ftell(out);
-        url_fseek(out, entries_pos, SEEK_SET);
-        put_be16(out, entries);
-        url_fseek(out, curpos, SEEK_SET);
+        curpos = avio_tell(out);
+        avio_seek(out, entries_pos, SEEK_SET);
+        avio_wb16(out, entries);
+        avio_seek(out, curpos, SEEK_SET);
     }
 
-    curpos = url_ftell(out);
-    url_fseek(out, count_pos, SEEK_SET);
-    put_be16(out, count);
-    url_fseek(out, curpos, SEEK_SET);
+    curpos = avio_tell(out);
+    avio_seek(out, count_pos, SEEK_SET);
+    avio_wb16(out, count);
+    avio_seek(out, curpos, SEEK_SET);
     return count;
 }
 
@@ -428,9 +393,8 @@ int ff_mov_add_hinted_packet(AVFormatContext *s, AVPacket *pkt,
     AVFormatContext *rtp_ctx = trk->rtp_ctx;
     uint8_t *buf = NULL;
     int size;
-    ByteIOContext *hintbuf = NULL;
+    AVIOContext *hintbuf = NULL;
     AVPacket hint_pkt;
-    AVPacket local_pkt;
     int ret = 0, count;
 
     if (!rtp_ctx)
@@ -441,20 +405,12 @@ int ff_mov_add_hinted_packet(AVFormatContext *s, AVPacket *pkt,
     sample_queue_push(&trk->sample_queue, pkt, sample);
 
     /* Feed the packet to the RTP muxer */
-    local_pkt = *pkt;
-    local_pkt.stream_index = 0;
-    local_pkt.pts = av_rescale_q(pkt->pts,
-        s->streams[pkt->stream_index]->time_base,
-        rtp_ctx->streams[0]->time_base);
-    local_pkt.dts = av_rescale_q(pkt->dts,
-        s->streams[pkt->stream_index]->time_base,
-        rtp_ctx->streams[0]->time_base);
-    av_write_frame(rtp_ctx, &local_pkt);
+    ff_write_chained(rtp_ctx, 0, pkt, s);
 
     /* Fetch the output from the RTP muxer, open a new output buffer
      * for next time. */
-    size = url_close_dyn_buf(rtp_ctx->pb, &buf);
-    if ((ret = url_open_dyn_packet_buf(&rtp_ctx->pb,
+    size = avio_close_dyn_buf(rtp_ctx->pb, &buf);
+    if ((ret = ffio_open_dyn_packet_buf(&rtp_ctx->pb,
                                        RTP_MAX_PACKET_SIZE)) < 0)
         goto done;
 
@@ -462,14 +418,14 @@ int ff_mov_add_hinted_packet(AVFormatContext *s, AVPacket *pkt,
         goto done;
 
     /* Open a buffer for writing the hint */
-    if ((ret = url_open_dyn_buf(&hintbuf)) < 0)
+    if ((ret = avio_open_dyn_buf(&hintbuf)) < 0)
         goto done;
     av_init_packet(&hint_pkt);
     count = write_hint_packets(hintbuf, buf, size, trk, &hint_pkt.dts);
     av_freep(&buf);
 
     /* Write the hint data into the hint track */
-    hint_pkt.size = size = url_close_dyn_buf(hintbuf, &buf);
+    hint_pkt.size = size = avio_close_dyn_buf(hintbuf, &buf);
     hint_pkt.data = buf;
     hint_pkt.pts  = hint_pkt.dts;
     hint_pkt.stream_index = track_index;
@@ -493,12 +449,9 @@ void ff_mov_close_hinting(MOVTrack *track) {
         return;
     if (rtp_ctx->pb) {
         av_write_trailer(rtp_ctx);
-        url_close_dyn_buf(rtp_ctx->pb, &ptr);
+        avio_close_dyn_buf(rtp_ctx->pb, &ptr);
         av_free(ptr);
     }
-    av_metadata_free(&rtp_ctx->streams[0]->metadata);
-    av_metadata_free(&rtp_ctx->metadata);
-    av_free(rtp_ctx->streams[0]);
-    av_freep(&rtp_ctx);
+    avformat_free_context(rtp_ctx);
 }
 
diff --git a/libavformat/mp3.c b/libavformat/mp3.c
deleted file mode 100644
index dcb59e8..0000000
--- a/libavformat/mp3.c
+++ /dev/null
@@ -1,366 +0,0 @@
-/*
- * MP3 muxer and demuxer
- * Copyright (c) 2003 Fabrice Bellard
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-#include <strings.h>
-#include "libavutil/avstring.h"
-#include "libavutil/intreadwrite.h"
-#include "avformat.h"
-#include "id3v2.h"
-#include "id3v1.h"
-
-#if CONFIG_MP3_DEMUXER
-
-#include "libavcodec/mpegaudio.h"
-#include "libavcodec/mpegaudiodecheader.h"
-
-/* mp3 read */
-
-static int mp3_read_probe(AVProbeData *p)
-{
-    int max_frames, first_frames = 0;
-    int fsize, frames, sample_rate;
-    uint32_t header;
-    uint8_t *buf, *buf0, *buf2, *end;
-    AVCodecContext avctx;
-
-    buf0 = p->buf;
-    if(ff_id3v2_match(buf0)) {
-        buf0 += ff_id3v2_tag_len(buf0);
-    }
-    end = p->buf + p->buf_size - sizeof(uint32_t);
-    while(buf0 < end && !*buf0)
-        buf0++;
-
-    max_frames = 0;
-    buf = buf0;
-
-    for(; buf < end; buf= buf2+1) {
-        buf2 = buf;
-
-        for(frames = 0; buf2 < end; frames++) {
-            header = AV_RB32(buf2);
-            fsize = ff_mpa_decode_header(&avctx, header, &sample_rate, &sample_rate, &sample_rate, &sample_rate);
-            if(fsize < 0)
-                break;
-            buf2 += fsize;
-        }
-        max_frames = FFMAX(max_frames, frames);
-        if(buf == buf0)
-            first_frames= frames;
-    }
-    // keep this in sync with ac3 probe, both need to avoid
-    // issues with MPEG-files!
-    if   (first_frames>=4) return AVPROBE_SCORE_MAX/2+1;
-    else if(max_frames>500)return AVPROBE_SCORE_MAX/2;
-    else if(max_frames>=4) return AVPROBE_SCORE_MAX/4;
-    else if(buf0!=p->buf)  return AVPROBE_SCORE_MAX/4-1;
-    else if(max_frames>=1) return 1;
-    else                   return 0;
-//mpegps_mp3_unrecognized_format.mpg has max_frames=3
-}
-
-/**
- * Try to find Xing/Info/VBRI tags and compute duration from info therein
- */
-static int mp3_parse_vbr_tags(AVFormatContext *s, AVStream *st, int64_t base)
-{
-    uint32_t v, spf;
-    int frames = -1; /* Total number of frames in file */
-    const int64_t xing_offtbl[2][2] = {{32, 17}, {17,9}};
-    MPADecodeHeader c;
-    int vbrtag_size = 0;
-
-    v = get_be32(s->pb);
-    if(ff_mpa_check_header(v) < 0)
-      return -1;
-
-    if (ff_mpegaudio_decode_header(&c, v) == 0)
-        vbrtag_size = c.frame_size;
-    if(c.layer != 3)
-        return -1;
-
-    /* Check for Xing / Info tag */
-    url_fseek(s->pb, xing_offtbl[c.lsf == 1][c.nb_channels == 1], SEEK_CUR);
-    v = get_be32(s->pb);
-    if(v == MKBETAG('X', 'i', 'n', 'g') || v == MKBETAG('I', 'n', 'f', 'o')) {
-        v = get_be32(s->pb);
-        if(v & 0x1)
-            frames = get_be32(s->pb);
-    }
-
-    /* Check for VBRI tag (always 32 bytes after end of mpegaudio header) */
-    url_fseek(s->pb, base + 4 + 32, SEEK_SET);
-    v = get_be32(s->pb);
-    if(v == MKBETAG('V', 'B', 'R', 'I')) {
-        /* Check tag version */
-        if(get_be16(s->pb) == 1) {
-            /* skip delay, quality and total bytes */
-            url_fseek(s->pb, 8, SEEK_CUR);
-            frames = get_be32(s->pb);
-        }
-    }
-
-    if(frames < 0)
-        return -1;
-
-    /* Skip the vbr tag frame */
-    url_fseek(s->pb, base + vbrtag_size, SEEK_SET);
-
-    spf = c.lsf ? 576 : 1152; /* Samples per frame, layer 3 */
-    st->duration = av_rescale_q(frames, (AVRational){spf, c.sample_rate},
-                                st->time_base);
-    return 0;
-}
-
-static int mp3_read_header(AVFormatContext *s,
-                           AVFormatParameters *ap)
-{
-    AVStream *st;
-    int64_t off;
-
-    st = av_new_stream(s, 0);
-    if (!st)
-        return AVERROR(ENOMEM);
-
-    st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
-    st->codec->codec_id = CODEC_ID_MP3;
-    st->need_parsing = AVSTREAM_PARSE_FULL;
-    st->start_time = 0;
-
-    // lcm of all mp3 sample rates
-    av_set_pts_info(st, 64, 1, 14112000);
-
-    ff_id3v2_read(s);
-    off = url_ftell(s->pb);
-
-    if (!av_metadata_get(s->metadata, "", NULL, AV_METADATA_IGNORE_SUFFIX))
-        ff_id3v1_read(s);
-
-    if (mp3_parse_vbr_tags(s, st, off) < 0)
-        url_fseek(s->pb, off, SEEK_SET);
-
-    /* the parameters will be extracted from the compressed bitstream */
-    return 0;
-}
-
-#define MP3_PACKET_SIZE 1024
-
-static int mp3_read_packet(AVFormatContext *s, AVPacket *pkt)
-{
-    int ret, size;
-    //    AVStream *st = s->streams[0];
-
-    size= MP3_PACKET_SIZE;
-
-    ret= av_get_packet(s->pb, pkt, size);
-
-    pkt->stream_index = 0;
-    if (ret <= 0) {
-        return AVERROR(EIO);
-    }
-    /* note: we need to modify the packet size here to handle the last
-       packet */
-    pkt->size = ret;
-    return ret;
-}
-
-AVInputFormat mp3_demuxer = {
-    "mp3",
-    NULL_IF_CONFIG_SMALL("MPEG audio layer 2/3"),
-    0,
-    mp3_read_probe,
-    mp3_read_header,
-    mp3_read_packet,
-    .flags= AVFMT_GENERIC_INDEX,
-    .extensions = "mp2,mp3,m2a", /* XXX: use probe */
-    .metadata_conv = ff_id3v2_metadata_conv,
-};
-#endif
-
-#if CONFIG_MP2_MUXER || CONFIG_MP3_MUXER
-static int id3v1_set_string(AVFormatContext *s, const char *key,
-                            uint8_t *buf, int buf_size)
-{
-    AVMetadataTag *tag;
-    if ((tag = av_metadata_get(s->metadata, key, NULL, 0)))
-        strncpy(buf, tag->value, buf_size);
-    return !!tag;
-}
-
-static int id3v1_create_tag(AVFormatContext *s, uint8_t *buf)
-{
-    AVMetadataTag *tag;
-    int i, count = 0;
-
-    memset(buf, 0, ID3v1_TAG_SIZE); /* fail safe */
-    buf[0] = 'T';
-    buf[1] = 'A';
-    buf[2] = 'G';
-    count += id3v1_set_string(s, "title",   buf +  3, 30);
-    count += id3v1_set_string(s, "author",  buf + 33, 30);
-    count += id3v1_set_string(s, "album",   buf + 63, 30);
-    count += id3v1_set_string(s, "date",    buf + 93,  4);
-    count += id3v1_set_string(s, "comment", buf + 97, 30);
-    if ((tag = av_metadata_get(s->metadata, "track", NULL, 0))) {
-        buf[125] = 0;
-        buf[126] = atoi(tag->value);
-        count++;
-    }
-    buf[127] = 0xFF; /* default to unknown genre */
-    if ((tag = av_metadata_get(s->metadata, "genre", NULL, 0))) {
-        for(i = 0; i <= ID3v1_GENRE_MAX; i++) {
-            if (!strcasecmp(tag->value, ff_id3v1_genre_str[i])) {
-                buf[127] = i;
-                count++;
-                break;
-            }
-        }
-    }
-    return count;
-}
-
-/* simple formats */
-
-static void id3v2_put_size(AVFormatContext *s, int size)
-{
-    put_byte(s->pb, size >> 21 & 0x7f);
-    put_byte(s->pb, size >> 14 & 0x7f);
-    put_byte(s->pb, size >> 7  & 0x7f);
-    put_byte(s->pb, size       & 0x7f);
-}
-
-static void id3v2_put_ttag(AVFormatContext *s, const char *buf, int len,
-                           uint32_t tag)
-{
-    put_be32(s->pb, tag);
-    id3v2_put_size(s, len + 1);
-    put_be16(s->pb, 0);
-    put_byte(s->pb, 3); /* UTF-8 */
-    put_buffer(s->pb, buf, len);
-}
-
-
-static int mp3_write_packet(struct AVFormatContext *s, AVPacket *pkt)
-{
-    put_buffer(s->pb, pkt->data, pkt->size);
-    put_flush_packet(s->pb);
-    return 0;
-}
-
-static int mp3_write_trailer(struct AVFormatContext *s)
-{
-    uint8_t buf[ID3v1_TAG_SIZE];
-
-    /* write the id3v1 tag */
-    if (id3v1_create_tag(s, buf) > 0) {
-        put_buffer(s->pb, buf, ID3v1_TAG_SIZE);
-        put_flush_packet(s->pb);
-    }
-    return 0;
-}
-#endif /* CONFIG_MP2_MUXER || CONFIG_MP3_MUXER */
-
-#if CONFIG_MP2_MUXER
-AVOutputFormat mp2_muxer = {
-    "mp2",
-    NULL_IF_CONFIG_SMALL("MPEG audio layer 2"),
-    "audio/x-mpeg",
-    "mp2,m2a",
-    0,
-    CODEC_ID_MP2,
-    CODEC_ID_NONE,
-    NULL,
-    mp3_write_packet,
-    mp3_write_trailer,
-};
-#endif
-
-#if CONFIG_MP3_MUXER
-/**
- * Write an ID3v2.4 header at beginning of stream
- */
-
-static int mp3_write_header(struct AVFormatContext *s)
-{
-    AVMetadataTag *t = NULL;
-    int totlen = 0;
-    int64_t size_pos, cur_pos;
-
-    put_be32(s->pb, MKBETAG('I', 'D', '3', 0x04)); /* ID3v2.4 */
-    put_byte(s->pb, 0);
-    put_byte(s->pb, 0); /* flags */
-
-    /* reserve space for size */
-    size_pos = url_ftell(s->pb);
-    put_be32(s->pb, 0);
-
-    while ((t = av_metadata_get(s->metadata, "", t, AV_METADATA_IGNORE_SUFFIX))) {
-        uint32_t tag = 0;
-
-        if (t->key[0] == 'T' && strlen(t->key) == 4) {
-            int i;
-            for (i = 0; *ff_id3v2_tags[i]; i++)
-                if (AV_RB32(t->key) == AV_RB32(ff_id3v2_tags[i])) {
-                    int len = strlen(t->value);
-                    tag = AV_RB32(t->key);
-                    totlen += len + ID3v2_HEADER_SIZE + 2;
-                    id3v2_put_ttag(s, t->value, len + 1, tag);
-                    break;
-                }
-        }
-
-        if (!tag) { /* unknown tag, write as TXXX frame */
-            int   len = strlen(t->key), len1 = strlen(t->value);
-            char *buf = av_malloc(len + len1 + 2);
-            if (!buf)
-                return AVERROR(ENOMEM);
-            tag = MKBETAG('T', 'X', 'X', 'X');
-            strcpy(buf,           t->key);
-            strcpy(buf + len + 1, t->value);
-            id3v2_put_ttag(s, buf, len + len1 + 2, tag);
-            totlen += len + len1 + ID3v2_HEADER_SIZE + 3;
-            av_free(buf);
-        }
-    }
-
-    cur_pos = url_ftell(s->pb);
-    url_fseek(s->pb, size_pos, SEEK_SET);
-    id3v2_put_size(s, totlen);
-    url_fseek(s->pb, cur_pos, SEEK_SET);
-
-    return 0;
-}
-
-AVOutputFormat mp3_muxer = {
-    "mp3",
-    NULL_IF_CONFIG_SMALL("MPEG audio layer 3"),
-    "audio/x-mpeg",
-    "mp3",
-    0,
-    CODEC_ID_MP3,
-    CODEC_ID_NONE,
-    mp3_write_header,
-    mp3_write_packet,
-    mp3_write_trailer,
-    AVFMT_NOTIMESTAMPS,
-    .metadata_conv = ff_id3v2_metadata_conv,
-};
-#endif
diff --git a/libavformat/mp3dec.c b/libavformat/mp3dec.c
new file mode 100644
index 0000000..dbecf3d
--- /dev/null
+++ b/libavformat/mp3dec.c
@@ -0,0 +1,197 @@
+/*
+ * MP3 demuxer
+ * Copyright (c) 2003 Fabrice Bellard
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "libavutil/avstring.h"
+#include "libavutil/intreadwrite.h"
+#include "avformat.h"
+#include "id3v2.h"
+#include "id3v1.h"
+#include "libavcodec/mpegaudiodecheader.h"
+
+/* mp3 read */
+
+static int mp3_read_probe(AVProbeData *p)
+{
+    int max_frames, first_frames = 0;
+    int fsize, frames, sample_rate;
+    uint32_t header;
+    uint8_t *buf, *buf0, *buf2, *end;
+    AVCodecContext avctx;
+
+    buf0 = p->buf;
+    end = p->buf + p->buf_size - sizeof(uint32_t);
+    while(buf0 < end && !*buf0)
+        buf0++;
+
+    max_frames = 0;
+    buf = buf0;
+
+    for(; buf < end; buf= buf2+1) {
+        buf2 = buf;
+
+        for(frames = 0; buf2 < end; frames++) {
+            header = AV_RB32(buf2);
+            fsize = ff_mpa_decode_header(&avctx, header, &sample_rate, &sample_rate, &sample_rate, &sample_rate);
+            if(fsize < 0)
+                break;
+            buf2 += fsize;
+        }
+        max_frames = FFMAX(max_frames, frames);
+        if(buf == buf0)
+            first_frames= frames;
+    }
+    // keep this in sync with ac3 probe, both need to avoid
+    // issues with MPEG-files!
+    if   (first_frames>=4) return AVPROBE_SCORE_MAX/2+1;
+    else if(max_frames>500)return AVPROBE_SCORE_MAX/2;
+    else if(max_frames>=4) return AVPROBE_SCORE_MAX/4;
+    else if(max_frames>=1) return 1;
+    else                   return 0;
+//mpegps_mp3_unrecognized_format.mpg has max_frames=3
+}
+
+/**
+ * Try to find Xing/Info/VBRI tags and compute duration from info therein
+ */
+static int mp3_parse_vbr_tags(AVFormatContext *s, AVStream *st, int64_t base)
+{
+    uint32_t v, spf;
+    unsigned frames = 0; /* Total number of frames in file */
+    unsigned size = 0; /* Total number of bytes in the stream */
+    const int64_t xing_offtbl[2][2] = {{32, 17}, {17,9}};
+    MPADecodeHeader c;
+    int vbrtag_size = 0;
+
+    v = avio_rb32(s->pb);
+    if(ff_mpa_check_header(v) < 0)
+      return -1;
+
+    if (ff_mpegaudio_decode_header(&c, v) == 0)
+        vbrtag_size = c.frame_size;
+    if(c.layer != 3)
+        return -1;
+
+    /* Check for Xing / Info tag */
+    avio_skip(s->pb, xing_offtbl[c.lsf == 1][c.nb_channels == 1]);
+    v = avio_rb32(s->pb);
+    if(v == MKBETAG('X', 'i', 'n', 'g') || v == MKBETAG('I', 'n', 'f', 'o')) {
+        v = avio_rb32(s->pb);
+        if(v & 0x1)
+            frames = avio_rb32(s->pb);
+        if(v & 0x2)
+            size = avio_rb32(s->pb);
+    }
+
+    /* Check for VBRI tag (always 32 bytes after end of mpegaudio header) */
+    avio_seek(s->pb, base + 4 + 32, SEEK_SET);
+    v = avio_rb32(s->pb);
+    if(v == MKBETAG('V', 'B', 'R', 'I')) {
+        /* Check tag version */
+        if(avio_rb16(s->pb) == 1) {
+            /* skip delay and quality */
+            avio_skip(s->pb, 4);
+            frames = avio_rb32(s->pb);
+            size = avio_rb32(s->pb);
+        }
+    }
+
+    if(!frames && !size)
+        return -1;
+
+    /* Skip the vbr tag frame */
+    avio_seek(s->pb, base + vbrtag_size, SEEK_SET);
+
+    spf = c.lsf ? 576 : 1152; /* Samples per frame, layer 3 */
+    if(frames)
+        st->duration = av_rescale_q(frames, (AVRational){spf, c.sample_rate},
+                                    st->time_base);
+    if(size && frames)
+        st->codec->bit_rate = av_rescale(size, 8 * c.sample_rate, frames * (int64_t)spf);
+
+    return 0;
+}
+
+static int mp3_read_header(AVFormatContext *s,
+                           AVFormatParameters *ap)
+{
+    AVStream *st;
+    int64_t off;
+
+    st = av_new_stream(s, 0);
+    if (!st)
+        return AVERROR(ENOMEM);
+
+    st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
+    st->codec->codec_id = CODEC_ID_MP3;
+    st->need_parsing = AVSTREAM_PARSE_FULL;
+    st->start_time = 0;
+
+    // lcm of all mp3 sample rates
+    av_set_pts_info(st, 64, 1, 14112000);
+
+    off = avio_tell(s->pb);
+
+    if (!av_metadata_get(s->metadata, "", NULL, AV_METADATA_IGNORE_SUFFIX))
+        ff_id3v1_read(s);
+
+    if (mp3_parse_vbr_tags(s, st, off) < 0)
+        avio_seek(s->pb, off, SEEK_SET);
+
+    /* the parameters will be extracted from the compressed bitstream */
+    return 0;
+}
+
+#define MP3_PACKET_SIZE 1024
+
+static int mp3_read_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    int ret, size;
+    //    AVStream *st = s->streams[0];
+
+    size= MP3_PACKET_SIZE;
+
+    ret= av_get_packet(s->pb, pkt, size);
+
+    pkt->stream_index = 0;
+    if (ret <= 0) {
+        return AVERROR(EIO);
+    }
+
+    if (ret > ID3v1_TAG_SIZE &&
+        memcmp(&pkt->data[ret - ID3v1_TAG_SIZE], "TAG", 3) == 0)
+        ret -= ID3v1_TAG_SIZE;
+
+    /* note: we need to modify the packet size here to handle the last
+       packet */
+    pkt->size = ret;
+    return ret;
+}
+
+AVInputFormat ff_mp3_demuxer = {
+    "mp3",
+    NULL_IF_CONFIG_SMALL("MPEG audio layer 2/3"),
+    0,
+    mp3_read_probe,
+    mp3_read_header,
+    mp3_read_packet,
+    .flags= AVFMT_GENERIC_INDEX,
+    .extensions = "mp2,mp3,m2a", /* XXX: use probe */
+};
diff --git a/libavformat/mp3enc.c b/libavformat/mp3enc.c
new file mode 100644
index 0000000..d46e67b
--- /dev/null
+++ b/libavformat/mp3enc.c
@@ -0,0 +1,255 @@
+/*
+ * MP3 muxer
+ * Copyright (c) 2003 Fabrice Bellard
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <strings.h>
+#include "avformat.h"
+#include "id3v1.h"
+#include "id3v2.h"
+#include "rawenc.h"
+#include "libavutil/intreadwrite.h"
+#include "libavutil/opt.h"
+
+static int id3v1_set_string(AVFormatContext *s, const char *key,
+                            uint8_t *buf, int buf_size)
+{
+    AVMetadataTag *tag;
+    if ((tag = av_metadata_get(s->metadata, key, NULL, 0)))
+        strncpy(buf, tag->value, buf_size);
+    return !!tag;
+}
+
+static int id3v1_create_tag(AVFormatContext *s, uint8_t *buf)
+{
+    AVMetadataTag *tag;
+    int i, count = 0;
+
+    memset(buf, 0, ID3v1_TAG_SIZE); /* fail safe */
+    buf[0] = 'T';
+    buf[1] = 'A';
+    buf[2] = 'G';
+    count += id3v1_set_string(s, "TIT2",    buf +  3, 30);       //title
+    count += id3v1_set_string(s, "TPE1",    buf + 33, 30);       //author|artist
+    count += id3v1_set_string(s, "TALB",    buf + 63, 30);       //album
+    count += id3v1_set_string(s, "TDRL",    buf + 93,  4);       //date
+    count += id3v1_set_string(s, "comment", buf + 97, 30);
+    if ((tag = av_metadata_get(s->metadata, "TRCK", NULL, 0))) { //track
+        buf[125] = 0;
+        buf[126] = atoi(tag->value);
+        count++;
+    }
+    buf[127] = 0xFF; /* default to unknown genre */
+    if ((tag = av_metadata_get(s->metadata, "TCON", NULL, 0))) { //genre
+        for(i = 0; i <= ID3v1_GENRE_MAX; i++) {
+            if (!strcasecmp(tag->value, ff_id3v1_genre_str[i])) {
+                buf[127] = i;
+                count++;
+                break;
+            }
+        }
+    }
+    return count;
+}
+
+/* simple formats */
+
+static void id3v2_put_size(AVFormatContext *s, int size)
+{
+    avio_w8(s->pb, size >> 21 & 0x7f);
+    avio_w8(s->pb, size >> 14 & 0x7f);
+    avio_w8(s->pb, size >> 7  & 0x7f);
+    avio_w8(s->pb, size       & 0x7f);
+}
+
+static int string_is_ascii(const uint8_t *str)
+{
+    while (*str && *str < 128) str++;
+    return !*str;
+}
+
+/**
+ * Write a text frame with one (normal frames) or two (TXXX frames) strings
+ * according to encoding (only UTF-8 or UTF-16+BOM supported).
+ * @return number of bytes written or a negative error code.
+ */
+static int id3v2_put_ttag(AVFormatContext *s, const char *str1, const char *str2,
+                          uint32_t tag, enum ID3v2Encoding enc)
+{
+    int len;
+    uint8_t *pb;
+    int (*put)(AVIOContext*, const char*);
+    AVIOContext *dyn_buf;
+    if (avio_open_dyn_buf(&dyn_buf) < 0)
+        return AVERROR(ENOMEM);
+
+    /* check if the strings are ASCII-only and use UTF16 only if
+     * they're not */
+    if (enc == ID3v2_ENCODING_UTF16BOM && string_is_ascii(str1) &&
+        (!str2 || string_is_ascii(str2)))
+        enc = ID3v2_ENCODING_ISO8859;
+
+    avio_w8(dyn_buf, enc);
+    if (enc == ID3v2_ENCODING_UTF16BOM) {
+        avio_wl16(dyn_buf, 0xFEFF);      /* BOM */
+        put = avio_put_str16le;
+    } else
+        put = avio_put_str;
+
+    put(dyn_buf, str1);
+    if (str2)
+        put(dyn_buf, str2);
+    len = avio_close_dyn_buf(dyn_buf, &pb);
+
+    avio_wb32(s->pb, tag);
+    id3v2_put_size(s, len);
+    avio_wb16(s->pb, 0);
+    avio_write(s->pb, pb, len);
+
+    av_freep(&pb);
+    return len + ID3v2_HEADER_SIZE;
+}
+
+static int mp3_write_trailer(struct AVFormatContext *s)
+{
+    uint8_t buf[ID3v1_TAG_SIZE];
+
+    /* write the id3v1 tag */
+    if (id3v1_create_tag(s, buf) > 0) {
+        avio_write(s->pb, buf, ID3v1_TAG_SIZE);
+        avio_flush(s->pb);
+    }
+    return 0;
+}
+
+#if CONFIG_MP2_MUXER
+AVOutputFormat ff_mp2_muxer = {
+    "mp2",
+    NULL_IF_CONFIG_SMALL("MPEG audio layer 2"),
+    "audio/x-mpeg",
+    "mp2,m2a",
+    0,
+    CODEC_ID_MP2,
+    CODEC_ID_NONE,
+    NULL,
+    ff_raw_write_packet,
+    mp3_write_trailer,
+};
+#endif
+
+#if CONFIG_MP3_MUXER
+typedef struct MP3Context {
+    const AVClass *class;
+    int id3v2_version;
+} MP3Context;
+
+static const AVOption options[] = {
+    { "id3v2_version", "Select ID3v2 version to write. Currently 3 and 4 are supported.",
+      offsetof(MP3Context, id3v2_version), FF_OPT_TYPE_INT, 4, 3, 4, AV_OPT_FLAG_ENCODING_PARAM},
+    { NULL },
+};
+
+static const AVClass mp3_muxer_class = {
+    "MP3 muxer",
+    av_default_item_name,
+    options,
+    LIBAVUTIL_VERSION_INT,
+};
+
+static int id3v2_check_write_tag(AVFormatContext *s, AVMetadataTag *t, const char table[][4],
+                                 enum ID3v2Encoding enc)
+{
+    uint32_t tag;
+    int i;
+
+    if (t->key[0] != 'T' || strlen(t->key) != 4)
+        return -1;
+    tag = AV_RB32(t->key);
+    for (i = 0; *table[i]; i++)
+        if (tag == AV_RB32(table[i]))
+            return id3v2_put_ttag(s, t->value, NULL, tag, enc);
+    return -1;
+}
+
+/**
+ * Write an ID3v2 header at beginning of stream
+ */
+
+static int mp3_write_header(struct AVFormatContext *s)
+{
+    MP3Context  *mp3 = s->priv_data;
+    AVMetadataTag *t = NULL;
+    int totlen = 0, enc = mp3->id3v2_version == 3 ? ID3v2_ENCODING_UTF16BOM :
+                                                    ID3v2_ENCODING_UTF8;
+    int64_t size_pos, cur_pos;
+
+    avio_wb32(s->pb, MKBETAG('I', 'D', '3', mp3->id3v2_version));
+    avio_w8(s->pb, 0);
+    avio_w8(s->pb, 0); /* flags */
+
+    /* reserve space for size */
+    size_pos = avio_tell(s->pb);
+    avio_wb32(s->pb, 0);
+
+    ff_metadata_conv(&s->metadata, ff_id3v2_34_metadata_conv, NULL);
+    if (mp3->id3v2_version == 4)
+        ff_metadata_conv(&s->metadata, ff_id3v2_4_metadata_conv, NULL);
+
+    while ((t = av_metadata_get(s->metadata, "", t, AV_METADATA_IGNORE_SUFFIX))) {
+        int ret;
+
+        if ((ret = id3v2_check_write_tag(s, t, ff_id3v2_tags, enc)) > 0) {
+            totlen += ret;
+            continue;
+        }
+        if ((ret = id3v2_check_write_tag(s, t, mp3->id3v2_version == 3 ?
+                                               ff_id3v2_3_tags : ff_id3v2_4_tags, enc)) > 0) {
+            totlen += ret;
+            continue;
+        }
+
+        /* unknown tag, write as TXXX frame */
+        if ((ret = id3v2_put_ttag(s, t->key, t->value, MKBETAG('T', 'X', 'X', 'X'), enc)) < 0)
+            return ret;
+        totlen += ret;
+    }
+
+    cur_pos = avio_tell(s->pb);
+    avio_seek(s->pb, size_pos, SEEK_SET);
+    id3v2_put_size(s, totlen);
+    avio_seek(s->pb, cur_pos, SEEK_SET);
+
+    return 0;
+}
+
+AVOutputFormat ff_mp3_muxer = {
+    "mp3",
+    NULL_IF_CONFIG_SMALL("MPEG audio layer 3"),
+    "audio/x-mpeg",
+    "mp3",
+    sizeof(MP3Context),
+    CODEC_ID_MP3,
+    CODEC_ID_NONE,
+    mp3_write_header,
+    ff_raw_write_packet,
+    mp3_write_trailer,
+    AVFMT_NOTIMESTAMPS,
+    .priv_class = &mp3_muxer_class,
+};
+#endif
diff --git a/libavformat/mpc.c b/libavformat/mpc.c
index 4dda65d..07c2299 100644
--- a/libavformat/mpc.c
+++ b/libavformat/mpc.c
@@ -2,27 +2,27 @@
  * Musepack demuxer
  * Copyright (c) 2006 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "libavcodec/get_bits.h"
 #include "avformat.h"
-#include "id3v2.h"
 #include "apetag.h"
+#include "id3v1.h"
 
 #define MPC_FRAMESIZE  1152
 #define DELAY_FRAMES   32
@@ -45,10 +45,6 @@ typedef struct {
 static int mpc_probe(AVProbeData *p)
 {
     const uint8_t *d = p->buf;
-    if (ff_id3v2_match(d)) {
-        d += ff_id3v2_tag_len(d);
-    }
-    if (d+3 < p->buf+p->buf_size)
     if (d[0] == 'M' && d[1] == 'P' && d[2] == '+' && (d[3] == 0x17 || d[3] == 0x7))
         return AVPROBE_SCORE_MAX;
     return 0;
@@ -58,39 +54,17 @@ static int mpc_read_header(AVFormatContext *s, AVFormatParameters *ap)
 {
     MPCContext *c = s->priv_data;
     AVStream *st;
-    int t, ret;
-    int64_t pos = url_ftell(s->pb);
 
-    t = get_le24(s->pb);
-    if(t != MKTAG('M', 'P', '+', 0)){
-        uint8_t buf[ID3v2_HEADER_SIZE];
-        if (url_fseek(s->pb, pos, SEEK_SET) < 0)
-            return -1;
-        ret = get_buffer(s->pb, buf, ID3v2_HEADER_SIZE);
-        if (ret != ID3v2_HEADER_SIZE || !ff_id3v2_match(buf)) {
-            av_log(s, AV_LOG_ERROR, "Not a Musepack file\n");
-            return -1;
-        }
-        /* skip ID3 tags and try again */
-        t = ff_id3v2_tag_len(buf) - ID3v2_HEADER_SIZE;
-        av_log(s, AV_LOG_DEBUG, "Skipping %d(%X) bytes of ID3 data\n", t, t);
-        url_fskip(s->pb, t);
-        if(get_le24(s->pb) != MKTAG('M', 'P', '+', 0)){
-            av_log(s, AV_LOG_ERROR, "Not a Musepack file\n");
-            return -1;
-        }
-        /* read ID3 tags */
-        if (url_fseek(s->pb, pos, SEEK_SET) < 0)
-            return -1;
-        ff_id3v2_read(s);
-        get_le24(s->pb);
+    if(avio_rl24(s->pb) != MKTAG('M', 'P', '+', 0)){
+        av_log(s, AV_LOG_ERROR, "Not a Musepack file\n");
+        return -1;
     }
-    c->ver = get_byte(s->pb);
+    c->ver = avio_r8(s->pb);
     if(c->ver != 0x07 && c->ver != 0x17){
         av_log(s, AV_LOG_ERROR, "Can demux Musepack SV7, got version %02X\n", c->ver);
         return -1;
     }
-    c->fcount = get_le32(s->pb);
+    c->fcount = avio_rl32(s->pb);
     if((int64_t)c->fcount * sizeof(MPCFrame) >= UINT_MAX){
         av_log(s, AV_LOG_ERROR, "Too many frames, seeking is not possible\n");
         return -1;
@@ -111,7 +85,7 @@ static int mpc_read_header(AVFormatContext *s, AVFormatParameters *ap)
 
     st->codec->extradata_size = 16;
     st->codec->extradata = av_mallocz(st->codec->extradata_size+FF_INPUT_BUFFER_PADDING_SIZE);
-    get_buffer(s->pb, st->codec->extradata, 16);
+    avio_read(s->pb, st->codec->extradata, 16);
     st->codec->sample_rate = mpc_rate[st->codec->extradata[2] & 3];
     av_set_pts_info(st, 32, MPC_FRAMESIZE, st->codec->sample_rate);
     /* scan for seekpoints */
@@ -119,10 +93,12 @@ static int mpc_read_header(AVFormatContext *s, AVFormatParameters *ap)
     st->duration = c->fcount;
 
     /* try to read APE tags */
-    if (!url_is_streamed(s->pb)) {
-        int64_t pos = url_ftell(s->pb);
+    if (s->pb->seekable) {
+        int64_t pos = avio_tell(s->pb);
         ff_ape_parse_tag(s);
-        url_fseek(s->pb, pos, SEEK_SET);
+        if (!av_metadata_get(s->metadata, "", NULL, AV_METADATA_IGNORE_SUFFIX))
+            ff_id3v1_read(s);
+        avio_seek(s->pb, pos, SEEK_SET);
     }
 
     return 0;
@@ -138,22 +114,22 @@ static int mpc_read_packet(AVFormatContext *s, AVPacket *pkt)
         return -1;
 
     if(c->curframe != c->lastframe + 1){
-        url_fseek(s->pb, c->frames[c->curframe].pos, SEEK_SET);
+        avio_seek(s->pb, c->frames[c->curframe].pos, SEEK_SET);
         c->curbits = c->frames[c->curframe].skip;
     }
     c->lastframe = c->curframe;
     c->curframe++;
     curbits = c->curbits;
-    pos = url_ftell(s->pb);
-    tmp = get_le32(s->pb);
+    pos = avio_tell(s->pb);
+    tmp = avio_rl32(s->pb);
     if(curbits <= 12){
         size2 = (tmp >> (12 - curbits)) & 0xFFFFF;
     }else{
-        tmp = (tmp << 32) | get_le32(s->pb);
+        tmp = (tmp << 32) | avio_rl32(s->pb);
         size2 = (tmp >> (44 - curbits)) & 0xFFFFF;
     }
     curbits += 20;
-    url_fseek(s->pb, pos, SEEK_SET);
+    avio_seek(s->pb, pos, SEEK_SET);
 
     size = ((size2 + curbits + 31) & ~31) >> 3;
     if(cur == c->frames_noted){
@@ -175,9 +151,9 @@ static int mpc_read_packet(AVFormatContext *s, AVPacket *pkt)
 
     pkt->stream_index = 0;
     pkt->pts = cur;
-    ret = get_buffer(s->pb, pkt->data + 4, size);
+    ret = avio_read(s->pb, pkt->data + 4, size);
     if(c->curbits)
-        url_fseek(s->pb, -4, SEEK_CUR);
+        avio_seek(s->pb, -4, SEEK_CUR);
     if(ret < size){
         av_free_packet(pkt);
         return AVERROR(EIO);
@@ -236,7 +212,7 @@ static int mpc_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp
 }
 
 
-AVInputFormat mpc_demuxer = {
+AVInputFormat ff_mpc_demuxer = {
     "mpc",
     NULL_IF_CONFIG_SMALL("Musepack"),
     sizeof(MPCContext),
diff --git a/libavformat/mpc8.c b/libavformat/mpc8.c
index 92e996c..c4810f6 100644
--- a/libavformat/mpc8.c
+++ b/libavformat/mpc8.c
@@ -2,26 +2,27 @@
  * Musepack SV8 demuxer
  * Copyright (c) 2007 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "libavcodec/get_bits.h"
 #include "libavcodec/unary.h"
 #include "avformat.h"
+#include "avio_internal.h"
 
 /// Two-byte MPC tag
 #define MKMPCTAG(a, b) (a | (b << 8))
@@ -117,13 +118,13 @@ static inline int64_t gb_get_v(GetBitContext *gb)
     return v;
 }
 
-static void mpc8_get_chunk_header(ByteIOContext *pb, int *tag, int64_t *size)
+static void mpc8_get_chunk_header(AVIOContext *pb, int *tag, int64_t *size)
 {
     int64_t pos;
-    pos = url_ftell(pb);
-    *tag = get_le16(pb);
-    *size = ff_get_v(pb);
-    *size -= url_ftell(pb) - pos;
+    pos = avio_tell(pb);
+    *tag = avio_rl16(pb);
+    *size = ffio_read_varlen(pb);
+    *size -= avio_tell(pb) - pos;
 }
 
 static void mpc8_parse_seektable(AVFormatContext *s, int64_t off)
@@ -135,7 +136,7 @@ static void mpc8_parse_seektable(AVFormatContext *s, int64_t off)
     int i, t, seekd;
     GetBitContext gb;
 
-    url_fseek(s->pb, off, SEEK_SET);
+    avio_seek(s->pb, off, SEEK_SET);
     mpc8_get_chunk_header(s->pb, &tag, &size);
     if(tag != TAG_SEEKTABLE){
         av_log(s, AV_LOG_ERROR, "No seek table at given position\n");
@@ -143,7 +144,7 @@ static void mpc8_parse_seektable(AVFormatContext *s, int64_t off)
     }
     if(!(buf = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE)))
         return;
-    get_buffer(s->pb, buf, size);
+    avio_read(s->pb, buf, size);
     init_get_bits(&gb, buf, size * 8);
     size = gb_get_v(&gb);
     if(size > UINT_MAX/4 || size > c->samples/1152){
@@ -171,37 +172,37 @@ static void mpc8_parse_seektable(AVFormatContext *s, int64_t off)
 
 static void mpc8_handle_chunk(AVFormatContext *s, int tag, int64_t chunk_pos, int64_t size)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int64_t pos, off;
 
     switch(tag){
     case TAG_SEEKTBLOFF:
-        pos = url_ftell(pb) + size;
-        off = ff_get_v(pb);
+        pos = avio_tell(pb) + size;
+        off = ffio_read_varlen(pb);
         mpc8_parse_seektable(s, chunk_pos + off);
-        url_fseek(pb, pos, SEEK_SET);
+        avio_seek(pb, pos, SEEK_SET);
         break;
     default:
-        url_fskip(pb, size);
+        avio_skip(pb, size);
     }
 }
 
 static int mpc8_read_header(AVFormatContext *s, AVFormatParameters *ap)
 {
     MPCContext *c = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVStream *st;
     int tag = 0;
     int64_t size, pos;
 
-    c->header_pos = url_ftell(pb);
-    if(get_le32(pb) != TAG_MPCK){
+    c->header_pos = avio_tell(pb);
+    if(avio_rl32(pb) != TAG_MPCK){
         av_log(s, AV_LOG_ERROR, "Not a Musepack8 file\n");
         return -1;
     }
 
-    while(!url_feof(pb)){
-        pos = url_ftell(pb);
+    while(!pb->eof_reached){
+        pos = avio_tell(pb);
         mpc8_get_chunk_header(pb, &tag, &size);
         if(tag == TAG_STREAMHDR)
             break;
@@ -211,15 +212,15 @@ static int mpc8_read_header(AVFormatContext *s, AVFormatParameters *ap)
         av_log(s, AV_LOG_ERROR, "Stream header not found\n");
         return -1;
     }
-    pos = url_ftell(pb);
-    url_fskip(pb, 4); //CRC
-    c->ver = get_byte(pb);
+    pos = avio_tell(pb);
+    avio_skip(pb, 4); //CRC
+    c->ver = avio_r8(pb);
     if(c->ver != 8){
         av_log(s, AV_LOG_ERROR, "Unknown stream version %d\n", c->ver);
         return -1;
     }
-    c->samples = ff_get_v(pb);
-    ff_get_v(pb); //silence samples at the beginning
+    c->samples = ffio_read_varlen(pb);
+    ffio_read_varlen(pb); //silence samples at the beginning
 
     st = av_new_stream(s, 0);
     if (!st)
@@ -230,13 +231,13 @@ static int mpc8_read_header(AVFormatContext *s, AVFormatParameters *ap)
 
     st->codec->extradata_size = 2;
     st->codec->extradata = av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
-    get_buffer(pb, st->codec->extradata, st->codec->extradata_size);
+    avio_read(pb, st->codec->extradata, st->codec->extradata_size);
 
     st->codec->channels = (st->codec->extradata[1] >> 4) + 1;
     st->codec->sample_rate = mpc8_rate[st->codec->extradata[0] >> 5];
     av_set_pts_info(st, 32, 1152  << (st->codec->extradata[1]&3)*2, st->codec->sample_rate);
     st->duration = c->samples / (1152 << (st->codec->extradata[1]&3)*2);
-    size -= url_ftell(pb) - pos;
+    size -= avio_tell(pb) - pos;
 
     return 0;
 }
@@ -247,8 +248,8 @@ static int mpc8_read_packet(AVFormatContext *s, AVPacket *pkt)
     int tag;
     int64_t pos, size;
 
-    while(!url_feof(s->pb)){
-        pos = url_ftell(s->pb);
+    while(!s->pb->eof_reached){
+        pos = avio_tell(s->pb);
         mpc8_get_chunk_header(s->pb, &tag, &size);
         if (size < 0)
             return -1;
@@ -273,13 +274,13 @@ static int mpc8_read_seek(AVFormatContext *s, int stream_index, int64_t timestam
     int index = av_index_search_timestamp(st, timestamp, flags);
 
     if(index < 0) return -1;
-    url_fseek(s->pb, st->index_entries[index].pos, SEEK_SET);
+    avio_seek(s->pb, st->index_entries[index].pos, SEEK_SET);
     c->frame = st->index_entries[index].timestamp;
     return 0;
 }
 
 
-AVInputFormat mpc8_demuxer = {
+AVInputFormat ff_mpc8_demuxer = {
     "mpc8",
     NULL_IF_CONFIG_SMALL("Musepack SV8"),
     sizeof(MPCContext),
diff --git a/libavformat/mpeg.c b/libavformat/mpeg.c
index 4224a04..68b685c 100644
--- a/libavformat/mpeg.c
+++ b/libavformat/mpeg.c
@@ -2,24 +2,25 @@
  * MPEG1/2 demuxer
  * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "avformat.h"
+#include "internal.h"
 #include "mpeg.h"
 
 //#define DEBUG_SEEK
@@ -60,16 +61,20 @@ static int mpegps_probe(AVProbeData *p)
     for(i=0; i<p->buf_size; i++){
         code = (code<<8) + p->buf[i];
         if ((code & 0xffffff00) == 0x100) {
+            int len= p->buf[i+1] << 8 | p->buf[i+2];
             int pes= check_pes(p->buf+i, p->buf+p->buf_size);
 
             if(code == SYSTEM_HEADER_START_CODE) sys++;
-            else if(code == PRIVATE_STREAM_1)    priv1++;
             else if(code == PACK_START_CODE)     pspack++;
             else if((code & 0xf0) == VIDEO_ID &&  pes) vid++;
-            else if((code & 0xe0) == AUDIO_ID &&  pes) audio++;
+            // skip pes payload to avoid start code emulation for private
+            // and audio streams
+            else if((code & 0xe0) == AUDIO_ID &&  pes) {audio++; i+=len;}
+            else if(code == PRIVATE_STREAM_1  &&  pes) {priv1++; i+=len;}
 
             else if((code & 0xf0) == VIDEO_ID && !pes) invalid++;
             else if((code & 0xe0) == AUDIO_ID && !pes) invalid++;
+            else if(code == PRIVATE_STREAM_1  && !pes) invalid++;
         }
     }
 
@@ -108,7 +113,7 @@ static int mpegps_read_header(AVFormatContext *s,
 
     m->sofdec = -1;
     do {
-        v = get_byte(s->pb);
+        v = avio_r8(s->pb);
         m->header_state = m->header_state << 8 | v;
         m->sofdec++;
     } while (v == sofdec[i] && i++ < 6);
@@ -119,17 +124,17 @@ static int mpegps_read_header(AVFormatContext *s,
     return 0;
 }
 
-static int64_t get_pts(ByteIOContext *pb, int c)
+static int64_t get_pts(AVIOContext *pb, int c)
 {
     uint8_t buf[5];
 
-    buf[0] = c<0 ? get_byte(pb) : c;
-    get_buffer(pb, buf+1, 4);
+    buf[0] = c<0 ? avio_r8(pb) : c;
+    avio_read(pb, buf+1, 4);
 
     return ff_parse_pes_pts(buf);
 }
 
-static int find_next_start_code(ByteIOContext *pb, int *size_ptr,
+static int find_next_start_code(AVIOContext *pb, int *size_ptr,
                                 int32_t *header_state)
 {
     unsigned int state, v;
@@ -138,9 +143,9 @@ static int find_next_start_code(ByteIOContext *pb, int *size_ptr,
     state = *header_state;
     n = *size_ptr;
     while (n > 0) {
-        if (url_feof(pb))
+        if (pb->eof_reached)
             break;
-        v = get_byte(pb);
+        v = avio_r8(pb);
         n--;
         if (state == 0x000001) {
             state = ((state << 8) | v) & 0xffffff;
@@ -158,20 +163,20 @@ static int find_next_start_code(ByteIOContext *pb, int *size_ptr,
 
 #if 0 /* unused, remove? */
 /* XXX: optimize */
-static int find_prev_start_code(ByteIOContext *pb, int *size_ptr)
+static int find_prev_start_code(AVIOContext *pb, int *size_ptr)
 {
     int64_t pos, pos_start;
     int max_size, start_code;
 
     max_size = *size_ptr;
-    pos_start = url_ftell(pb);
+    pos_start = avio_tell(pb);
 
     /* in order to go faster, we fill the buffer */
     pos = pos_start - 16386;
     if (pos < 0)
         pos = 0;
-    url_fseek(pb, pos, SEEK_SET);
-    get_byte(pb);
+    avio_seek(pb, pos, SEEK_SET);
+    avio_r8(pb);
 
     pos = pos_start;
     for(;;) {
@@ -180,8 +185,8 @@ static int find_prev_start_code(ByteIOContext *pb, int *size_ptr)
             start_code = -1;
             goto the_end;
         }
-        url_fseek(pb, pos, SEEK_SET);
-        start_code = get_be32(pb);
+        avio_seek(pb, pos, SEEK_SET);
+        start_code = avio_rb32(pb);
         if ((start_code & 0xffffff00) == 0x100)
             break;
     }
@@ -192,36 +197,36 @@ static int find_prev_start_code(ByteIOContext *pb, int *size_ptr)
 #endif
 
 /**
- * Extracts stream types from a program stream map
+ * Extract stream types from a program stream map
  * According to ISO/IEC 13818-1 ('MPEG-2 Systems') table 2-35
  *
  * @return number of bytes occupied by PSM in the bitstream
  */
-static long mpegps_psm_parse(MpegDemuxContext *m, ByteIOContext *pb)
+static long mpegps_psm_parse(MpegDemuxContext *m, AVIOContext *pb)
 {
     int psm_length, ps_info_length, es_map_length;
 
-    psm_length = get_be16(pb);
-    get_byte(pb);
-    get_byte(pb);
-    ps_info_length = get_be16(pb);
+    psm_length = avio_rb16(pb);
+    avio_r8(pb);
+    avio_r8(pb);
+    ps_info_length = avio_rb16(pb);
 
     /* skip program_stream_info */
-    url_fskip(pb, ps_info_length);
-    es_map_length = get_be16(pb);
+    avio_skip(pb, ps_info_length);
+    es_map_length = avio_rb16(pb);
 
     /* at least one es available? */
     while (es_map_length >= 4){
-        unsigned char type      = get_byte(pb);
-        unsigned char es_id     = get_byte(pb);
-        uint16_t es_info_length = get_be16(pb);
+        unsigned char type      = avio_r8(pb);
+        unsigned char es_id     = avio_r8(pb);
+        uint16_t es_info_length = avio_rb16(pb);
         /* remember mapping from stream id to stream type */
         m->psm_es_type[es_id] = type;
         /* skip program_stream_info */
-        url_fskip(pb, es_info_length);
+        avio_skip(pb, es_info_length);
         es_map_length -= 4 + es_info_length;
     }
-    get_be32(pb); /* crc32 */
+    avio_rb32(pb); /* crc32 */
     return 2 + psm_length;
 }
 
@@ -236,19 +241,19 @@ static int mpegps_read_pes_header(AVFormatContext *s,
     int len, size, startcode, c, flags, header_len;
     int pes_ext, ext2_len, id_ext, skip;
     int64_t pts, dts;
-    int64_t last_sync= url_ftell(s->pb);
+    int64_t last_sync= avio_tell(s->pb);
 
  error_redo:
-        url_fseek(s->pb, last_sync, SEEK_SET);
+        avio_seek(s->pb, last_sync, SEEK_SET);
  redo:
         /* next start code (should be immediately after) */
         m->header_state = 0xff;
         size = MAX_SYNC_SIZE;
         startcode = find_next_start_code(s->pb, &size, &m->header_state);
-        last_sync = url_ftell(s->pb);
-    //printf("startcode=%x pos=0x%"PRIx64"\n", startcode, url_ftell(s->pb));
+        last_sync = avio_tell(s->pb);
+    //printf("startcode=%x pos=0x%"PRIx64"\n", startcode, avio_tell(s->pb));
     if (startcode < 0){
-        if(url_feof(s->pb))
+        if(s->pb->eof_reached)
             return AVERROR_EOF;
         //FIXME we should remember header_state
         return AVERROR(EAGAIN);
@@ -259,16 +264,16 @@ static int mpegps_read_pes_header(AVFormatContext *s,
     if (startcode == SYSTEM_HEADER_START_CODE)
         goto redo;
     if (startcode == PADDING_STREAM) {
-        url_fskip(s->pb, get_be16(s->pb));
+        avio_skip(s->pb, avio_rb16(s->pb));
         goto redo;
     }
     if (startcode == PRIVATE_STREAM_2) {
-        len = get_be16(s->pb);
+        len = avio_rb16(s->pb);
         if (!m->sofdec) {
             while (len-- >= 6) {
-                if (get_byte(s->pb) == 'S') {
+                if (avio_r8(s->pb) == 'S') {
                     uint8_t buf[5];
-                    get_buffer(s->pb, buf, sizeof(buf));
+                    avio_read(s->pb, buf, sizeof(buf));
                     m->sofdec = !memcmp(buf, "ofdec", 5);
                     len -= sizeof(buf);
                     break;
@@ -276,7 +281,7 @@ static int mpegps_read_pes_header(AVFormatContext *s,
             }
             m->sofdec -= !m->sofdec;
         }
-        url_fskip(s->pb, len);
+        avio_skip(s->pb, len);
         goto redo;
     }
     if (startcode == PROGRAM_STREAM_MAP) {
@@ -290,16 +295,16 @@ static int mpegps_read_pes_header(AVFormatContext *s,
           (startcode == 0x1bd) || (startcode == 0x1fd)))
         goto redo;
     if (ppos) {
-        *ppos = url_ftell(s->pb) - 4;
+        *ppos = avio_tell(s->pb) - 4;
     }
-    len = get_be16(s->pb);
+    len = avio_rb16(s->pb);
     pts =
     dts = AV_NOPTS_VALUE;
     /* stuffing */
     for(;;) {
         if (len < 1)
             goto error_redo;
-        c = get_byte(s->pb);
+        c = avio_r8(s->pb);
         len--;
         /* XXX: for mpeg1, should test only bit 7 */
         if (c != 0xff)
@@ -307,8 +312,8 @@ static int mpegps_read_pes_header(AVFormatContext *s,
     }
     if ((c & 0xc0) == 0x40) {
         /* buffer scale & size */
-        get_byte(s->pb);
-        c = get_byte(s->pb);
+        avio_r8(s->pb);
+        c = avio_r8(s->pb);
         len -= 2;
     }
     if ((c & 0xe0) == 0x20) {
@@ -326,8 +331,8 @@ static int mpegps_read_pes_header(AVFormatContext *s,
             goto redo;
         }
 #endif
-        flags = get_byte(s->pb);
-        header_len = get_byte(s->pb);
+        flags = avio_r8(s->pb);
+        header_len = avio_r8(s->pb);
         len -= 2;
         if (header_len > len)
             goto error_redo;
@@ -345,7 +350,7 @@ static int mpegps_read_pes_header(AVFormatContext *s,
             av_log(s, AV_LOG_WARNING, "Further flags set but no bytes left\n");
         }
         if (flags & 0x01) { /* PES extension */
-            pes_ext = get_byte(s->pb);
+            pes_ext = avio_r8(s->pb);
             header_len--;
             /* Skip PES private data, program packet sequence counter and P-STD buffer */
             skip = (pes_ext >> 4) & 0xb;
@@ -354,14 +359,14 @@ static int mpegps_read_pes_header(AVFormatContext *s,
                 av_log(s, AV_LOG_WARNING, "pes_ext %X is invalid\n", pes_ext);
                 pes_ext=skip=0;
             }
-            url_fskip(s->pb, skip);
+            avio_skip(s->pb, skip);
             header_len -= skip;
 
             if (pes_ext & 0x01) { /* PES extension 2 */
-                ext2_len = get_byte(s->pb);
+                ext2_len = avio_r8(s->pb);
                 header_len--;
                 if ((ext2_len & 0x7f) > 0) {
-                    id_ext = get_byte(s->pb);
+                    id_ext = avio_r8(s->pb);
                     if ((id_ext & 0x80) == 0)
                         startcode = ((startcode & 0xff) << 8) | id_ext;
                     header_len--;
@@ -370,23 +375,23 @@ static int mpegps_read_pes_header(AVFormatContext *s,
         }
         if(header_len < 0)
             goto error_redo;
-        url_fskip(s->pb, header_len);
+        avio_skip(s->pb, header_len);
     }
     else if( c!= 0xf )
         goto redo;
 
     if (startcode == PRIVATE_STREAM_1 && !m->psm_es_type[startcode & 0xff]) {
-        startcode = get_byte(s->pb);
+        startcode = avio_r8(s->pb);
         len--;
         if (startcode >= 0x80 && startcode <= 0xcf) {
             /* audio: skip header */
-            get_byte(s->pb);
-            get_byte(s->pb);
-            get_byte(s->pb);
+            avio_r8(s->pb);
+            avio_r8(s->pb);
+            avio_r8(s->pb);
             len -= 3;
             if (startcode >= 0xb0 && startcode <= 0xbf) {
                 /* MLP/TrueHD audio has a 4-byte header */
-                get_byte(s->pb);
+                avio_r8(s->pb);
                 len--;
             }
         }
@@ -397,7 +402,7 @@ static int mpegps_read_pes_header(AVFormatContext *s,
         int i;
         for(i=0; i<s->nb_streams; i++){
             if(startcode == s->streams[i]->id &&
-               !url_is_streamed(s->pb) /* index useless on streams anyway */) {
+               s->pb->seekable /* index useless on streams anyway */) {
                 ff_reduce_index(s, i);
                 av_add_index_entry(s->streams[i], *ppos, dts, 0, 0, AVINDEX_KEYFRAME /* FIXME keyframe? */);
             }
@@ -427,8 +432,8 @@ static int mpegps_read_packet(AVFormatContext *s,
         return len;
 
     if(startcode == 0x1bd) {
-        dvdaudio_substream_type = get_byte(s->pb);
-        url_fskip(s->pb, 3);
+        dvdaudio_substream_type = avio_r8(s->pb);
+        avio_skip(s->pb, 3);
         len -= 4;
     }
 
@@ -469,8 +474,8 @@ static int mpegps_read_packet(AVFormatContext *s,
     } else if (startcode >= 0x1e0 && startcode <= 0x1ef) {
         static const unsigned char avs_seqh[4] = { 0, 0, 1, 0xb0 };
         unsigned char buf[8];
-        get_buffer(s->pb, buf, 8);
-        url_fseek(s->pb, -8, SEEK_CUR);
+        avio_read(s->pb, buf, 8);
+        avio_seek(s->pb, -8, SEEK_CUR);
         if(!memcmp(buf, avs_seqh, 4) && (buf[6] != 0 || buf[7] != 1))
             codec_id = CODEC_ID_CAVS;
         else
@@ -520,7 +525,7 @@ static int mpegps_read_packet(AVFormatContext *s,
     } else {
     skip:
         /* skip packet */
-        url_fskip(s->pb, len);
+        avio_skip(s->pb, len);
         goto redo;
     }
     /* no stream found: add a new stream */
@@ -542,9 +547,9 @@ static int mpegps_read_packet(AVFormatContext *s,
            audio data */
         if (len <= 3)
             goto skip;
-        get_byte(s->pb); /* emphasis (1), muse(1), reserved(1), frame number(5) */
-        b1 = get_byte(s->pb); /* quant (2), freq(2), reserved(1), channels(3) */
-        get_byte(s->pb); /* dynamic range control (0x80 = off) */
+        avio_r8(s->pb); /* emphasis (1), muse(1), reserved(1), frame number(5) */
+        b1 = avio_r8(s->pb); /* quant (2), freq(2), reserved(1), channels(3) */
+        avio_r8(s->pb); /* dynamic range control (0x80 = off) */
         len -= 3;
         freq = (b1 >> 4) & 3;
         st->codec->sample_rate = lpcm_freq_tab[freq];
@@ -559,7 +564,7 @@ static int mpegps_read_packet(AVFormatContext *s,
             return AVERROR(EINVAL);
     }
     av_new_packet(pkt, len);
-    get_buffer(s->pb, pkt->data, pkt->size);
+    avio_read(s->pb, pkt->data, pkt->size);
     pkt->pts = pts;
     pkt->dts = dts;
     pkt->pos = dummy_pos;
@@ -582,7 +587,7 @@ static int64_t mpegps_read_dts(AVFormatContext *s, int stream_index,
 #ifdef DEBUG_SEEK
     printf("read_dts: pos=0x%"PRIx64" next=%d -> ", pos, find_next);
 #endif
-    if (url_fseek(s->pb, pos, SEEK_SET) < 0)
+    if (avio_seek(s->pb, pos, SEEK_SET) < 0)
         return AV_NOPTS_VALUE;
 
     for(;;) {
@@ -597,7 +602,7 @@ static int64_t mpegps_read_dts(AVFormatContext *s, int stream_index,
             dts != AV_NOPTS_VALUE) {
             break;
         }
-        url_fskip(s->pb, len);
+        avio_skip(s->pb, len);
     }
 #ifdef DEBUG_SEEK
     printf("pos=0x%"PRIx64" dts=0x%"PRIx64" %0.3f\n", pos, dts, dts / 90000.0);
@@ -606,7 +611,7 @@ static int64_t mpegps_read_dts(AVFormatContext *s, int stream_index,
     return dts;
 }
 
-AVInputFormat mpegps_demuxer = {
+AVInputFormat ff_mpegps_demuxer = {
     "mpeg",
     NULL_IF_CONFIG_SMALL("MPEG-PS format"),
     sizeof(MpegDemuxContext),
diff --git a/libavformat/mpeg.h b/libavformat/mpeg.h
index d09b2e8..75dddf3 100644
--- a/libavformat/mpeg.h
+++ b/libavformat/mpeg.h
@@ -2,20 +2,20 @@
  * MPEG1/2 muxer and demuxer common defines
  * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -63,7 +63,7 @@ static const int lpcm_freq_tab[4] = { 48000, 96000, 44100, 32000 };
 /**
  * Parse MPEG-PES five-byte timestamp
  */
-static inline int64_t ff_parse_pes_pts(uint8_t *buf) {
+static inline int64_t ff_parse_pes_pts(const uint8_t *buf) {
     return (int64_t)(*buf & 0x0e) << 29 |
             (AV_RB16(buf+1) >> 1) << 15 |
              AV_RB16(buf+3) >> 1;
diff --git a/libavformat/mpegenc.c b/libavformat/mpegenc.c
index b37a774..0e01645 100644
--- a/libavformat/mpegenc.c
+++ b/libavformat/mpegenc.c
@@ -2,20 +2,20 @@
  * MPEG1/2 muxer
  * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -76,10 +76,10 @@ typedef struct {
 
 } MpegMuxContext;
 
-extern AVOutputFormat mpeg1vcd_muxer;
-extern AVOutputFormat mpeg2dvd_muxer;
-extern AVOutputFormat mpeg2svcd_muxer;
-extern AVOutputFormat mpeg2vob_muxer;
+extern AVOutputFormat ff_mpeg1vcd_muxer;
+extern AVOutputFormat ff_mpeg2dvd_muxer;
+extern AVOutputFormat ff_mpeg2svcd_muxer;
+extern AVOutputFormat ff_mpeg2vob_muxer;
 
 static int put_pack_header(AVFormatContext *ctx,
                            uint8_t *buf, int64_t timestamp)
@@ -297,12 +297,12 @@ static int mpeg_mux_init(AVFormatContext *ctx)
     int video_bitrate;
 
     s->packet_number = 0;
-    s->is_vcd =    (CONFIG_MPEG1VCD_MUXER  && ctx->oformat == &mpeg1vcd_muxer);
-    s->is_svcd =   (CONFIG_MPEG2SVCD_MUXER && ctx->oformat == &mpeg2svcd_muxer);
-    s->is_mpeg2 = ((CONFIG_MPEG2VOB_MUXER  && ctx->oformat == &mpeg2vob_muxer) ||
-                   (CONFIG_MPEG2DVD_MUXER  && ctx->oformat == &mpeg2dvd_muxer) ||
-                   (CONFIG_MPEG2SVCD_MUXER && ctx->oformat == &mpeg2svcd_muxer));
-    s->is_dvd =    (CONFIG_MPEG2DVD_MUXER  && ctx->oformat == &mpeg2dvd_muxer);
+    s->is_vcd =    (CONFIG_MPEG1VCD_MUXER  && ctx->oformat == &ff_mpeg1vcd_muxer);
+    s->is_svcd =   (CONFIG_MPEG2SVCD_MUXER && ctx->oformat == &ff_mpeg2svcd_muxer);
+    s->is_mpeg2 = ((CONFIG_MPEG2VOB_MUXER  && ctx->oformat == &ff_mpeg2vob_muxer) ||
+                   (CONFIG_MPEG2DVD_MUXER  && ctx->oformat == &ff_mpeg2dvd_muxer) ||
+                   (CONFIG_MPEG2SVCD_MUXER && ctx->oformat == &ff_mpeg2svcd_muxer));
+    s->is_dvd =    (CONFIG_MPEG2DVD_MUXER  && ctx->oformat == &ff_mpeg2dvd_muxer);
 
     if(ctx->packet_size) {
         if (ctx->packet_size < 20 || ctx->packet_size > (1 << 23) + 10) {
@@ -367,8 +367,10 @@ static int mpeg_mux_init(AVFormatContext *ctx)
             stream->id = mpv_id++;
             if (st->codec->rc_buffer_size)
                 stream->max_buffer_size = 6*1024 + st->codec->rc_buffer_size/8;
-            else
+            else {
+                av_log(ctx, AV_LOG_WARNING, "VBV buffer size not set, muxing may fail\n");
                 stream->max_buffer_size = 230*1024; //FIXME this is probably too small as default
+            }
 #if 0
                 /* see VCD standard, p. IV-7*/
                 stream->max_buffer_size = 46 * 1024;
@@ -489,14 +491,14 @@ static int mpeg_mux_init(AVFormatContext *ctx)
     return AVERROR(ENOMEM);
 }
 
-static inline void put_timestamp(ByteIOContext *pb, int id, int64_t timestamp)
+static inline void put_timestamp(AVIOContext *pb, int id, int64_t timestamp)
 {
-    put_byte(pb,
+    avio_w8(pb,
              (id << 4) |
              (((timestamp >> 30) & 0x07) << 1) |
              1);
-    put_be16(pb, (uint16_t)((((timestamp >> 15) & 0x7fff) << 1) | 1));
-    put_be16(pb, (uint16_t)((((timestamp      ) & 0x7fff) << 1) | 1));
+    avio_wb16(pb, (uint16_t)((((timestamp >> 15) & 0x7fff) << 1) | 1));
+    avio_wb16(pb, (uint16_t)((((timestamp      ) & 0x7fff) << 1) | 1));
 }
 
 
@@ -611,21 +613,21 @@ static int get_packet_payload_size(AVFormatContext *ctx, int stream_index,
 #endif
 
 /* Write an MPEG padding packet header. */
-static void put_padding_packet(AVFormatContext *ctx, ByteIOContext *pb,int packet_bytes)
+static void put_padding_packet(AVFormatContext *ctx, AVIOContext *pb,int packet_bytes)
 {
     MpegMuxContext *s = ctx->priv_data;
     int i;
 
-    put_be32(pb, PADDING_STREAM);
-    put_be16(pb, packet_bytes - 6);
+    avio_wb32(pb, PADDING_STREAM);
+    avio_wb16(pb, packet_bytes - 6);
     if (!s->is_mpeg2) {
-        put_byte(pb, 0x0f);
+        avio_w8(pb, 0x0f);
         packet_bytes -= 7;
     } else
         packet_bytes -= 6;
 
     for(i=0;i<packet_bytes;i++)
-        put_byte(pb, 0xff);
+        avio_w8(pb, 0xff);
 }
 
 static int get_nb_frames(AVFormatContext *ctx, StreamInfo *stream, int len){
@@ -697,19 +699,19 @@ static int flush_packet(AVFormatContext *ctx, int stream_index,
                     size = put_system_header(ctx, buf_ptr, 0);
                     buf_ptr += size;
                     size = buf_ptr - buffer;
-                    put_buffer(ctx->pb, buffer, size);
+                    avio_write(ctx->pb, buffer, size);
 
-                    put_be32(ctx->pb, PRIVATE_STREAM_2);
-                    put_be16(ctx->pb, 0x03d4);         // length
-                    put_byte(ctx->pb, 0x00);           // substream ID, 00=PCI
+                    avio_wb32(ctx->pb, PRIVATE_STREAM_2);
+                    avio_wb16(ctx->pb, 0x03d4);         // length
+                    avio_w8(ctx->pb, 0x00);           // substream ID, 00=PCI
                     for (i = 0; i < 979; i++)
-                        put_byte(ctx->pb, 0x00);
+                        avio_w8(ctx->pb, 0x00);
 
-                    put_be32(ctx->pb, PRIVATE_STREAM_2);
-                    put_be16(ctx->pb, 0x03fa);         // length
-                    put_byte(ctx->pb, 0x01);           // substream ID, 01=DSI
+                    avio_wb32(ctx->pb, PRIVATE_STREAM_2);
+                    avio_wb16(ctx->pb, 0x03fa);         // length
+                    avio_w8(ctx->pb, 0x01);           // substream ID, 01=DSI
                     for (i = 0; i < 1017; i++)
-                        put_byte(ctx->pb, 0x00);
+                        avio_w8(ctx->pb, 0x00);
 
                     memset(buffer, 0, 128);
                     buf_ptr = buffer;
@@ -732,7 +734,7 @@ static int flush_packet(AVFormatContext *ctx, int stream_index,
         }
     }
     size = buf_ptr - buffer;
-    put_buffer(ctx->pb, buffer, size);
+    avio_write(ctx->pb, buffer, size);
 
     packet_size = s->packet_size - size;
 
@@ -837,16 +839,16 @@ static int flush_packet(AVFormatContext *ctx, int stream_index,
 
         nb_frames= get_nb_frames(ctx, stream, payload_size - stuffing_size);
 
-        put_be32(ctx->pb, startcode);
+        avio_wb32(ctx->pb, startcode);
 
-        put_be16(ctx->pb, packet_size);
+        avio_wb16(ctx->pb, packet_size);
 
         if (!s->is_mpeg2)
             for(i=0;i<stuffing_size;i++)
-                put_byte(ctx->pb, 0xff);
+                avio_w8(ctx->pb, 0xff);
 
         if (s->is_mpeg2) {
-            put_byte(ctx->pb, 0x80); /* mpeg2 id */
+            avio_w8(ctx->pb, 0x80); /* mpeg2 id */
 
             pes_flags=0;
 
@@ -863,8 +865,8 @@ static int flush_packet(AVFormatContext *ctx, int stream_index,
             if (stream->packet_number == 0)
                 pes_flags |= 0x01;
 
-            put_byte(ctx->pb, pes_flags); /* flags */
-            put_byte(ctx->pb, header_len - 3 + stuffing_size);
+            avio_w8(ctx->pb, pes_flags); /* flags */
+            avio_w8(ctx->pb, header_len - 3 + stuffing_size);
 
             if (pes_flags & 0x80)  /*write pts*/
                 put_timestamp(ctx->pb, (pes_flags & 0x40) ? 0x03 : 0x02, pts);
@@ -872,13 +874,13 @@ static int flush_packet(AVFormatContext *ctx, int stream_index,
                 put_timestamp(ctx->pb, 0x01, dts);
 
             if (pes_flags & 0x01) {  /*write pes extension*/
-                put_byte(ctx->pb, 0x10); /* flags */
+                avio_w8(ctx->pb, 0x10); /* flags */
 
                 /* P-STD buffer info */
                 if ((id & 0xe0) == AUDIO_ID)
-                    put_be16(ctx->pb, 0x4000 | stream->max_buffer_size/ 128);
+                    avio_wb16(ctx->pb, 0x4000 | stream->max_buffer_size/ 128);
                 else
-                    put_be16(ctx->pb, 0x6000 | stream->max_buffer_size/1024);
+                    avio_wb16(ctx->pb, 0x6000 | stream->max_buffer_size/1024);
             }
 
         } else {
@@ -890,38 +892,38 @@ static int flush_packet(AVFormatContext *ctx, int stream_index,
                     put_timestamp(ctx->pb, 0x02, pts);
                 }
             } else {
-                put_byte(ctx->pb, 0x0f);
+                avio_w8(ctx->pb, 0x0f);
             }
         }
 
         if (s->is_mpeg2) {
             /* special stuffing byte that is always written
                to prevent accidental generation of start codes. */
-            put_byte(ctx->pb, 0xff);
+            avio_w8(ctx->pb, 0xff);
 
             for(i=0;i<stuffing_size;i++)
-                put_byte(ctx->pb, 0xff);
+                avio_w8(ctx->pb, 0xff);
         }
 
         if (startcode == PRIVATE_STREAM_1) {
-            put_byte(ctx->pb, id);
+            avio_w8(ctx->pb, id);
             if (id >= 0xa0) {
                 /* LPCM (XXX: check nb_frames) */
-                put_byte(ctx->pb, 7);
-                put_be16(ctx->pb, 4); /* skip 3 header bytes */
-                put_byte(ctx->pb, stream->lpcm_header[0]);
-                put_byte(ctx->pb, stream->lpcm_header[1]);
-                put_byte(ctx->pb, stream->lpcm_header[2]);
+                avio_w8(ctx->pb, 7);
+                avio_wb16(ctx->pb, 4); /* skip 3 header bytes */
+                avio_w8(ctx->pb, stream->lpcm_header[0]);
+                avio_w8(ctx->pb, stream->lpcm_header[1]);
+                avio_w8(ctx->pb, stream->lpcm_header[2]);
             } else if (id >= 0x40) {
                 /* AC-3 */
-                put_byte(ctx->pb, nb_frames);
-                put_be16(ctx->pb, trailer_size+1);
+                avio_w8(ctx->pb, nb_frames);
+                avio_wb16(ctx->pb, trailer_size+1);
             }
         }
 
         /* output data */
         assert(payload_size - stuffing_size <= av_fifo_size(stream->fifo));
-        av_fifo_generic_read(stream->fifo, ctx->pb, payload_size - stuffing_size, &put_buffer);
+        av_fifo_generic_read(stream->fifo, ctx->pb, payload_size - stuffing_size, &avio_write);
         stream->bytes_to_iframe -= payload_size - stuffing_size;
     }else{
         payload_size=
@@ -932,9 +934,9 @@ static int flush_packet(AVFormatContext *ctx, int stream_index,
         put_padding_packet(ctx,ctx->pb, pad_packet_bytes);
 
     for(i=0;i<zero_trail_bytes;i++)
-        put_byte(ctx->pb, 0x00);
+        avio_w8(ctx->pb, 0x00);
 
-    put_flush_packet(ctx->pb);
+    avio_flush(ctx->pb);
 
     s->packet_number++;
 
@@ -959,11 +961,11 @@ static void put_vcd_padding_sector(AVFormatContext *ctx)
     int i;
 
     for(i=0;i<s->packet_size;i++)
-        put_byte(ctx->pb, 0);
+        avio_w8(ctx->pb, 0);
 
     s->vcd_padding_bytes_written += s->packet_size;
 
-    put_flush_packet(ctx->pb);
+    avio_flush(ctx->pb);
 
     /* increasing the packet number is correct. The SCR of the following packs
        is calculated from the packet_number and it has to include the padding
@@ -1161,8 +1163,12 @@ static int mpeg_mux_write_packet(AVFormatContext *ctx, AVPacket *pkt)
     pts= pkt->pts;
     dts= pkt->dts;
 
-    if(pts != AV_NOPTS_VALUE) pts += preload;
-    if(dts != AV_NOPTS_VALUE) dts += preload;
+    if(pts != AV_NOPTS_VALUE) pts += 2*preload;
+    if(dts != AV_NOPTS_VALUE){
+        if(!s->last_scr)
+            s->last_scr= dts + preload;
+        dts += 2*preload;
+    }
 
 //av_log(ctx, AV_LOG_DEBUG, "dts:%f pts:%f flags:%d stream:%d nopts:%d\n", dts/90000.0, pts/90000.0, pkt->flags, pkt->stream_index, pts != AV_NOPTS_VALUE);
     if (!stream->premux_packet)
@@ -1214,8 +1220,8 @@ static int mpeg_mux_end(AVFormatContext *ctx)
     /* End header according to MPEG1 systems standard. We do not write
        it as it is usually not needed by decoders and because it
        complicates MPEG stream concatenation. */
-    //put_be32(ctx->pb, ISO_11172_END_CODE);
-    //put_flush_packet(ctx->pb);
+    //avio_wb32(ctx->pb, ISO_11172_END_CODE);
+    //avio_flush(ctx->pb);
 
     for(i=0;i<ctx->nb_streams;i++) {
         stream = ctx->streams[i]->priv_data;
@@ -1227,7 +1233,7 @@ static int mpeg_mux_end(AVFormatContext *ctx)
 }
 
 #if CONFIG_MPEG1SYSTEM_MUXER
-AVOutputFormat mpeg1system_muxer = {
+AVOutputFormat ff_mpeg1system_muxer = {
     "mpeg",
     NULL_IF_CONFIG_SMALL("MPEG-1 System format"),
     "video/mpeg",
@@ -1241,7 +1247,7 @@ AVOutputFormat mpeg1system_muxer = {
 };
 #endif
 #if CONFIG_MPEG1VCD_MUXER
-AVOutputFormat mpeg1vcd_muxer = {
+AVOutputFormat ff_mpeg1vcd_muxer = {
     "vcd",
     NULL_IF_CONFIG_SMALL("MPEG-1 System format (VCD)"),
     "video/mpeg",
@@ -1255,7 +1261,7 @@ AVOutputFormat mpeg1vcd_muxer = {
 };
 #endif
 #if CONFIG_MPEG2VOB_MUXER
-AVOutputFormat mpeg2vob_muxer = {
+AVOutputFormat ff_mpeg2vob_muxer = {
     "vob",
     NULL_IF_CONFIG_SMALL("MPEG-2 PS format (VOB)"),
     "video/mpeg",
@@ -1271,7 +1277,7 @@ AVOutputFormat mpeg2vob_muxer = {
 
 /* Same as mpeg2vob_mux except that the pack size is 2324 */
 #if CONFIG_MPEG2SVCD_MUXER
-AVOutputFormat mpeg2svcd_muxer = {
+AVOutputFormat ff_mpeg2svcd_muxer = {
     "svcd",
     NULL_IF_CONFIG_SMALL("MPEG-2 PS format (VOB)"),
     "video/mpeg",
@@ -1287,7 +1293,7 @@ AVOutputFormat mpeg2svcd_muxer = {
 
 /*  Same as mpeg2vob_mux except the 'is_dvd' flag is set to produce NAV pkts */
 #if CONFIG_MPEG2DVD_MUXER
-AVOutputFormat mpeg2dvd_muxer = {
+AVOutputFormat ff_mpeg2dvd_muxer = {
     "dvd",
     NULL_IF_CONFIG_SMALL("MPEG-2 PS format (DVD VOB)"),
     "video/mpeg",
diff --git a/libavformat/mpegts.c b/libavformat/mpegts.c
index 5960338..62e9dcb 100644
--- a/libavformat/mpegts.c
+++ b/libavformat/mpegts.c
@@ -2,20 +2,20 @@
  * MPEG2 transport stream (aka DVB) demuxer
  * Copyright (c) 2002-2003 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -29,10 +29,10 @@
 #include "avformat.h"
 #include "mpegts.h"
 #include "internal.h"
+#include "avio_internal.h"
 #include "seek.h"
-
-/* 1.0 second at 24Mbit/s */
-#define MAX_SCAN_PACKETS 32000
+#include "mpeg.h"
+#include "isom.h"
 
 /* maximum size in which we look for synchronisation if
    synchronisation is lost */
@@ -157,7 +157,7 @@ typedef struct PESContext {
     uint8_t *buffer;
 } PESContext;
 
-extern AVInputFormat mpegts_demuxer;
+extern AVInputFormat ff_mpegts_demuxer;
 
 static void clear_program(MpegTSContext *ts, unsigned int programid)
 {
@@ -239,7 +239,7 @@ static int discard_pid(MpegTSContext *ts, unsigned int pid)
 }
 
 /**
- *  Assembles PES packets out of TS packets, and then calls the "section_cb"
+ *  Assemble PES packets out of TS packets, and then call the "section_cb"
  *  function when they are complete.
  */
 static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
@@ -288,7 +288,7 @@ static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int
     MpegTSFilter *filter;
     MpegTSSectionFilter *sec;
 
-    dprintf(ts->stream, "Filter: pid=0x%x\n", pid);
+    av_dlog(ts->stream, "Filter: pid=0x%x\n", pid);
 
     if (pid >= NB_PID_MAX || ts->pids[pid])
         return NULL;
@@ -497,7 +497,7 @@ static const StreamType ISO_types[] = {
     { 0x04, AVMEDIA_TYPE_AUDIO,        CODEC_ID_MP3 },
     { 0x0f, AVMEDIA_TYPE_AUDIO,        CODEC_ID_AAC },
     { 0x10, AVMEDIA_TYPE_VIDEO,      CODEC_ID_MPEG4 },
-  //{ 0x11, AVMEDIA_TYPE_AUDIO,        CODEC_ID_AAC }, /* LATM syntax */
+    { 0x11, AVMEDIA_TYPE_AUDIO,   CODEC_ID_AAC_LATM }, /* LATM syntax */
     { 0x1b, AVMEDIA_TYPE_VIDEO,       CODEC_ID_H264 },
     { 0xd1, AVMEDIA_TYPE_VIDEO,      CODEC_ID_DIRAC },
     { 0xea, AVMEDIA_TYPE_VIDEO,        CODEC_ID_VC1 },
@@ -594,23 +594,12 @@ static int mpegts_set_stream_info(AVStream *st, PESContext *pes,
             sub_pes->sub_st = pes->sub_st = sub_st;
         }
     }
-    if (pes->stream_type == 0x11)
-        av_log(pes->stream, AV_LOG_WARNING,
-               "AAC LATM not currently supported, patch welcome\n");
     if (st->codec->codec_id == CODEC_ID_NONE)
         mpegts_find_stream_type(st, pes->stream_type, MISC_types);
 
     return 0;
 }
 
-static int64_t get_pts(const uint8_t *p)
-{
-    int64_t pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
-    pts |= (AV_RB16(p + 1) >> 1) << 15;
-    pts |=  AV_RB16(p + 3) >> 1;
-    return pts;
-}
-
 static void new_pes_packet(PESContext *pes, AVPacket *pkt)
 {
     av_init_packet(pkt);
@@ -680,13 +669,17 @@ static int mpegts_push_data(MpegTSFilter *filter,
                     pes->header[2] == 0x01) {
                     /* it must be an mpeg2 PES stream */
                     code = pes->header[3] | 0x100;
-                    dprintf(pes->stream, "pid=%x pes_code=%#x\n", pes->pid, code);
+                    av_dlog(pes->stream, "pid=%x pes_code=%#x\n", pes->pid, code);
 
-                    if ((!pes->st && pes->stream->nb_streams == MAX_STREAMS) ||
-                        (pes->st && pes->st->discard == AVDISCARD_ALL) ||
+                    if ((pes->st && pes->st->discard == AVDISCARD_ALL) ||
                         code == 0x1be) /* padding_stream */
                         goto skip;
 
+#if FF_API_MAX_STREAMS
+                    if (!pes->st && pes->stream->nb_streams == MAX_STREAMS)
+                        goto skip;
+#endif
+
                     /* stream not present in PMT */
                     if (!pes->st) {
                         pes->st = av_new_stream(ts->stream, pes->pid);
@@ -712,7 +705,7 @@ static int mpegts_push_data(MpegTSFilter *filter,
                         code != 0x1f8) {                  /* ITU-T Rec. H.222.1 type E stream */
                         pes->state = MPEGTS_PESHEADER;
                         if (pes->st->codec->codec_id == CODEC_ID_NONE) {
-                            dprintf(pes->stream, "pid=%x stream_type=%x probing\n",
+                            av_dlog(pes->stream, "pid=%x stream_type=%x probing\n",
                                     pes->pid, pes->stream_type);
                             pes->st->codec->codec_id = CODEC_ID_PROBE;
                         }
@@ -765,12 +758,12 @@ static int mpegts_push_data(MpegTSFilter *filter,
                 pes->pts = AV_NOPTS_VALUE;
                 pes->dts = AV_NOPTS_VALUE;
                 if ((flags & 0xc0) == 0x80) {
-                    pes->dts = pes->pts = get_pts(r);
+                    pes->dts = pes->pts = ff_parse_pes_pts(r);
                     r += 5;
                 } else if ((flags & 0xc0) == 0xc0) {
-                    pes->pts = get_pts(r);
+                    pes->pts = ff_parse_pes_pts(r);
                     r += 5;
-                    pes->dts = get_pts(r);
+                    pes->dts = ff_parse_pes_pts(r);
                     r += 5;
                 }
                 pes->extended_stream_id = -1;
@@ -795,13 +788,17 @@ static int mpegts_push_data(MpegTSFilter *filter,
             break;
         case MPEGTS_PAYLOAD:
             if (buf_size > 0 && pes->buffer) {
-                if (pes->data_index+buf_size > pes->total_size) {
+                if (pes->data_index > 0 && pes->data_index+buf_size > pes->total_size) {
                     new_pes_packet(pes, ts->pkt);
                     pes->total_size = MAX_PES_PAYLOAD;
                     pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
                     if (!pes->buffer)
                         return AVERROR(ENOMEM);
                     ts->stop_parse = 1;
+                } else if (pes->data_index == 0 && buf_size > pes->total_size) {
+                    // pes packet size is < ts size packet and pes data is padded with 0xff
+                    // not sure if this is legal in ts but see issue #2392
+                    buf_size = pes->total_size;
                 }
                 memcpy(pes->buffer+pes->data_index, p, buf_size);
                 pes->data_index += buf_size;
@@ -851,21 +848,165 @@ static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid)
     return pes;
 }
 
+static int mp4_read_iods(AVFormatContext *s, const uint8_t *buf, unsigned size,
+                         int *es_id, uint8_t **dec_config_descr,
+                         int *dec_config_descr_size)
+{
+    AVIOContext pb;
+    int tag;
+    unsigned len;
+
+    ffio_init_context(&pb, buf, size, 0, NULL, NULL, NULL, NULL);
+
+    len = ff_mp4_read_descr(s, &pb, &tag);
+    if (tag == MP4IODescrTag) {
+        avio_rb16(&pb); // ID
+        avio_r8(&pb);
+        avio_r8(&pb);
+        avio_r8(&pb);
+        avio_r8(&pb);
+        avio_r8(&pb);
+        len = ff_mp4_read_descr(s, &pb, &tag);
+        if (tag == MP4ESDescrTag) {
+            *es_id = avio_rb16(&pb); /* ES_ID */
+            av_dlog(s, "ES_ID %#x\n", *es_id);
+            avio_r8(&pb); /* priority */
+            len = ff_mp4_read_descr(s, &pb, &tag);
+            if (tag == MP4DecConfigDescrTag) {
+                *dec_config_descr = av_malloc(len);
+                if (!*dec_config_descr)
+                    return AVERROR(ENOMEM);
+                *dec_config_descr_size = len;
+                avio_read(&pb, *dec_config_descr, len);
+            }
+        }
+    }
+    return 0;
+}
+
+int ff_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type,
+                              const uint8_t **pp, const uint8_t *desc_list_end,
+                              int mp4_dec_config_descr_len, int mp4_es_id, int pid,
+                              uint8_t *mp4_dec_config_descr)
+{
+    const uint8_t *desc_end;
+    int desc_len, desc_tag;
+    char language[252];
+    int i;
+
+    desc_tag = get8(pp, desc_list_end);
+    if (desc_tag < 0)
+        return -1;
+    desc_len = get8(pp, desc_list_end);
+    if (desc_len < 0)
+        return -1;
+    desc_end = *pp + desc_len;
+    if (desc_end > desc_list_end)
+        return -1;
+
+    av_dlog(fc, "tag: 0x%02x len=%d\n", desc_tag, desc_len);
+
+    if (st->codec->codec_id == CODEC_ID_NONE &&
+        stream_type == STREAM_TYPE_PRIVATE_DATA)
+        mpegts_find_stream_type(st, desc_tag, DESC_types);
+
+    switch(desc_tag) {
+    case 0x1F: /* FMC descriptor */
+        get16(pp, desc_end);
+        if (st->codec->codec_id == CODEC_ID_AAC_LATM &&
+            mp4_dec_config_descr_len && mp4_es_id == pid) {
+            AVIOContext pb;
+            ffio_init_context(&pb, mp4_dec_config_descr,
+                          mp4_dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
+            ff_mp4_read_dec_config_descr(fc, st, &pb);
+            if (st->codec->codec_id == CODEC_ID_AAC &&
+                st->codec->extradata_size > 0)
+                st->need_parsing = 0;
+        }
+        break;
+    case 0x56: /* DVB teletext descriptor */
+        language[0] = get8(pp, desc_end);
+        language[1] = get8(pp, desc_end);
+        language[2] = get8(pp, desc_end);
+        language[3] = 0;
+        av_metadata_set2(&st->metadata, "language", language, 0);
+        break;
+    case 0x59: /* subtitling descriptor */
+        language[0] = get8(pp, desc_end);
+        language[1] = get8(pp, desc_end);
+        language[2] = get8(pp, desc_end);
+        language[3] = 0;
+        /* hearing impaired subtitles detection */
+        switch(get8(pp, desc_end)) {
+        case 0x20: /* DVB subtitles (for the hard of hearing) with no monitor aspect ratio criticality */
+        case 0x21: /* DVB subtitles (for the hard of hearing) for display on 4:3 aspect ratio monitor */
+        case 0x22: /* DVB subtitles (for the hard of hearing) for display on 16:9 aspect ratio monitor */
+        case 0x23: /* DVB subtitles (for the hard of hearing) for display on 2.21:1 aspect ratio monitor */
+        case 0x24: /* DVB subtitles (for the hard of hearing) for display on a high definition monitor */
+        case 0x25: /* DVB subtitles (for the hard of hearing) with plano-stereoscopic disparity for display on a high definition monitor */
+            st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
+            break;
+        }
+        if (st->codec->extradata) {
+            if (st->codec->extradata_size == 4 && memcmp(st->codec->extradata, *pp, 4))
+                av_log_ask_for_sample(fc, "DVB sub with multiple IDs\n");
+        } else {
+            st->codec->extradata = av_malloc(4 + FF_INPUT_BUFFER_PADDING_SIZE);
+            if (st->codec->extradata) {
+                st->codec->extradata_size = 4;
+                memcpy(st->codec->extradata, *pp, 4);
+            }
+        }
+        *pp += 4;
+        av_metadata_set2(&st->metadata, "language", language, 0);
+        break;
+    case 0x0a: /* ISO 639 language descriptor */
+        for (i = 0; i + 4 <= desc_len; i += 4) {
+            language[i + 0] = get8(pp, desc_end);
+            language[i + 1] = get8(pp, desc_end);
+            language[i + 2] = get8(pp, desc_end);
+            language[i + 3] = ',';
+        switch (get8(pp, desc_end)) {
+            case 0x01: st->disposition |= AV_DISPOSITION_CLEAN_EFFECTS; break;
+            case 0x02: st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED; break;
+            case 0x03: st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED; break;
+        }
+        }
+        if (i) {
+            language[i - 1] = 0;
+            av_metadata_set2(&st->metadata, "language", language, 0);
+        }
+        break;
+    case 0x05: /* registration descriptor */
+        st->codec->codec_tag = bytestream_get_le32(pp);
+        av_dlog(fc, "reg_desc=%.4s\n", (char*)&st->codec->codec_tag);
+        if (st->codec->codec_id == CODEC_ID_NONE &&
+            stream_type == STREAM_TYPE_PRIVATE_DATA)
+            mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types);
+        break;
+    default:
+        break;
+    }
+    *pp = desc_end;
+    return 0;
+}
+
 static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
 {
     MpegTSContext *ts = filter->u.section_filter.opaque;
     SectionHeader h1, *h = &h1;
     PESContext *pes;
     AVStream *st;
-    const uint8_t *p, *p_end, *desc_list_end, *desc_end;
+    const uint8_t *p, *p_end, *desc_list_end;
     int program_info_length, pcr_pid, pid, stream_type;
-    int desc_list_len, desc_len, desc_tag;
-    int comp_page, anc_page;
-    char language[4];
+    int desc_list_len;
     uint32_t prog_reg_desc = 0; /* registration descriptor */
+    uint8_t *mp4_dec_config_descr = NULL;
+    int mp4_dec_config_descr_len = 0;
+    int mp4_es_id = 0;
 
 #ifdef DEBUG
-    dprintf(ts->stream, "PMT: len %i\n", section_len);
+    av_dlog(ts->stream, "PMT: len %i\n", section_len);
     av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
 #endif
 
@@ -874,7 +1015,7 @@ static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len
     if (parse_section_header(h, &p, p_end) < 0)
         return;
 
-    dprintf(ts->stream, "sid=0x%x sec_num=%d/%d\n",
+    av_dlog(ts->stream, "sid=0x%x sec_num=%d/%d\n",
            h->id, h->sec_num, h->last_sec_num);
 
     if (h->tid != PMT_TID)
@@ -886,7 +1027,7 @@ static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len
         return;
     add_pid_to_pmt(ts, h->id, pcr_pid);
 
-    dprintf(ts->stream, "pcr_pid=0x%x\n", pcr_pid);
+    av_dlog(ts->stream, "pcr_pid=0x%x\n", pcr_pid);
 
     program_info_length = get16(&p, p_end) & 0xfff;
     if (program_info_length < 0)
@@ -895,11 +1036,20 @@ static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len
         uint8_t tag, len;
         tag = get8(&p, p_end);
         len = get8(&p, p_end);
+
+        av_dlog(ts->stream, "program tag: 0x%02x len=%d\n", tag, len);
+
         if(len > program_info_length - 2)
             //something else is broken, exit the program_descriptors_loop
             break;
         program_info_length -= len + 2;
-        if(tag == 0x05 && len >= 4) { // registration descriptor
+        if (tag == 0x1d) { // IOD descriptor
+            get8(&p, p_end); // scope
+            get8(&p, p_end); // label
+            len -= 2;
+            mp4_read_iods(ts->stream, p, len, &mp4_es_id,
+                          &mp4_dec_config_descr, &mp4_dec_config_descr_len);
+        } else if (tag == 0x05 && len >= 4) { // registration descriptor
             prog_reg_desc = bytestream_get_le32(&p);
             len -= 4;
         }
@@ -907,7 +1057,7 @@ static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len
     }
     p += program_info_length;
     if (p >= p_end)
-        return;
+        goto out;
 
     // stop parsing after pmt, we found header
     if (!ts->stream->nb_streams)
@@ -925,6 +1075,8 @@ static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len
         /* now create ffmpeg stream */
         if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
             pes = ts->pids[pid]->u.pes_filter.opaque;
+            if (!pes->st)
+                pes->st = av_new_stream(pes->stream, pes->pid);
             st = pes->st;
         } else {
             if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
@@ -934,7 +1086,7 @@ static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len
         }
 
         if (!st)
-            return;
+            goto out;
 
         if (!pes->stream_type)
             mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
@@ -950,61 +1102,10 @@ static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len
         if (desc_list_end > p_end)
             break;
         for(;;) {
-            desc_tag = get8(&p, desc_list_end);
-            if (desc_tag < 0)
-                break;
-            desc_len = get8(&p, desc_list_end);
-            if (desc_len < 0)
-                break;
-            desc_end = p + desc_len;
-            if (desc_end > desc_list_end)
+            if (ff_parse_mpeg2_descriptor(ts->stream, st, stream_type, &p, desc_list_end,
+                mp4_dec_config_descr_len, mp4_es_id, pid, mp4_dec_config_descr) < 0)
                 break;
 
-            dprintf(ts->stream, "tag: 0x%02x len=%d\n",
-                   desc_tag, desc_len);
-
-            if (st->codec->codec_id == CODEC_ID_NONE &&
-                stream_type == STREAM_TYPE_PRIVATE_DATA)
-                mpegts_find_stream_type(st, desc_tag, DESC_types);
-
-            switch(desc_tag) {
-            case 0x56: /* DVB teletext descriptor */
-                language[0] = get8(&p, desc_end);
-                language[1] = get8(&p, desc_end);
-                language[2] = get8(&p, desc_end);
-                language[3] = 0;
-                av_metadata_set2(&st->metadata, "language", language, 0);
-                break;
-            case 0x59: /* subtitling descriptor */
-                language[0] = get8(&p, desc_end);
-                language[1] = get8(&p, desc_end);
-                language[2] = get8(&p, desc_end);
-                language[3] = 0;
-                get8(&p, desc_end);
-                comp_page = get16(&p, desc_end);
-                anc_page = get16(&p, desc_end);
-                st->codec->sub_id = (anc_page << 16) | comp_page;
-                av_metadata_set2(&st->metadata, "language", language, 0);
-                break;
-            case 0x0a: /* ISO 639 language descriptor */
-                language[0] = get8(&p, desc_end);
-                language[1] = get8(&p, desc_end);
-                language[2] = get8(&p, desc_end);
-                language[3] = 0;
-                av_metadata_set2(&st->metadata, "language", language, 0);
-                break;
-            case 0x05: /* registration descriptor */
-                st->codec->codec_tag = bytestream_get_le32(&p);
-                dprintf(ts->stream, "reg_desc=%.4s\n", (char*)&st->codec->codec_tag);
-                if (st->codec->codec_id == CODEC_ID_NONE &&
-                    stream_type == STREAM_TYPE_PRIVATE_DATA)
-                    mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types);
-                break;
-            default:
-                break;
-            }
-            p = desc_end;
-
             if (prog_reg_desc == AV_RL32("HDMV") && stream_type == 0x83 && pes->sub_st) {
                 ff_program_add_stream_index(ts->stream, h->id, pes->sub_st->index);
                 pes->sub_st->codec->codec_tag = st->codec->codec_tag;
@@ -1012,8 +1113,9 @@ static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len
         }
         p = desc_list_end;
     }
-    /* all parameters are there */
-    mpegts_close_filter(ts, filter);
+
+ out:
+    av_free(mp4_dec_config_descr);
 }
 
 static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
@@ -1024,7 +1126,7 @@ static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len
     int sid, pmt_pid;
 
 #ifdef DEBUG
-    dprintf(ts->stream, "PAT:\n");
+    av_dlog(ts->stream, "PAT:\n");
     av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
 #endif
     p_end = section + section_len - 4;
@@ -1043,12 +1145,14 @@ static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len
         if (pmt_pid < 0)
             break;
 
-        dprintf(ts->stream, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
+        av_dlog(ts->stream, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
 
         if (sid == 0x0000) {
             /* NIT info */
         } else {
             av_new_program(ts->stream, sid);
+            if (ts->pids[pmt_pid])
+                mpegts_close_filter(ts, ts->pids[pmt_pid]);
             mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
             add_pat_entry(ts, sid);
             add_pid_to_pmt(ts, sid, 0); //add pat pid to program
@@ -1066,7 +1170,7 @@ static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len
     char *name, *provider_name;
 
 #ifdef DEBUG
-    dprintf(ts->stream, "SDT:\n");
+    av_dlog(ts->stream, "SDT:\n");
     av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
 #endif
 
@@ -1104,7 +1208,7 @@ static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len
             if (desc_end > desc_list_end)
                 break;
 
-            dprintf(ts->stream, "tag: 0x%02x len=%d\n",
+            av_dlog(ts->stream, "tag: 0x%02x len=%d\n",
                    desc_tag, desc_len);
 
             switch(desc_tag) {
@@ -1119,8 +1223,8 @@ static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len
                 if (name) {
                     AVProgram *program = av_new_program(ts->stream, sid);
                     if(program) {
-                        av_metadata_set2(&program->metadata, "name", name, 0);
-                        av_metadata_set2(&program->metadata, "provider_name", provider_name, 0);
+                        av_metadata_set2(&program->metadata, "service_name", name, 0);
+                        av_metadata_set2(&program->metadata, "service_provider", provider_name, 0);
                     }
                 }
                 av_free(name);
@@ -1177,7 +1281,7 @@ static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
     if (p >= p_end)
         return 0;
 
-    pos = url_ftell(ts->stream->pb);
+    pos = avio_tell(ts->stream->pb);
     ts->pos47= pos % ts->raw_packet_size;
 
     if (tss->type == MPEGTS_SECTION) {
@@ -1220,15 +1324,15 @@ static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
    get_packet_size() ?) */
 static int mpegts_resync(AVFormatContext *s)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int c, i;
 
     for(i = 0;i < MAX_RESYNC_SIZE; i++) {
-        c = url_fgetc(pb);
-        if (c < 0)
+        c = avio_r8(pb);
+        if (pb->eof_reached)
             return -1;
         if (c == 0x47) {
-            url_fseek(pb, -1, SEEK_CUR);
+            avio_seek(pb, -1, SEEK_CUR);
             return 0;
         }
     }
@@ -1240,17 +1344,17 @@ static int mpegts_resync(AVFormatContext *s)
 /* return -1 if error or EOF. Return 0 if OK. */
 static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int skip, len;
 
     for(;;) {
-        len = get_buffer(pb, buf, TS_PACKET_SIZE);
+        len = avio_read(pb, buf, TS_PACKET_SIZE);
         if (len != TS_PACKET_SIZE)
-            return AVERROR(EIO);
+            return len < 0 ? len : AVERROR_EOF;
         /* check paquet sync byte */
         if (buf[0] != 0x47) {
             /* find a new packet start */
-            url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
+            avio_seek(pb, -TS_PACKET_SIZE, SEEK_CUR);
             if (mpegts_resync(s) < 0)
                 return AVERROR(EAGAIN);
             else
@@ -1258,7 +1362,7 @@ static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size)
         } else {
             skip = raw_packet_size - TS_PACKET_SIZE;
             if (skip > 0)
-                url_fskip(pb, skip);
+                avio_skip(pb, skip);
             break;
         }
     }
@@ -1352,7 +1456,7 @@ static int mpegts_read_header(AVFormatContext *s,
                               AVFormatParameters *ap)
 {
     MpegTSContext *ts = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     uint8_t buf[5*1024];
     int len;
     int64_t pos;
@@ -1366,8 +1470,8 @@ static int mpegts_read_header(AVFormatContext *s,
     }
 
     /* read the first 1024 bytes to get packet size */
-    pos = url_ftell(pb);
-    len = get_buffer(pb, buf, sizeof(buf));
+    pos = avio_tell(pb);
+    len = avio_read(pb, buf, sizeof(buf));
     if (len != sizeof(buf))
         goto fail;
     ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
@@ -1376,11 +1480,12 @@ static int mpegts_read_header(AVFormatContext *s,
     ts->stream = s;
     ts->auto_guess = 0;
 
-    if (s->iformat == &mpegts_demuxer) {
+    if (s->iformat == &ff_mpegts_demuxer) {
         /* normal demux */
 
         /* first do a scaning to get all the services */
-        url_fseek(pb, pos, SEEK_SET);
+        if (avio_seek(pb, pos, SEEK_SET) < 0)
+            av_log(s, AV_LOG_ERROR, "Unable to seek back to the start\n");
 
         mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
 
@@ -1391,7 +1496,7 @@ static int mpegts_read_header(AVFormatContext *s,
 
         ts->auto_guess = 1;
 
-        dprintf(ts->stream, "tuning done\n");
+        av_dlog(ts->stream, "tuning done\n");
 
         s->ctx_flags |= AVFMTCTX_NOHEADER;
     } else {
@@ -1444,7 +1549,7 @@ static int mpegts_read_header(AVFormatContext *s,
 #endif
     }
 
-    url_fseek(pb, pos, SEEK_SET);
+    avio_seek(pb, pos, SEEK_SET);
     return 0;
  fail:
     return -1;
@@ -1463,7 +1568,7 @@ static int mpegts_raw_read_packet(AVFormatContext *s,
 
     if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
         return AVERROR(ENOMEM);
-    pkt->pos= url_ftell(s->pb);
+    pkt->pos= avio_tell(s->pb);
     ret = read_packet(s, pkt->data, ts->raw_packet_size);
     if (ret < 0) {
         av_free_packet(pkt);
@@ -1473,10 +1578,10 @@ static int mpegts_raw_read_packet(AVFormatContext *s,
         /* compute exact PCR for each packet */
         if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
             /* we read the next PCR (XXX: optimize it by using a bigger buffer */
-            pos = url_ftell(s->pb);
+            pos = avio_tell(s->pb);
             for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
-                url_fseek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
-                get_buffer(s->pb, pcr_buf, 12);
+                avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
+                avio_read(s->pb, pcr_buf, 12);
                 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
                     /* XXX: not precise enough */
                     ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
@@ -1484,7 +1589,7 @@ static int mpegts_raw_read_packet(AVFormatContext *s,
                     break;
                 }
             }
-            url_fseek(s->pb, pos, SEEK_SET);
+            avio_seek(s->pb, pos, SEEK_SET);
             /* no next PCR found: we use previous increment */
             ts->cur_pcr = pcr_h * 300 + pcr_l;
         }
@@ -1502,7 +1607,7 @@ static int mpegts_read_packet(AVFormatContext *s,
     MpegTSContext *ts = s->priv_data;
     int ret, i;
 
-    if (url_ftell(s->pb) != ts->last_pos) {
+    if (avio_tell(s->pb) != ts->last_pos) {
         /* seek detected, flush pes buffer */
         for (i = 0; i < NB_PID_MAX; i++) {
             if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
@@ -1531,7 +1636,7 @@ static int mpegts_read_packet(AVFormatContext *s,
         }
     }
 
-    ts->last_pos = url_ftell(s->pb);
+    ts->last_pos = avio_tell(s->pb);
 
     return ret;
 }
@@ -1560,8 +1665,8 @@ static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
     pos = ((*ppos  + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
     if (find_next) {
         for(;;) {
-            url_fseek(s->pb, pos, SEEK_SET);
-            if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
+            avio_seek(s->pb, pos, SEEK_SET);
+            if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
                 return AV_NOPTS_VALUE;
             if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
                 parse_pcr(&timestamp, &pcr_l, buf) == 0) {
@@ -1574,8 +1679,8 @@ static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
             pos -= ts->raw_packet_size;
             if (pos < 0)
                 return AV_NOPTS_VALUE;
-            url_fseek(s->pb, pos, SEEK_SET);
-            if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
+            avio_seek(s->pb, pos, SEEK_SET);
+            if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
                 return AV_NOPTS_VALUE;
             if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
                 parse_pcr(&timestamp, &pcr_l, buf) == 0) {
@@ -1682,17 +1787,17 @@ static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, in
     if(av_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
         return -1;
 
-    pos= url_ftell(s->pb);
+    pos= avio_tell(s->pb);
 
     for(;;) {
-        url_fseek(s->pb, pos, SEEK_SET);
-        if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
+        avio_seek(s->pb, pos, SEEK_SET);
+        if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
             return -1;
 //        pid = AV_RB16(buf + 1) & 0x1fff;
         if(buf[1] & 0x40) break;
         pos += ts->raw_packet_size;
     }
-    url_fseek(s->pb, pos, SEEK_SET);
+    avio_seek(s->pb, pos, SEEK_SET);
 
     return 0;
 }
@@ -1752,7 +1857,7 @@ void ff_mpegts_parse_close(MpegTSContext *ts)
     av_free(ts);
 }
 
-AVInputFormat mpegts_demuxer = {
+AVInputFormat ff_mpegts_demuxer = {
     "mpegts",
     NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
     sizeof(MpegTSContext),
@@ -1768,7 +1873,7 @@ AVInputFormat mpegts_demuxer = {
 #endif
 };
 
-AVInputFormat mpegtsraw_demuxer = {
+AVInputFormat ff_mpegtsraw_demuxer = {
     "mpegtsraw",
     NULL_IF_CONFIG_SMALL("MPEG-2 raw transport stream format"),
     sizeof(MpegTSContext),
diff --git a/libavformat/mpegts.h b/libavformat/mpegts.h
index 6be9b73..73ef2ed 100644
--- a/libavformat/mpegts.h
+++ b/libavformat/mpegts.h
@@ -2,20 +2,20 @@
  * MPEG2 transport stream defines
  * Copyright (c) 2003 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -48,6 +48,7 @@
 #define STREAM_TYPE_PRIVATE_SECTION 0x05
 #define STREAM_TYPE_PRIVATE_DATA    0x06
 #define STREAM_TYPE_AUDIO_AAC       0x0f
+#define STREAM_TYPE_AUDIO_AAC_LATM  0x11
 #define STREAM_TYPE_VIDEO_MPEG4     0x10
 #define STREAM_TYPE_VIDEO_H264      0x1b
 #define STREAM_TYPE_VIDEO_VC1       0xea
@@ -63,4 +64,22 @@ int ff_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
                            const uint8_t *buf, int len);
 void ff_mpegts_parse_close(MpegTSContext *ts);
 
+/**
+ * Parse an MPEG-2 descriptor
+ * @param[in] fc                    Format context (used for logging only)
+ * @param st                        Stream
+ * @param stream_type               STREAM_TYPE_xxx
+ * @param pp                        Descriptor buffer pointer
+ * @param desc_list_end             End of buffer
+ * @param mp4_dec_config_descr_len  Length of 'mp4_dec_config_descr', or zero if not present
+ * @param mp4_es_id
+ * @param pid
+ * @param mp4_dec_config_descr
+ * @return <0 to stop processing
+ */
+int ff_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type,
+                              const uint8_t **pp, const uint8_t *desc_list_end,
+                              int mp4_dec_config_descr_len, int mp4_es_id, int pid,
+                              uint8_t *mp4_dec_config_descr);
+
 #endif /* AVFORMAT_MPEGTS_H */
diff --git a/libavformat/mpegtsenc.c b/libavformat/mpegtsenc.c
index 3fc6dc1..2ffbd54 100644
--- a/libavformat/mpegtsenc.c
+++ b/libavformat/mpegtsenc.c
@@ -2,31 +2,34 @@
  * MPEG2 transport stream (aka DVB) muxer
  * Copyright (c) 2003 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "libavutil/bswap.h"
 #include "libavutil/crc.h"
+#include "libavutil/opt.h"
 #include "libavcodec/mpegvideo.h"
 #include "avformat.h"
 #include "internal.h"
 #include "mpegts.h"
 #include "adts.h"
 
+#define PCR_TIME_BASE 27000000
+
 /* write DVB SI sections */
 
 /*********************************************/
@@ -60,21 +63,48 @@ typedef struct MpegTSWrite {
     int nb_services;
     int onid;
     int tsid;
-    uint64_t cur_pcr;
+    int64_t first_pcr;
     int mux_rate; ///< set to 1 when VBR
+
+    int transport_stream_id;
+    int original_network_id;
+    int service_id;
+
+    int pmt_start_pid;
+    int start_pid;
 } MpegTSWrite;
 
+static const AVOption options[] = {
+    { "mpegts_transport_stream_id", "Set transport_stream_id field.",
+      offsetof(MpegTSWrite, transport_stream_id), FF_OPT_TYPE_INT, 0x0001, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM},
+    { "mpegts_original_network_id", "Set original_network_id field.",
+      offsetof(MpegTSWrite, original_network_id), FF_OPT_TYPE_INT, 0x0001, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM},
+    { "mpegts_service_id", "Set service_id field.",
+      offsetof(MpegTSWrite, service_id), FF_OPT_TYPE_INT, 0x0001, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM},
+    { "mpegts_pmt_start_pid", "Set the first pid of the PMT.",
+      offsetof(MpegTSWrite, pmt_start_pid), FF_OPT_TYPE_INT, 0x1000, 0x1000, 0x1f00, AV_OPT_FLAG_ENCODING_PARAM},
+    { "mpegts_start_pid", "Set the first pid.",
+      offsetof(MpegTSWrite, start_pid), FF_OPT_TYPE_INT, 0x0100, 0x0100, 0x0f00, AV_OPT_FLAG_ENCODING_PARAM},
+    { NULL },
+};
+
+static const AVClass mpegts_muxer_class = {
+    "MPEGTS muxer",
+    av_default_item_name,
+    options,
+    LIBAVUTIL_VERSION_INT,
+};
+
 /* NOTE: 4 bytes must be left at the end for the crc32 */
 static void mpegts_write_section(MpegTSSection *s, uint8_t *buf, int len)
 {
-    MpegTSWrite *ts = ((AVFormatContext*)s->opaque)->priv_data;
     unsigned int crc;
     unsigned char packet[TS_PACKET_SIZE];
     const unsigned char *buf_ptr;
     unsigned char *q;
     int first, b, len1, left;
 
-    crc = bswap_32(av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1, buf, len - 4));
+    crc = av_bswap32(av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1, buf, len - 4));
     buf[len - 4] = (crc >> 24) & 0xff;
     buf[len - 3] = (crc >> 16) & 0xff;
     buf[len - 2] = (crc >> 8) & 0xff;
@@ -109,8 +139,6 @@ static void mpegts_write_section(MpegTSSection *s, uint8_t *buf, int len)
 
         buf_ptr += len1;
         len -= len1;
-
-        ts->cur_pcr += TS_PACKET_SIZE*8*90000LL/ts->mux_rate;
     }
 }
 
@@ -129,6 +157,8 @@ static int mpegts_write_section1(MpegTSSection *s, int tid, int id,
 {
     uint8_t section[1024], *q;
     unsigned int tot_len;
+    /* reserved_future_use field must be set to 1 for SDT */
+    unsigned int flags = tid == SDT_TID ? 0xf000 : 0xb000;
 
     tot_len = 3 + 5 + len + 4;
     /* check if not too big */
@@ -137,7 +167,7 @@ static int mpegts_write_section1(MpegTSSection *s, int tid, int id,
 
     q = section;
     *q++ = tid;
-    put16(&q, 0xb000 | (len + 5 + 4)); /* 5 byte header + 4 byte CRC */
+    put16(&q, flags | (len + 5 + 4)); /* 5 byte header + 4 byte CRC */
     put16(&q, id);
     *q++ = 0xc1 | (version << 1); /* current_next_indicator = 1 */
     *q++ = sec_num;
@@ -151,16 +181,9 @@ static int mpegts_write_section1(MpegTSSection *s, int tid, int id,
 /*********************************************/
 /* mpegts writer */
 
-#define DEFAULT_PMT_START_PID   0x1000
-#define DEFAULT_START_PID       0x0100
-#define DEFAULT_PROVIDER_NAME   "FFmpeg"
+#define DEFAULT_PROVIDER_NAME   "Libav"
 #define DEFAULT_SERVICE_NAME    "Service01"
 
-/* default network id, transport stream and service identifiers */
-#define DEFAULT_ONID            0x0001
-#define DEFAULT_TSID            0x0001
-#define DEFAULT_SID             0x0001
-
 /* a PES packet header is generated every DEFAULT_PES_HEADER_FREQ packets */
 #define DEFAULT_PES_HEADER_FREQ 16
 #define DEFAULT_PES_PAYLOAD_SIZE ((DEFAULT_PES_HEADER_FREQ - 1) * 184 + 170)
@@ -242,6 +265,9 @@ static void mpegts_write_pmt(AVFormatContext *s, MpegTSService *service)
         case CODEC_ID_AAC:
             stream_type = STREAM_TYPE_AUDIO_AAC;
             break;
+        case CODEC_ID_AAC_LATM:
+            stream_type = STREAM_TYPE_AUDIO_AAC_LATM;
+            break;
         case CODEC_ID_AC3:
             stream_type = STREAM_TYPE_AUDIO_AC3;
             break;
@@ -257,13 +283,38 @@ static void mpegts_write_pmt(AVFormatContext *s, MpegTSService *service)
         /* write optional descriptors here */
         switch(st->codec->codec_type) {
         case AVMEDIA_TYPE_AUDIO:
-            if (lang && strlen(lang->value) == 3) {
+            if (lang) {
+                char *p;
+                char *next = lang->value;
+                uint8_t *len_ptr;
+
                 *q++ = 0x0a; /* ISO 639 language descriptor */
-                *q++ = 4;
-                *q++ = lang->value[0];
-                *q++ = lang->value[1];
-                *q++ = lang->value[2];
-                *q++ = 0; /* undefined type */
+                len_ptr = q++;
+                *len_ptr = 0;
+
+                for (p = lang->value; next && *len_ptr < 255 / 4 * 4; p = next + 1) {
+                    next = strchr(p, ',');
+                    if (strlen(p) != 3 && (!next || next != p + 3))
+                        continue; /* not a 3-letter code */
+
+                    *q++ = *p++;
+                    *q++ = *p++;
+                    *q++ = *p++;
+
+                if (st->disposition & AV_DISPOSITION_CLEAN_EFFECTS)
+                    *q++ = 0x01;
+                else if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
+                    *q++ = 0x02;
+                else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
+                    *q++ = 0x03;
+                else
+                    *q++ = 0; /* undefined type */
+
+                    *len_ptr += 4;
+                }
+
+                if (*len_ptr == 0)
+                    q -= 2; /* no language codes were written */
             }
             break;
         case AVMEDIA_TYPE_SUBTITLE:
@@ -276,8 +327,13 @@ static void mpegts_write_pmt(AVFormatContext *s, MpegTSService *service)
                 *q++ = language[1];
                 *q++ = language[2];
                 *q++ = 0x10; /* normal subtitles (0x20 = if hearing pb) */
-                put16(&q, 1); /* page id */
-                put16(&q, 1); /* ancillary page id */
+                if(st->codec->extradata_size == 4) {
+                    memcpy(q, st->codec->extradata, 4);
+                    q += 4;
+                } else {
+                    put16(&q, 1); /* page id */
+                    put16(&q, 1); /* ancillary page id */
+                }
             }
             break;
         case AVMEDIA_TYPE_VIDEO:
@@ -365,7 +421,7 @@ static MpegTSService *mpegts_add_service(MpegTSWrite *ts,
     service = av_mallocz(sizeof(MpegTSService));
     if (!service)
         return NULL;
-    service->pmt.pid = DEFAULT_PMT_START_PID + ts->nb_services - 1;
+    service->pmt.pid = ts->pmt_start_pid + ts->nb_services - 1;
     service->sid = sid;
     service->provider_name = av_strdup(provider_name);
     service->name = av_strdup(name);
@@ -377,7 +433,7 @@ static MpegTSService *mpegts_add_service(MpegTSWrite *ts,
 static void section_write_packet(MpegTSSection *s, const uint8_t *packet)
 {
     AVFormatContext *ctx = s->opaque;
-    put_buffer(ctx->pb, packet, TS_PACKET_SIZE);
+    avio_write(ctx->pb, packet, TS_PACKET_SIZE);
 }
 
 static int mpegts_write_header(AVFormatContext *s)
@@ -386,17 +442,22 @@ static int mpegts_write_header(AVFormatContext *s)
     MpegTSWriteStream *ts_st;
     MpegTSService *service;
     AVStream *st, *pcr_st = NULL;
-    AVMetadataTag *title;
-    int i;
+    AVMetadataTag *title, *provider;
+    int i, j;
     const char *service_name;
+    const char *provider_name;
+    int *pids;
 
-    ts->tsid = DEFAULT_TSID;
-    ts->onid = DEFAULT_ONID;
+    ts->tsid = ts->transport_stream_id;
+    ts->onid = ts->original_network_id;
     /* allocate a single DVB service */
-    title = av_metadata_get(s->metadata, "title", NULL, 0);
+    title = av_metadata_get(s->metadata, "service_name", NULL, 0);
+    if (!title)
+        title = av_metadata_get(s->metadata, "title", NULL, 0);
     service_name = title ? title->value : DEFAULT_SERVICE_NAME;
-    service = mpegts_add_service(ts, DEFAULT_SID,
-                                 DEFAULT_PROVIDER_NAME, service_name);
+    provider = av_metadata_get(s->metadata, "service_provider", NULL, 0);
+    provider_name = provider ? provider->value : DEFAULT_PROVIDER_NAME;
+    service = mpegts_add_service(ts, ts->service_id, provider_name, service_name);
     service->pmt.write_packet = section_write_packet;
     service->pmt.opaque = s;
     service->pmt.cc = 15;
@@ -411,15 +472,39 @@ static int mpegts_write_header(AVFormatContext *s)
     ts->sdt.write_packet = section_write_packet;
     ts->sdt.opaque = s;
 
+    pids = av_malloc(s->nb_streams * sizeof(*pids));
+    if (!pids)
+        return AVERROR(ENOMEM);
+
     /* assign pids to each stream */
     for(i = 0;i < s->nb_streams; i++) {
         st = s->streams[i];
+        av_set_pts_info(st, 33, 1, 90000);
         ts_st = av_mallocz(sizeof(MpegTSWriteStream));
         if (!ts_st)
             goto fail;
         st->priv_data = ts_st;
         ts_st->service = service;
-        ts_st->pid = DEFAULT_START_PID + i;
+        /* MPEG pid values < 16 are reserved. Applications which set st->id in
+         * this range are assigned a calculated pid. */
+        if (st->id < 16) {
+            ts_st->pid = ts->start_pid + i;
+        } else if (st->id < 0x1FFF) {
+            ts_st->pid = st->id;
+        } else {
+            av_log(s, AV_LOG_ERROR, "Invalid stream id %d, must be less than 8191\n", st->id);
+            goto fail;
+        }
+        if (ts_st->pid == service->pmt.pid) {
+            av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
+            goto fail;
+        }
+        for (j = 0; j < i; j++)
+            if (pids[j] == ts_st->pid) {
+                av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
+                goto fail;
+            }
+        pids[i] = ts_st->pid;
         ts_st->payload_pts = AV_NOPTS_VALUE;
         ts_st->payload_dts = AV_NOPTS_VALUE;
         ts_st->first_pts_check = 1;
@@ -441,6 +526,8 @@ static int mpegts_write_header(AVFormatContext *s)
         }
     }
 
+    av_free(pids);
+
     /* if no video stream, use the first stream as PCR */
     if (service->pcr_pid == 0x1fff && s->nb_streams > 0) {
         pcr_st = s->streams[0];
@@ -458,7 +545,7 @@ static int mpegts_write_header(AVFormatContext *s)
         ts->pat_packet_period      = (ts->mux_rate * PAT_RETRANS_TIME) /
             (TS_PACKET_SIZE * 8 * 1000);
 
-        ts->cur_pcr = av_rescale(s->max_delay, 90000, AV_TIME_BASE);
+        ts->first_pcr = av_rescale(s->max_delay, PCR_TIME_BASE, AV_TIME_BASE);
     } else {
         /* Arbitrary values, PAT/PMT could be written on key frames */
         ts->sdt_packet_period = 200;
@@ -484,18 +571,21 @@ static int mpegts_write_header(AVFormatContext *s)
     ts->pat_packet_count = ts->pat_packet_period-1;
     ts->sdt_packet_count = ts->sdt_packet_period-1;
 
-    av_log(s, AV_LOG_INFO,
-           "muxrate %d bps, pcr every %d pkts, "
+    if (ts->mux_rate == 1)
+        av_log(s, AV_LOG_INFO, "muxrate VBR, ");
+    else
+        av_log(s, AV_LOG_INFO, "muxrate %d, ", ts->mux_rate);
+    av_log(s, AV_LOG_INFO, "pcr every %d pkts, "
            "sdt every %d, pat/pmt every %d pkts\n",
-           ts->mux_rate, service->pcr_packet_period,
+           service->pcr_packet_period,
            ts->sdt_packet_period, ts->pat_packet_period);
 
-
-    put_flush_packet(s->pb);
+    avio_flush(s->pb);
 
     return 0;
 
  fail:
+    av_free(pids);
     for(i = 0;i < s->nb_streams; i++) {
         st = s->streams[i];
         av_free(st->priv_data);
@@ -522,10 +612,29 @@ static void retransmit_si_info(AVFormatContext *s)
     }
 }
 
+static int64_t get_pcr(const MpegTSWrite *ts, AVIOContext *pb)
+{
+    return av_rescale(avio_tell(pb) + 11, 8 * PCR_TIME_BASE, ts->mux_rate) +
+           ts->first_pcr;
+}
+
+static uint8_t* write_pcr_bits(uint8_t *buf, int64_t pcr)
+{
+    int64_t pcr_low = pcr % 300, pcr_high = pcr / 300;
+
+    *buf++ = pcr_high >> 25;
+    *buf++ = pcr_high >> 17;
+    *buf++ = pcr_high >> 9;
+    *buf++ = pcr_high >> 1;
+    *buf++ = pcr_high << 7 | pcr_low >> 8 | 0x7e;
+    *buf++ = pcr_low;
+
+    return buf;
+}
+
 /* Write a single null transport stream packet */
 static void mpegts_insert_null_packet(AVFormatContext *s)
 {
-    MpegTSWrite *ts = s->priv_data;
     uint8_t *q;
     uint8_t buf[TS_PACKET_SIZE];
 
@@ -535,8 +644,7 @@ static void mpegts_insert_null_packet(AVFormatContext *s)
     *q++ = 0xff;
     *q++ = 0x10;
     memset(q, 0x0FF, TS_PACKET_SIZE - (q - buf));
-    put_buffer(s->pb, buf, TS_PACKET_SIZE);
-    ts->cur_pcr += TS_PACKET_SIZE*8*90000LL/ts->mux_rate;
+    avio_write(s->pb, buf, TS_PACKET_SIZE);
 }
 
 /* Write a single transport stream packet with a PCR and no payload */
@@ -545,7 +653,6 @@ static void mpegts_insert_pcr_only(AVFormatContext *s, AVStream *st)
     MpegTSWrite *ts = s->priv_data;
     MpegTSWriteStream *ts_st = st->priv_data;
     uint8_t *q;
-    uint64_t pcr = ts->cur_pcr;
     uint8_t buf[TS_PACKET_SIZE];
 
     q = buf;
@@ -558,17 +665,11 @@ static void mpegts_insert_pcr_only(AVFormatContext *s, AVStream *st)
     *q++ = 0x10;               /* Adaptation flags: PCR present */
 
     /* PCR coded into 6 bytes */
-    *q++ = pcr >> 25;
-    *q++ = pcr >> 17;
-    *q++ = pcr >> 9;
-    *q++ = pcr >> 1;
-    *q++ = (pcr & 1) << 7;
-    *q++ = 0;
+    q = write_pcr_bits(q, get_pcr(ts, s->pb));
 
     /* stuffing bytes */
     memset(q, 0xFF, TS_PACKET_SIZE - (q - buf));
-    put_buffer(s->pb, buf, TS_PACKET_SIZE);
-    ts->cur_pcr += TS_PACKET_SIZE*8*90000LL/ts->mux_rate;
+    avio_write(s->pb, buf, TS_PACKET_SIZE);
 }
 
 static void write_pts(uint8_t *q, int fourbits, int64_t pts)
@@ -619,7 +720,7 @@ static void mpegts_write_pes(AVFormatContext *s, AVStream *st,
         }
 
         if (ts->mux_rate > 1 && dts != AV_NOPTS_VALUE &&
-            (dts - (int64_t)ts->cur_pcr) > delay) {
+            (dts - get_pcr(ts, s->pb)/300) > delay) {
             /* pcr insert gets priority over null packet insert */
             if (write_pcr)
                 mpegts_insert_pcr_only(s, st);
@@ -641,19 +742,14 @@ static void mpegts_write_pes(AVFormatContext *s, AVStream *st,
         if (write_pcr) {
             // add 11, pcr references the last byte of program clock reference base
             if (ts->mux_rate > 1)
-                pcr = ts->cur_pcr + (4+7)*8*90000LL / ts->mux_rate;
+                pcr = get_pcr(ts, s->pb);
             else
-                pcr = dts - delay;
-            if (dts != AV_NOPTS_VALUE && dts < pcr)
+                pcr = (dts - delay)*300;
+            if (dts != AV_NOPTS_VALUE && dts < pcr / 300)
                 av_log(s, AV_LOG_WARNING, "dts < pcr, TS is invalid\n");
             *q++ = 7; /* AFC length */
             *q++ = 0x10; /* flags: PCR present */
-            *q++ = pcr >> 25;
-            *q++ = pcr >> 17;
-            *q++ = pcr >> 9;
-            *q++ = pcr >> 1;
-            *q++ = (pcr & 1) << 7;
-            *q++ = 0;
+            q = write_pcr_bits(q, pcr);
         }
         if (is_start) {
             int pes_extension = 0;
@@ -669,7 +765,8 @@ static void mpegts_write_pes(AVFormatContext *s, AVStream *st,
                     *q++ = 0xe0;
             } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
                        (st->codec->codec_id == CODEC_ID_MP2 ||
-                        st->codec->codec_id == CODEC_ID_MP3)) {
+                        st->codec->codec_id == CODEC_ID_MP3 ||
+                        st->codec->codec_id == CODEC_ID_AAC)) {
                 *q++ = 0xc0;
             } else {
                 *q++ = 0xbd;
@@ -767,10 +864,9 @@ static void mpegts_write_pes(AVFormatContext *s, AVStream *st,
         memcpy(buf + TS_PACKET_SIZE - len, payload, len);
         payload += len;
         payload_size -= len;
-        put_buffer(s->pb, buf, TS_PACKET_SIZE);
-        ts->cur_pcr += TS_PACKET_SIZE*8*90000LL/ts->mux_rate;
+        avio_write(s->pb, buf, TS_PACKET_SIZE);
     }
-    put_flush_packet(s->pb);
+    avio_flush(s->pb);
 }
 
 static int mpegts_write_packet(AVFormatContext *s, AVPacket *pkt)
@@ -817,7 +913,7 @@ static int mpegts_write_packet(AVFormatContext *s, AVPacket *pkt)
             memcpy(data+6, pkt->data, pkt->size);
             AV_WB32(data, 0x00000001);
             data[4] = 0x09;
-            data[5] = 0xe0; // any slice type
+            data[5] = 0xf0; // any slice type (0xe) + rbsp stop one bit
             buf  = data;
             size = pkt->size+6;
         }
@@ -893,7 +989,7 @@ static int mpegts_write_end(AVFormatContext *s)
         }
         av_freep(&ts_st->adts);
     }
-    put_flush_packet(s->pb);
+    avio_flush(s->pb);
 
     for(i = 0; i < ts->nb_services; i++) {
         service = ts->services[i];
@@ -906,7 +1002,7 @@ static int mpegts_write_end(AVFormatContext *s)
     return 0;
 }
 
-AVOutputFormat mpegts_muxer = {
+AVOutputFormat ff_mpegts_muxer = {
     "mpegts",
     NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
     "video/x-mpegts",
@@ -917,4 +1013,5 @@ AVOutputFormat mpegts_muxer = {
     mpegts_write_header,
     mpegts_write_packet,
     mpegts_write_end,
+    .priv_class = &mpegts_muxer_class,
 };
diff --git a/libavformat/mpegvideodec.c b/libavformat/mpegvideodec.c
new file mode 100644
index 0000000..0669820
--- /dev/null
+++ b/libavformat/mpegvideodec.c
@@ -0,0 +1,67 @@
+/*
+ * RAW MPEG video demuxer
+ * Copyright (c) 2002-2003 Fabrice Bellard
+ * Copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "avformat.h"
+#include "rawdec.h"
+
+#define SEQ_START_CODE          0x000001b3
+#define GOP_START_CODE          0x000001b8
+#define PICTURE_START_CODE      0x00000100
+#define SLICE_START_CODE        0x00000101
+#define PACK_START_CODE         0x000001ba
+#define VIDEO_ID                0x000001e0
+#define AUDIO_ID                0x000001c0
+
+static int mpegvideo_probe(AVProbeData *p)
+{
+    uint32_t code= -1;
+    int pic=0, seq=0, slice=0, pspack=0, pes=0;
+    int i;
+
+    for(i=0; i<p->buf_size; i++){
+        code = (code<<8) + p->buf[i];
+        if ((code & 0xffffff00) == 0x100) {
+            switch(code){
+            case     SEQ_START_CODE:   seq++; break;
+            case PICTURE_START_CODE:   pic++; break;
+            case   SLICE_START_CODE: slice++; break;
+            case    PACK_START_CODE: pspack++; break;
+            }
+            if     ((code & 0x1f0) == VIDEO_ID)   pes++;
+            else if((code & 0x1e0) == AUDIO_ID)   pes++;
+        }
+    }
+    if(seq && seq*9<=pic*10 && pic*9<=slice*10 && !pspack && !pes)
+        return pic>1 ? AVPROBE_SCORE_MAX/2+1 : AVPROBE_SCORE_MAX/4; // +1 for .mpg
+    return 0;
+}
+
+AVInputFormat ff_mpegvideo_demuxer = {
+    "mpegvideo",
+    NULL_IF_CONFIG_SMALL("raw MPEG video"),
+    0,
+    mpegvideo_probe,
+    ff_raw_video_read_header,
+    ff_raw_read_partial_packet,
+    .flags= AVFMT_GENERIC_INDEX,
+    .value = CODEC_ID_MPEG1VIDEO,
+};
diff --git a/libavformat/mpjpeg.c b/libavformat/mpjpeg.c
index 8973877..ebb57bf 100644
--- a/libavformat/mpjpeg.c
+++ b/libavformat/mpjpeg.c
@@ -2,20 +2,20 @@
  * Multipart JPEG format
  * Copyright (c) 2000, 2001, 2002, 2003 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #include "avformat.h"
@@ -29,8 +29,8 @@ static int mpjpeg_write_header(AVFormatContext *s)
     uint8_t buf1[256];
 
     snprintf(buf1, sizeof(buf1), "--%s\n", BOUNDARY_TAG);
-    put_buffer(s->pb, buf1, strlen(buf1));
-    put_flush_packet(s->pb);
+    avio_write(s->pb, buf1, strlen(buf1));
+    avio_flush(s->pb);
     return 0;
 }
 
@@ -39,12 +39,12 @@ static int mpjpeg_write_packet(AVFormatContext *s, AVPacket *pkt)
     uint8_t buf1[256];
 
     snprintf(buf1, sizeof(buf1), "Content-type: image/jpeg\n\n");
-    put_buffer(s->pb, buf1, strlen(buf1));
-    put_buffer(s->pb, pkt->data, pkt->size);
+    avio_write(s->pb, buf1, strlen(buf1));
+    avio_write(s->pb, pkt->data, pkt->size);
 
     snprintf(buf1, sizeof(buf1), "\n--%s\n", BOUNDARY_TAG);
-    put_buffer(s->pb, buf1, strlen(buf1));
-    put_flush_packet(s->pb);
+    avio_write(s->pb, buf1, strlen(buf1));
+    avio_flush(s->pb);
     return 0;
 }
 
@@ -53,7 +53,7 @@ static int mpjpeg_write_trailer(AVFormatContext *s)
     return 0;
 }
 
-AVOutputFormat mpjpeg_muxer = {
+AVOutputFormat ff_mpjpeg_muxer = {
     "mpjpeg",
     NULL_IF_CONFIG_SMALL("MIME multipart JPEG format"),
     "multipart/x-mixed-replace;boundary=" BOUNDARY_TAG,
diff --git a/libavformat/msnwc_tcp.c b/libavformat/msnwc_tcp.c
index e548871..d9d8000 100644
--- a/libavformat/msnwc_tcp.c
+++ b/libavformat/msnwc_tcp.c
@@ -1,20 +1,20 @@
 /*
- * Copyright (C) 2008  Ramiro Polla <ramiro at lisha.ufsc.br>
+ * Copyright (C) 2008  Ramiro Polla
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -71,7 +71,7 @@ static int msnwc_tcp_probe(AVProbeData *p)
 
 static int msnwc_tcp_read_header(AVFormatContext *ctx, AVFormatParameters *ap)
 {
-    ByteIOContext *pb = ctx->pb;
+    AVIOContext *pb = ctx->pb;
     AVCodecContext *codec;
     AVStream *st;
 
@@ -88,9 +88,9 @@ static int msnwc_tcp_read_header(AVFormatContext *ctx, AVFormatParameters *ap)
 
     /* Some files start with "connected\r\n\r\n".
      * So skip until we find the first byte of struct size */
-    while(get_byte(pb) != HEADER_SIZE && !url_feof(pb));
+    while(avio_r8(pb) != HEADER_SIZE && !pb->eof_reached);
 
-    if(url_feof(pb)) {
+    if(pb->eof_reached) {
         av_log(ctx, AV_LOG_ERROR, "Could not find valid start.");
         return -1;
     }
@@ -100,23 +100,23 @@ static int msnwc_tcp_read_header(AVFormatContext *ctx, AVFormatParameters *ap)
 
 static int msnwc_tcp_read_packet(AVFormatContext *ctx, AVPacket *pkt)
 {
-    ByteIOContext *pb = ctx->pb;
+    AVIOContext *pb = ctx->pb;
     uint16_t keyframe;
     uint32_t size, timestamp;
 
-    url_fskip(pb, 1); /* one byte has been read ahead */
-    url_fskip(pb, 2);
-    url_fskip(pb, 2);
-    keyframe = get_le16(pb);
-    size = get_le32(pb);
-    url_fskip(pb, 4);
-    url_fskip(pb, 4);
-    timestamp = get_le32(pb);
+    avio_skip(pb, 1); /* one byte has been read ahead */
+    avio_skip(pb, 2);
+    avio_skip(pb, 2);
+    keyframe = avio_rl16(pb);
+    size = avio_rl32(pb);
+    avio_skip(pb, 4);
+    avio_skip(pb, 4);
+    timestamp = avio_rl32(pb);
 
     if(!size || av_get_packet(pb, pkt, size) != size)
         return -1;
 
-    url_fskip(pb, 1); /* Read ahead one byte of struct size like read_header */
+    avio_skip(pb, 1); /* Read ahead one byte of struct size like read_header */
 
     pkt->pts = timestamp;
     pkt->dts = timestamp;
@@ -130,7 +130,7 @@ static int msnwc_tcp_read_packet(AVFormatContext *ctx, AVPacket *pkt)
     return HEADER_SIZE + size;
 }
 
-AVInputFormat msnwc_tcp_demuxer = {
+AVInputFormat ff_msnwc_tcp_demuxer = {
     "msnwctcp",
     NULL_IF_CONFIG_SMALL("MSN TCP Webcam stream"),
     0,
diff --git a/libavformat/mtv.c b/libavformat/mtv.c
index 4eae1a1..92d38e1 100644
--- a/libavformat/mtv.c
+++ b/libavformat/mtv.c
@@ -2,20 +2,20 @@
  * mtv demuxer
  * Copyright (c) 2006 Reynaldo H. Verdejo Pinochet
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -79,21 +79,21 @@ static int mtv_probe(AVProbeData *p)
 static int mtv_read_header(AVFormatContext *s, AVFormatParameters *ap)
 {
     MTVDemuxContext *mtv = s->priv_data;
-    ByteIOContext   *pb  = s->pb;
+    AVIOContext   *pb  = s->pb;
     AVStream        *st;
     unsigned int    audio_subsegments;
 
-    url_fskip(pb, 3);
-    mtv->file_size         = get_le32(pb);
-    mtv->segments          = get_le32(pb);
-    url_fskip(pb, 32);
-    mtv->audio_identifier  = get_le24(pb);
-    mtv->audio_br          = get_le16(pb);
-    mtv->img_colorfmt      = get_le24(pb);
-    mtv->img_bpp           = get_byte(pb);
-    mtv->img_width         = get_le16(pb);
-    mtv->img_height        = get_le16(pb);
-    mtv->img_segment_size  = get_le16(pb);
+    avio_skip(pb, 3);
+    mtv->file_size         = avio_rl32(pb);
+    mtv->segments          = avio_rl32(pb);
+    avio_skip(pb, 32);
+    mtv->audio_identifier  = avio_rl24(pb);
+    mtv->audio_br          = avio_rl16(pb);
+    mtv->img_colorfmt      = avio_rl24(pb);
+    mtv->img_bpp           = avio_r8(pb);
+    mtv->img_width         = avio_rl16(pb);
+    mtv->img_height        = avio_rl16(pb);
+    mtv->img_segment_size  = avio_rl16(pb);
 
     /* Calculate width and height if missing from header */
 
@@ -105,8 +105,8 @@ static int mtv_read_header(AVFormatContext *s, AVFormatParameters *ap)
         mtv->img_height=mtv->img_segment_size / (mtv->img_bpp>>3)
                         / mtv->img_width;
 
-    url_fskip(pb, 4);
-    audio_subsegments = get_le16(pb);
+    avio_skip(pb, 4);
+    audio_subsegments = avio_rl16(pb);
     mtv->full_segment_size =
         audio_subsegments * (MTV_AUDIO_PADDING_SIZE + MTV_ASUBCHUNK_DATA_SIZE) +
         mtv->img_segment_size;
@@ -146,7 +146,7 @@ static int mtv_read_header(AVFormatContext *s, AVFormatParameters *ap)
 
     // Jump over header
 
-    if(url_fseek(pb, MTV_HEADER_SIZE, SEEK_SET) != MTV_HEADER_SIZE)
+    if(avio_seek(pb, MTV_HEADER_SIZE, SEEK_SET) != MTV_HEADER_SIZE)
         return AVERROR(EIO);
 
     return 0;
@@ -156,15 +156,15 @@ static int mtv_read_header(AVFormatContext *s, AVFormatParameters *ap)
 static int mtv_read_packet(AVFormatContext *s, AVPacket *pkt)
 {
     MTVDemuxContext *mtv = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int ret;
 #if !HAVE_BIGENDIAN
     int i;
 #endif
 
-    if((url_ftell(pb) - s->data_offset + mtv->img_segment_size) % mtv->full_segment_size)
+    if((avio_tell(pb) - s->data_offset + mtv->img_segment_size) % mtv->full_segment_size)
     {
-        url_fskip(pb, MTV_AUDIO_PADDING_SIZE);
+        avio_skip(pb, MTV_AUDIO_PADDING_SIZE);
 
         ret = av_get_packet(pb, pkt, MTV_ASUBCHUNK_DATA_SIZE);
         if(ret < 0)
@@ -188,7 +188,7 @@ static int mtv_read_packet(AVFormatContext *s, AVPacket *pkt)
          */
 
         for(i=0;i<mtv->img_segment_size/2;i++)
-            *((uint16_t *)pkt->data+i) = bswap_16(*((uint16_t *)pkt->data+i));
+            *((uint16_t *)pkt->data+i) = av_bswap16(*((uint16_t *)pkt->data+i));
 #endif
         pkt->stream_index = VIDEO_SID;
     }
@@ -196,7 +196,7 @@ static int mtv_read_packet(AVFormatContext *s, AVPacket *pkt)
     return ret;
 }
 
-AVInputFormat mtv_demuxer = {
+AVInputFormat ff_mtv_demuxer = {
     "MTV",
     NULL_IF_CONFIG_SMALL("MTV format"),
     sizeof(MTVDemuxContext),
diff --git a/libavformat/mvi.c b/libavformat/mvi.c
index 506976d..809cdf5 100644
--- a/libavformat/mvi.c
+++ b/libavformat/mvi.c
@@ -2,20 +2,20 @@
  * Motion Pixels MVI Demuxer
  * Copyright (c) 2008 Gregory Montoir (cyx at users.sourceforge.net)
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -27,7 +27,7 @@
 #define MVI_VIDEO_STREAM_INDEX 1
 
 typedef struct MviDemuxContext {
-    unsigned int (*get_int)(ByteIOContext *);
+    unsigned int (*get_int)(AVIOContext *);
     uint32_t audio_data_size;
     uint64_t audio_size_counter;
     uint64_t audio_frame_size;
@@ -38,7 +38,7 @@ typedef struct MviDemuxContext {
 static int read_header(AVFormatContext *s, AVFormatParameters *ap)
 {
     MviDemuxContext *mvi = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVStream *ast, *vst;
     unsigned int version, frames_count, msecs_per_frame, player_version;
 
@@ -53,20 +53,20 @@ static int read_header(AVFormatContext *s, AVFormatParameters *ap)
     vst->codec->extradata_size = 2;
     vst->codec->extradata = av_mallocz(2 + FF_INPUT_BUFFER_PADDING_SIZE);
 
-    version                  = get_byte(pb);
-    vst->codec->extradata[0] = get_byte(pb);
-    vst->codec->extradata[1] = get_byte(pb);
-    frames_count             = get_le32(pb);
-    msecs_per_frame          = get_le32(pb);
-    vst->codec->width        = get_le16(pb);
-    vst->codec->height       = get_le16(pb);
-    get_byte(pb);
-    ast->codec->sample_rate  = get_le16(pb);
-    mvi->audio_data_size     = get_le32(pb);
-    get_byte(pb);
-    player_version           = get_le32(pb);
-    get_le16(pb);
-    get_byte(pb);
+    version                  = avio_r8(pb);
+    vst->codec->extradata[0] = avio_r8(pb);
+    vst->codec->extradata[1] = avio_r8(pb);
+    frames_count             = avio_rl32(pb);
+    msecs_per_frame          = avio_rl32(pb);
+    vst->codec->width        = avio_rl16(pb);
+    vst->codec->height       = avio_rl16(pb);
+    avio_r8(pb);
+    ast->codec->sample_rate  = avio_rl16(pb);
+    mvi->audio_data_size     = avio_rl32(pb);
+    avio_r8(pb);
+    player_version           = avio_rl32(pb);
+    avio_rl16(pb);
+    avio_r8(pb);
 
     if (frames_count == 0 || mvi->audio_data_size == 0)
         return AVERROR_INVALIDDATA;
@@ -87,7 +87,7 @@ static int read_header(AVFormatContext *s, AVFormatParameters *ap)
     vst->codec->codec_type = AVMEDIA_TYPE_VIDEO;
     vst->codec->codec_id   = CODEC_ID_MOTIONPIXELS;
 
-    mvi->get_int = (vst->codec->width * vst->codec->height < (1 << 16)) ? get_le16 : get_le24;
+    mvi->get_int = (vst->codec->width * vst->codec->height < (1 << 16)) ? avio_rl16 : avio_rl24;
 
     mvi->audio_frame_size   = ((uint64_t)mvi->audio_data_size << MVI_FRAC_BITS) / frames_count;
     mvi->audio_size_counter = (ast->codec->sample_rate * 830 / mvi->audio_frame_size - 1) * mvi->audio_frame_size;
@@ -100,7 +100,7 @@ static int read_packet(AVFormatContext *s, AVPacket *pkt)
 {
     int ret, count;
     MviDemuxContext *mvi = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
 
     if (mvi->video_frame_size == 0) {
         mvi->video_frame_size = (mvi->get_int)(pb);
@@ -123,7 +123,7 @@ static int read_packet(AVFormatContext *s, AVPacket *pkt)
     return 0;
 }
 
-AVInputFormat mvi_demuxer = {
+AVInputFormat ff_mvi_demuxer = {
     "mvi",
     NULL_IF_CONFIG_SMALL("Motion Pixels MVI format"),
     sizeof(MviDemuxContext),
diff --git a/libavformat/mxf.c b/libavformat/mxf.c
index 452ee6d..6192368 100644
--- a/libavformat/mxf.c
+++ b/libavformat/mxf.c
@@ -2,20 +2,20 @@
  * MXF
  * Copyright (c) 2006 SmartJog S.A., Baptiste Coudurier <baptiste dot coudurier at smartjog dot com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -51,3 +51,47 @@ const MXFCodecUL ff_mxf_codec_uls[] = {
   //{ { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x02,0x03,0x02,0x1C,0x00 }, 15,    CODEC_ID_DOLBY_E }, /* Dolby-E */
     { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },  0,       CODEC_ID_NONE },
 };
+
+static const struct {
+    enum PixelFormat pix_fmt;
+    const char data[16];
+} ff_mxf_pixel_layouts[] = {
+    /**
+     * See SMPTE 377M E.2.46
+     *
+     * Note: Only RGB, palette based and "abnormal" YUV pixel formats like 4:2:2:4 go here.
+     *       For regular YUV, use CDCIPictureEssenceDescriptor.
+     *
+     * Note: Do not use these for encoding descriptors for little-endian formats until we
+     *       get samples or official word from SMPTE on how/if those can be encoded.
+     */
+    {PIX_FMT_ABGR,    {'A', 8,  'B', 8,  'G', 8, 'R', 8                 }},
+    {PIX_FMT_ARGB,    {'A', 8,  'R', 8,  'G', 8, 'B', 8                 }},
+    {PIX_FMT_BGR24,   {'B', 8,  'G', 8,  'R', 8                         }},
+    {PIX_FMT_BGRA,    {'B', 8,  'G', 8,  'R', 8, 'A', 8                 }},
+    {PIX_FMT_RGB24,   {'R', 8,  'G', 8,  'B', 8                         }},
+    {PIX_FMT_RGB444BE,{'F', 4,  'R', 4,  'G', 4, 'B', 4                 }},
+    {PIX_FMT_RGB48BE, {'R', 8,  'r', 8,  'G', 8, 'g', 8, 'B', 8, 'b', 8 }},
+    {PIX_FMT_RGB48BE, {'R', 16, 'G', 16, 'B', 16                        }},
+    {PIX_FMT_RGB48LE, {'r', 8,  'R', 8,  'g', 8, 'G', 8, 'b', 8, 'B', 8 }},
+    {PIX_FMT_RGB555BE,{'F', 1,  'R', 5,  'G', 5, 'B', 5                 }},
+    {PIX_FMT_RGB565BE,{'R', 5,  'G', 6,  'B', 5                         }},
+    {PIX_FMT_RGBA,    {'R', 8,  'G', 8,  'B', 8, 'A', 8                 }},
+    {PIX_FMT_PAL8,    {'P', 8                                           }},
+};
+
+static const int num_pixel_layouts = sizeof(ff_mxf_pixel_layouts) / sizeof(*ff_mxf_pixel_layouts);
+
+int ff_mxf_decode_pixel_layout(const char pixel_layout[16], enum PixelFormat *pix_fmt)
+{
+    int x;
+
+    for(x = 0; x < num_pixel_layouts; x++) {
+        if (!memcmp(pixel_layout, ff_mxf_pixel_layouts[x].data, 16)) {
+            *pix_fmt = ff_mxf_pixel_layouts[x].pix_fmt;
+            return 0;
+        }
+    }
+
+    return -1;
+}
diff --git a/libavformat/mxf.h b/libavformat/mxf.h
index 99553a5..beb6628 100644
--- a/libavformat/mxf.h
+++ b/libavformat/mxf.h
@@ -2,20 +2,20 @@
  * MXF
  * Copyright (c) 2006 SmartJog S.A., Baptiste Coudurier <baptiste dot coudurier at smartjog dot com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #ifndef AVFORMAT_MXF_H
@@ -61,11 +61,9 @@ typedef struct {
 extern const MXFCodecUL ff_mxf_data_definition_uls[];
 extern const MXFCodecUL ff_mxf_codec_uls[];
 
-#ifdef DEBUG
-#define PRINT_KEY(pc, s, x) dprintf(pc, "%s %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X\n", s, \
+int ff_mxf_decode_pixel_layout(const char pixel_layout[16], enum PixelFormat *pix_fmt);
+
+#define PRINT_KEY(pc, s, x) av_dlog(pc, "%s %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X\n", s, \
                              (x)[0], (x)[1], (x)[2], (x)[3], (x)[4], (x)[5], (x)[6], (x)[7], (x)[8], (x)[9], (x)[10], (x)[11], (x)[12], (x)[13], (x)[14], (x)[15])
-#else
-#define PRINT_KEY(pc, s, x)
-#endif
 
 #endif /* AVFORMAT_MXF_H */
diff --git a/libavformat/mxfdec.c b/libavformat/mxfdec.c
index 168fd8d..39c7fea 100644
--- a/libavformat/mxfdec.c
+++ b/libavformat/mxfdec.c
@@ -2,20 +2,20 @@
  * MXF demuxer.
  * Copyright (c) 2006 SmartJog S.A., Baptiste Coudurier <baptiste dot coudurier at smartjog dot com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -101,6 +101,7 @@ typedef struct {
     int linked_track_id;
     uint8_t *extradata;
     int extradata_size;
+    enum PixelFormat pix_fmt;
 } MXFDescriptor;
 
 typedef struct {
@@ -139,9 +140,11 @@ enum MXFWrappingScheme {
     Clip,
 };
 
+typedef int MXFMetadataReadFunc(void *arg, AVIOContext *pb, int tag, int size, UID uid);
+
 typedef struct {
     const UID key;
-    int (*read)();
+    MXFMetadataReadFunc *read;
     int ctx_size;
     enum MXFMetadataSetType type;
 } MXFMetadataReadTableEntry;
@@ -158,9 +161,9 @@ static const uint8_t mxf_sony_mpeg4_extradata[]            = { 0x06,0x0e,0x2b,0x
 
 #define IS_KLV_KEY(x, y) (!memcmp(x, y, sizeof(y)))
 
-static int64_t klv_decode_ber_length(ByteIOContext *pb)
+static int64_t klv_decode_ber_length(AVIOContext *pb)
 {
-    uint64_t size = get_byte(pb);
+    uint64_t size = avio_r8(pb);
     if (size & 0x80) { /* long form */
         int bytes_num = size & 0x7f;
         /* SMPTE 379M 5.3.4 guarantee that bytes_num must not exceed 8 bytes */
@@ -168,16 +171,16 @@ static int64_t klv_decode_ber_length(ByteIOContext *pb)
             return -1;
         size = 0;
         while (bytes_num--)
-            size = size << 8 | get_byte(pb);
+            size = size << 8 | avio_r8(pb);
     }
     return size;
 }
 
-static int mxf_read_sync(ByteIOContext *pb, const uint8_t *key, unsigned size)
+static int mxf_read_sync(AVIOContext *pb, const uint8_t *key, unsigned size)
 {
     int i, b;
-    for (i = 0; i < size && !url_feof(pb); i++) {
-        b = get_byte(pb);
+    for (i = 0; i < size && !pb->eof_reached; i++) {
+        b = avio_r8(pb);
         if (b == key[0])
             i = 0;
         else if (b != key[i])
@@ -186,13 +189,13 @@ static int mxf_read_sync(ByteIOContext *pb, const uint8_t *key, unsigned size)
     return i == size;
 }
 
-static int klv_read_packet(KLVPacket *klv, ByteIOContext *pb)
+static int klv_read_packet(KLVPacket *klv, AVIOContext *pb)
 {
     if (!mxf_read_sync(pb, mxf_klv_key, 4))
         return -1;
-    klv->offset = url_ftell(pb) - 4;
+    klv->offset = avio_tell(pb) - 4;
     memcpy(klv->key, mxf_klv_key, 4);
-    get_buffer(pb, klv->key + 4, 12);
+    avio_read(pb, klv->key + 4, 12);
     klv->length = klv_decode_ber_length(pb);
     return klv->length == -1 ? -1 : 0;
 }
@@ -212,7 +215,7 @@ static int mxf_get_stream_index(AVFormatContext *s, KLVPacket *klv)
 }
 
 /* XXX: use AVBitStreamFilter */
-static int mxf_get_d10_aes3_packet(ByteIOContext *pb, AVStream *st, AVPacket *pkt, int64_t length)
+static int mxf_get_d10_aes3_packet(AVIOContext *pb, AVStream *st, AVPacket *pkt, int64_t length)
 {
     const uint8_t *buf_ptr, *end_ptr;
     uint8_t *data_ptr;
@@ -221,7 +224,7 @@ static int mxf_get_d10_aes3_packet(ByteIOContext *pb, AVStream *st, AVPacket *pk
     if (length > 61444) /* worst case PAL 1920 samples 8 channels */
         return -1;
     av_new_packet(pkt, length);
-    get_buffer(pb, pkt->data, length);
+    avio_read(pb, pkt->data, length);
     data_ptr = pkt->data;
     end_ptr = pkt->data + length;
     buf_ptr = pkt->data + 4; /* skip SMPTE 331M header */
@@ -243,8 +246,8 @@ static int mxf_decrypt_triplet(AVFormatContext *s, AVPacket *pkt, KLVPacket *klv
 {
     static const uint8_t checkv[16] = {0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b};
     MXFContext *mxf = s->priv_data;
-    ByteIOContext *pb = s->pb;
-    int64_t end = url_ftell(pb) + klv->length;
+    AVIOContext *pb = s->pb;
+    int64_t end = avio_tell(pb) + klv->length;
     uint64_t size;
     uint64_t orig_size;
     uint64_t plaintext_size;
@@ -259,13 +262,13 @@ static int mxf_decrypt_triplet(AVFormatContext *s, AVPacket *pkt, KLVPacket *klv
         av_aes_init(mxf->aesc, s->key, 128, 1);
     }
     // crypto context
-    url_fskip(pb, klv_decode_ber_length(pb));
+    avio_skip(pb, klv_decode_ber_length(pb));
     // plaintext offset
     klv_decode_ber_length(pb);
-    plaintext_size = get_be64(pb);
+    plaintext_size = avio_rb64(pb);
     // source klv key
     klv_decode_ber_length(pb);
-    get_buffer(pb, klv->key, 16);
+    avio_read(pb, klv->key, 16);
     if (!IS_KLV_KEY(klv, mxf_essence_element_key))
         return -1;
     index = mxf_get_stream_index(s, klv);
@@ -273,15 +276,15 @@ static int mxf_decrypt_triplet(AVFormatContext *s, AVPacket *pkt, KLVPacket *klv
         return -1;
     // source size
     klv_decode_ber_length(pb);
-    orig_size = get_be64(pb);
+    orig_size = avio_rb64(pb);
     if (orig_size < plaintext_size)
         return -1;
     // enc. code
     size = klv_decode_ber_length(pb);
     if (size < 32 || size - 32 < orig_size)
         return -1;
-    get_buffer(pb, ivec, 16);
-    get_buffer(pb, tmpbuf, 16);
+    avio_read(pb, ivec, 16);
+    avio_read(pb, tmpbuf, 16);
     if (mxf->aesc)
         av_aes_crypt(mxf->aesc, tmpbuf, tmpbuf, 1, ivec, 1);
     if (memcmp(tmpbuf, checkv, 16))
@@ -294,7 +297,7 @@ static int mxf_decrypt_triplet(AVFormatContext *s, AVPacket *pkt, KLVPacket *klv
                      &pkt->data[plaintext_size], size >> 4, ivec, 1);
     pkt->size = orig_size;
     pkt->stream_index = index;
-    url_fskip(pb, end - url_ftell(pb));
+    avio_skip(pb, end - avio_tell(pb));
     return 0;
 }
 
@@ -302,11 +305,11 @@ static int mxf_read_packet(AVFormatContext *s, AVPacket *pkt)
 {
     KLVPacket klv;
 
-    while (!url_feof(s->pb)) {
+    while (!s->pb->eof_reached) {
         if (klv_read_packet(&klv, s->pb) < 0)
             return -1;
         PRINT_KEY(s, "read packet", klv.key);
-        dprintf(s, "size %lld offset %#llx\n", klv.length, klv.offset);
+        av_dlog(s, "size %lld offset %#llx\n", klv.length, klv.offset);
         if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key)) {
             int res = mxf_decrypt_triplet(s, pkt, &klv);
             if (res < 0) {
@@ -336,16 +339,16 @@ static int mxf_read_packet(AVFormatContext *s, AVPacket *pkt)
             return 0;
         } else
         skip:
-            url_fskip(s->pb, klv.length);
+            avio_skip(s->pb, klv.length);
     }
     return AVERROR_EOF;
 }
 
-static int mxf_read_primer_pack(MXFContext *mxf)
+static int mxf_read_primer_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid)
 {
-    ByteIOContext *pb = mxf->fc->pb;
-    int item_num = get_be32(pb);
-    int item_len = get_be32(pb);
+    MXFContext *mxf = arg;
+    int item_num = avio_rb32(pb);
+    int item_len = avio_rb32(pb);
 
     if (item_len != 18) {
         av_log(mxf->fc, AV_LOG_ERROR, "unsupported primer pack item length\n");
@@ -357,7 +360,7 @@ static int mxf_read_primer_pack(MXFContext *mxf)
     mxf->local_tags = av_malloc(item_num*item_len);
     if (!mxf->local_tags)
         return -1;
-    get_buffer(pb, mxf->local_tags, item_num*item_len);
+    avio_read(pb, mxf->local_tags, item_num*item_len);
     return 0;
 }
 
@@ -373,218 +376,222 @@ static int mxf_add_metadata_set(MXFContext *mxf, void *metadata_set)
     return 0;
 }
 
-static int mxf_read_cryptographic_context(MXFCryptoContext *cryptocontext, ByteIOContext *pb, int tag, int size, UID uid)
+static int mxf_read_cryptographic_context(void *arg, AVIOContext *pb, int tag, int size, UID uid)
 {
+    MXFCryptoContext *cryptocontext = arg;
     if (size != 16)
         return -1;
     if (IS_KLV_KEY(uid, mxf_crypto_source_container_ul))
-        get_buffer(pb, cryptocontext->source_container_ul, 16);
+        avio_read(pb, cryptocontext->source_container_ul, 16);
     return 0;
 }
 
-static int mxf_read_content_storage(MXFContext *mxf, ByteIOContext *pb, int tag)
+static int mxf_read_content_storage(void *arg, AVIOContext *pb, int tag, int size, UID uid)
 {
+    MXFContext *mxf = arg;
     switch (tag) {
     case 0x1901:
-        mxf->packages_count = get_be32(pb);
+        mxf->packages_count = avio_rb32(pb);
         if (mxf->packages_count >= UINT_MAX / sizeof(UID))
             return -1;
         mxf->packages_refs = av_malloc(mxf->packages_count * sizeof(UID));
         if (!mxf->packages_refs)
             return -1;
-        url_fskip(pb, 4); /* useless size of objects, always 16 according to specs */
-        get_buffer(pb, (uint8_t *)mxf->packages_refs, mxf->packages_count * sizeof(UID));
+        avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
+        avio_read(pb, (uint8_t *)mxf->packages_refs, mxf->packages_count * sizeof(UID));
         break;
     }
     return 0;
 }
 
-static int mxf_read_source_clip(MXFStructuralComponent *source_clip, ByteIOContext *pb, int tag)
+static int mxf_read_source_clip(void *arg, AVIOContext *pb, int tag, int size, UID uid)
 {
+    MXFStructuralComponent *source_clip = arg;
     switch(tag) {
     case 0x0202:
-        source_clip->duration = get_be64(pb);
+        source_clip->duration = avio_rb64(pb);
         break;
     case 0x1201:
-        source_clip->start_position = get_be64(pb);
+        source_clip->start_position = avio_rb64(pb);
         break;
     case 0x1101:
         /* UMID, only get last 16 bytes */
-        url_fskip(pb, 16);
-        get_buffer(pb, source_clip->source_package_uid, 16);
+        avio_skip(pb, 16);
+        avio_read(pb, source_clip->source_package_uid, 16);
         break;
     case 0x1102:
-        source_clip->source_track_id = get_be32(pb);
+        source_clip->source_track_id = avio_rb32(pb);
         break;
     }
     return 0;
 }
 
-static int mxf_read_material_package(MXFPackage *package, ByteIOContext *pb, int tag)
+static int mxf_read_material_package(void *arg, AVIOContext *pb, int tag, int size, UID uid)
 {
+    MXFPackage *package = arg;
     switch(tag) {
     case 0x4403:
-        package->tracks_count = get_be32(pb);
+        package->tracks_count = avio_rb32(pb);
         if (package->tracks_count >= UINT_MAX / sizeof(UID))
             return -1;
         package->tracks_refs = av_malloc(package->tracks_count * sizeof(UID));
         if (!package->tracks_refs)
             return -1;
-        url_fskip(pb, 4); /* useless size of objects, always 16 according to specs */
-        get_buffer(pb, (uint8_t *)package->tracks_refs, package->tracks_count * sizeof(UID));
+        avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
+        avio_read(pb, (uint8_t *)package->tracks_refs, package->tracks_count * sizeof(UID));
         break;
     }
     return 0;
 }
 
-static int mxf_read_track(MXFTrack *track, ByteIOContext *pb, int tag)
+static int mxf_read_track(void *arg, AVIOContext *pb, int tag, int size, UID uid)
 {
+    MXFTrack *track = arg;
     switch(tag) {
     case 0x4801:
-        track->track_id = get_be32(pb);
+        track->track_id = avio_rb32(pb);
         break;
     case 0x4804:
-        get_buffer(pb, track->track_number, 4);
+        avio_read(pb, track->track_number, 4);
         break;
     case 0x4B01:
-        track->edit_rate.den = get_be32(pb);
-        track->edit_rate.num = get_be32(pb);
+        track->edit_rate.den = avio_rb32(pb);
+        track->edit_rate.num = avio_rb32(pb);
         break;
     case 0x4803:
-        get_buffer(pb, track->sequence_ref, 16);
+        avio_read(pb, track->sequence_ref, 16);
         break;
     }
     return 0;
 }
 
-static int mxf_read_sequence(MXFSequence *sequence, ByteIOContext *pb, int tag)
+static int mxf_read_sequence(void *arg, AVIOContext *pb, int tag, int size, UID uid)
 {
+    MXFSequence *sequence = arg;
     switch(tag) {
     case 0x0202:
-        sequence->duration = get_be64(pb);
+        sequence->duration = avio_rb64(pb);
         break;
     case 0x0201:
-        get_buffer(pb, sequence->data_definition_ul, 16);
+        avio_read(pb, sequence->data_definition_ul, 16);
         break;
     case 0x1001:
-        sequence->structural_components_count = get_be32(pb);
+        sequence->structural_components_count = avio_rb32(pb);
         if (sequence->structural_components_count >= UINT_MAX / sizeof(UID))
             return -1;
         sequence->structural_components_refs = av_malloc(sequence->structural_components_count * sizeof(UID));
         if (!sequence->structural_components_refs)
             return -1;
-        url_fskip(pb, 4); /* useless size of objects, always 16 according to specs */
-        get_buffer(pb, (uint8_t *)sequence->structural_components_refs, sequence->structural_components_count * sizeof(UID));
+        avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
+        avio_read(pb, (uint8_t *)sequence->structural_components_refs, sequence->structural_components_count * sizeof(UID));
         break;
     }
     return 0;
 }
 
-static int mxf_read_source_package(MXFPackage *package, ByteIOContext *pb, int tag)
+static int mxf_read_source_package(void *arg, AVIOContext *pb, int tag, int size, UID uid)
 {
+    MXFPackage *package = arg;
     switch(tag) {
     case 0x4403:
-        package->tracks_count = get_be32(pb);
+        package->tracks_count = avio_rb32(pb);
         if (package->tracks_count >= UINT_MAX / sizeof(UID))
             return -1;
         package->tracks_refs = av_malloc(package->tracks_count * sizeof(UID));
         if (!package->tracks_refs)
             return -1;
-        url_fskip(pb, 4); /* useless size of objects, always 16 according to specs */
-        get_buffer(pb, (uint8_t *)package->tracks_refs, package->tracks_count * sizeof(UID));
+        avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
+        avio_read(pb, (uint8_t *)package->tracks_refs, package->tracks_count * sizeof(UID));
         break;
     case 0x4401:
         /* UMID, only get last 16 bytes */
-        url_fskip(pb, 16);
-        get_buffer(pb, package->package_uid, 16);
+        avio_skip(pb, 16);
+        avio_read(pb, package->package_uid, 16);
         break;
     case 0x4701:
-        get_buffer(pb, package->descriptor_ref, 16);
+        avio_read(pb, package->descriptor_ref, 16);
         break;
     }
     return 0;
 }
 
-static int mxf_read_index_table_segment(MXFIndexTableSegment *segment, ByteIOContext *pb, int tag)
+static int mxf_read_index_table_segment(void *arg, AVIOContext *pb, int tag, int size, UID uid)
 {
     switch(tag) {
-    case 0x3F05: dprintf(NULL, "EditUnitByteCount %d\n", get_be32(pb)); break;
-    case 0x3F06: dprintf(NULL, "IndexSID %d\n", get_be32(pb)); break;
-    case 0x3F07: dprintf(NULL, "BodySID %d\n", get_be32(pb)); break;
-    case 0x3F0B: dprintf(NULL, "IndexEditRate %d/%d\n", get_be32(pb), get_be32(pb)); break;
-    case 0x3F0C: dprintf(NULL, "IndexStartPosition %lld\n", get_be64(pb)); break;
-    case 0x3F0D: dprintf(NULL, "IndexDuration %lld\n", get_be64(pb)); break;
+    case 0x3F05: av_dlog(NULL, "EditUnitByteCount %d\n", avio_rb32(pb)); break;
+    case 0x3F06: av_dlog(NULL, "IndexSID %d\n", avio_rb32(pb)); break;
+    case 0x3F07: av_dlog(NULL, "BodySID %d\n", avio_rb32(pb)); break;
+    case 0x3F0B: av_dlog(NULL, "IndexEditRate %d/%d\n", avio_rb32(pb), avio_rb32(pb)); break;
+    case 0x3F0C: av_dlog(NULL, "IndexStartPosition %lld\n", avio_rb64(pb)); break;
+    case 0x3F0D: av_dlog(NULL, "IndexDuration %lld\n", avio_rb64(pb)); break;
     }
     return 0;
 }
 
-static void mxf_read_pixel_layout(ByteIOContext *pb, MXFDescriptor *descriptor)
+static void mxf_read_pixel_layout(AVIOContext *pb, MXFDescriptor *descriptor)
 {
-    int code;
+    int code, value, ofs = 0;
+    char layout[16] = {0};
 
     do {
-        code = get_byte(pb);
-        dprintf(NULL, "pixel layout: code %#x\n", code);
-        switch (code) {
-        case 0x52: /* R */
-            descriptor->bits_per_sample += get_byte(pb);
-            break;
-        case 0x47: /* G */
-            descriptor->bits_per_sample += get_byte(pb);
-            break;
-        case 0x42: /* B */
-            descriptor->bits_per_sample += get_byte(pb);
-            break;
-        default:
-            get_byte(pb);
+        code = avio_r8(pb);
+        value = avio_r8(pb);
+        av_dlog(NULL, "pixel layout: code %#x\n", code);
+
+        if (ofs < 16) {
+            layout[ofs++] = code;
+            layout[ofs++] = value;
         }
     } while (code != 0); /* SMPTE 377M E.2.46 */
+
+    ff_mxf_decode_pixel_layout(layout, &descriptor->pix_fmt);
 }
 
-static int mxf_read_generic_descriptor(MXFDescriptor *descriptor, ByteIOContext *pb, int tag, int size, UID uid)
+static int mxf_read_generic_descriptor(void *arg, AVIOContext *pb, int tag, int size, UID uid)
 {
+    MXFDescriptor *descriptor = arg;
     switch(tag) {
     case 0x3F01:
-        descriptor->sub_descriptors_count = get_be32(pb);
+        descriptor->sub_descriptors_count = avio_rb32(pb);
         if (descriptor->sub_descriptors_count >= UINT_MAX / sizeof(UID))
             return -1;
         descriptor->sub_descriptors_refs = av_malloc(descriptor->sub_descriptors_count * sizeof(UID));
         if (!descriptor->sub_descriptors_refs)
             return -1;
-        url_fskip(pb, 4); /* useless size of objects, always 16 according to specs */
-        get_buffer(pb, (uint8_t *)descriptor->sub_descriptors_refs, descriptor->sub_descriptors_count * sizeof(UID));
+        avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
+        avio_read(pb, (uint8_t *)descriptor->sub_descriptors_refs, descriptor->sub_descriptors_count * sizeof(UID));
         break;
     case 0x3004:
-        get_buffer(pb, descriptor->essence_container_ul, 16);
+        avio_read(pb, descriptor->essence_container_ul, 16);
         break;
     case 0x3006:
-        descriptor->linked_track_id = get_be32(pb);
+        descriptor->linked_track_id = avio_rb32(pb);
         break;
     case 0x3201: /* PictureEssenceCoding */
-        get_buffer(pb, descriptor->essence_codec_ul, 16);
+        avio_read(pb, descriptor->essence_codec_ul, 16);
         break;
     case 0x3203:
-        descriptor->width = get_be32(pb);
+        descriptor->width = avio_rb32(pb);
         break;
     case 0x3202:
-        descriptor->height = get_be32(pb);
+        descriptor->height = avio_rb32(pb);
         break;
     case 0x320E:
-        descriptor->aspect_ratio.num = get_be32(pb);
-        descriptor->aspect_ratio.den = get_be32(pb);
+        descriptor->aspect_ratio.num = avio_rb32(pb);
+        descriptor->aspect_ratio.den = avio_rb32(pb);
         break;
     case 0x3D03:
-        descriptor->sample_rate.num = get_be32(pb);
-        descriptor->sample_rate.den = get_be32(pb);
+        descriptor->sample_rate.num = avio_rb32(pb);
+        descriptor->sample_rate.den = avio_rb32(pb);
         break;
     case 0x3D06: /* SoundEssenceCompression */
-        get_buffer(pb, descriptor->essence_codec_ul, 16);
+        avio_read(pb, descriptor->essence_codec_ul, 16);
         break;
     case 0x3D07:
-        descriptor->channels = get_be32(pb);
+        descriptor->channels = avio_rb32(pb);
         break;
     case 0x3D01:
-        descriptor->bits_per_sample = get_be32(pb);
+        descriptor->bits_per_sample = avio_rb32(pb);
         break;
     case 0x3401:
         mxf_read_pixel_layout(pb, descriptor);
@@ -596,7 +603,7 @@ static int mxf_read_generic_descriptor(MXFDescriptor *descriptor, ByteIOContext
             if (!descriptor->extradata)
                 return -1;
             descriptor->extradata_size = size;
-            get_buffer(pb, descriptor->extradata, size);
+            avio_read(pb, descriptor->extradata, size);
         }
         break;
     }
@@ -659,7 +666,7 @@ static int mxf_parse_structural_metadata(MXFContext *mxf)
     MXFPackage *temp_package = NULL;
     int i, j, k;
 
-    dprintf(mxf->fc, "metadata sets count %d\n", mxf->metadata_sets_count);
+    av_dlog(mxf->fc, "metadata sets count %d\n", mxf->metadata_sets_count);
     /* TODO: handle multiple material packages (OP3x) */
     for (i = 0; i < mxf->packages_count; i++) {
         material_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[i], MaterialPackage);
@@ -801,7 +808,8 @@ static int mxf_parse_structural_metadata(MXFContext *mxf)
                 st->codec->codec_id = container_ul->id;
             st->codec->width = descriptor->width;
             st->codec->height = descriptor->height;
-            st->codec->bits_per_coded_sample = descriptor->bits_per_sample; /* Uncompressed */
+            if (st->codec->codec_id == CODEC_ID_RAWVIDEO)
+                st->codec->pix_fmt = descriptor->pix_fmt;
             st->need_parsing = AVSTREAM_PARSE_HEADERS;
         } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
             container_ul = mxf_get_codec_ul(mxf_essence_container_uls, essence_container_ul);
@@ -854,21 +862,21 @@ static const MXFMetadataReadTableEntry mxf_metadata_read_table[] = {
     { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, NULL, 0, AnyType },
 };
 
-static int mxf_read_local_tags(MXFContext *mxf, KLVPacket *klv, int (*read_child)(), int ctx_size, enum MXFMetadataSetType type)
+static int mxf_read_local_tags(MXFContext *mxf, KLVPacket *klv, MXFMetadataReadFunc *read_child, int ctx_size, enum MXFMetadataSetType type)
 {
-    ByteIOContext *pb = mxf->fc->pb;
+    AVIOContext *pb = mxf->fc->pb;
     MXFMetadataSet *ctx = ctx_size ? av_mallocz(ctx_size) : mxf;
-    uint64_t klv_end = url_ftell(pb) + klv->length;
+    uint64_t klv_end = avio_tell(pb) + klv->length;
 
     if (!ctx)
         return -1;
-    while (url_ftell(pb) + 4 < klv_end) {
-        int tag = get_be16(pb);
-        int size = get_be16(pb); /* KLV specified by 0x53 */
-        uint64_t next = url_ftell(pb) + size;
+    while (avio_tell(pb) + 4 < klv_end) {
+        int tag = avio_rb16(pb);
+        int size = avio_rb16(pb); /* KLV specified by 0x53 */
+        uint64_t next = avio_tell(pb) + size;
         UID uid = {0};
 
-        dprintf(mxf->fc, "local tag %#04x size %d\n", tag, size);
+        av_dlog(mxf->fc, "local tag %#04x size %d\n", tag, size);
         if (!size) { /* ignore empty tag, needed for some files with empty UMID tag */
             av_log(mxf->fc, AV_LOG_ERROR, "local tag %#04x with 0 size\n", tag);
             continue;
@@ -879,17 +887,17 @@ static int mxf_read_local_tags(MXFContext *mxf, KLVPacket *klv, int (*read_child
                 int local_tag = AV_RB16(mxf->local_tags+i*18);
                 if (local_tag == tag) {
                     memcpy(uid, mxf->local_tags+i*18+2, 16);
-                    dprintf(mxf->fc, "local tag %#04x\n", local_tag);
+                    av_dlog(mxf->fc, "local tag %#04x\n", local_tag);
                     PRINT_KEY(mxf->fc, "uid", uid);
                 }
             }
         }
         if (ctx_size && tag == 0x3C0A)
-            get_buffer(pb, ctx->uid, 16);
+            avio_read(pb, ctx->uid, 16);
         else if (read_child(ctx, pb, tag, size, uid) < 0)
             return -1;
 
-        url_fseek(pb, next, SEEK_SET);
+        avio_seek(pb, next, SEEK_SET);
     }
     if (ctx_size) ctx->type = type;
     return ctx_size ? mxf_add_metadata_set(mxf, ctx) : 0;
@@ -904,26 +912,30 @@ static int mxf_read_header(AVFormatContext *s, AVFormatParameters *ap)
         av_log(s, AV_LOG_ERROR, "could not find header partition pack key\n");
         return -1;
     }
-    url_fseek(s->pb, -14, SEEK_CUR);
+    avio_seek(s->pb, -14, SEEK_CUR);
     mxf->fc = s;
-    while (!url_feof(s->pb)) {
+    while (!s->pb->eof_reached) {
         const MXFMetadataReadTableEntry *metadata;
 
         if (klv_read_packet(&klv, s->pb) < 0)
             return -1;
         PRINT_KEY(s, "read header", klv.key);
-        dprintf(s, "size %lld offset %#llx\n", klv.length, klv.offset);
+        av_dlog(s, "size %lld offset %#llx\n", klv.length, klv.offset);
         if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key) ||
             IS_KLV_KEY(klv.key, mxf_essence_element_key)) {
             /* FIXME avoid seek */
-            url_fseek(s->pb, klv.offset, SEEK_SET);
+            avio_seek(s->pb, klv.offset, SEEK_SET);
             break;
         }
 
         for (metadata = mxf_metadata_read_table; metadata->read; metadata++) {
             if (IS_KLV_KEY(klv.key, metadata->key)) {
-                int (*read)() = klv.key[5] == 0x53 ? mxf_read_local_tags : metadata->read;
-                if (read(mxf, &klv, metadata->read, metadata->ctx_size, metadata->type) < 0) {
+                int res;
+                if (klv.key[5] == 0x53) {
+                    res = mxf_read_local_tags(mxf, &klv, metadata->read, metadata->ctx_size, metadata->type);
+                } else
+                    res = metadata->read(mxf, s->pb, 0, 0, NULL);
+                if (res < 0) {
                     av_log(s, AV_LOG_ERROR, "error reading header metadata\n");
                     return -1;
                 }
@@ -931,7 +943,7 @@ static int mxf_read_header(AVFormatContext *s, AVFormatParameters *ap)
             }
         }
         if (!metadata->read)
-            url_fskip(s->pb, klv.length);
+            avio_skip(s->pb, klv.length);
     }
     return mxf_parse_structural_metadata(mxf);
 }
@@ -997,12 +1009,12 @@ static int mxf_read_seek(AVFormatContext *s, int stream_index, int64_t sample_ti
     if (sample_time < 0)
         sample_time = 0;
     seconds = av_rescale(sample_time, st->time_base.num, st->time_base.den);
-    url_fseek(s->pb, (s->bit_rate * seconds) >> 3, SEEK_SET);
+    avio_seek(s->pb, (s->bit_rate * seconds) >> 3, SEEK_SET);
     av_update_cur_dts(s, st, sample_time);
     return 0;
 }
 
-AVInputFormat mxf_demuxer = {
+AVInputFormat ff_mxf_demuxer = {
     "mxf",
     NULL_IF_CONFIG_SMALL("Material eXchange Format"),
     sizeof(MXFContext),
diff --git a/libavformat/mxfenc.c b/libavformat/mxfenc.c
index ab38118..c448e14 100644
--- a/libavformat/mxfenc.c
+++ b/libavformat/mxfenc.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2008 GUCAS, Zhentan Feng <spyfeng at gmail dot com>
  * Copyright (c) 2008 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -44,7 +44,7 @@
 static const int NTSC_samples_per_frame[] = { 1602, 1601, 1602, 1601, 1602, 0 };
 static const int PAL_samples_per_frame[]  = { 1920, 0 };
 
-AVOutputFormat mxf_d10_muxer;
+extern AVOutputFormat ff_mxf_d10_muxer;
 
 #define EDIT_UNITS_PER_BODY 250
 #define KAG_SIZE 512
@@ -58,6 +58,7 @@ typedef struct {
     uint8_t flags;
     uint64_t offset;
     unsigned slice_offset; ///< offset of audio slice
+    uint16_t temporal_ref;
 } MXFIndexEntry;
 
 typedef struct {
@@ -76,7 +77,7 @@ typedef struct {
     UID container_ul;
     UID element_ul;
     UID codec_ul;
-    void (*write_desc)();
+    void (*write_desc)(AVFormatContext *, AVStream *);
 } MXFContainerEssenceEntry;
 
 static const struct {
@@ -304,26 +305,26 @@ static const MXFLocalTagPair mxf_local_tag_batch[] = {
     { 0x3D0A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x02,0x03,0x02,0x01,0x00,0x00,0x00}}, /* Block Align */
 };
 
-static void mxf_write_uuid(ByteIOContext *pb, enum MXFMetadataSetType type, int value)
+static void mxf_write_uuid(AVIOContext *pb, enum MXFMetadataSetType type, int value)
 {
-    put_buffer(pb, uuid_base, 12);
-    put_be16(pb, type);
-    put_be16(pb, value);
+    avio_write(pb, uuid_base, 12);
+    avio_wb16(pb, type);
+    avio_wb16(pb, value);
 }
 
 static void mxf_write_umid(AVFormatContext *s, int type)
 {
     MXFContext *mxf = s->priv_data;
-    put_buffer(s->pb, umid_ul, 13);
-    put_be24(s->pb, mxf->instance_number);
-    put_buffer(s->pb, mxf->umid, 15);
-    put_byte(s->pb, type);
+    avio_write(s->pb, umid_ul, 13);
+    avio_wb24(s->pb, mxf->instance_number);
+    avio_write(s->pb, mxf->umid, 15);
+    avio_w8(s->pb, type);
 }
 
-static void mxf_write_refs_count(ByteIOContext *pb, int ref_count)
+static void mxf_write_refs_count(AVIOContext *pb, int ref_count)
 {
-    put_be32(pb, ref_count);
-    put_be32(pb, 16);
+    avio_wb32(pb, ref_count);
+    avio_wb32(pb, 16);
 }
 
 static int klv_ber_length(uint64_t len)
@@ -334,31 +335,31 @@ static int klv_ber_length(uint64_t len)
         return (av_log2(len) >> 3) + 2;
 }
 
-static int klv_encode_ber_length(ByteIOContext *pb, uint64_t len)
+static int klv_encode_ber_length(AVIOContext *pb, uint64_t len)
 {
     // Determine the best BER size
     int size;
     if (len < 128) {
         //short form
-        put_byte(pb, len);
+        avio_w8(pb, len);
         return 1;
     }
 
     size = (av_log2(len) >> 3) + 1;
 
     // long form
-    put_byte(pb, 0x80 + size);
+    avio_w8(pb, 0x80 + size);
     while(size) {
         size--;
-        put_byte(pb, len >> 8 * size & 0xff);
+        avio_w8(pb, len >> 8 * size & 0xff);
     }
     return 0;
 }
 
-static void klv_encode_ber4_length(ByteIOContext *pb, int len)
+static void klv_encode_ber4_length(AVIOContext *pb, int len)
 {
-    put_byte(pb, 0x80 + 3);
-    put_be24(pb, len);
+    avio_w8(pb, 0x80 + 3);
+    avio_wb24(pb, len);
 }
 
 /*
@@ -375,33 +376,33 @@ static int mxf_get_essence_container_ul_index(enum CodecID id)
 
 static void mxf_write_primer_pack(AVFormatContext *s)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int local_tag_number, i = 0;
 
     local_tag_number = FF_ARRAY_ELEMS(mxf_local_tag_batch);
 
-    put_buffer(pb, primer_pack_key, 16);
+    avio_write(pb, primer_pack_key, 16);
     klv_encode_ber_length(pb, local_tag_number * 18 + 8);
 
-    put_be32(pb, local_tag_number); // local_tag num
-    put_be32(pb, 18); // item size, always 18 according to the specs
+    avio_wb32(pb, local_tag_number); // local_tag num
+    avio_wb32(pb, 18); // item size, always 18 according to the specs
 
     for (i = 0; i < local_tag_number; i++) {
-        put_be16(pb, mxf_local_tag_batch[i].local_tag);
-        put_buffer(pb, mxf_local_tag_batch[i].uid, 16);
+        avio_wb16(pb, mxf_local_tag_batch[i].local_tag);
+        avio_write(pb, mxf_local_tag_batch[i].uid, 16);
     }
 }
 
-static void mxf_write_local_tag(ByteIOContext *pb, int size, int tag)
+static void mxf_write_local_tag(AVIOContext *pb, int size, int tag)
 {
-    put_be16(pb, tag);
-    put_be16(pb, size);
+    avio_wb16(pb, tag);
+    avio_wb16(pb, size);
 }
 
-static void mxf_write_metadata_key(ByteIOContext *pb, unsigned int value)
+static void mxf_write_metadata_key(AVIOContext *pb, unsigned int value)
 {
-    put_buffer(pb, header_metadata_key, 13);
-    put_be24(pb, value);
+    avio_write(pb, header_metadata_key, 13);
+    avio_wb24(pb, value);
 }
 
 static void mxf_free(AVFormatContext *s)
@@ -428,21 +429,21 @@ static const MXFCodecUL *mxf_get_data_definition_ul(int type)
 static void mxf_write_essence_container_refs(AVFormatContext *s)
 {
     MXFContext *c = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int i;
 
     mxf_write_refs_count(pb, c->essence_container_count);
     av_log(s,AV_LOG_DEBUG, "essence container count:%d\n", c->essence_container_count);
     for (i = 0; i < c->essence_container_count; i++) {
         MXFStreamContext *sc = s->streams[i]->priv_data;
-        put_buffer(pb, mxf_essence_container_uls[sc->index].container_ul, 16);
+        avio_write(pb, mxf_essence_container_uls[sc->index].container_ul, 16);
     }
 }
 
 static void mxf_write_preface(AVFormatContext *s)
 {
     MXFContext *mxf = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
 
     mxf_write_metadata_key(pb, 0x012f00);
     PRINT_KEY(s, "preface key", pb->buf_ptr - 16);
@@ -455,11 +456,11 @@ static void mxf_write_preface(AVFormatContext *s)
 
     // last modified date
     mxf_write_local_tag(pb, 8, 0x3B02);
-    put_be64(pb, mxf->timestamp);
+    avio_wb64(pb, mxf->timestamp);
 
     // write version
     mxf_write_local_tag(pb, 2, 0x3B05);
-    put_be16(pb, 258); // v1.2
+    avio_wb16(pb, 258); // v1.2
 
     // write identification_refs
     mxf_write_local_tag(pb, 16 + 8, 0x3B06);
@@ -472,7 +473,7 @@ static void mxf_write_preface(AVFormatContext *s)
 
     // operational pattern
     mxf_write_local_tag(pb, 16, 0x3B09);
-    put_buffer(pb, op1a_ul, 16);
+    avio_write(pb, op1a_ul, 16);
 
     // write essence_container_refs
     mxf_write_local_tag(pb, 8 + 16 * mxf->essence_container_count, 0x3B0A);
@@ -480,25 +481,25 @@ static void mxf_write_preface(AVFormatContext *s)
 
     // write dm_scheme_refs
     mxf_write_local_tag(pb, 8, 0x3B0B);
-    put_be64(pb, 0);
+    avio_wb64(pb, 0);
 }
 
 /*
  * Write a local tag containing an ascii string as utf-16
  */
-static void mxf_write_local_tag_utf16(ByteIOContext *pb, int tag, const char *value)
+static void mxf_write_local_tag_utf16(AVIOContext *pb, int tag, const char *value)
 {
     int i, size = strlen(value);
     mxf_write_local_tag(pb, size*2, tag);
     for (i = 0; i < size; i++)
-        put_be16(pb, value[i]);
+        avio_wb16(pb, value[i]);
 }
 
 static void mxf_write_identification(AVFormatContext *s)
 {
     MXFContext *mxf = s->priv_data;
-    ByteIOContext *pb = s->pb;
-    const char *company = "FFmpeg";
+    AVIOContext *pb = s->pb;
+    const char *company = "Libav";
     const char *product = "OP1a Muxer";
     const char *version;
     int length;
@@ -530,12 +531,12 @@ static void mxf_write_identification(AVFormatContext *s)
 
     // modification date
     mxf_write_local_tag(pb, 8, 0x3C06);
-    put_be64(pb, mxf->timestamp);
+    avio_wb64(pb, mxf->timestamp);
 }
 
 static void mxf_write_content_storage(AVFormatContext *s)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
 
     mxf_write_metadata_key(pb, 0x011800);
     PRINT_KEY(s, "content storage key", pb->buf_ptr - 16);
@@ -561,7 +562,7 @@ static void mxf_write_content_storage(AVFormatContext *s)
 static void mxf_write_track(AVFormatContext *s, AVStream *st, enum MXFMetadataSetType type)
 {
     MXFContext *mxf = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     MXFStreamContext *sc = st->priv_data;
 
     mxf_write_metadata_key(pb, 0x013b00);
@@ -575,22 +576,22 @@ static void mxf_write_track(AVFormatContext *s, AVStream *st, enum MXFMetadataSe
 
     // write track id
     mxf_write_local_tag(pb, 4, 0x4801);
-    put_be32(pb, st->index+2);
+    avio_wb32(pb, st->index+2);
 
     // write track number
     mxf_write_local_tag(pb, 4, 0x4804);
     if (type == MaterialPackage)
-        put_be32(pb, 0); // track number of material package is 0
+        avio_wb32(pb, 0); // track number of material package is 0
     else
-        put_buffer(pb, sc->track_essence_element_key + 12, 4);
+        avio_write(pb, sc->track_essence_element_key + 12, 4);
 
     mxf_write_local_tag(pb, 8, 0x4B01);
-    put_be32(pb, mxf->time_base.den);
-    put_be32(pb, mxf->time_base.num);
+    avio_wb32(pb, mxf->time_base.den);
+    avio_wb32(pb, mxf->time_base.num);
 
     // write origin
     mxf_write_local_tag(pb, 8, 0x4B02);
-    put_be64(pb, 0);
+    avio_wb64(pb, 0);
 
     // write sequence refs
     mxf_write_local_tag(pb, 16, 0x4803);
@@ -602,26 +603,26 @@ static const uint8_t smpte_12m_timecode_track_data_ul[] = { 0x06,0x0E,0x2B,0x34,
 static void mxf_write_common_fields(AVFormatContext *s, AVStream *st)
 {
     MXFContext *mxf = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
 
     // find data define uls
     mxf_write_local_tag(pb, 16, 0x0201);
     if (st == mxf->timecode_track)
-        put_buffer(pb, smpte_12m_timecode_track_data_ul, 16);
+        avio_write(pb, smpte_12m_timecode_track_data_ul, 16);
     else {
         const MXFCodecUL *data_def_ul = mxf_get_data_definition_ul(st->codec->codec_type);
-        put_buffer(pb, data_def_ul->uid, 16);
+        avio_write(pb, data_def_ul->uid, 16);
     }
 
     // write duration
     mxf_write_local_tag(pb, 8, 0x0202);
-    put_be64(pb, mxf->duration);
+    avio_wb64(pb, mxf->duration);
 }
 
 static void mxf_write_sequence(AVFormatContext *s, AVStream *st, enum MXFMetadataSetType type)
 {
     MXFContext *mxf = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     enum MXFMetadataSetType component;
 
     mxf_write_metadata_key(pb, 0x010f00);
@@ -649,7 +650,7 @@ static void mxf_write_sequence(AVFormatContext *s, AVStream *st, enum MXFMetadat
 static void mxf_write_timecode_component(AVFormatContext *s, AVStream *st, enum MXFMetadataSetType type)
 {
     MXFContext *mxf = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
 
     mxf_write_metadata_key(pb, 0x011400);
     klv_encode_ber_length(pb, 75);
@@ -663,20 +664,20 @@ static void mxf_write_timecode_component(AVFormatContext *s, AVStream *st, enum
 
     // Start Time Code
     mxf_write_local_tag(pb, 8, 0x1501);
-    put_be64(pb, mxf->timecode_start);
+    avio_wb64(pb, mxf->timecode_start);
 
     // Rounded Time Code Base
     mxf_write_local_tag(pb, 2, 0x1502);
-    put_be16(pb, mxf->timecode_base);
+    avio_wb16(pb, mxf->timecode_base);
 
     // Drop Frame
     mxf_write_local_tag(pb, 1, 0x1503);
-    put_byte(pb, mxf->timecode_drop_frame);
+    avio_w8(pb, mxf->timecode_drop_frame);
 }
 
 static void mxf_write_structural_component(AVFormatContext *s, AVStream *st, enum MXFMetadataSetType type)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int i;
 
     mxf_write_metadata_key(pb, 0x011100);
@@ -692,28 +693,28 @@ static void mxf_write_structural_component(AVFormatContext *s, AVStream *st, enu
 
     // write start_position
     mxf_write_local_tag(pb, 8, 0x1201);
-    put_be64(pb, 0);
+    avio_wb64(pb, 0);
 
     // write source package uid, end of the reference
     mxf_write_local_tag(pb, 32, 0x1101);
     if (type == SourcePackage) {
         for (i = 0; i < 4; i++)
-            put_be64(pb, 0);
+            avio_wb64(pb, 0);
     } else
         mxf_write_umid(s, 1);
 
     // write source track id
     mxf_write_local_tag(pb, 4, 0x1102);
     if (type == SourcePackage)
-        put_be32(pb, 0);
+        avio_wb32(pb, 0);
     else
-        put_be32(pb, st->index+2);
+        avio_wb32(pb, st->index+2);
 }
 
 static void mxf_write_multi_descriptor(AVFormatContext *s)
 {
     MXFContext *mxf = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     const uint8_t *ul;
     int i;
 
@@ -727,8 +728,8 @@ static void mxf_write_multi_descriptor(AVFormatContext *s)
 
     // write sample rate
     mxf_write_local_tag(pb, 8, 0x3001);
-    put_be32(pb, mxf->time_base.den);
-    put_be32(pb, mxf->time_base.num);
+    avio_wb32(pb, mxf->time_base.den);
+    avio_wb32(pb, mxf->time_base.num);
 
     // write essence container ul
     mxf_write_local_tag(pb, 16, 0x3004);
@@ -738,7 +739,7 @@ static void mxf_write_multi_descriptor(AVFormatContext *s)
         MXFStreamContext *sc = s->streams[0]->priv_data;
         ul = mxf_essence_container_uls[sc->index].container_ul;
     }
-    put_buffer(pb, ul, 16);
+    avio_write(pb, ul, 16);
 
     // write sub descriptor refs
     mxf_write_local_tag(pb, s->nb_streams * 16 + 8, 0x3F01);
@@ -751,23 +752,23 @@ static void mxf_write_generic_desc(AVFormatContext *s, AVStream *st, const UID k
 {
     MXFContext *mxf = s->priv_data;
     MXFStreamContext *sc = st->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
 
-    put_buffer(pb, key, 16);
+    avio_write(pb, key, 16);
     klv_encode_ber4_length(pb, size+20+8+12+20);
 
     mxf_write_local_tag(pb, 16, 0x3C0A);
     mxf_write_uuid(pb, SubDescriptor, st->index);
 
     mxf_write_local_tag(pb, 4, 0x3006);
-    put_be32(pb, st->index+2);
+    avio_wb32(pb, st->index+2);
 
     mxf_write_local_tag(pb, 8, 0x3001);
-    put_be32(pb, mxf->time_base.den);
-    put_be32(pb, mxf->time_base.num);
+    avio_wb32(pb, mxf->time_base.den);
+    avio_wb32(pb, mxf->time_base.num);
 
     mxf_write_local_tag(pb, 16, 0x3004);
-    put_buffer(pb, mxf_essence_container_uls[sc->index].container_ul, 16);
+    avio_write(pb, mxf_essence_container_uls[sc->index].container_ul, 16);
 }
 
 static const UID mxf_mpegvideo_descriptor_key = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x51,0x00 };
@@ -779,7 +780,7 @@ static const UID mxf_generic_sound_descriptor_key = { 0x06,0x0E,0x2B,0x34,0x02,0
 static void mxf_write_cdci_common(AVFormatContext *s, AVStream *st, const UID key, unsigned size)
 {
     MXFStreamContext *sc = st->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int stored_height = (st->codec->height+15)/16*16;
     int display_height;
     int f1, f2;
@@ -787,13 +788,13 @@ static void mxf_write_cdci_common(AVFormatContext *s, AVStream *st, const UID ke
     mxf_write_generic_desc(s, st, key, size+8+8+8+8+8+8+5+16+sc->interlaced*4+12+20);
 
     mxf_write_local_tag(pb, 4, 0x3203);
-    put_be32(pb, st->codec->width);
+    avio_wb32(pb, st->codec->width);
 
     mxf_write_local_tag(pb, 4, 0x3202);
-    put_be32(pb, stored_height>>sc->interlaced);
+    avio_wb32(pb, stored_height>>sc->interlaced);
 
     mxf_write_local_tag(pb, 4, 0x3209);
-    put_be32(pb, st->codec->width);
+    avio_wb32(pb, st->codec->width);
 
     if (st->codec->height == 608) // PAL + VBI
         display_height = 576;
@@ -803,19 +804,19 @@ static void mxf_write_cdci_common(AVFormatContext *s, AVStream *st, const UID ke
         display_height = st->codec->height;
 
     mxf_write_local_tag(pb, 4, 0x3208);
-    put_be32(pb, display_height>>sc->interlaced);
+    avio_wb32(pb, display_height>>sc->interlaced);
 
     // component depth
     mxf_write_local_tag(pb, 4, 0x3301);
-    put_be32(pb, 8);
+    avio_wb32(pb, 8);
 
     // horizontal subsampling
     mxf_write_local_tag(pb, 4, 0x3302);
-    put_be32(pb, 2);
+    avio_wb32(pb, 2);
 
     // frame layout
     mxf_write_local_tag(pb, 1, 0x320C);
-    put_byte(pb, sc->interlaced);
+    avio_w8(pb, sc->interlaced);
 
     // video line map
     switch (st->codec->height) {
@@ -834,18 +835,18 @@ static void mxf_write_cdci_common(AVFormatContext *s, AVStream *st, const UID ke
     }
 
     mxf_write_local_tag(pb, 12+sc->interlaced*4, 0x320D);
-    put_be32(pb, sc->interlaced ? 2 : 1);
-    put_be32(pb, 4);
-    put_be32(pb, f1);
+    avio_wb32(pb, sc->interlaced ? 2 : 1);
+    avio_wb32(pb, 4);
+    avio_wb32(pb, f1);
     if (sc->interlaced)
-        put_be32(pb, f2);
+        avio_wb32(pb, f2);
 
     mxf_write_local_tag(pb, 8, 0x320E);
-    put_be32(pb, sc->aspect_ratio.num);
-    put_be32(pb, sc->aspect_ratio.den);
+    avio_wb32(pb, sc->aspect_ratio.num);
+    avio_wb32(pb, sc->aspect_ratio.den);
 
     mxf_write_local_tag(pb, 16, 0x3201);
-    put_buffer(pb, *sc->codec_ul, 16);
+    avio_write(pb, *sc->codec_ul, 16);
 }
 
 static void mxf_write_cdci_desc(AVFormatContext *s, AVStream *st)
@@ -855,56 +856,56 @@ static void mxf_write_cdci_desc(AVFormatContext *s, AVStream *st)
 
 static void mxf_write_mpegvideo_desc(AVFormatContext *s, AVStream *st)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int profile_and_level = (st->codec->profile<<4) | st->codec->level;
 
     mxf_write_cdci_common(s, st, mxf_mpegvideo_descriptor_key, 8+5);
 
     // bit rate
     mxf_write_local_tag(pb, 4, 0x8000);
-    put_be32(pb, st->codec->bit_rate);
+    avio_wb32(pb, st->codec->bit_rate);
 
     // profile and level
     mxf_write_local_tag(pb, 1, 0x8007);
     if (!st->codec->profile)
         profile_and_level |= 0x80; // escape bit
-    put_byte(pb, profile_and_level);
+    avio_w8(pb, profile_and_level);
 }
 
 static void mxf_write_generic_sound_common(AVFormatContext *s, AVStream *st, const UID key, unsigned size)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
 
     mxf_write_generic_desc(s, st, key, size+5+12+8+8);
 
     // audio locked
     mxf_write_local_tag(pb, 1, 0x3D02);
-    put_byte(pb, 1);
+    avio_w8(pb, 1);
 
     // write audio sampling rate
     mxf_write_local_tag(pb, 8, 0x3D03);
-    put_be32(pb, st->codec->sample_rate);
-    put_be32(pb, 1);
+    avio_wb32(pb, st->codec->sample_rate);
+    avio_wb32(pb, 1);
 
     mxf_write_local_tag(pb, 4, 0x3D07);
-    put_be32(pb, st->codec->channels);
+    avio_wb32(pb, st->codec->channels);
 
     mxf_write_local_tag(pb, 4, 0x3D01);
-    put_be32(pb, av_get_bits_per_sample(st->codec->codec_id));
+    avio_wb32(pb, av_get_bits_per_sample(st->codec->codec_id));
 }
 
 static void mxf_write_wav_common(AVFormatContext *s, AVStream *st, const UID key, unsigned size)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
 
     mxf_write_generic_sound_common(s, st, key, size+6+8);
 
     mxf_write_local_tag(pb, 2, 0x3D0A);
-    put_be16(pb, st->codec->block_align);
+    avio_wb16(pb, st->codec->block_align);
 
     // avg bytes per sec
     mxf_write_local_tag(pb, 4, 0x3D09);
-    put_be32(pb, st->codec->block_align*st->codec->sample_rate);
+    avio_wb32(pb, st->codec->block_align*st->codec->sample_rate);
 }
 
 static void mxf_write_wav_desc(AVFormatContext *s, AVStream *st)
@@ -925,7 +926,7 @@ static void mxf_write_generic_sound_desc(AVFormatContext *s, AVStream *st)
 static void mxf_write_package(AVFormatContext *s, enum MXFMetadataSetType type)
 {
     MXFContext *mxf = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int i, track_count = s->nb_streams+1;
 
     if (type == MaterialPackage) {
@@ -951,11 +952,11 @@ static void mxf_write_package(AVFormatContext *s, enum MXFMetadataSetType type)
 
     // package creation date
     mxf_write_local_tag(pb, 8, 0x4405);
-    put_be64(pb, mxf->timestamp);
+    avio_wb64(pb, mxf->timestamp);
 
     // package modified date
     mxf_write_local_tag(pb, 8, 0x4404);
-    put_be64(pb, mxf->timestamp);
+    avio_wb64(pb, mxf->timestamp);
 
     // write track refs
     mxf_write_local_tag(pb, track_count*16 + 8, 0x4403);
@@ -995,7 +996,7 @@ static void mxf_write_package(AVFormatContext *s, enum MXFMetadataSetType type)
 
 static int mxf_write_essence_container_data(AVFormatContext *s)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
 
     mxf_write_metadata_key(pb, 0x012300);
     klv_encode_ber_length(pb, 72);
@@ -1007,10 +1008,10 @@ static int mxf_write_essence_container_data(AVFormatContext *s)
     mxf_write_umid(s, 1);
 
     mxf_write_local_tag(pb, 4, 0x3F07); // BodySID
-    put_be32(pb, 1);
+    avio_wb32(pb, 1);
 
     mxf_write_local_tag(pb, 4, 0x3F06); // IndexSID
-    put_be32(pb, 2);
+    avio_wb32(pb, 2);
 
     return 0;
 }
@@ -1038,9 +1039,8 @@ static unsigned klv_fill_size(uint64_t size)
 static void mxf_write_index_table_segment(AVFormatContext *s)
 {
     MXFContext *mxf = s->priv_data;
-    ByteIOContext *pb = s->pb;
-    int i, j;
-    int temporal_reordering = 0;
+    AVIOContext *pb = s->pb;
+    int i, j, temporal_reordering = 0;
     int key_index = mxf->last_key_index;
 
     av_log(s, AV_LOG_DEBUG, "edit units count %d\n", mxf->edit_units_count);
@@ -1048,7 +1048,7 @@ static void mxf_write_index_table_segment(AVFormatContext *s)
     if (!mxf->edit_units_count && !mxf->edit_unit_byte_count)
         return;
 
-    put_buffer(pb, index_table_segment_key, 16);
+    avio_write(pb, index_table_segment_key, 16);
 
     if (mxf->edit_unit_byte_count) {
         klv_encode_ber_length(pb, 80);
@@ -1063,103 +1063,104 @@ static void mxf_write_index_table_segment(AVFormatContext *s)
 
     // index edit rate
     mxf_write_local_tag(pb, 8, 0x3F0B);
-    put_be32(pb, mxf->time_base.den);
-    put_be32(pb, mxf->time_base.num);
+    avio_wb32(pb, mxf->time_base.den);
+    avio_wb32(pb, mxf->time_base.num);
 
     // index start position
     mxf_write_local_tag(pb, 8, 0x3F0C);
-    put_be64(pb, mxf->last_indexed_edit_unit);
+    avio_wb64(pb, mxf->last_indexed_edit_unit);
 
     // index duration
     mxf_write_local_tag(pb, 8, 0x3F0D);
     if (mxf->edit_unit_byte_count)
-        put_be64(pb, 0); // index table covers whole container
+        avio_wb64(pb, 0); // index table covers whole container
     else
-        put_be64(pb, mxf->edit_units_count);
+        avio_wb64(pb, mxf->edit_units_count);
 
     // edit unit byte count
     mxf_write_local_tag(pb, 4, 0x3F05);
-    put_be32(pb, mxf->edit_unit_byte_count);
+    avio_wb32(pb, mxf->edit_unit_byte_count);
 
     // index sid
     mxf_write_local_tag(pb, 4, 0x3F06);
-    put_be32(pb, 2);
+    avio_wb32(pb, 2);
 
     // body sid
     mxf_write_local_tag(pb, 4, 0x3F07);
-    put_be32(pb, 1);
+    avio_wb32(pb, 1);
 
     if (!mxf->edit_unit_byte_count) {
         // real slice count - 1
         mxf_write_local_tag(pb, 1, 0x3F08);
-        put_byte(pb, mxf->slice_count);
+        avio_w8(pb, mxf->slice_count);
 
         // delta entry array
         mxf_write_local_tag(pb, 8 + (s->nb_streams+1)*6, 0x3F09);
-        put_be32(pb, s->nb_streams+1); // num of entries
-        put_be32(pb, 6);               // size of one entry
+        avio_wb32(pb, s->nb_streams+1); // num of entries
+        avio_wb32(pb, 6);               // size of one entry
         // write system item delta entry
-        put_byte(pb, 0);
-        put_byte(pb, 0); // slice entry
-        put_be32(pb, 0); // element delta
+        avio_w8(pb, 0);
+        avio_w8(pb, 0); // slice entry
+        avio_wb32(pb, 0); // element delta
         for (i = 0; i < s->nb_streams; i++) {
             AVStream *st = s->streams[i];
             MXFStreamContext *sc = st->priv_data;
-            put_byte(pb, sc->temporal_reordering);
+            avio_w8(pb, sc->temporal_reordering);
             if (sc->temporal_reordering)
                 temporal_reordering = 1;
             if (i == 0) { // video track
-                put_byte(pb, 0); // slice number
-                put_be32(pb, KAG_SIZE); // system item size including klv fill
+                avio_w8(pb, 0); // slice number
+                avio_wb32(pb, KAG_SIZE); // system item size including klv fill
             } else { // audio track
                 unsigned audio_frame_size = sc->aic.samples[0]*sc->aic.sample_size;
                 audio_frame_size += klv_fill_size(audio_frame_size);
-                put_byte(pb, 1);
-                put_be32(pb, (i-1)*audio_frame_size); // element delta
+                avio_w8(pb, 1);
+                avio_wb32(pb, (i-1)*audio_frame_size); // element delta
             }
         }
 
         mxf_write_local_tag(pb, 8 + mxf->edit_units_count*(11+mxf->slice_count*4), 0x3F0A);
-        put_be32(pb, mxf->edit_units_count);  // num of entries
-        put_be32(pb, 11+mxf->slice_count*4);  // size of one entry
+        avio_wb32(pb, mxf->edit_units_count);  // num of entries
+        avio_wb32(pb, 11+mxf->slice_count*4);  // size of one entry
+
         for (i = 0; i < mxf->edit_units_count; i++) {
             int temporal_offset = 0;
-            if (temporal_reordering) {
-                for (j = i+1; j < mxf->edit_units_count; j++) {
-                    temporal_offset++;
-                    if (mxf->index_entries[j].flags & 0x10) { // backward prediction
-                        // next is not b, so is reordered
-                        if (!(mxf->index_entries[i+1].flags & 0x10)) {
-                            if ((mxf->index_entries[i].flags & 0x11) == 0) // I frame
-                                temporal_offset = 0;
-                            else
-                                temporal_offset = -temporal_offset;
-                        }
-                        break;
-                    }
-                }
-            }
-            put_byte(pb, temporal_offset);
 
             if (!(mxf->index_entries[i].flags & 0x33)) { // I frame
-                if (mxf->index_entries[i].flags & 0x40 && // seq header
-                    (!temporal_reordering || !temporal_offset))
-                    mxf->index_entries[i].flags |= 0x80; // random access
                 mxf->last_key_index = key_index;
                 key_index = i;
             }
+
+            if (temporal_reordering) {
+                int pic_num_in_gop = i - key_index;
+                if (pic_num_in_gop != mxf->index_entries[i].temporal_ref) {
+                    for (j = key_index; j < mxf->edit_units_count; j++) {
+                        if (pic_num_in_gop == mxf->index_entries[j].temporal_ref)
+                            break;
+                    }
+                    if (j == mxf->edit_units_count)
+                        av_log(s, AV_LOG_WARNING, "missing frames\n");
+                    temporal_offset = j - key_index - pic_num_in_gop;
+                }
+            }
+            avio_w8(pb, temporal_offset);
+
             if ((mxf->index_entries[i].flags & 0x30) == 0x30) { // back and forward prediction
-                put_byte(pb, mxf->last_key_index - i);
+                avio_w8(pb, mxf->last_key_index - i);
             } else {
-                put_byte(pb, key_index - i); // key frame offset
+                avio_w8(pb, key_index - i); // key frame offset
                 if ((mxf->index_entries[i].flags & 0x20) == 0x20) // only forward
                     mxf->last_key_index = key_index;
             }
-            put_byte(pb, mxf->index_entries[i].flags);
+
+            if (!(mxf->index_entries[i].flags & 0x33) && // I frame
+                mxf->index_entries[i].flags & 0x40 && !temporal_offset)
+                mxf->index_entries[i].flags |= 0x80; // random access
+            avio_w8(pb, mxf->index_entries[i].flags);
             // stream offset
-            put_be64(pb, mxf->index_entries[i].offset);
+            avio_wb64(pb, mxf->index_entries[i].offset);
             if (s->nb_streams > 1)
-                put_be32(pb, mxf->index_entries[i].slice_offset);
+                avio_wb32(pb, mxf->index_entries[i].slice_offset);
         }
 
         mxf->last_key_index = key_index - mxf->edit_units_count;
@@ -1170,14 +1171,14 @@ static void mxf_write_index_table_segment(AVFormatContext *s)
 
 static void mxf_write_klv_fill(AVFormatContext *s)
 {
-    unsigned pad = klv_fill_size(url_ftell(s->pb));
+    unsigned pad = klv_fill_size(avio_tell(s->pb));
     if (pad) {
-        put_buffer(s->pb, klv_fill_key, 16);
+        avio_write(s->pb, klv_fill_key, 16);
         pad -= 16 + 4;
         klv_encode_ber4_length(s->pb, pad);
         for (; pad; pad--)
-            put_byte(s->pb, 0);
-        assert(!(url_ftell(s->pb) & (KAG_SIZE-1)));
+            avio_w8(s->pb, 0);
+        assert(!(avio_tell(s->pb) & (KAG_SIZE-1)));
     }
 }
 
@@ -1186,10 +1187,10 @@ static void mxf_write_partition(AVFormatContext *s, int bodysid,
                                 const uint8_t *key, int write_metadata)
 {
     MXFContext *mxf = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int64_t header_byte_count_offset;
     unsigned index_byte_count = 0;
-    uint64_t partition_offset = url_ftell(pb);
+    uint64_t partition_offset = avio_tell(pb);
 
     if (!mxf->edit_unit_byte_count && mxf->edit_units_count)
         index_byte_count = 85 + 12+(s->nb_streams+1)*6 +
@@ -1212,43 +1213,43 @@ static void mxf_write_partition(AVFormatContext *s, int bodysid,
     }
 
     // write klv
-    put_buffer(pb, key, 16);
+    avio_write(pb, key, 16);
     klv_encode_ber_length(pb, 88 + 16 * mxf->essence_container_count);
 
     // write partition value
-    put_be16(pb, 1); // majorVersion
-    put_be16(pb, 2); // minorVersion
-    put_be32(pb, KAG_SIZE); // KAGSize
+    avio_wb16(pb, 1); // majorVersion
+    avio_wb16(pb, 2); // minorVersion
+    avio_wb32(pb, KAG_SIZE); // KAGSize
 
-    put_be64(pb, partition_offset); // ThisPartition
+    avio_wb64(pb, partition_offset); // ThisPartition
 
     if (!memcmp(key, body_partition_key, 16) && mxf->body_partitions_count > 1)
-        put_be64(pb, mxf->body_partition_offset[mxf->body_partitions_count-2]); // PreviousPartition
+        avio_wb64(pb, mxf->body_partition_offset[mxf->body_partitions_count-2]); // PreviousPartition
     else if (!memcmp(key, footer_partition_key, 16) && mxf->body_partitions_count)
-        put_be64(pb, mxf->body_partition_offset[mxf->body_partitions_count-1]); // PreviousPartition
+        avio_wb64(pb, mxf->body_partition_offset[mxf->body_partitions_count-1]); // PreviousPartition
     else
-        put_be64(pb, 0);
+        avio_wb64(pb, 0);
 
-    put_be64(pb, mxf->footer_partition_offset); // footerPartition
+    avio_wb64(pb, mxf->footer_partition_offset); // footerPartition
 
     // set offset
-    header_byte_count_offset = url_ftell(pb);
-    put_be64(pb, 0); // headerByteCount, update later
+    header_byte_count_offset = avio_tell(pb);
+    avio_wb64(pb, 0); // headerByteCount, update later
 
     // indexTable
-    put_be64(pb, index_byte_count); // indexByteCount
-    put_be32(pb, index_byte_count ? indexsid : 0); // indexSID
+    avio_wb64(pb, index_byte_count); // indexByteCount
+    avio_wb32(pb, index_byte_count ? indexsid : 0); // indexSID
 
     // BodyOffset
     if (bodysid && mxf->edit_units_count && mxf->body_partitions_count) {
-        put_be64(pb, mxf->body_offset);
+        avio_wb64(pb, mxf->body_offset);
     } else
-        put_be64(pb, 0);
+        avio_wb64(pb, 0);
 
-    put_be32(pb, bodysid); // bodySID
+    avio_wb32(pb, bodysid); // bodySID
 
     // operational pattern
-    put_buffer(pb, op1a_ul, 16);
+    avio_write(pb, op1a_ul, 16);
 
     // essence container
     mxf_write_essence_container_refs(s);
@@ -1259,19 +1260,19 @@ static void mxf_write_partition(AVFormatContext *s, int bodysid,
         unsigned header_byte_count;
 
         mxf_write_klv_fill(s);
-        start = url_ftell(s->pb);
+        start = avio_tell(s->pb);
         mxf_write_primer_pack(s);
         mxf_write_header_metadata_sets(s);
-        pos = url_ftell(s->pb);
+        pos = avio_tell(s->pb);
         header_byte_count = pos - start + klv_fill_size(pos);
 
         // update header_byte_count
-        url_fseek(pb, header_byte_count_offset, SEEK_SET);
-        put_be64(pb, header_byte_count);
-        url_fseek(pb, pos, SEEK_SET);
+        avio_seek(pb, header_byte_count_offset, SEEK_SET);
+        avio_wb64(pb, header_byte_count);
+        avio_seek(pb, pos, SEEK_SET);
     }
 
-    put_flush_packet(pb);
+    avio_flush(pb);
 }
 
 static const UID mxf_mpeg2_codec_uls[] = {
@@ -1303,15 +1304,14 @@ static const UID *mxf_get_mpeg2_codec_ul(AVCodecContext *avctx)
     return NULL;
 }
 
-static int mxf_parse_mpeg2_frame(AVFormatContext *s, AVStream *st, AVPacket *pkt, int *flags)
+static int mxf_parse_mpeg2_frame(AVFormatContext *s, AVStream *st,
+                                 AVPacket *pkt, MXFIndexEntry *e)
 {
     MXFStreamContext *sc = st->priv_data;
     MXFContext *mxf = s->priv_data;
     uint32_t c = -1;
     int i;
 
-    *flags = 0;
-
     for(i = 0; i < pkt->size - 4; i++) {
         c = (c<<8) + pkt->data[i];
         if (c == 0x1b5) {
@@ -1325,8 +1325,8 @@ static int mxf_parse_mpeg2_frame(AVFormatContext *s, AVStream *st, AVPacket *pkt
         } else if (c == 0x1b8) { // gop
             if (pkt->data[i+4]>>6 & 0x01) { // closed
                 sc->closed_gop = 1;
-                if (*flags & 0x40) // sequence header present
-                    *flags |= 0x80; // random access
+                if (e->flags & 0x40) // sequence header present
+                    e->flags |= 0x80; // random access
             }
             if (!mxf->header_written) {
                 unsigned hours   =  (pkt->data[i+1]>>2) & 0x1f;
@@ -1344,7 +1344,7 @@ static int mxf_parse_mpeg2_frame(AVFormatContext *s, AVStream *st, AVPacket *pkt
                        hours, minutes, seconds, mxf->timecode_drop_frame ? ';':':', frames);
             }
         } else if (c == 0x1b3) { // seq
-            *flags |= 0x40;
+            e->flags |= 0x40;
             switch ((pkt->data[i+4]>>4) & 0xf) {
             case 2:  sc->aspect_ratio = (AVRational){  4,  3}; break;
             case 3:  sc->aspect_ratio = (AVRational){ 16,  9}; break;
@@ -1355,14 +1355,15 @@ static int mxf_parse_mpeg2_frame(AVFormatContext *s, AVStream *st, AVPacket *pkt
             }
         } else if (c == 0x100) { // pic
             int pict_type = (pkt->data[i+2]>>3) & 0x07;
+            e->temporal_ref = (pkt->data[i+1]<<2) | (pkt->data[i+2]>>6);
             if (pict_type == 2) { // P frame
-                *flags |= 0x22;
+                e->flags |= 0x22;
                 sc->closed_gop = 0; // reset closed gop, don't matter anymore
             } else if (pict_type == 3) { // B frame
                 if (sc->closed_gop)
-                    *flags |= 0x13; // only backward prediction
+                    e->flags |= 0x13; // only backward prediction
                 else
-                    *flags |= 0x33;
+                    e->flags |= 0x33;
                 sc->temporal_reordering = -1;
             } else if (!pict_type) {
                 av_log(s, AV_LOG_ERROR, "error parsing mpeg2 frame\n");
@@ -1370,7 +1371,7 @@ static int mxf_parse_mpeg2_frame(AVFormatContext *s, AVStream *st, AVPacket *pkt
             }
         }
     }
-    if (s->oformat != &mxf_d10_muxer)
+    if (s->oformat != &ff_mxf_d10_muxer)
         sc->codec_ul = mxf_get_mpeg2_codec_ul(st->codec);
     return !!sc->codec_ul;
 }
@@ -1378,6 +1379,8 @@ static int mxf_parse_mpeg2_frame(AVFormatContext *s, AVStream *st, AVPacket *pkt
 static uint64_t mxf_parse_timestamp(time_t timestamp)
 {
     struct tm *time = gmtime(&timestamp);
+    if (!time)
+        return 0;
     return (uint64_t)(time->tm_year+1900) << 48 |
            (uint64_t)(time->tm_mon+1)     << 40 |
            (uint64_t) time->tm_mday       << 32 |
@@ -1389,7 +1392,7 @@ static uint64_t mxf_parse_timestamp(time_t timestamp)
 static void mxf_gen_umid(AVFormatContext *s)
 {
     MXFContext *mxf = s->priv_data;
-    uint32_t seed = ff_random_get_seed();
+    uint32_t seed = av_get_random_seed();
     uint64_t umid = seed + 0x5294713400000000LL;
 
     AV_WB64(mxf->umid  , umid);
@@ -1433,7 +1436,7 @@ static int mxf_write_header(AVFormatContext *s)
                 return -1;
             }
             av_set_pts_info(st, 64, mxf->time_base.num, mxf->time_base.den);
-            if (s->oformat == &mxf_d10_muxer) {
+            if (s->oformat == &ff_mxf_d10_muxer) {
                 if (st->codec->bit_rate == 50000000)
                     if (mxf->time_base.den == 25) sc->index = 3;
                     else                          sc->index = 5;
@@ -1461,7 +1464,7 @@ static int mxf_write_header(AVFormatContext *s)
                 return -1;
             }
             av_set_pts_info(st, 64, 1, st->codec->sample_rate);
-            if (s->oformat == &mxf_d10_muxer) {
+            if (s->oformat == &ff_mxf_d10_muxer) {
                 if (st->index != 1) {
                     av_log(s, AV_LOG_ERROR, "MXF D-10 only support one audio track\n");
                     return -1;
@@ -1495,7 +1498,7 @@ static int mxf_write_header(AVFormatContext *s)
         present[sc->index]++;
     }
 
-    if (s->oformat == &mxf_d10_muxer) {
+    if (s->oformat == &ff_mxf_d10_muxer) {
         mxf->essence_container_count = 1;
     }
 
@@ -1554,48 +1557,48 @@ static uint32_t ff_framenum_to_12m_time_code(unsigned frame, int drop, int fps)
 static void mxf_write_system_item(AVFormatContext *s)
 {
     MXFContext *mxf = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     unsigned frame;
     uint32_t time_code;
 
     frame = mxf->timecode_start + mxf->last_indexed_edit_unit + mxf->edit_units_count;
 
     // write system metadata pack
-    put_buffer(pb, system_metadata_pack_key, 16);
+    avio_write(pb, system_metadata_pack_key, 16);
     klv_encode_ber4_length(pb, 57);
-    put_byte(pb, 0x5c); // UL, user date/time stamp, picture and sound item present
-    put_byte(pb, 0x04); // content package rate
-    put_byte(pb, 0x00); // content package type
-    put_be16(pb, 0x00); // channel handle
-    put_be16(pb, frame); // continuity count
+    avio_w8(pb, 0x5c); // UL, user date/time stamp, picture and sound item present
+    avio_w8(pb, 0x04); // content package rate
+    avio_w8(pb, 0x00); // content package type
+    avio_wb16(pb, 0x00); // channel handle
+    avio_wb16(pb, frame); // continuity count
     if (mxf->essence_container_count > 1)
-        put_buffer(pb, multiple_desc_ul, 16);
+        avio_write(pb, multiple_desc_ul, 16);
     else {
         MXFStreamContext *sc = s->streams[0]->priv_data;
-        put_buffer(pb, mxf_essence_container_uls[sc->index].container_ul, 16);
+        avio_write(pb, mxf_essence_container_uls[sc->index].container_ul, 16);
     }
-    put_byte(pb, 0);
-    put_be64(pb, 0);
-    put_be64(pb, 0); // creation date/time stamp
+    avio_w8(pb, 0);
+    avio_wb64(pb, 0);
+    avio_wb64(pb, 0); // creation date/time stamp
 
-    put_byte(pb, 0x81); // SMPTE 12M time code
+    avio_w8(pb, 0x81); // SMPTE 12M time code
     time_code = ff_framenum_to_12m_time_code(frame, mxf->timecode_drop_frame, mxf->timecode_base);
-    put_be32(pb, time_code);
-    put_be32(pb, 0); // binary group data
-    put_be64(pb, 0);
+    avio_wb32(pb, time_code);
+    avio_wb32(pb, 0); // binary group data
+    avio_wb64(pb, 0);
 
     // write system metadata package set
-    put_buffer(pb, system_metadata_package_set_key, 16);
+    avio_write(pb, system_metadata_package_set_key, 16);
     klv_encode_ber4_length(pb, 35);
-    put_byte(pb, 0x83); // UMID
-    put_be16(pb, 0x20);
+    avio_w8(pb, 0x83); // UMID
+    avio_wb16(pb, 0x20);
     mxf_write_umid(s, 1);
 }
 
 static void mxf_write_d10_video_packet(AVFormatContext *s, AVStream *st, AVPacket *pkt)
 {
     MXFContext *mxf = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int packet_size = (uint64_t)st->codec->bit_rate*mxf->time_base.num /
         (8*mxf->time_base.den); // frame size
     int pad;
@@ -1604,28 +1607,28 @@ static void mxf_write_d10_video_packet(AVFormatContext *s, AVStream *st, AVPacke
     packet_size += klv_fill_size(packet_size);
 
     klv_encode_ber4_length(pb, pkt->size);
-    put_buffer(pb, pkt->data, pkt->size);
+    avio_write(pb, pkt->data, pkt->size);
 
     // ensure CBR muxing by padding to correct video frame size
     pad = packet_size - pkt->size - 16 - 4;
     if (pad > 20) {
-        put_buffer(s->pb, klv_fill_key, 16);
+        avio_write(s->pb, klv_fill_key, 16);
         pad -= 16 + 4;
         klv_encode_ber4_length(s->pb, pad);
         for (; pad; pad--)
-            put_byte(s->pb, 0);
-        assert(!(url_ftell(s->pb) & (KAG_SIZE-1)));
+            avio_w8(s->pb, 0);
+        assert(!(avio_tell(s->pb) & (KAG_SIZE-1)));
     } else {
         av_log(s, AV_LOG_WARNING, "cannot fill d-10 video packet\n");
         for (; pad > 0; pad--)
-            put_byte(s->pb, 0);
+            avio_w8(s->pb, 0);
     }
 }
 
 static void mxf_write_d10_audio_packet(AVFormatContext *s, AVStream *st, AVPacket *pkt)
 {
     MXFContext *mxf = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int frame_size = pkt->size / st->codec->block_align;
     uint8_t *samples = pkt->data;
     uint8_t *end = pkt->data + pkt->size;
@@ -1633,9 +1636,9 @@ static void mxf_write_d10_audio_packet(AVFormatContext *s, AVStream *st, AVPacke
 
     klv_encode_ber4_length(pb, 4 + frame_size*4*8);
 
-    put_byte(pb, (frame_size == 1920 ? 0 : (mxf->edit_units_count-1) % 5 + 1));
-    put_le16(pb, frame_size);
-    put_byte(pb, (1<<st->codec->channels)-1);
+    avio_w8(pb, (frame_size == 1920 ? 0 : (mxf->edit_units_count-1) % 5 + 1));
+    avio_wl16(pb, frame_size);
+    avio_w8(pb, (1<<st->codec->channels)-1);
 
     while (samples < end) {
         for (i = 0; i < st->codec->channels; i++) {
@@ -1647,20 +1650,20 @@ static void mxf_write_d10_audio_packet(AVFormatContext *s, AVStream *st, AVPacke
                 sample = AV_RL16(samples)<<12;
                 samples += 2;
             }
-            put_le32(pb, sample | i);
+            avio_wl32(pb, sample | i);
         }
         for (; i < 8; i++)
-            put_le32(pb, i);
+            avio_wl32(pb, i);
     }
 }
 
 static int mxf_write_packet(AVFormatContext *s, AVPacket *pkt)
 {
     MXFContext *mxf = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVStream *st = s->streams[pkt->stream_index];
     MXFStreamContext *sc = st->priv_data;
-    int flags = 0;
+    MXFIndexEntry ie = {0};
 
     if (!mxf->edit_unit_byte_count && !(mxf->edit_units_count % EDIT_UNITS_PER_BODY)) {
         mxf->index_entries = av_realloc(mxf->index_entries,
@@ -1672,7 +1675,7 @@ static int mxf_write_packet(AVFormatContext *s, AVPacket *pkt)
     }
 
     if (st->codec->codec_id == CODEC_ID_MPEG2VIDEO) {
-        if (!mxf_parse_mpeg2_frame(s, st, pkt, &flags)) {
+        if (!mxf_parse_mpeg2_frame(s, st, pkt, &ie)) {
             av_log(s, AV_LOG_ERROR, "could not get mpeg2 profile and level\n");
             return -1;
         }
@@ -1692,7 +1695,7 @@ static int mxf_write_packet(AVFormatContext *s, AVPacket *pkt)
     if (st->index == 0) {
         if (!mxf->edit_unit_byte_count &&
             (!mxf->edit_units_count || mxf->edit_units_count > EDIT_UNITS_PER_BODY) &&
-            !(flags & 0x33)) { // I frame, Gop start
+            !(ie.flags & 0x33)) { // I frame, Gop start
             mxf_write_klv_fill(s);
             mxf_write_partition(s, 1, 2, body_partition_key, 0);
 
@@ -1705,7 +1708,8 @@ static int mxf_write_packet(AVFormatContext *s, AVPacket *pkt)
 
         if (!mxf->edit_unit_byte_count) {
             mxf->index_entries[mxf->edit_units_count].offset = mxf->body_offset;
-            mxf->index_entries[mxf->edit_units_count].flags = flags;
+            mxf->index_entries[mxf->edit_units_count].flags = ie.flags;
+            mxf->index_entries[mxf->edit_units_count].temporal_ref = ie.temporal_ref;
             mxf->body_offset += KAG_SIZE; // size of system element
         }
         mxf->edit_units_count++;
@@ -1715,19 +1719,19 @@ static int mxf_write_packet(AVFormatContext *s, AVPacket *pkt)
     }
 
     mxf_write_klv_fill(s);
-    put_buffer(pb, sc->track_essence_element_key, 16); // write key
-    if (s->oformat == &mxf_d10_muxer) {
+    avio_write(pb, sc->track_essence_element_key, 16); // write key
+    if (s->oformat == &ff_mxf_d10_muxer) {
         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
             mxf_write_d10_video_packet(s, st, pkt);
         else
             mxf_write_d10_audio_packet(s, st, pkt);
     } else {
         klv_encode_ber4_length(pb, pkt->size); // write length
-        put_buffer(pb, pkt->data, pkt->size);
+        avio_write(pb, pkt->data, pkt->size);
         mxf->body_offset += 16+4+pkt->size + klv_fill_size(16+4+pkt->size);
     }
 
-    put_flush_packet(pb);
+    avio_flush(pb);
 
     return 0;
 }
@@ -1735,39 +1739,39 @@ static int mxf_write_packet(AVFormatContext *s, AVPacket *pkt)
 static void mxf_write_random_index_pack(AVFormatContext *s)
 {
     MXFContext *mxf = s->priv_data;
-    ByteIOContext *pb = s->pb;
-    uint64_t pos = url_ftell(pb);
+    AVIOContext *pb = s->pb;
+    uint64_t pos = avio_tell(pb);
     int i;
 
-    put_buffer(pb, random_index_pack_key, 16);
+    avio_write(pb, random_index_pack_key, 16);
     klv_encode_ber_length(pb, 28 + 12*mxf->body_partitions_count);
 
     if (mxf->edit_unit_byte_count)
-        put_be32(pb, 1); // BodySID of header partition
+        avio_wb32(pb, 1); // BodySID of header partition
     else
-        put_be32(pb, 0);
-    put_be64(pb, 0); // offset of header partition
+        avio_wb32(pb, 0);
+    avio_wb64(pb, 0); // offset of header partition
 
     for (i = 0; i < mxf->body_partitions_count; i++) {
-        put_be32(pb, 1); // BodySID
-        put_be64(pb, mxf->body_partition_offset[i]);
+        avio_wb32(pb, 1); // BodySID
+        avio_wb64(pb, mxf->body_partition_offset[i]);
     }
 
-    put_be32(pb, 0); // BodySID of footer partition
-    put_be64(pb, mxf->footer_partition_offset);
+    avio_wb32(pb, 0); // BodySID of footer partition
+    avio_wb64(pb, mxf->footer_partition_offset);
 
-    put_be32(pb, url_ftell(pb) - pos + 4);
+    avio_wb32(pb, avio_tell(pb) - pos + 4);
 }
 
 static int mxf_write_footer(AVFormatContext *s)
 {
     MXFContext *mxf = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
 
     mxf->duration = mxf->last_indexed_edit_unit + mxf->edit_units_count;
 
     mxf_write_klv_fill(s);
-    mxf->footer_partition_offset = url_ftell(pb);
+    mxf->footer_partition_offset = avio_tell(pb);
     if (mxf->edit_unit_byte_count) { // no need to repeat index
         mxf_write_partition(s, 0, 0, footer_partition_key, 0);
     } else {
@@ -1780,8 +1784,8 @@ static int mxf_write_footer(AVFormatContext *s)
     mxf_write_klv_fill(s);
     mxf_write_random_index_pack(s);
 
-    if (!url_is_streamed(s->pb)) {
-        url_fseek(pb, 0, SEEK_SET);
+    if (s->pb->seekable) {
+        avio_seek(pb, 0, SEEK_SET);
         if (mxf->edit_unit_byte_count) {
             mxf_write_partition(s, 1, 2, header_closed_partition_key, 1);
             mxf_write_klv_fill(s);
@@ -1791,7 +1795,7 @@ static int mxf_write_footer(AVFormatContext *s)
         }
     }
 
-    put_flush_packet(pb);
+    avio_flush(pb);
 
     ff_audio_interleave_close(s);
 
@@ -1875,7 +1879,7 @@ static int mxf_interleave(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int
                                mxf_interleave_get_packet, mxf_compare_timestamps);
 }
 
-AVOutputFormat mxf_muxer = {
+AVOutputFormat ff_mxf_muxer = {
     "mxf",
     NULL_IF_CONFIG_SMALL("Material eXchange Format"),
     "application/mxf",
@@ -1891,7 +1895,7 @@ AVOutputFormat mxf_muxer = {
     mxf_interleave,
 };
 
-AVOutputFormat mxf_d10_muxer = {
+AVOutputFormat ff_mxf_d10_muxer = {
     "mxf_d10",
     NULL_IF_CONFIG_SMALL("Material eXchange Format, D-10 Mapping"),
     "application/mxf",
diff --git a/libavformat/mxg.c b/libavformat/mxg.c
new file mode 100644
index 0000000..5caa68a
--- /dev/null
+++ b/libavformat/mxg.c
@@ -0,0 +1,251 @@
+/*
+ * MxPEG clip file demuxer
+ * Copyright (c) 2010 Anatoly Nenashev
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "libavutil/intreadwrite.h"
+#include "libavcodec/mjpeg.h"
+#include "avformat.h"
+#include "avio.h"
+
+#define VIDEO_STREAM_INDEX 0
+#define AUDIO_STREAM_INDEX 1
+#define DEFAULT_PACKET_SIZE 1024
+#define OVERREAD_SIZE 3
+
+typedef struct MXGContext {
+    uint8_t *buffer;
+    uint8_t *buffer_ptr;
+    uint8_t *soi_ptr;
+    unsigned int buffer_size;
+    int64_t dts;
+    unsigned int cache_size;
+} MXGContext;
+
+static int mxg_read_header(AVFormatContext *s, AVFormatParameters *ap)
+{
+    AVStream *video_st, *audio_st;
+    MXGContext *mxg = s->priv_data;
+
+    /* video parameters will be extracted from the compressed bitstream */
+    video_st = av_new_stream(s, VIDEO_STREAM_INDEX);
+    if (!video_st)
+        return AVERROR(ENOMEM);
+    video_st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
+    video_st->codec->codec_id = CODEC_ID_MXPEG;
+    av_set_pts_info(video_st, 64, 1, 1000000);
+
+    audio_st = av_new_stream(s, AUDIO_STREAM_INDEX);
+    if (!audio_st)
+        return AVERROR(ENOMEM);
+    audio_st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
+    audio_st->codec->codec_id = CODEC_ID_PCM_ALAW;
+    audio_st->codec->channels = 1;
+    audio_st->codec->sample_rate = 8000;
+    audio_st->codec->bits_per_coded_sample = 8;
+    audio_st->codec->block_align = 1;
+    av_set_pts_info(audio_st, 64, 1, 1000000);
+
+    mxg->soi_ptr = mxg->buffer_ptr = mxg->buffer = 0;
+    mxg->buffer_size = 0;
+    mxg->dts = AV_NOPTS_VALUE;
+    mxg->cache_size = 0;
+
+    return 0;
+}
+
+static uint8_t* mxg_find_startmarker(uint8_t *p, uint8_t *end)
+{
+    for (; p < end - 3; p += 4) {
+        uint32_t x = *(uint32_t*)p;
+
+        if (x & (~(x+0x01010101)) & 0x80808080) {
+            if (p[0] == 0xff) {
+                return p;
+            } else if (p[1] == 0xff) {
+                return p+1;
+            } else if (p[2] == 0xff) {
+                return p+2;
+            } else if (p[3] == 0xff) {
+                return p+3;
+            }
+        }
+    }
+
+    for (; p < end; ++p) {
+        if (*p == 0xff) return p;
+    }
+
+    return end;
+}
+
+static int mxg_update_cache(AVFormatContext *s, unsigned int cache_size)
+{
+    MXGContext *mxg = s->priv_data;
+    unsigned int current_pos = mxg->buffer_ptr - mxg->buffer;
+    unsigned int soi_pos;
+    int ret;
+
+    /* reallocate internal buffer */
+    if (current_pos > current_pos + cache_size)
+        return AVERROR(ENOMEM);
+    if (mxg->soi_ptr) soi_pos = mxg->soi_ptr - mxg->buffer;
+    mxg->buffer = av_fast_realloc(mxg->buffer, &mxg->buffer_size,
+                                  current_pos + cache_size +
+                                  FF_INPUT_BUFFER_PADDING_SIZE);
+    if (!mxg->buffer)
+        return AVERROR(ENOMEM);
+    mxg->buffer_ptr = mxg->buffer + current_pos;
+    if (mxg->soi_ptr) mxg->soi_ptr = mxg->buffer + soi_pos;
+
+    /* get data */
+    ret = avio_read(s->pb, mxg->buffer_ptr + mxg->cache_size,
+                     cache_size - mxg->cache_size);
+    if (ret < 0)
+        return ret;
+
+    mxg->cache_size += ret;
+
+    return ret;
+}
+
+static int mxg_read_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    int ret;
+    unsigned int size;
+    uint8_t *startmarker_ptr, *end, *search_end, marker;
+    MXGContext *mxg = s->priv_data;
+
+    while (!s->pb->eof_reached && !s->pb->error){
+        if (mxg->cache_size <= OVERREAD_SIZE) {
+            /* update internal buffer */
+            ret = mxg_update_cache(s, DEFAULT_PACKET_SIZE + OVERREAD_SIZE);
+            if (ret < 0)
+                return ret;
+        }
+        end = mxg->buffer_ptr + mxg->cache_size;
+
+        /* find start marker - 0xff */
+        if (mxg->cache_size > OVERREAD_SIZE) {
+            search_end = end - OVERREAD_SIZE;
+            startmarker_ptr = mxg_find_startmarker(mxg->buffer_ptr, search_end);
+        } else {
+            search_end = end;
+            startmarker_ptr = mxg_find_startmarker(mxg->buffer_ptr, search_end);
+            if (startmarker_ptr >= search_end - 1 ||
+                *(startmarker_ptr + 1) != EOI) break;
+        }
+
+        if (startmarker_ptr != search_end) { /* start marker found */
+            marker = *(startmarker_ptr + 1);
+            mxg->buffer_ptr = startmarker_ptr + 2;
+            mxg->cache_size = end - mxg->buffer_ptr;
+
+            if (marker == SOI) {
+                mxg->soi_ptr = startmarker_ptr;
+            } else if (marker == EOI) {
+                if (!mxg->soi_ptr) {
+                    av_log(s, AV_LOG_WARNING, "Found EOI before SOI, skipping\n");
+                    continue;
+                }
+
+                pkt->pts = pkt->dts = mxg->dts;
+                pkt->stream_index = VIDEO_STREAM_INDEX;
+                pkt->destruct = NULL;
+                pkt->size = mxg->buffer_ptr - mxg->soi_ptr;
+                pkt->data = mxg->soi_ptr;
+
+                if (mxg->soi_ptr - mxg->buffer > mxg->cache_size) {
+                    if (mxg->cache_size > 0) {
+                        memcpy(mxg->buffer, mxg->buffer_ptr, mxg->cache_size);
+                    }
+
+                    mxg->buffer_ptr = mxg->buffer;
+                }
+                mxg->soi_ptr = 0;
+
+                return pkt->size;
+            } else if ( (SOF0 <= marker && marker <= SOF15) ||
+                        (SOS  <= marker && marker <= COM) ) {
+                /* all other markers that start marker segment also contain
+                   length value (see specification for JPEG Annex B.1) */
+                size = AV_RB16(mxg->buffer_ptr);
+                if (size < 2)
+                    return AVERROR(EINVAL);
+
+                if (mxg->cache_size < size) {
+                    ret = mxg_update_cache(s, size);
+                    if (ret < 0)
+                        return ret;
+                    startmarker_ptr = mxg->buffer_ptr - 2;
+                    mxg->cache_size = 0;
+                } else {
+                    mxg->cache_size -= size;
+                }
+
+                mxg->buffer_ptr += size;
+
+                if (marker == APP13 && size >= 16) { /* audio data */
+                    /* time (GMT) of first sample in usec since 1970, little-endian */
+                    pkt->pts = pkt->dts = AV_RL64(startmarker_ptr + 8);
+                    pkt->stream_index = AUDIO_STREAM_INDEX;
+                    pkt->destruct = NULL;
+                    pkt->size = size - 14;
+                    pkt->data = startmarker_ptr + 16;
+
+                    if (startmarker_ptr - mxg->buffer > mxg->cache_size) {
+                        if (mxg->cache_size > 0) {
+                            memcpy(mxg->buffer, mxg->buffer_ptr, mxg->cache_size);
+                        }
+                        mxg->buffer_ptr = mxg->buffer;
+                    }
+
+                    return pkt->size;
+                } else if (marker == COM && size >= 18 &&
+                           !strncmp(startmarker_ptr + 4, "MXF", 3)) {
+                    /* time (GMT) of video frame in usec since 1970, little-endian */
+                    mxg->dts = AV_RL64(startmarker_ptr + 12);
+                }
+            }
+        } else {
+            /* start marker not found */
+            mxg->buffer_ptr = search_end;
+            mxg->cache_size = OVERREAD_SIZE;
+        }
+    }
+
+    return AVERROR_EOF;
+}
+
+static int mxg_close(struct AVFormatContext *s)
+{
+    MXGContext *mxg = s->priv_data;
+    av_freep(&mxg->buffer);
+    return 0;
+}
+
+AVInputFormat ff_mxg_demuxer = {
+    .name = "mxg",
+    .long_name = NULL_IF_CONFIG_SMALL("MxPEG clip file format"),
+    .priv_data_size = sizeof(MXGContext),
+    .read_header = mxg_read_header,
+    .read_packet = mxg_read_packet,
+    .read_close = mxg_close,
+    .extensions = "mxg"
+};
diff --git a/libavformat/ncdec.c b/libavformat/ncdec.c
index 6d99a04..7e43adc 100644
--- a/libavformat/ncdec.c
+++ b/libavformat/ncdec.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2009  Nicolas Martin (martinic at iro dot umontreal dot ca)
  *                     Edouard Auvinet
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -66,14 +66,14 @@ static int nc_read_packet(AVFormatContext *s, AVPacket *pkt)
 
     uint32_t state=-1;
     while (state != NC_VIDEO_FLAG) {
-        if (url_feof(s->pb))
+        if (s->pb->eof_reached)
             return AVERROR(EIO);
-        state = (state<<8) + get_byte(s->pb);
+        state = (state<<8) + avio_r8(s->pb);
     }
 
-    get_byte(s->pb);
-    size = get_le16(s->pb);
-    url_fskip(s->pb, 9);
+    avio_r8(s->pb);
+    size = avio_rl16(s->pb);
+    avio_skip(s->pb, 9);
 
     if (size == 0) {
         av_log(s, AV_LOG_DEBUG, "Next packet size is zero\n");
@@ -90,7 +90,7 @@ static int nc_read_packet(AVFormatContext *s, AVPacket *pkt)
     return size;
 }
 
-AVInputFormat nc_demuxer = {
+AVInputFormat ff_nc_demuxer = {
     "nc",
     NULL_IF_CONFIG_SMALL("NC camera feed format"),
     0,
diff --git a/libavformat/network.h b/libavformat/network.h
index 0fbcbbb..84a8f53 100644
--- a/libavformat/network.h
+++ b/libavformat/network.h
@@ -1,20 +1,20 @@
 /*
- * Copyright (c) 2007 The FFmpeg Project
+ * Copyright (c) 2007 The Libav Project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -22,14 +22,27 @@
 #define AVFORMAT_NETWORK_H
 
 #include "config.h"
+#include "os_support.h"
 
 #if HAVE_WINSOCK2_H
 #include <winsock2.h>
 #include <ws2tcpip.h>
 
-#define ff_neterrno() (-WSAGetLastError())
-#define FF_NETERROR(err) (-WSA##err)
-#define WSAEAGAIN WSAEWOULDBLOCK
+#define EPROTONOSUPPORT WSAEPROTONOSUPPORT
+#define ETIMEDOUT       WSAETIMEDOUT
+#define ECONNREFUSED    WSAECONNREFUSED
+#define EINPROGRESS     WSAEINPROGRESS
+
+static inline int ff_neterrno() {
+    int err = WSAGetLastError();
+    switch (err) {
+    case WSAEWOULDBLOCK:
+        return AVERROR(EAGAIN);
+    case WSAEINTR:
+        return AVERROR(EINTR);
+    }
+    return -err;
+}
 #else
 #include <sys/types.h>
 #include <sys/socket.h>
@@ -37,13 +50,16 @@
 #include <netdb.h>
 
 #define ff_neterrno() AVERROR(errno)
-#define FF_NETERROR(err) AVERROR(err)
 #endif
 
 #if HAVE_ARPA_INET_H
 #include <arpa/inet.h>
 #endif
 
+#if HAVE_POLL_H
+#include <poll.h>
+#endif
+
 int ff_socket_nonblock(int socket, int enable);
 
 static inline int ff_network_init(void)
@@ -56,6 +72,15 @@ static inline int ff_network_init(void)
     return 1;
 }
 
+static inline int ff_network_wait_fd(int fd, int write)
+{
+    int ev = write ? POLLOUT : POLLIN;
+    struct pollfd p = { .fd = fd, .events = ev, .revents = 0 };
+    int ret;
+    ret = poll(&p, 1, 100);
+    return ret < 0 ? ff_neterrno() : p.revents & ev ? 0 : AVERROR(EAGAIN);
+}
+
 static inline void ff_network_close(void)
 {
 #if HAVE_WINSOCK2_H
@@ -151,4 +176,29 @@ const char *ff_gai_strerror(int ecode);
 #define gai_strerror ff_gai_strerror
 #endif
 
+#ifndef INET6_ADDRSTRLEN
+#define INET6_ADDRSTRLEN INET_ADDRSTRLEN
+#endif
+
+#ifndef IN_MULTICAST
+#define IN_MULTICAST(a) ((((uint32_t)(a)) & 0xf0000000) == 0xe0000000)
+#endif
+#ifndef IN6_IS_ADDR_MULTICAST
+#define IN6_IS_ADDR_MULTICAST(a) (((uint8_t *) (a))[0] == 0xff)
+#endif
+
+static inline int ff_is_multicast_address(struct sockaddr *addr)
+{
+    if (addr->sa_family == AF_INET) {
+        return IN_MULTICAST(ntohl(((struct sockaddr_in *)addr)->sin_addr.s_addr));
+    }
+#if HAVE_STRUCT_SOCKADDR_IN6
+    if (addr->sa_family == AF_INET6) {
+        return IN6_IS_ADDR_MULTICAST(&((struct sockaddr_in6 *)addr)->sin6_addr);
+    }
+#endif
+
+    return 0;
+}
+
 #endif /* AVFORMAT_NETWORK_H */
diff --git a/libavformat/nsvdec.c b/libavformat/nsvdec.c
index 44e5097..b70d3b9 100644
--- a/libavformat/nsvdec.c
+++ b/libavformat/nsvdec.c
@@ -1,21 +1,21 @@
 /*
  * NSV demuxer
- * Copyright (c) 2004 The FFmpeg Project
+ * Copyright (c) 2004 The Libav Project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #include "avformat.h"
@@ -81,12 +81,6 @@
  * - seek
  */
 
-#ifdef DEBUG
-#define PRINT(_v) printf _v
-#else
-#define PRINT(_v)
-#endif
-
 #if 0
 struct NSVf_header {
     uint32_t chunk_tag; /* 'NSVf' */
@@ -216,102 +210,96 @@ static const AVCodecTag nsv_codec_audio_tags[] = {
 //static int nsv_load_index(AVFormatContext *s);
 static int nsv_read_chunk(AVFormatContext *s, int fill_header);
 
-#ifdef DEBUG
-static void print_tag(const char *str, unsigned int tag, int size)
-{
-    printf("%s: tag=%c%c%c%c\n",
-           str, tag & 0xff,
-           (tag >> 8) & 0xff,
-           (tag >> 16) & 0xff,
-           (tag >> 24) & 0xff);
-}
-#endif
+#define print_tag(str, tag, size)       \
+    av_dlog(NULL, "%s: tag=%c%c%c%c\n", \
+            str, tag & 0xff,            \
+            (tag >> 8) & 0xff,          \
+            (tag >> 16) & 0xff,         \
+            (tag >> 24) & 0xff);
 
 /* try to find something we recognize, and set the state accordingly */
 static int nsv_resync(AVFormatContext *s)
 {
     NSVContext *nsv = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     uint32_t v = 0;
     int i;
 
-    PRINT(("%s(), offset = %"PRId64", state = %d\n", __FUNCTION__, url_ftell(pb), nsv->state));
+    av_dlog(s, "%s(), offset = %"PRId64", state = %d\n", __FUNCTION__, avio_tell(pb), nsv->state);
 
     //nsv->state = NSV_UNSYNC;
 
     for (i = 0; i < NSV_MAX_RESYNC; i++) {
-        if (url_feof(pb)) {
-            PRINT(("NSV EOF\n"));
+        if (pb->eof_reached) {
+            av_dlog(s, "NSV EOF\n");
             nsv->state = NSV_UNSYNC;
             return -1;
         }
         v <<= 8;
-        v |= get_byte(pb);
-/*
+        v |= avio_r8(pb);
         if (i < 8) {
-            PRINT(("NSV resync: [%d] = %02x\n", i, v & 0x0FF));
+            av_dlog(s, "NSV resync: [%d] = %02x\n", i, v & 0x0FF);
         }
-*/
 
         if ((v & 0x0000ffff) == 0xefbe) { /* BEEF */
-            PRINT(("NSV resynced on BEEF after %d bytes\n", i+1));
+            av_dlog(s, "NSV resynced on BEEF after %d bytes\n", i+1);
             nsv->state = NSV_FOUND_BEEF;
             return 0;
         }
         /* we read as big endian, thus the MK*BE* */
         if (v == TB_NSVF) { /* NSVf */
-            PRINT(("NSV resynced on NSVf after %d bytes\n", i+1));
+            av_dlog(s, "NSV resynced on NSVf after %d bytes\n", i+1);
             nsv->state = NSV_FOUND_NSVF;
             return 0;
         }
         if (v == MKBETAG('N', 'S', 'V', 's')) { /* NSVs */
-            PRINT(("NSV resynced on NSVs after %d bytes\n", i+1));
+            av_dlog(s, "NSV resynced on NSVs after %d bytes\n", i+1);
             nsv->state = NSV_FOUND_NSVS;
             return 0;
         }
 
     }
-    PRINT(("NSV sync lost\n"));
+    av_dlog(s, "NSV sync lost\n");
     return -1;
 }
 
 static int nsv_parse_NSVf_header(AVFormatContext *s, AVFormatParameters *ap)
 {
     NSVContext *nsv = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     unsigned int file_size, size;
     int64_t duration;
     int strings_size;
     int table_entries;
     int table_entries_used;
 
-    PRINT(("%s()\n", __FUNCTION__));
+    av_dlog(s, "%s()\n", __FUNCTION__);
 
     nsv->state = NSV_UNSYNC; /* in case we fail */
 
-    size = get_le32(pb);
+    size = avio_rl32(pb);
     if (size < 28)
         return -1;
     nsv->NSVf_end = size;
 
-    //s->file_size = (uint32_t)get_le32(pb);
-    file_size = (uint32_t)get_le32(pb);
-    PRINT(("NSV NSVf chunk_size %u\n", size));
-    PRINT(("NSV NSVf file_size %u\n", file_size));
+    //s->file_size = (uint32_t)avio_rl32(pb);
+    file_size = (uint32_t)avio_rl32(pb);
+    av_dlog(s, "NSV NSVf chunk_size %u\n", size);
+    av_dlog(s, "NSV NSVf file_size %u\n", file_size);
 
-    nsv->duration = duration = get_le32(pb); /* in ms */
-    PRINT(("NSV NSVf duration %"PRId64" ms\n", duration));
+    nsv->duration = duration = avio_rl32(pb); /* in ms */
+    av_dlog(s, "NSV NSVf duration %"PRId64" ms\n", duration);
     // XXX: store it in AVStreams
 
-    strings_size = get_le32(pb);
-    table_entries = get_le32(pb);
-    table_entries_used = get_le32(pb);
-    PRINT(("NSV NSVf info-strings size: %d, table entries: %d, bis %d\n",
-            strings_size, table_entries, table_entries_used));
-    if (url_feof(pb))
+    strings_size = avio_rl32(pb);
+    table_entries = avio_rl32(pb);
+    table_entries_used = avio_rl32(pb);
+    av_dlog(s, "NSV NSVf info-strings size: %d, table entries: %d, bis %d\n",
+            strings_size, table_entries, table_entries_used);
+    if (pb->eof_reached)
         return -1;
 
-    PRINT(("NSV got header; filepos %"PRId64"\n", url_ftell(pb)));
+    av_dlog(s, "NSV got header; filepos %"PRId64"\n", avio_tell(pb));
 
     if (strings_size > 0) {
         char *strings; /* last byte will be '\0' to play safe with str*() */
@@ -321,7 +309,7 @@ static int nsv_parse_NSVf_header(AVFormatContext *s, AVFormatParameters *ap)
 
         p = strings = av_mallocz(strings_size + 1);
         endp = strings + strings_size;
-        get_buffer(pb, strings, strings_size);
+        avio_read(pb, strings, strings_size);
         while (p < endp) {
             while (*p == ' ')
                 p++; /* strip out spaces */
@@ -338,15 +326,15 @@ static int nsv_parse_NSVf_header(AVFormatContext *s, AVFormatParameters *ap)
             if (!p || p >= endp)
                 break;
             *p++ = '\0';
-            PRINT(("NSV NSVf INFO: %s='%s'\n", token, value));
+            av_dlog(s, "NSV NSVf INFO: %s='%s'\n", token, value);
             av_metadata_set2(&s->metadata, token, value, 0);
         }
         av_free(strings);
     }
-    if (url_feof(pb))
+    if (pb->eof_reached)
         return -1;
 
-    PRINT(("NSV got infos; filepos %"PRId64"\n", url_ftell(pb)));
+    av_dlog(s, "NSV got infos; filepos %"PRId64"\n", avio_tell(pb));
 
     if (table_entries_used > 0) {
         int i;
@@ -356,41 +344,41 @@ static int nsv_parse_NSVf_header(AVFormatContext *s, AVFormatParameters *ap)
         nsv->nsvs_file_offset = av_malloc((unsigned)table_entries_used * sizeof(uint32_t));
 
         for(i=0;i<table_entries_used;i++)
-            nsv->nsvs_file_offset[i] = get_le32(pb) + size;
+            nsv->nsvs_file_offset[i] = avio_rl32(pb) + size;
 
         if(table_entries > table_entries_used &&
-           get_le32(pb) == MKTAG('T','O','C','2')) {
+           avio_rl32(pb) == MKTAG('T','O','C','2')) {
             nsv->nsvs_timestamps = av_malloc((unsigned)table_entries_used*sizeof(uint32_t));
             for(i=0;i<table_entries_used;i++) {
-                nsv->nsvs_timestamps[i] = get_le32(pb);
+                nsv->nsvs_timestamps[i] = avio_rl32(pb);
             }
         }
     }
 
-    PRINT(("NSV got index; filepos %"PRId64"\n", url_ftell(pb)));
+    av_dlog(s, "NSV got index; filepos %"PRId64"\n", avio_tell(pb));
 
 #ifdef DEBUG_DUMP_INDEX
 #define V(v) ((v<0x20 || v > 127)?'.':v)
     /* dump index */
-    PRINT(("NSV %d INDEX ENTRIES:\n", table_entries));
-    PRINT(("NSV [dataoffset][fileoffset]\n", table_entries));
+    av_dlog(s, "NSV %d INDEX ENTRIES:\n", table_entries);
+    av_dlog(s, "NSV [dataoffset][fileoffset]\n", table_entries);
     for (i = 0; i < table_entries; i++) {
         unsigned char b[8];
-        url_fseek(pb, size + nsv->nsvs_file_offset[i], SEEK_SET);
-        get_buffer(pb, b, 8);
-        PRINT(("NSV [0x%08lx][0x%08lx]: %02x %02x %02x %02x %02x %02x %02x %02x"
+        avio_seek(pb, size + nsv->nsvs_file_offset[i], SEEK_SET);
+        avio_read(pb, b, 8);
+        av_dlog(s, "NSV [0x%08lx][0x%08lx]: %02x %02x %02x %02x %02x %02x %02x %02x"
            "%c%c%c%c%c%c%c%c\n",
            nsv->nsvs_file_offset[i], size + nsv->nsvs_file_offset[i],
            b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7],
-           V(b[0]), V(b[1]), V(b[2]), V(b[3]), V(b[4]), V(b[5]), V(b[6]), V(b[7]) ));
+           V(b[0]), V(b[1]), V(b[2]), V(b[3]), V(b[4]), V(b[5]), V(b[6]), V(b[7]) );
     }
-    //url_fseek(pb, size, SEEK_SET); /* go back to end of header */
+    //avio_seek(pb, size, SEEK_SET); /* go back to end of header */
 #undef V
 #endif
 
-    url_fseek(pb, nsv->base_offset + size, SEEK_SET); /* required for dumbdriving-271.nsv (2 extra bytes) */
+    avio_seek(pb, nsv->base_offset + size, SEEK_SET); /* required for dumbdriving-271.nsv (2 extra bytes) */
 
-    if (url_feof(pb))
+    if (pb->eof_reached)
         return -1;
     nsv->state = NSV_HAS_READ_NSVF;
     return 0;
@@ -399,22 +387,22 @@ static int nsv_parse_NSVf_header(AVFormatContext *s, AVFormatParameters *ap)
 static int nsv_parse_NSVs_header(AVFormatContext *s, AVFormatParameters *ap)
 {
     NSVContext *nsv = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     uint32_t vtag, atag;
     uint16_t vwidth, vheight;
     AVRational framerate;
     int i;
     AVStream *st;
     NSVStream *nst;
-    PRINT(("%s()\n", __FUNCTION__));
+    av_dlog(s, "%s()\n", __FUNCTION__);
 
-    vtag = get_le32(pb);
-    atag = get_le32(pb);
-    vwidth = get_le16(pb);
-    vheight = get_le16(pb);
-    i = get_byte(pb);
+    vtag = avio_rl32(pb);
+    atag = avio_rl32(pb);
+    vwidth = avio_rl16(pb);
+    vheight = avio_rl16(pb);
+    i = avio_r8(pb);
 
-    PRINT(("NSV NSVs framerate code %2x\n", i));
+    av_dlog(s, "NSV NSVs framerate code %2x\n", i);
     if(i&0x80) { /* odd way of giving native framerates from docs */
         int t=(i & 0x7F)>>2;
         if(t<16) framerate = (AVRational){1, t+1};
@@ -432,13 +420,12 @@ static int nsv_parse_NSVs_header(AVFormatContext *s, AVFormatParameters *ap)
     else
         framerate= (AVRational){i, 1};
 
-    nsv->avsync = get_le16(pb);
+    nsv->avsync = avio_rl16(pb);
     nsv->framerate = framerate;
-#ifdef DEBUG
+
     print_tag("NSV NSVs vtag", vtag, 0);
     print_tag("NSV NSVs atag", atag, 0);
-    PRINT(("NSV NSVs vsize %dx%d\n", vwidth, vheight));
-#endif
+    av_dlog(s, "NSV NSVs vsize %dx%d\n", vwidth, vheight);
 
     /* XXX change to ap != NULL ? */
     if (s->nb_streams == 0) { /* streams not yet published, let's do that */
@@ -502,7 +489,7 @@ static int nsv_parse_NSVs_header(AVFormatContext *s, AVFormatParameters *ap)
 #ifdef CHECK_SUBSEQUENT_NSVS
     } else {
         if (nsv->vtag != vtag || nsv->atag != atag || nsv->vwidth != vwidth || nsv->vheight != vwidth) {
-            PRINT(("NSV NSVs header values differ from the first one!!!\n"));
+            av_dlog(s, "NSV NSVs header values differ from the first one!!!\n");
             //return -1;
         }
 #endif /* CHECK_SUBSEQUENT_NSVS */
@@ -521,8 +508,8 @@ static int nsv_read_header(AVFormatContext *s, AVFormatParameters *ap)
     NSVContext *nsv = s->priv_data;
     int i, err;
 
-    PRINT(("%s()\n", __FUNCTION__));
-    PRINT(("filename '%s'\n", s->filename));
+    av_dlog(s, "%s()\n", __FUNCTION__);
+    av_dlog(s, "filename '%s'\n", s->filename);
 
     nsv->state = NSV_UNSYNC;
     nsv->ahead[0].data = nsv->ahead[1].data = NULL;
@@ -543,14 +530,14 @@ static int nsv_read_header(AVFormatContext *s, AVFormatParameters *ap)
     /* now read the first chunk, so we can attempt to decode more info */
     err = nsv_read_chunk(s, 1);
 
-    PRINT(("parsed header\n"));
+    av_dlog(s, "parsed header\n");
     return 0;
 }
 
 static int nsv_read_chunk(AVFormatContext *s, int fill_header)
 {
     NSVContext *nsv = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVStream *st[2] = {NULL, NULL};
     NSVStream *nst;
     AVPacket *pkt;
@@ -561,13 +548,13 @@ static int nsv_read_chunk(AVFormatContext *s, int fill_header)
     uint16_t auxsize;
     uint32_t auxtag;
 
-    PRINT(("%s(%d)\n", __FUNCTION__, fill_header));
+    av_dlog(s, "%s(%d)\n", __FUNCTION__, fill_header);
 
     if (nsv->ahead[0].data || nsv->ahead[1].data)
         return 0; //-1; /* hey! eat what you've in your plate first! */
 
 null_chunk_retry:
-    if (url_feof(pb))
+    if (pb->eof_reached)
         return -1;
 
     for (i = 0; i < NSV_MAX_RESYNC_TRIES && nsv->state < NSV_FOUND_NSVS && !err; i++)
@@ -581,27 +568,27 @@ null_chunk_retry:
     if (nsv->state != NSV_HAS_READ_NSVS && nsv->state != NSV_FOUND_BEEF)
         return -1;
 
-    auxcount = get_byte(pb);
-    vsize = get_le16(pb);
-    asize = get_le16(pb);
+    auxcount = avio_r8(pb);
+    vsize = avio_rl16(pb);
+    asize = avio_rl16(pb);
     vsize = (vsize << 4) | (auxcount >> 4);
     auxcount &= 0x0f;
-    PRINT(("NSV CHUNK %d aux, %u bytes video, %d bytes audio\n", auxcount, vsize, asize));
+    av_dlog(s, "NSV CHUNK %d aux, %u bytes video, %d bytes audio\n", auxcount, vsize, asize);
     /* skip aux stuff */
     for (i = 0; i < auxcount; i++) {
-        auxsize = get_le16(pb);
-        auxtag = get_le32(pb);
-        PRINT(("NSV aux data: '%c%c%c%c', %d bytes\n",
+        auxsize = avio_rl16(pb);
+        auxtag = avio_rl32(pb);
+        av_dlog(s, "NSV aux data: '%c%c%c%c', %d bytes\n",
               (auxtag & 0x0ff),
               ((auxtag >> 8) & 0x0ff),
               ((auxtag >> 16) & 0x0ff),
               ((auxtag >> 24) & 0x0ff),
-              auxsize));
-        url_fskip(pb, auxsize);
+              auxsize);
+        avio_skip(pb, auxsize);
         vsize -= auxsize + sizeof(uint16_t) + sizeof(uint32_t); /* that's becoming braindead */
     }
 
-    if (url_feof(pb))
+    if (pb->eof_reached)
         return -1;
     if (!vsize && !asize) {
         nsv->state = NSV_UNSYNC;
@@ -621,10 +608,8 @@ null_chunk_retry:
         pkt->stream_index = st[NSV_ST_VIDEO]->index;//NSV_ST_VIDEO;
         pkt->dts = nst->frame_offset;
         pkt->flags |= nsv->state == NSV_HAS_READ_NSVS ? AV_PKT_FLAG_KEY : 0; /* keyframe only likely on a sync frame */
-/*
-        for (i = 0; i < MIN(8, vsize); i++)
-            PRINT(("NSV video: [%d] = %02x\n", i, pkt->data[i]));
-*/
+        for (i = 0; i < FFMIN(8, vsize); i++)
+            av_dlog(s, "NSV video: [%d] = %02x\n", i, pkt->data[i]);
     }
     if(st[NSV_ST_VIDEO])
         ((NSVStream*)st[NSV_ST_VIDEO]->priv_data)->frame_offset++;
@@ -638,15 +623,15 @@ null_chunk_retry:
             uint8_t bps;
             uint8_t channels;
             uint16_t samplerate;
-            bps = get_byte(pb);
-            channels = get_byte(pb);
-            samplerate = get_le16(pb);
+            bps = avio_r8(pb);
+            channels = avio_r8(pb);
+            samplerate = avio_rl16(pb);
             asize-=4;
-            PRINT(("NSV RAWAUDIO: bps %d, nchan %d, srate %d\n", bps, channels, samplerate));
+            av_dlog(s, "NSV RAWAUDIO: bps %d, nchan %d, srate %d\n", bps, channels, samplerate);
             if (fill_header) {
                 st[NSV_ST_AUDIO]->need_parsing = AVSTREAM_PARSE_NONE; /* we know everything */
                 if (bps != 16) {
-                    PRINT(("NSV AUDIO bit/sample != 16 (%d)!!!\n", bps));
+                    av_dlog(s, "NSV AUDIO bit/sample != 16 (%d)!!!\n", bps);
                 }
                 bps /= channels; // ???
                 if (bps == 8)
@@ -655,7 +640,7 @@ null_chunk_retry:
                 channels = 1;
                 st[NSV_ST_AUDIO]->codec->channels = channels;
                 st[NSV_ST_AUDIO]->codec->sample_rate = samplerate;
-                PRINT(("NSV RAWAUDIO: bps %d, nchan %d, srate %d\n", bps, channels, samplerate));
+                av_dlog(s, "NSV RAWAUDIO: bps %d, nchan %d, srate %d\n", bps, channels, samplerate);
             }
         }
         av_get_packet(pb, pkt, asize);
@@ -666,7 +651,7 @@ null_chunk_retry:
             pkt->dts = (((NSVStream*)st[NSV_ST_VIDEO]->priv_data)->frame_offset-1);
             pkt->dts *= (int64_t)1000        * nsv->framerate.den;
             pkt->dts += (int64_t)nsv->avsync * nsv->framerate.num;
-            PRINT(("NSV AUDIO: sync:%d, dts:%"PRId64, nsv->avsync, pkt->dts));
+            av_dlog(s, "NSV AUDIO: sync:%d, dts:%"PRId64, nsv->avsync, pkt->dts);
         }
         nst->frame_offset++;
     }
@@ -681,7 +666,7 @@ static int nsv_read_packet(AVFormatContext *s, AVPacket *pkt)
     NSVContext *nsv = s->priv_data;
     int i, err = 0;
 
-    PRINT(("%s()\n", __FUNCTION__));
+    av_dlog(s, "%s()\n", __FUNCTION__);
 
     /* in case we don't already have something to eat ... */
     if (nsv->ahead[0].data == NULL && nsv->ahead[1].data == NULL)
@@ -692,7 +677,7 @@ static int nsv_read_packet(AVFormatContext *s, AVPacket *pkt)
     /* now pick one of the plates */
     for (i = 0; i < 2; i++) {
         if (nsv->ahead[i].data) {
-                PRINT(("%s: using cached packet[%d]\n", __FUNCTION__, i));
+            av_dlog(s, "%s: using cached packet[%d]\n", __FUNCTION__, i);
             /* avoid the cost of new_packet + memcpy(->data) */
             memcpy(pkt, &nsv->ahead[i], sizeof(AVPacket));
             nsv->ahead[i].data = NULL; /* we ate that one */
@@ -715,7 +700,7 @@ static int nsv_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp
     if(index < 0)
         return -1;
 
-    url_fseek(s->pb, st->index_entries[index].pos, SEEK_SET);
+    avio_seek(s->pb, st->index_entries[index].pos, SEEK_SET);
     nst->frame_offset = st->index_entries[index].timestamp;
     nsv->state = NSV_UNSYNC;
     return 0;
@@ -752,7 +737,7 @@ static int nsv_read_close(AVFormatContext *s)
 static int nsv_probe(AVProbeData *p)
 {
     int i;
-//    PRINT(("nsv_probe(), buf_size %d\n", p->buf_size));
+    av_dlog(NULL, "nsv_probe(), buf_size %d\n", p->buf_size);
     /* check file header */
     /* streamed files might not have any header */
     if (p->buf[0] == 'N' && p->buf[1] == 'S' &&
@@ -774,7 +759,7 @@ static int nsv_probe(AVProbeData *p)
     return 0;
 }
 
-AVInputFormat nsv_demuxer = {
+AVInputFormat ff_nsv_demuxer = {
     "nsv",
     NULL_IF_CONFIG_SMALL("Nullsoft Streaming Video"),
     sizeof(NSVContext),
diff --git a/libavformat/nullenc.c b/libavformat/nullenc.c
new file mode 100644
index 0000000..8e38b27
--- /dev/null
+++ b/libavformat/nullenc.c
@@ -0,0 +1,40 @@
+/*
+ * RAW null muxer
+ * Copyright (c) 2002 Fabrice Bellard
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "avformat.h"
+
+static int null_write_packet(struct AVFormatContext *s, AVPacket *pkt)
+{
+    return 0;
+}
+
+AVOutputFormat ff_null_muxer = {
+    "null",
+    NULL_IF_CONFIG_SMALL("raw null video format"),
+    NULL,
+    NULL,
+    0,
+    AV_NE(CODEC_ID_PCM_S16BE, CODEC_ID_PCM_S16LE),
+    CODEC_ID_RAWVIDEO,
+    NULL,
+    null_write_packet,
+    .flags = AVFMT_NOFILE | AVFMT_RAWPICTURE | AVFMT_NOTIMESTAMPS,
+};
diff --git a/libavformat/nut.c b/libavformat/nut.c
index 9a6a41b..3a6e28f 100644
--- a/libavformat/nut.c
+++ b/libavformat/nut.c
@@ -2,25 +2,26 @@
  * nut
  * Copyright (c) 2004-2007 Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "libavutil/tree.h"
 #include "nut.h"
+#include "internal.h"
 
 const AVCodecTag ff_nut_subtitle_tags[] = {
     { CODEC_ID_TEXT        , MKTAG('U', 'T', 'F', '8') },
@@ -30,6 +31,55 @@ const AVCodecTag ff_nut_subtitle_tags[] = {
     { CODEC_ID_NONE        , 0                         }
 };
 
+const AVCodecTag ff_nut_video_tags[] = {
+    { CODEC_ID_RAWVIDEO, MKTAG('R', 'G', 'B', 15 ) },
+    { CODEC_ID_RAWVIDEO, MKTAG('B', 'G', 'R', 15 ) },
+    { CODEC_ID_RAWVIDEO, MKTAG('R', 'G', 'B', 16 ) },
+    { CODEC_ID_RAWVIDEO, MKTAG('B', 'G', 'R', 16 ) },
+    { CODEC_ID_RAWVIDEO, MKTAG(15 , 'B', 'G', 'R') },
+    { CODEC_ID_RAWVIDEO, MKTAG(15 , 'R', 'G', 'B') },
+    { CODEC_ID_RAWVIDEO, MKTAG(16 , 'B', 'G', 'R') },
+    { CODEC_ID_RAWVIDEO, MKTAG(16 , 'R', 'G', 'B') },
+    { CODEC_ID_RAWVIDEO, MKTAG('R', 'G', 'B', 12 ) },
+    { CODEC_ID_RAWVIDEO, MKTAG('B', 'G', 'R', 12 ) },
+    { CODEC_ID_RAWVIDEO, MKTAG(12 , 'B', 'G', 'R') },
+    { CODEC_ID_RAWVIDEO, MKTAG(12 , 'R', 'G', 'B') },
+    { CODEC_ID_RAWVIDEO, MKTAG('R', 'G', 'B', 'A') },
+    { CODEC_ID_RAWVIDEO, MKTAG('B', 'G', 'R', 'A') },
+    { CODEC_ID_RAWVIDEO, MKTAG('A', 'B', 'G', 'R') },
+    { CODEC_ID_RAWVIDEO, MKTAG('A', 'R', 'G', 'B') },
+    { CODEC_ID_RAWVIDEO, MKTAG('R', 'G', 'B', 24 ) },
+    { CODEC_ID_RAWVIDEO, MKTAG('B', 'G', 'R', 24 ) },
+    { CODEC_ID_RAWVIDEO, MKTAG('4', '1', '1', 'P') },
+    { CODEC_ID_RAWVIDEO, MKTAG('4', '2', '2', 'P') },
+    { CODEC_ID_RAWVIDEO, MKTAG('4', '2', '2', 'P') },
+    { CODEC_ID_RAWVIDEO, MKTAG('4', '4', '0', 'P') },
+    { CODEC_ID_RAWVIDEO, MKTAG('4', '4', '0', 'P') },
+    { CODEC_ID_RAWVIDEO, MKTAG('4', '4', '4', 'P') },
+    { CODEC_ID_RAWVIDEO, MKTAG('4', '4', '4', 'P') },
+    { CODEC_ID_RAWVIDEO, MKTAG('B', '1', 'W', '0') },
+    { CODEC_ID_RAWVIDEO, MKTAG('B', '0', 'W', '1') },
+    { CODEC_ID_RAWVIDEO, MKTAG('B', 'G', 'R',  8 ) },
+    { CODEC_ID_RAWVIDEO, MKTAG('R', 'G', 'B',  8 ) },
+    { CODEC_ID_RAWVIDEO, MKTAG('B', 'G', 'R',  4 ) },
+    { CODEC_ID_RAWVIDEO, MKTAG('R', 'G', 'B',  4 ) },
+    { CODEC_ID_RAWVIDEO, MKTAG('B', '4', 'B', 'Y') },
+    { CODEC_ID_RAWVIDEO, MKTAG('R', '4', 'B', 'Y') },
+    { CODEC_ID_RAWVIDEO, MKTAG('R', 'G', 'B', 48 ) },
+    { CODEC_ID_RAWVIDEO, MKTAG(48 , 'R', 'G', 'B') },
+    { CODEC_ID_RAWVIDEO, MKTAG('Y', '1',  0 , 16 ) },
+    { CODEC_ID_RAWVIDEO, MKTAG(16 ,  0 , '1', 'Y') },
+    { CODEC_ID_RAWVIDEO, MKTAG('Y', '3', 11 , 16 ) },
+    { CODEC_ID_RAWVIDEO, MKTAG(16 , 11 , '3', 'Y') },
+    { CODEC_ID_RAWVIDEO, MKTAG('Y', '3', 10 , 16 ) },
+    { CODEC_ID_RAWVIDEO, MKTAG(16 , 10 , '3', 'Y') },
+    { CODEC_ID_RAWVIDEO, MKTAG('Y', '3',  0 , 16 ) },
+    { CODEC_ID_RAWVIDEO, MKTAG(16 ,  0 , '3', 'Y') },
+    { CODEC_ID_RAWVIDEO, MKTAG('Y', '4', 11 ,  8 ) },
+    { CODEC_ID_RAWVIDEO, MKTAG('Y', '2',  0 ,  8 ) },
+    { CODEC_ID_NONE    , 0                         }
+};
+
 void ff_nut_reset_ts(NUTContext *nut, AVRational time_base, int64_t val){
     int i;
     for(i=0; i<nut->avf->nb_streams; i++){
diff --git a/libavformat/nut.h b/libavformat/nut.h
index ce052df..419b123 100644
--- a/libavformat/nut.h
+++ b/libavformat/nut.h
@@ -2,20 +2,20 @@
  * "NUT" Container Format (de)muxer
  * Copyright (c) 2006 Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -82,6 +82,10 @@ typedef struct {
 } StreamContext;
 
 typedef struct {
+    AVRational *time_base;
+} ChapterContext;
+
+typedef struct {
     AVFormatContext *avf;
 //    int written_packet_size;
 //    int64_t packet_start;
@@ -90,6 +94,7 @@ typedef struct {
     const uint8_t *header[128];
     uint64_t next_startcode;     ///< stores the next startcode if it has already been parsed but the stream is not seekable
     StreamContext *stream;
+    ChapterContext *chapter;
     unsigned int max_distance;
     unsigned int time_base_count;
     int64_t last_syncpoint_pos;
@@ -99,6 +104,7 @@ typedef struct {
 } NUTContext;
 
 extern const AVCodecTag ff_nut_subtitle_tags[];
+extern const AVCodecTag ff_nut_video_tags[];
 
 typedef struct {
     char str[9];
diff --git a/libavformat/nutdec.c b/libavformat/nutdec.c
index 5d5cd55..d3804f2 100644
--- a/libavformat/nutdec.c
+++ b/libavformat/nutdec.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2004-2006 Michael Niedermayer
  * Copyright (c) 2003 Alex Beregszaszi
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -24,18 +24,25 @@
 #include "libavutil/avstring.h"
 #include "libavutil/bswap.h"
 #include "libavutil/tree.h"
+#include "avio_internal.h"
 #include "nut.h"
 
 #undef NDEBUG
 #include <assert.h>
 
-static int get_str(ByteIOContext *bc, char *string, unsigned int maxlen){
-    unsigned int len= ff_get_v(bc);
+#if FF_API_MAX_STREAMS
+#define NUT_MAX_STREAMS MAX_STREAMS
+#else
+#define NUT_MAX_STREAMS 256    /* arbitrary sanity check value */
+#endif
+
+static int get_str(AVIOContext *bc, char *string, unsigned int maxlen){
+    unsigned int len= ffio_read_varlen(bc);
 
     if(len && maxlen)
-        get_buffer(bc, string, FFMIN(len, maxlen));
+        avio_read(bc, string, FFMIN(len, maxlen));
     while(len > maxlen){
-        get_byte(bc);
+        avio_r8(bc);
         len--;
     }
 
@@ -48,75 +55,75 @@ static int get_str(ByteIOContext *bc, char *string, unsigned int maxlen){
         return 0;
 }
 
-static int64_t get_s(ByteIOContext *bc){
-    int64_t v = ff_get_v(bc) + 1;
+static int64_t get_s(AVIOContext *bc){
+    int64_t v = ffio_read_varlen(bc) + 1;
 
     if (v&1) return -(v>>1);
     else     return  (v>>1);
 }
 
-static uint64_t get_fourcc(ByteIOContext *bc){
-    unsigned int len= ff_get_v(bc);
+static uint64_t get_fourcc(AVIOContext *bc){
+    unsigned int len= ffio_read_varlen(bc);
 
-    if     (len==2) return get_le16(bc);
-    else if(len==4) return get_le32(bc);
+    if     (len==2) return avio_rl16(bc);
+    else if(len==4) return avio_rl32(bc);
     else            return -1;
 }
 
 #ifdef TRACE
-static inline uint64_t get_v_trace(ByteIOContext *bc, char *file, char *func, int line){
-    uint64_t v= ff_get_v(bc);
+static inline uint64_t get_v_trace(AVIOContext *bc, char *file, char *func, int line){
+    uint64_t v= ffio_read_varlen(bc);
 
     av_log(NULL, AV_LOG_DEBUG, "get_v %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
     return v;
 }
 
-static inline int64_t get_s_trace(ByteIOContext *bc, char *file, char *func, int line){
+static inline int64_t get_s_trace(AVIOContext *bc, char *file, char *func, int line){
     int64_t v= get_s(bc);
 
     av_log(NULL, AV_LOG_DEBUG, "get_s %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
     return v;
 }
 
-static inline uint64_t get_vb_trace(ByteIOContext *bc, char *file, char *func, int line){
+static inline uint64_t get_vb_trace(AVIOContext *bc, char *file, char *func, int line){
     uint64_t v= get_vb(bc);
 
     av_log(NULL, AV_LOG_DEBUG, "get_vb %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
     return v;
 }
-#define ff_get_v(bc)  get_v_trace(bc, __FILE__, __PRETTY_FUNCTION__, __LINE__)
+#define ffio_read_varlen(bc)  get_v_trace(bc, __FILE__, __PRETTY_FUNCTION__, __LINE__)
 #define get_s(bc)  get_s_trace(bc, __FILE__, __PRETTY_FUNCTION__, __LINE__)
 #define get_vb(bc)  get_vb_trace(bc, __FILE__, __PRETTY_FUNCTION__, __LINE__)
 #endif
 
-static int get_packetheader(NUTContext *nut, ByteIOContext *bc, int calculate_checksum, uint64_t startcode)
+static int get_packetheader(NUTContext *nut, AVIOContext *bc, int calculate_checksum, uint64_t startcode)
 {
     int64_t size;
-//    start= url_ftell(bc) - 8;
+//    start= avio_tell(bc) - 8;
 
-    startcode= be2me_64(startcode);
-    startcode= ff_crc04C11DB7_update(0, &startcode, 8);
+    startcode= av_be2ne64(startcode);
+    startcode= ff_crc04C11DB7_update(0, (uint8_t*)&startcode, 8);
 
-    init_checksum(bc, ff_crc04C11DB7_update, startcode);
-    size= ff_get_v(bc);
+    ffio_init_checksum(bc, ff_crc04C11DB7_update, startcode);
+    size= ffio_read_varlen(bc);
     if(size > 4096)
-        get_be32(bc);
-    if(get_checksum(bc) && size > 4096)
+        avio_rb32(bc);
+    if(ffio_get_checksum(bc) && size > 4096)
         return -1;
 
-    init_checksum(bc, calculate_checksum ? ff_crc04C11DB7_update : NULL, 0);
+    ffio_init_checksum(bc, calculate_checksum ? ff_crc04C11DB7_update : NULL, 0);
 
     return size;
 }
 
-static uint64_t find_any_startcode(ByteIOContext *bc, int64_t pos){
+static uint64_t find_any_startcode(AVIOContext *bc, int64_t pos){
     uint64_t state=0;
 
     if(pos >= 0)
-        url_fseek(bc, pos, SEEK_SET); //note, this may fail if the stream is not seekable, but that should not matter, as in this case we simply start where we currently are
+        avio_seek(bc, pos, SEEK_SET); //note, this may fail if the stream is not seekable, but that should not matter, as in this case we simply start where we currently are
 
-    while(!url_feof(bc)){
-        state= (state<<8) | get_byte(bc);
+    while(!bc->eof_reached){
+        state= (state<<8) | avio_r8(bc);
         if((state>>56) != 'N')
             continue;
         switch(state){
@@ -138,11 +145,11 @@ static uint64_t find_any_startcode(ByteIOContext *bc, int64_t pos){
  * @param pos the start position of the search, or -1 if the current position
  * @return the position of the startcode or -1 if not found
  */
-static int64_t find_startcode(ByteIOContext *bc, uint64_t code, int64_t pos){
+static int64_t find_startcode(AVIOContext *bc, uint64_t code, int64_t pos){
     for(;;){
         uint64_t startcode= find_any_startcode(bc, pos);
         if(startcode == code)
-            return url_ftell(bc) - 8;
+            return avio_tell(bc) - 8;
         else if(startcode == 0)
             return -1;
         pos=-1;
@@ -162,40 +169,40 @@ static int nut_probe(AVProbeData *p){
 }
 
 #define GET_V(dst, check) \
-    tmp= ff_get_v(bc);\
+    tmp= ffio_read_varlen(bc);\
     if(!(check)){\
         av_log(s, AV_LOG_ERROR, "Error " #dst " is (%"PRId64")\n", tmp);\
         return -1;\
     }\
     dst= tmp;
 
-static int skip_reserved(ByteIOContext *bc, int64_t pos){
-    pos -= url_ftell(bc);
+static int skip_reserved(AVIOContext *bc, int64_t pos){
+    pos -= avio_tell(bc);
     if(pos<0){
-        url_fseek(bc, pos, SEEK_CUR);
+        avio_seek(bc, pos, SEEK_CUR);
         return -1;
     }else{
         while(pos--)
-            get_byte(bc);
+            avio_r8(bc);
         return 0;
     }
 }
 
 static int decode_main_header(NUTContext *nut){
     AVFormatContext *s= nut->avf;
-    ByteIOContext *bc = s->pb;
+    AVIOContext *bc = s->pb;
     uint64_t tmp, end;
     unsigned int stream_count;
     int i, j, tmp_stream, tmp_mul, tmp_pts, tmp_size, count, tmp_res, tmp_head_idx;
     int64_t tmp_match;
 
     end= get_packetheader(nut, bc, 1, MAIN_STARTCODE);
-    end += url_ftell(bc);
+    end += avio_tell(bc);
 
     GET_V(tmp              , tmp >=2 && tmp <= 3)
-    GET_V(stream_count     , tmp > 0 && tmp <=MAX_STREAMS)
+    GET_V(stream_count     , tmp > 0 && tmp <= NUT_MAX_STREAMS)
 
-    nut->max_distance = ff_get_v(bc);
+    nut->max_distance = ffio_read_varlen(bc);
     if(nut->max_distance > 65536){
         av_log(s, AV_LOG_DEBUG, "max_distance %d\n", nut->max_distance);
         nut->max_distance= 65536;
@@ -209,7 +216,7 @@ static int decode_main_header(NUTContext *nut){
         GET_V(nut->time_base[i].den, tmp>0 && tmp<(1ULL<<31))
         if(av_gcd(nut->time_base[i].num, nut->time_base[i].den) != 1){
             av_log(s, AV_LOG_ERROR, "time base invalid\n");
-            return -1;
+            return AVERROR_INVALIDDATA;
         }
     }
     tmp_pts=0;
@@ -218,30 +225,30 @@ static int decode_main_header(NUTContext *nut){
     tmp_match= 1-(1LL<<62);
     tmp_head_idx= 0;
     for(i=0; i<256;){
-        int tmp_flags = ff_get_v(bc);
-        int tmp_fields= ff_get_v(bc);
+        int tmp_flags = ffio_read_varlen(bc);
+        int tmp_fields= ffio_read_varlen(bc);
         if(tmp_fields>0) tmp_pts   = get_s(bc);
-        if(tmp_fields>1) tmp_mul   = ff_get_v(bc);
-        if(tmp_fields>2) tmp_stream= ff_get_v(bc);
-        if(tmp_fields>3) tmp_size  = ff_get_v(bc);
+        if(tmp_fields>1) tmp_mul   = ffio_read_varlen(bc);
+        if(tmp_fields>2) tmp_stream= ffio_read_varlen(bc);
+        if(tmp_fields>3) tmp_size  = ffio_read_varlen(bc);
         else             tmp_size  = 0;
-        if(tmp_fields>4) tmp_res   = ff_get_v(bc);
+        if(tmp_fields>4) tmp_res   = ffio_read_varlen(bc);
         else             tmp_res   = 0;
-        if(tmp_fields>5) count     = ff_get_v(bc);
+        if(tmp_fields>5) count     = ffio_read_varlen(bc);
         else             count     = tmp_mul - tmp_size;
         if(tmp_fields>6) tmp_match = get_s(bc);
-        if(tmp_fields>7) tmp_head_idx= ff_get_v(bc);
+        if(tmp_fields>7) tmp_head_idx= ffio_read_varlen(bc);
 
         while(tmp_fields-- > 8)
-           ff_get_v(bc);
+           ffio_read_varlen(bc);
 
         if(count == 0 || i+count > 256){
             av_log(s, AV_LOG_ERROR, "illegal count %d at %d\n", count, i);
-            return -1;
+            return AVERROR_INVALIDDATA;
         }
         if(tmp_stream >= stream_count){
             av_log(s, AV_LOG_ERROR, "illegal stream number\n");
-            return -1;
+            return AVERROR_INVALIDDATA;
         }
 
         for(j=0; j<count; j++,i++){
@@ -261,7 +268,7 @@ static int decode_main_header(NUTContext *nut){
     }
     assert(nut->frame_code['N'].flags == FLAG_INVALID);
 
-    if(end > url_ftell(bc) + 4){
+    if(end > avio_tell(bc) + 4){
         int rem= 1024;
         GET_V(nut->header_count, tmp<128U)
         nut->header_count++;
@@ -270,17 +277,17 @@ static int decode_main_header(NUTContext *nut){
             rem -= nut->header_len[i];
             if(rem < 0){
                 av_log(s, AV_LOG_ERROR, "invalid elision header\n");
-                return -1;
+                return AVERROR_INVALIDDATA;
             }
             nut->header[i]= av_malloc(nut->header_len[i]);
-            get_buffer(bc, nut->header[i], nut->header_len[i]);
+            avio_read(bc, nut->header[i], nut->header_len[i]);
         }
         assert(nut->header_len[0]==0);
     }
 
-    if(skip_reserved(bc, end) || get_checksum(bc)){
+    if(skip_reserved(bc, end) || ffio_get_checksum(bc)){
         av_log(s, AV_LOG_ERROR, "main header checksum mismatch\n");
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
 
     nut->stream = av_mallocz(sizeof(StreamContext)*stream_count);
@@ -293,14 +300,14 @@ static int decode_main_header(NUTContext *nut){
 
 static int decode_stream_header(NUTContext *nut){
     AVFormatContext *s= nut->avf;
-    ByteIOContext *bc = s->pb;
+    AVIOContext *bc = s->pb;
     StreamContext *stc;
     int class, stream_id;
     uint64_t tmp, end;
     AVStream *st;
 
     end= get_packetheader(nut, bc, 1, STREAM_STARTCODE);
-    end += url_ftell(bc);
+    end += avio_tell(bc);
 
     GET_V(stream_id, tmp < s->nb_streams && !nut->stream[tmp].time_base);
     stc= &nut->stream[stream_id];
@@ -309,14 +316,16 @@ static int decode_stream_header(NUTContext *nut){
     if (!st)
         return AVERROR(ENOMEM);
 
-    class = ff_get_v(bc);
+    class = ffio_read_varlen(bc);
     tmp = get_fourcc(bc);
     st->codec->codec_tag= tmp;
     switch(class)
     {
         case 0:
             st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
-            st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags, tmp);
+            st->codec->codec_id = av_codec_get_id(
+                (const AVCodecTag * const []) { ff_codec_bmp_tags, ff_nut_video_tags, 0 },
+                tmp);
             break;
         case 1:
             st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
@@ -339,33 +348,33 @@ static int decode_stream_header(NUTContext *nut){
 
     GET_V(stc->time_base_id    , tmp < nut->time_base_count);
     GET_V(stc->msb_pts_shift   , tmp < 16);
-    stc->max_pts_distance= ff_get_v(bc);
+    stc->max_pts_distance= ffio_read_varlen(bc);
     GET_V(stc->decode_delay    , tmp < 1000); //sanity limit, raise this if Moore's law is true
     st->codec->has_b_frames= stc->decode_delay;
-    ff_get_v(bc); //stream flags
+    ffio_read_varlen(bc); //stream flags
 
     GET_V(st->codec->extradata_size, tmp < (1<<30));
     if(st->codec->extradata_size){
         st->codec->extradata= av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
-        get_buffer(bc, st->codec->extradata, st->codec->extradata_size);
+        avio_read(bc, st->codec->extradata, st->codec->extradata_size);
     }
 
     if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO){
         GET_V(st->codec->width , tmp > 0)
         GET_V(st->codec->height, tmp > 0)
-        st->sample_aspect_ratio.num= ff_get_v(bc);
-        st->sample_aspect_ratio.den= ff_get_v(bc);
+        st->sample_aspect_ratio.num= ffio_read_varlen(bc);
+        st->sample_aspect_ratio.den= ffio_read_varlen(bc);
         if((!st->sample_aspect_ratio.num) != (!st->sample_aspect_ratio.den)){
             av_log(s, AV_LOG_ERROR, "invalid aspect ratio %d/%d\n", st->sample_aspect_ratio.num, st->sample_aspect_ratio.den);
             return -1;
         }
-        ff_get_v(bc); /* csp type */
+        ffio_read_varlen(bc); /* csp type */
     }else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO){
         GET_V(st->codec->sample_rate , tmp > 0)
-        ff_get_v(bc); // samplerate_den
+        ffio_read_varlen(bc); // samplerate_den
         GET_V(st->codec->channels, tmp > 0)
     }
-    if(skip_reserved(bc, end) || get_checksum(bc)){
+    if(skip_reserved(bc, end) || ffio_get_checksum(bc)){
         av_log(s, AV_LOG_ERROR, "stream header %d checksum mismatch\n", stream_id);
         return -1;
     }
@@ -389,7 +398,7 @@ static void set_disposition_bits(AVFormatContext* avf, char* value, int stream_i
 
 static int decode_info_header(NUTContext *nut){
     AVFormatContext *s= nut->avf;
-    ByteIOContext *bc = s->pb;
+    AVIOContext *bc = s->pb;
     uint64_t tmp, chapter_start, chapter_len;
     unsigned int stream_id_plus1, count;
     int chapter_id, i;
@@ -398,23 +407,28 @@ static int decode_info_header(NUTContext *nut){
     const char *type;
     AVChapter *chapter= NULL;
     AVStream *st= NULL;
+    AVMetadata **metadata = NULL;
 
     end= get_packetheader(nut, bc, 1, INFO_STARTCODE);
-    end += url_ftell(bc);
+    end += avio_tell(bc);
 
     GET_V(stream_id_plus1, tmp <= s->nb_streams)
     chapter_id   = get_s(bc);
-    chapter_start= ff_get_v(bc);
-    chapter_len  = ff_get_v(bc);
-    count        = ff_get_v(bc);
+    chapter_start= ffio_read_varlen(bc);
+    chapter_len  = ffio_read_varlen(bc);
+    count        = ffio_read_varlen(bc);
 
     if(chapter_id && !stream_id_plus1){
         int64_t start= chapter_start / nut->time_base_count;
         chapter= ff_new_chapter(s, chapter_id,
                                 nut->time_base[chapter_start % nut->time_base_count],
                                 start, start + chapter_len, NULL);
-    } else if(stream_id_plus1)
+        metadata = &chapter->metadata;
+    } else if(stream_id_plus1) {
         st= s->streams[stream_id_plus1 - 1];
+        metadata = &st->metadata;
+    } else
+        metadata = &s->metadata;
 
     for(i=0; i<count; i++){
         get_str(bc, name, sizeof(name));
@@ -431,7 +445,7 @@ static int decode_info_header(NUTContext *nut){
             value= get_s(bc);
         }else if(value == -4){
             type= "t";
-            value= ff_get_v(bc);
+            value= ffio_read_varlen(bc);
         }else if(value < -4){
             type= "r";
             get_s(bc);
@@ -445,19 +459,17 @@ static int decode_info_header(NUTContext *nut){
         }
 
         if(!strcmp(type, "UTF-8")){
-            AVMetadata **metadata = NULL;
-            if(chapter_id==0 && !strcmp(name, "Disposition"))
+            if(chapter_id==0 && !strcmp(name, "Disposition")) {
                 set_disposition_bits(s, str_value, stream_id_plus1 - 1);
-            else if(chapter)          metadata= &chapter->metadata;
-            else if(stream_id_plus1)  metadata= &st->metadata;
-            else                      metadata= &s->metadata;
+                continue;
+            }
             if(metadata && strcasecmp(name,"Uses")
                && strcasecmp(name,"Depends") && strcasecmp(name,"Replaces"))
                 av_metadata_set2(metadata, name, str_value, 0);
         }
     }
 
-    if(skip_reserved(bc, end) || get_checksum(bc)){
+    if(skip_reserved(bc, end) || ffio_get_checksum(bc)){
         av_log(s, AV_LOG_ERROR, "info header checksum mismatch\n");
         return -1;
     }
@@ -466,22 +478,22 @@ static int decode_info_header(NUTContext *nut){
 
 static int decode_syncpoint(NUTContext *nut, int64_t *ts, int64_t *back_ptr){
     AVFormatContext *s= nut->avf;
-    ByteIOContext *bc = s->pb;
+    AVIOContext *bc = s->pb;
     int64_t end, tmp;
 
-    nut->last_syncpoint_pos= url_ftell(bc)-8;
+    nut->last_syncpoint_pos= avio_tell(bc)-8;
 
     end= get_packetheader(nut, bc, 1, SYNCPOINT_STARTCODE);
-    end += url_ftell(bc);
+    end += avio_tell(bc);
 
-    tmp= ff_get_v(bc);
-    *back_ptr= nut->last_syncpoint_pos - 16*ff_get_v(bc);
+    tmp= ffio_read_varlen(bc);
+    *back_ptr= nut->last_syncpoint_pos - 16*ffio_read_varlen(bc);
     if(*back_ptr < 0)
         return -1;
 
     ff_nut_reset_ts(nut, nut->time_base[tmp % nut->time_base_count], tmp / nut->time_base_count);
 
-    if(skip_reserved(bc, end) || get_checksum(bc)){
+    if(skip_reserved(bc, end) || ffio_get_checksum(bc)){
         av_log(s, AV_LOG_ERROR, "sync point checksum mismatch\n");
         return -1;
     }
@@ -494,30 +506,30 @@ static int decode_syncpoint(NUTContext *nut, int64_t *ts, int64_t *back_ptr){
 
 static int find_and_decode_index(NUTContext *nut){
     AVFormatContext *s= nut->avf;
-    ByteIOContext *bc = s->pb;
+    AVIOContext *bc = s->pb;
     uint64_t tmp, end;
     int i, j, syncpoint_count;
-    int64_t filesize= url_fsize(bc);
+    int64_t filesize= avio_size(bc);
     int64_t *syncpoints;
     int8_t *has_keyframe;
     int ret= -1;
 
-    url_fseek(bc, filesize-12, SEEK_SET);
-    url_fseek(bc, filesize-get_be64(bc), SEEK_SET);
-    if(get_be64(bc) != INDEX_STARTCODE){
+    avio_seek(bc, filesize-12, SEEK_SET);
+    avio_seek(bc, filesize-avio_rb64(bc), SEEK_SET);
+    if(avio_rb64(bc) != INDEX_STARTCODE){
         av_log(s, AV_LOG_ERROR, "no index at the end\n");
         return -1;
     }
 
     end= get_packetheader(nut, bc, 1, INDEX_STARTCODE);
-    end += url_ftell(bc);
+    end += avio_tell(bc);
 
-    ff_get_v(bc); //max_pts
+    ffio_read_varlen(bc); //max_pts
     GET_V(syncpoint_count, tmp < INT_MAX/8 && tmp > 0)
     syncpoints= av_malloc(sizeof(int64_t)*syncpoint_count);
     has_keyframe= av_malloc(sizeof(int8_t)*(syncpoint_count+1));
     for(i=0; i<syncpoint_count; i++){
-        syncpoints[i] = ff_get_v(bc);
+        syncpoints[i] = ffio_read_varlen(bc);
         if(syncpoints[i] <= 0)
             goto fail;
         if(i)
@@ -527,7 +539,7 @@ static int find_and_decode_index(NUTContext *nut){
     for(i=0; i<s->nb_streams; i++){
         int64_t last_pts= -1;
         for(j=0; j<syncpoint_count;){
-            uint64_t x= ff_get_v(bc);
+            uint64_t x= ffio_read_varlen(bc);
             int type= x&1;
             int n= j;
             x>>=1;
@@ -558,10 +570,10 @@ static int find_and_decode_index(NUTContext *nut){
             assert(n<=syncpoint_count+1);
             for(; j<n && j<syncpoint_count; j++){
                 if(has_keyframe[j]){
-                    uint64_t B, A= ff_get_v(bc);
+                    uint64_t B, A= ffio_read_varlen(bc);
                     if(!A){
-                        A= ff_get_v(bc);
-                        B= ff_get_v(bc);
+                        A= ffio_read_varlen(bc);
+                        B= ffio_read_varlen(bc);
                         //eor_pts[j][i] = last_pts + A + B
                     }else
                         B= 0;
@@ -578,7 +590,7 @@ static int find_and_decode_index(NUTContext *nut){
         }
     }
 
-    if(skip_reserved(bc, end) || get_checksum(bc)){
+    if(skip_reserved(bc, end) || ffio_get_checksum(bc)){
         av_log(s, AV_LOG_ERROR, "index checksum mismatch\n");
         goto fail;
     }
@@ -592,7 +604,7 @@ fail:
 static int nut_read_header(AVFormatContext *s, AVFormatParameters *ap)
 {
     NUTContext *nut = s->priv_data;
-    ByteIOContext *bc = s->pb;
+    AVIOContext *bc = s->pb;
     int64_t pos;
     int initialized_stream_count;
 
@@ -604,7 +616,7 @@ static int nut_read_header(AVFormatContext *s, AVFormatParameters *ap)
         pos= find_startcode(bc, MAIN_STARTCODE, pos)+1;
         if (pos<0+1){
             av_log(s, AV_LOG_ERROR, "No main startcode found.\n");
-            return -1;
+            return AVERROR_INVALIDDATA;
         }
     }while(decode_main_header(nut) < 0);
 
@@ -614,7 +626,7 @@ static int nut_read_header(AVFormatContext *s, AVFormatParameters *ap)
         pos= find_startcode(bc, STREAM_STARTCODE, pos)+1;
         if (pos<0+1){
             av_log(s, AV_LOG_ERROR, "Not all stream headers found.\n");
-            return -1;
+            return AVERROR_INVALIDDATA;
         }
         if(decode_stream_header(nut) >= 0)
             initialized_stream_count++;
@@ -624,11 +636,11 @@ static int nut_read_header(AVFormatContext *s, AVFormatParameters *ap)
     pos=0;
     for(;;){
         uint64_t startcode= find_any_startcode(bc, pos);
-        pos= url_ftell(bc);
+        pos= avio_tell(bc);
 
         if(startcode==0){
             av_log(s, AV_LOG_ERROR, "EOF before video frames\n");
-            return -1;
+            return AVERROR_INVALIDDATA;
         }else if(startcode == SYNCPOINT_STARTCODE){
             nut->next_startcode= startcode;
             break;
@@ -641,26 +653,28 @@ static int nut_read_header(AVFormatContext *s, AVFormatParameters *ap)
 
     s->data_offset= pos-8;
 
-    if(!url_is_streamed(bc)){
-        int64_t orig_pos= url_ftell(bc);
+    if(bc->seekable){
+        int64_t orig_pos= avio_tell(bc);
         find_and_decode_index(nut);
-        url_fseek(bc, orig_pos, SEEK_SET);
+        avio_seek(bc, orig_pos, SEEK_SET);
     }
     assert(nut->next_startcode == SYNCPOINT_STARTCODE);
 
+    ff_metadata_conv_ctx(s, NULL, ff_nut_metadata_conv);
+
     return 0;
 }
 
 static int decode_frame_header(NUTContext *nut, int64_t *pts, int *stream_id, uint8_t *header_idx, int frame_code){
     AVFormatContext *s= nut->avf;
-    ByteIOContext *bc = s->pb;
+    AVIOContext *bc = s->pb;
     StreamContext *stc;
     int size, flags, size_mul, pts_delta, i, reserved_count;
     uint64_t tmp;
 
-    if(url_ftell(bc) > nut->last_syncpoint_pos + nut->max_distance){
-        av_log(s, AV_LOG_ERROR, "Last frame must have been damaged %"PRId64" > %"PRId64" + %d\n", url_ftell(bc), nut->last_syncpoint_pos, nut->max_distance);
-        return -1;
+    if(avio_tell(bc) > nut->last_syncpoint_pos + nut->max_distance){
+        av_log(s, AV_LOG_ERROR, "Last frame must have been damaged %"PRId64" > %"PRId64" + %d\n", avio_tell(bc), nut->last_syncpoint_pos, nut->max_distance);
+        return AVERROR_INVALIDDATA;
     }
 
     flags          = nut->frame_code[frame_code].flags;
@@ -672,15 +686,15 @@ static int decode_frame_header(NUTContext *nut, int64_t *pts, int *stream_id, ui
     *header_idx    = nut->frame_code[frame_code].header_idx;
 
     if(flags & FLAG_INVALID)
-        return -1;
+        return AVERROR_INVALIDDATA;
     if(flags & FLAG_CODED)
-        flags ^= ff_get_v(bc);
+        flags ^= ffio_read_varlen(bc);
     if(flags & FLAG_STREAM_ID){
         GET_V(*stream_id, tmp < s->nb_streams)
     }
     stc= &nut->stream[*stream_id];
     if(flags&FLAG_CODED_PTS){
-        int coded_pts= ff_get_v(bc);
+        int coded_pts= ffio_read_varlen(bc);
 //FIXME check last_pts validity?
         if(coded_pts < (1<<stc->msb_pts_shift)){
             *pts=ff_lsb2full(stc, coded_pts);
@@ -689,30 +703,30 @@ static int decode_frame_header(NUTContext *nut, int64_t *pts, int *stream_id, ui
     }else
         *pts= stc->last_pts + pts_delta;
     if(flags&FLAG_SIZE_MSB){
-        size += size_mul*ff_get_v(bc);
+        size += size_mul*ffio_read_varlen(bc);
     }
     if(flags&FLAG_MATCH_TIME)
         get_s(bc);
     if(flags&FLAG_HEADER_IDX)
-        *header_idx= ff_get_v(bc);
+        *header_idx= ffio_read_varlen(bc);
     if(flags&FLAG_RESERVED)
-        reserved_count= ff_get_v(bc);
+        reserved_count= ffio_read_varlen(bc);
     for(i=0; i<reserved_count; i++)
-        ff_get_v(bc);
+        ffio_read_varlen(bc);
 
     if(*header_idx >= (unsigned)nut->header_count){
         av_log(s, AV_LOG_ERROR, "header_idx invalid\n");
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
     if(size > 4096)
         *header_idx=0;
     size -= nut->header_len[*header_idx];
 
     if(flags&FLAG_CHECKSUM){
-        get_be32(bc); //FIXME check this
+        avio_rb32(bc); //FIXME check this
     }else if(size > 2*nut->max_distance || FFABS(stc->last_pts - *pts) > stc->max_pts_distance){
         av_log(s, AV_LOG_ERROR, "frame size > 2max_distance and no checksum\n");
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
 
     stc->last_pts= *pts;
@@ -723,7 +737,7 @@ static int decode_frame_header(NUTContext *nut, int64_t *pts, int *stream_id, ui
 
 static int decode_frame(NUTContext *nut, AVPacket *pkt, int frame_code){
     AVFormatContext *s= nut->avf;
-    ByteIOContext *bc = s->pb;
+    AVIOContext *bc = s->pb;
     int size, stream_id, discard;
     int64_t pts, last_IP_pts;
     StreamContext *stc;
@@ -731,7 +745,7 @@ static int decode_frame(NUTContext *nut, AVPacket *pkt, int frame_code){
 
     size= decode_frame_header(nut, &pts, &stream_id, &header_idx, frame_code);
     if(size < 0)
-        return -1;
+        return size;
 
     stc= &nut->stream[stream_id];
 
@@ -744,14 +758,14 @@ static int decode_frame(NUTContext *nut, AVPacket *pkt, int frame_code){
        ||(discard >= AVDISCARD_BIDIR && last_IP_pts != AV_NOPTS_VALUE && last_IP_pts > pts)
        || discard >= AVDISCARD_ALL
        || stc->skip_until_key_frame){
-        url_fskip(bc, size);
+        avio_skip(bc, size);
         return 1;
     }
 
     av_new_packet(pkt, size + nut->header_len[header_idx]);
     memcpy(pkt->data, nut->header[header_idx], nut->header_len[header_idx]);
-    pkt->pos= url_ftell(bc); //FIXME
-    get_buffer(bc, pkt->data + nut->header_len[header_idx], size);
+    pkt->pos= avio_tell(bc); //FIXME
+    avio_read(bc, pkt->data + nut->header_len[header_idx], size);
 
     pkt->stream_index = stream_id;
     if (stc->last_flags & FLAG_KEY)
@@ -764,25 +778,25 @@ static int decode_frame(NUTContext *nut, AVPacket *pkt, int frame_code){
 static int nut_read_packet(AVFormatContext *s, AVPacket *pkt)
 {
     NUTContext *nut = s->priv_data;
-    ByteIOContext *bc = s->pb;
+    AVIOContext *bc = s->pb;
     int i, frame_code=0, ret, skip;
     int64_t ts, back_ptr;
 
     for(;;){
-        int64_t pos= url_ftell(bc);
+        int64_t pos= avio_tell(bc);
         uint64_t tmp= nut->next_startcode;
         nut->next_startcode=0;
 
         if(tmp){
             pos-=8;
         }else{
-            frame_code = get_byte(bc);
-            if(url_feof(bc))
+            frame_code = avio_r8(bc);
+            if(bc->eof_reached)
                 return -1;
             if(frame_code == 'N'){
                 tmp= frame_code;
                 for(i=1; i<8; i++)
-                    tmp = (tmp<<8) + get_byte(bc);
+                    tmp = (tmp<<8) + avio_r8(bc);
             }
         }
         switch(tmp){
@@ -790,7 +804,7 @@ static int nut_read_packet(AVFormatContext *s, AVPacket *pkt)
         case STREAM_STARTCODE:
         case INDEX_STARTCODE:
             skip= get_packetheader(nut, bc, 0, tmp);
-            url_fseek(bc, skip, SEEK_CUR);
+            avio_skip(bc, skip);
             break;
         case INFO_STARTCODE:
             if(decode_info_header(nut)<0)
@@ -799,7 +813,7 @@ static int nut_read_packet(AVFormatContext *s, AVPacket *pkt)
         case SYNCPOINT_STARTCODE:
             if(decode_syncpoint(nut, &ts, &back_ptr)<0)
                 goto resync;
-            frame_code = get_byte(bc);
+            frame_code = avio_r8(bc);
         case 0:
             ret= decode_frame(nut, pkt, frame_code);
             if(ret==0)
@@ -811,7 +825,7 @@ resync:
 av_log(s, AV_LOG_DEBUG, "syncing from %"PRId64"\n", pos);
             tmp= find_any_startcode(bc, nut->last_syncpoint_pos+1);
             if(tmp==0)
-                return -1;
+                return AVERROR_INVALIDDATA;
 av_log(s, AV_LOG_DEBUG, "sync\n");
             nut->next_startcode= tmp;
         }
@@ -820,7 +834,7 @@ av_log(s, AV_LOG_DEBUG, "sync\n");
 
 static int64_t nut_read_timestamp(AVFormatContext *s, int stream_index, int64_t *pos_arg, int64_t pos_limit){
     NUTContext *nut = s->priv_data;
-    ByteIOContext *bc = s->pb;
+    AVIOContext *bc = s->pb;
     int64_t pos, pts, back_ptr;
 av_log(s, AV_LOG_DEBUG, "read_timestamp(X,%d,%"PRId64",%"PRId64")\n", stream_index, *pos_arg, pos_limit);
 
@@ -887,7 +901,7 @@ static int read_seek(AVFormatContext *s, int stream_index, int64_t pts, int flag
     }
     av_log(NULL, AV_LOG_DEBUG, "SEEKTO: %"PRId64"\n", pos2);
     pos= find_startcode(s->pb, SYNCPOINT_STARTCODE, pos2);
-    url_fseek(s->pb, pos, SEEK_SET);
+    avio_seek(s->pb, pos, SEEK_SET);
     av_log(NULL, AV_LOG_DEBUG, "SP: %"PRId64"\n", pos);
     if(pos2 > pos || pos2 + 15 < pos){
         av_log(NULL, AV_LOG_ERROR, "no syncpoint at backptr pos\n");
@@ -913,7 +927,7 @@ static int nut_read_close(AVFormatContext *s)
 }
 
 #if CONFIG_NUT_DEMUXER
-AVInputFormat nut_demuxer = {
+AVInputFormat ff_nut_demuxer = {
     "nut",
     NULL_IF_CONFIG_SMALL("NUT format"),
     sizeof(NUTContext),
@@ -923,6 +937,6 @@ AVInputFormat nut_demuxer = {
     nut_read_close,
     read_seek,
     .extensions = "nut",
-    .metadata_conv = ff_nut_metadata_conv,
+    .codec_tag = (const AVCodecTag * const []) { ff_codec_bmp_tags, ff_nut_video_tags, ff_codec_wav_tags, ff_nut_subtitle_tags, 0 },
 };
 #endif
diff --git a/libavformat/nutenc.c b/libavformat/nutenc.c
index dfda3ca..c17a15d 100644
--- a/libavformat/nutenc.c
+++ b/libavformat/nutenc.c
@@ -2,20 +2,20 @@
  * nut muxer
  * Copyright (c) 2004-2007 Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -23,6 +23,8 @@
 #include "libavutil/tree.h"
 #include "libavcodec/mpegaudiodata.h"
 #include "nut.h"
+#include "internal.h"
+#include "avio_internal.h"
 
 static int find_expected_header(AVCodecContext *c, int size, int key_frame, uint8_t out[64]){
     int sample_rate= c->sample_rate;
@@ -240,97 +242,76 @@ static void build_frame_code(AVFormatContext *s){
     nut->frame_code['N'].flags= FLAG_INVALID;
 }
 
-/**
- * Gets the length in bytes which is needed to store val as v.
- */
-static int get_length(uint64_t val){
-    int i=1;
-
-    while(val>>=7)
-        i++;
-
-    return i;
-}
-
-static void put_v(ByteIOContext *bc, uint64_t val){
-    int i= get_length(val);
-
-    while(--i>0)
-        put_byte(bc, 128 | (val>>(7*i)));
-
-    put_byte(bc, val&127);
-}
-
-static void put_tt(NUTContext *nut, StreamContext *nus, ByteIOContext *bc, uint64_t val){
+static void put_tt(NUTContext *nut, AVRational *time_base, AVIOContext *bc, uint64_t val){
     val *= nut->time_base_count;
-    val += nus->time_base - nut->time_base;
-    put_v(bc, val);
+    val += time_base - nut->time_base;
+    ff_put_v(bc, val);
 }
 
 /**
- * Stores a string as vb.
+ * Store a string as vb.
  */
-static void put_str(ByteIOContext *bc, const char *string){
+static void put_str(AVIOContext *bc, const char *string){
     int len= strlen(string);
 
-    put_v(bc, len);
-    put_buffer(bc, string, len);
+    ff_put_v(bc, len);
+    avio_write(bc, string, len);
 }
 
-static void put_s(ByteIOContext *bc, int64_t val){
-    put_v(bc, 2*FFABS(val) - (val>0));
+static void put_s(AVIOContext *bc, int64_t val){
+    ff_put_v(bc, 2*FFABS(val) - (val>0));
 }
 
 #ifdef TRACE
-static inline void put_v_trace(ByteIOContext *bc, uint64_t v, char *file, char *func, int line){
-    av_log(NULL, AV_LOG_DEBUG, "put_v %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
+static inline void ff_put_v_trace(AVIOContext *bc, uint64_t v, char *file, char *func, int line){
+    av_log(NULL, AV_LOG_DEBUG, "ff_put_v %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
 
-    put_v(bc, v);
+    ff_put_v(bc, v);
 }
 
-static inline void put_s_trace(ByteIOContext *bc, int64_t v, char *file, char *func, int line){
+static inline void put_s_trace(AVIOContext *bc, int64_t v, char *file, char *func, int line){
     av_log(NULL, AV_LOG_DEBUG, "put_s %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
 
     put_s(bc, v);
 }
-#define put_v(bc, v)  put_v_trace(bc, v, __FILE__, __PRETTY_FUNCTION__, __LINE__)
+#define ff_put_v(bc, v)  ff_put_v_trace(bc, v, __FILE__, __PRETTY_FUNCTION__, __LINE__)
 #define put_s(bc, v)  put_s_trace(bc, v, __FILE__, __PRETTY_FUNCTION__, __LINE__)
 #endif
 
 //FIXME remove calculate_checksum
-static void put_packet(NUTContext *nut, ByteIOContext *bc, ByteIOContext *dyn_bc, int calculate_checksum, uint64_t startcode){
+static void put_packet(NUTContext *nut, AVIOContext *bc, AVIOContext *dyn_bc, int calculate_checksum, uint64_t startcode){
     uint8_t *dyn_buf=NULL;
-    int dyn_size= url_close_dyn_buf(dyn_bc, &dyn_buf);
+    int dyn_size= avio_close_dyn_buf(dyn_bc, &dyn_buf);
     int forw_ptr= dyn_size + 4*calculate_checksum;
 
     if(forw_ptr > 4096)
-        init_checksum(bc, ff_crc04C11DB7_update, 0);
-    put_be64(bc, startcode);
-    put_v(bc, forw_ptr);
+        ffio_init_checksum(bc, ff_crc04C11DB7_update, 0);
+    avio_wb64(bc, startcode);
+    ff_put_v(bc, forw_ptr);
     if(forw_ptr > 4096)
-        put_le32(bc, get_checksum(bc));
+        avio_wl32(bc, ffio_get_checksum(bc));
 
     if(calculate_checksum)
-        init_checksum(bc, ff_crc04C11DB7_update, 0);
-    put_buffer(bc, dyn_buf, dyn_size);
+        ffio_init_checksum(bc, ff_crc04C11DB7_update, 0);
+    avio_write(bc, dyn_buf, dyn_size);
     if(calculate_checksum)
-        put_le32(bc, get_checksum(bc));
+        avio_wl32(bc, ffio_get_checksum(bc));
 
     av_free(dyn_buf);
 }
 
-static void write_mainheader(NUTContext *nut, ByteIOContext *bc){
+static void write_mainheader(NUTContext *nut, AVIOContext *bc){
     int i, j, tmp_pts, tmp_flags, tmp_stream, tmp_mul, tmp_size, tmp_fields, tmp_head_idx;
     int64_t tmp_match;
 
-    put_v(bc, 3); /* version */
-    put_v(bc, nut->avf->nb_streams);
-    put_v(bc, nut->max_distance);
-    put_v(bc, nut->time_base_count);
+    ff_put_v(bc, 3); /* version */
+    ff_put_v(bc, nut->avf->nb_streams);
+    ff_put_v(bc, nut->max_distance);
+    ff_put_v(bc, nut->time_base_count);
 
     for(i=0; i<nut->time_base_count; i++){
-        put_v(bc, nut->time_base[i].num);
-        put_v(bc, nut->time_base[i].den);
+        ff_put_v(bc, nut->time_base[i].num);
+        ff_put_v(bc, nut->time_base[i].den);
     }
 
     tmp_pts=0;
@@ -372,66 +353,69 @@ static void write_mainheader(NUTContext *nut, ByteIOContext *bc){
         }
         if(j != tmp_mul - tmp_size) tmp_fields=6;
 
-        put_v(bc, tmp_flags);
-        put_v(bc, tmp_fields);
+        ff_put_v(bc, tmp_flags);
+        ff_put_v(bc, tmp_fields);
         if(tmp_fields>0) put_s(bc, tmp_pts);
-        if(tmp_fields>1) put_v(bc, tmp_mul);
-        if(tmp_fields>2) put_v(bc, tmp_stream);
-        if(tmp_fields>3) put_v(bc, tmp_size);
-        if(tmp_fields>4) put_v(bc, 0 /*tmp_res*/);
-        if(tmp_fields>5) put_v(bc, j);
-        if(tmp_fields>6) put_v(bc, tmp_match);
-        if(tmp_fields>7) put_v(bc, tmp_head_idx);
+        if(tmp_fields>1) ff_put_v(bc, tmp_mul);
+        if(tmp_fields>2) ff_put_v(bc, tmp_stream);
+        if(tmp_fields>3) ff_put_v(bc, tmp_size);
+        if(tmp_fields>4) ff_put_v(bc, 0 /*tmp_res*/);
+        if(tmp_fields>5) ff_put_v(bc, j);
+        if(tmp_fields>6) ff_put_v(bc, tmp_match);
+        if(tmp_fields>7) ff_put_v(bc, tmp_head_idx);
     }
-    put_v(bc, nut->header_count-1);
+    ff_put_v(bc, nut->header_count-1);
     for(i=1; i<nut->header_count; i++){
-        put_v(bc, nut->header_len[i]);
-        put_buffer(bc, nut->header[i], nut->header_len[i]);
+        ff_put_v(bc, nut->header_len[i]);
+        avio_write(bc, nut->header[i], nut->header_len[i]);
     }
 }
 
-static int write_streamheader(NUTContext *nut, ByteIOContext *bc, AVStream *st, int i){
+static int write_streamheader(AVFormatContext *avctx, AVIOContext *bc, AVStream *st, int i){
+    NUTContext *nut = avctx->priv_data;
     AVCodecContext *codec = st->codec;
-    put_v(bc, i);
+    ff_put_v(bc, i);
     switch(codec->codec_type){
-    case AVMEDIA_TYPE_VIDEO: put_v(bc, 0); break;
-    case AVMEDIA_TYPE_AUDIO: put_v(bc, 1); break;
-    case AVMEDIA_TYPE_SUBTITLE: put_v(bc, 2); break;
-    default              : put_v(bc, 3); break;
+    case AVMEDIA_TYPE_VIDEO: ff_put_v(bc, 0); break;
+    case AVMEDIA_TYPE_AUDIO: ff_put_v(bc, 1); break;
+    case AVMEDIA_TYPE_SUBTITLE: ff_put_v(bc, 2); break;
+    default              : ff_put_v(bc, 3); break;
     }
-    put_v(bc, 4);
+    ff_put_v(bc, 4);
     if (codec->codec_tag){
-        put_le32(bc, codec->codec_tag);
-    }else
-        return -1;
+        avio_wl32(bc, codec->codec_tag);
+    } else {
+        av_log(avctx, AV_LOG_ERROR, "No codec tag defined for stream %d\n", i);
+        return AVERROR(EINVAL);
+    }
 
-    put_v(bc, nut->stream[i].time_base - nut->time_base);
-    put_v(bc, nut->stream[i].msb_pts_shift);
-    put_v(bc, nut->stream[i].max_pts_distance);
-    put_v(bc, codec->has_b_frames);
-    put_byte(bc, 0); /* flags: 0x1 - fixed_fps, 0x2 - index_present */
+    ff_put_v(bc, nut->stream[i].time_base - nut->time_base);
+    ff_put_v(bc, nut->stream[i].msb_pts_shift);
+    ff_put_v(bc, nut->stream[i].max_pts_distance);
+    ff_put_v(bc, codec->has_b_frames);
+    avio_w8(bc, 0); /* flags: 0x1 - fixed_fps, 0x2 - index_present */
 
-    put_v(bc, codec->extradata_size);
-    put_buffer(bc, codec->extradata, codec->extradata_size);
+    ff_put_v(bc, codec->extradata_size);
+    avio_write(bc, codec->extradata, codec->extradata_size);
 
     switch(codec->codec_type){
     case AVMEDIA_TYPE_AUDIO:
-        put_v(bc, codec->sample_rate);
-        put_v(bc, 1);
-        put_v(bc, codec->channels);
+        ff_put_v(bc, codec->sample_rate);
+        ff_put_v(bc, 1);
+        ff_put_v(bc, codec->channels);
         break;
     case AVMEDIA_TYPE_VIDEO:
-        put_v(bc, codec->width);
-        put_v(bc, codec->height);
+        ff_put_v(bc, codec->width);
+        ff_put_v(bc, codec->height);
 
         if(st->sample_aspect_ratio.num<=0 || st->sample_aspect_ratio.den<=0){
-            put_v(bc, 0);
-            put_v(bc, 0);
+            ff_put_v(bc, 0);
+            ff_put_v(bc, 0);
         }else{
-            put_v(bc, st->sample_aspect_ratio.num);
-            put_v(bc, st->sample_aspect_ratio.den);
+            ff_put_v(bc, st->sample_aspect_ratio.num);
+            ff_put_v(bc, st->sample_aspect_ratio.den);
         }
-        put_v(bc, 0); /* csp type -- unknown */
+        ff_put_v(bc, 0); /* csp type -- unknown */
         break;
     default:
         break;
@@ -439,46 +423,46 @@ static int write_streamheader(NUTContext *nut, ByteIOContext *bc, AVStream *st,
     return 0;
 }
 
-static int add_info(ByteIOContext *bc, const char *type, const char *value){
+static int add_info(AVIOContext *bc, const char *type, const char *value){
     put_str(bc, type);
     put_s(bc, -1);
     put_str(bc, value);
     return 1;
 }
 
-static int write_globalinfo(NUTContext *nut, ByteIOContext *bc){
+static int write_globalinfo(NUTContext *nut, AVIOContext *bc){
     AVFormatContext *s= nut->avf;
     AVMetadataTag *t = NULL;
-    ByteIOContext *dyn_bc;
+    AVIOContext *dyn_bc;
     uint8_t *dyn_buf=NULL;
     int count=0, dyn_size;
-    int ret = url_open_dyn_buf(&dyn_bc);
+    int ret = avio_open_dyn_buf(&dyn_bc);
     if(ret < 0)
         return ret;
 
     while ((t = av_metadata_get(s->metadata, "", t, AV_METADATA_IGNORE_SUFFIX)))
         count += add_info(dyn_bc, t->key, t->value);
 
-    put_v(bc, 0); //stream_if_plus1
-    put_v(bc, 0); //chapter_id
-    put_v(bc, 0); //timestamp_start
-    put_v(bc, 0); //length
+    ff_put_v(bc, 0); //stream_if_plus1
+    ff_put_v(bc, 0); //chapter_id
+    ff_put_v(bc, 0); //timestamp_start
+    ff_put_v(bc, 0); //length
 
-    put_v(bc, count);
+    ff_put_v(bc, count);
 
-    dyn_size= url_close_dyn_buf(dyn_bc, &dyn_buf);
-    put_buffer(bc, dyn_buf, dyn_size);
+    dyn_size= avio_close_dyn_buf(dyn_bc, &dyn_buf);
+    avio_write(bc, dyn_buf, dyn_size);
     av_free(dyn_buf);
     return 0;
 }
 
-static int write_streaminfo(NUTContext *nut, ByteIOContext *bc, int stream_id){
+static int write_streaminfo(NUTContext *nut, AVIOContext *bc, int stream_id){
     AVFormatContext *s= nut->avf;
     AVStream* st = s->streams[stream_id];
-    ByteIOContext *dyn_bc;
+    AVIOContext *dyn_bc;
     uint8_t *dyn_buf=NULL;
     int count=0, dyn_size, i;
-    int ret = url_open_dyn_buf(&dyn_bc);
+    int ret = avio_open_dyn_buf(&dyn_bc);
     if(ret < 0)
         return ret;
 
@@ -486,49 +470,81 @@ static int write_streaminfo(NUTContext *nut, ByteIOContext *bc, int stream_id){
         if (st->disposition & ff_nut_dispositions[i].flag)
             count += add_info(dyn_bc, "Disposition", ff_nut_dispositions[i].str);
     }
-    dyn_size = url_close_dyn_buf(dyn_bc, &dyn_buf);
+    dyn_size = avio_close_dyn_buf(dyn_bc, &dyn_buf);
 
     if (count) {
-        put_v(bc, stream_id + 1); //stream_id_plus1
-        put_v(bc, 0); //chapter_id
-        put_v(bc, 0); //timestamp_start
-        put_v(bc, 0); //length
+        ff_put_v(bc, stream_id + 1); //stream_id_plus1
+        ff_put_v(bc, 0); //chapter_id
+        ff_put_v(bc, 0); //timestamp_start
+        ff_put_v(bc, 0); //length
 
-        put_v(bc, count);
+        ff_put_v(bc, count);
 
-        put_buffer(bc, dyn_buf, dyn_size);
+        avio_write(bc, dyn_buf, dyn_size);
     }
 
     av_free(dyn_buf);
     return count;
 }
 
-static int write_headers(NUTContext *nut, ByteIOContext *bc){
-    ByteIOContext *dyn_bc;
+static int write_chapter(NUTContext *nut, AVIOContext *bc, int id)
+{
+    AVIOContext *dyn_bc;
+    uint8_t *dyn_buf = NULL;
+    AVMetadataTag *t = NULL;
+    AVChapter *ch    = nut->avf->chapters[id];
+    int ret, dyn_size, count = 0;
+
+    ret = avio_open_dyn_buf(&dyn_bc);
+    if (ret < 0)
+        return ret;
+
+    ff_put_v(bc, 0);                                        // stream_id_plus1
+    put_s(bc, id + 1);                                      // chapter_id
+    put_tt(nut, nut->chapter[id].time_base, bc, ch->start); // chapter_start
+    ff_put_v(bc, ch->end - ch->start);                      // chapter_len
+
+    while ((t = av_metadata_get(ch->metadata, "", t, AV_METADATA_IGNORE_SUFFIX)))
+        count += add_info(dyn_bc, t->key, t->value);
+
+    ff_put_v(bc, count);
+
+    dyn_size = avio_close_dyn_buf(dyn_bc, &dyn_buf);
+    avio_write(bc, dyn_buf, dyn_size);
+    av_freep(&dyn_buf);
+    return 0;
+}
+
+static int write_headers(AVFormatContext *avctx, AVIOContext *bc){
+    NUTContext *nut = avctx->priv_data;
+    AVIOContext *dyn_bc;
     int i, ret;
 
-    ret = url_open_dyn_buf(&dyn_bc);
+    ff_metadata_conv_ctx(avctx, ff_nut_metadata_conv, NULL);
+
+    ret = avio_open_dyn_buf(&dyn_bc);
     if(ret < 0)
         return ret;
     write_mainheader(nut, dyn_bc);
     put_packet(nut, bc, dyn_bc, 1, MAIN_STARTCODE);
 
     for (i=0; i < nut->avf->nb_streams; i++){
-        ret = url_open_dyn_buf(&dyn_bc);
+        ret = avio_open_dyn_buf(&dyn_bc);
         if(ret < 0)
             return ret;
-        write_streamheader(nut, dyn_bc, nut->avf->streams[i], i);
+        if ((ret = write_streamheader(avctx, dyn_bc, nut->avf->streams[i], i)) < 0)
+            return ret;
         put_packet(nut, bc, dyn_bc, 1, STREAM_STARTCODE);
     }
 
-    ret = url_open_dyn_buf(&dyn_bc);
+    ret = avio_open_dyn_buf(&dyn_bc);
     if(ret < 0)
         return ret;
     write_globalinfo(nut, dyn_bc);
     put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
 
     for (i = 0; i < nut->avf->nb_streams; i++) {
-        ret = url_open_dyn_buf(&dyn_bc);
+        ret = avio_open_dyn_buf(&dyn_bc);
         if(ret < 0)
             return ret;
         ret = write_streaminfo(nut, dyn_bc, i);
@@ -538,11 +554,25 @@ static int write_headers(NUTContext *nut, ByteIOContext *bc){
             put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
         else {
             uint8_t* buf;
-            url_close_dyn_buf(dyn_bc, &buf);
+            avio_close_dyn_buf(dyn_bc, &buf);
             av_free(buf);
         }
     }
 
+    for (i = 0; i < nut->avf->nb_chapters; i++) {
+        ret = avio_open_dyn_buf(&dyn_bc);
+        if (ret < 0)
+            return ret;
+        ret = write_chapter(nut, dyn_bc, i);
+        if (ret < 0) {
+            uint8_t *buf;
+            avio_close_dyn_buf(dyn_bc, &buf);
+            av_freep(&buf);
+            return ret;
+        }
+        put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
+    }
+
     nut->last_syncpoint_pos= INT_MIN;
     nut->header_count++;
     return 0;
@@ -550,13 +580,15 @@ static int write_headers(NUTContext *nut, ByteIOContext *bc){
 
 static int write_header(AVFormatContext *s){
     NUTContext *nut = s->priv_data;
-    ByteIOContext *bc = s->pb;
-    int i, j;
+    AVIOContext *bc = s->pb;
+    int i, j, ret;
 
     nut->avf= s;
 
     nut->stream   = av_mallocz(sizeof(StreamContext)*s->nb_streams);
-    nut->time_base= av_mallocz(sizeof(AVRational   )*s->nb_streams);
+    nut->chapter  = av_mallocz(sizeof(ChapterContext)*s->nb_chapters);
+    nut->time_base= av_mallocz(sizeof(AVRational   )*(s->nb_streams +
+                                                      s->nb_chapters));
 
     for(i=0; i<s->nb_streams; i++){
         AVStream *st= s->streams[i];
@@ -576,11 +608,25 @@ static int write_header(AVFormatContext *s){
         if(j==nut->time_base_count)
             nut->time_base_count++;
 
-        if(av_q2d(time_base) >= 0.001)
+        if(INT64_C(1000) * time_base.num >= time_base.den)
             nut->stream[i].msb_pts_shift = 7;
         else
             nut->stream[i].msb_pts_shift = 14;
-        nut->stream[i].max_pts_distance= FFMAX(1/av_q2d(time_base), 1);
+        nut->stream[i].max_pts_distance= FFMAX(time_base.den, time_base.num) / time_base.num;
+    }
+
+    for (i = 0; i < s->nb_chapters; i++) {
+        AVChapter *ch = s->chapters[i];
+
+        for (j = 0; j < nut->time_base_count; j++) {
+            if (!memcmp(&ch->time_base, &nut->time_base[j], sizeof(AVRational)))
+                break;
+        }
+
+        nut->time_base[j] = ch->time_base;
+        nut->chapter[i].time_base = &nut->time_base[j];
+        if(j == nut->time_base_count)
+            nut->time_base_count++;
     }
 
     nut->max_distance = MAX_DISTANCE;
@@ -588,12 +634,13 @@ static int write_header(AVFormatContext *s){
     build_frame_code(s);
     assert(nut->frame_code['N'].flags == FLAG_INVALID);
 
-    put_buffer(bc, ID_STRING, strlen(ID_STRING));
-    put_byte(bc, 0);
+    avio_write(bc, ID_STRING, strlen(ID_STRING));
+    avio_w8(bc, 0);
 
-    write_headers(nut, bc);
+    if ((ret = write_headers(s, bc)) < 0)
+        return ret;
 
-    put_flush_packet(bc);
+    avio_flush(bc);
 
     //FIXME index
 
@@ -640,7 +687,7 @@ static int find_best_header_idx(NUTContext *nut, AVPacket *pkt){
 static int write_packet(AVFormatContext *s, AVPacket *pkt){
     NUTContext *nut = s->priv_data;
     StreamContext *nus= &nut->stream[pkt->stream_index];
-    ByteIOContext *bc = s->pb, *dyn_bc;
+    AVIOContext *bc = s->pb, *dyn_bc;
     FrameCode *fc;
     int64_t coded_pts;
     int best_length, frame_code, flags, needed_flags, i, header_idx, best_header_idx;
@@ -651,13 +698,13 @@ static int write_packet(AVFormatContext *s, AVPacket *pkt){
     if(pkt->pts < 0)
         return -1;
 
-    if(1LL<<(20+3*nut->header_count) <= url_ftell(bc))
-        write_headers(nut, bc);
+    if(1LL<<(20+3*nut->header_count) <= avio_tell(bc))
+        write_headers(s, bc);
 
     if(key_frame && !(nus->last_flags & FLAG_KEY))
         store_sp= 1;
 
-    if(pkt->size + 30/*FIXME check*/ + url_ftell(bc) >= nut->last_syncpoint_pos + nut->max_distance)
+    if(pkt->size + 30/*FIXME check*/ + avio_tell(bc) >= nut->last_syncpoint_pos + nut->max_distance)
         store_sp= 1;
 
 //FIXME: Ensure store_sp is 1 in the first place.
@@ -680,12 +727,12 @@ static int write_packet(AVFormatContext *s, AVPacket *pkt){
         sp= av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pos_cmp,
                          NULL);
 
-        nut->last_syncpoint_pos= url_ftell(bc);
-        ret = url_open_dyn_buf(&dyn_bc);
+        nut->last_syncpoint_pos= avio_tell(bc);
+        ret = avio_open_dyn_buf(&dyn_bc);
         if(ret < 0)
             return ret;
-        put_tt(nut, nus, dyn_bc, pkt->dts);
-        put_v(dyn_bc, sp ? (nut->last_syncpoint_pos - sp->pos)>>4 : 0);
+        put_tt(nut, nus->time_base, dyn_bc, pkt->dts);
+        ff_put_v(dyn_bc, sp ? (nut->last_syncpoint_pos - sp->pos)>>4 : 0);
         put_packet(nut, bc, dyn_bc, 1, SYNCPOINT_STARTCODE);
 
         ff_nut_add_sp(nut, nut->last_syncpoint_pos, 0/*unused*/, pkt->dts);
@@ -721,18 +768,18 @@ static int write_packet(AVFormatContext *s, AVPacket *pkt){
             continue;
 
         if(flags & FLAG_STREAM_ID)
-            length+= get_length(pkt->stream_index);
+            length+= ff_get_v_length(pkt->stream_index);
 
         if(pkt->size % fc->size_mul != fc->size_lsb)
             continue;
         if(flags & FLAG_SIZE_MSB)
-            length += get_length(pkt->size / fc->size_mul);
+            length += ff_get_v_length(pkt->size / fc->size_mul);
 
         if(flags & FLAG_CHECKSUM)
             length+=4;
 
         if(flags & FLAG_CODED_PTS)
-            length += get_length(coded_pts);
+            length += ff_get_v_length(coded_pts);
 
         if(   (flags & FLAG_CODED)
            && nut->header_len[best_header_idx] > nut->header_len[fc->header_idx]+1){
@@ -760,21 +807,21 @@ static int write_packet(AVFormatContext *s, AVPacket *pkt){
     needed_flags= get_needed_flags(nut, nus, fc, pkt);
     header_idx= fc->header_idx;
 
-    init_checksum(bc, ff_crc04C11DB7_update, 0);
-    put_byte(bc, frame_code);
+    ffio_init_checksum(bc, ff_crc04C11DB7_update, 0);
+    avio_w8(bc, frame_code);
     if(flags & FLAG_CODED){
-        put_v(bc, (flags^needed_flags) & ~(FLAG_CODED));
+        ff_put_v(bc, (flags^needed_flags) & ~(FLAG_CODED));
         flags = needed_flags;
     }
-    if(flags & FLAG_STREAM_ID)  put_v(bc, pkt->stream_index);
-    if(flags & FLAG_CODED_PTS)  put_v(bc, coded_pts);
-    if(flags & FLAG_SIZE_MSB)   put_v(bc, pkt->size / fc->size_mul);
-    if(flags & FLAG_HEADER_IDX) put_v(bc, header_idx= best_header_idx);
+    if(flags & FLAG_STREAM_ID)  ff_put_v(bc, pkt->stream_index);
+    if(flags & FLAG_CODED_PTS)  ff_put_v(bc, coded_pts);
+    if(flags & FLAG_SIZE_MSB)   ff_put_v(bc, pkt->size / fc->size_mul);
+    if(flags & FLAG_HEADER_IDX) ff_put_v(bc, header_idx= best_header_idx);
 
-    if(flags & FLAG_CHECKSUM)   put_le32(bc, get_checksum(bc));
-    else                        get_checksum(bc);
+    if(flags & FLAG_CHECKSUM)   avio_wl32(bc, ffio_get_checksum(bc));
+    else                        ffio_get_checksum(bc);
 
-    put_buffer(bc, pkt->data + nut->header_len[header_idx], pkt->size - nut->header_len[header_idx]);
+    avio_write(bc, pkt->data + nut->header_len[header_idx], pkt->size - nut->header_len[header_idx]);
     nus->last_flags= flags;
     nus->last_pts= pkt->pts;
 
@@ -793,19 +840,20 @@ static int write_packet(AVFormatContext *s, AVPacket *pkt){
 
 static int write_trailer(AVFormatContext *s){
     NUTContext *nut= s->priv_data;
-    ByteIOContext *bc= s->pb;
+    AVIOContext *bc= s->pb;
 
     while(nut->header_count<3)
-        write_headers(nut, bc);
-    put_flush_packet(bc);
+        write_headers(s, bc);
+    avio_flush(bc);
     ff_nut_free_sp(nut);
     av_freep(&nut->stream);
+    av_freep(&nut->chapter);
     av_freep(&nut->time_base);
 
     return 0;
 }
 
-AVOutputFormat nut_muxer = {
+AVOutputFormat ff_nut_muxer = {
     "nut",
     NULL_IF_CONFIG_SMALL("NUT format"),
     "video/x-nut",
@@ -823,6 +871,5 @@ AVOutputFormat nut_muxer = {
     write_packet,
     write_trailer,
     .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
-    .codec_tag= (const AVCodecTag* const []){ff_codec_bmp_tags, ff_codec_wav_tags, ff_nut_subtitle_tags, 0},
-    .metadata_conv = ff_nut_metadata_conv,
+    .codec_tag = (const AVCodecTag * const []){ ff_codec_bmp_tags, ff_nut_video_tags, ff_codec_wav_tags, ff_nut_subtitle_tags, 0 },
 };
diff --git a/libavformat/nuv.c b/libavformat/nuv.c
index f0eacd5..bf59610 100644
--- a/libavformat/nuv.c
+++ b/libavformat/nuv.c
@@ -2,20 +2,20 @@
  * NuppelVideo demuxer.
  * Copyright (c) 2006 Reimar Doeffinger
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -55,100 +55,100 @@ static int nuv_probe(AVProbeData *p) {
  * \param myth set if this is a MythTVVideo format file
  * \return 1 if all required codec data was found
  */
-static int get_codec_data(ByteIOContext *pb, AVStream *vst,
+static int get_codec_data(AVIOContext *pb, AVStream *vst,
                           AVStream *ast, int myth) {
     nuv_frametype frametype;
     if (!vst && !myth)
         return 1; // no codec data needed
-    while (!url_feof(pb)) {
+    while (!pb->eof_reached) {
         int size, subtype;
-        frametype = get_byte(pb);
+        frametype = avio_r8(pb);
         switch (frametype) {
             case NUV_EXTRADATA:
-                subtype = get_byte(pb);
-                url_fskip(pb, 6);
-                size = PKTSIZE(get_le32(pb));
+                subtype = avio_r8(pb);
+                avio_skip(pb, 6);
+                size = PKTSIZE(avio_rl32(pb));
                 if (vst && subtype == 'R') {
                     vst->codec->extradata_size = size;
                     vst->codec->extradata = av_malloc(size);
-                    get_buffer(pb, vst->codec->extradata, size);
+                    avio_read(pb, vst->codec->extradata, size);
                     size = 0;
                     if (!myth)
                         return 1;
                 }
                 break;
             case NUV_MYTHEXT:
-                url_fskip(pb, 7);
-                size = PKTSIZE(get_le32(pb));
+                avio_skip(pb, 7);
+                size = PKTSIZE(avio_rl32(pb));
                 if (size != 128 * 4)
                     break;
-                get_le32(pb); // version
+                avio_rl32(pb); // version
                 if (vst) {
-                    vst->codec->codec_tag = get_le32(pb);
+                    vst->codec->codec_tag = avio_rl32(pb);
                     vst->codec->codec_id =
                         ff_codec_get_id(ff_codec_bmp_tags, vst->codec->codec_tag);
                     if (vst->codec->codec_tag == MKTAG('R', 'J', 'P', 'G'))
                         vst->codec->codec_id = CODEC_ID_NUV;
                 } else
-                    url_fskip(pb, 4);
+                    avio_skip(pb, 4);
 
                 if (ast) {
-                    ast->codec->codec_tag = get_le32(pb);
-                    ast->codec->sample_rate = get_le32(pb);
-                    ast->codec->bits_per_coded_sample = get_le32(pb);
-                    ast->codec->channels = get_le32(pb);
+                    ast->codec->codec_tag = avio_rl32(pb);
+                    ast->codec->sample_rate = avio_rl32(pb);
+                    ast->codec->bits_per_coded_sample = avio_rl32(pb);
+                    ast->codec->channels = avio_rl32(pb);
                     ast->codec->codec_id =
                         ff_wav_codec_get_id(ast->codec->codec_tag,
                                          ast->codec->bits_per_coded_sample);
                     ast->need_parsing = AVSTREAM_PARSE_FULL;
                 } else
-                    url_fskip(pb, 4 * 4);
+                    avio_skip(pb, 4 * 4);
 
                 size -= 6 * 4;
-                url_fskip(pb, size);
+                avio_skip(pb, size);
                 return 1;
             case NUV_SEEKP:
                 size = 11;
                 break;
             default:
-                url_fskip(pb, 7);
-                size = PKTSIZE(get_le32(pb));
+                avio_skip(pb, 7);
+                size = PKTSIZE(avio_rl32(pb));
                 break;
         }
-        url_fskip(pb, size);
+        avio_skip(pb, size);
     }
     return 0;
 }
 
 static int nuv_header(AVFormatContext *s, AVFormatParameters *ap) {
     NUVContext *ctx = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     char id_string[12];
     double aspect, fps;
     int is_mythtv, width, height, v_packs, a_packs;
     int stream_nr = 0;
     AVStream *vst = NULL, *ast = NULL;
-    get_buffer(pb, id_string, 12);
+    avio_read(pb, id_string, 12);
     is_mythtv = !memcmp(id_string, "MythTVVideo", 12);
-    url_fskip(pb, 5); // version string
-    url_fskip(pb, 3); // padding
-    width = get_le32(pb);
-    height = get_le32(pb);
-    get_le32(pb); // unused, "desiredwidth"
-    get_le32(pb); // unused, "desiredheight"
-    get_byte(pb); // 'P' == progressive, 'I' == interlaced
-    url_fskip(pb, 3); // padding
-    aspect = av_int2dbl(get_le64(pb));
+    avio_skip(pb, 5); // version string
+    avio_skip(pb, 3); // padding
+    width = avio_rl32(pb);
+    height = avio_rl32(pb);
+    avio_rl32(pb); // unused, "desiredwidth"
+    avio_rl32(pb); // unused, "desiredheight"
+    avio_r8(pb); // 'P' == progressive, 'I' == interlaced
+    avio_skip(pb, 3); // padding
+    aspect = av_int2dbl(avio_rl64(pb));
     if (aspect > 0.9999 && aspect < 1.0001)
         aspect = 4.0 / 3.0;
-    fps = av_int2dbl(get_le64(pb));
+    fps = av_int2dbl(avio_rl64(pb));
 
     // number of packets per stream type, -1 means unknown, e.g. streaming
-    v_packs = get_le32(pb);
-    a_packs = get_le32(pb);
-    get_le32(pb); // text
+    v_packs = avio_rl32(pb);
+    a_packs = avio_rl32(pb);
+    avio_rl32(pb); // text
 
-    get_le32(pb); // keyframe distance (?)
+    avio_rl32(pb); // keyframe distance (?)
 
     if (v_packs) {
         ctx->v_id = stream_nr++;
@@ -191,14 +191,14 @@ static int nuv_header(AVFormatContext *s, AVFormatParameters *ap) {
 
 static int nuv_packet(AVFormatContext *s, AVPacket *pkt) {
     NUVContext *ctx = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     uint8_t hdr[HDRSIZE];
     nuv_frametype frametype;
     int ret, size;
-    while (!url_feof(pb)) {
+    while (!pb->eof_reached) {
         int copyhdrsize = ctx->rtjpg_video ? HDRSIZE : 0;
-        uint64_t pos = url_ftell(pb);
-        ret = get_buffer(pb, hdr, HDRSIZE);
+        uint64_t pos = avio_tell(pb);
+        ret = avio_read(pb, hdr, HDRSIZE);
         if (ret < HDRSIZE)
             return ret < 0 ? ret : AVERROR(EIO);
         frametype = hdr[0];
@@ -206,13 +206,13 @@ static int nuv_packet(AVFormatContext *s, AVPacket *pkt) {
         switch (frametype) {
             case NUV_EXTRADATA:
                 if (!ctx->rtjpg_video) {
-                    url_fskip(pb, size);
+                    avio_skip(pb, size);
                     break;
                 }
             case NUV_VIDEO:
                 if (ctx->v_id < 0) {
                     av_log(s, AV_LOG_ERROR, "Video packet in file without video stream!\n");
-                    url_fskip(pb, size);
+                    avio_skip(pb, size);
                     break;
                 }
                 ret = av_new_packet(pkt, copyhdrsize + size);
@@ -225,7 +225,7 @@ static int nuv_packet(AVFormatContext *s, AVPacket *pkt) {
                 pkt->pts = AV_RL32(&hdr[4]);
                 pkt->stream_index = ctx->v_id;
                 memcpy(pkt->data, hdr, copyhdrsize);
-                ret = get_buffer(pb, pkt->data + copyhdrsize, size);
+                ret = avio_read(pb, pkt->data + copyhdrsize, size);
                 if (ret < 0) {
                     av_free_packet(pkt);
                     return ret;
@@ -236,7 +236,7 @@ static int nuv_packet(AVFormatContext *s, AVPacket *pkt) {
             case NUV_AUDIO:
                 if (ctx->a_id < 0) {
                     av_log(s, AV_LOG_ERROR, "Audio packet in file without audio stream!\n");
-                    url_fskip(pb, size);
+                    avio_skip(pb, size);
                     break;
                 }
                 ret = av_get_packet(pb, pkt, size);
@@ -250,14 +250,14 @@ static int nuv_packet(AVFormatContext *s, AVPacket *pkt) {
                 // contains no data, size value is invalid
                 break;
             default:
-                url_fskip(pb, size);
+                avio_skip(pb, size);
                 break;
         }
     }
     return AVERROR(EIO);
 }
 
-AVInputFormat nuv_demuxer = {
+AVInputFormat ff_nuv_demuxer = {
     "nuv",
     NULL_IF_CONFIG_SMALL("NuppelVideo format"),
     sizeof(NUVContext),
diff --git a/libavformat/oggdec.c b/libavformat/oggdec.c
index 3161e68..ce1152d 100644
--- a/libavformat/oggdec.c
+++ b/libavformat/oggdec.c
@@ -62,7 +62,7 @@ ogg_save (AVFormatContext * s)
     struct ogg_state *ost =
         av_malloc(sizeof (*ost) + (ogg->nstreams-1) * sizeof (*ogg->streams));
     int i;
-    ost->pos = url_ftell (s->pb);
+    ost->pos = avio_tell (s->pb);
     ost->curidx = ogg->curidx;
     ost->next = ogg->state;
     ost->nstreams = ogg->nstreams;
@@ -84,7 +84,7 @@ static int
 ogg_restore (AVFormatContext * s, int discard)
 {
     struct ogg *ogg = s->priv_data;
-    ByteIOContext *bc = s->pb;
+    AVIOContext *bc = s->pb;
     struct ogg_state *ost = ogg->state;
     int i;
 
@@ -97,7 +97,7 @@ ogg_restore (AVFormatContext * s, int discard)
         for (i = 0; i < ogg->nstreams; i++)
             av_free (ogg->streams[i].buf);
 
-        url_fseek (bc, ost->pos, SEEK_SET);
+        avio_seek (bc, ost->pos, SEEK_SET);
         ogg->curidx = ost->curidx;
         ogg->nstreams = ost->nstreams;
         memcpy(ogg->streams, ost->streams,
@@ -194,7 +194,7 @@ ogg_new_buf(struct ogg *ogg, int idx)
 static int
 ogg_read_page (AVFormatContext * s, int *str)
 {
-    ByteIOContext *bc = s->pb;
+    AVIOContext *bc = s->pb;
     struct ogg *ogg = s->priv_data;
     struct ogg_stream *os;
     int i = 0;
@@ -207,7 +207,7 @@ ogg_read_page (AVFormatContext * s, int *str)
     uint8_t sync[4];
     int sp = 0;
 
-    if (get_buffer (bc, sync, 4) < 4)
+    if (avio_read (bc, sync, 4) < 4)
         return -1;
 
     do{
@@ -218,8 +218,8 @@ ogg_read_page (AVFormatContext * s, int *str)
             sync[(sp + 2) & 3] == 'g' && sync[(sp + 3) & 3] == 'S')
             break;
 
-        c = url_fgetc (bc);
-        if (c < 0)
+        c = avio_r8(bc);
+        if (bc->eof_reached)
             return -1;
         sync[sp++ & 3] = c;
     }while (i++ < MAX_PAGE_SIZE);
@@ -229,30 +229,40 @@ ogg_read_page (AVFormatContext * s, int *str)
         return -1;
     }
 
-    if (url_fgetc (bc) != 0)      /* version */
+    if (avio_r8(bc) != 0)      /* version */
         return -1;
 
-    flags = url_fgetc (bc);
-    gp = get_le64 (bc);
-    serial = get_le32 (bc);
-    seq = get_le32 (bc);
-    crc = get_le32 (bc);
-    nsegs = url_fgetc (bc);
+    flags = avio_r8(bc);
+    gp = avio_rl64 (bc);
+    serial = avio_rl32 (bc);
+    seq = avio_rl32 (bc);
+    crc = avio_rl32 (bc);
+    nsegs = avio_r8(bc);
 
     idx = ogg_find_stream (ogg, serial);
     if (idx < 0){
+        if (ogg->headers) {
+                int n;
+
+                for (n = 0; n < ogg->nstreams; n++) {
+                    av_free(ogg->streams[n].buf);
+                    av_free(ogg->streams[n].private);
+                }
+                ogg->curidx   = -1;
+                ogg->nstreams = 0;
+        }
         idx = ogg_new_stream (s, serial);
         if (idx < 0)
             return -1;
     }
 
     os = ogg->streams + idx;
-    os->page_pos = url_ftell(bc) - 27;
+    os->page_pos = avio_tell(bc) - 27;
 
     if(os->psize > 0)
         ogg_new_buf(ogg, idx);
 
-    if (get_buffer (bc, os->segments, nsegs) < nsegs)
+    if (avio_read (bc, os->segments, nsegs) < nsegs)
         return -1;
 
     os->nsegs = nsegs;
@@ -284,7 +294,7 @@ ogg_read_page (AVFormatContext * s, int *str)
         os->buf = nb;
     }
 
-    if (get_buffer (bc, os->buf + os->bufpos, size) < size)
+    if (avio_read (bc, os->buf + os->bufpos, size) < size)
         return -1;
 
     os->bufpos += size;
@@ -363,7 +373,7 @@ ogg_packet (AVFormatContext * s, int *str, int *dstart, int *dsize, int64_t *fpo
 #endif
 
     if (os->granule == -1)
-        av_log(s, AV_LOG_WARNING, "Page at %lld is missing granule\n", os->page_pos);
+        av_log(s, AV_LOG_WARNING, "Page at %"PRId64" is missing granule\n", os->page_pos);
 
     ogg->curidx = idx;
     os->incomplete = 0;
@@ -373,9 +383,27 @@ ogg_packet (AVFormatContext * s, int *str, int *dstart, int *dsize, int64_t *fpo
         if (!os->header){
             os->segp = segp;
             os->psize = psize;
-            if (!ogg->headers)
-                s->data_offset = os->sync_pos;
+
+            // We have reached the first non-header packet in this stream.
+            // Unfortunately more header packets may still follow for others,
+            // so we reset this later unless we are done with the headers
+            // for all streams.
             ogg->headers = 1;
+
+            // Update the header state for all streams and
+            // compute the data_offset.
+            if (!s->data_offset)
+                s->data_offset = os->sync_pos;
+            for (i = 0; i < ogg->nstreams; i++) {
+                struct ogg_stream *cur_os = ogg->streams + i;
+                if (cur_os->header > 0)
+                    ogg->headers = 0;
+
+                // if we have a partial non-header packet, its start is
+                // obviously at or after the data start
+                if (cur_os->incomplete)
+                    s->data_offset = FFMIN(s->data_offset, cur_os->sync_pos);
+            }
         }else{
             os->pstart += os->psize;
             os->psize = 0;
@@ -437,20 +465,20 @@ ogg_get_length (AVFormatContext * s)
     int i;
     int64_t size, end;
 
-    if(url_is_streamed(s->pb))
+    if(!s->pb->seekable)
         return 0;
 
 // already set
     if (s->duration != AV_NOPTS_VALUE)
         return 0;
 
-    size = url_fsize(s->pb);
+    size = avio_size(s->pb);
     if(size < 0)
         return 0;
     end = size > MAX_PAGE_SIZE? size - MAX_PAGE_SIZE: 0;
 
     ogg_save (s);
-    url_fseek (s->pb, end, SEEK_SET);
+    avio_seek (s->pb, end, SEEK_SET);
 
     while (!ogg_read_page (s, &i)){
         if (ogg->streams[i].granule != -1 && ogg->streams[i].granule != 0 &&
@@ -583,13 +611,13 @@ ogg_read_timestamp (AVFormatContext * s, int stream_index, int64_t * pos_arg,
 {
     struct ogg *ogg = s->priv_data;
     struct ogg_stream *os = ogg->streams + stream_index;
-    ByteIOContext *bc = s->pb;
+    AVIOContext *bc = s->pb;
     int64_t pts = AV_NOPTS_VALUE;
     int i;
-    url_fseek(bc, *pos_arg, SEEK_SET);
+    avio_seek(bc, *pos_arg, SEEK_SET);
     ogg_reset(ogg);
 
-    while (url_ftell(bc) < pos_limit && !ogg_packet(s, &i, NULL, NULL, pos_arg)) {
+    while (avio_tell(bc) < pos_limit && !ogg_packet(s, &i, NULL, NULL, pos_arg)) {
         if (i == stream_index) {
             pts = ogg_calc_pts(s, i, NULL);
             if (os->keyframe_seek && !(os->pflags & AV_PKT_FLAG_KEY))
@@ -630,7 +658,7 @@ static int ogg_probe(AVProbeData *p)
         return 0;
 }
 
-AVInputFormat ogg_demuxer = {
+AVInputFormat ff_ogg_demuxer = {
     "ogg",
     NULL_IF_CONFIG_SMALL("Ogg"),
     sizeof (struct ogg),
@@ -641,6 +669,5 @@ AVInputFormat ogg_demuxer = {
     ogg_read_seek,
     ogg_read_timestamp,
     .extensions = "ogg",
-    .metadata_conv = ff_vorbiscomment_metadata_conv,
     .flags = AVFMT_GENERIC_INDEX,
 };
diff --git a/libavformat/oggenc.c b/libavformat/oggenc.c
index 70264a4..92c751c 100644
--- a/libavformat/oggenc.c
+++ b/libavformat/oggenc.c
@@ -2,28 +2,30 @@
  * Ogg muxer
  * Copyright (c) 2007 Baptiste Coudurier <baptiste dot coudurier at free dot fr>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "libavutil/crc.h"
+#include "libavutil/random_seed.h"
 #include "libavcodec/xiph.h"
 #include "libavcodec/bytestream.h"
 #include "libavcodec/flac.h"
 #include "avformat.h"
+#include "avio_internal.h"
 #include "internal.h"
 #include "vorbiscomment.h"
 
@@ -40,7 +42,6 @@ typedef struct {
 } OGGPage;
 
 typedef struct {
-    int64_t duration;
     unsigned page_counter;
     uint8_t *header[3];
     int header_len[3];
@@ -51,6 +52,8 @@ typedef struct {
     int eos;
     unsigned page_count; ///< number of page buffered
     OGGPage page; ///< current page
+    unsigned serial_num; ///< serial number
+    int64_t last_granule; ///< last packet granule
 } OGGStreamContext;
 
 typedef struct OGGPageList {
@@ -62,45 +65,60 @@ typedef struct {
     OGGPageList *page_list;
 } OGGContext;
 
-static void ogg_update_checksum(AVFormatContext *s, int64_t crc_offset)
+static void ogg_update_checksum(AVFormatContext *s, AVIOContext *pb, int64_t crc_offset)
 {
-    int64_t pos = url_ftell(s->pb);
-    uint32_t checksum = get_checksum(s->pb);
-    url_fseek(s->pb, crc_offset, SEEK_SET);
-    put_be32(s->pb, checksum);
-    url_fseek(s->pb, pos, SEEK_SET);
+    int64_t pos = avio_tell(pb);
+    uint32_t checksum = ffio_get_checksum(pb);
+    avio_seek(pb, crc_offset, SEEK_SET);
+    avio_wb32(pb, checksum);
+    avio_seek(pb, pos, SEEK_SET);
 }
 
-static void ogg_write_page(AVFormatContext *s, OGGPage *page, int extra_flags)
+static int ogg_write_page(AVFormatContext *s, OGGPage *page, int extra_flags)
 {
     OGGStreamContext *oggstream = s->streams[page->stream_index]->priv_data;
+    AVIOContext *pb;
     int64_t crc_offset;
+    int ret, size;
+    uint8_t *buf;
 
-    init_checksum(s->pb, ff_crc04C11DB7_update, 0);
-    put_tag(s->pb, "OggS");
-    put_byte(s->pb, 0);
-    put_byte(s->pb, page->flags | extra_flags);
-    put_le64(s->pb, page->granule);
-    put_le32(s->pb, page->stream_index);
-    put_le32(s->pb, oggstream->page_counter++);
-    crc_offset = url_ftell(s->pb);
-    put_le32(s->pb, 0); // crc
-    put_byte(s->pb, page->segments_count);
-    put_buffer(s->pb, page->segments, page->segments_count);
-    put_buffer(s->pb, page->data, page->size);
-
-    ogg_update_checksum(s, crc_offset);
-    put_flush_packet(s->pb);
+    ret = avio_open_dyn_buf(&pb);
+    if (ret < 0)
+        return ret;
+    ffio_init_checksum(pb, ff_crc04C11DB7_update, 0);
+    ffio_wfourcc(pb, "OggS");
+    avio_w8(pb, 0);
+    avio_w8(pb, page->flags | extra_flags);
+    avio_wl64(pb, page->granule);
+    avio_wl32(pb, oggstream->serial_num);
+    avio_wl32(pb, oggstream->page_counter++);
+    crc_offset = avio_tell(pb);
+    avio_wl32(pb, 0); // crc
+    avio_w8(pb, page->segments_count);
+    avio_write(pb, page->segments, page->segments_count);
+    avio_write(pb, page->data, page->size);
+
+    ogg_update_checksum(s, pb, crc_offset);
+    avio_flush(pb);
+
+    size = avio_close_dyn_buf(pb, &buf);
+    if (size < 0)
+        return size;
+
+    avio_write(s->pb, buf, size);
+    avio_flush(s->pb);
+    av_free(buf);
     oggstream->page_count--;
+    return 0;
 }
 
-static int64_t ogg_granule_to_timestamp(OGGStreamContext *oggstream, OGGPage *page)
+static int64_t ogg_granule_to_timestamp(OGGStreamContext *oggstream, int64_t granule)
 {
     if (oggstream->kfgshift)
-        return (page->granule>>oggstream->kfgshift) +
-            (page->granule & ((1<<oggstream->kfgshift)-1));
+        return (granule>>oggstream->kfgshift) +
+            (granule & ((1<<oggstream->kfgshift)-1));
     else
-        return page->granule;
+        return granule;
 }
 
 static int ogg_compare_granule(AVFormatContext *s, OGGPage *next, OGGPage *page)
@@ -112,9 +130,9 @@ static int ogg_compare_granule(AVFormatContext *s, OGGPage *next, OGGPage *page)
     if (next->granule == -1 || page->granule == -1)
         return 0;
 
-    next_granule = av_rescale_q(ogg_granule_to_timestamp(st2->priv_data, next),
+    next_granule = av_rescale_q(ogg_granule_to_timestamp(st2->priv_data, next->granule),
                                 st2->time_base, AV_TIME_BASE_Q);
-    cur_granule  = av_rescale_q(ogg_granule_to_timestamp(st->priv_data, page),
+    cur_granule  = av_rescale_q(ogg_granule_to_timestamp(st->priv_data, page->granule),
                                 st ->time_base, AV_TIME_BASE_Q);
     return next_granule > cur_granule;
 }
@@ -158,7 +176,16 @@ static int ogg_buffer_data(AVFormatContext *s, AVStream *st,
     OGGStreamContext *oggstream = st->priv_data;
     int total_segments = size / 255 + 1;
     uint8_t *p = data;
-    int i, segments, len;
+    int i, segments, len, flush = 0;
+
+    // Handles VFR by flushing page because this frame needs to have a timestamp
+    if (st->codec->codec_id == CODEC_ID_THEORA &&
+        ogg_granule_to_timestamp(oggstream, granule) >
+        ogg_granule_to_timestamp(oggstream, oggstream->last_granule) + 1) {
+        if (oggstream->page.granule != -1)
+            ogg_buffer_page(s, oggstream);
+        flush = 1;
+    }
 
     for (i = 0; i < total_segments; ) {
         OGGPage *page = &oggstream->page;
@@ -186,18 +213,24 @@ static int ogg_buffer_data(AVFormatContext *s, AVStream *st,
             ogg_buffer_page(s, oggstream);
         }
     }
+
+    if (flush && oggstream->page.granule != -1)
+        ogg_buffer_page(s, oggstream);
+
     return 0;
 }
 
 static uint8_t *ogg_write_vorbiscomment(int offset, int bitexact,
-                                        int *header_len, AVMetadata *m)
+                                        int *header_len, AVMetadata **m, int framing_bit)
 {
     const char *vendor = bitexact ? "ffmpeg" : LIBAVFORMAT_IDENT;
     int size;
     uint8_t *p, *p0;
     unsigned int count;
 
-    size = offset + ff_vorbiscomment_length(m, vendor, &count);
+    ff_metadata_conv(m, ff_vorbiscomment_metadata_conv, NULL);
+
+    size = offset + ff_vorbiscomment_length(*m, vendor, &count) + framing_bit;
     p = av_mallocz(size);
     if (!p)
         return NULL;
@@ -205,6 +238,8 @@ static uint8_t *ogg_write_vorbiscomment(int offset, int bitexact,
 
     p += offset;
     ff_vorbiscomment_write(&p, m, vendor, count);
+    if (framing_bit)
+        bytestream_put_byte(&p, 1);
 
     *header_len = size;
     return p0;
@@ -212,7 +247,7 @@ static uint8_t *ogg_write_vorbiscomment(int offset, int bitexact,
 
 static int ogg_build_flac_headers(AVCodecContext *avctx,
                                   OGGStreamContext *oggstream, int bitexact,
-                                  AVMetadata *m)
+                                  AVMetadata **m)
 {
     enum FLACExtradataFormat format;
     uint8_t *streaminfo;
@@ -238,7 +273,7 @@ static int ogg_build_flac_headers(AVCodecContext *avctx,
     bytestream_put_buffer(&p, streaminfo, FLAC_STREAMINFO_SIZE);
 
     // second packet: VorbisComment
-    p = ogg_write_vorbiscomment(4, bitexact, &oggstream->header_len[1], m);
+    p = ogg_write_vorbiscomment(4, bitexact, &oggstream->header_len[1], m, 0);
     if (!p)
         return AVERROR(ENOMEM);
     oggstream->header[1] = p;
@@ -252,7 +287,7 @@ static int ogg_build_flac_headers(AVCodecContext *avctx,
 
 static int ogg_build_speex_headers(AVCodecContext *avctx,
                                    OGGStreamContext *oggstream, int bitexact,
-                                   AVMetadata *m)
+                                   AVMetadata **m)
 {
     uint8_t *p;
 
@@ -269,7 +304,7 @@ static int ogg_build_speex_headers(AVCodecContext *avctx,
     AV_WL32(&oggstream->header[0][68], 0);  // set extra_headers to 0
 
     // second packet: VorbisComment
-    p = ogg_write_vorbiscomment(0, bitexact, &oggstream->header_len[1], m);
+    p = ogg_write_vorbiscomment(0, bitexact, &oggstream->header_len[1], m, 0);
     if (!p)
         return AVERROR(ENOMEM);
     oggstream->header[1] = p;
@@ -281,8 +316,11 @@ static int ogg_write_header(AVFormatContext *s)
 {
     OGGStreamContext *oggstream;
     int i, j;
+
     for (i = 0; i < s->nb_streams; i++) {
         AVStream *st = s->streams[i];
+        unsigned serial_num = i;
+
         if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
             av_set_pts_info(st, 64, 1, st->codec->sample_rate);
         else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
@@ -301,11 +339,23 @@ static int ogg_write_header(AVFormatContext *s)
         }
         oggstream = av_mallocz(sizeof(*oggstream));
         oggstream->page.stream_index = i;
+
+        if (!(st->codec->flags & CODEC_FLAG_BITEXACT))
+            do {
+                serial_num = av_get_random_seed();
+                for (j = 0; j < i; j++) {
+                    OGGStreamContext *sc = s->streams[j]->priv_data;
+                    if (serial_num == sc->serial_num)
+                        break;
+                }
+            } while (j < i);
+        oggstream->serial_num = serial_num;
+
         st->priv_data = oggstream;
         if (st->codec->codec_id == CODEC_ID_FLAC) {
             int err = ogg_build_flac_headers(st->codec, oggstream,
                                              st->codec->flags & CODEC_FLAG_BITEXACT,
-                                             s->metadata);
+                                             &s->metadata);
             if (err) {
                 av_log(s, AV_LOG_ERROR, "Error writing FLAC headers\n");
                 av_freep(&st->priv_data);
@@ -314,13 +364,18 @@ static int ogg_write_header(AVFormatContext *s)
         } else if (st->codec->codec_id == CODEC_ID_SPEEX) {
             int err = ogg_build_speex_headers(st->codec, oggstream,
                                               st->codec->flags & CODEC_FLAG_BITEXACT,
-                                              s->metadata);
+                                              &s->metadata);
             if (err) {
                 av_log(s, AV_LOG_ERROR, "Error writing Speex headers\n");
                 av_freep(&st->priv_data);
                 return err;
             }
         } else {
+            uint8_t *p;
+            const char *cstr = st->codec->codec_id == CODEC_ID_VORBIS ? "vorbis" : "theora";
+            int header_type = st->codec->codec_id == CODEC_ID_VORBIS ? 3 : 0x81;
+            int framing_bit = st->codec->codec_id == CODEC_ID_VORBIS ? 1 : 0;
+
             if (ff_split_xiph_headers(st->codec->extradata, st->codec->extradata_size,
                                       st->codec->codec_id == CODEC_ID_VORBIS ? 30 : 42,
                                       oggstream->header, oggstream->header_len) < 0) {
@@ -328,6 +383,17 @@ static int ogg_write_header(AVFormatContext *s)
                 av_freep(&st->priv_data);
                 return -1;
             }
+
+            p = ogg_write_vorbiscomment(7, st->codec->flags & CODEC_FLAG_BITEXACT,
+                                        &oggstream->header_len[1], &s->metadata,
+                                        framing_bit);
+            if (!p)
+                return AVERROR(ENOMEM);
+
+            oggstream->header[1] = p;
+            bytestream_put_byte(&p, header_type);
+            bytestream_put_buffer(&p, cstr, 6);
+
             if (st->codec->codec_id == CODEC_ID_THEORA) {
                 /** KFGSHIFT is the width of the less significant section of the granule position
                     The less significant section is the frame count since the last keyframe */
@@ -402,7 +468,6 @@ static int ogg_write_packet(AVFormatContext *s, AVPacket *pkt)
         granule = (oggstream->last_kf_pts<<oggstream->kfgshift) | pframe_count;
     } else
         granule = pkt->pts + pkt->duration;
-    oggstream->duration = granule;
 
     ret = ogg_buffer_data(s, st, pkt->data, pkt->size, granule);
     if (ret < 0)
@@ -410,6 +475,8 @@ static int ogg_write_packet(AVFormatContext *s, AVPacket *pkt)
 
     ogg_write_pages(s, 0);
 
+    oggstream->last_granule = granule;
+
     return 0;
 }
 
@@ -436,7 +503,7 @@ static int ogg_write_trailer(AVFormatContext *s)
     return 0;
 }
 
-AVOutputFormat ogg_muxer = {
+AVOutputFormat ff_ogg_muxer = {
     "ogg",
     NULL_IF_CONFIG_SMALL("Ogg"),
     "application/ogg",
@@ -447,5 +514,4 @@ AVOutputFormat ogg_muxer = {
     ogg_write_header,
     ogg_write_packet,
     ogg_write_trailer,
-    .metadata_conv = ff_vorbiscomment_metadata_conv,
 };
diff --git a/libavformat/oggparsedirac.c b/libavformat/oggparsedirac.c
index a7f0401..f6afafd 100644
--- a/libavformat/oggparsedirac.c
+++ b/libavformat/oggparsedirac.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (C) 2008  David Conrad
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -42,7 +42,7 @@ static int dirac_header(AVFormatContext *s, int idx)
     st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
     st->codec->codec_id = CODEC_ID_DIRAC;
     // dirac in ogg always stores timestamps as though the video were interlaced
-    st->time_base = (AVRational){st->codec->time_base.num, 2*st->codec->time_base.den};
+    av_set_pts_info(st, 64, st->codec->time_base.num, 2*st->codec->time_base.den);
     return 1;
 }
 
@@ -79,8 +79,7 @@ static int old_dirac_header(AVFormatContext *s, int idx)
 
     st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
     st->codec->codec_id = CODEC_ID_DIRAC;
-    st->time_base.den = AV_RB32(buf+8);
-    st->time_base.num = AV_RB32(buf+12);
+    av_set_pts_info(st, 64, AV_RB32(buf+12), AV_RB32(buf+8));
     return 1;
 }
 
diff --git a/libavformat/oggparseflac.c b/libavformat/oggparseflac.c
index e5034af..53cd0fa 100644
--- a/libavformat/oggparseflac.c
+++ b/libavformat/oggparseflac.c
@@ -1,20 +1,20 @@
 /*
  *    Copyright (C) 2005  Matthieu CASTET
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -65,8 +65,7 @@ flac_header (AVFormatContext * s, int idx)
         memcpy(st->codec->extradata, streaminfo_start, FLAC_STREAMINFO_SIZE);
         st->codec->extradata_size = FLAC_STREAMINFO_SIZE;
 
-        st->time_base.num = 1;
-        st->time_base.den = st->codec->sample_rate;
+        av_set_pts_info(st, 64, 1, st->codec->sample_rate);
     } else if (mdt == FLAC_METADATA_TYPE_VORBIS_COMMENT) {
         ff_vorbis_comment (s, &st->metadata, os->buf + os->pstart + 4, os->psize - 4);
     }
diff --git a/libavformat/oggparseogm.c b/libavformat/oggparseogm.c
index e1d046f..dda5be6 100644
--- a/libavformat/oggparseogm.c
+++ b/libavformat/oggparseogm.c
@@ -83,14 +83,13 @@ ogm_header(AVFormatContext *s, int idx)
             st->codec->height = bytestream_get_le32(&p);
             st->codec->time_base.den = spu * 10000000;
             st->codec->time_base.num = time_unit;
-            st->time_base = st->codec->time_base;
+            av_set_pts_info(st, 64, st->codec->time_base.num, st->codec->time_base.den);
         } else {
             st->codec->channels = bytestream_get_le16(&p);
             p += 2;                 /* block_align */
             st->codec->bit_rate = bytestream_get_le32(&p) * 8;
             st->codec->sample_rate = spu * 10000000 / time_unit;
-            st->time_base.num = 1;
-            st->time_base.den = st->codec->sample_rate;
+            av_set_pts_info(st, 64, 1, st->codec->sample_rate);
         }
     } else if (*p == 3) {
         if (os->psize > 8)
diff --git a/libavformat/oggparseskeleton.c b/libavformat/oggparseskeleton.c
index ad0dded..ceb7c69 100644
--- a/libavformat/oggparseskeleton.c
+++ b/libavformat/oggparseskeleton.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (C) 2010 David Conrad
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -60,8 +60,9 @@ static int skeleton_header(AVFormatContext *s, int idx)
         start_den = AV_RL64(buf+20);
 
         if (start_den) {
-            av_reduce(&start_time, &st->time_base.den, start_num, start_den, INT_MAX);
-            st->time_base.num = 1;
+            int base_den;
+            av_reduce(&start_time, &base_den, start_num, start_den, INT_MAX);
+            av_set_pts_info(st, 64, 1, base_den);
             os->lastpts =
             st->start_time = start_time;
         }
diff --git a/libavformat/oggparsespeex.c b/libavformat/oggparsespeex.c
index 936b37e..2f4aec7 100644
--- a/libavformat/oggparsespeex.c
+++ b/libavformat/oggparsespeex.c
@@ -59,7 +59,7 @@ static int speex_header(AVFormatContext *s, int idx) {
         st->codec->channels = AV_RL32(p + 48);
 
         /* We treat the whole Speex packet as a single frame everywhere Speex
-           is handled in FFmpeg.  This avoids the complexities of splitting
+           is handled in Libav.  This avoids the complexities of splitting
            and joining individual Speex frames, which are not always
            byte-aligned. */
         st->codec->frame_size = AV_RL32(p + 56);
@@ -72,8 +72,7 @@ static int speex_header(AVFormatContext *s, int idx) {
                                          + FF_INPUT_BUFFER_PADDING_SIZE);
         memcpy(st->codec->extradata, p, st->codec->extradata_size);
 
-        st->time_base.num = 1;
-        st->time_base.den = st->codec->sample_rate;
+        av_set_pts_info(st, 64, 1, st->codec->sample_rate);
     } else
         ff_vorbis_comment(s, &st->metadata, p, os->psize);
 
diff --git a/libavformat/oggparsetheora.c b/libavformat/oggparsetheora.c
index 2299f55..d02781f 100644
--- a/libavformat/oggparsetheora.c
+++ b/libavformat/oggparsetheora.c
@@ -91,7 +91,7 @@ theora_header (AVFormatContext * s, int idx)
             st->codec->time_base.num = 1;
             st->codec->time_base.den = 25;
         }
-        st->time_base = st->codec->time_base;
+        av_set_pts_info(st, 64, st->codec->time_base.num, st->codec->time_base.den);
 
         st->sample_aspect_ratio.num = get_bits_long(&gb, 24);
         st->sample_aspect_ratio.den = get_bits_long(&gb, 24);
diff --git a/libavformat/oggparsevorbis.c b/libavformat/oggparsevorbis.c
index 886ef52..830f0bc 100644
--- a/libavformat/oggparsevorbis.c
+++ b/libavformat/oggparsevorbis.c
@@ -28,7 +28,9 @@
 #include "libavcodec/get_bits.h"
 #include "libavcodec/bytestream.h"
 #include "avformat.h"
+#include "internal.h"
 #include "oggdec.h"
+#include "vorbiscomment.h"
 
 static int ogm_chapter(AVFormatContext *as, uint8_t *key, uint8_t *val)
 {
@@ -137,6 +139,8 @@ ff_vorbis_comment(AVFormatContext * as, AVMetadata **m, const uint8_t *buf, int
         av_log(as, AV_LOG_INFO,
                "truncated comment header, %i comments not found\n", n);
 
+    ff_metadata_conv(m, NULL, ff_vorbiscomment_metadata_conv);
+
     return 0;
 }
 
@@ -206,12 +210,19 @@ vorbis_header (AVFormatContext * s, int idx)
         return -1;
 
     priv = os->private;
+
+    if (priv->packet[pkt_type>>1])
+        return -1;
+    if (pkt_type > 1 && !priv->packet[0] || pkt_type > 3 && !priv->packet[1])
+        return -1;
+
     priv->len[pkt_type >> 1] = os->psize;
     priv->packet[pkt_type >> 1] = av_mallocz(os->psize);
     memcpy(priv->packet[pkt_type >> 1], os->buf + os->pstart, os->psize);
     if (os->buf[os->pstart] == 1) {
         const uint8_t *p = os->buf + os->pstart + 7; /* skip "\001vorbis" tag */
         unsigned blocksize, bs0, bs1;
+        int srate;
 
         if (os->psize != 30)
             return -1;
@@ -220,7 +231,7 @@ vorbis_header (AVFormatContext * s, int idx)
             return -1;
 
         st->codec->channels = bytestream_get_byte(&p);
-        st->codec->sample_rate = bytestream_get_le32(&p);
+        srate = bytestream_get_le32(&p);
         p += 4; // skip maximum bitrate
         st->codec->bit_rate = bytestream_get_le32(&p); // nominal bitrate
         p += 4; // skip minimum bitrate
@@ -240,11 +251,21 @@ vorbis_header (AVFormatContext * s, int idx)
         st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
         st->codec->codec_id = CODEC_ID_VORBIS;
 
-        st->time_base.num = 1;
-        st->time_base.den = st->codec->sample_rate;
+        if (srate > 0) {
+            st->codec->sample_rate = srate;
+            av_set_pts_info(st, 64, 1, srate);
+        }
     } else if (os->buf[os->pstart] == 3) {
-        if (os->psize > 8)
-            ff_vorbis_comment (s, &st->metadata, os->buf + os->pstart + 7, os->psize - 8);
+        if (os->psize > 8 &&
+            ff_vorbis_comment(s, &st->metadata, os->buf + os->pstart + 7, os->psize - 8) >= 0) {
+            // drop all metadata we parsed and which is not required by libvorbis
+            unsigned new_len = 7 + 4 + AV_RL32(priv->packet[1] + 7) + 4 + 1;
+            if (new_len >= 16 && new_len < os->psize) {
+                AV_WL32(priv->packet[1] + new_len - 5, 0);
+                priv->packet[1][new_len - 1] = 1;
+                priv->len[1] = new_len;
+            }
+        }
     } else {
         st->codec->extradata_size =
             fixup_vorbis_headers(s, priv, &st->codec->extradata);
diff --git a/libavformat/oma.c b/libavformat/oma.c
index c12365e..ba8901d 100644
--- a/libavformat/oma.c
+++ b/libavformat/oma.c
@@ -4,20 +4,20 @@
  * Copyright (c) 2008 Maxim Poliakovski
  *               2008 Benjamin Larsson
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -27,7 +27,8 @@
  *
  * Known file extensions: ".oma", "aa3"
  * The format of such files consists of three parts:
- * - "ea3" header carrying overall info and metadata.
+ * - "ea3" header carrying overall info and metadata. Except for starting with
+ *   "ea" instead of "ID", it's an ID3v2 header.
  * - "EA3" header is a Sony-specific header containing information about
  *   the OpenMG file: codec type (usually ATRAC, can also be MP3 or WMA),
  *   codec specific info (packet size, sample rate, channels and so on)
@@ -44,8 +45,9 @@
 
 #include "avformat.h"
 #include "libavutil/intreadwrite.h"
-#include "raw.h"
+#include "pcm.h"
 #include "riff.h"
+#include "id3v2.h"
 
 #define EA3_HEADER_SIZE 96
 
@@ -63,36 +65,21 @@ static const AVCodecTag codec_oma_tags[] = {
     { CODEC_ID_MP3,     OMA_CODECID_MP3 },
 };
 
+#define ID3v2_EA3_MAGIC "ea3"
+
 static int oma_read_header(AVFormatContext *s,
                            AVFormatParameters *ap)
 {
     static const uint16_t srate_tab[6] = {320,441,480,882,960,0};
-    int     ret, ea3_taglen, EA3_pos, framesize, jsflag, samplerate;
+    int     ret, framesize, jsflag, samplerate;
     uint32_t codec_params;
     int16_t eid;
     uint8_t buf[EA3_HEADER_SIZE];
     uint8_t *edata;
     AVStream *st;
 
-    ret = get_buffer(s->pb, buf, 10);
-    if (ret != 10)
-        return -1;
-
-    if(!memcmp(buf, "ea3", 3)) {
-        ea3_taglen = ((buf[6] & 0x7f) << 21) | ((buf[7] & 0x7f) << 14) | ((buf[8] & 0x7f) << 7) | (buf[9] & 0x7f);
-
-        EA3_pos = ea3_taglen + 10;
-        if (buf[5] & 0x10)
-            EA3_pos += 10;
-
-        url_fseek(s->pb, EA3_pos, SEEK_SET);
-        ret = get_buffer(s->pb, buf, EA3_HEADER_SIZE);
-        if (ret != EA3_HEADER_SIZE)
-            return -1;
-    } else {
-        ret = get_buffer(s->pb, buf + 10, EA3_HEADER_SIZE - 10);
-        EA3_pos = 0;
-    }
+    ff_id3v2_read(s, ID3v2_EA3_MAGIC);
+    ret = avio_read(s->pb, buf, EA3_HEADER_SIZE);
 
     if (memcmp(buf, ((const uint8_t[]){'E', 'A', '3'}),3) || buf[4] != 0 || buf[5] != EA3_HEADER_SIZE) {
         av_log(s, AV_LOG_ERROR, "Couldn't find the EA3 header !\n");
@@ -163,7 +150,6 @@ static int oma_read_header(AVFormatContext *s,
     }
 
     st->codec->block_align = framesize;
-    url_fseek(s->pb, EA3_pos + EA3_HEADER_SIZE, SEEK_SET);
 
     return 0;
 }
@@ -182,16 +168,28 @@ static int oma_read_packet(AVFormatContext *s, AVPacket *pkt)
 
 static int oma_read_probe(AVProbeData *p)
 {
-    if (!memcmp(p->buf, ((const uint8_t[]){'e', 'a', '3', 3, 0}), 5) ||
-        (!memcmp(p->buf, "EA3", 3) &&
-         !p->buf[4] && p->buf[5] == EA3_HEADER_SIZE))
+    const uint8_t *buf;
+    unsigned tag_len = 0;
+
+    buf = p->buf;
+    /* version must be 3 and flags byte zero */
+    if (ff_id3v2_match(buf, ID3v2_EA3_MAGIC) && buf[3] == 3 && !buf[4])
+        tag_len = ff_id3v2_tag_len(buf);
+
+    // This check cannot overflow as tag_len has at most 28 bits
+    if (p->buf_size < tag_len + 5)
+        return 0;
+
+    buf += tag_len;
+
+    if (!memcmp(buf, "EA3", 3) && !buf[4] && buf[5] == EA3_HEADER_SIZE)
         return AVPROBE_SCORE_MAX;
     else
         return 0;
 }
 
 
-AVInputFormat oma_demuxer = {
+AVInputFormat ff_oma_demuxer = {
     "oma",
     NULL_IF_CONFIG_SMALL("Sony OpenMG audio"),
     0,
diff --git a/libavformat/options.c b/libavformat/options.c
index 0c1ac2d..beaafd8 100644
--- a/libavformat/options.c
+++ b/libavformat/options.c
@@ -1,24 +1,24 @@
 /*
  * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #include "avformat.h"
-#include "libavcodec/opt.h"
+#include "libavutil/opt.h"
 
 /**
  * @file
@@ -48,9 +48,9 @@ static const AVOption options[]={
 {"genpts", "generate pts", 0, FF_OPT_TYPE_CONST, AVFMT_FLAG_GENPTS, INT_MIN, INT_MAX, D, "fflags"},
 {"nofillin", "do not fill in missing values that can be exactly calculated", 0, FF_OPT_TYPE_CONST, AVFMT_FLAG_NOFILLIN, INT_MIN, INT_MAX, D, "fflags"},
 {"noparse", "disable AVParsers, this needs nofillin too", 0, FF_OPT_TYPE_CONST, AVFMT_FLAG_NOPARSE, INT_MIN, INT_MAX, D, "fflags"},
-{"igndts", "ingore dts", 0, FF_OPT_TYPE_CONST, AVFMT_FLAG_IGNDTS, INT_MIN, INT_MAX, D, "fflags"},
+{"igndts", "ignore dts", 0, FF_OPT_TYPE_CONST, AVFMT_FLAG_IGNDTS, INT_MIN, INT_MAX, D, "fflags"},
 {"rtphint", "add rtp hinting", 0, FF_OPT_TYPE_CONST, AVFMT_FLAG_RTP_HINT, INT_MIN, INT_MAX, E, "fflags"},
-#if LIBAVFORMAT_VERSION_INT < (53<<16)
+#if FF_API_OLD_METADATA
 {"track", " set the track number", OFFSET(track), FF_OPT_TYPE_INT, DEFAULT, 0, INT_MAX, E},
 {"year", "set the year", OFFSET(year), FF_OPT_TYPE_INT, DEFAULT, INT_MIN, INT_MAX, E},
 #endif
@@ -60,6 +60,7 @@ static const AVOption options[]={
 {"rtbufsize", "max memory used for buffering real-time frames", OFFSET(max_picture_buffer), FF_OPT_TYPE_INT, 3041280, 0, INT_MAX, D}, /* defaults to 1s of 15fps 352x288 YUYV422 video */
 {"fdebug", "print specific debug info", OFFSET(debug), FF_OPT_TYPE_FLAGS, DEFAULT, 0, INT_MAX, E|D, "fdebug"},
 {"ts", NULL, 0, FF_OPT_TYPE_CONST, FF_FDEBUG_TS, INT_MIN, INT_MAX, E|D, "fdebug"},
+{"max_delay", "maximum muxing or demuxing delay in microseconds", OFFSET(max_delay), FF_OPT_TYPE_INT, DEFAULT, 0, INT_MAX, E|D},
 {NULL},
 };
 
@@ -88,7 +89,7 @@ AVFormatContext *avformat_alloc_context(void)
     return ic;
 }
 
-#if LIBAVFORMAT_VERSION_MAJOR < 53
+#if FF_API_ALLOC_FORMAT_CONTEXT
 AVFormatContext *av_alloc_format_context(void)
 {
     return avformat_alloc_context();
diff --git a/libavformat/os_support.c b/libavformat/os_support.c
index 2786303..5a3a1bb 100644
--- a/libavformat/os_support.c
+++ b/libavformat/os_support.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
  * copyright (c) 2002 Francois Revol
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -26,13 +26,13 @@
 
 #include "config.h"
 #include "avformat.h"
-#include <unistd.h>
-#include <fcntl.h>
-#include <sys/time.h>
 #include "os_support.h"
 
 #if CONFIG_NETWORK
+#include <fcntl.h>
+#include <unistd.h>
 #if !HAVE_POLL_H
+#include <sys/time.h>
 #if HAVE_WINSOCK2_H
 #include <winsock2.h>
 #elif HAVE_SYS_SELECT_H
@@ -234,9 +234,7 @@ int ff_socket_nonblock(int socket, int enable)
       return fcntl(socket, F_SETFL, fcntl(socket, F_GETFL) & ~O_NONBLOCK);
 #endif
 }
-#endif /* CONFIG_NETWORK */
 
-#if CONFIG_FFSERVER
 #if !HAVE_POLL_H
 int poll(struct pollfd *fds, nfds_t numfds, int timeout)
 {
@@ -294,7 +292,7 @@ int poll(struct pollfd *fds, nfds_t numfds, int timeout)
     if (rc < 0)
         return rc;
 
-    for(i = 0; i < (nfds_t) n; i++) {
+    for(i = 0; i < numfds; i++) {
         fds[i].revents = 0;
 
         if (FD_ISSET(fds[i].fd, &read_set))      fds[i].revents |= POLLIN;
@@ -305,5 +303,4 @@ int poll(struct pollfd *fds, nfds_t numfds, int timeout)
     return rc;
 }
 #endif /* HAVE_POLL_H */
-#endif /* CONFIG_FFSERVER */
-
+#endif /* CONFIG_NETWORK */
diff --git a/libavformat/os_support.h b/libavformat/os_support.h
index e90f2c2..dc01e64 100644
--- a/libavformat/os_support.h
+++ b/libavformat/os_support.h
@@ -2,20 +2,20 @@
  * various utilities for ffmpeg system
  * copyright (c) 2000, 2001, 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -32,6 +32,8 @@
 #if defined(__MINGW32__) && !defined(__MINGW32CE__)
 #  include <fcntl.h>
 #  define lseek(f,p,w) _lseeki64((f), (p), (w))
+#  define stat _stati64
+#  define fstat(f,s) _fstati64((f), (s))
 #endif /* defined(__MINGW32__) && !defined(__MINGW32CE__) */
 
 static inline int is_dos_path(const char *path)
@@ -43,23 +45,6 @@ static inline int is_dos_path(const char *path)
     return 0;
 }
 
-#ifdef __BEOS__
-#  include <sys/socket.h>
-#  include <netinet/in.h>
-   /* not net_server ? */
-#  include <BeBuild.h>
-   /* R5 didn't have usleep, fake it. Haiku and Zeta has it now. */
-#  if B_BEOS_VERSION <= B_BEOS_VERSION_5
-#    include <OS.h>
-     /* doesn't set errno but that's enough */
-#    define usleep(t)  snooze((bigtime_t)(t))
-#  endif
-#  ifndef SA_RESTART
-#    warning SA_RESTART not implemented; ffserver might misbehave.
-#    define SA_RESTART 0
-#  endif
-#endif
-
 #if CONFIG_NETWORK
 #if !HAVE_SOCKLEN_T
 typedef int socklen_t;
@@ -70,7 +55,6 @@ typedef int socklen_t;
 #define closesocket close
 #endif
 
-#if CONFIG_FFSERVER
 #if !HAVE_POLL_H
 typedef unsigned long nfds_t;
 
@@ -97,7 +81,6 @@ struct pollfd {
 
 int poll(struct pollfd *fds, nfds_t numfds, int timeout);
 #endif /* HAVE_POLL_H */
-#endif /* CONFIG_FFSERVER */
 #endif /* CONFIG_NETWORK */
 
 #endif /* AVFORMAT_OS_SUPPORT_H */
diff --git a/libavformat/output-example.c b/libavformat/output-example.c
index dd61cfe..27db78c 100644
--- a/libavformat/output-example.c
+++ b/libavformat/output-example.c
@@ -68,6 +68,7 @@ static AVStream *add_audio_stream(AVFormatContext *oc, enum CodecID codec_id)
     c->codec_type = AVMEDIA_TYPE_AUDIO;
 
     /* put sample parameters */
+    c->sample_fmt = AV_SAMPLE_FMT_S16;
     c->bit_rate = 64000;
     c->sample_rate = 44100;
     c->channels = 2;
@@ -480,7 +481,7 @@ int main(int argc, char **argv)
         exit(1);
     }
 
-    dump_format(oc, 0, filename, 1);
+    av_dump_format(oc, 0, filename, 1);
 
     /* now that all the parameters are set, we can open the audio and
        video codecs and allocate the necessary encode buffers */
@@ -491,7 +492,7 @@ int main(int argc, char **argv)
 
     /* open the output file, if needed */
     if (!(fmt->flags & AVFMT_NOFILE)) {
-        if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
+        if (avio_open(&oc->pb, filename, AVIO_WRONLY) < 0) {
             fprintf(stderr, "Could not open '%s'\n", filename);
             exit(1);
         }
@@ -544,7 +545,7 @@ int main(int argc, char **argv)
 
     if (!(fmt->flags & AVFMT_NOFILE)) {
         /* close the output file */
-        url_fclose(oc->pb);
+        avio_close(oc->pb);
     }
 
     /* free the stream */
diff --git a/libavformat/pcm.c b/libavformat/pcm.c
new file mode 100644
index 0000000..26ab142
--- /dev/null
+++ b/libavformat/pcm.c
@@ -0,0 +1,55 @@
+/*
+ * PCM common functions
+ * Copyright (c) 2003 Fabrice Bellard
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "avformat.h"
+#include "pcm.h"
+
+int pcm_read_seek(AVFormatContext *s,
+                  int stream_index, int64_t timestamp, int flags)
+{
+    AVStream *st;
+    int block_align, byte_rate;
+    int64_t pos, ret;
+
+    st = s->streams[0];
+
+    block_align = st->codec->block_align ? st->codec->block_align :
+        (av_get_bits_per_sample(st->codec->codec_id) * st->codec->channels) >> 3;
+    byte_rate = st->codec->bit_rate ? st->codec->bit_rate >> 3 :
+        block_align * st->codec->sample_rate;
+
+    if (block_align <= 0 || byte_rate <= 0)
+        return -1;
+    if (timestamp < 0) timestamp = 0;
+
+    /* compute the position by aligning it to block_align */
+    pos = av_rescale_rnd(timestamp * byte_rate,
+                         st->time_base.num,
+                         st->time_base.den * (int64_t)block_align,
+                         (flags & AVSEEK_FLAG_BACKWARD) ? AV_ROUND_DOWN : AV_ROUND_UP);
+    pos *= block_align;
+
+    /* recompute exact position */
+    st->cur_dts = av_rescale(pos, st->time_base.den, byte_rate * (int64_t)st->time_base.num);
+    if ((ret = avio_seek(s->pb, pos + s->data_offset, SEEK_SET)) < 0)
+        return ret;
+    return 0;
+}
diff --git a/libavformat/pcm.h b/libavformat/pcm.h
new file mode 100644
index 0000000..228df13
--- /dev/null
+++ b/libavformat/pcm.h
@@ -0,0 +1,30 @@
+/*
+ * PCM common functions
+ * Copyright (C) 2007  Aurelien Jacobs <aurel at gnuage.org>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVFORMAT_PCM_H
+#define AVFORMAT_PCM_H
+
+#include "avformat.h"
+
+int pcm_read_seek(AVFormatContext *s,
+                  int stream_index, int64_t timestamp, int flags);
+
+#endif /* AVFORMAT_PCM_H */
diff --git a/libavformat/pcmdec.c b/libavformat/pcmdec.c
new file mode 100644
index 0000000..a5b8278
--- /dev/null
+++ b/libavformat/pcmdec.c
@@ -0,0 +1,122 @@
+/*
+ * RAW PCM demuxers
+ * Copyright (c) 2002 Fabrice Bellard
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "avformat.h"
+#include "rawdec.h"
+#include "pcm.h"
+
+#define RAW_SAMPLES     1024
+
+static int raw_read_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    int ret, size, bps;
+    //    AVStream *st = s->streams[0];
+
+    size= RAW_SAMPLES*s->streams[0]->codec->block_align;
+
+    ret= av_get_packet(s->pb, pkt, size);
+
+    pkt->stream_index = 0;
+    if (ret < 0)
+        return ret;
+
+    bps= av_get_bits_per_sample(s->streams[0]->codec->codec_id);
+    assert(bps); // if false there IS a bug elsewhere (NOT in this function)
+    pkt->dts=
+    pkt->pts= pkt->pos*8 / (bps * s->streams[0]->codec->channels);
+
+    return ret;
+}
+
+#define PCMDEF(name, long_name, ext, codec) \
+AVInputFormat ff_pcm_ ## name ## _demuxer = {\
+    #name,\
+    NULL_IF_CONFIG_SMALL(long_name),\
+    0,\
+    NULL,\
+    ff_raw_read_header,\
+    raw_read_packet,\
+    NULL,\
+    pcm_read_seek,\
+    .flags= AVFMT_GENERIC_INDEX,\
+    .extensions = ext,\
+    .value = codec,\
+};
+
+PCMDEF(f64be, "PCM 64 bit floating-point big-endian format",
+       NULL, CODEC_ID_PCM_F64BE)
+
+PCMDEF(f64le, "PCM 64 bit floating-point little-endian format",
+       NULL, CODEC_ID_PCM_F64LE)
+
+PCMDEF(f32be, "PCM 32 bit floating-point big-endian format",
+       NULL, CODEC_ID_PCM_F32BE)
+
+PCMDEF(f32le, "PCM 32 bit floating-point little-endian format",
+       NULL, CODEC_ID_PCM_F32LE)
+
+PCMDEF(s32be, "PCM signed 32 bit big-endian format",
+       NULL, CODEC_ID_PCM_S32BE)
+
+PCMDEF(s32le, "PCM signed 32 bit little-endian format",
+       NULL, CODEC_ID_PCM_S32LE)
+
+PCMDEF(s24be, "PCM signed 24 bit big-endian format",
+       NULL, CODEC_ID_PCM_S24BE)
+
+PCMDEF(s24le, "PCM signed 24 bit little-endian format",
+       NULL, CODEC_ID_PCM_S24LE)
+
+PCMDEF(s16be, "PCM signed 16 bit big-endian format",
+       AV_NE("sw", NULL), CODEC_ID_PCM_S16BE)
+
+PCMDEF(s16le, "PCM signed 16 bit little-endian format",
+       AV_NE(NULL, "sw"), CODEC_ID_PCM_S16LE)
+
+PCMDEF(s8, "PCM signed 8 bit format",
+       "sb", CODEC_ID_PCM_S8)
+
+PCMDEF(u32be, "PCM unsigned 32 bit big-endian format",
+       NULL, CODEC_ID_PCM_U32BE)
+
+PCMDEF(u32le, "PCM unsigned 32 bit little-endian format",
+       NULL, CODEC_ID_PCM_U32LE)
+
+PCMDEF(u24be, "PCM unsigned 24 bit big-endian format",
+       NULL, CODEC_ID_PCM_U24BE)
+
+PCMDEF(u24le, "PCM unsigned 24 bit little-endian format",
+       NULL, CODEC_ID_PCM_U24LE)
+
+PCMDEF(u16be, "PCM unsigned 16 bit big-endian format",
+       AV_NE("uw", NULL), CODEC_ID_PCM_U16BE)
+
+PCMDEF(u16le, "PCM unsigned 16 bit little-endian format",
+       AV_NE(NULL, "uw"), CODEC_ID_PCM_U16LE)
+
+PCMDEF(u8, "PCM unsigned 8 bit format",
+       "ub", CODEC_ID_PCM_U8)
+
+PCMDEF(alaw, "PCM A-law format",
+       "al", CODEC_ID_PCM_ALAW)
+
+PCMDEF(mulaw, "PCM mu-law format",
+       "ul", CODEC_ID_PCM_MULAW)
diff --git a/libavformat/pcmenc.c b/libavformat/pcmenc.c
new file mode 100644
index 0000000..928124e
--- /dev/null
+++ b/libavformat/pcmenc.c
@@ -0,0 +1,97 @@
+/*
+ * RAW PCM muxers
+ * Copyright (c) 2002 Fabrice Bellard
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "avformat.h"
+#include "rawenc.h"
+
+#define PCMDEF(name, long_name, ext, codec) \
+AVOutputFormat ff_pcm_ ## name ## _muxer = {\
+    #name,\
+    NULL_IF_CONFIG_SMALL(long_name),\
+    NULL,\
+    ext,\
+    0,\
+    codec,\
+    CODEC_ID_NONE,\
+    NULL,\
+    ff_raw_write_packet,\
+    .flags= AVFMT_NOTIMESTAMPS,\
+};
+
+PCMDEF(f64be, "PCM 64 bit floating-point big-endian format",
+       NULL, CODEC_ID_PCM_F64BE)
+
+PCMDEF(f64le, "PCM 64 bit floating-point little-endian format",
+       NULL, CODEC_ID_PCM_F64LE)
+
+PCMDEF(f32be, "PCM 32 bit floating-point big-endian format",
+       NULL, CODEC_ID_PCM_F32BE)
+
+PCMDEF(f32le, "PCM 32 bit floating-point little-endian format",
+       NULL, CODEC_ID_PCM_F32LE)
+
+PCMDEF(s32be, "PCM signed 32 bit big-endian format",
+       NULL, CODEC_ID_PCM_S32BE)
+
+PCMDEF(s32le, "PCM signed 32 bit little-endian format",
+       NULL, CODEC_ID_PCM_S32LE)
+
+PCMDEF(s24be, "PCM signed 24 bit big-endian format",
+       NULL, CODEC_ID_PCM_S24BE)
+
+PCMDEF(s24le, "PCM signed 24 bit little-endian format",
+       NULL, CODEC_ID_PCM_S24LE)
+
+PCMDEF(s16be, "PCM signed 16 bit big-endian format",
+       AV_NE("sw", NULL), CODEC_ID_PCM_S16BE)
+
+PCMDEF(s16le, "PCM signed 16 bit little-endian format",
+       AV_NE(NULL, "sw"), CODEC_ID_PCM_S16LE)
+
+PCMDEF(s8, "PCM signed 8 bit format",
+       "sb", CODEC_ID_PCM_S8)
+
+PCMDEF(u32be, "PCM unsigned 32 bit big-endian format",
+       NULL, CODEC_ID_PCM_U32BE)
+
+PCMDEF(u32le, "PCM unsigned 32 bit little-endian format",
+       NULL, CODEC_ID_PCM_U32LE)
+
+PCMDEF(u24be, "PCM unsigned 24 bit big-endian format",
+       NULL, CODEC_ID_PCM_U24BE)
+
+PCMDEF(u24le, "PCM unsigned 24 bit little-endian format",
+       NULL, CODEC_ID_PCM_U24LE)
+
+PCMDEF(u16be, "PCM unsigned 16 bit big-endian format",
+       AV_NE("uw", NULL), CODEC_ID_PCM_U16BE)
+
+PCMDEF(u16le, "PCM unsigned 16 bit little-endian format",
+       AV_NE(NULL, "uw"), CODEC_ID_PCM_U16LE)
+
+PCMDEF(u8, "PCM unsigned 8 bit format",
+       "ub", CODEC_ID_PCM_U8)
+
+PCMDEF(alaw, "PCM A-law format",
+       "al", CODEC_ID_PCM_ALAW)
+
+PCMDEF(mulaw, "PCM mu-law format",
+       "ul", CODEC_ID_PCM_MULAW)
diff --git a/libavformat/psxstr.c b/libavformat/psxstr.c
index 347c26e..b7a9d3b 100644
--- a/libavformat/psxstr.c
+++ b/libavformat/psxstr.c
@@ -2,20 +2,20 @@
  * Sony Playstation (PSX) STR File Demuxer
  * Copyright (c) 2003 The ffmpeg Project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -98,21 +98,21 @@ static int str_probe(AVProbeData *p)
 static int str_read_header(AVFormatContext *s,
                            AVFormatParameters *ap)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     StrDemuxContext *str = s->priv_data;
     unsigned char sector[RAW_CD_SECTOR_SIZE];
     int start;
     int i;
 
     /* skip over any RIFF header */
-    if (get_buffer(pb, sector, RIFF_HEADER_SIZE) != RIFF_HEADER_SIZE)
+    if (avio_read(pb, sector, RIFF_HEADER_SIZE) != RIFF_HEADER_SIZE)
         return AVERROR(EIO);
     if (AV_RL32(&sector[0]) == RIFF_TAG)
         start = RIFF_HEADER_SIZE;
     else
         start = 0;
 
-    url_fseek(pb, start, SEEK_SET);
+    avio_seek(pb, start, SEEK_SET);
 
     for(i=0; i<32; i++){
         str->channels[i].video_stream_index=
@@ -127,7 +127,7 @@ static int str_read_header(AVFormatContext *s,
 static int str_read_packet(AVFormatContext *s,
                            AVPacket *ret_pkt)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     StrDemuxContext *str = s->priv_data;
     unsigned char sector[RAW_CD_SECTOR_SIZE];
     int channel;
@@ -136,7 +136,7 @@ static int str_read_packet(AVFormatContext *s,
 
     while (1) {
 
-        if (get_buffer(pb, sector, RAW_CD_SECTOR_SIZE) != RAW_CD_SECTOR_SIZE)
+        if (avio_read(pb, sector, RAW_CD_SECTOR_SIZE) != RAW_CD_SECTOR_SIZE)
             return AVERROR(EIO);
 
         channel = sector[0x11];
@@ -186,7 +186,7 @@ static int str_read_packet(AVFormatContext *s,
                     if (av_new_packet(pkt, sector_count*VIDEO_DATA_CHUNK_SIZE))
                         return AVERROR(EIO);
 
-                    pkt->pos= url_ftell(pb) - RAW_CD_SECTOR_SIZE;
+                    pkt->pos= avio_tell(pb) - RAW_CD_SECTOR_SIZE;
                     pkt->stream_index =
                         str->channels[channel].video_stream_index;
                 }
@@ -241,7 +241,7 @@ static int str_read_packet(AVFormatContext *s,
             break;
         }
 
-        if (url_feof(pb))
+        if (pb->eof_reached)
             return AVERROR(EIO);
     }
 }
@@ -258,7 +258,7 @@ static int str_read_close(AVFormatContext *s)
     return 0;
 }
 
-AVInputFormat str_demuxer = {
+AVInputFormat ff_str_demuxer = {
     "psxstr",
     NULL_IF_CONFIG_SMALL("Sony Playstation STR format"),
     sizeof(StrDemuxContext),
diff --git a/libavformat/pva.c b/libavformat/pva.c
index abbc6f1..79b959c 100644
--- a/libavformat/pva.c
+++ b/libavformat/pva.c
@@ -2,20 +2,20 @@
  * TechnoTrend PVA (.pva) demuxer
  * Copyright (c) 2007, 2008 Ivo van Poorten
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -67,20 +67,20 @@ static int pva_read_header(AVFormatContext *s, AVFormatParameters *ap) {
 
 static int read_part_of_packet(AVFormatContext *s, int64_t *pts,
                                int *len, int *strid, int read_packet) {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     PVAContext *pvactx = s->priv_data;
     int syncword, streamid, reserved, flags, length, pts_flag;
     int64_t pva_pts = AV_NOPTS_VALUE, startpos;
 
 recover:
-    startpos = url_ftell(pb);
+    startpos = avio_tell(pb);
 
-    syncword = get_be16(pb);
-    streamid = get_byte(pb);
-    get_byte(pb);               /* counter not used */
-    reserved = get_byte(pb);
-    flags    = get_byte(pb);
-    length   = get_be16(pb);
+    syncword = avio_rb16(pb);
+    streamid = avio_r8(pb);
+    avio_r8(pb);               /* counter not used */
+    reserved = avio_r8(pb);
+    flags    = avio_r8(pb);
+    length   = avio_rb16(pb);
 
     pts_flag = flags & 0x10;
 
@@ -101,7 +101,7 @@ recover:
     }
 
     if (streamid == PVA_VIDEO_PAYLOAD && pts_flag) {
-        pva_pts = get_be32(pb);
+        pva_pts = avio_rb32(pb);
         length -= 4;
     } else if (streamid == PVA_AUDIO_PAYLOAD) {
         /* PVA Audio Packets either start with a signaled PES packet or
@@ -113,22 +113,22 @@ recover:
                 pes_flags;
             unsigned char pes_header_data[256];
 
-            pes_signal             = get_be24(pb);
-            get_byte(pb);
-            pes_packet_length      = get_be16(pb);
-            pes_flags              = get_be16(pb);
-            pes_header_data_length = get_byte(pb);
+            pes_signal             = avio_rb24(pb);
+            avio_r8(pb);
+            pes_packet_length      = avio_rb16(pb);
+            pes_flags              = avio_rb16(pb);
+            pes_header_data_length = avio_r8(pb);
 
             if (pes_signal != 1) {
                 pva_log(s, AV_LOG_WARNING, "expected signaled PES packet, "
                                           "trying to recover\n");
-                url_fskip(pb, length - 9);
+                avio_skip(pb, length - 9);
                 if (!read_packet)
                     return AVERROR(EIO);
                 goto recover;
             }
 
-            get_buffer(pb, pes_header_data, pes_header_data_length);
+            avio_read(pb, pes_header_data, pes_header_data_length);
             length -= 9 + pes_header_data_length;
 
             pes_packet_length -= 3 + pes_header_data_length;
@@ -157,7 +157,7 @@ recover:
 }
 
 static int pva_read_packet(AVFormatContext *s, AVPacket *pkt) {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int64_t pva_pts;
     int ret, length, streamid;
 
@@ -173,7 +173,7 @@ static int pva_read_packet(AVFormatContext *s, AVPacket *pkt) {
 
 static int64_t pva_read_timestamp(struct AVFormatContext *s, int stream_index,
                                           int64_t *pos, int64_t pos_limit) {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     PVAContext *pvactx = s->priv_data;
     int length, streamid;
     int64_t res = AV_NOPTS_VALUE;
@@ -182,7 +182,7 @@ static int64_t pva_read_timestamp(struct AVFormatContext *s, int stream_index,
 
     while (*pos < pos_limit) {
         res = AV_NOPTS_VALUE;
-        url_fseek(pb, *pos, SEEK_SET);
+        avio_seek(pb, *pos, SEEK_SET);
 
         pvactx->continue_pes = 0;
         if (read_part_of_packet(s, &res, &length, &streamid, 0)) {
@@ -190,7 +190,7 @@ static int64_t pva_read_timestamp(struct AVFormatContext *s, int stream_index,
             continue;
         }
         if (streamid - 1 != stream_index || res == AV_NOPTS_VALUE) {
-            *pos = url_ftell(pb) + length;
+            *pos = avio_tell(pb) + length;
             continue;
         }
         break;
@@ -200,7 +200,7 @@ static int64_t pva_read_timestamp(struct AVFormatContext *s, int stream_index,
     return res;
 }
 
-AVInputFormat pva_demuxer = {
+AVInputFormat ff_pva_demuxer = {
     "pva",
     NULL_IF_CONFIG_SMALL("TechnoTrend PVA file and stream format"),
     sizeof(PVAContext),
diff --git a/libavformat/qcp.c b/libavformat/qcp.c
index 676e9c7..635d531 100644
--- a/libavformat/qcp.c
+++ b/libavformat/qcp.c
@@ -2,20 +2,20 @@
  * QCP format (.qcp) demuxer
  * Copyright (c) 2009 Kenan Gillet
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -82,7 +82,7 @@ static int qcp_probe(AVProbeData *pd)
 
 static int qcp_read_header(AVFormatContext *s, AVFormatParameters *ap)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     QCPContext    *c  = s->priv_data;
     AVStream      *st = av_new_stream(s, 0);
     uint8_t       buf[16];
@@ -91,13 +91,13 @@ static int qcp_read_header(AVFormatContext *s, AVFormatParameters *ap)
     if (!st)
         return AVERROR(ENOMEM);
 
-    get_be32(pb);                    // "RIFF"
-    s->file_size = get_le32(pb) + 8;
-    url_fskip(pb, 8 + 4 + 1 + 1);    // "QLCMfmt " + chunk-size + major-version + minor-version
+    avio_rb32(pb);                    // "RIFF"
+    s->file_size = avio_rl32(pb) + 8;
+    avio_skip(pb, 8 + 4 + 1 + 1);    // "QLCMfmt " + chunk-size + major-version + minor-version
 
     st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
     st->codec->channels   = 1;
-    get_buffer(pb, buf, 16);
+    avio_read(pb, buf, 16);
     if (is_qcelp_13k_guid(buf)) {
         st->codec->codec_id = CODEC_ID_QCELP;
     } else if (!memcmp(buf, guid_evrc, 16)) {
@@ -110,39 +110,39 @@ static int qcp_read_header(AVFormatContext *s, AVFormatParameters *ap)
         av_log(s, AV_LOG_ERROR, "Unknown codec GUID.\n");
         return AVERROR_INVALIDDATA;
     }
-    url_fskip(pb, 2 + 80); // codec-version + codec-name
-    st->codec->bit_rate = get_le16(pb);
+    avio_skip(pb, 2 + 80); // codec-version + codec-name
+    st->codec->bit_rate = avio_rl16(pb);
 
-    s->packet_size = get_le16(pb);
-    url_fskip(pb, 2); // block-size
-    st->codec->sample_rate = get_le16(pb);
-    url_fskip(pb, 2); // sample-size
+    s->packet_size = avio_rl16(pb);
+    avio_skip(pb, 2); // block-size
+    st->codec->sample_rate = avio_rl16(pb);
+    avio_skip(pb, 2); // sample-size
 
     memset(c->rates_per_mode, -1, sizeof(c->rates_per_mode));
-    nb_rates = get_le32(pb);
+    nb_rates = avio_rl32(pb);
     nb_rates = FFMIN(nb_rates, 8);
     for (i=0; i<nb_rates; i++) {
-        int size = get_byte(pb);
-        int mode = get_byte(pb);
+        int size = avio_r8(pb);
+        int mode = avio_r8(pb);
         if (mode > QCP_MAX_MODE) {
             av_log(s, AV_LOG_WARNING, "Unknown entry %d=>%d in rate-map-table.\n ", mode, size);
         } else
             c->rates_per_mode[mode] = size;
     }
-    url_fskip(pb, 16 - 2*nb_rates + 20); // empty entries of rate-map-table + reserved
+    avio_skip(pb, 16 - 2*nb_rates + 20); // empty entries of rate-map-table + reserved
 
     return 0;
 }
 
 static int qcp_read_packet(AVFormatContext *s, AVPacket *pkt)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     QCPContext    *c  = s->priv_data;
     unsigned int  chunk_size, tag;
 
-    while(!url_feof(pb)) {
+    while(!pb->eof_reached) {
         if (c->data_size) {
-            int pkt_size, ret, mode = get_byte(pb);
+            int pkt_size, ret, mode = avio_r8(pb);
 
             if (s->packet_size) {
                 pkt_size = s->packet_size - 1;
@@ -165,29 +165,29 @@ static int qcp_read_packet(AVFormatContext *s, AVPacket *pkt)
             return ret;
         }
 
-        if (url_ftell(pb) & 1 && get_byte(pb))
+        if (avio_tell(pb) & 1 && avio_r8(pb))
             av_log(s, AV_LOG_WARNING, "Padding should be 0.\n");
 
-        tag        = get_le32(pb);
-        chunk_size = get_le32(pb);
+        tag        = avio_rl32(pb);
+        chunk_size = avio_rl32(pb);
         switch (tag) {
         case MKTAG('v', 'r', 'a', 't'):
-            if (get_le32(pb)) // var-rate-flag
+            if (avio_rl32(pb)) // var-rate-flag
                 s->packet_size = 0;
-            url_fskip(pb, 4); // size-in-packets
+            avio_skip(pb, 4); // size-in-packets
             break;
         case MKTAG('d', 'a', 't', 'a'):
             c->data_size = chunk_size;
             break;
 
         default:
-            url_fskip(pb, chunk_size);
+            avio_skip(pb, chunk_size);
         }
     }
     return AVERROR_EOF;
 }
 
-AVInputFormat qcp_demuxer = {
+AVInputFormat ff_qcp_demuxer = {
     .name           = "qcp",
     .long_name      = NULL_IF_CONFIG_SMALL("QCP format"),
     .priv_data_size = sizeof(QCPContext),
diff --git a/libavformat/qtpalette.h b/libavformat/qtpalette.h
index 7d6802f..ecc85d3 100644
--- a/libavformat/qtpalette.h
+++ b/libavformat/qtpalette.h
@@ -3,20 +3,20 @@
  *  Automatically generated from a utility derived from XAnim:
  *  http://xanim.va.pubnix.com/home.html
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavformat/r3d.c b/libavformat/r3d.c
index 556a32b..e815fda 100644
--- a/libavformat/r3d.c
+++ b/libavformat/r3d.c
@@ -2,20 +2,20 @@
  * R3D REDCODE demuxer
  * Copyright (c) 2008 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -38,12 +38,12 @@ typedef struct {
 
 static int read_atom(AVFormatContext *s, Atom *atom)
 {
-    atom->offset = url_ftell(s->pb);
-    atom->size = get_be32(s->pb);
+    atom->offset = avio_tell(s->pb);
+    atom->size = avio_rb32(s->pb);
     if (atom->size < 8)
         return -1;
-    atom->tag = get_le32(s->pb);
-    dprintf(s, "atom %d %.4s offset %#llx\n",
+    atom->tag = avio_rl32(s->pb);
+    av_dlog(s, "atom %d %.4s offset %#llx\n",
             atom->size, (char*)&atom->tag, atom->offset);
     return atom->size;
 }
@@ -59,32 +59,32 @@ static int r3d_read_red1(AVFormatContext *s)
     st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
     st->codec->codec_id = CODEC_ID_JPEG2000;
 
-    tmp  = get_byte(s->pb); // major version
-    tmp2 = get_byte(s->pb); // minor version
-    dprintf(s, "version %d.%d\n", tmp, tmp2);
+    tmp  = avio_r8(s->pb); // major version
+    tmp2 = avio_r8(s->pb); // minor version
+    av_dlog(s, "version %d.%d\n", tmp, tmp2);
 
-    tmp = get_be16(s->pb); // unknown
-    dprintf(s, "unknown1 %d\n", tmp);
+    tmp = avio_rb16(s->pb); // unknown
+    av_dlog(s, "unknown1 %d\n", tmp);
 
-    tmp = get_be32(s->pb);
+    tmp = avio_rb32(s->pb);
     av_set_pts_info(st, 32, 1, tmp);
 
-    tmp = get_be32(s->pb); // filenum
-    dprintf(s, "filenum %d\n", tmp);
+    tmp = avio_rb32(s->pb); // filenum
+    av_dlog(s, "filenum %d\n", tmp);
 
-    url_fskip(s->pb, 32); // unknown
+    avio_skip(s->pb, 32); // unknown
 
-    st->codec->width  = get_be32(s->pb);
-    st->codec->height = get_be32(s->pb);
+    st->codec->width  = avio_rb32(s->pb);
+    st->codec->height = avio_rb32(s->pb);
 
-    tmp = get_be16(s->pb); // unknown
-    dprintf(s, "unknown2 %d\n", tmp);
+    tmp = avio_rb16(s->pb); // unknown
+    av_dlog(s, "unknown2 %d\n", tmp);
 
-    st->codec->time_base.den = get_be16(s->pb);
-    st->codec->time_base.num = get_be16(s->pb);
+    st->codec->time_base.den = avio_rb16(s->pb);
+    st->codec->time_base.num = avio_rb16(s->pb);
 
-    tmp = get_byte(s->pb); // audio channels
-    dprintf(s, "audio channels %d\n", tmp);
+    tmp = avio_r8(s->pb); // audio channels
+    av_dlog(s, "audio channels %d\n", tmp);
     if (tmp > 0) {
         AVStream *ast = av_new_stream(s, 1);
         if (!ast)
@@ -95,14 +95,14 @@ static int r3d_read_red1(AVFormatContext *s)
         av_set_pts_info(ast, 32, 1, st->time_base.den);
     }
 
-    get_buffer(s->pb, filename, 257);
+    avio_read(s->pb, filename, 257);
     filename[sizeof(filename)-1] = 0;
     av_metadata_set2(&st->metadata, "filename", filename, 0);
 
-    dprintf(s, "filename %s\n", filename);
-    dprintf(s, "resolution %dx%d\n", st->codec->width, st->codec->height);
-    dprintf(s, "timescale %d\n", st->time_base.den);
-    dprintf(s, "frame rate %d/%d\n",
+    av_dlog(s, "filename %s\n", filename);
+    av_dlog(s, "resolution %dx%d\n", st->codec->width, st->codec->height);
+    av_dlog(s, "timescale %d\n", st->time_base.den);
+    av_dlog(s, "frame rate %d/%d\n",
             st->codec->time_base.num, st->codec->time_base.den);
 
     return 0;
@@ -120,18 +120,18 @@ static int r3d_read_rdvo(AVFormatContext *s, Atom *atom)
         return AVERROR(ENOMEM);
 
     for (i = 0; i < r3d->video_offsets_count; i++) {
-        r3d->video_offsets[i] = get_be32(s->pb);
+        r3d->video_offsets[i] = avio_rb32(s->pb);
         if (!r3d->video_offsets[i]) {
             r3d->video_offsets_count = i;
             break;
         }
-        dprintf(s, "video offset %d: %#x\n", i, r3d->video_offsets[i]);
+        av_dlog(s, "video offset %d: %#x\n", i, r3d->video_offsets[i]);
     }
 
     if (st->codec->time_base.den)
         st->duration = (uint64_t)r3d->video_offsets_count*
             st->time_base.den*st->codec->time_base.num/st->codec->time_base.den;
-    dprintf(s, "duration %lld\n", st->duration);
+    av_dlog(s, "duration %lld\n", st->duration);
 
     return 0;
 }
@@ -141,18 +141,18 @@ static void r3d_read_reos(AVFormatContext *s)
     R3DContext *r3d = s->priv_data;
     int tmp;
 
-    r3d->rdvo_offset = get_be32(s->pb);
-    get_be32(s->pb); // rdvs offset
-    get_be32(s->pb); // rdao offset
-    get_be32(s->pb); // rdas offset
+    r3d->rdvo_offset = avio_rb32(s->pb);
+    avio_rb32(s->pb); // rdvs offset
+    avio_rb32(s->pb); // rdao offset
+    avio_rb32(s->pb); // rdas offset
 
-    tmp = get_be32(s->pb);
-    dprintf(s, "num video chunks %d\n", tmp);
+    tmp = avio_rb32(s->pb);
+    av_dlog(s, "num video chunks %d\n", tmp);
 
-    tmp = get_be32(s->pb);
-    dprintf(s, "num audio chunks %d\n", tmp);
+    tmp = avio_rb32(s->pb);
+    av_dlog(s, "num audio chunks %d\n", tmp);
 
-    url_fskip(s->pb, 6*4);
+    avio_skip(s->pb, 6*4);
 }
 
 static int r3d_read_header(AVFormatContext *s, AVFormatParameters *ap)
@@ -175,12 +175,12 @@ static int r3d_read_header(AVFormatContext *s, AVFormatParameters *ap)
         return -1;
     }
 
-    s->data_offset = url_ftell(s->pb);
-    dprintf(s, "data offset %#llx\n", s->data_offset);
-    if (url_is_streamed(s->pb))
+    s->data_offset = avio_tell(s->pb);
+    av_dlog(s, "data offset %#llx\n", s->data_offset);
+    if (!s->pb->seekable)
         return 0;
     // find REOB/REOF/REOS to load index
-    url_fseek(s->pb, url_fsize(s->pb)-48-8, SEEK_SET);
+    avio_seek(s->pb, avio_size(s->pb)-48-8, SEEK_SET);
     if (read_atom(s, &atom) < 0)
         av_log(s, AV_LOG_ERROR, "error reading end atom\n");
 
@@ -192,7 +192,7 @@ static int r3d_read_header(AVFormatContext *s, AVFormatParameters *ap)
     r3d_read_reos(s);
 
     if (r3d->rdvo_offset) {
-        url_fseek(s->pb, r3d->rdvo_offset, SEEK_SET);
+        avio_seek(s->pb, r3d->rdvo_offset, SEEK_SET);
         if (read_atom(s, &atom) < 0)
             av_log(s, AV_LOG_ERROR, "error reading 'rdvo' atom\n");
         if (atom.tag == MKTAG('R','D','V','O')) {
@@ -202,7 +202,7 @@ static int r3d_read_header(AVFormatContext *s, AVFormatParameters *ap)
     }
 
  out:
-    url_fseek(s->pb, s->data_offset, SEEK_SET);
+    avio_seek(s->pb, s->data_offset, SEEK_SET);
     return 0;
 }
 
@@ -210,38 +210,38 @@ static int r3d_read_redv(AVFormatContext *s, AVPacket *pkt, Atom *atom)
 {
     AVStream *st = s->streams[0];
     int tmp, tmp2;
-    uint64_t pos = url_ftell(s->pb);
+    uint64_t pos = avio_tell(s->pb);
     unsigned dts;
     int ret;
 
-    dts = get_be32(s->pb);
+    dts = avio_rb32(s->pb);
 
-    tmp = get_be32(s->pb);
-    dprintf(s, "frame num %d\n", tmp);
+    tmp = avio_rb32(s->pb);
+    av_dlog(s, "frame num %d\n", tmp);
 
-    tmp  = get_byte(s->pb); // major version
-    tmp2 = get_byte(s->pb); // minor version
-    dprintf(s, "version %d.%d\n", tmp, tmp2);
+    tmp  = avio_r8(s->pb); // major version
+    tmp2 = avio_r8(s->pb); // minor version
+    av_dlog(s, "version %d.%d\n", tmp, tmp2);
 
-    tmp = get_be16(s->pb); // unknown
-    dprintf(s, "unknown %d\n", tmp);
+    tmp = avio_rb16(s->pb); // unknown
+    av_dlog(s, "unknown %d\n", tmp);
 
     if (tmp > 4) {
-        tmp = get_be16(s->pb); // unknown
-        dprintf(s, "unknown %d\n", tmp);
+        tmp = avio_rb16(s->pb); // unknown
+        av_dlog(s, "unknown %d\n", tmp);
 
-        tmp = get_be16(s->pb); // unknown
-        dprintf(s, "unknown %d\n", tmp);
+        tmp = avio_rb16(s->pb); // unknown
+        av_dlog(s, "unknown %d\n", tmp);
 
-        tmp = get_be32(s->pb);
-        dprintf(s, "width %d\n", tmp);
-        tmp = get_be32(s->pb);
-        dprintf(s, "height %d\n", tmp);
+        tmp = avio_rb32(s->pb);
+        av_dlog(s, "width %d\n", tmp);
+        tmp = avio_rb32(s->pb);
+        av_dlog(s, "height %d\n", tmp);
 
-        tmp = get_be32(s->pb);
-        dprintf(s, "metadata len %d\n", tmp);
+        tmp = avio_rb32(s->pb);
+        av_dlog(s, "metadata len %d\n", tmp);
     }
-    tmp = atom->size - 8 - (url_ftell(s->pb) - pos);
+    tmp = atom->size - 8 - (avio_tell(s->pb) - pos);
     if (tmp < 0)
         return -1;
     ret = av_get_packet(s->pb, pkt, tmp);
@@ -255,7 +255,7 @@ static int r3d_read_redv(AVFormatContext *s, AVPacket *pkt, Atom *atom)
     if (st->codec->time_base.den)
         pkt->duration = (uint64_t)st->time_base.den*
             st->codec->time_base.num/st->codec->time_base.den;
-    dprintf(s, "pkt dts %lld duration %d\n", pkt->dts, pkt->duration);
+    av_dlog(s, "pkt dts %lld duration %d\n", pkt->dts, pkt->duration);
 
     return 0;
 }
@@ -264,30 +264,30 @@ static int r3d_read_reda(AVFormatContext *s, AVPacket *pkt, Atom *atom)
 {
     AVStream *st = s->streams[1];
     int tmp, tmp2, samples, size;
-    uint64_t pos = url_ftell(s->pb);
+    uint64_t pos = avio_tell(s->pb);
     unsigned dts;
     int ret;
 
-    dts = get_be32(s->pb);
+    dts = avio_rb32(s->pb);
 
-    st->codec->sample_rate = get_be32(s->pb);
+    st->codec->sample_rate = avio_rb32(s->pb);
 
-    samples = get_be32(s->pb);
+    samples = avio_rb32(s->pb);
 
-    tmp = get_be32(s->pb);
-    dprintf(s, "packet num %d\n", tmp);
+    tmp = avio_rb32(s->pb);
+    av_dlog(s, "packet num %d\n", tmp);
 
-    tmp = get_be16(s->pb); // unkown
-    dprintf(s, "unknown %d\n", tmp);
+    tmp = avio_rb16(s->pb); // unkown
+    av_dlog(s, "unknown %d\n", tmp);
 
-    tmp  = get_byte(s->pb); // major version
-    tmp2 = get_byte(s->pb); // minor version
-    dprintf(s, "version %d.%d\n", tmp, tmp2);
+    tmp  = avio_r8(s->pb); // major version
+    tmp2 = avio_r8(s->pb); // minor version
+    av_dlog(s, "version %d.%d\n", tmp, tmp2);
 
-    tmp = get_be32(s->pb); // unknown
-    dprintf(s, "unknown %d\n", tmp);
+    tmp = avio_rb32(s->pb); // unknown
+    av_dlog(s, "unknown %d\n", tmp);
 
-    size = atom->size - 8 - (url_ftell(s->pb) - pos);
+    size = atom->size - 8 - (avio_tell(s->pb) - pos);
     if (size < 0)
         return -1;
     ret = av_get_packet(s->pb, pkt, size);
@@ -299,7 +299,7 @@ static int r3d_read_reda(AVFormatContext *s, AVPacket *pkt, Atom *atom)
     pkt->stream_index = 1;
     pkt->dts = dts;
     pkt->duration = av_rescale(samples, st->time_base.den, st->codec->sample_rate);
-    dprintf(s, "pkt dts %lld duration %d samples %d sample rate %d\n",
+    av_dlog(s, "pkt dts %lld duration %d samples %d sample rate %d\n",
             pkt->dts, pkt->duration, samples, st->codec->sample_rate);
 
     return 0;
@@ -332,7 +332,7 @@ static int r3d_read_packet(AVFormatContext *s, AVPacket *pkt)
             break;
         default:
         skip:
-            url_fskip(s->pb, atom.size-8);
+            avio_skip(s->pb, atom.size-8);
         }
     }
     return err;
@@ -356,10 +356,10 @@ static int r3d_seek(AVFormatContext *s, int stream_index, int64_t sample_time, i
 
     frame_num = sample_time*st->codec->time_base.den/
         ((int64_t)st->codec->time_base.num*st->time_base.den);
-    dprintf(s, "seek frame num %d timestamp %lld\n", frame_num, sample_time);
+    av_dlog(s, "seek frame num %d timestamp %lld\n", frame_num, sample_time);
 
     if (frame_num < r3d->video_offsets_count) {
-        url_fseek(s->pb, r3d->video_offsets_count, SEEK_SET);
+        avio_seek(s->pb, r3d->video_offsets_count, SEEK_SET);
     } else {
         av_log(s, AV_LOG_ERROR, "could not seek to frame %d\n", frame_num);
         return -1;
@@ -377,7 +377,7 @@ static int r3d_close(AVFormatContext *s)
     return 0;
 }
 
-AVInputFormat r3d_demuxer = {
+AVInputFormat ff_r3d_demuxer = {
     "r3d",
     NULL_IF_CONFIG_SMALL("REDCODE R3D format"),
     sizeof(R3DContext),
diff --git a/libavformat/raw.c b/libavformat/raw.c
deleted file mode 100644
index 7837de8..0000000
--- a/libavformat/raw.c
+++ /dev/null
@@ -1,1363 +0,0 @@
-/*
- * RAW muxer and demuxer
- * Copyright (c) 2001 Fabrice Bellard
- * Copyright (c) 2005 Alex Beregszaszi
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-#include "libavutil/crc.h"
-#include "libavcodec/ac3_parser.h"
-#include "libavcodec/get_bits.h"
-#include "libavcodec/bytestream.h"
-#include "avformat.h"
-#include "raw.h"
-#include "id3v2.h"
-#include "id3v1.h"
-
-/* simple formats */
-
-#if CONFIG_ROQ_MUXER
-static int roq_write_header(struct AVFormatContext *s)
-{
-    static const uint8_t header[] = {
-        0x84, 0x10, 0xFF, 0xFF, 0xFF, 0xFF, 0x1E, 0x00
-    };
-
-    put_buffer(s->pb, header, 8);
-    put_flush_packet(s->pb);
-
-    return 0;
-}
-#endif
-
-#if CONFIG_NULL_MUXER
-static int null_write_packet(struct AVFormatContext *s, AVPacket *pkt)
-{
-    return 0;
-}
-#endif
-
-#if CONFIG_MUXERS
-static int raw_write_packet(struct AVFormatContext *s, AVPacket *pkt)
-{
-    put_buffer(s->pb, pkt->data, pkt->size);
-    put_flush_packet(s->pb);
-    return 0;
-}
-#endif
-
-#if CONFIG_DEMUXERS
-/* raw input */
-static int raw_read_header(AVFormatContext *s, AVFormatParameters *ap)
-{
-    AVStream *st;
-    enum CodecID id;
-
-    st = av_new_stream(s, 0);
-    if (!st)
-        return AVERROR(ENOMEM);
-
-        id = s->iformat->value;
-        if (id == CODEC_ID_RAWVIDEO) {
-            st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
-        } else {
-            st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
-        }
-        st->codec->codec_id = id;
-
-        switch(st->codec->codec_type) {
-        case AVMEDIA_TYPE_AUDIO:
-            st->codec->sample_rate = ap->sample_rate;
-            if(ap->channels) st->codec->channels = ap->channels;
-            else             st->codec->channels = 1;
-            st->codec->bits_per_coded_sample = av_get_bits_per_sample(st->codec->codec_id);
-            assert(st->codec->bits_per_coded_sample > 0);
-            st->codec->block_align = st->codec->bits_per_coded_sample*st->codec->channels/8;
-            av_set_pts_info(st, 64, 1, st->codec->sample_rate);
-            break;
-        case AVMEDIA_TYPE_VIDEO:
-            if(ap->time_base.num)
-                av_set_pts_info(st, 64, ap->time_base.num, ap->time_base.den);
-            else
-                av_set_pts_info(st, 64, 1, 25);
-            st->codec->width = ap->width;
-            st->codec->height = ap->height;
-            st->codec->pix_fmt = ap->pix_fmt;
-            if(st->codec->pix_fmt == PIX_FMT_NONE)
-                st->codec->pix_fmt= PIX_FMT_YUV420P;
-            break;
-        default:
-            return -1;
-        }
-    return 0;
-}
-
-#define RAW_PACKET_SIZE 1024
-#define RAW_SAMPLES     1024
-
-static int raw_read_packet(AVFormatContext *s, AVPacket *pkt)
-{
-    int ret, size, bps;
-    //    AVStream *st = s->streams[0];
-
-    size= RAW_SAMPLES*s->streams[0]->codec->block_align;
-
-    ret= av_get_packet(s->pb, pkt, size);
-
-    pkt->stream_index = 0;
-    if (ret < 0)
-        return ret;
-
-    bps= av_get_bits_per_sample(s->streams[0]->codec->codec_id);
-    assert(bps); // if false there IS a bug elsewhere (NOT in this function)
-    pkt->dts=
-    pkt->pts= pkt->pos*8 / (bps * s->streams[0]->codec->channels);
-
-    return ret;
-}
-
-int ff_raw_read_partial_packet(AVFormatContext *s, AVPacket *pkt)
-{
-    int ret, size;
-
-    size = RAW_PACKET_SIZE;
-
-    if (av_new_packet(pkt, size) < 0)
-        return AVERROR(ENOMEM);
-
-    pkt->pos= url_ftell(s->pb);
-    pkt->stream_index = 0;
-    ret = get_partial_buffer(s->pb, pkt->data, size);
-    if (ret < 0) {
-        av_free_packet(pkt);
-        return ret;
-    }
-    pkt->size = ret;
-    return ret;
-}
-#endif
-
-#if CONFIG_RAWVIDEO_DEMUXER
-static int rawvideo_read_packet(AVFormatContext *s, AVPacket *pkt)
-{
-    int packet_size, ret, width, height;
-    AVStream *st = s->streams[0];
-
-    width = st->codec->width;
-    height = st->codec->height;
-
-    packet_size = avpicture_get_size(st->codec->pix_fmt, width, height);
-    if (packet_size < 0)
-        return -1;
-
-    ret= av_get_packet(s->pb, pkt, packet_size);
-    pkt->pts=
-    pkt->dts= pkt->pos / packet_size;
-
-    pkt->stream_index = 0;
-    if (ret < 0)
-        return ret;
-    return 0;
-}
-#endif
-
-#if CONFIG_INGENIENT_DEMUXER
-// http://www.artificis.hu/files/texts/ingenient.txt
-static int ingenient_read_packet(AVFormatContext *s, AVPacket *pkt)
-{
-    int ret, size, w, h, unk1, unk2;
-
-    if (get_le32(s->pb) != MKTAG('M', 'J', 'P', 'G'))
-        return AVERROR(EIO); // FIXME
-
-    size = get_le32(s->pb);
-
-    w = get_le16(s->pb);
-    h = get_le16(s->pb);
-
-    url_fskip(s->pb, 8); // zero + size (padded?)
-    url_fskip(s->pb, 2);
-    unk1 = get_le16(s->pb);
-    unk2 = get_le16(s->pb);
-    url_fskip(s->pb, 22); // ASCII timestamp
-
-    av_log(s, AV_LOG_DEBUG, "Ingenient packet: size=%d, width=%d, height=%d, unk1=%d unk2=%d\n",
-        size, w, h, unk1, unk2);
-
-    if (av_new_packet(pkt, size) < 0)
-        return AVERROR(ENOMEM);
-
-    pkt->pos = url_ftell(s->pb);
-    pkt->stream_index = 0;
-    ret = get_buffer(s->pb, pkt->data, size);
-    if (ret < 0) {
-        av_free_packet(pkt);
-        return ret;
-    }
-    pkt->size = ret;
-    return ret;
-}
-#endif
-
-#if CONFIG_DEMUXERS
-int pcm_read_seek(AVFormatContext *s,
-                  int stream_index, int64_t timestamp, int flags)
-{
-    AVStream *st;
-    int block_align, byte_rate;
-    int64_t pos, ret;
-
-    st = s->streams[0];
-
-    block_align = st->codec->block_align ? st->codec->block_align :
-        (av_get_bits_per_sample(st->codec->codec_id) * st->codec->channels) >> 3;
-    byte_rate = st->codec->bit_rate ? st->codec->bit_rate >> 3 :
-        block_align * st->codec->sample_rate;
-
-    if (block_align <= 0 || byte_rate <= 0)
-        return -1;
-    if (timestamp < 0) timestamp = 0;
-
-    /* compute the position by aligning it to block_align */
-    pos = av_rescale_rnd(timestamp * byte_rate,
-                         st->time_base.num,
-                         st->time_base.den * (int64_t)block_align,
-                         (flags & AVSEEK_FLAG_BACKWARD) ? AV_ROUND_DOWN : AV_ROUND_UP);
-    pos *= block_align;
-
-    /* recompute exact position */
-    st->cur_dts = av_rescale(pos, st->time_base.den, byte_rate * (int64_t)st->time_base.num);
-    if ((ret = url_fseek(s->pb, pos + s->data_offset, SEEK_SET)) < 0)
-        return ret;
-    return 0;
-}
-
-static int audio_read_header(AVFormatContext *s,
-                             AVFormatParameters *ap)
-{
-    AVStream *st = av_new_stream(s, 0);
-    if (!st)
-        return AVERROR(ENOMEM);
-    st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
-    st->codec->codec_id = s->iformat->value;
-    st->need_parsing = AVSTREAM_PARSE_FULL;
-    /* the parameters will be extracted from the compressed bitstream */
-
-    return 0;
-}
-
-/* MPEG-1/H.263 input */
-static int video_read_header(AVFormatContext *s,
-                             AVFormatParameters *ap)
-{
-    AVStream *st;
-
-    st = av_new_stream(s, 0);
-    if (!st)
-        return AVERROR(ENOMEM);
-
-    st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
-    st->codec->codec_id = s->iformat->value;
-    st->need_parsing = AVSTREAM_PARSE_FULL;
-
-    /* for MJPEG, specify frame rate */
-    /* for MPEG-4 specify it, too (most MPEG-4 streams do not have the fixed_vop_rate set ...)*/
-    if (ap->time_base.num) {
-        st->codec->time_base= ap->time_base;
-    } else if ( st->codec->codec_id == CODEC_ID_MJPEG ||
-                st->codec->codec_id == CODEC_ID_MPEG4 ||
-                st->codec->codec_id == CODEC_ID_DIRAC ||
-                st->codec->codec_id == CODEC_ID_DNXHD ||
-                st->codec->codec_id == CODEC_ID_H264) {
-        st->codec->time_base= (AVRational){1,25};
-    }
-    av_set_pts_info(st, 64, 1, 1200000);
-
-    return 0;
-}
-#endif
-
-#if CONFIG_MPEGVIDEO_DEMUXER
-#define SEQ_START_CODE          0x000001b3
-#define GOP_START_CODE          0x000001b8
-#define PICTURE_START_CODE      0x00000100
-#define SLICE_START_CODE        0x00000101
-#define PACK_START_CODE         0x000001ba
-#define VIDEO_ID                0x000001e0
-#define AUDIO_ID                0x000001c0
-
-static int mpegvideo_probe(AVProbeData *p)
-{
-    uint32_t code= -1;
-    int pic=0, seq=0, slice=0, pspack=0, pes=0;
-    int i;
-
-    for(i=0; i<p->buf_size; i++){
-        code = (code<<8) + p->buf[i];
-        if ((code & 0xffffff00) == 0x100) {
-            switch(code){
-            case     SEQ_START_CODE:   seq++; break;
-            case PICTURE_START_CODE:   pic++; break;
-            case   SLICE_START_CODE: slice++; break;
-            case    PACK_START_CODE: pspack++; break;
-            }
-            if     ((code & 0x1f0) == VIDEO_ID)   pes++;
-            else if((code & 0x1e0) == AUDIO_ID)   pes++;
-        }
-    }
-    if(seq && seq*9<=pic*10 && pic*9<=slice*10 && !pspack && !pes)
-        return pic>1 ? AVPROBE_SCORE_MAX/2+1 : AVPROBE_SCORE_MAX/4; // +1 for .mpg
-    return 0;
-}
-#endif
-
-#if CONFIG_CAVSVIDEO_DEMUXER
-#define CAVS_SEQ_START_CODE       0x000001b0
-#define CAVS_PIC_I_START_CODE     0x000001b3
-#define CAVS_UNDEF_START_CODE     0x000001b4
-#define CAVS_PIC_PB_START_CODE    0x000001b6
-#define CAVS_VIDEO_EDIT_CODE      0x000001b7
-#define CAVS_PROFILE_JIZHUN       0x20
-
-static int cavsvideo_probe(AVProbeData *p)
-{
-    uint32_t code= -1;
-    int pic=0, seq=0, slice_pos = 0;
-    int i;
-
-    for(i=0; i<p->buf_size; i++){
-        code = (code<<8) + p->buf[i];
-        if ((code & 0xffffff00) == 0x100) {
-            if(code < CAVS_SEQ_START_CODE) {
-                /* slices have to be consecutive */
-                if(code < slice_pos)
-                    return 0;
-                slice_pos = code;
-            } else {
-                slice_pos = 0;
-            }
-            if (code == CAVS_SEQ_START_CODE) {
-                seq++;
-                /* check for the only currently supported profile */
-                if(p->buf[i+1] != CAVS_PROFILE_JIZHUN)
-                    return 0;
-            } else if ((code == CAVS_PIC_I_START_CODE) ||
-                       (code == CAVS_PIC_PB_START_CODE)) {
-                pic++;
-            } else if ((code == CAVS_UNDEF_START_CODE) ||
-                       (code >  CAVS_VIDEO_EDIT_CODE)) {
-                return 0;
-            }
-        }
-    }
-    if(seq && seq*9<=pic*10)
-        return AVPROBE_SCORE_MAX/2;
-    return 0;
-}
-#endif
-
-#if CONFIG_M4V_DEMUXER
-#define VISUAL_OBJECT_START_CODE       0x000001b5
-#define VOP_START_CODE                 0x000001b6
-
-static int mpeg4video_probe(AVProbeData *probe_packet)
-{
-    uint32_t temp_buffer= -1;
-    int VO=0, VOL=0, VOP = 0, VISO = 0, res=0;
-    int i;
-
-    for(i=0; i<probe_packet->buf_size; i++){
-        temp_buffer = (temp_buffer<<8) + probe_packet->buf[i];
-        if ((temp_buffer & 0xffffff00) != 0x100)
-            continue;
-
-        if (temp_buffer == VOP_START_CODE)                         VOP++;
-        else if (temp_buffer == VISUAL_OBJECT_START_CODE)          VISO++;
-        else if (temp_buffer < 0x120)                              VO++;
-        else if (temp_buffer < 0x130)                              VOL++;
-        else if (   !(0x1AF < temp_buffer && temp_buffer < 0x1B7)
-                 && !(0x1B9 < temp_buffer && temp_buffer < 0x1C4)) res++;
-    }
-
-    if ( VOP >= VISO && VOP >= VOL && VO >= VOL && VOL > 0 && res==0)
-        return AVPROBE_SCORE_MAX/2;
-    return 0;
-}
-#endif
-
-#if CONFIG_H264_DEMUXER
-static int h264_probe(AVProbeData *p)
-{
-    uint32_t code= -1;
-    int sps=0, pps=0, idr=0, res=0, sli=0;
-    int i;
-
-    for(i=0; i<p->buf_size; i++){
-        code = (code<<8) + p->buf[i];
-        if ((code & 0xffffff00) == 0x100) {
-            int ref_idc= (code>>5)&3;
-            int type   = code & 0x1F;
-            static const int8_t ref_zero[32]={
-                2, 0, 0, 0, 0,-1, 1,-1,
-               -1, 1, 1, 1, 1,-1, 2, 2,
-                2, 2, 2, 0, 2, 2, 2, 2,
-                2, 2, 2, 2, 2, 2, 2, 2
-            };
-
-            if(code & 0x80) //forbidden bit
-                return 0;
-
-            if(ref_zero[type] == 1 && ref_idc)
-                return 0;
-            if(ref_zero[type] ==-1 && !ref_idc)
-                return 0;
-            if(ref_zero[type] == 2)
-                res++;
-
-            switch(type){
-            case     1:   sli++; break;
-            case     5:   idr++; break;
-            case     7:
-                if(p->buf[i+2]&0x0F)
-                    return 0;
-                sps++;
-                break;
-            case     8:   pps++; break;
-            }
-        }
-    }
-    if(sps && pps && (idr||sli>3) && res<(sps+pps+idr))
-        return AVPROBE_SCORE_MAX/2+1; // +1 for .mpg
-    return 0;
-}
-#endif
-
-#if CONFIG_H263_DEMUXER
-static int h263_probe(AVProbeData *p)
-{
-    uint64_t code= -1;
-    int i;
-    int valid_psc=0;
-    int invalid_psc=0;
-    int res_change=0;
-    int src_fmt, last_src_fmt=-1;
-
-    for(i=0; i<p->buf_size; i++){
-        code = (code<<8) + p->buf[i];
-        if ((code & 0xfffffc0000) == 0x800000) {
-            src_fmt= (code>>2)&3;
-            if(   src_fmt != last_src_fmt
-               && last_src_fmt>0 && last_src_fmt<6
-               && src_fmt<6)
-                res_change++;
-
-            if((code&0x300)==0x200 && src_fmt){
-                valid_psc++;
-            }else
-                invalid_psc++;
-            last_src_fmt= src_fmt;
-        }
-    }
-//av_log(NULL, AV_LOG_ERROR, "h263_probe: psc:%d invalid:%d res_change:%d\n", valid_psc, invalid_psc, res_change);
-//h263_probe: psc:3 invalid:0 res_change:0 (1588/recent_ffmpeg_parses_mpg_incorrectly.mpg)
-    if(valid_psc > 2*invalid_psc + 2*res_change + 3){
-        return 50;
-    }else if(valid_psc > 2*invalid_psc)
-        return 25;
-    return 0;
-}
-#endif
-
-#if CONFIG_H261_DEMUXER
-static int h261_probe(AVProbeData *p)
-{
-    uint32_t code= -1;
-    int i;
-    int valid_psc=0;
-    int invalid_psc=0;
-    int next_gn=0;
-    int src_fmt=0;
-    GetBitContext gb;
-
-    init_get_bits(&gb, p->buf, p->buf_size*8);
-
-    for(i=0; i<p->buf_size*8; i++){
-        if ((code & 0x01ff0000) || !(code & 0xff00)) {
-            code = (code<<8) + get_bits(&gb, 8);
-            i += 7;
-        } else
-            code = (code<<1) + get_bits1(&gb);
-        if ((code & 0xffff0000) == 0x10000) {
-            int gn= (code>>12)&0xf;
-            if(!gn)
-                src_fmt= code&8;
-            if(gn != next_gn) invalid_psc++;
-            else              valid_psc++;
-
-            if(src_fmt){ // CIF
-                next_gn= (gn+1     )%13;
-            }else{       //QCIF
-                next_gn= (gn+1+!!gn)% 7;
-            }
-        }
-    }
-    if(valid_psc > 2*invalid_psc + 6){
-        return 50;
-    }else if(valid_psc > 2*invalid_psc + 2)
-        return 25;
-    return 0;
-}
-#endif
-
-#if CONFIG_DTS_DEMUXER
-#define DCA_MARKER_14B_BE 0x1FFFE800
-#define DCA_MARKER_14B_LE 0xFF1F00E8
-#define DCA_MARKER_RAW_BE 0x7FFE8001
-#define DCA_MARKER_RAW_LE 0xFE7F0180
-static int dts_probe(AVProbeData *p)
-{
-    const uint8_t *buf, *bufp;
-    uint32_t state = -1;
-    int markers[3] = {0};
-    int sum, max;
-
-    buf = p->buf;
-
-    for(; buf < (p->buf+p->buf_size)-2; buf+=2) {
-        bufp = buf;
-        state = (state << 16) | bytestream_get_be16(&bufp);
-
-        /* regular bitstream */
-        if (state == DCA_MARKER_RAW_BE || state == DCA_MARKER_RAW_LE)
-            markers[0]++;
-
-        /* 14 bits big-endian bitstream */
-        if (state == DCA_MARKER_14B_BE)
-            if ((bytestream_get_be16(&bufp) & 0xFFF0) == 0x07F0)
-                markers[1]++;
-
-        /* 14 bits little-endian bitstream */
-        if (state == DCA_MARKER_14B_LE)
-            if ((bytestream_get_be16(&bufp) & 0xF0FF) == 0xF007)
-                markers[2]++;
-    }
-    sum = markers[0] + markers[1] + markers[2];
-    max = markers[1] > markers[0];
-    max = markers[2] > markers[max] ? 2 : max;
-    if (markers[max] > 3 && p->buf_size / markers[max] < 32*1024 &&
-        markers[max] * 4 > sum * 3)
-        return AVPROBE_SCORE_MAX/2+1;
-
-    return 0;
-}
-#endif
-
-#if CONFIG_DIRAC_DEMUXER
-static int dirac_probe(AVProbeData *p)
-{
-    if (AV_RL32(p->buf) == MKTAG('B', 'B', 'C', 'D'))
-        return AVPROBE_SCORE_MAX;
-    else
-        return 0;
-}
-#endif
-
-#if CONFIG_DNXHD_DEMUXER
-static int dnxhd_probe(AVProbeData *p)
-{
-    static const uint8_t header[] = {0x00,0x00,0x02,0x80,0x01};
-    int w, h, compression_id;
-    if (p->buf_size < 0x2c)
-        return 0;
-    if (memcmp(p->buf, header, 5))
-        return 0;
-    h = AV_RB16(p->buf + 0x18);
-    w = AV_RB16(p->buf + 0x1a);
-    if (!w || !h)
-        return 0;
-    compression_id = AV_RB32(p->buf + 0x28);
-    if (compression_id < 1237 || compression_id > 1253)
-        return 0;
-    return AVPROBE_SCORE_MAX;
-}
-#endif
-
-#if CONFIG_AC3_DEMUXER || CONFIG_EAC3_DEMUXER
-static int ac3_eac3_probe(AVProbeData *p, enum CodecID expected_codec_id)
-{
-    int max_frames, first_frames = 0, frames;
-    uint8_t *buf, *buf2, *end;
-    AC3HeaderInfo hdr;
-    GetBitContext gbc;
-    enum CodecID codec_id = CODEC_ID_AC3;
-
-    max_frames = 0;
-    buf = p->buf;
-    end = buf + p->buf_size;
-
-    for(; buf < end; buf++) {
-        buf2 = buf;
-
-        for(frames = 0; buf2 < end; frames++) {
-            init_get_bits(&gbc, buf2, 54);
-            if(ff_ac3_parse_header(&gbc, &hdr) < 0)
-                break;
-            if(buf2 + hdr.frame_size > end ||
-               av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0, buf2 + 2, hdr.frame_size - 2))
-                break;
-            if (hdr.bitstream_id > 10)
-                codec_id = CODEC_ID_EAC3;
-            buf2 += hdr.frame_size;
-        }
-        max_frames = FFMAX(max_frames, frames);
-        if(buf == p->buf)
-            first_frames = frames;
-    }
-    if(codec_id != expected_codec_id) return 0;
-    // keep this in sync with mp3 probe, both need to avoid
-    // issues with MPEG-files!
-    if   (first_frames>=4) return AVPROBE_SCORE_MAX/2+1;
-    else if(max_frames>500)return AVPROBE_SCORE_MAX/2;
-    else if(max_frames>=4) return AVPROBE_SCORE_MAX/4;
-    else if(max_frames>=1) return 1;
-    else                   return 0;
-}
-#endif
-
-#if CONFIG_AC3_DEMUXER
-static int ac3_probe(AVProbeData *p)
-{
-    return ac3_eac3_probe(p, CODEC_ID_AC3);
-}
-#endif
-
-#if CONFIG_EAC3_DEMUXER
-static int eac3_probe(AVProbeData *p)
-{
-    return ac3_eac3_probe(p, CODEC_ID_EAC3);
-}
-#endif
-
-#if CONFIG_AAC_DEMUXER
-static int adts_aac_probe(AVProbeData *p)
-{
-    int max_frames = 0, first_frames = 0;
-    int fsize, frames;
-    uint8_t *buf0 = p->buf;
-    uint8_t *buf2;
-    uint8_t *buf;
-    uint8_t *end = buf0 + p->buf_size - 7;
-
-    if (ff_id3v2_match(buf0)) {
-        buf0 += ff_id3v2_tag_len(buf0);
-    }
-    buf = buf0;
-
-    for(; buf < end; buf= buf2+1) {
-        buf2 = buf;
-
-        for(frames = 0; buf2 < end; frames++) {
-            uint32_t header = AV_RB16(buf2);
-            if((header&0xFFF6) != 0xFFF0)
-                break;
-            fsize = (AV_RB32(buf2+3)>>13) & 0x8FFF;
-            if(fsize < 7)
-                break;
-            buf2 += fsize;
-        }
-        max_frames = FFMAX(max_frames, frames);
-        if(buf == buf0)
-            first_frames= frames;
-    }
-    if   (first_frames>=3) return AVPROBE_SCORE_MAX/2+1;
-    else if(max_frames>500)return AVPROBE_SCORE_MAX/2;
-    else if(max_frames>=3) return AVPROBE_SCORE_MAX/4;
-    else if(max_frames>=1) return 1;
-    else                   return 0;
-}
-
-static int adts_aac_read_header(AVFormatContext *s,
-                                AVFormatParameters *ap)
-{
-    AVStream *st;
-
-    st = av_new_stream(s, 0);
-    if (!st)
-        return AVERROR(ENOMEM);
-
-    st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
-    st->codec->codec_id = s->iformat->value;
-    st->need_parsing = AVSTREAM_PARSE_FULL;
-
-    ff_id3v1_read(s);
-    ff_id3v2_read(s);
-
-    return 0;
-}
-
-#endif
-
-/* Note: Do not forget to add new entries to the Makefile as well. */
-
-#if CONFIG_AAC_DEMUXER
-AVInputFormat aac_demuxer = {
-    "aac",
-    NULL_IF_CONFIG_SMALL("raw ADTS AAC"),
-    0,
-    adts_aac_probe,
-    adts_aac_read_header,
-    ff_raw_read_partial_packet,
-    .flags= AVFMT_GENERIC_INDEX,
-    .extensions = "aac",
-    .value = CODEC_ID_AAC,
-};
-#endif
-
-#if CONFIG_AC3_DEMUXER
-AVInputFormat ac3_demuxer = {
-    "ac3",
-    NULL_IF_CONFIG_SMALL("raw AC-3"),
-    0,
-    ac3_probe,
-    audio_read_header,
-    ff_raw_read_partial_packet,
-    .flags= AVFMT_GENERIC_INDEX,
-    .extensions = "ac3",
-    .value = CODEC_ID_AC3,
-};
-#endif
-
-#if CONFIG_AC3_MUXER
-AVOutputFormat ac3_muxer = {
-    "ac3",
-    NULL_IF_CONFIG_SMALL("raw AC-3"),
-    "audio/x-ac3",
-    "ac3",
-    0,
-    CODEC_ID_AC3,
-    CODEC_ID_NONE,
-    NULL,
-    raw_write_packet,
-    .flags= AVFMT_NOTIMESTAMPS,
-};
-#endif
-
-#if CONFIG_DIRAC_DEMUXER
-AVInputFormat dirac_demuxer = {
-    "dirac",
-    NULL_IF_CONFIG_SMALL("raw Dirac"),
-    0,
-    dirac_probe,
-    video_read_header,
-    ff_raw_read_partial_packet,
-    .flags= AVFMT_GENERIC_INDEX,
-    .value = CODEC_ID_DIRAC,
-};
-#endif
-
-#if CONFIG_DIRAC_MUXER
-AVOutputFormat dirac_muxer = {
-    "dirac",
-    NULL_IF_CONFIG_SMALL("raw Dirac"),
-    NULL,
-    "drc",
-    0,
-    CODEC_ID_NONE,
-    CODEC_ID_DIRAC,
-    NULL,
-    raw_write_packet,
-    .flags= AVFMT_NOTIMESTAMPS,
-};
-#endif
-
-#if CONFIG_DNXHD_DEMUXER
-AVInputFormat dnxhd_demuxer = {
-    "dnxhd",
-    NULL_IF_CONFIG_SMALL("raw DNxHD (SMPTE VC-3)"),
-    0,
-    dnxhd_probe,
-    video_read_header,
-    ff_raw_read_partial_packet,
-    .flags= AVFMT_GENERIC_INDEX,
-    .value = CODEC_ID_DNXHD,
-};
-#endif
-
-#if CONFIG_DNXHD_MUXER
-AVOutputFormat dnxhd_muxer = {
-    "dnxhd",
-    NULL_IF_CONFIG_SMALL("raw DNxHD (SMPTE VC-3)"),
-    NULL,
-    "dnxhd",
-    0,
-    CODEC_ID_NONE,
-    CODEC_ID_DNXHD,
-    NULL,
-    raw_write_packet,
-    .flags= AVFMT_NOTIMESTAMPS,
-};
-#endif
-
-#if CONFIG_DTS_DEMUXER
-AVInputFormat dts_demuxer = {
-    "dts",
-    NULL_IF_CONFIG_SMALL("raw DTS"),
-    0,
-    dts_probe,
-    audio_read_header,
-    ff_raw_read_partial_packet,
-    .flags= AVFMT_GENERIC_INDEX,
-    .extensions = "dts",
-    .value = CODEC_ID_DTS,
-};
-#endif
-
-#if CONFIG_DTS_MUXER
-AVOutputFormat dts_muxer = {
-    "dts",
-    NULL_IF_CONFIG_SMALL("raw DTS"),
-    "audio/x-dca",
-    "dts",
-    0,
-    CODEC_ID_DTS,
-    CODEC_ID_NONE,
-    NULL,
-    raw_write_packet,
-    .flags= AVFMT_NOTIMESTAMPS,
-};
-#endif
-
-#if CONFIG_EAC3_DEMUXER
-AVInputFormat eac3_demuxer = {
-    "eac3",
-    NULL_IF_CONFIG_SMALL("raw E-AC-3"),
-    0,
-    eac3_probe,
-    audio_read_header,
-    ff_raw_read_partial_packet,
-    .flags= AVFMT_GENERIC_INDEX,
-    .extensions = "eac3",
-    .value = CODEC_ID_EAC3,
-};
-#endif
-
-#if CONFIG_EAC3_MUXER
-AVOutputFormat eac3_muxer = {
-    "eac3",
-    NULL_IF_CONFIG_SMALL("raw E-AC-3"),
-    "audio/x-eac3",
-    "eac3",
-    0,
-    CODEC_ID_EAC3,
-    CODEC_ID_NONE,
-    NULL,
-    raw_write_packet,
-    .flags= AVFMT_NOTIMESTAMPS,
-};
-#endif
-
-#if CONFIG_GSM_DEMUXER
-AVInputFormat gsm_demuxer = {
-    "gsm",
-    NULL_IF_CONFIG_SMALL("raw GSM"),
-    0,
-    NULL,
-    audio_read_header,
-    ff_raw_read_partial_packet,
-    .flags= AVFMT_GENERIC_INDEX,
-    .extensions = "gsm",
-    .value = CODEC_ID_GSM,
-};
-#endif
-
-#if CONFIG_H261_DEMUXER
-AVInputFormat h261_demuxer = {
-    "h261",
-    NULL_IF_CONFIG_SMALL("raw H.261"),
-    0,
-    h261_probe,
-    video_read_header,
-    ff_raw_read_partial_packet,
-    .flags= AVFMT_GENERIC_INDEX,
-    .extensions = "h261",
-    .value = CODEC_ID_H261,
-};
-#endif
-
-#if CONFIG_H261_MUXER
-AVOutputFormat h261_muxer = {
-    "h261",
-    NULL_IF_CONFIG_SMALL("raw H.261"),
-    "video/x-h261",
-    "h261",
-    0,
-    CODEC_ID_NONE,
-    CODEC_ID_H261,
-    NULL,
-    raw_write_packet,
-    .flags= AVFMT_NOTIMESTAMPS,
-};
-#endif
-
-#if CONFIG_H263_DEMUXER
-AVInputFormat h263_demuxer = {
-    "h263",
-    NULL_IF_CONFIG_SMALL("raw H.263"),
-    0,
-    h263_probe,
-    video_read_header,
-    ff_raw_read_partial_packet,
-    .flags= AVFMT_GENERIC_INDEX,
-//    .extensions = "h263", //FIXME remove after writing mpeg4_probe
-    .value = CODEC_ID_H263,
-};
-#endif
-
-#if CONFIG_H263_MUXER
-AVOutputFormat h263_muxer = {
-    "h263",
-    NULL_IF_CONFIG_SMALL("raw H.263"),
-    "video/x-h263",
-    "h263",
-    0,
-    CODEC_ID_NONE,
-    CODEC_ID_H263,
-    NULL,
-    raw_write_packet,
-    .flags= AVFMT_NOTIMESTAMPS,
-};
-#endif
-
-#if CONFIG_H264_DEMUXER
-AVInputFormat h264_demuxer = {
-    "h264",
-    NULL_IF_CONFIG_SMALL("raw H.264 video format"),
-    0,
-    h264_probe,
-    video_read_header,
-    ff_raw_read_partial_packet,
-    .flags= AVFMT_GENERIC_INDEX,
-    .extensions = "h26l,h264,264", //FIXME remove after writing mpeg4_probe
-    .value = CODEC_ID_H264,
-};
-#endif
-
-#if CONFIG_H264_MUXER
-AVOutputFormat h264_muxer = {
-    "h264",
-    NULL_IF_CONFIG_SMALL("raw H.264 video format"),
-    NULL,
-    "h264",
-    0,
-    CODEC_ID_NONE,
-    CODEC_ID_H264,
-    NULL,
-    raw_write_packet,
-    .flags= AVFMT_NOTIMESTAMPS,
-};
-#endif
-
-#if CONFIG_INGENIENT_DEMUXER
-AVInputFormat ingenient_demuxer = {
-    "ingenient",
-    NULL_IF_CONFIG_SMALL("raw Ingenient MJPEG"),
-    0,
-    NULL,
-    video_read_header,
-    ingenient_read_packet,
-    .flags= AVFMT_GENERIC_INDEX,
-    .extensions = "cgi", // FIXME
-    .value = CODEC_ID_MJPEG,
-};
-#endif
-
-#if CONFIG_M4V_DEMUXER
-AVInputFormat m4v_demuxer = {
-    "m4v",
-    NULL_IF_CONFIG_SMALL("raw MPEG-4 video format"),
-    0,
-    mpeg4video_probe, /** probing for MPEG-4 data */
-    video_read_header,
-    ff_raw_read_partial_packet,
-    .flags= AVFMT_GENERIC_INDEX,
-    .extensions = "m4v",
-    .value = CODEC_ID_MPEG4,
-};
-#endif
-
-#if CONFIG_M4V_MUXER
-AVOutputFormat m4v_muxer = {
-    "m4v",
-    NULL_IF_CONFIG_SMALL("raw MPEG-4 video format"),
-    NULL,
-    "m4v",
-    0,
-    CODEC_ID_NONE,
-    CODEC_ID_MPEG4,
-    NULL,
-    raw_write_packet,
-    .flags= AVFMT_NOTIMESTAMPS,
-};
-#endif
-
-#if CONFIG_MJPEG_DEMUXER
-AVInputFormat mjpeg_demuxer = {
-    "mjpeg",
-    NULL_IF_CONFIG_SMALL("raw MJPEG video"),
-    0,
-    NULL,
-    video_read_header,
-    ff_raw_read_partial_packet,
-    .flags= AVFMT_GENERIC_INDEX,
-    .extensions = "mjpg,mjpeg",
-    .value = CODEC_ID_MJPEG,
-};
-#endif
-
-#if CONFIG_MJPEG_MUXER
-AVOutputFormat mjpeg_muxer = {
-    "mjpeg",
-    NULL_IF_CONFIG_SMALL("raw MJPEG video"),
-    "video/x-mjpeg",
-    "mjpg,mjpeg",
-    0,
-    CODEC_ID_NONE,
-    CODEC_ID_MJPEG,
-    NULL,
-    raw_write_packet,
-    .flags= AVFMT_NOTIMESTAMPS,
-};
-#endif
-
-#if CONFIG_MLP_DEMUXER
-AVInputFormat mlp_demuxer = {
-    "mlp",
-    NULL_IF_CONFIG_SMALL("raw MLP"),
-    0,
-    NULL,
-    audio_read_header,
-    ff_raw_read_partial_packet,
-    .flags= AVFMT_GENERIC_INDEX,
-    .extensions = "mlp",
-    .value = CODEC_ID_MLP,
-};
-#endif
-
-#if CONFIG_MLP_MUXER
-AVOutputFormat mlp_muxer = {
-    "mlp",
-    NULL_IF_CONFIG_SMALL("raw MLP"),
-    NULL,
-    "mlp",
-    0,
-    CODEC_ID_MLP,
-    CODEC_ID_NONE,
-    NULL,
-    raw_write_packet,
-    .flags= AVFMT_NOTIMESTAMPS,
-};
-#endif
-
-#if CONFIG_TRUEHD_DEMUXER
-AVInputFormat truehd_demuxer = {
-    "truehd",
-    NULL_IF_CONFIG_SMALL("raw TrueHD"),
-    0,
-    NULL,
-    audio_read_header,
-    ff_raw_read_partial_packet,
-    .flags= AVFMT_GENERIC_INDEX,
-    .extensions = "thd",
-    .value = CODEC_ID_TRUEHD,
-};
-#endif
-
-#if CONFIG_TRUEHD_MUXER
-AVOutputFormat truehd_muxer = {
-    "truehd",
-    NULL_IF_CONFIG_SMALL("raw TrueHD"),
-    NULL,
-    "thd",
-    0,
-    CODEC_ID_TRUEHD,
-    CODEC_ID_NONE,
-    NULL,
-    raw_write_packet,
-    .flags= AVFMT_NOTIMESTAMPS,
-};
-#endif
-
-#if CONFIG_MPEG1VIDEO_MUXER
-AVOutputFormat mpeg1video_muxer = {
-    "mpeg1video",
-    NULL_IF_CONFIG_SMALL("raw MPEG-1 video"),
-    "video/x-mpeg",
-    "mpg,mpeg,m1v",
-    0,
-    CODEC_ID_NONE,
-    CODEC_ID_MPEG1VIDEO,
-    NULL,
-    raw_write_packet,
-    .flags= AVFMT_NOTIMESTAMPS,
-};
-#endif
-
-#if CONFIG_MPEG2VIDEO_MUXER
-AVOutputFormat mpeg2video_muxer = {
-    "mpeg2video",
-    NULL_IF_CONFIG_SMALL("raw MPEG-2 video"),
-    NULL,
-    "m2v",
-    0,
-    CODEC_ID_NONE,
-    CODEC_ID_MPEG2VIDEO,
-    NULL,
-    raw_write_packet,
-    .flags= AVFMT_NOTIMESTAMPS,
-};
-#endif
-
-#if CONFIG_MPEGVIDEO_DEMUXER
-AVInputFormat mpegvideo_demuxer = {
-    "mpegvideo",
-    NULL_IF_CONFIG_SMALL("raw MPEG video"),
-    0,
-    mpegvideo_probe,
-    video_read_header,
-    ff_raw_read_partial_packet,
-    .flags= AVFMT_GENERIC_INDEX,
-    .value = CODEC_ID_MPEG1VIDEO,
-};
-#endif
-
-#if CONFIG_CAVSVIDEO_DEMUXER
-AVInputFormat cavsvideo_demuxer = {
-    "cavsvideo",
-    NULL_IF_CONFIG_SMALL("raw Chinese AVS video"),
-    0,
-    cavsvideo_probe,
-    video_read_header,
-    ff_raw_read_partial_packet,
-    .flags= AVFMT_GENERIC_INDEX,
-    .value = CODEC_ID_CAVS,
-};
-#endif
-
-#if CONFIG_NULL_MUXER
-AVOutputFormat null_muxer = {
-    "null",
-    NULL_IF_CONFIG_SMALL("raw null video format"),
-    NULL,
-    NULL,
-    0,
-#if HAVE_BIGENDIAN
-    CODEC_ID_PCM_S16BE,
-#else
-    CODEC_ID_PCM_S16LE,
-#endif
-    CODEC_ID_RAWVIDEO,
-    NULL,
-    null_write_packet,
-    .flags = AVFMT_NOFILE | AVFMT_RAWPICTURE | AVFMT_NOTIMESTAMPS,
-};
-#endif
-
-#if CONFIG_RAWVIDEO_DEMUXER
-AVInputFormat rawvideo_demuxer = {
-    "rawvideo",
-    NULL_IF_CONFIG_SMALL("raw video format"),
-    0,
-    NULL,
-    raw_read_header,
-    rawvideo_read_packet,
-    .flags= AVFMT_GENERIC_INDEX,
-    .extensions = "yuv,cif,qcif,rgb",
-    .value = CODEC_ID_RAWVIDEO,
-};
-#endif
-
-#if CONFIG_RAWVIDEO_MUXER
-AVOutputFormat rawvideo_muxer = {
-    "rawvideo",
-    NULL_IF_CONFIG_SMALL("raw video format"),
-    NULL,
-    "yuv,rgb",
-    0,
-    CODEC_ID_NONE,
-    CODEC_ID_RAWVIDEO,
-    NULL,
-    raw_write_packet,
-    .flags= AVFMT_NOTIMESTAMPS,
-};
-#endif
-
-#if CONFIG_ROQ_MUXER
-AVOutputFormat roq_muxer =
-{
-    "RoQ",
-    NULL_IF_CONFIG_SMALL("raw id RoQ format"),
-    NULL,
-    "roq",
-    0,
-    CODEC_ID_ROQ_DPCM,
-    CODEC_ID_ROQ,
-    roq_write_header,
-    raw_write_packet,
-};
-#endif
-
-#if CONFIG_SHORTEN_DEMUXER
-AVInputFormat shorten_demuxer = {
-    "shn",
-    NULL_IF_CONFIG_SMALL("raw Shorten"),
-    0,
-    NULL,
-    audio_read_header,
-    ff_raw_read_partial_packet,
-    .flags= AVFMT_GENERIC_INDEX,
-    .extensions = "shn",
-    .value = CODEC_ID_SHORTEN,
-};
-#endif
-
-#if CONFIG_VC1_DEMUXER
-AVInputFormat vc1_demuxer = {
-    "vc1",
-    NULL_IF_CONFIG_SMALL("raw VC-1"),
-    0,
-    NULL /* vc1_probe */,
-    video_read_header,
-    ff_raw_read_partial_packet,
-    .extensions = "vc1",
-    .value = CODEC_ID_VC1,
-};
-#endif
-
-/* PCM formats */
-
-#define PCMINPUTDEF(name, long_name, ext, codec) \
-AVInputFormat pcm_ ## name ## _demuxer = {\
-    #name,\
-    NULL_IF_CONFIG_SMALL(long_name),\
-    0,\
-    NULL,\
-    raw_read_header,\
-    raw_read_packet,\
-    NULL,\
-    pcm_read_seek,\
-    .flags= AVFMT_GENERIC_INDEX,\
-    .extensions = ext,\
-    .value = codec,\
-};
-
-#define PCMOUTPUTDEF(name, long_name, ext, codec) \
-AVOutputFormat pcm_ ## name ## _muxer = {\
-    #name,\
-    NULL_IF_CONFIG_SMALL(long_name),\
-    NULL,\
-    ext,\
-    0,\
-    codec,\
-    CODEC_ID_NONE,\
-    NULL,\
-    raw_write_packet,\
-    .flags= AVFMT_NOTIMESTAMPS,\
-};
-
-
-#if  !CONFIG_MUXERS && CONFIG_DEMUXERS
-#define PCMDEF(name, long_name, ext, codec) \
-        PCMINPUTDEF(name, long_name, ext, codec)
-#elif CONFIG_MUXERS && !CONFIG_DEMUXERS
-#define PCMDEF(name, long_name, ext, codec) \
-        PCMOUTPUTDEF(name, long_name, ext, codec)
-#elif CONFIG_MUXERS && CONFIG_DEMUXERS
-#define PCMDEF(name, long_name, ext, codec) \
-        PCMINPUTDEF(name, long_name, ext, codec)\
-        PCMOUTPUTDEF(name, long_name, ext, codec)
-#else
-#define PCMDEF(name, long_name, ext, codec)
-#endif
-
-#if HAVE_BIGENDIAN
-#define BE_DEF(s) s
-#define LE_DEF(s) NULL
-#else
-#define BE_DEF(s) NULL
-#define LE_DEF(s) s
-#endif
-
-PCMDEF(f64be, "PCM 64 bit floating-point big-endian format",
-       NULL, CODEC_ID_PCM_F64BE)
-
-PCMDEF(f64le, "PCM 64 bit floating-point little-endian format",
-       NULL, CODEC_ID_PCM_F64LE)
-
-PCMDEF(f32be, "PCM 32 bit floating-point big-endian format",
-       NULL, CODEC_ID_PCM_F32BE)
-
-PCMDEF(f32le, "PCM 32 bit floating-point little-endian format",
-       NULL, CODEC_ID_PCM_F32LE)
-
-PCMDEF(s32be, "PCM signed 32 bit big-endian format",
-       NULL, CODEC_ID_PCM_S32BE)
-
-PCMDEF(s32le, "PCM signed 32 bit little-endian format",
-       NULL, CODEC_ID_PCM_S32LE)
-
-PCMDEF(s24be, "PCM signed 24 bit big-endian format",
-       NULL, CODEC_ID_PCM_S24BE)
-
-PCMDEF(s24le, "PCM signed 24 bit little-endian format",
-       NULL, CODEC_ID_PCM_S24LE)
-
-PCMDEF(s16be, "PCM signed 16 bit big-endian format",
-       BE_DEF("sw"), CODEC_ID_PCM_S16BE)
-
-PCMDEF(s16le, "PCM signed 16 bit little-endian format",
-       LE_DEF("sw"), CODEC_ID_PCM_S16LE)
-
-PCMDEF(s8, "PCM signed 8 bit format",
-       "sb", CODEC_ID_PCM_S8)
-
-PCMDEF(u32be, "PCM unsigned 32 bit big-endian format",
-       NULL, CODEC_ID_PCM_U32BE)
-
-PCMDEF(u32le, "PCM unsigned 32 bit little-endian format",
-       NULL, CODEC_ID_PCM_U32LE)
-
-PCMDEF(u24be, "PCM unsigned 24 bit big-endian format",
-       NULL, CODEC_ID_PCM_U24BE)
-
-PCMDEF(u24le, "PCM unsigned 24 bit little-endian format",
-       NULL, CODEC_ID_PCM_U24LE)
-
-PCMDEF(u16be, "PCM unsigned 16 bit big-endian format",
-       BE_DEF("uw"), CODEC_ID_PCM_U16BE)
-
-PCMDEF(u16le, "PCM unsigned 16 bit little-endian format",
-       LE_DEF("uw"), CODEC_ID_PCM_U16LE)
-
-PCMDEF(u8, "PCM unsigned 8 bit format",
-       "ub", CODEC_ID_PCM_U8)
-
-PCMDEF(alaw, "PCM A-law format",
-       "al", CODEC_ID_PCM_ALAW)
-
-PCMDEF(mulaw, "PCM mu-law format",
-       "ul", CODEC_ID_PCM_MULAW)
diff --git a/libavformat/raw.h b/libavformat/raw.h
deleted file mode 100644
index 497c8be..0000000
--- a/libavformat/raw.h
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * RAW muxer and demuxer
- * Copyright (C) 2007  Aurelien Jacobs <aurel at gnuage.org>
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-#ifndef AVFORMAT_RAW_H
-#define AVFORMAT_RAW_H
-
-#include "avformat.h"
-
-int pcm_read_seek(AVFormatContext *s,
-                  int stream_index, int64_t timestamp, int flags);
-
-int ff_raw_read_partial_packet(AVFormatContext *s, AVPacket *pkt);
-
-#endif /* AVFORMAT_RAW_H */
diff --git a/libavformat/rawdec.c b/libavformat/rawdec.c
new file mode 100644
index 0000000..7df63a1
--- /dev/null
+++ b/libavformat/rawdec.c
@@ -0,0 +1,236 @@
+/*
+ * RAW demuxers
+ * Copyright (c) 2001 Fabrice Bellard
+ * Copyright (c) 2005 Alex Beregszaszi
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "avformat.h"
+#include "avio_internal.h"
+#include "rawdec.h"
+
+/* raw input */
+int ff_raw_read_header(AVFormatContext *s, AVFormatParameters *ap)
+{
+    AVStream *st;
+    enum CodecID id;
+
+    st = av_new_stream(s, 0);
+    if (!st)
+        return AVERROR(ENOMEM);
+
+        id = s->iformat->value;
+        if (id == CODEC_ID_RAWVIDEO) {
+            st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
+        } else {
+            st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
+        }
+        st->codec->codec_id = id;
+
+        switch(st->codec->codec_type) {
+        case AVMEDIA_TYPE_AUDIO:
+            st->codec->sample_rate = ap->sample_rate;
+            if(ap->channels) st->codec->channels = ap->channels;
+            else             st->codec->channels = 1;
+            st->codec->bits_per_coded_sample = av_get_bits_per_sample(st->codec->codec_id);
+            assert(st->codec->bits_per_coded_sample > 0);
+            st->codec->block_align = st->codec->bits_per_coded_sample*st->codec->channels/8;
+            av_set_pts_info(st, 64, 1, st->codec->sample_rate);
+            break;
+        case AVMEDIA_TYPE_VIDEO:
+            if(ap->time_base.num)
+                av_set_pts_info(st, 64, ap->time_base.num, ap->time_base.den);
+            else
+                av_set_pts_info(st, 64, 1, 25);
+            st->codec->width = ap->width;
+            st->codec->height = ap->height;
+            st->codec->pix_fmt = ap->pix_fmt;
+            if(st->codec->pix_fmt == PIX_FMT_NONE)
+                st->codec->pix_fmt= PIX_FMT_YUV420P;
+            break;
+        default:
+            return -1;
+        }
+    return 0;
+}
+
+#define RAW_PACKET_SIZE 1024
+
+int ff_raw_read_partial_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    int ret, size;
+
+    size = RAW_PACKET_SIZE;
+
+    if (av_new_packet(pkt, size) < 0)
+        return AVERROR(ENOMEM);
+
+    pkt->pos= avio_tell(s->pb);
+    pkt->stream_index = 0;
+    ret = ffio_read_partial(s->pb, pkt->data, size);
+    if (ret < 0) {
+        av_free_packet(pkt);
+        return ret;
+    }
+    pkt->size = ret;
+    return ret;
+}
+
+int ff_raw_audio_read_header(AVFormatContext *s,
+                             AVFormatParameters *ap)
+{
+    AVStream *st = av_new_stream(s, 0);
+    if (!st)
+        return AVERROR(ENOMEM);
+    st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
+    st->codec->codec_id = s->iformat->value;
+    st->need_parsing = AVSTREAM_PARSE_FULL;
+    /* the parameters will be extracted from the compressed bitstream */
+
+    return 0;
+}
+
+/* MPEG-1/H.263 input */
+int ff_raw_video_read_header(AVFormatContext *s,
+                             AVFormatParameters *ap)
+{
+    AVStream *st;
+
+    st = av_new_stream(s, 0);
+    if (!st)
+        return AVERROR(ENOMEM);
+
+    st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
+    st->codec->codec_id = s->iformat->value;
+    st->need_parsing = AVSTREAM_PARSE_FULL;
+
+    /* for MJPEG, specify frame rate */
+    /* for MPEG-4 specify it, too (most MPEG-4 streams do not have the fixed_vop_rate set ...)*/
+    if (ap->time_base.num) {
+        st->codec->time_base= ap->time_base;
+    } else if ( st->codec->codec_id == CODEC_ID_MJPEG ||
+                st->codec->codec_id == CODEC_ID_MPEG4 ||
+                st->codec->codec_id == CODEC_ID_DIRAC ||
+                st->codec->codec_id == CODEC_ID_DNXHD ||
+                st->codec->codec_id == CODEC_ID_VC1   ||
+                st->codec->codec_id == CODEC_ID_H264) {
+        st->codec->time_base= (AVRational){1,25};
+    }
+    av_set_pts_info(st, 64, 1, 1200000);
+
+    return 0;
+}
+
+/* Note: Do not forget to add new entries to the Makefile as well. */
+
+#if CONFIG_G722_DEMUXER
+AVInputFormat ff_g722_demuxer = {
+    "g722",
+    NULL_IF_CONFIG_SMALL("raw G.722"),
+    0,
+    NULL,
+    ff_raw_read_header,
+    ff_raw_read_partial_packet,
+    .flags= AVFMT_GENERIC_INDEX,
+    .extensions = "g722,722",
+    .value = CODEC_ID_ADPCM_G722,
+};
+#endif
+
+#if CONFIG_GSM_DEMUXER
+AVInputFormat ff_gsm_demuxer = {
+    "gsm",
+    NULL_IF_CONFIG_SMALL("raw GSM"),
+    0,
+    NULL,
+    ff_raw_audio_read_header,
+    ff_raw_read_partial_packet,
+    .flags= AVFMT_GENERIC_INDEX,
+    .extensions = "gsm",
+    .value = CODEC_ID_GSM,
+};
+#endif
+
+#if CONFIG_MJPEG_DEMUXER
+AVInputFormat ff_mjpeg_demuxer = {
+    "mjpeg",
+    NULL_IF_CONFIG_SMALL("raw MJPEG video"),
+    0,
+    NULL,
+    ff_raw_video_read_header,
+    ff_raw_read_partial_packet,
+    .flags= AVFMT_GENERIC_INDEX,
+    .extensions = "mjpg,mjpeg",
+    .value = CODEC_ID_MJPEG,
+};
+#endif
+
+#if CONFIG_MLP_DEMUXER
+AVInputFormat ff_mlp_demuxer = {
+    "mlp",
+    NULL_IF_CONFIG_SMALL("raw MLP"),
+    0,
+    NULL,
+    ff_raw_audio_read_header,
+    ff_raw_read_partial_packet,
+    .flags= AVFMT_GENERIC_INDEX,
+    .extensions = "mlp",
+    .value = CODEC_ID_MLP,
+};
+#endif
+
+#if CONFIG_TRUEHD_DEMUXER
+AVInputFormat ff_truehd_demuxer = {
+    "truehd",
+    NULL_IF_CONFIG_SMALL("raw TrueHD"),
+    0,
+    NULL,
+    ff_raw_audio_read_header,
+    ff_raw_read_partial_packet,
+    .flags= AVFMT_GENERIC_INDEX,
+    .extensions = "thd",
+    .value = CODEC_ID_TRUEHD,
+};
+#endif
+
+#if CONFIG_SHORTEN_DEMUXER
+AVInputFormat ff_shorten_demuxer = {
+    "shn",
+    NULL_IF_CONFIG_SMALL("raw Shorten"),
+    0,
+    NULL,
+    ff_raw_audio_read_header,
+    ff_raw_read_partial_packet,
+    .flags= AVFMT_GENERIC_INDEX,
+    .extensions = "shn",
+    .value = CODEC_ID_SHORTEN,
+};
+#endif
+
+#if CONFIG_VC1_DEMUXER
+AVInputFormat ff_vc1_demuxer = {
+    "vc1",
+    NULL_IF_CONFIG_SMALL("raw VC-1"),
+    0,
+    NULL /* vc1_probe */,
+    ff_raw_video_read_header,
+    ff_raw_read_partial_packet,
+    .extensions = "vc1",
+    .value = CODEC_ID_VC1,
+};
+#endif
diff --git a/libavformat/rawdec.h b/libavformat/rawdec.h
new file mode 100644
index 0000000..82672b7
--- /dev/null
+++ b/libavformat/rawdec.h
@@ -0,0 +1,35 @@
+/*
+ * RAW demuxers
+ * Copyright (C) 2007  Aurelien Jacobs <aurel at gnuage.org>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVFORMAT_RAWDEC_H
+#define AVFORMAT_RAWDEC_H
+
+#include "avformat.h"
+
+int ff_raw_read_header(AVFormatContext *s, AVFormatParameters *ap);
+
+int ff_raw_read_partial_packet(AVFormatContext *s, AVPacket *pkt);
+
+int ff_raw_audio_read_header(AVFormatContext *s, AVFormatParameters *ap);
+
+int ff_raw_video_read_header(AVFormatContext *s, AVFormatParameters *ap);
+
+#endif /* AVFORMAT_RAWDEC_H */
diff --git a/libavformat/rawenc.c b/libavformat/rawenc.c
new file mode 100644
index 0000000..00e43df
--- /dev/null
+++ b/libavformat/rawenc.c
@@ -0,0 +1,300 @@
+/*
+ * RAW muxers
+ * Copyright (c) 2001 Fabrice Bellard
+ * Copyright (c) 2005 Alex Beregszaszi
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "avformat.h"
+#include "rawenc.h"
+
+int ff_raw_write_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    avio_write(s->pb, pkt->data, pkt->size);
+    avio_flush(s->pb);
+    return 0;
+}
+
+/* Note: Do not forget to add new entries to the Makefile as well. */
+
+#if CONFIG_AC3_MUXER
+AVOutputFormat ff_ac3_muxer = {
+    "ac3",
+    NULL_IF_CONFIG_SMALL("raw AC-3"),
+    "audio/x-ac3",
+    "ac3",
+    0,
+    CODEC_ID_AC3,
+    CODEC_ID_NONE,
+    NULL,
+    ff_raw_write_packet,
+    .flags= AVFMT_NOTIMESTAMPS,
+};
+#endif
+
+#if CONFIG_DIRAC_MUXER
+AVOutputFormat ff_dirac_muxer = {
+    "dirac",
+    NULL_IF_CONFIG_SMALL("raw Dirac"),
+    NULL,
+    "drc",
+    0,
+    CODEC_ID_NONE,
+    CODEC_ID_DIRAC,
+    NULL,
+    ff_raw_write_packet,
+    .flags= AVFMT_NOTIMESTAMPS,
+};
+#endif
+
+#if CONFIG_DNXHD_MUXER
+AVOutputFormat ff_dnxhd_muxer = {
+    "dnxhd",
+    NULL_IF_CONFIG_SMALL("raw DNxHD (SMPTE VC-3)"),
+    NULL,
+    "dnxhd",
+    0,
+    CODEC_ID_NONE,
+    CODEC_ID_DNXHD,
+    NULL,
+    ff_raw_write_packet,
+    .flags= AVFMT_NOTIMESTAMPS,
+};
+#endif
+
+#if CONFIG_DTS_MUXER
+AVOutputFormat ff_dts_muxer = {
+    "dts",
+    NULL_IF_CONFIG_SMALL("raw DTS"),
+    "audio/x-dca",
+    "dts",
+    0,
+    CODEC_ID_DTS,
+    CODEC_ID_NONE,
+    NULL,
+    ff_raw_write_packet,
+    .flags= AVFMT_NOTIMESTAMPS,
+};
+#endif
+
+#if CONFIG_EAC3_MUXER
+AVOutputFormat ff_eac3_muxer = {
+    "eac3",
+    NULL_IF_CONFIG_SMALL("raw E-AC-3"),
+    "audio/x-eac3",
+    "eac3",
+    0,
+    CODEC_ID_EAC3,
+    CODEC_ID_NONE,
+    NULL,
+    ff_raw_write_packet,
+    .flags= AVFMT_NOTIMESTAMPS,
+};
+#endif
+
+#if CONFIG_G722_MUXER
+AVOutputFormat ff_g722_muxer = {
+    "g722",
+    NULL_IF_CONFIG_SMALL("raw G.722"),
+    "audio/G722",
+    "g722",
+    0,
+    CODEC_ID_ADPCM_G722,
+    CODEC_ID_NONE,
+    NULL,
+    ff_raw_write_packet,
+    .flags= AVFMT_NOTIMESTAMPS,
+};
+#endif
+
+#if CONFIG_H261_MUXER
+AVOutputFormat ff_h261_muxer = {
+    "h261",
+    NULL_IF_CONFIG_SMALL("raw H.261"),
+    "video/x-h261",
+    "h261",
+    0,
+    CODEC_ID_NONE,
+    CODEC_ID_H261,
+    NULL,
+    ff_raw_write_packet,
+    .flags= AVFMT_NOTIMESTAMPS,
+};
+#endif
+
+#if CONFIG_H263_MUXER
+AVOutputFormat ff_h263_muxer = {
+    "h263",
+    NULL_IF_CONFIG_SMALL("raw H.263"),
+    "video/x-h263",
+    "h263",
+    0,
+    CODEC_ID_NONE,
+    CODEC_ID_H263,
+    NULL,
+    ff_raw_write_packet,
+    .flags= AVFMT_NOTIMESTAMPS,
+};
+#endif
+
+#if CONFIG_H264_MUXER
+AVOutputFormat ff_h264_muxer = {
+    "h264",
+    NULL_IF_CONFIG_SMALL("raw H.264 video format"),
+    NULL,
+    "h264",
+    0,
+    CODEC_ID_NONE,
+    CODEC_ID_H264,
+    NULL,
+    ff_raw_write_packet,
+    .flags= AVFMT_NOTIMESTAMPS,
+};
+#endif
+
+#if CONFIG_CAVSVIDEO_MUXER
+AVOutputFormat ff_cavsvideo_muxer = {
+    "cavsvideo",
+    NULL_IF_CONFIG_SMALL("raw Chinese AVS video"),
+    NULL,
+    "cavs",
+    0,
+    CODEC_ID_NONE,
+    CODEC_ID_CAVS,
+    NULL,
+    ff_raw_write_packet,
+    .flags= AVFMT_NOTIMESTAMPS,
+};
+#endif
+
+#if CONFIG_M4V_MUXER
+AVOutputFormat ff_m4v_muxer = {
+    "m4v",
+    NULL_IF_CONFIG_SMALL("raw MPEG-4 video format"),
+    NULL,
+    "m4v",
+    0,
+    CODEC_ID_NONE,
+    CODEC_ID_MPEG4,
+    NULL,
+    ff_raw_write_packet,
+    .flags= AVFMT_NOTIMESTAMPS,
+};
+#endif
+
+#if CONFIG_MJPEG_MUXER
+AVOutputFormat ff_mjpeg_muxer = {
+    "mjpeg",
+    NULL_IF_CONFIG_SMALL("raw MJPEG video"),
+    "video/x-mjpeg",
+    "mjpg,mjpeg",
+    0,
+    CODEC_ID_NONE,
+    CODEC_ID_MJPEG,
+    NULL,
+    ff_raw_write_packet,
+    .flags= AVFMT_NOTIMESTAMPS,
+};
+#endif
+
+#if CONFIG_MLP_MUXER
+AVOutputFormat ff_mlp_muxer = {
+    "mlp",
+    NULL_IF_CONFIG_SMALL("raw MLP"),
+    NULL,
+    "mlp",
+    0,
+    CODEC_ID_MLP,
+    CODEC_ID_NONE,
+    NULL,
+    ff_raw_write_packet,
+    .flags= AVFMT_NOTIMESTAMPS,
+};
+#endif
+
+#if CONFIG_SRT_MUXER
+AVOutputFormat ff_srt_muxer = {
+    .name           = "srt",
+    .long_name      = NULL_IF_CONFIG_SMALL("SubRip subtitle format"),
+    .mime_type      = "application/x-subrip",
+    .extensions     = "srt",
+    .write_packet   = ff_raw_write_packet,
+    .flags          = AVFMT_NOTIMESTAMPS,
+    .subtitle_codec = CODEC_ID_SRT,
+};
+#endif
+
+#if CONFIG_TRUEHD_MUXER
+AVOutputFormat ff_truehd_muxer = {
+    "truehd",
+    NULL_IF_CONFIG_SMALL("raw TrueHD"),
+    NULL,
+    "thd",
+    0,
+    CODEC_ID_TRUEHD,
+    CODEC_ID_NONE,
+    NULL,
+    ff_raw_write_packet,
+    .flags= AVFMT_NOTIMESTAMPS,
+};
+#endif
+
+#if CONFIG_MPEG1VIDEO_MUXER
+AVOutputFormat ff_mpeg1video_muxer = {
+    "mpeg1video",
+    NULL_IF_CONFIG_SMALL("raw MPEG-1 video"),
+    "video/x-mpeg",
+    "mpg,mpeg,m1v",
+    0,
+    CODEC_ID_NONE,
+    CODEC_ID_MPEG1VIDEO,
+    NULL,
+    ff_raw_write_packet,
+    .flags= AVFMT_NOTIMESTAMPS,
+};
+#endif
+
+#if CONFIG_MPEG2VIDEO_MUXER
+AVOutputFormat ff_mpeg2video_muxer = {
+    "mpeg2video",
+    NULL_IF_CONFIG_SMALL("raw MPEG-2 video"),
+    NULL,
+    "m2v",
+    0,
+    CODEC_ID_NONE,
+    CODEC_ID_MPEG2VIDEO,
+    NULL,
+    ff_raw_write_packet,
+    .flags= AVFMT_NOTIMESTAMPS,
+};
+#endif
+
+#if CONFIG_RAWVIDEO_MUXER
+AVOutputFormat ff_rawvideo_muxer = {
+    "rawvideo",
+    NULL_IF_CONFIG_SMALL("raw video format"),
+    NULL,
+    "yuv,rgb",
+    0,
+    CODEC_ID_NONE,
+    CODEC_ID_RAWVIDEO,
+    NULL,
+    ff_raw_write_packet,
+    .flags= AVFMT_NOTIMESTAMPS,
+};
+#endif
diff --git a/libavformat/rawenc.h b/libavformat/rawenc.h
new file mode 100644
index 0000000..daa5489
--- /dev/null
+++ b/libavformat/rawenc.h
@@ -0,0 +1,29 @@
+/*
+ * RAW muxers
+ * Copyright (C) 2007  Aurelien Jacobs <aurel at gnuage.org>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVFORMAT_RAWENC_H
+#define AVFORMAT_RAWENC_H
+
+#include "avformat.h"
+
+int ff_raw_write_packet(AVFormatContext *s, AVPacket *pkt);
+
+#endif /* AVFORMAT_RAWENC_H */
diff --git a/libavformat/rawvideodec.c b/libavformat/rawvideodec.c
new file mode 100644
index 0000000..a29f7da
--- /dev/null
+++ b/libavformat/rawvideodec.c
@@ -0,0 +1,57 @@
+/*
+ * RAW video demuxer
+ * Copyright (c) 2001 Fabrice Bellard
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "avformat.h"
+#include "rawdec.h"
+
+static int rawvideo_read_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    int packet_size, ret, width, height;
+    AVStream *st = s->streams[0];
+
+    width = st->codec->width;
+    height = st->codec->height;
+
+    packet_size = avpicture_get_size(st->codec->pix_fmt, width, height);
+    if (packet_size < 0)
+        return -1;
+
+    ret= av_get_packet(s->pb, pkt, packet_size);
+    pkt->pts=
+    pkt->dts= pkt->pos / packet_size;
+
+    pkt->stream_index = 0;
+    if (ret < 0)
+        return ret;
+    return 0;
+}
+
+AVInputFormat ff_rawvideo_demuxer = {
+    "rawvideo",
+    NULL_IF_CONFIG_SMALL("raw video format"),
+    0,
+    NULL,
+    ff_raw_read_header,
+    rawvideo_read_packet,
+    .flags= AVFMT_GENERIC_INDEX,
+    .extensions = "yuv,cif,qcif,rgb",
+    .value = CODEC_ID_RAWVIDEO,
+};
diff --git a/libavformat/rdt.c b/libavformat/rdt.c
index 7dda3f3..dfb31d1 100644
--- a/libavformat/rdt.c
+++ b/libavformat/rdt.c
@@ -2,20 +2,20 @@
  * Realmedia RTSP protocol (RDT) support.
  * Copyright (c) 2007 Ronald S. Bultje
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -33,6 +33,7 @@
 #include "libavutil/md5.h"
 #include "rm.h"
 #include "internal.h"
+#include "avio_internal.h"
 #include "libavcodec/get_bits.h"
 
 struct RDTDemuxContext {
@@ -63,7 +64,7 @@ ff_rdt_parse_open(AVFormatContext *ic, int first_stream_of_set_idx,
     do {
         s->n_streams++;
     } while (first_stream_of_set_idx + s->n_streams < ic->nb_streams &&
-             s->streams[s->n_streams]->priv_data == s->streams[0]->priv_data);
+             s->streams[s->n_streams]->id == s->streams[0]->id);
     s->prev_set_id    = -1;
     s->prev_stream_id = -1;
     s->prev_timestamp = -1;
@@ -76,17 +77,13 @@ ff_rdt_parse_open(AVFormatContext *ic, int first_stream_of_set_idx,
 void
 ff_rdt_parse_close(RDTDemuxContext *s)
 {
-    int i;
-
-    for (i = 1; i < s->n_streams; i++)
-        s->streams[i]->priv_data = NULL;
-
     av_free(s);
 }
 
 struct PayloadContext {
     AVFormatContext *rmctx;
-    RMStream *rmst[MAX_STREAMS];
+    int nb_rmst;
+    RMStream **rmst;
     uint8_t *mlti_data;
     unsigned int mlti_data_size;
     char buffer[RTP_MAX_PACKET_LENGTH + FF_INPUT_BUFFER_PADDING_SIZE];
@@ -134,50 +131,50 @@ ff_rdt_calc_response_and_checksum(char response[41], char chksum[9],
 static int
 rdt_load_mdpr (PayloadContext *rdt, AVStream *st, int rule_nr)
 {
-    ByteIOContext pb;
+    AVIOContext pb;
     int size;
     uint32_t tag;
 
     /**
      * Layout of the MLTI chunk:
-     * 4:MLTI
-     * 2:<number of streams>
+     * 4: MLTI
+     * 2: number of streams
      * Then for each stream ([number_of_streams] times):
-     *     2:<mdpr index>
-     * 2:<number of mdpr chunks>
+     *     2: mdpr index
+     * 2: number of mdpr chunks
      * Then for each mdpr chunk ([number_of_mdpr_chunks] times):
-     *     4:<size>
-     *     [size]:<data>
+     *     4: size
+     *     [size]: data
      * we skip MDPR chunks until we reach the one of the stream
      * we're interested in, and forward that ([size]+[data]) to
      * the RM demuxer to parse the stream-specific header data.
      */
     if (!rdt->mlti_data)
         return -1;
-    init_put_byte(&pb, rdt->mlti_data, rdt->mlti_data_size, 0,
+    ffio_init_context(&pb, rdt->mlti_data, rdt->mlti_data_size, 0,
                   NULL, NULL, NULL, NULL);
-    tag = get_le32(&pb);
+    tag = avio_rl32(&pb);
     if (tag == MKTAG('M', 'L', 'T', 'I')) {
         int num, chunk_nr;
 
         /* read index of MDPR chunk numbers */
-        num = get_be16(&pb);
+        num = avio_rb16(&pb);
         if (rule_nr < 0 || rule_nr >= num)
             return -1;
-        url_fskip(&pb, rule_nr * 2);
-        chunk_nr = get_be16(&pb);
-        url_fskip(&pb, (num - 1 - rule_nr) * 2);
+        avio_skip(&pb, rule_nr * 2);
+        chunk_nr = avio_rb16(&pb);
+        avio_skip(&pb, (num - 1 - rule_nr) * 2);
 
         /* read MDPR chunks */
-        num = get_be16(&pb);
+        num = avio_rb16(&pb);
         if (chunk_nr >= num)
             return -1;
         while (chunk_nr--)
-            url_fskip(&pb, get_be32(&pb));
-        size = get_be32(&pb);
+            avio_skip(&pb, avio_rb32(&pb));
+        size = avio_rb32(&pb);
     } else {
         size = rdt->mlti_data_size;
-        url_fseek(&pb, 0, SEEK_SET);
+        avio_seek(&pb, 0, SEEK_SET);
     }
     if (ff_rm_read_mdpr_codecdata(rdt->rmctx, &pb, st, rdt->rmst[st->index], size) < 0)
         return -1;
@@ -299,22 +296,22 @@ rdt_parse_packet (AVFormatContext *ctx, PayloadContext *rdt, AVStream *st,
                   const uint8_t *buf, int len, int flags)
 {
     int seq = 1, res;
-    ByteIOContext pb;
+    AVIOContext pb;
 
     if (rdt->audio_pkt_cnt == 0) {
         int pos;
 
-        init_put_byte(&pb, buf, len, 0, NULL, NULL, NULL, NULL);
+        ffio_init_context(&pb, buf, len, 0, NULL, NULL, NULL, NULL);
         flags = (flags & RTP_FLAG_KEY) ? 2 : 0;
         res = ff_rm_parse_packet (rdt->rmctx, &pb, st, rdt->rmst[st->index], len, pkt,
                                   &seq, flags, *timestamp);
-        pos = url_ftell(&pb);
+        pos = avio_tell(&pb);
         if (res < 0)
             return res;
         if (res > 0) {
             if (st->codec->codec_id == CODEC_ID_AAC) {
                 memcpy (rdt->buffer, buf + pos, len - pos);
-                rdt->rmctx->pb = av_alloc_put_byte (rdt->buffer, len - pos, 0,
+                rdt->rmctx->pb = avio_alloc_context (rdt->buffer, len - pos, 0,
                                                     NULL, NULL, NULL, NULL);
             }
             goto get_cache;
@@ -336,8 +333,9 @@ get_cache:
 
 int
 ff_rdt_parse_packet(RDTDemuxContext *s, AVPacket *pkt,
-                    const uint8_t *buf, int len)
+                    uint8_t **bufptr, int len)
 {
+    uint8_t *buf = bufptr ? *bufptr : NULL;
     int seq_no, flags = 0, stream_id, set_id, is_keyframe;
     uint32_t timestamp;
     int rv= 0;
@@ -420,8 +418,18 @@ rdt_parse_sdp_line (AVFormatContext *s, int st_index,
         int n, first = -1;
 
         for (n = 0; n < s->nb_streams; n++)
-            if (s->streams[n]->priv_data == stream->priv_data) {
+            if (s->streams[n]->id == stream->id) {
+                int count = s->streams[n]->index + 1;
                 if (first == -1) first = n;
+                if (rdt->nb_rmst < count) {
+                    RMStream **rmst= av_realloc(rdt->rmst, count*sizeof(*rmst));
+                    if (!rmst)
+                        return AVERROR(ENOMEM);
+                    memset(rmst + rdt->nb_rmst, 0,
+                           (count - rdt->nb_rmst) * sizeof(*rmst));
+                    rdt->rmst    = rmst;
+                    rdt->nb_rmst = count;
+                }
                 rdt->rmst[s->streams[n]->index] = ff_rm_alloc_rmstream();
                 rdt_load_mdpr(rdt, s->streams[n], (n - first) * 2);
 
@@ -451,10 +459,9 @@ add_dstream(AVFormatContext *s, AVStream *orig_st)
 {
     AVStream *st;
 
-    if (!(st = av_new_stream(s, 0)))
+    if (!(st = av_new_stream(s, orig_st->id)))
         return NULL;
     st->codec->codec_type = orig_st->codec->codec_type;
-    st->priv_data         = orig_st->priv_data;
     st->first_dts         = orig_st->first_dts;
 
     return st;
@@ -465,7 +472,7 @@ real_parse_asm_rulebook(AVFormatContext *s, AVStream *orig_st,
                         const char *p)
 {
     const char *end;
-    int n_rules, odd = 0;
+    int n_rules = 0, odd = 0;
     AVStream *st;
 
     /**
@@ -483,7 +490,7 @@ real_parse_asm_rulebook(AVFormatContext *s, AVStream *orig_st,
      * for multi-bitrate streams.
      */
     if (*p == '\"') p++;
-    for (n_rules = 0; s->nb_streams < MAX_STREAMS;) {
+    while (1) {
         if (!(end = strchr(p, ';')))
             break;
         if (!odd && end != p) {
@@ -491,6 +498,8 @@ real_parse_asm_rulebook(AVFormatContext *s, AVStream *orig_st,
                 st = add_dstream(s, orig_st);
             else
                 st = orig_st;
+            if (!st)
+                break;
             real_parse_asm_rule(st, p, end);
             n_rules++;
         }
@@ -514,7 +523,7 @@ rdt_new_context (void)
 {
     PayloadContext *rdt = av_mallocz(sizeof(PayloadContext));
 
-    av_open_input_stream(&rdt->rmctx, NULL, "", &rdt_demuxer, NULL);
+    av_open_input_stream(&rdt->rmctx, NULL, "", &ff_rdt_demuxer, NULL);
 
     return rdt;
 }
@@ -524,7 +533,7 @@ rdt_free_context (PayloadContext *rdt)
 {
     int i;
 
-    for (i = 0; i < MAX_STREAMS; i++)
+    for (i = 0; i < rdt->nb_rmst; i++)
         if (rdt->rmst[i]) {
             ff_rm_free_rmstream(rdt->rmst[i]);
             av_freep(&rdt->rmst[i]);
@@ -532,6 +541,7 @@ rdt_free_context (PayloadContext *rdt)
     if (rdt->rmctx)
         av_close_input_stream(rdt->rmctx);
     av_freep(&rdt->mlti_data);
+    av_freep(&rdt->rmst);
     av_free(rdt);
 }
 
@@ -544,7 +554,7 @@ static RTPDynamicProtocolHandler ff_rdt_ ## n ## _handler = { \
     .open             = rdt_new_context, \
     .close            = rdt_free_context, \
     .parse_packet     = rdt_parse_packet \
-};
+}
 
 RDT_HANDLER(live_video, "x-pn-multirate-realvideo-live", AVMEDIA_TYPE_VIDEO);
 RDT_HANDLER(live_audio, "x-pn-multirate-realaudio-live", AVMEDIA_TYPE_AUDIO);
diff --git a/libavformat/rdt.h b/libavformat/rdt.h
index 1592c2f..08b17bc 100644
--- a/libavformat/rdt.h
+++ b/libavformat/rdt.h
@@ -2,20 +2,20 @@
  * Realmedia RTSP (RDT) definitions
  * Copyright (c) 2007 Ronald S. Bultje <rbultje at ronald.bitfreak.net>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -85,7 +85,7 @@ void ff_rdt_subscribe_rule(char *cmd, int size,
  * @param stream_id will be set to the stream ID this packet belongs to
  * @param is_keyframe will be whether this packet belongs to a keyframe
  * @param timestamp will be set to the timestamp of the packet
- * @return the amount of bytes consumed, or <0 on error
+ * @return the amount of bytes consumed, or negative on error
  */
 int ff_rdt_parse_header(const uint8_t *buf, int len,
                         int *set_id, int *seq_no, int *stream_id,
@@ -96,7 +96,7 @@ int ff_rdt_parse_header(const uint8_t *buf, int len,
  * Usage similar to rtp_parse_packet().
  */
 int ff_rdt_parse_packet(RDTDemuxContext *s, AVPacket *pkt,
-                        const uint8_t *buf, int len);
+                        uint8_t **buf, int len);
 
 /**
  * Parse a server-related SDP line.
diff --git a/libavformat/riff.c b/libavformat/riff.c
index 04b7108..c73152d 100644
--- a/libavformat/riff.c
+++ b/libavformat/riff.c
@@ -2,25 +2,26 @@
  * RIFF codec tags
  * Copyright (c) 2000 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "libavcodec/avcodec.h"
 #include "avformat.h"
+#include "avio_internal.h"
 #include "riff.h"
 #include "libavcodec/bytestream.h"
 
@@ -59,6 +60,7 @@ const AVCodecTag ff_codec_bmp_tags[] = {
     { 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') },
@@ -81,8 +83,8 @@ const AVCodecTag ff_codec_bmp_tags[] = {
     { 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_MSMPEG4V3,    MKTAG('D', 'I', 'V', '3') }, /* default signature when using MSMPEG4 */
     { 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') },
@@ -123,6 +125,7 @@ const AVCodecTag ff_codec_bmp_tags[] = {
     { 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_MJPEG,        MKTAG('M', 'J', 'P', 'G') },
     { CODEC_ID_MJPEG,        MKTAG('L', 'J', 'P', 'G') },
     { CODEC_ID_MJPEG,        MKTAG('d', 'm', 'b', '1') },
@@ -130,6 +133,7 @@ const AVCodecTag ff_codec_bmp_tags[] = {
     { 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') },
@@ -159,6 +163,7 @@ const AVCodecTag ff_codec_bmp_tags[] = {
     { 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('U', 'Y', 'V', 'Y') },
@@ -168,7 +173,15 @@ const AVCodecTag ff_codec_bmp_tags[] = {
     { 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_FRWU,         MKTAG('F', 'R', 'W', 'U') },
+    { CODEC_ID_R10K,         MKTAG('R', '1', '0', 'k') },
     { CODEC_ID_R210,         MKTAG('r', '2', '1', '0') },
     { CODEC_ID_V210,         MKTAG('v', '2', '1', '0') },
     { CODEC_ID_INDEO3,       MKTAG('I', 'V', '3', '1') },
@@ -183,6 +196,7 @@ const AVCodecTag ff_codec_bmp_tags[] = {
     { 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') },
@@ -215,8 +229,10 @@ const AVCodecTag ff_codec_bmp_tags[] = {
     { CODEC_ID_QPEG,         MKTAG('Q', '1', '.', '0') },
     { CODEC_ID_QPEG,         MKTAG('Q', '1', '.', '1') },
     { CODEC_ID_WMV3,         MKTAG('W', 'M', 'V', '3') },
+    { CODEC_ID_WMV3,         MKTAG('W', 'M', 'V', 'P') },
     { CODEC_ID_VC1,          MKTAG('W', 'V', 'C', '1') },
     { CODEC_ID_VC1,          MKTAG('W', 'M', 'V', 'A') },
+    { CODEC_ID_VC1,          MKTAG('W', 'V', 'P', '2') },
     { CODEC_ID_LOCO,         MKTAG('L', 'O', 'C', 'O') },
     { CODEC_ID_WNV1,         MKTAG('W', 'N', 'V', '1') },
     { CODEC_ID_AASC,         MKTAG('A', 'A', 'S', 'C') },
@@ -243,6 +259,7 @@ const AVCodecTag ff_codec_bmp_tags[] = {
     { CODEC_ID_AURA2,        MKTAG('A', 'U', 'R', '2') },
     { CODEC_ID_DPX,          MKTAG('d', 'p', 'x', ' ') },
     { CODEC_ID_KGV1,         MKTAG('K', 'G', 'V', '1') },
+    { CODEC_ID_LAGARITH,     MKTAG('L', 'A', 'G', 'S') },
     { CODEC_ID_NONE,         0 }
 };
 
@@ -279,9 +296,12 @@ const AVCodecTag ff_codec_wav_tags[] = {
     { CODEC_ID_WMALOSSLESS,     0x0163 },
     { CODEC_ID_ADPCM_CT,        0x0200 },
     { CODEC_ID_ATRAC3,          0x0270 },
+    { CODEC_ID_ADPCM_G722,      0x028F },
     { CODEC_ID_IMC,             0x0401 },
     { CODEC_ID_GSM_MS,          0x1500 },
     { CODEC_ID_TRUESPEECH,      0x1501 },
+    { CODEC_ID_AAC,             0x1600 }, /* ADTS AAC */
+    { CODEC_ID_AAC_LATM,        0x1602 },
     { CODEC_ID_AC3,             0x2000 },
     { CODEC_ID_DTS,             0x2001 },
     { CODEC_ID_SONIC,           0x2048 },
@@ -302,26 +322,26 @@ const AVCodecTag ff_codec_wav_tags[] = {
 };
 
 #if CONFIG_MUXERS
-int64_t ff_start_tag(ByteIOContext *pb, const char *tag)
+int64_t ff_start_tag(AVIOContext *pb, const char *tag)
 {
-    put_tag(pb, tag);
-    put_le32(pb, 0);
-    return url_ftell(pb);
+    ffio_wfourcc(pb, tag);
+    avio_wl32(pb, 0);
+    return avio_tell(pb);
 }
 
-void ff_end_tag(ByteIOContext *pb, int64_t start)
+void ff_end_tag(AVIOContext *pb, int64_t start)
 {
     int64_t pos;
 
-    pos = url_ftell(pb);
-    url_fseek(pb, start - 4, SEEK_SET);
-    put_le32(pb, (uint32_t)(pos - start));
-    url_fseek(pb, pos, SEEK_SET);
+    pos = avio_tell(pb);
+    avio_seek(pb, start - 4, SEEK_SET);
+    avio_wl32(pb, (uint32_t)(pos - start));
+    avio_seek(pb, pos, SEEK_SET);
 }
 
 /* WAVEFORMATEX header */
 /* returns the size or -1 on error */
-int ff_put_wav_header(ByteIOContext *pb, AVCodecContext *enc)
+int ff_put_wav_header(AVIOContext *pb, AVCodecContext *enc)
 {
     int bps, blkalign, bytespersec;
     int hdrsize = 18;
@@ -337,12 +357,12 @@ int ff_put_wav_header(ByteIOContext *pb, AVCodecContext *enc)
                           || av_get_bits_per_sample(enc->codec_id) > 16;
 
     if (waveformatextensible) {
-        put_le16(pb, 0xfffe);
+        avio_wl16(pb, 0xfffe);
     } else {
-        put_le16(pb, enc->codec_tag);
+        avio_wl16(pb, enc->codec_tag);
     }
-    put_le16(pb, enc->channels);
-    put_le32(pb, enc->sample_rate);
+    avio_wl16(pb, enc->channels);
+    avio_wl32(pb, enc->sample_rate);
     if (enc->codec_id == CODEC_ID_MP2 || enc->codec_id == CODEC_ID_MP3 || enc->codec_id == CODEC_ID_GSM_MS) {
         bps = 0;
     } else if (enc->codec_id == CODEC_ID_ADPCM_G726) {
@@ -355,9 +375,11 @@ int ff_put_wav_header(ByteIOContext *pb, AVCodecContext *enc)
         av_log(enc, AV_LOG_WARNING, "requested bits_per_coded_sample (%d) and actually stored (%d) differ\n", enc->bits_per_coded_sample, bps);
     }
 
-    if (enc->codec_id == CODEC_ID_MP2 || enc->codec_id == CODEC_ID_MP3 || enc->codec_id == CODEC_ID_AC3) {
+    if (enc->codec_id == CODEC_ID_MP2 || enc->codec_id == CODEC_ID_MP3) {
         blkalign = enc->frame_size; //this is wrong, but it seems many demuxers do not work if this is set correctly
         //blkalign = 144 * enc->bit_rate/enc->sample_rate;
+    } else if (enc->codec_id == CODEC_ID_AC3) {
+            blkalign = 3840; //maximum bytes per frame
     } else if (enc->codec_id == CODEC_ID_ADPCM_G726) { //
         blkalign = 1;
     } else if (enc->block_align != 0) { /* specified by the codec */
@@ -374,9 +396,9 @@ int ff_put_wav_header(ByteIOContext *pb, AVCodecContext *enc)
     } else {
         bytespersec = enc->bit_rate / 8;
     }
-    put_le32(pb, bytespersec); /* bytes per second */
-    put_le16(pb, blkalign); /* block align */
-    put_le16(pb, bps); /* bits per sample */
+    avio_wl32(pb, bytespersec); /* bytes per second */
+    avio_wl16(pb, blkalign); /* block align */
+    avio_wl16(pb, bps); /* bits per sample */
     if (enc->codec_id == CODEC_ID_MP3) {
         hdrsize += 12;
         bytestream_put_le16(&riff_extradata, 1);    /* wID */
@@ -406,47 +428,47 @@ int ff_put_wav_header(ByteIOContext *pb, AVCodecContext *enc)
     }
     if(waveformatextensible) {                                    /* write WAVEFORMATEXTENSIBLE extensions */
         hdrsize += 22;
-        put_le16(pb, riff_extradata - riff_extradata_start + 22); /* 22 is WAVEFORMATEXTENSIBLE size */
-        put_le16(pb, enc->bits_per_coded_sample);                 /* ValidBitsPerSample || SamplesPerBlock || Reserved */
-        put_le32(pb, enc->channel_layout);                        /* dwChannelMask */
-        put_le32(pb, enc->codec_tag);                             /* GUID + next 3 */
-        put_le32(pb, 0x00100000);
-        put_le32(pb, 0xAA000080);
-        put_le32(pb, 0x719B3800);
+        avio_wl16(pb, riff_extradata - riff_extradata_start + 22); /* 22 is WAVEFORMATEXTENSIBLE size */
+        avio_wl16(pb, enc->bits_per_coded_sample);                 /* ValidBitsPerSample || SamplesPerBlock || Reserved */
+        avio_wl32(pb, enc->channel_layout);                        /* dwChannelMask */
+        avio_wl32(pb, enc->codec_tag);                             /* GUID + next 3 */
+        avio_wl32(pb, 0x00100000);
+        avio_wl32(pb, 0xAA000080);
+        avio_wl32(pb, 0x719B3800);
     } else if(riff_extradata - riff_extradata_start) {
-        put_le16(pb, riff_extradata - riff_extradata_start);
+        avio_wl16(pb, riff_extradata - riff_extradata_start);
     }
-    put_buffer(pb, riff_extradata_start, riff_extradata - riff_extradata_start);
+    avio_write(pb, riff_extradata_start, riff_extradata - riff_extradata_start);
     if(hdrsize&1){
         hdrsize++;
-        put_byte(pb, 0);
+        avio_w8(pb, 0);
     }
 
     return hdrsize;
 }
 
 /* BITMAPINFOHEADER header */
-void ff_put_bmp_header(ByteIOContext *pb, AVCodecContext *enc, const AVCodecTag *tags, int for_asf)
+void ff_put_bmp_header(AVIOContext *pb, AVCodecContext *enc, const AVCodecTag *tags, int for_asf)
 {
-    put_le32(pb, 40 + enc->extradata_size); /* size */
-    put_le32(pb, enc->width);
+    avio_wl32(pb, 40 + enc->extradata_size); /* size */
+    avio_wl32(pb, enc->width);
     //We always store RGB TopDown
-    put_le32(pb, enc->codec_tag ? enc->height : -enc->height);
-    put_le16(pb, 1); /* planes */
+    avio_wl32(pb, enc->codec_tag ? enc->height : -enc->height);
+    avio_wl16(pb, 1); /* planes */
 
-    put_le16(pb, enc->bits_per_coded_sample ? enc->bits_per_coded_sample : 24); /* depth */
+    avio_wl16(pb, enc->bits_per_coded_sample ? enc->bits_per_coded_sample : 24); /* depth */
     /* compression type */
-    put_le32(pb, enc->codec_tag);
-    put_le32(pb, enc->width * enc->height * 3);
-    put_le32(pb, 0);
-    put_le32(pb, 0);
-    put_le32(pb, 0);
-    put_le32(pb, 0);
+    avio_wl32(pb, enc->codec_tag);
+    avio_wl32(pb, enc->width * enc->height * 3);
+    avio_wl32(pb, 0);
+    avio_wl32(pb, 0);
+    avio_wl32(pb, 0);
+    avio_wl32(pb, 0);
 
-    put_buffer(pb, enc->extradata, enc->extradata_size);
+    avio_write(pb, enc->extradata, enc->extradata_size);
 
     if (!for_asf && enc->extradata_size & 1)
-        put_byte(pb, 0);
+        avio_w8(pb, 0);
 }
 #endif //CONFIG_MUXERS
 
@@ -458,45 +480,54 @@ void ff_put_bmp_header(ByteIOContext *pb, AVCodecContext *enc, const AVCodecTag
  * WAVEFORMATEX adds 'WORD  cbSize' and basically makes itself
  * an openended structure.
  */
-void ff_get_wav_header(ByteIOContext *pb, AVCodecContext *codec, int size)
+int ff_get_wav_header(AVIOContext *pb, AVCodecContext *codec, int size)
 {
     int id;
 
-    id = get_le16(pb);
+    id = avio_rl16(pb);
     codec->codec_type = AVMEDIA_TYPE_AUDIO;
     codec->codec_tag = id;
-    codec->channels = get_le16(pb);
-    codec->sample_rate = get_le32(pb);
-    codec->bit_rate = get_le32(pb) * 8;
-    codec->block_align = get_le16(pb);
+    codec->channels = avio_rl16(pb);
+    codec->sample_rate = avio_rl32(pb);
+    codec->bit_rate = avio_rl32(pb) * 8;
+    codec->block_align = avio_rl16(pb);
     if (size == 14) {  /* We're dealing with plain vanilla WAVEFORMAT */
         codec->bits_per_coded_sample = 8;
     }else
-        codec->bits_per_coded_sample = get_le16(pb);
+        codec->bits_per_coded_sample = avio_rl16(pb);
     if (size >= 18) {  /* We're obviously dealing with WAVEFORMATEX */
-        int cbSize = get_le16(pb); /* cbSize */
+        int cbSize = avio_rl16(pb); /* cbSize */
         size -= 18;
         cbSize = FFMIN(size, cbSize);
         if (cbSize >= 22 && id == 0xfffe) { /* WAVEFORMATEXTENSIBLE */
-            codec->bits_per_coded_sample = get_le16(pb);
-            codec->channel_layout = get_le32(pb); /* dwChannelMask */
-            id = get_le32(pb); /* 4 first bytes of GUID */
-            url_fskip(pb, 12); /* skip end of GUID */
+            codec->bits_per_coded_sample = avio_rl16(pb);
+            codec->channel_layout = avio_rl32(pb); /* dwChannelMask */
+            id = avio_rl32(pb); /* 4 first bytes of GUID */
+            avio_skip(pb, 12); /* skip end of GUID */
             cbSize -= 22;
             size -= 22;
         }
         codec->extradata_size = cbSize;
         if (cbSize > 0) {
             codec->extradata = av_mallocz(codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
-            get_buffer(pb, codec->extradata, codec->extradata_size);
+            if (!codec->extradata)
+                return AVERROR(ENOMEM);
+            avio_read(pb, codec->extradata, codec->extradata_size);
             size -= cbSize;
         }
 
         /* It is possible for the chunk to contain garbage at the end */
         if (size > 0)
-            url_fskip(pb, size);
+            avio_skip(pb, size);
     }
     codec->codec_id = ff_wav_codec_get_id(id, codec->bits_per_coded_sample);
+    if (codec->codec_id == CODEC_ID_AAC_LATM) {
+        /* channels and sample_rate values are those prior to applying SBR and/or PS */
+        codec->channels    = 0;
+        codec->sample_rate = 0;
+    }
+
+    return 0;
 }
 
 
@@ -519,6 +550,23 @@ enum CodecID ff_wav_codec_get_id(unsigned int tag, int bps)
         id = CODEC_ID_PCM_ZORK;
     return id;
 }
+
+int ff_get_bmp_header(AVIOContext *pb, AVStream *st)
+{
+    int tag1;
+    avio_rl32(pb); /* size */
+    st->codec->width = avio_rl32(pb);
+    st->codec->height = (int32_t)avio_rl32(pb);
+    avio_rl16(pb); /* planes */
+    st->codec->bits_per_coded_sample= avio_rl16(pb); /* depth */
+    tag1 = avio_rl32(pb);
+    avio_rl32(pb); /* ImageSize */
+    avio_rl32(pb); /* XPelsPerMeter */
+    avio_rl32(pb); /* YPelsPerMeter */
+    avio_rl32(pb); /* ClrUsed */
+    avio_rl32(pb); /* ClrImportant */
+    return tag1;
+}
 #endif // CONFIG_DEMUXERS
 
 void ff_parse_specific_params(AVCodecContext *stream, int *au_rate, int *au_ssize, int *au_scale)
diff --git a/libavformat/riff.h b/libavformat/riff.h
index 2696a0b..a2fa8b7 100644
--- a/libavformat/riff.h
+++ b/libavformat/riff.h
@@ -2,20 +2,20 @@
  * RIFF codec tags
  * copyright (c) 2000 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -30,24 +30,27 @@
 
 #include "libavcodec/avcodec.h"
 #include "avio.h"
+#include "internal.h"
 
-int64_t ff_start_tag(ByteIOContext *pb, const char *tag);
-void ff_end_tag(ByteIOContext *pb, int64_t start);
+int64_t ff_start_tag(AVIOContext *pb, const char *tag);
+void ff_end_tag(AVIOContext *pb, int64_t start);
 
-typedef struct AVCodecTag {
-    enum CodecID id;
-    unsigned int tag;
-} AVCodecTag;
+/**
+ * Read BITMAPINFOHEADER structure and set AVStream codec width, height and
+ * bits_per_encoded_sample fields. Does not read extradata.
+ * @return codec tag
+ */
+int ff_get_bmp_header(AVIOContext *pb, AVStream *st);
 
-void ff_put_bmp_header(ByteIOContext *pb, AVCodecContext *enc, const AVCodecTag *tags, int for_asf);
-int ff_put_wav_header(ByteIOContext *pb, AVCodecContext *enc);
+void ff_put_bmp_header(AVIOContext *pb, AVCodecContext *enc, const AVCodecTag *tags, int for_asf);
+int ff_put_wav_header(AVIOContext *pb, AVCodecContext *enc);
 enum CodecID ff_wav_codec_get_id(unsigned int tag, int bps);
-void ff_get_wav_header(ByteIOContext *pb, AVCodecContext *codec, int size);
+int ff_get_wav_header(AVIOContext *pb, AVCodecContext *codec, int size);
 
 extern const AVCodecTag ff_codec_bmp_tags[];
 extern const AVCodecTag ff_codec_wav_tags[];
 
-unsigned int ff_codec_get_tag(const AVCodecTag *tags, int id);
+unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum CodecID id);
 enum CodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag);
 void ff_parse_specific_params(AVCodecContext *stream, int *au_rate, int *au_ssize, int *au_scale);
 
diff --git a/libavformat/rl2.c b/libavformat/rl2.c
index 1b7edce..f2d6838 100644
--- a/libavformat/rl2.c
+++ b/libavformat/rl2.c
@@ -2,20 +2,20 @@
  * RL2 Format Demuxer
  * Copyright (c) 2008 Sascha Sommer (saschasommer at freenet.de)
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -74,7 +74,7 @@ static int rl2_probe(AVProbeData *p)
 static av_cold int rl2_read_header(AVFormatContext *s,
                             AVFormatParameters *ap)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVStream *st;
     unsigned int frame_count;
     unsigned int audio_frame_counter = 0;
@@ -95,21 +95,21 @@ static av_cold int rl2_read_header(AVFormatContext *s,
     int i;
     int ret = 0;
 
-    url_fskip(pb,4);          /* skip FORM tag */
-    back_size = get_le32(pb); /** get size of the background frame */
-    signature = get_be32(pb);
-    data_size = get_be32(pb);
-    frame_count = get_le32(pb);
+    avio_skip(pb,4);          /* skip FORM tag */
+    back_size = avio_rl32(pb); /**< get size of the background frame */
+    signature = avio_rb32(pb);
+    data_size = avio_rb32(pb);
+    frame_count = avio_rl32(pb);
 
     /* disallow back_sizes and frame_counts that may lead to overflows later */
     if(back_size > INT_MAX/2  || frame_count > INT_MAX / sizeof(uint32_t))
         return AVERROR_INVALIDDATA;
 
-    encoding_method = get_le16(pb);
-    sound_rate = get_le16(pb);
-    rate = get_le16(pb);
-    channels = get_le16(pb);
-    def_sound_size = get_le16(pb);
+    encoding_method = avio_rl16(pb);
+    sound_rate = avio_rl16(pb);
+    rate = avio_rl16(pb);
+    channels = avio_rl16(pb);
+    def_sound_size = avio_rl16(pb);
 
     /** setup video stream */
     st = av_new_stream(s, 0);
@@ -133,7 +133,7 @@ static av_cold int rl2_read_header(AVFormatContext *s,
     if(!st->codec->extradata)
         return AVERROR(ENOMEM);
 
-    if(get_buffer(pb,st->codec->extradata,st->codec->extradata_size) !=
+    if(avio_read(pb,st->codec->extradata,st->codec->extradata_size) !=
                       st->codec->extradata_size)
         return AVERROR(EIO);
 
@@ -173,11 +173,11 @@ static av_cold int rl2_read_header(AVFormatContext *s,
 
     /** read offset and size tables */
     for(i=0; i < frame_count;i++)
-        chunk_size[i] = get_le32(pb);
+        chunk_size[i] = avio_rl32(pb);
     for(i=0; i < frame_count;i++)
-        chunk_offset[i] = get_le32(pb);
+        chunk_offset[i] = avio_rl32(pb);
     for(i=0; i < frame_count;i++)
-        audio_size[i] = get_le32(pb) & 0xFFFF;
+        audio_size[i] = avio_rl32(pb) & 0xFFFF;
 
     /** build the sample index */
     for(i=0;i<frame_count;i++){
@@ -214,7 +214,7 @@ static int rl2_read_packet(AVFormatContext *s,
                             AVPacket *pkt)
 {
     Rl2DemuxContext *rl2 = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVIndexEntry *sample = NULL;
     int i;
     int ret = 0;
@@ -237,7 +237,7 @@ static int rl2_read_packet(AVFormatContext *s,
     ++rl2->index_pos[stream_id];
 
     /** position the stream (will probably be there anyway) */
-    url_fseek(pb, sample->pos, SEEK_SET);
+    avio_seek(pb, sample->pos, SEEK_SET);
 
     /** fill the packet */
     ret = av_get_packet(pb, pkt, sample->size);
@@ -287,7 +287,7 @@ static int rl2_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp
     return 0;
 }
 
-AVInputFormat rl2_demuxer = {
+AVInputFormat ff_rl2_demuxer = {
     "rl2",
     NULL_IF_CONFIG_SMALL("RL2 format"),
     sizeof(Rl2DemuxContext),
diff --git a/libavformat/rm.c b/libavformat/rm.c
index 29a6e40..9c0ad4a 100644
--- a/libavformat/rm.c
+++ b/libavformat/rm.c
@@ -2,20 +2,20 @@
  * "Real" compatible muxer and demuxer common code.
  * Copyright (c) 2009  Aurelien Jacobs <aurel at gnuage.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -27,3 +27,20 @@ const char * const ff_rm_metadata[4] = {
     "copyright",
     "comment"
 };
+
+const AVCodecTag ff_rm_codec_tags[] = {
+    { CODEC_ID_RV10,   MKTAG('R','V','1','0') },
+    { CODEC_ID_RV20,   MKTAG('R','V','2','0') },
+    { CODEC_ID_RV20,   MKTAG('R','V','T','R') },
+    { CODEC_ID_RV30,   MKTAG('R','V','3','0') },
+    { CODEC_ID_RV40,   MKTAG('R','V','4','0') },
+    { CODEC_ID_AC3,    MKTAG('d','n','e','t') },
+    { CODEC_ID_RA_144, MKTAG('l','p','c','J') },
+    { CODEC_ID_RA_288, MKTAG('2','8','_','8') },
+    { CODEC_ID_COOK,   MKTAG('c','o','o','k') },
+    { CODEC_ID_ATRAC3, MKTAG('a','t','r','c') },
+    { CODEC_ID_SIPR,   MKTAG('s','i','p','r') },
+    { CODEC_ID_AAC,    MKTAG('r','a','a','c') },
+    { CODEC_ID_AAC,    MKTAG('r','a','c','p') },
+    { CODEC_ID_NONE },
+};
diff --git a/libavformat/rm.h b/libavformat/rm.h
index 4e63114..9d104ad 100644
--- a/libavformat/rm.h
+++ b/libavformat/rm.h
@@ -2,20 +2,20 @@
  * "Real" compatible muxer and demuxer.
  * Copyright (c) 2000, 2001 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -23,9 +23,11 @@
 #define AVFORMAT_RM_H
 
 #include "avformat.h"
+#include "internal.h"
 
 extern const char * const ff_rm_metadata[4];
 extern const unsigned char ff_sipr_subpk_size[4];
+extern const AVCodecTag ff_rm_codec_tags[];
 
 typedef struct RMStream RMStream;
 
@@ -33,13 +35,13 @@ RMStream *ff_rm_alloc_rmstream (void);
 void      ff_rm_free_rmstream  (RMStream *rms);
 
 /*< input format for Realmedia-style RTSP streams */
-extern AVInputFormat rdt_demuxer;
+extern AVInputFormat ff_rdt_demuxer;
 
 /**
  * Read the MDPR chunk, which contains stream-specific codec initialization
  * parameters.
  *
- * @param s context containing RMContext and ByteIOContext for stream reading
+ * @param s context containing RMContext and AVIOContext for stream reading
  * @param pb context to read the data from
  * @param st the stream that the MDPR chunk belongs to and where to store the
  *           parameters read from the chunk into
@@ -47,14 +49,14 @@ extern AVInputFormat rdt_demuxer;
  * @param codec_data_size size of the MDPR chunk
  * @return 0 on success, errno codes on error
  */
-int ff_rm_read_mdpr_codecdata (AVFormatContext *s, ByteIOContext *pb,
+int ff_rm_read_mdpr_codecdata (AVFormatContext *s, AVIOContext *pb,
                                AVStream *st, RMStream *rst,
                                int codec_data_size);
 
 /**
  * Parse one rm-stream packet from the input bytestream.
  *
- * @param s context containing RMContext and ByteIOContext for stream reading
+ * @param s context containing RMContext and AVIOContext for stream reading
  * @param pb context to read the data from
  * @param st stream to which the packet to be read belongs
  * @param rst Real-specific stream information
@@ -68,7 +70,7 @@ int ff_rm_read_mdpr_codecdata (AVFormatContext *s, ByteIOContext *pb,
  *         value >0 means that no data was placed in pkt, but that cached
  *         data is available by calling ff_rm_retrieve_cache().
  */
-int ff_rm_parse_packet (AVFormatContext *s, ByteIOContext *pb,
+int ff_rm_parse_packet (AVFormatContext *s, AVIOContext *pb,
                         AVStream *st, RMStream *rst, int len,
                         AVPacket *pkt, int *seq, int flags, int64_t ts);
 
@@ -80,7 +82,7 @@ int ff_rm_parse_packet (AVFormatContext *s, ByteIOContext *pb,
  * a positive number, the amount of cached packets. Using this function, each
  * of those packets can be retrieved sequentially.
  *
- * @param s context containing RMContext and ByteIOContext for stream reading
+ * @param s context containing RMContext and AVIOContext for stream reading
  * @param pb context to read the data from
  * @param st stream that this packet belongs to
  * @param rst Real-specific stream information
@@ -88,7 +90,7 @@ int ff_rm_parse_packet (AVFormatContext *s, ByteIOContext *pb,
  * @return the number of samples left for subsequent calls to this same
  *          function, or 0 if all samples have been retrieved.
  */
-int ff_rm_retrieve_cache (AVFormatContext *s, ByteIOContext *pb,
+int ff_rm_retrieve_cache (AVFormatContext *s, AVIOContext *pb,
                           AVStream *st, RMStream *rst, AVPacket *pkt);
 
 /**
diff --git a/libavformat/rmdec.c b/libavformat/rmdec.c
index f4603bf..bcf55fd 100644
--- a/libavformat/rmdec.c
+++ b/libavformat/rmdec.c
@@ -2,20 +2,20 @@
  * "Real" compatible demuxer.
  * Copyright (c) 2000, 2001 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -49,23 +49,6 @@ typedef struct {
     int audio_pkt_cnt; ///< Output packet counter
 } RMDemuxContext;
 
-static const AVCodecTag rm_codec_tags[] = {
-    { CODEC_ID_RV10,   MKTAG('R','V','1','0') },
-    { CODEC_ID_RV20,   MKTAG('R','V','2','0') },
-    { CODEC_ID_RV20,   MKTAG('R','V','T','R') },
-    { CODEC_ID_RV30,   MKTAG('R','V','3','0') },
-    { CODEC_ID_RV40,   MKTAG('R','V','4','0') },
-    { CODEC_ID_AC3,    MKTAG('d','n','e','t') },
-    { CODEC_ID_RA_144, MKTAG('l','p','c','J') },
-    { CODEC_ID_RA_288, MKTAG('2','8','_','8') },
-    { CODEC_ID_COOK,   MKTAG('c','o','o','k') },
-    { CODEC_ID_ATRAC3, MKTAG('a','t','r','c') },
-    { CODEC_ID_SIPR,   MKTAG('s','i','p','r') },
-    { CODEC_ID_AAC,    MKTAG('r','a','a','c') },
-    { CODEC_ID_AAC,    MKTAG('r','a','c','p') },
-    { CODEC_ID_NONE },
-};
-
 static const unsigned char sipr_swaps[38][2] = {
     {  0, 63 }, {  1, 22 }, {  2, 44 }, {  3, 90 },
     {  5, 81 }, {  7, 31 }, {  8, 86 }, {  9, 58 },
@@ -81,33 +64,33 @@ static const unsigned char sipr_swaps[38][2] = {
 
 const unsigned char ff_sipr_subpk_size[4] = { 29, 19, 37, 20 };
 
-static inline void get_strl(ByteIOContext *pb, char *buf, int buf_size, int len)
+static inline void get_strl(AVIOContext *pb, char *buf, int buf_size, int len)
 {
     int i;
     char *q, r;
 
     q = buf;
     for(i=0;i<len;i++) {
-        r = get_byte(pb);
+        r = avio_r8(pb);
         if (i < buf_size - 1)
             *q++ = r;
     }
     if (buf_size > 0) *q = '\0';
 }
 
-static void get_str8(ByteIOContext *pb, char *buf, int buf_size)
+static void get_str8(AVIOContext *pb, char *buf, int buf_size)
 {
-    get_strl(pb, buf, buf_size, get_byte(pb));
+    get_strl(pb, buf, buf_size, avio_r8(pb));
 }
 
-static int rm_read_extradata(ByteIOContext *pb, AVCodecContext *avctx, unsigned size)
+static int rm_read_extradata(AVIOContext *pb, AVCodecContext *avctx, unsigned size)
 {
     if (size >= 1<<24)
         return -1;
     avctx->extradata = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
     if (!avctx->extradata)
         return AVERROR(ENOMEM);
-    avctx->extradata_size = get_buffer(pb, avctx->extradata, size);
+    avctx->extradata_size = avio_read(pb, avctx->extradata, size);
     memset(avctx->extradata + avctx->extradata_size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
     if (avctx->extradata_size != size)
         return AVERROR(EIO);
@@ -119,7 +102,7 @@ static void rm_read_metadata(AVFormatContext *s, int wide)
     char buf[1024];
     int i;
     for (i=0; i<FF_ARRAY_ELEMS(ff_rm_metadata); i++) {
-        int len = wide ? get_be16(s->pb) : get_byte(s->pb);
+        int len = wide ? avio_rb16(s->pb) : avio_r8(s->pb);
         get_strl(s->pb, buf, sizeof(buf), len);
         av_metadata_set2(&s->metadata, ff_rm_metadata[i], buf, 0);
     }
@@ -137,7 +120,7 @@ void ff_rm_free_rmstream (RMStream *rms)
     av_free_packet(&rms->pkt);
 }
 
-static int rm_read_audio_stream_info(AVFormatContext *s, ByteIOContext *pb,
+static int rm_read_audio_stream_info(AVFormatContext *s, AVIOContext *pb,
                                      AVStream *st, RMStream *ast, int read_all)
 {
     char buf[256];
@@ -145,20 +128,20 @@ static int rm_read_audio_stream_info(AVFormatContext *s, ByteIOContext *pb,
     int ret;
 
     /* ra type header */
-    version = get_be16(pb); /* version */
+    version = avio_rb16(pb); /* version */
     if (version == 3) {
-        int header_size = get_be16(pb);
-        int64_t startpos = url_ftell(pb);
-        url_fskip(pb, 14);
+        int header_size = avio_rb16(pb);
+        int64_t startpos = avio_tell(pb);
+        avio_skip(pb, 14);
         rm_read_metadata(s, 0);
-        if ((startpos + header_size) >= url_ftell(pb) + 2) {
+        if ((startpos + header_size) >= avio_tell(pb) + 2) {
             // fourcc (should always be "lpcJ")
-            get_byte(pb);
+            avio_r8(pb);
             get_str8(pb, buf, sizeof(buf));
         }
         // Skip extra header crap (this should never happen)
-        if ((startpos + header_size) > url_ftell(pb))
-            url_fskip(pb, header_size + startpos - url_ftell(pb));
+        if ((startpos + header_size) > avio_tell(pb))
+            avio_skip(pb, header_size + startpos - avio_tell(pb));
         st->codec->sample_rate = 8000;
         st->codec->channels = 1;
         st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
@@ -167,29 +150,29 @@ static int rm_read_audio_stream_info(AVFormatContext *s, ByteIOContext *pb,
         int flavor, sub_packet_h, coded_framesize, sub_packet_size;
         int codecdata_length;
         /* old version (4) */
-        url_fskip(pb, 2); /* unused */
-        get_be32(pb); /* .ra4 */
-        get_be32(pb); /* data size */
-        get_be16(pb); /* version2 */
-        get_be32(pb); /* header size */
-        flavor= get_be16(pb); /* add codec info / flavor */
-        ast->coded_framesize = coded_framesize = get_be32(pb); /* coded frame size */
-        get_be32(pb); /* ??? */
-        get_be32(pb); /* ??? */
-        get_be32(pb); /* ??? */
-        ast->sub_packet_h = sub_packet_h = get_be16(pb); /* 1 */
-        st->codec->block_align= get_be16(pb); /* frame size */
-        ast->sub_packet_size = sub_packet_size = get_be16(pb); /* sub packet size */
-        get_be16(pb); /* ??? */
+        avio_skip(pb, 2); /* unused */
+        avio_rb32(pb); /* .ra4 */
+        avio_rb32(pb); /* data size */
+        avio_rb16(pb); /* version2 */
+        avio_rb32(pb); /* header size */
+        flavor= avio_rb16(pb); /* add codec info / flavor */
+        ast->coded_framesize = coded_framesize = avio_rb32(pb); /* coded frame size */
+        avio_rb32(pb); /* ??? */
+        avio_rb32(pb); /* ??? */
+        avio_rb32(pb); /* ??? */
+        ast->sub_packet_h = sub_packet_h = avio_rb16(pb); /* 1 */
+        st->codec->block_align= avio_rb16(pb); /* frame size */
+        ast->sub_packet_size = sub_packet_size = avio_rb16(pb); /* sub packet size */
+        avio_rb16(pb); /* ??? */
         if (version == 5) {
-            get_be16(pb); get_be16(pb); get_be16(pb);
+            avio_rb16(pb); avio_rb16(pb); avio_rb16(pb);
         }
-        st->codec->sample_rate = get_be16(pb);
-        get_be32(pb);
-        st->codec->channels = get_be16(pb);
+        st->codec->sample_rate = avio_rb16(pb);
+        avio_rb32(pb);
+        st->codec->channels = avio_rb16(pb);
         if (version == 5) {
-            get_be32(pb);
-            get_buffer(pb, buf, 4);
+            avio_rb32(pb);
+            avio_read(pb, buf, 4);
             buf[4] = 0;
         } else {
             get_str8(pb, buf, sizeof(buf)); /* desc */
@@ -197,7 +180,8 @@ static int rm_read_audio_stream_info(AVFormatContext *s, ByteIOContext *pb,
         }
         st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
         st->codec->codec_tag  = AV_RL32(buf);
-        st->codec->codec_id   = ff_codec_get_id(rm_codec_tags, st->codec->codec_tag);
+        st->codec->codec_id   = ff_codec_get_id(ff_rm_codec_tags,
+                                                st->codec->codec_tag);
         switch (st->codec->codec_id) {
         case CODEC_ID_AC3:
             st->need_parsing = AVSTREAM_PARSE_FULL;
@@ -217,19 +201,15 @@ static int rm_read_audio_stream_info(AVFormatContext *s, ByteIOContext *pb,
         case CODEC_ID_COOK:
         case CODEC_ID_ATRAC3:
         case CODEC_ID_SIPR:
-            get_be16(pb); get_byte(pb);
+            avio_rb16(pb); avio_r8(pb);
             if (version == 5)
-                get_byte(pb);
-            codecdata_length = get_be32(pb);
+                avio_r8(pb);
+            codecdata_length = avio_rb32(pb);
             if(codecdata_length + FF_INPUT_BUFFER_PADDING_SIZE <= (unsigned)codecdata_length){
                 av_log(s, AV_LOG_ERROR, "codecdata_length too large\n");
                 return -1;
             }
 
-            if (!strcmp(buf, "cook")) st->codec->codec_id = CODEC_ID_COOK;
-            else if (!strcmp(buf, "sipr")) st->codec->codec_id = CODEC_ID_SIPR;
-            else st->codec->codec_id = CODEC_ID_ATRAC3;
-
             ast->audio_framesize = st->codec->block_align;
             if (st->codec->codec_id == CODEC_ID_SIPR) {
                 if (flavor > 3) {
@@ -256,17 +236,16 @@ static int rm_read_audio_stream_info(AVFormatContext *s, ByteIOContext *pb,
             av_new_packet(&ast->pkt, ast->audio_framesize * sub_packet_h);
             break;
         case CODEC_ID_AAC:
-            get_be16(pb); get_byte(pb);
+            avio_rb16(pb); avio_r8(pb);
             if (version == 5)
-                get_byte(pb);
-            st->codec->codec_id = CODEC_ID_AAC;
-            codecdata_length = get_be32(pb);
+                avio_r8(pb);
+            codecdata_length = avio_rb32(pb);
             if(codecdata_length + FF_INPUT_BUFFER_PADDING_SIZE <= (unsigned)codecdata_length){
                 av_log(s, AV_LOG_ERROR, "codecdata_length too large\n");
                 return -1;
             }
             if (codecdata_length >= 1) {
-                get_byte(pb);
+                avio_r8(pb);
                 if ((ret = rm_read_extradata(pb, st->codec, codecdata_length - 1)) < 0)
                     return ret;
             }
@@ -275,9 +254,9 @@ static int rm_read_audio_stream_info(AVFormatContext *s, ByteIOContext *pb,
             av_strlcpy(st->codec->codec_name, buf, sizeof(st->codec->codec_name));
         }
         if (read_all) {
-            get_byte(pb);
-            get_byte(pb);
-            get_byte(pb);
+            avio_r8(pb);
+            avio_r8(pb);
+            avio_r8(pb);
             rm_read_metadata(s, 0);
         }
     }
@@ -285,7 +264,7 @@ static int rm_read_audio_stream_info(AVFormatContext *s, ByteIOContext *pb,
 }
 
 int
-ff_rm_read_mdpr_codecdata (AVFormatContext *s, ByteIOContext *pb,
+ff_rm_read_mdpr_codecdata (AVFormatContext *s, AVIOContext *pb,
                            AVStream *st, RMStream *rst, int codec_data_size)
 {
     unsigned int v;
@@ -294,34 +273,35 @@ ff_rm_read_mdpr_codecdata (AVFormatContext *s, ByteIOContext *pb,
     int ret;
 
     av_set_pts_info(st, 64, 1, 1000);
-    codec_pos = url_ftell(pb);
-    v = get_be32(pb);
+    codec_pos = avio_tell(pb);
+    v = avio_rb32(pb);
     if (v == MKTAG(0xfd, 'a', 'r', '.')) {
         /* ra type header */
         if (rm_read_audio_stream_info(s, pb, st, rst, 0))
             return -1;
     } else {
         int fps, fps2;
-        if (get_le32(pb) != MKTAG('V', 'I', 'D', 'O')) {
+        if (avio_rl32(pb) != MKTAG('V', 'I', 'D', 'O')) {
         fail1:
             av_log(st->codec, AV_LOG_ERROR, "Unsupported video codec\n");
             goto skip;
         }
-        st->codec->codec_tag = get_le32(pb);
-        st->codec->codec_id  = ff_codec_get_id(rm_codec_tags, st->codec->codec_tag);
+        st->codec->codec_tag = avio_rl32(pb);
+        st->codec->codec_id  = ff_codec_get_id(ff_rm_codec_tags,
+                                               st->codec->codec_tag);
 //        av_log(s, AV_LOG_DEBUG, "%X %X\n", st->codec->codec_tag, MKTAG('R', 'V', '2', '0'));
         if (st->codec->codec_id == CODEC_ID_NONE)
             goto fail1;
-        st->codec->width = get_be16(pb);
-        st->codec->height = get_be16(pb);
+        st->codec->width = avio_rb16(pb);
+        st->codec->height = avio_rb16(pb);
         st->codec->time_base.num= 1;
-        fps= get_be16(pb);
+        fps= avio_rb16(pb);
         st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
-        get_be32(pb);
-        fps2= get_be16(pb);
-        get_be16(pb);
+        avio_rb32(pb);
+        fps2= avio_rb16(pb);
+        avio_rb16(pb);
 
-        if ((ret = rm_read_extradata(pb, st->codec, codec_data_size - (url_ftell(pb) - codec_pos))) < 0)
+        if ((ret = rm_read_extradata(pb, st->codec, codec_data_size - (avio_tell(pb) - codec_pos))) < 0)
             return ret;
 
 //        av_log(s, AV_LOG_DEBUG, "fps= %d fps2= %d\n", fps, fps2);
@@ -340,8 +320,8 @@ ff_rm_read_mdpr_codecdata (AVFormatContext *s, ByteIOContext *pb,
 
 skip:
     /* skip codec info */
-    size = url_ftell(pb) - codec_pos;
-    url_fskip(pb, codec_data_size - size);
+    size = avio_tell(pb) - codec_pos;
+    avio_skip(pb, codec_data_size - size);
 
     return 0;
 }
@@ -350,20 +330,20 @@ skip:
  * of the INDX chunk, and will bail out if not. */
 static int rm_read_index(AVFormatContext *s)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     unsigned int size, n_pkts, str_id, next_off, n, pos, pts;
     AVStream *st;
 
     do {
-        if (get_le32(pb) != MKTAG('I','N','D','X'))
+        if (avio_rl32(pb) != MKTAG('I','N','D','X'))
             return -1;
-        size     = get_be32(pb);
+        size     = avio_rb32(pb);
         if (size < 20)
             return -1;
-        url_fskip(pb, 2);
-        n_pkts   = get_be32(pb);
-        str_id   = get_be16(pb);
-        next_off = get_be32(pb);
+        avio_skip(pb, 2);
+        n_pkts   = avio_rb32(pb);
+        str_id   = avio_rb16(pb);
+        next_off = avio_rb32(pb);
         for (n = 0; n < s->nb_streams; n++)
             if (s->streams[n]->id == str_id) {
                 st = s->streams[n];
@@ -373,17 +353,17 @@ static int rm_read_index(AVFormatContext *s)
             goto skip;
 
         for (n = 0; n < n_pkts; n++) {
-            url_fskip(pb, 2);
-            pts = get_be32(pb);
-            pos = get_be32(pb);
-            url_fskip(pb, 4); /* packet no. */
+            avio_skip(pb, 2);
+            pts = avio_rb32(pb);
+            pos = avio_rb32(pb);
+            avio_skip(pb, 4); /* packet no. */
 
             av_add_index_entry(st, pos, pts, 0, 0, AVINDEX_KEYFRAME);
         }
 
 skip:
-        if (next_off && url_ftell(pb) != next_off &&
-            url_fseek(pb, next_off, SEEK_SET) < 0)
+        if (next_off && avio_tell(pb) != next_off &&
+            avio_seek(pb, next_off, SEEK_SET) < 0)
             return -1;
     } while (next_off);
 
@@ -407,7 +387,7 @@ static int rm_read_header(AVFormatContext *s, AVFormatParameters *ap)
 {
     RMDemuxContext *rm = s->priv_data;
     AVStream *st;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     unsigned int tag;
     int tag_size;
     unsigned int start_time, duration;
@@ -415,7 +395,7 @@ static int rm_read_header(AVFormatContext *s, AVFormatParameters *ap)
     char buf[128];
     int flags = 0;
 
-    tag = get_le32(pb);
+    tag = avio_rl32(pb);
     if (tag == MKTAG('.', 'r', 'a', 0xfd)) {
         /* very old .ra format */
         return rm_read_header_old(s, ap);
@@ -423,17 +403,17 @@ static int rm_read_header(AVFormatContext *s, AVFormatParameters *ap)
         return AVERROR(EIO);
     }
 
-    get_be32(pb); /* header size */
-    get_be16(pb);
-    get_be32(pb);
-    get_be32(pb); /* number of headers */
+    avio_rb32(pb); /* header size */
+    avio_rb16(pb);
+    avio_rb32(pb);
+    avio_rb32(pb); /* number of headers */
 
     for(;;) {
-        if (url_feof(pb))
+        if (pb->eof_reached)
             return -1;
-        tag = get_le32(pb);
-        tag_size = get_be32(pb);
-        get_be16(pb);
+        tag = avio_rl32(pb);
+        tag_size = avio_rb32(pb);
+        avio_rb16(pb);
 #if 0
         printf("tag=%c%c%c%c (%08x) size=%d\n",
                (tag) & 0xff,
@@ -448,17 +428,17 @@ static int rm_read_header(AVFormatContext *s, AVFormatParameters *ap)
         switch(tag) {
         case MKTAG('P', 'R', 'O', 'P'):
             /* file header */
-            get_be32(pb); /* max bit rate */
-            get_be32(pb); /* avg bit rate */
-            get_be32(pb); /* max packet size */
-            get_be32(pb); /* avg packet size */
-            get_be32(pb); /* nb packets */
-            get_be32(pb); /* duration */
-            get_be32(pb); /* preroll */
-            indx_off = get_be32(pb); /* index offset */
-            data_off = get_be32(pb); /* data offset */
-            get_be16(pb); /* nb streams */
-            flags = get_be16(pb); /* flags */
+            avio_rb32(pb); /* max bit rate */
+            avio_rb32(pb); /* avg bit rate */
+            avio_rb32(pb); /* max packet size */
+            avio_rb32(pb); /* avg packet size */
+            avio_rb32(pb); /* nb packets */
+            avio_rb32(pb); /* duration */
+            avio_rb32(pb); /* preroll */
+            indx_off = avio_rb32(pb); /* index offset */
+            data_off = avio_rb32(pb); /* data offset */
+            avio_rb16(pb); /* nb streams */
+            flags = avio_rb16(pb); /* flags */
             break;
         case MKTAG('C', 'O', 'N', 'T'):
             rm_read_metadata(s, 1);
@@ -467,14 +447,14 @@ static int rm_read_header(AVFormatContext *s, AVFormatParameters *ap)
             st = av_new_stream(s, 0);
             if (!st)
                 return AVERROR(ENOMEM);
-            st->id = get_be16(pb);
-            get_be32(pb); /* max bit rate */
-            st->codec->bit_rate = get_be32(pb); /* bit rate */
-            get_be32(pb); /* max packet size */
-            get_be32(pb); /* avg packet size */
-            start_time = get_be32(pb); /* start time */
-            get_be32(pb); /* preroll */
-            duration = get_be32(pb); /* duration */
+            st->id = avio_rb16(pb);
+            avio_rb32(pb); /* max bit rate */
+            st->codec->bit_rate = avio_rb32(pb); /* bit rate */
+            avio_rb32(pb); /* max packet size */
+            avio_rb32(pb); /* avg packet size */
+            start_time = avio_rb32(pb); /* start time */
+            avio_rb32(pb); /* preroll */
+            duration = avio_rb32(pb); /* duration */
             st->start_time = start_time;
             st->duration = duration;
             get_str8(pb, buf, sizeof(buf)); /* desc */
@@ -482,44 +462,45 @@ static int rm_read_header(AVFormatContext *s, AVFormatParameters *ap)
             st->codec->codec_type = AVMEDIA_TYPE_DATA;
             st->priv_data = ff_rm_alloc_rmstream();
             if (ff_rm_read_mdpr_codecdata(s, s->pb, st, st->priv_data,
-                                          get_be32(pb)) < 0)
+                                          avio_rb32(pb)) < 0)
                 return -1;
             break;
         case MKTAG('D', 'A', 'T', 'A'):
             goto header_end;
         default:
             /* unknown tag: skip it */
-            url_fskip(pb, tag_size - 10);
+            avio_skip(pb, tag_size - 10);
             break;
         }
     }
  header_end:
-    rm->nb_packets = get_be32(pb); /* number of packets */
+    rm->nb_packets = avio_rb32(pb); /* number of packets */
     if (!rm->nb_packets && (flags & 4))
         rm->nb_packets = 3600 * 25;
-    get_be32(pb); /* next data header */
+    avio_rb32(pb); /* next data header */
 
     if (!data_off)
-        data_off = url_ftell(pb) - 18;
-    if (indx_off && url_fseek(pb, indx_off, SEEK_SET) >= 0) {
+        data_off = avio_tell(pb) - 18;
+    if (indx_off && pb->seekable && !(s->flags & AVFMT_FLAG_IGNIDX) &&
+        avio_seek(pb, indx_off, SEEK_SET) >= 0) {
         rm_read_index(s);
-        url_fseek(pb, data_off + 18, SEEK_SET);
+        avio_seek(pb, data_off + 18, SEEK_SET);
     }
 
     return 0;
 }
 
-static int get_num(ByteIOContext *pb, int *len)
+static int get_num(AVIOContext *pb, int *len)
 {
     int n, n1;
 
-    n = get_be16(pb);
+    n = avio_rb16(pb);
     (*len)-=2;
     n &= 0x7FFF;
     if (n >= 0x4000) {
         return n - 0x4000;
     } else {
-        n1 = get_be16(pb);
+        n1 = avio_rb16(pb);
         (*len)-=2;
         return (n << 16) | n1;
     }
@@ -530,26 +511,26 @@ static int get_num(ByteIOContext *pb, int *len)
 
 static int sync(AVFormatContext *s, int64_t *timestamp, int *flags, int *stream_index, int64_t *pos){
     RMDemuxContext *rm = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVStream *st;
     uint32_t state=0xFFFFFFFF;
 
-    while(!url_feof(pb)){
+    while(!pb->eof_reached){
         int len, num, i;
-        *pos= url_ftell(pb) - 3;
+        *pos= avio_tell(pb) - 3;
         if(rm->remaining_len > 0){
             num= rm->current_stream;
             len= rm->remaining_len;
             *timestamp = AV_NOPTS_VALUE;
             *flags= 0;
         }else{
-            state= (state<<8) + get_byte(pb);
+            state= (state<<8) + avio_r8(pb);
 
             if(state == MKBETAG('I', 'N', 'D', 'X')){
                 int n_pkts, expected_len;
-                len = get_be32(pb);
-                url_fskip(pb, 2);
-                n_pkts = get_be32(pb);
+                len = avio_rb32(pb);
+                avio_skip(pb, 2);
+                n_pkts = avio_rb32(pb);
                 expected_len = 20 + n_pkts * 14;
                 if (len == 20)
                     /* some files don't add index entries to chunk size... */
@@ -572,10 +553,10 @@ static int sync(AVFormatContext *s, int64_t *timestamp, int *flags, int *stream_
             len=state - 12;
             state= 0xFFFFFFFF;
 
-            num = get_be16(pb);
-            *timestamp = get_be32(pb);
-            get_byte(pb); /* reserved */
-            *flags = get_byte(pb); /* flags */
+            num = avio_rb16(pb);
+            *timestamp = avio_rb32(pb);
+            avio_r8(pb); /* reserved */
+            *flags = avio_r8(pb); /* flags */
         }
         for(i=0;i<s->nb_streams;i++) {
             st = s->streams[i];
@@ -585,7 +566,7 @@ static int sync(AVFormatContext *s, int64_t *timestamp, int *flags, int *stream_
         if (i == s->nb_streams) {
 skip:
             /* skip packet if unknown number */
-            url_fskip(pb, len);
+            avio_skip(pb, len);
             rm->remaining_len = 0;
             continue;
         }
@@ -596,23 +577,23 @@ skip:
     return -1;
 }
 
-static int rm_assemble_video_frame(AVFormatContext *s, ByteIOContext *pb,
+static int rm_assemble_video_frame(AVFormatContext *s, AVIOContext *pb,
                                    RMDemuxContext *rm, RMStream *vst,
                                    AVPacket *pkt, int len, int *pseq)
 {
     int hdr, seq, pic_num, len2, pos;
     int type;
 
-    hdr = get_byte(pb); len--;
+    hdr = avio_r8(pb); len--;
     type = hdr >> 6;
 
     if(type != 3){  // not frame as a part of packet
-        seq = get_byte(pb); len--;
+        seq = avio_r8(pb); len--;
     }
     if(type != 1){  // not whole frame
         len2 = get_num(pb, &len);
         pos  = get_num(pb, &len);
-        pic_num = get_byte(pb); len--;
+        pic_num = avio_r8(pb); len--;
     }
     if(len<0)
         return -1;
@@ -628,7 +609,7 @@ static int rm_assemble_video_frame(AVFormatContext *s, ByteIOContext *pb,
         pkt->data[0] = 0;
         AV_WL32(pkt->data + 1, 1);
         AV_WL32(pkt->data + 5, 0);
-        get_buffer(pb, pkt->data + 9, len);
+        avio_read(pb, pkt->data + 9, len);
         return 0;
     }
     //now we have to deal with single slice
@@ -643,7 +624,7 @@ static int rm_assemble_video_frame(AVFormatContext *s, ByteIOContext *pb,
         vst->videobufpos = 8*vst->slices + 1;
         vst->cur_slice = 0;
         vst->curpic_num = pic_num;
-        vst->pktpos = url_ftell(pb);
+        vst->pktpos = avio_tell(pb);
     }
     if(type == 2)
         len = FFMIN(len, pos);
@@ -654,7 +635,7 @@ static int rm_assemble_video_frame(AVFormatContext *s, ByteIOContext *pb,
     AV_WL32(vst->pkt.data - 3 + 8*vst->cur_slice, vst->videobufpos - 8*vst->slices - 1);
     if(vst->videobufpos + len > vst->videobufsize)
         return 1;
-    if (get_buffer(pb, vst->pkt.data + vst->videobufpos, len) != len)
+    if (avio_read(pb, vst->pkt.data + vst->videobufpos, len) != len)
         return AVERROR(EIO);
     vst->videobufpos += len;
     rm->remaining_len-= len;
@@ -719,7 +700,7 @@ void ff_rm_reorder_sipr_data(uint8_t *buf, int sub_packet_h, int framesize)
 }
 
 int
-ff_rm_parse_packet (AVFormatContext *s, ByteIOContext *pb,
+ff_rm_parse_packet (AVFormatContext *s, AVIOContext *pb,
                     AVStream *st, RMStream *ast, int len, AVPacket *pkt,
                     int *seq, int flags, int64_t timestamp)
 {
@@ -749,15 +730,15 @@ ff_rm_parse_packet (AVFormatContext *s, ByteIOContext *pb,
             switch(st->codec->codec_id) {
                 case CODEC_ID_RA_288:
                     for (x = 0; x < h/2; x++)
-                        get_buffer(pb, ast->pkt.data+x*2*w+y*cfs, cfs);
+                        avio_read(pb, ast->pkt.data+x*2*w+y*cfs, cfs);
                     break;
                 case CODEC_ID_ATRAC3:
                 case CODEC_ID_COOK:
                     for (x = 0; x < w/sps; x++)
-                        get_buffer(pb, ast->pkt.data+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), sps);
+                        avio_read(pb, ast->pkt.data+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), sps);
                     break;
                 case CODEC_ID_SIPR:
-                    get_buffer(pb, ast->pkt.data + y * w, w);
+                    avio_read(pb, ast->pkt.data + y * w, w);
                     break;
             }
 
@@ -772,10 +753,10 @@ ff_rm_parse_packet (AVFormatContext *s, ByteIOContext *pb,
         } else if (st->codec->codec_id == CODEC_ID_AAC) {
             int x;
             rm->audio_stream_num = st->index;
-            ast->sub_packet_cnt = (get_be16(pb) & 0xf0) >> 4;
+            ast->sub_packet_cnt = (avio_rb16(pb) & 0xf0) >> 4;
             if (ast->sub_packet_cnt) {
                 for (x = 0; x < ast->sub_packet_cnt; x++)
-                    ast->sub_packet_lengths[x] = get_be16(pb);
+                    ast->sub_packet_lengths[x] = avio_rb16(pb);
                 rm->audio_pkt_cnt = ast->sub_packet_cnt;
                 ast->audiotimestamp = timestamp;
             } else
@@ -810,7 +791,7 @@ ff_rm_parse_packet (AVFormatContext *s, ByteIOContext *pb,
 }
 
 int
-ff_rm_retrieve_cache (AVFormatContext *s, ByteIOContext *pb,
+ff_rm_retrieve_cache (AVFormatContext *s, AVIOContext *pb,
                       AVStream *st, RMStream *ast, AVPacket *pkt)
 {
     RMDemuxContext *rm = s->priv_data;
@@ -860,14 +841,14 @@ static int rm_read_packet(AVFormatContext *s, AVPacket *pkt)
                 len = !ast->audio_framesize ? RAW_PACKET_SIZE :
                     ast->coded_framesize * ast->sub_packet_h / 2;
                 flags = (seq++ == 1) ? 2 : 0;
-                pos = url_ftell(s->pb);
+                pos = avio_tell(s->pb);
             } else {
                 len=sync(s, &timestamp, &flags, &i, &pos);
                 if (len > 0)
                     st = s->streams[i];
             }
 
-            if(len<0 || url_feof(s->pb))
+            if(len<0 || s->pb->eof_reached)
                 return AVERROR(EIO);
 
             res = ff_rm_parse_packet (s, s->pb, st, st->priv_data, len, pkt,
@@ -923,7 +904,7 @@ static int64_t rm_read_dts(AVFormatContext *s, int stream_index,
     if(rm->old_format)
         return AV_NOPTS_VALUE;
 
-    url_fseek(s->pb, pos, SEEK_SET);
+    avio_seek(s->pb, pos, SEEK_SET);
     rm->remaining_len=0;
     for(;;){
         int seq=1;
@@ -935,9 +916,9 @@ static int64_t rm_read_dts(AVFormatContext *s, int stream_index,
 
         st = s->streams[stream_index2];
         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
-            h= get_byte(s->pb); len--;
+            h= avio_r8(s->pb); len--;
             if(!(h & 0x40)){
-                seq = get_byte(s->pb); len--;
+                seq = avio_r8(s->pb); len--;
             }
         }
 
@@ -948,13 +929,13 @@ static int64_t rm_read_dts(AVFormatContext *s, int stream_index,
                 break;
         }
 
-        url_fskip(s->pb, len);
+        avio_skip(s->pb, len);
     }
     *ppos = pos;
     return dts;
 }
 
-AVInputFormat rm_demuxer = {
+AVInputFormat ff_rm_demuxer = {
     "rm",
     NULL_IF_CONFIG_SMALL("RealMedia format"),
     sizeof(RMDemuxContext),
@@ -966,7 +947,7 @@ AVInputFormat rm_demuxer = {
     rm_read_dts,
 };
 
-AVInputFormat rdt_demuxer = {
+AVInputFormat ff_rdt_demuxer = {
     "rdt",
     NULL_IF_CONFIG_SMALL("RDT demuxer"),
     sizeof(RMDemuxContext),
diff --git a/libavformat/rmenc.c b/libavformat/rmenc.c
index 03db3ce..d64040c 100644
--- a/libavformat/rmenc.c
+++ b/libavformat/rmenc.c
@@ -2,23 +2,24 @@
  * "Real" compatible muxer.
  * Copyright (c) 2000, 2001 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #include "avformat.h"
+#include "avio_internal.h"
 #include "rm.h"
 
 typedef struct {
@@ -44,27 +45,27 @@ typedef struct {
 #define BUFFER_DURATION 0
 
 
-static void put_str(ByteIOContext *s, const char *tag)
+static void put_str(AVIOContext *s, const char *tag)
 {
-    put_be16(s,strlen(tag));
+    avio_wb16(s,strlen(tag));
     while (*tag) {
-        put_byte(s, *tag++);
+        avio_w8(s, *tag++);
     }
 }
 
-static void put_str8(ByteIOContext *s, const char *tag)
+static void put_str8(AVIOContext *s, const char *tag)
 {
-    put_byte(s, strlen(tag));
+    avio_w8(s, strlen(tag));
     while (*tag) {
-        put_byte(s, *tag++);
+        avio_w8(s, *tag++);
     }
 }
 
-static void rv10_write_header(AVFormatContext *ctx,
-                              int data_size, int index_pos)
+static int rv10_write_header(AVFormatContext *ctx,
+                             int data_size, int index_pos)
 {
     RMMuxContext *rm = ctx->priv_data;
-    ByteIOContext *s = ctx->pb;
+    AVIOContext *s = ctx->pb;
     StreamInfo *stream;
     unsigned char *data_offset_ptr, *start_ptr;
     const char *desc, *mimetype;
@@ -74,15 +75,15 @@ static void rv10_write_header(AVFormatContext *ctx,
 
     start_ptr = s->buf_ptr;
 
-    put_tag(s, ".RMF");
-    put_be32(s,18); /* header size */
-    put_be16(s,0);
-    put_be32(s,0);
-    put_be32(s,4 + ctx->nb_streams); /* num headers */
+    ffio_wfourcc(s, ".RMF");
+    avio_wb32(s,18); /* header size */
+    avio_wb16(s,0);
+    avio_wb32(s,0);
+    avio_wb32(s,4 + ctx->nb_streams); /* num headers */
 
-    put_tag(s,"PROP");
-    put_be32(s, 50);
-    put_be16(s, 0);
+    ffio_wfourcc(s,"PROP");
+    avio_wb32(s, 50);
+    avio_wb16(s, 0);
     packet_max_size = 0;
     packet_total_size = 0;
     nb_packets = 0;
@@ -100,37 +101,37 @@ static void rv10_write_header(AVFormatContext *ctx,
         if (v > duration)
             duration = v;
     }
-    put_be32(s, bit_rate); /* max bit rate */
-    put_be32(s, bit_rate); /* avg bit rate */
-    put_be32(s, packet_max_size);        /* max packet size */
+    avio_wb32(s, bit_rate); /* max bit rate */
+    avio_wb32(s, bit_rate); /* avg bit rate */
+    avio_wb32(s, packet_max_size);        /* max packet size */
     if (nb_packets > 0)
         packet_avg_size = packet_total_size / nb_packets;
     else
         packet_avg_size = 0;
-    put_be32(s, packet_avg_size);        /* avg packet size */
-    put_be32(s, nb_packets);  /* num packets */
-    put_be32(s, duration); /* duration */
-    put_be32(s, BUFFER_DURATION);           /* preroll */
-    put_be32(s, index_pos);           /* index offset */
+    avio_wb32(s, packet_avg_size);        /* avg packet size */
+    avio_wb32(s, nb_packets);  /* num packets */
+    avio_wb32(s, duration); /* duration */
+    avio_wb32(s, BUFFER_DURATION);           /* preroll */
+    avio_wb32(s, index_pos);           /* index offset */
     /* computation of data the data offset */
     data_offset_ptr = s->buf_ptr;
-    put_be32(s, 0);           /* data offset : will be patched after */
-    put_be16(s, ctx->nb_streams);    /* num streams */
+    avio_wb32(s, 0);           /* data offset : will be patched after */
+    avio_wb16(s, ctx->nb_streams);    /* num streams */
     flags = 1 | 2; /* save allowed & perfect play */
-    if (url_is_streamed(s))
+    if (!s->seekable)
         flags |= 4; /* live broadcast */
-    put_be16(s, flags);
+    avio_wb16(s, flags);
 
     /* comments */
 
-    put_tag(s,"CONT");
+    ffio_wfourcc(s,"CONT");
     size =  4 * 2 + 10;
     for(i=0; i<FF_ARRAY_ELEMS(ff_rm_metadata); i++) {
         tag = av_metadata_get(ctx->metadata, ff_rm_metadata[i], NULL, 0);
         if(tag) size += strlen(tag->value);
     }
-    put_be32(s,size);
-    put_be16(s,0);
+    avio_wb32(s,size);
+    avio_wb16(s,0);
     for(i=0; i<FF_ARRAY_ELEMS(ff_rm_metadata); i++) {
         tag = av_metadata_get(ctx->metadata, ff_rm_metadata[i], NULL, 0);
         put_str(s, tag ? tag->value : "");
@@ -151,31 +152,31 @@ static void rv10_write_header(AVFormatContext *ctx,
             codec_data_size = 34;
         }
 
-        put_tag(s,"MDPR");
+        ffio_wfourcc(s,"MDPR");
         size = 10 + 9 * 4 + strlen(desc) + strlen(mimetype) + codec_data_size;
-        put_be32(s, size);
-        put_be16(s, 0);
+        avio_wb32(s, size);
+        avio_wb16(s, 0);
 
-        put_be16(s, i); /* stream number */
-        put_be32(s, stream->bit_rate); /* max bit rate */
-        put_be32(s, stream->bit_rate); /* avg bit rate */
-        put_be32(s, stream->packet_max_size);        /* max packet size */
+        avio_wb16(s, i); /* stream number */
+        avio_wb32(s, stream->bit_rate); /* max bit rate */
+        avio_wb32(s, stream->bit_rate); /* avg bit rate */
+        avio_wb32(s, stream->packet_max_size);        /* max packet size */
         if (stream->nb_packets > 0)
             packet_avg_size = stream->packet_total_size /
                 stream->nb_packets;
         else
             packet_avg_size = 0;
-        put_be32(s, packet_avg_size);        /* avg packet size */
-        put_be32(s, 0);           /* start time */
-        put_be32(s, BUFFER_DURATION);           /* preroll */
+        avio_wb32(s, packet_avg_size);        /* avg packet size */
+        avio_wb32(s, 0);           /* start time */
+        avio_wb32(s, BUFFER_DURATION);           /* preroll */
         /* duration */
-        if (url_is_streamed(s) || !stream->total_frames)
-            put_be32(s, (int)(3600 * 1000));
+        if (!s->seekable || !stream->total_frames)
+            avio_wb32(s, (int)(3600 * 1000));
         else
-            put_be32(s, (int)(stream->total_frames * 1000 / stream->frame_rate));
+            avio_wb32(s, (int)(stream->total_frames * 1000 / stream->frame_rate));
         put_str8(s, desc);
         put_str8(s, mimetype);
-        put_be32(s, codec_data_size);
+        avio_wb32(s, codec_data_size);
 
         if (stream->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
             int coded_frame_size, fscode, sample_rate;
@@ -183,13 +184,13 @@ static void rv10_write_header(AVFormatContext *ctx,
             coded_frame_size = (stream->enc->bit_rate *
                                 stream->enc->frame_size) / (8 * sample_rate);
             /* audio codec info */
-            put_tag(s, ".ra");
-            put_byte(s, 0xfd);
-            put_be32(s, 0x00040000); /* version */
-            put_tag(s, ".ra4");
-            put_be32(s, 0x01b53530); /* stream length */
-            put_be16(s, 4); /* unknown */
-            put_be32(s, 0x39); /* header size */
+            avio_write(s, ".ra", 3);
+            avio_w8(s, 0xfd);
+            avio_wb32(s, 0x00040000); /* version */
+            ffio_wfourcc(s, ".ra4");
+            avio_wb32(s, 0x01b53530); /* stream length */
+            avio_wb16(s, 4); /* unknown */
+            avio_wb32(s, 0x39); /* header size */
 
             switch(sample_rate) {
             case 48000:
@@ -208,50 +209,57 @@ static void rv10_write_header(AVFormatContext *ctx,
             case 8000:
                 fscode = 3;
             }
-            put_be16(s, fscode); /* codec additional info, for AC-3, seems
+            avio_wb16(s, fscode); /* codec additional info, for AC-3, seems
                                      to be a frequency code */
             /* special hack to compensate rounding errors... */
             if (coded_frame_size == 557)
                 coded_frame_size--;
-            put_be32(s, coded_frame_size); /* frame length */
-            put_be32(s, 0x51540); /* unknown */
-            put_be32(s, 0x249f0); /* unknown */
-            put_be32(s, 0x249f0); /* unknown */
-            put_be16(s, 0x01);
+            avio_wb32(s, coded_frame_size); /* frame length */
+            avio_wb32(s, 0x51540); /* unknown */
+            avio_wb32(s, 0x249f0); /* unknown */
+            avio_wb32(s, 0x249f0); /* unknown */
+            avio_wb16(s, 0x01);
             /* frame length : seems to be very important */
-            put_be16(s, coded_frame_size);
-            put_be32(s, 0); /* unknown */
-            put_be16(s, stream->enc->sample_rate); /* sample rate */
-            put_be32(s, 0x10); /* unknown */
-            put_be16(s, stream->enc->channels);
+            avio_wb16(s, coded_frame_size);
+            avio_wb32(s, 0); /* unknown */
+            avio_wb16(s, stream->enc->sample_rate); /* sample rate */
+            avio_wb32(s, 0x10); /* unknown */
+            avio_wb16(s, stream->enc->channels);
             put_str8(s, "Int0"); /* codec name */
-            put_str8(s, "dnet"); /* codec name */
-            put_be16(s, 0); /* title length */
-            put_be16(s, 0); /* author length */
-            put_be16(s, 0); /* copyright length */
-            put_byte(s, 0); /* end of header */
+            if (stream->enc->codec_tag) {
+                avio_w8(s, 4); /* tag length */
+                avio_wl32(s, stream->enc->codec_tag);
+            } else {
+                av_log(ctx, AV_LOG_ERROR, "Invalid codec tag\n");
+                return -1;
+            }
+            avio_wb16(s, 0); /* title length */
+            avio_wb16(s, 0); /* author length */
+            avio_wb16(s, 0); /* copyright length */
+            avio_w8(s, 0); /* end of header */
         } else {
             /* video codec info */
-            put_be32(s,34); /* size */
+            avio_wb32(s,34); /* size */
+            ffio_wfourcc(s, "VIDO");
             if(stream->enc->codec_id == CODEC_ID_RV10)
-                put_tag(s,"VIDORV10");
+                ffio_wfourcc(s,"RV10");
             else
-                put_tag(s,"VIDORV20");
-            put_be16(s, stream->enc->width);
-            put_be16(s, stream->enc->height);
-            put_be16(s, (int) stream->frame_rate); /* frames per seconds ? */
-            put_be32(s,0);     /* unknown meaning */
-            put_be16(s, (int) stream->frame_rate);  /* unknown meaning */
-            put_be32(s,0);     /* unknown meaning */
-            put_be16(s, 8);    /* unknown meaning */
+                ffio_wfourcc(s,"RV20");
+            avio_wb16(s, stream->enc->width);
+            avio_wb16(s, stream->enc->height);
+            avio_wb16(s, (int) stream->frame_rate); /* frames per seconds ? */
+            avio_wb32(s,0);     /* unknown meaning */
+            avio_wb16(s, (int) stream->frame_rate);  /* unknown meaning */
+            avio_wb32(s,0);     /* unknown meaning */
+            avio_wb16(s, 8);    /* unknown meaning */
             /* Seems to be the codec version: only use basic H263. The next
                versions seems to add a diffential DC coding as in
                MPEG... nothing new under the sun */
             if(stream->enc->codec_id == CODEC_ID_RV10)
-                put_be32(s,0x10000000);
+                avio_wb32(s,0x10000000);
             else
-                put_be32(s,0x20103001);
-            //put_be32(s,0x10003000);
+                avio_wb32(s,0x20103001);
+            //avio_wb32(s,0x10003000);
         }
     }
 
@@ -264,32 +272,33 @@ static void rv10_write_header(AVFormatContext *ctx,
     data_offset_ptr[3] = data_pos;
 
     /* data stream */
-    put_tag(s,"DATA");
-    put_be32(s,data_size + 10 + 8);
-    put_be16(s,0);
+    ffio_wfourcc(s, "DATA");
+    avio_wb32(s,data_size + 10 + 8);
+    avio_wb16(s,0);
 
-    put_be32(s, nb_packets); /* number of packets */
-    put_be32(s,0); /* next data header */
+    avio_wb32(s, nb_packets); /* number of packets */
+    avio_wb32(s,0); /* next data header */
+    return 0;
 }
 
 static void write_packet_header(AVFormatContext *ctx, StreamInfo *stream,
                                 int length, int key_frame)
 {
     int timestamp;
-    ByteIOContext *s = ctx->pb;
+    AVIOContext *s = ctx->pb;
 
     stream->nb_packets++;
     stream->packet_total_size += length;
     if (length > stream->packet_max_size)
         stream->packet_max_size =  length;
 
-    put_be16(s,0); /* version */
-    put_be16(s,length + 12);
-    put_be16(s, stream->num); /* stream number */
+    avio_wb16(s,0); /* version */
+    avio_wb16(s,length + 12);
+    avio_wb16(s, stream->num); /* stream number */
     timestamp = (1000 * (float)stream->nb_frames) / stream->frame_rate;
-    put_be32(s, timestamp); /* timestamp */
-    put_byte(s, 0); /* reserved */
-    put_byte(s, key_frame ? 2 : 0); /* flags */
+    avio_wb32(s, timestamp); /* timestamp */
+    avio_w8(s, 0); /* reserved */
+    avio_w8(s, key_frame ? 2 : 0); /* flags */
 }
 
 static int rm_write_header(AVFormatContext *s)
@@ -330,8 +339,9 @@ static int rm_write_header(AVFormatContext *s)
         }
     }
 
-    rv10_write_header(s, 0, 0);
-    put_flush_packet(s->pb);
+    if (rv10_write_header(s, 0, 0))
+        return AVERROR_INVALIDDATA;
+    avio_flush(s->pb);
     return 0;
 }
 
@@ -339,7 +349,7 @@ static int rm_write_audio(AVFormatContext *s, const uint8_t *buf, int size, int
 {
     uint8_t *buf1;
     RMMuxContext *rm = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     StreamInfo *stream = rm->audio_stream;
     int i;
 
@@ -348,13 +358,17 @@ static int rm_write_audio(AVFormatContext *s, const uint8_t *buf, int size, int
 
     write_packet_header(s, stream, size, !!(flags & AV_PKT_FLAG_KEY));
 
-    /* for AC-3, the words seem to be reversed */
-    for(i=0;i<size;i+=2) {
-        buf1[i] = buf[i+1];
-        buf1[i+1] = buf[i];
+    if (stream->enc->codec_id == CODEC_ID_AC3) {
+        /* for AC-3, the words seem to be reversed */
+        for(i=0;i<size;i+=2) {
+            buf1[i] = buf[i+1];
+            buf1[i+1] = buf[i];
+        }
+        avio_write(pb, buf1, size);
+    } else {
+        avio_write(pb, buf, size);
     }
-    put_buffer(pb, buf1, size);
-    put_flush_packet(pb);
+    avio_flush(pb);
     stream->nb_frames++;
     av_free(buf1);
     return 0;
@@ -363,7 +377,7 @@ static int rm_write_audio(AVFormatContext *s, const uint8_t *buf, int size, int
 static int rm_write_video(AVFormatContext *s, const uint8_t *buf, int size, int flags)
 {
     RMMuxContext *rm = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     StreamInfo *stream = rm->video_stream;
     int key_frame = !!(flags & AV_PKT_FLAG_KEY);
 
@@ -374,32 +388,32 @@ static int rm_write_video(AVFormatContext *s, const uint8_t *buf, int size, int
 #if 1
     write_packet_header(s, stream, size + 7 + (size >= 0x4000)*4, key_frame);
     /* bit 7: '1' if final packet of a frame converted in several packets */
-    put_byte(pb, 0x81);
+    avio_w8(pb, 0x81);
     /* bit 7: '1' if I frame. bits 6..0 : sequence number in current
        frame starting from 1 */
     if (key_frame) {
-        put_byte(pb, 0x81);
+        avio_w8(pb, 0x81);
     } else {
-        put_byte(pb, 0x01);
+        avio_w8(pb, 0x01);
     }
     if(size >= 0x4000){
-        put_be32(pb, size); /* total frame size */
-        put_be32(pb, size); /* offset from the start or the end */
+        avio_wb32(pb, size); /* total frame size */
+        avio_wb32(pb, size); /* offset from the start or the end */
     }else{
-        put_be16(pb, 0x4000 | size); /* total frame size */
-        put_be16(pb, 0x4000 | size); /* offset from the start or the end */
+        avio_wb16(pb, 0x4000 | size); /* total frame size */
+        avio_wb16(pb, 0x4000 | size); /* offset from the start or the end */
     }
 #else
     /* full frame */
     write_packet_header(s, size + 6);
-    put_byte(pb, 0xc0);
-    put_be16(pb, 0x4000 + size); /* total frame size */
-    put_be16(pb, 0x4000 + packet_number * 126); /* position in stream */
+    avio_w8(pb, 0xc0);
+    avio_wb16(pb, 0x4000 + size); /* total frame size */
+    avio_wb16(pb, 0x4000 + packet_number * 126); /* position in stream */
 #endif
-    put_byte(pb, stream->nb_frames & 0xff);
+    avio_w8(pb, stream->nb_frames & 0xff);
 
-    put_buffer(pb, buf, size);
-    put_flush_packet(pb);
+    avio_write(pb, buf, size);
+    avio_flush(pb);
 
     stream->nb_frames++;
     return 0;
@@ -418,34 +432,34 @@ static int rm_write_trailer(AVFormatContext *s)
 {
     RMMuxContext *rm = s->priv_data;
     int data_size, index_pos, i;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
 
-    if (!url_is_streamed(s->pb)) {
+    if (s->pb->seekable) {
         /* end of file: finish to write header */
-        index_pos = url_fseek(pb, 0, SEEK_CUR);
+        index_pos = avio_tell(pb);
         data_size = index_pos - rm->data_pos;
 
         /* FIXME: write index */
 
         /* undocumented end header */
-        put_be32(pb, 0);
-        put_be32(pb, 0);
+        avio_wb32(pb, 0);
+        avio_wb32(pb, 0);
 
-        url_fseek(pb, 0, SEEK_SET);
+        avio_seek(pb, 0, SEEK_SET);
         for(i=0;i<s->nb_streams;i++)
             rm->streams[i].total_frames = rm->streams[i].nb_frames;
         rv10_write_header(s, data_size, 0);
     } else {
         /* undocumented end header */
-        put_be32(pb, 0);
-        put_be32(pb, 0);
+        avio_wb32(pb, 0);
+        avio_wb32(pb, 0);
     }
-    put_flush_packet(pb);
+    avio_flush(pb);
     return 0;
 }
 
 
-AVOutputFormat rm_muxer = {
+AVOutputFormat ff_rm_muxer = {
     "rm",
     NULL_IF_CONFIG_SMALL("RealMedia format"),
     "application/vnd.rn-realmedia",
@@ -456,4 +470,5 @@ AVOutputFormat rm_muxer = {
     rm_write_header,
     rm_write_packet,
     rm_write_trailer,
+    .codec_tag= (const AVCodecTag* const []){ff_rm_codec_tags, 0},
 };
diff --git a/libavformat/rpl.c b/libavformat/rpl.c
index f0fba3e..1ca4a86 100644
--- a/libavformat/rpl.c
+++ b/libavformat/rpl.c
@@ -2,20 +2,20 @@
  * ARMovie/RPL demuxer
  * Copyright (c) 2007 Christian Ohm, 2008 Eli Friedman
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -47,11 +47,11 @@ typedef struct RPLContext {
     uint32_t frame_in_part;
 } RPLContext;
 
-static int read_line(ByteIOContext * pb, char* line, int bufsize)
+static int read_line(AVIOContext * pb, char* line, int bufsize)
 {
     int i;
     for (i = 0; i < bufsize - 1; i++) {
-        int b = get_byte(pb);
+        int b = avio_r8(pb);
         if (b == 0)
             break;
         if (b == '\n') {
@@ -76,7 +76,7 @@ static int32_t read_int(const char* line, const char** endptr, int* error)
     return result;
 }
 
-static int32_t read_line_and_int(ByteIOContext * pb, int* error)
+static int32_t read_line_and_int(AVIOContext * pb, int* error)
 {
     char line[RPL_LINE_LENGTH];
     const char *endptr;
@@ -110,7 +110,7 @@ static AVRational read_fps(const char* line, int* error)
 
 static int rpl_read_header(AVFormatContext *s, AVFormatParameters *ap)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     RPLContext *rpl = s->priv_data;
     AVStream *vst = NULL, *ast = NULL;
     int total_audio_size;
@@ -250,7 +250,7 @@ static int rpl_read_header(AVFormatContext *s, AVFormatParameters *ap)
     error |= read_line(pb, line, sizeof(line));  // offset to key frame list
 
     // Read the index
-    url_fseek(pb, chunk_catalog_offset, SEEK_SET);
+    avio_seek(pb, chunk_catalog_offset, SEEK_SET);
     total_audio_size = 0;
     for (i = 0; i < number_of_chunks; i++) {
         int64_t offset, video_size, audio_size;
@@ -274,7 +274,7 @@ static int rpl_read_header(AVFormatContext *s, AVFormatParameters *ap)
 static int rpl_read_packet(AVFormatContext *s, AVPacket *pkt)
 {
     RPLContext *rpl = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVStream* stream;
     AVIndexEntry* index_entry;
     uint32_t ret;
@@ -292,7 +292,7 @@ static int rpl_read_packet(AVFormatContext *s, AVPacket *pkt)
     index_entry = &stream->index_entries[rpl->chunk_number];
 
     if (rpl->frame_in_part == 0)
-        if (url_fseek(pb, index_entry->pos, SEEK_SET) < 0)
+        if (avio_seek(pb, index_entry->pos, SEEK_SET) < 0)
             return AVERROR(EIO);
 
     if (stream->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
@@ -301,9 +301,9 @@ static int rpl_read_packet(AVFormatContext *s, AVPacket *pkt)
         // multiple frames per chunk in Escape 124 samples.
         uint32_t frame_size, frame_flags;
 
-        frame_flags = get_le32(pb);
-        frame_size = get_le32(pb);
-        if (url_fseek(pb, -8, SEEK_CUR) < 0)
+        frame_flags = avio_rl32(pb);
+        frame_size = avio_rl32(pb);
+        if (avio_seek(pb, -8, SEEK_CUR) < 0)
             return AVERROR(EIO);
 
         ret = av_get_packet(pb, pkt, frame_size);
@@ -349,7 +349,7 @@ static int rpl_read_packet(AVFormatContext *s, AVPacket *pkt)
     return ret;
 }
 
-AVInputFormat rpl_demuxer = {
+AVInputFormat ff_rpl_demuxer = {
     "rpl",
     NULL_IF_CONFIG_SMALL("RPL/ARMovie format"),
     sizeof(RPLContext),
diff --git a/libavformat/rso.c b/libavformat/rso.c
new file mode 100644
index 0000000..fc39abc
--- /dev/null
+++ b/libavformat/rso.c
@@ -0,0 +1,30 @@
+/*
+ * RSO format common data
+ * Copyright (c) 2010 Rafael Carre
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "avformat.h"
+#include "internal.h"
+#include "rso.h"
+
+const AVCodecTag ff_codec_rso_tags[] = {
+    { CODEC_ID_PCM_U8,          0x0100 },
+    { CODEC_ID_ADPCM_IMA_WAV,   0x0101 },
+    { CODEC_ID_NONE, 0 },
+};
diff --git a/libavformat/rso.h b/libavformat/rso.h
new file mode 100644
index 0000000..bdb39e8
--- /dev/null
+++ b/libavformat/rso.h
@@ -0,0 +1,32 @@
+/*
+ * RSO format common data
+ * Copyright (c) 2010 Rafael Carre
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVFORMAT_RSO_H
+#define AVFORMAT_RSO_H
+
+#include "internal.h"
+
+#define RSO_HEADER_SIZE 8
+
+/* The ffmpeg codecs we support, and the IDs they have in the file */
+extern const AVCodecTag ff_codec_rso_tags[];
+
+#endif /* AVFORMAT_RSO_H */
diff --git a/libavformat/rsodec.c b/libavformat/rsodec.c
new file mode 100644
index 0000000..98de8fe
--- /dev/null
+++ b/libavformat/rsodec.c
@@ -0,0 +1,102 @@
+/*
+ * RSO demuxer
+ * Copyright (c) 2001 Fabrice Bellard (original AU code)
+ * Copyright (c) 2010 Rafael Carre
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "libavutil/intreadwrite.h"
+#include "avformat.h"
+#include "internal.h"
+#include "pcm.h"
+#include "riff.h"
+#include "rso.h"
+
+static int rso_read_header(AVFormatContext *s, AVFormatParameters *ap)
+{
+    AVIOContext *pb = s->pb;
+    int id, rate, bps;
+    unsigned int size;
+    enum CodecID codec;
+    AVStream *st;
+
+    id   = avio_rb16(pb);
+    size = avio_rb16(pb);
+    rate = avio_rb16(pb);
+    avio_rb16(pb);   /* play mode ? (0x0000 = don't loop) */
+
+    codec = ff_codec_get_id(ff_codec_rso_tags, id);
+
+    if (codec == CODEC_ID_ADPCM_IMA_WAV) {
+        av_log(s, AV_LOG_ERROR, "ADPCM in RSO not implemented\n");
+        return AVERROR_PATCHWELCOME;
+    }
+
+    bps = av_get_bits_per_sample(codec);
+    if (!bps) {
+        av_log_ask_for_sample(s, "could not determine bits per sample\n");
+        return AVERROR_INVALIDDATA;
+    }
+
+    /* now we are ready: build format streams */
+    st = av_new_stream(s, 0);
+    if (!st)
+        return AVERROR(ENOMEM);
+
+    st->duration            = (size * 8) / bps;
+    st->codec->codec_type   = AVMEDIA_TYPE_AUDIO;
+    st->codec->codec_tag    = id;
+    st->codec->codec_id     = codec;
+    st->codec->channels     = 1;
+    st->codec->sample_rate  = rate;
+
+    av_set_pts_info(st, 64, 1, rate);
+
+    return 0;
+}
+
+#define BLOCK_SIZE 1024 /* in samples */
+
+static int rso_read_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    int bps = av_get_bits_per_sample(s->streams[0]->codec->codec_id);
+    int ret = av_get_packet(s->pb, pkt, BLOCK_SIZE * bps >> 3);
+
+    if (ret < 0)
+        return ret;
+
+    pkt->stream_index = 0;
+
+    /* note: we need to modify the packet size here to handle the last packet */
+    pkt->size = ret;
+
+    return 0;
+}
+
+AVInputFormat ff_rso_demuxer = {
+    .name           =   "rso",
+    .long_name      =   NULL_IF_CONFIG_SMALL("Lego Mindstorms RSO format"),
+    .extensions     =   "rso",
+    .priv_data_size =   0,
+    .read_probe     =   NULL, /* no magic value in this format */
+    .read_header    =   rso_read_header,
+    .read_packet    =   rso_read_packet,
+    .read_close     =   NULL,
+    .read_seek      =   pcm_read_seek,
+    .codec_tag      =   (const AVCodecTag* const []){ff_codec_rso_tags, 0},
+};
diff --git a/libavformat/rsoenc.c b/libavformat/rsoenc.c
new file mode 100644
index 0000000..338ecf0
--- /dev/null
+++ b/libavformat/rsoenc.c
@@ -0,0 +1,114 @@
+/*
+ * RSO muxer
+ * Copyright (c) 2001 Fabrice Bellard (original AU code)
+ * Copyright (c) 2010 Rafael Carre
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "avformat.h"
+#include "internal.h"
+#include "riff.h"
+#include "rso.h"
+
+static int rso_write_header(AVFormatContext *s)
+{
+    AVIOContext  *pb  = s->pb;
+    AVCodecContext *enc = s->streams[0]->codec;
+
+    if (!enc->codec_tag)
+        return AVERROR_INVALIDDATA;
+
+    if (enc->channels != 1) {
+        av_log(s, AV_LOG_ERROR, "RSO only supports mono\n");
+        return AVERROR_INVALIDDATA;
+    }
+
+    if (!s->pb->seekable) {
+        av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
+        return AVERROR_INVALIDDATA;
+    }
+
+    /* XXX: find legal sample rates (if any) */
+    if (enc->sample_rate >= 1u<<16) {
+        av_log(s, AV_LOG_ERROR, "Sample rate must be < 65536\n");
+        return AVERROR_INVALIDDATA;
+    }
+
+    if (enc->codec_id == CODEC_ID_ADPCM_IMA_WAV) {
+        av_log(s, AV_LOG_ERROR, "ADPCM in RSO not implemented\n");
+        return AVERROR_PATCHWELCOME;
+    }
+
+    /* format header */
+    avio_wb16(pb, enc->codec_tag);   /* codec ID */
+    avio_wb16(pb, 0);                /* data size, will be written at EOF */
+    avio_wb16(pb, enc->sample_rate);
+    avio_wb16(pb, 0x0000);           /* play mode ? (0x0000 = don't loop) */
+
+    avio_flush(pb);
+
+    return 0;
+}
+
+static int rso_write_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    avio_write(s->pb, pkt->data, pkt->size);
+    return 0;
+}
+
+static int rso_write_trailer(AVFormatContext *s)
+{
+    AVIOContext *pb = s->pb;
+    int64_t file_size;
+    uint16_t coded_file_size;
+
+    file_size = avio_tell(pb);
+
+    if (file_size < 0)
+        return file_size;
+
+    if (file_size > 0xffff + RSO_HEADER_SIZE) {
+        av_log(s, AV_LOG_WARNING,
+               "Output file is too big (%"PRId64" bytes >= 64kB)\n", file_size);
+        coded_file_size = 0xffff;
+    } else {
+        coded_file_size = file_size - RSO_HEADER_SIZE;
+    }
+
+    /* update file size */
+    avio_seek(pb, 2, SEEK_SET);
+    avio_wb16(pb, coded_file_size);
+    avio_seek(pb, file_size, SEEK_SET);
+
+    avio_flush(pb);
+
+    return 0;
+}
+
+AVOutputFormat ff_rso_muxer = {
+    .name           =   "rso",
+    .long_name      =   NULL_IF_CONFIG_SMALL("Lego Mindstorms RSO format"),
+    .extensions     =   "rso",
+    .priv_data_size =   0,
+    .audio_codec    =   CODEC_ID_PCM_U8,
+    .video_codec    =   CODEC_ID_NONE,
+    .write_header   =   rso_write_header,
+    .write_packet   =   rso_write_packet,
+    .write_trailer  =   rso_write_trailer,
+    .codec_tag      =   (const AVCodecTag* const []){ff_codec_rso_tags, 0},
+};
diff --git a/libavformat/rtmp.h b/libavformat/rtmp.h
index b0436c0..45de73e 100644
--- a/libavformat/rtmp.h
+++ b/libavformat/rtmp.h
@@ -2,20 +2,20 @@
  * RTMP definitions
  * Copyright (c) 2009 Kostya Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavformat/rtmppkt.c b/libavformat/rtmppkt.c
index 58c3abe..63b0628 100644
--- a/libavformat/rtmppkt.c
+++ b/libavformat/rtmppkt.c
@@ -2,20 +2,20 @@
  * RTMP input format
  * Copyright (c) 2009 Kostya Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,6 +25,7 @@
 
 #include "rtmppkt.h"
 #include "flv.h"
+#include "url.h"
 
 void ff_amf_write_bool(uint8_t **dst, int val)
 {
@@ -78,14 +79,14 @@ int ff_rtmp_packet_read(URLContext *h, RTMPPacket *p,
     enum RTMPPacketType type;
     int size = 0;
 
-    if (url_read(h, &hdr, 1) != 1)
+    if (ffurl_read(h, &hdr, 1) != 1)
         return AVERROR(EIO);
     size++;
     channel_id = hdr & 0x3F;
 
     if (channel_id < 2) { //special case for channel number >= 64
         buf[1] = 0;
-        if (url_read_complete(h, buf, channel_id + 1) != channel_id + 1)
+        if (ffurl_read_complete(h, buf, channel_id + 1) != channel_id + 1)
             return AVERROR(EIO);
         size += channel_id + 1;
         channel_id = AV_RL16(buf) + 64;
@@ -98,28 +99,28 @@ int ff_rtmp_packet_read(URLContext *h, RTMPPacket *p,
     if (hdr == RTMP_PS_ONEBYTE) {
         timestamp = prev_pkt[channel_id].ts_delta;
     } else {
-        if (url_read_complete(h, buf, 3) != 3)
+        if (ffurl_read_complete(h, buf, 3) != 3)
             return AVERROR(EIO);
         size += 3;
         timestamp = AV_RB24(buf);
         if (hdr != RTMP_PS_FOURBYTES) {
-            if (url_read_complete(h, buf, 3) != 3)
+            if (ffurl_read_complete(h, buf, 3) != 3)
                 return AVERROR(EIO);
             size += 3;
             data_size = AV_RB24(buf);
-            if (url_read_complete(h, buf, 1) != 1)
+            if (ffurl_read_complete(h, buf, 1) != 1)
                 return AVERROR(EIO);
             size++;
             type = buf[0];
             if (hdr == RTMP_PS_TWELVEBYTES) {
-                if (url_read_complete(h, buf, 4) != 4)
+                if (ffurl_read_complete(h, buf, 4) != 4)
                     return AVERROR(EIO);
                 size += 4;
                 extra = AV_RL32(buf);
             }
         }
         if (timestamp == 0xFFFFFF) {
-            if (url_read_complete(h, buf, 4) != 4)
+            if (ffurl_read_complete(h, buf, 4) != 4)
                 return AVERROR(EIO);
             timestamp = AV_RB32(buf);
         }
@@ -139,7 +140,7 @@ int ff_rtmp_packet_read(URLContext *h, RTMPPacket *p,
     prev_pkt[channel_id].extra      = extra;
     while (data_size > 0) {
         int toread = FFMIN(data_size, chunk_size);
-        if (url_read_complete(h, p->data + offset, toread) != toread) {
+        if (ffurl_read_complete(h, p->data + offset, toread) != toread) {
             ff_rtmp_packet_destroy(p);
             return AVERROR(EIO);
         }
@@ -147,7 +148,7 @@ int ff_rtmp_packet_read(URLContext *h, RTMPPacket *p,
         offset    += chunk_size;
         size      += chunk_size;
         if (data_size > 0) {
-            url_read_complete(h, &t, 1); //marker
+            ffurl_read_complete(h, &t, 1); //marker
             size++;
             if (t != (0xC0 + channel_id))
                 return -1;
@@ -214,15 +215,15 @@ int ff_rtmp_packet_write(URLContext *h, RTMPPacket *pkt,
     }
     prev_pkt[pkt->channel_id].extra      = pkt->extra;
 
-    url_write(h, pkt_hdr, p-pkt_hdr);
+    ffurl_write(h, pkt_hdr, p-pkt_hdr);
     size = p - pkt_hdr + pkt->data_size;
     while (off < pkt->data_size) {
         int towrite = FFMIN(chunk_size, pkt->data_size - off);
-        url_write(h, pkt->data + off, towrite);
+        ffurl_write(h, pkt->data + off, towrite);
         off += towrite;
         if (off < pkt->data_size) {
             uint8_t marker = 0xC0 | pkt->channel_id;
-            url_write(h, &marker, 1);
+            ffurl_write(h, &marker, 1);
             size++;
         }
     }
diff --git a/libavformat/rtmppkt.h b/libavformat/rtmppkt.h
index 23d4ebc..bb34758 100644
--- a/libavformat/rtmppkt.h
+++ b/libavformat/rtmppkt.h
@@ -2,20 +2,20 @@
  * RTMP packet utilities
  * Copyright (c) 2009 Kostya Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -23,6 +23,7 @@
 #define AVFORMAT_RTMPPKT_H
 
 #include "avformat.h"
+#include "url.h"
 
 /** maximum possible number of different RTMP channels */
 #define RTMP_CHANNELS 65599
@@ -83,7 +84,7 @@ typedef struct RTMPPacket {
 } RTMPPacket;
 
 /**
- * Creates new RTMP packet with given attributes.
+ * Create new RTMP packet with given attributes.
  *
  * @param pkt        packet
  * @param channel_id packet channel ID
@@ -96,14 +97,14 @@ int ff_rtmp_packet_create(RTMPPacket *pkt, int channel_id, RTMPPacketType type,
                           int timestamp, int size);
 
 /**
- * Frees RTMP packet.
+ * Free RTMP packet.
  *
  * @param pkt packet
  */
 void ff_rtmp_packet_destroy(RTMPPacket *pkt);
 
 /**
- * Reads RTMP packet sent by the server.
+ * Read RTMP packet sent by the server.
  *
  * @param h          reader context
  * @param p          packet
@@ -116,7 +117,7 @@ int ff_rtmp_packet_read(URLContext *h, RTMPPacket *p,
                         int chunk_size, RTMPPacket *prev_pkt);
 
 /**
- * Sends RTMP packet to the server.
+ * Send RTMP packet to the server.
  *
  * @param h          reader context
  * @param p          packet to send
@@ -129,9 +130,9 @@ int ff_rtmp_packet_write(URLContext *h, RTMPPacket *p,
                          int chunk_size, RTMPPacket *prev_pkt);
 
 /**
- * Prints information and contents of RTMP packet.
+ * Print information and contents of RTMP packet.
  *
- * @param h          output context
+ * @param ctx        output context
  * @param p          packet to dump
  */
 void ff_rtmp_packet_dump(void *ctx, RTMPPacket *p);
@@ -143,7 +144,7 @@ void ff_rtmp_packet_dump(void *ctx, RTMPPacket *p);
  */
 
 /**
- * Calculates number of bytes taken by first AMF entry in data.
+ * Calculate number of bytes taken by first AMF entry in data.
  *
  * @param data input data
  * @param data_end input buffer end
@@ -152,7 +153,7 @@ void ff_rtmp_packet_dump(void *ctx, RTMPPacket *p);
 int ff_amf_tag_size(const uint8_t *data, const uint8_t *data_end);
 
 /**
- * Retrieves value of given AMF object field in string form.
+ * Retrieve value of given AMF object field in string form.
  *
  * @param data     AMF object data
  * @param data_end input buffer end
@@ -165,7 +166,7 @@ int ff_amf_get_field_value(const uint8_t *data, const uint8_t *data_end,
                            const uint8_t *name, uint8_t *dst, int dst_size);
 
 /**
- * Writes boolean value in AMF format to buffer.
+ * Write boolean value in AMF format to buffer.
  *
  * @param dst pointer to the input buffer (will be modified)
  * @param val value to write
@@ -173,7 +174,7 @@ int ff_amf_get_field_value(const uint8_t *data, const uint8_t *data_end,
 void ff_amf_write_bool(uint8_t **dst, int val);
 
 /**
- * Writes number in AMF format to buffer.
+ * Write number in AMF format to buffer.
  *
  * @param dst pointer to the input buffer (will be modified)
  * @param num value to write
@@ -181,7 +182,7 @@ void ff_amf_write_bool(uint8_t **dst, int val);
 void ff_amf_write_number(uint8_t **dst, double num);
 
 /**
- * Writes string in AMF format to buffer.
+ * Write string in AMF format to buffer.
  *
  * @param dst pointer to the input buffer (will be modified)
  * @param str string to write
@@ -189,21 +190,21 @@ void ff_amf_write_number(uint8_t **dst, double num);
 void ff_amf_write_string(uint8_t **dst, const char *str);
 
 /**
- * Writes AMF NULL value to buffer.
+ * Write AMF NULL value to buffer.
  *
  * @param dst pointer to the input buffer (will be modified)
  */
 void ff_amf_write_null(uint8_t **dst);
 
 /**
- * Writes marker for AMF object to buffer.
+ * Write marker for AMF object to buffer.
  *
  * @param dst pointer to the input buffer (will be modified)
  */
 void ff_amf_write_object_start(uint8_t **dst);
 
 /**
- * Writes string used as field name in AMF object to buffer.
+ * Write string used as field name in AMF object to buffer.
  *
  * @param dst pointer to the input buffer (will be modified)
  * @param str string to write
@@ -211,7 +212,7 @@ void ff_amf_write_object_start(uint8_t **dst);
 void ff_amf_write_field_name(uint8_t **dst, const char *str);
 
 /**
- * Writes marker for end of AMF object to buffer.
+ * Write marker for end of AMF object to buffer.
  *
  * @param dst pointer to the input buffer (will be modified)
  */
diff --git a/libavformat/rtmpproto.c b/libavformat/rtmpproto.c
index 4edbffa..9fc5196 100644
--- a/libavformat/rtmpproto.c
+++ b/libavformat/rtmpproto.c
@@ -2,20 +2,20 @@
  * RTMP network protocol
  * Copyright (c) 2009 Kostya Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -36,12 +36,13 @@
 #include "flv.h"
 #include "rtmp.h"
 #include "rtmppkt.h"
+#include "url.h"
 
 /* we can't use av_log() with URLContext yet... */
-#if LIBAVFORMAT_VERSION_MAJOR < 53
-#define LOG_CONTEXT NULL
-#else
+#if FF_API_URL_CLASS
 #define LOG_CONTEXT s
+#else
+#define LOG_CONTEXT NULL
 #endif
 
 //#define DEBUG
@@ -102,7 +103,7 @@ static const uint8_t rtmp_server_key[] = {
 };
 
 /**
- * Generates 'connect' call and sends it to the server.
+ * Generate 'connect' call and send it to the server.
  */
 static void gen_connect(URLContext *s, RTMPContext *rt, const char *proto,
                         const char *host, int port)
@@ -154,7 +155,7 @@ static void gen_connect(URLContext *s, RTMPContext *rt, const char *proto,
 }
 
 /**
- * Generates 'releaseStream' call and sends it to the server. It should make
+ * Generate 'releaseStream' call and send it to the server. It should make
  * the server release some channel for media streams.
  */
 static void gen_release_stream(URLContext *s, RTMPContext *rt)
@@ -177,7 +178,7 @@ static void gen_release_stream(URLContext *s, RTMPContext *rt)
 }
 
 /**
- * Generates 'FCPublish' call and sends it to the server. It should make
+ * Generate 'FCPublish' call and send it to the server. It should make
  * the server preapare for receiving media streams.
  */
 static void gen_fcpublish_stream(URLContext *s, RTMPContext *rt)
@@ -200,7 +201,7 @@ static void gen_fcpublish_stream(URLContext *s, RTMPContext *rt)
 }
 
 /**
- * Generates 'FCUnpublish' call and sends it to the server. It should make
+ * Generate 'FCUnpublish' call and send it to the server. It should make
  * the server destroy stream.
  */
 static void gen_fcunpublish_stream(URLContext *s, RTMPContext *rt)
@@ -223,7 +224,7 @@ static void gen_fcunpublish_stream(URLContext *s, RTMPContext *rt)
 }
 
 /**
- * Generates 'createStream' call and sends it to the server. It should make
+ * Generate 'createStream' call and send it to the server. It should make
  * the server allocate some channel for media streams.
  */
 static void gen_create_stream(URLContext *s, RTMPContext *rt)
@@ -245,7 +246,7 @@ static void gen_create_stream(URLContext *s, RTMPContext *rt)
 
 
 /**
- * Generates 'deleteStream' call and sends it to the server. It should make
+ * Generate 'deleteStream' call and send it to the server. It should make
  * the server remove some channel for media streams.
  */
 static void gen_delete_stream(URLContext *s, RTMPContext *rt)
@@ -267,7 +268,7 @@ static void gen_delete_stream(URLContext *s, RTMPContext *rt)
 }
 
 /**
- * Generates 'play' call and sends it to the server, then pings the server
+ * Generate 'play' call and send it to the server, then ping the server
  * to start actual playing.
  */
 static void gen_play(URLContext *s, RTMPContext *rt)
@@ -302,7 +303,7 @@ static void gen_play(URLContext *s, RTMPContext *rt)
 }
 
 /**
- * Generates 'publish' call and sends it to the server.
+ * Generate 'publish' call and send it to the server.
  */
 static void gen_publish(URLContext *s, RTMPContext *rt)
 {
@@ -326,7 +327,7 @@ static void gen_publish(URLContext *s, RTMPContext *rt)
 }
 
 /**
- * Generates ping reply and sends it to the server.
+ * Generate ping reply and send it to the server.
  */
 static void gen_pong(URLContext *s, RTMPContext *rt, RTMPPacket *ppkt)
 {
@@ -342,7 +343,7 @@ static void gen_pong(URLContext *s, RTMPContext *rt, RTMPPacket *ppkt)
 }
 
 /**
- * Generates report on bytes read so far and sends it to the server.
+ * Generate report on bytes read so far and send it to the server.
  */
 static void gen_bytes_read(URLContext *s, RTMPContext *rt, uint32_t ts)
 {
@@ -361,7 +362,7 @@ static void gen_bytes_read(URLContext *s, RTMPContext *rt, uint32_t ts)
 #define HMAC_OPAD_VAL 0x5C
 
 /**
- * Calculates HMAC-SHA2 digest for RTMP handshake packets.
+ * Calculate HMAC-SHA2 digest for RTMP handshake packets.
  *
  * @param src    input buffer
  * @param len    input buffer length (should be 1536)
@@ -410,7 +411,7 @@ static void rtmp_calc_digest(const uint8_t *src, int len, int gap,
 }
 
 /**
- * Puts HMAC-SHA2 digest of packet data (except for the bytes where this digest
+ * Put HMAC-SHA2 digest of packet data (except for the bytes where this digest
  * will be stored) into that packet.
  *
  * @param buf handshake data (1536 bytes)
@@ -431,7 +432,7 @@ static int rtmp_handshake_imprint_with_digest(uint8_t *buf)
 }
 
 /**
- * Verifies that the received server response has the expected digest value.
+ * Verify that the received server response has the expected digest value.
  *
  * @param buf handshake data received from the server (1536 bytes)
  * @param off position to search digest offset from
@@ -455,7 +456,7 @@ static int rtmp_validate_digest(uint8_t *buf, int off)
 }
 
 /**
- * Performs handshake with the server by means of exchanging pseudorandom data
+ * Perform handshake with the server by means of exchanging pseudorandom data
  * signed with HMAC-SHA2 digest.
  *
  * @return 0 if handshake succeeds, negative value otherwise
@@ -485,13 +486,13 @@ static int rtmp_handshake(URLContext *s, RTMPContext *rt)
         tosend[i] = av_lfg_get(&rnd) >> 24;
     client_pos = rtmp_handshake_imprint_with_digest(tosend + 1);
 
-    url_write(rt->stream, tosend, RTMP_HANDSHAKE_PACKET_SIZE + 1);
-    i = url_read_complete(rt->stream, serverdata, RTMP_HANDSHAKE_PACKET_SIZE + 1);
+    ffurl_write(rt->stream, tosend, RTMP_HANDSHAKE_PACKET_SIZE + 1);
+    i = ffurl_read_complete(rt->stream, serverdata, RTMP_HANDSHAKE_PACKET_SIZE + 1);
     if (i != RTMP_HANDSHAKE_PACKET_SIZE + 1) {
         av_log(LOG_CONTEXT, AV_LOG_ERROR, "Cannot read RTMP handshake response\n");
         return -1;
     }
-    i = url_read_complete(rt->stream, clientdata, RTMP_HANDSHAKE_PACKET_SIZE);
+    i = ffurl_read_complete(rt->stream, clientdata, RTMP_HANDSHAKE_PACKET_SIZE);
     if (i != RTMP_HANDSHAKE_PACKET_SIZE) {
         av_log(LOG_CONTEXT, AV_LOG_ERROR, "Cannot read RTMP handshake response\n");
         return -1;
@@ -531,16 +532,16 @@ static int rtmp_handshake(URLContext *s, RTMPContext *rt)
                          tosend + RTMP_HANDSHAKE_PACKET_SIZE - 32);
 
         // write reply back to the server
-        url_write(rt->stream, tosend, RTMP_HANDSHAKE_PACKET_SIZE);
+        ffurl_write(rt->stream, tosend, RTMP_HANDSHAKE_PACKET_SIZE);
     } else {
-        url_write(rt->stream, serverdata+1, RTMP_HANDSHAKE_PACKET_SIZE);
+        ffurl_write(rt->stream, serverdata+1, RTMP_HANDSHAKE_PACKET_SIZE);
     }
 
     return 0;
 }
 
 /**
- * Parses received packet and may perform some action depending on
+ * Parse received packet and possibly perform some action depending on
  * the packet contents.
  * @return 0 for no errors, negative values for serious errors which prevent
  *         further communications, positive values for uncritical errors
@@ -666,7 +667,7 @@ static int rtmp_parse_result(URLContext *s, RTMPContext *rt, RTMPPacket *pkt)
 }
 
 /**
- * Interacts with the server by receiving and sending RTMP packets until
+ * Interact with the server by receiving and sending RTMP packets until
  * there is some significant data (media data or expected status notification).
  *
  * @param s          reading context
@@ -752,7 +753,7 @@ static int get_packet(URLContext *s, int for_header)
                 data_size = bytestream_get_be24(&next);
                 p=next;
                 cts = bytestream_get_be24(&next);
-                cts |= bytestream_get_byte(&next);
+                cts |= bytestream_get_byte(&next) << 24;
                 if (pts==0)
                     pts=cts;
                 ts += cts - pts;
@@ -785,13 +786,13 @@ static int rtmp_close(URLContext *h)
         gen_delete_stream(h, rt);
 
     av_freep(&rt->flv_data);
-    url_close(rt->stream);
+    ffurl_close(rt->stream);
     av_free(rt);
     return 0;
 }
 
 /**
- * Opens RTMP connection and verifies that the stream can be played.
+ * Open RTMP connection and verify that the stream can be played.
  *
  * URL syntax: rtmp://server[:port][/app][/playpath]
  *             where 'app' is first one or two directories in the path
@@ -811,16 +812,16 @@ static int rtmp_open(URLContext *s, const char *uri, int flags)
     if (!rt)
         return AVERROR(ENOMEM);
     s->priv_data = rt;
-    rt->is_input = !(flags & URL_WRONLY);
+    rt->is_input = !(flags & AVIO_WRONLY);
 
-    ff_url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname), &port,
+    av_url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname), &port,
                  path, sizeof(path), s->filename);
 
     if (port < 0)
         port = RTMP_DEFAULT_PORT;
     ff_url_join(buf, sizeof(buf), "tcp", NULL, hostname, port, NULL);
 
-    if (url_open(&rt->stream, buf, URL_RDWR) < 0) {
+    if (ffurl_open(&rt->stream, buf, AVIO_RDWR) < 0) {
         av_log(LOG_CONTEXT, AV_LOG_ERROR, "Cannot open connection %s\n", buf);
         goto fail;
     }
@@ -887,7 +888,7 @@ static int rtmp_open(URLContext *s, const char *uri, int flags)
         rt->flv_off  = 0;
     }
 
-    s->max_packet_size = url_get_max_packet_size(rt->stream);
+    s->max_packet_size = rt->stream->max_packet_size;
     s->is_streamed     = 1;
     return 0;
 
@@ -915,6 +916,7 @@ static int rtmp_read(URLContext *s, uint8_t *buf, int size)
             buf  += data_left;
             size -= data_left;
             rt->flv_off = rt->flv_size;
+            return data_left;
         }
         if ((ret = get_packet(s, 0)) < 0)
            return ret;
@@ -922,9 +924,9 @@ static int rtmp_read(URLContext *s, uint8_t *buf, int size)
     return orig_size;
 }
 
-static int rtmp_write(URLContext *h, uint8_t *buf, int size)
+static int rtmp_write(URLContext *s, const uint8_t *buf, int size)
 {
-    RTMPContext *rt = h->priv_data;
+    RTMPContext *rt = s->priv_data;
     int size_temp = size;
     int pktsize, pkttype;
     uint32_t ts;
@@ -988,11 +990,10 @@ static int rtmp_write(URLContext *h, uint8_t *buf, int size)
     return size;
 }
 
-URLProtocol rtmp_protocol = {
-    "rtmp",
-    rtmp_open,
-    rtmp_read,
-    rtmp_write,
-    NULL, /* seek */
-    rtmp_close,
+URLProtocol ff_rtmp_protocol = {
+    .name      = "rtmp",
+    .url_open  = rtmp_open,
+    .url_read  = rtmp_read,
+    .url_write = rtmp_write,
+    .url_close = rtmp_close,
 };
diff --git a/libavformat/rtp.c b/libavformat/rtp.c
index a8dcfd7..d59b694 100644
--- a/libavformat/rtp.c
+++ b/libavformat/rtp.c
@@ -2,20 +2,20 @@
  * RTP input/output format
  * Copyright (c) 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -48,7 +48,7 @@ static const struct
   {6, "DVI4",        AVMEDIA_TYPE_AUDIO,   CODEC_ID_NONE, 16000, 1},
   {7, "LPC",         AVMEDIA_TYPE_AUDIO,   CODEC_ID_NONE, 8000, 1},
   {8, "PCMA",        AVMEDIA_TYPE_AUDIO,   CODEC_ID_PCM_ALAW, 8000, 1},
-  {9, "G722",        AVMEDIA_TYPE_AUDIO,   CODEC_ID_NONE, 8000, 1},
+  {9, "G722",        AVMEDIA_TYPE_AUDIO,   CODEC_ID_ADPCM_G722, 8000, 1},
   {10, "L16",        AVMEDIA_TYPE_AUDIO,   CODEC_ID_PCM_S16BE, 44100, 2},
   {11, "L16",        AVMEDIA_TYPE_AUDIO,   CODEC_ID_PCM_S16BE, 44100, 1},
   {12, "QCELP",      AVMEDIA_TYPE_AUDIO,   CODEC_ID_QCELP, 8000, 1},
diff --git a/libavformat/rtp.h b/libavformat/rtp.h
index 7834f9d..36157ce 100644
--- a/libavformat/rtp.h
+++ b/libavformat/rtp.h
@@ -2,20 +2,20 @@
  * RTP definitions
  * Copyright (c) 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #ifndef AVFORMAT_RTP_H
@@ -76,4 +76,19 @@ enum CodecID ff_rtp_codec_id(const char *buf, enum AVMediaType codec_type);
 #define RTCP_TX_RATIO_NUM 5
 #define RTCP_TX_RATIO_DEN 1000
 
+/* An arbitrary id value for RTP Xiph streams - only relevant to indicate
+ * the the configuration has changed within a stream (by changing the
+ * ident value sent).
+ */
+#define RTP_XIPH_IDENT 0xfecdba
+
+/* RTCP packet types */
+enum RTCPType {
+    RTCP_SR     = 200,
+    RTCP_RR,   // 201
+    RTCP_SDES, // 202
+    RTCP_BYE,  // 203
+    RTCP_APP   // 204
+};
+
 #endif /* AVFORMAT_RTP_H */
diff --git a/libavformat/rtpdec.c b/libavformat/rtpdec.c
index 0d2df59..43305a3 100644
--- a/libavformat/rtpdec.c
+++ b/libavformat/rtpdec.c
@@ -2,20 +2,20 @@
  * RTP input format
  * Copyright (c) 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,16 +25,14 @@
 #include "libavcodec/get_bits.h"
 #include "avformat.h"
 #include "mpegts.h"
+#include "url.h"
 
 #include <unistd.h>
+#include <strings.h>
 #include "network.h"
 
 #include "rtpdec.h"
-#include "rtpdec_amr.h"
-#include "rtpdec_asf.h"
-#include "rtpdec_h263.h"
-#include "rtpdec_h264.h"
-#include "rtpdec_xiph.h"
+#include "rtpdec_formats.h"
 
 //#define DEBUG
 
@@ -44,14 +42,17 @@
          buffer to 'rtp_write_packet' contains all the packets for ONE
          frame. Each packet should have a four byte header containing
          the length in big endian format (same trick as
-         'url_open_dyn_packet_buf')
+         'ffio_open_dyn_packet_buf')
 */
 
-/* statistics functions */
-RTPDynamicProtocolHandler *RTPFirstDynamicPayloadHandler= NULL;
+static RTPDynamicProtocolHandler ff_realmedia_mp3_dynamic_handler = {
+    .enc_name           = "X-MP3-draft-00",
+    .codec_type         = AVMEDIA_TYPE_AUDIO,
+    .codec_id           = CODEC_ID_MP3ADU,
+};
 
-static RTPDynamicProtocolHandler mp4v_es_handler= {"MP4V-ES", AVMEDIA_TYPE_VIDEO, CODEC_ID_MPEG4};
-static RTPDynamicProtocolHandler mpeg4_generic_handler= {"mpeg4-generic", AVMEDIA_TYPE_AUDIO, CODEC_ID_AAC};
+/* statistics functions */
+static RTPDynamicProtocolHandler *RTPFirstDynamicPayloadHandler= NULL;
 
 void ff_register_dynamic_payload_handler(RTPDynamicProtocolHandler *handler)
 {
@@ -61,8 +62,8 @@ void ff_register_dynamic_payload_handler(RTPDynamicProtocolHandler *handler)
 
 void av_register_rtp_dynamic_payload_handlers(void)
 {
-    ff_register_dynamic_payload_handler(&mp4v_es_handler);
-    ff_register_dynamic_payload_handler(&mpeg4_generic_handler);
+    ff_register_dynamic_payload_handler(&ff_mp4v_es_dynamic_handler);
+    ff_register_dynamic_payload_handler(&ff_mpeg4_generic_dynamic_handler);
     ff_register_dynamic_payload_handler(&ff_amr_nb_dynamic_handler);
     ff_register_dynamic_payload_handler(&ff_amr_wb_dynamic_handler);
     ff_register_dynamic_payload_handler(&ff_h263_1998_dynamic_handler);
@@ -70,20 +71,77 @@ void av_register_rtp_dynamic_payload_handlers(void)
     ff_register_dynamic_payload_handler(&ff_h264_dynamic_handler);
     ff_register_dynamic_payload_handler(&ff_vorbis_dynamic_handler);
     ff_register_dynamic_payload_handler(&ff_theora_dynamic_handler);
+    ff_register_dynamic_payload_handler(&ff_qdm2_dynamic_handler);
+    ff_register_dynamic_payload_handler(&ff_svq3_dynamic_handler);
+    ff_register_dynamic_payload_handler(&ff_mp4a_latm_dynamic_handler);
+    ff_register_dynamic_payload_handler(&ff_vp8_dynamic_handler);
+    ff_register_dynamic_payload_handler(&ff_qcelp_dynamic_handler);
+    ff_register_dynamic_payload_handler(&ff_realmedia_mp3_dynamic_handler);
 
     ff_register_dynamic_payload_handler(&ff_ms_rtp_asf_pfv_handler);
     ff_register_dynamic_payload_handler(&ff_ms_rtp_asf_pfa_handler);
+
+    ff_register_dynamic_payload_handler(&ff_qt_rtp_aud_handler);
+    ff_register_dynamic_payload_handler(&ff_qt_rtp_vid_handler);
+    ff_register_dynamic_payload_handler(&ff_quicktime_rtp_aud_handler);
+    ff_register_dynamic_payload_handler(&ff_quicktime_rtp_vid_handler);
+}
+
+RTPDynamicProtocolHandler *ff_rtp_handler_find_by_name(const char *name,
+                                                  enum AVMediaType codec_type)
+{
+    RTPDynamicProtocolHandler *handler;
+    for (handler = RTPFirstDynamicPayloadHandler;
+         handler; handler = handler->next)
+        if (!strcasecmp(name, handler->enc_name) &&
+            codec_type == handler->codec_type)
+            return handler;
+    return NULL;
+}
+
+RTPDynamicProtocolHandler *ff_rtp_handler_find_by_id(int id,
+                                                enum AVMediaType codec_type)
+{
+    RTPDynamicProtocolHandler *handler;
+    for (handler = RTPFirstDynamicPayloadHandler;
+         handler; handler = handler->next)
+        if (handler->static_payload_id && handler->static_payload_id == id &&
+            codec_type == handler->codec_type)
+            return handler;
+    return NULL;
 }
 
 static int rtcp_parse_packet(RTPDemuxContext *s, const unsigned char *buf, int len)
 {
-    if (buf[1] != 200)
-        return -1;
-    s->last_rtcp_ntp_time = AV_RB64(buf + 8);
-    if (s->first_rtcp_ntp_time == AV_NOPTS_VALUE)
-        s->first_rtcp_ntp_time = s->last_rtcp_ntp_time;
-    s->last_rtcp_timestamp = AV_RB32(buf + 16);
-    return 0;
+    int payload_len;
+    while (len >= 2) {
+        switch (buf[1]) {
+        case RTCP_SR:
+            if (len < 16) {
+                av_log(NULL, AV_LOG_ERROR, "Invalid length for RTCP SR packet\n");
+                return AVERROR_INVALIDDATA;
+            }
+            payload_len = (AV_RB16(buf + 2) + 1) * 4;
+
+            s->last_rtcp_ntp_time = AV_RB64(buf + 8);
+            s->last_rtcp_timestamp = AV_RB32(buf + 16);
+            if (s->first_rtcp_ntp_time == AV_NOPTS_VALUE) {
+                s->first_rtcp_ntp_time = s->last_rtcp_ntp_time;
+                if (!s->base_timestamp)
+                    s->base_timestamp = s->last_rtcp_timestamp;
+                s->rtcp_ts_offset = s->last_rtcp_timestamp - s->base_timestamp;
+            }
+
+            buf += payload_len;
+            len -= payload_len;
+            break;
+        case RTCP_BYE:
+            return -RTCP_BYE;
+        default:
+            return -1;
+        }
+    }
+    return -1;
 }
 
 #define RTP_SEQ_MOD (1<<16)
@@ -180,7 +238,7 @@ static void rtcp_update_jitter(RTPStatistics *s, uint32_t sent_timestamp, uint32
 
 int rtp_check_and_send_back_rr(RTPDemuxContext *s, int count)
 {
-    ByteIOContext *pb;
+    AVIOContext *pb;
     uint8_t *buf;
     int len;
     int rtcp_bytes;
@@ -207,15 +265,16 @@ int rtp_check_and_send_back_rr(RTPDemuxContext *s, int count)
         return -1;
     s->last_octet_count = s->octet_count;
 
-    if (url_open_dyn_buf(&pb) < 0)
+    if (avio_open_dyn_buf(&pb) < 0)
         return -1;
 
     // Receiver Report
-    put_byte(pb, (RTP_VERSION << 6) + 1); /* 1 report block */
-    put_byte(pb, 201);
-    put_be16(pb, 7); /* length in words - 1 */
-    put_be32(pb, s->ssrc); // our own SSRC
-    put_be32(pb, s->ssrc); // XXX: should be the server's here!
+    avio_w8(pb, (RTP_VERSION << 6) + 1); /* 1 report block */
+    avio_w8(pb, RTCP_RR);
+    avio_wb16(pb, 7); /* length in words - 1 */
+    // our own SSRC: we use the server's SSRC + 1 to avoid conflicts
+    avio_wb32(pb, s->ssrc + 1);
+    avio_wb32(pb, s->ssrc); // server SSRC
     // some placeholders we should really fill...
     // RFC 1889/p64
     extended_max= stats->cycles + stats->max_seq;
@@ -232,43 +291,43 @@ int rtp_check_and_send_back_rr(RTPDemuxContext *s, int count)
 
     fraction= (fraction<<24) | lost;
 
-    put_be32(pb, fraction); /* 8 bits of fraction, 24 bits of total packets lost */
-    put_be32(pb, extended_max); /* max sequence received */
-    put_be32(pb, stats->jitter>>4); /* jitter */
+    avio_wb32(pb, fraction); /* 8 bits of fraction, 24 bits of total packets lost */
+    avio_wb32(pb, extended_max); /* max sequence received */
+    avio_wb32(pb, stats->jitter>>4); /* jitter */
 
     if(s->last_rtcp_ntp_time==AV_NOPTS_VALUE)
     {
-        put_be32(pb, 0); /* last SR timestamp */
-        put_be32(pb, 0); /* delay since last SR */
+        avio_wb32(pb, 0); /* last SR timestamp */
+        avio_wb32(pb, 0); /* delay since last SR */
     } else {
         uint32_t middle_32_bits= s->last_rtcp_ntp_time>>16; // this is valid, right? do we need to handle 64 bit values special?
         uint32_t delay_since_last= ntp_time - s->last_rtcp_ntp_time;
 
-        put_be32(pb, middle_32_bits); /* last SR timestamp */
-        put_be32(pb, delay_since_last); /* delay since last SR */
+        avio_wb32(pb, middle_32_bits); /* last SR timestamp */
+        avio_wb32(pb, delay_since_last); /* delay since last SR */
     }
 
     // CNAME
-    put_byte(pb, (RTP_VERSION << 6) + 1); /* 1 report block */
-    put_byte(pb, 202);
+    avio_w8(pb, (RTP_VERSION << 6) + 1); /* 1 report block */
+    avio_w8(pb, RTCP_SDES);
     len = strlen(s->hostname);
-    put_be16(pb, (6 + len + 3) / 4); /* length in words - 1 */
-    put_be32(pb, s->ssrc);
-    put_byte(pb, 0x01);
-    put_byte(pb, len);
-    put_buffer(pb, s->hostname, len);
+    avio_wb16(pb, (6 + len + 3) / 4); /* length in words - 1 */
+    avio_wb32(pb, s->ssrc);
+    avio_w8(pb, 0x01);
+    avio_w8(pb, len);
+    avio_write(pb, s->hostname, len);
     // padding
     for (len = (6 + len) % 4; len % 4; len++) {
-        put_byte(pb, 0);
+        avio_w8(pb, 0);
     }
 
-    put_flush_packet(pb);
-    len = url_close_dyn_buf(pb, &buf);
+    avio_flush(pb);
+    len = avio_close_dyn_buf(pb, &buf);
     if ((len > 0) && buf) {
         int result;
-        dprintf(s->ic, "sending %d bytes of RR\n", len);
-        result= url_write(s->rtp_ctx, buf, len);
-        dprintf(s->ic, "result from url_write: %d\n", result);
+        av_dlog(s->ic, "sending %d bytes of RR\n", len);
+        result= ffurl_write(s->rtp_ctx, buf, len);
+        av_dlog(s->ic, "result from ffurl_write: %d\n", result);
         av_free(buf);
     }
     return 0;
@@ -276,39 +335,39 @@ int rtp_check_and_send_back_rr(RTPDemuxContext *s, int count)
 
 void rtp_send_punch_packets(URLContext* rtp_handle)
 {
-    ByteIOContext *pb;
+    AVIOContext *pb;
     uint8_t *buf;
     int len;
 
     /* Send a small RTP packet */
-    if (url_open_dyn_buf(&pb) < 0)
+    if (avio_open_dyn_buf(&pb) < 0)
         return;
 
-    put_byte(pb, (RTP_VERSION << 6));
-    put_byte(pb, 0); /* Payload type */
-    put_be16(pb, 0); /* Seq */
-    put_be32(pb, 0); /* Timestamp */
-    put_be32(pb, 0); /* SSRC */
+    avio_w8(pb, (RTP_VERSION << 6));
+    avio_w8(pb, 0); /* Payload type */
+    avio_wb16(pb, 0); /* Seq */
+    avio_wb32(pb, 0); /* Timestamp */
+    avio_wb32(pb, 0); /* SSRC */
 
-    put_flush_packet(pb);
-    len = url_close_dyn_buf(pb, &buf);
+    avio_flush(pb);
+    len = avio_close_dyn_buf(pb, &buf);
     if ((len > 0) && buf)
-        url_write(rtp_handle, buf, len);
+        ffurl_write(rtp_handle, buf, len);
     av_free(buf);
 
     /* Send a minimal RTCP RR */
-    if (url_open_dyn_buf(&pb) < 0)
+    if (avio_open_dyn_buf(&pb) < 0)
         return;
 
-    put_byte(pb, (RTP_VERSION << 6));
-    put_byte(pb, 201); /* receiver report */
-    put_be16(pb, 1); /* length in words - 1 */
-    put_be32(pb, 0); /* our own SSRC */
+    avio_w8(pb, (RTP_VERSION << 6));
+    avio_w8(pb, RTCP_RR); /* receiver report */
+    avio_wb16(pb, 1); /* length in words - 1 */
+    avio_wb32(pb, 0); /* our own SSRC */
 
-    put_flush_packet(pb);
-    len = url_close_dyn_buf(pb, &buf);
+    avio_flush(pb);
+    len = avio_close_dyn_buf(pb, &buf);
     if ((len > 0) && buf)
-        url_write(rtp_handle, buf, len);
+        ffurl_write(rtp_handle, buf, len);
     av_free(buf);
 }
 
@@ -317,9 +376,8 @@ void rtp_send_punch_packets(URLContext* rtp_handle)
  * open a new RTP parse context for stream 'st'. 'st' can be NULL for
  * MPEG2TS streams to indicate that they should be demuxed inside the
  * rtp demux (otherwise CODEC_ID_MPEG2TS packets are returned)
- * TODO: change this to not take rtp_payload data, and use the new dynamic payload system.
  */
-RTPDemuxContext *rtp_parse_open(AVFormatContext *s1, AVStream *st, URLContext *rtpc, int payload_type, RTPPayloadData *rtp_payload_data)
+RTPDemuxContext *rtp_parse_open(AVFormatContext *s1, AVStream *st, URLContext *rtpc, int payload_type, int queue_size)
 {
     RTPDemuxContext *s;
 
@@ -331,7 +389,7 @@ RTPDemuxContext *rtp_parse_open(AVFormatContext *s1, AVStream *st, URLContext *r
     s->first_rtcp_ntp_time = AV_NOPTS_VALUE;
     s->ic = s1;
     s->st = st;
-    s->rtp_payload_data = rtp_payload_data;
+    s->queue_size = queue_size;
     rtp_init_statistics(&s->statistics, 0); // do we know the initial sequence from sdp?
     if (!strcmp(ff_rtp_enc_name(payload_type), "MP2T")) {
         s->ts = ff_mpegts_parse_open(s->ic);
@@ -340,7 +398,6 @@ RTPDemuxContext *rtp_parse_open(AVFormatContext *s1, AVStream *st, URLContext *r
             return NULL;
         }
     } else {
-        av_set_pts_info(st, 32, 1, 90000);
         switch(st->codec->codec_id) {
         case CODEC_ID_MPEG1VIDEO:
         case CODEC_ID_MPEG2VIDEO:
@@ -351,10 +408,13 @@ RTPDemuxContext *rtp_parse_open(AVFormatContext *s1, AVStream *st, URLContext *r
         case CODEC_ID_H264:
             st->need_parsing = AVSTREAM_PARSE_FULL;
             break;
+        case CODEC_ID_ADPCM_G722:
+            /* According to RFC 3551, the stream clock rate is 8000
+             * even if the sample rate is 16000. */
+            if (st->codec->sample_rate == 8000)
+                st->codec->sample_rate = 16000;
+            break;
         default:
-            if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
-                av_set_pts_info(st, 32, 1, st->codec->sample_rate);
-            }
             break;
         }
     }
@@ -372,64 +432,14 @@ rtp_parse_set_dynamic_protocol(RTPDemuxContext *s, PayloadContext *ctx,
     s->parse_packet = handler->parse_packet;
 }
 
-static int rtp_parse_mp4_au(RTPDemuxContext *s, const uint8_t *buf)
-{
-    int au_headers_length, au_header_size, i;
-    GetBitContext getbitcontext;
-    RTPPayloadData *infos;
-
-    infos = s->rtp_payload_data;
-
-    if (infos == NULL)
-        return -1;
-
-    /* decode the first 2 bytes where the AUHeader sections are stored
-       length in bits */
-    au_headers_length = AV_RB16(buf);
-
-    if (au_headers_length > RTP_MAX_PACKET_LENGTH)
-      return -1;
-
-    infos->au_headers_length_bytes = (au_headers_length + 7) / 8;
-
-    /* skip AU headers length section (2 bytes) */
-    buf += 2;
-
-    init_get_bits(&getbitcontext, buf, infos->au_headers_length_bytes * 8);
-
-    /* XXX: Wrong if optionnal additional sections are present (cts, dts etc...) */
-    au_header_size = infos->sizelength + infos->indexlength;
-    if (au_header_size <= 0 || (au_headers_length % au_header_size != 0))
-        return -1;
-
-    infos->nb_au_headers = au_headers_length / au_header_size;
-    if (!infos->au_headers || infos->au_headers_allocated < infos->nb_au_headers) {
-        av_free(infos->au_headers);
-        infos->au_headers = av_malloc(sizeof(struct AUHeaders) * infos->nb_au_headers);
-        infos->au_headers_allocated = infos->nb_au_headers;
-    }
-
-    /* XXX: We handle multiple AU Section as only one (need to fix this for interleaving)
-       In my test, the FAAD decoder does not behave correctly when sending each AU one by one
-       but does when sending the whole as one big packet...  */
-    infos->au_headers[0].size = 0;
-    infos->au_headers[0].index = 0;
-    for (i = 0; i < infos->nb_au_headers; ++i) {
-        infos->au_headers[0].size += get_bits_long(&getbitcontext, infos->sizelength);
-        infos->au_headers[0].index = get_bits_long(&getbitcontext, infos->indexlength);
-    }
-
-    infos->nb_au_headers = 1;
-
-    return 0;
-}
-
 /**
  * This was the second switch in rtp_parse packet.  Normalizes time, if required, sets stream_index, etc.
  */
 static void finalize_packet(RTPDemuxContext *s, AVPacket *pkt, uint32_t timestamp)
 {
-    if (s->last_rtcp_ntp_time != AV_NOPTS_VALUE) {
+    if (pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE)
+        return; /* Timestamp already set by depacketizer */
+    if (s->last_rtcp_ntp_time != AV_NOPTS_VALUE && timestamp != RTP_NOTS_VALUE) {
         int64_t addend;
         int delta_timestamp;
 
@@ -437,61 +447,28 @@ static void finalize_packet(RTPDemuxContext *s, AVPacket *pkt, uint32_t timestam
         delta_timestamp = timestamp - s->last_rtcp_timestamp;
         /* convert to the PTS timebase */
         addend = av_rescale(s->last_rtcp_ntp_time - s->first_rtcp_ntp_time, s->st->time_base.den, (uint64_t)s->st->time_base.num << 32);
-        pkt->pts = s->range_start_offset + addend + delta_timestamp;
+        pkt->pts = s->range_start_offset + s->rtcp_ts_offset + addend +
+                   delta_timestamp;
+        return;
     }
+    if (timestamp == RTP_NOTS_VALUE)
+        return;
+    if (!s->base_timestamp)
+        s->base_timestamp = timestamp;
+    pkt->pts = s->range_start_offset + timestamp - s->base_timestamp;
 }
 
-/**
- * Parse an RTP or RTCP packet directly sent as a buffer.
- * @param s RTP parse context.
- * @param pkt returned packet
- * @param buf input buffer or NULL to read the next packets
- * @param len buffer len
- * @return 0 if a packet is returned, 1 if a packet is returned and more can follow
- * (use buf as NULL to read the next). -1 if no packet (error or no more packet).
- */
-int rtp_parse_packet(RTPDemuxContext *s, AVPacket *pkt,
-                     const uint8_t *buf, int len)
+static int rtp_parse_packet_internal(RTPDemuxContext *s, AVPacket *pkt,
+                                     const uint8_t *buf, int len)
 {
     unsigned int ssrc, h;
     int payload_type, seq, ret, flags = 0;
+    int ext;
     AVStream *st;
     uint32_t timestamp;
     int rv= 0;
 
-    if (!buf) {
-        /* return the next packets, if any */
-        if(s->st && s->parse_packet) {
-            timestamp= 0; ///< Should not be used if buf is NULL, but should be set to the timestamp of the packet returned....
-            rv= s->parse_packet(s->ic, s->dynamic_protocol_context,
-                                s->st, pkt, &timestamp, NULL, 0, flags);
-            finalize_packet(s, pkt, timestamp);
-            return rv;
-        } else {
-            // TODO: Move to a dynamic packet handler (like above)
-            if (s->read_buf_index >= s->read_buf_size)
-                return -1;
-            ret = ff_mpegts_parse_packet(s->ts, pkt, s->buf + s->read_buf_index,
-                                      s->read_buf_size - s->read_buf_index);
-            if (ret < 0)
-                return -1;
-            s->read_buf_index += ret;
-            if (s->read_buf_index < s->read_buf_size)
-                return 1;
-            else
-                return 0;
-        }
-    }
-
-    if (len < 12)
-        return -1;
-
-    if ((buf[0] & 0xc0) != (RTP_VERSION << 6))
-        return -1;
-    if (buf[1] >= 200 && buf[1] <= 204) {
-        rtcp_parse_packet(s, buf, len);
-        return -1;
-    }
+    ext = buf[0] & 0x10;
     payload_type = buf[1] & 0x7f;
     if (buf[1] & 0x80)
         flags |= RTP_FLAG_MARKER;
@@ -514,15 +491,39 @@ int rtp_parse_packet(RTPDemuxContext *s, AVPacket *pkt,
         return -1;
     }
 
+    if (buf[0] & 0x20) {
+        int padding = buf[len - 1];
+        if (len >= 12 + padding)
+            len -= padding;
+    }
+
     s->seq = seq;
     len -= 12;
     buf += 12;
 
+    /* RFC 3550 Section 5.3.1 RTP Header Extension handling */
+    if (ext) {
+        if (len < 4)
+            return -1;
+        /* calculate the header extension length (stored as number
+         * of 32-bit words) */
+        ext = (AV_RB16(buf + 2) + 1) << 2;
+
+        if (len < ext)
+            return -1;
+        // skip past RTP header extension
+        len -= ext;
+        buf += ext;
+    }
+
     if (!st) {
         /* specific MPEG2TS demux support */
         ret = ff_mpegts_parse_packet(s->ts, pkt, buf, len);
+        /* The only error that can be returned from ff_mpegts_parse_packet
+         * is "no more data to return from the provided buffer", so return
+         * AVERROR(EAGAIN) for all errors */
         if (ret < 0)
-            return -1;
+            return AVERROR(EAGAIN);
         if (ret < len) {
             s->read_buf_size = len - ret;
             memcpy(s->buf, buf + ret, s->read_buf_size);
@@ -565,29 +566,6 @@ int rtp_parse_packet(RTPDemuxContext *s, AVPacket *pkt,
             av_new_packet(pkt, len);
             memcpy(pkt->data, buf, len);
             break;
-            // moved from below, verbatim.  this is because this section handles packets, and the lower switch handles
-            // timestamps.
-            // TODO: Put this into a dynamic packet handler...
-        case CODEC_ID_AAC:
-            if (rtp_parse_mp4_au(s, buf))
-                return -1;
-            {
-                RTPPayloadData *infos = s->rtp_payload_data;
-                if (infos == NULL)
-                    return -1;
-                buf += infos->au_headers_length_bytes + 2;
-                len -= infos->au_headers_length_bytes + 2;
-
-                /* XXX: Fixme we only handle the case where rtp_parse_mp4_au define
-                    one au_header */
-                av_new_packet(pkt, infos->au_headers[0].size);
-                memcpy(pkt->data, buf, infos->au_headers[0].size);
-                buf += infos->au_headers[0].size;
-                len -= infos->au_headers[0].size;
-            }
-            s->read_buf_size = len;
-            rv= 0;
-            break;
         default:
             av_new_packet(pkt, len);
             memcpy(pkt->data, buf, len);
@@ -603,13 +581,214 @@ int rtp_parse_packet(RTPDemuxContext *s, AVPacket *pkt,
     return rv;
 }
 
+void ff_rtp_reset_packet_queue(RTPDemuxContext *s)
+{
+    while (s->queue) {
+        RTPPacket *next = s->queue->next;
+        av_free(s->queue->buf);
+        av_free(s->queue);
+        s->queue = next;
+    }
+    s->seq       = 0;
+    s->queue_len = 0;
+    s->prev_ret  = 0;
+}
+
+static void enqueue_packet(RTPDemuxContext *s, uint8_t *buf, int len)
+{
+    uint16_t seq = AV_RB16(buf + 2);
+    RTPPacket *cur = s->queue, *prev = NULL, *packet;
+
+    /* Find the correct place in the queue to insert the packet */
+    while (cur) {
+        int16_t diff = seq - cur->seq;
+        if (diff < 0)
+            break;
+        prev = cur;
+        cur = cur->next;
+    }
+
+    packet = av_mallocz(sizeof(*packet));
+    if (!packet)
+        return;
+    packet->recvtime = av_gettime();
+    packet->seq = seq;
+    packet->len = len;
+    packet->buf = buf;
+    packet->next = cur;
+    if (prev)
+        prev->next = packet;
+    else
+        s->queue = packet;
+    s->queue_len++;
+}
+
+static int has_next_packet(RTPDemuxContext *s)
+{
+    return s->queue && s->queue->seq == (uint16_t) (s->seq + 1);
+}
+
+int64_t ff_rtp_queued_packet_time(RTPDemuxContext *s)
+{
+    return s->queue ? s->queue->recvtime : 0;
+}
+
+static int rtp_parse_queued_packet(RTPDemuxContext *s, AVPacket *pkt)
+{
+    int rv;
+    RTPPacket *next;
+
+    if (s->queue_len <= 0)
+        return -1;
+
+    if (!has_next_packet(s))
+        av_log(s->st ? s->st->codec : NULL, AV_LOG_WARNING,
+               "RTP: missed %d packets\n", s->queue->seq - s->seq - 1);
+
+    /* Parse the first packet in the queue, and dequeue it */
+    rv = rtp_parse_packet_internal(s, pkt, s->queue->buf, s->queue->len);
+    next = s->queue->next;
+    av_free(s->queue->buf);
+    av_free(s->queue);
+    s->queue = next;
+    s->queue_len--;
+    return rv;
+}
+
+static int rtp_parse_one_packet(RTPDemuxContext *s, AVPacket *pkt,
+                     uint8_t **bufptr, int len)
+{
+    uint8_t* buf = bufptr ? *bufptr : NULL;
+    int ret, flags = 0;
+    uint32_t timestamp;
+    int rv= 0;
+
+    if (!buf) {
+        /* If parsing of the previous packet actually returned 0 or an error,
+         * there's nothing more to be parsed from that packet, but we may have
+         * indicated that we can return the next enqueued packet. */
+        if (s->prev_ret <= 0)
+            return rtp_parse_queued_packet(s, pkt);
+        /* return the next packets, if any */
+        if(s->st && s->parse_packet) {
+            /* timestamp should be overwritten by parse_packet, if not,
+             * the packet is left with pts == AV_NOPTS_VALUE */
+            timestamp = RTP_NOTS_VALUE;
+            rv= s->parse_packet(s->ic, s->dynamic_protocol_context,
+                                s->st, pkt, &timestamp, NULL, 0, flags);
+            finalize_packet(s, pkt, timestamp);
+            return rv;
+        } else {
+            // TODO: Move to a dynamic packet handler (like above)
+            if (s->read_buf_index >= s->read_buf_size)
+                return AVERROR(EAGAIN);
+            ret = ff_mpegts_parse_packet(s->ts, pkt, s->buf + s->read_buf_index,
+                                      s->read_buf_size - s->read_buf_index);
+            if (ret < 0)
+                return AVERROR(EAGAIN);
+            s->read_buf_index += ret;
+            if (s->read_buf_index < s->read_buf_size)
+                return 1;
+            else
+                return 0;
+        }
+    }
+
+    if (len < 12)
+        return -1;
+
+    if ((buf[0] & 0xc0) != (RTP_VERSION << 6))
+        return -1;
+    if (buf[1] >= RTCP_SR && buf[1] <= RTCP_APP) {
+        return rtcp_parse_packet(s, buf, len);
+    }
+
+    if ((s->seq == 0 && !s->queue) || s->queue_size <= 1) {
+        /* First packet, or no reordering */
+        return rtp_parse_packet_internal(s, pkt, buf, len);
+    } else {
+        uint16_t seq = AV_RB16(buf + 2);
+        int16_t diff = seq - s->seq;
+        if (diff < 0) {
+            /* Packet older than the previously emitted one, drop */
+            av_log(s->st ? s->st->codec : NULL, AV_LOG_WARNING,
+                   "RTP: dropping old packet received too late\n");
+            return -1;
+        } else if (diff <= 1) {
+            /* Correct packet */
+            rv = rtp_parse_packet_internal(s, pkt, buf, len);
+            return rv;
+        } else {
+            /* Still missing some packet, enqueue this one. */
+            enqueue_packet(s, buf, len);
+            *bufptr = NULL;
+            /* Return the first enqueued packet if the queue is full,
+             * even if we're missing something */
+            if (s->queue_len >= s->queue_size)
+                return rtp_parse_queued_packet(s, pkt);
+            return -1;
+        }
+    }
+}
+
+/**
+ * Parse an RTP or RTCP packet directly sent as a buffer.
+ * @param s RTP parse context.
+ * @param pkt returned packet
+ * @param bufptr pointer to the input buffer or NULL to read the next packets
+ * @param len buffer len
+ * @return 0 if a packet is returned, 1 if a packet is returned and more can follow
+ * (use buf as NULL to read the next). -1 if no packet (error or no more packet).
+ */
+int rtp_parse_packet(RTPDemuxContext *s, AVPacket *pkt,
+                     uint8_t **bufptr, int len)
+{
+    int rv = rtp_parse_one_packet(s, pkt, bufptr, len);
+    s->prev_ret = rv;
+    while (rv == AVERROR(EAGAIN) && has_next_packet(s))
+        rv = rtp_parse_queued_packet(s, pkt);
+    return rv ? rv : has_next_packet(s);
+}
+
 void rtp_parse_close(RTPDemuxContext *s)
 {
-    // TODO: fold this into the protocol specific data fields.
-    av_free(s->rtp_payload_data->mode);
-    av_free(s->rtp_payload_data->au_headers);
+    ff_rtp_reset_packet_queue(s);
     if (!strcmp(ff_rtp_enc_name(s->payload_type), "MP2T")) {
         ff_mpegts_parse_close(s->ts);
     }
     av_free(s);
 }
+
+int ff_parse_fmtp(AVStream *stream, PayloadContext *data, const char *p,
+                  int (*parse_fmtp)(AVStream *stream,
+                                    PayloadContext *data,
+                                    char *attr, char *value))
+{
+    char attr[256];
+    char *value;
+    int res;
+    int value_size = strlen(p) + 1;
+
+    if (!(value = av_malloc(value_size))) {
+        av_log(stream, AV_LOG_ERROR, "Failed to allocate data for FMTP.");
+        return AVERROR(ENOMEM);
+    }
+
+    // remove protocol identifier
+    while (*p && *p == ' ') p++; // strip spaces
+    while (*p && *p != ' ') p++; // eat protocol identifier
+    while (*p && *p == ' ') p++; // strip trailing spaces
+
+    while (ff_rtsp_next_attr_and_value(&p,
+                                       attr, sizeof(attr),
+                                       value, value_size)) {
+
+        res = parse_fmtp(stream, data, attr, value);
+        if (res < 0 && res != AVERROR_PATCHWELCOME) {
+            av_free(value);
+            return res;
+        }
+    }
+    av_free(value);
+    return 0;
+}
diff --git a/libavformat/rtpdec.h b/libavformat/rtpdec.h
index 477ab72..da53efc 100644
--- a/libavformat/rtpdec.h
+++ b/libavformat/rtpdec.h
@@ -3,20 +3,20 @@
  * Copyright (c) 2002 Fabrice Bellard
  * Copyright (c) 2006 Ryan Martell <rdm4 at martellventures.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #ifndef AVFORMAT_RTPDEC_H
@@ -25,34 +25,7 @@
 #include "libavcodec/avcodec.h"
 #include "avformat.h"
 #include "rtp.h"
-
-/** Structure listing useful vars to parse RTP packet payload*/
-typedef struct rtp_payload_data
-{
-    int sizelength;
-    int indexlength;
-    int indexdeltalength;
-    int profile_level_id;
-    int streamtype;
-    int objecttype;
-    char *mode;
-
-    /** mpeg 4 AU headers */
-    struct AUHeaders {
-        int size;
-        int index;
-        int cts_flag;
-        int cts;
-        int dts_flag;
-        int dts;
-        int rap_flag;
-        int streamstate;
-    } *au_headers;
-    int au_headers_allocated;
-    int nb_au_headers;
-    int au_headers_length_bytes;
-    int cur_au_index;
-} RTPPayloadData;
+#include "url.h"
 
 typedef struct PayloadContext PayloadContext;
 typedef struct RTPDynamicProtocolHandler_s RTPDynamicProtocolHandler;
@@ -60,23 +33,23 @@ typedef struct RTPDynamicProtocolHandler_s RTPDynamicProtocolHandler;
 #define RTP_MIN_PACKET_LENGTH 12
 #define RTP_MAX_PACKET_LENGTH 1500 /* XXX: suppress this define */
 
+#define RTP_REORDER_QUEUE_DEFAULT_SIZE 10
+
+#define RTP_NOTS_VALUE ((uint32_t)-1)
+
 typedef struct RTPDemuxContext RTPDemuxContext;
-RTPDemuxContext *rtp_parse_open(AVFormatContext *s1, AVStream *st, URLContext *rtpc, int payload_type, RTPPayloadData *rtp_payload_data);
+RTPDemuxContext *rtp_parse_open(AVFormatContext *s1, AVStream *st, URLContext *rtpc, int payload_type, int queue_size);
 void rtp_parse_set_dynamic_protocol(RTPDemuxContext *s, PayloadContext *ctx,
                                     RTPDynamicProtocolHandler *handler);
 int rtp_parse_packet(RTPDemuxContext *s, AVPacket *pkt,
-                     const uint8_t *buf, int len);
+                     uint8_t **buf, int len);
 void rtp_parse_close(RTPDemuxContext *s);
-#if (LIBAVFORMAT_VERSION_MAJOR <= 53)
-int rtp_get_local_port(URLContext *h);
-#endif
+int64_t ff_rtp_queued_packet_time(RTPDemuxContext *s);
+void ff_rtp_reset_packet_queue(RTPDemuxContext *s);
 int rtp_get_local_rtp_port(URLContext *h);
 int rtp_get_local_rtcp_port(URLContext *h);
 
 int rtp_set_remote_url(URLContext *h, const char *uri);
-#if (LIBAVFORMAT_VERSION_MAJOR <= 52)
-void rtp_get_file_handles(URLContext *h, int *prtp_fd, int *prtcp_fd);
-#endif
 
 /**
  * Send a dummy packet on both port pairs to set up the connection
@@ -98,6 +71,11 @@ void rtp_send_punch_packets(URLContext* rtp_handle);
  */
 int rtp_check_and_send_back_rr(RTPDemuxContext *s, int count);
 
+/**
+ * Get the file handle for the RTCP socket.
+ */
+int rtp_get_rtcp_file_handle(URLContext *h);
+
 // these statistics are used for rtcp receiver reports...
 typedef struct {
     uint16_t max_seq;           ///< highest sequence number seen
@@ -139,6 +117,9 @@ struct RTPDynamicProtocolHandler_s {
     const char enc_name[50];    /* XXX: still why 50 ? ;-) */
     enum AVMediaType codec_type;
     enum CodecID codec_id;
+    int static_payload_id; /* 0 means no payload id is set. 0 is a valid
+                            * payload ID (PCMU), too, but that format doesn't
+                            * require any custom depacketization code. */
 
     // may be null
     int (*parse_sdp_a_line) (AVFormatContext *s,
@@ -152,6 +133,14 @@ struct RTPDynamicProtocolHandler_s {
     struct RTPDynamicProtocolHandler_s *next;
 };
 
+typedef struct RTPPacket {
+    uint16_t seq;
+    uint8_t *buf;
+    int len;
+    int64_t recvtime;
+    struct RTPPacket *next;
+} RTPPacket;
+
 // moved out of rtp.c, because the h264 decoder needs to know about this structure..
 struct RTPDemuxContext {
     AVFormatContext *ic;
@@ -173,10 +162,18 @@ struct RTPDemuxContext {
 
     RTPStatistics statistics; ///< Statistics for this stream (used by RTCP receiver reports)
 
+    /** Fields for packet reordering @{ */
+    int prev_ret;     ///< The return value of the actual parsing of the previous packet
+    RTPPacket* queue; ///< A sorted queue of buffered packets not yet returned
+    int queue_len;    ///< The number of packets in queue
+    int queue_size;   ///< The size of queue, or 0 if reordering is disabled
+    /*@}*/
+
     /* rtcp sender statistics receive */
     int64_t last_rtcp_ntp_time;    // TODO: move into statistics
     int64_t first_rtcp_ntp_time;   // TODO: move into statistics
     uint32_t last_rtcp_timestamp;  // TODO: move into statistics
+    int64_t rtcp_ts_offset;
 
     /* rtcp sender statistics */
     unsigned int packet_count;     // TODO: move into statistics (outgoing)
@@ -187,20 +184,25 @@ struct RTPDemuxContext {
     uint8_t buf[RTP_MAX_PACKET_LENGTH];
     uint8_t *buf_ptr;
 
-    /* special infos for au headers parsing */
-    RTPPayloadData *rtp_payload_data; // TODO: Move into dynamic payload handlers
-
     /* dynamic payload stuff */
     DynamicPayloadPacketHandlerProc parse_packet;     ///< This is also copied from the dynamic protocol handler structure
     PayloadContext *dynamic_protocol_context;        ///< This is a copy from the values setup from the sdp parsing, in rtsp.c don't free me.
     int max_frames_per_packet;
 };
 
-extern RTPDynamicProtocolHandler *RTPFirstDynamicPayloadHandler;
 void ff_register_dynamic_payload_handler(RTPDynamicProtocolHandler *handler);
+RTPDynamicProtocolHandler *ff_rtp_handler_find_by_name(const char *name,
+                                                  enum AVMediaType codec_type);
+RTPDynamicProtocolHandler *ff_rtp_handler_find_by_id(int id,
+                                                enum AVMediaType codec_type);
 
 int ff_rtsp_next_attr_and_value(const char **p, char *attr, int attr_size, char *value, int value_size); ///< from rtsp.c, but used by rtp dynamic protocol handlers.
 
+int ff_parse_fmtp(AVStream *stream, PayloadContext *data, const char *p,
+                  int (*parse_fmtp)(AVStream *stream,
+                                    PayloadContext *data,
+                                    char *attr, char *value));
+
 void av_register_rtp_dynamic_payload_handlers(void);
 
 #endif /* AVFORMAT_RTPDEC_H */
diff --git a/libavformat/rtpdec_amr.c b/libavformat/rtpdec_amr.c
index a7b36c7..802e7c1 100644
--- a/libavformat/rtpdec_amr.c
+++ b/libavformat/rtpdec_amr.c
@@ -2,25 +2,25 @@
  * RTP AMR Depacketizer, RFC 3267
  * Copyright (c) 2010 Martin Storsjo
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "avformat.h"
-#include "rtpdec_amr.h"
+#include "rtpdec_formats.h"
 #include "libavutil/avstring.h"
 
 static const uint8_t frame_sizes_nb[16] = {
@@ -30,6 +30,26 @@ static const uint8_t frame_sizes_wb[16] = {
     17, 23, 32, 36, 40, 46, 50, 58, 60, 5, 5, 0, 0, 0, 0, 0
 };
 
+struct PayloadContext {
+    int octet_align;
+    int crc;
+    int interleaving;
+    int channels;
+};
+
+static PayloadContext *amr_new_context(void)
+{
+    PayloadContext *data = av_mallocz(sizeof(PayloadContext));
+    if(!data) return data;
+    data->channels = 1;
+    return data;
+}
+
+static void amr_free_context(PayloadContext *data)
+{
+    av_free(data);
+}
+
 static int amr_handle_packet(AVFormatContext *ctx,
                              PayloadContext *data,
                              AVStream *st,
@@ -120,11 +140,34 @@ static int amr_handle_packet(AVFormatContext *ctx,
     return 0;
 }
 
+static int amr_parse_fmtp(AVStream *stream, PayloadContext *data,
+                          char *attr, char *value)
+{
+    /* Some AMR SDP configurations contain "octet-align", without
+     * the trailing =1. Therefore, if the value is empty,
+     * interpret it as "1".
+     */
+    if (!strcmp(value, "")) {
+        av_log(NULL, AV_LOG_WARNING, "AMR fmtp attribute %s had "
+                                     "nonstandard empty value\n", attr);
+        strcpy(value, "1");
+    }
+    if (!strcmp(attr, "octet-align"))
+        data->octet_align = atoi(value);
+    else if (!strcmp(attr, "crc"))
+        data->crc = atoi(value);
+    else if (!strcmp(attr, "interleaving"))
+        data->interleaving = atoi(value);
+    else if (!strcmp(attr, "channels"))
+        data->channels = atoi(value);
+    return 0;
+}
+
 static int amr_parse_sdp_line(AVFormatContext *s, int st_index,
                               PayloadContext *data, const char *line)
 {
     const char *p;
-    char attr[25], value[25];
+    int ret;
 
     /* Parse an fmtp line this one:
      * a=fmtp:97 octet-align=1; interleaving=0
@@ -132,38 +175,13 @@ static int amr_parse_sdp_line(AVFormatContext *s, int st_index,
      * separated key/value pairs.
      */
     if (av_strstart(line, "fmtp:", &p)) {
-        int octet_align = 0;
-        int crc = 0;
-        int interleaving = 0;
-        int channels = 1;
-
-        while (*p && *p == ' ') p++; /* strip spaces */
-        while (*p && *p != ' ') p++; /* eat protocol identifier */
-        while (*p && *p == ' ') p++; /* strip trailing spaces */
-
-        while (ff_rtsp_next_attr_and_value(&p, attr, sizeof(attr), value, sizeof(value))) {
-            /* Some AMR SDP configurations contain "octet-align", without
-             * the trailing =1. Therefore, if the value is empty,
-             * interpret it as "1".
-             */
-            if (!strcmp(value, "")) {
-                av_log(s, AV_LOG_WARNING, "AMR fmtp attribute %s had "
-                                          "nonstandard empty value\n", attr);
-                strcpy(value, "1");
-            }
-            if (!strcmp(attr, "octet-align"))
-                octet_align = atoi(value);
-            else if (!strcmp(attr, "crc"))
-                crc = atoi(value);
-            else if (!strcmp(attr, "interleaving"))
-                interleaving = atoi(value);
-            else if (!strcmp(attr, "channels"))
-                channels = atoi(value);
-        }
-        if (!octet_align || crc || interleaving || channels != 1) {
+        ret = ff_parse_fmtp(s->streams[st_index], data, p, amr_parse_fmtp);
+        if (!data->octet_align || data->crc ||
+            data->interleaving || data->channels != 1) {
             av_log(s, AV_LOG_ERROR, "Unsupported RTP/AMR configuration!\n");
             return -1;
         }
+        return ret;
     }
     return 0;
 }
@@ -173,6 +191,8 @@ RTPDynamicProtocolHandler ff_amr_nb_dynamic_handler = {
     .codec_type       = AVMEDIA_TYPE_AUDIO,
     .codec_id         = CODEC_ID_AMR_NB,
     .parse_sdp_a_line = amr_parse_sdp_line,
+    .open             = amr_new_context,
+    .close            = amr_free_context,
     .parse_packet     = amr_handle_packet,
 };
 
@@ -181,6 +201,8 @@ RTPDynamicProtocolHandler ff_amr_wb_dynamic_handler = {
     .codec_type       = AVMEDIA_TYPE_AUDIO,
     .codec_id         = CODEC_ID_AMR_WB,
     .parse_sdp_a_line = amr_parse_sdp_line,
+    .open             = amr_new_context,
+    .close            = amr_free_context,
     .parse_packet     = amr_handle_packet,
 };
 
diff --git a/libavformat/rtpdec_amr.h b/libavformat/rtpdec_amr.h
deleted file mode 100644
index 3cd9dd1..0000000
--- a/libavformat/rtpdec_amr.h
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * RTP AMR Depacketizer, RFC 3267
- * Copyright (c) 2010 Martin Storsjo
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-#ifndef AVFORMAT_RTPDEC_AMR_H
-#define AVFORMAT_RTPDEC_AMR_H
-
-#include "rtpdec.h"
-
-extern RTPDynamicProtocolHandler ff_amr_nb_dynamic_handler;
-extern RTPDynamicProtocolHandler ff_amr_wb_dynamic_handler;
-
-#endif /* AVFORMAT_RTPDEC_AMR_H */
diff --git a/libavformat/rtpdec_asf.c b/libavformat/rtpdec_asf.c
index 7ca15f0..a8326cf 100644
--- a/libavformat/rtpdec_asf.c
+++ b/libavformat/rtpdec_asf.c
@@ -2,20 +2,20 @@
  * Microsoft RTP/ASF support.
  * Copyright (c) 2008 Ronald S. Bultje
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,13 +25,14 @@
  * @author Ronald S. Bultje <rbultje at ronald.bitfreak.net>
  */
 
-#include <libavutil/base64.h>
-#include <libavutil/avstring.h>
-#include <libavutil/intreadwrite.h>
+#include "libavutil/base64.h"
+#include "libavutil/avstring.h"
+#include "libavutil/intreadwrite.h"
 #include "rtp.h"
-#include "rtpdec_asf.h"
+#include "rtpdec_formats.h"
 #include "rtsp.h"
 #include "asf.h"
+#include "avio_internal.h"
 
 /**
  * From MSDN 2.2.1.4, we learn that ASF data packets over RTP should not
@@ -72,7 +73,7 @@ static int rtp_asf_fix_header(uint8_t *buf, int len)
 }
 
 /**
- * The following code is basically a buffered ByteIOContext,
+ * The following code is basically a buffered AVIOContext,
  * with the added benefit of returning -EAGAIN (instead of 0)
  * on packet boundaries, such that the ASF demuxer can return
  * safely and resume business at the next packet.
@@ -82,19 +83,20 @@ static int packetizer_read(void *opaque, uint8_t *buf, int buf_size)
     return AVERROR(EAGAIN);
 }
 
-static void init_packetizer(ByteIOContext *pb, uint8_t *buf, int len)
+static void init_packetizer(AVIOContext *pb, uint8_t *buf, int len)
 {
-    init_put_byte(pb, buf, len, 0, NULL, packetizer_read, NULL, NULL);
+    ffio_init_context(pb, buf, len, 0, NULL, packetizer_read, NULL, NULL);
 
     /* this "fills" the buffer with its current content */
     pb->pos     = len;
     pb->buf_end = buf + len;
 }
 
-void ff_wms_parse_sdp_a_line(AVFormatContext *s, const char *p)
+int ff_wms_parse_sdp_a_line(AVFormatContext *s, const char *p)
 {
+    int ret = 0;
     if (av_strstart(p, "pgmpu:data:application/vnd.ms.wms-hdr.asfv1;base64,", &p)) {
-        ByteIOContext pb;
+        AVIOContext pb;
         RTSPState *rt = s->priv_data;
         int len = strlen(p) * 6 / 8;
         char *buf = av_mallocz(len);
@@ -108,11 +110,15 @@ void ff_wms_parse_sdp_a_line(AVFormatContext *s, const char *p)
             av_close_input_stream(rt->asf_ctx);
             rt->asf_ctx = NULL;
         }
-        av_open_input_stream(&rt->asf_ctx, &pb, "", &asf_demuxer, NULL);
-        rt->asf_pb_pos = url_ftell(&pb);
+        ret = av_open_input_stream(&rt->asf_ctx, &pb, "", &ff_asf_demuxer, NULL);
+        if (ret < 0)
+            return ret;
+        av_metadata_copy(&s->metadata, rt->asf_ctx->metadata, 0);
+        rt->asf_pb_pos = avio_tell(&pb);
         av_free(buf);
         rt->asf_ctx->pb = NULL;
     }
+    return ret;
 }
 
 static int asfrtp_parse_sdp_line(AVFormatContext *s, int stream_index,
@@ -142,8 +148,8 @@ static int asfrtp_parse_sdp_line(AVFormatContext *s, int stream_index,
 }
 
 struct PayloadContext {
-    ByteIOContext *pktbuf, pb;
-    char *buf;
+    AVIOContext *pktbuf, pb;
+    uint8_t *buf;
 };
 
 /**
@@ -156,7 +162,7 @@ static int asfrtp_parse_packet(AVFormatContext *s, PayloadContext *asf,
                                uint32_t *timestamp,
                                const uint8_t *buf, int len, int flags)
 {
-    ByteIOContext *pb = &asf->pb;
+    AVIOContext *pb = &asf->pb;
     int res, mflags, len_off;
     RTSPState *rt = s->priv_data;
 
@@ -164,64 +170,72 @@ static int asfrtp_parse_packet(AVFormatContext *s, PayloadContext *asf,
         return -1;
 
     if (len > 0) {
-        int off, out_len;
+        int off, out_len = 0;
 
         if (len < 4)
             return -1;
 
-        init_put_byte(pb, buf, len, 0, NULL, NULL, NULL, NULL);
-        mflags = get_byte(pb);
-        if (mflags & 0x80)
-            flags |= RTP_FLAG_KEY;
-        len_off = get_be24(pb);
-        if (mflags & 0x20)   /**< relative timestamp */
-            url_fskip(pb, 4);
-        if (mflags & 0x10)   /**< has duration */
-            url_fskip(pb, 4);
-        if (mflags & 0x8)    /**< has location ID */
-            url_fskip(pb, 4);
-        off = url_ftell(pb);
-
         av_freep(&asf->buf);
-        if (!(mflags & 0x40)) {
-            /**
-             * If 0x40 is not set, the len_off field specifies an offset of this
-             * packet's payload data in the complete (reassembled) ASF packet.
-             * This is used to spread one ASF packet over multiple RTP packets.
-             */
-            if (asf->pktbuf && len_off != url_ftell(asf->pktbuf)) {
-                uint8_t *p;
-                url_close_dyn_buf(asf->pktbuf, &p);
+
+        ffio_init_context(pb, buf, len, 0, NULL, NULL, NULL, NULL);
+
+        while (avio_tell(pb) + 4 < len) {
+            int start_off = avio_tell(pb);
+
+            mflags = avio_r8(pb);
+            if (mflags & 0x80)
+                flags |= RTP_FLAG_KEY;
+            len_off = avio_rb24(pb);
+            if (mflags & 0x20)   /**< relative timestamp */
+                avio_skip(pb, 4);
+            if (mflags & 0x10)   /**< has duration */
+                avio_skip(pb, 4);
+            if (mflags & 0x8)    /**< has location ID */
+                avio_skip(pb, 4);
+            off = avio_tell(pb);
+
+            if (!(mflags & 0x40)) {
+                /**
+                 * If 0x40 is not set, the len_off field specifies an offset
+                 * of this packet's payload data in the complete (reassembled)
+                 * ASF packet. This is used to spread one ASF packet over
+                 * multiple RTP packets.
+                 */
+                if (asf->pktbuf && len_off != avio_tell(asf->pktbuf)) {
+                    uint8_t *p;
+                    avio_close_dyn_buf(asf->pktbuf, &p);
+                    asf->pktbuf = NULL;
+                    av_free(p);
+                }
+                if (!len_off && !asf->pktbuf &&
+                    (res = avio_open_dyn_buf(&asf->pktbuf)) < 0)
+                    return res;
+                if (!asf->pktbuf)
+                    return AVERROR(EIO);
+
+                avio_write(asf->pktbuf, buf + off, len - off);
+                avio_skip(pb, len - off);
+                if (!(flags & RTP_FLAG_MARKER))
+                    return -1;
+                out_len     = avio_close_dyn_buf(asf->pktbuf, &asf->buf);
                 asf->pktbuf = NULL;
-                av_free(p);
-            }
-            if (!len_off && !asf->pktbuf &&
-                (res = url_open_dyn_buf(&asf->pktbuf)) < 0)
-                return res;
-            if (!asf->pktbuf)
-                return AVERROR(EIO);
-
-            put_buffer(asf->pktbuf, buf + off, len - off);
-            if (!(flags & RTP_FLAG_MARKER))
-                return -1;
-            out_len     = url_close_dyn_buf(asf->pktbuf, &asf->buf);
-            asf->pktbuf = NULL;
-        } else {
-            /**
-             * If 0x40 is set, the len_off field specifies the length of the
-             * next ASF packet that can be read from this payload data alone.
-             * This is commonly the same as the payload size, but could be
-             * less in case of packet splitting (i.e. multiple ASF packets in
-             * one RTP packet).
-             */
-            if (len_off != len) {
-                av_log_missing_feature(s,
-                    "RTSP-MS packet splitting", 1);
-                return -1;
+            } else {
+                /**
+                 * If 0x40 is set, the len_off field specifies the length of
+                 * the next ASF packet that can be read from this payload
+                 * data alone. This is commonly the same as the payload size,
+                 * but could be less in case of packet splitting (i.e.
+                 * multiple ASF packets in one RTP packet).
+                 */
+
+                int cur_len = start_off + len_off - off;
+                int prev_len = out_len;
+                out_len += cur_len;
+                asf->buf = av_realloc(asf->buf, out_len);
+                memcpy(asf->buf + prev_len, buf + off,
+                       FFMIN(cur_len, len - off));
+                avio_skip(pb, cur_len);
             }
-            asf->buf = av_malloc(len - off);
-            out_len  = len - off;
-            memcpy(asf->buf, buf + off, len - off);
         }
 
         init_packetizer(pb, asf->buf, out_len);
@@ -234,7 +248,7 @@ static int asfrtp_parse_packet(AVFormatContext *s, PayloadContext *asf,
         int i;
 
         res = av_read_packet(rt->asf_ctx, pkt);
-        rt->asf_pb_pos = url_ftell(pb);
+        rt->asf_pb_pos = avio_tell(pb);
         if (res != 0)
             break;
         for (i = 0; i < s->nb_streams; i++) {
@@ -258,7 +272,7 @@ static void asfrtp_free_context(PayloadContext *asf)
 {
     if (asf->pktbuf) {
         uint8_t *p = NULL;
-        url_close_dyn_buf(asf->pktbuf, &p);
+        avio_close_dyn_buf(asf->pktbuf, &p);
         asf->pktbuf = NULL;
         av_free(p);
     }
@@ -275,7 +289,7 @@ RTPDynamicProtocolHandler ff_ms_rtp_ ## n ## _handler = { \
     .open             = asfrtp_new_context, \
     .close            = asfrtp_free_context, \
     .parse_packet     = asfrtp_parse_packet,   \
-};
+}
 
 RTP_ASF_HANDLER(asf_pfv, "x-asf-pf",  AVMEDIA_TYPE_VIDEO);
 RTP_ASF_HANDLER(asf_pfa, "x-asf-pf",  AVMEDIA_TYPE_AUDIO);
diff --git a/libavformat/rtpdec_asf.h b/libavformat/rtpdec_asf.h
deleted file mode 100644
index 5d60a14..0000000
--- a/libavformat/rtpdec_asf.h
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Microsoft RTP/ASF support.
- * Copyright (c) 2008 Ronald S. Bultje
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-#ifndef AVFORMAT_RTPDEC_ASF_H
-#define AVFORMAT_RTPDEC_ASF_H
-
-#include "avformat.h"
-#include "rtpdec.h"
-
-/**
- * Parse a Windows Media Server-specific SDP line
- *
- * @param s RTSP demux context
- * @param line the SDP line to be parsed
- */
-void ff_wms_parse_sdp_a_line(AVFormatContext *s, const char *p);
-
-/**
- * Handlers for the x-asf-pf payloads (the payload ID for RTP/ASF).
- * Defined and implemented in rtp_asf.c, registered in rtpdec.c.
- */
-extern RTPDynamicProtocolHandler ff_ms_rtp_asf_pfv_handler,
-                                 ff_ms_rtp_asf_pfa_handler;
-
-#endif /* AVFORMAT_RTPDEC_ASF_H */
diff --git a/libavformat/rtpdec_formats.h b/libavformat/rtpdec_formats.h
new file mode 100644
index 0000000..708c299
--- /dev/null
+++ b/libavformat/rtpdec_formats.h
@@ -0,0 +1,55 @@
+/*
+ * RTP depacketizer declarations
+ * Copyright (c) 2010 Martin Storsjo
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVFORMAT_RTPDEC_FORMATS_H
+#define AVFORMAT_RTPDEC_FORMATS_H
+
+#include "rtpdec.h"
+
+/**
+ * Parse a Windows Media Server-specific SDP line
+ *
+ * @param s RTSP demux context
+ */
+int ff_wms_parse_sdp_a_line(AVFormatContext *s, const char *p);
+
+extern RTPDynamicProtocolHandler ff_amr_nb_dynamic_handler;
+extern RTPDynamicProtocolHandler ff_amr_wb_dynamic_handler;
+extern RTPDynamicProtocolHandler ff_h263_1998_dynamic_handler;
+extern RTPDynamicProtocolHandler ff_h263_2000_dynamic_handler;
+extern RTPDynamicProtocolHandler ff_h264_dynamic_handler;
+extern RTPDynamicProtocolHandler ff_mp4a_latm_dynamic_handler;
+extern RTPDynamicProtocolHandler ff_mp4v_es_dynamic_handler;
+extern RTPDynamicProtocolHandler ff_mpeg4_generic_dynamic_handler;
+extern RTPDynamicProtocolHandler ff_ms_rtp_asf_pfa_handler;
+extern RTPDynamicProtocolHandler ff_ms_rtp_asf_pfv_handler;
+extern RTPDynamicProtocolHandler ff_qcelp_dynamic_handler;
+extern RTPDynamicProtocolHandler ff_qdm2_dynamic_handler;
+extern RTPDynamicProtocolHandler ff_qt_rtp_aud_handler;
+extern RTPDynamicProtocolHandler ff_qt_rtp_vid_handler;
+extern RTPDynamicProtocolHandler ff_quicktime_rtp_aud_handler;
+extern RTPDynamicProtocolHandler ff_quicktime_rtp_vid_handler;
+extern RTPDynamicProtocolHandler ff_svq3_dynamic_handler;
+extern RTPDynamicProtocolHandler ff_theora_dynamic_handler;
+extern RTPDynamicProtocolHandler ff_vorbis_dynamic_handler;
+extern RTPDynamicProtocolHandler ff_vp8_dynamic_handler;
+
+#endif /* AVFORMAT_RTPDEC_FORMATS_H */
diff --git a/libavformat/rtpdec_h263.c b/libavformat/rtpdec_h263.c
index 19de6ec..0fb1b25 100644
--- a/libavformat/rtpdec_h263.c
+++ b/libavformat/rtpdec_h263.c
@@ -2,25 +2,25 @@
  * RTP H.263 Depacketizer, RFC 4629
  * Copyright (c) 2010 Martin Storsjo
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "avformat.h"
-#include "rtpdec_h263.h"
+#include "rtpdec_formats.h"
 #include "libavutil/intreadwrite.h"
 
 static int h263_handle_packet(AVFormatContext *ctx,
diff --git a/libavformat/rtpdec_h263.h b/libavformat/rtpdec_h263.h
deleted file mode 100644
index 5b51128..0000000
--- a/libavformat/rtpdec_h263.h
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * RTP H.263 Depacketizer, RFC 4629
- * Copyright (c) 2010 Martin Storsjo
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-#ifndef AVFORMAT_RTPDEC_H263_H
-#define AVFORMAT_RTPDEC_H263_H
-
-#include "rtpdec.h"
-
-extern RTPDynamicProtocolHandler ff_h263_1998_dynamic_handler;
-extern RTPDynamicProtocolHandler ff_h263_2000_dynamic_handler;
-
-#endif /* AVFORMAT_RTPDEC_H263_H */
diff --git a/libavformat/rtpdec_h264.c b/libavformat/rtpdec_h264.c
index d690173..4c9b8ba 100644
--- a/libavformat/rtpdec_h264.c
+++ b/libavformat/rtpdec_h264.c
@@ -2,20 +2,20 @@
  * RTP H264 Protocol (RFC3984)
  * Copyright (c) 2006 Ryan Martell
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -47,7 +47,7 @@
 #include <assert.h>
 
 #include "rtpdec.h"
-#include "rtpdec_h264.h"
+#include "rtpdec_formats.h"
 
 /**
     RTP/H264 specific private data.
@@ -69,9 +69,9 @@ struct PayloadContext {
 #define DEAD_COOKIE (0xdeaddead)        ///< Cookie for the extradata; once it is freed.
 
 /* ---------------- private code */
-static void sdp_parse_fmtp_config_h264(AVStream * stream,
-                                       PayloadContext * h264_data,
-                                       char *attr, char *value)
+static int sdp_parse_fmtp_config_h264(AVStream * stream,
+                                      PayloadContext * h264_data,
+                                      char *attr, char *value)
 {
     AVCodecContext *codec = stream->codec;
     assert(codec->codec_id == CODEC_ID_H264);
@@ -120,7 +120,7 @@ static void sdp_parse_fmtp_config_h264(AVStream * stream,
         while (*value) {
             char base64packet[1024];
             uint8_t decoded_packet[1024];
-            uint32_t packet_size;
+            int packet_size;
             char *dst = base64packet;
 
             while (*value && *value != ','
@@ -133,7 +133,7 @@ static void sdp_parse_fmtp_config_h264(AVStream * stream,
                 value++;
 
             packet_size= av_base64_decode(decoded_packet, base64packet, sizeof(decoded_packet));
-            if (packet_size) {
+            if (packet_size > 0) {
                 uint8_t *dest = av_malloc(packet_size + sizeof(start_sequence) +
                                          codec->extradata_size +
                                          FF_INPUT_BUFFER_PADDING_SIZE);
@@ -155,11 +155,13 @@ static void sdp_parse_fmtp_config_h264(AVStream * stream,
                     codec->extradata_size+= sizeof(start_sequence)+packet_size;
                 } else {
                     av_log(codec, AV_LOG_ERROR, "Unable to allocate memory for extradata!");
+                    return AVERROR(ENOMEM);
                 }
             }
         }
         av_log(codec, AV_LOG_DEBUG, "Extradata set to %p (size: %d)!", codec->extradata, codec->extradata_size);
     }
+    return 0;
 }
 
 // return 0 on packet, no more left, 1 on packet, 1 on partial packet...
@@ -185,10 +187,7 @@ static int h264_handle_packet(AVFormatContext *ctx,
     if (type >= 1 && type <= 23)
         type = 1;              // simplify the case. (these are all the nal types used internally by the h264 codec)
     switch (type) {
-    case 0:                    // undefined;
-        result= -1;
-        break;
-
+    case 0:                    // undefined, but pass them through
     case 1:
         av_new_packet(pkt, len+sizeof(start_sequence));
         memcpy(pkt->data, start_sequence, sizeof(start_sequence));
@@ -383,26 +382,11 @@ static int parse_h264_sdp_line(AVFormatContext *s, int st_index,
         codec->height = atoi(p + 1); // skip the -
         codec->pix_fmt = PIX_FMT_YUV420P;
     } else if (av_strstart(p, "fmtp:", &p)) {
-        char attr[256];
-        char value[4096];
-
-        // remove the protocol identifier..
-        while (*p && *p == ' ') p++; // strip spaces.
-        while (*p && *p != ' ') p++; // eat protocol identifier
-        while (*p && *p == ' ') p++; // strip trailing spaces.
-
-        /* loop on each attribute */
-        while (ff_rtsp_next_attr_and_value
-               (&p, attr, sizeof(attr), value, sizeof(value))) {
-            /* grab the codec extra_data from the config parameter of the fmtp line */
-            sdp_parse_fmtp_config_h264(stream, h264_data, attr, value);
-        }
+        return ff_parse_fmtp(stream, h264_data, p, sdp_parse_fmtp_config_h264);
     } else if (av_strstart(p, "cliprect:", &p)) {
         // could use this if we wanted.
     }
 
-    av_set_pts_info(stream, 33, 1, 90000);      // 33 should be right, because the pts is 64 bit? (done elsewhere; this is a one time thing)
-
     return 0;                   // keep processing it the normal way...
 }
 
diff --git a/libavformat/rtpdec_h264.h b/libavformat/rtpdec_h264.h
deleted file mode 100644
index b4d54de..0000000
--- a/libavformat/rtpdec_h264.h
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * RTP H264 Protocol (RFC3984)
- * Copyright (c) 2006 Ryan Martell
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-#ifndef AVFORMAT_RTPDEC_H264_H
-#define AVFORMAT_RTPDEC_H264_H
-
-#include "rtpdec.h"
-
-extern RTPDynamicProtocolHandler ff_h264_dynamic_handler;
-
-#endif /* AVFORMAT_RTPDEC_H264_H */
diff --git a/libavformat/rtpdec_latm.c b/libavformat/rtpdec_latm.c
new file mode 100644
index 0000000..5bf4c19
--- /dev/null
+++ b/libavformat/rtpdec_latm.c
@@ -0,0 +1,187 @@
+/**
+ * RTP Depacketization of MP4A-LATM, RFC 3016
+ * Copyright (c) 2010 Martin Storsjo
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "rtpdec_formats.h"
+#include "internal.h"
+#include "libavutil/avstring.h"
+#include "libavcodec/get_bits.h"
+#include <strings.h>
+
+struct PayloadContext {
+    AVIOContext *dyn_buf;
+    uint8_t *buf;
+    int pos, len;
+    uint32_t timestamp;
+};
+
+static PayloadContext *latm_new_context(void)
+{
+    return av_mallocz(sizeof(PayloadContext));
+}
+
+static void latm_free_context(PayloadContext *data)
+{
+    if (!data)
+        return;
+    if (data->dyn_buf) {
+        uint8_t *p;
+        avio_close_dyn_buf(data->dyn_buf, &p);
+        av_free(p);
+    }
+    av_free(data->buf);
+    av_free(data);
+}
+
+static int latm_parse_packet(AVFormatContext *ctx, PayloadContext *data,
+                             AVStream *st, AVPacket *pkt, uint32_t *timestamp,
+                             const uint8_t *buf, int len, int flags)
+{
+    int ret, cur_len;
+
+    if (buf) {
+        if (!data->dyn_buf || data->timestamp != *timestamp) {
+            av_freep(&data->buf);
+            if (data->dyn_buf)
+                avio_close_dyn_buf(data->dyn_buf, &data->buf);
+            data->dyn_buf = NULL;
+            av_freep(&data->buf);
+
+            data->timestamp = *timestamp;
+            if ((ret = avio_open_dyn_buf(&data->dyn_buf)) < 0)
+                return ret;
+        }
+        avio_write(data->dyn_buf, buf, len);
+
+        if (!(flags & RTP_FLAG_MARKER))
+            return AVERROR(EAGAIN);
+        av_free(data->buf);
+        data->len = avio_close_dyn_buf(data->dyn_buf, &data->buf);
+        data->dyn_buf = NULL;
+        data->pos = 0;
+    }
+
+    if (!data->buf) {
+        av_log(ctx, AV_LOG_ERROR, "No data available yet\n");
+        return AVERROR(EIO);
+    }
+
+    cur_len = 0;
+    while (data->pos < data->len) {
+        uint8_t val = data->buf[data->pos++];
+        cur_len += val;
+        if (val != 0xff)
+            break;
+    }
+    if (data->pos + cur_len > data->len) {
+        av_log(ctx, AV_LOG_ERROR, "Malformed LATM packet\n");
+        return AVERROR(EIO);
+    }
+
+    if ((ret = av_new_packet(pkt, cur_len)) < 0)
+        return ret;
+    memcpy(pkt->data, data->buf + data->pos, cur_len);
+    data->pos += cur_len;
+    pkt->stream_index = st->index;
+    return data->pos < data->len;
+}
+
+static int parse_fmtp_config(AVStream *st, char *value)
+{
+    int len = ff_hex_to_data(NULL, value), i, ret = 0;
+    GetBitContext gb;
+    uint8_t *config;
+    int audio_mux_version, same_time_framing, num_sub_frames,
+        num_programs, num_layers;
+
+    /* Pad this buffer, too, to avoid out of bounds reads with get_bits below */
+    config = av_mallocz(len + FF_INPUT_BUFFER_PADDING_SIZE);
+    if (!config)
+        return AVERROR(ENOMEM);
+    ff_hex_to_data(config, value);
+    init_get_bits(&gb, config, len*8);
+    audio_mux_version = get_bits(&gb, 1);
+    same_time_framing = get_bits(&gb, 1);
+    num_sub_frames    = get_bits(&gb, 6);
+    num_programs      = get_bits(&gb, 4);
+    num_layers        = get_bits(&gb, 3);
+    if (audio_mux_version != 0 || same_time_framing != 1 || num_programs != 0 ||
+        num_layers != 0) {
+        av_log(NULL, AV_LOG_WARNING, "Unsupported LATM config (%d,%d,%d,%d)\n",
+                                     audio_mux_version, same_time_framing,
+                                     num_programs, num_layers);
+        ret = AVERROR_PATCHWELCOME;
+        goto end;
+    }
+    av_freep(&st->codec->extradata);
+    st->codec->extradata_size = (get_bits_left(&gb) + 7)/8;
+    st->codec->extradata = av_mallocz(st->codec->extradata_size +
+                                      FF_INPUT_BUFFER_PADDING_SIZE);
+    if (!st->codec->extradata) {
+        ret = AVERROR(ENOMEM);
+        goto end;
+    }
+    for (i = 0; i < st->codec->extradata_size; i++)
+        st->codec->extradata[i] = get_bits(&gb, 8);
+
+end:
+    av_free(config);
+    return ret;
+}
+
+static int parse_fmtp(AVStream *stream, PayloadContext *data,
+                      char *attr, char *value)
+{
+    int res;
+
+    if (!strcmp(attr, "config")) {
+        res = parse_fmtp_config(stream, value);
+        if (res < 0)
+            return res;
+    } else if (!strcmp(attr, "cpresent")) {
+        int cpresent = atoi(value);
+        if (cpresent != 0)
+            av_log_missing_feature(NULL, "RTP MP4A-LATM with in-band "
+                                         "configuration", 1);
+    }
+
+    return 0;
+}
+
+static int latm_parse_sdp_line(AVFormatContext *s, int st_index,
+                               PayloadContext *data, const char *line)
+{
+    const char *p;
+
+    if (av_strstart(line, "fmtp:", &p))
+        return ff_parse_fmtp(s->streams[st_index], data, p, parse_fmtp);
+
+    return 0;
+}
+
+RTPDynamicProtocolHandler ff_mp4a_latm_dynamic_handler = {
+    .enc_name           = "MP4A-LATM",
+    .codec_type         = AVMEDIA_TYPE_AUDIO,
+    .codec_id           = CODEC_ID_AAC,
+    .parse_sdp_a_line   = latm_parse_sdp_line,
+    .open               = latm_new_context,
+    .close              = latm_free_context,
+    .parse_packet       = latm_parse_packet
+};
diff --git a/libavformat/rtpdec_mpeg4.c b/libavformat/rtpdec_mpeg4.c
new file mode 100644
index 0000000..9f2fcb3
--- /dev/null
+++ b/libavformat/rtpdec_mpeg4.c
@@ -0,0 +1,251 @@
+/**
+ * Common code for the RTP depacketization of MPEG-4 formats.
+ * Copyright (c) 2010 Fabrice Bellard
+ *                    Romain Degez
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * @brief MPEG4 / RTP Code
+ * @author Fabrice Bellard
+ * @author Romain Degez
+ */
+
+#include "rtpdec_formats.h"
+#include "internal.h"
+#include "libavutil/avstring.h"
+#include "libavcodec/get_bits.h"
+#include <strings.h>
+
+/** Structure listing useful vars to parse RTP packet payload*/
+struct PayloadContext
+{
+    int sizelength;
+    int indexlength;
+    int indexdeltalength;
+    int profile_level_id;
+    int streamtype;
+    int objecttype;
+    char *mode;
+
+    /** mpeg 4 AU headers */
+    struct AUHeaders {
+        int size;
+        int index;
+        int cts_flag;
+        int cts;
+        int dts_flag;
+        int dts;
+        int rap_flag;
+        int streamstate;
+    } *au_headers;
+    int au_headers_allocated;
+    int nb_au_headers;
+    int au_headers_length_bytes;
+    int cur_au_index;
+};
+
+typedef struct {
+    const char *str;
+    uint16_t    type;
+    uint32_t    offset;
+} AttrNameMap;
+
+/* All known fmtp parameters and the corresponding RTPAttrTypeEnum */
+#define ATTR_NAME_TYPE_INT 0
+#define ATTR_NAME_TYPE_STR 1
+static const AttrNameMap attr_names[]=
+{
+    { "SizeLength",       ATTR_NAME_TYPE_INT,
+      offsetof(PayloadContext, sizelength) },
+    { "IndexLength",      ATTR_NAME_TYPE_INT,
+      offsetof(PayloadContext, indexlength) },
+    { "IndexDeltaLength", ATTR_NAME_TYPE_INT,
+      offsetof(PayloadContext, indexdeltalength) },
+    { "profile-level-id", ATTR_NAME_TYPE_INT,
+      offsetof(PayloadContext, profile_level_id) },
+    { "StreamType",       ATTR_NAME_TYPE_INT,
+      offsetof(PayloadContext, streamtype) },
+    { "mode",             ATTR_NAME_TYPE_STR,
+      offsetof(PayloadContext, mode) },
+    { NULL, -1, -1 },
+};
+
+static PayloadContext *new_context(void)
+{
+    return av_mallocz(sizeof(PayloadContext));
+}
+
+static void free_context(PayloadContext * data)
+{
+    int i;
+    for (i = 0; i < data->nb_au_headers; i++) {
+         /* according to rtp_parse_mp4_au, we treat multiple
+          * au headers as one, so nb_au_headers is always 1.
+          * loop anyway in case this changes.
+          * (note: changes done carelessly might lead to a double free)
+          */
+       av_free(&data->au_headers[i]);
+    }
+    av_free(data->mode);
+    av_free(data);
+}
+
+static int parse_fmtp_config(AVCodecContext * codec, char *value)
+{
+    /* decode the hexa encoded parameter */
+    int len = ff_hex_to_data(NULL, value);
+    av_free(codec->extradata);
+    codec->extradata = av_mallocz(len + FF_INPUT_BUFFER_PADDING_SIZE);
+    if (!codec->extradata)
+        return AVERROR(ENOMEM);
+    codec->extradata_size = len;
+    ff_hex_to_data(codec->extradata, value);
+    return 0;
+}
+
+static int rtp_parse_mp4_au(PayloadContext *data, const uint8_t *buf)
+{
+    int au_headers_length, au_header_size, i;
+    GetBitContext getbitcontext;
+
+    /* decode the first 2 bytes where the AUHeader sections are stored
+       length in bits */
+    au_headers_length = AV_RB16(buf);
+
+    if (au_headers_length > RTP_MAX_PACKET_LENGTH)
+      return -1;
+
+    data->au_headers_length_bytes = (au_headers_length + 7) / 8;
+
+    /* skip AU headers length section (2 bytes) */
+    buf += 2;
+
+    init_get_bits(&getbitcontext, buf, data->au_headers_length_bytes * 8);
+
+    /* XXX: Wrong if optionnal additional sections are present (cts, dts etc...) */
+    au_header_size = data->sizelength + data->indexlength;
+    if (au_header_size <= 0 || (au_headers_length % au_header_size != 0))
+        return -1;
+
+    data->nb_au_headers = au_headers_length / au_header_size;
+    if (!data->au_headers || data->au_headers_allocated < data->nb_au_headers) {
+        av_free(data->au_headers);
+        data->au_headers = av_malloc(sizeof(struct AUHeaders) * data->nb_au_headers);
+        data->au_headers_allocated = data->nb_au_headers;
+    }
+
+    /* XXX: We handle multiple AU Section as only one (need to fix this for interleaving)
+       In my test, the FAAD decoder does not behave correctly when sending each AU one by one
+       but does when sending the whole as one big packet...  */
+    data->au_headers[0].size = 0;
+    data->au_headers[0].index = 0;
+    for (i = 0; i < data->nb_au_headers; ++i) {
+        data->au_headers[0].size += get_bits_long(&getbitcontext, data->sizelength);
+        data->au_headers[0].index = get_bits_long(&getbitcontext, data->indexlength);
+    }
+
+    data->nb_au_headers = 1;
+
+    return 0;
+}
+
+
+/* Follows RFC 3640 */
+static int aac_parse_packet(AVFormatContext *ctx,
+                            PayloadContext *data,
+                            AVStream *st,
+                            AVPacket *pkt,
+                            uint32_t *timestamp,
+                            const uint8_t *buf, int len, int flags)
+{
+    if (rtp_parse_mp4_au(data, buf))
+        return -1;
+
+    buf += data->au_headers_length_bytes + 2;
+    len -= data->au_headers_length_bytes + 2;
+
+    /* XXX: Fixme we only handle the case where rtp_parse_mp4_au define
+                    one au_header */
+    av_new_packet(pkt, data->au_headers[0].size);
+    memcpy(pkt->data, buf, data->au_headers[0].size);
+
+    pkt->stream_index = st->index;
+    return 0;
+}
+
+static int parse_fmtp(AVStream *stream, PayloadContext *data,
+                      char *attr, char *value)
+{
+    AVCodecContext *codec = stream->codec;
+    int res, i;
+
+    if (!strcmp(attr, "config")) {
+        res = parse_fmtp_config(codec, value);
+
+        if (res < 0)
+            return res;
+    }
+
+    if (codec->codec_id == CODEC_ID_AAC) {
+        /* Looking for a known attribute */
+        for (i = 0; attr_names[i].str; ++i) {
+            if (!strcasecmp(attr, attr_names[i].str)) {
+                if (attr_names[i].type == ATTR_NAME_TYPE_INT) {
+                    *(int *)((char *)data+
+                        attr_names[i].offset) = atoi(value);
+                } else if (attr_names[i].type == ATTR_NAME_TYPE_STR)
+                    *(char **)((char *)data+
+                        attr_names[i].offset) = av_strdup(value);
+            }
+        }
+    }
+    return 0;
+}
+
+static int parse_sdp_line(AVFormatContext *s, int st_index,
+                          PayloadContext *data, const char *line)
+{
+    const char *p;
+
+    if (av_strstart(line, "fmtp:", &p))
+        return ff_parse_fmtp(s->streams[st_index], data, p, parse_fmtp);
+
+    return 0;
+}
+
+RTPDynamicProtocolHandler ff_mp4v_es_dynamic_handler = {
+    .enc_name           = "MP4V-ES",
+    .codec_type         = AVMEDIA_TYPE_VIDEO,
+    .codec_id           = CODEC_ID_MPEG4,
+    .parse_sdp_a_line   = parse_sdp_line,
+    .open               = NULL,
+    .close              = NULL,
+    .parse_packet       = NULL
+};
+
+RTPDynamicProtocolHandler ff_mpeg4_generic_dynamic_handler = {
+    .enc_name           = "mpeg4-generic",
+    .codec_type         = AVMEDIA_TYPE_AUDIO,
+    .codec_id           = CODEC_ID_AAC,
+    .parse_sdp_a_line   = parse_sdp_line,
+    .open               = new_context,
+    .close              = free_context,
+    .parse_packet       = aac_parse_packet
+};
diff --git a/libavformat/rtpdec_qcelp.c b/libavformat/rtpdec_qcelp.c
new file mode 100644
index 0000000..cc16ec1
--- /dev/null
+++ b/libavformat/rtpdec_qcelp.c
@@ -0,0 +1,229 @@
+/**
+ * RTP Depacketization of QCELP/PureVoice, RFC 2658
+ * Copyright (c) 2010 Martin Storsjo
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "rtpdec_formats.h"
+
+static const uint8_t frame_sizes[] = {
+    1, 4, 8, 17, 35
+};
+
+typedef struct {
+    int pos;
+    int size;
+    /* The largest frame is 35 bytes, only 10 frames are allowed per
+     * packet, and we return the first one immediately, so allocate
+     * space for 9 frames */
+    uint8_t data[35*9];
+} InterleavePacket;
+
+struct PayloadContext {
+    int interleave_size;
+    int interleave_index;
+    InterleavePacket group[6];
+    int group_finished;
+
+    /* The maximum packet size, 10 frames of 35 bytes each, and one
+     * packet header byte. */
+    uint8_t  next_data[1 + 35*10];
+    int      next_size;
+    uint32_t next_timestamp;
+};
+
+static PayloadContext *qcelp_new_context(void)
+{
+    return av_mallocz(sizeof(PayloadContext));
+}
+
+static void qcelp_free_context(PayloadContext *data)
+{
+    av_free(data);
+}
+
+static int return_stored_frame(AVFormatContext *ctx, PayloadContext *data,
+                               AVStream *st, AVPacket *pkt, uint32_t *timestamp,
+                               const uint8_t *buf, int len);
+
+static int store_packet(AVFormatContext *ctx, PayloadContext *data,
+                        AVStream *st, AVPacket *pkt, uint32_t *timestamp,
+                        const uint8_t *buf, int len)
+{
+    int interleave_size, interleave_index;
+    int frame_size, ret;
+    InterleavePacket* ip;
+
+    if (len < 2)
+        return AVERROR_INVALIDDATA;
+
+    interleave_size  = buf[0] >> 3 & 7;
+    interleave_index = buf[0]      & 7;
+
+    if (interleave_size > 5) {
+        av_log(ctx, AV_LOG_ERROR, "Invalid interleave size %d\n",
+                                   interleave_size);
+        return AVERROR_INVALIDDATA;
+    }
+    if (interleave_index > interleave_size) {
+        av_log(ctx, AV_LOG_ERROR, "Invalid interleave index %d/%d\n",
+                                   interleave_index, interleave_size);
+        return AVERROR_INVALIDDATA;
+    }
+    if (interleave_size != data->interleave_size) {
+        int i;
+        /* First packet, or changed interleave size */
+        data->interleave_size = interleave_size;
+        data->interleave_index = 0;
+        for (i = 0; i < 6; i++)
+            data->group[i].size = 0;
+    }
+
+    if (interleave_index < data->interleave_index) {
+        /* Wrapped around - missed the last packet of the previous group. */
+        if (data->group_finished) {
+            /* No more data in the packets in this interleaving group, just
+             * start processing the next one */
+            data->interleave_index = 0;
+        } else {
+            /* Stash away the current packet, emit everything we have of the
+             * previous group. */
+            for (; data->interleave_index <= interleave_size;
+                 data->interleave_index++)
+                data->group[data->interleave_index].size = 0;
+
+            if (len > sizeof(data->next_data))
+                return AVERROR_INVALIDDATA;
+            memcpy(data->next_data, buf, len);
+            data->next_size = len;
+            data->next_timestamp = *timestamp;
+            *timestamp = RTP_NOTS_VALUE;
+
+            data->interleave_index = 0;
+            return return_stored_frame(ctx, data, st, pkt, timestamp, buf, len);
+        }
+    }
+    if (interleave_index > data->interleave_index) {
+        /* We missed a packet */
+        for (; data->interleave_index < interleave_index;
+             data->interleave_index++)
+            data->group[data->interleave_index].size = 0;
+    }
+    data->interleave_index = interleave_index;
+
+    if (buf[1] >= FF_ARRAY_ELEMS(frame_sizes))
+        return AVERROR_INVALIDDATA;
+    frame_size = frame_sizes[buf[1]];
+    if (1 + frame_size > len)
+        return AVERROR_INVALIDDATA;
+
+    if (len - 1 - frame_size > sizeof(data->group[0].data))
+        return AVERROR_INVALIDDATA;
+
+    if ((ret = av_new_packet(pkt, frame_size)) < 0)
+        return ret;
+    memcpy(pkt->data, &buf[1], frame_size);
+    pkt->stream_index = st->index;
+
+    ip = &data->group[data->interleave_index];
+    ip->size = len - 1 - frame_size;
+    ip->pos = 0;
+    memcpy(ip->data, &buf[1 + frame_size], ip->size);
+    /* Each packet must contain the same number of frames according to the
+     * RFC. If there's no data left in this packet, there shouldn't be any
+     * in any of the other frames in the interleaving group either. */
+    data->group_finished = ip->size == 0;
+
+    if (interleave_index == interleave_size) {
+        data->interleave_index = 0;
+        return !data->group_finished;
+    } else {
+        data->interleave_index++;
+        return 0;
+    }
+}
+
+static int return_stored_frame(AVFormatContext *ctx, PayloadContext *data,
+                               AVStream *st, AVPacket *pkt, uint32_t *timestamp,
+                               const uint8_t *buf, int len)
+{
+    InterleavePacket* ip = &data->group[data->interleave_index];
+    int frame_size, ret;
+
+    if (data->group_finished && data->interleave_index == 0) {
+        *timestamp = data->next_timestamp;
+        ret = store_packet(ctx, data, st, pkt, timestamp, data->next_data,
+                           data->next_size);
+        data->next_size = 0;
+        return ret;
+    }
+
+    if (ip->size == 0) {
+        /* No stored data for this interleave block, output an empty packet */
+        if ((ret = av_new_packet(pkt, 1)) < 0)
+            return ret;
+        pkt->data[0] = 0; // Blank - could also be 14, Erasure
+    } else {
+        if (ip->pos >= ip->size)
+            return AVERROR_INVALIDDATA;
+        if (ip->data[ip->pos] >= FF_ARRAY_ELEMS(frame_sizes))
+            return AVERROR_INVALIDDATA;
+        frame_size = frame_sizes[ip->data[ip->pos]];
+        if (ip->pos + frame_size > ip->size)
+            return AVERROR_INVALIDDATA;
+
+        if ((ret = av_new_packet(pkt, frame_size)) < 0)
+            return ret;
+        memcpy(pkt->data, &ip->data[ip->pos], frame_size);
+
+        ip->pos += frame_size;
+        data->group_finished = ip->pos >= ip->size;
+    }
+    pkt->stream_index = st->index;
+
+    if (data->interleave_index == data->interleave_size) {
+        data->interleave_index = 0;
+        if (!data->group_finished)
+            return 1;
+        else
+            return data->next_size > 0;
+    } else {
+        data->interleave_index++;
+        return 1;
+    }
+}
+
+static int qcelp_parse_packet(AVFormatContext *ctx, PayloadContext *data,
+                              AVStream *st, AVPacket *pkt, uint32_t *timestamp,
+                              const uint8_t *buf, int len, int flags)
+{
+    if (buf)
+        return store_packet(ctx, data, st, pkt, timestamp, buf, len);
+    else
+        return return_stored_frame(ctx, data, st, pkt, timestamp, buf, len);
+}
+
+RTPDynamicProtocolHandler ff_qcelp_dynamic_handler = {
+    .enc_name           = "x-Purevoice",
+    .codec_type         = AVMEDIA_TYPE_AUDIO,
+    .codec_id           = CODEC_ID_QCELP,
+    .static_payload_id  = 12,
+    .open               = qcelp_new_context,
+    .close              = qcelp_free_context,
+    .parse_packet       = qcelp_parse_packet
+};
diff --git a/libavformat/rtpdec_qdm2.c b/libavformat/rtpdec_qdm2.c
new file mode 100644
index 0000000..0d744be
--- /dev/null
+++ b/libavformat/rtpdec_qdm2.c
@@ -0,0 +1,315 @@
+/*
+ * QDesign Music 2 (QDM2) payload for RTP
+ * Copyright (c) 2010 Ronald S. Bultje
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * @brief RTP support for the QDM2 payload (todo: wiki)
+ * @author Ronald S. Bultje <rbultje at ronald.bitfreak.net>
+ */
+
+#include <string.h>
+#include "libavutil/intreadwrite.h"
+#include "libavcodec/avcodec.h"
+#include "rtp.h"
+#include "rtpdec.h"
+#include "rtpdec_formats.h"
+
+struct PayloadContext {
+    /** values read from the config header, used as packet headers */
+    //@{
+    int block_type;            ///< superblock type, value 2 .. 8
+    int block_size;            ///< from extradata, used as pkt length
+    int subpkts_per_block;     ///< max. nr. of subpackets to add per output buffer
+    //@}
+
+    /** Temporary storage for superblock restoring, per packet ID (0x80 total) */
+    //@{
+    uint16_t len[0x80];        ///< how much the temporary buffer is filled
+    uint8_t  buf[0x80][0x800]; ///< the temporary storage buffer
+
+    unsigned int cache;        ///< number of data packets that we have cached right now
+    unsigned int n_pkts;       ///< number of RTP packets received since last packet output / config
+    uint32_t timestamp;        ///< timestamp of next-to-be-returned packet
+    //@}
+};
+
+/**
+ * Parses configuration (basically the codec-specific extradata) from
+ * a RTP config subpacket (starts with 0xff).
+ *
+ * Layout of the config subpacket (in bytes):
+ * 1: 0xFF          <- config ID
+ * then an array {
+ *     1: size      <- of the current item
+ *     1: item type <- 0 .. 4
+ *     size-2: data <- data depends on the item type
+ * }
+ *
+ * Item 0 implies the end of the config subpacket, and has no data.
+ * Item 1 implies a stream configuration without extradata.
+ * Item 2 max. nr. of subpackets per superblock
+ * Item 3 superblock type for the stream
+ * Item 4 implies a stream configuration with extradata (size >= 0x1c).
+ *
+ * @return <0 on error, otherwise the number of bytes parsed from the
+ *         input buffer.
+ */
+static int qdm2_parse_config(PayloadContext *qdm, AVStream *st,
+                             const uint8_t *buf, const uint8_t *end)
+{
+    const uint8_t *p = buf;
+
+    while (end - p >= 2) {
+        unsigned int item_len = p[0], config_item = p[1];
+
+        if (item_len < 2 || end - p < item_len || config_item > 4)
+            return AVERROR_INVALIDDATA;
+
+        switch (config_item) {
+            case 0: /* end of config block */
+                return p - buf + item_len;
+            case 1: /* stream without extradata */
+                /* FIXME: set default qdm->block_size */
+                break;
+            case 2: /**< subpackets per block */
+                if (item_len < 3)
+                    return AVERROR_INVALIDDATA;
+                qdm->subpkts_per_block = p[2];
+                break;
+            case 3: /* superblock type */
+                if (item_len < 4)
+                    return AVERROR_INVALIDDATA;
+                qdm->block_type = AV_RB16(p + 2);
+                break;
+            case 4: /* stream with extradata */
+                if (item_len < 30)
+                    return AVERROR_INVALIDDATA;
+                av_freep(&st->codec->extradata);
+                st->codec->extradata_size = 26 + item_len;
+                if (!(st->codec->extradata = av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE))) {
+                    st->codec->extradata_size = 0;
+                    return AVERROR(ENOMEM);
+                }
+                AV_WB32(st->codec->extradata, 12);
+                memcpy(st->codec->extradata + 4, "frma", 4);
+                memcpy(st->codec->extradata + 8, "QDM2", 4);
+                AV_WB32(st->codec->extradata + 12, 6 + item_len);
+                memcpy(st->codec->extradata + 16, "QDCA", 4);
+                memcpy(st->codec->extradata + 20, p + 2, item_len - 2);
+                AV_WB32(st->codec->extradata + 18 + item_len, 8);
+                AV_WB32(st->codec->extradata + 22 + item_len, 0);
+
+                qdm->block_size = AV_RB32(p + 26);
+                break;
+        }
+
+        p += item_len;
+    }
+
+    return AVERROR(EAGAIN); /* not enough data */
+}
+
+/**
+ * Parses a single subpacket. We store this subpacket in an intermediate
+ * buffer (position depends on the ID (byte[0]). When called, at least
+ * 4 bytes are available for reading (see qdm2_parse_packet()).
+ *
+ * Layout of a single subpacket (RTP packets commonly contain multiple
+ * such subpackets) - length in bytes:
+ * 1:    ordering ID        <- 0 .. 0x7F
+ * 1:    subpacket type     <- 0 .. 0x7F; value & 0x80 means subpacket length = 2 bytes, else 1 byte
+ * 1/2:  subpacket length   <- length of the data following the flags/length fields
+ * if (subpacket type & 0x7F) == 0x7F
+ *   1:  subpacket type, higher bits
+ * size: subpacket data
+ *
+ * The subpackets come in randomly, and should be encapsulated into 1
+ * or more superblocks (containing qdm->subpkts_per_block subpackets
+ * each) per RTP packet, in order of ascending "ordering ID", see
+ * qdm2_restore_block().
+ *
+ * @return <0 on error, otherwise the number of bytes parsed from the
+ *         input buffer.
+ */
+static int qdm2_parse_subpacket(PayloadContext *qdm, AVStream *st,
+                                const uint8_t *buf, const uint8_t *end)
+{
+    const uint8_t *p = buf;
+    unsigned int id, len, type, to_copy;
+
+    /* parse header so we know the size of the header/data */
+    id       = *p++;
+    type     = *p++;
+    if (type & 0x80) {
+        len   = AV_RB16(p);
+        p    += 2;
+        type &= 0x7F;
+    } else
+        len = *p++;
+
+    if (end - p < len + (type == 0x7F) || id >= 0x80)
+        return AVERROR_INVALIDDATA;
+    if (type == 0x7F)
+        type |= *p++ << 8;
+
+    /* copy data into a temporary buffer */
+    to_copy = FFMIN(len + (p - &buf[1]), 0x800 - qdm->len[id]);
+    memcpy(&qdm->buf[id][qdm->len[id]], buf + 1, to_copy);
+    qdm->len[id] += to_copy;
+
+    return p + len - buf;
+}
+
+/**
+ * Adds a superblock header around a set of subpackets.
+ *
+ * @return <0 on error, else 0.
+ */
+static int qdm2_restore_block(PayloadContext *qdm, AVStream *st, AVPacket *pkt)
+{
+    int to_copy, n, res, include_csum;
+    uint8_t *p, *csum_pos = NULL;
+
+    /* create packet to hold subpkts into a superblock */
+    assert(qdm->cache > 0);
+    for (n = 0; n < 0x80; n++)
+        if (qdm->len[n] > 0)
+            break;
+    assert(n < 0x80);
+
+    if ((res = av_new_packet(pkt, qdm->block_size)) < 0)
+        return res;
+    memset(pkt->data, 0, pkt->size);
+    pkt->stream_index  = st->index;
+    p                  = pkt->data;
+
+    /* superblock header */
+    if (qdm->len[n] > 0xff) {
+        *p++ = qdm->block_type | 0x80;
+        AV_WB16(p, qdm->len[n]);
+        p   += 2;
+    } else {
+        *p++ = qdm->block_type;
+        *p++ = qdm->len[n];
+    }
+    if ((include_csum = (qdm->block_type == 2 || qdm->block_type == 4))) {
+        csum_pos = p;
+        p       += 2;
+    }
+
+    /* subpacket data */
+    to_copy = FFMIN(qdm->len[n], pkt->size - (p - pkt->data));
+    memcpy(p, qdm->buf[n], to_copy);
+    qdm->len[n] = 0;
+
+    /* checksum header */
+    if (include_csum) {
+        unsigned int total = 0;
+        uint8_t *q;
+
+        for (q = pkt->data; q < &pkt->data[qdm->block_size]; q++)
+            total += *q;
+        AV_WB16(csum_pos, (uint16_t) total);
+    }
+
+    return 0;
+}
+
+/** return 0 on packet, no more left, 1 on packet, -1 on partial packet... */
+static int qdm2_parse_packet(AVFormatContext *s, PayloadContext *qdm,
+                             AVStream *st, AVPacket *pkt,
+                             uint32_t *timestamp,
+                             const uint8_t *buf, int len, int flags)
+{
+    int res = AVERROR_INVALIDDATA, n;
+    const uint8_t *end = buf + len, *p = buf;
+
+    if (len > 0) {
+        if (len < 2)
+            return AVERROR_INVALIDDATA;
+
+        /* configuration block */
+        if (*p == 0xff) {
+            if (qdm->n_pkts > 0) {
+                av_log(s, AV_LOG_WARNING,
+                       "Out of sequence config - dropping queue\n");
+                qdm->n_pkts = 0;
+                memset(qdm->len, 0, sizeof(qdm->len));
+            }
+
+            if ((res = qdm2_parse_config(qdm, st, ++p, end)) < 0)
+                return res;
+            p += res;
+
+            /* We set codec_id to CODEC_ID_NONE initially to
+             * delay decoder initialization since extradata is
+             * carried within the RTP stream, not SDP. Here,
+             * by setting codec_id to CODEC_ID_QDM2, we are signalling
+             * to the decoder that it is OK to initialize. */
+            st->codec->codec_id = CODEC_ID_QDM2;
+        }
+
+        /* subpackets */
+        while (end - p >= 4) {
+            if ((res = qdm2_parse_subpacket(qdm, st, p, end)) < 0)
+                return res;
+            p += res;
+        }
+
+        qdm->timestamp = *timestamp;
+        if (++qdm->n_pkts < qdm->subpkts_per_block)
+            return AVERROR(EAGAIN);
+        qdm->cache = 0;
+        for (n = 0; n < 0x80; n++)
+            if (qdm->len[n] > 0)
+                qdm->cache++;
+    }
+
+    /* output the subpackets into freshly created superblock structures */
+    if (!qdm->cache || (res = qdm2_restore_block(qdm, st, pkt)) < 0)
+        return res;
+    if (--qdm->cache == 0)
+        qdm->n_pkts = 0;
+
+    *timestamp = qdm->timestamp;
+    qdm->timestamp = RTP_NOTS_VALUE;
+
+    return (qdm->cache > 0) ? 1 : 0;
+}
+
+static PayloadContext *qdm2_extradata_new(void)
+{
+    return av_mallocz(sizeof(PayloadContext));
+}
+
+static void qdm2_extradata_free(PayloadContext *qdm)
+{
+    av_free(qdm);
+}
+
+RTPDynamicProtocolHandler ff_qdm2_dynamic_handler = {
+    .enc_name         = "X-QDM",
+    .codec_type       = AVMEDIA_TYPE_AUDIO,
+    .codec_id         = CODEC_ID_NONE,
+    .open             = qdm2_extradata_new,
+    .close            = qdm2_extradata_free,
+    .parse_packet     = qdm2_parse_packet,
+};
diff --git a/libavformat/rtpdec_qt.c b/libavformat/rtpdec_qt.c
new file mode 100644
index 0000000..a295ba7
--- /dev/null
+++ b/libavformat/rtpdec_qt.c
@@ -0,0 +1,255 @@
+/*
+ * RTP/Quicktime support.
+ * Copyright (c) 2009 Ronald S. Bultje
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * @brief Quicktime-style RTP support
+ * @author Ronald S. Bultje <rbultje at ronald.bitfreak.net>
+ */
+
+#include "avformat.h"
+#include "avio_internal.h"
+#include "rtp.h"
+#include "rtpdec.h"
+#include "isom.h"
+#include "libavcodec/get_bits.h"
+
+struct PayloadContext {
+    AVPacket pkt;
+    int bytes_per_frame, remaining;
+    uint32_t timestamp;
+};
+
+static int qt_rtp_parse_packet(AVFormatContext *s, PayloadContext *qt,
+                               AVStream *st, AVPacket *pkt,
+                               uint32_t *timestamp, const uint8_t *buf,
+                               int len, int flags)
+{
+    AVIOContext pb;
+    GetBitContext gb;
+    int packing_scheme, has_payload_desc, has_packet_info, alen,
+        has_marker_bit = flags & RTP_FLAG_MARKER;
+
+    if (qt->remaining) {
+        int num = qt->pkt.size / qt->bytes_per_frame;
+
+        if (av_new_packet(pkt, qt->bytes_per_frame))
+            return AVERROR(ENOMEM);
+        pkt->stream_index = st->index;
+        pkt->flags        = qt->pkt.flags;
+        memcpy(pkt->data,
+               &qt->pkt.data[(num - qt->remaining) * qt->bytes_per_frame],
+               qt->bytes_per_frame);
+        if (--qt->remaining == 0) {
+            av_freep(&qt->pkt.data);
+            qt->pkt.size = 0;
+        }
+        return qt->remaining > 0;
+    }
+
+    /**
+     * The RTP payload is described in:
+     * http://developer.apple.com/quicktime/icefloe/dispatch026.html
+     */
+    init_get_bits(&gb, buf, len << 3);
+    ffio_init_context(&pb, buf, len, 0, NULL, NULL, NULL, NULL);
+
+    if (len < 4)
+        return AVERROR_INVALIDDATA;
+
+    skip_bits(&gb, 4); // version
+    if ((packing_scheme = get_bits(&gb, 2)) == 0)
+        return AVERROR_INVALIDDATA;
+    if (get_bits1(&gb))
+        flags          |= RTP_FLAG_KEY;
+    has_payload_desc    = get_bits1(&gb);
+    has_packet_info     = get_bits1(&gb);
+    skip_bits(&gb, 23); // reserved:7, cache payload info:1, payload ID:15
+
+    if (has_payload_desc) {
+        int data_len, pos, is_start, is_finish;
+        uint32_t tag;
+
+        pos = get_bits_count(&gb) >> 3;
+        if (pos + 12 > len)
+            return AVERROR_INVALIDDATA;
+
+        skip_bits(&gb, 2); // has non-I frames:1, is sparse:1
+        is_start  = get_bits1(&gb);
+        is_finish = get_bits1(&gb);
+        if (!is_start || !is_finish) {
+            av_log_missing_feature(s, "RTP-X-QT with payload description "
+                                      "split over several packets", 1);
+            return AVERROR(ENOSYS);
+        }
+        skip_bits(&gb, 12); // reserved
+        data_len = get_bits(&gb, 16);
+
+        avio_seek(&pb, pos + 4, SEEK_SET);
+        tag = avio_rl32(&pb);
+        if ((st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
+                 tag != MKTAG('v','i','d','e')) ||
+            (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
+                 tag != MKTAG('s','o','u','n')))
+            return AVERROR_INVALIDDATA;
+        av_set_pts_info(st, 32, 1, avio_rb32(&pb));
+
+        if (pos + data_len > len)
+            return AVERROR_INVALIDDATA;
+        /* TLVs */
+        while (avio_tell(&pb) + 4 < pos + data_len) {
+            int tlv_len = avio_rb16(&pb);
+            tag = avio_rl16(&pb);
+            if (avio_tell(&pb) + tlv_len > pos + data_len)
+                return AVERROR_INVALIDDATA;
+
+#define MKTAG16(a,b) MKTAG(a,b,0,0)
+            switch (tag) {
+            case MKTAG16('s','d'): {
+                MOVStreamContext *msc;
+                void *priv_data = st->priv_data;
+                int nb_streams = s->nb_streams;
+                MOVContext *mc = av_mallocz(sizeof(*mc));
+                if (!mc)
+                    return AVERROR(ENOMEM);
+                mc->fc = s;
+                st->priv_data = msc = av_mallocz(sizeof(MOVStreamContext));
+                if (!msc) {
+                    av_free(mc);
+                    st->priv_data = priv_data;
+                    return AVERROR(ENOMEM);
+                }
+                /* ff_mov_read_stsd_entries updates stream s->nb_streams-1,
+                 * so set it temporarily to indicate which stream to update. */
+                s->nb_streams = st->index + 1;
+                ff_mov_read_stsd_entries(mc, &pb, 1);
+                qt->bytes_per_frame = msc->bytes_per_frame;
+                av_free(msc);
+                av_free(mc);
+                st->priv_data = priv_data;
+                s->nb_streams = nb_streams;
+                break;
+            }
+            default:
+                avio_skip(&pb, tlv_len);
+                break;
+            }
+        }
+
+        /* 32-bit alignment */
+        avio_skip(&pb, ((avio_tell(&pb) + 3) & ~3) - avio_tell(&pb));
+    } else
+        avio_seek(&pb, 4, SEEK_SET);
+
+    if (has_packet_info) {
+        av_log_missing_feature(s, "RTP-X-QT with packet specific info", 1);
+        return AVERROR(ENOSYS);
+    }
+
+    alen = len - avio_tell(&pb);
+    if (alen <= 0)
+        return AVERROR_INVALIDDATA;
+
+    switch (packing_scheme) {
+    case 3: /* one data packet spread over 1 or multiple RTP packets */
+        if (qt->pkt.size > 0 && qt->timestamp == *timestamp) {
+            qt->pkt.data = av_realloc(qt->pkt.data, qt->pkt.size + alen +
+                                      FF_INPUT_BUFFER_PADDING_SIZE);
+        } else {
+            av_freep(&qt->pkt.data);
+            av_init_packet(&qt->pkt);
+            qt->pkt.data = av_malloc(alen + FF_INPUT_BUFFER_PADDING_SIZE);
+            qt->pkt.size = 0;
+            qt->timestamp = *timestamp;
+        }
+        if (!qt->pkt.data)
+            return AVERROR(ENOMEM);
+        memcpy(qt->pkt.data + qt->pkt.size, buf + avio_tell(&pb), alen);
+        qt->pkt.size += alen;
+        if (has_marker_bit) {
+            *pkt = qt->pkt;
+            qt->pkt.size = 0;
+            qt->pkt.data = NULL;
+            pkt->flags        = flags & RTP_FLAG_KEY ? AV_PKT_FLAG_KEY : 0;
+            pkt->stream_index = st->index;
+            pkt->destruct     = av_destruct_packet;
+            memset(pkt->data + pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
+            return 0;
+        }
+        return AVERROR(EAGAIN);
+
+    case 1: /* constant packet size, multiple packets per RTP packet */
+        if (qt->bytes_per_frame == 0 ||
+            alen % qt->bytes_per_frame != 0)
+            return AVERROR_INVALIDDATA; /* wrongly padded */
+        qt->remaining = (alen / qt->bytes_per_frame) - 1;
+        if (av_new_packet(pkt, qt->bytes_per_frame))
+            return AVERROR(ENOMEM);
+        memcpy(pkt->data, buf + avio_tell(&pb), qt->bytes_per_frame);
+        pkt->flags = flags & RTP_FLAG_KEY ? AV_PKT_FLAG_KEY : 0;
+        pkt->stream_index = st->index;
+        if (qt->remaining > 0) {
+            av_freep(&qt->pkt.data);
+            qt->pkt.data = av_malloc(qt->remaining * qt->bytes_per_frame);
+            if (!qt->pkt.data) {
+                av_free_packet(pkt);
+                return AVERROR(ENOMEM);
+            }
+            qt->pkt.size = qt->remaining * qt->bytes_per_frame;
+            memcpy(qt->pkt.data,
+                   buf + avio_tell(&pb) + qt->bytes_per_frame,
+                   qt->remaining * qt->bytes_per_frame);
+            qt->pkt.flags = pkt->flags;
+            return 1;
+        }
+        return 0;
+
+    default:  /* unimplemented */
+        av_log_missing_feature(NULL, "RTP-X-QT with packing scheme 2", 1);
+        return AVERROR(ENOSYS);
+    }
+}
+
+static PayloadContext *qt_rtp_new(void)
+{
+    return av_mallocz(sizeof(PayloadContext));
+}
+
+static void qt_rtp_free(PayloadContext *qt)
+{
+    av_freep(&qt->pkt.data);
+    av_free(qt);
+}
+
+#define RTP_QT_HANDLER(m, n, s, t) \
+RTPDynamicProtocolHandler ff_ ## m ## _rtp_ ## n ## _handler = { \
+    .enc_name         = s, \
+    .codec_type       = t, \
+    .codec_id         = CODEC_ID_NONE, \
+    .open             = qt_rtp_new,    \
+    .close            = qt_rtp_free,   \
+    .parse_packet     = qt_rtp_parse_packet, \
+}
+
+RTP_QT_HANDLER(qt,        vid, "X-QT",        AVMEDIA_TYPE_VIDEO);
+RTP_QT_HANDLER(qt,        aud, "X-QT",        AVMEDIA_TYPE_AUDIO);
+RTP_QT_HANDLER(quicktime, vid, "X-QUICKTIME", AVMEDIA_TYPE_VIDEO);
+RTP_QT_HANDLER(quicktime, aud, "X-QUICKTIME", AVMEDIA_TYPE_AUDIO);
diff --git a/libavformat/rtpdec_svq3.c b/libavformat/rtpdec_svq3.c
new file mode 100644
index 0000000..8c09262
--- /dev/null
+++ b/libavformat/rtpdec_svq3.c
@@ -0,0 +1,134 @@
+/*
+ * Sorenson-3 (SVQ3/SV3V) payload for RTP
+ * Copyright (c) 2010 Ronald S. Bultje
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * @brief RTP support for the SV3V (SVQ3) payload
+ * (http://wiki.multimedia.cx/index.php?title=Sorenson_Video_3#Packetization)
+ * @author Ronald S. Bultje <rbultje at ronald.bitfreak.net>
+ */
+
+#include <string.h>
+#include "libavutil/intreadwrite.h"
+#include "rtp.h"
+#include "rtpdec.h"
+#include "rtpdec_formats.h"
+
+struct PayloadContext {
+    AVIOContext *pktbuf;
+    int64_t        timestamp;
+};
+
+/** return 0 on packet, <0 on partial packet or error... */
+static int svq3_parse_packet (AVFormatContext *s, PayloadContext *sv,
+                              AVStream *st, AVPacket *pkt,
+                              uint32_t *timestamp,
+                              const uint8_t *buf, int len, int flags)
+{
+    int config_packet, start_packet, end_packet;
+
+    if (len < 2)
+        return AVERROR_INVALIDDATA;
+
+    config_packet = buf[0] & 0x40;
+    start_packet  = buf[0] & 0x20;
+    end_packet    = buf[0] & 0x10;
+    buf += 2;     // ignore buf[1]
+    len -= 2;
+
+    if (config_packet) {
+
+        av_freep(&st->codec->extradata);
+        st->codec->extradata_size = 0;
+
+        if (len < 2 || !(st->codec->extradata =
+                         av_malloc(len + 8 + FF_INPUT_BUFFER_PADDING_SIZE)))
+            return AVERROR_INVALIDDATA;
+
+        st->codec->extradata_size = len + 8;
+        memcpy(st->codec->extradata, "SEQH", 4);
+        AV_WB32(st->codec->extradata + 4, len);
+        memcpy(st->codec->extradata + 8, buf, len);
+
+        /* We set codec_id to CODEC_ID_NONE initially to
+         * delay decoder initialization since extradata is
+         * carried within the RTP stream, not SDP. Here,
+         * by setting codec_id to CODEC_ID_SVQ3, we are signalling
+         * to the decoder that it is OK to initialize. */
+        st->codec->codec_id = CODEC_ID_SVQ3;
+
+        return AVERROR(EAGAIN);
+    }
+
+    if (start_packet) {
+        int res;
+
+        if (sv->pktbuf) {
+            uint8_t *tmp;
+            avio_close_dyn_buf(sv->pktbuf, &tmp);
+            av_free(tmp);
+        }
+        if ((res = avio_open_dyn_buf(&sv->pktbuf)) < 0)
+            return res;
+        sv->timestamp   = *timestamp;
+    }
+
+    if (!sv->pktbuf)
+        return AVERROR_INVALIDDATA;
+
+    avio_write(sv->pktbuf, buf, len);
+
+    if (end_packet) {
+        av_init_packet(pkt);
+        pkt->stream_index = st->index;
+        *timestamp        = sv->timestamp;
+        pkt->size         = avio_close_dyn_buf(sv->pktbuf, &pkt->data);
+        pkt->destruct     = av_destruct_packet;
+        sv->pktbuf        = NULL;
+        return 0;
+    }
+
+    return AVERROR(EAGAIN);
+}
+
+static PayloadContext *svq3_extradata_new(void)
+{
+    return av_mallocz(sizeof(PayloadContext));
+}
+
+static void svq3_extradata_free(PayloadContext *sv)
+{
+    if (sv->pktbuf) {
+        uint8_t *buf;
+        avio_close_dyn_buf(sv->pktbuf, &buf);
+        av_free(buf);
+    }
+    av_free(sv);
+}
+
+RTPDynamicProtocolHandler ff_svq3_dynamic_handler = {
+    .enc_name         = "X-SV3V-ES",
+    .codec_type       = AVMEDIA_TYPE_VIDEO,
+    .codec_id         = CODEC_ID_NONE,      // see if (config_packet) above
+    .open             = svq3_extradata_new,
+    .close            = svq3_extradata_free,
+    .parse_packet     = svq3_parse_packet,
+};
diff --git a/libavformat/rtpdec_vp8.c b/libavformat/rtpdec_vp8.c
new file mode 100644
index 0000000..9e50cc4
--- /dev/null
+++ b/libavformat/rtpdec_vp8.c
@@ -0,0 +1,154 @@
+/*
+ * RTP VP8 Depacketizer
+ * Copyright (c) 2010 Josh Allmann
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * @brief RTP support for the VP8 payload
+ * @author Josh Allmann <joshua.allmann at gmail.com>
+ * ( http://www.webmproject.org/code/specs/rtp/ )
+ */
+
+#include "libavcodec/bytestream.h"
+
+#include "rtpdec_formats.h"
+
+struct PayloadContext {
+    AVIOContext *data;
+    uint32_t       timestamp;
+    int is_keyframe;
+};
+
+static void prepare_packet(AVPacket *pkt, PayloadContext *vp8, int stream)
+{
+    av_init_packet(pkt);
+    pkt->stream_index = stream;
+    pkt->flags        = vp8->is_keyframe ? AV_PKT_FLAG_KEY : 0;
+    pkt->size         = avio_close_dyn_buf(vp8->data, &pkt->data);
+    pkt->destruct     = av_destruct_packet;
+    vp8->data         = NULL;
+}
+
+static int vp8_handle_packet(AVFormatContext *ctx,
+                             PayloadContext *vp8,
+                             AVStream *st,
+                             AVPacket *pkt,
+                             uint32_t *timestamp,
+                             const uint8_t *buf,
+                             int len, int flags)
+{
+    int start_packet, end_packet, has_au, ret = AVERROR(EAGAIN);
+
+    if (!buf) {
+        // only called when vp8_handle_packet returns 1
+        if (!vp8->data) {
+            av_log(ctx, AV_LOG_ERROR, "Invalid VP8 data passed\n");
+            return AVERROR_INVALIDDATA;
+        }
+        prepare_packet(pkt, vp8, st->index);
+        *timestamp = vp8->timestamp;
+        return 0;
+    }
+
+    start_packet = *buf & 1;
+    end_packet   = flags & RTP_FLAG_MARKER;
+    has_au       = *buf & 2;
+    buf++;
+    len--;
+
+    if (start_packet) {
+        int res;
+        uint32_t ts = *timestamp;
+        if (vp8->data) {
+            // missing end marker; return old frame anyway. untested
+            prepare_packet(pkt, vp8, st->index);
+            *timestamp = vp8->timestamp; // reset timestamp from old frame
+
+            // if current frame fits into one rtp packet, need to hold
+            // that for the next av_get_packet call
+            ret = end_packet ? 1 : 0;
+        }
+        if ((res = avio_open_dyn_buf(&vp8->data)) < 0)
+            return res;
+        vp8->is_keyframe = *buf & 1;
+        vp8->timestamp   = ts;
+     }
+
+    if (!vp8->data || vp8->timestamp != *timestamp && ret == AVERROR(EAGAIN)) {
+        av_log(ctx, AV_LOG_WARNING,
+               "Received no start marker; dropping frame\n");
+        return AVERROR(EAGAIN);
+    }
+
+    // cycle through VP8AU headers if needed
+    // not tested with actual VP8AUs
+    while (len) {
+        int au_len = len;
+        if (has_au && len > 2) {
+            au_len = AV_RB16(buf);
+            buf += 2;
+            len -= 2;
+            if (buf + au_len > buf + len) {
+                av_log(ctx, AV_LOG_ERROR, "Invalid VP8AU length\n");
+                return AVERROR_INVALIDDATA;
+            }
+        }
+
+        avio_write(vp8->data, buf, au_len);
+        buf += au_len;
+        len -= au_len;
+    }
+
+    if (ret != AVERROR(EAGAIN)) // did we miss a end marker?
+        return ret;
+
+    if (end_packet) {
+        prepare_packet(pkt, vp8, st->index);
+        return 0;
+    }
+
+    return AVERROR(EAGAIN);
+}
+
+static PayloadContext *vp8_new_context(void)
+{
+    av_log(NULL, AV_LOG_ERROR, "RTP VP8 payload implementation is incompatible "
+                               "with the latest spec drafts.\n");
+    return av_mallocz(sizeof(PayloadContext));
+}
+
+static void vp8_free_context(PayloadContext *vp8)
+{
+    if (vp8->data) {
+        uint8_t *tmp;
+        avio_close_dyn_buf(vp8->data, &tmp);
+        av_free(tmp);
+    }
+    av_free(vp8);
+}
+
+RTPDynamicProtocolHandler ff_vp8_dynamic_handler = {
+    .enc_name       = "VP8",
+    .codec_type     = AVMEDIA_TYPE_VIDEO,
+    .codec_id       = CODEC_ID_VP8,
+    .open           = vp8_new_context,
+    .close          = vp8_free_context,
+    .parse_packet   = vp8_handle_packet,
+};
diff --git a/libavformat/rtpdec_xiph.c b/libavformat/rtpdec_xiph.c
index 9a1f33d..4d8e834 100644
--- a/libavformat/rtpdec_xiph.c
+++ b/libavformat/rtpdec_xiph.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2009 Colin McQuillian
  * Copyright (c) 2010 Josh Allmann
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -34,7 +34,7 @@
 #include <assert.h>
 
 #include "rtpdec.h"
-#include "rtpdec_xiph.h"
+#include "rtpdec_formats.h"
 
 /**
  * RTP/Xiph specific private data.
@@ -42,7 +42,10 @@
 struct PayloadContext {
     unsigned ident;             ///< 24-bit stream configuration identifier
     uint32_t timestamp;
-    ByteIOContext* fragment;    ///< buffer for split payloads
+    AVIOContext* fragment;    ///< buffer for split payloads
+    uint8_t *split_buf;
+    int split_pos, split_buf_len, split_buf_size;
+    int split_pkts;
 };
 
 static PayloadContext *xiph_new_context(void)
@@ -54,7 +57,7 @@ static inline void free_fragment_if_needed(PayloadContext * data)
 {
     if (data->fragment) {
         uint8_t* p;
-        url_close_dyn_buf(data->fragment, &p);
+        avio_close_dyn_buf(data->fragment, &p);
         av_free(p);
         data->fragment = NULL;
     }
@@ -63,6 +66,7 @@ static inline void free_fragment_if_needed(PayloadContext * data)
 static void xiph_free_context(PayloadContext * data)
 {
     free_fragment_if_needed(data);
+    av_free(data->split_buf);
     av_free(data);
 }
 
@@ -76,6 +80,29 @@ static int xiph_handle_packet(AVFormatContext * ctx,
 
     int ident, fragmented, tdt, num_pkts, pkt_len;
 
+    if (!buf) {
+        if (!data->split_buf || data->split_pos + 2 > data->split_buf_len ||
+            data->split_pkts <= 0) {
+            av_log(ctx, AV_LOG_ERROR, "No more data to return\n");
+            return AVERROR_INVALIDDATA;
+        }
+        pkt_len = AV_RB16(data->split_buf + data->split_pos);
+        data->split_pos += 2;
+        if (data->split_pos + pkt_len > data->split_buf_len) {
+            av_log(ctx, AV_LOG_ERROR, "Not enough data to return\n");
+            return AVERROR_INVALIDDATA;
+        }
+        if (av_new_packet(pkt, pkt_len)) {
+            av_log(ctx, AV_LOG_ERROR, "Out of memory.\n");
+            return AVERROR(ENOMEM);
+        }
+        pkt->stream_index = st->index;
+        memcpy(pkt->data, data->split_buf + data->split_pos, pkt_len);
+        data->split_pos += pkt_len;
+        data->split_pkts--;
+        return data->split_pkts > 0;
+    }
+
     if (len < 6) {
         av_log(ctx, AV_LOG_ERROR, "Invalid %d byte packet\n", len);
         return AVERROR_INVALIDDATA;
@@ -85,7 +112,7 @@ static int xiph_handle_packet(AVFormatContext * ctx,
     ident       = AV_RB24(buf);
     fragmented  = buf[3] >> 6;
     tdt         = (buf[3] >> 4) & 3;
-    num_pkts    = buf[3] & 7;
+    num_pkts    = buf[3] & 0xf;
     pkt_len     = AV_RB16(buf + 4);
 
     if (pkt_len > len - 6) {
@@ -112,41 +139,33 @@ static int xiph_handle_packet(AVFormatContext * ctx,
     len -= 6;
 
     if (fragmented == 0) {
-        // whole frame(s)
-        int i, data_len, write_len;
-        buf -= 2;
-        len += 2;
-
-        // fast first pass to calculate total length
-        for (i = 0, data_len = 0;  (i < num_pkts) && (len >= 2);  i++) {
-            int off   = data_len + (i << 1);
-            pkt_len   = AV_RB16(buf + off);
-            data_len += pkt_len;
-            len      -= pkt_len + 2;
-        }
-
-        if (len < 0 || i < num_pkts) {
-            av_log(ctx, AV_LOG_ERROR,
-                   "Bad packet: %d bytes left at frame %d of %d\n",
-                   len, i, num_pkts);
-            return AVERROR_INVALIDDATA;
-        }
-
-        if (av_new_packet(pkt, data_len)) {
+        if (av_new_packet(pkt, pkt_len)) {
             av_log(ctx, AV_LOG_ERROR, "Out of memory.\n");
             return AVERROR(ENOMEM);
         }
         pkt->stream_index = st->index;
-
-        // concatenate frames
-        for (i = 0, write_len = 0; write_len < data_len; i++) {
-            pkt_len = AV_RB16(buf);
-            buf += 2;
-            memcpy(pkt->data + write_len, buf, pkt_len);
-            write_len += pkt_len;
-            buf += pkt_len;
+        memcpy(pkt->data, buf, pkt_len);
+        buf += pkt_len;
+        len -= pkt_len;
+        num_pkts--;
+
+        if (num_pkts > 0) {
+            if (len > data->split_buf_size || !data->split_buf) {
+                av_freep(&data->split_buf);
+                data->split_buf_size = 2 * len;
+                data->split_buf = av_malloc(data->split_buf_size);
+                if (!data->split_buf) {
+                    av_log(ctx, AV_LOG_ERROR, "Out of memory.\n");
+                    av_free_packet(pkt);
+                    return AVERROR(ENOMEM);
+                }
+            }
+            memcpy(data->split_buf, buf, len);
+            data->split_buf_len = len;
+            data->split_pos = 0;
+            data->split_pkts = num_pkts;
+            return 1;
         }
-        assert(write_len == data_len);
 
         return 0;
 
@@ -157,10 +176,10 @@ static int xiph_handle_packet(AVFormatContext * ctx,
         // end packet has been lost somewhere, so drop buffered data
         free_fragment_if_needed(data);
 
-        if((res = url_open_dyn_buf(&data->fragment)) < 0)
+        if((res = avio_open_dyn_buf(&data->fragment)) < 0)
             return res;
 
-        put_buffer(data->fragment, buf, pkt_len);
+        avio_write(data->fragment, buf, pkt_len);
         data->timestamp = *timestamp;
 
     } else {
@@ -172,30 +191,29 @@ static int xiph_handle_packet(AVFormatContext * ctx,
             av_log(ctx, AV_LOG_ERROR, "RTP timestamps don't match!\n");
             return AVERROR_INVALIDDATA;
         }
+        if (!data->fragment) {
+            av_log(ctx, AV_LOG_WARNING,
+                   "Received packet without a start fragment; dropping.\n");
+            return AVERROR(EAGAIN);
+        }
 
         // copy data to fragment buffer
-        put_buffer(data->fragment, buf, pkt_len);
+        avio_write(data->fragment, buf, pkt_len);
 
         if (fragmented == 3) {
             // end of xiph data packet
-            uint8_t* xiph_data;
-            int frame_size = url_close_dyn_buf(data->fragment, &xiph_data);
+            av_init_packet(pkt);
+            pkt->size = avio_close_dyn_buf(data->fragment, &pkt->data);
 
-            if (frame_size < 0) {
+            if (pkt->size < 0) {
                 av_log(ctx, AV_LOG_ERROR,
                        "Error occurred when getting fragment buffer.");
-                return frame_size;
-            }
-
-            if (av_new_packet(pkt, frame_size)) {
-                av_log(ctx, AV_LOG_ERROR, "Out of memory.\n");
-                return AVERROR(ENOMEM);
+                return pkt->size;
             }
 
-            memcpy(pkt->data, xiph_data, frame_size);
             pkt->stream_index = st->index;
+            pkt->destruct = av_destruct_packet;
 
-            av_free(xiph_data);
             data->fragment = NULL;
 
             return 0;
@@ -236,7 +254,7 @@ parse_packed_headers(const uint8_t * packed_headers,
 
     if (packed_headers_end - packed_headers < 9) {
         av_log(codec, AV_LOG_ERROR,
-               "Invalid %d byte packed header.",
+               "Invalid %td byte packed header.",
                packed_headers_end - packed_headers);
         return AVERROR_INVALIDDATA;
     }
@@ -258,7 +276,7 @@ parse_packed_headers(const uint8_t * packed_headers,
     if (packed_headers_end - packed_headers != length ||
         length1 > length || length2 > length - length1) {
         av_log(codec, AV_LOG_ERROR,
-               "Bad packed header lengths (%d,%d,%d,%d)\n", length1,
+               "Bad packed header lengths (%d,%d,%td,%d)\n", length1,
                length2, packed_headers_end - packed_headers, length);
         return AVERROR_INVALIDDATA;
     }
@@ -286,14 +304,25 @@ parse_packed_headers(const uint8_t * packed_headers,
     return 0;
 }
 
-static int xiph_parse_fmtp_pair(AVCodecContext * codec,
+static int xiph_parse_fmtp_pair(AVStream* stream,
                                 PayloadContext *xiph_data,
                                 char *attr, char *value)
 {
+    AVCodecContext *codec = stream->codec;
     int result = 0;
 
     if (!strcmp(attr, "sampling")) {
-        return AVERROR_PATCHWELCOME;
+        if (!strcmp(value, "YCbCr-4:2:0")) {
+            codec->pix_fmt = PIX_FMT_YUV420P;
+        } else if (!strcmp(value, "YCbCr-4:4:2")) {
+            codec->pix_fmt = PIX_FMT_YUV422P;
+        } else if (!strcmp(value, "YCbCr-4:4:4")) {
+            codec->pix_fmt = PIX_FMT_YUV444P;
+        } else {
+            av_log(codec, AV_LOG_ERROR,
+                   "Unsupported pixel format %s\n", attr);
+            return AVERROR_INVALIDDATA;
+        }
     } else if (!strcmp(attr, "width")) {
         /* This is an integer between 1 and 1048561
          * and MUST be in multiples of 16. */
@@ -346,34 +375,12 @@ static int xiph_parse_sdp_line(AVFormatContext *s, int st_index,
                                  PayloadContext *data, const char *line)
 {
     const char *p;
-    char *value;
-    char attr[25];
-    int value_size = strlen(line), attr_size = sizeof(attr), res = 0;
-    AVCodecContext* codec = s->streams[st_index]->codec;
-
-    assert(data);
-
-    if (!(value = av_malloc(value_size))) {
-        av_log(codec, AV_LOG_ERROR, "Out of memory\n");
-        return AVERROR(ENOMEM);
-    }
 
     if (av_strstart(line, "fmtp:", &p)) {
-        // remove protocol identifier
-        while (*p && *p == ' ') p++; // strip spaces
-        while (*p && *p != ' ') p++; // eat protocol identifier
-        while (*p && *p == ' ') p++; // strip trailing spaces
-
-        while (ff_rtsp_next_attr_and_value(&p,
-                                           attr, attr_size,
-                                           value, value_size)) {
-            res = xiph_parse_fmtp_pair(codec, data, attr, value);
-            if (res < 0 && res != AVERROR_PATCHWELCOME)
-                return res;
-        }
+        return ff_parse_fmtp(s->streams[st_index], data, p,
+                             xiph_parse_fmtp_pair);
     }
 
-    av_free(value);
     return 0;
 }
 
diff --git a/libavformat/rtpdec_xiph.h b/libavformat/rtpdec_xiph.h
deleted file mode 100644
index 50aa77f..0000000
--- a/libavformat/rtpdec_xiph.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Xiph RTP Protocols
- * Based off RFC 5215 (Vorbis RTP) and the Theora RTP draft.
- * Copyright (c) 2009 Colin McQuillian
- * Copyright (c) 2010 Josh Allmann
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-#ifndef AVFORMAT_RTPDEC_XIPH_H
-#define AVFORMAT_RTPDEC_XIPH_H
-
-#include "libavcodec/avcodec.h"
-#include "rtpdec.h"
-
-/**
- * Theora RTP callbacks.
- */
-extern RTPDynamicProtocolHandler ff_theora_dynamic_handler;
-
-/**
- * Vorbis RTP callbacks.
- */
-extern RTPDynamicProtocolHandler ff_vorbis_dynamic_handler;
-
-#endif /* AVFORMAT_RTPDEC_XIPH_H */
diff --git a/libavformat/rtpenc.c b/libavformat/rtpenc.c
index 5df101e..7cedff3 100644
--- a/libavformat/rtpenc.c
+++ b/libavformat/rtpenc.c
@@ -2,20 +2,20 @@
  * RTP output format
  * Copyright (c) 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -24,8 +24,6 @@
 #include "internal.h"
 #include "libavutil/random_seed.h"
 
-#include <unistd.h>
-
 #include "rtpenc.h"
 
 //#define DEBUG
@@ -55,6 +53,10 @@ static int is_supported(enum CodecID id)
     case CODEC_ID_MPEG2TS:
     case CODEC_ID_AMR_NB:
     case CODEC_ID_AMR_WB:
+    case CODEC_ID_VORBIS:
+    case CODEC_ID_THEORA:
+    case CODEC_ID_VP8:
+    case CODEC_ID_ADPCM_G722:
         return 1;
     default:
         return 0;
@@ -80,10 +82,10 @@ static int rtp_write_header(AVFormatContext *s1)
     if (s->payload_type < 0)
         s->payload_type = RTP_PT_PRIVATE + (st->codec->codec_type == AVMEDIA_TYPE_AUDIO);
 
-    s->base_timestamp = ff_random_get_seed();
+    s->base_timestamp = av_get_random_seed();
     s->timestamp = s->base_timestamp;
     s->cur_timestamp = 0;
-    s->ssrc = ff_random_get_seed();
+    s->ssrc = av_get_random_seed();
     s->first_packet = 1;
     s->first_rtcp_ntp_time = ff_ntp_time();
     if (s1->start_time_realtime)
@@ -91,7 +93,7 @@ static int rtp_write_header(AVFormatContext *s1)
         s->first_rtcp_ntp_time = (s1->start_time_realtime / 1000) * 1000 +
                                  NTP_OFFSET_US;
 
-    max_packet_size = url_fget_max_packet_size(s1->pb);
+    max_packet_size = s1->pb->max_packet_size;
     if (max_packet_size <= 12)
         return AVERROR(EIO);
     s->buf = av_malloc(max_packet_size);
@@ -131,6 +133,28 @@ static int rtp_write_header(AVFormatContext *s1)
         s->max_payload_size = n * TS_PACKET_SIZE;
         s->buf_ptr = s->buf;
         break;
+    case CODEC_ID_H264:
+        /* check for H.264 MP4 syntax */
+        if (st->codec->extradata_size > 4 && st->codec->extradata[0] == 1) {
+            s->nal_length_size = (st->codec->extradata[4] & 0x03) + 1;
+        }
+        break;
+    case CODEC_ID_VORBIS:
+    case CODEC_ID_THEORA:
+        if (!s->max_frames_per_packet) s->max_frames_per_packet = 15;
+        s->max_frames_per_packet = av_clip(s->max_frames_per_packet, 1, 15);
+        s->max_payload_size -= 6; // ident+frag+tdt/vdt+pkt_num+pkt_length
+        s->num_frames = 0;
+        goto defaultcase;
+    case CODEC_ID_VP8:
+        av_log(s1, AV_LOG_ERROR, "RTP VP8 payload implementation is "
+                                 "incompatible with the latest spec drafts.\n");
+        break;
+    case CODEC_ID_ADPCM_G722:
+        /* Due to a historical error, the clock rate for G722 in RTP is
+         * 8000, even if the sample rate is 16000. See RFC 3551. */
+        av_set_pts_info(st, 32, 1, 8000);
+        break;
     case CODEC_ID_AMR_NB:
     case CODEC_ID_AMR_WB:
         if (!s->max_frames_per_packet)
@@ -151,6 +175,7 @@ static int rtp_write_header(AVFormatContext *s1)
     case CODEC_ID_AAC:
         s->num_frames = 0;
     default:
+defaultcase:
         if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
             av_set_pts_info(st, 32, 1, st->codec->sample_rate);
         }
@@ -167,21 +192,21 @@ static void rtcp_send_sr(AVFormatContext *s1, int64_t ntp_time)
     RTPMuxContext *s = s1->priv_data;
     uint32_t rtp_ts;
 
-    dprintf(s1, "RTCP: %02x %"PRIx64" %x\n", s->payload_type, ntp_time, s->timestamp);
+    av_dlog(s1, "RTCP: %02x %"PRIx64" %x\n", s->payload_type, ntp_time, s->timestamp);
 
     s->last_rtcp_ntp_time = ntp_time;
     rtp_ts = av_rescale_q(ntp_time - s->first_rtcp_ntp_time, (AVRational){1, 1000000},
                           s1->streams[0]->time_base) + s->base_timestamp;
-    put_byte(s1->pb, (RTP_VERSION << 6));
-    put_byte(s1->pb, 200);
-    put_be16(s1->pb, 6); /* length in words - 1 */
-    put_be32(s1->pb, s->ssrc);
-    put_be32(s1->pb, ntp_time / 1000000);
-    put_be32(s1->pb, ((ntp_time % 1000000) << 32) / 1000000);
-    put_be32(s1->pb, rtp_ts);
-    put_be32(s1->pb, s->packet_count);
-    put_be32(s1->pb, s->octet_count);
-    put_flush_packet(s1->pb);
+    avio_w8(s1->pb, (RTP_VERSION << 6));
+    avio_w8(s1->pb, RTCP_SR);
+    avio_wb16(s1->pb, 6); /* length in words - 1 */
+    avio_wb32(s1->pb, s->ssrc);
+    avio_wb32(s1->pb, ntp_time / 1000000);
+    avio_wb32(s1->pb, ((ntp_time % 1000000) << 32) / 1000000);
+    avio_wb32(s1->pb, rtp_ts);
+    avio_wb32(s1->pb, s->packet_count);
+    avio_wb32(s1->pb, s->octet_count);
+    avio_flush(s1->pb);
 }
 
 /* send an rtp packet. sequence number is incremented, but the caller
@@ -190,17 +215,17 @@ void ff_rtp_send_data(AVFormatContext *s1, const uint8_t *buf1, int len, int m)
 {
     RTPMuxContext *s = s1->priv_data;
 
-    dprintf(s1, "rtp_send_data size=%d\n", len);
+    av_dlog(s1, "rtp_send_data size=%d\n", len);
 
     /* build the RTP header */
-    put_byte(s1->pb, (RTP_VERSION << 6));
-    put_byte(s1->pb, (s->payload_type & 0x7f) | ((m & 0x01) << 7));
-    put_be16(s1->pb, s->seq);
-    put_be32(s1->pb, s->timestamp);
-    put_be32(s1->pb, s->ssrc);
+    avio_w8(s1->pb, (RTP_VERSION << 6));
+    avio_w8(s1->pb, (s->payload_type & 0x7f) | ((m & 0x01) << 7));
+    avio_wb16(s1->pb, s->seq);
+    avio_wb32(s1->pb, s->timestamp);
+    avio_wb32(s1->pb, s->ssrc);
 
-    put_buffer(s1->pb, buf1, len);
-    put_flush_packet(s1->pb);
+    avio_write(s1->pb, buf1, len);
+    avio_flush(s1->pb);
 
     s->seq++;
     s->octet_count += len;
@@ -339,7 +364,7 @@ static int rtp_write_packet(AVFormatContext *s1, AVPacket *pkt)
     int rtcp_bytes;
     int size= pkt->size;
 
-    dprintf(s1, "%d: write len=%d\n", pkt->stream_index, size);
+    av_dlog(s1, "%d: write len=%d\n", pkt->stream_index, size);
 
     rtcp_bytes = ((s->octet_count - s->last_octet_count) * RTCP_TX_RATIO_NUM) /
         RTCP_TX_RATIO_DEN;
@@ -364,6 +389,12 @@ static int rtp_write_packet(AVFormatContext *s1, AVPacket *pkt)
     case CODEC_ID_PCM_S16LE:
         rtp_send_samples(s1, pkt->data, size, 2 * st->codec->channels);
         break;
+    case CODEC_ID_ADPCM_G722:
+        /* The actual sample size is half a byte per sample, but since the
+         * stream clock rate is 8000 Hz while the sample rate is 16000 Hz,
+         * the correct parameter for send_samples is 1 byte per stream clock. */
+        rtp_send_samples(s1, pkt->data, size, 1 * st->codec->channels);
+        break;
     case CODEC_ID_MP2:
     case CODEC_ID_MP3:
         rtp_send_mpegaudio(s1, pkt->data, size);
@@ -389,6 +420,13 @@ static int rtp_write_packet(AVFormatContext *s1, AVPacket *pkt)
     case CODEC_ID_H263P:
         ff_rtp_send_h263(s1, pkt->data, size);
         break;
+    case CODEC_ID_VORBIS:
+    case CODEC_ID_THEORA:
+        ff_rtp_send_xiph(s1, pkt->data, size);
+        break;
+    case CODEC_ID_VP8:
+        ff_rtp_send_vp8(s1, pkt->data, size);
+        break;
     default:
         /* better than nothing : send the codec raw data */
         rtp_send_raw(s1, pkt->data, size);
@@ -406,7 +444,7 @@ static int rtp_write_trailer(AVFormatContext *s1)
     return 0;
 }
 
-AVOutputFormat rtp_muxer = {
+AVOutputFormat ff_rtp_muxer = {
     "rtp",
     NULL_IF_CONFIG_SMALL("RTP output format"),
     NULL,
diff --git a/libavformat/rtpenc.h b/libavformat/rtpenc.h
index 5710160..21c5c31 100644
--- a/libavformat/rtpenc.h
+++ b/libavformat/rtpenc.h
@@ -2,20 +2,20 @@
  * RTP muxer definitions
  * Copyright (c) 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #ifndef AVFORMAT_RTPENC_H
@@ -50,6 +50,12 @@ struct RTPMuxContext {
     uint8_t *buf_ptr;
 
     int max_frames_per_packet;
+
+    /**
+     * Number of bytes used for H.264 NAL length, if the MP4 syntax is used
+     * (1, 2 or 4)
+     */
+    int nal_length_size;
 };
 
 typedef struct RTPMuxContext RTPMuxContext;
@@ -61,5 +67,7 @@ void ff_rtp_send_h263(AVFormatContext *s1, const uint8_t *buf1, int size);
 void ff_rtp_send_aac(AVFormatContext *s1, const uint8_t *buff, int size);
 void ff_rtp_send_amr(AVFormatContext *s1, const uint8_t *buff, int size);
 void ff_rtp_send_mpegvideo(AVFormatContext *s1, const uint8_t *buf1, int size);
+void ff_rtp_send_xiph(AVFormatContext *s1, const uint8_t *buff, int size);
+void ff_rtp_send_vp8(AVFormatContext *s1, const uint8_t *buff, int size);
 
 #endif /* AVFORMAT_RTPENC_H */
diff --git a/libavformat/rtpenc_aac.c b/libavformat/rtpenc_aac.c
index e19b286..86318df 100644
--- a/libavformat/rtpenc_aac.c
+++ b/libavformat/rtpenc_aac.c
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2007 Luca Abeni
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavformat/rtpenc_amr.c b/libavformat/rtpenc_amr.c
index 367789f..4da7ace 100644
--- a/libavformat/rtpenc_amr.c
+++ b/libavformat/rtpenc_amr.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2007 Luca Abeni
  * Copyright (c) 2009 Martin Storsjo
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavformat/rtpenc_chain.c b/libavformat/rtpenc_chain.c
new file mode 100644
index 0000000..1727740
--- /dev/null
+++ b/libavformat/rtpenc_chain.c
@@ -0,0 +1,77 @@
+/*
+ * RTP muxer chaining code
+ * Copyright (c) 2010 Martin Storsjo
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "avformat.h"
+#include "avio_internal.h"
+#include "rtpenc_chain.h"
+#include "avio_internal.h"
+
+AVFormatContext *ff_rtp_chain_mux_open(AVFormatContext *s, AVStream *st,
+                                       URLContext *handle, int packet_size)
+{
+    AVFormatContext *rtpctx;
+    int ret;
+    AVOutputFormat *rtp_format = av_guess_format("rtp", NULL, NULL);
+
+    if (!rtp_format)
+        return NULL;
+
+    /* Allocate an AVFormatContext for each output stream */
+    rtpctx = avformat_alloc_context();
+    if (!rtpctx)
+        return NULL;
+
+    rtpctx->oformat = rtp_format;
+    if (!av_new_stream(rtpctx, 0)) {
+        av_free(rtpctx);
+        return NULL;
+    }
+    /* Copy the max delay setting; the rtp muxer reads this. */
+    rtpctx->max_delay = s->max_delay;
+    /* Copy other stream parameters. */
+    rtpctx->streams[0]->sample_aspect_ratio = st->sample_aspect_ratio;
+
+    /* Set the synchronized start time. */
+    rtpctx->start_time_realtime = s->start_time_realtime;
+
+    avcodec_copy_context(rtpctx->streams[0]->codec, st->codec);
+
+    if (handle) {
+        ffio_fdopen(&rtpctx->pb, handle);
+    } else
+        ffio_open_dyn_packet_buf(&rtpctx->pb, packet_size);
+    ret = av_write_header(rtpctx);
+
+    if (ret) {
+        if (handle) {
+            avio_close(rtpctx->pb);
+        } else {
+            uint8_t *ptr;
+            avio_close_dyn_buf(rtpctx->pb, &ptr);
+            av_free(ptr);
+        }
+        avformat_free_context(rtpctx);
+        return NULL;
+    }
+
+    return rtpctx;
+}
+
diff --git a/libavformat/rtpenc_chain.h b/libavformat/rtpenc_chain.h
new file mode 100644
index 0000000..6bdddcf
--- /dev/null
+++ b/libavformat/rtpenc_chain.h
@@ -0,0 +1,31 @@
+/*
+ * RTP muxer chaining code
+ * Copyright (c) 2010 Martin Storsjo
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVFORMAT_RTPENC_CHAIN_H
+#define AVFORMAT_RTPENC_CHAIN_H
+
+#include "avformat.h"
+#include "url.h"
+
+AVFormatContext *ff_rtp_chain_mux_open(AVFormatContext *s, AVStream *st,
+                                       URLContext *handle, int packet_size);
+
+#endif /* AVFORMAT_RTPENC_CHAIN_H */
diff --git a/libavformat/rtpenc_h263.c b/libavformat/rtpenc_h263.c
index 84403a1..fbc696e 100644
--- a/libavformat/rtpenc_h263.c
+++ b/libavformat/rtpenc_h263.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2009 Luca Abeni
  * Copyright (c) 2009 Martin Storsjo
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavformat/rtpenc_h264.c b/libavformat/rtpenc_h264.c
index 697def6..9ca6f7f 100644
--- a/libavformat/rtpenc_h264.c
+++ b/libavformat/rtpenc_h264.c
@@ -2,20 +2,20 @@
  * RTP packetization for H.264 (RFC3984)
  * Copyright (c) 2008 Luca Abeni
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavformat/rtpenc_mpv.c b/libavformat/rtpenc_mpv.c
index b23c8f8..f6a5d77 100644
--- a/libavformat/rtpenc_mpv.c
+++ b/libavformat/rtpenc_mpv.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2002 Fabrice Bellard
  * Copyright (c) 2007 Luca Abeni
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavformat/rtpenc_vp8.c b/libavformat/rtpenc_vp8.c
new file mode 100644
index 0000000..afedbb4
--- /dev/null
+++ b/libavformat/rtpenc_vp8.c
@@ -0,0 +1,47 @@
+/*
+ * RTP VP8 Packetizer
+ * Copyright (c) 2010 Josh Allmann
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "rtpenc.h"
+
+/* Based on a draft spec for VP8 RTP.
+ * ( http://www.webmproject.org/code/specs/rtp/ ) */
+void ff_rtp_send_vp8(AVFormatContext *s1, const uint8_t *buf, int size)
+{
+    RTPMuxContext *s = s1->priv_data;
+    int len, max_packet_size;
+
+    s->buf_ptr      = s->buf;
+    s->timestamp    = s->cur_timestamp;
+    max_packet_size = s->max_payload_size - 1; // minus one for header byte
+
+    *s->buf_ptr++ = 1; // 0b1 indicates start of frame
+    while (size > 0) {
+        len = FFMIN(size, max_packet_size);
+
+        memcpy(s->buf_ptr, buf, len);
+        ff_rtp_send_data(s1, s->buf, len+1, size == len); // marker bit is last packet in frame
+
+        size         -= len;
+        buf          += len;
+        s->buf_ptr    = s->buf;
+        *s->buf_ptr++ = 0; // payload descriptor
+    }
+}
diff --git a/libavformat/rtpenc_xiph.c b/libavformat/rtpenc_xiph.c
new file mode 100644
index 0000000..07086b1
--- /dev/null
+++ b/libavformat/rtpenc_xiph.c
@@ -0,0 +1,126 @@
+/*
+ * RTP packetization for Xiph audio and video
+ * Copyright (c) 2010 Josh Allmann
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "avformat.h"
+#include "rtpenc.h"
+
+/**
+ * Packetize Xiph frames into RTP according to
+ * RFC 5215 (Vorbis) and the Theora RFC draft.
+ * (http://svn.xiph.org/trunk/theora/doc/draft-ietf-avt-rtp-theora-00.txt)
+ */
+void ff_rtp_send_xiph(AVFormatContext *s1, const uint8_t *buff, int size)
+{
+    RTPMuxContext *s = s1->priv_data;
+    int max_pkt_size, xdt, frag;
+    uint8_t *q;
+
+    max_pkt_size = s->max_payload_size;
+
+    // set xiph data type
+    switch (*buff) {
+    case 0x01:   // vorbis id
+    case 0x05:   // vorbis setup
+    case 0x80:   // theora header
+    case 0x82:   // theora tables
+        xdt = 1; // packed config payload
+        break;
+    case 0x03:   // vorbis comments
+    case 0x81:   // theora comments
+        xdt = 2; // comment payload
+        break;
+    default:
+        xdt = 0; // raw data payload
+        break;
+    }
+
+    // Set ident.
+    // Probably need a non-fixed way of generating
+    // this, but it has to be done in SDP and passed in from there.
+    q = s->buf;
+    *q++ = (RTP_XIPH_IDENT >> 16) & 0xff;
+    *q++ = (RTP_XIPH_IDENT >>  8) & 0xff;
+    *q++ = (RTP_XIPH_IDENT      ) & 0xff;
+
+    // set fragment
+    // 0 - whole frame (possibly multiple frames)
+    // 1 - first fragment
+    // 2 - fragment continuation
+    // 3 - last fragmement
+    frag = size <= max_pkt_size ? 0 : 1;
+
+    if (!frag && !xdt) { // do we have a whole frame of raw data?
+        uint8_t *end_ptr = s->buf + 6 + max_pkt_size; // what we're allowed to write
+        uint8_t *ptr     = s->buf_ptr + 2 + size; // what we're going to write
+        int remaining    = end_ptr - ptr;
+
+        assert(s->num_frames <= s->max_frames_per_packet);
+        if ((s->num_frames > 0 && remaining < 0) ||
+            s->num_frames == s->max_frames_per_packet) {
+            // send previous packets now; no room for new data
+            ff_rtp_send_data(s1, s->buf, s->buf_ptr - s->buf, 0);
+            s->num_frames = 0;
+        }
+
+        // buffer current frame to send later
+        if (0 == s->num_frames) s->timestamp = s->cur_timestamp;
+        s->num_frames++;
+
+        // Set packet header. Normally, this is OR'd with frag and xdt,
+        // but those are zero, so omitted here
+        *q++ = s->num_frames;
+
+        if (s->num_frames > 1) q = s->buf_ptr; // jump ahead if needed
+        *q++ = (size >> 8) & 0xff;
+        *q++ = size & 0xff;
+        memcpy(q, buff, size);
+        q += size;
+        s->buf_ptr = q;
+
+        return;
+    } else if (s->num_frames) {
+        // immediately send buffered frames if buffer is not raw data,
+        // or if current frame is fragmented.
+        ff_rtp_send_data(s1, s->buf, s->buf_ptr - s->buf, 0);
+    }
+
+    s->timestamp = s->cur_timestamp;
+    s->num_frames = 0;
+    s->buf_ptr = q;
+    while (size > 0) {
+        int len = (!frag || frag == 3) ? size : max_pkt_size;
+        q = s->buf_ptr;
+
+        // set packet headers
+        *q++ = (frag << 6) | (xdt << 4); // num_frames = 0
+        *q++ = (len >> 8) & 0xff;
+        *q++ = len & 0xff;
+        // set packet body
+        memcpy(q, buff, len);
+        q += len;
+        buff += len;
+        size -= len;
+
+        ff_rtp_send_data(s1, s->buf, q - s->buf, 0);
+
+        frag = size <= max_pkt_size ? 3 : 2;
+    }
+}
diff --git a/libavformat/rtpproto.c b/libavformat/rtpproto.c
index 754908c..b92b2e7 100644
--- a/libavformat/rtpproto.c
+++ b/libavformat/rtpproto.c
@@ -2,20 +2,20 @@
  * RTP network protocol
  * Copyright (c) 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -24,9 +24,12 @@
  * RTP protocol
  */
 
+#include "libavutil/parseutils.h"
 #include "libavutil/avstring.h"
 #include "avformat.h"
+#include "avio_internal.h"
 #include "rtpdec.h"
+#include "url.h"
 
 #include <unistd.h>
 #include <stdarg.h>
@@ -34,8 +37,8 @@
 #include "network.h"
 #include "os_support.h"
 #include <fcntl.h>
-#if HAVE_SYS_SELECT_H
-#include <sys/select.h>
+#if HAVE_POLL_H
+#include <sys/poll.h>
 #endif
 #include <sys/time.h>
 
@@ -52,7 +55,7 @@ typedef struct RTPContext {
  * get the local port first, then you must call this function to set
  * the remote server address.
  *
- * @param s1 media file context
+ * @param h media file context
  * @param uri of the remote server
  * @return zero if no error.
  */
@@ -66,14 +69,14 @@ int rtp_set_remote_url(URLContext *h, const char *uri)
     char buf[1024];
     char path[1024];
 
-    ff_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port,
+    av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port,
                  path, sizeof(path), uri);
 
     ff_url_join(buf, sizeof(buf), "udp", NULL, hostname, port, "%s", path);
-    udp_set_remote_url(s->rtp_hd, buf);
+    ff_udp_set_remote_url(s->rtp_hd, buf);
 
     ff_url_join(buf, sizeof(buf), "udp", NULL, hostname, port + 1, "%s", path);
-    udp_set_remote_url(s->rtcp_hd, buf);
+    ff_udp_set_remote_url(s->rtcp_hd, buf);
     return 0;
 }
 
@@ -101,7 +104,7 @@ static void url_add_option(char *buf, int buf_size, const char *fmt, ...)
 static void build_udp_url(char *buf, int buf_size,
                           const char *hostname, int port,
                           int local_port, int ttl,
-                          int max_packet_size)
+                          int max_packet_size, int connect)
 {
     ff_url_join(buf, buf_size, "udp", NULL, hostname, port, NULL);
     if (local_port >= 0)
@@ -110,6 +113,8 @@ static void build_udp_url(char *buf, int buf_size,
         url_add_option(buf, buf_size, "ttl=%d", ttl);
     if (max_packet_size >=0)
         url_add_option(buf, buf_size, "pkt_size=%d", max_packet_size);
+    if (connect)
+        url_add_option(buf, buf_size, "connect=1");
 }
 
 /**
@@ -119,6 +124,7 @@ static void build_udp_url(char *buf, int buf_size,
  *         'localrtpport=n'   : set the local rtp port to n
  *         'localrtcpport=n'  : set the local rtcp port to n
  *         'pkt_size=n'       : set max packet size
+ *         'connect=0/1'      : do a connect() on the UDP socket
  * deprecated option:
  *         'localport=n'      : set the local port to n
  *
@@ -132,21 +138,21 @@ static int rtp_open(URLContext *h, const char *uri, int flags)
 {
     RTPContext *s;
     int rtp_port, rtcp_port,
-        is_output, ttl,
+        is_output, ttl, connect,
         local_rtp_port, local_rtcp_port, max_packet_size;
     char hostname[256];
     char buf[1024];
     char path[1024];
     const char *p;
 
-    is_output = (flags & URL_WRONLY);
+    is_output = (flags & AVIO_WRONLY);
 
     s = av_mallocz(sizeof(RTPContext));
     if (!s)
         return AVERROR(ENOMEM);
     h->priv_data = s;
 
-    ff_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &rtp_port,
+    av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &rtp_port,
                  path, sizeof(path), uri);
     /* extract parameters */
     ttl = -1;
@@ -154,55 +160,61 @@ static int rtp_open(URLContext *h, const char *uri, int flags)
     local_rtp_port = -1;
     local_rtcp_port = -1;
     max_packet_size = -1;
+    connect = 0;
 
     p = strchr(uri, '?');
     if (p) {
-        if (find_info_tag(buf, sizeof(buf), "ttl", p)) {
+        if (av_find_info_tag(buf, sizeof(buf), "ttl", p)) {
             ttl = strtol(buf, NULL, 10);
         }
-        if (find_info_tag(buf, sizeof(buf), "rtcpport", p)) {
+        if (av_find_info_tag(buf, sizeof(buf), "rtcpport", p)) {
             rtcp_port = strtol(buf, NULL, 10);
         }
-        if (find_info_tag(buf, sizeof(buf), "localport", p)) {
+        if (av_find_info_tag(buf, sizeof(buf), "localport", p)) {
             local_rtp_port = strtol(buf, NULL, 10);
         }
-        if (find_info_tag(buf, sizeof(buf), "localrtpport", p)) {
+        if (av_find_info_tag(buf, sizeof(buf), "localrtpport", p)) {
             local_rtp_port = strtol(buf, NULL, 10);
         }
-        if (find_info_tag(buf, sizeof(buf), "localrtcpport", p)) {
+        if (av_find_info_tag(buf, sizeof(buf), "localrtcpport", p)) {
             local_rtcp_port = strtol(buf, NULL, 10);
         }
-        if (find_info_tag(buf, sizeof(buf), "pkt_size", p)) {
+        if (av_find_info_tag(buf, sizeof(buf), "pkt_size", p)) {
             max_packet_size = strtol(buf, NULL, 10);
         }
+        if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
+            connect = strtol(buf, NULL, 10);
+        }
     }
 
     build_udp_url(buf, sizeof(buf),
-                  hostname, rtp_port, local_rtp_port, ttl, max_packet_size);
-    if (url_open(&s->rtp_hd, buf, flags) < 0)
+                  hostname, rtp_port, local_rtp_port, ttl, max_packet_size,
+                  connect);
+    if (ffurl_open(&s->rtp_hd, buf, flags) < 0)
         goto fail;
     if (local_rtp_port>=0 && local_rtcp_port<0)
-        local_rtcp_port = udp_get_local_port(s->rtp_hd) + 1;
+        local_rtcp_port = ff_udp_get_local_port(s->rtp_hd) + 1;
 
     build_udp_url(buf, sizeof(buf),
-                  hostname, rtcp_port, local_rtcp_port, ttl, max_packet_size);
-    if (url_open(&s->rtcp_hd, buf, flags) < 0)
+                  hostname, rtcp_port, local_rtcp_port, ttl, max_packet_size,
+                  connect);
+    if (ffurl_open(&s->rtcp_hd, buf, flags) < 0)
         goto fail;
 
     /* just to ease handle access. XXX: need to suppress direct handle
        access */
-    s->rtp_fd = url_get_file_handle(s->rtp_hd);
-    s->rtcp_fd = url_get_file_handle(s->rtcp_hd);
+    s->rtp_fd = ffurl_get_file_handle(s->rtp_hd);
+    s->rtcp_fd = ffurl_get_file_handle(s->rtcp_hd);
 
-    h->max_packet_size = url_get_max_packet_size(s->rtp_hd);
+    h->max_packet_size = s->rtp_hd->max_packet_size;
     h->is_streamed = 1;
     return 0;
 
  fail:
     if (s->rtp_hd)
-        url_close(s->rtp_hd);
+        ffurl_close(s->rtp_hd);
     if (s->rtcp_hd)
-        url_close(s->rtcp_hd);
+        ffurl_close(s->rtcp_hd);
     av_free(s);
     return AVERROR(EIO);
 }
@@ -210,19 +222,19 @@ static int rtp_open(URLContext *h, const char *uri, int flags)
 static int rtp_read(URLContext *h, uint8_t *buf, int size)
 {
     RTPContext *s = h->priv_data;
-    struct sockaddr_in from;
+    struct sockaddr_storage from;
     socklen_t from_len;
-    int len, fd_max, n;
-    fd_set rfds;
-    struct timeval tv;
+    int len, n;
+    struct pollfd p[2] = {{s->rtp_fd, POLLIN, 0}, {s->rtcp_fd, POLLIN, 0}};
+
 #if 0
     for(;;) {
         from_len = sizeof(from);
         len = recvfrom (s->rtp_fd, buf, size, 0,
                         (struct sockaddr *)&from, &from_len);
         if (len < 0) {
-            if (ff_neterrno() == FF_NETERROR(EAGAIN) ||
-                ff_neterrno() == FF_NETERROR(EINTR))
+            if (ff_neterrno() == AVERROR(EAGAIN) ||
+                ff_neterrno() == AVERROR(EINTR))
                 continue;
             return AVERROR(EIO);
         }
@@ -231,46 +243,38 @@ static int rtp_read(URLContext *h, uint8_t *buf, int size)
 #else
     for(;;) {
         if (url_interrupt_cb())
-            return AVERROR(EINTR);
+            return AVERROR_EXIT;
         /* build fdset to listen to RTP and RTCP packets */
-        FD_ZERO(&rfds);
-        fd_max = s->rtp_fd;
-        FD_SET(s->rtp_fd, &rfds);
-        if (s->rtcp_fd > fd_max)
-            fd_max = s->rtcp_fd;
-        FD_SET(s->rtcp_fd, &rfds);
-        tv.tv_sec = 0;
-        tv.tv_usec = 100 * 1000;
-        n = select(fd_max + 1, &rfds, NULL, NULL, &tv);
+        n = poll(p, 2, 100);
         if (n > 0) {
             /* first try RTCP */
-            if (FD_ISSET(s->rtcp_fd, &rfds)) {
+            if (p[1].revents & POLLIN) {
                 from_len = sizeof(from);
                 len = recvfrom (s->rtcp_fd, buf, size, 0,
                                 (struct sockaddr *)&from, &from_len);
                 if (len < 0) {
-                    if (ff_neterrno() == FF_NETERROR(EAGAIN) ||
-                        ff_neterrno() == FF_NETERROR(EINTR))
+                    if (ff_neterrno() == AVERROR(EAGAIN) ||
+                        ff_neterrno() == AVERROR(EINTR))
                         continue;
                     return AVERROR(EIO);
                 }
                 break;
             }
             /* then RTP */
-            if (FD_ISSET(s->rtp_fd, &rfds)) {
+            if (p[0].revents & POLLIN) {
                 from_len = sizeof(from);
                 len = recvfrom (s->rtp_fd, buf, size, 0,
                                 (struct sockaddr *)&from, &from_len);
                 if (len < 0) {
-                    if (ff_neterrno() == FF_NETERROR(EAGAIN) ||
-                        ff_neterrno() == FF_NETERROR(EINTR))
+                    if (ff_neterrno() == AVERROR(EAGAIN) ||
+                        ff_neterrno() == AVERROR(EINTR))
                         continue;
                     return AVERROR(EIO);
                 }
                 break;
             }
         } else if (n < 0) {
-            if (ff_neterrno() == FF_NETERROR(EINTR))
+            if (ff_neterrno() == AVERROR(EINTR))
                 continue;
             return AVERROR(EIO);
         }
@@ -279,13 +283,13 @@ static int rtp_read(URLContext *h, uint8_t *buf, int size)
     return len;
 }
 
-static int rtp_write(URLContext *h, uint8_t *buf, int size)
+static int rtp_write(URLContext *h, const uint8_t *buf, int size)
 {
     RTPContext *s = h->priv_data;
     int ret;
     URLContext *hd;
 
-    if (buf[1] >= 200 && buf[1] <= 204) {
+    if (buf[1] >= RTCP_SR && buf[1] <= RTCP_APP) {
         /* RTCP payload type */
         hd = s->rtcp_hd;
     } else {
@@ -293,7 +297,7 @@ static int rtp_write(URLContext *h, uint8_t *buf, int size)
         hd = s->rtp_hd;
     }
 
-    ret = url_write(hd, buf, size);
+    ret = ffurl_write(hd, buf, size);
 #if 0
     {
         struct timespec ts;
@@ -309,76 +313,52 @@ static int rtp_close(URLContext *h)
 {
     RTPContext *s = h->priv_data;
 
-    url_close(s->rtp_hd);
-    url_close(s->rtcp_hd);
+    ffurl_close(s->rtp_hd);
+    ffurl_close(s->rtcp_hd);
     av_free(s);
     return 0;
 }
 
 /**
  * Return the local rtp port used by the RTP connection
- * @param s1 media file context
+ * @param h media file context
  * @return the local port number
  */
 
 int rtp_get_local_rtp_port(URLContext *h)
 {
     RTPContext *s = h->priv_data;
-    return udp_get_local_port(s->rtp_hd);
-}
-
-/**
- * Return the local rtp port used by the RTP connection
- * @param s1 media file context
- * @return the local port number
- */
-
-int rtp_get_local_port(URLContext *h)
-{
-    RTPContext *s = h->priv_data;
-    return udp_get_local_port(s->rtp_hd);
+    return ff_udp_get_local_port(s->rtp_hd);
 }
 
 /**
  * Return the local rtcp port used by the RTP connection
- * @param s1 media file context
+ * @param h media file context
  * @return the local port number
  */
 
 int rtp_get_local_rtcp_port(URLContext *h)
 {
     RTPContext *s = h->priv_data;
-    return udp_get_local_port(s->rtcp_hd);
+    return ff_udp_get_local_port(s->rtcp_hd);
 }
 
-#if (LIBAVFORMAT_VERSION_MAJOR <= 52)
-/**
- * Return the rtp and rtcp file handles for select() usage to wait for
- * several RTP streams at the same time.
- * @param h media file context
- */
-
-void rtp_get_file_handles(URLContext *h, int *prtp_fd, int *prtcp_fd)
+static int rtp_get_file_handle(URLContext *h)
 {
     RTPContext *s = h->priv_data;
-
-    *prtp_fd = s->rtp_fd;
-    *prtcp_fd = s->rtcp_fd;
+    return s->rtp_fd;
 }
-#endif
 
-static int rtp_get_file_handle(URLContext *h)
-{
+int rtp_get_rtcp_file_handle(URLContext *h) {
     RTPContext *s = h->priv_data;
-    return s->rtp_fd;
+    return s->rtcp_fd;
 }
 
-URLProtocol rtp_protocol = {
-    "rtp",
-    rtp_open,
-    rtp_read,
-    rtp_write,
-    NULL, /* seek */
-    rtp_close,
+URLProtocol ff_rtp_protocol = {
+    .name                = "rtp",
+    .url_open            = rtp_open,
+    .url_read            = rtp_read,
+    .url_write           = rtp_write,
+    .url_close           = rtp_close,
     .url_get_file_handle = rtp_get_file_handle,
 };
diff --git a/libavformat/rtsp.c b/libavformat/rtsp.c
index 6dbd796..62c9d35 100644
--- a/libavformat/rtsp.c
+++ b/libavformat/rtsp.c
@@ -2,67 +2,58 @@
  * RTSP/SDP client
  * Copyright (c) 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "libavutil/base64.h"
 #include "libavutil/avstring.h"
 #include "libavutil/intreadwrite.h"
+#include "libavutil/parseutils.h"
+#include "libavutil/random_seed.h"
 #include "avformat.h"
+#include "avio_internal.h"
 
 #include <sys/time.h>
-#if HAVE_SYS_SELECT_H
-#include <sys/select.h>
+#if HAVE_POLL_H
+#include <poll.h>
 #endif
 #include <strings.h>
 #include "internal.h"
 #include "network.h"
 #include "os_support.h"
+#include "http.h"
 #include "rtsp.h"
 
 #include "rtpdec.h"
 #include "rdt.h"
-#include "rtpdec_asf.h"
+#include "rtpdec_formats.h"
+#include "rtpenc_chain.h"
+#include "url.h"
 
 //#define DEBUG
 //#define DEBUG_RTP_TCP
 
-#if LIBAVFORMAT_VERSION_INT < (53 << 16)
-int rtsp_default_protocols = (1 << RTSP_LOWER_TRANSPORT_UDP);
-#endif
-
-/* Timeout values for socket select, in ms,
+/* Timeout values for socket poll, in ms,
  * and read_packet(), in seconds  */
-#define SELECT_TIMEOUT_MS 100
+#define POLL_TIMEOUT_MS 100
 #define READ_PACKET_TIMEOUT_S 10
-#define MAX_TIMEOUTS READ_PACKET_TIMEOUT_S * 1000 / SELECT_TIMEOUT_MS
-
-#define SPACE_CHARS " \t\r\n"
-/* we use memchr() instead of strchr() here because strchr() will return
- * the terminating '\0' of SPACE_CHARS instead of NULL if c is '\0'. */
-#define redir_isspace(c) memchr(SPACE_CHARS, c, 4)
-static void skip_spaces(const char **pp)
-{
-    const char *p;
-    p = *pp;
-    while (redir_isspace(*p))
-        p++;
-    *pp = p;
-}
+#define MAX_TIMEOUTS READ_PACKET_TIMEOUT_S * 1000 / POLL_TIMEOUT_MS
+#define SDP_MAX_SIZE 16384
+#define RECVBUF_SIZE 10 * RTP_MAX_PACKET_LENGTH
 
 static void get_word_until_chars(char *buf, int buf_size,
                                  const char *sep, const char **pp)
@@ -71,7 +62,7 @@ static void get_word_until_chars(char *buf, int buf_size,
     char *q;
 
     p = *pp;
-    skip_spaces(&p);
+    p += strspn(p, SPACE_CHARS);
     q = buf;
     while (!strchr(sep, *p) && *p != '\0') {
         if ((q - buf) < buf_size - 1)
@@ -95,11 +86,62 @@ static void get_word(char *buf, int buf_size, const char **pp)
     get_word_until_chars(buf, buf_size, SPACE_CHARS, pp);
 }
 
+/** Parse a string p in the form of Range:npt=xx-xx, and determine the start
+ *  and end time.
+ *  Used for seeking in the rtp stream.
+ */
+static void rtsp_parse_range_npt(const char *p, int64_t *start, int64_t *end)
+{
+    char buf[256];
+
+    p += strspn(p, SPACE_CHARS);
+    if (!av_stristart(p, "npt=", &p))
+        return;
+
+    *start = AV_NOPTS_VALUE;
+    *end = AV_NOPTS_VALUE;
+
+    get_word_sep(buf, sizeof(buf), "-", &p);
+    av_parse_time(start, buf, 1);
+    if (*p == '-') {
+        p++;
+        get_word_sep(buf, sizeof(buf), "-", &p);
+        av_parse_time(end, buf, 1);
+    }
+//    av_log(NULL, AV_LOG_DEBUG, "Range Start: %lld\n", *start);
+//    av_log(NULL, AV_LOG_DEBUG, "Range End: %lld\n", *end);
+}
+
+static int get_sockaddr(const char *buf, struct sockaddr_storage *sock)
+{
+    struct addrinfo hints, *ai = NULL;
+    memset(&hints, 0, sizeof(hints));
+    hints.ai_flags = AI_NUMERICHOST;
+    if (getaddrinfo(buf, NULL, &hints, &ai))
+        return -1;
+    memcpy(sock, ai->ai_addr, FFMIN(sizeof(*sock), ai->ai_addrlen));
+    freeaddrinfo(ai);
+    return 0;
+}
+
+#if CONFIG_RTPDEC
+static void init_rtp_handler(RTPDynamicProtocolHandler *handler,
+                             RTSPStream *rtsp_st, AVCodecContext *codec)
+{
+    if (!handler)
+        return;
+    codec->codec_id          = handler->codec_id;
+    rtsp_st->dynamic_handler = handler;
+    if (handler->open)
+        rtsp_st->dynamic_protocol_context = handler->open();
+}
+
 /* parse the rtpmap description: <codec_name>/<clock_rate>[/<other params>] */
 static int sdp_parse_rtpmap(AVFormatContext *s,
-                            AVCodecContext *codec, RTSPStream *rtsp_st,
+                            AVStream *st, RTSPStream *rtsp_st,
                             int payload_type, const char *p)
 {
+    AVCodecContext *codec = st->codec;
     char buf[256];
     int i;
     AVCodec *c;
@@ -112,18 +154,15 @@ static int sdp_parse_rtpmap(AVFormatContext *s,
      * have a trailing space. */
     get_word_sep(buf, sizeof(buf), "/ ", &p);
     if (payload_type >= RTP_PT_PRIVATE) {
-        RTPDynamicProtocolHandler *handler;
-        for (handler = RTPFirstDynamicPayloadHandler;
-             handler; handler = handler->next) {
-            if (!strcasecmp(buf, handler->enc_name) &&
-                codec->codec_type == handler->codec_type) {
-                codec->codec_id          = handler->codec_id;
-                rtsp_st->dynamic_handler = handler;
-                if (handler->open)
-                    rtsp_st->dynamic_protocol_context = handler->open();
-                break;
-            }
-        }
+        RTPDynamicProtocolHandler *handler =
+            ff_rtp_handler_find_by_name(buf, codec->codec_type);
+        init_rtp_handler(handler, rtsp_st, codec);
+        /* If no dynamic handler was found, check with the list of standard
+         * allocated types, if such a stream for some reason happens to
+         * use a private payload type. This isn't handled in rtpdec.c, since
+         * the format name from the rtpmap line never is passed into rtpdec. */
+        if (!rtsp_st->dynamic_handler)
+            codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
     } else {
         /* We are in a standard case
          * (from http://www.iana.org/assignments/rtp-parameters). */
@@ -146,6 +185,7 @@ static int sdp_parse_rtpmap(AVFormatContext *s,
         codec->channels = RTSP_DEFAULT_NB_AUDIO_CHANNELS;
         if (i > 0) {
             codec->sample_rate = i;
+            av_set_pts_info(st, 32, 1, codec->sample_rate);
             get_word_sep(buf, sizeof(buf), "/", &p);
             i = atoi(buf);
             if (i > 0)
@@ -162,6 +202,8 @@ static int sdp_parse_rtpmap(AVFormatContext *s,
         break;
     case AVMEDIA_TYPE_VIDEO:
         av_log(s, AV_LOG_DEBUG, "video codec set to: %s\n", c_name);
+        if (i > 0)
+            av_set_pts_info(st, 32, 1, i);
         break;
     default:
         break;
@@ -169,92 +211,13 @@ static int sdp_parse_rtpmap(AVFormatContext *s,
     return 0;
 }
 
-/* return the length and optionally the data */
-static int hex_to_data(uint8_t *data, const char *p)
-{
-    int c, len, v;
-
-    len = 0;
-    v = 1;
-    for (;;) {
-        skip_spaces(&p);
-        if (*p == '\0')
-            break;
-        c = toupper((unsigned char) *p++);
-        if (c >= '0' && c <= '9')
-            c = c - '0';
-        else if (c >= 'A' && c <= 'F')
-            c = c - 'A' + 10;
-        else
-            break;
-        v = (v << 4) | c;
-        if (v & 0x100) {
-            if (data)
-                data[len] = v;
-            len++;
-            v = 1;
-        }
-    }
-    return len;
-}
-
-static void sdp_parse_fmtp_config(AVCodecContext * codec, void *ctx,
-                                  char *attr, char *value)
-{
-    switch (codec->codec_id) {
-    case CODEC_ID_MPEG4:
-    case CODEC_ID_AAC:
-        if (!strcmp(attr, "config")) {
-            /* decode the hexa encoded parameter */
-            int len = hex_to_data(NULL, value);
-            if (codec->extradata)
-                av_free(codec->extradata);
-            codec->extradata = av_mallocz(len + FF_INPUT_BUFFER_PADDING_SIZE);
-            if (!codec->extradata)
-                return;
-            codec->extradata_size = len;
-            hex_to_data(codec->extradata, value);
-        }
-        break;
-    default:
-        break;
-    }
-    return;
-}
-
-typedef struct {
-    const char *str;
-    uint16_t    type;
-    uint32_t    offset;
-} AttrNameMap;
-
-/* All known fmtp parameters and the corresponding RTPAttrTypeEnum */
-#define ATTR_NAME_TYPE_INT 0
-#define ATTR_NAME_TYPE_STR 1
-static const AttrNameMap attr_names[]=
-{
-    { "SizeLength",       ATTR_NAME_TYPE_INT,
-      offsetof(RTPPayloadData, sizelength) },
-    { "IndexLength",      ATTR_NAME_TYPE_INT,
-      offsetof(RTPPayloadData, indexlength) },
-    { "IndexDeltaLength", ATTR_NAME_TYPE_INT,
-      offsetof(RTPPayloadData, indexdeltalength) },
-    { "profile-level-id", ATTR_NAME_TYPE_INT,
-      offsetof(RTPPayloadData, profile_level_id) },
-    { "StreamType",       ATTR_NAME_TYPE_INT,
-      offsetof(RTPPayloadData, streamtype) },
-    { "mode",             ATTR_NAME_TYPE_STR,
-      offsetof(RTPPayloadData, mode) },
-    { NULL, -1, -1 },
-};
-
 /* parse the attribute line from the fmtp a line of an sdp response. This
  * is broken out as a function because it is used in rtp_h264.c, which is
  * forthcoming. */
 int ff_rtsp_next_attr_and_value(const char **p, char *attr, int attr_size,
                                 char *value, int value_size)
 {
-    skip_spaces(p);
+    *p += strspn(*p, SPACE_CHARS);
     if (**p) {
         get_word_sep(attr, attr_size, "=", p);
         if (**p == '=')
@@ -267,68 +230,9 @@ int ff_rtsp_next_attr_and_value(const char **p, char *attr, int attr_size,
     return 0;
 }
 
-/* parse a SDP line and save stream attributes */
-static void sdp_parse_fmtp(AVStream *st, const char *p)
-{
-    char attr[256];
-    /* Vorbis setup headers can be up to 12KB and are sent base64
-     * encoded, giving a 12KB * (4/3) = 16KB FMTP line. */
-    char value[16384];
-    int i;
-    RTSPStream *rtsp_st = st->priv_data;
-    AVCodecContext *codec = st->codec;
-    RTPPayloadData *rtp_payload_data = &rtsp_st->rtp_payload_data;
-
-    /* loop on each attribute */
-    while (ff_rtsp_next_attr_and_value(&p, attr, sizeof(attr),
-                                       value, sizeof(value))) {
-        /* grab the codec extra_data from the config parameter of the fmtp
-         * line */
-        sdp_parse_fmtp_config(codec, rtsp_st->dynamic_protocol_context,
-                              attr, value);
-        /* Looking for a known attribute */
-        for (i = 0; attr_names[i].str; ++i) {
-            if (!strcasecmp(attr, attr_names[i].str)) {
-                if (attr_names[i].type == ATTR_NAME_TYPE_INT) {
-                    *(int *)((char *)rtp_payload_data +
-                        attr_names[i].offset) = atoi(value);
-                } else if (attr_names[i].type == ATTR_NAME_TYPE_STR)
-                    *(char **)((char *)rtp_payload_data +
-                        attr_names[i].offset) = av_strdup(value);
-            }
-        }
-    }
-}
-
-/** Parse a string p in the form of Range:npt=xx-xx, and determine the start
- *  and end time.
- *  Used for seeking in the rtp stream.
- */
-static void rtsp_parse_range_npt(const char *p, int64_t *start, int64_t *end)
-{
-    char buf[256];
-
-    skip_spaces(&p);
-    if (!av_stristart(p, "npt=", &p))
-        return;
-
-    *start = AV_NOPTS_VALUE;
-    *end = AV_NOPTS_VALUE;
-
-    get_word_sep(buf, sizeof(buf), "-", &p);
-    *start = parse_date(buf, 1);
-    if (*p == '-') {
-        p++;
-        get_word_sep(buf, sizeof(buf), "-", &p);
-        *end = parse_date(buf, 1);
-    }
-//    av_log(NULL, AV_LOG_DEBUG, "Range Start: %lld\n", *start);
-//    av_log(NULL, AV_LOG_DEBUG, "Range End: %lld\n", *end);
-}
-
 typedef struct SDPParseState {
     /* SDP only */
-    struct in_addr default_ip;
+    struct sockaddr_storage default_ip;
     int            default_ttl;
     int            skip_media;  ///< set if an unknown m= line occurs
 } SDPParseState;
@@ -343,10 +247,10 @@ static void sdp_parse_line(AVFormatContext *s, SDPParseState *s1,
     int payload_type, i;
     AVStream *st;
     RTSPStream *rtsp_st;
-    struct in_addr sdp_ip;
+    struct sockaddr_storage sdp_ip;
     int ttl;
 
-    dprintf(s, "sdp: %c='%s'\n", letter, buf);
+    av_dlog(s, "sdp: %c='%s'\n", letter, buf);
 
     p = buf;
     if (s1->skip_media && letter != 'm')
@@ -357,10 +261,10 @@ static void sdp_parse_line(AVFormatContext *s, SDPParseState *s1,
         if (strcmp(buf1, "IN") != 0)
             return;
         get_word(buf1, sizeof(buf1), &p);
-        if (strcmp(buf1, "IP4") != 0)
+        if (strcmp(buf1, "IP4") && strcmp(buf1, "IP6"))
             return;
         get_word_sep(buf1, sizeof(buf1), "/", &p);
-        if (ff_inet_aton(buf1, &sdp_ip) == 0)
+        if (get_sockaddr(buf1, &sdp_ip))
             return;
         ttl = 16;
         if (*p == '/') {
@@ -372,8 +276,7 @@ static void sdp_parse_line(AVFormatContext *s, SDPParseState *s1,
             s1->default_ip = sdp_ip;
             s1->default_ttl = ttl;
         } else {
-            st = s->streams[s->nb_streams - 1];
-            rtsp_st = st->priv_data;
+            rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
             rtsp_st->sdp_ip = sdp_ip;
             rtsp_st->sdp_ttl = ttl;
         }
@@ -422,15 +325,22 @@ static void sdp_parse_line(AVFormatContext *s, SDPParseState *s1,
         if (!strcmp(ff_rtp_enc_name(rtsp_st->sdp_payload_type), "MP2T")) {
             /* no corresponding stream */
         } else {
-            st = av_new_stream(s, 0);
+            st = av_new_stream(s, rt->nb_rtsp_streams - 1);
             if (!st)
                 return;
-            st->priv_data = rtsp_st;
             rtsp_st->stream_index = st->index;
             st->codec->codec_type = codec_type;
             if (rtsp_st->sdp_payload_type < RTP_PT_PRIVATE) {
+                RTPDynamicProtocolHandler *handler;
                 /* if standard payload type, we can find the codec right now */
                 ff_rtp_get_codec_info(st->codec, rtsp_st->sdp_payload_type);
+                if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
+                    st->codec->sample_rate > 0)
+                    av_set_pts_info(st, 32, 1, st->codec->sample_rate);
+                /* Even static payload types may need a custom depacketizer */
+                handler = ff_rtp_handler_find_by_id(
+                              rtsp_st->sdp_payload_type, st->codec->codec_type);
+                init_rtp_handler(handler, rtsp_st, st->codec);
             }
         }
         /* put a default control url */
@@ -444,54 +354,39 @@ static void sdp_parse_line(AVFormatContext *s, SDPParseState *s1,
                     av_strlcpy(rt->control_uri, p,
                                sizeof(rt->control_uri));
             } else {
-            char proto[32];
-            /* get the control url */
-            st = s->streams[s->nb_streams - 1];
-            rtsp_st = st->priv_data;
-
-            /* XXX: may need to add full url resolution */
-            ff_url_split(proto, sizeof(proto), NULL, 0, NULL, 0,
-                         NULL, NULL, 0, p);
-            if (proto[0] == '\0') {
-                /* relative control URL */
-                if (rtsp_st->control_url[strlen(rtsp_st->control_url)-1]!='/')
-                av_strlcat(rtsp_st->control_url, "/",
-                           sizeof(rtsp_st->control_url));
-                av_strlcat(rtsp_st->control_url, p,
-                           sizeof(rtsp_st->control_url));
-            } else
-                av_strlcpy(rtsp_st->control_url, p,
-                           sizeof(rtsp_st->control_url));
+                char proto[32];
+                /* get the control url */
+                rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
+
+                /* XXX: may need to add full url resolution */
+                av_url_split(proto, sizeof(proto), NULL, 0, NULL, 0,
+                             NULL, NULL, 0, p);
+                if (proto[0] == '\0') {
+                    /* relative control URL */
+                    if (rtsp_st->control_url[strlen(rtsp_st->control_url)-1]!='/')
+                    av_strlcat(rtsp_st->control_url, "/",
+                               sizeof(rtsp_st->control_url));
+                    av_strlcat(rtsp_st->control_url, p,
+                               sizeof(rtsp_st->control_url));
+                } else
+                    av_strlcpy(rtsp_st->control_url, p,
+                               sizeof(rtsp_st->control_url));
             }
         } else if (av_strstart(p, "rtpmap:", &p) && s->nb_streams > 0) {
             /* NOTE: rtpmap is only supported AFTER the 'm=' tag */
             get_word(buf1, sizeof(buf1), &p);
             payload_type = atoi(buf1);
             st = s->streams[s->nb_streams - 1];
-            rtsp_st = st->priv_data;
-            sdp_parse_rtpmap(s, st->codec, rtsp_st, payload_type, p);
-        } else if (av_strstart(p, "fmtp:", &p)) {
+            rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
+            sdp_parse_rtpmap(s, st, rtsp_st, payload_type, p);
+        } else if (av_strstart(p, "fmtp:", &p) ||
+                   av_strstart(p, "framesize:", &p)) {
             /* NOTE: fmtp is only supported AFTER the 'a=rtpmap:xxx' tag */
-            get_word(buf1, sizeof(buf1), &p);
-            payload_type = atoi(buf1);
-            for (i = 0; i < s->nb_streams; i++) {
-                st      = s->streams[i];
-                rtsp_st = st->priv_data;
-                if (rtsp_st->sdp_payload_type == payload_type) {
-                    if (!(rtsp_st->dynamic_handler &&
-                          rtsp_st->dynamic_handler->parse_sdp_a_line &&
-                          rtsp_st->dynamic_handler->parse_sdp_a_line(s,
-                              i, rtsp_st->dynamic_protocol_context, buf)))
-                        sdp_parse_fmtp(st, p);
-                }
-            }
-        } else if (av_strstart(p, "framesize:", &p)) {
             // let dynamic protocol handlers have a stab at the line.
             get_word(buf1, sizeof(buf1), &p);
             payload_type = atoi(buf1);
-            for (i = 0; i < s->nb_streams; i++) {
-                st      = s->streams[i];
-                rtsp_st = st->priv_data;
+            for (i = 0; i < rt->nb_rtsp_streams; i++) {
+                rtsp_st = rt->rtsp_streams[i];
                 if (rtsp_st->sdp_payload_type == payload_type &&
                     rtsp_st->dynamic_handler &&
                     rtsp_st->dynamic_handler->parse_sdp_a_line)
@@ -510,6 +405,10 @@ static void sdp_parse_line(AVFormatContext *s, SDPParseState *s1,
         } else if (av_strstart(p, "IsRealDataType:integer;",&p)) {
             if (atoi(p) == 1)
                 rt->transport = RTSP_TRANSPORT_RDT;
+        } else if (av_strstart(p, "SampleRate:integer;", &p) &&
+                   s->nb_streams > 0) {
+            st = s->streams[s->nb_streams - 1];
+            st->codec->sample_rate = atoi(p);
         } else {
             if (rt->server_type == RTSP_SERVER_WMS)
                 ff_wms_parse_sdp_a_line(s, p);
@@ -517,7 +416,7 @@ static void sdp_parse_line(AVFormatContext *s, SDPParseState *s1,
                 if (rt->server_type == RTSP_SERVER_REAL)
                     ff_real_parse_sdp_a_line(s, s->nb_streams - 1, p);
 
-                rtsp_st = s->streams[s->nb_streams - 1]->priv_data;
+                rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
                 if (rtsp_st->dynamic_handler &&
                     rtsp_st->dynamic_handler->parse_sdp_a_line)
                     rtsp_st->dynamic_handler->parse_sdp_a_line(s,
@@ -529,8 +428,14 @@ static void sdp_parse_line(AVFormatContext *s, SDPParseState *s1,
     }
 }
 
-static int sdp_parse(AVFormatContext *s, const char *content)
+/**
+ * Parse the sdp description and allocate the rtp streams and the
+ * pollfd array used for udp ones.
+ */
+
+int ff_sdp_parse(AVFormatContext *s, const char *content)
 {
+    RTSPState *rt = s->priv_data;
     const char *p;
     int letter;
     /* Some SDP lines, particularly for Realmedia or ASF RTSP streams,
@@ -539,14 +444,15 @@ static int sdp_parse(AVFormatContext *s, const char *content)
      * "rulebooks" describing their properties. Therefore, the SDP line
      * buffer is large.
      *
-     * The Vorbis FMTP line can be up to 16KB - see sdp_parse_fmtp. */
+     * The Vorbis FMTP line can be up to 16KB - see xiph_parse_sdp_line
+     * in rtpdec_xiph.c. */
     char buf[16384], *q;
     SDPParseState sdp_parse_state, *s1 = &sdp_parse_state;
 
     memset(s1, 0, sizeof(SDPParseState));
     p = content;
     for (;;) {
-        skip_spaces(&p);
+        p += strspn(p, SPACE_CHARS);
         letter = *p;
         if (letter == '\0')
             break;
@@ -569,8 +475,44 @@ static int sdp_parse(AVFormatContext *s, const char *content)
         if (*p == '\n')
             p++;
     }
+    rt->p = av_malloc(sizeof(struct pollfd)*2*(rt->nb_rtsp_streams+1));
+    if (!rt->p) return AVERROR(ENOMEM);
     return 0;
 }
+#endif /* CONFIG_RTPDEC */
+
+void ff_rtsp_undo_setup(AVFormatContext *s)
+{
+    RTSPState *rt = s->priv_data;
+    int i;
+
+    for (i = 0; i < rt->nb_rtsp_streams; i++) {
+        RTSPStream *rtsp_st = rt->rtsp_streams[i];
+        if (!rtsp_st)
+            continue;
+        if (rtsp_st->transport_priv) {
+            if (s->oformat) {
+                AVFormatContext *rtpctx = rtsp_st->transport_priv;
+                av_write_trailer(rtpctx);
+                if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
+                    uint8_t *ptr;
+                    avio_close_dyn_buf(rtpctx->pb, &ptr);
+                    av_free(ptr);
+                } else {
+                    avio_close(rtpctx->pb);
+                }
+                avformat_free_context(rtpctx);
+            } else if (rt->transport == RTSP_TRANSPORT_RDT && CONFIG_RTPDEC)
+                ff_rdt_parse_close(rtsp_st->transport_priv);
+            else if (CONFIG_RTPDEC)
+                rtp_parse_close(rtsp_st->transport_priv);
+        }
+        rtsp_st->transport_priv = NULL;
+        if (rtsp_st->rtp_handle)
+            ffurl_close(rtsp_st->rtp_handle);
+        rtsp_st->rtp_handle = NULL;
+    }
+}
 
 /* close and free RTSP streams */
 void ff_rtsp_close_streams(AVFormatContext *s)
@@ -579,34 +521,14 @@ void ff_rtsp_close_streams(AVFormatContext *s)
     int i;
     RTSPStream *rtsp_st;
 
+    ff_rtsp_undo_setup(s);
     for (i = 0; i < rt->nb_rtsp_streams; i++) {
         rtsp_st = rt->rtsp_streams[i];
         if (rtsp_st) {
-            if (rtsp_st->transport_priv) {
-                if (s->oformat) {
-                    AVFormatContext *rtpctx = rtsp_st->transport_priv;
-                    av_write_trailer(rtpctx);
-                    if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
-                        uint8_t *ptr;
-                        url_close_dyn_buf(rtpctx->pb, &ptr);
-                        av_free(ptr);
-                    } else {
-                        url_fclose(rtpctx->pb);
-                    }
-                    av_metadata_free(&rtpctx->streams[0]->metadata);
-                    av_metadata_free(&rtpctx->metadata);
-                    av_free(rtpctx->streams[0]);
-                    av_free(rtpctx);
-                } else if (rt->transport == RTSP_TRANSPORT_RDT)
-                    ff_rdt_parse_close(rtsp_st->transport_priv);
-                else
-                    rtp_parse_close(rtsp_st->transport_priv);
-            }
-            if (rtsp_st->rtp_handle)
-                url_close(rtsp_st->rtp_handle);
             if (rtsp_st->dynamic_handler && rtsp_st->dynamic_protocol_context)
                 rtsp_st->dynamic_handler->close(
                     rtsp_st->dynamic_protocol_context);
+            av_free(rtsp_st);
         }
     }
     av_free(rt->rtsp_streams);
@@ -614,65 +536,8 @@ void ff_rtsp_close_streams(AVFormatContext *s)
         av_close_input_stream (rt->asf_ctx);
         rt->asf_ctx = NULL;
     }
-}
-
-static void *rtsp_rtp_mux_open(AVFormatContext *s, AVStream *st,
-                               URLContext *handle)
-{
-    RTSPState *rt = s->priv_data;
-    AVFormatContext *rtpctx;
-    int ret;
-    AVOutputFormat *rtp_format = av_guess_format("rtp", NULL, NULL);
-
-    if (!rtp_format)
-        return NULL;
-
-    /* Allocate an AVFormatContext for each output stream */
-    rtpctx = avformat_alloc_context();
-    if (!rtpctx)
-        return NULL;
-
-    rtpctx->oformat = rtp_format;
-    if (!av_new_stream(rtpctx, 0)) {
-        av_free(rtpctx);
-        return NULL;
-    }
-    /* Copy the max delay setting; the rtp muxer reads this. */
-    rtpctx->max_delay = s->max_delay;
-    /* Copy other stream parameters. */
-    rtpctx->streams[0]->sample_aspect_ratio = st->sample_aspect_ratio;
-
-    /* Set the synchronized start time. */
-    rtpctx->start_time_realtime = rt->start_time;
-
-    /* Remove the local codec, link to the original codec
-     * context instead, to give the rtp muxer access to
-     * codec parameters. */
-    av_free(rtpctx->streams[0]->codec);
-    rtpctx->streams[0]->codec = st->codec;
-
-    if (handle) {
-        url_fdopen(&rtpctx->pb, handle);
-    } else
-        url_open_dyn_packet_buf(&rtpctx->pb, RTSP_TCP_MAX_PACKET_SIZE);
-    ret = av_write_header(rtpctx);
-
-    if (ret) {
-        if (handle) {
-            url_fclose(rtpctx->pb);
-        } else {
-            uint8_t *ptr;
-            url_close_dyn_buf(rtpctx->pb, &ptr);
-            av_free(ptr);
-        }
-        av_free(rtpctx->streams[0]);
-        av_free(rtpctx);
-        return NULL;
-    }
-
-    /* Copy the RTP AVStream timebase back to the original AVStream */
-    st->time_base = rtpctx->streams[0]->time_base;
-    return rtpctx;
+    av_free(rt->p);
+    av_free(rt->recvbuf);
 }
 
 static int rtsp_open_transport_ctx(AVFormatContext *s, RTSPStream *rtsp_st)
@@ -686,22 +551,25 @@ static int rtsp_open_transport_ctx(AVFormatContext *s, RTSPStream *rtsp_st)
     if (!st)
         s->ctx_flags |= AVFMTCTX_NOHEADER;
 
-    if (s->oformat) {
-        rtsp_st->transport_priv = rtsp_rtp_mux_open(s, st, rtsp_st->rtp_handle);
+    if (s->oformat && CONFIG_RTSP_MUXER) {
+        rtsp_st->transport_priv = ff_rtp_chain_mux_open(s, st,
+                                      rtsp_st->rtp_handle,
+                                      RTSP_TCP_MAX_PACKET_SIZE);
         /* Ownership of rtp_handle is passed to the rtp mux context */
         rtsp_st->rtp_handle = NULL;
-    } else if (rt->transport == RTSP_TRANSPORT_RDT)
+    } else if (rt->transport == RTSP_TRANSPORT_RDT && CONFIG_RTPDEC)
         rtsp_st->transport_priv = ff_rdt_parse_open(s, st->index,
                                             rtsp_st->dynamic_protocol_context,
                                             rtsp_st->dynamic_handler);
-    else
+    else if (CONFIG_RTPDEC)
         rtsp_st->transport_priv = rtp_parse_open(s, st, rtsp_st->rtp_handle,
                                          rtsp_st->sdp_payload_type,
-                                         &rtsp_st->rtp_payload_data);
+            (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP || !s->max_delay)
+            ? 0 : RTP_REORDER_QUEUE_DEFAULT_SIZE);
 
     if (!rtsp_st->transport_priv) {
          return AVERROR(ENOMEM);
-    } else if (rt->transport != RTSP_TRANSPORT_RDT) {
+    } else if (rt->transport != RTSP_TRANSPORT_RDT && CONFIG_RTPDEC) {
         if (rtsp_st->dynamic_handler) {
             rtp_parse_set_dynamic_protocol(rtsp_st->transport_priv,
                                            rtsp_st->dynamic_protocol_context,
@@ -713,20 +581,13 @@ static int rtsp_open_transport_ctx(AVFormatContext *s, RTSPStream *rtsp_st)
 }
 
 #if CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER
-static int rtsp_probe(AVProbeData *p)
-{
-    if (av_strstart(p->filename, "rtsp:", NULL))
-        return AVPROBE_SCORE_MAX;
-    return 0;
-}
-
 static void rtsp_parse_range(int *min_ptr, int *max_ptr, const char **pp)
 {
     const char *p;
     int v;
 
     p = *pp;
-    skip_spaces(&p);
+    p += strspn(p, SPACE_CHARS);
     v = strtol(p, (char **)&p, 10);
     if (*p == '-') {
         p++;
@@ -753,7 +614,7 @@ static void rtsp_parse_transport(RTSPMessageHeader *reply, const char *p)
     reply->nb_transports = 0;
 
     for (;;) {
-        skip_spaces(&p);
+        p += strspn(p, SPACE_CHARS);
         if (*p == '\0')
             break;
 
@@ -819,15 +680,19 @@ static void rtsp_parse_transport(RTSPMessageHeader *reply, const char *p)
                     th->ttl = strtol(p, (char **)&p, 10);
                 }
             } else if (!strcmp(parameter, "destination")) {
-                struct in_addr ipaddr;
-
                 if (*p == '=') {
                     p++;
                     get_word_sep(buf, sizeof(buf), ";,", &p);
-                    if (ff_inet_aton(buf, &ipaddr))
-                        th->destination = ntohl(ipaddr.s_addr);
+                    get_sockaddr(buf, &th->destination);
+                }
+            } else if (!strcmp(parameter, "source")) {
+                if (*p == '=') {
+                    p++;
+                    get_word_sep(buf, sizeof(buf), ";,", &p);
+                    av_strlcpy(th->source, buf, sizeof(th->source));
                 }
             }
+
             while (*p != ';' && *p != '\0' && *p != ',')
                 p++;
             if (*p == ';')
@@ -840,8 +705,63 @@ static void rtsp_parse_transport(RTSPMessageHeader *reply, const char *p)
     }
 }
 
+static void handle_rtp_info(RTSPState *rt, const char *url,
+                            uint32_t seq, uint32_t rtptime)
+{
+    int i;
+    if (!rtptime || !url[0])
+        return;
+    if (rt->transport != RTSP_TRANSPORT_RTP)
+        return;
+    for (i = 0; i < rt->nb_rtsp_streams; i++) {
+        RTSPStream *rtsp_st = rt->rtsp_streams[i];
+        RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
+        if (!rtpctx)
+            continue;
+        if (!strcmp(rtsp_st->control_url, url)) {
+            rtpctx->base_timestamp = rtptime;
+            break;
+        }
+    }
+}
+
+static void rtsp_parse_rtp_info(RTSPState *rt, const char *p)
+{
+    int read = 0;
+    char key[20], value[1024], url[1024] = "";
+    uint32_t seq = 0, rtptime = 0;
+
+    for (;;) {
+        p += strspn(p, SPACE_CHARS);
+        if (!*p)
+            break;
+        get_word_sep(key, sizeof(key), "=", &p);
+        if (*p != '=')
+            break;
+        p++;
+        get_word_sep(value, sizeof(value), ";, ", &p);
+        read++;
+        if (!strcmp(key, "url"))
+            av_strlcpy(url, value, sizeof(url));
+        else if (!strcmp(key, "seq"))
+            seq = strtol(value, NULL, 10);
+        else if (!strcmp(key, "rtptime"))
+            rtptime = strtol(value, NULL, 10);
+        if (*p == ',') {
+            handle_rtp_info(rt, url, seq, rtptime);
+            url[0] = '\0';
+            seq = rtptime = 0;
+            read = 0;
+        }
+        if (*p)
+            p++;
+    }
+    if (read > 0)
+        handle_rtp_info(rt, url, seq, rtptime);
+}
+
 void ff_rtsp_parse_line(RTSPMessageHeader *reply, const char *buf,
-                        HTTPAuthState *auth_state)
+                        RTSPState *rt, const char *method)
 {
     const char *p;
 
@@ -863,23 +783,31 @@ void ff_rtsp_parse_line(RTSPMessageHeader *reply, const char *buf,
     } else if (av_stristart(p, "Range:", &p)) {
         rtsp_parse_range_npt(p, &reply->range_start, &reply->range_end);
     } else if (av_stristart(p, "RealChallenge1:", &p)) {
-        skip_spaces(&p);
+        p += strspn(p, SPACE_CHARS);
         av_strlcpy(reply->real_challenge, p, sizeof(reply->real_challenge));
     } else if (av_stristart(p, "Server:", &p)) {
-        skip_spaces(&p);
+        p += strspn(p, SPACE_CHARS);
         av_strlcpy(reply->server, p, sizeof(reply->server));
     } else if (av_stristart(p, "Notice:", &p) ||
                av_stristart(p, "X-Notice:", &p)) {
         reply->notice = strtol(p, NULL, 10);
     } else if (av_stristart(p, "Location:", &p)) {
-        skip_spaces(&p);
+        p += strspn(p, SPACE_CHARS);
         av_strlcpy(reply->location, p , sizeof(reply->location));
-    } else if (av_stristart(p, "WWW-Authenticate:", &p) && auth_state) {
-        skip_spaces(&p);
-        ff_http_auth_handle_header(auth_state, "WWW-Authenticate", p);
-    } else if (av_stristart(p, "Authentication-Info:", &p) && auth_state) {
-        skip_spaces(&p);
-        ff_http_auth_handle_header(auth_state, "Authentication-Info", p);
+    } else if (av_stristart(p, "WWW-Authenticate:", &p) && rt) {
+        p += strspn(p, SPACE_CHARS);
+        ff_http_auth_handle_header(&rt->auth_state, "WWW-Authenticate", p);
+    } else if (av_stristart(p, "Authentication-Info:", &p) && rt) {
+        p += strspn(p, SPACE_CHARS);
+        ff_http_auth_handle_header(&rt->auth_state, "Authentication-Info", p);
+    } else if (av_stristart(p, "Content-Base:", &p) && rt) {
+        p += strspn(p, SPACE_CHARS);
+        if (method && !strcmp(method, "DESCRIBE"))
+            av_strlcpy(rt->control_uri, p , sizeof(rt->control_uri));
+    } else if (av_stristart(p, "RTP-Info:", &p) && rt) {
+        p += strspn(p, SPACE_CHARS);
+        if (method && !strcmp(method, "PLAY"))
+            rtsp_parse_rtp_info(rt, p);
     }
 }
 
@@ -890,19 +818,19 @@ void ff_rtsp_skip_packet(AVFormatContext *s)
     int ret, len, len1;
     uint8_t buf[1024];
 
-    ret = url_read_complete(rt->rtsp_hd, buf, 3);
+    ret = ffurl_read_complete(rt->rtsp_hd, buf, 3);
     if (ret != 3)
         return;
     len = AV_RB16(buf + 1);
 
-    dprintf(s, "skipping RTP packet len=%d\n", len);
+    av_dlog(s, "skipping RTP packet len=%d\n", len);
 
     /* skip payload */
     while (len > 0) {
         len1 = len;
         if (len1 > sizeof(buf))
             len1 = sizeof(buf);
-        ret = url_read_complete(rt->rtsp_hd, buf, len1);
+        ret = ffurl_read_complete(rt->rtsp_hd, buf, len1);
         if (ret != len1)
             return;
         len -= len1;
@@ -911,7 +839,7 @@ void ff_rtsp_skip_packet(AVFormatContext *s)
 
 int ff_rtsp_read_reply(AVFormatContext *s, RTSPMessageHeader *reply,
                        unsigned char **content_ptr,
-                       int return_on_interleaved_data)
+                       int return_on_interleaved_data, const char *method)
 {
     RTSPState *rt = s->priv_data;
     char buf[4096], buf1[1024], *q;
@@ -927,12 +855,12 @@ int ff_rtsp_read_reply(AVFormatContext *s, RTSPMessageHeader *reply,
     for (;;) {
         q = buf;
         for (;;) {
-            ret = url_read_complete(rt->rtsp_hd, &ch, 1);
+            ret = ffurl_read_complete(rt->rtsp_hd, &ch, 1);
 #ifdef DEBUG_RTP_TCP
-            dprintf(s, "ret=%d c=%02x [%c]\n", ret, ch, ch);
+            av_dlog(s, "ret=%d c=%02x [%c]\n", ret, ch, ch);
 #endif
             if (ret != 1)
-                return -1;
+                return AVERROR_EOF;
             if (ch == '\n')
                 break;
             if (ch == '$') {
@@ -948,7 +876,7 @@ int ff_rtsp_read_reply(AVFormatContext *s, RTSPMessageHeader *reply,
         }
         *q = '\0';
 
-        dprintf(s, "line='%s'\n", buf);
+        av_dlog(s, "line='%s'\n", buf);
 
         /* test if last line */
         if (buf[0] == '\0')
@@ -959,8 +887,9 @@ int ff_rtsp_read_reply(AVFormatContext *s, RTSPMessageHeader *reply,
             get_word(buf1, sizeof(buf1), &p);
             get_word(buf1, sizeof(buf1), &p);
             reply->status_code = atoi(buf1);
+            av_strlcpy(reply->reason, p, sizeof(reply->reason));
         } else {
-            ff_rtsp_parse_line(reply, p, &rt->auth_state);
+            ff_rtsp_parse_line(reply, p, rt, method);
             av_strlcat(rt->last_reply, p,    sizeof(rt->last_reply));
             av_strlcat(rt->last_reply, "\n", sizeof(rt->last_reply));
         }
@@ -974,7 +903,7 @@ int ff_rtsp_read_reply(AVFormatContext *s, RTSPMessageHeader *reply,
     if (content_length > 0) {
         /* leave some room for a trailing '\0' (useful for simple parsing) */
         content = av_malloc(content_length + 1);
-        (void)url_read_complete(rt->rtsp_hd, content, content_length);
+        ffurl_read_complete(rt->rtsp_hd, content, content_length);
         content[content_length] = '\0';
     }
     if (content_ptr)
@@ -1001,15 +930,31 @@ int ff_rtsp_read_reply(AVFormatContext *s, RTSPMessageHeader *reply,
     return 0;
 }
 
-void ff_rtsp_send_cmd_with_content_async(AVFormatContext *s,
-                                         const char *method, const char *url,
-                                         const char *headers,
-                                         const unsigned char *send_content,
-                                         int send_content_length)
+/**
+ * Send a command to the RTSP server without waiting for the reply.
+ *
+ * @param s RTSP (de)muxer context
+ * @param method the method for the request
+ * @param url the target url for the request
+ * @param headers extra header lines to include in the request
+ * @param send_content if non-null, the data to send as request body content
+ * @param send_content_length the length of the send_content data, or 0 if
+ *                            send_content is null
+ *
+ * @return zero if success, nonzero otherwise
+ */
+static int ff_rtsp_send_cmd_with_content_async(AVFormatContext *s,
+                                               const char *method, const char *url,
+                                               const char *headers,
+                                               const unsigned char *send_content,
+                                               int send_content_length)
 {
     RTSPState *rt = s->priv_data;
-    char buf[4096];
+    char buf[4096], *out_buf;
+    char base64buf[AV_BASE64_SIZE(sizeof(buf))];
 
+    /* Add in RTSP headers */
+    out_buf = buf;
     rt->seq++;
     snprintf(buf, sizeof(buf), "%s %s RTSP/1.0\r\n", method, url);
     if (headers)
@@ -1030,55 +975,83 @@ void ff_rtsp_send_cmd_with_content_async(AVFormatContext *s,
         av_strlcatf(buf, sizeof(buf), "Content-Length: %d\r\n", send_content_length);
     av_strlcat(buf, "\r\n", sizeof(buf));
 
-    dprintf(s, "Sending:\n%s--\n", buf);
+    /* base64 encode rtsp if tunneling */
+    if (rt->control_transport == RTSP_MODE_TUNNEL) {
+        av_base64_encode(base64buf, sizeof(base64buf), buf, strlen(buf));
+        out_buf = base64buf;
+    }
 
-    url_write(rt->rtsp_hd, buf, strlen(buf));
-    if (send_content_length > 0 && send_content)
-        url_write(rt->rtsp_hd, send_content, send_content_length);
+    av_dlog(s, "Sending:\n%s--\n", buf);
+
+    ffurl_write(rt->rtsp_hd_out, out_buf, strlen(out_buf));
+    if (send_content_length > 0 && send_content) {
+        if (rt->control_transport == RTSP_MODE_TUNNEL) {
+            av_log(s, AV_LOG_ERROR, "tunneling of RTSP requests "
+                                    "with content data not supported\n");
+            return AVERROR_PATCHWELCOME;
+        }
+        ffurl_write(rt->rtsp_hd_out, send_content, send_content_length);
+    }
     rt->last_cmd_time = av_gettime();
+
+    return 0;
 }
 
-void ff_rtsp_send_cmd_async(AVFormatContext *s, const char *method,
-                            const char *url, const char *headers)
+int ff_rtsp_send_cmd_async(AVFormatContext *s, const char *method,
+                           const char *url, const char *headers)
 {
-    ff_rtsp_send_cmd_with_content_async(s, method, url, headers, NULL, 0);
+    return ff_rtsp_send_cmd_with_content_async(s, method, url, headers, NULL, 0);
 }
 
-void ff_rtsp_send_cmd(AVFormatContext *s, const char *method, const char *url,
-                      const char *headers, RTSPMessageHeader *reply,
-                      unsigned char **content_ptr)
+int ff_rtsp_send_cmd(AVFormatContext *s, const char *method, const char *url,
+                     const char *headers, RTSPMessageHeader *reply,
+                     unsigned char **content_ptr)
 {
-    ff_rtsp_send_cmd_with_content(s, method, url, headers, reply,
-                                  content_ptr, NULL, 0);
+    return ff_rtsp_send_cmd_with_content(s, method, url, headers, reply,
+                                         content_ptr, NULL, 0);
 }
 
-void ff_rtsp_send_cmd_with_content(AVFormatContext *s,
-                                   const char *method, const char *url,
-                                   const char *header,
-                                   RTSPMessageHeader *reply,
-                                   unsigned char **content_ptr,
-                                   const unsigned char *send_content,
-                                   int send_content_length)
+int ff_rtsp_send_cmd_with_content(AVFormatContext *s,
+                                  const char *method, const char *url,
+                                  const char *header,
+                                  RTSPMessageHeader *reply,
+                                  unsigned char **content_ptr,
+                                  const unsigned char *send_content,
+                                  int send_content_length)
 {
     RTSPState *rt = s->priv_data;
     HTTPAuthType cur_auth_type;
+    int ret;
 
 retry:
     cur_auth_type = rt->auth_state.auth_type;
-    ff_rtsp_send_cmd_with_content_async(s, method, url, header,
-                                        send_content, send_content_length);
+    if ((ret = ff_rtsp_send_cmd_with_content_async(s, method, url, header,
+                                                   send_content,
+                                                   send_content_length)))
+        return ret;
 
-    ff_rtsp_read_reply(s, reply, content_ptr, 0);
+    if ((ret = ff_rtsp_read_reply(s, reply, content_ptr, 0, method) ) < 0)
+        return ret;
 
     if (reply->status_code == 401 && cur_auth_type == HTTP_AUTH_NONE &&
         rt->auth_state.auth_type != HTTP_AUTH_NONE)
         goto retry;
+
+    if (reply->status_code > 400){
+        av_log(s, AV_LOG_ERROR, "method %s failed: %d%s\n",
+               method,
+               reply->status_code,
+               reply->reason);
+        av_log(s, AV_LOG_DEBUG, "%s\n", rt->last_reply);
+    }
+
+    return 0;
 }
 
 /**
  * @return 0 on success, <0 on error, 1 if protocol is unavailable.
  */
-static int make_setup_request(AVFormatContext *s, const char *host, int port,
+int ff_rtsp_make_setup_request(AVFormatContext *s, const char *host, int port,
                               int lower_transport, const char *real_challenge)
 {
     RTSPState *rt = s->priv_data;
@@ -1143,21 +1116,25 @@ static int make_setup_request(AVFormatContext *s, const char *host, int port,
                                 "?localport=%d", j);
                     /* we will use two ports per rtp stream (rtp and rtcp) */
                     j += 2;
-                    if (url_open(&rtsp_st->rtp_handle, buf, URL_RDWR) == 0)
+                    if (ffurl_open(&rtsp_st->rtp_handle, buf, AVIO_RDWR) == 0)
                         goto rtp_opened;
                 }
             }
 
 #if 0
             /* then try on any port */
-            if (url_open(&rtsp_st->rtp_handle, "rtp://", URL_RDONLY) < 0) {
+            if (ffurl_open(&rtsp_st->rtp_handle, "rtp://", AVIO_RDONLY) < 0) {
                 err = AVERROR_INVALIDDATA;
                 goto fail;
             }
+#else
+            av_log(s, AV_LOG_ERROR, "Unable to open an input RTP port\n");
+            err = AVERROR(EIO);
+            goto fail;
 #endif
 
         rtp_opened:
-            port = rtp_get_local_port(rtsp_st->rtp_handle);
+            port = rtp_get_local_rtp_port(rtsp_st->rtp_handle);
         have_port:
             snprintf(transport, sizeof(transport) - 1,
                      "%s/UDP;", trans_pref);
@@ -1181,7 +1158,7 @@ static int make_setup_request(AVFormatContext *s, const char *host, int port,
                 continue;
             snprintf(transport, sizeof(transport) - 1,
                      "%s/TCP;", trans_pref);
-            if (rt->server_type == RTSP_SERVER_WMS)
+            if (rt->transport != RTSP_TRANSPORT_RDT)
                 av_strlcat(transport, "unicast;", sizeof(transport));
             av_strlcatf(transport, sizeof(transport),
                         "interleaved=%d-%d",
@@ -1201,7 +1178,7 @@ static int make_setup_request(AVFormatContext *s, const char *host, int port,
         snprintf(cmd, sizeof(cmd),
                  "Transport: %s\r\n",
                  transport);
-        if (i == 0 && rt->server_type == RTSP_SERVER_REAL) {
+        if (i == 0 && rt->server_type == RTSP_SERVER_REAL && CONFIG_RTPDEC) {
             char real_res[41], real_csum[9];
             ff_rdt_calc_response_and_checksum(real_res, real_csum,
                                               real_challenge);
@@ -1232,11 +1209,12 @@ static int make_setup_request(AVFormatContext *s, const char *host, int port,
             rt->transport = reply->transports[0].transport;
         }
 
-        /* close RTP connection if not choosen */
-        if (reply->transports[0].lower_transport != RTSP_LOWER_TRANSPORT_UDP &&
-            (lower_transport == RTSP_LOWER_TRANSPORT_UDP)) {
-            url_close(rtsp_st->rtp_handle);
-            rtsp_st->rtp_handle = NULL;
+        /* Fail if the server responded with another lower transport mode
+         * than what we requested. */
+        if (reply->transports[0].lower_transport != lower_transport) {
+            av_log(s, AV_LOG_ERROR, "Nonmatching transport in server reply\n");
+            err = AVERROR_INVALIDDATA;
+            goto fail;
         }
 
         switch(reply->transports[0].lower_transport) {
@@ -1246,11 +1224,19 @@ static int make_setup_request(AVFormatContext *s, const char *host, int port,
             break;
 
         case RTSP_LOWER_TRANSPORT_UDP: {
-            char url[1024];
-
-            /* XXX: also use address if specified */
-            ff_url_join(url, sizeof(url), "rtp", NULL, host,
-                        reply->transports[0].server_port_min, NULL);
+            char url[1024], options[30] = "";
+
+            if (rt->filter_source)
+                av_strlcpy(options, "?connect=1", sizeof(options));
+            /* Use source address if specified */
+            if (reply->transports[0].source[0]) {
+                ff_url_join(url, sizeof(url), "rtp", NULL,
+                            reply->transports[0].source,
+                            reply->transports[0].server_port_min, options);
+            } else {
+                ff_url_join(url, sizeof(url), "rtp", NULL, host,
+                            reply->transports[0].server_port_min, options);
+            }
             if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) &&
                 rtp_set_remote_url(rtsp_st->rtp_handle, url) < 0) {
                 err = AVERROR_INVALIDDATA;
@@ -1260,27 +1246,30 @@ static int make_setup_request(AVFormatContext *s, const char *host, int port,
              * potential NAT router by sending dummy packets.
              * RTP/RTCP dummy packets are used for RDT, too.
              */
-            if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) && s->iformat)
+            if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) && s->iformat &&
+                CONFIG_RTPDEC)
                 rtp_send_punch_packets(rtsp_st->rtp_handle);
             break;
         }
         case RTSP_LOWER_TRANSPORT_UDP_MULTICAST: {
-            char url[1024];
-            struct in_addr in;
+            char url[1024], namebuf[50];
+            struct sockaddr_storage addr;
             int port, ttl;
 
-            if (reply->transports[0].destination) {
-                in.s_addr = htonl(reply->transports[0].destination);
+            if (reply->transports[0].destination.ss_family) {
+                addr      = reply->transports[0].destination;
                 port      = reply->transports[0].port_min;
                 ttl       = reply->transports[0].ttl;
             } else {
-                in        = rtsp_st->sdp_ip;
+                addr      = rtsp_st->sdp_ip;
                 port      = rtsp_st->sdp_port;
                 ttl       = rtsp_st->sdp_ttl;
             }
-            ff_url_join(url, sizeof(url), "rtp", NULL, inet_ntoa(in),
+            getnameinfo((struct sockaddr*) &addr, sizeof(addr),
+                        namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
+            ff_url_join(url, sizeof(url), "rtp", NULL, namebuf,
                         port, "?ttl=%d", ttl);
-            if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
+            if (ffurl_open(&rtsp_st->rtp_handle, url, AVIO_RDWR) < 0) {
                 err = AVERROR_INVALIDDATA;
                 goto fail;
             }
@@ -1301,157 +1290,16 @@ static int make_setup_request(AVFormatContext *s, const char *host, int port,
     return 0;
 
 fail:
-    for (i = 0; i < rt->nb_rtsp_streams; i++) {
-        if (rt->rtsp_streams[i]->rtp_handle) {
-            url_close(rt->rtsp_streams[i]->rtp_handle);
-            rt->rtsp_streams[i]->rtp_handle = NULL;
-        }
-    }
+    ff_rtsp_undo_setup(s);
     return err;
 }
 
-static int rtsp_read_play(AVFormatContext *s)
-{
-    RTSPState *rt = s->priv_data;
-    RTSPMessageHeader reply1, *reply = &reply1;
-    int i;
-    char cmd[1024];
-
-    av_log(s, AV_LOG_DEBUG, "hello state=%d\n", rt->state);
-
-    if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
-        if (rt->state == RTSP_STATE_PAUSED) {
-            cmd[0] = 0;
-        } else {
-            snprintf(cmd, sizeof(cmd),
-                     "Range: npt=%0.3f-\r\n",
-                     (double)rt->seek_timestamp / AV_TIME_BASE);
-        }
-        ff_rtsp_send_cmd(s, "PLAY", rt->control_uri, cmd, reply, NULL);
-        if (reply->status_code != RTSP_STATUS_OK) {
-            return -1;
-        }
-        if (reply->range_start != AV_NOPTS_VALUE &&
-            rt->transport == RTSP_TRANSPORT_RTP) {
-            for (i = 0; i < rt->nb_rtsp_streams; i++) {
-                RTSPStream *rtsp_st = rt->rtsp_streams[i];
-                RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
-                AVStream *st = NULL;
-                if (!rtpctx)
-                    continue;
-                if (rtsp_st->stream_index >= 0)
-                    st = s->streams[rtsp_st->stream_index];
-                rtpctx->last_rtcp_ntp_time  = AV_NOPTS_VALUE;
-                rtpctx->first_rtcp_ntp_time = AV_NOPTS_VALUE;
-                if (st)
-                    rtpctx->range_start_offset = av_rescale_q(reply->range_start,
-                                                              AV_TIME_BASE_Q,
-                                                              st->time_base);
-            }
-        }
-    }
-    rt->state = RTSP_STATE_STREAMING;
-    return 0;
-}
-
-static int rtsp_setup_input_streams(AVFormatContext *s, RTSPMessageHeader *reply)
-{
-    RTSPState *rt = s->priv_data;
-    char cmd[1024];
-    unsigned char *content = NULL;
-    int ret;
-
-    /* describe the stream */
-    snprintf(cmd, sizeof(cmd),
-             "Accept: application/sdp\r\n");
-    if (rt->server_type == RTSP_SERVER_REAL) {
-        /**
-         * The Require: attribute is needed for proper streaming from
-         * Realmedia servers.
-         */
-        av_strlcat(cmd,
-                   "Require: com.real.retain-entity-for-setup\r\n",
-                   sizeof(cmd));
-    }
-    ff_rtsp_send_cmd(s, "DESCRIBE", rt->control_uri, cmd, reply, &content);
-    if (!content)
-        return AVERROR_INVALIDDATA;
-    if (reply->status_code != RTSP_STATUS_OK) {
-        av_freep(&content);
-        return AVERROR_INVALIDDATA;
-    }
-
-    /* now we got the SDP description, we parse it */
-    ret = sdp_parse(s, (const char *)content);
-    av_freep(&content);
-    if (ret < 0)
-        return AVERROR_INVALIDDATA;
-
-    return 0;
-}
-
-static int rtsp_setup_output_streams(AVFormatContext *s, const char *addr)
+void ff_rtsp_close_connections(AVFormatContext *s)
 {
     RTSPState *rt = s->priv_data;
-    RTSPMessageHeader reply1, *reply = &reply1;
-    int i;
-    char *sdp;
-    AVFormatContext sdp_ctx, *ctx_array[1];
-
-    rt->start_time = av_gettime();
-
-    /* Announce the stream */
-    sdp = av_mallocz(8192);
-    if (sdp == NULL)
-        return AVERROR(ENOMEM);
-    /* We create the SDP based on the RTSP AVFormatContext where we
-     * aren't allowed to change the filename field. (We create the SDP
-     * based on the RTSP context since the contexts for the RTP streams
-     * don't exist yet.) In order to specify a custom URL with the actual
-     * peer IP instead of the originally specified hostname, we create
-     * a temporary copy of the AVFormatContext, where the custom URL is set.
-     *
-     * FIXME: Create the SDP without copying the AVFormatContext.
-     * This either requires setting up the RTP stream AVFormatContexts
-     * already here (complicating things immensely) or getting a more
-     * flexible SDP creation interface.
-     */
-    sdp_ctx = *s;
-    ff_url_join(sdp_ctx.filename, sizeof(sdp_ctx.filename),
-                "rtsp", NULL, addr, -1, NULL);
-    ctx_array[0] = &sdp_ctx;
-    if (avf_sdp_create(ctx_array, 1, sdp, 8192)) {
-        av_free(sdp);
-        return AVERROR_INVALIDDATA;
-    }
-    av_log(s, AV_LOG_INFO, "SDP:\n%s\n", sdp);
-    ff_rtsp_send_cmd_with_content(s, "ANNOUNCE", rt->control_uri,
-                                  "Content-Type: application/sdp\r\n",
-                                  reply, NULL, sdp, strlen(sdp));
-    av_free(sdp);
-    if (reply->status_code != RTSP_STATUS_OK)
-        return AVERROR_INVALIDDATA;
-
-    /* Set up the RTSPStreams for each AVStream */
-    for (i = 0; i < s->nb_streams; i++) {
-        RTSPStream *rtsp_st;
-        AVStream *st = s->streams[i];
-
-        rtsp_st = av_mallocz(sizeof(RTSPStream));
-        if (!rtsp_st)
-            return AVERROR(ENOMEM);
-        dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
-
-        st->priv_data = rtsp_st;
-        rtsp_st->stream_index = i;
-
-        av_strlcpy(rtsp_st->control_url, rt->control_uri, sizeof(rtsp_st->control_url));
-        /* Note, this must match the relative uri set in the sdp content */
-        av_strlcatf(rtsp_st->control_url, sizeof(rtsp_st->control_url),
-                    "/streamid=%d", i);
-    }
-
-    return 0;
+    if (rt->rtsp_hd_out != rt->rtsp_hd) ffurl_close(rt->rtsp_hd_out);
+    ffurl_close(rt->rtsp_hd);
+    rt->rtsp_hd = rt->rtsp_hd_out = NULL;
 }
 
 int ff_rtsp_connect(AVFormatContext *s)
@@ -1459,19 +1307,19 @@ int ff_rtsp_connect(AVFormatContext *s)
     RTSPState *rt = s->priv_data;
     char host[1024], path[1024], tcpname[1024], cmd[2048], auth[128];
     char *option_list, *option, *filename;
-    URLContext *rtsp_hd;
     int port, err, tcp_fd;
-    RTSPMessageHeader reply1 = {}, *reply = &reply1;
+    RTSPMessageHeader reply1 = {0}, *reply = &reply1;
     int lower_transport_mask = 0;
-    char real_challenge[64];
+    char real_challenge[64] = "";
     struct sockaddr_storage peer;
     socklen_t peer_len = sizeof(peer);
 
     if (!ff_network_init())
         return AVERROR(EIO);
 redirect:
+    rt->control_transport = RTSP_MODE_PLAIN;
     /* extract hostname and port */
-    ff_url_split(NULL, 0, auth, sizeof(auth),
+    av_url_split(NULL, 0, auth, sizeof(auth),
                  host, sizeof(host), &port, path, sizeof(path), s->filename);
     if (*auth) {
         av_strlcpy(rt->auth, auth, sizeof(rt->auth));
@@ -1499,6 +1347,11 @@ redirect:
                 lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
             } else if (!strcmp(option, "tcp")) {
                 lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_TCP);
+            } else if(!strcmp(option, "http")) {
+                lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_TCP);
+                rt->control_transport = RTSP_MODE_TUNNEL;
+            } else if (!strcmp(option, "filter_src")) {
+                rt->filter_source = 1;
             } else {
                 /* Write options back into the buffer, using memmove instead
                  * of strcpy since the strings may overlap. */
@@ -1518,7 +1371,7 @@ redirect:
         /* Only UDP or TCP - UDP multicast isn't supported. */
         lower_transport_mask &= (1 << RTSP_LOWER_TRANSPORT_UDP) |
                                 (1 << RTSP_LOWER_TRANSPORT_TCP);
-        if (!lower_transport_mask) {
+        if (!lower_transport_mask || rt->control_transport == RTSP_MODE_TUNNEL) {
             av_log(s, AV_LOG_ERROR, "Unsupported lower transport method, "
                                     "only UDP and TCP are supported for output.\n");
             err = AVERROR(EINVAL);
@@ -1532,16 +1385,90 @@ redirect:
     ff_url_join(rt->control_uri, sizeof(rt->control_uri), "rtsp", NULL,
                 host, port, "%s", path);
 
-    /* open the tcp connexion */
-    ff_url_join(tcpname, sizeof(tcpname), "tcp", NULL, host, port, NULL);
-    if (url_open(&rtsp_hd, tcpname, URL_RDWR) < 0) {
-        err = AVERROR(EIO);
-        goto fail;
+    if (rt->control_transport == RTSP_MODE_TUNNEL) {
+        /* set up initial handshake for tunneling */
+        char httpname[1024];
+        char sessioncookie[17];
+        char headers[1024];
+
+        ff_url_join(httpname, sizeof(httpname), "http", auth, host, port, "%s", path);
+        snprintf(sessioncookie, sizeof(sessioncookie), "%08x%08x",
+                 av_get_random_seed(), av_get_random_seed());
+
+        /* GET requests */
+        if (ffurl_alloc(&rt->rtsp_hd, httpname, AVIO_RDONLY) < 0) {
+            err = AVERROR(EIO);
+            goto fail;
+        }
+
+        /* generate GET headers */
+        snprintf(headers, sizeof(headers),
+                 "x-sessioncookie: %s\r\n"
+                 "Accept: application/x-rtsp-tunnelled\r\n"
+                 "Pragma: no-cache\r\n"
+                 "Cache-Control: no-cache\r\n",
+                 sessioncookie);
+        ff_http_set_headers(rt->rtsp_hd, headers);
+
+        /* complete the connection */
+        if (ffurl_connect(rt->rtsp_hd)) {
+            err = AVERROR(EIO);
+            goto fail;
+        }
+
+        /* POST requests */
+        if (ffurl_alloc(&rt->rtsp_hd_out, httpname, AVIO_WRONLY) < 0 ) {
+            err = AVERROR(EIO);
+            goto fail;
+        }
+
+        /* generate POST headers */
+        snprintf(headers, sizeof(headers),
+                 "x-sessioncookie: %s\r\n"
+                 "Content-Type: application/x-rtsp-tunnelled\r\n"
+                 "Pragma: no-cache\r\n"
+                 "Cache-Control: no-cache\r\n"
+                 "Content-Length: 32767\r\n"
+                 "Expires: Sun, 9 Jan 1972 00:00:00 GMT\r\n",
+                 sessioncookie);
+        ff_http_set_headers(rt->rtsp_hd_out, headers);
+        ff_http_set_chunked_transfer_encoding(rt->rtsp_hd_out, 0);
+
+        /* Initialize the authentication state for the POST session. The HTTP
+         * protocol implementation doesn't properly handle multi-pass
+         * authentication for POST requests, since it would require one of
+         * the following:
+         * - implementing Expect: 100-continue, which many HTTP servers
+         *   don't support anyway, even less the RTSP servers that do HTTP
+         *   tunneling
+         * - sending the whole POST data until getting a 401 reply specifying
+         *   what authentication method to use, then resending all that data
+         * - waiting for potential 401 replies directly after sending the
+         *   POST header (waiting for some unspecified time)
+         * Therefore, we copy the full auth state, which works for both basic
+         * and digest. (For digest, we would have to synchronize the nonce
+         * count variable between the two sessions, if we'd do more requests
+         * with the original session, though.)
+         */
+        ff_http_init_auth_state(rt->rtsp_hd_out, rt->rtsp_hd);
+
+        /* complete the connection */
+        if (ffurl_connect(rt->rtsp_hd_out)) {
+            err = AVERROR(EIO);
+            goto fail;
+        }
+    } else {
+        /* open the tcp connection */
+        ff_url_join(tcpname, sizeof(tcpname), "tcp", NULL, host, port, NULL);
+        if (ffurl_open(&rt->rtsp_hd, tcpname, AVIO_RDWR) < 0) {
+            err = AVERROR(EIO);
+            goto fail;
+        }
+        rt->rtsp_hd_out = rt->rtsp_hd;
     }
-    rt->rtsp_hd = rtsp_hd;
     rt->seq = 0;
 
-    tcp_fd = url_get_file_handle(rtsp_hd);
+    tcp_fd = ffurl_get_file_handle(rt->rtsp_hd);
     if (!getpeername(tcp_fd, (struct sockaddr*) &peer, &peer_len)) {
         getnameinfo((struct sockaddr*) &peer, peer_len, host, sizeof(host),
                     NULL, 0, NI_NUMERICHOST);
@@ -1584,10 +1511,10 @@ redirect:
         break;
     }
 
-    if (s->iformat)
-        err = rtsp_setup_input_streams(s, reply);
-    else
-        err = rtsp_setup_output_streams(s, host);
+    if (s->iformat && CONFIG_RTSP_DEMUXER)
+        err = ff_rtsp_setup_input_streams(s, reply);
+    else if (CONFIG_RTSP_MUXER)
+        err = ff_rtsp_setup_output_streams(s, host);
     if (err)
         goto fail;
 
@@ -1595,24 +1522,26 @@ redirect:
         int lower_transport = ff_log2_tab[lower_transport_mask &
                                   ~(lower_transport_mask - 1)];
 
-        err = make_setup_request(s, host, port, lower_transport,
+        err = ff_rtsp_make_setup_request(s, host, port, lower_transport,
                                  rt->server_type == RTSP_SERVER_REAL ?
                                      real_challenge : NULL);
         if (err < 0)
             goto fail;
         lower_transport_mask &= ~(1 << lower_transport);
         if (lower_transport_mask == 0 && err == 1) {
-            err = FF_NETERROR(EPROTONOSUPPORT);
+            err = AVERROR(EPROTONOSUPPORT);
             goto fail;
         }
     } while (err);
 
+    rt->lower_transport_mask = lower_transport_mask;
+    av_strlcpy(rt->real_challenge, real_challenge, sizeof(rt->real_challenge));
     rt->state = RTSP_STATE_IDLE;
     rt->seek_timestamp = 0; /* default is to start stream at position zero */
     return 0;
  fail:
     ff_rtsp_close_streams(s);
-    url_close(rt->rtsp_hd);
+    ff_rtsp_close_connections(s);
     if (reply->status_code >=300 && reply->status_code < 400 && s->iformat) {
         av_strlcpy(s->filename, reply->location, sizeof(s->filename));
         av_log(s, AV_LOG_INFO, "Status %d: Redirecting to %s\n",
@@ -1623,86 +1552,62 @@ redirect:
     ff_network_close();
     return err;
 }
-#endif
-
-#if CONFIG_RTSP_DEMUXER
-static int rtsp_read_header(AVFormatContext *s,
-                            AVFormatParameters *ap)
-{
-    RTSPState *rt = s->priv_data;
-    int ret;
-
-    ret = ff_rtsp_connect(s);
-    if (ret)
-        return ret;
-
-    if (ap->initial_pause) {
-         /* do not start immediately */
-    } else {
-         if (rtsp_read_play(s) < 0) {
-            ff_rtsp_close_streams(s);
-            url_close(rt->rtsp_hd);
-            return AVERROR_INVALIDDATA;
-        }
-    }
-
-    return 0;
-}
+#endif /* CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER */
 
+#if CONFIG_RTPDEC
 static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
-                           uint8_t *buf, int buf_size)
+                           uint8_t *buf, int buf_size, int64_t wait_end)
 {
     RTSPState *rt = s->priv_data;
     RTSPStream *rtsp_st;
-    fd_set rfds;
-    int fd, fd_max, n, i, ret, tcp_fd, timeout_cnt = 0;
-    struct timeval tv;
+    int n, i, ret, tcp_fd, timeout_cnt = 0;
+    int max_p = 0;
+    struct pollfd *p = rt->p;
 
     for (;;) {
         if (url_interrupt_cb())
-            return AVERROR(EINTR);
-        FD_ZERO(&rfds);
+            return AVERROR_EXIT;
+        if (wait_end && wait_end - av_gettime() < 0)
+            return AVERROR(EAGAIN);
+        max_p = 0;
         if (rt->rtsp_hd) {
-            tcp_fd = fd_max = url_get_file_handle(rt->rtsp_hd);
-            FD_SET(tcp_fd, &rfds);
+            tcp_fd = ffurl_get_file_handle(rt->rtsp_hd);
+            p[max_p].fd = tcp_fd;
+            p[max_p++].events = POLLIN;
         } else {
-            fd_max = 0;
             tcp_fd = -1;
         }
         for (i = 0; i < rt->nb_rtsp_streams; i++) {
             rtsp_st = rt->rtsp_streams[i];
             if (rtsp_st->rtp_handle) {
-                /* currently, we cannot probe RTCP handle because of
-                 * blocking restrictions */
-                fd = url_get_file_handle(rtsp_st->rtp_handle);
-                if (fd > fd_max)
-                    fd_max = fd;
-                FD_SET(fd, &rfds);
+                p[max_p].fd = ffurl_get_file_handle(rtsp_st->rtp_handle);
+                p[max_p++].events = POLLIN;
+                p[max_p].fd = rtp_get_rtcp_file_handle(rtsp_st->rtp_handle);
+                p[max_p++].events = POLLIN;
             }
         }
-        tv.tv_sec = 0;
-        tv.tv_usec = SELECT_TIMEOUT_MS * 1000;
-        n = select(fd_max + 1, &rfds, NULL, NULL, &tv);
+        n = poll(p, max_p, POLL_TIMEOUT_MS);
         if (n > 0) {
+            int j = 1 - (tcp_fd == -1);
             timeout_cnt = 0;
             for (i = 0; i < rt->nb_rtsp_streams; i++) {
                 rtsp_st = rt->rtsp_streams[i];
                 if (rtsp_st->rtp_handle) {
-                    fd = url_get_file_handle(rtsp_st->rtp_handle);
-                    if (FD_ISSET(fd, &rfds)) {
-                        ret = url_read(rtsp_st->rtp_handle, buf, buf_size);
+                    if (p[j].revents & POLLIN || p[j+1].revents & POLLIN) {
+                        ret = ffurl_read(rtsp_st->rtp_handle, buf, buf_size);
                         if (ret > 0) {
                             *prtsp_st = rtsp_st;
                             return ret;
                         }
                     }
+                    j+=2;
                 }
             }
 #if CONFIG_RTSP_DEMUXER
-            if (tcp_fd != -1 && FD_ISSET(tcp_fd, &rfds)) {
+            if (tcp_fd != -1 && p[0].revents & POLLIN) {
                 RTSPMessageHeader reply;
 
-                ret = ff_rtsp_read_reply(s, &reply, NULL, 0);
+                ret = ff_rtsp_read_reply(s, &reply, NULL, 0, NULL);
                 if (ret < 0)
                     return ret;
                 /* XXX: parse message */
@@ -1711,72 +1616,21 @@ static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
             }
 #endif
         } else if (n == 0 && ++timeout_cnt >= MAX_TIMEOUTS) {
-            return FF_NETERROR(ETIMEDOUT);
+            return AVERROR(ETIMEDOUT);
         } else if (n < 0 && errno != EINTR)
             return AVERROR(errno);
     }
 }
 
-static int tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
-                           uint8_t *buf, int buf_size)
-{
-    RTSPState *rt = s->priv_data;
-    int id, len, i, ret;
-    RTSPStream *rtsp_st;
-
-#ifdef DEBUG_RTP_TCP
-    dprintf(s, "tcp_read_packet:\n");
-#endif
-redo:
-    for (;;) {
-        RTSPMessageHeader reply;
-
-        ret = ff_rtsp_read_reply(s, &reply, NULL, 1);
-        if (ret == -1)
-            return -1;
-        if (ret == 1) /* received '$' */
-            break;
-        /* XXX: parse message */
-        if (rt->state != RTSP_STATE_STREAMING)
-            return 0;
-    }
-    ret = url_read_complete(rt->rtsp_hd, buf, 3);
-    if (ret != 3)
-        return -1;
-    id  = buf[0];
-    len = AV_RB16(buf + 1);
-#ifdef DEBUG_RTP_TCP
-    dprintf(s, "id=%d len=%d\n", id, len);
-#endif
-    if (len > buf_size || len < 12)
-        goto redo;
-    /* get the data */
-    ret = url_read_complete(rt->rtsp_hd, buf, len);
-    if (ret != len)
-        return -1;
-    if (rt->transport == RTSP_TRANSPORT_RDT &&
-        ff_rdt_parse_header(buf, len, &id, NULL, NULL, NULL, NULL) < 0)
-        return -1;
-
-    /* find the matching stream */
-    for (i = 0; i < rt->nb_rtsp_streams; i++) {
-        rtsp_st = rt->rtsp_streams[i];
-        if (id >= rtsp_st->interleaved_min &&
-            id <= rtsp_st->interleaved_max)
-            goto found;
-    }
-    goto redo;
-found:
-    *prtsp_st = rtsp_st;
-    return len;
-}
-
-static int rtsp_fetch_packet(AVFormatContext *s, AVPacket *pkt)
+int ff_rtsp_fetch_packet(AVFormatContext *s, AVPacket *pkt)
 {
     RTSPState *rt = s->priv_data;
     int ret, len;
-    uint8_t buf[10 * RTP_MAX_PACKET_LENGTH];
-    RTSPStream *rtsp_st;
+    RTSPStream *rtsp_st, *first_queue_st = NULL;
+    int64_t wait_end = 0;
+
+    if (rt->nb_byes == rt->nb_rtsp_streams)
+        return AVERROR_EOF;
 
     /* get next frames from the same RTP packet */
     if (rt->cur_transport_priv) {
@@ -1793,30 +1647,61 @@ static int rtsp_fetch_packet(AVFormatContext *s, AVPacket *pkt)
             rt->cur_transport_priv = NULL;
     }
 
+    if (rt->transport == RTSP_TRANSPORT_RTP) {
+        int i;
+        int64_t first_queue_time = 0;
+        for (i = 0; i < rt->nb_rtsp_streams; i++) {
+            RTPDemuxContext *rtpctx = rt->rtsp_streams[i]->transport_priv;
+            int64_t queue_time;
+            if (!rtpctx)
+                continue;
+            queue_time = ff_rtp_queued_packet_time(rtpctx);
+            if (queue_time && (queue_time - first_queue_time < 0 ||
+                               !first_queue_time)) {
+                first_queue_time = queue_time;
+                first_queue_st   = rt->rtsp_streams[i];
+            }
+        }
+        if (first_queue_time)
+            wait_end = first_queue_time + s->max_delay;
+    }
+
     /* read next RTP packet */
  redo:
+    if (!rt->recvbuf) {
+        rt->recvbuf = av_malloc(RECVBUF_SIZE);
+        if (!rt->recvbuf)
+            return AVERROR(ENOMEM);
+    }
+
     switch(rt->lower_transport) {
     default:
 #if CONFIG_RTSP_DEMUXER
     case RTSP_LOWER_TRANSPORT_TCP:
-        len = tcp_read_packet(s, &rtsp_st, buf, sizeof(buf));
+        len = ff_rtsp_tcp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE);
         break;
 #endif
     case RTSP_LOWER_TRANSPORT_UDP:
     case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
-        len = udp_read_packet(s, &rtsp_st, buf, sizeof(buf));
-        if (len >=0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)
+        len = udp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE, wait_end);
+        if (len > 0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)
             rtp_check_and_send_back_rr(rtsp_st->transport_priv, len);
         break;
     }
+    if (len == AVERROR(EAGAIN) && first_queue_st &&
+        rt->transport == RTSP_TRANSPORT_RTP) {
+        rtsp_st = first_queue_st;
+        ret = rtp_parse_packet(rtsp_st->transport_priv, pkt, NULL, 0);
+        goto end;
+    }
     if (len < 0)
         return len;
     if (len == 0)
         return AVERROR_EOF;
     if (rt->transport == RTSP_TRANSPORT_RDT) {
-        ret = ff_rdt_parse_packet(rtsp_st->transport_priv, pkt, buf, len);
+        ret = ff_rdt_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);
     } else {
-        ret = rtp_parse_packet(rtsp_st->transport_priv, pkt, buf, len);
+        ret = rtp_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);
         if (ret < 0) {
             /* Either bad packet, or a RTCP packet. Check if the
              * first_rtcp_ntp_time field was initialized. */
@@ -1827,15 +1712,35 @@ static int rtsp_fetch_packet(AVFormatContext *s, AVPacket *pkt)
                  * in order to map their timestamp origin to the same ntp time
                  * as this one. */
                 int i;
+                AVStream *st = NULL;
+                if (rtsp_st->stream_index >= 0)
+                    st = s->streams[rtsp_st->stream_index];
                 for (i = 0; i < rt->nb_rtsp_streams; i++) {
-                    RTPDemuxContext *rtpctx2 = rtsp_st->transport_priv;
-                    if (rtpctx2 &&
-                        rtpctx2->first_rtcp_ntp_time == AV_NOPTS_VALUE)
+                    RTPDemuxContext *rtpctx2 = rt->rtsp_streams[i]->transport_priv;
+                    AVStream *st2 = NULL;
+                    if (rt->rtsp_streams[i]->stream_index >= 0)
+                        st2 = s->streams[rt->rtsp_streams[i]->stream_index];
+                    if (rtpctx2 && st && st2 &&
+                        rtpctx2->first_rtcp_ntp_time == AV_NOPTS_VALUE) {
                         rtpctx2->first_rtcp_ntp_time = rtpctx->first_rtcp_ntp_time;
+                        rtpctx2->rtcp_ts_offset = av_rescale_q(
+                            rtpctx->rtcp_ts_offset, st->time_base,
+                            st2->time_base);
+                    }
                 }
             }
+            if (ret == -RTCP_BYE) {
+                rt->nb_byes++;
+
+                av_log(s, AV_LOG_DEBUG, "Received BYE for stream %d (%d/%d)\n",
+                       rtsp_st->stream_index, rt->nb_byes, rt->nb_rtsp_streams);
+
+                if (rt->nb_byes == rt->nb_rtsp_streams)
+                    return AVERROR_EOF;
+            }
         }
     }
+end:
     if (ret < 0)
         goto redo;
     if (ret == 1)
@@ -1844,176 +1749,17 @@ static int rtsp_fetch_packet(AVFormatContext *s, AVPacket *pkt)
 
     return ret;
 }
+#endif /* CONFIG_RTPDEC */
 
-static int rtsp_read_packet(AVFormatContext *s, AVPacket *pkt)
-{
-    RTSPState *rt = s->priv_data;
-    int ret;
-    RTSPMessageHeader reply1, *reply = &reply1;
-    char cmd[1024];
-
-    if (rt->server_type == RTSP_SERVER_REAL) {
-        int i;
-        enum AVDiscard cache[MAX_STREAMS];
-
-        for (i = 0; i < s->nb_streams; i++)
-            cache[i] = s->streams[i]->discard;
-
-        if (!rt->need_subscription) {
-            if (memcmp (cache, rt->real_setup_cache,
-                        sizeof(enum AVDiscard) * s->nb_streams)) {
-                snprintf(cmd, sizeof(cmd),
-                         "Unsubscribe: %s\r\n",
-                         rt->last_subscription);
-                ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
-                                 cmd, reply, NULL);
-                if (reply->status_code != RTSP_STATUS_OK)
-                    return AVERROR_INVALIDDATA;
-                rt->need_subscription = 1;
-            }
-        }
-
-        if (rt->need_subscription) {
-            int r, rule_nr, first = 1;
-
-            memcpy(rt->real_setup_cache, cache,
-                   sizeof(enum AVDiscard) * s->nb_streams);
-            rt->last_subscription[0] = 0;
-
-            snprintf(cmd, sizeof(cmd),
-                     "Subscribe: ");
-            for (i = 0; i < rt->nb_rtsp_streams; i++) {
-                rule_nr = 0;
-                for (r = 0; r < s->nb_streams; r++) {
-                    if (s->streams[r]->priv_data == rt->rtsp_streams[i]) {
-                        if (s->streams[r]->discard != AVDISCARD_ALL) {
-                            if (!first)
-                                av_strlcat(rt->last_subscription, ",",
-                                           sizeof(rt->last_subscription));
-                            ff_rdt_subscribe_rule(
-                                rt->last_subscription,
-                                sizeof(rt->last_subscription), i, rule_nr);
-                            first = 0;
-                        }
-                        rule_nr++;
-                    }
-                }
-            }
-            av_strlcatf(cmd, sizeof(cmd), "%s\r\n", rt->last_subscription);
-            ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
-                             cmd, reply, NULL);
-            if (reply->status_code != RTSP_STATUS_OK)
-                return AVERROR_INVALIDDATA;
-            rt->need_subscription = 0;
-
-            if (rt->state == RTSP_STATE_STREAMING)
-                rtsp_read_play (s);
-        }
-    }
-
-    ret = rtsp_fetch_packet(s, pkt);
-    if (ret < 0)
-        return ret;
-
-    /* send dummy request to keep TCP connection alive */
-    if ((rt->server_type == RTSP_SERVER_WMS ||
-         rt->server_type == RTSP_SERVER_REAL) &&
-        (av_gettime() - rt->last_cmd_time) / 1000000 >= rt->timeout / 2) {
-        if (rt->server_type == RTSP_SERVER_WMS) {
-            ff_rtsp_send_cmd_async(s, "GET_PARAMETER", rt->control_uri, NULL);
-        } else {
-            ff_rtsp_send_cmd_async(s, "OPTIONS", "*", NULL);
-        }
-    }
-
-    return 0;
-}
-
-/* pause the stream */
-static int rtsp_read_pause(AVFormatContext *s)
-{
-    RTSPState *rt = s->priv_data;
-    RTSPMessageHeader reply1, *reply = &reply1;
-
-    if (rt->state != RTSP_STATE_STREAMING)
-        return 0;
-    else if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
-        ff_rtsp_send_cmd(s, "PAUSE", rt->control_uri, NULL, reply, NULL);
-        if (reply->status_code != RTSP_STATUS_OK) {
-            return -1;
-        }
-    }
-    rt->state = RTSP_STATE_PAUSED;
-    return 0;
-}
-
-static int rtsp_read_seek(AVFormatContext *s, int stream_index,
-                          int64_t timestamp, int flags)
-{
-    RTSPState *rt = s->priv_data;
-
-    rt->seek_timestamp = av_rescale_q(timestamp,
-                                      s->streams[stream_index]->time_base,
-                                      AV_TIME_BASE_Q);
-    switch(rt->state) {
-    default:
-    case RTSP_STATE_IDLE:
-        break;
-    case RTSP_STATE_STREAMING:
-        if (rtsp_read_pause(s) != 0)
-            return -1;
-        rt->state = RTSP_STATE_SEEKING;
-        if (rtsp_read_play(s) != 0)
-            return -1;
-        break;
-    case RTSP_STATE_PAUSED:
-        rt->state = RTSP_STATE_IDLE;
-        break;
-    }
-    return 0;
-}
-
-static int rtsp_read_close(AVFormatContext *s)
-{
-    RTSPState *rt = s->priv_data;
-
-#if 0
-    /* NOTE: it is valid to flush the buffer here */
-    if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
-        url_fclose(&rt->rtsp_gb);
-    }
-#endif
-    ff_rtsp_send_cmd_async(s, "TEARDOWN", rt->control_uri, NULL);
-
-    ff_rtsp_close_streams(s);
-    url_close(rt->rtsp_hd);
-    ff_network_close();
-    return 0;
-}
-
-AVInputFormat rtsp_demuxer = {
-    "rtsp",
-    NULL_IF_CONFIG_SMALL("RTSP input format"),
-    sizeof(RTSPState),
-    rtsp_probe,
-    rtsp_read_header,
-    rtsp_read_packet,
-    rtsp_read_close,
-    rtsp_read_seek,
-    .flags = AVFMT_NOFILE,
-    .read_play = rtsp_read_play,
-    .read_pause = rtsp_read_pause,
-};
-#endif
-
+#if CONFIG_SDP_DEMUXER
 static int sdp_probe(AVProbeData *p1)
 {
     const char *p = p1->buf, *p_end = p1->buf + p1->buf_size;
 
-    /* we look for a line beginning "c=IN IP4" */
+    /* we look for a line beginning "c=IN IP" */
     while (p < p_end && *p != '\0') {
-        if (p + sizeof("c=IN IP4") - 1 < p_end &&
-            av_strstart(p, "c=IN IP4", NULL))
+        if (p + sizeof("c=IN IP") - 1 < p_end &&
+            av_strstart(p, "c=IN IP", NULL))
             return AVPROBE_SCORE_MAX / 2;
 
         while (p < p_end - 1 && *p != '\n') p++;
@@ -2025,8 +1771,6 @@ static int sdp_probe(AVProbeData *p1)
     return 0;
 }
 
-#define SDP_MAX_SIZE 8192
-
 static int sdp_read_header(AVFormatContext *s, AVFormatParameters *ap)
 {
     RTSPState *rt = s->priv_data;
@@ -2041,25 +1785,29 @@ static int sdp_read_header(AVFormatContext *s, AVFormatParameters *ap)
     /* read the whole sdp file */
     /* XXX: better loading */
     content = av_malloc(SDP_MAX_SIZE);
-    size = get_buffer(s->pb, content, SDP_MAX_SIZE - 1);
+    size = avio_read(s->pb, content, SDP_MAX_SIZE - 1);
     if (size <= 0) {
         av_free(content);
         return AVERROR_INVALIDDATA;
     }
     content[size] ='\0';
 
-    sdp_parse(s, content);
+    err = ff_sdp_parse(s, content);
     av_free(content);
+    if (err) goto fail;
 
     /* open each RTP stream */
     for (i = 0; i < rt->nb_rtsp_streams; i++) {
+        char namebuf[50];
         rtsp_st = rt->rtsp_streams[i];
 
+        getnameinfo((struct sockaddr*) &rtsp_st->sdp_ip, sizeof(rtsp_st->sdp_ip),
+                    namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
         ff_url_join(url, sizeof(url), "rtp", NULL,
-                    inet_ntoa(rtsp_st->sdp_ip), rtsp_st->sdp_port,
+                    namebuf, rtsp_st->sdp_port,
                     "?localport=%d&ttl=%d", rtsp_st->sdp_port,
                     rtsp_st->sdp_ttl);
-        if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
+        if (ffurl_open(&rtsp_st->rtp_handle, url, AVIO_RDWR) < 0) {
             err = AVERROR_INVALIDDATA;
             goto fail;
         }
@@ -2080,12 +1828,119 @@ static int sdp_read_close(AVFormatContext *s)
     return 0;
 }
 
-AVInputFormat sdp_demuxer = {
+AVInputFormat ff_sdp_demuxer = {
     "sdp",
     NULL_IF_CONFIG_SMALL("SDP"),
     sizeof(RTSPState),
     sdp_probe,
     sdp_read_header,
-    rtsp_fetch_packet,
+    ff_rtsp_fetch_packet,
     sdp_read_close,
 };
+#endif /* CONFIG_SDP_DEMUXER */
+
+#if CONFIG_RTP_DEMUXER
+static int rtp_probe(AVProbeData *p)
+{
+    if (av_strstart(p->filename, "rtp:", NULL))
+        return AVPROBE_SCORE_MAX;
+    return 0;
+}
+
+static int rtp_read_header(AVFormatContext *s,
+                           AVFormatParameters *ap)
+{
+    uint8_t recvbuf[1500];
+    char host[500], sdp[500];
+    int ret, port;
+    URLContext* in = NULL;
+    int payload_type;
+    AVCodecContext codec;
+    struct sockaddr_storage addr;
+    AVIOContext pb;
+    socklen_t addrlen = sizeof(addr);
+
+    if (!ff_network_init())
+        return AVERROR(EIO);
+
+    ret = ffurl_open(&in, s->filename, AVIO_RDONLY);
+    if (ret)
+        goto fail;
+
+    while (1) {
+        ret = ffurl_read(in, recvbuf, sizeof(recvbuf));
+        if (ret == AVERROR(EAGAIN))
+            continue;
+        if (ret < 0)
+            goto fail;
+        if (ret < 12) {
+            av_log(s, AV_LOG_WARNING, "Received too short packet\n");
+            continue;
+        }
+
+        if ((recvbuf[0] & 0xc0) != 0x80) {
+            av_log(s, AV_LOG_WARNING, "Unsupported RTP version packet "
+                                      "received\n");
+            continue;
+        }
+
+        payload_type = recvbuf[1] & 0x7f;
+        break;
+    }
+    getsockname(ffurl_get_file_handle(in), (struct sockaddr*) &addr, &addrlen);
+    ffurl_close(in);
+    in = NULL;
+
+    memset(&codec, 0, sizeof(codec));
+    if (ff_rtp_get_codec_info(&codec, payload_type)) {
+        av_log(s, AV_LOG_ERROR, "Unable to receive RTP payload type %d "
+                                "without an SDP file describing it\n",
+                                 payload_type);
+        goto fail;
+    }
+    if (codec.codec_type != AVMEDIA_TYPE_DATA) {
+        av_log(s, AV_LOG_WARNING, "Guessing on RTP content - if not received "
+                                  "properly you need an SDP file "
+                                  "describing it\n");
+    }
+
+    av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port,
+                 NULL, 0, s->filename);
+
+    snprintf(sdp, sizeof(sdp),
+             "v=0\r\nc=IN IP%d %s\r\nm=%s %d RTP/AVP %d\r\n",
+             addr.ss_family == AF_INET ? 4 : 6, host,
+             codec.codec_type == AVMEDIA_TYPE_DATA  ? "application" :
+             codec.codec_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio",
+             port, payload_type);
+    av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", sdp);
+
+    ffio_init_context(&pb, sdp, strlen(sdp), 0, NULL, NULL, NULL, NULL);
+    s->pb = &pb;
+
+    /* sdp_read_header initializes this again */
+    ff_network_close();
+
+    ret = sdp_read_header(s, ap);
+    s->pb = NULL;
+    return ret;
+
+fail:
+    if (in)
+        ffurl_close(in);
+    ff_network_close();
+    return ret;
+}
+
+AVInputFormat ff_rtp_demuxer = {
+    "rtp",
+    NULL_IF_CONFIG_SMALL("RTP input format"),
+    sizeof(RTSPState),
+    rtp_probe,
+    rtp_read_header,
+    ff_rtsp_fetch_packet,
+    sdp_read_close,
+    .flags = AVFMT_NOFILE,
+};
+#endif /* CONFIG_RTP_DEMUXER */
+
diff --git a/libavformat/rtsp.h b/libavformat/rtsp.h
index 357d3bf..e1f1df9 100644
--- a/libavformat/rtsp.h
+++ b/libavformat/rtsp.h
@@ -2,20 +2,20 @@
  * RTSP definitions
  * Copyright (c) 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #ifndef AVFORMAT_RTSP_H
@@ -49,10 +49,19 @@ enum RTSPTransport {
     RTSP_TRANSPORT_NB
 };
 
+/**
+ * Transport mode for the RTSP data. This may be plain, or
+ * tunneled, which is done over HTTP.
+ */
+enum RTSPControlTransport {
+    RTSP_MODE_PLAIN,   /**< Normal RTSP */
+    RTSP_MODE_TUNNEL   /**< RTSP over HTTP (tunneling) */
+};
+
 #define RTSP_DEFAULT_PORT   554
 #define RTSP_MAX_TRANSPORTS 8
 #define RTSP_TCP_MAX_PACKET_SIZE 1472
-#define RTSP_DEFAULT_NB_AUDIO_CHANNELS 2
+#define RTSP_DEFAULT_NB_AUDIO_CHANNELS 1
 #define RTSP_DEFAULT_AUDIO_SAMPLERATE 44100
 #define RTSP_RTP_PORT_MIN 5000
 #define RTSP_RTP_PORT_MAX 10000
@@ -87,7 +96,8 @@ typedef struct RTSPTransportField {
      * packets will be allowed to make before being discarded. */
     int ttl;
 
-    uint32_t destination; /**< destination IP address */
+    struct sockaddr_storage destination; /**< destination IP address */
+    char source[INET6_ADDRSTRLEN + 1]; /**< source IP address */
 
     /** data/packet transport protocol; e.g. RTP or RDT */
     enum RTSPTransport transport;
@@ -150,6 +160,11 @@ typedef struct RTSPMessageHeader {
      * http://tools.ietf.org/html/draft-stiemerling-rtsp-announce-00
      * for a complete list of supported values. */
     int notice;
+
+    /** The "reason" is meant to specify better the meaning of the error code
+     * returned
+     */
+    char reason[256];
 } RTSPMessageHeader;
 
 /**
@@ -178,10 +193,10 @@ enum RTSPServerType {
 /**
  * Private data for the RTSP demuxer.
  *
- * @todo Use ByteIOContext instead of URLContext
+ * @todo Use AVIOContext instead of URLContext
  */
 typedef struct RTSPState {
-    URLContext *rtsp_hd; /* RTSP TCP connexion handle */
+    URLContext *rtsp_hd; /* RTSP TCP connection handle */
 
     /** number of items in the 'rtsp_streams' variable */
     int nb_rtsp_streams;
@@ -203,7 +218,7 @@ typedef struct RTSPState {
     int64_t seek_timestamp;
 
     /* XXX: currently we use unbuffered input */
-    //    ByteIOContext rtsp_gb;
+    //    AVIOContext rtsp_gb;
 
     int seq;                          /**< RTSP command sequence number */
 
@@ -233,6 +248,9 @@ typedef struct RTSPState {
      * of RTSPMessageHeader->real_challenge */
     enum RTSPServerType server_type;
 
+    /** the "RealChallenge1:" field from the server */
+    char real_challenge[64];
+
     /** plaintext authorization line (username:password) */
     char auth[128];
 
@@ -253,7 +271,11 @@ typedef struct RTSPState {
 
     /** stream setup during the last frame read. This is used to detect if
      * we need to subscribe or unsubscribe to any new streams. */
-    enum AVDiscard real_setup_cache[MAX_STREAMS];
+    enum AVDiscard *real_setup_cache;
+
+    /** current stream setup. This is a temporary buffer used to compare
+     * current setup to previous frame setup. */
+    enum AVDiscard *real_setup;
 
     /** the last value of the "SET_PARAMETER Subscribe:" RTSP command.
      * this is used to send the same "Unsubscribe:" if stream setup changed,
@@ -276,8 +298,39 @@ typedef struct RTSPState {
      * other cases, this is a copy of AVFormatContext->filename. */
     char control_uri[1024];
 
-    /** The synchronized start time of the output streams. */
-    int64_t start_time;
+    /** Additional output handle, used when input and output are done
+     * separately, eg for HTTP tunneling. */
+    URLContext *rtsp_hd_out;
+
+    /** RTSP transport mode, such as plain or tunneled. */
+    enum RTSPControlTransport control_transport;
+
+    /* Number of RTCP BYE packets the RTSP session has received.
+     * An EOF is propagated back if nb_byes == nb_streams.
+     * This is reset after a seek. */
+    int nb_byes;
+
+    /** Reusable buffer for receiving packets */
+    uint8_t* recvbuf;
+
+    /** Filter incoming UDP packets - receive packets only from the right
+     * source address and port. */
+    int filter_source;
+
+    /**
+     * A mask with all requested transport methods
+     */
+    int lower_transport_mask;
+
+    /**
+     * The number of returned packets
+     */
+    uint64_t packets;
+
+    /**
+     * Polling array for udp
+     */
+    struct pollfd *p;
 } RTSPState;
 
 /**
@@ -302,16 +355,11 @@ typedef struct RTSPStream {
     /** The following are used only in SDP, not RTSP */
     //@{
     int sdp_port;             /**< port (from SDP content) */
-    struct in_addr sdp_ip;    /**< IP address (from SDP content) */
+    struct sockaddr_storage sdp_ip; /**< IP address (from SDP content) */
     int sdp_ttl;              /**< IP Time-To-Live (from SDP content) */
     int sdp_payload_type;     /**< payload type */
     //@}
 
-    /** rtp payload parsing infos from SDP (i.e. mapping between private
-     * payload IDs and media-types (string), so that we can derive what
-     * type of payload we're dealing with (and how to parse it). */
-    RTPPayloadData rtp_payload_data;
-
     /** The following are used for dynamic protocols (rtp_*.c/rdt.c) */
     //@{
     /** handler structure */
@@ -323,37 +371,18 @@ typedef struct RTSPStream {
 } RTSPStream;
 
 void ff_rtsp_parse_line(RTSPMessageHeader *reply, const char *buf,
-                        HTTPAuthState *auth_state);
+                        RTSPState *rt, const char *method);
 
-#if LIBAVFORMAT_VERSION_INT < (53 << 16)
-extern int rtsp_default_protocols;
-#endif
 extern int rtsp_rtp_port_min;
 extern int rtsp_rtp_port_max;
 
 /**
  * Send a command to the RTSP server without waiting for the reply.
  *
- * @param s RTSP (de)muxer context
- * @param method the method for the request
- * @param url the target url for the request
- * @param headers extra header lines to include in the request
- * @param send_content if non-null, the data to send as request body content
- * @param send_content_length the length of the send_content data, or 0 if
- *                            send_content is null
- */
-void ff_rtsp_send_cmd_with_content_async(AVFormatContext *s,
-                                         const char *method, const char *url,
-                                         const char *headers,
-                                         const unsigned char *send_content,
-                                         int send_content_length);
-/**
- * Send a command to the RTSP server without waiting for the reply.
- *
  * @see rtsp_send_cmd_with_content_async
  */
-void ff_rtsp_send_cmd_async(AVFormatContext *s, const char *method,
-                            const char *url, const char *headers);
+int ff_rtsp_send_cmd_async(AVFormatContext *s, const char *method,
+                           const char *url, const char *headers);
 
 /**
  * Send a command to the RTSP server and wait for the reply.
@@ -368,23 +397,25 @@ void ff_rtsp_send_cmd_async(AVFormatContext *s, const char *method,
  * @param send_content if non-null, the data to send as request body content
  * @param send_content_length the length of the send_content data, or 0 if
  *                            send_content is null
+ *
+ * @return zero if success, nonzero otherwise
  */
-void ff_rtsp_send_cmd_with_content(AVFormatContext *s,
-                                   const char *method, const char *url,
-                                   const char *headers,
-                                   RTSPMessageHeader *reply,
-                                   unsigned char **content_ptr,
-                                   const unsigned char *send_content,
-                                   int send_content_length);
+int ff_rtsp_send_cmd_with_content(AVFormatContext *s,
+                                  const char *method, const char *url,
+                                  const char *headers,
+                                  RTSPMessageHeader *reply,
+                                  unsigned char **content_ptr,
+                                  const unsigned char *send_content,
+                                  int send_content_length);
 
 /**
  * Send a command to the RTSP server and wait for the reply.
  *
  * @see rtsp_send_cmd_with_content
  */
-void ff_rtsp_send_cmd(AVFormatContext *s, const char *method,
-                      const char *url, const char *headers,
-                      RTSPMessageHeader *reply, unsigned char **content_ptr);
+int ff_rtsp_send_cmd(AVFormatContext *s, const char *method,
+                     const char *url, const char *headers,
+                     RTSPMessageHeader *reply, unsigned char **content_ptr);
 
 /**
  * Read a RTSP message from the server, or prepare to read data
@@ -403,13 +434,15 @@ void ff_rtsp_send_cmd(AVFormatContext *s, const char *method,
  *                   data packets (if they are encountered), until a reply
  *                   has been fully parsed. If no more data is available
  *                   without parsing a reply, it will return an error.
+ * @param method the RTSP method this is a reply to. This affects how
+ *               some response headers are acted upon. May be NULL.
  *
  * @return 1 if a data packets is ready to be received, -1 on error,
  *          and 0 on success.
  */
 int ff_rtsp_read_reply(AVFormatContext *s, RTSPMessageHeader *reply,
                        unsigned char **content_ptr,
-                       int return_on_interleaved_data);
+                       int return_on_interleaved_data, const char *method);
 
 /**
  * Skip a RTP/TCP interleaved packet.
@@ -434,4 +467,54 @@ int ff_rtsp_connect(AVFormatContext *s);
  */
 void ff_rtsp_close_streams(AVFormatContext *s);
 
+/**
+ * Close all connection handles within the RTSP (de)muxer
+ *
+ * @param rt RTSP (de)muxer context
+ */
+void ff_rtsp_close_connections(AVFormatContext *rt);
+
+/**
+ * Get the description of the stream and set up the RTSPStream child
+ * objects.
+ */
+int ff_rtsp_setup_input_streams(AVFormatContext *s, RTSPMessageHeader *reply);
+
+/**
+ * Announce the stream to the server and set up the RTSPStream child
+ * objects for each media stream.
+ */
+int ff_rtsp_setup_output_streams(AVFormatContext *s, const char *addr);
+
+/**
+ * Parse a SDP description of streams by populating an RTSPState struct
+ * within the AVFormatContext.
+ */
+int ff_sdp_parse(AVFormatContext *s, const char *content);
+
+/**
+ * Receive one RTP packet from an TCP interleaved RTSP stream.
+ */
+int ff_rtsp_tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
+                            uint8_t *buf, int buf_size);
+
+/**
+ * Receive one packet from the RTSPStreams set up in the AVFormatContext
+ * (which should contain a RTSPState struct as priv_data).
+ */
+int ff_rtsp_fetch_packet(AVFormatContext *s, AVPacket *pkt);
+
+/**
+ * Do the SETUP requests for each stream for the chosen
+ * lower transport mode.
+ */
+int ff_rtsp_make_setup_request(AVFormatContext *s, const char *host, int port,
+                               int lower_transport, const char *real_challenge);
+
+/**
+ * Undo the effect of ff_rtsp_make_setup_request, close the
+ * transport_priv and rtp_handle fields.
+ */
+void ff_rtsp_undo_setup(AVFormatContext *s);
+
 #endif /* AVFORMAT_RTSP_H */
diff --git a/libavformat/rtspcodes.h b/libavformat/rtspcodes.h
index 9ee96bf..63ceb66 100644
--- a/libavformat/rtspcodes.h
+++ b/libavformat/rtspcodes.h
@@ -2,20 +2,20 @@
  * RTSP definitions
  * copyright (c) 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavformat/rtspdec.c b/libavformat/rtspdec.c
new file mode 100644
index 0000000..866f313
--- /dev/null
+++ b/libavformat/rtspdec.c
@@ -0,0 +1,412 @@
+/*
+ * RTSP demuxer
+ * Copyright (c) 2002 Fabrice Bellard
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "libavutil/avstring.h"
+#include "libavutil/intreadwrite.h"
+#include "avformat.h"
+
+#include "internal.h"
+#include "network.h"
+#include "os_support.h"
+#include "rtsp.h"
+#include "rdt.h"
+#include "url.h"
+
+//#define DEBUG
+//#define DEBUG_RTP_TCP
+
+static int rtsp_read_play(AVFormatContext *s)
+{
+    RTSPState *rt = s->priv_data;
+    RTSPMessageHeader reply1, *reply = &reply1;
+    int i;
+    char cmd[1024];
+
+    av_log(s, AV_LOG_DEBUG, "hello state=%d\n", rt->state);
+    rt->nb_byes = 0;
+
+    if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
+        if (rt->transport == RTSP_TRANSPORT_RTP) {
+            for (i = 0; i < rt->nb_rtsp_streams; i++) {
+                RTSPStream *rtsp_st = rt->rtsp_streams[i];
+                RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
+                if (!rtpctx)
+                    continue;
+                ff_rtp_reset_packet_queue(rtpctx);
+                rtpctx->last_rtcp_ntp_time  = AV_NOPTS_VALUE;
+                rtpctx->first_rtcp_ntp_time = AV_NOPTS_VALUE;
+                rtpctx->base_timestamp      = 0;
+                rtpctx->rtcp_ts_offset      = 0;
+            }
+        }
+        if (rt->state == RTSP_STATE_PAUSED) {
+            cmd[0] = 0;
+        } else {
+            snprintf(cmd, sizeof(cmd),
+                     "Range: npt=%"PRId64".%03"PRId64"-\r\n",
+                     rt->seek_timestamp / AV_TIME_BASE,
+                     rt->seek_timestamp / (AV_TIME_BASE / 1000) % 1000);
+        }
+        ff_rtsp_send_cmd(s, "PLAY", rt->control_uri, cmd, reply, NULL);
+        if (reply->status_code != RTSP_STATUS_OK) {
+            return -1;
+        }
+        if (rt->transport == RTSP_TRANSPORT_RTP &&
+            reply->range_start != AV_NOPTS_VALUE) {
+            for (i = 0; i < rt->nb_rtsp_streams; i++) {
+                RTSPStream *rtsp_st = rt->rtsp_streams[i];
+                RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
+                AVStream *st = NULL;
+                if (!rtpctx || rtsp_st->stream_index < 0)
+                    continue;
+                st = s->streams[rtsp_st->stream_index];
+                rtpctx->range_start_offset =
+                    av_rescale_q(reply->range_start, AV_TIME_BASE_Q,
+                                 st->time_base);
+            }
+        }
+    }
+    rt->state = RTSP_STATE_STREAMING;
+    return 0;
+}
+
+/* pause the stream */
+static int rtsp_read_pause(AVFormatContext *s)
+{
+    RTSPState *rt = s->priv_data;
+    RTSPMessageHeader reply1, *reply = &reply1;
+
+    if (rt->state != RTSP_STATE_STREAMING)
+        return 0;
+    else if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
+        ff_rtsp_send_cmd(s, "PAUSE", rt->control_uri, NULL, reply, NULL);
+        if (reply->status_code != RTSP_STATUS_OK) {
+            return -1;
+        }
+    }
+    rt->state = RTSP_STATE_PAUSED;
+    return 0;
+}
+
+int ff_rtsp_setup_input_streams(AVFormatContext *s, RTSPMessageHeader *reply)
+{
+    RTSPState *rt = s->priv_data;
+    char cmd[1024];
+    unsigned char *content = NULL;
+    int ret;
+
+    /* describe the stream */
+    snprintf(cmd, sizeof(cmd),
+             "Accept: application/sdp\r\n");
+    if (rt->server_type == RTSP_SERVER_REAL) {
+        /**
+         * The Require: attribute is needed for proper streaming from
+         * Realmedia servers.
+         */
+        av_strlcat(cmd,
+                   "Require: com.real.retain-entity-for-setup\r\n",
+                   sizeof(cmd));
+    }
+    ff_rtsp_send_cmd(s, "DESCRIBE", rt->control_uri, cmd, reply, &content);
+    if (!content)
+        return AVERROR_INVALIDDATA;
+    if (reply->status_code != RTSP_STATUS_OK) {
+        av_freep(&content);
+        return AVERROR_INVALIDDATA;
+    }
+
+    av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", content);
+    /* now we got the SDP description, we parse it */
+    ret = ff_sdp_parse(s, (const char *)content);
+    av_freep(&content);
+    if (ret < 0)
+        return ret;
+
+    return 0;
+}
+
+static int rtsp_probe(AVProbeData *p)
+{
+    if (av_strstart(p->filename, "rtsp:", NULL))
+        return AVPROBE_SCORE_MAX;
+    return 0;
+}
+
+static int rtsp_read_header(AVFormatContext *s,
+                            AVFormatParameters *ap)
+{
+    RTSPState *rt = s->priv_data;
+    int ret;
+
+    ret = ff_rtsp_connect(s);
+    if (ret)
+        return ret;
+
+    rt->real_setup_cache = av_mallocz(2 * s->nb_streams * sizeof(*rt->real_setup_cache));
+    if (!rt->real_setup_cache)
+        return AVERROR(ENOMEM);
+    rt->real_setup = rt->real_setup_cache + s->nb_streams;
+
+    if (ap->initial_pause) {
+         /* do not start immediately */
+    } else {
+         if (rtsp_read_play(s) < 0) {
+            ff_rtsp_close_streams(s);
+            ff_rtsp_close_connections(s);
+            return AVERROR_INVALIDDATA;
+        }
+    }
+
+    return 0;
+}
+
+int ff_rtsp_tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
+                            uint8_t *buf, int buf_size)
+{
+    RTSPState *rt = s->priv_data;
+    int id, len, i, ret;
+    RTSPStream *rtsp_st;
+
+#ifdef DEBUG_RTP_TCP
+    av_dlog(s, "tcp_read_packet:\n");
+#endif
+redo:
+    for (;;) {
+        RTSPMessageHeader reply;
+
+        ret = ff_rtsp_read_reply(s, &reply, NULL, 1, NULL);
+        if (ret < 0)
+            return ret;
+        if (ret == 1) /* received '$' */
+            break;
+        /* XXX: parse message */
+        if (rt->state != RTSP_STATE_STREAMING)
+            return 0;
+    }
+    ret = ffurl_read_complete(rt->rtsp_hd, buf, 3);
+    if (ret != 3)
+        return -1;
+    id  = buf[0];
+    len = AV_RB16(buf + 1);
+#ifdef DEBUG_RTP_TCP
+    av_dlog(s, "id=%d len=%d\n", id, len);
+#endif
+    if (len > buf_size || len < 12)
+        goto redo;
+    /* get the data */
+    ret = ffurl_read_complete(rt->rtsp_hd, buf, len);
+    if (ret != len)
+        return -1;
+    if (rt->transport == RTSP_TRANSPORT_RDT &&
+        ff_rdt_parse_header(buf, len, &id, NULL, NULL, NULL, NULL) < 0)
+        return -1;
+
+    /* find the matching stream */
+    for (i = 0; i < rt->nb_rtsp_streams; i++) {
+        rtsp_st = rt->rtsp_streams[i];
+        if (id >= rtsp_st->interleaved_min &&
+            id <= rtsp_st->interleaved_max)
+            goto found;
+    }
+    goto redo;
+found:
+    *prtsp_st = rtsp_st;
+    return len;
+}
+
+static int resetup_tcp(AVFormatContext *s)
+{
+    RTSPState *rt = s->priv_data;
+    char host[1024];
+    int port;
+
+    av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port, NULL, 0,
+                 s->filename);
+    ff_rtsp_undo_setup(s);
+    return ff_rtsp_make_setup_request(s, host, port, RTSP_LOWER_TRANSPORT_TCP,
+                                      rt->real_challenge);
+}
+
+static int rtsp_read_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    RTSPState *rt = s->priv_data;
+    int ret;
+    RTSPMessageHeader reply1, *reply = &reply1;
+    char cmd[1024];
+
+retry:
+    if (rt->server_type == RTSP_SERVER_REAL) {
+        int i;
+
+        for (i = 0; i < s->nb_streams; i++)
+            rt->real_setup[i] = s->streams[i]->discard;
+
+        if (!rt->need_subscription) {
+            if (memcmp (rt->real_setup, rt->real_setup_cache,
+                        sizeof(enum AVDiscard) * s->nb_streams)) {
+                snprintf(cmd, sizeof(cmd),
+                         "Unsubscribe: %s\r\n",
+                         rt->last_subscription);
+                ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
+                                 cmd, reply, NULL);
+                if (reply->status_code != RTSP_STATUS_OK)
+                    return AVERROR_INVALIDDATA;
+                rt->need_subscription = 1;
+            }
+        }
+
+        if (rt->need_subscription) {
+            int r, rule_nr, first = 1;
+
+            memcpy(rt->real_setup_cache, rt->real_setup,
+                   sizeof(enum AVDiscard) * s->nb_streams);
+            rt->last_subscription[0] = 0;
+
+            snprintf(cmd, sizeof(cmd),
+                     "Subscribe: ");
+            for (i = 0; i < rt->nb_rtsp_streams; i++) {
+                rule_nr = 0;
+                for (r = 0; r < s->nb_streams; r++) {
+                    if (s->streams[r]->id == i) {
+                        if (s->streams[r]->discard != AVDISCARD_ALL) {
+                            if (!first)
+                                av_strlcat(rt->last_subscription, ",",
+                                           sizeof(rt->last_subscription));
+                            ff_rdt_subscribe_rule(
+                                rt->last_subscription,
+                                sizeof(rt->last_subscription), i, rule_nr);
+                            first = 0;
+                        }
+                        rule_nr++;
+                    }
+                }
+            }
+            av_strlcatf(cmd, sizeof(cmd), "%s\r\n", rt->last_subscription);
+            ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
+                             cmd, reply, NULL);
+            if (reply->status_code != RTSP_STATUS_OK)
+                return AVERROR_INVALIDDATA;
+            rt->need_subscription = 0;
+
+            if (rt->state == RTSP_STATE_STREAMING)
+                rtsp_read_play (s);
+        }
+    }
+
+    ret = ff_rtsp_fetch_packet(s, pkt);
+    if (ret < 0) {
+        if (ret == AVERROR(ETIMEDOUT) && !rt->packets) {
+            if (rt->lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
+                rt->lower_transport_mask & (1 << RTSP_LOWER_TRANSPORT_TCP)) {
+                RTSPMessageHeader reply1, *reply = &reply1;
+                av_log(s, AV_LOG_WARNING, "UDP timeout, retrying with TCP\n");
+                if (rtsp_read_pause(s) != 0)
+                    return -1;
+                // TEARDOWN is required on Real-RTSP, but might make
+                // other servers close the connection.
+                if (rt->server_type == RTSP_SERVER_REAL)
+                    ff_rtsp_send_cmd(s, "TEARDOWN", rt->control_uri, NULL,
+                                     reply, NULL);
+                rt->session_id[0] = '\0';
+                if (resetup_tcp(s) == 0) {
+                    rt->state = RTSP_STATE_IDLE;
+                    rt->need_subscription = 1;
+                    if (rtsp_read_play(s) != 0)
+                        return -1;
+                    goto retry;
+                }
+            }
+        }
+        return ret;
+    }
+    rt->packets++;
+
+    /* send dummy request to keep TCP connection alive */
+    if ((av_gettime() - rt->last_cmd_time) / 1000000 >= rt->timeout / 2) {
+        if (rt->server_type != RTSP_SERVER_REAL) {
+            ff_rtsp_send_cmd_async(s, "GET_PARAMETER", rt->control_uri, NULL);
+        } else {
+            ff_rtsp_send_cmd_async(s, "OPTIONS", "*", NULL);
+        }
+    }
+
+    return 0;
+}
+
+static int rtsp_read_seek(AVFormatContext *s, int stream_index,
+                          int64_t timestamp, int flags)
+{
+    RTSPState *rt = s->priv_data;
+
+    rt->seek_timestamp = av_rescale_q(timestamp,
+                                      s->streams[stream_index]->time_base,
+                                      AV_TIME_BASE_Q);
+    switch(rt->state) {
+    default:
+    case RTSP_STATE_IDLE:
+        break;
+    case RTSP_STATE_STREAMING:
+        if (rtsp_read_pause(s) != 0)
+            return -1;
+        rt->state = RTSP_STATE_SEEKING;
+        if (rtsp_read_play(s) != 0)
+            return -1;
+        break;
+    case RTSP_STATE_PAUSED:
+        rt->state = RTSP_STATE_IDLE;
+        break;
+    }
+    return 0;
+}
+
+static int rtsp_read_close(AVFormatContext *s)
+{
+    RTSPState *rt = s->priv_data;
+
+#if 0
+    /* NOTE: it is valid to flush the buffer here */
+    if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
+        avio_close(&rt->rtsp_gb);
+    }
+#endif
+    ff_rtsp_send_cmd_async(s, "TEARDOWN", rt->control_uri, NULL);
+
+    ff_rtsp_close_streams(s);
+    ff_rtsp_close_connections(s);
+    ff_network_close();
+    rt->real_setup = NULL;
+    av_freep(&rt->real_setup_cache);
+    return 0;
+}
+
+AVInputFormat ff_rtsp_demuxer = {
+    "rtsp",
+    NULL_IF_CONFIG_SMALL("RTSP input format"),
+    sizeof(RTSPState),
+    rtsp_probe,
+    rtsp_read_header,
+    rtsp_read_packet,
+    rtsp_read_close,
+    rtsp_read_seek,
+    .flags = AVFMT_NOFILE,
+    .read_play = rtsp_read_play,
+    .read_pause = rtsp_read_pause,
+};
diff --git a/libavformat/rtspenc.c b/libavformat/rtspenc.c
index f7aadd6..c1fc97c 100644
--- a/libavformat/rtspenc.c
+++ b/libavformat/rtspenc.c
@@ -2,32 +2,101 @@
  * RTSP muxer
  * Copyright (c) 2010 Martin Storsjo
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "avformat.h"
 
 #include <sys/time.h>
-#if HAVE_SYS_SELECT_H
-#include <sys/select.h>
+#if HAVE_POLL_H
+#include <poll.h>
 #endif
 #include "network.h"
+#include "os_support.h"
 #include "rtsp.h"
-#include <libavutil/intreadwrite.h>
+#include "internal.h"
+#include "avio_internal.h"
+#include "libavutil/intreadwrite.h"
+#include "libavutil/avstring.h"
+#include "url.h"
+
+#define SDP_MAX_SIZE 16384
+
+int ff_rtsp_setup_output_streams(AVFormatContext *s, const char *addr)
+{
+    RTSPState *rt = s->priv_data;
+    RTSPMessageHeader reply1, *reply = &reply1;
+    int i;
+    char *sdp;
+    AVFormatContext sdp_ctx, *ctx_array[1];
+
+    s->start_time_realtime = av_gettime();
+
+    /* Announce the stream */
+    sdp = av_mallocz(SDP_MAX_SIZE);
+    if (sdp == NULL)
+        return AVERROR(ENOMEM);
+    /* We create the SDP based on the RTSP AVFormatContext where we
+     * aren't allowed to change the filename field. (We create the SDP
+     * based on the RTSP context since the contexts for the RTP streams
+     * don't exist yet.) In order to specify a custom URL with the actual
+     * peer IP instead of the originally specified hostname, we create
+     * a temporary copy of the AVFormatContext, where the custom URL is set.
+     *
+     * FIXME: Create the SDP without copying the AVFormatContext.
+     * This either requires setting up the RTP stream AVFormatContexts
+     * already here (complicating things immensely) or getting a more
+     * flexible SDP creation interface.
+     */
+    sdp_ctx = *s;
+    ff_url_join(sdp_ctx.filename, sizeof(sdp_ctx.filename),
+                "rtsp", NULL, addr, -1, NULL);
+    ctx_array[0] = &sdp_ctx;
+    if (av_sdp_create(ctx_array, 1, sdp, SDP_MAX_SIZE)) {
+        av_free(sdp);
+        return AVERROR_INVALIDDATA;
+    }
+    av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", sdp);
+    ff_rtsp_send_cmd_with_content(s, "ANNOUNCE", rt->control_uri,
+                                  "Content-Type: application/sdp\r\n",
+                                  reply, NULL, sdp, strlen(sdp));
+    av_free(sdp);
+    if (reply->status_code != RTSP_STATUS_OK)
+        return AVERROR_INVALIDDATA;
+
+    /* Set up the RTSPStreams for each AVStream */
+    for (i = 0; i < s->nb_streams; i++) {
+        RTSPStream *rtsp_st;
+
+        rtsp_st = av_mallocz(sizeof(RTSPStream));
+        if (!rtsp_st)
+            return AVERROR(ENOMEM);
+        dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
+
+        rtsp_st->stream_index = i;
+
+        av_strlcpy(rtsp_st->control_url, rt->control_uri, sizeof(rtsp_st->control_url));
+        /* Note, this must match the relative uri set in the sdp content */
+        av_strlcatf(rtsp_st->control_url, sizeof(rtsp_st->control_url),
+                    "/streamid=%d", i);
+    }
+
+    return 0;
+}
 
 static int rtsp_write_record(AVFormatContext *s)
 {
@@ -36,8 +105,7 @@ static int rtsp_write_record(AVFormatContext *s)
     char cmd[1024];
 
     snprintf(cmd, sizeof(cmd),
-             "Range: npt=%0.3f-\r\n",
-             (double) 0);
+             "Range: npt=0.000-\r\n");
     ff_rtsp_send_cmd(s, "RECORD", rt->control_uri, cmd, reply, NULL);
     if (reply->status_code != RTSP_STATUS_OK)
         return -1;
@@ -47,7 +115,6 @@ static int rtsp_write_record(AVFormatContext *s)
 
 static int rtsp_write_header(AVFormatContext *s)
 {
-    RTSPState *rt = s->priv_data;
     int ret;
 
     ret = ff_rtsp_connect(s);
@@ -56,7 +123,7 @@ static int rtsp_write_header(AVFormatContext *s)
 
     if (rtsp_write_record(s) < 0) {
         ff_rtsp_close_streams(s);
-        url_close(rt->rtsp_hd);
+        ff_rtsp_close_connections(s);
         return AVERROR_INVALIDDATA;
     }
     return 0;
@@ -68,31 +135,36 @@ static int tcp_write_packet(AVFormatContext *s, RTSPStream *rtsp_st)
     AVFormatContext *rtpctx = rtsp_st->transport_priv;
     uint8_t *buf, *ptr;
     int size;
-    uint8_t interleave_header[4];
+    uint8_t *interleave_header, *interleaved_packet;
 
-    size = url_close_dyn_buf(rtpctx->pb, &buf);
+    size = avio_close_dyn_buf(rtpctx->pb, &buf);
     ptr = buf;
     while (size > 4) {
         uint32_t packet_len = AV_RB32(ptr);
         int id;
+        /* The interleaving header is exactly 4 bytes, which happens to be
+         * the same size as the packet length header from
+         * ffio_open_dyn_packet_buf. So by writing the interleaving header
+         * over these bytes, we get a consecutive interleaved packet
+         * that can be written in one call. */
+        interleaved_packet = interleave_header = ptr;
         ptr += 4;
         size -= 4;
         if (packet_len > size || packet_len < 2)
             break;
-        if (ptr[1] >= 200 && ptr[1] <= 204)
+        if (ptr[1] >= RTCP_SR && ptr[1] <= RTCP_APP)
             id = rtsp_st->interleaved_max; /* RTCP */
         else
             id = rtsp_st->interleaved_min; /* RTP */
         interleave_header[0] = '$';
         interleave_header[1] = id;
         AV_WB16(interleave_header + 2, packet_len);
-        url_write(rt->rtsp_hd, interleave_header, 4);
-        url_write(rt->rtsp_hd, ptr, packet_len);
+        ffurl_write(rt->rtsp_hd_out, interleaved_packet, 4 + packet_len);
         ptr += packet_len;
         size -= packet_len;
     }
     av_free(buf);
-    url_open_dyn_packet_buf(&rtpctx->pb, RTSP_TCP_MAX_PACKET_SIZE);
+    ffio_open_dyn_packet_buf(&rtpctx->pb, RTSP_TCP_MAX_PACKET_SIZE);
     return 0;
 }
 
@@ -100,31 +172,23 @@ static int rtsp_write_packet(AVFormatContext *s, AVPacket *pkt)
 {
     RTSPState *rt = s->priv_data;
     RTSPStream *rtsp_st;
-    fd_set rfds;
-    int n, tcp_fd;
-    struct timeval tv;
+    int n;
+    struct pollfd p = {ffurl_get_file_handle(rt->rtsp_hd), POLLIN, 0};
     AVFormatContext *rtpctx;
-    AVPacket local_pkt;
     int ret;
 
-    tcp_fd = url_get_file_handle(rt->rtsp_hd);
-
     while (1) {
-        FD_ZERO(&rfds);
-        FD_SET(tcp_fd, &rfds);
-        tv.tv_sec = 0;
-        tv.tv_usec = 0;
-        n = select(tcp_fd + 1, &rfds, NULL, NULL, &tv);
+        n = poll(&p, 1, 0);
         if (n <= 0)
             break;
-        if (FD_ISSET(tcp_fd, &rfds)) {
+        if (p.revents & POLLIN) {
             RTSPMessageHeader reply;
 
             /* Don't let ff_rtsp_read_reply handle interleaved packets,
              * since it would block and wait for an RTSP reply on the socket
              * (which may not be coming any time soon) if it handles
              * interleaved packets internally. */
-            ret = ff_rtsp_read_reply(s, &reply, NULL, 1);
+            ret = ff_rtsp_read_reply(s, &reply, NULL, 1, NULL);
             if (ret < 0)
                 return AVERROR(EPIPE);
             if (ret == 1)
@@ -140,12 +204,8 @@ static int rtsp_write_packet(AVFormatContext *s, AVPacket *pkt)
     rtsp_st = rt->rtsp_streams[pkt->stream_index];
     rtpctx = rtsp_st->transport_priv;
 
-    /* Use a local packet for writing to the chained muxer, otherwise
-     * the internal stream_index = 0 becomes visible to the muxer user. */
-    local_pkt = *pkt;
-    local_pkt.stream_index = 0;
-    ret = av_write_frame(rtpctx, &local_pkt);
-    /* av_write_frame does all the RTP packetization. If using TCP as
+    ret = ff_write_chained(rtpctx, 0, pkt, s);
+    /* ff_write_chained does all the RTP packetization. If using TCP as
      * transport, rtpctx->pb is only a dyn_packet_buf that queues up the
      * packets, so we need to send them out on the TCP connection separately.
      */
@@ -161,19 +221,19 @@ static int rtsp_write_close(AVFormatContext *s)
     ff_rtsp_send_cmd_async(s, "TEARDOWN", rt->control_uri, NULL);
 
     ff_rtsp_close_streams(s);
-    url_close(rt->rtsp_hd);
+    ff_rtsp_close_connections(s);
     ff_network_close();
     return 0;
 }
 
-AVOutputFormat rtsp_muxer = {
+AVOutputFormat ff_rtsp_muxer = {
     "rtsp",
     NULL_IF_CONFIG_SMALL("RTSP output format"),
     NULL,
     NULL,
     sizeof(RTSPState),
-    CODEC_ID_PCM_MULAW,
-    CODEC_ID_NONE,
+    CODEC_ID_AAC,
+    CODEC_ID_MPEG4,
     rtsp_write_header,
     rtsp_write_packet,
     rtsp_write_close,
diff --git a/libavformat/sapdec.c b/libavformat/sapdec.c
new file mode 100644
index 0000000..1eb40b7
--- /dev/null
+++ b/libavformat/sapdec.c
@@ -0,0 +1,237 @@
+/*
+ * Session Announcement Protocol (RFC 2974) demuxer
+ * Copyright (c) 2010 Martin Storsjo
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "avformat.h"
+#include "libavutil/avstring.h"
+#include "libavutil/intreadwrite.h"
+#include "network.h"
+#include "os_support.h"
+#include "internal.h"
+#include "avio_internal.h"
+#include "url.h"
+#if HAVE_POLL_H
+#include <poll.h>
+#endif
+#include <sys/time.h>
+
+struct SAPState {
+    URLContext *ann_fd;
+    AVFormatContext *sdp_ctx;
+    AVIOContext sdp_pb;
+    uint16_t hash;
+    char *sdp;
+    int eof;
+};
+
+static int sap_probe(AVProbeData *p)
+{
+    if (av_strstart(p->filename, "sap:", NULL))
+        return AVPROBE_SCORE_MAX;
+    return 0;
+}
+
+static int sap_read_close(AVFormatContext *s)
+{
+    struct SAPState *sap = s->priv_data;
+    if (sap->sdp_ctx)
+        av_close_input_stream(sap->sdp_ctx);
+    if (sap->ann_fd)
+        ffurl_close(sap->ann_fd);
+    av_freep(&sap->sdp);
+    ff_network_close();
+    return 0;
+}
+
+static int sap_read_header(AVFormatContext *s,
+                           AVFormatParameters *ap)
+{
+    struct SAPState *sap = s->priv_data;
+    char host[1024], path[1024], url[1024];
+    uint8_t recvbuf[1500];
+    int port;
+    int ret, i;
+    AVInputFormat* infmt;
+
+    if (!ff_network_init())
+        return AVERROR(EIO);
+
+    av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port,
+                 path, sizeof(path), s->filename);
+    if (port < 0)
+        port = 9875;
+
+    if (!host[0]) {
+        /* Listen for announcements on sap.mcast.net if no host was specified */
+        av_strlcpy(host, "224.2.127.254", sizeof(host));
+    }
+
+    ff_url_join(url, sizeof(url), "udp", NULL, host, port, "?localport=%d",
+                port);
+    ret = ffurl_open(&sap->ann_fd, url, AVIO_RDONLY);
+    if (ret)
+        goto fail;
+
+    while (1) {
+        int addr_type, auth_len;
+        int pos;
+
+        ret = ffurl_read(sap->ann_fd, recvbuf, sizeof(recvbuf) - 1);
+        if (ret == AVERROR(EAGAIN))
+            continue;
+        if (ret < 0)
+            goto fail;
+        recvbuf[ret] = '\0'; /* Null terminate for easier parsing */
+        if (ret < 8) {
+            av_log(s, AV_LOG_WARNING, "Received too short packet\n");
+            continue;
+        }
+
+        if ((recvbuf[0] & 0xe0) != 0x20) {
+            av_log(s, AV_LOG_WARNING, "Unsupported SAP version packet "
+                                      "received\n");
+            continue;
+        }
+
+        if (recvbuf[0] & 0x04) {
+            av_log(s, AV_LOG_WARNING, "Received stream deletion "
+                                      "announcement\n");
+            continue;
+        }
+        addr_type = recvbuf[0] & 0x10;
+        auth_len  = recvbuf[1];
+        sap->hash = AV_RB16(&recvbuf[2]);
+        pos = 4;
+        if (addr_type)
+            pos += 16; /* IPv6 */
+        else
+            pos += 4; /* IPv4 */
+        pos += auth_len * 4;
+        if (pos + 4 >= ret) {
+            av_log(s, AV_LOG_WARNING, "Received too short packet\n");
+            continue;
+        }
+#define MIME "application/sdp"
+        if (strcmp(&recvbuf[pos], MIME) == 0) {
+            pos += strlen(MIME) + 1;
+        } else if (strncmp(&recvbuf[pos], "v=0\r\n", 5) == 0) {
+            // Direct SDP without a mime type
+        } else {
+            av_log(s, AV_LOG_WARNING, "Unsupported mime type %s\n",
+                                      &recvbuf[pos]);
+            continue;
+        }
+
+        sap->sdp = av_strdup(&recvbuf[pos]);
+        break;
+    }
+
+    av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", sap->sdp);
+    ffio_init_context(&sap->sdp_pb, sap->sdp, strlen(sap->sdp), 0, NULL, NULL,
+                  NULL, NULL);
+
+    infmt = av_find_input_format("sdp");
+    if (!infmt)
+        goto fail;
+    sap->sdp_ctx = avformat_alloc_context();
+    if (!sap->sdp_ctx) {
+        ret = AVERROR(ENOMEM);
+        goto fail;
+    }
+    sap->sdp_ctx->max_delay = s->max_delay;
+    ap->prealloced_context = 1;
+    ret = av_open_input_stream(&sap->sdp_ctx, &sap->sdp_pb, "temp.sdp",
+                               infmt, ap);
+    if (ret < 0)
+        goto fail;
+    if (sap->sdp_ctx->ctx_flags & AVFMTCTX_NOHEADER)
+        s->ctx_flags |= AVFMTCTX_NOHEADER;
+    for (i = 0; i < sap->sdp_ctx->nb_streams; i++) {
+        AVStream *st = av_new_stream(s, i);
+        if (!st) {
+            ret = AVERROR(ENOMEM);
+            goto fail;
+        }
+        avcodec_copy_context(st->codec, sap->sdp_ctx->streams[i]->codec);
+        st->time_base = sap->sdp_ctx->streams[i]->time_base;
+    }
+
+    return 0;
+
+fail:
+    sap_read_close(s);
+    return ret;
+}
+
+static int sap_fetch_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    struct SAPState *sap = s->priv_data;
+    int fd = ffurl_get_file_handle(sap->ann_fd);
+    int n, ret;
+    struct pollfd p = {fd, POLLIN, 0};
+    uint8_t recvbuf[1500];
+
+    if (sap->eof)
+        return AVERROR_EOF;
+
+    while (1) {
+        n = poll(&p, 1, 0);
+        if (n <= 0 || !(p.revents & POLLIN))
+            break;
+        ret = ffurl_read(sap->ann_fd, recvbuf, sizeof(recvbuf));
+        if (ret >= 8) {
+            uint16_t hash = AV_RB16(&recvbuf[2]);
+            /* Should ideally check the source IP address, too */
+            if (recvbuf[0] & 0x04 && hash == sap->hash) {
+                /* Stream deletion */
+                sap->eof = 1;
+                return AVERROR_EOF;
+            }
+        }
+    }
+    ret = av_read_frame(sap->sdp_ctx, pkt);
+    if (ret < 0)
+        return ret;
+    if (s->ctx_flags & AVFMTCTX_NOHEADER) {
+        while (sap->sdp_ctx->nb_streams > s->nb_streams) {
+            int i = s->nb_streams;
+            AVStream *st = av_new_stream(s, i);
+            if (!st) {
+                av_free_packet(pkt);
+                return AVERROR(ENOMEM);
+            }
+            avcodec_copy_context(st->codec, sap->sdp_ctx->streams[i]->codec);
+            st->time_base = sap->sdp_ctx->streams[i]->time_base;
+        }
+    }
+    return ret;
+}
+
+AVInputFormat ff_sap_demuxer = {
+    "sap",
+    NULL_IF_CONFIG_SMALL("SAP input format"),
+    sizeof(struct SAPState),
+    sap_probe,
+    sap_read_header,
+    sap_fetch_packet,
+    sap_read_close,
+    .flags = AVFMT_NOFILE,
+};
+
diff --git a/libavformat/sapenc.c b/libavformat/sapenc.c
new file mode 100644
index 0000000..455e653
--- /dev/null
+++ b/libavformat/sapenc.c
@@ -0,0 +1,265 @@
+/*
+ * Session Announcement Protocol (RFC 2974) muxer
+ * Copyright (c) 2010 Martin Storsjo
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "avformat.h"
+#include "libavutil/parseutils.h"
+#include "libavutil/random_seed.h"
+#include "libavutil/avstring.h"
+#include "libavutil/intreadwrite.h"
+#include "internal.h"
+#include "network.h"
+#include "os_support.h"
+#include "rtpenc_chain.h"
+#include "url.h"
+
+struct SAPState {
+    uint8_t    *ann;
+    int         ann_size;
+    URLContext *ann_fd;
+    int64_t     last_time;
+};
+
+static int sap_write_close(AVFormatContext *s)
+{
+    struct SAPState *sap = s->priv_data;
+    int i;
+
+    for (i = 0; i < s->nb_streams; i++) {
+        AVFormatContext *rtpctx = s->streams[i]->priv_data;
+        if (!rtpctx)
+            continue;
+        av_write_trailer(rtpctx);
+        avio_close(rtpctx->pb);
+        avformat_free_context(rtpctx);
+        s->streams[i]->priv_data = NULL;
+    }
+
+    if (sap->last_time && sap->ann && sap->ann_fd) {
+        sap->ann[0] |= 4; /* Session deletion*/
+        ffurl_write(sap->ann_fd, sap->ann, sap->ann_size);
+    }
+
+    av_freep(&sap->ann);
+    if (sap->ann_fd)
+        ffurl_close(sap->ann_fd);
+    ff_network_close();
+    return 0;
+}
+
+static int sap_write_header(AVFormatContext *s)
+{
+    struct SAPState *sap = s->priv_data;
+    char host[1024], path[1024], url[1024], announce_addr[50] = "";
+    char *option_list;
+    int port = 9875, base_port = 5004, i, pos = 0, same_port = 0, ttl = 255;
+    AVFormatContext **contexts = NULL;
+    int ret = 0;
+    struct sockaddr_storage localaddr;
+    socklen_t addrlen = sizeof(localaddr);
+    int udp_fd;
+
+    if (!ff_network_init())
+        return AVERROR(EIO);
+
+    /* extract hostname and port */
+    av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &base_port,
+                 path, sizeof(path), s->filename);
+    if (base_port < 0)
+        base_port = 5004;
+
+    /* search for options */
+    option_list = strrchr(path, '?');
+    if (option_list) {
+        char buf[50];
+        if (av_find_info_tag(buf, sizeof(buf), "announce_port", option_list)) {
+            port = strtol(buf, NULL, 10);
+        }
+        if (av_find_info_tag(buf, sizeof(buf), "same_port", option_list)) {
+            same_port = strtol(buf, NULL, 10);
+        }
+        if (av_find_info_tag(buf, sizeof(buf), "ttl", option_list)) {
+            ttl = strtol(buf, NULL, 10);
+        }
+        if (av_find_info_tag(buf, sizeof(buf), "announce_addr", option_list)) {
+            av_strlcpy(announce_addr, buf, sizeof(announce_addr));
+        }
+    }
+
+    if (!announce_addr[0]) {
+        struct addrinfo hints, *ai = NULL;
+        memset(&hints, 0, sizeof(hints));
+        hints.ai_family = AF_UNSPEC;
+        if (getaddrinfo(host, NULL, &hints, &ai)) {
+            av_log(s, AV_LOG_ERROR, "Unable to resolve %s\n", host);
+            ret = AVERROR(EIO);
+            goto fail;
+        }
+        if (ai->ai_family == AF_INET) {
+            /* Also known as sap.mcast.net */
+            av_strlcpy(announce_addr, "224.2.127.254", sizeof(announce_addr));
+#if HAVE_STRUCT_SOCKADDR_IN6
+        } else if (ai->ai_family == AF_INET6) {
+            /* With IPv6, you can use the same destination in many different
+             * multicast subnets, to choose how far you want it routed.
+             * This one is intended to be routed globally. */
+            av_strlcpy(announce_addr, "ff0e::2:7ffe", sizeof(announce_addr));
+#endif
+        } else {
+            freeaddrinfo(ai);
+            av_log(s, AV_LOG_ERROR, "Host %s resolved to unsupported "
+                                    "address family\n", host);
+            ret = AVERROR(EIO);
+            goto fail;
+        }
+        freeaddrinfo(ai);
+    }
+
+    contexts = av_mallocz(sizeof(AVFormatContext*) * s->nb_streams);
+    if (!contexts) {
+        ret = AVERROR(ENOMEM);
+        goto fail;
+    }
+
+    s->start_time_realtime = av_gettime();
+    for (i = 0; i < s->nb_streams; i++) {
+        URLContext *fd;
+
+        ff_url_join(url, sizeof(url), "rtp", NULL, host, base_port,
+                    "?ttl=%d", ttl);
+        if (!same_port)
+            base_port += 2;
+        ret = ffurl_open(&fd, url, AVIO_WRONLY);
+        if (ret) {
+            ret = AVERROR(EIO);
+            goto fail;
+        }
+        s->streams[i]->priv_data = contexts[i] =
+            ff_rtp_chain_mux_open(s, s->streams[i], fd, 0);
+        av_strlcpy(contexts[i]->filename, url, sizeof(contexts[i]->filename));
+    }
+
+    ff_url_join(url, sizeof(url), "udp", NULL, announce_addr, port,
+                "?ttl=%d&connect=1", ttl);
+    ret = ffurl_open(&sap->ann_fd, url, AVIO_WRONLY);
+    if (ret) {
+        ret = AVERROR(EIO);
+        goto fail;
+    }
+
+    udp_fd = ffurl_get_file_handle(sap->ann_fd);
+    if (getsockname(udp_fd, (struct sockaddr*) &localaddr, &addrlen)) {
+        ret = AVERROR(EIO);
+        goto fail;
+    }
+    if (localaddr.ss_family != AF_INET
+#if HAVE_STRUCT_SOCKADDR_IN6
+        && localaddr.ss_family != AF_INET6
+#endif
+        ) {
+        av_log(s, AV_LOG_ERROR, "Unsupported protocol family\n");
+        ret = AVERROR(EIO);
+        goto fail;
+    }
+    sap->ann_size = 8192;
+    sap->ann = av_mallocz(sap->ann_size);
+    if (!sap->ann) {
+        ret = AVERROR(EIO);
+        goto fail;
+    }
+    sap->ann[pos] = (1 << 5);
+#if HAVE_STRUCT_SOCKADDR_IN6
+    if (localaddr.ss_family == AF_INET6)
+        sap->ann[pos] |= 0x10;
+#endif
+    pos++;
+    sap->ann[pos++] = 0; /* Authentication length */
+    AV_WB16(&sap->ann[pos], av_get_random_seed());
+    pos += 2;
+    if (localaddr.ss_family == AF_INET) {
+        memcpy(&sap->ann[pos], &((struct sockaddr_in*)&localaddr)->sin_addr,
+               sizeof(struct in_addr));
+        pos += sizeof(struct in_addr);
+#if HAVE_STRUCT_SOCKADDR_IN6
+    } else {
+        memcpy(&sap->ann[pos], &((struct sockaddr_in6*)&localaddr)->sin6_addr,
+               sizeof(struct in6_addr));
+        pos += sizeof(struct in6_addr);
+#endif
+    }
+
+    av_strlcpy(&sap->ann[pos], "application/sdp", sap->ann_size - pos);
+    pos += strlen(&sap->ann[pos]) + 1;
+
+    if (av_sdp_create(contexts, s->nb_streams, &sap->ann[pos],
+                       sap->ann_size - pos)) {
+        ret = AVERROR_INVALIDDATA;
+        goto fail;
+    }
+    av_freep(&contexts);
+    av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", &sap->ann[pos]);
+    pos += strlen(&sap->ann[pos]);
+    sap->ann_size = pos;
+
+    if (sap->ann_size > sap->ann_fd->max_packet_size) {
+        av_log(s, AV_LOG_ERROR, "Announcement too large to send in one "
+                                "packet\n");
+        goto fail;
+    }
+
+    return 0;
+
+fail:
+    av_free(contexts);
+    sap_write_close(s);
+    return ret;
+}
+
+static int sap_write_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    AVFormatContext *rtpctx;
+    struct SAPState *sap = s->priv_data;
+    int64_t now = av_gettime();
+
+    if (!sap->last_time || now - sap->last_time > 5000000) {
+        int ret = ffurl_write(sap->ann_fd, sap->ann, sap->ann_size);
+        /* Don't abort even if we get "Destination unreachable" */
+        if (ret < 0 && ret != AVERROR(ECONNREFUSED))
+            return ret;
+        sap->last_time = now;
+    }
+    rtpctx = s->streams[pkt->stream_index]->priv_data;
+    return ff_write_chained(rtpctx, 0, pkt, s);
+}
+
+AVOutputFormat ff_sap_muxer = {
+    "sap",
+    NULL_IF_CONFIG_SMALL("SAP output format"),
+    NULL,
+    NULL,
+    sizeof(struct SAPState),
+    CODEC_ID_AAC,
+    CODEC_ID_MPEG4,
+    sap_write_header,
+    sap_write_packet,
+    sap_write_close,
+    .flags = AVFMT_NOFILE | AVFMT_GLOBALHEADER,
+};
+
diff --git a/libavformat/sauce.c b/libavformat/sauce.c
new file mode 100644
index 0000000..cf33ab7
--- /dev/null
+++ b/libavformat/sauce.c
@@ -0,0 +1,103 @@
+/*
+ * SAUCE header parser
+ * Copyright (c) 2010 Peter Ross <pross at xvid.org>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * SAUCE header parser
+ */
+
+#include "libavutil/intreadwrite.h"
+#include "avformat.h"
+#include "sauce.h"
+
+int ff_sauce_read(AVFormatContext *avctx, uint64_t *fsize, int *got_width, int get_height)
+{
+    AVIOContext *pb = avctx->pb;
+    char buf[36];
+    int datatype, filetype, t1, t2, nb_comments, flags;
+    uint64_t start_pos = avio_size(pb) - 128;
+
+    avio_seek(pb, start_pos, SEEK_SET);
+    if (avio_read(pb, buf, 7) != 7)
+        return -1;
+    if (memcmp(buf, "SAUCE00", 7))
+        return -1;
+
+#define GET_SAUCE_META(name,size) \
+    if (avio_read(pb, buf, size) == size && buf[0]) { \
+        buf[size] = 0; \
+        av_metadata_set2(&avctx->metadata, name, buf, 0); \
+    }
+
+    GET_SAUCE_META("title",     35)
+    GET_SAUCE_META("artist",    20)
+    GET_SAUCE_META("publisher", 20)
+    GET_SAUCE_META("date",      8)
+    avio_skip(pb, 4);
+    datatype    = avio_r8(pb);
+    filetype    = avio_r8(pb);
+    t1          = avio_rl16(pb);
+    t2          = avio_rl16(pb);
+    nb_comments = avio_r8(pb);
+    flags       = avio_r8(pb);
+    avio_skip(pb, 4);
+    GET_SAUCE_META("encoder",   22);
+
+    if (got_width && datatype && filetype) {
+        if ((datatype == 1 && filetype <=2) || (datatype == 5 && filetype == 255) || datatype == 6) {
+            if (t1) {
+                avctx->streams[0]->codec->width = t1<<3;
+                *got_width = 1;
+            }
+            if (get_height && t2)
+                avctx->streams[0]->codec->height = t2<<4;
+        } else if (datatype == 5) {
+            if (filetype > 1) {
+                avctx->streams[0]->codec->width = (filetype == 1 ? t1 : filetype) << 4;
+                *got_width = 1;
+            }
+            if (get_height && t2)
+                avctx->streams[0]->codec->height = t2<<4;
+        }
+    }
+
+    *fsize -= 128;
+
+    if (nb_comments > 0) {
+        avio_seek(pb, start_pos - 64*nb_comments - 5, SEEK_SET);
+        if (avio_read(pb, buf, 5) == 5 && !memcmp(buf, "COMNT", 5)) {
+            int i;
+            char *str = av_malloc(65*nb_comments + 1);
+            *fsize -= 64*nb_comments + 5;
+            if (!str)
+                return 0;
+            for (i = 0; i < nb_comments; i++) {
+                if (avio_read(pb, str + 65*i, 64) != 64)
+                    break;
+                str[65*i + 64] = '\n';
+            }
+            str[65*i] = 0;
+            av_metadata_set2(&avctx->metadata, "comment", str, AV_METADATA_DONT_STRDUP_VAL);
+        }
+    }
+
+    return 0;
+}
diff --git a/libavformat/sauce.h b/libavformat/sauce.h
new file mode 100644
index 0000000..62d8e68
--- /dev/null
+++ b/libavformat/sauce.h
@@ -0,0 +1,40 @@
+/*
+ * SAUCE header parser
+ * Copyright (c) 2010 Peter Ross <pross at xvid.org>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * SAUCE header parser
+ */
+
+#ifndef AVFORMAT_SAUCE_H
+#define AVFORMAT_SAUCE_H
+
+#include "avformat.h"
+
+/**
+ * @param avctx AVFormatContext
+ * @param[out] fsize return length of file, less SAUCE header
+ * @param[out] got_width set to non-zero if SAUCE header reported height
+ * @param get_height Tell SAUCE header to parse height
+ */
+int ff_sauce_read(AVFormatContext *avctx, uint64_t *fsize, int *got_width, int get_height);
+
+#endif /* AVFORMAT_SAUCE_H */
diff --git a/libavformat/sdp.c b/libavformat/sdp.c
index 6bf05db..005434c 100644
--- a/libavformat/sdp.c
+++ b/libavformat/sdp.c
@@ -1,26 +1,28 @@
 /*
  * copyright (c) 2007 Luca Abeni
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include <string.h>
 #include "libavutil/avstring.h"
 #include "libavutil/base64.h"
+#include "libavutil/parseutils.h"
+#include "libavcodec/xiph.h"
 #include "avformat.h"
 #include "internal.h"
 #include "avc.h"
@@ -43,17 +45,24 @@ struct sdp_session_level {
     int ttl;              /**< TTL, in case of multicast stream */
     const char *user;     /**< username of the session's creator */
     const char *src_addr; /**< IP address of the machine from which the session was created */
+    const char *src_type; /**< address type of src_addr */
     const char *dst_addr; /**< destination IP address (can be multicast) */
+    const char *dst_type; /**< destination IP address type */
     const char *name;     /**< session name (can be an empty string) */
 };
 
-static void sdp_write_address(char *buff, int size, const char *dest_addr, int ttl)
+static void sdp_write_address(char *buff, int size, const char *dest_addr,
+                              const char *dest_type, int ttl)
 {
     if (dest_addr) {
-        if (ttl > 0) {
-            av_strlcatf(buff, size, "c=IN IP4 %s/%d\r\n", dest_addr, ttl);
+        if (!dest_type)
+            dest_type = "IP4";
+        if (ttl > 0 && !strcmp(dest_type, "IP4")) {
+            /* The TTL should only be specified for IPv4 multicast addresses,
+             * not for IPv6. */
+            av_strlcatf(buff, size, "c=IN %s %s/%d\r\n", dest_type, dest_addr, ttl);
         } else {
-            av_strlcatf(buff, size, "c=IN IP4 %s\r\n", dest_addr);
+            av_strlcatf(buff, size, "c=IN %s %s\r\n", dest_type, dest_addr);
         }
     }
 }
@@ -61,45 +70,49 @@ static void sdp_write_address(char *buff, int size, const char *dest_addr, int t
 static void sdp_write_header(char *buff, int size, struct sdp_session_level *s)
 {
     av_strlcatf(buff, size, "v=%d\r\n"
-                            "o=- %d %d IN IP4 %s\r\n"
+                            "o=- %d %d IN %s %s\r\n"
                             "s=%s\r\n",
                             s->sdp_version,
-                            s->id, s->version, s->src_addr,
+                            s->id, s->version, s->src_type, s->src_addr,
                             s->name);
-    sdp_write_address(buff, size, s->dst_addr, s->ttl);
+    sdp_write_address(buff, size, s->dst_addr, s->dst_type, s->ttl);
     av_strlcatf(buff, size, "t=%d %d\r\n"
                             "a=tool:libavformat " AV_STRINGIFY(LIBAVFORMAT_VERSION) "\r\n",
                             s->start_time, s->end_time);
 }
 
 #if CONFIG_NETWORK
-static void resolve_destination(char *dest_addr, int size)
+static int resolve_destination(char *dest_addr, int size, char *type,
+                               int type_size)
 {
-    struct addrinfo hints, *ai, *cur;
+    struct addrinfo hints, *ai;
+    int is_multicast;
 
+    av_strlcpy(type, "IP4", type_size);
     if (!dest_addr[0])
-        return;
+        return 0;
 
     /* Resolve the destination, since it must be written
      * as a numeric IP address in the SDP. */
 
     memset(&hints, 0, sizeof(hints));
-    /* We only support IPv4 addresses in the SDP at the moment. */
-    hints.ai_family = AF_INET;
     if (getaddrinfo(dest_addr, NULL, &hints, &ai))
-        return;
-    for (cur = ai; cur; cur = cur->ai_next) {
-        if (cur->ai_family == AF_INET) {
-            getnameinfo(cur->ai_addr, cur->ai_addrlen, dest_addr, size,
-                        NULL, 0, NI_NUMERICHOST);
-            break;
-        }
-    }
+        return 0;
+    getnameinfo(ai->ai_addr, ai->ai_addrlen, dest_addr, size,
+                NULL, 0, NI_NUMERICHOST);
+#ifdef AF_INET6
+    if (ai->ai_family == AF_INET6)
+        av_strlcpy(type, "IP6", type_size);
+#endif
+    is_multicast = ff_is_multicast_address(ai->ai_addr);
     freeaddrinfo(ai);
+    return is_multicast;
 }
 #else
-static void resolve_destination(char *dest_addr, int size)
+static int resolve_destination(char *dest_addr, int size, char *type,
+                               int type_size)
 {
+    return 0;
 }
 #endif
 
@@ -109,7 +122,7 @@ static int sdp_get_address(char *dest_addr, int size, int *ttl, const char *url)
     const char *p;
     char proto[32];
 
-    ff_url_split(proto, sizeof(proto), NULL, 0, dest_addr, size, &port, NULL, 0, url);
+    av_url_split(proto, sizeof(proto), NULL, 0, dest_addr, size, &port, NULL, 0, url);
 
     *ttl = 0;
 
@@ -123,14 +136,11 @@ static int sdp_get_address(char *dest_addr, int size, int *ttl, const char *url)
     p = strchr(url, '?');
     if (p) {
         char buff[64];
-        int is_multicast = find_info_tag(buff, sizeof(buff), "multicast", p);
 
-        if (is_multicast) {
-            if (find_info_tag(buff, sizeof(buff), "ttl", p)) {
-                *ttl = strtol(buff, NULL, 10);
-            } else {
-                *ttl = 5;
-            }
+        if (av_find_info_tag(buff, sizeof(buff), "ttl", p)) {
+            *ttl = strtol(buff, NULL, 10);
+        } else {
+            *ttl = 5;
         }
     }
 
@@ -149,6 +159,19 @@ static char *extradata2psets(AVCodecContext *c)
 
         return NULL;
     }
+    if (c->extradata[0] == 1) {
+        uint8_t *dummy_p;
+        int dummy_int;
+        AVBitStreamFilterContext *bsfc= av_bitstream_filter_init("h264_mp4toannexb");
+
+        if (!bsfc) {
+            av_log(c, AV_LOG_ERROR, "Cannot open the h264_mp4toannexb BSF!\n");
+
+            return NULL;
+        }
+        av_bitstream_filter_filter(bsfc, c, NULL, &dummy_p, &dummy_int, NULL, 0, 0);
+        av_bitstream_filter_close(bsfc);
+    }
 
     psets = av_mallocz(MAX_PSET_SIZE);
     if (psets == NULL) {
@@ -207,6 +230,75 @@ static char *extradata2config(AVCodecContext *c)
     return config;
 }
 
+static char *xiph_extradata2config(AVCodecContext *c)
+{
+    char *config, *encoded_config;
+    uint8_t *header_start[3];
+    int headers_len, header_len[3], config_len;
+    int first_header_size;
+
+    switch (c->codec_id) {
+    case CODEC_ID_THEORA:
+        first_header_size = 42;
+        break;
+    case CODEC_ID_VORBIS:
+        first_header_size = 30;
+        break;
+    default:
+        av_log(c, AV_LOG_ERROR, "Unsupported Xiph codec ID\n");
+        return NULL;
+    }
+
+    if (ff_split_xiph_headers(c->extradata, c->extradata_size,
+                              first_header_size, header_start,
+                              header_len) < 0) {
+        av_log(c, AV_LOG_ERROR, "Extradata corrupt.\n");
+        return NULL;
+    }
+
+    headers_len = header_len[0] + header_len[2];
+    config_len = 4 +          // count
+                 3 +          // ident
+                 2 +          // packet size
+                 1 +          // header count
+                 2 +          // header size
+                 headers_len; // and the rest
+
+    config = av_malloc(config_len);
+    if (!config)
+        goto xiph_fail;
+
+    encoded_config = av_malloc(AV_BASE64_SIZE(config_len));
+    if (!encoded_config) {
+        av_free(config);
+        goto xiph_fail;
+    }
+
+    config[0] = config[1] = config[2] = 0;
+    config[3] = 1;
+    config[4] = (RTP_XIPH_IDENT >> 16) & 0xff;
+    config[5] = (RTP_XIPH_IDENT >>  8) & 0xff;
+    config[6] = (RTP_XIPH_IDENT      ) & 0xff;
+    config[7] = (headers_len >> 8) & 0xff;
+    config[8] = headers_len & 0xff;
+    config[9] = 2;
+    config[10] = header_len[0];
+    config[11] = 0; // size of comment header; nonexistent
+    memcpy(config + 12, header_start[0], header_len[0]);
+    memcpy(config + 12 + header_len[0], header_start[2], header_len[2]);
+
+    av_base64_encode(encoded_config, AV_BASE64_SIZE(config_len),
+                     config, config_len);
+    av_free(config);
+
+    return encoded_config;
+
+xiph_fail:
+    av_log(c, AV_LOG_ERROR,
+           "Not enough memory for configuration string\n");
+    return NULL;
+}
+
 static char *sdp_write_media_attributes(char *buff, int size, AVCodecContext *c, int payload_type)
 {
     char *config = NULL;
@@ -223,7 +315,14 @@ static char *sdp_write_media_attributes(char *buff, int size, AVCodecContext *c,
             break;
         case CODEC_ID_H263:
         case CODEC_ID_H263P:
-            av_strlcatf(buff, size, "a=rtpmap:%d H263-2000/90000\r\n", payload_type);
+            /* a=framesize is required by 3GPP TS 26.234 (PSS). It
+             * actually specifies the maximum video size, but we only know
+             * the current size. This is required for playback on Android
+             * stagefright and on Samsung bada. */
+            av_strlcatf(buff, size, "a=rtpmap:%d H263-2000/90000\r\n"
+                                    "a=framesize:%d %d-%d\r\n",
+                                    payload_type,
+                                    payload_type, c->width, c->height);
             break;
         case CODEC_ID_MPEG4:
             if (c->extradata_size) {
@@ -284,6 +383,61 @@ static char *sdp_write_media_attributes(char *buff, int size, AVCodecContext *c,
                                      payload_type, c->sample_rate, c->channels,
                                      payload_type);
             break;
+        case CODEC_ID_VORBIS:
+            if (c->extradata_size)
+                config = xiph_extradata2config(c);
+            else
+                av_log(c, AV_LOG_ERROR, "Vorbis configuration info missing\n");
+            if (!config)
+                return NULL;
+
+            av_strlcatf(buff, size, "a=rtpmap:%d vorbis/%d/%d\r\n"
+                                    "a=fmtp:%d configuration=%s\r\n",
+                                    payload_type, c->sample_rate, c->channels,
+                                    payload_type, config);
+            break;
+        case CODEC_ID_THEORA: {
+            const char *pix_fmt;
+            if (c->extradata_size)
+                config = xiph_extradata2config(c);
+            else
+                av_log(c, AV_LOG_ERROR, "Theora configuation info missing\n");
+            if (!config)
+                return NULL;
+
+            switch (c->pix_fmt) {
+            case PIX_FMT_YUV420P:
+                pix_fmt = "YCbCr-4:2:0";
+                break;
+            case PIX_FMT_YUV422P:
+                pix_fmt = "YCbCr-4:2:2";
+                break;
+            case PIX_FMT_YUV444P:
+                pix_fmt = "YCbCr-4:4:4";
+                break;
+            default:
+                av_log(c, AV_LOG_ERROR, "Unsupported pixel format.\n");
+                return NULL;
+            }
+
+            av_strlcatf(buff, size, "a=rtpmap:%d theora/90000\r\n"
+                                    "a=fmtp:%d delivery-method=inline; "
+                                    "width=%d; height=%d; sampling=%s; "
+                                    "configuration=%s\r\n",
+                                    payload_type, payload_type,
+                                    c->width, c->height, pix_fmt, config);
+            break;
+        }
+        case CODEC_ID_VP8:
+            av_strlcatf(buff, size, "a=rtpmap:%d VP8/90000\r\n",
+                                     payload_type);
+            break;
+        case CODEC_ID_ADPCM_G722:
+            if (payload_type >= RTP_PT_PRIVATE)
+                av_strlcatf(buff, size, "a=rtpmap:%d G722/%d/%d\r\n",
+                                         payload_type,
+                                         8000, c->channels);
+            break;
         default:
             /* Nothing special to do here... */
             break;
@@ -294,7 +448,7 @@ static char *sdp_write_media_attributes(char *buff, int size, AVCodecContext *c,
     return buff;
 }
 
-void ff_sdp_write_media(char *buff, int size, AVCodecContext *c, const char *dest_addr, int port, int ttl)
+void ff_sdp_write_media(char *buff, int size, AVCodecContext *c, const char *dest_addr, const char *dest_type, int port, int ttl)
 {
     const char *type;
     int payload_type;
@@ -312,7 +466,7 @@ void ff_sdp_write_media(char *buff, int size, AVCodecContext *c, const char *des
     }
 
     av_strlcatf(buff, size, "m=%s %d RTP/AVP %d\r\n", type, port, payload_type);
-    sdp_write_address(buff, size, dest_addr, ttl);
+    sdp_write_address(buff, size, dest_addr, dest_type, ttl);
     if (c->bit_rate) {
         av_strlcatf(buff, size, "b=AS:%d\r\n", c->bit_rate / 1000);
     }
@@ -320,43 +474,55 @@ void ff_sdp_write_media(char *buff, int size, AVCodecContext *c, const char *des
     sdp_write_media_attributes(buff, size, c, payload_type);
 }
 
-int avf_sdp_create(AVFormatContext *ac[], int n_files, char *buff, int size)
+int av_sdp_create(AVFormatContext *ac[], int n_files, char *buf, int size)
 {
     AVMetadataTag *title = av_metadata_get(ac[0]->metadata, "title", NULL, 0);
     struct sdp_session_level s;
-    int i, j, port, ttl;
-    char dst[32];
+    int i, j, port, ttl, is_multicast;
+    char dst[32], dst_type[5];
 
-    memset(buff, 0, size);
+    memset(buf, 0, size);
     memset(&s, 0, sizeof(struct sdp_session_level));
     s.user = "-";
     s.src_addr = "127.0.0.1";    /* FIXME: Properly set this */
+    s.src_type = "IP4";
     s.name = title ? title->value : "No Name";
 
     port = 0;
     ttl = 0;
     if (n_files == 1) {
         port = sdp_get_address(dst, sizeof(dst), &ttl, ac[0]->filename);
-        resolve_destination(dst, sizeof(dst));
+        is_multicast = resolve_destination(dst, sizeof(dst), dst_type,
+                                           sizeof(dst_type));
+        if (!is_multicast)
+            ttl = 0;
         if (dst[0]) {
             s.dst_addr = dst;
+            s.dst_type = dst_type;
             s.ttl = ttl;
+            if (!strcmp(dst_type, "IP6")) {
+                s.src_addr = "::1";
+                s.src_type = "IP6";
+            }
         }
     }
-    sdp_write_header(buff, size, &s);
+    sdp_write_header(buf, size, &s);
 
     dst[0] = 0;
     for (i = 0; i < n_files; i++) {
         if (n_files != 1) {
             port = sdp_get_address(dst, sizeof(dst), &ttl, ac[i]->filename);
-            resolve_destination(dst, sizeof(dst));
+            is_multicast = resolve_destination(dst, sizeof(dst), dst_type,
+                                               sizeof(dst_type));
+            if (!is_multicast)
+                ttl = 0;
         }
         for (j = 0; j < ac[i]->nb_streams; j++) {
-            ff_sdp_write_media(buff, size,
+            ff_sdp_write_media(buf, size,
                                   ac[i]->streams[j]->codec, dst[0] ? dst : NULL,
-                                  (port > 0) ? port + j * 2 : 0, ttl);
+                                  dst_type, (port > 0) ? port + j * 2 : 0, ttl);
             if (port <= 0) {
-                av_strlcatf(buff, size,
+                av_strlcatf(buf, size,
                                    "a=control:streamid=%d\r\n", i + j);
             }
         }
@@ -365,13 +531,19 @@ int avf_sdp_create(AVFormatContext *ac[], int n_files, char *buff, int size)
     return 0;
 }
 #else
-int avf_sdp_create(AVFormatContext *ac[], int n_files, char *buff, int size)
+int av_sdp_create(AVFormatContext *ac[], int n_files, char *buf, int size)
 {
     return AVERROR(ENOSYS);
 }
 
-void ff_sdp_write_media(char *buff, int size, AVCodecContext *c,
-                        const char *dest_addr, int port, int ttl)
+void ff_sdp_write_media(char *buff, int size, AVCodecContext *c, const char *dest_addr, const char *dest_type, int port, int ttl)
+{
+}
+#endif
+
+#if FF_API_SDP_CREATE
+int avf_sdp_create(AVFormatContext *ac[], int n_files, char *buff, int size)
 {
+    return av_sdp_create(ac, n_files, buff, size);
 }
 #endif
diff --git a/libavformat/seek.c b/libavformat/seek.c
index 26b622f..71e2f8a 100644
--- a/libavformat/seek.c
+++ b/libavformat/seek.c
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2009 Ivan Schreter
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -313,7 +313,7 @@ int64_t ff_gen_syncpoint_search(AVFormatContext *s,
     step = s->pb->buffer_size;
     curpos = FFMAX(pos - step / 2, 0);
     for (;;) {
-        url_fseek(s->pb, curpos, SEEK_SET);
+        avio_seek(s->pb, curpos, SEEK_SET);
         search_hi_lo_keyframes(s,
                                ts, time_base,
                                flags,
@@ -385,7 +385,7 @@ int64_t ff_gen_syncpoint_search(AVFormatContext *s,
         }
     }
 
-    url_fseek(s->pb, pos, SEEK_SET);
+    avio_seek(s->pb, pos, SEEK_SET);
     av_free(sync);
     return pos;
 }
@@ -405,7 +405,7 @@ AVParserState *ff_store_parser_state(AVFormatContext *s)
         return NULL;
     }
 
-    state->fpos = url_ftell(s->pb);
+    state->fpos = avio_tell(s->pb);
 
     // copy context structures
     state->cur_st                           = s->cur_st;
@@ -456,7 +456,7 @@ void ff_restore_parser_state(AVFormatContext *s, AVParserState *state)
     if (!state)
         return;
 
-    url_fseek(s->pb, state->fpos, SEEK_SET);
+    avio_seek(s->pb, state->fpos, SEEK_SET);
 
     // copy context structures
     s->cur_st                           = state->cur_st;
diff --git a/libavformat/seek.h b/libavformat/seek.h
index 408f7d6..fd95f49 100644
--- a/libavformat/seek.h
+++ b/libavformat/seek.h
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2009 Ivan Schreter
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavformat/segafilm.c b/libavformat/segafilm.c
index 6274041..0ad5fbb 100644
--- a/libavformat/segafilm.c
+++ b/libavformat/segafilm.c
@@ -2,20 +2,20 @@
  * Sega FILM Format (CPK) Demuxer
  * Copyright (c) 2003 The ffmpeg Project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -77,7 +77,7 @@ static int film_read_header(AVFormatContext *s,
                             AVFormatParameters *ap)
 {
     FilmDemuxContext *film = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVStream *st;
     unsigned char scratch[256];
     int i;
@@ -89,7 +89,7 @@ static int film_read_header(AVFormatContext *s,
     film->stereo_buffer_size = 0;
 
     /* load the main FILM header */
-    if (get_buffer(pb, scratch, 16) != 16)
+    if (avio_read(pb, scratch, 16) != 16)
         return AVERROR(EIO);
     data_offset = AV_RB32(&scratch[4]);
     film->version = AV_RB32(&scratch[8]);
@@ -97,7 +97,7 @@ static int film_read_header(AVFormatContext *s,
     /* load the FDSC chunk */
     if (film->version == 0) {
         /* special case for Lemmings .film files; 20-byte header */
-        if (get_buffer(pb, scratch, 20) != 20)
+        if (avio_read(pb, scratch, 20) != 20)
             return AVERROR(EIO);
         /* make some assumptions about the audio parameters */
         film->audio_type = CODEC_ID_PCM_S8;
@@ -106,7 +106,7 @@ static int film_read_header(AVFormatContext *s,
         film->audio_bits = 8;
     } else {
         /* normal Saturn .cpk files; 32-byte header */
-        if (get_buffer(pb, scratch, 32) != 32)
+        if (avio_read(pb, scratch, 32) != 32)
             return AVERROR(EIO);
         film->audio_samplerate = AV_RB16(&scratch[24]);
         film->audio_channels = scratch[21];
@@ -158,7 +158,7 @@ static int film_read_header(AVFormatContext *s,
     }
 
     /* load the sample table */
-    if (get_buffer(pb, scratch, 16) != 16)
+    if (avio_read(pb, scratch, 16) != 16)
         return AVERROR(EIO);
     if (AV_RB32(&scratch[0]) != STAB_TAG)
         return AVERROR_INVALIDDATA;
@@ -174,7 +174,7 @@ static int film_read_header(AVFormatContext *s,
     audio_frame_counter = 0;
     for (i = 0; i < film->sample_count; i++) {
         /* load the next sample record and transfer it to an internal struct */
-        if (get_buffer(pb, scratch, 16) != 16) {
+        if (avio_read(pb, scratch, 16) != 16) {
             av_free(film->sample_table);
             return AVERROR(EIO);
         }
@@ -205,7 +205,7 @@ static int film_read_packet(AVFormatContext *s,
                             AVPacket *pkt)
 {
     FilmDemuxContext *film = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     film_sample *sample;
     int ret = 0;
     int i;
@@ -217,15 +217,15 @@ static int film_read_packet(AVFormatContext *s,
     sample = &film->sample_table[film->current_sample];
 
     /* position the stream (will probably be there anyway) */
-    url_fseek(pb, sample->sample_offset, SEEK_SET);
+    avio_seek(pb, sample->sample_offset, SEEK_SET);
 
     /* do a special song and dance when loading FILM Cinepak chunks */
     if ((sample->stream == film->video_stream_index) &&
         (film->video_type == CODEC_ID_CINEPAK)) {
-        pkt->pos= url_ftell(pb);
+        pkt->pos= avio_tell(pb);
         if (av_new_packet(pkt, sample->sample_size))
             return AVERROR(ENOMEM);
-        get_buffer(pb, pkt->data, sample->sample_size);
+        avio_read(pb, pkt->data, sample->sample_size);
     } else if ((sample->stream == film->audio_stream_index) &&
         (film->audio_channels == 2)) {
         /* stereo PCM needs to be interleaved */
@@ -240,8 +240,8 @@ static int film_read_packet(AVFormatContext *s,
             film->stereo_buffer = av_malloc(film->stereo_buffer_size);
         }
 
-        pkt->pos= url_ftell(pb);
-        ret = get_buffer(pb, film->stereo_buffer, sample->sample_size);
+        pkt->pos= avio_tell(pb);
+        ret = avio_read(pb, film->stereo_buffer, sample->sample_size);
         if (ret != sample->sample_size)
             ret = AVERROR(EIO);
 
@@ -282,7 +282,7 @@ static int film_read_close(AVFormatContext *s)
     return 0;
 }
 
-AVInputFormat segafilm_demuxer = {
+AVInputFormat ff_segafilm_demuxer = {
     "film_cpk",
     NULL_IF_CONFIG_SMALL("Sega FILM/CPK format"),
     sizeof(FilmDemuxContext),
diff --git a/libavformat/sierravmd.c b/libavformat/sierravmd.c
index c239f5c..c0fb222 100644
--- a/libavformat/sierravmd.c
+++ b/libavformat/sierravmd.c
@@ -2,20 +2,20 @@
  * Sierra VMD Format Demuxer
  * Copyright (c) 2004 The ffmpeg Project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -81,7 +81,7 @@ static int vmd_read_header(AVFormatContext *s,
                            AVFormatParameters *ap)
 {
     VmdDemuxContext *vmd = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVStream *st = NULL, *vst;
     unsigned int toc_offset;
     unsigned char *raw_frame_table;
@@ -95,11 +95,11 @@ static int vmd_read_header(AVFormatContext *s,
     int sound_buffers;
 
     /* fetch the main header, including the 2 header length bytes */
-    url_fseek(pb, 0, SEEK_SET);
-    if (get_buffer(pb, vmd->vmd_header, VMD_HEADER_SIZE) != VMD_HEADER_SIZE)
+    avio_seek(pb, 0, SEEK_SET);
+    if (avio_read(pb, vmd->vmd_header, VMD_HEADER_SIZE) != VMD_HEADER_SIZE)
         return AVERROR(EIO);
 
-    if(vmd->vmd_header[16] == 'i' && vmd->vmd_header[17] == 'v' && vmd->vmd_header[18] == '3')
+    if(vmd->vmd_header[24] == 'i' && vmd->vmd_header[25] == 'v' && vmd->vmd_header[26] == '3')
         vmd->is_indeo3 = 1;
     else
         vmd->is_indeo3 = 0;
@@ -155,7 +155,7 @@ static int vmd_read_header(AVFormatContext *s,
     toc_offset = AV_RL32(&vmd->vmd_header[812]);
     vmd->frame_count = AV_RL16(&vmd->vmd_header[6]);
     vmd->frames_per_block = AV_RL16(&vmd->vmd_header[18]);
-    url_fseek(pb, toc_offset, SEEK_SET);
+    avio_seek(pb, toc_offset, SEEK_SET);
 
     raw_frame_table = NULL;
     vmd->frame_table = NULL;
@@ -172,7 +172,7 @@ static int vmd_read_header(AVFormatContext *s,
         av_free(vmd->frame_table);
         return AVERROR(ENOMEM);
     }
-    if (get_buffer(pb, raw_frame_table, raw_frame_table_size) !=
+    if (avio_read(pb, raw_frame_table, raw_frame_table_size) !=
         raw_frame_table_size) {
         av_free(raw_frame_table);
         av_free(vmd->frame_table);
@@ -189,7 +189,7 @@ static int vmd_read_header(AVFormatContext *s,
             int type;
             uint32_t size;
 
-            get_buffer(pb, chunk, BYTES_PER_FRAME_RECORD);
+            avio_read(pb, chunk, BYTES_PER_FRAME_RECORD);
             type = chunk[0];
             size = AV_RL32(&chunk[2]);
             if(!size && type != 1)
@@ -234,7 +234,7 @@ static int vmd_read_packet(AVFormatContext *s,
                            AVPacket *pkt)
 {
     VmdDemuxContext *vmd = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int ret = 0;
     vmd_frame *frame;
 
@@ -243,16 +243,16 @@ static int vmd_read_packet(AVFormatContext *s,
 
     frame = &vmd->frame_table[vmd->current_frame];
     /* position the stream (will probably be there already) */
-    url_fseek(pb, frame->frame_offset, SEEK_SET);
+    avio_seek(pb, frame->frame_offset, SEEK_SET);
 
     if (av_new_packet(pkt, frame->frame_size + BYTES_PER_FRAME_RECORD))
         return AVERROR(ENOMEM);
-    pkt->pos= url_ftell(pb);
+    pkt->pos= avio_tell(pb);
     memcpy(pkt->data, frame->frame_record, BYTES_PER_FRAME_RECORD);
-    if(vmd->is_indeo3)
-        ret = get_buffer(pb, pkt->data, frame->frame_size);
+    if(vmd->is_indeo3 && frame->frame_record[0] == 0x02)
+        ret = avio_read(pb, pkt->data, frame->frame_size);
     else
-        ret = get_buffer(pb, pkt->data + BYTES_PER_FRAME_RECORD,
+        ret = avio_read(pb, pkt->data + BYTES_PER_FRAME_RECORD,
             frame->frame_size);
 
     if (ret != frame->frame_size) {
@@ -280,7 +280,7 @@ static int vmd_read_close(AVFormatContext *s)
     return 0;
 }
 
-AVInputFormat vmd_demuxer = {
+AVInputFormat ff_vmd_demuxer = {
     "vmd",
     NULL_IF_CONFIG_SMALL("Sierra VMD format"),
     sizeof(VmdDemuxContext),
diff --git a/libavformat/siff.c b/libavformat/siff.c
index 3a0b9bb..23c122f 100644
--- a/libavformat/siff.c
+++ b/libavformat/siff.c
@@ -2,20 +2,20 @@
  * Beam Software SIFF demuxer
  * Copyright (c) 2007 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -84,36 +84,36 @@ static int create_audio_stream(AVFormatContext *s, SIFFContext *c)
     return 0;
 }
 
-static int siff_parse_vbv1(AVFormatContext *s, SIFFContext *c, ByteIOContext *pb)
+static int siff_parse_vbv1(AVFormatContext *s, SIFFContext *c, AVIOContext *pb)
 {
     AVStream *st;
     int width, height;
 
-    if (get_le32(pb) != TAG_VBHD){
+    if (avio_rl32(pb) != TAG_VBHD){
         av_log(s, AV_LOG_ERROR, "Header chunk is missing\n");
         return -1;
     }
-    if(get_be32(pb) != 32){
+    if(avio_rb32(pb) != 32){
         av_log(s, AV_LOG_ERROR, "Header chunk size is incorrect\n");
         return -1;
     }
-    if(get_le16(pb) != 1){
+    if(avio_rl16(pb) != 1){
         av_log(s, AV_LOG_ERROR, "Incorrect header version\n");
         return -1;
     }
-    width = get_le16(pb);
-    height = get_le16(pb);
-    url_fskip(pb, 4);
-    c->frames = get_le16(pb);
+    width = avio_rl16(pb);
+    height = avio_rl16(pb);
+    avio_skip(pb, 4);
+    c->frames = avio_rl16(pb);
     if(!c->frames){
         av_log(s, AV_LOG_ERROR, "File contains no frames ???\n");
         return -1;
     }
-    c->bits = get_le16(pb);
-    c->rate = get_le16(pb);
+    c->bits = avio_rl16(pb);
+    c->rate = avio_rl16(pb);
     c->block_align = c->rate * (c->bits >> 3);
 
-    url_fskip(pb, 16); //zeroes
+    avio_skip(pb, 16); //zeroes
 
     st = av_new_stream(s, 0);
     if (!st)
@@ -135,33 +135,33 @@ static int siff_parse_vbv1(AVFormatContext *s, SIFFContext *c, ByteIOContext *pb
     return 0;
 }
 
-static int siff_parse_soun(AVFormatContext *s, SIFFContext *c, ByteIOContext *pb)
+static int siff_parse_soun(AVFormatContext *s, SIFFContext *c, AVIOContext *pb)
 {
-    if (get_le32(pb) != TAG_SHDR){
+    if (avio_rl32(pb) != TAG_SHDR){
         av_log(s, AV_LOG_ERROR, "Header chunk is missing\n");
         return -1;
     }
-    if(get_be32(pb) != 8){
+    if(avio_rb32(pb) != 8){
         av_log(s, AV_LOG_ERROR, "Header chunk size is incorrect\n");
         return -1;
     }
-    url_fskip(pb, 4); //unknown value
-    c->rate = get_le16(pb);
-    c->bits = get_le16(pb);
+    avio_skip(pb, 4); //unknown value
+    c->rate = avio_rl16(pb);
+    c->bits = avio_rl16(pb);
     c->block_align = c->rate * (c->bits >> 3);
     return create_audio_stream(s, c);
 }
 
 static int siff_read_header(AVFormatContext *s, AVFormatParameters *ap)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     SIFFContext *c = s->priv_data;
     uint32_t tag;
 
-    if (get_le32(pb) != TAG_SIFF)
+    if (avio_rl32(pb) != TAG_SIFF)
         return -1;
-    url_fskip(pb, 4); //ignore size
-    tag = get_le32(pb);
+    avio_skip(pb, 4); //ignore size
+    tag = avio_rl32(pb);
 
     if (tag != TAG_VBV1 && tag != TAG_SOUN){
         av_log(s, AV_LOG_ERROR, "Not a VBV file\n");
@@ -172,11 +172,11 @@ static int siff_read_header(AVFormatContext *s, AVFormatParameters *ap)
         return -1;
     if (tag == TAG_SOUN && siff_parse_soun(s, c, pb) < 0)
         return -1;
-    if (get_le32(pb) != MKTAG('B', 'O', 'D', 'Y')){
+    if (avio_rl32(pb) != MKTAG('B', 'O', 'D', 'Y')){
         av_log(s, AV_LOG_ERROR, "'BODY' chunk is missing\n");
         return -1;
     }
-    url_fskip(pb, 4); //ignore size
+    avio_skip(pb, 4); //ignore size
 
     return 0;
 }
@@ -190,12 +190,12 @@ static int siff_read_packet(AVFormatContext *s, AVPacket *pkt)
         if (c->cur_frame >= c->frames)
             return AVERROR(EIO);
         if (c->curstrm == -1){
-            c->pktsize = get_le32(s->pb) - 4;
-            c->flags = get_le16(s->pb);
+            c->pktsize = avio_rl32(s->pb) - 4;
+            c->flags = avio_rl16(s->pb);
             c->gmcsize = (c->flags & VB_HAS_GMC) ? 4 : 0;
             if (c->gmcsize)
-                get_buffer(s->pb, c->gmc, c->gmcsize);
-            c->sndsize = (c->flags & VB_HAS_AUDIO) ? get_le32(s->pb): 0;
+                avio_read(s->pb, c->gmc, c->gmcsize);
+            c->sndsize = (c->flags & VB_HAS_AUDIO) ? avio_rl32(s->pb): 0;
             c->curstrm = !!(c->flags & VB_HAS_AUDIO);
         }
 
@@ -206,7 +206,7 @@ static int siff_read_packet(AVFormatContext *s, AVPacket *pkt)
             AV_WL16(pkt->data, c->flags);
             if (c->gmcsize)
                 memcpy(pkt->data + 2, c->gmc, c->gmcsize);
-            get_buffer(s->pb, pkt->data + 2 + c->gmcsize, size - c->gmcsize - 2);
+            avio_read(s->pb, pkt->data + 2 + c->gmcsize, size - c->gmcsize - 2);
             pkt->stream_index = 0;
             c->curstrm = -1;
         }else{
@@ -227,7 +227,7 @@ static int siff_read_packet(AVFormatContext *s, AVPacket *pkt)
     return pkt->size;
 }
 
-AVInputFormat siff_demuxer = {
+AVInputFormat ff_siff_demuxer = {
     "siff",
     NULL_IF_CONFIG_SMALL("Beam Software SIFF"),
     sizeof(SIFFContext),
diff --git a/libavformat/smacker.c b/libavformat/smacker.c
index 0dcc286..01d1303 100644
--- a/libavformat/smacker.c
+++ b/libavformat/smacker.c
@@ -2,20 +2,20 @@
  * Smacker demuxer
  * Copyright (c) 2006 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -98,26 +98,26 @@ static int smacker_probe(AVProbeData *p)
 
 static int smacker_read_header(AVFormatContext *s, AVFormatParameters *ap)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     SmackerContext *smk = s->priv_data;
     AVStream *st, *ast[7];
     int i, ret;
     int tbase;
 
     /* read and check header */
-    smk->magic = get_le32(pb);
+    smk->magic = avio_rl32(pb);
     if (smk->magic != MKTAG('S', 'M', 'K', '2') && smk->magic != MKTAG('S', 'M', 'K', '4'))
         return -1;
-    smk->width = get_le32(pb);
-    smk->height = get_le32(pb);
-    smk->frames = get_le32(pb);
-    smk->pts_inc = (int32_t)get_le32(pb);
-    smk->flags = get_le32(pb);
+    smk->width = avio_rl32(pb);
+    smk->height = avio_rl32(pb);
+    smk->frames = avio_rl32(pb);
+    smk->pts_inc = (int32_t)avio_rl32(pb);
+    smk->flags = avio_rl32(pb);
     if(smk->flags & SMACKER_FLAG_RING_FRAME)
         smk->frames++;
     for(i = 0; i < 7; i++)
-        smk->audio[i] = get_le32(pb);
-    smk->treesize = get_le32(pb);
+        smk->audio[i] = avio_rl32(pb);
+    smk->treesize = avio_rl32(pb);
 
     if(smk->treesize >= UINT_MAX/4){ // smk->treesize + 16 must not overflow (this check is probably redundant)
         av_log(s, AV_LOG_ERROR, "treesize too large\n");
@@ -125,13 +125,13 @@ static int smacker_read_header(AVFormatContext *s, AVFormatParameters *ap)
     }
 
 //FIXME remove extradata "rebuilding"
-    smk->mmap_size = get_le32(pb);
-    smk->mclr_size = get_le32(pb);
-    smk->full_size = get_le32(pb);
-    smk->type_size = get_le32(pb);
+    smk->mmap_size = avio_rl32(pb);
+    smk->mclr_size = avio_rl32(pb);
+    smk->full_size = avio_rl32(pb);
+    smk->type_size = avio_rl32(pb);
     for(i = 0; i < 7; i++)
-        smk->rates[i] = get_le32(pb);
-    smk->pad = get_le32(pb);
+        smk->rates[i] = avio_rl32(pb);
+    smk->pad = avio_rl32(pb);
     /* setup data */
     if(smk->frames > 0xFFFFFF) {
         av_log(s, AV_LOG_ERROR, "Too many frames: %i\n", smk->frames);
@@ -144,10 +144,10 @@ static int smacker_read_header(AVFormatContext *s, AVFormatParameters *ap)
 
     /* read frame info */
     for(i = 0; i < smk->frames; i++) {
-        smk->frm_size[i] = get_le32(pb);
+        smk->frm_size[i] = avio_rl32(pb);
     }
     for(i = 0; i < smk->frames; i++) {
-        smk->frm_flags[i] = get_byte(pb);
+        smk->frm_flags[i] = avio_r8(pb);
     }
 
     /* init video codec */
@@ -207,19 +207,19 @@ static int smacker_read_header(AVFormatContext *s, AVFormatParameters *ap)
         av_free(smk->frm_flags);
         return -1;
     }
-    ret = get_buffer(pb, st->codec->extradata + 16, st->codec->extradata_size - 16);
+    ret = avio_read(pb, st->codec->extradata + 16, st->codec->extradata_size - 16);
     if(ret != st->codec->extradata_size - 16){
         av_free(smk->frm_size);
         av_free(smk->frm_flags);
         return AVERROR(EIO);
     }
-    ((int32_t*)st->codec->extradata)[0] = le2me_32(smk->mmap_size);
-    ((int32_t*)st->codec->extradata)[1] = le2me_32(smk->mclr_size);
-    ((int32_t*)st->codec->extradata)[2] = le2me_32(smk->full_size);
-    ((int32_t*)st->codec->extradata)[3] = le2me_32(smk->type_size);
+    ((int32_t*)st->codec->extradata)[0] = av_le2ne32(smk->mmap_size);
+    ((int32_t*)st->codec->extradata)[1] = av_le2ne32(smk->mclr_size);
+    ((int32_t*)st->codec->extradata)[2] = av_le2ne32(smk->full_size);
+    ((int32_t*)st->codec->extradata)[3] = av_le2ne32(smk->type_size);
 
     smk->curstream = -1;
-    smk->nextpos = url_ftell(pb);
+    smk->nextpos = avio_tell(pb);
 
     return 0;
 }
@@ -235,35 +235,35 @@ static int smacker_read_packet(AVFormatContext *s, AVPacket *pkt)
     int palchange = 0;
     int pos;
 
-    if (url_feof(s->pb) || smk->cur_frame >= smk->frames)
-        return AVERROR(EIO);
+    if (s->pb->eof_reached || smk->cur_frame >= smk->frames)
+        return AVERROR_EOF;
 
     /* if we demuxed all streams, pass another frame */
     if(smk->curstream < 0) {
-        url_fseek(s->pb, smk->nextpos, 0);
+        avio_seek(s->pb, smk->nextpos, 0);
         frame_size = smk->frm_size[smk->cur_frame] & (~3);
         flags = smk->frm_flags[smk->cur_frame];
         /* handle palette change event */
-        pos = url_ftell(s->pb);
+        pos = avio_tell(s->pb);
         if(flags & SMACKER_PAL){
             int size, sz, t, off, j, pos;
             uint8_t *pal = smk->pal;
             uint8_t oldpal[768];
 
             memcpy(oldpal, pal, 768);
-            size = get_byte(s->pb);
+            size = avio_r8(s->pb);
             size = size * 4 - 1;
             frame_size -= size;
             frame_size--;
             sz = 0;
-            pos = url_ftell(s->pb) + size;
+            pos = avio_tell(s->pb) + size;
             while(sz < 256){
-                t = get_byte(s->pb);
+                t = avio_r8(s->pb);
                 if(t & 0x80){ /* skip palette entries */
                     sz += (t & 0x7F) + 1;
                     pal += ((t & 0x7F) + 1) * 3;
                 } else if(t & 0x40){ /* copy with offset */
-                    off = get_byte(s->pb) * 3;
+                    off = avio_r8(s->pb) * 3;
                     j = (t & 0x3F) + 1;
                     while(j-- && sz < 256) {
                         *pal++ = oldpal[off + 0];
@@ -274,12 +274,12 @@ static int smacker_read_packet(AVFormatContext *s, AVPacket *pkt)
                     }
                 } else { /* new entries */
                     *pal++ = smk_pal[t];
-                    *pal++ = smk_pal[get_byte(s->pb) & 0x3F];
-                    *pal++ = smk_pal[get_byte(s->pb) & 0x3F];
+                    *pal++ = smk_pal[avio_r8(s->pb) & 0x3F];
+                    *pal++ = smk_pal[avio_r8(s->pb) & 0x3F];
                     sz++;
                 }
             }
-            url_fseek(s->pb, pos, 0);
+            avio_seek(s->pb, pos, 0);
             palchange |= 1;
         }
         flags >>= 1;
@@ -288,13 +288,13 @@ static int smacker_read_packet(AVFormatContext *s, AVPacket *pkt)
         for(i = 0; i < 7; i++) {
             if(flags & 1) {
                 int size;
-                size = get_le32(s->pb) - 4;
+                size = avio_rl32(s->pb) - 4;
                 frame_size -= size;
                 frame_size -= 4;
                 smk->curstream++;
                 smk->bufs[smk->curstream] = av_realloc(smk->bufs[smk->curstream], size);
                 smk->buf_sizes[smk->curstream] = size;
-                ret = get_buffer(s->pb, smk->bufs[smk->curstream], size);
+                ret = avio_read(s->pb, smk->bufs[smk->curstream], size);
                 if(ret != size)
                     return AVERROR(EIO);
                 smk->stream_id[smk->curstream] = smk->indexes[i];
@@ -307,13 +307,13 @@ static int smacker_read_packet(AVFormatContext *s, AVPacket *pkt)
             palchange |= 2;
         pkt->data[0] = palchange;
         memcpy(pkt->data + 1, smk->pal, 768);
-        ret = get_buffer(s->pb, pkt->data + 769, frame_size);
+        ret = avio_read(s->pb, pkt->data + 769, frame_size);
         if(ret != frame_size)
             return AVERROR(EIO);
         pkt->stream_index = smk->videoindex;
         pkt->size = ret + 769;
         smk->cur_frame++;
-        smk->nextpos = url_ftell(s->pb);
+        smk->nextpos = avio_tell(s->pb);
     } else {
         if (av_new_packet(pkt, smk->buf_sizes[smk->curstream]))
             return AVERROR(ENOMEM);
@@ -334,17 +334,14 @@ static int smacker_read_close(AVFormatContext *s)
     int i;
 
     for(i = 0; i < 7; i++)
-        if(smk->bufs[i])
-            av_free(smk->bufs[i]);
-    if(smk->frm_size)
-        av_free(smk->frm_size);
-    if(smk->frm_flags)
-        av_free(smk->frm_flags);
+        av_free(smk->bufs[i]);
+    av_free(smk->frm_size);
+    av_free(smk->frm_flags);
 
     return 0;
 }
 
-AVInputFormat smacker_demuxer = {
+AVInputFormat ff_smacker_demuxer = {
     "smk",
     NULL_IF_CONFIG_SMALL("Smacker video"),
     sizeof(SmackerContext),
diff --git a/libavformat/sol.c b/libavformat/sol.c
index 3ae2d04..1c9ce69 100644
--- a/libavformat/sol.c
+++ b/libavformat/sol.c
@@ -2,20 +2,20 @@
  * Sierra SOL demuxer
  * Copyright Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,7 +25,7 @@
 
 #include "libavutil/bswap.h"
 #include "avformat.h"
-#include "raw.h"
+#include "pcm.h"
 
 /* if we don't know the size in advance */
 #define AU_UNKNOWN_SIZE ((uint32_t)(~0))
@@ -34,7 +34,7 @@ static int sol_probe(AVProbeData *p)
 {
     /* check file header */
     uint16_t magic;
-    magic=le2me_16(*((uint16_t*)p->buf));
+    magic=av_le2ne16(*((uint16_t*)p->buf));
     if ((magic == 0x0B8D || magic == 0x0C0D || magic == 0x0C8D) &&
         p->buf[2] == 'S' && p->buf[3] == 'O' &&
         p->buf[4] == 'L' && p->buf[5] == 0)
@@ -87,21 +87,21 @@ static int sol_read_header(AVFormatContext *s,
 {
     int size;
     unsigned int magic,tag;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     unsigned int id, channels, rate, type;
     enum CodecID codec;
     AVStream *st;
 
     /* check ".snd" header */
-    magic = get_le16(pb);
-    tag = get_le32(pb);
+    magic = avio_rl16(pb);
+    tag = avio_rl32(pb);
     if (tag != MKTAG('S', 'O', 'L', 0))
         return -1;
-    rate = get_le16(pb);
-    type = get_byte(pb);
-    size = get_le32(pb);
+    rate = avio_rl16(pb);
+    type = avio_r8(pb);
+    size = avio_rl32(pb);
     if (magic != 0x0B8D)
-        get_byte(pb); /* newer SOLs contain padding byte */
+        avio_r8(pb); /* newer SOLs contain padding byte */
 
     codec = sol_codec_id(magic, type);
     channels = sol_channels(magic, type);
@@ -130,7 +130,7 @@ static int sol_read_packet(AVFormatContext *s,
 {
     int ret;
 
-    if (url_feof(s->pb))
+    if (s->pb->eof_reached)
         return AVERROR(EIO);
     ret= av_get_packet(s->pb, pkt, MAX_SIZE);
     pkt->stream_index = 0;
@@ -141,7 +141,7 @@ static int sol_read_packet(AVFormatContext *s,
     return 0;
 }
 
-AVInputFormat sol_demuxer = {
+AVInputFormat ff_sol_demuxer = {
     "sol",
     NULL_IF_CONFIG_SMALL("Sierra SOL format"),
     0,
diff --git a/libavformat/sox.h b/libavformat/sox.h
index f4a12e9..e59531b 100644
--- a/libavformat/sox.h
+++ b/libavformat/sox.h
@@ -2,20 +2,20 @@
  * SoX native format common data
  * Copyright (c) 2009 Daniel Verkamp <daniel at drv.nu>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavformat/soxdec.c b/libavformat/soxdec.c
index 42fa53e..74e5372 100644
--- a/libavformat/soxdec.c
+++ b/libavformat/soxdec.c
@@ -5,20 +5,20 @@
  * Based on libSoX sox-fmt.c
  * Copyright (c) 2008 robs at users.sourceforge.net
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -31,7 +31,7 @@
 
 #include "libavutil/intreadwrite.h"
 #include "avformat.h"
-#include "raw.h"
+#include "pcm.h"
 #include "sox.h"
 
 static int sox_probe(AVProbeData *p)
@@ -44,7 +44,7 @@ static int sox_probe(AVProbeData *p)
 static int sox_read_header(AVFormatContext *s,
                            AVFormatParameters *ap)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     unsigned header_size, comment_size;
     double sample_rate, sample_rate_frac;
     AVStream *st;
@@ -55,20 +55,20 @@ static int sox_read_header(AVFormatContext *s,
 
     st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
 
-    if (get_le32(pb) == SOX_TAG) {
+    if (avio_rl32(pb) == SOX_TAG) {
         st->codec->codec_id = CODEC_ID_PCM_S32LE;
-        header_size         = get_le32(pb);
-        url_fskip(pb, 8); /* sample count */
-        sample_rate         = av_int2dbl(get_le64(pb));
-        st->codec->channels = get_le32(pb);
-        comment_size        = get_le32(pb);
+        header_size         = avio_rl32(pb);
+        avio_skip(pb, 8); /* sample count */
+        sample_rate         = av_int2dbl(avio_rl64(pb));
+        st->codec->channels = avio_rl32(pb);
+        comment_size        = avio_rl32(pb);
     } else {
         st->codec->codec_id = CODEC_ID_PCM_S32BE;
-        header_size         = get_be32(pb);
-        url_fskip(pb, 8); /* sample count */
-        sample_rate         = av_int2dbl(get_be64(pb));
-        st->codec->channels = get_be32(pb);
-        comment_size        = get_be32(pb);
+        header_size         = avio_rb32(pb);
+        avio_skip(pb, 8); /* sample count */
+        sample_rate         = av_int2dbl(avio_rb64(pb));
+        st->codec->channels = avio_rb32(pb);
+        comment_size        = avio_rb32(pb);
     }
 
     if (comment_size > 0xFFFFFFFFU - SOX_FIXED_HDR - 4U) {
@@ -95,7 +95,7 @@ static int sox_read_header(AVFormatContext *s,
 
     if (comment_size && comment_size < UINT_MAX) {
         char *comment = av_malloc(comment_size+1);
-        if (get_buffer(pb, comment, comment_size) != comment_size) {
+        if (avio_read(pb, comment, comment_size) != comment_size) {
             av_freep(&comment);
             return AVERROR(EIO);
         }
@@ -105,7 +105,7 @@ static int sox_read_header(AVFormatContext *s,
                                AV_METADATA_DONT_STRDUP_VAL);
     }
 
-    url_fskip(pb, header_size - SOX_FIXED_HDR - comment_size);
+    avio_skip(pb, header_size - SOX_FIXED_HDR - comment_size);
 
     st->codec->sample_rate           = sample_rate;
     st->codec->bits_per_coded_sample = 32;
@@ -127,7 +127,7 @@ static int sox_read_packet(AVFormatContext *s,
 {
     int ret, size;
 
-    if (url_feof(s->pb))
+    if (s->pb->eof_reached)
         return AVERROR_EOF;
 
     size = SOX_SAMPLES*s->streams[0]->codec->block_align;
@@ -140,7 +140,7 @@ static int sox_read_packet(AVFormatContext *s,
     return 0;
 }
 
-AVInputFormat sox_demuxer = {
+AVInputFormat ff_sox_demuxer = {
     "sox",
     NULL_IF_CONFIG_SMALL("SoX native format"),
     0,
diff --git a/libavformat/soxenc.c b/libavformat/soxenc.c
index 918bfad..cb71d73 100644
--- a/libavformat/soxenc.c
+++ b/libavformat/soxenc.c
@@ -5,20 +5,20 @@
  * Based on libSoX sox-fmt.c
  * Copyright (c) 2008 robs at users.sourceforge.net
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -31,6 +31,7 @@
 
 #include "libavutil/intreadwrite.h"
 #include "avformat.h"
+#include "avio_internal.h"
 #include "sox.h"
 
 typedef struct {
@@ -40,7 +41,7 @@ typedef struct {
 static int sox_write_header(AVFormatContext *s)
 {
     SoXContext *sox = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVCodecContext *enc = s->streams[0]->codec;
     AVMetadataTag *comment;
     size_t comment_len = 0, comment_size;
@@ -53,66 +54,66 @@ static int sox_write_header(AVFormatContext *s)
     sox->header_size = SOX_FIXED_HDR + comment_size;
 
     if (enc->codec_id == CODEC_ID_PCM_S32LE) {
-        put_tag(pb, ".SoX");
-        put_le32(pb, sox->header_size);
-        put_le64(pb, 0); /* number of samples */
-        put_le64(pb, av_dbl2int(enc->sample_rate));
-        put_le32(pb, enc->channels);
-        put_le32(pb, comment_size);
+        ffio_wfourcc(pb, ".SoX");
+        avio_wl32(pb, sox->header_size);
+        avio_wl64(pb, 0); /* number of samples */
+        avio_wl64(pb, av_dbl2int(enc->sample_rate));
+        avio_wl32(pb, enc->channels);
+        avio_wl32(pb, comment_size);
     } else if (enc->codec_id == CODEC_ID_PCM_S32BE) {
-        put_tag(pb, "XoS.");
-        put_be32(pb, sox->header_size);
-        put_be64(pb, 0); /* number of samples */
-        put_be64(pb, av_dbl2int(enc->sample_rate));
-        put_be32(pb, enc->channels);
-        put_be32(pb, comment_size);
+        ffio_wfourcc(pb, "XoS.");
+        avio_wb32(pb, sox->header_size);
+        avio_wb64(pb, 0); /* number of samples */
+        avio_wb64(pb, av_dbl2int(enc->sample_rate));
+        avio_wb32(pb, enc->channels);
+        avio_wb32(pb, comment_size);
     } else {
         av_log(s, AV_LOG_ERROR, "invalid codec; use pcm_s32le or pcm_s32be\n");
         return -1;
     }
 
     if (comment_len)
-        put_buffer(pb, comment->value, comment_len);
+        avio_write(pb, comment->value, comment_len);
 
     for ( ; comment_size > comment_len; comment_len++)
-        put_byte(pb, 0);
+        avio_w8(pb, 0);
 
-    put_flush_packet(pb);
+    avio_flush(pb);
 
     return 0;
 }
 
 static int sox_write_packet(AVFormatContext *s, AVPacket *pkt)
 {
-    ByteIOContext *pb = s->pb;
-    put_buffer(pb, pkt->data, pkt->size);
+    AVIOContext *pb = s->pb;
+    avio_write(pb, pkt->data, pkt->size);
     return 0;
 }
 
 static int sox_write_trailer(AVFormatContext *s)
 {
     SoXContext *sox = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVCodecContext *enc = s->streams[0]->codec;
 
-    if (!url_is_streamed(s->pb)) {
+    if (s->pb->seekable) {
         /* update number of samples */
-        int64_t file_size = url_ftell(pb);
+        int64_t file_size = avio_tell(pb);
         int64_t num_samples = (file_size - sox->header_size - 4LL) >> 2LL;
-        url_fseek(pb, 8, SEEK_SET);
+        avio_seek(pb, 8, SEEK_SET);
         if (enc->codec_id == CODEC_ID_PCM_S32LE) {
-            put_le64(pb, num_samples);
+            avio_wl64(pb, num_samples);
         } else
-            put_be64(pb, num_samples);
-        url_fseek(pb, file_size, SEEK_SET);
+            avio_wb64(pb, num_samples);
+        avio_seek(pb, file_size, SEEK_SET);
 
-        put_flush_packet(pb);
+        avio_flush(pb);
     }
 
     return 0;
 }
 
-AVOutputFormat sox_muxer = {
+AVOutputFormat ff_sox_muxer = {
     "sox",
     NULL_IF_CONFIG_SMALL("SoX native format"),
     NULL,
diff --git a/libavformat/spdif.c b/libavformat/spdif.c
index 1c53f73..777ac47 100644
--- a/libavformat/spdif.c
+++ b/libavformat/spdif.c
@@ -1,306 +1,42 @@
 /*
- * IEC958 muxer
+ * IEC 61937 common code
  * Copyright (c) 2009 Bartlomiej Wolowiec
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
-/**
- * @file
- * IEC-61937 encapsulation of various formats, used by S/PDIF
- * @author Bartlomiej Wolowiec
- */
-
-/*
- * Terminology used in specification:
- * data-burst - IEC958 frame, contains header and encapsuled frame
- * burst-preambule - IEC958 frame header, contains 16-bits words named Pa, Pb, Pc and Pd
- * burst-payload - encapsuled frame
- * Pa, Pb - syncword - 0xF872, 0x4E1F
- * Pc - burst-info, contains data-type (bits 0-6), error flag (bit 7), data-type-dependent info (bits 8-12)
- *      and bitstream number (bits 13-15)
- * data-type - determines type of encapsuled frames
- * Pd - length code (number of bits or bytes of encapsuled frame - according to data_type)
- *
- * IEC958 frames at normal usage start every specific count of bytes,
- *      dependent from data-type (spaces between packets are filled by zeros)
- */
-
-#include "avformat.h"
-#include "libavcodec/ac3.h"
-#include "libavcodec/dca.h"
-#include "libavcodec/aac_parser.h"
-
-#define SYNCWORD1 0xF872
-#define SYNCWORD2 0x4E1F
-#define BURST_HEADER_SIZE 0x8
-
-enum IEC958DataType {
-    IEC958_AC3                = 0x01,          ///< AC-3 data
-    IEC958_MPEG1_LAYER1       = 0x04,          ///< MPEG-1 layer 1
-    IEC958_MPEG1_LAYER23      = 0x05,          ///< MPEG-1 layer 2 or 3 data or MPEG-2 without extension
-    IEC958_MPEG2_EXT          = 0x06,          ///< MPEG-2 data with extension
-    IEC958_MPEG2_AAC          = 0x07,          ///< MPEG-2 AAC ADTS
-    IEC958_MPEG2_LAYER1_LSF   = 0x08,          ///< MPEG-2, layer-1 low sampling frequency
-    IEC958_MPEG2_LAYER2_LSF   = 0x09,          ///< MPEG-2, layer-2 low sampling frequency
-    IEC958_MPEG2_LAYER3_LSF   = 0x0A,          ///< MPEG-2, layer-3 low sampling frequency
-    IEC958_DTS1               = 0x0B,          ///< DTS type I   (512 samples)
-    IEC958_DTS2               = 0x0C,          ///< DTS type II  (1024 samples)
-    IEC958_DTS3               = 0x0D,          ///< DTS type III (2048 samples)
-    IEC958_MPEG2_AAC_LSF_2048 = 0x13,          ///< MPEG-2 AAC ADTS half-rate low sampling frequency
-    IEC958_MPEG2_AAC_LSF_4096 = 0x13 | 0x20,   ///< MPEG-2 AAC ADTS quarter-rate low sampling frequency
-};
-
-typedef struct IEC958Context {
-    enum IEC958DataType data_type;  ///< burst info - reference to type of payload of the data-burst
-    int pkt_size;                   ///< length code in bits
-    int pkt_offset;                 ///< data burst repetition period in bytes
-    uint8_t *buffer;                ///< allocated buffer, used for swap bytes
-    int buffer_size;                ///< size of allocated buffer
-
-    /// function, which generates codec dependent header information.
-    /// Sets data_type and data_offset
-    int (*header_info) (AVFormatContext *s, AVPacket *pkt);
-} IEC958Context;
+#include "spdif.h"
+#include "libavutil/bswap.h"
 
 //TODO move to DSP
-static void bswap_buf16(uint16_t *dst, const uint16_t *src, int w)
+void ff_spdif_bswap_buf16(uint16_t *dst, const uint16_t *src, int w)
 {
     int i;
 
     for (i = 0; i + 8 <= w; i += 8) {
-        dst[i + 0] = bswap_16(src[i + 0]);
-        dst[i + 1] = bswap_16(src[i + 1]);
-        dst[i + 2] = bswap_16(src[i + 2]);
-        dst[i + 3] = bswap_16(src[i + 3]);
-        dst[i + 4] = bswap_16(src[i + 4]);
-        dst[i + 5] = bswap_16(src[i + 5]);
-        dst[i + 6] = bswap_16(src[i + 6]);
-        dst[i + 7] = bswap_16(src[i + 7]);
+        dst[i + 0] = av_bswap16(src[i + 0]);
+        dst[i + 1] = av_bswap16(src[i + 1]);
+        dst[i + 2] = av_bswap16(src[i + 2]);
+        dst[i + 3] = av_bswap16(src[i + 3]);
+        dst[i + 4] = av_bswap16(src[i + 4]);
+        dst[i + 5] = av_bswap16(src[i + 5]);
+        dst[i + 6] = av_bswap16(src[i + 6]);
+        dst[i + 7] = av_bswap16(src[i + 7]);
     }
     for (; i < w; i++)
-        dst[i + 0] = bswap_16(src[i + 0]);
-}
-
-static int spdif_header_ac3(AVFormatContext *s, AVPacket *pkt)
-{
-    IEC958Context *ctx = s->priv_data;
-    int bitstream_mode = pkt->data[6] & 0x7;
-
-    ctx->data_type  = IEC958_AC3 | (bitstream_mode << 8);
-    ctx->pkt_offset = AC3_FRAME_SIZE << 2;
-    return 0;
-}
-
-static int spdif_header_dts(AVFormatContext *s, AVPacket *pkt)
-{
-    IEC958Context *ctx = s->priv_data;
-    uint32_t syncword_dts = AV_RB32(pkt->data);
-    int blocks;
-
-    switch (syncword_dts) {
-    case DCA_MARKER_RAW_BE:
-        blocks = (AV_RB16(pkt->data + 4) >> 2) & 0x7f;
-        break;
-    case DCA_MARKER_RAW_LE:
-        blocks = (AV_RL16(pkt->data + 4) >> 2) & 0x7f;
-        break;
-    case DCA_MARKER_14B_BE:
-        blocks =
-            (((pkt->data[5] & 0x07) << 4) | ((pkt->data[6] & 0x3f) >> 2));
-        break;
-    case DCA_MARKER_14B_LE:
-        blocks =
-            (((pkt->data[4] & 0x07) << 4) | ((pkt->data[7] & 0x3f) >> 2));
-        break;
-    default:
-        av_log(s, AV_LOG_ERROR, "bad DTS syncword 0x%x\n", syncword_dts);
-        return -1;
-    }
-    blocks++;
-    switch (blocks) {
-    case  512 >> 5: ctx->data_type = IEC958_DTS1; break;
-    case 1024 >> 5: ctx->data_type = IEC958_DTS2; break;
-    case 2048 >> 5: ctx->data_type = IEC958_DTS3; break;
-    default:
-        av_log(s, AV_LOG_ERROR, "%i samples in DTS frame not supported\n",
-               blocks << 5);
-        return -1;
-    }
-    ctx->pkt_offset = blocks << 7;
-
-    return 0;
-}
-
-static const enum IEC958DataType mpeg_data_type[2][3] = {
-    //     LAYER1                      LAYER2                  LAYER3
-    { IEC958_MPEG2_LAYER1_LSF, IEC958_MPEG2_LAYER2_LSF, IEC958_MPEG2_LAYER3_LSF },  //MPEG2 LSF
-    { IEC958_MPEG1_LAYER1,     IEC958_MPEG1_LAYER23,    IEC958_MPEG1_LAYER23 },     //MPEG1
-};
-
-static const uint16_t mpeg_pkt_offset[2][3] = {
-    //LAYER1  LAYER2  LAYER3
-    { 3072,    9216,   4608 }, // MPEG2 LSF
-    { 1536,    4608,   4608 }, // MPEG1
-};
-
-static int spdif_header_mpeg(AVFormatContext *s, AVPacket *pkt)
-{
-    IEC958Context *ctx = s->priv_data;
-    int version =      (pkt->data[1] >> 3) & 3;
-    int layer   = 3 - ((pkt->data[1] >> 1) & 3);
-    int extension = pkt->data[2] & 1;
-
-    if (layer == 3 || version == 1) {
-        av_log(s, AV_LOG_ERROR, "Wrong MPEG file format\n");
-        return -1;
-    }
-    av_log(s, AV_LOG_DEBUG, "version: %i layer: %i extension: %i\n", version, layer, extension);
-    if (version == 2 && extension) {
-        ctx->data_type  = IEC958_MPEG2_EXT;
-        ctx->pkt_offset = 4608;
-    } else {
-        ctx->data_type  = mpeg_data_type [version & 1][layer];
-        ctx->pkt_offset = mpeg_pkt_offset[version & 1][layer];
-    }
-    // TODO Data type dependant info (normal/karaoke, dynamic range control)
-    return 0;
+        dst[i + 0] = av_bswap16(src[i + 0]);
 }
-
-static int spdif_header_aac(AVFormatContext *s, AVPacket *pkt)
-{
-    IEC958Context *ctx = s->priv_data;
-    AACADTSHeaderInfo hdr;
-    GetBitContext gbc;
-    int ret;
-
-    init_get_bits(&gbc, pkt->data, AAC_ADTS_HEADER_SIZE * 8);
-    ret = ff_aac_parse_header(&gbc, &hdr);
-    if (ret < 0) {
-        av_log(s, AV_LOG_ERROR, "Wrong AAC file format\n");
-        return -1;
-    }
-
-    ctx->pkt_offset = hdr.samples << 2;
-    switch (hdr.num_aac_frames) {
-    case 1:
-        ctx->data_type = IEC958_MPEG2_AAC;
-        break;
-    case 2:
-        ctx->data_type = IEC958_MPEG2_AAC_LSF_2048;
-        break;
-    case 4:
-        ctx->data_type = IEC958_MPEG2_AAC_LSF_4096;
-        break;
-    default:
-        av_log(s, AV_LOG_ERROR, "%i samples in AAC frame not supported\n",
-               hdr.samples);
-        return -1;
-    }
-    //TODO Data type dependent info (LC profile/SBR)
-    return 0;
-}
-
-static int spdif_write_header(AVFormatContext *s)
-{
-    IEC958Context *ctx = s->priv_data;
-
-    switch (s->streams[0]->codec->codec_id) {
-    case CODEC_ID_AC3:
-        ctx->header_info = spdif_header_ac3;
-        break;
-    case CODEC_ID_MP1:
-    case CODEC_ID_MP2:
-    case CODEC_ID_MP3:
-        ctx->header_info = spdif_header_mpeg;
-        break;
-    case CODEC_ID_DTS:
-        ctx->header_info = spdif_header_dts;
-        break;
-    case CODEC_ID_AAC:
-        ctx->header_info = spdif_header_aac;
-        break;
-    default:
-        av_log(s, AV_LOG_ERROR, "codec not supported\n");
-        return -1;
-    }
-    return 0;
-}
-
-static int spdif_write_trailer(AVFormatContext *s)
-{
-    IEC958Context *ctx = s->priv_data;
-    av_freep(&ctx->buffer);
-    return 0;
-}
-
-static int spdif_write_packet(struct AVFormatContext *s, AVPacket *pkt)
-{
-    IEC958Context *ctx = s->priv_data;
-    int ret, padding;
-
-    ctx->pkt_size = FFALIGN(pkt->size, 2) << 3;
-    ret = ctx->header_info(s, pkt);
-    if (ret < 0)
-        return -1;
-
-    padding = (ctx->pkt_offset - BURST_HEADER_SIZE - pkt->size) >> 1;
-    if (padding < 0) {
-        av_log(s, AV_LOG_ERROR, "bitrate is too high\n");
-        return -1;
-    }
-
-    put_le16(s->pb, SYNCWORD1);      //Pa
-    put_le16(s->pb, SYNCWORD2);      //Pb
-    put_le16(s->pb, ctx->data_type); //Pc
-    put_le16(s->pb, ctx->pkt_size);  //Pd
-
-#if HAVE_BIGENDIAN
-    put_buffer(s->pb, pkt->data, pkt->size & ~1);
-#else
-    av_fast_malloc(&ctx->buffer, &ctx->buffer_size, pkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
-    if (!ctx->buffer)
-        return AVERROR(ENOMEM);
-    bswap_buf16((uint16_t *)ctx->buffer, (uint16_t *)pkt->data, pkt->size >> 1);
-    put_buffer(s->pb, ctx->buffer, pkt->size & ~1);
-#endif
-
-    if (pkt->size & 1)
-        put_be16(s->pb, pkt->data[pkt->size - 1]);
-
-    for (; padding > 0; padding--)
-        put_be16(s->pb, 0);
-
-    av_log(s, AV_LOG_DEBUG, "type=%x len=%i pkt_offset=%i\n",
-           ctx->data_type, pkt->size, ctx->pkt_offset);
-
-    put_flush_packet(s->pb);
-    return 0;
-}
-
-AVOutputFormat spdif_muxer = {
-    "spdif",
-    NULL_IF_CONFIG_SMALL("IEC958 - S/PDIF (IEC-61937)"),
-    NULL,
-    "spdif",
-    sizeof(IEC958Context),
-    CODEC_ID_AC3,
-    CODEC_ID_NONE,
-    spdif_write_header,
-    spdif_write_packet,
-    spdif_write_trailer,
-};
diff --git a/libavformat/spdif.h b/libavformat/spdif.h
new file mode 100644
index 0000000..dedb4e8
--- /dev/null
+++ b/libavformat/spdif.h
@@ -0,0 +1,57 @@
+/*
+ * IEC 61937 common header
+ * Copyright (c) 2009 Bartlomiej Wolowiec
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <stdint.h>
+
+#define SYNCWORD1 0xF872
+#define SYNCWORD2 0x4E1F
+#define BURST_HEADER_SIZE 0x8
+
+enum IEC61937DataType {
+    IEC61937_AC3                = 0x01,          ///< AC-3 data
+    IEC61937_MPEG1_LAYER1       = 0x04,          ///< MPEG-1 layer 1
+    IEC61937_MPEG1_LAYER23      = 0x05,          ///< MPEG-1 layer 2 or 3 data or MPEG-2 without extension
+    IEC61937_MPEG2_EXT          = 0x06,          ///< MPEG-2 data with extension
+    IEC61937_MPEG2_AAC          = 0x07,          ///< MPEG-2 AAC ADTS
+    IEC61937_MPEG2_LAYER1_LSF   = 0x08,          ///< MPEG-2, layer-1 low sampling frequency
+    IEC61937_MPEG2_LAYER2_LSF   = 0x09,          ///< MPEG-2, layer-2 low sampling frequency
+    IEC61937_MPEG2_LAYER3_LSF   = 0x0A,          ///< MPEG-2, layer-3 low sampling frequency
+    IEC61937_DTS1               = 0x0B,          ///< DTS type I   (512 samples)
+    IEC61937_DTS2               = 0x0C,          ///< DTS type II  (1024 samples)
+    IEC61937_DTS3               = 0x0D,          ///< DTS type III (2048 samples)
+    IEC61937_ATRAC              = 0x0E,          ///< Atrac data
+    IEC61937_ATRAC3             = 0x0F,          ///< Atrac 3 data
+    IEC61937_ATRACX             = 0x10,          ///< Atrac 3 plus data
+    IEC61937_DTSHD              = 0x11,          ///< DTS HD data
+    IEC61937_WMAPRO             = 0x12,          ///< WMA 9 Professional data
+    IEC61937_MPEG2_AAC_LSF_2048 = 0x13,          ///< MPEG-2 AAC ADTS half-rate low sampling frequency
+    IEC61937_MPEG2_AAC_LSF_4096 = 0x13 | 0x20,   ///< MPEG-2 AAC ADTS quarter-rate low sampling frequency
+    IEC61937_EAC3               = 0x15,          ///< E-AC-3 data
+    IEC61937_TRUEHD             = 0x16,          ///< TrueHD data
+};
+
+static const uint16_t spdif_mpeg_pkt_offset[2][3] = {
+    //LAYER1  LAYER2  LAYER3
+    { 3072,    9216,   4608 }, // MPEG2 LSF
+    { 1536,    4608,   4608 }, // MPEG1
+};
+
+void ff_spdif_bswap_buf16(uint16_t *dst, const uint16_t *src, int w);
diff --git a/libavformat/spdifdec.c b/libavformat/spdifdec.c
new file mode 100644
index 0000000..1c09025
--- /dev/null
+++ b/libavformat/spdifdec.c
@@ -0,0 +1,236 @@
+/*
+ * IEC 61937 demuxer
+ * Copyright (c) 2010 Anssi Hannula <anssi.hannula at iki.fi>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * IEC 61937 demuxer, used for compressed data in S/PDIF
+ * @author Anssi Hannula
+ */
+
+#include "avformat.h"
+#include "spdif.h"
+#include "libavcodec/ac3.h"
+#include "libavcodec/aacadtsdec.h"
+
+static int spdif_get_offset_and_codec(AVFormatContext *s,
+                                      enum IEC61937DataType data_type,
+                                      const char *buf, int *offset,
+                                      enum CodecID *codec)
+{
+    AACADTSHeaderInfo aac_hdr;
+    GetBitContext gbc;
+
+    switch (data_type & 0xff) {
+    case IEC61937_AC3:
+        *offset = AC3_FRAME_SIZE << 2;
+        *codec = CODEC_ID_AC3;
+        break;
+    case IEC61937_MPEG1_LAYER1:
+        *offset = spdif_mpeg_pkt_offset[1][0];
+        *codec = CODEC_ID_MP1;
+        break;
+    case IEC61937_MPEG1_LAYER23:
+        *offset = spdif_mpeg_pkt_offset[1][0];
+        *codec = CODEC_ID_MP3;
+        break;
+    case IEC61937_MPEG2_EXT:
+        *offset = 4608;
+        *codec = CODEC_ID_MP3;
+        break;
+    case IEC61937_MPEG2_AAC:
+        init_get_bits(&gbc, buf, AAC_ADTS_HEADER_SIZE * 8);
+        if (ff_aac_parse_header(&gbc, &aac_hdr)) {
+            if (s) /* be silent during a probe */
+                av_log(s, AV_LOG_ERROR, "Invalid AAC packet in IEC 61937\n");
+            return AVERROR_INVALIDDATA;
+        }
+        *offset = aac_hdr.samples << 2;
+        *codec = CODEC_ID_AAC;
+        break;
+    case IEC61937_MPEG2_LAYER1_LSF:
+        *offset = spdif_mpeg_pkt_offset[0][0];
+        *codec = CODEC_ID_MP1;
+        break;
+    case IEC61937_MPEG2_LAYER2_LSF:
+        *offset = spdif_mpeg_pkt_offset[0][1];
+        *codec = CODEC_ID_MP2;
+        break;
+    case IEC61937_MPEG2_LAYER3_LSF:
+        *offset = spdif_mpeg_pkt_offset[0][2];
+        *codec = CODEC_ID_MP3;
+        break;
+    case IEC61937_DTS1:
+        *offset = 2048;
+        *codec = CODEC_ID_DTS;
+        break;
+    case IEC61937_DTS2:
+        *offset = 4096;
+        *codec = CODEC_ID_DTS;
+        break;
+    case IEC61937_DTS3:
+        *offset = 8192;
+        *codec = CODEC_ID_DTS;
+        break;
+    default:
+        if (s) { /* be silent during a probe */
+            av_log(s, AV_LOG_WARNING, "Data type 0x%04x", data_type);
+            av_log_missing_feature(s, " in IEC 61937 is", 1);
+        }
+        return AVERROR_PATCHWELCOME;
+    }
+    return 0;
+}
+
+/* Largest offset between bursts we currently handle, i.e. AAC with
+   aac_hdr.samples = 4096 */
+#define SPDIF_MAX_OFFSET 16384
+
+static int spdif_probe(AVProbeData *p)
+{
+    const uint8_t *buf = p->buf;
+    const uint8_t *probe_end = p->buf + FFMIN(2 * SPDIF_MAX_OFFSET, p->buf_size - 1);
+    const uint8_t *expected_code = buf + 7;
+    uint32_t state = 0;
+    int sync_codes = 0;
+    int consecutive_codes = 0;
+    int offset;
+    enum CodecID codec;
+
+    for (; buf < probe_end; buf++) {
+        state = (state << 8) | *buf;
+
+        if (state == (AV_BSWAP16C(SYNCWORD1) << 16 | AV_BSWAP16C(SYNCWORD2))
+                && buf[1] < 0x37) {
+            sync_codes++;
+
+            if (buf == expected_code) {
+                if (++consecutive_codes >= 2)
+                    return AVPROBE_SCORE_MAX;
+            } else
+                consecutive_codes = 0;
+
+            if (buf + 4 + AAC_ADTS_HEADER_SIZE > p->buf + p->buf_size)
+                break;
+
+            /* continue probing to find more sync codes */
+            probe_end = FFMIN(buf + SPDIF_MAX_OFFSET, p->buf + p->buf_size - 1);
+
+            /* skip directly to the next sync code */
+            if (!spdif_get_offset_and_codec(NULL, (buf[2] << 8) | buf[1],
+                                            &buf[5], &offset, &codec)) {
+                if (buf + offset >= p->buf + p->buf_size)
+                    break;
+                expected_code = buf + offset;
+                buf = expected_code - 7;
+            }
+        }
+    }
+
+    if (!sync_codes)
+        return 0;
+
+    if (sync_codes >= 6)
+        /* good amount of sync codes but with unexpected offsets */
+        return AVPROBE_SCORE_MAX / 2;
+
+    /* some sync codes were found */
+    return AVPROBE_SCORE_MAX / 8;
+}
+
+static int spdif_read_header(AVFormatContext *s, AVFormatParameters *ap)
+{
+    s->ctx_flags |= AVFMTCTX_NOHEADER;
+    return 0;
+}
+
+static int spdif_read_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    AVIOContext *pb = s->pb;
+    enum IEC61937DataType data_type;
+    enum CodecID codec_id;
+    uint32_t state = 0;
+    int pkt_size_bits, offset, ret;
+
+    while (state != (AV_BSWAP16C(SYNCWORD1) << 16 | AV_BSWAP16C(SYNCWORD2))) {
+        state = (state << 8) | avio_r8(pb);
+        if (pb->eof_reached)
+            return AVERROR_EOF;
+    }
+
+    data_type = avio_rl16(pb);
+    pkt_size_bits = avio_rl16(pb);
+
+    if (pkt_size_bits % 16)
+        av_log_ask_for_sample(s, "Packet does not end to a 16-bit boundary.");
+
+    ret = av_new_packet(pkt, FFALIGN(pkt_size_bits, 16) >> 3);
+    if (ret)
+        return ret;
+
+    pkt->pos = avio_tell(pb) - BURST_HEADER_SIZE;
+
+    if (avio_read(pb, pkt->data, pkt->size) < pkt->size) {
+        av_free_packet(pkt);
+        return AVERROR_EOF;
+    }
+    ff_spdif_bswap_buf16((uint16_t *)pkt->data, (uint16_t *)pkt->data, pkt->size >> 1);
+
+    ret = spdif_get_offset_and_codec(s, data_type, pkt->data,
+                                     &offset, &codec_id);
+    if (ret) {
+        av_free_packet(pkt);
+        return ret;
+    }
+
+    /* skip over the padding to the beginning of the next frame */
+    avio_skip(pb, offset - pkt->size - BURST_HEADER_SIZE);
+
+    if (!s->nb_streams) {
+        /* first packet, create a stream */
+        AVStream *st = av_new_stream(s, 0);
+        if (!st) {
+            av_free_packet(pkt);
+            return AVERROR(ENOMEM);
+        }
+        st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
+        st->codec->codec_id = codec_id;
+    } else if (codec_id != s->streams[0]->codec->codec_id) {
+        av_log_missing_feature(s, "codec change in IEC 61937", 0);
+        return AVERROR_PATCHWELCOME;
+    }
+
+    if (!s->bit_rate && s->streams[0]->codec->sample_rate)
+        /* stream bitrate matches 16-bit stereo PCM bitrate for currently
+           supported codecs */
+        s->bit_rate = 2 * 16 * s->streams[0]->codec->sample_rate;
+
+    return 0;
+}
+
+AVInputFormat ff_spdif_demuxer = {
+    "spdif",
+    NULL_IF_CONFIG_SMALL("IEC 61937 (compressed data in S/PDIF)"),
+    0,
+    spdif_probe,
+    spdif_read_header,
+    spdif_read_packet,
+    .flags = AVFMT_GENERIC_INDEX,
+};
diff --git a/libavformat/spdifenc.c b/libavformat/spdifenc.c
new file mode 100644
index 0000000..35c7b16
--- /dev/null
+++ b/libavformat/spdifenc.c
@@ -0,0 +1,551 @@
+/*
+ * IEC 61937 muxer
+ * Copyright (c) 2009 Bartlomiej Wolowiec
+ * Copyright (c) 2010 Anssi Hannula
+ * Copyright (c) 2010 Carl Eugen Hoyos
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * IEC-61937 encapsulation of various formats, used by S/PDIF
+ * @author Bartlomiej Wolowiec
+ * @author Anssi Hannula
+ * @author Carl Eugen Hoyos
+ */
+
+/*
+ * Terminology used in specification:
+ * data-burst - IEC61937 frame, contains header and encapsuled frame
+ * burst-preambule - IEC61937 frame header, contains 16-bits words named Pa, Pb, Pc and Pd
+ * burst-payload - encapsuled frame
+ * Pa, Pb - syncword - 0xF872, 0x4E1F
+ * Pc - burst-info, contains data-type (bits 0-6), error flag (bit 7), data-type-dependent info (bits 8-12)
+ *      and bitstream number (bits 13-15)
+ * data-type - determines type of encapsuled frames
+ * Pd - length code (number of bits or bytes of encapsuled frame - according to data_type)
+ *
+ * IEC 61937 frames at normal usage start every specific count of bytes,
+ *      dependent from data-type (spaces between packets are filled by zeros)
+ */
+
+#include "avformat.h"
+#include "avio_internal.h"
+#include "spdif.h"
+#include "libavcodec/ac3.h"
+#include "libavcodec/dca.h"
+#include "libavcodec/dcadata.h"
+#include "libavcodec/aacadtsdec.h"
+#include "libavutil/opt.h"
+
+typedef struct IEC61937Context {
+    const AVClass *av_class;
+    enum IEC61937DataType data_type;///< burst info - reference to type of payload of the data-burst
+    int length_code;                ///< length code in bits or bytes, depending on data type
+    int pkt_offset;                 ///< data burst repetition period in bytes
+    uint8_t *buffer;                ///< allocated buffer, used for swap bytes
+    int buffer_size;                ///< size of allocated buffer
+
+    uint8_t *out_buf;               ///< pointer to the outgoing data before byte-swapping
+    int out_bytes;                  ///< amount of outgoing bytes
+
+    int use_preamble;               ///< preamble enabled (disabled for exactly pre-padded DTS)
+    int extra_bswap;                ///< extra bswap for payload (for LE DTS => standard BE DTS)
+
+    uint8_t *hd_buf;                ///< allocated buffer to concatenate hd audio frames
+    int hd_buf_size;                ///< size of the hd audio buffer
+    int hd_buf_count;               ///< number of frames in the hd audio buffer
+    int hd_buf_filled;              ///< amount of bytes in the hd audio buffer
+
+    int dtshd_skip;                 ///< counter used for skipping DTS-HD frames
+
+    /* AVOptions: */
+    int dtshd_rate;
+    int dtshd_fallback;
+#define SPDIF_FLAG_BIGENDIAN    0x01
+    int spdif_flags;
+
+    /// function, which generates codec dependent header information.
+    /// Sets data_type and pkt_offset, and length_code, out_bytes, out_buf if necessary
+    int (*header_info) (AVFormatContext *s, AVPacket *pkt);
+} IEC61937Context;
+
+static const AVOption options[] = {
+{ "spdif_flags", "IEC 61937 encapsulation flags", offsetof(IEC61937Context, spdif_flags), FF_OPT_TYPE_FLAGS, 0, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "spdif_flags" },
+{ "be", "output in big-endian format (for use as s16be)", 0, FF_OPT_TYPE_CONST, SPDIF_FLAG_BIGENDIAN, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "spdif_flags" },
+{ "dtshd_rate", "mux complete DTS frames in HD mode at the specified IEC958 rate (in Hz, default 0=disabled)", offsetof(IEC61937Context, dtshd_rate), FF_OPT_TYPE_INT, 0, 0, 768000, AV_OPT_FLAG_ENCODING_PARAM },
+{ "dtshd_fallback_time", "min secs to strip HD for after an overflow (-1: till the end, default 60)", offsetof(IEC61937Context, dtshd_fallback), FF_OPT_TYPE_INT, 60, -1, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
+{ NULL },
+};
+
+static const AVClass class = { "spdif", av_default_item_name, options, LIBAVUTIL_VERSION_INT };
+
+static int spdif_header_ac3(AVFormatContext *s, AVPacket *pkt)
+{
+    IEC61937Context *ctx = s->priv_data;
+    int bitstream_mode = pkt->data[5] & 0x7;
+
+    ctx->data_type  = IEC61937_AC3 | (bitstream_mode << 8);
+    ctx->pkt_offset = AC3_FRAME_SIZE << 2;
+    return 0;
+}
+
+static int spdif_header_eac3(AVFormatContext *s, AVPacket *pkt)
+{
+    IEC61937Context *ctx = s->priv_data;
+    static const uint8_t eac3_repeat[4] = {6, 3, 2, 1};
+    int repeat = 1;
+
+    if ((pkt->data[4] & 0xc0) != 0xc0) /* fscod */
+        repeat = eac3_repeat[(pkt->data[4] & 0x30) >> 4]; /* numblkscod */
+
+    ctx->hd_buf = av_fast_realloc(ctx->hd_buf, &ctx->hd_buf_size, ctx->hd_buf_filled + pkt->size);
+    if (!ctx->hd_buf)
+        return AVERROR(ENOMEM);
+
+    memcpy(&ctx->hd_buf[ctx->hd_buf_filled], pkt->data, pkt->size);
+
+    ctx->hd_buf_filled += pkt->size;
+    if (++ctx->hd_buf_count < repeat){
+        ctx->pkt_offset = 0;
+        return 0;
+    }
+    ctx->data_type   = IEC61937_EAC3;
+    ctx->pkt_offset  = 24576;
+    ctx->out_buf     = ctx->hd_buf;
+    ctx->out_bytes   = ctx->hd_buf_filled;
+    ctx->length_code = ctx->hd_buf_filled;
+
+    ctx->hd_buf_count  = 0;
+    ctx->hd_buf_filled = 0;
+    return 0;
+}
+
+/*
+ * DTS type IV (DTS-HD) can be transmitted with various frame repetition
+ * periods; longer repetition periods allow for longer packets and therefore
+ * higher bitrate. Longer repetition periods mean that the constant bitrate of
+ * the outputted IEC 61937 stream is higher.
+ * The repetition period is measured in IEC 60958 frames (4 bytes).
+ */
+static int spdif_dts4_subtype(int period)
+{
+    switch (period) {
+    case 512:   return 0x0;
+    case 1024:  return 0x1;
+    case 2048:  return 0x2;
+    case 4096:  return 0x3;
+    case 8192:  return 0x4;
+    case 16384: return 0x5;
+    }
+    return -1;
+}
+
+static int spdif_header_dts4(AVFormatContext *s, AVPacket *pkt, int core_size,
+                             int sample_rate, int blocks)
+{
+    IEC61937Context *ctx = s->priv_data;
+    static const char dtshd_start_code[10] = { 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0xfe };
+    int pkt_size = pkt->size;
+    int period;
+    int subtype;
+
+    if (!core_size) {
+        av_log(s, AV_LOG_ERROR, "HD mode not supported for this format\n");
+        return AVERROR(EINVAL);
+    }
+
+    if (!sample_rate) {
+        av_log(s, AV_LOG_ERROR, "Unknown DTS sample rate for HD\n");
+        return AVERROR_INVALIDDATA;
+    }
+
+    period = ctx->dtshd_rate * (blocks << 5) / sample_rate;
+    subtype = spdif_dts4_subtype(period);
+
+    if (subtype < 0) {
+        av_log(s, AV_LOG_ERROR, "Specified HD rate of %d Hz would require an "
+               "impossible repetition period of %d for the current DTS stream"
+               " (blocks = %d, sample rate = %d)\n", ctx->dtshd_rate, period,
+               blocks << 5, sample_rate);
+        return AVERROR(EINVAL);
+    }
+
+    /* set pkt_offset and DTS IV subtype according to the requested output
+     * rate */
+    ctx->pkt_offset = period * 4;
+    ctx->data_type = IEC61937_DTSHD | subtype << 8;
+
+    /* If the bitrate is too high for transmitting at the selected
+     * repetition period setting, strip DTS-HD until a good amount
+     * of consecutive non-overflowing HD frames have been observed.
+     * This generally only happens if the caller is cramming a Master
+     * Audio stream into 192kHz IEC 60958 (which may or may not fit). */
+    if (sizeof(dtshd_start_code) + 2 + pkt_size
+            > ctx->pkt_offset - BURST_HEADER_SIZE && core_size) {
+        if (!ctx->dtshd_skip)
+            av_log(s, AV_LOG_WARNING, "DTS-HD bitrate too high, "
+                                      "temporarily sending core only\n");
+        if (ctx->dtshd_fallback > 0)
+            ctx->dtshd_skip = sample_rate * ctx->dtshd_fallback / (blocks << 5);
+        else
+            /* skip permanently (dtshd_fallback == -1) or just once
+             * (dtshd_fallback == 0) */
+            ctx->dtshd_skip = 1;
+    }
+    if (ctx->dtshd_skip && core_size) {
+        pkt_size = core_size;
+        if (ctx->dtshd_fallback >= 0)
+            --ctx->dtshd_skip;
+    }
+
+    ctx->out_bytes   = sizeof(dtshd_start_code) + 2 + pkt_size;
+    ctx->length_code = ctx->out_bytes;
+
+    av_fast_malloc(&ctx->hd_buf, &ctx->hd_buf_size, ctx->out_bytes);
+    if (!ctx->hd_buf)
+        return AVERROR(ENOMEM);
+
+    ctx->out_buf = ctx->hd_buf;
+
+    memcpy(ctx->hd_buf, dtshd_start_code, sizeof(dtshd_start_code));
+    AV_WB16(ctx->hd_buf + sizeof(dtshd_start_code), pkt_size);
+    memcpy(ctx->hd_buf + sizeof(dtshd_start_code) + 2, pkt->data, pkt_size);
+
+    return 0;
+}
+
+static int spdif_header_dts(AVFormatContext *s, AVPacket *pkt)
+{
+    IEC61937Context *ctx = s->priv_data;
+    uint32_t syncword_dts = AV_RB32(pkt->data);
+    int blocks;
+    int sample_rate = 0;
+    int core_size = 0;
+
+    if (pkt->size < 9)
+        return AVERROR_INVALIDDATA;
+
+    switch (syncword_dts) {
+    case DCA_MARKER_RAW_BE:
+        blocks = (AV_RB16(pkt->data + 4) >> 2) & 0x7f;
+        core_size = ((AV_RB24(pkt->data + 5) >> 4) & 0x3fff) + 1;
+        sample_rate = dca_sample_rates[(pkt->data[8] >> 2) & 0x0f];
+        break;
+    case DCA_MARKER_RAW_LE:
+        blocks = (AV_RL16(pkt->data + 4) >> 2) & 0x7f;
+        ctx->extra_bswap = 1;
+        break;
+    case DCA_MARKER_14B_BE:
+        blocks =
+            (((pkt->data[5] & 0x07) << 4) | ((pkt->data[6] & 0x3f) >> 2));
+        break;
+    case DCA_MARKER_14B_LE:
+        blocks =
+            (((pkt->data[4] & 0x07) << 4) | ((pkt->data[7] & 0x3f) >> 2));
+        ctx->extra_bswap = 1;
+        break;
+    case DCA_HD_MARKER:
+        /* We only handle HD frames that are paired with core. However,
+           sometimes DTS-HD streams with core have a stray HD frame without
+           core in the beginning of the stream. */
+        av_log(s, AV_LOG_ERROR, "stray DTS-HD frame\n");
+        return AVERROR_INVALIDDATA;
+    default:
+        av_log(s, AV_LOG_ERROR, "bad DTS syncword 0x%x\n", syncword_dts);
+        return AVERROR_INVALIDDATA;
+    }
+    blocks++;
+
+    if (ctx->dtshd_rate)
+        /* DTS type IV output requested */
+        return spdif_header_dts4(s, pkt, core_size, sample_rate, blocks);
+
+    switch (blocks) {
+    case  512 >> 5: ctx->data_type = IEC61937_DTS1; break;
+    case 1024 >> 5: ctx->data_type = IEC61937_DTS2; break;
+    case 2048 >> 5: ctx->data_type = IEC61937_DTS3; break;
+    default:
+        av_log(s, AV_LOG_ERROR, "%i samples in DTS frame not supported\n",
+               blocks << 5);
+        return AVERROR(ENOSYS);
+    }
+
+    /* discard extraneous data by default */
+    if (core_size && core_size < pkt->size) {
+        ctx->out_bytes = core_size;
+        ctx->length_code = core_size << 3;
+    }
+
+    ctx->pkt_offset = blocks << 7;
+
+    if (ctx->out_bytes == ctx->pkt_offset) {
+        /* The DTS stream fits exactly into the output stream, so skip the
+         * preamble as it would not fit in there. This is the case for dts
+         * discs and dts-in-wav. */
+        ctx->use_preamble = 0;
+    } else if (ctx->out_bytes > ctx->pkt_offset - BURST_HEADER_SIZE) {
+        av_log_ask_for_sample(s, "Unrecognized large DTS frame.");
+        /* This will fail with a "bitrate too high" in the caller */
+    }
+
+    return 0;
+}
+
+static const enum IEC61937DataType mpeg_data_type[2][3] = {
+    //     LAYER1                      LAYER2                  LAYER3
+    { IEC61937_MPEG2_LAYER1_LSF, IEC61937_MPEG2_LAYER2_LSF, IEC61937_MPEG2_LAYER3_LSF },//MPEG2 LSF
+    { IEC61937_MPEG1_LAYER1,     IEC61937_MPEG1_LAYER23,    IEC61937_MPEG1_LAYER23 },   //MPEG1
+};
+
+static int spdif_header_mpeg(AVFormatContext *s, AVPacket *pkt)
+{
+    IEC61937Context *ctx = s->priv_data;
+    int version =      (pkt->data[1] >> 3) & 3;
+    int layer   = 3 - ((pkt->data[1] >> 1) & 3);
+    int extension = pkt->data[2] & 1;
+
+    if (layer == 3 || version == 1) {
+        av_log(s, AV_LOG_ERROR, "Wrong MPEG file format\n");
+        return AVERROR_INVALIDDATA;
+    }
+    av_log(s, AV_LOG_DEBUG, "version: %i layer: %i extension: %i\n", version, layer, extension);
+    if (version == 2 && extension) {
+        ctx->data_type  = IEC61937_MPEG2_EXT;
+        ctx->pkt_offset = 4608;
+    } else {
+        ctx->data_type  = mpeg_data_type [version & 1][layer];
+        ctx->pkt_offset = spdif_mpeg_pkt_offset[version & 1][layer];
+    }
+    // TODO Data type dependant info (normal/karaoke, dynamic range control)
+    return 0;
+}
+
+static int spdif_header_aac(AVFormatContext *s, AVPacket *pkt)
+{
+    IEC61937Context *ctx = s->priv_data;
+    AACADTSHeaderInfo hdr;
+    GetBitContext gbc;
+    int ret;
+
+    init_get_bits(&gbc, pkt->data, AAC_ADTS_HEADER_SIZE * 8);
+    ret = ff_aac_parse_header(&gbc, &hdr);
+    if (ret < 0) {
+        av_log(s, AV_LOG_ERROR, "Wrong AAC file format\n");
+        return AVERROR_INVALIDDATA;
+    }
+
+    ctx->pkt_offset = hdr.samples << 2;
+    switch (hdr.num_aac_frames) {
+    case 1:
+        ctx->data_type = IEC61937_MPEG2_AAC;
+        break;
+    case 2:
+        ctx->data_type = IEC61937_MPEG2_AAC_LSF_2048;
+        break;
+    case 4:
+        ctx->data_type = IEC61937_MPEG2_AAC_LSF_4096;
+        break;
+    default:
+        av_log(s, AV_LOG_ERROR, "%i samples in AAC frame not supported\n",
+               hdr.samples);
+        return AVERROR(EINVAL);
+    }
+    //TODO Data type dependent info (LC profile/SBR)
+    return 0;
+}
+
+
+/*
+ * It seems Dolby TrueHD frames have to be encapsulated in MAT frames before
+ * they can be encapsulated in IEC 61937.
+ * Here we encapsulate 24 TrueHD frames in a single MAT frame, padding them
+ * to achieve constant rate.
+ * The actual format of a MAT frame is unknown, but the below seems to work.
+ * However, it seems it is not actually necessary for the 24 TrueHD frames to
+ * be in an exact alignment with the MAT frame.
+ */
+#define MAT_FRAME_SIZE          61424
+#define TRUEHD_FRAME_OFFSET     2560
+#define MAT_MIDDLE_CODE_OFFSET  -4
+
+static int spdif_header_truehd(AVFormatContext *s, AVPacket *pkt)
+{
+    IEC61937Context *ctx = s->priv_data;
+    int mat_code_length = 0;
+    const char mat_end_code[16] = { 0xC3, 0xC2, 0xC0, 0xC4, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x97, 0x11 };
+
+    if (!ctx->hd_buf_count) {
+        const char mat_start_code[20] = { 0x07, 0x9E, 0x00, 0x03, 0x84, 0x01, 0x01, 0x01, 0x80, 0x00, 0x56, 0xA5, 0x3B, 0xF4, 0x81, 0x83, 0x49, 0x80, 0x77, 0xE0 };
+        mat_code_length = sizeof(mat_start_code) + BURST_HEADER_SIZE;
+        memcpy(ctx->hd_buf, mat_start_code, sizeof(mat_start_code));
+
+    } else if (ctx->hd_buf_count == 12) {
+        const char mat_middle_code[12] = { 0xC3, 0xC1, 0x42, 0x49, 0x3B, 0xFA, 0x82, 0x83, 0x49, 0x80, 0x77, 0xE0 };
+        mat_code_length = sizeof(mat_middle_code) + MAT_MIDDLE_CODE_OFFSET;
+        memcpy(&ctx->hd_buf[12 * TRUEHD_FRAME_OFFSET - BURST_HEADER_SIZE + MAT_MIDDLE_CODE_OFFSET],
+               mat_middle_code, sizeof(mat_middle_code));
+    }
+
+    if (pkt->size > TRUEHD_FRAME_OFFSET - mat_code_length) {
+        /* if such frames exist, we'd need some more complex logic to
+         * distribute the TrueHD frames in the MAT frame */
+        av_log(s, AV_LOG_ERROR, "TrueHD frame too big, %d bytes\n", pkt->size);
+        av_log_ask_for_sample(s, NULL);
+        return AVERROR_INVALIDDATA;
+    }
+
+    memcpy(&ctx->hd_buf[ctx->hd_buf_count * TRUEHD_FRAME_OFFSET - BURST_HEADER_SIZE + mat_code_length],
+           pkt->data, pkt->size);
+    memset(&ctx->hd_buf[ctx->hd_buf_count * TRUEHD_FRAME_OFFSET - BURST_HEADER_SIZE + mat_code_length + pkt->size],
+           0, TRUEHD_FRAME_OFFSET - pkt->size - mat_code_length);
+
+    if (++ctx->hd_buf_count < 24){
+        ctx->pkt_offset = 0;
+        return 0;
+    }
+    memcpy(&ctx->hd_buf[MAT_FRAME_SIZE - sizeof(mat_end_code)], mat_end_code, sizeof(mat_end_code));
+    ctx->hd_buf_count = 0;
+
+    ctx->data_type   = IEC61937_TRUEHD;
+    ctx->pkt_offset  = 61440;
+    ctx->out_buf     = ctx->hd_buf;
+    ctx->out_bytes   = MAT_FRAME_SIZE;
+    ctx->length_code = MAT_FRAME_SIZE;
+    return 0;
+}
+
+static int spdif_write_header(AVFormatContext *s)
+{
+    IEC61937Context *ctx = s->priv_data;
+
+    switch (s->streams[0]->codec->codec_id) {
+    case CODEC_ID_AC3:
+        ctx->header_info = spdif_header_ac3;
+        break;
+    case CODEC_ID_EAC3:
+        ctx->header_info = spdif_header_eac3;
+        break;
+    case CODEC_ID_MP1:
+    case CODEC_ID_MP2:
+    case CODEC_ID_MP3:
+        ctx->header_info = spdif_header_mpeg;
+        break;
+    case CODEC_ID_DTS:
+        ctx->header_info = spdif_header_dts;
+        break;
+    case CODEC_ID_AAC:
+        ctx->header_info = spdif_header_aac;
+        break;
+    case CODEC_ID_TRUEHD:
+        ctx->header_info = spdif_header_truehd;
+        ctx->hd_buf = av_malloc(MAT_FRAME_SIZE);
+        if (!ctx->hd_buf)
+            return AVERROR(ENOMEM);
+        break;
+    default:
+        av_log(s, AV_LOG_ERROR, "codec not supported\n");
+        return AVERROR_PATCHWELCOME;
+    }
+    return 0;
+}
+
+static int spdif_write_trailer(AVFormatContext *s)
+{
+    IEC61937Context *ctx = s->priv_data;
+    av_freep(&ctx->buffer);
+    av_freep(&ctx->hd_buf);
+    return 0;
+}
+
+static av_always_inline void spdif_put_16(IEC61937Context *ctx,
+                                          AVIOContext *pb, unsigned int val)
+{
+    if (ctx->spdif_flags & SPDIF_FLAG_BIGENDIAN)
+        avio_wb16(pb, val);
+    else
+        avio_wl16(pb, val);
+}
+
+static int spdif_write_packet(struct AVFormatContext *s, AVPacket *pkt)
+{
+    IEC61937Context *ctx = s->priv_data;
+    int ret, padding;
+
+    ctx->out_buf = pkt->data;
+    ctx->out_bytes = pkt->size;
+    ctx->length_code = FFALIGN(pkt->size, 2) << 3;
+    ctx->use_preamble = 1;
+    ctx->extra_bswap = 0;
+
+    ret = ctx->header_info(s, pkt);
+    if (ret < 0)
+        return ret;
+    if (!ctx->pkt_offset)
+        return 0;
+
+    padding = (ctx->pkt_offset - ctx->use_preamble * BURST_HEADER_SIZE - ctx->out_bytes) & ~1;
+    if (padding < 0) {
+        av_log(s, AV_LOG_ERROR, "bitrate is too high\n");
+        return AVERROR(EINVAL);
+    }
+
+    if (ctx->use_preamble) {
+        spdif_put_16(ctx, s->pb, SYNCWORD1);       //Pa
+        spdif_put_16(ctx, s->pb, SYNCWORD2);       //Pb
+        spdif_put_16(ctx, s->pb, ctx->data_type);  //Pc
+        spdif_put_16(ctx, s->pb, ctx->length_code);//Pd
+    }
+
+    if (ctx->extra_bswap ^ (ctx->spdif_flags & SPDIF_FLAG_BIGENDIAN)) {
+    avio_write(s->pb, ctx->out_buf, ctx->out_bytes & ~1);
+    } else {
+    av_fast_malloc(&ctx->buffer, &ctx->buffer_size, ctx->out_bytes + FF_INPUT_BUFFER_PADDING_SIZE);
+    if (!ctx->buffer)
+        return AVERROR(ENOMEM);
+    ff_spdif_bswap_buf16((uint16_t *)ctx->buffer, (uint16_t *)ctx->out_buf, ctx->out_bytes >> 1);
+    avio_write(s->pb, ctx->buffer, ctx->out_bytes & ~1);
+    }
+
+    /* a final lone byte has to be MSB aligned */
+    if (ctx->out_bytes & 1)
+        spdif_put_16(ctx, s->pb, ctx->out_buf[ctx->out_bytes - 1] << 8);
+
+    ffio_fill(s->pb, 0, padding);
+
+    av_log(s, AV_LOG_DEBUG, "type=%x len=%i pkt_offset=%i\n",
+           ctx->data_type, ctx->out_bytes, ctx->pkt_offset);
+
+    avio_flush(s->pb);
+    return 0;
+}
+
+AVOutputFormat ff_spdif_muxer = {
+    "spdif",
+    NULL_IF_CONFIG_SMALL("IEC 61937 (used on S/PDIF - IEC958)"),
+    NULL,
+    "spdif",
+    sizeof(IEC61937Context),
+    CODEC_ID_AC3,
+    CODEC_ID_NONE,
+    spdif_write_header,
+    spdif_write_packet,
+    spdif_write_trailer,
+    .flags = AVFMT_NOTIMESTAMPS,
+    .priv_class = &class,
+};
diff --git a/libavformat/srtdec.c b/libavformat/srtdec.c
new file mode 100644
index 0000000..72c5c80
--- /dev/null
+++ b/libavformat/srtdec.c
@@ -0,0 +1,102 @@
+/*
+ * SubRip subtitle demuxer
+ * Copyright (c) 2010  Aurelien Jacobs <aurel at gnuage.org>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "avformat.h"
+#include "internal.h"
+#include "libavutil/intreadwrite.h"
+
+static int srt_probe(AVProbeData *p)
+{
+    unsigned char *ptr = p->buf;
+    int i, v, num = 0;
+
+    if (AV_RB24(ptr) == 0xEFBBBF)
+        ptr += 3;  /* skip UTF-8 BOM */
+
+    for (i=0; i<2; i++) {
+        if (num == i && sscanf(ptr, "%*d:%*2d:%*2d%*1[,.]%*3d --> %*d:%*2d:%*2d%*1[,.]%3d", &v) == 1)
+            return AVPROBE_SCORE_MAX;
+        num = atoi(ptr);
+        ptr += strcspn(ptr, "\n") + 1;
+    }
+    return 0;
+}
+
+static int srt_read_header(AVFormatContext *s, AVFormatParameters *ap)
+{
+    AVStream *st = av_new_stream(s, 0);
+    if (!st)
+        return -1;
+    av_set_pts_info(st, 64, 1, 1000);
+    st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
+    st->codec->codec_id   = CODEC_ID_SRT;
+    return 0;
+}
+
+static int64_t get_pts(const char *buf)
+{
+    int i, v, hour, min, sec, hsec;
+
+    for (i=0; i<2; i++) {
+        if (sscanf(buf, "%d:%2d:%2d%*1[,.]%3d --> %*d:%*2d:%*2d%*1[,.]%3d",
+                   &hour, &min, &sec, &hsec, &v) == 5) {
+            min += 60*hour;
+            sec += 60*min;
+            return sec*1000+hsec;
+        }
+        buf += strcspn(buf, "\n") + 1;
+    }
+    return AV_NOPTS_VALUE;
+}
+
+static inline int is_eol(char c)
+{
+    return c == '\r' || c == '\n';
+}
+
+static int srt_read_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    char buffer[2048], *ptr = buffer, *ptr2;
+    int64_t pos = avio_tell(s->pb);
+    int res = AVERROR_EOF;
+
+    do {
+        ptr2 = ptr;
+        ptr += ff_get_line(s->pb, ptr, sizeof(buffer)+buffer-ptr);
+    } while (!is_eol(*ptr2) && !s->pb->eof_reached && ptr-buffer<sizeof(buffer)-1);
+
+    if (buffer[0] && !(res = av_new_packet(pkt, ptr-buffer))) {
+        memcpy(pkt->data, buffer, pkt->size);
+        pkt->flags |= AV_PKT_FLAG_KEY;
+        pkt->pos = pos;
+        pkt->pts = pkt->dts = get_pts(pkt->data);
+    }
+    return res;
+}
+
+AVInputFormat ff_srt_demuxer = {
+    .name        = "srt",
+    .long_name   = NULL_IF_CONFIG_SMALL("SubRip subtitle format"),
+    .read_probe  = srt_probe,
+    .read_header = srt_read_header,
+    .read_packet = srt_read_packet,
+    .flags       = AVFMT_GENERIC_INDEX,
+};
diff --git a/libavformat/swf.h b/libavformat/swf.h
index affebe9..2be6cd5 100644
--- a/libavformat/swf.h
+++ b/libavformat/swf.h
@@ -3,20 +3,20 @@
  * Copyright (c) 2000 Fabrice Bellard
  * Copyright (c) 2003 Tinic Uro
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavformat/swfdec.c b/libavformat/swfdec.c
index 64f775f..eec9524 100644
--- a/libavformat/swfdec.c
+++ b/libavformat/swfdec.c
@@ -3,38 +3,38 @@
  * Copyright (c) 2000 Fabrice Bellard
  * Copyright (c) 2003 Tinic Uro
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "libavutil/intreadwrite.h"
 #include "swf.h"
 
-static int get_swf_tag(ByteIOContext *pb, int *len_ptr)
+static int get_swf_tag(AVIOContext *pb, int *len_ptr)
 {
     int tag, len;
 
-    if (url_feof(pb))
+    if (pb->eof_reached)
         return -1;
 
-    tag = get_le16(pb);
+    tag = avio_rl16(pb);
     len = tag & 0x3f;
     tag = tag >> 6;
     if (len == 0x3f) {
-        len = get_le32(pb);
+        len = avio_rl32(pb);
     }
 //    av_log(NULL, AV_LOG_DEBUG, "Tag: %d - Len: %d\n", tag, len);
     *len_ptr = len;
@@ -55,10 +55,10 @@ static int swf_probe(AVProbeData *p)
 static int swf_read_header(AVFormatContext *s, AVFormatParameters *ap)
 {
     SWFContext *swf = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int nbits, len, tag;
 
-    tag = get_be32(pb) & 0xffffff00;
+    tag = avio_rb32(pb) & 0xffffff00;
 
     if (tag == MKBETAG('C', 'W', 'S', 0)) {
         av_log(s, AV_LOG_ERROR, "Compressed SWF format not supported\n");
@@ -66,13 +66,13 @@ static int swf_read_header(AVFormatContext *s, AVFormatParameters *ap)
     }
     if (tag != MKBETAG('F', 'W', 'S', 0))
         return AVERROR(EIO);
-    get_le32(pb);
+    avio_rl32(pb);
     /* skip rectangle size */
-    nbits = get_byte(pb) >> 3;
+    nbits = avio_r8(pb) >> 3;
     len = (4 * nbits - 3 + 7) / 8;
-    url_fskip(pb, len);
-    swf->frame_rate = get_le16(pb); /* 8.8 fixed */
-    get_le16(pb); /* frame count */
+    avio_skip(pb, len);
+    swf->frame_rate = avio_rl16(pb); /* 8.8 fixed */
+    avio_rl16(pb); /* frame count */
 
     swf->samples_per_frame = 0;
     s->ctx_flags |= AVFMTCTX_NOHEADER;
@@ -82,17 +82,17 @@ static int swf_read_header(AVFormatContext *s, AVFormatParameters *ap)
 static int swf_read_packet(AVFormatContext *s, AVPacket *pkt)
 {
     SWFContext *swf = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVStream *vst = NULL, *ast = NULL, *st = 0;
     int tag, len, i, frame, v;
 
     for(;;) {
-        uint64_t pos = url_ftell(pb);
+        uint64_t pos = avio_tell(pb);
         tag = get_swf_tag(pb, &len);
         if (tag < 0)
             return AVERROR(EIO);
         if (tag == TAG_VIDEOSTREAM) {
-            int ch_id = get_le16(pb);
+            int ch_id = avio_rl16(pb);
             len -= 2;
 
             for (i=0; i<s->nb_streams; i++) {
@@ -101,16 +101,16 @@ static int swf_read_packet(AVFormatContext *s, AVPacket *pkt)
                     goto skip;
             }
 
-            get_le16(pb);
-            get_le16(pb);
-            get_le16(pb);
-            get_byte(pb);
+            avio_rl16(pb);
+            avio_rl16(pb);
+            avio_rl16(pb);
+            avio_r8(pb);
             /* Check for FLV1 */
             vst = av_new_stream(s, ch_id);
             if (!vst)
                 return -1;
             vst->codec->codec_type = AVMEDIA_TYPE_VIDEO;
-            vst->codec->codec_id = ff_codec_get_id(swf_codec_tags, get_byte(pb));
+            vst->codec->codec_id = ff_codec_get_id(swf_codec_tags, avio_r8(pb));
             av_set_pts_info(vst, 16, 256, swf->frame_rate);
             vst->codec->time_base = (AVRational){ 256, swf->frame_rate };
             len -= 8;
@@ -124,9 +124,9 @@ static int swf_read_packet(AVFormatContext *s, AVPacket *pkt)
                     goto skip;
             }
 
-            get_byte(pb);
-            v = get_byte(pb);
-            swf->samples_per_frame = get_le16(pb);
+            avio_r8(pb);
+            v = avio_r8(pb);
+            swf->samples_per_frame = avio_rl16(pb);
             ast = av_new_stream(s, -1); /* -1 to avoid clash with video stream ch_id */
             if (!ast)
                 return -1;
@@ -141,12 +141,12 @@ static int swf_read_packet(AVFormatContext *s, AVPacket *pkt)
             av_set_pts_info(ast, 64, 1, ast->codec->sample_rate);
             len -= 4;
         } else if (tag == TAG_VIDEOFRAME) {
-            int ch_id = get_le16(pb);
+            int ch_id = avio_rl16(pb);
             len -= 2;
             for(i=0; i<s->nb_streams; i++) {
                 st = s->streams[i];
                 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && st->id == ch_id) {
-                    frame = get_le16(pb);
+                    frame = avio_rl16(pb);
                     av_get_packet(pb, pkt, len-2);
                     pkt->pos = pos;
                     pkt->pts = frame;
@@ -159,7 +159,7 @@ static int swf_read_packet(AVFormatContext *s, AVPacket *pkt)
                 st = s->streams[i];
                 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && st->id == -1) {
             if (st->codec->codec_id == CODEC_ID_MP3) {
-                url_fskip(pb, 4);
+                avio_skip(pb, 4);
                 av_get_packet(pb, pkt, len-4);
             } else { // ADPCM, PCM
                 av_get_packet(pb, pkt, len);
@@ -185,29 +185,29 @@ static int swf_read_packet(AVFormatContext *s, AVPacket *pkt)
                 vst->codec->time_base = (AVRational){ 256, swf->frame_rate };
                 st = vst;
             }
-            get_le16(pb); /* BITMAP_ID */
+            avio_rl16(pb); /* BITMAP_ID */
             av_new_packet(pkt, len-2);
-            get_buffer(pb, pkt->data, 4);
+            avio_read(pb, pkt->data, 4);
             if (AV_RB32(pkt->data) == 0xffd8ffd9 ||
                 AV_RB32(pkt->data) == 0xffd9ffd8) {
                 /* old SWF files containing SOI/EOI as data start */
                 /* files created by swink have reversed tag */
                 pkt->size -= 4;
-                get_buffer(pb, pkt->data, pkt->size);
+                avio_read(pb, pkt->data, pkt->size);
             } else {
-                get_buffer(pb, pkt->data + 4, pkt->size - 4);
+                avio_read(pb, pkt->data + 4, pkt->size - 4);
             }
             pkt->pos = pos;
             pkt->stream_index = st->index;
             return pkt->size;
         }
     skip:
-        url_fskip(pb, len);
+        avio_skip(pb, len);
     }
     return 0;
 }
 
-AVInputFormat swf_demuxer = {
+AVInputFormat ff_swf_demuxer = {
     "swf",
     NULL_IF_CONFIG_SMALL("Flash format"),
     sizeof(SWFContext),
diff --git a/libavformat/swfenc.c b/libavformat/swfenc.c
index 1a1a9ab..4c5c315 100644
--- a/libavformat/swfenc.c
+++ b/libavformat/swfenc.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2000 Fabrice Bellard
  * Copyright (c) 2003 Tinic Uro
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -27,39 +27,39 @@
 static void put_swf_tag(AVFormatContext *s, int tag)
 {
     SWFContext *swf = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
 
-    swf->tag_pos = url_ftell(pb);
+    swf->tag_pos = avio_tell(pb);
     swf->tag = tag;
     /* reserve some room for the tag */
     if (tag & TAG_LONG) {
-        put_le16(pb, 0);
-        put_le32(pb, 0);
+        avio_wl16(pb, 0);
+        avio_wl32(pb, 0);
     } else {
-        put_le16(pb, 0);
+        avio_wl16(pb, 0);
     }
 }
 
 static void put_swf_end_tag(AVFormatContext *s)
 {
     SWFContext *swf = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int64_t pos;
     int tag_len, tag;
 
-    pos = url_ftell(pb);
+    pos = avio_tell(pb);
     tag_len = pos - swf->tag_pos - 2;
     tag = swf->tag;
-    url_fseek(pb, swf->tag_pos, SEEK_SET);
+    avio_seek(pb, swf->tag_pos, SEEK_SET);
     if (tag & TAG_LONG) {
         tag &= ~TAG_LONG;
-        put_le16(pb, (tag << 6) | 0x3f);
-        put_le32(pb, tag_len - 4);
+        avio_wl16(pb, (tag << 6) | 0x3f);
+        avio_wl32(pb, tag_len - 4);
     } else {
         assert(tag_len < 0x3f);
-        put_le16(pb, (tag << 6) | tag_len);
+        avio_wl16(pb, (tag << 6) | tag_len);
     }
-    url_fseek(pb, pos, SEEK_SET);
+    avio_seek(pb, pos, SEEK_SET);
 }
 
 static inline void max_nbits(int *nbits_ptr, int val)
@@ -78,7 +78,7 @@ static inline void max_nbits(int *nbits_ptr, int val)
         *nbits_ptr = n;
 }
 
-static void put_swf_rect(ByteIOContext *pb,
+static void put_swf_rect(AVIOContext *pb,
                          int xmin, int xmax, int ymin, int ymax)
 {
     PutBitContext p;
@@ -102,7 +102,7 @@ static void put_swf_rect(ByteIOContext *pb,
     put_bits(&p, nbits, ymax & mask);
 
     flush_put_bits(&p);
-    put_buffer(pb, buf, put_bits_ptr(&p) - p.buf);
+    avio_write(pb, buf, put_bits_ptr(&p) - p.buf);
 }
 
 static void put_swf_line_edge(PutBitContext *pb, int dx, int dy)
@@ -134,7 +134,7 @@ static void put_swf_line_edge(PutBitContext *pb, int dx, int dy)
 
 #define FRAC_BITS 16
 
-static void put_swf_matrix(ByteIOContext *pb,
+static void put_swf_matrix(AVIOContext *pb,
                            int a, int b, int c, int d, int tx, int ty)
 {
     PutBitContext p;
@@ -167,13 +167,13 @@ static void put_swf_matrix(ByteIOContext *pb,
     put_bits(&p, nbits, ty);
 
     flush_put_bits(&p);
-    put_buffer(pb, buf, put_bits_ptr(&p) - p.buf);
+    avio_write(pb, buf, put_bits_ptr(&p) - p.buf);
 }
 
 static int swf_write_header(AVFormatContext *s)
 {
     SWFContext *swf = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     PutBitContext p;
     uint8_t buf1[256];
     int i, width, height, rate, rate_base;
@@ -229,7 +229,7 @@ static int swf_write_header(AVFormatContext *s)
     else
         swf->samples_per_frame = (swf->audio_enc->sample_rate * rate_base) / rate;
 
-    put_tag(pb, "FWS");
+    avio_write(pb, "FWS", 3);
 
     if (!strcmp("avm2", s->oformat->name))
         version = 9;
@@ -239,20 +239,20 @@ static int swf_write_header(AVFormatContext *s)
         version = 6; /* version 6 and above support FLV1 codec */
     else
         version = 4; /* version 4 for mpeg audio support */
-    put_byte(pb, version);
+    avio_w8(pb, version);
 
-    put_le32(pb, DUMMY_FILE_SIZE); /* dummy size
+    avio_wl32(pb, DUMMY_FILE_SIZE); /* dummy size
                                       (will be patched if not streamed) */
 
     put_swf_rect(pb, 0, width * 20, 0, height * 20);
-    put_le16(pb, (rate * 256) / rate_base); /* frame rate */
-    swf->duration_pos = url_ftell(pb);
-    put_le16(pb, (uint16_t)(DUMMY_DURATION * (int64_t)rate / rate_base)); /* frame count */
+    avio_wl16(pb, (rate * 256) / rate_base); /* frame rate */
+    swf->duration_pos = avio_tell(pb);
+    avio_wl16(pb, (uint16_t)(DUMMY_DURATION * (int64_t)rate / rate_base)); /* frame count */
 
     /* avm2/swf v9 (also v8?) files require a file attribute tag */
     if (version == 9) {
         put_swf_tag(s, TAG_FILEATTRIBUTES);
-        put_le32(pb, 1<<3); /* set ActionScript v3/AVM2 flag */
+        avio_wl32(pb, 1<<3); /* set ActionScript v3/AVM2 flag */
         put_swf_end_tag(s);
     }
 
@@ -260,17 +260,17 @@ static int swf_write_header(AVFormatContext *s)
     if (swf->video_enc && swf->video_enc->codec_id == CODEC_ID_MJPEG) {
         put_swf_tag(s, TAG_DEFINESHAPE);
 
-        put_le16(pb, SHAPE_ID); /* ID of shape */
+        avio_wl16(pb, SHAPE_ID); /* ID of shape */
         /* bounding rectangle */
         put_swf_rect(pb, 0, width, 0, height);
         /* style info */
-        put_byte(pb, 1); /* one fill style */
-        put_byte(pb, 0x41); /* clipped bitmap fill */
-        put_le16(pb, BITMAP_ID); /* bitmap ID */
+        avio_w8(pb, 1); /* one fill style */
+        avio_w8(pb, 0x41); /* clipped bitmap fill */
+        avio_wl16(pb, BITMAP_ID); /* bitmap ID */
         /* position of the bitmap */
         put_swf_matrix(pb, (int)(1.0 * (1 << FRAC_BITS)), 0,
                        0, (int)(1.0 * (1 << FRAC_BITS)), 0, 0);
-        put_byte(pb, 0); /* no line style */
+        avio_w8(pb, 0); /* no line style */
 
         /* shape drawing */
         init_put_bits(&p, buf1, sizeof(buf1));
@@ -295,7 +295,7 @@ static int swf_write_header(AVFormatContext *s)
         put_bits(&p, 5, 0);
 
         flush_put_bits(&p);
-        put_buffer(pb, buf1, put_bits_ptr(&p) - p.buf);
+        avio_write(pb, buf1, put_bits_ptr(&p) - p.buf);
 
         put_swf_end_tag(s);
     }
@@ -317,16 +317,16 @@ static int swf_write_header(AVFormatContext *s)
         v |= 0x02; /* 16 bit playback */
         if (swf->audio_enc->channels == 2)
             v |= 0x01; /* stereo playback */
-        put_byte(s->pb, v);
+        avio_w8(s->pb, v);
         v |= 0x20; /* mp3 compressed */
-        put_byte(s->pb, v);
-        put_le16(s->pb, swf->samples_per_frame);  /* avg samples per frame */
-        put_le16(s->pb, 0);
+        avio_w8(s->pb, v);
+        avio_wl16(s->pb, swf->samples_per_frame);  /* avg samples per frame */
+        avio_wl16(s->pb, 0);
 
         put_swf_end_tag(s);
     }
 
-    put_flush_packet(s->pb);
+    avio_flush(s->pb);
     return 0;
 }
 
@@ -334,7 +334,7 @@ static int swf_write_video(AVFormatContext *s,
                            AVCodecContext *enc, const uint8_t *buf, int size)
 {
     SWFContext *swf = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
 
     /* Flash Player limit */
     if (swf->swf_frame_number == 16000)
@@ -345,70 +345,70 @@ static int swf_write_video(AVFormatContext *s,
         if (swf->video_frame_number == 0) {
             /* create a new video object */
             put_swf_tag(s, TAG_VIDEOSTREAM);
-            put_le16(pb, VIDEO_ID);
-            swf->vframes_pos = url_ftell(pb);
-            put_le16(pb, 15000); /* hard flash player limit */
-            put_le16(pb, enc->width);
-            put_le16(pb, enc->height);
-            put_byte(pb, 0);
-            put_byte(pb,ff_codec_get_tag(swf_codec_tags,enc->codec_id));
+            avio_wl16(pb, VIDEO_ID);
+            swf->vframes_pos = avio_tell(pb);
+            avio_wl16(pb, 15000); /* hard flash player limit */
+            avio_wl16(pb, enc->width);
+            avio_wl16(pb, enc->height);
+            avio_w8(pb, 0);
+            avio_w8(pb,ff_codec_get_tag(swf_codec_tags,enc->codec_id));
             put_swf_end_tag(s);
 
             /* place the video object for the first time */
             put_swf_tag(s, TAG_PLACEOBJECT2);
-            put_byte(pb, 0x36);
-            put_le16(pb, 1);
-            put_le16(pb, VIDEO_ID);
+            avio_w8(pb, 0x36);
+            avio_wl16(pb, 1);
+            avio_wl16(pb, VIDEO_ID);
             put_swf_matrix(pb, 1 << FRAC_BITS, 0, 0, 1 << FRAC_BITS, 0, 0);
-            put_le16(pb, swf->video_frame_number);
-            put_tag(pb, "video");
-            put_byte(pb, 0x00);
+            avio_wl16(pb, swf->video_frame_number);
+            avio_write(pb, "video", 5);
+            avio_w8(pb, 0x00);
             put_swf_end_tag(s);
         } else {
             /* mark the character for update */
             put_swf_tag(s, TAG_PLACEOBJECT2);
-            put_byte(pb, 0x11);
-            put_le16(pb, 1);
-            put_le16(pb, swf->video_frame_number);
+            avio_w8(pb, 0x11);
+            avio_wl16(pb, 1);
+            avio_wl16(pb, swf->video_frame_number);
             put_swf_end_tag(s);
         }
 
         /* set video frame data */
         put_swf_tag(s, TAG_VIDEOFRAME | TAG_LONG);
-        put_le16(pb, VIDEO_ID);
-        put_le16(pb, swf->video_frame_number++);
-        put_buffer(pb, buf, size);
+        avio_wl16(pb, VIDEO_ID);
+        avio_wl16(pb, swf->video_frame_number++);
+        avio_write(pb, buf, size);
         put_swf_end_tag(s);
     } else if (enc->codec_id == CODEC_ID_MJPEG) {
         if (swf->swf_frame_number > 0) {
             /* remove the shape */
             put_swf_tag(s, TAG_REMOVEOBJECT);
-            put_le16(pb, SHAPE_ID); /* shape ID */
-            put_le16(pb, 1); /* depth */
+            avio_wl16(pb, SHAPE_ID); /* shape ID */
+            avio_wl16(pb, 1); /* depth */
             put_swf_end_tag(s);
 
             /* free the bitmap */
             put_swf_tag(s, TAG_FREECHARACTER);
-            put_le16(pb, BITMAP_ID);
+            avio_wl16(pb, BITMAP_ID);
             put_swf_end_tag(s);
         }
 
         put_swf_tag(s, TAG_JPEG2 | TAG_LONG);
 
-        put_le16(pb, BITMAP_ID); /* ID of the image */
+        avio_wl16(pb, BITMAP_ID); /* ID of the image */
 
         /* a dummy jpeg header seems to be required */
-        put_be32(pb, 0xffd8ffd9);
+        avio_wb32(pb, 0xffd8ffd9);
         /* write the jpeg image */
-        put_buffer(pb, buf, size);
+        avio_write(pb, buf, size);
 
         put_swf_end_tag(s);
 
         /* draw the shape */
 
         put_swf_tag(s, TAG_PLACEOBJECT);
-        put_le16(pb, SHAPE_ID); /* shape ID */
-        put_le16(pb, 1); /* depth */
+        avio_wl16(pb, SHAPE_ID); /* shape ID */
+        avio_wl16(pb, 1); /* depth */
         put_swf_matrix(pb, 20 << FRAC_BITS, 0, 0, 20 << FRAC_BITS, 0, 0);
         put_swf_end_tag(s);
     }
@@ -419,9 +419,9 @@ static int swf_write_video(AVFormatContext *s,
     if (swf->audio_enc && av_fifo_size(swf->audio_fifo)) {
         int frame_size = av_fifo_size(swf->audio_fifo);
         put_swf_tag(s, TAG_STREAMBLOCK | TAG_LONG);
-        put_le16(pb, swf->sound_samples);
-        put_le16(pb, 0); // seek samples
-        av_fifo_generic_read(swf->audio_fifo, pb, frame_size, &put_buffer);
+        avio_wl16(pb, swf->sound_samples);
+        avio_wl16(pb, 0); // seek samples
+        av_fifo_generic_read(swf->audio_fifo, pb, frame_size, &avio_write);
         put_swf_end_tag(s);
 
         /* update FIFO */
@@ -432,7 +432,7 @@ static int swf_write_video(AVFormatContext *s,
     put_swf_tag(s, TAG_SHOWFRAME);
     put_swf_end_tag(s);
 
-    put_flush_packet(s->pb);
+    avio_flush(s->pb);
 
     return 0;
 }
@@ -473,7 +473,7 @@ static int swf_write_packet(AVFormatContext *s, AVPacket *pkt)
 static int swf_write_trailer(AVFormatContext *s)
 {
     SWFContext *swf = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVCodecContext *enc, *video_enc;
     int file_size, i;
 
@@ -489,24 +489,24 @@ static int swf_write_trailer(AVFormatContext *s)
     put_swf_tag(s, TAG_END);
     put_swf_end_tag(s);
 
-    put_flush_packet(s->pb);
+    avio_flush(s->pb);
 
     /* patch file size and number of frames if not streamed */
-    if (!url_is_streamed(s->pb) && video_enc) {
-        file_size = url_ftell(pb);
-        url_fseek(pb, 4, SEEK_SET);
-        put_le32(pb, file_size);
-        url_fseek(pb, swf->duration_pos, SEEK_SET);
-        put_le16(pb, swf->video_frame_number);
-        url_fseek(pb, swf->vframes_pos, SEEK_SET);
-        put_le16(pb, swf->video_frame_number);
-        url_fseek(pb, file_size, SEEK_SET);
+    if (s->pb->seekable && video_enc) {
+        file_size = avio_tell(pb);
+        avio_seek(pb, 4, SEEK_SET);
+        avio_wl32(pb, file_size);
+        avio_seek(pb, swf->duration_pos, SEEK_SET);
+        avio_wl16(pb, swf->video_frame_number);
+        avio_seek(pb, swf->vframes_pos, SEEK_SET);
+        avio_wl16(pb, swf->video_frame_number);
+        avio_seek(pb, file_size, SEEK_SET);
     }
     return 0;
 }
 
 #if CONFIG_SWF_MUXER
-AVOutputFormat swf_muxer = {
+AVOutputFormat ff_swf_muxer = {
     "swf",
     NULL_IF_CONFIG_SMALL("Flash format"),
     "application/x-shockwave-flash",
@@ -520,7 +520,7 @@ AVOutputFormat swf_muxer = {
 };
 #endif
 #if CONFIG_AVM2_MUXER
-AVOutputFormat avm2_muxer = {
+AVOutputFormat ff_avm2_muxer = {
     "avm2",
     NULL_IF_CONFIG_SMALL("Flash 9 (AVM2) format"),
     "application/x-shockwave-flash",
diff --git a/libavformat/tcp.c b/libavformat/tcp.c
index 79cabdf..0cb3ae3 100644
--- a/libavformat/tcp.c
+++ b/libavformat/tcp.c
@@ -2,29 +2,31 @@
  * TCP protocol
  * Copyright (c) 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #include "avformat.h"
+#include "libavutil/parseutils.h"
 #include <unistd.h>
 #include "internal.h"
 #include "network.h"
 #include "os_support.h"
-#if HAVE_SYS_SELECT_H
-#include <sys/select.h>
+#include "url.h"
+#if HAVE_POLL_H
+#include <poll.h>
 #endif
 #include <sys/time.h>
 
@@ -38,24 +40,35 @@ static int tcp_open(URLContext *h, const char *uri, int flags)
     struct addrinfo hints, *ai, *cur_ai;
     int port, fd = -1;
     TCPContext *s = NULL;
-    fd_set wfds;
-    int fd_max, ret;
-    struct timeval tv;
+    int listen_socket = 0;
+    const char *p;
+    char buf[256];
+    int ret;
     socklen_t optlen;
     char hostname[1024],proto[1024],path[1024];
     char portstr[10];
 
-    ff_url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname),
+    av_url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname),
         &port, path, sizeof(path), uri);
     if (strcmp(proto,"tcp") || port <= 0 || port >= 65536)
         return AVERROR(EINVAL);
 
+    p = strchr(uri, '?');
+    if (p) {
+        if (av_find_info_tag(buf, sizeof(buf), "listen", p))
+            listen_socket = 1;
+    }
     memset(&hints, 0, sizeof(hints));
     hints.ai_family = AF_UNSPEC;
     hints.ai_socktype = SOCK_STREAM;
     snprintf(portstr, sizeof(portstr), "%d", port);
-    if (getaddrinfo(hostname, portstr, &hints, &ai))
+    ret = getaddrinfo(hostname, portstr, &hints, &ai);
+    if (ret) {
+        av_log(NULL, AV_LOG_ERROR,
+               "Failed to resolve hostname %s: %s\n",
+               hostname, gai_strerror(ret));
         return AVERROR(EIO);
+    }
 
     cur_ai = ai;
 
@@ -63,38 +76,54 @@ static int tcp_open(URLContext *h, const char *uri, int flags)
     fd = socket(cur_ai->ai_family, cur_ai->ai_socktype, cur_ai->ai_protocol);
     if (fd < 0)
         goto fail;
-    ff_socket_nonblock(fd, 1);
 
+    if (listen_socket) {
+        int fd1;
+        ret = bind(fd, cur_ai->ai_addr, cur_ai->ai_addrlen);
+        listen(fd, 1);
+        fd1 = accept(fd, NULL, NULL);
+        closesocket(fd);
+        fd = fd1;
+    } else {
  redo:
-    ret = connect(fd, cur_ai->ai_addr, cur_ai->ai_addrlen);
+        ret = connect(fd, cur_ai->ai_addr, cur_ai->ai_addrlen);
+    }
+
+    ff_socket_nonblock(fd, 1);
+
     if (ret < 0) {
-        if (ff_neterrno() == FF_NETERROR(EINTR))
+        struct pollfd p = {fd, POLLOUT, 0};
+        if (ff_neterrno() == AVERROR(EINTR)) {
+            if (url_interrupt_cb()) {
+                ret = AVERROR_EXIT;
+                goto fail1;
+            }
             goto redo;
-        if (ff_neterrno() != FF_NETERROR(EINPROGRESS) &&
-            ff_neterrno() != FF_NETERROR(EAGAIN))
+        }
+        if (ff_neterrno() != AVERROR(EINPROGRESS) &&
+            ff_neterrno() != AVERROR(EAGAIN))
             goto fail;
 
         /* wait until we are connected or until abort */
         for(;;) {
             if (url_interrupt_cb()) {
-                ret = AVERROR(EINTR);
+                ret = AVERROR_EXIT;
                 goto fail1;
             }
-            fd_max = fd;
-            FD_ZERO(&wfds);
-            FD_SET(fd, &wfds);
-            tv.tv_sec = 0;
-            tv.tv_usec = 100 * 1000;
-            ret = select(fd_max + 1, NULL, &wfds, NULL, &tv);
-            if (ret > 0 && FD_ISSET(fd, &wfds))
+            ret = poll(&p, 1, 100);
+            if (ret > 0)
                 break;
         }
 
         /* test error */
         optlen = sizeof(ret);
         getsockopt (fd, SOL_SOCKET, SO_ERROR, &ret, &optlen);
-        if (ret != 0)
+        if (ret != 0) {
+            av_log(NULL, AV_LOG_ERROR,
+                   "TCP connection to %s:%d failed: %s\n",
+                   hostname, port, strerror(ret));
             goto fail;
+        }
     }
     s = av_malloc(sizeof(TCPContext));
     if (!s) {
@@ -126,68 +155,29 @@ static int tcp_open(URLContext *h, const char *uri, int flags)
 static int tcp_read(URLContext *h, uint8_t *buf, int size)
 {
     TCPContext *s = h->priv_data;
-    int len, fd_max, ret;
-    fd_set rfds;
-    struct timeval tv;
-
-    for (;;) {
-        if (url_interrupt_cb())
-            return AVERROR(EINTR);
-        fd_max = s->fd;
-        FD_ZERO(&rfds);
-        FD_SET(s->fd, &rfds);
-        tv.tv_sec = 0;
-        tv.tv_usec = 100 * 1000;
-        ret = select(fd_max + 1, &rfds, NULL, NULL, &tv);
-        if (ret > 0 && FD_ISSET(s->fd, &rfds)) {
-            len = recv(s->fd, buf, size, 0);
-            if (len < 0) {
-                if (ff_neterrno() != FF_NETERROR(EINTR) &&
-                    ff_neterrno() != FF_NETERROR(EAGAIN))
-                    return AVERROR(ff_neterrno());
-            } else return len;
-        } else if (ret < 0) {
-            if (ff_neterrno() == FF_NETERROR(EINTR))
-                continue;
-            return -1;
-        }
+    int ret;
+
+    if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
+        ret = ff_network_wait_fd(s->fd, 0);
+        if (ret < 0)
+            return ret;
     }
+    ret = recv(s->fd, buf, size, 0);
+    return ret < 0 ? ff_neterrno() : ret;
 }
 
-static int tcp_write(URLContext *h, uint8_t *buf, int size)
+static int tcp_write(URLContext *h, const uint8_t *buf, int size)
 {
     TCPContext *s = h->priv_data;
-    int ret, size1, fd_max, len;
-    fd_set wfds;
-    struct timeval tv;
-
-    size1 = size;
-    while (size > 0) {
-        if (url_interrupt_cb())
-            return AVERROR(EINTR);
-        fd_max = s->fd;
-        FD_ZERO(&wfds);
-        FD_SET(s->fd, &wfds);
-        tv.tv_sec = 0;
-        tv.tv_usec = 100 * 1000;
-        ret = select(fd_max + 1, NULL, &wfds, NULL, &tv);
-        if (ret > 0 && FD_ISSET(s->fd, &wfds)) {
-            len = send(s->fd, buf, size, 0);
-            if (len < 0) {
-                if (ff_neterrno() != FF_NETERROR(EINTR) &&
-                    ff_neterrno() != FF_NETERROR(EAGAIN))
-                    return AVERROR(ff_neterrno());
-                continue;
-            }
-            size -= len;
-            buf += len;
-        } else if (ret < 0) {
-            if (ff_neterrno() == FF_NETERROR(EINTR))
-                continue;
-            return -1;
-        }
+    int ret;
+
+    if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
+        ret = ff_network_wait_fd(s->fd, 1);
+        if (ret < 0)
+            return ret;
     }
-    return size1 - size;
+    ret = send(s->fd, buf, size, 0);
+    return ret < 0 ? ff_neterrno() : ret;
 }
 
 static int tcp_close(URLContext *h)
@@ -204,12 +194,11 @@ static int tcp_get_file_handle(URLContext *h)
     return s->fd;
 }
 
-URLProtocol tcp_protocol = {
-    "tcp",
-    tcp_open,
-    tcp_read,
-    tcp_write,
-    NULL, /* seek */
-    tcp_close,
+URLProtocol ff_tcp_protocol = {
+    .name                = "tcp",
+    .url_open            = tcp_open,
+    .url_read            = tcp_read,
+    .url_write           = tcp_write,
+    .url_close           = tcp_close,
     .url_get_file_handle = tcp_get_file_handle,
 };
diff --git a/libavformat/thp.c b/libavformat/thp.c
index 82966dd..6cdcefd 100644
--- a/libavformat/thp.c
+++ b/libavformat/thp.c
@@ -2,20 +2,20 @@
  * THP Demuxer
  * Copyright (c) 2007 Marco Gerards
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -57,35 +57,35 @@ static int thp_read_header(AVFormatContext *s,
 {
     ThpDemuxContext *thp = s->priv_data;
     AVStream *st;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int i;
 
     /* Read the file header.  */
-                           get_be32(pb); /* Skip Magic.  */
-    thp->version         = get_be32(pb);
+                           avio_rb32(pb); /* Skip Magic.  */
+    thp->version         = avio_rb32(pb);
 
-                           get_be32(pb); /* Max buf size.  */
-                           get_be32(pb); /* Max samples.  */
+                           avio_rb32(pb); /* Max buf size.  */
+                           avio_rb32(pb); /* Max samples.  */
 
-    thp->fps             = av_d2q(av_int2flt(get_be32(pb)), INT_MAX);
-    thp->framecnt        = get_be32(pb);
-    thp->first_framesz   = get_be32(pb);
-                           get_be32(pb); /* Data size.  */
+    thp->fps             = av_d2q(av_int2flt(avio_rb32(pb)), INT_MAX);
+    thp->framecnt        = avio_rb32(pb);
+    thp->first_framesz   = avio_rb32(pb);
+                           avio_rb32(pb); /* Data size.  */
 
-    thp->compoff         = get_be32(pb);
-                           get_be32(pb); /* offsetDataOffset.  */
-    thp->first_frame     = get_be32(pb);
-    thp->last_frame      = get_be32(pb);
+    thp->compoff         = avio_rb32(pb);
+                           avio_rb32(pb); /* offsetDataOffset.  */
+    thp->first_frame     = avio_rb32(pb);
+    thp->last_frame      = avio_rb32(pb);
 
     thp->next_framesz    = thp->first_framesz;
     thp->next_frame      = thp->first_frame;
 
     /* Read the component structure.  */
-    url_fseek (pb, thp->compoff, SEEK_SET);
-    thp->compcount       = get_be32(pb);
+    avio_seek (pb, thp->compoff, SEEK_SET);
+    thp->compcount       = avio_rb32(pb);
 
     /* Read the list of component types.  */
-    get_buffer(pb, thp->components, 16);
+    avio_read(pb, thp->components, 16);
 
     for (i = 0; i < thp->compcount; i++) {
         if (thp->components[i] == 0) {
@@ -103,14 +103,14 @@ static int thp_read_header(AVFormatContext *s,
             st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
             st->codec->codec_id = CODEC_ID_THP;
             st->codec->codec_tag = 0;  /* no fourcc */
-            st->codec->width = get_be32(pb);
-            st->codec->height = get_be32(pb);
+            st->codec->width = avio_rb32(pb);
+            st->codec->height = avio_rb32(pb);
             st->codec->sample_rate = av_q2d(thp->fps);
             thp->vst = st;
             thp->video_stream_index = st->index;
 
             if (thp->version == 0x11000)
-                get_be32(pb); /* Unknown.  */
+                avio_rb32(pb); /* Unknown.  */
         } else if (thp->components[i] == 1) {
             if (thp->has_audio != 0)
                 break;
@@ -123,8 +123,8 @@ static int thp_read_header(AVFormatContext *s,
             st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
             st->codec->codec_id = CODEC_ID_ADPCM_THP;
             st->codec->codec_tag = 0;  /* no fourcc */
-            st->codec->channels    = get_be32(pb); /* numChannels.  */
-            st->codec->sample_rate = get_be32(pb); /* Frequency.  */
+            st->codec->channels    = avio_rb32(pb); /* numChannels.  */
+            st->codec->sample_rate = avio_rb32(pb); /* Frequency.  */
 
             av_set_pts_info(st, 64, 1, st->codec->sample_rate);
 
@@ -140,7 +140,7 @@ static int thp_read_packet(AVFormatContext *s,
                             AVPacket *pkt)
 {
     ThpDemuxContext *thp = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int size;
     int ret;
 
@@ -149,19 +149,19 @@ static int thp_read_packet(AVFormatContext *s,
         if (thp->frame >= thp->framecnt)
             return AVERROR(EIO);
 
-        url_fseek(pb, thp->next_frame, SEEK_SET);
+        avio_seek(pb, thp->next_frame, SEEK_SET);
 
         /* Locate the next frame and read out its size.  */
         thp->next_frame += thp->next_framesz;
-        thp->next_framesz = get_be32(pb);
+        thp->next_framesz = avio_rb32(pb);
 
-                        get_be32(pb); /* Previous total size.  */
-        size          = get_be32(pb); /* Total size of this frame.  */
+                        avio_rb32(pb); /* Previous total size.  */
+        size          = avio_rb32(pb); /* Total size of this frame.  */
 
         /* Store the audiosize so the next time this function is called,
            the audio can be read.  */
         if (thp->has_audio)
-            thp->audiosize = get_be32(pb); /* Audio size.  */
+            thp->audiosize = avio_rb32(pb); /* Audio size.  */
         else
             thp->frame++;
 
@@ -187,7 +187,7 @@ static int thp_read_packet(AVFormatContext *s,
     return 0;
 }
 
-AVInputFormat thp_demuxer = {
+AVInputFormat ff_thp_demuxer = {
     "thp",
     NULL_IF_CONFIG_SMALL("THP"),
     sizeof(ThpDemuxContext),
diff --git a/libavformat/tiertexseq.c b/libavformat/tiertexseq.c
index 938eea5..7ca0464 100644
--- a/libavformat/tiertexseq.c
+++ b/libavformat/tiertexseq.c
@@ -2,20 +2,20 @@
  * Tiertex Limited SEQ File Demuxer
  * Copyright (c) 2006 Gregory Montoir (cyx at users.sourceforge.net)
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -78,15 +78,15 @@ static int seq_probe(AVProbeData *p)
     return AVPROBE_SCORE_MAX / 4;
 }
 
-static int seq_init_frame_buffers(SeqDemuxContext *seq, ByteIOContext *pb)
+static int seq_init_frame_buffers(SeqDemuxContext *seq, AVIOContext *pb)
 {
     int i, sz;
     TiertexSeqFrameBuffer *seq_buffer;
 
-    url_fseek(pb, 256, SEEK_SET);
+    avio_seek(pb, 256, SEEK_SET);
 
     for (i = 0; i < SEQ_NUM_FRAME_BUFFERS; i++) {
-        sz = get_le16(pb);
+        sz = avio_rl16(pb);
         if (sz == 0)
             break;
         else {
@@ -102,7 +102,7 @@ static int seq_init_frame_buffers(SeqDemuxContext *seq, ByteIOContext *pb)
     return 0;
 }
 
-static int seq_fill_buffer(SeqDemuxContext *seq, ByteIOContext *pb, int buffer_num, unsigned int data_offs, int data_size)
+static int seq_fill_buffer(SeqDemuxContext *seq, AVIOContext *pb, int buffer_num, unsigned int data_offs, int data_size)
 {
     TiertexSeqFrameBuffer *seq_buffer;
 
@@ -113,25 +113,25 @@ static int seq_fill_buffer(SeqDemuxContext *seq, ByteIOContext *pb, int buffer_n
     if (seq_buffer->fill_size + data_size > seq_buffer->data_size || data_size <= 0)
         return AVERROR_INVALIDDATA;
 
-    url_fseek(pb, seq->current_frame_offs + data_offs, SEEK_SET);
-    if (get_buffer(pb, seq_buffer->data + seq_buffer->fill_size, data_size) != data_size)
+    avio_seek(pb, seq->current_frame_offs + data_offs, SEEK_SET);
+    if (avio_read(pb, seq_buffer->data + seq_buffer->fill_size, data_size) != data_size)
         return AVERROR(EIO);
 
     seq_buffer->fill_size += data_size;
     return 0;
 }
 
-static int seq_parse_frame_data(SeqDemuxContext *seq, ByteIOContext *pb)
+static int seq_parse_frame_data(SeqDemuxContext *seq, AVIOContext *pb)
 {
     unsigned int offset_table[4], buffer_num[4];
     TiertexSeqFrameBuffer *seq_buffer;
     int i, e, err;
 
     seq->current_frame_offs += SEQ_FRAME_SIZE;
-    url_fseek(pb, seq->current_frame_offs, SEEK_SET);
+    avio_seek(pb, seq->current_frame_offs, SEEK_SET);
 
     /* sound data */
-    seq->current_audio_data_offs = get_le16(pb);
+    seq->current_audio_data_offs = avio_rl16(pb);
     if (seq->current_audio_data_offs) {
         seq->current_audio_data_size = SEQ_AUDIO_BUFFER_SIZE * 2;
     } else {
@@ -139,7 +139,7 @@ static int seq_parse_frame_data(SeqDemuxContext *seq, ByteIOContext *pb)
     }
 
     /* palette data */
-    seq->current_pal_data_offs = get_le16(pb);
+    seq->current_pal_data_offs = avio_rl16(pb);
     if (seq->current_pal_data_offs) {
         seq->current_pal_data_size = 768;
     } else {
@@ -148,10 +148,10 @@ static int seq_parse_frame_data(SeqDemuxContext *seq, ByteIOContext *pb)
 
     /* video data */
     for (i = 0; i < 4; i++)
-        buffer_num[i] = get_byte(pb);
+        buffer_num[i] = avio_r8(pb);
 
     for (i = 0; i < 4; i++)
-        offset_table[i] = get_le16(pb);
+        offset_table[i] = avio_rl16(pb);
 
     for (i = 0; i < 3; i++) {
         if (offset_table[i]) {
@@ -184,7 +184,7 @@ static int seq_read_header(AVFormatContext *s, AVFormatParameters *ap)
 {
     int i, rc;
     SeqDemuxContext *seq = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVStream *st;
 
     /* init internal buffers */
@@ -241,7 +241,7 @@ static int seq_read_packet(AVFormatContext *s, AVPacket *pkt)
 {
     int rc;
     SeqDemuxContext *seq = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
 
     if (!seq->audio_buffer_full) {
         rc = seq_parse_frame_data(seq, pb);
@@ -256,8 +256,8 @@ static int seq_read_packet(AVFormatContext *s, AVPacket *pkt)
             pkt->data[0] = 0;
             if (seq->current_pal_data_size) {
                 pkt->data[0] |= 1;
-                url_fseek(pb, seq->current_frame_offs + seq->current_pal_data_offs, SEEK_SET);
-                if (get_buffer(pb, &pkt->data[1], seq->current_pal_data_size) != seq->current_pal_data_size)
+                avio_seek(pb, seq->current_frame_offs + seq->current_pal_data_offs, SEEK_SET);
+                if (avio_read(pb, &pkt->data[1], seq->current_pal_data_size) != seq->current_pal_data_size)
                     return AVERROR(EIO);
             }
             if (seq->current_video_data_size) {
@@ -279,7 +279,7 @@ static int seq_read_packet(AVFormatContext *s, AVPacket *pkt)
     if (seq->current_audio_data_offs == 0) /* end of data reached */
         return AVERROR(EIO);
 
-    url_fseek(pb, seq->current_frame_offs + seq->current_audio_data_offs, SEEK_SET);
+    avio_seek(pb, seq->current_frame_offs + seq->current_audio_data_offs, SEEK_SET);
     rc = av_get_packet(pb, pkt, seq->current_audio_data_size);
     if (rc < 0)
         return rc;
@@ -302,7 +302,7 @@ static int seq_read_close(AVFormatContext *s)
     return 0;
 }
 
-AVInputFormat tiertexseq_demuxer = {
+AVInputFormat ff_tiertexseq_demuxer = {
     "tiertexseq",
     NULL_IF_CONFIG_SMALL("Tiertex Limited SEQ format"),
     sizeof(SeqDemuxContext),
diff --git a/libavformat/timefilter.c b/libavformat/timefilter.c
index 4a58224..4860a4f 100644
--- a/libavformat/timefilter.c
+++ b/libavformat/timefilter.c
@@ -5,20 +5,20 @@
  * Author: Olivier Guilyardi <olivier samalyse com>
  *         Michael Niedermayer <michaelni gmx at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -79,6 +79,8 @@ double ff_timefilter_update(TimeFilter *self, double system_time, double period)
 #include "libavutil/lfg.h"
 #define LFG_MAX ((1LL << 32) - 1)
 
+#undef printf
+
 int main(void)
 {
     AVLFG prng;
diff --git a/libavformat/timefilter.h b/libavformat/timefilter.h
index ded8ec7..aa7db53 100644
--- a/libavformat/timefilter.h
+++ b/libavformat/timefilter.h
@@ -5,20 +5,20 @@
  * Author: Olivier Guilyardi <olivier samalyse com>
  *         Michael Niedermayer <michaelni gmx at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavformat/tmv.c b/libavformat/tmv.c
index 4be2f32..f894eab 100644
--- a/libavformat/tmv.c
+++ b/libavformat/tmv.c
@@ -2,20 +2,20 @@
  * 8088flex TMV file demuxer
  * Copyright (c) 2009 Daniel Verkamp <daniel at drv.nu>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -65,12 +65,12 @@ static int tmv_probe(AVProbeData *p)
 static int tmv_read_header(AVFormatContext *s, AVFormatParameters *ap)
 {
     TMVContext *tmv   = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVStream *vst, *ast;
     AVRational fps;
     unsigned comp_method, char_cols, char_rows, features;
 
-    if (get_le32(pb) != TMV_TAG)
+    if (avio_rl32(pb) != TMV_TAG)
         return -1;
 
     if (!(vst = av_new_stream(s, 0)))
@@ -79,30 +79,30 @@ static int tmv_read_header(AVFormatContext *s, AVFormatParameters *ap)
     if (!(ast = av_new_stream(s, 0)))
         return AVERROR(ENOMEM);
 
-    ast->codec->sample_rate = get_le16(pb);
+    ast->codec->sample_rate = avio_rl16(pb);
     if (!ast->codec->sample_rate) {
         av_log(s, AV_LOG_ERROR, "invalid sample rate\n");
         return -1;
     }
 
-    tmv->audio_chunk_size   = get_le16(pb);
+    tmv->audio_chunk_size   = avio_rl16(pb);
     if (!tmv->audio_chunk_size) {
         av_log(s, AV_LOG_ERROR, "invalid audio chunk size\n");
         return -1;
     }
 
-    comp_method             = get_byte(pb);
+    comp_method             = avio_r8(pb);
     if (comp_method) {
         av_log(s, AV_LOG_ERROR, "unsupported compression method %d\n",
                comp_method);
         return -1;
     }
 
-    char_cols = get_byte(pb);
-    char_rows = get_byte(pb);
+    char_cols = avio_r8(pb);
+    char_rows = avio_r8(pb);
     tmv->video_chunk_size = char_cols * char_rows * 2;
 
-    features  = get_byte(pb);
+    features  = avio_r8(pb);
     if (features & ~(TMV_PADDING | TMV_STEREO)) {
         av_log(s, AV_LOG_ERROR, "unsupported features 0x%02x\n",
                features & ~(TMV_PADDING | TMV_STEREO));
@@ -142,17 +142,17 @@ static int tmv_read_header(AVFormatContext *s, AVFormatParameters *ap)
 static int tmv_read_packet(AVFormatContext *s, AVPacket *pkt)
 {
     TMVContext *tmv   = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int ret, pkt_size = tmv->stream_index ?
                         tmv->audio_chunk_size : tmv->video_chunk_size;
 
-    if (url_feof(pb))
+    if (pb->eof_reached)
         return AVERROR_EOF;
 
     ret = av_get_packet(pb, pkt, pkt_size);
 
     if (tmv->stream_index)
-        url_fskip(pb, tmv->padding);
+        avio_skip(pb, tmv->padding);
 
     pkt->stream_index  = tmv->stream_index;
     tmv->stream_index ^= 1;
@@ -173,12 +173,12 @@ static int tmv_read_seek(AVFormatContext *s, int stream_index,
     pos = timestamp *
           (tmv->audio_chunk_size + tmv->video_chunk_size + tmv->padding);
 
-    url_fseek(s->pb, pos + TMV_HEADER_SIZE, SEEK_SET);
+    avio_seek(s->pb, pos + TMV_HEADER_SIZE, SEEK_SET);
     tmv->stream_index = 0;
     return 0;
 }
 
-AVInputFormat tmv_demuxer = {
+AVInputFormat ff_tmv_demuxer = {
     "tmv",
     NULL_IF_CONFIG_SMALL("8088flex TMV"),
     sizeof(TMVContext),
diff --git a/libavformat/tta.c b/libavformat/tta.c
index 66d3bad..0036200 100644
--- a/libavformat/tta.c
+++ b/libavformat/tta.c
@@ -2,26 +2,25 @@
  * TTA demuxer
  * Copyright (c) 2006 Alex Beregszaszi
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "libavcodec/get_bits.h"
 #include "avformat.h"
-#include "id3v2.h"
 #include "id3v1.h"
 
 typedef struct {
@@ -32,12 +31,6 @@ static int tta_probe(AVProbeData *p)
 {
     const uint8_t *d = p->buf;
 
-    if (ff_id3v2_match(d))
-        d += ff_id3v2_tag_len(d);
-
-    if (d - p->buf >= p->buf_size)
-        return 0;
-
     if (d[0] == 'T' && d[1] == 'T' && d[2] == 'A' && d[3] == '1')
         return 80;
     return 0;
@@ -50,30 +43,29 @@ static int tta_read_header(AVFormatContext *s, AVFormatParameters *ap)
     int i, channels, bps, samplerate, datalen, framelen;
     uint64_t framepos, start_offset;
 
-    ff_id3v2_read(s);
     if (!av_metadata_get(s->metadata, "", NULL, AV_METADATA_IGNORE_SUFFIX))
         ff_id3v1_read(s);
 
-    start_offset = url_ftell(s->pb);
-    if (get_le32(s->pb) != AV_RL32("TTA1"))
+    start_offset = avio_tell(s->pb);
+    if (avio_rl32(s->pb) != AV_RL32("TTA1"))
         return -1; // not tta file
 
-    url_fskip(s->pb, 2); // FIXME: flags
-    channels = get_le16(s->pb);
-    bps = get_le16(s->pb);
-    samplerate = get_le32(s->pb);
+    avio_skip(s->pb, 2); // FIXME: flags
+    channels = avio_rl16(s->pb);
+    bps = avio_rl16(s->pb);
+    samplerate = avio_rl32(s->pb);
     if(samplerate <= 0 || samplerate > 1000000){
         av_log(s, AV_LOG_ERROR, "nonsense samplerate\n");
         return -1;
     }
 
-    datalen = get_le32(s->pb);
+    datalen = avio_rl32(s->pb);
     if(datalen < 0){
         av_log(s, AV_LOG_ERROR, "nonsense datalen\n");
         return -1;
     }
 
-    url_fskip(s->pb, 4); // header crc
+    avio_skip(s->pb, 4); // header crc
 
     framelen = samplerate*256/245;
     c->totalframes = datalen / framelen + ((datalen % framelen) ? 1 : 0);
@@ -92,14 +84,14 @@ static int tta_read_header(AVFormatContext *s, AVFormatParameters *ap)
     st->start_time = 0;
     st->duration = datalen;
 
-    framepos = url_ftell(s->pb) + 4*c->totalframes + 4;
+    framepos = avio_tell(s->pb) + 4*c->totalframes + 4;
 
     for (i = 0; i < c->totalframes; i++) {
-        uint32_t size = get_le32(s->pb);
+        uint32_t size = avio_rl32(s->pb);
         av_add_index_entry(st, framepos, i*framelen, size, 0, AVINDEX_KEYFRAME);
         framepos += size;
     }
-    url_fskip(s->pb, 4); // seektable crc
+    avio_skip(s->pb, 4); // seektable crc
 
     st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
     st->codec->codec_id = CODEC_ID_TTA;
@@ -107,15 +99,15 @@ static int tta_read_header(AVFormatContext *s, AVFormatParameters *ap)
     st->codec->sample_rate = samplerate;
     st->codec->bits_per_coded_sample = bps;
 
-    st->codec->extradata_size = url_ftell(s->pb) - start_offset;
+    st->codec->extradata_size = avio_tell(s->pb) - start_offset;
     if(st->codec->extradata_size+FF_INPUT_BUFFER_PADDING_SIZE <= (unsigned)st->codec->extradata_size){
-        //this check is redundant as get_buffer should fail
+        //this check is redundant as avio_read should fail
         av_log(s, AV_LOG_ERROR, "extradata_size too large\n");
         return -1;
     }
     st->codec->extradata = av_mallocz(st->codec->extradata_size+FF_INPUT_BUFFER_PADDING_SIZE);
-    url_fseek(s->pb, start_offset, SEEK_SET);
-    get_buffer(s->pb, st->codec->extradata, st->codec->extradata_size);
+    avio_seek(s->pb, start_offset, SEEK_SET);
+    avio_read(s->pb, st->codec->extradata, st->codec->extradata_size);
 
     return 0;
 }
@@ -146,12 +138,12 @@ static int tta_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp
         return -1;
 
     c->currentframe = index;
-    url_fseek(s->pb, st->index_entries[index].pos, SEEK_SET);
+    avio_seek(s->pb, st->index_entries[index].pos, SEEK_SET);
 
     return 0;
 }
 
-AVInputFormat tta_demuxer = {
+AVInputFormat ff_tta_demuxer = {
     "tta",
     NULL_IF_CONFIG_SMALL("True Audio"),
     sizeof(TTAContext),
diff --git a/libavformat/tty.c b/libavformat/tty.c
new file mode 100644
index 0000000..ea8d0c7
--- /dev/null
+++ b/libavformat/tty.c
@@ -0,0 +1,134 @@
+/*
+ * Tele-typewriter demuxer
+ * Copyright (c) 2010 Peter Ross <pross at xvid.org>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * Tele-typewriter demuxer
+ */
+
+#include "libavutil/intreadwrite.h"
+#include "libavutil/avstring.h"
+#include "avformat.h"
+#include "sauce.h"
+
+#define LINE_RATE 6000 /* characters per second */
+
+typedef struct {
+    int chars_per_frame;
+    uint64_t fsize;  /**< file size less metadata buffer */
+} TtyDemuxContext;
+
+/**
+ * Parse EFI header
+ */
+static int efi_read(AVFormatContext *avctx, uint64_t start_pos)
+{
+    TtyDemuxContext *s = avctx->priv_data;
+    AVIOContext *pb = avctx->pb;
+    char buf[37];
+    int len;
+
+    avio_seek(pb, start_pos, SEEK_SET);
+    if (avio_r8(pb) != 0x1A)
+        return -1;
+
+#define GET_EFI_META(name,size) \
+    len = avio_r8(pb); \
+    if (len < 1 || len > size) \
+        return -1; \
+    if (avio_read(pb, buf, size) == size) { \
+        buf[len] = 0; \
+        av_metadata_set2(&avctx->metadata, name, buf, 0); \
+    }
+
+    GET_EFI_META("filename", 12)
+    GET_EFI_META("title",    36)
+
+    s->fsize = start_pos;
+    return 0;
+}
+
+static int read_header(AVFormatContext *avctx,
+                       AVFormatParameters *ap)
+{
+    TtyDemuxContext *s = avctx->priv_data;
+    AVStream *st = av_new_stream(avctx, 0);
+    if (!st)
+        return AVERROR(ENOMEM);
+    st->codec->codec_tag   = 0;
+    st->codec->codec_type  = AVMEDIA_TYPE_VIDEO;
+    st->codec->codec_id    = CODEC_ID_ANSI;
+    if (ap->width)  st->codec->width  = ap->width;
+    if (ap->height) st->codec->height = ap->height;
+
+    if (!ap->time_base.num) {
+        av_set_pts_info(st, 60, 1, 25);
+    } else {
+        av_set_pts_info(st, 60, ap->time_base.num, ap->time_base.den);
+    }
+
+    /* simulate tty display speed */
+    s->chars_per_frame = FFMAX(av_q2d(st->time_base) * (ap->sample_rate ? ap->sample_rate : LINE_RATE), 1);
+
+    if (avctx->pb->seekable) {
+        s->fsize = avio_size(avctx->pb);
+        st->duration = (s->fsize + s->chars_per_frame - 1) / s->chars_per_frame;
+
+        if (ff_sauce_read(avctx, &s->fsize, 0, 0) < 0)
+            efi_read(avctx, s->fsize - 51);
+
+        avio_seek(avctx->pb, 0, SEEK_SET);
+    }
+
+    return 0;
+}
+
+static int read_packet(AVFormatContext *avctx, AVPacket *pkt)
+{
+    TtyDemuxContext *s = avctx->priv_data;
+    int n;
+
+    if (avctx->pb->eof_reached)
+        return AVERROR_EOF;
+
+    n = s->chars_per_frame;
+    if (s->fsize) {
+        // ignore metadata buffer
+        uint64_t p = avio_tell(avctx->pb);
+        if (p + s->chars_per_frame > s->fsize)
+            n = s->fsize - p;
+    }
+
+    pkt->size = av_get_packet(avctx->pb, pkt, n);
+    if (pkt->size <= 0)
+        return AVERROR(EIO);
+    pkt->flags |= AV_PKT_FLAG_KEY;
+    return 0;
+}
+
+AVInputFormat ff_tty_demuxer = {
+    .name           = "tty",
+    .long_name      = NULL_IF_CONFIG_SMALL("Tele-typewriter"),
+    .priv_data_size = sizeof(TtyDemuxContext),
+    .read_header    = read_header,
+    .read_packet    = read_packet,
+    .extensions     = "ans,art,asc,diz,ice,nfo,txt,vt",
+};
diff --git a/libavformat/txd.c b/libavformat/txd.c
index 38bdb1b..0a93b7c 100644
--- a/libavformat/txd.c
+++ b/libavformat/txd.c
@@ -2,20 +2,20 @@
  * Renderware TeXture Dictionary (.txd) demuxer
  * Copyright (c) 2007 Ivo van Poorten
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -52,16 +52,16 @@ static int txd_read_header(AVFormatContext *s, AVFormatParameters *ap) {
 }
 
 static int txd_read_packet(AVFormatContext *s, AVPacket *pkt) {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     unsigned int id, chunk_size, marker;
     int ret;
 
 next_chunk:
-    id         = get_le32(pb);
-    chunk_size = get_le32(pb);
-    marker     = get_le32(pb);
+    id         = avio_rl32(pb);
+    chunk_size = avio_rl32(pb);
+    marker     = avio_rl32(pb);
 
-    if (url_feof(s->pb))
+    if (s->pb->eof_reached)
         return AVERROR_EOF;
     if (marker != TXD_MARKER && marker != TXD_MARKER2) {
         av_log(s, AV_LOG_ERROR, "marker does not match\n");
@@ -73,7 +73,7 @@ next_chunk:
             if (chunk_size > 100)
                 break;
         case TXD_EXTRA:
-            url_fskip(s->pb, chunk_size);
+            avio_skip(s->pb, chunk_size);
         case TXD_FILE:
         case TXD_TEXTURE:
             goto next_chunk;
@@ -90,7 +90,7 @@ next_chunk:
     return 0;
 }
 
-AVInputFormat txd_demuxer =
+AVInputFormat ff_txd_demuxer =
 {
     "txd",
     NULL_IF_CONFIG_SMALL("Renderware TeXture Dictionary"),
diff --git a/libavformat/udp.c b/libavformat/udp.c
index a11f4c3..b881ff9 100644
--- a/libavformat/udp.c
+++ b/libavformat/udp.c
@@ -2,20 +2,20 @@
  * UDP prototype streaming system
  * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,26 +25,21 @@
  */
 
 #define _BSD_SOURCE     /* Needed for using struct ip_mreq with recent glibc */
+#define _DARWIN_C_SOURCE /* Needed for using IP_MULTICAST_TTL on OS X */
 #include "avformat.h"
+#include "avio_internal.h"
+#include "libavutil/parseutils.h"
 #include <unistd.h>
 #include "internal.h"
 #include "network.h"
 #include "os_support.h"
-#if HAVE_SYS_SELECT_H
-#include <sys/select.h>
-#endif
+#include "url.h"
 #include <sys/time.h>
 
 #ifndef IPV6_ADD_MEMBERSHIP
 #define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
 #define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP
 #endif
-#ifndef IN_MULTICAST
-#define IN_MULTICAST(a) ((((uint32_t)(a)) & 0xf0000000) == 0xe0000000)
-#endif
-#ifndef IN6_IS_ADDR_MULTICAST
-#define IN6_IS_ADDR_MULTICAST(a) (((uint8_t *) (a))[0] == 0xff)
-#endif
 
 typedef struct {
     int udp_fd;
@@ -55,6 +50,7 @@ typedef struct {
     int reuse_socket;
     struct sockaddr_storage dest_addr;
     int dest_addr_len;
+    int is_connected;
 } UDPContext;
 
 #define UDP_TX_BUF_SIZE 32768
@@ -96,7 +92,7 @@ static int udp_join_multicast_group(int sockfd, struct sockaddr *addr)
         }
     }
 #endif
-#if HAVE_STRUCT_IPV6_MREQ
+#if HAVE_STRUCT_IPV6_MREQ && defined(IPPROTO_IPV6)
     if (addr->sa_family == AF_INET6) {
         struct ipv6_mreq mreq6;
 
@@ -125,7 +121,7 @@ static int udp_leave_multicast_group(int sockfd, struct sockaddr *addr)
         }
     }
 #endif
-#if HAVE_STRUCT_IPV6_MREQ
+#if HAVE_STRUCT_IPV6_MREQ && defined(IPPROTO_IPV6)
     if (addr->sa_family == AF_INET6) {
         struct ipv6_mreq mreq6;
 
@@ -182,20 +178,6 @@ static int udp_set_url(struct sockaddr_storage *addr,
     return addr_len;
 }
 
-static int is_multicast_address(struct sockaddr_storage *addr)
-{
-    if (addr->ss_family == AF_INET) {
-        return IN_MULTICAST(ntohl(((struct sockaddr_in *)addr)->sin_addr.s_addr));
-    }
-#if HAVE_STRUCT_SOCKADDR_IN6
-    if (addr->ss_family == AF_INET6) {
-        return IN6_IS_ADDR_MULTICAST(&((struct sockaddr_in6 *)addr)->sin6_addr);
-    }
-#endif
-
-    return 0;
-}
-
 static int udp_socket_create(UDPContext *s,
                              struct sockaddr_storage *addr, int *addr_len)
 {
@@ -256,34 +238,50 @@ static int udp_port(struct sockaddr_storage *addr, int addr_len)
  *         'pkt_size=n'  : set max packet size
  *         'reuse=1'     : enable reusing the socket
  *
- * @param s1 media file context
+ * @param h media file context
  * @param uri of the remote server
  * @return zero if no error.
  */
-int udp_set_remote_url(URLContext *h, const char *uri)
+int ff_udp_set_remote_url(URLContext *h, const char *uri)
 {
     UDPContext *s = h->priv_data;
-    char hostname[256];
+    char hostname[256], buf[10];
     int port;
+    const char *p;
 
-    ff_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
+    av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
 
     /* set the destination address */
     s->dest_addr_len = udp_set_url(&s->dest_addr, hostname, port);
     if (s->dest_addr_len < 0) {
         return AVERROR(EIO);
     }
-    s->is_multicast = is_multicast_address(&s->dest_addr);
+    s->is_multicast = ff_is_multicast_address((struct sockaddr*) &s->dest_addr);
+    p = strchr(uri, '?');
+    if (p) {
+        if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
+            int was_connected = s->is_connected;
+            s->is_connected = strtol(buf, NULL, 10);
+            if (s->is_connected && !was_connected) {
+                if (connect(s->udp_fd, (struct sockaddr *) &s->dest_addr,
+                            s->dest_addr_len)) {
+                    s->is_connected = 0;
+                    av_log(NULL, AV_LOG_ERROR, "connect: %s\n", strerror(errno));
+                    return AVERROR(EIO);
+                }
+            }
+        }
+    }
 
     return 0;
 }
 
 /**
- * Return the local port used by the UDP connexion
- * @param s1 media file context
+ * Return the local port used by the UDP connection
+ * @param h media file context
  * @return the local port number
  */
-int udp_get_local_port(URLContext *h)
+int ff_udp_get_local_port(URLContext *h)
 {
     UDPContext *s = h->priv_data;
     return s->local_port;
@@ -294,7 +292,7 @@ int udp_get_local_port(URLContext *h)
  * streams at the same time.
  * @param h media file context
  */
-#if (LIBAVFORMAT_VERSION_MAJOR >= 53)
+#if !FF_API_UDP_GET_FILE
 static
 #endif
 int udp_get_file_handle(URLContext *h)
@@ -315,11 +313,12 @@ static int udp_open(URLContext *h, const char *uri, int flags)
     char buf[256];
     struct sockaddr_storage my_addr;
     int len;
+    int reuse_specified = 0;
 
     h->is_streamed = 1;
     h->max_packet_size = 1472;
 
-    is_output = (flags & URL_WRONLY);
+    is_output = (flags & AVIO_WRONLY);
 
     s = av_mallocz(sizeof(UDPContext));
     if (!s)
@@ -331,46 +330,62 @@ static int udp_open(URLContext *h, const char *uri, int flags)
 
     p = strchr(uri, '?');
     if (p) {
-        s->reuse_socket = find_info_tag(buf, sizeof(buf), "reuse", p);
-        if (find_info_tag(buf, sizeof(buf), "ttl", p)) {
+        if (av_find_info_tag(buf, sizeof(buf), "reuse", p)) {
+            const char *endptr=NULL;
+            s->reuse_socket = strtol(buf, &endptr, 10);
+            /* assume if no digits were found it is a request to enable it */
+            if (buf == endptr)
+                s->reuse_socket = 1;
+            reuse_specified = 1;
+        }
+        if (av_find_info_tag(buf, sizeof(buf), "ttl", p)) {
             s->ttl = strtol(buf, NULL, 10);
         }
-        if (find_info_tag(buf, sizeof(buf), "localport", p)) {
+        if (av_find_info_tag(buf, sizeof(buf), "localport", p)) {
             s->local_port = strtol(buf, NULL, 10);
         }
-        if (find_info_tag(buf, sizeof(buf), "pkt_size", p)) {
+        if (av_find_info_tag(buf, sizeof(buf), "pkt_size", p)) {
             h->max_packet_size = strtol(buf, NULL, 10);
         }
-        if (find_info_tag(buf, sizeof(buf), "buffer_size", p)) {
+        if (av_find_info_tag(buf, sizeof(buf), "buffer_size", p)) {
             s->buffer_size = strtol(buf, NULL, 10);
         }
+        if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
+            s->is_connected = strtol(buf, NULL, 10);
+        }
     }
 
     /* fill the dest addr */
-    ff_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
+    av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
 
-    /* XXX: fix ff_url_split */
+    /* XXX: fix av_url_split */
     if (hostname[0] == '\0' || hostname[0] == '?') {
         /* only accepts null hostname if input */
-        if (flags & URL_WRONLY)
+        if (flags & AVIO_WRONLY)
             goto fail;
     } else {
-        udp_set_remote_url(h, uri);
+        if (ff_udp_set_remote_url(h, uri) < 0)
+            goto fail;
     }
 
-    if (s->is_multicast && !(h->flags & URL_WRONLY))
+    if (s->is_multicast && !(h->flags & AVIO_WRONLY))
         s->local_port = port;
     udp_fd = udp_socket_create(s, &my_addr, &len);
     if (udp_fd < 0)
         goto fail;
 
-    if (s->reuse_socket)
+    /* Follow the requested reuse option, unless it's multicast in which
+     * case enable reuse unless explicitely disabled.
+     */
+    if (s->reuse_socket || (s->is_multicast && !reuse_specified)) {
+        s->reuse_socket = 1;
         if (setsockopt (udp_fd, SOL_SOCKET, SO_REUSEADDR, &(s->reuse_socket), sizeof(s->reuse_socket)) != 0)
             goto fail;
+    }
 
     /* the bind is needed to give a port to the socket now */
     /* if multicast, try the multicast address bind first */
-    if (s->is_multicast && !(h->flags & URL_WRONLY)) {
+    if (s->is_multicast && !(h->flags & AVIO_WRONLY)) {
         bind_ret = bind(udp_fd,(struct sockaddr *)&s->dest_addr, len);
     }
     /* bind to the local address if not multicast or if the multicast
@@ -383,7 +398,7 @@ static int udp_open(URLContext *h, const char *uri, int flags)
     s->local_port = udp_port(&my_addr, len);
 
     if (s->is_multicast) {
-        if (h->flags & URL_WRONLY) {
+        if (h->flags & AVIO_WRONLY) {
             /* output */
             if (udp_set_multicast_ttl(udp_fd, s->ttl, (struct sockaddr *)&s->dest_addr) < 0)
                 goto fail;
@@ -411,6 +426,12 @@ static int udp_open(URLContext *h, const char *uri, int flags)
         /* make the socket non-blocking */
         ff_socket_nonblock(udp_fd, 1);
     }
+    if (s->is_connected) {
+        if (connect(udp_fd, (struct sockaddr *) &s->dest_addr, s->dest_addr_len)) {
+            av_log(NULL, AV_LOG_ERROR, "connect: %s\n", strerror(errno));
+            goto fail;
+        }
+    }
 
     s->udp_fd = udp_fd;
     return 0;
@@ -424,75 +445,54 @@ static int udp_open(URLContext *h, const char *uri, int flags)
 static int udp_read(URLContext *h, uint8_t *buf, int size)
 {
     UDPContext *s = h->priv_data;
-    int len;
-    fd_set rfds;
     int ret;
-    struct timeval tv;
-
-    for(;;) {
-        if (url_interrupt_cb())
-            return AVERROR(EINTR);
-        FD_ZERO(&rfds);
-        FD_SET(s->udp_fd, &rfds);
-        tv.tv_sec = 0;
-        tv.tv_usec = 100 * 1000;
-        ret = select(s->udp_fd + 1, &rfds, NULL, NULL, &tv);
-        if (ret < 0) {
-            if (ff_neterrno() == FF_NETERROR(EINTR))
-                continue;
-            return AVERROR(EIO);
-        }
-        if (!(ret > 0 && FD_ISSET(s->udp_fd, &rfds)))
-            continue;
-        len = recv(s->udp_fd, buf, size, 0);
-        if (len < 0) {
-            if (ff_neterrno() != FF_NETERROR(EAGAIN) &&
-                ff_neterrno() != FF_NETERROR(EINTR))
-                return AVERROR(EIO);
-        } else {
-            break;
-        }
+
+    if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
+        ret = ff_network_wait_fd(s->udp_fd, 0);
+        if (ret < 0)
+            return ret;
     }
-    return len;
+    ret = recv(s->udp_fd, buf, size, 0);
+    return ret < 0 ? ff_neterrno() : ret;
 }
 
-static int udp_write(URLContext *h, uint8_t *buf, int size)
+static int udp_write(URLContext *h, const uint8_t *buf, int size)
 {
     UDPContext *s = h->priv_data;
     int ret;
 
-    for(;;) {
+    if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
+        ret = ff_network_wait_fd(s->udp_fd, 1);
+        if (ret < 0)
+            return ret;
+    }
+
+    if (!s->is_connected) {
         ret = sendto (s->udp_fd, buf, size, 0,
                       (struct sockaddr *) &s->dest_addr,
                       s->dest_addr_len);
-        if (ret < 0) {
-            if (ff_neterrno() != FF_NETERROR(EINTR) &&
-                ff_neterrno() != FF_NETERROR(EAGAIN))
-                return AVERROR(EIO);
-        } else {
-            break;
-        }
-    }
-    return size;
+    } else
+        ret = send(s->udp_fd, buf, size, 0);
+
+    return ret < 0 ? ff_neterrno() : ret;
 }
 
 static int udp_close(URLContext *h)
 {
     UDPContext *s = h->priv_data;
 
-    if (s->is_multicast && !(h->flags & URL_WRONLY))
+    if (s->is_multicast && !(h->flags & AVIO_WRONLY))
         udp_leave_multicast_group(s->udp_fd, (struct sockaddr *)&s->dest_addr);
     closesocket(s->udp_fd);
     av_free(s);
     return 0;
 }
 
-URLProtocol udp_protocol = {
-    "udp",
-    udp_open,
-    udp_read,
-    udp_write,
-    NULL, /* seek */
-    udp_close,
+URLProtocol ff_udp_protocol = {
+    .name                = "udp",
+    .url_open            = udp_open,
+    .url_read            = udp_read,
+    .url_write           = udp_write,
+    .url_close           = udp_close,
     .url_get_file_handle = udp_get_file_handle,
 };
diff --git a/libavformat/url.h b/libavformat/url.h
new file mode 100644
index 0000000..c5732c6
--- /dev/null
+++ b/libavformat/url.h
@@ -0,0 +1,176 @@
+/*
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * unbuffered private I/O API
+ */
+
+#ifndef AVFORMAT_URL_H
+#define AVFORMAT_URL_H
+
+#include "avio.h"
+#include "libavformat/version.h"
+
+#if !FF_API_OLD_AVIO
+#define URL_PROTOCOL_FLAG_NESTED_SCHEME 1 /*< The protocol name can be the first part of a nested protocol scheme */
+
+extern int (*url_interrupt_cb)(void);
+
+typedef struct URLContext {
+    const AVClass *av_class;    /**< information for av_log(). Set by url_open(). */
+    struct URLProtocol *prot;
+    void *priv_data;
+    char *filename;             /**< specified URL */
+    int flags;
+    int max_packet_size;        /**< if non zero, the stream is packetized with this max packet size */
+    int is_streamed;            /**< true if streamed (no seek possible), default = false */
+    int is_connected;
+} URLContext;
+
+typedef struct URLProtocol {
+    const char *name;
+    int     (*url_open)( URLContext *h, const char *url, int flags);
+    int     (*url_read)( URLContext *h, unsigned char *buf, int size);
+    int     (*url_write)(URLContext *h, const unsigned char *buf, int size);
+    int64_t (*url_seek)( URLContext *h, int64_t pos, int whence);
+    int     (*url_close)(URLContext *h);
+    struct URLProtocol *next;
+    int (*url_read_pause)(URLContext *h, int pause);
+    int64_t (*url_read_seek)(URLContext *h, int stream_index,
+                             int64_t timestamp, int flags);
+    int (*url_get_file_handle)(URLContext *h);
+    int priv_data_size;
+    const AVClass *priv_data_class;
+    int flags;
+    int (*url_check)(URLContext *h, int mask);
+} URLProtocol;
+#endif
+
+/**
+ * Create a URLContext for accessing to the resource indicated by
+ * url, but do not initiate the connection yet.
+ *
+ * @param puc pointer to the location where, in case of success, the
+ * function puts the pointer to the created URLContext
+ * @param flags flags which control how the resource indicated by url
+ * is to be opened
+ * @return 0 in case of success, a negative value corresponding to an
+ * AVERROR code in case of failure
+ */
+int ffurl_alloc(URLContext **h, const char *url, int flags);
+
+/**
+ * Connect an URLContext that has been allocated by ffurl_alloc
+ */
+int ffurl_connect(URLContext *h);
+
+/**
+ * Create an URLContext for accessing to the resource indicated by
+ * url, and open it.
+ *
+ * @param puc pointer to the location where, in case of success, the
+ * function puts the pointer to the created URLContext
+ * @param flags flags which control how the resource indicated by url
+ * is to be opened
+ * @return 0 in case of success, a negative value corresponding to an
+ * AVERROR code in case of failure
+ */
+int ffurl_open(URLContext **h, const char *url, int flags);
+
+/**
+ * Read up to size bytes from the resource accessed by h, and store
+ * the read bytes in buf.
+ *
+ * @return The number of bytes actually read, or a negative value
+ * corresponding to an AVERROR code in case of error. A value of zero
+ * indicates that it is not possible to read more from the accessed
+ * resource (except if the value of the size argument is also zero).
+ */
+int ffurl_read(URLContext *h, unsigned char *buf, int size);
+
+/**
+ * Read as many bytes as possible (up to size), calling the
+ * read function multiple times if necessary.
+ * This makes special short-read handling in applications
+ * unnecessary, if the return value is < size then it is
+ * certain there was either an error or the end of file was reached.
+ */
+int ffurl_read_complete(URLContext *h, unsigned char *buf, int size);
+
+/**
+ * Write size bytes from buf to the resource accessed by h.
+ *
+ * @return the number of bytes actually written, or a negative value
+ * corresponding to an AVERROR code in case of failure
+ */
+int ffurl_write(URLContext *h, const unsigned char *buf, int size);
+
+/**
+ * Change the position that will be used by the next read/write
+ * operation on the resource accessed by h.
+ *
+ * @param pos specifies the new position to set
+ * @param whence specifies how pos should be interpreted, it must be
+ * one of SEEK_SET (seek from the beginning), SEEK_CUR (seek from the
+ * current position), SEEK_END (seek from the end), or AVSEEK_SIZE
+ * (return the filesize of the requested resource, pos is ignored).
+ * @return a negative value corresponding to an AVERROR code in case
+ * of failure, or the resulting file position, measured in bytes from
+ * the beginning of the file. You can use this feature together with
+ * SEEK_CUR to read the current file position.
+ */
+int64_t ffurl_seek(URLContext *h, int64_t pos, int whence);
+
+/**
+ * Close the resource accessed by the URLContext h, and free the
+ * memory used by it.
+ *
+ * @return a negative value if an error condition occurred, 0
+ * otherwise
+ */
+int ffurl_close(URLContext *h);
+
+/**
+ * Return the filesize of the resource accessed by h, AVERROR(ENOSYS)
+ * if the operation is not supported by h, or another negative value
+ * corresponding to an AVERROR error code in case of failure.
+ */
+int64_t ffurl_size(URLContext *h);
+
+/**
+ * Return the file descriptor associated with this URL. For RTP, this
+ * will return only the RTP file descriptor, not the RTCP file descriptor.
+ *
+ * @return the file descriptor associated with this URL, or <0 on error.
+ */
+int ffurl_get_file_handle(URLContext *h);
+
+/**
+ * Register the URLProtocol protocol.
+ *
+ * @param size the size of the URLProtocol struct referenced
+ */
+int ffurl_register_protocol(URLProtocol *protocol, int size);
+
+/* udp.c */
+int ff_udp_set_remote_url(URLContext *h, const char *uri);
+int ff_udp_get_local_port(URLContext *h);
+
+#endif //AVFORMAT_URL_H
diff --git a/libavformat/utils.c b/libavformat/utils.c
index 6224a35..6b38e66 100644
--- a/libavformat/utils.c
+++ b/libavformat/utils.c
@@ -1,30 +1,37 @@
 /*
- * various utility functions for use within FFmpeg
+ * various utility functions for use within Libav
  * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
+
+/* #define DEBUG */
+
 #include "avformat.h"
+#include "avio_internal.h"
 #include "internal.h"
-#include "libavcodec/opt.h"
+#include "libavcodec/internal.h"
+#include "libavutil/opt.h"
 #include "metadata.h"
+#include "id3v2.h"
 #include "libavutil/avstring.h"
 #include "riff.h"
 #include "audiointerleave.h"
+#include "url.h"
 #include <sys/time.h>
 #include <time.h>
 #include <strings.h>
@@ -38,7 +45,7 @@
 
 /**
  * @file
- * various utility functions for use within FFmpeg
+ * various utility functions for use within Libav
  */
 
 unsigned avformat_version(void)
@@ -48,13 +55,13 @@ unsigned avformat_version(void)
 
 const char *avformat_configuration(void)
 {
-    return FFMPEG_CONFIGURATION;
+    return LIBAV_CONFIGURATION;
 }
 
 const char *avformat_license(void)
 {
 #define LICENSE_PREFIX "libavformat license: "
-    return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1;
+    return LICENSE_PREFIX LIBAV_LICENSE + sizeof(LICENSE_PREFIX) - 1;
 }
 
 /* fraction handling */
@@ -108,8 +115,14 @@ static void av_frac_add(AVFrac *f, int64_t incr)
 }
 
 /** head of registered input format linked list */
+#if !FF_API_FIRST_FORMAT
+static
+#endif
 AVInputFormat *first_iformat = NULL;
 /** head of registered output format linked list */
+#if !FF_API_FIRST_FORMAT
+static
+#endif
 AVOutputFormat *first_oformat = NULL;
 
 AVInputFormat  *av_iformat_next(AVInputFormat  *f)
@@ -187,7 +200,7 @@ static int match_format(const char *name, const char *names)
     return !strcasecmp(name, names);
 }
 
-#if LIBAVFORMAT_VERSION_MAJOR < 53
+#if FF_API_GUESS_FORMAT
 AVOutputFormat *guess_format(const char *short_name, const char *filename,
                              const char *mime_type)
 {
@@ -198,22 +211,21 @@ AVOutputFormat *guess_format(const char *short_name, const char *filename,
 AVOutputFormat *av_guess_format(const char *short_name, const char *filename,
                                 const char *mime_type)
 {
-    AVOutputFormat *fmt, *fmt_found;
+    AVOutputFormat *fmt = NULL, *fmt_found;
     int score_max, score;
 
     /* specific test for image sequences */
 #if CONFIG_IMAGE2_MUXER
     if (!short_name && filename &&
         av_filename_number_test(filename) &&
-        av_guess_image2_codec(filename) != CODEC_ID_NONE) {
+        ff_guess_image2_codec(filename) != CODEC_ID_NONE) {
         return av_guess_format("image2", NULL, NULL);
     }
 #endif
     /* Find the proper file type. */
     fmt_found = NULL;
     score_max = 0;
-    fmt = first_oformat;
-    while (fmt != NULL) {
+    while ((fmt = av_oformat_next(fmt))) {
         score = 0;
         if (fmt->name && short_name && !strcmp(fmt->name, short_name))
             score += 100;
@@ -227,12 +239,11 @@ AVOutputFormat *av_guess_format(const char *short_name, const char *filename,
             score_max = score;
             fmt_found = fmt;
         }
-        fmt = fmt->next;
     }
     return fmt_found;
 }
 
-#if LIBAVFORMAT_VERSION_MAJOR < 53
+#if FF_API_GUESS_FORMAT
 AVOutputFormat *guess_stream_format(const char *short_name, const char *filename,
                              const char *mime_type)
 {
@@ -260,7 +271,7 @@ enum CodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name,
 
 #if CONFIG_IMAGE2_MUXER
         if(!strcmp(fmt->name, "image2") || !strcmp(fmt->name, "image2pipe")){
-            codec_id= av_guess_image2_codec(filename);
+            codec_id= ff_guess_image2_codec(filename);
         }
 #endif
         if(codec_id == CODEC_ID_NONE)
@@ -268,21 +279,23 @@ enum CodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name,
         return codec_id;
     }else if(type == AVMEDIA_TYPE_AUDIO)
         return fmt->audio_codec;
+    else if (type == AVMEDIA_TYPE_SUBTITLE)
+        return fmt->subtitle_codec;
     else
         return CODEC_ID_NONE;
 }
 
 AVInputFormat *av_find_input_format(const char *short_name)
 {
-    AVInputFormat *fmt;
-    for(fmt = first_iformat; fmt != NULL; fmt = fmt->next) {
+    AVInputFormat *fmt = NULL;
+    while ((fmt = av_iformat_next(fmt))) {
         if (match_format(short_name, fmt->name))
             return fmt;
     }
     return NULL;
 }
 
-#if LIBAVFORMAT_VERSION_MAJOR < 53 && CONFIG_SHARED && HAVE_SYMVER
+#if FF_API_SYMVER && CONFIG_SHARED && HAVE_SYMVER
 FF_SYMVER(void, av_destruct_packet_nofree, (AVPacket *pkt), "LIBAVFORMAT_52")
 {
     av_destruct_packet_nofree(pkt);
@@ -315,16 +328,16 @@ FF_SYMVER(void, av_init_packet, (AVPacket *pkt), "LIBAVFORMAT_52")
 }
 #endif
 
-int av_get_packet(ByteIOContext *s, AVPacket *pkt, int size)
+int av_get_packet(AVIOContext *s, AVPacket *pkt, int size)
 {
     int ret= av_new_packet(pkt, size);
 
     if(ret<0)
         return ret;
 
-    pkt->pos= url_ftell(s);
+    pkt->pos= avio_tell(s);
 
-    ret= get_buffer(s, pkt->data, size);
+    ret= avio_read(s, pkt->data, size);
     if(ret<=0)
         av_free_packet(pkt);
     else
@@ -333,6 +346,21 @@ int av_get_packet(ByteIOContext *s, AVPacket *pkt, int size)
     return ret;
 }
 
+int av_append_packet(AVIOContext *s, AVPacket *pkt, int size)
+{
+    int ret;
+    int old_size;
+    if (!pkt->size)
+        return av_get_packet(s, pkt, size);
+    old_size = pkt->size;
+    ret = av_grow_packet(pkt, size);
+    if (ret < 0)
+        return ret;
+    ret = avio_read(s, pkt->data + old_size, size);
+    av_shrink_packet(pkt, old_size + FFMAX(ret, 0));
+    return ret;
+}
+
 
 int av_filename_number_test(const char *filename)
 {
@@ -342,18 +370,28 @@ int av_filename_number_test(const char *filename)
 
 AVInputFormat *av_probe_input_format2(AVProbeData *pd, int is_opened, int *score_max)
 {
-    AVInputFormat *fmt1, *fmt;
-    int score;
+    AVProbeData lpd = *pd;
+    AVInputFormat *fmt1 = NULL, *fmt;
+    int score, id3 = 0;
+
+    if (lpd.buf_size > 10 && ff_id3v2_match(lpd.buf, ID3v2_DEFAULT_MAGIC)) {
+        int id3len = ff_id3v2_tag_len(lpd.buf);
+        if (lpd.buf_size > id3len + 16) {
+            lpd.buf += id3len;
+            lpd.buf_size -= id3len;
+        }
+        id3 = 1;
+    }
 
     fmt = NULL;
-    for(fmt1 = first_iformat; fmt1 != NULL; fmt1 = fmt1->next) {
+    while ((fmt1 = av_iformat_next(fmt1))) {
         if (!is_opened == !(fmt1->flags & AVFMT_NOFILE))
             continue;
         score = 0;
         if (fmt1->read_probe) {
-            score = fmt1->read_probe(pd);
+            score = fmt1->read_probe(&lpd);
         } else if (fmt1->extensions) {
-            if (av_match_ext(pd->filename, fmt1->extensions)) {
+            if (av_match_ext(lpd.filename, fmt1->extensions)) {
                 score = 50;
             }
         }
@@ -363,6 +401,16 @@ AVInputFormat *av_probe_input_format2(AVProbeData *pd, int is_opened, int *score
         }else if (score == *score_max)
             fmt = NULL;
     }
+
+    /* a hack for files with huge id3v2 tags -- try to guess by file extension. */
+    if (!fmt && id3 && *score_max < AVPROBE_SCORE_MAX/4) {
+        while ((fmt = av_iformat_next(fmt)))
+            if (fmt->extensions && av_match_ext(lpd.filename, fmt->extensions)) {
+                *score_max = AVPROBE_SCORE_MAX/4;
+                break;
+            }
+    }
+
     return fmt;
 }
 
@@ -373,36 +421,31 @@ AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened){
 
 static int set_codec_from_probe_data(AVFormatContext *s, AVStream *st, AVProbeData *pd, int score)
 {
-    AVInputFormat *fmt;
-    fmt = av_probe_input_format2(pd, 1, &score);
+    static const struct {
+        const char *name; enum CodecID id; enum AVMediaType type;
+    } fmt_id_type[] = {
+        { "aac"      , CODEC_ID_AAC       , AVMEDIA_TYPE_AUDIO },
+        { "ac3"      , CODEC_ID_AC3       , AVMEDIA_TYPE_AUDIO },
+        { "dts"      , CODEC_ID_DTS       , AVMEDIA_TYPE_AUDIO },
+        { "eac3"     , CODEC_ID_EAC3      , AVMEDIA_TYPE_AUDIO },
+        { "h264"     , CODEC_ID_H264      , AVMEDIA_TYPE_VIDEO },
+        { "m4v"      , CODEC_ID_MPEG4     , AVMEDIA_TYPE_VIDEO },
+        { "mp3"      , CODEC_ID_MP3       , AVMEDIA_TYPE_AUDIO },
+        { "mpegvideo", CODEC_ID_MPEG2VIDEO, AVMEDIA_TYPE_VIDEO },
+        { 0 }
+    };
+    AVInputFormat *fmt = av_probe_input_format2(pd, 1, &score);
 
     if (fmt) {
+        int i;
         av_log(s, AV_LOG_DEBUG, "Probe with size=%d, packets=%d detected %s with score=%d\n",
                pd->buf_size, MAX_PROBE_PACKETS - st->probe_packets, fmt->name, score);
-        if (!strcmp(fmt->name, "mp3")) {
-            st->codec->codec_id = CODEC_ID_MP3;
-            st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
-        } else if (!strcmp(fmt->name, "ac3")) {
-            st->codec->codec_id = CODEC_ID_AC3;
-            st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
-        } else if (!strcmp(fmt->name, "eac3")) {
-            st->codec->codec_id = CODEC_ID_EAC3;
-            st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
-        } else if (!strcmp(fmt->name, "mpegvideo")) {
-            st->codec->codec_id = CODEC_ID_MPEG2VIDEO;
-            st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
-        } else if (!strcmp(fmt->name, "m4v")) {
-            st->codec->codec_id = CODEC_ID_MPEG4;
-            st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
-        } else if (!strcmp(fmt->name, "h264")) {
-            st->codec->codec_id = CODEC_ID_H264;
-            st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
-        } else if (!strcmp(fmt->name, "dts")) {
-            st->codec->codec_id = CODEC_ID_DTS;
-            st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
-        } else if (!strcmp(fmt->name, "aac")) {
-            st->codec->codec_id = CODEC_ID_AAC;
-            st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
+        for (i = 0; fmt_id_type[i].name; i++) {
+            if (!strcmp(fmt->name, fmt_id_type[i].name)) {
+                st->codec->codec_id   = fmt_id_type[i].id;
+                st->codec->codec_type = fmt_id_type[i].type;
+                break;
+            }
         }
     }
     return !!fmt;
@@ -415,7 +458,7 @@ static int set_codec_from_probe_data(AVFormatContext *s, AVStream *st, AVProbeDa
  * Open a media file from an IO stream. 'fmt' must be specified.
  */
 int av_open_input_stream(AVFormatContext **ic_ptr,
-                         ByteIOContext *pb, const char *filename,
+                         AVIOContext *pb, const char *filename,
                          AVInputFormat *fmt, AVFormatParameters *ap)
 {
     int err;
@@ -452,6 +495,10 @@ int av_open_input_stream(AVFormatContext **ic_ptr,
         ic->priv_data = NULL;
     }
 
+    // e.g. AVFMT_NOFILE formats will not have a AVIOContext
+    if (ic->pb)
+        ff_id3v2_read(ic, ID3v2_DEFAULT_MAGIC);
+
     if (ic->iformat->read_header) {
         err = ic->iformat->read_header(ic, ap);
         if (err < 0)
@@ -459,9 +506,9 @@ int av_open_input_stream(AVFormatContext **ic_ptr,
     }
 
     if (pb && !ic->data_offset)
-        ic->data_offset = url_ftell(ic->pb);
+        ic->data_offset = avio_tell(ic->pb);
 
-#if LIBAVFORMAT_VERSION_MAJOR < 53
+#if FF_API_OLD_METADATA
     ff_metadata_demux_compat(ic);
 #endif
 
@@ -478,6 +525,8 @@ int av_open_input_stream(AVFormatContext **ic_ptr,
             if (st) {
                 av_free(st->priv_data);
                 av_free(st->codec->extradata);
+                av_free(st->codec);
+                av_free(st->info);
             }
             av_free(st);
         }
@@ -491,7 +540,7 @@ int av_open_input_stream(AVFormatContext **ic_ptr,
 #define PROBE_BUF_MIN 2048
 #define PROBE_BUF_MAX (1<<20)
 
-int ff_probe_input_buffer(ByteIOContext **pb, AVInputFormat **fmt,
+int av_probe_input_buffer(AVIOContext *pb, AVInputFormat **fmt,
                           const char *filename, void *logctx,
                           unsigned int offset, unsigned int max_probe_size)
 {
@@ -522,7 +571,7 @@ int ff_probe_input_buffer(ByteIOContext **pb, AVInputFormat **fmt,
 
         /* read probe data */
         buf = av_realloc(buf, probe_size + AVPROBE_PADDING_SIZE);
-        if ((ret = get_buffer(*pb, buf + buf_offset, probe_size - buf_offset)) < 0) {
+        if ((ret = avio_read(pb, buf + buf_offset, probe_size - buf_offset)) < 0) {
             /* fail if error was not end of file, otherwise, lower score */
             if (ret != AVERROR_EOF) {
                 av_free(buf);
@@ -552,7 +601,7 @@ int ff_probe_input_buffer(ByteIOContext **pb, AVInputFormat **fmt,
     }
 
     /* rewind. reuse probe buffer to avoid seeking */
-    if ((ret = ff_rewind_with_probe_data(*pb, buf, pd.buf_size)) < 0)
+    if ((ret = ffio_rewind_with_probe_data(pb, buf, pd.buf_size)) < 0)
         av_free(buf);
 
     return ret;
@@ -565,7 +614,7 @@ int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
 {
     int err;
     AVProbeData probe_data, *pd = &probe_data;
-    ByteIOContext *pb = NULL;
+    AVIOContext *pb = NULL;
     void *logctx= ap && ap->prealloced_context ? *ic_ptr : NULL;
 
     pd->filename = "";
@@ -583,13 +632,13 @@ int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
        hack needed to handle RTSP/TCP */
     if (!fmt || !(fmt->flags & AVFMT_NOFILE)) {
         /* if no file needed do not try to open one */
-        if ((err=url_fopen(&pb, filename, URL_RDONLY)) < 0) {
+        if ((err=avio_open(&pb, filename, AVIO_RDONLY)) < 0) {
             goto fail;
         }
         if (buf_size > 0) {
-            url_setbufsize(pb, buf_size);
+            ffio_set_buf_size(pb, buf_size);
         }
-        if (!fmt && (err = ff_probe_input_buffer(&pb, &fmt, filename, logctx, 0, logctx ? (*ic_ptr)->probesize : 0)) < 0) {
+        if (!fmt && (err = av_probe_input_buffer(pb, &fmt, filename, logctx, 0, logctx ? (*ic_ptr)->probesize : 0)) < 0) {
             goto fail;
         }
     }
@@ -614,7 +663,7 @@ int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
  fail:
     av_freep(&pd->buf);
     if (pb)
-        url_fclose(pb);
+        avio_close(pb);
     if (ap && ap->prealloced_context)
         av_free(*ic_ptr);
     *ic_ptr = NULL;
@@ -779,7 +828,7 @@ static void compute_frame_duration(int *pnum, int *pden, AVStream *st,
         break;
     case AVMEDIA_TYPE_AUDIO:
         frame_size = get_audio_frame_size(st->codec, pkt->size);
-        if (frame_size < 0)
+        if (frame_size <= 0 || st->codec->sample_rate <= 0)
             break;
         *pnum = frame_size;
         *pden = st->codec->sample_rate;
@@ -897,6 +946,12 @@ static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
     /* do we have a video B-frame ? */
     delay= st->codec->has_b_frames;
     presentation_delayed = 0;
+
+    // ignore delay caused by frame threading so that the mpeg2-without-dts
+    // warning will not trigger
+    if (delay && st->codec->active_thread_type&FF_THREAD_FRAME)
+        delay -= st->codec->thread_count-1;
+
     /* XXX: need has_b_frame, but cannot get it if the codec is
         not initialized */
     if (delay &&
@@ -912,7 +967,7 @@ static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
     // we take the conservative approach and discard both
     // Note, if this is misbehaving for a H.264 file then possibly presentation_delayed is not set correctly.
     if(delay==1 && pkt->dts == pkt->pts && pkt->dts != AV_NOPTS_VALUE && presentation_delayed){
-        av_log(s, AV_LOG_WARNING, "invalid dts/pts combination\n");
+        av_log(s, AV_LOG_DEBUG, "invalid dts/pts combination\n");
         pkt->dts= pkt->pts= AV_NOPTS_VALUE;
     }
 
@@ -1078,7 +1133,15 @@ static int av_read_frame_internal(AVFormatContext *s, AVPacket *pkt)
                     pkt->pts = st->parser->pts;
                     pkt->dts = st->parser->dts;
                     pkt->pos = st->parser->pos;
+                    if(pkt->data == st->cur_pkt.data && pkt->size == st->cur_pkt.size){
+                        s->cur_st = NULL;
+                        pkt->destruct= st->cur_pkt.destruct;
+                        st->cur_pkt.destruct= NULL;
+                        st->cur_pkt.data    = NULL;
+                        assert(st->cur_len == 0);
+                    }else{
                     pkt->destruct = NULL;
+                    }
                     compute_pkt_fields(s, st, st->parser, pkt);
 
                     if((s->iformat->flags & AVFMT_GENERIC_INDEX) && pkt->flags & AV_PKT_FLAG_KEY){
@@ -1151,10 +1214,8 @@ static int av_read_frame_internal(AVFormatContext *s, AVPacket *pkt)
                     st->need_parsing = AVSTREAM_PARSE_NONE;
                 }else if(st->need_parsing == AVSTREAM_PARSE_HEADERS){
                     st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
-                }
-                if(st->parser && (s->iformat->flags & AVFMT_GENERIC_INDEX)){
-                    st->parser->next_frame_offset=
-                    st->parser->cur_offset= st->cur_pkt.pos;
+                }else if(st->need_parsing == AVSTREAM_PARSE_FULL_ONCE){
+                    st->parser->flags |= PARSER_FLAG_ONCE;
                 }
             }
         }
@@ -1183,11 +1244,11 @@ int av_read_frame(AVFormatContext *s, AVPacket *pkt)
             AVPacket *next_pkt= &pktl->pkt;
 
             if(genpts && next_pkt->dts != AV_NOPTS_VALUE){
+                int wrap_bits = s->streams[next_pkt->stream_index]->pts_wrap_bits;
                 while(pktl && next_pkt->pts == AV_NOPTS_VALUE){
                     if(   pktl->pkt.stream_index == next_pkt->stream_index
-                       && next_pkt->dts < pktl->pkt.dts
-                       && pktl->pkt.pts != pktl->pkt.dts //not b frame
-                       /*&& pktl->pkt.dts != AV_NOPTS_VALUE*/){
+                       && (0 > av_compare_mod(next_pkt->dts, pktl->pkt.dts, 2LL << (wrap_bits - 1)))
+                       && av_compare_mod(pktl->pkt.pts, pktl->pkt.dts, 2LL << (wrap_bits - 1))) { //not b frame
                         next_pkt->pts= pktl->pkt.dts;
                     }
                     pktl= pktl->next;
@@ -1331,28 +1392,30 @@ void ff_reduce_index(AVFormatContext *s, int stream_index)
     }
 }
 
-int av_add_index_entry(AVStream *st,
-                            int64_t pos, int64_t timestamp, int size, int distance, int flags)
+int ff_add_index_entry(AVIndexEntry **index_entries,
+                       int *nb_index_entries,
+                       unsigned int *index_entries_allocated_size,
+                       int64_t pos, int64_t timestamp, int size, int distance, int flags)
 {
     AVIndexEntry *entries, *ie;
     int index;
 
-    if((unsigned)st->nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
+    if((unsigned)*nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
         return -1;
 
-    entries = av_fast_realloc(st->index_entries,
-                              &st->index_entries_allocated_size,
-                              (st->nb_index_entries + 1) *
+    entries = av_fast_realloc(*index_entries,
+                              index_entries_allocated_size,
+                              (*nb_index_entries + 1) *
                               sizeof(AVIndexEntry));
     if(!entries)
         return -1;
 
-    st->index_entries= entries;
+    *index_entries= entries;
 
-    index= av_index_search_timestamp(st, timestamp, AVSEEK_FLAG_ANY);
+    index= ff_index_search_timestamp(*index_entries, *nb_index_entries, timestamp, AVSEEK_FLAG_ANY);
 
     if(index<0){
-        index= st->nb_index_entries++;
+        index= (*nb_index_entries)++;
         ie= &entries[index];
         assert(index==0 || ie[-1].timestamp < timestamp);
     }else{
@@ -1360,8 +1423,8 @@ int av_add_index_entry(AVStream *st,
         if(ie->timestamp != timestamp){
             if(ie->timestamp <= timestamp)
                 return -1;
-            memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(st->nb_index_entries - index));
-            st->nb_index_entries++;
+            memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(*nb_index_entries - index));
+            (*nb_index_entries)++;
         }else if(ie->pos == pos && distance < ie->min_distance) //do not reduce the distance
             distance= ie->min_distance;
     }
@@ -1375,11 +1438,17 @@ int av_add_index_entry(AVStream *st,
     return index;
 }
 
-int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp,
-                              int flags)
+int av_add_index_entry(AVStream *st,
+                       int64_t pos, int64_t timestamp, int size, int distance, int flags)
+{
+    return ff_add_index_entry(&st->index_entries, &st->nb_index_entries,
+                              &st->index_entries_allocated_size, pos,
+                              timestamp, size, distance, flags);
+}
+
+int ff_index_search_timestamp(const AVIndexEntry *entries, int nb_entries,
+                              int64_t wanted_timestamp, int flags)
 {
-    AVIndexEntry *entries= st->index_entries;
-    int nb_entries= st->nb_index_entries;
     int a, b, m;
     int64_t timestamp;
 
@@ -1411,6 +1480,13 @@ int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp,
     return  m;
 }
 
+int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp,
+                              int flags)
+{
+    return ff_index_search_timestamp(st->index_entries, st->nb_index_entries,
+                                     wanted_timestamp, flags);
+}
+
 #define DEBUG_SEEK
 
 int av_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
@@ -1471,7 +1547,7 @@ int av_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts
         return -1;
 
     /* do the seek */
-    if ((ret = url_fseek(s->pb, pos, SEEK_SET)) < 0)
+    if ((ret = avio_seek(s->pb, pos, SEEK_SET)) < 0)
         return ret;
 
     av_update_cur_dts(s, st, ts);
@@ -1497,7 +1573,7 @@ int64_t av_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts, i
 
     if(ts_max == AV_NOPTS_VALUE){
         int step= 1024;
-        filesize = url_fsize(s->pb);
+        filesize = avio_size(s->pb);
         pos_max = filesize - 1;
         do{
             pos_max -= step;
@@ -1606,12 +1682,12 @@ static int av_seek_frame_byte(AVFormatContext *s, int stream_index, int64_t pos,
 #endif
 
     pos_min = s->data_offset;
-    pos_max = url_fsize(s->pb) - 1;
+    pos_max = avio_size(s->pb) - 1;
 
     if     (pos < pos_min) pos= pos_min;
     else if(pos > pos_max) pos= pos_max;
 
-    url_fseek(s->pb, pos, SEEK_SET);
+    avio_seek(s->pb, pos, SEEK_SET);
 
 #if 0
     av_update_cur_dts(s, st, ts);
@@ -1641,11 +1717,11 @@ static int av_seek_frame_generic(AVFormatContext *s,
         if(st->nb_index_entries){
             assert(st->index_entries);
             ie= &st->index_entries[st->nb_index_entries-1];
-            if ((ret = url_fseek(s->pb, ie->pos, SEEK_SET)) < 0)
+            if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
                 return ret;
             av_update_cur_dts(s, st, ie->timestamp);
         }else{
-            if ((ret = url_fseek(s->pb, s->data_offset, SEEK_SET)) < 0)
+            if ((ret = avio_seek(s->pb, s->data_offset, SEEK_SET)) < 0)
                 return ret;
         }
         for(i=0;; i++) {
@@ -1672,7 +1748,7 @@ static int av_seek_frame_generic(AVFormatContext *s,
             return 0;
     }
     ie = &st->index_entries[index];
-    if ((ret = url_fseek(s->pb, ie->pos, SEEK_SET)) < 0)
+    if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
         return ret;
     av_update_cur_dts(s, st, ie->timestamp);
 
@@ -1739,7 +1815,7 @@ int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts, int
 /*******************************************************/
 
 /**
- * Returns TRUE if the stream has accurate duration in any stream.
+ * Return TRUE if the stream has accurate duration in any stream.
  *
  * @return TRUE if the stream has accurate duration for at least one component.
  */
@@ -1831,10 +1907,11 @@ static void av_estimate_timings_from_bit_rate(AVFormatContext *ic)
     AVStream *st;
 
     /* if bit_rate is already set, we believe it */
-    if (ic->bit_rate == 0) {
+    if (ic->bit_rate <= 0) {
         bit_rate = 0;
         for(i=0;i<ic->nb_streams;i++) {
             st = ic->streams[i];
+            if (st->codec->bit_rate > 0)
             bit_rate += st->codec->bit_rate;
         }
         ic->bit_rate = bit_rate;
@@ -1865,7 +1942,7 @@ static void av_estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset
     AVPacket pkt1, *pkt = &pkt1;
     AVStream *st;
     int read_size, i, ret;
-    int64_t end_time, start_time[MAX_STREAMS];
+    int64_t end_time;
     int64_t filesize, offset, duration;
     int retry=0;
 
@@ -1874,13 +1951,9 @@ static void av_estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset
     /* flush packet queue */
     flush_packet_queue(ic);
 
-    for(i=0;i<ic->nb_streams;i++) {
+    for (i=0; i<ic->nb_streams; i++) {
         st = ic->streams[i];
-        if(st->start_time != AV_NOPTS_VALUE){
-            start_time[i]= st->start_time;
-        }else if(st->first_dts != AV_NOPTS_VALUE){
-            start_time[i]= st->first_dts;
-        }else
+        if (st->start_time == AV_NOPTS_VALUE && st->first_dts == AV_NOPTS_VALUE)
             av_log(st->codec, AV_LOG_WARNING, "start time is not set in av_estimate_timings_from_pts\n");
 
         if (st->parser) {
@@ -1899,7 +1972,7 @@ static void av_estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset
     if (offset < 0)
         offset = 0;
 
-    url_fseek(ic->pb, offset, SEEK_SET);
+    avio_seek(ic->pb, offset, SEEK_SET);
     read_size = 0;
     for(;;) {
         if (read_size >= DURATION_MAX_READ_SIZE<<(FFMAX(retry-1,0)))
@@ -1913,9 +1986,11 @@ static void av_estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset
         read_size += pkt->size;
         st = ic->streams[pkt->stream_index];
         if (pkt->pts != AV_NOPTS_VALUE &&
-            start_time[pkt->stream_index] != AV_NOPTS_VALUE) {
-            end_time = pkt->pts;
-            duration = end_time - start_time[pkt->stream_index];
+            (st->start_time != AV_NOPTS_VALUE ||
+             st->first_dts  != AV_NOPTS_VALUE)) {
+            duration = end_time = pkt->pts;
+            if (st->start_time != AV_NOPTS_VALUE)  duration -= st->start_time;
+            else                                   duration -= st->first_dts;
             if (duration < 0)
                 duration += 1LL<<st->pts_wrap_bits;
             if (duration > 0) {
@@ -1932,8 +2007,8 @@ static void av_estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset
 
     fill_all_stream_timings(ic);
 
-    url_fseek(ic->pb, old_offset, SEEK_SET);
-    for(i=0; i<ic->nb_streams; i++){
+    avio_seek(ic->pb, old_offset, SEEK_SET);
+    for (i=0; i<ic->nb_streams; i++) {
         st= ic->streams[i];
         st->cur_dts= st->first_dts;
         st->last_IP_pts = AV_NOPTS_VALUE;
@@ -1948,7 +2023,7 @@ static void av_estimate_timings(AVFormatContext *ic, int64_t old_offset)
     if (ic->iformat->flags & AVFMT_NOFILE) {
         file_size = 0;
     } else {
-        file_size = url_fsize(ic->pb);
+        file_size = avio_size(ic->pb);
         if (file_size < 0)
             file_size = 0;
     }
@@ -1956,7 +2031,7 @@ static void av_estimate_timings(AVFormatContext *ic, int64_t old_offset)
 
     if ((!strcmp(ic->iformat->name, "mpeg") ||
          !strcmp(ic->iformat->name, "mpegts")) &&
-        file_size && !url_is_streamed(ic->pb)) {
+        file_size && ic->pb->seekable) {
         /* get accurate estimate from the PTSes */
         av_estimate_timings_from_pts(ic, old_offset);
     } else if (av_has_duration(ic)) {
@@ -1993,7 +2068,7 @@ static int has_codec_parameters(AVCodecContext *enc)
     int val;
     switch(enc->codec_type) {
     case AVMEDIA_TYPE_AUDIO:
-        val = enc->sample_rate && enc->channels && enc->sample_fmt != SAMPLE_FMT_NONE;
+        val = enc->sample_rate && enc->channels && enc->sample_fmt != AV_SAMPLE_FMT_NONE;
         if(!enc->frame_size &&
            (enc->codec_id == CODEC_ID_VORBIS ||
             enc->codec_id == CODEC_ID_AAC ||
@@ -2013,6 +2088,12 @@ static int has_codec_parameters(AVCodecContext *enc)
     return enc->codec_id != CODEC_ID_NONE && val != 0;
 }
 
+static int has_decode_delay_been_guessed(AVStream *st)
+{
+    return st->codec->codec_id != CODEC_ID_H264 ||
+        st->codec_info_nb_frames >= 6 + st->codec->has_b_frames;
+}
+
 static int try_decode_frame(AVStream *st, AVPacket *avpkt)
 {
     int16_t *samples;
@@ -2029,7 +2110,7 @@ static int try_decode_frame(AVStream *st, AVPacket *avpkt)
             return ret;
     }
 
-    if(!has_codec_parameters(st->codec)){
+    if(!has_codec_parameters(st->codec) || !has_decode_delay_been_guessed(st)){
         switch(st->codec->codec_type) {
         case AVMEDIA_TYPE_VIDEO:
             avcodec_get_frame_defaults(&picture);
@@ -2053,7 +2134,7 @@ static int try_decode_frame(AVStream *st, AVPacket *avpkt)
     return ret;
 }
 
-unsigned int ff_codec_get_tag(const AVCodecTag *tags, int id)
+unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum CodecID id)
 {
     while (tags->id != CODEC_ID_NONE) {
         if (tags->id == id)
@@ -2071,10 +2152,7 @@ enum CodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
             return tags[i].id;
     }
     for(i=0; tags[i].id != CODEC_ID_NONE; i++) {
-        if(   toupper((tag >> 0)&0xFF) == toupper((tags[i].tag >> 0)&0xFF)
-           && toupper((tag >> 8)&0xFF) == toupper((tags[i].tag >> 8)&0xFF)
-           && toupper((tag >>16)&0xFF) == toupper((tags[i].tag >>16)&0xFF)
-           && toupper((tag >>24)&0xFF) == toupper((tags[i].tag >>24)&0xFF))
+        if (ff_toupper4(tag) == ff_toupper4(tags[i].tag))
             return tags[i].id;
     }
     return CODEC_ID_NONE;
@@ -2102,25 +2180,25 @@ enum CodecID av_codec_get_id(const AVCodecTag * const *tags, unsigned int tag)
 
 static void compute_chapters_end(AVFormatContext *s)
 {
-    unsigned int i;
+    unsigned int i, j;
+    int64_t max_time = s->duration + (s->start_time == AV_NOPTS_VALUE) ? 0 : s->start_time;
 
-    for (i=0; i+1<s->nb_chapters; i++)
+    for (i = 0; i < s->nb_chapters; i++)
         if (s->chapters[i]->end == AV_NOPTS_VALUE) {
-            assert(s->chapters[i]->start <= s->chapters[i+1]->start);
-            assert(!av_cmp_q(s->chapters[i]->time_base, s->chapters[i+1]->time_base));
-            s->chapters[i]->end = s->chapters[i+1]->start;
+            AVChapter *ch = s->chapters[i];
+            int64_t   end = max_time ? av_rescale_q(max_time, AV_TIME_BASE_Q, ch->time_base)
+                                     : INT64_MAX;
+
+            for (j = 0; j < s->nb_chapters; j++) {
+                AVChapter *ch1 = s->chapters[j];
+                int64_t next_start = av_rescale_q(ch1->start, ch1->time_base, ch->time_base);
+                if (j != i && next_start > ch->start && next_start < end)
+                    end = next_start;
+            }
+            ch->end = (end == INT64_MAX) ? ch->start : end;
         }
-
-    if (s->nb_chapters && s->chapters[i]->end == AV_NOPTS_VALUE) {
-        assert(s->start_time != AV_NOPTS_VALUE);
-        assert(s->duration > 0);
-        s->chapters[i]->end = av_rescale_q(s->start_time + s->duration,
-                                           AV_TIME_BASE_Q,
-                                           s->chapters[i]->time_base);
-    }
 }
 
-#define MAX_STD_TIMEBASES (60*12+5)
 static int get_std_framerate(int i){
     if(i<60*12) return i*1001;
     else        return ((const int[]){24,30,60,12,15})[i-60*12]*1000*12;
@@ -2151,24 +2229,18 @@ int av_find_stream_info(AVFormatContext *ic)
     int i, count, ret, read_size, j;
     AVStream *st;
     AVPacket pkt1, *pkt;
-    int64_t last_dts[MAX_STREAMS];
-    int64_t duration_gcd[MAX_STREAMS]={0};
-    int duration_count[MAX_STREAMS]={0};
-    double (*duration_error)[MAX_STD_TIMEBASES];
-    int64_t old_offset = url_ftell(ic->pb);
-    int64_t codec_info_duration[MAX_STREAMS]={0};
-
-    duration_error = av_mallocz(MAX_STREAMS * sizeof(*duration_error));
-    if (!duration_error) return AVERROR(ENOMEM);
+    int64_t old_offset = avio_tell(ic->pb);
 
     for(i=0;i<ic->nb_streams;i++) {
+        AVCodec *codec;
         st = ic->streams[i];
         if (st->codec->codec_id == CODEC_ID_AAC) {
             st->codec->sample_rate = 0;
             st->codec->frame_size = 0;
             st->codec->channels = 0;
         }
-        if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO){
+        if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
+            st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
 /*            if(!st->time_base.num)
                 st->time_base= */
             if(!st->codec->time_base.num)
@@ -2182,23 +2254,36 @@ int av_find_stream_info(AVFormatContext *ic)
             }
         }
         assert(!st->codec->codec);
+        codec = avcodec_find_decoder(st->codec->codec_id);
+
+        /* Force decoding of at least one frame of codec data
+         * this makes sure the codec initializes the channel configuration
+         * and does not trust the values from the container.
+         */
+        if (codec && codec->capabilities & CODEC_CAP_CHANNEL_CONF)
+            st->codec->channels = 0;
+
+        /* Ensure that subtitle_header is properly set. */
+        if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE
+            && codec && !st->codec->codec)
+            avcodec_open(st->codec, codec);
+
         //try to just open decoders, in case this is enough to get parameters
         if(!has_codec_parameters(st->codec)){
-            AVCodec *codec = avcodec_find_decoder(st->codec->codec_id);
-            if (codec)
+            if (codec && !st->codec->codec)
                 avcodec_open(st->codec, codec);
         }
     }
 
-    for(i=0;i<MAX_STREAMS;i++){
-        last_dts[i]= AV_NOPTS_VALUE;
+    for (i=0; i<ic->nb_streams; i++) {
+        ic->streams[i]->info->last_dts = AV_NOPTS_VALUE;
     }
 
     count = 0;
     read_size = 0;
     for(;;) {
         if(url_interrupt_cb()){
-            ret= AVERROR(EINTR);
+            ret= AVERROR_EXIT;
             av_log(ic, AV_LOG_DEBUG, "interrupted\n");
             break;
         }
@@ -2210,7 +2295,7 @@ int av_find_stream_info(AVFormatContext *ic)
                 break;
             /* variable fps and no guess at the real fps */
             if(   tb_unreliable(st->codec) && !(st->r_frame_rate.num && st->avg_frame_rate.num)
-               && duration_count[i]<20 && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
+               && st->info->duration_count<20 && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
                 break;
             if(st->parser && st->parser->parser->split && !st->codec->extradata)
                 break;
@@ -2238,9 +2323,7 @@ int av_find_stream_info(AVFormatContext *ic)
         /* NOTE: a new stream can be added there if no header in file
            (AVFMTCTX_NOHEADER) */
         ret = av_read_frame_internal(ic, &pkt1);
-        if(ret == AVERROR(EAGAIN))
-            continue;
-        if (ret < 0) {
+        if (ret < 0 && ret != AVERROR(EAGAIN)) {
             /* EOF or error */
             ret = -1; /* we could not have all the codec parameters before EOF */
             for(i=0;i<ic->nb_streams;i++) {
@@ -2256,27 +2339,25 @@ int av_find_stream_info(AVFormatContext *ic)
             break;
         }
 
+        if (ret == AVERROR(EAGAIN))
+            continue;
+
         pkt= add_to_pktbuf(&ic->packet_buffer, &pkt1, &ic->packet_buffer_end);
-        if(av_dup_packet(pkt) < 0) {
-            av_free(duration_error);
-            return AVERROR(ENOMEM);
-        }
+        if ((ret = av_dup_packet(pkt)) < 0)
+            goto find_stream_info_err;
 
         read_size += pkt->size;
 
         st = ic->streams[pkt->stream_index];
-        if(st->codec_info_nb_frames>1) {
-            if (st->time_base.den > 0 && av_rescale_q(codec_info_duration[st->index], st->time_base, AV_TIME_BASE_Q) >= ic->max_analyze_duration){
+        if (st->codec_info_nb_frames>1) {
+            if (st->time_base.den > 0 && av_rescale_q(st->info->codec_info_duration, st->time_base, AV_TIME_BASE_Q) >= ic->max_analyze_duration) {
                 av_log(ic, AV_LOG_WARNING, "max_analyze_duration reached\n");
                 break;
             }
-            codec_info_duration[st->index] += pkt->duration;
+            st->info->codec_info_duration += pkt->duration;
         }
-            st->codec_info_nb_frames++;
-
         {
-            int index= pkt->stream_index;
-            int64_t last= last_dts[index];
+            int64_t last = st->info->last_dts;
             int64_t duration= pkt->dts - last;
 
             if(pkt->dts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && duration>0){
@@ -2284,21 +2365,21 @@ int av_find_stream_info(AVFormatContext *ic)
 
 //                if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
 //                    av_log(NULL, AV_LOG_ERROR, "%f\n", dur);
-                if(duration_count[index] < 2)
-                    memset(duration_error[index], 0, sizeof(*duration_error));
-                for(i=1; i<MAX_STD_TIMEBASES; i++){
+                if (st->info->duration_count < 2)
+                    memset(st->info->duration_error, 0, sizeof(st->info->duration_error));
+                for (i=1; i<FF_ARRAY_ELEMS(st->info->duration_error); i++) {
                     int framerate= get_std_framerate(i);
                     int ticks= lrintf(dur*framerate/(1001*12));
                     double error= dur - ticks*1001*12/(double)framerate;
-                    duration_error[index][i] += error*error;
+                    st->info->duration_error[i] += error*error;
                 }
-                duration_count[index]++;
+                st->info->duration_count++;
                 // ignore the first 4 values, they might have some random jitter
-                if (duration_count[index] > 3)
-                    duration_gcd[index] = av_gcd(duration_gcd[index], duration);
+                if (st->info->duration_count > 3)
+                    st->info->duration_gcd = av_gcd(st->info->duration_gcd, duration);
             }
-            if(last == AV_NOPTS_VALUE || duration_count[index]<=1)
-                last_dts[pkt->stream_index]= pkt->dts;
+            if (last == AV_NOPTS_VALUE || st->info->duration_count <= 1)
+                st->info->last_dts = pkt->dts;
         }
         if(st->parser && st->parser->parser->split && !st->codec->extradata){
             int i= st->parser->parser->split(st->codec, pkt->data, pkt->size);
@@ -2314,9 +2395,10 @@ int av_find_stream_info(AVFormatContext *ic)
            decompress the frame. We try to avoid that in most cases as
            it takes longer and uses more memory. For MPEG-4, we need to
            decompress for QuickTime. */
-        if (!has_codec_parameters(st->codec))
+        if (!has_codec_parameters(st->codec) || !has_decode_delay_been_guessed(st))
             try_decode_frame(st, pkt);
 
+        st->codec_info_nb_frames++;
         count++;
     }
 
@@ -2328,10 +2410,10 @@ int av_find_stream_info(AVFormatContext *ic)
     }
     for(i=0;i<ic->nb_streams;i++) {
         st = ic->streams[i];
-        if(st->codec_info_nb_frames>2 && !st->avg_frame_rate.num && codec_info_duration[i])
+        if (st->codec_info_nb_frames>2 && !st->avg_frame_rate.num && st->info->codec_info_duration)
             av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
                      (st->codec_info_nb_frames-2)*(int64_t)st->time_base.den,
-                      codec_info_duration[i]    *(int64_t)st->time_base.num, 60000);
+                      st->info->codec_info_duration*(int64_t)st->time_base.num, 60000);
         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
             if(st->codec->codec_id == CODEC_ID_RAWVIDEO && !st->codec->codec_tag && !st->codec->bits_per_coded_sample)
                 st->codec->codec_tag= avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
@@ -2339,18 +2421,18 @@ int av_find_stream_info(AVFormatContext *ic)
             // the check for tb_unreliable() is not completely correct, since this is not about handling
             // a unreliable/inexact time base, but a time base that is finer than necessary, as e.g.
             // ipmovie.c produces.
-            if (tb_unreliable(st->codec) && duration_count[i] > 15 && duration_gcd[i] > 1 && !st->r_frame_rate.num)
-                av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, st->time_base.den, st->time_base.num * duration_gcd[i], INT_MAX);
-            if(duration_count[i] && !st->r_frame_rate.num
+            if (tb_unreliable(st->codec) && st->info->duration_count > 15 && st->info->duration_gcd > 1 && !st->r_frame_rate.num)
+                av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, st->time_base.den, st->time_base.num * st->info->duration_gcd, INT_MAX);
+            if (st->info->duration_count && !st->r_frame_rate.num
                && tb_unreliable(st->codec) /*&&
                //FIXME we should not special-case MPEG-2, but this needs testing with non-MPEG-2 ...
-               st->time_base.num*duration_sum[i]/duration_count[i]*101LL > st->time_base.den*/){
+               st->time_base.num*duration_sum[i]/st->info->duration_count*101LL > st->time_base.den*/){
                 int num = 0;
                 double best_error= 2*av_q2d(st->time_base);
-                best_error= best_error*best_error*duration_count[i]*1000*12*30;
+                best_error = best_error*best_error*st->info->duration_count*1000*12*30;
 
-                for(j=1; j<MAX_STD_TIMEBASES; j++){
-                    double error= duration_error[i][j] * get_std_framerate(j);
+                for (j=1; j<FF_ARRAY_ELEMS(st->info->duration_error); j++) {
+                    double error = st->info->duration_error[j] * get_std_framerate(j);
 //                    if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
 //                        av_log(NULL, AV_LOG_ERROR, "%f %f\n", get_std_framerate(j) / 12.0/1001, error);
                     if(error < best_error){
@@ -2376,6 +2458,19 @@ int av_find_stream_info(AVFormatContext *ic)
         }else if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
             if(!st->codec->bits_per_coded_sample)
                 st->codec->bits_per_coded_sample= av_get_bits_per_sample(st->codec->codec_id);
+            // set stream disposition based on audio service type
+            switch (st->codec->audio_service_type) {
+            case AV_AUDIO_SERVICE_TYPE_EFFECTS:
+                st->disposition = AV_DISPOSITION_CLEAN_EFFECTS;    break;
+            case AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED:
+                st->disposition = AV_DISPOSITION_VISUAL_IMPAIRED;  break;
+            case AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED:
+                st->disposition = AV_DISPOSITION_HEARING_IMPAIRED; break;
+            case AV_AUDIO_SERVICE_TYPE_COMMENTARY:
+                st->disposition = AV_DISPOSITION_COMMENT;          break;
+            case AV_AUDIO_SERVICE_TYPE_KARAOKE:
+                st->disposition = AV_DISPOSITION_KARAOKE;          break;
+            }
         }
     }
 
@@ -2408,8 +2503,72 @@ int av_find_stream_info(AVFormatContext *ic)
     }
 #endif
 
-    av_free(duration_error);
+ find_stream_info_err:
+    for (i=0; i < ic->nb_streams; i++)
+        av_freep(&ic->streams[i]->info);
+    return ret;
+}
 
+static AVProgram *find_program_from_stream(AVFormatContext *ic, int s)
+{
+    int i, j;
+
+    for (i = 0; i < ic->nb_programs; i++)
+        for (j = 0; j < ic->programs[i]->nb_stream_indexes; j++)
+            if (ic->programs[i]->stream_index[j] == s)
+                return ic->programs[i];
+    return NULL;
+}
+
+int av_find_best_stream(AVFormatContext *ic,
+                        enum AVMediaType type,
+                        int wanted_stream_nb,
+                        int related_stream,
+                        AVCodec **decoder_ret,
+                        int flags)
+{
+    int i, nb_streams = ic->nb_streams, stream_number = 0;
+    int ret = AVERROR_STREAM_NOT_FOUND, best_count = -1;
+    unsigned *program = NULL;
+    AVCodec *decoder = NULL, *best_decoder = NULL;
+
+    if (related_stream >= 0 && wanted_stream_nb < 0) {
+        AVProgram *p = find_program_from_stream(ic, related_stream);
+        if (p) {
+            program = p->stream_index;
+            nb_streams = p->nb_stream_indexes;
+        }
+    }
+    for (i = 0; i < nb_streams; i++) {
+        AVStream *st = ic->streams[program ? program[i] : i];
+        AVCodecContext *avctx = st->codec;
+        if (avctx->codec_type != type)
+            continue;
+        if (wanted_stream_nb >= 0 && stream_number++ != wanted_stream_nb)
+            continue;
+        if (st->disposition & (AV_DISPOSITION_HEARING_IMPAIRED|AV_DISPOSITION_VISUAL_IMPAIRED))
+            continue;
+        if (decoder_ret) {
+            decoder = avcodec_find_decoder(ic->streams[i]->codec->codec_id);
+            if (!decoder) {
+                if (ret < 0)
+                    ret = AVERROR_DECODER_NOT_FOUND;
+                continue;
+            }
+        }
+        if (best_count >= st->codec_info_nb_frames)
+            continue;
+        best_count = st->codec_info_nb_frames;
+        ret = program ? program[i] : i;
+        best_decoder = decoder;
+        if (program && i == nb_streams - 1 && ret < 0) {
+            program = NULL;
+            nb_streams = ic->nb_streams;
+            i = 0; /* no related stream found, try again with everything */
+        }
+    }
+    if (decoder_ret)
+        *decoder_ret = best_decoder;
     return ret;
 }
 
@@ -2420,7 +2579,7 @@ int av_read_play(AVFormatContext *s)
     if (s->iformat->read_play)
         return s->iformat->read_play(s);
     if (s->pb)
-        return av_url_read_fpause(s->pb, 0);
+        return avio_pause(s->pb, 0);
     return AVERROR(ENOSYS);
 }
 
@@ -2429,17 +2588,23 @@ int av_read_pause(AVFormatContext *s)
     if (s->iformat->read_pause)
         return s->iformat->read_pause(s);
     if (s->pb)
-        return av_url_read_fpause(s->pb, 1);
+        return avio_pause(s->pb, 1);
     return AVERROR(ENOSYS);
 }
 
 void av_close_input_stream(AVFormatContext *s)
 {
+    flush_packet_queue(s);
+    if (s->iformat->read_close)
+        s->iformat->read_close(s);
+    avformat_free_context(s);
+}
+
+void avformat_free_context(AVFormatContext *s)
+{
     int i;
     AVStream *st;
 
-    if (s->iformat->read_close)
-        s->iformat->read_close(s);
     for(i=0;i<s->nb_streams;i++) {
         /* free all data in a stream component */
         st = s->streams[i];
@@ -2450,15 +2615,17 @@ void av_close_input_stream(AVFormatContext *s)
         av_metadata_free(&st->metadata);
         av_free(st->index_entries);
         av_free(st->codec->extradata);
+        av_free(st->codec->subtitle_header);
         av_free(st->codec);
-#if LIBAVFORMAT_VERSION_INT < (53<<16)
+#if FF_API_OLD_METADATA
         av_free(st->filename);
 #endif
         av_free(st->priv_data);
+        av_free(st->info);
         av_free(st);
     }
     for(i=s->nb_programs-1; i>=0; i--) {
-#if LIBAVFORMAT_VERSION_INT < (53<<16)
+#if FF_API_OLD_METADATA
         av_freep(&s->programs[i]->provider_name);
         av_freep(&s->programs[i]->name);
 #endif
@@ -2467,10 +2634,9 @@ void av_close_input_stream(AVFormatContext *s)
         av_freep(&s->programs[i]);
     }
     av_freep(&s->programs);
-    flush_packet_queue(s);
     av_freep(&s->priv_data);
     while(s->nb_chapters--) {
-#if LIBAVFORMAT_VERSION_INT < (53<<16)
+#if FF_API_OLD_METADATA
         av_free(s->chapters[s->nb_chapters]->title);
 #endif
         av_metadata_free(&s->chapters[s->nb_chapters]->metadata);
@@ -2478,15 +2644,16 @@ void av_close_input_stream(AVFormatContext *s)
     }
     av_freep(&s->chapters);
     av_metadata_free(&s->metadata);
+    av_freep(&s->key);
     av_free(s);
 }
 
 void av_close_input_file(AVFormatContext *s)
 {
-    ByteIOContext *pb = s->iformat->flags & AVFMT_NOFILE ? NULL : s->pb;
+    AVIOContext *pb = s->iformat->flags & AVFMT_NOFILE ? NULL : s->pb;
     av_close_input_stream(s);
     if (pb)
-        url_fclose(pb);
+        avio_close(pb);
 }
 
 AVStream *av_new_stream(AVFormatContext *s, int id)
@@ -2494,12 +2661,29 @@ AVStream *av_new_stream(AVFormatContext *s, int id)
     AVStream *st;
     int i;
 
-    if (s->nb_streams >= MAX_STREAMS)
+#if FF_API_MAX_STREAMS
+    if (s->nb_streams >= MAX_STREAMS){
+        av_log(s, AV_LOG_ERROR, "Too many streams\n");
+        return NULL;
+    }
+#else
+    AVStream **streams;
+
+    if (s->nb_streams >= INT_MAX/sizeof(*streams))
         return NULL;
+    streams = av_realloc(s->streams, (s->nb_streams + 1) * sizeof(*streams));
+    if (!streams)
+        return NULL;
+    s->streams = streams;
+#endif
 
     st = av_mallocz(sizeof(AVStream));
     if (!st)
         return NULL;
+    if (!(st->info = av_mallocz(sizeof(*st->info)))) {
+        av_free(st);
+        return NULL;
+    }
 
     st->codec= avcodec_alloc_context();
     if (s->iformat) {
@@ -2571,7 +2755,7 @@ AVChapter *ff_new_chapter(AVFormatContext *s, int id, AVRational time_base, int6
             return NULL;
         dynarray_add(&s->chapters, &s->nb_chapters, chapter);
     }
-#if LIBAVFORMAT_VERSION_INT < (53<<16)
+#if FF_API_OLD_METADATA
     av_free(chapter->title);
 #endif
     av_metadata_set2(&chapter->metadata, "title", title, 0);
@@ -2594,6 +2778,10 @@ int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
         s->priv_data = av_mallocz(s->oformat->priv_data_size);
         if (!s->priv_data)
             return AVERROR(ENOMEM);
+        if (s->oformat->priv_class) {
+            *(const AVClass**)s->priv_data= s->oformat->priv_class;
+            av_opt_set_defaults(s->priv_data);
+        }
     } else
         s->priv_data = NULL;
 
@@ -2605,15 +2793,48 @@ int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
     return 0;
 }
 
+static int validate_codec_tag(AVFormatContext *s, AVStream *st)
+{
+    const AVCodecTag *avctag;
+    int n;
+    enum CodecID id = CODEC_ID_NONE;
+    unsigned int tag = 0;
+
+    /**
+     * Check that tag + id is in the table
+     * If neither is in the table -> OK
+     * If tag is in the table with another id -> FAIL
+     * If id is in the table with another tag -> FAIL unless strict < normal
+     */
+    for (n = 0; s->oformat->codec_tag[n]; n++) {
+        avctag = s->oformat->codec_tag[n];
+        while (avctag->id != CODEC_ID_NONE) {
+            if (ff_toupper4(avctag->tag) == ff_toupper4(st->codec->codec_tag)) {
+                id = avctag->id;
+                if (id == st->codec->codec_id)
+                    return 1;
+            }
+            if (avctag->id == st->codec->codec_id)
+                tag = avctag->tag;
+            avctag++;
+        }
+    }
+    if (id != CODEC_ID_NONE)
+        return 0;
+    if (tag && (st->codec->strict_std_compliance >= FF_COMPLIANCE_NORMAL))
+        return 0;
+    return 1;
+}
+
 int av_write_header(AVFormatContext *s)
 {
     int ret, i;
     AVStream *st;
 
     // some sanity checks
-    if (s->nb_streams == 0) {
+    if (s->nb_streams == 0 && !(s->oformat->flags & AVFMT_NOSTREAMS)) {
         av_log(s, AV_LOG_ERROR, "no streams\n");
-        return -1;
+        return AVERROR(EINVAL);
     }
 
     for(i=0;i<s->nb_streams;i++) {
@@ -2623,7 +2844,7 @@ int av_write_header(AVFormatContext *s)
         case AVMEDIA_TYPE_AUDIO:
             if(st->codec->sample_rate<=0){
                 av_log(s, AV_LOG_ERROR, "sample rate not set\n");
-                return -1;
+                return AVERROR(EINVAL);
             }
             if(!st->codec->block_align)
                 st->codec->block_align = st->codec->channels *
@@ -2632,26 +2853,33 @@ int av_write_header(AVFormatContext *s)
         case AVMEDIA_TYPE_VIDEO:
             if(st->codec->time_base.num<=0 || st->codec->time_base.den<=0){ //FIXME audio too?
                 av_log(s, AV_LOG_ERROR, "time base not set\n");
-                return -1;
+                return AVERROR(EINVAL);
             }
             if((st->codec->width<=0 || st->codec->height<=0) && !(s->oformat->flags & AVFMT_NODIMENSIONS)){
                 av_log(s, AV_LOG_ERROR, "dimensions not set\n");
-                return -1;
+                return AVERROR(EINVAL);
             }
             if(av_cmp_q(st->sample_aspect_ratio, st->codec->sample_aspect_ratio)){
                 av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between encoder and muxer layer\n");
-                return -1;
+                return AVERROR(EINVAL);
             }
             break;
         }
 
         if(s->oformat->codec_tag){
+            if(st->codec->codec_tag && st->codec->codec_id == CODEC_ID_RAWVIDEO && av_codec_get_tag(s->oformat->codec_tag, st->codec->codec_id) == 0 && !validate_codec_tag(s, st)){
+                //the current rawvideo encoding system ends up setting the wrong codec_tag for avi, we override it here
+                st->codec->codec_tag= 0;
+            }
             if(st->codec->codec_tag){
-                //FIXME
-                //check that tag + id is in the table
-                //if neither is in the table -> OK
-                //if tag is in the table with another id -> FAIL
-                //if id is in the table with another tag -> FAIL unless strict < ?
+                if (!validate_codec_tag(s, st)) {
+                    char tagbuf[32];
+                    av_get_codec_tag_string(tagbuf, sizeof(tagbuf), st->codec->codec_tag);
+                    av_log(s, AV_LOG_ERROR,
+                           "Tag %s/0x%08x incompatible with output codec id '%d'\n",
+                           tagbuf, st->codec->codec_tag, st->codec->codec_id);
+                    return AVERROR_INVALIDDATA;
+                }
             }else
                 st->codec->codec_tag= av_codec_get_tag(s->oformat->codec_tag, st->codec->codec_id);
         }
@@ -2667,22 +2895,13 @@ int av_write_header(AVFormatContext *s)
             return AVERROR(ENOMEM);
     }
 
-#if LIBAVFORMAT_VERSION_MAJOR < 53
+#if FF_API_OLD_METADATA
     ff_metadata_mux_compat(s);
 #endif
 
     /* set muxer identification string */
-    if (!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
-        AVMetadata *m;
-        AVMetadataTag *t;
-
-        if (!(m = av_mallocz(sizeof(AVMetadata))))
-            return AVERROR(ENOMEM);
-        av_metadata_set2(&m, "encoder", LIBAVFORMAT_IDENT, 0);
-        metadata_conv(&m, s->oformat->metadata_conv, NULL);
-        if ((t = av_metadata_get(m, "", NULL, AV_METADATA_IGNORE_SUFFIX)))
-            av_metadata_set2(&s->metadata, t->key, t->value, 0);
-        av_metadata_free(&m);
+    if (s->nb_streams && !(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
+        av_metadata_set2(&s->metadata, "encoder", LIBAVFORMAT_IDENT, 0);
     }
 
     if(s->oformat->write_header){
@@ -2720,7 +2939,8 @@ static int compute_pkt_fields2(AVFormatContext *s, AVStream *st, AVPacket *pkt){
     int delay = FFMAX(st->codec->has_b_frames, !!st->codec->max_b_frames);
     int num, den, frame_size, i;
 
-//    av_log(s, AV_LOG_DEBUG, "av_write_frame: pts:%"PRId64" dts:%"PRId64" cur_dts:%"PRId64" b:%d size:%d st:%d\n", pkt->pts, pkt->dts, st->cur_dts, delay, pkt->size, pkt->stream_index);
+    av_dlog(s, "av_write_frame: pts:%"PRId64" dts:%"PRId64" cur_dts:%"PRId64" b:%d size:%d st:%d\n",
+            pkt->pts, pkt->dts, st->cur_dts, delay, pkt->size, pkt->stream_index);
 
 /*    if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
         return -1;*/
@@ -2756,12 +2976,12 @@ static int compute_pkt_fields2(AVFormatContext *s, AVStream *st, AVPacket *pkt){
 
     if(st->cur_dts && st->cur_dts != AV_NOPTS_VALUE && st->cur_dts >= pkt->dts){
         av_log(s, AV_LOG_ERROR,
-               "st:%d error, non monotone timestamps %"PRId64" >= %"PRId64"\n",
+               "Application provided invalid, non monotonically increasing dts to muxer in stream %d: %"PRId64" >= %"PRId64"\n",
                st->index, st->cur_dts, pkt->dts);
         return -1;
     }
     if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts){
-        av_log(s, AV_LOG_ERROR, "st:%d error, pts < dts\n", st->index);
+        av_log(s, AV_LOG_ERROR, "pts < dts in stream %d\n", st->index);
         return -1;
     }
 
@@ -2798,8 +3018,6 @@ int av_write_frame(AVFormatContext *s, AVPacket *pkt)
         return ret;
 
     ret= s->oformat->write_packet(s, pkt);
-    if(!ret)
-        ret= url_ferror(s->pb);
     return ret;
 }
 
@@ -2839,13 +3057,16 @@ next_non_null:
     *next_point= this_pktl;
 }
 
-int ff_interleave_compare_dts(AVFormatContext *s, AVPacket *next, AVPacket *pkt)
+static int ff_interleave_compare_dts(AVFormatContext *s, AVPacket *next, AVPacket *pkt)
 {
     AVStream *st = s->streams[ pkt ->stream_index];
     AVStream *st2= s->streams[ next->stream_index];
     int64_t a= st2->time_base.num * (int64_t)st ->time_base.den;
     int64_t b= st ->time_base.num * (int64_t)st2->time_base.den;
-    return av_rescale_rnd(pkt->dts, b, a, AV_ROUND_DOWN) < next->dts;
+    int64_t dts1 = av_rescale_rnd(pkt->dts, b, a, AV_ROUND_DOWN);
+    if (dts1 == next->dts)
+        return pkt->stream_index < next->stream_index;
+    return dts1 < next->dts;
 }
 
 int av_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush){
@@ -2879,7 +3100,7 @@ int av_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out, AVPacket *pk
 }
 
 /**
- * Interleaves an AVPacket correctly so it can be muxed.
+ * Interleave an AVPacket correctly so it can be muxed.
  * @param out the interleaved packet will be output here
  * @param in the input packet
  * @param flush 1 if no further packets are available as input and all
@@ -2896,17 +3117,19 @@ static int av_interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in,
 
 int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt){
     AVStream *st= s->streams[ pkt->stream_index];
+    int ret;
 
     //FIXME/XXX/HACK drop zero sized packets
     if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO && pkt->size==0)
         return 0;
 
-//av_log(NULL, AV_LOG_DEBUG, "av_interleaved_write_frame %d %"PRId64" %"PRId64"\n", pkt->size, pkt->dts, pkt->pts);
-    if(compute_pkt_fields2(s, st, pkt) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
-        return -1;
+    av_dlog(s, "av_interleaved_write_frame size:%d dts:%"PRId64" pts:%"PRId64"\n",
+            pkt->size, pkt->dts, pkt->pts);
+    if((ret = compute_pkt_fields2(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
+        return ret;
 
     if(pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
-        return -1;
+        return AVERROR(EINVAL);
 
     for(;;){
         AVPacket opkt;
@@ -2921,8 +3144,6 @@ int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt){
 
         if(ret<0)
             return ret;
-        if(url_ferror(s->pb))
-            return url_ferror(s->pb);
     }
 }
 
@@ -2944,15 +3165,11 @@ int av_write_trailer(AVFormatContext *s)
 
         if(ret<0)
             goto fail;
-        if(url_ferror(s->pb))
-            goto fail;
     }
 
     if(s->oformat->write_trailer)
         ret = s->oformat->write_trailer(s);
 fail:
-    if(ret == 0)
-       ret=url_ferror(s->pb);
     for(i=0;i<s->nb_streams;i++) {
         av_freep(&s->streams[i]->priv_data);
         av_freep(&s->streams[i]->index_entries);
@@ -3048,15 +3265,45 @@ static void dump_stream_format(AVFormatContext *ic, int i, int index, int is_out
         if(st->codec->time_base.den && st->codec->time_base.num)
             print_fps(1/av_q2d(st->codec->time_base), "tbc");
     }
+    if (st->disposition & AV_DISPOSITION_DEFAULT)
+        av_log(NULL, AV_LOG_INFO, " (default)");
+    if (st->disposition & AV_DISPOSITION_DUB)
+        av_log(NULL, AV_LOG_INFO, " (dub)");
+    if (st->disposition & AV_DISPOSITION_ORIGINAL)
+        av_log(NULL, AV_LOG_INFO, " (original)");
+    if (st->disposition & AV_DISPOSITION_COMMENT)
+        av_log(NULL, AV_LOG_INFO, " (comment)");
+    if (st->disposition & AV_DISPOSITION_LYRICS)
+        av_log(NULL, AV_LOG_INFO, " (lyrics)");
+    if (st->disposition & AV_DISPOSITION_KARAOKE)
+        av_log(NULL, AV_LOG_INFO, " (karaoke)");
+    if (st->disposition & AV_DISPOSITION_FORCED)
+        av_log(NULL, AV_LOG_INFO, " (forced)");
+    if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
+        av_log(NULL, AV_LOG_INFO, " (hearing impaired)");
+    if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
+        av_log(NULL, AV_LOG_INFO, " (visual impaired)");
+    if (st->disposition & AV_DISPOSITION_CLEAN_EFFECTS)
+        av_log(NULL, AV_LOG_INFO, " (clean effects)");
     av_log(NULL, AV_LOG_INFO, "\n");
     dump_metadata(NULL, st->metadata, "    ");
 }
 
+#if FF_API_DUMP_FORMAT
 void dump_format(AVFormatContext *ic,
                  int index,
                  const char *url,
                  int is_output)
 {
+    av_dump_format(ic, index, url, is_output);
+}
+#endif
+
+void av_dump_format(AVFormatContext *ic,
+                    int index,
+                    const char *url,
+                    int is_output)
+{
     int i;
     uint8_t *printed = av_mallocz(ic->nb_streams);
     if (ic->nb_streams && !printed)
@@ -3087,7 +3334,7 @@ void dump_format(AVFormatContext *ic,
             int secs, us;
             av_log(NULL, AV_LOG_INFO, ", start: ");
             secs = ic->start_time / AV_TIME_BASE;
-            us = ic->start_time % AV_TIME_BASE;
+            us = abs(ic->start_time % AV_TIME_BASE);
             av_log(NULL, AV_LOG_INFO, "%d.%06d",
                    secs, (int)av_rescale(us, 1000000, AV_TIME_BASE));
         }
@@ -3131,16 +3378,18 @@ void dump_format(AVFormatContext *ic,
     av_free(printed);
 }
 
-#if LIBAVFORMAT_VERSION_MAJOR < 53
+#if FF_API_PARSE_FRAME_PARAM
+#include "libavutil/parseutils.h"
+
 int parse_image_size(int *width_ptr, int *height_ptr, const char *str)
 {
-    return av_parse_video_frame_size(width_ptr, height_ptr, str);
+    return av_parse_video_size(width_ptr, height_ptr, str);
 }
 
 int parse_frame_rate(int *frame_rate_num, int *frame_rate_den, const char *arg)
 {
     AVRational frame_rate;
-    int ret = av_parse_video_frame_rate(&frame_rate, arg);
+    int ret = av_parse_video_rate(&frame_rate, arg);
     *frame_rate_num= frame_rate.num;
     *frame_rate_den= frame_rate.den;
     return ret;
@@ -3159,163 +3408,25 @@ uint64_t ff_ntp_time(void)
   return (av_gettime() / 1000) * 1000 + NTP_OFFSET_US;
 }
 
-int64_t parse_date(const char *datestr, int duration)
-{
-    const char *p;
-    int64_t t;
-    struct tm dt;
-    int i;
-    static const char * const date_fmt[] = {
-        "%Y-%m-%d",
-        "%Y%m%d",
-    };
-    static const char * const time_fmt[] = {
-        "%H:%M:%S",
-        "%H%M%S",
-    };
-    const char *q;
-    int is_utc, len;
-    char lastch;
-    int negative = 0;
-
-#undef time
-    time_t now = time(0);
-
-    len = strlen(datestr);
-    if (len > 0)
-        lastch = datestr[len - 1];
-    else
-        lastch = '\0';
-    is_utc = (lastch == 'z' || lastch == 'Z');
-
-    memset(&dt, 0, sizeof(dt));
-
-    p = datestr;
-    q = NULL;
-    if (!duration) {
-        if (!strncasecmp(datestr, "now", len))
-            return (int64_t) now * 1000000;
-
-        /* parse the year-month-day part */
-        for (i = 0; i < FF_ARRAY_ELEMS(date_fmt); i++) {
-            q = small_strptime(p, date_fmt[i], &dt);
-            if (q) {
-                break;
-            }
-        }
-
-        /* if the year-month-day part is missing, then take the
-         * current year-month-day time */
-        if (!q) {
-            if (is_utc) {
-                dt = *gmtime(&now);
-            } else {
-                dt = *localtime(&now);
-            }
-            dt.tm_hour = dt.tm_min = dt.tm_sec = 0;
-        } else {
-            p = q;
-        }
+#if FF_API_PARSE_DATE
+#include "libavutil/parseutils.h"
 
-        if (*p == 'T' || *p == 't' || *p == ' ')
-            p++;
-
-        /* parse the hour-minute-second part */
-        for (i = 0; i < FF_ARRAY_ELEMS(time_fmt); i++) {
-            q = small_strptime(p, time_fmt[i], &dt);
-            if (q) {
-                break;
-            }
-        }
-    } else {
-        /* parse datestr as a duration */
-        if (p[0] == '-') {
-            negative = 1;
-            ++p;
-        }
-        /* parse datestr as HH:MM:SS */
-        q = small_strptime(p, time_fmt[0], &dt);
-        if (!q) {
-            /* parse datestr as S+ */
-            dt.tm_sec = strtol(p, (char **)&q, 10);
-            if (q == p)
-                /* the parsing didn't succeed */
-                return INT64_MIN;
-            dt.tm_min = 0;
-            dt.tm_hour = 0;
-        }
-    }
-
-    /* Now we have all the fields that we can get */
-    if (!q) {
-        return INT64_MIN;
-    }
-
-    if (duration) {
-        t = dt.tm_hour * 3600 + dt.tm_min * 60 + dt.tm_sec;
-    } else {
-        dt.tm_isdst = -1;       /* unknown */
-        if (is_utc) {
-            t = mktimegm(&dt);
-        } else {
-            t = mktime(&dt);
-        }
-    }
-
-    t *= 1000000;
-
-    /* parse the .m... part */
-    if (*q == '.') {
-        int val, n;
-        q++;
-        for (val = 0, n = 100000; n >= 1; n /= 10, q++) {
-            if (!isdigit(*q))
-                break;
-            val += n * (*q - '0');
-        }
-        t += val;
-    }
-    return negative ? -t : t;
+int64_t parse_date(const char *timestr, int duration)
+{
+    int64_t timeval;
+    av_parse_time(&timeval, timestr, duration);
+    return timeval;
 }
+#endif
+
+#if FF_API_FIND_INFO_TAG
+#include "libavutil/parseutils.h"
 
 int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
 {
-    const char *p;
-    char tag[128], *q;
-
-    p = info;
-    if (*p == '?')
-        p++;
-    for(;;) {
-        q = tag;
-        while (*p != '\0' && *p != '=' && *p != '&') {
-            if ((q - tag) < sizeof(tag) - 1)
-                *q++ = *p;
-            p++;
-        }
-        *q = '\0';
-        q = arg;
-        if (*p == '=') {
-            p++;
-            while (*p != '&' && *p != '\0') {
-                if ((q - arg) < arg_size - 1) {
-                    if (*p == '+')
-                        *q++ = ' ';
-                    else
-                        *q++ = *p;
-                }
-                p++;
-            }
-            *q = '\0';
-        }
-        if (!strcmp(tag, tag1))
-            return 1;
-        if (*p != '&')
-            break;
-        p++;
-    }
-    return 0;
+    return av_find_info_tag(arg, arg_size, tag1, info);
 }
+#endif
 
 int av_get_frame_filename(char *buf, int buf_size,
                           const char *path, int number)
@@ -3411,26 +3522,25 @@ void av_hex_dump_log(void *avcl, int level, uint8_t *buf, int size)
     hex_dump_internal(avcl, NULL, level, buf, size);
 }
 
- //FIXME needs to know the time_base
-static void pkt_dump_internal(void *avcl, FILE *f, int level, AVPacket *pkt, int dump_payload)
+static void pkt_dump_internal(void *avcl, FILE *f, int level, AVPacket *pkt, int dump_payload, AVRational time_base)
 {
 #undef fprintf
 #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
     PRINT("stream #%d:\n", pkt->stream_index);
     PRINT("  keyframe=%d\n", ((pkt->flags & AV_PKT_FLAG_KEY) != 0));
-    PRINT("  duration=%0.3f\n", (double)pkt->duration / AV_TIME_BASE);
+    PRINT("  duration=%0.3f\n", pkt->duration * av_q2d(time_base));
     /* DTS is _always_ valid after av_read_frame() */
     PRINT("  dts=");
     if (pkt->dts == AV_NOPTS_VALUE)
         PRINT("N/A");
     else
-        PRINT("%0.3f", (double)pkt->dts / AV_TIME_BASE);
+        PRINT("%0.3f", pkt->dts * av_q2d(time_base));
     /* PTS may not be known if B-frames are present. */
     PRINT("  pts=");
     if (pkt->pts == AV_NOPTS_VALUE)
         PRINT("N/A");
     else
-        PRINT("%0.3f", (double)pkt->pts / AV_TIME_BASE);
+        PRINT("%0.3f", pkt->pts * av_q2d(time_base));
     PRINT("\n");
     PRINT("  size=%d\n", pkt->size);
 #undef PRINT
@@ -3438,16 +3548,35 @@ static void pkt_dump_internal(void *avcl, FILE *f, int level, AVPacket *pkt, int
         av_hex_dump(f, pkt->data, pkt->size);
 }
 
+#if FF_API_PKT_DUMP
 void av_pkt_dump(FILE *f, AVPacket *pkt, int dump_payload)
 {
-    pkt_dump_internal(NULL, f, 0, pkt, dump_payload);
+    AVRational tb = { 1, AV_TIME_BASE };
+    pkt_dump_internal(NULL, f, 0, pkt, dump_payload, tb);
+}
+#endif
+
+void av_pkt_dump2(FILE *f, AVPacket *pkt, int dump_payload, AVStream *st)
+{
+    pkt_dump_internal(NULL, f, 0, pkt, dump_payload, st->time_base);
 }
 
+#if FF_API_PKT_DUMP
 void av_pkt_dump_log(void *avcl, int level, AVPacket *pkt, int dump_payload)
 {
-    pkt_dump_internal(avcl, NULL, level, pkt, dump_payload);
+    AVRational tb = { 1, AV_TIME_BASE };
+    pkt_dump_internal(avcl, NULL, level, pkt, dump_payload, tb);
+}
+#endif
+
+void av_pkt_dump_log2(void *avcl, int level, AVPacket *pkt, int dump_payload,
+                      AVStream *st)
+{
+    pkt_dump_internal(avcl, NULL, level, pkt, dump_payload, st->time_base);
 }
 
+#if FF_API_URL_SPLIT
+attribute_deprecated
 void ff_url_split(char *proto, int proto_size,
                   char *authorization, int authorization_size,
                   char *hostname, int hostname_size,
@@ -3455,6 +3584,22 @@ void ff_url_split(char *proto, int proto_size,
                   char *path, int path_size,
                   const char *url)
 {
+    av_url_split(proto, proto_size,
+                 authorization, authorization_size,
+                 hostname, hostname_size,
+                 port_ptr,
+                 path, path_size,
+                 url);
+}
+#endif
+
+void av_url_split(char *proto, int proto_size,
+                  char *authorization, int authorization_size,
+                  char *hostname, int hostname_size,
+                  int *port_ptr,
+                  char *path, int path_size,
+                  const char *url)
+{
     const char *p, *ls, *at, *col, *brk;
 
     if (port_ptr)               *port_ptr = -1;
@@ -3530,19 +3675,50 @@ char *ff_data_to_hex(char *buff, const uint8_t *src, int s, int lowercase)
     return buff;
 }
 
+int ff_hex_to_data(uint8_t *data, const char *p)
+{
+    int c, len, v;
+
+    len = 0;
+    v = 1;
+    for (;;) {
+        p += strspn(p, SPACE_CHARS);
+        if (*p == '\0')
+            break;
+        c = toupper((unsigned char) *p++);
+        if (c >= '0' && c <= '9')
+            c = c - '0';
+        else if (c >= 'A' && c <= 'F')
+            c = c - 'A' + 10;
+        else
+            break;
+        v = (v << 4) | c;
+        if (v & 0x100) {
+            if (data)
+                data[len] = v;
+            len++;
+            v = 1;
+        }
+    }
+    return len;
+}
+
 void av_set_pts_info(AVStream *s, int pts_wrap_bits,
                      unsigned int pts_num, unsigned int pts_den)
 {
-    s->pts_wrap_bits = pts_wrap_bits;
-
-    if(av_reduce(&s->time_base.num, &s->time_base.den, pts_num, pts_den, INT_MAX)){
-        if(s->time_base.num != pts_num)
-            av_log(NULL, AV_LOG_DEBUG, "st:%d removing common factor %d from timebase\n", s->index, pts_num/s->time_base.num);
+    AVRational new_tb;
+    if(av_reduce(&new_tb.num, &new_tb.den, pts_num, pts_den, INT_MAX)){
+        if(new_tb.num != pts_num)
+            av_log(NULL, AV_LOG_DEBUG, "st:%d removing common factor %d from timebase\n", s->index, pts_num/new_tb.num);
     }else
         av_log(NULL, AV_LOG_WARNING, "st:%d has too large timebase, reducing\n", s->index);
 
-    if(!s->time_base.num || !s->time_base.den)
-        s->time_base.num= s->time_base.den= 0;
+    if(new_tb.num <= 0 || new_tb.den <= 0) {
+        av_log(NULL, AV_LOG_ERROR, "Ignoring attempt to set invalid timebase for st:%d\n", s->index);
+        return;
+    }
+    s->time_base = new_tb;
+    s->pts_wrap_bits = pts_wrap_bits;
 }
 
 int ff_url_join(char *str, int size, const char *proto,
@@ -3556,7 +3732,7 @@ int ff_url_join(char *str, int size, const char *proto,
     str[0] = '\0';
     if (proto)
         av_strlcatf(str, size, "%s://", proto);
-    if (authorization)
+    if (authorization && authorization[0])
         av_strlcatf(str, size, "%s@", authorization);
 #if CONFIG_NETWORK && defined(AF_INET6)
     /* Determine if hostname is a numerical IPv6 address,
@@ -3589,3 +3765,136 @@ int ff_url_join(char *str, int size, const char *proto,
     }
     return strlen(str);
 }
+
+int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
+                     AVFormatContext *src)
+{
+    AVPacket local_pkt;
+
+    local_pkt = *pkt;
+    local_pkt.stream_index = dst_stream;
+    if (pkt->pts != AV_NOPTS_VALUE)
+        local_pkt.pts = av_rescale_q(pkt->pts,
+                                     src->streams[pkt->stream_index]->time_base,
+                                     dst->streams[dst_stream]->time_base);
+    if (pkt->dts != AV_NOPTS_VALUE)
+        local_pkt.dts = av_rescale_q(pkt->dts,
+                                     src->streams[pkt->stream_index]->time_base,
+                                     dst->streams[dst_stream]->time_base);
+    return av_write_frame(dst, &local_pkt);
+}
+
+void ff_parse_key_value(const char *str, ff_parse_key_val_cb callback_get_buf,
+                        void *context)
+{
+    const char *ptr = str;
+
+    /* Parse key=value pairs. */
+    for (;;) {
+        const char *key;
+        char *dest = NULL, *dest_end;
+        int key_len, dest_len = 0;
+
+        /* Skip whitespace and potential commas. */
+        while (*ptr && (isspace(*ptr) || *ptr == ','))
+            ptr++;
+        if (!*ptr)
+            break;
+
+        key = ptr;
+
+        if (!(ptr = strchr(key, '=')))
+            break;
+        ptr++;
+        key_len = ptr - key;
+
+        callback_get_buf(context, key, key_len, &dest, &dest_len);
+        dest_end = dest + dest_len - 1;
+
+        if (*ptr == '\"') {
+            ptr++;
+            while (*ptr && *ptr != '\"') {
+                if (*ptr == '\\') {
+                    if (!ptr[1])
+                        break;
+                    if (dest && dest < dest_end)
+                        *dest++ = ptr[1];
+                    ptr += 2;
+                } else {
+                    if (dest && dest < dest_end)
+                        *dest++ = *ptr;
+                    ptr++;
+                }
+            }
+            if (*ptr == '\"')
+                ptr++;
+        } else {
+            for (; *ptr && !(isspace(*ptr) || *ptr == ','); ptr++)
+                if (dest && dest < dest_end)
+                    *dest++ = *ptr;
+        }
+        if (dest)
+            *dest = 0;
+    }
+}
+
+int ff_find_stream_index(AVFormatContext *s, int id)
+{
+    int i;
+    for (i = 0; i < s->nb_streams; i++) {
+        if (s->streams[i]->id == id)
+            return i;
+    }
+    return -1;
+}
+
+void ff_make_absolute_url(char *buf, int size, const char *base,
+                          const char *rel)
+{
+    char *sep;
+    /* Absolute path, relative to the current server */
+    if (base && strstr(base, "://") && rel[0] == '/') {
+        if (base != buf)
+            av_strlcpy(buf, base, size);
+        sep = strstr(buf, "://");
+        if (sep) {
+            sep += 3;
+            sep = strchr(sep, '/');
+            if (sep)
+                *sep = '\0';
+        }
+        av_strlcat(buf, rel, size);
+        return;
+    }
+    /* If rel actually is an absolute url, just copy it */
+    if (!base || strstr(rel, "://") || rel[0] == '/') {
+        av_strlcpy(buf, rel, size);
+        return;
+    }
+    if (base != buf)
+        av_strlcpy(buf, base, size);
+    /* Remove the file name from the base url */
+    sep = strrchr(buf, '/');
+    if (sep)
+        sep[1] = '\0';
+    else
+        buf[0] = '\0';
+    while (av_strstart(rel, "../", NULL) && sep) {
+        /* Remove the path delimiter at the end */
+        sep[0] = '\0';
+        sep = strrchr(buf, '/');
+        /* If the next directory name to pop off is "..", break here */
+        if (!strcmp(sep ? &sep[1] : buf, "..")) {
+            /* Readd the slash we just removed */
+            av_strlcat(buf, "/", size);
+            break;
+        }
+        /* Cut off the directory name */
+        if (sep)
+            sep[1] = '\0';
+        else
+            buf[0] = '\0';
+        rel += 3;
+    }
+    av_strlcat(buf, rel, size);
+}
diff --git a/libavformat/vc1test.c b/libavformat/vc1test.c
index 7a006f2..07f3247 100644
--- a/libavformat/vc1test.c
+++ b/libavformat/vc1test.c
@@ -2,20 +2,20 @@
  * VC1 Test Bitstreams Format Demuxer
  * Copyright (c) 2006, 2008 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -44,13 +44,13 @@ static int vc1t_probe(AVProbeData *p)
 static int vc1t_read_header(AVFormatContext *s,
                            AVFormatParameters *ap)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVStream *st;
     int frames;
     uint32_t fps;
 
-    frames = get_le24(pb);
-    if(get_byte(pb) != 0xC5 || get_le32(pb) != 4)
+    frames = avio_rl24(pb);
+    if(avio_r8(pb) != 0xC5 || avio_rl32(pb) != 4)
         return -1;
 
     /* init video codec */
@@ -63,13 +63,13 @@ static int vc1t_read_header(AVFormatContext *s,
 
     st->codec->extradata = av_malloc(VC1_EXTRADATA_SIZE);
     st->codec->extradata_size = VC1_EXTRADATA_SIZE;
-    get_buffer(pb, st->codec->extradata, VC1_EXTRADATA_SIZE);
-    st->codec->height = get_le32(pb);
-    st->codec->width = get_le32(pb);
-    if(get_le32(pb) != 0xC)
+    avio_read(pb, st->codec->extradata, VC1_EXTRADATA_SIZE);
+    st->codec->height = avio_rl32(pb);
+    st->codec->width = avio_rl32(pb);
+    if(avio_rl32(pb) != 0xC)
         return -1;
-    url_fskip(pb, 8);
-    fps = get_le32(pb);
+    avio_skip(pb, 8);
+    fps = avio_rl32(pb);
     if(fps == 0xFFFFFFFF)
         av_set_pts_info(st, 32, 1, 1000);
     else{
@@ -87,18 +87,18 @@ static int vc1t_read_header(AVFormatContext *s,
 static int vc1t_read_packet(AVFormatContext *s,
                            AVPacket *pkt)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int frame_size;
     int keyframe = 0;
     uint32_t pts;
 
-    if(url_feof(pb))
+    if(pb->eof_reached)
         return AVERROR(EIO);
 
-    frame_size = get_le24(pb);
-    if(get_byte(pb) & 0x80)
+    frame_size = avio_rl24(pb);
+    if(avio_r8(pb) & 0x80)
         keyframe = 1;
-    pts = get_le32(pb);
+    pts = avio_rl32(pb);
     if(av_get_packet(pb, pkt, frame_size) < 0)
         return AVERROR(EIO);
     if(s->streams[0]->time_base.den == 1000)
@@ -109,7 +109,7 @@ static int vc1t_read_packet(AVFormatContext *s,
     return pkt->size;
 }
 
-AVInputFormat vc1t_demuxer = {
+AVInputFormat ff_vc1t_demuxer = {
     "vc1test",
     NULL_IF_CONFIG_SMALL("VC-1 test bitstream format"),
     0,
diff --git a/libavformat/vc1testenc.c b/libavformat/vc1testenc.c
index b4b1e02..2b0728d 100644
--- a/libavformat/vc1testenc.c
+++ b/libavformat/vc1testenc.c
@@ -2,20 +2,20 @@
  * VC-1 test bitstreams format muxer.
  * Copyright (c) 2008 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #include "avformat.h"
@@ -27,26 +27,27 @@ typedef struct RCVContext {
 static int vc1test_write_header(AVFormatContext *s)
 {
     AVCodecContext *avc = s->streams[0]->codec;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
 
     if (avc->codec_id != CODEC_ID_WMV3) {
         av_log(s, AV_LOG_ERROR, "Only WMV3 is accepted!\n");
         return -1;
     }
-    put_le24(pb, 0); //frames count will be here
-    put_byte(pb, 0xC5);
-    put_le32(pb, 4);
-    put_buffer(pb, avc->extradata, 4);
-    put_le32(pb, avc->height);
-    put_le32(pb, avc->width);
-    put_le32(pb, 0xC);
-    put_le24(pb, 0); // hrd_buffer
-    put_byte(pb, 0x80); // level|cbr|res1
-    put_le32(pb, 0); // hrd_rate
+    avio_wl24(pb, 0); //frames count will be here
+    avio_w8(pb, 0xC5);
+    avio_wl32(pb, 4);
+    avio_write(pb, avc->extradata, 4);
+    avio_wl32(pb, avc->height);
+    avio_wl32(pb, avc->width);
+    avio_wl32(pb, 0xC);
+    avio_wl24(pb, 0); // hrd_buffer
+    avio_w8(pb, 0x80); // level|cbr|res1
+    avio_wl32(pb, 0); // hrd_rate
     if (s->streams[0]->r_frame_rate.den && s->streams[0]->r_frame_rate.num == 1)
-        put_le32(pb, s->streams[0]->r_frame_rate.den);
+        avio_wl32(pb, s->streams[0]->r_frame_rate.den);
     else
-        put_le32(pb, 0xFFFFFFFF); //variable framerate
+        avio_wl32(pb, 0xFFFFFFFF); //variable framerate
+    av_set_pts_info(s->streams[0], 32, 1, 1000);
 
     return 0;
 }
@@ -54,14 +55,14 @@ static int vc1test_write_header(AVFormatContext *s)
 static int vc1test_write_packet(AVFormatContext *s, AVPacket *pkt)
 {
     RCVContext *ctx = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
 
     if (!pkt->size)
         return 0;
-    put_le32(pb, pkt->size | ((pkt->flags & AV_PKT_FLAG_KEY) ? 0x80000000 : 0));
-    put_le32(pb, pkt->pts);
-    put_buffer(pb, pkt->data, pkt->size);
-    put_flush_packet(pb);
+    avio_wl32(pb, pkt->size | ((pkt->flags & AV_PKT_FLAG_KEY) ? 0x80000000 : 0));
+    avio_wl32(pb, pkt->pts);
+    avio_write(pb, pkt->data, pkt->size);
+    avio_flush(pb);
     ctx->frames++;
 
     return 0;
@@ -70,17 +71,17 @@ static int vc1test_write_packet(AVFormatContext *s, AVPacket *pkt)
 static int vc1test_write_trailer(AVFormatContext *s)
 {
     RCVContext *ctx = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
 
-    if (!url_is_streamed(s->pb)) {
-        url_fseek(pb, 0, SEEK_SET);
-        put_le24(pb, ctx->frames);
-        put_flush_packet(pb);
+    if (s->pb->seekable) {
+        avio_seek(pb, 0, SEEK_SET);
+        avio_wl24(pb, ctx->frames);
+        avio_flush(pb);
     }
     return 0;
 }
 
-AVOutputFormat vc1t_muxer = {
+AVOutputFormat ff_vc1t_muxer = {
     "rcv",
     NULL_IF_CONFIG_SMALL("VC-1 test bitstream"),
     "",
diff --git a/libavformat/version.h b/libavformat/version.h
new file mode 100644
index 0000000..b21938a
--- /dev/null
+++ b/libavformat/version.h
@@ -0,0 +1,117 @@
+/*
+ * Version macros.
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVFORMAT_VERSION_H
+#define AVFORMAT_VERSION_H
+
+#include "libavutil/avutil.h"
+
+#define LIBAVFORMAT_VERSION_MAJOR 53
+#define LIBAVFORMAT_VERSION_MINOR  0
+#define LIBAVFORMAT_VERSION_MICRO  0
+
+#define LIBAVFORMAT_VERSION_INT AV_VERSION_INT(LIBAVFORMAT_VERSION_MAJOR, \
+                                               LIBAVFORMAT_VERSION_MINOR, \
+                                               LIBAVFORMAT_VERSION_MICRO)
+#define LIBAVFORMAT_VERSION     AV_VERSION(LIBAVFORMAT_VERSION_MAJOR,   \
+                                           LIBAVFORMAT_VERSION_MINOR,   \
+                                           LIBAVFORMAT_VERSION_MICRO)
+#define LIBAVFORMAT_BUILD       LIBAVFORMAT_VERSION_INT
+
+#define LIBAVFORMAT_IDENT       "Lavf" AV_STRINGIFY(LIBAVFORMAT_VERSION)
+
+/**
+ * Those FF_API_* defines are not part of public API.
+ * They may change, break or disappear at any time.
+ */
+#ifndef FF_API_MAX_STREAMS
+#define FF_API_MAX_STREAMS             (LIBAVFORMAT_VERSION_MAJOR < 53)
+#endif
+#ifndef FF_API_OLD_METADATA
+#define FF_API_OLD_METADATA            (LIBAVFORMAT_VERSION_MAJOR < 53)
+#endif
+#ifndef FF_API_OLD_METADATA2
+#define FF_API_OLD_METADATA2           (LIBAVFORMAT_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_URL_CLASS
+#define FF_API_URL_CLASS               (LIBAVFORMAT_VERSION_MAJOR >= 53)
+#endif
+#ifndef FF_API_URL_RESETBUF
+#define FF_API_URL_RESETBUF            (LIBAVFORMAT_VERSION_MAJOR < 53)
+#endif
+#ifndef FF_API_REGISTER_PROTOCOL
+#define FF_API_REGISTER_PROTOCOL       (LIBAVFORMAT_VERSION_MAJOR < 53)
+#endif
+#ifndef FF_API_GUESS_FORMAT
+#define FF_API_GUESS_FORMAT            (LIBAVFORMAT_VERSION_MAJOR < 53)
+#endif
+#ifndef FF_API_UDP_GET_FILE
+#define FF_API_UDP_GET_FILE            (LIBAVFORMAT_VERSION_MAJOR < 53)
+#endif
+#ifndef FF_API_URL_SPLIT
+#define FF_API_URL_SPLIT               (LIBAVFORMAT_VERSION_MAJOR < 53)
+#endif
+#ifndef FF_API_ALLOC_FORMAT_CONTEXT
+#define FF_API_ALLOC_FORMAT_CONTEXT    (LIBAVFORMAT_VERSION_MAJOR < 53)
+#endif
+#ifndef FF_API_PARSE_FRAME_PARAM
+#define FF_API_PARSE_FRAME_PARAM       (LIBAVFORMAT_VERSION_MAJOR < 53)
+#endif
+#ifndef FF_API_READ_SEEK
+#define FF_API_READ_SEEK               (LIBAVFORMAT_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_LAVF_UNUSED
+#define FF_API_LAVF_UNUSED             (LIBAVFORMAT_VERSION_MAJOR < 53)
+#endif
+#ifndef FF_API_PARAMETERS_CODEC_ID
+#define FF_API_PARAMETERS_CODEC_ID     (LIBAVFORMAT_VERSION_MAJOR < 53)
+#endif
+#ifndef FF_API_FIRST_FORMAT
+#define FF_API_FIRST_FORMAT            (LIBAVFORMAT_VERSION_MAJOR < 53)
+#endif
+#ifndef FF_API_SYMVER
+#define FF_API_SYMVER                  (LIBAVFORMAT_VERSION_MAJOR < 53)
+#endif
+#ifndef FF_API_OLD_AVIO
+#define FF_API_OLD_AVIO                (LIBAVFORMAT_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_INDEX_BUILT
+#define FF_API_INDEX_BUILT             (LIBAVFORMAT_VERSION_MAJOR < 53)
+#endif
+#ifndef FF_API_DUMP_FORMAT
+#define FF_API_DUMP_FORMAT             (LIBAVFORMAT_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_PARSE_DATE
+#define FF_API_PARSE_DATE              (LIBAVFORMAT_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_FIND_INFO_TAG
+#define FF_API_FIND_INFO_TAG           (LIBAVFORMAT_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_PKT_DUMP
+#define FF_API_PKT_DUMP                (LIBAVFORMAT_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_GUESS_IMG2_CODEC
+#define FF_API_GUESS_IMG2_CODEC        (LIBAVFORMAT_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_SDP_CREATE
+#define FF_API_SDP_CREATE              (LIBAVFORMAT_VERSION_MAJOR < 54)
+#endif
+
+#endif //AVFORMAT_VERSION_H
diff --git a/libavformat/voc.c b/libavformat/voc.c
index eed8db8..314623e 100644
--- a/libavformat/voc.c
+++ b/libavformat/voc.c
@@ -2,24 +2,25 @@
  * Creative Voice File common data.
  * Copyright (c) 2006  Aurelien Jacobs <aurel at gnuage.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "voc.h"
+#include "internal.h"
 
 const unsigned char ff_voc_magic[21] = "Creative Voice File\x1A";
 
diff --git a/libavformat/voc.h b/libavformat/voc.h
index 3f995ad..abd8fdb 100644
--- a/libavformat/voc.h
+++ b/libavformat/voc.h
@@ -2,20 +2,20 @@
  * Creative Voice File demuxer.
  * Copyright (c) 2006  Aurelien Jacobs <aurel at gnuage.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavformat/vocdec.c b/libavformat/vocdec.c
index 13d48f7..eaa2f25 100644
--- a/libavformat/vocdec.c
+++ b/libavformat/vocdec.c
@@ -2,25 +2,26 @@
  * Creative Voice File demuxer.
  * Copyright (c) 2006  Aurelien Jacobs <aurel at gnuage.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "libavutil/intreadwrite.h"
 #include "voc.h"
+#include "internal.h"
 
 
 static int voc_probe(AVProbeData *p)
@@ -40,17 +41,17 @@ static int voc_probe(AVProbeData *p)
 static int voc_read_header(AVFormatContext *s, AVFormatParameters *ap)
 {
     VocDecContext *voc = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int header_size;
     AVStream *st;
 
-    url_fskip(pb, 20);
-    header_size = get_le16(pb) - 22;
+    avio_skip(pb, 20);
+    header_size = avio_rl16(pb) - 22;
     if (header_size != 4) {
         av_log(s, AV_LOG_ERROR, "unknown header size: %d\n", header_size);
         return AVERROR(ENOSYS);
     }
-    url_fskip(pb, header_size);
+    avio_skip(pb, header_size);
     st = av_new_stream(s, 0);
     if (!st)
         return AVERROR(ENOMEM);
@@ -65,31 +66,31 @@ voc_get_packet(AVFormatContext *s, AVPacket *pkt, AVStream *st, int max_size)
 {
     VocDecContext *voc = s->priv_data;
     AVCodecContext *dec = st->codec;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     VocType type;
-    int size;
+    int size, tmp_codec=-1;
     int sample_rate = 0;
     int channels = 1;
 
     while (!voc->remaining_size) {
-        type = get_byte(pb);
+        type = avio_r8(pb);
         if (type == VOC_TYPE_EOF)
             return AVERROR(EIO);
-        voc->remaining_size = get_le24(pb);
+        voc->remaining_size = avio_rl24(pb);
         if (!voc->remaining_size) {
-            if (url_is_streamed(s->pb))
+            if (!s->pb->seekable)
                 return AVERROR(EIO);
-            voc->remaining_size = url_fsize(pb) - url_ftell(pb);
+            voc->remaining_size = avio_size(pb) - avio_tell(pb);
         }
         max_size -= 4;
 
         switch (type) {
         case VOC_TYPE_VOICE_DATA:
-            dec->sample_rate = 1000000 / (256 - get_byte(pb));
+            dec->sample_rate = 1000000 / (256 - avio_r8(pb));
             if (sample_rate)
                 dec->sample_rate = sample_rate;
             dec->channels = channels;
-            dec->codec_id = ff_codec_get_id(ff_voc_codec_tags, get_byte(pb));
+            tmp_codec = avio_r8(pb);
             dec->bits_per_coded_sample = av_get_bits_per_sample(dec->codec_id);
             voc->remaining_size -= 2;
             max_size -= 2;
@@ -100,32 +101,47 @@ voc_get_packet(AVFormatContext *s, AVPacket *pkt, AVStream *st, int max_size)
             break;
 
         case VOC_TYPE_EXTENDED:
-            sample_rate = get_le16(pb);
-            get_byte(pb);
-            channels = get_byte(pb) + 1;
+            sample_rate = avio_rl16(pb);
+            avio_r8(pb);
+            channels = avio_r8(pb) + 1;
             sample_rate = 256000000 / (channels * (65536 - sample_rate));
             voc->remaining_size = 0;
             max_size -= 4;
             break;
 
         case VOC_TYPE_NEW_VOICE_DATA:
-            dec->sample_rate = get_le32(pb);
-            dec->bits_per_coded_sample = get_byte(pb);
-            dec->channels = get_byte(pb);
-            dec->codec_id = ff_codec_get_id(ff_voc_codec_tags, get_le16(pb));
-            url_fskip(pb, 4);
+            dec->sample_rate = avio_rl32(pb);
+            dec->bits_per_coded_sample = avio_r8(pb);
+            dec->channels = avio_r8(pb);
+            tmp_codec = avio_rl16(pb);
+            avio_skip(pb, 4);
             voc->remaining_size -= 12;
             max_size -= 12;
             break;
 
         default:
-            url_fskip(pb, voc->remaining_size);
+            avio_skip(pb, voc->remaining_size);
             max_size -= voc->remaining_size;
             voc->remaining_size = 0;
             break;
         }
     }
 
+    if (tmp_codec >= 0) {
+        tmp_codec = ff_codec_get_id(ff_voc_codec_tags, tmp_codec);
+        if (dec->codec_id == CODEC_ID_NONE)
+            dec->codec_id = tmp_codec;
+        else if (dec->codec_id != tmp_codec)
+            av_log(s, AV_LOG_WARNING, "Ignoring mid-stream change in audio codec\n");
+        if (dec->codec_id == CODEC_ID_NONE) {
+            if (s->audio_codec_id == CODEC_ID_NONE) {
+                av_log(s, AV_LOG_ERROR, "unknown codec tag\n");
+                return AVERROR(EINVAL);
+            }
+            av_log(s, AV_LOG_WARNING, "unknown codec tag\n");
+        }
+    }
+
     dec->bit_rate = dec->sample_rate * dec->bits_per_coded_sample;
 
     if (max_size <= 0)
@@ -140,7 +156,7 @@ static int voc_read_packet(AVFormatContext *s, AVPacket *pkt)
     return voc_get_packet(s, pkt, s->streams[0], 0);
 }
 
-AVInputFormat voc_demuxer = {
+AVInputFormat ff_voc_demuxer = {
     "voc",
     NULL_IF_CONFIG_SMALL("Creative Voice file format"),
     sizeof(VocDecContext),
diff --git a/libavformat/vocenc.c b/libavformat/vocenc.c
index f127c7e..bbb69c8 100644
--- a/libavformat/vocenc.c
+++ b/libavformat/vocenc.c
@@ -2,24 +2,25 @@
  * Creative Voice File muxer.
  * Copyright (c) 2006  Aurelien Jacobs <aurel at gnuage.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "voc.h"
+#include "internal.h"
 
 
 typedef struct voc_enc_context {
@@ -28,7 +29,7 @@ typedef struct voc_enc_context {
 
 static int voc_write_header(AVFormatContext *s)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     const int header_size = 26;
     const int version = 0x0114;
 
@@ -36,10 +37,10 @@ static int voc_write_header(AVFormatContext *s)
         || s->streams[0]->codec->codec_type != AVMEDIA_TYPE_AUDIO)
         return AVERROR_PATCHWELCOME;
 
-    put_buffer(pb, ff_voc_magic, sizeof(ff_voc_magic) - 1);
-    put_le16(pb, header_size);
-    put_le16(pb, version);
-    put_le16(pb, ~version + 0x1234);
+    avio_write(pb, ff_voc_magic, sizeof(ff_voc_magic) - 1);
+    avio_wl16(pb, header_size);
+    avio_wl16(pb, version);
+    avio_wl16(pb, ~version + 0x1234);
 
     return 0;
 }
@@ -48,47 +49,47 @@ static int voc_write_packet(AVFormatContext *s, AVPacket *pkt)
 {
     VocEncContext *voc = s->priv_data;
     AVCodecContext *enc = s->streams[0]->codec;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
 
     if (!voc->param_written) {
         if (enc->codec_tag > 0xFF) {
-            put_byte(pb, VOC_TYPE_NEW_VOICE_DATA);
-            put_le24(pb, pkt->size + 12);
-            put_le32(pb, enc->sample_rate);
-            put_byte(pb, enc->bits_per_coded_sample);
-            put_byte(pb, enc->channels);
-            put_le16(pb, enc->codec_tag);
-            put_le32(pb, 0);
+            avio_w8(pb, VOC_TYPE_NEW_VOICE_DATA);
+            avio_wl24(pb, pkt->size + 12);
+            avio_wl32(pb, enc->sample_rate);
+            avio_w8(pb, enc->bits_per_coded_sample);
+            avio_w8(pb, enc->channels);
+            avio_wl16(pb, enc->codec_tag);
+            avio_wl32(pb, 0);
         } else {
             if (s->streams[0]->codec->channels > 1) {
-                put_byte(pb, VOC_TYPE_EXTENDED);
-                put_le24(pb, 4);
-                put_le16(pb, 65536-256000000/(enc->sample_rate*enc->channels));
-                put_byte(pb, enc->codec_tag);
-                put_byte(pb, enc->channels - 1);
+                avio_w8(pb, VOC_TYPE_EXTENDED);
+                avio_wl24(pb, 4);
+                avio_wl16(pb, 65536-256000000/(enc->sample_rate*enc->channels));
+                avio_w8(pb, enc->codec_tag);
+                avio_w8(pb, enc->channels - 1);
             }
-            put_byte(pb, VOC_TYPE_VOICE_DATA);
-            put_le24(pb, pkt->size + 2);
-            put_byte(pb, 256 - 1000000 / enc->sample_rate);
-            put_byte(pb, enc->codec_tag);
+            avio_w8(pb, VOC_TYPE_VOICE_DATA);
+            avio_wl24(pb, pkt->size + 2);
+            avio_w8(pb, 256 - 1000000 / enc->sample_rate);
+            avio_w8(pb, enc->codec_tag);
         }
         voc->param_written = 1;
     } else {
-        put_byte(pb, VOC_TYPE_VOICE_DATA_CONT);
-        put_le24(pb, pkt->size);
+        avio_w8(pb, VOC_TYPE_VOICE_DATA_CONT);
+        avio_wl24(pb, pkt->size);
     }
 
-    put_buffer(pb, pkt->data, pkt->size);
+    avio_write(pb, pkt->data, pkt->size);
     return 0;
 }
 
 static int voc_write_trailer(AVFormatContext *s)
 {
-    put_byte(s->pb, 0);
+    avio_w8(s->pb, 0);
     return 0;
 }
 
-AVOutputFormat voc_muxer = {
+AVOutputFormat ff_voc_muxer = {
     "voc",
     NULL_IF_CONFIG_SMALL("Creative Voice file format"),
     "audio/x-voc",
diff --git a/libavformat/vorbiscomment.c b/libavformat/vorbiscomment.c
index d23c66d..22176c6 100644
--- a/libavformat/vorbiscomment.c
+++ b/libavformat/vorbiscomment.c
@@ -2,20 +2,20 @@
  * VorbisComment writer
  * Copyright (c) 2009 James Darnley
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -32,6 +32,7 @@
 const AVMetadataConv ff_vorbiscomment_metadata_conv[] = {
     { "ALBUMARTIST", "album_artist"},
     { "TRACKNUMBER", "track"  },
+    { "DISCNUMBER",  "disc"   },
     { 0 }
 };
 
@@ -43,7 +44,7 @@ int ff_vorbiscomment_length(AVMetadata *m, const char *vendor_string,
     *count = 0;
     if (m) {
         AVMetadataTag *tag = NULL;
-        while ( (tag = av_metadata_get(m, "", tag, AV_METADATA_IGNORE_SUFFIX) ) ) {
+        while ((tag = av_metadata_get(m, "", tag, AV_METADATA_IGNORE_SUFFIX))) {
             len += 4 +strlen(tag->key) + 1 + strlen(tag->value);
             (*count)++;
         }
@@ -51,15 +52,15 @@ int ff_vorbiscomment_length(AVMetadata *m, const char *vendor_string,
     return len;
 }
 
-int ff_vorbiscomment_write(uint8_t **p, AVMetadata *m,
+int ff_vorbiscomment_write(uint8_t **p, AVMetadata **m,
                            const char *vendor_string, const unsigned count)
 {
     bytestream_put_le32(p, strlen(vendor_string));
     bytestream_put_buffer(p, vendor_string, strlen(vendor_string));
-    if (m) {
+    if (*m) {
         AVMetadataTag *tag = NULL;
         bytestream_put_le32(p, count);
-        while ( (tag = av_metadata_get(m, "", tag, AV_METADATA_IGNORE_SUFFIX) ) ) {
+        while ((tag = av_metadata_get(*m, "", tag, AV_METADATA_IGNORE_SUFFIX))) {
             unsigned int len1 = strlen(tag->key);
             unsigned int len2 = strlen(tag->value);
             bytestream_put_le32(p, len1+1+len2);
diff --git a/libavformat/vorbiscomment.h b/libavformat/vorbiscomment.h
index 714f1f2..98cc4f8 100644
--- a/libavformat/vorbiscomment.h
+++ b/libavformat/vorbiscomment.h
@@ -2,20 +2,20 @@
  * VorbisComment writer
  * Copyright (c) 2009 James Darnley
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -26,7 +26,7 @@
 #include "metadata.h"
 
 /**
- * Calculates the length in bytes of a VorbisComment. This is the minimum
+ * Calculate the length in bytes of a VorbisComment. This is the minimum
  * size required by ff_vorbiscomment_write().
  *
  * @param m The metadata structure to be parsed. For no metadata, set to NULL.
@@ -49,7 +49,7 @@ int ff_vorbiscomment_length(AVMetadata *m, const char *vendor_string,
  * @param vendor_string The vendor string to write.
  * @param count The number of tags in m because m->count is "not allowed"
  */
-int ff_vorbiscomment_write(uint8_t **p, AVMetadata *m,
+int ff_vorbiscomment_write(uint8_t **p, AVMetadata **m,
                            const char *vendor_string, const unsigned count);
 
 extern const AVMetadataConv ff_vorbiscomment_metadata_conv[];
diff --git a/libavformat/vqf.c b/libavformat/vqf.c
index b0ec020..14fb8d7 100644
--- a/libavformat/vqf.c
+++ b/libavformat/vqf.c
@@ -2,20 +2,20 @@
  * VQF demuxer
  * Copyright (c) 2009 Vitor Sessak
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -54,7 +54,7 @@ static void add_metadata(AVFormatContext *s, const char *tag,
     buf = av_malloc(len+1);
     if (!buf)
         return;
-    get_buffer(s->pb, buf, len);
+    avio_read(s->pb, buf, len);
     buf[len] = 0;
     av_metadata_set2(&s->metadata, tag, buf, AV_METADATA_DONT_STRDUP_VAL);
 }
@@ -72,9 +72,9 @@ static int vqf_read_header(AVFormatContext *s, AVFormatParameters *ap)
     if (!st)
         return AVERROR(ENOMEM);
 
-    url_fskip(s->pb, 12);
+    avio_skip(s->pb, 12);
 
-    header_size = get_be32(s->pb);
+    header_size = avio_rb32(s->pb);
 
     st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
     st->codec->codec_id   = CODEC_ID_TWINVQ;
@@ -82,12 +82,12 @@ static int vqf_read_header(AVFormatContext *s, AVFormatParameters *ap)
 
     do {
         int len;
-        chunk_tag = get_le32(s->pb);
+        chunk_tag = avio_rl32(s->pb);
 
         if (chunk_tag == MKTAG('D','A','T','A'))
             break;
 
-        len = get_be32(s->pb);
+        len = avio_rb32(s->pb);
 
         if ((unsigned) len > INT_MAX/2) {
             av_log(s, AV_LOG_ERROR, "Malformed header\n");
@@ -98,10 +98,10 @@ static int vqf_read_header(AVFormatContext *s, AVFormatParameters *ap)
 
         switch(chunk_tag){
         case MKTAG('C','O','M','M'):
-            st->codec->channels = get_be32(s->pb) + 1;
-            read_bitrate        = get_be32(s->pb);
-            rate_flag           = get_be32(s->pb);
-            url_fskip(s->pb, len-12);
+            st->codec->channels = avio_rb32(s->pb) + 1;
+            read_bitrate        = avio_rb32(s->pb);
+            rate_flag           = avio_rb32(s->pb);
+            avio_skip(s->pb, len-12);
 
             st->codec->bit_rate              = read_bitrate*1000;
             st->codec->bits_per_coded_sample = 16;
@@ -140,7 +140,7 @@ static int vqf_read_header(AVFormatContext *s, AVFormatParameters *ap)
             av_log(s, AV_LOG_ERROR, "Unknown chunk: %c%c%c%c\n",
                    ((char*)&chunk_tag)[0], ((char*)&chunk_tag)[1],
                    ((char*)&chunk_tag)[2], ((char*)&chunk_tag)[3]);
-            url_fskip(s->pb, FFMIN(len, header_size));
+            avio_skip(s->pb, FFMIN(len, header_size));
             break;
         }
 
@@ -200,7 +200,7 @@ static int vqf_read_packet(AVFormatContext *s, AVPacket *pkt)
     int ret;
     int size = (c->frame_bit_len - c->remaining_bits + 7)>>3;
 
-    pkt->pos          = url_ftell(s->pb);
+    pkt->pos          = avio_tell(s->pb);
     pkt->stream_index = 0;
 
     if (av_new_packet(pkt, size+2) < 0)
@@ -208,7 +208,7 @@ static int vqf_read_packet(AVFormatContext *s, AVPacket *pkt)
 
     pkt->data[0] = 8 - c->remaining_bits; // Number of bits to skip
     pkt->data[1] = c->last_frame_bits;
-    ret = get_buffer(s->pb, pkt->data+2, size);
+    ret = avio_read(s->pb, pkt->data+2, size);
 
     if (ret<=0) {
         av_free_packet(pkt);
@@ -240,14 +240,14 @@ static int vqf_read_seek(AVFormatContext *s,
     st->cur_dts = av_rescale(pos, st->time_base.den,
                              st->codec->bit_rate * (int64_t)st->time_base.num);
 
-    if ((ret = url_fseek(s->pb, ((pos-7) >> 3) + s->data_offset, SEEK_SET)) < 0)
+    if ((ret = avio_seek(s->pb, ((pos-7) >> 3) + s->data_offset, SEEK_SET)) < 0)
         return ret;
 
     c->remaining_bits = -7 - ((pos-7)&7);
     return 0;
 }
 
-AVInputFormat vqf_demuxer = {
+AVInputFormat ff_vqf_demuxer = {
     "vqf",
     NULL_IF_CONFIG_SMALL("Nippon Telegraph and Telephone Corporation (NTT) TwinVQ"),
     sizeof(VqfContext),
diff --git a/libavformat/wav.c b/libavformat/wav.c
index da08558..21374e8 100644
--- a/libavformat/wav.c
+++ b/libavformat/wav.c
@@ -6,24 +6,25 @@
  * RF64 demuxer
  * Copyright (c) 2009 Daniel Verkamp
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #include "avformat.h"
-#include "raw.h"
+#include "avio_internal.h"
+#include "pcm.h"
 #include "riff.h"
 
 typedef struct {
@@ -39,12 +40,12 @@ typedef struct {
 static int wav_write_header(AVFormatContext *s)
 {
     WAVContext *wav = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int64_t fmt, fact;
 
-    put_tag(pb, "RIFF");
-    put_le32(pb, 0); /* file length */
-    put_tag(pb, "WAVE");
+    ffio_wfourcc(pb, "RIFF");
+    avio_wl32(pb, 0); /* file length */
+    ffio_wfourcc(pb, "WAVE");
 
     /* format header */
     fmt = ff_start_tag(pb, "fmt ");
@@ -57,9 +58,9 @@ static int wav_write_header(AVFormatContext *s)
     ff_end_tag(pb, fmt);
 
     if (s->streams[0]->codec->codec_tag != 0x01 /* hence for all other than PCM */
-        && !url_is_streamed(s->pb)) {
+        && s->pb->seekable) {
         fact = ff_start_tag(pb, "fact");
-        put_le32(pb, 0);
+        avio_wl32(pb, 0);
         ff_end_tag(pb, fact);
     }
 
@@ -70,16 +71,16 @@ static int wav_write_header(AVFormatContext *s)
     /* data header */
     wav->data = ff_start_tag(pb, "data");
 
-    put_flush_packet(pb);
+    avio_flush(pb);
 
     return 0;
 }
 
 static int wav_write_packet(AVFormatContext *s, AVPacket *pkt)
 {
-    ByteIOContext *pb  = s->pb;
+    AVIOContext *pb  = s->pb;
     WAVContext    *wav = s->priv_data;
-    put_buffer(pb, pkt->data, pkt->size);
+    avio_write(pb, pkt->data, pkt->size);
     if(pkt->pts != AV_NOPTS_VALUE) {
         wav->minpts        = FFMIN(wav->minpts, pkt->pts);
         wav->maxpts        = FFMAX(wav->maxpts, pkt->pts);
@@ -91,20 +92,22 @@ static int wav_write_packet(AVFormatContext *s, AVPacket *pkt)
 
 static int wav_write_trailer(AVFormatContext *s)
 {
-    ByteIOContext *pb  = s->pb;
+    AVIOContext *pb  = s->pb;
     WAVContext    *wav = s->priv_data;
     int64_t file_size;
 
-    if (!url_is_streamed(s->pb)) {
+    avio_flush(pb);
+
+    if (s->pb->seekable) {
         ff_end_tag(pb, wav->data);
 
         /* update file size */
-        file_size = url_ftell(pb);
-        url_fseek(pb, 4, SEEK_SET);
-        put_le32(pb, (uint32_t)(file_size - 8));
-        url_fseek(pb, file_size, SEEK_SET);
+        file_size = avio_tell(pb);
+        avio_seek(pb, 4, SEEK_SET);
+        avio_wl32(pb, (uint32_t)(file_size - 8));
+        avio_seek(pb, file_size, SEEK_SET);
 
-        put_flush_packet(pb);
+        avio_flush(pb);
 
         if(s->streams[0]->codec->codec_tag != 0x01) {
             /* Update num_samps in fact chunk */
@@ -112,16 +115,16 @@ static int wav_write_trailer(AVFormatContext *s)
             number_of_samples = av_rescale(wav->maxpts - wav->minpts + wav->last_duration,
                                            s->streams[0]->codec->sample_rate * (int64_t)s->streams[0]->time_base.num,
                                            s->streams[0]->time_base.den);
-            url_fseek(pb, wav->data-12, SEEK_SET);
-            put_le32(pb, number_of_samples);
-            url_fseek(pb, file_size, SEEK_SET);
-            put_flush_packet(pb);
+            avio_seek(pb, wav->data-12, SEEK_SET);
+            avio_wl32(pb, number_of_samples);
+            avio_seek(pb, file_size, SEEK_SET);
+            avio_flush(pb);
         }
     }
     return 0;
 }
 
-AVOutputFormat wav_muxer = {
+AVOutputFormat ff_wav_muxer = {
     "wav",
     NULL_IF_CONFIG_SMALL("WAV format"),
     "audio/x-wav",
@@ -138,20 +141,26 @@ AVOutputFormat wav_muxer = {
 
 
 #if CONFIG_WAV_DEMUXER
+
+static int64_t next_tag(AVIOContext *pb, unsigned int *tag)
+{
+    *tag = avio_rl32(pb);
+    return avio_rl32(pb);
+}
+
 /* return the size of the found tag */
-static int64_t find_tag(ByteIOContext *pb, uint32_t tag1)
+static int64_t find_tag(AVIOContext *pb, uint32_t tag1)
 {
     unsigned int tag;
     int64_t size;
 
     for (;;) {
-        if (url_feof(pb))
+        if (pb->eof_reached)
             return -1;
-        tag  = get_le32(pb);
-        size = get_le32(pb);
+        size = next_tag(pb, &tag);
         if (tag == tag1)
             break;
-        url_fseek(pb, size, SEEK_CUR);
+        avio_skip(pb, size);
     }
     return size;
 }
@@ -181,32 +190,35 @@ static int wav_read_header(AVFormatContext *s,
                            AVFormatParameters *ap)
 {
     int64_t size, av_uninit(data_size);
+    int64_t sample_count=0;
     int rf64;
     unsigned int tag;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVStream *st;
     WAVContext *wav = s->priv_data;
+    int ret;
 
     /* check RIFF header */
-    tag = get_le32(pb);
+    tag = avio_rl32(pb);
 
     rf64 = tag == MKTAG('R', 'F', '6', '4');
     if (!rf64 && tag != MKTAG('R', 'I', 'F', 'F'))
         return -1;
-    get_le32(pb); /* file size */
-    tag = get_le32(pb);
+    avio_rl32(pb); /* file size */
+    tag = avio_rl32(pb);
     if (tag != MKTAG('W', 'A', 'V', 'E'))
         return -1;
 
     if (rf64) {
-        if (get_le32(pb) != MKTAG('d', 's', '6', '4'))
+        if (avio_rl32(pb) != MKTAG('d', 's', '6', '4'))
             return -1;
-        size = get_le32(pb);
+        size = avio_rl32(pb);
         if (size < 16)
             return -1;
-        get_le64(pb); /* RIFF size */
-        data_size = get_le64(pb);
-        url_fskip(pb, size - 16); /* skip rest of ds64 chunk */
+        avio_rl64(pb); /* RIFF size */
+        data_size = avio_rl64(pb);
+        sample_count = avio_rl64(pb);
+        avio_skip(pb, size - 16); /* skip rest of ds64 chunk */
     }
 
     /* parse fmt header */
@@ -217,12 +229,25 @@ static int wav_read_header(AVFormatContext *s,
     if (!st)
         return AVERROR(ENOMEM);
 
-    ff_get_wav_header(pb, st->codec, size);
+    ret = ff_get_wav_header(pb, st->codec, size);
+    if (ret < 0)
+        return ret;
     st->need_parsing = AVSTREAM_PARSE_FULL;
 
     av_set_pts_info(st, 64, 1, st->codec->sample_rate);
 
-    size = find_tag(pb, MKTAG('d', 'a', 't', 'a'));
+    for (;;) {
+        if (pb->eof_reached)
+            return -1;
+        size = next_tag(pb, &tag);
+        if (tag == MKTAG('d', 'a', 't', 'a')){
+            break;
+        }else if (tag == MKTAG('f','a','c','t') && !sample_count){
+            sample_count = avio_rl32(pb);
+            size -= 4;
+        }
+        avio_skip(pb, size);
+    }
     if (rf64)
         size = data_size;
     if (size < 0)
@@ -230,26 +255,31 @@ static int wav_read_header(AVFormatContext *s,
     if (!size) {
         wav->data_end = INT64_MAX;
     } else
-        wav->data_end= url_ftell(pb) + size;
+        wav->data_end= avio_tell(pb) + size;
+
+    if (!sample_count && st->codec->channels && av_get_bits_per_sample(st->codec->codec_id))
+        sample_count = (size<<3) / (st->codec->channels * (uint64_t)av_get_bits_per_sample(st->codec->codec_id));
+    if (sample_count)
+        st->duration = sample_count;
     return 0;
 }
 
 /** Find chunk with w64 GUID by skipping over other chunks
  * @return the size of the found chunk
  */
-static int64_t find_guid(ByteIOContext *pb, const uint8_t guid1[16])
+static int64_t find_guid(AVIOContext *pb, const uint8_t guid1[16])
 {
     uint8_t guid[16];
     int64_t size;
 
-    while (!url_feof(pb)) {
-        get_buffer(pb, guid, 16);
-        size = get_le64(pb);
+    while (!pb->eof_reached) {
+        avio_read(pb, guid, 16);
+        size = avio_rl64(pb);
         if (size <= 24)
             return -1;
         if (!memcmp(guid, guid1, 16))
             return size;
-        url_fskip(pb, FFALIGN(size, INT64_C(8)) - 24);
+        avio_skip(pb, FFALIGN(size, INT64_C(8)) - 24);
     }
     return -1;
 }
@@ -269,7 +299,7 @@ static int wav_read_packet(AVFormatContext *s,
 
     st = s->streams[0];
 
-    left = wav->data_end - url_ftell(s->pb);
+    left = wav->data_end - avio_tell(s->pb);
     if (left <= 0){
         if (CONFIG_W64_DEMUXER && wav->w64)
             left = find_guid(s->pb, guid_data) - 24;
@@ -277,7 +307,7 @@ static int wav_read_packet(AVFormatContext *s,
             left = find_tag(s->pb, MKTAG('d', 'a', 't', 'a'));
         if (left < 0)
             return AVERROR_EOF;
-        wav->data_end= url_ftell(s->pb) + left;
+        wav->data_end= avio_tell(s->pb) + left;
     }
 
     size = MAX_SIZE;
@@ -314,7 +344,7 @@ static int wav_read_seek(AVFormatContext *s,
     return pcm_read_seek(s, stream_index, timestamp, flags);
 }
 
-AVInputFormat wav_demuxer = {
+AVInputFormat ff_wav_demuxer = {
     "wav",
     NULL_IF_CONFIG_SMALL("WAV format"),
     sizeof(WAVContext),
@@ -353,19 +383,20 @@ static int w64_probe(AVProbeData *p)
 static int w64_read_header(AVFormatContext *s, AVFormatParameters *ap)
 {
     int64_t size;
-    ByteIOContext *pb  = s->pb;
+    AVIOContext *pb  = s->pb;
     WAVContext    *wav = s->priv_data;
     AVStream *st;
     uint8_t guid[16];
+    int ret;
 
-    get_buffer(pb, guid, 16);
+    avio_read(pb, guid, 16);
     if (memcmp(guid, guid_riff, 16))
         return -1;
 
-    if (get_le64(pb) < 16 + 8 + 16 + 8 + 16 + 8) /* riff + wave + fmt + sizes */
+    if (avio_rl64(pb) < 16 + 8 + 16 + 8 + 16 + 8) /* riff + wave + fmt + sizes */
         return -1;
 
-    get_buffer(pb, guid, 16);
+    avio_read(pb, guid, 16);
     if (memcmp(guid, guid_wave, 16)) {
         av_log(s, AV_LOG_ERROR, "could not find wave guid\n");
         return -1;
@@ -382,8 +413,10 @@ static int w64_read_header(AVFormatContext *s, AVFormatParameters *ap)
         return AVERROR(ENOMEM);
 
     /* subtract chunk header size - normal wav file doesn't count it */
-    ff_get_wav_header(pb, st->codec, size - 24);
-    url_fskip(pb, FFALIGN(size, INT64_C(8)) - size);
+    ret = ff_get_wav_header(pb, st->codec, size - 24);
+    if (ret < 0)
+        return ret;
+    avio_skip(pb, FFALIGN(size, INT64_C(8)) - size);
 
     st->need_parsing = AVSTREAM_PARSE_FULL;
 
@@ -394,13 +427,13 @@ static int w64_read_header(AVFormatContext *s, AVFormatParameters *ap)
         av_log(s, AV_LOG_ERROR, "could not find data guid\n");
         return -1;
     }
-    wav->data_end = url_ftell(pb) + size - 24;
+    wav->data_end = avio_tell(pb) + size - 24;
     wav->w64      = 1;
 
     return 0;
 }
 
-AVInputFormat w64_demuxer = {
+AVInputFormat ff_w64_demuxer = {
     "w64",
     NULL_IF_CONFIG_SMALL("Sony Wave64 format"),
     sizeof(WAVContext),
diff --git a/libavformat/wc3movie.c b/libavformat/wc3movie.c
index d5f0863..292ef66 100644
--- a/libavformat/wc3movie.c
+++ b/libavformat/wc3movie.c
@@ -2,20 +2,20 @@
  * Wing Commander III Movie (.mve) File Demuxer
  * Copyright (c) 2003 The ffmpeg Project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -57,69 +57,18 @@
 #define WC3_FRAME_FPS 15
 
 #define PALETTE_SIZE (256 * 3)
-#define PALETTE_COUNT 256
 
 typedef struct Wc3DemuxContext {
     int width;
     int height;
-    unsigned char *palettes;
-    int palette_count;
     int64_t pts;
     int video_stream_index;
     int audio_stream_index;
 
-    AVPaletteControl palette_control;
+    AVPacket vpkt;
 
 } Wc3DemuxContext;
 
-/**
- * palette lookup table that does gamma correction
- *
- * can be calculated by this formula:
- * for i between 0 and 251 inclusive:
- * wc3_pal_lookup[i] = round(pow(i / 256.0, 0.8) * 256);
- * values 252, 253, 254 and 255 are all 0xFD
- * calculating this at runtime should not cause any
- * rounding issues, the maximum difference between
- * the table values and the calculated doubles is
- * about 0.497527
- */
-static const unsigned char wc3_pal_lookup[] = {
-  0x00, 0x03, 0x05, 0x07, 0x09, 0x0B, 0x0D, 0x0E,
-  0x10, 0x12, 0x13, 0x15, 0x16, 0x18, 0x19, 0x1A,
-  0x1C, 0x1D, 0x1F, 0x20, 0x21, 0x23, 0x24, 0x25,
-  0x27, 0x28, 0x29, 0x2A, 0x2C, 0x2D, 0x2E, 0x2F,
-  0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x38, 0x39,
-  0x3A, 0x3B, 0x3C, 0x3D, 0x3F, 0x40, 0x41, 0x42,
-  0x43, 0x44, 0x45, 0x46, 0x48, 0x49, 0x4A, 0x4B,
-  0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53,
-  0x54, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x5B, 0x5C,
-  0x5D, 0x5E, 0x5F, 0x60, 0x61, 0x62, 0x63, 0x64,
-  0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C,
-  0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74,
-  0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x7B, 0x7C,
-  0x7D, 0x7D, 0x7E, 0x7F, 0x80, 0x81, 0x82, 0x83,
-  0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x8B,
-  0x8C, 0x8D, 0x8D, 0x8E, 0x8F, 0x90, 0x91, 0x92,
-  0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x99,
-  0x9A, 0x9B, 0x9C, 0x9D, 0x9E, 0x9F, 0xA0, 0xA1,
-  0xA2, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8,
-  0xA9, 0xAA, 0xAA, 0xAB, 0xAC, 0xAD, 0xAE, 0xAF,
-  0xB0, 0xB1, 0xB2, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6,
-  0xB7, 0xB8, 0xB9, 0xB9, 0xBA, 0xBB, 0xBC, 0xBD,
-  0xBE, 0xBF, 0xBF, 0xC0, 0xC1, 0xC2, 0xC3, 0xC4,
-  0xC5, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB,
-  0xCB, 0xCC, 0xCD, 0xCE, 0xCF, 0xD0, 0xD0, 0xD1,
-  0xD2, 0xD3, 0xD4, 0xD5, 0xD5, 0xD6, 0xD7, 0xD8,
-  0xD9, 0xDA, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0xDF,
-  0xDF, 0xE0, 0xE1, 0xE2, 0xE3, 0xE4, 0xE4, 0xE5,
-  0xE6, 0xE7, 0xE8, 0xE9, 0xE9, 0xEA, 0xEB, 0xEC,
-  0xED, 0xED, 0xEE, 0xEF, 0xF0, 0xF1, 0xF1, 0xF2,
-  0xF3, 0xF4, 0xF5, 0xF6, 0xF6, 0xF7, 0xF8, 0xF9,
-  0xFA, 0xFA, 0xFB, 0xFC, 0xFD, 0xFD, 0xFD, 0xFD
-};
-
-
 static int wc3_probe(AVProbeData *p)
 {
     if (p->buf_size < 12)
@@ -136,31 +85,28 @@ static int wc3_read_header(AVFormatContext *s,
                            AVFormatParameters *ap)
 {
     Wc3DemuxContext *wc3 = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     unsigned int fourcc_tag;
     unsigned int size;
     AVStream *st;
     int ret = 0;
-    int current_palette = 0;
     char *buffer;
-    int i;
-    unsigned char rotate;
 
     /* default context members */
     wc3->width = WC3_DEFAULT_WIDTH;
     wc3->height = WC3_DEFAULT_HEIGHT;
-    wc3->palettes = NULL;
-    wc3->palette_count = 0;
     wc3->pts = 0;
     wc3->video_stream_index = wc3->audio_stream_index = 0;
+    av_init_packet(&wc3->vpkt);
+    wc3->vpkt.data = NULL; wc3->vpkt.size = 0;
 
     /* skip the first 3 32-bit numbers */
-    url_fseek(pb, 12, SEEK_CUR);
+    avio_skip(pb, 12);
 
     /* traverse through the chunks and load the header information before
      * the first BRCH tag */
-    fourcc_tag = get_le32(pb);
-    size = (get_be32(pb) + 1) & (~1);
+    fourcc_tag = avio_rl32(pb);
+    size = (avio_rb32(pb) + 1) & (~1);
 
     do {
         switch (fourcc_tag) {
@@ -168,18 +114,12 @@ static int wc3_read_header(AVFormatContext *s,
         case SOND_TAG:
         case INDX_TAG:
             /* SOND unknown, INDX unnecessary; ignore both */
-            url_fseek(pb, size, SEEK_CUR);
+            avio_skip(pb, size);
             break;
 
         case PC__TAG:
-            /* need the number of palettes */
-            url_fseek(pb, 8, SEEK_CUR);
-            wc3->palette_count = get_le32(pb);
-            if((unsigned)wc3->palette_count >= UINT_MAX / PALETTE_SIZE){
-                wc3->palette_count= 0;
-                return -1;
-            }
-            wc3->palettes = av_malloc(wc3->palette_count * PALETTE_SIZE);
+            /* number of palettes, unneeded */
+            avio_skip(pb, 12);
             break;
 
         case BNAM_TAG:
@@ -187,7 +127,7 @@ static int wc3_read_header(AVFormatContext *s,
             buffer = av_malloc(size+1);
             if (!buffer)
                 return AVERROR(ENOMEM);
-            if ((ret = get_buffer(pb, buffer, size)) != size)
+            if ((ret = avio_read(pb, buffer, size)) != size)
                 return AVERROR(EIO);
             buffer[size] = 0;
             av_metadata_set2(&s->metadata, "title", buffer,
@@ -196,29 +136,14 @@ static int wc3_read_header(AVFormatContext *s,
 
         case SIZE_TAG:
             /* video resolution override */
-            wc3->width  = get_le32(pb);
-            wc3->height = get_le32(pb);
+            wc3->width  = avio_rl32(pb);
+            wc3->height = avio_rl32(pb);
             break;
 
         case PALT_TAG:
             /* one of several palettes */
-            if ((unsigned)current_palette >= wc3->palette_count)
-                return AVERROR_INVALIDDATA;
-            if ((ret = get_buffer(pb,
-                &wc3->palettes[current_palette * PALETTE_SIZE],
-                PALETTE_SIZE)) != PALETTE_SIZE)
-                return AVERROR(EIO);
-
-            /* transform the current palette in place */
-            for (i = current_palette * PALETTE_SIZE;
-                 i < (current_palette + 1) * PALETTE_SIZE; i++) {
-                /* rotate each palette component left by 2 and use the result
-                 * as an index into the color component table */
-                rotate = ((wc3->palettes[i] << 2) & 0xFF) |
-                         ((wc3->palettes[i] >> 6) & 0xFF);
-                wc3->palettes[i] = wc3_pal_lookup[rotate];
-            }
-            current_palette++;
+            avio_seek(pb, -8, SEEK_CUR);
+            av_append_packet(pb, &wc3->vpkt, 8 + PALETTE_SIZE);
             break;
 
         default:
@@ -229,10 +154,10 @@ static int wc3_read_header(AVFormatContext *s,
             break;
         }
 
-        fourcc_tag = get_le32(pb);
+        fourcc_tag = avio_rl32(pb);
         /* chunk sizes are 16-bit aligned */
-        size = (get_be32(pb) + 1) & (~1);
-        if (url_feof(pb))
+        size = (avio_rb32(pb) + 1) & (~1);
+        if (pb->eof_reached)
             return AVERROR(EIO);
 
     } while (fourcc_tag != BRCH_TAG);
@@ -249,9 +174,6 @@ static int wc3_read_header(AVFormatContext *s,
     st->codec->width = wc3->width;
     st->codec->height = wc3->height;
 
-    /* palette considerations */
-    st->codec->palctrl = &wc3->palette_control;
-
     st = av_new_stream(s, 0);
     if (!st)
         return AVERROR(ENOMEM);
@@ -274,23 +196,19 @@ static int wc3_read_packet(AVFormatContext *s,
                            AVPacket *pkt)
 {
     Wc3DemuxContext *wc3 = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     unsigned int fourcc_tag;
     unsigned int size;
     int packet_read = 0;
     int ret = 0;
     unsigned char text[1024];
-    unsigned int palette_number;
-    int i;
-    unsigned char r, g, b;
-    int base_palette_index;
 
     while (!packet_read) {
 
-        fourcc_tag = get_le32(pb);
+        fourcc_tag = avio_rl32(pb);
         /* chunk sizes are 16-bit aligned */
-        size = (get_be32(pb) + 1) & (~1);
-        if (url_feof(pb))
+        size = (avio_rb32(pb) + 1) & (~1);
+        if (pb->eof_reached)
             return AVERROR(EIO);
 
         switch (fourcc_tag) {
@@ -301,22 +219,19 @@ static int wc3_read_packet(AVFormatContext *s,
 
         case SHOT_TAG:
             /* load up new palette */
-            palette_number = get_le32(pb);
-            if (palette_number >= wc3->palette_count)
-                return AVERROR_INVALIDDATA;
-            base_palette_index = palette_number * PALETTE_COUNT * 3;
-            for (i = 0; i < PALETTE_COUNT; i++) {
-                r = wc3->palettes[base_palette_index + i * 3 + 0];
-                g = wc3->palettes[base_palette_index + i * 3 + 1];
-                b = wc3->palettes[base_palette_index + i * 3 + 2];
-                wc3->palette_control.palette[i] = (r << 16) | (g << 8) | (b);
-            }
-            wc3->palette_control.palette_changed = 1;
+            avio_seek(pb, -8, SEEK_CUR);
+            av_append_packet(pb, &wc3->vpkt, 8 + 4);
             break;
 
         case VGA__TAG:
             /* send out video chunk */
-            ret= av_get_packet(pb, pkt, size);
+            avio_seek(pb, -8, SEEK_CUR);
+            ret= av_append_packet(pb, &wc3->vpkt, 8 + size);
+            // ignore error if we have some data
+            if (wc3->vpkt.size > 0)
+                ret = 0;
+            *pkt = wc3->vpkt;
+            wc3->vpkt.data = NULL; wc3->vpkt.size = 0;
             pkt->stream_index = wc3->video_stream_index;
             pkt->pts = wc3->pts;
             packet_read = 1;
@@ -325,9 +240,9 @@ static int wc3_read_packet(AVFormatContext *s,
         case TEXT_TAG:
             /* subtitle chunk */
 #if 0
-            url_fseek(pb, size, SEEK_CUR);
+            avio_skip(pb, size);
 #else
-            if ((unsigned)size > sizeof(text) || (ret = get_buffer(pb, text, size)) != size)
+            if ((unsigned)size > sizeof(text) || (ret = avio_read(pb, text, size)) != size)
                 ret = AVERROR(EIO);
             else {
                 int i = 0;
@@ -370,12 +285,13 @@ static int wc3_read_close(AVFormatContext *s)
 {
     Wc3DemuxContext *wc3 = s->priv_data;
 
-    av_free(wc3->palettes);
+    if (wc3->vpkt.size > 0)
+        av_free_packet(&wc3->vpkt);
 
     return 0;
 }
 
-AVInputFormat wc3_demuxer = {
+AVInputFormat ff_wc3_demuxer = {
     "wc3movie",
     NULL_IF_CONFIG_SMALL("Wing Commander III movie format"),
     sizeof(Wc3DemuxContext),
diff --git a/libavformat/westwood.c b/libavformat/westwood.c
index 10d5798..7c2b17d 100644
--- a/libavformat/westwood.c
+++ b/libavformat/westwood.c
@@ -2,20 +2,20 @@
  * Westwood Studios Multimedia Formats Demuxer (VQA, AUD)
  * Copyright (c) 2003 The ffmpeg Project
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -126,11 +126,11 @@ static int wsaud_read_header(AVFormatContext *s,
                              AVFormatParameters *ap)
 {
     WsAudDemuxContext *wsaud = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVStream *st;
     unsigned char header[AUD_HEADER_SIZE];
 
-    if (get_buffer(pb, header, AUD_HEADER_SIZE) != AUD_HEADER_SIZE)
+    if (avio_read(pb, header, AUD_HEADER_SIZE) != AUD_HEADER_SIZE)
         return AVERROR(EIO);
     wsaud->audio_samplerate = AV_RL16(&header[0]);
     if (header[11] == 99)
@@ -168,12 +168,12 @@ static int wsaud_read_packet(AVFormatContext *s,
                              AVPacket *pkt)
 {
     WsAudDemuxContext *wsaud = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     unsigned char preamble[AUD_CHUNK_PREAMBLE_SIZE];
     unsigned int chunk_size;
     int ret = 0;
 
-    if (get_buffer(pb, preamble, AUD_CHUNK_PREAMBLE_SIZE) !=
+    if (avio_read(pb, preamble, AUD_CHUNK_PREAMBLE_SIZE) !=
         AUD_CHUNK_PREAMBLE_SIZE)
         return AVERROR(EIO);
 
@@ -213,7 +213,7 @@ static int wsvqa_read_header(AVFormatContext *s,
                              AVFormatParameters *ap)
 {
     WsVqaDemuxContext *wsvqa = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVStream *st;
     unsigned char *header;
     unsigned char scratch[VQA_PREAMBLE_SIZE];
@@ -231,13 +231,13 @@ static int wsvqa_read_header(AVFormatContext *s,
     st->codec->codec_tag = 0;  /* no fourcc */
 
     /* skip to the start of the VQA header */
-    url_fseek(pb, 20, SEEK_SET);
+    avio_seek(pb, 20, SEEK_SET);
 
     /* the VQA header needs to go to the decoder */
     st->codec->extradata_size = VQA_HEADER_SIZE;
     st->codec->extradata = av_mallocz(VQA_HEADER_SIZE + FF_INPUT_BUFFER_PADDING_SIZE);
     header = (unsigned char *)st->codec->extradata;
-    if (get_buffer(pb, st->codec->extradata, VQA_HEADER_SIZE) !=
+    if (avio_read(pb, st->codec->extradata, VQA_HEADER_SIZE) !=
         VQA_HEADER_SIZE) {
         av_free(st->codec->extradata);
         return AVERROR(EIO);
@@ -277,7 +277,7 @@ static int wsvqa_read_header(AVFormatContext *s,
     /* there are 0 or more chunks before the FINF chunk; iterate until
      * FINF has been skipped and the file will be ready to be demuxed */
     do {
-        if (get_buffer(pb, scratch, VQA_PREAMBLE_SIZE) != VQA_PREAMBLE_SIZE) {
+        if (avio_read(pb, scratch, VQA_PREAMBLE_SIZE) != VQA_PREAMBLE_SIZE) {
             av_free(st->codec->extradata);
             return AVERROR(EIO);
         }
@@ -303,7 +303,7 @@ static int wsvqa_read_header(AVFormatContext *s,
             break;
         }
 
-        url_fseek(pb, chunk_size, SEEK_CUR);
+        avio_skip(pb, chunk_size);
     } while (chunk_tag != FINF_TAG);
 
     return 0;
@@ -313,14 +313,14 @@ static int wsvqa_read_packet(AVFormatContext *s,
                              AVPacket *pkt)
 {
     WsVqaDemuxContext *wsvqa = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int ret = -1;
     unsigned char preamble[VQA_PREAMBLE_SIZE];
     unsigned int chunk_type;
     unsigned int chunk_size;
     int skip_byte;
 
-    while (get_buffer(pb, preamble, VQA_PREAMBLE_SIZE) == VQA_PREAMBLE_SIZE) {
+    while (avio_read(pb, preamble, VQA_PREAMBLE_SIZE) == VQA_PREAMBLE_SIZE) {
         chunk_type = AV_RB32(&preamble[0]);
         chunk_size = AV_RB32(&preamble[4]);
         skip_byte = chunk_size & 0x01;
@@ -329,7 +329,7 @@ static int wsvqa_read_packet(AVFormatContext *s,
 
             if (av_new_packet(pkt, chunk_size))
                 return AVERROR(EIO);
-            ret = get_buffer(pb, pkt->data, chunk_size);
+            ret = avio_read(pb, pkt->data, chunk_size);
             if (ret != chunk_size) {
                 av_free_packet(pkt);
                 return AVERROR(EIO);
@@ -348,7 +348,7 @@ static int wsvqa_read_packet(AVFormatContext *s,
             }
             /* stay on 16-bit alignment */
             if (skip_byte)
-                url_fseek(pb, 1, SEEK_CUR);
+                avio_skip(pb, 1);
 
             return ret;
         } else {
@@ -359,7 +359,7 @@ static int wsvqa_read_packet(AVFormatContext *s,
             default:
                 av_log(s, AV_LOG_INFO, "Skipping unknown chunk 0x%08X\n", chunk_type);
             }
-            url_fseek(pb, chunk_size + skip_byte, SEEK_CUR);
+            avio_skip(pb, chunk_size + skip_byte);
         }
     }
 
@@ -367,7 +367,7 @@ static int wsvqa_read_packet(AVFormatContext *s,
 }
 
 #if CONFIG_WSAUD_DEMUXER
-AVInputFormat wsaud_demuxer = {
+AVInputFormat ff_wsaud_demuxer = {
     "wsaud",
     NULL_IF_CONFIG_SMALL("Westwood Studios audio format"),
     sizeof(WsAudDemuxContext),
@@ -377,7 +377,7 @@ AVInputFormat wsaud_demuxer = {
 };
 #endif
 #if CONFIG_WSVQA_DEMUXER
-AVInputFormat wsvqa_demuxer = {
+AVInputFormat ff_wsvqa_demuxer = {
     "wsvqa",
     NULL_IF_CONFIG_SMALL("Westwood Studios VQA format"),
     sizeof(WsVqaDemuxContext),
diff --git a/libavformat/wtv.c b/libavformat/wtv.c
new file mode 100644
index 0000000..0a18c8e
--- /dev/null
+++ b/libavformat/wtv.c
@@ -0,0 +1,1109 @@
+/*
+ * Windows Television (WTV) demuxer
+ * Copyright (c) 2010-2011 Peter Ross <pross at xvid.org>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * Windows Television (WTV) demuxer
+ * @author Peter Ross <pross at xvid.org>
+ */
+
+#include "libavutil/intreadwrite.h"
+#include "libavutil/intfloat_readwrite.h"
+#include "avformat.h"
+#include "internal.h"
+#include "riff.h"
+#include "asf.h"
+#include "mpegts.h"
+#include <strings.h>
+
+/* Macros for formating GUIDs */
+#define PRI_GUID \
+    "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x"
+#define ARG_GUID(g) \
+    g[0],g[1],g[2],g[3],g[4],g[5],g[6],g[7],g[8],g[9],g[10],g[11],g[12],g[13],g[14],g[15]
+
+#define PRI_PRETTY_GUID \
+    "%08x-%04x-%04x-%02x%02x%02x%02x%02x%02x%02x%02x"
+#define ARG_PRETTY_GUID(g) \
+    AV_RL32(g),AV_RL16(g+4),AV_RL16(g+6),g[8],g[9],g[10],g[11],g[12],g[13],g[14],g[15]
+#define LEN_PRETTY_GUID 34
+
+/*
+ *
+ * File system routines
+ *
+ */
+
+#define WTV_SECTOR_BITS    12
+#define WTV_SECTOR_SIZE    (1 << WTV_SECTOR_BITS)
+#define WTV_BIGSECTOR_BITS 18
+
+typedef struct {
+    AVIOContext *pb_filesystem;  /** file system (AVFormatContext->pb) */
+
+    int sector_bits;     /** sector shift bits; used to convert sector number into pb_filesystem offset */
+    uint32_t *sectors;   /** file allocation table */
+    int nb_sectors;      /** number of sectors */
+
+    int error;
+    int64_t position;
+    int64_t length;
+} WtvFile;
+
+/**
+ * @return bytes read, 0 on end of file, or <0 on error
+ */
+static int wtvfile_read_packet(void *opaque, uint8_t *buf, int buf_size)
+{
+    WtvFile *wf = opaque;
+    AVIOContext *pb = wf->pb_filesystem;
+    int nread = 0;
+
+    if (wf->error || pb->error)
+        return -1;
+    if (wf->position >= wf->length || pb->eof_reached)
+        return 0;
+
+    buf_size = FFMIN(buf_size, wf->length - wf->position);
+    while(nread < buf_size) {
+        int n;
+        int remaining_in_sector = (1 << wf->sector_bits) - (wf->position & ((1 << wf->sector_bits) - 1));
+        int read_request        = FFMIN(buf_size - nread, remaining_in_sector);
+
+        n = avio_read(pb, buf, read_request);
+        if (n <= 0)
+            break;
+        nread += n;
+        buf += n;
+        wf->position += n;
+        if (n == remaining_in_sector) {
+            int i = wf->position >> wf->sector_bits;
+            if (i >= wf->nb_sectors ||
+                (wf->sectors[i] != wf->sectors[i - 1] + (1 << (wf->sector_bits - WTV_SECTOR_BITS)) &&
+                avio_seek(pb, (int64_t)wf->sectors[i] << WTV_SECTOR_BITS, SEEK_SET) < 0)) {
+                wf->error = 1;
+                break;
+            }
+        }
+    }
+    return nread;
+}
+
+/**
+ * @return position (or file length)
+ */
+static int64_t wtvfile_seek(void *opaque, int64_t offset, int whence)
+{
+    WtvFile *wf = opaque;
+    AVIOContext *pb = wf->pb_filesystem;
+
+    if (whence == AVSEEK_SIZE)
+        return wf->length;
+    else if (whence == SEEK_CUR)
+        offset = wf->position + offset;
+    else if (whence == SEEK_END)
+        offset = wf->length;
+
+    wf->error = offset < 0 || offset >= wf->length ||
+                avio_seek(pb, ((int64_t)wf->sectors[offset >> wf->sector_bits] << WTV_SECTOR_BITS)
+                              + (offset & ((1 << wf->sector_bits) - 1)), SEEK_SET) < 0;
+    wf->position = offset;
+    return offset;
+}
+
+/**
+ * read non-zero integers (le32) from input stream
+ * @param pb
+ * @param[out] data destination
+ * @param     count maximum number of integers to read
+ * @return    total number of integers read
+ */
+static int read_ints(AVIOContext *pb, uint32_t *data, int count)
+{
+    int i, total = 0;
+    for (i = 0; i < count; i++) {
+        if ((data[total] = avio_rl32(pb)))
+           total++;
+    }
+    return total;
+}
+
+/**
+ * Open file
+ * @param first_sector  First sector
+ * @param length        Length of file (bytes)
+ * @param depth         File allocation table depth
+ * @return NULL on error
+ */
+static AVIOContext * wtvfile_open_sector(int first_sector, uint64_t length, int depth, AVFormatContext *s)
+{
+    AVIOContext *pb;
+    WtvFile *wf;
+    uint8_t *buffer;
+
+    if (avio_seek(s->pb, first_sector << WTV_SECTOR_BITS, SEEK_SET) < 0)
+        return NULL;
+
+    wf = av_mallocz(sizeof(WtvFile));
+    if (!wf)
+        return NULL;
+
+    if (depth == 0) {
+        wf->sectors = av_malloc(sizeof(uint32_t));
+        if (!wf->sectors) {
+            av_free(wf);
+            return NULL;
+        }
+        wf->sectors[0]  = first_sector;
+        wf->nb_sectors  = 1;
+        wf->sector_bits = WTV_SECTOR_BITS;
+    } else if (depth == 1) {
+        wf->sectors = av_malloc(WTV_SECTOR_SIZE);
+        if (!wf->sectors) {
+            av_free(wf);
+            return NULL;
+        }
+        wf->nb_sectors  = read_ints(s->pb, wf->sectors, WTV_SECTOR_SIZE / 4);
+        wf->sector_bits = length & (1ULL<<63) ? WTV_SECTOR_BITS : WTV_BIGSECTOR_BITS;
+    } else if (depth == 2) {
+        uint32_t sectors1[WTV_SECTOR_SIZE / 4];
+        int nb_sectors1 = read_ints(s->pb, sectors1, WTV_SECTOR_SIZE / 4);
+        int i;
+
+        wf->sectors = av_malloc(nb_sectors1 << WTV_SECTOR_BITS);
+        if (!wf->sectors) {
+            av_free(wf);
+            return NULL;
+        }
+        wf->nb_sectors = 0;
+        for (i = 0; i < nb_sectors1; i++) {
+            if (avio_seek(s->pb, (int64_t)sectors1[i] << WTV_SECTOR_BITS, SEEK_SET) < 0)
+                break;
+            wf->nb_sectors += read_ints(s->pb, wf->sectors + i * WTV_SECTOR_SIZE / 4, WTV_SECTOR_SIZE / 4);
+        }
+        wf->sector_bits = length & (1ULL<<63) ? WTV_SECTOR_BITS : WTV_BIGSECTOR_BITS;
+    } else {
+        av_log(s, AV_LOG_ERROR, "unsupported file allocation table depth (0x%x)\n", depth);
+        av_free(wf);
+        return NULL;
+    }
+
+    if (!wf->nb_sectors) {
+        av_free(wf->sectors);
+        av_free(wf);
+        return NULL;
+    }
+
+    /* check length */
+    length &= 0xFFFFFFFFFFFF;
+    if (length > ((int64_t)wf->nb_sectors << wf->sector_bits)) {
+        av_log(s, AV_LOG_WARNING, "reported file length (0x%"PRIx64") exceeds number of available sectors (0x%"PRIx64")\n", length, (int64_t)wf->nb_sectors << wf->sector_bits);
+        length = (int64_t)wf->nb_sectors <<  wf->sector_bits;
+    }
+    wf->length = length;
+
+    /* seek to intial sector */
+    wf->position = 0;
+    if (avio_seek(s->pb, (int64_t)wf->sectors[0] << WTV_SECTOR_BITS, SEEK_SET) < 0) {
+        av_free(wf->sectors);
+        av_free(wf);
+        return NULL;
+    }
+
+    wf->pb_filesystem = s->pb;
+    buffer = av_malloc(1 << wf->sector_bits);
+    if (!buffer) {
+        av_free(wf->sectors);
+        av_free(wf);
+        return NULL;
+    }
+
+    pb = avio_alloc_context(buffer, 1 << wf->sector_bits, 0, wf,
+                           wtvfile_read_packet, NULL, wtvfile_seek);
+    if (!pb) {
+        av_free(buffer);
+        av_free(wf->sectors);
+        av_free(wf);
+    }
+    return pb;
+}
+
+static const ff_asf_guid dir_entry_guid =
+    {0x92,0xB7,0x74,0x91,0x59,0x70,0x70,0x44,0x88,0xDF,0x06,0x3B,0x82,0xCC,0x21,0x3D};
+
+/**
+ * Open file using filename
+ * @param[in]  buf       directory buffer
+ * @param      buf_size  directory buffer size
+ * @param[in]  filename
+ * @param      filename_size size of filename
+ * @return NULL on error
+ */
+static AVIOContext * wtvfile_open2(AVFormatContext *s, const uint8_t *buf, int buf_size, const uint8_t *filename, int filename_size)
+{
+    const uint8_t *buf_end = buf + buf_size;
+
+    while(buf + 48 <= buf_end) {
+        int dir_length, name_size, first_sector, depth;
+        uint64_t file_length;
+        const uint8_t *name;
+        if (ff_guidcmp(buf, dir_entry_guid)) {
+            av_log(s, AV_LOG_ERROR, "unknown guid "PRI_GUID", expected dir_entry_guid; "
+                   "remaining directory entries ignored\n", ARG_GUID(buf));
+            break;
+        }
+        dir_length  = AV_RL16(buf + 16);
+        file_length = AV_RL64(buf + 24);
+        name_size   = 2 * AV_RL32(buf + 32);
+        if (buf + 48 + name_size > buf_end) {
+            av_log(s, AV_LOG_ERROR, "filename exceeds buffer size; remaining directory entries ignored\n");
+            break;
+        }
+        first_sector = AV_RL32(buf + 40 + name_size);
+        depth        = AV_RL32(buf + 44 + name_size);
+
+        /* compare file name; test optional null terminator */
+        name = buf + 40;
+        if (name_size >= filename_size &&
+            !memcmp(name, filename, filename_size) &&
+            (name_size < filename_size + 2 || !AV_RN16(name + filename_size)))
+            return wtvfile_open_sector(first_sector, file_length, depth, s);
+
+        buf += dir_length;
+    }
+    return 0;
+}
+
+#define wtvfile_open(s, buf, buf_size, filename) \
+    wtvfile_open2(s, buf, buf_size, filename, sizeof(filename))
+
+/**
+ * Close file opened with wtvfile_open_sector(), or wtv_open()
+ */
+static void wtvfile_close(AVIOContext *pb)
+{
+    WtvFile *wf = pb->opaque;
+    av_free(wf->sectors);
+    av_free(pb);
+}
+
+/*
+ *
+ * Main demuxer
+ *
+ */
+
+typedef struct {
+    int seen_data;
+} WtvStream;
+
+typedef struct {
+    AVIOContext *pb;       /** timeline file */
+    int64_t epoch;
+    int64_t pts;             /** pts for next data chunk */
+    int64_t last_valid_pts;  /** latest valid pts, used for interative seeking */
+
+    /* maintain private seek index, as the AVIndexEntry->pos is relative to the
+       start of the 'timeline' file, not the file system (AVFormatContext->pb) */
+    AVIndexEntry *index_entries;
+    int nb_index_entries;
+    unsigned int index_entries_allocated_size;
+} WtvContext;
+
+typedef struct {
+    enum CodecID id;
+    ff_asf_guid guid;
+} AVCodecGuid;
+
+static enum CodecID ff_codec_guid_get_id(const AVCodecGuid *guids, ff_asf_guid guid)
+{
+    int i;
+    for (i = 0; guids[i].id != CODEC_ID_NONE; i++) {
+        if (!ff_guidcmp(guids[i].guid, guid))
+            return guids[i].id;
+    }
+    return CODEC_ID_NONE;
+}
+
+/* WTV GUIDs */
+static const ff_asf_guid wtv_guid =
+    {0xB7,0xD8,0x00,0x20,0x37,0x49,0xDA,0x11,0xA6,0x4E,0x00,0x07,0xE9,0x5E,0xAD,0x8D};
+static const ff_asf_guid metadata_guid =
+    {0x5A,0xFE,0xD7,0x6D,0xC8,0x1D,0x8F,0x4A,0x99,0x22,0xFA,0xB1,0x1C,0x38,0x14,0x53};
+static const ff_asf_guid timestamp_guid =
+    {0x5B,0x05,0xE6,0x1B,0x97,0xA9,0x49,0x43,0x88,0x17,0x1A,0x65,0x5A,0x29,0x8A,0x97};
+static const ff_asf_guid data_guid =
+    {0x95,0xC3,0xD2,0xC2,0x7E,0x9A,0xDA,0x11,0x8B,0xF7,0x00,0x07,0xE9,0x5E,0xAD,0x8D};
+static const ff_asf_guid stream_guid =
+    {0xED,0xA4,0x13,0x23,0x2D,0xBF,0x4F,0x45,0xAD,0x8A,0xD9,0x5B,0xA7,0xF9,0x1F,0xEE};
+static const ff_asf_guid stream2_guid =
+    {0xA2,0xC3,0xD2,0xC2,0x7E,0x9A,0xDA,0x11,0x8B,0xF7,0x00,0x07,0xE9,0x5E,0xAD,0x8D};
+static const ff_asf_guid EVENTID_SubtitleSpanningEvent =
+    {0x48,0xC0,0xCE,0x5D,0xB9,0xD0,0x63,0x41,0x87,0x2C,0x4F,0x32,0x22,0x3B,0xE8,0x8A};
+static const ff_asf_guid EVENTID_LanguageSpanningEvent =
+    {0x6D,0x66,0x92,0xE2,0x02,0x9C,0x8D,0x44,0xAA,0x8D,0x78,0x1A,0x93,0xFD,0xC3,0x95};
+static const ff_asf_guid EVENTID_AudioDescriptorSpanningEvent =
+    {0x1C,0xD4,0x7B,0x10,0xDA,0xA6,0x91,0x46,0x83,0x69,0x11,0xB2,0xCD,0xAA,0x28,0x8E};
+static const ff_asf_guid EVENTID_CtxADescriptorSpanningEvent =
+    {0xE6,0xA2,0xB4,0x3A,0x47,0x42,0x34,0x4B,0x89,0x6C,0x30,0xAF,0xA5,0xD2,0x1C,0x24};
+static const ff_asf_guid EVENTID_CSDescriptorSpanningEvent =
+    {0xD9,0x79,0xE7,0xEf,0xF0,0x97,0x86,0x47,0x80,0x0D,0x95,0xCF,0x50,0x5D,0xDC,0x66};
+static const ff_asf_guid EVENTID_DVBScramblingControlSpanningEvent =
+    {0xC4,0xE1,0xD4,0x4B,0xA1,0x90,0x09,0x41,0x82,0x36,0x27,0xF0,0x0E,0x7D,0xCC,0x5B};
+static const ff_asf_guid EVENTID_StreamIDSpanningEvent =
+    {0x68,0xAB,0xF1,0xCA,0x53,0xE1,0x41,0x4D,0xA6,0xB3,0xA7,0xC9,0x98,0xDB,0x75,0xEE};
+static const ff_asf_guid EVENTID_TeletextSpanningEvent =
+    {0x50,0xD9,0x99,0x95,0x33,0x5F,0x17,0x46,0xAF,0x7C,0x1E,0x54,0xB5,0x10,0xDA,0xA3};
+static const ff_asf_guid EVENTID_AudioTypeSpanningEvent =
+    {0xBE,0xBF,0x1C,0x50,0x49,0xB8,0xCE,0x42,0x9B,0xE9,0x3D,0xB8,0x69,0xFB,0x82,0xB3};
+
+/* Windows media GUIDs */
+
+#define MEDIASUBTYPE_BASE_GUID \
+    0x00,0x00,0x10,0x00,0x80,0x00,0x00,0xAA,0x00,0x38,0x9B,0x71
+
+/* Media types */
+static const ff_asf_guid mediatype_audio =
+    {'a','u','d','s',MEDIASUBTYPE_BASE_GUID};
+static const ff_asf_guid mediatype_video =
+    {'v','i','d','s',MEDIASUBTYPE_BASE_GUID};
+static const ff_asf_guid mediasubtype_mpeg1payload =
+    {0x81,0xEB,0x36,0xE4,0x4F,0x52,0xCE,0x11,0x9F,0x53,0x00,0x20,0xAF,0x0B,0xA7,0x70};
+static const ff_asf_guid mediatype_mpeg2_sections =
+    {0x6C,0x17,0x5F,0x45,0x06,0x4B,0xCE,0x47,0x9A,0xEF,0x8C,0xAE,0xF7,0x3D,0xF7,0xB5};
+static const ff_asf_guid mediatype_mpeg2_pes =
+    {0x20,0x80,0x6D,0xE0,0x46,0xDB,0xCF,0x11,0xB4,0xD1,0x00,0x80,0x5F,0x6C,0xBB,0xEA};
+static const ff_asf_guid mediatype_mstvcaption =
+    {0x89,0x8A,0x8B,0xB8,0x49,0xB0,0x80,0x4C,0xAD,0xCF,0x58,0x98,0x98,0x5E,0x22,0xC1};
+
+/* Media subtypes */
+static const ff_asf_guid mediasubtype_cpfilters_processed =
+    {0x28,0xBD,0xAD,0x46,0xD0,0x6F,0x96,0x47,0x93,0xB2,0x15,0x5C,0x51,0xDC,0x04,0x8D};
+static const ff_asf_guid mediasubtype_dvb_subtitle =
+    {0xC3,0xCB,0xFF,0x34,0xB3,0xD5,0x71,0x41,0x90,0x02,0xD4,0xC6,0x03,0x01,0x69,0x7F};
+static const ff_asf_guid mediasubtype_teletext =
+    {0xE3,0x76,0x2A,0xF7,0x0A,0xEB,0xD0,0x11,0xAC,0xE4,0x00,0x00,0xC0,0xCC,0x16,0xBA};
+static const ff_asf_guid mediasubtype_dtvccdata =
+    {0xAA,0xDD,0x2A,0xF5,0xF0,0x36,0xF5,0x43,0x95,0xEA,0x6D,0x86,0x64,0x84,0x26,0x2A};
+static const ff_asf_guid mediasubtype_mpeg2_sections =
+    {0x79,0x85,0x9F,0x4A,0xF8,0x6B,0x92,0x43,0x8A,0x6D,0xD2,0xDD,0x09,0xFA,0x78,0x61};
+
+/* Formats */
+static const ff_asf_guid format_cpfilters_processed =
+    {0x6F,0xB3,0x39,0x67,0x5F,0x1D,0xC2,0x4A,0x81,0x92,0x28,0xBB,0x0E,0x73,0xD1,0x6A};
+static const ff_asf_guid format_waveformatex =
+    {0x81,0x9F,0x58,0x05,0x56,0xC3,0xCE,0x11,0xBF,0x01,0x00,0xAA,0x00,0x55,0x59,0x5A};
+static const ff_asf_guid format_videoinfo2 =
+    {0xA0,0x76,0x2A,0xF7,0x0A,0xEB,0xD0,0x11,0xAC,0xE4,0x00,0x00,0xC0,0xCC,0x16,0xBA};
+static const ff_asf_guid format_mpeg2_video =
+    {0xE3,0x80,0x6D,0xE0,0x46,0xDB,0xCF,0x11,0xB4,0xD1,0x00,0x80,0x5F,0x6C,0xBB,0xEA};
+static const ff_asf_guid format_none =
+    {0xD6,0x17,0x64,0x0F,0x18,0xC3,0xD0,0x11,0xA4,0x3F,0x00,0xA0,0xC9,0x22,0x31,0x96};
+
+static const AVCodecGuid video_guids[] = {
+    {CODEC_ID_MPEG2VIDEO, {0x26,0x80,0x6D,0xE0,0x46,0xDB,0xCF,0x11,0xB4,0xD1,0x00,0x80,0x5F,0x6C,0xBB,0xEA}},
+    {CODEC_ID_NONE}
+};
+
+static const AVCodecGuid audio_guids[] = {
+    {CODEC_ID_AC3,        {0x2C,0x80,0x6D,0xE0,0x46,0xDB,0xCF,0x11,0xB4,0xD1,0x00,0x80,0x5F,0x6C,0xBB,0xEA}},
+    {CODEC_ID_EAC3,       {0xAF,0x87,0xFB,0xA7,0x02,0x2D,0xFB,0x42,0xA4,0xD4,0x05,0xCD,0x93,0x84,0x3B,0xDD}},
+    {CODEC_ID_MP2,        {0x2B,0x80,0x6D,0xE0,0x46,0xDB,0xCF,0x11,0xB4,0xD1,0x00,0x80,0x5F,0x6C,0xBB,0xEA}},
+    {CODEC_ID_NONE}
+};
+
+static int read_probe(AVProbeData *p)
+{
+    return ff_guidcmp(p->buf, wtv_guid) ? 0 : AVPROBE_SCORE_MAX;
+}
+
+/**
+ * Convert win32 FILETIME to ISO-8601 string
+ */
+static void filetime_to_iso8601(char *buf, int buf_size, int64_t value)
+{
+    time_t t = (value / 10000000LL) - 11644473600LL;
+    strftime(buf, buf_size, "%Y-%m-%d %H:%M:%S", gmtime(&t));
+}
+
+/**
+ * Convert crazy time (100ns since 1 Jan 0001) to ISO-8601 string
+ */
+static void crazytime_to_iso8601(char *buf, int buf_size, int64_t value)
+{
+    time_t t = (value / 10000000LL) - 719162LL*86400LL;
+    strftime(buf, buf_size, "%Y-%m-%d %H:%M:%S", gmtime(&t));
+}
+
+/**
+ * Convert OLE DATE to ISO-8601 string
+ */
+static void oledate_to_iso8601(char *buf, int buf_size, int64_t value)
+{
+    time_t t = 631112400LL + 86400*av_int2dbl(value);
+    strftime(buf, buf_size, "%Y-%m-%d %H:%M:%S", gmtime(&t));
+}
+
+static void get_attachment(AVFormatContext *s, AVIOContext *pb, int length)
+{
+    char mime[1024];
+    char description[1024];
+    unsigned int filesize;
+    AVStream *st;
+    int64_t pos = avio_tell(pb);
+
+    avio_get_str16le(pb, INT_MAX, mime, sizeof(mime));
+    if (strcmp(mime, "image/jpeg"))
+        goto done;
+
+    avio_r8(pb);
+    avio_get_str16le(pb, INT_MAX, description, sizeof(description));
+    filesize = avio_rl32(pb);
+    if (!filesize)
+        goto done;
+
+    st = av_new_stream(s, 0);
+    if (!st)
+        goto done;
+    av_metadata_set2(&st->metadata, "title", description, 0);
+    st->codec->codec_id   = CODEC_ID_MJPEG;
+    st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;
+    st->codec->extradata  = av_mallocz(filesize);
+    if (!st->codec->extradata)
+        goto done;
+    st->codec->extradata_size = filesize;
+    avio_read(pb, st->codec->extradata, filesize);
+done:
+    avio_seek(pb, pos + length, SEEK_SET);
+}
+
+static void get_tag(AVFormatContext *s, AVIOContext *pb, const char *key, int type, int length)
+{
+    int buf_size = FFMAX(2*length, LEN_PRETTY_GUID) + 1;
+    char *buf = av_malloc(buf_size);
+    if (!buf)
+        return;
+
+    if (type == 0 && length == 4) {
+        snprintf(buf, buf_size, "%"PRIi32, avio_rl32(pb));
+    } else if (type == 1) {
+        avio_get_str16le(pb, length, buf, buf_size);
+        if (!strlen(buf)) {
+           av_free(buf);
+           return;
+        }
+    } else if (type == 3 && length == 4) {
+        strcpy(buf, avio_rl32(pb) ? "true" : "false");
+    } else if (type == 4 && length == 8) {
+        int64_t num = avio_rl64(pb);
+        if (!strcmp(key, "WM/EncodingTime") ||
+            !strcmp(key, "WM/MediaOriginalBroadcastDateTime"))
+            filetime_to_iso8601(buf, buf_size, num);
+        else if (!strcmp(key, "WM/WMRVEncodeTime") ||
+                 !strcmp(key, "WM/WMRVEndTime"))
+            crazytime_to_iso8601(buf, buf_size, num);
+        else if (!strcmp(key, "WM/WMRVExpirationDate"))
+            oledate_to_iso8601(buf, buf_size, num);
+        else if (!strcmp(key, "WM/WMRVBitrate"))
+            snprintf(buf, buf_size, "%f", av_int2dbl(num));
+        else
+            snprintf(buf, buf_size, "%"PRIi64, num);
+    } else if (type == 5 && length == 2) {
+        snprintf(buf, buf_size, "%"PRIi16, avio_rl16(pb));
+    } else if (type == 6 && length == 16) {
+        ff_asf_guid guid;
+        avio_read(pb, guid, 16);
+        snprintf(buf, buf_size, PRI_PRETTY_GUID, ARG_PRETTY_GUID(guid));
+    } else if (type == 2 && !strcmp(key, "WM/Picture")) {
+        get_attachment(s, pb, length);
+        av_freep(&buf);
+        return;
+    } else {
+        av_freep(&buf);
+        av_log(s, AV_LOG_WARNING, "unsupported metadata entry; key:%s, type:%d, length:0x%x\n", key, type, length);
+        avio_skip(pb, length);
+        return;
+    }
+
+    av_metadata_set2(&s->metadata, key, buf, 0);
+    av_freep(&buf);
+}
+
+/**
+ * Parse metadata entries
+ */
+static void parse_legacy_attrib(AVFormatContext *s, AVIOContext *pb)
+{
+    ff_asf_guid guid;
+    int length, type;
+    while(!pb->eof_reached) {
+        char key[1024];
+        ff_get_guid(pb, &guid);
+        type   = avio_rl32(pb);
+        length = avio_rl32(pb);
+        if (!length)
+            break;
+        if (ff_guidcmp(&guid, metadata_guid)) {
+            av_log(s, AV_LOG_WARNING, "unknown guid "PRI_GUID", expected metadata_guid; "
+                   "remaining metadata entries ignored\n", ARG_GUID(guid));
+            break;
+        }
+        avio_get_str16le(pb, INT_MAX, key, sizeof(key));
+        get_tag(s, pb, key, type, length);
+    }
+
+    ff_metadata_conv(&s->metadata, NULL, ff_asf_metadata_conv);
+}
+
+/**
+ * parse VIDEOINFOHEADER2 structure
+ * @return bytes consumed
+ */
+static int parse_videoinfoheader2(AVFormatContext *s, AVStream *st)
+{
+    WtvContext *wtv = s->priv_data;
+    AVIOContext *pb = wtv->pb;
+
+    avio_skip(pb, 72);  // picture aspect ratio is unreliable
+    ff_get_bmp_header(pb, st);
+
+    return 72 + 40;
+}
+
+/**
+ * Parse MPEG1WAVEFORMATEX extradata structure
+ */
+static void parse_mpeg1waveformatex(AVStream *st)
+{
+    /* fwHeadLayer */
+    switch (AV_RL16(st->codec->extradata)) {
+    case 0x0001 : st->codec->codec_id = CODEC_ID_MP1; break;
+    case 0x0002 : st->codec->codec_id = CODEC_ID_MP2; break;
+    case 0x0004 : st->codec->codec_id = CODEC_ID_MP3; break;
+    }
+
+    st->codec->bit_rate = AV_RL32(st->codec->extradata + 2); /* dwHeadBitrate */
+
+    /* dwHeadMode */
+    switch (AV_RL16(st->codec->extradata + 6)) {
+    case 1 : case 2 : case 4 : st->codec->channels = 2; break;
+    case 8 :                   st->codec->channels = 1; break;
+    }
+}
+
+/**
+ * Initialise stream
+ * @param st Stream to initialise, or NULL to create and initialise new stream
+ * @return NULL on error
+ */
+static AVStream * new_stream(AVFormatContext *s, AVStream *st, int sid, int codec_type)
+{
+    if (st) {
+        if (st->codec->extradata) {
+            av_freep(&st->codec->extradata);
+            st->codec->extradata_size = 0;
+        }
+    } else {
+        WtvStream *wst = av_mallocz(sizeof(WtvStream));
+        if (!wst)
+            return NULL;
+        st = av_new_stream(s, sid);
+        if (!st)
+            return NULL;
+        st->priv_data = wst;
+    }
+    st->codec->codec_type = codec_type;
+    st->need_parsing      = AVSTREAM_PARSE_FULL;
+    av_set_pts_info(st, 64, 1, 10000000);
+    return st;
+}
+
+/**
+ * parse Media Type structure and populate stream
+ * @param st         Stream, or NULL to create new stream
+ * @param mediatype  Mediatype GUID
+ * @param subtype    Subtype GUID
+ * @param formattype Format GUID
+ * @param size       Size of format buffer
+ * @return NULL on error
+ */
+static AVStream * parse_media_type(AVFormatContext *s, AVStream *st, int sid,
+                                   ff_asf_guid mediatype, ff_asf_guid subtype,
+                                   ff_asf_guid formattype, int size)
+{
+    WtvContext *wtv = s->priv_data;
+    AVIOContext *pb = wtv->pb;
+    if (!ff_guidcmp(subtype, mediasubtype_cpfilters_processed) &&
+        !ff_guidcmp(formattype, format_cpfilters_processed)) {
+        ff_asf_guid actual_subtype;
+        ff_asf_guid actual_formattype;
+
+        if (size < 32) {
+            av_log(s, AV_LOG_WARNING, "format buffer size underflow\n");
+            avio_skip(pb, size);
+            return NULL;
+        }
+
+        avio_skip(pb, size - 32);
+        ff_get_guid(pb, &actual_subtype);
+        ff_get_guid(pb, &actual_formattype);
+        avio_seek(pb, -size, SEEK_CUR);
+
+        st = parse_media_type(s, st, sid, mediatype, actual_subtype, actual_formattype, size - 32);
+        avio_skip(pb, 32);
+        return st;
+    } else if (!ff_guidcmp(mediatype, mediatype_audio)) {
+        st = new_stream(s, st, sid, AVMEDIA_TYPE_AUDIO);
+        if (!st)
+            return NULL;
+        if (!ff_guidcmp(formattype, format_waveformatex)) {
+            int ret = ff_get_wav_header(pb, st->codec, size);
+            if (ret < 0)
+                return NULL;
+        } else {
+            if (ff_guidcmp(formattype, format_none))
+                av_log(s, AV_LOG_WARNING, "unknown formattype:"PRI_GUID"\n", ARG_GUID(formattype));
+            avio_skip(pb, size);
+        }
+
+        if (!memcmp(subtype + 4, (const uint8_t[]){MEDIASUBTYPE_BASE_GUID}, 12)) {
+            st->codec->codec_id = ff_wav_codec_get_id(AV_RL32(subtype), st->codec->bits_per_coded_sample);
+        } else if (!ff_guidcmp(subtype, mediasubtype_mpeg1payload)) {
+            if (st->codec->extradata && st->codec->extradata_size >= 22)
+                parse_mpeg1waveformatex(st);
+            else
+                av_log(s, AV_LOG_WARNING, "MPEG1WAVEFORMATEX underflow\n");
+        } else {
+            st->codec->codec_id = ff_codec_guid_get_id(audio_guids, subtype);
+            if (st->codec->codec_id == CODEC_ID_NONE)
+                av_log(s, AV_LOG_WARNING, "unknown subtype:"PRI_GUID"\n", ARG_GUID(subtype));
+        }
+        return st;
+    } else if (!ff_guidcmp(mediatype, mediatype_video)) {
+        st = new_stream(s, st, sid, AVMEDIA_TYPE_VIDEO);
+        if (!st)
+            return NULL;
+        if (!ff_guidcmp(formattype, format_videoinfo2)) {
+            int consumed = parse_videoinfoheader2(s, st);
+            avio_skip(pb, FFMAX(size - consumed, 0));
+        } else if (!ff_guidcmp(formattype, format_mpeg2_video)) {
+            int consumed = parse_videoinfoheader2(s, st);
+            avio_skip(pb, FFMAX(size - consumed, 0));
+        } else {
+            if (ff_guidcmp(formattype, format_none))
+                av_log(s, AV_LOG_WARNING, "unknown formattype:"PRI_GUID"\n", ARG_GUID(formattype));
+            avio_skip(pb, size);
+        }
+
+        if (!memcmp(subtype + 4, (const uint8_t[]){MEDIASUBTYPE_BASE_GUID}, 12)) {
+            st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags, AV_RL32(subtype));
+        } else {
+            st->codec->codec_id = ff_codec_guid_get_id(video_guids, subtype);
+        }
+        if (st->codec->codec_id == CODEC_ID_NONE)
+            av_log(s, AV_LOG_WARNING, "unknown subtype:"PRI_GUID"\n", ARG_GUID(subtype));
+        return st;
+    } else if (!ff_guidcmp(mediatype, mediatype_mpeg2_pes) &&
+               !ff_guidcmp(subtype, mediasubtype_dvb_subtitle)) {
+        st = new_stream(s, st, sid, AVMEDIA_TYPE_SUBTITLE);
+        if (!st)
+            return NULL;
+        if (ff_guidcmp(formattype, format_none))
+            av_log(s, AV_LOG_WARNING, "unknown formattype:"PRI_GUID"\n", ARG_GUID(formattype));
+        avio_skip(pb, size);
+        st->codec->codec_id = CODEC_ID_DVB_SUBTITLE;
+        return st;
+    } else if (!ff_guidcmp(mediatype, mediatype_mstvcaption) &&
+               (!ff_guidcmp(subtype, mediasubtype_teletext) || !ff_guidcmp(subtype, mediasubtype_dtvccdata))) {
+        st = new_stream(s, st, sid, AVMEDIA_TYPE_SUBTITLE);
+        if (!st)
+            return NULL;
+        if (ff_guidcmp(formattype, format_none))
+            av_log(s, AV_LOG_WARNING, "unknown formattype:"PRI_GUID"\n", ARG_GUID(formattype));
+        avio_skip(pb, size);
+        st->codec->codec_id   = CODEC_ID_DVB_TELETEXT;
+        return st;
+    } else if (!ff_guidcmp(mediatype, mediatype_mpeg2_sections) &&
+               !ff_guidcmp(subtype, mediasubtype_mpeg2_sections)) {
+        if (ff_guidcmp(formattype, format_none))
+            av_log(s, AV_LOG_WARNING, "unknown formattype:"PRI_GUID"\n", ARG_GUID(formattype));
+        avio_skip(pb, size);
+        return NULL;
+    }
+
+    av_log(s, AV_LOG_WARNING, "unknown media type, mediatype:"PRI_GUID
+                              ", subtype:"PRI_GUID", formattype:"PRI_GUID"\n",
+                              ARG_GUID(mediatype), ARG_GUID(subtype), ARG_GUID(formattype));
+    avio_skip(pb, size);
+    return NULL;
+}
+
+enum {
+    SEEK_TO_DATA = 0,
+    SEEK_TO_PTS,
+};
+
+/**
+ * Parse WTV chunks
+ * @param mode SEEK_TO_DATA or SEEK_TO_PTS
+ * @param seekts timestamp
+ * @param[out] len Length of data chunk
+ * @return stream index of data chunk, or <0 on error
+ */
+static int parse_chunks(AVFormatContext *s, int mode, int64_t seekts, int *len_ptr)
+{
+    WtvContext *wtv = s->priv_data;
+    AVIOContext *pb = wtv->pb;
+    while (!pb->eof_reached) {
+        ff_asf_guid g;
+        int len, sid, consumed;
+
+        ff_get_guid(pb, &g);
+        len = avio_rl32(pb);
+        if (len < 32)
+            break;
+        sid = avio_rl32(pb) & 0x7FFF;
+        avio_skip(pb, 8);
+        consumed = 32;
+
+        if (!ff_guidcmp(g, stream_guid)) {
+            if (ff_find_stream_index(s, sid) < 0) {
+                ff_asf_guid mediatype, subtype, formattype;
+                int size;
+                avio_skip(pb, 28);
+                ff_get_guid(pb, &mediatype);
+                ff_get_guid(pb, &subtype);
+                avio_skip(pb, 12);
+                ff_get_guid(pb, &formattype);
+                size = avio_rl32(pb);
+                parse_media_type(s, 0, sid, mediatype, subtype, formattype, size);
+                consumed += 92 + size;
+            }
+        } else if (!ff_guidcmp(g, stream2_guid)) {
+            int stream_index = ff_find_stream_index(s, sid);
+            if (stream_index >= 0 && !((WtvStream*)s->streams[stream_index]->priv_data)->seen_data) {
+                ff_asf_guid mediatype, subtype, formattype;
+                int size;
+                avio_skip(pb, 12);
+                ff_get_guid(pb, &mediatype);
+                ff_get_guid(pb, &subtype);
+                avio_skip(pb, 12);
+                ff_get_guid(pb, &formattype);
+                size = avio_rl32(pb);
+                parse_media_type(s, s->streams[stream_index], sid, mediatype, subtype, formattype, size);
+                consumed += 76 + size;
+            }
+        } else if (!ff_guidcmp(g, EVENTID_AudioDescriptorSpanningEvent) ||
+                   !ff_guidcmp(g, EVENTID_CtxADescriptorSpanningEvent) ||
+                   !ff_guidcmp(g, EVENTID_CSDescriptorSpanningEvent) ||
+                   !ff_guidcmp(g, EVENTID_StreamIDSpanningEvent) ||
+                   !ff_guidcmp(g, EVENTID_SubtitleSpanningEvent) ||
+                   !ff_guidcmp(g, EVENTID_TeletextSpanningEvent)) {
+            int stream_index = ff_find_stream_index(s, sid);
+            if (stream_index >= 0) {
+                AVStream *st = s->streams[stream_index];
+                uint8_t buf[258];
+                const uint8_t *pbuf = buf;
+                int buf_size;
+
+                avio_skip(pb, 8);
+                consumed += 8;
+                if (!ff_guidcmp(g, EVENTID_CtxADescriptorSpanningEvent) ||
+                    !ff_guidcmp(g, EVENTID_CSDescriptorSpanningEvent)) {
+                    avio_skip(pb, 6);
+                    consumed += 6;
+                }
+
+                buf_size = FFMIN(len - consumed, sizeof(buf));
+                avio_read(pb, buf, buf_size);
+                consumed += buf_size;
+                ff_parse_mpeg2_descriptor(s, st, 0, &pbuf, buf + buf_size, 0, 0, 0, 0);
+            }
+        } else if (!ff_guidcmp(g, EVENTID_AudioTypeSpanningEvent)) {
+            int stream_index = ff_find_stream_index(s, sid);
+            if (stream_index >= 0) {
+                AVStream *st = s->streams[stream_index];
+                int audio_type;
+                avio_skip(pb, 8);
+                audio_type = avio_r8(pb);
+                if (audio_type == 2)
+                    st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
+                else if (audio_type == 3)
+                    st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED;
+                consumed += 9;
+            }
+        } else if (!ff_guidcmp(g, EVENTID_DVBScramblingControlSpanningEvent)) {
+            int stream_index = ff_find_stream_index(s, sid);
+            if (stream_index >= 0) {
+                avio_skip(pb, 12);
+                if (avio_rl32(pb))
+                    av_log(s, AV_LOG_WARNING, "DVB scrambled stream detected (st:%d), decoding will likely fail\n", stream_index);
+                consumed += 16;
+            }
+        } else if (!ff_guidcmp(g, EVENTID_LanguageSpanningEvent)) {
+            int stream_index = ff_find_stream_index(s, sid);
+            if (stream_index >= 0) {
+                AVStream *st = s->streams[stream_index];
+                uint8_t language[4];
+                avio_skip(pb, 12);
+                avio_read(pb, language, 3);
+                if (language[0]) {
+                    language[3] = 0;
+                    av_metadata_set2(&st->metadata, "language", language, 0);
+                    if (!strcmp(language, "nar") || !strcmp(language, "NAR"))
+                        st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED;
+                }
+                consumed += 15;
+            }
+        } else if (!ff_guidcmp(g, timestamp_guid)) {
+            int stream_index = ff_find_stream_index(s, sid);
+            if (stream_index >= 0) {
+                avio_skip(pb, 8);
+                wtv->pts = avio_rl64(pb);
+                consumed += 16;
+                if (wtv->pts == -1)
+                    wtv->pts = AV_NOPTS_VALUE;
+                else {
+                    wtv->last_valid_pts = wtv->pts;
+                    if (wtv->epoch == AV_NOPTS_VALUE || wtv->pts < wtv->epoch)
+                        wtv->epoch = wtv->pts;
+                if (mode == SEEK_TO_PTS && wtv->pts >= seekts) {
+#define WTV_PAD8(x) (((x) + 7) & ~7)
+                    avio_skip(pb, WTV_PAD8(len) - consumed);
+                    return 0;
+                }
+                }
+            }
+        } else if (!ff_guidcmp(g, data_guid)) {
+            int stream_index = ff_find_stream_index(s, sid);
+            if (mode == SEEK_TO_DATA && stream_index >= 0 && len > 32) {
+                WtvStream *wst = s->streams[stream_index]->priv_data;
+                wst->seen_data = 1;
+                if (len_ptr) {
+                    *len_ptr = len;
+                }
+                return stream_index;
+            }
+        } else if (
+            !ff_guidcmp(g, /* DSATTRIB_CAPTURE_STREAMTIME */ (const ff_asf_guid){0x14,0x56,0x1A,0x0C,0xCD,0x30,0x40,0x4F,0xBC,0xBF,0xD0,0x3E,0x52,0x30,0x62,0x07}) ||
+            !ff_guidcmp(g, /* DSATTRIB_PicSampleSeq */ (const ff_asf_guid){0x02,0xAE,0x5B,0x2F,0x8F,0x7B,0x60,0x4F,0x82,0xD6,0xE4,0xEA,0x2F,0x1F,0x4C,0x99}) ||
+            !ff_guidcmp(g, /* DSATTRIB_TRANSPORT_PROPERTIES */ (const ff_asf_guid){0x12,0xF6,0x22,0xB6,0xAD,0x47,0x71,0x46,0xAD,0x6C,0x05,0xA9,0x8E,0x65,0xDE,0x3A}) ||
+            !ff_guidcmp(g, /* dvr_ms_vid_frame_rep_data */ (const ff_asf_guid){0xCC,0x32,0x64,0xDD,0x29,0xE2,0xDB,0x40,0x80,0xF6,0xD2,0x63,0x28,0xD2,0x76,0x1F}) ||
+            !ff_guidcmp(g, /* EVENTID_ChannelChangeSpanningEvent */ (const ff_asf_guid){0xE5,0xC5,0x67,0x90,0x5C,0x4C,0x05,0x42,0x86,0xC8,0x7A,0xFE,0x20,0xFE,0x1E,0xFA}) ||
+            !ff_guidcmp(g, /* EVENTID_ChannelInfoSpanningEvent */ (const ff_asf_guid){0x80,0x6D,0xF3,0x41,0x32,0x41,0xC2,0x4C,0xB1,0x21,0x01,0xA4,0x32,0x19,0xD8,0x1B}) ||
+            !ff_guidcmp(g, /* EVENTID_ChannelTypeSpanningEvent */ (const ff_asf_guid){0x51,0x1D,0xAB,0x72,0xD2,0x87,0x9B,0x48,0xBA,0x11,0x0E,0x08,0xDC,0x21,0x02,0x43}) ||
+            !ff_guidcmp(g, /* EVENTID_PIDListSpanningEvent */ (const ff_asf_guid){0x65,0x8F,0xFC,0x47,0xBB,0xE2,0x34,0x46,0x9C,0xEF,0xFD,0xBF,0xE6,0x26,0x1D,0x5C}) ||
+            !ff_guidcmp(g, /* EVENTID_SignalAndServiceStatusSpanningEvent */ (const ff_asf_guid){0xCB,0xC5,0x68,0x80,0x04,0x3C,0x2B,0x49,0xB4,0x7D,0x03,0x08,0x82,0x0D,0xCE,0x51}) ||
+            !ff_guidcmp(g, /* EVENTID_StreamTypeSpanningEvent */ (const ff_asf_guid){0xBC,0x2E,0xAF,0x82,0xA6,0x30,0x64,0x42,0xA8,0x0B,0xAD,0x2E,0x13,0x72,0xAC,0x60}) ||
+            !ff_guidcmp(g, (const ff_asf_guid){0x1E,0xBE,0xC3,0xC5,0x43,0x92,0xDC,0x11,0x85,0xE5,0x00,0x12,0x3F,0x6F,0x73,0xB9}) ||
+            !ff_guidcmp(g, (const ff_asf_guid){0x3B,0x86,0xA2,0xB1,0xEB,0x1E,0xC3,0x44,0x8C,0x88,0x1C,0xA3,0xFF,0xE3,0xE7,0x6A}) ||
+            !ff_guidcmp(g, (const ff_asf_guid){0x4E,0x7F,0x4C,0x5B,0xC4,0xD0,0x38,0x4B,0xA8,0x3E,0x21,0x7F,0x7B,0xBF,0x52,0xE7}) ||
+            !ff_guidcmp(g, (const ff_asf_guid){0x63,0x36,0xEB,0xFE,0xA1,0x7E,0xD9,0x11,0x83,0x08,0x00,0x07,0xE9,0x5E,0xAD,0x8D}) ||
+            !ff_guidcmp(g, (const ff_asf_guid){0x70,0xE9,0xF1,0xF8,0x89,0xA4,0x4C,0x4D,0x83,0x73,0xB8,0x12,0xE0,0xD5,0xF8,0x1E}) ||
+            !ff_guidcmp(g, (const ff_asf_guid){0x96,0xC3,0xD2,0xC2,0x7E,0x9A,0xDA,0x11,0x8B,0xF7,0x00,0x07,0xE9,0x5E,0xAD,0x8D}) ||
+            !ff_guidcmp(g, (const ff_asf_guid){0x97,0xC3,0xD2,0xC2,0x7E,0x9A,0xDA,0x11,0x8B,0xF7,0x00,0x07,0xE9,0x5E,0xAD,0x8D}) ||
+            !ff_guidcmp(g, (const ff_asf_guid){0xA1,0xC3,0xD2,0xC2,0x7E,0x9A,0xDA,0x11,0x8B,0xF7,0x00,0x07,0xE9,0x5E,0xAD,0x8D})) {
+            //ignore known guids
+        } else
+            av_log(s, AV_LOG_WARNING, "unsupported chunk:"PRI_GUID"\n", ARG_GUID(g));
+
+        avio_skip(pb, WTV_PAD8(len) - consumed);
+    }
+    return AVERROR_EOF;
+}
+
+/* declare utf16le strings */
+#define _ , 0,
+static const uint8_t timeline_le16[] =
+    {'t'_'i'_'m'_'e'_'l'_'i'_'n'_'e', 0};
+static const uint8_t table_0_entries_legacy_attrib_le16[] =
+    {'t'_'a'_'b'_'l'_'e'_'.'_'0'_'.'_'e'_'n'_'t'_'r'_'i'_'e'_'s'_'.'_'l'_'e'_'g'_'a'_'c'_'y'_'_'_'a'_'t'_'t'_'r'_'i'_'b', 0};
+static const uint8_t table_0_entries_time_le16[] =
+    {'t'_'a'_'b'_'l'_'e'_'.'_'0'_'.'_'e'_'n'_'t'_'r'_'i'_'e'_'s'_'.'_'t'_'i'_'m'_'e', 0};
+static const uint8_t timeline_table_0_entries_Events_le16[] =
+    {'t'_'i'_'m'_'e'_'l'_'i'_'n'_'e'_'.'_'t'_'a'_'b'_'l'_'e'_'.'_'0'_'.'_'e'_'n'_'t'_'r'_'i'_'e'_'s'_'.'_'E'_'v'_'e'_'n'_'t'_'s', 0};
+#undef _
+
+static int read_header(AVFormatContext *s, AVFormatParameters *ap)
+{
+    WtvContext *wtv = s->priv_data;
+    int root_sector, root_size;
+    uint8_t root[WTV_SECTOR_SIZE];
+    AVIOContext *pb;
+    int64_t timeline_pos;
+    int ret;
+
+    wtv->epoch          =
+    wtv->pts            =
+    wtv->last_valid_pts = AV_NOPTS_VALUE;
+
+    /* read root directory sector */
+    avio_skip(s->pb, 0x30);
+    root_size = avio_rl32(s->pb);
+    if (root_size > sizeof(root)) {
+        av_log(s, AV_LOG_ERROR, "root directory size exceeds sector size\n");
+        return AVERROR_INVALIDDATA;
+    }
+    avio_skip(s->pb, 4);
+    root_sector = avio_rl32(s->pb);
+
+    avio_seek(s->pb, root_sector << WTV_SECTOR_BITS, SEEK_SET);
+    root_size = avio_read(s->pb, root, root_size);
+    if (root_size < 0)
+        return AVERROR_INVALIDDATA;
+
+    /* parse chunks up until first data chunk */
+    wtv->pb = wtvfile_open(s, root, root_size, timeline_le16);
+    if (!wtv->pb) {
+        av_log(s, AV_LOG_ERROR, "timeline data missing\n");
+        return AVERROR_INVALIDDATA;
+    }
+
+    ret = parse_chunks(s, SEEK_TO_DATA, 0, 0);
+    if (ret < 0)
+        return ret;
+    avio_seek(wtv->pb, -32, SEEK_CUR);
+
+    timeline_pos = avio_tell(s->pb); // save before opening another file
+
+    /* read metadata */
+    pb = wtvfile_open(s, root, root_size, table_0_entries_legacy_attrib_le16);
+    if (pb) {
+        parse_legacy_attrib(s, pb);
+        wtvfile_close(pb);
+    }
+
+    /* read seek index */
+    if (s->nb_streams) {
+        AVStream *st = s->streams[0];
+        pb = wtvfile_open(s, root, root_size, table_0_entries_time_le16);
+        if (pb) {
+            while(1) {
+                uint64_t timestamp = avio_rl64(pb);
+                uint64_t frame_nb  = avio_rl64(pb);
+                if (pb->eof_reached)
+                    break;
+                ff_add_index_entry(&wtv->index_entries, &wtv->nb_index_entries, &wtv->index_entries_allocated_size,
+                                   0, timestamp, frame_nb, 0, AVINDEX_KEYFRAME);
+            }
+            wtvfile_close(pb);
+
+            if (wtv->nb_index_entries) {
+                pb = wtvfile_open(s, root, root_size, timeline_table_0_entries_Events_le16);
+                if (pb) {
+                    int i;
+                    while (1) {
+                        uint64_t frame_nb = avio_rl64(pb);
+                        uint64_t position = avio_rl64(pb);
+                        if (pb->eof_reached)
+                            break;
+                        for (i = wtv->nb_index_entries - 1; i >= 0; i--) {
+                            AVIndexEntry *e = wtv->index_entries + i;
+                            if (frame_nb > e->size)
+                                break;
+                            if (position > e->pos)
+                                e->pos = position;
+                        }
+                    }
+                    wtvfile_close(pb);
+                    st->duration = wtv->index_entries[wtv->nb_index_entries - 1].timestamp;
+                }
+            }
+        }
+    }
+
+    avio_seek(s->pb, timeline_pos, SEEK_SET);
+    return 0;
+}
+
+static int read_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    WtvContext *wtv = s->priv_data;
+    AVIOContext *pb = wtv->pb;
+    int stream_index, len, ret;
+
+    stream_index = parse_chunks(s, SEEK_TO_DATA, 0, &len);
+    if (stream_index < 0)
+        return stream_index;
+
+    ret = av_get_packet(pb, pkt, len - 32);
+    if (ret < 0)
+        return ret;
+    pkt->stream_index = stream_index;
+    pkt->pts          = wtv->pts;
+    avio_skip(pb, WTV_PAD8(len) - len);
+    return 0;
+}
+
+static int read_seek(AVFormatContext *s, int stream_index,
+                     int64_t ts, int flags)
+{
+    WtvContext *wtv = s->priv_data;
+    AVIOContext *pb = wtv->pb;
+    AVStream *st = s->streams[0];
+    int64_t ts_relative;
+    int i;
+
+    if ((flags & AVSEEK_FLAG_FRAME) || (flags & AVSEEK_FLAG_BYTE))
+        return AVERROR(ENOSYS);
+
+    /* timestamp adjustment is required because wtv->pts values are absolute,
+     * whereas AVIndexEntry->timestamp values are relative to epoch. */
+    ts_relative = ts;
+    if (wtv->epoch != AV_NOPTS_VALUE)
+        ts_relative -= wtv->epoch;
+
+    i = ff_index_search_timestamp(wtv->index_entries, wtv->nb_index_entries, ts_relative, flags);
+    if (i < 0) {
+        if (wtv->last_valid_pts == AV_NOPTS_VALUE || ts < wtv->last_valid_pts)
+            avio_seek(pb, 0, SEEK_SET);
+        else if (st->duration != AV_NOPTS_VALUE && ts_relative > st->duration && wtv->nb_index_entries)
+            avio_seek(pb, wtv->index_entries[wtv->nb_index_entries - 1].pos, SEEK_SET);
+        if (parse_chunks(s, SEEK_TO_PTS, ts, 0) < 0)
+            return AVERROR(ERANGE);
+        return 0;
+    }
+    wtv->pts = wtv->index_entries[i].timestamp;
+    if (wtv->epoch != AV_NOPTS_VALUE)
+        wtv->pts += wtv->epoch;
+    wtv->last_valid_pts = wtv->pts;
+    avio_seek(pb, wtv->index_entries[i].pos, SEEK_SET);
+    return 0;
+}
+
+static int read_close(AVFormatContext *s)
+{
+    WtvContext *wtv = s->priv_data;
+    wtvfile_close(wtv->pb);
+    return 0;
+}
+
+AVInputFormat ff_wtv_demuxer = {
+    .name           = "wtv",
+    .long_name      = NULL_IF_CONFIG_SMALL("Windows Television (WTV)"),
+    .priv_data_size = sizeof(WtvContext),
+    .read_probe     = read_probe,
+    .read_header    = read_header,
+    .read_packet    = read_packet,
+    .read_seek      = read_seek,
+    .read_close     = read_close,
+    .flags          = AVFMT_SHOW_IDS,
+};
diff --git a/libavformat/wv.c b/libavformat/wv.c
index 03b864b..7106735 100644
--- a/libavformat/wv.c
+++ b/libavformat/wv.c
@@ -1,24 +1,25 @@
 /*
  * WavPack demuxer
- * Copyright (c) 2006 Konstantin Shishkov
+ * Copyright (c) 2006,2011 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/audioconvert.h"
 #include "libavutil/intreadwrite.h"
 #include "avformat.h"
 #include "apetag.h"
@@ -29,6 +30,10 @@
 
 #define WV_EXTRA_SIZE 12
 
+#define WV_START_BLOCK  0x0800
+#define WV_END_BLOCK    0x1000
+#define WV_SINGLE_BLOCK (WV_START_BLOCK | WV_END_BLOCK)
+
 enum WV_FLAGS{
     WV_MONO   = 0x0004,
     WV_HYBRID = 0x0008,
@@ -51,7 +56,9 @@ static const int wv_rates[16] = {
 typedef struct{
     uint32_t blksize, flags;
     int rate, chan, bpp;
+    uint32_t chmask;
     uint32_t samples, soff;
+    int multichannel;
     int block_parsed;
     uint8_t extra[WV_EXTRA_SIZE];
     int64_t pos;
@@ -69,73 +76,117 @@ static int wv_probe(AVProbeData *p)
         return 0;
 }
 
-static int wv_read_block_header(AVFormatContext *ctx, ByteIOContext *pb)
+static int wv_read_block_header(AVFormatContext *ctx, AVIOContext *pb, int append)
 {
     WVContext *wc = ctx->priv_data;
     uint32_t tag, ver;
     int size;
     int rate, bpp, chan;
+    uint32_t chmask;
 
-    wc->pos = url_ftell(pb);
-    tag = get_le32(pb);
-    if (tag != MKTAG('w', 'v', 'p', 'k'))
-        return -1;
-    size = get_le32(pb);
-    if(size < 24 || size > WV_BLOCK_LIMIT){
-        av_log(ctx, AV_LOG_ERROR, "Incorrect block size %i\n", size);
-        return -1;
-    }
-    wc->blksize = size;
-    ver = get_le16(pb);
-    if(ver < 0x402 || ver > 0x410){
-        av_log(ctx, AV_LOG_ERROR, "Unsupported version %03X\n", ver);
-        return -1;
+    wc->pos = avio_tell(pb);
+    if(!append){
+        tag = avio_rl32(pb);
+        if (tag != MKTAG('w', 'v', 'p', 'k'))
+            return -1;
+        size = avio_rl32(pb);
+        if(size < 24 || size > WV_BLOCK_LIMIT){
+            av_log(ctx, AV_LOG_ERROR, "Incorrect block size %i\n", size);
+            return -1;
+        }
+        wc->blksize = size;
+        ver = avio_rl16(pb);
+        if(ver < 0x402 || ver > 0x410){
+            av_log(ctx, AV_LOG_ERROR, "Unsupported version %03X\n", ver);
+            return -1;
+        }
+        avio_r8(pb); // track no
+        avio_r8(pb); // track sub index
+        wc->samples = avio_rl32(pb); // total samples in file
+        wc->soff = avio_rl32(pb); // offset in samples of current block
+        avio_read(pb, wc->extra, WV_EXTRA_SIZE);
+    }else{
+        size = wc->blksize;
     }
-    get_byte(pb); // track no
-    get_byte(pb); // track sub index
-    wc->samples = get_le32(pb); // total samples in file
-    wc->soff = get_le32(pb); // offset in samples of current block
-    get_buffer(pb, wc->extra, WV_EXTRA_SIZE);
     wc->flags = AV_RL32(wc->extra + 4);
     //parse flags
     bpp = ((wc->flags & 3) + 1) << 3;
     chan = 1 + !(wc->flags & WV_MONO);
+    chmask = wc->flags & WV_MONO ? AV_CH_LAYOUT_MONO : AV_CH_LAYOUT_STEREO;
     rate = wv_rates[(wc->flags >> 23) & 0xF];
-    if(rate == -1 && !wc->block_parsed){
-        int64_t block_end = url_ftell(pb) + wc->blksize - 24;
-        if(url_is_streamed(pb)){
-            av_log(ctx, AV_LOG_ERROR, "Cannot determine custom sampling rate\n");
+    wc->multichannel = !!((wc->flags & WV_SINGLE_BLOCK) != WV_SINGLE_BLOCK);
+    if(wc->multichannel){
+        chan = wc->chan;
+        chmask = wc->chmask;
+    }
+    if((rate == -1 || !chan) && !wc->block_parsed){
+        int64_t block_end = avio_tell(pb) + wc->blksize - 24;
+        if(!pb->seekable){
+            av_log(ctx, AV_LOG_ERROR, "Cannot determine additional parameters\n");
             return -1;
         }
-        while(url_ftell(pb) < block_end){
+        while(avio_tell(pb) < block_end){
             int id, size;
-            id = get_byte(pb);
-            size = (id & 0x80) ? get_le24(pb) : get_byte(pb);
+            id = avio_r8(pb);
+            size = (id & 0x80) ? avio_rl24(pb) : avio_r8(pb);
             size <<= 1;
             if(id&0x40)
                 size--;
-            if((id&0x3F) == 0x27){
-                rate = get_le24(pb);
+            switch(id&0x3F){
+            case 0xD:
+                if(size <= 1){
+                    av_log(ctx, AV_LOG_ERROR, "Insufficient channel information\n");
+                    return -1;
+                }
+                chan = avio_r8(pb);
+                switch(size - 2){
+                case 0:
+                    chmask = avio_r8(pb);
+                    break;
+                case 1:
+                    chmask = avio_rl16(pb);
+                    break;
+                case 2:
+                    chmask = avio_rl24(pb);
+                    break;
+                case 3:
+                    chmask = avio_rl32(pb);
+                    break;
+                case 5:
+                    avio_skip(pb, 1);
+                    chan |= (avio_r8(pb) & 0xF) << 8;
+                    chmask = avio_rl24(pb);
+                    break;
+                default:
+                    av_log(ctx, AV_LOG_ERROR, "Invalid channel info size %d\n", size);
+                    return -1;
+                }
+                break;
+            case 0x27:
+                rate = avio_rl24(pb);
                 break;
-            }else{
-                url_fskip(pb, size);
+            default:
+                avio_skip(pb, size);
             }
+            if(id&0x40)
+                avio_skip(pb, 1);
         }
         if(rate == -1){
             av_log(ctx, AV_LOG_ERROR, "Cannot determine custom sampling rate\n");
             return -1;
         }
-        url_fseek(pb, block_end - wc->blksize + 24, SEEK_SET);
+        avio_seek(pb, block_end - wc->blksize + 24, SEEK_SET);
     }
     if(!wc->bpp) wc->bpp = bpp;
     if(!wc->chan) wc->chan = chan;
+    if(!wc->chmask) wc->chmask = chmask;
     if(!wc->rate) wc->rate = rate;
 
     if(wc->flags && bpp != wc->bpp){
         av_log(ctx, AV_LOG_ERROR, "Bits per sample differ, this block: %i, header block: %i\n", bpp, wc->bpp);
         return -1;
     }
-    if(wc->flags && chan != wc->chan){
+    if(wc->flags && !wc->multichannel && chan != wc->chan){
         av_log(ctx, AV_LOG_ERROR, "Channels differ, this block: %i, header block: %i\n", chan, wc->chan);
         return -1;
     }
@@ -150,12 +201,12 @@ static int wv_read_block_header(AVFormatContext *ctx, ByteIOContext *pb)
 static int wv_read_header(AVFormatContext *s,
                           AVFormatParameters *ap)
 {
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     WVContext *wc = s->priv_data;
     AVStream *st;
 
     wc->block_parsed = 0;
-    if(wv_read_block_header(s, pb) < 0)
+    if(wv_read_block_header(s, pb, 0) < 0)
         return -1;
 
     /* now we are ready: build format streams */
@@ -165,18 +216,19 @@ static int wv_read_header(AVFormatContext *s,
     st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
     st->codec->codec_id = CODEC_ID_WAVPACK;
     st->codec->channels = wc->chan;
+    st->codec->channel_layout = wc->chmask;
     st->codec->sample_rate = wc->rate;
     st->codec->bits_per_coded_sample = wc->bpp;
     av_set_pts_info(st, 64, 1, wc->rate);
     st->start_time = 0;
     st->duration = wc->samples;
 
-    if(!url_is_streamed(s->pb)) {
-        int64_t cur = url_ftell(s->pb);
+    if(s->pb->seekable) {
+        int64_t cur = avio_tell(s->pb);
         ff_ape_parse_tag(s);
         if(!av_metadata_get(s->metadata, "", NULL, AV_METADATA_IGNORE_SUFFIX))
             ff_id3v1_read(s);
-        url_fseek(s->pb, cur, SEEK_SET);
+        avio_seek(s->pb, cur, SEEK_SET);
     }
 
     return 0;
@@ -187,25 +239,70 @@ static int wv_read_packet(AVFormatContext *s,
 {
     WVContext *wc = s->priv_data;
     int ret;
+    int size, ver, off;
 
-    if (url_feof(s->pb))
+    if (s->pb->eof_reached)
         return AVERROR(EIO);
     if(wc->block_parsed){
-        if(wv_read_block_header(s, s->pb) < 0)
+        if(wv_read_block_header(s, s->pb, 0) < 0)
             return -1;
     }
 
-    if(av_new_packet(pkt, wc->blksize + WV_EXTRA_SIZE) < 0)
+    off = wc->multichannel ? 4 : 0;
+    if(av_new_packet(pkt, wc->blksize + WV_EXTRA_SIZE + off) < 0)
         return AVERROR(ENOMEM);
-    memcpy(pkt->data, wc->extra, WV_EXTRA_SIZE);
-    ret = get_buffer(s->pb, pkt->data + WV_EXTRA_SIZE, wc->blksize);
+    if(wc->multichannel)
+        AV_WL32(pkt->data, wc->blksize + WV_EXTRA_SIZE + 12);
+    memcpy(pkt->data + off, wc->extra, WV_EXTRA_SIZE);
+    ret = avio_read(s->pb, pkt->data + WV_EXTRA_SIZE + off, wc->blksize);
     if(ret != wc->blksize){
         av_free_packet(pkt);
         return AVERROR(EIO);
     }
+    while(!(wc->flags & WV_END_BLOCK)){
+        if(avio_rl32(s->pb) != MKTAG('w', 'v', 'p', 'k')){
+            av_free_packet(pkt);
+            return -1;
+        }
+        if((ret = av_append_packet(s->pb, pkt, 4)) < 0){
+            av_free_packet(pkt);
+            return ret;
+        }
+        size = AV_RL32(pkt->data + pkt->size - 4);
+        if(size < 24 || size > WV_BLOCK_LIMIT){
+            av_free_packet(pkt);
+            av_log(s, AV_LOG_ERROR, "Incorrect block size %d\n", size);
+            return -1;
+        }
+        wc->blksize = size;
+        ver = avio_rl16(s->pb);
+        if(ver < 0x402 || ver > 0x410){
+            av_free_packet(pkt);
+            av_log(s, AV_LOG_ERROR, "Unsupported version %03X\n", ver);
+            return -1;
+        }
+        avio_r8(s->pb); // track no
+        avio_r8(s->pb); // track sub index
+        wc->samples = avio_rl32(s->pb); // total samples in file
+        wc->soff = avio_rl32(s->pb); // offset in samples of current block
+        if((ret = av_append_packet(s->pb, pkt, WV_EXTRA_SIZE)) < 0){
+            av_free_packet(pkt);
+            return ret;
+        }
+        memcpy(wc->extra, pkt->data + pkt->size - WV_EXTRA_SIZE, WV_EXTRA_SIZE);
+
+        if(wv_read_block_header(s, s->pb, 1) < 0){
+            av_free_packet(pkt);
+            return -1;
+        }
+        ret = av_append_packet(s->pb, pkt, wc->blksize);
+        if(ret < 0){
+            av_free_packet(pkt);
+            return ret;
+        }
+    }
     pkt->stream_index = 0;
     wc->block_parsed = 1;
-    pkt->size = ret + WV_EXTRA_SIZE;
     pkt->pts = wc->soff;
     av_add_index_entry(s->streams[0], wc->pos, pkt->pts, 0, 0, AVINDEX_KEYFRAME);
     return 0;
@@ -223,18 +320,18 @@ static int wv_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp,
     /* if found, seek there */
     if (index >= 0){
         wc->block_parsed = 1;
-        url_fseek(s->pb, st->index_entries[index].pos, SEEK_SET);
+        avio_seek(s->pb, st->index_entries[index].pos, SEEK_SET);
         return 0;
     }
     /* if timestamp is out of bounds, return error */
     if(timestamp < 0 || timestamp >= s->duration)
         return -1;
 
-    pos = url_ftell(s->pb);
+    pos = avio_tell(s->pb);
     do{
         ret = av_read_frame(s, pkt);
         if (ret < 0){
-            url_fseek(s->pb, pos, SEEK_SET);
+            avio_seek(s->pb, pos, SEEK_SET);
             return -1;
         }
         pts = pkt->pts;
@@ -243,7 +340,7 @@ static int wv_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp,
     return 0;
 }
 
-AVInputFormat wv_demuxer = {
+AVInputFormat ff_wv_demuxer = {
     "wv",
     NULL_IF_CONFIG_SMALL("WavPack"),
     sizeof(WVContext),
diff --git a/libavformat/xa.c b/libavformat/xa.c
index 3a866b9..c3421a3 100644
--- a/libavformat/xa.c
+++ b/libavformat/xa.c
@@ -2,20 +2,20 @@
  * Maxis XA (.xa) File Demuxer
  * Copyright (c) 2008 Robert Marston
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -66,7 +66,7 @@ static int xa_read_header(AVFormatContext *s,
                AVFormatParameters *ap)
 {
     MaxisXADemuxContext *xa = s->priv_data;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVStream *st;
 
     /*Set up the XA Audio Decoder*/
@@ -76,15 +76,15 @@ static int xa_read_header(AVFormatContext *s,
 
     st->codec->codec_type   = AVMEDIA_TYPE_AUDIO;
     st->codec->codec_id     = CODEC_ID_ADPCM_EA_MAXIS_XA;
-    url_fskip(pb, 4);       /* Skip the XA ID */
-    xa->out_size            =  get_le32(pb);
-    url_fskip(pb, 2);       /* Skip the tag */
-    st->codec->channels     = get_le16(pb);
-    st->codec->sample_rate  = get_le32(pb);
+    avio_skip(pb, 4);       /* Skip the XA ID */
+    xa->out_size            =  avio_rl32(pb);
+    avio_skip(pb, 2);       /* Skip the tag */
+    st->codec->channels     = avio_rl16(pb);
+    st->codec->sample_rate  = avio_rl32(pb);
     /* Value in file is average byte rate*/
-    st->codec->bit_rate     = get_le32(pb) * 8;
-    st->codec->block_align  = get_le16(pb);
-    st->codec->bits_per_coded_sample = get_le16(pb);
+    st->codec->bit_rate     = avio_rl32(pb) * 8;
+    st->codec->block_align  = avio_rl16(pb);
+    st->codec->bits_per_coded_sample = avio_rl16(pb);
 
     av_set_pts_info(st, 64, 1, st->codec->sample_rate);
 
@@ -96,7 +96,7 @@ static int xa_read_packet(AVFormatContext *s,
 {
     MaxisXADemuxContext *xa = s->priv_data;
     AVStream *st = s->streams[0];
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     unsigned int packet_size;
     int ret;
 
@@ -118,7 +118,7 @@ static int xa_read_packet(AVFormatContext *s,
     return ret;
 }
 
-AVInputFormat xa_demuxer = {
+AVInputFormat ff_xa_demuxer = {
     "xa",
     NULL_IF_CONFIG_SMALL("Maxis XA File Format"),
     sizeof(MaxisXADemuxContext),
diff --git a/libavformat/xwma.c b/libavformat/xwma.c
new file mode 100644
index 0000000..d18ab48
--- /dev/null
+++ b/libavformat/xwma.c
@@ -0,0 +1,261 @@
+/*
+ * xWMA demuxer
+ * Copyright (c) 2011 Max Horn
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <inttypes.h>
+
+#include "avformat.h"
+#include "riff.h"
+
+/*
+ * Demuxer for xWMA, a Microsoft audio container used by XAudio 2.
+ */
+
+typedef struct {
+    int64_t data_end;
+} XWMAContext;
+
+static int xwma_probe(AVProbeData *p)
+{
+    if (!memcmp(p->buf, "RIFF", 4) && !memcmp(p->buf + 8, "XWMA", 4))
+        return AVPROBE_SCORE_MAX;
+    return 0;
+}
+
+static int xwma_read_header(AVFormatContext *s, AVFormatParameters *ap)
+{
+    int64_t size, av_uninit(data_size);
+    int ret;
+    uint32_t dpds_table_size = 0;
+    uint32_t *dpds_table = 0;
+    unsigned int tag;
+    AVIOContext *pb = s->pb;
+    AVStream *st;
+    XWMAContext *xwma = s->priv_data;
+    int i;
+
+    /* The following code is mostly copied from wav.c, with some
+     * minor alterations.
+     */
+
+    /* check RIFF header */
+    tag = avio_rl32(pb);
+    if (tag != MKTAG('R', 'I', 'F', 'F'))
+        return -1;
+    avio_rl32(pb); /* file size */
+    tag = avio_rl32(pb);
+    if (tag != MKTAG('X', 'W', 'M', 'A'))
+        return -1;
+
+    /* parse fmt header */
+    tag = avio_rl32(pb);
+    if (tag != MKTAG('f', 'm', 't', ' '))
+        return -1;
+    size = avio_rl32(pb);
+    st = av_new_stream(s, 0);
+    if (!st)
+        return AVERROR(ENOMEM);
+
+    ret = ff_get_wav_header(pb, st->codec, size);
+    if (ret < 0)
+        return ret;
+    st->need_parsing = AVSTREAM_PARSE_NONE;
+
+    /* All xWMA files I have seen contained WMAv2 data. If there are files
+     * using WMA Pro or some other codec, then we need to figure out the right
+     * extradata for that. Thus, ask the user for feedback, but try to go on
+     * anyway.
+     */
+    if (st->codec->codec_id != CODEC_ID_WMAV2) {
+        av_log(s, AV_LOG_WARNING, "unexpected codec (tag 0x04%x; id %d)\n",
+                              st->codec->codec_tag, st->codec->codec_id);
+        av_log_ask_for_sample(s, NULL);
+    } else {
+        /* In all xWMA files I have seen, there is no extradata. But the WMA
+         * codecs require extradata, so we provide our own fake extradata.
+         *
+         * First, check that there really was no extradata in the header. If
+         * there was, then try to use it, after asking the user to provide a
+         * sample of this unusual file.
+         */
+        if (st->codec->extradata_size != 0) {
+            /* Surprise, surprise: We *did* get some extradata. No idea
+             * if it will work, but just go on and try it, after asking
+             * the user for a sample.
+             */
+            av_log(s, AV_LOG_WARNING, "unexpected extradata (%d bytes)\n",
+                                  st->codec->extradata_size);
+            av_log_ask_for_sample(s, NULL);
+        } else {
+            st->codec->extradata_size = 6;
+            st->codec->extradata      = av_mallocz(6 + FF_INPUT_BUFFER_PADDING_SIZE);
+            if (!st->codec->extradata)
+                return AVERROR(ENOMEM);
+
+            /* setup extradata with our experimentally obtained value */
+            st->codec->extradata[4] = 31;
+        }
+    }
+
+    /* set the sample rate */
+    av_set_pts_info(st, 64, 1, st->codec->sample_rate);
+
+    /* parse the remaining RIFF chunks */
+    for (;;) {
+        if (pb->eof_reached)
+            return -1;
+        /* read next chunk tag */
+        tag = avio_rl32(pb);
+        size = avio_rl32(pb);
+        if (tag == MKTAG('d', 'a', 't', 'a')) {
+            /* We assume that the data chunk comes last. */
+            break;
+        } else if (tag == MKTAG('d','p','d','s')) {
+            /* Quoting the MSDN xWMA docs on the dpds chunk: "Contains the
+             * decoded packet cumulative data size array, each element is the
+             * number of bytes accumulated after the corresponding xWMA packet
+             * is decoded in order."
+             *
+             * Each packet has size equal to st->codec->block_align, which in
+             * all cases I saw so far was always 2230. Thus, we can use the
+             * dpds data to compute a seeking index.
+             */
+
+            /* Error out if there is more than one dpds chunk. */
+            if (dpds_table) {
+                av_log(s, AV_LOG_ERROR, "two dpds chunks present\n");
+                return -1;
+            }
+
+            /* Compute the number of entries in the dpds chunk. */
+            if (size & 3) {  /* Size should be divisible by four */
+                av_log(s, AV_LOG_WARNING,
+                       "dpds chunk size %"PRId64" not divisible by 4\n", size);
+            }
+            dpds_table_size = size / 4;
+            if (dpds_table_size == 0 || dpds_table_size >= INT_MAX / 4) {
+                av_log(s, AV_LOG_ERROR,
+                       "dpds chunk size %"PRId64" invalid\n", size);
+                return -1;
+            }
+
+            /* Allocate some temporary storage to keep the dpds data around.
+             * for processing later on.
+             */
+            dpds_table = av_malloc(dpds_table_size * sizeof(uint32_t));
+            if (!dpds_table) {
+                return AVERROR(ENOMEM);
+            }
+
+            for (i = 0; i < dpds_table_size; ++i) {
+                dpds_table[i] = avio_rl32(pb);
+                size -= 4;
+            }
+        }
+        avio_skip(pb, size);
+    }
+
+    /* Determine overall data length */
+    if (size < 0)
+        return -1;
+    if (!size) {
+        xwma->data_end = INT64_MAX;
+    } else
+        xwma->data_end = avio_tell(pb) + size;
+
+
+    if (dpds_table && dpds_table_size) {
+        int64_t cur_pos;
+        const uint32_t bytes_per_sample
+                = (st->codec->channels * st->codec->bits_per_coded_sample) >> 3;
+
+        /* Estimate the duration from the total number of output bytes. */
+        const uint64_t total_decoded_bytes = dpds_table[dpds_table_size - 1];
+        st->duration = total_decoded_bytes / bytes_per_sample;
+
+        /* Use the dpds data to build a seek table.  We can only do this after
+         * we know the offset to the data chunk, as we need that to determine
+         * the actual offset to each input block.
+         * Note: If we allowed ourselves to assume that the data chunk always
+         * follows immediately after the dpds block, we could of course guess
+         * the data block's start offset already while reading the dpds chunk.
+         * I decided against that, just in case other chunks ever are
+         * discovered.
+         */
+        cur_pos = avio_tell(pb);
+        for (i = 0; i < dpds_table_size; ++i) {
+            /* From the number of output bytes that would accumulate in the
+             * output buffer after decoding the first (i+1) packets, we compute
+             * an offset / timestamp pair.
+             */
+            av_add_index_entry(st,
+                               cur_pos + (i+1) * st->codec->block_align, /* pos */
+                               dpds_table[i] / bytes_per_sample,         /* timestamp */
+                               st->codec->block_align,                   /* size */
+                               0,                                        /* duration */
+                               AVINDEX_KEYFRAME);
+        }
+    } else if (st->codec->bit_rate) {
+        /* No dpds chunk was present (or only an empty one), so estimate
+         * the total duration using the average bits per sample and the
+         * total data length.
+         */
+        st->duration = (size<<3) * st->codec->sample_rate / st->codec->bit_rate;
+    }
+
+    av_free(dpds_table);
+
+    return 0;
+}
+
+static int xwma_read_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    int ret, size;
+    int64_t left;
+    AVStream *st;
+    XWMAContext *xwma = s->priv_data;
+
+    st = s->streams[0];
+
+    left = xwma->data_end - avio_tell(s->pb);
+    if (left <= 0) {
+        return AVERROR_EOF;
+    }
+
+    /* read a single block; the default block size is 2230. */
+    size = (st->codec->block_align > 1) ? st->codec->block_align : 2230;
+    size = FFMIN(size, left);
+
+    ret  = av_get_packet(s->pb, pkt, size);
+    if (ret < 0)
+        return ret;
+
+    pkt->stream_index = 0;
+    return ret;
+}
+
+AVInputFormat ff_xwma_demuxer = {
+    "xwma",
+    NULL_IF_CONFIG_SMALL("Microsoft xWMA"),
+    sizeof(XWMAContext),
+    xwma_probe,
+    xwma_read_header,
+    xwma_read_packet,
+};
diff --git a/libavformat/yop.c b/libavformat/yop.c
index 54d3845..e367187 100644
--- a/libavformat/yop.c
+++ b/libavformat/yop.c
@@ -6,20 +6,20 @@
  * derived from the code by
  * Copyright (C) 2009 Thomas P. Higdon <thomas.p.higdon at gmail.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -50,7 +50,7 @@ static int yop_probe(AVProbeData *probe_packet)
 static int yop_read_header(AVFormatContext *s, AVFormatParameters *ap)
 {
     YopDecContext *yop = s->priv_data;
-    ByteIOContext *pb  = s->pb;
+    AVIOContext *pb  = s->pb;
 
     AVCodecContext *audio_dec, *video_dec;
     AVStream *audio_stream, *video_stream;
@@ -81,16 +81,16 @@ static int yop_read_header(AVFormatContext *s, AVFormatParameters *ap)
     video_dec->codec_type   = AVMEDIA_TYPE_VIDEO;
     video_dec->codec_id     = CODEC_ID_YOP;
 
-    url_fskip(pb, 6);
+    avio_skip(pb, 6);
 
-    frame_rate              = get_byte(pb);
-    yop->frame_size         = get_byte(pb) * 2048;
-    video_dec->width        = get_le16(pb);
-    video_dec->height       = get_le16(pb);
+    frame_rate              = avio_r8(pb);
+    yop->frame_size         = avio_r8(pb) * 2048;
+    video_dec->width        = avio_rl16(pb);
+    video_dec->height       = avio_rl16(pb);
 
     video_stream->sample_aspect_ratio = (AVRational){1, 2};
 
-    ret = get_buffer(pb, video_dec->extradata, 8);
+    ret = avio_read(pb, video_dec->extradata, 8);
     if (ret < 8)
         return ret < 0 ? ret : AVERROR_EOF;
 
@@ -104,7 +104,7 @@ static int yop_read_header(AVFormatContext *s, AVFormatParameters *ap)
         return AVERROR_INVALIDDATA;
     }
 
-    url_fseek(pb, 2048, SEEK_SET);
+    avio_seek(pb, 2048, SEEK_SET);
 
     av_set_pts_info(video_stream, 32, 1, frame_rate);
 
@@ -114,7 +114,7 @@ static int yop_read_header(AVFormatContext *s, AVFormatParameters *ap)
 static int yop_read_packet(AVFormatContext *s, AVPacket *pkt)
 {
     YopDecContext *yop = s->priv_data;
-    ByteIOContext *pb  = s->pb;
+    AVIOContext *pb  = s->pb;
 
     int ret;
     int actual_video_data_size = yop->frame_size -
@@ -136,9 +136,9 @@ static int yop_read_packet(AVFormatContext *s, AVPacket *pkt)
     if (ret < 0)
         return ret;
 
-    yop->video_packet.pos = url_ftell(pb);
+    yop->video_packet.pos = avio_tell(pb);
 
-    ret = get_buffer(pb, yop->video_packet.data, yop->palette_size);
+    ret = avio_read(pb, yop->video_packet.data, yop->palette_size);
     if (ret < 0) {
         goto err_out;
     }else if (ret < yop->palette_size) {
@@ -153,9 +153,9 @@ static int yop_read_packet(AVFormatContext *s, AVPacket *pkt)
     // Set position to the start of the frame
     pkt->pos = yop->video_packet.pos;
 
-    url_fskip(pb, yop->audio_block_length - ret);
+    avio_skip(pb, yop->audio_block_length - ret);
 
-    ret = get_buffer(pb, yop->video_packet.data + yop->palette_size,
+    ret = avio_read(pb, yop->video_packet.data + yop->palette_size,
                      actual_video_data_size);
     if (ret < 0)
         goto err_out;
@@ -190,7 +190,7 @@ static int yop_read_seek(AVFormatContext *s, int stream_index,
         return -1;
 
     pos_min        = s->data_offset;
-    pos_max        = url_fsize(s->pb) - yop->frame_size;
+    pos_max        = avio_size(s->pb) - yop->frame_size;
     frame_count    = (pos_max - pos_min) / yop->frame_size;
 
     timestamp      = FFMAX(0, FFMIN(frame_count, timestamp));
@@ -198,11 +198,11 @@ static int yop_read_seek(AVFormatContext *s, int stream_index,
     frame_pos      = timestamp * yop->frame_size + pos_min;
     yop->odd_frame = timestamp & 1;
 
-    url_fseek(s->pb, frame_pos, SEEK_SET);
+    avio_seek(s->pb, frame_pos, SEEK_SET);
     return 0;
 }
 
-AVInputFormat yop_demuxer = {
+AVInputFormat ff_yop_demuxer = {
     "yop",
     NULL_IF_CONFIG_SMALL("Psygnosis YOP Format"),
     sizeof(YopDecContext),
diff --git a/libavformat/yuv4mpeg.c b/libavformat/yuv4mpeg.c
index 99a1ce2..d712321 100644
--- a/libavformat/yuv4mpeg.c
+++ b/libavformat/yuv4mpeg.c
@@ -2,20 +2,20 @@
  * YUV4MPEG format
  * Copyright (c) 2001, 2002, 2003 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #include "avformat.h"
@@ -90,7 +90,7 @@ static int yuv4_generate_header(AVFormatContext *s, char* buf)
 static int yuv4_write_packet(AVFormatContext *s, AVPacket *pkt)
 {
     AVStream *st = s->streams[pkt->stream_index];
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     AVPicture *picture;
     int* first_pkt = s->priv_data;
     int width, height, h_chroma_shift, v_chroma_shift;
@@ -108,21 +108,21 @@ static int yuv4_write_packet(AVFormatContext *s, AVPacket *pkt)
             av_log(s, AV_LOG_ERROR, "Error. YUV4MPEG stream header write failed.\n");
             return AVERROR(EIO);
         } else {
-            put_buffer(pb, buf2, strlen(buf2));
+            avio_write(pb, buf2, strlen(buf2));
         }
     }
 
     /* construct frame header */
 
     m = snprintf(buf1, sizeof(buf1), "%s\n", Y4M_FRAME_MAGIC);
-    put_buffer(pb, buf1, strlen(buf1));
+    avio_write(pb, buf1, strlen(buf1));
 
     width = st->codec->width;
     height = st->codec->height;
 
     ptr = picture->data[0];
     for(i=0;i<height;i++) {
-        put_buffer(pb, ptr, width);
+        avio_write(pb, ptr, width);
         ptr += picture->linesize[0];
     }
 
@@ -135,15 +135,15 @@ static int yuv4_write_packet(AVFormatContext *s, AVPacket *pkt)
     ptr1 = picture->data[1];
     ptr2 = picture->data[2];
     for(i=0;i<height;i++) {     /* Cb */
-        put_buffer(pb, ptr1, width);
+        avio_write(pb, ptr1, width);
         ptr1 += picture->linesize[1];
     }
     for(i=0;i<height;i++) {     /* Cr */
-        put_buffer(pb, ptr2, width);
+        avio_write(pb, ptr2, width);
             ptr2 += picture->linesize[2];
     }
     }
-    put_flush_packet(pb);
+    avio_flush(pb);
     return 0;
 }
 
@@ -169,7 +169,7 @@ static int yuv4_write_header(AVFormatContext *s)
     return 0;
 }
 
-AVOutputFormat yuv4mpegpipe_muxer = {
+AVOutputFormat ff_yuv4mpegpipe_muxer = {
     "yuv4mpegpipe",
     NULL_IF_CONFIG_SMALL("YUV4MPEG pipe format"),
     "",
@@ -192,7 +192,7 @@ static int yuv4_read_header(AVFormatContext *s, AVFormatParameters *ap)
     char header[MAX_YUV4_HEADER+10];  // Include headroom for the longest option
     char *tokstart,*tokend,*header_end;
     int i;
-    ByteIOContext *pb = s->pb;
+    AVIOContext *pb = s->pb;
     int width=-1, height=-1, raten=0, rated=0, aspectn=0, aspectd=0;
     enum PixelFormat pix_fmt=PIX_FMT_NONE,alt_pix_fmt=PIX_FMT_NONE;
     enum AVChromaLocation chroma_sample_location = AVCHROMA_LOC_UNSPECIFIED;
@@ -200,7 +200,7 @@ static int yuv4_read_header(AVFormatContext *s, AVFormatParameters *ap)
     struct frame_attributes *s1 = s->priv_data;
 
     for (i=0; i<MAX_YUV4_HEADER; i++) {
-        header[i] = get_byte(pb);
+        header[i] = avio_r8(pb);
         if (header[i] == '\n') {
             header[i+1] = 0x20;  // Add a space after last option. Makes parsing "444" vs "444alpha" easier.
             header[i+2] = 0;
@@ -316,7 +316,7 @@ static int yuv4_read_header(AVFormatContext *s, AVFormatParameters *ap)
             pix_fmt = alt_pix_fmt;
     }
 
-    if (raten == 0 && rated == 0) {
+    if (raten <= 0 || rated <= 0) {
         // Frame rate unknown
         raten = 25;
         rated = 1;
@@ -352,7 +352,7 @@ static int yuv4_read_packet(AVFormatContext *s, AVPacket *pkt)
     struct frame_attributes *s1 = s->priv_data;
 
     for (i=0; i<MAX_FRAME_HEADER; i++) {
-        header[i] = get_byte(s->pb);
+        header[i] = avio_r8(s->pb);
         if (header[i] == '\n') {
             header[i+1] = 0;
             break;
@@ -390,7 +390,7 @@ static int yuv4_probe(AVProbeData *pd)
 }
 
 #if CONFIG_YUV4MPEGPIPE_DEMUXER
-AVInputFormat yuv4mpegpipe_demuxer = {
+AVInputFormat ff_yuv4mpegpipe_demuxer = {
     "yuv4mpegpipe",
     NULL_IF_CONFIG_SMALL("YUV4MPEG pipe format"),
     sizeof(struct frame_attributes),
diff --git a/libavutil/Makefile b/libavutil/Makefile
index 79506c0..baee496 100644
--- a/libavutil/Makefile
+++ b/libavutil/Makefile
@@ -3,36 +3,57 @@ include $(SUBDIR)../config.mak
 NAME = avutil
 
 HEADERS = adler32.h                                                     \
+          aes.h                                                         \
           attributes.h                                                  \
+          audioconvert.h                                                \
+          avassert.h                                                    \
           avstring.h                                                    \
           avutil.h                                                      \
           base64.h                                                      \
+          bswap.h                                                       \
           common.h                                                      \
+          cpu.h                                                         \
           crc.h                                                         \
           error.h                                                       \
+          eval.h                                                        \
           fifo.h                                                        \
+          file.h                                                        \
+          imgutils.h                                                    \
           intfloat_readwrite.h                                          \
+          intreadwrite.h                                                \
+          lfg.h                                                         \
           log.h                                                         \
           lzo.h                                                         \
           mathematics.h                                                 \
           md5.h                                                         \
           mem.h                                                         \
+          opt.h                                                         \
+          parseutils.h                                                  \
           pixdesc.h                                                     \
           pixfmt.h                                                      \
+          random_seed.h                                                 \
           rational.h                                                    \
+          samplefmt.h                                                   \
+          sha.h                                                         \
           sha1.h                                                        \
 
 BUILT_HEADERS = avconfig.h
 
 OBJS = adler32.o                                                        \
        aes.o                                                            \
+       audioconvert.o                                                   \
        avstring.o                                                       \
        base64.o                                                         \
+       cpu.o                                                            \
        crc.o                                                            \
        des.o                                                            \
        error.o                                                          \
+       eval.o                                                           \
        fifo.o                                                           \
+       file.o                                                           \
+       imgutils.o                                                       \
        intfloat_readwrite.o                                             \
+       inverse.o                                                        \
        lfg.o                                                            \
        lls.o                                                            \
        log.o                                                            \
@@ -40,15 +61,22 @@ OBJS = adler32.o                                                        \
        mathematics.o                                                    \
        md5.o                                                            \
        mem.o                                                            \
+       opt.o                                                            \
+       parseutils.o                                                     \
        pixdesc.o                                                        \
        random_seed.o                                                    \
        rational.o                                                       \
        rc4.o                                                            \
+       samplefmt.o                                                      \
        sha.o                                                            \
        tree.o                                                           \
        utils.o                                                          \
 
-TESTPROGS = adler32 aes base64 crc des lls md5 pca sha softfloat tree
+OBJS-$(ARCH_ARM) += arm/cpu.o
+OBJS-$(ARCH_PPC) += ppc/cpu.o
+OBJS-$(ARCH_X86) += x86/cpu.o
+
+TESTPROGS = adler32 aes base64 cpu crc des lls md5 pca sha softfloat tree
 TESTPROGS-$(HAVE_LZO1X_999_COMPRESS) += lzo
 
 DIRS = arm bfin sh4 x86
diff --git a/libavutil/adler32.h b/libavutil/adler32.h
index 9626c80..913db2d 100644
--- a/libavutil/adler32.h
+++ b/libavutil/adler32.h
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2006 Mans Rullgard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -24,6 +24,18 @@
 #include <stdint.h>
 #include "attributes.h"
 
+/**
+ * Calculate the Adler32 checksum of a buffer.
+ *
+ * Passing the return value to a subsequent av_adler32_update() call
+ * allows the checksum of multiple buffers to be calculated as though
+ * they were concatenated.
+ *
+ * @param adler initial checksum value
+ * @param buf   pointer to input buffer
+ * @param len   size of input buffer
+ * @return      updated checksum
+ */
 unsigned long av_adler32_update(unsigned long adler, const uint8_t *buf,
                                 unsigned int len) av_pure;
 
diff --git a/libavutil/aes.c b/libavutil/aes.c
index d3a271c..346676b 100644
--- a/libavutil/aes.c
+++ b/libavutil/aes.c
@@ -3,31 +3,38 @@
  *
  * some optimization ideas from aes128.c by Reimar Doeffinger
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "common.h"
 #include "aes.h"
 
+typedef union {
+    uint64_t u64[2];
+    uint32_t u32[4];
+    uint8_t u8x4[4][4];
+    uint8_t u8[16];
+} av_aes_block;
+
 typedef struct AVAES{
     // Note: round_key[16] is accessed in the init code, but this only
     // overwrites state, which does not matter (see also r7471).
-    uint8_t round_key[15][4][4];
-    uint8_t state[2][4][4];
+    av_aes_block round_key[15];
+    av_aes_block state[2];
     int rounds;
 }AVAES;
 
@@ -47,21 +54,21 @@ static uint32_t enc_multbl[4][256];
 static uint32_t dec_multbl[4][256];
 #endif
 
-static inline void addkey(uint64_t dst[2], const uint64_t src[2], const uint64_t round_key[2]){
-    dst[0] = src[0] ^ round_key[0];
-    dst[1] = src[1] ^ round_key[1];
+static inline void addkey(av_aes_block *dst, const av_aes_block *src, const av_aes_block *round_key){
+    dst->u64[0] = src->u64[0] ^ round_key->u64[0];
+    dst->u64[1] = src->u64[1] ^ round_key->u64[1];
 }
 
-static void subshift(uint8_t s0[2][16], int s, const uint8_t *box){
-    uint8_t (*s1)[16]= s0[0] - s;
-    uint8_t (*s3)[16]= s0[0] + s;
-    s0[0][0]=box[s0[1][ 0]]; s0[0][ 4]=box[s0[1][ 4]]; s0[0][ 8]=box[s0[1][ 8]]; s0[0][12]=box[s0[1][12]];
-    s1[0][3]=box[s1[1][ 7]]; s1[0][ 7]=box[s1[1][11]]; s1[0][11]=box[s1[1][15]]; s1[0][15]=box[s1[1][ 3]];
-    s0[0][2]=box[s0[1][10]]; s0[0][10]=box[s0[1][ 2]]; s0[0][ 6]=box[s0[1][14]]; s0[0][14]=box[s0[1][ 6]];
-    s3[0][1]=box[s3[1][13]]; s3[0][13]=box[s3[1][ 9]]; s3[0][ 9]=box[s3[1][ 5]]; s3[0][ 5]=box[s3[1][ 1]];
+static void subshift(av_aes_block s0[2], int s, const uint8_t *box){
+    av_aes_block *s1= (av_aes_block *)(s0[0].u8 - s);
+    av_aes_block *s3= (av_aes_block *)(s0[0].u8 + s);
+    s0[0].u8[0]=box[s0[1].u8[ 0]]; s0[0].u8[ 4]=box[s0[1].u8[ 4]]; s0[0].u8[ 8]=box[s0[1].u8[ 8]]; s0[0].u8[12]=box[s0[1].u8[12]];
+    s1[0].u8[3]=box[s1[1].u8[ 7]]; s1[0].u8[ 7]=box[s1[1].u8[11]]; s1[0].u8[11]=box[s1[1].u8[15]]; s1[0].u8[15]=box[s1[1].u8[ 3]];
+    s0[0].u8[2]=box[s0[1].u8[10]]; s0[0].u8[10]=box[s0[1].u8[ 2]]; s0[0].u8[ 6]=box[s0[1].u8[14]]; s0[0].u8[14]=box[s0[1].u8[ 6]];
+    s3[0].u8[1]=box[s3[1].u8[13]]; s3[0].u8[13]=box[s3[1].u8[ 9]]; s3[0].u8[ 9]=box[s3[1].u8[ 5]]; s3[0].u8[ 5]=box[s3[1].u8[ 1]];
 }
 
-static inline int mix_core(uint32_t multbl[4][256], int a, int b, int c, int d){
+static inline int mix_core(uint32_t multbl[][256], int a, int b, int c, int d){
 #if CONFIG_SMALL
 #define ROT(x,s) ((x<<s)|(x>>(32-s)))
     return multbl[0][a] ^ ROT(multbl[0][b], 8) ^ ROT(multbl[0][c], 16) ^ ROT(multbl[0][d], 24);
@@ -70,41 +77,45 @@ static inline int mix_core(uint32_t multbl[4][256], int a, int b, int c, int d){
 #endif
 }
 
-static inline void mix(uint8_t state[2][4][4], uint32_t multbl[4][256], int s1, int s3){
-    ((uint32_t *)(state))[0] = mix_core(multbl, state[1][0][0], state[1][s1  ][1], state[1][2][2], state[1][s3  ][3]);
-    ((uint32_t *)(state))[1] = mix_core(multbl, state[1][1][0], state[1][s3-1][1], state[1][3][2], state[1][s1-1][3]);
-    ((uint32_t *)(state))[2] = mix_core(multbl, state[1][2][0], state[1][s3  ][1], state[1][0][2], state[1][s1  ][3]);
-    ((uint32_t *)(state))[3] = mix_core(multbl, state[1][3][0], state[1][s1-1][1], state[1][1][2], state[1][s3-1][3]);
+static inline void mix(av_aes_block state[2], uint32_t multbl[][256], int s1, int s3){
+    uint8_t (*src)[4] = state[1].u8x4;
+    state[0].u32[0] = mix_core(multbl, src[0][0], src[s1  ][1], src[2][2], src[s3  ][3]);
+    state[0].u32[1] = mix_core(multbl, src[1][0], src[s3-1][1], src[3][2], src[s1-1][3]);
+    state[0].u32[2] = mix_core(multbl, src[2][0], src[s3  ][1], src[0][2], src[s1  ][3]);
+    state[0].u32[3] = mix_core(multbl, src[3][0], src[s1-1][1], src[1][2], src[s3-1][3]);
 }
 
-static inline void crypt(AVAES *a, int s, const uint8_t *sbox, const uint32_t *multbl){
+static inline void crypt(AVAES *a, int s, const uint8_t *sbox, uint32_t multbl[][256]){
     int r;
 
     for(r=a->rounds-1; r>0; r--){
         mix(a->state, multbl, 3-s, 1+s);
-        addkey(a->state[1], a->state[0], a->round_key[r]);
+        addkey(&a->state[1], &a->state[0], &a->round_key[r]);
     }
-    subshift(a->state[0][0], s, sbox);
+    subshift(&a->state[0], s, sbox);
 }
 
-void av_aes_crypt(AVAES *a, uint8_t *dst, const uint8_t *src, int count, uint8_t *iv, int decrypt){
+void av_aes_crypt(AVAES *a, uint8_t *dst_, const uint8_t *src_, int count, uint8_t *iv_, int decrypt){
+    av_aes_block *dst = (av_aes_block *)dst_;
+    const av_aes_block *src = (const av_aes_block *)src_;
+    av_aes_block *iv = (av_aes_block *)iv_;
     while(count--){
-        addkey(a->state[1], src, a->round_key[a->rounds]);
+        addkey(&a->state[1], src, &a->round_key[a->rounds]);
         if(decrypt) {
             crypt(a, 0, inv_sbox, dec_multbl);
             if(iv){
-                addkey(a->state[0], a->state[0], iv);
+                addkey(&a->state[0], &a->state[0], iv);
                 memcpy(iv, src, 16);
             }
-            addkey(dst, a->state[0], a->round_key[0]);
+            addkey(dst, &a->state[0], &a->round_key[0]);
         }else{
-            if(iv) addkey(a->state[1], a->state[1], iv);
+            if(iv) addkey(&a->state[1], &a->state[1], iv);
             crypt(a, 2,     sbox, enc_multbl);
-            addkey(dst, a->state[0], a->round_key[0]);
+            addkey(dst, &a->state[0], &a->round_key[0]);
             if(iv) memcpy(iv, dst, 16);
         }
-        src+=16;
-        dst+=16;
+        src++;
+        dst++;
     }
 }
 
@@ -130,7 +141,7 @@ int av_aes_init(AVAES *a, const uint8_t *key, int key_bits, int decrypt) {
     uint8_t  log8[256];
     uint8_t alog8[512];
 
-    if(!enc_multbl[0][sizeof(enc_multbl)/sizeof(enc_multbl[0][0])-1]){
+    if(!enc_multbl[FF_ARRAY_ELEMS(enc_multbl)-1][FF_ARRAY_ELEMS(enc_multbl[0])-1]){
         j=1;
         for(i=0; i<255; i++){
             alog8[i]=
@@ -158,7 +169,7 @@ int av_aes_init(AVAES *a, const uint8_t *key, int key_bits, int decrypt) {
     memcpy(tk, key, KC*4);
 
     for(t= 0; t < (rounds+1)*16;) {
-        memcpy(a->round_key[0][0]+t, tk, KC*4);
+        memcpy(a->round_key[0].u8+t, tk, KC*4);
         t+= KC*4;
 
         for(i = 0; i < 4; i++)
@@ -175,16 +186,16 @@ int av_aes_init(AVAES *a, const uint8_t *key, int key_bits, int decrypt) {
 
     if(decrypt){
         for(i=1; i<rounds; i++){
-            uint8_t tmp[3][16];
-            memcpy(tmp[2], a->round_key[i][0], 16);
-            subshift(tmp[1], 0, sbox);
+            av_aes_block tmp[3];
+            memcpy(&tmp[2], &a->round_key[i], 16);
+            subshift(&tmp[1], 0, sbox);
             mix(tmp, dec_multbl, 1, 3);
-            memcpy(a->round_key[i][0], tmp[0], 16);
+            memcpy(&a->round_key[i], &tmp[0], 16);
         }
     }else{
         for(i=0; i<(rounds+1)>>1; i++){
             for(j=0; j<16; j++)
-                FFSWAP(int, a->round_key[i][0][j], a->round_key[rounds-i][0][j]);
+                FFSWAP(int, a->round_key[i].u8[j], a->round_key[rounds-i].u8[j]);
         }
     }
 
diff --git a/libavutil/aes.h b/libavutil/aes.h
index 1ca853d..6e5d320 100644
--- a/libavutil/aes.h
+++ b/libavutil/aes.h
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2007 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -28,14 +28,14 @@ extern const int av_aes_size;
 struct AVAES;
 
 /**
- * Initializes an AVAES context.
+ * Initialize an AVAES context.
  * @param key_bits 128, 192 or 256
  * @param decrypt 0 for encryption, 1 for decryption
  */
 int av_aes_init(struct AVAES *a, const uint8_t *key, int key_bits, int decrypt);
 
 /**
- * Encrypts / decrypts.
+ * Encrypt or decrypt a buffer using a previously initialized context.
  * @param count number of 16 byte blocks
  * @param dst destination array, can be equal to src
  * @param src source array, can be equal to dst
diff --git a/libavutil/arm/bswap.h b/libavutil/arm/bswap.h
index 9126350..478ae98 100644
--- a/libavutil/arm/bswap.h
+++ b/libavutil/arm/bswap.h
@@ -1,18 +1,18 @@
 /*
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -26,15 +26,15 @@
 #ifdef __ARMCC_VERSION
 
 #if HAVE_ARMV6
-#define bswap_16 bswap_16
-static av_always_inline av_const unsigned bswap_16(unsigned x)
+#define av_bswap16 av_bswap16
+static av_always_inline av_const unsigned av_bswap16(unsigned x)
 {
     __asm { rev16 x, x }
     return x;
 }
 
-#define bswap_32 bswap_32
-static av_always_inline av_const uint32_t bswap_32(uint32_t x)
+#define av_bswap32 av_bswap32
+static av_always_inline av_const uint32_t av_bswap32(uint32_t x)
 {
     return __rev(x);
 }
@@ -43,16 +43,16 @@ static av_always_inline av_const uint32_t bswap_32(uint32_t x)
 #elif HAVE_INLINE_ASM
 
 #if HAVE_ARMV6
-#define bswap_16 bswap_16
-static av_always_inline av_const unsigned bswap_16(unsigned x)
+#define av_bswap16 av_bswap16
+static av_always_inline av_const unsigned av_bswap16(unsigned x)
 {
     __asm__("rev16 %0, %0" : "+r"(x));
     return x;
 }
 #endif
 
-#define bswap_32 bswap_32
-static av_always_inline av_const uint32_t bswap_32(uint32_t x)
+#define av_bswap32 av_bswap32
+static av_always_inline av_const uint32_t av_bswap32(uint32_t x)
 {
 #if HAVE_ARMV6
     __asm__("rev %0, %0" : "+r"(x));
diff --git a/libavutil/arm/cpu.c b/libavutil/arm/cpu.c
new file mode 100644
index 0000000..835513e
--- /dev/null
+++ b/libavutil/arm/cpu.c
@@ -0,0 +1,25 @@
+/*
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "libavutil/cpu.h"
+#include "config.h"
+
+int ff_get_cpu_flags_arm(void)
+{
+    return HAVE_IWMMXT * AV_CPU_FLAG_IWMMXT;
+}
diff --git a/libavutil/arm/intmath.h b/libavutil/arm/intmath.h
index 48a05ea..2f651d1 100644
--- a/libavutil/arm/intmath.h
+++ b/libavutil/arm/intmath.h
@@ -1,33 +1,37 @@
 /*
  * Copyright (c) 2010 Mans Rullgard <mans at mansr.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #ifndef AVUTIL_ARM_INTMATH_H
 #define AVUTIL_ARM_INTMATH_H
 
+#include <stdint.h>
+
 #include "config.h"
 #include "libavutil/attributes.h"
 
 #if HAVE_INLINE_ASM
 
 #if HAVE_ARMV6
-static inline av_const int FASTDIV(int a, int b)
+
+#define FASTDIV FASTDIV
+static av_always_inline av_const int FASTDIV(int a, int b)
 {
     int r, t;
     __asm__ volatile("cmp     %3, #2               \n\t"
@@ -37,17 +41,62 @@ static inline av_const int FASTDIV(int a, int b)
                      : "=&r"(r), "=&r"(t) : "r"(a), "r"(b), "r"(ff_inverse));
     return r;
 }
-#else
-static inline av_const int FASTDIV(int a, int b)
+
+#define av_clip_uint8 av_clip_uint8_arm
+static av_always_inline av_const uint8_t av_clip_uint8_arm(int a)
+{
+    unsigned x;
+    __asm__ volatile ("usat %0, #8,  %1" : "=r"(x) : "r"(a));
+    return x;
+}
+
+#define av_clip_int8 av_clip_int8_arm
+static av_always_inline av_const uint8_t av_clip_int8_arm(int a)
+{
+    unsigned x;
+    __asm__ volatile ("ssat %0, #8,  %1" : "=r"(x) : "r"(a));
+    return x;
+}
+
+#define av_clip_uint16 av_clip_uint16_arm
+static av_always_inline av_const uint16_t av_clip_uint16_arm(int a)
+{
+    unsigned x;
+    __asm__ volatile ("usat %0, #16, %1" : "=r"(x) : "r"(a));
+    return x;
+}
+
+#define av_clip_int16 av_clip_int16_arm
+static av_always_inline av_const int16_t av_clip_int16_arm(int a)
+{
+    int x;
+    __asm__ volatile ("ssat %0, #16, %1" : "=r"(x) : "r"(a));
+    return x;
+}
+
+#else /* HAVE_ARMV6 */
+
+#define FASTDIV FASTDIV
+static av_always_inline av_const int FASTDIV(int a, int b)
 {
     int r, t;
     __asm__ volatile("umull %1, %0, %2, %3"
                      : "=&r"(r), "=&r"(t) : "r"(a), "r"(ff_inverse[b]));
     return r;
 }
-#endif
 
-#define FASTDIV FASTDIV
+#endif /* HAVE_ARMV6 */
+
+#define av_clipl_int32 av_clipl_int32_arm
+static av_always_inline av_const int32_t av_clipl_int32_arm(int64_t a)
+{
+    int x, y;
+    __asm__ volatile ("adds   %1, %R2, %Q2, lsr #31  \n\t"
+                      "mvnne  %1, #1<<31             \n\t"
+                      "eorne  %0, %1,  %R2, asr #31  \n\t"
+                      : "=r"(x), "=&r"(y) : "r"(a));
+    return x;
+}
 
 #endif /* HAVE_INLINE_ASM */
 
diff --git a/libavutil/arm/intreadwrite.h b/libavutil/arm/intreadwrite.h
index 011694d..a5ee146 100644
--- a/libavutil/arm/intreadwrite.h
+++ b/libavutil/arm/intreadwrite.h
@@ -1,18 +1,18 @@
 /*
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,9 +25,9 @@
 #if HAVE_FAST_UNALIGNED && HAVE_INLINE_ASM
 
 #define AV_RN16 AV_RN16
-static av_always_inline uint16_t AV_RN16(const void *p)
+static av_always_inline unsigned AV_RN16(const void *p)
 {
-    uint16_t v;
+    unsigned v;
     __asm__ ("ldrh %0, %1" : "=r"(v) : "m"(*(const uint16_t *)p));
     return v;
 }
diff --git a/libavutil/arm/timer.h b/libavutil/arm/timer.h
index 5e8bc8e..4bca877 100644
--- a/libavutil/arm/timer.h
+++ b/libavutil/arm/timer.h
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2009 Mans Rullgard <mans at mansr.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavutil/attributes.h b/libavutil/attributes.h
index da45234..4abe78f 100644
--- a/libavutil/attributes.h
+++ b/libavutil/attributes.h
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -65,7 +65,7 @@
 #endif
 
 #ifndef av_cold
-#if (!defined(__ICC) || __ICC > 1110) && AV_GCC_VERSION_AT_LEAST(4,3)
+#if AV_GCC_VERSION_AT_LEAST(4,3)
 #    define av_cold __attribute__((cold))
 #else
 #    define av_cold
@@ -73,7 +73,7 @@
 #endif
 
 #ifndef av_flatten
-#if (!defined(__ICC) || __ICC > 1110) && AV_GCC_VERSION_AT_LEAST(4,1)
+#if AV_GCC_VERSION_AT_LEAST(4,1)
 #    define av_flatten __attribute__((flatten))
 #else
 #    define av_flatten
@@ -96,6 +96,27 @@
 #endif
 #endif
 
+/**
+ * Mark a variable as used and prevent the compiler from optimizing it
+ * away.  This is useful for variables accessed only from inline
+ * assembler without the compiler being aware.
+ */
+#ifndef av_used
+#if AV_GCC_VERSION_AT_LEAST(3,1)
+#    define av_used __attribute__((used))
+#else
+#    define av_used
+#endif
+#endif
+
+#ifndef av_alias
+#if AV_GCC_VERSION_AT_LEAST(3,3)
+#   define av_alias __attribute__((may_alias))
+#else
+#   define av_alias
+#endif
+#endif
+
 #ifndef av_uninit
 #if defined(__GNUC__) && !defined(__ICC)
 #    define av_uninit(x) x=x
diff --git a/libavutil/audioconvert.c b/libavutil/audioconvert.c
new file mode 100644
index 0000000..f789c77
--- /dev/null
+++ b/libavutil/audioconvert.c
@@ -0,0 +1,117 @@
+/*
+ * Copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * audio conversion routines
+ */
+
+#include "libavutil/avutil.h"
+#include "libavutil/avstring.h"
+#include "audioconvert.h"
+
+static const char * const channel_names[] = {
+    "FL", "FR", "FC", "LFE", "BL",  "BR",  "FLC", "FRC",
+    "BC", "SL", "SR", "TC",  "TFL", "TFC", "TFR", "TBL",
+    "TBC", "TBR",
+    [29] = "DL",
+    [30] = "DR",
+};
+
+static const char *get_channel_name(int channel_id)
+{
+    if (channel_id < 0 || channel_id >= FF_ARRAY_ELEMS(channel_names))
+        return NULL;
+    return channel_names[channel_id];
+}
+
+static const struct {
+    const char *name;
+    int         nb_channels;
+    int64_t     layout;
+} channel_layout_map[] = {
+    { "mono",        1,  AV_CH_LAYOUT_MONO },
+    { "stereo",      2,  AV_CH_LAYOUT_STEREO },
+    { "4.0",         4,  AV_CH_LAYOUT_4POINT0 },
+    { "quad",        4,  AV_CH_LAYOUT_QUAD },
+    { "5.0",         5,  AV_CH_LAYOUT_5POINT0 },
+    { "5.0",         5,  AV_CH_LAYOUT_5POINT0_BACK },
+    { "5.1",         6,  AV_CH_LAYOUT_5POINT1 },
+    { "5.1",         6,  AV_CH_LAYOUT_5POINT1_BACK },
+    { "5.1+downmix", 8,  AV_CH_LAYOUT_5POINT1|AV_CH_LAYOUT_STEREO_DOWNMIX, },
+    { "7.1",         8,  AV_CH_LAYOUT_7POINT1 },
+    { "7.1(wide)",   8,  AV_CH_LAYOUT_7POINT1_WIDE },
+    { "7.1+downmix", 10, AV_CH_LAYOUT_7POINT1|AV_CH_LAYOUT_STEREO_DOWNMIX, },
+    { 0 }
+};
+
+int64_t av_get_channel_layout(const char *name)
+{
+    int i = 0;
+    do {
+        if (!strcmp(channel_layout_map[i].name, name))
+            return channel_layout_map[i].layout;
+        i++;
+    } while (channel_layout_map[i].name);
+
+    return 0;
+}
+
+void av_get_channel_layout_string(char *buf, int buf_size,
+                                  int nb_channels, int64_t channel_layout)
+{
+    int i;
+
+    if (nb_channels <= 0)
+        nb_channels = av_get_channel_layout_nb_channels(channel_layout);
+
+    for (i = 0; channel_layout_map[i].name; i++)
+        if (nb_channels    == channel_layout_map[i].nb_channels &&
+            channel_layout == channel_layout_map[i].layout) {
+            av_strlcpy(buf, channel_layout_map[i].name, buf_size);
+            return;
+        }
+
+    snprintf(buf, buf_size, "%d channels", nb_channels);
+    if (channel_layout) {
+        int i,ch;
+        av_strlcat(buf, " (", buf_size);
+        for(i=0,ch=0; i<64; i++) {
+            if ((channel_layout & (1L<<i))) {
+                const char *name = get_channel_name(i);
+                if (name) {
+                    if (ch>0) av_strlcat(buf, "|", buf_size);
+                    av_strlcat(buf, name, buf_size);
+                }
+                ch++;
+            }
+        }
+        av_strlcat(buf, ")", buf_size);
+    }
+}
+
+int av_get_channel_layout_nb_channels(int64_t channel_layout)
+{
+    int count;
+    uint64_t x = channel_layout;
+    for (count = 0; x; count++)
+        x &= x-1; // unset lowest set bit
+    return count;
+}
diff --git a/libavutil/audioconvert.h b/libavutil/audioconvert.h
new file mode 100644
index 0000000..e37a2e8
--- /dev/null
+++ b/libavutil/audioconvert.h
@@ -0,0 +1,95 @@
+/*
+ * Copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at>
+ * Copyright (c) 2008 Peter Ross
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_AUDIOCONVERT_H
+#define AVUTIL_AUDIOCONVERT_H
+
+#include <stdint.h>
+
+/**
+ * @file
+ * audio conversion routines
+ */
+
+/* Audio channel masks */
+#define AV_CH_FRONT_LEFT             0x00000001
+#define AV_CH_FRONT_RIGHT            0x00000002
+#define AV_CH_FRONT_CENTER           0x00000004
+#define AV_CH_LOW_FREQUENCY          0x00000008
+#define AV_CH_BACK_LEFT              0x00000010
+#define AV_CH_BACK_RIGHT             0x00000020
+#define AV_CH_FRONT_LEFT_OF_CENTER   0x00000040
+#define AV_CH_FRONT_RIGHT_OF_CENTER  0x00000080
+#define AV_CH_BACK_CENTER            0x00000100
+#define AV_CH_SIDE_LEFT              0x00000200
+#define AV_CH_SIDE_RIGHT             0x00000400
+#define AV_CH_TOP_CENTER             0x00000800
+#define AV_CH_TOP_FRONT_LEFT         0x00001000
+#define AV_CH_TOP_FRONT_CENTER       0x00002000
+#define AV_CH_TOP_FRONT_RIGHT        0x00004000
+#define AV_CH_TOP_BACK_LEFT          0x00008000
+#define AV_CH_TOP_BACK_CENTER        0x00010000
+#define AV_CH_TOP_BACK_RIGHT         0x00020000
+#define AV_CH_STEREO_LEFT            0x20000000  ///< Stereo downmix.
+#define AV_CH_STEREO_RIGHT           0x40000000  ///< See AV_CH_STEREO_LEFT.
+
+/** Channel mask value used for AVCodecContext.request_channel_layout
+    to indicate that the user requests the channel order of the decoder output
+    to be the native codec channel order. */
+#define AV_CH_LAYOUT_NATIVE          0x8000000000000000LL
+
+/* Audio channel convenience macros */
+#define AV_CH_LAYOUT_MONO              (AV_CH_FRONT_CENTER)
+#define AV_CH_LAYOUT_STEREO            (AV_CH_FRONT_LEFT|AV_CH_FRONT_RIGHT)
+#define AV_CH_LAYOUT_2_1               (AV_CH_LAYOUT_STEREO|AV_CH_BACK_CENTER)
+#define AV_CH_LAYOUT_SURROUND          (AV_CH_LAYOUT_STEREO|AV_CH_FRONT_CENTER)
+#define AV_CH_LAYOUT_4POINT0           (AV_CH_LAYOUT_SURROUND|AV_CH_BACK_CENTER)
+#define AV_CH_LAYOUT_2_2               (AV_CH_LAYOUT_STEREO|AV_CH_SIDE_LEFT|AV_CH_SIDE_RIGHT)
+#define AV_CH_LAYOUT_QUAD              (AV_CH_LAYOUT_STEREO|AV_CH_BACK_LEFT|AV_CH_BACK_RIGHT)
+#define AV_CH_LAYOUT_5POINT0           (AV_CH_LAYOUT_SURROUND|AV_CH_SIDE_LEFT|AV_CH_SIDE_RIGHT)
+#define AV_CH_LAYOUT_5POINT1           (AV_CH_LAYOUT_5POINT0|AV_CH_LOW_FREQUENCY)
+#define AV_CH_LAYOUT_5POINT0_BACK      (AV_CH_LAYOUT_SURROUND|AV_CH_BACK_LEFT|AV_CH_BACK_RIGHT)
+#define AV_CH_LAYOUT_5POINT1_BACK      (AV_CH_LAYOUT_5POINT0_BACK|AV_CH_LOW_FREQUENCY)
+#define AV_CH_LAYOUT_7POINT0           (AV_CH_LAYOUT_5POINT0|AV_CH_BACK_LEFT|AV_CH_BACK_RIGHT)
+#define AV_CH_LAYOUT_7POINT1           (AV_CH_LAYOUT_5POINT1|AV_CH_BACK_LEFT|AV_CH_BACK_RIGHT)
+#define AV_CH_LAYOUT_7POINT1_WIDE      (AV_CH_LAYOUT_5POINT1_BACK|AV_CH_FRONT_LEFT_OF_CENTER|AV_CH_FRONT_RIGHT_OF_CENTER)
+#define AV_CH_LAYOUT_STEREO_DOWNMIX    (AV_CH_STEREO_LEFT|AV_CH_STEREO_RIGHT)
+
+/**
+ * Return a channel layout id that matches name, 0 if no match.
+ */
+int64_t av_get_channel_layout(const char *name);
+
+/**
+ * Return a description of a channel layout.
+ * If nb_channels is <= 0, it is guessed from the channel_layout.
+ *
+ * @param buf put here the string containing the channel layout
+ * @param buf_size size in bytes of the buffer
+ */
+void av_get_channel_layout_string(char *buf, int buf_size, int nb_channels, int64_t channel_layout);
+
+/**
+ * Return the number of channels in the channel layout.
+ */
+int av_get_channel_layout_nb_channels(int64_t channel_layout);
+
+#endif /* AVUTIL_AUDIOCONVERT_H */
diff --git a/libavutil/avassert.h b/libavutil/avassert.h
new file mode 100644
index 0000000..8733313
--- /dev/null
+++ b/libavutil/avassert.h
@@ -0,0 +1,66 @@
+/*
+ * copyright (c) 2010 Michael Niedermayer <michaelni at gmx.at>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * simple assert() macros that are a bit more flexible than ISO C assert().
+ * @author Michael Niedermayer <michaelni at gmx.at>
+ */
+
+#ifndef AVUTIL_AVASSERT_H
+#define AVUTIL_AVASSERT_H
+
+#include <stdlib.h>
+#include "avutil.h"
+#include "log.h"
+
+/**
+ * assert() equivalent, that is always enabled.
+ */
+#define av_assert0(cond) do {                                           \
+    if (!(cond)) {                                                      \
+        av_log(NULL, AV_LOG_FATAL, "Assertion %s failed at %s:%d\n",    \
+               AV_STRINGIFY(cond), __FILE__, __LINE__);                 \
+        abort();                                                        \
+    }                                                                   \
+} while (0)
+
+
+/**
+ * assert() equivalent, that does not lie in speed critical code.
+ * These asserts() thus can be enabled without fearing speedloss.
+ */
+#if defined(ASSERT_LEVEL) && ASSERT_LEVEL > 0
+#define av_assert1(cond) av_assert0(cond)
+#else
+#define av_assert1(cond) ((void)0)
+#endif
+
+
+/**
+ * assert() equivalent, that does lie in speed critical code.
+ */
+#if defined(ASSERT_LEVEL) && ASSERT_LEVEL > 1
+#define av_assert2(cond) av_assert0(cond)
+#else
+#define av_assert2(cond) ((void)0)
+#endif
+
+#endif
diff --git a/libavutil/avr32/bswap.h b/libavutil/avr32/bswap.h
index e8c8ddc..857f024 100644
--- a/libavutil/avr32/bswap.h
+++ b/libavutil/avr32/bswap.h
@@ -1,18 +1,18 @@
 /*
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,15 +25,15 @@
 
 #if HAVE_INLINE_ASM
 
-#define bswap_16 bswap_16
-static av_always_inline av_const uint16_t bswap_16(uint16_t x)
+#define av_bswap16 av_bswap16
+static av_always_inline av_const uint16_t av_bswap16(uint16_t x)
 {
     __asm__ ("swap.bh %0" : "+r"(x));
     return x;
 }
 
-#define bswap_32 bswap_32
-static av_always_inline av_const uint32_t bswap_32(uint32_t x)
+#define av_bswap32 av_bswap32
+static av_always_inline av_const uint32_t av_bswap32(uint32_t x)
 {
     __asm__ ("swap.b  %0" : "+r"(x));
     return x;
diff --git a/libavutil/avr32/intreadwrite.h b/libavutil/avr32/intreadwrite.h
index 3e468b4..e0049fe 100644
--- a/libavutil/avr32/intreadwrite.h
+++ b/libavutil/avr32/intreadwrite.h
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2009 Mans Rullgard <mans at mansr.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -106,8 +106,8 @@ static av_always_inline void AV_WB32(void *p, uint32_t v)
 }
 
 /* These two would be defined by generic code, but we need them sooner. */
-#define AV_RL32(p)    bswap_32(AV_RB32(p))
-#define AV_WL32(p, v) AV_WB32(p, bswap_32(v))
+#define AV_RL32(p)    av_bswap32(AV_RB32(p))
+#define AV_WL32(p, v) AV_WB32(p, av_bswap32(v))
 
 #define AV_WB64 AV_WB64
 static av_always_inline void AV_WB64(void *p, uint64_t v)
diff --git a/libavutil/avstring.c b/libavutil/avstring.c
index 4844e28..2b8c2d4 100644
--- a/libavutil/avstring.c
+++ b/libavutil/avstring.c
@@ -2,20 +2,20 @@
  * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
  * Copyright (c) 2007 Mans Rullgard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -97,3 +97,91 @@ char *av_d2str(double d)
     if(str) snprintf(str, 16, "%f", d);
     return str;
 }
+
+#define WHITESPACES " \n\t"
+
+char *av_get_token(const char **buf, const char *term)
+{
+    char *out = av_malloc(strlen(*buf) + 1);
+    char *ret= out, *end= out;
+    const char *p = *buf;
+    if (!out) return NULL;
+    p += strspn(p, WHITESPACES);
+
+    while(*p && !strspn(p, term)) {
+        char c = *p++;
+        if(c == '\\' && *p){
+            *out++ = *p++;
+            end= out;
+        }else if(c == '\''){
+            while(*p && *p != '\'')
+                *out++ = *p++;
+            if(*p){
+                p++;
+                end= out;
+            }
+        }else{
+            *out++ = c;
+        }
+    }
+
+    do{
+        *out-- = 0;
+    }while(out >= end && strspn(out, WHITESPACES));
+
+    *buf = p;
+
+    return ret;
+}
+
+#ifdef TEST
+
+#undef printf
+
+int main(void)
+{
+    int i;
+
+    printf("Testing av_get_token()\n");
+    {
+        const char *strings[] = {
+            "''",
+            "",
+            ":",
+            "\\",
+            "'",
+            "    ''    :",
+            "    ''  ''  :",
+            "foo   '' :",
+            "'foo'",
+            "foo     ",
+            "  '  foo  '  ",
+            "foo\\",
+            "foo':  blah:blah",
+            "foo\\:  blah:blah",
+            "foo\'",
+            "'foo :  '  :blahblah",
+            "\\ :blah",
+            "     foo",
+            "      foo       ",
+            "      foo     \\ ",
+            "foo ':blah",
+            " foo   bar    :   blahblah",
+            "\\f\\o\\o",
+            "'foo : \\ \\  '   : blahblah",
+            "'\\fo\\o:': blahblah",
+            "\\'fo\\o\\:':  foo  '  :blahblah"
+        };
+
+        for (i=0; i < FF_ARRAY_ELEMS(strings); i++) {
+            const char *p= strings[i];
+            printf("|%s|", p);
+            printf(" -> |%s|", av_get_token(&p, ":"));
+            printf(" + |%s|\n", p);
+        }
+    }
+
+    return 0;
+}
+
+#endif /* TEST */
diff --git a/libavutil/avstring.h b/libavutil/avstring.h
index 01c2391..b40acf6 100644
--- a/libavutil/avstring.h
+++ b/libavutil/avstring.h
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2007 Mans Rullgard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -114,4 +114,20 @@ size_t av_strlcatf(char *dst, size_t size, const char *fmt, ...);
  */
 char *av_d2str(double d);
 
+/**
+ * Unescape the given string until a non escaped terminating char,
+ * and return the token corresponding to the unescaped string.
+ *
+ * The normal \ and ' escaping is supported. Leading and trailing
+ * whitespaces are removed, unless they are escaped with '\' or are
+ * enclosed between ''.
+ *
+ * @param buf the buffer to parse, buf will be updated to point to the
+ * terminating char
+ * @param term a 0-terminated list of terminating chars
+ * @return the malloced unescaped string, which must be av_freed by
+ * the user, NULL in case of allocation failure
+ */
+char *av_get_token(const char **buf, const char *term);
+
 #endif /* AVUTIL_AVSTRING_H */
diff --git a/libavutil/avutil.h b/libavutil/avutil.h
index e9e07b9..6f2517c 100644
--- a/libavutil/avutil.h
+++ b/libavutil/avutil.h
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -39,9 +39,9 @@
 #define AV_VERSION_DOT(a, b, c) a ##.## b ##.## c
 #define AV_VERSION(a, b, c) AV_VERSION_DOT(a, b, c)
 
-#define LIBAVUTIL_VERSION_MAJOR 50
-#define LIBAVUTIL_VERSION_MINOR 15
-#define LIBAVUTIL_VERSION_MICRO  1
+#define LIBAVUTIL_VERSION_MAJOR 51
+#define LIBAVUTIL_VERSION_MINOR  0
+#define LIBAVUTIL_VERSION_MICRO  0
 
 #define LIBAVUTIL_VERSION_INT   AV_VERSION_INT(LIBAVUTIL_VERSION_MAJOR, \
                                                LIBAVUTIL_VERSION_MINOR, \
@@ -54,17 +54,25 @@
 #define LIBAVUTIL_IDENT         "Lavu" AV_STRINGIFY(LIBAVUTIL_VERSION)
 
 /**
- * Returns the LIBAVUTIL_VERSION_INT constant.
+ * Those FF_API_* defines are not part of public API.
+ * They may change, break or disappear at any time.
+ */
+#ifndef FF_API_OLD_EVAL_NAMES
+#define FF_API_OLD_EVAL_NAMES (LIBAVUTIL_VERSION_MAJOR < 51)
+#endif
+
+/**
+ * Return the LIBAVUTIL_VERSION_INT constant.
  */
 unsigned avutil_version(void);
 
 /**
- * Returns the libavutil build-time configuration.
+ * Return the libavutil build-time configuration.
  */
 const char *avutil_configuration(void);
 
 /**
- * Returns the libavutil license.
+ * Return the libavutil license.
  */
 const char *avutil_license(void);
 
@@ -78,6 +86,25 @@ enum AVMediaType {
     AVMEDIA_TYPE_NB
 };
 
+#define FF_LAMBDA_SHIFT 7
+#define FF_LAMBDA_SCALE (1<<FF_LAMBDA_SHIFT)
+#define FF_QP2LAMBDA 118 ///< factor to convert from H.263 QP to lambda
+#define FF_LAMBDA_MAX (256*128-1)
+
+#define FF_QUALITY_SCALE FF_LAMBDA_SCALE //FIXME maybe remove
+
+#define AV_NOPTS_VALUE          INT64_C(0x8000000000000000)
+#define AV_TIME_BASE            1000000
+#define AV_TIME_BASE_Q          (AVRational){1, AV_TIME_BASE}
+
+/**
+ * Those FF_API_* defines are not part of public API.
+ * They may change, break or disappear at any time.
+ */
+#ifndef FF_API_OLD_IMAGE_NAMES
+#define FF_API_OLD_IMAGE_NAMES (LIBAVUTIL_VERSION_MAJOR < 51)
+#endif
+
 #include "common.h"
 #include "error.h"
 #include "mathematics.h"
diff --git a/libavutil/base64.c b/libavutil/base64.c
index d84ca36..73872b8 100644
--- a/libavutil/base64.c
+++ b/libavutil/base64.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2006 Ryan Martell. (rdm4 at martellventures.com)
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -79,7 +79,7 @@ char *av_base64_encode(char *out, int out_size, const uint8_t *in, int in_size)
     int bytes_remaining = in_size;
 
     if (in_size >= UINT_MAX / 4 ||
-        out_size < (in_size+2) / 3 * 4 + 1)
+        out_size < AV_BASE64_SIZE(in_size))
         return NULL;
     ret = dst = out;
     while (bytes_remaining) {
diff --git a/libavutil/base64.h b/libavutil/base64.h
index 103860e..96c0a4a 100644
--- a/libavutil/base64.h
+++ b/libavutil/base64.h
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2006 Ryan Martell. (rdm4 at martellventures.com)
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -24,26 +24,31 @@
 #include <stdint.h>
 
 /**
- * Decodes the base64-encoded string in in and puts the decoded
- * data in out.
+ * Decode a base64-encoded string.
  *
- * @param out_size size in bytes of the out buffer, it should be at
- * least 3/4 of the length of in
- * @return the number of bytes written, or a negative value in case of
- * error
+ * @param out      buffer for decoded data
+ * @param in       null-terminated input string
+ * @param out_size size in bytes of the out buffer, must be at
+ *                 least 3/4 of the length of in
+ * @return         number of bytes written, or a negative value in case of
+ *                 invalid input
  */
 int av_base64_decode(uint8_t *out, const char *in, int out_size);
 
 /**
- * Encodes in base64 the data in in and puts the resulting string
- * in out.
+ * Encode data to base64 and null-terminate.
  *
- * @param out_size size in bytes of the out string, it should be at
- * least ((in_size + 2) / 3) * 4 + 1
- * @param in_size size in bytes of the in buffer
- * @return the string containing the encoded data, or NULL in case of
- * error
+ * @param out      buffer for encoded data
+ * @param out_size size in bytes of the output buffer, must be at
+ *                 least AV_BASE64_SIZE(in_size)
+ * @param in_size  size in bytes of the 'in' buffer
+ * @return         'out' or NULL in case of error
  */
 char *av_base64_encode(char *out, int out_size, const uint8_t *in, int in_size);
 
+/**
+ * Calculate the output size needed to base64-encode x bytes.
+ */
+#define AV_BASE64_SIZE(x)  (((x)+2) / 3 * 4 + 1)
+
 #endif /* AVUTIL_BASE64_H */
diff --git a/libavutil/bfin/bswap.h b/libavutil/bfin/bswap.h
index ccdfeb7..2837a2f 100644
--- a/libavutil/bfin/bswap.h
+++ b/libavutil/bfin/bswap.h
@@ -1,20 +1,20 @@
 /*
  * Copyright (C) 2007 Marc Hoffman
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -30,8 +30,8 @@
 #include "config.h"
 #include "libavutil/attributes.h"
 
-#define bswap_32 bswap_32
-static av_always_inline av_const uint32_t bswap_32(uint32_t x)
+#define av_bswap32 av_bswap32
+static av_always_inline av_const uint32_t av_bswap32(uint32_t x)
 {
     unsigned tmp;
     __asm__("%1 = %0 >> 8 (V);      \n\t"
diff --git a/libavutil/bfin/timer.h b/libavutil/bfin/timer.h
index 644573d..49d32a8 100644
--- a/libavutil/bfin/timer.h
+++ b/libavutil/bfin/timer.h
@@ -1,20 +1,20 @@
 /*
  * Copyright (C) 2007 Marc Hoffman
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavutil/bswap.h b/libavutil/bswap.h
index 6dd2a35..c93825f 100644
--- a/libavutil/bswap.h
+++ b/libavutil/bswap.h
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -27,9 +27,13 @@
 #define AVUTIL_BSWAP_H
 
 #include <stdint.h>
-#include "config.h"
+#include "libavutil/avconfig.h"
 #include "attributes.h"
 
+#ifdef HAVE_AV_CONFIG_H
+
+#include "config.h"
+
 #if   ARCH_ARM
 #   include "arm/bswap.h"
 #elif ARCH_AVR32
@@ -42,22 +46,24 @@
 #   include "x86/bswap.h"
 #endif
 
+#endif /* HAVE_AV_CONFIG_H */
+
 #define AV_BSWAP16C(x) (((x) << 8 & 0xff00)  | ((x) >> 8 & 0x00ff))
 #define AV_BSWAP32C(x) (AV_BSWAP16C(x) << 16 | AV_BSWAP16C((x) >> 16))
 #define AV_BSWAP64C(x) (AV_BSWAP32C(x) << 32 | AV_BSWAP32C((x) >> 32))
 
 #define AV_BSWAPC(s, x) AV_BSWAP##s##C(x)
 
-#ifndef bswap_16
-static av_always_inline av_const uint16_t bswap_16(uint16_t x)
+#ifndef av_bswap16
+static av_always_inline av_const uint16_t av_bswap16(uint16_t x)
 {
     x= (x>>8) | (x<<8);
     return x;
 }
 #endif
 
-#ifndef bswap_32
-static av_always_inline av_const uint32_t bswap_32(uint32_t x)
+#ifndef av_bswap32
+static av_always_inline av_const uint32_t av_bswap32(uint32_t x)
 {
     x= ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
     x= (x>>16) | (x<<16);
@@ -65,8 +71,8 @@ static av_always_inline av_const uint32_t bswap_32(uint32_t x)
 }
 #endif
 
-#ifndef bswap_64
-static inline uint64_t av_const bswap_64(uint64_t x)
+#ifndef av_bswap64
+static inline uint64_t av_const av_bswap64(uint64_t x)
 {
 #if 0
     x= ((x<< 8)&0xFF00FF00FF00FF00ULL) | ((x>> 8)&0x00FF00FF00FF00FFULL);
@@ -78,41 +84,41 @@ static inline uint64_t av_const bswap_64(uint64_t x)
         uint32_t l[2];
     } w, r;
     w.ll = x;
-    r.l[0] = bswap_32 (w.l[1]);
-    r.l[1] = bswap_32 (w.l[0]);
+    r.l[0] = av_bswap32 (w.l[1]);
+    r.l[1] = av_bswap32 (w.l[0]);
     return r.ll;
 #endif
 }
 #endif
 
-// be2me ... big-endian to machine-endian
-// le2me ... little-endian to machine-endian
-
-#if HAVE_BIGENDIAN
-#define be2me_16(x) (x)
-#define be2me_32(x) (x)
-#define be2me_64(x) (x)
-#define le2me_16(x) bswap_16(x)
-#define le2me_32(x) bswap_32(x)
-#define le2me_64(x) bswap_64(x)
-#define AV_BE2MEC(s, x) (x)
-#define AV_LE2MEC(s, x) AV_BSWAPC(s, x)
+// be2ne ... big-endian to native-endian
+// le2ne ... little-endian to native-endian
+
+#if AV_HAVE_BIGENDIAN
+#define av_be2ne16(x) (x)
+#define av_be2ne32(x) (x)
+#define av_be2ne64(x) (x)
+#define av_le2ne16(x) av_bswap16(x)
+#define av_le2ne32(x) av_bswap32(x)
+#define av_le2ne64(x) av_bswap64(x)
+#define AV_BE2NEC(s, x) (x)
+#define AV_LE2NEC(s, x) AV_BSWAPC(s, x)
 #else
-#define be2me_16(x) bswap_16(x)
-#define be2me_32(x) bswap_32(x)
-#define be2me_64(x) bswap_64(x)
-#define le2me_16(x) (x)
-#define le2me_32(x) (x)
-#define le2me_64(x) (x)
-#define AV_BE2MEC(s, x) AV_BSWAPC(s, x)
-#define AV_LE2MEC(s, x) (x)
+#define av_be2ne16(x) av_bswap16(x)
+#define av_be2ne32(x) av_bswap32(x)
+#define av_be2ne64(x) av_bswap64(x)
+#define av_le2ne16(x) (x)
+#define av_le2ne32(x) (x)
+#define av_le2ne64(x) (x)
+#define AV_BE2NEC(s, x) AV_BSWAPC(s, x)
+#define AV_LE2NEC(s, x) (x)
 #endif
 
-#define AV_BE2ME16C(x) AV_BE2MEC(16, x)
-#define AV_BE2ME32C(x) AV_BE2MEC(32, x)
-#define AV_BE2ME64C(x) AV_BE2MEC(64, x)
-#define AV_LE2ME16C(x) AV_LE2MEC(16, x)
-#define AV_LE2ME32C(x) AV_LE2MEC(32, x)
-#define AV_LE2ME64C(x) AV_LE2MEC(64, x)
+#define AV_BE2NE16C(x) AV_BE2NEC(16, x)
+#define AV_BE2NE32C(x) AV_BE2NEC(32, x)
+#define AV_BE2NE64C(x) AV_BE2NEC(64, x)
+#define AV_LE2NE16C(x) AV_LE2NEC(16, x)
+#define AV_LE2NE32C(x) AV_LE2NEC(32, x)
+#define AV_LE2NE64C(x) AV_LE2NEC(64, x)
 
 #endif /* AVUTIL_BSWAP_H */
diff --git a/libavutil/colorspace.h b/libavutil/colorspace.h
new file mode 100644
index 0000000..8757566
--- /dev/null
+++ b/libavutil/colorspace.h
@@ -0,0 +1,111 @@
+/*
+ * Colorspace conversion defines
+ * Copyright (c) 2001, 2002, 2003 Fabrice Bellard
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * Various defines for YUV<->RGB conversion
+ */
+
+#ifndef AVUTIL_COLORSPACE_H
+#define AVUTIL_COLORSPACE_H
+
+#define SCALEBITS 10
+#define ONE_HALF  (1 << (SCALEBITS - 1))
+#define FIX(x)    ((int) ((x) * (1<<SCALEBITS) + 0.5))
+
+#define YUV_TO_RGB1_CCIR(cb1, cr1)\
+{\
+    cb = (cb1) - 128;\
+    cr = (cr1) - 128;\
+    r_add = FIX(1.40200*255.0/224.0) * cr + ONE_HALF;\
+    g_add = - FIX(0.34414*255.0/224.0) * cb - FIX(0.71414*255.0/224.0) * cr + \
+            ONE_HALF;\
+    b_add = FIX(1.77200*255.0/224.0) * cb + ONE_HALF;\
+}
+
+#define YUV_TO_RGB2_CCIR(r, g, b, y1)\
+{\
+    y = ((y1) - 16) * FIX(255.0/219.0);\
+    r = cm[(y + r_add) >> SCALEBITS];\
+    g = cm[(y + g_add) >> SCALEBITS];\
+    b = cm[(y + b_add) >> SCALEBITS];\
+}
+
+#define YUV_TO_RGB1(cb1, cr1)\
+{\
+    cb = (cb1) - 128;\
+    cr = (cr1) - 128;\
+    r_add = FIX(1.40200) * cr + ONE_HALF;\
+    g_add = - FIX(0.34414) * cb - FIX(0.71414) * cr + ONE_HALF;\
+    b_add = FIX(1.77200) * cb + ONE_HALF;\
+}
+
+#define YUV_TO_RGB2(r, g, b, y1)\
+{\
+    y = (y1) << SCALEBITS;\
+    r = cm[(y + r_add) >> SCALEBITS];\
+    g = cm[(y + g_add) >> SCALEBITS];\
+    b = cm[(y + b_add) >> SCALEBITS];\
+}
+
+#define Y_CCIR_TO_JPEG(y)\
+ cm[((y) * FIX(255.0/219.0) + (ONE_HALF - 16 * FIX(255.0/219.0))) >> SCALEBITS]
+
+#define Y_JPEG_TO_CCIR(y)\
+ (((y) * FIX(219.0/255.0) + (ONE_HALF + (16 << SCALEBITS))) >> SCALEBITS)
+
+#define C_CCIR_TO_JPEG(y)\
+ cm[(((y) - 128) * FIX(127.0/112.0) + (ONE_HALF + (128 << SCALEBITS))) >> SCALEBITS]
+
+/* NOTE: the clamp is really necessary! */
+static inline int C_JPEG_TO_CCIR(int y) {
+    y = (((y - 128) * FIX(112.0/127.0) + (ONE_HALF + (128 << SCALEBITS))) >> SCALEBITS);
+    if (y < 16)
+        y = 16;
+    return y;
+}
+
+
+#define RGB_TO_Y(r, g, b) \
+((FIX(0.29900) * (r) + FIX(0.58700) * (g) + \
+  FIX(0.11400) * (b) + ONE_HALF) >> SCALEBITS)
+
+#define RGB_TO_U(r1, g1, b1, shift)\
+(((- FIX(0.16874) * r1 - FIX(0.33126) * g1 +         \
+     FIX(0.50000) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
+
+#define RGB_TO_V(r1, g1, b1, shift)\
+(((FIX(0.50000) * r1 - FIX(0.41869) * g1 -           \
+   FIX(0.08131) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
+
+#define RGB_TO_Y_CCIR(r, g, b) \
+((FIX(0.29900*219.0/255.0) * (r) + FIX(0.58700*219.0/255.0) * (g) + \
+  FIX(0.11400*219.0/255.0) * (b) + (ONE_HALF + (16 << SCALEBITS))) >> SCALEBITS)
+
+#define RGB_TO_U_CCIR(r1, g1, b1, shift)\
+(((- FIX(0.16874*224.0/255.0) * r1 - FIX(0.33126*224.0/255.0) * g1 +         \
+     FIX(0.50000*224.0/255.0) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
+
+#define RGB_TO_V_CCIR(r1, g1, b1, shift)\
+(((FIX(0.50000*224.0/255.0) * r1 - FIX(0.41869*224.0/255.0) * g1 -           \
+   FIX(0.08131*224.0/255.0) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
+
+#endif /* AVUTIL_COLORSPACE_H */
diff --git a/libavutil/common.h b/libavutil/common.h
index 4aa00a9..e5c1dfd 100644
--- a/libavutil/common.h
+++ b/libavutil/common.h
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -35,6 +35,13 @@
 #include <stdlib.h>
 #include <string.h>
 #include "attributes.h"
+#include "libavutil/avconfig.h"
+
+#if AV_HAVE_BIGENDIAN
+#   define AV_NE(be, le) (be)
+#else
+#   define AV_NE(be, le) (le)
+#endif
 
 //rounded division & shift
 #define RSHIFT(a,b) ((a) > 0 ? ((a) + ((1<<(b))>>1))>>(b) : ((a) + ((1<<(b))>>1)-1)>>(b))
@@ -57,7 +64,7 @@ extern const uint8_t ff_log2_tab[256];
 
 extern const uint8_t av_reverse[256];
 
-static inline av_const int av_log2_c(unsigned int v)
+static av_always_inline av_const int av_log2_c(unsigned int v)
 {
     int n = 0;
     if (v & 0xffff0000) {
@@ -73,7 +80,7 @@ static inline av_const int av_log2_c(unsigned int v)
     return n;
 }
 
-static inline av_const int av_log2_16bit_c(unsigned int v)
+static av_always_inline av_const int av_log2_16bit_c(unsigned int v)
 {
     int n = 0;
     if (v & 0xff00) {
@@ -90,21 +97,17 @@ static inline av_const int av_log2_16bit_c(unsigned int v)
 #   include "intmath.h"
 #endif
 
-#ifndef av_log2
-#   define av_log2       av_log2_c
-#endif
-#ifndef av_log2_16bit
-#   define av_log2_16bit av_log2_16bit_c
-#endif
+/* Pull in unguarded fallback defines at the end of this file. */
+#include "common.h"
 
 /**
- * Clips a signed integer value into the amin-amax range.
+ * Clip a signed integer value into the amin-amax range.
  * @param a value to clip
  * @param amin minimum value of the clip range
  * @param amax maximum value of the clip range
  * @return clipped value
  */
-static inline av_const int av_clip(int a, int amin, int amax)
+static av_always_inline av_const int av_clip_c(int a, int amin, int amax)
 {
     if      (a < amin) return amin;
     else if (a > amax) return amax;
@@ -112,87 +115,110 @@ static inline av_const int av_clip(int a, int amin, int amax)
 }
 
 /**
- * Clips a signed integer value into the 0-255 range.
+ * Clip a signed integer value into the 0-255 range.
  * @param a value to clip
  * @return clipped value
  */
-static inline av_const uint8_t av_clip_uint8(int a)
+static av_always_inline av_const uint8_t av_clip_uint8_c(int a)
 {
     if (a&(~0xFF)) return (-a)>>31;
     else           return a;
 }
 
 /**
- * Clips a signed integer value into the 0-65535 range.
+ * Clip a signed integer value into the -128,127 range.
  * @param a value to clip
  * @return clipped value
  */
-static inline av_const uint16_t av_clip_uint16(int a)
+static av_always_inline av_const int8_t av_clip_int8_c(int a)
+{
+    if ((a+0x80) & ~0xFF) return (a>>31) ^ 0x7F;
+    else                  return a;
+}
+
+/**
+ * Clip a signed integer value into the 0-65535 range.
+ * @param a value to clip
+ * @return clipped value
+ */
+static av_always_inline av_const uint16_t av_clip_uint16_c(int a)
 {
     if (a&(~0xFFFF)) return (-a)>>31;
     else             return a;
 }
 
 /**
- * Clips a signed integer value into the -32768,32767 range.
+ * Clip a signed integer value into the -32768,32767 range.
  * @param a value to clip
  * @return clipped value
  */
-static inline av_const int16_t av_clip_int16(int a)
+static av_always_inline av_const int16_t av_clip_int16_c(int a)
 {
     if ((a+0x8000) & ~0xFFFF) return (a>>31) ^ 0x7FFF;
     else                      return a;
 }
 
 /**
- * Clips a signed 64-bit integer value into the -2147483648,2147483647 range.
+ * Clip a signed 64-bit integer value into the -2147483648,2147483647 range.
  * @param a value to clip
  * @return clipped value
  */
-static inline av_const int32_t av_clipl_int32(int64_t a)
+static av_always_inline av_const int32_t av_clipl_int32_c(int64_t a)
 {
     if ((a+0x80000000u) & ~UINT64_C(0xFFFFFFFF)) return (a>>63) ^ 0x7FFFFFFF;
     else                                         return a;
 }
 
 /**
- * Clips a float value into the amin-amax range.
+ * Clip a float value into the amin-amax range.
  * @param a value to clip
  * @param amin minimum value of the clip range
  * @param amax maximum value of the clip range
  * @return clipped value
  */
-static inline av_const float av_clipf(float a, float amin, float amax)
+static av_always_inline av_const float av_clipf_c(float a, float amin, float amax)
 {
     if      (a < amin) return amin;
     else if (a > amax) return amax;
     else               return a;
 }
 
-/** Computes ceil(log2(x)).
+/** Compute ceil(log2(x)).
  * @param x value used to compute ceil(log2(x))
  * @return computed ceiling of log2(x)
  */
-static inline av_const int av_ceil_log2(int x)
+static av_always_inline av_const int av_ceil_log2_c(int x)
 {
     return av_log2((x - 1) << 1);
 }
 
-#define MKTAG(a,b,c,d) (a | (b << 8) | (c << 16) | (d << 24))
-#define MKBETAG(a,b,c,d) (d | (c << 8) | (b << 16) | (a << 24))
+/**
+ * Count number of bits set to one in x
+ * @param x value to count bits of
+ * @return the number of bits set to one in x
+ */
+static av_always_inline av_const int av_popcount_c(uint32_t x)
+{
+    x -= (x >> 1) & 0x55555555;
+    x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
+    x = (x + (x >> 4)) & 0x0F0F0F0F;
+    x += x >> 8;
+    return (x + (x >> 16)) & 0x3F;
+}
 
-/*!
- * \def GET_UTF8(val, GET_BYTE, ERROR)
- * Converts a UTF-8 character (up to 4 bytes long) to its 32-bit UCS-4 encoded form
- * \param val is the output and should be of type uint32_t. It holds the converted
- * UCS-4 character and should be a left value.
- * \param GET_BYTE gets UTF-8 encoded bytes from any proper source. It can be
- * a function or a statement whose return value or evaluated value is of type
- * uint8_t. It will be executed up to 4 times for values in the valid UTF-8 range,
- * and up to 7 times in the general case.
- * \param ERROR action that should be taken when an invalid UTF-8 byte is returned
- * from GET_BYTE. It should be a statement that jumps out of the macro,
- * like exit(), goto, return, break, or continue.
+#define MKTAG(a,b,c,d) ((a) | ((b) << 8) | ((c) << 16) | ((d) << 24))
+#define MKBETAG(a,b,c,d) ((d) | ((c) << 8) | ((b) << 16) | ((a) << 24))
+
+/**
+ * Convert a UTF-8 character (up to 4 bytes) to its 32-bit UCS-4 encoded form.
+ *
+ * @param val      Output value, must be an lvalue of type uint32_t.
+ * @param GET_BYTE Expression reading one byte from the input.
+ *                 Evaluated up to 7 times (4 for the currently
+ *                 assigned Unicode range).  With a memory buffer
+ *                 input, this could be *ptr++.
+ * @param ERROR    Expression to be evaluated on invalid input,
+ *                 typically a goto statement.
  */
 #define GET_UTF8(val, GET_BYTE, ERROR)\
     val= GET_BYTE;\
@@ -209,17 +235,14 @@ static inline av_const int av_ceil_log2(int x)
         }\
     }
 
-/*!
- * \def GET_UTF16(val, GET_16BIT, ERROR)
- * Converts a UTF-16 character (2 or 4 bytes) to its 32-bit UCS-4 encoded form
- * \param val is the output and should be of type uint32_t. It holds the converted
- * UCS-4 character and should be a left value.
- * \param GET_16BIT gets two bytes of UTF-16 encoded data converted to native endianness.
- * It can be a function or a statement whose return value or evaluated value is of type
- * uint16_t. It will be executed up to 2 times.
- * \param ERROR action that should be taken when an invalid UTF-16 surrogate is
- * returned from GET_BYTE. It should be a statement that jumps out of the macro,
- * like exit(), goto, return, break, or continue.
+/**
+ * Convert a UTF-16 character (2 or 4 bytes) to its 32-bit UCS-4 encoded form.
+ *
+ * @param val       Output value, must be an lvalue of type uint32_t.
+ * @param GET_16BIT Expression returning two bytes of UTF-16 data converted
+ *                  to native byte order.  Evaluated one or two times.
+ * @param ERROR     Expression to be evaluated on invalid input,
+ *                  typically a goto statement.
  */
 #define GET_UTF16(val, GET_16BIT, ERROR)\
     val = GET_16BIT;\
@@ -235,7 +258,7 @@ static inline av_const int av_ceil_log2(int x)
 
 /*!
  * \def PUT_UTF8(val, tmp, PUT_BYTE)
- * Converts a 32-bit Unicode character to its UTF-8 encoded form (up to 4 bytes long).
+ * Convert a 32-bit Unicode character to its UTF-8 encoded form (up to 4 bytes long).
  * \param val is an input-only argument and should be of type uint32_t. It holds
  * a UCS-4 encoded Unicode character that is to be converted to UTF-8. If
  * val is given as a function it is executed only once.
@@ -271,7 +294,7 @@ static inline av_const int av_ceil_log2(int x)
 
 /*!
  * \def PUT_UTF16(val, tmp, PUT_16BIT)
- * Converts a 32-bit Unicode character to its UTF-16 encoded form (2 or 4 bytes).
+ * Convert a 32-bit Unicode character to its UTF-16 encoded form (2 or 4 bytes).
  * \param val is an input-only argument and should be of type uint32_t. It holds
  * a UCS-4 encoded Unicode character that is to be converted to UTF-16. If
  * val is given as a function it is executed only once.
@@ -306,3 +329,42 @@ static inline av_const int av_ceil_log2(int x)
 #endif /* HAVE_AV_CONFIG_H */
 
 #endif /* AVUTIL_COMMON_H */
+
+/*
+ * The following definitions are outside the multiple inclusion guard
+ * to ensure they are immediately available in intmath.h.
+ */
+
+#ifndef av_log2
+#   define av_log2       av_log2_c
+#endif
+#ifndef av_log2_16bit
+#   define av_log2_16bit av_log2_16bit_c
+#endif
+#ifndef av_ceil_log2
+#   define av_ceil_log2     av_ceil_log2_c
+#endif
+#ifndef av_clip
+#   define av_clip          av_clip_c
+#endif
+#ifndef av_clip_uint8
+#   define av_clip_uint8    av_clip_uint8_c
+#endif
+#ifndef av_clip_int8
+#   define av_clip_int8     av_clip_int8_c
+#endif
+#ifndef av_clip_uint16
+#   define av_clip_uint16   av_clip_uint16_c
+#endif
+#ifndef av_clip_int16
+#   define av_clip_int16    av_clip_int16_c
+#endif
+#ifndef av_clipl_int32
+#   define av_clipl_int32   av_clipl_int32_c
+#endif
+#ifndef av_clipf
+#   define av_clipf         av_clipf_c
+#endif
+#ifndef av_popcount
+#   define av_popcount      av_popcount_c
+#endif
diff --git a/libavutil/cpu.c b/libavutil/cpu.c
new file mode 100644
index 0000000..ddccd00
--- /dev/null
+++ b/libavutil/cpu.c
@@ -0,0 +1,71 @@
+/*
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "cpu.h"
+#include "config.h"
+
+int av_get_cpu_flags(void)
+{
+    static int flags, checked;
+
+    if (checked)
+        return flags;
+
+    if (ARCH_ARM) flags = ff_get_cpu_flags_arm();
+    if (ARCH_PPC) flags = ff_get_cpu_flags_ppc();
+    if (ARCH_X86) flags = ff_get_cpu_flags_x86();
+
+    checked = 1;
+    return flags;
+}
+
+#ifdef TEST
+
+#undef printf
+#include <stdio.h>
+
+int main(void)
+{
+    int cpu_flags = av_get_cpu_flags();
+
+    printf("cpu_flags = 0x%08X\n", cpu_flags);
+    printf("cpu_flags = %s%s%s%s%s%s%s%s%s%s%s%s%s\n",
+#if   ARCH_ARM
+           cpu_flags & AV_CPU_FLAG_IWMMXT   ? "IWMMXT "     : "",
+#elif ARCH_PPC
+           cpu_flags & AV_CPU_FLAG_ALTIVEC  ? "ALTIVEC "    : "",
+#elif ARCH_X86
+           cpu_flags & AV_CPU_FLAG_MMX      ? "MMX "        : "",
+           cpu_flags & AV_CPU_FLAG_MMX2     ? "MMX2 "       : "",
+           cpu_flags & AV_CPU_FLAG_SSE      ? "SSE "        : "",
+           cpu_flags & AV_CPU_FLAG_SSE2     ? "SSE2 "       : "",
+           cpu_flags & AV_CPU_FLAG_SSE2SLOW ? "SSE2(slow) " : "",
+           cpu_flags & AV_CPU_FLAG_SSE3     ? "SSE3 "       : "",
+           cpu_flags & AV_CPU_FLAG_SSE3SLOW ? "SSE3(slow) " : "",
+           cpu_flags & AV_CPU_FLAG_SSSE3    ? "SSSE3 "      : "",
+           cpu_flags & AV_CPU_FLAG_ATOM     ? "Atom "       : "",
+           cpu_flags & AV_CPU_FLAG_SSE4     ? "SSE4.1 "     : "",
+           cpu_flags & AV_CPU_FLAG_SSE42    ? "SSE4.2 "     : "",
+           cpu_flags & AV_CPU_FLAG_AVX      ? "AVX "        : "",
+           cpu_flags & AV_CPU_FLAG_3DNOW    ? "3DNow "      : "",
+           cpu_flags & AV_CPU_FLAG_3DNOWEXT ? "3DNowExt "   : "");
+#endif
+    return 0;
+}
+
+#endif
diff --git a/libavutil/cpu.h b/libavutil/cpu.h
new file mode 100644
index 0000000..11ba368
--- /dev/null
+++ b/libavutil/cpu.h
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_CPU_H
+#define AVUTIL_CPU_H
+
+#define AV_CPU_FLAG_FORCE    0x80000000 /* force usage of selected flags (OR) */
+
+    /* lower 16 bits - CPU features */
+#define AV_CPU_FLAG_MMX          0x0001 ///< standard MMX
+#define AV_CPU_FLAG_MMX2         0x0002 ///< SSE integer functions or AMD MMX ext
+#define AV_CPU_FLAG_3DNOW        0x0004 ///< AMD 3DNOW
+#define AV_CPU_FLAG_SSE          0x0008 ///< SSE functions
+#define AV_CPU_FLAG_SSE2         0x0010 ///< PIV SSE2 functions
+#define AV_CPU_FLAG_SSE2SLOW 0x40000000 ///< SSE2 supported, but usually not faster
+#define AV_CPU_FLAG_3DNOWEXT     0x0020 ///< AMD 3DNowExt
+#define AV_CPU_FLAG_SSE3         0x0040 ///< Prescott SSE3 functions
+#define AV_CPU_FLAG_SSE3SLOW 0x20000000 ///< SSE3 supported, but usually not faster
+#define AV_CPU_FLAG_SSSE3        0x0080 ///< Conroe SSSE3 functions
+#define AV_CPU_FLAG_ATOM     0x10000000 ///< Atom processor, some SSSE3 instructions are slower
+#define AV_CPU_FLAG_SSE4         0x0100 ///< Penryn SSE4.1 functions
+#define AV_CPU_FLAG_SSE42        0x0200 ///< Nehalem SSE4.2 functions
+#define AV_CPU_FLAG_AVX          0x4000 ///< AVX functions: requires OS support even if YMM registers aren't used
+#define AV_CPU_FLAG_IWMMXT       0x0100 ///< XScale IWMMXT
+#define AV_CPU_FLAG_ALTIVEC      0x0001 ///< standard
+
+/**
+ * Return the flags which specify extensions supported by the CPU.
+ */
+int av_get_cpu_flags(void);
+
+/* The following CPU-specific functions shall not be called directly. */
+int ff_get_cpu_flags_arm(void);
+int ff_get_cpu_flags_ppc(void);
+int ff_get_cpu_flags_x86(void);
+
+#endif  /* AVUTIL_CPU_H */
diff --git a/libavutil/crc.c b/libavutil/crc.c
index 2719bae..6c9f928 100644
--- a/libavutil/crc.c
+++ b/libavutil/crc.c
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -41,19 +41,19 @@ static AVCRC av_crc_table[AV_CRC_MAX][257];
 #endif
 
 /**
- * Initializes a CRC table.
+ * Initialize a CRC table.
  * @param ctx must be an array of size sizeof(AVCRC)*257 or sizeof(AVCRC)*1024
- * @param cts_size size of ctx in bytes
  * @param le If 1, the lowest bit represents the coefficient for the highest
  *           exponent of the corresponding polynomial (both for poly and
  *           actual CRC).
  *           If 0, you must swap the CRC parameter and the result of av_crc
  *           if you need the standard representation (can be simplified in
  *           most cases to e.g. bswap16):
- *           bswap_32(crc << (32-bits))
+ *           av_bswap32(crc << (32-bits))
  * @param bits number of bits for the CRC
  * @param poly generator polynomial without the x**bits coefficient, in the
  *             representation as specified by le
+ * @param ctx_size size of ctx in bytes
  * @return <0 on failure
  */
 int av_crc_init(AVCRC *ctx, int le, int bits, uint32_t poly, int ctx_size){
@@ -73,7 +73,7 @@ int av_crc_init(AVCRC *ctx, int le, int bits, uint32_t poly, int ctx_size){
         } else {
             for (c = i << 24, j = 0; j < 8; j++)
                 c = (c<<1) ^ ((poly<<(32-bits)) & (((int32_t)c)>>31) );
-            ctx[i] = bswap_32(c);
+            ctx[i] = av_bswap32(c);
         }
     }
     ctx[256]=1;
@@ -88,7 +88,7 @@ int av_crc_init(AVCRC *ctx, int le, int bits, uint32_t poly, int ctx_size){
 }
 
 /**
- * Gets an initialized standard CRC table.
+ * Get an initialized standard CRC table.
  * @param crc_id ID of a standard CRC
  * @return a pointer to the CRC table or NULL on failure
  */
@@ -106,7 +106,7 @@ const AVCRC *av_crc_get_table(AVCRCId crc_id){
 }
 
 /**
- * Calculates the CRC of a block.
+ * Calculate the CRC of a block.
  * @param crc CRC of previous blocks if any or initial value for CRC
  * @return CRC updated with the data from the given block
  *
@@ -121,7 +121,7 @@ uint32_t av_crc(const AVCRC *ctx, uint32_t crc, const uint8_t *buffer, size_t le
             crc = ctx[((uint8_t)crc) ^ *buffer++] ^ (crc >> 8);
 
         while(buffer<end-3){
-            crc ^= le2me_32(*(const uint32_t*)buffer); buffer+=4;
+            crc ^= av_le2ne32(*(const uint32_t*)buffer); buffer+=4;
             crc =  ctx[3*256 + ( crc     &0xFF)]
                   ^ctx[2*256 + ((crc>>8 )&0xFF)]
                   ^ctx[1*256 + ((crc>>16)&0xFF)]
diff --git a/libavutil/crc.h b/libavutil/crc.h
index 6c0baab..a934119 100644
--- a/libavutil/crc.h
+++ b/libavutil/crc.h
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavutil/crc_data.h b/libavutil/crc_data.h
index afa25e7..8e4e6af 100644
--- a/libavutil/crc_data.h
+++ b/libavutil/crc_data.h
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2008 Aurelien Jacobs <aurel at gnuage.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavutil/des.c b/libavutil/des.c
index ab66a0b..e8009a2 100644
--- a/libavutil/des.c
+++ b/libavutil/des.c
@@ -2,20 +2,20 @@
  * DES encryption/decryption
  * Copyright (c) 2007 Reimar Doeffinger
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #include <inttypes.h>
@@ -297,10 +297,10 @@ int av_des_init(AVDES *d, const uint8_t *key, int key_bits, int decrypt) {
 }
 
 void av_des_crypt(AVDES *d, uint8_t *dst, const uint8_t *src, int count, uint8_t *iv, int decrypt) {
-    uint64_t iv_val = iv ? be2me_64(*(uint64_t *)iv) : 0;
+    uint64_t iv_val = iv ? av_be2ne64(*(uint64_t *)iv) : 0;
     while (count-- > 0) {
         uint64_t dst_val;
-        uint64_t src_val = src ? be2me_64(*(const uint64_t *)src) : 0;
+        uint64_t src_val = src ? av_be2ne64(*(const uint64_t *)src) : 0;
         if (decrypt) {
             uint64_t tmp = src_val;
             if (d->triple_des) {
@@ -317,12 +317,12 @@ void av_des_crypt(AVDES *d, uint8_t *dst, const uint8_t *src, int count, uint8_t
             }
             iv_val = iv ? dst_val : 0;
         }
-        *(uint64_t *)dst = be2me_64(dst_val);
+        *(uint64_t *)dst = av_be2ne64(dst_val);
         src += 8;
         dst += 8;
     }
     if (iv)
-        *(uint64_t *)iv = be2me_64(iv_val);
+        *(uint64_t *)iv = av_be2ne64(iv_val);
 }
 
 #ifdef TEST
diff --git a/libavutil/des.h b/libavutil/des.h
index e80bdd3..5a6d4a1 100644
--- a/libavutil/des.h
+++ b/libavutil/des.h
@@ -2,20 +2,20 @@
  * DES encryption/decryption
  * Copyright (c) 2007 Reimar Doeffinger
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavutil/error.c b/libavutil/error.c
index b6d6019..978e543 100644
--- a/libavutil/error.c
+++ b/libavutil/error.c
@@ -1,18 +1,18 @@
 /*
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -28,7 +28,16 @@ int av_strerror(int errnum, char *errbuf, size_t errbuf_size)
     case AVERROR_EOF:               errstr = "End of file"; break;
     case AVERROR_INVALIDDATA:       errstr = "Invalid data found when processing input"; break;
     case AVERROR_NUMEXPECTED:       errstr = "Number syntax expected in filename"; break;
-    case AVERROR_PATCHWELCOME:      errstr = "Not yet implemented in FFmpeg, patches welcome"; break;
+    case AVERROR_PATCHWELCOME:      errstr = "Not yet implemented in Libav, patches welcome"; break;
+    case AVERROR_DEMUXER_NOT_FOUND: errstr = "Demuxer not found"; break;
+    case AVERROR_MUXER_NOT_FOUND:   errstr = "Muxer not found"; break;
+    case AVERROR_DECODER_NOT_FOUND: errstr = "Decoder not found"; break;
+    case AVERROR_ENCODER_NOT_FOUND: errstr = "Encoder not found"; break;
+    case AVERROR_PROTOCOL_NOT_FOUND:errstr = "Protocol not found"; break;
+    case AVERROR_FILTER_NOT_FOUND:  errstr = "Filter not found"; break;
+    case AVERROR_BSF_NOT_FOUND:     errstr = "Bitstream filter not found"; break;
+    case AVERROR_STREAM_NOT_FOUND:  errstr = "Stream not found"; break;
+    case AVERROR_EXIT:              errstr = "Immediate exit requested"; break;
     }
 
     if (errstr) {
diff --git a/libavutil/error.h b/libavutil/error.h
index 13a9a35..8c83ecd 100644
--- a/libavutil/error.h
+++ b/libavutil/error.h
@@ -1,18 +1,18 @@
 /*
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -50,19 +50,32 @@
 
 #define AVERROR_EOF         AVERROR(EPIPE)   ///< End of file
 
-#define AVERROR_PATCHWELCOME    (-MKTAG('P','A','W','E')) ///< Not yet implemented in FFmpeg, patches welcome
+#define AVERROR_PATCHWELCOME    (-MKTAG('P','A','W','E')) ///< Not yet implemented in Libav, patches welcome
 
 #if LIBAVUTIL_VERSION_MAJOR > 50
 #define AVERROR_INVALIDDATA     (-MKTAG('I','N','D','A')) ///< Invalid data found when processing input
 #define AVERROR_NUMEXPECTED     (-MKTAG('N','U','E','X')) ///< Number syntax expected in filename
 #endif
 
+#define AVERROR_DEMUXER_NOT_FOUND  (-MKTAG(0xF8,'D','E','M')) ///< Demuxer not found
+#define AVERROR_MUXER_NOT_FOUND    (-MKTAG(0xF8,'M','U','X')) ///< Muxer not found
+#define AVERROR_DECODER_NOT_FOUND  (-MKTAG(0xF8,'D','E','C')) ///< Decoder not found
+#define AVERROR_ENCODER_NOT_FOUND  (-MKTAG(0xF8,'E','N','C')) ///< Encoder not found
+#define AVERROR_PROTOCOL_NOT_FOUND (-MKTAG(0xF8,'P','R','O')) ///< Protocol not found
+#define AVERROR_FILTER_NOT_FOUND   (-MKTAG(0xF8,'F','I','L')) ///< Filter not found
+#define AVERROR_BSF_NOT_FOUND      (-MKTAG(0xF8,'B','S','F')) ///< Bitstream filter not found
+#define AVERROR_STREAM_NOT_FOUND   (-MKTAG(0xF8,'S','T','R')) ///< Stream not found
+
+#define AVERROR_EXIT (-MKTAG('E','X','I','T')) ///< Immediate exit was requested; the called function should not be restarted
+
 /**
- * Puts a description of the AVERROR code errnum in errbuf.
+ * Put a description of the AVERROR code errnum in errbuf.
  * In case of failure the global variable errno is set to indicate the
  * error. Even in case of failure av_strerror() will print a generic
  * error message indicating the errnum provided to errbuf.
  *
+ * @param errnum      error code to describe
+ * @param errbuf      buffer to which description is written
  * @param errbuf_size the size in bytes of errbuf
  * @return 0 on success, a negative value if a description for errnum
  * cannot be found
diff --git a/libavutil/eval.c b/libavutil/eval.c
new file mode 100644
index 0000000..7488a31
--- /dev/null
+++ b/libavutil/eval.c
@@ -0,0 +1,660 @@
+/*
+ * Copyright (c) 2002-2006 Michael Niedermayer <michaelni at gmx.at>
+ * Copyright (c) 2006 Oded Shimon <ods15 at ods15.dyndns.org>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * simple arithmetic expression evaluator.
+ *
+ * see http://joe.hotchkiss.com/programming/eval/eval.html
+ */
+
+#include "libavutil/avutil.h"
+#include "eval.h"
+
+typedef struct Parser {
+    const AVClass *class;
+    int stack_index;
+    char *s;
+    const double *const_values;
+    const char * const *const_names;          // NULL terminated
+    double (* const *funcs1)(void *, double a);           // NULL terminated
+    const char * const *func1_names;          // NULL terminated
+    double (* const *funcs2)(void *, double a, double b); // NULL terminated
+    const char * const *func2_names;          // NULL terminated
+    void *opaque;
+    int log_offset;
+    void *log_ctx;
+#define VARS 10
+    double var[VARS];
+} Parser;
+
+static const AVClass class = { "Eval", av_default_item_name, NULL, LIBAVUTIL_VERSION_INT, offsetof(Parser,log_offset), offsetof(Parser,log_ctx) };
+
+static const int8_t si_prefixes['z' - 'E' + 1] = {
+    ['y'-'E']= -24,
+    ['z'-'E']= -21,
+    ['a'-'E']= -18,
+    ['f'-'E']= -15,
+    ['p'-'E']= -12,
+    ['n'-'E']= - 9,
+    ['u'-'E']= - 6,
+    ['m'-'E']= - 3,
+    ['c'-'E']= - 2,
+    ['d'-'E']= - 1,
+    ['h'-'E']=   2,
+    ['k'-'E']=   3,
+    ['K'-'E']=   3,
+    ['M'-'E']=   6,
+    ['G'-'E']=   9,
+    ['T'-'E']=  12,
+    ['P'-'E']=  15,
+    ['E'-'E']=  18,
+    ['Z'-'E']=  21,
+    ['Y'-'E']=  24,
+};
+
+double av_strtod(const char *numstr, char **tail)
+{
+    double d;
+    char *next;
+    d = strtod(numstr, &next);
+    /* if parsing succeeded, check for and interpret postfixes */
+    if (next!=numstr) {
+        if (*next >= 'E' && *next <= 'z') {
+            int e= si_prefixes[*next - 'E'];
+            if (e) {
+                if (next[1] == 'i') {
+                    d*= pow( 2, e/0.3);
+                    next+=2;
+                } else {
+                    d*= pow(10, e);
+                    next++;
+                }
+            }
+        }
+
+        if (*next=='B') {
+            d*=8;
+            next++;
+        }
+    }
+    /* if requested, fill in tail with the position after the last parsed
+       character */
+    if (tail)
+        *tail = next;
+    return d;
+}
+
+#define IS_IDENTIFIER_CHAR(c) ((c) - '0' <= 9U || (c) - 'a' <= 25U || (c) - 'A' <= 25U || (c) == '_')
+
+static int strmatch(const char *s, const char *prefix)
+{
+    int i;
+    for (i=0; prefix[i]; i++) {
+        if (prefix[i] != s[i]) return 0;
+    }
+    /* return 1 only if the s identifier is terminated */
+    return !IS_IDENTIFIER_CHAR(s[i]);
+}
+
+struct AVExpr {
+    enum {
+        e_value, e_const, e_func0, e_func1, e_func2,
+        e_squish, e_gauss, e_ld, e_isnan,
+        e_mod, e_max, e_min, e_eq, e_gt, e_gte,
+        e_pow, e_mul, e_div, e_add,
+        e_last, e_st, e_while, e_floor, e_ceil, e_trunc,
+    } type;
+    double value; // is sign in other types
+    union {
+        int const_index;
+        double (*func0)(double);
+        double (*func1)(void *, double);
+        double (*func2)(void *, double, double);
+    } a;
+    struct AVExpr *param[2];
+};
+
+static double eval_expr(Parser *p, AVExpr *e)
+{
+    switch (e->type) {
+        case e_value:  return e->value;
+        case e_const:  return e->value * p->const_values[e->a.const_index];
+        case e_func0:  return e->value * e->a.func0(eval_expr(p, e->param[0]));
+        case e_func1:  return e->value * e->a.func1(p->opaque, eval_expr(p, e->param[0]));
+        case e_func2:  return e->value * e->a.func2(p->opaque, eval_expr(p, e->param[0]), eval_expr(p, e->param[1]));
+        case e_squish: return 1/(1+exp(4*eval_expr(p, e->param[0])));
+        case e_gauss: { double d = eval_expr(p, e->param[0]); return exp(-d*d/2)/sqrt(2*M_PI); }
+        case e_ld:     return e->value * p->var[av_clip(eval_expr(p, e->param[0]), 0, VARS-1)];
+        case e_isnan:  return e->value * !!isnan(eval_expr(p, e->param[0]));
+        case e_floor:  return e->value * floor(eval_expr(p, e->param[0]));
+        case e_ceil :  return e->value * ceil (eval_expr(p, e->param[0]));
+        case e_trunc:  return e->value * trunc(eval_expr(p, e->param[0]));
+        case e_while: {
+            double d = NAN;
+            while (eval_expr(p, e->param[0]))
+                d=eval_expr(p, e->param[1]);
+            return d;
+        }
+        default: {
+            double d = eval_expr(p, e->param[0]);
+            double d2 = eval_expr(p, e->param[1]);
+            switch (e->type) {
+                case e_mod: return e->value * (d - floor(d/d2)*d2);
+                case e_max: return e->value * (d >  d2 ?   d : d2);
+                case e_min: return e->value * (d <  d2 ?   d : d2);
+                case e_eq:  return e->value * (d == d2 ? 1.0 : 0.0);
+                case e_gt:  return e->value * (d >  d2 ? 1.0 : 0.0);
+                case e_gte: return e->value * (d >= d2 ? 1.0 : 0.0);
+                case e_pow: return e->value * pow(d, d2);
+                case e_mul: return e->value * (d * d2);
+                case e_div: return e->value * (d / d2);
+                case e_add: return e->value * (d + d2);
+                case e_last:return e->value * d2;
+                case e_st : return e->value * (p->var[av_clip(d, 0, VARS-1)]= d2);
+            }
+        }
+    }
+    return NAN;
+}
+
+static int parse_expr(AVExpr **e, Parser *p);
+
+void av_expr_free(AVExpr *e)
+{
+    if (!e) return;
+    av_expr_free(e->param[0]);
+    av_expr_free(e->param[1]);
+    av_freep(&e);
+}
+
+static int parse_primary(AVExpr **e, Parser *p)
+{
+    AVExpr *d = av_mallocz(sizeof(AVExpr));
+    char *next = p->s, *s0 = p->s;
+    int ret, i;
+
+    if (!d)
+        return AVERROR(ENOMEM);
+
+    /* number */
+    d->value = av_strtod(p->s, &next);
+    if (next != p->s) {
+        d->type = e_value;
+        p->s= next;
+        *e = d;
+        return 0;
+    }
+    d->value = 1;
+
+    /* named constants */
+    for (i=0; p->const_names && p->const_names[i]; i++) {
+        if (strmatch(p->s, p->const_names[i])) {
+            p->s+= strlen(p->const_names[i]);
+            d->type = e_const;
+            d->a.const_index = i;
+            *e = d;
+            return 0;
+        }
+    }
+
+    p->s= strchr(p->s, '(');
+    if (p->s==NULL) {
+        av_log(p, AV_LOG_ERROR, "Undefined constant or missing '(' in '%s'\n", s0);
+        p->s= next;
+        av_expr_free(d);
+        return AVERROR(EINVAL);
+    }
+    p->s++; // "("
+    if (*next == '(') { // special case do-nothing
+        av_freep(&d);
+        if ((ret = parse_expr(&d, p)) < 0)
+            return ret;
+        if (p->s[0] != ')') {
+            av_log(p, AV_LOG_ERROR, "Missing ')' in '%s'\n", s0);
+            av_expr_free(d);
+            return AVERROR(EINVAL);
+        }
+        p->s++; // ")"
+        *e = d;
+        return 0;
+    }
+    if ((ret = parse_expr(&(d->param[0]), p)) < 0) {
+        av_expr_free(d);
+        return ret;
+    }
+    if (p->s[0]== ',') {
+        p->s++; // ","
+        parse_expr(&d->param[1], p);
+    }
+    if (p->s[0] != ')') {
+        av_log(p, AV_LOG_ERROR, "Missing ')' or too many args in '%s'\n", s0);
+        av_expr_free(d);
+        return AVERROR(EINVAL);
+    }
+    p->s++; // ")"
+
+    d->type = e_func0;
+         if (strmatch(next, "sinh"  )) d->a.func0 = sinh;
+    else if (strmatch(next, "cosh"  )) d->a.func0 = cosh;
+    else if (strmatch(next, "tanh"  )) d->a.func0 = tanh;
+    else if (strmatch(next, "sin"   )) d->a.func0 = sin;
+    else if (strmatch(next, "cos"   )) d->a.func0 = cos;
+    else if (strmatch(next, "tan"   )) d->a.func0 = tan;
+    else if (strmatch(next, "atan"  )) d->a.func0 = atan;
+    else if (strmatch(next, "asin"  )) d->a.func0 = asin;
+    else if (strmatch(next, "acos"  )) d->a.func0 = acos;
+    else if (strmatch(next, "exp"   )) d->a.func0 = exp;
+    else if (strmatch(next, "log"   )) d->a.func0 = log;
+    else if (strmatch(next, "abs"   )) d->a.func0 = fabs;
+    else if (strmatch(next, "squish")) d->type = e_squish;
+    else if (strmatch(next, "gauss" )) d->type = e_gauss;
+    else if (strmatch(next, "mod"   )) d->type = e_mod;
+    else if (strmatch(next, "max"   )) d->type = e_max;
+    else if (strmatch(next, "min"   )) d->type = e_min;
+    else if (strmatch(next, "eq"    )) d->type = e_eq;
+    else if (strmatch(next, "gte"   )) d->type = e_gte;
+    else if (strmatch(next, "gt"    )) d->type = e_gt;
+    else if (strmatch(next, "lte"   )) { AVExpr *tmp = d->param[1]; d->param[1] = d->param[0]; d->param[0] = tmp; d->type = e_gt; }
+    else if (strmatch(next, "lt"    )) { AVExpr *tmp = d->param[1]; d->param[1] = d->param[0]; d->param[0] = tmp; d->type = e_gte; }
+    else if (strmatch(next, "ld"    )) d->type = e_ld;
+    else if (strmatch(next, "isnan" )) d->type = e_isnan;
+    else if (strmatch(next, "st"    )) d->type = e_st;
+    else if (strmatch(next, "while" )) d->type = e_while;
+    else if (strmatch(next, "floor" )) d->type = e_floor;
+    else if (strmatch(next, "ceil"  )) d->type = e_ceil;
+    else if (strmatch(next, "trunc" )) d->type = e_trunc;
+    else {
+        for (i=0; p->func1_names && p->func1_names[i]; i++) {
+            if (strmatch(next, p->func1_names[i])) {
+                d->a.func1 = p->funcs1[i];
+                d->type = e_func1;
+                *e = d;
+                return 0;
+            }
+        }
+
+        for (i=0; p->func2_names && p->func2_names[i]; i++) {
+            if (strmatch(next, p->func2_names[i])) {
+                d->a.func2 = p->funcs2[i];
+                d->type = e_func2;
+                *e = d;
+                return 0;
+            }
+        }
+
+        av_log(p, AV_LOG_ERROR, "Unknown function in '%s'\n", s0);
+        av_expr_free(d);
+        return AVERROR(EINVAL);
+    }
+
+    *e = d;
+    return 0;
+}
+
+static AVExpr *new_eval_expr(int type, int value, AVExpr *p0, AVExpr *p1)
+{
+    AVExpr *e = av_mallocz(sizeof(AVExpr));
+    if (!e)
+        return NULL;
+    e->type     =type   ;
+    e->value    =value  ;
+    e->param[0] =p0     ;
+    e->param[1] =p1     ;
+    return e;
+}
+
+static int parse_pow(AVExpr **e, Parser *p, int *sign)
+{
+    *sign= (*p->s == '+') - (*p->s == '-');
+    p->s += *sign&1;
+    return parse_primary(e, p);
+}
+
+static int parse_factor(AVExpr **e, Parser *p)
+{
+    int sign, sign2, ret;
+    AVExpr *e0, *e1, *e2;
+    if ((ret = parse_pow(&e0, p, &sign)) < 0)
+        return ret;
+    while(p->s[0]=='^'){
+        e1 = e0;
+        p->s++;
+        if ((ret = parse_pow(&e2, p, &sign2)) < 0) {
+            av_expr_free(e1);
+            return ret;
+        }
+        e0 = new_eval_expr(e_pow, 1, e1, e2);
+        if (!e0) {
+            av_expr_free(e1);
+            av_expr_free(e2);
+            return AVERROR(ENOMEM);
+        }
+        if (e0->param[1]) e0->param[1]->value *= (sign2|1);
+    }
+    if (e0) e0->value *= (sign|1);
+
+    *e = e0;
+    return 0;
+}
+
+static int parse_term(AVExpr **e, Parser *p)
+{
+    int ret;
+    AVExpr *e0, *e1, *e2;
+    if ((ret = parse_factor(&e0, p)) < 0)
+        return ret;
+    while (p->s[0]=='*' || p->s[0]=='/') {
+        int c= *p->s++;
+        e1 = e0;
+        if ((ret = parse_factor(&e2, p)) < 0) {
+            av_expr_free(e1);
+            return ret;
+        }
+        e0 = new_eval_expr(c == '*' ? e_mul : e_div, 1, e1, e2);
+        if (!e0) {
+            av_expr_free(e1);
+            av_expr_free(e2);
+            return AVERROR(ENOMEM);
+        }
+    }
+    *e = e0;
+    return 0;
+}
+
+static int parse_subexpr(AVExpr **e, Parser *p)
+{
+    int ret;
+    AVExpr *e0, *e1, *e2;
+    if ((ret = parse_term(&e0, p)) < 0)
+        return ret;
+    while (*p->s == '+' || *p->s == '-') {
+        e1 = e0;
+        if ((ret = parse_term(&e2, p)) < 0) {
+            av_expr_free(e1);
+            return ret;
+        }
+        e0 = new_eval_expr(e_add, 1, e1, e2);
+        if (!e0) {
+            av_expr_free(e1);
+            av_expr_free(e2);
+            return AVERROR(ENOMEM);
+        }
+    };
+
+    *e = e0;
+    return 0;
+}
+
+static int parse_expr(AVExpr **e, Parser *p)
+{
+    int ret;
+    AVExpr *e0, *e1, *e2;
+    if (p->stack_index <= 0) //protect against stack overflows
+        return AVERROR(EINVAL);
+    p->stack_index--;
+
+    if ((ret = parse_subexpr(&e0, p)) < 0)
+        return ret;
+    while (*p->s == ';') {
+        p->s++;
+        e1 = e0;
+        if ((ret = parse_subexpr(&e2, p)) < 0) {
+            av_expr_free(e1);
+            return ret;
+        }
+        e0 = new_eval_expr(e_last, 1, e1, e2);
+        if (!e0) {
+            av_expr_free(e1);
+            av_expr_free(e2);
+            return AVERROR(ENOMEM);
+        }
+    };
+
+    p->stack_index++;
+    *e = e0;
+    return 0;
+}
+
+static int verify_expr(AVExpr *e)
+{
+    if (!e) return 0;
+    switch (e->type) {
+        case e_value:
+        case e_const: return 1;
+        case e_func0:
+        case e_func1:
+        case e_squish:
+        case e_ld:
+        case e_gauss:
+        case e_isnan:
+        case e_floor:
+        case e_ceil:
+        case e_trunc:
+            return verify_expr(e->param[0]);
+        default: return verify_expr(e->param[0]) && verify_expr(e->param[1]);
+    }
+}
+
+int av_expr_parse(AVExpr **expr, const char *s,
+                  const char * const *const_names,
+                  const char * const *func1_names, double (* const *funcs1)(void *, double),
+                  const char * const *func2_names, double (* const *funcs2)(void *, double, double),
+                  int log_offset, void *log_ctx)
+{
+    Parser p;
+    AVExpr *e = NULL;
+    char *w = av_malloc(strlen(s) + 1);
+    char *wp = w;
+    const char *s0 = s;
+    int ret = 0;
+
+    if (!w)
+        return AVERROR(ENOMEM);
+
+    while (*s)
+        if (!isspace(*s++)) *wp++ = s[-1];
+    *wp++ = 0;
+
+    p.class      = &class;
+    p.stack_index=100;
+    p.s= w;
+    p.const_names = const_names;
+    p.funcs1      = funcs1;
+    p.func1_names = func1_names;
+    p.funcs2      = funcs2;
+    p.func2_names = func2_names;
+    p.log_offset = log_offset;
+    p.log_ctx    = log_ctx;
+
+    if ((ret = parse_expr(&e, &p)) < 0)
+        goto end;
+    if (*p.s) {
+        av_log(&p, AV_LOG_ERROR, "Invalid chars '%s' at the end of expression '%s'\n", p.s, s0);
+        ret = AVERROR(EINVAL);
+        goto end;
+    }
+    if (!verify_expr(e)) {
+        av_expr_free(e);
+        ret = AVERROR(EINVAL);
+        goto end;
+    }
+    *expr = e;
+end:
+    av_free(w);
+    return ret;
+}
+
+double av_expr_eval(AVExpr *e, const double *const_values, void *opaque)
+{
+    Parser p;
+
+    p.const_values = const_values;
+    p.opaque     = opaque;
+    return eval_expr(&p, e);
+}
+
+int av_expr_parse_and_eval(double *d, const char *s,
+                           const char * const *const_names, const double *const_values,
+                           const char * const *func1_names, double (* const *funcs1)(void *, double),
+                           const char * const *func2_names, double (* const *funcs2)(void *, double, double),
+                           void *opaque, int log_offset, void *log_ctx)
+{
+    AVExpr *e = NULL;
+    int ret = av_expr_parse(&e, s, const_names, func1_names, funcs1, func2_names, funcs2, log_offset, log_ctx);
+
+    if (ret < 0) {
+        *d = NAN;
+        return ret;
+    }
+    *d = av_expr_eval(e, const_values, opaque);
+    av_expr_free(e);
+    return isnan(*d) ? AVERROR(EINVAL) : 0;
+}
+
+#if FF_API_OLD_EVAL_NAMES
+int av_parse_expr(AVExpr **expr, const char *s,
+                  const char * const *const_names,
+                  const char * const *func1_names, double (* const *funcs1)(void *, double),
+                  const char * const *func2_names, double (* const *funcs2)(void *, double, double),
+                  int log_offset, void *log_ctx)
+{
+    return av_expr_parse(expr, s, const_names, func1_names, funcs1, func2_names, funcs2,
+                      log_offset, log_ctx);
+}
+
+double av_eval_expr(AVExpr *e, const double *const_values, void *opaque)
+{
+    return av_expr_eval(e, const_values, opaque);
+}
+
+int av_parse_and_eval_expr(double *res, const char *s,
+                           const char * const *const_names, const double *const_values,
+                           const char * const *func1_names, double (* const *funcs1)(void *, double),
+                           const char * const *func2_names, double (* const *funcs2)(void *, double, double),
+                           void *opaque, int log_offset, void *log_ctx)
+{
+    return av_expr_parse_and_eval(res, s, const_names, const_values, func1_names, funcs1, func2_names, funcs2,
+                                  opaque, log_offset, log_ctx);
+}
+
+void av_free_expr(AVExpr *e)
+{
+    av_expr_free(e);
+}
+#endif /* FF_API_OLD_EVAL_NAMES */
+
+#ifdef TEST
+#undef printf
+static double const_values[] = {
+    M_PI,
+    M_E,
+    0
+};
+
+static const char *const_names[] = {
+    "PI",
+    "E",
+    0
+};
+
+int main(void)
+{
+    int i;
+    double d;
+    const char **expr, *exprs[] = {
+        "",
+        "1;2",
+        "-20",
+        "-PI",
+        "+PI",
+        "1+(5-2)^(3-1)+1/2+sin(PI)-max(-2.2,-3.1)",
+        "80G/80Gi"
+        "1k",
+        "1Gi",
+        "1gi",
+        "1GiFoo",
+        "1k+1k",
+        "1Gi*3foo",
+        "foo",
+        "foo(",
+        "foo()",
+        "foo)",
+        "sin",
+        "sin(",
+        "sin()",
+        "sin)",
+        "sin 10",
+        "sin(1,2,3)",
+        "sin(1 )",
+        "1",
+        "1foo",
+        "bar + PI + E + 100f*2 + foo",
+        "13k + 12f - foo(1, 2)",
+        "1gi",
+        "1Gi",
+        "st(0, 123)",
+        "st(1, 123); ld(1)",
+        /* compute 1+2+...+N */
+        "st(0, 1); while(lte(ld(0), 100), st(1, ld(1)+ld(0));st(0, ld(0)+1)); ld(1)",
+        /* compute Fib(N) */
+        "st(1, 1); st(2, 2); st(0, 1); while(lte(ld(0),10), st(3, ld(1)+ld(2)); st(1, ld(2)); st(2, ld(3)); st(0, ld(0)+1)); ld(3)",
+        "while(0, 10)",
+        "st(0, 1); while(lte(ld(0),100), st(1, ld(1)+ld(0)); st(0, ld(0)+1))",
+        "isnan(1)",
+        "isnan(NAN)",
+        "floor(NAN)",
+        "floor(123.123)",
+        "floor(-123.123)",
+        "trunc(123.123)",
+        "trunc(-123.123)",
+        "ceil(123.123)",
+        "ceil(-123.123)",
+        NULL
+    };
+
+    for (expr = exprs; *expr; expr++) {
+        printf("Evaluating '%s'\n", *expr);
+        av_expr_parse_and_eval(&d, *expr,
+                               const_names, const_values,
+                               NULL, NULL, NULL, NULL, NULL, 0, NULL);
+        printf("'%s' -> %f\n\n", *expr, d);
+    }
+
+    av_expr_parse_and_eval(&d, "1+(5-2)^(3-1)+1/2+sin(PI)-max(-2.2,-3.1)",
+                           const_names, const_values,
+                           NULL, NULL, NULL, NULL, NULL, 0, NULL);
+    printf("%f == 12.7\n", d);
+    av_expr_parse_and_eval(&d, "80G/80Gi",
+                           const_names, const_values,
+                           NULL, NULL, NULL, NULL, NULL, 0, NULL);
+    printf("%f == 0.931322575\n", d);
+
+    for (i=0; i<1050; i++) {
+        START_TIMER
+            av_expr_parse_and_eval(&d, "1+(5-2)^(3-1)+1/2+sin(PI)-max(-2.2,-3.1)",
+                                   const_names, const_values,
+                                   NULL, NULL, NULL, NULL, NULL, 0, NULL);
+        STOP_TIMER("av_expr_parse_and_eval")
+    }
+    return 0;
+}
+#endif
diff --git a/libavutil/eval.h b/libavutil/eval.h
new file mode 100644
index 0000000..a20a006
--- /dev/null
+++ b/libavutil/eval.h
@@ -0,0 +1,146 @@
+/*
+ * Copyright (c) 2002 Michael Niedermayer <michaelni at gmx.at>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * simple arithmetic expression evaluator
+ */
+
+#ifndef AVUTIL_EVAL_H
+#define AVUTIL_EVAL_H
+
+#include "avutil.h"
+
+typedef struct AVExpr AVExpr;
+
+/**
+ * Parse and evaluate an expression.
+ * Note, this is significantly slower than av_expr_eval().
+ *
+ * @param res a pointer to a double where is put the result value of
+ * the expression, or NAN in case of error
+ * @param s expression as a zero terminated string, for example "1+2^3+5*5+sin(2/3)"
+ * @param const_names NULL terminated array of zero terminated strings of constant identifiers, for example {"PI", "E", 0}
+ * @param const_values a zero terminated array of values for the identifiers from const_names
+ * @param func1_names NULL terminated array of zero terminated strings of funcs1 identifiers
+ * @param funcs1 NULL terminated array of function pointers for functions which take 1 argument
+ * @param func2_names NULL terminated array of zero terminated strings of funcs2 identifiers
+ * @param funcs2 NULL terminated array of function pointers for functions which take 2 arguments
+ * @param opaque a pointer which will be passed to all functions from funcs1 and funcs2
+ * @param log_ctx parent logging context
+ * @return 0 in case of success, a negative value corresponding to an
+ * AVERROR code otherwise
+ */
+int av_expr_parse_and_eval(double *res, const char *s,
+                           const char * const *const_names, const double *const_values,
+                           const char * const *func1_names, double (* const *funcs1)(void *, double),
+                           const char * const *func2_names, double (* const *funcs2)(void *, double, double),
+                           void *opaque, int log_offset, void *log_ctx);
+
+/**
+ * Parse an expression.
+ *
+ * @param expr a pointer where is put an AVExpr containing the parsed
+ * value in case of successfull parsing, or NULL otherwise.
+ * The pointed to AVExpr must be freed with av_expr_free() by the user
+ * when it is not needed anymore.
+ * @param s expression as a zero terminated string, for example "1+2^3+5*5+sin(2/3)"
+ * @param const_names NULL terminated array of zero terminated strings of constant identifiers, for example {"PI", "E", 0}
+ * @param func1_names NULL terminated array of zero terminated strings of funcs1 identifiers
+ * @param funcs1 NULL terminated array of function pointers for functions which take 1 argument
+ * @param func2_names NULL terminated array of zero terminated strings of funcs2 identifiers
+ * @param funcs2 NULL terminated array of function pointers for functions which take 2 arguments
+ * @param log_ctx parent logging context
+ * @return 0 in case of success, a negative value corresponding to an
+ * AVERROR code otherwise
+ */
+int av_expr_parse(AVExpr **expr, const char *s,
+                  const char * const *const_names,
+                  const char * const *func1_names, double (* const *funcs1)(void *, double),
+                  const char * const *func2_names, double (* const *funcs2)(void *, double, double),
+                  int log_offset, void *log_ctx);
+
+/**
+ * Evaluate a previously parsed expression.
+ *
+ * @param const_values a zero terminated array of values for the identifiers from av_expr_parse() const_names
+ * @param opaque a pointer which will be passed to all functions from funcs1 and funcs2
+ * @return the value of the expression
+ */
+double av_expr_eval(AVExpr *e, const double *const_values, void *opaque);
+
+/**
+ * Free a parsed expression previously created with av_expr_parse().
+ */
+void av_expr_free(AVExpr *e);
+
+#if FF_API_OLD_EVAL_NAMES
+/**
+ * @deprecated Deprecated in favor of av_expr_parse_and_eval().
+ */
+attribute_deprecated
+int av_parse_and_eval_expr(double *res, const char *s,
+                           const char * const *const_names, const double *const_values,
+                           const char * const *func1_names, double (* const *funcs1)(void *, double),
+                           const char * const *func2_names, double (* const *funcs2)(void *, double, double),
+                           void *opaque, int log_offset, void *log_ctx);
+
+/**
+ * @deprecated Deprecated in favor of av_expr_parse().
+ */
+attribute_deprecated
+int av_parse_expr(AVExpr **expr, const char *s,
+                  const char * const *const_names,
+                  const char * const *func1_names, double (* const *funcs1)(void *, double),
+                  const char * const *func2_names, double (* const *funcs2)(void *, double, double),
+                  int log_offset, void *log_ctx);
+/**
+ * @deprecated Deprecated in favor of av_expr_eval().
+ */
+attribute_deprecated
+double av_eval_expr(AVExpr *e, const double *const_values, void *opaque);
+
+/**
+ * @deprecated Deprecated in favor of av_expr_free().
+ */
+attribute_deprecated
+void av_free_expr(AVExpr *e);
+#endif /* FF_API_OLD_EVAL_NAMES */
+
+/**
+ * Parse the string in numstr and return its value as a double. If
+ * the string is empty, contains only whitespaces, or does not contain
+ * an initial substring that has the expected syntax for a
+ * floating-point number, no conversion is performed. In this case,
+ * returns a value of zero and the value returned in tail is the value
+ * of numstr.
+ *
+ * @param numstr a string representing a number, may contain one of
+ * the International System number postfixes, for example 'K', 'M',
+ * 'G'. If 'i' is appended after the postfix, powers of 2 are used
+ * instead of powers of 10. The 'B' postfix multiplies the value for
+ * 8, and can be appended after another postfix or used alone. This
+ * allows using for example 'KB', 'MiB', 'G' and 'B' as postfix.
+ * @param tail if non-NULL puts here the pointer to the char next
+ * after the last parsed character
+ */
+double av_strtod(const char *numstr, char **tail);
+
+#endif /* AVUTIL_EVAL_H */
diff --git a/libavutil/fifo.c b/libavutil/fifo.c
index cfb716e..f87a99d 100644
--- a/libavutil/fifo.c
+++ b/libavutil/fifo.c
@@ -3,20 +3,20 @@
  * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
  * Copyright (c) 2006 Roman Shaposhnik
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #include "common.h"
diff --git a/libavutil/fifo.h b/libavutil/fifo.h
index fb1ed47..cd361b0 100644
--- a/libavutil/fifo.h
+++ b/libavutil/fifo.h
@@ -1,18 +1,18 @@
 /*
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -33,26 +33,26 @@ typedef struct AVFifoBuffer {
 } AVFifoBuffer;
 
 /**
- * Initializes an AVFifoBuffer.
+ * Initialize an AVFifoBuffer.
  * @param size of FIFO
  * @return AVFifoBuffer or NULL in case of memory allocation failure
  */
 AVFifoBuffer *av_fifo_alloc(unsigned int size);
 
 /**
- * Frees an AVFifoBuffer.
+ * Free an AVFifoBuffer.
  * @param *f AVFifoBuffer to free
  */
 void av_fifo_free(AVFifoBuffer *f);
 
 /**
- * Resets the AVFifoBuffer to the state right after av_fifo_alloc, in particular it is emptied.
+ * Reset the AVFifoBuffer to the state right after av_fifo_alloc, in particular it is emptied.
  * @param *f AVFifoBuffer to reset
  */
 void av_fifo_reset(AVFifoBuffer *f);
 
 /**
- * Returns the amount of data in bytes in the AVFifoBuffer, that is the
+ * Return the amount of data in bytes in the AVFifoBuffer, that is the
  * amount of data you can read from it.
  * @param *f AVFifoBuffer to read from
  * @return size
@@ -60,7 +60,7 @@ void av_fifo_reset(AVFifoBuffer *f);
 int av_fifo_size(AVFifoBuffer *f);
 
 /**
- * Returns the amount of space in bytes in the AVFifoBuffer, that is the
+ * Return the amount of space in bytes in the AVFifoBuffer, that is the
  * amount of data you can write into it.
  * @param *f AVFifoBuffer to write into
  * @return size
@@ -68,7 +68,7 @@ int av_fifo_size(AVFifoBuffer *f);
 int av_fifo_space(AVFifoBuffer *f);
 
 /**
- * Feeds data from an AVFifoBuffer to a user-supplied callback.
+ * Feed data from an AVFifoBuffer to a user-supplied callback.
  * @param *f AVFifoBuffer to read from
  * @param buf_size number of bytes to read
  * @param *func generic read function
@@ -77,7 +77,7 @@ int av_fifo_space(AVFifoBuffer *f);
 int av_fifo_generic_read(AVFifoBuffer *f, void *dest, int buf_size, void (*func)(void*, void*, int));
 
 /**
- * Feeds data from a user-supplied callback to an AVFifoBuffer.
+ * Feed data from a user-supplied callback to an AVFifoBuffer.
  * @param *f AVFifoBuffer to write to
  * @param *src data source; non-const since it may be used as a
  * modifiable context by the function defined in func
@@ -92,7 +92,7 @@ int av_fifo_generic_read(AVFifoBuffer *f, void *dest, int buf_size, void (*func)
 int av_fifo_generic_write(AVFifoBuffer *f, void *src, int size, int (*func)(void*, void*, int));
 
 /**
- * Resizes an AVFifoBuffer.
+ * Resize an AVFifoBuffer.
  * @param *f AVFifoBuffer to resize
  * @param size new AVFifoBuffer size in bytes
  * @return <0 for failure, >=0 otherwise
@@ -100,7 +100,7 @@ int av_fifo_generic_write(AVFifoBuffer *f, void *src, int size, int (*func)(void
 int av_fifo_realloc2(AVFifoBuffer *f, unsigned int size);
 
 /**
- * Reads and discards the specified amount of data from an AVFifoBuffer.
+ * Read and discard the specified amount of data from an AVFifoBuffer.
  * @param *f AVFifoBuffer to read from
  * @param size amount of data to read in bytes
  */
diff --git a/libavutil/file.c b/libavutil/file.c
new file mode 100644
index 0000000..757e73b
--- /dev/null
+++ b/libavutil/file.c
@@ -0,0 +1,149 @@
+/*
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "file.h"
+#include <fcntl.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#if HAVE_MMAP
+#include <sys/mman.h>
+#elif HAVE_MAPVIEWOFFILE
+#include <io.h>
+#include <windows.h>
+#endif
+
+typedef struct {
+    const AVClass *class;
+    int   log_offset;
+    void *log_ctx;
+} FileLogContext;
+
+static const AVClass file_log_ctx_class = {
+    "FILE", av_default_item_name, NULL, LIBAVUTIL_VERSION_INT,
+    offsetof(FileLogContext, log_offset), offsetof(FileLogContext, log_ctx)
+};
+
+int av_file_map(const char *filename, uint8_t **bufptr, size_t *size,
+                int log_offset, void *log_ctx)
+{
+    FileLogContext file_log_ctx = { &file_log_ctx_class, log_offset, log_ctx };
+    int err, fd = open(filename, O_RDONLY);
+    struct stat st;
+    av_unused void *ptr;
+    off_t off_size;
+    char errbuf[128];
+    size_t max_size = HAVE_MMAP ? SIZE_MAX : FF_INTERNAL_MEM_TYPE_MAX_VALUE;
+    *bufptr = NULL;
+
+    if (fd < 0) {
+        err = AVERROR(errno);
+        av_strerror(err, errbuf, sizeof(errbuf));
+        av_log(&file_log_ctx, AV_LOG_ERROR, "Cannot read file '%s': %s\n", filename, errbuf);
+        return err;
+    }
+
+    if (fstat(fd, &st) < 0) {
+        err = AVERROR(errno);
+        av_strerror(err, errbuf, sizeof(errbuf));
+        av_log(&file_log_ctx, AV_LOG_ERROR, "Error occurred in fstat(): %s\n", errbuf);
+        close(fd);
+        return err;
+    }
+
+    off_size = st.st_size;
+    if (off_size > max_size) {
+        av_log(&file_log_ctx, AV_LOG_ERROR,
+               "File size for file '%s' is too big\n", filename);
+        close(fd);
+        return AVERROR(EINVAL);
+    }
+    *size = off_size;
+
+#if HAVE_MMAP
+    ptr = mmap(NULL, *size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
+    if ((int)(ptr) == -1) {
+        err = AVERROR(errno);
+        av_strerror(err, errbuf, sizeof(errbuf));
+        av_log(&file_log_ctx, AV_LOG_ERROR, "Error occurred in mmap(): %s\n", errbuf);
+        close(fd);
+        return err;
+    }
+    *bufptr = ptr;
+#elif HAVE_MAPVIEWOFFILE
+    {
+        HANDLE mh, fh = (HANDLE)_get_osfhandle(fd);
+
+        mh = CreateFileMapping(fh, NULL, PAGE_READONLY, 0, 0, NULL);
+        if (!mh) {
+            av_log(&file_log_ctx, AV_LOG_ERROR, "Error occurred in CreateFileMapping()\n");
+            close(fd);
+            return -1;
+        }
+
+        ptr = MapViewOfFile(mh, FILE_MAP_READ, 0, 0, *size);
+        CloseHandle(mh);
+        if (!ptr) {
+            av_log(&file_log_ctx, AV_LOG_ERROR, "Error occurred in MapViewOfFile()\n");
+            close(fd);
+            return -1;
+        }
+
+        *bufptr = ptr;
+    }
+#else
+    *bufptr = av_malloc(*size);
+    if (!*bufptr) {
+        av_log(&file_log_ctx, AV_LOG_ERROR, "Memory allocation error occurred\n");
+        close(fd);
+        return AVERROR(ENOMEM);
+    }
+    read(fd, *bufptr, *size);
+#endif
+
+    close(fd);
+    return 0;
+}
+
+void av_file_unmap(uint8_t *bufptr, size_t size)
+{
+#if HAVE_MMAP
+    munmap(bufptr, size);
+#elif HAVE_MAPVIEWOFFILE
+    UnmapViewOfFile(bufptr);
+#else
+    av_free(bufptr);
+#endif
+}
+
+#ifdef TEST
+
+#undef printf
+
+int main(void)
+{
+    uint8_t *buf;
+    size_t size;
+    if (av_file_map("file.c", &buf, &size, 0, NULL) < 0)
+        return 1;
+
+    buf[0] = 's';
+    printf("%s", buf);
+    av_file_unmap(buf, size);
+    return 0;
+}
+#endif
diff --git a/libavutil/file.h b/libavutil/file.h
new file mode 100644
index 0000000..8b65bfb
--- /dev/null
+++ b/libavutil/file.h
@@ -0,0 +1,51 @@
+/*
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_FILE_H
+#define AVUTIL_FILE_H
+
+#include "avutil.h"
+
+/**
+ * @file misc file utilities
+ */
+
+/**
+ * Read the file with name filename, and put its content in a newly
+ * allocated buffer or map it with mmap() when available.
+ * In case of success set *bufptr to the read or mmapped buffer, and
+ * *size to the size in bytes of the buffer in *bufptr.
+ * The returned buffer must be released with av_file_unmap().
+ *
+ * @param log_offset loglevel offset used for logging
+ * @param log_ctx context used for logging
+ * @return a non negative number in case of success, a negative value
+ * corresponding to an AVERROR error code in case of failure
+ */
+int av_file_map(const char *filename, uint8_t **bufptr, size_t *size,
+                int log_offset, void *log_ctx);
+
+/**
+ * Unmap or free the buffer bufptr created by av_file_map().
+ *
+ * @param size size in bytes of bufptr, must be the same as returned
+ * by av_file_map()
+ */
+void av_file_unmap(uint8_t *bufptr, size_t size);
+
+#endif /* AVUTIL_FILE_H */
diff --git a/libavutil/imgutils.c b/libavutil/imgutils.c
new file mode 100644
index 0000000..129fb95
--- /dev/null
+++ b/libavutil/imgutils.c
@@ -0,0 +1,297 @@
+/*
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * misc image utilities
+ */
+
+#include "imgutils.h"
+#include "internal.h"
+#include "libavutil/pixdesc.h"
+
+void av_image_fill_max_pixsteps(int max_pixsteps[4], int max_pixstep_comps[4],
+                                const AVPixFmtDescriptor *pixdesc)
+{
+    int i;
+    memset(max_pixsteps, 0, 4*sizeof(max_pixsteps[0]));
+    if (max_pixstep_comps)
+        memset(max_pixstep_comps, 0, 4*sizeof(max_pixstep_comps[0]));
+
+    for (i = 0; i < 4; i++) {
+        const AVComponentDescriptor *comp = &(pixdesc->comp[i]);
+        if ((comp->step_minus1+1) > max_pixsteps[comp->plane]) {
+            max_pixsteps[comp->plane] = comp->step_minus1+1;
+            if (max_pixstep_comps)
+                max_pixstep_comps[comp->plane] = i;
+        }
+    }
+}
+
+int av_image_get_linesize(enum PixelFormat pix_fmt, int width, int plane)
+{
+    const AVPixFmtDescriptor *desc = &av_pix_fmt_descriptors[pix_fmt];
+    int max_step     [4];       /* max pixel step for each plane */
+    int max_step_comp[4];       /* the component for each plane which has the max pixel step */
+    int s;
+
+    if (desc->flags & PIX_FMT_BITSTREAM)
+        return (width * (desc->comp[0].step_minus1+1) + 7) >> 3;
+
+    av_image_fill_max_pixsteps(max_step, max_step_comp, desc);
+    s = (max_step_comp[plane] == 1 || max_step_comp[plane] == 2) ? desc->log2_chroma_w : 0;
+    return max_step[plane] * (((width + (1 << s) - 1)) >> s);
+}
+
+int av_image_fill_linesizes(int linesizes[4], enum PixelFormat pix_fmt, int width)
+{
+    int i;
+    const AVPixFmtDescriptor *desc = &av_pix_fmt_descriptors[pix_fmt];
+    int max_step     [4];       /* max pixel step for each plane */
+    int max_step_comp[4];       /* the component for each plane which has the max pixel step */
+
+    memset(linesizes, 0, 4*sizeof(linesizes[0]));
+
+    if ((unsigned)pix_fmt >= PIX_FMT_NB || desc->flags & PIX_FMT_HWACCEL)
+        return AVERROR(EINVAL);
+
+    if (desc->flags & PIX_FMT_BITSTREAM) {
+        if (width > (INT_MAX -7) / (desc->comp[0].step_minus1+1))
+            return AVERROR(EINVAL);
+        linesizes[0] = (width * (desc->comp[0].step_minus1+1) + 7) >> 3;
+        return 0;
+    }
+
+    av_image_fill_max_pixsteps(max_step, max_step_comp, desc);
+    for (i = 0; i < 4; i++) {
+        int s = (max_step_comp[i] == 1 || max_step_comp[i] == 2) ? desc->log2_chroma_w : 0;
+        int shifted_w = ((width + (1 << s) - 1)) >> s;
+        if (max_step[i] > INT_MAX / shifted_w)
+            return AVERROR(EINVAL);
+        linesizes[i] = max_step[i] * shifted_w;
+    }
+
+    return 0;
+}
+
+int av_image_fill_pointers(uint8_t *data[4], enum PixelFormat pix_fmt, int height,
+                           uint8_t *ptr, const int linesizes[4])
+{
+    int i, total_size, size[4], has_plane[4];
+
+    const AVPixFmtDescriptor *desc = &av_pix_fmt_descriptors[pix_fmt];
+    memset(data     , 0, sizeof(data[0])*4);
+    memset(size     , 0, sizeof(size));
+    memset(has_plane, 0, sizeof(has_plane));
+
+    if ((unsigned)pix_fmt >= PIX_FMT_NB || desc->flags & PIX_FMT_HWACCEL)
+        return AVERROR(EINVAL);
+
+    data[0] = ptr;
+    if (linesizes[0] > (INT_MAX - 1024) / height)
+        return AVERROR(EINVAL);
+    size[0] = linesizes[0] * height;
+
+    if (desc->flags & PIX_FMT_PAL) {
+        size[0] = (size[0] + 3) & ~3;
+        data[1] = ptr + size[0]; /* palette is stored here as 256 32 bits words */
+        return size[0] + 256 * 4;
+    }
+
+    for (i = 0; i < 4; i++)
+        has_plane[desc->comp[i].plane] = 1;
+
+    total_size = size[0];
+    for (i = 1; has_plane[i] && i < 4; i++) {
+        int h, s = (i == 1 || i == 2) ? desc->log2_chroma_h : 0;
+        data[i] = data[i-1] + size[i-1];
+        h = (height + (1 << s) - 1) >> s;
+        if (linesizes[i] > INT_MAX / h)
+            return AVERROR(EINVAL);
+        size[i] = h * linesizes[i];
+        if (total_size > INT_MAX - size[i])
+            return AVERROR(EINVAL);
+        total_size += size[i];
+    }
+
+    return total_size;
+}
+
+int ff_set_systematic_pal2(uint32_t pal[256], enum PixelFormat pix_fmt)
+{
+    int i;
+
+    for (i = 0; i < 256; i++) {
+        int r, g, b;
+
+        switch (pix_fmt) {
+        case PIX_FMT_RGB8:
+            r = (i>>5    )*36;
+            g = ((i>>2)&7)*36;
+            b = (i&3     )*85;
+            break;
+        case PIX_FMT_BGR8:
+            b = (i>>6    )*85;
+            g = ((i>>3)&7)*36;
+            r = (i&7     )*36;
+            break;
+        case PIX_FMT_RGB4_BYTE:
+            r = (i>>3    )*255;
+            g = ((i>>1)&3)*85;
+            b = (i&1     )*255;
+            break;
+        case PIX_FMT_BGR4_BYTE:
+            b = (i>>3    )*255;
+            g = ((i>>1)&3)*85;
+            r = (i&1     )*255;
+            break;
+        case PIX_FMT_GRAY8:
+            r = b = g = i;
+            break;
+        default:
+            return AVERROR(EINVAL);
+        }
+        pal[i] = b + (g<<8) + (r<<16);
+    }
+
+    return 0;
+}
+
+int av_image_alloc(uint8_t *pointers[4], int linesizes[4],
+                   int w, int h, enum PixelFormat pix_fmt, int align)
+{
+    int i, ret;
+    uint8_t *buf;
+
+    if ((ret = av_image_check_size(w, h, 0, NULL)) < 0)
+        return ret;
+    if ((ret = av_image_fill_linesizes(linesizes, pix_fmt, w)) < 0)
+        return ret;
+
+    for (i = 0; i < 4; i++)
+        linesizes[i] = FFALIGN(linesizes[i], align);
+
+    if ((ret = av_image_fill_pointers(pointers, pix_fmt, h, NULL, linesizes)) < 0)
+        return ret;
+    buf = av_malloc(ret + align);
+    if (!buf)
+        return AVERROR(ENOMEM);
+    if ((ret = av_image_fill_pointers(pointers, pix_fmt, h, buf, linesizes)) < 0) {
+        av_free(buf);
+        return ret;
+    }
+    if (av_pix_fmt_descriptors[pix_fmt].flags & PIX_FMT_PAL)
+        ff_set_systematic_pal2((uint32_t*)pointers[1], pix_fmt);
+
+    return ret;
+}
+
+typedef struct ImgUtils {
+    const AVClass *class;
+    int   log_offset;
+    void *log_ctx;
+} ImgUtils;
+
+static const AVClass imgutils_class = { "IMGUTILS", av_default_item_name, NULL, LIBAVUTIL_VERSION_INT, offsetof(ImgUtils, log_offset), offsetof(ImgUtils, log_ctx) };
+
+int av_image_check_size(unsigned int w, unsigned int h, int log_offset, void *log_ctx)
+{
+    ImgUtils imgutils = { &imgutils_class, log_offset, log_ctx };
+
+    if ((int)w>0 && (int)h>0 && (w+128)*(uint64_t)(h+128) < INT_MAX/8)
+        return 0;
+
+    av_log(&imgutils, AV_LOG_ERROR, "Picture size %ux%u is invalid\n", w, h);
+    return AVERROR(EINVAL);
+}
+
+void av_image_copy_plane(uint8_t       *dst, int dst_linesize,
+                         const uint8_t *src, int src_linesize,
+                         int bytewidth, int height)
+{
+    if (!dst || !src)
+        return;
+    for (;height > 0; height--) {
+        memcpy(dst, src, bytewidth);
+        dst += dst_linesize;
+        src += src_linesize;
+    }
+}
+
+void av_image_copy(uint8_t *dst_data[4], int dst_linesizes[4],
+                   const uint8_t *src_data[4], const int src_linesizes[4],
+                   enum PixelFormat pix_fmt, int width, int height)
+{
+    const AVPixFmtDescriptor *desc = &av_pix_fmt_descriptors[pix_fmt];
+
+    if (desc->flags & PIX_FMT_HWACCEL)
+        return;
+
+    if (desc->flags & PIX_FMT_PAL) {
+        av_image_copy_plane(dst_data[0], dst_linesizes[0],
+                            src_data[0], src_linesizes[0],
+                            width, height);
+        /* copy the palette */
+        memcpy(dst_data[1], src_data[1], 4*256);
+    } else {
+        int i, planes_nb = 0;
+
+        for (i = 0; i < desc->nb_components; i++)
+            planes_nb = FFMAX(planes_nb, desc->comp[i].plane + 1);
+
+        for (i = 0; i < planes_nb; i++) {
+            int h = height;
+            int bwidth = av_image_get_linesize(pix_fmt, width, i);
+            if (i == 1 || i == 2) {
+                h= -((-height)>>desc->log2_chroma_h);
+            }
+            av_image_copy_plane(dst_data[i], dst_linesizes[i],
+                                src_data[i], src_linesizes[i],
+                                bwidth, h);
+        }
+    }
+}
+
+#if FF_API_OLD_IMAGE_NAMES
+void av_fill_image_max_pixsteps(int max_pixsteps[4], int max_pixstep_comps[4],
+                                const AVPixFmtDescriptor *pixdesc)
+{
+    av_image_fill_max_pixsteps(max_pixsteps, max_pixstep_comps, pixdesc);
+}
+
+int av_get_image_linesize(enum PixelFormat pix_fmt, int width, int plane)
+{
+    return av_image_get_linesize(pix_fmt, width, plane);
+}
+
+int av_fill_image_linesizes(int linesizes[4], enum PixelFormat pix_fmt, int width)
+{
+    return av_image_fill_linesizes(linesizes, pix_fmt, width);
+}
+
+int av_fill_image_pointers(uint8_t *data[4], enum PixelFormat pix_fmt, int height,
+                           uint8_t *ptr, const int linesizes[4])
+{
+    return av_image_fill_pointers(data, pix_fmt, height, ptr, linesizes);
+}
+
+int av_check_image_size(unsigned int w, unsigned int h, int log_offset, void *log_ctx)
+{
+    return av_image_check_size(w, h, log_offset, log_ctx);
+}
+#endif
diff --git a/libavutil/imgutils.h b/libavutil/imgutils.h
new file mode 100644
index 0000000..6ebb1b0
--- /dev/null
+++ b/libavutil/imgutils.h
@@ -0,0 +1,149 @@
+/*
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_IMGUTILS_H
+#define AVUTIL_IMGUTILS_H
+
+/**
+ * @file
+ * misc image utilities
+ */
+
+#include "libavutil/pixdesc.h"
+#include "avutil.h"
+
+/**
+ * Compute the max pixel step for each plane of an image with a
+ * format described by pixdesc.
+ *
+ * The pixel step is the distance in bytes between the first byte of
+ * the group of bytes which describe a pixel component and the first
+ * byte of the successive group in the same plane for the same
+ * component.
+ *
+ * @param max_pixsteps an array which is filled with the max pixel step
+ * for each plane. Since a plane may contain different pixel
+ * components, the computed max_pixsteps[plane] is relative to the
+ * component in the plane with the max pixel step.
+ * @param max_pixstep_comps an array which is filled with the component
+ * for each plane which has the max pixel step. May be NULL.
+ */
+void av_image_fill_max_pixsteps(int max_pixsteps[4], int max_pixstep_comps[4],
+                                const AVPixFmtDescriptor *pixdesc);
+
+/**
+ * Compute the size of an image line with format pix_fmt and width
+ * width for the plane plane.
+ *
+ * @return the computed size in bytes
+ */
+int av_image_get_linesize(enum PixelFormat pix_fmt, int width, int plane);
+
+/**
+ * Fill plane linesizes for an image with pixel format pix_fmt and
+ * width width.
+ *
+ * @param linesizes array to be filled with the linesize for each plane
+ * @return >= 0 in case of success, a negative error code otherwise
+ */
+int av_image_fill_linesizes(int linesizes[4], enum PixelFormat pix_fmt, int width);
+
+/**
+ * Fill plane data pointers for an image with pixel format pix_fmt and
+ * height height.
+ *
+ * @param data pointers array to be filled with the pointer for each image plane
+ * @param ptr the pointer to a buffer which will contain the image
+ * @param linesizes[4] the array containing the linesize for each
+ * plane, should be filled by av_image_fill_linesizes()
+ * @return the size in bytes required for the image buffer, a negative
+ * error code in case of failure
+ */
+int av_image_fill_pointers(uint8_t *data[4], enum PixelFormat pix_fmt, int height,
+                           uint8_t *ptr, const int linesizes[4]);
+
+/**
+ * Allocate an image with size w and h and pixel format pix_fmt, and
+ * fill pointers and linesizes accordingly.
+ * The allocated image buffer has to be freed by using
+ * av_freep(&pointers[0]).
+ *
+ * @param align the value to use for buffer size alignment
+ * @return the size in bytes required for the image buffer, a negative
+ * error code in case of failure
+ */
+int av_image_alloc(uint8_t *pointers[4], int linesizes[4],
+                   int w, int h, enum PixelFormat pix_fmt, int align);
+
+/**
+ * Copy image plane from src to dst.
+ * That is, copy "height" number of lines of "bytewidth" bytes each.
+ * The first byte of each successive line is separated by *_linesize
+ * bytes.
+ *
+ * @param dst_linesize linesize for the image plane in dst
+ * @param src_linesize linesize for the image plane in src
+ */
+void av_image_copy_plane(uint8_t       *dst, int dst_linesize,
+                         const uint8_t *src, int src_linesize,
+                         int bytewidth, int height);
+
+/**
+ * Copy image in src_data to dst_data.
+ *
+ * @param dst_linesize linesizes for the image in dst_data
+ * @param src_linesize linesizes for the image in src_data
+ */
+void av_image_copy(uint8_t *dst_data[4], int dst_linesizes[4],
+                   const uint8_t *src_data[4], const int src_linesizes[4],
+                   enum PixelFormat pix_fmt, int width, int height);
+
+/**
+ * Check if the given dimension of an image is valid, meaning that all
+ * bytes of the image can be addressed with a signed int.
+ *
+ * @param w the width of the picture
+ * @param h the height of the picture
+ * @param log_offset the offset to sum to the log level for logging with log_ctx
+ * @param log_ctx the parent logging context, it may be NULL
+ * @return >= 0 if valid, a negative error code otherwise
+ */
+int av_image_check_size(unsigned int w, unsigned int h, int log_offset, void *log_ctx);
+
+int ff_set_systematic_pal2(uint32_t pal[256], enum PixelFormat pix_fmt);
+
+#if FF_API_OLD_IMAGE_NAMES
+attribute_deprecated
+void av_fill_image_max_pixsteps(int max_pixsteps[4], int max_pixstep_comps[4],
+                                const AVPixFmtDescriptor *pixdesc);
+
+attribute_deprecated
+int av_get_image_linesize(enum PixelFormat pix_fmt, int width, int plane);
+
+attribute_deprecated
+int av_fill_image_linesizes(int linesizes[4], enum PixelFormat pix_fmt, int width);
+
+attribute_deprecated
+int av_fill_image_pointers(uint8_t *data[4], enum PixelFormat pix_fmt, int height,
+                           uint8_t *ptr, const int linesizes[4]);
+
+attribute_deprecated
+int av_check_image_size(unsigned int w, unsigned int h, int log_offset, void *log_ctx);
+#endif
+
+#endif /* AVUTIL_IMGUTILS_H */
diff --git a/libavutil/integer.c b/libavutil/integer.c
index 4f9b66c..0114bb0 100644
--- a/libavutil/integer.c
+++ b/libavutil/integer.c
@@ -2,20 +2,20 @@
  * arbitrary precision integers
  * Copyright (c) 2004 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavutil/integer.h b/libavutil/integer.h
index fb46acb..f434cfa 100644
--- a/libavutil/integer.h
+++ b/libavutil/integer.h
@@ -2,20 +2,20 @@
  * arbitrary precision integers
  * Copyright (c) 2004 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -41,7 +41,7 @@ AVInteger av_add_i(AVInteger a, AVInteger b) av_const;
 AVInteger av_sub_i(AVInteger a, AVInteger b) av_const;
 
 /**
- * Returns the rounded-down value of the base 2 logarithm of the given
+ * Return the rounded-down value of the base 2 logarithm of the given
  * AVInteger. This is simply the index of the most significant bit
  * which is 1, or 0 if all bits are 0.
  */
@@ -49,7 +49,7 @@ int av_log2_i(AVInteger a) av_const;
 AVInteger av_mul_i(AVInteger a, AVInteger b) av_const;
 
 /**
- * Returns 0 if a==b, 1 if a>b and -1 if a<b.
+ * Return 0 if a==b, 1 if a>b and -1 if a<b.
  */
 int av_cmp_i(AVInteger a, AVInteger b) av_const;
 
@@ -61,23 +61,23 @@ int av_cmp_i(AVInteger a, AVInteger b) av_const;
 AVInteger av_shr_i(AVInteger a, int s) av_const;
 
 /**
- * Returns a % b.
+ * Return a % b.
  * @param quot a/b will be stored here.
  */
 AVInteger av_mod_i(AVInteger *quot, AVInteger a, AVInteger b);
 
 /**
- * Returns a/b.
+ * Return a/b.
  */
 AVInteger av_div_i(AVInteger a, AVInteger b) av_const;
 
 /**
- * Converts the given int64_t to an AVInteger.
+ * Convert the given int64_t to an AVInteger.
  */
 AVInteger av_int2i(int64_t a) av_const;
 
 /**
- * Converts the given AVInteger to an int64_t.
+ * Convert the given AVInteger to an int64_t.
  * If the AVInteger is too large to fit into an int64_t,
  * then only the least significant 64 bits will be used.
  */
diff --git a/libavutil/internal.h b/libavutil/internal.h
index fe8a6fa..37bc681 100644
--- a/libavutil/internal.h
+++ b/libavutil/internal.h
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -39,29 +39,13 @@
 #include "timer.h"
 
 #ifndef attribute_align_arg
-#if (!defined(__ICC) || __ICC > 1110) && AV_GCC_VERSION_AT_LEAST(4,2)
+#if ARCH_X86_32 && AV_GCC_VERSION_AT_LEAST(4,2)
 #    define attribute_align_arg __attribute__((force_align_arg_pointer))
 #else
 #    define attribute_align_arg
 #endif
 #endif
 
-#ifndef attribute_used
-#if AV_GCC_VERSION_AT_LEAST(3,1)
-#    define attribute_used __attribute__((used))
-#else
-#    define attribute_used
-#endif
-#endif
-
-#ifndef av_alias
-#if HAVE_ATTRIBUTE_MAY_ALIAS && (!defined(__ICC) || __ICC > 1110) && AV_GCC_VERSION_AT_LEAST(3,3)
-#   define av_alias __attribute__((may_alias))
-#else
-#   define av_alias
-#endif
-#endif
-
 #ifndef INT16_MIN
 #define INT16_MIN       (-0x7fff - 1)
 #endif
@@ -116,13 +100,6 @@
 
 /* debug stuff */
 
-/* dprintf macros */
-#ifdef DEBUG
-#    define dprintf(pctx, ...) av_log(pctx, AV_LOG_DEBUG, __VA_ARGS__)
-#else
-#    define dprintf(pctx, ...)
-#endif
-
 #define av_abort()      do { av_log(NULL, AV_LOG_ERROR, "Abort at %s:%d\n", __FILE__, __LINE__); abort(); } while (0)
 
 /* math */
@@ -194,7 +171,7 @@
 #include "libm.h"
 
 /**
- * Returns NULL if CONFIG_SMALL is true, otherwise the argument
+ * Return NULL if CONFIG_SMALL is true, otherwise the argument
  * without modification. Used to disable the definition of strings
  * (for example AVCodec long_names).
  */
@@ -204,6 +181,24 @@
 #   define NULL_IF_CONFIG_SMALL(x) x
 #endif
 
+
+/**
+ * Define a function with only the non-default version specified.
+ *
+ * On systems with ELF shared libraries, all symbols exported from
+ * Libav libraries are tagged with the name and major version of the
+ * library to which they belong.  If a function is moved from one
+ * library to another, a wrapper must be retained in the original
+ * location to preserve binary compatibility.
+ *
+ * Functions defined with this macro will never be used to resolve
+ * symbols by the build-time linker.
+ *
+ * @param type return type of function
+ * @param name name of function
+ * @param args argument list of function
+ * @param ver  version tag to assign function
+ */
 #if HAVE_SYMVER_ASM_LABEL
 #   define FF_SYMVER(type, name, args, ver)                     \
     type ff_##name args __asm__ (EXTERN_PREFIX #name "@" ver);  \
@@ -215,4 +210,15 @@
     type ff_##name args
 #endif
 
+/**
+ * Returns NULL if a threading library has not been enabled.
+ * Used to disable threading functions in AVCodec definitions
+ * when not needed.
+ */
+#if HAVE_THREADS
+#   define ONLY_IF_THREADS_ENABLED(x) x
+#else
+#   define ONLY_IF_THREADS_ENABLED(x) NULL
+#endif
+
 #endif /* AVUTIL_INTERNAL_H */
diff --git a/libavutil/intfloat_readwrite.c b/libavutil/intfloat_readwrite.c
index 79fe186..21a1c31 100644
--- a/libavutil/intfloat_readwrite.c
+++ b/libavutil/intfloat_readwrite.c
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2005 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -26,18 +26,18 @@
  */
 
 #include <stdint.h>
-#include <math.h>
+#include "mathematics.h"
 #include "intfloat_readwrite.h"
 
 double av_int2dbl(int64_t v){
     if(v+v > 0xFFEULL<<52)
-        return 0.0/0.0;
+        return NAN;
     return ldexp(((v&((1LL<<52)-1)) + (1LL<<52)) * (v>>63|1), (v>>52&0x7FF)-1075);
 }
 
 float av_int2flt(int32_t v){
     if(v+v > 0xFF000000U)
-        return 0.0/0.0;
+        return NAN;
     return ldexp(((v&0x7FFFFF) + (1<<23)) * (v>>31|1), (v>>23&0xFF)-150);
 }
 
@@ -49,7 +49,7 @@ double av_ext2dbl(const AVExtFloat ext){
         m = (m<<8) + ext.mantissa[i];
     e = (((int)ext.exponent[0]&0x7f)<<8) | ext.exponent[1];
     if (e == 0x7fff && m)
-        return 0.0/0.0;
+        return NAN;
     e -= 16383 + 63;        /* In IEEE 80 bits, the whole (i.e. 1.xxxx)
                              * mantissa bit is written as opposed to the
                              * single and double precision formats. */
@@ -88,7 +88,7 @@ AVExtFloat av_dbl2ext(double d){
             ext.mantissa[i] = m>>(56-(i<<3));
     } else if (f != 0.0) {
         ext.exponent[0] = 0x7f; ext.exponent[1] = 0xff;
-        if (f != 1/0.0)
+        if (f != INFINITY)
             ext.mantissa[0] = ~0;
     }
     if (d < 0)
diff --git a/libavutil/intfloat_readwrite.h b/libavutil/intfloat_readwrite.h
index 1b80fc6..10ecbed 100644
--- a/libavutil/intfloat_readwrite.h
+++ b/libavutil/intfloat_readwrite.h
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2005 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavutil/intmath.h b/libavutil/intmath.h
index 95ee1ff..3325975 100644
--- a/libavutil/intmath.h
+++ b/libavutil/intmath.h
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2010 Mans Rullgard <mans at mansr.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -36,43 +36,24 @@ extern const uint32_t ff_inverse[257];
 #if HAVE_FAST_CLZ && AV_GCC_VERSION_AT_LEAST(3,4)
 
 #ifndef av_log2
-
-#define av_log2(x) (31 - __builtin_clz((x)|1))
-
-#ifndef av_log2_16bit
-#define av_log2_16bit av_log2
-#endif
-
+#   define av_log2(x) (31 - __builtin_clz((x)|1))
+#   ifndef av_log2_16bit
+#      define av_log2_16bit av_log2
+#   endif
 #endif /* av_log2 */
 
 #endif /* AV_GCC_VERSION_AT_LEAST(3,4) */
 
 #ifndef FASTDIV
-
-#if CONFIG_FASTDIV
-#    define FASTDIV(a,b)   ((uint32_t)((((uint64_t)a) * ff_inverse[b]) >> 32))
-#else
-#    define FASTDIV(a,b)   ((a) / (b))
-#endif
-
+#   if CONFIG_FASTDIV
+#       define FASTDIV(a,b) ((uint32_t)((((uint64_t)a) * ff_inverse[b]) >> 32))
+#   else
+#       define FASTDIV(a,b) ((a) / (b))
+#   endif
 #endif /* FASTDIV */
 
-/*
- * Get definition of av_log2_c from common.h.  In the event we got
- * here through common.h including this file, including it again will
- * be a no-op due to multi-inclusion guards, so we must duplicate the
- * fallback defines here.
- */
-
 #include "common.h"
 
-#ifndef av_log2
-#   define av_log2       av_log2_c
-#endif
-#ifndef av_log2_16bit
-#   define av_log2_16bit av_log2_16bit_c
-#endif
-
 extern const uint8_t ff_sqrt_tab[256];
 
 static inline av_const unsigned int ff_sqrt(unsigned int a)
diff --git a/libavutil/intreadwrite.h b/libavutil/intreadwrite.h
index c8026f0..c8489f1 100644
--- a/libavutil/intreadwrite.h
+++ b/libavutil/intreadwrite.h
@@ -1,18 +1,18 @@
 /*
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -20,9 +20,9 @@
 #define AVUTIL_INTREADWRITE_H
 
 #include <stdint.h>
-#include "config.h"
+#include "libavutil/avconfig.h"
+#include "attributes.h"
 #include "bswap.h"
-#include "common.h"
 
 typedef union {
     uint64_t u64;
@@ -52,6 +52,10 @@ typedef union {
  * as inline functions.
  */
 
+#ifdef HAVE_AV_CONFIG_H
+
+#include "config.h"
+
 #if   ARCH_ARM
 #   include "arm/intreadwrite.h"
 #elif ARCH_AVR32
@@ -66,11 +70,13 @@ typedef union {
 #   include "x86/intreadwrite.h"
 #endif
 
+#endif /* HAVE_AV_CONFIG_H */
+
 /*
  * Map AV_RNXX <-> AV_R[BL]XX for all variants provided by per-arch headers.
  */
 
-#if HAVE_BIGENDIAN
+#if AV_HAVE_BIGENDIAN
 
 #   if    defined(AV_RN16) && !defined(AV_RB16)
 #       define AV_RB16(p) AV_RN16(p)
@@ -120,7 +126,7 @@ typedef union {
 #       define AV_WN64(p, v) AV_WB64(p, v)
 #   endif
 
-#else /* HAVE_BIGENDIAN */
+#else /* AV_HAVE_BIGENDIAN */
 
 #   if    defined(AV_RN16) && !defined(AV_RL16)
 #       define AV_RL16(p) AV_RN16(p)
@@ -170,14 +176,14 @@ typedef union {
 #       define AV_WN64(p, v) AV_WL64(p, v)
 #   endif
 
-#endif /* !HAVE_BIGENDIAN */
+#endif /* !AV_HAVE_BIGENDIAN */
 
 /*
  * Define AV_[RW]N helper macros to simplify definitions not provided
  * by per-arch headers.
  */
 
-#if   HAVE_ATTRIBUTE_PACKED
+#if defined(__GNUC__) && !defined(__TI_COMPILER_VERSION__)
 
 union unaligned_64 { uint64_t l; } __attribute__((packed)) av_alias;
 union unaligned_32 { uint32_t l; } __attribute__((packed)) av_alias;
@@ -191,7 +197,7 @@ union unaligned_16 { uint16_t l; } __attribute__((packed)) av_alias;
 #   define AV_RN(s, p) (*((const __unaligned uint##s##_t*)(p)))
 #   define AV_WN(s, p, v) (*((__unaligned uint##s##_t*)(p)) = (v))
 
-#elif HAVE_FAST_UNALIGNED
+#elif AV_HAVE_FAST_UNALIGNED
 
 #   define AV_RN(s, p) (((const av_alias##s*)(p))->u##s)
 #   define AV_WN(s, p, v) (((av_alias##s*)(p))->u##s = (v))
@@ -302,7 +308,7 @@ union unaligned_16 { uint16_t l; } __attribute__((packed)) av_alias;
     } while(0)
 #endif
 
-#if HAVE_BIGENDIAN
+#if AV_HAVE_BIGENDIAN
 #   define AV_RN(s, p)    AV_RB##s(p)
 #   define AV_WN(s, p, v) AV_WB##s(p, v)
 #else
@@ -336,14 +342,14 @@ union unaligned_16 { uint16_t l; } __attribute__((packed)) av_alias;
 #   define AV_WN64(p, v) AV_WN(64, p, v)
 #endif
 
-#if HAVE_BIGENDIAN
+#if AV_HAVE_BIGENDIAN
 #   define AV_RB(s, p)    AV_RN##s(p)
 #   define AV_WB(s, p, v) AV_WN##s(p, v)
-#   define AV_RL(s, p)    bswap_##s(AV_RN##s(p))
-#   define AV_WL(s, p, v) AV_WN##s(p, bswap_##s(v))
+#   define AV_RL(s, p)    av_bswap##s(AV_RN##s(p))
+#   define AV_WL(s, p, v) AV_WN##s(p, av_bswap##s(v))
 #else
-#   define AV_RB(s, p)    bswap_##s(AV_RN##s(p))
-#   define AV_WB(s, p, v) AV_WN##s(p, bswap_##s(v))
+#   define AV_RB(s, p)    av_bswap##s(AV_RN##s(p))
+#   define AV_WB(s, p, v) AV_WN##s(p, av_bswap##s(v))
 #   define AV_RL(s, p)    AV_RN##s(p)
 #   define AV_WL(s, p, v) AV_WN##s(p, v)
 #endif
diff --git a/libavutil/inverse.c b/libavutil/inverse.c
new file mode 100644
index 0000000..bca6183
--- /dev/null
+++ b/libavutil/inverse.c
@@ -0,0 +1,60 @@
+/*
+ * Inverse table
+ * Copyright (c) 2002-2004 Michael Niedermayer <michaelni at gmx.at>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "libavutil/intmath.h"
+
+/* a*inverse[b]>>32 == a/b for all 0<=a<=16909558 && 2<=b<=256
+ * for a>16909558, is an overestimate by less than 1 part in 1<<24 */
+const uint32_t ff_inverse[257]={
+         0, 4294967295U,2147483648U,1431655766, 1073741824,  858993460,  715827883,  613566757,
+ 536870912,  477218589,  429496730,  390451573,  357913942,  330382100,  306783379,  286331154,
+ 268435456,  252645136,  238609295,  226050911,  214748365,  204522253,  195225787,  186737709,
+ 178956971,  171798692,  165191050,  159072863,  153391690,  148102321,  143165577,  138547333,
+ 134217728,  130150525,  126322568,  122713352,  119304648,  116080198,  113025456,  110127367,
+ 107374183,  104755300,  102261127,   99882961,   97612894,   95443718,   93368855,   91382283,
+  89478486,   87652394,   85899346,   84215046,   82595525,   81037119,   79536432,   78090315,
+  76695845,   75350304,   74051161,   72796056,   71582789,   70409300,   69273667,   68174085,
+  67108864,   66076420,   65075263,   64103990,   63161284,   62245903,   61356676,   60492498,
+  59652324,   58835169,   58040099,   57266231,   56512728,   55778797,   55063684,   54366675,
+  53687092,   53024288,   52377650,   51746594,   51130564,   50529028,   49941481,   49367441,
+  48806447,   48258060,   47721859,   47197443,   46684428,   46182445,   45691142,   45210183,
+  44739243,   44278014,   43826197,   43383509,   42949673,   42524429,   42107523,   41698712,
+  41297763,   40904451,   40518560,   40139882,   39768216,   39403370,   39045158,   38693400,
+  38347923,   38008561,   37675152,   37347542,   37025581,   36709123,   36398028,   36092163,
+  35791395,   35495598,   35204650,   34918434,   34636834,   34359739,   34087043,   33818641,
+  33554432,   33294321,   33038210,   32786010,   32537632,   32292988,   32051995,   31814573,
+  31580642,   31350127,   31122952,   30899046,   30678338,   30460761,   30246249,   30034737,
+  29826162,   29620465,   29417585,   29217465,   29020050,   28825284,   28633116,   28443493,
+  28256364,   28071682,   27889399,   27709467,   27531842,   27356480,   27183338,   27012373,
+  26843546,   26676816,   26512144,   26349493,   26188825,   26030105,   25873297,   25718368,
+  25565282,   25414008,   25264514,   25116768,   24970741,   24826401,   24683721,   24542671,
+  24403224,   24265352,   24129030,   23994231,   23860930,   23729102,   23598722,   23469767,
+  23342214,   23216040,   23091223,   22967740,   22845571,   22724695,   22605092,   22486740,
+  22369622,   22253717,   22139007,   22025474,   21913099,   21801865,   21691755,   21582751,
+  21474837,   21367997,   21262215,   21157475,   21053762,   20951060,   20849356,   20748635,
+  20648882,   20550083,   20452226,   20355296,   20259280,   20164166,   20069941,   19976593,
+  19884108,   19792477,   19701685,   19611723,   19522579,   19434242,   19346700,   19259944,
+  19173962,   19088744,   19004281,   18920561,   18837576,   18755316,   18673771,   18592933,
+  18512791,   18433337,   18354562,   18276457,   18199014,   18122225,   18046082,   17970575,
+  17895698,   17821442,   17747799,   17674763,   17602325,   17530479,   17459217,   17388532,
+  17318417,   17248865,   17179870,   17111424,   17043522,   16976156,   16909321,   16843010,
+  16777216
+};
diff --git a/libavutil/lfg.c b/libavutil/lfg.c
index 1dad4e4..7fab806 100644
--- a/libavutil/lfg.c
+++ b/libavutil/lfg.c
@@ -2,24 +2,26 @@
  * Lagged Fibonacci PRNG
  * Copyright (c) 2008 Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include <inttypes.h>
+#include <limits.h>
+#include <math.h>
 #include "lfg.h"
 #include "md5.h"
 #include "intreadwrite.h"
diff --git a/libavutil/lfg.h b/libavutil/lfg.h
index ac89d12..89a635a 100644
--- a/libavutil/lfg.h
+++ b/libavutil/lfg.h
@@ -2,20 +2,20 @@
  * Lagged Fibonacci PRNG
  * Copyright (c) 2008 Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -30,7 +30,7 @@ typedef struct {
 void av_lfg_init(AVLFG *c, unsigned int seed);
 
 /**
- * Gets the next random unsigned 32-bit number using an ALFG.
+ * Get the next random unsigned 32-bit number using an ALFG.
  *
  * Please also consider a simple LCG like state= state*1664525+1013904223,
  * it may be good enough and faster for your specific use case.
@@ -41,7 +41,7 @@ static inline unsigned int av_lfg_get(AVLFG *c){
 }
 
 /**
- * Gets the next random unsigned 32-bit number using a MLFG.
+ * Get the next random unsigned 32-bit number using a MLFG.
  *
  * Please also consider av_lfg_get() above, it is faster.
  */
@@ -52,10 +52,10 @@ static inline unsigned int av_mlfg_get(AVLFG *c){
 }
 
 /**
- * Gets the next two numbers generated by a Box-Muller Gaussian
+ * Get the next two numbers generated by a Box-Muller Gaussian
  * generator using the random numbers issued by lfg.
  *
- * @param out[2] array where are placed the two generated numbers
+ * @param out[2] array where the two generated numbers are placed
  */
 void av_bmg_get(AVLFG *lfg, double out[2]);
 
diff --git a/libavutil/libm.h b/libavutil/libm.h
index c7c28ac..704bcf9 100644
--- a/libavutil/libm.h
+++ b/libavutil/libm.h
@@ -1,18 +1,18 @@
 /*
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavutil/lls.c b/libavutil/lls.c
index 3855792..6797385 100644
--- a/libavutil/lls.c
+++ b/libavutil/lls.c
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavutil/lls.h b/libavutil/lls.h
index d168e59..3db391b 100644
--- a/libavutil/lls.h
+++ b/libavutil/lls.h
@@ -3,20 +3,20 @@
  *
  * Copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavutil/log.c b/libavutil/log.c
index 9a8b66e..3b82448 100644
--- a/libavutil/log.c
+++ b/libavutil/log.c
@@ -2,20 +2,20 @@
  * log functions
  * Copyright (c) 2003 Michel Bardiaux
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -33,55 +33,95 @@
 static
 #endif
 int av_log_level = AV_LOG_INFO;
+static int flags;
 
-static int use_ansi_color=-1;
+#if defined(_WIN32) && !defined(__MINGW32CE__)
+#include <windows.h>
+static const uint8_t color[] = {12,12,12,14,7,7,7};
+static int16_t background, attr_orig;
+static HANDLE con;
+#define set_color(x)  SetConsoleTextAttribute(con, background | color[x])
+#define reset_color() SetConsoleTextAttribute(con, attr_orig)
+#else
+static const uint8_t color[]={0x41,0x41,0x11,0x03,9,9,9};
+#define set_color(x)  fprintf(stderr, "\033[%d;3%dm", color[x]>>4, color[x]&15)
+#define reset_color() fprintf(stderr, "\033[0m")
+#endif
+static int use_color=-1;
 
 #undef fprintf
-static void colored_fputs(int color, const char *str){
-    if(use_ansi_color<0){
-#if HAVE_ISATTY && !defined(_WIN32)
-        use_ansi_color= getenv("TERM") && !getenv("NO_COLOR") && isatty(2);
+static void colored_fputs(int level, const char *str){
+    if(use_color<0){
+#if defined(_WIN32) && !defined(__MINGW32CE__)
+        CONSOLE_SCREEN_BUFFER_INFO con_info;
+        con = GetStdHandle(STD_ERROR_HANDLE);
+        use_color = (con != INVALID_HANDLE_VALUE) && !getenv("NO_COLOR") && !getenv("FFMPEG_FORCE_NOCOLOR");
+        if (use_color) {
+            GetConsoleScreenBufferInfo(con, &con_info);
+            attr_orig  = con_info.wAttributes;
+            background = attr_orig & 0xF0;
+        }
+#elif HAVE_ISATTY
+        use_color= !getenv("NO_COLOR") && !getenv("FFMPEG_FORCE_NOCOLOR") &&
+            (getenv("TERM") && isatty(2) || getenv("FFMPEG_FORCE_COLOR"));
 #else
-        use_ansi_color= 0;
+        use_color= getenv("FFMPEG_FORCE_COLOR") && !getenv("NO_COLOR") && !getenv("FFMPEG_FORCE_NOCOLOR");
 #endif
     }
 
-    if(use_ansi_color){
-        fprintf(stderr, "\033[%d;3%dm", color>>4, color&15);
+    if(use_color){
+        set_color(level);
     }
     fputs(str, stderr);
-    if(use_ansi_color){
-        fprintf(stderr, "\033[0m");
+    if(use_color){
+        reset_color();
     }
 }
 
+const char* av_default_item_name(void* ptr){
+    return (*(AVClass**)ptr)->class_name;
+}
+
 void av_log_default_callback(void* ptr, int level, const char* fmt, va_list vl)
 {
     static int print_prefix=1;
     static int count;
     static char line[1024], prev[1024];
-    static const uint8_t color[]={0x41,0x41,0x11,0x03,9,9,9};
+    static int is_atty;
     AVClass* avc= ptr ? *(AVClass**)ptr : NULL;
     if(level>av_log_level)
         return;
+    line[0]=0;
 #undef fprintf
     if(print_prefix && avc) {
-        snprintf(line, sizeof(line), "[%s @ %p]", avc->item_name(ptr), ptr);
-    }else
-        line[0]=0;
+        if(avc->version >= (50<<16 | 15<<8 | 3) && avc->parent_log_context_offset){
+            AVClass** parent= *(AVClass***)(((uint8_t*)ptr) + avc->parent_log_context_offset);
+            if(parent && *parent){
+                snprintf(line, sizeof(line), "[%s @ %p] ", (*parent)->item_name(parent), parent);
+            }
+        }
+        snprintf(line + strlen(line), sizeof(line) - strlen(line), "[%s @ %p] ", avc->item_name(ptr), ptr);
+    }
 
     vsnprintf(line + strlen(line), sizeof(line) - strlen(line), fmt, vl);
 
     print_prefix= line[strlen(line)-1] == '\n';
-    if(print_prefix && !strcmp(line, prev)){
+
+#if HAVE_ISATTY
+    if(!is_atty) is_atty= isatty(2) ? 1 : -1;
+#endif
+
+    if(print_prefix && (flags & AV_LOG_SKIP_REPEATED) && !strcmp(line, prev)){
         count++;
+        if(is_atty==1)
+            fprintf(stderr, "    Last message repeated %d times\r", count);
         return;
     }
     if(count>0){
         fprintf(stderr, "    Last message repeated %d times\n", count);
         count=0;
     }
-    colored_fputs(color[av_clip(level>>3, 0, 6)], line);
+    colored_fputs(av_clip(level>>3, 0, 6), line);
     strcpy(prev, line);
 }
 
@@ -89,8 +129,11 @@ static void (*av_log_callback)(void*, int, const char*, va_list) = av_log_defaul
 
 void av_log(void* avcl, int level, const char *fmt, ...)
 {
+    AVClass* avc= avcl ? *(AVClass**)avcl : NULL;
     va_list vl;
     va_start(vl, fmt);
+    if(avc && avc->version >= (50<<16 | 15<<8 | 2) && avc->log_level_offset_offset && level>=AV_LOG_FATAL)
+        level += *(int*)(((uint8_t*)avcl) + avc->log_level_offset_offset);
     av_vlog(avcl, level, fmt, vl);
     va_end(vl);
 }
@@ -110,6 +153,11 @@ void av_log_set_level(int level)
     av_log_level = level;
 }
 
+void av_log_set_flags(int arg)
+{
+    flags= arg;
+}
+
 void av_log_set_callback(void (*callback)(void*, int, const char*, va_list))
 {
     av_log_callback = callback;
diff --git a/libavutil/log.h b/libavutil/log.h
index 1c3e490..1cd9269 100644
--- a/libavutil/log.h
+++ b/libavutil/log.h
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,7 +25,7 @@
 #include "avutil.h"
 
 /**
- * Describes the class of an AVClass context structure. That is an
+ * Describe the class of an AVClass context structure. That is an
  * arbitrary struct of which the first field is a pointer to an
  * AVClass struct (e.g. AVCodecContext, AVFormatContext etc.).
  */
@@ -56,6 +56,20 @@ typedef struct {
      */
 
     int version;
+
+    /**
+     * Offset in the structure where log_level_offset is stored.
+     * 0 means there is no such variable
+     */
+    int log_level_offset_offset;
+
+    /**
+     * Offset in the structure where a pointer to the parent context for loging is stored.
+     * for example a decoder that uses eval.c could pass its AVCodecContext to eval as such
+     * parent context. And a av_log() implementation could then display the parent context
+     * can be NULL of course
+     */
+    int parent_log_context_offset;
 } AVClass;
 
 /* av_log API */
@@ -95,7 +109,7 @@ typedef struct {
 #define AV_LOG_DEBUG    48
 
 /**
- * Sends the specified message to the log if the level is less than or equal
+ * Send the specified message to the log if the level is less than or equal
  * to the current av_log_level. By default, all logging messages are sent to
  * stderr. This behavior can be altered by setting a different av_vlog callback
  * function.
@@ -109,15 +123,38 @@ typedef struct {
  * @see av_vlog
  */
 #ifdef __GNUC__
-void av_log(void*, int level, const char *fmt, ...) __attribute__ ((__format__ (__printf__, 3, 4)));
+void av_log(void *avcl, int level, const char *fmt, ...) __attribute__ ((__format__ (__printf__, 3, 4)));
 #else
-void av_log(void*, int level, const char *fmt, ...);
+void av_log(void *avcl, int level, const char *fmt, ...);
 #endif
 
-void av_vlog(void*, int level, const char *fmt, va_list);
+void av_vlog(void *avcl, int level, const char *fmt, va_list);
 int av_log_get_level(void);
 void av_log_set_level(int);
 void av_log_set_callback(void (*)(void*, int, const char*, va_list));
 void av_log_default_callback(void* ptr, int level, const char* fmt, va_list vl);
+const char* av_default_item_name(void* ctx);
+
+/**
+ * av_dlog macros
+ * Useful to print debug messages that shouldn't get compiled in normally.
+ */
+
+#ifdef DEBUG
+#    define av_dlog(pctx, ...) av_log(pctx, AV_LOG_DEBUG, __VA_ARGS__)
+#else
+#    define av_dlog(pctx, ...)
+#endif
+
+/**
+ * Skip repeated messages, this requires the user app to use av_log() instead of
+ * (f)printf as the 2 would otherwise interfere and lead to
+ * "Last message repeated x times" messages below (f)printf messages with some
+ * bad luck.
+ * Also to receive the last, "last repeated" line if any, the user app must
+ * call av_log(NULL, AV_LOG_QUIET, ""); at the end
+ */
+#define AV_LOG_SKIP_REPEATED 1
+void av_log_set_flags(int arg);
 
 #endif /* AVUTIL_LOG_H */
diff --git a/libavutil/lzo.c b/libavutil/lzo.c
index a876fc7..ef01653 100644
--- a/libavutil/lzo.c
+++ b/libavutil/lzo.c
@@ -2,20 +2,20 @@
  * LZO 1x decompression
  * Copyright (c) 2006 Reimar Doeffinger
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -175,6 +175,14 @@ int av_lzo1x_decode(void *out, int *outlen, const void *in, int *inlen) {
     int state= 0;
     int x;
     LZOContext c;
+    if (!*outlen || !*inlen) {
+        int res = 0;
+        if (!*outlen)
+            res |= AV_LZO_OUTPUT_FULL;
+        if (!*inlen)
+            res |= AV_LZO_INPUT_DEPLETED;
+        return res;
+    }
     c.in = in;
     c.in_end = (const uint8_t *)in + *inlen;
     c.out = c.out_start = out;
diff --git a/libavutil/lzo.h b/libavutil/lzo.h
index 6788054..01c9280 100644
--- a/libavutil/lzo.h
+++ b/libavutil/lzo.h
@@ -2,20 +2,20 @@
  * LZO 1x decompression
  * copyright (c) 2006 Reimar Doeffinger
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavutil/mathematics.c b/libavutil/mathematics.c
index c06cb16..53155c3 100644
--- a/libavutil/mathematics.c
+++ b/libavutil/mathematics.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2005 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -78,7 +78,7 @@ int64_t av_rescale_rnd(int64_t a, int64_t b, int64_t c, enum AVRounding rnd){
     int64_t r=0;
     assert(c > 0);
     assert(b >=0);
-    assert(rnd >=0 && rnd<=5 && rnd!=4);
+    assert((unsigned)rnd<=5 && rnd!=4);
 
     if(a<0 && a != INT64_MIN) return -av_rescale_rnd(-a, b, c, rnd ^ ((rnd>>1)&1));
 
@@ -144,6 +144,13 @@ int av_compare_ts(int64_t ts_a, AVRational tb_a, int64_t ts_b, AVRational tb_b){
     return 0;
 }
 
+int64_t av_compare_mod(uint64_t a, uint64_t b, uint64_t mod){
+    int64_t c= (a-b) & (mod-1);
+    if(c > (mod>>1))
+        c-= mod;
+    return c;
+}
+
 #ifdef TEST
 #include "integer.h"
 #undef printf
diff --git a/libavutil/mathematics.h b/libavutil/mathematics.h
index e198aef..35494bb 100644
--- a/libavutil/mathematics.h
+++ b/libavutil/mathematics.h
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2005 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -38,6 +38,9 @@
 #ifndef M_LOG2_10
 #define M_LOG2_10      3.32192809488736234787  /* log_2 10 */
 #endif
+#ifndef M_PHI
+#define M_PHI          1.61803398874989484820   /* phi / golden ratio */
+#endif
 #ifndef M_PI
 #define M_PI           3.14159265358979323846  /* pi */
 #endif
@@ -63,36 +66,47 @@ enum AVRounding {
 };
 
 /**
- * Returns the greatest common divisor of a and b.
+ * Return the greatest common divisor of a and b.
  * If both a and b are 0 or either or both are <0 then behavior is
  * undefined.
  */
 int64_t av_const av_gcd(int64_t a, int64_t b);
 
 /**
- * Rescales a 64-bit integer with rounding to nearest.
+ * Rescale a 64-bit integer with rounding to nearest.
  * A simple a*b/c isn't possible as it can overflow.
  */
 int64_t av_rescale(int64_t a, int64_t b, int64_t c) av_const;
 
 /**
- * Rescales a 64-bit integer with specified rounding.
+ * Rescale a 64-bit integer with specified rounding.
  * A simple a*b/c isn't possible as it can overflow.
  */
 int64_t av_rescale_rnd(int64_t a, int64_t b, int64_t c, enum AVRounding) av_const;
 
 /**
- * Rescales a 64-bit integer by 2 rational numbers.
+ * Rescale a 64-bit integer by 2 rational numbers.
  */
 int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq) av_const;
 
 /**
- * Compares 2 timestamps each in its own timebases.
+ * Compare 2 timestamps each in its own timebases.
  * The result of the function is undefined if one of the timestamps
  * is outside the int64_t range when represented in the others timebase.
  * @return -1 if ts_a is before ts_b, 1 if ts_a is after ts_b or 0 if they represent the same position
  */
 int av_compare_ts(int64_t ts_a, AVRational tb_a, int64_t ts_b, AVRational tb_b);
 
+/**
+ * Compare 2 integers modulo mod.
+ * That is we compare integers a and b for which only the least
+ * significant log2(mod) bits are known.
+ *
+ * @param mod must be a power of 2
+ * @return a negative value if a is smaller than b
+ *         a positive value if a is greater than b
+ *         0                if a equals          b
+ */
+int64_t av_compare_mod(uint64_t a, uint64_t b, uint64_t mod);
 
 #endif /* AVUTIL_MATHEMATICS_H */
diff --git a/libavutil/md5.c b/libavutil/md5.c
index 39ee624..271d71f 100644
--- a/libavutil/md5.c
+++ b/libavutil/md5.c
@@ -13,20 +13,20 @@
  * If you use gcc, then version 4.1 or later and -fomit-frame-pointer is
  * strongly recommended.
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -95,7 +95,7 @@ static void body(uint32_t ABCD[4], uint32_t X[16]){
 
 #if HAVE_BIGENDIAN
     for(i=0; i<16; i++)
-        X[i]= bswap_32(X[i]);
+        X[i]= av_bswap32(X[i]);
 #endif
 
 #if CONFIG_SMALL
@@ -141,7 +141,7 @@ void av_md5_update(AVMD5 *ctx, const uint8_t *src, const int len){
 
 void av_md5_final(AVMD5 *ctx, uint8_t *dst){
     int i;
-    uint64_t finalcount= le2me_64(ctx->len<<3);
+    uint64_t finalcount= av_le2ne64(ctx->len<<3);
 
     av_md5_update(ctx, "\200", 1);
     while((ctx->len & 63)!=56)
@@ -150,7 +150,7 @@ void av_md5_final(AVMD5 *ctx, uint8_t *dst){
     av_md5_update(ctx, (uint8_t*)&finalcount, 8);
 
     for(i=0; i<4; i++)
-        ((uint32_t*)dst)[i]= le2me_32(ctx->ABCD[3-i]);
+        ((uint32_t*)dst)[i]= av_le2ne32(ctx->ABCD[3-i]);
 }
 
 void av_md5_sum(uint8_t *dst, const uint8_t *src, const int len){
diff --git a/libavutil/md5.h b/libavutil/md5.h
index 969202a..c178bbb 100644
--- a/libavutil/md5.h
+++ b/libavutil/md5.h
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavutil/mem.c b/libavutil/mem.c
index 8cad089..7a54bd0 100644
--- a/libavutil/mem.c
+++ b/libavutil/mem.c
@@ -2,20 +2,20 @@
  * default memory allocator for libavutil
  * Copyright (c) 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -61,7 +61,7 @@ void  free(void *ptr);
    memory allocator. You do not need to suppress this file because the
    linker will do it automatically. */
 
-void *av_malloc(unsigned int size)
+void *av_malloc(FF_INTERNAL_MEM_TYPE size)
 {
     void *ptr = NULL;
 #if CONFIG_MEMALIGN_HACK
@@ -116,7 +116,7 @@ void *av_malloc(unsigned int size)
     return ptr;
 }
 
-void *av_realloc(void *ptr, unsigned int size)
+void *av_realloc(void *ptr, FF_INTERNAL_MEM_TYPE size)
 {
 #if CONFIG_MEMALIGN_HACK
     int diff;
@@ -138,12 +138,11 @@ void *av_realloc(void *ptr, unsigned int size)
 
 void av_free(void *ptr)
 {
-    /* XXX: this test should not be needed on most libcs */
-    if (ptr)
 #if CONFIG_MEMALIGN_HACK
+    if (ptr)
         free((char*)ptr - ((char*)ptr)[-1]);
 #else
-        free(ptr);
+    free(ptr);
 #endif
 }
 
@@ -154,7 +153,7 @@ void av_freep(void *arg)
     *ptr = NULL;
 }
 
-void *av_mallocz(unsigned int size)
+void *av_mallocz(FF_INTERNAL_MEM_TYPE size)
 {
     void *ptr = av_malloc(size);
     if (ptr)
diff --git a/libavutil/mem.h b/libavutil/mem.h
index 1488792..f52777b 100644
--- a/libavutil/mem.h
+++ b/libavutil/mem.h
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -27,8 +27,9 @@
 #define AVUTIL_MEM_H
 
 #include "attributes.h"
+#include "avutil.h"
 
-#if defined(__ICC) || defined(__SUNPRO_C)
+#if defined(__ICC) && _ICC < 1200 || defined(__SUNPRO_C)
     #define DECLARE_ALIGNED(n,t,v)      t __attribute__ ((aligned (n))) v
     #define DECLARE_ASM_CONST(n,t,v)    const t __attribute__ ((aligned (n))) v
 #elif defined(__TI_COMPILER_VERSION__)
@@ -40,7 +41,7 @@
         static const t __attribute__((aligned(n))) v
 #elif defined(__GNUC__)
     #define DECLARE_ALIGNED(n,t,v)      t __attribute__ ((aligned (n))) v
-    #define DECLARE_ASM_CONST(n,t,v)    static const t attribute_used __attribute__ ((aligned (n))) v
+    #define DECLARE_ASM_CONST(n,t,v)    static const t av_used __attribute__ ((aligned (n))) v
 #elif defined(_MSC_VER)
     #define DECLARE_ALIGNED(n,t,v)      __declspec(align(n)) t v
     #define DECLARE_ASM_CONST(n,t,v)    __declspec(align(n)) static const t v
@@ -55,26 +56,34 @@
     #define av_malloc_attrib
 #endif
 
-#if (!defined(__ICC) || __ICC > 1110) && AV_GCC_VERSION_AT_LEAST(4,3)
+#if AV_GCC_VERSION_AT_LEAST(4,3)
     #define av_alloc_size(n) __attribute__((alloc_size(n)))
 #else
     #define av_alloc_size(n)
 #endif
 
+#if LIBAVUTIL_VERSION_MAJOR < 51
+#   define FF_INTERNAL_MEM_TYPE unsigned int
+#   define FF_INTERNAL_MEM_TYPE_MAX_VALUE UINT_MAX
+#else
+#   define FF_INTERNAL_MEM_TYPE size_t
+#   define FF_INTERNAL_MEM_TYPE_MAX_VALUE SIZE_MAX
+#endif
+
 /**
- * Allocates a block of size bytes with alignment suitable for all
+ * Allocate a block of size bytes with alignment suitable for all
  * memory accesses (including vectors if available on the CPU).
  * @param size Size in bytes for the memory block to be allocated.
  * @return Pointer to the allocated block, NULL if the block cannot
  * be allocated.
  * @see av_mallocz()
  */
-void *av_malloc(unsigned int size) av_malloc_attrib av_alloc_size(1);
+void *av_malloc(FF_INTERNAL_MEM_TYPE size) av_malloc_attrib av_alloc_size(1);
 
 /**
- * Allocates or reallocates a block of memory.
- * If ptr is NULL and size > 0, allocates a new block. If
- * size is zero, frees the memory block pointed to by ptr.
+ * Allocate or reallocate a block of memory.
+ * If ptr is NULL and size > 0, allocate a new block. If
+ * size is zero, free the memory block pointed to by ptr.
  * @param size Size in bytes for the memory block to be allocated or
  * reallocated.
  * @param ptr Pointer to a memory block already allocated with
@@ -83,10 +92,10 @@ void *av_malloc(unsigned int size) av_malloc_attrib av_alloc_size(1);
  * cannot be reallocated or the function is used to free the memory block.
  * @see av_fast_realloc()
  */
-void *av_realloc(void *ptr, unsigned int size) av_alloc_size(2);
+void *av_realloc(void *ptr, FF_INTERNAL_MEM_TYPE size) av_alloc_size(2);
 
 /**
- * Frees a memory block which has been allocated with av_malloc(z)() or
+ * Free a memory block which has been allocated with av_malloc(z)() or
  * av_realloc().
  * @param ptr Pointer to the memory block which should be freed.
  * @note ptr = NULL is explicitly allowed.
@@ -96,17 +105,17 @@ void *av_realloc(void *ptr, unsigned int size) av_alloc_size(2);
 void av_free(void *ptr);
 
 /**
- * Allocates a block of size bytes with alignment suitable for all
+ * Allocate a block of size bytes with alignment suitable for all
  * memory accesses (including vectors if available on the CPU) and
- * zeroes all the bytes of the block.
+ * zero all the bytes of the block.
  * @param size Size in bytes for the memory block to be allocated.
  * @return Pointer to the allocated block, NULL if it cannot be allocated.
  * @see av_malloc()
  */
-void *av_mallocz(unsigned int size) av_malloc_attrib av_alloc_size(1);
+void *av_mallocz(FF_INTERNAL_MEM_TYPE size) av_malloc_attrib av_alloc_size(1);
 
 /**
- * Duplicates the string s.
+ * Duplicate the string s.
  * @param s string to be duplicated
  * @return Pointer to a newly allocated string containing a
  * copy of s or NULL if the string cannot be allocated.
@@ -114,7 +123,7 @@ void *av_mallocz(unsigned int size) av_malloc_attrib av_alloc_size(1);
 char *av_strdup(const char *s) av_malloc_attrib;
 
 /**
- * Frees a memory block which has been allocated with av_malloc(z)() or
+ * Free a memory block which has been allocated with av_malloc(z)() or
  * av_realloc() and set the pointer pointing to it to NULL.
  * @param ptr Pointer to the pointer to the memory block which should
  * be freed.
diff --git a/libavutil/mips/intreadwrite.h b/libavutil/mips/intreadwrite.h
index b7479d3..0e0cc06 100644
--- a/libavutil/mips/intreadwrite.h
+++ b/libavutil/mips/intreadwrite.h
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2009 Mans Rullgard <mans at mansr.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -24,6 +24,8 @@
 #include <stdint.h>
 #include "config.h"
 
+#if HAVE_INLINE_ASM
+
 #define AV_RN32 AV_RN32
 static av_always_inline uint32_t AV_RN32(const void *p)
 {
@@ -91,4 +93,6 @@ static av_always_inline void AV_WN64(void *p, uint64_t v)
 
 #endif /* ARCH_MIPS64 */
 
+#endif /* HAVE_INLINE_ASM */
+
 #endif /* AVUTIL_MIPS_INTREADWRITE_H */
diff --git a/libavutil/opt.c b/libavutil/opt.c
new file mode 100644
index 0000000..30efb52
--- /dev/null
+++ b/libavutil/opt.c
@@ -0,0 +1,607 @@
+/*
+ * AVOptions
+ * Copyright (c) 2005 Michael Niedermayer <michaelni at gmx.at>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * AVOptions
+ * @author Michael Niedermayer <michaelni at gmx.at>
+ */
+
+#include "avutil.h"
+#include "avstring.h"
+#include "opt.h"
+#include "eval.h"
+
+//FIXME order them and do a bin search
+const AVOption *av_find_opt(void *v, const char *name, const char *unit, int mask, int flags)
+{
+    AVClass *c= *(AVClass**)v; //FIXME silly way of storing AVClass
+    const AVOption *o= c->option;
+
+    for (; o && o->name; o++) {
+        if (!strcmp(o->name, name) && (!unit || (o->unit && !strcmp(o->unit, unit))) && (o->flags & mask) == flags)
+            return o;
+    }
+    return NULL;
+}
+
+const AVOption *av_next_option(void *obj, const AVOption *last)
+{
+    if (last && last[1].name) return ++last;
+    else if (last)            return NULL;
+    else                      return (*(AVClass**)obj)->option;
+}
+
+static int av_set_number2(void *obj, const char *name, double num, int den, int64_t intnum, const AVOption **o_out)
+{
+    const AVOption *o= av_find_opt(obj, name, NULL, 0, 0);
+    void *dst;
+    if (o_out)
+        *o_out= o;
+    if (!o || o->offset<=0)
+        return AVERROR(ENOENT);
+
+    if (o->max*den < num*intnum || o->min*den > num*intnum) {
+        av_log(obj, AV_LOG_ERROR, "Value %lf for parameter '%s' out of range\n", num, name);
+        return AVERROR(ERANGE);
+    }
+
+    dst= ((uint8_t*)obj) + o->offset;
+
+    switch (o->type) {
+    case FF_OPT_TYPE_FLAGS:
+    case FF_OPT_TYPE_INT:   *(int       *)dst= llrint(num/den)*intnum; break;
+    case FF_OPT_TYPE_INT64: *(int64_t   *)dst= llrint(num/den)*intnum; break;
+    case FF_OPT_TYPE_FLOAT: *(float     *)dst= num*intnum/den;         break;
+    case FF_OPT_TYPE_DOUBLE:*(double    *)dst= num*intnum/den;         break;
+    case FF_OPT_TYPE_RATIONAL:
+        if ((int)num == num) *(AVRational*)dst= (AVRational){num*intnum, den};
+        else                 *(AVRational*)dst= av_d2q(num*intnum/den, 1<<24);
+        break;
+    default:
+        return AVERROR(EINVAL);
+    }
+    return 0;
+}
+
+static const AVOption *av_set_number(void *obj, const char *name, double num, int den, int64_t intnum)
+{
+    const AVOption *o = NULL;
+    if (av_set_number2(obj, name, num, den, intnum, &o) < 0)
+        return NULL;
+    else
+        return o;
+}
+
+static const double const_values[] = {
+    M_PI,
+    M_E,
+    FF_QP2LAMBDA,
+    0
+};
+
+static const char * const const_names[] = {
+    "PI",
+    "E",
+    "QP2LAMBDA",
+    0
+};
+
+static int hexchar2int(char c) {
+    if (c >= '0' && c <= '9') return c - '0';
+    if (c >= 'a' && c <= 'f') return c - 'a' + 10;
+    if (c >= 'A' && c <= 'F') return c - 'A' + 10;
+    return -1;
+}
+
+int av_set_string3(void *obj, const char *name, const char *val, int alloc, const AVOption **o_out)
+{
+    int ret;
+    const AVOption *o= av_find_opt(obj, name, NULL, 0, 0);
+    if (o_out)
+        *o_out = o;
+    if (!o)
+        return AVERROR(ENOENT);
+    if (!val || o->offset<=0)
+        return AVERROR(EINVAL);
+
+    if (o->type == FF_OPT_TYPE_BINARY) {
+        uint8_t **dst = (uint8_t **)(((uint8_t*)obj) + o->offset);
+        int *lendst = (int *)(dst + 1);
+        uint8_t *bin, *ptr;
+        int len = strlen(val);
+        av_freep(dst);
+        *lendst = 0;
+        if (len & 1) return AVERROR(EINVAL);
+        len /= 2;
+        ptr = bin = av_malloc(len);
+        while (*val) {
+            int a = hexchar2int(*val++);
+            int b = hexchar2int(*val++);
+            if (a < 0 || b < 0) {
+                av_free(bin);
+                return AVERROR(EINVAL);
+            }
+            *ptr++ = (a << 4) | b;
+        }
+        *dst = bin;
+        *lendst = len;
+        return 0;
+    }
+    if (o->type != FF_OPT_TYPE_STRING) {
+        int notfirst=0;
+        for (;;) {
+            int i;
+            char buf[256];
+            int cmd=0;
+            double d;
+
+            if (*val == '+' || *val == '-')
+                cmd= *(val++);
+
+            for (i=0; i<sizeof(buf)-1 && val[i] && val[i]!='+' && val[i]!='-'; i++)
+                buf[i]= val[i];
+            buf[i]=0;
+
+            {
+                const AVOption *o_named= av_find_opt(obj, buf, o->unit, 0, 0);
+                if (o_named && o_named->type == FF_OPT_TYPE_CONST)
+                    d= o_named->default_val;
+                else if (!strcmp(buf, "default")) d= o->default_val;
+                else if (!strcmp(buf, "max"    )) d= o->max;
+                else if (!strcmp(buf, "min"    )) d= o->min;
+                else if (!strcmp(buf, "none"   )) d= 0;
+                else if (!strcmp(buf, "all"    )) d= ~0;
+                else {
+                    int res = av_expr_parse_and_eval(&d, buf, const_names, const_values, NULL, NULL, NULL, NULL, NULL, 0, obj);
+                    if (res < 0) {
+                        av_log(obj, AV_LOG_ERROR, "Unable to parse option value \"%s\"\n", val);
+                        return res;
+                    }
+                }
+            }
+            if (o->type == FF_OPT_TYPE_FLAGS) {
+                if      (cmd=='+') d= av_get_int(obj, name, NULL) | (int64_t)d;
+                else if (cmd=='-') d= av_get_int(obj, name, NULL) &~(int64_t)d;
+            } else {
+                if      (cmd=='+') d= notfirst*av_get_double(obj, name, NULL) + d;
+                else if (cmd=='-') d= notfirst*av_get_double(obj, name, NULL) - d;
+            }
+
+            if ((ret = av_set_number2(obj, name, d, 1, 1, o_out)) < 0)
+                return ret;
+            val+= i;
+            if (!*val)
+                return 0;
+            notfirst=1;
+        }
+        return AVERROR(EINVAL);
+    }
+
+    if (alloc) {
+        av_free(*(void**)(((uint8_t*)obj) + o->offset));
+        val= av_strdup(val);
+    }
+
+    memcpy(((uint8_t*)obj) + o->offset, &val, sizeof(val));
+    return 0;
+}
+
+const AVOption *av_set_double(void *obj, const char *name, double n)
+{
+    return av_set_number(obj, name, n, 1, 1);
+}
+
+const AVOption *av_set_q(void *obj, const char *name, AVRational n)
+{
+    return av_set_number(obj, name, n.num, n.den, 1);
+}
+
+const AVOption *av_set_int(void *obj, const char *name, int64_t n)
+{
+    return av_set_number(obj, name, 1, 1, n);
+}
+
+/**
+ *
+ * @param buf a buffer which is used for returning non string values as strings, can be NULL
+ * @param buf_len allocated length in bytes of buf
+ */
+const char *av_get_string(void *obj, const char *name, const AVOption **o_out, char *buf, int buf_len)
+{
+    const AVOption *o= av_find_opt(obj, name, NULL, 0, 0);
+    void *dst;
+    uint8_t *bin;
+    int len, i;
+    if (!o || o->offset<=0)
+        return NULL;
+    if (o->type != FF_OPT_TYPE_STRING && (!buf || !buf_len))
+        return NULL;
+
+    dst= ((uint8_t*)obj) + o->offset;
+    if (o_out) *o_out= o;
+
+    switch (o->type) {
+    case FF_OPT_TYPE_FLAGS:     snprintf(buf, buf_len, "0x%08X",*(int    *)dst);break;
+    case FF_OPT_TYPE_INT:       snprintf(buf, buf_len, "%d" , *(int    *)dst);break;
+    case FF_OPT_TYPE_INT64:     snprintf(buf, buf_len, "%"PRId64, *(int64_t*)dst);break;
+    case FF_OPT_TYPE_FLOAT:     snprintf(buf, buf_len, "%f" , *(float  *)dst);break;
+    case FF_OPT_TYPE_DOUBLE:    snprintf(buf, buf_len, "%f" , *(double *)dst);break;
+    case FF_OPT_TYPE_RATIONAL:  snprintf(buf, buf_len, "%d/%d", ((AVRational*)dst)->num, ((AVRational*)dst)->den);break;
+    case FF_OPT_TYPE_STRING:    return *(void**)dst;
+    case FF_OPT_TYPE_BINARY:
+        len = *(int*)(((uint8_t *)dst) + sizeof(uint8_t *));
+        if (len >= (buf_len + 1)/2) return NULL;
+        bin = *(uint8_t**)dst;
+        for (i = 0; i < len; i++) snprintf(buf + i*2, 3, "%02X", bin[i]);
+        break;
+    default: return NULL;
+    }
+    return buf;
+}
+
+static int av_get_number(void *obj, const char *name, const AVOption **o_out, double *num, int *den, int64_t *intnum)
+{
+    const AVOption *o= av_find_opt(obj, name, NULL, 0, 0);
+    void *dst;
+    if (!o || o->offset<=0)
+        goto error;
+
+    dst= ((uint8_t*)obj) + o->offset;
+
+    if (o_out) *o_out= o;
+
+    switch (o->type) {
+    case FF_OPT_TYPE_FLAGS:     *intnum= *(unsigned int*)dst;return 0;
+    case FF_OPT_TYPE_INT:       *intnum= *(int    *)dst;return 0;
+    case FF_OPT_TYPE_INT64:     *intnum= *(int64_t*)dst;return 0;
+    case FF_OPT_TYPE_FLOAT:     *num=    *(float  *)dst;return 0;
+    case FF_OPT_TYPE_DOUBLE:    *num=    *(double *)dst;return 0;
+    case FF_OPT_TYPE_RATIONAL:  *intnum= ((AVRational*)dst)->num;
+                                *den   = ((AVRational*)dst)->den;
+                                                        return 0;
+    }
+error:
+    *den=*intnum=0;
+    return -1;
+}
+
+double av_get_double(void *obj, const char *name, const AVOption **o_out)
+{
+    int64_t intnum=1;
+    double num=1;
+    int den=1;
+
+    av_get_number(obj, name, o_out, &num, &den, &intnum);
+    return num*intnum/den;
+}
+
+AVRational av_get_q(void *obj, const char *name, const AVOption **o_out)
+{
+    int64_t intnum=1;
+    double num=1;
+    int den=1;
+
+    av_get_number(obj, name, o_out, &num, &den, &intnum);
+    if (num == 1.0 && (int)intnum == intnum)
+        return (AVRational){intnum, den};
+    else
+        return av_d2q(num*intnum/den, 1<<24);
+}
+
+int64_t av_get_int(void *obj, const char *name, const AVOption **o_out)
+{
+    int64_t intnum=1;
+    double num=1;
+    int den=1;
+
+    av_get_number(obj, name, o_out, &num, &den, &intnum);
+    return num*intnum/den;
+}
+
+static void opt_list(void *obj, void *av_log_obj, const char *unit,
+                     int req_flags, int rej_flags)
+{
+    const AVOption *opt=NULL;
+
+    while ((opt= av_next_option(obj, opt))) {
+        if (!(opt->flags & req_flags) || (opt->flags & rej_flags))
+            continue;
+
+        /* Don't print CONST's on level one.
+         * Don't print anything but CONST's on level two.
+         * Only print items from the requested unit.
+         */
+        if (!unit && opt->type==FF_OPT_TYPE_CONST)
+            continue;
+        else if (unit && opt->type!=FF_OPT_TYPE_CONST)
+            continue;
+        else if (unit && opt->type==FF_OPT_TYPE_CONST && strcmp(unit, opt->unit))
+            continue;
+        else if (unit && opt->type == FF_OPT_TYPE_CONST)
+            av_log(av_log_obj, AV_LOG_INFO, "   %-15s ", opt->name);
+        else
+            av_log(av_log_obj, AV_LOG_INFO, "-%-17s ", opt->name);
+
+        switch (opt->type) {
+            case FF_OPT_TYPE_FLAGS:
+                av_log(av_log_obj, AV_LOG_INFO, "%-7s ", "<flags>");
+                break;
+            case FF_OPT_TYPE_INT:
+                av_log(av_log_obj, AV_LOG_INFO, "%-7s ", "<int>");
+                break;
+            case FF_OPT_TYPE_INT64:
+                av_log(av_log_obj, AV_LOG_INFO, "%-7s ", "<int64>");
+                break;
+            case FF_OPT_TYPE_DOUBLE:
+                av_log(av_log_obj, AV_LOG_INFO, "%-7s ", "<double>");
+                break;
+            case FF_OPT_TYPE_FLOAT:
+                av_log(av_log_obj, AV_LOG_INFO, "%-7s ", "<float>");
+                break;
+            case FF_OPT_TYPE_STRING:
+                av_log(av_log_obj, AV_LOG_INFO, "%-7s ", "<string>");
+                break;
+            case FF_OPT_TYPE_RATIONAL:
+                av_log(av_log_obj, AV_LOG_INFO, "%-7s ", "<rational>");
+                break;
+            case FF_OPT_TYPE_BINARY:
+                av_log(av_log_obj, AV_LOG_INFO, "%-7s ", "<binary>");
+                break;
+            case FF_OPT_TYPE_CONST:
+            default:
+                av_log(av_log_obj, AV_LOG_INFO, "%-7s ", "");
+                break;
+        }
+        av_log(av_log_obj, AV_LOG_INFO, "%c", (opt->flags & AV_OPT_FLAG_ENCODING_PARAM) ? 'E' : '.');
+        av_log(av_log_obj, AV_LOG_INFO, "%c", (opt->flags & AV_OPT_FLAG_DECODING_PARAM) ? 'D' : '.');
+        av_log(av_log_obj, AV_LOG_INFO, "%c", (opt->flags & AV_OPT_FLAG_VIDEO_PARAM   ) ? 'V' : '.');
+        av_log(av_log_obj, AV_LOG_INFO, "%c", (opt->flags & AV_OPT_FLAG_AUDIO_PARAM   ) ? 'A' : '.');
+        av_log(av_log_obj, AV_LOG_INFO, "%c", (opt->flags & AV_OPT_FLAG_SUBTITLE_PARAM) ? 'S' : '.');
+
+        if (opt->help)
+            av_log(av_log_obj, AV_LOG_INFO, " %s", opt->help);
+        av_log(av_log_obj, AV_LOG_INFO, "\n");
+        if (opt->unit && opt->type != FF_OPT_TYPE_CONST) {
+            opt_list(obj, av_log_obj, opt->unit, req_flags, rej_flags);
+        }
+    }
+}
+
+int av_opt_show2(void *obj, void *av_log_obj, int req_flags, int rej_flags)
+{
+    if (!obj)
+        return -1;
+
+    av_log(av_log_obj, AV_LOG_INFO, "%s AVOptions:\n", (*(AVClass**)obj)->class_name);
+
+    opt_list(obj, av_log_obj, NULL, req_flags, rej_flags);
+
+    return 0;
+}
+
+/** Set the values of the AVCodecContext or AVFormatContext structure.
+ * They are set to the defaults specified in the according AVOption options
+ * array default_val field.
+ *
+ * @param s AVCodecContext or AVFormatContext for which the defaults will be set
+ */
+void av_opt_set_defaults2(void *s, int mask, int flags)
+{
+    const AVOption *opt = NULL;
+    while ((opt = av_next_option(s, opt)) != NULL) {
+        if ((opt->flags & mask) != flags)
+            continue;
+        switch (opt->type) {
+            case FF_OPT_TYPE_CONST:
+                /* Nothing to be done here */
+            break;
+            case FF_OPT_TYPE_FLAGS:
+            case FF_OPT_TYPE_INT: {
+                int val;
+                val = opt->default_val;
+                av_set_int(s, opt->name, val);
+            }
+            break;
+            case FF_OPT_TYPE_INT64:
+                if ((double)(opt->default_val+0.6) == opt->default_val)
+                    av_log(s, AV_LOG_DEBUG, "loss of precision in default of %s\n", opt->name);
+                av_set_int(s, opt->name, opt->default_val);
+            break;
+            case FF_OPT_TYPE_DOUBLE:
+            case FF_OPT_TYPE_FLOAT: {
+                double val;
+                val = opt->default_val;
+                av_set_double(s, opt->name, val);
+            }
+            break;
+            case FF_OPT_TYPE_RATIONAL: {
+                AVRational val;
+                val = av_d2q(opt->default_val, INT_MAX);
+                av_set_q(s, opt->name, val);
+            }
+            break;
+            case FF_OPT_TYPE_STRING:
+            case FF_OPT_TYPE_BINARY:
+                /* Cannot set default for string as default_val is of type * double */
+            break;
+            default:
+                av_log(s, AV_LOG_DEBUG, "AVOption type %d of option %s not implemented yet\n", opt->type, opt->name);
+        }
+    }
+}
+
+void av_opt_set_defaults(void *s)
+{
+    av_opt_set_defaults2(s, 0, 0);
+}
+
+/**
+ * Store the value in the field in ctx that is named like key.
+ * ctx must be an AVClass context, storing is done using AVOptions.
+ *
+ * @param buf the string to parse, buf will be updated to point at the
+ * separator just after the parsed key/value pair
+ * @param key_val_sep a 0-terminated list of characters used to
+ * separate key from value
+ * @param pairs_sep a 0-terminated list of characters used to separate
+ * two pairs from each other
+ * @return 0 if the key/value pair has been successfully parsed and
+ * set, or a negative value corresponding to an AVERROR code in case
+ * of error:
+ * AVERROR(EINVAL) if the key/value pair cannot be parsed,
+ * the error code issued by av_set_string3() if the key/value pair
+ * cannot be set
+ */
+static int parse_key_value_pair(void *ctx, const char **buf,
+                                const char *key_val_sep, const char *pairs_sep)
+{
+    char *key = av_get_token(buf, key_val_sep);
+    char *val;
+    int ret;
+
+    if (*key && strspn(*buf, key_val_sep)) {
+        (*buf)++;
+        val = av_get_token(buf, pairs_sep);
+    } else {
+        av_log(ctx, AV_LOG_ERROR, "Missing key or no key/value separator found after key '%s'\n", key);
+        av_free(key);
+        return AVERROR(EINVAL);
+    }
+
+    av_log(ctx, AV_LOG_DEBUG, "Setting value '%s' for key '%s'\n", val, key);
+
+    ret = av_set_string3(ctx, key, val, 1, NULL);
+    if (ret == AVERROR(ENOENT))
+        av_log(ctx, AV_LOG_ERROR, "Key '%s' not found.\n", key);
+
+    av_free(key);
+    av_free(val);
+    return ret;
+}
+
+int av_set_options_string(void *ctx, const char *opts,
+                          const char *key_val_sep, const char *pairs_sep)
+{
+    int ret, count = 0;
+
+    while (*opts) {
+        if ((ret = parse_key_value_pair(ctx, &opts, key_val_sep, pairs_sep)) < 0)
+            return ret;
+        count++;
+
+        if (*opts)
+            opts++;
+    }
+
+    return count;
+}
+
+#ifdef TEST
+
+#undef printf
+
+typedef struct TestContext
+{
+    const AVClass *class;
+    int num;
+    int toggle;
+    char *string;
+    int flags;
+    AVRational rational;
+} TestContext;
+
+#define OFFSET(x) offsetof(TestContext, x)
+
+#define TEST_FLAG_COOL 01
+#define TEST_FLAG_LAME 02
+#define TEST_FLAG_MU   04
+
+static const AVOption test_options[]= {
+{"num",      "set num",        OFFSET(num),      FF_OPT_TYPE_INT,      0,              0,        100                 },
+{"toggle",   "set toggle",     OFFSET(toggle),   FF_OPT_TYPE_INT,      0,              0,        1                   },
+{"rational", "set rational",   OFFSET(rational), FF_OPT_TYPE_RATIONAL, 0,              0,        10                  },
+{"string",   "set string",     OFFSET(string),   FF_OPT_TYPE_STRING,   0,              CHAR_MIN, CHAR_MAX            },
+{"flags",    "set flags",      OFFSET(flags),    FF_OPT_TYPE_FLAGS,    0,              0,        INT_MAX, 0, "flags" },
+{"cool",     "set cool flag ", 0,                FF_OPT_TYPE_CONST,    TEST_FLAG_COOL, INT_MIN,  INT_MAX, 0, "flags" },
+{"lame",     "set lame flag ", 0,                FF_OPT_TYPE_CONST,    TEST_FLAG_LAME, INT_MIN,  INT_MAX, 0, "flags" },
+{"mu",       "set mu flag ",   0,                FF_OPT_TYPE_CONST,    TEST_FLAG_MU,   INT_MIN,  INT_MAX, 0, "flags" },
+{NULL},
+};
+
+static const char *test_get_name(void *ctx)
+{
+    return "test";
+}
+
+static const AVClass test_class = {
+    "TestContext",
+    test_get_name,
+    test_options
+};
+
+int main(void)
+{
+    int i;
+
+    printf("\nTesting av_set_options_string()\n");
+    {
+        TestContext test_ctx;
+        const char *options[] = {
+            "",
+            ":",
+            "=",
+            "foo=:",
+            ":=foo",
+            "=foo",
+            "foo=",
+            "foo",
+            "foo=val",
+            "foo==val",
+            "toggle=:",
+            "string=:",
+            "toggle=1 : foo",
+            "toggle=100",
+            "toggle==1",
+            "flags=+mu-lame : num=42: toggle=0",
+            "num=42 : string=blahblah",
+            "rational=0 : rational=1/2 : rational=1/-1",
+            "rational=-1/0",
+        };
+
+        test_ctx.class = &test_class;
+        av_opt_set_defaults2(&test_ctx, 0, 0);
+        test_ctx.string = av_strdup("default");
+
+        av_log_set_level(AV_LOG_DEBUG);
+
+        for (i=0; i < FF_ARRAY_ELEMS(options); i++) {
+            av_log(&test_ctx, AV_LOG_DEBUG, "Setting options string '%s'\n", options[i]);
+            if (av_set_options_string(&test_ctx, options[i], "=", ":") < 0)
+                av_log(&test_ctx, AV_LOG_ERROR, "Error setting options string: '%s'\n", options[i]);
+            printf("\n");
+        }
+    }
+
+    return 0;
+}
+
+#endif
diff --git a/libavutil/opt.h b/libavutil/opt.h
new file mode 100644
index 0000000..3e61737
--- /dev/null
+++ b/libavutil/opt.h
@@ -0,0 +1,226 @@
+/*
+ * AVOptions
+ * copyright (c) 2005 Michael Niedermayer <michaelni at gmx.at>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_OPT_H
+#define AVUTIL_OPT_H
+
+/**
+ * @file
+ * AVOptions
+ */
+
+#include "rational.h"
+#include "avutil.h"
+
+enum AVOptionType{
+    FF_OPT_TYPE_FLAGS,
+    FF_OPT_TYPE_INT,
+    FF_OPT_TYPE_INT64,
+    FF_OPT_TYPE_DOUBLE,
+    FF_OPT_TYPE_FLOAT,
+    FF_OPT_TYPE_STRING,
+    FF_OPT_TYPE_RATIONAL,
+    FF_OPT_TYPE_BINARY,  ///< offset must point to a pointer immediately followed by an int for the length
+    FF_OPT_TYPE_CONST=128,
+};
+
+/**
+ * AVOption
+ */
+typedef struct AVOption {
+    const char *name;
+
+    /**
+     * short English help text
+     * @todo What about other languages?
+     */
+    const char *help;
+
+    /**
+     * The offset relative to the context structure where the option
+     * value is stored. It should be 0 for named constants.
+     */
+    int offset;
+    enum AVOptionType type;
+
+    /**
+     * the default value for scalar options
+     */
+    double default_val;
+    double min;                 ///< minimum valid value for the option
+    double max;                 ///< maximum valid value for the option
+
+    int flags;
+#define AV_OPT_FLAG_ENCODING_PARAM  1   ///< a generic parameter which can be set by the user for muxing or encoding
+#define AV_OPT_FLAG_DECODING_PARAM  2   ///< a generic parameter which can be set by the user for demuxing or decoding
+#define AV_OPT_FLAG_METADATA        4   ///< some data extracted or inserted into the file like title, comment, ...
+#define AV_OPT_FLAG_AUDIO_PARAM     8
+#define AV_OPT_FLAG_VIDEO_PARAM     16
+#define AV_OPT_FLAG_SUBTITLE_PARAM  32
+//FIXME think about enc-audio, ... style flags
+
+    /**
+     * The logical unit to which the option belongs. Non-constant
+     * options and corresponding named constants share the same
+     * unit. May be NULL.
+     */
+    const char *unit;
+} AVOption;
+
+/**
+ * AVOption2.
+ * THIS IS NOT PART OF THE API/ABI YET!
+ * This is identical to AVOption except that default_val was replaced by
+ * an union, it should be compatible with AVOption on normal platforms.
+ */
+typedef struct AVOption2 {
+    const char *name;
+
+    /**
+     * short English help text
+     * @todo What about other languages?
+     */
+    const char *help;
+
+    /**
+     * The offset relative to the context structure where the option
+     * value is stored. It should be 0 for named constants.
+     */
+    int offset;
+    enum AVOptionType type;
+
+    /**
+     * the default value for scalar options
+     */
+    union {
+        double dbl;
+        const char *str;
+    } default_val;
+
+    double min;                 ///< minimum valid value for the option
+    double max;                 ///< maximum valid value for the option
+
+    int flags;
+/*
+#define AV_OPT_FLAG_ENCODING_PARAM  1   ///< a generic parameter which can be set by the user for muxing or encoding
+#define AV_OPT_FLAG_DECODING_PARAM  2   ///< a generic parameter which can be set by the user for demuxing or decoding
+#define AV_OPT_FLAG_METADATA        4   ///< some data extracted or inserted into the file like title, comment, ...
+#define AV_OPT_FLAG_AUDIO_PARAM     8
+#define AV_OPT_FLAG_VIDEO_PARAM     16
+#define AV_OPT_FLAG_SUBTITLE_PARAM  32
+*/
+//FIXME think about enc-audio, ... style flags
+
+    /**
+     * The logical unit to which the option belongs. Non-constant
+     * options and corresponding named constants share the same
+     * unit. May be NULL.
+     */
+    const char *unit;
+} AVOption2;
+
+
+/**
+ * Look for an option in obj. Look only for the options which
+ * have the flags set as specified in mask and flags (that is,
+ * for which it is the case that opt->flags & mask == flags).
+ *
+ * @param[in] obj a pointer to a struct whose first element is a
+ * pointer to an AVClass
+ * @param[in] name the name of the option to look for
+ * @param[in] unit the unit of the option to look for, or any if NULL
+ * @return a pointer to the option found, or NULL if no option
+ * has been found
+ */
+const AVOption *av_find_opt(void *obj, const char *name, const char *unit, int mask, int flags);
+
+/**
+ * Set the field of obj with the given name to value.
+ *
+ * @param[in] obj A struct whose first element is a pointer to an
+ * AVClass.
+ * @param[in] name the name of the field to set
+ * @param[in] val The value to set. If the field is not of a string
+ * type, then the given string is parsed.
+ * SI postfixes and some named scalars are supported.
+ * If the field is of a numeric type, it has to be a numeric or named
+ * scalar. Behavior with more than one scalar and +- infix operators
+ * is undefined.
+ * If the field is of a flags type, it has to be a sequence of numeric
+ * scalars or named flags separated by '+' or '-'. Prefixing a flag
+ * with '+' causes it to be set without affecting the other flags;
+ * similarly, '-' unsets a flag.
+ * @param[out] o_out if non-NULL put here a pointer to the AVOption
+ * found
+ * @param alloc when 1 then the old value will be av_freed() and the
+ *                     new av_strduped()
+ *              when 0 then no av_free() nor av_strdup() will be used
+ * @return 0 if the value has been set, or an AVERROR code in case of
+ * error:
+ * AVERROR(ENOENT) if no matching option exists
+ * AVERROR(ERANGE) if the value is out of range
+ * AVERROR(EINVAL) if the value is not valid
+ */
+int av_set_string3(void *obj, const char *name, const char *val, int alloc, const AVOption **o_out);
+
+const AVOption *av_set_double(void *obj, const char *name, double n);
+const AVOption *av_set_q(void *obj, const char *name, AVRational n);
+const AVOption *av_set_int(void *obj, const char *name, int64_t n);
+double av_get_double(void *obj, const char *name, const AVOption **o_out);
+AVRational av_get_q(void *obj, const char *name, const AVOption **o_out);
+int64_t av_get_int(void *obj, const char *name, const AVOption **o_out);
+const char *av_get_string(void *obj, const char *name, const AVOption **o_out, char *buf, int buf_len);
+const AVOption *av_next_option(void *obj, const AVOption *last);
+
+/**
+ * Show the obj options.
+ *
+ * @param req_flags requested flags for the options to show. Show only the
+ * options for which it is opt->flags & req_flags.
+ * @param rej_flags rejected flags for the options to show. Show only the
+ * options for which it is !(opt->flags & req_flags).
+ * @param av_log_obj log context to use for showing the options
+ */
+int av_opt_show2(void *obj, void *av_log_obj, int req_flags, int rej_flags);
+
+void av_opt_set_defaults(void *s);
+void av_opt_set_defaults2(void *s, int mask, int flags);
+
+/**
+ * Parse the key/value pairs list in opts. For each key/value pair
+ * found, stores the value in the field in ctx that is named like the
+ * key. ctx must be an AVClass context, storing is done using
+ * AVOptions.
+ *
+ * @param key_val_sep a 0-terminated list of characters used to
+ * separate key from value
+ * @param pairs_sep a 0-terminated list of characters used to separate
+ * two pairs from each other
+ * @return the number of successfully set key/value pairs, or a negative
+ * value corresponding to an AVERROR code in case of error:
+ * AVERROR(EINVAL) if opts cannot be parsed,
+ * the error code issued by av_set_string3() if a key/value pair
+ * cannot be set
+ */
+int av_set_options_string(void *ctx, const char *opts,
+                          const char *key_val_sep, const char *pairs_sep);
+
+#endif /* AVUTIL_OPT_H */
diff --git a/libavutil/parseutils.c b/libavutil/parseutils.c
new file mode 100644
index 0000000..cc90131
--- /dev/null
+++ b/libavutil/parseutils.c
@@ -0,0 +1,750 @@
+/*
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * misc parsing utilities
+ */
+
+#include <strings.h>
+#include <sys/time.h>
+#include <time.h>
+#include "parseutils.h"
+#include "libavutil/avutil.h"
+#include "libavutil/eval.h"
+#include "libavutil/avstring.h"
+#include "libavutil/random_seed.h"
+
+typedef struct {
+    const char *abbr;
+    int width, height;
+} VideoSizeAbbr;
+
+typedef struct {
+    const char *abbr;
+    AVRational rate;
+} VideoRateAbbr;
+
+static const VideoSizeAbbr video_size_abbrs[] = {
+    { "ntsc",      720, 480 },
+    { "pal",       720, 576 },
+    { "qntsc",     352, 240 }, /* VCD compliant NTSC */
+    { "qpal",      352, 288 }, /* VCD compliant PAL */
+    { "sntsc",     640, 480 }, /* square pixel NTSC */
+    { "spal",      768, 576 }, /* square pixel PAL */
+    { "film",      352, 240 },
+    { "ntsc-film", 352, 240 },
+    { "sqcif",     128,  96 },
+    { "qcif",      176, 144 },
+    { "cif",       352, 288 },
+    { "4cif",      704, 576 },
+    { "16cif",    1408,1152 },
+    { "qqvga",     160, 120 },
+    { "qvga",      320, 240 },
+    { "vga",       640, 480 },
+    { "svga",      800, 600 },
+    { "xga",      1024, 768 },
+    { "uxga",     1600,1200 },
+    { "qxga",     2048,1536 },
+    { "sxga",     1280,1024 },
+    { "qsxga",    2560,2048 },
+    { "hsxga",    5120,4096 },
+    { "wvga",      852, 480 },
+    { "wxga",     1366, 768 },
+    { "wsxga",    1600,1024 },
+    { "wuxga",    1920,1200 },
+    { "woxga",    2560,1600 },
+    { "wqsxga",   3200,2048 },
+    { "wquxga",   3840,2400 },
+    { "whsxga",   6400,4096 },
+    { "whuxga",   7680,4800 },
+    { "cga",       320, 200 },
+    { "ega",       640, 350 },
+    { "hd480",     852, 480 },
+    { "hd720",    1280, 720 },
+    { "hd1080",   1920,1080 },
+};
+
+static const VideoRateAbbr video_rate_abbrs[]= {
+    { "ntsc",      { 30000, 1001 } },
+    { "pal",       {    25,    1 } },
+    { "qntsc",     { 30000, 1001 } }, /* VCD compliant NTSC */
+    { "qpal",      {    25,    1 } }, /* VCD compliant PAL */
+    { "sntsc",     { 30000, 1001 } }, /* square pixel NTSC */
+    { "spal",      {    25,    1 } }, /* square pixel PAL */
+    { "film",      {    24,    1 } },
+    { "ntsc-film", { 24000, 1001 } },
+};
+
+int av_parse_video_size(int *width_ptr, int *height_ptr, const char *str)
+{
+    int i;
+    int n = FF_ARRAY_ELEMS(video_size_abbrs);
+    char *p;
+    int width = 0, height = 0;
+
+    for (i = 0; i < n; i++) {
+        if (!strcmp(video_size_abbrs[i].abbr, str)) {
+            width  = video_size_abbrs[i].width;
+            height = video_size_abbrs[i].height;
+            break;
+        }
+    }
+    if (i == n) {
+        p = str;
+        width = strtol(p, &p, 10);
+        if (*p)
+            p++;
+        height = strtol(p, &p, 10);
+    }
+    if (width <= 0 || height <= 0)
+        return AVERROR(EINVAL);
+    *width_ptr  = width;
+    *height_ptr = height;
+    return 0;
+}
+
+int av_parse_video_rate(AVRational *rate, const char *arg)
+{
+    int i, ret;
+    int n = FF_ARRAY_ELEMS(video_rate_abbrs);
+    double res;
+
+    /* First, we check our abbreviation table */
+    for (i = 0; i < n; ++i)
+        if (!strcmp(video_rate_abbrs[i].abbr, arg)) {
+            *rate = video_rate_abbrs[i].rate;
+            return 0;
+        }
+
+    /* Then, we try to parse it as fraction */
+    if ((ret = av_expr_parse_and_eval(&res, arg, NULL, NULL, NULL, NULL, NULL, NULL,
+                                      NULL, 0, NULL)) < 0)
+        return ret;
+    *rate = av_d2q(res, 1001000);
+    if (rate->num <= 0 || rate->den <= 0)
+        return AVERROR(EINVAL);
+    return 0;
+}
+
+typedef struct {
+    const char *name;            ///< a string representing the name of the color
+    uint8_t     rgb_color[3];    ///< RGB values for the color
+} ColorEntry;
+
+static ColorEntry color_table[] = {
+    { "AliceBlue",            { 0xF0, 0xF8, 0xFF } },
+    { "AntiqueWhite",         { 0xFA, 0xEB, 0xD7 } },
+    { "Aqua",                 { 0x00, 0xFF, 0xFF } },
+    { "Aquamarine",           { 0x7F, 0xFF, 0xD4 } },
+    { "Azure",                { 0xF0, 0xFF, 0xFF } },
+    { "Beige",                { 0xF5, 0xF5, 0xDC } },
+    { "Bisque",               { 0xFF, 0xE4, 0xC4 } },
+    { "Black",                { 0x00, 0x00, 0x00 } },
+    { "BlanchedAlmond",       { 0xFF, 0xEB, 0xCD } },
+    { "Blue",                 { 0x00, 0x00, 0xFF } },
+    { "BlueViolet",           { 0x8A, 0x2B, 0xE2 } },
+    { "Brown",                { 0xA5, 0x2A, 0x2A } },
+    { "BurlyWood",            { 0xDE, 0xB8, 0x87 } },
+    { "CadetBlue",            { 0x5F, 0x9E, 0xA0 } },
+    { "Chartreuse",           { 0x7F, 0xFF, 0x00 } },
+    { "Chocolate",            { 0xD2, 0x69, 0x1E } },
+    { "Coral",                { 0xFF, 0x7F, 0x50 } },
+    { "CornflowerBlue",       { 0x64, 0x95, 0xED } },
+    { "Cornsilk",             { 0xFF, 0xF8, 0xDC } },
+    { "Crimson",              { 0xDC, 0x14, 0x3C } },
+    { "Cyan",                 { 0x00, 0xFF, 0xFF } },
+    { "DarkBlue",             { 0x00, 0x00, 0x8B } },
+    { "DarkCyan",             { 0x00, 0x8B, 0x8B } },
+    { "DarkGoldenRod",        { 0xB8, 0x86, 0x0B } },
+    { "DarkGray",             { 0xA9, 0xA9, 0xA9 } },
+    { "DarkGreen",            { 0x00, 0x64, 0x00 } },
+    { "DarkKhaki",            { 0xBD, 0xB7, 0x6B } },
+    { "DarkMagenta",          { 0x8B, 0x00, 0x8B } },
+    { "DarkOliveGreen",       { 0x55, 0x6B, 0x2F } },
+    { "Darkorange",           { 0xFF, 0x8C, 0x00 } },
+    { "DarkOrchid",           { 0x99, 0x32, 0xCC } },
+    { "DarkRed",              { 0x8B, 0x00, 0x00 } },
+    { "DarkSalmon",           { 0xE9, 0x96, 0x7A } },
+    { "DarkSeaGreen",         { 0x8F, 0xBC, 0x8F } },
+    { "DarkSlateBlue",        { 0x48, 0x3D, 0x8B } },
+    { "DarkSlateGray",        { 0x2F, 0x4F, 0x4F } },
+    { "DarkTurquoise",        { 0x00, 0xCE, 0xD1 } },
+    { "DarkViolet",           { 0x94, 0x00, 0xD3 } },
+    { "DeepPink",             { 0xFF, 0x14, 0x93 } },
+    { "DeepSkyBlue",          { 0x00, 0xBF, 0xFF } },
+    { "DimGray",              { 0x69, 0x69, 0x69 } },
+    { "DodgerBlue",           { 0x1E, 0x90, 0xFF } },
+    { "FireBrick",            { 0xB2, 0x22, 0x22 } },
+    { "FloralWhite",          { 0xFF, 0xFA, 0xF0 } },
+    { "ForestGreen",          { 0x22, 0x8B, 0x22 } },
+    { "Fuchsia",              { 0xFF, 0x00, 0xFF } },
+    { "Gainsboro",            { 0xDC, 0xDC, 0xDC } },
+    { "GhostWhite",           { 0xF8, 0xF8, 0xFF } },
+    { "Gold",                 { 0xFF, 0xD7, 0x00 } },
+    { "GoldenRod",            { 0xDA, 0xA5, 0x20 } },
+    { "Gray",                 { 0x80, 0x80, 0x80 } },
+    { "Green",                { 0x00, 0x80, 0x00 } },
+    { "GreenYellow",          { 0xAD, 0xFF, 0x2F } },
+    { "HoneyDew",             { 0xF0, 0xFF, 0xF0 } },
+    { "HotPink",              { 0xFF, 0x69, 0xB4 } },
+    { "IndianRed",            { 0xCD, 0x5C, 0x5C } },
+    { "Indigo",               { 0x4B, 0x00, 0x82 } },
+    { "Ivory",                { 0xFF, 0xFF, 0xF0 } },
+    { "Khaki",                { 0xF0, 0xE6, 0x8C } },
+    { "Lavender",             { 0xE6, 0xE6, 0xFA } },
+    { "LavenderBlush",        { 0xFF, 0xF0, 0xF5 } },
+    { "LawnGreen",            { 0x7C, 0xFC, 0x00 } },
+    { "LemonChiffon",         { 0xFF, 0xFA, 0xCD } },
+    { "LightBlue",            { 0xAD, 0xD8, 0xE6 } },
+    { "LightCoral",           { 0xF0, 0x80, 0x80 } },
+    { "LightCyan",            { 0xE0, 0xFF, 0xFF } },
+    { "LightGoldenRodYellow", { 0xFA, 0xFA, 0xD2 } },
+    { "LightGrey",            { 0xD3, 0xD3, 0xD3 } },
+    { "LightGreen",           { 0x90, 0xEE, 0x90 } },
+    { "LightPink",            { 0xFF, 0xB6, 0xC1 } },
+    { "LightSalmon",          { 0xFF, 0xA0, 0x7A } },
+    { "LightSeaGreen",        { 0x20, 0xB2, 0xAA } },
+    { "LightSkyBlue",         { 0x87, 0xCE, 0xFA } },
+    { "LightSlateGray",       { 0x77, 0x88, 0x99 } },
+    { "LightSteelBlue",       { 0xB0, 0xC4, 0xDE } },
+    { "LightYellow",          { 0xFF, 0xFF, 0xE0 } },
+    { "Lime",                 { 0x00, 0xFF, 0x00 } },
+    { "LimeGreen",            { 0x32, 0xCD, 0x32 } },
+    { "Linen",                { 0xFA, 0xF0, 0xE6 } },
+    { "Magenta",              { 0xFF, 0x00, 0xFF } },
+    { "Maroon",               { 0x80, 0x00, 0x00 } },
+    { "MediumAquaMarine",     { 0x66, 0xCD, 0xAA } },
+    { "MediumBlue",           { 0x00, 0x00, 0xCD } },
+    { "MediumOrchid",         { 0xBA, 0x55, 0xD3 } },
+    { "MediumPurple",         { 0x93, 0x70, 0xD8 } },
+    { "MediumSeaGreen",       { 0x3C, 0xB3, 0x71 } },
+    { "MediumSlateBlue",      { 0x7B, 0x68, 0xEE } },
+    { "MediumSpringGreen",    { 0x00, 0xFA, 0x9A } },
+    { "MediumTurquoise",      { 0x48, 0xD1, 0xCC } },
+    { "MediumVioletRed",      { 0xC7, 0x15, 0x85 } },
+    { "MidnightBlue",         { 0x19, 0x19, 0x70 } },
+    { "MintCream",            { 0xF5, 0xFF, 0xFA } },
+    { "MistyRose",            { 0xFF, 0xE4, 0xE1 } },
+    { "Moccasin",             { 0xFF, 0xE4, 0xB5 } },
+    { "NavajoWhite",          { 0xFF, 0xDE, 0xAD } },
+    { "Navy",                 { 0x00, 0x00, 0x80 } },
+    { "OldLace",              { 0xFD, 0xF5, 0xE6 } },
+    { "Olive",                { 0x80, 0x80, 0x00 } },
+    { "OliveDrab",            { 0x6B, 0x8E, 0x23 } },
+    { "Orange",               { 0xFF, 0xA5, 0x00 } },
+    { "OrangeRed",            { 0xFF, 0x45, 0x00 } },
+    { "Orchid",               { 0xDA, 0x70, 0xD6 } },
+    { "PaleGoldenRod",        { 0xEE, 0xE8, 0xAA } },
+    { "PaleGreen",            { 0x98, 0xFB, 0x98 } },
+    { "PaleTurquoise",        { 0xAF, 0xEE, 0xEE } },
+    { "PaleVioletRed",        { 0xD8, 0x70, 0x93 } },
+    { "PapayaWhip",           { 0xFF, 0xEF, 0xD5 } },
+    { "PeachPuff",            { 0xFF, 0xDA, 0xB9 } },
+    { "Peru",                 { 0xCD, 0x85, 0x3F } },
+    { "Pink",                 { 0xFF, 0xC0, 0xCB } },
+    { "Plum",                 { 0xDD, 0xA0, 0xDD } },
+    { "PowderBlue",           { 0xB0, 0xE0, 0xE6 } },
+    { "Purple",               { 0x80, 0x00, 0x80 } },
+    { "Red",                  { 0xFF, 0x00, 0x00 } },
+    { "RosyBrown",            { 0xBC, 0x8F, 0x8F } },
+    { "RoyalBlue",            { 0x41, 0x69, 0xE1 } },
+    { "SaddleBrown",          { 0x8B, 0x45, 0x13 } },
+    { "Salmon",               { 0xFA, 0x80, 0x72 } },
+    { "SandyBrown",           { 0xF4, 0xA4, 0x60 } },
+    { "SeaGreen",             { 0x2E, 0x8B, 0x57 } },
+    { "SeaShell",             { 0xFF, 0xF5, 0xEE } },
+    { "Sienna",               { 0xA0, 0x52, 0x2D } },
+    { "Silver",               { 0xC0, 0xC0, 0xC0 } },
+    { "SkyBlue",              { 0x87, 0xCE, 0xEB } },
+    { "SlateBlue",            { 0x6A, 0x5A, 0xCD } },
+    { "SlateGray",            { 0x70, 0x80, 0x90 } },
+    { "Snow",                 { 0xFF, 0xFA, 0xFA } },
+    { "SpringGreen",          { 0x00, 0xFF, 0x7F } },
+    { "SteelBlue",            { 0x46, 0x82, 0xB4 } },
+    { "Tan",                  { 0xD2, 0xB4, 0x8C } },
+    { "Teal",                 { 0x00, 0x80, 0x80 } },
+    { "Thistle",              { 0xD8, 0xBF, 0xD8 } },
+    { "Tomato",               { 0xFF, 0x63, 0x47 } },
+    { "Turquoise",            { 0x40, 0xE0, 0xD0 } },
+    { "Violet",               { 0xEE, 0x82, 0xEE } },
+    { "Wheat",                { 0xF5, 0xDE, 0xB3 } },
+    { "White",                { 0xFF, 0xFF, 0xFF } },
+    { "WhiteSmoke",           { 0xF5, 0xF5, 0xF5 } },
+    { "Yellow",               { 0xFF, 0xFF, 0x00 } },
+    { "YellowGreen",          { 0x9A, 0xCD, 0x32 } },
+};
+
+static int color_table_compare(const void *lhs, const void *rhs)
+{
+    return strcasecmp(lhs, ((const ColorEntry *)rhs)->name);
+}
+
+#define ALPHA_SEP '@'
+
+int av_parse_color(uint8_t *rgba_color, const char *color_string, int slen,
+                   void *log_ctx)
+{
+    char *tail, color_string2[128];
+    const ColorEntry *entry;
+    int len, hex_offset = 0;
+
+    if (color_string[0] == '#') {
+        hex_offset = 1;
+    } else if (!strncmp(color_string, "0x", 2))
+        hex_offset = 2;
+
+    if (slen < 0)
+        slen = strlen(color_string);
+    av_strlcpy(color_string2, color_string + hex_offset,
+               FFMIN(slen-hex_offset+1, sizeof(color_string2)));
+    if ((tail = strchr(color_string2, ALPHA_SEP)))
+        *tail++ = 0;
+    len = strlen(color_string2);
+    rgba_color[3] = 255;
+
+    if (!strcasecmp(color_string2, "random") || !strcasecmp(color_string2, "bikeshed")) {
+        int rgba = av_get_random_seed();
+        rgba_color[0] = rgba >> 24;
+        rgba_color[1] = rgba >> 16;
+        rgba_color[2] = rgba >> 8;
+        rgba_color[3] = rgba;
+    } else if (hex_offset ||
+               strspn(color_string2, "0123456789ABCDEFabcdef") == len) {
+        char *tail;
+        unsigned int rgba = strtoul(color_string2, &tail, 16);
+
+        if (*tail || (len != 6 && len != 8)) {
+            av_log(log_ctx, AV_LOG_ERROR, "Invalid 0xRRGGBB[AA] color string: '%s'\n", color_string2);
+            return AVERROR(EINVAL);
+        }
+        if (len == 8) {
+            rgba_color[3] = rgba;
+            rgba >>= 8;
+        }
+        rgba_color[0] = rgba >> 16;
+        rgba_color[1] = rgba >> 8;
+        rgba_color[2] = rgba;
+    } else {
+        entry = bsearch(color_string2,
+                        color_table,
+                        FF_ARRAY_ELEMS(color_table),
+                        sizeof(ColorEntry),
+                        color_table_compare);
+        if (!entry) {
+            av_log(log_ctx, AV_LOG_ERROR, "Cannot find color '%s'\n", color_string2);
+            return AVERROR(EINVAL);
+        }
+        memcpy(rgba_color, entry->rgb_color, 3);
+    }
+
+    if (tail) {
+        unsigned long int alpha;
+        const char *alpha_string = tail;
+        if (!strncmp(alpha_string, "0x", 2)) {
+            alpha = strtoul(alpha_string, &tail, 16);
+        } else {
+            alpha = 255 * strtod(alpha_string, &tail);
+        }
+
+        if (tail == alpha_string || *tail || alpha > 255) {
+            av_log(log_ctx, AV_LOG_ERROR, "Invalid alpha value specifier '%s' in '%s'\n",
+                   alpha_string, color_string);
+            return AVERROR(EINVAL);
+        }
+        rgba_color[3] = alpha;
+    }
+
+    return 0;
+}
+
+/* get a positive number between n_min and n_max, for a maximum length
+   of len_max. Return -1 if error. */
+static int date_get_num(const char **pp,
+                        int n_min, int n_max, int len_max)
+{
+    int i, val, c;
+    const char *p;
+
+    p = *pp;
+    val = 0;
+    for(i = 0; i < len_max; i++) {
+        c = *p;
+        if (!isdigit(c))
+            break;
+        val = (val * 10) + c - '0';
+        p++;
+    }
+    /* no number read ? */
+    if (p == *pp)
+        return -1;
+    if (val < n_min || val > n_max)
+        return -1;
+    *pp = p;
+    return val;
+}
+
+/* small strptime for ffmpeg */
+static
+const char *small_strptime(const char *p, const char *fmt,
+                           struct tm *dt)
+{
+    int c, val;
+
+    for(;;) {
+        c = *fmt++;
+        if (c == '\0') {
+            return p;
+        } else if (c == '%') {
+            c = *fmt++;
+            switch(c) {
+            case 'H':
+                val = date_get_num(&p, 0, 23, 2);
+                if (val == -1)
+                    return NULL;
+                dt->tm_hour = val;
+                break;
+            case 'M':
+                val = date_get_num(&p, 0, 59, 2);
+                if (val == -1)
+                    return NULL;
+                dt->tm_min = val;
+                break;
+            case 'S':
+                val = date_get_num(&p, 0, 59, 2);
+                if (val == -1)
+                    return NULL;
+                dt->tm_sec = val;
+                break;
+            case 'Y':
+                val = date_get_num(&p, 0, 9999, 4);
+                if (val == -1)
+                    return NULL;
+                dt->tm_year = val - 1900;
+                break;
+            case 'm':
+                val = date_get_num(&p, 1, 12, 2);
+                if (val == -1)
+                    return NULL;
+                dt->tm_mon = val - 1;
+                break;
+            case 'd':
+                val = date_get_num(&p, 1, 31, 2);
+                if (val == -1)
+                    return NULL;
+                dt->tm_mday = val;
+                break;
+            case '%':
+                goto match;
+            default:
+                return NULL;
+            }
+        } else {
+        match:
+            if (c != *p)
+                return NULL;
+            p++;
+        }
+    }
+    return p;
+}
+
+static time_t mktimegm(struct tm *tm)
+{
+    time_t t;
+
+    int y = tm->tm_year + 1900, m = tm->tm_mon + 1, d = tm->tm_mday;
+
+    if (m < 3) {
+        m += 12;
+        y--;
+    }
+
+    t = 86400 *
+        (d + (153 * m - 457) / 5 + 365 * y + y / 4 - y / 100 + y / 400 - 719469);
+
+    t += 3600 * tm->tm_hour + 60 * tm->tm_min + tm->tm_sec;
+
+    return t;
+}
+
+int av_parse_time(int64_t *timeval, const char *datestr, int duration)
+{
+    const char *p;
+    int64_t t;
+    struct tm dt;
+    int i;
+    static const char * const date_fmt[] = {
+        "%Y-%m-%d",
+        "%Y%m%d",
+    };
+    static const char * const time_fmt[] = {
+        "%H:%M:%S",
+        "%H%M%S",
+    };
+    const char *q;
+    int is_utc, len;
+    char lastch;
+    int negative = 0;
+
+#undef time
+    time_t now = time(0);
+
+    len = strlen(datestr);
+    if (len > 0)
+        lastch = datestr[len - 1];
+    else
+        lastch = '\0';
+    is_utc = (lastch == 'z' || lastch == 'Z');
+
+    memset(&dt, 0, sizeof(dt));
+
+    p = datestr;
+    q = NULL;
+    if (!duration) {
+        if (!strncasecmp(datestr, "now", len)) {
+            *timeval = (int64_t) now * 1000000;
+            return 0;
+        }
+
+        /* parse the year-month-day part */
+        for (i = 0; i < FF_ARRAY_ELEMS(date_fmt); i++) {
+            q = small_strptime(p, date_fmt[i], &dt);
+            if (q) {
+                break;
+            }
+        }
+
+        /* if the year-month-day part is missing, then take the
+         * current year-month-day time */
+        if (!q) {
+            if (is_utc) {
+                dt = *gmtime(&now);
+            } else {
+                dt = *localtime(&now);
+            }
+            dt.tm_hour = dt.tm_min = dt.tm_sec = 0;
+        } else {
+            p = q;
+        }
+
+        if (*p == 'T' || *p == 't' || *p == ' ')
+            p++;
+
+        /* parse the hour-minute-second part */
+        for (i = 0; i < FF_ARRAY_ELEMS(time_fmt); i++) {
+            q = small_strptime(p, time_fmt[i], &dt);
+            if (q) {
+                break;
+            }
+        }
+    } else {
+        /* parse datestr as a duration */
+        if (p[0] == '-') {
+            negative = 1;
+            ++p;
+        }
+        /* parse datestr as HH:MM:SS */
+        q = small_strptime(p, time_fmt[0], &dt);
+        if (!q) {
+            /* parse datestr as S+ */
+            dt.tm_sec = strtol(p, (char **)&q, 10);
+            if (q == p) {
+                /* the parsing didn't succeed */
+                *timeval = INT64_MIN;
+                return AVERROR(EINVAL);
+            }
+            dt.tm_min = 0;
+            dt.tm_hour = 0;
+        }
+    }
+
+    /* Now we have all the fields that we can get */
+    if (!q) {
+        *timeval = INT64_MIN;
+        return AVERROR(EINVAL);
+    }
+
+    if (duration) {
+        t = dt.tm_hour * 3600 + dt.tm_min * 60 + dt.tm_sec;
+    } else {
+        dt.tm_isdst = -1;       /* unknown */
+        if (is_utc) {
+            t = mktimegm(&dt);
+        } else {
+            t = mktime(&dt);
+        }
+    }
+
+    t *= 1000000;
+
+    /* parse the .m... part */
+    if (*q == '.') {
+        int val, n;
+        q++;
+        for (val = 0, n = 100000; n >= 1; n /= 10, q++) {
+            if (!isdigit(*q))
+                break;
+            val += n * (*q - '0');
+        }
+        t += val;
+    }
+    *timeval = negative ? -t : t;
+    return 0;
+}
+
+int av_find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
+{
+    const char *p;
+    char tag[128], *q;
+
+    p = info;
+    if (*p == '?')
+        p++;
+    for(;;) {
+        q = tag;
+        while (*p != '\0' && *p != '=' && *p != '&') {
+            if ((q - tag) < sizeof(tag) - 1)
+                *q++ = *p;
+            p++;
+        }
+        *q = '\0';
+        q = arg;
+        if (*p == '=') {
+            p++;
+            while (*p != '&' && *p != '\0') {
+                if ((q - arg) < arg_size - 1) {
+                    if (*p == '+')
+                        *q++ = ' ';
+                    else
+                        *q++ = *p;
+                }
+                p++;
+            }
+        }
+        *q = '\0';
+        if (!strcmp(tag, tag1))
+            return 1;
+        if (*p != '&')
+            break;
+        p++;
+    }
+    return 0;
+}
+
+#ifdef TEST
+
+#undef printf
+
+int main(void)
+{
+    printf("Testing av_parse_video_rate()\n");
+    {
+        int i;
+        const char *rates[] = {
+            "-inf",
+            "inf",
+            "nan",
+            "123/0",
+            "-123 / 0",
+            "",
+            "/",
+            " 123  /  321",
+            "foo/foo",
+            "foo/1",
+            "1/foo",
+            "0/0",
+            "/0",
+            "1/",
+            "1",
+            "0",
+            "-123/123",
+            "-foo",
+            "123.23",
+            ".23",
+            "-.23",
+            "-0.234",
+            "-0.0000001",
+            "  21332.2324   ",
+            " -21332.2324   ",
+        };
+
+        for (i = 0; i < FF_ARRAY_ELEMS(rates); i++) {
+            int ret;
+            AVRational q = (AVRational){0, 0};
+            ret = av_parse_video_rate(&q, rates[i]),
+            printf("'%s' -> %d/%d ret:%d\n",
+                   rates[i], q.num, q.den, ret);
+        }
+    }
+
+    printf("\nTesting av_parse_color()\n");
+    {
+        int i;
+        uint8_t rgba[4];
+        const char *color_names[] = {
+            "bikeshed",
+            "RaNdOm",
+            "foo",
+            "red",
+            "Red ",
+            "RED",
+            "Violet",
+            "Yellow",
+            "Red",
+            "0x000000",
+            "0x0000000",
+            "0xff000000",
+            "0x3e34ff",
+            "0x3e34ffaa",
+            "0xffXXee",
+            "0xfoobar",
+            "0xffffeeeeeeee",
+            "#ff0000",
+            "#ffXX00",
+            "ff0000",
+            "ffXX00",
+            "red at foo",
+            "random at 10",
+            "0xff0000 at 1.0",
+            "red@",
+            "red at 0xfff",
+            "red at 0xf",
+            "red at 2",
+            "red at 0.1",
+            "red at -1",
+            "red at 0.5",
+            "red at 1.0",
+            "red at 256",
+            "red at 10foo",
+            "red at -1.0",
+            "red at -0.0",
+        };
+
+        av_log_set_level(AV_LOG_DEBUG);
+
+        for (i = 0;  i < FF_ARRAY_ELEMS(color_names); i++) {
+            if (av_parse_color(rgba, color_names[i], -1, NULL) >= 0)
+                printf("%s -> R(%d) G(%d) B(%d) A(%d)\n", color_names[i], rgba[0], rgba[1], rgba[2], rgba[3]);
+        }
+    }
+
+    return 0;
+}
+
+#endif /* TEST */
diff --git a/libavutil/parseutils.h b/libavutil/parseutils.h
new file mode 100644
index 0000000..c0f9aec
--- /dev/null
+++ b/libavutil/parseutils.h
@@ -0,0 +1,117 @@
+/*
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_PARSEUTILS_H
+#define AVUTIL_PARSEUTILS_H
+
+#include "libavutil/rational.h"
+
+/**
+ * @file
+ * misc parsing utilities
+ */
+
+/**
+ * Parse str and put in width_ptr and height_ptr the detected values.
+ *
+ * @param[in,out] width_ptr pointer to the variable which will contain the detected
+ * width value
+ * @param[in,out] height_ptr pointer to the variable which will contain the detected
+ * height value
+ * @param[in] str the string to parse: it has to be a string in the format
+ * width x height or a valid video size abbreviation.
+ * @return >= 0 on success, a negative error code otherwise
+ */
+int av_parse_video_size(int *width_ptr, int *height_ptr, const char *str);
+
+/**
+ * Parse str and store the detected values in *rate.
+ *
+ * @param[in,out] rate pointer to the AVRational which will contain the detected
+ * frame rate
+ * @param[in] str the string to parse: it has to be a string in the format
+ * rate_num / rate_den, a float number or a valid video rate abbreviation
+ * @return >= 0 on success, a negative error code otherwise
+ */
+int av_parse_video_rate(AVRational *rate, const char *str);
+
+/**
+ * Put the RGBA values that correspond to color_string in rgba_color.
+ *
+ * @param color_string a string specifying a color. It can be the name of
+ * a color (case insensitive match) or a [0x|#]RRGGBB[AA] sequence,
+ * possibly followed by "@" and a string representing the alpha
+ * component.
+ * The alpha component may be a string composed by "0x" followed by an
+ * hexadecimal number or a decimal number between 0.0 and 1.0, which
+ * represents the opacity value (0x00/0.0 means completely transparent,
+ * 0xff/1.0 completely opaque).
+ * If the alpha component is not specified then 0xff is assumed.
+ * The string "random" will result in a random color.
+ * @param slen length of the initial part of color_string containing the
+ * color. It can be set to -1 if color_string is a null terminated string
+ * containing nothing else than the color.
+ * @return >= 0 in case of success, a negative value in case of
+ * failure (for example if color_string cannot be parsed).
+ */
+int av_parse_color(uint8_t *rgba_color, const char *color_string, int slen,
+                   void *log_ctx);
+
+/**
+ * Parses timestr and returns in *time a corresponding number of
+ * microseconds.
+ *
+ * @param timeval puts here the number of microseconds corresponding
+ * to the string in timestr. If the string represents a duration, it
+ * is the number of microseconds contained in the time interval.  If
+ * the string is a date, is the number of microseconds since 1st of
+ * January, 1970 up to the time of the parsed date.  If timestr cannot
+ * be successfully parsed, set *time to INT64_MIN.
+
+ * @param datestr a string representing a date or a duration.
+ * - If a date the syntax is:
+ * @code
+ * [{YYYY-MM-DD|YYYYMMDD}[T|t| ]]{{HH[:MM[:SS[.m...]]]}|{HH[MM[SS[.m...]]]}}[Z]
+ * now
+ * @endcode
+ * If the value is "now" it takes the current time.
+ * Time is local time unless Z is appended, in which case it is
+ * interpreted as UTC.
+ * If the year-month-day part is not specified it takes the current
+ * year-month-day.
+ * - If a duration the syntax is:
+ * @code
+ * [-]HH[:MM[:SS[.m...]]]
+ * [-]S+[.m...]
+ * @endcode
+ * @param duration flag which tells how to interpret timestr, if not
+ * zero timestr is interpreted as a duration, otherwise as a date
+ * @return 0 in case of success, a negative value corresponding to an
+ * AVERROR code otherwise
+ */
+int av_parse_time(int64_t *timeval, const char *timestr, int duration);
+
+/**
+ * Attempt to find a specific tag in a URL.
+ *
+ * syntax: '?tag1=val1&tag2=val2...'. Little URL decoding is done.
+ * Return 1 if found.
+ */
+int av_find_info_tag(char *arg, int arg_size, const char *tag1, const char *info);
+
+#endif /* AVUTIL_PARSEUTILS_H */
diff --git a/libavutil/pca.c b/libavutil/pca.c
index ce08e9c..770dc8d 100644
--- a/libavutil/pca.c
+++ b/libavutil/pca.c
@@ -2,20 +2,20 @@
  * principal component analysis (PCA)
  * Copyright (c) 2004 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavutil/pca.h b/libavutil/pca.h
index 00ddd60..436f122 100644
--- a/libavutil/pca.h
+++ b/libavutil/pca.h
@@ -2,20 +2,20 @@
  * principal component analysis (PCA)
  * Copyright (c) 2004 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavutil/pixdesc.c b/libavutil/pixdesc.c
index 82b3631..16a26da 100644
--- a/libavutil/pixdesc.c
+++ b/libavutil/pixdesc.c
@@ -2,30 +2,32 @@
  * pixel format descriptor
  * Copyright (c) 2009 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include <stdio.h>
+#include <string.h>
 #include "pixfmt.h"
 #include "pixdesc.h"
 
 #include "intreadwrite.h"
 
-void read_line(uint16_t *dst, const uint8_t *data[4], const int linesize[4],
-               const AVPixFmtDescriptor *desc, int x, int y, int c, int w, int read_pal_component)
+void av_read_image_line(uint16_t *dst, const uint8_t *data[4], const int linesize[4],
+                        const AVPixFmtDescriptor *desc, int x, int y, int c, int w, int read_pal_component)
 {
     AVComponentDescriptor comp= desc->comp[c];
     int plane= comp.plane;
@@ -51,11 +53,14 @@ void read_line(uint16_t *dst, const uint8_t *data[4], const int linesize[4],
         }
     } else {
         const uint8_t *p = data[plane]+ y*linesize[plane] + x*step + comp.offset_plus1-1;
+        int is_8bit = shift + depth <= 8;
+
+        if (is_8bit)
+            p += !!(flags & PIX_FMT_BE);
 
         while(w--){
-            int val;
-            if(flags & PIX_FMT_BE) val= AV_RB16(p);
-            else                   val= AV_RL16(p);
+            int val = is_8bit ? *p :
+                flags & PIX_FMT_BE ? AV_RB16(p) : AV_RL16(p);
             val = (val>>shift) & mask;
             if(read_pal_component)
                 val= data[1][4*val + c];
@@ -65,8 +70,8 @@ void read_line(uint16_t *dst, const uint8_t *data[4], const int linesize[4],
     }
 }
 
-void write_line(const uint16_t *src, uint8_t *data[4], const int linesize[4],
-                const AVPixFmtDescriptor *desc, int x, int y, int c, int w)
+void av_write_image_line(const uint16_t *src, uint8_t *data[4], const int linesize[4],
+                         const AVPixFmtDescriptor *desc, int x, int y, int c, int w)
 {
     AVComponentDescriptor comp = desc->comp[c];
     int plane = comp.plane;
@@ -89,15 +94,23 @@ void write_line(const uint16_t *src, uint8_t *data[4], const int linesize[4],
         int shift = comp.shift;
         uint8_t *p = data[plane]+ y*linesize[plane] + x*step + comp.offset_plus1-1;
 
-        while (w--) {
-            if (flags & PIX_FMT_BE) {
-                uint16_t val = AV_RB16(p) | (*src++<<shift);
-                AV_WB16(p, val);
-            } else {
-                uint16_t val = AV_RL16(p) | (*src++<<shift);
-                AV_WL16(p, val);
+        if (shift + depth <= 8) {
+            p += !!(flags & PIX_FMT_BE);
+            while (w--) {
+                *p |= (*src++<<shift);
+                p += step;
+            }
+        } else {
+            while (w--) {
+                if (flags & PIX_FMT_BE) {
+                    uint16_t val = AV_RB16(p) | (*src++<<shift);
+                    AV_WB16(p, val);
+                } else {
+                    uint16_t val = AV_RL16(p) | (*src++<<shift);
+                    AV_WL16(p, val);
+                }
+                p+= step;
             }
-            p+= step;
         }
     }
 }
@@ -617,6 +630,29 @@ const AVPixFmtDescriptor av_pix_fmt_descriptors[PIX_FMT_NB] = {
             {0,1,1,0,3},        /* B */
         },
     },
+    [PIX_FMT_BGR48BE] = {
+        .name = "bgr48be",
+        .nb_components= 3,
+        .log2_chroma_w= 0,
+        .log2_chroma_h= 0,
+        .comp = {
+            {0,5,1,0,15},       /* B */
+            {0,5,3,0,15},       /* G */
+            {0,5,5,0,15},       /* R */
+        },
+        .flags = PIX_FMT_BE,
+    },
+    [PIX_FMT_BGR48LE] = {
+        .name = "bgr48le",
+        .nb_components= 3,
+        .log2_chroma_w= 0,
+        .log2_chroma_h= 0,
+        .comp = {
+            {0,5,1,0,15},       /* B */
+            {0,5,3,0,15},       /* G */
+            {0,5,5,0,15},       /* R */
+        },
+    },
     [PIX_FMT_BGR565BE] = {
         .name = "bgr565be",
         .nb_components= 3,
@@ -838,3 +874,17 @@ int av_get_bits_per_pixel(const AVPixFmtDescriptor *pixdesc)
 
     return bits >> log2_pixels;
 }
+
+char *av_get_pix_fmt_string (char *buf, int buf_size, enum PixelFormat pix_fmt)
+{
+    /* print header */
+    if (pix_fmt < 0) {
+        snprintf (buf, buf_size, "name      " " nb_components" " nb_bits");
+    } else {
+        const AVPixFmtDescriptor *pixdesc = &av_pix_fmt_descriptors[pix_fmt];
+        snprintf(buf, buf_size, "%-11s %7d %10d",
+                 pixdesc->name, pixdesc->nb_components, av_get_bits_per_pixel(pixdesc));
+    }
+
+    return buf;
+}
diff --git a/libavutil/pixdesc.h b/libavutil/pixdesc.h
index 8e4c85d..cb75641 100644
--- a/libavutil/pixdesc.h
+++ b/libavutil/pixdesc.h
@@ -2,20 +2,20 @@
  * pixel format descriptor
  * Copyright (c) 2009 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -93,11 +93,11 @@ typedef struct AVPixFmtDescriptor{
 extern const AVPixFmtDescriptor av_pix_fmt_descriptors[];
 
 /**
- * Reads a line from an image, and writes the values of the
+ * Read a line from an image, and write the values of the
  * pixel format component c to dst.
  *
  * @param data the array containing the pointers to the planes of the image
- * @param linesizes the array containing the linesizes of the image
+ * @param linesize the array containing the linesizes of the image
  * @param desc the pixel format descriptor for the image
  * @param x the horizontal coordinate of the first pixel to read
  * @param y the vertical coordinate of the first pixel to read
@@ -108,28 +108,28 @@ extern const AVPixFmtDescriptor av_pix_fmt_descriptors[];
  * component c in data[1] to dst, rather than the palette indexes in
  * data[0]. The behavior is undefined if the format is not paletted.
  */
-void read_line(uint16_t *dst, const uint8_t *data[4], const int linesize[4],
-               const AVPixFmtDescriptor *desc, int x, int y, int c, int w, int read_pal_component);
+void av_read_image_line(uint16_t *dst, const uint8_t *data[4], const int linesize[4],
+                        const AVPixFmtDescriptor *desc, int x, int y, int c, int w, int read_pal_component);
 
 /**
- * Writes the values from src to the pixel format component c of an
+ * Write the values from src to the pixel format component c of an
  * image line.
  *
  * @param src array containing the values to write
  * @param data the array containing the pointers to the planes of the
  * image to write into. It is supposed to be zeroed.
- * @param linesizes the array containing the linesizes of the image
+ * @param linesize the array containing the linesizes of the image
  * @param desc the pixel format descriptor for the image
  * @param x the horizontal coordinate of the first pixel to write
  * @param y the vertical coordinate of the first pixel to write
  * @param w the width of the line to write, that is the number of
  * values to write to the image line
  */
-void write_line(const uint16_t *src, uint8_t *data[4], const int linesize[4],
-                const AVPixFmtDescriptor *desc, int x, int y, int c, int w);
+void av_write_image_line(const uint16_t *src, uint8_t *data[4], const int linesize[4],
+                         const AVPixFmtDescriptor *desc, int x, int y, int c, int w);
 
 /**
- * Returns the pixel format corresponding to name.
+ * Return the pixel format corresponding to name.
  *
  * If there is no pixel format with name name, then looks for a
  * pixel format with the name corresponding to the native endian
@@ -142,7 +142,19 @@ void write_line(const uint16_t *src, uint8_t *data[4], const int linesize[4],
 enum PixelFormat av_get_pix_fmt(const char *name);
 
 /**
- * Returns the number of bits per pixel used by the pixel format
+ * Print in buf the string corresponding to the pixel format with
+ * number pix_fmt, or an header if pix_fmt is negative.
+ *
+ * @param buf the buffer where to write the string
+ * @param buf_size the size of buf
+ * @param pix_fmt the number of the pixel format to print the
+ * corresponding info string, or a negative value to print the
+ * corresponding header.
+ */
+char *av_get_pix_fmt_string (char *buf, int buf_size, enum PixelFormat pix_fmt);
+
+/**
+ * Return the number of bits per pixel used by the pixel format
  * described by pixdesc.
  *
  * The returned number of bits refers to the number of bits actually
diff --git a/libavutil/pixfmt.h b/libavutil/pixfmt.h
index d976f34..dcdf4af 100644
--- a/libavutil/pixfmt.h
+++ b/libavutil/pixfmt.h
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -71,9 +71,9 @@ enum PixelFormat {
     PIX_FMT_MONOWHITE, ///<        Y        ,  1bpp, 0 is white, 1 is black, in each byte pixels are ordered from the msb to the lsb
     PIX_FMT_MONOBLACK, ///<        Y        ,  1bpp, 0 is black, 1 is white, in each byte pixels are ordered from the msb to the lsb
     PIX_FMT_PAL8,      ///< 8 bit with PIX_FMT_RGB32 palette
-    PIX_FMT_YUVJ420P,  ///< planar YUV 4:2:0, 12bpp, full scale (JPEG)
-    PIX_FMT_YUVJ422P,  ///< planar YUV 4:2:2, 16bpp, full scale (JPEG)
-    PIX_FMT_YUVJ444P,  ///< planar YUV 4:4:4, 24bpp, full scale (JPEG)
+    PIX_FMT_YUVJ420P,  ///< planar YUV 4:2:0, 12bpp, full scale (JPEG), deprecated in favor of PIX_FMT_YUV420P and setting color_range
+    PIX_FMT_YUVJ422P,  ///< planar YUV 4:2:2, 16bpp, full scale (JPEG), deprecated in favor of PIX_FMT_YUV422P and setting color_range
+    PIX_FMT_YUVJ444P,  ///< planar YUV 4:4:4, 24bpp, full scale (JPEG), deprecated in favor of PIX_FMT_YUV444P and setting color_range
     PIX_FMT_XVMC_MPEG2_MC,///< XVideo Motion Acceleration via common packet passing
     PIX_FMT_XVMC_MPEG2_IDCT,
     PIX_FMT_UYVY422,   ///< packed YUV 4:2:2, 16bpp, Cb Y0 Cr Y1
@@ -95,7 +95,7 @@ enum PixelFormat {
     PIX_FMT_GRAY16BE,  ///<        Y        , 16bpp, big-endian
     PIX_FMT_GRAY16LE,  ///<        Y        , 16bpp, little-endian
     PIX_FMT_YUV440P,   ///< planar YUV 4:4:0 (1 Cr & Cb sample per 1x2 Y samples)
-    PIX_FMT_YUVJ440P,  ///< planar YUV 4:4:0 full scale (JPEG)
+    PIX_FMT_YUVJ440P,  ///< planar YUV 4:4:0 full scale (JPEG), deprecated in favor of PIX_FMT_YUV440P and setting color_range
     PIX_FMT_YUVA420P,  ///< planar YUV 4:2:0, 20bpp, (1 Cr & Cb sample per 2x2 Y & A samples)
     PIX_FMT_VDPAU_H264,///< H.264 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers
     PIX_FMT_VDPAU_MPEG1,///< MPEG-1 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers
@@ -133,6 +133,8 @@ enum PixelFormat {
     PIX_FMT_BGR444BE,  ///< packed BGR 4:4:4, 16bpp, (msb)4A 4B 4G 4R(lsb), big-endian, most significant bits to 1
     PIX_FMT_BGR444LE,  ///< packed BGR 4:4:4, 16bpp, (msb)4A 4B 4G 4R(lsb), little-endian, most significant bits to 1
     PIX_FMT_Y400A,     ///< 8bit gray, 8bit alpha
+    PIX_FMT_BGR48BE,   ///< packed RGB 16:16:16, 48bpp, 16B, 16G, 16R, the 2-byte value for each R/G/B component is stored as big-endian
+    PIX_FMT_BGR48LE,   ///< packed RGB 16:16:16, 48bpp, 16B, 16G, 16R, the 2-byte value for each R/G/B component is stored as little-endian
     PIX_FMT_NB,        ///< number of pixel formats, DO NOT USE THIS if you want to link with shared libav* because the number of formats might differ between versions
 };
 
@@ -152,6 +154,7 @@ enum PixelFormat {
 #define PIX_FMT_RGB565 PIX_FMT_NE(RGB565BE, RGB565LE)
 #define PIX_FMT_RGB555 PIX_FMT_NE(RGB555BE, RGB555LE)
 #define PIX_FMT_RGB444 PIX_FMT_NE(RGB444BE, RGB444LE)
+#define PIX_FMT_BGR48  PIX_FMT_NE(BGR48BE,  BGR48LE)
 #define PIX_FMT_BGR565 PIX_FMT_NE(BGR565BE, BGR565LE)
 #define PIX_FMT_BGR555 PIX_FMT_NE(BGR555BE, BGR555LE)
 #define PIX_FMT_BGR444 PIX_FMT_NE(BGR444BE, BGR444LE)
diff --git a/libavutil/ppc/cpu.c b/libavutil/ppc/cpu.c
new file mode 100644
index 0000000..6b122ed
--- /dev/null
+++ b/libavutil/ppc/cpu.c
@@ -0,0 +1,85 @@
+/*
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifdef __APPLE__
+#undef _POSIX_C_SOURCE
+#include <sys/sysctl.h>
+#elif defined(__OpenBSD__)
+#undef _POSIX_C_SOURCE
+#include <sys/param.h>
+#include <sys/sysctl.h>
+#include <machine/cpu.h>
+#elif defined(__AMIGAOS4__)
+#include <exec/exec.h>
+#include <interfaces/exec.h>
+#include <proto/exec.h>
+#endif /* __APPLE__ */
+
+#include "libavutil/cpu.h"
+#include "config.h"
+
+/**
+ * This function MAY rely on signal() or fork() in order to make sure AltiVec
+ * is present.
+ */
+int ff_get_cpu_flags_ppc(void)
+{
+#if HAVE_ALTIVEC
+#ifdef __AMIGAOS4__
+    ULONG result = 0;
+    extern struct ExecIFace *IExec;
+
+    IExec->GetCPUInfoTags(GCIT_VectorUnit, &result, TAG_DONE);
+    if (result == VECTORTYPE_ALTIVEC)
+        return AV_CPU_FLAG_ALTIVEC;
+    return 0;
+#elif defined(__APPLE__) || defined(__OpenBSD__)
+#ifdef __OpenBSD__
+    int sels[2] = {CTL_MACHDEP, CPU_ALTIVEC};
+#else
+    int sels[2] = {CTL_HW, HW_VECTORUNIT};
+#endif
+    int has_vu = 0;
+    size_t len = sizeof(has_vu);
+    int err;
+
+    err = sysctl(sels, 2, &has_vu, &len, NULL, 0);
+
+    if (err == 0)
+        return has_vu ? AV_CPU_FLAG_ALTIVEC : 0;
+    return 0;
+#elif CONFIG_RUNTIME_CPUDETECT
+    int proc_ver;
+    // Support of mfspr PVR emulation added in Linux 2.6.17.
+    __asm__ volatile("mfspr %0, 287" : "=r" (proc_ver));
+    proc_ver >>= 16;
+    if (proc_ver  & 0x8000 ||
+        proc_ver == 0x000c ||
+        proc_ver == 0x0039 || proc_ver == 0x003c ||
+        proc_ver == 0x0044 || proc_ver == 0x0045 ||
+        proc_ver == 0x0070)
+        return AV_CPU_FLAG_ALTIVEC;
+    return 0;
+#else
+    // Since we were compiled for AltiVec, just assume we have it
+    // until someone comes up with a proper way (not involving signal hacks).
+    return AV_CPU_FLAG_ALTIVEC;
+#endif /* __AMIGAOS4__ */
+#endif /* HAVE_ALTIVEC */
+    return 0;
+}
diff --git a/libavutil/ppc/intreadwrite.h b/libavutil/ppc/intreadwrite.h
index 3667703..fec54e6 100644
--- a/libavutil/ppc/intreadwrite.h
+++ b/libavutil/ppc/intreadwrite.h
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2008 Mans Rullgard <mans at mansr.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavutil/ppc/timer.h b/libavutil/ppc/timer.h
index 155fc01..0981d0c 100644
--- a/libavutil/ppc/timer.h
+++ b/libavutil/ppc/timer.h
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2005 Luca Barbato <lu_zero at gentoo.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavutil/random_seed.c b/libavutil/random_seed.c
index 236cadd..6dc8d22 100644
--- a/libavutil/random_seed.c
+++ b/libavutil/random_seed.c
@@ -1,44 +1,90 @@
 /*
  * Copyright (c) 2009 Baptiste Coudurier <baptiste.coudurier at gmail.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include <unistd.h>
 #include <fcntl.h>
 #include "timer.h"
+#include "time.h"
 #include "random_seed.h"
+#include "avutil.h"
 
-uint32_t ff_random_get_seed(void)
+static int read_random(uint32_t *dst, const char *file)
 {
-    uint32_t seed;
-    int fd;
-
-    if ((fd = open("/dev/random", O_RDONLY)) == -1)
-        fd = open("/dev/urandom", O_RDONLY);
-    if (fd != -1){
-        int err = read(fd, &seed, 4);
-        close(fd);
-        if (err == 4)
-            return seed;
+    int fd = open(file, O_RDONLY);
+    int err = -1;
+
+    if (fd == -1)
+        return -1;
+    err = read(fd, dst, sizeof(*dst));
+    close(fd);
+
+    return err;
+}
+
+static uint32_t get_generic_seed(void)
+{
+    clock_t last_t=0;
+    int bits=0;
+    uint64_t random=0;
+    unsigned i;
+    float s=0.000000000001;
+
+    for(i=0;bits<64;i++){
+        clock_t t= clock();
+        if(last_t && fabs(t-last_t)>s || t==(clock_t)-1){
+            if(i<10000 && s<(1<<24)){
+                s+=s;
+                i=t=0;
+            }else{
+                random= 2*random + (i&1);
+                bits++;
+            }
+        }
+        last_t= t;
     }
 #ifdef AV_READ_TIME
-    seed = AV_READ_TIME();
+    random ^= AV_READ_TIME();
+#else
+    random ^= clock();
 #endif
-    // XXX what to do ?
-    return seed;
+
+    random += random>>32;
+
+    return random;
 }
+
+uint32_t av_get_random_seed(void)
+{
+    uint32_t seed;
+
+    if (read_random(&seed, "/dev/urandom") == sizeof(seed))
+        return seed;
+    if (read_random(&seed, "/dev/random")  == sizeof(seed))
+        return seed;
+    return get_generic_seed();
+}
+
+#if LIBAVUTIL_VERSION_MAJOR < 51
+attribute_deprecated uint32_t ff_random_get_seed(void);
+uint32_t ff_random_get_seed(void)
+{
+    return av_get_random_seed();
+}
+#endif
diff --git a/libavutil/random_seed.h b/libavutil/random_seed.h
index a954381..8157d42 100644
--- a/libavutil/random_seed.h
+++ b/libavutil/random_seed.h
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2009 Baptiste Coudurier <baptiste.coudurier at gmail.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -24,8 +24,8 @@
 #include <stdint.h>
 
 /**
- * Gets a seed to use in conjunction with random functions.
+ * Get a seed to use in conjunction with random functions.
  */
-uint32_t ff_random_get_seed(void);
+uint32_t av_get_random_seed(void);
 
 #endif /* AVUTIL_RANDOM_SEED_H */
diff --git a/libavutil/rational.c b/libavutil/rational.c
index 3e8b885..b2b05cc 100644
--- a/libavutil/rational.c
+++ b/libavutil/rational.c
@@ -2,20 +2,20 @@
  * rational numbers
  * Copyright (c) 2003 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,7 +25,7 @@
  * @author Michael Niedermayer <michaelni at gmx.at>
  */
 
-#include <assert.h>
+#include "avassert.h"
 //#include <math.h>
 #include <limits.h>
 
@@ -67,7 +67,7 @@ int av_reduce(int *dst_num, int *dst_den, int64_t num, int64_t den, int64_t max)
         num= den;
         den= next_den;
     }
-    assert(av_gcd(a1.num, a1.den) <= 1U);
+    av_assert2(av_gcd(a1.num, a1.den) <= 1U);
 
     *dst_num = sign ? -a1.num : a1.num;
     *dst_den = a1.den;
@@ -96,10 +96,14 @@ AVRational av_sub_q(AVRational b, AVRational c){
 AVRational av_d2q(double d, int max){
     AVRational a;
 #define LOG2  0.69314718055994530941723212145817656807550013436025
-    int exponent= FFMAX( (int)(log(fabs(d) + 1e-20)/LOG2), 0);
-    int64_t den= 1LL << (61 - exponent);
+    int exponent;
+    int64_t den;
     if (isnan(d))
         return (AVRational){0,0};
+    if (isinf(d))
+        return (AVRational){ d<0 ? -1:1, 0 };
+    exponent = FFMAX( (int)(log(fabs(d) + 1e-20)/LOG2), 0);
+    den = 1LL << (61 - exponent);
     av_reduce(&a.num, &a.den, (int64_t)(d * den + 0.5), den, max);
 
     return a;
@@ -129,3 +133,23 @@ int av_find_nearest_q_idx(AVRational q, const AVRational* q_list)
 
     return nearest_q_idx;
 }
+
+#ifdef TEST
+main(){
+    AVRational a,b;
+    for(a.num=-2; a.num<=2; a.num++){
+        for(a.den=-2; a.den<=2; a.den++){
+            for(b.num=-2; b.num<=2; b.num++){
+                for(b.den=-2; b.den<=2; b.den++){
+                    int c= av_cmp_q(a,b);
+                    double d= av_q2d(a) == av_q2d(b) ? 0 : (av_q2d(a) - av_q2d(b));
+                    if(d>0) d=1;
+                    else if(d<0) d=-1;
+                    else if(d != d) d= INT_MIN;
+                    if(c!=d) av_log(0, AV_LOG_ERROR, "%d/%d %d/%d, %d %f\n", a.num, a.den, b.num, b.den, c,d);
+                }
+            }
+        }
+    }
+}
+#endif
diff --git a/libavutil/rational.h b/libavutil/rational.h
index 4d91f7b..a487114 100644
--- a/libavutil/rational.h
+++ b/libavutil/rational.h
@@ -2,20 +2,20 @@
  * rational numbers
  * Copyright (c) 2003 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -29,6 +29,7 @@
 #define AVUTIL_RATIONAL_H
 
 #include <stdint.h>
+#include <limits.h>
 #include "attributes.h"
 
 /**
@@ -40,20 +41,23 @@ typedef struct AVRational{
 } AVRational;
 
 /**
- * Compares two rationals.
+ * Compare two rationals.
  * @param a first rational
  * @param b second rational
- * @return 0 if a==b, 1 if a>b and -1 if a<b
+ * @return 0 if a==b, 1 if a>b, -1 if a<b, and INT_MIN if one of the
+ * values is of the form 0/0
  */
 static inline int av_cmp_q(AVRational a, AVRational b){
     const int64_t tmp= a.num * (int64_t)b.den - b.num * (int64_t)a.den;
 
-    if(tmp) return (tmp>>63)|1;
-    else    return 0;
+    if(tmp) return ((tmp ^ a.den ^ b.den)>>63)|1;
+    else if(b.den && a.den) return 0;
+    else if(a.num && b.num) return (a.num>>31) - (b.num>>31);
+    else                    return INT_MIN;
 }
 
 /**
- * Converts rational to double.
+ * Convert rational to double.
  * @param a rational to convert
  * @return (double) a
  */
@@ -62,7 +66,7 @@ static inline double av_q2d(AVRational a){
 }
 
 /**
- * Reduces a fraction.
+ * Reduce a fraction.
  * This is useful for framerate calculations.
  * @param dst_num destination numerator
  * @param dst_den destination denominator
@@ -74,7 +78,7 @@ static inline double av_q2d(AVRational a){
 int av_reduce(int *dst_num, int *dst_den, int64_t num, int64_t den, int64_t max);
 
 /**
- * Multiplies two rationals.
+ * Multiply two rationals.
  * @param b first rational
  * @param c second rational
  * @return b*c
@@ -82,7 +86,7 @@ int av_reduce(int *dst_num, int *dst_den, int64_t num, int64_t den, int64_t max)
 AVRational av_mul_q(AVRational b, AVRational c) av_const;
 
 /**
- * Divides one rational by another.
+ * Divide one rational by another.
  * @param b first rational
  * @param c second rational
  * @return b/c
@@ -90,7 +94,7 @@ AVRational av_mul_q(AVRational b, AVRational c) av_const;
 AVRational av_div_q(AVRational b, AVRational c) av_const;
 
 /**
- * Adds two rationals.
+ * Add two rationals.
  * @param b first rational
  * @param c second rational
  * @return b+c
@@ -98,7 +102,7 @@ AVRational av_div_q(AVRational b, AVRational c) av_const;
 AVRational av_add_q(AVRational b, AVRational c) av_const;
 
 /**
- * Subtracts one rational from another.
+ * Subtract one rational from another.
  * @param b first rational
  * @param c second rational
  * @return b-c
@@ -106,7 +110,9 @@ AVRational av_add_q(AVRational b, AVRational c) av_const;
 AVRational av_sub_q(AVRational b, AVRational c) av_const;
 
 /**
- * Converts a double precision floating point number to a rational.
+ * Convert a double precision floating point number to a rational.
+ * inf is expressed as {1,0} or {-1,0} depending on the sign.
+ *
  * @param d double to convert
  * @param max the maximum allowed numerator and denominator
  * @return (AVRational) d
@@ -120,7 +126,7 @@ AVRational av_d2q(double d, int max) av_const;
 int av_nearer_q(AVRational q, AVRational q1, AVRational q2);
 
 /**
- * Finds the nearest value in q_list to q.
+ * Find the nearest value in q_list to q.
  * @param q_list an array of rationals terminated by {0, 0}
  * @return the index of the nearest value found in the array
  */
diff --git a/libavutil/rc4.c b/libavutil/rc4.c
index 4e52ba5..3bf710f 100644
--- a/libavutil/rc4.c
+++ b/libavutil/rc4.c
@@ -4,20 +4,20 @@
  *
  * loosely based on LibTomCrypt by Tom St Denis
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #include "avutil.h"
diff --git a/libavutil/rc4.h b/libavutil/rc4.h
index 07223a5..dc5066d 100644
--- a/libavutil/rc4.h
+++ b/libavutil/rc4.h
@@ -1,20 +1,20 @@
 /*
  * RC4 encryption/decryption/pseudo-random number generator
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavutil/samplefmt.c b/libavutil/samplefmt.c
new file mode 100644
index 0000000..06b50d9
--- /dev/null
+++ b/libavutil/samplefmt.c
@@ -0,0 +1,73 @@
+/*
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "samplefmt.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+typedef struct SampleFmtInfo {
+    const char *name;
+    int bits;
+} SampleFmtInfo;
+
+/** this table gives more information about formats */
+static const SampleFmtInfo sample_fmt_info[AV_SAMPLE_FMT_NB] = {
+    [AV_SAMPLE_FMT_U8]  = { .name = "u8",  .bits = 8 },
+    [AV_SAMPLE_FMT_S16] = { .name = "s16", .bits = 16 },
+    [AV_SAMPLE_FMT_S32] = { .name = "s32", .bits = 32 },
+    [AV_SAMPLE_FMT_FLT] = { .name = "flt", .bits = 32 },
+    [AV_SAMPLE_FMT_DBL] = { .name = "dbl", .bits = 64 },
+};
+
+const char *av_get_sample_fmt_name(enum AVSampleFormat sample_fmt)
+{
+    if (sample_fmt < 0 || sample_fmt >= AV_SAMPLE_FMT_NB)
+        return NULL;
+    return sample_fmt_info[sample_fmt].name;
+}
+
+enum AVSampleFormat av_get_sample_fmt(const char *name)
+{
+    int i;
+
+    for (i = 0; i < AV_SAMPLE_FMT_NB; i++)
+        if (!strcmp(sample_fmt_info[i].name, name))
+            return i;
+    return AV_SAMPLE_FMT_NONE;
+}
+
+char *av_get_sample_fmt_string (char *buf, int buf_size, enum AVSampleFormat sample_fmt)
+{
+    /* print header */
+    if (sample_fmt < 0)
+        snprintf(buf, buf_size, "name  " " depth");
+    else if (sample_fmt < AV_SAMPLE_FMT_NB) {
+        SampleFmtInfo info = sample_fmt_info[sample_fmt];
+        snprintf (buf, buf_size, "%-6s" "   %2d ", info.name, info.bits);
+    }
+
+    return buf;
+}
+
+int av_get_bits_per_sample_fmt(enum AVSampleFormat sample_fmt)
+{
+    return sample_fmt < 0 || sample_fmt >= AV_SAMPLE_FMT_NB ?
+        0 : sample_fmt_info[sample_fmt].bits;
+}
diff --git a/libavutil/samplefmt.h b/libavutil/samplefmt.h
new file mode 100644
index 0000000..2326f4a
--- /dev/null
+++ b/libavutil/samplefmt.h
@@ -0,0 +1,70 @@
+/*
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_SAMPLEFMT_H
+#define AVUTIL_SAMPLEFMT_H
+
+/**
+ * all in native-endian format
+ */
+enum AVSampleFormat {
+    AV_SAMPLE_FMT_NONE = -1,
+    AV_SAMPLE_FMT_U8,          ///< unsigned 8 bits
+    AV_SAMPLE_FMT_S16,         ///< signed 16 bits
+    AV_SAMPLE_FMT_S32,         ///< signed 32 bits
+    AV_SAMPLE_FMT_FLT,         ///< float
+    AV_SAMPLE_FMT_DBL,         ///< double
+    AV_SAMPLE_FMT_NB           ///< Number of sample formats. DO NOT USE if linking dynamically
+};
+
+/**
+ * Return the name of sample_fmt, or NULL if sample_fmt is not
+ * recognized.
+ */
+const char *av_get_sample_fmt_name(enum AVSampleFormat sample_fmt);
+
+/**
+ * Return a sample format corresponding to name, or AV_SAMPLE_FMT_NONE
+ * on error.
+ */
+enum AVSampleFormat av_get_sample_fmt(const char *name);
+
+/**
+ * Generate a string corresponding to the sample format with
+ * sample_fmt, or a header if sample_fmt is negative.
+ *
+ * @param buf the buffer where to write the string
+ * @param buf_size the size of buf
+ * @param sample_fmt the number of the sample format to print the
+ * corresponding info string, or a negative value to print the
+ * corresponding header.
+ * @return the pointer to the filled buffer or NULL if sample_fmt is
+ * unknown or in case of other errors
+ */
+char *av_get_sample_fmt_string(char *buf, int buf_size, enum AVSampleFormat sample_fmt);
+
+/**
+ * Return sample format bits per sample.
+ *
+ * @param sample_fmt the sample format
+ * @return number of bits per sample or zero if unknown for the given
+ * sample format
+ */
+int av_get_bits_per_sample_fmt(enum AVSampleFormat sample_fmt);
+
+#endif /* AVUTIL_SAMPLEFMT_H */
diff --git a/libavutil/sh4/bswap.h b/libavutil/sh4/bswap.h
index 6d237c5..1ff1bfd 100644
--- a/libavutil/sh4/bswap.h
+++ b/libavutil/sh4/bswap.h
@@ -1,18 +1,18 @@
 /*
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -28,15 +28,15 @@
 #include "config.h"
 #include "libavutil/attributes.h"
 
-#define bswap_16 bswap_16
-static av_always_inline av_const uint16_t bswap_16(uint16_t x)
+#define av_bswap16 av_bswap16
+static av_always_inline av_const uint16_t av_bswap16(uint16_t x)
 {
     __asm__("swap.b %0,%0" : "+r"(x));
     return x;
 }
 
-#define bswap_32 bswap_32
-static av_always_inline av_const uint32_t bswap_32(uint32_t x)
+#define av_bswap32 av_bswap32
+static av_always_inline av_const uint32_t av_bswap32(uint32_t x)
 {
     __asm__("swap.b %0,%0\n"
             "swap.w %0,%0\n"
diff --git a/libavutil/sha.c b/libavutil/sha.c
index 5a3b575..6d9c84e 100644
--- a/libavutil/sha.c
+++ b/libavutil/sha.c
@@ -4,20 +4,20 @@
  * based on public domain SHA-1 code by Steve Reid <steve at edmweb.com>
  * and on BSD-licensed SHA-2 code by Aaron D. Gifford
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -43,7 +43,7 @@ const int av_sha_size = sizeof(AVSHA);
 #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
 
 /* (R0+R1), R2, R3, R4 are the different operations used in SHA1 */
-#define blk0(i) (block[i] = be2me_32(((const uint32_t*)buffer)[i]))
+#define blk0(i) (block[i] = av_be2ne32(((const uint32_t*)buffer)[i]))
 #define blk(i)  (block[i] = rol(block[i-3] ^ block[i-8] ^ block[i-14] ^ block[i-16], 1))
 
 #define R0(v,w,x,y,z,i) z += ((w&(x^y))^y)     + blk0(i) + 0x5A827999 + rol(v, 5); w = rol(w, 30);
@@ -68,7 +68,7 @@ static void sha1_transform(uint32_t state[5], const uint8_t buffer[64])
     for (i = 0; i < 80; i++) {
         int t;
         if (i < 16)
-            t = be2me_32(((uint32_t*)buffer)[i]);
+            t = av_be2ne32(((uint32_t*)buffer)[i]);
         else
             t = rol(block[i-3] ^ block[i-8] ^ block[i-14] ^ block[i-16], 1);
         block[i] = t;
@@ -314,7 +314,7 @@ void av_sha_update(AVSHA* ctx, const uint8_t* data, unsigned int len)
 void av_sha_final(AVSHA* ctx, uint8_t *digest)
 {
     int i;
-    uint64_t finalcount = be2me_64(ctx->count << 3);
+    uint64_t finalcount = av_be2ne64(ctx->count << 3);
 
     av_sha_update(ctx, "\200", 1);
     while ((ctx->count & 63) != 56)
diff --git a/libavutil/sha.h b/libavutil/sha.h
index 5a20230..df261fa 100644
--- a/libavutil/sha.h
+++ b/libavutil/sha.h
@@ -1,20 +1,20 @@
 /*
  * Copyright (C) 2007 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -28,7 +28,7 @@ extern const int av_sha_size;
 struct AVSHA;
 
 /**
- * Initializes SHA-1 or SHA-2 hashing.
+ * Initialize SHA-1 or SHA-2 hashing.
  *
  * @param context pointer to the function context (of size av_sha_size)
  * @param bits    number of bits in digest (SHA-1 - 160 bits, SHA-2 224 or 256 bits)
@@ -37,7 +37,7 @@ struct AVSHA;
 int av_sha_init(struct AVSHA* context, int bits);
 
 /**
- * Updates hash value.
+ * Update hash value.
  *
  * @param context hash function context
  * @param data    input data to update hash with
@@ -46,7 +46,7 @@ int av_sha_init(struct AVSHA* context, int bits);
 void av_sha_update(struct AVSHA* context, const uint8_t* data, unsigned int len);
 
 /**
- * Finishes hashing and output digest value.
+ * Finish hashing and output digest value.
  *
  * @param context hash function context
  * @param digest  buffer where output digest value is stored
diff --git a/libavutil/sha1.h b/libavutil/sha1.h
index cf7c4a6..b60d770 100644
--- a/libavutil/sha1.h
+++ b/libavutil/sha1.h
@@ -1,20 +1,20 @@
 /*
  * Copyright (C) 2007 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -28,7 +28,7 @@ extern const int av_sha1_size;
 struct AVSHA1;
 
 /**
- * Initializes SHA-1 hashing.
+ * Initialize SHA-1 hashing.
  *
  * @param context pointer to the function context (of size av_sha_size)
  * @deprecated use av_sha_init() instead
@@ -36,7 +36,7 @@ struct AVSHA1;
 void av_sha1_init(struct AVSHA1* context);
 
 /**
- * Updates hash value.
+ * Update hash value.
  *
  * @param context hash function context
  * @param data    input data to update hash with
@@ -46,7 +46,7 @@ void av_sha1_init(struct AVSHA1* context);
 void av_sha1_update(struct AVSHA1* context, const uint8_t* data, unsigned int len);
 
 /**
- * Finishes hashing and output digest value.
+ * Finish hashing and output digest value.
  *
  * @param context hash function context
  * @param digest  buffer where output digest value is stored
diff --git a/libavutil/softfloat.c b/libavutil/softfloat.c
index efa0420..55969fb 100644
--- a/libavutil/softfloat.c
+++ b/libavutil/softfloat.c
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavutil/softfloat.h b/libavutil/softfloat.h
index 97e09ea..3078bd7 100644
--- a/libavutil/softfloat.h
+++ b/libavutil/softfloat.h
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavutil/timer.h b/libavutil/timer.h
index cd8fba8..a2ca5cf 100644
--- a/libavutil/timer.h
+++ b/libavutil/timer.h
@@ -4,20 +4,20 @@
  *
  * copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavutil/tomi/intreadwrite.h b/libavutil/tomi/intreadwrite.h
index 778b804..9295004 100644
--- a/libavutil/tomi/intreadwrite.h
+++ b/libavutil/tomi/intreadwrite.h
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2010 Mans Rullgard <mans at mansr.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavutil/tree.c b/libavutil/tree.c
index 8769c76..067e5b0 100644
--- a/libavutil/tree.c
+++ b/libavutil/tree.c
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavutil/tree.h b/libavutil/tree.h
index dde2f10..9115e2f 100644
--- a/libavutil/tree.h
+++ b/libavutil/tree.h
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -33,7 +33,7 @@ struct AVTreeNode;
 extern const int av_tree_node_size;
 
 /**
- * Finds an element.
+ * Find an element.
  * @param root a pointer to the root node of the tree
  * @param next If next is not NULL, then next[0] will contain the previous
  *             element and next[1] the next element. If either does not exist,
@@ -44,7 +44,7 @@ extern const int av_tree_node_size;
 void *av_tree_find(const struct AVTreeNode *root, void *key, int (*cmp)(void *key, const void *b), void *next[2]);
 
 /**
- * Inserts or removes an element.
+ * Insert or remove an element.
  * If *next is NULL, then the supplied element will be removed if it exists.
  * If *next is not NULL, then the supplied element will be inserted, unless
  * it already exists in the tree.
@@ -67,7 +67,7 @@ void *av_tree_find(const struct AVTreeNode *root, void *key, int (*cmp)(void *ke
  *                 return av_tree_insert(rootp, key, cmp, next);
  *             }
  *             void *tree_remove(struct AVTreeNode **rootp, void *key, int (*cmp)(void *key, const void *b, AVTreeNode **next)){
- *                 if(*next) av_freep(next);
+ *                 av_freep(next);
  *                 return av_tree_insert(rootp, key, cmp, next);
  *             }
  *             @endcode
@@ -80,7 +80,7 @@ void *av_tree_insert(struct AVTreeNode **rootp, void *key, int (*cmp)(void *key,
 void av_tree_destroy(struct AVTreeNode *t);
 
 /**
- * Applies enu(opaque, &elem) to all the elements in the tree in a given range.
+ * Apply enu(opaque, &elem) to all the elements in the tree in a given range.
  *
  * @param cmp a comparison function that returns < 0 for a element below the
  *            range, > 0 for a element above the range and == 0 for a
diff --git a/libavutil/utils.c b/libavutil/utils.c
index 8a1d32e..042e735 100644
--- a/libavutil/utils.c
+++ b/libavutil/utils.c
@@ -1,18 +1,18 @@
 /*
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -31,11 +31,11 @@ unsigned avutil_version(void)
 
 const char *avutil_configuration(void)
 {
-    return FFMPEG_CONFIGURATION;
+    return LIBAV_CONFIGURATION;
 }
 
 const char *avutil_license(void)
 {
 #define LICENSE_PREFIX "libavutil license: "
-    return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1;
+    return LICENSE_PREFIX LIBAV_LICENSE + sizeof(LICENSE_PREFIX) - 1;
 }
diff --git a/libavutil/x86/bswap.h b/libavutil/x86/bswap.h
index 26dc4e2..28e3fec 100644
--- a/libavutil/x86/bswap.h
+++ b/libavutil/x86/bswap.h
@@ -1,18 +1,18 @@
 /*
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -28,15 +28,15 @@
 #include "config.h"
 #include "libavutil/attributes.h"
 
-#define bswap_16 bswap_16
-static av_always_inline av_const uint16_t bswap_16(uint16_t x)
+#define av_bswap16 av_bswap16
+static av_always_inline av_const uint16_t av_bswap16(uint16_t x)
 {
     __asm__("rorw $8, %0" : "+r"(x));
     return x;
 }
 
-#define bswap_32 bswap_32
-static av_always_inline av_const uint32_t bswap_32(uint32_t x)
+#define av_bswap32 av_bswap32
+static av_always_inline av_const uint32_t av_bswap32(uint32_t x)
 {
 #if HAVE_BSWAP
     __asm__("bswap   %0" : "+r" (x));
@@ -50,8 +50,8 @@ static av_always_inline av_const uint32_t bswap_32(uint32_t x)
 }
 
 #if ARCH_X86_64
-#define bswap_64 bswap_64
-static inline uint64_t av_const bswap_64(uint64_t x)
+#define av_bswap64 av_bswap64
+static inline uint64_t av_const av_bswap64(uint64_t x)
 {
     __asm__("bswap  %0": "=r" (x) : "0" (x));
     return x;
diff --git a/libavutil/x86/cpu.c b/libavutil/x86/cpu.c
new file mode 100644
index 0000000..78aeadf
--- /dev/null
+++ b/libavutil/x86/cpu.c
@@ -0,0 +1,159 @@
+/*
+ * CPU detection code, extracted from mmx.h
+ * (c)1997-99 by H. Dietz and R. Fisher
+ * Converted to C and improved by Fabrice Bellard.
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <stdlib.h>
+#include <string.h>
+#include "libavutil/x86_cpu.h"
+#include "libavutil/cpu.h"
+
+/* ebx saving is necessary for PIC. gcc seems unable to see it alone */
+#define cpuid(index,eax,ebx,ecx,edx)\
+    __asm__ volatile\
+        ("mov %%"REG_b", %%"REG_S"\n\t"\
+         "cpuid\n\t"\
+         "xchg %%"REG_b", %%"REG_S\
+         : "=a" (eax), "=S" (ebx),\
+           "=c" (ecx), "=d" (edx)\
+         : "0" (index));
+
+#define xgetbv(index,eax,edx)                                   \
+    __asm__ (".byte 0x0f, 0x01, 0xd0" : "=a"(eax), "=d"(edx) : "c" (index))
+
+/* Function to test if multimedia instructions are supported...  */
+int ff_get_cpu_flags_x86(void)
+{
+    int rval = 0;
+    int eax, ebx, ecx, edx;
+    int max_std_level, max_ext_level, std_caps=0, ext_caps=0;
+    int family=0, model=0;
+    union { int i[3]; char c[12]; } vendor;
+
+#if ARCH_X86_32
+    x86_reg a, c;
+    __asm__ volatile (
+        /* See if CPUID instruction is supported ... */
+        /* ... Get copies of EFLAGS into eax and ecx */
+        "pushfl\n\t"
+        "pop %0\n\t"
+        "mov %0, %1\n\t"
+
+        /* ... Toggle the ID bit in one copy and store */
+        /*     to the EFLAGS reg */
+        "xor $0x200000, %0\n\t"
+        "push %0\n\t"
+        "popfl\n\t"
+
+        /* ... Get the (hopefully modified) EFLAGS */
+        "pushfl\n\t"
+        "pop %0\n\t"
+        : "=a" (a), "=c" (c)
+        :
+        : "cc"
+        );
+
+    if (a == c)
+        return 0; /* CPUID not supported */
+#endif
+
+    cpuid(0, max_std_level, vendor.i[0], vendor.i[2], vendor.i[1]);
+
+    if(max_std_level >= 1){
+        cpuid(1, eax, ebx, ecx, std_caps);
+        family = ((eax>>8)&0xf) + ((eax>>20)&0xff);
+        model  = ((eax>>4)&0xf) + ((eax>>12)&0xf0);
+        if (std_caps & (1<<23))
+            rval |= AV_CPU_FLAG_MMX;
+        if (std_caps & (1<<25))
+            rval |= AV_CPU_FLAG_MMX2
+#if HAVE_SSE
+                  | AV_CPU_FLAG_SSE;
+        if (std_caps & (1<<26))
+            rval |= AV_CPU_FLAG_SSE2;
+        if (ecx & 1)
+            rval |= AV_CPU_FLAG_SSE3;
+        if (ecx & 0x00000200 )
+            rval |= AV_CPU_FLAG_SSSE3;
+        if (ecx & 0x00080000 )
+            rval |= AV_CPU_FLAG_SSE4;
+        if (ecx & 0x00100000 )
+            rval |= AV_CPU_FLAG_SSE42;
+#if HAVE_AVX
+        /* Check OXSAVE and AVX bits */
+        if ((ecx & 0x18000000) == 0x18000000) {
+            /* Check for OS support */
+            xgetbv(0, eax, edx);
+            if ((eax & 0x6) == 0x6)
+                rval |= AV_CPU_FLAG_AVX;
+        }
+#endif
+#endif
+                  ;
+    }
+
+    cpuid(0x80000000, max_ext_level, ebx, ecx, edx);
+
+    if(max_ext_level >= 0x80000001){
+        cpuid(0x80000001, eax, ebx, ecx, ext_caps);
+        if (ext_caps & (1<<31))
+            rval |= AV_CPU_FLAG_3DNOW;
+        if (ext_caps & (1<<30))
+            rval |= AV_CPU_FLAG_3DNOWEXT;
+        if (ext_caps & (1<<23))
+            rval |= AV_CPU_FLAG_MMX;
+        if (ext_caps & (1<<22))
+            rval |= AV_CPU_FLAG_MMX2;
+
+        /* Allow for selectively disabling SSE2 functions on AMD processors
+           with SSE2 support but not SSE4a. This includes Athlon64, some
+           Opteron, and some Sempron processors. MMX, SSE, or 3DNow! are faster
+           than SSE2 often enough to utilize this special-case flag.
+           AV_CPU_FLAG_SSE2 and AV_CPU_FLAG_SSE2SLOW are both set in this case
+           so that SSE2 is used unless explicitly disabled by checking
+           AV_CPU_FLAG_SSE2SLOW. */
+        if (!strncmp(vendor.c, "AuthenticAMD", 12) &&
+            rval & AV_CPU_FLAG_SSE2 && !(ecx & 0x00000040)) {
+            rval |= AV_CPU_FLAG_SSE2SLOW;
+        }
+    }
+
+    if (!strncmp(vendor.c, "GenuineIntel", 12)) {
+        if (family == 6 && (model == 9 || model == 13 || model == 14)) {
+            /* 6/9 (pentium-m "banias"), 6/13 (pentium-m "dothan"), and 6/14 (core1 "yonah")
+            * theoretically support sse2, but it's usually slower than mmx,
+            * so let's just pretend they don't. AV_CPU_FLAG_SSE2 is disabled and
+            * AV_CPU_FLAG_SSE2SLOW is enabled so that SSE2 is not used unless
+            * explicitly enabled by checking AV_CPU_FLAG_SSE2SLOW. The same
+            * situation applies for AV_CPU_FLAG_SSE3 and AV_CPU_FLAG_SSE3SLOW. */
+            if (rval & AV_CPU_FLAG_SSE2) rval ^= AV_CPU_FLAG_SSE2SLOW|AV_CPU_FLAG_SSE2;
+            if (rval & AV_CPU_FLAG_SSE3) rval ^= AV_CPU_FLAG_SSE3SLOW|AV_CPU_FLAG_SSE3;
+        }
+        /* The Atom processor has SSSE3 support, which is useful in many cases,
+         * but sometimes the SSSE3 version is slower than the SSE2 equivalent
+         * on the Atom, but is generally faster on other processors supporting
+         * SSSE3. This flag allows for selectively disabling certain SSSE3
+         * functions on the Atom. */
+        if (family == 6 && model == 28)
+            rval |= AV_CPU_FLAG_ATOM;
+    }
+
+    return rval;
+}
diff --git a/libavutil/x86/intmath.h b/libavutil/x86/intmath.h
index f3acddc..a7e82b1 100644
--- a/libavutil/x86/intmath.h
+++ b/libavutil/x86/intmath.h
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2010 Mans Rullgard <mans at mansr.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavutil/x86/intreadwrite.h b/libavutil/x86/intreadwrite.h
index 4061d19..635096e 100644
--- a/libavutil/x86/intreadwrite.h
+++ b/libavutil/x86/intreadwrite.h
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2010 Alexander Strange <astrange at ithinksw.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavutil/x86/timer.h b/libavutil/x86/timer.h
index 62a111f..7f51816 100644
--- a/libavutil/x86/timer.h
+++ b/libavutil/x86/timer.h
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libavutil/x86_cpu.h b/libavutil/x86_cpu.h
index 08d3146..f84eba6 100644
--- a/libavutil/x86_cpu.h
+++ b/libavutil/x86_cpu.h
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,6 +25,7 @@
 #include "config.h"
 
 #if ARCH_X86_64
+#    define OPSIZE "q"
 #    define REG_a "rax"
 #    define REG_b "rbx"
 #    define REG_c "rcx"
@@ -45,6 +46,7 @@ typedef int64_t x86_reg;
 
 #elif ARCH_X86_32
 
+#    define OPSIZE "l"
 #    define REG_a "eax"
 #    define REG_b "ebx"
 #    define REG_c "ecx"
@@ -73,4 +75,24 @@ typedef int x86_reg;
 #    define BROKEN_RELOCATIONS 1
 #endif
 
+/*
+ * If gcc is not set to support sse (-msse) it will not accept xmm registers
+ * in the clobber list for inline asm. XMM_CLOBBERS takes a list of xmm
+ * registers to be marked as clobbered and evaluates to nothing if they are
+ * not supported, or to the list itself if they are supported. Since a clobber
+ * list may not be empty, XMM_CLOBBERS_ONLY should be used if the xmm
+ * registers are the only in the clobber list.
+ * For example a list with "eax" and "xmm0" as clobbers should become:
+ * : XMM_CLOBBERS("xmm0",) "eax"
+ * and a list with only "xmm0" should become:
+ * XMM_CLOBBERS_ONLY("xmm0")
+ */
+#if HAVE_XMM_CLOBBERS
+#    define XMM_CLOBBERS(...)        __VA_ARGS__
+#    define XMM_CLOBBERS_ONLY(...) : __VA_ARGS__
+#else
+#    define XMM_CLOBBERS(...)
+#    define XMM_CLOBBERS_ONLY(...)
+#endif
+
 #endif /* AVUTIL_X86_CPU_H */
diff --git a/libpostproc/postprocess.c b/libpostproc/postprocess.c
index 92c822b..73ffcb4 100644
--- a/libpostproc/postprocess.c
+++ b/libpostproc/postprocess.c
@@ -3,20 +3,20 @@
  *
  * AltiVec optimizations (C) 2004 Romain Dolbeau <romain at dolbeau.org>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or modify
+ * Libav is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
  * the Free Software Foundation; either version 2 of the License, or
  * (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
- * along with FFmpeg; if not, write to the Free Software
+ * along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -71,7 +71,7 @@ try to unroll inner for(x=0 ... loop to avoid these damn if(x ... checks
 ...
 */
 
-//Changelog: use the Subversion log
+//Changelog: use git log
 
 #include "config.h"
 #include "libavutil/avutil.h"
@@ -94,13 +94,13 @@ unsigned postproc_version(void)
 
 const char *postproc_configuration(void)
 {
-    return FFMPEG_CONFIGURATION;
+    return LIBAV_CONFIGURATION;
 }
 
 const char *postproc_license(void)
 {
 #define LICENSE_PREFIX "libpostproc license: "
-    return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1;
+    return LICENSE_PREFIX LIBAV_LICENSE + sizeof(LICENSE_PREFIX) - 1;
 }
 
 #if HAVE_ALTIVEC_H
diff --git a/libpostproc/postprocess.h b/libpostproc/postprocess.h
index 4cfcf7c..9e74589 100644
--- a/libpostproc/postprocess.h
+++ b/libpostproc/postprocess.h
@@ -1,20 +1,20 @@
 /*
  * Copyright (C) 2001-2003 Michael Niedermayer (michaelni at gmx.at)
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or modify
+ * Libav is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
  * the Free Software Foundation; either version 2 of the License, or
  * (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
- * along with FFmpeg; if not, write to the Free Software
+ * along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -29,8 +29,8 @@
 
 #include "libavutil/avutil.h"
 
-#define LIBPOSTPROC_VERSION_MAJOR 51
-#define LIBPOSTPROC_VERSION_MINOR  2
+#define LIBPOSTPROC_VERSION_MAJOR 52
+#define LIBPOSTPROC_VERSION_MINOR  0
 #define LIBPOSTPROC_VERSION_MICRO  0
 
 #define LIBPOSTPROC_VERSION_INT AV_VERSION_INT(LIBPOSTPROC_VERSION_MAJOR, \
@@ -44,17 +44,17 @@
 #define LIBPOSTPROC_IDENT       "postproc" AV_STRINGIFY(LIBPOSTPROC_VERSION)
 
 /**
- * Returns the LIBPOSTPROC_VERSION_INT constant.
+ * Return the LIBPOSTPROC_VERSION_INT constant.
  */
 unsigned postproc_version(void);
 
 /**
- * Returns the libpostproc build-time configuration.
+ * Return the libpostproc build-time configuration.
  */
 const char *postproc_configuration(void);
 
 /**
- * Returns the libpostproc license.
+ * Return the libpostproc license.
  */
 const char *postproc_license(void);
 
diff --git a/libpostproc/postprocess_altivec_template.c b/libpostproc/postprocess_altivec_template.c
index c5851d9..56d7b16 100644
--- a/libpostproc/postprocess_altivec_template.c
+++ b/libpostproc/postprocess_altivec_template.c
@@ -3,20 +3,20 @@
  *
  * based on code by Copyright (C) 2001-2003 Michael Niedermayer (michaelni at gmx.at)
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or modify
+ * Libav is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
  * the Free Software Foundation; either version 2 of the License, or
  * (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
- * along with FFmpeg; if not, write to the Free Software
+ * along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -62,10 +62,11 @@ static inline int vertClassify_altivec(uint8_t src[], int stride, PPContext *c)
     vector by assuming (stride % 16) == 0, unfortunately
     this is not always true.
     */
+    short data_0 = ((c->nonBQP*c->ppMode.baseDcDiff)>>8) + 1;
     DECLARE_ALIGNED(16, short, data)[8] =
                     {
-                        ((c->nonBQP*c->ppMode.baseDcDiff)>>8) + 1,
-                        data[0] * 2 + 1,
+                        data_0,
+                        data_0 * 2 + 1,
                         c->QP * 2,
                         c->QP * 4
                     };
diff --git a/libpostproc/postprocess_internal.h b/libpostproc/postprocess_internal.h
index 3bc51c4..010e629 100644
--- a/libpostproc/postprocess_internal.h
+++ b/libpostproc/postprocess_internal.h
@@ -1,20 +1,20 @@
 /*
  * Copyright (C) 2001-2002 Michael Niedermayer (michaelni at gmx.at)
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or modify
+ * Libav is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
  * the Free Software Foundation; either version 2 of the License, or
  * (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
- * along with FFmpeg; if not, write to the Free Software
+ * along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libpostproc/postprocess_template.c b/libpostproc/postprocess_template.c
index 637ebc6..3b6d0f8 100644
--- a/libpostproc/postprocess_template.c
+++ b/libpostproc/postprocess_template.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (C) 2001-2002 Michael Niedermayer (michaelni at gmx.at)
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or modify
+ * Libav is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
  * the Free Software Foundation; either version 2 of the License, or
  * (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
- * along with FFmpeg; if not, write to the Free Software
+ * along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -1390,7 +1390,7 @@ DERING_CORE((%0, %1, 8)    ,(%%REGd, %1, 4),%%mm2,%%mm4,%%mm0,%%mm3,%%mm5,%%mm1,
 #endif //HAVE_ALTIVEC
 
 /**
- * Deinterlaces the given block by linearly interpolating every second line.
+ * Deinterlace the given block by linearly interpolating every second line.
  * will be called for every 8x8 block and can read & write from line 4-15
  * lines 0-3 have been passed through the deblock / dering filters already, but can be read, too.
  * lines 4-12 will be read into the deblocking filter and should be deinterlaced
@@ -1442,7 +1442,7 @@ static inline void RENAME(deInterlaceInterpolateLinear)(uint8_t src[], int strid
 }
 
 /**
- * Deinterlaces the given block by cubic interpolating every second line.
+ * Deinterlace the given block by cubic interpolating every second line.
  * will be called for every 8x8 block and can read & write from line 4-15
  * lines 0-3 have been passed through the deblock / dering filters already, but can be read, too.
  * lines 4-12 will be read into the deblocking filter and should be deinterlaced
@@ -1506,7 +1506,7 @@ DEINT_CUBIC((%%REGd, %1), (%0, %1, 8) , (%%REGd, %1, 4), (%%REGc)    , (%%REGc,
 }
 
 /**
- * Deinterlaces the given block by filtering every second line with a (-1 4 2 4 -1) filter.
+ * Deinterlace the given block by filtering every second line with a (-1 4 2 4 -1) filter.
  * will be called for every 8x8 block and can read & write from line 4-15
  * lines 0-3 have been passed through the deblock / dering filters already, but can be read, too.
  * lines 4-12 will be read into the deblocking filter and should be deinterlaced
@@ -1585,7 +1585,7 @@ DEINT_FF((%%REGd, %1), (%%REGd, %1, 2), (%0, %1, 8) , (%%REGd, %1, 4))
 }
 
 /**
- * Deinterlaces the given block by filtering every line with a (-1 2 6 2 -1) filter.
+ * Deinterlace the given block by filtering every line with a (-1 2 6 2 -1) filter.
  * will be called for every 8x8 block and can read & write from line 4-15
  * lines 0-3 have been passed through the deblock / dering filters already, but can be read, too.
  * lines 4-12 will be read into the deblocking filter and should be deinterlaced
@@ -1686,7 +1686,7 @@ DEINT_L5(%%mm1, %%mm0, (%%REGd, %1, 2), (%0, %1, 8)    , (%%REGd, %1, 4))
 }
 
 /**
- * Deinterlaces the given block by filtering all lines with a (1 2 1) filter.
+ * Deinterlace the given block by filtering all lines with a (1 2 1) filter.
  * will be called for every 8x8 block and can read & write from line 4-15
  * lines 0-3 have been passed through the deblock / dering filters already, but can be read, too.
  * lines 4-12 will be read into the deblocking filter and should be deinterlaced
@@ -1788,7 +1788,7 @@ static inline void RENAME(deInterlaceBlendLinear)(uint8_t src[], int stride, uin
 }
 
 /**
- * Deinterlaces the given block by applying a median filter to every second line.
+ * Deinterlace the given block by applying a median filter to every second line.
  * will be called for every 8x8 block and can read & write from line 4-15,
  * lines 0-3 have been passed through the deblock / dering filters already, but can be read, too.
  * lines 4-12 will be read into the deblocking filter and should be deinterlaced
@@ -3006,7 +3006,7 @@ static void RENAME(postProcess)(const uint8_t src[], int srcStride, uint8_t dst[
                                 const QP_STORE_T QPs[], int QPStride, int isColor, PPContext *c);
 
 /**
- * Copies a block from src to dst and fixes the blacklevel.
+ * Copy a block from src to dst and fixes the blacklevel.
  * levelFix == 0 -> do not touch the brighness & contrast
  */
 #undef REAL_SCALED_CPY
@@ -3138,7 +3138,7 @@ SIMPLE_CPY((%%REGa, %2), (%%REGa, %2, 2), (%%REGd, %3), (%%REGd, %3, 2))
 }
 
 /**
- * Duplicates the given 8 src pixels ? times upward
+ * Duplicate the given 8 src pixels ? times upward
  */
 static inline void RENAME(duplicate)(uint8_t src[], int stride)
 {
@@ -3163,7 +3163,7 @@ static inline void RENAME(duplicate)(uint8_t src[], int stride)
 }
 
 /**
- * Filters array of bytes (Y or U or V values)
+ * Filter array of bytes (Y or U or V values)
  */
 static void RENAME(postProcess)(const uint8_t src[], int srcStride, uint8_t dst[], int dstStride, int width, int height,
                                 const QP_STORE_T QPs[], int QPStride, int isColor, PPContext *c2)
diff --git a/libswscale/Makefile b/libswscale/Makefile
index 6976079..7f8f721 100644
--- a/libswscale/Makefile
+++ b/libswscale/Makefile
@@ -12,7 +12,8 @@ OBJS-$(ARCH_BFIN)          +=  bfin/internal_bfin.o     \
                                bfin/yuv2rgb_bfin.o
 OBJS-$(CONFIG_MLIB)        +=  mlib/yuv2rgb_mlib.o
 OBJS-$(HAVE_ALTIVEC)       +=  ppc/yuv2rgb_altivec.o
-OBJS-$(HAVE_MMX)           +=  x86/yuv2rgb_mmx.o
+OBJS-$(HAVE_MMX)           +=  x86/rgb2rgb.o            \
+                               x86/yuv2rgb_mmx.o
 OBJS-$(HAVE_VIS)           +=  sparc/yuv2rgb_vis.o
 
 TESTPROGS = colorspace swscale
diff --git a/libswscale/bfin/internal_bfin.S b/libswscale/bfin/internal_bfin.S
index 5af4654..dea2321 100644
--- a/libswscale/bfin/internal_bfin.S
+++ b/libswscale/bfin/internal_bfin.S
@@ -5,20 +5,20 @@
  * Blackfin video color space converter operations
  * convert I420 YV12 to RGB in various formats
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libswscale/bfin/swscale_bfin.c b/libswscale/bfin/swscale_bfin.c
index ce2f172..fa3c03b 100644
--- a/libswscale/bfin/swscale_bfin.c
+++ b/libswscale/bfin/swscale_bfin.c
@@ -3,20 +3,20 @@
  *
  * Blackfin software video scaler operations
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libswscale/bfin/yuv2rgb_bfin.c b/libswscale/bfin/yuv2rgb_bfin.c
index eaa83ea..68af522 100644
--- a/libswscale/bfin/yuv2rgb_bfin.c
+++ b/libswscale/bfin/yuv2rgb_bfin.c
@@ -4,20 +4,20 @@
  * Blackfin video color space converter operations
  * convert I420 YV12 to RGB in various formats
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libswscale/colorspace-test.c b/libswscale/colorspace-test.c
index 5a48065..4e7116f 100644
--- a/libswscale/colorspace-test.c
+++ b/libswscale/colorspace-test.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (C) 2002 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -108,7 +108,7 @@ int main(int argc, char **argv)
             FUNC(4, 2, rgb32tobgr15),
             FUNC(4, 2, rgb32tobgr16),
             FUNC(4, 3, rgb32tobgr24),
-            FUNC(4, 4, rgb32tobgr32),
+            FUNC(4, 4, shuffle_bytes_2103), /* rgb32tobgr32 */
             FUNC(0, 0, NULL)
         };
         int width;
diff --git a/libswscale/mlib/yuv2rgb_mlib.c b/libswscale/mlib/yuv2rgb_mlib.c
index 011b0ef..526c975 100644
--- a/libswscale/mlib/yuv2rgb_mlib.c
+++ b/libswscale/mlib/yuv2rgb_mlib.c
@@ -3,20 +3,20 @@
  *
  * Copyright (C) 2003 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -29,6 +29,7 @@
 #include <assert.h>
 
 #include "libswscale/swscale.h"
+#include "libswscale/swscale_internal.h"
 
 static int mlib_YUV2ARGB420_32(SwsContext *c, uint8_t* src[], int srcStride[], int srcSliceY,
                                int srcSliceH, uint8_t* dst[], int dstStride[])
diff --git a/libswscale/options.c b/libswscale/options.c
index 75564cb..59b9994 100644
--- a/libswscale/options.c
+++ b/libswscale/options.c
@@ -1,24 +1,25 @@
 /*
  * Copyright (C) 2001-2003 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "libavutil/avutil.h"
+#include "libavutil/pixfmt.h"
 #include "libavcodec/opt.h"
 #include "swscale.h"
 #include "swscale_internal.h"
@@ -49,12 +50,25 @@ static const AVOption options[] = {
     { "accurate_rnd", "accurate rounding", 0, FF_OPT_TYPE_CONST, SWS_ACCURATE_RND, INT_MIN, INT_MAX, VE, "sws_flags" },
     { "mmx", "MMX SIMD acceleration", 0, FF_OPT_TYPE_CONST, SWS_CPU_CAPS_MMX, INT_MIN, INT_MAX, VE, "sws_flags" },
     { "mmx2", "MMX2 SIMD acceleration", 0, FF_OPT_TYPE_CONST, SWS_CPU_CAPS_MMX2, INT_MIN, INT_MAX, VE, "sws_flags" },
+    { "sse2", "SSE2 SIMD acceleration", 0, FF_OPT_TYPE_CONST, SWS_CPU_CAPS_SSE2, INT_MIN, INT_MAX, VE, "sws_flags" },
     { "3dnow", "3DNOW SIMD acceleration", 0, FF_OPT_TYPE_CONST, SWS_CPU_CAPS_3DNOW, INT_MIN, INT_MAX, VE, "sws_flags" },
     { "altivec", "AltiVec SIMD acceleration", 0, FF_OPT_TYPE_CONST, SWS_CPU_CAPS_ALTIVEC, INT_MIN, INT_MAX, VE, "sws_flags" },
     { "bfin", "Blackfin SIMD acceleration", 0, FF_OPT_TYPE_CONST, SWS_CPU_CAPS_BFIN, INT_MIN, INT_MAX, VE, "sws_flags" },
     { "full_chroma_int", "full chroma interpolation", 0 , FF_OPT_TYPE_CONST, SWS_FULL_CHR_H_INT, INT_MIN, INT_MAX, VE, "sws_flags" },
     { "full_chroma_inp", "full chroma input", 0 , FF_OPT_TYPE_CONST, SWS_FULL_CHR_H_INP, INT_MIN, INT_MAX, VE, "sws_flags" },
     { "bitexact", "", 0 , FF_OPT_TYPE_CONST, SWS_BITEXACT, INT_MIN, INT_MAX, VE, "sws_flags" },
+
+    { "srcw", "source width"      , OFFSET(srcW), FF_OPT_TYPE_INT, 16, 1, INT_MAX, VE },
+    { "srch", "source height"     , OFFSET(srcH), FF_OPT_TYPE_INT, 16, 1, INT_MAX, VE },
+    { "dstw", "destination width" , OFFSET(dstW), FF_OPT_TYPE_INT, 16, 1, INT_MAX, VE },
+    { "dsth", "destination height", OFFSET(dstH), FF_OPT_TYPE_INT, 16, 1, INT_MAX, VE },
+    { "src_format", "source format"     , OFFSET(srcFormat), FF_OPT_TYPE_INT, DEFAULT, 0, PIX_FMT_NB-1, VE },
+    { "dst_format", "destination format", OFFSET(dstFormat), FF_OPT_TYPE_INT, DEFAULT, 0, PIX_FMT_NB-1, VE },
+    { "src_range" , "source range"      , OFFSET(srcRange) , FF_OPT_TYPE_INT, DEFAULT, 0, 1, VE },
+    { "dst_range" , "destination range" , OFFSET(dstRange) , FF_OPT_TYPE_INT, DEFAULT, 0, 1, VE },
+    { "param0" , "scaler param 0" , OFFSET(param[0]) , FF_OPT_TYPE_DOUBLE, SWS_PARAM_DEFAULT, INT_MIN, INT_MAX, VE },
+    { "param1" , "scaler param 1" , OFFSET(param[1]) , FF_OPT_TYPE_DOUBLE, SWS_PARAM_DEFAULT, INT_MIN, INT_MAX, VE },
+
     { NULL }
 };
 
diff --git a/libswscale/ppc/swscale_altivec_template.c b/libswscale/ppc/swscale_altivec_template.c
index a438e4c..b123f70 100644
--- a/libswscale/ppc/swscale_altivec_template.c
+++ b/libswscale/ppc/swscale_altivec_template.c
@@ -4,20 +4,20 @@
  * Copyright (C) 2004 Romain Dolbeau <romain at dolbeau.org>
  * based on the equivalent C code in swscale.c
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -86,8 +86,8 @@ altivec_packIntArrayToCharArray(int *val, uint8_t* dest, int dstW)
 }
 
 static inline void
-yuv2yuvX_altivec_real(const int16_t *lumFilter, int16_t **lumSrc, int lumFilterSize,
-                      const int16_t *chrFilter, int16_t **chrSrc, int chrFilterSize,
+yuv2yuvX_altivec_real(const int16_t *lumFilter, const int16_t **lumSrc, int lumFilterSize,
+                      const int16_t *chrFilter, const int16_t **chrSrc, int chrFilterSize,
                       uint8_t *dest, uint8_t *uDest, uint8_t *vDest, int dstW, int chrDstW)
 {
     const vector signed int vini = {(1 << 18), (1 << 18), (1 << 18), (1 << 18)};
@@ -389,14 +389,14 @@ static inline void hScale_altivec_real(int16_t *dst, int dstW,
     }
 }
 
-static inline int yv12toyuy2_unscaled_altivec(SwsContext *c, uint8_t* src[], int srcStride[], int srcSliceY,
+static inline int yv12toyuy2_unscaled_altivec(SwsContext *c, const uint8_t* src[], int srcStride[], int srcSliceY,
                                               int srcSliceH, uint8_t* dstParam[], int dstStride_a[])
 {
     uint8_t *dst=dstParam[0] + dstStride_a[0]*srcSliceY;
     // yv12toyuy2(src[0], src[1], src[2], dst, c->srcW, srcSliceH, srcStride[0], srcStride[1], dstStride[0]);
-    uint8_t *ysrc = src[0];
-    uint8_t *usrc = src[1];
-    uint8_t *vsrc = src[2];
+    const uint8_t *ysrc = src[0];
+    const uint8_t *usrc = src[1];
+    const uint8_t *vsrc = src[2];
     const int width = c->srcW;
     const int height = srcSliceH;
     const int lumStride = srcStride[0];
@@ -467,14 +467,14 @@ static inline int yv12toyuy2_unscaled_altivec(SwsContext *c, uint8_t* src[], int
     return srcSliceH;
 }
 
-static inline int yv12touyvy_unscaled_altivec(SwsContext *c, uint8_t* src[], int srcStride[], int srcSliceY,
+static inline int yv12touyvy_unscaled_altivec(SwsContext *c, const uint8_t* src[], int srcStride[], int srcSliceY,
                                               int srcSliceH, uint8_t* dstParam[], int dstStride_a[])
 {
     uint8_t *dst=dstParam[0] + dstStride_a[0]*srcSliceY;
     // yv12toyuy2(src[0], src[1], src[2], dst, c->srcW, srcSliceH, srcStride[0], srcStride[1], dstStride[0]);
-    uint8_t *ysrc = src[0];
-    uint8_t *usrc = src[1];
-    uint8_t *vsrc = src[2];
+    const uint8_t *ysrc = src[0];
+    const uint8_t *usrc = src[1];
+    const uint8_t *vsrc = src[2];
     const int width = c->srcW;
     const int height = srcSliceH;
     const int lumStride = srcStride[0];
diff --git a/libswscale/ppc/swscale_template.c b/libswscale/ppc/swscale_template.c
new file mode 100644
index 0000000..3e40c3f
--- /dev/null
+++ b/libswscale/ppc/swscale_template.c
@@ -0,0 +1,903 @@
+/*
+ * Copyright (C) 2001-2003 Michael Niedermayer <michaelni at gmx.at>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+
+#if COMPILE_TEMPLATE_ALTIVEC
+#include "swscale_altivec_template.c"
+#endif
+
+static inline void RENAME(yuv2yuvX)(SwsContext *c, const int16_t *lumFilter, const int16_t **lumSrc, int lumFilterSize,
+                                    const int16_t *chrFilter, const int16_t **chrSrc, int chrFilterSize, const int16_t **alpSrc,
+                                    uint8_t *dest, uint8_t *uDest, uint8_t *vDest, uint8_t *aDest, long dstW, long chrDstW)
+{
+#if COMPILE_TEMPLATE_ALTIVEC
+    yuv2yuvX_altivec_real(lumFilter, lumSrc, lumFilterSize,
+                          chrFilter, chrSrc, chrFilterSize,
+                          dest, uDest, vDest, dstW, chrDstW);
+#else //COMPILE_TEMPLATE_ALTIVEC
+    yuv2yuvXinC(lumFilter, lumSrc, lumFilterSize,
+                chrFilter, chrSrc, chrFilterSize,
+                alpSrc, dest, uDest, vDest, aDest, dstW, chrDstW);
+#endif //!COMPILE_TEMPLATE_ALTIVEC
+}
+
+static inline void RENAME(yuv2nv12X)(SwsContext *c, const int16_t *lumFilter, const int16_t **lumSrc, int lumFilterSize,
+                                     const int16_t *chrFilter, const int16_t **chrSrc, int chrFilterSize,
+                                     uint8_t *dest, uint8_t *uDest, int dstW, int chrDstW, enum PixelFormat dstFormat)
+{
+    yuv2nv12XinC(lumFilter, lumSrc, lumFilterSize,
+                 chrFilter, chrSrc, chrFilterSize,
+                 dest, uDest, dstW, chrDstW, dstFormat);
+}
+
+static inline void RENAME(yuv2yuv1)(SwsContext *c, const int16_t *lumSrc, const int16_t *chrSrc, const int16_t *alpSrc,
+                                    uint8_t *dest, uint8_t *uDest, uint8_t *vDest, uint8_t *aDest, long dstW, long chrDstW)
+{
+    int i;
+    for (i=0; i<dstW; i++) {
+        int val= (lumSrc[i]+64)>>7;
+
+        if (val&256) {
+            if (val<0) val=0;
+            else       val=255;
+        }
+
+        dest[i]= val;
+    }
+
+    if (uDest)
+        for (i=0; i<chrDstW; i++) {
+            int u=(chrSrc[i       ]+64)>>7;
+            int v=(chrSrc[i + VOFW]+64)>>7;
+
+            if ((u|v)&256) {
+                if (u<0)        u=0;
+                else if (u>255) u=255;
+                if (v<0)        v=0;
+                else if (v>255) v=255;
+            }
+
+            uDest[i]= u;
+            vDest[i]= v;
+        }
+
+    if (CONFIG_SWSCALE_ALPHA && aDest)
+        for (i=0; i<dstW; i++) {
+            int val= (alpSrc[i]+64)>>7;
+            aDest[i]= av_clip_uint8(val);
+        }
+}
+
+
+/**
+ * vertical scale YV12 to RGB
+ */
+static inline void RENAME(yuv2packedX)(SwsContext *c, const int16_t *lumFilter, const int16_t **lumSrc, int lumFilterSize,
+                                       const int16_t *chrFilter, const int16_t **chrSrc, int chrFilterSize,
+                                       const int16_t **alpSrc, uint8_t *dest, long dstW, long dstY)
+{
+#if COMPILE_TEMPLATE_ALTIVEC
+    /* The following list of supported dstFormat values should
+       match what's found in the body of ff_yuv2packedX_altivec() */
+    if (!(c->flags & SWS_BITEXACT) && !c->alpPixBuf &&
+         (c->dstFormat==PIX_FMT_ABGR  || c->dstFormat==PIX_FMT_BGRA  ||
+          c->dstFormat==PIX_FMT_BGR24 || c->dstFormat==PIX_FMT_RGB24 ||
+          c->dstFormat==PIX_FMT_RGBA  || c->dstFormat==PIX_FMT_ARGB))
+            ff_yuv2packedX_altivec(c, lumFilter, lumSrc, lumFilterSize,
+                                   chrFilter, chrSrc, chrFilterSize,
+                                   dest, dstW, dstY);
+    else
+#endif
+        yuv2packedXinC(c, lumFilter, lumSrc, lumFilterSize,
+                       chrFilter, chrSrc, chrFilterSize,
+                       alpSrc, dest, dstW, dstY);
+}
+
+/**
+ * vertical bilinear scale YV12 to RGB
+ */
+static inline void RENAME(yuv2packed2)(SwsContext *c, const uint16_t *buf0, const uint16_t *buf1, const uint16_t *uvbuf0, const uint16_t *uvbuf1,
+                          const uint16_t *abuf0, const uint16_t *abuf1, uint8_t *dest, int dstW, int yalpha, int uvalpha, int y)
+{
+    int  yalpha1=4095- yalpha;
+    int uvalpha1=4095-uvalpha;
+    int i;
+
+    YSCALE_YUV_2_ANYRGB_C(YSCALE_YUV_2_RGB2_C, YSCALE_YUV_2_PACKED2_C(void,0), YSCALE_YUV_2_GRAY16_2_C, YSCALE_YUV_2_MONO2_C)
+}
+
+/**
+ * YV12 to RGB without scaling or interpolating
+ */
+static inline void RENAME(yuv2packed1)(SwsContext *c, const uint16_t *buf0, const uint16_t *uvbuf0, const uint16_t *uvbuf1,
+                          const uint16_t *abuf0, uint8_t *dest, int dstW, int uvalpha, enum PixelFormat dstFormat, int flags, int y)
+{
+    const int yalpha1=0;
+    int i;
+
+    const uint16_t *buf1= buf0; //FIXME needed for RGB1/BGR1
+    const int yalpha= 4096; //FIXME ...
+
+    if (flags&SWS_FULL_CHR_H_INT) {
+        c->yuv2packed2(c, buf0, buf0, uvbuf0, uvbuf1, abuf0, abuf0, dest, dstW, 0, uvalpha, y);
+        return;
+    }
+
+    if (uvalpha < 2048) {
+        YSCALE_YUV_2_ANYRGB_C(YSCALE_YUV_2_RGB1_C, YSCALE_YUV_2_PACKED1_C(void,0), YSCALE_YUV_2_GRAY16_1_C, YSCALE_YUV_2_MONO2_C)
+    } else {
+        YSCALE_YUV_2_ANYRGB_C(YSCALE_YUV_2_RGB1B_C, YSCALE_YUV_2_PACKED1B_C(void,0), YSCALE_YUV_2_GRAY16_1_C, YSCALE_YUV_2_MONO2_C)
+    }
+}
+
+//FIXME yuy2* can read up to 7 samples too much
+
+static inline void RENAME(yuy2ToY)(uint8_t *dst, const uint8_t *src, long width, uint32_t *unused)
+{
+    int i;
+    for (i=0; i<width; i++)
+        dst[i]= src[2*i];
+}
+
+static inline void RENAME(yuy2ToUV)(uint8_t *dstU, uint8_t *dstV, const uint8_t *src1, const uint8_t *src2, long width, uint32_t *unused)
+{
+    int i;
+    for (i=0; i<width; i++) {
+        dstU[i]= src1[4*i + 1];
+        dstV[i]= src1[4*i + 3];
+    }
+    assert(src1 == src2);
+}
+
+static inline void RENAME(LEToUV)(uint8_t *dstU, uint8_t *dstV, const uint8_t *src1, const uint8_t *src2, long width, uint32_t *unused)
+{
+    int i;
+    for (i=0; i<width; i++) {
+        dstU[i]= src1[2*i + 1];
+        dstV[i]= src2[2*i + 1];
+    }
+}
+
+/* This is almost identical to the previous, end exists only because
+ * yuy2ToY/UV)(dst, src+1, ...) would have 100% unaligned accesses. */
+static inline void RENAME(uyvyToY)(uint8_t *dst, const uint8_t *src, long width, uint32_t *unused)
+{
+    int i;
+    for (i=0; i<width; i++)
+        dst[i]= src[2*i+1];
+}
+
+static inline void RENAME(uyvyToUV)(uint8_t *dstU, uint8_t *dstV, const uint8_t *src1, const uint8_t *src2, long width, uint32_t *unused)
+{
+    int i;
+    for (i=0; i<width; i++) {
+        dstU[i]= src1[4*i + 0];
+        dstV[i]= src1[4*i + 2];
+    }
+    assert(src1 == src2);
+}
+
+static inline void RENAME(BEToUV)(uint8_t *dstU, uint8_t *dstV, const uint8_t *src1, const uint8_t *src2, long width, uint32_t *unused)
+{
+    int i;
+    for (i=0; i<width; i++) {
+        dstU[i]= src1[2*i];
+        dstV[i]= src2[2*i];
+    }
+}
+
+static inline void RENAME(nvXXtoUV)(uint8_t *dst1, uint8_t *dst2,
+                                    const uint8_t *src, long width)
+{
+    int i;
+    for (i = 0; i < width; i++) {
+        dst1[i] = src[2*i+0];
+        dst2[i] = src[2*i+1];
+    }
+}
+
+static inline void RENAME(nv12ToUV)(uint8_t *dstU, uint8_t *dstV,
+                                    const uint8_t *src1, const uint8_t *src2,
+                                    long width, uint32_t *unused)
+{
+    RENAME(nvXXtoUV)(dstU, dstV, src1, width);
+}
+
+static inline void RENAME(nv21ToUV)(uint8_t *dstU, uint8_t *dstV,
+                                    const uint8_t *src1, const uint8_t *src2,
+                                    long width, uint32_t *unused)
+{
+    RENAME(nvXXtoUV)(dstV, dstU, src1, width);
+}
+
+
+static inline void RENAME(bgr24ToY)(uint8_t *dst, const uint8_t *src, long width, uint32_t *unused)
+{
+    int i;
+    for (i=0; i<width; i++) {
+        int b= src[i*3+0];
+        int g= src[i*3+1];
+        int r= src[i*3+2];
+
+        dst[i]= ((RY*r + GY*g + BY*b + (33<<(RGB2YUV_SHIFT-1)))>>RGB2YUV_SHIFT);
+    }
+}
+
+static inline void RENAME(bgr24ToUV)(uint8_t *dstU, uint8_t *dstV, const uint8_t *src1, const uint8_t *src2, long width, uint32_t *unused)
+{
+    int i;
+    for (i=0; i<width; i++) {
+        int b= src1[3*i + 0];
+        int g= src1[3*i + 1];
+        int r= src1[3*i + 2];
+
+        dstU[i]= (RU*r + GU*g + BU*b + (257<<(RGB2YUV_SHIFT-1)))>>RGB2YUV_SHIFT;
+        dstV[i]= (RV*r + GV*g + BV*b + (257<<(RGB2YUV_SHIFT-1)))>>RGB2YUV_SHIFT;
+    }
+    assert(src1 == src2);
+}
+
+static inline void RENAME(bgr24ToUV_half)(uint8_t *dstU, uint8_t *dstV, const uint8_t *src1, const uint8_t *src2, long width, uint32_t *unused)
+{
+    int i;
+    for (i=0; i<width; i++) {
+        int b= src1[6*i + 0] + src1[6*i + 3];
+        int g= src1[6*i + 1] + src1[6*i + 4];
+        int r= src1[6*i + 2] + src1[6*i + 5];
+
+        dstU[i]= (RU*r + GU*g + BU*b + (257<<RGB2YUV_SHIFT))>>(RGB2YUV_SHIFT+1);
+        dstV[i]= (RV*r + GV*g + BV*b + (257<<RGB2YUV_SHIFT))>>(RGB2YUV_SHIFT+1);
+    }
+    assert(src1 == src2);
+}
+
+static inline void RENAME(rgb24ToY)(uint8_t *dst, const uint8_t *src, long width, uint32_t *unused)
+{
+    int i;
+    for (i=0; i<width; i++) {
+        int r= src[i*3+0];
+        int g= src[i*3+1];
+        int b= src[i*3+2];
+
+        dst[i]= ((RY*r + GY*g + BY*b + (33<<(RGB2YUV_SHIFT-1)))>>RGB2YUV_SHIFT);
+    }
+}
+
+static inline void RENAME(rgb24ToUV)(uint8_t *dstU, uint8_t *dstV, const uint8_t *src1, const uint8_t *src2, long width, uint32_t *unused)
+{
+    int i;
+    assert(src1==src2);
+    for (i=0; i<width; i++) {
+        int r= src1[3*i + 0];
+        int g= src1[3*i + 1];
+        int b= src1[3*i + 2];
+
+        dstU[i]= (RU*r + GU*g + BU*b + (257<<(RGB2YUV_SHIFT-1)))>>RGB2YUV_SHIFT;
+        dstV[i]= (RV*r + GV*g + BV*b + (257<<(RGB2YUV_SHIFT-1)))>>RGB2YUV_SHIFT;
+    }
+}
+
+static inline void RENAME(rgb24ToUV_half)(uint8_t *dstU, uint8_t *dstV, const uint8_t *src1, const uint8_t *src2, long width, uint32_t *unused)
+{
+    int i;
+    assert(src1==src2);
+    for (i=0; i<width; i++) {
+        int r= src1[6*i + 0] + src1[6*i + 3];
+        int g= src1[6*i + 1] + src1[6*i + 4];
+        int b= src1[6*i + 2] + src1[6*i + 5];
+
+        dstU[i]= (RU*r + GU*g + BU*b + (257<<RGB2YUV_SHIFT))>>(RGB2YUV_SHIFT+1);
+        dstV[i]= (RV*r + GV*g + BV*b + (257<<RGB2YUV_SHIFT))>>(RGB2YUV_SHIFT+1);
+    }
+}
+
+
+// bilinear / bicubic scaling
+static inline void RENAME(hScale)(int16_t *dst, int dstW, const uint8_t *src, int srcW, int xInc,
+                                  const int16_t *filter, const int16_t *filterPos, long filterSize)
+{
+#if COMPILE_TEMPLATE_ALTIVEC
+    hScale_altivec_real(dst, dstW, src, srcW, xInc, filter, filterPos, filterSize);
+#else
+    int i;
+    for (i=0; i<dstW; i++) {
+        int j;
+        int srcPos= filterPos[i];
+        int val=0;
+        //printf("filterPos: %d\n", filterPos[i]);
+        for (j=0; j<filterSize; j++) {
+            //printf("filter: %d, src: %d\n", filter[i], src[srcPos + j]);
+            val += ((int)src[srcPos + j])*filter[filterSize*i + j];
+        }
+        //filter += hFilterSize;
+        dst[i] = FFMIN(val>>7, (1<<15)-1); // the cubic equation does overflow ...
+        //dst[i] = val>>7;
+    }
+#endif /* COMPILE_TEMPLATE_ALTIVEC */
+}
+
+//FIXME all pal and rgb srcFormats could do this convertion as well
+//FIXME all scalers more complex than bilinear could do half of this transform
+static void RENAME(chrRangeToJpeg)(uint16_t *dst, int width)
+{
+    int i;
+    for (i = 0; i < width; i++) {
+        dst[i     ] = (FFMIN(dst[i     ],30775)*4663 - 9289992)>>12; //-264
+        dst[i+VOFW] = (FFMIN(dst[i+VOFW],30775)*4663 - 9289992)>>12; //-264
+    }
+}
+static void RENAME(chrRangeFromJpeg)(uint16_t *dst, int width)
+{
+    int i;
+    for (i = 0; i < width; i++) {
+        dst[i     ] = (dst[i     ]*1799 + 4081085)>>11; //1469
+        dst[i+VOFW] = (dst[i+VOFW]*1799 + 4081085)>>11; //1469
+    }
+}
+static void RENAME(lumRangeToJpeg)(uint16_t *dst, int width)
+{
+    int i;
+    for (i = 0; i < width; i++)
+        dst[i] = (FFMIN(dst[i],30189)*19077 - 39057361)>>14;
+}
+static void RENAME(lumRangeFromJpeg)(uint16_t *dst, int width)
+{
+    int i;
+    for (i = 0; i < width; i++)
+        dst[i] = (dst[i]*14071 + 33561947)>>14;
+}
+
+static inline void RENAME(hyscale_fast)(SwsContext *c, int16_t *dst,
+                                        long dstWidth, const uint8_t *src, int srcW,
+                                        int xInc)
+{
+    int i;
+    unsigned int xpos=0;
+    for (i=0;i<dstWidth;i++) {
+        register unsigned int xx=xpos>>16;
+        register unsigned int xalpha=(xpos&0xFFFF)>>9;
+        dst[i]= (src[xx]<<7) + (src[xx+1] - src[xx])*xalpha;
+        xpos+=xInc;
+    }
+}
+
+      // *** horizontal scale Y line to temp buffer
+static inline void RENAME(hyscale)(SwsContext *c, uint16_t *dst, long dstWidth, const uint8_t *src, int srcW, int xInc,
+                                   const int16_t *hLumFilter,
+                                   const int16_t *hLumFilterPos, int hLumFilterSize,
+                                   uint8_t *formatConvBuffer,
+                                   uint32_t *pal, int isAlpha)
+{
+    void (*toYV12)(uint8_t *, const uint8_t *, long, uint32_t *) = isAlpha ? c->alpToYV12 : c->lumToYV12;
+    void (*convertRange)(uint16_t *, int) = isAlpha ? NULL : c->lumConvertRange;
+
+    src += isAlpha ? c->alpSrcOffset : c->lumSrcOffset;
+
+    if (toYV12) {
+        toYV12(formatConvBuffer, src, srcW, pal);
+        src= formatConvBuffer;
+    }
+
+    if (!c->hyscale_fast) {
+        c->hScale(dst, dstWidth, src, srcW, xInc, hLumFilter, hLumFilterPos, hLumFilterSize);
+    } else { // fast bilinear upscale / crap downscale
+        c->hyscale_fast(c, dst, dstWidth, src, srcW, xInc);
+    }
+
+    if (convertRange)
+        convertRange(dst, dstWidth);
+}
+
+static inline void RENAME(hcscale_fast)(SwsContext *c, int16_t *dst,
+                                        long dstWidth, const uint8_t *src1,
+                                        const uint8_t *src2, int srcW, int xInc)
+{
+    int i;
+    unsigned int xpos=0;
+    for (i=0;i<dstWidth;i++) {
+        register unsigned int xx=xpos>>16;
+        register unsigned int xalpha=(xpos&0xFFFF)>>9;
+        dst[i]=(src1[xx]*(xalpha^127)+src1[xx+1]*xalpha);
+        dst[i+VOFW]=(src2[xx]*(xalpha^127)+src2[xx+1]*xalpha);
+        /* slower
+        dst[i]= (src1[xx]<<7) + (src1[xx+1] - src1[xx])*xalpha;
+        dst[i+VOFW]=(src2[xx]<<7) + (src2[xx+1] - src2[xx])*xalpha;
+        */
+        xpos+=xInc;
+    }
+}
+
+inline static void RENAME(hcscale)(SwsContext *c, uint16_t *dst, long dstWidth, const uint8_t *src1, const uint8_t *src2,
+                                   int srcW, int xInc, const int16_t *hChrFilter,
+                                   const int16_t *hChrFilterPos, int hChrFilterSize,
+                                   uint8_t *formatConvBuffer,
+                                   uint32_t *pal)
+{
+
+    src1 += c->chrSrcOffset;
+    src2 += c->chrSrcOffset;
+
+    if (c->chrToYV12) {
+        c->chrToYV12(formatConvBuffer, formatConvBuffer+VOFW, src1, src2, srcW, pal);
+        src1= formatConvBuffer;
+        src2= formatConvBuffer+VOFW;
+    }
+
+    if (!c->hcscale_fast) {
+        c->hScale(dst     , dstWidth, src1, srcW, xInc, hChrFilter, hChrFilterPos, hChrFilterSize);
+        c->hScale(dst+VOFW, dstWidth, src2, srcW, xInc, hChrFilter, hChrFilterPos, hChrFilterSize);
+    } else { // fast bilinear upscale / crap downscale
+        c->hcscale_fast(c, dst, dstWidth, src1, src2, srcW, xInc);
+    }
+
+    if (c->chrConvertRange)
+        c->chrConvertRange(dst, dstWidth);
+}
+
+#define DEBUG_SWSCALE_BUFFERS 0
+#define DEBUG_BUFFERS(...) if (DEBUG_SWSCALE_BUFFERS) av_log(c, AV_LOG_DEBUG, __VA_ARGS__)
+
+static int RENAME(swScale)(SwsContext *c, const uint8_t* src[], int srcStride[], int srcSliceY,
+                           int srcSliceH, uint8_t* dst[], int dstStride[])
+{
+    /* load a few things into local vars to make the code more readable? and faster */
+    const int srcW= c->srcW;
+    const int dstW= c->dstW;
+    const int dstH= c->dstH;
+    const int chrDstW= c->chrDstW;
+    const int chrSrcW= c->chrSrcW;
+    const int lumXInc= c->lumXInc;
+    const int chrXInc= c->chrXInc;
+    const enum PixelFormat dstFormat= c->dstFormat;
+    const int flags= c->flags;
+    int16_t *vLumFilterPos= c->vLumFilterPos;
+    int16_t *vChrFilterPos= c->vChrFilterPos;
+    int16_t *hLumFilterPos= c->hLumFilterPos;
+    int16_t *hChrFilterPos= c->hChrFilterPos;
+    int16_t *vLumFilter= c->vLumFilter;
+    int16_t *vChrFilter= c->vChrFilter;
+    int16_t *hLumFilter= c->hLumFilter;
+    int16_t *hChrFilter= c->hChrFilter;
+    int32_t *lumMmxFilter= c->lumMmxFilter;
+    int32_t *chrMmxFilter= c->chrMmxFilter;
+    int32_t av_unused *alpMmxFilter= c->alpMmxFilter;
+    const int vLumFilterSize= c->vLumFilterSize;
+    const int vChrFilterSize= c->vChrFilterSize;
+    const int hLumFilterSize= c->hLumFilterSize;
+    const int hChrFilterSize= c->hChrFilterSize;
+    int16_t **lumPixBuf= c->lumPixBuf;
+    int16_t **chrPixBuf= c->chrPixBuf;
+    int16_t **alpPixBuf= c->alpPixBuf;
+    const int vLumBufSize= c->vLumBufSize;
+    const int vChrBufSize= c->vChrBufSize;
+    uint8_t *formatConvBuffer= c->formatConvBuffer;
+    const int chrSrcSliceY= srcSliceY >> c->chrSrcVSubSample;
+    const int chrSrcSliceH= -((-srcSliceH) >> c->chrSrcVSubSample);
+    int lastDstY;
+    uint32_t *pal=c->pal_yuv;
+
+    /* vars which will change and which we need to store back in the context */
+    int dstY= c->dstY;
+    int lumBufIndex= c->lumBufIndex;
+    int chrBufIndex= c->chrBufIndex;
+    int lastInLumBuf= c->lastInLumBuf;
+    int lastInChrBuf= c->lastInChrBuf;
+
+    if (isPacked(c->srcFormat)) {
+        src[0]=
+        src[1]=
+        src[2]=
+        src[3]= src[0];
+        srcStride[0]=
+        srcStride[1]=
+        srcStride[2]=
+        srcStride[3]= srcStride[0];
+    }
+    srcStride[1]<<= c->vChrDrop;
+    srcStride[2]<<= c->vChrDrop;
+
+    DEBUG_BUFFERS("swScale() %p[%d] %p[%d] %p[%d] %p[%d] -> %p[%d] %p[%d] %p[%d] %p[%d]\n",
+                  src[0], srcStride[0], src[1], srcStride[1], src[2], srcStride[2], src[3], srcStride[3],
+                  dst[0], dstStride[0], dst[1], dstStride[1], dst[2], dstStride[2], dst[3], dstStride[3]);
+    DEBUG_BUFFERS("srcSliceY: %d srcSliceH: %d dstY: %d dstH: %d\n",
+                   srcSliceY,    srcSliceH,    dstY,    dstH);
+    DEBUG_BUFFERS("vLumFilterSize: %d vLumBufSize: %d vChrFilterSize: %d vChrBufSize: %d\n",
+                   vLumFilterSize,    vLumBufSize,    vChrFilterSize,    vChrBufSize);
+
+    if (dstStride[0]%8 !=0 || dstStride[1]%8 !=0 || dstStride[2]%8 !=0 || dstStride[3]%8 != 0) {
+        static int warnedAlready=0; //FIXME move this into the context perhaps
+        if (flags & SWS_PRINT_INFO && !warnedAlready) {
+            av_log(c, AV_LOG_WARNING, "Warning: dstStride is not aligned!\n"
+                   "         ->cannot do aligned memory accesses anymore\n");
+            warnedAlready=1;
+        }
+    }
+
+    /* Note the user might start scaling the picture in the middle so this
+       will not get executed. This is not really intended but works
+       currently, so people might do it. */
+    if (srcSliceY ==0) {
+        lumBufIndex=-1;
+        chrBufIndex=-1;
+        dstY=0;
+        lastInLumBuf= -1;
+        lastInChrBuf= -1;
+    }
+
+    lastDstY= dstY;
+
+    for (;dstY < dstH; dstY++) {
+        unsigned char *dest =dst[0]+dstStride[0]*dstY;
+        const int chrDstY= dstY>>c->chrDstVSubSample;
+        unsigned char *uDest=dst[1]+dstStride[1]*chrDstY;
+        unsigned char *vDest=dst[2]+dstStride[2]*chrDstY;
+        unsigned char *aDest=(CONFIG_SWSCALE_ALPHA && alpPixBuf) ? dst[3]+dstStride[3]*dstY : NULL;
+
+        const int firstLumSrcY= vLumFilterPos[dstY]; //First line needed as input
+        const int firstLumSrcY2= vLumFilterPos[FFMIN(dstY | ((1<<c->chrDstVSubSample) - 1), dstH-1)];
+        const int firstChrSrcY= vChrFilterPos[chrDstY]; //First line needed as input
+        int lastLumSrcY= firstLumSrcY + vLumFilterSize -1; // Last line needed as input
+        int lastLumSrcY2=firstLumSrcY2+ vLumFilterSize -1; // Last line needed as input
+        int lastChrSrcY= firstChrSrcY + vChrFilterSize -1; // Last line needed as input
+        int enough_lines;
+
+        //handle holes (FAST_BILINEAR & weird filters)
+        if (firstLumSrcY > lastInLumBuf) lastInLumBuf= firstLumSrcY-1;
+        if (firstChrSrcY > lastInChrBuf) lastInChrBuf= firstChrSrcY-1;
+        assert(firstLumSrcY >= lastInLumBuf - vLumBufSize + 1);
+        assert(firstChrSrcY >= lastInChrBuf - vChrBufSize + 1);
+
+        DEBUG_BUFFERS("dstY: %d\n", dstY);
+        DEBUG_BUFFERS("\tfirstLumSrcY: %d lastLumSrcY: %d lastInLumBuf: %d\n",
+                         firstLumSrcY,    lastLumSrcY,    lastInLumBuf);
+        DEBUG_BUFFERS("\tfirstChrSrcY: %d lastChrSrcY: %d lastInChrBuf: %d\n",
+                         firstChrSrcY,    lastChrSrcY,    lastInChrBuf);
+
+        // Do we have enough lines in this slice to output the dstY line
+        enough_lines = lastLumSrcY2 < srcSliceY + srcSliceH && lastChrSrcY < -((-srcSliceY - srcSliceH)>>c->chrSrcVSubSample);
+
+        if (!enough_lines) {
+            lastLumSrcY = srcSliceY + srcSliceH - 1;
+            lastChrSrcY = chrSrcSliceY + chrSrcSliceH - 1;
+            DEBUG_BUFFERS("buffering slice: lastLumSrcY %d lastChrSrcY %d\n",
+                                            lastLumSrcY, lastChrSrcY);
+        }
+
+        //Do horizontal scaling
+        while(lastInLumBuf < lastLumSrcY) {
+            const uint8_t *src1= src[0]+(lastInLumBuf + 1 - srcSliceY)*srcStride[0];
+            const uint8_t *src2= src[3]+(lastInLumBuf + 1 - srcSliceY)*srcStride[3];
+            lumBufIndex++;
+            assert(lumBufIndex < 2*vLumBufSize);
+            assert(lastInLumBuf + 1 - srcSliceY < srcSliceH);
+            assert(lastInLumBuf + 1 - srcSliceY >= 0);
+            RENAME(hyscale)(c, lumPixBuf[ lumBufIndex ], dstW, src1, srcW, lumXInc,
+                            hLumFilter, hLumFilterPos, hLumFilterSize,
+                            formatConvBuffer,
+                            pal, 0);
+            if (CONFIG_SWSCALE_ALPHA && alpPixBuf)
+                RENAME(hyscale)(c, alpPixBuf[ lumBufIndex ], dstW, src2, srcW, lumXInc,
+                                hLumFilter, hLumFilterPos, hLumFilterSize,
+                                formatConvBuffer,
+                                pal, 1);
+            lastInLumBuf++;
+            DEBUG_BUFFERS("\t\tlumBufIndex %d: lastInLumBuf: %d\n",
+                               lumBufIndex,    lastInLumBuf);
+        }
+        while(lastInChrBuf < lastChrSrcY) {
+            const uint8_t *src1= src[1]+(lastInChrBuf + 1 - chrSrcSliceY)*srcStride[1];
+            const uint8_t *src2= src[2]+(lastInChrBuf + 1 - chrSrcSliceY)*srcStride[2];
+            chrBufIndex++;
+            assert(chrBufIndex < 2*vChrBufSize);
+            assert(lastInChrBuf + 1 - chrSrcSliceY < (chrSrcSliceH));
+            assert(lastInChrBuf + 1 - chrSrcSliceY >= 0);
+            //FIXME replace parameters through context struct (some at least)
+
+            if (c->needs_hcscale)
+                RENAME(hcscale)(c, chrPixBuf[ chrBufIndex ], chrDstW, src1, src2, chrSrcW, chrXInc,
+                                hChrFilter, hChrFilterPos, hChrFilterSize,
+                                formatConvBuffer,
+                                pal);
+            lastInChrBuf++;
+            DEBUG_BUFFERS("\t\tchrBufIndex %d: lastInChrBuf: %d\n",
+                               chrBufIndex,    lastInChrBuf);
+        }
+        //wrap buf index around to stay inside the ring buffer
+        if (lumBufIndex >= vLumBufSize) lumBufIndex-= vLumBufSize;
+        if (chrBufIndex >= vChrBufSize) chrBufIndex-= vChrBufSize;
+        if (!enough_lines)
+            break; //we can't output a dstY line so let's try with the next slice
+
+        if (dstY < dstH-2) {
+            const int16_t **lumSrcPtr= (const int16_t **) lumPixBuf + lumBufIndex + firstLumSrcY - lastInLumBuf + vLumBufSize;
+            const int16_t **chrSrcPtr= (const int16_t **) chrPixBuf + chrBufIndex + firstChrSrcY - lastInChrBuf + vChrBufSize;
+            const int16_t **alpSrcPtr= (CONFIG_SWSCALE_ALPHA && alpPixBuf) ? (const int16_t **) alpPixBuf + lumBufIndex + firstLumSrcY - lastInLumBuf + vLumBufSize : NULL;
+            if (dstFormat == PIX_FMT_NV12 || dstFormat == PIX_FMT_NV21) {
+                const int chrSkipMask= (1<<c->chrDstVSubSample)-1;
+                if (dstY&chrSkipMask) uDest= NULL; //FIXME split functions in lumi / chromi
+                c->yuv2nv12X(c,
+                             vLumFilter+dstY*vLumFilterSize   , lumSrcPtr, vLumFilterSize,
+                             vChrFilter+chrDstY*vChrFilterSize, chrSrcPtr, vChrFilterSize,
+                             dest, uDest, dstW, chrDstW, dstFormat);
+            } else if (isPlanarYUV(dstFormat) || dstFormat==PIX_FMT_GRAY8) { //YV12 like
+                const int chrSkipMask= (1<<c->chrDstVSubSample)-1;
+                if ((dstY&chrSkipMask) || isGray(dstFormat)) uDest=vDest= NULL; //FIXME split functions in lumi / chromi
+                if (is16BPS(dstFormat)) {
+                    yuv2yuvX16inC(
+                                  vLumFilter+dstY*vLumFilterSize   , lumSrcPtr, vLumFilterSize,
+                                  vChrFilter+chrDstY*vChrFilterSize, chrSrcPtr, vChrFilterSize,
+                                  alpSrcPtr, (uint16_t *) dest, (uint16_t *) uDest, (uint16_t *) vDest, (uint16_t *) aDest, dstW, chrDstW,
+                                  dstFormat);
+                } else if (vLumFilterSize == 1 && vChrFilterSize == 1) { // unscaled YV12
+                    const int16_t *lumBuf = lumSrcPtr[0];
+                    const int16_t *chrBuf= chrSrcPtr[0];
+                    const int16_t *alpBuf= (CONFIG_SWSCALE_ALPHA && alpPixBuf) ? alpSrcPtr[0] : NULL;
+                    c->yuv2yuv1(c, lumBuf, chrBuf, alpBuf, dest, uDest, vDest, aDest, dstW, chrDstW);
+                } else { //General YV12
+                    c->yuv2yuvX(c,
+                                vLumFilter+dstY*vLumFilterSize   , lumSrcPtr, vLumFilterSize,
+                                vChrFilter+chrDstY*vChrFilterSize, chrSrcPtr, vChrFilterSize,
+                                alpSrcPtr, dest, uDest, vDest, aDest, dstW, chrDstW);
+                }
+            } else {
+                assert(lumSrcPtr + vLumFilterSize - 1 < lumPixBuf + vLumBufSize*2);
+                assert(chrSrcPtr + vChrFilterSize - 1 < chrPixBuf + vChrBufSize*2);
+                if (vLumFilterSize == 1 && vChrFilterSize == 2) { //unscaled RGB
+                    int chrAlpha= vChrFilter[2*dstY+1];
+                    if(flags & SWS_FULL_CHR_H_INT) {
+                        yuv2rgbXinC_full(c, //FIXME write a packed1_full function
+                                         vLumFilter+dstY*vLumFilterSize, lumSrcPtr, vLumFilterSize,
+                                         vChrFilter+dstY*vChrFilterSize, chrSrcPtr, vChrFilterSize,
+                                         alpSrcPtr, dest, dstW, dstY);
+                    } else {
+                        c->yuv2packed1(c, *lumSrcPtr, *chrSrcPtr, *(chrSrcPtr+1),
+                                       alpPixBuf ? *alpSrcPtr : NULL,
+                                       dest, dstW, chrAlpha, dstFormat, flags, dstY);
+                    }
+                } else if (vLumFilterSize == 2 && vChrFilterSize == 2) { //bilinear upscale RGB
+                    int lumAlpha= vLumFilter[2*dstY+1];
+                    int chrAlpha= vChrFilter[2*dstY+1];
+                    lumMmxFilter[2]=
+                    lumMmxFilter[3]= vLumFilter[2*dstY   ]*0x10001;
+                    chrMmxFilter[2]=
+                    chrMmxFilter[3]= vChrFilter[2*chrDstY]*0x10001;
+                    if(flags & SWS_FULL_CHR_H_INT) {
+                        yuv2rgbXinC_full(c, //FIXME write a packed2_full function
+                                         vLumFilter+dstY*vLumFilterSize, lumSrcPtr, vLumFilterSize,
+                                         vChrFilter+dstY*vChrFilterSize, chrSrcPtr, vChrFilterSize,
+                                         alpSrcPtr, dest, dstW, dstY);
+                    } else {
+                        c->yuv2packed2(c, *lumSrcPtr, *(lumSrcPtr+1), *chrSrcPtr, *(chrSrcPtr+1),
+                                       alpPixBuf ? *alpSrcPtr : NULL, alpPixBuf ? *(alpSrcPtr+1) : NULL,
+                                       dest, dstW, lumAlpha, chrAlpha, dstY);
+                    }
+                } else { //general RGB
+                    if(flags & SWS_FULL_CHR_H_INT) {
+                        yuv2rgbXinC_full(c,
+                                         vLumFilter+dstY*vLumFilterSize, lumSrcPtr, vLumFilterSize,
+                                         vChrFilter+dstY*vChrFilterSize, chrSrcPtr, vChrFilterSize,
+                                         alpSrcPtr, dest, dstW, dstY);
+                    } else {
+                        c->yuv2packedX(c,
+                                       vLumFilter+dstY*vLumFilterSize, lumSrcPtr, vLumFilterSize,
+                                       vChrFilter+dstY*vChrFilterSize, chrSrcPtr, vChrFilterSize,
+                                       alpSrcPtr, dest, dstW, dstY);
+                    }
+                }
+            }
+        } else { // hmm looks like we can't use MMX here without overwriting this array's tail
+            const int16_t **lumSrcPtr= (const int16_t **)lumPixBuf + lumBufIndex + firstLumSrcY - lastInLumBuf + vLumBufSize;
+            const int16_t **chrSrcPtr= (const int16_t **)chrPixBuf + chrBufIndex + firstChrSrcY - lastInChrBuf + vChrBufSize;
+            const int16_t **alpSrcPtr= (CONFIG_SWSCALE_ALPHA && alpPixBuf) ? (const int16_t **)alpPixBuf + lumBufIndex + firstLumSrcY - lastInLumBuf + vLumBufSize : NULL;
+            if (dstFormat == PIX_FMT_NV12 || dstFormat == PIX_FMT_NV21) {
+                const int chrSkipMask= (1<<c->chrDstVSubSample)-1;
+                if (dstY&chrSkipMask) uDest= NULL; //FIXME split functions in lumi / chromi
+                yuv2nv12XinC(
+                             vLumFilter+dstY*vLumFilterSize   , lumSrcPtr, vLumFilterSize,
+                             vChrFilter+chrDstY*vChrFilterSize, chrSrcPtr, vChrFilterSize,
+                             dest, uDest, dstW, chrDstW, dstFormat);
+            } else if (isPlanarYUV(dstFormat) || dstFormat==PIX_FMT_GRAY8) { //YV12
+                const int chrSkipMask= (1<<c->chrDstVSubSample)-1;
+                if ((dstY&chrSkipMask) || isGray(dstFormat)) uDest=vDest= NULL; //FIXME split functions in lumi / chromi
+                if (is16BPS(dstFormat)) {
+                    yuv2yuvX16inC(
+                                  vLumFilter+dstY*vLumFilterSize   , lumSrcPtr, vLumFilterSize,
+                                  vChrFilter+chrDstY*vChrFilterSize, chrSrcPtr, vChrFilterSize,
+                                  alpSrcPtr, (uint16_t *) dest, (uint16_t *) uDest, (uint16_t *) vDest, (uint16_t *) aDest, dstW, chrDstW,
+                                  dstFormat);
+                } else {
+                    yuv2yuvXinC(
+                                vLumFilter+dstY*vLumFilterSize   , lumSrcPtr, vLumFilterSize,
+                                vChrFilter+chrDstY*vChrFilterSize, chrSrcPtr, vChrFilterSize,
+                                alpSrcPtr, dest, uDest, vDest, aDest, dstW, chrDstW);
+                }
+            } else {
+                assert(lumSrcPtr + vLumFilterSize - 1 < lumPixBuf + vLumBufSize*2);
+                assert(chrSrcPtr + vChrFilterSize - 1 < chrPixBuf + vChrBufSize*2);
+                if(flags & SWS_FULL_CHR_H_INT) {
+                    yuv2rgbXinC_full(c,
+                                     vLumFilter+dstY*vLumFilterSize, lumSrcPtr, vLumFilterSize,
+                                     vChrFilter+dstY*vChrFilterSize, chrSrcPtr, vChrFilterSize,
+                                     alpSrcPtr, dest, dstW, dstY);
+                } else {
+                    yuv2packedXinC(c,
+                                   vLumFilter+dstY*vLumFilterSize, lumSrcPtr, vLumFilterSize,
+                                   vChrFilter+dstY*vChrFilterSize, chrSrcPtr, vChrFilterSize,
+                                   alpSrcPtr, dest, dstW, dstY);
+                }
+            }
+        }
+    }
+
+    if ((dstFormat == PIX_FMT_YUVA420P) && !alpPixBuf)
+        fillPlane(dst[3], dstStride[3], dstW, dstY-lastDstY, lastDstY, 255);
+
+    /* store changed local vars back in the context */
+    c->dstY= dstY;
+    c->lumBufIndex= lumBufIndex;
+    c->chrBufIndex= chrBufIndex;
+    c->lastInLumBuf= lastInLumBuf;
+    c->lastInChrBuf= lastInChrBuf;
+
+    return dstY - lastDstY;
+}
+
+static void RENAME(sws_init_swScale)(SwsContext *c)
+{
+    enum PixelFormat srcFormat = c->srcFormat;
+
+    c->yuv2nv12X    = RENAME(yuv2nv12X   );
+    c->yuv2yuv1     = RENAME(yuv2yuv1    );
+    c->yuv2yuvX     = RENAME(yuv2yuvX    );
+    c->yuv2packed1  = RENAME(yuv2packed1 );
+    c->yuv2packed2  = RENAME(yuv2packed2 );
+    c->yuv2packedX  = RENAME(yuv2packedX );
+
+    c->hScale       = RENAME(hScale      );
+
+    if (c->flags & SWS_FAST_BILINEAR)
+    {
+        c->hyscale_fast = RENAME(hyscale_fast);
+        c->hcscale_fast = RENAME(hcscale_fast);
+    }
+
+    c->chrToYV12 = NULL;
+    switch(srcFormat) {
+        case PIX_FMT_YUYV422  : c->chrToYV12 = RENAME(yuy2ToUV); break;
+        case PIX_FMT_UYVY422  : c->chrToYV12 = RENAME(uyvyToUV); break;
+        case PIX_FMT_NV12     : c->chrToYV12 = RENAME(nv12ToUV); break;
+        case PIX_FMT_NV21     : c->chrToYV12 = RENAME(nv21ToUV); break;
+        case PIX_FMT_RGB8     :
+        case PIX_FMT_BGR8     :
+        case PIX_FMT_PAL8     :
+        case PIX_FMT_BGR4_BYTE:
+        case PIX_FMT_RGB4_BYTE: c->chrToYV12 = palToUV; break;
+        case PIX_FMT_YUV420P16BE:
+        case PIX_FMT_YUV422P16BE:
+        case PIX_FMT_YUV444P16BE: c->chrToYV12 = RENAME(BEToUV); break;
+        case PIX_FMT_YUV420P16LE:
+        case PIX_FMT_YUV422P16LE:
+        case PIX_FMT_YUV444P16LE: c->chrToYV12 = RENAME(LEToUV); break;
+    }
+    if (c->chrSrcHSubSample) {
+        switch(srcFormat) {
+        case PIX_FMT_RGB48BE:
+        case PIX_FMT_RGB48LE: c->chrToYV12 = rgb48ToUV_half; break;
+        case PIX_FMT_RGB32  : c->chrToYV12 = bgr32ToUV_half;  break;
+        case PIX_FMT_RGB32_1: c->chrToYV12 = bgr321ToUV_half; break;
+        case PIX_FMT_BGR24  : c->chrToYV12 = RENAME(bgr24ToUV_half); break;
+        case PIX_FMT_BGR565 : c->chrToYV12 = bgr16ToUV_half; break;
+        case PIX_FMT_BGR555 : c->chrToYV12 = bgr15ToUV_half; break;
+        case PIX_FMT_BGR32  : c->chrToYV12 = rgb32ToUV_half;  break;
+        case PIX_FMT_BGR32_1: c->chrToYV12 = rgb321ToUV_half; break;
+        case PIX_FMT_RGB24  : c->chrToYV12 = RENAME(rgb24ToUV_half); break;
+        case PIX_FMT_RGB565 : c->chrToYV12 = rgb16ToUV_half; break;
+        case PIX_FMT_RGB555 : c->chrToYV12 = rgb15ToUV_half; break;
+        }
+    } else {
+        switch(srcFormat) {
+        case PIX_FMT_RGB48BE:
+        case PIX_FMT_RGB48LE: c->chrToYV12 = rgb48ToUV; break;
+        case PIX_FMT_RGB32  : c->chrToYV12 = bgr32ToUV;  break;
+        case PIX_FMT_RGB32_1: c->chrToYV12 = bgr321ToUV; break;
+        case PIX_FMT_BGR24  : c->chrToYV12 = RENAME(bgr24ToUV); break;
+        case PIX_FMT_BGR565 : c->chrToYV12 = bgr16ToUV; break;
+        case PIX_FMT_BGR555 : c->chrToYV12 = bgr15ToUV; break;
+        case PIX_FMT_BGR32  : c->chrToYV12 = rgb32ToUV;  break;
+        case PIX_FMT_BGR32_1: c->chrToYV12 = rgb321ToUV; break;
+        case PIX_FMT_RGB24  : c->chrToYV12 = RENAME(rgb24ToUV); break;
+        case PIX_FMT_RGB565 : c->chrToYV12 = rgb16ToUV; break;
+        case PIX_FMT_RGB555 : c->chrToYV12 = rgb15ToUV; break;
+        }
+    }
+
+    c->lumToYV12 = NULL;
+    c->alpToYV12 = NULL;
+    switch (srcFormat) {
+    case PIX_FMT_YUYV422  :
+    case PIX_FMT_YUV420P16BE:
+    case PIX_FMT_YUV422P16BE:
+    case PIX_FMT_YUV444P16BE:
+    case PIX_FMT_Y400A    :
+    case PIX_FMT_GRAY16BE : c->lumToYV12 = RENAME(yuy2ToY); break;
+    case PIX_FMT_UYVY422  :
+    case PIX_FMT_YUV420P16LE:
+    case PIX_FMT_YUV422P16LE:
+    case PIX_FMT_YUV444P16LE:
+    case PIX_FMT_GRAY16LE : c->lumToYV12 = RENAME(uyvyToY); break;
+    case PIX_FMT_BGR24    : c->lumToYV12 = RENAME(bgr24ToY); break;
+    case PIX_FMT_BGR565   : c->lumToYV12 = bgr16ToY; break;
+    case PIX_FMT_BGR555   : c->lumToYV12 = bgr15ToY; break;
+    case PIX_FMT_RGB24    : c->lumToYV12 = RENAME(rgb24ToY); break;
+    case PIX_FMT_RGB565   : c->lumToYV12 = rgb16ToY; break;
+    case PIX_FMT_RGB555   : c->lumToYV12 = rgb15ToY; break;
+    case PIX_FMT_RGB8     :
+    case PIX_FMT_BGR8     :
+    case PIX_FMT_PAL8     :
+    case PIX_FMT_BGR4_BYTE:
+    case PIX_FMT_RGB4_BYTE: c->lumToYV12 = palToY; break;
+    case PIX_FMT_MONOBLACK: c->lumToYV12 = monoblack2Y; break;
+    case PIX_FMT_MONOWHITE: c->lumToYV12 = monowhite2Y; break;
+    case PIX_FMT_RGB32  : c->lumToYV12 = bgr32ToY;  break;
+    case PIX_FMT_RGB32_1: c->lumToYV12 = bgr321ToY; break;
+    case PIX_FMT_BGR32  : c->lumToYV12 = rgb32ToY;  break;
+    case PIX_FMT_BGR32_1: c->lumToYV12 = rgb321ToY; break;
+    case PIX_FMT_RGB48BE:
+    case PIX_FMT_RGB48LE: c->lumToYV12 = rgb48ToY; break;
+    }
+    if (c->alpPixBuf) {
+        switch (srcFormat) {
+        case PIX_FMT_RGB32  :
+        case PIX_FMT_RGB32_1:
+        case PIX_FMT_BGR32  :
+        case PIX_FMT_BGR32_1: c->alpToYV12 = abgrToA; break;
+        case PIX_FMT_Y400A  : c->alpToYV12 = RENAME(yuy2ToY); break;
+        }
+    }
+
+    switch (srcFormat) {
+    case PIX_FMT_Y400A  :
+        c->alpSrcOffset = 1;
+        break;
+    case PIX_FMT_RGB32  :
+    case PIX_FMT_BGR32  :
+        c->alpSrcOffset = 3;
+        break;
+    case PIX_FMT_RGB48LE:
+        c->lumSrcOffset = 1;
+        c->chrSrcOffset = 1;
+        c->alpSrcOffset = 1;
+        break;
+    }
+
+    if (c->srcRange != c->dstRange && !isAnyRGB(c->dstFormat)) {
+        if (c->srcRange) {
+            c->lumConvertRange = RENAME(lumRangeFromJpeg);
+            c->chrConvertRange = RENAME(chrRangeFromJpeg);
+        } else {
+            c->lumConvertRange = RENAME(lumRangeToJpeg);
+            c->chrConvertRange = RENAME(chrRangeToJpeg);
+        }
+    }
+
+    if (!(isGray(srcFormat) || isGray(c->dstFormat) ||
+          srcFormat == PIX_FMT_MONOBLACK || srcFormat == PIX_FMT_MONOWHITE))
+        c->needs_hcscale = 1;
+}
diff --git a/libswscale/ppc/yuv2rgb_altivec.c b/libswscale/ppc/yuv2rgb_altivec.c
index be26647..0113c8d 100644
--- a/libswscale/ppc/yuv2rgb_altivec.c
+++ b/libswscale/ppc/yuv2rgb_altivec.c
@@ -3,20 +3,20 @@
  *
  * copyright (C) 2004 Marc Hoffman <marc.hoffman at analog.com>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -275,7 +275,7 @@ static inline void cvtyuvtoRGB (SwsContext *c,
 
 #define DEFCSP420_CVT(name,out_pixels)                                  \
 static int altivec_##name (SwsContext *c,                               \
-                           unsigned char **in, int *instrides,          \
+                           const unsigned char **in, int *instrides,    \
                            int srcSliceY,        int srcSliceH,         \
                            unsigned char **oplanes, int *outstrides)    \
 {                                                                       \
@@ -309,10 +309,10 @@ static int altivec_##name (SwsContext *c,                               \
                                                                         \
     vector unsigned short lCSHIFT = c->CSHIFT;                          \
                                                                         \
-    ubyte *y1i   = in[0];                                               \
-    ubyte *y2i   = in[0]+instrides[0];                                  \
-    ubyte *ui    = in[1];                                               \
-    ubyte *vi    = in[2];                                               \
+    const ubyte *y1i   = in[0];                                         \
+    const ubyte *y2i   = in[0]+instrides[0];                            \
+    const ubyte *ui    = in[1];                                         \
+    const ubyte *vi    = in[2];                                         \
                                                                         \
     vector unsigned char *oute                                          \
         = (vector unsigned char *)                                      \
@@ -626,7 +626,7 @@ const vector unsigned char
   this is so I can play live CCIR raw video
 */
 static int altivec_uyvy_rgb32 (SwsContext *c,
-                               unsigned char **in, int *instrides,
+                               const unsigned char **in, int *instrides,
                                int srcSliceY,        int srcSliceH,
                                unsigned char **oplanes, int *outstrides)
 {
@@ -638,7 +638,7 @@ static int altivec_uyvy_rgb32 (SwsContext *c,
     vector signed   short R0,G0,B0,R1,G1,B1;
     vector unsigned char  R,G,B;
     vector unsigned char *out;
-    ubyte *img;
+    const ubyte *img;
 
     img = in[0];
     out = (vector unsigned char *)(oplanes[0]+srcSliceY*outstrides[0]);
@@ -778,8 +778,8 @@ void ff_yuv2rgb_init_tables_altivec(SwsContext *c, const int inv_table[4], int b
 
 void
 ff_yuv2packedX_altivec(SwsContext *c,
-                       const int16_t *lumFilter, int16_t **lumSrc, int lumFilterSize,
-                       const int16_t *chrFilter, int16_t **chrSrc, int chrFilterSize,
+                       const int16_t *lumFilter, const int16_t **lumSrc, int lumFilterSize,
+                       const int16_t *chrFilter, const int16_t **chrSrc, int chrFilterSize,
                      uint8_t *dest, int dstW, int dstY)
 {
     int i,j;
diff --git a/libswscale/rgb2rgb.c b/libswscale/rgb2rgb.c
index b506b12..12d6287 100644
--- a/libswscale/rgb2rgb.c
+++ b/libswscale/rgb2rgb.c
@@ -6,32 +6,29 @@
  * Written by Nick Kurshev.
  * palette & YUV & runtime CPU stuff by Michael (michaelni at gmx.at)
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #include <inttypes.h>
 #include "config.h"
-#include "libavutil/x86_cpu.h"
 #include "libavutil/bswap.h"
 #include "rgb2rgb.h"
 #include "swscale.h"
 #include "swscale_internal.h"
 
-#define FAST_BGR2YV12 // use 7-bit instead of 15-bit coefficients
-
 void (*rgb24tobgr32)(const uint8_t *src, uint8_t *dst, long src_size);
 void (*rgb24tobgr16)(const uint8_t *src, uint8_t *dst, long src_size);
 void (*rgb24tobgr15)(const uint8_t *src, uint8_t *dst, long src_size);
@@ -47,7 +44,7 @@ void (*rgb16to32)(const uint8_t *src, uint8_t *dst, long src_size);
 void (*rgb24tobgr24)(const uint8_t *src, uint8_t *dst, long src_size);
 void (*rgb24to16)(const uint8_t *src, uint8_t *dst, long src_size);
 void (*rgb24to15)(const uint8_t *src, uint8_t *dst, long src_size);
-void (*rgb32tobgr32)(const uint8_t *src, uint8_t *dst, long src_size);
+void (*shuffle_bytes_2103)(const uint8_t *src, uint8_t *dst, long src_size);
 void (*rgb32tobgr16)(const uint8_t *src, uint8_t *dst, long src_size);
 void (*rgb32tobgr15)(const uint8_t *src, uint8_t *dst, long src_size);
 
@@ -97,44 +94,6 @@ void (*yuyvtoyuv422)(uint8_t *ydst, uint8_t *udst, uint8_t *vdst, const uint8_t
                      long width, long height,
                      long lumStride, long chromStride, long srcStride);
 
-
-#if ARCH_X86
-DECLARE_ASM_CONST(8, uint64_t, mmx_null)     = 0x0000000000000000ULL;
-DECLARE_ASM_CONST(8, uint64_t, mmx_one)      = 0xFFFFFFFFFFFFFFFFULL;
-DECLARE_ASM_CONST(8, uint64_t, mask32b)      = 0x000000FF000000FFULL;
-DECLARE_ASM_CONST(8, uint64_t, mask32g)      = 0x0000FF000000FF00ULL;
-DECLARE_ASM_CONST(8, uint64_t, mask32r)      = 0x00FF000000FF0000ULL;
-DECLARE_ASM_CONST(8, uint64_t, mask32a)      = 0xFF000000FF000000ULL;
-DECLARE_ASM_CONST(8, uint64_t, mask32)       = 0x00FFFFFF00FFFFFFULL;
-DECLARE_ASM_CONST(8, uint64_t, mask3216br)   = 0x00F800F800F800F8ULL;
-DECLARE_ASM_CONST(8, uint64_t, mask3216g)    = 0x0000FC000000FC00ULL;
-DECLARE_ASM_CONST(8, uint64_t, mask3215g)    = 0x0000F8000000F800ULL;
-DECLARE_ASM_CONST(8, uint64_t, mul3216)      = 0x2000000420000004ULL;
-DECLARE_ASM_CONST(8, uint64_t, mul3215)      = 0x2000000820000008ULL;
-DECLARE_ASM_CONST(8, uint64_t, mask24b)      = 0x00FF0000FF0000FFULL;
-DECLARE_ASM_CONST(8, uint64_t, mask24g)      = 0xFF0000FF0000FF00ULL;
-DECLARE_ASM_CONST(8, uint64_t, mask24r)      = 0x0000FF0000FF0000ULL;
-DECLARE_ASM_CONST(8, uint64_t, mask24l)      = 0x0000000000FFFFFFULL;
-DECLARE_ASM_CONST(8, uint64_t, mask24h)      = 0x0000FFFFFF000000ULL;
-DECLARE_ASM_CONST(8, uint64_t, mask24hh)     = 0xffff000000000000ULL;
-DECLARE_ASM_CONST(8, uint64_t, mask24hhh)    = 0xffffffff00000000ULL;
-DECLARE_ASM_CONST(8, uint64_t, mask24hhhh)   = 0xffffffffffff0000ULL;
-DECLARE_ASM_CONST(8, uint64_t, mask15b)      = 0x001F001F001F001FULL; /* 00000000 00011111  xxB */
-DECLARE_ASM_CONST(8, uint64_t, mask15rg)     = 0x7FE07FE07FE07FE0ULL; /* 01111111 11100000  RGx */
-DECLARE_ASM_CONST(8, uint64_t, mask15s)      = 0xFFE0FFE0FFE0FFE0ULL;
-DECLARE_ASM_CONST(8, uint64_t, mask15g)      = 0x03E003E003E003E0ULL;
-DECLARE_ASM_CONST(8, uint64_t, mask15r)      = 0x7C007C007C007C00ULL;
-#define mask16b mask15b
-DECLARE_ASM_CONST(8, uint64_t, mask16g)      = 0x07E007E007E007E0ULL;
-DECLARE_ASM_CONST(8, uint64_t, mask16r)      = 0xF800F800F800F800ULL;
-DECLARE_ASM_CONST(8, uint64_t, red_16mask)   = 0x0000f8000000f800ULL;
-DECLARE_ASM_CONST(8, uint64_t, green_16mask) = 0x000007e0000007e0ULL;
-DECLARE_ASM_CONST(8, uint64_t, blue_16mask)  = 0x0000001f0000001fULL;
-DECLARE_ASM_CONST(8, uint64_t, red_15mask)   = 0x00007c0000007c00ULL;
-DECLARE_ASM_CONST(8, uint64_t, green_15mask) = 0x000003e0000003e0ULL;
-DECLARE_ASM_CONST(8, uint64_t, blue_15mask)  = 0x0000001f0000001fULL;
-#endif /* ARCH_X86 */
-
 #define RGB2YUV_SHIFT 8
 #define BY ((int)( 0.098*(1<<RGB2YUV_SHIFT)+0.5))
 #define BV ((int)(-0.071*(1<<RGB2YUV_SHIFT)+0.5))
@@ -146,45 +105,9 @@ DECLARE_ASM_CONST(8, uint64_t, blue_15mask)  = 0x0000001f0000001fULL;
 #define RV ((int)( 0.439*(1<<RGB2YUV_SHIFT)+0.5))
 #define RU ((int)(-0.148*(1<<RGB2YUV_SHIFT)+0.5))
 
-//Note: We have C, MMX, MMX2, 3DNOW versions, there is no 3DNOW + MMX2 one.
 //plain C versions
-#undef HAVE_MMX
-#undef HAVE_MMX2
-#undef HAVE_AMD3DNOW
-#undef HAVE_SSE2
-#define HAVE_MMX 0
-#define HAVE_MMX2 0
-#define HAVE_AMD3DNOW 0
-#define HAVE_SSE2 0
-#define RENAME(a) a ## _C
 #include "rgb2rgb_template.c"
 
-#if ARCH_X86
-
-//MMX versions
-#undef RENAME
-#undef HAVE_MMX
-#define HAVE_MMX 1
-#define RENAME(a) a ## _MMX
-#include "rgb2rgb_template.c"
-
-//MMX2 versions
-#undef RENAME
-#undef HAVE_MMX2
-#define HAVE_MMX2 1
-#define RENAME(a) a ## _MMX2
-#include "rgb2rgb_template.c"
-
-//3DNOW versions
-#undef RENAME
-#undef HAVE_MMX2
-#undef HAVE_AMD3DNOW
-#define HAVE_MMX2 0
-#define HAVE_AMD3DNOW 1
-#define RENAME(a) a ## _3DNOW
-#include "rgb2rgb_template.c"
-
-#endif //ARCH_X86 || ARCH_X86_64
 
 /*
  RGB15->RGB16 original by Strepto/Astral
@@ -195,16 +118,10 @@ DECLARE_ASM_CONST(8, uint64_t, blue_15mask)  = 0x0000001f0000001fULL;
 
 void sws_rgb2rgb_init(int flags)
 {
+    rgb2rgb_init_c();
 #if HAVE_MMX2 || HAVE_AMD3DNOW || HAVE_MMX
-    if (flags & SWS_CPU_CAPS_MMX2)
-        rgb2rgb_init_MMX2();
-    else if (flags & SWS_CPU_CAPS_3DNOW)
-        rgb2rgb_init_3DNOW();
-    else if (flags & SWS_CPU_CAPS_MMX)
-        rgb2rgb_init_MMX();
-    else
+    rgb2rgb_init_x86(flags);
 #endif /* HAVE_MMX2 || HAVE_AMD3DNOW || HAVE_MMX */
-        rgb2rgb_init_C();
 }
 
 #if LIBSWSCALE_VERSION_MAJOR < 1
@@ -231,9 +148,8 @@ void palette8tobgr16(const uint8_t *src, uint8_t *dst, long num_pixels, const ui
 {
     long i;
     for (i=0; i<num_pixels; i++)
-        ((uint16_t *)dst)[i] = bswap_16(((const uint16_t *)palette)[src[i]]);
+        ((uint16_t *)dst)[i] = av_bswap16(((const uint16_t *)palette)[src[i]]);
 }
-
 #endif
 
 void rgb32to24(const uint8_t *src, uint8_t *dst, long src_size)
@@ -425,7 +341,6 @@ void shuffle_bytes_##a##b##c##d(const uint8_t *src, uint8_t *dst, long src_size)
 
 DEFINE_SHUFFLE_BYTES(0, 3, 2, 1);
 DEFINE_SHUFFLE_BYTES(1, 2, 3, 0);
-DEFINE_SHUFFLE_BYTES(2, 1, 0, 3);
 DEFINE_SHUFFLE_BYTES(3, 0, 1, 2);
 DEFINE_SHUFFLE_BYTES(3, 2, 1, 0);
 
diff --git a/libswscale/rgb2rgb.h b/libswscale/rgb2rgb.h
index 2e182dd..bde1134 100644
--- a/libswscale/rgb2rgb.h
+++ b/libswscale/rgb2rgb.h
@@ -6,20 +6,20 @@
  *  Written by Nick Kurshev.
  *  YUV & runtime CPU stuff by Michael (michaelni at gmx.at)
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -47,7 +47,7 @@ extern void (*rgb16to32)   (const uint8_t *src, uint8_t *dst, long src_size);
 extern void (*rgb24tobgr24)(const uint8_t *src, uint8_t *dst, long src_size);
 extern void (*rgb24to16)   (const uint8_t *src, uint8_t *dst, long src_size);
 extern void (*rgb24to15)   (const uint8_t *src, uint8_t *dst, long src_size);
-extern void (*rgb32tobgr32)(const uint8_t *src, uint8_t *dst, long src_size);
+extern void (*shuffle_bytes_2103)(const uint8_t *src, uint8_t *dst, long src_size);
 extern void (*rgb32tobgr16)(const uint8_t *src, uint8_t *dst, long src_size);
 extern void (*rgb32tobgr15)(const uint8_t *src, uint8_t *dst, long src_size);
 
@@ -65,7 +65,6 @@ void bgr8torgb8  (const uint8_t *src, uint8_t *dst, long src_size);
 
 void shuffle_bytes_0321(const uint8_t *src, uint8_t *dst, long src_size);
 void shuffle_bytes_1230(const uint8_t *src, uint8_t *dst, long src_size);
-void shuffle_bytes_2103(const uint8_t *src, uint8_t *dst, long src_size);
 void shuffle_bytes_3012(const uint8_t *src, uint8_t *dst, long src_size);
 void shuffle_bytes_3210(const uint8_t *src, uint8_t *dst, long src_size);
 
@@ -169,4 +168,6 @@ extern void (*yuyvtoyuv422)(uint8_t *ydst, uint8_t *udst, uint8_t *vdst, const u
 
 void sws_rgb2rgb_init(int flags);
 
+void rgb2rgb_init_x86(int flags);
+
 #endif /* SWSCALE_RGB2RGB_H */
diff --git a/libswscale/rgb2rgb_template.c b/libswscale/rgb2rgb_template.c
index d86cafc..7537419 100644
--- a/libswscale/rgb2rgb_template.c
+++ b/libswscale/rgb2rgb_template.c
@@ -7,104 +7,32 @@
  * palette & YUV & runtime CPU stuff by Michael (michaelni at gmx.at)
  * lot of big-endian byte order fixes by Alex Beregszaszi
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include <stddef.h>
 
-#undef PREFETCH
-#undef MOVNTQ
-#undef EMMS
-#undef SFENCE
-#undef MMREG_SIZE
-#undef PAVGB
-
-#if HAVE_SSE2
-#define MMREG_SIZE 16
-#else
-#define MMREG_SIZE 8
-#endif
-
-#if HAVE_AMD3DNOW
-#define PREFETCH  "prefetch"
-#define PAVGB     "pavgusb"
-#elif HAVE_MMX2
-#define PREFETCH "prefetchnta"
-#define PAVGB     "pavgb"
-#else
-#define PREFETCH  " # nop"
-#endif
-
-#if HAVE_AMD3DNOW
-/* On K6 femms is faster than emms. On K7 femms is directly mapped to emms. */
-#define EMMS     "femms"
-#else
-#define EMMS     "emms"
-#endif
-
-#if HAVE_MMX2
-#define MOVNTQ "movntq"
-#define SFENCE "sfence"
-#else
-#define MOVNTQ "movq"
-#define SFENCE " # nop"
-#endif
-
-static inline void RENAME(rgb24tobgr32)(const uint8_t *src, uint8_t *dst, long src_size)
+static inline void rgb24tobgr32_c(const uint8_t *src, uint8_t *dst, long src_size)
 {
     uint8_t *dest = dst;
     const uint8_t *s = src;
     const uint8_t *end;
-#if HAVE_MMX
-    const uint8_t *mm_end;
-#endif
     end = s + src_size;
-#if HAVE_MMX
-    __asm__ volatile(PREFETCH"    %0"::"m"(*s):"memory");
-    mm_end = end - 23;
-    __asm__ volatile("movq        %0, %%mm7"::"m"(mask32a):"memory");
-    while (s < mm_end) {
-        __asm__ volatile(
-            PREFETCH"    32%1           \n\t"
-            "movd          %1, %%mm0    \n\t"
-            "punpckldq    3%1, %%mm0    \n\t"
-            "movd         6%1, %%mm1    \n\t"
-            "punpckldq    9%1, %%mm1    \n\t"
-            "movd        12%1, %%mm2    \n\t"
-            "punpckldq   15%1, %%mm2    \n\t"
-            "movd        18%1, %%mm3    \n\t"
-            "punpckldq   21%1, %%mm3    \n\t"
-            "por        %%mm7, %%mm0    \n\t"
-            "por        %%mm7, %%mm1    \n\t"
-            "por        %%mm7, %%mm2    \n\t"
-            "por        %%mm7, %%mm3    \n\t"
-            MOVNTQ"     %%mm0,   %0     \n\t"
-            MOVNTQ"     %%mm1,  8%0     \n\t"
-            MOVNTQ"     %%mm2, 16%0     \n\t"
-            MOVNTQ"     %%mm3, 24%0"
-            :"=m"(*dest)
-            :"m"(*s)
-            :"memory");
-        dest += 32;
-        s += 24;
-    }
-    __asm__ volatile(SFENCE:::"memory");
-    __asm__ volatile(EMMS:::"memory");
-#endif
+
     while (s < end) {
 #if HAVE_BIGENDIAN
         /* RGB24 (= R,G,B) -> RGB32 (= A,B,G,R) */
@@ -122,76 +50,14 @@ static inline void RENAME(rgb24tobgr32)(const uint8_t *src, uint8_t *dst, long s
     }
 }
 
-#define STORE_BGR24_MMX \
-            "psrlq         $8, %%mm2    \n\t" \
-            "psrlq         $8, %%mm3    \n\t" \
-            "psrlq         $8, %%mm6    \n\t" \
-            "psrlq         $8, %%mm7    \n\t" \
-            "pand "MANGLE(mask24l)", %%mm0\n\t" \
-            "pand "MANGLE(mask24l)", %%mm1\n\t" \
-            "pand "MANGLE(mask24l)", %%mm4\n\t" \
-            "pand "MANGLE(mask24l)", %%mm5\n\t" \
-            "pand "MANGLE(mask24h)", %%mm2\n\t" \
-            "pand "MANGLE(mask24h)", %%mm3\n\t" \
-            "pand "MANGLE(mask24h)", %%mm6\n\t" \
-            "pand "MANGLE(mask24h)", %%mm7\n\t" \
-            "por        %%mm2, %%mm0    \n\t" \
-            "por        %%mm3, %%mm1    \n\t" \
-            "por        %%mm6, %%mm4    \n\t" \
-            "por        %%mm7, %%mm5    \n\t" \
- \
-            "movq       %%mm1, %%mm2    \n\t" \
-            "movq       %%mm4, %%mm3    \n\t" \
-            "psllq        $48, %%mm2    \n\t" \
-            "psllq        $32, %%mm3    \n\t" \
-            "pand "MANGLE(mask24hh)", %%mm2\n\t" \
-            "pand "MANGLE(mask24hhh)", %%mm3\n\t" \
-            "por        %%mm2, %%mm0    \n\t" \
-            "psrlq        $16, %%mm1    \n\t" \
-            "psrlq        $32, %%mm4    \n\t" \
-            "psllq        $16, %%mm5    \n\t" \
-            "por        %%mm3, %%mm1    \n\t" \
-            "pand  "MANGLE(mask24hhhh)", %%mm5\n\t" \
-            "por        %%mm5, %%mm4    \n\t" \
- \
-            MOVNTQ"     %%mm0,   %0     \n\t" \
-            MOVNTQ"     %%mm1,  8%0     \n\t" \
-            MOVNTQ"     %%mm4, 16%0"
-
-
-static inline void RENAME(rgb32tobgr24)(const uint8_t *src, uint8_t *dst, long src_size)
+static inline void rgb32tobgr24_c(const uint8_t *src, uint8_t *dst, long src_size)
 {
     uint8_t *dest = dst;
     const uint8_t *s = src;
     const uint8_t *end;
-#if HAVE_MMX
-    const uint8_t *mm_end;
-#endif
+
     end = s + src_size;
-#if HAVE_MMX
-    __asm__ volatile(PREFETCH"    %0"::"m"(*s):"memory");
-    mm_end = end - 31;
-    while (s < mm_end) {
-        __asm__ volatile(
-            PREFETCH"    32%1           \n\t"
-            "movq          %1, %%mm0    \n\t"
-            "movq         8%1, %%mm1    \n\t"
-            "movq        16%1, %%mm4    \n\t"
-            "movq        24%1, %%mm5    \n\t"
-            "movq       %%mm0, %%mm2    \n\t"
-            "movq       %%mm1, %%mm3    \n\t"
-            "movq       %%mm4, %%mm6    \n\t"
-            "movq       %%mm5, %%mm7    \n\t"
-            STORE_BGR24_MMX
-            :"=m"(*dest)
-            :"m"(*s)
-            :"memory");
-        dest += 24;
-        s += 32;
-    }
-    __asm__ volatile(SFENCE:::"memory");
-    __asm__ volatile(EMMS:::"memory");
-#endif
+
     while (s < end) {
 #if HAVE_BIGENDIAN
         /* RGB32 (= A,B,G,R) -> RGB24 (= R,G,B) */
@@ -215,39 +81,13 @@ static inline void RENAME(rgb32tobgr24)(const uint8_t *src, uint8_t *dst, long s
  MMX2, 3DNOW optimization by Nick Kurshev
  32-bit C version, and and&add trick by Michael Niedermayer
 */
-static inline void RENAME(rgb15to16)(const uint8_t *src, uint8_t *dst, long src_size)
+static inline void rgb15to16_c(const uint8_t *src, uint8_t *dst, long src_size)
 {
     register const uint8_t* s=src;
     register uint8_t* d=dst;
     register const uint8_t *end;
     const uint8_t *mm_end;
     end = s + src_size;
-#if HAVE_MMX
-    __asm__ volatile(PREFETCH"    %0"::"m"(*s));
-    __asm__ volatile("movq        %0, %%mm4"::"m"(mask15s));
-    mm_end = end - 15;
-    while (s<mm_end) {
-        __asm__ volatile(
-            PREFETCH"  32%1         \n\t"
-            "movq        %1, %%mm0  \n\t"
-            "movq       8%1, %%mm2  \n\t"
-            "movq     %%mm0, %%mm1  \n\t"
-            "movq     %%mm2, %%mm3  \n\t"
-            "pand     %%mm4, %%mm0  \n\t"
-            "pand     %%mm4, %%mm2  \n\t"
-            "paddw    %%mm1, %%mm0  \n\t"
-            "paddw    %%mm3, %%mm2  \n\t"
-            MOVNTQ"   %%mm0,  %0    \n\t"
-            MOVNTQ"   %%mm2, 8%0"
-            :"=m"(*d)
-            :"m"(*s)
-        );
-        d+=16;
-        s+=16;
-    }
-    __asm__ volatile(SFENCE:::"memory");
-    __asm__ volatile(EMMS:::"memory");
-#endif
     mm_end = end - 3;
     while (s < mm_end) {
         register unsigned x= *((const uint32_t *)s);
@@ -261,44 +101,14 @@ static inline void RENAME(rgb15to16)(const uint8_t *src, uint8_t *dst, long src_
     }
 }
 
-static inline void RENAME(rgb16to15)(const uint8_t *src, uint8_t *dst, long src_size)
+static inline void rgb16to15_c(const uint8_t *src, uint8_t *dst, long src_size)
 {
     register const uint8_t* s=src;
     register uint8_t* d=dst;
     register const uint8_t *end;
     const uint8_t *mm_end;
     end = s + src_size;
-#if HAVE_MMX
-    __asm__ volatile(PREFETCH"    %0"::"m"(*s));
-    __asm__ volatile("movq        %0, %%mm7"::"m"(mask15rg));
-    __asm__ volatile("movq        %0, %%mm6"::"m"(mask15b));
-    mm_end = end - 15;
-    while (s<mm_end) {
-        __asm__ volatile(
-            PREFETCH"  32%1         \n\t"
-            "movq        %1, %%mm0  \n\t"
-            "movq       8%1, %%mm2  \n\t"
-            "movq     %%mm0, %%mm1  \n\t"
-            "movq     %%mm2, %%mm3  \n\t"
-            "psrlq       $1, %%mm0  \n\t"
-            "psrlq       $1, %%mm2  \n\t"
-            "pand     %%mm7, %%mm0  \n\t"
-            "pand     %%mm7, %%mm2  \n\t"
-            "pand     %%mm6, %%mm1  \n\t"
-            "pand     %%mm6, %%mm3  \n\t"
-            "por      %%mm1, %%mm0  \n\t"
-            "por      %%mm3, %%mm2  \n\t"
-            MOVNTQ"   %%mm0,  %0    \n\t"
-            MOVNTQ"   %%mm2, 8%0"
-            :"=m"(*d)
-            :"m"(*s)
-        );
-        d+=16;
-        s+=16;
-    }
-    __asm__ volatile(SFENCE:::"memory");
-    __asm__ volatile(EMMS:::"memory");
-#endif
+
     mm_end = end - 3;
     while (s < mm_end) {
         register uint32_t x= *((const uint32_t*)s);
@@ -312,369 +122,61 @@ static inline void RENAME(rgb16to15)(const uint8_t *src, uint8_t *dst, long src_
     }
 }
 
-static inline void RENAME(rgb32to16)(const uint8_t *src, uint8_t *dst, long src_size)
+static inline void rgb32to16_c(const uint8_t *src, uint8_t *dst, long src_size)
 {
     const uint8_t *s = src;
     const uint8_t *end;
-#if HAVE_MMX
-    const uint8_t *mm_end;
-#endif
     uint16_t *d = (uint16_t *)dst;
     end = s + src_size;
-#if HAVE_MMX
-    mm_end = end - 15;
-#if 1 //is faster only if multiplies are reasonably fast (FIXME figure out on which CPUs this is faster, on Athlon it is slightly faster)
-    __asm__ volatile(
-        "movq           %3, %%mm5   \n\t"
-        "movq           %4, %%mm6   \n\t"
-        "movq           %5, %%mm7   \n\t"
-        "jmp 2f                     \n\t"
-        ASMALIGN(4)
-        "1:                         \n\t"
-        PREFETCH"   32(%1)          \n\t"
-        "movd         (%1), %%mm0   \n\t"
-        "movd        4(%1), %%mm3   \n\t"
-        "punpckldq   8(%1), %%mm0   \n\t"
-        "punpckldq  12(%1), %%mm3   \n\t"
-        "movq        %%mm0, %%mm1   \n\t"
-        "movq        %%mm3, %%mm4   \n\t"
-        "pand        %%mm6, %%mm0   \n\t"
-        "pand        %%mm6, %%mm3   \n\t"
-        "pmaddwd     %%mm7, %%mm0   \n\t"
-        "pmaddwd     %%mm7, %%mm3   \n\t"
-        "pand        %%mm5, %%mm1   \n\t"
-        "pand        %%mm5, %%mm4   \n\t"
-        "por         %%mm1, %%mm0   \n\t"
-        "por         %%mm4, %%mm3   \n\t"
-        "psrld          $5, %%mm0   \n\t"
-        "pslld         $11, %%mm3   \n\t"
-        "por         %%mm3, %%mm0   \n\t"
-        MOVNTQ"      %%mm0, (%0)    \n\t"
-        "add           $16,  %1     \n\t"
-        "add            $8,  %0     \n\t"
-        "2:                         \n\t"
-        "cmp            %2,  %1     \n\t"
-        " jb            1b          \n\t"
-        : "+r" (d), "+r"(s)
-        : "r" (mm_end), "m" (mask3216g), "m" (mask3216br), "m" (mul3216)
-    );
-#else
-    __asm__ volatile(PREFETCH"    %0"::"m"(*src):"memory");
-    __asm__ volatile(
-        "movq    %0, %%mm7    \n\t"
-        "movq    %1, %%mm6    \n\t"
-        ::"m"(red_16mask),"m"(green_16mask));
-    while (s < mm_end) {
-        __asm__ volatile(
-            PREFETCH"    32%1           \n\t"
-            "movd          %1, %%mm0    \n\t"
-            "movd         4%1, %%mm3    \n\t"
-            "punpckldq    8%1, %%mm0    \n\t"
-            "punpckldq   12%1, %%mm3    \n\t"
-            "movq       %%mm0, %%mm1    \n\t"
-            "movq       %%mm0, %%mm2    \n\t"
-            "movq       %%mm3, %%mm4    \n\t"
-            "movq       %%mm3, %%mm5    \n\t"
-            "psrlq         $3, %%mm0    \n\t"
-            "psrlq         $3, %%mm3    \n\t"
-            "pand          %2, %%mm0    \n\t"
-            "pand          %2, %%mm3    \n\t"
-            "psrlq         $5, %%mm1    \n\t"
-            "psrlq         $5, %%mm4    \n\t"
-            "pand       %%mm6, %%mm1    \n\t"
-            "pand       %%mm6, %%mm4    \n\t"
-            "psrlq         $8, %%mm2    \n\t"
-            "psrlq         $8, %%mm5    \n\t"
-            "pand       %%mm7, %%mm2    \n\t"
-            "pand       %%mm7, %%mm5    \n\t"
-            "por        %%mm1, %%mm0    \n\t"
-            "por        %%mm4, %%mm3    \n\t"
-            "por        %%mm2, %%mm0    \n\t"
-            "por        %%mm5, %%mm3    \n\t"
-            "psllq        $16, %%mm3    \n\t"
-            "por        %%mm3, %%mm0    \n\t"
-            MOVNTQ"     %%mm0, %0       \n\t"
-            :"=m"(*d):"m"(*s),"m"(blue_16mask):"memory");
-        d += 4;
-        s += 16;
-    }
-#endif
-    __asm__ volatile(SFENCE:::"memory");
-    __asm__ volatile(EMMS:::"memory");
-#endif
+
     while (s < end) {
         register int rgb = *(const uint32_t*)s; s += 4;
         *d++ = ((rgb&0xFF)>>3) + ((rgb&0xFC00)>>5) + ((rgb&0xF80000)>>8);
     }
 }
 
-static inline void RENAME(rgb32tobgr16)(const uint8_t *src, uint8_t *dst, long src_size)
+static inline void rgb32tobgr16_c(const uint8_t *src, uint8_t *dst, long src_size)
 {
     const uint8_t *s = src;
     const uint8_t *end;
-#if HAVE_MMX
-    const uint8_t *mm_end;
-#endif
     uint16_t *d = (uint16_t *)dst;
     end = s + src_size;
-#if HAVE_MMX
-    __asm__ volatile(PREFETCH"    %0"::"m"(*src):"memory");
-    __asm__ volatile(
-        "movq          %0, %%mm7    \n\t"
-        "movq          %1, %%mm6    \n\t"
-        ::"m"(red_16mask),"m"(green_16mask));
-    mm_end = end - 15;
-    while (s < mm_end) {
-        __asm__ volatile(
-            PREFETCH"    32%1           \n\t"
-            "movd          %1, %%mm0    \n\t"
-            "movd         4%1, %%mm3    \n\t"
-            "punpckldq    8%1, %%mm0    \n\t"
-            "punpckldq   12%1, %%mm3    \n\t"
-            "movq       %%mm0, %%mm1    \n\t"
-            "movq       %%mm0, %%mm2    \n\t"
-            "movq       %%mm3, %%mm4    \n\t"
-            "movq       %%mm3, %%mm5    \n\t"
-            "psllq         $8, %%mm0    \n\t"
-            "psllq         $8, %%mm3    \n\t"
-            "pand       %%mm7, %%mm0    \n\t"
-            "pand       %%mm7, %%mm3    \n\t"
-            "psrlq         $5, %%mm1    \n\t"
-            "psrlq         $5, %%mm4    \n\t"
-            "pand       %%mm6, %%mm1    \n\t"
-            "pand       %%mm6, %%mm4    \n\t"
-            "psrlq        $19, %%mm2    \n\t"
-            "psrlq        $19, %%mm5    \n\t"
-            "pand          %2, %%mm2    \n\t"
-            "pand          %2, %%mm5    \n\t"
-            "por        %%mm1, %%mm0    \n\t"
-            "por        %%mm4, %%mm3    \n\t"
-            "por        %%mm2, %%mm0    \n\t"
-            "por        %%mm5, %%mm3    \n\t"
-            "psllq        $16, %%mm3    \n\t"
-            "por        %%mm3, %%mm0    \n\t"
-            MOVNTQ"     %%mm0, %0       \n\t"
-            :"=m"(*d):"m"(*s),"m"(blue_16mask):"memory");
-        d += 4;
-        s += 16;
-    }
-    __asm__ volatile(SFENCE:::"memory");
-    __asm__ volatile(EMMS:::"memory");
-#endif
     while (s < end) {
         register int rgb = *(const uint32_t*)s; s += 4;
         *d++ = ((rgb&0xF8)<<8) + ((rgb&0xFC00)>>5) + ((rgb&0xF80000)>>19);
     }
 }
 
-static inline void RENAME(rgb32to15)(const uint8_t *src, uint8_t *dst, long src_size)
+static inline void rgb32to15_c(const uint8_t *src, uint8_t *dst, long src_size)
 {
     const uint8_t *s = src;
     const uint8_t *end;
-#if HAVE_MMX
-    const uint8_t *mm_end;
-#endif
     uint16_t *d = (uint16_t *)dst;
     end = s + src_size;
-#if HAVE_MMX
-    mm_end = end - 15;
-#if 1 //is faster only if multiplies are reasonably fast (FIXME figure out on which CPUs this is faster, on Athlon it is slightly faster)
-    __asm__ volatile(
-        "movq           %3, %%mm5   \n\t"
-        "movq           %4, %%mm6   \n\t"
-        "movq           %5, %%mm7   \n\t"
-        "jmp            2f          \n\t"
-        ASMALIGN(4)
-        "1:                         \n\t"
-        PREFETCH"   32(%1)          \n\t"
-        "movd         (%1), %%mm0   \n\t"
-        "movd        4(%1), %%mm3   \n\t"
-        "punpckldq   8(%1), %%mm0   \n\t"
-        "punpckldq  12(%1), %%mm3   \n\t"
-        "movq        %%mm0, %%mm1   \n\t"
-        "movq        %%mm3, %%mm4   \n\t"
-        "pand        %%mm6, %%mm0   \n\t"
-        "pand        %%mm6, %%mm3   \n\t"
-        "pmaddwd     %%mm7, %%mm0   \n\t"
-        "pmaddwd     %%mm7, %%mm3   \n\t"
-        "pand        %%mm5, %%mm1   \n\t"
-        "pand        %%mm5, %%mm4   \n\t"
-        "por         %%mm1, %%mm0   \n\t"
-        "por         %%mm4, %%mm3   \n\t"
-        "psrld          $6, %%mm0   \n\t"
-        "pslld         $10, %%mm3   \n\t"
-        "por         %%mm3, %%mm0   \n\t"
-        MOVNTQ"      %%mm0, (%0)    \n\t"
-        "add           $16,  %1     \n\t"
-        "add            $8,  %0     \n\t"
-        "2:                         \n\t"
-        "cmp            %2,  %1     \n\t"
-        " jb            1b          \n\t"
-        : "+r" (d), "+r"(s)
-        : "r" (mm_end), "m" (mask3215g), "m" (mask3216br), "m" (mul3215)
-    );
-#else
-    __asm__ volatile(PREFETCH"    %0"::"m"(*src):"memory");
-    __asm__ volatile(
-        "movq          %0, %%mm7    \n\t"
-        "movq          %1, %%mm6    \n\t"
-        ::"m"(red_15mask),"m"(green_15mask));
-    while (s < mm_end) {
-        __asm__ volatile(
-            PREFETCH"    32%1           \n\t"
-            "movd          %1, %%mm0    \n\t"
-            "movd         4%1, %%mm3    \n\t"
-            "punpckldq    8%1, %%mm0    \n\t"
-            "punpckldq   12%1, %%mm3    \n\t"
-            "movq       %%mm0, %%mm1    \n\t"
-            "movq       %%mm0, %%mm2    \n\t"
-            "movq       %%mm3, %%mm4    \n\t"
-            "movq       %%mm3, %%mm5    \n\t"
-            "psrlq         $3, %%mm0    \n\t"
-            "psrlq         $3, %%mm3    \n\t"
-            "pand          %2, %%mm0    \n\t"
-            "pand          %2, %%mm3    \n\t"
-            "psrlq         $6, %%mm1    \n\t"
-            "psrlq         $6, %%mm4    \n\t"
-            "pand       %%mm6, %%mm1    \n\t"
-            "pand       %%mm6, %%mm4    \n\t"
-            "psrlq         $9, %%mm2    \n\t"
-            "psrlq         $9, %%mm5    \n\t"
-            "pand       %%mm7, %%mm2    \n\t"
-            "pand       %%mm7, %%mm5    \n\t"
-            "por        %%mm1, %%mm0    \n\t"
-            "por        %%mm4, %%mm3    \n\t"
-            "por        %%mm2, %%mm0    \n\t"
-            "por        %%mm5, %%mm3    \n\t"
-            "psllq        $16, %%mm3    \n\t"
-            "por        %%mm3, %%mm0    \n\t"
-            MOVNTQ"     %%mm0, %0       \n\t"
-            :"=m"(*d):"m"(*s),"m"(blue_15mask):"memory");
-        d += 4;
-        s += 16;
-    }
-#endif
-    __asm__ volatile(SFENCE:::"memory");
-    __asm__ volatile(EMMS:::"memory");
-#endif
     while (s < end) {
         register int rgb = *(const uint32_t*)s; s += 4;
         *d++ = ((rgb&0xFF)>>3) + ((rgb&0xF800)>>6) + ((rgb&0xF80000)>>9);
     }
 }
 
-static inline void RENAME(rgb32tobgr15)(const uint8_t *src, uint8_t *dst, long src_size)
+static inline void rgb32tobgr15_c(const uint8_t *src, uint8_t *dst, long src_size)
 {
     const uint8_t *s = src;
     const uint8_t *end;
-#if HAVE_MMX
-    const uint8_t *mm_end;
-#endif
     uint16_t *d = (uint16_t *)dst;
     end = s + src_size;
-#if HAVE_MMX
-    __asm__ volatile(PREFETCH"    %0"::"m"(*src):"memory");
-    __asm__ volatile(
-        "movq          %0, %%mm7    \n\t"
-        "movq          %1, %%mm6    \n\t"
-        ::"m"(red_15mask),"m"(green_15mask));
-    mm_end = end - 15;
-    while (s < mm_end) {
-        __asm__ volatile(
-            PREFETCH"    32%1           \n\t"
-            "movd          %1, %%mm0    \n\t"
-            "movd         4%1, %%mm3    \n\t"
-            "punpckldq    8%1, %%mm0    \n\t"
-            "punpckldq   12%1, %%mm3    \n\t"
-            "movq       %%mm0, %%mm1    \n\t"
-            "movq       %%mm0, %%mm2    \n\t"
-            "movq       %%mm3, %%mm4    \n\t"
-            "movq       %%mm3, %%mm5    \n\t"
-            "psllq         $7, %%mm0    \n\t"
-            "psllq         $7, %%mm3    \n\t"
-            "pand       %%mm7, %%mm0    \n\t"
-            "pand       %%mm7, %%mm3    \n\t"
-            "psrlq         $6, %%mm1    \n\t"
-            "psrlq         $6, %%mm4    \n\t"
-            "pand       %%mm6, %%mm1    \n\t"
-            "pand       %%mm6, %%mm4    \n\t"
-            "psrlq        $19, %%mm2    \n\t"
-            "psrlq        $19, %%mm5    \n\t"
-            "pand          %2, %%mm2    \n\t"
-            "pand          %2, %%mm5    \n\t"
-            "por        %%mm1, %%mm0    \n\t"
-            "por        %%mm4, %%mm3    \n\t"
-            "por        %%mm2, %%mm0    \n\t"
-            "por        %%mm5, %%mm3    \n\t"
-            "psllq        $16, %%mm3    \n\t"
-            "por        %%mm3, %%mm0    \n\t"
-            MOVNTQ"     %%mm0, %0       \n\t"
-            :"=m"(*d):"m"(*s),"m"(blue_15mask):"memory");
-        d += 4;
-        s += 16;
-    }
-    __asm__ volatile(SFENCE:::"memory");
-    __asm__ volatile(EMMS:::"memory");
-#endif
     while (s < end) {
         register int rgb = *(const uint32_t*)s; s += 4;
         *d++ = ((rgb&0xF8)<<7) + ((rgb&0xF800)>>6) + ((rgb&0xF80000)>>19);
     }
 }
 
-static inline void RENAME(rgb24tobgr16)(const uint8_t *src, uint8_t *dst, long src_size)
+static inline void rgb24tobgr16_c(const uint8_t *src, uint8_t *dst, long src_size)
 {
     const uint8_t *s = src;
     const uint8_t *end;
-#if HAVE_MMX
-    const uint8_t *mm_end;
-#endif
     uint16_t *d = (uint16_t *)dst;
     end = s + src_size;
-#if HAVE_MMX
-    __asm__ volatile(PREFETCH"    %0"::"m"(*src):"memory");
-    __asm__ volatile(
-        "movq         %0, %%mm7     \n\t"
-        "movq         %1, %%mm6     \n\t"
-        ::"m"(red_16mask),"m"(green_16mask));
-    mm_end = end - 11;
-    while (s < mm_end) {
-        __asm__ volatile(
-            PREFETCH"    32%1           \n\t"
-            "movd          %1, %%mm0    \n\t"
-            "movd         3%1, %%mm3    \n\t"
-            "punpckldq    6%1, %%mm0    \n\t"
-            "punpckldq    9%1, %%mm3    \n\t"
-            "movq       %%mm0, %%mm1    \n\t"
-            "movq       %%mm0, %%mm2    \n\t"
-            "movq       %%mm3, %%mm4    \n\t"
-            "movq       %%mm3, %%mm5    \n\t"
-            "psrlq         $3, %%mm0    \n\t"
-            "psrlq         $3, %%mm3    \n\t"
-            "pand          %2, %%mm0    \n\t"
-            "pand          %2, %%mm3    \n\t"
-            "psrlq         $5, %%mm1    \n\t"
-            "psrlq         $5, %%mm4    \n\t"
-            "pand       %%mm6, %%mm1    \n\t"
-            "pand       %%mm6, %%mm4    \n\t"
-            "psrlq         $8, %%mm2    \n\t"
-            "psrlq         $8, %%mm5    \n\t"
-            "pand       %%mm7, %%mm2    \n\t"
-            "pand       %%mm7, %%mm5    \n\t"
-            "por        %%mm1, %%mm0    \n\t"
-            "por        %%mm4, %%mm3    \n\t"
-            "por        %%mm2, %%mm0    \n\t"
-            "por        %%mm5, %%mm3    \n\t"
-            "psllq        $16, %%mm3    \n\t"
-            "por        %%mm3, %%mm0    \n\t"
-            MOVNTQ"     %%mm0, %0       \n\t"
-            :"=m"(*d):"m"(*s),"m"(blue_16mask):"memory");
-        d += 4;
-        s += 12;
-    }
-    __asm__ volatile(SFENCE:::"memory");
-    __asm__ volatile(EMMS:::"memory");
-#endif
     while (s < end) {
         const int b = *s++;
         const int g = *s++;
@@ -683,59 +185,12 @@ static inline void RENAME(rgb24tobgr16)(const uint8_t *src, uint8_t *dst, long s
     }
 }
 
-static inline void RENAME(rgb24to16)(const uint8_t *src, uint8_t *dst, long src_size)
+static inline void rgb24to16_c(const uint8_t *src, uint8_t *dst, long src_size)
 {
     const uint8_t *s = src;
     const uint8_t *end;
-#if HAVE_MMX
-    const uint8_t *mm_end;
-#endif
     uint16_t *d = (uint16_t *)dst;
     end = s + src_size;
-#if HAVE_MMX
-    __asm__ volatile(PREFETCH"    %0"::"m"(*src):"memory");
-    __asm__ volatile(
-        "movq         %0, %%mm7     \n\t"
-        "movq         %1, %%mm6     \n\t"
-        ::"m"(red_16mask),"m"(green_16mask));
-    mm_end = end - 15;
-    while (s < mm_end) {
-        __asm__ volatile(
-            PREFETCH"    32%1           \n\t"
-            "movd          %1, %%mm0    \n\t"
-            "movd         3%1, %%mm3    \n\t"
-            "punpckldq    6%1, %%mm0    \n\t"
-            "punpckldq    9%1, %%mm3    \n\t"
-            "movq       %%mm0, %%mm1    \n\t"
-            "movq       %%mm0, %%mm2    \n\t"
-            "movq       %%mm3, %%mm4    \n\t"
-            "movq       %%mm3, %%mm5    \n\t"
-            "psllq         $8, %%mm0    \n\t"
-            "psllq         $8, %%mm3    \n\t"
-            "pand       %%mm7, %%mm0    \n\t"
-            "pand       %%mm7, %%mm3    \n\t"
-            "psrlq         $5, %%mm1    \n\t"
-            "psrlq         $5, %%mm4    \n\t"
-            "pand       %%mm6, %%mm1    \n\t"
-            "pand       %%mm6, %%mm4    \n\t"
-            "psrlq        $19, %%mm2    \n\t"
-            "psrlq        $19, %%mm5    \n\t"
-            "pand          %2, %%mm2    \n\t"
-            "pand          %2, %%mm5    \n\t"
-            "por        %%mm1, %%mm0    \n\t"
-            "por        %%mm4, %%mm3    \n\t"
-            "por        %%mm2, %%mm0    \n\t"
-            "por        %%mm5, %%mm3    \n\t"
-            "psllq        $16, %%mm3    \n\t"
-            "por        %%mm3, %%mm0    \n\t"
-            MOVNTQ"     %%mm0, %0       \n\t"
-            :"=m"(*d):"m"(*s),"m"(blue_16mask):"memory");
-        d += 4;
-        s += 12;
-    }
-    __asm__ volatile(SFENCE:::"memory");
-    __asm__ volatile(EMMS:::"memory");
-#endif
     while (s < end) {
         const int r = *s++;
         const int g = *s++;
@@ -744,59 +199,12 @@ static inline void RENAME(rgb24to16)(const uint8_t *src, uint8_t *dst, long src_
     }
 }
 
-static inline void RENAME(rgb24tobgr15)(const uint8_t *src, uint8_t *dst, long src_size)
+static inline void rgb24tobgr15_c(const uint8_t *src, uint8_t *dst, long src_size)
 {
     const uint8_t *s = src;
     const uint8_t *end;
-#if HAVE_MMX
-    const uint8_t *mm_end;
-#endif
     uint16_t *d = (uint16_t *)dst;
     end = s + src_size;
-#if HAVE_MMX
-    __asm__ volatile(PREFETCH"    %0"::"m"(*src):"memory");
-    __asm__ volatile(
-        "movq          %0, %%mm7    \n\t"
-        "movq          %1, %%mm6    \n\t"
-        ::"m"(red_15mask),"m"(green_15mask));
-    mm_end = end - 11;
-    while (s < mm_end) {
-        __asm__ volatile(
-            PREFETCH"    32%1           \n\t"
-            "movd          %1, %%mm0    \n\t"
-            "movd         3%1, %%mm3    \n\t"
-            "punpckldq    6%1, %%mm0    \n\t"
-            "punpckldq    9%1, %%mm3    \n\t"
-            "movq       %%mm0, %%mm1    \n\t"
-            "movq       %%mm0, %%mm2    \n\t"
-            "movq       %%mm3, %%mm4    \n\t"
-            "movq       %%mm3, %%mm5    \n\t"
-            "psrlq         $3, %%mm0    \n\t"
-            "psrlq         $3, %%mm3    \n\t"
-            "pand          %2, %%mm0    \n\t"
-            "pand          %2, %%mm3    \n\t"
-            "psrlq         $6, %%mm1    \n\t"
-            "psrlq         $6, %%mm4    \n\t"
-            "pand       %%mm6, %%mm1    \n\t"
-            "pand       %%mm6, %%mm4    \n\t"
-            "psrlq         $9, %%mm2    \n\t"
-            "psrlq         $9, %%mm5    \n\t"
-            "pand       %%mm7, %%mm2    \n\t"
-            "pand       %%mm7, %%mm5    \n\t"
-            "por        %%mm1, %%mm0    \n\t"
-            "por        %%mm4, %%mm3    \n\t"
-            "por        %%mm2, %%mm0    \n\t"
-            "por        %%mm5, %%mm3    \n\t"
-            "psllq        $16, %%mm3    \n\t"
-            "por        %%mm3, %%mm0    \n\t"
-            MOVNTQ"     %%mm0, %0       \n\t"
-            :"=m"(*d):"m"(*s),"m"(blue_15mask):"memory");
-        d += 4;
-        s += 12;
-    }
-    __asm__ volatile(SFENCE:::"memory");
-    __asm__ volatile(EMMS:::"memory");
-#endif
     while (s < end) {
         const int b = *s++;
         const int g = *s++;
@@ -805,59 +213,12 @@ static inline void RENAME(rgb24tobgr15)(const uint8_t *src, uint8_t *dst, long s
     }
 }
 
-static inline void RENAME(rgb24to15)(const uint8_t *src, uint8_t *dst, long src_size)
+static inline void rgb24to15_c(const uint8_t *src, uint8_t *dst, long src_size)
 {
     const uint8_t *s = src;
     const uint8_t *end;
-#if HAVE_MMX
-    const uint8_t *mm_end;
-#endif
     uint16_t *d = (uint16_t *)dst;
     end = s + src_size;
-#if HAVE_MMX
-    __asm__ volatile(PREFETCH"    %0"::"m"(*src):"memory");
-    __asm__ volatile(
-        "movq         %0, %%mm7     \n\t"
-        "movq         %1, %%mm6     \n\t"
-        ::"m"(red_15mask),"m"(green_15mask));
-    mm_end = end - 15;
-    while (s < mm_end) {
-        __asm__ volatile(
-            PREFETCH"   32%1            \n\t"
-            "movd         %1, %%mm0     \n\t"
-            "movd        3%1, %%mm3     \n\t"
-            "punpckldq   6%1, %%mm0     \n\t"
-            "punpckldq   9%1, %%mm3     \n\t"
-            "movq      %%mm0, %%mm1     \n\t"
-            "movq      %%mm0, %%mm2     \n\t"
-            "movq      %%mm3, %%mm4     \n\t"
-            "movq      %%mm3, %%mm5     \n\t"
-            "psllq        $7, %%mm0     \n\t"
-            "psllq        $7, %%mm3     \n\t"
-            "pand      %%mm7, %%mm0     \n\t"
-            "pand      %%mm7, %%mm3     \n\t"
-            "psrlq        $6, %%mm1     \n\t"
-            "psrlq        $6, %%mm4     \n\t"
-            "pand      %%mm6, %%mm1     \n\t"
-            "pand      %%mm6, %%mm4     \n\t"
-            "psrlq       $19, %%mm2     \n\t"
-            "psrlq       $19, %%mm5     \n\t"
-            "pand         %2, %%mm2     \n\t"
-            "pand         %2, %%mm5     \n\t"
-            "por       %%mm1, %%mm0     \n\t"
-            "por       %%mm4, %%mm3     \n\t"
-            "por       %%mm2, %%mm0     \n\t"
-            "por       %%mm5, %%mm3     \n\t"
-            "psllq       $16, %%mm3     \n\t"
-            "por       %%mm3, %%mm0     \n\t"
-            MOVNTQ"    %%mm0, %0        \n\t"
-            :"=m"(*d):"m"(*s),"m"(blue_15mask):"memory");
-        d += 4;
-        s += 12;
-    }
-    __asm__ volatile(SFENCE:::"memory");
-    __asm__ volatile(EMMS:::"memory");
-#endif
     while (s < end) {
         const int r = *s++;
         const int g = *s++;
@@ -887,104 +248,12 @@ static inline void RENAME(rgb24to15)(const uint8_t *src, uint8_t *dst, long src_
        |
    original bits
 */
-static inline void RENAME(rgb15tobgr24)(const uint8_t *src, uint8_t *dst, long src_size)
+static inline void rgb15tobgr24_c(const uint8_t *src, uint8_t *dst, long src_size)
 {
     const uint16_t *end;
-#if HAVE_MMX
-    const uint16_t *mm_end;
-#endif
     uint8_t *d = dst;
     const uint16_t *s = (const uint16_t*)src;
     end = s + src_size/2;
-#if HAVE_MMX
-    __asm__ volatile(PREFETCH"    %0"::"m"(*s):"memory");
-    mm_end = end - 7;
-    while (s < mm_end) {
-        __asm__ volatile(
-            PREFETCH"    32%1           \n\t"
-            "movq          %1, %%mm0    \n\t"
-            "movq          %1, %%mm1    \n\t"
-            "movq          %1, %%mm2    \n\t"
-            "pand          %2, %%mm0    \n\t"
-            "pand          %3, %%mm1    \n\t"
-            "pand          %4, %%mm2    \n\t"
-            "psllq         $3, %%mm0    \n\t"
-            "psrlq         $2, %%mm1    \n\t"
-            "psrlq         $7, %%mm2    \n\t"
-            "movq       %%mm0, %%mm3    \n\t"
-            "movq       %%mm1, %%mm4    \n\t"
-            "movq       %%mm2, %%mm5    \n\t"
-            "punpcklwd     %5, %%mm0    \n\t"
-            "punpcklwd     %5, %%mm1    \n\t"
-            "punpcklwd     %5, %%mm2    \n\t"
-            "punpckhwd     %5, %%mm3    \n\t"
-            "punpckhwd     %5, %%mm4    \n\t"
-            "punpckhwd     %5, %%mm5    \n\t"
-            "psllq         $8, %%mm1    \n\t"
-            "psllq        $16, %%mm2    \n\t"
-            "por        %%mm1, %%mm0    \n\t"
-            "por        %%mm2, %%mm0    \n\t"
-            "psllq         $8, %%mm4    \n\t"
-            "psllq        $16, %%mm5    \n\t"
-            "por        %%mm4, %%mm3    \n\t"
-            "por        %%mm5, %%mm3    \n\t"
-
-            "movq       %%mm0, %%mm6    \n\t"
-            "movq       %%mm3, %%mm7    \n\t"
-
-            "movq         8%1, %%mm0    \n\t"
-            "movq         8%1, %%mm1    \n\t"
-            "movq         8%1, %%mm2    \n\t"
-            "pand          %2, %%mm0    \n\t"
-            "pand          %3, %%mm1    \n\t"
-            "pand          %4, %%mm2    \n\t"
-            "psllq         $3, %%mm0    \n\t"
-            "psrlq         $2, %%mm1    \n\t"
-            "psrlq         $7, %%mm2    \n\t"
-            "movq       %%mm0, %%mm3    \n\t"
-            "movq       %%mm1, %%mm4    \n\t"
-            "movq       %%mm2, %%mm5    \n\t"
-            "punpcklwd     %5, %%mm0    \n\t"
-            "punpcklwd     %5, %%mm1    \n\t"
-            "punpcklwd     %5, %%mm2    \n\t"
-            "punpckhwd     %5, %%mm3    \n\t"
-            "punpckhwd     %5, %%mm4    \n\t"
-            "punpckhwd     %5, %%mm5    \n\t"
-            "psllq         $8, %%mm1    \n\t"
-            "psllq        $16, %%mm2    \n\t"
-            "por        %%mm1, %%mm0    \n\t"
-            "por        %%mm2, %%mm0    \n\t"
-            "psllq         $8, %%mm4    \n\t"
-            "psllq        $16, %%mm5    \n\t"
-            "por        %%mm4, %%mm3    \n\t"
-            "por        %%mm5, %%mm3    \n\t"
-
-            :"=m"(*d)
-            :"m"(*s),"m"(mask15b),"m"(mask15g),"m"(mask15r), "m"(mmx_null)
-            :"memory");
-        /* borrowed 32 to 24 */
-        __asm__ volatile(
-            "movq       %%mm0, %%mm4    \n\t"
-            "movq       %%mm3, %%mm5    \n\t"
-            "movq       %%mm6, %%mm0    \n\t"
-            "movq       %%mm7, %%mm1    \n\t"
-
-            "movq       %%mm4, %%mm6    \n\t"
-            "movq       %%mm5, %%mm7    \n\t"
-            "movq       %%mm0, %%mm2    \n\t"
-            "movq       %%mm1, %%mm3    \n\t"
-
-            STORE_BGR24_MMX
-
-            :"=m"(*d)
-            :"m"(*s)
-            :"memory");
-        d += 24;
-        s += 8;
-    }
-    __asm__ volatile(SFENCE:::"memory");
-    __asm__ volatile(EMMS:::"memory");
-#endif
     while (s < end) {
         register uint16_t bgr;
         bgr = *s++;
@@ -994,103 +263,12 @@ static inline void RENAME(rgb15tobgr24)(const uint8_t *src, uint8_t *dst, long s
     }
 }
 
-static inline void RENAME(rgb16tobgr24)(const uint8_t *src, uint8_t *dst, long src_size)
+static inline void rgb16tobgr24_c(const uint8_t *src, uint8_t *dst, long src_size)
 {
     const uint16_t *end;
-#if HAVE_MMX
-    const uint16_t *mm_end;
-#endif
     uint8_t *d = (uint8_t *)dst;
     const uint16_t *s = (const uint16_t *)src;
     end = s + src_size/2;
-#if HAVE_MMX
-    __asm__ volatile(PREFETCH"    %0"::"m"(*s):"memory");
-    mm_end = end - 7;
-    while (s < mm_end) {
-        __asm__ volatile(
-            PREFETCH"    32%1           \n\t"
-            "movq          %1, %%mm0    \n\t"
-            "movq          %1, %%mm1    \n\t"
-            "movq          %1, %%mm2    \n\t"
-            "pand          %2, %%mm0    \n\t"
-            "pand          %3, %%mm1    \n\t"
-            "pand          %4, %%mm2    \n\t"
-            "psllq         $3, %%mm0    \n\t"
-            "psrlq         $3, %%mm1    \n\t"
-            "psrlq         $8, %%mm2    \n\t"
-            "movq       %%mm0, %%mm3    \n\t"
-            "movq       %%mm1, %%mm4    \n\t"
-            "movq       %%mm2, %%mm5    \n\t"
-            "punpcklwd     %5, %%mm0    \n\t"
-            "punpcklwd     %5, %%mm1    \n\t"
-            "punpcklwd     %5, %%mm2    \n\t"
-            "punpckhwd     %5, %%mm3    \n\t"
-            "punpckhwd     %5, %%mm4    \n\t"
-            "punpckhwd     %5, %%mm5    \n\t"
-            "psllq         $8, %%mm1    \n\t"
-            "psllq        $16, %%mm2    \n\t"
-            "por        %%mm1, %%mm0    \n\t"
-            "por        %%mm2, %%mm0    \n\t"
-            "psllq         $8, %%mm4    \n\t"
-            "psllq        $16, %%mm5    \n\t"
-            "por        %%mm4, %%mm3    \n\t"
-            "por        %%mm5, %%mm3    \n\t"
-
-            "movq       %%mm0, %%mm6    \n\t"
-            "movq       %%mm3, %%mm7    \n\t"
-
-            "movq         8%1, %%mm0    \n\t"
-            "movq         8%1, %%mm1    \n\t"
-            "movq         8%1, %%mm2    \n\t"
-            "pand          %2, %%mm0    \n\t"
-            "pand          %3, %%mm1    \n\t"
-            "pand          %4, %%mm2    \n\t"
-            "psllq         $3, %%mm0    \n\t"
-            "psrlq         $3, %%mm1    \n\t"
-            "psrlq         $8, %%mm2    \n\t"
-            "movq       %%mm0, %%mm3    \n\t"
-            "movq       %%mm1, %%mm4    \n\t"
-            "movq       %%mm2, %%mm5    \n\t"
-            "punpcklwd     %5, %%mm0    \n\t"
-            "punpcklwd     %5, %%mm1    \n\t"
-            "punpcklwd     %5, %%mm2    \n\t"
-            "punpckhwd     %5, %%mm3    \n\t"
-            "punpckhwd     %5, %%mm4    \n\t"
-            "punpckhwd     %5, %%mm5    \n\t"
-            "psllq         $8, %%mm1    \n\t"
-            "psllq        $16, %%mm2    \n\t"
-            "por        %%mm1, %%mm0    \n\t"
-            "por        %%mm2, %%mm0    \n\t"
-            "psllq         $8, %%mm4    \n\t"
-            "psllq        $16, %%mm5    \n\t"
-            "por        %%mm4, %%mm3    \n\t"
-            "por        %%mm5, %%mm3    \n\t"
-            :"=m"(*d)
-            :"m"(*s),"m"(mask16b),"m"(mask16g),"m"(mask16r),"m"(mmx_null)
-            :"memory");
-        /* borrowed 32 to 24 */
-        __asm__ volatile(
-            "movq       %%mm0, %%mm4    \n\t"
-            "movq       %%mm3, %%mm5    \n\t"
-            "movq       %%mm6, %%mm0    \n\t"
-            "movq       %%mm7, %%mm1    \n\t"
-
-            "movq       %%mm4, %%mm6    \n\t"
-            "movq       %%mm5, %%mm7    \n\t"
-            "movq       %%mm0, %%mm2    \n\t"
-            "movq       %%mm1, %%mm3    \n\t"
-
-            STORE_BGR24_MMX
-
-            :"=m"(*d)
-            :"m"(*s)
-            :"memory");
-        d += 24;
-        s += 8;
-    }
-    __asm__ volatile(SFENCE:::"memory");
-    __asm__ volatile(EMMS:::"memory");
-#endif
     while (s < end) {
         register uint16_t bgr;
         bgr = *s++;
@@ -1119,42 +297,12 @@ static inline void RENAME(rgb16tobgr24)(const uint8_t *src, uint8_t *dst, long s
     MOVNTQ"     %%mm0,  %0      \n\t"                               \
     MOVNTQ"     %%mm3, 8%0      \n\t"                               \
 
-static inline void RENAME(rgb15to32)(const uint8_t *src, uint8_t *dst, long src_size)
+static inline void rgb15to32_c(const uint8_t *src, uint8_t *dst, long src_size)
 {
     const uint16_t *end;
-#if HAVE_MMX
-    const uint16_t *mm_end;
-#endif
     uint8_t *d = dst;
     const uint16_t *s = (const uint16_t *)src;
     end = s + src_size/2;
-#if HAVE_MMX
-    __asm__ volatile(PREFETCH"    %0"::"m"(*s):"memory");
-    __asm__ volatile("pxor    %%mm7,%%mm7    \n\t":::"memory");
-    __asm__ volatile("pcmpeqd %%mm6,%%mm6    \n\t":::"memory");
-    mm_end = end - 3;
-    while (s < mm_end) {
-        __asm__ volatile(
-            PREFETCH"    32%1           \n\t"
-            "movq          %1, %%mm0    \n\t"
-            "movq          %1, %%mm1    \n\t"
-            "movq          %1, %%mm2    \n\t"
-            "pand          %2, %%mm0    \n\t"
-            "pand          %3, %%mm1    \n\t"
-            "pand          %4, %%mm2    \n\t"
-            "psllq         $3, %%mm0    \n\t"
-            "psrlq         $2, %%mm1    \n\t"
-            "psrlq         $7, %%mm2    \n\t"
-            PACK_RGB32
-            :"=m"(*d)
-            :"m"(*s),"m"(mask15b),"m"(mask15g),"m"(mask15r)
-            :"memory");
-        d += 16;
-        s += 4;
-    }
-    __asm__ volatile(SFENCE:::"memory");
-    __asm__ volatile(EMMS:::"memory");
-#endif
     while (s < end) {
         register uint16_t bgr;
         bgr = *s++;
@@ -1172,42 +320,12 @@ static inline void RENAME(rgb15to32)(const uint8_t *src, uint8_t *dst, long src_
     }
 }
 
-static inline void RENAME(rgb16to32)(const uint8_t *src, uint8_t *dst, long src_size)
+static inline void rgb16to32_c(const uint8_t *src, uint8_t *dst, long src_size)
 {
     const uint16_t *end;
-#if HAVE_MMX
-    const uint16_t *mm_end;
-#endif
     uint8_t *d = dst;
     const uint16_t *s = (const uint16_t*)src;
     end = s + src_size/2;
-#if HAVE_MMX
-    __asm__ volatile(PREFETCH"    %0"::"m"(*s):"memory");
-    __asm__ volatile("pxor    %%mm7,%%mm7    \n\t":::"memory");
-    __asm__ volatile("pcmpeqd %%mm6,%%mm6    \n\t":::"memory");
-    mm_end = end - 3;
-    while (s < mm_end) {
-        __asm__ volatile(
-            PREFETCH"    32%1           \n\t"
-            "movq          %1, %%mm0    \n\t"
-            "movq          %1, %%mm1    \n\t"
-            "movq          %1, %%mm2    \n\t"
-            "pand          %2, %%mm0    \n\t"
-            "pand          %3, %%mm1    \n\t"
-            "pand          %4, %%mm2    \n\t"
-            "psllq         $3, %%mm0    \n\t"
-            "psrlq         $3, %%mm1    \n\t"
-            "psrlq         $8, %%mm2    \n\t"
-            PACK_RGB32
-            :"=m"(*d)
-            :"m"(*s),"m"(mask16b),"m"(mask16g),"m"(mask16r)
-            :"memory");
-        d += 16;
-        s += 4;
-    }
-    __asm__ volatile(SFENCE:::"memory");
-    __asm__ volatile(EMMS:::"memory");
-#endif
     while (s < end) {
         register uint16_t bgr;
         bgr = *s++;
@@ -1225,63 +343,11 @@ static inline void RENAME(rgb16to32)(const uint8_t *src, uint8_t *dst, long src_
     }
 }
 
-static inline void RENAME(rgb32tobgr32)(const uint8_t *src, uint8_t *dst, long src_size)
+static inline void shuffle_bytes_2103_c(const uint8_t *src, uint8_t *dst, long src_size)
 {
-    x86_reg idx = 15 - src_size;
+    int idx = 15 - src_size;
     const uint8_t *s = src-idx;
     uint8_t *d = dst-idx;
-#if HAVE_MMX
-    __asm__ volatile(
-        "test          %0, %0           \n\t"
-        "jns           2f               \n\t"
-        PREFETCH"       (%1, %0)        \n\t"
-        "movq          %3, %%mm7        \n\t"
-        "pxor          %4, %%mm7        \n\t"
-        "movq       %%mm7, %%mm6        \n\t"
-        "pxor          %5, %%mm7        \n\t"
-        ASMALIGN(4)
-        "1:                             \n\t"
-        PREFETCH"     32(%1, %0)        \n\t"
-        "movq           (%1, %0), %%mm0 \n\t"
-        "movq          8(%1, %0), %%mm1 \n\t"
-# if HAVE_MMX2
-        "pshufw      $177, %%mm0, %%mm3 \n\t"
-        "pshufw      $177, %%mm1, %%mm5 \n\t"
-        "pand       %%mm7, %%mm0        \n\t"
-        "pand       %%mm6, %%mm3        \n\t"
-        "pand       %%mm7, %%mm1        \n\t"
-        "pand       %%mm6, %%mm5        \n\t"
-        "por        %%mm3, %%mm0        \n\t"
-        "por        %%mm5, %%mm1        \n\t"
-# else
-        "movq       %%mm0, %%mm2        \n\t"
-        "movq       %%mm1, %%mm4        \n\t"
-        "pand       %%mm7, %%mm0        \n\t"
-        "pand       %%mm6, %%mm2        \n\t"
-        "pand       %%mm7, %%mm1        \n\t"
-        "pand       %%mm6, %%mm4        \n\t"
-        "movq       %%mm2, %%mm3        \n\t"
-        "movq       %%mm4, %%mm5        \n\t"
-        "pslld        $16, %%mm2        \n\t"
-        "psrld        $16, %%mm3        \n\t"
-        "pslld        $16, %%mm4        \n\t"
-        "psrld        $16, %%mm5        \n\t"
-        "por        %%mm2, %%mm0        \n\t"
-        "por        %%mm4, %%mm1        \n\t"
-        "por        %%mm3, %%mm0        \n\t"
-        "por        %%mm5, %%mm1        \n\t"
-# endif
-        MOVNTQ"     %%mm0,  (%2, %0)    \n\t"
-        MOVNTQ"     %%mm1, 8(%2, %0)    \n\t"
-        "add          $16, %0           \n\t"
-        "js            1b               \n\t"
-        SFENCE"                         \n\t"
-        EMMS"                           \n\t"
-        "2:                             \n\t"
-        : "+&r"(idx)
-        : "r" (s), "r" (d), "m" (mask32b), "m" (mask32r), "m" (mmx_one)
-        : "memory");
-#endif
     for (; idx<15; idx+=4) {
         register int v = *(const uint32_t *)&s[idx], g = v & 0xff00ff00;
         v &= 0xff00ff;
@@ -1289,66 +355,9 @@ static inline void RENAME(rgb32tobgr32)(const uint8_t *src, uint8_t *dst, long s
     }
 }
 
-static inline void RENAME(rgb24tobgr24)(const uint8_t *src, uint8_t *dst, long src_size)
+static inline void rgb24tobgr24_c(const uint8_t *src, uint8_t *dst, long src_size)
 {
     unsigned i;
-#if HAVE_MMX
-    x86_reg mmx_size= 23 - src_size;
-    __asm__ volatile (
-        "test             %%"REG_a", %%"REG_a"          \n\t"
-        "jns                     2f                     \n\t"
-        "movq     "MANGLE(mask24r)", %%mm5              \n\t"
-        "movq     "MANGLE(mask24g)", %%mm6              \n\t"
-        "movq     "MANGLE(mask24b)", %%mm7              \n\t"
-        ASMALIGN(4)
-        "1:                                             \n\t"
-        PREFETCH" 32(%1, %%"REG_a")                     \n\t"
-        "movq       (%1, %%"REG_a"), %%mm0              \n\t" // BGR BGR BG
-        "movq       (%1, %%"REG_a"), %%mm1              \n\t" // BGR BGR BG
-        "movq      2(%1, %%"REG_a"), %%mm2              \n\t" // R BGR BGR B
-        "psllq                  $16, %%mm0              \n\t" // 00 BGR BGR
-        "pand                 %%mm5, %%mm0              \n\t"
-        "pand                 %%mm6, %%mm1              \n\t"
-        "pand                 %%mm7, %%mm2              \n\t"
-        "por                  %%mm0, %%mm1              \n\t"
-        "por                  %%mm2, %%mm1              \n\t"
-        "movq      6(%1, %%"REG_a"), %%mm0              \n\t" // BGR BGR BG
-        MOVNTQ"               %%mm1,   (%2, %%"REG_a")  \n\t" // RGB RGB RG
-        "movq      8(%1, %%"REG_a"), %%mm1              \n\t" // R BGR BGR B
-        "movq     10(%1, %%"REG_a"), %%mm2              \n\t" // GR BGR BGR
-        "pand                 %%mm7, %%mm0              \n\t"
-        "pand                 %%mm5, %%mm1              \n\t"
-        "pand                 %%mm6, %%mm2              \n\t"
-        "por                  %%mm0, %%mm1              \n\t"
-        "por                  %%mm2, %%mm1              \n\t"
-        "movq     14(%1, %%"REG_a"), %%mm0              \n\t" // R BGR BGR B
-        MOVNTQ"               %%mm1,  8(%2, %%"REG_a")  \n\t" // B RGB RGB R
-        "movq     16(%1, %%"REG_a"), %%mm1              \n\t" // GR BGR BGR
-        "movq     18(%1, %%"REG_a"), %%mm2              \n\t" // BGR BGR BG
-        "pand                 %%mm6, %%mm0              \n\t"
-        "pand                 %%mm7, %%mm1              \n\t"
-        "pand                 %%mm5, %%mm2              \n\t"
-        "por                  %%mm0, %%mm1              \n\t"
-        "por                  %%mm2, %%mm1              \n\t"
-        MOVNTQ"               %%mm1, 16(%2, %%"REG_a")  \n\t"
-        "add                    $24, %%"REG_a"          \n\t"
-        " js                     1b                     \n\t"
-        "2:                                             \n\t"
-        : "+a" (mmx_size)
-        : "r" (src-mmx_size), "r"(dst-mmx_size)
-    );
-
-    __asm__ volatile(SFENCE:::"memory");
-    __asm__ volatile(EMMS:::"memory");
-
-    if (mmx_size==23) return; //finished, was multiple of 8
-
-    src+= src_size;
-    dst+= src_size;
-    src_size= 23-mmx_size;
-    src-= src_size;
-    dst-= src_size;
-#endif
     for (i=0; i<src_size; i+=3) {
         register uint8_t x;
         x          = src[i + 2];
@@ -1358,98 +367,16 @@ static inline void RENAME(rgb24tobgr24)(const uint8_t *src, uint8_t *dst, long s
     }
 }
 
-static inline void RENAME(yuvPlanartoyuy2)(const uint8_t *ysrc, const uint8_t *usrc, const uint8_t *vsrc, uint8_t *dst,
-                                           long width, long height,
-                                           long lumStride, long chromStride, long dstStride, long vertLumPerChroma)
+static inline void yuvPlanartoyuy2_c(const uint8_t *ysrc, const uint8_t *usrc,
+                                     const uint8_t *vsrc, uint8_t *dst,
+                                     long width, long height,
+                                     long lumStride, long chromStride,
+                                     long dstStride, long vertLumPerChroma)
 {
     long y;
-    const x86_reg chromWidth= width>>1;
+    const int chromWidth = width >> 1;
     for (y=0; y<height; y++) {
-#if HAVE_MMX
-        //FIXME handle 2 lines at once (fewer prefetches, reuse some chroma, but very likely memory-limited anyway)
-        __asm__ volatile(
-            "xor                 %%"REG_a", %%"REG_a"   \n\t"
-            ASMALIGN(4)
-            "1:                                         \n\t"
-            PREFETCH"    32(%1, %%"REG_a", 2)           \n\t"
-            PREFETCH"    32(%2, %%"REG_a")              \n\t"
-            PREFETCH"    32(%3, %%"REG_a")              \n\t"
-            "movq          (%2, %%"REG_a"), %%mm0       \n\t" // U(0)
-            "movq                    %%mm0, %%mm2       \n\t" // U(0)
-            "movq          (%3, %%"REG_a"), %%mm1       \n\t" // V(0)
-            "punpcklbw               %%mm1, %%mm0       \n\t" // UVUV UVUV(0)
-            "punpckhbw               %%mm1, %%mm2       \n\t" // UVUV UVUV(8)
-
-            "movq        (%1, %%"REG_a",2), %%mm3       \n\t" // Y(0)
-            "movq       8(%1, %%"REG_a",2), %%mm5       \n\t" // Y(8)
-            "movq                    %%mm3, %%mm4       \n\t" // Y(0)
-            "movq                    %%mm5, %%mm6       \n\t" // Y(8)
-            "punpcklbw               %%mm0, %%mm3       \n\t" // YUYV YUYV(0)
-            "punpckhbw               %%mm0, %%mm4       \n\t" // YUYV YUYV(4)
-            "punpcklbw               %%mm2, %%mm5       \n\t" // YUYV YUYV(8)
-            "punpckhbw               %%mm2, %%mm6       \n\t" // YUYV YUYV(12)
-
-            MOVNTQ"                  %%mm3,   (%0, %%"REG_a", 4)    \n\t"
-            MOVNTQ"                  %%mm4,  8(%0, %%"REG_a", 4)    \n\t"
-            MOVNTQ"                  %%mm5, 16(%0, %%"REG_a", 4)    \n\t"
-            MOVNTQ"                  %%mm6, 24(%0, %%"REG_a", 4)    \n\t"
-
-            "add                        $8, %%"REG_a"   \n\t"
-            "cmp                        %4, %%"REG_a"   \n\t"
-            " jb                        1b              \n\t"
-            ::"r"(dst), "r"(ysrc), "r"(usrc), "r"(vsrc), "g" (chromWidth)
-            : "%"REG_a
-        );
-#else
-
-#if ARCH_ALPHA && HAVE_MVI
-#define pl2yuy2(n)                  \
-    y1 = yc[n];                     \
-    y2 = yc2[n];                    \
-    u = uc[n];                      \
-    v = vc[n];                      \
-    __asm__("unpkbw %1, %0" : "=r"(y1) : "r"(y1));  \
-    __asm__("unpkbw %1, %0" : "=r"(y2) : "r"(y2));  \
-    __asm__("unpkbl %1, %0" : "=r"(u) : "r"(u));    \
-    __asm__("unpkbl %1, %0" : "=r"(v) : "r"(v));    \
-    yuv1 = (u << 8) + (v << 24);                \
-    yuv2 = yuv1 + y2;               \
-    yuv1 += y1;                     \
-    qdst[n]  = yuv1;                \
-    qdst2[n] = yuv2;
-
-        int i;
-        uint64_t *qdst = (uint64_t *) dst;
-        uint64_t *qdst2 = (uint64_t *) (dst + dstStride);
-        const uint32_t *yc = (uint32_t *) ysrc;
-        const uint32_t *yc2 = (uint32_t *) (ysrc + lumStride);
-        const uint16_t *uc = (uint16_t*) usrc, *vc = (uint16_t*) vsrc;
-        for (i = 0; i < chromWidth; i += 8) {
-            uint64_t y1, y2, yuv1, yuv2;
-            uint64_t u, v;
-            /* Prefetch */
-            __asm__("ldq $31,64(%0)" :: "r"(yc));
-            __asm__("ldq $31,64(%0)" :: "r"(yc2));
-            __asm__("ldq $31,64(%0)" :: "r"(uc));
-            __asm__("ldq $31,64(%0)" :: "r"(vc));
-
-            pl2yuy2(0);
-            pl2yuy2(1);
-            pl2yuy2(2);
-            pl2yuy2(3);
-
-            yc    += 4;
-            yc2   += 4;
-            uc    += 4;
-            vc    += 4;
-            qdst  += 4;
-            qdst2 += 4;
-        }
-        y++;
-        ysrc += lumStride;
-        dst += dstStride;
-
-#elif HAVE_FAST_64BIT
+#if HAVE_FAST_64BIT
         int i;
         uint64_t *ldst = (uint64_t *) dst;
         const uint8_t *yc = ysrc, *uc = usrc, *vc = vsrc;
@@ -1481,7 +408,6 @@ static inline void RENAME(yuvPlanartoyuy2)(const uint8_t *ysrc, const uint8_t *u
             vc++;
         }
 #endif
-#endif
         if ((y&(vertLumPerChroma-1)) == vertLumPerChroma-1) {
             usrc += chromStride;
             vsrc += chromStride;
@@ -1489,70 +415,32 @@ static inline void RENAME(yuvPlanartoyuy2)(const uint8_t *ysrc, const uint8_t *u
         ysrc += lumStride;
         dst  += dstStride;
     }
-#if HAVE_MMX
-    __asm__(EMMS"       \n\t"
-            SFENCE"     \n\t"
-            :::"memory");
-#endif
 }
 
 /**
  * Height should be a multiple of 2 and width should be a multiple of 16.
  * (If this is a problem for anyone then tell me, and I will fix it.)
  */
-static inline void RENAME(yv12toyuy2)(const uint8_t *ysrc, const uint8_t *usrc, const uint8_t *vsrc, uint8_t *dst,
-                                      long width, long height,
-                                      long lumStride, long chromStride, long dstStride)
+static inline void yv12toyuy2_c(const uint8_t *ysrc, const uint8_t *usrc,
+                                const uint8_t *vsrc, uint8_t *dst,
+                                long width, long height,
+                                long lumStride, long chromStride,
+                                long dstStride)
 {
     //FIXME interpolate chroma
-    RENAME(yuvPlanartoyuy2)(ysrc, usrc, vsrc, dst, width, height, lumStride, chromStride, dstStride, 2);
+    yuvPlanartoyuy2_c(ysrc, usrc, vsrc, dst, width, height, lumStride,
+                      chromStride, dstStride, 2);
 }
 
-static inline void RENAME(yuvPlanartouyvy)(const uint8_t *ysrc, const uint8_t *usrc, const uint8_t *vsrc, uint8_t *dst,
-                                           long width, long height,
-                                           long lumStride, long chromStride, long dstStride, long vertLumPerChroma)
+static inline void yuvPlanartouyvy_c(const uint8_t *ysrc, const uint8_t *usrc,
+                                     const uint8_t *vsrc, uint8_t *dst,
+                                     long width, long height,
+                                     long lumStride, long chromStride,
+                                     long dstStride, long vertLumPerChroma)
 {
     long y;
-    const x86_reg chromWidth= width>>1;
+    const int chromWidth = width >> 1;
     for (y=0; y<height; y++) {
-#if HAVE_MMX
-        //FIXME handle 2 lines at once (fewer prefetches, reuse some chroma, but very likely memory-limited anyway)
-        __asm__ volatile(
-            "xor                %%"REG_a", %%"REG_a"    \n\t"
-            ASMALIGN(4)
-            "1:                                         \n\t"
-            PREFETCH"   32(%1, %%"REG_a", 2)            \n\t"
-            PREFETCH"   32(%2, %%"REG_a")               \n\t"
-            PREFETCH"   32(%3, %%"REG_a")               \n\t"
-            "movq         (%2, %%"REG_a"), %%mm0        \n\t" // U(0)
-            "movq                   %%mm0, %%mm2        \n\t" // U(0)
-            "movq         (%3, %%"REG_a"), %%mm1        \n\t" // V(0)
-            "punpcklbw              %%mm1, %%mm0        \n\t" // UVUV UVUV(0)
-            "punpckhbw              %%mm1, %%mm2        \n\t" // UVUV UVUV(8)
-
-            "movq       (%1, %%"REG_a",2), %%mm3        \n\t" // Y(0)
-            "movq      8(%1, %%"REG_a",2), %%mm5        \n\t" // Y(8)
-            "movq                   %%mm0, %%mm4        \n\t" // Y(0)
-            "movq                   %%mm2, %%mm6        \n\t" // Y(8)
-            "punpcklbw              %%mm3, %%mm0        \n\t" // YUYV YUYV(0)
-            "punpckhbw              %%mm3, %%mm4        \n\t" // YUYV YUYV(4)
-            "punpcklbw              %%mm5, %%mm2        \n\t" // YUYV YUYV(8)
-            "punpckhbw              %%mm5, %%mm6        \n\t" // YUYV YUYV(12)
-
-            MOVNTQ"                 %%mm0,   (%0, %%"REG_a", 4)     \n\t"
-            MOVNTQ"                 %%mm4,  8(%0, %%"REG_a", 4)     \n\t"
-            MOVNTQ"                 %%mm2, 16(%0, %%"REG_a", 4)     \n\t"
-            MOVNTQ"                 %%mm6, 24(%0, %%"REG_a", 4)     \n\t"
-
-            "add                       $8, %%"REG_a"    \n\t"
-            "cmp                       %4, %%"REG_a"    \n\t"
-            " jb                       1b               \n\t"
-            ::"r"(dst), "r"(ysrc), "r"(usrc), "r"(vsrc), "g" (chromWidth)
-            : "%"REG_a
-        );
-#else
-//FIXME adapt the Alpha ASM code from yv12->yuy2
-
 #if HAVE_FAST_64BIT
         int i;
         uint64_t *ldst = (uint64_t *) dst;
@@ -1585,7 +473,6 @@ static inline void RENAME(yuvPlanartouyvy)(const uint8_t *ysrc, const uint8_t *u
             vc++;
         }
 #endif
-#endif
         if ((y&(vertLumPerChroma-1)) == vertLumPerChroma-1) {
             usrc += chromStride;
             vsrc += chromStride;
@@ -1593,139 +480,62 @@ static inline void RENAME(yuvPlanartouyvy)(const uint8_t *ysrc, const uint8_t *u
         ysrc += lumStride;
         dst += dstStride;
     }
-#if HAVE_MMX
-    __asm__(EMMS"       \n\t"
-            SFENCE"     \n\t"
-            :::"memory");
-#endif
 }
 
 /**
  * Height should be a multiple of 2 and width should be a multiple of 16
  * (If this is a problem for anyone then tell me, and I will fix it.)
  */
-static inline void RENAME(yv12touyvy)(const uint8_t *ysrc, const uint8_t *usrc, const uint8_t *vsrc, uint8_t *dst,
-                                      long width, long height,
-                                      long lumStride, long chromStride, long dstStride)
+static inline void yv12touyvy_c(const uint8_t *ysrc, const uint8_t *usrc,
+                                const uint8_t *vsrc, uint8_t *dst,
+                                long width, long height,
+                                long lumStride, long chromStride,
+                                long dstStride)
 {
     //FIXME interpolate chroma
-    RENAME(yuvPlanartouyvy)(ysrc, usrc, vsrc, dst, width, height, lumStride, chromStride, dstStride, 2);
+    yuvPlanartouyvy_c(ysrc, usrc, vsrc, dst, width, height, lumStride,
+                      chromStride, dstStride, 2);
 }
 
 /**
  * Width should be a multiple of 16.
  */
-static inline void RENAME(yuv422ptouyvy)(const uint8_t *ysrc, const uint8_t *usrc, const uint8_t *vsrc, uint8_t *dst,
-                                         long width, long height,
-                                         long lumStride, long chromStride, long dstStride)
+static inline void yuv422ptouyvy_c(const uint8_t *ysrc, const uint8_t *usrc,
+                                   const uint8_t *vsrc, uint8_t *dst,
+                                   long width, long height,
+                                   long lumStride, long chromStride,
+                                   long dstStride)
 {
-    RENAME(yuvPlanartouyvy)(ysrc, usrc, vsrc, dst, width, height, lumStride, chromStride, dstStride, 1);
+    yuvPlanartouyvy_c(ysrc, usrc, vsrc, dst, width, height, lumStride,
+                      chromStride, dstStride, 1);
 }
 
 /**
  * Width should be a multiple of 16.
  */
-static inline void RENAME(yuv422ptoyuy2)(const uint8_t *ysrc, const uint8_t *usrc, const uint8_t *vsrc, uint8_t *dst,
-                                         long width, long height,
-                                         long lumStride, long chromStride, long dstStride)
+static inline void yuv422ptoyuy2_c(const uint8_t *ysrc, const uint8_t *usrc,
+                                   const uint8_t *vsrc, uint8_t *dst,
+                                   long width, long height,
+                                   long lumStride, long chromStride,
+                                   long dstStride)
 {
-    RENAME(yuvPlanartoyuy2)(ysrc, usrc, vsrc, dst, width, height, lumStride, chromStride, dstStride, 1);
+    yuvPlanartoyuy2_c(ysrc, usrc, vsrc, dst, width, height, lumStride,
+                      chromStride, dstStride, 1);
 }
 
 /**
  * Height should be a multiple of 2 and width should be a multiple of 16.
  * (If this is a problem for anyone then tell me, and I will fix it.)
  */
-static inline void RENAME(yuy2toyv12)(const uint8_t *src, uint8_t *ydst, uint8_t *udst, uint8_t *vdst,
-                                      long width, long height,
-                                      long lumStride, long chromStride, long srcStride)
+static inline void yuy2toyv12_c(const uint8_t *src, uint8_t *ydst,
+                                uint8_t *udst, uint8_t *vdst,
+                                long width, long height,
+                                long lumStride, long chromStride,
+                                long srcStride)
 {
     long y;
-    const x86_reg chromWidth= width>>1;
+    const int chromWidth = width >> 1;
     for (y=0; y<height; y+=2) {
-#if HAVE_MMX
-        __asm__ volatile(
-            "xor                 %%"REG_a", %%"REG_a"   \n\t"
-            "pcmpeqw                 %%mm7, %%mm7       \n\t"
-            "psrlw                      $8, %%mm7       \n\t" // FF,00,FF,00...
-            ASMALIGN(4)
-            "1:                \n\t"
-            PREFETCH" 64(%0, %%"REG_a", 4)              \n\t"
-            "movq       (%0, %%"REG_a", 4), %%mm0       \n\t" // YUYV YUYV(0)
-            "movq      8(%0, %%"REG_a", 4), %%mm1       \n\t" // YUYV YUYV(4)
-            "movq                    %%mm0, %%mm2       \n\t" // YUYV YUYV(0)
-            "movq                    %%mm1, %%mm3       \n\t" // YUYV YUYV(4)
-            "psrlw                      $8, %%mm0       \n\t" // U0V0 U0V0(0)
-            "psrlw                      $8, %%mm1       \n\t" // U0V0 U0V0(4)
-            "pand                    %%mm7, %%mm2       \n\t" // Y0Y0 Y0Y0(0)
-            "pand                    %%mm7, %%mm3       \n\t" // Y0Y0 Y0Y0(4)
-            "packuswb                %%mm1, %%mm0       \n\t" // UVUV UVUV(0)
-            "packuswb                %%mm3, %%mm2       \n\t" // YYYY YYYY(0)
-
-            MOVNTQ"                  %%mm2, (%1, %%"REG_a", 2)  \n\t"
-
-            "movq     16(%0, %%"REG_a", 4), %%mm1       \n\t" // YUYV YUYV(8)
-            "movq     24(%0, %%"REG_a", 4), %%mm2       \n\t" // YUYV YUYV(12)
-            "movq                    %%mm1, %%mm3       \n\t" // YUYV YUYV(8)
-            "movq                    %%mm2, %%mm4       \n\t" // YUYV YUYV(12)
-            "psrlw                      $8, %%mm1       \n\t" // U0V0 U0V0(8)
-            "psrlw                      $8, %%mm2       \n\t" // U0V0 U0V0(12)
-            "pand                    %%mm7, %%mm3       \n\t" // Y0Y0 Y0Y0(8)
-            "pand                    %%mm7, %%mm4       \n\t" // Y0Y0 Y0Y0(12)
-            "packuswb                %%mm2, %%mm1       \n\t" // UVUV UVUV(8)
-            "packuswb                %%mm4, %%mm3       \n\t" // YYYY YYYY(8)
-
-            MOVNTQ"                  %%mm3, 8(%1, %%"REG_a", 2) \n\t"
-
-            "movq                    %%mm0, %%mm2       \n\t" // UVUV UVUV(0)
-            "movq                    %%mm1, %%mm3       \n\t" // UVUV UVUV(8)
-            "psrlw                      $8, %%mm0       \n\t" // V0V0 V0V0(0)
-            "psrlw                      $8, %%mm1       \n\t" // V0V0 V0V0(8)
-            "pand                    %%mm7, %%mm2       \n\t" // U0U0 U0U0(0)
-            "pand                    %%mm7, %%mm3       \n\t" // U0U0 U0U0(8)
-            "packuswb                %%mm1, %%mm0       \n\t" // VVVV VVVV(0)
-            "packuswb                %%mm3, %%mm2       \n\t" // UUUU UUUU(0)
-
-            MOVNTQ"                  %%mm0, (%3, %%"REG_a")     \n\t"
-            MOVNTQ"                  %%mm2, (%2, %%"REG_a")     \n\t"
-
-            "add                        $8, %%"REG_a"   \n\t"
-            "cmp                        %4, %%"REG_a"   \n\t"
-            " jb                        1b              \n\t"
-            ::"r"(src), "r"(ydst), "r"(udst), "r"(vdst), "g" (chromWidth)
-            : "memory", "%"REG_a
-        );
-
-        ydst += lumStride;
-        src  += srcStride;
-
-        __asm__ volatile(
-            "xor                 %%"REG_a", %%"REG_a"   \n\t"
-            ASMALIGN(4)
-            "1:                                         \n\t"
-            PREFETCH" 64(%0, %%"REG_a", 4)              \n\t"
-            "movq       (%0, %%"REG_a", 4), %%mm0       \n\t" // YUYV YUYV(0)
-            "movq      8(%0, %%"REG_a", 4), %%mm1       \n\t" // YUYV YUYV(4)
-            "movq     16(%0, %%"REG_a", 4), %%mm2       \n\t" // YUYV YUYV(8)
-            "movq     24(%0, %%"REG_a", 4), %%mm3       \n\t" // YUYV YUYV(12)
-            "pand                    %%mm7, %%mm0       \n\t" // Y0Y0 Y0Y0(0)
-            "pand                    %%mm7, %%mm1       \n\t" // Y0Y0 Y0Y0(4)
-            "pand                    %%mm7, %%mm2       \n\t" // Y0Y0 Y0Y0(8)
-            "pand                    %%mm7, %%mm3       \n\t" // Y0Y0 Y0Y0(12)
-            "packuswb                %%mm1, %%mm0       \n\t" // YYYY YYYY(0)
-            "packuswb                %%mm3, %%mm2       \n\t" // YYYY YYYY(8)
-
-            MOVNTQ"                  %%mm0,  (%1, %%"REG_a", 2) \n\t"
-            MOVNTQ"                  %%mm2, 8(%1, %%"REG_a", 2) \n\t"
-
-            "add                        $8, %%"REG_a"   \n\t"
-            "cmp                        %4, %%"REG_a"   \n\t"
-            " jb                        1b              \n\t"
-
-            ::"r"(src), "r"(ydst), "r"(udst), "r"(vdst), "g" (chromWidth)
-            : "memory", "%"REG_a
-        );
-#else
         long i;
         for (i=0; i<chromWidth; i++) {
             ydst[2*i+0]     = src[4*i+0];
@@ -1740,30 +550,15 @@ static inline void RENAME(yuy2toyv12)(const uint8_t *src, uint8_t *ydst, uint8_t
             ydst[2*i+0]     = src[4*i+0];
             ydst[2*i+1]     = src[4*i+2];
         }
-#endif
         udst += chromStride;
         vdst += chromStride;
         ydst += lumStride;
         src  += srcStride;
     }
-#if HAVE_MMX
-    __asm__ volatile(EMMS"       \n\t"
-                     SFENCE"     \n\t"
-                     :::"memory");
-#endif
 }
 
-static inline void RENAME(yvu9toyv12)(const uint8_t *ysrc, const uint8_t *usrc, const uint8_t *vsrc,
-                                      uint8_t *ydst, uint8_t *udst, uint8_t *vdst,
-                                      long width, long height, long lumStride, long chromStride)
-{
-    /* Y Plane */
-    memcpy(ydst, ysrc, width*height);
-
-    /* XXX: implement upscaling for U,V */
-}
-
-static inline void RENAME(planar2x)(const uint8_t *src, uint8_t *dst, long srcWidth, long srcHeight, long srcStride, long dstStride)
+static inline void planar2x_c(const uint8_t *src, uint8_t *dst, long srcWidth,
+                              long srcHeight, long srcStride, long dstStride)
 {
     long x,y;
 
@@ -1779,53 +574,8 @@ static inline void RENAME(planar2x)(const uint8_t *src, uint8_t *dst, long srcWi
     dst+= dstStride;
 
     for (y=1; y<srcHeight; y++) {
-#if HAVE_MMX2 || HAVE_AMD3DNOW
-        const x86_reg mmxSize= srcWidth&~15;
-        __asm__ volatile(
-            "mov           %4, %%"REG_a"            \n\t"
-            "1:                                     \n\t"
-            "movq         (%0, %%"REG_a"), %%mm0    \n\t"
-            "movq         (%1, %%"REG_a"), %%mm1    \n\t"
-            "movq        1(%0, %%"REG_a"), %%mm2    \n\t"
-            "movq        1(%1, %%"REG_a"), %%mm3    \n\t"
-            "movq       -1(%0, %%"REG_a"), %%mm4    \n\t"
-            "movq       -1(%1, %%"REG_a"), %%mm5    \n\t"
-            PAVGB"                  %%mm0, %%mm5    \n\t"
-            PAVGB"                  %%mm0, %%mm3    \n\t"
-            PAVGB"                  %%mm0, %%mm5    \n\t"
-            PAVGB"                  %%mm0, %%mm3    \n\t"
-            PAVGB"                  %%mm1, %%mm4    \n\t"
-            PAVGB"                  %%mm1, %%mm2    \n\t"
-            PAVGB"                  %%mm1, %%mm4    \n\t"
-            PAVGB"                  %%mm1, %%mm2    \n\t"
-            "movq                   %%mm5, %%mm7    \n\t"
-            "movq                   %%mm4, %%mm6    \n\t"
-            "punpcklbw              %%mm3, %%mm5    \n\t"
-            "punpckhbw              %%mm3, %%mm7    \n\t"
-            "punpcklbw              %%mm2, %%mm4    \n\t"
-            "punpckhbw              %%mm2, %%mm6    \n\t"
-#if 1
-            MOVNTQ"                 %%mm5,  (%2, %%"REG_a", 2)  \n\t"
-            MOVNTQ"                 %%mm7, 8(%2, %%"REG_a", 2)  \n\t"
-            MOVNTQ"                 %%mm4,  (%3, %%"REG_a", 2)  \n\t"
-            MOVNTQ"                 %%mm6, 8(%3, %%"REG_a", 2)  \n\t"
-#else
-            "movq                   %%mm5,  (%2, %%"REG_a", 2)  \n\t"
-            "movq                   %%mm7, 8(%2, %%"REG_a", 2)  \n\t"
-            "movq                   %%mm4,  (%3, %%"REG_a", 2)  \n\t"
-            "movq                   %%mm6, 8(%3, %%"REG_a", 2)  \n\t"
-#endif
-            "add                       $8, %%"REG_a"            \n\t"
-            " js                       1b                       \n\t"
-            :: "r" (src + mmxSize  ), "r" (src + srcStride + mmxSize  ),
-            "r" (dst + mmxSize*2), "r" (dst + dstStride + mmxSize*2),
-            "g" (-mmxSize)
-            : "%"REG_a
-
-        );
-#else
-        const x86_reg mmxSize=1;
-#endif
+        const int mmxSize = 1;
+
         dst[0        ]= (3*src[0] +   src[srcStride])>>2;
         dst[dstStride]= (  src[0] + 3*src[srcStride])>>2;
 
@@ -1857,12 +607,6 @@ static inline void RENAME(planar2x)(const uint8_t *src, uint8_t *dst, long srcWi
         dst[2*x+1]= src[x];
     }
 #endif
-
-#if HAVE_MMX
-    __asm__ volatile(EMMS"       \n\t"
-                     SFENCE"     \n\t"
-                     :::"memory");
-#endif
 }
 
 /**
@@ -1871,96 +615,15 @@ static inline void RENAME(planar2x)(const uint8_t *src, uint8_t *dst, long srcWi
  * Chrominance data is only taken from every second line, others are ignored.
  * FIXME: Write HQ version.
  */
-static inline void RENAME(uyvytoyv12)(const uint8_t *src, uint8_t *ydst, uint8_t *udst, uint8_t *vdst,
-                                      long width, long height,
-                                      long lumStride, long chromStride, long srcStride)
+static inline void uyvytoyv12_c(const uint8_t *src, uint8_t *ydst,
+                                uint8_t *udst, uint8_t *vdst,
+                                long width, long height,
+                                long lumStride, long chromStride,
+                                long srcStride)
 {
     long y;
-    const x86_reg chromWidth= width>>1;
+    const int chromWidth = width >> 1;
     for (y=0; y<height; y+=2) {
-#if HAVE_MMX
-        __asm__ volatile(
-            "xor                 %%"REG_a", %%"REG_a"   \n\t"
-            "pcmpeqw             %%mm7, %%mm7   \n\t"
-            "psrlw                  $8, %%mm7   \n\t" // FF,00,FF,00...
-            ASMALIGN(4)
-            "1:                                 \n\t"
-            PREFETCH" 64(%0, %%"REG_a", 4)          \n\t"
-            "movq       (%0, %%"REG_a", 4), %%mm0   \n\t" // UYVY UYVY(0)
-            "movq      8(%0, %%"REG_a", 4), %%mm1   \n\t" // UYVY UYVY(4)
-            "movq                %%mm0, %%mm2   \n\t" // UYVY UYVY(0)
-            "movq                %%mm1, %%mm3   \n\t" // UYVY UYVY(4)
-            "pand                %%mm7, %%mm0   \n\t" // U0V0 U0V0(0)
-            "pand                %%mm7, %%mm1   \n\t" // U0V0 U0V0(4)
-            "psrlw                  $8, %%mm2   \n\t" // Y0Y0 Y0Y0(0)
-            "psrlw                  $8, %%mm3   \n\t" // Y0Y0 Y0Y0(4)
-            "packuswb            %%mm1, %%mm0   \n\t" // UVUV UVUV(0)
-            "packuswb            %%mm3, %%mm2   \n\t" // YYYY YYYY(0)
-
-            MOVNTQ"              %%mm2,  (%1, %%"REG_a", 2) \n\t"
-
-            "movq     16(%0, %%"REG_a", 4), %%mm1   \n\t" // UYVY UYVY(8)
-            "movq     24(%0, %%"REG_a", 4), %%mm2   \n\t" // UYVY UYVY(12)
-            "movq                %%mm1, %%mm3   \n\t" // UYVY UYVY(8)
-            "movq                %%mm2, %%mm4   \n\t" // UYVY UYVY(12)
-            "pand                %%mm7, %%mm1   \n\t" // U0V0 U0V0(8)
-            "pand                %%mm7, %%mm2   \n\t" // U0V0 U0V0(12)
-            "psrlw                  $8, %%mm3   \n\t" // Y0Y0 Y0Y0(8)
-            "psrlw                  $8, %%mm4   \n\t" // Y0Y0 Y0Y0(12)
-            "packuswb            %%mm2, %%mm1   \n\t" // UVUV UVUV(8)
-            "packuswb            %%mm4, %%mm3   \n\t" // YYYY YYYY(8)
-
-            MOVNTQ"              %%mm3, 8(%1, %%"REG_a", 2) \n\t"
-
-            "movq                %%mm0, %%mm2   \n\t" // UVUV UVUV(0)
-            "movq                %%mm1, %%mm3   \n\t" // UVUV UVUV(8)
-            "psrlw                  $8, %%mm0   \n\t" // V0V0 V0V0(0)
-            "psrlw                  $8, %%mm1   \n\t" // V0V0 V0V0(8)
-            "pand                %%mm7, %%mm2   \n\t" // U0U0 U0U0(0)
-            "pand                %%mm7, %%mm3   \n\t" // U0U0 U0U0(8)
-            "packuswb            %%mm1, %%mm0   \n\t" // VVVV VVVV(0)
-            "packuswb            %%mm3, %%mm2   \n\t" // UUUU UUUU(0)
-
-            MOVNTQ"              %%mm0, (%3, %%"REG_a") \n\t"
-            MOVNTQ"              %%mm2, (%2, %%"REG_a") \n\t"
-
-            "add                    $8, %%"REG_a"   \n\t"
-            "cmp                    %4, %%"REG_a"   \n\t"
-            " jb                    1b          \n\t"
-            ::"r"(src), "r"(ydst), "r"(udst), "r"(vdst), "g" (chromWidth)
-            : "memory", "%"REG_a
-        );
-
-        ydst += lumStride;
-        src  += srcStride;
-
-        __asm__ volatile(
-            "xor                 %%"REG_a", %%"REG_a"   \n\t"
-            ASMALIGN(4)
-            "1:                                 \n\t"
-            PREFETCH" 64(%0, %%"REG_a", 4)          \n\t"
-            "movq       (%0, %%"REG_a", 4), %%mm0   \n\t" // YUYV YUYV(0)
-            "movq      8(%0, %%"REG_a", 4), %%mm1   \n\t" // YUYV YUYV(4)
-            "movq     16(%0, %%"REG_a", 4), %%mm2   \n\t" // YUYV YUYV(8)
-            "movq     24(%0, %%"REG_a", 4), %%mm3   \n\t" // YUYV YUYV(12)
-            "psrlw                  $8, %%mm0   \n\t" // Y0Y0 Y0Y0(0)
-            "psrlw                  $8, %%mm1   \n\t" // Y0Y0 Y0Y0(4)
-            "psrlw                  $8, %%mm2   \n\t" // Y0Y0 Y0Y0(8)
-            "psrlw                  $8, %%mm3   \n\t" // Y0Y0 Y0Y0(12)
-            "packuswb            %%mm1, %%mm0   \n\t" // YYYY YYYY(0)
-            "packuswb            %%mm3, %%mm2   \n\t" // YYYY YYYY(8)
-
-            MOVNTQ"              %%mm0,  (%1, %%"REG_a", 2) \n\t"
-            MOVNTQ"              %%mm2, 8(%1, %%"REG_a", 2) \n\t"
-
-            "add                    $8, %%"REG_a"   \n\t"
-            "cmp                    %4, %%"REG_a"   \n\t"
-            " jb                    1b          \n\t"
-
-            ::"r"(src), "r"(ydst), "r"(udst), "r"(vdst), "g" (chromWidth)
-            : "memory", "%"REG_a
-        );
-#else
         long i;
         for (i=0; i<chromWidth; i++) {
             udst[i]     = src[4*i+0];
@@ -1975,17 +638,11 @@ static inline void RENAME(uyvytoyv12)(const uint8_t *src, uint8_t *ydst, uint8_t
             ydst[2*i+0] = src[4*i+1];
             ydst[2*i+1] = src[4*i+3];
         }
-#endif
         udst += chromStride;
         vdst += chromStride;
         ydst += lumStride;
         src  += srcStride;
     }
-#if HAVE_MMX
-    __asm__ volatile(EMMS"       \n\t"
-                     SFENCE"     \n\t"
-                     :::"memory");
-#endif
 }
 
 /**
@@ -1995,249 +652,15 @@ static inline void RENAME(uyvytoyv12)(const uint8_t *src, uint8_t *ydst, uint8_t
  * others are ignored in the C version.
  * FIXME: Write HQ version.
  */
-static inline void RENAME(rgb24toyv12)(const uint8_t *src, uint8_t *ydst, uint8_t *udst, uint8_t *vdst,
-                                       long width, long height,
-                                       long lumStride, long chromStride, long srcStride)
+static inline void rgb24toyv12_c(const uint8_t *src, uint8_t *ydst,
+                                 uint8_t *udst, uint8_t *vdst,
+                                 long width, long height,
+                                 long lumStride, long chromStride,
+                                 long srcStride)
 {
     long y;
-    const x86_reg chromWidth= width>>1;
-#if HAVE_MMX
-    for (y=0; y<height-2; y+=2) {
-        long i;
-        for (i=0; i<2; i++) {
-            __asm__ volatile(
-                "mov                        %2, %%"REG_a"   \n\t"
-                "movq  "MANGLE(ff_bgr2YCoeff)", %%mm6       \n\t"
-                "movq       "MANGLE(ff_w1111)", %%mm5       \n\t"
-                "pxor                    %%mm7, %%mm7       \n\t"
-                "lea (%%"REG_a", %%"REG_a", 2), %%"REG_d"   \n\t"
-                ASMALIGN(4)
-                "1:                                         \n\t"
-                PREFETCH"    64(%0, %%"REG_d")              \n\t"
-                "movd          (%0, %%"REG_d"), %%mm0       \n\t"
-                "movd         3(%0, %%"REG_d"), %%mm1       \n\t"
-                "punpcklbw               %%mm7, %%mm0       \n\t"
-                "punpcklbw               %%mm7, %%mm1       \n\t"
-                "movd         6(%0, %%"REG_d"), %%mm2       \n\t"
-                "movd         9(%0, %%"REG_d"), %%mm3       \n\t"
-                "punpcklbw               %%mm7, %%mm2       \n\t"
-                "punpcklbw               %%mm7, %%mm3       \n\t"
-                "pmaddwd                 %%mm6, %%mm0       \n\t"
-                "pmaddwd                 %%mm6, %%mm1       \n\t"
-                "pmaddwd                 %%mm6, %%mm2       \n\t"
-                "pmaddwd                 %%mm6, %%mm3       \n\t"
-#ifndef FAST_BGR2YV12
-                "psrad                      $8, %%mm0       \n\t"
-                "psrad                      $8, %%mm1       \n\t"
-                "psrad                      $8, %%mm2       \n\t"
-                "psrad                      $8, %%mm3       \n\t"
-#endif
-                "packssdw                %%mm1, %%mm0       \n\t"
-                "packssdw                %%mm3, %%mm2       \n\t"
-                "pmaddwd                 %%mm5, %%mm0       \n\t"
-                "pmaddwd                 %%mm5, %%mm2       \n\t"
-                "packssdw                %%mm2, %%mm0       \n\t"
-                "psraw                      $7, %%mm0       \n\t"
-
-                "movd        12(%0, %%"REG_d"), %%mm4       \n\t"
-                "movd        15(%0, %%"REG_d"), %%mm1       \n\t"
-                "punpcklbw               %%mm7, %%mm4       \n\t"
-                "punpcklbw               %%mm7, %%mm1       \n\t"
-                "movd        18(%0, %%"REG_d"), %%mm2       \n\t"
-                "movd        21(%0, %%"REG_d"), %%mm3       \n\t"
-                "punpcklbw               %%mm7, %%mm2       \n\t"
-                "punpcklbw               %%mm7, %%mm3       \n\t"
-                "pmaddwd                 %%mm6, %%mm4       \n\t"
-                "pmaddwd                 %%mm6, %%mm1       \n\t"
-                "pmaddwd                 %%mm6, %%mm2       \n\t"
-                "pmaddwd                 %%mm6, %%mm3       \n\t"
-#ifndef FAST_BGR2YV12
-                "psrad                      $8, %%mm4       \n\t"
-                "psrad                      $8, %%mm1       \n\t"
-                "psrad                      $8, %%mm2       \n\t"
-                "psrad                      $8, %%mm3       \n\t"
-#endif
-                "packssdw                %%mm1, %%mm4       \n\t"
-                "packssdw                %%mm3, %%mm2       \n\t"
-                "pmaddwd                 %%mm5, %%mm4       \n\t"
-                "pmaddwd                 %%mm5, %%mm2       \n\t"
-                "add                       $24, %%"REG_d"   \n\t"
-                "packssdw                %%mm2, %%mm4       \n\t"
-                "psraw                      $7, %%mm4       \n\t"
-
-                "packuswb                %%mm4, %%mm0       \n\t"
-                "paddusb "MANGLE(ff_bgr2YOffset)", %%mm0    \n\t"
-
-                MOVNTQ"                  %%mm0, (%1, %%"REG_a") \n\t"
-                "add                        $8,      %%"REG_a"  \n\t"
-                " js                        1b                  \n\t"
-                : : "r" (src+width*3), "r" (ydst+width), "g" ((x86_reg)-width)
-                : "%"REG_a, "%"REG_d
-            );
-            ydst += lumStride;
-            src  += srcStride;
-        }
-        src -= srcStride*2;
-        __asm__ volatile(
-            "mov                        %4, %%"REG_a"   \n\t"
-            "movq       "MANGLE(ff_w1111)", %%mm5       \n\t"
-            "movq  "MANGLE(ff_bgr2UCoeff)", %%mm6       \n\t"
-            "pxor                    %%mm7, %%mm7       \n\t"
-            "lea (%%"REG_a", %%"REG_a", 2), %%"REG_d"   \n\t"
-            "add                 %%"REG_d", %%"REG_d"   \n\t"
-            ASMALIGN(4)
-            "1:                                         \n\t"
-            PREFETCH"    64(%0, %%"REG_d")              \n\t"
-            PREFETCH"    64(%1, %%"REG_d")              \n\t"
-#if HAVE_MMX2 || HAVE_AMD3DNOW
-            "movq          (%0, %%"REG_d"), %%mm0       \n\t"
-            "movq          (%1, %%"REG_d"), %%mm1       \n\t"
-            "movq         6(%0, %%"REG_d"), %%mm2       \n\t"
-            "movq         6(%1, %%"REG_d"), %%mm3       \n\t"
-            PAVGB"                   %%mm1, %%mm0       \n\t"
-            PAVGB"                   %%mm3, %%mm2       \n\t"
-            "movq                    %%mm0, %%mm1       \n\t"
-            "movq                    %%mm2, %%mm3       \n\t"
-            "psrlq                     $24, %%mm0       \n\t"
-            "psrlq                     $24, %%mm2       \n\t"
-            PAVGB"                   %%mm1, %%mm0       \n\t"
-            PAVGB"                   %%mm3, %%mm2       \n\t"
-            "punpcklbw               %%mm7, %%mm0       \n\t"
-            "punpcklbw               %%mm7, %%mm2       \n\t"
-#else
-            "movd          (%0, %%"REG_d"), %%mm0       \n\t"
-            "movd          (%1, %%"REG_d"), %%mm1       \n\t"
-            "movd         3(%0, %%"REG_d"), %%mm2       \n\t"
-            "movd         3(%1, %%"REG_d"), %%mm3       \n\t"
-            "punpcklbw               %%mm7, %%mm0       \n\t"
-            "punpcklbw               %%mm7, %%mm1       \n\t"
-            "punpcklbw               %%mm7, %%mm2       \n\t"
-            "punpcklbw               %%mm7, %%mm3       \n\t"
-            "paddw                   %%mm1, %%mm0       \n\t"
-            "paddw                   %%mm3, %%mm2       \n\t"
-            "paddw                   %%mm2, %%mm0       \n\t"
-            "movd         6(%0, %%"REG_d"), %%mm4       \n\t"
-            "movd         6(%1, %%"REG_d"), %%mm1       \n\t"
-            "movd         9(%0, %%"REG_d"), %%mm2       \n\t"
-            "movd         9(%1, %%"REG_d"), %%mm3       \n\t"
-            "punpcklbw               %%mm7, %%mm4       \n\t"
-            "punpcklbw               %%mm7, %%mm1       \n\t"
-            "punpcklbw               %%mm7, %%mm2       \n\t"
-            "punpcklbw               %%mm7, %%mm3       \n\t"
-            "paddw                   %%mm1, %%mm4       \n\t"
-            "paddw                   %%mm3, %%mm2       \n\t"
-            "paddw                   %%mm4, %%mm2       \n\t"
-            "psrlw                      $2, %%mm0       \n\t"
-            "psrlw                      $2, %%mm2       \n\t"
-#endif
-            "movq  "MANGLE(ff_bgr2VCoeff)", %%mm1       \n\t"
-            "movq  "MANGLE(ff_bgr2VCoeff)", %%mm3       \n\t"
-
-            "pmaddwd                 %%mm0, %%mm1       \n\t"
-            "pmaddwd                 %%mm2, %%mm3       \n\t"
-            "pmaddwd                 %%mm6, %%mm0       \n\t"
-            "pmaddwd                 %%mm6, %%mm2       \n\t"
-#ifndef FAST_BGR2YV12
-            "psrad                      $8, %%mm0       \n\t"
-            "psrad                      $8, %%mm1       \n\t"
-            "psrad                      $8, %%mm2       \n\t"
-            "psrad                      $8, %%mm3       \n\t"
-#endif
-            "packssdw                %%mm2, %%mm0       \n\t"
-            "packssdw                %%mm3, %%mm1       \n\t"
-            "pmaddwd                 %%mm5, %%mm0       \n\t"
-            "pmaddwd                 %%mm5, %%mm1       \n\t"
-            "packssdw                %%mm1, %%mm0       \n\t" // V1 V0 U1 U0
-            "psraw                      $7, %%mm0       \n\t"
-
-#if HAVE_MMX2 || HAVE_AMD3DNOW
-            "movq        12(%0, %%"REG_d"), %%mm4       \n\t"
-            "movq        12(%1, %%"REG_d"), %%mm1       \n\t"
-            "movq        18(%0, %%"REG_d"), %%mm2       \n\t"
-            "movq        18(%1, %%"REG_d"), %%mm3       \n\t"
-            PAVGB"                   %%mm1, %%mm4       \n\t"
-            PAVGB"                   %%mm3, %%mm2       \n\t"
-            "movq                    %%mm4, %%mm1       \n\t"
-            "movq                    %%mm2, %%mm3       \n\t"
-            "psrlq                     $24, %%mm4       \n\t"
-            "psrlq                     $24, %%mm2       \n\t"
-            PAVGB"                   %%mm1, %%mm4       \n\t"
-            PAVGB"                   %%mm3, %%mm2       \n\t"
-            "punpcklbw               %%mm7, %%mm4       \n\t"
-            "punpcklbw               %%mm7, %%mm2       \n\t"
-#else
-            "movd        12(%0, %%"REG_d"), %%mm4       \n\t"
-            "movd        12(%1, %%"REG_d"), %%mm1       \n\t"
-            "movd        15(%0, %%"REG_d"), %%mm2       \n\t"
-            "movd        15(%1, %%"REG_d"), %%mm3       \n\t"
-            "punpcklbw               %%mm7, %%mm4       \n\t"
-            "punpcklbw               %%mm7, %%mm1       \n\t"
-            "punpcklbw               %%mm7, %%mm2       \n\t"
-            "punpcklbw               %%mm7, %%mm3       \n\t"
-            "paddw                   %%mm1, %%mm4       \n\t"
-            "paddw                   %%mm3, %%mm2       \n\t"
-            "paddw                   %%mm2, %%mm4       \n\t"
-            "movd        18(%0, %%"REG_d"), %%mm5       \n\t"
-            "movd        18(%1, %%"REG_d"), %%mm1       \n\t"
-            "movd        21(%0, %%"REG_d"), %%mm2       \n\t"
-            "movd        21(%1, %%"REG_d"), %%mm3       \n\t"
-            "punpcklbw               %%mm7, %%mm5       \n\t"
-            "punpcklbw               %%mm7, %%mm1       \n\t"
-            "punpcklbw               %%mm7, %%mm2       \n\t"
-            "punpcklbw               %%mm7, %%mm3       \n\t"
-            "paddw                   %%mm1, %%mm5       \n\t"
-            "paddw                   %%mm3, %%mm2       \n\t"
-            "paddw                   %%mm5, %%mm2       \n\t"
-            "movq       "MANGLE(ff_w1111)", %%mm5       \n\t"
-            "psrlw                      $2, %%mm4       \n\t"
-            "psrlw                      $2, %%mm2       \n\t"
-#endif
-            "movq  "MANGLE(ff_bgr2VCoeff)", %%mm1       \n\t"
-            "movq  "MANGLE(ff_bgr2VCoeff)", %%mm3       \n\t"
-
-            "pmaddwd                 %%mm4, %%mm1       \n\t"
-            "pmaddwd                 %%mm2, %%mm3       \n\t"
-            "pmaddwd                 %%mm6, %%mm4       \n\t"
-            "pmaddwd                 %%mm6, %%mm2       \n\t"
-#ifndef FAST_BGR2YV12
-            "psrad                      $8, %%mm4       \n\t"
-            "psrad                      $8, %%mm1       \n\t"
-            "psrad                      $8, %%mm2       \n\t"
-            "psrad                      $8, %%mm3       \n\t"
-#endif
-            "packssdw                %%mm2, %%mm4       \n\t"
-            "packssdw                %%mm3, %%mm1       \n\t"
-            "pmaddwd                 %%mm5, %%mm4       \n\t"
-            "pmaddwd                 %%mm5, %%mm1       \n\t"
-            "add                       $24, %%"REG_d"   \n\t"
-            "packssdw                %%mm1, %%mm4       \n\t" // V3 V2 U3 U2
-            "psraw                      $7, %%mm4       \n\t"
-
-            "movq                    %%mm0, %%mm1           \n\t"
-            "punpckldq               %%mm4, %%mm0           \n\t"
-            "punpckhdq               %%mm4, %%mm1           \n\t"
-            "packsswb                %%mm1, %%mm0           \n\t"
-            "paddb "MANGLE(ff_bgr2UVOffset)", %%mm0         \n\t"
-            "movd                    %%mm0, (%2, %%"REG_a") \n\t"
-            "punpckhdq               %%mm0, %%mm0           \n\t"
-            "movd                    %%mm0, (%3, %%"REG_a") \n\t"
-            "add                        $4, %%"REG_a"       \n\t"
-            " js                        1b                  \n\t"
-            : : "r" (src+chromWidth*6), "r" (src+srcStride+chromWidth*6), "r" (udst+chromWidth), "r" (vdst+chromWidth), "g" (-chromWidth)
-            : "%"REG_a, "%"REG_d
-        );
-
-        udst += chromStride;
-        vdst += chromStride;
-        src  += srcStride*2;
-    }
-
-    __asm__ volatile(EMMS"       \n\t"
-                     SFENCE"     \n\t"
-                     :::"memory");
-#else
+    const int chromWidth = width >> 1;
     y=0;
-#endif
     for (; y<height; y+=2) {
         long i;
         for (i=0; i<chromWidth; i++) {
@@ -2286,194 +709,55 @@ static inline void RENAME(rgb24toyv12)(const uint8_t *src, uint8_t *ydst, uint8_
     }
 }
 
-static void RENAME(interleaveBytes)(const uint8_t *src1, const uint8_t *src2, uint8_t *dest,
-                             long width, long height, long src1Stride,
-                             long src2Stride, long dstStride)
+static void interleaveBytes_c(const uint8_t *src1, const uint8_t *src2,
+                              uint8_t *dest, long width,
+                              long height, long src1Stride,
+                              long src2Stride, long dstStride)
 {
     long h;
 
     for (h=0; h < height; h++) {
         long w;
-
-#if HAVE_MMX
-#if HAVE_SSE2
-        __asm__(
-            "xor              %%"REG_a", %%"REG_a"  \n\t"
-            "1:                                     \n\t"
-            PREFETCH" 64(%1, %%"REG_a")             \n\t"
-            PREFETCH" 64(%2, %%"REG_a")             \n\t"
-            "movdqa     (%1, %%"REG_a"), %%xmm0     \n\t"
-            "movdqa     (%1, %%"REG_a"), %%xmm1     \n\t"
-            "movdqa     (%2, %%"REG_a"), %%xmm2     \n\t"
-            "punpcklbw           %%xmm2, %%xmm0     \n\t"
-            "punpckhbw           %%xmm2, %%xmm1     \n\t"
-            "movntdq             %%xmm0,   (%0, %%"REG_a", 2)   \n\t"
-            "movntdq             %%xmm1, 16(%0, %%"REG_a", 2)   \n\t"
-            "add                    $16, %%"REG_a"  \n\t"
-            "cmp                     %3, %%"REG_a"  \n\t"
-            " jb                     1b             \n\t"
-            ::"r"(dest), "r"(src1), "r"(src2), "r" ((x86_reg)width-15)
-            : "memory", "%"REG_a""
-        );
-#else
-        __asm__(
-            "xor %%"REG_a", %%"REG_a"               \n\t"
-            "1:                                     \n\t"
-            PREFETCH" 64(%1, %%"REG_a")             \n\t"
-            PREFETCH" 64(%2, %%"REG_a")             \n\t"
-            "movq       (%1, %%"REG_a"), %%mm0      \n\t"
-            "movq      8(%1, %%"REG_a"), %%mm2      \n\t"
-            "movq                 %%mm0, %%mm1      \n\t"
-            "movq                 %%mm2, %%mm3      \n\t"
-            "movq       (%2, %%"REG_a"), %%mm4      \n\t"
-            "movq      8(%2, %%"REG_a"), %%mm5      \n\t"
-            "punpcklbw            %%mm4, %%mm0      \n\t"
-            "punpckhbw            %%mm4, %%mm1      \n\t"
-            "punpcklbw            %%mm5, %%mm2      \n\t"
-            "punpckhbw            %%mm5, %%mm3      \n\t"
-            MOVNTQ"               %%mm0,   (%0, %%"REG_a", 2)   \n\t"
-            MOVNTQ"               %%mm1,  8(%0, %%"REG_a", 2)   \n\t"
-            MOVNTQ"               %%mm2, 16(%0, %%"REG_a", 2)   \n\t"
-            MOVNTQ"               %%mm3, 24(%0, %%"REG_a", 2)   \n\t"
-            "add                    $16, %%"REG_a"  \n\t"
-            "cmp                     %3, %%"REG_a"  \n\t"
-            " jb                     1b             \n\t"
-            ::"r"(dest), "r"(src1), "r"(src2), "r" ((x86_reg)width-15)
-            : "memory", "%"REG_a
-        );
-#endif
-        for (w= (width&(~15)); w < width; w++) {
-            dest[2*w+0] = src1[w];
-            dest[2*w+1] = src2[w];
-        }
-#else
         for (w=0; w < width; w++) {
             dest[2*w+0] = src1[w];
             dest[2*w+1] = src2[w];
         }
-#endif
         dest += dstStride;
-                src1 += src1Stride;
-                src2 += src2Stride;
+        src1 += src1Stride;
+        src2 += src2Stride;
     }
-#if HAVE_MMX
-    __asm__(
-            EMMS"       \n\t"
-            SFENCE"     \n\t"
-            ::: "memory"
-            );
-#endif
 }
 
-static inline void RENAME(vu9_to_vu12)(const uint8_t *src1, const uint8_t *src2,
-                                       uint8_t *dst1, uint8_t *dst2,
-                                       long width, long height,
-                                       long srcStride1, long srcStride2,
-                                       long dstStride1, long dstStride2)
+static inline void vu9_to_vu12_c(const uint8_t *src1, const uint8_t *src2,
+                                 uint8_t *dst1, uint8_t *dst2,
+                                 long width, long height,
+                                 long srcStride1, long srcStride2,
+                                 long dstStride1, long dstStride2)
 {
-    x86_reg y;
+    int y;
     long x,w,h;
     w=width/2; h=height/2;
-#if HAVE_MMX
-    __asm__ volatile(
-        PREFETCH" %0    \n\t"
-        PREFETCH" %1    \n\t"
-        ::"m"(*(src1+srcStride1)),"m"(*(src2+srcStride2)):"memory");
-#endif
     for (y=0;y<h;y++) {
         const uint8_t* s1=src1+srcStride1*(y>>1);
         uint8_t* d=dst1+dstStride1*y;
         x=0;
-#if HAVE_MMX
-        for (;x<w-31;x+=32) {
-            __asm__ volatile(
-                PREFETCH"   32%1        \n\t"
-                "movq         %1, %%mm0 \n\t"
-                "movq        8%1, %%mm2 \n\t"
-                "movq       16%1, %%mm4 \n\t"
-                "movq       24%1, %%mm6 \n\t"
-                "movq      %%mm0, %%mm1 \n\t"
-                "movq      %%mm2, %%mm3 \n\t"
-                "movq      %%mm4, %%mm5 \n\t"
-                "movq      %%mm6, %%mm7 \n\t"
-                "punpcklbw %%mm0, %%mm0 \n\t"
-                "punpckhbw %%mm1, %%mm1 \n\t"
-                "punpcklbw %%mm2, %%mm2 \n\t"
-                "punpckhbw %%mm3, %%mm3 \n\t"
-                "punpcklbw %%mm4, %%mm4 \n\t"
-                "punpckhbw %%mm5, %%mm5 \n\t"
-                "punpcklbw %%mm6, %%mm6 \n\t"
-                "punpckhbw %%mm7, %%mm7 \n\t"
-                MOVNTQ"    %%mm0,   %0  \n\t"
-                MOVNTQ"    %%mm1,  8%0  \n\t"
-                MOVNTQ"    %%mm2, 16%0  \n\t"
-                MOVNTQ"    %%mm3, 24%0  \n\t"
-                MOVNTQ"    %%mm4, 32%0  \n\t"
-                MOVNTQ"    %%mm5, 40%0  \n\t"
-                MOVNTQ"    %%mm6, 48%0  \n\t"
-                MOVNTQ"    %%mm7, 56%0"
-                :"=m"(d[2*x])
-                :"m"(s1[x])
-                :"memory");
-        }
-#endif
         for (;x<w;x++) d[2*x]=d[2*x+1]=s1[x];
     }
     for (y=0;y<h;y++) {
         const uint8_t* s2=src2+srcStride2*(y>>1);
         uint8_t* d=dst2+dstStride2*y;
         x=0;
-#if HAVE_MMX
-        for (;x<w-31;x+=32) {
-            __asm__ volatile(
-                PREFETCH"   32%1        \n\t"
-                "movq         %1, %%mm0 \n\t"
-                "movq        8%1, %%mm2 \n\t"
-                "movq       16%1, %%mm4 \n\t"
-                "movq       24%1, %%mm6 \n\t"
-                "movq      %%mm0, %%mm1 \n\t"
-                "movq      %%mm2, %%mm3 \n\t"
-                "movq      %%mm4, %%mm5 \n\t"
-                "movq      %%mm6, %%mm7 \n\t"
-                "punpcklbw %%mm0, %%mm0 \n\t"
-                "punpckhbw %%mm1, %%mm1 \n\t"
-                "punpcklbw %%mm2, %%mm2 \n\t"
-                "punpckhbw %%mm3, %%mm3 \n\t"
-                "punpcklbw %%mm4, %%mm4 \n\t"
-                "punpckhbw %%mm5, %%mm5 \n\t"
-                "punpcklbw %%mm6, %%mm6 \n\t"
-                "punpckhbw %%mm7, %%mm7 \n\t"
-                MOVNTQ"    %%mm0,   %0  \n\t"
-                MOVNTQ"    %%mm1,  8%0  \n\t"
-                MOVNTQ"    %%mm2, 16%0  \n\t"
-                MOVNTQ"    %%mm3, 24%0  \n\t"
-                MOVNTQ"    %%mm4, 32%0  \n\t"
-                MOVNTQ"    %%mm5, 40%0  \n\t"
-                MOVNTQ"    %%mm6, 48%0  \n\t"
-                MOVNTQ"    %%mm7, 56%0"
-                :"=m"(d[2*x])
-                :"m"(s2[x])
-                :"memory");
-        }
-#endif
         for (;x<w;x++) d[2*x]=d[2*x+1]=s2[x];
     }
-#if HAVE_MMX
-    __asm__(
-            EMMS"       \n\t"
-            SFENCE"     \n\t"
-            ::: "memory"
-        );
-#endif
 }
 
-static inline void RENAME(yvu9_to_yuy2)(const uint8_t *src1, const uint8_t *src2, const uint8_t *src3,
-                                        uint8_t *dst,
-                                        long width, long height,
-                                        long srcStride1, long srcStride2,
-                                        long srcStride3, long dstStride)
+static inline void yvu9_to_yuy2_c(const uint8_t *src1, const uint8_t *src2,
+                                  const uint8_t *src3, uint8_t *dst,
+                                  long width, long height,
+                                  long srcStride1, long srcStride2,
+                                  long srcStride3, long dstStride)
 {
-    x86_reg x;
+    int x;
     long y,w,h;
     w=width/2; h=height;
     for (y=0;y<h;y++) {
@@ -2482,60 +766,6 @@ static inline void RENAME(yvu9_to_yuy2)(const uint8_t *src1, const uint8_t *src2
         const uint8_t* vp=src3+srcStride3*(y>>2);
         uint8_t* d=dst+dstStride*y;
         x=0;
-#if HAVE_MMX
-        for (;x<w-7;x+=8) {
-            __asm__ volatile(
-                PREFETCH"   32(%1, %0)          \n\t"
-                PREFETCH"   32(%2, %0)          \n\t"
-                PREFETCH"   32(%3, %0)          \n\t"
-                "movq      (%1, %0, 4), %%mm0   \n\t" /* Y0Y1Y2Y3Y4Y5Y6Y7 */
-                "movq         (%2, %0), %%mm1   \n\t" /* U0U1U2U3U4U5U6U7 */
-                "movq         (%3, %0), %%mm2   \n\t" /* V0V1V2V3V4V5V6V7 */
-                "movq            %%mm0, %%mm3   \n\t" /* Y0Y1Y2Y3Y4Y5Y6Y7 */
-                "movq            %%mm1, %%mm4   \n\t" /* U0U1U2U3U4U5U6U7 */
-                "movq            %%mm2, %%mm5   \n\t" /* V0V1V2V3V4V5V6V7 */
-                "punpcklbw       %%mm1, %%mm1   \n\t" /* U0U0 U1U1 U2U2 U3U3 */
-                "punpcklbw       %%mm2, %%mm2   \n\t" /* V0V0 V1V1 V2V2 V3V3 */
-                "punpckhbw       %%mm4, %%mm4   \n\t" /* U4U4 U5U5 U6U6 U7U7 */
-                "punpckhbw       %%mm5, %%mm5   \n\t" /* V4V4 V5V5 V6V6 V7V7 */
-
-                "movq            %%mm1, %%mm6   \n\t"
-                "punpcklbw       %%mm2, %%mm1   \n\t" /* U0V0 U0V0 U1V1 U1V1*/
-                "punpcklbw       %%mm1, %%mm0   \n\t" /* Y0U0 Y1V0 Y2U0 Y3V0*/
-                "punpckhbw       %%mm1, %%mm3   \n\t" /* Y4U1 Y5V1 Y6U1 Y7V1*/
-                MOVNTQ"          %%mm0,  (%4, %0, 8)    \n\t"
-                MOVNTQ"          %%mm3, 8(%4, %0, 8)    \n\t"
-
-                "punpckhbw       %%mm2, %%mm6   \n\t" /* U2V2 U2V2 U3V3 U3V3*/
-                "movq     8(%1, %0, 4), %%mm0   \n\t"
-                "movq            %%mm0, %%mm3   \n\t"
-                "punpcklbw       %%mm6, %%mm0   \n\t" /* Y U2 Y V2 Y U2 Y V2*/
-                "punpckhbw       %%mm6, %%mm3   \n\t" /* Y U3 Y V3 Y U3 Y V3*/
-                MOVNTQ"          %%mm0, 16(%4, %0, 8)   \n\t"
-                MOVNTQ"          %%mm3, 24(%4, %0, 8)   \n\t"
-
-                "movq            %%mm4, %%mm6   \n\t"
-                "movq    16(%1, %0, 4), %%mm0   \n\t"
-                "movq            %%mm0, %%mm3   \n\t"
-                "punpcklbw       %%mm5, %%mm4   \n\t"
-                "punpcklbw       %%mm4, %%mm0   \n\t" /* Y U4 Y V4 Y U4 Y V4*/
-                "punpckhbw       %%mm4, %%mm3   \n\t" /* Y U5 Y V5 Y U5 Y V5*/
-                MOVNTQ"          %%mm0, 32(%4, %0, 8)   \n\t"
-                MOVNTQ"          %%mm3, 40(%4, %0, 8)   \n\t"
-
-                "punpckhbw       %%mm5, %%mm6   \n\t"
-                "movq    24(%1, %0, 4), %%mm0   \n\t"
-                "movq            %%mm0, %%mm3   \n\t"
-                "punpcklbw       %%mm6, %%mm0   \n\t" /* Y U6 Y V6 Y U6 Y V6*/
-                "punpckhbw       %%mm6, %%mm3   \n\t" /* Y U7 Y V7 Y U7 Y V7*/
-                MOVNTQ"          %%mm0, 48(%4, %0, 8)   \n\t"
-                MOVNTQ"          %%mm3, 56(%4, %0, 8)   \n\t"
-
-                : "+r" (x)
-                : "r"(yp), "r" (up), "r"(vp), "r"(d)
-                :"memory");
-        }
-#endif
         for (; x<w; x++) {
             const long x2 = x<<2;
             d[8*x+0] = yp[x2];
@@ -2548,95 +778,27 @@ static inline void RENAME(yvu9_to_yuy2)(const uint8_t *src1, const uint8_t *src2
             d[8*x+7] = vp[x];
         }
     }
-#if HAVE_MMX
-    __asm__(
-            EMMS"       \n\t"
-            SFENCE"     \n\t"
-            ::: "memory"
-        );
-#endif
 }
 
-static void RENAME(extract_even)(const uint8_t *src, uint8_t *dst, x86_reg count)
+static void extract_even_c(const uint8_t *src, uint8_t *dst, int count)
 {
     dst +=   count;
     src += 2*count;
     count= - count;
 
-#if HAVE_MMX
-    if(count <= -16) {
-        count += 15;
-        __asm__ volatile(
-            "pcmpeqw       %%mm7, %%mm7        \n\t"
-            "psrlw            $8, %%mm7        \n\t"
-            "1:                                \n\t"
-            "movq -30(%1, %0, 2), %%mm0        \n\t"
-            "movq -22(%1, %0, 2), %%mm1        \n\t"
-            "movq -14(%1, %0, 2), %%mm2        \n\t"
-            "movq  -6(%1, %0, 2), %%mm3        \n\t"
-            "pand          %%mm7, %%mm0        \n\t"
-            "pand          %%mm7, %%mm1        \n\t"
-            "pand          %%mm7, %%mm2        \n\t"
-            "pand          %%mm7, %%mm3        \n\t"
-            "packuswb      %%mm1, %%mm0        \n\t"
-            "packuswb      %%mm3, %%mm2        \n\t"
-            MOVNTQ"        %%mm0,-15(%2, %0)   \n\t"
-            MOVNTQ"        %%mm2,- 7(%2, %0)   \n\t"
-            "add             $16, %0           \n\t"
-            " js 1b                            \n\t"
-            : "+r"(count)
-            : "r"(src), "r"(dst)
-        );
-        count -= 15;
-    }
-#endif
     while(count<0) {
         dst[count]= src[2*count];
         count++;
     }
 }
 
-static void RENAME(extract_even2)(const uint8_t *src, uint8_t *dst0, uint8_t *dst1, x86_reg count)
+static void extract_even2_c(const uint8_t *src, uint8_t *dst0, uint8_t *dst1,
+                            int count)
 {
     dst0+=   count;
     dst1+=   count;
     src += 4*count;
     count= - count;
-#if HAVE_MMX
-    if(count <= -8) {
-        count += 7;
-        __asm__ volatile(
-            "pcmpeqw       %%mm7, %%mm7        \n\t"
-            "psrlw            $8, %%mm7        \n\t"
-            "1:                                \n\t"
-            "movq -28(%1, %0, 4), %%mm0        \n\t"
-            "movq -20(%1, %0, 4), %%mm1        \n\t"
-            "movq -12(%1, %0, 4), %%mm2        \n\t"
-            "movq  -4(%1, %0, 4), %%mm3        \n\t"
-            "pand          %%mm7, %%mm0        \n\t"
-            "pand          %%mm7, %%mm1        \n\t"
-            "pand          %%mm7, %%mm2        \n\t"
-            "pand          %%mm7, %%mm3        \n\t"
-            "packuswb      %%mm1, %%mm0        \n\t"
-            "packuswb      %%mm3, %%mm2        \n\t"
-            "movq          %%mm0, %%mm1        \n\t"
-            "movq          %%mm2, %%mm3        \n\t"
-            "psrlw            $8, %%mm0        \n\t"
-            "psrlw            $8, %%mm2        \n\t"
-            "pand          %%mm7, %%mm1        \n\t"
-            "pand          %%mm7, %%mm3        \n\t"
-            "packuswb      %%mm2, %%mm0        \n\t"
-            "packuswb      %%mm3, %%mm1        \n\t"
-            MOVNTQ"        %%mm0,- 7(%3, %0)   \n\t"
-            MOVNTQ"        %%mm1,- 7(%2, %0)   \n\t"
-            "add              $8, %0           \n\t"
-            " js 1b                            \n\t"
-            : "+r"(count)
-            : "r"(src), "r"(dst0), "r"(dst1)
-        );
-        count -= 7;
-    }
-#endif
     while(count<0) {
         dst0[count]= src[4*count+0];
         dst1[count]= src[4*count+2];
@@ -2644,52 +806,14 @@ static void RENAME(extract_even2)(const uint8_t *src, uint8_t *dst0, uint8_t *ds
     }
 }
 
-static void RENAME(extract_even2avg)(const uint8_t *src0, const uint8_t *src1, uint8_t *dst0, uint8_t *dst1, x86_reg count)
+static void extract_even2avg_c(const uint8_t *src0, const uint8_t *src1,
+                               uint8_t *dst0, uint8_t *dst1, int count)
 {
     dst0 +=   count;
     dst1 +=   count;
     src0 += 4*count;
     src1 += 4*count;
     count= - count;
-#ifdef PAVGB
-    if(count <= -8) {
-        count += 7;
-        __asm__ volatile(
-            "pcmpeqw        %%mm7, %%mm7        \n\t"
-            "psrlw             $8, %%mm7        \n\t"
-            "1:                                \n\t"
-            "movq  -28(%1, %0, 4), %%mm0        \n\t"
-            "movq  -20(%1, %0, 4), %%mm1        \n\t"
-            "movq  -12(%1, %0, 4), %%mm2        \n\t"
-            "movq   -4(%1, %0, 4), %%mm3        \n\t"
-            PAVGB" -28(%2, %0, 4), %%mm0        \n\t"
-            PAVGB" -20(%2, %0, 4), %%mm1        \n\t"
-            PAVGB" -12(%2, %0, 4), %%mm2        \n\t"
-            PAVGB" - 4(%2, %0, 4), %%mm3        \n\t"
-            "pand           %%mm7, %%mm0        \n\t"
-            "pand           %%mm7, %%mm1        \n\t"
-            "pand           %%mm7, %%mm2        \n\t"
-            "pand           %%mm7, %%mm3        \n\t"
-            "packuswb       %%mm1, %%mm0        \n\t"
-            "packuswb       %%mm3, %%mm2        \n\t"
-            "movq           %%mm0, %%mm1        \n\t"
-            "movq           %%mm2, %%mm3        \n\t"
-            "psrlw             $8, %%mm0        \n\t"
-            "psrlw             $8, %%mm2        \n\t"
-            "pand           %%mm7, %%mm1        \n\t"
-            "pand           %%mm7, %%mm3        \n\t"
-            "packuswb       %%mm2, %%mm0        \n\t"
-            "packuswb       %%mm3, %%mm1        \n\t"
-            MOVNTQ"         %%mm0,- 7(%4, %0)   \n\t"
-            MOVNTQ"         %%mm1,- 7(%3, %0)   \n\t"
-            "add               $8, %0           \n\t"
-            " js 1b                            \n\t"
-            : "+r"(count)
-            : "r"(src0), "r"(src1), "r"(dst0), "r"(dst1)
-        );
-        count -= 7;
-    }
-#endif
     while(count<0) {
         dst0[count]= (src0[4*count+0]+src1[4*count+0])>>1;
         dst1[count]= (src0[4*count+2]+src1[4*count+2])>>1;
@@ -2697,47 +821,13 @@ static void RENAME(extract_even2avg)(const uint8_t *src0, const uint8_t *src1, u
     }
 }
 
-static void RENAME(extract_odd2)(const uint8_t *src, uint8_t *dst0, uint8_t *dst1, x86_reg count)
+static void extract_odd2_c(const uint8_t *src, uint8_t *dst0, uint8_t *dst1,
+                           int count)
 {
     dst0+=   count;
     dst1+=   count;
     src += 4*count;
     count= - count;
-#if HAVE_MMX
-    if(count <= -8) {
-        count += 7;
-        __asm__ volatile(
-            "pcmpeqw       %%mm7, %%mm7        \n\t"
-            "psrlw            $8, %%mm7        \n\t"
-            "1:                                \n\t"
-            "movq -28(%1, %0, 4), %%mm0        \n\t"
-            "movq -20(%1, %0, 4), %%mm1        \n\t"
-            "movq -12(%1, %0, 4), %%mm2        \n\t"
-            "movq  -4(%1, %0, 4), %%mm3        \n\t"
-            "psrlw            $8, %%mm0        \n\t"
-            "psrlw            $8, %%mm1        \n\t"
-            "psrlw            $8, %%mm2        \n\t"
-            "psrlw            $8, %%mm3        \n\t"
-            "packuswb      %%mm1, %%mm0        \n\t"
-            "packuswb      %%mm3, %%mm2        \n\t"
-            "movq          %%mm0, %%mm1        \n\t"
-            "movq          %%mm2, %%mm3        \n\t"
-            "psrlw            $8, %%mm0        \n\t"
-            "psrlw            $8, %%mm2        \n\t"
-            "pand          %%mm7, %%mm1        \n\t"
-            "pand          %%mm7, %%mm3        \n\t"
-            "packuswb      %%mm2, %%mm0        \n\t"
-            "packuswb      %%mm3, %%mm1        \n\t"
-            MOVNTQ"        %%mm0,- 7(%3, %0)   \n\t"
-            MOVNTQ"        %%mm1,- 7(%2, %0)   \n\t"
-            "add              $8, %0           \n\t"
-            " js 1b                            \n\t"
-            : "+r"(count)
-            : "r"(src), "r"(dst0), "r"(dst1)
-        );
-        count -= 7;
-    }
-#endif
     src++;
     while(count<0) {
         dst0[count]= src[4*count+0];
@@ -2746,52 +836,14 @@ static void RENAME(extract_odd2)(const uint8_t *src, uint8_t *dst0, uint8_t *dst
     }
 }
 
-static void RENAME(extract_odd2avg)(const uint8_t *src0, const uint8_t *src1, uint8_t *dst0, uint8_t *dst1, x86_reg count)
+static void extract_odd2avg_c(const uint8_t *src0, const uint8_t *src1,
+                              uint8_t *dst0, uint8_t *dst1, int count)
 {
     dst0 +=   count;
     dst1 +=   count;
     src0 += 4*count;
     src1 += 4*count;
     count= - count;
-#ifdef PAVGB
-    if(count <= -8) {
-        count += 7;
-        __asm__ volatile(
-            "pcmpeqw        %%mm7, %%mm7        \n\t"
-            "psrlw             $8, %%mm7        \n\t"
-            "1:                                \n\t"
-            "movq  -28(%1, %0, 4), %%mm0        \n\t"
-            "movq  -20(%1, %0, 4), %%mm1        \n\t"
-            "movq  -12(%1, %0, 4), %%mm2        \n\t"
-            "movq   -4(%1, %0, 4), %%mm3        \n\t"
-            PAVGB" -28(%2, %0, 4), %%mm0        \n\t"
-            PAVGB" -20(%2, %0, 4), %%mm1        \n\t"
-            PAVGB" -12(%2, %0, 4), %%mm2        \n\t"
-            PAVGB" - 4(%2, %0, 4), %%mm3        \n\t"
-            "psrlw             $8, %%mm0        \n\t"
-            "psrlw             $8, %%mm1        \n\t"
-            "psrlw             $8, %%mm2        \n\t"
-            "psrlw             $8, %%mm3        \n\t"
-            "packuswb       %%mm1, %%mm0        \n\t"
-            "packuswb       %%mm3, %%mm2        \n\t"
-            "movq           %%mm0, %%mm1        \n\t"
-            "movq           %%mm2, %%mm3        \n\t"
-            "psrlw             $8, %%mm0        \n\t"
-            "psrlw             $8, %%mm2        \n\t"
-            "pand           %%mm7, %%mm1        \n\t"
-            "pand           %%mm7, %%mm3        \n\t"
-            "packuswb       %%mm2, %%mm0        \n\t"
-            "packuswb       %%mm3, %%mm1        \n\t"
-            MOVNTQ"         %%mm0,- 7(%4, %0)   \n\t"
-            MOVNTQ"         %%mm1,- 7(%3, %0)   \n\t"
-            "add               $8, %0           \n\t"
-            " js 1b                            \n\t"
-            : "+r"(count)
-            : "r"(src0), "r"(src1), "r"(dst0), "r"(dst1)
-        );
-        count -= 7;
-    }
-#endif
     src0++;
     src1++;
     while(count<0) {
@@ -2801,17 +853,17 @@ static void RENAME(extract_odd2avg)(const uint8_t *src0, const uint8_t *src1, ui
     }
 }
 
-static void RENAME(yuyvtoyuv420)(uint8_t *ydst, uint8_t *udst, uint8_t *vdst, const uint8_t *src,
-                                      long width, long height,
-                                      long lumStride, long chromStride, long srcStride)
+static void yuyvtoyuv420_c(uint8_t *ydst, uint8_t *udst, uint8_t *vdst,
+                           const uint8_t *src, long width, long height,
+                           long lumStride, long chromStride, long srcStride)
 {
     long y;
     const long chromWidth= -((-width)>>1);
 
     for (y=0; y<height; y++) {
-        RENAME(extract_even)(src, ydst, width);
+        extract_even_c(src, ydst, width);
         if(y&1) {
-            RENAME(extract_odd2avg)(src-srcStride, src, udst, vdst, chromWidth);
+            extract_odd2avg_c(src - srcStride, src, udst, vdst, chromWidth);
             udst+= chromStride;
             vdst+= chromStride;
         }
@@ -2819,51 +871,37 @@ static void RENAME(yuyvtoyuv420)(uint8_t *ydst, uint8_t *udst, uint8_t *vdst, co
         src += srcStride;
         ydst+= lumStride;
     }
-#if HAVE_MMX
-    __asm__(
-            EMMS"       \n\t"
-            SFENCE"     \n\t"
-            ::: "memory"
-        );
-#endif
 }
 
-static void RENAME(yuyvtoyuv422)(uint8_t *ydst, uint8_t *udst, uint8_t *vdst, const uint8_t *src,
-                                      long width, long height,
-                                      long lumStride, long chromStride, long srcStride)
+static void yuyvtoyuv422_c(uint8_t *ydst, uint8_t *udst, uint8_t *vdst,
+                           const uint8_t *src, long width, long height,
+                           long lumStride, long chromStride, long srcStride)
 {
     long y;
     const long chromWidth= -((-width)>>1);
 
     for (y=0; y<height; y++) {
-        RENAME(extract_even)(src, ydst, width);
-        RENAME(extract_odd2)(src, udst, vdst, chromWidth);
+        extract_even_c(src, ydst, width);
+        extract_odd2_c(src, udst, vdst, chromWidth);
 
         src += srcStride;
         ydst+= lumStride;
         udst+= chromStride;
         vdst+= chromStride;
     }
-#if HAVE_MMX
-    __asm__(
-            EMMS"       \n\t"
-            SFENCE"     \n\t"
-            ::: "memory"
-        );
-#endif
 }
 
-static void RENAME(uyvytoyuv420)(uint8_t *ydst, uint8_t *udst, uint8_t *vdst, const uint8_t *src,
-                                      long width, long height,
-                                      long lumStride, long chromStride, long srcStride)
+static void uyvytoyuv420_c(uint8_t *ydst, uint8_t *udst, uint8_t *vdst,
+                           const uint8_t *src, long width, long height,
+                           long lumStride, long chromStride, long srcStride)
 {
     long y;
     const long chromWidth= -((-width)>>1);
 
     for (y=0; y<height; y++) {
-        RENAME(extract_even)(src+1, ydst, width);
+        extract_even_c(src + 1, ydst, width);
         if(y&1) {
-            RENAME(extract_even2avg)(src-srcStride, src, udst, vdst, chromWidth);
+            extract_even2avg_c(src - srcStride, src, udst, vdst, chromWidth);
             udst+= chromStride;
             vdst+= chromStride;
         }
@@ -2871,74 +909,59 @@ static void RENAME(uyvytoyuv420)(uint8_t *ydst, uint8_t *udst, uint8_t *vdst, co
         src += srcStride;
         ydst+= lumStride;
     }
-#if HAVE_MMX
-    __asm__(
-            EMMS"       \n\t"
-            SFENCE"     \n\t"
-            ::: "memory"
-        );
-#endif
 }
 
-static void RENAME(uyvytoyuv422)(uint8_t *ydst, uint8_t *udst, uint8_t *vdst, const uint8_t *src,
-                                      long width, long height,
-                                      long lumStride, long chromStride, long srcStride)
+static void uyvytoyuv422_c(uint8_t *ydst, uint8_t *udst, uint8_t *vdst,
+                           const uint8_t *src, long width, long height,
+                           long lumStride, long chromStride, long srcStride)
 {
     long y;
     const long chromWidth= -((-width)>>1);
 
     for (y=0; y<height; y++) {
-        RENAME(extract_even)(src+1, ydst, width);
-        RENAME(extract_even2)(src, udst, vdst, chromWidth);
+        extract_even_c(src + 1, ydst, width);
+        extract_even2_c(src, udst, vdst, chromWidth);
 
         src += srcStride;
         ydst+= lumStride;
         udst+= chromStride;
         vdst+= chromStride;
     }
-#if HAVE_MMX
-    __asm__(
-            EMMS"       \n\t"
-            SFENCE"     \n\t"
-            ::: "memory"
-        );
-#endif
 }
 
-static inline void RENAME(rgb2rgb_init)(void)
-{
-    rgb15to16       = RENAME(rgb15to16);
-    rgb15tobgr24    = RENAME(rgb15tobgr24);
-    rgb15to32       = RENAME(rgb15to32);
-    rgb16tobgr24    = RENAME(rgb16tobgr24);
-    rgb16to32       = RENAME(rgb16to32);
-    rgb16to15       = RENAME(rgb16to15);
-    rgb24tobgr16    = RENAME(rgb24tobgr16);
-    rgb24tobgr15    = RENAME(rgb24tobgr15);
-    rgb24tobgr32    = RENAME(rgb24tobgr32);
-    rgb32to16       = RENAME(rgb32to16);
-    rgb32to15       = RENAME(rgb32to15);
-    rgb32tobgr24    = RENAME(rgb32tobgr24);
-    rgb24to15       = RENAME(rgb24to15);
-    rgb24to16       = RENAME(rgb24to16);
-    rgb24tobgr24    = RENAME(rgb24tobgr24);
-    rgb32tobgr32    = RENAME(rgb32tobgr32);
-    rgb32tobgr16    = RENAME(rgb32tobgr16);
-    rgb32tobgr15    = RENAME(rgb32tobgr15);
-    yv12toyuy2      = RENAME(yv12toyuy2);
-    yv12touyvy      = RENAME(yv12touyvy);
-    yuv422ptoyuy2   = RENAME(yuv422ptoyuy2);
-    yuv422ptouyvy   = RENAME(yuv422ptouyvy);
-    yuy2toyv12      = RENAME(yuy2toyv12);
-//    yvu9toyv12      = RENAME(yvu9toyv12);
-    planar2x        = RENAME(planar2x);
-    rgb24toyv12     = RENAME(rgb24toyv12);
-    interleaveBytes = RENAME(interleaveBytes);
-    vu9_to_vu12     = RENAME(vu9_to_vu12);
-    yvu9_to_yuy2    = RENAME(yvu9_to_yuy2);
-
-    uyvytoyuv420    = RENAME(uyvytoyuv420);
-    uyvytoyuv422    = RENAME(uyvytoyuv422);
-    yuyvtoyuv420    = RENAME(yuyvtoyuv420);
-    yuyvtoyuv422    = RENAME(yuyvtoyuv422);
+static inline void rgb2rgb_init_c(void)
+{
+    rgb15to16          = rgb15to16_c;
+    rgb15tobgr24       = rgb15tobgr24_c;
+    rgb15to32          = rgb15to32_c;
+    rgb16tobgr24       = rgb16tobgr24_c;
+    rgb16to32          = rgb16to32_c;
+    rgb16to15          = rgb16to15_c;
+    rgb24tobgr16       = rgb24tobgr16_c;
+    rgb24tobgr15       = rgb24tobgr15_c;
+    rgb24tobgr32       = rgb24tobgr32_c;
+    rgb32to16          = rgb32to16_c;
+    rgb32to15          = rgb32to15_c;
+    rgb32tobgr24       = rgb32tobgr24_c;
+    rgb24to15          = rgb24to15_c;
+    rgb24to16          = rgb24to16_c;
+    rgb24tobgr24       = rgb24tobgr24_c;
+    shuffle_bytes_2103 = shuffle_bytes_2103_c;
+    rgb32tobgr16       = rgb32tobgr16_c;
+    rgb32tobgr15       = rgb32tobgr15_c;
+    yv12toyuy2         = yv12toyuy2_c;
+    yv12touyvy         = yv12touyvy_c;
+    yuv422ptoyuy2      = yuv422ptoyuy2_c;
+    yuv422ptouyvy      = yuv422ptouyvy_c;
+    yuy2toyv12         = yuy2toyv12_c;
+    planar2x           = planar2x_c;
+    rgb24toyv12        = rgb24toyv12_c;
+    interleaveBytes    = interleaveBytes_c;
+    vu9_to_vu12        = vu9_to_vu12_c;
+    yvu9_to_yuy2       = yvu9_to_yuy2_c;
+
+    uyvytoyuv420       = uyvytoyuv420_c;
+    uyvytoyuv422       = uyvytoyuv422_c;
+    yuyvtoyuv420       = yuyvtoyuv420_c;
+    yuyvtoyuv422       = yuyvtoyuv422_c;
 }
diff --git a/libswscale/sparc/yuv2rgb_vis.c b/libswscale/sparc/yuv2rgb_vis.c
index cc98f04..2111ea8 100644
--- a/libswscale/sparc/yuv2rgb_vis.c
+++ b/libswscale/sparc/yuv2rgb_vis.c
@@ -2,20 +2,20 @@
  * VIS optimized software YUV to RGB converter
  * Copyright (c) 2007 Denes Balatoni <dbalatoni at programozo.hu>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/libswscale/swscale-test.c b/libswscale/swscale-test.c
index 887973a..22d8a70 100644
--- a/libswscale/swscale-test.c
+++ b/libswscale/swscale-test.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (C) 2003 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -25,14 +25,16 @@
 #include <stdarg.h>
 
 #undef HAVE_AV_CONFIG_H
+#include "libavutil/imgutils.h"
 #include "libavutil/mem.h"
 #include "libavutil/avutil.h"
+#include "libavutil/crc.h"
+#include "libavutil/pixdesc.h"
 #include "libavutil/lfg.h"
 #include "swscale.h"
 
 /* HACK Duplicated from swscale_internal.h.
  * Should be removed when a cleaner pixel format system exists. */
-const char *sws_format_name(enum PixelFormat format);
 #define isGray(x)       (           \
            (x)==PIX_FMT_GRAY8       \
         || (x)==PIX_FMT_GRAY16BE    \
@@ -69,47 +71,81 @@ static uint64_t getSSD(uint8_t *src1, uint8_t *src2, int stride1, int stride2, i
     return ssd;
 }
 
+struct Results {
+    uint64_t ssdY;
+    uint64_t ssdU;
+    uint64_t ssdV;
+    uint64_t ssdA;
+    uint32_t crc;
+};
+
 // test by ref -> src -> dst -> out & compare out against ref
 // ref & out are YV12
 static int doTest(uint8_t *ref[4], int refStride[4], int w, int h,
                   enum PixelFormat srcFormat, enum PixelFormat dstFormat,
-                  int srcW, int srcH, int dstW, int dstH, int flags)
+                  int srcW, int srcH, int dstW, int dstH, int flags,
+                  struct Results *r)
 {
-    uint8_t *src[4] = {0};
+    static enum PixelFormat cur_srcFormat;
+    static int cur_srcW, cur_srcH;
+    static uint8_t *src[4];
+    static int srcStride[4];
     uint8_t *dst[4] = {0};
     uint8_t *out[4] = {0};
-    int srcStride[4], dstStride[4];
+    int dstStride[4];
     int i;
     uint64_t ssdY, ssdU=0, ssdV=0, ssdA=0;
-    struct SwsContext *srcContext = NULL, *dstContext = NULL,
-                      *outContext = NULL;
-    int res;
+    struct SwsContext *dstContext = NULL, *outContext = NULL;
+    uint32_t crc = 0;
+    int res = 0;
+
+    if (cur_srcFormat != srcFormat || cur_srcW != srcW || cur_srcH != srcH) {
+        struct SwsContext *srcContext = NULL;
+        int p;
+
+        for (p = 0; p < 4; p++)
+            av_freep(&src[p]);
+
+        av_image_fill_linesizes(srcStride, srcFormat, srcW);
+        for (p = 0; p < 4; p++) {
+            if (srcStride[p])
+                src[p] = av_mallocz(srcStride[p]*srcH+16);
+            if (srcStride[p] && !src[p]) {
+                perror("Malloc");
+                res = -1;
+
+                goto end;
+            }
+        }
+        srcContext = sws_getContext(w, h, PIX_FMT_YUVA420P, srcW, srcH,
+                                    srcFormat, SWS_BILINEAR, NULL, NULL, NULL);
+        if (!srcContext) {
+            fprintf(stderr, "Failed to get %s ---> %s\n",
+                    av_pix_fmt_descriptors[PIX_FMT_YUVA420P].name,
+                    av_pix_fmt_descriptors[srcFormat].name);
+            res = -1;
 
-    res = 0;
-    for (i=0; i<4; i++) {
-        // avoid stride % bpp != 0
-        if (srcFormat==PIX_FMT_RGB24 || srcFormat==PIX_FMT_BGR24)
-            srcStride[i]= srcW*3;
-        else if (srcFormat==PIX_FMT_RGB48BE || srcFormat==PIX_FMT_RGB48LE)
-            srcStride[i]= srcW*6;
-        else
-            srcStride[i]= srcW*4;
-
-        if (dstFormat==PIX_FMT_RGB24 || dstFormat==PIX_FMT_BGR24)
-            dstStride[i]= dstW*3;
-        else if (dstFormat==PIX_FMT_RGB48BE || dstFormat==PIX_FMT_RGB48LE)
-            dstStride[i]= dstW*6;
-        else
-            dstStride[i]= dstW*4;
+            goto end;
+        }
+        sws_scale(srcContext, ref, refStride, 0, h, src, srcStride);
+        sws_freeContext(srcContext);
 
+        cur_srcFormat = srcFormat;
+        cur_srcW = srcW;
+        cur_srcH = srcH;
+    }
+
+    av_image_fill_linesizes(dstStride, dstFormat, dstW);
+    for (i=0; i<4; i++) {
         /* Image buffers passed into libswscale can be allocated any way you
          * prefer, as long as they're aligned enough for the architecture, and
          * they're freed appropriately (such as using av_free for buffers
          * allocated with av_malloc). */
-        src[i]= av_mallocz(srcStride[i]*srcH);
-        dst[i]= av_mallocz(dstStride[i]*dstH);
-        out[i]= av_mallocz(refStride[i]*h);
-        if (!src[i] || !dst[i] || !out[i]) {
+        /* An extra 16 bytes is being allocated because some scalers may write
+         * out of bounds. */
+        if (dstStride[i])
+            dst[i]= av_mallocz(dstStride[i]*dstH+16);
+        if (dstStride[i] && !dst[i]) {
             perror("Malloc");
             res = -1;
 
@@ -117,29 +153,11 @@ static int doTest(uint8_t *ref[4], int refStride[4], int w, int h,
         }
     }
 
-    srcContext= sws_getContext(w, h, PIX_FMT_YUVA420P, srcW, srcH, srcFormat, flags, NULL, NULL, NULL);
-    if (!srcContext) {
-        fprintf(stderr, "Failed to get %s ---> %s\n",
-                sws_format_name(PIX_FMT_YUVA420P),
-                sws_format_name(srcFormat));
-        res = -1;
-
-        goto end;
-    }
     dstContext= sws_getContext(srcW, srcH, srcFormat, dstW, dstH, dstFormat, flags, NULL, NULL, NULL);
     if (!dstContext) {
         fprintf(stderr, "Failed to get %s ---> %s\n",
-                sws_format_name(srcFormat),
-                sws_format_name(dstFormat));
-        res = -1;
-
-        goto end;
-    }
-    outContext= sws_getContext(dstW, dstH, dstFormat, w, h, PIX_FMT_YUVA420P, flags, NULL, NULL, NULL);
-    if (!outContext) {
-        fprintf(stderr, "Failed to get %s ---> %s\n",
-                sws_format_name(dstFormat),
-                sws_format_name(PIX_FMT_YUVA420P));
+                av_pix_fmt_descriptors[srcFormat].name,
+                av_pix_fmt_descriptors[dstFormat].name);
         res = -1;
 
         goto end;
@@ -147,46 +165,85 @@ static int doTest(uint8_t *ref[4], int refStride[4], int w, int h,
 //    printf("test %X %X %X -> %X %X %X\n", (int)ref[0], (int)ref[1], (int)ref[2],
 //        (int)src[0], (int)src[1], (int)src[2]);
 
-    sws_scale(srcContext, ref, refStride, 0, h   , src, srcStride);
+    printf(" %s %dx%d -> %s %3dx%3d flags=%2d",
+           av_pix_fmt_descriptors[srcFormat].name, srcW, srcH,
+           av_pix_fmt_descriptors[dstFormat].name, dstW, dstH,
+           flags);
+    fflush(stdout);
+
     sws_scale(dstContext, src, srcStride, 0, srcH, dst, dstStride);
-    sws_scale(outContext, dst, dstStride, 0, dstH, out, refStride);
 
-    ssdY= getSSD(ref[0], out[0], refStride[0], refStride[0], w, h);
-    if (hasChroma(srcFormat) && hasChroma(dstFormat)) {
-        //FIXME check that output is really gray
-        ssdU= getSSD(ref[1], out[1], refStride[1], refStride[1], (w+1)>>1, (h+1)>>1);
-        ssdV= getSSD(ref[2], out[2], refStride[2], refStride[2], (w+1)>>1, (h+1)>>1);
+    for (i = 0; i < 4 && dstStride[i]; i++) {
+        crc = av_crc(av_crc_get_table(AV_CRC_32_IEEE), crc, dst[i], dstStride[i] * dstH);
+    }
+
+    if (r && crc == r->crc) {
+        ssdY = r->ssdY;
+        ssdU = r->ssdU;
+        ssdV = r->ssdV;
+        ssdA = r->ssdA;
+    } else {
+        for (i=0; i<4; i++) {
+            if (refStride[i])
+                out[i]= av_mallocz(refStride[i]*h);
+            if (refStride[i] && !out[i]) {
+                perror("Malloc");
+                res = -1;
+
+                goto end;
+            }
+        }
+        outContext= sws_getContext(dstW, dstH, dstFormat, w, h, PIX_FMT_YUVA420P, SWS_BILINEAR, NULL, NULL, NULL);
+        if (!outContext) {
+            fprintf(stderr, "Failed to get %s ---> %s\n",
+                    av_pix_fmt_descriptors[dstFormat].name,
+                    av_pix_fmt_descriptors[PIX_FMT_YUVA420P].name);
+            res = -1;
+
+            goto end;
+        }
+        sws_scale(outContext, dst, dstStride, 0, dstH, out, refStride);
+
+        ssdY= getSSD(ref[0], out[0], refStride[0], refStride[0], w, h);
+        if (hasChroma(srcFormat) && hasChroma(dstFormat)) {
+            //FIXME check that output is really gray
+            ssdU= getSSD(ref[1], out[1], refStride[1], refStride[1], (w+1)>>1, (h+1)>>1);
+            ssdV= getSSD(ref[2], out[2], refStride[2], refStride[2], (w+1)>>1, (h+1)>>1);
+        }
+        if (isALPHA(srcFormat) && isALPHA(dstFormat))
+            ssdA= getSSD(ref[3], out[3], refStride[3], refStride[3], w, h);
+
+        ssdY/= w*h;
+        ssdU/= w*h/4;
+        ssdV/= w*h/4;
+        ssdA/= w*h;
+
+        sws_freeContext(outContext);
+
+        for (i=0; i<4; i++) {
+            if (refStride[i])
+                av_free(out[i]);
+        }
     }
-    if (isALPHA(srcFormat) && isALPHA(dstFormat))
-        ssdA= getSSD(ref[3], out[3], refStride[3], refStride[3], w, h);
-
-    ssdY/= w*h;
-    ssdU/= w*h/4;
-    ssdV/= w*h/4;
-    ssdA/= w*h;
-
-    printf(" %s %dx%d -> %s %4dx%4d flags=%2d SSD=%5"PRId64",%5"PRId64",%5"PRId64",%5"PRId64"\n",
-           sws_format_name(srcFormat), srcW, srcH,
-           sws_format_name(dstFormat), dstW, dstH,
-           flags, ssdY, ssdU, ssdV, ssdA);
-    fflush(stdout);
+
+    printf(" CRC=%08x SSD=%5"PRId64",%5"PRId64",%5"PRId64",%5"PRId64"\n",
+           crc, ssdY, ssdU, ssdV, ssdA);
 
 end:
 
-    sws_freeContext(srcContext);
     sws_freeContext(dstContext);
-    sws_freeContext(outContext);
 
     for (i=0; i<4; i++) {
-        av_free(src[i]);
-        av_free(dst[i]);
-        av_free(out[i]);
+        if (dstStride[i])
+            av_free(dst[i]);
     }
 
     return res;
 }
 
-static void selfTest(uint8_t *ref[4], int refStride[4], int w, int h)
+static void selfTest(uint8_t *ref[4], int refStride[4], int w, int h,
+                     enum PixelFormat srcFormat_in,
+                     enum PixelFormat dstFormat_in)
 {
     const int flags[] = { SWS_FAST_BILINEAR,
                           SWS_BILINEAR, SWS_BICUBIC,
@@ -197,11 +254,13 @@ static void selfTest(uint8_t *ref[4], int refStride[4], int w, int h)
     const int dstH[] = { srcH - srcH/3, srcH, srcH + srcH/3, 0 };
     enum PixelFormat srcFormat, dstFormat;
 
-    for (srcFormat = 0; srcFormat < PIX_FMT_NB; srcFormat++) {
+    for (srcFormat = srcFormat_in != PIX_FMT_NONE ? srcFormat_in : 0;
+         srcFormat < PIX_FMT_NB; srcFormat++) {
         if (!sws_isSupportedInput(srcFormat) || !sws_isSupportedOutput(srcFormat))
             continue;
 
-        for (dstFormat = 0; dstFormat < PIX_FMT_NB; dstFormat++) {
+        for (dstFormat = dstFormat_in != PIX_FMT_NONE ? dstFormat_in : 0;
+             dstFormat < PIX_FMT_NB; dstFormat++) {
             int i, j, k;
             int res = 0;
 
@@ -209,17 +268,74 @@ static void selfTest(uint8_t *ref[4], int refStride[4], int w, int h)
                 continue;
 
             printf("%s -> %s\n",
-                   sws_format_name(srcFormat),
-                   sws_format_name(dstFormat));
+                   av_pix_fmt_descriptors[srcFormat].name,
+                   av_pix_fmt_descriptors[dstFormat].name);
             fflush(stdout);
 
-            for (i = 0; dstW[i] && !res; i++)
-                for (j = 0; dstH[j] && !res; j++)
-                    for (k = 0; flags[k] && !res; k++)
-                        res = doTest(ref, refStride, w, h, srcFormat, dstFormat,
-                                     srcW, srcH, dstW[i], dstH[j], flags[k]);
+            for (k = 0; flags[k] && !res; k++) {
+                for (i = 0; dstW[i] && !res; i++)
+                    for (j = 0; dstH[j] && !res; j++)
+                        res = doTest(ref, refStride, w, h,
+                                     srcFormat, dstFormat,
+                                     srcW, srcH, dstW[i], dstH[j], flags[k],
+                                     NULL);
+            }
+            if (dstFormat_in != PIX_FMT_NONE)
+                break;
+        }
+        if (srcFormat_in != PIX_FMT_NONE)
+            break;
+    }
+}
+
+static int fileTest(uint8_t *ref[4], int refStride[4], int w, int h, FILE *fp,
+                    enum PixelFormat srcFormat_in,
+                    enum PixelFormat dstFormat_in)
+{
+    char buf[256];
+
+    while (fgets(buf, sizeof(buf), fp)) {
+        struct Results r;
+        enum PixelFormat srcFormat;
+        char srcStr[12];
+        int srcW, srcH;
+        enum PixelFormat dstFormat;
+        char dstStr[12];
+        int dstW, dstH;
+        int flags;
+        int ret;
+
+        ret = sscanf(buf, " %12s %dx%d -> %12s %dx%d flags=%d CRC=%x"
+                          " SSD=%"PRId64", %"PRId64", %"PRId64", %"PRId64"\n",
+                          srcStr, &srcW, &srcH, dstStr, &dstW, &dstH,
+                          &flags, &r.crc, &r.ssdY, &r.ssdU, &r.ssdV, &r.ssdA);
+        if (ret != 12) {
+            srcStr[0] = dstStr[0] = 0;
+            ret = sscanf(buf, "%12s -> %12s\n", srcStr, dstStr);
+        }
+
+        srcFormat = av_get_pix_fmt(srcStr);
+        dstFormat = av_get_pix_fmt(dstStr);
+
+        if (srcFormat == PIX_FMT_NONE || dstFormat == PIX_FMT_NONE) {
+            fprintf(stderr, "malformed input file\n");
+            return -1;
         }
+        if ((srcFormat_in != PIX_FMT_NONE && srcFormat_in != srcFormat) ||
+            (dstFormat_in != PIX_FMT_NONE && dstFormat_in != dstFormat))
+            continue;
+        if (ret != 12) {
+            printf("%s", buf);
+            continue;
+        }
+
+        doTest(ref, refStride, w, h,
+               srcFormat, dstFormat,
+               srcW, srcH, dstW, dstH, flags,
+               &r);
     }
+
+    return 0;
 }
 
 #define W 96
@@ -227,6 +343,8 @@ static void selfTest(uint8_t *ref[4], int refStride[4], int w, int h)
 
 int main(int argc, char **argv)
 {
+    enum PixelFormat srcFormat = PIX_FMT_NONE;
+    enum PixelFormat dstFormat = PIX_FMT_NONE;
     uint8_t *rgb_data = av_malloc (W*H*4);
     uint8_t *rgb_src[3]= {rgb_data, NULL, NULL};
     int rgb_stride[3]={4*W, 0, 0};
@@ -236,6 +354,8 @@ int main(int argc, char **argv)
     int x, y;
     struct SwsContext *sws;
     AVLFG rand;
+    int res = -1;
+    int i;
 
     if (!rgb_data || !data)
         return -1;
@@ -253,8 +373,42 @@ int main(int argc, char **argv)
     sws_freeContext(sws);
     av_free(rgb_data);
 
-    selfTest(src, stride, W, H);
+    for (i = 1; i < argc; i += 2) {
+        if (argv[i][0] != '-' || i+1 == argc)
+            goto bad_option;
+        if (!strcmp(argv[i], "-ref")) {
+            FILE *fp = fopen(argv[i+1], "r");
+            if (!fp) {
+                fprintf(stderr, "could not open '%s'\n", argv[i+1]);
+                goto error;
+            }
+            res = fileTest(src, stride, W, H, fp, srcFormat, dstFormat);
+            fclose(fp);
+            goto end;
+        } else if (!strcmp(argv[i], "-src")) {
+            srcFormat = av_get_pix_fmt(argv[i+1]);
+            if (srcFormat == PIX_FMT_NONE) {
+                fprintf(stderr, "invalid pixel format %s\n", argv[i+1]);
+                return -1;
+            }
+        } else if (!strcmp(argv[i], "-dst")) {
+            dstFormat = av_get_pix_fmt(argv[i+1]);
+            if (dstFormat == PIX_FMT_NONE) {
+                fprintf(stderr, "invalid pixel format %s\n", argv[i+1]);
+                return -1;
+            }
+        } else {
+bad_option:
+            fprintf(stderr, "bad option or argument missing (%s)\n", argv[i]);
+            goto error;
+        }
+    }
+
+    selfTest(src, stride, W, H, srcFormat, dstFormat);
+end:
+    res = 0;
+error:
     av_free(data);
 
-    return 0;
+    return res;
 }
diff --git a/libswscale/swscale.c b/libswscale/swscale.c
index 81f475c..9a4f89c 100644
--- a/libswscale/swscale.c
+++ b/libswscale/swscale.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (C) 2001-2003 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -63,6 +63,7 @@ untested special converters
 #include "libavutil/intreadwrite.h"
 #include "libavutil/x86_cpu.h"
 #include "libavutil/avutil.h"
+#include "libavutil/mathematics.h"
 #include "libavutil/bswap.h"
 #include "libavutil/pixdesc.h"
 
@@ -75,18 +76,11 @@ untested special converters
 //#undef ARCH_X86
 #define DITHER1XBPP
 
-#define FAST_BGR2YV12 // use 7 bit coefficients instead of 15 bit
-
-#ifdef M_PI
-#define PI M_PI
-#else
-#define PI 3.14159265358979323846
-#endif
-
 #define isPacked(x)         (       \
            (x)==PIX_FMT_PAL8        \
         || (x)==PIX_FMT_YUYV422     \
         || (x)==PIX_FMT_UYVY422     \
+        || (x)==PIX_FMT_Y400A       \
         || isAnyRGB(x)              \
     )
 
@@ -102,14 +96,14 @@ untested special converters
 #define RU (-(int)(0.169*224/255*(1<<RGB2YUV_SHIFT)+0.5))
 
 static const double rgb2yuv_table[8][9]={
-    {0.7152, 0.0722, 0.2126, -0.386, 0.5, -0.115, -0.454, -0.046, 0.5},
-    {0.7152, 0.0722, 0.2126, -0.386, 0.5, -0.115, -0.454, -0.046, 0.5},
-    {0.587 , 0.114 , 0.299 , -0.331, 0.5, -0.169, -0.419, -0.081, 0.5},
-    {0.587 , 0.114 , 0.299 , -0.331, 0.5, -0.169, -0.419, -0.081, 0.5},
+    {0.7152, 0.0722, 0.2126, -0.386, 0.5, -0.115, -0.454, -0.046, 0.5}, //ITU709
+    {0.7152, 0.0722, 0.2126, -0.386, 0.5, -0.115, -0.454, -0.046, 0.5}, //ITU709
+    {0.587 , 0.114 , 0.299 , -0.331, 0.5, -0.169, -0.419, -0.081, 0.5}, //DEFAULT / ITU601 / ITU624 / SMPTE 170M
+    {0.587 , 0.114 , 0.299 , -0.331, 0.5, -0.169, -0.419, -0.081, 0.5}, //DEFAULT / ITU601 / ITU624 / SMPTE 170M
     {0.59  , 0.11  , 0.30  , -0.331, 0.5, -0.169, -0.421, -0.079, 0.5}, //FCC
-    {0.587 , 0.114 , 0.299 , -0.331, 0.5, -0.169, -0.419, -0.081, 0.5},
-    {0.587 , 0.114 , 0.299 , -0.331, 0.5, -0.169, -0.419, -0.081, 0.5}, //SMPTE 170M
-    {0.701 , 0.087 , 0.212 , -0.384, 0.5  -0.116, -0.445, -0.055, 0.5}, //SMPTE 240M
+    {0.587 , 0.114 , 0.299 , -0.331, 0.5, -0.169, -0.419, -0.081, 0.5}, //DEFAULT / ITU601 / ITU624 / SMPTE 170M
+    {0.587 , 0.114 , 0.299 , -0.331, 0.5, -0.169, -0.419, -0.081, 0.5}, //DEFAULT / ITU601 / ITU624 / SMPTE 170M
+    {0.701 , 0.087 , 0.212 , -0.384, 0.5, -0.116, -0.445, -0.055, 0.5}, //SMPTE 240M
 };
 
 /*
@@ -127,63 +121,6 @@ add BGR4 output support
 write special BGR->BGR scaler
 */
 
-#if ARCH_X86
-DECLARE_ASM_CONST(8, uint64_t, bF8)=       0xF8F8F8F8F8F8F8F8LL;
-DECLARE_ASM_CONST(8, uint64_t, bFC)=       0xFCFCFCFCFCFCFCFCLL;
-DECLARE_ASM_CONST(8, uint64_t, w10)=       0x0010001000100010LL;
-DECLARE_ASM_CONST(8, uint64_t, w02)=       0x0002000200020002LL;
-DECLARE_ASM_CONST(8, uint64_t, bm00001111)=0x00000000FFFFFFFFLL;
-DECLARE_ASM_CONST(8, uint64_t, bm00000111)=0x0000000000FFFFFFLL;
-DECLARE_ASM_CONST(8, uint64_t, bm11111000)=0xFFFFFFFFFF000000LL;
-DECLARE_ASM_CONST(8, uint64_t, bm01010101)=0x00FF00FF00FF00FFLL;
-
-const DECLARE_ALIGNED(8, uint64_t, ff_dither4)[2] = {
-        0x0103010301030103LL,
-        0x0200020002000200LL,};
-
-const DECLARE_ALIGNED(8, uint64_t, ff_dither8)[2] = {
-        0x0602060206020602LL,
-        0x0004000400040004LL,};
-
-DECLARE_ASM_CONST(8, uint64_t, b16Mask)=   0x001F001F001F001FLL;
-DECLARE_ASM_CONST(8, uint64_t, g16Mask)=   0x07E007E007E007E0LL;
-DECLARE_ASM_CONST(8, uint64_t, r16Mask)=   0xF800F800F800F800LL;
-DECLARE_ASM_CONST(8, uint64_t, b15Mask)=   0x001F001F001F001FLL;
-DECLARE_ASM_CONST(8, uint64_t, g15Mask)=   0x03E003E003E003E0LL;
-DECLARE_ASM_CONST(8, uint64_t, r15Mask)=   0x7C007C007C007C00LL;
-
-DECLARE_ALIGNED(8, const uint64_t, ff_M24A)         = 0x00FF0000FF0000FFLL;
-DECLARE_ALIGNED(8, const uint64_t, ff_M24B)         = 0xFF0000FF0000FF00LL;
-DECLARE_ALIGNED(8, const uint64_t, ff_M24C)         = 0x0000FF0000FF0000LL;
-
-#ifdef FAST_BGR2YV12
-DECLARE_ALIGNED(8, const uint64_t, ff_bgr2YCoeff)   = 0x000000210041000DULL;
-DECLARE_ALIGNED(8, const uint64_t, ff_bgr2UCoeff)   = 0x0000FFEEFFDC0038ULL;
-DECLARE_ALIGNED(8, const uint64_t, ff_bgr2VCoeff)   = 0x00000038FFD2FFF8ULL;
-#else
-DECLARE_ALIGNED(8, const uint64_t, ff_bgr2YCoeff)   = 0x000020E540830C8BULL;
-DECLARE_ALIGNED(8, const uint64_t, ff_bgr2UCoeff)   = 0x0000ED0FDAC23831ULL;
-DECLARE_ALIGNED(8, const uint64_t, ff_bgr2VCoeff)   = 0x00003831D0E6F6EAULL;
-#endif /* FAST_BGR2YV12 */
-DECLARE_ALIGNED(8, const uint64_t, ff_bgr2YOffset)  = 0x1010101010101010ULL;
-DECLARE_ALIGNED(8, const uint64_t, ff_bgr2UVOffset) = 0x8080808080808080ULL;
-DECLARE_ALIGNED(8, const uint64_t, ff_w1111)        = 0x0001000100010001ULL;
-
-DECLARE_ASM_CONST(8, uint64_t, ff_bgr24toY1Coeff) = 0x0C88000040870C88ULL;
-DECLARE_ASM_CONST(8, uint64_t, ff_bgr24toY2Coeff) = 0x20DE4087000020DEULL;
-DECLARE_ASM_CONST(8, uint64_t, ff_rgb24toY1Coeff) = 0x20DE0000408720DEULL;
-DECLARE_ASM_CONST(8, uint64_t, ff_rgb24toY2Coeff) = 0x0C88408700000C88ULL;
-DECLARE_ASM_CONST(8, uint64_t, ff_bgr24toYOffset) = 0x0008400000084000ULL;
-
-DECLARE_ASM_CONST(8, uint64_t, ff_bgr24toUV)[2][4] = {
-    {0x38380000DAC83838ULL, 0xECFFDAC80000ECFFULL, 0xF6E40000D0E3F6E4ULL, 0x3838D0E300003838ULL},
-    {0xECFF0000DAC8ECFFULL, 0x3838DAC800003838ULL, 0x38380000D0E33838ULL, 0xF6E4D0E30000F6E4ULL},
-};
-
-DECLARE_ASM_CONST(8, uint64_t, ff_bgr24toUVOffset)= 0x0040400000404000ULL;
-
-#endif /* ARCH_X86 */
-
 DECLARE_ALIGNED(8, static const uint8_t, dither_2x2_4)[2][8]={
 {  1,   3,   1,   3,   1,   3,   1,   3, },
 {  2,   0,   2,   0,   2,   0,   2,   0, },
@@ -994,7 +931,7 @@ static void fillPlane(uint8_t* plane, int stride, int width, int height, int y,
     }
 }
 
-static inline void rgb48ToY(uint8_t *dst, const uint8_t *src, int width,
+static inline void rgb48ToY(uint8_t *dst, const uint8_t *src, long width,
                             uint32_t *unused)
 {
     int i;
@@ -1009,7 +946,7 @@ static inline void rgb48ToY(uint8_t *dst, const uint8_t *src, int width,
 
 static inline void rgb48ToUV(uint8_t *dstU, uint8_t *dstV,
                              const uint8_t *src1, const uint8_t *src2,
-                             int width, uint32_t *unused)
+                             long width, uint32_t *unused)
 {
     int i;
     assert(src1==src2);
@@ -1025,7 +962,7 @@ static inline void rgb48ToUV(uint8_t *dstU, uint8_t *dstV,
 
 static inline void rgb48ToUV_half(uint8_t *dstU, uint8_t *dstV,
                                   const uint8_t *src1, const uint8_t *src2,
-                                  int width, uint32_t *unused)
+                                  long width, uint32_t *unused)
 {
     int i;
     assert(src1==src2);
@@ -1053,7 +990,9 @@ static inline void name(uint8_t *dst, const uint8_t *src, long width, uint32_t *
 }
 
 BGR2Y(uint32_t, bgr32ToY,16, 0, 0, 0x00FF, 0xFF00, 0x00FF, RY<< 8, GY   , BY<< 8, RGB2YUV_SHIFT+8)
+BGR2Y(uint32_t,bgr321ToY,16,16, 0, 0xFF00, 0x00FF, 0xFF00, RY    , GY<<8, BY    , RGB2YUV_SHIFT+8)
 BGR2Y(uint32_t, rgb32ToY, 0, 0,16, 0x00FF, 0xFF00, 0x00FF, RY<< 8, GY   , BY<< 8, RGB2YUV_SHIFT+8)
+BGR2Y(uint32_t,rgb321ToY, 0,16,16, 0xFF00, 0x00FF, 0xFF00, RY    , GY<<8, BY    , RGB2YUV_SHIFT+8)
 BGR2Y(uint16_t, bgr16ToY, 0, 0, 0, 0x001F, 0x07E0, 0xF800, RY<<11, GY<<5, BY    , RGB2YUV_SHIFT+8)
 BGR2Y(uint16_t, bgr15ToY, 0, 0, 0, 0x001F, 0x03E0, 0x7C00, RY<<10, GY<<5, BY    , RGB2YUV_SHIFT+7)
 BGR2Y(uint16_t, rgb16ToY, 0, 0, 0, 0xF800, 0x07E0, 0x001F, RY    , GY<<5, BY<<11, RGB2YUV_SHIFT+8)
@@ -1067,14 +1006,14 @@ static inline void abgrToA(uint8_t *dst, const uint8_t *src, long width, uint32_
     }
 }
 
-#define BGR2UV(type, name, shr, shg, shb, maska, maskr, maskg, maskb, RU, GU, BU, RV, GV, BV, S)\
+#define BGR2UV(type, name, shr, shg, shb, shp, maskr, maskg, maskb, RU, GU, BU, RV, GV, BV, S) \
 static inline void name(uint8_t *dstU, uint8_t *dstV, const uint8_t *src, const uint8_t *dummy, long width, uint32_t *unused)\
 {\
     int i;\
     for (i=0; i<width; i++) {\
-        int b= (((const type*)src)[i]&maskb)>>shb;\
-        int g= (((const type*)src)[i]&maskg)>>shg;\
-        int r= (((const type*)src)[i]&maskr)>>shr;\
+        int b= ((((const type*)src)[i]>>shp)&maskb)>>shb;\
+        int g= ((((const type*)src)[i]>>shp)&maskg)>>shg;\
+        int r= ((((const type*)src)[i]>>shp)&maskr)>>shr;\
 \
         dstU[i]= ((RU)*r + (GU)*g + (BU)*b + (257<<((S)-1)))>>(S);\
         dstV[i]= ((RV)*r + (GV)*g + (BV)*b + (257<<((S)-1)))>>(S);\
@@ -1084,8 +1023,8 @@ static inline void name ## _half(uint8_t *dstU, uint8_t *dstV, const uint8_t *sr
 {\
     int i;\
     for (i=0; i<width; i++) {\
-        int pix0= ((const type*)src)[2*i+0];\
-        int pix1= ((const type*)src)[2*i+1];\
+        int pix0= ((const type*)src)[2*i+0]>>shp;\
+        int pix1= ((const type*)src)[2*i+1]>>shp;\
         int g= (pix0&~(maskr|maskb))+(pix1&~(maskr|maskb));\
         int b= ((pix0+pix1-g)&(maskb|(2*maskb)))>>shb;\
         int r= ((pix0+pix1-g)&(maskr|(2*maskr)))>>shr;\
@@ -1098,12 +1037,14 @@ static inline void name ## _half(uint8_t *dstU, uint8_t *dstV, const uint8_t *sr
     }\
 }
 
-BGR2UV(uint32_t, bgr32ToUV,16, 0, 0, 0xFF000000, 0xFF0000, 0xFF00,   0x00FF, RU<< 8, GU   , BU<< 8, RV<< 8, GV   , BV<< 8, RGB2YUV_SHIFT+8)
-BGR2UV(uint32_t, rgb32ToUV, 0, 0,16, 0xFF000000,   0x00FF, 0xFF00, 0xFF0000, RU<< 8, GU   , BU<< 8, RV<< 8, GV   , BV<< 8, RGB2YUV_SHIFT+8)
-BGR2UV(uint16_t, bgr16ToUV, 0, 0, 0,          0,   0x001F, 0x07E0,   0xF800, RU<<11, GU<<5, BU    , RV<<11, GV<<5, BV    , RGB2YUV_SHIFT+8)
-BGR2UV(uint16_t, bgr15ToUV, 0, 0, 0,          0,   0x001F, 0x03E0,   0x7C00, RU<<10, GU<<5, BU    , RV<<10, GV<<5, BV    , RGB2YUV_SHIFT+7)
-BGR2UV(uint16_t, rgb16ToUV, 0, 0, 0,          0,   0xF800, 0x07E0,   0x001F, RU    , GU<<5, BU<<11, RV    , GV<<5, BV<<11, RGB2YUV_SHIFT+8)
-BGR2UV(uint16_t, rgb15ToUV, 0, 0, 0,          0,   0x7C00, 0x03E0,   0x001F, RU    , GU<<5, BU<<10, RV    , GV<<5, BV<<10, RGB2YUV_SHIFT+7)
+BGR2UV(uint32_t, bgr32ToUV,16, 0, 0, 0, 0xFF0000, 0xFF00,   0x00FF, RU<< 8, GU   , BU<< 8, RV<< 8, GV   , BV<< 8, RGB2YUV_SHIFT+8)
+BGR2UV(uint32_t,bgr321ToUV,16, 0, 0, 8, 0xFF0000, 0xFF00,   0x00FF, RU<< 8, GU   , BU<< 8, RV<< 8, GV   , BV<< 8, RGB2YUV_SHIFT+8)
+BGR2UV(uint32_t, rgb32ToUV, 0, 0,16, 0,   0x00FF, 0xFF00, 0xFF0000, RU<< 8, GU   , BU<< 8, RV<< 8, GV   , BV<< 8, RGB2YUV_SHIFT+8)
+BGR2UV(uint32_t,rgb321ToUV, 0, 0,16, 8,   0x00FF, 0xFF00, 0xFF0000, RU<< 8, GU   , BU<< 8, RV<< 8, GV   , BV<< 8, RGB2YUV_SHIFT+8)
+BGR2UV(uint16_t, bgr16ToUV, 0, 0, 0, 0,   0x001F, 0x07E0,   0xF800, RU<<11, GU<<5, BU    , RV<<11, GV<<5, BV    , RGB2YUV_SHIFT+8)
+BGR2UV(uint16_t, bgr15ToUV, 0, 0, 0, 0,   0x001F, 0x03E0,   0x7C00, RU<<10, GU<<5, BU    , RV<<10, GV<<5, BV    , RGB2YUV_SHIFT+7)
+BGR2UV(uint16_t, rgb16ToUV, 0, 0, 0, 0,   0xF800, 0x07E0,   0x001F, RU    , GU<<5, BU<<11, RV    , GV<<5, BV<<11, RGB2YUV_SHIFT+8)
+BGR2UV(uint16_t, rgb15ToUV, 0, 0, 0, 0,   0x7C00, 0x03E0,   0x001F, RU    , GU<<5, BU<<10, RV    , GV<<5, BV<<10, RGB2YUV_SHIFT+7)
 
 static inline void palToY(uint8_t *dst, const uint8_t *src, long width, uint32_t *pal)
 {
@@ -1151,53 +1092,68 @@ static inline void monoblack2Y(uint8_t *dst, const uint8_t *src, long width, uin
 
 //Note: we have C, MMX, MMX2, 3DNOW versions, there is no 3DNOW+MMX2 one
 //Plain C versions
-#if (!HAVE_MMX && !HAVE_ALTIVEC) || CONFIG_RUNTIME_CPUDETECT
-#define COMPILE_C
+#if CONFIG_RUNTIME_CPUDETECT
+#  define COMPILE_C 1
+#  if   ARCH_X86
+#    define COMPILE_MMX     HAVE_MMX
+#    define COMPILE_MMX2    HAVE_MMX2
+#    define COMPILE_3DNOW   HAVE_AMD3DNOW
+#  elif ARCH_PPC
+#    define COMPILE_ALTIVEC HAVE_ALTIVEC
+#  endif
+#else /* CONFIG_RUNTIME_CPUDETECT */
+#  if   ARCH_X86
+#    if   HAVE_MMX2
+#      define COMPILE_MMX2  1
+#    elif HAVE_AMD3DNOW
+#      define COMPILE_3DNOW 1
+#    elif HAVE_MMX
+#      define COMPILE_MMX   1
+#    else
+#      define COMPILE_C     1
+#    endif
+#  elif ARCH_PPC && HAVE_ALTIVEC
+#    define COMPILE_ALTIVEC 1
+#  else
+#    define COMPILE_C       1
+#  endif
 #endif
 
-#if ARCH_PPC
-#if HAVE_ALTIVEC
-#define COMPILE_ALTIVEC
+#ifndef COMPILE_C
+#  define COMPILE_C 0
 #endif
-#endif //ARCH_PPC
-
-#if ARCH_X86
-
-#if (HAVE_MMX && !HAVE_AMD3DNOW && !HAVE_MMX2) || CONFIG_RUNTIME_CPUDETECT
-#define COMPILE_MMX
+#ifndef COMPILE_MMX
+#  define COMPILE_MMX 0
 #endif
-
-#if HAVE_MMX2 || CONFIG_RUNTIME_CPUDETECT
-#define COMPILE_MMX2
+#ifndef COMPILE_MMX2
+#  define COMPILE_MMX2 0
 #endif
-
-#if (HAVE_AMD3DNOW && !HAVE_MMX2) || CONFIG_RUNTIME_CPUDETECT
-#define COMPILE_3DNOW
+#ifndef COMPILE_3DNOW
+#  define COMPILE_3DNOW 0
+#endif
+#ifndef COMPILE_ALTIVEC
+#  define COMPILE_ALTIVEC 0
 #endif
-#endif //ARCH_X86
 
 #define COMPILE_TEMPLATE_MMX 0
 #define COMPILE_TEMPLATE_MMX2 0
 #define COMPILE_TEMPLATE_AMD3DNOW 0
 #define COMPILE_TEMPLATE_ALTIVEC 0
 
-#ifdef COMPILE_C
-#define RENAME(a) a ## _C
 #include "swscale_template.c"
-#endif
 
-#ifdef COMPILE_ALTIVEC
+#if COMPILE_ALTIVEC
 #undef RENAME
 #undef COMPILE_TEMPLATE_ALTIVEC
 #define COMPILE_TEMPLATE_ALTIVEC 1
 #define RENAME(a) a ## _altivec
-#include "swscale_template.c"
+#include "ppc/swscale_template.c"
 #endif
 
 #if ARCH_X86
 
 //MMX versions
-#ifdef COMPILE_MMX
+#if COMPILE_MMX
 #undef RENAME
 #undef COMPILE_TEMPLATE_MMX
 #undef COMPILE_TEMPLATE_MMX2
@@ -1206,11 +1162,11 @@ static inline void monoblack2Y(uint8_t *dst, const uint8_t *src, long width, uin
 #define COMPILE_TEMPLATE_MMX2 0
 #define COMPILE_TEMPLATE_AMD3DNOW 0
 #define RENAME(a) a ## _MMX
-#include "swscale_template.c"
+#include "x86/swscale_template.c"
 #endif
 
 //MMX2 versions
-#ifdef COMPILE_MMX2
+#if COMPILE_MMX2
 #undef RENAME
 #undef COMPILE_TEMPLATE_MMX
 #undef COMPILE_TEMPLATE_MMX2
@@ -1219,11 +1175,11 @@ static inline void monoblack2Y(uint8_t *dst, const uint8_t *src, long width, uin
 #define COMPILE_TEMPLATE_MMX2 1
 #define COMPILE_TEMPLATE_AMD3DNOW 0
 #define RENAME(a) a ## _MMX2
-#include "swscale_template.c"
+#include "x86/swscale_template.c"
 #endif
 
 //3DNOW versions
-#ifdef COMPILE_3DNOW
+#if COMPILE_3DNOW
 #undef RENAME
 #undef COMPILE_TEMPLATE_MMX
 #undef COMPILE_TEMPLATE_MMX2
@@ -1232,44 +1188,36 @@ static inline void monoblack2Y(uint8_t *dst, const uint8_t *src, long width, uin
 #define COMPILE_TEMPLATE_MMX2 0
 #define COMPILE_TEMPLATE_AMD3DNOW 1
 #define RENAME(a) a ## _3DNow
-#include "swscale_template.c"
+#include "x86/swscale_template.c"
 #endif
 
 #endif //ARCH_X86
 
 SwsFunc ff_getSwsFunc(SwsContext *c)
 {
-#if CONFIG_RUNTIME_CPUDETECT
-    int flags = c->flags;
+    sws_init_swScale_c(c);
 
+#if CONFIG_RUNTIME_CPUDETECT
 #if ARCH_X86
     // ordered per speed fastest first
-    if (flags & SWS_CPU_CAPS_MMX2) {
+    if (c->flags & SWS_CPU_CAPS_MMX2) {
         sws_init_swScale_MMX2(c);
         return swScale_MMX2;
-    } else if (flags & SWS_CPU_CAPS_3DNOW) {
+    } else if (c->flags & SWS_CPU_CAPS_3DNOW) {
         sws_init_swScale_3DNow(c);
         return swScale_3DNow;
-    } else if (flags & SWS_CPU_CAPS_MMX) {
+    } else if (c->flags & SWS_CPU_CAPS_MMX) {
         sws_init_swScale_MMX(c);
         return swScale_MMX;
-    } else {
-        sws_init_swScale_C(c);
-        return swScale_C;
     }
 
 #else
-#ifdef COMPILE_ALTIVEC
-    if (flags & SWS_CPU_CAPS_ALTIVEC) {
+#if COMPILE_ALTIVEC
+    if (c->flags & SWS_CPU_CAPS_ALTIVEC) {
         sws_init_swScale_altivec(c);
         return swScale_altivec;
-    } else {
-        sws_init_swScale_C(c);
-        return swScale_C;
     }
 #endif
-    sws_init_swScale_C(c);
-    return swScale_C;
 #endif /* ARCH_X86 */
 #else //CONFIG_RUNTIME_CPUDETECT
 #if   COMPILE_TEMPLATE_MMX2
@@ -1284,31 +1232,37 @@ SwsFunc ff_getSwsFunc(SwsContext *c)
 #elif COMPILE_TEMPLATE_ALTIVEC
     sws_init_swScale_altivec(c);
     return swScale_altivec;
-#else
-    sws_init_swScale_C(c);
-    return swScale_C;
 #endif
 #endif //!CONFIG_RUNTIME_CPUDETECT
+
+    return swScale_c;
 }
 
-static int planarToNv12Wrapper(SwsContext *c, const uint8_t* src[], int srcStride[], int srcSliceY,
-                               int srcSliceH, uint8_t* dstParam[], int dstStride[])
+static void copyPlane(const uint8_t *src, int srcStride,
+                      int srcSliceY, int srcSliceH, int width,
+                      uint8_t *dst, int dstStride)
 {
-    uint8_t *dst=dstParam[0] + dstStride[0]*srcSliceY;
-    /* Copy Y plane */
-    if (dstStride[0]==srcStride[0] && srcStride[0] > 0)
-        memcpy(dst, src[0], srcSliceH*dstStride[0]);
-    else {
+    dst += dstStride * srcSliceY;
+    if (dstStride == srcStride && srcStride > 0) {
+        memcpy(dst, src, srcSliceH * dstStride);
+    } else {
         int i;
-        const uint8_t *srcPtr= src[0];
-        uint8_t *dstPtr= dst;
         for (i=0; i<srcSliceH; i++) {
-            memcpy(dstPtr, srcPtr, c->srcW);
-            srcPtr+= srcStride[0];
-            dstPtr+= dstStride[0];
+            memcpy(dst, src, width);
+            src += srcStride;
+            dst += dstStride;
         }
     }
-    dst = dstParam[1] + dstStride[1]*srcSliceY/2;
+}
+
+static int planarToNv12Wrapper(SwsContext *c, const uint8_t* src[], int srcStride[], int srcSliceY,
+                               int srcSliceH, uint8_t* dstParam[], int dstStride[])
+{
+    uint8_t *dst = dstParam[1] + dstStride[1]*srcSliceY/2;
+
+    copyPlane(src[0], srcStride[0], srcSliceY, srcSliceH, c->srcW,
+              dstParam[0], dstStride[0]);
+
     if (c->dstFormat == PIX_FMT_NV12)
         interleaveBytes(src[1], src[2], dst, c->srcW/2, srcSliceH/2, srcStride[1], srcStride[2], dstStride[0]);
     else
@@ -1411,6 +1365,34 @@ static int uyvyToYuv422Wrapper(SwsContext *c, const uint8_t* src[], int srcStrid
     return srcSliceH;
 }
 
+static void gray8aToPacked32(const uint8_t *src, uint8_t *dst, long num_pixels, const uint8_t *palette)
+{
+    long i;
+    for (i=0; i<num_pixels; i++)
+        ((uint32_t *) dst)[i] = ((const uint32_t *)palette)[src[i<<1]] | (src[(i<<1)+1] << 24);
+}
+
+static void gray8aToPacked32_1(const uint8_t *src, uint8_t *dst, long num_pixels, const uint8_t *palette)
+{
+    long i;
+
+    for (i=0; i<num_pixels; i++)
+        ((uint32_t *) dst)[i] = ((const uint32_t *)palette)[src[i<<1]] | src[(i<<1)+1];
+}
+
+static void gray8aToPacked24(const uint8_t *src, uint8_t *dst, long num_pixels, const uint8_t *palette)
+{
+    long i;
+
+    for (i=0; i<num_pixels; i++) {
+        //FIXME slow?
+        dst[0]= palette[src[i<<1]*4+0];
+        dst[1]= palette[src[i<<1]*4+1];
+        dst[2]= palette[src[i<<1]*4+2];
+        dst+= 3;
+    }
+}
+
 static int palToRgbWrapper(SwsContext *c, const uint8_t* src[], int srcStride[], int srcSliceY,
                            int srcSliceH, uint8_t* dst[], int dstStride[])
 {
@@ -1422,7 +1404,16 @@ static int palToRgbWrapper(SwsContext *c, const uint8_t* src[], int srcStride[],
     uint8_t *dstPtr= dst[0] + dstStride[0]*srcSliceY;
     const uint8_t *srcPtr= src[0];
 
-    if (usePal(srcFormat)) {
+    if (srcFormat == PIX_FMT_Y400A) {
+        switch (dstFormat) {
+        case PIX_FMT_RGB32  : conv = gray8aToPacked32; break;
+        case PIX_FMT_BGR32  : conv = gray8aToPacked32; break;
+        case PIX_FMT_BGR32_1: conv = gray8aToPacked32_1; break;
+        case PIX_FMT_RGB32_1: conv = gray8aToPacked32_1; break;
+        case PIX_FMT_RGB24  : conv = gray8aToPacked24; break;
+        case PIX_FMT_BGR24  : conv = gray8aToPacked24; break;
+        }
+    } else if (usePal(srcFormat)) {
         switch (dstFormat) {
         case PIX_FMT_RGB32  : conv = sws_convertPalette8ToPacked32; break;
         case PIX_FMT_BGR32  : conv = sws_convertPalette8ToPacked32; break;
@@ -1566,33 +1557,13 @@ static int bgr24ToYv12Wrapper(SwsContext *c, const uint8_t* src[], int srcStride
 static int yvu9ToYv12Wrapper(SwsContext *c, const uint8_t* src[], int srcStride[], int srcSliceY,
                              int srcSliceH, uint8_t* dst[], int dstStride[])
 {
-    int i;
+    copyPlane(src[0], srcStride[0], srcSliceY, srcSliceH, c->srcW,
+              dst[0], dstStride[0]);
 
-    /* copy Y */
-    if (srcStride[0]==dstStride[0] && srcStride[0] > 0)
-        memcpy(dst[0]+ srcSliceY*dstStride[0], src[0], srcStride[0]*srcSliceH);
-    else {
-        const uint8_t *srcPtr= src[0];
-        uint8_t *dstPtr= dst[0] + dstStride[0]*srcSliceY;
-
-        for (i=0; i<srcSliceH; i++) {
-            memcpy(dstPtr, srcPtr, c->srcW);
-            srcPtr+= srcStride[0];
-            dstPtr+= dstStride[0];
-        }
-    }
-
-    if (c->dstFormat==PIX_FMT_YUV420P || c->dstFormat==PIX_FMT_YUVA420P) {
-        planar2x(src[1], dst[1] + dstStride[1]*(srcSliceY >> 1), c->chrSrcW,
-                 srcSliceH >> 2, srcStride[1], dstStride[1]);
-        planar2x(src[2], dst[2] + dstStride[2]*(srcSliceY >> 1), c->chrSrcW,
-                 srcSliceH >> 2, srcStride[2], dstStride[2]);
-    } else {
-        planar2x(src[1], dst[2] + dstStride[2]*(srcSliceY >> 1), c->chrSrcW,
-                 srcSliceH >> 2, srcStride[1], dstStride[2]);
-        planar2x(src[2], dst[1] + dstStride[1]*(srcSliceY >> 1), c->chrSrcW,
-                 srcSliceH >> 2, srcStride[2], dstStride[1]);
-    }
+    planar2x(src[1], dst[1] + dstStride[1]*(srcSliceY >> 1), c->chrSrcW,
+             srcSliceH >> 2, srcStride[1], dstStride[1]);
+    planar2x(src[2], dst[2] + dstStride[2]*(srcSliceY >> 1), c->chrSrcW,
+             srcSliceH >> 2, srcStride[2], dstStride[2]);
     if (dst[3])
         fillPlane(dst[3], dstStride[3], c->srcW, srcSliceH, srcSliceY, 255);
     return srcSliceH;
@@ -1664,13 +1635,15 @@ static int planarCopyWrapper(SwsContext *c, const uint8_t* src[], int srcStride[
 
                 for (i=0; i<height; i++) {
                     for (j=0; j<length; j++)
-                        ((uint16_t*)dstPtr)[j] = bswap_16(((const uint16_t*)srcPtr)[j]);
+                        ((uint16_t*)dstPtr)[j] = av_bswap16(((const uint16_t*)srcPtr)[j]);
                     srcPtr+= srcStride[plane];
                     dstPtr+= dstStride[plane];
                 }
-            } else if (dstStride[plane]==srcStride[plane] && srcStride[plane] > 0)
-                memcpy(dst[plane] + dstStride[plane]*y, src[plane], height*dstStride[plane]);
-            else {
+            } else if (dstStride[plane] == srcStride[plane] &&
+                       srcStride[plane] > 0 && srcStride[plane] == length) {
+                memcpy(dst[plane] + dstStride[plane]*y, src[plane],
+                       height*dstStride[plane]);
+            } else {
                 if(is16BPS(c->srcFormat) && is16BPS(c->dstFormat))
                     length*=2;
                 for (i=0; i<height; i++) {
@@ -1782,7 +1755,7 @@ void ff_get_unscaled_swscale(SwsContext *c)
     if(srcFormat == PIX_FMT_UYVY422 && dstFormat == PIX_FMT_YUV422P)
         c->swScale= uyvyToYuv422Wrapper;
 
-#ifdef COMPILE_ALTIVEC
+#if COMPILE_ALTIVEC
     if ((c->flags & SWS_CPU_CAPS_ALTIVEC) &&
         !(c->flags & SWS_BITEXACT) &&
         srcFormat == PIX_FMT_YUV420P) {
@@ -1830,6 +1803,21 @@ static void reset_ptr(const uint8_t* src[], int format)
     }
 }
 
+static int check_image_pointers(uint8_t *data[4], enum PixelFormat pix_fmt,
+                                const int linesizes[4])
+{
+    const AVPixFmtDescriptor *desc = &av_pix_fmt_descriptors[pix_fmt];
+    int i;
+
+    for (i = 0; i < 4; i++) {
+        int plane = desc->comp[i].plane;
+        if (!data[plane] || !linesizes[plane])
+            return 0;
+    }
+
+    return 1;
+}
+
 /**
  * swscale wrapper, so we don't need to export the SwsContext.
  * Assumes planar YUV to be in YUV order instead of YVU.
@@ -1845,6 +1833,15 @@ int sws_scale(SwsContext *c, const uint8_t* const src[], const int srcStride[],
     if (srcSliceH == 0)
         return 0;
 
+    if (!check_image_pointers(src, c->srcFormat, srcStride)) {
+        av_log(c, AV_LOG_ERROR, "bad src image pointers\n");
+        return 0;
+    }
+    if (!check_image_pointers(dst, c->dstFormat, dstStride)) {
+        av_log(c, AV_LOG_ERROR, "bad dst image pointers\n");
+        return 0;
+    }
+
     if (c->sliceDir == 0 && srcSliceY != 0 && srcSliceY + srcSliceH != c->srcH) {
         av_log(c, AV_LOG_ERROR, "Slices start in the middle!\n");
         return 0;
@@ -1873,7 +1870,7 @@ int sws_scale(SwsContext *c, const uint8_t* const src[], const int srcStride[],
                 r= (i>>3    )*255;
                 g= ((i>>1)&3)*85;
                 b= (i&1     )*255;
-            } else if(c->srcFormat == PIX_FMT_GRAY8) {
+            } else if(c->srcFormat == PIX_FMT_GRAY8 || c->srcFormat == PIX_FMT_Y400A) {
                 r = g = b = i;
             } else {
                 assert(c->srcFormat == PIX_FMT_BGR4_BYTE);
diff --git a/libswscale/swscale.h b/libswscale/swscale.h
index 1e7af3a..5b0802c 100644
--- a/libswscale/swscale.h
+++ b/libswscale/swscale.h
@@ -1,20 +1,20 @@
 /*
  * Copyright (C) 2001-2003 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -29,8 +29,8 @@
 
 #include "libavutil/avutil.h"
 
-#define LIBSWSCALE_VERSION_MAJOR 0
-#define LIBSWSCALE_VERSION_MINOR 11
+#define LIBSWSCALE_VERSION_MAJOR 1
+#define LIBSWSCALE_VERSION_MINOR 0
 #define LIBSWSCALE_VERSION_MICRO 0
 
 #define LIBSWSCALE_VERSION_INT  AV_VERSION_INT(LIBSWSCALE_VERSION_MAJOR, \
@@ -44,6 +44,14 @@
 #define LIBSWSCALE_IDENT        "SwS" AV_STRINGIFY(LIBSWSCALE_VERSION)
 
 /**
+ * Those FF_API_* defines are not part of public API.
+ * They may change, break or disappear at any time.
+ */
+#ifndef FF_API_SWS_GETCONTEXT
+#define FF_API_SWS_GETCONTEXT  (LIBSWSCALE_VERSION_MAJOR < 2)
+#endif
+
+/**
  * Returns the LIBSWSCALE_VERSION_INT constant.
  */
 unsigned swscale_version(void);
@@ -92,6 +100,7 @@ const char *swscale_license(void);
 #define SWS_CPU_CAPS_3DNOW    0x40000000
 #define SWS_CPU_CAPS_ALTIVEC  0x10000000
 #define SWS_CPU_CAPS_BFIN     0x01000000
+#define SWS_CPU_CAPS_SSE2     0x02000000
 
 #define SWS_MAX_REDUCE_CUTOFF 0.002
 
@@ -143,11 +152,27 @@ int sws_isSupportedInput(enum PixelFormat pix_fmt);
 int sws_isSupportedOutput(enum PixelFormat pix_fmt);
 
 /**
+ * Allocates an empty SwsContext. This must be filled and passed to
+ * sws_init_context(). For filling see AVOptions, options.c and
+ * sws_setColorspaceDetails().
+ */
+struct SwsContext *sws_alloc_context(void);
+
+/**
+ * Initializes the swscaler context sws_context.
+ *
+ * @return zero or positive value on success, a negative value on
+ * error
+ */
+int sws_init_context(struct SwsContext *sws_context, SwsFilter *srcFilter, SwsFilter *dstFilter);
+
+/**
  * Frees the swscaler context swsContext.
  * If swsContext is NULL, then does nothing.
  */
 void sws_freeContext(struct SwsContext *swsContext);
 
+#if FF_API_SWS_GETCONTEXT
 /**
  * Allocates and returns a SwsContext. You need it to perform
  * scaling/conversion operations using sws_scale().
@@ -160,11 +185,14 @@ void sws_freeContext(struct SwsContext *swsContext);
  * @param dstFormat the destination image format
  * @param flags specify which algorithm and options to use for rescaling
  * @return a pointer to an allocated context, or NULL in case of error
+ * @note this function is to be removed after a saner alternative is
+ *       written
  */
 struct SwsContext *sws_getContext(int srcW, int srcH, enum PixelFormat srcFormat,
                                   int dstW, int dstH, enum PixelFormat dstFormat,
                                   int flags, SwsFilter *srcFilter,
                                   SwsFilter *dstFilter, const double *param);
+#endif
 
 /**
  * Scales the image slice in srcSlice and puts the resulting scaled
@@ -194,6 +222,7 @@ struct SwsContext *sws_getContext(int srcW, int srcH, enum PixelFormat srcFormat
  */
 int sws_scale(struct SwsContext *context, const uint8_t* const srcSlice[], const int srcStride[],
               int srcSliceY, int srcSliceH, uint8_t* const dst[], const int dstStride[]);
+
 #if LIBSWSCALE_VERSION_MAJOR < 1
 /**
  * @deprecated Use sws_scale() instead.
diff --git a/libswscale/swscale_internal.h b/libswscale/swscale_internal.h
index 5be17d4..4c6ad2a 100644
--- a/libswscale/swscale_internal.h
+++ b/libswscale/swscale_internal.h
@@ -1,20 +1,20 @@
 /*
  * Copyright (C) 2001-2003 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -31,6 +31,8 @@
 
 #define STR(s)         AV_TOSTRING(s) //AV_STRINGIFY is too long
 
+#define FAST_BGR2YV12 //use 7-bit instead of 15-bit coefficients
+
 #define MAX_FILTER_SIZE 256
 
 #if ARCH_X86
@@ -331,8 +333,8 @@ SwsFunc ff_yuv2rgb_init_altivec(SwsContext *c);
 SwsFunc ff_yuv2rgb_get_func_ptr_bfin(SwsContext *c);
 void ff_bfin_get_unscaled_swscale(SwsContext *c);
 void ff_yuv2packedX_altivec(SwsContext *c,
-                            const int16_t *lumFilter, int16_t **lumSrc, int lumFilterSize,
-                            const int16_t *chrFilter, int16_t **chrSrc, int chrFilterSize,
+                            const int16_t *lumFilter, const int16_t **lumSrc, int lumFilterSize,
+                            const int16_t *chrFilter, const int16_t **chrSrc, int chrFilterSize,
                             uint8_t *dest, int dstW, int dstY);
 
 const char *sws_format_name(enum PixelFormat format);
@@ -343,12 +345,12 @@ const char *sws_format_name(enum PixelFormat format);
         || (x)==PIX_FMT_GRAY16LE    \
         || (x)==PIX_FMT_RGB48BE     \
         || (x)==PIX_FMT_RGB48LE     \
-        || (x)==PIX_FMT_YUV420P16LE   \
-        || (x)==PIX_FMT_YUV422P16LE   \
-        || (x)==PIX_FMT_YUV444P16LE   \
-        || (x)==PIX_FMT_YUV420P16BE   \
-        || (x)==PIX_FMT_YUV422P16BE   \
-        || (x)==PIX_FMT_YUV444P16BE   \
+        || (x)==PIX_FMT_YUV420P16LE \
+        || (x)==PIX_FMT_YUV422P16LE \
+        || (x)==PIX_FMT_YUV444P16LE \
+        || (x)==PIX_FMT_YUV420P16BE \
+        || (x)==PIX_FMT_YUV422P16BE \
+        || (x)==PIX_FMT_YUV444P16BE \
     )
 #define isBE(x) ((x)&1)
 #define isPlanar8YUV(x) (           \
@@ -364,12 +366,12 @@ const char *sws_format_name(enum PixelFormat format);
     )
 #define isPlanarYUV(x)  (           \
         isPlanar8YUV(x)             \
-        || (x)==PIX_FMT_YUV420P16LE   \
-        || (x)==PIX_FMT_YUV422P16LE   \
-        || (x)==PIX_FMT_YUV444P16LE   \
-        || (x)==PIX_FMT_YUV420P16BE   \
-        || (x)==PIX_FMT_YUV422P16BE   \
-        || (x)==PIX_FMT_YUV444P16BE   \
+        || (x)==PIX_FMT_YUV420P16LE \
+        || (x)==PIX_FMT_YUV422P16LE \
+        || (x)==PIX_FMT_YUV444P16LE \
+        || (x)==PIX_FMT_YUV420P16BE \
+        || (x)==PIX_FMT_YUV422P16BE \
+        || (x)==PIX_FMT_YUV444P16BE \
     )
 #define isYUV(x)        (           \
            (x)==PIX_FMT_UYVY422     \
@@ -378,6 +380,7 @@ const char *sws_format_name(enum PixelFormat format);
     )
 #define isGray(x)       (           \
            (x)==PIX_FMT_GRAY8       \
+        || (x)==PIX_FMT_Y400A      \
         || (x)==PIX_FMT_GRAY16BE    \
         || (x)==PIX_FMT_GRAY16LE    \
     )
@@ -440,9 +443,10 @@ const char *sws_format_name(enum PixelFormat format);
         || (x)==PIX_FMT_BGR32_1     \
         || (x)==PIX_FMT_RGB32       \
         || (x)==PIX_FMT_RGB32_1     \
+        || (x)==PIX_FMT_Y400A       \
         || (x)==PIX_FMT_YUVA420P    \
     )
-#define usePal(x) (av_pix_fmt_descriptors[x].flags & PIX_FMT_PAL)
+#define usePal(x) ((av_pix_fmt_descriptors[x].flags & PIX_FMT_PAL) || (x) == PIX_FMT_Y400A)
 
 extern const uint64_t ff_dither4[2];
 extern const uint64_t ff_dither8[2];
diff --git a/libswscale/swscale_template.c b/libswscale/swscale_template.c
index 0d259ed..e8d3f28 100644
--- a/libswscale/swscale_template.c
+++ b/libswscale/swscale_template.c
@@ -1,986 +1,52 @@
 /*
  * Copyright (C) 2001-2003 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
-#undef REAL_MOVNTQ
-#undef MOVNTQ
-#undef PAVGB
-#undef PREFETCH
-
-#if COMPILE_TEMPLATE_AMD3DNOW
-#define PREFETCH  "prefetch"
-#elif COMPILE_TEMPLATE_MMX2
-#define PREFETCH "prefetchnta"
-#else
-#define PREFETCH  " # nop"
-#endif
-
-#if COMPILE_TEMPLATE_MMX2
-#define PAVGB(a,b) "pavgb " #a ", " #b " \n\t"
-#elif COMPILE_TEMPLATE_AMD3DNOW
-#define PAVGB(a,b) "pavgusb " #a ", " #b " \n\t"
-#endif
-
-#if COMPILE_TEMPLATE_MMX2
-#define REAL_MOVNTQ(a,b) "movntq " #a ", " #b " \n\t"
-#else
-#define REAL_MOVNTQ(a,b) "movq " #a ", " #b " \n\t"
-#endif
-#define MOVNTQ(a,b)  REAL_MOVNTQ(a,b)
-
-#if COMPILE_TEMPLATE_ALTIVEC
-#include "ppc/swscale_altivec_template.c"
-#endif
-
-#define YSCALEYUV2YV12X(x, offset, dest, width) \
-    __asm__ volatile(\
-        "xor                          %%"REG_a", %%"REG_a"  \n\t"\
-        "movq             "VROUNDER_OFFSET"(%0), %%mm3      \n\t"\
-        "movq                             %%mm3, %%mm4      \n\t"\
-        "lea                     " offset "(%0), %%"REG_d"  \n\t"\
-        "mov                        (%%"REG_d"), %%"REG_S"  \n\t"\
-        ASMALIGN(4) /* FIXME Unroll? */\
-        "1:                                                 \n\t"\
-        "movq                      8(%%"REG_d"), %%mm0      \n\t" /* filterCoeff */\
-        "movq   "  x "(%%"REG_S", %%"REG_a", 2), %%mm2      \n\t" /* srcData */\
-        "movq 8+"  x "(%%"REG_S", %%"REG_a", 2), %%mm5      \n\t" /* srcData */\
-        "add                                $16, %%"REG_d"  \n\t"\
-        "mov                        (%%"REG_d"), %%"REG_S"  \n\t"\
-        "test                         %%"REG_S", %%"REG_S"  \n\t"\
-        "pmulhw                           %%mm0, %%mm2      \n\t"\
-        "pmulhw                           %%mm0, %%mm5      \n\t"\
-        "paddw                            %%mm2, %%mm3      \n\t"\
-        "paddw                            %%mm5, %%mm4      \n\t"\
-        " jnz                                1b             \n\t"\
-        "psraw                               $3, %%mm3      \n\t"\
-        "psraw                               $3, %%mm4      \n\t"\
-        "packuswb                         %%mm4, %%mm3      \n\t"\
-        MOVNTQ(%%mm3, (%1, %%REGa))\
-        "add                                 $8, %%"REG_a"  \n\t"\
-        "cmp                                 %2, %%"REG_a"  \n\t"\
-        "movq             "VROUNDER_OFFSET"(%0), %%mm3      \n\t"\
-        "movq                             %%mm3, %%mm4      \n\t"\
-        "lea                     " offset "(%0), %%"REG_d"  \n\t"\
-        "mov                        (%%"REG_d"), %%"REG_S"  \n\t"\
-        "jb                                  1b             \n\t"\
-        :: "r" (&c->redDither),\
-        "r" (dest), "g" (width)\
-        : "%"REG_a, "%"REG_d, "%"REG_S\
-    );
-
-#define YSCALEYUV2YV12X_ACCURATE(x, offset, dest, width) \
-    __asm__ volatile(\
-        "lea                     " offset "(%0), %%"REG_d"  \n\t"\
-        "xor                          %%"REG_a", %%"REG_a"  \n\t"\
-        "pxor                             %%mm4, %%mm4      \n\t"\
-        "pxor                             %%mm5, %%mm5      \n\t"\
-        "pxor                             %%mm6, %%mm6      \n\t"\
-        "pxor                             %%mm7, %%mm7      \n\t"\
-        "mov                        (%%"REG_d"), %%"REG_S"  \n\t"\
-        ASMALIGN(4) \
-        "1:                                                 \n\t"\
-        "movq   "  x "(%%"REG_S", %%"REG_a", 2), %%mm0      \n\t" /* srcData */\
-        "movq 8+"  x "(%%"REG_S", %%"REG_a", 2), %%mm2      \n\t" /* srcData */\
-        "mov        "STR(APCK_PTR2)"(%%"REG_d"), %%"REG_S"  \n\t"\
-        "movq   "  x "(%%"REG_S", %%"REG_a", 2), %%mm1      \n\t" /* srcData */\
-        "movq                             %%mm0, %%mm3      \n\t"\
-        "punpcklwd                        %%mm1, %%mm0      \n\t"\
-        "punpckhwd                        %%mm1, %%mm3      \n\t"\
-        "movq       "STR(APCK_COEF)"(%%"REG_d"), %%mm1      \n\t" /* filterCoeff */\
-        "pmaddwd                          %%mm1, %%mm0      \n\t"\
-        "pmaddwd                          %%mm1, %%mm3      \n\t"\
-        "paddd                            %%mm0, %%mm4      \n\t"\
-        "paddd                            %%mm3, %%mm5      \n\t"\
-        "movq 8+"  x "(%%"REG_S", %%"REG_a", 2), %%mm3      \n\t" /* srcData */\
-        "mov        "STR(APCK_SIZE)"(%%"REG_d"), %%"REG_S"  \n\t"\
-        "add                  $"STR(APCK_SIZE)", %%"REG_d"  \n\t"\
-        "test                         %%"REG_S", %%"REG_S"  \n\t"\
-        "movq                             %%mm2, %%mm0      \n\t"\
-        "punpcklwd                        %%mm3, %%mm2      \n\t"\
-        "punpckhwd                        %%mm3, %%mm0      \n\t"\
-        "pmaddwd                          %%mm1, %%mm2      \n\t"\
-        "pmaddwd                          %%mm1, %%mm0      \n\t"\
-        "paddd                            %%mm2, %%mm6      \n\t"\
-        "paddd                            %%mm0, %%mm7      \n\t"\
-        " jnz                                1b             \n\t"\
-        "psrad                              $16, %%mm4      \n\t"\
-        "psrad                              $16, %%mm5      \n\t"\
-        "psrad                              $16, %%mm6      \n\t"\
-        "psrad                              $16, %%mm7      \n\t"\
-        "movq             "VROUNDER_OFFSET"(%0), %%mm0      \n\t"\
-        "packssdw                         %%mm5, %%mm4      \n\t"\
-        "packssdw                         %%mm7, %%mm6      \n\t"\
-        "paddw                            %%mm0, %%mm4      \n\t"\
-        "paddw                            %%mm0, %%mm6      \n\t"\
-        "psraw                               $3, %%mm4      \n\t"\
-        "psraw                               $3, %%mm6      \n\t"\
-        "packuswb                         %%mm6, %%mm4      \n\t"\
-        MOVNTQ(%%mm4, (%1, %%REGa))\
-        "add                                 $8, %%"REG_a"  \n\t"\
-        "cmp                                 %2, %%"REG_a"  \n\t"\
-        "lea                     " offset "(%0), %%"REG_d"  \n\t"\
-        "pxor                             %%mm4, %%mm4      \n\t"\
-        "pxor                             %%mm5, %%mm5      \n\t"\
-        "pxor                             %%mm6, %%mm6      \n\t"\
-        "pxor                             %%mm7, %%mm7      \n\t"\
-        "mov                        (%%"REG_d"), %%"REG_S"  \n\t"\
-        "jb                                  1b             \n\t"\
-        :: "r" (&c->redDither),\
-        "r" (dest), "g" (width)\
-        : "%"REG_a, "%"REG_d, "%"REG_S\
-    );
-
-#define YSCALEYUV2YV121 \
-    "mov %2, %%"REG_a"                    \n\t"\
-    ASMALIGN(4) /* FIXME Unroll? */\
-    "1:                                   \n\t"\
-    "movq  (%0, %%"REG_a", 2), %%mm0      \n\t"\
-    "movq 8(%0, %%"REG_a", 2), %%mm1      \n\t"\
-    "psraw                 $7, %%mm0      \n\t"\
-    "psraw                 $7, %%mm1      \n\t"\
-    "packuswb           %%mm1, %%mm0      \n\t"\
-    MOVNTQ(%%mm0, (%1, %%REGa))\
-    "add                   $8, %%"REG_a"  \n\t"\
-    "jnc                   1b             \n\t"
-
-#define YSCALEYUV2YV121_ACCURATE \
-    "mov %2, %%"REG_a"                    \n\t"\
-    "pcmpeqw %%mm7, %%mm7                 \n\t"\
-    "psrlw                 $15, %%mm7     \n\t"\
-    "psllw                  $6, %%mm7     \n\t"\
-    ASMALIGN(4) /* FIXME Unroll? */\
-    "1:                                   \n\t"\
-    "movq  (%0, %%"REG_a", 2), %%mm0      \n\t"\
-    "movq 8(%0, %%"REG_a", 2), %%mm1      \n\t"\
-    "paddsw             %%mm7, %%mm0      \n\t"\
-    "paddsw             %%mm7, %%mm1      \n\t"\
-    "psraw                 $7, %%mm0      \n\t"\
-    "psraw                 $7, %%mm1      \n\t"\
-    "packuswb           %%mm1, %%mm0      \n\t"\
-    MOVNTQ(%%mm0, (%1, %%REGa))\
-    "add                   $8, %%"REG_a"  \n\t"\
-    "jnc                   1b             \n\t"
-
-/*
-    :: "m" (-lumFilterSize), "m" (-chrFilterSize),
-       "m" (lumMmxFilter+lumFilterSize*4), "m" (chrMmxFilter+chrFilterSize*4),
-       "r" (dest), "m" (dstW),
-       "m" (lumSrc+lumFilterSize), "m" (chrSrc+chrFilterSize)
-    : "%eax", "%ebx", "%ecx", "%edx", "%esi"
-*/
-#define YSCALEYUV2PACKEDX_UV \
-    __asm__ volatile(\
-        "xor                   %%"REG_a", %%"REG_a"     \n\t"\
-        ASMALIGN(4)\
-        "nop                                            \n\t"\
-        "1:                                             \n\t"\
-        "lea "CHR_MMX_FILTER_OFFSET"(%0), %%"REG_d"     \n\t"\
-        "mov                 (%%"REG_d"), %%"REG_S"     \n\t"\
-        "movq      "VROUNDER_OFFSET"(%0), %%mm3         \n\t"\
-        "movq                      %%mm3, %%mm4         \n\t"\
-        ASMALIGN(4)\
-        "2:                                             \n\t"\
-        "movq               8(%%"REG_d"), %%mm0         \n\t" /* filterCoeff */\
-        "movq     (%%"REG_S", %%"REG_a"), %%mm2         \n\t" /* UsrcData */\
-        "movq "AV_STRINGIFY(VOF)"(%%"REG_S", %%"REG_a"), %%mm5         \n\t" /* VsrcData */\
-        "add                         $16, %%"REG_d"     \n\t"\
-        "mov                 (%%"REG_d"), %%"REG_S"     \n\t"\
-        "pmulhw                    %%mm0, %%mm2         \n\t"\
-        "pmulhw                    %%mm0, %%mm5         \n\t"\
-        "paddw                     %%mm2, %%mm3         \n\t"\
-        "paddw                     %%mm5, %%mm4         \n\t"\
-        "test                  %%"REG_S", %%"REG_S"     \n\t"\
-        " jnz                         2b                \n\t"\
-
-#define YSCALEYUV2PACKEDX_YA(offset,coeff,src1,src2,dst1,dst2) \
-    "lea                "offset"(%0), %%"REG_d"     \n\t"\
-    "mov                 (%%"REG_d"), %%"REG_S"     \n\t"\
-    "movq      "VROUNDER_OFFSET"(%0), "#dst1"       \n\t"\
-    "movq                    "#dst1", "#dst2"       \n\t"\
-    ASMALIGN(4)\
-    "2:                                             \n\t"\
-    "movq               8(%%"REG_d"), "#coeff"      \n\t" /* filterCoeff */\
-    "movq  (%%"REG_S", %%"REG_a", 2), "#src1"       \n\t" /* Y1srcData */\
-    "movq 8(%%"REG_S", %%"REG_a", 2), "#src2"       \n\t" /* Y2srcData */\
-    "add                         $16, %%"REG_d"            \n\t"\
-    "mov                 (%%"REG_d"), %%"REG_S"     \n\t"\
-    "pmulhw                 "#coeff", "#src1"       \n\t"\
-    "pmulhw                 "#coeff", "#src2"       \n\t"\
-    "paddw                   "#src1", "#dst1"       \n\t"\
-    "paddw                   "#src2", "#dst2"       \n\t"\
-    "test                  %%"REG_S", %%"REG_S"     \n\t"\
-    " jnz                         2b                \n\t"\
-
-#define YSCALEYUV2PACKEDX \
-    YSCALEYUV2PACKEDX_UV \
-    YSCALEYUV2PACKEDX_YA(LUM_MMX_FILTER_OFFSET,%%mm0,%%mm2,%%mm5,%%mm1,%%mm7) \
-
-#define YSCALEYUV2PACKEDX_END                     \
-        :: "r" (&c->redDither),                   \
-            "m" (dummy), "m" (dummy), "m" (dummy),\
-            "r" (dest), "m" (dstW)                \
-        : "%"REG_a, "%"REG_d, "%"REG_S            \
-    );
-
-#define YSCALEYUV2PACKEDX_ACCURATE_UV \
-    __asm__ volatile(\
-        "xor %%"REG_a", %%"REG_a"                       \n\t"\
-        ASMALIGN(4)\
-        "nop                                            \n\t"\
-        "1:                                             \n\t"\
-        "lea "CHR_MMX_FILTER_OFFSET"(%0), %%"REG_d"     \n\t"\
-        "mov                 (%%"REG_d"), %%"REG_S"     \n\t"\
-        "pxor                      %%mm4, %%mm4         \n\t"\
-        "pxor                      %%mm5, %%mm5         \n\t"\
-        "pxor                      %%mm6, %%mm6         \n\t"\
-        "pxor                      %%mm7, %%mm7         \n\t"\
-        ASMALIGN(4)\
-        "2:                                             \n\t"\
-        "movq     (%%"REG_S", %%"REG_a"), %%mm0         \n\t" /* UsrcData */\
-        "movq "AV_STRINGIFY(VOF)"(%%"REG_S", %%"REG_a"), %%mm2         \n\t" /* VsrcData */\
-        "mov "STR(APCK_PTR2)"(%%"REG_d"), %%"REG_S"     \n\t"\
-        "movq     (%%"REG_S", %%"REG_a"), %%mm1         \n\t" /* UsrcData */\
-        "movq                      %%mm0, %%mm3         \n\t"\
-        "punpcklwd                 %%mm1, %%mm0         \n\t"\
-        "punpckhwd                 %%mm1, %%mm3         \n\t"\
-        "movq "STR(APCK_COEF)"(%%"REG_d"),%%mm1         \n\t" /* filterCoeff */\
-        "pmaddwd                   %%mm1, %%mm0         \n\t"\
-        "pmaddwd                   %%mm1, %%mm3         \n\t"\
-        "paddd                     %%mm0, %%mm4         \n\t"\
-        "paddd                     %%mm3, %%mm5         \n\t"\
-        "movq "AV_STRINGIFY(VOF)"(%%"REG_S", %%"REG_a"), %%mm3         \n\t" /* VsrcData */\
-        "mov "STR(APCK_SIZE)"(%%"REG_d"), %%"REG_S"     \n\t"\
-        "add           $"STR(APCK_SIZE)", %%"REG_d"     \n\t"\
-        "test                  %%"REG_S", %%"REG_S"     \n\t"\
-        "movq                      %%mm2, %%mm0         \n\t"\
-        "punpcklwd                 %%mm3, %%mm2         \n\t"\
-        "punpckhwd                 %%mm3, %%mm0         \n\t"\
-        "pmaddwd                   %%mm1, %%mm2         \n\t"\
-        "pmaddwd                   %%mm1, %%mm0         \n\t"\
-        "paddd                     %%mm2, %%mm6         \n\t"\
-        "paddd                     %%mm0, %%mm7         \n\t"\
-        " jnz                         2b                \n\t"\
-        "psrad                       $16, %%mm4         \n\t"\
-        "psrad                       $16, %%mm5         \n\t"\
-        "psrad                       $16, %%mm6         \n\t"\
-        "psrad                       $16, %%mm7         \n\t"\
-        "movq      "VROUNDER_OFFSET"(%0), %%mm0         \n\t"\
-        "packssdw                  %%mm5, %%mm4         \n\t"\
-        "packssdw                  %%mm7, %%mm6         \n\t"\
-        "paddw                     %%mm0, %%mm4         \n\t"\
-        "paddw                     %%mm0, %%mm6         \n\t"\
-        "movq                      %%mm4, "U_TEMP"(%0)  \n\t"\
-        "movq                      %%mm6, "V_TEMP"(%0)  \n\t"\
-
-#define YSCALEYUV2PACKEDX_ACCURATE_YA(offset) \
-    "lea                "offset"(%0), %%"REG_d"     \n\t"\
-    "mov                 (%%"REG_d"), %%"REG_S"     \n\t"\
-    "pxor                      %%mm1, %%mm1         \n\t"\
-    "pxor                      %%mm5, %%mm5         \n\t"\
-    "pxor                      %%mm7, %%mm7         \n\t"\
-    "pxor                      %%mm6, %%mm6         \n\t"\
-    ASMALIGN(4)\
-    "2:                                             \n\t"\
-    "movq  (%%"REG_S", %%"REG_a", 2), %%mm0         \n\t" /* Y1srcData */\
-    "movq 8(%%"REG_S", %%"REG_a", 2), %%mm2         \n\t" /* Y2srcData */\
-    "mov "STR(APCK_PTR2)"(%%"REG_d"), %%"REG_S"     \n\t"\
-    "movq  (%%"REG_S", %%"REG_a", 2), %%mm4         \n\t" /* Y1srcData */\
-    "movq                      %%mm0, %%mm3         \n\t"\
-    "punpcklwd                 %%mm4, %%mm0         \n\t"\
-    "punpckhwd                 %%mm4, %%mm3         \n\t"\
-    "movq "STR(APCK_COEF)"(%%"REG_d"), %%mm4         \n\t" /* filterCoeff */\
-    "pmaddwd                   %%mm4, %%mm0         \n\t"\
-    "pmaddwd                   %%mm4, %%mm3         \n\t"\
-    "paddd                     %%mm0, %%mm1         \n\t"\
-    "paddd                     %%mm3, %%mm5         \n\t"\
-    "movq 8(%%"REG_S", %%"REG_a", 2), %%mm3         \n\t" /* Y2srcData */\
-    "mov "STR(APCK_SIZE)"(%%"REG_d"), %%"REG_S"     \n\t"\
-    "add           $"STR(APCK_SIZE)", %%"REG_d"     \n\t"\
-    "test                  %%"REG_S", %%"REG_S"     \n\t"\
-    "movq                      %%mm2, %%mm0         \n\t"\
-    "punpcklwd                 %%mm3, %%mm2         \n\t"\
-    "punpckhwd                 %%mm3, %%mm0         \n\t"\
-    "pmaddwd                   %%mm4, %%mm2         \n\t"\
-    "pmaddwd                   %%mm4, %%mm0         \n\t"\
-    "paddd                     %%mm2, %%mm7         \n\t"\
-    "paddd                     %%mm0, %%mm6         \n\t"\
-    " jnz                         2b                \n\t"\
-    "psrad                       $16, %%mm1         \n\t"\
-    "psrad                       $16, %%mm5         \n\t"\
-    "psrad                       $16, %%mm7         \n\t"\
-    "psrad                       $16, %%mm6         \n\t"\
-    "movq      "VROUNDER_OFFSET"(%0), %%mm0         \n\t"\
-    "packssdw                  %%mm5, %%mm1         \n\t"\
-    "packssdw                  %%mm6, %%mm7         \n\t"\
-    "paddw                     %%mm0, %%mm1         \n\t"\
-    "paddw                     %%mm0, %%mm7         \n\t"\
-    "movq               "U_TEMP"(%0), %%mm3         \n\t"\
-    "movq               "V_TEMP"(%0), %%mm4         \n\t"\
-
-#define YSCALEYUV2PACKEDX_ACCURATE \
-    YSCALEYUV2PACKEDX_ACCURATE_UV \
-    YSCALEYUV2PACKEDX_ACCURATE_YA(LUM_MMX_FILTER_OFFSET)
-
-#define YSCALEYUV2RGBX \
-    "psubw  "U_OFFSET"(%0), %%mm3       \n\t" /* (U-128)8*/\
-    "psubw  "V_OFFSET"(%0), %%mm4       \n\t" /* (V-128)8*/\
-    "movq            %%mm3, %%mm2       \n\t" /* (U-128)8*/\
-    "movq            %%mm4, %%mm5       \n\t" /* (V-128)8*/\
-    "pmulhw "UG_COEFF"(%0), %%mm3       \n\t"\
-    "pmulhw "VG_COEFF"(%0), %%mm4       \n\t"\
-    /* mm2=(U-128)8, mm3=ug, mm4=vg mm5=(V-128)8 */\
-    "pmulhw "UB_COEFF"(%0), %%mm2       \n\t"\
-    "pmulhw "VR_COEFF"(%0), %%mm5       \n\t"\
-    "psubw  "Y_OFFSET"(%0), %%mm1       \n\t" /* 8(Y-16)*/\
-    "psubw  "Y_OFFSET"(%0), %%mm7       \n\t" /* 8(Y-16)*/\
-    "pmulhw  "Y_COEFF"(%0), %%mm1       \n\t"\
-    "pmulhw  "Y_COEFF"(%0), %%mm7       \n\t"\
-    /* mm1= Y1, mm2=ub, mm3=ug, mm4=vg mm5=vr, mm7=Y2 */\
-    "paddw           %%mm3, %%mm4       \n\t"\
-    "movq            %%mm2, %%mm0       \n\t"\
-    "movq            %%mm5, %%mm6       \n\t"\
-    "movq            %%mm4, %%mm3       \n\t"\
-    "punpcklwd       %%mm2, %%mm2       \n\t"\
-    "punpcklwd       %%mm5, %%mm5       \n\t"\
-    "punpcklwd       %%mm4, %%mm4       \n\t"\
-    "paddw           %%mm1, %%mm2       \n\t"\
-    "paddw           %%mm1, %%mm5       \n\t"\
-    "paddw           %%mm1, %%mm4       \n\t"\
-    "punpckhwd       %%mm0, %%mm0       \n\t"\
-    "punpckhwd       %%mm6, %%mm6       \n\t"\
-    "punpckhwd       %%mm3, %%mm3       \n\t"\
-    "paddw           %%mm7, %%mm0       \n\t"\
-    "paddw           %%mm7, %%mm6       \n\t"\
-    "paddw           %%mm7, %%mm3       \n\t"\
-    /* mm0=B1, mm2=B2, mm3=G2, mm4=G1, mm5=R1, mm6=R2 */\
-    "packuswb        %%mm0, %%mm2       \n\t"\
-    "packuswb        %%mm6, %%mm5       \n\t"\
-    "packuswb        %%mm3, %%mm4       \n\t"\
-
-#define REAL_YSCALEYUV2PACKED(index, c) \
-    "movq "CHR_MMX_FILTER_OFFSET"+8("#c"), %%mm0              \n\t"\
-    "movq "LUM_MMX_FILTER_OFFSET"+8("#c"), %%mm1              \n\t"\
-    "psraw                $3, %%mm0                           \n\t"\
-    "psraw                $3, %%mm1                           \n\t"\
-    "movq              %%mm0, "CHR_MMX_FILTER_OFFSET"+8("#c") \n\t"\
-    "movq              %%mm1, "LUM_MMX_FILTER_OFFSET"+8("#c") \n\t"\
-    "xor            "#index", "#index"                        \n\t"\
-    ASMALIGN(4)\
-    "1:                                 \n\t"\
-    "movq     (%2, "#index"), %%mm2     \n\t" /* uvbuf0[eax]*/\
-    "movq     (%3, "#index"), %%mm3     \n\t" /* uvbuf1[eax]*/\
-    "movq "AV_STRINGIFY(VOF)"(%2, "#index"), %%mm5     \n\t" /* uvbuf0[eax+2048]*/\
-    "movq "AV_STRINGIFY(VOF)"(%3, "#index"), %%mm4     \n\t" /* uvbuf1[eax+2048]*/\
-    "psubw             %%mm3, %%mm2     \n\t" /* uvbuf0[eax] - uvbuf1[eax]*/\
-    "psubw             %%mm4, %%mm5     \n\t" /* uvbuf0[eax+2048] - uvbuf1[eax+2048]*/\
-    "movq "CHR_MMX_FILTER_OFFSET"+8("#c"), %%mm0    \n\t"\
-    "pmulhw            %%mm0, %%mm2     \n\t" /* (uvbuf0[eax] - uvbuf1[eax])uvalpha1>>16*/\
-    "pmulhw            %%mm0, %%mm5     \n\t" /* (uvbuf0[eax+2048] - uvbuf1[eax+2048])uvalpha1>>16*/\
-    "psraw                $7, %%mm3     \n\t" /* uvbuf0[eax] - uvbuf1[eax] >>4*/\
-    "psraw                $7, %%mm4     \n\t" /* uvbuf0[eax+2048] - uvbuf1[eax+2048] >>4*/\
-    "paddw             %%mm2, %%mm3     \n\t" /* uvbuf0[eax]uvalpha1 - uvbuf1[eax](1-uvalpha1)*/\
-    "paddw             %%mm5, %%mm4     \n\t" /* uvbuf0[eax+2048]uvalpha1 - uvbuf1[eax+2048](1-uvalpha1)*/\
-    "movq  (%0, "#index", 2), %%mm0     \n\t" /*buf0[eax]*/\
-    "movq  (%1, "#index", 2), %%mm1     \n\t" /*buf1[eax]*/\
-    "movq 8(%0, "#index", 2), %%mm6     \n\t" /*buf0[eax]*/\
-    "movq 8(%1, "#index", 2), %%mm7     \n\t" /*buf1[eax]*/\
-    "psubw             %%mm1, %%mm0     \n\t" /* buf0[eax] - buf1[eax]*/\
-    "psubw             %%mm7, %%mm6     \n\t" /* buf0[eax] - buf1[eax]*/\
-    "pmulhw "LUM_MMX_FILTER_OFFSET"+8("#c"), %%mm0  \n\t" /* (buf0[eax] - buf1[eax])yalpha1>>16*/\
-    "pmulhw "LUM_MMX_FILTER_OFFSET"+8("#c"), %%mm6  \n\t" /* (buf0[eax] - buf1[eax])yalpha1>>16*/\
-    "psraw                $7, %%mm1     \n\t" /* buf0[eax] - buf1[eax] >>4*/\
-    "psraw                $7, %%mm7     \n\t" /* buf0[eax] - buf1[eax] >>4*/\
-    "paddw             %%mm0, %%mm1     \n\t" /* buf0[eax]yalpha1 + buf1[eax](1-yalpha1) >>16*/\
-    "paddw             %%mm6, %%mm7     \n\t" /* buf0[eax]yalpha1 + buf1[eax](1-yalpha1) >>16*/\
-
-#define YSCALEYUV2PACKED(index, c)  REAL_YSCALEYUV2PACKED(index, c)
-
-#define REAL_YSCALEYUV2RGB_UV(index, c) \
-    "xor            "#index", "#index"  \n\t"\
-    ASMALIGN(4)\
-    "1:                                 \n\t"\
-    "movq     (%2, "#index"), %%mm2     \n\t" /* uvbuf0[eax]*/\
-    "movq     (%3, "#index"), %%mm3     \n\t" /* uvbuf1[eax]*/\
-    "movq "AV_STRINGIFY(VOF)"(%2, "#index"), %%mm5     \n\t" /* uvbuf0[eax+2048]*/\
-    "movq "AV_STRINGIFY(VOF)"(%3, "#index"), %%mm4     \n\t" /* uvbuf1[eax+2048]*/\
-    "psubw             %%mm3, %%mm2     \n\t" /* uvbuf0[eax] - uvbuf1[eax]*/\
-    "psubw             %%mm4, %%mm5     \n\t" /* uvbuf0[eax+2048] - uvbuf1[eax+2048]*/\
-    "movq "CHR_MMX_FILTER_OFFSET"+8("#c"), %%mm0    \n\t"\
-    "pmulhw            %%mm0, %%mm2     \n\t" /* (uvbuf0[eax] - uvbuf1[eax])uvalpha1>>16*/\
-    "pmulhw            %%mm0, %%mm5     \n\t" /* (uvbuf0[eax+2048] - uvbuf1[eax+2048])uvalpha1>>16*/\
-    "psraw                $4, %%mm3     \n\t" /* uvbuf0[eax] - uvbuf1[eax] >>4*/\
-    "psraw                $4, %%mm4     \n\t" /* uvbuf0[eax+2048] - uvbuf1[eax+2048] >>4*/\
-    "paddw             %%mm2, %%mm3     \n\t" /* uvbuf0[eax]uvalpha1 - uvbuf1[eax](1-uvalpha1)*/\
-    "paddw             %%mm5, %%mm4     \n\t" /* uvbuf0[eax+2048]uvalpha1 - uvbuf1[eax+2048](1-uvalpha1)*/\
-    "psubw  "U_OFFSET"("#c"), %%mm3     \n\t" /* (U-128)8*/\
-    "psubw  "V_OFFSET"("#c"), %%mm4     \n\t" /* (V-128)8*/\
-    "movq              %%mm3, %%mm2     \n\t" /* (U-128)8*/\
-    "movq              %%mm4, %%mm5     \n\t" /* (V-128)8*/\
-    "pmulhw "UG_COEFF"("#c"), %%mm3     \n\t"\
-    "pmulhw "VG_COEFF"("#c"), %%mm4     \n\t"\
-    /* mm2=(U-128)8, mm3=ug, mm4=vg mm5=(V-128)8 */\
-
-#define REAL_YSCALEYUV2RGB_YA(index, c, b1, b2) \
-    "movq  ("#b1", "#index", 2), %%mm0     \n\t" /*buf0[eax]*/\
-    "movq  ("#b2", "#index", 2), %%mm1     \n\t" /*buf1[eax]*/\
-    "movq 8("#b1", "#index", 2), %%mm6     \n\t" /*buf0[eax]*/\
-    "movq 8("#b2", "#index", 2), %%mm7     \n\t" /*buf1[eax]*/\
-    "psubw             %%mm1, %%mm0     \n\t" /* buf0[eax] - buf1[eax]*/\
-    "psubw             %%mm7, %%mm6     \n\t" /* buf0[eax] - buf1[eax]*/\
-    "pmulhw "LUM_MMX_FILTER_OFFSET"+8("#c"), %%mm0  \n\t" /* (buf0[eax] - buf1[eax])yalpha1>>16*/\
-    "pmulhw "LUM_MMX_FILTER_OFFSET"+8("#c"), %%mm6  \n\t" /* (buf0[eax] - buf1[eax])yalpha1>>16*/\
-    "psraw                $4, %%mm1     \n\t" /* buf0[eax] - buf1[eax] >>4*/\
-    "psraw                $4, %%mm7     \n\t" /* buf0[eax] - buf1[eax] >>4*/\
-    "paddw             %%mm0, %%mm1     \n\t" /* buf0[eax]yalpha1 + buf1[eax](1-yalpha1) >>16*/\
-    "paddw             %%mm6, %%mm7     \n\t" /* buf0[eax]yalpha1 + buf1[eax](1-yalpha1) >>16*/\
-
-#define REAL_YSCALEYUV2RGB_COEFF(c) \
-    "pmulhw "UB_COEFF"("#c"), %%mm2     \n\t"\
-    "pmulhw "VR_COEFF"("#c"), %%mm5     \n\t"\
-    "psubw  "Y_OFFSET"("#c"), %%mm1     \n\t" /* 8(Y-16)*/\
-    "psubw  "Y_OFFSET"("#c"), %%mm7     \n\t" /* 8(Y-16)*/\
-    "pmulhw  "Y_COEFF"("#c"), %%mm1     \n\t"\
-    "pmulhw  "Y_COEFF"("#c"), %%mm7     \n\t"\
-    /* mm1= Y1, mm2=ub, mm3=ug, mm4=vg mm5=vr, mm7=Y2 */\
-    "paddw             %%mm3, %%mm4     \n\t"\
-    "movq              %%mm2, %%mm0     \n\t"\
-    "movq              %%mm5, %%mm6     \n\t"\
-    "movq              %%mm4, %%mm3     \n\t"\
-    "punpcklwd         %%mm2, %%mm2     \n\t"\
-    "punpcklwd         %%mm5, %%mm5     \n\t"\
-    "punpcklwd         %%mm4, %%mm4     \n\t"\
-    "paddw             %%mm1, %%mm2     \n\t"\
-    "paddw             %%mm1, %%mm5     \n\t"\
-    "paddw             %%mm1, %%mm4     \n\t"\
-    "punpckhwd         %%mm0, %%mm0     \n\t"\
-    "punpckhwd         %%mm6, %%mm6     \n\t"\
-    "punpckhwd         %%mm3, %%mm3     \n\t"\
-    "paddw             %%mm7, %%mm0     \n\t"\
-    "paddw             %%mm7, %%mm6     \n\t"\
-    "paddw             %%mm7, %%mm3     \n\t"\
-    /* mm0=B1, mm2=B2, mm3=G2, mm4=G1, mm5=R1, mm6=R2 */\
-    "packuswb          %%mm0, %%mm2     \n\t"\
-    "packuswb          %%mm6, %%mm5     \n\t"\
-    "packuswb          %%mm3, %%mm4     \n\t"\
-
-#define YSCALEYUV2RGB_YA(index, c, b1, b2) REAL_YSCALEYUV2RGB_YA(index, c, b1, b2)
-
-#define YSCALEYUV2RGB(index, c) \
-    REAL_YSCALEYUV2RGB_UV(index, c) \
-    REAL_YSCALEYUV2RGB_YA(index, c, %0, %1) \
-    REAL_YSCALEYUV2RGB_COEFF(c)
-
-#define REAL_YSCALEYUV2PACKED1(index, c) \
-    "xor            "#index", "#index"  \n\t"\
-    ASMALIGN(4)\
-    "1:                                 \n\t"\
-    "movq     (%2, "#index"), %%mm3     \n\t" /* uvbuf0[eax]*/\
-    "movq "AV_STRINGIFY(VOF)"(%2, "#index"), %%mm4     \n\t" /* uvbuf0[eax+2048]*/\
-    "psraw                $7, %%mm3     \n\t" \
-    "psraw                $7, %%mm4     \n\t" \
-    "movq  (%0, "#index", 2), %%mm1     \n\t" /*buf0[eax]*/\
-    "movq 8(%0, "#index", 2), %%mm7     \n\t" /*buf0[eax]*/\
-    "psraw                $7, %%mm1     \n\t" \
-    "psraw                $7, %%mm7     \n\t" \
-
-#define YSCALEYUV2PACKED1(index, c)  REAL_YSCALEYUV2PACKED1(index, c)
-
-#define REAL_YSCALEYUV2RGB1(index, c) \
-    "xor            "#index", "#index"  \n\t"\
-    ASMALIGN(4)\
-    "1:                                 \n\t"\
-    "movq     (%2, "#index"), %%mm3     \n\t" /* uvbuf0[eax]*/\
-    "movq "AV_STRINGIFY(VOF)"(%2, "#index"), %%mm4     \n\t" /* uvbuf0[eax+2048]*/\
-    "psraw                $4, %%mm3     \n\t" /* uvbuf0[eax] - uvbuf1[eax] >>4*/\
-    "psraw                $4, %%mm4     \n\t" /* uvbuf0[eax+2048] - uvbuf1[eax+2048] >>4*/\
-    "psubw  "U_OFFSET"("#c"), %%mm3     \n\t" /* (U-128)8*/\
-    "psubw  "V_OFFSET"("#c"), %%mm4     \n\t" /* (V-128)8*/\
-    "movq              %%mm3, %%mm2     \n\t" /* (U-128)8*/\
-    "movq              %%mm4, %%mm5     \n\t" /* (V-128)8*/\
-    "pmulhw "UG_COEFF"("#c"), %%mm3     \n\t"\
-    "pmulhw "VG_COEFF"("#c"), %%mm4     \n\t"\
-    /* mm2=(U-128)8, mm3=ug, mm4=vg mm5=(V-128)8 */\
-    "movq  (%0, "#index", 2), %%mm1     \n\t" /*buf0[eax]*/\
-    "movq 8(%0, "#index", 2), %%mm7     \n\t" /*buf0[eax]*/\
-    "psraw                $4, %%mm1     \n\t" /* buf0[eax] - buf1[eax] >>4*/\
-    "psraw                $4, %%mm7     \n\t" /* buf0[eax] - buf1[eax] >>4*/\
-    "pmulhw "UB_COEFF"("#c"), %%mm2     \n\t"\
-    "pmulhw "VR_COEFF"("#c"), %%mm5     \n\t"\
-    "psubw  "Y_OFFSET"("#c"), %%mm1     \n\t" /* 8(Y-16)*/\
-    "psubw  "Y_OFFSET"("#c"), %%mm7     \n\t" /* 8(Y-16)*/\
-    "pmulhw  "Y_COEFF"("#c"), %%mm1     \n\t"\
-    "pmulhw  "Y_COEFF"("#c"), %%mm7     \n\t"\
-    /* mm1= Y1, mm2=ub, mm3=ug, mm4=vg mm5=vr, mm7=Y2 */\
-    "paddw             %%mm3, %%mm4     \n\t"\
-    "movq              %%mm2, %%mm0     \n\t"\
-    "movq              %%mm5, %%mm6     \n\t"\
-    "movq              %%mm4, %%mm3     \n\t"\
-    "punpcklwd         %%mm2, %%mm2     \n\t"\
-    "punpcklwd         %%mm5, %%mm5     \n\t"\
-    "punpcklwd         %%mm4, %%mm4     \n\t"\
-    "paddw             %%mm1, %%mm2     \n\t"\
-    "paddw             %%mm1, %%mm5     \n\t"\
-    "paddw             %%mm1, %%mm4     \n\t"\
-    "punpckhwd         %%mm0, %%mm0     \n\t"\
-    "punpckhwd         %%mm6, %%mm6     \n\t"\
-    "punpckhwd         %%mm3, %%mm3     \n\t"\
-    "paddw             %%mm7, %%mm0     \n\t"\
-    "paddw             %%mm7, %%mm6     \n\t"\
-    "paddw             %%mm7, %%mm3     \n\t"\
-    /* mm0=B1, mm2=B2, mm3=G2, mm4=G1, mm5=R1, mm6=R2 */\
-    "packuswb          %%mm0, %%mm2     \n\t"\
-    "packuswb          %%mm6, %%mm5     \n\t"\
-    "packuswb          %%mm3, %%mm4     \n\t"\
-
-#define YSCALEYUV2RGB1(index, c)  REAL_YSCALEYUV2RGB1(index, c)
-
-#define REAL_YSCALEYUV2PACKED1b(index, c) \
-    "xor "#index", "#index"             \n\t"\
-    ASMALIGN(4)\
-    "1:                                 \n\t"\
-    "movq     (%2, "#index"), %%mm2     \n\t" /* uvbuf0[eax]*/\
-    "movq     (%3, "#index"), %%mm3     \n\t" /* uvbuf1[eax]*/\
-    "movq "AV_STRINGIFY(VOF)"(%2, "#index"), %%mm5     \n\t" /* uvbuf0[eax+2048]*/\
-    "movq "AV_STRINGIFY(VOF)"(%3, "#index"), %%mm4     \n\t" /* uvbuf1[eax+2048]*/\
-    "paddw             %%mm2, %%mm3     \n\t" /* uvbuf0[eax] + uvbuf1[eax]*/\
-    "paddw             %%mm5, %%mm4     \n\t" /* uvbuf0[eax+2048] + uvbuf1[eax+2048]*/\
-    "psrlw                $8, %%mm3     \n\t" \
-    "psrlw                $8, %%mm4     \n\t" \
-    "movq  (%0, "#index", 2), %%mm1     \n\t" /*buf0[eax]*/\
-    "movq 8(%0, "#index", 2), %%mm7     \n\t" /*buf0[eax]*/\
-    "psraw                $7, %%mm1     \n\t" \
-    "psraw                $7, %%mm7     \n\t"
-#define YSCALEYUV2PACKED1b(index, c)  REAL_YSCALEYUV2PACKED1b(index, c)
-
-// do vertical chrominance interpolation
-#define REAL_YSCALEYUV2RGB1b(index, c) \
-    "xor            "#index", "#index"  \n\t"\
-    ASMALIGN(4)\
-    "1:                                 \n\t"\
-    "movq     (%2, "#index"), %%mm2     \n\t" /* uvbuf0[eax]*/\
-    "movq     (%3, "#index"), %%mm3     \n\t" /* uvbuf1[eax]*/\
-    "movq "AV_STRINGIFY(VOF)"(%2, "#index"), %%mm5     \n\t" /* uvbuf0[eax+2048]*/\
-    "movq "AV_STRINGIFY(VOF)"(%3, "#index"), %%mm4     \n\t" /* uvbuf1[eax+2048]*/\
-    "paddw             %%mm2, %%mm3     \n\t" /* uvbuf0[eax] + uvbuf1[eax]*/\
-    "paddw             %%mm5, %%mm4     \n\t" /* uvbuf0[eax+2048] + uvbuf1[eax+2048]*/\
-    "psrlw                $5, %%mm3     \n\t" /*FIXME might overflow*/\
-    "psrlw                $5, %%mm4     \n\t" /*FIXME might overflow*/\
-    "psubw  "U_OFFSET"("#c"), %%mm3     \n\t" /* (U-128)8*/\
-    "psubw  "V_OFFSET"("#c"), %%mm4     \n\t" /* (V-128)8*/\
-    "movq              %%mm3, %%mm2     \n\t" /* (U-128)8*/\
-    "movq              %%mm4, %%mm5     \n\t" /* (V-128)8*/\
-    "pmulhw "UG_COEFF"("#c"), %%mm3     \n\t"\
-    "pmulhw "VG_COEFF"("#c"), %%mm4     \n\t"\
-    /* mm2=(U-128)8, mm3=ug, mm4=vg mm5=(V-128)8 */\
-    "movq  (%0, "#index", 2), %%mm1     \n\t" /*buf0[eax]*/\
-    "movq 8(%0, "#index", 2), %%mm7     \n\t" /*buf0[eax]*/\
-    "psraw                $4, %%mm1     \n\t" /* buf0[eax] - buf1[eax] >>4*/\
-    "psraw                $4, %%mm7     \n\t" /* buf0[eax] - buf1[eax] >>4*/\
-    "pmulhw "UB_COEFF"("#c"), %%mm2     \n\t"\
-    "pmulhw "VR_COEFF"("#c"), %%mm5     \n\t"\
-    "psubw  "Y_OFFSET"("#c"), %%mm1     \n\t" /* 8(Y-16)*/\
-    "psubw  "Y_OFFSET"("#c"), %%mm7     \n\t" /* 8(Y-16)*/\
-    "pmulhw  "Y_COEFF"("#c"), %%mm1     \n\t"\
-    "pmulhw  "Y_COEFF"("#c"), %%mm7     \n\t"\
-    /* mm1= Y1, mm2=ub, mm3=ug, mm4=vg mm5=vr, mm7=Y2 */\
-    "paddw             %%mm3, %%mm4     \n\t"\
-    "movq              %%mm2, %%mm0     \n\t"\
-    "movq              %%mm5, %%mm6     \n\t"\
-    "movq              %%mm4, %%mm3     \n\t"\
-    "punpcklwd         %%mm2, %%mm2     \n\t"\
-    "punpcklwd         %%mm5, %%mm5     \n\t"\
-    "punpcklwd         %%mm4, %%mm4     \n\t"\
-    "paddw             %%mm1, %%mm2     \n\t"\
-    "paddw             %%mm1, %%mm5     \n\t"\
-    "paddw             %%mm1, %%mm4     \n\t"\
-    "punpckhwd         %%mm0, %%mm0     \n\t"\
-    "punpckhwd         %%mm6, %%mm6     \n\t"\
-    "punpckhwd         %%mm3, %%mm3     \n\t"\
-    "paddw             %%mm7, %%mm0     \n\t"\
-    "paddw             %%mm7, %%mm6     \n\t"\
-    "paddw             %%mm7, %%mm3     \n\t"\
-    /* mm0=B1, mm2=B2, mm3=G2, mm4=G1, mm5=R1, mm6=R2 */\
-    "packuswb          %%mm0, %%mm2     \n\t"\
-    "packuswb          %%mm6, %%mm5     \n\t"\
-    "packuswb          %%mm3, %%mm4     \n\t"\
-
-#define YSCALEYUV2RGB1b(index, c)  REAL_YSCALEYUV2RGB1b(index, c)
-
-#define REAL_YSCALEYUV2RGB1_ALPHA(index) \
-    "movq  (%1, "#index", 2), %%mm7     \n\t" /* abuf0[index  ]     */\
-    "movq 8(%1, "#index", 2), %%mm1     \n\t" /* abuf0[index+4]     */\
-    "psraw                $7, %%mm7     \n\t" /* abuf0[index  ] >>7 */\
-    "psraw                $7, %%mm1     \n\t" /* abuf0[index+4] >>7 */\
-    "packuswb          %%mm1, %%mm7     \n\t"
-#define YSCALEYUV2RGB1_ALPHA(index) REAL_YSCALEYUV2RGB1_ALPHA(index)
-
-#define REAL_WRITEBGR32(dst, dstw, index, b, g, r, a, q0, q2, q3, t) \
-    "movq       "#b", "#q2"     \n\t" /* B */\
-    "movq       "#r", "#t"      \n\t" /* R */\
-    "punpcklbw  "#g", "#b"      \n\t" /* GBGBGBGB 0 */\
-    "punpcklbw  "#a", "#r"      \n\t" /* ARARARAR 0 */\
-    "punpckhbw  "#g", "#q2"     \n\t" /* GBGBGBGB 2 */\
-    "punpckhbw  "#a", "#t"      \n\t" /* ARARARAR 2 */\
-    "movq       "#b", "#q0"     \n\t" /* GBGBGBGB 0 */\
-    "movq      "#q2", "#q3"     \n\t" /* GBGBGBGB 2 */\
-    "punpcklwd  "#r", "#q0"     \n\t" /* ARGBARGB 0 */\
-    "punpckhwd  "#r", "#b"      \n\t" /* ARGBARGB 1 */\
-    "punpcklwd  "#t", "#q2"     \n\t" /* ARGBARGB 2 */\
-    "punpckhwd  "#t", "#q3"     \n\t" /* ARGBARGB 3 */\
-\
-    MOVNTQ(   q0,   (dst, index, 4))\
-    MOVNTQ(    b,  8(dst, index, 4))\
-    MOVNTQ(   q2, 16(dst, index, 4))\
-    MOVNTQ(   q3, 24(dst, index, 4))\
-\
-    "add      $8, "#index"      \n\t"\
-    "cmp "#dstw", "#index"      \n\t"\
-    " jb      1b                \n\t"
-#define WRITEBGR32(dst, dstw, index, b, g, r, a, q0, q2, q3, t)  REAL_WRITEBGR32(dst, dstw, index, b, g, r, a, q0, q2, q3, t)
-
-#define REAL_WRITERGB16(dst, dstw, index) \
-    "pand "MANGLE(bF8)", %%mm2  \n\t" /* B */\
-    "pand "MANGLE(bFC)", %%mm4  \n\t" /* G */\
-    "pand "MANGLE(bF8)", %%mm5  \n\t" /* R */\
-    "psrlq           $3, %%mm2  \n\t"\
-\
-    "movq         %%mm2, %%mm1  \n\t"\
-    "movq         %%mm4, %%mm3  \n\t"\
-\
-    "punpcklbw    %%mm7, %%mm3  \n\t"\
-    "punpcklbw    %%mm5, %%mm2  \n\t"\
-    "punpckhbw    %%mm7, %%mm4  \n\t"\
-    "punpckhbw    %%mm5, %%mm1  \n\t"\
-\
-    "psllq           $3, %%mm3  \n\t"\
-    "psllq           $3, %%mm4  \n\t"\
-\
-    "por          %%mm3, %%mm2  \n\t"\
-    "por          %%mm4, %%mm1  \n\t"\
-\
-    MOVNTQ(%%mm2,  (dst, index, 2))\
-    MOVNTQ(%%mm1, 8(dst, index, 2))\
-\
-    "add             $8, "#index"   \n\t"\
-    "cmp        "#dstw", "#index"   \n\t"\
-    " jb             1b             \n\t"
-#define WRITERGB16(dst, dstw, index)  REAL_WRITERGB16(dst, dstw, index)
-
-#define REAL_WRITERGB15(dst, dstw, index) \
-    "pand "MANGLE(bF8)", %%mm2  \n\t" /* B */\
-    "pand "MANGLE(bF8)", %%mm4  \n\t" /* G */\
-    "pand "MANGLE(bF8)", %%mm5  \n\t" /* R */\
-    "psrlq           $3, %%mm2  \n\t"\
-    "psrlq           $1, %%mm5  \n\t"\
-\
-    "movq         %%mm2, %%mm1  \n\t"\
-    "movq         %%mm4, %%mm3  \n\t"\
-\
-    "punpcklbw    %%mm7, %%mm3  \n\t"\
-    "punpcklbw    %%mm5, %%mm2  \n\t"\
-    "punpckhbw    %%mm7, %%mm4  \n\t"\
-    "punpckhbw    %%mm5, %%mm1  \n\t"\
-\
-    "psllq           $2, %%mm3  \n\t"\
-    "psllq           $2, %%mm4  \n\t"\
-\
-    "por          %%mm3, %%mm2  \n\t"\
-    "por          %%mm4, %%mm1  \n\t"\
-\
-    MOVNTQ(%%mm2,  (dst, index, 2))\
-    MOVNTQ(%%mm1, 8(dst, index, 2))\
-\
-    "add             $8, "#index"   \n\t"\
-    "cmp        "#dstw", "#index"   \n\t"\
-    " jb             1b             \n\t"
-#define WRITERGB15(dst, dstw, index)  REAL_WRITERGB15(dst, dstw, index)
-
-#define WRITEBGR24OLD(dst, dstw, index) \
-    /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */\
-    "movq      %%mm2, %%mm1             \n\t" /* B */\
-    "movq      %%mm5, %%mm6             \n\t" /* R */\
-    "punpcklbw %%mm4, %%mm2             \n\t" /* GBGBGBGB 0 */\
-    "punpcklbw %%mm7, %%mm5             \n\t" /* 0R0R0R0R 0 */\
-    "punpckhbw %%mm4, %%mm1             \n\t" /* GBGBGBGB 2 */\
-    "punpckhbw %%mm7, %%mm6             \n\t" /* 0R0R0R0R 2 */\
-    "movq      %%mm2, %%mm0             \n\t" /* GBGBGBGB 0 */\
-    "movq      %%mm1, %%mm3             \n\t" /* GBGBGBGB 2 */\
-    "punpcklwd %%mm5, %%mm0             \n\t" /* 0RGB0RGB 0 */\
-    "punpckhwd %%mm5, %%mm2             \n\t" /* 0RGB0RGB 1 */\
-    "punpcklwd %%mm6, %%mm1             \n\t" /* 0RGB0RGB 2 */\
-    "punpckhwd %%mm6, %%mm3             \n\t" /* 0RGB0RGB 3 */\
-\
-    "movq      %%mm0, %%mm4             \n\t" /* 0RGB0RGB 0 */\
-    "psrlq        $8, %%mm0             \n\t" /* 00RGB0RG 0 */\
-    "pand "MANGLE(bm00000111)", %%mm4   \n\t" /* 00000RGB 0 */\
-    "pand "MANGLE(bm11111000)", %%mm0   \n\t" /* 00RGB000 0.5 */\
-    "por       %%mm4, %%mm0             \n\t" /* 00RGBRGB 0 */\
-    "movq      %%mm2, %%mm4             \n\t" /* 0RGB0RGB 1 */\
-    "psllq       $48, %%mm2             \n\t" /* GB000000 1 */\
-    "por       %%mm2, %%mm0             \n\t" /* GBRGBRGB 0 */\
-\
-    "movq      %%mm4, %%mm2             \n\t" /* 0RGB0RGB 1 */\
-    "psrld       $16, %%mm4             \n\t" /* 000R000R 1 */\
-    "psrlq       $24, %%mm2             \n\t" /* 0000RGB0 1.5 */\
-    "por       %%mm4, %%mm2             \n\t" /* 000RRGBR 1 */\
-    "pand "MANGLE(bm00001111)", %%mm2   \n\t" /* 0000RGBR 1 */\
-    "movq      %%mm1, %%mm4             \n\t" /* 0RGB0RGB 2 */\
-    "psrlq        $8, %%mm1             \n\t" /* 00RGB0RG 2 */\
-    "pand "MANGLE(bm00000111)", %%mm4   \n\t" /* 00000RGB 2 */\
-    "pand "MANGLE(bm11111000)", %%mm1   \n\t" /* 00RGB000 2.5 */\
-    "por       %%mm4, %%mm1             \n\t" /* 00RGBRGB 2 */\
-    "movq      %%mm1, %%mm4             \n\t" /* 00RGBRGB 2 */\
-    "psllq       $32, %%mm1             \n\t" /* BRGB0000 2 */\
-    "por       %%mm1, %%mm2             \n\t" /* BRGBRGBR 1 */\
-\
-    "psrlq       $32, %%mm4             \n\t" /* 000000RG 2.5 */\
-    "movq      %%mm3, %%mm5             \n\t" /* 0RGB0RGB 3 */\
-    "psrlq        $8, %%mm3             \n\t" /* 00RGB0RG 3 */\
-    "pand "MANGLE(bm00000111)", %%mm5   \n\t" /* 00000RGB 3 */\
-    "pand "MANGLE(bm11111000)", %%mm3   \n\t" /* 00RGB000 3.5 */\
-    "por       %%mm5, %%mm3             \n\t" /* 00RGBRGB 3 */\
-    "psllq       $16, %%mm3             \n\t" /* RGBRGB00 3 */\
-    "por       %%mm4, %%mm3             \n\t" /* RGBRGBRG 2.5 */\
-\
-    MOVNTQ(%%mm0,   (dst))\
-    MOVNTQ(%%mm2,  8(dst))\
-    MOVNTQ(%%mm3, 16(dst))\
-    "add         $24, "#dst"            \n\t"\
-\
-    "add          $8, "#index"          \n\t"\
-    "cmp     "#dstw", "#index"          \n\t"\
-    " jb          1b                    \n\t"
-
-#define WRITEBGR24MMX(dst, dstw, index) \
-    /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */\
-    "movq      %%mm2, %%mm1     \n\t" /* B */\
-    "movq      %%mm5, %%mm6     \n\t" /* R */\
-    "punpcklbw %%mm4, %%mm2     \n\t" /* GBGBGBGB 0 */\
-    "punpcklbw %%mm7, %%mm5     \n\t" /* 0R0R0R0R 0 */\
-    "punpckhbw %%mm4, %%mm1     \n\t" /* GBGBGBGB 2 */\
-    "punpckhbw %%mm7, %%mm6     \n\t" /* 0R0R0R0R 2 */\
-    "movq      %%mm2, %%mm0     \n\t" /* GBGBGBGB 0 */\
-    "movq      %%mm1, %%mm3     \n\t" /* GBGBGBGB 2 */\
-    "punpcklwd %%mm5, %%mm0     \n\t" /* 0RGB0RGB 0 */\
-    "punpckhwd %%mm5, %%mm2     \n\t" /* 0RGB0RGB 1 */\
-    "punpcklwd %%mm6, %%mm1     \n\t" /* 0RGB0RGB 2 */\
-    "punpckhwd %%mm6, %%mm3     \n\t" /* 0RGB0RGB 3 */\
-\
-    "movq      %%mm0, %%mm4     \n\t" /* 0RGB0RGB 0 */\
-    "movq      %%mm2, %%mm6     \n\t" /* 0RGB0RGB 1 */\
-    "movq      %%mm1, %%mm5     \n\t" /* 0RGB0RGB 2 */\
-    "movq      %%mm3, %%mm7     \n\t" /* 0RGB0RGB 3 */\
-\
-    "psllq       $40, %%mm0     \n\t" /* RGB00000 0 */\
-    "psllq       $40, %%mm2     \n\t" /* RGB00000 1 */\
-    "psllq       $40, %%mm1     \n\t" /* RGB00000 2 */\
-    "psllq       $40, %%mm3     \n\t" /* RGB00000 3 */\
-\
-    "punpckhdq %%mm4, %%mm0     \n\t" /* 0RGBRGB0 0 */\
-    "punpckhdq %%mm6, %%mm2     \n\t" /* 0RGBRGB0 1 */\
-    "punpckhdq %%mm5, %%mm1     \n\t" /* 0RGBRGB0 2 */\
-    "punpckhdq %%mm7, %%mm3     \n\t" /* 0RGBRGB0 3 */\
-\
-    "psrlq        $8, %%mm0     \n\t" /* 00RGBRGB 0 */\
-    "movq      %%mm2, %%mm6     \n\t" /* 0RGBRGB0 1 */\
-    "psllq       $40, %%mm2     \n\t" /* GB000000 1 */\
-    "por       %%mm2, %%mm0     \n\t" /* GBRGBRGB 0 */\
-    MOVNTQ(%%mm0, (dst))\
-\
-    "psrlq       $24, %%mm6     \n\t" /* 0000RGBR 1 */\
-    "movq      %%mm1, %%mm5     \n\t" /* 0RGBRGB0 2 */\
-    "psllq       $24, %%mm1     \n\t" /* BRGB0000 2 */\
-    "por       %%mm1, %%mm6     \n\t" /* BRGBRGBR 1 */\
-    MOVNTQ(%%mm6, 8(dst))\
-\
-    "psrlq       $40, %%mm5     \n\t" /* 000000RG 2 */\
-    "psllq        $8, %%mm3     \n\t" /* RGBRGB00 3 */\
-    "por       %%mm3, %%mm5     \n\t" /* RGBRGBRG 2 */\
-    MOVNTQ(%%mm5, 16(dst))\
-\
-    "add         $24, "#dst"    \n\t"\
-\
-    "add          $8, "#index"  \n\t"\
-    "cmp     "#dstw", "#index"  \n\t"\
-    " jb          1b            \n\t"
-
-#define WRITEBGR24MMX2(dst, dstw, index) \
-    /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */\
-    "movq "MANGLE(ff_M24A)", %%mm0 \n\t"\
-    "movq "MANGLE(ff_M24C)", %%mm7 \n\t"\
-    "pshufw $0x50, %%mm2, %%mm1 \n\t" /* B3 B2 B3 B2  B1 B0 B1 B0 */\
-    "pshufw $0x50, %%mm4, %%mm3 \n\t" /* G3 G2 G3 G2  G1 G0 G1 G0 */\
-    "pshufw $0x00, %%mm5, %%mm6 \n\t" /* R1 R0 R1 R0  R1 R0 R1 R0 */\
-\
-    "pand   %%mm0, %%mm1        \n\t" /*    B2        B1       B0 */\
-    "pand   %%mm0, %%mm3        \n\t" /*    G2        G1       G0 */\
-    "pand   %%mm7, %%mm6        \n\t" /*       R1        R0       */\
-\
-    "psllq     $8, %%mm3        \n\t" /* G2        G1       G0    */\
-    "por    %%mm1, %%mm6        \n\t"\
-    "por    %%mm3, %%mm6        \n\t"\
-    MOVNTQ(%%mm6, (dst))\
-\
-    "psrlq     $8, %%mm4        \n\t" /* 00 G7 G6 G5  G4 G3 G2 G1 */\
-    "pshufw $0xA5, %%mm2, %%mm1 \n\t" /* B5 B4 B5 B4  B3 B2 B3 B2 */\
-    "pshufw $0x55, %%mm4, %%mm3 \n\t" /* G4 G3 G4 G3  G4 G3 G4 G3 */\
-    "pshufw $0xA5, %%mm5, %%mm6 \n\t" /* R5 R4 R5 R4  R3 R2 R3 R2 */\
-\
-    "pand "MANGLE(ff_M24B)", %%mm1 \n\t" /* B5       B4        B3    */\
-    "pand   %%mm7, %%mm3        \n\t" /*       G4        G3       */\
-    "pand   %%mm0, %%mm6        \n\t" /*    R4        R3       R2 */\
-\
-    "por    %%mm1, %%mm3        \n\t" /* B5    G4 B4     G3 B3    */\
-    "por    %%mm3, %%mm6        \n\t"\
-    MOVNTQ(%%mm6, 8(dst))\
-\
-    "pshufw $0xFF, %%mm2, %%mm1 \n\t" /* B7 B6 B7 B6  B7 B6 B6 B7 */\
-    "pshufw $0xFA, %%mm4, %%mm3 \n\t" /* 00 G7 00 G7  G6 G5 G6 G5 */\
-    "pshufw $0xFA, %%mm5, %%mm6 \n\t" /* R7 R6 R7 R6  R5 R4 R5 R4 */\
-\
-    "pand   %%mm7, %%mm1        \n\t" /*       B7        B6       */\
-    "pand   %%mm0, %%mm3        \n\t" /*    G7        G6       G5 */\
-    "pand "MANGLE(ff_M24B)", %%mm6 \n\t" /* R7       R6        R5    */\
-\
-    "por    %%mm1, %%mm3        \n\t"\
-    "por    %%mm3, %%mm6        \n\t"\
-    MOVNTQ(%%mm6, 16(dst))\
-\
-    "add      $24, "#dst"       \n\t"\
-\
-    "add       $8, "#index"     \n\t"\
-    "cmp  "#dstw", "#index"     \n\t"\
-    " jb       1b               \n\t"
-
-#if COMPILE_TEMPLATE_MMX2
-#undef WRITEBGR24
-#define WRITEBGR24(dst, dstw, index)  WRITEBGR24MMX2(dst, dstw, index)
-#else
-#undef WRITEBGR24
-#define WRITEBGR24(dst, dstw, index)  WRITEBGR24MMX(dst, dstw, index)
-#endif
-
-#define REAL_WRITEYUY2(dst, dstw, index) \
-    "packuswb  %%mm3, %%mm3     \n\t"\
-    "packuswb  %%mm4, %%mm4     \n\t"\
-    "packuswb  %%mm7, %%mm1     \n\t"\
-    "punpcklbw %%mm4, %%mm3     \n\t"\
-    "movq      %%mm1, %%mm7     \n\t"\
-    "punpcklbw %%mm3, %%mm1     \n\t"\
-    "punpckhbw %%mm3, %%mm7     \n\t"\
-\
-    MOVNTQ(%%mm1, (dst, index, 2))\
-    MOVNTQ(%%mm7, 8(dst, index, 2))\
-\
-    "add          $8, "#index"  \n\t"\
-    "cmp     "#dstw", "#index"  \n\t"\
-    " jb          1b            \n\t"
-#define WRITEYUY2(dst, dstw, index)  REAL_WRITEYUY2(dst, dstw, index)
-
-
-static inline void RENAME(yuv2yuvX)(SwsContext *c, const int16_t *lumFilter, const int16_t **lumSrc, int lumFilterSize,
-                                    const int16_t *chrFilter, const int16_t **chrSrc, int chrFilterSize, const int16_t **alpSrc,
-                                    uint8_t *dest, uint8_t *uDest, uint8_t *vDest, uint8_t *aDest, long dstW, long chrDstW)
+static inline void yuv2yuvX_c(SwsContext *c, const int16_t *lumFilter,
+                              const int16_t **lumSrc, int lumFilterSize,
+                              const int16_t *chrFilter, const int16_t **chrSrc,
+                              int chrFilterSize, const int16_t **alpSrc,
+                              uint8_t *dest, uint8_t *uDest, uint8_t *vDest,
+                              uint8_t *aDest, long dstW, long chrDstW)
 {
-#if COMPILE_TEMPLATE_MMX
-    if(!(c->flags & SWS_BITEXACT)) {
-        if (c->flags & SWS_ACCURATE_RND) {
-            if (uDest) {
-                YSCALEYUV2YV12X_ACCURATE(   "0", CHR_MMX_FILTER_OFFSET, uDest, chrDstW)
-                YSCALEYUV2YV12X_ACCURATE(AV_STRINGIFY(VOF), CHR_MMX_FILTER_OFFSET, vDest, chrDstW)
-            }
-            if (CONFIG_SWSCALE_ALPHA && aDest) {
-                YSCALEYUV2YV12X_ACCURATE(   "0", ALP_MMX_FILTER_OFFSET, aDest, dstW)
-            }
-
-            YSCALEYUV2YV12X_ACCURATE("0", LUM_MMX_FILTER_OFFSET, dest, dstW)
-        } else {
-            if (uDest) {
-                YSCALEYUV2YV12X(   "0", CHR_MMX_FILTER_OFFSET, uDest, chrDstW)
-                YSCALEYUV2YV12X(AV_STRINGIFY(VOF), CHR_MMX_FILTER_OFFSET, vDest, chrDstW)
-            }
-            if (CONFIG_SWSCALE_ALPHA && aDest) {
-                YSCALEYUV2YV12X(   "0", ALP_MMX_FILTER_OFFSET, aDest, dstW)
-            }
-
-            YSCALEYUV2YV12X("0", LUM_MMX_FILTER_OFFSET, dest, dstW)
-        }
-        return;
-    }
-#endif
-#if COMPILE_TEMPLATE_ALTIVEC
-    yuv2yuvX_altivec_real(lumFilter, lumSrc, lumFilterSize,
-                          chrFilter, chrSrc, chrFilterSize,
-                          dest, uDest, vDest, dstW, chrDstW);
-#else //COMPILE_TEMPLATE_ALTIVEC
     yuv2yuvXinC(lumFilter, lumSrc, lumFilterSize,
                 chrFilter, chrSrc, chrFilterSize,
                 alpSrc, dest, uDest, vDest, aDest, dstW, chrDstW);
-#endif //!COMPILE_TEMPLATE_ALTIVEC
 }
 
-static inline void RENAME(yuv2nv12X)(SwsContext *c, const int16_t *lumFilter, const int16_t **lumSrc, int lumFilterSize,
-                                     const int16_t *chrFilter, const int16_t **chrSrc, int chrFilterSize,
-                                     uint8_t *dest, uint8_t *uDest, int dstW, int chrDstW, enum PixelFormat dstFormat)
+static inline void yuv2nv12X_c(SwsContext *c, const int16_t *lumFilter,
+                               const int16_t **lumSrc, int lumFilterSize,
+                               const int16_t *chrFilter, const int16_t **chrSrc,
+                               int chrFilterSize, uint8_t *dest, uint8_t *uDest,
+                               int dstW, int chrDstW, enum PixelFormat dstFormat)
 {
     yuv2nv12XinC(lumFilter, lumSrc, lumFilterSize,
                  chrFilter, chrSrc, chrFilterSize,
                  dest, uDest, dstW, chrDstW, dstFormat);
 }
 
-static inline void RENAME(yuv2yuv1)(SwsContext *c, const int16_t *lumSrc, const int16_t *chrSrc, const int16_t *alpSrc,
-                                    uint8_t *dest, uint8_t *uDest, uint8_t *vDest, uint8_t *aDest, long dstW, long chrDstW)
+static inline void yuv2yuv1_c(SwsContext *c, const int16_t *lumSrc,
+                              const int16_t *chrSrc, const int16_t *alpSrc,
+                              uint8_t *dest, uint8_t *uDest, uint8_t *vDest,
+                              uint8_t *aDest, long dstW, long chrDstW)
 {
     int i;
-#if COMPILE_TEMPLATE_MMX
-    if(!(c->flags & SWS_BITEXACT)) {
-        long p= 4;
-        const uint8_t *src[4]= {alpSrc + dstW, lumSrc + dstW, chrSrc + chrDstW, chrSrc + VOFW + chrDstW};
-        uint8_t *dst[4]= {aDest, dest, uDest, vDest};
-        x86_reg counter[4]= {dstW, dstW, chrDstW, chrDstW};
-
-        if (c->flags & SWS_ACCURATE_RND) {
-            while(p--) {
-                if (dst[p]) {
-                    __asm__ volatile(
-                        YSCALEYUV2YV121_ACCURATE
-                        :: "r" (src[p]), "r" (dst[p] + counter[p]),
-                        "g" (-counter[p])
-                        : "%"REG_a
-                    );
-                }
-            }
-        } else {
-            while(p--) {
-                if (dst[p]) {
-                    __asm__ volatile(
-                        YSCALEYUV2YV121
-                        :: "r" (src[p]), "r" (dst[p] + counter[p]),
-                        "g" (-counter[p])
-                        : "%"REG_a
-                    );
-                }
-            }
-        }
-        return;
-    }
-#endif
     for (i=0; i<dstW; i++) {
         int val= (lumSrc[i]+64)>>7;
 
@@ -1019,183 +85,12 @@ static inline void RENAME(yuv2yuv1)(SwsContext *c, const int16_t *lumSrc, const
 /**
  * vertical scale YV12 to RGB
  */
-static inline void RENAME(yuv2packedX)(SwsContext *c, const int16_t *lumFilter, const int16_t **lumSrc, int lumFilterSize,
-                                       const int16_t *chrFilter, const int16_t **chrSrc, int chrFilterSize,
-                                       const int16_t **alpSrc, uint8_t *dest, long dstW, long dstY)
+static inline void yuv2packedX_c(SwsContext *c, const int16_t *lumFilter,
+                                 const int16_t **lumSrc, int lumFilterSize,
+                                 const int16_t *chrFilter, const int16_t **chrSrc,
+                                 int chrFilterSize, const int16_t **alpSrc,
+                                 uint8_t *dest, long dstW, long dstY)
 {
-#if COMPILE_TEMPLATE_MMX
-    x86_reg dummy=0;
-    if(!(c->flags & SWS_BITEXACT)) {
-        if (c->flags & SWS_ACCURATE_RND) {
-            switch(c->dstFormat) {
-            case PIX_FMT_RGB32:
-                if (CONFIG_SWSCALE_ALPHA && c->alpPixBuf) {
-                    YSCALEYUV2PACKEDX_ACCURATE
-                    YSCALEYUV2RGBX
-                    "movq                      %%mm2, "U_TEMP"(%0)  \n\t"
-                    "movq                      %%mm4, "V_TEMP"(%0)  \n\t"
-                    "movq                      %%mm5, "Y_TEMP"(%0)  \n\t"
-                    YSCALEYUV2PACKEDX_ACCURATE_YA(ALP_MMX_FILTER_OFFSET)
-                    "movq               "Y_TEMP"(%0), %%mm5         \n\t"
-                    "psraw                        $3, %%mm1         \n\t"
-                    "psraw                        $3, %%mm7         \n\t"
-                    "packuswb                  %%mm7, %%mm1         \n\t"
-                    WRITEBGR32(%4, %5, %%REGa, %%mm3, %%mm4, %%mm5, %%mm1, %%mm0, %%mm7, %%mm2, %%mm6)
-
-                    YSCALEYUV2PACKEDX_END
-                } else {
-                    YSCALEYUV2PACKEDX_ACCURATE
-                    YSCALEYUV2RGBX
-                    "pcmpeqd %%mm7, %%mm7 \n\t"
-                    WRITEBGR32(%4, %5, %%REGa, %%mm2, %%mm4, %%mm5, %%mm7, %%mm0, %%mm1, %%mm3, %%mm6)
-
-                    YSCALEYUV2PACKEDX_END
-                }
-                return;
-            case PIX_FMT_BGR24:
-                YSCALEYUV2PACKEDX_ACCURATE
-                YSCALEYUV2RGBX
-                "pxor %%mm7, %%mm7 \n\t"
-                "lea (%%"REG_a", %%"REG_a", 2), %%"REG_c"\n\t" //FIXME optimize
-                "add %4, %%"REG_c"                        \n\t"
-                WRITEBGR24(%%REGc, %5, %%REGa)
-
-
-                :: "r" (&c->redDither),
-                "m" (dummy), "m" (dummy), "m" (dummy),
-                "r" (dest), "m" (dstW)
-                : "%"REG_a, "%"REG_c, "%"REG_d, "%"REG_S
-                );
-                return;
-            case PIX_FMT_RGB555:
-                YSCALEYUV2PACKEDX_ACCURATE
-                YSCALEYUV2RGBX
-                "pxor %%mm7, %%mm7 \n\t"
-                /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */
-#ifdef DITHER1XBPP
-                "paddusb "BLUE_DITHER"(%0), %%mm2\n\t"
-                "paddusb "GREEN_DITHER"(%0), %%mm4\n\t"
-                "paddusb "RED_DITHER"(%0), %%mm5\n\t"
-#endif
-
-                WRITERGB15(%4, %5, %%REGa)
-                YSCALEYUV2PACKEDX_END
-                return;
-            case PIX_FMT_RGB565:
-                YSCALEYUV2PACKEDX_ACCURATE
-                YSCALEYUV2RGBX
-                "pxor %%mm7, %%mm7 \n\t"
-                /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */
-#ifdef DITHER1XBPP
-                "paddusb "BLUE_DITHER"(%0), %%mm2\n\t"
-                "paddusb "GREEN_DITHER"(%0), %%mm4\n\t"
-                "paddusb "RED_DITHER"(%0), %%mm5\n\t"
-#endif
-
-                WRITERGB16(%4, %5, %%REGa)
-                YSCALEYUV2PACKEDX_END
-                return;
-            case PIX_FMT_YUYV422:
-                YSCALEYUV2PACKEDX_ACCURATE
-                /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */
-
-                "psraw $3, %%mm3    \n\t"
-                "psraw $3, %%mm4    \n\t"
-                "psraw $3, %%mm1    \n\t"
-                "psraw $3, %%mm7    \n\t"
-                WRITEYUY2(%4, %5, %%REGa)
-                YSCALEYUV2PACKEDX_END
-                return;
-            }
-        } else {
-            switch(c->dstFormat) {
-            case PIX_FMT_RGB32:
-                if (CONFIG_SWSCALE_ALPHA && c->alpPixBuf) {
-                    YSCALEYUV2PACKEDX
-                    YSCALEYUV2RGBX
-                    YSCALEYUV2PACKEDX_YA(ALP_MMX_FILTER_OFFSET, %%mm0, %%mm3, %%mm6, %%mm1, %%mm7)
-                    "psraw                        $3, %%mm1         \n\t"
-                    "psraw                        $3, %%mm7         \n\t"
-                    "packuswb                  %%mm7, %%mm1         \n\t"
-                    WRITEBGR32(%4, %5, %%REGa, %%mm2, %%mm4, %%mm5, %%mm1, %%mm0, %%mm7, %%mm3, %%mm6)
-                    YSCALEYUV2PACKEDX_END
-                } else {
-                    YSCALEYUV2PACKEDX
-                    YSCALEYUV2RGBX
-                    "pcmpeqd %%mm7, %%mm7 \n\t"
-                    WRITEBGR32(%4, %5, %%REGa, %%mm2, %%mm4, %%mm5, %%mm7, %%mm0, %%mm1, %%mm3, %%mm6)
-                    YSCALEYUV2PACKEDX_END
-                }
-                return;
-            case PIX_FMT_BGR24:
-                YSCALEYUV2PACKEDX
-                YSCALEYUV2RGBX
-                "pxor                    %%mm7, %%mm7       \n\t"
-                "lea (%%"REG_a", %%"REG_a", 2), %%"REG_c"   \n\t" //FIXME optimize
-                "add                        %4, %%"REG_c"   \n\t"
-                WRITEBGR24(%%REGc, %5, %%REGa)
-
-                :: "r" (&c->redDither),
-                "m" (dummy), "m" (dummy), "m" (dummy),
-                "r" (dest),  "m" (dstW)
-                : "%"REG_a, "%"REG_c, "%"REG_d, "%"REG_S
-                );
-                return;
-            case PIX_FMT_RGB555:
-                YSCALEYUV2PACKEDX
-                YSCALEYUV2RGBX
-                "pxor %%mm7, %%mm7 \n\t"
-                /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */
-#ifdef DITHER1XBPP
-                "paddusb "BLUE_DITHER"(%0), %%mm2  \n\t"
-                "paddusb "GREEN_DITHER"(%0), %%mm4  \n\t"
-                "paddusb "RED_DITHER"(%0), %%mm5  \n\t"
-#endif
-
-                WRITERGB15(%4, %5, %%REGa)
-                YSCALEYUV2PACKEDX_END
-                return;
-            case PIX_FMT_RGB565:
-                YSCALEYUV2PACKEDX
-                YSCALEYUV2RGBX
-                "pxor %%mm7, %%mm7 \n\t"
-                /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */
-#ifdef DITHER1XBPP
-                "paddusb "BLUE_DITHER"(%0), %%mm2  \n\t"
-                "paddusb "GREEN_DITHER"(%0), %%mm4  \n\t"
-                "paddusb "RED_DITHER"(%0), %%mm5  \n\t"
-#endif
-
-                WRITERGB16(%4, %5, %%REGa)
-                YSCALEYUV2PACKEDX_END
-                return;
-            case PIX_FMT_YUYV422:
-                YSCALEYUV2PACKEDX
-                /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */
-
-                "psraw $3, %%mm3    \n\t"
-                "psraw $3, %%mm4    \n\t"
-                "psraw $3, %%mm1    \n\t"
-                "psraw $3, %%mm7    \n\t"
-                WRITEYUY2(%4, %5, %%REGa)
-                YSCALEYUV2PACKEDX_END
-                return;
-            }
-        }
-    }
-#endif /* COMPILE_TEMPLATE_MMX */
-#if COMPILE_TEMPLATE_ALTIVEC
-    /* The following list of supported dstFormat values should
-       match what's found in the body of ff_yuv2packedX_altivec() */
-    if (!(c->flags & SWS_BITEXACT) && !c->alpPixBuf &&
-         (c->dstFormat==PIX_FMT_ABGR  || c->dstFormat==PIX_FMT_BGRA  ||
-          c->dstFormat==PIX_FMT_BGR24 || c->dstFormat==PIX_FMT_RGB24 ||
-          c->dstFormat==PIX_FMT_RGBA  || c->dstFormat==PIX_FMT_ARGB))
-            ff_yuv2packedX_altivec(c, lumFilter, lumSrc, lumFilterSize,
-                                   chrFilter, chrSrc, chrFilterSize,
-                                   dest, dstW, dstY);
-    else
-#endif
         yuv2packedXinC(c, lumFilter, lumSrc, lumFilterSize,
                        chrFilter, chrSrc, chrFilterSize,
                        alpSrc, dest, dstW, dstY);
@@ -1204,157 +99,27 @@ static inline void RENAME(yuv2packedX)(SwsContext *c, const int16_t *lumFilter,
 /**
  * vertical bilinear scale YV12 to RGB
  */
-static inline void RENAME(yuv2packed2)(SwsContext *c, const uint16_t *buf0, const uint16_t *buf1, const uint16_t *uvbuf0, const uint16_t *uvbuf1,
-                          const uint16_t *abuf0, const uint16_t *abuf1, uint8_t *dest, int dstW, int yalpha, int uvalpha, int y)
+static inline void yuv2packed2_c(SwsContext *c, const uint16_t *buf0,
+                                 const uint16_t *buf1, const uint16_t *uvbuf0,
+                                 const uint16_t *uvbuf1, const uint16_t *abuf0,
+                                 const uint16_t *abuf1, uint8_t *dest, int dstW,
+                                 int yalpha, int uvalpha, int y)
 {
     int  yalpha1=4095- yalpha;
     int uvalpha1=4095-uvalpha;
     int i;
 
-#if COMPILE_TEMPLATE_MMX
-    if(!(c->flags & SWS_BITEXACT)) {
-        switch(c->dstFormat) {
-        //Note 8280 == DSTW_OFFSET but the preprocessor can't handle that there :(
-        case PIX_FMT_RGB32:
-            if (CONFIG_SWSCALE_ALPHA && c->alpPixBuf) {
-#if ARCH_X86_64
-                __asm__ volatile(
-                    YSCALEYUV2RGB(%%r8, %5)
-                    YSCALEYUV2RGB_YA(%%r8, %5, %6, %7)
-                    "psraw                  $3, %%mm1       \n\t" /* abuf0[eax] - abuf1[eax] >>7*/
-                    "psraw                  $3, %%mm7       \n\t" /* abuf0[eax] - abuf1[eax] >>7*/
-                    "packuswb            %%mm7, %%mm1       \n\t"
-                    WRITEBGR32(%4, 8280(%5), %%r8, %%mm2, %%mm4, %%mm5, %%mm1, %%mm0, %%mm7, %%mm3, %%mm6)
-
-                    :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "r" (dest),
-                    "a" (&c->redDither)
-                    ,"r" (abuf0), "r" (abuf1)
-                    : "%r8"
-                );
-#else
-                *(const uint16_t **)(&c->u_temp)=abuf0;
-                *(const uint16_t **)(&c->v_temp)=abuf1;
-                __asm__ volatile(
-                    "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"
-                    "mov        %4, %%"REG_b"               \n\t"
-                    "push %%"REG_BP"                        \n\t"
-                    YSCALEYUV2RGB(%%REGBP, %5)
-                    "push                   %0              \n\t"
-                    "push                   %1              \n\t"
-                    "mov          "U_TEMP"(%5), %0          \n\t"
-                    "mov          "V_TEMP"(%5), %1          \n\t"
-                    YSCALEYUV2RGB_YA(%%REGBP, %5, %0, %1)
-                    "psraw                  $3, %%mm1       \n\t" /* abuf0[eax] - abuf1[eax] >>7*/
-                    "psraw                  $3, %%mm7       \n\t" /* abuf0[eax] - abuf1[eax] >>7*/
-                    "packuswb            %%mm7, %%mm1       \n\t"
-                    "pop                    %1              \n\t"
-                    "pop                    %0              \n\t"
-                    WRITEBGR32(%%REGb, 8280(%5), %%REGBP, %%mm2, %%mm4, %%mm5, %%mm1, %%mm0, %%mm7, %%mm3, %%mm6)
-                    "pop %%"REG_BP"                         \n\t"
-                    "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"
-
-                    :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),
-                    "a" (&c->redDither)
-                );
-#endif
-            } else {
-                __asm__ volatile(
-                    "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"
-                    "mov        %4, %%"REG_b"               \n\t"
-                    "push %%"REG_BP"                        \n\t"
-                    YSCALEYUV2RGB(%%REGBP, %5)
-                    "pcmpeqd %%mm7, %%mm7                   \n\t"
-                    WRITEBGR32(%%REGb, 8280(%5), %%REGBP, %%mm2, %%mm4, %%mm5, %%mm7, %%mm0, %%mm1, %%mm3, %%mm6)
-                    "pop %%"REG_BP"                         \n\t"
-                    "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"
-
-                    :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),
-                    "a" (&c->redDither)
-                );
-            }
-            return;
-        case PIX_FMT_BGR24:
-            __asm__ volatile(
-                "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"
-                "mov        %4, %%"REG_b"               \n\t"
-                "push %%"REG_BP"                        \n\t"
-                YSCALEYUV2RGB(%%REGBP, %5)
-                "pxor    %%mm7, %%mm7                   \n\t"
-                WRITEBGR24(%%REGb, 8280(%5), %%REGBP)
-                "pop %%"REG_BP"                         \n\t"
-                "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"
-                :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),
-                "a" (&c->redDither)
-            );
-            return;
-        case PIX_FMT_RGB555:
-            __asm__ volatile(
-                "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"
-                "mov        %4, %%"REG_b"               \n\t"
-                "push %%"REG_BP"                        \n\t"
-                YSCALEYUV2RGB(%%REGBP, %5)
-                "pxor    %%mm7, %%mm7                   \n\t"
-                /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */
-#ifdef DITHER1XBPP
-                "paddusb "BLUE_DITHER"(%5), %%mm2      \n\t"
-                "paddusb "GREEN_DITHER"(%5), %%mm4      \n\t"
-                "paddusb "RED_DITHER"(%5), %%mm5      \n\t"
-#endif
-
-                WRITERGB15(%%REGb, 8280(%5), %%REGBP)
-                "pop %%"REG_BP"                         \n\t"
-                "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"
-
-                :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),
-                "a" (&c->redDither)
-            );
-            return;
-        case PIX_FMT_RGB565:
-            __asm__ volatile(
-                "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"
-                "mov        %4, %%"REG_b"               \n\t"
-                "push %%"REG_BP"                        \n\t"
-                YSCALEYUV2RGB(%%REGBP, %5)
-                "pxor    %%mm7, %%mm7                   \n\t"
-                /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */
-#ifdef DITHER1XBPP
-                "paddusb "BLUE_DITHER"(%5), %%mm2      \n\t"
-                "paddusb "GREEN_DITHER"(%5), %%mm4      \n\t"
-                "paddusb "RED_DITHER"(%5), %%mm5      \n\t"
-#endif
-
-                WRITERGB16(%%REGb, 8280(%5), %%REGBP)
-                "pop %%"REG_BP"                         \n\t"
-                "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"
-                :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),
-                "a" (&c->redDither)
-            );
-            return;
-        case PIX_FMT_YUYV422:
-            __asm__ volatile(
-                "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"
-                "mov %4, %%"REG_b"                        \n\t"
-                "push %%"REG_BP"                        \n\t"
-                YSCALEYUV2PACKED(%%REGBP, %5)
-                WRITEYUY2(%%REGb, 8280(%5), %%REGBP)
-                "pop %%"REG_BP"                         \n\t"
-                "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"
-                :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),
-                "a" (&c->redDither)
-            );
-            return;
-        default: break;
-        }
-    }
-#endif //COMPILE_TEMPLATE_MMX
     YSCALE_YUV_2_ANYRGB_C(YSCALE_YUV_2_RGB2_C, YSCALE_YUV_2_PACKED2_C(void,0), YSCALE_YUV_2_GRAY16_2_C, YSCALE_YUV_2_MONO2_C)
 }
 
 /**
  * YV12 to RGB without scaling or interpolating
  */
-static inline void RENAME(yuv2packed1)(SwsContext *c, const uint16_t *buf0, const uint16_t *uvbuf0, const uint16_t *uvbuf1,
-                          const uint16_t *abuf0, uint8_t *dest, int dstW, int uvalpha, enum PixelFormat dstFormat, int flags, int y)
+static inline void yuv2packed1_c(SwsContext *c, const uint16_t *buf0,
+                                 const uint16_t *uvbuf0, const uint16_t *uvbuf1,
+                                 const uint16_t *abuf0, uint8_t *dest, int dstW,
+                                 int uvalpha, enum PixelFormat dstFormat,
+                                 int flags, int y)
 {
     const int yalpha1=0;
     int i;
@@ -1367,223 +132,6 @@ static inline void RENAME(yuv2packed1)(SwsContext *c, const uint16_t *buf0, cons
         return;
     }
 
-#if COMPILE_TEMPLATE_MMX
-    if(!(flags & SWS_BITEXACT)) {
-        if (uvalpha < 2048) { // note this is not correct (shifts chrominance by 0.5 pixels) but it is a bit faster
-            switch(dstFormat) {
-            case PIX_FMT_RGB32:
-                if (CONFIG_SWSCALE_ALPHA && c->alpPixBuf) {
-                    __asm__ volatile(
-                        "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"
-                        "mov        %4, %%"REG_b"               \n\t"
-                        "push %%"REG_BP"                        \n\t"
-                        YSCALEYUV2RGB1(%%REGBP, %5)
-                        YSCALEYUV2RGB1_ALPHA(%%REGBP)
-                        WRITEBGR32(%%REGb, 8280(%5), %%REGBP, %%mm2, %%mm4, %%mm5, %%mm7, %%mm0, %%mm1, %%mm3, %%mm6)
-                        "pop %%"REG_BP"                         \n\t"
-                        "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"
-
-                        :: "c" (buf0), "d" (abuf0), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),
-                        "a" (&c->redDither)
-                    );
-                } else {
-                    __asm__ volatile(
-                        "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"
-                        "mov        %4, %%"REG_b"               \n\t"
-                        "push %%"REG_BP"                        \n\t"
-                        YSCALEYUV2RGB1(%%REGBP, %5)
-                        "pcmpeqd %%mm7, %%mm7                   \n\t"
-                        WRITEBGR32(%%REGb, 8280(%5), %%REGBP, %%mm2, %%mm4, %%mm5, %%mm7, %%mm0, %%mm1, %%mm3, %%mm6)
-                        "pop %%"REG_BP"                         \n\t"
-                        "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"
-
-                        :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),
-                        "a" (&c->redDither)
-                    );
-                }
-                return;
-            case PIX_FMT_BGR24:
-                __asm__ volatile(
-                    "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"
-                    "mov        %4, %%"REG_b"               \n\t"
-                    "push %%"REG_BP"                        \n\t"
-                    YSCALEYUV2RGB1(%%REGBP, %5)
-                    "pxor    %%mm7, %%mm7                   \n\t"
-                    WRITEBGR24(%%REGb, 8280(%5), %%REGBP)
-                    "pop %%"REG_BP"                         \n\t"
-                    "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"
-
-                    :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),
-                    "a" (&c->redDither)
-                );
-                return;
-            case PIX_FMT_RGB555:
-                __asm__ volatile(
-                    "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"
-                    "mov        %4, %%"REG_b"               \n\t"
-                    "push %%"REG_BP"                        \n\t"
-                    YSCALEYUV2RGB1(%%REGBP, %5)
-                    "pxor    %%mm7, %%mm7                   \n\t"
-                    /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */
-#ifdef DITHER1XBPP
-                    "paddusb "BLUE_DITHER"(%5), %%mm2      \n\t"
-                    "paddusb "GREEN_DITHER"(%5), %%mm4      \n\t"
-                    "paddusb "RED_DITHER"(%5), %%mm5      \n\t"
-#endif
-                    WRITERGB15(%%REGb, 8280(%5), %%REGBP)
-                    "pop %%"REG_BP"                         \n\t"
-                    "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"
-
-                    :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),
-                    "a" (&c->redDither)
-                );
-                return;
-            case PIX_FMT_RGB565:
-                __asm__ volatile(
-                    "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"
-                    "mov        %4, %%"REG_b"               \n\t"
-                    "push %%"REG_BP"                        \n\t"
-                    YSCALEYUV2RGB1(%%REGBP, %5)
-                    "pxor    %%mm7, %%mm7                   \n\t"
-                    /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */
-#ifdef DITHER1XBPP
-                    "paddusb "BLUE_DITHER"(%5), %%mm2      \n\t"
-                    "paddusb "GREEN_DITHER"(%5), %%mm4      \n\t"
-                    "paddusb "RED_DITHER"(%5), %%mm5      \n\t"
-#endif
-
-                    WRITERGB16(%%REGb, 8280(%5), %%REGBP)
-                    "pop %%"REG_BP"                         \n\t"
-                    "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"
-
-                    :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),
-                    "a" (&c->redDither)
-                );
-                return;
-            case PIX_FMT_YUYV422:
-                __asm__ volatile(
-                    "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"
-                    "mov        %4, %%"REG_b"               \n\t"
-                    "push %%"REG_BP"                        \n\t"
-                    YSCALEYUV2PACKED1(%%REGBP, %5)
-                    WRITEYUY2(%%REGb, 8280(%5), %%REGBP)
-                    "pop %%"REG_BP"                         \n\t"
-                    "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"
-
-                    :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),
-                    "a" (&c->redDither)
-                );
-                return;
-            }
-        } else {
-            switch(dstFormat) {
-            case PIX_FMT_RGB32:
-                if (CONFIG_SWSCALE_ALPHA && c->alpPixBuf) {
-                    __asm__ volatile(
-                        "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"
-                        "mov        %4, %%"REG_b"               \n\t"
-                        "push %%"REG_BP"                        \n\t"
-                        YSCALEYUV2RGB1b(%%REGBP, %5)
-                        YSCALEYUV2RGB1_ALPHA(%%REGBP)
-                        WRITEBGR32(%%REGb, 8280(%5), %%REGBP, %%mm2, %%mm4, %%mm5, %%mm7, %%mm0, %%mm1, %%mm3, %%mm6)
-                        "pop %%"REG_BP"                         \n\t"
-                        "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"
-
-                        :: "c" (buf0), "d" (abuf0), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),
-                        "a" (&c->redDither)
-                    );
-                } else {
-                    __asm__ volatile(
-                        "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"
-                        "mov        %4, %%"REG_b"               \n\t"
-                        "push %%"REG_BP"                        \n\t"
-                        YSCALEYUV2RGB1b(%%REGBP, %5)
-                        "pcmpeqd %%mm7, %%mm7                   \n\t"
-                        WRITEBGR32(%%REGb, 8280(%5), %%REGBP, %%mm2, %%mm4, %%mm5, %%mm7, %%mm0, %%mm1, %%mm3, %%mm6)
-                        "pop %%"REG_BP"                         \n\t"
-                        "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"
-
-                        :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),
-                        "a" (&c->redDither)
-                    );
-                }
-                return;
-            case PIX_FMT_BGR24:
-                __asm__ volatile(
-                    "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"
-                    "mov        %4, %%"REG_b"               \n\t"
-                    "push %%"REG_BP"                        \n\t"
-                    YSCALEYUV2RGB1b(%%REGBP, %5)
-                    "pxor    %%mm7, %%mm7                   \n\t"
-                    WRITEBGR24(%%REGb, 8280(%5), %%REGBP)
-                    "pop %%"REG_BP"                         \n\t"
-                    "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"
-
-                    :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),
-                    "a" (&c->redDither)
-                );
-                return;
-            case PIX_FMT_RGB555:
-                __asm__ volatile(
-                    "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"
-                    "mov        %4, %%"REG_b"               \n\t"
-                    "push %%"REG_BP"                        \n\t"
-                    YSCALEYUV2RGB1b(%%REGBP, %5)
-                    "pxor    %%mm7, %%mm7                   \n\t"
-                    /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */
-#ifdef DITHER1XBPP
-                    "paddusb "BLUE_DITHER"(%5), %%mm2      \n\t"
-                    "paddusb "GREEN_DITHER"(%5), %%mm4      \n\t"
-                    "paddusb "RED_DITHER"(%5), %%mm5      \n\t"
-#endif
-                    WRITERGB15(%%REGb, 8280(%5), %%REGBP)
-                    "pop %%"REG_BP"                         \n\t"
-                    "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"
-
-                    :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),
-                    "a" (&c->redDither)
-                );
-                return;
-            case PIX_FMT_RGB565:
-                __asm__ volatile(
-                    "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"
-                    "mov        %4, %%"REG_b"               \n\t"
-                    "push %%"REG_BP"                        \n\t"
-                    YSCALEYUV2RGB1b(%%REGBP, %5)
-                    "pxor    %%mm7, %%mm7                   \n\t"
-                    /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */
-#ifdef DITHER1XBPP
-                    "paddusb "BLUE_DITHER"(%5), %%mm2      \n\t"
-                    "paddusb "GREEN_DITHER"(%5), %%mm4      \n\t"
-                    "paddusb "RED_DITHER"(%5), %%mm5      \n\t"
-#endif
-
-                    WRITERGB16(%%REGb, 8280(%5), %%REGBP)
-                    "pop %%"REG_BP"                         \n\t"
-                    "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"
-
-                    :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),
-                    "a" (&c->redDither)
-                );
-                return;
-            case PIX_FMT_YUYV422:
-                __asm__ volatile(
-                    "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"
-                    "mov        %4, %%"REG_b"               \n\t"
-                    "push %%"REG_BP"                        \n\t"
-                    YSCALEYUV2PACKED1b(%%REGBP, %5)
-                    WRITEYUY2(%%REGb, 8280(%5), %%REGBP)
-                    "pop %%"REG_BP"                         \n\t"
-                    "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"
-
-                    :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),
-                    "a" (&c->redDither)
-                );
-                return;
-            }
-        }
-    }
-#endif /* COMPILE_TEMPLATE_MMX */
     if (uvalpha < 2048) {
         YSCALE_YUV_2_ANYRGB_C(YSCALE_YUV_2_RGB1_C, YSCALE_YUV_2_PACKED1_C(void,0), YSCALE_YUV_2_GRAY16_1_C, YSCALE_YUV_2_MONO2_C)
     } else {
@@ -1593,356 +141,93 @@ static inline void RENAME(yuv2packed1)(SwsContext *c, const uint16_t *buf0, cons
 
 //FIXME yuy2* can read up to 7 samples too much
 
-static inline void RENAME(yuy2ToY)(uint8_t *dst, const uint8_t *src, long width, uint32_t *unused)
+static inline void yuy2ToY_c(uint8_t *dst, const uint8_t *src, long width,
+                             uint32_t *unused)
 {
-#if COMPILE_TEMPLATE_MMX
-    __asm__ volatile(
-        "movq "MANGLE(bm01010101)", %%mm2           \n\t"
-        "mov                    %0, %%"REG_a"       \n\t"
-        "1:                                         \n\t"
-        "movq    (%1, %%"REG_a",2), %%mm0           \n\t"
-        "movq   8(%1, %%"REG_a",2), %%mm1           \n\t"
-        "pand                %%mm2, %%mm0           \n\t"
-        "pand                %%mm2, %%mm1           \n\t"
-        "packuswb            %%mm1, %%mm0           \n\t"
-        "movq                %%mm0, (%2, %%"REG_a") \n\t"
-        "add                    $8, %%"REG_a"       \n\t"
-        " js                    1b                  \n\t"
-        : : "g" ((x86_reg)-width), "r" (src+width*2), "r" (dst+width)
-        : "%"REG_a
-    );
-#else
     int i;
     for (i=0; i<width; i++)
         dst[i]= src[2*i];
-#endif
 }
 
-static inline void RENAME(yuy2ToUV)(uint8_t *dstU, uint8_t *dstV, const uint8_t *src1, const uint8_t *src2, long width, uint32_t *unused)
+static inline void yuy2ToUV_c(uint8_t *dstU, uint8_t *dstV, const uint8_t *src1,
+                              const uint8_t *src2, long width, uint32_t *unused)
 {
-#if COMPILE_TEMPLATE_MMX
-    __asm__ volatile(
-        "movq "MANGLE(bm01010101)", %%mm4           \n\t"
-        "mov                    %0, %%"REG_a"       \n\t"
-        "1:                                         \n\t"
-        "movq    (%1, %%"REG_a",4), %%mm0           \n\t"
-        "movq   8(%1, %%"REG_a",4), %%mm1           \n\t"
-        "psrlw                  $8, %%mm0           \n\t"
-        "psrlw                  $8, %%mm1           \n\t"
-        "packuswb            %%mm1, %%mm0           \n\t"
-        "movq                %%mm0, %%mm1           \n\t"
-        "psrlw                  $8, %%mm0           \n\t"
-        "pand                %%mm4, %%mm1           \n\t"
-        "packuswb            %%mm0, %%mm0           \n\t"
-        "packuswb            %%mm1, %%mm1           \n\t"
-        "movd                %%mm0, (%3, %%"REG_a") \n\t"
-        "movd                %%mm1, (%2, %%"REG_a") \n\t"
-        "add                    $4, %%"REG_a"       \n\t"
-        " js                    1b                  \n\t"
-        : : "g" ((x86_reg)-width), "r" (src1+width*4), "r" (dstU+width), "r" (dstV+width)
-        : "%"REG_a
-    );
-#else
     int i;
     for (i=0; i<width; i++) {
         dstU[i]= src1[4*i + 1];
         dstV[i]= src1[4*i + 3];
     }
-#endif
     assert(src1 == src2);
 }
 
-static inline void RENAME(LEToUV)(uint8_t *dstU, uint8_t *dstV, const uint8_t *src1, const uint8_t *src2, long width, uint32_t *unused)
+static inline void LEToUV_c(uint8_t *dstU, uint8_t *dstV, const uint8_t *src1,
+                            const uint8_t *src2, long width, uint32_t *unused)
 {
-#if COMPILE_TEMPLATE_MMX
-    __asm__ volatile(
-        "mov                    %0, %%"REG_a"       \n\t"
-        "1:                                         \n\t"
-        "movq    (%1, %%"REG_a",2), %%mm0           \n\t"
-        "movq   8(%1, %%"REG_a",2), %%mm1           \n\t"
-        "movq    (%2, %%"REG_a",2), %%mm2           \n\t"
-        "movq   8(%2, %%"REG_a",2), %%mm3           \n\t"
-        "psrlw                  $8, %%mm0           \n\t"
-        "psrlw                  $8, %%mm1           \n\t"
-        "psrlw                  $8, %%mm2           \n\t"
-        "psrlw                  $8, %%mm3           \n\t"
-        "packuswb            %%mm1, %%mm0           \n\t"
-        "packuswb            %%mm3, %%mm2           \n\t"
-        "movq                %%mm0, (%3, %%"REG_a") \n\t"
-        "movq                %%mm2, (%4, %%"REG_a") \n\t"
-        "add                    $8, %%"REG_a"       \n\t"
-        " js                    1b                  \n\t"
-        : : "g" ((x86_reg)-width), "r" (src1+width*2), "r" (src2+width*2), "r" (dstU+width), "r" (dstV+width)
-        : "%"REG_a
-    );
-#else
     int i;
     for (i=0; i<width; i++) {
         dstU[i]= src1[2*i + 1];
         dstV[i]= src2[2*i + 1];
     }
-#endif
 }
 
 /* This is almost identical to the previous, end exists only because
  * yuy2ToY/UV)(dst, src+1, ...) would have 100% unaligned accesses. */
-static inline void RENAME(uyvyToY)(uint8_t *dst, const uint8_t *src, long width, uint32_t *unused)
+static inline void uyvyToY_c(uint8_t *dst, const uint8_t *src, long width,
+                             uint32_t *unused)
 {
-#if COMPILE_TEMPLATE_MMX
-    __asm__ volatile(
-        "mov                  %0, %%"REG_a"         \n\t"
-        "1:                                         \n\t"
-        "movq  (%1, %%"REG_a",2), %%mm0             \n\t"
-        "movq 8(%1, %%"REG_a",2), %%mm1             \n\t"
-        "psrlw                $8, %%mm0             \n\t"
-        "psrlw                $8, %%mm1             \n\t"
-        "packuswb          %%mm1, %%mm0             \n\t"
-        "movq              %%mm0, (%2, %%"REG_a")   \n\t"
-        "add                  $8, %%"REG_a"         \n\t"
-        " js                  1b                    \n\t"
-        : : "g" ((x86_reg)-width), "r" (src+width*2), "r" (dst+width)
-        : "%"REG_a
-    );
-#else
     int i;
     for (i=0; i<width; i++)
         dst[i]= src[2*i+1];
-#endif
 }
 
-static inline void RENAME(uyvyToUV)(uint8_t *dstU, uint8_t *dstV, const uint8_t *src1, const uint8_t *src2, long width, uint32_t *unused)
+static inline void uyvyToUV_c(uint8_t *dstU, uint8_t *dstV, const uint8_t *src1,
+                              const uint8_t *src2, long width, uint32_t *unused)
 {
-#if COMPILE_TEMPLATE_MMX
-    __asm__ volatile(
-        "movq "MANGLE(bm01010101)", %%mm4           \n\t"
-        "mov                    %0, %%"REG_a"       \n\t"
-        "1:                                         \n\t"
-        "movq    (%1, %%"REG_a",4), %%mm0           \n\t"
-        "movq   8(%1, %%"REG_a",4), %%mm1           \n\t"
-        "pand                %%mm4, %%mm0           \n\t"
-        "pand                %%mm4, %%mm1           \n\t"
-        "packuswb            %%mm1, %%mm0           \n\t"
-        "movq                %%mm0, %%mm1           \n\t"
-        "psrlw                  $8, %%mm0           \n\t"
-        "pand                %%mm4, %%mm1           \n\t"
-        "packuswb            %%mm0, %%mm0           \n\t"
-        "packuswb            %%mm1, %%mm1           \n\t"
-        "movd                %%mm0, (%3, %%"REG_a") \n\t"
-        "movd                %%mm1, (%2, %%"REG_a") \n\t"
-        "add                    $4, %%"REG_a"       \n\t"
-        " js                    1b                  \n\t"
-        : : "g" ((x86_reg)-width), "r" (src1+width*4), "r" (dstU+width), "r" (dstV+width)
-        : "%"REG_a
-    );
-#else
     int i;
     for (i=0; i<width; i++) {
         dstU[i]= src1[4*i + 0];
         dstV[i]= src1[4*i + 2];
     }
-#endif
     assert(src1 == src2);
 }
 
-static inline void RENAME(BEToUV)(uint8_t *dstU, uint8_t *dstV, const uint8_t *src1, const uint8_t *src2, long width, uint32_t *unused)
+static inline void BEToUV_c(uint8_t *dstU, uint8_t *dstV, const uint8_t *src1,
+                            const uint8_t *src2, long width, uint32_t *unused)
 {
-#if COMPILE_TEMPLATE_MMX
-    __asm__ volatile(
-        "movq "MANGLE(bm01010101)", %%mm4           \n\t"
-        "mov                    %0, %%"REG_a"       \n\t"
-        "1:                                         \n\t"
-        "movq    (%1, %%"REG_a",2), %%mm0           \n\t"
-        "movq   8(%1, %%"REG_a",2), %%mm1           \n\t"
-        "movq    (%2, %%"REG_a",2), %%mm2           \n\t"
-        "movq   8(%2, %%"REG_a",2), %%mm3           \n\t"
-        "pand                %%mm4, %%mm0           \n\t"
-        "pand                %%mm4, %%mm1           \n\t"
-        "pand                %%mm4, %%mm2           \n\t"
-        "pand                %%mm4, %%mm3           \n\t"
-        "packuswb            %%mm1, %%mm0           \n\t"
-        "packuswb            %%mm3, %%mm2           \n\t"
-        "movq                %%mm0, (%3, %%"REG_a") \n\t"
-        "movq                %%mm2, (%4, %%"REG_a") \n\t"
-        "add                    $8, %%"REG_a"       \n\t"
-        " js                    1b                  \n\t"
-        : : "g" ((x86_reg)-width), "r" (src1+width*2), "r" (src2+width*2), "r" (dstU+width), "r" (dstV+width)
-        : "%"REG_a
-    );
-#else
     int i;
     for (i=0; i<width; i++) {
         dstU[i]= src1[2*i];
         dstV[i]= src2[2*i];
     }
-#endif
 }
 
-static inline void RENAME(nvXXtoUV)(uint8_t *dst1, uint8_t *dst2,
-                                    const uint8_t *src, long width)
+static inline void nvXXtoUV_c(uint8_t *dst1, uint8_t *dst2,
+                              const uint8_t *src, long width)
 {
-#if COMPILE_TEMPLATE_MMX
-    __asm__ volatile(
-        "movq "MANGLE(bm01010101)", %%mm4           \n\t"
-        "mov                    %0, %%"REG_a"       \n\t"
-        "1:                                         \n\t"
-        "movq    (%1, %%"REG_a",2), %%mm0           \n\t"
-        "movq   8(%1, %%"REG_a",2), %%mm1           \n\t"
-        "movq                %%mm0, %%mm2           \n\t"
-        "movq                %%mm1, %%mm3           \n\t"
-        "pand                %%mm4, %%mm0           \n\t"
-        "pand                %%mm4, %%mm1           \n\t"
-        "psrlw                  $8, %%mm2           \n\t"
-        "psrlw                  $8, %%mm3           \n\t"
-        "packuswb            %%mm1, %%mm0           \n\t"
-        "packuswb            %%mm3, %%mm2           \n\t"
-        "movq                %%mm0, (%2, %%"REG_a") \n\t"
-        "movq                %%mm2, (%3, %%"REG_a") \n\t"
-        "add                    $8, %%"REG_a"       \n\t"
-        " js                    1b                  \n\t"
-        : : "g" ((x86_reg)-width), "r" (src+width*2), "r" (dst1+width), "r" (dst2+width)
-        : "%"REG_a
-    );
-#else
     int i;
     for (i = 0; i < width; i++) {
         dst1[i] = src[2*i+0];
         dst2[i] = src[2*i+1];
     }
-#endif
-}
-
-static inline void RENAME(nv12ToUV)(uint8_t *dstU, uint8_t *dstV,
-                                    const uint8_t *src1, const uint8_t *src2,
-                                    long width, uint32_t *unused)
-{
-    RENAME(nvXXtoUV)(dstU, dstV, src1, width);
 }
 
-static inline void RENAME(nv21ToUV)(uint8_t *dstU, uint8_t *dstV,
-                                    const uint8_t *src1, const uint8_t *src2,
-                                    long width, uint32_t *unused)
+static inline void nv12ToUV_c(uint8_t *dstU, uint8_t *dstV,
+                              const uint8_t *src1, const uint8_t *src2,
+                              long width, uint32_t *unused)
 {
-    RENAME(nvXXtoUV)(dstV, dstU, src1, width);
-}
-
-#if COMPILE_TEMPLATE_MMX
-static inline void RENAME(bgr24ToY_mmx)(uint8_t *dst, const uint8_t *src, long width, enum PixelFormat srcFormat)
-{
-
-    if(srcFormat == PIX_FMT_BGR24) {
-        __asm__ volatile(
-            "movq  "MANGLE(ff_bgr24toY1Coeff)", %%mm5       \n\t"
-            "movq  "MANGLE(ff_bgr24toY2Coeff)", %%mm6       \n\t"
-            :
-        );
-    } else {
-        __asm__ volatile(
-            "movq  "MANGLE(ff_rgb24toY1Coeff)", %%mm5       \n\t"
-            "movq  "MANGLE(ff_rgb24toY2Coeff)", %%mm6       \n\t"
-            :
-        );
-    }
-
-    __asm__ volatile(
-        "movq  "MANGLE(ff_bgr24toYOffset)", %%mm4   \n\t"
-        "mov                        %2, %%"REG_a"   \n\t"
-        "pxor                    %%mm7, %%mm7       \n\t"
-        "1:                                         \n\t"
-        PREFETCH"               64(%0)              \n\t"
-        "movd                     (%0), %%mm0       \n\t"
-        "movd                    2(%0), %%mm1       \n\t"
-        "movd                    6(%0), %%mm2       \n\t"
-        "movd                    8(%0), %%mm3       \n\t"
-        "add                       $12, %0          \n\t"
-        "punpcklbw               %%mm7, %%mm0       \n\t"
-        "punpcklbw               %%mm7, %%mm1       \n\t"
-        "punpcklbw               %%mm7, %%mm2       \n\t"
-        "punpcklbw               %%mm7, %%mm3       \n\t"
-        "pmaddwd                 %%mm5, %%mm0       \n\t"
-        "pmaddwd                 %%mm6, %%mm1       \n\t"
-        "pmaddwd                 %%mm5, %%mm2       \n\t"
-        "pmaddwd                 %%mm6, %%mm3       \n\t"
-        "paddd                   %%mm1, %%mm0       \n\t"
-        "paddd                   %%mm3, %%mm2       \n\t"
-        "paddd                   %%mm4, %%mm0       \n\t"
-        "paddd                   %%mm4, %%mm2       \n\t"
-        "psrad                     $15, %%mm0       \n\t"
-        "psrad                     $15, %%mm2       \n\t"
-        "packssdw                %%mm2, %%mm0       \n\t"
-        "packuswb                %%mm0, %%mm0       \n\t"
-        "movd                %%mm0, (%1, %%"REG_a") \n\t"
-        "add                        $4, %%"REG_a"   \n\t"
-        " js                        1b              \n\t"
-    : "+r" (src)
-    : "r" (dst+width), "g" ((x86_reg)-width)
-    : "%"REG_a
-    );
+    nvXXtoUV_c(dstU, dstV, src1, width);
 }
 
-static inline void RENAME(bgr24ToUV_mmx)(uint8_t *dstU, uint8_t *dstV, const uint8_t *src, long width, enum PixelFormat srcFormat)
+static inline void nv21ToUV_c(uint8_t *dstU, uint8_t *dstV,
+                              const uint8_t *src1, const uint8_t *src2,
+                              long width, uint32_t *unused)
 {
-    __asm__ volatile(
-        "movq                    24+%4, %%mm6       \n\t"
-        "mov                        %3, %%"REG_a"   \n\t"
-        "pxor                    %%mm7, %%mm7       \n\t"
-        "1:                                         \n\t"
-        PREFETCH"               64(%0)              \n\t"
-        "movd                     (%0), %%mm0       \n\t"
-        "movd                    2(%0), %%mm1       \n\t"
-        "punpcklbw               %%mm7, %%mm0       \n\t"
-        "punpcklbw               %%mm7, %%mm1       \n\t"
-        "movq                    %%mm0, %%mm2       \n\t"
-        "movq                    %%mm1, %%mm3       \n\t"
-        "pmaddwd                    %4, %%mm0       \n\t"
-        "pmaddwd                  8+%4, %%mm1       \n\t"
-        "pmaddwd                 16+%4, %%mm2       \n\t"
-        "pmaddwd                 %%mm6, %%mm3       \n\t"
-        "paddd                   %%mm1, %%mm0       \n\t"
-        "paddd                   %%mm3, %%mm2       \n\t"
-
-        "movd                    6(%0), %%mm1       \n\t"
-        "movd                    8(%0), %%mm3       \n\t"
-        "add                       $12, %0          \n\t"
-        "punpcklbw               %%mm7, %%mm1       \n\t"
-        "punpcklbw               %%mm7, %%mm3       \n\t"
-        "movq                    %%mm1, %%mm4       \n\t"
-        "movq                    %%mm3, %%mm5       \n\t"
-        "pmaddwd                    %4, %%mm1       \n\t"
-        "pmaddwd                  8+%4, %%mm3       \n\t"
-        "pmaddwd                 16+%4, %%mm4       \n\t"
-        "pmaddwd                 %%mm6, %%mm5       \n\t"
-        "paddd                   %%mm3, %%mm1       \n\t"
-        "paddd                   %%mm5, %%mm4       \n\t"
-
-        "movq "MANGLE(ff_bgr24toUVOffset)", %%mm3       \n\t"
-        "paddd                   %%mm3, %%mm0       \n\t"
-        "paddd                   %%mm3, %%mm2       \n\t"
-        "paddd                   %%mm3, %%mm1       \n\t"
-        "paddd                   %%mm3, %%mm4       \n\t"
-        "psrad                     $15, %%mm0       \n\t"
-        "psrad                     $15, %%mm2       \n\t"
-        "psrad                     $15, %%mm1       \n\t"
-        "psrad                     $15, %%mm4       \n\t"
-        "packssdw                %%mm1, %%mm0       \n\t"
-        "packssdw                %%mm4, %%mm2       \n\t"
-        "packuswb                %%mm0, %%mm0       \n\t"
-        "packuswb                %%mm2, %%mm2       \n\t"
-        "movd                %%mm0, (%1, %%"REG_a") \n\t"
-        "movd                %%mm2, (%2, %%"REG_a") \n\t"
-        "add                        $4, %%"REG_a"   \n\t"
-        " js                        1b              \n\t"
-    : "+r" (src)
-    : "r" (dstU+width), "r" (dstV+width), "g" ((x86_reg)-width), "m"(ff_bgr24toUV[srcFormat == PIX_FMT_RGB24][0])
-    : "%"REG_a
-    );
+    nvXXtoUV_c(dstV, dstU, src1, width);
 }
-#endif
 
-static inline void RENAME(bgr24ToY)(uint8_t *dst, const uint8_t *src, long width, uint32_t *unused)
+static inline void bgr24ToY_c(uint8_t *dst, const uint8_t *src,
+                              long width, uint32_t *unused)
 {
-#if COMPILE_TEMPLATE_MMX
-    RENAME(bgr24ToY_mmx)(dst, src, width, PIX_FMT_BGR24);
-#else
     int i;
     for (i=0; i<width; i++) {
         int b= src[i*3+0];
@@ -1951,14 +236,11 @@ static inline void RENAME(bgr24ToY)(uint8_t *dst, const uint8_t *src, long width
 
         dst[i]= ((RY*r + GY*g + BY*b + (33<<(RGB2YUV_SHIFT-1)))>>RGB2YUV_SHIFT);
     }
-#endif /* COMPILE_TEMPLATE_MMX */
 }
 
-static inline void RENAME(bgr24ToUV)(uint8_t *dstU, uint8_t *dstV, const uint8_t *src1, const uint8_t *src2, long width, uint32_t *unused)
+static inline void bgr24ToUV_c(uint8_t *dstU, uint8_t *dstV, const uint8_t *src1,
+                               const uint8_t *src2, long width, uint32_t *unused)
 {
-#if COMPILE_TEMPLATE_MMX
-    RENAME(bgr24ToUV_mmx)(dstU, dstV, src1, width, PIX_FMT_BGR24);
-#else
     int i;
     for (i=0; i<width; i++) {
         int b= src1[3*i + 0];
@@ -1968,11 +250,11 @@ static inline void RENAME(bgr24ToUV)(uint8_t *dstU, uint8_t *dstV, const uint8_t
         dstU[i]= (RU*r + GU*g + BU*b + (257<<(RGB2YUV_SHIFT-1)))>>RGB2YUV_SHIFT;
         dstV[i]= (RV*r + GV*g + BV*b + (257<<(RGB2YUV_SHIFT-1)))>>RGB2YUV_SHIFT;
     }
-#endif /* COMPILE_TEMPLATE_MMX */
     assert(src1 == src2);
 }
 
-static inline void RENAME(bgr24ToUV_half)(uint8_t *dstU, uint8_t *dstV, const uint8_t *src1, const uint8_t *src2, long width, uint32_t *unused)
+static inline void bgr24ToUV_half_c(uint8_t *dstU, uint8_t *dstV, const uint8_t *src1,
+                                    const uint8_t *src2, long width, uint32_t *unused)
 {
     int i;
     for (i=0; i<width; i++) {
@@ -1986,11 +268,9 @@ static inline void RENAME(bgr24ToUV_half)(uint8_t *dstU, uint8_t *dstV, const ui
     assert(src1 == src2);
 }
 
-static inline void RENAME(rgb24ToY)(uint8_t *dst, const uint8_t *src, long width, uint32_t *unused)
+static inline void rgb24ToY_c(uint8_t *dst, const uint8_t *src, long width,
+                              uint32_t *unused)
 {
-#if COMPILE_TEMPLATE_MMX
-    RENAME(bgr24ToY_mmx)(dst, src, width, PIX_FMT_RGB24);
-#else
     int i;
     for (i=0; i<width; i++) {
         int r= src[i*3+0];
@@ -1999,15 +279,11 @@ static inline void RENAME(rgb24ToY)(uint8_t *dst, const uint8_t *src, long width
 
         dst[i]= ((RY*r + GY*g + BY*b + (33<<(RGB2YUV_SHIFT-1)))>>RGB2YUV_SHIFT);
     }
-#endif
 }
 
-static inline void RENAME(rgb24ToUV)(uint8_t *dstU, uint8_t *dstV, const uint8_t *src1, const uint8_t *src2, long width, uint32_t *unused)
+static inline void rgb24ToUV_c(uint8_t *dstU, uint8_t *dstV, const uint8_t *src1,
+                               const uint8_t *src2, long width, uint32_t *unused)
 {
-#if COMPILE_TEMPLATE_MMX
-    assert(src1==src2);
-    RENAME(bgr24ToUV_mmx)(dstU, dstV, src1, width, PIX_FMT_RGB24);
-#else
     int i;
     assert(src1==src2);
     for (i=0; i<width; i++) {
@@ -2018,10 +294,10 @@ static inline void RENAME(rgb24ToUV)(uint8_t *dstU, uint8_t *dstV, const uint8_t
         dstU[i]= (RU*r + GU*g + BU*b + (257<<(RGB2YUV_SHIFT-1)))>>RGB2YUV_SHIFT;
         dstV[i]= (RV*r + GV*g + BV*b + (257<<(RGB2YUV_SHIFT-1)))>>RGB2YUV_SHIFT;
     }
-#endif
 }
 
-static inline void RENAME(rgb24ToUV_half)(uint8_t *dstU, uint8_t *dstV, const uint8_t *src1, const uint8_t *src2, long width, uint32_t *unused)
+static inline void rgb24ToUV_half_c(uint8_t *dstU, uint8_t *dstV, const uint8_t *src1,
+                                    const uint8_t *src2, long width, uint32_t *unused)
 {
     int i;
     assert(src1==src2);
@@ -2037,163 +313,11 @@ static inline void RENAME(rgb24ToUV_half)(uint8_t *dstU, uint8_t *dstV, const ui
 
 
 // bilinear / bicubic scaling
-static inline void RENAME(hScale)(int16_t *dst, int dstW, const uint8_t *src, int srcW, int xInc,
-                                  const int16_t *filter, const int16_t *filterPos, long filterSize)
+static inline void hScale_c(int16_t *dst, int dstW, const uint8_t *src,
+                            int srcW, int xInc,
+                            const int16_t *filter, const int16_t *filterPos,
+                            long filterSize)
 {
-#if COMPILE_TEMPLATE_MMX
-    assert(filterSize % 4 == 0 && filterSize>0);
-    if (filterSize==4) { // Always true for upscaling, sometimes for down, too.
-        x86_reg counter= -2*dstW;
-        filter-= counter*2;
-        filterPos-= counter/2;
-        dst-= counter/2;
-        __asm__ volatile(
-#if defined(PIC)
-            "push            %%"REG_b"              \n\t"
-#endif
-            "pxor                %%mm7, %%mm7       \n\t"
-            "push           %%"REG_BP"              \n\t" // we use 7 regs here ...
-            "mov             %%"REG_a", %%"REG_BP"  \n\t"
-            ASMALIGN(4)
-            "1:                                     \n\t"
-            "movzwl   (%2, %%"REG_BP"), %%eax       \n\t"
-            "movzwl  2(%2, %%"REG_BP"), %%ebx       \n\t"
-            "movq  (%1, %%"REG_BP", 4), %%mm1       \n\t"
-            "movq 8(%1, %%"REG_BP", 4), %%mm3       \n\t"
-            "movd      (%3, %%"REG_a"), %%mm0       \n\t"
-            "movd      (%3, %%"REG_b"), %%mm2       \n\t"
-            "punpcklbw           %%mm7, %%mm0       \n\t"
-            "punpcklbw           %%mm7, %%mm2       \n\t"
-            "pmaddwd             %%mm1, %%mm0       \n\t"
-            "pmaddwd             %%mm2, %%mm3       \n\t"
-            "movq                %%mm0, %%mm4       \n\t"
-            "punpckldq           %%mm3, %%mm0       \n\t"
-            "punpckhdq           %%mm3, %%mm4       \n\t"
-            "paddd               %%mm4, %%mm0       \n\t"
-            "psrad                  $7, %%mm0       \n\t"
-            "packssdw            %%mm0, %%mm0       \n\t"
-            "movd                %%mm0, (%4, %%"REG_BP")    \n\t"
-            "add                    $4, %%"REG_BP"  \n\t"
-            " jnc                   1b              \n\t"
-
-            "pop            %%"REG_BP"              \n\t"
-#if defined(PIC)
-            "pop             %%"REG_b"              \n\t"
-#endif
-            : "+a" (counter)
-            : "c" (filter), "d" (filterPos), "S" (src), "D" (dst)
-#if !defined(PIC)
-            : "%"REG_b
-#endif
-        );
-    } else if (filterSize==8) {
-        x86_reg counter= -2*dstW;
-        filter-= counter*4;
-        filterPos-= counter/2;
-        dst-= counter/2;
-        __asm__ volatile(
-#if defined(PIC)
-            "push             %%"REG_b"             \n\t"
-#endif
-            "pxor                 %%mm7, %%mm7      \n\t"
-            "push            %%"REG_BP"             \n\t" // we use 7 regs here ...
-            "mov              %%"REG_a", %%"REG_BP" \n\t"
-            ASMALIGN(4)
-            "1:                                     \n\t"
-            "movzwl    (%2, %%"REG_BP"), %%eax      \n\t"
-            "movzwl   2(%2, %%"REG_BP"), %%ebx      \n\t"
-            "movq   (%1, %%"REG_BP", 8), %%mm1      \n\t"
-            "movq 16(%1, %%"REG_BP", 8), %%mm3      \n\t"
-            "movd       (%3, %%"REG_a"), %%mm0      \n\t"
-            "movd       (%3, %%"REG_b"), %%mm2      \n\t"
-            "punpcklbw            %%mm7, %%mm0      \n\t"
-            "punpcklbw            %%mm7, %%mm2      \n\t"
-            "pmaddwd              %%mm1, %%mm0      \n\t"
-            "pmaddwd              %%mm2, %%mm3      \n\t"
-
-            "movq  8(%1, %%"REG_BP", 8), %%mm1      \n\t"
-            "movq 24(%1, %%"REG_BP", 8), %%mm5      \n\t"
-            "movd      4(%3, %%"REG_a"), %%mm4      \n\t"
-            "movd      4(%3, %%"REG_b"), %%mm2      \n\t"
-            "punpcklbw            %%mm7, %%mm4      \n\t"
-            "punpcklbw            %%mm7, %%mm2      \n\t"
-            "pmaddwd              %%mm1, %%mm4      \n\t"
-            "pmaddwd              %%mm2, %%mm5      \n\t"
-            "paddd                %%mm4, %%mm0      \n\t"
-            "paddd                %%mm5, %%mm3      \n\t"
-            "movq                 %%mm0, %%mm4      \n\t"
-            "punpckldq            %%mm3, %%mm0      \n\t"
-            "punpckhdq            %%mm3, %%mm4      \n\t"
-            "paddd                %%mm4, %%mm0      \n\t"
-            "psrad                   $7, %%mm0      \n\t"
-            "packssdw             %%mm0, %%mm0      \n\t"
-            "movd                 %%mm0, (%4, %%"REG_BP")   \n\t"
-            "add                     $4, %%"REG_BP" \n\t"
-            " jnc                    1b             \n\t"
-
-            "pop             %%"REG_BP"             \n\t"
-#if defined(PIC)
-            "pop              %%"REG_b"             \n\t"
-#endif
-            : "+a" (counter)
-            : "c" (filter), "d" (filterPos), "S" (src), "D" (dst)
-#if !defined(PIC)
-            : "%"REG_b
-#endif
-        );
-    } else {
-        const uint8_t *offset = src+filterSize;
-        x86_reg counter= -2*dstW;
-        //filter-= counter*filterSize/2;
-        filterPos-= counter/2;
-        dst-= counter/2;
-        __asm__ volatile(
-            "pxor                  %%mm7, %%mm7     \n\t"
-            ASMALIGN(4)
-            "1:                                     \n\t"
-            "mov                      %2, %%"REG_c" \n\t"
-            "movzwl      (%%"REG_c", %0), %%eax     \n\t"
-            "movzwl     2(%%"REG_c", %0), %%edx     \n\t"
-            "mov                      %5, %%"REG_c" \n\t"
-            "pxor                  %%mm4, %%mm4     \n\t"
-            "pxor                  %%mm5, %%mm5     \n\t"
-            "2:                                     \n\t"
-            "movq                   (%1), %%mm1     \n\t"
-            "movq               (%1, %6), %%mm3     \n\t"
-            "movd (%%"REG_c", %%"REG_a"), %%mm0     \n\t"
-            "movd (%%"REG_c", %%"REG_d"), %%mm2     \n\t"
-            "punpcklbw             %%mm7, %%mm0     \n\t"
-            "punpcklbw             %%mm7, %%mm2     \n\t"
-            "pmaddwd               %%mm1, %%mm0     \n\t"
-            "pmaddwd               %%mm2, %%mm3     \n\t"
-            "paddd                 %%mm3, %%mm5     \n\t"
-            "paddd                 %%mm0, %%mm4     \n\t"
-            "add                      $8, %1        \n\t"
-            "add                      $4, %%"REG_c" \n\t"
-            "cmp                      %4, %%"REG_c" \n\t"
-            " jb                      2b            \n\t"
-            "add                      %6, %1        \n\t"
-            "movq                  %%mm4, %%mm0     \n\t"
-            "punpckldq             %%mm5, %%mm4     \n\t"
-            "punpckhdq             %%mm5, %%mm0     \n\t"
-            "paddd                 %%mm0, %%mm4     \n\t"
-            "psrad                    $7, %%mm4     \n\t"
-            "packssdw              %%mm4, %%mm4     \n\t"
-            "mov                      %3, %%"REG_a" \n\t"
-            "movd                  %%mm4, (%%"REG_a", %0)   \n\t"
-            "add                      $4, %0        \n\t"
-            " jnc                     1b            \n\t"
-
-            : "+r" (counter), "+r" (filter)
-            : "m" (filterPos), "m" (dst), "m"(offset),
-            "m" (src), "r" ((x86_reg)filterSize*2)
-            : "%"REG_a, "%"REG_c, "%"REG_d
-        );
-    }
-#else
-#if COMPILE_TEMPLATE_ALTIVEC
-    hScale_altivec_real(dst, dstW, src, srcW, xInc, filter, filterPos, filterSize);
-#else
     int i;
     for (i=0; i<dstW; i++) {
         int j;
@@ -2208,13 +332,11 @@ static inline void RENAME(hScale)(int16_t *dst, int dstW, const uint8_t *src, in
         dst[i] = FFMIN(val>>7, (1<<15)-1); // the cubic equation does overflow ...
         //dst[i] = val>>7;
     }
-#endif /* COMPILE_TEMPLATE_ALTIVEC */
-#endif /* COMPILE_MMX */
 }
 
 //FIXME all pal and rgb srcFormats could do this convertion as well
 //FIXME all scalers more complex than bilinear could do half of this transform
-static void RENAME(chrRangeToJpeg)(uint16_t *dst, int width)
+static void chrRangeToJpeg_c(uint16_t *dst, int width)
 {
     int i;
     for (i = 0; i < width; i++) {
@@ -2222,7 +344,7 @@ static void RENAME(chrRangeToJpeg)(uint16_t *dst, int width)
         dst[i+VOFW] = (FFMIN(dst[i+VOFW],30775)*4663 - 9289992)>>12; //-264
     }
 }
-static void RENAME(chrRangeFromJpeg)(uint16_t *dst, int width)
+static void chrRangeFromJpeg_c(uint16_t *dst, int width)
 {
     int i;
     for (i = 0; i < width; i++) {
@@ -2230,138 +352,22 @@ static void RENAME(chrRangeFromJpeg)(uint16_t *dst, int width)
         dst[i+VOFW] = (dst[i+VOFW]*1799 + 4081085)>>11; //1469
     }
 }
-static void RENAME(lumRangeToJpeg)(uint16_t *dst, int width)
+static void lumRangeToJpeg_c(uint16_t *dst, int width)
 {
     int i;
     for (i = 0; i < width; i++)
         dst[i] = (FFMIN(dst[i],30189)*19077 - 39057361)>>14;
 }
-static void RENAME(lumRangeFromJpeg)(uint16_t *dst, int width)
+static void lumRangeFromJpeg_c(uint16_t *dst, int width)
 {
     int i;
     for (i = 0; i < width; i++)
         dst[i] = (dst[i]*14071 + 33561947)>>14;
 }
 
-#define FAST_BILINEAR_X86 \
-    "subl    %%edi, %%esi    \n\t" /*  src[xx+1] - src[xx] */                   \
-    "imull   %%ecx, %%esi    \n\t" /* (src[xx+1] - src[xx])*xalpha */           \
-    "shll      $16, %%edi    \n\t"                                              \
-    "addl    %%edi, %%esi    \n\t" /* src[xx+1]*xalpha + src[xx]*(1-xalpha) */  \
-    "mov        %1, %%"REG_D"\n\t"                                              \
-    "shrl       $9, %%esi    \n\t"                                              \
-
-static inline void RENAME(hyscale_fast)(SwsContext *c, int16_t *dst,
-                                        long dstWidth, const uint8_t *src, int srcW,
-                                        int xInc)
+static inline void hyscale_fast_c(SwsContext *c, int16_t *dst, long dstWidth,
+                                  const uint8_t *src, int srcW, int xInc)
 {
-#if ARCH_X86
-#if COMPILE_TEMPLATE_MMX2
-    int32_t *filterPos = c->hLumFilterPos;
-    int16_t *filter    = c->hLumFilter;
-    int     canMMX2BeUsed  = c->canMMX2BeUsed;
-    void    *mmx2FilterCode= c->lumMmx2FilterCode;
-    int i;
-#if defined(PIC)
-    DECLARE_ALIGNED(8, uint64_t, ebxsave);
-#endif
-    if (canMMX2BeUsed) {
-        __asm__ volatile(
-#if defined(PIC)
-            "mov               %%"REG_b", %5        \n\t"
-#endif
-            "pxor                  %%mm7, %%mm7     \n\t"
-            "mov                      %0, %%"REG_c" \n\t"
-            "mov                      %1, %%"REG_D" \n\t"
-            "mov                      %2, %%"REG_d" \n\t"
-            "mov                      %3, %%"REG_b" \n\t"
-            "xor               %%"REG_a", %%"REG_a" \n\t" // i
-            PREFETCH"        (%%"REG_c")            \n\t"
-            PREFETCH"      32(%%"REG_c")            \n\t"
-            PREFETCH"      64(%%"REG_c")            \n\t"
-
-#if ARCH_X86_64
-
-#define CALL_MMX2_FILTER_CODE \
-            "movl            (%%"REG_b"), %%esi     \n\t"\
-            "call                    *%4            \n\t"\
-            "movl (%%"REG_b", %%"REG_a"), %%esi     \n\t"\
-            "add               %%"REG_S", %%"REG_c" \n\t"\
-            "add               %%"REG_a", %%"REG_D" \n\t"\
-            "xor               %%"REG_a", %%"REG_a" \n\t"\
-
-#else
-
-#define CALL_MMX2_FILTER_CODE \
-            "movl (%%"REG_b"), %%esi        \n\t"\
-            "call         *%4                       \n\t"\
-            "addl (%%"REG_b", %%"REG_a"), %%"REG_c" \n\t"\
-            "add               %%"REG_a", %%"REG_D" \n\t"\
-            "xor               %%"REG_a", %%"REG_a" \n\t"\
-
-#endif /* ARCH_X86_64 */
-
-            CALL_MMX2_FILTER_CODE
-            CALL_MMX2_FILTER_CODE
-            CALL_MMX2_FILTER_CODE
-            CALL_MMX2_FILTER_CODE
-            CALL_MMX2_FILTER_CODE
-            CALL_MMX2_FILTER_CODE
-            CALL_MMX2_FILTER_CODE
-            CALL_MMX2_FILTER_CODE
-
-#if defined(PIC)
-            "mov                      %5, %%"REG_b" \n\t"
-#endif
-            :: "m" (src), "m" (dst), "m" (filter), "m" (filterPos),
-            "m" (mmx2FilterCode)
-#if defined(PIC)
-            ,"m" (ebxsave)
-#endif
-            : "%"REG_a, "%"REG_c, "%"REG_d, "%"REG_S, "%"REG_D
-#if !defined(PIC)
-            ,"%"REG_b
-#endif
-        );
-        for (i=dstWidth-1; (i*xInc)>>16 >=srcW-1; i--) dst[i] = src[srcW-1]*128;
-    } else {
-#endif /* COMPILE_TEMPLATE_MMX2 */
-    x86_reg xInc_shr16 = xInc >> 16;
-    uint16_t xInc_mask = xInc & 0xffff;
-    //NO MMX just normal asm ...
-    __asm__ volatile(
-        "xor %%"REG_a", %%"REG_a"            \n\t" // i
-        "xor %%"REG_d", %%"REG_d"            \n\t" // xx
-        "xorl    %%ecx, %%ecx                \n\t" // xalpha
-        ASMALIGN(4)
-        "1:                                  \n\t"
-        "movzbl    (%0, %%"REG_d"), %%edi    \n\t" //src[xx]
-        "movzbl   1(%0, %%"REG_d"), %%esi    \n\t" //src[xx+1]
-        FAST_BILINEAR_X86
-        "movw     %%si, (%%"REG_D", %%"REG_a", 2)   \n\t"
-        "addw       %4, %%cx                 \n\t" //xalpha += xInc&0xFFFF
-        "adc        %3, %%"REG_d"            \n\t" //xx+= xInc>>16 + carry
-
-        "movzbl    (%0, %%"REG_d"), %%edi    \n\t" //src[xx]
-        "movzbl   1(%0, %%"REG_d"), %%esi    \n\t" //src[xx+1]
-        FAST_BILINEAR_X86
-        "movw     %%si, 2(%%"REG_D", %%"REG_a", 2)  \n\t"
-        "addw       %4, %%cx                 \n\t" //xalpha += xInc&0xFFFF
-        "adc        %3, %%"REG_d"            \n\t" //xx+= xInc>>16 + carry
-
-
-        "add        $2, %%"REG_a"            \n\t"
-        "cmp        %2, %%"REG_a"            \n\t"
-        " jb        1b                       \n\t"
-
-
-        :: "r" (src), "m" (dst), "m" (dstWidth), "m" (xInc_shr16), "m" (xInc_mask)
-        : "%"REG_a, "%"REG_d, "%ecx", "%"REG_D, "%esi"
-    );
-#if COMPILE_TEMPLATE_MMX2
-    } //if MMX2 can't be used
-#endif
-#else
     int i;
     unsigned int xpos=0;
     for (i=0;i<dstWidth;i++) {
@@ -2370,15 +376,15 @@ static inline void RENAME(hyscale_fast)(SwsContext *c, int16_t *dst,
         dst[i]= (src[xx]<<7) + (src[xx+1] - src[xx])*xalpha;
         xpos+=xInc;
     }
-#endif /* ARCH_X86 */
 }
 
       // *** horizontal scale Y line to temp buffer
-static inline void RENAME(hyscale)(SwsContext *c, uint16_t *dst, long dstWidth, const uint8_t *src, int srcW, int xInc,
-                                   const int16_t *hLumFilter,
-                                   const int16_t *hLumFilterPos, int hLumFilterSize,
-                                   uint8_t *formatConvBuffer,
-                                   uint32_t *pal, int isAlpha)
+static inline void hyscale_c(SwsContext *c, uint16_t *dst, long dstWidth,
+                             const uint8_t *src, int srcW, int xInc,
+                             const int16_t *hLumFilter,
+                             const int16_t *hLumFilterPos, int hLumFilterSize,
+                             uint8_t *formatConvBuffer,
+                             uint32_t *pal, int isAlpha)
 {
     void (*toYV12)(uint8_t *, const uint8_t *, long, uint32_t *) = isAlpha ? c->alpToYV12 : c->lumToYV12;
     void (*convertRange)(uint16_t *, int) = isAlpha ? NULL : c->lumConvertRange;
@@ -2400,111 +406,10 @@ static inline void RENAME(hyscale)(SwsContext *c, uint16_t *dst, long dstWidth,
         convertRange(dst, dstWidth);
 }
 
-static inline void RENAME(hcscale_fast)(SwsContext *c, int16_t *dst,
-                                        long dstWidth, const uint8_t *src1,
-                                        const uint8_t *src2, int srcW, int xInc)
+static inline void hcscale_fast_c(SwsContext *c, int16_t *dst,
+                                  long dstWidth, const uint8_t *src1,
+                                  const uint8_t *src2, int srcW, int xInc)
 {
-#if ARCH_X86
-#if COMPILE_TEMPLATE_MMX2
-    int32_t *filterPos = c->hChrFilterPos;
-    int16_t *filter    = c->hChrFilter;
-    int     canMMX2BeUsed  = c->canMMX2BeUsed;
-    void    *mmx2FilterCode= c->chrMmx2FilterCode;
-    int i;
-#if defined(PIC)
-    DECLARE_ALIGNED(8, uint64_t, ebxsave);
-#endif
-    if (canMMX2BeUsed) {
-        __asm__ volatile(
-#if defined(PIC)
-            "mov          %%"REG_b", %6         \n\t"
-#endif
-            "pxor             %%mm7, %%mm7      \n\t"
-            "mov                 %0, %%"REG_c"  \n\t"
-            "mov                 %1, %%"REG_D"  \n\t"
-            "mov                 %2, %%"REG_d"  \n\t"
-            "mov                 %3, %%"REG_b"  \n\t"
-            "xor          %%"REG_a", %%"REG_a"  \n\t" // i
-            PREFETCH"   (%%"REG_c")             \n\t"
-            PREFETCH" 32(%%"REG_c")             \n\t"
-            PREFETCH" 64(%%"REG_c")             \n\t"
-
-            CALL_MMX2_FILTER_CODE
-            CALL_MMX2_FILTER_CODE
-            CALL_MMX2_FILTER_CODE
-            CALL_MMX2_FILTER_CODE
-            "xor          %%"REG_a", %%"REG_a"  \n\t" // i
-            "mov                 %5, %%"REG_c"  \n\t" // src
-            "mov                 %1, %%"REG_D"  \n\t" // buf1
-            "add              $"AV_STRINGIFY(VOF)", %%"REG_D"  \n\t"
-            PREFETCH"   (%%"REG_c")             \n\t"
-            PREFETCH" 32(%%"REG_c")             \n\t"
-            PREFETCH" 64(%%"REG_c")             \n\t"
-
-            CALL_MMX2_FILTER_CODE
-            CALL_MMX2_FILTER_CODE
-            CALL_MMX2_FILTER_CODE
-            CALL_MMX2_FILTER_CODE
-
-#if defined(PIC)
-            "mov %6, %%"REG_b"    \n\t"
-#endif
-            :: "m" (src1), "m" (dst), "m" (filter), "m" (filterPos),
-            "m" (mmx2FilterCode), "m" (src2)
-#if defined(PIC)
-            ,"m" (ebxsave)
-#endif
-            : "%"REG_a, "%"REG_c, "%"REG_d, "%"REG_S, "%"REG_D
-#if !defined(PIC)
-            ,"%"REG_b
-#endif
-        );
-        for (i=dstWidth-1; (i*xInc)>>16 >=srcW-1; i--) {
-            //printf("%d %d %d\n", dstWidth, i, srcW);
-            dst[i] = src1[srcW-1]*128;
-            dst[i+VOFW] = src2[srcW-1]*128;
-        }
-    } else {
-#endif /* COMPILE_TEMPLATE_MMX2 */
-        x86_reg xInc_shr16 = (x86_reg) (xInc >> 16);
-        uint16_t xInc_mask = xInc & 0xffff;
-        __asm__ volatile(
-            "xor %%"REG_a", %%"REG_a"               \n\t" // i
-            "xor %%"REG_d", %%"REG_d"               \n\t" // xx
-            "xorl    %%ecx, %%ecx                   \n\t" // xalpha
-            ASMALIGN(4)
-            "1:                                     \n\t"
-            "mov        %0, %%"REG_S"               \n\t"
-            "movzbl  (%%"REG_S", %%"REG_d"), %%edi  \n\t" //src[xx]
-            "movzbl 1(%%"REG_S", %%"REG_d"), %%esi  \n\t" //src[xx+1]
-            FAST_BILINEAR_X86
-            "movw     %%si, (%%"REG_D", %%"REG_a", 2)   \n\t"
-
-            "movzbl    (%5, %%"REG_d"), %%edi       \n\t" //src[xx]
-            "movzbl   1(%5, %%"REG_d"), %%esi       \n\t" //src[xx+1]
-            FAST_BILINEAR_X86
-            "movw     %%si, "AV_STRINGIFY(VOF)"(%%"REG_D", %%"REG_a", 2)   \n\t"
-
-            "addw       %4, %%cx                    \n\t" //xalpha += xInc&0xFFFF
-            "adc        %3, %%"REG_d"               \n\t" //xx+= xInc>>16 + carry
-            "add        $1, %%"REG_a"               \n\t"
-            "cmp        %2, %%"REG_a"               \n\t"
-            " jb        1b                          \n\t"
-
-/* GCC 3.3 makes MPlayer crash on IA-32 machines when using "g" operand here,
-which is needed to support GCC 4.0. */
-#if ARCH_X86_64 && AV_GCC_VERSION_AT_LEAST(3,4)
-            :: "m" (src1), "m" (dst), "g" (dstWidth), "m" (xInc_shr16), "m" (xInc_mask),
-#else
-            :: "m" (src1), "m" (dst), "m" (dstWidth), "m" (xInc_shr16), "m" (xInc_mask),
-#endif
-            "r" (src2)
-            : "%"REG_a, "%"REG_d, "%ecx", "%"REG_D, "%esi"
-        );
-#if COMPILE_TEMPLATE_MMX2
-    } //if MMX2 can't be used
-#endif
-#else
     int i;
     unsigned int xpos=0;
     for (i=0;i<dstWidth;i++) {
@@ -2518,14 +423,13 @@ which is needed to support GCC 4.0. */
         */
         xpos+=xInc;
     }
-#endif /* ARCH_X86 */
 }
 
-inline static void RENAME(hcscale)(SwsContext *c, uint16_t *dst, long dstWidth, const uint8_t *src1, const uint8_t *src2,
-                                   int srcW, int xInc, const int16_t *hChrFilter,
-                                   const int16_t *hChrFilterPos, int hChrFilterSize,
-                                   uint8_t *formatConvBuffer,
-                                   uint32_t *pal)
+inline static void hcscale_c(SwsContext *c, uint16_t *dst, long dstWidth,
+                             const uint8_t *src1, const uint8_t *src2,
+                             int srcW, int xInc, const int16_t *hChrFilter,
+                             const int16_t *hChrFilterPos, int hChrFilterSize,
+                             uint8_t *formatConvBuffer, uint32_t *pal)
 {
 
     src1 += c->chrSrcOffset;
@@ -2551,8 +455,8 @@ inline static void RENAME(hcscale)(SwsContext *c, uint16_t *dst, long dstWidth,
 #define DEBUG_SWSCALE_BUFFERS 0
 #define DEBUG_BUFFERS(...) if (DEBUG_SWSCALE_BUFFERS) av_log(c, AV_LOG_DEBUG, __VA_ARGS__)
 
-static int RENAME(swScale)(SwsContext *c, const uint8_t* src[], int srcStride[], int srcSliceY,
-                           int srcSliceH, uint8_t* dst[], int dstStride[])
+static int swScale_c(SwsContext *c, const uint8_t* src[], int srcStride[],
+                     int srcSliceY, int srcSliceH, uint8_t* dst[], int dstStride[])
 {
     /* load a few things into local vars to make the code more readable? and faster */
     const int srcW= c->srcW;
@@ -2685,15 +589,15 @@ static int RENAME(swScale)(SwsContext *c, const uint8_t* src[], int srcStride[],
             assert(lumBufIndex < 2*vLumBufSize);
             assert(lastInLumBuf + 1 - srcSliceY < srcSliceH);
             assert(lastInLumBuf + 1 - srcSliceY >= 0);
-            RENAME(hyscale)(c, lumPixBuf[ lumBufIndex ], dstW, src1, srcW, lumXInc,
-                            hLumFilter, hLumFilterPos, hLumFilterSize,
-                            formatConvBuffer,
-                            pal, 0);
+            hyscale_c(c, lumPixBuf[ lumBufIndex ], dstW, src1, srcW, lumXInc,
+                      hLumFilter, hLumFilterPos, hLumFilterSize,
+                      formatConvBuffer,
+                      pal, 0);
             if (CONFIG_SWSCALE_ALPHA && alpPixBuf)
-                RENAME(hyscale)(c, alpPixBuf[ lumBufIndex ], dstW, src2, srcW, lumXInc,
-                                hLumFilter, hLumFilterPos, hLumFilterSize,
-                                formatConvBuffer,
-                                pal, 1);
+                hyscale_c(c, alpPixBuf[ lumBufIndex ], dstW, src2, srcW,
+                          lumXInc, hLumFilter, hLumFilterPos, hLumFilterSize,
+                          formatConvBuffer,
+                          pal, 1);
             lastInLumBuf++;
             DEBUG_BUFFERS("\t\tlumBufIndex %d: lastInLumBuf: %d\n",
                                lumBufIndex,    lastInLumBuf);
@@ -2708,7 +612,7 @@ static int RENAME(swScale)(SwsContext *c, const uint8_t* src[], int srcStride[],
             //FIXME replace parameters through context struct (some at least)
 
             if (c->needs_hcscale)
-                RENAME(hcscale)(c, chrPixBuf[ chrBufIndex ], chrDstW, src1, src2, chrSrcW, chrXInc,
+                hcscale_c(c, chrPixBuf[ chrBufIndex ], chrDstW, src1, src2, chrSrcW, chrXInc,
                                 hChrFilter, hChrFilterPos, hChrFilterSize,
                                 formatConvBuffer,
                                 pal);
@@ -2722,65 +626,10 @@ static int RENAME(swScale)(SwsContext *c, const uint8_t* src[], int srcStride[],
         if (!enough_lines)
             break; //we can't output a dstY line so let's try with the next slice
 
-#if COMPILE_TEMPLATE_MMX
-        c->blueDither= ff_dither8[dstY&1];
-        if (c->dstFormat == PIX_FMT_RGB555 || c->dstFormat == PIX_FMT_BGR555)
-            c->greenDither= ff_dither8[dstY&1];
-        else
-            c->greenDither= ff_dither4[dstY&1];
-        c->redDither= ff_dither8[(dstY+1)&1];
-#endif
         if (dstY < dstH-2) {
             const int16_t **lumSrcPtr= (const int16_t **) lumPixBuf + lumBufIndex + firstLumSrcY - lastInLumBuf + vLumBufSize;
             const int16_t **chrSrcPtr= (const int16_t **) chrPixBuf + chrBufIndex + firstChrSrcY - lastInChrBuf + vChrBufSize;
             const int16_t **alpSrcPtr= (CONFIG_SWSCALE_ALPHA && alpPixBuf) ? (const int16_t **) alpPixBuf + lumBufIndex + firstLumSrcY - lastInLumBuf + vLumBufSize : NULL;
-#if COMPILE_TEMPLATE_MMX
-            int i;
-            if (flags & SWS_ACCURATE_RND) {
-                int s= APCK_SIZE / 8;
-                for (i=0; i<vLumFilterSize; i+=2) {
-                    *(const void**)&lumMmxFilter[s*i              ]= lumSrcPtr[i  ];
-                    *(const void**)&lumMmxFilter[s*i+APCK_PTR2/4  ]= lumSrcPtr[i+(vLumFilterSize>1)];
-                              lumMmxFilter[s*i+APCK_COEF/4  ]=
-                              lumMmxFilter[s*i+APCK_COEF/4+1]= vLumFilter[dstY*vLumFilterSize + i    ]
-                        + (vLumFilterSize>1 ? vLumFilter[dstY*vLumFilterSize + i + 1]<<16 : 0);
-                    if (CONFIG_SWSCALE_ALPHA && alpPixBuf) {
-                        *(const void**)&alpMmxFilter[s*i              ]= alpSrcPtr[i  ];
-                        *(const void**)&alpMmxFilter[s*i+APCK_PTR2/4  ]= alpSrcPtr[i+(vLumFilterSize>1)];
-                                  alpMmxFilter[s*i+APCK_COEF/4  ]=
-                                  alpMmxFilter[s*i+APCK_COEF/4+1]= lumMmxFilter[s*i+APCK_COEF/4  ];
-                    }
-                }
-                for (i=0; i<vChrFilterSize; i+=2) {
-                    *(const void**)&chrMmxFilter[s*i              ]= chrSrcPtr[i  ];
-                    *(const void**)&chrMmxFilter[s*i+APCK_PTR2/4  ]= chrSrcPtr[i+(vChrFilterSize>1)];
-                              chrMmxFilter[s*i+APCK_COEF/4  ]=
-                              chrMmxFilter[s*i+APCK_COEF/4+1]= vChrFilter[chrDstY*vChrFilterSize + i    ]
-                        + (vChrFilterSize>1 ? vChrFilter[chrDstY*vChrFilterSize + i + 1]<<16 : 0);
-                }
-            } else {
-                for (i=0; i<vLumFilterSize; i++) {
-                    lumMmxFilter[4*i+0]= (int32_t)lumSrcPtr[i];
-                    lumMmxFilter[4*i+1]= (uint64_t)lumSrcPtr[i] >> 32;
-                    lumMmxFilter[4*i+2]=
-                    lumMmxFilter[4*i+3]=
-                        ((uint16_t)vLumFilter[dstY*vLumFilterSize + i])*0x10001;
-                    if (CONFIG_SWSCALE_ALPHA && alpPixBuf) {
-                        alpMmxFilter[4*i+0]= (int32_t)alpSrcPtr[i];
-                        alpMmxFilter[4*i+1]= (uint64_t)alpSrcPtr[i] >> 32;
-                        alpMmxFilter[4*i+2]=
-                        alpMmxFilter[4*i+3]= lumMmxFilter[4*i+2];
-                    }
-                }
-                for (i=0; i<vChrFilterSize; i++) {
-                    chrMmxFilter[4*i+0]= (int32_t)chrSrcPtr[i];
-                    chrMmxFilter[4*i+1]= (uint64_t)chrSrcPtr[i] >> 32;
-                    chrMmxFilter[4*i+2]=
-                    chrMmxFilter[4*i+3]=
-                        ((uint16_t)vChrFilter[chrDstY*vChrFilterSize + i])*0x10001;
-                }
-            }
-#endif
             if (dstFormat == PIX_FMT_NV12 || dstFormat == PIX_FMT_NV21) {
                 const int chrSkipMask= (1<<c->chrDstVSubSample)-1;
                 if (dstY&chrSkipMask) uDest= NULL; //FIXME split functions in lumi / chromi
@@ -2901,12 +750,6 @@ static int RENAME(swScale)(SwsContext *c, const uint8_t* src[], int srcStride[],
     if ((dstFormat == PIX_FMT_YUVA420P) && !alpPixBuf)
         fillPlane(dst[3], dstStride[3], dstW, dstY-lastDstY, lastDstY, 255);
 
-#if COMPILE_TEMPLATE_MMX
-    if (flags & SWS_CPU_CAPS_MMX2 )  __asm__ volatile("sfence":::"memory");
-    /* On K6 femms is faster than emms. On K7 femms is directly mapped to emms. */
-    if (flags & SWS_CPU_CAPS_3DNOW)  __asm__ volatile("femms" :::"memory");
-    else                             __asm__ volatile("emms"  :::"memory");
-#endif
     /* store changed local vars back in the context */
     c->dstY= dstY;
     c->lumBufIndex= lumBufIndex;
@@ -2917,36 +760,31 @@ static int RENAME(swScale)(SwsContext *c, const uint8_t* src[], int srcStride[],
     return dstY - lastDstY;
 }
 
-static void RENAME(sws_init_swScale)(SwsContext *c)
+static void sws_init_swScale_c(SwsContext *c)
 {
     enum PixelFormat srcFormat = c->srcFormat;
 
-    c->yuv2nv12X    = RENAME(yuv2nv12X   );
-    c->yuv2yuv1     = RENAME(yuv2yuv1    );
-    c->yuv2yuvX     = RENAME(yuv2yuvX    );
-    c->yuv2packed1  = RENAME(yuv2packed1 );
-    c->yuv2packed2  = RENAME(yuv2packed2 );
-    c->yuv2packedX  = RENAME(yuv2packedX );
+    c->yuv2nv12X    = yuv2nv12X_c;
+    c->yuv2yuv1     = yuv2yuv1_c;
+    c->yuv2yuvX     = yuv2yuvX_c;
+    c->yuv2packed1  = yuv2packed1_c;
+    c->yuv2packed2  = yuv2packed2_c;
+    c->yuv2packedX  = yuv2packedX_c;
 
-    c->hScale       = RENAME(hScale      );
+    c->hScale       = hScale_c;
 
-#if COMPILE_TEMPLATE_MMX
-    // Use the new MMX scaler if the MMX2 one can't be used (it is faster than the x86 ASM one).
-    if (c->flags & SWS_FAST_BILINEAR && c->canMMX2BeUsed)
-#else
     if (c->flags & SWS_FAST_BILINEAR)
-#endif
     {
-        c->hyscale_fast = RENAME(hyscale_fast);
-        c->hcscale_fast = RENAME(hcscale_fast);
+        c->hyscale_fast = hyscale_fast_c;
+        c->hcscale_fast = hcscale_fast_c;
     }
 
     c->chrToYV12 = NULL;
     switch(srcFormat) {
-        case PIX_FMT_YUYV422  : c->chrToYV12 = RENAME(yuy2ToUV); break;
-        case PIX_FMT_UYVY422  : c->chrToYV12 = RENAME(uyvyToUV); break;
-        case PIX_FMT_NV12     : c->chrToYV12 = RENAME(nv12ToUV); break;
-        case PIX_FMT_NV21     : c->chrToYV12 = RENAME(nv21ToUV); break;
+        case PIX_FMT_YUYV422  : c->chrToYV12 = yuy2ToUV_c; break;
+        case PIX_FMT_UYVY422  : c->chrToYV12 = uyvyToUV_c; break;
+        case PIX_FMT_NV12     : c->chrToYV12 = nv12ToUV_c; break;
+        case PIX_FMT_NV21     : c->chrToYV12 = nv21ToUV_c; break;
         case PIX_FMT_RGB8     :
         case PIX_FMT_BGR8     :
         case PIX_FMT_PAL8     :
@@ -2954,23 +792,23 @@ static void RENAME(sws_init_swScale)(SwsContext *c)
         case PIX_FMT_RGB4_BYTE: c->chrToYV12 = palToUV; break;
         case PIX_FMT_YUV420P16BE:
         case PIX_FMT_YUV422P16BE:
-        case PIX_FMT_YUV444P16BE: c->chrToYV12 = RENAME(BEToUV); break;
+        case PIX_FMT_YUV444P16BE: c->chrToYV12 = BEToUV_c; break;
         case PIX_FMT_YUV420P16LE:
         case PIX_FMT_YUV422P16LE:
-        case PIX_FMT_YUV444P16LE: c->chrToYV12 = RENAME(LEToUV); break;
+        case PIX_FMT_YUV444P16LE: c->chrToYV12 = LEToUV_c; break;
     }
     if (c->chrSrcHSubSample) {
         switch(srcFormat) {
         case PIX_FMT_RGB48BE:
         case PIX_FMT_RGB48LE: c->chrToYV12 = rgb48ToUV_half; break;
-        case PIX_FMT_RGB32  :
-        case PIX_FMT_RGB32_1: c->chrToYV12 = bgr32ToUV_half; break;
-        case PIX_FMT_BGR24  : c->chrToYV12 = RENAME(bgr24ToUV_half); break;
+        case PIX_FMT_RGB32  : c->chrToYV12 = bgr32ToUV_half;  break;
+        case PIX_FMT_RGB32_1: c->chrToYV12 = bgr321ToUV_half; break;
+        case PIX_FMT_BGR24  : c->chrToYV12 = bgr24ToUV_half_c; break;
         case PIX_FMT_BGR565 : c->chrToYV12 = bgr16ToUV_half; break;
         case PIX_FMT_BGR555 : c->chrToYV12 = bgr15ToUV_half; break;
-        case PIX_FMT_BGR32  :
-        case PIX_FMT_BGR32_1: c->chrToYV12 = rgb32ToUV_half; break;
-        case PIX_FMT_RGB24  : c->chrToYV12 = RENAME(rgb24ToUV_half); break;
+        case PIX_FMT_BGR32  : c->chrToYV12 = rgb32ToUV_half;  break;
+        case PIX_FMT_BGR32_1: c->chrToYV12 = rgb321ToUV_half; break;
+        case PIX_FMT_RGB24  : c->chrToYV12 = rgb24ToUV_half_c; break;
         case PIX_FMT_RGB565 : c->chrToYV12 = rgb16ToUV_half; break;
         case PIX_FMT_RGB555 : c->chrToYV12 = rgb15ToUV_half; break;
         }
@@ -2978,14 +816,14 @@ static void RENAME(sws_init_swScale)(SwsContext *c)
         switch(srcFormat) {
         case PIX_FMT_RGB48BE:
         case PIX_FMT_RGB48LE: c->chrToYV12 = rgb48ToUV; break;
-        case PIX_FMT_RGB32  :
-        case PIX_FMT_RGB32_1: c->chrToYV12 = bgr32ToUV; break;
-        case PIX_FMT_BGR24  : c->chrToYV12 = RENAME(bgr24ToUV); break;
+        case PIX_FMT_RGB32  : c->chrToYV12 = bgr32ToUV;  break;
+        case PIX_FMT_RGB32_1: c->chrToYV12 = bgr321ToUV; break;
+        case PIX_FMT_BGR24  : c->chrToYV12 = bgr24ToUV_c; break;
         case PIX_FMT_BGR565 : c->chrToYV12 = bgr16ToUV; break;
         case PIX_FMT_BGR555 : c->chrToYV12 = bgr15ToUV; break;
-        case PIX_FMT_BGR32  :
-        case PIX_FMT_BGR32_1: c->chrToYV12 = rgb32ToUV; break;
-        case PIX_FMT_RGB24  : c->chrToYV12 = RENAME(rgb24ToUV); break;
+        case PIX_FMT_BGR32  : c->chrToYV12 = rgb32ToUV;  break;
+        case PIX_FMT_BGR32_1: c->chrToYV12 = rgb321ToUV; break;
+        case PIX_FMT_RGB24  : c->chrToYV12 = rgb24ToUV_c; break;
         case PIX_FMT_RGB565 : c->chrToYV12 = rgb16ToUV; break;
         case PIX_FMT_RGB555 : c->chrToYV12 = rgb15ToUV; break;
         }
@@ -2998,16 +836,17 @@ static void RENAME(sws_init_swScale)(SwsContext *c)
     case PIX_FMT_YUV420P16BE:
     case PIX_FMT_YUV422P16BE:
     case PIX_FMT_YUV444P16BE:
-    case PIX_FMT_GRAY16BE : c->lumToYV12 = RENAME(yuy2ToY); break;
+    case PIX_FMT_Y400A    :
+    case PIX_FMT_GRAY16BE : c->lumToYV12 = yuy2ToY_c; break;
     case PIX_FMT_UYVY422  :
     case PIX_FMT_YUV420P16LE:
     case PIX_FMT_YUV422P16LE:
     case PIX_FMT_YUV444P16LE:
-    case PIX_FMT_GRAY16LE : c->lumToYV12 = RENAME(uyvyToY); break;
-    case PIX_FMT_BGR24    : c->lumToYV12 = RENAME(bgr24ToY); break;
+    case PIX_FMT_GRAY16LE : c->lumToYV12 = uyvyToY_c; break;
+    case PIX_FMT_BGR24    : c->lumToYV12 = bgr24ToY_c; break;
     case PIX_FMT_BGR565   : c->lumToYV12 = bgr16ToY; break;
     case PIX_FMT_BGR555   : c->lumToYV12 = bgr15ToY; break;
-    case PIX_FMT_RGB24    : c->lumToYV12 = RENAME(rgb24ToY); break;
+    case PIX_FMT_RGB24    : c->lumToYV12 = rgb24ToY_c; break;
     case PIX_FMT_RGB565   : c->lumToYV12 = rgb16ToY; break;
     case PIX_FMT_RGB555   : c->lumToYV12 = rgb15ToY; break;
     case PIX_FMT_RGB8     :
@@ -3017,10 +856,10 @@ static void RENAME(sws_init_swScale)(SwsContext *c)
     case PIX_FMT_RGB4_BYTE: c->lumToYV12 = palToY; break;
     case PIX_FMT_MONOBLACK: c->lumToYV12 = monoblack2Y; break;
     case PIX_FMT_MONOWHITE: c->lumToYV12 = monowhite2Y; break;
-    case PIX_FMT_RGB32  :
-    case PIX_FMT_RGB32_1: c->lumToYV12 = bgr32ToY; break;
-    case PIX_FMT_BGR32  :
-    case PIX_FMT_BGR32_1: c->lumToYV12 = rgb32ToY; break;
+    case PIX_FMT_RGB32  : c->lumToYV12 = bgr32ToY;  break;
+    case PIX_FMT_RGB32_1: c->lumToYV12 = bgr321ToY; break;
+    case PIX_FMT_BGR32  : c->lumToYV12 = rgb32ToY;  break;
+    case PIX_FMT_BGR32_1: c->lumToYV12 = rgb321ToY; break;
     case PIX_FMT_RGB48BE:
     case PIX_FMT_RGB48LE: c->lumToYV12 = rgb48ToY; break;
     }
@@ -3030,19 +869,18 @@ static void RENAME(sws_init_swScale)(SwsContext *c)
         case PIX_FMT_RGB32_1:
         case PIX_FMT_BGR32  :
         case PIX_FMT_BGR32_1: c->alpToYV12 = abgrToA; break;
+        case PIX_FMT_Y400A  : c->alpToYV12 = yuy2ToY_c; break;
         }
     }
 
     switch (srcFormat) {
+    case PIX_FMT_Y400A  :
+        c->alpSrcOffset = 1;
+        break;
     case PIX_FMT_RGB32  :
     case PIX_FMT_BGR32  :
         c->alpSrcOffset = 3;
         break;
-    case PIX_FMT_RGB32_1:
-    case PIX_FMT_BGR32_1:
-        c->lumSrcOffset = ALT32_CORR;
-        c->chrSrcOffset = ALT32_CORR;
-        break;
     case PIX_FMT_RGB48LE:
         c->lumSrcOffset = 1;
         c->chrSrcOffset = 1;
@@ -3052,11 +890,11 @@ static void RENAME(sws_init_swScale)(SwsContext *c)
 
     if (c->srcRange != c->dstRange && !isAnyRGB(c->dstFormat)) {
         if (c->srcRange) {
-            c->lumConvertRange = RENAME(lumRangeFromJpeg);
-            c->chrConvertRange = RENAME(chrRangeFromJpeg);
+            c->lumConvertRange = lumRangeFromJpeg_c;
+            c->chrConvertRange = chrRangeFromJpeg_c;
         } else {
-            c->lumConvertRange = RENAME(lumRangeToJpeg);
-            c->chrConvertRange = RENAME(chrRangeToJpeg);
+            c->lumConvertRange = lumRangeToJpeg_c;
+            c->chrConvertRange = chrRangeToJpeg_c;
         }
     }
 
diff --git a/libswscale/utils.c b/libswscale/utils.c
index d7a6ea2..bf61dfd 100644
--- a/libswscale/utils.c
+++ b/libswscale/utils.c
@@ -1,24 +1,25 @@
 /*
  * Copyright (C) 2001-2003 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #define _SVID_SOURCE //needed for MAP_ANONYMOUS
+#define _DARWIN_C_SOURCE // needed for MAP_ANON
 #include <inttypes.h>
 #include <string.h>
 #include <math.h>
@@ -42,6 +43,7 @@
 #include "libavutil/x86_cpu.h"
 #include "libavutil/avutil.h"
 #include "libavutil/bswap.h"
+#include "libavutil/opt.h"
 #include "libavutil/pixdesc.h"
 
 unsigned swscale_version(void)
@@ -51,13 +53,13 @@ unsigned swscale_version(void)
 
 const char *swscale_configuration(void)
 {
-    return FFMPEG_CONFIGURATION;
+    return LIBAV_CONFIGURATION;
 }
 
 const char *swscale_license(void)
 {
 #define LICENSE_PREFIX "libswscale license: "
-    return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1;
+    return LICENSE_PREFIX LIBAV_LICENSE + sizeof(LICENSE_PREFIX) - 1;
 }
 
 #define RET 0xC3 //near return opcode for x86
@@ -80,6 +82,7 @@ const char *swscale_license(void)
         || (x)==PIX_FMT_RGB565      \
         || (x)==PIX_FMT_RGB555      \
         || (x)==PIX_FMT_GRAY8       \
+        || (x)==PIX_FMT_Y400A       \
         || (x)==PIX_FMT_YUV410P     \
         || (x)==PIX_FMT_YUV440P     \
         || (x)==PIX_FMT_NV12        \
@@ -287,7 +290,7 @@ static int initFilter(int16_t **outFilter, int16_t **filterPos, int *outFilterSi
                 }
 /*                else if (flags & SWS_X) {
                     double p= param ? param*0.01 : 0.3;
-                    coeff = d ? sin(d*PI)/(d*PI) : 1.0;
+                    coeff = d ? sin(d*M_PI)/(d*M_PI) : 1.0;
                     coeff*= pow(2.0, - p*d*d);
                 }*/
                 else if (flags & SWS_X) {
@@ -671,23 +674,10 @@ static void getSubSampleFactors(int *h, int *v, enum PixelFormat format)
     *v = av_pix_fmt_descriptors[format].log2_chroma_h;
 }
 
-static uint16_t roundToInt16(int64_t f)
-{
-    int r= (f + (1<<15))>>16;
-         if (r<-0x7FFF) return 0x8000;
-    else if (r> 0x7FFF) return 0x7FFF;
-    else                return r;
-}
+static int update_flags_cpu(int flags);
 
 int sws_setColorspaceDetails(SwsContext *c, const int inv_table[4], int srcRange, const int table[4], int dstRange, int brightness, int contrast, int saturation)
 {
-    int64_t crv =  inv_table[0];
-    int64_t cbu =  inv_table[1];
-    int64_t cgu = -inv_table[2];
-    int64_t cgv = -inv_table[3];
-    int64_t cy  = 1<<16;
-    int64_t oy  = 0;
-
     memcpy(c->srcColorspaceTable, inv_table, sizeof(int)*4);
     memcpy(c->dstColorspaceTable,     table, sizeof(int)*4);
 
@@ -698,40 +688,9 @@ int sws_setColorspaceDetails(SwsContext *c, const int inv_table[4], int srcRange
     c->dstRange  = dstRange;
     if (isYUV(c->dstFormat) || isGray(c->dstFormat)) return -1;
 
-    c->uOffset=   0x0400040004000400LL;
-    c->vOffset=   0x0400040004000400LL;
-
-    if (!srcRange) {
-        cy= (cy*255) / 219;
-        oy= 16<<16;
-    } else {
-        crv= (crv*224) / 255;
-        cbu= (cbu*224) / 255;
-        cgu= (cgu*224) / 255;
-        cgv= (cgv*224) / 255;
-    }
-
-    cy = (cy *contrast             )>>16;
-    crv= (crv*contrast * saturation)>>32;
-    cbu= (cbu*contrast * saturation)>>32;
-    cgu= (cgu*contrast * saturation)>>32;
-    cgv= (cgv*contrast * saturation)>>32;
-
-    oy -= 256*brightness;
-
-    c->yCoeff=    roundToInt16(cy *8192) * 0x0001000100010001ULL;
-    c->vrCoeff=   roundToInt16(crv*8192) * 0x0001000100010001ULL;
-    c->ubCoeff=   roundToInt16(cbu*8192) * 0x0001000100010001ULL;
-    c->vgCoeff=   roundToInt16(cgv*8192) * 0x0001000100010001ULL;
-    c->ugCoeff=   roundToInt16(cgu*8192) * 0x0001000100010001ULL;
-    c->yOffset=   roundToInt16(oy *   8) * 0x0001000100010001ULL;
-
-    c->yuv2rgb_y_coeff  = (int16_t)roundToInt16(cy <<13);
-    c->yuv2rgb_y_offset = (int16_t)roundToInt16(oy << 9);
-    c->yuv2rgb_v2r_coeff= (int16_t)roundToInt16(crv<<13);
-    c->yuv2rgb_v2g_coeff= (int16_t)roundToInt16(cgv<<13);
-    c->yuv2rgb_u2g_coeff= (int16_t)roundToInt16(cgu<<13);
-    c->yuv2rgb_u2b_coeff= (int16_t)roundToInt16(cbu<<13);
+    c->dstFormatBpp = av_get_bits_per_pixel(&av_pix_fmt_descriptors[c->dstFormat]);
+    c->srcFormatBpp = av_get_bits_per_pixel(&av_pix_fmt_descriptors[c->srcFormat]);
+    c->flags = update_flags_cpu(c->flags);
 
     ff_yuv2rgb_c_init_tables(c, inv_table, srcRange, brightness, contrast, saturation);
     //FIXME factorize
@@ -761,56 +720,68 @@ int sws_getColorspaceDetails(SwsContext *c, int **inv_table, int *srcRange, int
 static int handle_jpeg(enum 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;
+    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 *sws_getContext(int srcW, int srcH, enum PixelFormat srcFormat,
-                           int dstW, int dstH, enum PixelFormat dstFormat, int flags,
-                           SwsFilter *srcFilter, SwsFilter *dstFilter, const double *param)
+static int update_flags_cpu(int flags)
+{
+#if !CONFIG_RUNTIME_CPUDETECT //ensure that the flags match the compiled variant if cpudetect is off
+    flags &= ~( SWS_CPU_CAPS_MMX
+               |SWS_CPU_CAPS_MMX2
+               |SWS_CPU_CAPS_3DNOW
+               |SWS_CPU_CAPS_SSE2
+               |SWS_CPU_CAPS_ALTIVEC
+               |SWS_CPU_CAPS_BFIN);
+    flags |= ff_hardcodedcpuflags();
+#endif /* CONFIG_RUNTIME_CPUDETECT */
+    return flags;
+}
+
+SwsContext *sws_alloc_context(void)
+{
+    SwsContext *c= av_mallocz(sizeof(SwsContext));
+
+    c->av_class = &sws_context_class;
+    av_opt_set_defaults(c);
+
+    return c;
+}
+
+int sws_init_context(SwsContext *c, SwsFilter *srcFilter, SwsFilter *dstFilter)
 {
-    SwsContext *c;
     int i;
     int usesVFilter, usesHFilter;
     int unscaled;
-    int srcRange, dstRange;
     SwsFilter dummyFilter= {NULL, NULL, NULL, NULL};
+    int srcW= c->srcW;
+    int srcH= c->srcH;
+    int dstW= c->dstW;
+    int dstH= c->dstH;
+    int flags;
+    enum PixelFormat srcFormat= c->srcFormat;
+    enum PixelFormat dstFormat= c->dstFormat;
+
+    flags= c->flags = update_flags_cpu(c->flags);
 #if ARCH_X86
     if (flags & SWS_CPU_CAPS_MMX)
         __asm__ volatile("emms\n\t"::: "memory");
 #endif
-
-#if !CONFIG_RUNTIME_CPUDETECT //ensure that the flags match the compiled variant if cpudetect is off
-    flags &= ~(SWS_CPU_CAPS_MMX|SWS_CPU_CAPS_MMX2|SWS_CPU_CAPS_3DNOW|SWS_CPU_CAPS_ALTIVEC|SWS_CPU_CAPS_BFIN);
-    flags |= ff_hardcodedcpuflags();
-#endif /* CONFIG_RUNTIME_CPUDETECT */
     if (!rgb15to16) sws_rgb2rgb_init(flags);
 
     unscaled = (srcW == dstW && srcH == dstH);
 
-    srcRange = handle_jpeg(&srcFormat);
-    dstRange = handle_jpeg(&dstFormat);
-
     if (!isSupportedIn(srcFormat)) {
         av_log(NULL, AV_LOG_ERROR, "swScaler: %s is not supported as input pixel format\n", sws_format_name(srcFormat));
-        return NULL;
+        return AVERROR(EINVAL);
     }
     if (!isSupportedOut(dstFormat)) {
         av_log(NULL, AV_LOG_ERROR, "swScaler: %s is not supported as output pixel format\n", sws_format_name(dstFormat));
-        return NULL;
+        return AVERROR(EINVAL);
     }
 
     i= flags & ( SWS_POINT
@@ -826,35 +797,24 @@ SwsContext *sws_getContext(int srcW, int srcH, enum PixelFormat srcFormat,
                 |SWS_BICUBLIN);
     if(!i || (i & (i-1))) {
         av_log(NULL, AV_LOG_ERROR, "swScaler: Exactly one scaler algorithm must be chosen\n");
-        return NULL;
+        return AVERROR(EINVAL);
     }
-
     /* sanity check */
     if (srcW<4 || srcH<1 || dstW<8 || dstH<1) { //FIXME check if these are enough and try to lowwer them after fixing the relevant parts of the code
         av_log(NULL, AV_LOG_ERROR, "swScaler: %dx%d -> %dx%d is invalid scaling dimension\n",
                srcW, srcH, dstW, dstH);
-        return NULL;
+        return AVERROR(EINVAL);
     }
     if(srcW > VOFW || dstW > VOFW) {
         av_log(NULL, AV_LOG_ERROR, "swScaler: Compile-time maximum width is "AV_STRINGIFY(VOFW)" change VOF/VOFW and recompile\n");
-        return NULL;
+        return AVERROR(EINVAL);
     }
 
     if (!dstFilter) dstFilter= &dummyFilter;
     if (!srcFilter) srcFilter= &dummyFilter;
 
-    FF_ALLOCZ_OR_GOTO(NULL, c, sizeof(SwsContext), fail);
-
-    c->av_class = &sws_context_class;
-    c->srcW= srcW;
-    c->srcH= srcH;
-    c->dstW= dstW;
-    c->dstH= dstH;
     c->lumXInc= ((srcW<<16) + (dstW>>1))/dstW;
     c->lumYInc= ((srcH<<16) + (dstH>>1))/dstH;
-    c->flags= flags;
-    c->dstFormat= dstFormat;
-    c->srcFormat= srcFormat;
     c->dstFormatBpp = av_get_bits_per_pixel(&av_pix_fmt_descriptors[dstFormat]);
     c->srcFormatBpp = av_get_bits_per_pixel(&av_pix_fmt_descriptors[srcFormat]);
     c->vRounder= 4* 0x0001000100010001ULL;
@@ -883,34 +843,24 @@ SwsContext *sws_getContext(int srcW, int srcH, enum PixelFormat srcFormat,
       && srcFormat!=PIX_FMT_RGB8      && srcFormat!=PIX_FMT_BGR8
       && srcFormat!=PIX_FMT_RGB4      && srcFormat!=PIX_FMT_BGR4
       && srcFormat!=PIX_FMT_RGB4_BYTE && srcFormat!=PIX_FMT_BGR4_BYTE
-      && ((dstW>>c->chrDstHSubSample) <= (srcW>>1) || (flags&(SWS_FAST_BILINEAR|SWS_POINT))))
+      && ((dstW>>c->chrDstHSubSample) <= (srcW>>1) || (flags&SWS_FAST_BILINEAR)))
         c->chrSrcHSubSample=1;
 
-    if (param) {
-        c->param[0] = param[0];
-        c->param[1] = param[1];
-    } else {
-        c->param[0] =
-        c->param[1] = SWS_PARAM_DEFAULT;
-    }
-
     // Note the -((-x)>>y) is so that we always round toward +inf.
     c->chrSrcW= -((-srcW) >> c->chrSrcHSubSample);
     c->chrSrcH= -((-srcH) >> c->chrSrcVSubSample);
     c->chrDstW= -((-dstW) >> c->chrDstHSubSample);
     c->chrDstH= -((-dstH) >> c->chrDstVSubSample);
 
-    sws_setColorspaceDetails(c, ff_yuv2rgb_coeffs[SWS_CS_DEFAULT], srcRange, ff_yuv2rgb_coeffs[SWS_CS_DEFAULT] /* FIXME*/, dstRange, 0, 1<<16, 1<<16);
-
     /* unscaled special cases */
-    if (unscaled && !usesHFilter && !usesVFilter && (srcRange == dstRange || isAnyRGB(dstFormat))) {
+    if (unscaled && !usesHFilter && !usesVFilter && (c->srcRange == c->dstRange || isAnyRGB(dstFormat))) {
         ff_get_unscaled_swscale(c);
 
         if (c->swScale) {
             if (flags&SWS_PRINT_INFO)
                 av_log(c, AV_LOG_INFO, "using unscaled %s -> %s special converter\n",
                        sws_format_name(srcFormat), sws_format_name(dstFormat));
-            return c;
+            return 0;
         }
     }
 
@@ -955,8 +905,8 @@ SwsContext *sws_getContext(int srcW, int srcH, enum PixelFormat srcFormat,
             c->chrMmx2FilterCodeSize = initMMX2HScaler(c->chrDstW, c->chrXInc, NULL, NULL, NULL, 4);
 
 #ifdef MAP_ANONYMOUS
-            c->lumMmx2FilterCode = mmap(NULL, c->lumMmx2FilterCodeSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
-            c->chrMmx2FilterCode = mmap(NULL, c->chrMmx2FilterCodeSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
+            c->lumMmx2FilterCode = mmap(NULL, c->lumMmx2FilterCodeSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+            c->chrMmx2FilterCode = mmap(NULL, c->chrMmx2FilterCodeSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
 #elif HAVE_VIRTUALALLOC
             c->lumMmx2FilterCode = VirtualAlloc(NULL, c->lumMmx2FilterCodeSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
             c->chrMmx2FilterCode = VirtualAlloc(NULL, c->chrMmx2FilterCodeSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
@@ -966,7 +916,7 @@ SwsContext *sws_getContext(int srcW, int srcH, enum PixelFormat srcFormat,
 #endif
 
             if (!c->lumMmx2FilterCode || !c->chrMmx2FilterCode)
-                goto fail;
+                return AVERROR(ENOMEM);
             FF_ALLOCZ_OR_GOTO(c, c->hLumFilter   , (dstW        /8+8)*sizeof(int16_t), fail);
             FF_ALLOCZ_OR_GOTO(c, c->hChrFilter   , (c->chrDstW  /4+8)*sizeof(int16_t), fail);
             FF_ALLOCZ_OR_GOTO(c, c->hLumFilterPos, (dstW      /2/8+8)*sizeof(int32_t), fail);
@@ -1084,30 +1034,18 @@ SwsContext *sws_getContext(int srcW, int srcH, enum PixelFormat srcFormat,
     assert(c->chrDstH <= dstH);
 
     if (flags&SWS_PRINT_INFO) {
-        if (flags&SWS_FAST_BILINEAR)
-            av_log(c, AV_LOG_INFO, "FAST_BILINEAR scaler, ");
-        else if (flags&SWS_BILINEAR)
-            av_log(c, AV_LOG_INFO, "BILINEAR scaler, ");
-        else if (flags&SWS_BICUBIC)
-            av_log(c, AV_LOG_INFO, "BICUBIC scaler, ");
-        else if (flags&SWS_X)
-            av_log(c, AV_LOG_INFO, "Experimental scaler, ");
-        else if (flags&SWS_POINT)
-            av_log(c, AV_LOG_INFO, "Nearest Neighbor / POINT scaler, ");
-        else if (flags&SWS_AREA)
-            av_log(c, AV_LOG_INFO, "Area Averaging scaler, ");
-        else if (flags&SWS_BICUBLIN)
-            av_log(c, AV_LOG_INFO, "luma BICUBIC / chroma BILINEAR scaler, ");
-        else if (flags&SWS_GAUSS)
-            av_log(c, AV_LOG_INFO, "Gaussian scaler, ");
-        else if (flags&SWS_SINC)
-            av_log(c, AV_LOG_INFO, "Sinc scaler, ");
-        else if (flags&SWS_LANCZOS)
-            av_log(c, AV_LOG_INFO, "Lanczos scaler, ");
-        else if (flags&SWS_SPLINE)
-            av_log(c, AV_LOG_INFO, "Bicubic spline scaler, ");
-        else
-            av_log(c, AV_LOG_INFO, "ehh flags invalid?! ");
+        if      (flags&SWS_FAST_BILINEAR) av_log(c, AV_LOG_INFO, "FAST_BILINEAR scaler, ");
+        else if (flags&SWS_BILINEAR)      av_log(c, AV_LOG_INFO, "BILINEAR scaler, ");
+        else if (flags&SWS_BICUBIC)       av_log(c, AV_LOG_INFO, "BICUBIC scaler, ");
+        else if (flags&SWS_X)             av_log(c, AV_LOG_INFO, "Experimental scaler, ");
+        else if (flags&SWS_POINT)         av_log(c, AV_LOG_INFO, "Nearest Neighbor / POINT scaler, ");
+        else if (flags&SWS_AREA)          av_log(c, AV_LOG_INFO, "Area Averaging scaler, ");
+        else if (flags&SWS_BICUBLIN)      av_log(c, AV_LOG_INFO, "luma BICUBIC / chroma BILINEAR scaler, ");
+        else if (flags&SWS_GAUSS)         av_log(c, AV_LOG_INFO, "Gaussian scaler, ");
+        else if (flags&SWS_SINC)          av_log(c, AV_LOG_INFO, "Sinc scaler, ");
+        else if (flags&SWS_LANCZOS)       av_log(c, AV_LOG_INFO, "Lanczos scaler, ");
+        else if (flags&SWS_SPLINE)        av_log(c, AV_LOG_INFO, "Bicubic spline scaler, ");
+        else                              av_log(c, AV_LOG_INFO, "ehh flags invalid?! ");
 
         av_log(c, AV_LOG_INFO, "from %s to %s%s ",
                sws_format_name(srcFormat),
@@ -1120,16 +1058,11 @@ SwsContext *sws_getContext(int srcW, int srcH, enum PixelFormat srcFormat,
 #endif
                sws_format_name(dstFormat));
 
-        if (flags & SWS_CPU_CAPS_MMX2)
-            av_log(c, AV_LOG_INFO, "using MMX2\n");
-        else if (flags & SWS_CPU_CAPS_3DNOW)
-            av_log(c, AV_LOG_INFO, "using 3DNOW\n");
-        else if (flags & SWS_CPU_CAPS_MMX)
-            av_log(c, AV_LOG_INFO, "using MMX\n");
-        else if (flags & SWS_CPU_CAPS_ALTIVEC)
-            av_log(c, AV_LOG_INFO, "using AltiVec\n");
-        else
-            av_log(c, AV_LOG_INFO, "using C\n");
+        if      (flags & SWS_CPU_CAPS_MMX2)    av_log(c, AV_LOG_INFO, "using MMX2\n");
+        else if (flags & SWS_CPU_CAPS_3DNOW)   av_log(c, AV_LOG_INFO, "using 3DNOW\n");
+        else if (flags & SWS_CPU_CAPS_MMX)     av_log(c, AV_LOG_INFO, "using MMX\n");
+        else if (flags & SWS_CPU_CAPS_ALTIVEC) av_log(c, AV_LOG_INFO, "using AltiVec\n");
+        else                                   av_log(c, AV_LOG_INFO, "using C\n");
 
         if (flags & SWS_CPU_CAPS_MMX) {
             if (c->canMMX2BeUsed && (flags&SWS_FAST_BILINEAR))
@@ -1195,12 +1128,45 @@ SwsContext *sws_getContext(int srcW, int srcH, enum PixelFormat srcFormat,
     }
 
     c->swScale= ff_getSwsFunc(c);
-    return c;
+    return 0;
+fail: //FIXME replace things by appropriate error codes
+    return -1;
+}
 
-fail:
-    sws_freeContext(c);
-    return NULL;
+#if FF_API_SWS_GETCONTEXT
+SwsContext *sws_getContext(int srcW, int srcH, enum PixelFormat srcFormat,
+                           int dstW, int dstH, enum PixelFormat dstFormat, int flags,
+                           SwsFilter *srcFilter, SwsFilter *dstFilter, const double *param)
+{
+    SwsContext *c;
+
+    if(!(c=sws_alloc_context()))
+        return NULL;
+
+    c->flags= flags;
+    c->srcW= srcW;
+    c->srcH= srcH;
+    c->dstW= dstW;
+    c->dstH= dstH;
+    c->srcRange = handle_jpeg(&srcFormat);
+    c->dstRange = handle_jpeg(&dstFormat);
+    c->srcFormat= srcFormat;
+    c->dstFormat= dstFormat;
+
+    if (param) {
+        c->param[0] = param[0];
+        c->param[1] = param[1];
+    }
+    sws_setColorspaceDetails(c, ff_yuv2rgb_coeffs[SWS_CS_DEFAULT], c->srcRange, ff_yuv2rgb_coeffs[SWS_CS_DEFAULT] /* FIXME*/, c->dstRange, 0, 1<<16, 1<<16);
+
+    if(sws_init_context(c, srcFilter, dstFilter) < 0){
+        sws_freeContext(c);
+        return NULL;
+    }
+
+    return c;
 }
+#endif
 
 SwsFilter *sws_getDefaultFilter(float lumaGBlur, float chromaGBlur,
                                 float lumaSharpen, float chromaSharpen,
@@ -1567,6 +1533,8 @@ struct SwsContext *sws_getCachedContext(struct SwsContext *context,
     if (!param)
         param = default_param;
 
+    flags = update_flags_cpu(flags);
+
     if (context &&
         (context->srcW      != srcW      ||
          context->srcH      != srcH      ||
@@ -1582,9 +1550,24 @@ struct SwsContext *sws_getCachedContext(struct SwsContext *context,
     }
 
     if (!context) {
-        return sws_getContext(srcW, srcH, srcFormat,
-                              dstW, dstH, dstFormat, flags,
-                              srcFilter, dstFilter, param);
+        if (!(context = sws_alloc_context()))
+            return NULL;
+        context->srcW      = srcW;
+        context->srcH      = srcH;
+        context->srcRange  = handle_jpeg(&srcFormat);
+        context->srcFormat = srcFormat;
+        context->dstW      = dstW;
+        context->dstH      = dstH;
+        context->dstRange  = handle_jpeg(&dstFormat);
+        context->dstFormat = dstFormat;
+        context->flags     = flags;
+        context->param[0]  = param[0];
+        context->param[1]  = param[1];
+        sws_setColorspaceDetails(context, ff_yuv2rgb_coeffs[SWS_CS_DEFAULT], context->srcRange, ff_yuv2rgb_coeffs[SWS_CS_DEFAULT] /* FIXME*/, context->dstRange, 0, 1<<16, 1<<16);
+        if (sws_init_context(context, srcFilter, dstFilter) < 0) {
+            sws_freeContext(context);
+            return NULL;
+        }
     }
     return context;
 }
diff --git a/libswscale/x86/rgb2rgb.c b/libswscale/x86/rgb2rgb.c
new file mode 100644
index 0000000..e84bc1b
--- /dev/null
+++ b/libswscale/x86/rgb2rgb.c
@@ -0,0 +1,137 @@
+/*
+ * software RGB to RGB converter
+ * pluralize by software PAL8 to RGB converter
+ *              software YUV to YUV converter
+ *              software YUV to RGB converter
+ * Written by Nick Kurshev.
+ * palette & YUV & runtime CPU stuff by Michael (michaelni at gmx.at)
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <stdint.h>
+
+#include "config.h"
+#include "libavutil/x86_cpu.h"
+#include "libavutil/bswap.h"
+#include "libswscale/rgb2rgb.h"
+#include "libswscale/swscale.h"
+#include "libswscale/swscale_internal.h"
+
+DECLARE_ASM_CONST(8, uint64_t, mmx_ff)       = 0x00000000000000FFULL;
+DECLARE_ASM_CONST(8, uint64_t, mmx_null)     = 0x0000000000000000ULL;
+DECLARE_ASM_CONST(8, uint64_t, mmx_one)      = 0xFFFFFFFFFFFFFFFFULL;
+DECLARE_ASM_CONST(8, uint64_t, mask32b)      = 0x000000FF000000FFULL;
+DECLARE_ASM_CONST(8, uint64_t, mask32g)      = 0x0000FF000000FF00ULL;
+DECLARE_ASM_CONST(8, uint64_t, mask32r)      = 0x00FF000000FF0000ULL;
+DECLARE_ASM_CONST(8, uint64_t, mask32a)      = 0xFF000000FF000000ULL;
+DECLARE_ASM_CONST(8, uint64_t, mask32)       = 0x00FFFFFF00FFFFFFULL;
+DECLARE_ASM_CONST(8, uint64_t, mask3216br)   = 0x00F800F800F800F8ULL;
+DECLARE_ASM_CONST(8, uint64_t, mask3216g)    = 0x0000FC000000FC00ULL;
+DECLARE_ASM_CONST(8, uint64_t, mask3215g)    = 0x0000F8000000F800ULL;
+DECLARE_ASM_CONST(8, uint64_t, mul3216)      = 0x2000000420000004ULL;
+DECLARE_ASM_CONST(8, uint64_t, mul3215)      = 0x2000000820000008ULL;
+DECLARE_ASM_CONST(8, uint64_t, mask24b)      = 0x00FF0000FF0000FFULL;
+DECLARE_ASM_CONST(8, uint64_t, mask24g)      = 0xFF0000FF0000FF00ULL;
+DECLARE_ASM_CONST(8, uint64_t, mask24r)      = 0x0000FF0000FF0000ULL;
+DECLARE_ASM_CONST(8, uint64_t, mask24l)      = 0x0000000000FFFFFFULL;
+DECLARE_ASM_CONST(8, uint64_t, mask24h)      = 0x0000FFFFFF000000ULL;
+DECLARE_ASM_CONST(8, uint64_t, mask24hh)     = 0xffff000000000000ULL;
+DECLARE_ASM_CONST(8, uint64_t, mask24hhh)    = 0xffffffff00000000ULL;
+DECLARE_ASM_CONST(8, uint64_t, mask24hhhh)   = 0xffffffffffff0000ULL;
+DECLARE_ASM_CONST(8, uint64_t, mask15b)      = 0x001F001F001F001FULL; /* 00000000 00011111  xxB */
+DECLARE_ASM_CONST(8, uint64_t, mask15rg)     = 0x7FE07FE07FE07FE0ULL; /* 01111111 11100000  RGx */
+DECLARE_ASM_CONST(8, uint64_t, mask15s)      = 0xFFE0FFE0FFE0FFE0ULL;
+DECLARE_ASM_CONST(8, uint64_t, mask15g)      = 0x03E003E003E003E0ULL;
+DECLARE_ASM_CONST(8, uint64_t, mask15r)      = 0x7C007C007C007C00ULL;
+#define mask16b mask15b
+DECLARE_ASM_CONST(8, uint64_t, mask16g)      = 0x07E007E007E007E0ULL;
+DECLARE_ASM_CONST(8, uint64_t, mask16r)      = 0xF800F800F800F800ULL;
+DECLARE_ASM_CONST(8, uint64_t, red_16mask)   = 0x0000f8000000f800ULL;
+DECLARE_ASM_CONST(8, uint64_t, green_16mask) = 0x000007e0000007e0ULL;
+DECLARE_ASM_CONST(8, uint64_t, blue_16mask)  = 0x0000001f0000001fULL;
+DECLARE_ASM_CONST(8, uint64_t, red_15mask)   = 0x00007c0000007c00ULL;
+DECLARE_ASM_CONST(8, uint64_t, green_15mask) = 0x000003e0000003e0ULL;
+DECLARE_ASM_CONST(8, uint64_t, blue_15mask)  = 0x0000001f0000001fULL;
+
+#define RGB2YUV_SHIFT 8
+#define BY ((int)( 0.098*(1<<RGB2YUV_SHIFT)+0.5))
+#define BV ((int)(-0.071*(1<<RGB2YUV_SHIFT)+0.5))
+#define BU ((int)( 0.439*(1<<RGB2YUV_SHIFT)+0.5))
+#define GY ((int)( 0.504*(1<<RGB2YUV_SHIFT)+0.5))
+#define GV ((int)(-0.368*(1<<RGB2YUV_SHIFT)+0.5))
+#define GU ((int)(-0.291*(1<<RGB2YUV_SHIFT)+0.5))
+#define RY ((int)( 0.257*(1<<RGB2YUV_SHIFT)+0.5))
+#define RV ((int)( 0.439*(1<<RGB2YUV_SHIFT)+0.5))
+#define RU ((int)(-0.148*(1<<RGB2YUV_SHIFT)+0.5))
+
+//Note: We have C, MMX, MMX2, 3DNOW versions, there is no 3DNOW + MMX2 one.
+
+#define COMPILE_TEMPLATE_MMX2 0
+#define COMPILE_TEMPLATE_AMD3DNOW 0
+#define COMPILE_TEMPLATE_SSE2 0
+
+//MMX versions
+#undef RENAME
+#define RENAME(a) a ## _MMX
+#include "rgb2rgb_template.c"
+
+//MMX2 versions
+#undef RENAME
+#undef COMPILE_TEMPLATE_MMX2
+#define COMPILE_TEMPLATE_MMX2 1
+#define RENAME(a) a ## _MMX2
+#include "rgb2rgb_template.c"
+
+//SSE2 versions
+#undef RENAME
+#undef COMPILE_TEMPLATE_SSE2
+#define COMPILE_TEMPLATE_SSE2 1
+#define RENAME(a) a ## _SSE2
+#include "rgb2rgb_template.c"
+
+//3DNOW versions
+#undef RENAME
+#undef COMPILE_TEMPLATE_MMX2
+#undef COMPILE_TEMPLATE_SSE2
+#undef COMPILE_TEMPLATE_AMD3DNOW
+#define COMPILE_TEMPLATE_MMX2 0
+#define COMPILE_TEMPLATE_SSE2 1
+#define COMPILE_TEMPLATE_AMD3DNOW 1
+#define RENAME(a) a ## _3DNOW
+#include "rgb2rgb_template.c"
+
+/*
+ RGB15->RGB16 original by Strepto/Astral
+ ported to gcc & bugfixed : A'rpi
+ MMX2, 3DNOW optimization by Nick Kurshev
+ 32-bit C version, and and&add trick by Michael Niedermayer
+*/
+
+void rgb2rgb_init_x86(int flags)
+{
+#if HAVE_MMX2 || HAVE_AMD3DNOW || HAVE_MMX
+    if (flags & SWS_CPU_CAPS_SSE2)
+        rgb2rgb_init_SSE2();
+    else if (flags & SWS_CPU_CAPS_MMX2)
+        rgb2rgb_init_MMX2();
+    else if (flags & SWS_CPU_CAPS_3DNOW)
+        rgb2rgb_init_3DNOW();
+    else if (flags & SWS_CPU_CAPS_MMX)
+        rgb2rgb_init_MMX();
+#endif /* HAVE_MMX2 || HAVE_AMD3DNOW || HAVE_MMX */
+}
diff --git a/libswscale/x86/rgb2rgb_template.c b/libswscale/x86/rgb2rgb_template.c
new file mode 100644
index 0000000..a083fc8
--- /dev/null
+++ b/libswscale/x86/rgb2rgb_template.c
@@ -0,0 +1,2646 @@
+/*
+ * software RGB to RGB converter
+ * pluralize by software PAL8 to RGB converter
+ *              software YUV to YUV converter
+ *              software YUV to RGB converter
+ * Written by Nick Kurshev.
+ * palette & YUV & runtime CPU stuff by Michael (michaelni at gmx.at)
+ * lot of big-endian byte order fixes by Alex Beregszaszi
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <stddef.h>
+
+#undef PREFETCH
+#undef MOVNTQ
+#undef EMMS
+#undef SFENCE
+#undef MMREG_SIZE
+#undef PAVGB
+
+#if COMPILE_TEMPLATE_SSE2
+#define MMREG_SIZE 16
+#else
+#define MMREG_SIZE 8
+#endif
+
+#if COMPILE_TEMPLATE_AMD3DNOW
+#define PREFETCH  "prefetch"
+#define PAVGB     "pavgusb"
+#elif COMPILE_TEMPLATE_MMX2
+#define PREFETCH "prefetchnta"
+#define PAVGB     "pavgb"
+#else
+#define PREFETCH  " # nop"
+#endif
+
+#if COMPILE_TEMPLATE_AMD3DNOW
+/* On K6 femms is faster than emms. On K7 femms is directly mapped to emms. */
+#define EMMS     "femms"
+#else
+#define EMMS     "emms"
+#endif
+
+#if COMPILE_TEMPLATE_MMX2
+#define MOVNTQ "movntq"
+#define SFENCE "sfence"
+#else
+#define MOVNTQ "movq"
+#define SFENCE " # nop"
+#endif
+
+static inline void RENAME(rgb24tobgr32)(const uint8_t *src, uint8_t *dst, long src_size)
+{
+    uint8_t *dest = dst;
+    const uint8_t *s = src;
+    const uint8_t *end;
+    const uint8_t *mm_end;
+    end = s + src_size;
+    __asm__ volatile(PREFETCH"    %0"::"m"(*s):"memory");
+    mm_end = end - 23;
+    __asm__ volatile("movq        %0, %%mm7"::"m"(mask32a):"memory");
+    while (s < mm_end) {
+        __asm__ volatile(
+            PREFETCH"    32%1           \n\t"
+            "movd          %1, %%mm0    \n\t"
+            "punpckldq    3%1, %%mm0    \n\t"
+            "movd         6%1, %%mm1    \n\t"
+            "punpckldq    9%1, %%mm1    \n\t"
+            "movd        12%1, %%mm2    \n\t"
+            "punpckldq   15%1, %%mm2    \n\t"
+            "movd        18%1, %%mm3    \n\t"
+            "punpckldq   21%1, %%mm3    \n\t"
+            "por        %%mm7, %%mm0    \n\t"
+            "por        %%mm7, %%mm1    \n\t"
+            "por        %%mm7, %%mm2    \n\t"
+            "por        %%mm7, %%mm3    \n\t"
+            MOVNTQ"     %%mm0,   %0     \n\t"
+            MOVNTQ"     %%mm1,  8%0     \n\t"
+            MOVNTQ"     %%mm2, 16%0     \n\t"
+            MOVNTQ"     %%mm3, 24%0"
+            :"=m"(*dest)
+            :"m"(*s)
+            :"memory");
+        dest += 32;
+        s += 24;
+    }
+    __asm__ volatile(SFENCE:::"memory");
+    __asm__ volatile(EMMS:::"memory");
+    while (s < end) {
+        *dest++ = *s++;
+        *dest++ = *s++;
+        *dest++ = *s++;
+        *dest++ = 255;
+    }
+}
+
+#define STORE_BGR24_MMX \
+            "psrlq         $8, %%mm2    \n\t" \
+            "psrlq         $8, %%mm3    \n\t" \
+            "psrlq         $8, %%mm6    \n\t" \
+            "psrlq         $8, %%mm7    \n\t" \
+            "pand "MANGLE(mask24l)", %%mm0\n\t" \
+            "pand "MANGLE(mask24l)", %%mm1\n\t" \
+            "pand "MANGLE(mask24l)", %%mm4\n\t" \
+            "pand "MANGLE(mask24l)", %%mm5\n\t" \
+            "pand "MANGLE(mask24h)", %%mm2\n\t" \
+            "pand "MANGLE(mask24h)", %%mm3\n\t" \
+            "pand "MANGLE(mask24h)", %%mm6\n\t" \
+            "pand "MANGLE(mask24h)", %%mm7\n\t" \
+            "por        %%mm2, %%mm0    \n\t" \
+            "por        %%mm3, %%mm1    \n\t" \
+            "por        %%mm6, %%mm4    \n\t" \
+            "por        %%mm7, %%mm5    \n\t" \
+ \
+            "movq       %%mm1, %%mm2    \n\t" \
+            "movq       %%mm4, %%mm3    \n\t" \
+            "psllq        $48, %%mm2    \n\t" \
+            "psllq        $32, %%mm3    \n\t" \
+            "pand "MANGLE(mask24hh)", %%mm2\n\t" \
+            "pand "MANGLE(mask24hhh)", %%mm3\n\t" \
+            "por        %%mm2, %%mm0    \n\t" \
+            "psrlq        $16, %%mm1    \n\t" \
+            "psrlq        $32, %%mm4    \n\t" \
+            "psllq        $16, %%mm5    \n\t" \
+            "por        %%mm3, %%mm1    \n\t" \
+            "pand  "MANGLE(mask24hhhh)", %%mm5\n\t" \
+            "por        %%mm5, %%mm4    \n\t" \
+ \
+            MOVNTQ"     %%mm0,   %0     \n\t" \
+            MOVNTQ"     %%mm1,  8%0     \n\t" \
+            MOVNTQ"     %%mm4, 16%0"
+
+
+static inline void RENAME(rgb32tobgr24)(const uint8_t *src, uint8_t *dst, long src_size)
+{
+    uint8_t *dest = dst;
+    const uint8_t *s = src;
+    const uint8_t *end;
+    const uint8_t *mm_end;
+    end = s + src_size;
+    __asm__ volatile(PREFETCH"    %0"::"m"(*s):"memory");
+    mm_end = end - 31;
+    while (s < mm_end) {
+        __asm__ volatile(
+            PREFETCH"    32%1           \n\t"
+            "movq          %1, %%mm0    \n\t"
+            "movq         8%1, %%mm1    \n\t"
+            "movq        16%1, %%mm4    \n\t"
+            "movq        24%1, %%mm5    \n\t"
+            "movq       %%mm0, %%mm2    \n\t"
+            "movq       %%mm1, %%mm3    \n\t"
+            "movq       %%mm4, %%mm6    \n\t"
+            "movq       %%mm5, %%mm7    \n\t"
+            STORE_BGR24_MMX
+            :"=m"(*dest)
+            :"m"(*s)
+            :"memory");
+        dest += 24;
+        s += 32;
+    }
+    __asm__ volatile(SFENCE:::"memory");
+    __asm__ volatile(EMMS:::"memory");
+    while (s < end) {
+        *dest++ = *s++;
+        *dest++ = *s++;
+        *dest++ = *s++;
+        s++;
+    }
+}
+
+/*
+ original by Strepto/Astral
+ ported to gcc & bugfixed: A'rpi
+ MMX2, 3DNOW optimization by Nick Kurshev
+ 32-bit C version, and and&add trick by Michael Niedermayer
+*/
+static inline void RENAME(rgb15to16)(const uint8_t *src, uint8_t *dst, long src_size)
+{
+    register const uint8_t* s=src;
+    register uint8_t* d=dst;
+    register const uint8_t *end;
+    const uint8_t *mm_end;
+    end = s + src_size;
+    __asm__ volatile(PREFETCH"    %0"::"m"(*s));
+    __asm__ volatile("movq        %0, %%mm4"::"m"(mask15s));
+    mm_end = end - 15;
+    while (s<mm_end) {
+        __asm__ volatile(
+            PREFETCH"  32%1         \n\t"
+            "movq        %1, %%mm0  \n\t"
+            "movq       8%1, %%mm2  \n\t"
+            "movq     %%mm0, %%mm1  \n\t"
+            "movq     %%mm2, %%mm3  \n\t"
+            "pand     %%mm4, %%mm0  \n\t"
+            "pand     %%mm4, %%mm2  \n\t"
+            "paddw    %%mm1, %%mm0  \n\t"
+            "paddw    %%mm3, %%mm2  \n\t"
+            MOVNTQ"   %%mm0,  %0    \n\t"
+            MOVNTQ"   %%mm2, 8%0"
+            :"=m"(*d)
+            :"m"(*s)
+        );
+        d+=16;
+        s+=16;
+    }
+    __asm__ volatile(SFENCE:::"memory");
+    __asm__ volatile(EMMS:::"memory");
+    mm_end = end - 3;
+    while (s < mm_end) {
+        register unsigned x= *((const uint32_t *)s);
+        *((uint32_t *)d) = (x&0x7FFF7FFF) + (x&0x7FE07FE0);
+        d+=4;
+        s+=4;
+    }
+    if (s < end) {
+        register unsigned short x= *((const uint16_t *)s);
+        *((uint16_t *)d) = (x&0x7FFF) + (x&0x7FE0);
+    }
+}
+
+static inline void RENAME(rgb16to15)(const uint8_t *src, uint8_t *dst, long src_size)
+{
+    register const uint8_t* s=src;
+    register uint8_t* d=dst;
+    register const uint8_t *end;
+    const uint8_t *mm_end;
+    end = s + src_size;
+    __asm__ volatile(PREFETCH"    %0"::"m"(*s));
+    __asm__ volatile("movq        %0, %%mm7"::"m"(mask15rg));
+    __asm__ volatile("movq        %0, %%mm6"::"m"(mask15b));
+    mm_end = end - 15;
+    while (s<mm_end) {
+        __asm__ volatile(
+            PREFETCH"  32%1         \n\t"
+            "movq        %1, %%mm0  \n\t"
+            "movq       8%1, %%mm2  \n\t"
+            "movq     %%mm0, %%mm1  \n\t"
+            "movq     %%mm2, %%mm3  \n\t"
+            "psrlq       $1, %%mm0  \n\t"
+            "psrlq       $1, %%mm2  \n\t"
+            "pand     %%mm7, %%mm0  \n\t"
+            "pand     %%mm7, %%mm2  \n\t"
+            "pand     %%mm6, %%mm1  \n\t"
+            "pand     %%mm6, %%mm3  \n\t"
+            "por      %%mm1, %%mm0  \n\t"
+            "por      %%mm3, %%mm2  \n\t"
+            MOVNTQ"   %%mm0,  %0    \n\t"
+            MOVNTQ"   %%mm2, 8%0"
+            :"=m"(*d)
+            :"m"(*s)
+        );
+        d+=16;
+        s+=16;
+    }
+    __asm__ volatile(SFENCE:::"memory");
+    __asm__ volatile(EMMS:::"memory");
+    mm_end = end - 3;
+    while (s < mm_end) {
+        register uint32_t x= *((const uint32_t*)s);
+        *((uint32_t *)d) = ((x>>1)&0x7FE07FE0) | (x&0x001F001F);
+        s+=4;
+        d+=4;
+    }
+    if (s < end) {
+        register uint16_t x= *((const uint16_t*)s);
+        *((uint16_t *)d) = ((x>>1)&0x7FE0) | (x&0x001F);
+    }
+}
+
+static inline void RENAME(rgb32to16)(const uint8_t *src, uint8_t *dst, long src_size)
+{
+    const uint8_t *s = src;
+    const uint8_t *end;
+    const uint8_t *mm_end;
+    uint16_t *d = (uint16_t *)dst;
+    end = s + src_size;
+    mm_end = end - 15;
+#if 1 //is faster only if multiplies are reasonably fast (FIXME figure out on which CPUs this is faster, on Athlon it is slightly faster)
+    __asm__ volatile(
+        "movq           %3, %%mm5   \n\t"
+        "movq           %4, %%mm6   \n\t"
+        "movq           %5, %%mm7   \n\t"
+        "jmp 2f                     \n\t"
+        ".p2align        4          \n\t"
+        "1:                         \n\t"
+        PREFETCH"   32(%1)          \n\t"
+        "movd         (%1), %%mm0   \n\t"
+        "movd        4(%1), %%mm3   \n\t"
+        "punpckldq   8(%1), %%mm0   \n\t"
+        "punpckldq  12(%1), %%mm3   \n\t"
+        "movq        %%mm0, %%mm1   \n\t"
+        "movq        %%mm3, %%mm4   \n\t"
+        "pand        %%mm6, %%mm0   \n\t"
+        "pand        %%mm6, %%mm3   \n\t"
+        "pmaddwd     %%mm7, %%mm0   \n\t"
+        "pmaddwd     %%mm7, %%mm3   \n\t"
+        "pand        %%mm5, %%mm1   \n\t"
+        "pand        %%mm5, %%mm4   \n\t"
+        "por         %%mm1, %%mm0   \n\t"
+        "por         %%mm4, %%mm3   \n\t"
+        "psrld          $5, %%mm0   \n\t"
+        "pslld         $11, %%mm3   \n\t"
+        "por         %%mm3, %%mm0   \n\t"
+        MOVNTQ"      %%mm0, (%0)    \n\t"
+        "add           $16,  %1     \n\t"
+        "add            $8,  %0     \n\t"
+        "2:                         \n\t"
+        "cmp            %2,  %1     \n\t"
+        " jb            1b          \n\t"
+        : "+r" (d), "+r"(s)
+        : "r" (mm_end), "m" (mask3216g), "m" (mask3216br), "m" (mul3216)
+    );
+#else
+    __asm__ volatile(PREFETCH"    %0"::"m"(*src):"memory");
+    __asm__ volatile(
+        "movq    %0, %%mm7    \n\t"
+        "movq    %1, %%mm6    \n\t"
+        ::"m"(red_16mask),"m"(green_16mask));
+    while (s < mm_end) {
+        __asm__ volatile(
+            PREFETCH"    32%1           \n\t"
+            "movd          %1, %%mm0    \n\t"
+            "movd         4%1, %%mm3    \n\t"
+            "punpckldq    8%1, %%mm0    \n\t"
+            "punpckldq   12%1, %%mm3    \n\t"
+            "movq       %%mm0, %%mm1    \n\t"
+            "movq       %%mm0, %%mm2    \n\t"
+            "movq       %%mm3, %%mm4    \n\t"
+            "movq       %%mm3, %%mm5    \n\t"
+            "psrlq         $3, %%mm0    \n\t"
+            "psrlq         $3, %%mm3    \n\t"
+            "pand          %2, %%mm0    \n\t"
+            "pand          %2, %%mm3    \n\t"
+            "psrlq         $5, %%mm1    \n\t"
+            "psrlq         $5, %%mm4    \n\t"
+            "pand       %%mm6, %%mm1    \n\t"
+            "pand       %%mm6, %%mm4    \n\t"
+            "psrlq         $8, %%mm2    \n\t"
+            "psrlq         $8, %%mm5    \n\t"
+            "pand       %%mm7, %%mm2    \n\t"
+            "pand       %%mm7, %%mm5    \n\t"
+            "por        %%mm1, %%mm0    \n\t"
+            "por        %%mm4, %%mm3    \n\t"
+            "por        %%mm2, %%mm0    \n\t"
+            "por        %%mm5, %%mm3    \n\t"
+            "psllq        $16, %%mm3    \n\t"
+            "por        %%mm3, %%mm0    \n\t"
+            MOVNTQ"     %%mm0, %0       \n\t"
+            :"=m"(*d):"m"(*s),"m"(blue_16mask):"memory");
+        d += 4;
+        s += 16;
+    }
+#endif
+    __asm__ volatile(SFENCE:::"memory");
+    __asm__ volatile(EMMS:::"memory");
+    while (s < end) {
+        register int rgb = *(const uint32_t*)s; s += 4;
+        *d++ = ((rgb&0xFF)>>3) + ((rgb&0xFC00)>>5) + ((rgb&0xF80000)>>8);
+    }
+}
+
+static inline void RENAME(rgb32tobgr16)(const uint8_t *src, uint8_t *dst, long src_size)
+{
+    const uint8_t *s = src;
+    const uint8_t *end;
+    const uint8_t *mm_end;
+    uint16_t *d = (uint16_t *)dst;
+    end = s + src_size;
+    __asm__ volatile(PREFETCH"    %0"::"m"(*src):"memory");
+    __asm__ volatile(
+        "movq          %0, %%mm7    \n\t"
+        "movq          %1, %%mm6    \n\t"
+        ::"m"(red_16mask),"m"(green_16mask));
+    mm_end = end - 15;
+    while (s < mm_end) {
+        __asm__ volatile(
+            PREFETCH"    32%1           \n\t"
+            "movd          %1, %%mm0    \n\t"
+            "movd         4%1, %%mm3    \n\t"
+            "punpckldq    8%1, %%mm0    \n\t"
+            "punpckldq   12%1, %%mm3    \n\t"
+            "movq       %%mm0, %%mm1    \n\t"
+            "movq       %%mm0, %%mm2    \n\t"
+            "movq       %%mm3, %%mm4    \n\t"
+            "movq       %%mm3, %%mm5    \n\t"
+            "psllq         $8, %%mm0    \n\t"
+            "psllq         $8, %%mm3    \n\t"
+            "pand       %%mm7, %%mm0    \n\t"
+            "pand       %%mm7, %%mm3    \n\t"
+            "psrlq         $5, %%mm1    \n\t"
+            "psrlq         $5, %%mm4    \n\t"
+            "pand       %%mm6, %%mm1    \n\t"
+            "pand       %%mm6, %%mm4    \n\t"
+            "psrlq        $19, %%mm2    \n\t"
+            "psrlq        $19, %%mm5    \n\t"
+            "pand          %2, %%mm2    \n\t"
+            "pand          %2, %%mm5    \n\t"
+            "por        %%mm1, %%mm0    \n\t"
+            "por        %%mm4, %%mm3    \n\t"
+            "por        %%mm2, %%mm0    \n\t"
+            "por        %%mm5, %%mm3    \n\t"
+            "psllq        $16, %%mm3    \n\t"
+            "por        %%mm3, %%mm0    \n\t"
+            MOVNTQ"     %%mm0, %0       \n\t"
+            :"=m"(*d):"m"(*s),"m"(blue_16mask):"memory");
+        d += 4;
+        s += 16;
+    }
+    __asm__ volatile(SFENCE:::"memory");
+    __asm__ volatile(EMMS:::"memory");
+    while (s < end) {
+        register int rgb = *(const uint32_t*)s; s += 4;
+        *d++ = ((rgb&0xF8)<<8) + ((rgb&0xFC00)>>5) + ((rgb&0xF80000)>>19);
+    }
+}
+
+static inline void RENAME(rgb32to15)(const uint8_t *src, uint8_t *dst, long src_size)
+{
+    const uint8_t *s = src;
+    const uint8_t *end;
+    const uint8_t *mm_end;
+    uint16_t *d = (uint16_t *)dst;
+    end = s + src_size;
+    mm_end = end - 15;
+#if 1 //is faster only if multiplies are reasonably fast (FIXME figure out on which CPUs this is faster, on Athlon it is slightly faster)
+    __asm__ volatile(
+        "movq           %3, %%mm5   \n\t"
+        "movq           %4, %%mm6   \n\t"
+        "movq           %5, %%mm7   \n\t"
+        "jmp            2f          \n\t"
+        ".p2align        4          \n\t"
+        "1:                         \n\t"
+        PREFETCH"   32(%1)          \n\t"
+        "movd         (%1), %%mm0   \n\t"
+        "movd        4(%1), %%mm3   \n\t"
+        "punpckldq   8(%1), %%mm0   \n\t"
+        "punpckldq  12(%1), %%mm3   \n\t"
+        "movq        %%mm0, %%mm1   \n\t"
+        "movq        %%mm3, %%mm4   \n\t"
+        "pand        %%mm6, %%mm0   \n\t"
+        "pand        %%mm6, %%mm3   \n\t"
+        "pmaddwd     %%mm7, %%mm0   \n\t"
+        "pmaddwd     %%mm7, %%mm3   \n\t"
+        "pand        %%mm5, %%mm1   \n\t"
+        "pand        %%mm5, %%mm4   \n\t"
+        "por         %%mm1, %%mm0   \n\t"
+        "por         %%mm4, %%mm3   \n\t"
+        "psrld          $6, %%mm0   \n\t"
+        "pslld         $10, %%mm3   \n\t"
+        "por         %%mm3, %%mm0   \n\t"
+        MOVNTQ"      %%mm0, (%0)    \n\t"
+        "add           $16,  %1     \n\t"
+        "add            $8,  %0     \n\t"
+        "2:                         \n\t"
+        "cmp            %2,  %1     \n\t"
+        " jb            1b          \n\t"
+        : "+r" (d), "+r"(s)
+        : "r" (mm_end), "m" (mask3215g), "m" (mask3216br), "m" (mul3215)
+    );
+#else
+    __asm__ volatile(PREFETCH"    %0"::"m"(*src):"memory");
+    __asm__ volatile(
+        "movq          %0, %%mm7    \n\t"
+        "movq          %1, %%mm6    \n\t"
+        ::"m"(red_15mask),"m"(green_15mask));
+    while (s < mm_end) {
+        __asm__ volatile(
+            PREFETCH"    32%1           \n\t"
+            "movd          %1, %%mm0    \n\t"
+            "movd         4%1, %%mm3    \n\t"
+            "punpckldq    8%1, %%mm0    \n\t"
+            "punpckldq   12%1, %%mm3    \n\t"
+            "movq       %%mm0, %%mm1    \n\t"
+            "movq       %%mm0, %%mm2    \n\t"
+            "movq       %%mm3, %%mm4    \n\t"
+            "movq       %%mm3, %%mm5    \n\t"
+            "psrlq         $3, %%mm0    \n\t"
+            "psrlq         $3, %%mm3    \n\t"
+            "pand          %2, %%mm0    \n\t"
+            "pand          %2, %%mm3    \n\t"
+            "psrlq         $6, %%mm1    \n\t"
+            "psrlq         $6, %%mm4    \n\t"
+            "pand       %%mm6, %%mm1    \n\t"
+            "pand       %%mm6, %%mm4    \n\t"
+            "psrlq         $9, %%mm2    \n\t"
+            "psrlq         $9, %%mm5    \n\t"
+            "pand       %%mm7, %%mm2    \n\t"
+            "pand       %%mm7, %%mm5    \n\t"
+            "por        %%mm1, %%mm0    \n\t"
+            "por        %%mm4, %%mm3    \n\t"
+            "por        %%mm2, %%mm0    \n\t"
+            "por        %%mm5, %%mm3    \n\t"
+            "psllq        $16, %%mm3    \n\t"
+            "por        %%mm3, %%mm0    \n\t"
+            MOVNTQ"     %%mm0, %0       \n\t"
+            :"=m"(*d):"m"(*s),"m"(blue_15mask):"memory");
+        d += 4;
+        s += 16;
+    }
+#endif
+    __asm__ volatile(SFENCE:::"memory");
+    __asm__ volatile(EMMS:::"memory");
+    while (s < end) {
+        register int rgb = *(const uint32_t*)s; s += 4;
+        *d++ = ((rgb&0xFF)>>3) + ((rgb&0xF800)>>6) + ((rgb&0xF80000)>>9);
+    }
+}
+
+static inline void RENAME(rgb32tobgr15)(const uint8_t *src, uint8_t *dst, long src_size)
+{
+    const uint8_t *s = src;
+    const uint8_t *end;
+    const uint8_t *mm_end;
+    uint16_t *d = (uint16_t *)dst;
+    end = s + src_size;
+    __asm__ volatile(PREFETCH"    %0"::"m"(*src):"memory");
+    __asm__ volatile(
+        "movq          %0, %%mm7    \n\t"
+        "movq          %1, %%mm6    \n\t"
+        ::"m"(red_15mask),"m"(green_15mask));
+    mm_end = end - 15;
+    while (s < mm_end) {
+        __asm__ volatile(
+            PREFETCH"    32%1           \n\t"
+            "movd          %1, %%mm0    \n\t"
+            "movd         4%1, %%mm3    \n\t"
+            "punpckldq    8%1, %%mm0    \n\t"
+            "punpckldq   12%1, %%mm3    \n\t"
+            "movq       %%mm0, %%mm1    \n\t"
+            "movq       %%mm0, %%mm2    \n\t"
+            "movq       %%mm3, %%mm4    \n\t"
+            "movq       %%mm3, %%mm5    \n\t"
+            "psllq         $7, %%mm0    \n\t"
+            "psllq         $7, %%mm3    \n\t"
+            "pand       %%mm7, %%mm0    \n\t"
+            "pand       %%mm7, %%mm3    \n\t"
+            "psrlq         $6, %%mm1    \n\t"
+            "psrlq         $6, %%mm4    \n\t"
+            "pand       %%mm6, %%mm1    \n\t"
+            "pand       %%mm6, %%mm4    \n\t"
+            "psrlq        $19, %%mm2    \n\t"
+            "psrlq        $19, %%mm5    \n\t"
+            "pand          %2, %%mm2    \n\t"
+            "pand          %2, %%mm5    \n\t"
+            "por        %%mm1, %%mm0    \n\t"
+            "por        %%mm4, %%mm3    \n\t"
+            "por        %%mm2, %%mm0    \n\t"
+            "por        %%mm5, %%mm3    \n\t"
+            "psllq        $16, %%mm3    \n\t"
+            "por        %%mm3, %%mm0    \n\t"
+            MOVNTQ"     %%mm0, %0       \n\t"
+            :"=m"(*d):"m"(*s),"m"(blue_15mask):"memory");
+        d += 4;
+        s += 16;
+    }
+    __asm__ volatile(SFENCE:::"memory");
+    __asm__ volatile(EMMS:::"memory");
+    while (s < end) {
+        register int rgb = *(const uint32_t*)s; s += 4;
+        *d++ = ((rgb&0xF8)<<7) + ((rgb&0xF800)>>6) + ((rgb&0xF80000)>>19);
+    }
+}
+
+static inline void RENAME(rgb24tobgr16)(const uint8_t *src, uint8_t *dst, long src_size)
+{
+    const uint8_t *s = src;
+    const uint8_t *end;
+    const uint8_t *mm_end;
+    uint16_t *d = (uint16_t *)dst;
+    end = s + src_size;
+    __asm__ volatile(PREFETCH"    %0"::"m"(*src):"memory");
+    __asm__ volatile(
+        "movq         %0, %%mm7     \n\t"
+        "movq         %1, %%mm6     \n\t"
+        ::"m"(red_16mask),"m"(green_16mask));
+    mm_end = end - 11;
+    while (s < mm_end) {
+        __asm__ volatile(
+            PREFETCH"    32%1           \n\t"
+            "movd          %1, %%mm0    \n\t"
+            "movd         3%1, %%mm3    \n\t"
+            "punpckldq    6%1, %%mm0    \n\t"
+            "punpckldq    9%1, %%mm3    \n\t"
+            "movq       %%mm0, %%mm1    \n\t"
+            "movq       %%mm0, %%mm2    \n\t"
+            "movq       %%mm3, %%mm4    \n\t"
+            "movq       %%mm3, %%mm5    \n\t"
+            "psrlq         $3, %%mm0    \n\t"
+            "psrlq         $3, %%mm3    \n\t"
+            "pand          %2, %%mm0    \n\t"
+            "pand          %2, %%mm3    \n\t"
+            "psrlq         $5, %%mm1    \n\t"
+            "psrlq         $5, %%mm4    \n\t"
+            "pand       %%mm6, %%mm1    \n\t"
+            "pand       %%mm6, %%mm4    \n\t"
+            "psrlq         $8, %%mm2    \n\t"
+            "psrlq         $8, %%mm5    \n\t"
+            "pand       %%mm7, %%mm2    \n\t"
+            "pand       %%mm7, %%mm5    \n\t"
+            "por        %%mm1, %%mm0    \n\t"
+            "por        %%mm4, %%mm3    \n\t"
+            "por        %%mm2, %%mm0    \n\t"
+            "por        %%mm5, %%mm3    \n\t"
+            "psllq        $16, %%mm3    \n\t"
+            "por        %%mm3, %%mm0    \n\t"
+            MOVNTQ"     %%mm0, %0       \n\t"
+            :"=m"(*d):"m"(*s),"m"(blue_16mask):"memory");
+        d += 4;
+        s += 12;
+    }
+    __asm__ volatile(SFENCE:::"memory");
+    __asm__ volatile(EMMS:::"memory");
+    while (s < end) {
+        const int b = *s++;
+        const int g = *s++;
+        const int r = *s++;
+        *d++ = (b>>3) | ((g&0xFC)<<3) | ((r&0xF8)<<8);
+    }
+}
+
+static inline void RENAME(rgb24to16)(const uint8_t *src, uint8_t *dst, long src_size)
+{
+    const uint8_t *s = src;
+    const uint8_t *end;
+    const uint8_t *mm_end;
+    uint16_t *d = (uint16_t *)dst;
+    end = s + src_size;
+    __asm__ volatile(PREFETCH"    %0"::"m"(*src):"memory");
+    __asm__ volatile(
+        "movq         %0, %%mm7     \n\t"
+        "movq         %1, %%mm6     \n\t"
+        ::"m"(red_16mask),"m"(green_16mask));
+    mm_end = end - 15;
+    while (s < mm_end) {
+        __asm__ volatile(
+            PREFETCH"    32%1           \n\t"
+            "movd          %1, %%mm0    \n\t"
+            "movd         3%1, %%mm3    \n\t"
+            "punpckldq    6%1, %%mm0    \n\t"
+            "punpckldq    9%1, %%mm3    \n\t"
+            "movq       %%mm0, %%mm1    \n\t"
+            "movq       %%mm0, %%mm2    \n\t"
+            "movq       %%mm3, %%mm4    \n\t"
+            "movq       %%mm3, %%mm5    \n\t"
+            "psllq         $8, %%mm0    \n\t"
+            "psllq         $8, %%mm3    \n\t"
+            "pand       %%mm7, %%mm0    \n\t"
+            "pand       %%mm7, %%mm3    \n\t"
+            "psrlq         $5, %%mm1    \n\t"
+            "psrlq         $5, %%mm4    \n\t"
+            "pand       %%mm6, %%mm1    \n\t"
+            "pand       %%mm6, %%mm4    \n\t"
+            "psrlq        $19, %%mm2    \n\t"
+            "psrlq        $19, %%mm5    \n\t"
+            "pand          %2, %%mm2    \n\t"
+            "pand          %2, %%mm5    \n\t"
+            "por        %%mm1, %%mm0    \n\t"
+            "por        %%mm4, %%mm3    \n\t"
+            "por        %%mm2, %%mm0    \n\t"
+            "por        %%mm5, %%mm3    \n\t"
+            "psllq        $16, %%mm3    \n\t"
+            "por        %%mm3, %%mm0    \n\t"
+            MOVNTQ"     %%mm0, %0       \n\t"
+            :"=m"(*d):"m"(*s),"m"(blue_16mask):"memory");
+        d += 4;
+        s += 12;
+    }
+    __asm__ volatile(SFENCE:::"memory");
+    __asm__ volatile(EMMS:::"memory");
+    while (s < end) {
+        const int r = *s++;
+        const int g = *s++;
+        const int b = *s++;
+        *d++ = (b>>3) | ((g&0xFC)<<3) | ((r&0xF8)<<8);
+    }
+}
+
+static inline void RENAME(rgb24tobgr15)(const uint8_t *src, uint8_t *dst, long src_size)
+{
+    const uint8_t *s = src;
+    const uint8_t *end;
+    const uint8_t *mm_end;
+    uint16_t *d = (uint16_t *)dst;
+    end = s + src_size;
+    __asm__ volatile(PREFETCH"    %0"::"m"(*src):"memory");
+    __asm__ volatile(
+        "movq          %0, %%mm7    \n\t"
+        "movq          %1, %%mm6    \n\t"
+        ::"m"(red_15mask),"m"(green_15mask));
+    mm_end = end - 11;
+    while (s < mm_end) {
+        __asm__ volatile(
+            PREFETCH"    32%1           \n\t"
+            "movd          %1, %%mm0    \n\t"
+            "movd         3%1, %%mm3    \n\t"
+            "punpckldq    6%1, %%mm0    \n\t"
+            "punpckldq    9%1, %%mm3    \n\t"
+            "movq       %%mm0, %%mm1    \n\t"
+            "movq       %%mm0, %%mm2    \n\t"
+            "movq       %%mm3, %%mm4    \n\t"
+            "movq       %%mm3, %%mm5    \n\t"
+            "psrlq         $3, %%mm0    \n\t"
+            "psrlq         $3, %%mm3    \n\t"
+            "pand          %2, %%mm0    \n\t"
+            "pand          %2, %%mm3    \n\t"
+            "psrlq         $6, %%mm1    \n\t"
+            "psrlq         $6, %%mm4    \n\t"
+            "pand       %%mm6, %%mm1    \n\t"
+            "pand       %%mm6, %%mm4    \n\t"
+            "psrlq         $9, %%mm2    \n\t"
+            "psrlq         $9, %%mm5    \n\t"
+            "pand       %%mm7, %%mm2    \n\t"
+            "pand       %%mm7, %%mm5    \n\t"
+            "por        %%mm1, %%mm0    \n\t"
+            "por        %%mm4, %%mm3    \n\t"
+            "por        %%mm2, %%mm0    \n\t"
+            "por        %%mm5, %%mm3    \n\t"
+            "psllq        $16, %%mm3    \n\t"
+            "por        %%mm3, %%mm0    \n\t"
+            MOVNTQ"     %%mm0, %0       \n\t"
+            :"=m"(*d):"m"(*s),"m"(blue_15mask):"memory");
+        d += 4;
+        s += 12;
+    }
+    __asm__ volatile(SFENCE:::"memory");
+    __asm__ volatile(EMMS:::"memory");
+    while (s < end) {
+        const int b = *s++;
+        const int g = *s++;
+        const int r = *s++;
+        *d++ = (b>>3) | ((g&0xF8)<<2) | ((r&0xF8)<<7);
+    }
+}
+
+static inline void RENAME(rgb24to15)(const uint8_t *src, uint8_t *dst, long src_size)
+{
+    const uint8_t *s = src;
+    const uint8_t *end;
+    const uint8_t *mm_end;
+    uint16_t *d = (uint16_t *)dst;
+    end = s + src_size;
+    __asm__ volatile(PREFETCH"    %0"::"m"(*src):"memory");
+    __asm__ volatile(
+        "movq         %0, %%mm7     \n\t"
+        "movq         %1, %%mm6     \n\t"
+        ::"m"(red_15mask),"m"(green_15mask));
+    mm_end = end - 15;
+    while (s < mm_end) {
+        __asm__ volatile(
+            PREFETCH"   32%1            \n\t"
+            "movd         %1, %%mm0     \n\t"
+            "movd        3%1, %%mm3     \n\t"
+            "punpckldq   6%1, %%mm0     \n\t"
+            "punpckldq   9%1, %%mm3     \n\t"
+            "movq      %%mm0, %%mm1     \n\t"
+            "movq      %%mm0, %%mm2     \n\t"
+            "movq      %%mm3, %%mm4     \n\t"
+            "movq      %%mm3, %%mm5     \n\t"
+            "psllq        $7, %%mm0     \n\t"
+            "psllq        $7, %%mm3     \n\t"
+            "pand      %%mm7, %%mm0     \n\t"
+            "pand      %%mm7, %%mm3     \n\t"
+            "psrlq        $6, %%mm1     \n\t"
+            "psrlq        $6, %%mm4     \n\t"
+            "pand      %%mm6, %%mm1     \n\t"
+            "pand      %%mm6, %%mm4     \n\t"
+            "psrlq       $19, %%mm2     \n\t"
+            "psrlq       $19, %%mm5     \n\t"
+            "pand         %2, %%mm2     \n\t"
+            "pand         %2, %%mm5     \n\t"
+            "por       %%mm1, %%mm0     \n\t"
+            "por       %%mm4, %%mm3     \n\t"
+            "por       %%mm2, %%mm0     \n\t"
+            "por       %%mm5, %%mm3     \n\t"
+            "psllq       $16, %%mm3     \n\t"
+            "por       %%mm3, %%mm0     \n\t"
+            MOVNTQ"    %%mm0, %0        \n\t"
+            :"=m"(*d):"m"(*s),"m"(blue_15mask):"memory");
+        d += 4;
+        s += 12;
+    }
+    __asm__ volatile(SFENCE:::"memory");
+    __asm__ volatile(EMMS:::"memory");
+    while (s < end) {
+        const int r = *s++;
+        const int g = *s++;
+        const int b = *s++;
+        *d++ = (b>>3) | ((g&0xF8)<<2) | ((r&0xF8)<<7);
+    }
+}
+
+/*
+  I use less accurate approximation here by simply left-shifting the input
+  value and filling the low order bits with zeroes. This method improves PNG
+  compression but this scheme cannot reproduce white exactly, since it does
+  not generate an all-ones maximum value; the net effect is to darken the
+  image slightly.
+
+  The better method should be "left bit replication":
+
+   4 3 2 1 0
+   ---------
+   1 1 0 1 1
+
+   7 6 5 4 3  2 1 0
+   ----------------
+   1 1 0 1 1  1 1 0
+   |=======|  |===|
+       |      leftmost bits repeated to fill open bits
+       |
+   original bits
+*/
+static inline void RENAME(rgb15tobgr24)(const uint8_t *src, uint8_t *dst, long src_size)
+{
+    const uint16_t *end;
+    const uint16_t *mm_end;
+    uint8_t *d = dst;
+    const uint16_t *s = (const uint16_t*)src;
+    end = s + src_size/2;
+    __asm__ volatile(PREFETCH"    %0"::"m"(*s):"memory");
+    mm_end = end - 7;
+    while (s < mm_end) {
+        __asm__ volatile(
+            PREFETCH"    32%1           \n\t"
+            "movq          %1, %%mm0    \n\t"
+            "movq          %1, %%mm1    \n\t"
+            "movq          %1, %%mm2    \n\t"
+            "pand          %2, %%mm0    \n\t"
+            "pand          %3, %%mm1    \n\t"
+            "pand          %4, %%mm2    \n\t"
+            "psllq         $3, %%mm0    \n\t"
+            "psrlq         $2, %%mm1    \n\t"
+            "psrlq         $7, %%mm2    \n\t"
+            "movq       %%mm0, %%mm3    \n\t"
+            "movq       %%mm1, %%mm4    \n\t"
+            "movq       %%mm2, %%mm5    \n\t"
+            "punpcklwd     %5, %%mm0    \n\t"
+            "punpcklwd     %5, %%mm1    \n\t"
+            "punpcklwd     %5, %%mm2    \n\t"
+            "punpckhwd     %5, %%mm3    \n\t"
+            "punpckhwd     %5, %%mm4    \n\t"
+            "punpckhwd     %5, %%mm5    \n\t"
+            "psllq         $8, %%mm1    \n\t"
+            "psllq        $16, %%mm2    \n\t"
+            "por        %%mm1, %%mm0    \n\t"
+            "por        %%mm2, %%mm0    \n\t"
+            "psllq         $8, %%mm4    \n\t"
+            "psllq        $16, %%mm5    \n\t"
+            "por        %%mm4, %%mm3    \n\t"
+            "por        %%mm5, %%mm3    \n\t"
+
+            "movq       %%mm0, %%mm6    \n\t"
+            "movq       %%mm3, %%mm7    \n\t"
+
+            "movq         8%1, %%mm0    \n\t"
+            "movq         8%1, %%mm1    \n\t"
+            "movq         8%1, %%mm2    \n\t"
+            "pand          %2, %%mm0    \n\t"
+            "pand          %3, %%mm1    \n\t"
+            "pand          %4, %%mm2    \n\t"
+            "psllq         $3, %%mm0    \n\t"
+            "psrlq         $2, %%mm1    \n\t"
+            "psrlq         $7, %%mm2    \n\t"
+            "movq       %%mm0, %%mm3    \n\t"
+            "movq       %%mm1, %%mm4    \n\t"
+            "movq       %%mm2, %%mm5    \n\t"
+            "punpcklwd     %5, %%mm0    \n\t"
+            "punpcklwd     %5, %%mm1    \n\t"
+            "punpcklwd     %5, %%mm2    \n\t"
+            "punpckhwd     %5, %%mm3    \n\t"
+            "punpckhwd     %5, %%mm4    \n\t"
+            "punpckhwd     %5, %%mm5    \n\t"
+            "psllq         $8, %%mm1    \n\t"
+            "psllq        $16, %%mm2    \n\t"
+            "por        %%mm1, %%mm0    \n\t"
+            "por        %%mm2, %%mm0    \n\t"
+            "psllq         $8, %%mm4    \n\t"
+            "psllq        $16, %%mm5    \n\t"
+            "por        %%mm4, %%mm3    \n\t"
+            "por        %%mm5, %%mm3    \n\t"
+
+            :"=m"(*d)
+            :"m"(*s),"m"(mask15b),"m"(mask15g),"m"(mask15r), "m"(mmx_null)
+            :"memory");
+        /* borrowed 32 to 24 */
+        __asm__ volatile(
+            "movq       %%mm0, %%mm4    \n\t"
+            "movq       %%mm3, %%mm5    \n\t"
+            "movq       %%mm6, %%mm0    \n\t"
+            "movq       %%mm7, %%mm1    \n\t"
+
+            "movq       %%mm4, %%mm6    \n\t"
+            "movq       %%mm5, %%mm7    \n\t"
+            "movq       %%mm0, %%mm2    \n\t"
+            "movq       %%mm1, %%mm3    \n\t"
+
+            STORE_BGR24_MMX
+
+            :"=m"(*d)
+            :"m"(*s)
+            :"memory");
+        d += 24;
+        s += 8;
+    }
+    __asm__ volatile(SFENCE:::"memory");
+    __asm__ volatile(EMMS:::"memory");
+    while (s < end) {
+        register uint16_t bgr;
+        bgr = *s++;
+        *d++ = (bgr&0x1F)<<3;
+        *d++ = (bgr&0x3E0)>>2;
+        *d++ = (bgr&0x7C00)>>7;
+    }
+}
+
+static inline void RENAME(rgb16tobgr24)(const uint8_t *src, uint8_t *dst, long src_size)
+{
+    const uint16_t *end;
+    const uint16_t *mm_end;
+    uint8_t *d = (uint8_t *)dst;
+    const uint16_t *s = (const uint16_t *)src;
+    end = s + src_size/2;
+    __asm__ volatile(PREFETCH"    %0"::"m"(*s):"memory");
+    mm_end = end - 7;
+    while (s < mm_end) {
+        __asm__ volatile(
+            PREFETCH"    32%1           \n\t"
+            "movq          %1, %%mm0    \n\t"
+            "movq          %1, %%mm1    \n\t"
+            "movq          %1, %%mm2    \n\t"
+            "pand          %2, %%mm0    \n\t"
+            "pand          %3, %%mm1    \n\t"
+            "pand          %4, %%mm2    \n\t"
+            "psllq         $3, %%mm0    \n\t"
+            "psrlq         $3, %%mm1    \n\t"
+            "psrlq         $8, %%mm2    \n\t"
+            "movq       %%mm0, %%mm3    \n\t"
+            "movq       %%mm1, %%mm4    \n\t"
+            "movq       %%mm2, %%mm5    \n\t"
+            "punpcklwd     %5, %%mm0    \n\t"
+            "punpcklwd     %5, %%mm1    \n\t"
+            "punpcklwd     %5, %%mm2    \n\t"
+            "punpckhwd     %5, %%mm3    \n\t"
+            "punpckhwd     %5, %%mm4    \n\t"
+            "punpckhwd     %5, %%mm5    \n\t"
+            "psllq         $8, %%mm1    \n\t"
+            "psllq        $16, %%mm2    \n\t"
+            "por        %%mm1, %%mm0    \n\t"
+            "por        %%mm2, %%mm0    \n\t"
+            "psllq         $8, %%mm4    \n\t"
+            "psllq        $16, %%mm5    \n\t"
+            "por        %%mm4, %%mm3    \n\t"
+            "por        %%mm5, %%mm3    \n\t"
+
+            "movq       %%mm0, %%mm6    \n\t"
+            "movq       %%mm3, %%mm7    \n\t"
+
+            "movq         8%1, %%mm0    \n\t"
+            "movq         8%1, %%mm1    \n\t"
+            "movq         8%1, %%mm2    \n\t"
+            "pand          %2, %%mm0    \n\t"
+            "pand          %3, %%mm1    \n\t"
+            "pand          %4, %%mm2    \n\t"
+            "psllq         $3, %%mm0    \n\t"
+            "psrlq         $3, %%mm1    \n\t"
+            "psrlq         $8, %%mm2    \n\t"
+            "movq       %%mm0, %%mm3    \n\t"
+            "movq       %%mm1, %%mm4    \n\t"
+            "movq       %%mm2, %%mm5    \n\t"
+            "punpcklwd     %5, %%mm0    \n\t"
+            "punpcklwd     %5, %%mm1    \n\t"
+            "punpcklwd     %5, %%mm2    \n\t"
+            "punpckhwd     %5, %%mm3    \n\t"
+            "punpckhwd     %5, %%mm4    \n\t"
+            "punpckhwd     %5, %%mm5    \n\t"
+            "psllq         $8, %%mm1    \n\t"
+            "psllq        $16, %%mm2    \n\t"
+            "por        %%mm1, %%mm0    \n\t"
+            "por        %%mm2, %%mm0    \n\t"
+            "psllq         $8, %%mm4    \n\t"
+            "psllq        $16, %%mm5    \n\t"
+            "por        %%mm4, %%mm3    \n\t"
+            "por        %%mm5, %%mm3    \n\t"
+            :"=m"(*d)
+            :"m"(*s),"m"(mask16b),"m"(mask16g),"m"(mask16r),"m"(mmx_null)
+            :"memory");
+        /* borrowed 32 to 24 */
+        __asm__ volatile(
+            "movq       %%mm0, %%mm4    \n\t"
+            "movq       %%mm3, %%mm5    \n\t"
+            "movq       %%mm6, %%mm0    \n\t"
+            "movq       %%mm7, %%mm1    \n\t"
+
+            "movq       %%mm4, %%mm6    \n\t"
+            "movq       %%mm5, %%mm7    \n\t"
+            "movq       %%mm0, %%mm2    \n\t"
+            "movq       %%mm1, %%mm3    \n\t"
+
+            STORE_BGR24_MMX
+
+            :"=m"(*d)
+            :"m"(*s)
+            :"memory");
+        d += 24;
+        s += 8;
+    }
+    __asm__ volatile(SFENCE:::"memory");
+    __asm__ volatile(EMMS:::"memory");
+    while (s < end) {
+        register uint16_t bgr;
+        bgr = *s++;
+        *d++ = (bgr&0x1F)<<3;
+        *d++ = (bgr&0x7E0)>>3;
+        *d++ = (bgr&0xF800)>>8;
+    }
+}
+
+/*
+ * mm0 = 00 B3 00 B2 00 B1 00 B0
+ * mm1 = 00 G3 00 G2 00 G1 00 G0
+ * mm2 = 00 R3 00 R2 00 R1 00 R0
+ * mm6 = FF FF FF FF FF FF FF FF
+ * mm7 = 00 00 00 00 00 00 00 00
+ */
+#define PACK_RGB32 \
+    "packuswb   %%mm7, %%mm0    \n\t" /* 00 00 00 00 B3 B2 B1 B0 */ \
+    "packuswb   %%mm7, %%mm1    \n\t" /* 00 00 00 00 G3 G2 G1 G0 */ \
+    "packuswb   %%mm7, %%mm2    \n\t" /* 00 00 00 00 R3 R2 R1 R0 */ \
+    "punpcklbw  %%mm1, %%mm0    \n\t" /* G3 B3 G2 B2 G1 B1 G0 B0 */ \
+    "punpcklbw  %%mm6, %%mm2    \n\t" /* FF R3 FF R2 FF R1 FF R0 */ \
+    "movq       %%mm0, %%mm3    \n\t"                               \
+    "punpcklwd  %%mm2, %%mm0    \n\t" /* FF R1 G1 B1 FF R0 G0 B0 */ \
+    "punpckhwd  %%mm2, %%mm3    \n\t" /* FF R3 G3 B3 FF R2 G2 B2 */ \
+    MOVNTQ"     %%mm0,  %0      \n\t"                               \
+    MOVNTQ"     %%mm3, 8%0      \n\t"                               \
+
+static inline void RENAME(rgb15to32)(const uint8_t *src, uint8_t *dst, long src_size)
+{
+    const uint16_t *end;
+    const uint16_t *mm_end;
+    uint8_t *d = dst;
+    const uint16_t *s = (const uint16_t *)src;
+    end = s + src_size/2;
+    __asm__ volatile(PREFETCH"    %0"::"m"(*s):"memory");
+    __asm__ volatile("pxor    %%mm7,%%mm7    \n\t":::"memory");
+    __asm__ volatile("pcmpeqd %%mm6,%%mm6    \n\t":::"memory");
+    mm_end = end - 3;
+    while (s < mm_end) {
+        __asm__ volatile(
+            PREFETCH"    32%1           \n\t"
+            "movq          %1, %%mm0    \n\t"
+            "movq          %1, %%mm1    \n\t"
+            "movq          %1, %%mm2    \n\t"
+            "pand          %2, %%mm0    \n\t"
+            "pand          %3, %%mm1    \n\t"
+            "pand          %4, %%mm2    \n\t"
+            "psllq         $3, %%mm0    \n\t"
+            "psrlq         $2, %%mm1    \n\t"
+            "psrlq         $7, %%mm2    \n\t"
+            PACK_RGB32
+            :"=m"(*d)
+            :"m"(*s),"m"(mask15b),"m"(mask15g),"m"(mask15r)
+            :"memory");
+        d += 16;
+        s += 4;
+    }
+    __asm__ volatile(SFENCE:::"memory");
+    __asm__ volatile(EMMS:::"memory");
+    while (s < end) {
+        register uint16_t bgr;
+        bgr = *s++;
+        *d++ = (bgr&0x1F)<<3;
+        *d++ = (bgr&0x3E0)>>2;
+        *d++ = (bgr&0x7C00)>>7;
+        *d++ = 255;
+    }
+}
+
+static inline void RENAME(rgb16to32)(const uint8_t *src, uint8_t *dst, long src_size)
+{
+    const uint16_t *end;
+    const uint16_t *mm_end;
+    uint8_t *d = dst;
+    const uint16_t *s = (const uint16_t*)src;
+    end = s + src_size/2;
+    __asm__ volatile(PREFETCH"    %0"::"m"(*s):"memory");
+    __asm__ volatile("pxor    %%mm7,%%mm7    \n\t":::"memory");
+    __asm__ volatile("pcmpeqd %%mm6,%%mm6    \n\t":::"memory");
+    mm_end = end - 3;
+    while (s < mm_end) {
+        __asm__ volatile(
+            PREFETCH"    32%1           \n\t"
+            "movq          %1, %%mm0    \n\t"
+            "movq          %1, %%mm1    \n\t"
+            "movq          %1, %%mm2    \n\t"
+            "pand          %2, %%mm0    \n\t"
+            "pand          %3, %%mm1    \n\t"
+            "pand          %4, %%mm2    \n\t"
+            "psllq         $3, %%mm0    \n\t"
+            "psrlq         $3, %%mm1    \n\t"
+            "psrlq         $8, %%mm2    \n\t"
+            PACK_RGB32
+            :"=m"(*d)
+            :"m"(*s),"m"(mask16b),"m"(mask16g),"m"(mask16r)
+            :"memory");
+        d += 16;
+        s += 4;
+    }
+    __asm__ volatile(SFENCE:::"memory");
+    __asm__ volatile(EMMS:::"memory");
+    while (s < end) {
+        register uint16_t bgr;
+        bgr = *s++;
+        *d++ = (bgr&0x1F)<<3;
+        *d++ = (bgr&0x7E0)>>3;
+        *d++ = (bgr&0xF800)>>8;
+        *d++ = 255;
+    }
+}
+
+static inline void RENAME(shuffle_bytes_2103)(const uint8_t *src, uint8_t *dst, long src_size)
+{
+    x86_reg idx = 15 - src_size;
+    const uint8_t *s = src-idx;
+    uint8_t *d = dst-idx;
+    __asm__ volatile(
+        "test          %0, %0           \n\t"
+        "jns           2f               \n\t"
+        PREFETCH"       (%1, %0)        \n\t"
+        "movq          %3, %%mm7        \n\t"
+        "pxor          %4, %%mm7        \n\t"
+        "movq       %%mm7, %%mm6        \n\t"
+        "pxor          %5, %%mm7        \n\t"
+        ".p2align       4               \n\t"
+        "1:                             \n\t"
+        PREFETCH"     32(%1, %0)        \n\t"
+        "movq           (%1, %0), %%mm0 \n\t"
+        "movq          8(%1, %0), %%mm1 \n\t"
+# if COMPILE_TEMPLATE_MMX2
+        "pshufw      $177, %%mm0, %%mm3 \n\t"
+        "pshufw      $177, %%mm1, %%mm5 \n\t"
+        "pand       %%mm7, %%mm0        \n\t"
+        "pand       %%mm6, %%mm3        \n\t"
+        "pand       %%mm7, %%mm1        \n\t"
+        "pand       %%mm6, %%mm5        \n\t"
+        "por        %%mm3, %%mm0        \n\t"
+        "por        %%mm5, %%mm1        \n\t"
+# else
+        "movq       %%mm0, %%mm2        \n\t"
+        "movq       %%mm1, %%mm4        \n\t"
+        "pand       %%mm7, %%mm0        \n\t"
+        "pand       %%mm6, %%mm2        \n\t"
+        "pand       %%mm7, %%mm1        \n\t"
+        "pand       %%mm6, %%mm4        \n\t"
+        "movq       %%mm2, %%mm3        \n\t"
+        "movq       %%mm4, %%mm5        \n\t"
+        "pslld        $16, %%mm2        \n\t"
+        "psrld        $16, %%mm3        \n\t"
+        "pslld        $16, %%mm4        \n\t"
+        "psrld        $16, %%mm5        \n\t"
+        "por        %%mm2, %%mm0        \n\t"
+        "por        %%mm4, %%mm1        \n\t"
+        "por        %%mm3, %%mm0        \n\t"
+        "por        %%mm5, %%mm1        \n\t"
+# endif
+        MOVNTQ"     %%mm0,  (%2, %0)    \n\t"
+        MOVNTQ"     %%mm1, 8(%2, %0)    \n\t"
+        "add          $16, %0           \n\t"
+        "js            1b               \n\t"
+        SFENCE"                         \n\t"
+        EMMS"                           \n\t"
+        "2:                             \n\t"
+        : "+&r"(idx)
+        : "r" (s), "r" (d), "m" (mask32b), "m" (mask32r), "m" (mmx_one)
+        : "memory");
+    for (; idx<15; idx+=4) {
+        register int v = *(const uint32_t *)&s[idx], g = v & 0xff00ff00;
+        v &= 0xff00ff;
+        *(uint32_t *)&d[idx] = (v>>16) + g + (v<<16);
+    }
+}
+
+static inline void RENAME(rgb24tobgr24)(const uint8_t *src, uint8_t *dst, long src_size)
+{
+    unsigned i;
+    x86_reg mmx_size= 23 - src_size;
+    __asm__ volatile (
+        "test             %%"REG_a", %%"REG_a"          \n\t"
+        "jns                     2f                     \n\t"
+        "movq     "MANGLE(mask24r)", %%mm5              \n\t"
+        "movq     "MANGLE(mask24g)", %%mm6              \n\t"
+        "movq     "MANGLE(mask24b)", %%mm7              \n\t"
+        ".p2align                 4                     \n\t"
+        "1:                                             \n\t"
+        PREFETCH" 32(%1, %%"REG_a")                     \n\t"
+        "movq       (%1, %%"REG_a"), %%mm0              \n\t" // BGR BGR BG
+        "movq       (%1, %%"REG_a"), %%mm1              \n\t" // BGR BGR BG
+        "movq      2(%1, %%"REG_a"), %%mm2              \n\t" // R BGR BGR B
+        "psllq                  $16, %%mm0              \n\t" // 00 BGR BGR
+        "pand                 %%mm5, %%mm0              \n\t"
+        "pand                 %%mm6, %%mm1              \n\t"
+        "pand                 %%mm7, %%mm2              \n\t"
+        "por                  %%mm0, %%mm1              \n\t"
+        "por                  %%mm2, %%mm1              \n\t"
+        "movq      6(%1, %%"REG_a"), %%mm0              \n\t" // BGR BGR BG
+        MOVNTQ"               %%mm1,   (%2, %%"REG_a")  \n\t" // RGB RGB RG
+        "movq      8(%1, %%"REG_a"), %%mm1              \n\t" // R BGR BGR B
+        "movq     10(%1, %%"REG_a"), %%mm2              \n\t" // GR BGR BGR
+        "pand                 %%mm7, %%mm0              \n\t"
+        "pand                 %%mm5, %%mm1              \n\t"
+        "pand                 %%mm6, %%mm2              \n\t"
+        "por                  %%mm0, %%mm1              \n\t"
+        "por                  %%mm2, %%mm1              \n\t"
+        "movq     14(%1, %%"REG_a"), %%mm0              \n\t" // R BGR BGR B
+        MOVNTQ"               %%mm1,  8(%2, %%"REG_a")  \n\t" // B RGB RGB R
+        "movq     16(%1, %%"REG_a"), %%mm1              \n\t" // GR BGR BGR
+        "movq     18(%1, %%"REG_a"), %%mm2              \n\t" // BGR BGR BG
+        "pand                 %%mm6, %%mm0              \n\t"
+        "pand                 %%mm7, %%mm1              \n\t"
+        "pand                 %%mm5, %%mm2              \n\t"
+        "por                  %%mm0, %%mm1              \n\t"
+        "por                  %%mm2, %%mm1              \n\t"
+        MOVNTQ"               %%mm1, 16(%2, %%"REG_a")  \n\t"
+        "add                    $24, %%"REG_a"          \n\t"
+        " js                     1b                     \n\t"
+        "2:                                             \n\t"
+        : "+a" (mmx_size)
+        : "r" (src-mmx_size), "r"(dst-mmx_size)
+    );
+
+    __asm__ volatile(SFENCE:::"memory");
+    __asm__ volatile(EMMS:::"memory");
+
+    if (mmx_size==23) return; //finished, was multiple of 8
+
+    src+= src_size;
+    dst+= src_size;
+    src_size= 23-mmx_size;
+    src-= src_size;
+    dst-= src_size;
+    for (i=0; i<src_size; i+=3) {
+        register uint8_t x;
+        x          = src[i + 2];
+        dst[i + 1] = src[i + 1];
+        dst[i + 2] = src[i + 0];
+        dst[i + 0] = x;
+    }
+}
+
+static inline void RENAME(yuvPlanartoyuy2)(const uint8_t *ysrc, const uint8_t *usrc, const uint8_t *vsrc, uint8_t *dst,
+                                           long width, long height,
+                                           long lumStride, long chromStride, long dstStride, long vertLumPerChroma)
+{
+    long y;
+    const x86_reg chromWidth= width>>1;
+    for (y=0; y<height; y++) {
+        //FIXME handle 2 lines at once (fewer prefetches, reuse some chroma, but very likely memory-limited anyway)
+        __asm__ volatile(
+            "xor                 %%"REG_a", %%"REG_a"   \n\t"
+            ".p2align                    4              \n\t"
+            "1:                                         \n\t"
+            PREFETCH"    32(%1, %%"REG_a", 2)           \n\t"
+            PREFETCH"    32(%2, %%"REG_a")              \n\t"
+            PREFETCH"    32(%3, %%"REG_a")              \n\t"
+            "movq          (%2, %%"REG_a"), %%mm0       \n\t" // U(0)
+            "movq                    %%mm0, %%mm2       \n\t" // U(0)
+            "movq          (%3, %%"REG_a"), %%mm1       \n\t" // V(0)
+            "punpcklbw               %%mm1, %%mm0       \n\t" // UVUV UVUV(0)
+            "punpckhbw               %%mm1, %%mm2       \n\t" // UVUV UVUV(8)
+
+            "movq        (%1, %%"REG_a",2), %%mm3       \n\t" // Y(0)
+            "movq       8(%1, %%"REG_a",2), %%mm5       \n\t" // Y(8)
+            "movq                    %%mm3, %%mm4       \n\t" // Y(0)
+            "movq                    %%mm5, %%mm6       \n\t" // Y(8)
+            "punpcklbw               %%mm0, %%mm3       \n\t" // YUYV YUYV(0)
+            "punpckhbw               %%mm0, %%mm4       \n\t" // YUYV YUYV(4)
+            "punpcklbw               %%mm2, %%mm5       \n\t" // YUYV YUYV(8)
+            "punpckhbw               %%mm2, %%mm6       \n\t" // YUYV YUYV(12)
+
+            MOVNTQ"                  %%mm3,   (%0, %%"REG_a", 4)    \n\t"
+            MOVNTQ"                  %%mm4,  8(%0, %%"REG_a", 4)    \n\t"
+            MOVNTQ"                  %%mm5, 16(%0, %%"REG_a", 4)    \n\t"
+            MOVNTQ"                  %%mm6, 24(%0, %%"REG_a", 4)    \n\t"
+
+            "add                        $8, %%"REG_a"   \n\t"
+            "cmp                        %4, %%"REG_a"   \n\t"
+            " jb                        1b              \n\t"
+            ::"r"(dst), "r"(ysrc), "r"(usrc), "r"(vsrc), "g" (chromWidth)
+            : "%"REG_a
+        );
+        if ((y&(vertLumPerChroma-1)) == vertLumPerChroma-1) {
+            usrc += chromStride;
+            vsrc += chromStride;
+        }
+        ysrc += lumStride;
+        dst  += dstStride;
+    }
+    __asm__(EMMS"       \n\t"
+            SFENCE"     \n\t"
+            :::"memory");
+}
+
+/**
+ * Height should be a multiple of 2 and width should be a multiple of 16.
+ * (If this is a problem for anyone then tell me, and I will fix it.)
+ */
+static inline void RENAME(yv12toyuy2)(const uint8_t *ysrc, const uint8_t *usrc, const uint8_t *vsrc, uint8_t *dst,
+                                      long width, long height,
+                                      long lumStride, long chromStride, long dstStride)
+{
+    //FIXME interpolate chroma
+    RENAME(yuvPlanartoyuy2)(ysrc, usrc, vsrc, dst, width, height, lumStride, chromStride, dstStride, 2);
+}
+
+static inline void RENAME(yuvPlanartouyvy)(const uint8_t *ysrc, const uint8_t *usrc, const uint8_t *vsrc, uint8_t *dst,
+                                           long width, long height,
+                                           long lumStride, long chromStride, long dstStride, long vertLumPerChroma)
+{
+    long y;
+    const x86_reg chromWidth= width>>1;
+    for (y=0; y<height; y++) {
+        //FIXME handle 2 lines at once (fewer prefetches, reuse some chroma, but very likely memory-limited anyway)
+        __asm__ volatile(
+            "xor                %%"REG_a", %%"REG_a"    \n\t"
+            ".p2align                   4               \n\t"
+            "1:                                         \n\t"
+            PREFETCH"   32(%1, %%"REG_a", 2)            \n\t"
+            PREFETCH"   32(%2, %%"REG_a")               \n\t"
+            PREFETCH"   32(%3, %%"REG_a")               \n\t"
+            "movq         (%2, %%"REG_a"), %%mm0        \n\t" // U(0)
+            "movq                   %%mm0, %%mm2        \n\t" // U(0)
+            "movq         (%3, %%"REG_a"), %%mm1        \n\t" // V(0)
+            "punpcklbw              %%mm1, %%mm0        \n\t" // UVUV UVUV(0)
+            "punpckhbw              %%mm1, %%mm2        \n\t" // UVUV UVUV(8)
+
+            "movq       (%1, %%"REG_a",2), %%mm3        \n\t" // Y(0)
+            "movq      8(%1, %%"REG_a",2), %%mm5        \n\t" // Y(8)
+            "movq                   %%mm0, %%mm4        \n\t" // Y(0)
+            "movq                   %%mm2, %%mm6        \n\t" // Y(8)
+            "punpcklbw              %%mm3, %%mm0        \n\t" // YUYV YUYV(0)
+            "punpckhbw              %%mm3, %%mm4        \n\t" // YUYV YUYV(4)
+            "punpcklbw              %%mm5, %%mm2        \n\t" // YUYV YUYV(8)
+            "punpckhbw              %%mm5, %%mm6        \n\t" // YUYV YUYV(12)
+
+            MOVNTQ"                 %%mm0,   (%0, %%"REG_a", 4)     \n\t"
+            MOVNTQ"                 %%mm4,  8(%0, %%"REG_a", 4)     \n\t"
+            MOVNTQ"                 %%mm2, 16(%0, %%"REG_a", 4)     \n\t"
+            MOVNTQ"                 %%mm6, 24(%0, %%"REG_a", 4)     \n\t"
+
+            "add                       $8, %%"REG_a"    \n\t"
+            "cmp                       %4, %%"REG_a"    \n\t"
+            " jb                       1b               \n\t"
+            ::"r"(dst), "r"(ysrc), "r"(usrc), "r"(vsrc), "g" (chromWidth)
+            : "%"REG_a
+        );
+        if ((y&(vertLumPerChroma-1)) == vertLumPerChroma-1) {
+            usrc += chromStride;
+            vsrc += chromStride;
+        }
+        ysrc += lumStride;
+        dst += dstStride;
+    }
+    __asm__(EMMS"       \n\t"
+            SFENCE"     \n\t"
+            :::"memory");
+}
+
+/**
+ * Height should be a multiple of 2 and width should be a multiple of 16
+ * (If this is a problem for anyone then tell me, and I will fix it.)
+ */
+static inline void RENAME(yv12touyvy)(const uint8_t *ysrc, const uint8_t *usrc, const uint8_t *vsrc, uint8_t *dst,
+                                      long width, long height,
+                                      long lumStride, long chromStride, long dstStride)
+{
+    //FIXME interpolate chroma
+    RENAME(yuvPlanartouyvy)(ysrc, usrc, vsrc, dst, width, height, lumStride, chromStride, dstStride, 2);
+}
+
+/**
+ * Width should be a multiple of 16.
+ */
+static inline void RENAME(yuv422ptouyvy)(const uint8_t *ysrc, const uint8_t *usrc, const uint8_t *vsrc, uint8_t *dst,
+                                         long width, long height,
+                                         long lumStride, long chromStride, long dstStride)
+{
+    RENAME(yuvPlanartouyvy)(ysrc, usrc, vsrc, dst, width, height, lumStride, chromStride, dstStride, 1);
+}
+
+/**
+ * Width should be a multiple of 16.
+ */
+static inline void RENAME(yuv422ptoyuy2)(const uint8_t *ysrc, const uint8_t *usrc, const uint8_t *vsrc, uint8_t *dst,
+                                         long width, long height,
+                                         long lumStride, long chromStride, long dstStride)
+{
+    RENAME(yuvPlanartoyuy2)(ysrc, usrc, vsrc, dst, width, height, lumStride, chromStride, dstStride, 1);
+}
+
+/**
+ * Height should be a multiple of 2 and width should be a multiple of 16.
+ * (If this is a problem for anyone then tell me, and I will fix it.)
+ */
+static inline void RENAME(yuy2toyv12)(const uint8_t *src, uint8_t *ydst, uint8_t *udst, uint8_t *vdst,
+                                      long width, long height,
+                                      long lumStride, long chromStride, long srcStride)
+{
+    long y;
+    const x86_reg chromWidth= width>>1;
+    for (y=0; y<height; y+=2) {
+        __asm__ volatile(
+            "xor                 %%"REG_a", %%"REG_a"   \n\t"
+            "pcmpeqw                 %%mm7, %%mm7       \n\t"
+            "psrlw                      $8, %%mm7       \n\t" // FF,00,FF,00...
+            ".p2align                    4              \n\t"
+            "1:                \n\t"
+            PREFETCH" 64(%0, %%"REG_a", 4)              \n\t"
+            "movq       (%0, %%"REG_a", 4), %%mm0       \n\t" // YUYV YUYV(0)
+            "movq      8(%0, %%"REG_a", 4), %%mm1       \n\t" // YUYV YUYV(4)
+            "movq                    %%mm0, %%mm2       \n\t" // YUYV YUYV(0)
+            "movq                    %%mm1, %%mm3       \n\t" // YUYV YUYV(4)
+            "psrlw                      $8, %%mm0       \n\t" // U0V0 U0V0(0)
+            "psrlw                      $8, %%mm1       \n\t" // U0V0 U0V0(4)
+            "pand                    %%mm7, %%mm2       \n\t" // Y0Y0 Y0Y0(0)
+            "pand                    %%mm7, %%mm3       \n\t" // Y0Y0 Y0Y0(4)
+            "packuswb                %%mm1, %%mm0       \n\t" // UVUV UVUV(0)
+            "packuswb                %%mm3, %%mm2       \n\t" // YYYY YYYY(0)
+
+            MOVNTQ"                  %%mm2, (%1, %%"REG_a", 2)  \n\t"
+
+            "movq     16(%0, %%"REG_a", 4), %%mm1       \n\t" // YUYV YUYV(8)
+            "movq     24(%0, %%"REG_a", 4), %%mm2       \n\t" // YUYV YUYV(12)
+            "movq                    %%mm1, %%mm3       \n\t" // YUYV YUYV(8)
+            "movq                    %%mm2, %%mm4       \n\t" // YUYV YUYV(12)
+            "psrlw                      $8, %%mm1       \n\t" // U0V0 U0V0(8)
+            "psrlw                      $8, %%mm2       \n\t" // U0V0 U0V0(12)
+            "pand                    %%mm7, %%mm3       \n\t" // Y0Y0 Y0Y0(8)
+            "pand                    %%mm7, %%mm4       \n\t" // Y0Y0 Y0Y0(12)
+            "packuswb                %%mm2, %%mm1       \n\t" // UVUV UVUV(8)
+            "packuswb                %%mm4, %%mm3       \n\t" // YYYY YYYY(8)
+
+            MOVNTQ"                  %%mm3, 8(%1, %%"REG_a", 2) \n\t"
+
+            "movq                    %%mm0, %%mm2       \n\t" // UVUV UVUV(0)
+            "movq                    %%mm1, %%mm3       \n\t" // UVUV UVUV(8)
+            "psrlw                      $8, %%mm0       \n\t" // V0V0 V0V0(0)
+            "psrlw                      $8, %%mm1       \n\t" // V0V0 V0V0(8)
+            "pand                    %%mm7, %%mm2       \n\t" // U0U0 U0U0(0)
+            "pand                    %%mm7, %%mm3       \n\t" // U0U0 U0U0(8)
+            "packuswb                %%mm1, %%mm0       \n\t" // VVVV VVVV(0)
+            "packuswb                %%mm3, %%mm2       \n\t" // UUUU UUUU(0)
+
+            MOVNTQ"                  %%mm0, (%3, %%"REG_a")     \n\t"
+            MOVNTQ"                  %%mm2, (%2, %%"REG_a")     \n\t"
+
+            "add                        $8, %%"REG_a"   \n\t"
+            "cmp                        %4, %%"REG_a"   \n\t"
+            " jb                        1b              \n\t"
+            ::"r"(src), "r"(ydst), "r"(udst), "r"(vdst), "g" (chromWidth)
+            : "memory", "%"REG_a
+        );
+
+        ydst += lumStride;
+        src  += srcStride;
+
+        __asm__ volatile(
+            "xor                 %%"REG_a", %%"REG_a"   \n\t"
+            ".p2align                    4              \n\t"
+            "1:                                         \n\t"
+            PREFETCH" 64(%0, %%"REG_a", 4)              \n\t"
+            "movq       (%0, %%"REG_a", 4), %%mm0       \n\t" // YUYV YUYV(0)
+            "movq      8(%0, %%"REG_a", 4), %%mm1       \n\t" // YUYV YUYV(4)
+            "movq     16(%0, %%"REG_a", 4), %%mm2       \n\t" // YUYV YUYV(8)
+            "movq     24(%0, %%"REG_a", 4), %%mm3       \n\t" // YUYV YUYV(12)
+            "pand                    %%mm7, %%mm0       \n\t" // Y0Y0 Y0Y0(0)
+            "pand                    %%mm7, %%mm1       \n\t" // Y0Y0 Y0Y0(4)
+            "pand                    %%mm7, %%mm2       \n\t" // Y0Y0 Y0Y0(8)
+            "pand                    %%mm7, %%mm3       \n\t" // Y0Y0 Y0Y0(12)
+            "packuswb                %%mm1, %%mm0       \n\t" // YYYY YYYY(0)
+            "packuswb                %%mm3, %%mm2       \n\t" // YYYY YYYY(8)
+
+            MOVNTQ"                  %%mm0,  (%1, %%"REG_a", 2) \n\t"
+            MOVNTQ"                  %%mm2, 8(%1, %%"REG_a", 2) \n\t"
+
+            "add                        $8, %%"REG_a"   \n\t"
+            "cmp                        %4, %%"REG_a"   \n\t"
+            " jb                        1b              \n\t"
+
+            ::"r"(src), "r"(ydst), "r"(udst), "r"(vdst), "g" (chromWidth)
+            : "memory", "%"REG_a
+        );
+        udst += chromStride;
+        vdst += chromStride;
+        ydst += lumStride;
+        src  += srcStride;
+    }
+    __asm__ volatile(EMMS"       \n\t"
+                     SFENCE"     \n\t"
+                     :::"memory");
+}
+
+static inline void RENAME(planar2x)(const uint8_t *src, uint8_t *dst, long srcWidth, long srcHeight, long srcStride, long dstStride)
+{
+    long x,y;
+
+    dst[0]= src[0];
+
+    // first line
+    for (x=0; x<srcWidth-1; x++) {
+        dst[2*x+1]= (3*src[x] +   src[x+1])>>2;
+        dst[2*x+2]= (  src[x] + 3*src[x+1])>>2;
+    }
+    dst[2*srcWidth-1]= src[srcWidth-1];
+
+    dst+= dstStride;
+
+    for (y=1; y<srcHeight; y++) {
+#if COMPILE_TEMPLATE_MMX2 || COMPILE_TEMPLATE_AMD3DNOW
+        const x86_reg mmxSize= srcWidth&~15;
+        __asm__ volatile(
+            "mov           %4, %%"REG_a"            \n\t"
+            "movq        "MANGLE(mmx_ff)", %%mm0    \n\t"
+            "movq         (%0, %%"REG_a"), %%mm4    \n\t"
+            "movq                   %%mm4, %%mm2    \n\t"
+            "psllq                     $8, %%mm4    \n\t"
+            "pand                   %%mm0, %%mm2    \n\t"
+            "por                    %%mm2, %%mm4    \n\t"
+            "movq         (%1, %%"REG_a"), %%mm5    \n\t"
+            "movq                   %%mm5, %%mm3    \n\t"
+            "psllq                     $8, %%mm5    \n\t"
+            "pand                   %%mm0, %%mm3    \n\t"
+            "por                    %%mm3, %%mm5    \n\t"
+            "1:                                     \n\t"
+            "movq         (%0, %%"REG_a"), %%mm0    \n\t"
+            "movq         (%1, %%"REG_a"), %%mm1    \n\t"
+            "movq        1(%0, %%"REG_a"), %%mm2    \n\t"
+            "movq        1(%1, %%"REG_a"), %%mm3    \n\t"
+            PAVGB"                  %%mm0, %%mm5    \n\t"
+            PAVGB"                  %%mm0, %%mm3    \n\t"
+            PAVGB"                  %%mm0, %%mm5    \n\t"
+            PAVGB"                  %%mm0, %%mm3    \n\t"
+            PAVGB"                  %%mm1, %%mm4    \n\t"
+            PAVGB"                  %%mm1, %%mm2    \n\t"
+            PAVGB"                  %%mm1, %%mm4    \n\t"
+            PAVGB"                  %%mm1, %%mm2    \n\t"
+            "movq                   %%mm5, %%mm7    \n\t"
+            "movq                   %%mm4, %%mm6    \n\t"
+            "punpcklbw              %%mm3, %%mm5    \n\t"
+            "punpckhbw              %%mm3, %%mm7    \n\t"
+            "punpcklbw              %%mm2, %%mm4    \n\t"
+            "punpckhbw              %%mm2, %%mm6    \n\t"
+#if 1
+            MOVNTQ"                 %%mm5,  (%2, %%"REG_a", 2)  \n\t"
+            MOVNTQ"                 %%mm7, 8(%2, %%"REG_a", 2)  \n\t"
+            MOVNTQ"                 %%mm4,  (%3, %%"REG_a", 2)  \n\t"
+            MOVNTQ"                 %%mm6, 8(%3, %%"REG_a", 2)  \n\t"
+#else
+            "movq                   %%mm5,  (%2, %%"REG_a", 2)  \n\t"
+            "movq                   %%mm7, 8(%2, %%"REG_a", 2)  \n\t"
+            "movq                   %%mm4,  (%3, %%"REG_a", 2)  \n\t"
+            "movq                   %%mm6, 8(%3, %%"REG_a", 2)  \n\t"
+#endif
+            "add                       $8, %%"REG_a"            \n\t"
+            "movq       -1(%0, %%"REG_a"), %%mm4    \n\t"
+            "movq       -1(%1, %%"REG_a"), %%mm5    \n\t"
+            " js                       1b                       \n\t"
+            :: "r" (src + mmxSize  ), "r" (src + srcStride + mmxSize  ),
+               "r" (dst + mmxSize*2), "r" (dst + dstStride + mmxSize*2),
+               "g" (-mmxSize)
+            : "%"REG_a
+        );
+#else
+        const x86_reg mmxSize=1;
+
+        dst[0        ]= (3*src[0] +   src[srcStride])>>2;
+        dst[dstStride]= (  src[0] + 3*src[srcStride])>>2;
+#endif
+
+        for (x=mmxSize-1; x<srcWidth-1; x++) {
+            dst[2*x          +1]= (3*src[x+0] +   src[x+srcStride+1])>>2;
+            dst[2*x+dstStride+2]= (  src[x+0] + 3*src[x+srcStride+1])>>2;
+            dst[2*x+dstStride+1]= (  src[x+1] + 3*src[x+srcStride  ])>>2;
+            dst[2*x          +2]= (3*src[x+1] +   src[x+srcStride  ])>>2;
+        }
+        dst[srcWidth*2 -1            ]= (3*src[srcWidth-1] +   src[srcWidth-1 + srcStride])>>2;
+        dst[srcWidth*2 -1 + dstStride]= (  src[srcWidth-1] + 3*src[srcWidth-1 + srcStride])>>2;
+
+        dst+=dstStride*2;
+        src+=srcStride;
+    }
+
+    // last line
+#if 1
+    dst[0]= src[0];
+
+    for (x=0; x<srcWidth-1; x++) {
+        dst[2*x+1]= (3*src[x] +   src[x+1])>>2;
+        dst[2*x+2]= (  src[x] + 3*src[x+1])>>2;
+    }
+    dst[2*srcWidth-1]= src[srcWidth-1];
+#else
+    for (x=0; x<srcWidth; x++) {
+        dst[2*x+0]=
+        dst[2*x+1]= src[x];
+    }
+#endif
+
+    __asm__ volatile(EMMS"       \n\t"
+                     SFENCE"     \n\t"
+                     :::"memory");
+}
+
+/**
+ * Height should be a multiple of 2 and width should be a multiple of 16.
+ * (If this is a problem for anyone then tell me, and I will fix it.)
+ * Chrominance data is only taken from every second line, others are ignored.
+ * FIXME: Write HQ version.
+ */
+static inline void RENAME(uyvytoyv12)(const uint8_t *src, uint8_t *ydst, uint8_t *udst, uint8_t *vdst,
+                                      long width, long height,
+                                      long lumStride, long chromStride, long srcStride)
+{
+    long y;
+    const x86_reg chromWidth= width>>1;
+    for (y=0; y<height; y+=2) {
+        __asm__ volatile(
+            "xor                 %%"REG_a", %%"REG_a"   \n\t"
+            "pcmpeqw             %%mm7, %%mm7   \n\t"
+            "psrlw                  $8, %%mm7   \n\t" // FF,00,FF,00...
+            ".p2align                4          \n\t"
+            "1:                                 \n\t"
+            PREFETCH" 64(%0, %%"REG_a", 4)          \n\t"
+            "movq       (%0, %%"REG_a", 4), %%mm0   \n\t" // UYVY UYVY(0)
+            "movq      8(%0, %%"REG_a", 4), %%mm1   \n\t" // UYVY UYVY(4)
+            "movq                %%mm0, %%mm2   \n\t" // UYVY UYVY(0)
+            "movq                %%mm1, %%mm3   \n\t" // UYVY UYVY(4)
+            "pand                %%mm7, %%mm0   \n\t" // U0V0 U0V0(0)
+            "pand                %%mm7, %%mm1   \n\t" // U0V0 U0V0(4)
+            "psrlw                  $8, %%mm2   \n\t" // Y0Y0 Y0Y0(0)
+            "psrlw                  $8, %%mm3   \n\t" // Y0Y0 Y0Y0(4)
+            "packuswb            %%mm1, %%mm0   \n\t" // UVUV UVUV(0)
+            "packuswb            %%mm3, %%mm2   \n\t" // YYYY YYYY(0)
+
+            MOVNTQ"              %%mm2,  (%1, %%"REG_a", 2) \n\t"
+
+            "movq     16(%0, %%"REG_a", 4), %%mm1   \n\t" // UYVY UYVY(8)
+            "movq     24(%0, %%"REG_a", 4), %%mm2   \n\t" // UYVY UYVY(12)
+            "movq                %%mm1, %%mm3   \n\t" // UYVY UYVY(8)
+            "movq                %%mm2, %%mm4   \n\t" // UYVY UYVY(12)
+            "pand                %%mm7, %%mm1   \n\t" // U0V0 U0V0(8)
+            "pand                %%mm7, %%mm2   \n\t" // U0V0 U0V0(12)
+            "psrlw                  $8, %%mm3   \n\t" // Y0Y0 Y0Y0(8)
+            "psrlw                  $8, %%mm4   \n\t" // Y0Y0 Y0Y0(12)
+            "packuswb            %%mm2, %%mm1   \n\t" // UVUV UVUV(8)
+            "packuswb            %%mm4, %%mm3   \n\t" // YYYY YYYY(8)
+
+            MOVNTQ"              %%mm3, 8(%1, %%"REG_a", 2) \n\t"
+
+            "movq                %%mm0, %%mm2   \n\t" // UVUV UVUV(0)
+            "movq                %%mm1, %%mm3   \n\t" // UVUV UVUV(8)
+            "psrlw                  $8, %%mm0   \n\t" // V0V0 V0V0(0)
+            "psrlw                  $8, %%mm1   \n\t" // V0V0 V0V0(8)
+            "pand                %%mm7, %%mm2   \n\t" // U0U0 U0U0(0)
+            "pand                %%mm7, %%mm3   \n\t" // U0U0 U0U0(8)
+            "packuswb            %%mm1, %%mm0   \n\t" // VVVV VVVV(0)
+            "packuswb            %%mm3, %%mm2   \n\t" // UUUU UUUU(0)
+
+            MOVNTQ"              %%mm0, (%3, %%"REG_a") \n\t"
+            MOVNTQ"              %%mm2, (%2, %%"REG_a") \n\t"
+
+            "add                    $8, %%"REG_a"   \n\t"
+            "cmp                    %4, %%"REG_a"   \n\t"
+            " jb                    1b          \n\t"
+            ::"r"(src), "r"(ydst), "r"(udst), "r"(vdst), "g" (chromWidth)
+            : "memory", "%"REG_a
+        );
+
+        ydst += lumStride;
+        src  += srcStride;
+
+        __asm__ volatile(
+            "xor                 %%"REG_a", %%"REG_a"   \n\t"
+            ".p2align                    4              \n\t"
+            "1:                                 \n\t"
+            PREFETCH" 64(%0, %%"REG_a", 4)          \n\t"
+            "movq       (%0, %%"REG_a", 4), %%mm0   \n\t" // YUYV YUYV(0)
+            "movq      8(%0, %%"REG_a", 4), %%mm1   \n\t" // YUYV YUYV(4)
+            "movq     16(%0, %%"REG_a", 4), %%mm2   \n\t" // YUYV YUYV(8)
+            "movq     24(%0, %%"REG_a", 4), %%mm3   \n\t" // YUYV YUYV(12)
+            "psrlw                  $8, %%mm0   \n\t" // Y0Y0 Y0Y0(0)
+            "psrlw                  $8, %%mm1   \n\t" // Y0Y0 Y0Y0(4)
+            "psrlw                  $8, %%mm2   \n\t" // Y0Y0 Y0Y0(8)
+            "psrlw                  $8, %%mm3   \n\t" // Y0Y0 Y0Y0(12)
+            "packuswb            %%mm1, %%mm0   \n\t" // YYYY YYYY(0)
+            "packuswb            %%mm3, %%mm2   \n\t" // YYYY YYYY(8)
+
+            MOVNTQ"              %%mm0,  (%1, %%"REG_a", 2) \n\t"
+            MOVNTQ"              %%mm2, 8(%1, %%"REG_a", 2) \n\t"
+
+            "add                    $8, %%"REG_a"   \n\t"
+            "cmp                    %4, %%"REG_a"   \n\t"
+            " jb                    1b          \n\t"
+
+            ::"r"(src), "r"(ydst), "r"(udst), "r"(vdst), "g" (chromWidth)
+            : "memory", "%"REG_a
+        );
+        udst += chromStride;
+        vdst += chromStride;
+        ydst += lumStride;
+        src  += srcStride;
+    }
+    __asm__ volatile(EMMS"       \n\t"
+                     SFENCE"     \n\t"
+                     :::"memory");
+}
+
+/**
+ * Height should be a multiple of 2 and width should be a multiple of 2.
+ * (If this is a problem for anyone then tell me, and I will fix it.)
+ * Chrominance data is only taken from every second line,
+ * others are ignored in the C version.
+ * FIXME: Write HQ version.
+ */
+static inline void RENAME(rgb24toyv12)(const uint8_t *src, uint8_t *ydst, uint8_t *udst, uint8_t *vdst,
+                                       long width, long height,
+                                       long lumStride, long chromStride, long srcStride)
+{
+    long y;
+    const x86_reg chromWidth= width>>1;
+    for (y=0; y<height-2; y+=2) {
+        long i;
+        for (i=0; i<2; i++) {
+            __asm__ volatile(
+                "mov                        %2, %%"REG_a"   \n\t"
+                "movq  "MANGLE(ff_bgr2YCoeff)", %%mm6       \n\t"
+                "movq       "MANGLE(ff_w1111)", %%mm5       \n\t"
+                "pxor                    %%mm7, %%mm7       \n\t"
+                "lea (%%"REG_a", %%"REG_a", 2), %%"REG_d"   \n\t"
+                ".p2align                    4              \n\t"
+                "1:                                         \n\t"
+                PREFETCH"    64(%0, %%"REG_d")              \n\t"
+                "movd          (%0, %%"REG_d"), %%mm0       \n\t"
+                "movd         3(%0, %%"REG_d"), %%mm1       \n\t"
+                "punpcklbw               %%mm7, %%mm0       \n\t"
+                "punpcklbw               %%mm7, %%mm1       \n\t"
+                "movd         6(%0, %%"REG_d"), %%mm2       \n\t"
+                "movd         9(%0, %%"REG_d"), %%mm3       \n\t"
+                "punpcklbw               %%mm7, %%mm2       \n\t"
+                "punpcklbw               %%mm7, %%mm3       \n\t"
+                "pmaddwd                 %%mm6, %%mm0       \n\t"
+                "pmaddwd                 %%mm6, %%mm1       \n\t"
+                "pmaddwd                 %%mm6, %%mm2       \n\t"
+                "pmaddwd                 %%mm6, %%mm3       \n\t"
+#ifndef FAST_BGR2YV12
+                "psrad                      $8, %%mm0       \n\t"
+                "psrad                      $8, %%mm1       \n\t"
+                "psrad                      $8, %%mm2       \n\t"
+                "psrad                      $8, %%mm3       \n\t"
+#endif
+                "packssdw                %%mm1, %%mm0       \n\t"
+                "packssdw                %%mm3, %%mm2       \n\t"
+                "pmaddwd                 %%mm5, %%mm0       \n\t"
+                "pmaddwd                 %%mm5, %%mm2       \n\t"
+                "packssdw                %%mm2, %%mm0       \n\t"
+                "psraw                      $7, %%mm0       \n\t"
+
+                "movd        12(%0, %%"REG_d"), %%mm4       \n\t"
+                "movd        15(%0, %%"REG_d"), %%mm1       \n\t"
+                "punpcklbw               %%mm7, %%mm4       \n\t"
+                "punpcklbw               %%mm7, %%mm1       \n\t"
+                "movd        18(%0, %%"REG_d"), %%mm2       \n\t"
+                "movd        21(%0, %%"REG_d"), %%mm3       \n\t"
+                "punpcklbw               %%mm7, %%mm2       \n\t"
+                "punpcklbw               %%mm7, %%mm3       \n\t"
+                "pmaddwd                 %%mm6, %%mm4       \n\t"
+                "pmaddwd                 %%mm6, %%mm1       \n\t"
+                "pmaddwd                 %%mm6, %%mm2       \n\t"
+                "pmaddwd                 %%mm6, %%mm3       \n\t"
+#ifndef FAST_BGR2YV12
+                "psrad                      $8, %%mm4       \n\t"
+                "psrad                      $8, %%mm1       \n\t"
+                "psrad                      $8, %%mm2       \n\t"
+                "psrad                      $8, %%mm3       \n\t"
+#endif
+                "packssdw                %%mm1, %%mm4       \n\t"
+                "packssdw                %%mm3, %%mm2       \n\t"
+                "pmaddwd                 %%mm5, %%mm4       \n\t"
+                "pmaddwd                 %%mm5, %%mm2       \n\t"
+                "add                       $24, %%"REG_d"   \n\t"
+                "packssdw                %%mm2, %%mm4       \n\t"
+                "psraw                      $7, %%mm4       \n\t"
+
+                "packuswb                %%mm4, %%mm0       \n\t"
+                "paddusb "MANGLE(ff_bgr2YOffset)", %%mm0    \n\t"
+
+                MOVNTQ"                  %%mm0, (%1, %%"REG_a") \n\t"
+                "add                        $8,      %%"REG_a"  \n\t"
+                " js                        1b                  \n\t"
+                : : "r" (src+width*3), "r" (ydst+width), "g" ((x86_reg)-width)
+                : "%"REG_a, "%"REG_d
+            );
+            ydst += lumStride;
+            src  += srcStride;
+        }
+        src -= srcStride*2;
+        __asm__ volatile(
+            "mov                        %4, %%"REG_a"   \n\t"
+            "movq       "MANGLE(ff_w1111)", %%mm5       \n\t"
+            "movq  "MANGLE(ff_bgr2UCoeff)", %%mm6       \n\t"
+            "pxor                    %%mm7, %%mm7       \n\t"
+            "lea (%%"REG_a", %%"REG_a", 2), %%"REG_d"   \n\t"
+            "add                 %%"REG_d", %%"REG_d"   \n\t"
+            ".p2align                    4              \n\t"
+            "1:                                         \n\t"
+            PREFETCH"    64(%0, %%"REG_d")              \n\t"
+            PREFETCH"    64(%1, %%"REG_d")              \n\t"
+#if COMPILE_TEMPLATE_MMX2 || COMPILE_TEMPLATE_AMD3DNOW
+            "movq          (%0, %%"REG_d"), %%mm0       \n\t"
+            "movq          (%1, %%"REG_d"), %%mm1       \n\t"
+            "movq         6(%0, %%"REG_d"), %%mm2       \n\t"
+            "movq         6(%1, %%"REG_d"), %%mm3       \n\t"
+            PAVGB"                   %%mm1, %%mm0       \n\t"
+            PAVGB"                   %%mm3, %%mm2       \n\t"
+            "movq                    %%mm0, %%mm1       \n\t"
+            "movq                    %%mm2, %%mm3       \n\t"
+            "psrlq                     $24, %%mm0       \n\t"
+            "psrlq                     $24, %%mm2       \n\t"
+            PAVGB"                   %%mm1, %%mm0       \n\t"
+            PAVGB"                   %%mm3, %%mm2       \n\t"
+            "punpcklbw               %%mm7, %%mm0       \n\t"
+            "punpcklbw               %%mm7, %%mm2       \n\t"
+#else
+            "movd          (%0, %%"REG_d"), %%mm0       \n\t"
+            "movd          (%1, %%"REG_d"), %%mm1       \n\t"
+            "movd         3(%0, %%"REG_d"), %%mm2       \n\t"
+            "movd         3(%1, %%"REG_d"), %%mm3       \n\t"
+            "punpcklbw               %%mm7, %%mm0       \n\t"
+            "punpcklbw               %%mm7, %%mm1       \n\t"
+            "punpcklbw               %%mm7, %%mm2       \n\t"
+            "punpcklbw               %%mm7, %%mm3       \n\t"
+            "paddw                   %%mm1, %%mm0       \n\t"
+            "paddw                   %%mm3, %%mm2       \n\t"
+            "paddw                   %%mm2, %%mm0       \n\t"
+            "movd         6(%0, %%"REG_d"), %%mm4       \n\t"
+            "movd         6(%1, %%"REG_d"), %%mm1       \n\t"
+            "movd         9(%0, %%"REG_d"), %%mm2       \n\t"
+            "movd         9(%1, %%"REG_d"), %%mm3       \n\t"
+            "punpcklbw               %%mm7, %%mm4       \n\t"
+            "punpcklbw               %%mm7, %%mm1       \n\t"
+            "punpcklbw               %%mm7, %%mm2       \n\t"
+            "punpcklbw               %%mm7, %%mm3       \n\t"
+            "paddw                   %%mm1, %%mm4       \n\t"
+            "paddw                   %%mm3, %%mm2       \n\t"
+            "paddw                   %%mm4, %%mm2       \n\t"
+            "psrlw                      $2, %%mm0       \n\t"
+            "psrlw                      $2, %%mm2       \n\t"
+#endif
+            "movq  "MANGLE(ff_bgr2VCoeff)", %%mm1       \n\t"
+            "movq  "MANGLE(ff_bgr2VCoeff)", %%mm3       \n\t"
+
+            "pmaddwd                 %%mm0, %%mm1       \n\t"
+            "pmaddwd                 %%mm2, %%mm3       \n\t"
+            "pmaddwd                 %%mm6, %%mm0       \n\t"
+            "pmaddwd                 %%mm6, %%mm2       \n\t"
+#ifndef FAST_BGR2YV12
+            "psrad                      $8, %%mm0       \n\t"
+            "psrad                      $8, %%mm1       \n\t"
+            "psrad                      $8, %%mm2       \n\t"
+            "psrad                      $8, %%mm3       \n\t"
+#endif
+            "packssdw                %%mm2, %%mm0       \n\t"
+            "packssdw                %%mm3, %%mm1       \n\t"
+            "pmaddwd                 %%mm5, %%mm0       \n\t"
+            "pmaddwd                 %%mm5, %%mm1       \n\t"
+            "packssdw                %%mm1, %%mm0       \n\t" // V1 V0 U1 U0
+            "psraw                      $7, %%mm0       \n\t"
+
+#if COMPILE_TEMPLATE_MMX2 || COMPILE_TEMPLATE_AMD3DNOW
+            "movq        12(%0, %%"REG_d"), %%mm4       \n\t"
+            "movq        12(%1, %%"REG_d"), %%mm1       \n\t"
+            "movq        18(%0, %%"REG_d"), %%mm2       \n\t"
+            "movq        18(%1, %%"REG_d"), %%mm3       \n\t"
+            PAVGB"                   %%mm1, %%mm4       \n\t"
+            PAVGB"                   %%mm3, %%mm2       \n\t"
+            "movq                    %%mm4, %%mm1       \n\t"
+            "movq                    %%mm2, %%mm3       \n\t"
+            "psrlq                     $24, %%mm4       \n\t"
+            "psrlq                     $24, %%mm2       \n\t"
+            PAVGB"                   %%mm1, %%mm4       \n\t"
+            PAVGB"                   %%mm3, %%mm2       \n\t"
+            "punpcklbw               %%mm7, %%mm4       \n\t"
+            "punpcklbw               %%mm7, %%mm2       \n\t"
+#else
+            "movd        12(%0, %%"REG_d"), %%mm4       \n\t"
+            "movd        12(%1, %%"REG_d"), %%mm1       \n\t"
+            "movd        15(%0, %%"REG_d"), %%mm2       \n\t"
+            "movd        15(%1, %%"REG_d"), %%mm3       \n\t"
+            "punpcklbw               %%mm7, %%mm4       \n\t"
+            "punpcklbw               %%mm7, %%mm1       \n\t"
+            "punpcklbw               %%mm7, %%mm2       \n\t"
+            "punpcklbw               %%mm7, %%mm3       \n\t"
+            "paddw                   %%mm1, %%mm4       \n\t"
+            "paddw                   %%mm3, %%mm2       \n\t"
+            "paddw                   %%mm2, %%mm4       \n\t"
+            "movd        18(%0, %%"REG_d"), %%mm5       \n\t"
+            "movd        18(%1, %%"REG_d"), %%mm1       \n\t"
+            "movd        21(%0, %%"REG_d"), %%mm2       \n\t"
+            "movd        21(%1, %%"REG_d"), %%mm3       \n\t"
+            "punpcklbw               %%mm7, %%mm5       \n\t"
+            "punpcklbw               %%mm7, %%mm1       \n\t"
+            "punpcklbw               %%mm7, %%mm2       \n\t"
+            "punpcklbw               %%mm7, %%mm3       \n\t"
+            "paddw                   %%mm1, %%mm5       \n\t"
+            "paddw                   %%mm3, %%mm2       \n\t"
+            "paddw                   %%mm5, %%mm2       \n\t"
+            "movq       "MANGLE(ff_w1111)", %%mm5       \n\t"
+            "psrlw                      $2, %%mm4       \n\t"
+            "psrlw                      $2, %%mm2       \n\t"
+#endif
+            "movq  "MANGLE(ff_bgr2VCoeff)", %%mm1       \n\t"
+            "movq  "MANGLE(ff_bgr2VCoeff)", %%mm3       \n\t"
+
+            "pmaddwd                 %%mm4, %%mm1       \n\t"
+            "pmaddwd                 %%mm2, %%mm3       \n\t"
+            "pmaddwd                 %%mm6, %%mm4       \n\t"
+            "pmaddwd                 %%mm6, %%mm2       \n\t"
+#ifndef FAST_BGR2YV12
+            "psrad                      $8, %%mm4       \n\t"
+            "psrad                      $8, %%mm1       \n\t"
+            "psrad                      $8, %%mm2       \n\t"
+            "psrad                      $8, %%mm3       \n\t"
+#endif
+            "packssdw                %%mm2, %%mm4       \n\t"
+            "packssdw                %%mm3, %%mm1       \n\t"
+            "pmaddwd                 %%mm5, %%mm4       \n\t"
+            "pmaddwd                 %%mm5, %%mm1       \n\t"
+            "add                       $24, %%"REG_d"   \n\t"
+            "packssdw                %%mm1, %%mm4       \n\t" // V3 V2 U3 U2
+            "psraw                      $7, %%mm4       \n\t"
+
+            "movq                    %%mm0, %%mm1           \n\t"
+            "punpckldq               %%mm4, %%mm0           \n\t"
+            "punpckhdq               %%mm4, %%mm1           \n\t"
+            "packsswb                %%mm1, %%mm0           \n\t"
+            "paddb "MANGLE(ff_bgr2UVOffset)", %%mm0         \n\t"
+            "movd                    %%mm0, (%2, %%"REG_a") \n\t"
+            "punpckhdq               %%mm0, %%mm0           \n\t"
+            "movd                    %%mm0, (%3, %%"REG_a") \n\t"
+            "add                        $4, %%"REG_a"       \n\t"
+            " js                        1b                  \n\t"
+            : : "r" (src+chromWidth*6), "r" (src+srcStride+chromWidth*6), "r" (udst+chromWidth), "r" (vdst+chromWidth), "g" (-chromWidth)
+            : "%"REG_a, "%"REG_d
+        );
+
+        udst += chromStride;
+        vdst += chromStride;
+        src  += srcStride*2;
+    }
+
+    __asm__ volatile(EMMS"       \n\t"
+                     SFENCE"     \n\t"
+                     :::"memory");
+
+    for (; y<height; y+=2) {
+        long i;
+        for (i=0; i<chromWidth; i++) {
+            unsigned int b = src[6*i+0];
+            unsigned int g = src[6*i+1];
+            unsigned int r = src[6*i+2];
+
+            unsigned int Y  =  ((RY*r + GY*g + BY*b)>>RGB2YUV_SHIFT) + 16;
+            unsigned int V  =  ((RV*r + GV*g + BV*b)>>RGB2YUV_SHIFT) + 128;
+            unsigned int U  =  ((RU*r + GU*g + BU*b)>>RGB2YUV_SHIFT) + 128;
+
+            udst[i]     = U;
+            vdst[i]     = V;
+            ydst[2*i]   = Y;
+
+            b = src[6*i+3];
+            g = src[6*i+4];
+            r = src[6*i+5];
+
+            Y  =  ((RY*r + GY*g + BY*b)>>RGB2YUV_SHIFT) + 16;
+            ydst[2*i+1]     = Y;
+        }
+        ydst += lumStride;
+        src  += srcStride;
+
+        for (i=0; i<chromWidth; i++) {
+            unsigned int b = src[6*i+0];
+            unsigned int g = src[6*i+1];
+            unsigned int r = src[6*i+2];
+
+            unsigned int Y  =  ((RY*r + GY*g + BY*b)>>RGB2YUV_SHIFT) + 16;
+
+            ydst[2*i]     = Y;
+
+            b = src[6*i+3];
+            g = src[6*i+4];
+            r = src[6*i+5];
+
+            Y  =  ((RY*r + GY*g + BY*b)>>RGB2YUV_SHIFT) + 16;
+            ydst[2*i+1]     = Y;
+        }
+        udst += chromStride;
+        vdst += chromStride;
+        ydst += lumStride;
+        src  += srcStride;
+    }
+}
+
+static void RENAME(interleaveBytes)(const uint8_t *src1, const uint8_t *src2, uint8_t *dest,
+                                    long width, long height, long src1Stride,
+                                    long src2Stride, long dstStride)
+{
+    long h;
+
+    for (h=0; h < height; h++) {
+        long w;
+
+#if COMPILE_TEMPLATE_SSE2
+        __asm__(
+            "xor              %%"REG_a", %%"REG_a"  \n\t"
+            "1:                                     \n\t"
+            PREFETCH" 64(%1, %%"REG_a")             \n\t"
+            PREFETCH" 64(%2, %%"REG_a")             \n\t"
+            "movdqa     (%1, %%"REG_a"), %%xmm0     \n\t"
+            "movdqa     (%1, %%"REG_a"), %%xmm1     \n\t"
+            "movdqa     (%2, %%"REG_a"), %%xmm2     \n\t"
+            "punpcklbw           %%xmm2, %%xmm0     \n\t"
+            "punpckhbw           %%xmm2, %%xmm1     \n\t"
+            "movntdq             %%xmm0,   (%0, %%"REG_a", 2)   \n\t"
+            "movntdq             %%xmm1, 16(%0, %%"REG_a", 2)   \n\t"
+            "add                    $16, %%"REG_a"  \n\t"
+            "cmp                     %3, %%"REG_a"  \n\t"
+            " jb                     1b             \n\t"
+            ::"r"(dest), "r"(src1), "r"(src2), "r" ((x86_reg)width-15)
+            : "memory", "%"REG_a""
+        );
+#else
+        __asm__(
+            "xor %%"REG_a", %%"REG_a"               \n\t"
+            "1:                                     \n\t"
+            PREFETCH" 64(%1, %%"REG_a")             \n\t"
+            PREFETCH" 64(%2, %%"REG_a")             \n\t"
+            "movq       (%1, %%"REG_a"), %%mm0      \n\t"
+            "movq      8(%1, %%"REG_a"), %%mm2      \n\t"
+            "movq                 %%mm0, %%mm1      \n\t"
+            "movq                 %%mm2, %%mm3      \n\t"
+            "movq       (%2, %%"REG_a"), %%mm4      \n\t"
+            "movq      8(%2, %%"REG_a"), %%mm5      \n\t"
+            "punpcklbw            %%mm4, %%mm0      \n\t"
+            "punpckhbw            %%mm4, %%mm1      \n\t"
+            "punpcklbw            %%mm5, %%mm2      \n\t"
+            "punpckhbw            %%mm5, %%mm3      \n\t"
+            MOVNTQ"               %%mm0,   (%0, %%"REG_a", 2)   \n\t"
+            MOVNTQ"               %%mm1,  8(%0, %%"REG_a", 2)   \n\t"
+            MOVNTQ"               %%mm2, 16(%0, %%"REG_a", 2)   \n\t"
+            MOVNTQ"               %%mm3, 24(%0, %%"REG_a", 2)   \n\t"
+            "add                    $16, %%"REG_a"  \n\t"
+            "cmp                     %3, %%"REG_a"  \n\t"
+            " jb                     1b             \n\t"
+            ::"r"(dest), "r"(src1), "r"(src2), "r" ((x86_reg)width-15)
+            : "memory", "%"REG_a
+        );
+#endif
+        for (w= (width&(~15)); w < width; w++) {
+            dest[2*w+0] = src1[w];
+            dest[2*w+1] = src2[w];
+        }
+        dest += dstStride;
+        src1 += src1Stride;
+        src2 += src2Stride;
+    }
+    __asm__(
+            EMMS"       \n\t"
+            SFENCE"     \n\t"
+            ::: "memory"
+            );
+}
+
+static inline void RENAME(vu9_to_vu12)(const uint8_t *src1, const uint8_t *src2,
+                                       uint8_t *dst1, uint8_t *dst2,
+                                       long width, long height,
+                                       long srcStride1, long srcStride2,
+                                       long dstStride1, long dstStride2)
+{
+    x86_reg y;
+    long x,w,h;
+    w=width/2; h=height/2;
+    __asm__ volatile(
+        PREFETCH" %0    \n\t"
+        PREFETCH" %1    \n\t"
+        ::"m"(*(src1+srcStride1)),"m"(*(src2+srcStride2)):"memory");
+    for (y=0;y<h;y++) {
+        const uint8_t* s1=src1+srcStride1*(y>>1);
+        uint8_t* d=dst1+dstStride1*y;
+        x=0;
+        for (;x<w-31;x+=32) {
+            __asm__ volatile(
+                PREFETCH"   32%1        \n\t"
+                "movq         %1, %%mm0 \n\t"
+                "movq        8%1, %%mm2 \n\t"
+                "movq       16%1, %%mm4 \n\t"
+                "movq       24%1, %%mm6 \n\t"
+                "movq      %%mm0, %%mm1 \n\t"
+                "movq      %%mm2, %%mm3 \n\t"
+                "movq      %%mm4, %%mm5 \n\t"
+                "movq      %%mm6, %%mm7 \n\t"
+                "punpcklbw %%mm0, %%mm0 \n\t"
+                "punpckhbw %%mm1, %%mm1 \n\t"
+                "punpcklbw %%mm2, %%mm2 \n\t"
+                "punpckhbw %%mm3, %%mm3 \n\t"
+                "punpcklbw %%mm4, %%mm4 \n\t"
+                "punpckhbw %%mm5, %%mm5 \n\t"
+                "punpcklbw %%mm6, %%mm6 \n\t"
+                "punpckhbw %%mm7, %%mm7 \n\t"
+                MOVNTQ"    %%mm0,   %0  \n\t"
+                MOVNTQ"    %%mm1,  8%0  \n\t"
+                MOVNTQ"    %%mm2, 16%0  \n\t"
+                MOVNTQ"    %%mm3, 24%0  \n\t"
+                MOVNTQ"    %%mm4, 32%0  \n\t"
+                MOVNTQ"    %%mm5, 40%0  \n\t"
+                MOVNTQ"    %%mm6, 48%0  \n\t"
+                MOVNTQ"    %%mm7, 56%0"
+                :"=m"(d[2*x])
+                :"m"(s1[x])
+                :"memory");
+        }
+        for (;x<w;x++) d[2*x]=d[2*x+1]=s1[x];
+    }
+    for (y=0;y<h;y++) {
+        const uint8_t* s2=src2+srcStride2*(y>>1);
+        uint8_t* d=dst2+dstStride2*y;
+        x=0;
+        for (;x<w-31;x+=32) {
+            __asm__ volatile(
+                PREFETCH"   32%1        \n\t"
+                "movq         %1, %%mm0 \n\t"
+                "movq        8%1, %%mm2 \n\t"
+                "movq       16%1, %%mm4 \n\t"
+                "movq       24%1, %%mm6 \n\t"
+                "movq      %%mm0, %%mm1 \n\t"
+                "movq      %%mm2, %%mm3 \n\t"
+                "movq      %%mm4, %%mm5 \n\t"
+                "movq      %%mm6, %%mm7 \n\t"
+                "punpcklbw %%mm0, %%mm0 \n\t"
+                "punpckhbw %%mm1, %%mm1 \n\t"
+                "punpcklbw %%mm2, %%mm2 \n\t"
+                "punpckhbw %%mm3, %%mm3 \n\t"
+                "punpcklbw %%mm4, %%mm4 \n\t"
+                "punpckhbw %%mm5, %%mm5 \n\t"
+                "punpcklbw %%mm6, %%mm6 \n\t"
+                "punpckhbw %%mm7, %%mm7 \n\t"
+                MOVNTQ"    %%mm0,   %0  \n\t"
+                MOVNTQ"    %%mm1,  8%0  \n\t"
+                MOVNTQ"    %%mm2, 16%0  \n\t"
+                MOVNTQ"    %%mm3, 24%0  \n\t"
+                MOVNTQ"    %%mm4, 32%0  \n\t"
+                MOVNTQ"    %%mm5, 40%0  \n\t"
+                MOVNTQ"    %%mm6, 48%0  \n\t"
+                MOVNTQ"    %%mm7, 56%0"
+                :"=m"(d[2*x])
+                :"m"(s2[x])
+                :"memory");
+        }
+        for (;x<w;x++) d[2*x]=d[2*x+1]=s2[x];
+    }
+    __asm__(
+            EMMS"       \n\t"
+            SFENCE"     \n\t"
+            ::: "memory"
+        );
+}
+
+static inline void RENAME(yvu9_to_yuy2)(const uint8_t *src1, const uint8_t *src2, const uint8_t *src3,
+                                        uint8_t *dst,
+                                        long width, long height,
+                                        long srcStride1, long srcStride2,
+                                        long srcStride3, long dstStride)
+{
+    x86_reg x;
+    long y,w,h;
+    w=width/2; h=height;
+    for (y=0;y<h;y++) {
+        const uint8_t* yp=src1+srcStride1*y;
+        const uint8_t* up=src2+srcStride2*(y>>2);
+        const uint8_t* vp=src3+srcStride3*(y>>2);
+        uint8_t* d=dst+dstStride*y;
+        x=0;
+        for (;x<w-7;x+=8) {
+            __asm__ volatile(
+                PREFETCH"   32(%1, %0)          \n\t"
+                PREFETCH"   32(%2, %0)          \n\t"
+                PREFETCH"   32(%3, %0)          \n\t"
+                "movq      (%1, %0, 4), %%mm0   \n\t" /* Y0Y1Y2Y3Y4Y5Y6Y7 */
+                "movq         (%2, %0), %%mm1   \n\t" /* U0U1U2U3U4U5U6U7 */
+                "movq         (%3, %0), %%mm2   \n\t" /* V0V1V2V3V4V5V6V7 */
+                "movq            %%mm0, %%mm3   \n\t" /* Y0Y1Y2Y3Y4Y5Y6Y7 */
+                "movq            %%mm1, %%mm4   \n\t" /* U0U1U2U3U4U5U6U7 */
+                "movq            %%mm2, %%mm5   \n\t" /* V0V1V2V3V4V5V6V7 */
+                "punpcklbw       %%mm1, %%mm1   \n\t" /* U0U0 U1U1 U2U2 U3U3 */
+                "punpcklbw       %%mm2, %%mm2   \n\t" /* V0V0 V1V1 V2V2 V3V3 */
+                "punpckhbw       %%mm4, %%mm4   \n\t" /* U4U4 U5U5 U6U6 U7U7 */
+                "punpckhbw       %%mm5, %%mm5   \n\t" /* V4V4 V5V5 V6V6 V7V7 */
+
+                "movq            %%mm1, %%mm6   \n\t"
+                "punpcklbw       %%mm2, %%mm1   \n\t" /* U0V0 U0V0 U1V1 U1V1*/
+                "punpcklbw       %%mm1, %%mm0   \n\t" /* Y0U0 Y1V0 Y2U0 Y3V0*/
+                "punpckhbw       %%mm1, %%mm3   \n\t" /* Y4U1 Y5V1 Y6U1 Y7V1*/
+                MOVNTQ"          %%mm0,  (%4, %0, 8)    \n\t"
+                MOVNTQ"          %%mm3, 8(%4, %0, 8)    \n\t"
+
+                "punpckhbw       %%mm2, %%mm6   \n\t" /* U2V2 U2V2 U3V3 U3V3*/
+                "movq     8(%1, %0, 4), %%mm0   \n\t"
+                "movq            %%mm0, %%mm3   \n\t"
+                "punpcklbw       %%mm6, %%mm0   \n\t" /* Y U2 Y V2 Y U2 Y V2*/
+                "punpckhbw       %%mm6, %%mm3   \n\t" /* Y U3 Y V3 Y U3 Y V3*/
+                MOVNTQ"          %%mm0, 16(%4, %0, 8)   \n\t"
+                MOVNTQ"          %%mm3, 24(%4, %0, 8)   \n\t"
+
+                "movq            %%mm4, %%mm6   \n\t"
+                "movq    16(%1, %0, 4), %%mm0   \n\t"
+                "movq            %%mm0, %%mm3   \n\t"
+                "punpcklbw       %%mm5, %%mm4   \n\t"
+                "punpcklbw       %%mm4, %%mm0   \n\t" /* Y U4 Y V4 Y U4 Y V4*/
+                "punpckhbw       %%mm4, %%mm3   \n\t" /* Y U5 Y V5 Y U5 Y V5*/
+                MOVNTQ"          %%mm0, 32(%4, %0, 8)   \n\t"
+                MOVNTQ"          %%mm3, 40(%4, %0, 8)   \n\t"
+
+                "punpckhbw       %%mm5, %%mm6   \n\t"
+                "movq    24(%1, %0, 4), %%mm0   \n\t"
+                "movq            %%mm0, %%mm3   \n\t"
+                "punpcklbw       %%mm6, %%mm0   \n\t" /* Y U6 Y V6 Y U6 Y V6*/
+                "punpckhbw       %%mm6, %%mm3   \n\t" /* Y U7 Y V7 Y U7 Y V7*/
+                MOVNTQ"          %%mm0, 48(%4, %0, 8)   \n\t"
+                MOVNTQ"          %%mm3, 56(%4, %0, 8)   \n\t"
+
+                : "+r" (x)
+                : "r"(yp), "r" (up), "r"(vp), "r"(d)
+                :"memory");
+        }
+        for (; x<w; x++) {
+            const long x2 = x<<2;
+            d[8*x+0] = yp[x2];
+            d[8*x+1] = up[x];
+            d[8*x+2] = yp[x2+1];
+            d[8*x+3] = vp[x];
+            d[8*x+4] = yp[x2+2];
+            d[8*x+5] = up[x];
+            d[8*x+6] = yp[x2+3];
+            d[8*x+7] = vp[x];
+        }
+    }
+    __asm__(
+            EMMS"       \n\t"
+            SFENCE"     \n\t"
+            ::: "memory"
+        );
+}
+
+static void RENAME(extract_even)(const uint8_t *src, uint8_t *dst, x86_reg count)
+{
+    dst +=   count;
+    src += 2*count;
+    count= - count;
+
+    if(count <= -16) {
+        count += 15;
+        __asm__ volatile(
+            "pcmpeqw       %%mm7, %%mm7        \n\t"
+            "psrlw            $8, %%mm7        \n\t"
+            "1:                                \n\t"
+            "movq -30(%1, %0, 2), %%mm0        \n\t"
+            "movq -22(%1, %0, 2), %%mm1        \n\t"
+            "movq -14(%1, %0, 2), %%mm2        \n\t"
+            "movq  -6(%1, %0, 2), %%mm3        \n\t"
+            "pand          %%mm7, %%mm0        \n\t"
+            "pand          %%mm7, %%mm1        \n\t"
+            "pand          %%mm7, %%mm2        \n\t"
+            "pand          %%mm7, %%mm3        \n\t"
+            "packuswb      %%mm1, %%mm0        \n\t"
+            "packuswb      %%mm3, %%mm2        \n\t"
+            MOVNTQ"        %%mm0,-15(%2, %0)   \n\t"
+            MOVNTQ"        %%mm2,- 7(%2, %0)   \n\t"
+            "add             $16, %0           \n\t"
+            " js 1b                            \n\t"
+            : "+r"(count)
+            : "r"(src), "r"(dst)
+        );
+        count -= 15;
+    }
+    while(count<0) {
+        dst[count]= src[2*count];
+        count++;
+    }
+}
+
+static void RENAME(extract_even2)(const uint8_t *src, uint8_t *dst0, uint8_t *dst1, x86_reg count)
+{
+    dst0+=   count;
+    dst1+=   count;
+    src += 4*count;
+    count= - count;
+    if(count <= -8) {
+        count += 7;
+        __asm__ volatile(
+            "pcmpeqw       %%mm7, %%mm7        \n\t"
+            "psrlw            $8, %%mm7        \n\t"
+            "1:                                \n\t"
+            "movq -28(%1, %0, 4), %%mm0        \n\t"
+            "movq -20(%1, %0, 4), %%mm1        \n\t"
+            "movq -12(%1, %0, 4), %%mm2        \n\t"
+            "movq  -4(%1, %0, 4), %%mm3        \n\t"
+            "pand          %%mm7, %%mm0        \n\t"
+            "pand          %%mm7, %%mm1        \n\t"
+            "pand          %%mm7, %%mm2        \n\t"
+            "pand          %%mm7, %%mm3        \n\t"
+            "packuswb      %%mm1, %%mm0        \n\t"
+            "packuswb      %%mm3, %%mm2        \n\t"
+            "movq          %%mm0, %%mm1        \n\t"
+            "movq          %%mm2, %%mm3        \n\t"
+            "psrlw            $8, %%mm0        \n\t"
+            "psrlw            $8, %%mm2        \n\t"
+            "pand          %%mm7, %%mm1        \n\t"
+            "pand          %%mm7, %%mm3        \n\t"
+            "packuswb      %%mm2, %%mm0        \n\t"
+            "packuswb      %%mm3, %%mm1        \n\t"
+            MOVNTQ"        %%mm0,- 7(%3, %0)   \n\t"
+            MOVNTQ"        %%mm1,- 7(%2, %0)   \n\t"
+            "add              $8, %0           \n\t"
+            " js 1b                            \n\t"
+            : "+r"(count)
+            : "r"(src), "r"(dst0), "r"(dst1)
+        );
+        count -= 7;
+    }
+    while(count<0) {
+        dst0[count]= src[4*count+0];
+        dst1[count]= src[4*count+2];
+        count++;
+    }
+}
+
+static void RENAME(extract_even2avg)(const uint8_t *src0, const uint8_t *src1, uint8_t *dst0, uint8_t *dst1, x86_reg count)
+{
+    dst0 +=   count;
+    dst1 +=   count;
+    src0 += 4*count;
+    src1 += 4*count;
+    count= - count;
+#ifdef PAVGB
+    if(count <= -8) {
+        count += 7;
+        __asm__ volatile(
+            "pcmpeqw        %%mm7, %%mm7        \n\t"
+            "psrlw             $8, %%mm7        \n\t"
+            "1:                                \n\t"
+            "movq  -28(%1, %0, 4), %%mm0        \n\t"
+            "movq  -20(%1, %0, 4), %%mm1        \n\t"
+            "movq  -12(%1, %0, 4), %%mm2        \n\t"
+            "movq   -4(%1, %0, 4), %%mm3        \n\t"
+            PAVGB" -28(%2, %0, 4), %%mm0        \n\t"
+            PAVGB" -20(%2, %0, 4), %%mm1        \n\t"
+            PAVGB" -12(%2, %0, 4), %%mm2        \n\t"
+            PAVGB" - 4(%2, %0, 4), %%mm3        \n\t"
+            "pand           %%mm7, %%mm0        \n\t"
+            "pand           %%mm7, %%mm1        \n\t"
+            "pand           %%mm7, %%mm2        \n\t"
+            "pand           %%mm7, %%mm3        \n\t"
+            "packuswb       %%mm1, %%mm0        \n\t"
+            "packuswb       %%mm3, %%mm2        \n\t"
+            "movq           %%mm0, %%mm1        \n\t"
+            "movq           %%mm2, %%mm3        \n\t"
+            "psrlw             $8, %%mm0        \n\t"
+            "psrlw             $8, %%mm2        \n\t"
+            "pand           %%mm7, %%mm1        \n\t"
+            "pand           %%mm7, %%mm3        \n\t"
+            "packuswb       %%mm2, %%mm0        \n\t"
+            "packuswb       %%mm3, %%mm1        \n\t"
+            MOVNTQ"         %%mm0,- 7(%4, %0)   \n\t"
+            MOVNTQ"         %%mm1,- 7(%3, %0)   \n\t"
+            "add               $8, %0           \n\t"
+            " js 1b                            \n\t"
+            : "+r"(count)
+            : "r"(src0), "r"(src1), "r"(dst0), "r"(dst1)
+        );
+        count -= 7;
+    }
+#endif
+    while(count<0) {
+        dst0[count]= (src0[4*count+0]+src1[4*count+0])>>1;
+        dst1[count]= (src0[4*count+2]+src1[4*count+2])>>1;
+        count++;
+    }
+}
+
+static void RENAME(extract_odd2)(const uint8_t *src, uint8_t *dst0, uint8_t *dst1, x86_reg count)
+{
+    dst0+=   count;
+    dst1+=   count;
+    src += 4*count;
+    count= - count;
+    if(count <= -8) {
+        count += 7;
+        __asm__ volatile(
+            "pcmpeqw       %%mm7, %%mm7        \n\t"
+            "psrlw            $8, %%mm7        \n\t"
+            "1:                                \n\t"
+            "movq -28(%1, %0, 4), %%mm0        \n\t"
+            "movq -20(%1, %0, 4), %%mm1        \n\t"
+            "movq -12(%1, %0, 4), %%mm2        \n\t"
+            "movq  -4(%1, %0, 4), %%mm3        \n\t"
+            "psrlw            $8, %%mm0        \n\t"
+            "psrlw            $8, %%mm1        \n\t"
+            "psrlw            $8, %%mm2        \n\t"
+            "psrlw            $8, %%mm3        \n\t"
+            "packuswb      %%mm1, %%mm0        \n\t"
+            "packuswb      %%mm3, %%mm2        \n\t"
+            "movq          %%mm0, %%mm1        \n\t"
+            "movq          %%mm2, %%mm3        \n\t"
+            "psrlw            $8, %%mm0        \n\t"
+            "psrlw            $8, %%mm2        \n\t"
+            "pand          %%mm7, %%mm1        \n\t"
+            "pand          %%mm7, %%mm3        \n\t"
+            "packuswb      %%mm2, %%mm0        \n\t"
+            "packuswb      %%mm3, %%mm1        \n\t"
+            MOVNTQ"        %%mm0,- 7(%3, %0)   \n\t"
+            MOVNTQ"        %%mm1,- 7(%2, %0)   \n\t"
+            "add              $8, %0           \n\t"
+            " js 1b                            \n\t"
+            : "+r"(count)
+            : "r"(src), "r"(dst0), "r"(dst1)
+        );
+        count -= 7;
+    }
+    src++;
+    while(count<0) {
+        dst0[count]= src[4*count+0];
+        dst1[count]= src[4*count+2];
+        count++;
+    }
+}
+
+static void RENAME(extract_odd2avg)(const uint8_t *src0, const uint8_t *src1, uint8_t *dst0, uint8_t *dst1, x86_reg count)
+{
+    dst0 +=   count;
+    dst1 +=   count;
+    src0 += 4*count;
+    src1 += 4*count;
+    count= - count;
+#ifdef PAVGB
+    if(count <= -8) {
+        count += 7;
+        __asm__ volatile(
+            "pcmpeqw        %%mm7, %%mm7        \n\t"
+            "psrlw             $8, %%mm7        \n\t"
+            "1:                                \n\t"
+            "movq  -28(%1, %0, 4), %%mm0        \n\t"
+            "movq  -20(%1, %0, 4), %%mm1        \n\t"
+            "movq  -12(%1, %0, 4), %%mm2        \n\t"
+            "movq   -4(%1, %0, 4), %%mm3        \n\t"
+            PAVGB" -28(%2, %0, 4), %%mm0        \n\t"
+            PAVGB" -20(%2, %0, 4), %%mm1        \n\t"
+            PAVGB" -12(%2, %0, 4), %%mm2        \n\t"
+            PAVGB" - 4(%2, %0, 4), %%mm3        \n\t"
+            "psrlw             $8, %%mm0        \n\t"
+            "psrlw             $8, %%mm1        \n\t"
+            "psrlw             $8, %%mm2        \n\t"
+            "psrlw             $8, %%mm3        \n\t"
+            "packuswb       %%mm1, %%mm0        \n\t"
+            "packuswb       %%mm3, %%mm2        \n\t"
+            "movq           %%mm0, %%mm1        \n\t"
+            "movq           %%mm2, %%mm3        \n\t"
+            "psrlw             $8, %%mm0        \n\t"
+            "psrlw             $8, %%mm2        \n\t"
+            "pand           %%mm7, %%mm1        \n\t"
+            "pand           %%mm7, %%mm3        \n\t"
+            "packuswb       %%mm2, %%mm0        \n\t"
+            "packuswb       %%mm3, %%mm1        \n\t"
+            MOVNTQ"         %%mm0,- 7(%4, %0)   \n\t"
+            MOVNTQ"         %%mm1,- 7(%3, %0)   \n\t"
+            "add               $8, %0           \n\t"
+            " js 1b                            \n\t"
+            : "+r"(count)
+            : "r"(src0), "r"(src1), "r"(dst0), "r"(dst1)
+        );
+        count -= 7;
+    }
+#endif
+    src0++;
+    src1++;
+    while(count<0) {
+        dst0[count]= (src0[4*count+0]+src1[4*count+0])>>1;
+        dst1[count]= (src0[4*count+2]+src1[4*count+2])>>1;
+        count++;
+    }
+}
+
+static void RENAME(yuyvtoyuv420)(uint8_t *ydst, uint8_t *udst, uint8_t *vdst, const uint8_t *src,
+                                 long width, long height,
+                                 long lumStride, long chromStride, long srcStride)
+{
+    long y;
+    const long chromWidth= -((-width)>>1);
+
+    for (y=0; y<height; y++) {
+        RENAME(extract_even)(src, ydst, width);
+        if(y&1) {
+            RENAME(extract_odd2avg)(src-srcStride, src, udst, vdst, chromWidth);
+            udst+= chromStride;
+            vdst+= chromStride;
+        }
+
+        src += srcStride;
+        ydst+= lumStride;
+    }
+    __asm__(
+            EMMS"       \n\t"
+            SFENCE"     \n\t"
+            ::: "memory"
+        );
+}
+
+static void RENAME(yuyvtoyuv422)(uint8_t *ydst, uint8_t *udst, uint8_t *vdst, const uint8_t *src,
+                                 long width, long height,
+                                 long lumStride, long chromStride, long srcStride)
+{
+    long y;
+    const long chromWidth= -((-width)>>1);
+
+    for (y=0; y<height; y++) {
+        RENAME(extract_even)(src, ydst, width);
+        RENAME(extract_odd2)(src, udst, vdst, chromWidth);
+
+        src += srcStride;
+        ydst+= lumStride;
+        udst+= chromStride;
+        vdst+= chromStride;
+    }
+    __asm__(
+            EMMS"       \n\t"
+            SFENCE"     \n\t"
+            ::: "memory"
+        );
+}
+
+static void RENAME(uyvytoyuv420)(uint8_t *ydst, uint8_t *udst, uint8_t *vdst, const uint8_t *src,
+                                 long width, long height,
+                                 long lumStride, long chromStride, long srcStride)
+{
+    long y;
+    const long chromWidth= -((-width)>>1);
+
+    for (y=0; y<height; y++) {
+        RENAME(extract_even)(src+1, ydst, width);
+        if(y&1) {
+            RENAME(extract_even2avg)(src-srcStride, src, udst, vdst, chromWidth);
+            udst+= chromStride;
+            vdst+= chromStride;
+        }
+
+        src += srcStride;
+        ydst+= lumStride;
+    }
+    __asm__(
+            EMMS"       \n\t"
+            SFENCE"     \n\t"
+            ::: "memory"
+        );
+}
+
+static void RENAME(uyvytoyuv422)(uint8_t *ydst, uint8_t *udst, uint8_t *vdst, const uint8_t *src,
+                                 long width, long height,
+                                 long lumStride, long chromStride, long srcStride)
+{
+    long y;
+    const long chromWidth= -((-width)>>1);
+
+    for (y=0; y<height; y++) {
+        RENAME(extract_even)(src+1, ydst, width);
+        RENAME(extract_even2)(src, udst, vdst, chromWidth);
+
+        src += srcStride;
+        ydst+= lumStride;
+        udst+= chromStride;
+        vdst+= chromStride;
+    }
+    __asm__(
+            EMMS"       \n\t"
+            SFENCE"     \n\t"
+            ::: "memory"
+        );
+}
+
+static inline void RENAME(rgb2rgb_init)(void)
+{
+    rgb15to16          = RENAME(rgb15to16);
+    rgb15tobgr24       = RENAME(rgb15tobgr24);
+    rgb15to32          = RENAME(rgb15to32);
+    rgb16tobgr24       = RENAME(rgb16tobgr24);
+    rgb16to32          = RENAME(rgb16to32);
+    rgb16to15          = RENAME(rgb16to15);
+    rgb24tobgr16       = RENAME(rgb24tobgr16);
+    rgb24tobgr15       = RENAME(rgb24tobgr15);
+    rgb24tobgr32       = RENAME(rgb24tobgr32);
+    rgb32to16          = RENAME(rgb32to16);
+    rgb32to15          = RENAME(rgb32to15);
+    rgb32tobgr24       = RENAME(rgb32tobgr24);
+    rgb24to15          = RENAME(rgb24to15);
+    rgb24to16          = RENAME(rgb24to16);
+    rgb24tobgr24       = RENAME(rgb24tobgr24);
+    shuffle_bytes_2103 = RENAME(shuffle_bytes_2103);
+    rgb32tobgr16       = RENAME(rgb32tobgr16);
+    rgb32tobgr15       = RENAME(rgb32tobgr15);
+    yv12toyuy2         = RENAME(yv12toyuy2);
+    yv12touyvy         = RENAME(yv12touyvy);
+    yuv422ptoyuy2      = RENAME(yuv422ptoyuy2);
+    yuv422ptouyvy      = RENAME(yuv422ptouyvy);
+    yuy2toyv12         = RENAME(yuy2toyv12);
+    planar2x           = RENAME(planar2x);
+    rgb24toyv12        = RENAME(rgb24toyv12);
+    interleaveBytes    = RENAME(interleaveBytes);
+    vu9_to_vu12        = RENAME(vu9_to_vu12);
+    yvu9_to_yuy2       = RENAME(yvu9_to_yuy2);
+
+    uyvytoyuv420       = RENAME(uyvytoyuv420);
+    uyvytoyuv422       = RENAME(uyvytoyuv422);
+    yuyvtoyuv420       = RENAME(yuyvtoyuv420);
+    yuyvtoyuv422       = RENAME(yuyvtoyuv422);
+}
diff --git a/libswscale/x86/swscale_template.c b/libswscale/x86/swscale_template.c
new file mode 100644
index 0000000..b1009cb
--- /dev/null
+++ b/libswscale/x86/swscale_template.c
@@ -0,0 +1,2820 @@
+/*
+ * Copyright (C) 2001-2003 Michael Niedermayer <michaelni at gmx.at>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "swscale_template.h"
+
+#undef REAL_MOVNTQ
+#undef MOVNTQ
+#undef PAVGB
+#undef PREFETCH
+
+#if COMPILE_TEMPLATE_AMD3DNOW
+#define PREFETCH  "prefetch"
+#elif COMPILE_TEMPLATE_MMX2
+#define PREFETCH "prefetchnta"
+#else
+#define PREFETCH  " # nop"
+#endif
+
+#if COMPILE_TEMPLATE_MMX2
+#define PAVGB(a,b) "pavgb " #a ", " #b " \n\t"
+#elif COMPILE_TEMPLATE_AMD3DNOW
+#define PAVGB(a,b) "pavgusb " #a ", " #b " \n\t"
+#endif
+
+#if COMPILE_TEMPLATE_MMX2
+#define REAL_MOVNTQ(a,b) "movntq " #a ", " #b " \n\t"
+#else
+#define REAL_MOVNTQ(a,b) "movq " #a ", " #b " \n\t"
+#endif
+#define MOVNTQ(a,b)  REAL_MOVNTQ(a,b)
+
+#define YSCALEYUV2YV12X(x, offset, dest, width) \
+    __asm__ volatile(\
+        "xor                          %%"REG_a", %%"REG_a"  \n\t"\
+        "movq             "VROUNDER_OFFSET"(%0), %%mm3      \n\t"\
+        "movq                             %%mm3, %%mm4      \n\t"\
+        "lea                     " offset "(%0), %%"REG_d"  \n\t"\
+        "mov                        (%%"REG_d"), %%"REG_S"  \n\t"\
+        ".p2align                             4             \n\t" /* FIXME Unroll? */\
+        "1:                                                 \n\t"\
+        "movq                      8(%%"REG_d"), %%mm0      \n\t" /* filterCoeff */\
+        "movq   "  x "(%%"REG_S", %%"REG_a", 2), %%mm2      \n\t" /* srcData */\
+        "movq 8+"  x "(%%"REG_S", %%"REG_a", 2), %%mm5      \n\t" /* srcData */\
+        "add                                $16, %%"REG_d"  \n\t"\
+        "mov                        (%%"REG_d"), %%"REG_S"  \n\t"\
+        "test                         %%"REG_S", %%"REG_S"  \n\t"\
+        "pmulhw                           %%mm0, %%mm2      \n\t"\
+        "pmulhw                           %%mm0, %%mm5      \n\t"\
+        "paddw                            %%mm2, %%mm3      \n\t"\
+        "paddw                            %%mm5, %%mm4      \n\t"\
+        " jnz                                1b             \n\t"\
+        "psraw                               $3, %%mm3      \n\t"\
+        "psraw                               $3, %%mm4      \n\t"\
+        "packuswb                         %%mm4, %%mm3      \n\t"\
+        MOVNTQ(%%mm3, (%1, %%REGa))\
+        "add                                 $8, %%"REG_a"  \n\t"\
+        "cmp                                 %2, %%"REG_a"  \n\t"\
+        "movq             "VROUNDER_OFFSET"(%0), %%mm3      \n\t"\
+        "movq                             %%mm3, %%mm4      \n\t"\
+        "lea                     " offset "(%0), %%"REG_d"  \n\t"\
+        "mov                        (%%"REG_d"), %%"REG_S"  \n\t"\
+        "jb                                  1b             \n\t"\
+        :: "r" (&c->redDither),\
+        "r" (dest), "g" ((x86_reg)width)\
+        : "%"REG_a, "%"REG_d, "%"REG_S\
+    );
+
+#define YSCALEYUV2YV12X_ACCURATE(x, offset, dest, width) \
+    __asm__ volatile(\
+        "lea                     " offset "(%0), %%"REG_d"  \n\t"\
+        "xor                          %%"REG_a", %%"REG_a"  \n\t"\
+        "pxor                             %%mm4, %%mm4      \n\t"\
+        "pxor                             %%mm5, %%mm5      \n\t"\
+        "pxor                             %%mm6, %%mm6      \n\t"\
+        "pxor                             %%mm7, %%mm7      \n\t"\
+        "mov                        (%%"REG_d"), %%"REG_S"  \n\t"\
+        ".p2align                             4             \n\t"\
+        "1:                                                 \n\t"\
+        "movq   "  x "(%%"REG_S", %%"REG_a", 2), %%mm0      \n\t" /* srcData */\
+        "movq 8+"  x "(%%"REG_S", %%"REG_a", 2), %%mm2      \n\t" /* srcData */\
+        "mov        "STR(APCK_PTR2)"(%%"REG_d"), %%"REG_S"  \n\t"\
+        "movq   "  x "(%%"REG_S", %%"REG_a", 2), %%mm1      \n\t" /* srcData */\
+        "movq                             %%mm0, %%mm3      \n\t"\
+        "punpcklwd                        %%mm1, %%mm0      \n\t"\
+        "punpckhwd                        %%mm1, %%mm3      \n\t"\
+        "movq       "STR(APCK_COEF)"(%%"REG_d"), %%mm1      \n\t" /* filterCoeff */\
+        "pmaddwd                          %%mm1, %%mm0      \n\t"\
+        "pmaddwd                          %%mm1, %%mm3      \n\t"\
+        "paddd                            %%mm0, %%mm4      \n\t"\
+        "paddd                            %%mm3, %%mm5      \n\t"\
+        "movq 8+"  x "(%%"REG_S", %%"REG_a", 2), %%mm3      \n\t" /* srcData */\
+        "mov        "STR(APCK_SIZE)"(%%"REG_d"), %%"REG_S"  \n\t"\
+        "add                  $"STR(APCK_SIZE)", %%"REG_d"  \n\t"\
+        "test                         %%"REG_S", %%"REG_S"  \n\t"\
+        "movq                             %%mm2, %%mm0      \n\t"\
+        "punpcklwd                        %%mm3, %%mm2      \n\t"\
+        "punpckhwd                        %%mm3, %%mm0      \n\t"\
+        "pmaddwd                          %%mm1, %%mm2      \n\t"\
+        "pmaddwd                          %%mm1, %%mm0      \n\t"\
+        "paddd                            %%mm2, %%mm6      \n\t"\
+        "paddd                            %%mm0, %%mm7      \n\t"\
+        " jnz                                1b             \n\t"\
+        "psrad                              $16, %%mm4      \n\t"\
+        "psrad                              $16, %%mm5      \n\t"\
+        "psrad                              $16, %%mm6      \n\t"\
+        "psrad                              $16, %%mm7      \n\t"\
+        "movq             "VROUNDER_OFFSET"(%0), %%mm0      \n\t"\
+        "packssdw                         %%mm5, %%mm4      \n\t"\
+        "packssdw                         %%mm7, %%mm6      \n\t"\
+        "paddw                            %%mm0, %%mm4      \n\t"\
+        "paddw                            %%mm0, %%mm6      \n\t"\
+        "psraw                               $3, %%mm4      \n\t"\
+        "psraw                               $3, %%mm6      \n\t"\
+        "packuswb                         %%mm6, %%mm4      \n\t"\
+        MOVNTQ(%%mm4, (%1, %%REGa))\
+        "add                                 $8, %%"REG_a"  \n\t"\
+        "cmp                                 %2, %%"REG_a"  \n\t"\
+        "lea                     " offset "(%0), %%"REG_d"  \n\t"\
+        "pxor                             %%mm4, %%mm4      \n\t"\
+        "pxor                             %%mm5, %%mm5      \n\t"\
+        "pxor                             %%mm6, %%mm6      \n\t"\
+        "pxor                             %%mm7, %%mm7      \n\t"\
+        "mov                        (%%"REG_d"), %%"REG_S"  \n\t"\
+        "jb                                  1b             \n\t"\
+        :: "r" (&c->redDither),\
+        "r" (dest), "g" ((x86_reg)width)\
+        : "%"REG_a, "%"REG_d, "%"REG_S\
+    );
+
+#define YSCALEYUV2YV121 \
+    "mov %2, %%"REG_a"                    \n\t"\
+    ".p2align               4             \n\t" /* FIXME Unroll? */\
+    "1:                                   \n\t"\
+    "movq  (%0, %%"REG_a", 2), %%mm0      \n\t"\
+    "movq 8(%0, %%"REG_a", 2), %%mm1      \n\t"\
+    "psraw                 $7, %%mm0      \n\t"\
+    "psraw                 $7, %%mm1      \n\t"\
+    "packuswb           %%mm1, %%mm0      \n\t"\
+    MOVNTQ(%%mm0, (%1, %%REGa))\
+    "add                   $8, %%"REG_a"  \n\t"\
+    "jnc                   1b             \n\t"
+
+#define YSCALEYUV2YV121_ACCURATE \
+    "mov %2, %%"REG_a"                    \n\t"\
+    "pcmpeqw %%mm7, %%mm7                 \n\t"\
+    "psrlw                 $15, %%mm7     \n\t"\
+    "psllw                  $6, %%mm7     \n\t"\
+    ".p2align                4            \n\t" /* FIXME Unroll? */\
+    "1:                                   \n\t"\
+    "movq  (%0, %%"REG_a", 2), %%mm0      \n\t"\
+    "movq 8(%0, %%"REG_a", 2), %%mm1      \n\t"\
+    "paddsw             %%mm7, %%mm0      \n\t"\
+    "paddsw             %%mm7, %%mm1      \n\t"\
+    "psraw                 $7, %%mm0      \n\t"\
+    "psraw                 $7, %%mm1      \n\t"\
+    "packuswb           %%mm1, %%mm0      \n\t"\
+    MOVNTQ(%%mm0, (%1, %%REGa))\
+    "add                   $8, %%"REG_a"  \n\t"\
+    "jnc                   1b             \n\t"
+
+/*
+    :: "m" (-lumFilterSize), "m" (-chrFilterSize),
+       "m" (lumMmxFilter+lumFilterSize*4), "m" (chrMmxFilter+chrFilterSize*4),
+       "r" (dest), "m" (dstW_reg),
+       "m" (lumSrc+lumFilterSize), "m" (chrSrc+chrFilterSize)
+    : "%eax", "%ebx", "%ecx", "%edx", "%esi"
+*/
+#define YSCALEYUV2PACKEDX_UV \
+    __asm__ volatile(\
+        "xor                   %%"REG_a", %%"REG_a"     \n\t"\
+        ".p2align                      4                \n\t"\
+        "nop                                            \n\t"\
+        "1:                                             \n\t"\
+        "lea "CHR_MMX_FILTER_OFFSET"(%0), %%"REG_d"     \n\t"\
+        "mov                 (%%"REG_d"), %%"REG_S"     \n\t"\
+        "movq      "VROUNDER_OFFSET"(%0), %%mm3         \n\t"\
+        "movq                      %%mm3, %%mm4         \n\t"\
+        ".p2align                      4                \n\t"\
+        "2:                                             \n\t"\
+        "movq               8(%%"REG_d"), %%mm0         \n\t" /* filterCoeff */\
+        "movq     (%%"REG_S", %%"REG_a"), %%mm2         \n\t" /* UsrcData */\
+        "movq "AV_STRINGIFY(VOF)"(%%"REG_S", %%"REG_a"), %%mm5         \n\t" /* VsrcData */\
+        "add                         $16, %%"REG_d"     \n\t"\
+        "mov                 (%%"REG_d"), %%"REG_S"     \n\t"\
+        "pmulhw                    %%mm0, %%mm2         \n\t"\
+        "pmulhw                    %%mm0, %%mm5         \n\t"\
+        "paddw                     %%mm2, %%mm3         \n\t"\
+        "paddw                     %%mm5, %%mm4         \n\t"\
+        "test                  %%"REG_S", %%"REG_S"     \n\t"\
+        " jnz                         2b                \n\t"\
+
+#define YSCALEYUV2PACKEDX_YA(offset,coeff,src1,src2,dst1,dst2) \
+    "lea                "offset"(%0), %%"REG_d"     \n\t"\
+    "mov                 (%%"REG_d"), %%"REG_S"     \n\t"\
+    "movq      "VROUNDER_OFFSET"(%0), "#dst1"       \n\t"\
+    "movq                    "#dst1", "#dst2"       \n\t"\
+    ".p2align                      4                \n\t"\
+    "2:                                             \n\t"\
+    "movq               8(%%"REG_d"), "#coeff"      \n\t" /* filterCoeff */\
+    "movq  (%%"REG_S", %%"REG_a", 2), "#src1"       \n\t" /* Y1srcData */\
+    "movq 8(%%"REG_S", %%"REG_a", 2), "#src2"       \n\t" /* Y2srcData */\
+    "add                         $16, %%"REG_d"            \n\t"\
+    "mov                 (%%"REG_d"), %%"REG_S"     \n\t"\
+    "pmulhw                 "#coeff", "#src1"       \n\t"\
+    "pmulhw                 "#coeff", "#src2"       \n\t"\
+    "paddw                   "#src1", "#dst1"       \n\t"\
+    "paddw                   "#src2", "#dst2"       \n\t"\
+    "test                  %%"REG_S", %%"REG_S"     \n\t"\
+    " jnz                         2b                \n\t"\
+
+#define YSCALEYUV2PACKEDX \
+    YSCALEYUV2PACKEDX_UV \
+    YSCALEYUV2PACKEDX_YA(LUM_MMX_FILTER_OFFSET,%%mm0,%%mm2,%%mm5,%%mm1,%%mm7) \
+
+#define YSCALEYUV2PACKEDX_END                     \
+        :: "r" (&c->redDither),                   \
+            "m" (dummy), "m" (dummy), "m" (dummy),\
+            "r" (dest), "m" (dstW_reg)            \
+        : "%"REG_a, "%"REG_d, "%"REG_S            \
+    );
+
+#define YSCALEYUV2PACKEDX_ACCURATE_UV \
+    __asm__ volatile(\
+        "xor %%"REG_a", %%"REG_a"                       \n\t"\
+        ".p2align                      4                \n\t"\
+        "nop                                            \n\t"\
+        "1:                                             \n\t"\
+        "lea "CHR_MMX_FILTER_OFFSET"(%0), %%"REG_d"     \n\t"\
+        "mov                 (%%"REG_d"), %%"REG_S"     \n\t"\
+        "pxor                      %%mm4, %%mm4         \n\t"\
+        "pxor                      %%mm5, %%mm5         \n\t"\
+        "pxor                      %%mm6, %%mm6         \n\t"\
+        "pxor                      %%mm7, %%mm7         \n\t"\
+        ".p2align                      4                \n\t"\
+        "2:                                             \n\t"\
+        "movq     (%%"REG_S", %%"REG_a"), %%mm0         \n\t" /* UsrcData */\
+        "movq "AV_STRINGIFY(VOF)"(%%"REG_S", %%"REG_a"), %%mm2         \n\t" /* VsrcData */\
+        "mov "STR(APCK_PTR2)"(%%"REG_d"), %%"REG_S"     \n\t"\
+        "movq     (%%"REG_S", %%"REG_a"), %%mm1         \n\t" /* UsrcData */\
+        "movq                      %%mm0, %%mm3         \n\t"\
+        "punpcklwd                 %%mm1, %%mm0         \n\t"\
+        "punpckhwd                 %%mm1, %%mm3         \n\t"\
+        "movq "STR(APCK_COEF)"(%%"REG_d"),%%mm1         \n\t" /* filterCoeff */\
+        "pmaddwd                   %%mm1, %%mm0         \n\t"\
+        "pmaddwd                   %%mm1, %%mm3         \n\t"\
+        "paddd                     %%mm0, %%mm4         \n\t"\
+        "paddd                     %%mm3, %%mm5         \n\t"\
+        "movq "AV_STRINGIFY(VOF)"(%%"REG_S", %%"REG_a"), %%mm3         \n\t" /* VsrcData */\
+        "mov "STR(APCK_SIZE)"(%%"REG_d"), %%"REG_S"     \n\t"\
+        "add           $"STR(APCK_SIZE)", %%"REG_d"     \n\t"\
+        "test                  %%"REG_S", %%"REG_S"     \n\t"\
+        "movq                      %%mm2, %%mm0         \n\t"\
+        "punpcklwd                 %%mm3, %%mm2         \n\t"\
+        "punpckhwd                 %%mm3, %%mm0         \n\t"\
+        "pmaddwd                   %%mm1, %%mm2         \n\t"\
+        "pmaddwd                   %%mm1, %%mm0         \n\t"\
+        "paddd                     %%mm2, %%mm6         \n\t"\
+        "paddd                     %%mm0, %%mm7         \n\t"\
+        " jnz                         2b                \n\t"\
+        "psrad                       $16, %%mm4         \n\t"\
+        "psrad                       $16, %%mm5         \n\t"\
+        "psrad                       $16, %%mm6         \n\t"\
+        "psrad                       $16, %%mm7         \n\t"\
+        "movq      "VROUNDER_OFFSET"(%0), %%mm0         \n\t"\
+        "packssdw                  %%mm5, %%mm4         \n\t"\
+        "packssdw                  %%mm7, %%mm6         \n\t"\
+        "paddw                     %%mm0, %%mm4         \n\t"\
+        "paddw                     %%mm0, %%mm6         \n\t"\
+        "movq                      %%mm4, "U_TEMP"(%0)  \n\t"\
+        "movq                      %%mm6, "V_TEMP"(%0)  \n\t"\
+
+#define YSCALEYUV2PACKEDX_ACCURATE_YA(offset) \
+    "lea                "offset"(%0), %%"REG_d"     \n\t"\
+    "mov                 (%%"REG_d"), %%"REG_S"     \n\t"\
+    "pxor                      %%mm1, %%mm1         \n\t"\
+    "pxor                      %%mm5, %%mm5         \n\t"\
+    "pxor                      %%mm7, %%mm7         \n\t"\
+    "pxor                      %%mm6, %%mm6         \n\t"\
+    ".p2align                      4                \n\t"\
+    "2:                                             \n\t"\
+    "movq  (%%"REG_S", %%"REG_a", 2), %%mm0         \n\t" /* Y1srcData */\
+    "movq 8(%%"REG_S", %%"REG_a", 2), %%mm2         \n\t" /* Y2srcData */\
+    "mov "STR(APCK_PTR2)"(%%"REG_d"), %%"REG_S"     \n\t"\
+    "movq  (%%"REG_S", %%"REG_a", 2), %%mm4         \n\t" /* Y1srcData */\
+    "movq                      %%mm0, %%mm3         \n\t"\
+    "punpcklwd                 %%mm4, %%mm0         \n\t"\
+    "punpckhwd                 %%mm4, %%mm3         \n\t"\
+    "movq "STR(APCK_COEF)"(%%"REG_d"), %%mm4         \n\t" /* filterCoeff */\
+    "pmaddwd                   %%mm4, %%mm0         \n\t"\
+    "pmaddwd                   %%mm4, %%mm3         \n\t"\
+    "paddd                     %%mm0, %%mm1         \n\t"\
+    "paddd                     %%mm3, %%mm5         \n\t"\
+    "movq 8(%%"REG_S", %%"REG_a", 2), %%mm3         \n\t" /* Y2srcData */\
+    "mov "STR(APCK_SIZE)"(%%"REG_d"), %%"REG_S"     \n\t"\
+    "add           $"STR(APCK_SIZE)", %%"REG_d"     \n\t"\
+    "test                  %%"REG_S", %%"REG_S"     \n\t"\
+    "movq                      %%mm2, %%mm0         \n\t"\
+    "punpcklwd                 %%mm3, %%mm2         \n\t"\
+    "punpckhwd                 %%mm3, %%mm0         \n\t"\
+    "pmaddwd                   %%mm4, %%mm2         \n\t"\
+    "pmaddwd                   %%mm4, %%mm0         \n\t"\
+    "paddd                     %%mm2, %%mm7         \n\t"\
+    "paddd                     %%mm0, %%mm6         \n\t"\
+    " jnz                         2b                \n\t"\
+    "psrad                       $16, %%mm1         \n\t"\
+    "psrad                       $16, %%mm5         \n\t"\
+    "psrad                       $16, %%mm7         \n\t"\
+    "psrad                       $16, %%mm6         \n\t"\
+    "movq      "VROUNDER_OFFSET"(%0), %%mm0         \n\t"\
+    "packssdw                  %%mm5, %%mm1         \n\t"\
+    "packssdw                  %%mm6, %%mm7         \n\t"\
+    "paddw                     %%mm0, %%mm1         \n\t"\
+    "paddw                     %%mm0, %%mm7         \n\t"\
+    "movq               "U_TEMP"(%0), %%mm3         \n\t"\
+    "movq               "V_TEMP"(%0), %%mm4         \n\t"\
+
+#define YSCALEYUV2PACKEDX_ACCURATE \
+    YSCALEYUV2PACKEDX_ACCURATE_UV \
+    YSCALEYUV2PACKEDX_ACCURATE_YA(LUM_MMX_FILTER_OFFSET)
+
+#define YSCALEYUV2RGBX \
+    "psubw  "U_OFFSET"(%0), %%mm3       \n\t" /* (U-128)8*/\
+    "psubw  "V_OFFSET"(%0), %%mm4       \n\t" /* (V-128)8*/\
+    "movq            %%mm3, %%mm2       \n\t" /* (U-128)8*/\
+    "movq            %%mm4, %%mm5       \n\t" /* (V-128)8*/\
+    "pmulhw "UG_COEFF"(%0), %%mm3       \n\t"\
+    "pmulhw "VG_COEFF"(%0), %%mm4       \n\t"\
+    /* mm2=(U-128)8, mm3=ug, mm4=vg mm5=(V-128)8 */\
+    "pmulhw "UB_COEFF"(%0), %%mm2       \n\t"\
+    "pmulhw "VR_COEFF"(%0), %%mm5       \n\t"\
+    "psubw  "Y_OFFSET"(%0), %%mm1       \n\t" /* 8(Y-16)*/\
+    "psubw  "Y_OFFSET"(%0), %%mm7       \n\t" /* 8(Y-16)*/\
+    "pmulhw  "Y_COEFF"(%0), %%mm1       \n\t"\
+    "pmulhw  "Y_COEFF"(%0), %%mm7       \n\t"\
+    /* mm1= Y1, mm2=ub, mm3=ug, mm4=vg mm5=vr, mm7=Y2 */\
+    "paddw           %%mm3, %%mm4       \n\t"\
+    "movq            %%mm2, %%mm0       \n\t"\
+    "movq            %%mm5, %%mm6       \n\t"\
+    "movq            %%mm4, %%mm3       \n\t"\
+    "punpcklwd       %%mm2, %%mm2       \n\t"\
+    "punpcklwd       %%mm5, %%mm5       \n\t"\
+    "punpcklwd       %%mm4, %%mm4       \n\t"\
+    "paddw           %%mm1, %%mm2       \n\t"\
+    "paddw           %%mm1, %%mm5       \n\t"\
+    "paddw           %%mm1, %%mm4       \n\t"\
+    "punpckhwd       %%mm0, %%mm0       \n\t"\
+    "punpckhwd       %%mm6, %%mm6       \n\t"\
+    "punpckhwd       %%mm3, %%mm3       \n\t"\
+    "paddw           %%mm7, %%mm0       \n\t"\
+    "paddw           %%mm7, %%mm6       \n\t"\
+    "paddw           %%mm7, %%mm3       \n\t"\
+    /* mm0=B1, mm2=B2, mm3=G2, mm4=G1, mm5=R1, mm6=R2 */\
+    "packuswb        %%mm0, %%mm2       \n\t"\
+    "packuswb        %%mm6, %%mm5       \n\t"\
+    "packuswb        %%mm3, %%mm4       \n\t"\
+
+#define REAL_YSCALEYUV2PACKED(index, c) \
+    "movq "CHR_MMX_FILTER_OFFSET"+8("#c"), %%mm0              \n\t"\
+    "movq "LUM_MMX_FILTER_OFFSET"+8("#c"), %%mm1              \n\t"\
+    "psraw                $3, %%mm0                           \n\t"\
+    "psraw                $3, %%mm1                           \n\t"\
+    "movq              %%mm0, "CHR_MMX_FILTER_OFFSET"+8("#c") \n\t"\
+    "movq              %%mm1, "LUM_MMX_FILTER_OFFSET"+8("#c") \n\t"\
+    "xor            "#index", "#index"                        \n\t"\
+    ".p2align              4            \n\t"\
+    "1:                                 \n\t"\
+    "movq     (%2, "#index"), %%mm2     \n\t" /* uvbuf0[eax]*/\
+    "movq     (%3, "#index"), %%mm3     \n\t" /* uvbuf1[eax]*/\
+    "movq "AV_STRINGIFY(VOF)"(%2, "#index"), %%mm5     \n\t" /* uvbuf0[eax+2048]*/\
+    "movq "AV_STRINGIFY(VOF)"(%3, "#index"), %%mm4     \n\t" /* uvbuf1[eax+2048]*/\
+    "psubw             %%mm3, %%mm2     \n\t" /* uvbuf0[eax] - uvbuf1[eax]*/\
+    "psubw             %%mm4, %%mm5     \n\t" /* uvbuf0[eax+2048] - uvbuf1[eax+2048]*/\
+    "movq "CHR_MMX_FILTER_OFFSET"+8("#c"), %%mm0    \n\t"\
+    "pmulhw            %%mm0, %%mm2     \n\t" /* (uvbuf0[eax] - uvbuf1[eax])uvalpha1>>16*/\
+    "pmulhw            %%mm0, %%mm5     \n\t" /* (uvbuf0[eax+2048] - uvbuf1[eax+2048])uvalpha1>>16*/\
+    "psraw                $7, %%mm3     \n\t" /* uvbuf0[eax] - uvbuf1[eax] >>4*/\
+    "psraw                $7, %%mm4     \n\t" /* uvbuf0[eax+2048] - uvbuf1[eax+2048] >>4*/\
+    "paddw             %%mm2, %%mm3     \n\t" /* uvbuf0[eax]uvalpha1 - uvbuf1[eax](1-uvalpha1)*/\
+    "paddw             %%mm5, %%mm4     \n\t" /* uvbuf0[eax+2048]uvalpha1 - uvbuf1[eax+2048](1-uvalpha1)*/\
+    "movq  (%0, "#index", 2), %%mm0     \n\t" /*buf0[eax]*/\
+    "movq  (%1, "#index", 2), %%mm1     \n\t" /*buf1[eax]*/\
+    "movq 8(%0, "#index", 2), %%mm6     \n\t" /*buf0[eax]*/\
+    "movq 8(%1, "#index", 2), %%mm7     \n\t" /*buf1[eax]*/\
+    "psubw             %%mm1, %%mm0     \n\t" /* buf0[eax] - buf1[eax]*/\
+    "psubw             %%mm7, %%mm6     \n\t" /* buf0[eax] - buf1[eax]*/\
+    "pmulhw "LUM_MMX_FILTER_OFFSET"+8("#c"), %%mm0  \n\t" /* (buf0[eax] - buf1[eax])yalpha1>>16*/\
+    "pmulhw "LUM_MMX_FILTER_OFFSET"+8("#c"), %%mm6  \n\t" /* (buf0[eax] - buf1[eax])yalpha1>>16*/\
+    "psraw                $7, %%mm1     \n\t" /* buf0[eax] - buf1[eax] >>4*/\
+    "psraw                $7, %%mm7     \n\t" /* buf0[eax] - buf1[eax] >>4*/\
+    "paddw             %%mm0, %%mm1     \n\t" /* buf0[eax]yalpha1 + buf1[eax](1-yalpha1) >>16*/\
+    "paddw             %%mm6, %%mm7     \n\t" /* buf0[eax]yalpha1 + buf1[eax](1-yalpha1) >>16*/\
+
+#define YSCALEYUV2PACKED(index, c)  REAL_YSCALEYUV2PACKED(index, c)
+
+#define REAL_YSCALEYUV2RGB_UV(index, c) \
+    "xor            "#index", "#index"  \n\t"\
+    ".p2align              4            \n\t"\
+    "1:                                 \n\t"\
+    "movq     (%2, "#index"), %%mm2     \n\t" /* uvbuf0[eax]*/\
+    "movq     (%3, "#index"), %%mm3     \n\t" /* uvbuf1[eax]*/\
+    "movq "AV_STRINGIFY(VOF)"(%2, "#index"), %%mm5     \n\t" /* uvbuf0[eax+2048]*/\
+    "movq "AV_STRINGIFY(VOF)"(%3, "#index"), %%mm4     \n\t" /* uvbuf1[eax+2048]*/\
+    "psubw             %%mm3, %%mm2     \n\t" /* uvbuf0[eax] - uvbuf1[eax]*/\
+    "psubw             %%mm4, %%mm5     \n\t" /* uvbuf0[eax+2048] - uvbuf1[eax+2048]*/\
+    "movq "CHR_MMX_FILTER_OFFSET"+8("#c"), %%mm0    \n\t"\
+    "pmulhw            %%mm0, %%mm2     \n\t" /* (uvbuf0[eax] - uvbuf1[eax])uvalpha1>>16*/\
+    "pmulhw            %%mm0, %%mm5     \n\t" /* (uvbuf0[eax+2048] - uvbuf1[eax+2048])uvalpha1>>16*/\
+    "psraw                $4, %%mm3     \n\t" /* uvbuf0[eax] - uvbuf1[eax] >>4*/\
+    "psraw                $4, %%mm4     \n\t" /* uvbuf0[eax+2048] - uvbuf1[eax+2048] >>4*/\
+    "paddw             %%mm2, %%mm3     \n\t" /* uvbuf0[eax]uvalpha1 - uvbuf1[eax](1-uvalpha1)*/\
+    "paddw             %%mm5, %%mm4     \n\t" /* uvbuf0[eax+2048]uvalpha1 - uvbuf1[eax+2048](1-uvalpha1)*/\
+    "psubw  "U_OFFSET"("#c"), %%mm3     \n\t" /* (U-128)8*/\
+    "psubw  "V_OFFSET"("#c"), %%mm4     \n\t" /* (V-128)8*/\
+    "movq              %%mm3, %%mm2     \n\t" /* (U-128)8*/\
+    "movq              %%mm4, %%mm5     \n\t" /* (V-128)8*/\
+    "pmulhw "UG_COEFF"("#c"), %%mm3     \n\t"\
+    "pmulhw "VG_COEFF"("#c"), %%mm4     \n\t"\
+    /* mm2=(U-128)8, mm3=ug, mm4=vg mm5=(V-128)8 */\
+
+#define REAL_YSCALEYUV2RGB_YA(index, c, b1, b2) \
+    "movq  ("#b1", "#index", 2), %%mm0     \n\t" /*buf0[eax]*/\
+    "movq  ("#b2", "#index", 2), %%mm1     \n\t" /*buf1[eax]*/\
+    "movq 8("#b1", "#index", 2), %%mm6     \n\t" /*buf0[eax]*/\
+    "movq 8("#b2", "#index", 2), %%mm7     \n\t" /*buf1[eax]*/\
+    "psubw             %%mm1, %%mm0     \n\t" /* buf0[eax] - buf1[eax]*/\
+    "psubw             %%mm7, %%mm6     \n\t" /* buf0[eax] - buf1[eax]*/\
+    "pmulhw "LUM_MMX_FILTER_OFFSET"+8("#c"), %%mm0  \n\t" /* (buf0[eax] - buf1[eax])yalpha1>>16*/\
+    "pmulhw "LUM_MMX_FILTER_OFFSET"+8("#c"), %%mm6  \n\t" /* (buf0[eax] - buf1[eax])yalpha1>>16*/\
+    "psraw                $4, %%mm1     \n\t" /* buf0[eax] - buf1[eax] >>4*/\
+    "psraw                $4, %%mm7     \n\t" /* buf0[eax] - buf1[eax] >>4*/\
+    "paddw             %%mm0, %%mm1     \n\t" /* buf0[eax]yalpha1 + buf1[eax](1-yalpha1) >>16*/\
+    "paddw             %%mm6, %%mm7     \n\t" /* buf0[eax]yalpha1 + buf1[eax](1-yalpha1) >>16*/\
+
+#define REAL_YSCALEYUV2RGB_COEFF(c) \
+    "pmulhw "UB_COEFF"("#c"), %%mm2     \n\t"\
+    "pmulhw "VR_COEFF"("#c"), %%mm5     \n\t"\
+    "psubw  "Y_OFFSET"("#c"), %%mm1     \n\t" /* 8(Y-16)*/\
+    "psubw  "Y_OFFSET"("#c"), %%mm7     \n\t" /* 8(Y-16)*/\
+    "pmulhw  "Y_COEFF"("#c"), %%mm1     \n\t"\
+    "pmulhw  "Y_COEFF"("#c"), %%mm7     \n\t"\
+    /* mm1= Y1, mm2=ub, mm3=ug, mm4=vg mm5=vr, mm7=Y2 */\
+    "paddw             %%mm3, %%mm4     \n\t"\
+    "movq              %%mm2, %%mm0     \n\t"\
+    "movq              %%mm5, %%mm6     \n\t"\
+    "movq              %%mm4, %%mm3     \n\t"\
+    "punpcklwd         %%mm2, %%mm2     \n\t"\
+    "punpcklwd         %%mm5, %%mm5     \n\t"\
+    "punpcklwd         %%mm4, %%mm4     \n\t"\
+    "paddw             %%mm1, %%mm2     \n\t"\
+    "paddw             %%mm1, %%mm5     \n\t"\
+    "paddw             %%mm1, %%mm4     \n\t"\
+    "punpckhwd         %%mm0, %%mm0     \n\t"\
+    "punpckhwd         %%mm6, %%mm6     \n\t"\
+    "punpckhwd         %%mm3, %%mm3     \n\t"\
+    "paddw             %%mm7, %%mm0     \n\t"\
+    "paddw             %%mm7, %%mm6     \n\t"\
+    "paddw             %%mm7, %%mm3     \n\t"\
+    /* mm0=B1, mm2=B2, mm3=G2, mm4=G1, mm5=R1, mm6=R2 */\
+    "packuswb          %%mm0, %%mm2     \n\t"\
+    "packuswb          %%mm6, %%mm5     \n\t"\
+    "packuswb          %%mm3, %%mm4     \n\t"\
+
+#define YSCALEYUV2RGB_YA(index, c, b1, b2) REAL_YSCALEYUV2RGB_YA(index, c, b1, b2)
+
+#define YSCALEYUV2RGB(index, c) \
+    REAL_YSCALEYUV2RGB_UV(index, c) \
+    REAL_YSCALEYUV2RGB_YA(index, c, %0, %1) \
+    REAL_YSCALEYUV2RGB_COEFF(c)
+
+#define REAL_YSCALEYUV2PACKED1(index, c) \
+    "xor            "#index", "#index"  \n\t"\
+    ".p2align              4            \n\t"\
+    "1:                                 \n\t"\
+    "movq     (%2, "#index"), %%mm3     \n\t" /* uvbuf0[eax]*/\
+    "movq "AV_STRINGIFY(VOF)"(%2, "#index"), %%mm4     \n\t" /* uvbuf0[eax+2048]*/\
+    "psraw                $7, %%mm3     \n\t" \
+    "psraw                $7, %%mm4     \n\t" \
+    "movq  (%0, "#index", 2), %%mm1     \n\t" /*buf0[eax]*/\
+    "movq 8(%0, "#index", 2), %%mm7     \n\t" /*buf0[eax]*/\
+    "psraw                $7, %%mm1     \n\t" \
+    "psraw                $7, %%mm7     \n\t" \
+
+#define YSCALEYUV2PACKED1(index, c)  REAL_YSCALEYUV2PACKED1(index, c)
+
+#define REAL_YSCALEYUV2RGB1(index, c) \
+    "xor            "#index", "#index"  \n\t"\
+    ".p2align              4            \n\t"\
+    "1:                                 \n\t"\
+    "movq     (%2, "#index"), %%mm3     \n\t" /* uvbuf0[eax]*/\
+    "movq "AV_STRINGIFY(VOF)"(%2, "#index"), %%mm4     \n\t" /* uvbuf0[eax+2048]*/\
+    "psraw                $4, %%mm3     \n\t" /* uvbuf0[eax] - uvbuf1[eax] >>4*/\
+    "psraw                $4, %%mm4     \n\t" /* uvbuf0[eax+2048] - uvbuf1[eax+2048] >>4*/\
+    "psubw  "U_OFFSET"("#c"), %%mm3     \n\t" /* (U-128)8*/\
+    "psubw  "V_OFFSET"("#c"), %%mm4     \n\t" /* (V-128)8*/\
+    "movq              %%mm3, %%mm2     \n\t" /* (U-128)8*/\
+    "movq              %%mm4, %%mm5     \n\t" /* (V-128)8*/\
+    "pmulhw "UG_COEFF"("#c"), %%mm3     \n\t"\
+    "pmulhw "VG_COEFF"("#c"), %%mm4     \n\t"\
+    /* mm2=(U-128)8, mm3=ug, mm4=vg mm5=(V-128)8 */\
+    "movq  (%0, "#index", 2), %%mm1     \n\t" /*buf0[eax]*/\
+    "movq 8(%0, "#index", 2), %%mm7     \n\t" /*buf0[eax]*/\
+    "psraw                $4, %%mm1     \n\t" /* buf0[eax] - buf1[eax] >>4*/\
+    "psraw                $4, %%mm7     \n\t" /* buf0[eax] - buf1[eax] >>4*/\
+    "pmulhw "UB_COEFF"("#c"), %%mm2     \n\t"\
+    "pmulhw "VR_COEFF"("#c"), %%mm5     \n\t"\
+    "psubw  "Y_OFFSET"("#c"), %%mm1     \n\t" /* 8(Y-16)*/\
+    "psubw  "Y_OFFSET"("#c"), %%mm7     \n\t" /* 8(Y-16)*/\
+    "pmulhw  "Y_COEFF"("#c"), %%mm1     \n\t"\
+    "pmulhw  "Y_COEFF"("#c"), %%mm7     \n\t"\
+    /* mm1= Y1, mm2=ub, mm3=ug, mm4=vg mm5=vr, mm7=Y2 */\
+    "paddw             %%mm3, %%mm4     \n\t"\
+    "movq              %%mm2, %%mm0     \n\t"\
+    "movq              %%mm5, %%mm6     \n\t"\
+    "movq              %%mm4, %%mm3     \n\t"\
+    "punpcklwd         %%mm2, %%mm2     \n\t"\
+    "punpcklwd         %%mm5, %%mm5     \n\t"\
+    "punpcklwd         %%mm4, %%mm4     \n\t"\
+    "paddw             %%mm1, %%mm2     \n\t"\
+    "paddw             %%mm1, %%mm5     \n\t"\
+    "paddw             %%mm1, %%mm4     \n\t"\
+    "punpckhwd         %%mm0, %%mm0     \n\t"\
+    "punpckhwd         %%mm6, %%mm6     \n\t"\
+    "punpckhwd         %%mm3, %%mm3     \n\t"\
+    "paddw             %%mm7, %%mm0     \n\t"\
+    "paddw             %%mm7, %%mm6     \n\t"\
+    "paddw             %%mm7, %%mm3     \n\t"\
+    /* mm0=B1, mm2=B2, mm3=G2, mm4=G1, mm5=R1, mm6=R2 */\
+    "packuswb          %%mm0, %%mm2     \n\t"\
+    "packuswb          %%mm6, %%mm5     \n\t"\
+    "packuswb          %%mm3, %%mm4     \n\t"\
+
+#define YSCALEYUV2RGB1(index, c)  REAL_YSCALEYUV2RGB1(index, c)
+
+#define REAL_YSCALEYUV2PACKED1b(index, c) \
+    "xor "#index", "#index"             \n\t"\
+    ".p2align              4            \n\t"\
+    "1:                                 \n\t"\
+    "movq     (%2, "#index"), %%mm2     \n\t" /* uvbuf0[eax]*/\
+    "movq     (%3, "#index"), %%mm3     \n\t" /* uvbuf1[eax]*/\
+    "movq "AV_STRINGIFY(VOF)"(%2, "#index"), %%mm5     \n\t" /* uvbuf0[eax+2048]*/\
+    "movq "AV_STRINGIFY(VOF)"(%3, "#index"), %%mm4     \n\t" /* uvbuf1[eax+2048]*/\
+    "paddw             %%mm2, %%mm3     \n\t" /* uvbuf0[eax] + uvbuf1[eax]*/\
+    "paddw             %%mm5, %%mm4     \n\t" /* uvbuf0[eax+2048] + uvbuf1[eax+2048]*/\
+    "psrlw                $8, %%mm3     \n\t" \
+    "psrlw                $8, %%mm4     \n\t" \
+    "movq  (%0, "#index", 2), %%mm1     \n\t" /*buf0[eax]*/\
+    "movq 8(%0, "#index", 2), %%mm7     \n\t" /*buf0[eax]*/\
+    "psraw                $7, %%mm1     \n\t" \
+    "psraw                $7, %%mm7     \n\t"
+#define YSCALEYUV2PACKED1b(index, c)  REAL_YSCALEYUV2PACKED1b(index, c)
+
+// do vertical chrominance interpolation
+#define REAL_YSCALEYUV2RGB1b(index, c) \
+    "xor            "#index", "#index"  \n\t"\
+    ".p2align              4            \n\t"\
+    "1:                                 \n\t"\
+    "movq     (%2, "#index"), %%mm2     \n\t" /* uvbuf0[eax]*/\
+    "movq     (%3, "#index"), %%mm3     \n\t" /* uvbuf1[eax]*/\
+    "movq "AV_STRINGIFY(VOF)"(%2, "#index"), %%mm5     \n\t" /* uvbuf0[eax+2048]*/\
+    "movq "AV_STRINGIFY(VOF)"(%3, "#index"), %%mm4     \n\t" /* uvbuf1[eax+2048]*/\
+    "paddw             %%mm2, %%mm3     \n\t" /* uvbuf0[eax] + uvbuf1[eax]*/\
+    "paddw             %%mm5, %%mm4     \n\t" /* uvbuf0[eax+2048] + uvbuf1[eax+2048]*/\
+    "psrlw                $5, %%mm3     \n\t" /*FIXME might overflow*/\
+    "psrlw                $5, %%mm4     \n\t" /*FIXME might overflow*/\
+    "psubw  "U_OFFSET"("#c"), %%mm3     \n\t" /* (U-128)8*/\
+    "psubw  "V_OFFSET"("#c"), %%mm4     \n\t" /* (V-128)8*/\
+    "movq              %%mm3, %%mm2     \n\t" /* (U-128)8*/\
+    "movq              %%mm4, %%mm5     \n\t" /* (V-128)8*/\
+    "pmulhw "UG_COEFF"("#c"), %%mm3     \n\t"\
+    "pmulhw "VG_COEFF"("#c"), %%mm4     \n\t"\
+    /* mm2=(U-128)8, mm3=ug, mm4=vg mm5=(V-128)8 */\
+    "movq  (%0, "#index", 2), %%mm1     \n\t" /*buf0[eax]*/\
+    "movq 8(%0, "#index", 2), %%mm7     \n\t" /*buf0[eax]*/\
+    "psraw                $4, %%mm1     \n\t" /* buf0[eax] - buf1[eax] >>4*/\
+    "psraw                $4, %%mm7     \n\t" /* buf0[eax] - buf1[eax] >>4*/\
+    "pmulhw "UB_COEFF"("#c"), %%mm2     \n\t"\
+    "pmulhw "VR_COEFF"("#c"), %%mm5     \n\t"\
+    "psubw  "Y_OFFSET"("#c"), %%mm1     \n\t" /* 8(Y-16)*/\
+    "psubw  "Y_OFFSET"("#c"), %%mm7     \n\t" /* 8(Y-16)*/\
+    "pmulhw  "Y_COEFF"("#c"), %%mm1     \n\t"\
+    "pmulhw  "Y_COEFF"("#c"), %%mm7     \n\t"\
+    /* mm1= Y1, mm2=ub, mm3=ug, mm4=vg mm5=vr, mm7=Y2 */\
+    "paddw             %%mm3, %%mm4     \n\t"\
+    "movq              %%mm2, %%mm0     \n\t"\
+    "movq              %%mm5, %%mm6     \n\t"\
+    "movq              %%mm4, %%mm3     \n\t"\
+    "punpcklwd         %%mm2, %%mm2     \n\t"\
+    "punpcklwd         %%mm5, %%mm5     \n\t"\
+    "punpcklwd         %%mm4, %%mm4     \n\t"\
+    "paddw             %%mm1, %%mm2     \n\t"\
+    "paddw             %%mm1, %%mm5     \n\t"\
+    "paddw             %%mm1, %%mm4     \n\t"\
+    "punpckhwd         %%mm0, %%mm0     \n\t"\
+    "punpckhwd         %%mm6, %%mm6     \n\t"\
+    "punpckhwd         %%mm3, %%mm3     \n\t"\
+    "paddw             %%mm7, %%mm0     \n\t"\
+    "paddw             %%mm7, %%mm6     \n\t"\
+    "paddw             %%mm7, %%mm3     \n\t"\
+    /* mm0=B1, mm2=B2, mm3=G2, mm4=G1, mm5=R1, mm6=R2 */\
+    "packuswb          %%mm0, %%mm2     \n\t"\
+    "packuswb          %%mm6, %%mm5     \n\t"\
+    "packuswb          %%mm3, %%mm4     \n\t"\
+
+#define YSCALEYUV2RGB1b(index, c)  REAL_YSCALEYUV2RGB1b(index, c)
+
+#define REAL_YSCALEYUV2RGB1_ALPHA(index) \
+    "movq  (%1, "#index", 2), %%mm7     \n\t" /* abuf0[index  ]     */\
+    "movq 8(%1, "#index", 2), %%mm1     \n\t" /* abuf0[index+4]     */\
+    "psraw                $7, %%mm7     \n\t" /* abuf0[index  ] >>7 */\
+    "psraw                $7, %%mm1     \n\t" /* abuf0[index+4] >>7 */\
+    "packuswb          %%mm1, %%mm7     \n\t"
+#define YSCALEYUV2RGB1_ALPHA(index) REAL_YSCALEYUV2RGB1_ALPHA(index)
+
+#define REAL_WRITEBGR32(dst, dstw, index, b, g, r, a, q0, q2, q3, t) \
+    "movq       "#b", "#q2"     \n\t" /* B */\
+    "movq       "#r", "#t"      \n\t" /* R */\
+    "punpcklbw  "#g", "#b"      \n\t" /* GBGBGBGB 0 */\
+    "punpcklbw  "#a", "#r"      \n\t" /* ARARARAR 0 */\
+    "punpckhbw  "#g", "#q2"     \n\t" /* GBGBGBGB 2 */\
+    "punpckhbw  "#a", "#t"      \n\t" /* ARARARAR 2 */\
+    "movq       "#b", "#q0"     \n\t" /* GBGBGBGB 0 */\
+    "movq      "#q2", "#q3"     \n\t" /* GBGBGBGB 2 */\
+    "punpcklwd  "#r", "#q0"     \n\t" /* ARGBARGB 0 */\
+    "punpckhwd  "#r", "#b"      \n\t" /* ARGBARGB 1 */\
+    "punpcklwd  "#t", "#q2"     \n\t" /* ARGBARGB 2 */\
+    "punpckhwd  "#t", "#q3"     \n\t" /* ARGBARGB 3 */\
+\
+    MOVNTQ(   q0,   (dst, index, 4))\
+    MOVNTQ(    b,  8(dst, index, 4))\
+    MOVNTQ(   q2, 16(dst, index, 4))\
+    MOVNTQ(   q3, 24(dst, index, 4))\
+\
+    "add      $8, "#index"      \n\t"\
+    "cmp "#dstw", "#index"      \n\t"\
+    " jb      1b                \n\t"
+#define WRITEBGR32(dst, dstw, index, b, g, r, a, q0, q2, q3, t)  REAL_WRITEBGR32(dst, dstw, index, b, g, r, a, q0, q2, q3, t)
+
+#define REAL_WRITERGB16(dst, dstw, index) \
+    "pand "MANGLE(bF8)", %%mm2  \n\t" /* B */\
+    "pand "MANGLE(bFC)", %%mm4  \n\t" /* G */\
+    "pand "MANGLE(bF8)", %%mm5  \n\t" /* R */\
+    "psrlq           $3, %%mm2  \n\t"\
+\
+    "movq         %%mm2, %%mm1  \n\t"\
+    "movq         %%mm4, %%mm3  \n\t"\
+\
+    "punpcklbw    %%mm7, %%mm3  \n\t"\
+    "punpcklbw    %%mm5, %%mm2  \n\t"\
+    "punpckhbw    %%mm7, %%mm4  \n\t"\
+    "punpckhbw    %%mm5, %%mm1  \n\t"\
+\
+    "psllq           $3, %%mm3  \n\t"\
+    "psllq           $3, %%mm4  \n\t"\
+\
+    "por          %%mm3, %%mm2  \n\t"\
+    "por          %%mm4, %%mm1  \n\t"\
+\
+    MOVNTQ(%%mm2,  (dst, index, 2))\
+    MOVNTQ(%%mm1, 8(dst, index, 2))\
+\
+    "add             $8, "#index"   \n\t"\
+    "cmp        "#dstw", "#index"   \n\t"\
+    " jb             1b             \n\t"
+#define WRITERGB16(dst, dstw, index)  REAL_WRITERGB16(dst, dstw, index)
+
+#define REAL_WRITERGB15(dst, dstw, index) \
+    "pand "MANGLE(bF8)", %%mm2  \n\t" /* B */\
+    "pand "MANGLE(bF8)", %%mm4  \n\t" /* G */\
+    "pand "MANGLE(bF8)", %%mm5  \n\t" /* R */\
+    "psrlq           $3, %%mm2  \n\t"\
+    "psrlq           $1, %%mm5  \n\t"\
+\
+    "movq         %%mm2, %%mm1  \n\t"\
+    "movq         %%mm4, %%mm3  \n\t"\
+\
+    "punpcklbw    %%mm7, %%mm3  \n\t"\
+    "punpcklbw    %%mm5, %%mm2  \n\t"\
+    "punpckhbw    %%mm7, %%mm4  \n\t"\
+    "punpckhbw    %%mm5, %%mm1  \n\t"\
+\
+    "psllq           $2, %%mm3  \n\t"\
+    "psllq           $2, %%mm4  \n\t"\
+\
+    "por          %%mm3, %%mm2  \n\t"\
+    "por          %%mm4, %%mm1  \n\t"\
+\
+    MOVNTQ(%%mm2,  (dst, index, 2))\
+    MOVNTQ(%%mm1, 8(dst, index, 2))\
+\
+    "add             $8, "#index"   \n\t"\
+    "cmp        "#dstw", "#index"   \n\t"\
+    " jb             1b             \n\t"
+#define WRITERGB15(dst, dstw, index)  REAL_WRITERGB15(dst, dstw, index)
+
+#define WRITEBGR24OLD(dst, dstw, index) \
+    /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */\
+    "movq      %%mm2, %%mm1             \n\t" /* B */\
+    "movq      %%mm5, %%mm6             \n\t" /* R */\
+    "punpcklbw %%mm4, %%mm2             \n\t" /* GBGBGBGB 0 */\
+    "punpcklbw %%mm7, %%mm5             \n\t" /* 0R0R0R0R 0 */\
+    "punpckhbw %%mm4, %%mm1             \n\t" /* GBGBGBGB 2 */\
+    "punpckhbw %%mm7, %%mm6             \n\t" /* 0R0R0R0R 2 */\
+    "movq      %%mm2, %%mm0             \n\t" /* GBGBGBGB 0 */\
+    "movq      %%mm1, %%mm3             \n\t" /* GBGBGBGB 2 */\
+    "punpcklwd %%mm5, %%mm0             \n\t" /* 0RGB0RGB 0 */\
+    "punpckhwd %%mm5, %%mm2             \n\t" /* 0RGB0RGB 1 */\
+    "punpcklwd %%mm6, %%mm1             \n\t" /* 0RGB0RGB 2 */\
+    "punpckhwd %%mm6, %%mm3             \n\t" /* 0RGB0RGB 3 */\
+\
+    "movq      %%mm0, %%mm4             \n\t" /* 0RGB0RGB 0 */\
+    "psrlq        $8, %%mm0             \n\t" /* 00RGB0RG 0 */\
+    "pand "MANGLE(bm00000111)", %%mm4   \n\t" /* 00000RGB 0 */\
+    "pand "MANGLE(bm11111000)", %%mm0   \n\t" /* 00RGB000 0.5 */\
+    "por       %%mm4, %%mm0             \n\t" /* 00RGBRGB 0 */\
+    "movq      %%mm2, %%mm4             \n\t" /* 0RGB0RGB 1 */\
+    "psllq       $48, %%mm2             \n\t" /* GB000000 1 */\
+    "por       %%mm2, %%mm0             \n\t" /* GBRGBRGB 0 */\
+\
+    "movq      %%mm4, %%mm2             \n\t" /* 0RGB0RGB 1 */\
+    "psrld       $16, %%mm4             \n\t" /* 000R000R 1 */\
+    "psrlq       $24, %%mm2             \n\t" /* 0000RGB0 1.5 */\
+    "por       %%mm4, %%mm2             \n\t" /* 000RRGBR 1 */\
+    "pand "MANGLE(bm00001111)", %%mm2   \n\t" /* 0000RGBR 1 */\
+    "movq      %%mm1, %%mm4             \n\t" /* 0RGB0RGB 2 */\
+    "psrlq        $8, %%mm1             \n\t" /* 00RGB0RG 2 */\
+    "pand "MANGLE(bm00000111)", %%mm4   \n\t" /* 00000RGB 2 */\
+    "pand "MANGLE(bm11111000)", %%mm1   \n\t" /* 00RGB000 2.5 */\
+    "por       %%mm4, %%mm1             \n\t" /* 00RGBRGB 2 */\
+    "movq      %%mm1, %%mm4             \n\t" /* 00RGBRGB 2 */\
+    "psllq       $32, %%mm1             \n\t" /* BRGB0000 2 */\
+    "por       %%mm1, %%mm2             \n\t" /* BRGBRGBR 1 */\
+\
+    "psrlq       $32, %%mm4             \n\t" /* 000000RG 2.5 */\
+    "movq      %%mm3, %%mm5             \n\t" /* 0RGB0RGB 3 */\
+    "psrlq        $8, %%mm3             \n\t" /* 00RGB0RG 3 */\
+    "pand "MANGLE(bm00000111)", %%mm5   \n\t" /* 00000RGB 3 */\
+    "pand "MANGLE(bm11111000)", %%mm3   \n\t" /* 00RGB000 3.5 */\
+    "por       %%mm5, %%mm3             \n\t" /* 00RGBRGB 3 */\
+    "psllq       $16, %%mm3             \n\t" /* RGBRGB00 3 */\
+    "por       %%mm4, %%mm3             \n\t" /* RGBRGBRG 2.5 */\
+\
+    MOVNTQ(%%mm0,   (dst))\
+    MOVNTQ(%%mm2,  8(dst))\
+    MOVNTQ(%%mm3, 16(dst))\
+    "add         $24, "#dst"            \n\t"\
+\
+    "add          $8, "#index"          \n\t"\
+    "cmp     "#dstw", "#index"          \n\t"\
+    " jb          1b                    \n\t"
+
+#define WRITEBGR24MMX(dst, dstw, index) \
+    /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */\
+    "movq      %%mm2, %%mm1     \n\t" /* B */\
+    "movq      %%mm5, %%mm6     \n\t" /* R */\
+    "punpcklbw %%mm4, %%mm2     \n\t" /* GBGBGBGB 0 */\
+    "punpcklbw %%mm7, %%mm5     \n\t" /* 0R0R0R0R 0 */\
+    "punpckhbw %%mm4, %%mm1     \n\t" /* GBGBGBGB 2 */\
+    "punpckhbw %%mm7, %%mm6     \n\t" /* 0R0R0R0R 2 */\
+    "movq      %%mm2, %%mm0     \n\t" /* GBGBGBGB 0 */\
+    "movq      %%mm1, %%mm3     \n\t" /* GBGBGBGB 2 */\
+    "punpcklwd %%mm5, %%mm0     \n\t" /* 0RGB0RGB 0 */\
+    "punpckhwd %%mm5, %%mm2     \n\t" /* 0RGB0RGB 1 */\
+    "punpcklwd %%mm6, %%mm1     \n\t" /* 0RGB0RGB 2 */\
+    "punpckhwd %%mm6, %%mm3     \n\t" /* 0RGB0RGB 3 */\
+\
+    "movq      %%mm0, %%mm4     \n\t" /* 0RGB0RGB 0 */\
+    "movq      %%mm2, %%mm6     \n\t" /* 0RGB0RGB 1 */\
+    "movq      %%mm1, %%mm5     \n\t" /* 0RGB0RGB 2 */\
+    "movq      %%mm3, %%mm7     \n\t" /* 0RGB0RGB 3 */\
+\
+    "psllq       $40, %%mm0     \n\t" /* RGB00000 0 */\
+    "psllq       $40, %%mm2     \n\t" /* RGB00000 1 */\
+    "psllq       $40, %%mm1     \n\t" /* RGB00000 2 */\
+    "psllq       $40, %%mm3     \n\t" /* RGB00000 3 */\
+\
+    "punpckhdq %%mm4, %%mm0     \n\t" /* 0RGBRGB0 0 */\
+    "punpckhdq %%mm6, %%mm2     \n\t" /* 0RGBRGB0 1 */\
+    "punpckhdq %%mm5, %%mm1     \n\t" /* 0RGBRGB0 2 */\
+    "punpckhdq %%mm7, %%mm3     \n\t" /* 0RGBRGB0 3 */\
+\
+    "psrlq        $8, %%mm0     \n\t" /* 00RGBRGB 0 */\
+    "movq      %%mm2, %%mm6     \n\t" /* 0RGBRGB0 1 */\
+    "psllq       $40, %%mm2     \n\t" /* GB000000 1 */\
+    "por       %%mm2, %%mm0     \n\t" /* GBRGBRGB 0 */\
+    MOVNTQ(%%mm0, (dst))\
+\
+    "psrlq       $24, %%mm6     \n\t" /* 0000RGBR 1 */\
+    "movq      %%mm1, %%mm5     \n\t" /* 0RGBRGB0 2 */\
+    "psllq       $24, %%mm1     \n\t" /* BRGB0000 2 */\
+    "por       %%mm1, %%mm6     \n\t" /* BRGBRGBR 1 */\
+    MOVNTQ(%%mm6, 8(dst))\
+\
+    "psrlq       $40, %%mm5     \n\t" /* 000000RG 2 */\
+    "psllq        $8, %%mm3     \n\t" /* RGBRGB00 3 */\
+    "por       %%mm3, %%mm5     \n\t" /* RGBRGBRG 2 */\
+    MOVNTQ(%%mm5, 16(dst))\
+\
+    "add         $24, "#dst"    \n\t"\
+\
+    "add          $8, "#index"  \n\t"\
+    "cmp     "#dstw", "#index"  \n\t"\
+    " jb          1b            \n\t"
+
+#define WRITEBGR24MMX2(dst, dstw, index) \
+    /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */\
+    "movq "MANGLE(ff_M24A)", %%mm0 \n\t"\
+    "movq "MANGLE(ff_M24C)", %%mm7 \n\t"\
+    "pshufw $0x50, %%mm2, %%mm1 \n\t" /* B3 B2 B3 B2  B1 B0 B1 B0 */\
+    "pshufw $0x50, %%mm4, %%mm3 \n\t" /* G3 G2 G3 G2  G1 G0 G1 G0 */\
+    "pshufw $0x00, %%mm5, %%mm6 \n\t" /* R1 R0 R1 R0  R1 R0 R1 R0 */\
+\
+    "pand   %%mm0, %%mm1        \n\t" /*    B2        B1       B0 */\
+    "pand   %%mm0, %%mm3        \n\t" /*    G2        G1       G0 */\
+    "pand   %%mm7, %%mm6        \n\t" /*       R1        R0       */\
+\
+    "psllq     $8, %%mm3        \n\t" /* G2        G1       G0    */\
+    "por    %%mm1, %%mm6        \n\t"\
+    "por    %%mm3, %%mm6        \n\t"\
+    MOVNTQ(%%mm6, (dst))\
+\
+    "psrlq     $8, %%mm4        \n\t" /* 00 G7 G6 G5  G4 G3 G2 G1 */\
+    "pshufw $0xA5, %%mm2, %%mm1 \n\t" /* B5 B4 B5 B4  B3 B2 B3 B2 */\
+    "pshufw $0x55, %%mm4, %%mm3 \n\t" /* G4 G3 G4 G3  G4 G3 G4 G3 */\
+    "pshufw $0xA5, %%mm5, %%mm6 \n\t" /* R5 R4 R5 R4  R3 R2 R3 R2 */\
+\
+    "pand "MANGLE(ff_M24B)", %%mm1 \n\t" /* B5       B4        B3    */\
+    "pand   %%mm7, %%mm3        \n\t" /*       G4        G3       */\
+    "pand   %%mm0, %%mm6        \n\t" /*    R4        R3       R2 */\
+\
+    "por    %%mm1, %%mm3        \n\t" /* B5    G4 B4     G3 B3    */\
+    "por    %%mm3, %%mm6        \n\t"\
+    MOVNTQ(%%mm6, 8(dst))\
+\
+    "pshufw $0xFF, %%mm2, %%mm1 \n\t" /* B7 B6 B7 B6  B7 B6 B6 B7 */\
+    "pshufw $0xFA, %%mm4, %%mm3 \n\t" /* 00 G7 00 G7  G6 G5 G6 G5 */\
+    "pshufw $0xFA, %%mm5, %%mm6 \n\t" /* R7 R6 R7 R6  R5 R4 R5 R4 */\
+\
+    "pand   %%mm7, %%mm1        \n\t" /*       B7        B6       */\
+    "pand   %%mm0, %%mm3        \n\t" /*    G7        G6       G5 */\
+    "pand "MANGLE(ff_M24B)", %%mm6 \n\t" /* R7       R6        R5    */\
+\
+    "por    %%mm1, %%mm3        \n\t"\
+    "por    %%mm3, %%mm6        \n\t"\
+    MOVNTQ(%%mm6, 16(dst))\
+\
+    "add      $24, "#dst"       \n\t"\
+\
+    "add       $8, "#index"     \n\t"\
+    "cmp  "#dstw", "#index"     \n\t"\
+    " jb       1b               \n\t"
+
+#if COMPILE_TEMPLATE_MMX2
+#undef WRITEBGR24
+#define WRITEBGR24(dst, dstw, index)  WRITEBGR24MMX2(dst, dstw, index)
+#else
+#undef WRITEBGR24
+#define WRITEBGR24(dst, dstw, index)  WRITEBGR24MMX(dst, dstw, index)
+#endif
+
+#define REAL_WRITEYUY2(dst, dstw, index) \
+    "packuswb  %%mm3, %%mm3     \n\t"\
+    "packuswb  %%mm4, %%mm4     \n\t"\
+    "packuswb  %%mm7, %%mm1     \n\t"\
+    "punpcklbw %%mm4, %%mm3     \n\t"\
+    "movq      %%mm1, %%mm7     \n\t"\
+    "punpcklbw %%mm3, %%mm1     \n\t"\
+    "punpckhbw %%mm3, %%mm7     \n\t"\
+\
+    MOVNTQ(%%mm1, (dst, index, 2))\
+    MOVNTQ(%%mm7, 8(dst, index, 2))\
+\
+    "add          $8, "#index"  \n\t"\
+    "cmp     "#dstw", "#index"  \n\t"\
+    " jb          1b            \n\t"
+#define WRITEYUY2(dst, dstw, index)  REAL_WRITEYUY2(dst, dstw, index)
+
+
+static inline void RENAME(yuv2yuvX)(SwsContext *c, const int16_t *lumFilter, const int16_t **lumSrc, int lumFilterSize,
+                                    const int16_t *chrFilter, const int16_t **chrSrc, int chrFilterSize, const int16_t **alpSrc,
+                                    uint8_t *dest, uint8_t *uDest, uint8_t *vDest, uint8_t *aDest, long dstW, long chrDstW)
+{
+    if(!(c->flags & SWS_BITEXACT)) {
+        if (c->flags & SWS_ACCURATE_RND) {
+            if (uDest) {
+                YSCALEYUV2YV12X_ACCURATE(   "0", CHR_MMX_FILTER_OFFSET, uDest, chrDstW)
+                YSCALEYUV2YV12X_ACCURATE(AV_STRINGIFY(VOF), CHR_MMX_FILTER_OFFSET, vDest, chrDstW)
+            }
+            if (CONFIG_SWSCALE_ALPHA && aDest) {
+                YSCALEYUV2YV12X_ACCURATE(   "0", ALP_MMX_FILTER_OFFSET, aDest, dstW)
+            }
+
+            YSCALEYUV2YV12X_ACCURATE("0", LUM_MMX_FILTER_OFFSET, dest, dstW)
+        } else {
+            if (uDest) {
+                YSCALEYUV2YV12X(   "0", CHR_MMX_FILTER_OFFSET, uDest, chrDstW)
+                YSCALEYUV2YV12X(AV_STRINGIFY(VOF), CHR_MMX_FILTER_OFFSET, vDest, chrDstW)
+            }
+            if (CONFIG_SWSCALE_ALPHA && aDest) {
+                YSCALEYUV2YV12X(   "0", ALP_MMX_FILTER_OFFSET, aDest, dstW)
+            }
+
+            YSCALEYUV2YV12X("0", LUM_MMX_FILTER_OFFSET, dest, dstW)
+        }
+        return;
+    }
+    yuv2yuvXinC(lumFilter, lumSrc, lumFilterSize,
+                chrFilter, chrSrc, chrFilterSize,
+                alpSrc, dest, uDest, vDest, aDest, dstW, chrDstW);
+}
+
+static inline void RENAME(yuv2nv12X)(SwsContext *c, const int16_t *lumFilter, const int16_t **lumSrc, int lumFilterSize,
+                                     const int16_t *chrFilter, const int16_t **chrSrc, int chrFilterSize,
+                                     uint8_t *dest, uint8_t *uDest, int dstW, int chrDstW, enum PixelFormat dstFormat)
+{
+    yuv2nv12XinC(lumFilter, lumSrc, lumFilterSize,
+                 chrFilter, chrSrc, chrFilterSize,
+                 dest, uDest, dstW, chrDstW, dstFormat);
+}
+
+static inline void RENAME(yuv2yuv1)(SwsContext *c, const int16_t *lumSrc, const int16_t *chrSrc, const int16_t *alpSrc,
+                                    uint8_t *dest, uint8_t *uDest, uint8_t *vDest, uint8_t *aDest, long dstW, long chrDstW)
+{
+    int i;
+    if(!(c->flags & SWS_BITEXACT)) {
+        long p= 4;
+        const uint8_t *src[4]= {alpSrc + dstW, lumSrc + dstW, chrSrc + chrDstW, chrSrc + VOFW + chrDstW};
+        uint8_t *dst[4]= {aDest, dest, uDest, vDest};
+        x86_reg counter[4]= {dstW, dstW, chrDstW, chrDstW};
+
+        if (c->flags & SWS_ACCURATE_RND) {
+            while(p--) {
+                if (dst[p]) {
+                    __asm__ volatile(
+                        YSCALEYUV2YV121_ACCURATE
+                        :: "r" (src[p]), "r" (dst[p] + counter[p]),
+                        "g" (-counter[p])
+                        : "%"REG_a
+                    );
+                }
+            }
+        } else {
+            while(p--) {
+                if (dst[p]) {
+                    __asm__ volatile(
+                        YSCALEYUV2YV121
+                        :: "r" (src[p]), "r" (dst[p] + counter[p]),
+                        "g" (-counter[p])
+                        : "%"REG_a
+                    );
+                }
+            }
+        }
+        return;
+    }
+    for (i=0; i<dstW; i++) {
+        int val= (lumSrc[i]+64)>>7;
+
+        if (val&256) {
+            if (val<0) val=0;
+            else       val=255;
+        }
+
+        dest[i]= val;
+    }
+
+    if (uDest)
+        for (i=0; i<chrDstW; i++) {
+            int u=(chrSrc[i       ]+64)>>7;
+            int v=(chrSrc[i + VOFW]+64)>>7;
+
+            if ((u|v)&256) {
+                if (u<0)        u=0;
+                else if (u>255) u=255;
+                if (v<0)        v=0;
+                else if (v>255) v=255;
+            }
+
+            uDest[i]= u;
+            vDest[i]= v;
+        }
+
+    if (CONFIG_SWSCALE_ALPHA && aDest)
+        for (i=0; i<dstW; i++) {
+            int val= (alpSrc[i]+64)>>7;
+            aDest[i]= av_clip_uint8(val);
+        }
+}
+
+
+/**
+ * vertical scale YV12 to RGB
+ */
+static inline void RENAME(yuv2packedX)(SwsContext *c, const int16_t *lumFilter, const int16_t **lumSrc, int lumFilterSize,
+                                       const int16_t *chrFilter, const int16_t **chrSrc, int chrFilterSize,
+                                       const int16_t **alpSrc, uint8_t *dest, long dstW, long dstY)
+{
+    x86_reg dummy=0;
+    x86_reg dstW_reg = dstW;
+    if(!(c->flags & SWS_BITEXACT)) {
+        if (c->flags & SWS_ACCURATE_RND) {
+            switch(c->dstFormat) {
+            case PIX_FMT_RGB32:
+                if (CONFIG_SWSCALE_ALPHA && c->alpPixBuf) {
+                    YSCALEYUV2PACKEDX_ACCURATE
+                    YSCALEYUV2RGBX
+                    "movq                      %%mm2, "U_TEMP"(%0)  \n\t"
+                    "movq                      %%mm4, "V_TEMP"(%0)  \n\t"
+                    "movq                      %%mm5, "Y_TEMP"(%0)  \n\t"
+                    YSCALEYUV2PACKEDX_ACCURATE_YA(ALP_MMX_FILTER_OFFSET)
+                    "movq               "Y_TEMP"(%0), %%mm5         \n\t"
+                    "psraw                        $3, %%mm1         \n\t"
+                    "psraw                        $3, %%mm7         \n\t"
+                    "packuswb                  %%mm7, %%mm1         \n\t"
+                    WRITEBGR32(%4, %5, %%REGa, %%mm3, %%mm4, %%mm5, %%mm1, %%mm0, %%mm7, %%mm2, %%mm6)
+
+                    YSCALEYUV2PACKEDX_END
+                } else {
+                    YSCALEYUV2PACKEDX_ACCURATE
+                    YSCALEYUV2RGBX
+                    "pcmpeqd %%mm7, %%mm7 \n\t"
+                    WRITEBGR32(%4, %5, %%REGa, %%mm2, %%mm4, %%mm5, %%mm7, %%mm0, %%mm1, %%mm3, %%mm6)
+
+                    YSCALEYUV2PACKEDX_END
+                }
+                return;
+            case PIX_FMT_BGR24:
+                YSCALEYUV2PACKEDX_ACCURATE
+                YSCALEYUV2RGBX
+                "pxor %%mm7, %%mm7 \n\t"
+                "lea (%%"REG_a", %%"REG_a", 2), %%"REG_c"\n\t" //FIXME optimize
+                "add %4, %%"REG_c"                        \n\t"
+                WRITEBGR24(%%REGc, %5, %%REGa)
+
+
+                :: "r" (&c->redDither),
+                "m" (dummy), "m" (dummy), "m" (dummy),
+                "r" (dest), "m" (dstW_reg)
+                : "%"REG_a, "%"REG_c, "%"REG_d, "%"REG_S
+                );
+                return;
+            case PIX_FMT_RGB555:
+                YSCALEYUV2PACKEDX_ACCURATE
+                YSCALEYUV2RGBX
+                "pxor %%mm7, %%mm7 \n\t"
+                /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */
+#ifdef DITHER1XBPP
+                "paddusb "BLUE_DITHER"(%0), %%mm2\n\t"
+                "paddusb "GREEN_DITHER"(%0), %%mm4\n\t"
+                "paddusb "RED_DITHER"(%0), %%mm5\n\t"
+#endif
+
+                WRITERGB15(%4, %5, %%REGa)
+                YSCALEYUV2PACKEDX_END
+                return;
+            case PIX_FMT_RGB565:
+                YSCALEYUV2PACKEDX_ACCURATE
+                YSCALEYUV2RGBX
+                "pxor %%mm7, %%mm7 \n\t"
+                /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */
+#ifdef DITHER1XBPP
+                "paddusb "BLUE_DITHER"(%0), %%mm2\n\t"
+                "paddusb "GREEN_DITHER"(%0), %%mm4\n\t"
+                "paddusb "RED_DITHER"(%0), %%mm5\n\t"
+#endif
+
+                WRITERGB16(%4, %5, %%REGa)
+                YSCALEYUV2PACKEDX_END
+                return;
+            case PIX_FMT_YUYV422:
+                YSCALEYUV2PACKEDX_ACCURATE
+                /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */
+
+                "psraw $3, %%mm3    \n\t"
+                "psraw $3, %%mm4    \n\t"
+                "psraw $3, %%mm1    \n\t"
+                "psraw $3, %%mm7    \n\t"
+                WRITEYUY2(%4, %5, %%REGa)
+                YSCALEYUV2PACKEDX_END
+                return;
+            }
+        } else {
+            switch(c->dstFormat) {
+            case PIX_FMT_RGB32:
+                if (CONFIG_SWSCALE_ALPHA && c->alpPixBuf) {
+                    YSCALEYUV2PACKEDX
+                    YSCALEYUV2RGBX
+                    YSCALEYUV2PACKEDX_YA(ALP_MMX_FILTER_OFFSET, %%mm0, %%mm3, %%mm6, %%mm1, %%mm7)
+                    "psraw                        $3, %%mm1         \n\t"
+                    "psraw                        $3, %%mm7         \n\t"
+                    "packuswb                  %%mm7, %%mm1         \n\t"
+                    WRITEBGR32(%4, %5, %%REGa, %%mm2, %%mm4, %%mm5, %%mm1, %%mm0, %%mm7, %%mm3, %%mm6)
+                    YSCALEYUV2PACKEDX_END
+                } else {
+                    YSCALEYUV2PACKEDX
+                    YSCALEYUV2RGBX
+                    "pcmpeqd %%mm7, %%mm7 \n\t"
+                    WRITEBGR32(%4, %5, %%REGa, %%mm2, %%mm4, %%mm5, %%mm7, %%mm0, %%mm1, %%mm3, %%mm6)
+                    YSCALEYUV2PACKEDX_END
+                }
+                return;
+            case PIX_FMT_BGR24:
+                YSCALEYUV2PACKEDX
+                YSCALEYUV2RGBX
+                "pxor                    %%mm7, %%mm7       \n\t"
+                "lea (%%"REG_a", %%"REG_a", 2), %%"REG_c"   \n\t" //FIXME optimize
+                "add                        %4, %%"REG_c"   \n\t"
+                WRITEBGR24(%%REGc, %5, %%REGa)
+
+                :: "r" (&c->redDither),
+                "m" (dummy), "m" (dummy), "m" (dummy),
+                "r" (dest),  "m" (dstW_reg)
+                : "%"REG_a, "%"REG_c, "%"REG_d, "%"REG_S
+                );
+                return;
+            case PIX_FMT_RGB555:
+                YSCALEYUV2PACKEDX
+                YSCALEYUV2RGBX
+                "pxor %%mm7, %%mm7 \n\t"
+                /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */
+#ifdef DITHER1XBPP
+                "paddusb "BLUE_DITHER"(%0), %%mm2  \n\t"
+                "paddusb "GREEN_DITHER"(%0), %%mm4  \n\t"
+                "paddusb "RED_DITHER"(%0), %%mm5  \n\t"
+#endif
+
+                WRITERGB15(%4, %5, %%REGa)
+                YSCALEYUV2PACKEDX_END
+                return;
+            case PIX_FMT_RGB565:
+                YSCALEYUV2PACKEDX
+                YSCALEYUV2RGBX
+                "pxor %%mm7, %%mm7 \n\t"
+                /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */
+#ifdef DITHER1XBPP
+                "paddusb "BLUE_DITHER"(%0), %%mm2  \n\t"
+                "paddusb "GREEN_DITHER"(%0), %%mm4  \n\t"
+                "paddusb "RED_DITHER"(%0), %%mm5  \n\t"
+#endif
+
+                WRITERGB16(%4, %5, %%REGa)
+                YSCALEYUV2PACKEDX_END
+                return;
+            case PIX_FMT_YUYV422:
+                YSCALEYUV2PACKEDX
+                /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */
+
+                "psraw $3, %%mm3    \n\t"
+                "psraw $3, %%mm4    \n\t"
+                "psraw $3, %%mm1    \n\t"
+                "psraw $3, %%mm7    \n\t"
+                WRITEYUY2(%4, %5, %%REGa)
+                YSCALEYUV2PACKEDX_END
+                return;
+            }
+        }
+    }
+    yuv2packedXinC(c, lumFilter, lumSrc, lumFilterSize,
+                   chrFilter, chrSrc, chrFilterSize,
+                   alpSrc, dest, dstW, dstY);
+}
+
+/**
+ * vertical bilinear scale YV12 to RGB
+ */
+static inline void RENAME(yuv2packed2)(SwsContext *c, const uint16_t *buf0, const uint16_t *buf1, const uint16_t *uvbuf0, const uint16_t *uvbuf1,
+                          const uint16_t *abuf0, const uint16_t *abuf1, uint8_t *dest, int dstW, int yalpha, int uvalpha, int y)
+{
+    int  yalpha1=4095- yalpha;
+    int uvalpha1=4095-uvalpha;
+    int i;
+
+    if(!(c->flags & SWS_BITEXACT)) {
+        switch(c->dstFormat) {
+        //Note 8280 == DSTW_OFFSET but the preprocessor can't handle that there :(
+        case PIX_FMT_RGB32:
+            if (CONFIG_SWSCALE_ALPHA && c->alpPixBuf) {
+#if ARCH_X86_64
+                __asm__ volatile(
+                    YSCALEYUV2RGB(%%r8, %5)
+                    YSCALEYUV2RGB_YA(%%r8, %5, %6, %7)
+                    "psraw                  $3, %%mm1       \n\t" /* abuf0[eax] - abuf1[eax] >>7*/
+                    "psraw                  $3, %%mm7       \n\t" /* abuf0[eax] - abuf1[eax] >>7*/
+                    "packuswb            %%mm7, %%mm1       \n\t"
+                    WRITEBGR32(%4, 8280(%5), %%r8, %%mm2, %%mm4, %%mm5, %%mm1, %%mm0, %%mm7, %%mm3, %%mm6)
+
+                    :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "r" (dest),
+                    "a" (&c->redDither)
+                    ,"r" (abuf0), "r" (abuf1)
+                    : "%r8"
+                );
+#else
+                *(const uint16_t **)(&c->u_temp)=abuf0;
+                *(const uint16_t **)(&c->v_temp)=abuf1;
+                __asm__ volatile(
+                    "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"
+                    "mov        %4, %%"REG_b"               \n\t"
+                    "push %%"REG_BP"                        \n\t"
+                    YSCALEYUV2RGB(%%REGBP, %5)
+                    "push                   %0              \n\t"
+                    "push                   %1              \n\t"
+                    "mov          "U_TEMP"(%5), %0          \n\t"
+                    "mov          "V_TEMP"(%5), %1          \n\t"
+                    YSCALEYUV2RGB_YA(%%REGBP, %5, %0, %1)
+                    "psraw                  $3, %%mm1       \n\t" /* abuf0[eax] - abuf1[eax] >>7*/
+                    "psraw                  $3, %%mm7       \n\t" /* abuf0[eax] - abuf1[eax] >>7*/
+                    "packuswb            %%mm7, %%mm1       \n\t"
+                    "pop                    %1              \n\t"
+                    "pop                    %0              \n\t"
+                    WRITEBGR32(%%REGb, 8280(%5), %%REGBP, %%mm2, %%mm4, %%mm5, %%mm1, %%mm0, %%mm7, %%mm3, %%mm6)
+                    "pop %%"REG_BP"                         \n\t"
+                    "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"
+
+                    :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),
+                    "a" (&c->redDither)
+                );
+#endif
+            } else {
+                __asm__ volatile(
+                    "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"
+                    "mov        %4, %%"REG_b"               \n\t"
+                    "push %%"REG_BP"                        \n\t"
+                    YSCALEYUV2RGB(%%REGBP, %5)
+                    "pcmpeqd %%mm7, %%mm7                   \n\t"
+                    WRITEBGR32(%%REGb, 8280(%5), %%REGBP, %%mm2, %%mm4, %%mm5, %%mm7, %%mm0, %%mm1, %%mm3, %%mm6)
+                    "pop %%"REG_BP"                         \n\t"
+                    "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"
+
+                    :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),
+                    "a" (&c->redDither)
+                );
+            }
+            return;
+        case PIX_FMT_BGR24:
+            __asm__ volatile(
+                "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"
+                "mov        %4, %%"REG_b"               \n\t"
+                "push %%"REG_BP"                        \n\t"
+                YSCALEYUV2RGB(%%REGBP, %5)
+                "pxor    %%mm7, %%mm7                   \n\t"
+                WRITEBGR24(%%REGb, 8280(%5), %%REGBP)
+                "pop %%"REG_BP"                         \n\t"
+                "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"
+                :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),
+                "a" (&c->redDither)
+            );
+            return;
+        case PIX_FMT_RGB555:
+            __asm__ volatile(
+                "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"
+                "mov        %4, %%"REG_b"               \n\t"
+                "push %%"REG_BP"                        \n\t"
+                YSCALEYUV2RGB(%%REGBP, %5)
+                "pxor    %%mm7, %%mm7                   \n\t"
+                /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */
+#ifdef DITHER1XBPP
+                "paddusb "BLUE_DITHER"(%5), %%mm2      \n\t"
+                "paddusb "GREEN_DITHER"(%5), %%mm4      \n\t"
+                "paddusb "RED_DITHER"(%5), %%mm5      \n\t"
+#endif
+
+                WRITERGB15(%%REGb, 8280(%5), %%REGBP)
+                "pop %%"REG_BP"                         \n\t"
+                "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"
+
+                :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),
+                "a" (&c->redDither)
+            );
+            return;
+        case PIX_FMT_RGB565:
+            __asm__ volatile(
+                "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"
+                "mov        %4, %%"REG_b"               \n\t"
+                "push %%"REG_BP"                        \n\t"
+                YSCALEYUV2RGB(%%REGBP, %5)
+                "pxor    %%mm7, %%mm7                   \n\t"
+                /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */
+#ifdef DITHER1XBPP
+                "paddusb "BLUE_DITHER"(%5), %%mm2      \n\t"
+                "paddusb "GREEN_DITHER"(%5), %%mm4      \n\t"
+                "paddusb "RED_DITHER"(%5), %%mm5      \n\t"
+#endif
+
+                WRITERGB16(%%REGb, 8280(%5), %%REGBP)
+                "pop %%"REG_BP"                         \n\t"
+                "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"
+                :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),
+                "a" (&c->redDither)
+            );
+            return;
+        case PIX_FMT_YUYV422:
+            __asm__ volatile(
+                "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"
+                "mov %4, %%"REG_b"                        \n\t"
+                "push %%"REG_BP"                        \n\t"
+                YSCALEYUV2PACKED(%%REGBP, %5)
+                WRITEYUY2(%%REGb, 8280(%5), %%REGBP)
+                "pop %%"REG_BP"                         \n\t"
+                "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"
+                :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),
+                "a" (&c->redDither)
+            );
+            return;
+        default: break;
+        }
+    }
+    YSCALE_YUV_2_ANYRGB_C(YSCALE_YUV_2_RGB2_C, YSCALE_YUV_2_PACKED2_C(void,0), YSCALE_YUV_2_GRAY16_2_C, YSCALE_YUV_2_MONO2_C)
+}
+
+/**
+ * YV12 to RGB without scaling or interpolating
+ */
+static inline void RENAME(yuv2packed1)(SwsContext *c, const uint16_t *buf0, const uint16_t *uvbuf0, const uint16_t *uvbuf1,
+                          const uint16_t *abuf0, uint8_t *dest, int dstW, int uvalpha, enum PixelFormat dstFormat, int flags, int y)
+{
+    const int yalpha1=0;
+    int i;
+
+    const uint16_t *buf1= buf0; //FIXME needed for RGB1/BGR1
+    const int yalpha= 4096; //FIXME ...
+
+    if (flags&SWS_FULL_CHR_H_INT) {
+        c->yuv2packed2(c, buf0, buf0, uvbuf0, uvbuf1, abuf0, abuf0, dest, dstW, 0, uvalpha, y);
+        return;
+    }
+
+    if(!(flags & SWS_BITEXACT)) {
+        if (uvalpha < 2048) { // note this is not correct (shifts chrominance by 0.5 pixels) but it is a bit faster
+            switch(dstFormat) {
+            case PIX_FMT_RGB32:
+                if (CONFIG_SWSCALE_ALPHA && c->alpPixBuf) {
+                    __asm__ volatile(
+                        "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"
+                        "mov        %4, %%"REG_b"               \n\t"
+                        "push %%"REG_BP"                        \n\t"
+                        YSCALEYUV2RGB1(%%REGBP, %5)
+                        YSCALEYUV2RGB1_ALPHA(%%REGBP)
+                        WRITEBGR32(%%REGb, 8280(%5), %%REGBP, %%mm2, %%mm4, %%mm5, %%mm7, %%mm0, %%mm1, %%mm3, %%mm6)
+                        "pop %%"REG_BP"                         \n\t"
+                        "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"
+
+                        :: "c" (buf0), "d" (abuf0), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),
+                        "a" (&c->redDither)
+                    );
+                } else {
+                    __asm__ volatile(
+                        "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"
+                        "mov        %4, %%"REG_b"               \n\t"
+                        "push %%"REG_BP"                        \n\t"
+                        YSCALEYUV2RGB1(%%REGBP, %5)
+                        "pcmpeqd %%mm7, %%mm7                   \n\t"
+                        WRITEBGR32(%%REGb, 8280(%5), %%REGBP, %%mm2, %%mm4, %%mm5, %%mm7, %%mm0, %%mm1, %%mm3, %%mm6)
+                        "pop %%"REG_BP"                         \n\t"
+                        "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"
+
+                        :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),
+                        "a" (&c->redDither)
+                    );
+                }
+                return;
+            case PIX_FMT_BGR24:
+                __asm__ volatile(
+                    "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"
+                    "mov        %4, %%"REG_b"               \n\t"
+                    "push %%"REG_BP"                        \n\t"
+                    YSCALEYUV2RGB1(%%REGBP, %5)
+                    "pxor    %%mm7, %%mm7                   \n\t"
+                    WRITEBGR24(%%REGb, 8280(%5), %%REGBP)
+                    "pop %%"REG_BP"                         \n\t"
+                    "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"
+
+                    :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),
+                    "a" (&c->redDither)
+                );
+                return;
+            case PIX_FMT_RGB555:
+                __asm__ volatile(
+                    "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"
+                    "mov        %4, %%"REG_b"               \n\t"
+                    "push %%"REG_BP"                        \n\t"
+                    YSCALEYUV2RGB1(%%REGBP, %5)
+                    "pxor    %%mm7, %%mm7                   \n\t"
+                    /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */
+#ifdef DITHER1XBPP
+                    "paddusb "BLUE_DITHER"(%5), %%mm2      \n\t"
+                    "paddusb "GREEN_DITHER"(%5), %%mm4      \n\t"
+                    "paddusb "RED_DITHER"(%5), %%mm5      \n\t"
+#endif
+                    WRITERGB15(%%REGb, 8280(%5), %%REGBP)
+                    "pop %%"REG_BP"                         \n\t"
+                    "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"
+
+                    :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),
+                    "a" (&c->redDither)
+                );
+                return;
+            case PIX_FMT_RGB565:
+                __asm__ volatile(
+                    "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"
+                    "mov        %4, %%"REG_b"               \n\t"
+                    "push %%"REG_BP"                        \n\t"
+                    YSCALEYUV2RGB1(%%REGBP, %5)
+                    "pxor    %%mm7, %%mm7                   \n\t"
+                    /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */
+#ifdef DITHER1XBPP
+                    "paddusb "BLUE_DITHER"(%5), %%mm2      \n\t"
+                    "paddusb "GREEN_DITHER"(%5), %%mm4      \n\t"
+                    "paddusb "RED_DITHER"(%5), %%mm5      \n\t"
+#endif
+
+                    WRITERGB16(%%REGb, 8280(%5), %%REGBP)
+                    "pop %%"REG_BP"                         \n\t"
+                    "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"
+
+                    :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),
+                    "a" (&c->redDither)
+                );
+                return;
+            case PIX_FMT_YUYV422:
+                __asm__ volatile(
+                    "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"
+                    "mov        %4, %%"REG_b"               \n\t"
+                    "push %%"REG_BP"                        \n\t"
+                    YSCALEYUV2PACKED1(%%REGBP, %5)
+                    WRITEYUY2(%%REGb, 8280(%5), %%REGBP)
+                    "pop %%"REG_BP"                         \n\t"
+                    "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"
+
+                    :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),
+                    "a" (&c->redDither)
+                );
+                return;
+            }
+        } else {
+            switch(dstFormat) {
+            case PIX_FMT_RGB32:
+                if (CONFIG_SWSCALE_ALPHA && c->alpPixBuf) {
+                    __asm__ volatile(
+                        "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"
+                        "mov        %4, %%"REG_b"               \n\t"
+                        "push %%"REG_BP"                        \n\t"
+                        YSCALEYUV2RGB1b(%%REGBP, %5)
+                        YSCALEYUV2RGB1_ALPHA(%%REGBP)
+                        WRITEBGR32(%%REGb, 8280(%5), %%REGBP, %%mm2, %%mm4, %%mm5, %%mm7, %%mm0, %%mm1, %%mm3, %%mm6)
+                        "pop %%"REG_BP"                         \n\t"
+                        "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"
+
+                        :: "c" (buf0), "d" (abuf0), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),
+                        "a" (&c->redDither)
+                    );
+                } else {
+                    __asm__ volatile(
+                        "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"
+                        "mov        %4, %%"REG_b"               \n\t"
+                        "push %%"REG_BP"                        \n\t"
+                        YSCALEYUV2RGB1b(%%REGBP, %5)
+                        "pcmpeqd %%mm7, %%mm7                   \n\t"
+                        WRITEBGR32(%%REGb, 8280(%5), %%REGBP, %%mm2, %%mm4, %%mm5, %%mm7, %%mm0, %%mm1, %%mm3, %%mm6)
+                        "pop %%"REG_BP"                         \n\t"
+                        "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"
+
+                        :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),
+                        "a" (&c->redDither)
+                    );
+                }
+                return;
+            case PIX_FMT_BGR24:
+                __asm__ volatile(
+                    "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"
+                    "mov        %4, %%"REG_b"               \n\t"
+                    "push %%"REG_BP"                        \n\t"
+                    YSCALEYUV2RGB1b(%%REGBP, %5)
+                    "pxor    %%mm7, %%mm7                   \n\t"
+                    WRITEBGR24(%%REGb, 8280(%5), %%REGBP)
+                    "pop %%"REG_BP"                         \n\t"
+                    "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"
+
+                    :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),
+                    "a" (&c->redDither)
+                );
+                return;
+            case PIX_FMT_RGB555:
+                __asm__ volatile(
+                    "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"
+                    "mov        %4, %%"REG_b"               \n\t"
+                    "push %%"REG_BP"                        \n\t"
+                    YSCALEYUV2RGB1b(%%REGBP, %5)
+                    "pxor    %%mm7, %%mm7                   \n\t"
+                    /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */
+#ifdef DITHER1XBPP
+                    "paddusb "BLUE_DITHER"(%5), %%mm2      \n\t"
+                    "paddusb "GREEN_DITHER"(%5), %%mm4      \n\t"
+                    "paddusb "RED_DITHER"(%5), %%mm5      \n\t"
+#endif
+                    WRITERGB15(%%REGb, 8280(%5), %%REGBP)
+                    "pop %%"REG_BP"                         \n\t"
+                    "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"
+
+                    :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),
+                    "a" (&c->redDither)
+                );
+                return;
+            case PIX_FMT_RGB565:
+                __asm__ volatile(
+                    "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"
+                    "mov        %4, %%"REG_b"               \n\t"
+                    "push %%"REG_BP"                        \n\t"
+                    YSCALEYUV2RGB1b(%%REGBP, %5)
+                    "pxor    %%mm7, %%mm7                   \n\t"
+                    /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */
+#ifdef DITHER1XBPP
+                    "paddusb "BLUE_DITHER"(%5), %%mm2      \n\t"
+                    "paddusb "GREEN_DITHER"(%5), %%mm4      \n\t"
+                    "paddusb "RED_DITHER"(%5), %%mm5      \n\t"
+#endif
+
+                    WRITERGB16(%%REGb, 8280(%5), %%REGBP)
+                    "pop %%"REG_BP"                         \n\t"
+                    "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"
+
+                    :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),
+                    "a" (&c->redDither)
+                );
+                return;
+            case PIX_FMT_YUYV422:
+                __asm__ volatile(
+                    "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"
+                    "mov        %4, %%"REG_b"               \n\t"
+                    "push %%"REG_BP"                        \n\t"
+                    YSCALEYUV2PACKED1b(%%REGBP, %5)
+                    WRITEYUY2(%%REGb, 8280(%5), %%REGBP)
+                    "pop %%"REG_BP"                         \n\t"
+                    "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"
+
+                    :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),
+                    "a" (&c->redDither)
+                );
+                return;
+            }
+        }
+    }
+    if (uvalpha < 2048) {
+        YSCALE_YUV_2_ANYRGB_C(YSCALE_YUV_2_RGB1_C, YSCALE_YUV_2_PACKED1_C(void,0), YSCALE_YUV_2_GRAY16_1_C, YSCALE_YUV_2_MONO2_C)
+    } else {
+        YSCALE_YUV_2_ANYRGB_C(YSCALE_YUV_2_RGB1B_C, YSCALE_YUV_2_PACKED1B_C(void,0), YSCALE_YUV_2_GRAY16_1_C, YSCALE_YUV_2_MONO2_C)
+    }
+}
+
+//FIXME yuy2* can read up to 7 samples too much
+
+static inline void RENAME(yuy2ToY)(uint8_t *dst, const uint8_t *src, long width, uint32_t *unused)
+{
+    __asm__ volatile(
+        "movq "MANGLE(bm01010101)", %%mm2           \n\t"
+        "mov                    %0, %%"REG_a"       \n\t"
+        "1:                                         \n\t"
+        "movq    (%1, %%"REG_a",2), %%mm0           \n\t"
+        "movq   8(%1, %%"REG_a",2), %%mm1           \n\t"
+        "pand                %%mm2, %%mm0           \n\t"
+        "pand                %%mm2, %%mm1           \n\t"
+        "packuswb            %%mm1, %%mm0           \n\t"
+        "movq                %%mm0, (%2, %%"REG_a") \n\t"
+        "add                    $8, %%"REG_a"       \n\t"
+        " js                    1b                  \n\t"
+        : : "g" ((x86_reg)-width), "r" (src+width*2), "r" (dst+width)
+        : "%"REG_a
+    );
+}
+
+static inline void RENAME(yuy2ToUV)(uint8_t *dstU, uint8_t *dstV, const uint8_t *src1, const uint8_t *src2, long width, uint32_t *unused)
+{
+    __asm__ volatile(
+        "movq "MANGLE(bm01010101)", %%mm4           \n\t"
+        "mov                    %0, %%"REG_a"       \n\t"
+        "1:                                         \n\t"
+        "movq    (%1, %%"REG_a",4), %%mm0           \n\t"
+        "movq   8(%1, %%"REG_a",4), %%mm1           \n\t"
+        "psrlw                  $8, %%mm0           \n\t"
+        "psrlw                  $8, %%mm1           \n\t"
+        "packuswb            %%mm1, %%mm0           \n\t"
+        "movq                %%mm0, %%mm1           \n\t"
+        "psrlw                  $8, %%mm0           \n\t"
+        "pand                %%mm4, %%mm1           \n\t"
+        "packuswb            %%mm0, %%mm0           \n\t"
+        "packuswb            %%mm1, %%mm1           \n\t"
+        "movd                %%mm0, (%3, %%"REG_a") \n\t"
+        "movd                %%mm1, (%2, %%"REG_a") \n\t"
+        "add                    $4, %%"REG_a"       \n\t"
+        " js                    1b                  \n\t"
+        : : "g" ((x86_reg)-width), "r" (src1+width*4), "r" (dstU+width), "r" (dstV+width)
+        : "%"REG_a
+    );
+    assert(src1 == src2);
+}
+
+static inline void RENAME(LEToUV)(uint8_t *dstU, uint8_t *dstV, const uint8_t *src1, const uint8_t *src2, long width, uint32_t *unused)
+{
+    __asm__ volatile(
+        "mov                    %0, %%"REG_a"       \n\t"
+        "1:                                         \n\t"
+        "movq    (%1, %%"REG_a",2), %%mm0           \n\t"
+        "movq   8(%1, %%"REG_a",2), %%mm1           \n\t"
+        "movq    (%2, %%"REG_a",2), %%mm2           \n\t"
+        "movq   8(%2, %%"REG_a",2), %%mm3           \n\t"
+        "psrlw                  $8, %%mm0           \n\t"
+        "psrlw                  $8, %%mm1           \n\t"
+        "psrlw                  $8, %%mm2           \n\t"
+        "psrlw                  $8, %%mm3           \n\t"
+        "packuswb            %%mm1, %%mm0           \n\t"
+        "packuswb            %%mm3, %%mm2           \n\t"
+        "movq                %%mm0, (%3, %%"REG_a") \n\t"
+        "movq                %%mm2, (%4, %%"REG_a") \n\t"
+        "add                    $8, %%"REG_a"       \n\t"
+        " js                    1b                  \n\t"
+        : : "g" ((x86_reg)-width), "r" (src1+width*2), "r" (src2+width*2), "r" (dstU+width), "r" (dstV+width)
+        : "%"REG_a
+    );
+}
+
+/* This is almost identical to the previous, end exists only because
+ * yuy2ToY/UV)(dst, src+1, ...) would have 100% unaligned accesses. */
+static inline void RENAME(uyvyToY)(uint8_t *dst, const uint8_t *src, long width, uint32_t *unused)
+{
+    __asm__ volatile(
+        "mov                  %0, %%"REG_a"         \n\t"
+        "1:                                         \n\t"
+        "movq  (%1, %%"REG_a",2), %%mm0             \n\t"
+        "movq 8(%1, %%"REG_a",2), %%mm1             \n\t"
+        "psrlw                $8, %%mm0             \n\t"
+        "psrlw                $8, %%mm1             \n\t"
+        "packuswb          %%mm1, %%mm0             \n\t"
+        "movq              %%mm0, (%2, %%"REG_a")   \n\t"
+        "add                  $8, %%"REG_a"         \n\t"
+        " js                  1b                    \n\t"
+        : : "g" ((x86_reg)-width), "r" (src+width*2), "r" (dst+width)
+        : "%"REG_a
+    );
+}
+
+static inline void RENAME(uyvyToUV)(uint8_t *dstU, uint8_t *dstV, const uint8_t *src1, const uint8_t *src2, long width, uint32_t *unused)
+{
+    __asm__ volatile(
+        "movq "MANGLE(bm01010101)", %%mm4           \n\t"
+        "mov                    %0, %%"REG_a"       \n\t"
+        "1:                                         \n\t"
+        "movq    (%1, %%"REG_a",4), %%mm0           \n\t"
+        "movq   8(%1, %%"REG_a",4), %%mm1           \n\t"
+        "pand                %%mm4, %%mm0           \n\t"
+        "pand                %%mm4, %%mm1           \n\t"
+        "packuswb            %%mm1, %%mm0           \n\t"
+        "movq                %%mm0, %%mm1           \n\t"
+        "psrlw                  $8, %%mm0           \n\t"
+        "pand                %%mm4, %%mm1           \n\t"
+        "packuswb            %%mm0, %%mm0           \n\t"
+        "packuswb            %%mm1, %%mm1           \n\t"
+        "movd                %%mm0, (%3, %%"REG_a") \n\t"
+        "movd                %%mm1, (%2, %%"REG_a") \n\t"
+        "add                    $4, %%"REG_a"       \n\t"
+        " js                    1b                  \n\t"
+        : : "g" ((x86_reg)-width), "r" (src1+width*4), "r" (dstU+width), "r" (dstV+width)
+        : "%"REG_a
+    );
+    assert(src1 == src2);
+}
+
+static inline void RENAME(BEToUV)(uint8_t *dstU, uint8_t *dstV, const uint8_t *src1, const uint8_t *src2, long width, uint32_t *unused)
+{
+    __asm__ volatile(
+        "movq "MANGLE(bm01010101)", %%mm4           \n\t"
+        "mov                    %0, %%"REG_a"       \n\t"
+        "1:                                         \n\t"
+        "movq    (%1, %%"REG_a",2), %%mm0           \n\t"
+        "movq   8(%1, %%"REG_a",2), %%mm1           \n\t"
+        "movq    (%2, %%"REG_a",2), %%mm2           \n\t"
+        "movq   8(%2, %%"REG_a",2), %%mm3           \n\t"
+        "pand                %%mm4, %%mm0           \n\t"
+        "pand                %%mm4, %%mm1           \n\t"
+        "pand                %%mm4, %%mm2           \n\t"
+        "pand                %%mm4, %%mm3           \n\t"
+        "packuswb            %%mm1, %%mm0           \n\t"
+        "packuswb            %%mm3, %%mm2           \n\t"
+        "movq                %%mm0, (%3, %%"REG_a") \n\t"
+        "movq                %%mm2, (%4, %%"REG_a") \n\t"
+        "add                    $8, %%"REG_a"       \n\t"
+        " js                    1b                  \n\t"
+        : : "g" ((x86_reg)-width), "r" (src1+width*2), "r" (src2+width*2), "r" (dstU+width), "r" (dstV+width)
+        : "%"REG_a
+    );
+}
+
+static inline void RENAME(nvXXtoUV)(uint8_t *dst1, uint8_t *dst2,
+                                    const uint8_t *src, long width)
+{
+    __asm__ volatile(
+        "movq "MANGLE(bm01010101)", %%mm4           \n\t"
+        "mov                    %0, %%"REG_a"       \n\t"
+        "1:                                         \n\t"
+        "movq    (%1, %%"REG_a",2), %%mm0           \n\t"
+        "movq   8(%1, %%"REG_a",2), %%mm1           \n\t"
+        "movq                %%mm0, %%mm2           \n\t"
+        "movq                %%mm1, %%mm3           \n\t"
+        "pand                %%mm4, %%mm0           \n\t"
+        "pand                %%mm4, %%mm1           \n\t"
+        "psrlw                  $8, %%mm2           \n\t"
+        "psrlw                  $8, %%mm3           \n\t"
+        "packuswb            %%mm1, %%mm0           \n\t"
+        "packuswb            %%mm3, %%mm2           \n\t"
+        "movq                %%mm0, (%2, %%"REG_a") \n\t"
+        "movq                %%mm2, (%3, %%"REG_a") \n\t"
+        "add                    $8, %%"REG_a"       \n\t"
+        " js                    1b                  \n\t"
+        : : "g" ((x86_reg)-width), "r" (src+width*2), "r" (dst1+width), "r" (dst2+width)
+        : "%"REG_a
+    );
+}
+
+static inline void RENAME(nv12ToUV)(uint8_t *dstU, uint8_t *dstV,
+                                    const uint8_t *src1, const uint8_t *src2,
+                                    long width, uint32_t *unused)
+{
+    RENAME(nvXXtoUV)(dstU, dstV, src1, width);
+}
+
+static inline void RENAME(nv21ToUV)(uint8_t *dstU, uint8_t *dstV,
+                                    const uint8_t *src1, const uint8_t *src2,
+                                    long width, uint32_t *unused)
+{
+    RENAME(nvXXtoUV)(dstV, dstU, src1, width);
+}
+
+static inline void RENAME(bgr24ToY_mmx)(uint8_t *dst, const uint8_t *src, long width, enum PixelFormat srcFormat)
+{
+
+    if(srcFormat == PIX_FMT_BGR24) {
+        __asm__ volatile(
+            "movq  "MANGLE(ff_bgr24toY1Coeff)", %%mm5       \n\t"
+            "movq  "MANGLE(ff_bgr24toY2Coeff)", %%mm6       \n\t"
+            :
+        );
+    } else {
+        __asm__ volatile(
+            "movq  "MANGLE(ff_rgb24toY1Coeff)", %%mm5       \n\t"
+            "movq  "MANGLE(ff_rgb24toY2Coeff)", %%mm6       \n\t"
+            :
+        );
+    }
+
+    __asm__ volatile(
+        "movq  "MANGLE(ff_bgr24toYOffset)", %%mm4   \n\t"
+        "mov                        %2, %%"REG_a"   \n\t"
+        "pxor                    %%mm7, %%mm7       \n\t"
+        "1:                                         \n\t"
+        PREFETCH"               64(%0)              \n\t"
+        "movd                     (%0), %%mm0       \n\t"
+        "movd                    2(%0), %%mm1       \n\t"
+        "movd                    6(%0), %%mm2       \n\t"
+        "movd                    8(%0), %%mm3       \n\t"
+        "add                       $12, %0          \n\t"
+        "punpcklbw               %%mm7, %%mm0       \n\t"
+        "punpcklbw               %%mm7, %%mm1       \n\t"
+        "punpcklbw               %%mm7, %%mm2       \n\t"
+        "punpcklbw               %%mm7, %%mm3       \n\t"
+        "pmaddwd                 %%mm5, %%mm0       \n\t"
+        "pmaddwd                 %%mm6, %%mm1       \n\t"
+        "pmaddwd                 %%mm5, %%mm2       \n\t"
+        "pmaddwd                 %%mm6, %%mm3       \n\t"
+        "paddd                   %%mm1, %%mm0       \n\t"
+        "paddd                   %%mm3, %%mm2       \n\t"
+        "paddd                   %%mm4, %%mm0       \n\t"
+        "paddd                   %%mm4, %%mm2       \n\t"
+        "psrad                     $15, %%mm0       \n\t"
+        "psrad                     $15, %%mm2       \n\t"
+        "packssdw                %%mm2, %%mm0       \n\t"
+        "packuswb                %%mm0, %%mm0       \n\t"
+        "movd                %%mm0, (%1, %%"REG_a") \n\t"
+        "add                        $4, %%"REG_a"   \n\t"
+        " js                        1b              \n\t"
+    : "+r" (src)
+    : "r" (dst+width), "g" ((x86_reg)-width)
+    : "%"REG_a
+    );
+}
+
+static inline void RENAME(bgr24ToUV_mmx)(uint8_t *dstU, uint8_t *dstV, const uint8_t *src, long width, enum PixelFormat srcFormat)
+{
+    __asm__ volatile(
+        "movq                    24(%4), %%mm6       \n\t"
+        "mov                        %3, %%"REG_a"   \n\t"
+        "pxor                    %%mm7, %%mm7       \n\t"
+        "1:                                         \n\t"
+        PREFETCH"               64(%0)              \n\t"
+        "movd                     (%0), %%mm0       \n\t"
+        "movd                    2(%0), %%mm1       \n\t"
+        "punpcklbw               %%mm7, %%mm0       \n\t"
+        "punpcklbw               %%mm7, %%mm1       \n\t"
+        "movq                    %%mm0, %%mm2       \n\t"
+        "movq                    %%mm1, %%mm3       \n\t"
+        "pmaddwd                  (%4), %%mm0       \n\t"
+        "pmaddwd                 8(%4), %%mm1       \n\t"
+        "pmaddwd                16(%4), %%mm2       \n\t"
+        "pmaddwd                 %%mm6, %%mm3       \n\t"
+        "paddd                   %%mm1, %%mm0       \n\t"
+        "paddd                   %%mm3, %%mm2       \n\t"
+
+        "movd                    6(%0), %%mm1       \n\t"
+        "movd                    8(%0), %%mm3       \n\t"
+        "add                       $12, %0          \n\t"
+        "punpcklbw               %%mm7, %%mm1       \n\t"
+        "punpcklbw               %%mm7, %%mm3       \n\t"
+        "movq                    %%mm1, %%mm4       \n\t"
+        "movq                    %%mm3, %%mm5       \n\t"
+        "pmaddwd                  (%4), %%mm1       \n\t"
+        "pmaddwd                 8(%4), %%mm3       \n\t"
+        "pmaddwd                16(%4), %%mm4       \n\t"
+        "pmaddwd                 %%mm6, %%mm5       \n\t"
+        "paddd                   %%mm3, %%mm1       \n\t"
+        "paddd                   %%mm5, %%mm4       \n\t"
+
+        "movq "MANGLE(ff_bgr24toUVOffset)", %%mm3       \n\t"
+        "paddd                   %%mm3, %%mm0       \n\t"
+        "paddd                   %%mm3, %%mm2       \n\t"
+        "paddd                   %%mm3, %%mm1       \n\t"
+        "paddd                   %%mm3, %%mm4       \n\t"
+        "psrad                     $15, %%mm0       \n\t"
+        "psrad                     $15, %%mm2       \n\t"
+        "psrad                     $15, %%mm1       \n\t"
+        "psrad                     $15, %%mm4       \n\t"
+        "packssdw                %%mm1, %%mm0       \n\t"
+        "packssdw                %%mm4, %%mm2       \n\t"
+        "packuswb                %%mm0, %%mm0       \n\t"
+        "packuswb                %%mm2, %%mm2       \n\t"
+        "movd                %%mm0, (%1, %%"REG_a") \n\t"
+        "movd                %%mm2, (%2, %%"REG_a") \n\t"
+        "add                        $4, %%"REG_a"   \n\t"
+        " js                        1b              \n\t"
+    : "+r" (src)
+    : "r" (dstU+width), "r" (dstV+width), "g" ((x86_reg)-width), "r"(ff_bgr24toUV[srcFormat == PIX_FMT_RGB24])
+    : "%"REG_a
+    );
+}
+
+static inline void RENAME(bgr24ToY)(uint8_t *dst, const uint8_t *src, long width, uint32_t *unused)
+{
+    RENAME(bgr24ToY_mmx)(dst, src, width, PIX_FMT_BGR24);
+}
+
+static inline void RENAME(bgr24ToUV)(uint8_t *dstU, uint8_t *dstV, const uint8_t *src1, const uint8_t *src2, long width, uint32_t *unused)
+{
+    RENAME(bgr24ToUV_mmx)(dstU, dstV, src1, width, PIX_FMT_BGR24);
+    assert(src1 == src2);
+}
+
+static inline void RENAME(bgr24ToUV_half)(uint8_t *dstU, uint8_t *dstV, const uint8_t *src1, const uint8_t *src2, long width, uint32_t *unused)
+{
+    int i;
+    for (i=0; i<width; i++) {
+        int b= src1[6*i + 0] + src1[6*i + 3];
+        int g= src1[6*i + 1] + src1[6*i + 4];
+        int r= src1[6*i + 2] + src1[6*i + 5];
+
+        dstU[i]= (RU*r + GU*g + BU*b + (257<<RGB2YUV_SHIFT))>>(RGB2YUV_SHIFT+1);
+        dstV[i]= (RV*r + GV*g + BV*b + (257<<RGB2YUV_SHIFT))>>(RGB2YUV_SHIFT+1);
+    }
+    assert(src1 == src2);
+}
+
+static inline void RENAME(rgb24ToY)(uint8_t *dst, const uint8_t *src, long width, uint32_t *unused)
+{
+    RENAME(bgr24ToY_mmx)(dst, src, width, PIX_FMT_RGB24);
+}
+
+static inline void RENAME(rgb24ToUV)(uint8_t *dstU, uint8_t *dstV, const uint8_t *src1, const uint8_t *src2, long width, uint32_t *unused)
+{
+    assert(src1==src2);
+    RENAME(bgr24ToUV_mmx)(dstU, dstV, src1, width, PIX_FMT_RGB24);
+}
+
+static inline void RENAME(rgb24ToUV_half)(uint8_t *dstU, uint8_t *dstV, const uint8_t *src1, const uint8_t *src2, long width, uint32_t *unused)
+{
+    int i;
+    assert(src1==src2);
+    for (i=0; i<width; i++) {
+        int r= src1[6*i + 0] + src1[6*i + 3];
+        int g= src1[6*i + 1] + src1[6*i + 4];
+        int b= src1[6*i + 2] + src1[6*i + 5];
+
+        dstU[i]= (RU*r + GU*g + BU*b + (257<<RGB2YUV_SHIFT))>>(RGB2YUV_SHIFT+1);
+        dstV[i]= (RV*r + GV*g + BV*b + (257<<RGB2YUV_SHIFT))>>(RGB2YUV_SHIFT+1);
+    }
+}
+
+
+// bilinear / bicubic scaling
+static inline void RENAME(hScale)(int16_t *dst, int dstW, const uint8_t *src, int srcW, int xInc,
+                                  const int16_t *filter, const int16_t *filterPos, long filterSize)
+{
+    assert(filterSize % 4 == 0 && filterSize>0);
+    if (filterSize==4) { // Always true for upscaling, sometimes for down, too.
+        x86_reg counter= -2*dstW;
+        filter-= counter*2;
+        filterPos-= counter/2;
+        dst-= counter/2;
+        __asm__ volatile(
+#if defined(PIC)
+            "push            %%"REG_b"              \n\t"
+#endif
+            "pxor                %%mm7, %%mm7       \n\t"
+            "push           %%"REG_BP"              \n\t" // we use 7 regs here ...
+            "mov             %%"REG_a", %%"REG_BP"  \n\t"
+            ".p2align                4              \n\t"
+            "1:                                     \n\t"
+            "movzwl   (%2, %%"REG_BP"), %%eax       \n\t"
+            "movzwl  2(%2, %%"REG_BP"), %%ebx       \n\t"
+            "movq  (%1, %%"REG_BP", 4), %%mm1       \n\t"
+            "movq 8(%1, %%"REG_BP", 4), %%mm3       \n\t"
+            "movd      (%3, %%"REG_a"), %%mm0       \n\t"
+            "movd      (%3, %%"REG_b"), %%mm2       \n\t"
+            "punpcklbw           %%mm7, %%mm0       \n\t"
+            "punpcklbw           %%mm7, %%mm2       \n\t"
+            "pmaddwd             %%mm1, %%mm0       \n\t"
+            "pmaddwd             %%mm2, %%mm3       \n\t"
+            "movq                %%mm0, %%mm4       \n\t"
+            "punpckldq           %%mm3, %%mm0       \n\t"
+            "punpckhdq           %%mm3, %%mm4       \n\t"
+            "paddd               %%mm4, %%mm0       \n\t"
+            "psrad                  $7, %%mm0       \n\t"
+            "packssdw            %%mm0, %%mm0       \n\t"
+            "movd                %%mm0, (%4, %%"REG_BP")    \n\t"
+            "add                    $4, %%"REG_BP"  \n\t"
+            " jnc                   1b              \n\t"
+
+            "pop            %%"REG_BP"              \n\t"
+#if defined(PIC)
+            "pop             %%"REG_b"              \n\t"
+#endif
+            : "+a" (counter)
+            : "c" (filter), "d" (filterPos), "S" (src), "D" (dst)
+#if !defined(PIC)
+            : "%"REG_b
+#endif
+        );
+    } else if (filterSize==8) {
+        x86_reg counter= -2*dstW;
+        filter-= counter*4;
+        filterPos-= counter/2;
+        dst-= counter/2;
+        __asm__ volatile(
+#if defined(PIC)
+            "push             %%"REG_b"             \n\t"
+#endif
+            "pxor                 %%mm7, %%mm7      \n\t"
+            "push            %%"REG_BP"             \n\t" // we use 7 regs here ...
+            "mov              %%"REG_a", %%"REG_BP" \n\t"
+            ".p2align                 4             \n\t"
+            "1:                                     \n\t"
+            "movzwl    (%2, %%"REG_BP"), %%eax      \n\t"
+            "movzwl   2(%2, %%"REG_BP"), %%ebx      \n\t"
+            "movq   (%1, %%"REG_BP", 8), %%mm1      \n\t"
+            "movq 16(%1, %%"REG_BP", 8), %%mm3      \n\t"
+            "movd       (%3, %%"REG_a"), %%mm0      \n\t"
+            "movd       (%3, %%"REG_b"), %%mm2      \n\t"
+            "punpcklbw            %%mm7, %%mm0      \n\t"
+            "punpcklbw            %%mm7, %%mm2      \n\t"
+            "pmaddwd              %%mm1, %%mm0      \n\t"
+            "pmaddwd              %%mm2, %%mm3      \n\t"
+
+            "movq  8(%1, %%"REG_BP", 8), %%mm1      \n\t"
+            "movq 24(%1, %%"REG_BP", 8), %%mm5      \n\t"
+            "movd      4(%3, %%"REG_a"), %%mm4      \n\t"
+            "movd      4(%3, %%"REG_b"), %%mm2      \n\t"
+            "punpcklbw            %%mm7, %%mm4      \n\t"
+            "punpcklbw            %%mm7, %%mm2      \n\t"
+            "pmaddwd              %%mm1, %%mm4      \n\t"
+            "pmaddwd              %%mm2, %%mm5      \n\t"
+            "paddd                %%mm4, %%mm0      \n\t"
+            "paddd                %%mm5, %%mm3      \n\t"
+            "movq                 %%mm0, %%mm4      \n\t"
+            "punpckldq            %%mm3, %%mm0      \n\t"
+            "punpckhdq            %%mm3, %%mm4      \n\t"
+            "paddd                %%mm4, %%mm0      \n\t"
+            "psrad                   $7, %%mm0      \n\t"
+            "packssdw             %%mm0, %%mm0      \n\t"
+            "movd                 %%mm0, (%4, %%"REG_BP")   \n\t"
+            "add                     $4, %%"REG_BP" \n\t"
+            " jnc                    1b             \n\t"
+
+            "pop             %%"REG_BP"             \n\t"
+#if defined(PIC)
+            "pop              %%"REG_b"             \n\t"
+#endif
+            : "+a" (counter)
+            : "c" (filter), "d" (filterPos), "S" (src), "D" (dst)
+#if !defined(PIC)
+            : "%"REG_b
+#endif
+        );
+    } else {
+        const uint8_t *offset = src+filterSize;
+        x86_reg counter= -2*dstW;
+        //filter-= counter*filterSize/2;
+        filterPos-= counter/2;
+        dst-= counter/2;
+        __asm__ volatile(
+            "pxor                  %%mm7, %%mm7     \n\t"
+            ".p2align                  4            \n\t"
+            "1:                                     \n\t"
+            "mov                      %2, %%"REG_c" \n\t"
+            "movzwl      (%%"REG_c", %0), %%eax     \n\t"
+            "movzwl     2(%%"REG_c", %0), %%edx     \n\t"
+            "mov                      %5, %%"REG_c" \n\t"
+            "pxor                  %%mm4, %%mm4     \n\t"
+            "pxor                  %%mm5, %%mm5     \n\t"
+            "2:                                     \n\t"
+            "movq                   (%1), %%mm1     \n\t"
+            "movq               (%1, %6), %%mm3     \n\t"
+            "movd (%%"REG_c", %%"REG_a"), %%mm0     \n\t"
+            "movd (%%"REG_c", %%"REG_d"), %%mm2     \n\t"
+            "punpcklbw             %%mm7, %%mm0     \n\t"
+            "punpcklbw             %%mm7, %%mm2     \n\t"
+            "pmaddwd               %%mm1, %%mm0     \n\t"
+            "pmaddwd               %%mm2, %%mm3     \n\t"
+            "paddd                 %%mm3, %%mm5     \n\t"
+            "paddd                 %%mm0, %%mm4     \n\t"
+            "add                      $8, %1        \n\t"
+            "add                      $4, %%"REG_c" \n\t"
+            "cmp                      %4, %%"REG_c" \n\t"
+            " jb                      2b            \n\t"
+            "add                      %6, %1        \n\t"
+            "movq                  %%mm4, %%mm0     \n\t"
+            "punpckldq             %%mm5, %%mm4     \n\t"
+            "punpckhdq             %%mm5, %%mm0     \n\t"
+            "paddd                 %%mm0, %%mm4     \n\t"
+            "psrad                    $7, %%mm4     \n\t"
+            "packssdw              %%mm4, %%mm4     \n\t"
+            "mov                      %3, %%"REG_a" \n\t"
+            "movd                  %%mm4, (%%"REG_a", %0)   \n\t"
+            "add                      $4, %0        \n\t"
+            " jnc                     1b            \n\t"
+
+            : "+r" (counter), "+r" (filter)
+            : "m" (filterPos), "m" (dst), "m"(offset),
+            "m" (src), "r" ((x86_reg)filterSize*2)
+            : "%"REG_a, "%"REG_c, "%"REG_d
+        );
+    }
+}
+
+//FIXME all pal and rgb srcFormats could do this convertion as well
+//FIXME all scalers more complex than bilinear could do half of this transform
+static void RENAME(chrRangeToJpeg)(uint16_t *dst, int width)
+{
+    int i;
+    for (i = 0; i < width; i++) {
+        dst[i     ] = (FFMIN(dst[i     ],30775)*4663 - 9289992)>>12; //-264
+        dst[i+VOFW] = (FFMIN(dst[i+VOFW],30775)*4663 - 9289992)>>12; //-264
+    }
+}
+static void RENAME(chrRangeFromJpeg)(uint16_t *dst, int width)
+{
+    int i;
+    for (i = 0; i < width; i++) {
+        dst[i     ] = (dst[i     ]*1799 + 4081085)>>11; //1469
+        dst[i+VOFW] = (dst[i+VOFW]*1799 + 4081085)>>11; //1469
+    }
+}
+static void RENAME(lumRangeToJpeg)(uint16_t *dst, int width)
+{
+    int i;
+    for (i = 0; i < width; i++)
+        dst[i] = (FFMIN(dst[i],30189)*19077 - 39057361)>>14;
+}
+static void RENAME(lumRangeFromJpeg)(uint16_t *dst, int width)
+{
+    int i;
+    for (i = 0; i < width; i++)
+        dst[i] = (dst[i]*14071 + 33561947)>>14;
+}
+
+#define FAST_BILINEAR_X86 \
+    "subl    %%edi, %%esi    \n\t" /*  src[xx+1] - src[xx] */                   \
+    "imull   %%ecx, %%esi    \n\t" /* (src[xx+1] - src[xx])*xalpha */           \
+    "shll      $16, %%edi    \n\t"                                              \
+    "addl    %%edi, %%esi    \n\t" /* src[xx+1]*xalpha + src[xx]*(1-xalpha) */  \
+    "mov        %1, %%"REG_D"\n\t"                                              \
+    "shrl       $9, %%esi    \n\t"                                              \
+
+static inline void RENAME(hyscale_fast)(SwsContext *c, int16_t *dst,
+                                        long dstWidth, const uint8_t *src, int srcW,
+                                        int xInc)
+{
+#if COMPILE_TEMPLATE_MMX2
+    int32_t *filterPos = c->hLumFilterPos;
+    int16_t *filter    = c->hLumFilter;
+    int     canMMX2BeUsed  = c->canMMX2BeUsed;
+    void    *mmx2FilterCode= c->lumMmx2FilterCode;
+    int i;
+#if defined(PIC)
+    DECLARE_ALIGNED(8, uint64_t, ebxsave);
+#endif
+    if (canMMX2BeUsed) {
+        __asm__ volatile(
+#if defined(PIC)
+            "mov               %%"REG_b", %5        \n\t"
+#endif
+            "pxor                  %%mm7, %%mm7     \n\t"
+            "mov                      %0, %%"REG_c" \n\t"
+            "mov                      %1, %%"REG_D" \n\t"
+            "mov                      %2, %%"REG_d" \n\t"
+            "mov                      %3, %%"REG_b" \n\t"
+            "xor               %%"REG_a", %%"REG_a" \n\t" // i
+            PREFETCH"        (%%"REG_c")            \n\t"
+            PREFETCH"      32(%%"REG_c")            \n\t"
+            PREFETCH"      64(%%"REG_c")            \n\t"
+
+#if ARCH_X86_64
+
+#define CALL_MMX2_FILTER_CODE \
+            "movl            (%%"REG_b"), %%esi     \n\t"\
+            "call                    *%4            \n\t"\
+            "movl (%%"REG_b", %%"REG_a"), %%esi     \n\t"\
+            "add               %%"REG_S", %%"REG_c" \n\t"\
+            "add               %%"REG_a", %%"REG_D" \n\t"\
+            "xor               %%"REG_a", %%"REG_a" \n\t"\
+
+#else
+
+#define CALL_MMX2_FILTER_CODE \
+            "movl (%%"REG_b"), %%esi        \n\t"\
+            "call         *%4                       \n\t"\
+            "addl (%%"REG_b", %%"REG_a"), %%"REG_c" \n\t"\
+            "add               %%"REG_a", %%"REG_D" \n\t"\
+            "xor               %%"REG_a", %%"REG_a" \n\t"\
+
+#endif /* ARCH_X86_64 */
+
+            CALL_MMX2_FILTER_CODE
+            CALL_MMX2_FILTER_CODE
+            CALL_MMX2_FILTER_CODE
+            CALL_MMX2_FILTER_CODE
+            CALL_MMX2_FILTER_CODE
+            CALL_MMX2_FILTER_CODE
+            CALL_MMX2_FILTER_CODE
+            CALL_MMX2_FILTER_CODE
+
+#if defined(PIC)
+            "mov                      %5, %%"REG_b" \n\t"
+#endif
+            :: "m" (src), "m" (dst), "m" (filter), "m" (filterPos),
+            "m" (mmx2FilterCode)
+#if defined(PIC)
+            ,"m" (ebxsave)
+#endif
+            : "%"REG_a, "%"REG_c, "%"REG_d, "%"REG_S, "%"REG_D
+#if !defined(PIC)
+            ,"%"REG_b
+#endif
+        );
+        for (i=dstWidth-1; (i*xInc)>>16 >=srcW-1; i--) dst[i] = src[srcW-1]*128;
+    } else {
+#endif /* COMPILE_TEMPLATE_MMX2 */
+    x86_reg xInc_shr16 = xInc >> 16;
+    uint16_t xInc_mask = xInc & 0xffff;
+    x86_reg dstWidth_reg = dstWidth;
+    //NO MMX just normal asm ...
+    __asm__ volatile(
+        "xor %%"REG_a", %%"REG_a"            \n\t" // i
+        "xor %%"REG_d", %%"REG_d"            \n\t" // xx
+        "xorl    %%ecx, %%ecx                \n\t" // xalpha
+        ".p2align                4           \n\t"
+        "1:                                  \n\t"
+        "movzbl    (%0, %%"REG_d"), %%edi    \n\t" //src[xx]
+        "movzbl   1(%0, %%"REG_d"), %%esi    \n\t" //src[xx+1]
+        FAST_BILINEAR_X86
+        "movw     %%si, (%%"REG_D", %%"REG_a", 2)   \n\t"
+        "addw       %4, %%cx                 \n\t" //xalpha += xInc&0xFFFF
+        "adc        %3, %%"REG_d"            \n\t" //xx+= xInc>>16 + carry
+
+        "movzbl    (%0, %%"REG_d"), %%edi    \n\t" //src[xx]
+        "movzbl   1(%0, %%"REG_d"), %%esi    \n\t" //src[xx+1]
+        FAST_BILINEAR_X86
+        "movw     %%si, 2(%%"REG_D", %%"REG_a", 2)  \n\t"
+        "addw       %4, %%cx                 \n\t" //xalpha += xInc&0xFFFF
+        "adc        %3, %%"REG_d"            \n\t" //xx+= xInc>>16 + carry
+
+
+        "add        $2, %%"REG_a"            \n\t"
+        "cmp        %2, %%"REG_a"            \n\t"
+        " jb        1b                       \n\t"
+
+
+        :: "r" (src), "m" (dst), "m" (dstWidth_reg), "m" (xInc_shr16), "m" (xInc_mask)
+        : "%"REG_a, "%"REG_d, "%ecx", "%"REG_D, "%esi"
+    );
+#if COMPILE_TEMPLATE_MMX2
+    } //if MMX2 can't be used
+#endif
+}
+
+      // *** horizontal scale Y line to temp buffer
+static inline void RENAME(hyscale)(SwsContext *c, uint16_t *dst, long dstWidth, const uint8_t *src, int srcW, int xInc,
+                                   const int16_t *hLumFilter,
+                                   const int16_t *hLumFilterPos, int hLumFilterSize,
+                                   uint8_t *formatConvBuffer,
+                                   uint32_t *pal, int isAlpha)
+{
+    void (*toYV12)(uint8_t *, const uint8_t *, long, uint32_t *) = isAlpha ? c->alpToYV12 : c->lumToYV12;
+    void (*convertRange)(uint16_t *, int) = isAlpha ? NULL : c->lumConvertRange;
+
+    src += isAlpha ? c->alpSrcOffset : c->lumSrcOffset;
+
+    if (toYV12) {
+        toYV12(formatConvBuffer, src, srcW, pal);
+        src= formatConvBuffer;
+    }
+
+    if (!c->hyscale_fast) {
+        c->hScale(dst, dstWidth, src, srcW, xInc, hLumFilter, hLumFilterPos, hLumFilterSize);
+    } else { // fast bilinear upscale / crap downscale
+        c->hyscale_fast(c, dst, dstWidth, src, srcW, xInc);
+    }
+
+    if (convertRange)
+        convertRange(dst, dstWidth);
+}
+
+static inline void RENAME(hcscale_fast)(SwsContext *c, int16_t *dst,
+                                        long dstWidth, const uint8_t *src1,
+                                        const uint8_t *src2, int srcW, int xInc)
+{
+#if COMPILE_TEMPLATE_MMX2
+    int32_t *filterPos = c->hChrFilterPos;
+    int16_t *filter    = c->hChrFilter;
+    int     canMMX2BeUsed  = c->canMMX2BeUsed;
+    void    *mmx2FilterCode= c->chrMmx2FilterCode;
+    int i;
+#if defined(PIC)
+    DECLARE_ALIGNED(8, uint64_t, ebxsave);
+#endif
+    if (canMMX2BeUsed) {
+        __asm__ volatile(
+#if defined(PIC)
+            "mov          %%"REG_b", %6         \n\t"
+#endif
+            "pxor             %%mm7, %%mm7      \n\t"
+            "mov                 %0, %%"REG_c"  \n\t"
+            "mov                 %1, %%"REG_D"  \n\t"
+            "mov                 %2, %%"REG_d"  \n\t"
+            "mov                 %3, %%"REG_b"  \n\t"
+            "xor          %%"REG_a", %%"REG_a"  \n\t" // i
+            PREFETCH"   (%%"REG_c")             \n\t"
+            PREFETCH" 32(%%"REG_c")             \n\t"
+            PREFETCH" 64(%%"REG_c")             \n\t"
+
+            CALL_MMX2_FILTER_CODE
+            CALL_MMX2_FILTER_CODE
+            CALL_MMX2_FILTER_CODE
+            CALL_MMX2_FILTER_CODE
+            "xor          %%"REG_a", %%"REG_a"  \n\t" // i
+            "mov                 %5, %%"REG_c"  \n\t" // src
+            "mov                 %1, %%"REG_D"  \n\t" // buf1
+            "add              $"AV_STRINGIFY(VOF)", %%"REG_D"  \n\t"
+            PREFETCH"   (%%"REG_c")             \n\t"
+            PREFETCH" 32(%%"REG_c")             \n\t"
+            PREFETCH" 64(%%"REG_c")             \n\t"
+
+            CALL_MMX2_FILTER_CODE
+            CALL_MMX2_FILTER_CODE
+            CALL_MMX2_FILTER_CODE
+            CALL_MMX2_FILTER_CODE
+
+#if defined(PIC)
+            "mov %6, %%"REG_b"    \n\t"
+#endif
+            :: "m" (src1), "m" (dst), "m" (filter), "m" (filterPos),
+            "m" (mmx2FilterCode), "m" (src2)
+#if defined(PIC)
+            ,"m" (ebxsave)
+#endif
+            : "%"REG_a, "%"REG_c, "%"REG_d, "%"REG_S, "%"REG_D
+#if !defined(PIC)
+            ,"%"REG_b
+#endif
+        );
+        for (i=dstWidth-1; (i*xInc)>>16 >=srcW-1; i--) {
+            //printf("%d %d %d\n", dstWidth, i, srcW);
+            dst[i] = src1[srcW-1]*128;
+            dst[i+VOFW] = src2[srcW-1]*128;
+        }
+    } else {
+#endif /* COMPILE_TEMPLATE_MMX2 */
+        x86_reg xInc_shr16 = (x86_reg) (xInc >> 16);
+        uint16_t xInc_mask = xInc & 0xffff;
+        x86_reg dstWidth_reg = dstWidth;
+        __asm__ volatile(
+            "xor %%"REG_a", %%"REG_a"               \n\t" // i
+            "xor %%"REG_d", %%"REG_d"               \n\t" // xx
+            "xorl    %%ecx, %%ecx                   \n\t" // xalpha
+            ".p2align    4                          \n\t"
+            "1:                                     \n\t"
+            "mov        %0, %%"REG_S"               \n\t"
+            "movzbl  (%%"REG_S", %%"REG_d"), %%edi  \n\t" //src[xx]
+            "movzbl 1(%%"REG_S", %%"REG_d"), %%esi  \n\t" //src[xx+1]
+            FAST_BILINEAR_X86
+            "movw     %%si, (%%"REG_D", %%"REG_a", 2)   \n\t"
+
+            "movzbl    (%5, %%"REG_d"), %%edi       \n\t" //src[xx]
+            "movzbl   1(%5, %%"REG_d"), %%esi       \n\t" //src[xx+1]
+            FAST_BILINEAR_X86
+            "movw     %%si, "AV_STRINGIFY(VOF)"(%%"REG_D", %%"REG_a", 2)   \n\t"
+
+            "addw       %4, %%cx                    \n\t" //xalpha += xInc&0xFFFF
+            "adc        %3, %%"REG_d"               \n\t" //xx+= xInc>>16 + carry
+            "add        $1, %%"REG_a"               \n\t"
+            "cmp        %2, %%"REG_a"               \n\t"
+            " jb        1b                          \n\t"
+
+/* GCC 3.3 makes MPlayer crash on IA-32 machines when using "g" operand here,
+which is needed to support GCC 4.0. */
+#if ARCH_X86_64 && AV_GCC_VERSION_AT_LEAST(3,4)
+            :: "m" (src1), "m" (dst), "g" (dstWidth_reg), "m" (xInc_shr16), "m" (xInc_mask),
+#else
+            :: "m" (src1), "m" (dst), "m" (dstWidth_reg), "m" (xInc_shr16), "m" (xInc_mask),
+#endif
+            "r" (src2)
+            : "%"REG_a, "%"REG_d, "%ecx", "%"REG_D, "%esi"
+        );
+#if COMPILE_TEMPLATE_MMX2
+    } //if MMX2 can't be used
+#endif
+}
+
+inline static void RENAME(hcscale)(SwsContext *c, uint16_t *dst, long dstWidth, const uint8_t *src1, const uint8_t *src2,
+                                   int srcW, int xInc, const int16_t *hChrFilter,
+                                   const int16_t *hChrFilterPos, int hChrFilterSize,
+                                   uint8_t *formatConvBuffer,
+                                   uint32_t *pal)
+{
+
+    src1 += c->chrSrcOffset;
+    src2 += c->chrSrcOffset;
+
+    if (c->chrToYV12) {
+        c->chrToYV12(formatConvBuffer, formatConvBuffer+VOFW, src1, src2, srcW, pal);
+        src1= formatConvBuffer;
+        src2= formatConvBuffer+VOFW;
+    }
+
+    if (!c->hcscale_fast) {
+        c->hScale(dst     , dstWidth, src1, srcW, xInc, hChrFilter, hChrFilterPos, hChrFilterSize);
+        c->hScale(dst+VOFW, dstWidth, src2, srcW, xInc, hChrFilter, hChrFilterPos, hChrFilterSize);
+    } else { // fast bilinear upscale / crap downscale
+        c->hcscale_fast(c, dst, dstWidth, src1, src2, srcW, xInc);
+    }
+
+    if (c->chrConvertRange)
+        c->chrConvertRange(dst, dstWidth);
+}
+
+#define DEBUG_SWSCALE_BUFFERS 0
+#define DEBUG_BUFFERS(...) if (DEBUG_SWSCALE_BUFFERS) av_log(c, AV_LOG_DEBUG, __VA_ARGS__)
+
+static int RENAME(swScale)(SwsContext *c, const uint8_t* src[], int srcStride[], int srcSliceY,
+                           int srcSliceH, uint8_t* dst[], int dstStride[])
+{
+    /* load a few things into local vars to make the code more readable? and faster */
+    const int srcW= c->srcW;
+    const int dstW= c->dstW;
+    const int dstH= c->dstH;
+    const int chrDstW= c->chrDstW;
+    const int chrSrcW= c->chrSrcW;
+    const int lumXInc= c->lumXInc;
+    const int chrXInc= c->chrXInc;
+    const enum PixelFormat dstFormat= c->dstFormat;
+    const int flags= c->flags;
+    int16_t *vLumFilterPos= c->vLumFilterPos;
+    int16_t *vChrFilterPos= c->vChrFilterPos;
+    int16_t *hLumFilterPos= c->hLumFilterPos;
+    int16_t *hChrFilterPos= c->hChrFilterPos;
+    int16_t *vLumFilter= c->vLumFilter;
+    int16_t *vChrFilter= c->vChrFilter;
+    int16_t *hLumFilter= c->hLumFilter;
+    int16_t *hChrFilter= c->hChrFilter;
+    int32_t *lumMmxFilter= c->lumMmxFilter;
+    int32_t *chrMmxFilter= c->chrMmxFilter;
+    int32_t av_unused *alpMmxFilter= c->alpMmxFilter;
+    const int vLumFilterSize= c->vLumFilterSize;
+    const int vChrFilterSize= c->vChrFilterSize;
+    const int hLumFilterSize= c->hLumFilterSize;
+    const int hChrFilterSize= c->hChrFilterSize;
+    int16_t **lumPixBuf= c->lumPixBuf;
+    int16_t **chrPixBuf= c->chrPixBuf;
+    int16_t **alpPixBuf= c->alpPixBuf;
+    const int vLumBufSize= c->vLumBufSize;
+    const int vChrBufSize= c->vChrBufSize;
+    uint8_t *formatConvBuffer= c->formatConvBuffer;
+    const int chrSrcSliceY= srcSliceY >> c->chrSrcVSubSample;
+    const int chrSrcSliceH= -((-srcSliceH) >> c->chrSrcVSubSample);
+    int lastDstY;
+    uint32_t *pal=c->pal_yuv;
+
+    /* vars which will change and which we need to store back in the context */
+    int dstY= c->dstY;
+    int lumBufIndex= c->lumBufIndex;
+    int chrBufIndex= c->chrBufIndex;
+    int lastInLumBuf= c->lastInLumBuf;
+    int lastInChrBuf= c->lastInChrBuf;
+
+    if (isPacked(c->srcFormat)) {
+        src[0]=
+        src[1]=
+        src[2]=
+        src[3]= src[0];
+        srcStride[0]=
+        srcStride[1]=
+        srcStride[2]=
+        srcStride[3]= srcStride[0];
+    }
+    srcStride[1]<<= c->vChrDrop;
+    srcStride[2]<<= c->vChrDrop;
+
+    DEBUG_BUFFERS("swScale() %p[%d] %p[%d] %p[%d] %p[%d] -> %p[%d] %p[%d] %p[%d] %p[%d]\n",
+                  src[0], srcStride[0], src[1], srcStride[1], src[2], srcStride[2], src[3], srcStride[3],
+                  dst[0], dstStride[0], dst[1], dstStride[1], dst[2], dstStride[2], dst[3], dstStride[3]);
+    DEBUG_BUFFERS("srcSliceY: %d srcSliceH: %d dstY: %d dstH: %d\n",
+                   srcSliceY,    srcSliceH,    dstY,    dstH);
+    DEBUG_BUFFERS("vLumFilterSize: %d vLumBufSize: %d vChrFilterSize: %d vChrBufSize: %d\n",
+                   vLumFilterSize,    vLumBufSize,    vChrFilterSize,    vChrBufSize);
+
+    if (dstStride[0]%8 !=0 || dstStride[1]%8 !=0 || dstStride[2]%8 !=0 || dstStride[3]%8 != 0) {
+        static int warnedAlready=0; //FIXME move this into the context perhaps
+        if (flags & SWS_PRINT_INFO && !warnedAlready) {
+            av_log(c, AV_LOG_WARNING, "Warning: dstStride is not aligned!\n"
+                   "         ->cannot do aligned memory accesses anymore\n");
+            warnedAlready=1;
+        }
+    }
+
+    /* Note the user might start scaling the picture in the middle so this
+       will not get executed. This is not really intended but works
+       currently, so people might do it. */
+    if (srcSliceY ==0) {
+        lumBufIndex=-1;
+        chrBufIndex=-1;
+        dstY=0;
+        lastInLumBuf= -1;
+        lastInChrBuf= -1;
+    }
+
+    lastDstY= dstY;
+
+    for (;dstY < dstH; dstY++) {
+        unsigned char *dest =dst[0]+dstStride[0]*dstY;
+        const int chrDstY= dstY>>c->chrDstVSubSample;
+        unsigned char *uDest=dst[1]+dstStride[1]*chrDstY;
+        unsigned char *vDest=dst[2]+dstStride[2]*chrDstY;
+        unsigned char *aDest=(CONFIG_SWSCALE_ALPHA && alpPixBuf) ? dst[3]+dstStride[3]*dstY : NULL;
+
+        const int firstLumSrcY= vLumFilterPos[dstY]; //First line needed as input
+        const int firstLumSrcY2= vLumFilterPos[FFMIN(dstY | ((1<<c->chrDstVSubSample) - 1), dstH-1)];
+        const int firstChrSrcY= vChrFilterPos[chrDstY]; //First line needed as input
+        int lastLumSrcY= firstLumSrcY + vLumFilterSize -1; // Last line needed as input
+        int lastLumSrcY2=firstLumSrcY2+ vLumFilterSize -1; // Last line needed as input
+        int lastChrSrcY= firstChrSrcY + vChrFilterSize -1; // Last line needed as input
+        int enough_lines;
+
+        //handle holes (FAST_BILINEAR & weird filters)
+        if (firstLumSrcY > lastInLumBuf) lastInLumBuf= firstLumSrcY-1;
+        if (firstChrSrcY > lastInChrBuf) lastInChrBuf= firstChrSrcY-1;
+        assert(firstLumSrcY >= lastInLumBuf - vLumBufSize + 1);
+        assert(firstChrSrcY >= lastInChrBuf - vChrBufSize + 1);
+
+        DEBUG_BUFFERS("dstY: %d\n", dstY);
+        DEBUG_BUFFERS("\tfirstLumSrcY: %d lastLumSrcY: %d lastInLumBuf: %d\n",
+                         firstLumSrcY,    lastLumSrcY,    lastInLumBuf);
+        DEBUG_BUFFERS("\tfirstChrSrcY: %d lastChrSrcY: %d lastInChrBuf: %d\n",
+                         firstChrSrcY,    lastChrSrcY,    lastInChrBuf);
+
+        // Do we have enough lines in this slice to output the dstY line
+        enough_lines = lastLumSrcY2 < srcSliceY + srcSliceH && lastChrSrcY < -((-srcSliceY - srcSliceH)>>c->chrSrcVSubSample);
+
+        if (!enough_lines) {
+            lastLumSrcY = srcSliceY + srcSliceH - 1;
+            lastChrSrcY = chrSrcSliceY + chrSrcSliceH - 1;
+            DEBUG_BUFFERS("buffering slice: lastLumSrcY %d lastChrSrcY %d\n",
+                                            lastLumSrcY, lastChrSrcY);
+        }
+
+        //Do horizontal scaling
+        while(lastInLumBuf < lastLumSrcY) {
+            const uint8_t *src1= src[0]+(lastInLumBuf + 1 - srcSliceY)*srcStride[0];
+            const uint8_t *src2= src[3]+(lastInLumBuf + 1 - srcSliceY)*srcStride[3];
+            lumBufIndex++;
+            assert(lumBufIndex < 2*vLumBufSize);
+            assert(lastInLumBuf + 1 - srcSliceY < srcSliceH);
+            assert(lastInLumBuf + 1 - srcSliceY >= 0);
+            RENAME(hyscale)(c, lumPixBuf[ lumBufIndex ], dstW, src1, srcW, lumXInc,
+                            hLumFilter, hLumFilterPos, hLumFilterSize,
+                            formatConvBuffer,
+                            pal, 0);
+            if (CONFIG_SWSCALE_ALPHA && alpPixBuf)
+                RENAME(hyscale)(c, alpPixBuf[ lumBufIndex ], dstW, src2, srcW, lumXInc,
+                                hLumFilter, hLumFilterPos, hLumFilterSize,
+                                formatConvBuffer,
+                                pal, 1);
+            lastInLumBuf++;
+            DEBUG_BUFFERS("\t\tlumBufIndex %d: lastInLumBuf: %d\n",
+                               lumBufIndex,    lastInLumBuf);
+        }
+        while(lastInChrBuf < lastChrSrcY) {
+            const uint8_t *src1= src[1]+(lastInChrBuf + 1 - chrSrcSliceY)*srcStride[1];
+            const uint8_t *src2= src[2]+(lastInChrBuf + 1 - chrSrcSliceY)*srcStride[2];
+            chrBufIndex++;
+            assert(chrBufIndex < 2*vChrBufSize);
+            assert(lastInChrBuf + 1 - chrSrcSliceY < (chrSrcSliceH));
+            assert(lastInChrBuf + 1 - chrSrcSliceY >= 0);
+            //FIXME replace parameters through context struct (some at least)
+
+            if (c->needs_hcscale)
+                RENAME(hcscale)(c, chrPixBuf[ chrBufIndex ], chrDstW, src1, src2, chrSrcW, chrXInc,
+                                hChrFilter, hChrFilterPos, hChrFilterSize,
+                                formatConvBuffer,
+                                pal);
+            lastInChrBuf++;
+            DEBUG_BUFFERS("\t\tchrBufIndex %d: lastInChrBuf: %d\n",
+                               chrBufIndex,    lastInChrBuf);
+        }
+        //wrap buf index around to stay inside the ring buffer
+        if (lumBufIndex >= vLumBufSize) lumBufIndex-= vLumBufSize;
+        if (chrBufIndex >= vChrBufSize) chrBufIndex-= vChrBufSize;
+        if (!enough_lines)
+            break; //we can't output a dstY line so let's try with the next slice
+
+        c->blueDither= ff_dither8[dstY&1];
+        if (c->dstFormat == PIX_FMT_RGB555 || c->dstFormat == PIX_FMT_BGR555)
+            c->greenDither= ff_dither8[dstY&1];
+        else
+            c->greenDither= ff_dither4[dstY&1];
+        c->redDither= ff_dither8[(dstY+1)&1];
+        if (dstY < dstH-2) {
+            const int16_t **lumSrcPtr= (const int16_t **) lumPixBuf + lumBufIndex + firstLumSrcY - lastInLumBuf + vLumBufSize;
+            const int16_t **chrSrcPtr= (const int16_t **) chrPixBuf + chrBufIndex + firstChrSrcY - lastInChrBuf + vChrBufSize;
+            const int16_t **alpSrcPtr= (CONFIG_SWSCALE_ALPHA && alpPixBuf) ? (const int16_t **) alpPixBuf + lumBufIndex + firstLumSrcY - lastInLumBuf + vLumBufSize : NULL;
+            int i;
+            if (flags & SWS_ACCURATE_RND) {
+                int s= APCK_SIZE / 8;
+                for (i=0; i<vLumFilterSize; i+=2) {
+                    *(const void**)&lumMmxFilter[s*i              ]= lumSrcPtr[i  ];
+                    *(const void**)&lumMmxFilter[s*i+APCK_PTR2/4  ]= lumSrcPtr[i+(vLumFilterSize>1)];
+                              lumMmxFilter[s*i+APCK_COEF/4  ]=
+                              lumMmxFilter[s*i+APCK_COEF/4+1]= vLumFilter[dstY*vLumFilterSize + i    ]
+                        + (vLumFilterSize>1 ? vLumFilter[dstY*vLumFilterSize + i + 1]<<16 : 0);
+                    if (CONFIG_SWSCALE_ALPHA && alpPixBuf) {
+                        *(const void**)&alpMmxFilter[s*i              ]= alpSrcPtr[i  ];
+                        *(const void**)&alpMmxFilter[s*i+APCK_PTR2/4  ]= alpSrcPtr[i+(vLumFilterSize>1)];
+                                  alpMmxFilter[s*i+APCK_COEF/4  ]=
+                                  alpMmxFilter[s*i+APCK_COEF/4+1]= lumMmxFilter[s*i+APCK_COEF/4  ];
+                    }
+                }
+                for (i=0; i<vChrFilterSize; i+=2) {
+                    *(const void**)&chrMmxFilter[s*i              ]= chrSrcPtr[i  ];
+                    *(const void**)&chrMmxFilter[s*i+APCK_PTR2/4  ]= chrSrcPtr[i+(vChrFilterSize>1)];
+                              chrMmxFilter[s*i+APCK_COEF/4  ]=
+                              chrMmxFilter[s*i+APCK_COEF/4+1]= vChrFilter[chrDstY*vChrFilterSize + i    ]
+                        + (vChrFilterSize>1 ? vChrFilter[chrDstY*vChrFilterSize + i + 1]<<16 : 0);
+                }
+            } else {
+                for (i=0; i<vLumFilterSize; i++) {
+                    lumMmxFilter[4*i+0]= (int32_t)lumSrcPtr[i];
+                    lumMmxFilter[4*i+1]= (uint64_t)lumSrcPtr[i] >> 32;
+                    lumMmxFilter[4*i+2]=
+                    lumMmxFilter[4*i+3]=
+                        ((uint16_t)vLumFilter[dstY*vLumFilterSize + i])*0x10001;
+                    if (CONFIG_SWSCALE_ALPHA && alpPixBuf) {
+                        alpMmxFilter[4*i+0]= (int32_t)alpSrcPtr[i];
+                        alpMmxFilter[4*i+1]= (uint64_t)alpSrcPtr[i] >> 32;
+                        alpMmxFilter[4*i+2]=
+                        alpMmxFilter[4*i+3]= lumMmxFilter[4*i+2];
+                    }
+                }
+                for (i=0; i<vChrFilterSize; i++) {
+                    chrMmxFilter[4*i+0]= (int32_t)chrSrcPtr[i];
+                    chrMmxFilter[4*i+1]= (uint64_t)chrSrcPtr[i] >> 32;
+                    chrMmxFilter[4*i+2]=
+                    chrMmxFilter[4*i+3]=
+                        ((uint16_t)vChrFilter[chrDstY*vChrFilterSize + i])*0x10001;
+                }
+            }
+            if (dstFormat == PIX_FMT_NV12 || dstFormat == PIX_FMT_NV21) {
+                const int chrSkipMask= (1<<c->chrDstVSubSample)-1;
+                if (dstY&chrSkipMask) uDest= NULL; //FIXME split functions in lumi / chromi
+                c->yuv2nv12X(c,
+                             vLumFilter+dstY*vLumFilterSize   , lumSrcPtr, vLumFilterSize,
+                             vChrFilter+chrDstY*vChrFilterSize, chrSrcPtr, vChrFilterSize,
+                             dest, uDest, dstW, chrDstW, dstFormat);
+            } else if (isPlanarYUV(dstFormat) || dstFormat==PIX_FMT_GRAY8) { //YV12 like
+                const int chrSkipMask= (1<<c->chrDstVSubSample)-1;
+                if ((dstY&chrSkipMask) || isGray(dstFormat)) uDest=vDest= NULL; //FIXME split functions in lumi / chromi
+                if (is16BPS(dstFormat)) {
+                    yuv2yuvX16inC(
+                                  vLumFilter+dstY*vLumFilterSize   , lumSrcPtr, vLumFilterSize,
+                                  vChrFilter+chrDstY*vChrFilterSize, chrSrcPtr, vChrFilterSize,
+                                  alpSrcPtr, (uint16_t *) dest, (uint16_t *) uDest, (uint16_t *) vDest, (uint16_t *) aDest, dstW, chrDstW,
+                                  dstFormat);
+                } else if (vLumFilterSize == 1 && vChrFilterSize == 1) { // unscaled YV12
+                    const int16_t *lumBuf = lumSrcPtr[0];
+                    const int16_t *chrBuf= chrSrcPtr[0];
+                    const int16_t *alpBuf= (CONFIG_SWSCALE_ALPHA && alpPixBuf) ? alpSrcPtr[0] : NULL;
+                    c->yuv2yuv1(c, lumBuf, chrBuf, alpBuf, dest, uDest, vDest, aDest, dstW, chrDstW);
+                } else { //General YV12
+                    c->yuv2yuvX(c,
+                                vLumFilter+dstY*vLumFilterSize   , lumSrcPtr, vLumFilterSize,
+                                vChrFilter+chrDstY*vChrFilterSize, chrSrcPtr, vChrFilterSize,
+                                alpSrcPtr, dest, uDest, vDest, aDest, dstW, chrDstW);
+                }
+            } else {
+                assert(lumSrcPtr + vLumFilterSize - 1 < lumPixBuf + vLumBufSize*2);
+                assert(chrSrcPtr + vChrFilterSize - 1 < chrPixBuf + vChrBufSize*2);
+                if (vLumFilterSize == 1 && vChrFilterSize == 2) { //unscaled RGB
+                    int chrAlpha= vChrFilter[2*dstY+1];
+                    if(flags & SWS_FULL_CHR_H_INT) {
+                        yuv2rgbXinC_full(c, //FIXME write a packed1_full function
+                                         vLumFilter+dstY*vLumFilterSize, lumSrcPtr, vLumFilterSize,
+                                         vChrFilter+dstY*vChrFilterSize, chrSrcPtr, vChrFilterSize,
+                                         alpSrcPtr, dest, dstW, dstY);
+                    } else {
+                        c->yuv2packed1(c, *lumSrcPtr, *chrSrcPtr, *(chrSrcPtr+1),
+                                       alpPixBuf ? *alpSrcPtr : NULL,
+                                       dest, dstW, chrAlpha, dstFormat, flags, dstY);
+                    }
+                } else if (vLumFilterSize == 2 && vChrFilterSize == 2) { //bilinear upscale RGB
+                    int lumAlpha= vLumFilter[2*dstY+1];
+                    int chrAlpha= vChrFilter[2*dstY+1];
+                    lumMmxFilter[2]=
+                    lumMmxFilter[3]= vLumFilter[2*dstY   ]*0x10001;
+                    chrMmxFilter[2]=
+                    chrMmxFilter[3]= vChrFilter[2*chrDstY]*0x10001;
+                    if(flags & SWS_FULL_CHR_H_INT) {
+                        yuv2rgbXinC_full(c, //FIXME write a packed2_full function
+                                         vLumFilter+dstY*vLumFilterSize, lumSrcPtr, vLumFilterSize,
+                                         vChrFilter+dstY*vChrFilterSize, chrSrcPtr, vChrFilterSize,
+                                         alpSrcPtr, dest, dstW, dstY);
+                    } else {
+                        c->yuv2packed2(c, *lumSrcPtr, *(lumSrcPtr+1), *chrSrcPtr, *(chrSrcPtr+1),
+                                       alpPixBuf ? *alpSrcPtr : NULL, alpPixBuf ? *(alpSrcPtr+1) : NULL,
+                                       dest, dstW, lumAlpha, chrAlpha, dstY);
+                    }
+                } else { //general RGB
+                    if(flags & SWS_FULL_CHR_H_INT) {
+                        yuv2rgbXinC_full(c,
+                                         vLumFilter+dstY*vLumFilterSize, lumSrcPtr, vLumFilterSize,
+                                         vChrFilter+dstY*vChrFilterSize, chrSrcPtr, vChrFilterSize,
+                                         alpSrcPtr, dest, dstW, dstY);
+                    } else {
+                        c->yuv2packedX(c,
+                                       vLumFilter+dstY*vLumFilterSize, lumSrcPtr, vLumFilterSize,
+                                       vChrFilter+dstY*vChrFilterSize, chrSrcPtr, vChrFilterSize,
+                                       alpSrcPtr, dest, dstW, dstY);
+                    }
+                }
+            }
+        } else { // hmm looks like we can't use MMX here without overwriting this array's tail
+            const int16_t **lumSrcPtr= (const int16_t **)lumPixBuf + lumBufIndex + firstLumSrcY - lastInLumBuf + vLumBufSize;
+            const int16_t **chrSrcPtr= (const int16_t **)chrPixBuf + chrBufIndex + firstChrSrcY - lastInChrBuf + vChrBufSize;
+            const int16_t **alpSrcPtr= (CONFIG_SWSCALE_ALPHA && alpPixBuf) ? (const int16_t **)alpPixBuf + lumBufIndex + firstLumSrcY - lastInLumBuf + vLumBufSize : NULL;
+            if (dstFormat == PIX_FMT_NV12 || dstFormat == PIX_FMT_NV21) {
+                const int chrSkipMask= (1<<c->chrDstVSubSample)-1;
+                if (dstY&chrSkipMask) uDest= NULL; //FIXME split functions in lumi / chromi
+                yuv2nv12XinC(
+                             vLumFilter+dstY*vLumFilterSize   , lumSrcPtr, vLumFilterSize,
+                             vChrFilter+chrDstY*vChrFilterSize, chrSrcPtr, vChrFilterSize,
+                             dest, uDest, dstW, chrDstW, dstFormat);
+            } else if (isPlanarYUV(dstFormat) || dstFormat==PIX_FMT_GRAY8) { //YV12
+                const int chrSkipMask= (1<<c->chrDstVSubSample)-1;
+                if ((dstY&chrSkipMask) || isGray(dstFormat)) uDest=vDest= NULL; //FIXME split functions in lumi / chromi
+                if (is16BPS(dstFormat)) {
+                    yuv2yuvX16inC(
+                                  vLumFilter+dstY*vLumFilterSize   , lumSrcPtr, vLumFilterSize,
+                                  vChrFilter+chrDstY*vChrFilterSize, chrSrcPtr, vChrFilterSize,
+                                  alpSrcPtr, (uint16_t *) dest, (uint16_t *) uDest, (uint16_t *) vDest, (uint16_t *) aDest, dstW, chrDstW,
+                                  dstFormat);
+                } else {
+                    yuv2yuvXinC(
+                                vLumFilter+dstY*vLumFilterSize   , lumSrcPtr, vLumFilterSize,
+                                vChrFilter+chrDstY*vChrFilterSize, chrSrcPtr, vChrFilterSize,
+                                alpSrcPtr, dest, uDest, vDest, aDest, dstW, chrDstW);
+                }
+            } else {
+                assert(lumSrcPtr + vLumFilterSize - 1 < lumPixBuf + vLumBufSize*2);
+                assert(chrSrcPtr + vChrFilterSize - 1 < chrPixBuf + vChrBufSize*2);
+                if(flags & SWS_FULL_CHR_H_INT) {
+                    yuv2rgbXinC_full(c,
+                                     vLumFilter+dstY*vLumFilterSize, lumSrcPtr, vLumFilterSize,
+                                     vChrFilter+dstY*vChrFilterSize, chrSrcPtr, vChrFilterSize,
+                                     alpSrcPtr, dest, dstW, dstY);
+                } else {
+                    yuv2packedXinC(c,
+                                   vLumFilter+dstY*vLumFilterSize, lumSrcPtr, vLumFilterSize,
+                                   vChrFilter+dstY*vChrFilterSize, chrSrcPtr, vChrFilterSize,
+                                   alpSrcPtr, dest, dstW, dstY);
+                }
+            }
+        }
+    }
+
+    if ((dstFormat == PIX_FMT_YUVA420P) && !alpPixBuf)
+        fillPlane(dst[3], dstStride[3], dstW, dstY-lastDstY, lastDstY, 255);
+
+    if (flags & SWS_CPU_CAPS_MMX2 )  __asm__ volatile("sfence":::"memory");
+    /* On K6 femms is faster than emms. On K7 femms is directly mapped to emms. */
+    if (flags & SWS_CPU_CAPS_3DNOW)  __asm__ volatile("femms" :::"memory");
+    else                             __asm__ volatile("emms"  :::"memory");
+    /* store changed local vars back in the context */
+    c->dstY= dstY;
+    c->lumBufIndex= lumBufIndex;
+    c->chrBufIndex= chrBufIndex;
+    c->lastInLumBuf= lastInLumBuf;
+    c->lastInChrBuf= lastInChrBuf;
+
+    return dstY - lastDstY;
+}
+
+static void RENAME(sws_init_swScale)(SwsContext *c)
+{
+    enum PixelFormat srcFormat = c->srcFormat;
+
+    c->yuv2nv12X    = RENAME(yuv2nv12X   );
+    c->yuv2yuv1     = RENAME(yuv2yuv1    );
+    c->yuv2yuvX     = RENAME(yuv2yuvX    );
+    c->yuv2packed1  = RENAME(yuv2packed1 );
+    c->yuv2packed2  = RENAME(yuv2packed2 );
+    c->yuv2packedX  = RENAME(yuv2packedX );
+
+    c->hScale       = RENAME(hScale      );
+
+    // Use the new MMX scaler if the MMX2 one can't be used (it is faster than the x86 ASM one).
+    if (c->flags & SWS_FAST_BILINEAR && c->canMMX2BeUsed)
+    {
+        c->hyscale_fast = RENAME(hyscale_fast);
+        c->hcscale_fast = RENAME(hcscale_fast);
+    } else {
+        c->hyscale_fast = NULL;
+        c->hcscale_fast = NULL;
+    }
+
+    switch(srcFormat) {
+        case PIX_FMT_YUYV422  : c->chrToYV12 = RENAME(yuy2ToUV); break;
+        case PIX_FMT_UYVY422  : c->chrToYV12 = RENAME(uyvyToUV); break;
+        case PIX_FMT_NV12     : c->chrToYV12 = RENAME(nv12ToUV); break;
+        case PIX_FMT_NV21     : c->chrToYV12 = RENAME(nv21ToUV); break;
+        case PIX_FMT_YUV420P16BE:
+        case PIX_FMT_YUV422P16BE:
+        case PIX_FMT_YUV444P16BE: c->chrToYV12 = RENAME(BEToUV); break;
+        case PIX_FMT_YUV420P16LE:
+        case PIX_FMT_YUV422P16LE:
+        case PIX_FMT_YUV444P16LE: c->chrToYV12 = RENAME(LEToUV); break;
+        default: break;
+    }
+    if (c->chrSrcHSubSample) {
+        switch(srcFormat) {
+        case PIX_FMT_BGR24  : c->chrToYV12 = RENAME(bgr24ToUV_half); break;
+        case PIX_FMT_RGB24  : c->chrToYV12 = RENAME(rgb24ToUV_half); break;
+        default: break;
+        }
+    } else {
+        switch(srcFormat) {
+        case PIX_FMT_BGR24  : c->chrToYV12 = RENAME(bgr24ToUV); break;
+        case PIX_FMT_RGB24  : c->chrToYV12 = RENAME(rgb24ToUV); break;
+        default: break;
+        }
+    }
+
+    switch (srcFormat) {
+    case PIX_FMT_YUYV422  :
+    case PIX_FMT_YUV420P16BE:
+    case PIX_FMT_YUV422P16BE:
+    case PIX_FMT_YUV444P16BE:
+    case PIX_FMT_Y400A    :
+    case PIX_FMT_GRAY16BE : c->lumToYV12 = RENAME(yuy2ToY); break;
+    case PIX_FMT_UYVY422  :
+    case PIX_FMT_YUV420P16LE:
+    case PIX_FMT_YUV422P16LE:
+    case PIX_FMT_YUV444P16LE:
+    case PIX_FMT_GRAY16LE : c->lumToYV12 = RENAME(uyvyToY); break;
+    case PIX_FMT_BGR24    : c->lumToYV12 = RENAME(bgr24ToY); break;
+    case PIX_FMT_RGB24    : c->lumToYV12 = RENAME(rgb24ToY); break;
+    default: break;
+    }
+    if (c->alpPixBuf) {
+        switch (srcFormat) {
+        case PIX_FMT_Y400A  : c->alpToYV12 = RENAME(yuy2ToY); break;
+        default: break;
+        }
+    }
+
+    if (c->srcRange != c->dstRange && !isAnyRGB(c->dstFormat)) {
+        if (c->srcRange) {
+            c->lumConvertRange = RENAME(lumRangeFromJpeg);
+            c->chrConvertRange = RENAME(chrRangeFromJpeg);
+        } else {
+            c->lumConvertRange = RENAME(lumRangeToJpeg);
+            c->chrConvertRange = RENAME(chrRangeToJpeg);
+        }
+    }
+}
diff --git a/libswscale/x86/swscale_template.h b/libswscale/x86/swscale_template.h
new file mode 100644
index 0000000..320e563
--- /dev/null
+++ b/libswscale/x86/swscale_template.h
@@ -0,0 +1,79 @@
+/*
+ * Copyright (C) 2001-2003 Michael Niedermayer <michaelni at gmx.at>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+
+#ifndef SWSCALE_X86_SWSCALE_TEMPLATE_H
+#define SWSCALE_X86_SWSCALE_TEMPLATE_H
+
+DECLARE_ASM_CONST(8, uint64_t, bF8)=       0xF8F8F8F8F8F8F8F8LL;
+DECLARE_ASM_CONST(8, uint64_t, bFC)=       0xFCFCFCFCFCFCFCFCLL;
+DECLARE_ASM_CONST(8, uint64_t, w10)=       0x0010001000100010LL;
+DECLARE_ASM_CONST(8, uint64_t, w02)=       0x0002000200020002LL;
+DECLARE_ASM_CONST(8, uint64_t, bm00001111)=0x00000000FFFFFFFFLL;
+DECLARE_ASM_CONST(8, uint64_t, bm00000111)=0x0000000000FFFFFFLL;
+DECLARE_ASM_CONST(8, uint64_t, bm11111000)=0xFFFFFFFFFF000000LL;
+DECLARE_ASM_CONST(8, uint64_t, bm01010101)=0x00FF00FF00FF00FFLL;
+
+const DECLARE_ALIGNED(8, uint64_t, ff_dither4)[2] = {
+        0x0103010301030103LL,
+        0x0200020002000200LL,};
+
+const DECLARE_ALIGNED(8, uint64_t, ff_dither8)[2] = {
+        0x0602060206020602LL,
+        0x0004000400040004LL,};
+
+DECLARE_ASM_CONST(8, uint64_t, b16Mask)=   0x001F001F001F001FLL;
+DECLARE_ASM_CONST(8, uint64_t, g16Mask)=   0x07E007E007E007E0LL;
+DECLARE_ASM_CONST(8, uint64_t, r16Mask)=   0xF800F800F800F800LL;
+DECLARE_ASM_CONST(8, uint64_t, b15Mask)=   0x001F001F001F001FLL;
+DECLARE_ASM_CONST(8, uint64_t, g15Mask)=   0x03E003E003E003E0LL;
+DECLARE_ASM_CONST(8, uint64_t, r15Mask)=   0x7C007C007C007C00LL;
+
+DECLARE_ALIGNED(8, const uint64_t, ff_M24A)         = 0x00FF0000FF0000FFLL;
+DECLARE_ALIGNED(8, const uint64_t, ff_M24B)         = 0xFF0000FF0000FF00LL;
+DECLARE_ALIGNED(8, const uint64_t, ff_M24C)         = 0x0000FF0000FF0000LL;
+
+#ifdef FAST_BGR2YV12
+DECLARE_ALIGNED(8, const uint64_t, ff_bgr2YCoeff)   = 0x000000210041000DULL;
+DECLARE_ALIGNED(8, const uint64_t, ff_bgr2UCoeff)   = 0x0000FFEEFFDC0038ULL;
+DECLARE_ALIGNED(8, const uint64_t, ff_bgr2VCoeff)   = 0x00000038FFD2FFF8ULL;
+#else
+DECLARE_ALIGNED(8, const uint64_t, ff_bgr2YCoeff)   = 0x000020E540830C8BULL;
+DECLARE_ALIGNED(8, const uint64_t, ff_bgr2UCoeff)   = 0x0000ED0FDAC23831ULL;
+DECLARE_ALIGNED(8, const uint64_t, ff_bgr2VCoeff)   = 0x00003831D0E6F6EAULL;
+#endif /* FAST_BGR2YV12 */
+DECLARE_ALIGNED(8, const uint64_t, ff_bgr2YOffset)  = 0x1010101010101010ULL;
+DECLARE_ALIGNED(8, const uint64_t, ff_bgr2UVOffset) = 0x8080808080808080ULL;
+DECLARE_ALIGNED(8, const uint64_t, ff_w1111)        = 0x0001000100010001ULL;
+
+DECLARE_ASM_CONST(8, uint64_t, ff_bgr24toY1Coeff) = 0x0C88000040870C88ULL;
+DECLARE_ASM_CONST(8, uint64_t, ff_bgr24toY2Coeff) = 0x20DE4087000020DEULL;
+DECLARE_ASM_CONST(8, uint64_t, ff_rgb24toY1Coeff) = 0x20DE0000408720DEULL;
+DECLARE_ASM_CONST(8, uint64_t, ff_rgb24toY2Coeff) = 0x0C88408700000C88ULL;
+DECLARE_ASM_CONST(8, uint64_t, ff_bgr24toYOffset) = 0x0008400000084000ULL;
+
+DECLARE_ASM_CONST(8, uint64_t, ff_bgr24toUV)[2][4] = {
+    {0x38380000DAC83838ULL, 0xECFFDAC80000ECFFULL, 0xF6E40000D0E3F6E4ULL, 0x3838D0E300003838ULL},
+    {0xECFF0000DAC8ECFFULL, 0x3838DAC800003838ULL, 0x38380000D0E33838ULL, 0xF6E4D0E30000F6E4ULL},
+};
+
+DECLARE_ASM_CONST(8, uint64_t, ff_bgr24toUVOffset)= 0x0040400000404000ULL;
+
+#endif /* SWSCALE_X86_SWSCALE_TEMPLATE_H */
diff --git a/libswscale/x86/yuv2rgb_mmx.c b/libswscale/x86/yuv2rgb_mmx.c
index d042421..ff3a93d 100644
--- a/libswscale/x86/yuv2rgb_mmx.c
+++ b/libswscale/x86/yuv2rgb_mmx.c
@@ -7,20 +7,20 @@
  * 1,4,8bpp support and context / deglobalize stuff
  * by Michael Niedermayer (michaelni at gmx.at)
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -41,6 +41,9 @@
 DECLARE_ASM_CONST(8, uint64_t, mmx_00ffw)   = 0x00ff00ff00ff00ffULL;
 DECLARE_ASM_CONST(8, uint64_t, mmx_redmask) = 0xf8f8f8f8f8f8f8f8ULL;
 DECLARE_ASM_CONST(8, uint64_t, mmx_grnmask) = 0xfcfcfcfcfcfcfcfcULL;
+DECLARE_ASM_CONST(8, uint64_t, pb_e0) = 0xe0e0e0e0e0e0e0e0ULL;
+DECLARE_ASM_CONST(8, uint64_t, pb_03) = 0x0303030303030303ULL;
+DECLARE_ASM_CONST(8, uint64_t, pb_07) = 0x0707070707070707ULL;
 
 //MMX versions
 #undef RENAME
@@ -49,22 +52,14 @@ DECLARE_ASM_CONST(8, uint64_t, mmx_grnmask) = 0xfcfcfcfcfcfcfcfcULL;
 #define HAVE_MMX2 0
 #define HAVE_AMD3DNOW 0
 #define RENAME(a) a ## _MMX
-#if CONFIG_GPL
 #include "yuv2rgb_template.c"
-#else
-#include "yuv2rgb_template2.c"
-#endif
 
 //MMX2 versions
 #undef RENAME
 #undef HAVE_MMX2
 #define HAVE_MMX2 1
 #define RENAME(a) a ## _MMX2
-#if CONFIG_GPL
 #include "yuv2rgb_template.c"
-#else
-#include "yuv2rgb_template2.c"
-#endif
 
 SwsFunc ff_yuv2rgb_init_mmx(SwsContext *c)
 {
diff --git a/libswscale/x86/yuv2rgb_template.c b/libswscale/x86/yuv2rgb_template.c
index ba90689..cf8f0d3 100644
--- a/libswscale/x86/yuv2rgb_template.c
+++ b/libswscale/x86/yuv2rgb_template.c
@@ -1,28 +1,23 @@
 /*
- * yuv2rgb_mmx.c, software YUV to RGB converter with Intel MMX "technology"
+ * software YUV to RGB converter
  *
- * Copyright (C) 2000, Silicon Integrated System Corp
+ * Copyright (C) 2001-2007 Michael Niedermayer
+ *           (c) 2010 Konstantin Shishkov
  *
- * Author: Olie Lho <ollie at sis.com.tw>
+ * This file is part of Libav.
  *
- * 15,24 bpp and dithering from Michael Niedermayer (michaelni at gmx.at)
- * MMX/MMX2 Template stuff from Michael Niedermayer (needed for fast movntq support)
- * context / deglobalize stuff by Michael Niedermayer
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
  *
- * This file is part of mpeg2dec, a free MPEG-2 video decoder
- *
- * mpeg2dec is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2, or (at your option)
- * any later version.
- *
- * mpeg2dec is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
  *
- * You should have received a copy of the GNU General Public License
- * along with mpeg2dec; if not, write to the Free Software
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -32,9 +27,9 @@
 
 #if HAVE_AMD3DNOW
 /* On K6 femms is faster than emms. On K7 femms is directly mapped to emms. */
-#define EMMS     "femms"
+#define EMMS   "femms"
 #else
-#define EMMS     "emms"
+#define EMMS   "emms"
 #endif
 
 #if HAVE_MMX2
@@ -45,520 +40,418 @@
 #define SFENCE " # nop"
 #endif
 
-#define YUV2RGB \
-    /* Do the multiply part of the conversion for even and odd pixels,
-       register usage:
-       mm0 -> Cblue, mm1 -> Cred, mm2 -> Cgreen even pixels,
-       mm3 -> Cblue, mm4 -> Cred, mm5 -> Cgreen odd pixels,
-       mm6 -> Y even, mm7 -> Y odd */\
-    /* convert the chroma part */\
-    "punpcklbw %%mm4, %%mm0;" /* scatter 4 Cb 00 u3 00 u2 00 u1 00 u0 */ \
-    "punpcklbw %%mm4, %%mm1;" /* scatter 4 Cr 00 v3 00 v2 00 v1 00 v0 */ \
-\
-    "psllw $3, %%mm0;" /* Promote precision */ \
-    "psllw $3, %%mm1;" /* Promote precision */ \
-\
-    "psubsw "U_OFFSET"(%4), %%mm0;" /* Cb -= 128 */ \
-    "psubsw "V_OFFSET"(%4), %%mm1;" /* Cr -= 128 */ \
-\
-    "movq %%mm0, %%mm2;" /* Copy 4 Cb 00 u3 00 u2 00 u1 00 u0 */ \
-    "movq %%mm1, %%mm3;" /* Copy 4 Cr 00 v3 00 v2 00 v1 00 v0 */ \
-\
-    "pmulhw "UG_COEFF"(%4), %%mm2;" /* Mul Cb with green coeff -> Cb green */ \
-    "pmulhw "VG_COEFF"(%4), %%mm3;" /* Mul Cr with green coeff -> Cr green */ \
-\
-    "pmulhw "UB_COEFF"(%4), %%mm0;" /* Mul Cb -> Cblue 00 b3 00 b2 00 b1 00 b0 */\
-    "pmulhw "VR_COEFF"(%4), %%mm1;" /* Mul Cr -> Cred 00 r3 00 r2 00 r1 00 r0 */\
-\
-    "paddsw %%mm3, %%mm2;" /* Cb green + Cr green -> Cgreen */\
-\
-    /* convert the luma part */\
-    "movq %%mm6, %%mm7;" /* Copy 8 Y Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y0 */\
-    "pand "MANGLE(mmx_00ffw)", %%mm6;" /* get Y even 00 Y6 00 Y4 00 Y2 00 Y0 */\
-\
-    "psrlw $8, %%mm7;" /* get Y odd 00 Y7 00 Y5 00 Y3 00 Y1 */\
-\
-    "psllw $3, %%mm6;" /* Promote precision */\
-    "psllw $3, %%mm7;" /* Promote precision */\
-\
-    "psubw "Y_OFFSET"(%4), %%mm6;" /* Y -= 16 */\
-    "psubw "Y_OFFSET"(%4), %%mm7;" /* Y -= 16 */\
-\
-    "pmulhw "Y_COEFF"(%4), %%mm6;" /* Mul 4 Y even 00 y6 00 y4 00 y2 00 y0 */\
-    "pmulhw "Y_COEFF"(%4), %%mm7;" /* Mul 4 Y odd 00 y7 00 y5 00 y3 00 y1 */\
-\
-    /* Do the addition part of the conversion for even and odd pixels,
-       register usage:
-       mm0 -> Cblue, mm1 -> Cred, mm2 -> Cgreen even pixels,
-       mm3 -> Cblue, mm4 -> Cred, mm5 -> Cgreen odd pixels,
-       mm6 -> Y even, mm7 -> Y odd */\
-    "movq %%mm0, %%mm3;" /* Copy Cblue */\
-    "movq %%mm1, %%mm4;" /* Copy Cred */\
-    "movq %%mm2, %%mm5;" /* Copy Cgreen */\
-\
-    "paddsw %%mm6, %%mm0;" /* Y even + Cblue 00 B6 00 B4 00 B2 00 B0 */\
-    "paddsw %%mm7, %%mm3;" /* Y odd + Cblue 00 B7 00 B5 00 B3 00 B1 */\
-\
-    "paddsw %%mm6, %%mm1;" /* Y even + Cred 00 R6 00 R4 00 R2 00 R0 */\
-    "paddsw %%mm7, %%mm4;" /* Y odd + Cred 00 R7 00 R5 00 R3 00 R1 */\
-\
-    "paddsw %%mm6, %%mm2;" /* Y even + Cgreen 00 G6 00 G4 00 G2 00 G0 */\
-    "paddsw %%mm7, %%mm5;" /* Y odd + Cgreen 00 G7 00 G5 00 G3 00 G1 */\
-\
-    /* Limit RGB even to 0..255 */\
-    "packuswb %%mm0, %%mm0;" /* B6 B4 B2 B0  B6 B4 B2 B0 */\
-    "packuswb %%mm1, %%mm1;" /* R6 R4 R2 R0  R6 R4 R2 R0 */\
-    "packuswb %%mm2, %%mm2;" /* G6 G4 G2 G0  G6 G4 G2 G0 */\
-\
-    /* Limit RGB odd to 0..255 */\
-    "packuswb %%mm3, %%mm3;" /* B7 B5 B3 B1  B7 B5 B3 B1 */\
-    "packuswb %%mm4, %%mm4;" /* R7 R5 R3 R1  R7 R5 R3 R1 */\
-    "packuswb %%mm5, %%mm5;" /* G7 G5 G3 G1  G7 G5 G3 G1 */\
-\
-    /* Interleave RGB even and odd */\
-    "punpcklbw %%mm3, %%mm0;" /* B7 B6 B5 B4 B3 B2 B1 B0 */\
-    "punpcklbw %%mm4, %%mm1;" /* R7 R6 R5 R4 R3 R2 R1 R0 */\
-    "punpcklbw %%mm5, %%mm2;" /* G7 G6 G5 G4 G3 G2 G1 G0 */\
-
-
-#define YUV422_UNSHIFT                   \
-    if(c->srcFormat == PIX_FMT_YUV422P) {\
-        srcStride[1] *= 2;               \
-        srcStride[2] *= 2;               \
-    }                                    \
+#define REG_BLUE  "0"
+#define REG_RED   "1"
+#define REG_GREEN "2"
+#define REG_ALPHA "3"
 
-#define YUV2RGB_LOOP(depth)                                   \
-    h_size= (c->dstW+7)&~7;                                   \
-    if(h_size*depth > FFABS(dstStride[0])) h_size-=8;         \
-\
-    __asm__ volatile ("pxor %mm4, %mm4;" /* zero mm4 */ );    \
-    for (y= 0; y<srcSliceH; y++ ) {                           \
-        uint8_t *image = dst[0] + (y+srcSliceY)*dstStride[0]; \
-        const uint8_t *py = src[0] + y*srcStride[0];          \
-        const uint8_t *pu = src[1] + (y>>1)*srcStride[1];     \
-        const uint8_t *pv = src[2] + (y>>1)*srcStride[2];     \
-        x86_reg index= -h_size/2;                                \
-
-#define YUV2RGB_INIT                                                       \
-        /* This MMX assembly code deals with a SINGLE scan line at a time, \
-         * it converts 8 pixels in each iteration. */                      \
-        __asm__ volatile (                                                 \
-        /* load data for start of next scan line */                        \
-        "movd    (%2, %0), %%mm0;" /* Load 4 Cb 00 00 00 00 u3 u2 u1 u0 */ \
-        "movd    (%3, %0), %%mm1;" /* Load 4 Cr 00 00 00 00 v3 v2 v1 v0 */ \
-        "movq (%5, %0, 2), %%mm6;" /* Load 8  Y Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y0 */ \
-        /*                                                                 \
-        ".balign 16     \n\t"                                              \
-        */                                                                 \
-        "1:             \n\t"                                              \
-        /* No speed difference on my p3 at 500 with prefetch,                 \
-         * if it is faster for anyone with -benchmark then tell me.        \
-        PREFETCH" 64(%0) \n\t"                                             \
-        PREFETCH" 64(%1) \n\t"                                             \
-        PREFETCH" 64(%2) \n\t"                                             \
-        */                                                                 \
-
-#define YUV2RGB_ENDLOOP(depth) \
-        "add $"AV_STRINGIFY(depth*8)", %1    \n\t" \
-        "add                       $4, %0    \n\t" \
-        " js                       1b        \n\t" \
-
-#define YUV2RGB_OPERANDS \
-        : "+r" (index), "+r" (image) \
-        : "r" (pu - index), "r" (pv - index), "r"(&c->redDither), "r" (py - 2*index) \
-        ); \
-    } \
-    __asm__ volatile (SFENCE"\n\t"EMMS); \
-    return srcSliceH; \
-
-#define YUV2RGB_OPERANDS_ALPHA \
-        : "+r" (index), "+r" (image) \
-        : "r" (pu - index), "r" (pv - index), "r"(&c->redDither), "r" (py - 2*index), "r" (pa - 2*index) \
-        ); \
-    } \
-    __asm__ volatile (SFENCE"\n\t"EMMS); \
-    return srcSliceH; \
-
-static inline int RENAME(yuv420_rgb16)(SwsContext *c, const uint8_t* src[], int srcStride[], int srcSliceY,
-                                       int srcSliceH, uint8_t* dst[], int dstStride[])
+#define YUV2RGB_LOOP(depth)                                          \
+    h_size = (c->dstW + 7) & ~7;                                     \
+    if (h_size * depth > FFABS(dstStride[0]))                        \
+        h_size -= 8;                                                 \
+                                                                     \
+    if (c->srcFormat == PIX_FMT_YUV422P) {                           \
+        srcStride[1] *= 2;                                           \
+        srcStride[2] *= 2;                                           \
+    }                                                                \
+                                                                     \
+    __asm__ volatile ("pxor %mm4, %mm4\n\t");                        \
+    for (y = 0; y < srcSliceH; y++) {                                \
+        uint8_t *image    = dst[0] + (y + srcSliceY) * dstStride[0]; \
+        const uint8_t *py = src[0] +               y * srcStride[0]; \
+        const uint8_t *pu = src[1] +        (y >> 1) * srcStride[1]; \
+        const uint8_t *pv = src[2] +        (y >> 1) * srcStride[2]; \
+        x86_reg index = -h_size / 2;                                 \
+
+#define YUV2RGB_INITIAL_LOAD          \
+    __asm__ volatile (                \
+        "movq (%5, %0, 2), %%mm6\n\t" \
+        "movd    (%2, %0), %%mm0\n\t" \
+        "movd    (%3, %0), %%mm1\n\t" \
+        "1: \n\t"                     \
+
+/* YUV2RGB core
+ * Conversion is performed in usual way:
+ * R = Y' * Ycoef + Vred * V'
+ * G = Y' * Ycoef + Vgreen * V' + Ugreen * U'
+ * B = Y' * Ycoef               + Ublue * U'
+ *
+ * where X' = X * 8 - Xoffset (multiplication is performed to increase
+ * precision a bit).
+ * Since it operates in YUV420 colorspace, Y component is additionally
+ * split into Y1 and Y2 for even and odd pixels.
+ *
+ * Input:
+ * mm0 - U (4 elems), mm1 - V (4 elems), mm6 - Y (8 elems), mm4 - zero register
+ * Output:
+ * mm1 - R, mm2 - G, mm0 - B
+ */
+#define YUV2RGB                                  \
+    /* convert Y, U, V into Y1', Y2', U', V' */  \
+    "movq      %%mm6, %%mm7\n\t"                 \
+    "punpcklbw %%mm4, %%mm0\n\t"                 \
+    "punpcklbw %%mm4, %%mm1\n\t"                 \
+    "pand     "MANGLE(mmx_00ffw)", %%mm6\n\t"    \
+    "psrlw     $8,    %%mm7\n\t"                 \
+    "psllw     $3,    %%mm0\n\t"                 \
+    "psllw     $3,    %%mm1\n\t"                 \
+    "psllw     $3,    %%mm6\n\t"                 \
+    "psllw     $3,    %%mm7\n\t"                 \
+    "psubsw   "U_OFFSET"(%4), %%mm0\n\t"         \
+    "psubsw   "V_OFFSET"(%4), %%mm1\n\t"         \
+    "psubw    "Y_OFFSET"(%4), %%mm6\n\t"         \
+    "psubw    "Y_OFFSET"(%4), %%mm7\n\t"         \
+\
+     /* multiply by coefficients */              \
+    "movq      %%mm0, %%mm2\n\t"                 \
+    "movq      %%mm1, %%mm3\n\t"                 \
+    "pmulhw   "UG_COEFF"(%4), %%mm2\n\t"         \
+    "pmulhw   "VG_COEFF"(%4), %%mm3\n\t"         \
+    "pmulhw   "Y_COEFF" (%4), %%mm6\n\t"         \
+    "pmulhw   "Y_COEFF" (%4), %%mm7\n\t"         \
+    "pmulhw   "UB_COEFF"(%4), %%mm0\n\t"         \
+    "pmulhw   "VR_COEFF"(%4), %%mm1\n\t"         \
+    "paddsw    %%mm3, %%mm2\n\t"                 \
+    /* now: mm0 = UB, mm1 = VR, mm2 = CG */      \
+    /*      mm6 = Y1, mm7 = Y2 */                \
+\
+    /* produce RGB */                            \
+    "movq      %%mm7, %%mm3\n\t"                 \
+    "movq      %%mm7, %%mm5\n\t"                 \
+    "paddsw    %%mm0, %%mm3\n\t"                 \
+    "paddsw    %%mm1, %%mm5\n\t"                 \
+    "paddsw    %%mm2, %%mm7\n\t"                 \
+    "paddsw    %%mm6, %%mm0\n\t"                 \
+    "paddsw    %%mm6, %%mm1\n\t"                 \
+    "paddsw    %%mm6, %%mm2\n\t"                 \
+
+#define RGB_PACK_INTERLEAVE                  \
+    /* pack and interleave even/odd pixels */    \
+    "packuswb  %%mm1, %%mm0\n\t"                 \
+    "packuswb  %%mm5, %%mm3\n\t"                 \
+    "packuswb  %%mm2, %%mm2\n\t"                 \
+    "movq      %%mm0, %%mm1\n\n"                 \
+    "packuswb  %%mm7, %%mm7\n\t"                 \
+    "punpcklbw %%mm3, %%mm0\n\t"                 \
+    "punpckhbw %%mm3, %%mm1\n\t"                 \
+    "punpcklbw %%mm7, %%mm2\n\t"                 \
+
+#define YUV2RGB_ENDLOOP(depth)                   \
+    "movq 8 (%5, %0, 2), %%mm6\n\t"              \
+    "movd 4 (%3, %0),    %%mm1\n\t"              \
+    "movd 4 (%2, %0),    %%mm0\n\t"              \
+    "add $"AV_STRINGIFY(depth * 8)", %1\n\t"     \
+    "add  $4, %0\n\t"                            \
+    "js   1b\n\t"                                \
+
+#define YUV2RGB_OPERANDS                                          \
+        : "+r" (index), "+r" (image)                              \
+        : "r" (pu - index), "r" (pv - index), "r"(&c->redDither), \
+          "r" (py - 2*index)                                      \
+        );                                                        \
+    }                                                             \
+
+#define YUV2RGB_OPERANDS_ALPHA                                    \
+        : "+r" (index), "+r" (image)                              \
+        : "r" (pu - index), "r" (pv - index), "r"(&c->redDither), \
+          "r" (py - 2*index), "r" (pa - 2*index)                  \
+        );                                                        \
+    }                                                             \
+
+#define YUV2RGB_ENDFUNC                          \
+    __asm__ volatile (SFENCE"\n\t"EMMS);         \
+    return srcSliceH;                            \
+
+#define IF0(x)
+#define IF1(x) x
+
+#define RGB_PACK16(gmask, is15)                  \
+    "pand      "MANGLE(mmx_redmask)", %%mm0\n\t" \
+    "pand      "MANGLE(mmx_redmask)", %%mm1\n\t" \
+    "movq      %%mm2,     %%mm3\n\t"             \
+    "psllw   $"AV_STRINGIFY(3-is15)", %%mm2\n\t" \
+    "psrlw   $"AV_STRINGIFY(5+is15)", %%mm3\n\t" \
+    "psrlw     $3,        %%mm0\n\t"             \
+    IF##is15("psrlw  $1,  %%mm1\n\t")            \
+    "pand "MANGLE(pb_e0)", %%mm2\n\t"            \
+    "pand "MANGLE(gmask)", %%mm3\n\t"            \
+    "por       %%mm2,     %%mm0\n\t"             \
+    "por       %%mm3,     %%mm1\n\t"             \
+    "movq      %%mm0,     %%mm2\n\t"             \
+    "punpcklbw %%mm1,     %%mm0\n\t"             \
+    "punpckhbw %%mm1,     %%mm2\n\t"             \
+    MOVNTQ "   %%mm0,      (%1)\n\t"             \
+    MOVNTQ "   %%mm2,     8(%1)\n\t"             \
+
+#define DITHER_RGB                               \
+    "paddusb "BLUE_DITHER"(%4),  %%mm0\n\t"      \
+    "paddusb "GREEN_DITHER"(%4), %%mm2\n\t"      \
+    "paddusb "RED_DITHER"(%4),   %%mm1\n\t"      \
+
+static inline int RENAME(yuv420_rgb15)(SwsContext *c, const uint8_t *src[],
+                                       int srcStride[],
+                                       int srcSliceY, int srcSliceH,
+                                       uint8_t *dst[], int dstStride[])
 {
     int y, h_size;
 
-    YUV422_UNSHIFT
     YUV2RGB_LOOP(2)
 
-        c->blueDither= ff_dither8[y&1];
-        c->greenDither= ff_dither4[y&1];
-        c->redDither= ff_dither8[(y+1)&1];
+#ifdef DITHER1XBPP
+        c->blueDither  = ff_dither8[y       & 1];
+        c->greenDither = ff_dither8[y       & 1];
+        c->redDither   = ff_dither8[(y + 1) & 1];
+#endif
 
-        YUV2RGB_INIT
+        YUV2RGB_INITIAL_LOAD
         YUV2RGB
-
+        RGB_PACK_INTERLEAVE
 #ifdef DITHER1XBPP
-        "paddusb "BLUE_DITHER"(%4), %%mm0;"
-        "paddusb "GREEN_DITHER"(%4), %%mm2;"
-        "paddusb "RED_DITHER"(%4), %%mm1;"
+        DITHER_RGB
 #endif
-        /* mask unneeded bits off */
-        "pand "MANGLE(mmx_redmask)", %%mm0;" /* b7b6b5b4 b3_0_0_0 b7b6b5b4 b3_0_0_0 */
-        "pand "MANGLE(mmx_grnmask)", %%mm2;" /* g7g6g5g4 g3g2_0_0 g7g6g5g4 g3g2_0_0 */
-        "pand "MANGLE(mmx_redmask)", %%mm1;" /* r7r6r5r4 r3_0_0_0 r7r6r5r4 r3_0_0_0 */
-
-        "psrlw   $3, %%mm0;" /* 0_0_0_b7 b6b5b4b3 0_0_0_b7 b6b5b4b3 */
-        "pxor %%mm4, %%mm4;" /* zero mm4 */
-
-        "movq %%mm0, %%mm5;" /* Copy B7-B0 */
-        "movq %%mm2, %%mm7;" /* Copy G7-G0 */
-
-        /* convert RGB24 plane to RGB16 pack for pixel 0-3 */
-        "punpcklbw %%mm4, %%mm2;" /* 0_0_0_0 0_0_0_0 g7g6g5g4 g3g2_0_0 */
-        "punpcklbw %%mm1, %%mm0;" /* r7r6r5r4 r3_0_0_0 0_0_0_b7 b6b5b4b3 */
-
-        "psllw  $3, %%mm2;" /* 0_0_0_0 0_g7g6g5 g4g3g2_0 0_0_0_0 */
-        "por %%mm2, %%mm0;" /* r7r6r5r4 r3g7g6g5 g4g3g2b7 b6b5b4b3 */
-
-        "movq 8 (%5, %0, 2), %%mm6;" /* Load 8 Y Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y0 */
-        MOVNTQ "      %%mm0, (%1);" /* store pixel 0-3 */
-
-        /* convert RGB24 plane to RGB16 pack for pixel 0-3 */
-        "punpckhbw %%mm4, %%mm7;" /* 0_0_0_0 0_0_0_0 g7g6g5g4 g3g2_0_0 */
-        "punpckhbw %%mm1, %%mm5;" /* r7r6r5r4 r3_0_0_0 0_0_0_b7 b6b5b4b3 */
-
-        "psllw        $3, %%mm7;" /* 0_0_0_0 0_g7g6g5 g4g3g2_0 0_0_0_0 */
-        "movd 4 (%2, %0), %%mm0;" /* Load 4 Cb 00 00 00 00 u3 u2 u1 u0 */
-
-        "por       %%mm7, %%mm5;" /* r7r6r5r4 r3g7g6g5 g4g3g2b7 b6b5b4b3 */
-        "movd 4 (%3, %0), %%mm1;" /* Load 4 Cr 00 00 00 00 v3 v2 v1 v0 */
-
-        MOVNTQ "   %%mm5, 8 (%1);" /* store pixel 4-7 */
+        RGB_PACK16(pb_03, 1)
 
     YUV2RGB_ENDLOOP(2)
     YUV2RGB_OPERANDS
+    YUV2RGB_ENDFUNC
 }
 
-static inline int RENAME(yuv420_rgb15)(SwsContext *c, const uint8_t* src[], int srcStride[], int srcSliceY,
-                                       int srcSliceH, uint8_t* dst[], int dstStride[])
+static inline int RENAME(yuv420_rgb16)(SwsContext *c, const uint8_t *src[],
+                                       int srcStride[],
+                                       int srcSliceY, int srcSliceH,
+                                       uint8_t *dst[], int dstStride[])
 {
     int y, h_size;
 
-    YUV422_UNSHIFT
     YUV2RGB_LOOP(2)
 
-        c->blueDither= ff_dither8[y&1];
-        c->greenDither= ff_dither8[y&1];
-        c->redDither= ff_dither8[(y+1)&1];
+#ifdef DITHER1XBPP
+        c->blueDither  = ff_dither8[y       & 1];
+        c->greenDither = ff_dither4[y       & 1];
+        c->redDither   = ff_dither8[(y + 1) & 1];
+#endif
 
-        YUV2RGB_INIT
+        YUV2RGB_INITIAL_LOAD
         YUV2RGB
-
+        RGB_PACK_INTERLEAVE
 #ifdef DITHER1XBPP
-        "paddusb "BLUE_DITHER"(%4), %%mm0  \n\t"
-        "paddusb "GREEN_DITHER"(%4), %%mm2  \n\t"
-        "paddusb "RED_DITHER"(%4), %%mm1  \n\t"
+        DITHER_RGB
 #endif
-
-        /* mask unneeded bits off */
-        "pand "MANGLE(mmx_redmask)", %%mm0;" /* b7b6b5b4 b3_0_0_0 b7b6b5b4 b3_0_0_0 */
-        "pand "MANGLE(mmx_redmask)", %%mm2;" /* g7g6g5g4 g3_0_0_0 g7g6g5g4 g3_0_0_0 */
-        "pand "MANGLE(mmx_redmask)", %%mm1;" /* r7r6r5r4 r3_0_0_0 r7r6r5r4 r3_0_0_0 */
-
-        "psrlw   $3, %%mm0;" /* 0_0_0_b7 b6b5b4b3 0_0_0_b7 b6b5b4b3 */
-        "psrlw   $1, %%mm1;" /* 0_r7r6r5  r4r3_0_0 0_r7r6r5 r4r3_0_0 */
-        "pxor %%mm4, %%mm4;" /* zero mm4 */
-
-        "movq %%mm0, %%mm5;" /* Copy B7-B0 */
-        "movq %%mm2, %%mm7;" /* Copy G7-G0 */
-
-        /* convert RGB24 plane to RGB16 pack for pixel 0-3 */
-        "punpcklbw %%mm4, %%mm2;" /* 0_0_0_0 0_0_0_0 g7g6g5g4 g3_0_0_0 */
-        "punpcklbw %%mm1, %%mm0;" /* r7r6r5r4 r3_0_0_0 0_0_0_b7 b6b5b4b3 */
-
-        "psllw  $2, %%mm2;" /* 0_0_0_0 0_0_g7g6 g5g4g3_0 0_0_0_0 */
-        "por %%mm2, %%mm0;" /* 0_r7r6r5 r4r3g7g6 g5g4g3b7 b6b5b4b3 */
-
-        "movq 8 (%5, %0, 2), %%mm6;" /* Load 8 Y Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y0 */
-        MOVNTQ "      %%mm0, (%1);"  /* store pixel 0-3 */
-
-        /* convert RGB24 plane to RGB16 pack for pixel 0-3 */
-        "punpckhbw %%mm4, %%mm7;" /* 0_0_0_0 0_0_0_0 0_g7g6g5 g4g3_0_0 */
-        "punpckhbw %%mm1, %%mm5;" /* r7r6r5r4 r3_0_0_0 0_0_0_b7 b6b5b4b3 */
-
-        "psllw        $2, %%mm7;" /* 0_0_0_0 0_0_g7g6 g5g4g3_0 0_0_0_0 */
-        "movd 4 (%2, %0), %%mm0;" /* Load 4 Cb 00 00 00 00 u3 u2 u1 u0 */
-
-        "por       %%mm7, %%mm5;" /* 0_r7r6r5 r4r3g7g6 g5g4g3b7 b6b5b4b3 */
-        "movd 4 (%3, %0), %%mm1;" /* Load 4 Cr 00 00 00 00 v3 v2 v1 v0 */
-
-        MOVNTQ " %%mm5, 8 (%1);" /* store pixel 4-7 */
+        RGB_PACK16(pb_07, 0)
 
     YUV2RGB_ENDLOOP(2)
     YUV2RGB_OPERANDS
+    YUV2RGB_ENDFUNC
 }
 
-#undef RGB_PLANAR2PACKED24
+#define RGB_PACK24(blue, red)\
+    "packuswb  %%mm3,      %%mm0 \n" /* R0 R2 R4 R6 R1 R3 R5 R7 */\
+    "packuswb  %%mm5,      %%mm1 \n" /* B0 B2 B4 B6 B1 B3 B5 B7 */\
+    "packuswb  %%mm7,      %%mm2 \n" /* G0 G2 G4 G6 G1 G3 G5 G7 */\
+    "movq      %%mm"red",  %%mm3 \n"\
+    "movq      %%mm"blue", %%mm6 \n"\
+    "psrlq     $32,        %%mm"red" \n" /* R1 R3 R5 R7 */\
+    "punpcklbw %%mm2,      %%mm3 \n" /* R0 G0 R2 G2 R4 G4 R6 G6 */\
+    "punpcklbw %%mm"red",  %%mm6 \n" /* B0 R1 B2 R3 B4 R5 B6 R7 */\
+    "movq      %%mm3,      %%mm5 \n"\
+    "punpckhbw %%mm"blue", %%mm2 \n" /* G1 B1 G3 B3 G5 B5 G7 B7 */\
+    "punpcklwd %%mm6,      %%mm3 \n" /* R0 G0 B0 R1 R2 G2 B2 R3 */\
+    "punpckhwd %%mm6,      %%mm5 \n" /* R4 G4 B4 R5 R6 G6 B6 R7 */\
+    RGB_PACK24_B
+
 #if HAVE_MMX2
-#define RGB_PLANAR2PACKED24(red, blue)\
-        "movq "MANGLE(ff_M24A)", %%mm4     \n\t"\
-        "movq "MANGLE(ff_M24C)", %%mm7     \n\t"\
-        "pshufw $0x50, %%mm"blue", %%mm5   \n\t" /* B3 B2 B3 B2  B1 B0 B1 B0 */\
-        "pshufw $0x50, %%mm2, %%mm3     \n\t" /* G3 G2 G3 G2  G1 G0 G1 G0 */\
-        "pshufw $0x00, %%mm"red", %%mm6 \n\t" /* R1 R0 R1 R0  R1 R0 R1 R0 */\
-\
-        "pand   %%mm4, %%mm5            \n\t" /*    B2        B1       B0 */\
-        "pand   %%mm4, %%mm3            \n\t" /*    G2        G1       G0 */\
-        "pand   %%mm7, %%mm6            \n\t" /*       R1        R0       */\
-\
-        "psllq     $8, %%mm3            \n\t" /* G2        G1       G0    */\
-        "por    %%mm5, %%mm6            \n\t"\
-        "por    %%mm3, %%mm6            \n\t"\
-        MOVNTQ" %%mm6, (%1)             \n\t"\
-\
-        "psrlq     $8, %%mm2            \n\t" /* 00 G7 G6 G5  G4 G3 G2 G1 */\
-        "pshufw $0xA5, %%mm"blue", %%mm5\n\t" /* B5 B4 B5 B4  B3 B2 B3 B2 */\
-        "pshufw $0x55, %%mm2, %%mm3     \n\t" /* G4 G3 G4 G3  G4 G3 G4 G3 */\
-        "pshufw $0xA5, %%mm"red", %%mm6 \n\t" /* R5 R4 R5 R4  R3 R2 R3 R2 */\
-\
-        "pand "MANGLE(ff_M24B)", %%mm5  \n\t" /* B5       B4        B3    */\
-        "pand          %%mm7, %%mm3     \n\t" /*       G4        G3       */\
-        "pand          %%mm4, %%mm6     \n\t" /*    R4        R3       R2 */\
-\
-        "por    %%mm5, %%mm3            \n\t" /* B5    G4 B4     G3 B3    */\
-        "por    %%mm3, %%mm6            \n\t"\
-        MOVNTQ" %%mm6, 8(%1)            \n\t"\
-\
-        "pshufw $0xFF, %%mm"blue", %%mm5\n\t" /* B7 B6 B7 B6  B7 B6 B6 B7 */\
-        "pshufw $0xFA, %%mm2, %%mm3     \n\t" /* 00 G7 00 G7  G6 G5 G6 G5 */\
-        "pshufw $0xFA, %%mm"red", %%mm6 \n\t" /* R7 R6 R7 R6  R5 R4 R5 R4 */\
-        "movd 4 (%2, %0), %%mm0;" /* Load 4 Cb 00 00 00 00 u3 u2 u1 u0 */\
-\
-        "pand          %%mm7, %%mm5     \n\t" /*       B7        B6       */\
-        "pand          %%mm4, %%mm3     \n\t" /*    G7        G6       G5 */\
-        "pand "MANGLE(ff_M24B)", %%mm6  \n\t" /* R7       R6        R5    */\
-        "movd 4 (%3, %0), %%mm1;" /* Load 4 Cr 00 00 00 00 v3 v2 v1 v0 */\
-\
-        "por          %%mm5, %%mm3      \n\t"\
-        "por          %%mm3, %%mm6      \n\t"\
-        MOVNTQ"       %%mm6, 16(%1)     \n\t"\
-        "movq 8 (%5, %0, 2), %%mm6;" /* Load 8 Y Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y0 */\
-        "pxor         %%mm4, %%mm4      \n\t"
+DECLARE_ASM_CONST(8, int16_t, mask1101[4]) = {-1,-1, 0,-1};
+DECLARE_ASM_CONST(8, int16_t, mask0010[4]) = { 0, 0,-1, 0};
+DECLARE_ASM_CONST(8, int16_t, mask0110[4]) = { 0,-1,-1, 0};
+DECLARE_ASM_CONST(8, int16_t, mask1001[4]) = {-1, 0, 0,-1};
+DECLARE_ASM_CONST(8, int16_t, mask0100[4]) = { 0,-1, 0, 0};
+#undef RGB_PACK24_B
+#define RGB_PACK24_B\
+    "pshufw    $0xc6,  %%mm2, %%mm1 \n"\
+    "pshufw    $0x84,  %%mm3, %%mm6 \n"\
+    "pshufw    $0x38,  %%mm5, %%mm7 \n"\
+    "pand "MANGLE(mask1101)", %%mm6 \n" /* R0 G0 B0 R1 -- -- R2 G2 */\
+    "movq      %%mm1,         %%mm0 \n"\
+    "pand "MANGLE(mask0110)", %%mm7 \n" /* -- -- R6 G6 B6 R7 -- -- */\
+    "movq      %%mm1,         %%mm2 \n"\
+    "pand "MANGLE(mask0100)", %%mm1 \n" /* -- -- G3 B3 -- -- -- -- */\
+    "psrlq       $48,         %%mm3 \n" /* B2 R3 -- -- -- -- -- -- */\
+    "pand "MANGLE(mask0010)", %%mm0 \n" /* -- -- -- -- G1 B1 -- -- */\
+    "psllq       $32,         %%mm5 \n" /* -- -- -- -- R4 G4 B4 R5 */\
+    "pand "MANGLE(mask1001)", %%mm2 \n" /* G5 B5 -- -- -- -- G7 B7 */\
+    "por       %%mm3,         %%mm1 \n"\
+    "por       %%mm6,         %%mm0 \n"\
+    "por       %%mm5,         %%mm1 \n"\
+    "por       %%mm7,         %%mm2 \n"\
+    MOVNTQ"    %%mm0,          (%1) \n"\
+    MOVNTQ"    %%mm1,         8(%1) \n"\
+    MOVNTQ"    %%mm2,        16(%1) \n"\
+
 #else
-#define RGB_PLANAR2PACKED24(red, blue)\
-        "pxor      %%mm4, %%mm4     \n\t"\
-        "movq      %%mm"blue", %%mm5\n\t" /* B */\
-        "movq      %%mm"red", %%mm6 \n\t" /* R */\
-        "punpcklbw %%mm2, %%mm"blue"\n\t" /* GBGBGBGB 0 */\
-        "punpcklbw %%mm4, %%mm"red" \n\t" /* 0R0R0R0R 0 */\
-        "punpckhbw %%mm2, %%mm5     \n\t" /* GBGBGBGB 2 */\
-        "punpckhbw %%mm4, %%mm6     \n\t" /* 0R0R0R0R 2 */\
-        "movq      %%mm"blue", %%mm7\n\t" /* GBGBGBGB 0 */\
-        "movq      %%mm5, %%mm3     \n\t" /* GBGBGBGB 2 */\
-        "punpcklwd %%mm"red", %%mm7 \n\t" /* 0RGB0RGB 0 */\
-        "punpckhwd %%mm"red", %%mm"blue"\n\t" /* 0RGB0RGB 1 */\
-        "punpcklwd %%mm6, %%mm5     \n\t" /* 0RGB0RGB 2 */\
-        "punpckhwd %%mm6, %%mm3     \n\t" /* 0RGB0RGB 3 */\
-\
-        "movq      %%mm7, %%mm2     \n\t" /* 0RGB0RGB 0 */\
-        "movq      %%mm"blue", %%mm6\n\t" /* 0RGB0RGB 1 */\
-        "movq      %%mm5, %%mm"red" \n\t" /* 0RGB0RGB 2 */\
-        "movq      %%mm3, %%mm4     \n\t" /* 0RGB0RGB 3 */\
-\
-        "psllq       $40, %%mm7     \n\t" /* RGB00000 0 */\
-        "psllq       $40, %%mm"blue"\n\t" /* RGB00000 1 */\
-        "psllq       $40, %%mm5     \n\t" /* RGB00000 2 */\
-        "psllq       $40, %%mm3     \n\t" /* RGB00000 3 */\
-\
-        "punpckhdq %%mm2, %%mm7     \n\t" /* 0RGBRGB0 0 */\
-        "punpckhdq %%mm6, %%mm"blue"\n\t" /* 0RGBRGB0 1 */\
-        "punpckhdq %%mm"red", %%mm5 \n\t" /* 0RGBRGB0 2 */\
-        "punpckhdq %%mm4, %%mm3     \n\t" /* 0RGBRGB0 3 */\
-\
-        "psrlq        $8, %%mm7     \n\t" /* 00RGBRGB 0 */\
-        "movq      %%mm"blue", %%mm6\n\t" /* 0RGBRGB0 1 */\
-        "psllq       $40, %%mm"blue"\n\t" /* GB000000 1 */\
-        "por       %%mm"blue", %%mm7\n\t" /* GBRGBRGB 0 */\
-        MOVNTQ"    %%mm7, (%1)      \n\t"\
-\
-        "psrlq       $24, %%mm6     \n\t" /* 0000RGBR 1 */\
-        "movq      %%mm5, %%mm"red" \n\t" /* 0RGBRGB0 2 */\
-        "psllq       $24, %%mm5     \n\t" /* BRGB0000 2 */\
-        "por       %%mm5, %%mm6     \n\t" /* BRGBRGBR 1 */\
-        MOVNTQ"    %%mm6, 8(%1)     \n\t"\
-\
-        "movq 8 (%5, %0, 2), %%mm6;" /* Load 8 Y Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y0 */\
-\
-        "psrlq       $40, %%mm"red" \n\t" /* 000000RG 2 */\
-        "psllq        $8, %%mm3     \n\t" /* RGBRGB00 3 */\
-        "por       %%mm3, %%mm"red" \n\t" /* RGBRGBRG 2 */\
-        MOVNTQ"    %%mm"red", 16(%1)\n\t"\
-\
-        "movd 4 (%3, %0), %%mm1;" /* Load 4 Cr 00 00 00 00 v3 v2 v1 v0 */\
-        "movd 4 (%2, %0), %%mm0;" /* Load 4 Cb 00 00 00 00 u3 u2 u1 u0 */\
-        "pxor      %%mm4, %%mm4     \n\t"
+#undef RGB_PACK24_B
+#define RGB_PACK24_B\
+    "movd      %%mm3,       (%1) \n" /* R0 G0 B0 R1 */\
+    "movd      %%mm2,      4(%1) \n" /* G1 B1 */\
+    "psrlq     $32,        %%mm3 \n"\
+    "psrlq     $16,        %%mm2 \n"\
+    "movd      %%mm3,      6(%1) \n" /* R2 G2 B2 R3 */\
+    "movd      %%mm2,     10(%1) \n" /* G3 B3 */\
+    "psrlq     $16,        %%mm2 \n"\
+    "movd      %%mm5,     12(%1) \n" /* R4 G4 B4 R5 */\
+    "movd      %%mm2,     16(%1) \n" /* G5 B5 */\
+    "psrlq     $32,        %%mm5 \n"\
+    "movd      %%mm2,     20(%1) \n" /* -- -- G7 B7 */\
+    "movd      %%mm5,     18(%1) \n" /* R6 G6 B6 R7 */\
+
 #endif
 
-static inline int RENAME(yuv420_rgb24)(SwsContext *c, const uint8_t* src[], int srcStride[], int srcSliceY,
-                                       int srcSliceH, uint8_t* dst[], int dstStride[])
+static inline int RENAME(yuv420_rgb24)(SwsContext *c, const uint8_t *src[],
+                                       int srcStride[],
+                                       int srcSliceY, int srcSliceH,
+                                       uint8_t *dst[], int dstStride[])
 {
     int y, h_size;
 
-    YUV422_UNSHIFT
     YUV2RGB_LOOP(3)
 
-        YUV2RGB_INIT
+        YUV2RGB_INITIAL_LOAD
         YUV2RGB
-        /* mm0=B, %%mm2=G, %%mm1=R */
-        RGB_PLANAR2PACKED24("0", "1")
+        RGB_PACK24(REG_BLUE, REG_RED)
 
     YUV2RGB_ENDLOOP(3)
     YUV2RGB_OPERANDS
+    YUV2RGB_ENDFUNC
 }
 
-static inline int RENAME(yuv420_bgr24)(SwsContext *c, const uint8_t* src[], int srcStride[], int srcSliceY,
-                                       int srcSliceH, uint8_t* dst[], int dstStride[])
+static inline int RENAME(yuv420_bgr24)(SwsContext *c, const uint8_t *src[],
+                                       int srcStride[],
+                                       int srcSliceY, int srcSliceH,
+                                       uint8_t *dst[], int dstStride[])
 {
     int y, h_size;
 
-    YUV422_UNSHIFT
     YUV2RGB_LOOP(3)
 
-        YUV2RGB_INIT
+        YUV2RGB_INITIAL_LOAD
         YUV2RGB
-        /* mm0=B, %%mm2=G, %%mm1=R */
-        RGB_PLANAR2PACKED24("1", "0")
+        RGB_PACK24(REG_RED, REG_BLUE)
 
     YUV2RGB_ENDLOOP(3)
     YUV2RGB_OPERANDS
+    YUV2RGB_ENDFUNC
 }
 
-/*
 
-RGB_PLANAR2PACKED32(red,green,blue,alpha)
-
-convert RGB plane to RGB packed format
-
-macro parameters specify the output color channel order:
-
-RGB_PLANAR2PACKED32(REG_RED,  REG_GREEN, REG_BLUE, REG_ALPHA) for RGBA output,
-RGB_PLANAR2PACKED32(REG_BLUE, REG_GREEN, REG_RED,  REG_ALPHA) for BGRA output,
-RGB_PLANAR2PACKED32(REG_ALPHA,REG_BLUE,  REG_GREEN,REG_RED)   for ABGR output,
-
-etc.
-*/
-
-#define REG_BLUE  "0"
-#define REG_RED   "1"
-#define REG_GREEN "2"
-#define REG_ALPHA "3"
-
-#define RGB_PLANAR2PACKED32(red,green,blue,alpha)                       \
-    /* convert RGB plane to RGB packed format,                          \
-       mm0 ->  B, mm1 -> R, mm2 -> G, mm3 -> A,                         \
-       mm4 -> GB, mm5 -> AR pixel 4-7,                                  \
-       mm6 -> GB, mm7 -> AR pixel 0-3 */                                \
-    "movq      %%mm" blue ", %%mm6;"   /* B7 B6 B5 B4 B3 B2 B1 B0 */    \
-    "movq      %%mm" red  ", %%mm7;"   /* R7 R6 R5 R4 R3 R2 R1 R0 */    \
-\
-    "movq      %%mm" blue ", %%mm4;"   /* B7 B6 B5 B4 B3 B2 B1 B0 */    \
-    "movq      %%mm" red  ", %%mm5;"   /* R7 R6 R5 R4 R3 R2 R1 R0 */    \
-\
-    "punpcklbw %%mm" green ", %%mm6;"  /* G3 B3 G2 B2 G1 B1 G0 B0 */    \
-    "punpcklbw %%mm" alpha ", %%mm7;"  /* A3 R3 A2 R2 A1 R1 A0 R0 */    \
-\
-    "punpcklwd %%mm7, %%mm6;"          /* A1 R1 B1 G1 A0 R0 B0 G0 */    \
-    MOVNTQ "   %%mm6, (%1);"           /* Store ARGB1 ARGB0 */          \
-\
-    "movq      %%mm" blue ", %%mm6;"   /* B7 B6 B5 B4 B3 B2 B1 B0 */    \
-    "punpcklbw %%mm" green ", %%mm6;"  /* G3 B3 G2 B2 G1 B1 G0 B0 */    \
-\
-    "punpckhwd %%mm7, %%mm6;"          /* A3 R3 G3 B3 A2 R2 B3 G2 */    \
-    MOVNTQ "   %%mm6, 8 (%1);"         /* Store ARGB3 ARGB2 */          \
-\
-    "punpckhbw %%mm" green ", %%mm4;"  /* G7 B7 G6 B6 G5 B5 G4 B4 */    \
-    "punpckhbw %%mm" alpha ", %%mm5;"  /* A7 R7 A6 R6 A5 R5 A4 R4 */    \
-\
-    "punpcklwd %%mm5, %%mm4;"          /* A5 R5 B5 G5 A4 R4 B4 G4 */    \
-    MOVNTQ "   %%mm4, 16 (%1);"        /* Store ARGB5 ARGB4 */          \
-\
-    "movq      %%mm" blue ", %%mm4;"   /* B7 B6 B5 B4 B3 B2 B1 B0 */    \
-    "punpckhbw %%mm" green ", %%mm4;"  /* G7 B7 G6 B6 G5 B5 G4 B4 */    \
-\
-    "punpckhwd %%mm5, %%mm4;"   /* A7 R7 G7 B7 A6 R6 B6 G6 */           \
-    MOVNTQ "   %%mm4, 24 (%1);" /* Store ARGB7 ARGB6 */                 \
-\
-    "movd 4 (%2, %0), %%mm0;"   /* Load 4 Cb 00 00 00 00 u3 u2 u1 u0 */ \
-    "movd 4 (%3, %0), %%mm1;"   /* Load 4 Cr 00 00 00 00 v3 v2 v1 v0 */ \
-\
-    "pxor         %%mm4, %%mm4;" /* zero mm4 */                         \
-    "movq 8 (%5, %0, 2), %%mm6;" /* Load 8 Y Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y0 */ \
-
-static inline int RENAME(yuv420_rgb32)(SwsContext *c, const uint8_t* src[], int srcStride[], int srcSliceY,
-                                       int srcSliceH, uint8_t* dst[], int dstStride[])
+#define SET_EMPTY_ALPHA                                                      \
+    "pcmpeqd   %%mm"REG_ALPHA", %%mm"REG_ALPHA"\n\t" /* set alpha to 0xFF */ \
+
+#define LOAD_ALPHA                                   \
+    "movq      (%6, %0, 2),     %%mm"REG_ALPHA"\n\t" \
+
+#define RGB_PACK32(red, green, blue, alpha)  \
+    "movq      %%mm"blue",  %%mm5\n\t"       \
+    "movq      %%mm"red",   %%mm6\n\t"       \
+    "punpckhbw %%mm"green", %%mm5\n\t"       \
+    "punpcklbw %%mm"green", %%mm"blue"\n\t"  \
+    "punpckhbw %%mm"alpha", %%mm6\n\t"       \
+    "punpcklbw %%mm"alpha", %%mm"red"\n\t"   \
+    "movq      %%mm"blue",  %%mm"green"\n\t" \
+    "movq      %%mm5,       %%mm"alpha"\n\t" \
+    "punpcklwd %%mm"red",   %%mm"blue"\n\t"  \
+    "punpckhwd %%mm"red",   %%mm"green"\n\t" \
+    "punpcklwd %%mm6,       %%mm5\n\t"       \
+    "punpckhwd %%mm6,       %%mm"alpha"\n\t" \
+    MOVNTQ "   %%mm"blue",   0(%1)\n\t"      \
+    MOVNTQ "   %%mm"green",  8(%1)\n\t"      \
+    MOVNTQ "   %%mm5,       16(%1)\n\t"      \
+    MOVNTQ "   %%mm"alpha", 24(%1)\n\t"      \
+
+static inline int RENAME(yuv420_rgb32)(SwsContext *c, const uint8_t *src[],
+                                       int srcStride[],
+                                       int srcSliceY, int srcSliceH,
+                                       uint8_t *dst[], int dstStride[])
 {
     int y, h_size;
 
-    YUV422_UNSHIFT
     YUV2RGB_LOOP(4)
 
-        YUV2RGB_INIT
+        YUV2RGB_INITIAL_LOAD
         YUV2RGB
-        "pcmpeqd   %%mm3, %%mm3;"   /* fill mm3 */
-        RGB_PLANAR2PACKED32(REG_RED,REG_GREEN,REG_BLUE,REG_ALPHA)
+        RGB_PACK_INTERLEAVE
+        SET_EMPTY_ALPHA
+        RGB_PACK32(REG_RED, REG_GREEN, REG_BLUE, REG_ALPHA)
 
     YUV2RGB_ENDLOOP(4)
     YUV2RGB_OPERANDS
+    YUV2RGB_ENDFUNC
 }
 
-static inline int RENAME(yuva420_rgb32)(SwsContext *c, const uint8_t* src[], int srcStride[], int srcSliceY,
-                                        int srcSliceH, uint8_t* dst[], int dstStride[])
+static inline int RENAME(yuva420_rgb32)(SwsContext *c, const uint8_t *src[],
+                                        int srcStride[],
+                                        int srcSliceY, int srcSliceH,
+                                        uint8_t *dst[], int dstStride[])
 {
 #if HAVE_7REGS
     int y, h_size;
 
     YUV2RGB_LOOP(4)
 
-        const uint8_t *pa = src[3] + y*srcStride[3];
-        YUV2RGB_INIT
+        const uint8_t *pa = src[3] + y * srcStride[3];
+        YUV2RGB_INITIAL_LOAD
         YUV2RGB
-        "movq     (%6, %0, 2), %%mm3;"            /* Load 8 A A7 A6 A5 A4 A3 A2 A1 A0 */
-        RGB_PLANAR2PACKED32(REG_RED,REG_GREEN,REG_BLUE,REG_ALPHA)
+        RGB_PACK_INTERLEAVE
+        LOAD_ALPHA
+        RGB_PACK32(REG_RED, REG_GREEN, REG_BLUE, REG_ALPHA)
 
     YUV2RGB_ENDLOOP(4)
     YUV2RGB_OPERANDS_ALPHA
+    YUV2RGB_ENDFUNC
+#else
+    return 0;
 #endif
 }
 
-static inline int RENAME(yuv420_bgr32)(SwsContext *c, const uint8_t* src[], int srcStride[], int srcSliceY,
-                                       int srcSliceH, uint8_t* dst[], int dstStride[])
+static inline int RENAME(yuv420_bgr32)(SwsContext *c, const uint8_t *src[],
+                                       int srcStride[],
+                                       int srcSliceY, int srcSliceH,
+                                       uint8_t *dst[], int dstStride[])
 {
     int y, h_size;
 
-    YUV422_UNSHIFT
     YUV2RGB_LOOP(4)
 
-        YUV2RGB_INIT
+        YUV2RGB_INITIAL_LOAD
         YUV2RGB
-        "pcmpeqd   %%mm3, %%mm3;"   /* fill mm3 */
-        RGB_PLANAR2PACKED32(REG_BLUE,REG_GREEN,REG_RED,REG_ALPHA)
+        RGB_PACK_INTERLEAVE
+        SET_EMPTY_ALPHA
+        RGB_PACK32(REG_BLUE, REG_GREEN, REG_RED, REG_ALPHA)
 
     YUV2RGB_ENDLOOP(4)
     YUV2RGB_OPERANDS
+    YUV2RGB_ENDFUNC
 }
 
-static inline int RENAME(yuva420_bgr32)(SwsContext *c, const uint8_t* src[], int srcStride[], int srcSliceY,
-                                        int srcSliceH, uint8_t* dst[], int dstStride[])
+static inline int RENAME(yuva420_bgr32)(SwsContext *c, const uint8_t *src[],
+                                        int srcStride[],
+                                        int srcSliceY, int srcSliceH,
+                                        uint8_t *dst[], int dstStride[])
 {
 #if HAVE_7REGS
     int y, h_size;
 
     YUV2RGB_LOOP(4)
 
-        const uint8_t *pa = src[3] + y*srcStride[3];
-        YUV2RGB_INIT
+        const uint8_t *pa = src[3] + y * srcStride[3];
+        YUV2RGB_INITIAL_LOAD
         YUV2RGB
-        "movq     (%6, %0, 2), %%mm3;"            /* Load 8 A A7 A6 A5 A4 A3 A2 A1 A0 */
-        RGB_PLANAR2PACKED32(REG_BLUE,REG_GREEN,REG_RED,REG_ALPHA)
+        RGB_PACK_INTERLEAVE
+        LOAD_ALPHA
+        RGB_PACK32(REG_BLUE, REG_GREEN, REG_RED, REG_ALPHA)
 
     YUV2RGB_ENDLOOP(4)
     YUV2RGB_OPERANDS_ALPHA
+    YUV2RGB_ENDFUNC
+#else
+    return 0;
 #endif
 }
diff --git a/libswscale/x86/yuv2rgb_template2.c b/libswscale/x86/yuv2rgb_template2.c
deleted file mode 100644
index f391cde..0000000
--- a/libswscale/x86/yuv2rgb_template2.c
+++ /dev/null
@@ -1,459 +0,0 @@
-/*
- * software YUV to RGB converter
- *
- * Copyright (C) 2001-2007 Michael Niedermayer
- *           (c) 2010 Konstantin Shishkov
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-#undef MOVNTQ
-#undef EMMS
-#undef SFENCE
-
-#if HAVE_AMD3DNOW
-/* On K6 femms is faster than emms. On K7 femms is directly mapped to emms. */
-#define EMMS   "femms"
-#else
-#define EMMS   "emms"
-#endif
-
-#if HAVE_MMX2
-#define MOVNTQ "movntq"
-#define SFENCE "sfence"
-#else
-#define MOVNTQ "movq"
-#define SFENCE " # nop"
-#endif
-
-#define REG_BLUE  "0"
-#define REG_RED   "1"
-#define REG_GREEN "2"
-#define REG_ALPHA "3"
-
-#define YUV2RGB_LOOP(depth)                                          \
-    h_size = (c->dstW + 7) & ~7;                                     \
-    if (h_size * depth > FFABS(dstStride[0]))                        \
-        h_size -= 8;                                                 \
-                                                                     \
-    if (c->srcFormat == PIX_FMT_YUV422P) {                           \
-        srcStride[1] *= 2;                                           \
-        srcStride[2] *= 2;                                           \
-    }                                                                \
-                                                                     \
-    __asm__ volatile ("pxor %mm4, %mm4\n\t");                        \
-    for (y = 0; y < srcSliceH; y++) {                                \
-        uint8_t *image    = dst[0] + (y + srcSliceY) * dstStride[0]; \
-        const uint8_t *py = src[0] +               y * srcStride[0]; \
-        const uint8_t *pu = src[1] +        (y >> 1) * srcStride[1]; \
-        const uint8_t *pv = src[2] +        (y >> 1) * srcStride[2]; \
-        x86_reg index = -h_size / 2;                                 \
-
-#define YUV2RGB_INITIAL_LOAD          \
-    __asm__ volatile (                \
-        "movq (%5, %0, 2), %%mm6\n\t" \
-        "movd    (%2, %0), %%mm0\n\t" \
-        "movd    (%3, %0), %%mm1\n\t" \
-        "1: \n\t"                     \
-
-/* YUV2RGB core
- * Conversion is performed in usual way:
- * R = Y' * Ycoef + Vred * V'
- * G = Y' * Ycoef + Vgreen * V' + Ugreen * U'
- * B = Y' * Ycoef               + Ublue * U'
- *
- * where X' = X * 8 - Xoffset (multiplication is performed to increase
- * precision a bit).
- * Since it operates in YUV420 colorspace, Y component is additionally
- * split into Y1 and Y2 for even and odd pixels.
- *
- * Input:
- * mm0 - U (4 elems), mm1 - V (4 elems), mm6 - Y (8 elems), mm4 - zero register
- * Output:
- * mm1 - R, mm2 - G, mm0 - B
- */
-#define YUV2RGB                                  \
-    /* convert Y, U, V into Y1', Y2', U', V' */  \
-    "movq      %%mm6, %%mm7\n\t"                 \
-    "punpcklbw %%mm4, %%mm0\n\t"                 \
-    "punpcklbw %%mm4, %%mm1\n\t"                 \
-    "pand     "MANGLE(mmx_00ffw)", %%mm6\n\t"    \
-    "psrlw     $8,    %%mm7\n\t"                 \
-    "psllw     $3,    %%mm0\n\t"                 \
-    "psllw     $3,    %%mm1\n\t"                 \
-    "psllw     $3,    %%mm6\n\t"                 \
-    "psllw     $3,    %%mm7\n\t"                 \
-    "psubsw   "U_OFFSET"(%4), %%mm0\n\t"         \
-    "psubsw   "V_OFFSET"(%4), %%mm1\n\t"         \
-    "psubw    "Y_OFFSET"(%4), %%mm6\n\t"         \
-    "psubw    "Y_OFFSET"(%4), %%mm7\n\t"         \
-\
-     /* multiply by coefficients */              \
-    "movq      %%mm0, %%mm2\n\t"                 \
-    "movq      %%mm1, %%mm3\n\t"                 \
-    "pmulhw   "UG_COEFF"(%4), %%mm2\n\t"         \
-    "pmulhw   "VG_COEFF"(%4), %%mm3\n\t"         \
-    "pmulhw   "Y_COEFF" (%4), %%mm6\n\t"         \
-    "pmulhw   "Y_COEFF" (%4), %%mm7\n\t"         \
-    "pmulhw   "UB_COEFF"(%4), %%mm0\n\t"         \
-    "pmulhw   "VR_COEFF"(%4), %%mm1\n\t"         \
-    "paddsw    %%mm3, %%mm2\n\t"                 \
-    /* now: mm0 = UB, mm1 = VR, mm2 = CG */      \
-    /*      mm6 = Y1, mm7 = Y2 */                \
-\
-    /* produce RGB */                            \
-    "movq      %%mm7, %%mm3\n\t"                 \
-    "movq      %%mm7, %%mm5\n\t"                 \
-    "paddsw    %%mm0, %%mm3\n\t"                 \
-    "paddsw    %%mm1, %%mm5\n\t"                 \
-    "paddsw    %%mm2, %%mm7\n\t"                 \
-    "paddsw    %%mm6, %%mm0\n\t"                 \
-    "paddsw    %%mm6, %%mm1\n\t"                 \
-    "paddsw    %%mm6, %%mm2\n\t"                 \
-\
-    /* pack and interleave even/odd pixels */    \
-    "packuswb  %%mm0, %%mm0\n\t"                 \
-    "packuswb  %%mm1, %%mm1\n\t"                 \
-    "packuswb  %%mm2, %%mm2\n\t"                 \
-    "packuswb  %%mm3, %%mm3\n\t"                 \
-    "packuswb  %%mm5, %%mm5\n\t"                 \
-    "packuswb  %%mm7, %%mm7\n\t"                 \
-    "punpcklbw %%mm3, %%mm0\n\t"                 \
-    "punpcklbw %%mm5, %%mm1\n\t"                 \
-    "punpcklbw %%mm7, %%mm2\n\t"                 \
-
-#define YUV2RGB_ENDLOOP(depth)                   \
-    "movq 8 (%5, %0, 2), %%mm6\n\t"              \
-    "movd 4 (%3, %0),    %%mm1\n\t"              \
-    "movd 4 (%2, %0),    %%mm0\n\t"              \
-    "add $"AV_STRINGIFY(depth * 8)", %1\n\t"     \
-    "add  $4, %0\n\t"                            \
-    "js   1b\n\t"                                \
-
-#define YUV2RGB_OPERANDS                                          \
-        : "+r" (index), "+r" (image)                              \
-        : "r" (pu - index), "r" (pv - index), "r"(&c->redDither), \
-          "r" (py - 2*index)                                      \
-        );                                                        \
-    }                                                             \
-
-#define YUV2RGB_OPERANDS_ALPHA                                    \
-        : "+r" (index), "+r" (image)                              \
-        : "r" (pu - index), "r" (pv - index), "r"(&c->redDither), \
-          "r" (py - 2*index), "r" (pa - 2*index)                  \
-        );                                                        \
-    }                                                             \
-
-#define YUV2RGB_ENDFUNC                          \
-    __asm__ volatile (SFENCE"\n\t"EMMS);         \
-    return srcSliceH;                            \
-
-
-#define RGB_PACK16(gmask, gshift, rshift)        \
-    "pand      "MANGLE(mmx_redmask)", %%mm0\n\t" \
-    "pand      "MANGLE(mmx_redmask)", %%mm1\n\t" \
-    "psrlw     $3,        %%mm0\n\t"             \
-    "pand      "MANGLE(gmask)",       %%mm2\n\t" \
-    "movq      %%mm0,     %%mm5\n\t"             \
-    "movq      %%mm1,     %%mm6\n\t"             \
-    "movq      %%mm2,     %%mm7\n\t"             \
-    "punpcklbw %%mm4,     %%mm0\n\t"             \
-    "punpcklbw %%mm4,     %%mm1\n\t"             \
-    "punpcklbw %%mm4,     %%mm2\n\t"             \
-    "punpckhbw %%mm4,     %%mm5\n\t"             \
-    "punpckhbw %%mm4,     %%mm6\n\t"             \
-    "punpckhbw %%mm4,     %%mm7\n\t"             \
-    "psllw     $"rshift", %%mm1\n\t"             \
-    "psllw     $"rshift", %%mm6\n\t"             \
-    "psllw     $"gshift", %%mm2\n\t"             \
-    "psllw     $"gshift", %%mm7\n\t"             \
-    "por       %%mm1,     %%mm0\n\t"             \
-    "por       %%mm6,     %%mm5\n\t"             \
-    "por       %%mm2,     %%mm0\n\t"             \
-    "por       %%mm7,     %%mm5\n\t"             \
-    MOVNTQ "   %%mm0,      (%1)\n\t"             \
-    MOVNTQ "   %%mm5,     8(%1)\n\t"             \
-
-#define DITHER_RGB                               \
-    "paddusb "BLUE_DITHER"(%4),  %%mm0\n\t"      \
-    "paddusb "GREEN_DITHER"(%4), %%mm2\n\t"      \
-    "paddusb "RED_DITHER"(%4),   %%mm1\n\t"      \
-
-static inline int RENAME(yuv420_rgb15)(SwsContext *c, const uint8_t *src[],
-                                       int srcStride[],
-                                       int srcSliceY, int srcSliceH,
-                                       uint8_t *dst[], int dstStride[])
-{
-    int y, h_size;
-
-    YUV2RGB_LOOP(2)
-
-#ifdef DITHER1XBPP
-        c->blueDither  = ff_dither8[y       & 1];
-        c->greenDither = ff_dither8[y       & 1];
-        c->redDither   = ff_dither8[(y + 1) & 1];
-#endif
-
-        YUV2RGB_INITIAL_LOAD
-        YUV2RGB
-#ifdef DITHER1XBPP
-        DITHER_RGB
-#endif
-        RGB_PACK16(mmx_redmask, "2", "7")
-
-    YUV2RGB_ENDLOOP(2)
-    YUV2RGB_OPERANDS
-    YUV2RGB_ENDFUNC
-}
-
-static inline int RENAME(yuv420_rgb16)(SwsContext *c, const uint8_t *src[],
-                                       int srcStride[],
-                                       int srcSliceY, int srcSliceH,
-                                       uint8_t *dst[], int dstStride[])
-{
-    int y, h_size;
-
-    YUV2RGB_LOOP(2)
-
-#ifdef DITHER1XBPP
-        c->blueDither  = ff_dither8[y       & 1];
-        c->greenDither = ff_dither4[y       & 1];
-        c->redDither   = ff_dither8[(y + 1) & 1];
-#endif
-
-        YUV2RGB_INITIAL_LOAD
-        YUV2RGB
-#ifdef DITHER1XBPP
-        DITHER_RGB
-#endif
-        RGB_PACK16(mmx_grnmask, "3", "8")
-
-    YUV2RGB_ENDLOOP(2)
-    YUV2RGB_OPERANDS
-    YUV2RGB_ENDFUNC
-}
-
-
-#define RGB_PACK24(red, blue)              \
-    /* generate first packed RGB octet */  \
-    "movq      %%mm2,      %%mm5\n\t"      \
-    "movq      %%mm"blue", %%mm6\n\t"      \
-    "movq      %%mm"red",  %%mm7\n\t"      \
-    "punpcklbw %%mm5,      %%mm6\n\t"      \
-    "punpcklbw %%mm4,      %%mm7\n\t"      \
-    "movq      %%mm6,      %%mm3\n\t"      \
-    "punpcklwd %%mm7,      %%mm6\n\t"      \
-    "psrlq     $32,        %%mm3\n\t"      \
-    "movq      %%mm6,      %%mm5\n\t"      \
-    "psllq     $40,        %%mm6\n\t"      \
-    "psllq     $48,        %%mm3\n\t"      \
-    "psrlq     $32,        %%mm5\n\t"      \
-    "psrlq     $40,        %%mm6\n\t"      \
-    "psllq     $24,        %%mm5\n\t"      \
-    "por       %%mm3,      %%mm6\n\t"      \
-    "por       %%mm5,      %%mm6\n\t"      \
-    MOVNTQ "   %%mm6,      (%1)\n\t"       \
-\
-    /* generate second packed RGB octet */ \
-    "movq      %%mm"red",  %%mm7\n\t"      \
-    "movq      %%mm2,      %%mm5\n\t"      \
-    "movq      %%mm"blue", %%mm6\n\t"      \
-    "punpcklbw %%mm4,      %%mm7\n\t"      \
-    "punpcklbw %%mm5,      %%mm6\n\t"      \
-    "movq      %%mm7,      %%mm3\n\t"      \
-    "punpckhwd %%mm7,      %%mm6\n\t"      \
-    "psllq     $16,        %%mm3\n\t"      \
-    "psrlq     $32,        %%mm6\n\t"      \
-    "psrlq     $48,        %%mm3\n\t"      \
-    "psllq     $8,         %%mm6\n\t"      \
-    "movq      %%mm"red",  %%mm7\n\t"      \
-    "por       %%mm6,      %%mm3\n\t"      \
-    "movq      %%mm"blue", %%mm6\n\t"      \
-    "movq      %%mm2,      %%mm5\n\t"      \
-    "punpckhbw %%mm4,      %%mm7\n\t"      \
-    "punpckhbw %%mm5,      %%mm6\n\t"      \
-    "movq      %%mm6,      %%mm5\n\t"      \
-    "punpcklwd %%mm7,      %%mm6\n\t"      \
-    "psrlq     $16,        %%mm5\n\t"      \
-    "psllq     $56,        %%mm5\n\t"      \
-    "por       %%mm5,      %%mm3\n\t"      \
-    "psllq     $32,        %%mm6\n\t"      \
-    "por       %%mm6,      %%mm3\n\t"      \
-    MOVNTQ "   %%mm3,      8(%1)\n\t"      \
-\
-    /* generate third packed RGB octet */  \
-    "movq      %%mm"red",  %%mm7\n\t"      \
-    "movq      %%mm2,      %%mm5\n\t"      \
-    "movq      %%mm2,      %%mm3\n\t"      \
-    "movq      %%mm"blue", %%mm6\n\t"      \
-    "punpckhbw %%mm"red",  %%mm3\n\t"      \
-    "punpckhbw %%mm4,      %%mm7\n\t"      \
-    "psllq     $32,        %%mm3\n\t"      \
-    "punpckhbw %%mm5,      %%mm6\n\t"      \
-    "psrlq     $48,        %%mm3\n\t"      \
-    "punpckhwd %%mm7,      %%mm6\n\t"      \
-    "movq      %%mm6,      %%mm7\n\t"      \
-    "psrlq     $32,        %%mm6\n\t"      \
-    "psllq     $32,        %%mm7\n\t"      \
-    "psllq     $40,        %%mm6\n\t"      \
-    "psrlq     $16,        %%mm7\n\t"      \
-    "por       %%mm6,      %%mm3\n\t"      \
-    "por       %%mm7,      %%mm3\n\t"      \
-    MOVNTQ "   %%mm3,      16(%1)\n\t"     \
-
-static inline int RENAME(yuv420_rgb24)(SwsContext *c, const uint8_t *src[],
-                                       int srcStride[],
-                                       int srcSliceY, int srcSliceH,
-                                       uint8_t *dst[], int dstStride[])
-{
-    int y, h_size;
-
-    YUV2RGB_LOOP(3)
-
-        YUV2RGB_INITIAL_LOAD
-        YUV2RGB
-        RGB_PACK24(REG_BLUE, REG_RED)
-
-    YUV2RGB_ENDLOOP(3)
-    YUV2RGB_OPERANDS
-    YUV2RGB_ENDFUNC
-}
-
-static inline int RENAME(yuv420_bgr24)(SwsContext *c, const uint8_t *src[],
-                                       int srcStride[],
-                                       int srcSliceY, int srcSliceH,
-                                       uint8_t *dst[], int dstStride[])
-{
-    int y, h_size;
-
-    YUV2RGB_LOOP(3)
-
-        YUV2RGB_INITIAL_LOAD
-        YUV2RGB
-        RGB_PACK24(REG_RED, REG_BLUE)
-
-    YUV2RGB_ENDLOOP(3)
-    YUV2RGB_OPERANDS
-    YUV2RGB_ENDFUNC
-}
-
-
-#define SET_EMPTY_ALPHA                                                      \
-    "pcmpeqd   %%mm"REG_ALPHA", %%mm"REG_ALPHA"\n\t" /* set alpha to 0xFF */ \
-
-#define LOAD_ALPHA                                   \
-    "movq      (%6, %0, 2),     %%mm"REG_ALPHA"\n\t" \
-
-#define RGB_PACK32(red, green, blue, alpha)  \
-    "movq      %%mm"blue",  %%mm5\n\t"       \
-    "movq      %%mm"red",   %%mm6\n\t"       \
-    "punpckhbw %%mm"green", %%mm5\n\t"       \
-    "punpcklbw %%mm"green", %%mm"blue"\n\t"  \
-    "punpckhbw %%mm"alpha", %%mm6\n\t"       \
-    "punpcklbw %%mm"alpha", %%mm"red"\n\t"   \
-    "movq      %%mm"blue",  %%mm"green"\n\t" \
-    "movq      %%mm5,       %%mm"alpha"\n\t" \
-    "punpcklwd %%mm"red",   %%mm"blue"\n\t"  \
-    "punpckhwd %%mm"red",   %%mm"green"\n\t" \
-    "punpcklwd %%mm6,       %%mm5\n\t"       \
-    "punpckhwd %%mm6,       %%mm"alpha"\n\t" \
-    MOVNTQ "   %%mm"blue",   0(%1)\n\t"      \
-    MOVNTQ "   %%mm"green",  8(%1)\n\t"      \
-    MOVNTQ "   %%mm5,       16(%1)\n\t"      \
-    MOVNTQ "   %%mm"alpha", 24(%1)\n\t"      \
-
-static inline int RENAME(yuv420_rgb32)(SwsContext *c, const uint8_t *src[],
-                                       int srcStride[],
-                                       int srcSliceY, int srcSliceH,
-                                       uint8_t *dst[], int dstStride[])
-{
-    int y, h_size;
-
-    YUV2RGB_LOOP(4)
-
-        YUV2RGB_INITIAL_LOAD
-        YUV2RGB
-        SET_EMPTY_ALPHA
-        RGB_PACK32(REG_RED, REG_GREEN, REG_BLUE, REG_ALPHA)
-
-    YUV2RGB_ENDLOOP(4)
-    YUV2RGB_OPERANDS
-    YUV2RGB_ENDFUNC
-}
-
-static inline int RENAME(yuva420_rgb32)(SwsContext *c, const uint8_t *src[],
-                                        int srcStride[],
-                                        int srcSliceY, int srcSliceH,
-                                        uint8_t *dst[], int dstStride[])
-{
-#if HAVE_7REGS
-    int y, h_size;
-
-    YUV2RGB_LOOP(4)
-
-        const uint8_t *pa = src[3] + y * srcStride[3];
-        YUV2RGB_INITIAL_LOAD
-        YUV2RGB
-        LOAD_ALPHA
-        RGB_PACK32(REG_RED, REG_GREEN, REG_BLUE, REG_ALPHA)
-
-    YUV2RGB_ENDLOOP(4)
-    YUV2RGB_OPERANDS_ALPHA
-    YUV2RGB_ENDFUNC
-#endif
-}
-
-static inline int RENAME(yuv420_bgr32)(SwsContext *c, const uint8_t *src[],
-                                       int srcStride[],
-                                       int srcSliceY, int srcSliceH,
-                                       uint8_t *dst[], int dstStride[])
-{
-    int y, h_size;
-
-    YUV2RGB_LOOP(4)
-
-        YUV2RGB_INITIAL_LOAD
-        YUV2RGB
-        SET_EMPTY_ALPHA
-        RGB_PACK32(REG_BLUE, REG_GREEN, REG_RED, REG_ALPHA)
-
-    YUV2RGB_ENDLOOP(4)
-    YUV2RGB_OPERANDS
-    YUV2RGB_ENDFUNC
-}
-
-static inline int RENAME(yuva420_bgr32)(SwsContext *c, const uint8_t *src[],
-                                        int srcStride[],
-                                        int srcSliceY, int srcSliceH,
-                                        uint8_t *dst[], int dstStride[])
-{
-#if HAVE_7REGS
-    int y, h_size;
-
-    YUV2RGB_LOOP(4)
-
-        const uint8_t *pa = src[3] + y * srcStride[3];
-        YUV2RGB_INITIAL_LOAD
-        YUV2RGB
-        LOAD_ALPHA
-        RGB_PACK32(REG_BLUE, REG_GREEN, REG_RED, REG_ALPHA)
-
-    YUV2RGB_ENDLOOP(4)
-    YUV2RGB_OPERANDS_ALPHA
-    YUV2RGB_ENDFUNC
-#endif
-}
diff --git a/libswscale/yuv2rgb.c b/libswscale/yuv2rgb.c
index f47b15d..8ea41af 100644
--- a/libswscale/yuv2rgb.c
+++ b/libswscale/yuv2rgb.c
@@ -6,20 +6,20 @@
  * 1,4,8bpp support and context / deglobalize stuff
  * by Michael Niedermayer (michaelni at gmx.at)
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -595,10 +595,11 @@ SwsFunc ff_yuv2rgb_get_func_ptr(SwsContext *c)
     return NULL;
 }
 
-static void fill_table(uint8_t* table[256], const int elemsize, const int inc, uint8_t *y_table)
+static void fill_table(uint8_t* table[256], const int elemsize, const int inc, void *y_tab)
 {
     int i;
     int64_t cb = 0;
+    uint8_t *y_table = y_tab;
 
     y_table -= elemsize * (inc >> 9);
 
@@ -620,6 +621,14 @@ static void fill_gv_table(int table[256], const int elemsize, const int inc)
     }
 }
 
+static uint16_t roundToInt16(int64_t f)
+{
+    int r= (f + (1<<15))>>16;
+         if (r<-0x7FFF) return 0x8000;
+    else if (r> 0x7FFF) return 0x7FFF;
+    else                return r;
+}
+
 av_cold int ff_yuv2rgb_c_init_tables(SwsContext *c, const int inv_table[4], int fullRange,
                                      int brightness, int contrast, int saturation)
 {
@@ -675,6 +684,22 @@ av_cold int ff_yuv2rgb_c_init_tables(SwsContext *c, const int inv_table[4], int
     cgv = (cgv*contrast * saturation) >> 32;
     oy -= 256*brightness;
 
+    c->uOffset=   0x0400040004000400LL;
+    c->vOffset=   0x0400040004000400LL;
+    c->yCoeff=    roundToInt16(cy *8192) * 0x0001000100010001ULL;
+    c->vrCoeff=   roundToInt16(crv*8192) * 0x0001000100010001ULL;
+    c->ubCoeff=   roundToInt16(cbu*8192) * 0x0001000100010001ULL;
+    c->vgCoeff=   roundToInt16(cgv*8192) * 0x0001000100010001ULL;
+    c->ugCoeff=   roundToInt16(cgu*8192) * 0x0001000100010001ULL;
+    c->yOffset=   roundToInt16(oy *   8) * 0x0001000100010001ULL;
+
+    c->yuv2rgb_y_coeff  = (int16_t)roundToInt16(cy <<13);
+    c->yuv2rgb_y_offset = (int16_t)roundToInt16(oy << 9);
+    c->yuv2rgb_v2r_coeff= (int16_t)roundToInt16(crv<<13);
+    c->yuv2rgb_v2g_coeff= (int16_t)roundToInt16(cgv<<13);
+    c->yuv2rgb_u2g_coeff= (int16_t)roundToInt16(cgu<<13);
+    c->yuv2rgb_u2b_coeff= (int16_t)roundToInt16(cbu<<13);
+
     //scale coefficients by cy
     crv = ((crv << 16) + 0x8000) / cy;
     cbu = ((cbu << 16) + 0x8000) / cy;
@@ -750,7 +775,7 @@ av_cold int ff_yuv2rgb_c_init_tables(SwsContext *c, const int inv_table[4], int
         }
         if (isNotNe)
             for (i = 0; i < 1024*3; i++)
-                y_table16[i] = bswap_16(y_table16[i]);
+                y_table16[i] = av_bswap16(y_table16[i]);
         fill_table(c->table_rV, 2, crv, y_table16 + yoffs);
         fill_table(c->table_gU, 2, cgu, y_table16 + yoffs + 1024);
         fill_table(c->table_bU, 2, cbu, y_table16 + yoffs + 2048);
@@ -773,7 +798,7 @@ av_cold int ff_yuv2rgb_c_init_tables(SwsContext *c, const int inv_table[4], int
         }
         if(isNotNe)
             for (i = 0; i < 1024*3; i++)
-                y_table16[i] = bswap_16(y_table16[i]);
+                y_table16[i] = av_bswap16(y_table16[i]);
         fill_table(c->table_rV, 2, crv, y_table16 + yoffs);
         fill_table(c->table_gU, 2, cgu, y_table16 + yoffs + 1024);
         fill_table(c->table_bU, 2, cbu, y_table16 + yoffs + 2048);
diff --git a/subdir.mak b/subdir.mak
index 36a40d3..7fdeddc 100644
--- a/subdir.mak
+++ b/subdir.mak
@@ -10,10 +10,10 @@ THIS_LIB   := $(SUBDIR)$($(CONFIG_SHARED:yes=S)LIBNAME)
 all-$(CONFIG_STATIC): $(SUBDIR)$(LIBNAME)
 all-$(CONFIG_SHARED): $(SUBDIR)$(SLIBNAME)
 
-$(SUBDIR)%-test.o: $(SUBDIR)%.c
+$(SUBDIR)%-test.o: $(SUBDIR)%-test.c
 	$(CC) $(CPPFLAGS) $(CFLAGS) -DTEST -c $(CC_O) $^
 
-$(SUBDIR)%-test.o: $(SUBDIR)%-test.c
+$(SUBDIR)%-test.o: $(SUBDIR)%.c
 	$(CC) $(CPPFLAGS) $(CFLAGS) -DTEST -c $(CC_O) $^
 
 $(SUBDIR)x86/%.o: $(SUBDIR)x86/%.asm
@@ -60,7 +60,6 @@ distclean:: clean
 install-lib$(NAME)-shared: $(SUBDIR)$(SLIBNAME)
 	$(Q)mkdir -p "$(SHLIBDIR)"
 	$$(INSTALL) -m 755 $$< "$(SHLIBDIR)/$(SLIBNAME_WITH_VERSION)"
-	$$(STRIP) "$(SHLIBDIR)/$(SLIBNAME_WITH_VERSION)"
 	$(Q)cd "$(SHLIBDIR)" && \
 		$(LN_S) $(SLIBNAME_WITH_VERSION) $(SLIBNAME_WITH_MAJOR)
 	$(Q)cd "$(SHLIBDIR)" && \
diff --git a/tests/audiogen.c b/tests/audiogen.c
index 38ca5dd..ddd1e18 100644
--- a/tests/audiogen.c
+++ b/tests/audiogen.c
@@ -4,28 +4,27 @@
  *
  * Copyright (c) 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include <stdlib.h>
 #include <stdio.h>
 
-#define NB_CHANNELS 2
-#define FE 44100
+#define MAX_CHANNELS 8
 
 static unsigned int myrnd(unsigned int *seed_ptr, int n)
 {
@@ -104,15 +103,34 @@ int main(int argc, char **argv)
 {
     int i, a, v, j, f, amp, ampa;
     unsigned int seed = 1;
-    int tabf1[NB_CHANNELS], tabf2[NB_CHANNELS];
-    int taba[NB_CHANNELS];
-
-    if (argc != 2) {
-        printf("usage: %s file\n"
-               "generate a test raw 16 bit stereo audio stream\n", argv[0]);
+    int tabf1[MAX_CHANNELS], tabf2[MAX_CHANNELS];
+    int taba[MAX_CHANNELS];
+    int sample_rate = 44100;
+    int nb_channels = 2;
+
+    if (argc < 2 || argc > 4) {
+        printf("usage: %s file [<sample rate> [<channels>]]\n"
+               "generate a test raw 16 bit audio stream\n"
+               "default: 44100 Hz stereo\n", argv[0]);
         exit(1);
     }
 
+    if (argc > 2) {
+        sample_rate = atoi(argv[2]);
+        if (sample_rate <= 0) {
+            fprintf(stderr, "invalid sample rate: %d\n", sample_rate);
+            return 1;
+        }
+    }
+
+    if (argc > 3) {
+        nb_channels = atoi(argv[3]);
+        if (nb_channels < 1 || nb_channels > MAX_CHANNELS) {
+            fprintf(stderr, "invalid number of channels: %d\n", nb_channels);
+            return 1;
+        }
+    }
+
     outfile = fopen(argv[1], "wb");
     if (!outfile) {
         perror(argv[1]);
@@ -121,64 +139,64 @@ int main(int argc, char **argv)
 
     /* 1 second of single freq sinus at 1000 Hz */
     a = 0;
-    for(i=0;i<1 * FE;i++) {
+    for(i=0;i<1 * sample_rate;i++) {
         v = (int_cos(a) * 10000) >> FRAC_BITS;
-        for(j=0;j<NB_CHANNELS;j++)
+        for(j=0;j<nb_channels;j++)
             put_sample(v);
-        a += (1000 * FRAC_ONE) / FE;
+        a += (1000 * FRAC_ONE) / sample_rate;
     }
 
     /* 1 second of varing frequency between 100 and 10000 Hz */
     a = 0;
-    for(i=0;i<1 * FE;i++) {
+    for(i=0;i<1 * sample_rate;i++) {
         v = (int_cos(a) * 10000) >> FRAC_BITS;
-        for(j=0;j<NB_CHANNELS;j++)
+        for(j=0;j<nb_channels;j++)
             put_sample(v);
-        f = 100 + (((10000 - 100) * i) / FE);
-        a += (f * FRAC_ONE) / FE;
+        f = 100 + (((10000 - 100) * i) / sample_rate);
+        a += (f * FRAC_ONE) / sample_rate;
     }
 
     /* 0.5 second of low amplitude white noise */
-    for(i=0;i<FE / 2;i++) {
+    for(i=0;i<sample_rate / 2;i++) {
         v = myrnd(&seed, 20000) - 10000;
-        for(j=0;j<NB_CHANNELS;j++)
+        for(j=0;j<nb_channels;j++)
             put_sample(v);
     }
 
     /* 0.5 second of high amplitude white noise */
-    for(i=0;i<FE / 2;i++) {
+    for(i=0;i<sample_rate / 2;i++) {
         v = myrnd(&seed, 65535) - 32768;
-        for(j=0;j<NB_CHANNELS;j++)
+        for(j=0;j<nb_channels;j++)
             put_sample(v);
     }
 
-    /* stereo : 2 unrelated ramps */
-    for(j=0;j<NB_CHANNELS;j++) {
+    /* 1 second of unrelated ramps for each channel */
+    for(j=0;j<nb_channels;j++) {
         taba[j] = 0;
         tabf1[j] = 100 + myrnd(&seed, 5000);
         tabf2[j] = 100 + myrnd(&seed, 5000);
     }
-    for(i=0;i<1 * FE;i++) {
-        for(j=0;j<NB_CHANNELS;j++) {
+    for(i=0;i<1 * sample_rate;i++) {
+        for(j=0;j<nb_channels;j++) {
             v = (int_cos(taba[j]) * 10000) >> FRAC_BITS;
             put_sample(v);
-            f = tabf1[j] + (((tabf2[j] - tabf1[j]) * i) / FE);
-            taba[j] += (f * FRAC_ONE) / FE;
+            f = tabf1[j] + (((tabf2[j] - tabf1[j]) * i) / sample_rate);
+            taba[j] += (f * FRAC_ONE) / sample_rate;
         }
     }
 
-    /* stereo 500 Hz with varying volume */
+    /* 2 seconds of 500 Hz with varying volume */
     a = 0;
     ampa = 0;
-    for(i=0;i<2 * FE;i++) {
-        for(j=0;j<NB_CHANNELS;j++) {
+    for(i=0;i<2 * sample_rate;i++) {
+        for(j=0;j<nb_channels;j++) {
             amp = ((FRAC_ONE + int_cos(ampa)) * 5000) >> FRAC_BITS;
             if (j & 1)
                 amp = 10000 - amp;
             v = (int_cos(a) * amp) >> FRAC_BITS;
             put_sample(v);
-            a += (500 * FRAC_ONE) / FE;
-            ampa += (2 * FRAC_ONE) / FE;
+            a += (500 * FRAC_ONE) / sample_rate;
+            ampa += (2 * FRAC_ONE) / sample_rate;
         }
     }
 
diff --git a/tests/base64.c b/tests/base64.c
new file mode 100644
index 0000000..aad7dfb
--- /dev/null
+++ b/tests/base64.c
@@ -0,0 +1,53 @@
+/*
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/*
+ * Based on libavutil/base64.c
+ */
+
+#include <stdio.h>
+
+int main(void)
+{
+    static const char b64[] =
+        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+    unsigned i_bits = 0;
+    int i_shift = 0;
+    int out_len = 0;
+    int in;
+
+#define putb64() do {                                   \
+        putchar(b64[(i_bits << 6 >> i_shift) & 0x3f]);  \
+        out_len++;                                      \
+        i_shift -= 6;                                   \
+    } while (0)
+
+    while ((in = getchar()) != EOF) {
+        i_bits = (i_bits << 8) + in;
+        i_shift += 8;
+        while (i_shift > 6)
+            putb64();
+    }
+    while (i_shift > 0)
+        putb64();
+    while (out_len++ & 3)
+        putchar('=');
+    putchar('\n');
+
+    return 0;
+}
diff --git a/tests/codec-regression.sh b/tests/codec-regression.sh
index ce958ce..b705bc1 100755
--- a/tests/codec-regression.sh
+++ b/tests/codec-regression.sh
@@ -219,17 +219,17 @@ fi
 
 if [ -n "$do_dnxhd_1080i" ] ; then
 # FIXME: interlaced raw DNxHD decoding is broken
-do_video_encoding dnxhd-1080i.mov "" "-vcodec dnxhd -flags +ildct -s hd1080 -b 120Mb -pix_fmt yuv422p -vframes 5 -an"
+do_video_encoding dnxhd-1080i.mov "" "-vcodec dnxhd -flags +ildct -s hd1080 -b 120M -pix_fmt yuv422p -vframes 5 -an"
 do_video_decoding "-r 25" "-s cif -pix_fmt yuv420p"
 fi
 
 if [ -n "$do_dnxhd_720p" ] ; then
-do_video_encoding dnxhd-720p.dnxhd "" "-s hd720 -b 90Mb -pix_fmt yuv422p -vframes 5 -an"
+do_video_encoding dnxhd-720p.dnxhd "" "-s hd720 -b 90M -pix_fmt yuv422p -vframes 5 -an"
 do_video_decoding "-r 25" "-s cif -pix_fmt yuv420p"
 fi
 
 if [ -n "$do_dnxhd_720p_rd" ] ; then
-do_video_encoding dnxhd-720p-rd.dnxhd "" "-threads 4 -mbd rd -s hd720 -b 90Mb -pix_fmt yuv422p -vframes 5 -an"
+do_video_encoding dnxhd-720p-rd.dnxhd "" "-threads 4 -mbd rd -s hd720 -b 90M -pix_fmt yuv422p -vframes 5 -an"
 do_video_decoding "-r 25" "-s cif -pix_fmt yuv420p"
 fi
 
@@ -248,14 +248,29 @@ do_video_encoding roqav.roq "" "-vframes 5"
 do_video_decoding "" "-pix_fmt yuv420p"
 fi
 
+if [ -n "$do_qtrle" ] ; then
+do_video_encoding qtrle.mov "" "-an -vcodec qtrle"
+do_video_decoding "" "-pix_fmt yuv420p"
+fi
+
+if [ -n "$do_rgb" ] ; then
+do_video_encoding rgb.avi "" "-an -vcodec rawvideo -pix_fmt bgr24"
+do_video_decoding "" "-pix_fmt yuv420p"
+fi
+
+if [ -n "$do_yuv" ] ; then
+do_video_encoding yuv.avi "" "-an -vcodec rawvideo -pix_fmt yuv420p"
+do_video_decoding "" "-pix_fmt yuv420p"
+fi
+
 if [ -n "$do_mp2" ] ; then
 do_audio_encoding mp2.mp2 "-ar 44100"
 do_audio_decoding
 $tiny_psnr $pcm_dst $pcm_ref 2 1924 >> $logfile
 fi
 
-if [ -n "$do_ac3" ] ; then
-do_audio_encoding ac3.rm "" -vn
+if [ -n "$do_ac3_fixed" ] ; then
+do_audio_encoding ac3.rm "" "-vn -acodec ac3_fixed"
 # binaries configured with --disable-sse decode ac3 differently
 #do_audio_decoding
 #$tiny_psnr $pcm_dst $pcm_ref 2 1024 >> $logfile
@@ -348,5 +363,3 @@ do_audio_enc_dec wav dbl pcm_f64le
 do_audio_enc_dec wav s16 pcm_zork
 do_audio_enc_dec 302 s16 pcm_s24daud "-ac 6 -ar 96000"
 fi
-
-rm -f "$bench" "$bench2"
diff --git a/tests/copycooker.sh b/tests/copycooker.sh
index 4b5811d..3118e3f 100755
--- a/tests/copycooker.sh
+++ b/tests/copycooker.sh
@@ -13,8 +13,8 @@ rm -f $logfile
 for i in $list ; do
     echo ---------------- >> $logfile
     echo $i >> $logfile
-    ./ffmpeg_g -flags +bitexact -i $i -acodec copy -vcodec copy -y first.nut
-    ./ffmpeg_g -flags +bitexact -i first.nut -acodec copy -vcodec copy -y second.nut
+    ./ffmpeg -flags +bitexact -i $i -acodec copy -vcodec copy -y first.nut
+    ./ffmpeg -flags +bitexact -i first.nut -acodec copy -vcodec copy -y second.nut
     cmp first.nut second.nut >> $logfile
     md5sum first.nut >> $logfile
 done
diff --git a/tests/fate-run.sh b/tests/fate-run.sh
index 899580f..3a6b46b 100755
--- a/tests/fate-run.sh
+++ b/tests/fate-run.sh
@@ -1,19 +1,140 @@
 #! /bin/sh
 
+export LC_ALL=C
+
 base=$(dirname $0)
 . "${base}/md5.sh"
 
+base64=tests/base64
+
 test="${1#fate-}"
-SAMPLES_PATH=$2
+samples=$2
 target_exec=$3
-BUILD_PATH=$4
+target_path=$4
 command=$5
+cmp=${6:-diff}
+ref=${7:-"${base}/ref/fate/${test}"}
+fuzz=$8
+threads=${9:-1}
 
-ref="${base}/ref/fate/${test}"
 outdir="tests/data/fate"
 outfile="${outdir}/${test}"
+errfile="${outdir}/${test}.err"
+cmpfile="${outdir}/${test}.diff"
+repfile="${outdir}/${test}.rep"
+
+do_tiny_psnr(){
+    psnr=$(tests/tiny_psnr "$1" "$2" 2 0 0)
+    val=$(expr "$psnr" : ".*$3: *\([0-9.]*\)")
+    size1=$(expr "$psnr" : '.*bytes: *\([0-9]*\)')
+    size2=$(expr "$psnr" : '.*bytes:[ 0-9]*/ *\([0-9]*\)')
+    res=$(echo "if ($val $4 $5) 1" | bc)
+    if [ "$res" != 1 ] || [ $size1 != $size2 ]; then
+        echo "$psnr"
+        return 1
+    fi
+}
+
+oneoff(){
+    do_tiny_psnr "$1" "$2" MAXDIFF '<=' ${fuzz:-1}
+}
+
+stddev(){
+    do_tiny_psnr "$1" "$2" stddev  '<=' ${fuzz:-1}
+}
+
+run(){
+    test "${V:-0}" -gt 0 && echo "$target_exec" $target_path/"$@" >&3
+    $target_exec $target_path/"$@"
+}
+
+ffmpeg(){
+    run ffmpeg -v 0 -threads $threads "$@"
+}
+
+framecrc(){
+    ffmpeg "$@" -f framecrc -
+}
+
+framemd5(){
+    ffmpeg "$@" -f framemd5 -
+}
+
+crc(){
+    ffmpeg "$@" -f crc -
+}
+
+md5(){
+    ffmpeg "$@" md5:
+}
+
+pcm(){
+    ffmpeg "$@" -vn -f s16le -
+}
+
+regtest(){
+    t="${test#$2-}"
+    ref=${base}/ref/$2/$t
+    cleanfiles="$cleanfiles $outfile $errfile"
+    outfile=tests/data/regression/$2/$t
+    errfile=tests/data/$t.$2.err
+    ${base}/${1}-regression.sh $t $2 $3 "$target_exec" "$target_path" "$threads"
+}
+
+codectest(){
+    regtest codec $1 tests/$1
+}
+
+lavftest(){
+    regtest lavf lavf tests/vsynth1
+}
+
+lavfitest(){
+    cleanfiles="tests/data/lavfi/${test#lavfi-}.nut"
+    regtest lavfi lavfi tests/vsynth1
+}
+
+seektest(){
+    t="${test#seek-}"
+    ref=${base}/ref/seek/$t
+    case $t in
+        image_*) file="tests/data/images/${t#image_}/%02d.${t#image_}" ;;
+        *)       file=$(echo $t | tr _ '?')
+                 for d in acodec vsynth2 lavf; do
+                     test -f tests/data/$d/$file && break
+                 done
+                 file=$(echo tests/data/$d/$file)
+                 ;;
+    esac
+    $target_exec $target_path/tests/seek_test $target_path/$file
+}
 
 mkdir -p "$outdir"
 
-eval $target_exec $command > "$outfile" 2>/dev/null
-diff -u -w "$ref" "$outfile"
+exec 3>&2
+$command > "$outfile" 2>$errfile
+err=$?
+
+if [ $err -gt 128 ]; then
+    sig=$(kill -l $err 2>/dev/null)
+    test "${sig}" = "${sig%[!A-Za-z]*}" || unset sig
+fi
+
+if test -e "$ref"; then
+    case $cmp in
+        diff)   diff -u -w "$ref" "$outfile"            >$cmpfile ;;
+        oneoff) oneoff     "$ref" "$outfile" "$fuzz"    >$cmpfile ;;
+        stddev) stddev     "$ref" "$outfile" "$fuzz"    >$cmpfile ;;
+    esac
+    cmperr=$?
+    test $err = 0 && err=$cmperr
+    test $err = 0 || cat $cmpfile
+else
+    echo "reference file '$ref' not found"
+    err=1
+fi
+
+echo "${test}:${sig:-$err}:$($base64 <$cmpfile):$($base64 <$errfile)" >$repfile
+
+test $err = 0 && rm -f $outfile $errfile $cmpfile $cleanfiles
+exit $err
diff --git a/tests/fate-update.sh b/tests/fate-update.sh
deleted file mode 100755
index 92eaaf5..0000000
--- a/tests/fate-update.sh
+++ /dev/null
@@ -1,36 +0,0 @@
-#! /bin/sh
-
-set -e
-
-base=$(dirname $0)
-ref="${base}/ref/fate"
-
-FATE_DB_URL="http://fate.multimedia.cx/fate-tests.sqlite.bz2"
-FATE_DB=$(mktemp fate-db.XXXXXX)
-SQL_TESTS='SELECT id,short_name,command FROM test_spec WHERE active=1 ORDER BY short_name'
-
-do_sql(){
-    sqlite3 -noheader -separator ' ' "$FATE_DB" "$@"
-}
-
-wget -q -O - "$FATE_DB_URL" | bunzip2 > "$FATE_DB"
-rm -rf "$ref"
-mkdir -p "$ref"
-exec 3>"$base/fate.mak"
-
-do_sql "$SQL_TESTS" | while read id name command; do
-    case "$name" in
-        00-full-regression|ffmpeg-help|binsize-*) continue ;;
-    esac
-    case "$command" in
-        {MD5}*) command="${command#\{MD5\}} | do_md5sum | cut -c-32" ;;
-        {*}*)   continue ;;
-    esac
-    command=$(echo "$command" | sed 's/\$/$$/g')
-    do_sql "SELECT expected_stdout FROM test_spec WHERE id=$id" | awk '/./{print}' > "$ref/$name"
-    printf "FATE_TESTS += fate-${name}\n" >&3
-    printf "fate-${name}: CMD = %s\n" "$command" >&3
-done
-
-exec 3<&-
-rm -f "$FATE_DB"
diff --git a/tests/fate.mak b/tests/fate.mak
index 933dec6..0e33311 100644
--- a/tests/fate.mak
+++ b/tests/fate.mak
@@ -1,694 +1,364 @@
-FATE_TESTS += fate-4xm
-fate-4xm: CMD =  $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/4xm/TimeGatep01s01n01a02_2.4xm -f s16le - | do_md5sum | cut -c-32
+FATE_TESTS += fate-4xm-1
+fate-4xm-1: CMD = framecrc -i $(SAMPLES)/4xm/version1.4xm -pix_fmt rgb24 -an
+FATE_TESTS += fate-4xm-2
+fate-4xm-2: CMD = framecrc -i $(SAMPLES)/4xm/version2.4xm -pix_fmt rgb24 -an
 FATE_TESTS += fate-8bps
-fate-8bps: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/8bps/full9iron-partial.mov -pix_fmt rgb24 -f framecrc -
+fate-8bps: CMD = framecrc  -i $(SAMPLES)/8bps/full9iron-partial.mov -pix_fmt rgb24
 FATE_TESTS += fate-aac-demux
-fate-aac-demux: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/aac/ct_faac-adts.aac -acodec copy -f crc -
+fate-aac-demux: CMD = crc  -i $(SAMPLES)/aac/ct_faac-adts.aac -acodec copy
 FATE_TESTS += fate-aasc
-fate-aasc: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/aasc/AASC-1.5MB.AVI -pix_fmt rgb24 -f framecrc -
+fate-aasc: CMD = framecrc  -i $(SAMPLES)/aasc/AASC-1.5MB.AVI -pix_fmt rgb24
 FATE_TESTS += fate-adpcm-ea-r2
-fate-adpcm-ea-r2: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/ea-mpc/THX_logo.mpc -vn -f crc -
+fate-adpcm-ea-r2: CMD = crc  -i $(SAMPLES)/ea-mpc/THX_logo.mpc -vn
 FATE_TESTS += fate-adpcm-ea-r3
-fate-adpcm-ea-r3: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/ea-vp6/THX_logo.vp6 -vn -f crc -
+fate-adpcm-ea-r3: CMD = crc  -i $(SAMPLES)/ea-vp6/THX_logo.vp6 -vn
 FATE_TESTS += fate-aea-demux
-fate-aea-demux: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/aea/chirp.aea -acodec copy -f crc -
+fate-aea-demux: CMD = crc  -i $(SAMPLES)/aea/chirp.aea -acodec copy
 FATE_TESTS += fate-alg-mm
-fate-alg-mm: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/alg-mm/ibmlogo.mm -an -pix_fmt rgb24 -f framecrc -
+fate-alg-mm: CMD = framecrc  -i $(SAMPLES)/alg-mm/ibmlogo.mm -an -pix_fmt rgb24
 FATE_TESTS += fate-amv
-fate-amv: CMD = $$BUILD_PATH/ffmpeg -idct simple -i $$SAMPLES_PATH/amv/MTV_high_res_320x240_sample_Penguin_Joke_MTV_from_WMV.amv -t 10 -f framecrc -
+fate-amv: CMD = framecrc  -idct simple -i $(SAMPLES)/amv/MTV_high_res_320x240_sample_Penguin_Joke_MTV_from_WMV.amv -t 10
 FATE_TESTS += fate-armovie-escape124
-fate-armovie-escape124: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/rpl/ESCAPE.RPL -pix_fmt rgb24 -f framecrc -
+fate-armovie-escape124: CMD = framecrc  -i $(SAMPLES)/rpl/ESCAPE.RPL -pix_fmt rgb24
 FATE_TESTS += fate-auravision
-fate-auravision: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/auravision/SOUVIDEO.AVI -an -f framecrc -
+fate-auravision: CMD = framecrc  -i $(SAMPLES)/auravision/SOUVIDEO.AVI -an
 FATE_TESTS += fate-auravision-v2
-fate-auravision-v2: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/auravision/salma-hayek-in-ugly-betty-partial-avi -an -f framecrc -
+fate-auravision-v2: CMD = framecrc  -i $(SAMPLES)/auravision/salma-hayek-in-ugly-betty-partial-avi -an
 FATE_TESTS += fate-bethsoft-vid
-fate-bethsoft-vid: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/bethsoft-vid/ANIM0001.VID -vsync 0 -t 5 -pix_fmt rgb24 -f framecrc -
+fate-bethsoft-vid: CMD = framecrc  -i $(SAMPLES)/bethsoft-vid/ANIM0001.VID -vsync 0 -t 5 -pix_fmt rgb24
 FATE_TESTS += fate-bfi
-fate-bfi: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/bfi/2287.bfi -pix_fmt rgb24 -f framecrc -
+fate-bfi: CMD = framecrc  -i $(SAMPLES)/bfi/2287.bfi -pix_fmt rgb24
 FATE_TESTS += fate-bink-demux
-fate-bink-demux: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/bink/Snd0a7d9b58.dee -vn -acodec copy -f crc -
+fate-bink-demux: CMD = crc  -i $(SAMPLES)/bink/Snd0a7d9b58.dee -vn -acodec copy
 FATE_TESTS += fate-bink-demux-video
-fate-bink-demux-video: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/bink/hol2br.bik -f framecrc -
+fate-bink-demux-video: CMD = framecrc  -i $(SAMPLES)/bink/hol2br.bik
 FATE_TESTS += fate-caf
-fate-caf: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/caf/caf-pcm16.caf -f crc -
+fate-caf: CMD = crc  -i $(SAMPLES)/caf/caf-pcm16.caf
 FATE_TESTS += fate-cdgraphics
-fate-cdgraphics: CMD = $$BUILD_PATH/ffmpeg -t 1 -i $$SAMPLES_PATH/cdgraphics/BrotherJohn.cdg -pix_fmt rgb24 -f framecrc -
+fate-cdgraphics: CMD = framecrc  -t 1 -i $(SAMPLES)/cdgraphics/BrotherJohn.cdg -pix_fmt rgb24
 FATE_TESTS += fate-cljr
-fate-cljr: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/cljr/testcljr-partial.avi -f framecrc -
+fate-cljr: CMD = framecrc  -i $(SAMPLES)/cljr/testcljr-partial.avi
 FATE_TESTS += fate-corepng
-fate-corepng: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/png1/corepng-partial.avi -f framecrc -
+fate-corepng: CMD = framecrc  -i $(SAMPLES)/png1/corepng-partial.avi
 FATE_TESTS += fate-creative-adpcm
-fate-creative-adpcm: CMD =  $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/creative/intro-partial.wav -f s16le - | do_md5sum | cut -c-32
+fate-creative-adpcm: CMD = md5  -i $(SAMPLES)/creative/intro-partial.wav -f s16le
 FATE_TESTS += fate-creative-adpcm-8-2.6bit
-fate-creative-adpcm-8-2.6bit: CMD =  $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/creative/BBC_3BIT.VOC -f s16le - | do_md5sum | cut -c-32
+fate-creative-adpcm-8-2.6bit: CMD = md5  -i $(SAMPLES)/creative/BBC_3BIT.VOC -f s16le
 FATE_TESTS += fate-creative-adpcm-8-2bit
-fate-creative-adpcm-8-2bit: CMD =  $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/creative/BBC_2BIT.VOC -f s16le - | do_md5sum | cut -c-32
+fate-creative-adpcm-8-2bit: CMD = md5  -i $(SAMPLES)/creative/BBC_2BIT.VOC -f s16le
 FATE_TESTS += fate-creative-adpcm-8-4bit
-fate-creative-adpcm-8-4bit: CMD =  $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/creative/BBC_4BIT.VOC -f s16le - | do_md5sum | cut -c-32
+fate-creative-adpcm-8-4bit: CMD = md5  -i $(SAMPLES)/creative/BBC_4BIT.VOC -f s16le
 FATE_TESTS += fate-creatureshock-avs
-fate-creatureshock-avs: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/creatureshock-avs/OUTATIME.AVS -pix_fmt rgb24  -f framecrc -
+fate-creatureshock-avs: CMD = framecrc  -i $(SAMPLES)/creatureshock-avs/OUTATIME.AVS -pix_fmt rgb24
 FATE_TESTS += fate-cryo-apc
-fate-cryo-apc: CMD =  $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/cryo-apc/cine007.APC -f s16le - | do_md5sum | cut -c-32
+fate-cryo-apc: CMD = md5  -i $(SAMPLES)/cryo-apc/cine007.APC -f s16le
 FATE_TESTS += fate-cscd
-fate-cscd: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/CSCD/sample_video.avi -an -vsync 0 -pix_fmt rgb24 -f framecrc -
+fate-cscd: CMD = framecrc  -i $(SAMPLES)/CSCD/sample_video.avi -an -vsync 0 -pix_fmt rgb24
 FATE_TESTS += fate-cvid
-fate-cvid: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/cvid/laracroft-cinepak-partial.avi -an -f framecrc -
+fate-cvid: CMD = framecrc  -i $(SAMPLES)/cvid/laracroft-cinepak-partial.avi -an
 FATE_TESTS += fate-cvid-palette
-fate-cvid-palette: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/cvid/catfight-cvid-pal8-partial.mov -pix_fmt rgb24 -an -f framecrc -
+fate-cvid-palette: CMD = framecrc  -i $(SAMPLES)/cvid/catfight-cvid-pal8-partial.mov -pix_fmt rgb24 -an
 FATE_TESTS += fate-cyberia-c93
-fate-cyberia-c93: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/cyberia-c93/intro1.c93 -t 3 -pix_fmt rgb24  -f framecrc -
+fate-cyberia-c93: CMD = framecrc  -i $(SAMPLES)/cyberia-c93/intro1.c93 -t 3 -pix_fmt rgb24
 FATE_TESTS += fate-cyuv
-fate-cyuv: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/cyuv/cyuv.avi -f framecrc -
+fate-cyuv: CMD = framecrc  -i $(SAMPLES)/cyuv/cyuv.avi
 FATE_TESTS += fate-d-cinema-demux
-fate-d-cinema-demux: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/d-cinema/THX_Science_FLT_1920-partial.302 -acodec copy -pix_fmt rgb24 -f framecrc -
+fate-d-cinema-demux: CMD = framecrc  -i $(SAMPLES)/d-cinema/THX_Science_FLT_1920-partial.302 -acodec copy -pix_fmt rgb24
 FATE_TESTS += fate-delphine-cin
-fate-delphine-cin: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/delphine-cin/LOGO-partial.CIN -pix_fmt rgb24 -vsync 0 -f framecrc -
+fate-delphine-cin: CMD = framecrc  -i $(SAMPLES)/delphine-cin/LOGO-partial.CIN -pix_fmt rgb24 -vsync 0
 FATE_TESTS += fate-deluxepaint-anm
-fate-deluxepaint-anm: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/deluxepaint-anm/INTRO1.ANM -pix_fmt rgb24 -f framecrc -
+fate-deluxepaint-anm: CMD = framecrc  -i $(SAMPLES)/deluxepaint-anm/INTRO1.ANM -pix_fmt rgb24
 FATE_TESTS += fate-dpx
-fate-dpx: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/dpx/lighthouse_rgb48.dpx -f framecrc -
+fate-dpx: CMD = framecrc  -i $(SAMPLES)/dpx/lighthouse_rgb48.dpx
 FATE_TESTS += fate-duck-dk3
-fate-duck-dk3: CMD =  $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/duck/sop-audio-only.avi -f s16le - | do_md5sum | cut -c-32
+fate-duck-dk3: CMD = md5  -i $(SAMPLES)/duck/sop-audio-only.avi -f s16le
 FATE_TESTS += fate-duck-dk4
-fate-duck-dk4: CMD =  $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/duck/salsa-audio-only.avi -f s16le - | do_md5sum | cut -c-32
+fate-duck-dk4: CMD = md5  -i $(SAMPLES)/duck/salsa-audio-only.avi -f s16le
 FATE_TESTS += fate-duck-tm2
-fate-duck-tm2: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/duck/tm20.avi -f framecrc -
+fate-duck-tm2: CMD = framecrc  -i $(SAMPLES)/duck/tm20.avi
 FATE_TESTS += fate-ea-cdata
-fate-ea-cdata: CMD =  $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/ea-cdata/166b084d.46410f77.0009b440.24be960c.cdata -f s16le - | do_md5sum | cut -c-32
+fate-ea-cdata: CMD = md5  -i $(SAMPLES)/ea-cdata/166b084d.46410f77.0009b440.24be960c.cdata -f s16le
 FATE_TESTS += fate-ea-cmv
-fate-ea-cmv: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/ea-cmv/TITLE.CMV -vsync 0 -pix_fmt rgb24 -f framecrc -
+fate-ea-cmv: CMD = framecrc  -i $(SAMPLES)/ea-cmv/TITLE.CMV -vsync 0 -pix_fmt rgb24
 FATE_TESTS += fate-ea-dct
-fate-ea-dct: CMD = $$BUILD_PATH/ffmpeg -idct simple -i $$SAMPLES_PATH/ea-dct/NFS2Esprit-partial.dct -f framecrc -
+fate-ea-dct: CMD = framecrc  -idct simple -i $(SAMPLES)/ea-dct/NFS2Esprit-partial.dct
 FATE_TESTS += fate-ea-mad-adpcm-ea-r1
-fate-ea-mad-adpcm-ea-r1: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/ea-mad/NFS6LogoE.mad -f framecrc -
+fate-ea-mad-adpcm-ea-r1: CMD = framecrc  -i $(SAMPLES)/ea-mad/NFS6LogoE.mad
 FATE_TESTS += fate-ea-mad-pcm-planar
-fate-ea-mad-pcm-planar: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/ea-mad/xeasport.mad -f framecrc -
+fate-ea-mad-pcm-planar: CMD = framecrc  -i $(SAMPLES)/ea-mad/xeasport.mad
 FATE_TESTS += fate-ea-tgq
-fate-ea-tgq: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/ea-tgq/v27.tgq -an -f framecrc -
+fate-ea-tgq: CMD = framecrc  -i $(SAMPLES)/ea-tgq/v27.tgq -an
 FATE_TESTS += fate-ea-tgv-ima-ea-eacs
-fate-ea-tgv-ima-ea-eacs: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/ea-tgv/INTRO8K-partial.TGV -pix_fmt rgb24 -f framecrc -
+fate-ea-tgv-ima-ea-eacs: CMD = framecrc  -i $(SAMPLES)/ea-tgv/INTRO8K-partial.TGV -pix_fmt rgb24
 FATE_TESTS += fate-ea-tgv-ima-ea-sead
-fate-ea-tgv-ima-ea-sead: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/ea-tgv/INTEL_S.TGV -pix_fmt rgb24 -f framecrc -
+fate-ea-tgv-ima-ea-sead: CMD = framecrc  -i $(SAMPLES)/ea-tgv/INTEL_S.TGV -pix_fmt rgb24
 FATE_TESTS += fate-ea-tqi-adpcm
-fate-ea-tqi-adpcm: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/ea-wve/networkBackbone-partial.wve -f framecrc -
+fate-ea-tqi-adpcm: CMD = framecrc  -i $(SAMPLES)/ea-wve/networkBackbone-partial.wve
 FATE_TESTS += fate-ea-vp60
-fate-ea-vp60: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/ea-vp6/g36.vp6 -f framecrc -
+fate-ea-vp60: CMD = framecrc  -i $(SAMPLES)/ea-vp6/g36.vp6
 FATE_TESTS += fate-ea-vp61
-fate-ea-vp61: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/ea-vp6/MovieSkirmishGondor.vp6 -t 4 -f framecrc -
+fate-ea-vp61: CMD = framecrc  -i $(SAMPLES)/ea-vp6/MovieSkirmishGondor.vp6 -t 4
 FATE_TESTS += fate-feeble-dxa
-fate-feeble-dxa: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/dxa/meetsquid.dxa -t 2 -pix_fmt rgb24  -f framecrc -
+fate-feeble-dxa: CMD = framecrc  -i $(SAMPLES)/dxa/meetsquid.dxa -t 2 -pix_fmt rgb24
 FATE_TESTS += fate-film-cvid-pcm-stereo-8bit
-fate-film-cvid-pcm-stereo-8bit: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/film/logo-capcom.cpk -f framecrc -
+fate-film-cvid-pcm-stereo-8bit: CMD = framecrc  -i $(SAMPLES)/film/logo-capcom.cpk
 FATE_TESTS += fate-flic-af11-palette-change
-fate-flic-af11-palette-change: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/fli/fli-engines.fli -t 3.3 -pix_fmt rgb24 -f framecrc -
+fate-flic-af11-palette-change: CMD = framecrc  -i $(SAMPLES)/fli/fli-engines.fli -t 3.3 -pix_fmt rgb24
 FATE_TESTS += fate-flic-af12
-fate-flic-af12: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/fli/jj00c2.fli -pix_fmt rgb24 -f framecrc -
+fate-flic-af12: CMD = framecrc  -i $(SAMPLES)/fli/jj00c2.fli -pix_fmt rgb24
 FATE_TESTS += fate-flic-magiccarpet
-fate-flic-magiccarpet: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/fli/intel.dat -pix_fmt rgb24 -f framecrc -
+fate-flic-magiccarpet: CMD = framecrc  -i $(SAMPLES)/fli/intel.dat -pix_fmt rgb24
 FATE_TESTS += fate-fraps-v0
-fate-fraps-v0: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/fraps/Griffin_Ragdoll01-partial.avi -f framecrc -
+fate-fraps-v0: CMD = framecrc  -i $(SAMPLES)/fraps/Griffin_Ragdoll01-partial.avi
 FATE_TESTS += fate-fraps-v1
-fate-fraps-v1: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/fraps/sample-v1.avi -an -f framecrc -
+fate-fraps-v1: CMD = framecrc  -i $(SAMPLES)/fraps/sample-v1.avi -an
 FATE_TESTS += fate-fraps-v2
-fate-fraps-v2: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/fraps/test3-nosound-partial.avi -f framecrc -
+fate-fraps-v2: CMD = framecrc  -i $(SAMPLES)/fraps/test3-nosound-partial.avi
 FATE_TESTS += fate-fraps-v3
-fate-fraps-v3: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/fraps/psclient-partial.avi -pix_fmt rgb24 -f framecrc -
+fate-fraps-v3: CMD = framecrc  -i $(SAMPLES)/fraps/psclient-partial.avi -pix_fmt rgb24
 FATE_TESTS += fate-fraps-v4
-fate-fraps-v4: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/fraps/WoW_2006-11-03_14-58-17-19-nosound-partial.avi -f framecrc -
+fate-fraps-v4: CMD = framecrc  -i $(SAMPLES)/fraps/WoW_2006-11-03_14-58-17-19-nosound-partial.avi
 FATE_TESTS += fate-fraps-v5
-fate-fraps-v5: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/fraps/fraps-v5-bouncing-balls-partial.avi -f framecrc -
+fate-fraps-v5: CMD = framecrc  -i $(SAMPLES)/fraps/fraps-v5-bouncing-balls-partial.avi
 FATE_TESTS += fate-frwu
-fate-frwu: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/frwu/frwu.avi -f framecrc -
+fate-frwu: CMD = framecrc  -i $(SAMPLES)/frwu/frwu.avi
 FATE_TESTS += fate-funcom-iss
-fate-funcom-iss: CMD =  $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/funcom-iss/0004010100.iss -f s16le - | do_md5sum | cut -c-32
-FATE_TESTS += fate-h264-conformance-aud_mw_e
-fate-h264-conformance-aud_mw_e: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/AUD_MW_E.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-ba1_ft_c
-fate-h264-conformance-ba1_ft_c: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/BA1_FT_C.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-ba1_sony_d
-fate-h264-conformance-ba1_sony_d: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/BA1_Sony_D.jsv -f framecrc -
-FATE_TESTS += fate-h264-conformance-ba2_sony_f
-fate-h264-conformance-ba2_sony_f: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/BA2_Sony_F.jsv -f framecrc -
-FATE_TESTS += fate-h264-conformance-ba3_sva_c
-fate-h264-conformance-ba3_sva_c: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/BA3_SVA_C.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-ba_mw_d
-fate-h264-conformance-ba_mw_d: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/BA_MW_D.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-bamq1_jvc_c
-fate-h264-conformance-bamq1_jvc_c: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/BAMQ1_JVC_C.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-bamq2_jvc_c
-fate-h264-conformance-bamq2_jvc_c: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/BAMQ2_JVC_C.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-banm_mw_d
-fate-h264-conformance-banm_mw_d: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/BANM_MW_D.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-basqp1_sony_c
-fate-h264-conformance-basqp1_sony_c: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/BASQP1_Sony_C.jsv -f framecrc -
-FATE_TESTS += fate-h264-conformance-caba1_sony_d
-fate-h264-conformance-caba1_sony_d: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/CABA1_Sony_D.jsv -f framecrc -
-FATE_TESTS += fate-h264-conformance-caba1_sva_b
-fate-h264-conformance-caba1_sva_b: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/CABA1_SVA_B.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-caba2_sony_e
-fate-h264-conformance-caba2_sony_e: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/CABA2_Sony_E.jsv -f framecrc -
-FATE_TESTS += fate-h264-conformance-caba2_sva_b
-fate-h264-conformance-caba2_sva_b: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/CABA2_SVA_B.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-caba3_sony_c
-fate-h264-conformance-caba3_sony_c: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/CABA3_Sony_C.jsv -f framecrc -
-FATE_TESTS += fate-h264-conformance-caba3_sva_b
-fate-h264-conformance-caba3_sva_b: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/CABA3_SVA_B.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-caba3_toshiba_e
-fate-h264-conformance-caba3_toshiba_e: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/CABA3_TOSHIBA_E.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-cabac_mot_fld0_full
-fate-h264-conformance-cabac_mot_fld0_full: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/camp_mot_fld0_full.26l -f framecrc -
-FATE_TESTS += fate-h264-conformance-cabac_mot_frm0_full
-fate-h264-conformance-cabac_mot_frm0_full: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/camp_mot_frm0_full.26l -f framecrc -
-FATE_TESTS += fate-h264-conformance-cabac_mot_mbaff0_full
-fate-h264-conformance-cabac_mot_mbaff0_full: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/camp_mot_mbaff0_full.26l -f framecrc -
-FATE_TESTS += fate-h264-conformance-cabac_mot_picaff0_full
-fate-h264-conformance-cabac_mot_picaff0_full: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/camp_mot_picaff0_full.26l -f framecrc -
-FATE_TESTS += fate-h264-conformance-cabaci3_sony_b
-fate-h264-conformance-cabaci3_sony_b: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/CABACI3_Sony_B.jsv -f framecrc -
-FATE_TESTS += fate-h264-conformance-cabast3_sony_e
-fate-h264-conformance-cabast3_sony_e: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/CABAST3_Sony_E.jsv -f framecrc -
-FATE_TESTS += fate-h264-conformance-cabastbr3_sony_b
-fate-h264-conformance-cabastbr3_sony_b: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/CABASTBR3_Sony_B.jsv -f framecrc -
-FATE_TESTS += fate-h264-conformance-cabref3_sand_d
-fate-h264-conformance-cabref3_sand_d: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/CABREF3_Sand_D.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-cacqp3_sony_d
-fate-h264-conformance-cacqp3_sony_d: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/CACQP3_Sony_D.jsv -f framecrc -
-FATE_TESTS += fate-h264-conformance-cafi1_sva_c
-fate-h264-conformance-cafi1_sva_c: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/CAFI1_SVA_C.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-cama1_sony_c
-fate-h264-conformance-cama1_sony_c: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/CAMA1_Sony_C.jsv -f framecrc -
-FATE_TESTS += fate-h264-conformance-cama1_toshiba_b
-fate-h264-conformance-cama1_toshiba_b: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/CAMA1_TOSHIBA_B.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-cama1_vtc_c
-fate-h264-conformance-cama1_vtc_c: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/cama1_vtc_c.avc -f framecrc -
-FATE_TESTS += fate-h264-conformance-cama2_vtc_b
-fate-h264-conformance-cama2_vtc_b: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -i $$SAMPLES_PATH/h264-conformance/cama2_vtc_b.avc -f framecrc -
-FATE_TESTS += fate-h264-conformance-cama3_sand_e
-fate-h264-conformance-cama3_sand_e: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/CAMA3_Sand_E.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-cama3_vtc_b
-fate-h264-conformance-cama3_vtc_b: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/cama3_vtc_b.avc -f framecrc -
-FATE_TESTS += fate-h264-conformance-camaci3_sony_c
-fate-h264-conformance-camaci3_sony_c: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/CAMACI3_Sony_C.jsv -f framecrc -
-FATE_TESTS += fate-h264-conformance-camanl1_toshiba_b
-fate-h264-conformance-camanl1_toshiba_b: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/CAMANL1_TOSHIBA_B.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-camanl2_toshiba_b
-fate-h264-conformance-camanl2_toshiba_b: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/CAMANL2_TOSHIBA_B.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-camanl3_sand_e
-fate-h264-conformance-camanl3_sand_e: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/CAMANL3_Sand_E.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-camasl3_sony_b
-fate-h264-conformance-camasl3_sony_b: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/CAMASL3_Sony_B.jsv -f framecrc -
-FATE_TESTS += fate-h264-conformance-camp_mot_mbaff_l30
-fate-h264-conformance-camp_mot_mbaff_l30: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/CAMP_MOT_MBAFF_L30.26l -f framecrc -
-FATE_TESTS += fate-h264-conformance-camp_mot_mbaff_l31
-fate-h264-conformance-camp_mot_mbaff_l31: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/CAMP_MOT_MBAFF_L31.26l -f framecrc -
-FATE_TESTS += fate-h264-conformance-canl1_sony_e
-fate-h264-conformance-canl1_sony_e: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/CANL1_Sony_E.jsv -f framecrc -
-FATE_TESTS += fate-h264-conformance-canl1_sva_b
-fate-h264-conformance-canl1_sva_b: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/CANL1_SVA_B.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-canl1_toshiba_g
-fate-h264-conformance-canl1_toshiba_g: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/CANL1_TOSHIBA_G.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-canl2_sony_e
-fate-h264-conformance-canl2_sony_e: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/CANL2_Sony_E.jsv -f framecrc -
-FATE_TESTS += fate-h264-conformance-canl2_sva_b
-fate-h264-conformance-canl2_sva_b: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/CANL2_SVA_B.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-canl3_sony_c
-fate-h264-conformance-canl3_sony_c: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/CANL3_Sony_C.jsv -f framecrc -
-FATE_TESTS += fate-h264-conformance-canl3_sva_b
-fate-h264-conformance-canl3_sva_b: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/CANL3_SVA_B.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-canl4_sva_b
-fate-h264-conformance-canl4_sva_b: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/CANL4_SVA_B.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-canlma2_sony_c
-fate-h264-conformance-canlma2_sony_c: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/CANLMA2_Sony_C.jsv -f framecrc -
-FATE_TESTS += fate-h264-conformance-canlma3_sony_c
-fate-h264-conformance-canlma3_sony_c: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/CANLMA3_Sony_C.jsv -f framecrc -
-FATE_TESTS += fate-h264-conformance-capa1_toshiba_b
-fate-h264-conformance-capa1_toshiba_b: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/CAPA1_TOSHIBA_B.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-capama3_sand_f
-fate-h264-conformance-capama3_sand_f: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/CAPAMA3_Sand_F.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-capcm1_sand_e
-fate-h264-conformance-capcm1_sand_e: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/CAPCM1_Sand_E.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-capcmnl1_sand_e
-fate-h264-conformance-capcmnl1_sand_e: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/CAPCMNL1_Sand_E.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-capm3_sony_d
-fate-h264-conformance-capm3_sony_d: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/CAPM3_Sony_D.jsv -f framecrc -
-FATE_TESTS += fate-h264-conformance-caqp1_sony_b
-fate-h264-conformance-caqp1_sony_b: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/CAQP1_Sony_B.jsv -f framecrc -
-FATE_TESTS += fate-h264-conformance-cavlc_mot_fld0_full_b
-fate-h264-conformance-cavlc_mot_fld0_full_b: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/cvmp_mot_fld0_full_B.26l -f framecrc -
-FATE_TESTS += fate-h264-conformance-cavlc_mot_frm0_full_b
-fate-h264-conformance-cavlc_mot_frm0_full_b: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/cvmp_mot_frm0_full_B.26l -f framecrc -
-FATE_TESTS += fate-h264-conformance-cavlc_mot_mbaff0_full_b
-fate-h264-conformance-cavlc_mot_mbaff0_full_b: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/cvmp_mot_mbaff0_full_B.26l -f framecrc -
-FATE_TESTS += fate-h264-conformance-cavlc_mot_picaff0_full_b
-fate-h264-conformance-cavlc_mot_picaff0_full_b: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/cvmp_mot_picaff0_full_B.26l -f framecrc -
-FATE_TESTS += fate-h264-conformance-cawp1_toshiba_e
-fate-h264-conformance-cawp1_toshiba_e: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/CAWP1_TOSHIBA_E.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-cawp5_toshiba_e
-fate-h264-conformance-cawp5_toshiba_e: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/CAWP5_TOSHIBA_E.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-ci1_ft_b
-fate-h264-conformance-ci1_ft_b: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/CI1_FT_B.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-ci_mw_d
-fate-h264-conformance-ci_mw_d: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/CI_MW_D.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-cvbs3_sony_c
-fate-h264-conformance-cvbs3_sony_c: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/CVBS3_Sony_C.jsv -f framecrc -
-FATE_TESTS += fate-h264-conformance-cvcanlma2_sony_c
-fate-h264-conformance-cvcanlma2_sony_c: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/CVCANLMA2_Sony_C.jsv -f framecrc -
-FATE_TESTS += fate-h264-conformance-cvfi1_sony_d
-fate-h264-conformance-cvfi1_sony_d: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/CVFI1_Sony_D.jsv -f framecrc -
-FATE_TESTS += fate-h264-conformance-cvfi1_sva_c
-fate-h264-conformance-cvfi1_sva_c: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/CVFI1_SVA_C.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-cvfi2_sony_h
-fate-h264-conformance-cvfi2_sony_h: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/CVFI2_Sony_H.jsv -f framecrc -
-FATE_TESTS += fate-h264-conformance-cvfi2_sva_c
-fate-h264-conformance-cvfi2_sva_c: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/CVFI2_SVA_C.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-cvma1_sony_d
-fate-h264-conformance-cvma1_sony_d: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/CVMA1_Sony_D.jsv -f framecrc -
-FATE_TESTS += fate-h264-conformance-cvma1_toshiba_b
-fate-h264-conformance-cvma1_toshiba_b: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/CVMA1_TOSHIBA_B.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-cvmanl1_toshiba_b
-fate-h264-conformance-cvmanl1_toshiba_b: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/CVMANL1_TOSHIBA_B.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-cvmanl2_toshiba_b
-fate-h264-conformance-cvmanl2_toshiba_b: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/CVMANL2_TOSHIBA_B.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-cvmapaqp3_sony_e
-fate-h264-conformance-cvmapaqp3_sony_e: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/CVMAPAQP3_Sony_E.jsv -f framecrc -
-FATE_TESTS += fate-h264-conformance-cvmaqp2_sony_g
-fate-h264-conformance-cvmaqp2_sony_g: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/CVMAQP2_Sony_G.jsv -f framecrc -
-FATE_TESTS += fate-h264-conformance-cvmaqp3_sony_d
-fate-h264-conformance-cvmaqp3_sony_d: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/CVMAQP3_Sony_D.jsv -f framecrc -
-FATE_TESTS += fate-h264-conformance-cvmp_mot_fld_l30_b
-fate-h264-conformance-cvmp_mot_fld_l30_b: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/CVMP_MOT_FLD_L30_B.26l -f framecrc -
-FATE_TESTS += fate-h264-conformance-cvmp_mot_frm_l31_b
-fate-h264-conformance-cvmp_mot_frm_l31_b: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/CVMP_MOT_FRM_L31_B.26l -f framecrc -
-FATE_TESTS += fate-h264-conformance-cvnlfi1_sony_c
-fate-h264-conformance-cvnlfi1_sony_c: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -i $$SAMPLES_PATH/h264-conformance/CVNLFI1_Sony_C.jsv -f framecrc -
-FATE_TESTS += fate-h264-conformance-cvnlfi2_sony_h
-fate-h264-conformance-cvnlfi2_sony_h: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/CVNLFI2_Sony_H.jsv -f framecrc -
-FATE_TESTS += fate-h264-conformance-cvpa1_toshiba_b
-fate-h264-conformance-cvpa1_toshiba_b: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/CVPA1_TOSHIBA_B.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-cvpcmnl1_sva_c
-fate-h264-conformance-cvpcmnl1_sva_c: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/CVPCMNL1_SVA_C.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-cvpcmnl2_sva_c
-fate-h264-conformance-cvpcmnl2_sva_c: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/CVPCMNL2_SVA_C.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-cvwp1_toshiba_e
-fate-h264-conformance-cvwp1_toshiba_e: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/CVWP1_TOSHIBA_E.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-cvwp2_toshiba_e
-fate-h264-conformance-cvwp2_toshiba_e: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/CVWP2_TOSHIBA_E.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-cvwp3_toshiba_e
-fate-h264-conformance-cvwp3_toshiba_e: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/CVWP3_TOSHIBA_E.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-cvwp5_toshiba_e
-fate-h264-conformance-cvwp5_toshiba_e: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/CVWP5_TOSHIBA_E.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-fi1_sony_e
-fate-h264-conformance-fi1_sony_e: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -i $$SAMPLES_PATH/h264-conformance/FI1_Sony_E.jsv -f framecrc -
-FATE_TESTS += fate-h264-conformance-frext-alphaconformanceg
-fate-h264-conformance-frext-alphaconformanceg: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/FRext/test8b43.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-frext-bcrm_freh10
-fate-h264-conformance-frext-bcrm_freh10: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/FRext/freh10.264 -vsync 0 -f framecrc -
-FATE_TESTS += fate-h264-conformance-frext-brcm_freh11
-fate-h264-conformance-frext-brcm_freh11: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/FRext/freh11.264 -vsync 0 -f framecrc -
-FATE_TESTS += fate-h264-conformance-frext-brcm_freh3
-fate-h264-conformance-frext-brcm_freh3: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/FRext/freh3.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-frext-brcm_freh4
-fate-h264-conformance-frext-brcm_freh4: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/FRext/freh4.264 -vsync 0 -f framecrc -
-FATE_TESTS += fate-h264-conformance-frext-brcm_freh5
-fate-h264-conformance-frext-brcm_freh5: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/FRext/freh5.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-frext-brcm_freh8
-fate-h264-conformance-frext-brcm_freh8: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/FRext/freh8.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-frext-brcm_freh9
-fate-h264-conformance-frext-brcm_freh9: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/FRext/freh9.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-frext-freh12_b
-fate-h264-conformance-frext-freh12_b: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/FRext/Freh12_B.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-frext-freh1_b
-fate-h264-conformance-frext-freh1_b: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/FRext/Freh1_B.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-frext-freh2_b
-fate-h264-conformance-frext-freh2_b: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/FRext/Freh2_B.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-frext-freh6
-fate-h264-conformance-frext-freh6: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/FRext/freh6.264 -vsync 0 -f framecrc -
-FATE_TESTS += fate-h264-conformance-frext-freh7_b
-fate-h264-conformance-frext-freh7_b: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/FRext/Freh7_B.264 -vsync 0 -f framecrc -
-FATE_TESTS += fate-h264-conformance-frext-frext01_jvc_d
-fate-h264-conformance-frext-frext01_jvc_d: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/FRext/FREXT01_JVC_D.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-frext-frext02_jvc_c
-fate-h264-conformance-frext-frext02_jvc_c: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/FRext/FREXT02_JVC_C.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-frext-frext1_panasonic_c
-fate-h264-conformance-frext-frext1_panasonic_c: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/FRext/FRExt1_Panasonic.avc -f framecrc -
-FATE_TESTS += fate-h264-conformance-frext-frext2_panasonic_b
-fate-h264-conformance-frext-frext2_panasonic_b: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/FRext/FRExt2_Panasonic.avc -vsync 0 -f framecrc -
-FATE_TESTS += fate-h264-conformance-frext-frext3_panasonic_d
-fate-h264-conformance-frext-frext3_panasonic_d: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/FRext/FRExt3_Panasonic.avc -f framecrc -
-FATE_TESTS += fate-h264-conformance-frext-frext4_panasonic_a
-fate-h264-conformance-frext-frext4_panasonic_a: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/FRext/FRExt4_Panasonic.avc -f framecrc -
-FATE_TESTS += fate-h264-conformance-frext-frext_mmco4_sony_b
-fate-h264-conformance-frext-frext_mmco4_sony_b: CMD = $$BUILD_PATH/ffmpeg -strict 1 -i $$SAMPLES_PATH/h264-conformance/FRext/FRExt_MMCO4_Sony_B.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-frext-hcaff1_hhi_b
-fate-h264-conformance-frext-hcaff1_hhi_b: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/FRext/HCAFF1_HHI.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-frext-hcafr1_hhi_c
-fate-h264-conformance-frext-hcafr1_hhi_c: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/FRext/HCAFR1_HHI.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-frext-hcafr2_hhi_a
-fate-h264-conformance-frext-hcafr2_hhi_a: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/FRext/HCAFR2_HHI.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-frext-hcafr3_hhi_a
-fate-h264-conformance-frext-hcafr3_hhi_a: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/FRext/HCAFR3_HHI.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-frext-hcafr4_hhi_a
-fate-h264-conformance-frext-hcafr4_hhi_a: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/FRext/HCAFR4_HHI.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-frext-hcamff1_hhi_b
-fate-h264-conformance-frext-hcamff1_hhi_b: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/FRext/HCAMFF1_HHI.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-frext-hpca_brcm_c
-fate-h264-conformance-frext-hpca_brcm_c: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/FRext/HPCA_BRCM_C.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-frext-hpcadq_brcm_b
-fate-h264-conformance-frext-hpcadq_brcm_b: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/FRext/HPCADQ_BRCM_B.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-frext-hpcafl_bcrm_c
-fate-h264-conformance-frext-hpcafl_bcrm_c: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/FRext/HPCAFL_BRCM_C.264 -vsync 0 -f framecrc -
-FATE_TESTS += fate-h264-conformance-frext-hpcaflnl_bcrm_c
-fate-h264-conformance-frext-hpcaflnl_bcrm_c: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/FRext/HPCAFLNL_BRCM_C.264 -vsync 0 -f framecrc -
-FATE_TESTS += fate-h264-conformance-frext-hpcalq_brcm_b
-fate-h264-conformance-frext-hpcalq_brcm_b: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/FRext/HPCALQ_BRCM_B.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-frext-hpcamapalq_bcrm_b
-fate-h264-conformance-frext-hpcamapalq_bcrm_b: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/FRext/HPCAMAPALQ_BRCM_B.264 -vsync 0 -f framecrc -
-FATE_TESTS += fate-h264-conformance-frext-hpcamolq_brcm_b
-fate-h264-conformance-frext-hpcamolq_brcm_b: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/FRext/HPCAMOLQ_BRCM_B.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-frext-hpcanl_brcm_c
-fate-h264-conformance-frext-hpcanl_brcm_c: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/FRext/HPCANL_BRCM_C.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-frext-hpcaq2lq_brcm_b
-fate-h264-conformance-frext-hpcaq2lq_brcm_b: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/FRext/HPCAQ2LQ_BRCM_B.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-frext-hpcv_brcm_a
-fate-h264-conformance-frext-hpcv_brcm_a: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/FRext/HPCV_BRCM_A.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-frext-hpcvfl_bcrm_a
-fate-h264-conformance-frext-hpcvfl_bcrm_a: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/FRext/HPCVFL_BRCM_A.264 -vsync 0 -f framecrc -
-FATE_TESTS += fate-h264-conformance-frext-hpcvflnl_bcrm_a
-fate-h264-conformance-frext-hpcvflnl_bcrm_a: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/FRext/HPCVFLNL_BRCM_A.264 -vsync 0 -f framecrc -
-FATE_TESTS += fate-h264-conformance-frext-hpcvmolq_brcm_b
-fate-h264-conformance-frext-hpcvmolq_brcm_b: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/FRext/HPCVMOLQ_BRCM_B.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-frext-hpcvnl_brcm_a
-fate-h264-conformance-frext-hpcvnl_brcm_a: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/FRext/HPCVNL_BRCM_A.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-hcbp2_hhi_a
-fate-h264-conformance-hcbp2_hhi_a: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/HCBP2_HHI_A.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-hcmp1_hhi_a
-fate-h264-conformance-hcmp1_hhi_a: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/HCMP1_HHI_A.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-ls_sva_d
-fate-h264-conformance-ls_sva_d: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/LS_SVA_D.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-midr_mw_d
-fate-h264-conformance-midr_mw_d: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/MIDR_MW_D.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-mps_mw_a
-fate-h264-conformance-mps_mw_a: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/MPS_MW_A.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-mr1_bt_a
-fate-h264-conformance-mr1_bt_a: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/MR1_BT_A.h264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-mr1_mw_a
-fate-h264-conformance-mr1_mw_a: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/MR1_MW_A.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-mr2_mw_a
-fate-h264-conformance-mr2_mw_a: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/MR2_MW_A.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-mr2_tandberg_e
-fate-h264-conformance-mr2_tandberg_e: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/MR2_TANDBERG_E.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-mr3_tandberg_b
-fate-h264-conformance-mr3_tandberg_b: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/MR3_TANDBERG_B.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-mr4_tandberg_c
-fate-h264-conformance-mr4_tandberg_c: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/MR4_TANDBERG_C.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-mr5_tandberg_c
-fate-h264-conformance-mr5_tandberg_c: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/MR5_TANDBERG_C.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-mr6_bt_b
-fate-h264-conformance-mr6_bt_b: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/MR6_BT_B.h264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-mr7_bt_b
-fate-h264-conformance-mr7_bt_b: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/MR7_BT_B.h264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-mr8_bt_b
-fate-h264-conformance-mr8_bt_b: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/MR8_BT_B.h264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-mr9_bt_b
-fate-h264-conformance-mr9_bt_b: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/MR9_BT_B.h264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-mv1_brcm_d
-fate-h264-conformance-mv1_brcm_d: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/src19td.IBP.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-nl1_sony_d
-fate-h264-conformance-nl1_sony_d: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/NL1_Sony_D.jsv -f framecrc -
-FATE_TESTS += fate-h264-conformance-nl2_sony_h
-fate-h264-conformance-nl2_sony_h: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/NL2_Sony_H.jsv -f framecrc -
-FATE_TESTS += fate-h264-conformance-nl3_sva_e
-fate-h264-conformance-nl3_sva_e: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/NL3_SVA_E.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-nlmq1_jvc_c
-fate-h264-conformance-nlmq1_jvc_c: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/NLMQ1_JVC_C.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-nlmq2_jvc_c
-fate-h264-conformance-nlmq2_jvc_c: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/NLMQ2_JVC_C.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-nrf_mw_e
-fate-h264-conformance-nrf_mw_e: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/NRF_MW_E.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-sharp_mp_field_1_b
-fate-h264-conformance-sharp_mp_field_1_b: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -i $$SAMPLES_PATH/h264-conformance/Sharp_MP_Field_1_B.jvt -f framecrc -
-FATE_TESTS += fate-h264-conformance-sharp_mp_field_2_b
-fate-h264-conformance-sharp_mp_field_2_b: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -i $$SAMPLES_PATH/h264-conformance/Sharp_MP_Field_2_B.jvt -f framecrc -
-FATE_TESTS += fate-h264-conformance-sharp_mp_field_3_b
-fate-h264-conformance-sharp_mp_field_3_b: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -i $$SAMPLES_PATH/h264-conformance/Sharp_MP_Field_3_B.jvt -f framecrc -
-FATE_TESTS += fate-h264-conformance-sharp_mp_paff_1r2
-fate-h264-conformance-sharp_mp_paff_1r2: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/Sharp_MP_PAFF_1r2.jvt -f framecrc -
-FATE_TESTS += fate-h264-conformance-sharp_mp_paff_2r
-fate-h264-conformance-sharp_mp_paff_2r: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/Sharp_MP_PAFF_2.jvt -f framecrc -
-FATE_TESTS += fate-h264-conformance-sl1_sva_b
-fate-h264-conformance-sl1_sva_b: CMD = $$BUILD_PATH/ffmpeg -vsync 0 -strict 1 -i $$SAMPLES_PATH/h264-conformance/SL1_SVA_B.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-sva_ba1_b
-fate-h264-conformance-sva_ba1_b: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/SVA_BA1_B.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-sva_ba2_d
-fate-h264-conformance-sva_ba2_d: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/SVA_BA2_D.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-sva_base_b
-fate-h264-conformance-sva_base_b: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/SVA_Base_B.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-sva_cl1_e
-fate-h264-conformance-sva_cl1_e: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/SVA_CL1_E.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-sva_fm1_e
-fate-h264-conformance-sva_fm1_e: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/SVA_FM1_E.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-sva_nl1_b
-fate-h264-conformance-sva_nl1_b: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/SVA_NL1_B.264 -f framecrc -
-FATE_TESTS += fate-h264-conformance-sva_nl2_e
-fate-h264-conformance-sva_nl2_e: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/h264-conformance/SVA_NL2_E.264 -f framecrc -
+fate-funcom-iss: CMD = md5  -i $(SAMPLES)/funcom-iss/0004010100.iss -f s16le
 FATE_TESTS += fate-id-cin-video
-fate-id-cin-video: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/idcin/idlog-2MB.cin -pix_fmt rgb24 -f framecrc -
+fate-id-cin-video: CMD = framecrc  -i $(SAMPLES)/idcin/idlog-2MB.cin -pix_fmt rgb24
 FATE_TESTS += fate-idroq-video-dpcm
-fate-idroq-video-dpcm: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/idroq/idlogo.roq -f framecrc -
+fate-idroq-video-dpcm: CMD = framecrc  -i $(SAMPLES)/idroq/idlogo.roq
 FATE_TESTS += fate-idroq-video-encode
-fate-idroq-video-encode: CMD =  $$BUILD_PATH/ffmpeg -t 0.2 -f image2 -vcodec pgmyuv -i $$SAMPLES_PATH/ffmpeg-synthetic/vsynth1/%02d.pgm -sws_flags +bitexact -padleft 80 -padright 80 -padtop 112 -padbottom 112 -f RoQ - | do_md5sum | cut -c-32
+fate-idroq-video-encode: CMD = md5  -t 0.2 -f image2 -vcodec pgmyuv -i $(SAMPLES)/ffmpeg-synthetic/vsynth1/%02d.pgm -sws_flags +bitexact -vf pad=512:512:80:112 -f RoQ
 FATE_TESTS += fate-iff-byterun1
-fate-iff-byterun1: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/iff/ASH.LBM -pix_fmt rgb24 -f framecrc -
+fate-iff-byterun1: CMD = framecrc  -i $(SAMPLES)/iff/ASH.LBM -pix_fmt rgb24
 FATE_TESTS += fate-iff-fibonacci
-fate-iff-fibonacci: CMD =  $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/iff/dasboot-in-compressed -f s16le - | do_md5sum | cut -c-32
+fate-iff-fibonacci: CMD = md5  -i $(SAMPLES)/iff/dasboot-in-compressed -f s16le
 FATE_TESTS += fate-iff-ilbm
-fate-iff-ilbm: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/iff/lms-matriks.ilbm -pix_fmt rgb24 -f framecrc -
+fate-iff-ilbm: CMD = framecrc  -i $(SAMPLES)/iff/lms-matriks.ilbm -pix_fmt rgb24
 FATE_TESTS += fate-iff-pcm
-fate-iff-pcm: CMD =  $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/iff/Bells -f s16le - | do_md5sum | cut -c-32
+fate-iff-pcm: CMD = md5  -i $(SAMPLES)/iff/Bells -f s16le
 FATE_TESTS += fate-indeo2
-fate-indeo2: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/rt21/VPAR0026.AVI -f framecrc -
+fate-indeo2: CMD = framecrc  -i $(SAMPLES)/rt21/VPAR0026.AVI
 FATE_TESTS += fate-indeo3
-fate-indeo3: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/iv32/cubes.mov -f framecrc -
+fate-indeo3: CMD = framecrc  -i $(SAMPLES)/iv32/cubes.mov
 FATE_TESTS += fate-indeo5
-fate-indeo5: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/iv50/Educ_Movie_DeadlyForce.avi -an -f framecrc -
+fate-indeo5: CMD = framecrc  -i $(SAMPLES)/iv50/Educ_Movie_DeadlyForce.avi -an
 FATE_TESTS += fate-interplay-mve-16bit
-fate-interplay-mve-16bit: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/interplay-mve/descent3-level5-16bit-partial.mve -pix_fmt rgb24 -f framecrc -
+fate-interplay-mve-16bit: CMD = framecrc  -i $(SAMPLES)/interplay-mve/descent3-level5-16bit-partial.mve -pix_fmt rgb24
 FATE_TESTS += fate-interplay-mve-8bit
-fate-interplay-mve-8bit: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/interplay-mve/interplay-logo-2MB.mve -pix_fmt rgb24 -f framecrc -
+fate-interplay-mve-8bit: CMD = framecrc  -i $(SAMPLES)/interplay-mve/interplay-logo-2MB.mve -pix_fmt rgb24
 FATE_TESTS += fate-iv8-demux
-fate-iv8-demux: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/iv8/zzz-partial.mpg -vsync 0 -vcodec copy -f framecrc -
+fate-iv8-demux: CMD = framecrc  -i $(SAMPLES)/iv8/zzz-partial.mpg -vsync 0 -vcodec copy
 FATE_TESTS += fate-kmvc
-fate-kmvc: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/KMVC/LOGO1.AVI -an -t 3 -pix_fmt rgb24  -f framecrc -
+fate-kmvc: CMD = framecrc  -i $(SAMPLES)/KMVC/LOGO1.AVI -an -t 3 -pix_fmt rgb24
 FATE_TESTS += fate-lmlm4-demux
-fate-lmlm4-demux: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/lmlm4/LMLM4_CIFat30fps.divx -t 3 -acodec copy -vcodec copy -f framecrc -
+fate-lmlm4-demux: CMD = framecrc  -i $(SAMPLES)/lmlm4/LMLM4_CIFat30fps.divx -t 3 -acodec copy -vcodec copy
 FATE_TESTS += fate-loco-rgb
-fate-loco-rgb: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/loco/pig-loco-rgb.avi -f framecrc -
+fate-loco-rgb: CMD = framecrc  -i $(SAMPLES)/loco/pig-loco-rgb.avi
 FATE_TESTS += fate-loco-yuy2
-fate-loco-yuy2: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/loco/pig-loco-0.avi -f framecrc -
+fate-loco-yuy2: CMD = framecrc  -i $(SAMPLES)/loco/pig-loco-0.avi
 FATE_TESTS += fate-lossless-appleaudio
-fate-lossless-appleaudio: CMD =  $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/lossless-audio/inside.m4a -f s16le - | do_md5sum | cut -c-32
+fate-lossless-appleaudio: CMD = md5  -i $(SAMPLES)/lossless-audio/inside.m4a -f s16le
 FATE_TESTS += fate-lossless-meridianaudio
-fate-lossless-meridianaudio: CMD =  $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/lossless-audio/luckynight-partial.mlp -f s16le - | do_md5sum | cut -c-32
+fate-lossless-meridianaudio: CMD = md5  -i $(SAMPLES)/lossless-audio/luckynight-partial.mlp -f s16le
 FATE_TESTS += fate-lossless-monkeysaudio
-fate-lossless-monkeysaudio: CMD =  $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/lossless-audio/luckynight-partial.ape -f s16le - | do_md5sum | cut -c-32
+fate-lossless-monkeysaudio: CMD = md5  -i $(SAMPLES)/lossless-audio/luckynight-partial.ape -f s16le
 FATE_TESTS += fate-lossless-shortenaudio
-fate-lossless-shortenaudio: CMD =  $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/lossless-audio/luckynight-partial.shn -f s16le - | do_md5sum | cut -c-32
+fate-lossless-shortenaudio: CMD = md5  -i $(SAMPLES)/lossless-audio/luckynight-partial.shn -f s16le
 FATE_TESTS += fate-lossless-tta
-fate-lossless-tta: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/lossless-audio/inside.tta -f crc -
+fate-lossless-tta: CMD = crc  -i $(SAMPLES)/lossless-audio/inside.tta
 FATE_TESTS += fate-lossless-wavpackaudio
-fate-lossless-wavpackaudio: CMD =  $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/lossless-audio/luckynight-partial.wv -f s16le - | do_md5sum | cut -c-32
+fate-lossless-wavpackaudio: CMD = md5  -i $(SAMPLES)/lossless-audio/luckynight-partial.wv -f s16le
 FATE_TESTS += fate-maxis-xa
-fate-maxis-xa: CMD =  $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/maxis-xa/SC2KBUG.XA -f s16le - | do_md5sum | cut -c-32
+fate-maxis-xa: CMD = md5  -i $(SAMPLES)/maxis-xa/SC2KBUG.XA -f s16le
 FATE_TESTS += fate-mimic
-fate-mimic: CMD = $$BUILD_PATH/ffmpeg -idct simple -i $$SAMPLES_PATH/mimic/mimic2-womanloveffmpeg.cam -vsync 0 -f framecrc -
+fate-mimic: CMD = framecrc  -idct simple -i $(SAMPLES)/mimic/mimic2-womanloveffmpeg.cam -vsync 0
 FATE_TESTS += fate-motionpixels
-fate-motionpixels: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/motion-pixels/INTRO-partial.MVI -an -pix_fmt rgb24 -f framecrc -
+fate-motionpixels: CMD = framecrc  -i $(SAMPLES)/motion-pixels/INTRO-partial.MVI -an -pix_fmt rgb24
 FATE_TESTS += fate-mpc7-demux
-fate-mpc7-demux: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/musepack/inside-mp7.mpc -acodec copy -f crc -
+fate-mpc7-demux: CMD = crc  -i $(SAMPLES)/musepack/inside-mp7.mpc -acodec copy
 FATE_TESTS += fate-mpc8-demux
-fate-mpc8-demux: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/musepack/inside-mp8.mpc -acodec copy -f crc -
-FATE_TESTS += fate-mpeg4-als-conformance-00
-fate-mpeg4-als-conformance-00: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/lossless-audio/als_00_2ch48k16b.mp4 -f crc -
-FATE_TESTS += fate-mpeg4-als-conformance-01
-fate-mpeg4-als-conformance-01: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/lossless-audio/als_01_2ch48k16b.mp4 -f crc -
-FATE_TESTS += fate-mpeg4-als-conformance-02
-fate-mpeg4-als-conformance-02: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/lossless-audio/als_02_2ch48k16b.mp4 -f crc -
-FATE_TESTS += fate-mpeg4-als-conformance-03
-fate-mpeg4-als-conformance-03: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/lossless-audio/als_03_2ch48k16b.mp4 -f crc -
-FATE_TESTS += fate-mpeg4-als-conformance-04
-fate-mpeg4-als-conformance-04: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/lossless-audio/als_04_2ch48k16b.mp4 -f crc -
-FATE_TESTS += fate-mpeg4-als-conformance-05
-fate-mpeg4-als-conformance-05: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/lossless-audio/als_05_2ch48k16b.mp4 -f crc -
+fate-mpc8-demux: CMD = crc  -i $(SAMPLES)/musepack/inside-mp8.mpc -acodec copy
 FATE_TESTS += fate-msrle-8bit
-fate-msrle-8bit: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/msrle/Search-RLE.avi -pix_fmt rgb24 -f framecrc -
+fate-msrle-8bit: CMD = framecrc  -i $(SAMPLES)/msrle/Search-RLE.avi -pix_fmt rgb24
 FATE_TESTS += fate-msvideo1-16bit
-fate-msvideo1-16bit: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/cram/clock-cram16.avi -pix_fmt rgb24 -f framecrc -
+fate-msvideo1-16bit: CMD = framecrc  -i $(SAMPLES)/cram/clock-cram16.avi -pix_fmt rgb24
 FATE_TESTS += fate-msvideo1-8bit
-fate-msvideo1-8bit: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/cram/skating.avi -t 1 -pix_fmt rgb24 -f framecrc -
+fate-msvideo1-8bit: CMD = framecrc  -i $(SAMPLES)/cram/skating.avi -t 1 -pix_fmt rgb24
 FATE_TESTS += fate-mszh
-fate-mszh: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/lcl/mszh-1frame.avi -f framecrc -
+fate-mszh: CMD = framecrc  -i $(SAMPLES)/lcl/mszh-1frame.avi
 FATE_TESTS += fate-mtv
-fate-mtv: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/mtv/comedian_auto-partial.mtv -acodec copy -pix_fmt rgb24 -f framecrc -
+fate-mtv: CMD = framecrc  -i $(SAMPLES)/mtv/comedian_auto-partial.mtv -acodec copy -pix_fmt rgb24
 FATE_TESTS += fate-mxf-demux
-fate-mxf-demux: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/mxf/C0023S01.mxf -acodec copy -vcodec copy -f framecrc -
+fate-mxf-demux: CMD = framecrc  -i $(SAMPLES)/mxf/C0023S01.mxf -acodec copy -vcodec copy
 FATE_TESTS += fate-nc-demux
-fate-nc-demux: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/nc-camera/nc-sample-partial -vcodec copy -f framecrc -
+fate-nc-demux: CMD = framecrc  -i $(SAMPLES)/nc-camera/nc-sample-partial -vcodec copy
 FATE_TESTS += fate-nsv-demux
-fate-nsv-demux: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/nsv/witchblade-51kbps.nsv -t 6 -vcodec copy -acodec copy -f framecrc -
+fate-nsv-demux: CMD = framecrc  -i $(SAMPLES)/nsv/witchblade-51kbps.nsv -t 6 -vcodec copy -acodec copy
 FATE_TESTS += fate-nuv
-fate-nuv: CMD = $$BUILD_PATH/ffmpeg -idct simple -i $$SAMPLES_PATH/nuv/Today.nuv -f framecrc -
+fate-nuv: CMD = framecrc  -idct simple -i $(SAMPLES)/nuv/Today.nuv
 FATE_TESTS += fate-oma-demux
-fate-oma-demux: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/oma/01-Untitled-partial.oma -acodec copy -f crc -
+fate-oma-demux: CMD = crc  -i $(SAMPLES)/oma/01-Untitled-partial.oma -acodec copy
 FATE_TESTS += fate-pcm_dvd
-fate-pcm_dvd: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/pcm-dvd/coolitnow-partial.vob -vn -f framecrc -
+fate-pcm_dvd: CMD = framecrc  -i $(SAMPLES)/pcm-dvd/coolitnow-partial.vob -vn
 FATE_TESTS += fate-psx-str
-fate-psx-str: CMD = $$BUILD_PATH/ffmpeg -idct simple -i $$SAMPLES_PATH/psx-str/descent-partial.str -f framecrc -
+fate-psx-str: CMD = framecrc  -i $(SAMPLES)/psx-str/descent-partial.str
+FATE_TESTS += fate-psx-str-v3-mdec
+fate-psx-str-v3-mdec: CMD = framecrc  -i $(SAMPLES)/psx-str/abc000_cut.str -an
+FATE_TESTS += fate-psx-str-v3-adpcm_xa
+fate-psx-str-v3-adpcm_xa: CMD = framecrc  -i $(SAMPLES)/psx-str/abc000_cut.str -vn
 FATE_TESTS += fate-ptx
-fate-ptx: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/ptx/_113kw_pic.ptx -pix_fmt rgb24 -f framecrc -
+fate-ptx: CMD = framecrc  -i $(SAMPLES)/ptx/_113kw_pic.ptx -pix_fmt rgb24
 FATE_TESTS += fate-pva-demux
-fate-pva-demux: CMD = $$BUILD_PATH/ffmpeg -idct simple -i $$SAMPLES_PATH/pva/PVA_test-partial.pva -t 0.6 -acodec copy -f framecrc -
+fate-pva-demux: CMD = framecrc  -idct simple -i $(SAMPLES)/pva/PVA_test-partial.pva -t 0.6 -acodec copy
 FATE_TESTS += fate-qcp-demux
-fate-qcp-demux: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/qcp/0036580847.QCP -acodec copy -f crc -
+fate-qcp-demux: CMD = crc  -i $(SAMPLES)/qcp/0036580847.QCP -acodec copy
 FATE_TESTS += fate-qpeg
-fate-qpeg: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/qpeg/Clock.avi -an -pix_fmt rgb24  -f framecrc -
+fate-qpeg: CMD = framecrc  -i $(SAMPLES)/qpeg/Clock.avi -an -pix_fmt rgb24
 FATE_TESTS += fate-qt-alaw-mono
-fate-qt-alaw-mono: CMD =  $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/qt-surge-suite/surge-1-16-B-alaw.mov -f s16le - | do_md5sum | cut -c-32
+fate-qt-alaw-mono: CMD = md5  -i $(SAMPLES)/qt-surge-suite/surge-1-16-B-alaw.mov -f s16le
 FATE_TESTS += fate-qt-alaw-stereo
-fate-qt-alaw-stereo: CMD =  $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/qt-surge-suite/surge-2-16-B-alaw.mov -f s16le - | do_md5sum | cut -c-32
+fate-qt-alaw-stereo: CMD = md5  -i $(SAMPLES)/qt-surge-suite/surge-2-16-B-alaw.mov -f s16le
 FATE_TESTS += fate-qt-ima4-mono
-fate-qt-ima4-mono: CMD =  $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/qt-surge-suite/surge-1-16-B-ima4.mov -f s16le - | do_md5sum | cut -c-32
+fate-qt-ima4-mono: CMD = md5  -i $(SAMPLES)/qt-surge-suite/surge-1-16-B-ima4.mov -f s16le
 FATE_TESTS += fate-qt-ima4-stereo
-fate-qt-ima4-stereo: CMD =  $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/qt-surge-suite/surge-2-16-B-ima4.mov -f s16le - | do_md5sum | cut -c-32
+fate-qt-ima4-stereo: CMD = md5  -i $(SAMPLES)/qt-surge-suite/surge-2-16-B-ima4.mov -f s16le
 FATE_TESTS += fate-qt-mac3-mono
-fate-qt-mac3-mono: CMD =  $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/qt-surge-suite/surge-1-8-MAC3.mov -f s16le - | do_md5sum | cut -c-32
+fate-qt-mac3-mono: CMD = md5  -i $(SAMPLES)/qt-surge-suite/surge-1-8-MAC3.mov -f s16le
 FATE_TESTS += fate-qt-mac3-stereo
-fate-qt-mac3-stereo: CMD =  $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/qt-surge-suite/surge-2-8-MAC3.mov -f s16le - | do_md5sum | cut -c-32
+fate-qt-mac3-stereo: CMD = md5  -i $(SAMPLES)/qt-surge-suite/surge-2-8-MAC3.mov -f s16le
 FATE_TESTS += fate-qt-mac6-mono
-fate-qt-mac6-mono: CMD =  $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/qt-surge-suite/surge-1-8-MAC6.mov -f s16le - | do_md5sum | cut -c-32
+fate-qt-mac6-mono: CMD = md5  -i $(SAMPLES)/qt-surge-suite/surge-1-8-MAC6.mov -f s16le
 FATE_TESTS += fate-qt-mac6-stereo
-fate-qt-mac6-stereo: CMD =  $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/qt-surge-suite/surge-2-8-MAC6.mov -f s16le - | do_md5sum | cut -c-32
+fate-qt-mac6-stereo: CMD = md5  -i $(SAMPLES)/qt-surge-suite/surge-2-8-MAC6.mov -f s16le
 FATE_TESTS += fate-qt-msadpcm-stereo
-fate-qt-msadpcm-stereo: CMD =  $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/qt-surge-suite/surge-2-16-L-ms02.mov -f s16le - | do_md5sum | cut -c-32
+fate-qt-msadpcm-stereo: CMD = md5  -i $(SAMPLES)/qt-surge-suite/surge-2-16-L-ms02.mov -f s16le
 FATE_TESTS += fate-qt-msimaadpcm-stereo
-fate-qt-msimaadpcm-stereo: CMD =  $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/qt-surge-suite/surge-2-16-L-ms11.mov -f s16le - | do_md5sum | cut -c-32
+fate-qt-msimaadpcm-stereo: CMD = md5  -i $(SAMPLES)/qt-surge-suite/surge-2-16-L-ms11.mov -f s16le
 FATE_TESTS += fate-qt-rawpcm-16bit-stereo-signed-be
-fate-qt-rawpcm-16bit-stereo-signed-be: CMD =  $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/qt-surge-suite/surge-2-16-B-twos.mov -f s16le - | do_md5sum | cut -c-32
+fate-qt-rawpcm-16bit-stereo-signed-be: CMD = md5  -i $(SAMPLES)/qt-surge-suite/surge-2-16-B-twos.mov -f s16le
 FATE_TESTS += fate-qt-rawpcm-16bit-stereo-signed-le
-fate-qt-rawpcm-16bit-stereo-signed-le: CMD =  $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/qt-surge-suite/surge-2-16-L-sowt.mov -f s16le - | do_md5sum | cut -c-32
+fate-qt-rawpcm-16bit-stereo-signed-le: CMD = md5  -i $(SAMPLES)/qt-surge-suite/surge-2-16-L-sowt.mov -f s16le
 FATE_TESTS += fate-qt-rawpcm-8bit-mono-unsigned
-fate-qt-rawpcm-8bit-mono-unsigned: CMD =  $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/qt-surge-suite/surge-1-8-raw.mov -f s16le - | do_md5sum | cut -c-32
+fate-qt-rawpcm-8bit-mono-unsigned: CMD = md5  -i $(SAMPLES)/qt-surge-suite/surge-1-8-raw.mov -f s16le
 FATE_TESTS += fate-qt-rawpcm-8bit-stereo-unsigned
-fate-qt-rawpcm-8bit-stereo-unsigned: CMD =  $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/qt-surge-suite/surge-2-8-raw.mov -f s16le - | do_md5sum | cut -c-32
+fate-qt-rawpcm-8bit-stereo-unsigned: CMD = md5  -i $(SAMPLES)/qt-surge-suite/surge-2-8-raw.mov -f s16le
 FATE_TESTS += fate-qt-ulaw-mono
-fate-qt-ulaw-mono: CMD =  $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/qt-surge-suite/surge-1-16-B-ulaw.mov -f s16le - | do_md5sum | cut -c-32
+fate-qt-ulaw-mono: CMD = md5  -i $(SAMPLES)/qt-surge-suite/surge-1-16-B-ulaw.mov -f s16le
 FATE_TESTS += fate-qt-ulaw-stereo
-fate-qt-ulaw-stereo: CMD =  $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/qt-surge-suite/surge-2-16-B-ulaw.mov -f s16le - | do_md5sum | cut -c-32
+fate-qt-ulaw-stereo: CMD = md5  -i $(SAMPLES)/qt-surge-suite/surge-2-16-B-ulaw.mov -f s16le
 FATE_TESTS += fate-qtrle-16bit
-fate-qtrle-16bit: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/qtrle/mr-cork-rle.mov -pix_fmt rgb24 -f framecrc -
+fate-qtrle-16bit: CMD = framecrc  -i $(SAMPLES)/qtrle/mr-cork-rle.mov -pix_fmt rgb24
 FATE_TESTS += fate-qtrle-1bit
-fate-qtrle-1bit: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/qtrle/Animation-Monochrome.mov -f framecrc -
+fate-qtrle-1bit: CMD = framecrc  -i $(SAMPLES)/qtrle/Animation-Monochrome.mov
 FATE_TESTS += fate-qtrle-24bit
-fate-qtrle-24bit: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/qtrle/aletrek-rle.mov -vsync 0 -f framecrc -
+fate-qtrle-24bit: CMD = framecrc  -i $(SAMPLES)/qtrle/aletrek-rle.mov -vsync 0
 FATE_TESTS += fate-qtrle-2bit
-fate-qtrle-2bit: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/qtrle/Animation-4Greys.mov -pix_fmt rgb24 -f framecrc -
+fate-qtrle-2bit: CMD = framecrc  -i $(SAMPLES)/qtrle/Animation-4Greys.mov -pix_fmt rgb24
 FATE_TESTS += fate-qtrle-32bit
-fate-qtrle-32bit: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/qtrle/ultra_demo_720_480_32bpp_rle.mov -pix_fmt rgb24 -f framecrc -
+fate-qtrle-32bit: CMD = framecrc  -i $(SAMPLES)/qtrle/ultra_demo_720_480_32bpp_rle.mov -pix_fmt rgb24
 FATE_TESTS += fate-qtrle-4bit
-fate-qtrle-4bit: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/qtrle/Animation-16Greys.mov -pix_fmt rgb24 -an -f framecrc -
+fate-qtrle-4bit: CMD = framecrc  -i $(SAMPLES)/qtrle/Animation-16Greys.mov -pix_fmt rgb24 -an
 FATE_TESTS += fate-qtrle-8bit
-fate-qtrle-8bit: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/qtrle/criticalpath-credits.mov -vsync 0 -pix_fmt rgb24 -an -f framecrc -
+fate-qtrle-8bit: CMD = framecrc  -i $(SAMPLES)/qtrle/criticalpath-credits.mov -vsync 0 -pix_fmt rgb24 -an
 FATE_TESTS += fate-quickdraw
-fate-quickdraw: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/quickdraw/Airplane.mov -pix_fmt rgb24 -f framecrc -
+fate-quickdraw: CMD = framecrc  -i $(SAMPLES)/quickdraw/Airplane.mov -pix_fmt rgb24
 FATE_TESTS += fate-real-14_4
-fate-real-14_4: CMD =  $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/real/ra3_in_rm_file.rm -f s16le - | do_md5sum | cut -c-32
+fate-real-14_4: CMD = md5  -i $(SAMPLES)/real/ra3_in_rm_file.rm -f s16le
 FATE_TESTS += fate-real-rv40
-fate-real-rv40: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/real/spygames-2MB.rmvb -t 10 -an -f framecrc -
+fate-real-rv40: CMD = framecrc  -i $(SAMPLES)/real/spygames-2MB.rmvb -t 10 -an
 FATE_TESTS += fate-redcode-demux
-fate-redcode-demux: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/r3d/4MB-sample.r3d -vcodec copy -acodec copy -f framecrc -
+fate-redcode-demux: CMD = framecrc  -i $(SAMPLES)/r3d/4MB-sample.r3d -vcodec copy -acodec copy
 FATE_TESTS += fate-rl2
-fate-rl2: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/rl2/Z4915300.RL2 -pix_fmt rgb24 -an -vsync 0 -f framecrc -
+fate-rl2: CMD = framecrc  -i $(SAMPLES)/rl2/Z4915300.RL2 -pix_fmt rgb24 -an -vsync 0
 FATE_TESTS += fate-rpza
-fate-rpza: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/rpza/rpza2.mov -t 2 -pix_fmt rgb24 -f framecrc -
+fate-rpza: CMD = framecrc  -i $(SAMPLES)/rpza/rpza2.mov -t 2 -pix_fmt rgb24
 FATE_TESTS += fate-sierra-audio
-fate-sierra-audio: CMD =  $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/sol/lsl7sample.sol -f s16le - | do_md5sum | cut -c-32
+fate-sierra-audio: CMD = md5  -i $(SAMPLES)/sol/lsl7sample.sol -f s16le
 FATE_TESTS += fate-sierra-vmd
-fate-sierra-vmd: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/vmd/12.vmd -vsync 0 -pix_fmt rgb24 -f framecrc -
+fate-sierra-vmd: CMD = framecrc  -i $(SAMPLES)/vmd/12.vmd -vsync 0 -pix_fmt rgb24
 FATE_TESTS += fate-siff
-fate-siff: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/SIFF/INTRO_B.VB -t 3 -pix_fmt rgb24 -f framecrc -
+fate-siff: CMD = framecrc  -i $(SAMPLES)/SIFF/INTRO_B.VB -t 3 -pix_fmt rgb24
 FATE_TESTS += fate-smacker
-fate-smacker: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/smacker/wetlogo.smk -pix_fmt rgb24 -f framecrc -
+fate-smacker: CMD = framecrc  -i $(SAMPLES)/smacker/wetlogo.smk -pix_fmt rgb24
 FATE_TESTS += fate-smc
-fate-smc: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/smc/cass_schi.qt -vsync 0 -pix_fmt rgb24 -f framecrc -
+fate-smc: CMD = framecrc  -i $(SAMPLES)/smc/cass_schi.qt -vsync 0 -pix_fmt rgb24
 FATE_TESTS += fate-sp5x
-fate-sp5x: CMD = $$BUILD_PATH/ffmpeg -idct simple -i $$SAMPLES_PATH/sp5x/sp5x_problem.avi -f framecrc -
+fate-sp5x: CMD = framecrc  -idct simple -i $(SAMPLES)/sp5x/sp5x_problem.avi
+FATE_TESTS += fate-sub-srt
+fate-sub-srt: CMD = md5  -i $(SAMPLES)/sub/SubRip_capability_tester.srt -f ass
 FATE_TESTS += fate-sunraster-1bit-raw
-fate-sunraster-1bit-raw: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/sunraster/lena-1bit-raw.sun -f framecrc -
+fate-sunraster-1bit-raw: CMD = framecrc  -i $(SAMPLES)/sunraster/lena-1bit-raw.sun
 FATE_TESTS += fate-sunraster-1bit-rle
-fate-sunraster-1bit-rle: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/sunraster/lena-1bit-rle.sun -f framecrc -
+fate-sunraster-1bit-rle: CMD = framecrc  -i $(SAMPLES)/sunraster/lena-1bit-rle.sun
 FATE_TESTS += fate-sunraster-24bit-raw
-fate-sunraster-24bit-raw: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/sunraster/lena-24bit-raw.sun -f framecrc -
+fate-sunraster-24bit-raw: CMD = framecrc  -i $(SAMPLES)/sunraster/lena-24bit-raw.sun
 FATE_TESTS += fate-sunraster-24bit-rle
-fate-sunraster-24bit-rle: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/sunraster/lena-24bit-rle.sun -f framecrc -
+fate-sunraster-24bit-rle: CMD = framecrc  -i $(SAMPLES)/sunraster/lena-24bit-rle.sun
 FATE_TESTS += fate-sunraster-8bit-raw
-fate-sunraster-8bit-raw: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/sunraster/lena-8bit-raw.sun -pix_fmt rgb24 -f framecrc -
+fate-sunraster-8bit-raw: CMD = framecrc  -i $(SAMPLES)/sunraster/lena-8bit-raw.sun -pix_fmt rgb24
 FATE_TESTS += fate-sunraster-8bit-rle
-fate-sunraster-8bit-rle: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/sunraster/lena-8bit-rle.sun -pix_fmt rgb24 -f framecrc -
+fate-sunraster-8bit-rle: CMD = framecrc  -i $(SAMPLES)/sunraster/lena-8bit-rle.sun -pix_fmt rgb24
 FATE_TESTS += fate-svq1
-fate-svq1: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/svq1/marymary-shackles.mov -an -t 10 -f framecrc -
+fate-svq1: CMD = framecrc  -i $(SAMPLES)/svq1/marymary-shackles.mov -an -t 10
 FATE_TESTS += fate-svq3
-fate-svq3: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/svq3/Vertical400kbit.sorenson3.mov -t 6 -an -f framecrc -
+fate-svq3: CMD = framecrc  -i $(SAMPLES)/svq3/Vertical400kbit.sorenson3.mov -t 6 -an
 FATE_TESTS += fate-thp-mjpeg-adpcm
-fate-thp-mjpeg-adpcm: CMD = $$BUILD_PATH/ffmpeg -idct simple -i $$SAMPLES_PATH/thp/pikmin2-opening1-partial.thp -f framecrc -
+fate-thp-mjpeg-adpcm: CMD = framecrc  -idct simple -i $(SAMPLES)/thp/pikmin2-opening1-partial.thp
 FATE_TESTS += fate-tiertex-seq
-fate-tiertex-seq: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/tiertex-seq/Gameover.seq -pix_fmt rgb24 -f framecrc -
+fate-tiertex-seq: CMD = framecrc  -i $(SAMPLES)/tiertex-seq/Gameover.seq -pix_fmt rgb24
 FATE_TESTS += fate-tmv
-fate-tmv: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/tmv/pop-partial.tmv -pix_fmt rgb24 -f framecrc -
+fate-tmv: CMD = framecrc  -i $(SAMPLES)/tmv/pop-partial.tmv -pix_fmt rgb24
+FATE_TESTS += fate-truemotion1-15
+fate-truemotion1-15: CMD = framecrc -i $(SAMPLES)/duck/phant2-940.duk -pix_fmt rgb24
+FATE_TESTS += fate-truemotion1-24
+fate-truemotion1-24: CMD = framecrc -i $(SAMPLES)/duck/sonic3dblast_intro-partial.avi -pix_fmt rgb24
 FATE_TESTS += fate-tscc-15bit
-fate-tscc-15bit: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/tscc/oneminute.avi -t 15 -pix_fmt rgb24 -f framecrc -
+fate-tscc-15bit: CMD = framecrc  -i $(SAMPLES)/tscc/oneminute.avi -t 15 -pix_fmt rgb24
 FATE_TESTS += fate-tscc-32bit
-fate-tscc-32bit: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/tscc/2004-12-17-uebung9-partial.avi -pix_fmt rgb24 -an -f framecrc -
+fate-tscc-32bit: CMD = framecrc  -i $(SAMPLES)/tscc/2004-12-17-uebung9-partial.avi -pix_fmt rgb24 -an
 FATE_TESTS += fate-ulti
-fate-ulti: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/ulti/hit12w.avi -an -f framecrc -
+fate-ulti: CMD = framecrc  -i $(SAMPLES)/ulti/hit12w.avi -an
 FATE_TESTS += fate-v210
-fate-v210: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/v210/v210_720p-partial.avi -pix_fmt yuv422p16be -an -f framecrc -
+fate-v210: CMD = framecrc  -i $(SAMPLES)/v210/v210_720p-partial.avi -pix_fmt yuv422p16be -an
 FATE_TESTS += fate-vc1
-fate-vc1: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/vc1/SA00040.vc1 -f framecrc -
+fate-vc1: CMD = framecrc  -i $(SAMPLES)/vc1/SA00040.vc1
 FATE_TESTS += fate-vcr1
-fate-vcr1: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/vcr1/VCR1test.avi -an -f framecrc -
+fate-vcr1: CMD = framecrc  -i $(SAMPLES)/vcr1/VCR1test.avi -an
 FATE_TESTS += fate-video-xl
-fate-video-xl: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/vixl/pig-vixl.avi -f framecrc -
+fate-video-xl: CMD = framecrc  -i $(SAMPLES)/vixl/pig-vixl.avi
 FATE_TESTS += fate-vmnc-16bit
-fate-vmnc-16bit: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/VMnc/test.avi -pix_fmt rgb24 -f framecrc -
+fate-vmnc-16bit: CMD = framecrc  -i $(SAMPLES)/VMnc/test.avi -pix_fmt rgb24
 FATE_TESTS += fate-vmnc-32bit
-fate-vmnc-32bit: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/VMnc/VS2k5DebugDemo-01-partial.avi -pix_fmt rgb24 -f framecrc -
+fate-vmnc-32bit: CMD = framecrc  -i $(SAMPLES)/VMnc/VS2k5DebugDemo-01-partial.avi -pix_fmt rgb24
 FATE_TESTS += fate-vp5
-fate-vp5: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/vp5/potter512-400-partial.avi -an -f framecrc -
+fate-vp5: CMD = framecrc  -i $(SAMPLES)/vp5/potter512-400-partial.avi -an
 FATE_TESTS += fate-vp6a
-fate-vp6a: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/flash-vp6/300x180-Scr-f8-056alpha.flv -f framecrc -
+fate-vp6a: CMD = framecrc  -i $(SAMPLES)/flash-vp6/300x180-Scr-f8-056alpha.flv
 FATE_TESTS += fate-vp6f
-fate-vp6f: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/flash-vp6/clip1024.flv -f framecrc -
+fate-vp6f: CMD = framecrc  -i $(SAMPLES)/flash-vp6/clip1024.flv
 FATE_TESTS += fate-vqa-cc
-fate-vqa-cc: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/vqa/cc-demo1-partial.vqa -pix_fmt rgb24 -f framecrc -
+fate-vqa-cc: CMD = framecrc  -i $(SAMPLES)/vqa/cc-demo1-partial.vqa -pix_fmt rgb24
 FATE_TESTS += fate-vqf-demux
-fate-vqf-demux: CMD =  $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/vqf/achterba.vqf -acodec copy -f framecrc - | do_md5sum | cut -c-32
+fate-vqf-demux: CMD = md5  -i $(SAMPLES)/vqf/achterba.vqf -acodec copy -f framecrc
 FATE_TESTS += fate-w64
-fate-w64: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/w64/w64-pcm16.w64 -f crc -
+fate-w64: CMD = crc  -i $(SAMPLES)/w64/w64-pcm16.w64
 FATE_TESTS += fate-wc3movie-xan
-fate-wc3movie-xan: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/wc3movie/SC_32-part.MVE -pix_fmt rgb24 -f framecrc -
+fate-wc3movie-xan: CMD = framecrc  -i $(SAMPLES)/wc3movie/SC_32-part.MVE -pix_fmt rgb24
 FATE_TESTS += fate-westwood-aud
-fate-westwood-aud: CMD =  $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/westwood-aud/excellent.aud -f s16le - | do_md5sum | cut -c-32
+fate-westwood-aud: CMD = md5  -i $(SAMPLES)/westwood-aud/excellent.aud -f s16le
 FATE_TESTS += fate-wnv1
-fate-wnv1: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/wnv1/wnv1-codec.avi -an -f framecrc -
+fate-wnv1: CMD = framecrc  -i $(SAMPLES)/wnv1/wnv1-codec.avi -an
 FATE_TESTS += fate-xan-dpcm
-fate-xan-dpcm: CMD =  $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/wc4-xan/wc4_2.avi -vn -f s16le - | do_md5sum | cut -c-32
+fate-xan-dpcm: CMD = md5  -i $(SAMPLES)/wc4-xan/wc4_2.avi -vn -f s16le
 FATE_TESTS += fate-zlib
-fate-zlib: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/lcl/zlib-1frame.avi -f framecrc -
+fate-zlib: CMD = framecrc  -i $(SAMPLES)/lcl/zlib-1frame.avi
 FATE_TESTS += fate-zmbv-15bit
-fate-zmbv-15bit: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/zmbv/zmbv_15bit.avi -pix_fmt rgb24 -t 25 -f framecrc -
+fate-zmbv-15bit: CMD = framecrc  -i $(SAMPLES)/zmbv/zmbv_15bit.avi -pix_fmt rgb24 -t 25
 FATE_TESTS += fate-zmbv-16bit
-fate-zmbv-16bit: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/zmbv/zmbv_16bit.avi -pix_fmt rgb24 -t 25 -f framecrc -
+fate-zmbv-16bit: CMD = framecrc  -i $(SAMPLES)/zmbv/zmbv_16bit.avi -pix_fmt rgb24 -t 25
 FATE_TESTS += fate-zmbv-32bit
-fate-zmbv-32bit: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/zmbv/zmbv_32bit.avi -pix_fmt rgb24 -t 25 -f framecrc -
+fate-zmbv-32bit: CMD = framecrc  -i $(SAMPLES)/zmbv/zmbv_32bit.avi -pix_fmt rgb24 -t 25
 FATE_TESTS += fate-zmbv-8bit
-fate-zmbv-8bit: CMD = $$BUILD_PATH/ffmpeg -i $$SAMPLES_PATH/zmbv/wc2_001-partial.avi -an -pix_fmt rgb24 -f framecrc -
+fate-zmbv-8bit: CMD = framecrc  -i $(SAMPLES)/zmbv/wc2_001-partial.avi -an -pix_fmt rgb24
diff --git a/tests/fate.sh b/tests/fate.sh
new file mode 100755
index 0000000..6f0e0ff
--- /dev/null
+++ b/tests/fate.sh
@@ -0,0 +1,112 @@
+#! /bin/sh
+
+config=$1
+
+die(){
+    echo "$@"
+    exit 1
+}
+
+test -r "$config"  || die "usage: fate.sh <config>"
+
+workdir=$(cd $(dirname $config) && pwd)
+make=make
+tar='tar c'
+
+. "$config"
+
+test -n "$slot"    || die "slot not specified"
+test -n "$repo"    || die "repo not specified"
+test -d "$samples" || die "samples location not specified"
+
+lock(){
+    lock=$1/fate.lock
+    (set -C; exec >$lock) 2>/dev/null || return
+    trap 'rm $lock' EXIT
+}
+
+checkout(){
+    case "$repo" in
+        file:*|/*) src="${repo#file:}"      ;;
+        git:*)     git clone "$repo" "$src" ;;
+    esac
+}
+
+update()(
+    cd ${src} || return
+    case "$repo" in
+        git:*) git pull ;;
+    esac
+)
+
+configure()(
+    cd ${build} || return
+    ${src}/configure                                                    \
+        --prefix="${inst}"                                              \
+        --samples="${samples}"                                          \
+        --enable-gpl                                                    \
+        ${arch:+--arch=$arch}                                           \
+        ${cpu:+--cpu="$cpu"}                                            \
+        ${cross_prefix:+--cross-prefix="$cross_prefix"}                 \
+        ${cc:+--cc="$cc"}                                               \
+        ${target_os:+--target-os="$target_os"}                          \
+        ${sysroot:+--sysroot="$sysroot"}                                \
+        ${target_exec:+--target-exec="$target_exec"}                    \
+        ${target_path:+--target-path="$target_path"}                    \
+        ${extra_cflags:+--extra-cflags="$extra_cflags"}                 \
+        ${extra_ldflags:+--extra-ldflags="$extra_ldflags"}              \
+        ${extra_libs:+--extra-libs="$extra_libs"}                       \
+        ${extra_conf}
+)
+
+compile()(
+    cd ${build} || return
+    ${make} ${makeopts} && ${make} install
+)
+
+fate()(
+    cd ${build} || return
+    ${make} ${makeopts} -k fate
+)
+
+clean(){
+    rm -r ${build} ${inst}
+}
+
+report(){
+    date=$(date -u +%Y%m%d%H%M%S)
+    echo "fate:0:${date}:${slot}:${version}:$1:$2" >report
+    cat ${build}/config.fate ${build}/tests/data/fate/*.rep >>report
+    test -n "$fate_recv" && $tar report *.log | gzip | $fate_recv
+}
+
+fail(){
+    report "$@"
+    clean
+    exit
+}
+
+mkdir -p ${workdir} || die "Error creating ${workdir}"
+lock ${workdir}     || die "${workdir} locked"
+cd ${workdir}       || die "cd ${workdir} failed"
+
+src=${workdir}/src
+build=${workdir}/build
+inst=${workdir}/install
+
+test -d "$src" && update || checkout || die "Error fetching source"
+
+cd ${workdir}
+
+version=$(${src}/version.sh ${src})
+test "$version" = "$(cat version-$slot 2>/dev/null)" && exit 0
+echo ${version} >version-$slot
+
+rm -rf "${build}" *.log
+mkdir -p ${build}
+
+configure >configure.log 2>&1 || fail $? "error configuring"
+compile   >compile.log   2>&1 || fail $? "error compiling"
+fate      >test.log      2>&1 || fail $? "error testing"
+report 0 success
+clean
diff --git a/tests/fate/aac.mak b/tests/fate/aac.mak
new file mode 100644
index 0000000..41df4f6
--- /dev/null
+++ b/tests/fate/aac.mak
@@ -0,0 +1,28 @@
+FATE_AAC += fate-aac-al04_44
+fate-aac-al04_44: CMD = pcm -i $(SAMPLES)/aac/al04_44.mp4
+fate-aac-al04_44: REF = $(SAMPLES)/aac/al04_44.s16
+
+FATE_AAC += fate-aac-al07_96
+fate-aac-al07_96: CMD = pcm -i $(SAMPLES)/aac/al07_96.mp4
+fate-aac-al07_96: REF = $(SAMPLES)/aac/al07_96.s16
+
+FATE_AAC += fate-aac-am00_88
+fate-aac-am00_88: CMD = pcm -i $(SAMPLES)/aac/am00_88.mp4
+fate-aac-am00_88: REF = $(SAMPLES)/aac/am00_88.s16
+
+FATE_AAC += fate-aac-al_sbr_hq_cm_48_2
+fate-aac-al_sbr_hq_cm_48_2: CMD = pcm -i $(SAMPLES)/aac/al_sbr_cm_48_2.mp4
+fate-aac-al_sbr_hq_cm_48_2: REF = $(SAMPLES)/aac/al_sbr_hq_cm_48_2.s16
+
+FATE_AAC += fate-aac-al_sbr_ps_06_ur
+fate-aac-al_sbr_ps_06_ur: CMD = pcm -i $(SAMPLES)/aac/al_sbr_ps_06_new.mp4
+fate-aac-al_sbr_ps_06_ur: REF = $(SAMPLES)/aac/al_sbr_ps_06_ur.s16
+
+FATE_AAC += fate-aac-latm_000000001180bc60
+fate-aac-latm_000000001180bc60: CMD = pcm -i $(SAMPLES)/aac/latm_000000001180bc60.mpg
+fate-aac-latm_000000001180bc60: REF = $(SAMPLES)/aac/latm_000000001180bc60.s16
+
+FATE_TESTS += $(FATE_AAC)
+fate-aac: $(FATE_AAC)
+$(FATE_AAC): CMP = oneoff
+$(FATE_AAC): FUZZ = 2
diff --git a/tests/fate/als.mak b/tests/fate/als.mak
new file mode 100644
index 0000000..2674034
--- /dev/null
+++ b/tests/fate/als.mak
@@ -0,0 +1,11 @@
+ALS_SUITE = 00 01 02 03 04 05
+
+define FATE_ALS_SUITE
+FATE_ALS += fate-mpeg4-als-conformance-$(1)
+fate-mpeg4-als-conformance-$(1): CMD = crc -i $(SAMPLES)/lossless-audio/als_$(1)_2ch48k16b.mp4
+endef
+
+$(foreach N,$(ALS_SUITE),$(eval $(call FATE_ALS_SUITE,$(N))))
+
+FATE_TESTS += $(FATE_ALS)
+fate-als: $(FATE_ALS)
diff --git a/tests/fate/fft.mak b/tests/fate/fft.mak
new file mode 100644
index 0000000..042a7bf
--- /dev/null
+++ b/tests/fate/fft.mak
@@ -0,0 +1,31 @@
+FATE_FFT = fate-fft   fate-ifft   \
+           fate-mdct  fate-imdct  \
+           fate-rdft  fate-irdft  \
+           fate-dct1d fate-idct1d
+
+fate-fft:    CMD = run libavcodec/fft-test
+fate-ifft:   CMD = run libavcodec/fft-test -i
+fate-mdct:   CMD = run libavcodec/fft-test -m
+fate-imdct:  CMD = run libavcodec/fft-test -m -i
+fate-rdft:   CMD = run libavcodec/fft-test -r
+fate-irdft:  CMD = run libavcodec/fft-test -r -i
+fate-dct1d:  CMD = run libavcodec/fft-test -d
+fate-idct1d: CMD = run libavcodec/fft-test -d -i
+
+fate-fft-test: $(FATE_FFT)
+$(FATE_FFT): libavcodec/fft-test$(EXESUF)
+$(FATE_FFT): REF = /dev/null
+
+FATE_FFT_FIXED = fate-fft-fixed  fate-ifft-fixed  \
+                 fate-mdct-fixed fate-imdct-fixed
+
+fate-fft-fixed:   CMD = run libavcodec/fft-fixed-test
+fate-ifft-fixed:  CMD = run libavcodec/fft-fixed-test -i
+fate-mdct-fixed:  CMD = run libavcodec/fft-fixed-test -m
+fate-imdct-fixed: CMD = run libavcodec/fft-fixed-test -m -i
+
+fate-fft-fixed-test: $(FATE_FFT_FIXED)
+$(FATE_FFT_FIXED): libavcodec/fft-fixed-test$(EXESUF)
+$(FATE_FFT_FIXED): REF = /dev/null
+
+FATE_TESTS += $(FATE_FFT) $(FATE_FFT_FIXED)
diff --git a/tests/fate/h264.mak b/tests/fate/h264.mak
new file mode 100644
index 0000000..259e1e0
--- /dev/null
+++ b/tests/fate/h264.mak
@@ -0,0 +1,343 @@
+FATE_H264 = aud_mw_e                                                    \
+            ba1_ft_c                                                    \
+            ba1_sony_d                                                  \
+            ba2_sony_f                                                  \
+            ba3_sva_c                                                   \
+            ba_mw_d                                                     \
+            bamq1_jvc_c                                                 \
+            bamq2_jvc_c                                                 \
+            banm_mw_d                                                   \
+            basqp1_sony_c                                               \
+            caba1_sony_d                                                \
+            caba1_sva_b                                                 \
+            caba2_sony_e                                                \
+            caba2_sva_b                                                 \
+            caba3_sony_c                                                \
+            caba3_sva_b                                                 \
+            caba3_toshiba_e                                             \
+            cabac_mot_fld0_full                                         \
+            cabac_mot_frm0_full                                         \
+            cabac_mot_mbaff0_full                                       \
+            cabac_mot_picaff0_full                                      \
+            cabaci3_sony_b                                              \
+            cabast3_sony_e                                              \
+            cabastbr3_sony_b                                            \
+            cabref3_sand_d                                              \
+            cacqp3_sony_d                                               \
+            cafi1_sva_c                                                 \
+            cama1_sony_c                                                \
+            cama1_toshiba_b                                             \
+            cama1_vtc_c                                                 \
+            cama2_vtc_b                                                 \
+            cama3_sand_e                                                \
+            cama3_vtc_b                                                 \
+            camaci3_sony_c                                              \
+            camanl1_toshiba_b                                           \
+            camanl2_toshiba_b                                           \
+            camanl3_sand_e                                              \
+            camasl3_sony_b                                              \
+            camp_mot_mbaff_l30                                          \
+            camp_mot_mbaff_l31                                          \
+            canl1_sony_e                                                \
+            canl1_sva_b                                                 \
+            canl1_toshiba_g                                             \
+            canl2_sony_e                                                \
+            canl2_sva_b                                                 \
+            canl3_sony_c                                                \
+            canl3_sva_b                                                 \
+            canl4_sva_b                                                 \
+            canlma2_sony_c                                              \
+            canlma3_sony_c                                              \
+            capa1_toshiba_b                                             \
+            capama3_sand_f                                              \
+            capcm1_sand_e                                               \
+            capcmnl1_sand_e                                             \
+            capm3_sony_d                                                \
+            caqp1_sony_b                                                \
+            cavlc_mot_fld0_full_b                                       \
+            cavlc_mot_frm0_full_b                                       \
+            cavlc_mot_mbaff0_full_b                                     \
+            cavlc_mot_picaff0_full_b                                    \
+            cawp1_toshiba_e                                             \
+            cawp5_toshiba_e                                             \
+            ci1_ft_b                                                    \
+            ci_mw_d                                                     \
+            cvbs3_sony_c                                                \
+            cvcanlma2_sony_c                                            \
+            cvfi1_sony_d                                                \
+            cvfi1_sva_c                                                 \
+            cvfi2_sony_h                                                \
+            cvfi2_sva_c                                                 \
+            cvma1_sony_d                                                \
+            cvma1_toshiba_b                                             \
+            cvmanl1_toshiba_b                                           \
+            cvmanl2_toshiba_b                                           \
+            cvmapaqp3_sony_e                                            \
+            cvmaqp2_sony_g                                              \
+            cvmaqp3_sony_d                                              \
+            cvmp_mot_fld_l30_b                                          \
+            cvmp_mot_frm_l31_b                                          \
+            cvnlfi1_sony_c                                              \
+            cvnlfi2_sony_h                                              \
+            cvpa1_toshiba_b                                             \
+            cvpcmnl1_sva_c                                              \
+            cvpcmnl2_sva_c                                              \
+            cvwp1_toshiba_e                                             \
+            cvwp2_toshiba_e                                             \
+            cvwp3_toshiba_e                                             \
+            cvwp5_toshiba_e                                             \
+            fi1_sony_e                                                  \
+            frext-alphaconformanceg                                     \
+            frext-bcrm_freh10                                           \
+            frext-brcm_freh11                                           \
+            frext-brcm_freh3                                            \
+            frext-brcm_freh4                                            \
+            frext-brcm_freh5                                            \
+            frext-brcm_freh8                                            \
+            frext-brcm_freh9                                            \
+            frext-freh12_b                                              \
+            frext-freh1_b                                               \
+            frext-freh2_b                                               \
+            frext-freh6                                                 \
+            frext-freh7_b                                               \
+            frext-frext01_jvc_d                                         \
+            frext-frext02_jvc_c                                         \
+            frext-frext1_panasonic_c                                    \
+            frext-frext2_panasonic_b                                    \
+            frext-frext3_panasonic_d                                    \
+            frext-frext4_panasonic_a                                    \
+            frext-frext_mmco4_sony_b                                    \
+            frext-hcaff1_hhi_b                                          \
+            frext-hcafr1_hhi_c                                          \
+            frext-hcafr2_hhi_a                                          \
+            frext-hcafr3_hhi_a                                          \
+            frext-hcafr4_hhi_a                                          \
+            frext-hcamff1_hhi_b                                         \
+            frext-hpca_brcm_c                                           \
+            frext-hpcadq_brcm_b                                         \
+            frext-hpcafl_bcrm_c                                         \
+            frext-hpcaflnl_bcrm_c                                       \
+            frext-hpcalq_brcm_b                                         \
+            frext-hpcamapalq_bcrm_b                                     \
+            frext-hpcamolq_brcm_b                                       \
+            frext-hpcanl_brcm_c                                         \
+            frext-hpcaq2lq_brcm_b                                       \
+            frext-hpcv_brcm_a                                           \
+            frext-hpcvfl_bcrm_a                                         \
+            frext-hpcvflnl_bcrm_a                                       \
+            frext-hpcvmolq_brcm_b                                       \
+            frext-hpcvnl_brcm_a                                         \
+            hcbp2_hhi_a                                                 \
+            hcmp1_hhi_a                                                 \
+            ls_sva_d                                                    \
+            midr_mw_d                                                   \
+            mps_mw_a                                                    \
+            mr1_bt_a                                                    \
+            mr1_mw_a                                                    \
+            mr2_mw_a                                                    \
+            mr2_tandberg_e                                              \
+            mr3_tandberg_b                                              \
+            mr4_tandberg_c                                              \
+            mr5_tandberg_c                                              \
+            mr6_bt_b                                                    \
+            mr7_bt_b                                                    \
+            mr8_bt_b                                                    \
+            mr9_bt_b                                                    \
+            mv1_brcm_d                                                  \
+            nl1_sony_d                                                  \
+            nl2_sony_h                                                  \
+            nl3_sva_e                                                   \
+            nlmq1_jvc_c                                                 \
+            nlmq2_jvc_c                                                 \
+            nrf_mw_e                                                    \
+            sharp_mp_field_1_b                                          \
+            sharp_mp_field_2_b                                          \
+            sharp_mp_field_3_b                                          \
+            sharp_mp_paff_1r2                                           \
+            sharp_mp_paff_2r                                            \
+            sl1_sva_b                                                   \
+            sva_ba1_b                                                   \
+            sva_ba2_d                                                   \
+            sva_base_b                                                  \
+            sva_cl1_e                                                   \
+            sva_fm1_e                                                   \
+            sva_nl1_b                                                   \
+            sva_nl2_e                                                   \
+
+FATE_H264  := $(FATE_H264:%=fate-h264-conformance-%)                    \
+              fate-h264-interlace-crop                                  \
+              fate-h264-lossless                                        \
+              fate-h264-extreme-plane-pred                              \
+
+FATE_TESTS += $(FATE_H264)
+fate-h264: $(FATE_H264)
+
+fate-h264-conformance-aud_mw_e: CMD = framecrc  -i $(SAMPLES)/h264-conformance/AUD_MW_E.264
+fate-h264-conformance-ba1_ft_c: CMD = framecrc  -i $(SAMPLES)/h264-conformance/BA1_FT_C.264
+fate-h264-conformance-ba1_sony_d: CMD = framecrc  -i $(SAMPLES)/h264-conformance/BA1_Sony_D.jsv
+fate-h264-conformance-ba2_sony_f: CMD = framecrc  -i $(SAMPLES)/h264-conformance/BA2_Sony_F.jsv
+fate-h264-conformance-ba3_sva_c: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/BA3_SVA_C.264
+fate-h264-conformance-ba_mw_d: CMD = framecrc  -i $(SAMPLES)/h264-conformance/BA_MW_D.264
+fate-h264-conformance-bamq1_jvc_c: CMD = framecrc  -i $(SAMPLES)/h264-conformance/BAMQ1_JVC_C.264
+fate-h264-conformance-bamq2_jvc_c: CMD = framecrc  -i $(SAMPLES)/h264-conformance/BAMQ2_JVC_C.264
+fate-h264-conformance-banm_mw_d: CMD = framecrc  -i $(SAMPLES)/h264-conformance/BANM_MW_D.264
+fate-h264-conformance-basqp1_sony_c: CMD = framecrc  -i $(SAMPLES)/h264-conformance/BASQP1_Sony_C.jsv
+fate-h264-conformance-caba1_sony_d: CMD = framecrc  -i $(SAMPLES)/h264-conformance/CABA1_Sony_D.jsv
+fate-h264-conformance-caba1_sva_b: CMD = framecrc  -i $(SAMPLES)/h264-conformance/CABA1_SVA_B.264
+fate-h264-conformance-caba2_sony_e: CMD = framecrc  -i $(SAMPLES)/h264-conformance/CABA2_Sony_E.jsv
+fate-h264-conformance-caba2_sva_b: CMD = framecrc  -i $(SAMPLES)/h264-conformance/CABA2_SVA_B.264
+fate-h264-conformance-caba3_sony_c: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/CABA3_Sony_C.jsv
+fate-h264-conformance-caba3_sva_b: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/CABA3_SVA_B.264
+fate-h264-conformance-caba3_toshiba_e: CMD = framecrc  -i $(SAMPLES)/h264-conformance/CABA3_TOSHIBA_E.264
+fate-h264-conformance-cabac_mot_fld0_full: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/camp_mot_fld0_full.26l
+fate-h264-conformance-cabac_mot_frm0_full: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/camp_mot_frm0_full.26l
+fate-h264-conformance-cabac_mot_mbaff0_full: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/camp_mot_mbaff0_full.26l
+fate-h264-conformance-cabac_mot_picaff0_full: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/camp_mot_picaff0_full.26l
+fate-h264-conformance-cabaci3_sony_b: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/CABACI3_Sony_B.jsv
+fate-h264-conformance-cabast3_sony_e: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/CABAST3_Sony_E.jsv
+fate-h264-conformance-cabastbr3_sony_b: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/CABASTBR3_Sony_B.jsv
+fate-h264-conformance-cabref3_sand_d: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/CABREF3_Sand_D.264
+fate-h264-conformance-cacqp3_sony_d: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/CACQP3_Sony_D.jsv
+fate-h264-conformance-cafi1_sva_c: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/CAFI1_SVA_C.264
+fate-h264-conformance-cama1_sony_c: CMD = framecrc  -i $(SAMPLES)/h264-conformance/CAMA1_Sony_C.jsv
+fate-h264-conformance-cama1_toshiba_b: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/CAMA1_TOSHIBA_B.264
+fate-h264-conformance-cama1_vtc_c: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/cama1_vtc_c.avc
+fate-h264-conformance-cama2_vtc_b: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/cama2_vtc_b.avc
+fate-h264-conformance-cama3_sand_e: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/CAMA3_Sand_E.264
+fate-h264-conformance-cama3_vtc_b: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/cama3_vtc_b.avc
+fate-h264-conformance-camaci3_sony_c: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/CAMACI3_Sony_C.jsv
+fate-h264-conformance-camanl1_toshiba_b: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/CAMANL1_TOSHIBA_B.264
+fate-h264-conformance-camanl2_toshiba_b: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/CAMANL2_TOSHIBA_B.264
+fate-h264-conformance-camanl3_sand_e: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/CAMANL3_Sand_E.264
+fate-h264-conformance-camasl3_sony_b: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/CAMASL3_Sony_B.jsv
+fate-h264-conformance-camp_mot_mbaff_l30: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/CAMP_MOT_MBAFF_L30.26l
+fate-h264-conformance-camp_mot_mbaff_l31: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/CAMP_MOT_MBAFF_L31.26l
+fate-h264-conformance-canl1_sony_e: CMD = framecrc  -i $(SAMPLES)/h264-conformance/CANL1_Sony_E.jsv
+fate-h264-conformance-canl1_sva_b: CMD = framecrc  -i $(SAMPLES)/h264-conformance/CANL1_SVA_B.264
+fate-h264-conformance-canl1_toshiba_g: CMD = framecrc  -i $(SAMPLES)/h264-conformance/CANL1_TOSHIBA_G.264
+fate-h264-conformance-canl2_sony_e: CMD = framecrc  -i $(SAMPLES)/h264-conformance/CANL2_Sony_E.jsv
+fate-h264-conformance-canl2_sva_b: CMD = framecrc  -i $(SAMPLES)/h264-conformance/CANL2_SVA_B.264
+fate-h264-conformance-canl3_sony_c: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/CANL3_Sony_C.jsv
+fate-h264-conformance-canl3_sva_b: CMD = framecrc  -i $(SAMPLES)/h264-conformance/CANL3_SVA_B.264
+fate-h264-conformance-canl4_sva_b: CMD = framecrc  -i $(SAMPLES)/h264-conformance/CANL4_SVA_B.264
+fate-h264-conformance-canlma2_sony_c: CMD = framecrc  -i $(SAMPLES)/h264-conformance/CANLMA2_Sony_C.jsv
+fate-h264-conformance-canlma3_sony_c: CMD = framecrc  -i $(SAMPLES)/h264-conformance/CANLMA3_Sony_C.jsv
+fate-h264-conformance-capa1_toshiba_b: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/CAPA1_TOSHIBA_B.264
+fate-h264-conformance-capama3_sand_f: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/CAPAMA3_Sand_F.264
+fate-h264-conformance-capcm1_sand_e: CMD = framecrc  -i $(SAMPLES)/h264-conformance/CAPCM1_Sand_E.264
+fate-h264-conformance-capcmnl1_sand_e: CMD = framecrc  -i $(SAMPLES)/h264-conformance/CAPCMNL1_Sand_E.264
+fate-h264-conformance-capm3_sony_d: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/CAPM3_Sony_D.jsv
+fate-h264-conformance-caqp1_sony_b: CMD = framecrc  -i $(SAMPLES)/h264-conformance/CAQP1_Sony_B.jsv
+fate-h264-conformance-cavlc_mot_fld0_full_b: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/cvmp_mot_fld0_full_B.26l
+fate-h264-conformance-cavlc_mot_frm0_full_b: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/cvmp_mot_frm0_full_B.26l
+fate-h264-conformance-cavlc_mot_mbaff0_full_b: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/cvmp_mot_mbaff0_full_B.26l
+fate-h264-conformance-cavlc_mot_picaff0_full_b: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/cvmp_mot_picaff0_full_B.26l
+fate-h264-conformance-cawp1_toshiba_e: CMD = framecrc  -i $(SAMPLES)/h264-conformance/CAWP1_TOSHIBA_E.264
+fate-h264-conformance-cawp5_toshiba_e: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/CAWP5_TOSHIBA_E.264
+fate-h264-conformance-ci1_ft_b: CMD = framecrc  -i $(SAMPLES)/h264-conformance/CI1_FT_B.264
+fate-h264-conformance-ci_mw_d: CMD = framecrc  -i $(SAMPLES)/h264-conformance/CI_MW_D.264
+fate-h264-conformance-cvbs3_sony_c: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/CVBS3_Sony_C.jsv
+fate-h264-conformance-cvcanlma2_sony_c: CMD = framecrc  -i $(SAMPLES)/h264-conformance/CVCANLMA2_Sony_C.jsv
+fate-h264-conformance-cvfi1_sony_d: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/CVFI1_Sony_D.jsv
+fate-h264-conformance-cvfi1_sva_c: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/CVFI1_SVA_C.264
+fate-h264-conformance-cvfi2_sony_h: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/CVFI2_Sony_H.jsv
+fate-h264-conformance-cvfi2_sva_c: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/CVFI2_SVA_C.264
+fate-h264-conformance-cvma1_sony_d: CMD = framecrc  -i $(SAMPLES)/h264-conformance/CVMA1_Sony_D.jsv
+fate-h264-conformance-cvma1_toshiba_b: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/CVMA1_TOSHIBA_B.264
+fate-h264-conformance-cvmanl1_toshiba_b: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/CVMANL1_TOSHIBA_B.264
+fate-h264-conformance-cvmanl2_toshiba_b: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/CVMANL2_TOSHIBA_B.264
+fate-h264-conformance-cvmapaqp3_sony_e: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/CVMAPAQP3_Sony_E.jsv
+fate-h264-conformance-cvmaqp2_sony_g: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/CVMAQP2_Sony_G.jsv
+fate-h264-conformance-cvmaqp3_sony_d: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/CVMAQP3_Sony_D.jsv
+fate-h264-conformance-cvmp_mot_fld_l30_b: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/CVMP_MOT_FLD_L30_B.26l
+fate-h264-conformance-cvmp_mot_frm_l31_b: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/CVMP_MOT_FRM_L31_B.26l
+fate-h264-conformance-cvnlfi1_sony_c: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/CVNLFI1_Sony_C.jsv
+fate-h264-conformance-cvnlfi2_sony_h: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/CVNLFI2_Sony_H.jsv
+fate-h264-conformance-cvpa1_toshiba_b: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/CVPA1_TOSHIBA_B.264
+fate-h264-conformance-cvpcmnl1_sva_c: CMD = framecrc  -i $(SAMPLES)/h264-conformance/CVPCMNL1_SVA_C.264
+fate-h264-conformance-cvpcmnl2_sva_c: CMD = framecrc  -i $(SAMPLES)/h264-conformance/CVPCMNL2_SVA_C.264
+fate-h264-conformance-cvwp1_toshiba_e: CMD = framecrc  -i $(SAMPLES)/h264-conformance/CVWP1_TOSHIBA_E.264
+fate-h264-conformance-cvwp2_toshiba_e: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/CVWP2_TOSHIBA_E.264
+fate-h264-conformance-cvwp3_toshiba_e: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/CVWP3_TOSHIBA_E.264
+fate-h264-conformance-cvwp5_toshiba_e: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/CVWP5_TOSHIBA_E.264
+fate-h264-conformance-fi1_sony_e: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/FI1_Sony_E.jsv
+fate-h264-conformance-frext-alphaconformanceg: CMD = framecrc  -i $(SAMPLES)/h264-conformance/FRext/test8b43.264
+fate-h264-conformance-frext-bcrm_freh10: CMD = framecrc  -i $(SAMPLES)/h264-conformance/FRext/freh10.264 -vsync 0
+fate-h264-conformance-frext-brcm_freh11: CMD = framecrc  -i $(SAMPLES)/h264-conformance/FRext/freh11.264 -vsync 0
+fate-h264-conformance-frext-brcm_freh3: CMD = framecrc  -i $(SAMPLES)/h264-conformance/FRext/freh3.264
+fate-h264-conformance-frext-brcm_freh4: CMD = framecrc  -i $(SAMPLES)/h264-conformance/FRext/freh4.264 -vsync 0
+fate-h264-conformance-frext-brcm_freh5: CMD = framecrc  -i $(SAMPLES)/h264-conformance/FRext/freh5.264
+fate-h264-conformance-frext-brcm_freh8: CMD = framecrc  -i $(SAMPLES)/h264-conformance/FRext/freh8.264
+fate-h264-conformance-frext-brcm_freh9: CMD = framecrc  -i $(SAMPLES)/h264-conformance/FRext/freh9.264
+fate-h264-conformance-frext-freh12_b: CMD = framecrc  -i $(SAMPLES)/h264-conformance/FRext/Freh12_B.264
+fate-h264-conformance-frext-freh1_b: CMD = framecrc  -i $(SAMPLES)/h264-conformance/FRext/Freh1_B.264
+fate-h264-conformance-frext-freh2_b: CMD = framecrc  -i $(SAMPLES)/h264-conformance/FRext/Freh2_B.264
+fate-h264-conformance-frext-freh6: CMD = framecrc  -i $(SAMPLES)/h264-conformance/FRext/freh6.264 -vsync 0
+fate-h264-conformance-frext-freh7_b: CMD = framecrc  -i $(SAMPLES)/h264-conformance/FRext/Freh7_B.264 -vsync 0
+fate-h264-conformance-frext-frext01_jvc_d: CMD = framecrc  -i $(SAMPLES)/h264-conformance/FRext/FREXT01_JVC_D.264
+fate-h264-conformance-frext-frext02_jvc_c: CMD = framecrc  -i $(SAMPLES)/h264-conformance/FRext/FREXT02_JVC_C.264
+fate-h264-conformance-frext-frext1_panasonic_c: CMD = framecrc  -i $(SAMPLES)/h264-conformance/FRext/FRExt1_Panasonic.avc
+fate-h264-conformance-frext-frext2_panasonic_b: CMD = framecrc  -i $(SAMPLES)/h264-conformance/FRext/FRExt2_Panasonic.avc -vsync 0
+fate-h264-conformance-frext-frext3_panasonic_d: CMD = framecrc  -i $(SAMPLES)/h264-conformance/FRext/FRExt3_Panasonic.avc
+fate-h264-conformance-frext-frext4_panasonic_a: CMD = framecrc  -i $(SAMPLES)/h264-conformance/FRext/FRExt4_Panasonic.avc
+fate-h264-conformance-frext-frext_mmco4_sony_b: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/FRext/FRExt_MMCO4_Sony_B.264
+fate-h264-conformance-frext-hcaff1_hhi_b: CMD = framecrc  -i $(SAMPLES)/h264-conformance/FRext/HCAFF1_HHI.264
+fate-h264-conformance-frext-hcafr1_hhi_c: CMD = framecrc  -i $(SAMPLES)/h264-conformance/FRext/HCAFR1_HHI.264
+fate-h264-conformance-frext-hcafr2_hhi_a: CMD = framecrc  -i $(SAMPLES)/h264-conformance/FRext/HCAFR2_HHI.264
+fate-h264-conformance-frext-hcafr3_hhi_a: CMD = framecrc  -i $(SAMPLES)/h264-conformance/FRext/HCAFR3_HHI.264
+fate-h264-conformance-frext-hcafr4_hhi_a: CMD = framecrc  -i $(SAMPLES)/h264-conformance/FRext/HCAFR4_HHI.264
+fate-h264-conformance-frext-hcamff1_hhi_b: CMD = framecrc  -i $(SAMPLES)/h264-conformance/FRext/HCAMFF1_HHI.264
+fate-h264-conformance-frext-hpca_brcm_c: CMD = framecrc  -i $(SAMPLES)/h264-conformance/FRext/HPCA_BRCM_C.264
+fate-h264-conformance-frext-hpcadq_brcm_b: CMD = framecrc  -i $(SAMPLES)/h264-conformance/FRext/HPCADQ_BRCM_B.264
+fate-h264-conformance-frext-hpcafl_bcrm_c: CMD = framecrc  -i $(SAMPLES)/h264-conformance/FRext/HPCAFL_BRCM_C.264 -vsync 0
+fate-h264-conformance-frext-hpcaflnl_bcrm_c: CMD = framecrc  -i $(SAMPLES)/h264-conformance/FRext/HPCAFLNL_BRCM_C.264 -vsync 0
+fate-h264-conformance-frext-hpcalq_brcm_b: CMD = framecrc  -i $(SAMPLES)/h264-conformance/FRext/HPCALQ_BRCM_B.264
+fate-h264-conformance-frext-hpcamapalq_bcrm_b: CMD = framecrc  -i $(SAMPLES)/h264-conformance/FRext/HPCAMAPALQ_BRCM_B.264 -vsync 0
+fate-h264-conformance-frext-hpcamolq_brcm_b: CMD = framecrc  -i $(SAMPLES)/h264-conformance/FRext/HPCAMOLQ_BRCM_B.264
+fate-h264-conformance-frext-hpcanl_brcm_c: CMD = framecrc  -i $(SAMPLES)/h264-conformance/FRext/HPCANL_BRCM_C.264
+fate-h264-conformance-frext-hpcaq2lq_brcm_b: CMD = framecrc  -i $(SAMPLES)/h264-conformance/FRext/HPCAQ2LQ_BRCM_B.264
+fate-h264-conformance-frext-hpcv_brcm_a: CMD = framecrc  -i $(SAMPLES)/h264-conformance/FRext/HPCV_BRCM_A.264
+fate-h264-conformance-frext-hpcvfl_bcrm_a: CMD = framecrc  -i $(SAMPLES)/h264-conformance/FRext/HPCVFL_BRCM_A.264 -vsync 0
+fate-h264-conformance-frext-hpcvflnl_bcrm_a: CMD = framecrc  -i $(SAMPLES)/h264-conformance/FRext/HPCVFLNL_BRCM_A.264 -vsync 0
+fate-h264-conformance-frext-hpcvmolq_brcm_b: CMD = framecrc  -i $(SAMPLES)/h264-conformance/FRext/HPCVMOLQ_BRCM_B.264
+fate-h264-conformance-frext-hpcvnl_brcm_a: CMD = framecrc  -i $(SAMPLES)/h264-conformance/FRext/HPCVNL_BRCM_A.264
+fate-h264-conformance-hcbp2_hhi_a: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/HCBP2_HHI_A.264
+fate-h264-conformance-hcmp1_hhi_a: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/HCMP1_HHI_A.264
+fate-h264-conformance-ls_sva_d: CMD = framecrc  -i $(SAMPLES)/h264-conformance/LS_SVA_D.264
+fate-h264-conformance-midr_mw_d: CMD = framecrc  -i $(SAMPLES)/h264-conformance/MIDR_MW_D.264
+fate-h264-conformance-mps_mw_a: CMD = framecrc  -i $(SAMPLES)/h264-conformance/MPS_MW_A.264
+fate-h264-conformance-mr1_bt_a: CMD = framecrc  -i $(SAMPLES)/h264-conformance/MR1_BT_A.h264
+fate-h264-conformance-mr1_mw_a: CMD = framecrc  -i $(SAMPLES)/h264-conformance/MR1_MW_A.264
+fate-h264-conformance-mr2_mw_a: CMD = framecrc  -i $(SAMPLES)/h264-conformance/MR2_MW_A.264
+fate-h264-conformance-mr2_tandberg_e: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/MR2_TANDBERG_E.264
+fate-h264-conformance-mr3_tandberg_b: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/MR3_TANDBERG_B.264
+fate-h264-conformance-mr4_tandberg_c: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/MR4_TANDBERG_C.264
+fate-h264-conformance-mr5_tandberg_c: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/MR5_TANDBERG_C.264
+fate-h264-conformance-mr6_bt_b: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/MR6_BT_B.h264
+fate-h264-conformance-mr7_bt_b: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/MR7_BT_B.h264
+fate-h264-conformance-mr8_bt_b: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/MR8_BT_B.h264
+fate-h264-conformance-mr9_bt_b: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/MR9_BT_B.h264
+fate-h264-conformance-mv1_brcm_d: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/src19td.IBP.264
+fate-h264-conformance-nl1_sony_d: CMD = framecrc  -i $(SAMPLES)/h264-conformance/NL1_Sony_D.jsv
+fate-h264-conformance-nl2_sony_h: CMD = framecrc  -i $(SAMPLES)/h264-conformance/NL2_Sony_H.jsv
+fate-h264-conformance-nl3_sva_e: CMD = framecrc  -i $(SAMPLES)/h264-conformance/NL3_SVA_E.264
+fate-h264-conformance-nlmq1_jvc_c: CMD = framecrc  -i $(SAMPLES)/h264-conformance/NLMQ1_JVC_C.264
+fate-h264-conformance-nlmq2_jvc_c: CMD = framecrc  -i $(SAMPLES)/h264-conformance/NLMQ2_JVC_C.264
+fate-h264-conformance-nrf_mw_e: CMD = framecrc  -i $(SAMPLES)/h264-conformance/NRF_MW_E.264
+fate-h264-conformance-sharp_mp_field_1_b: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/Sharp_MP_Field_1_B.jvt
+fate-h264-conformance-sharp_mp_field_2_b: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/Sharp_MP_Field_2_B.jvt
+fate-h264-conformance-sharp_mp_field_3_b: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/Sharp_MP_Field_3_B.jvt
+fate-h264-conformance-sharp_mp_paff_1r2: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/Sharp_MP_PAFF_1r2.jvt
+fate-h264-conformance-sharp_mp_paff_2r: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/Sharp_MP_PAFF_2.jvt
+fate-h264-conformance-sl1_sva_b: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/SL1_SVA_B.264
+fate-h264-conformance-sva_ba1_b: CMD = framecrc  -i $(SAMPLES)/h264-conformance/SVA_BA1_B.264
+fate-h264-conformance-sva_ba2_d: CMD = framecrc  -i $(SAMPLES)/h264-conformance/SVA_BA2_D.264
+fate-h264-conformance-sva_base_b: CMD = framecrc  -i $(SAMPLES)/h264-conformance/SVA_Base_B.264
+fate-h264-conformance-sva_cl1_e: CMD = framecrc  -i $(SAMPLES)/h264-conformance/SVA_CL1_E.264
+fate-h264-conformance-sva_fm1_e: CMD = framecrc  -i $(SAMPLES)/h264-conformance/SVA_FM1_E.264
+fate-h264-conformance-sva_nl1_b: CMD = framecrc  -i $(SAMPLES)/h264-conformance/SVA_NL1_B.264
+fate-h264-conformance-sva_nl2_e: CMD = framecrc  -i $(SAMPLES)/h264-conformance/SVA_NL2_E.264
+
+fate-h264-interlace-crop: CMD = framecrc  -vframes 3 -i $(SAMPLES)/h264/interlaced_crop.mp4
+fate-h264-lossless: CMD = framecrc -i $(SAMPLES)/h264/lossless.h264
+fate-h264-extreme-plane-pred: CMD = framemd5 -strict 1 -vsync 0 -i $(SAMPLES)/h264/extreme-plane-pred.h264
diff --git a/tests/fate/mp3.mak b/tests/fate/mp3.mak
new file mode 100644
index 0000000..859a4f3
--- /dev/null
+++ b/tests/fate/mp3.mak
@@ -0,0 +1,39 @@
+FATE_MP3 += fate-mp3-float-conf-compl
+fate-mp3-float-conf-compl: CMD = pcm -acodec mp3float -i $(SAMPLES)/mp3-conformance/compl.bit
+fate-mp3-float-conf-compl: CMP = stddev
+fate-mp3-float-conf-compl: REF = $(SAMPLES)/mp3-conformance/compl.pcm
+
+FATE_MP3 += fate-mp3-float-conf-he_32khz
+fate-mp3-float-conf-he_32khz: CMD = pcm -acodec mp3float  -fs 343296 -i $(SAMPLES)/mp3-conformance/he_32khz.bit
+fate-mp3-float-conf-he_32khz: CMP = stddev
+fate-mp3-float-conf-he_32khz: REF = $(SAMPLES)/mp3-conformance/he_32khz.pcm
+
+FATE_MP3 += fate-mp3-float-conf-he_44khz
+fate-mp3-float-conf-he_44khz: CMD = pcm -acodec mp3float -fs 942336 -i $(SAMPLES)/mp3-conformance/he_44khz.bit
+fate-mp3-float-conf-he_44khz: CMP = stddev
+fate-mp3-float-conf-he_44khz: REF = $(SAMPLES)/mp3-conformance/he_44khz.pcm
+
+FATE_MP3 += fate-mp3-float-conf-he_48khz
+fate-mp3-float-conf-he_48khz: CMD = pcm -acodec mp3float -fs 343296 -i $(SAMPLES)/mp3-conformance/he_48khz.bit
+fate-mp3-float-conf-he_48khz: CMP = stddev
+fate-mp3-float-conf-he_48khz: REF = $(SAMPLES)/mp3-conformance/he_48khz.pcm
+
+FATE_MP3 += fate-mp3-float-conf-hecommon
+fate-mp3-float-conf-hecommon: CMD = pcm -acodec mp3float -fs 133632 -i $(SAMPLES)/mp3-conformance/hecommon.bit
+fate-mp3-float-conf-hecommon: CMP = stddev
+fate-mp3-float-conf-hecommon: REF = $(SAMPLES)/mp3-conformance/hecommon.pcm
+
+FATE_MP3 += fate-mp3-float-conf-si
+fate-mp3-float-conf-si: CMD = pcm -acodec mp3float -fs 269568 -i $(SAMPLES)/mp3-conformance/si.bit
+fate-mp3-float-conf-si: CMP = stddev
+fate-mp3-float-conf-si: REF = $(SAMPLES)/mp3-conformance/si.pcm
+
+FATE_MP3 += fate-mp3-float-conf-si_block
+fate-mp3-float-conf-si_block: CMD = pcm -acodec mp3float -fs 145152 -i $(SAMPLES)/mp3-conformance/si_block.bit
+fate-mp3-float-conf-si_block: CMP = stddev
+fate-mp3-float-conf-si_block: REF = $(SAMPLES)/mp3-conformance/si_block.pcm
+
+FATE_TESTS += $(FATE_MP3)
+fate-mp3: $(FATE_MP3)
+$(FATE_MP3): CMP = stddev
+$(FATE_MP3): FUZZ = 0.07
diff --git a/tests/fate/vorbis.mak b/tests/fate/vorbis.mak
new file mode 100644
index 0000000..5452b74
--- /dev/null
+++ b/tests/fate/vorbis.mak
@@ -0,0 +1,80 @@
+FATE_VORBIS += fate-vorbis-1
+fate-vorbis-1: CMD = pcm -i $(SAMPLES)/vorbis/1.0.1-test_small.ogg
+fate-vorbis-1: REF = $(SAMPLES)/vorbis/1.0.1-test_small.pcm
+
+FATE_VORBIS += fate-vorbis-2
+fate-vorbis-2: CMD = pcm -i $(SAMPLES)/vorbis/1.0-test_small.ogg
+fate-vorbis-2: REF = $(SAMPLES)/vorbis/1.0-test_small.pcm
+
+FATE_VORBIS += fate-vorbis-3
+fate-vorbis-3: CMD = pcm -i $(SAMPLES)/vorbis/beta3-test_small.ogg
+fate-vorbis-3: REF = $(SAMPLES)/vorbis/beta3-test_small.pcm
+
+FATE_VORBIS += fate-vorbis-4
+fate-vorbis-4: CMD = pcm -i $(SAMPLES)/vorbis/beta4-test_small.ogg
+fate-vorbis-4: REF = $(SAMPLES)/vorbis/beta4-test_small.pcm
+
+FATE_VORBIS += fate-vorbis-5
+fate-vorbis-5: CMD = pcm -i $(SAMPLES)/vorbis/chain-test1_small.ogg
+fate-vorbis-5: REF = $(SAMPLES)/vorbis/chain-test1_small.pcm
+
+FATE_VORBIS += fate-vorbis-6
+fate-vorbis-6: CMD = pcm -i $(SAMPLES)/vorbis/chain-test2_small.ogg
+fate-vorbis-6: REF = $(SAMPLES)/vorbis/chain-test2_small.pcm
+
+FATE_VORBIS += fate-vorbis-7
+fate-vorbis-7: CMD = pcm -i $(SAMPLES)/vorbis/highrate-test_small.ogg
+fate-vorbis-7: REF = $(SAMPLES)/vorbis/highrate-test_small.pcm
+
+FATE_VORBIS += fate-vorbis-8
+fate-vorbis-8: CMD = pcm -i $(SAMPLES)/vorbis/lsp-test2_small.ogg
+fate-vorbis-8: REF = $(SAMPLES)/vorbis/lsp-test2_small.pcm
+
+FATE_VORBIS += fate-vorbis-9
+fate-vorbis-9: CMD = pcm -i $(SAMPLES)/vorbis/lsp-test3_small.ogg
+fate-vorbis-9: REF = $(SAMPLES)/vorbis/lsp-test3_small.pcm
+
+FATE_VORBIS += fate-vorbis-10
+fate-vorbis-10: CMD = pcm -i $(SAMPLES)/vorbis/lsp-test4_small.ogg
+fate-vorbis-10: REF = $(SAMPLES)/vorbis/lsp-test4_small.pcm
+
+FATE_VORBIS += fate-vorbis-11
+fate-vorbis-11: CMD = pcm -i $(SAMPLES)/vorbis/lsp-test_small.ogg
+fate-vorbis-11: REF = $(SAMPLES)/vorbis/lsp-test_small.pcm
+
+FATE_VORBIS += fate-vorbis-12
+fate-vorbis-12: CMD = pcm -i $(SAMPLES)/vorbis/mono_small.ogg
+fate-vorbis-12: REF = $(SAMPLES)/vorbis/mono_small.pcm
+
+FATE_VORBIS += fate-vorbis-13
+fate-vorbis-13: CMD = pcm -i $(SAMPLES)/vorbis/moog_small.ogg
+fate-vorbis-13: REF = $(SAMPLES)/vorbis/moog_small.pcm
+
+FATE_VORBIS += fate-vorbis-14
+fate-vorbis-14: CMD = pcm -i $(SAMPLES)/vorbis/rc1-test_small.ogg
+fate-vorbis-14: REF = $(SAMPLES)/vorbis/rc1-test_small.pcm
+
+FATE_VORBIS += fate-vorbis-15
+fate-vorbis-15: CMD = pcm -i $(SAMPLES)/vorbis/rc2-test2_small.ogg
+fate-vorbis-15: REF = $(SAMPLES)/vorbis/rc2-test2_small.pcm
+
+FATE_VORBIS += fate-vorbis-16
+fate-vorbis-16: CMD = pcm -i $(SAMPLES)/vorbis/rc2-test_small.ogg
+fate-vorbis-16: REF = $(SAMPLES)/vorbis/rc2-test_small.pcm
+
+FATE_VORBIS += fate-vorbis-17
+fate-vorbis-17: CMD = pcm -i $(SAMPLES)/vorbis/rc3-test_small.ogg
+fate-vorbis-17: REF = $(SAMPLES)/vorbis/rc3-test_small.pcm
+
+FATE_VORBIS += fate-vorbis-18
+fate-vorbis-18: CMD = pcm -i $(SAMPLES)/vorbis/sleepzor_small.ogg
+fate-vorbis-18: REF = $(SAMPLES)/vorbis/sleepzor_small.pcm
+fate-vorbis-18: FUZZ = 2
+
+FATE_VORBIS += fate-vorbis-19
+fate-vorbis-19: CMD = pcm -i $(SAMPLES)/vorbis/test-short2_small.ogg
+fate-vorbis-19: REF = $(SAMPLES)/vorbis/test-short2_small.pcm
+
+FATE_TESTS += $(FATE_VORBIS)
+fate-vorbis: $(FATE_VORBIS)
+$(FATE_VORBIS): CMP = oneoff
diff --git a/tests/fate/vp8.mak b/tests/fate/vp8.mak
new file mode 100644
index 0000000..2b17130
--- /dev/null
+++ b/tests/fate/vp8.mak
@@ -0,0 +1,20 @@
+VP8_SUITE = 001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016 017
+
+define FATE_VP8_SUITE
+FATE_VP8 += fate-vp8-test-vector$(2)-$(1)
+fate-vp8-test-vector$(2)-$(1): CMD = framemd5 $(3) -i $(SAMPLES)/vp8-test-vectors-r1/vp80-00-comprehensive-$(1).ivf
+fate-vp8-test-vector$(2)-$(1): REF = $(SRC_PATH_BARE)/tests/ref/fate/vp8-test-vector-$(1)
+endef
+
+define FATE_VP8_FULL
+$(foreach N,$(VP8_SUITE),$(eval $(call FATE_VP8_SUITE,$(N),$(1),$(2))))
+
+FATE_VP8 += fate-vp8-sign-bias$(1)
+fate-vp8-sign-bias$(1): CMD = framemd5 $(2) -i $(SAMPLES)/vp8/sintel-signbias.ivf
+fate-vp8-sign-bias$(1): REF = $(SRC_PATH_BARE)/tests/ref/fate/vp8-sign-bias
+endef
+
+$(eval $(call FATE_VP8_FULL))
+$(eval $(call FATE_VP8_FULL,-emu-edge,-flags emu_edge))
+FATE_TESTS += $(FATE_VP8)
+fate-vp8: $(FATE_VP8)
diff --git a/tests/fate2.mak b/tests/fate2.mak
new file mode 100644
index 0000000..6a9448f
--- /dev/null
+++ b/tests/fate2.mak
@@ -0,0 +1,332 @@
+FATE_TESTS += fate-twinvq
+fate-twinvq: CMD = pcm -i $(SAMPLES)/vqf/achterba.vqf
+fate-twinvq: CMP = oneoff
+fate-twinvq: REF = $(SAMPLES)/vqf/achterba.pcm
+
+FATE_TESTS += fate-sipr-16k
+fate-sipr-16k: CMD = pcm -i $(SAMPLES)/sipr/sipr_16k.rm
+fate-sipr-16k: CMP = oneoff
+fate-sipr-16k: REF = $(SAMPLES)/sipr/sipr_16k.pcm
+
+FATE_TESTS += fate-sipr-8k5
+fate-sipr-8k5: CMD = pcm -i $(SAMPLES)/sipr/sipr_8k5.rm
+fate-sipr-8k5: CMP = oneoff
+fate-sipr-8k5: REF = $(SAMPLES)/sipr/sipr_8k5.pcm
+
+FATE_TESTS += fate-sipr-6k5
+fate-sipr-6k5: CMD = pcm -i $(SAMPLES)/sipr/sipr_6k5.rm
+fate-sipr-6k5: CMP = oneoff
+fate-sipr-6k5: REF = $(SAMPLES)/sipr/sipr_6k5.pcm
+
+FATE_TESTS += fate-sipr-5k0
+fate-sipr-5k0: CMD = pcm -i $(SAMPLES)/sipr/sipr_5k0.rm
+fate-sipr-5k0: CMP = oneoff
+fate-sipr-5k0: REF = $(SAMPLES)/sipr/sipr_5k0.pcm
+
+FATE_TESTS += fate-ra-288
+fate-ra-288: CMD = pcm -i $(SAMPLES)/real/ra_288.rm
+fate-ra-288: CMP = oneoff
+fate-ra-288: REF = $(SAMPLES)/real/ra_288.pcm
+fate-ra-288: FUZZ = 2
+
+FATE_TESTS += fate-ra-cook
+fate-ra-cook: CMD = pcm -i $(SAMPLES)/real/ra_cook.rm
+fate-ra-cook: CMP = oneoff
+fate-ra-cook: REF = $(SAMPLES)/real/ra_cook.pcm
+
+FATE_TESTS += fate-mpeg2-field-enc
+fate-mpeg2-field-enc: CMD = framecrc -flags +bitexact -dct fastint -idct simple -i $(SAMPLES)/mpeg2/mpeg2_field_encoding.ts -an
+
+FATE_TESTS += fate-qcelp
+fate-qcelp: CMD = pcm -i $(SAMPLES)/qcp/0036580847.QCP
+fate-qcelp: CMP = oneoff
+fate-qcelp: REF = $(SAMPLES)/qcp/0036580847.pcm
+
+FATE_TESTS += fate-qdm2
+fate-qdm2: CMD = pcm -i $(SAMPLES)/qt-surge-suite/surge-2-16-B-QDM2.mov
+fate-qdm2: CMP = oneoff
+fate-qdm2: REF = $(SAMPLES)/qt-surge-suite/surge-2-16-B-QDM2.pcm
+fate-qdm2: FUZZ = 2
+
+FATE_TESTS += fate-imc
+fate-imc: CMD = pcm -i $(SAMPLES)/imc/imc.avi
+fate-imc: CMP = oneoff
+fate-imc: REF = $(SAMPLES)/imc/imc.pcm
+
+FATE_TESTS += fate-yop
+fate-yop: CMD = framecrc -i $(SAMPLES)/yop/test1.yop -pix_fmt rgb24 -an
+
+FATE_TESTS += fate-pictor
+fate-pictor: CMD = framecrc -i $(SAMPLES)/pictor/MFISH.PIC -pix_fmt rgb24 -an
+
+FATE_TESTS += fate-dts
+fate-dts: CMD = pcm -i $(SAMPLES)/dts/dts.ts
+fate-dts: CMP = oneoff
+fate-dts: REF = $(SAMPLES)/dts/dts.pcm
+
+FATE_TESTS += fate-nellymoser
+fate-nellymoser: CMD = pcm -i $(SAMPLES)/nellymoser/nellymoser.flv
+fate-nellymoser: CMP = oneoff
+fate-nellymoser: REF = $(SAMPLES)/nellymoser/nellymoser.pcm
+
+FATE_TESTS += fate-truespeech
+fate-truespeech: CMD = pcm -i $(SAMPLES)/truespeech/a6.wav
+fate-truespeech: CMP = oneoff
+fate-truespeech: REF = $(SAMPLES)/truespeech/a6.pcm
+
+FATE_TESTS += fate-ac3-2.0
+fate-ac3-2.0: CMD = pcm -i $(SAMPLES)/ac3/monsters_inc_2.0_192_small.ac3
+fate-ac3-2.0: CMP = oneoff
+fate-ac3-2.0: REF = $(SAMPLES)/ac3/monsters_inc_2.0_192_small.pcm
+
+FATE_TESTS += fate-ac3-5.1
+fate-ac3-5.1: CMD = pcm -i $(SAMPLES)/ac3/monsters_inc_5.1_448_small.ac3
+fate-ac3-5.1: CMP = oneoff
+fate-ac3-5.1: REF = $(SAMPLES)/ac3/monsters_inc_5.1_448_small.pcm
+
+FATE_TESTS += fate-eac3-1
+fate-eac3-1: CMD = pcm -i $(SAMPLES)/eac3/csi_miami_5.1_256_spx_small.eac3
+fate-eac3-1: CMP = oneoff
+fate-eac3-1: REF = $(SAMPLES)/eac3/csi_miami_5.1_256_spx_small.pcm
+
+FATE_TESTS += fate-eac3-2
+fate-eac3-2: CMD = pcm -i $(SAMPLES)/eac3/csi_miami_stereo_128_spx_small.eac3
+fate-eac3-2: CMP = oneoff
+fate-eac3-2: REF = $(SAMPLES)/eac3/csi_miami_stereo_128_spx_small.pcm
+
+FATE_TESTS += fate-eac3-3
+fate-eac3-3: CMD = pcm -i $(SAMPLES)/eac3/matrix2_commentary1_stereo_192_small.eac3
+fate-eac3-3: CMP = oneoff
+fate-eac3-3: REF = $(SAMPLES)/eac3/matrix2_commentary1_stereo_192_small.pcm
+
+FATE_TESTS += fate-eac3-4
+fate-eac3-4: CMD = pcm -i $(SAMPLES)/eac3/serenity_english_5.1_1536_small.eac3
+fate-eac3-4: CMP = oneoff
+fate-eac3-4: REF = $(SAMPLES)/eac3/serenity_english_5.1_1536_small.pcm
+
+FATE_TESTS += fate-atrac1
+fate-atrac1: CMD = pcm -i $(SAMPLES)/atrac1/test_tones_small.aea
+fate-atrac1: CMP = oneoff
+fate-atrac1: REF = $(SAMPLES)/atrac1/test_tones_small.pcm
+
+FATE_TESTS += fate-atrac3-1
+fate-atrac3-1: CMD = pcm -i $(SAMPLES)/atrac3/mc_sich_at3_066_small.wav
+fate-atrac3-1: CMP = oneoff
+fate-atrac3-1: REF = $(SAMPLES)/atrac3/mc_sich_at3_066_small.pcm
+
+FATE_TESTS += fate-atrac3-2
+fate-atrac3-2: CMD = pcm -i $(SAMPLES)/atrac3/mc_sich_at3_105_small.wav
+fate-atrac3-2: CMP = oneoff
+fate-atrac3-2: REF = $(SAMPLES)/atrac3/mc_sich_at3_105_small.pcm
+
+FATE_TESTS += fate-atrac3-3
+fate-atrac3-3: CMD = pcm -i $(SAMPLES)/atrac3/mc_sich_at3_132_small.wav
+fate-atrac3-3: CMP = oneoff
+fate-atrac3-3: REF = $(SAMPLES)/atrac3/mc_sich_at3_132_small.pcm
+
+FATE_TESTS += fate-gsm
+fate-gsm: CMD = framecrc -t 10 -i $(SAMPLES)/gsm/sample-gsm-8000.mov
+
+FATE_TESTS += fate-gsm-ms
+fate-gsm-ms: CMD = framecrc -i $(SAMPLES)/gsm/ciao.wav
+
+FATE_TESTS += fate-g722dec-1
+fate-g722dec-1: CMD = framecrc -ar 16000 -i $(SAMPLES)/g722/conf-adminmenu-162.g722
+
+FATE_TESTS += fate-msmpeg4v1
+fate-msmpeg4v1: CMD = framecrc -flags +bitexact -dct fastint -idct simple -i $(SAMPLES)/msmpeg4v1/mpg4.avi -an
+
+FATE_TESTS += fate-wmavoice-7k
+fate-wmavoice-7k: CMD = pcm -i $(SAMPLES)/wmavoice/streaming_CBR-7K.wma
+fate-wmavoice-7k: CMP = stddev
+fate-wmavoice-7k: REF = $(SAMPLES)/wmavoice/streaming_CBR-7K.pcm
+fate-wmavoice-7k: FUZZ = 3
+
+FATE_TESTS += fate-wmavoice-11k
+fate-wmavoice-11k: CMD = pcm -i $(SAMPLES)/wmavoice/streaming_CBR-11K.wma
+fate-wmavoice-11k: CMP = stddev
+fate-wmavoice-11k: REF = $(SAMPLES)/wmavoice/streaming_CBR-11K.pcm
+fate-wmavoice-11k: FUZZ = 3
+
+FATE_TESTS += fate-wmavoice-19k
+fate-wmavoice-19k: CMD = pcm -i $(SAMPLES)/wmavoice/streaming_CBR-19K.wma
+fate-wmavoice-19k: CMP = stddev
+fate-wmavoice-19k: REF = $(SAMPLES)/wmavoice/streaming_CBR-19K.pcm
+fate-wmavoice-19k: FUZZ = 3
+
+FATE_TESTS += fate-wmapro-5.1
+fate-wmapro-5.1: CMD = pcm -i $(SAMPLES)/wmapro/latin_192_mulitchannel_cut.wma
+fate-wmapro-5.1: CMP = oneoff
+fate-wmapro-5.1: REF = $(SAMPLES)/wmapro/latin_192_mulitchannel_cut.pcm
+
+FATE_TESTS += fate-wmapro-2ch
+fate-wmapro-2ch: CMD = pcm -i $(SAMPLES)/wmapro/Beethovens_9th-1_small.wma
+fate-wmapro-2ch: CMP = oneoff
+fate-wmapro-2ch: REF = $(SAMPLES)/wmapro/Beethovens_9th-1_small.pcm
+
+FATE_TESTS += fate-ansi
+fate-ansi: CMD = framecrc -i $(SAMPLES)/ansi/TRE-IOM5.ANS -pix_fmt rgb24
+
+FATE_TESTS += fate-wmv8-drm
+# discard last packet to avoid fails due to overread of VC-1 decoder
+fate-wmv8-drm: CMD = framecrc -cryptokey 137381538c84c068111902a59c5cf6c340247c39 -i $(SAMPLES)/wmv8/wmv_drm.wmv -an -vframes 162
+
+FATE_TESTS += fate-wmv8-drm-nodec
+fate-wmv8-drm-nodec: CMD = framecrc -cryptokey 137381538c84c068111902a59c5cf6c340247c39 -i $(SAMPLES)/wmv8/wmv_drm.wmv -acodec copy -vcodec copy
+
+FATE_TESTS += fate-binkaudio-dct
+fate-binkaudio-dct: CMD = pcm -i $(SAMPLES)/bink/binkaudio_dct.bik
+fate-binkaudio-dct: CMP = oneoff
+fate-binkaudio-dct: REF = $(SAMPLES)/bink/binkaudio_dct.pcm
+fate-binkaudio-dct: FUZZ = 2
+
+FATE_TESTS += fate-binkaudio-rdft
+fate-binkaudio-rdft: CMD = pcm -i $(SAMPLES)/bink/binkaudio_rdft.bik
+fate-binkaudio-rdft: CMP = oneoff
+fate-binkaudio-rdft: REF = $(SAMPLES)/bink/binkaudio_rdft.pcm
+fate-binkaudio-rdft: FUZZ = 2
+
+FATE_TESTS += fate-txd-pal8
+fate-txd-pal8: CMD = framecrc -i $(SAMPLES)/txd/outro.txd -pix_fmt rgb24 -an
+
+FATE_TESTS += fate-txd-16bpp
+fate-txd-16bpp: CMD = framecrc -i $(SAMPLES)/txd/misc.txd -pix_fmt bgra -an
+
+FATE_TESTS += fate-vp3
+fate-vp3: CMD = framecrc -i $(SAMPLES)/vp3/vp31.avi
+
+FATE_TESTS += fate-fax-g3
+fate-fax-g3: CMD = framecrc -i $(SAMPLES)/CCITT_fax/G31D.TIF
+
+FATE_TESTS += fate-fax-g3s
+fate-fax-g3s: CMD = framecrc -i $(SAMPLES)/CCITT_fax/G31DS.TIF
+
+FATE_TESTS += fate-ws_snd
+fate-ws_snd: CMD = md5  -i $(SAMPLES)/vqa/ws_snd.vqa -f s16le
+
+FATE_TESTS += fate-dxa-scummvm
+fate-dxa-scummvm: CMD = framecrc -i $(SAMPLES)/dxa/scummvm.dxa -pix_fmt rgb24
+
+FATE_TESTS += fate-mjpegb
+fate-mjpegb: CMD = framecrc -idct simple -flags +bitexact -i $(SAMPLES)/mjpegb/mjpegb_part.mov -an
+
+FATE_TESTS += fate-rv30
+fate-rv30: CMD = framecrc -flags +bitexact -dct fastint -idct simple -i $(SAMPLES)/real/rv30.rm -an
+
+FATE_TESTS += fate-sha
+fate-sha: libavutil/sha-test$(EXESUF)
+fate-sha: CMD = run libavutil/sha-test
+
+FATE_TESTS += fate-musepack7
+fate-musepack7: CMD = pcm -i $(SAMPLES)/musepack/inside-mp7.mpc
+fate-musepack7: CMP = oneoff
+fate-musepack7: REF = $(SAMPLES)/musepack/inside-mp7.pcm
+fate-musepack7: FUZZ = 1
+
+FATE_TESTS += fate-amrnb-4k75
+fate-amrnb-4k75: CMD = pcm -i $(SAMPLES)/amrnb/4.75k.amr
+fate-amrnb-4k75: CMP = stddev
+fate-amrnb-4k75: REF = $(SAMPLES)/amrnb/4.75k.pcm
+fate-amrnb-4k75: FUZZ = 1
+
+FATE_TESTS += fate-amrnb-5k15
+fate-amrnb-5k15: CMD = pcm -i $(SAMPLES)/amrnb/5.15k.amr
+fate-amrnb-5k15: CMP = stddev
+fate-amrnb-5k15: REF = $(SAMPLES)/amrnb/5.15k.pcm
+fate-amrnb-5k15: FUZZ = 1
+
+FATE_TESTS += fate-amrnb-5k9
+fate-amrnb-5k9: CMD = pcm -i $(SAMPLES)/amrnb/5.9k.amr
+fate-amrnb-5k9: CMP = stddev
+fate-amrnb-5k9: REF = $(SAMPLES)/amrnb/5.9k.pcm
+fate-amrnb-5k9: FUZZ = 1
+
+FATE_TESTS += fate-amrnb-6k7
+fate-amrnb-6k7: CMD = pcm -i $(SAMPLES)/amrnb/6.7k.amr
+fate-amrnb-6k7: CMP = stddev
+fate-amrnb-6k7: REF = $(SAMPLES)/amrnb/6.7k.pcm
+fate-amrnb-6k7: FUZZ = 1
+
+FATE_TESTS += fate-amrnb-7k4
+fate-amrnb-7k4: CMD = pcm -i $(SAMPLES)/amrnb/7.4k.amr
+fate-amrnb-7k4: CMP = stddev
+fate-amrnb-7k4: REF = $(SAMPLES)/amrnb/7.4k.pcm
+fate-amrnb-7k4: FUZZ = 1
+
+FATE_TESTS += fate-amrnb-7k95
+fate-amrnb-7k95: CMD = pcm -i $(SAMPLES)/amrnb/7.95k.amr
+fate-amrnb-7k95: CMP = stddev
+fate-amrnb-7k95: REF = $(SAMPLES)/amrnb/7.95k.pcm
+fate-amrnb-7k95: FUZZ = 1
+
+FATE_TESTS += fate-amrnb-10k2
+fate-amrnb-10k2: CMD = pcm -i $(SAMPLES)/amrnb/10.2k.amr
+fate-amrnb-10k2: CMP = stddev
+fate-amrnb-10k2: REF = $(SAMPLES)/amrnb/10.2k.pcm
+fate-amrnb-10k2: FUZZ = 1
+
+FATE_TESTS += fate-amrnb-12k2
+fate-amrnb-12k2: CMD = pcm -i $(SAMPLES)/amrnb/12.2k.amr
+fate-amrnb-12k2: CMP = stddev
+fate-amrnb-12k2: REF = $(SAMPLES)/amrnb/12.2k.pcm
+fate-amrnb-12k2: FUZZ = 1
+
+FATE_TESTS += fate-amrwb-6k60
+fate-amrwb-6k60: CMD = pcm -i $(SAMPLES)/amrwb/seed-6k60.awb
+fate-amrwb-6k60: CMP = stddev
+fate-amrwb-6k60: REF = $(SAMPLES)/amrwb/seed-6k60.pcm
+fate-amrwb-6k60: FUZZ = 1
+
+FATE_TESTS += fate-amrwb-8k85
+fate-amrwb-8k85: CMD = pcm -i $(SAMPLES)/amrwb/seed-8k85.awb
+fate-amrwb-8k85: CMP = stddev
+fate-amrwb-8k85: REF = $(SAMPLES)/amrwb/seed-8k85.pcm
+fate-amrwb-8k85: FUZZ = 1
+
+FATE_TESTS += fate-amrwb-12k65
+fate-amrwb-12k65: CMD = pcm -i $(SAMPLES)/amrwb/seed-12k65.awb
+fate-amrwb-12k65: CMP = stddev
+fate-amrwb-12k65: REF = $(SAMPLES)/amrwb/seed-12k65.pcm
+fate-amrwb-12k65: FUZZ = 1
+
+FATE_TESTS += fate-amrwb-14k25
+fate-amrwb-14k25: CMD = pcm -i $(SAMPLES)/amrwb/seed-14k25.awb
+fate-amrwb-14k25: CMP = stddev
+fate-amrwb-14k25: REF = $(SAMPLES)/amrwb/seed-14k25.pcm
+fate-amrwb-14k25: FUZZ = 2.6
+
+FATE_TESTS += fate-amrwb-15k85
+fate-amrwb-15k85: CMD = pcm -i $(SAMPLES)/amrwb/seed-15k85.awb
+fate-amrwb-15k85: CMP = stddev
+fate-amrwb-15k85: REF = $(SAMPLES)/amrwb/seed-15k85.pcm
+fate-amrwb-15k85: FUZZ = 1
+
+FATE_TESTS += fate-amrwb-18k25
+fate-amrwb-18k25: CMD = pcm -i $(SAMPLES)/amrwb/seed-18k25.awb
+fate-amrwb-18k25: CMP = stddev
+fate-amrwb-18k25: REF = $(SAMPLES)/amrwb/seed-18k25.pcm
+fate-amrwb-18k25: FUZZ = 1
+
+FATE_TESTS += fate-amrwb-19k85
+fate-amrwb-19k85: CMD = pcm -i $(SAMPLES)/amrwb/seed-19k85.awb
+fate-amrwb-19k85: CMP = stddev
+fate-amrwb-19k85: REF = $(SAMPLES)/amrwb/seed-19k85.pcm
+fate-amrwb-19k85: FUZZ = 1
+
+FATE_TESTS += fate-amrwb-23k05
+fate-amrwb-23k05: CMD = pcm -i $(SAMPLES)/amrwb/seed-23k05.awb
+fate-amrwb-23k05: CMP = stddev
+fate-amrwb-23k05: REF = $(SAMPLES)/amrwb/seed-23k05.pcm
+fate-amrwb-23k05: FUZZ = 2
+
+FATE_TESTS += fate-amrwb-23k85
+fate-amrwb-23k85: CMD = pcm -i $(SAMPLES)/amrwb/seed-23k85.awb
+fate-amrwb-23k85: CMP = stddev
+fate-amrwb-23k85: REF = $(SAMPLES)/amrwb/seed-23k85.pcm
+fate-amrwb-23k85: FUZZ = 2
+
+FATE_TESTS += fate-amrwb-23k85-2
+fate-amrwb-23k85-2: CMD = pcm -i $(SAMPLES)/amrwb/deus-23k85.awb
+fate-amrwb-23k85-2: CMP = stddev
+fate-amrwb-23k85-2: REF = $(SAMPLES)/amrwb/deus-23k85.pcm
+fate-amrwb-23k85-2: FUZZ = 1
diff --git a/tests/lavf-regression.sh b/tests/lavf-regression.sh
index 6e489a6..b14a58e 100755
--- a/tests/lavf-regression.sh
+++ b/tests/lavf-regression.sh
@@ -40,7 +40,7 @@ do_image_formats()
 do_audio_only()
 {
     file=${outfile}lavf.$1
-    do_ffmpeg $file -t 1 -qscale 10 -f s16le -i $pcm_src
+    do_ffmpeg $file -t 1 -qscale 10 $2 -f s16le -i $pcm_src $3
     do_ffmpeg_crc $file -i $target_path/$file
 }
 
@@ -57,7 +57,7 @@ fi
 
 if [ -n "$do_rm" ] ; then
 file=${outfile}lavf.rm
-do_ffmpeg $file -t 1 -qscale 10 -f image2 -vcodec pgmyuv -i $raw_src -f s16le -i $pcm_src
+do_ffmpeg $file -t 1 -qscale 10 -f image2 -vcodec pgmyuv -i $raw_src -f s16le -i $pcm_src -acodec ac3_fixed
 # broken
 #do_ffmpeg_crc $file -i $target_path/$file
 fi
@@ -68,7 +68,7 @@ fi
 
 if [ -n "$do_mxf" ] ; then
 do_lavf mxf "-ar 48000 -bf 2 -timecode_frame_start 264363"
-do_lavf mxf_d10 "-ar 48000 -ac 2 -r 25 -s 720x576 -padtop 32 -vcodec mpeg2video -intra -flags +ildct+low_delay -dc 10 -flags2 +ivlc+non_linear_q -qscale 1 -ps 1 -qmin 1 -rc_max_vbv_use 1 -rc_min_vbv_use 1 -pix_fmt yuv422p -minrate 30000k -maxrate 30000k -b 30000k -bufsize 1200000 -top 1 -rc_init_occupancy 1200000 -qmax 12 -f mxf_d10"
+do_lavf mxf_d10 "-ar 48000 -ac 2 -r 25 -s 720x576 -vf pad=720:608:0:32 -vcodec mpeg2video -intra -flags +ildct+low_delay -dc 10 -flags2 +ivlc+non_linear_q -qscale 1 -ps 1 -qmin 1 -rc_max_vbv_use 1 -rc_min_vbv_use 1 -pix_fmt yuv422p -minrate 30000k -maxrate 30000k -b 30000k -bufsize 1200000 -top 1 -rc_init_occupancy 1200000 -qmax 12 -f mxf_d10"
 fi
 
 if [ -n "$do_ts" ] ; then
@@ -129,7 +129,7 @@ fi
 if [ -n "$do_gif" ] ; then
 file=${outfile}lavf.gif
 do_ffmpeg $file -t 1 -qscale 10 -f image2 -vcodec pgmyuv -i $raw_src -pix_fmt rgb24
-#do_ffmpeg_crc $file -i $target_path/$file
+do_ffmpeg_crc $file -i $target_path/$file -pix_fmt rgb24
 fi
 
 if [ -n "$do_yuv4mpeg" ] ; then
@@ -148,6 +148,10 @@ if [ -n "$do_ppm" ] ; then
 do_image_formats ppm
 fi
 
+if [ -n "$do_png" ] ; then
+do_image_formats png
+fi
+
 if [ -n "$do_bmp" ] ; then
 do_image_formats bmp
 fi
@@ -202,10 +206,18 @@ if [ -n "$do_voc" ] ; then
 do_audio_only voc
 fi
 
+if [ -n "$do_voc_s16" ] ; then
+do_audio_only s16.voc "-ac 2" "-acodec pcm_s16le"
+fi
+
 if [ -n "$do_ogg" ] ; then
 do_audio_only ogg
 fi
 
+if [ -n "$do_rso" ] ; then
+do_audio_only rso
+fi
+
 # pix_fmt conversions
 
 if [ -n "$do_pixfmt" ] ; then
@@ -222,5 +234,3 @@ for pix_fmt in $conversions ; do
                     -f rawvideo -s 352x288 -pix_fmt yuv444p
 done
 fi
-
-rm -f "$bench" "$bench2"
diff --git a/tests/lavfi-regression.sh b/tests/lavfi-regression.sh
index 03e7cef..ed13f70 100755
--- a/tests/lavfi-regression.sh
+++ b/tests/lavfi-regression.sh
@@ -14,30 +14,71 @@ eval do_$test=y
 rm -f "$logfile"
 rm -f "$benchfile"
 
+do_video_filter() {
+    label=$1
+    filters=$2
+    shift 2
+    printf '%-20s' $label >>$logfile
+    run_ffmpeg -f image2 -vcodec pgmyuv -i $raw_src    \
+        -vf "$filters" -vcodec rawvideo $* -f nut md5: >>$logfile
+}
+
 do_lavfi() {
-    test_name=$1
-    eval test=\$do_$test_name
     vfilters="slicify=random,$2"
 
-    if [ -n "$test" ] ; then
-        do_video_encoding ${test_name}.nut "" "-vcodec rawvideo -vfilters $vfilters"
+    if [ $test = $1 ] ; then
+        do_video_filter $test "$vfilters"
     fi
 }
 
-do_lavfi "crop"               "crop=100:100"
-do_lavfi "crop_scale"         "crop=100:100,scale=400:-1"
-do_lavfi "crop_scale_vflip"   "null,null,crop=200:200,crop=20:20,scale=200:200,scale=250:250,vflip,vflip,null,scale=200:200,crop=100:100,vflip,scale=200:200,null,vflip,crop=100:100,null"
-do_lavfi "crop_vflip"         "crop=100:100,vflip"
+do_lavfi "crop"               "crop=iw-100:ih-100:100:100"
+do_lavfi "crop_scale"         "crop=iw-100:ih-100:100:100,scale=400:-1"
+do_lavfi "crop_scale_vflip"   "null,null,crop=iw-200:ih-200:200:200,crop=iw-20:ih-20:20:20,scale=200:200,scale=250:250,vflip,vflip,null,scale=200:200,crop=iw-100:ih-100:100:100,vflip,scale=200:200,null,vflip,crop=iw-100:ih-100:100:100,null"
+do_lavfi "crop_vflip"         "crop=iw-100:ih-100:100:100,vflip"
 do_lavfi "null"               "null"
 do_lavfi "scale200"           "scale=200:200"
 do_lavfi "scale500"           "scale=500:500"
 do_lavfi "vflip"              "vflip"
-do_lavfi "vflip_crop"         "vflip,crop=100:100"
+do_lavfi "vflip_crop"         "vflip,crop=iw-100:ih-100:100:100"
 do_lavfi "vflip_vflip"        "vflip,vflip"
 
+do_lavfi_pixfmts(){
+    test ${test%_[bl]e} = pixfmts_$1 || return 0
+    filter=$1
+    filter_args=$2
+
+    showfiltfmts="$target_exec $target_path/tools/lavfi-showfiltfmts"
+    exclude_fmts=${outfile}${1}_exclude_fmts
+    out_fmts=${outfile}${1}_out_fmts
+
+    # exclude pixel formats which are not supported as input
+    $ffmpeg -pix_fmts list 2>/dev/null | sed -ne '9,$p' | grep '^\..\.' | cut -d' ' -f2 | sort >$exclude_fmts
+    $showfiltfmts scale | awk -F '[ \r]' '/^OUTPUT/{ print $3 }' | sort | comm -23 - $exclude_fmts >$out_fmts
+
+    pix_fmts=$($showfiltfmts $filter | awk -F '[ \r]' '/^INPUT/{ print $3 }' | sort | comm -12 - $out_fmts)
+    for pix_fmt in $pix_fmts; do
+        do_video_filter $pix_fmt "slicify=random,format=$pix_fmt,$filter=$filter_args" -pix_fmt $pix_fmt
+    done
+
+    rm $exclude_fmts $out_fmts
+}
+
+# all these filters have exactly one input and exactly one output
+do_lavfi_pixfmts "copy"    ""
+do_lavfi_pixfmts "crop"    "100:100:100:100"
+do_lavfi_pixfmts "hflip"   ""
+do_lavfi_pixfmts "null"    ""
+do_lavfi_pixfmts "pad"     "500:400:20:20"
+do_lavfi_pixfmts "scale"   "200:100"
+do_lavfi_pixfmts "vflip"   ""
+
+if [ -n "$do_pixdesc_be" ] || [ -n "$do_pixdesc_le" ]; then
+    pix_fmts="$($ffmpeg -pix_fmts list 2>/dev/null | sed -ne '9,$p' | grep '^IO' | cut -d' ' -f2 | sort)"
+    for pix_fmt in $pix_fmts; do
+        do_video_filter $pix_fmt "slicify=random,format=$pix_fmt,pixdesctest" -pix_fmt $pix_fmt
+    done
+fi
+
 # TODO: add tests for
 # direct rendering,
-# slices
 # chains with feedback loops
-
-rm -f "$bench" "$bench2"
diff --git a/tests/md5.sh b/tests/md5.sh
index 6809169..16b0281 100644
--- a/tests/md5.sh
+++ b/tests/md5.sh
@@ -6,6 +6,8 @@ elif [ X"$(echo | md5 2> /dev/null)" != X ]; then
     do_md5sum() { md5 $1 | sed 's#MD5 (\(.*\)) = \(.*\)#\2 *\1#'; }
 elif [ -x /sbin/md5 ]; then
     do_md5sum() { /sbin/md5 -r $1 | sed 's# \**\./# *./#'; }
+elif openssl version >/dev/null 2>&1; then
+    do_md5sum() { openssl md5 $1 | sed 's/MD5(\(.*\))= \(.*\)/\2 *\1/'; }
 else
     do_md5sum() { echo No md5sum program found; }
 fi
diff --git a/tests/ref/acodec/ac3 b/tests/ref/acodec/ac3
deleted file mode 100644
index b393956..0000000
--- a/tests/ref/acodec/ac3
+++ /dev/null
@@ -1,2 +0,0 @@
-081bfd5e683b13cccf1b07c43c1c5005 *./tests/data/acodec/ac3.rm
-98751 ./tests/data/acodec/ac3.rm
diff --git a/tests/ref/acodec/ac3_fixed b/tests/ref/acodec/ac3_fixed
new file mode 100644
index 0000000..a3032d0
--- /dev/null
+++ b/tests/ref/acodec/ac3_fixed
@@ -0,0 +1,2 @@
+5ddb6d25dd117db29627f9d286153a7a *./tests/data/acodec/ac3.rm
+98751 ./tests/data/acodec/ac3.rm
diff --git a/tests/ref/acodec/adpcm_ima_qt b/tests/ref/acodec/adpcm_ima_qt
index 4fef154..6e44156 100644
--- a/tests/ref/acodec/adpcm_ima_qt
+++ b/tests/ref/acodec/adpcm_ima_qt
@@ -1,4 +1,4 @@
 3c06fd2f7831e3e8735b936e23ca220c *./tests/data/acodec/adpcm_qt.aiff
 281252 ./tests/data/acodec/adpcm_qt.aiff
 9580492803ba1c1a3746367b24b751c8 *./tests/data/adpcm_ima_qt.acodec.out.wav
-stddev:  914.63 PSNR: 37.10 bytes:  1058604/  1058444
+stddev:  914.65 PSNR: 37.10 MAXDIFF:34026 bytes:  1058560/  1058400
diff --git a/tests/ref/acodec/adpcm_ima_wav b/tests/ref/acodec/adpcm_ima_wav
index a58c279..29f5836 100644
--- a/tests/ref/acodec/adpcm_ima_wav
+++ b/tests/ref/acodec/adpcm_ima_wav
@@ -1,4 +1,4 @@
 56b75c3a6dacedcf2ce7b0586aa33594 *./tests/data/acodec/adpcm_ima.wav
 267324 ./tests/data/acodec/adpcm_ima.wav
 78a2af1c895792d0c221d127bdd48ece *./tests/data/adpcm_ima_wav.acodec.out.wav
-stddev:  903.51 PSNR: 37.21 bytes:  1061792/  1058444
+stddev:  903.51 PSNR: 37.21 MAXDIFF:34026 bytes:  1061748/  1058400
diff --git a/tests/ref/acodec/adpcm_ms b/tests/ref/acodec/adpcm_ms
index 99a7105..65d2a6c 100644
--- a/tests/ref/acodec/adpcm_ms
+++ b/tests/ref/acodec/adpcm_ms
@@ -1,4 +1,4 @@
 a407b87daeef5b25dfb6c5b3f519e9c1 *./tests/data/acodec/adpcm_ms.wav
 268378 ./tests/data/acodec/adpcm_ms.wav
 7be370f937c51e8a967e6a3d08d5156a *./tests/data/adpcm_ms.acodec.out.wav
-stddev: 1050.00 PSNR: 35.91 bytes:  1060620/  1058444
+stddev: 1050.01 PSNR: 35.91 MAXDIFF:29806 bytes:  1060576/  1058400
diff --git a/tests/ref/acodec/adpcm_swf b/tests/ref/acodec/adpcm_swf
index 59bf8f3..27a5da5 100644
--- a/tests/ref/acodec/adpcm_swf
+++ b/tests/ref/acodec/adpcm_swf
@@ -1,4 +1,4 @@
 42d4639866ed4d692eaf126228a4fa2a *./tests/data/acodec/adpcm_swf.flv
 269166 ./tests/data/acodec/adpcm_swf.flv
 628089745a7059ae4055c2515b6d668b *./tests/data/adpcm_swf.acodec.out.wav
-stddev:  933.65 PSNR: 36.93 bytes:  1065004/  1058444
+stddev:  933.58 PSNR: 36.93 MAXDIFF:51119 bytes:  1064960/  1058400
diff --git a/tests/ref/acodec/adpcm_yam b/tests/ref/acodec/adpcm_yam
index 9889dd9..d7076e7 100644
--- a/tests/ref/acodec/adpcm_yam
+++ b/tests/ref/acodec/adpcm_yam
@@ -1,4 +1,4 @@
 2546d72df736b5ffa1557e8c9c9ef788 *./tests/data/acodec/adpcm_yam.wav
 266296 ./tests/data/acodec/adpcm_yam.wav
 c80c847a53a0fee17a88fa889ec34a4e *./tests/data/adpcm_yam.acodec.out.wav
-stddev: 1247.64 PSNR: 34.41 bytes:  1065004/  1058444
+stddev: 1247.60 PSNR: 34.41 MAXDIFF:39895 bytes:  1064960/  1058400
diff --git a/tests/ref/acodec/alac b/tests/ref/acodec/alac
index 143b1f3..1f4b264 100644
--- a/tests/ref/acodec/alac
+++ b/tests/ref/acodec/alac
@@ -1,4 +1,4 @@
 c68f649777ab8e7c9a0f1f221451d3ad *./tests/data/acodec/alac.m4a
 389386 ./tests/data/acodec/alac.m4a
 95e54b261530a1bcf6de6fe3b21dc5f6 *./tests/data/alac.acodec.out.wav
-stddev:    0.00 PSNR:999.99 bytes:  1058444/  1058444
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  1058400/  1058400
diff --git a/tests/ref/acodec/flac b/tests/ref/acodec/flac
index b1e4174..e9d7cfc 100644
--- a/tests/ref/acodec/flac
+++ b/tests/ref/acodec/flac
@@ -1,4 +1,4 @@
 151eef9097f944726968bec48649f00a *./tests/data/acodec/flac.flac
 361582 ./tests/data/acodec/flac.flac
 95e54b261530a1bcf6de6fe3b21dc5f6 *./tests/data/flac.acodec.out.wav
-stddev:    0.00 PSNR:999.99 bytes:  1058444/  1058444
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  1058400/  1058400
diff --git a/tests/ref/acodec/g726 b/tests/ref/acodec/g726
index 02b9eea..d2dbe50 100644
--- a/tests/ref/acodec/g726
+++ b/tests/ref/acodec/g726
@@ -1,4 +1,4 @@
-5d8cce28f83dd33c3c7eaf43a5db5294 *./tests/data/acodec/g726.wav
-24082 ./tests/data/acodec/g726.wav
-4f1ba1af75dee64625a1c852e6cd01d3 *./tests/data/g726.acodec.out.wav
-stddev: 8506.46 PSNR: 17.73 bytes:    96148/  1058444
+fd090ddf05cc3401cc75c4a5ace1d05a *./tests/data/acodec/g726.wav
+24052 ./tests/data/acodec/g726.wav
+74abea06027375111eeac1b2f8c7d3af *./tests/data/g726.acodec.out.wav
+stddev: 8554.55 PSNR: 17.69 MAXDIFF:29353 bytes:    95984/  1058400
diff --git a/tests/ref/acodec/mp2 b/tests/ref/acodec/mp2
index 0607cab..df21be2 100644
--- a/tests/ref/acodec/mp2
+++ b/tests/ref/acodec/mp2
@@ -1,5 +1,5 @@
 f6eb0a205350bbd7fb1028a01c7ae8aa *./tests/data/acodec/mp2.mp2
 96130 ./tests/data/acodec/mp2.mp2
 74c7b6b15a001add199619fafe4059a1 *./tests/data/mp2.acodec.out.wav
-stddev: 9315.80 PSNR: 16.94 bytes:  1059884/  1058444
-stddev: 4385.25 PSNR: 23.49 bytes:  1057960/  1058444
+stddev: 9315.99 PSNR: 16.94 MAXDIFF:65388 bytes:  1059840/  1058400
+stddev: 4384.33 PSNR: 23.49 MAXDIFF:52631 bytes:  1057916/  1058400
diff --git a/tests/ref/acodec/pcm b/tests/ref/acodec/pcm
index 8e34408..033f8bc 100644
--- a/tests/ref/acodec/pcm
+++ b/tests/ref/acodec/pcm
@@ -1,72 +1,72 @@
 89f5b8dd97e0dddbe59af0d44fd229f3 *./tests/data/acodec/pcm_alaw.wav
 529256 ./tests/data/acodec/pcm_alaw.wav
 0568b0b9a72e31559e150e7e09d301cd *./tests/data/pcm.acodec.out.wav
-stddev:  101.67 PSNR: 56.19 bytes:  1058444/  1058444
+stddev:  101.67 PSNR: 56.19 MAXDIFF:  515 bytes:  1058400/  1058400
 f443a8eeb1647ec1eeb8370c939e52d4 *./tests/data/acodec/pcm_mulaw.wav
 529256 ./tests/data/acodec/pcm_mulaw.wav
 1c3eeaa8814ebd4916780dff80ed6dc5 *./tests/data/pcm.acodec.out.wav
-stddev:  103.38 PSNR: 56.04 bytes:  1058444/  1058444
+stddev:  103.38 PSNR: 56.04 MAXDIFF:  644 bytes:  1058400/  1058400
 b7936d7170e0efefb379349d81aed360 *./tests/data/acodec/pcm_s8.mov
 530837 ./tests/data/acodec/pcm_s8.mov
 652edf30f35ad89bf27bcc9d2f9c7b53 *./tests/data/pcm.acodec.out.wav
-stddev:  147.89 PSNR: 52.93 bytes:  1058444/  1058444
+stddev:  147.89 PSNR: 52.93 MAXDIFF:  255 bytes:  1058400/  1058400
 98cadb3502dbdc99e6e077c28b1a036c *./tests/data/acodec/pcm_u8.wav
 529244 ./tests/data/acodec/pcm_u8.wav
 652edf30f35ad89bf27bcc9d2f9c7b53 *./tests/data/pcm.acodec.out.wav
-stddev:  147.89 PSNR: 52.93 bytes:  1058444/  1058444
+stddev:  147.89 PSNR: 52.93 MAXDIFF:  255 bytes:  1058400/  1058400
 c42b9c04305455250366c84e17c1023f *./tests/data/acodec/pcm_s16be.mov
 1060037 ./tests/data/acodec/pcm_s16be.mov
 95e54b261530a1bcf6de6fe3b21dc5f6 *./tests/data/pcm.acodec.out.wav
-stddev:    0.00 PSNR:999.99 bytes:  1058444/  1058444
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  1058400/  1058400
 95e54b261530a1bcf6de6fe3b21dc5f6 *./tests/data/acodec/pcm_s16le.wav
 1058444 ./tests/data/acodec/pcm_s16le.wav
 95e54b261530a1bcf6de6fe3b21dc5f6 *./tests/data/pcm.acodec.out.wav
-stddev:    0.00 PSNR:999.99 bytes:  1058444/  1058444
-43440f8078f2383c0dd618ad606f6830 *./tests/data/acodec/pcm_s16be.mkv
- 1060693 ./tests/data/acodec/pcm_s16be.mkv
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  1058400/  1058400
+af717ca95eaca310772eb1238c745d1b *./tests/data/acodec/pcm_s16be.mkv
+1060638 ./tests/data/acodec/pcm_s16be.mkv
 95e54b261530a1bcf6de6fe3b21dc5f6 *./tests/data/pcm.acodec.out.wav
-stddev:    0.00 PSNR:999.99 bytes:  1058444/  1058444
-1e63166f1672b7eb00877c697c06743c *./tests/data/acodec/pcm_s16le.mkv
- 1060693 ./tests/data/acodec/pcm_s16le.mkv
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  1058400/  1058400
+c4f51bf32fad2f7af8ea5beedb56168b *./tests/data/acodec/pcm_s16le.mkv
+1060638 ./tests/data/acodec/pcm_s16le.mkv
 95e54b261530a1bcf6de6fe3b21dc5f6 *./tests/data/pcm.acodec.out.wav
-stddev:    0.00 PSNR:999.99 bytes:  1058444/  1058444
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  1058400/  1058400
 07ffe7ffb78f3648b6524debdde5aec1 *./tests/data/acodec/pcm_s24be.mov
 1589237 ./tests/data/acodec/pcm_s24be.mov
 95e54b261530a1bcf6de6fe3b21dc5f6 *./tests/data/pcm.acodec.out.wav
-stddev:    0.00 PSNR:999.99 bytes:  1058444/  1058444
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  1058400/  1058400
 a85380fb79b0d4fff38e24ac1e34bb94 *./tests/data/acodec/pcm_s24le.wav
 1587668 ./tests/data/acodec/pcm_s24le.wav
 95e54b261530a1bcf6de6fe3b21dc5f6 *./tests/data/pcm.acodec.out.wav
-stddev:    0.00 PSNR:999.99 bytes:  1058444/  1058444
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  1058400/  1058400
 d7792f0343cd66fda8b50b569e2bcc48 *./tests/data/acodec/pcm_s32be.mov
 2118437 ./tests/data/acodec/pcm_s32be.mov
 95e54b261530a1bcf6de6fe3b21dc5f6 *./tests/data/pcm.acodec.out.wav
-stddev:    0.00 PSNR:999.99 bytes:  1058444/  1058444
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  1058400/  1058400
 da6ed80f4f40f0082577dea80827e014 *./tests/data/acodec/pcm_s32le.wav
 2116868 ./tests/data/acodec/pcm_s32le.wav
 95e54b261530a1bcf6de6fe3b21dc5f6 *./tests/data/pcm.acodec.out.wav
-stddev:    0.00 PSNR:999.99 bytes:  1058444/  1058444
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  1058400/  1058400
 118ff3dc83c62ce9ce669eef57e55bb2 *./tests/data/acodec/pcm_f32be.au
 2116824 ./tests/data/acodec/pcm_f32be.au
 95e54b261530a1bcf6de6fe3b21dc5f6 *./tests/data/pcm.acodec.out.wav
-stddev:    0.00 PSNR:999.99 bytes:  1058444/  1058444
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  1058400/  1058400
 46f44f86a18984a832206ab9e29a79f2 *./tests/data/acodec/pcm_f32le.wav
 2116880 ./tests/data/acodec/pcm_f32le.wav
 95e54b261530a1bcf6de6fe3b21dc5f6 *./tests/data/pcm.acodec.out.wav
-stddev:    0.00 PSNR:999.99 bytes:  1058444/  1058444
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  1058400/  1058400
 8112296b1ed94f72f20d04b1a54850a7 *./tests/data/acodec/pcm_f64be.au
 4233624 ./tests/data/acodec/pcm_f64be.au
 95e54b261530a1bcf6de6fe3b21dc5f6 *./tests/data/pcm.acodec.out.wav
-stddev:    0.00 PSNR:999.99 bytes:  1058444/  1058444
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  1058400/  1058400
 ba17c6d1a270e1333e981f239bf7eb45 *./tests/data/acodec/pcm_f64le.wav
 4233680 ./tests/data/acodec/pcm_f64le.wav
 95e54b261530a1bcf6de6fe3b21dc5f6 *./tests/data/pcm.acodec.out.wav
-stddev:    0.00 PSNR:999.99 bytes:  1058444/  1058444
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  1058400/  1058400
 8c74234928ed425b1171211a89f67ead *./tests/data/acodec/pcm_zork.wav
 529256 ./tests/data/acodec/pcm_zork.wav
 864c8c866ac25642c29a13b122c70709 *./tests/data/pcm.acodec.out.wav
-stddev:  633.10 PSNR: 40.30 bytes:  1058444/  1058444
+stddev:  633.11 PSNR: 40.30 MAXDIFF:32768 bytes:  1058400/  1058400
 8168a5c1343553ef027541830f2cb879 *./tests/data/acodec/pcm_s24daud.302
 10368730 ./tests/data/acodec/pcm_s24daud.302
 f552afadfdfcd6348a07095da6382de5 *./tests/data/pcm.acodec.out.wav
-stddev: 9415.16 PSNR: 16.85 bytes:  6911864/  1058444
+stddev: 9416.28 PSNR: 16.85 MAXDIFF:42744 bytes:  6911796/  1058400
diff --git a/tests/ref/acodec/wmav1 b/tests/ref/acodec/wmav1
index f1bb69c..916e4a8 100644
--- a/tests/ref/acodec/wmav1
+++ b/tests/ref/acodec/wmav1
@@ -1,4 +1,4 @@
 26a7f6b0f0b7181df8df3fa589f6bf81 *./tests/data/acodec/wmav1.asf
 106004 ./tests/data/acodec/wmav1.asf
-stddev:12245.27 PSNR: 14.57 bytes:  1065004/  1058444
-stddev: 2097.78 PSNR: 29.89 bytes:  1056812/  1058444
+stddev:12245.52 PSNR: 14.57 MAXDIFF:65521 bytes:  1064960/  1058400
+stddev: 2095.89 PSNR: 29.90 MAXDIFF:27658 bytes:  1056768/  1058400
diff --git a/tests/ref/acodec/wmav2 b/tests/ref/acodec/wmav2
index ca18dea..622b6fc 100644
--- a/tests/ref/acodec/wmav2
+++ b/tests/ref/acodec/wmav2
@@ -1,4 +1,4 @@
 7c6c0cb692af01b312ae345723674b5f *./tests/data/acodec/wmav2.asf
 106044 ./tests/data/acodec/wmav2.asf
-stddev:12249.69 PSNR: 14.57 bytes:  1065004/  1058444
-stddev: 2091.12 PSNR: 29.92 bytes:  1056812/  1058444
+stddev:12249.93 PSNR: 14.57 MAXDIFF:65521 bytes:  1064960/  1058400
+stddev: 2089.21 PSNR: 29.93 MAXDIFF:27650 bytes:  1056768/  1058400
diff --git a/tests/ref/fate/4xm b/tests/ref/fate/4xm
deleted file mode 100644
index 614da5e..0000000
--- a/tests/ref/fate/4xm
+++ /dev/null
@@ -1 +0,0 @@
-88a53430410d1cec5ed46846652ffd51
diff --git a/tests/ref/fate/4xm-1 b/tests/ref/fate/4xm-1
new file mode 100644
index 0000000..5e66dcc
--- /dev/null
+++ b/tests/ref/fate/4xm-1
@@ -0,0 +1,15 @@
+0, 0, 921600, 0xd08f97c7
+0, 6000, 921600, 0xc433a85b
+0, 12000, 921600, 0x7ffeee42
+0, 18000, 921600, 0xc0ad9f52
+0, 24000, 921600, 0xb0235112
+0, 30000, 921600, 0xcbdd9805
+0, 36000, 921600, 0x5468bdb9
+0, 42000, 921600, 0x2f0c63fd
+0, 48000, 921600, 0xf1de04f0
+0, 54000, 921600, 0x95709ce2
+0, 60000, 921600, 0x69037c4a
+0, 66000, 921600, 0x513f8a98
+0, 72000, 921600, 0x55b82fa1
+0, 78000, 921600, 0x5c8ace28
+0, 84000, 921600, 0xb019770a
diff --git a/tests/ref/fate/4xm-2 b/tests/ref/fate/4xm-2
new file mode 100644
index 0000000..4037f28
--- /dev/null
+++ b/tests/ref/fate/4xm-2
@@ -0,0 +1,174 @@
+0, 0, 80640, 0x00000000
+0, 15000, 80640, 0x3a942680
+0, 30000, 80640, 0x3a942680
+0, 45000, 80640, 0x3a942680
+0, 60000, 80640, 0x3a942680
+0, 75000, 80640, 0x3a942680
+0, 90000, 80640, 0x3a942680
+0, 105000, 80640, 0x1956ebfc
+0, 120000, 80640, 0x61686290
+0, 135000, 80640, 0x7e2c2753
+0, 150000, 80640, 0x63e5e14f
+0, 165000, 80640, 0xa775947a
+0, 180000, 80640, 0x4b91b93d
+0, 195000, 80640, 0x83345f32
+0, 210000, 80640, 0x5d3a3374
+0, 225000, 80640, 0x164808c5
+0, 240000, 80640, 0xfd0189af
+0, 255000, 80640, 0x062f9389
+0, 270000, 80640, 0xe4dcaff8
+0, 285000, 80640, 0xb2d9ec51
+0, 300000, 80640, 0x3b4d5331
+0, 315000, 80640, 0xfcbd8da1
+0, 330000, 80640, 0xa0732142
+0, 345000, 80640, 0x6438df5f
+0, 360000, 80640, 0x614302fa
+0, 375000, 80640, 0x53edf986
+0, 390000, 80640, 0x6dfe13f0
+0, 405000, 80640, 0x0b2194c3
+0, 420000, 80640, 0xe0436945
+0, 435000, 80640, 0x8d8ba77f
+0, 450000, 80640, 0x9c723388
+0, 465000, 80640, 0x336bd2a2
+0, 480000, 80640, 0x5905fd0b
+0, 495000, 80640, 0x2ca368bb
+0, 510000, 80640, 0x38c1e5ec
+0, 525000, 80640, 0xe439a194
+0, 540000, 80640, 0xe7a19a64
+0, 555000, 80640, 0xbe7f9094
+0, 570000, 80640, 0x0b2cbec9
+0, 585000, 80640, 0x8050bf7d
+0, 600000, 80640, 0x4e9d4e78
+0, 615000, 80640, 0xaa7bb85d
+0, 630000, 80640, 0x6e42b1a6
+0, 645000, 80640, 0x27043fe0
+0, 660000, 80640, 0xe04bd5e6
+0, 675000, 80640, 0xd60762d6
+0, 690000, 80640, 0x2729df8f
+0, 705000, 80640, 0x1b62c4f7
+0, 720000, 80640, 0xe6b5d2f7
+0, 735000, 80640, 0xf5885096
+0, 750000, 80640, 0xe7625cf6
+0, 765000, 80640, 0xed804de6
+0, 780000, 80640, 0x3f92728e
+0, 795000, 80640, 0x353e4b0d
+0, 810000, 80640, 0x70b0228c
+0, 825000, 80640, 0x851bd554
+0, 840000, 80640, 0x594f22eb
+0, 855000, 80640, 0xa2267c0b
+0, 870000, 80640, 0xdc0fbafb
+0, 885000, 80640, 0xd596b763
+0, 900000, 80640, 0x3b9c4b1b
+0, 915000, 80640, 0x218ac4b4
+0, 930000, 80640, 0x4af393a4
+0, 945000, 80640, 0x66c098c5
+0, 960000, 80640, 0x7cc91e86
+0, 975000, 80640, 0xba282a2e
+0, 990000, 80640, 0x50932be6
+0, 1005000, 80640, 0x6531386e
+0, 1020000, 80640, 0x2616235f
+0, 1035000, 80640, 0x27aad18a
+0, 1050000, 80640, 0x67491df3
+0, 1065000, 80640, 0x167028f1
+0, 1080000, 80640, 0xa4229420
+0, 1095000, 80640, 0x77eaed07
+0, 1110000, 80640, 0xbdf7d8e8
+0, 1125000, 80640, 0xc2ac8545
+0, 1140000, 80640, 0xf3fe64ec
+0, 1155000, 80640, 0x66451d43
+0, 1170000, 80640, 0x1af2f05e
+0, 1185000, 80640, 0x2a63c2c4
+0, 1200000, 80640, 0xe4e07a0f
+0, 1215000, 80640, 0x598e8b11
+0, 1230000, 80640, 0xb2ebb868
+0, 1245000, 80640, 0xa4b6bb8a
+0, 1260000, 80640, 0x5037e910
+0, 1275000, 80640, 0x0c55f6c0
+0, 1290000, 80640, 0x3f4704f7
+0, 1305000, 80640, 0xa6a8e810
+0, 1320000, 80640, 0xedbfcfb0
+0, 1335000, 80640, 0xe568caa0
+0, 1350000, 80640, 0xdf21cc20
+0, 1365000, 80640, 0xb66cd4a8
+0, 1380000, 80640, 0xcd26c9c8
+0, 1395000, 80640, 0x5fe8d598
+0, 1410000, 80640, 0xed0dc9c8
+0, 1425000, 80640, 0x8313d288
+0, 1440000, 80640, 0x9ccdd4a0
+0, 1455000, 80640, 0x66ffe970
+0, 1470000, 80640, 0xf68ad1c8
+0, 1485000, 80640, 0xd570f658
+0, 1500000, 80640, 0x8c39d998
+0, 1515000, 80640, 0xe18fe5e0
+0, 1530000, 80640, 0xbbe7e340
+0, 1545000, 80640, 0x9a90d470
+0, 1560000, 80640, 0xd2bbced0
+0, 1575000, 80640, 0xbbf9dce0
+0, 1590000, 80640, 0x4ff7c888
+0, 1605000, 80640, 0xc2e7e1f0
+0, 1620000, 80640, 0x2104e3b0
+0, 1635000, 80640, 0xaef5e8f0
+0, 1650000, 80640, 0xc477e890
+0, 1665000, 80640, 0xb12df778
+0, 1680000, 80640, 0xd2115720
+0, 1695000, 80640, 0x620b6538
+0, 1710000, 80640, 0x894a8db8
+0, 1725000, 80640, 0x8da3bcb0
+0, 1740000, 80640, 0x96be8930
+0, 1755000, 80640, 0xe69dc1f0
+0, 1770000, 80640, 0x42b8d4e0
+0, 1785000, 80640, 0x0a8da4f0
+0, 1800000, 80640, 0x245fd3d8
+0, 1815000, 80640, 0x3fd1e858
+0, 1830000, 80640, 0xe2c299f0
+0, 1845000, 80640, 0xda1cddd0
+0, 1860000, 80640, 0xf126e498
+0, 1875000, 80640, 0xc85ab920
+0, 1890000, 80640, 0x52f39de8
+0, 1905000, 80640, 0xd0daac60
+0, 1920000, 80640, 0xef323347
+0, 1935000, 80640, 0xcc063317
+0, 1950000, 80640, 0xb6f53057
+0, 1965000, 80640, 0x5fe53b07
+0, 1980000, 80640, 0x63183d7f
+0, 1995000, 80640, 0x91a44bbf
+0, 2010000, 80640, 0xa433480f
+0, 2025000, 80640, 0xe90652ef
+0, 2040000, 80640, 0xe96e35bf
+0, 2055000, 80640, 0x84ff2ccf
+0, 2070000, 80640, 0x930f2b07
+0, 2085000, 80640, 0x5a1228d7
+0, 2100000, 80640, 0x29f226ef
+0, 2115000, 80640, 0xd35136df
+0, 2130000, 80640, 0x0e2d407f
+0, 2145000, 80640, 0x34a93267
+0, 2160000, 80640, 0x7ae82af7
+0, 2175000, 80640, 0xb20c2477
+0, 2190000, 80640, 0xa104218f
+0, 2205000, 80640, 0xcb1121e7
+0, 2220000, 80640, 0xaca04751
+0, 2235000, 80640, 0x3a51c704
+0, 2250000, 80640, 0xfa632e3d
+0, 2265000, 80640, 0x61c9407c
+0, 2280000, 80640, 0xe9a08dd9
+0, 2295000, 80640, 0xebf3c623
+0, 2310000, 80640, 0x00000000
+0, 2325000, 80640, 0x0f412500
+0, 2340000, 80640, 0x0f412500
+0, 2355000, 80640, 0x0f412500
+0, 2370000, 80640, 0xb6634270
+0, 2385000, 80640, 0x9e43a4a0
+0, 2400000, 80640, 0x136ab60b
+0, 2415000, 80640, 0x6ce3254e
+0, 2430000, 80640, 0xf4340d15
+0, 2445000, 80640, 0x73861114
+0, 2460000, 80640, 0x36b300d3
+0, 2475000, 80640, 0x2ddde523
+0, 2490000, 80640, 0xfdd79c02
+0, 2505000, 80640, 0xe6cc4fe9
+0, 2520000, 80640, 0x5b13e2b9
+0, 2535000, 80640, 0x0d588e70
+0, 2550000, 80640, 0xc6e4023f
+0, 2565000, 80640, 0xf54c496f
+0, 2580000, 80640, 0xa315a5cf
+0, 2595000, 80640, 0x2d2ac9c7
diff --git a/tests/ref/fate/8bps b/tests/ref/fate/8bps
index 6ee9617..30ec8c5 100644
--- a/tests/ref/fate/8bps
+++ b/tests/ref/fate/8bps
@@ -1,5 +1,5 @@
-1, 0, 2048, 0x3d042426
 0, 0, 259200, 0x7e91df07
+1, 0, 2048, 0x3d042426
 1, 4180, 2048, 0x5bcae456
 0, 7200, 259200, 0x7e91df07
 1, 8359, 2048, 0xb6043655
diff --git a/tests/ref/fate/ansi b/tests/ref/fate/ansi
new file mode 100644
index 0000000..bb9f35f
--- /dev/null
+++ b/tests/ref/fate/ansi
@@ -0,0 +1,17 @@
+0, 0, 768000, 0x3032d0de
+0, 3600, 768000, 0xc3be5922
+0, 7200, 768000, 0xf530c476
+0, 10800, 768000, 0x11c1fb8e
+0, 14400, 768000, 0x72d12da9
+0, 18000, 768000, 0x39c7a70d
+0, 21600, 768000, 0x94bd32a4
+0, 25200, 768000, 0x06dd5ba1
+0, 28800, 768000, 0x9616ec95
+0, 32400, 768000, 0x6df5b9e2
+0, 36000, 768000, 0x7be7f60a
+0, 39600, 768000, 0x2abc8623
+0, 43200, 768000, 0x5678bfff
+0, 46800, 768000, 0x24a03042
+0, 50400, 768000, 0xfb011b23
+0, 54000, 768000, 0x925ff5e9
+0, 57600, 768000, 0x890e2a56
diff --git a/tests/ref/fate/bethsoft-vid b/tests/ref/fate/bethsoft-vid
index 4c252bd..92c694b 100644
--- a/tests/ref/fate/bethsoft-vid
+++ b/tests/ref/fate/bethsoft-vid
@@ -1,5 +1,5 @@
-1, 0, 1480, 0x00000000
 0, 0, 192000, 0x00000000
+1, 0, 1480, 0x00000000
 0, 1500, 192000, 0x01a6cf45
 0, 3000, 192000, 0xd07d57e9
 0, 4500, 192000, 0x3cb1dff5
diff --git a/tests/ref/fate/bfi b/tests/ref/fate/bfi
index b0d853b..1471670 100644
--- a/tests/ref/fate/bfi
+++ b/tests/ref/fate/bfi
@@ -1,5 +1,5 @@
-1, 0, 17768, 0x07df135c
 0, 0, 134400, 0xc218b00c
+1, 0, 17768, 0x07df135c
 0, 10000, 134400, 0x114daf7c
 0, 20000, 134400, 0xe14db24c
 0, 30000, 134400, 0x88c71df7
diff --git a/tests/ref/fate/bink-demux-video b/tests/ref/fate/bink-demux-video
index 22fb3c5..f3adf76 100644
--- a/tests/ref/fate/bink-demux-video
+++ b/tests/ref/fate/bink-demux-video
@@ -13,8 +13,8 @@
 0, 72000, 460800, 0x71c0f48e
 0, 78000, 460800, 0x5fc8f783
 0, 84000, 460800, 0xd23d336a
-0, 90000, 460800, 0xa7aca9e0
-0, 96000, 460800, 0x1dff2144
-0, 102000, 460800, 0x82cf8b2b
-0, 108000, 460800, 0x4cbe3544
+0, 90000, 460800, 0xadcfa9e0
+0, 96000, 460800, 0x24222144
+0, 102000, 460800, 0x88f28b2b
+0, 108000, 460800, 0x52e13544
 0, 114000, 460800, 0x7e724731
diff --git a/tests/ref/fate/corepng b/tests/ref/fate/corepng
index 7b01e7a..2b197d2 100644
--- a/tests/ref/fate/corepng
+++ b/tests/ref/fate/corepng
@@ -1,5 +1,5 @@
-1, 0, 11026, 0x27ad637c
 0, 0, 230400, 0x03e25ead
+1, 0, 11026, 0x27ad637c
 0, 6000, 230400, 0x0a520ffd
 0, 12000, 230400, 0x0b11a671
 0, 18000, 230400, 0x7d3fce32
diff --git a/tests/ref/fate/creatureshock-avs b/tests/ref/fate/creatureshock-avs
index 54ed2f8..bd6739f 100644
--- a/tests/ref/fate/creatureshock-avs
+++ b/tests/ref/fate/creatureshock-avs
@@ -1,5 +1,5 @@
-1, 0, 16372, 0xfaaab59d
 0, 0, 188892, 0xcb5be3dd
+1, 0, 16372, 0xfaaab59d
 0, 6000, 188892, 0x0f313ebc
 0, 12000, 188892, 0xc0da25cc
 0, 18000, 188892, 0xad6e1d44
diff --git a/tests/ref/fate/dxa-scummvm b/tests/ref/fate/dxa-scummvm
new file mode 100644
index 0000000..79bc1d0
--- /dev/null
+++ b/tests/ref/fate/dxa-scummvm
@@ -0,0 +1,12 @@
+0, 0, 384000, 0xef37f34b
+0, 7500, 384000, 0xef37f34b
+0, 14999, 384000, 0xfca3cd8b
+0, 22499, 384000, 0xfca3cd8b
+0, 29999, 384000, 0x6dd34bb7
+0, 37499, 384000, 0x6dd34bb7
+0, 44998, 384000, 0xfd518717
+0, 52498, 384000, 0xfd518717
+0, 59998, 384000, 0x82db5c7b
+0, 67497, 384000, 0x82db5c7b
+0, 74997, 384000, 0xe280a5a6
+0, 82497, 384000, 0xe280a5a6
diff --git a/tests/ref/fate/fax-g3 b/tests/ref/fate/fax-g3
new file mode 100644
index 0000000..b712dd2
--- /dev/null
+++ b/tests/ref/fate/fax-g3
@@ -0,0 +1 @@
+0, 0, 1000384, 0xb758eb8b
diff --git a/tests/ref/fate/fax-g3s b/tests/ref/fate/fax-g3s
new file mode 100644
index 0000000..b712dd2
--- /dev/null
+++ b/tests/ref/fate/fax-g3s
@@ -0,0 +1 @@
+0, 0, 1000384, 0xb758eb8b
diff --git a/tests/ref/fate/feeble-dxa b/tests/ref/fate/feeble-dxa
index 3096032..9013f99 100644
--- a/tests/ref/fate/feeble-dxa
+++ b/tests/ref/fate/feeble-dxa
@@ -1,5 +1,5 @@
-1, 0, 1000, 0x64cd9403
 0, 0, 921600, 0x0d03844f
+1, 0, 1000, 0x64cd9403
 1, 4082, 1000, 0xa4ef8a9d
 1, 8163, 1000, 0x75c19868
 0, 9000, 921600, 0x0d03844f
diff --git a/tests/ref/fate/film-cvid-pcm-stereo-8bit b/tests/ref/fate/film-cvid-pcm-stereo-8bit
index ebe0fc4..3566b0f 100644
--- a/tests/ref/fate/film-cvid-pcm-stereo-8bit
+++ b/tests/ref/fate/film-cvid-pcm-stereo-8bit
@@ -1,5 +1,5 @@
-1, 0, 88192, 0x23bb50ae
 0, 0, 107520, 0xa6c9fdd2
+1, 0, 88192, 0x23bb50ae
 0, 3000, 107520, 0x61eb28c1
 0, 6000, 107520, 0x45e20af7
 0, 9000, 107520, 0x45e20af7
@@ -31,8 +31,8 @@
 0, 81000, 107520, 0xee7324f0
 0, 84000, 107520, 0xe15025b3
 0, 87000, 107520, 0xe15025b3
-1, 90000, 44112, 0x18fed048
 0, 90000, 107520, 0x8afa312e
+1, 90000, 44112, 0x18fed048
 0, 93000, 107520, 0x8afa312e
 0, 96000, 107520, 0x717a7d0f
 0, 99000, 107520, 0x717a7d0f
@@ -65,8 +65,8 @@
 0, 171000, 107520, 0x14147bd6
 0, 174000, 107520, 0x07d54bec
 0, 177000, 107520, 0x07d54bec
-1, 180000, 44112, 0xddc19d91
 0, 180000, 107520, 0xe287a0a7
+1, 180000, 44112, 0xddc19d91
 0, 183000, 107520, 0xe287a0a7
 0, 186000, 107520, 0xc023a14d
 0, 189000, 107520, 0xc023a14d
@@ -99,8 +99,8 @@
 0, 261000, 107520, 0x3e0e4d8d
 0, 264000, 107520, 0xd268865b
 0, 267000, 107520, 0xd268865b
-1, 270000, 44112, 0x99c8c3d9
 0, 270000, 107520, 0x89a4efeb
+1, 270000, 44112, 0x99c8c3d9
 0, 273000, 107520, 0x89a4efeb
 0, 276000, 107520, 0x70ca2478
 0, 279000, 107520, 0x70ca2478
@@ -133,8 +133,8 @@
 0, 351000, 107520, 0x3a1d7571
 0, 354000, 107520, 0x3a1d7571
 0, 357000, 107520, 0x3a1d7571
-1, 360000, 44112, 0x9e475274
 0, 360000, 107520, 0xe974733e
+1, 360000, 44112, 0x9e475274
 0, 363000, 107520, 0xe974733e
 0, 366000, 107520, 0x999c6fbf
 0, 369000, 107520, 0x999c6fbf
@@ -167,8 +167,8 @@
 0, 441000, 107520, 0xfce5fd07
 0, 444000, 107520, 0xd993f193
 0, 447000, 107520, 0xd993f193
-1, 450000, 44112, 0xb8f86e48
 0, 450000, 107520, 0x4d48e7b4
+1, 450000, 44112, 0xb8f86e48
 0, 453000, 107520, 0x4d48e7b4
 0, 456000, 107520, 0x61ccdf83
 0, 459000, 107520, 0x61ccdf83
@@ -201,8 +201,8 @@
 0, 531000, 107520, 0xf464c343
 0, 534000, 107520, 0xf464c343
 0, 537000, 107520, 0xf464c343
-1, 540000, 44112, 0xe0ac619f
 0, 540000, 107520, 0xf464c343
+1, 540000, 44112, 0xe0ac619f
 0, 543000, 107520, 0xf464c343
 0, 546000, 107520, 0xf2b2c712
 0, 549000, 107520, 0xf2b2c712
@@ -235,8 +235,8 @@
 0, 621000, 107520, 0x5ecc379e
 0, 624000, 107520, 0xea09432a
 0, 627000, 107520, 0xea09432a
-1, 630000, 44112, 0x00000000
 0, 630000, 107520, 0xe01e6b73
+1, 630000, 44112, 0x00000000
 0, 633000, 107520, 0xe01e6b73
 0, 636000, 107520, 0x1d13bba8
 0, 639000, 107520, 0x1d13bba8
diff --git a/tests/ref/fate/g722dec-1 b/tests/ref/fate/g722dec-1
new file mode 100644
index 0000000..4c4b2b5
--- /dev/null
+++ b/tests/ref/fate/g722dec-1
@@ -0,0 +1,167 @@
+0, 0, 4096, 0xde68394d
+0, 11520, 4096, 0xa5c28cb7
+0, 23040, 4096, 0x2e3c2f23
+0, 34560, 4096, 0xd7757825
+0, 46080, 4096, 0xafd1fd61
+0, 57600, 4096, 0x686afcbe
+0, 69120, 4096, 0x2290e848
+0, 80640, 4096, 0xddd484ad
+0, 92160, 4096, 0x148811a6
+0, 103680, 4096, 0x8b965613
+0, 115200, 4096, 0x8b095d51
+0, 126720, 4096, 0xf7625485
+0, 138240, 4096, 0x982a688c
+0, 149760, 4096, 0xc290dcfc
+0, 161280, 4096, 0x8bdef225
+0, 172800, 4096, 0xfca27fdc
+0, 184320, 4096, 0x95eff313
+0, 195840, 4096, 0x691ed4f7
+0, 207360, 4096, 0xd7e7b492
+0, 218880, 4096, 0xb0416bfe
+0, 230400, 4096, 0xf94b3ebd
+0, 241920, 4096, 0x7f73ca12
+0, 253440, 4096, 0xe91da4a3
+0, 264960, 4096, 0x1f74dc0e
+0, 276480, 4096, 0xd95b35e8
+0, 288000, 4096, 0x6dcdde1a
+0, 299520, 4096, 0x614fd4e4
+0, 311040, 4096, 0xe38d0fd5
+0, 322560, 4096, 0xfeba2999
+0, 334080, 4096, 0x1bf541e1
+0, 345600, 4096, 0x689f50d8
+0, 357120, 4096, 0x0aa60f5f
+0, 368640, 4096, 0x60ac3116
+0, 380160, 4096, 0xfa60e5e6
+0, 391680, 4096, 0xc7207c5b
+0, 403200, 4096, 0x01196277
+0, 414720, 4096, 0x609ca46c
+0, 426240, 4096, 0xfb799142
+0, 437760, 4096, 0x720910df
+0, 449280, 4096, 0xe21a8662
+0, 460800, 4096, 0x07105120
+0, 472320, 4096, 0x593f627e
+0, 483840, 4096, 0x28ddc80c
+0, 495360, 4096, 0xc69ef356
+0, 506880, 4096, 0x2defc5bd
+0, 518400, 4096, 0x82a4f418
+0, 529920, 4096, 0x424cb997
+0, 541440, 4096, 0x167a49b7
+0, 552960, 4096, 0x32a3e0d4
+0, 564480, 4096, 0x08a353ae
+0, 576000, 4096, 0x9543577b
+0, 587520, 4096, 0x2ed137cf
+0, 599040, 4096, 0xd80b0538
+0, 610560, 4096, 0x2ad31bef
+0, 622080, 4096, 0x1060cff8
+0, 633600, 4096, 0x76ab5ab8
+0, 645120, 4096, 0x8eedb68d
+0, 656640, 4096, 0xf4e2dc46
+0, 668160, 4096, 0xc52d3326
+0, 679680, 4096, 0x25201a26
+0, 691200, 4096, 0x16419378
+0, 702720, 4096, 0x97061f3c
+0, 714240, 4096, 0xd54edecd
+0, 725760, 4096, 0xc830b07b
+0, 737280, 4096, 0x804bae00
+0, 748800, 4096, 0xbb279150
+0, 760320, 4096, 0x95c4d5aa
+0, 771840, 4096, 0xc51d5259
+0, 783360, 4096, 0x856e1ab0
+0, 794880, 4096, 0x9e6ccb12
+0, 806400, 4096, 0xa2e5c1bb
+0, 817920, 4096, 0xe62fb62f
+0, 829440, 4096, 0xf10e3df0
+0, 840960, 4096, 0x76def18b
+0, 852480, 4096, 0xc9c3a26d
+0, 864000, 4096, 0x8ec0e061
+0, 875520, 4096, 0x3d4e8512
+0, 887040, 4096, 0xec45cd46
+0, 898560, 4096, 0xa34f3ddf
+0, 910080, 4096, 0x52b81c53
+0, 921600, 4096, 0xd0f0397a
+0, 933120, 4096, 0x7c0de231
+0, 944640, 4096, 0xfe86c032
+0, 956160, 4096, 0x67cdb848
+0, 967680, 4096, 0x90532cc0
+0, 979200, 4096, 0x03bca9e9
+0, 990720, 4096, 0x73169fd1
+0, 1002240, 4096, 0x0b93967d
+0, 1013760, 4096, 0x6486d8be
+0, 1025280, 4096, 0x555cc2ac
+0, 1036800, 4096, 0x07c1912e
+0, 1048320, 4096, 0xe0423c66
+0, 1059840, 4096, 0xc12d0fa1
+0, 1071360, 4096, 0xdf497c2f
+0, 1082880, 4096, 0x9298d1ba
+0, 1094400, 4096, 0x691a4e15
+0, 1105920, 4096, 0x725adc6e
+0, 1117440, 4096, 0xf68e88de
+0, 1128960, 4096, 0x37a234aa
+0, 1140480, 4096, 0x43fb0558
+0, 1152000, 4096, 0x653e4320
+0, 1163520, 4096, 0x651e2f13
+0, 1175040, 4096, 0x179049f9
+0, 1186560, 4096, 0xe02fbb9d
+0, 1198080, 4096, 0xb7e9f2a0
+0, 1209600, 4096, 0x94ee81df
+0, 1221120, 4096, 0x398a98de
+0, 1232640, 4096, 0x1267594a
+0, 1244160, 4096, 0x715adbaf
+0, 1255680, 4096, 0x28ce1a20
+0, 1267200, 4096, 0x4f8073d0
+0, 1278720, 4096, 0x536846d3
+0, 1290240, 4096, 0x7dc7defe
+0, 1301760, 4096, 0x08a28e2a
+0, 1313280, 4096, 0xd717c5cd
+0, 1324800, 4096, 0x5d6e1efd
+0, 1336320, 4096, 0x4d0eea27
+0, 1347840, 4096, 0x70fff90c
+0, 1359360, 4096, 0xd5cc8207
+0, 1370880, 4096, 0xf87cae0e
+0, 1382400, 4096, 0x26814ab5
+0, 1393920, 4096, 0x9569fb8d
+0, 1405440, 4096, 0x7835122e
+0, 1416960, 4096, 0xa38840dd
+0, 1428480, 4096, 0xfc499ba3
+0, 1440000, 4096, 0x0aa60cb0
+0, 1451520, 4096, 0x530ef56e
+0, 1463040, 4096, 0xead968db
+0, 1474560, 4096, 0x64484214
+0, 1486080, 4096, 0xfd0cc89e
+0, 1497600, 4096, 0x0d452a5d
+0, 1509120, 4096, 0x36ef8482
+0, 1520640, 4096, 0x462b641b
+0, 1532160, 4096, 0x2a5c1c0c
+0, 1543680, 4096, 0x8837ff80
+0, 1555200, 4096, 0x27a3de22
+0, 1566720, 4096, 0xf88d28c1
+0, 1578240, 4096, 0xed85ea97
+0, 1589760, 4096, 0x50c3e7db
+0, 1601280, 4096, 0x82bcb480
+0, 1612800, 4096, 0xc50ee536
+0, 1624320, 4096, 0x086280ee
+0, 1635840, 4096, 0x6f18f2b2
+0, 1647360, 4096, 0x1c7c0856
+0, 1658880, 4096, 0xc576268a
+0, 1670400, 4096, 0x7a9af56d
+0, 1681920, 4096, 0x6d058fc5
+0, 1693440, 4096, 0x8fb1107b
+0, 1704960, 4096, 0x807588d1
+0, 1716480, 4096, 0x56178443
+0, 1728000, 4096, 0xf2460763
+0, 1739520, 4096, 0x284255f2
+0, 1751040, 4096, 0xb29d17fb
+0, 1762560, 4096, 0x5e7e4633
+0, 1774080, 4096, 0x57704db1
+0, 1785600, 4096, 0xd87dcc1d
+0, 1797120, 4096, 0x28d4bb93
+0, 1808640, 4096, 0x3a2e5c6c
+0, 1820160, 4096, 0xf3581656
+0, 1831680, 4096, 0x42f1942f
+0, 1843200, 4096, 0xe75c5092
+0, 1854720, 4096, 0x3fae7f6d
+0, 1866240, 4096, 0xf99ad73e
+0, 1877760, 4096, 0x80564e3e
+0, 1889280, 4096, 0x8ff6ebe5
+0, 1900800, 4096, 0x436d5e69
+0, 1912320, 1368, 0xe0ebeda3
diff --git a/tests/ref/fate/gsm b/tests/ref/fate/gsm
new file mode 100644
index 0000000..89f87d4
--- /dev/null
+++ b/tests/ref/fate/gsm
@@ -0,0 +1,500 @@
+0, 0, 320, 0x4c32ab06
+0, 1800, 320, 0x2052a4e7
+0, 3600, 320, 0xe9aeafca
+0, 5400, 320, 0xde83b450
+0, 7200, 320, 0x06a6a80e
+0, 9000, 320, 0xf6aeb1e2
+0, 10800, 320, 0x2623b40c
+0, 12600, 320, 0x8ec69f25
+0, 14400, 320, 0xddaaac88
+0, 16200, 320, 0x9e60b713
+0, 18000, 320, 0xb738ab30
+0, 19800, 320, 0xdb4bbb92
+0, 21600, 320, 0x0370ae8b
+0, 23400, 320, 0xb611a3fb
+0, 25200, 320, 0x07ee8e3b
+0, 27000, 320, 0xdb1ec628
+0, 28800, 320, 0xd5f1bda2
+0, 30600, 320, 0xcabb9a9c
+0, 32400, 320, 0x16c8ad61
+0, 34200, 320, 0xf76fc25e
+0, 36000, 320, 0x7118a10d
+0, 37800, 320, 0x29f9a0db
+0, 39600, 320, 0x41f2a4ef
+0, 41400, 320, 0x36dfb231
+0, 43200, 320, 0xc5399eda
+0, 45000, 320, 0x17d4b9e0
+0, 46800, 320, 0x2b5797ac
+0, 48600, 320, 0x0128c5e7
+0, 50400, 320, 0xf4f38037
+0, 52200, 320, 0x77d6b5f2
+0, 54000, 320, 0xd94a93e0
+0, 55800, 320, 0x968daae3
+0, 57600, 320, 0xda5ba0ec
+0, 59400, 320, 0x316da1ec
+0, 61200, 320, 0x3a35b2d2
+0, 63000, 320, 0xca0b988f
+0, 64800, 320, 0x1295b0b1
+0, 66600, 320, 0xe121ae72
+0, 68400, 320, 0x7da7ad43
+0, 70200, 320, 0x96a49cfe
+0, 72000, 320, 0x70c2b1de
+0, 73800, 320, 0x668d88c0
+0, 75600, 320, 0x5460b5a8
+0, 77400, 320, 0x6ac78eab
+0, 79200, 320, 0x0d8dab87
+0, 81000, 320, 0xe2be94af
+0, 82800, 320, 0x3487acdc
+0, 84600, 320, 0x5048955a
+0, 86400, 320, 0x2ef4ae0d
+0, 88200, 320, 0xc765b773
+0, 90000, 320, 0xad96a486
+0, 91800, 320, 0xb9fdbf1f
+0, 93600, 320, 0xf26c9ecf
+0, 95400, 320, 0xbcadb535
+0, 97200, 320, 0xa8c897bc
+0, 99000, 320, 0xaa58b520
+0, 100800, 320, 0xcb48a716
+0, 102600, 320, 0x4d5da564
+0, 104400, 320, 0x9809ae28
+0, 106200, 320, 0x5baeb1e4
+0, 108000, 320, 0x6a719b63
+0, 109800, 320, 0xc27d92f0
+0, 111600, 320, 0x0e9b9fe9
+0, 113400, 320, 0xbf9d9bf7
+0, 115200, 320, 0xf35aa64d
+0, 117000, 320, 0x26449ce8
+0, 118800, 320, 0x58f4a997
+0, 120600, 320, 0x155da289
+0, 122400, 320, 0x63b19a5c
+0, 124200, 320, 0xe01aad38
+0, 126000, 320, 0x4e0f9c43
+0, 127800, 320, 0x9447a284
+0, 129600, 320, 0xdb36a433
+0, 131400, 320, 0x799a9b2c
+0, 133200, 320, 0x1526a162
+0, 135000, 320, 0x0a4ea140
+0, 136800, 320, 0xb08f9ed7
+0, 138600, 320, 0x221bab76
+0, 140400, 320, 0x4befacf0
+0, 142200, 320, 0xac489509
+0, 144000, 320, 0x57a1a5b4
+0, 145800, 320, 0x81e8ab97
+0, 147600, 320, 0xc6ada4d6
+0, 149400, 320, 0x12489975
+0, 151200, 320, 0x1da59ba9
+0, 153000, 320, 0xf225ac62
+0, 154800, 320, 0x8c8e9eab
+0, 156600, 320, 0x10599dec
+0, 158400, 320, 0x06c39fa5
+0, 160200, 320, 0xb0efa3c4
+0, 162000, 320, 0x72caadab
+0, 163800, 320, 0xe4619ff0
+0, 165600, 320, 0x49bca017
+0, 167400, 320, 0x413f9fbe
+0, 169200, 320, 0x6eaed0ee
+0, 171000, 320, 0x27e4b1eb
+0, 172800, 320, 0x8c42a30f
+0, 174600, 320, 0x0afaa0f4
+0, 176400, 320, 0x0f74b76b
+0, 178200, 320, 0xa9a2b9d5
+0, 180000, 320, 0xde2a8712
+0, 181800, 320, 0xcfc8b3a2
+0, 183600, 320, 0x768cadce
+0, 185400, 320, 0x3a8a97f1
+0, 187200, 320, 0x502fa59b
+0, 189000, 320, 0x4c3e9b0f
+0, 190800, 320, 0x1cd2b111
+0, 192600, 320, 0xa845a5a3
+0, 194400, 320, 0xa6b8b982
+0, 196200, 320, 0x4d5caab9
+0, 198000, 320, 0x7993b604
+0, 199800, 320, 0x8d19b37b
+0, 201600, 320, 0xbe48adb6
+0, 203400, 320, 0x7d68ab8e
+0, 205200, 320, 0xbfffb0e2
+0, 207000, 320, 0x90b5b7e3
+0, 208800, 320, 0x9fa1b016
+0, 210600, 320, 0x70abafc9
+0, 212400, 320, 0x82cfad9c
+0, 214200, 320, 0x05f6aa2c
+0, 216000, 320, 0x511cbb5b
+0, 217800, 320, 0xd27caaa6
+0, 219600, 320, 0x781ca481
+0, 221400, 320, 0x12e9ad1a
+0, 223200, 320, 0xe46b989d
+0, 225000, 320, 0x76dbb0a7
+0, 226800, 320, 0x10eba486
+0, 228600, 320, 0x2269a7c8
+0, 230400, 320, 0x084a9c7e
+0, 232200, 320, 0x84eda891
+0, 234000, 320, 0x2ef9a639
+0, 235800, 320, 0x8bb2a0dd
+0, 237600, 320, 0x47e5a169
+0, 239400, 320, 0x98faae42
+0, 241200, 320, 0x81d2aba4
+0, 243000, 320, 0x5af8bb33
+0, 244800, 320, 0x331e8d9f
+0, 246600, 320, 0xd9b0c09a
+0, 248400, 320, 0xbaf9bfcf
+0, 250200, 320, 0x54e89ab5
+0, 252000, 320, 0x1d62c1d2
+0, 253800, 320, 0xead6b436
+0, 255600, 320, 0x465f98bc
+0, 257400, 320, 0xe707a346
+0, 259200, 320, 0xf66cb1c2
+0, 261000, 320, 0xcfc89ae6
+0, 262800, 320, 0x0b10b796
+0, 264600, 320, 0xb29caf2c
+0, 266400, 320, 0x0284a9d1
+0, 268200, 320, 0xb966b5fc
+0, 270000, 320, 0x2defa630
+0, 271800, 320, 0xcdcd8ef3
+0, 273600, 320, 0xa81bba2b
+0, 275400, 320, 0x6bc0aeb1
+0, 277200, 320, 0x38d8ac82
+0, 279000, 320, 0xeb66a865
+0, 280800, 320, 0x4fff9cd9
+0, 282600, 320, 0x6819a19b
+0, 284400, 320, 0xfd7c93ce
+0, 286200, 320, 0xa7419f63
+0, 288000, 320, 0x572caacb
+0, 289800, 320, 0x918fb1de
+0, 291600, 320, 0x0088a675
+0, 293400, 320, 0x19229cf7
+0, 295200, 320, 0x827ea812
+0, 297000, 320, 0x6c258ef7
+0, 298800, 320, 0x6a89b8fe
+0, 300600, 320, 0x166c9ce0
+0, 302400, 320, 0x68b39db7
+0, 304200, 320, 0x3d5aa8ec
+0, 306000, 320, 0x25e09ff3
+0, 307800, 320, 0x759aa4ce
+0, 309600, 320, 0xe5aab0ea
+0, 311400, 320, 0xf0359e9a
+0, 313200, 320, 0x51199fff
+0, 315000, 320, 0xb04aa236
+0, 316800, 320, 0xe09da0e3
+0, 318600, 320, 0x144f98a9
+0, 320400, 320, 0x0b4e9f8d
+0, 322200, 320, 0xbb69a090
+0, 324000, 320, 0xec6e9b5b
+0, 325800, 320, 0x4f86a477
+0, 327600, 320, 0x4a179d04
+0, 329400, 320, 0x9682a375
+0, 331200, 320, 0x3c6ba55e
+0, 333000, 320, 0x50c0ab50
+0, 334800, 320, 0xe58ea907
+0, 336600, 320, 0xc5eaa021
+0, 338400, 320, 0x38859f01
+0, 340200, 320, 0x73f8a540
+0, 342000, 320, 0x395da234
+0, 343800, 320, 0x7f50b144
+0, 345600, 320, 0x45568ceb
+0, 347400, 320, 0xd0508dec
+0, 349200, 320, 0x60aba7e4
+0, 351000, 320, 0x4b24b15f
+0, 352800, 320, 0xbfc9afd6
+0, 354600, 320, 0xf0f2ad49
+0, 356400, 320, 0xeea0a426
+0, 358200, 320, 0xff07a7c9
+0, 360000, 320, 0xce1fc788
+0, 361800, 320, 0xc074ae9b
+0, 363600, 320, 0x51649696
+0, 365400, 320, 0x24399744
+0, 367200, 320, 0xfb0eb920
+0, 369000, 320, 0x3bf8af5c
+0, 370800, 320, 0xeab69ee0
+0, 372600, 320, 0x182696bb
+0, 374400, 320, 0x36e6af72
+0, 376200, 320, 0x48cc9ecc
+0, 378000, 320, 0xfb3ca7b8
+0, 379800, 320, 0xe01aa4b4
+0, 381600, 320, 0x5c6dac8c
+0, 383400, 320, 0x072fbd93
+0, 385200, 320, 0xc8899ccc
+0, 387000, 320, 0xdcc990ac
+0, 388800, 320, 0x28e0a9d0
+0, 390600, 320, 0x0cdbaa11
+0, 392400, 320, 0x8f4ca093
+0, 394200, 320, 0x7ee79ea9
+0, 396000, 320, 0xa762b695
+0, 397800, 320, 0x9af0b5da
+0, 399600, 320, 0x1f2cb0e7
+0, 401400, 320, 0x6029b8bb
+0, 403200, 320, 0xf2f7acec
+0, 405000, 320, 0xb3e5b5be
+0, 406800, 320, 0x266ba8a6
+0, 408600, 320, 0x4ff59296
+0, 410400, 320, 0x11d1b9ac
+0, 412200, 320, 0x749197f7
+0, 414000, 320, 0x8192b517
+0, 415800, 320, 0xde129dbe
+0, 417600, 320, 0x85e4a096
+0, 419400, 320, 0xdebf9182
+0, 421200, 320, 0x7a4ba0bf
+0, 423000, 320, 0x55fe9fcd
+0, 424800, 320, 0xd242adec
+0, 426600, 320, 0xeaf5b159
+0, 428400, 320, 0xfcb1a571
+0, 430200, 320, 0x62fabda0
+0, 432000, 320, 0x45a9abcc
+0, 433800, 320, 0x07af974b
+0, 435600, 320, 0xc2a0b4fd
+0, 437400, 320, 0xc30abccd
+0, 439200, 320, 0xd33ca61c
+0, 441000, 320, 0x3c33d11a
+0, 442800, 320, 0x9c2ca0ac
+0, 444600, 320, 0xa5d69777
+0, 446400, 320, 0xb7d2c6b8
+0, 448200, 320, 0x34bbaab9
+0, 450000, 320, 0x3e7baccb
+0, 451800, 320, 0x92c6b7e6
+0, 453600, 320, 0xc810a18a
+0, 455400, 320, 0x06a09f56
+0, 457200, 320, 0x8804a504
+0, 459000, 320, 0x783ba7d5
+0, 460800, 320, 0x24dcada6
+0, 462600, 320, 0x4af796be
+0, 464400, 320, 0x1454b19c
+0, 466200, 320, 0x0ad0a56e
+0, 468000, 320, 0x8944a44e
+0, 469800, 320, 0x31069ebd
+0, 471600, 320, 0x19cb9812
+0, 473400, 320, 0xac75abe2
+0, 475200, 320, 0x0162a200
+0, 477000, 320, 0xa2d7a4b2
+0, 478800, 320, 0x078ca611
+0, 480600, 320, 0x0ec39b40
+0, 482400, 320, 0xe8f794b2
+0, 484200, 320, 0xc2cfb258
+0, 486000, 320, 0xe4759061
+0, 487800, 320, 0xb1b6aea4
+0, 489600, 320, 0x9bfb96df
+0, 491400, 320, 0xcc61b5d3
+0, 493200, 320, 0xd14e8df9
+0, 495000, 320, 0xd9d5bbf5
+0, 496800, 320, 0x4d9fa9b0
+0, 498600, 320, 0xf606abfc
+0, 500400, 320, 0x720baa19
+0, 502200, 320, 0x7f7cac49
+0, 504000, 320, 0xceab9b54
+0, 505800, 320, 0x645fa70a
+0, 507600, 320, 0xa081a40f
+0, 509400, 320, 0x21d78f8c
+0, 511200, 320, 0xedf3abc6
+0, 513000, 320, 0x17679637
+0, 514800, 320, 0x1cb1ae04
+0, 516600, 320, 0x17cd9f62
+0, 518400, 320, 0xf4bca3ab
+0, 520200, 320, 0xb3bd9152
+0, 522000, 320, 0x4e1e9825
+0, 523800, 320, 0x037e9a56
+0, 525600, 320, 0xd7589fcc
+0, 527400, 320, 0x5f949e90
+0, 529200, 320, 0xe133a495
+0, 531000, 320, 0x7cb7a52c
+0, 532800, 320, 0xb8b29d95
+0, 534600, 320, 0x01bca472
+0, 536400, 320, 0xbcc69895
+0, 538200, 320, 0xabffa0ee
+0, 540000, 320, 0xe6629eca
+0, 541800, 320, 0x572da7cd
+0, 543600, 320, 0x3017972d
+0, 545400, 320, 0xac4e9c78
+0, 547200, 320, 0x112f9c45
+0, 549000, 320, 0x05e9a64d
+0, 550800, 320, 0x8f7394d4
+0, 552600, 320, 0xbaeea07e
+0, 554400, 320, 0xd757c00e
+0, 556200, 320, 0x8aa09783
+0, 558000, 320, 0x31d4ae7a
+0, 559800, 320, 0x221493e8
+0, 561600, 320, 0x92f4a3a7
+0, 563400, 320, 0xbd5bafd9
+0, 565200, 320, 0x1895b760
+0, 567000, 320, 0x7a4eacdd
+0, 568800, 320, 0xc9f7a1c3
+0, 570600, 320, 0xd750be06
+0, 572400, 320, 0x641d9a6f
+0, 574200, 320, 0x70d6b6ff
+0, 576000, 320, 0x1fd3a546
+0, 577800, 320, 0x72cfaabe
+0, 579600, 320, 0x2e61b6ce
+0, 581400, 320, 0x4813a091
+0, 583200, 320, 0xbfe7bc0f
+0, 585000, 320, 0x8c759c1f
+0, 586800, 320, 0xf4c1c952
+0, 588600, 320, 0x00fdaa79
+0, 590400, 320, 0x2ffda252
+0, 592200, 320, 0x841aa523
+0, 594000, 320, 0x8c079e5e
+0, 595800, 320, 0x96e9a83f
+0, 597600, 320, 0x5926a639
+0, 599400, 320, 0x02e1a07b
+0, 601200, 320, 0x2972a999
+0, 603000, 320, 0x30c89c62
+0, 604800, 320, 0x83f5a263
+0, 606600, 320, 0xa3909667
+0, 608400, 320, 0xd5309fd4
+0, 610200, 320, 0x3154a571
+0, 612000, 320, 0x51039a5e
+0, 613800, 320, 0xf167a344
+0, 615600, 320, 0x8e709d7d
+0, 617400, 320, 0x936fa0fd
+0, 619200, 320, 0x024b9e3c
+0, 621000, 320, 0x2ea1aa75
+0, 622800, 320, 0x33f0a2bb
+0, 624600, 320, 0xbf079d2d
+0, 626400, 320, 0x847ba2c8
+0, 628200, 320, 0x37e1a767
+0, 630000, 320, 0xb607acbb
+0, 631800, 320, 0x1288ac6d
+0, 633600, 320, 0xf60e98b3
+0, 635400, 320, 0xc6b5abdd
+0, 637200, 320, 0x7feaa710
+0, 639000, 320, 0x77329fcd
+0, 640800, 320, 0x91a6a715
+0, 642600, 320, 0xd0e99f24
+0, 644400, 320, 0x07089f61
+0, 646200, 320, 0x2bbda900
+0, 648000, 320, 0xad3da0d5
+0, 649800, 320, 0x997ba6d2
+0, 651600, 320, 0xb15b9dcb
+0, 653400, 320, 0x17cea82f
+0, 655200, 320, 0xab51a73e
+0, 657000, 320, 0x77a1abd6
+0, 658800, 320, 0x0bddacad
+0, 660600, 320, 0x43b3bdc4
+0, 662400, 320, 0xefe0a9ba
+0, 664200, 320, 0x8eb4bc2f
+0, 666000, 320, 0x39cdc190
+0, 667800, 320, 0x1ef3baff
+0, 669600, 320, 0x1a6ab7e2
+0, 671400, 320, 0x444ccc69
+0, 673200, 320, 0x05ebb598
+0, 675000, 320, 0x4ac5b0ad
+0, 676800, 320, 0x0ee5ba52
+0, 678600, 320, 0x501d9fa0
+0, 680400, 320, 0x2038a9f4
+0, 682200, 320, 0xa61cb8b3
+0, 684000, 320, 0xdd009777
+0, 685800, 320, 0x2a2db86d
+0, 687600, 320, 0xe9bab3bc
+0, 689400, 320, 0xf7f8a056
+0, 691200, 320, 0x514caf14
+0, 693000, 320, 0xa220b149
+0, 694800, 320, 0xbf7ea183
+0, 696600, 320, 0x1d8dc5c6
+0, 698400, 320, 0x9182a8ea
+0, 700200, 320, 0x31eba026
+0, 702000, 320, 0xcfbcc3df
+0, 703800, 320, 0x3d8cb7ae
+0, 705600, 320, 0xbe39aec0
+0, 707400, 320, 0xd236bf71
+0, 709200, 320, 0x9377b0b2
+0, 711000, 320, 0xb5e6b2df
+0, 712800, 320, 0xa3b9bbce
+0, 714600, 320, 0xa7bda251
+0, 716400, 320, 0xbf9ab162
+0, 718200, 320, 0x6928b9cb
+0, 720000, 320, 0xf5cca209
+0, 721800, 320, 0xfdf4afad
+0, 723600, 320, 0xe7e7c216
+0, 725400, 320, 0x0c5797c6
+0, 727200, 320, 0x66c1a9ca
+0, 729000, 320, 0x6b5ca48d
+0, 730800, 320, 0xec04968a
+0, 732600, 320, 0xaaada691
+0, 734400, 320, 0x77c3a624
+0, 736200, 320, 0xaed9a5d5
+0, 738000, 320, 0x360fac41
+0, 739800, 320, 0xa05ea727
+0, 741600, 320, 0x9f7b9f83
+0, 743400, 320, 0x474bc4c2
+0, 745200, 320, 0xb6078d3b
+0, 747000, 320, 0x8e15a8f9
+0, 748800, 320, 0x7dc7d4a8
+0, 750600, 320, 0x55ceab6b
+0, 752400, 320, 0x982cc94f
+0, 754200, 320, 0x6153948f
+0, 756000, 320, 0x5338c621
+0, 757800, 320, 0x2e2db6e8
+0, 759600, 320, 0x28e3a9c3
+0, 761400, 320, 0x74d7b435
+0, 763200, 320, 0xcf17a10c
+0, 765000, 320, 0xf1f9ac8c
+0, 766800, 320, 0x35e0b480
+0, 768600, 320, 0x5e60b3a4
+0, 770400, 320, 0x20579b26
+0, 772200, 320, 0x3e27b89b
+0, 774000, 320, 0x02e4af94
+0, 775800, 320, 0x6d6897f1
+0, 777600, 320, 0x1582b267
+0, 779400, 320, 0x33ba9eb3
+0, 781200, 320, 0xb6acad7d
+0, 783000, 320, 0x1969a6c2
+0, 784800, 320, 0x363fa350
+0, 786600, 320, 0xae50bf65
+0, 788400, 320, 0x0877a50f
+0, 790200, 320, 0x66e2a42f
+0, 792000, 320, 0x0b0abcb3
+0, 793800, 320, 0x23a9afaa
+0, 795600, 320, 0xc3729b40
+0, 797400, 320, 0xdd3fc7e2
+0, 799200, 320, 0x7e0494af
+0, 801000, 320, 0xcbd096fb
+0, 802800, 320, 0x5d71b303
+0, 804600, 320, 0xeedca04a
+0, 806400, 320, 0x2836a47d
+0, 808200, 320, 0x7237c2a0
+0, 810000, 320, 0x7c009bc0
+0, 811800, 320, 0xc9dcb366
+0, 813600, 320, 0x4993aac8
+0, 815400, 320, 0x05ec9954
+0, 817200, 320, 0xa955bd5c
+0, 819000, 320, 0x9018aea3
+0, 820800, 320, 0x780cca52
+0, 822600, 320, 0x9b8f95f6
+0, 824400, 320, 0xcd7bb178
+0, 826200, 320, 0xfec6b443
+0, 828000, 320, 0xe214abb6
+0, 829800, 320, 0xdcbebb38
+0, 831600, 320, 0xe683a30d
+0, 833400, 320, 0xe4cdb197
+0, 835200, 320, 0xa426c432
+0, 837000, 320, 0x761ba6cc
+0, 838800, 320, 0xcc9aa6aa
+0, 840600, 320, 0x742bd03d
+0, 842400, 320, 0x61d9a511
+0, 844200, 320, 0x3021a4dd
+0, 846000, 320, 0x6970bbc0
+0, 847800, 320, 0x76f5a037
+0, 849600, 320, 0x758d91f2
+0, 851400, 320, 0xe854a2f1
+0, 853200, 320, 0xf994a6f8
+0, 855000, 320, 0x31ebaf40
+0, 856800, 320, 0x24699970
+0, 858600, 320, 0x37dda53e
+0, 860400, 320, 0xa857a752
+0, 862200, 320, 0xc483ad1d
+0, 864000, 320, 0x5966add9
+0, 865800, 320, 0x4dbab89c
+0, 867600, 320, 0x2f0bb0e6
+0, 869400, 320, 0x913aaa88
+0, 871200, 320, 0x245dc1c3
+0, 873000, 320, 0xb085c5ad
+0, 874800, 320, 0x9cf1b0fa
+0, 876600, 320, 0x6887b543
+0, 878400, 320, 0xcad69feb
+0, 880200, 320, 0xc12a8ddb
+0, 882000, 320, 0x01d1bc5a
+0, 883800, 320, 0x3018b7e8
+0, 885600, 320, 0x6431b0ef
+0, 887400, 320, 0x3a53998e
+0, 889200, 320, 0x1c80a6c6
+0, 891000, 320, 0x6639adc5
+0, 892800, 320, 0x92489f9a
+0, 894600, 320, 0x8cafad00
+0, 896400, 320, 0xca0392e1
+0, 898200, 320, 0x30a9ae88
diff --git a/tests/ref/fate/gsm-ms b/tests/ref/fate/gsm-ms
new file mode 100644
index 0000000..76a6f29
--- /dev/null
+++ b/tests/ref/fate/gsm-ms
@@ -0,0 +1,89 @@
+0, 0, 640, 0xf79c59ee
+0, 3600, 640, 0x6e6248be
+0, 7200, 640, 0x2a5b3aed
+0, 10800, 640, 0xf7012e06
+0, 14400, 640, 0x626645cd
+0, 18000, 640, 0x9f482b66
+0, 21600, 640, 0xea443886
+0, 25200, 640, 0xa79b3dc0
+0, 28800, 640, 0x0161263f
+0, 32400, 640, 0x61b33154
+0, 36000, 640, 0xf7fa388c
+0, 39600, 640, 0xb63038e9
+0, 43200, 640, 0x61b03506
+0, 46800, 640, 0xed4e2eac
+0, 50400, 640, 0x9b8127f1
+0, 54000, 640, 0xe50627be
+0, 57600, 640, 0x6b5038f9
+0, 61200, 640, 0x8e794c10
+0, 64800, 640, 0x426d2c93
+0, 68400, 640, 0x9a373111
+0, 72000, 640, 0x94132ccb
+0, 75600, 640, 0x610b3788
+0, 79200, 640, 0x27204206
+0, 82800, 640, 0xbdf82268
+0, 86400, 640, 0x2e653066
+0, 90000, 640, 0xccfd2328
+0, 93600, 640, 0xf2431e04
+0, 97200, 640, 0x7b412094
+0, 100800, 640, 0x5c2635fa
+0, 104400, 640, 0xdcbd2c60
+0, 108000, 640, 0x65173699
+0, 111600, 640, 0xbcff19ed
+0, 115200, 640, 0xf5b2206c
+0, 118800, 640, 0x587e460c
+0, 122400, 640, 0x2418382d
+0, 126000, 640, 0xbfad2f9b
+0, 129600, 640, 0x87d92d6c
+0, 133200, 640, 0xdc582c69
+0, 136800, 640, 0xcfe52ebf
+0, 140400, 640, 0xe0032e70
+0, 144000, 640, 0xf8a61b57
+0, 147600, 640, 0xa9ef2ee5
+0, 151200, 640, 0x7f513313
+0, 154800, 640, 0x93731177
+0, 158400, 640, 0xed2c2340
+0, 162000, 640, 0x85b02913
+0, 165600, 640, 0xa5a92f3e
+0, 169200, 640, 0x72472490
+0, 172800, 640, 0x856231fc
+0, 176400, 640, 0xda2e3c22
+0, 180000, 640, 0xcce84c36
+0, 183600, 640, 0x39312c78
+0, 187200, 640, 0xf1aa2365
+0, 190800, 640, 0x1dba3f7e
+0, 194400, 640, 0x21953579
+0, 198000, 640, 0xbbd52c22
+0, 201600, 640, 0x45c71537
+0, 205200, 640, 0x26051cec
+0, 208800, 640, 0x27ae223e
+0, 212400, 640, 0x223c0bb8
+0, 216000, 640, 0xc5b72796
+0, 219600, 640, 0xe7fd294d
+0, 223200, 640, 0x19042293
+0, 226800, 640, 0xa6572c6b
+0, 230400, 640, 0x58ac1d16
+0, 234000, 640, 0xd0631bd6
+0, 237600, 640, 0xe74f276c
+0, 241200, 640, 0x87d0295f
+0, 244800, 640, 0x054e3dc8
+0, 248400, 640, 0x0ca51c2d
+0, 252000, 640, 0x17a02616
+0, 255600, 640, 0x56b2235d
+0, 259200, 640, 0x1cd93302
+0, 262800, 640, 0xe3672352
+0, 266400, 640, 0xc99f2e45
+0, 270000, 640, 0x36a43e9d
+0, 273600, 640, 0xfcd73e87
+0, 277200, 640, 0x813b2e20
+0, 280800, 640, 0x8f7a4cac
+0, 284400, 640, 0xcf3e4106
+0, 288000, 640, 0x8a752b07
+0, 291600, 640, 0xe5013dcd
+0, 295200, 640, 0xda4a3d03
+0, 298800, 640, 0x05ce2c64
+0, 302400, 640, 0x1e0f42b5
+0, 306000, 640, 0xe4bd326a
+0, 309600, 640, 0x701c28de
+0, 313200, 640, 0xd0b02f97
+0, 316800, 640, 0x7950419b
diff --git a/tests/ref/fate/h264-extreme-plane-pred b/tests/ref/fate/h264-extreme-plane-pred
new file mode 100644
index 0000000..d8bee85
--- /dev/null
+++ b/tests/ref/fate/h264-extreme-plane-pred
@@ -0,0 +1,100 @@
+0, 0, 152064, 1e857d2dfeea75297e090ffe9e37a249
+0, 3600, 152064, 29d8336b4e9b77298025074dbad641d1
+0, 7200, 152064, 3f1a87d2088a7708f4ed06890c8cd018
+0, 10800, 152064, 56b8b8d9fefbd501c4f7918f21f9b015
+0, 14400, 152064, 597392c162ea79af1e5d3dd552ffeb47
+0, 18000, 152064, 064fdd170aa24463409b1cb0ddc7f5b6
+0, 21600, 152064, 9924da4026b10110fa644039e73f92c1
+0, 25200, 152064, afdb77f4a4c87faaf35988bf2d1d7c18
+0, 28800, 152064, 80714dc3bf376f38c00f8c67fc534fae
+0, 32400, 152064, fb0ab4028e1e9879b0bf0e414c0ccb33
+0, 36000, 152064, 03c694f4b9e6116214078131f3edff91
+0, 39600, 152064, 22d2de0d8f9e5477230b50c50ec46269
+0, 43200, 152064, 470e9a6c5bbb15e151afbfd6b2f254a3
+0, 46800, 152064, b585555552169640b1a896094335b624
+0, 50400, 152064, e261e0f650e6d649a35773520e7f5bff
+0, 54000, 152064, 2d1bf889eef057016e473a041fbceac0
+0, 57600, 152064, b1a3f8ebf1de26bc8c32d47a4a53c862
+0, 61200, 152064, d5cdb80386dbb996ca007a0e210a9905
+0, 64800, 152064, 05a200df7b8baa19d2a0309476727dd7
+0, 68400, 152064, 890d62163f4aa70a2055d50de0395a35
+0, 72000, 152064, c00bdd1c5f0d69bae66ba46a897ad0ad
+0, 75600, 152064, 65f76c6d453822eb48b180ac630cbdce
+0, 79200, 152064, d6b85fc02c6d8efa53a9f0f148a0520e
+0, 82800, 152064, adcb1621c5100b8e201592328bcd11be
+0, 86400, 152064, bad7da936734cf4304c1564d6d3e74b9
+0, 90000, 152064, a98d1232d0c22e6967415700d980c67f
+0, 93600, 152064, 3fa1110c3ada7d37f0495a26774a58fb
+0, 97200, 152064, 37613c65cfd3d77e8dda3b5b913e467f
+0, 100800, 152064, 42a5cf583a82e722e04c04b10fd36542
+0, 104400, 152064, 41c2870e102e3584780cd0243baa1900
+0, 108000, 152064, da389397c874f5fd974c57278bd1e327
+0, 111600, 152064, 238c265971ef9144d3fe6bc95a2ea060
+0, 115200, 152064, 085c83a54aa9327e1e3ee76ffa337538
+0, 118800, 152064, f462966f59018b39c10f9a65a80a41f8
+0, 122400, 152064, 6e9697b7c8193b38551af4ef56861b7a
+0, 126000, 152064, e68113abf3e81a28cafd95d91871886e
+0, 129600, 152064, 35a78df5ac1ff6ee469626b750241c9b
+0, 133200, 152064, b3302a87e334634a9f92ce51acf96ab3
+0, 136800, 152064, 52198528552cefe90004a2b045b33e8f
+0, 140400, 152064, 12d9ad991d4bb7935342c8b6474d1726
+0, 144000, 152064, 2e6a508aba965f292c7b2e82bd0debbe
+0, 147600, 152064, 8daff69112bb5fbc0158cbbf7fbe057e
+0, 151200, 152064, 5495a0bb6c88a115957d98b272b0d643
+0, 154800, 152064, 955db92ab0c482381200247a207e12bc
+0, 158400, 152064, c0f81c5f95fd658c153798a514fedd22
+0, 162000, 152064, 3cfc7b9c2d73621cdb04d7e7e8bc2b3b
+0, 165600, 152064, e8b6d1d526d6443cba2e64ccd5393a4f
+0, 169200, 152064, 7722e2420db0279c9eb7c6f7dfa89c07
+0, 172800, 152064, 41b908a50b97a2e927f2e6e285e27592
+0, 176400, 152064, e05f0ddd08debc2a0578893662c33ce0
+0, 180000, 152064, 1edcedca921dbb68c0ce53371abddd8f
+0, 183600, 152064, cdbf0c89feb336e58472f0163e43b02b
+0, 187200, 152064, 39c4d20ecfeee09800feae5ad783e0bd
+0, 190800, 152064, f60d05d20b3f338aa5917490d2b58f77
+0, 194400, 152064, 76e5eae7a5205f6f6aaf8099197dbb1f
+0, 198000, 152064, f7c4c80e79b691826915b7810ab7c2a6
+0, 201600, 152064, afbc098dcaa8c2a3f41dfc3e846e8e7b
+0, 205200, 152064, 6582805bbe4ab9a9138a23deb2ca45a8
+0, 208800, 152064, 54444ce52dd1ce7bc24e9cbaba89dc59
+0, 212400, 152064, c81193469c0cd5a50c451d869e07a786
+0, 216000, 152064, 89f2295b63db3adce2961630569749a5
+0, 219600, 152064, 3f4d6dd4dd819168a358384d6b134d00
+0, 223200, 152064, 45d3b5c72609a15c1be5a45f790a24c4
+0, 226800, 152064, f2283a8bf9599754d2e251c5f0861199
+0, 230400, 152064, 06a9ccf8132c494884954bb4cc148c11
+0, 234000, 152064, e20e0143fc840db46a88a8556d887ea2
+0, 237600, 152064, bcb1ca471f70109293a15b7e1b0f3a7f
+0, 241200, 152064, 0c5f59f091b3fd5ced9bb626e5b66ec8
+0, 244800, 152064, 4dd6cf80daf74390afe0423f726c2fb6
+0, 248400, 152064, fd52e6d570960cf100ac7c973dbd222e
+0, 252000, 152064, 684758faa9b5517b2e5dbbabccc6125b
+0, 255600, 152064, e538a3bcb2125c8ac324a5be49470960
+0, 259200, 152064, 0c91795b7f52e942a1c28b4c6510c6fa
+0, 262800, 152064, b33315c61d714bd70d2adce3309633fe
+0, 266400, 152064, af2554b6b1d3f215641f85494a78ad3d
+0, 270000, 152064, e59b20b3b2c5ec215ea34ab4850f940e
+0, 273600, 152064, fb543e874bdd9749aaa710d1551e0ebd
+0, 277200, 152064, 4383abaf938da0282fecabed153bca0e
+0, 280800, 152064, 4ce40ffa75b42320593e40596c34862a
+0, 284400, 152064, f337d0cc81b5c1b1b92c3f367ed5f9cd
+0, 288000, 152064, 0f5a8c41fb7334811a485239d9126808
+0, 291600, 152064, 0daf3d981474940bdf10a93148d69353
+0, 295200, 152064, 21a51f1686071a6af7973df92361964b
+0, 298800, 152064, 1f0d471c7b1fa86f236c2dee32822464
+0, 302400, 152064, cedc6fd29d67976f899a6a8afba6b38d
+0, 306000, 152064, 4af936d3d3b456953c7beb551476824a
+0, 309600, 152064, bcaf539953adb1952fefc2cdec6c2f60
+0, 313200, 152064, d1dfeafa0939fddc256986c2b00f73c7
+0, 316800, 152064, 99c9a2c7b198e2c8cfe007ff4330f036
+0, 320400, 152064, 4db6a7edfc44389536983aeeb15edb66
+0, 324000, 152064, 8d840674b90e3b488a34e04645430ee7
+0, 327600, 152064, ad7b3e55a2eb62fc5102cc5af49301aa
+0, 331200, 152064, f24484a975ec64acb50df3e9f9e8eddd
+0, 334800, 152064, 5794617c7e40bfcb7f024bda2f2a991d
+0, 338400, 152064, ae1c22fcfa7f3b3b62dd2ace4e4b4dc7
+0, 342000, 152064, ad9d13345ae5322a578e43653e9a9c16
+0, 345600, 152064, be1b86ee130ea9255d9640117559818d
+0, 349200, 152064, 81ed195d2831e62fc2cd4fa886de8e20
+0, 352800, 152064, 8dde0af730b03ea8b3acd14d42daba04
+0, 356400, 152064, c8ffbd5ba1af8b881daf511e4d8c26f3
diff --git a/tests/ref/fate/h264-interlace-crop b/tests/ref/fate/h264-interlace-crop
new file mode 100644
index 0000000..2202c08
--- /dev/null
+++ b/tests/ref/fate/h264-interlace-crop
@@ -0,0 +1,3 @@
+0, 0, 345600, 0xa9cb7e5a
+0, 3600, 345600, 0x73e47555
+0, 7200, 345600, 0x87aac593
diff --git a/tests/ref/fate/h264-lossless b/tests/ref/fate/h264-lossless
new file mode 100644
index 0000000..c6659ca
--- /dev/null
+++ b/tests/ref/fate/h264-lossless
@@ -0,0 +1,10 @@
+0, 0, 460800, 0x7731dd2f
+0, 1500, 460800, 0x944b8c64
+0, 3000, 460800, 0xbe833041
+0, 4500, 460800, 0xbe95d96a
+0, 6000, 460800, 0xfe7ea5e6
+0, 7500, 460800, 0x381743c7
+0, 9000, 460800, 0x63fcc2e9
+0, 10500, 460800, 0x79574960
+0, 12000, 460800, 0xdab9e18a
+0, 13500, 460800, 0xd88e8fe8
diff --git a/tests/ref/fate/idroq-video-dpcm b/tests/ref/fate/idroq-video-dpcm
index cad87fe..7e0a10e 100644
--- a/tests/ref/fate/idroq-video-dpcm
+++ b/tests/ref/fate/idroq-video-dpcm
@@ -1,5 +1,5 @@
-1, 0, 29824, 0x77e265b7
 0, 0, 393216, 0x56995aac
+1, 0, 29824, 0x77e265b7
 0, 3000, 393216, 0xf9ed5d6c
 0, 6000, 393216, 0xd3285d75
 0, 9000, 393216, 0x82d15d62
diff --git a/tests/ref/fate/interplay-mve-16bit b/tests/ref/fate/interplay-mve-16bit
index 2d22cca..74f0b35 100644
--- a/tests/ref/fate/interplay-mve-16bit
+++ b/tests/ref/fate/interplay-mve-16bit
@@ -1,5 +1,5 @@
-1, 0, 5788, 0x916d2db8
 0, 0, 614400, 0x00000000
+1, 0, 5788, 0x916d2db8
 1, 2953, 5888, 0xc65cb069
 0, 3002, 614400, 0x00000000
 1, 5957, 5888, 0xd8ec1acc
diff --git a/tests/ref/fate/interplay-mve-8bit b/tests/ref/fate/interplay-mve-8bit
index 0b41f35..13959c3 100644
--- a/tests/ref/fate/interplay-mve-8bit
+++ b/tests/ref/fate/interplay-mve-8bit
@@ -1,5 +1,5 @@
-1, 0, 5848, 0xea04292b
 0, 0, 414720, 0xa5cd50ca
+1, 0, 5848, 0xea04292b
 1, 5967, 5888, 0x0e59e942
 0, 6006, 414720, 0x3facd321
 1, 11976, 5888, 0x56d480f6
diff --git a/tests/ref/fate/lmlm4-demux b/tests/ref/fate/lmlm4-demux
index 8ecf4b2..f322300 100644
--- a/tests/ref/fate/lmlm4-demux
+++ b/tests/ref/fate/lmlm4-demux
@@ -1,5 +1,5 @@
-1, 0, 768, 0xaebcbebb
 0, 0, 5951, 0xe9118e0d
+1, 0, 768, 0xaebcbebb
 1, 2160, 768, 0xaebcbebb
 0, 3003, 1672, 0x4b80d4ca
 1, 4320, 768, 0xaebcbebb
diff --git a/tests/ref/fate/mjpegb b/tests/ref/fate/mjpegb
new file mode 100644
index 0000000..f2d0ec8
--- /dev/null
+++ b/tests/ref/fate/mjpegb
@@ -0,0 +1,10 @@
+0, 0, 38400, 0x45311080
+0, 7500, 38400, 0x9474f731
+0, 15000, 38400, 0x429ebb12
+0, 22500, 38400, 0x472c199a
+0, 30000, 38400, 0xefd49dae
+0, 37500, 38400, 0x78627fa9
+0, 45000, 38400, 0x2a8d9148
+0, 52500, 38400, 0x21cc6738
+0, 60000, 38400, 0x0bc4703f
+0, 67500, 38400, 0x1ddcc035
diff --git a/tests/ref/fate/mpeg2-field-enc b/tests/ref/fate/mpeg2-field-enc
new file mode 100644
index 0000000..1ea05bd
--- /dev/null
+++ b/tests/ref/fate/mpeg2-field-enc
@@ -0,0 +1,39 @@
+0, 0, 622080, 0xb3b66c5c
+0, 3600, 622080, 0xb3b66c5c
+0, 7200, 622080, 0xb3b66c5c
+0, 10800, 622080, 0xb3b66c5c
+0, 14400, 622080, 0xb3b66c5c
+0, 18000, 622080, 0xb3b66c5c
+0, 21600, 622080, 0xb3b66c5c
+0, 25200, 622080, 0xb3b66c5c
+0, 28800, 622080, 0xb3b66c5c
+0, 32400, 622080, 0x088ec02b
+0, 36000, 622080, 0x7a36db21
+0, 39600, 622080, 0x541b286f
+0, 43200, 622080, 0xb6c3e590
+0, 46800, 622080, 0x39dbed51
+0, 50400, 622080, 0x973dc728
+0, 54000, 622080, 0xd7a4f804
+0, 57600, 622080, 0xa2484762
+0, 61200, 622080, 0x0cd268d1
+0, 64800, 622080, 0x72eb663d
+0, 68400, 622080, 0x8fdbac59
+0, 72000, 622080, 0xa6f4feb9
+0, 75600, 622080, 0xadb828c6
+0, 79200, 622080, 0xea630a63
+0, 82800, 622080, 0xa901d925
+0, 86400, 622080, 0xac5e7087
+0, 90000, 622080, 0x10274a2b
+0, 93600, 622080, 0x143d541c
+0, 97200, 622080, 0xee94c93a
+0, 100800, 622080, 0xca030208
+0, 104400, 622080, 0x26f30ead
+0, 108000, 622080, 0xfc22f32c
+0, 111600, 622080, 0x940a5ff8
+0, 115200, 622080, 0x2164f805
+0, 118800, 622080, 0xa76f5aba
+0, 122400, 622080, 0x8c311471
+0, 126000, 622080, 0xa45e1d95
+0, 129600, 622080, 0x6cc61d6c
+0, 133200, 622080, 0x6983b417
+0, 136800, 622080, 0x982363c0
diff --git a/tests/ref/fate/msmpeg4v1 b/tests/ref/fate/msmpeg4v1
new file mode 100644
index 0000000..d6fea22
--- /dev/null
+++ b/tests/ref/fate/msmpeg4v1
@@ -0,0 +1,50 @@
+0, 0, 126720, 0x84284323
+0, 3003, 126720, 0x336fe236
+0, 6006, 126720, 0x901f1299
+0, 9009, 126720, 0x3b8be5fe
+0, 12012, 126720, 0x6da06397
+0, 15015, 126720, 0xe83de744
+0, 18018, 126720, 0xef2ed2bb
+0, 21021, 126720, 0x3ed1797f
+0, 24024, 126720, 0xf8c81785
+0, 27027, 126720, 0xf38239e0
+0, 30030, 126720, 0x005a2d6d
+0, 33033, 126720, 0xd6be525d
+0, 36036, 126720, 0x39482727
+0, 39039, 126720, 0xc8d95bc5
+0, 42042, 126720, 0xbaebd1e7
+0, 45045, 126720, 0xc94d60b3
+0, 48048, 126720, 0x80886d64
+0, 51051, 126720, 0xf99a39ee
+0, 54054, 126720, 0xbc8b6c26
+0, 57057, 126720, 0x2270acf1
+0, 60060, 126720, 0x754b5965
+0, 63063, 126720, 0x5312dc30
+0, 66066, 126720, 0x2254cc6e
+0, 69069, 126720, 0x58b4bdcc
+0, 72072, 126720, 0xd1ed63ee
+0, 75075, 126720, 0x4442dec5
+0, 78078, 126720, 0x53403cef
+0, 81081, 126720, 0x495d575f
+0, 84084, 126720, 0x3ebfc7e8
+0, 87087, 126720, 0x8f0abe01
+0, 90090, 126720, 0x9540ba61
+0, 93093, 126720, 0xb011e3cf
+0, 96096, 126720, 0x70b4b1f4
+0, 99099, 126720, 0x803b67f9
+0, 102102, 126720, 0xa1c92662
+0, 105105, 126720, 0x3a3d9e4c
+0, 108108, 126720, 0x12660aa2
+0, 111111, 126720, 0xb84c7602
+0, 114114, 126720, 0x920df241
+0, 117117, 126720, 0x5f9db168
+0, 120120, 126720, 0xe3f524a6
+0, 123123, 126720, 0x5f390fa7
+0, 126126, 126720, 0xa9503b4f
+0, 129129, 126720, 0x259c08e2
+0, 132132, 126720, 0xef7a0279
+0, 135135, 126720, 0x4d31ed35
+0, 138138, 126720, 0xe10e3c7e
+0, 141141, 126720, 0xc35f191e
+0, 144144, 126720, 0x3401e9a9
+0, 147147, 126720, 0xd50603f9
diff --git a/tests/ref/fate/mtv b/tests/ref/fate/mtv
index d7dfa94..6699f62 100644
--- a/tests/ref/fate/mtv
+++ b/tests/ref/fate/mtv
@@ -1,5 +1,5 @@
-1, 0, 417, 0xae1cc66a
 0, 0, 18432, 0xbd7e0ac8
+1, 0, 417, 0xae1cc66a
 1, 2351, 418, 0xdc3ec850
 1, 4702, 418, 0x4e8ed05f
 0, 5625, 18432, 0xbd7e0ac8
diff --git a/tests/ref/fate/nuv b/tests/ref/fate/nuv
index 204a411..b047378 100644
--- a/tests/ref/fate/nuv
+++ b/tests/ref/fate/nuv
@@ -1,5 +1,5 @@
-1, 0, 4096, 0x00000000
 0, 0, 460800, 0x54aedafe
+1, 0, 4096, 0x00000000
 1, 2090, 4096, 0x4dfae7a6
 0, 3003, 460800, 0x54aedafe
 1, 4180, 4096, 0x3fd9f5c6
diff --git a/tests/ref/fate/pictor b/tests/ref/fate/pictor
new file mode 100644
index 0000000..3fa0f31
--- /dev/null
+++ b/tests/ref/fate/pictor
@@ -0,0 +1 @@
+0, 0, 192816, 0xf97e2ba1
diff --git a/tests/ref/fate/psx-str b/tests/ref/fate/psx-str
index c0b9908..3872e28 100644
--- a/tests/ref/fate/psx-str
+++ b/tests/ref/fate/psx-str
@@ -1,5 +1,5 @@
-1, 0, 8064, 0x02260037
 0, 0, 115200, 0x6b106a56
+1, 0, 8064, 0x02260037
 1, 4800, 8064, 0x4ee9f4e9
 0, 6000, 115200, 0x53c16930
 1, 9600, 8064, 0xf8fd82aa
@@ -7,8 +7,8 @@
 1, 14400, 8064, 0xc100792b
 0, 18000, 115200, 0xc3c18ba0
 1, 19200, 8064, 0xf11a5316
-1, 24000, 8064, 0x6937f8c0
 0, 24000, 115200, 0xe281b655
+1, 24000, 8064, 0x6937f8c0
 1, 28800, 8064, 0xed194e42
 0, 30000, 115200, 0x7b1e0536
 1, 33600, 8064, 0x619ce54b
@@ -16,8 +16,8 @@
 1, 38400, 8064, 0x544999ec
 0, 42000, 115200, 0xfc67bf8e
 1, 43200, 8064, 0x0ea877b4
-1, 48000, 8064, 0xb764d1c0
 0, 48000, 115200, 0xb463151c
+1, 48000, 8064, 0xb764d1c0
 1, 52800, 8064, 0x7a2fd211
 0, 54000, 115200, 0x6e686846
 1, 57600, 8064, 0xff69f6c5
@@ -25,8 +25,8 @@
 1, 62400, 8064, 0x26c11ec7
 0, 66000, 115200, 0x17b91efc
 1, 67200, 8064, 0xfb4ecc0c
-1, 72000, 8064, 0x111d799b
 0, 72000, 115200, 0xc051a49a
+1, 72000, 8064, 0x111d799b
 1, 76800, 8064, 0xc704dc91
 0, 78000, 115200, 0xc68c227b
 1, 81600, 8064, 0xa9f372fb
@@ -34,8 +34,8 @@
 1, 86400, 8064, 0xa3f0ad0f
 0, 90000, 115200, 0x09d56ecc
 1, 91200, 8064, 0x958719b9
-1, 96000, 8064, 0x9b011bf7
 0, 96000, 115200, 0xc20e3485
+1, 96000, 8064, 0x9b011bf7
 1, 100800, 8064, 0x466d96fb
 0, 102000, 115200, 0xf07e2c48
 1, 105600, 8064, 0x6ed4eb29
@@ -43,8 +43,8 @@
 1, 110400, 8064, 0x066966db
 0, 114000, 115200, 0xed65bacd
 1, 115200, 8064, 0xf60fe0bc
-1, 120000, 8064, 0x2c845167
 0, 120000, 115200, 0x51a23a3b
+1, 120000, 8064, 0x2c845167
 1, 124800, 8064, 0x7d63894f
 0, 126000, 115200, 0x559ddce1
 1, 129600, 8064, 0x0682ee36
@@ -52,8 +52,8 @@
 1, 134400, 8064, 0xcaeb7c70
 0, 138000, 115200, 0x11b2dece
 1, 139200, 8064, 0x93948697
-1, 144000, 8064, 0x5805f0d6
 0, 144000, 115200, 0x851b877c
+1, 144000, 8064, 0x5805f0d6
 1, 148800, 8064, 0xcfb641ff
 0, 150000, 115200, 0x5f9a7c99
 1, 153600, 8064, 0xe3499bb1
@@ -61,8 +61,8 @@
 1, 158400, 8064, 0x689fe483
 0, 162000, 115200, 0x950b0de8
 1, 163200, 8064, 0x1b8f2f2d
-1, 168000, 8064, 0x23852e71
 0, 168000, 115200, 0x6ec4c89a
+1, 168000, 8064, 0x23852e71
 1, 172800, 8064, 0x15e7b298
 0, 174000, 115200, 0xa9234812
 1, 177600, 8064, 0x5345a9a3
@@ -70,8 +70,8 @@
 1, 182400, 8064, 0x257b6ecf
 0, 186000, 115200, 0x2cc1a2aa
 1, 187200, 8064, 0xaf62836c
-1, 192000, 8064, 0xc3a401e3
 0, 192000, 115200, 0x5df53b71
+1, 192000, 8064, 0xc3a401e3
 1, 196800, 8064, 0x2b98fdf1
 0, 198000, 115200, 0xe1d0cb31
 1, 201600, 8064, 0x37168697
@@ -79,8 +79,8 @@
 1, 206400, 8064, 0x2d876c89
 0, 210000, 115200, 0x9342d739
 1, 211200, 8064, 0xc40a6ada
-1, 216000, 8064, 0xcca6b829
 0, 216000, 115200, 0x586bc658
+1, 216000, 8064, 0xcca6b829
 1, 220800, 8064, 0x6667550a
 0, 222000, 115200, 0x76902834
 1, 225600, 8064, 0x99c1b5cb
@@ -88,8 +88,8 @@
 1, 230400, 8064, 0xc05d3ed3
 0, 234000, 115200, 0xce8c95fb
 1, 235200, 8064, 0xdd641781
-1, 240000, 8064, 0xa65d49dc
 0, 240000, 115200, 0xdf0d3de6
+1, 240000, 8064, 0xa65d49dc
 1, 244800, 8064, 0x2a0d5df7
 0, 246000, 115200, 0x120db7ae
 1, 249600, 8064, 0xa6348438
@@ -97,8 +97,8 @@
 1, 254400, 8064, 0xf2e1412d
 0, 258000, 115200, 0x2498d3b6
 1, 259200, 8064, 0xc41c6a7a
-1, 264000, 8064, 0x147edc3d
 0, 264000, 115200, 0x99975ff8
+1, 264000, 8064, 0x147edc3d
 1, 268800, 8064, 0x17e3cfe7
 0, 270000, 115200, 0xbad65f9f
 1, 273600, 8064, 0x01fe3969
@@ -106,8 +106,8 @@
 1, 278400, 8064, 0xc437ac11
 0, 282000, 115200, 0x6f8a61a0
 1, 283200, 8064, 0xbbf747c1
-1, 288000, 8064, 0x2a4b88c0
 0, 288000, 115200, 0x80c96143
+1, 288000, 8064, 0x2a4b88c0
 1, 292800, 8064, 0xcd149c80
 0, 294000, 115200, 0x663c6198
 1, 297600, 8064, 0xcf339dfc
@@ -115,8 +115,8 @@
 1, 302400, 8064, 0xc81ff84b
 0, 306000, 115200, 0xfe186346
 1, 307200, 8064, 0x4d978100
-1, 312000, 8064, 0x6da6665b
 0, 312000, 115200, 0x844962f8
+1, 312000, 8064, 0x6da6665b
 1, 316800, 8064, 0x12fa354f
 0, 318000, 115200, 0x917c672f
 1, 321600, 8064, 0x6baedae6
@@ -124,8 +124,8 @@
 1, 326400, 8064, 0xddd77327
 0, 330000, 115200, 0xace06816
 1, 331200, 8064, 0x0a31c118
-1, 336000, 8064, 0x7652ee6e
 0, 336000, 115200, 0x4ef26aa2
+1, 336000, 8064, 0x7652ee6e
 1, 340800, 8064, 0x486a24cc
 0, 342000, 115200, 0xf2046bb3
 1, 345600, 8064, 0xf6cf01ee
@@ -133,8 +133,8 @@
 1, 350400, 8064, 0x2a19e830
 0, 354000, 115200, 0x8a17716d
 1, 355200, 8064, 0xde675a31
-1, 360000, 8064, 0xeefcc9af
 0, 360000, 115200, 0x36127568
+1, 360000, 8064, 0xeefcc9af
 1, 364800, 8064, 0xaec4c989
 0, 366000, 115200, 0x3e877b5c
 1, 369600, 8064, 0x16b73de9
@@ -142,8 +142,8 @@
 1, 374400, 8064, 0x188a582a
 0, 378000, 115200, 0x41bc8a39
 1, 379200, 8064, 0xc092e73d
-1, 384000, 8064, 0xf7ebca97
 0, 384000, 115200, 0x6f839446
+1, 384000, 8064, 0xf7ebca97
 1, 388800, 8064, 0x170ce07a
 0, 390000, 115200, 0xef74a005
 1, 393600, 8064, 0xa0705384
@@ -151,8 +151,8 @@
 1, 398400, 8064, 0xd0154a3c
 0, 402000, 115200, 0x4607cf99
 1, 403200, 8064, 0x57c73c6c
-1, 408000, 8064, 0x590c9ddb
 0, 408000, 115200, 0x4c18e8db
+1, 408000, 8064, 0x590c9ddb
 1, 412800, 8064, 0x2cbe552f
 0, 414000, 115200, 0x04d71efb
 1, 417600, 8064, 0x0d286932
@@ -160,8 +160,8 @@
 1, 422400, 8064, 0x5931cea3
 0, 426000, 115200, 0x4dd48d01
 1, 427200, 8064, 0xaf0fb80d
-1, 432000, 8064, 0x7fb61e9b
 0, 432000, 115200, 0x5fa9627f
+1, 432000, 8064, 0x7fb61e9b
 1, 436800, 8064, 0xf17134bb
 0, 438000, 115200, 0x7a413f88
 1, 441600, 8064, 0xd647859a
@@ -169,8 +169,8 @@
 1, 446400, 8064, 0x55a60921
 0, 450000, 115200, 0x3d720e05
 1, 451200, 8064, 0x3811fa58
-1, 456000, 8064, 0xaceeccea
 0, 456000, 115200, 0x49243fd8
+1, 456000, 8064, 0xaceeccea
 1, 460800, 8064, 0x5fcedf14
 0, 462000, 115200, 0x9834b697
 1, 465600, 8064, 0xd8c64abf
@@ -178,8 +178,8 @@
 1, 470400, 8064, 0x79495e8d
 0, 474000, 115200, 0x3eaf5504
 1, 475200, 8064, 0x4b7db039
-1, 480000, 8064, 0x7152f86d
 0, 480000, 115200, 0x057a3701
+1, 480000, 8064, 0x7152f86d
 1, 484800, 8064, 0xd92cfc1a
 0, 486000, 115200, 0x6e88f21a
 1, 489600, 8064, 0x75c540ef
@@ -187,8 +187,8 @@
 1, 494400, 8064, 0x9c03ef5e
 0, 498000, 115200, 0x92212d84
 1, 499200, 8064, 0x7b2911c8
-1, 504000, 8064, 0x69d9d553
 0, 504000, 115200, 0xf6b0a4ff
+1, 504000, 8064, 0x69d9d553
 1, 508800, 8064, 0xcb45d7c5
 0, 510000, 115200, 0xb49e9b4e
 1, 513600, 8064, 0x37ec8b0a
@@ -196,5 +196,5 @@
 1, 518400, 8064, 0xe4354221
 0, 522000, 115200, 0x65f3339a
 1, 523200, 8064, 0xc0d91cdb
-1, 528000, 8064, 0xea0be175
 0, 528000, 115200, 0x38e40a20
+1, 528000, 8064, 0xea0be175
diff --git a/tests/ref/fate/psx-str-v3-adpcm_xa b/tests/ref/fate/psx-str-v3-adpcm_xa
new file mode 100644
index 0000000..ee0c354
--- /dev/null
+++ b/tests/ref/fate/psx-str-v3-adpcm_xa
@@ -0,0 +1,37 @@
+0, 0, 8064, 0xa307ed8c
+0, 4800, 8064, 0xd2551927
+0, 9600, 8064, 0x3264a799
+0, 14400, 8064, 0x75da1393
+0, 19200, 8064, 0x68665f59
+0, 24000, 8064, 0xaf266a18
+0, 28800, 8064, 0x4d4b69fd
+0, 33600, 8064, 0x129d7e17
+0, 38400, 8064, 0x78c56725
+0, 43200, 8064, 0x59902cf1
+0, 48000, 8064, 0x6e699c87
+0, 52800, 8064, 0xc30692d7
+0, 57600, 8064, 0x29c043e5
+0, 62400, 8064, 0x61907704
+0, 67200, 8064, 0xf9210630
+0, 72000, 8064, 0xc0bdda08
+0, 76800, 8064, 0x6171b96d
+0, 81600, 8064, 0x082947cf
+0, 86400, 8064, 0xf7bbf1ce
+0, 91200, 8064, 0xe50e4436
+0, 96000, 8064, 0x2a860844
+0, 100800, 8064, 0xedcb502c
+0, 105600, 8064, 0x448e3c7f
+0, 110400, 8064, 0xf782f366
+0, 115200, 8064, 0xf57f66a5
+0, 120000, 8064, 0xdcc36939
+0, 124800, 8064, 0x34959d99
+0, 129600, 8064, 0xa5c20433
+0, 134400, 8064, 0xf1364e9b
+0, 139200, 8064, 0x232fe9c7
+0, 144000, 8064, 0xdc068d5a
+0, 148800, 8064, 0x4962e812
+0, 153600, 8064, 0x36a6709b
+0, 158400, 8064, 0xa2837bd8
+0, 163200, 8064, 0x68612ddb
+0, 168000, 8064, 0x8d76d1cb
+0, 172800, 8064, 0x7707cfc7
diff --git a/tests/ref/fate/psx-str-v3-mdec b/tests/ref/fate/psx-str-v3-mdec
new file mode 100644
index 0000000..52a3835
--- /dev/null
+++ b/tests/ref/fate/psx-str-v3-mdec
@@ -0,0 +1,59 @@
+0, 0, 76800, 0x2677be82
+0, 6000, 76800, 0x1f323c75
+0, 12000, 76800, 0xc8be3be9
+0, 18000, 76800, 0x1f323c75
+0, 24000, 76800, 0x7e484488
+0, 30000, 76800, 0x8bd644aa
+0, 36000, 76800, 0xaa62e7b8
+0, 42000, 76800, 0xaa62e7b8
+0, 48000, 76800, 0x53fadb39
+0, 54000, 76800, 0x53fadb39
+0, 60000, 76800, 0x1ff9d964
+0, 66000, 76800, 0x1ff9d964
+0, 72000, 76800, 0xd8c8d947
+0, 78000, 76800, 0xd8c8d947
+0, 84000, 76800, 0x6d0bd94c
+0, 90000, 76800, 0x6d0bd94c
+0, 96000, 76800, 0x7e66d948
+0, 102000, 76800, 0x7e66d948
+0, 108000, 76800, 0x8eecfd72
+0, 114000, 76800, 0xb15f29ab
+0, 120000, 76800, 0x08e5502e
+0, 126000, 76800, 0xaa58796d
+0, 132000, 76800, 0xe254a27c
+0, 138000, 76800, 0xeec8cf68
+0, 144000, 76800, 0x812bf8ee
+0, 150000, 76800, 0x929922ef
+0, 156000, 76800, 0xe1174e06
+0, 162000, 76800, 0x2da77bf1
+0, 168000, 76800, 0xd0f6a727
+0, 174000, 76800, 0x31bfd168
+0, 180000, 76800, 0xb87af225
+0, 186000, 76800, 0xd0080859
+0, 192000, 76800, 0x99ab15ba
+0, 198000, 76800, 0x99ab15ba
+0, 204000, 76800, 0x99ab15ba
+0, 210000, 76800, 0x99ab15ba
+0, 216000, 76800, 0x99ab15ba
+0, 222000, 76800, 0x99ab15ba
+0, 228000, 76800, 0x99ab15ba
+0, 234000, 76800, 0x99ab15ba
+0, 240000, 76800, 0x99ab15ba
+0, 246000, 76800, 0x99ab15ba
+0, 252000, 76800, 0x99ab15ba
+0, 258000, 76800, 0x99ab15ba
+0, 264000, 76800, 0x99ab15ba
+0, 270000, 76800, 0x99ab15ba
+0, 276000, 76800, 0x99ab15ba
+0, 282000, 76800, 0x99ab15ba
+0, 288000, 76800, 0x0c1617d5
+0, 294000, 76800, 0xb1c81b5d
+0, 300000, 76800, 0xb4e41e44
+0, 306000, 76800, 0x765725e2
+0, 312000, 76800, 0x25cd3109
+0, 318000, 76800, 0xa42b5291
+0, 324000, 76800, 0x15bb6ee4
+0, 330000, 76800, 0xb33c9f50
+0, 336000, 76800, 0x1ca1b874
+0, 342000, 76800, 0x7506e92a
+0, 348000, 76800, 0x97c9030a
diff --git a/tests/ref/fate/rv30 b/tests/ref/fate/rv30
new file mode 100644
index 0000000..5b43588
--- /dev/null
+++ b/tests/ref/fate/rv30
@@ -0,0 +1,46 @@
+0, 0, 126720, 0xcefaec47
+0, 7500, 126720, 0xa416ece5
+0, 15000, 126720, 0xa416ece5
+0, 22500, 126720, 0xa416ece5
+0, 30000, 126720, 0xcc10f4b7
+0, 37500, 126720, 0xeb6fb8d7
+0, 45000, 126720, 0xda71b917
+0, 52500, 126720, 0xbb1abbb7
+0, 60000, 126720, 0x273fbc37
+0, 67500, 126720, 0x16eebbd7
+0, 75000, 126720, 0x105eb927
+0, 82500, 126720, 0x7fa3ae27
+0, 90000, 126720, 0xd115a757
+0, 97500, 126720, 0x04e7897c
+0, 105000, 126720, 0x68cfda2b
+0, 112500, 126720, 0xe572dfc9
+0, 120000, 126720, 0xbc3cc34f
+0, 127500, 126720, 0xcf8cb0e2
+0, 135000, 126720, 0x6d1c630d
+0, 142500, 126720, 0x4338e469
+0, 150000, 126720, 0x9d82ea38
+0, 157500, 126720, 0x55e0b559
+0, 165000, 126720, 0x5eefb5ef
+0, 172500, 126720, 0x4b10b746
+0, 180000, 126720, 0x8b07a1db
+0, 187500, 126720, 0x8c639b34
+0, 195000, 126720, 0x63eb0b9f
+0, 202500, 126720, 0x31c80c83
+0, 210000, 126720, 0x78495352
+0, 217500, 126720, 0x63d609c4
+0, 225000, 126720, 0xcd2a62d8
+0, 232500, 126720, 0x4aea732d
+0, 240000, 126720, 0xe3bb352c
+0, 247500, 126720, 0x4b9036ad
+0, 255000, 126720, 0x88b66e2d
+0, 262500, 126720, 0x4a8a1b16
+0, 270000, 126720, 0x2e014eac
+0, 277500, 126720, 0x83212c67
+0, 285000, 126720, 0x4937e897
+0, 292500, 126720, 0x2d38babe
+0, 300000, 126720, 0xbcb43c09
+0, 307500, 126720, 0x955ffaf4
+0, 315000, 126720, 0x3337d4a2
+0, 322500, 126720, 0xe8f58c33
+0, 330000, 126720, 0x3a7f771f
+0, 337500, 126720, 0xb67c39b9
diff --git a/tests/ref/fate/sha b/tests/ref/fate/sha
new file mode 100644
index 0000000..2da0694
--- /dev/null
+++ b/tests/ref/fate/sha
@@ -0,0 +1,21 @@
+Testing SHA-160
+A9993E364706816ABA3E25717850C26C9CD0D89D
+84983E441C3BD26EBAAE4AA1F95129E5E54670F1
+34AA973CD4C4DAA4F61EEB2BDBAD27316534016F
+A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D
+84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1
+34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F
+Testing SHA-224
+23097D223405D8228642A477BDA255B32AADBCE4BDA0B3F7E36C9DA7
+75388B16512776CC5DBA5DA1FD890150B0C6455CB4F58B1952522525
+20794655980C91D8BBB4C1EA97618A4BF03F42581948B2EE4EE7AD67
+23097d22 3405d822 8642a477 bda255b3 2aadbce4 bda0b3f7 e36c9da7
+75388b16 512776cc 5dba5da1 fd890150 b0c6455c b4f58b19 52522525
+20794655 980c91d8 bbb4c1ea 97618a4b f03f4258 1948b2ee 4ee7ad67
+Testing SHA-256
+BA7816BF8F01CFEA414140DE5DAE2223B00361A396177A9CB410FF61F20015AD
+248D6A61D20638B8E5C026930C3E6039A33CE45964FF2167F6ECEDD419DB06C1
+CDC76E5C9914FB9281A1C7E284D73E67F1809A48A497200E046D39CCC7112CD0
+ba7816bf 8f01cfea 414140de 5dae2223 b00361a3 96177a9c b410ff61 f20015ad
+248d6a61 d20638b8 e5c02693 0c3e6039 a33ce459 64ff2167 f6ecedd4 19db06c1
+cdc76e5c 9914fb92 81a1c7e2 84d73e67 f1809a48 a497200e 046d39cc c7112cd0
diff --git a/tests/ref/fate/sierra-vmd b/tests/ref/fate/sierra-vmd
index 4d9e4cd..8ea1570 100644
--- a/tests/ref/fate/sierra-vmd
+++ b/tests/ref/fate/sierra-vmd
@@ -1,5 +1,5 @@
 0, 0, 230400, 0x0224ab01
-1, 0, 123480, 0xc1059826
+1, 0, 123480, 0x3a794c13
 0, 9000, 230400, 0x449e4d81
 0, 18000, 230400, 0x3e15e07a
 0, 27000, 230400, 0xdabe4172
@@ -27,277 +27,306 @@
 0, 225000, 230400, 0x76aebdae
 0, 234000, 230400, 0x81357545
 0, 243000, 230400, 0x38baeebd
-1, 252000, 4410, 0x261a09c0
 0, 252000, 230400, 0x1c5c44d4
-1, 261000, 4410, 0x68e9489e
+1, 252000, 4410, 0x109d04e0
 0, 261000, 230400, 0x60e189cc
-1, 270000, 4410, 0xb830827a
+1, 261000, 4410, 0x224d244f
 0, 270000, 230400, 0xb1f4381c
-1, 279000, 4410, 0xb053b70c
+1, 270000, 4410, 0xbb72413d
 0, 279000, 230400, 0xb5048fed
-1, 288000, 4410, 0xd8845d5d
+1, 279000, 4410, 0xaa5f5b86
 0, 288000, 230400, 0xc947c30e
-1, 297000, 4410, 0xd741f940
+1, 288000, 4410, 0x94e7aea7
 0, 297000, 230400, 0xe8e31c07
-1, 306000, 4410, 0x4860193c
+1, 297000, 4410, 0xad497ca0
 0, 306000, 230400, 0x6d49dd02
-1, 315000, 4410, 0x2e70df5f
+1, 306000, 4410, 0x1de10c9e
 0, 315000, 230400, 0x293e15d3
-1, 324000, 4410, 0x4b3e0e54
+1, 315000, 4410, 0x9f55efa8
 0, 324000, 230400, 0x354d792e
-1, 333000, 4410, 0x4afbf661
+1, 324000, 4410, 0x220a072a
 0, 333000, 230400, 0x35468780
-1, 342000, 4410, 0x485c3903
+1, 333000, 4410, 0xa7dafb29
 0, 342000, 230400, 0x365d3991
-1, 351000, 4410, 0xc0a1a00c
+1, 342000, 4410, 0xd5e29c7a
 0, 351000, 230400, 0xc9debef2
-1, 360000, 4410, 0x0ce2d38e
+1, 351000, 4410, 0xb8465006
 0, 360000, 230400, 0x4c4634c2
-1, 369000, 4410, 0x5b52dfa3
+1, 360000, 4410, 0x518669c7
 0, 369000, 230400, 0x347c2dca
-1, 378000, 4410, 0x0d6c02ba
+1, 369000, 4410, 0xb5b5efca
 0, 378000, 230400, 0x1efa0aaa
-1, 387000, 4410, 0x55f31fe1
+1, 378000, 4410, 0x8600015d
 0, 387000, 230400, 0xa79a0b5a
-1, 396000, 4410, 0x7350b1b2
+1, 387000, 4410, 0xe2f68fe9
 0, 396000, 230400, 0xfdb2dcdb
-1, 405000, 4410, 0x2b918eea
+1, 396000, 4410, 0x8d3458d9
 0, 405000, 230400, 0x42dbea33
-1, 414000, 4410, 0x6df6cf92
+1, 405000, 4410, 0xf1ff4775
 0, 414000, 230400, 0x2a207e43
-1, 423000, 4410, 0x2ddd1782
+1, 414000, 4410, 0x830f67c9
 0, 423000, 230400, 0x86573783
-1, 432000, 4410, 0x12265e8e
+1, 423000, 4410, 0x110e0bc1
 0, 432000, 230400, 0xc3968473
-1, 441000, 4410, 0x00c62139
+1, 432000, 4410, 0x71682f47
 0, 441000, 230400, 0x8f62a7b4
-1, 450000, 4410, 0xf2579b6c
+1, 441000, 4410, 0x38119095
 0, 450000, 230400, 0x5a2e3073
-1, 459000, 4410, 0x3bc24a12
+1, 450000, 4410, 0xd2494db6
 0, 459000, 230400, 0xd24f5e2c
-1, 468000, 4410, 0x0ce25212
+1, 459000, 4410, 0x8b552509
 0, 468000, 230400, 0x1df3c67d
-1, 477000, 4410, 0xad70de9a
+1, 468000, 4410, 0x71e52909
 0, 477000, 230400, 0xe4fd884d
-1, 486000, 4410, 0x232705e4
+1, 477000, 4410, 0x9f0a6f4d
 0, 486000, 230400, 0x9a228555
-1, 495000, 4410, 0x5ceba444
+1, 486000, 4410, 0x901302f2
 0, 495000, 230400, 0x9eba8ed5
-1, 504000, 4410, 0x17a3660b
+1, 495000, 4410, 0x855d5222
 0, 504000, 230400, 0x3d808a3d
-1, 513000, 4410, 0x291bb07e
+1, 504000, 4410, 0x324bb2fe
 0, 513000, 230400, 0xf57e866d
-1, 522000, 4410, 0xc13ccf88
+1, 513000, 4410, 0xe85f583f
 0, 522000, 230400, 0x85f594f5
-1, 531000, 4410, 0xfb0cd542
+1, 522000, 4410, 0x2cbc67c4
 0, 531000, 230400, 0xb09f99dd
-1, 540000, 4410, 0xb6438478
+1, 531000, 4410, 0xc82e6aa1
 0, 540000, 230400, 0x2b368475
-1, 549000, 4410, 0x263e9df2
+1, 540000, 4410, 0xb9fc423c
 0, 549000, 230400, 0xa2417afd
-1, 558000, 4410, 0x81621e20
+1, 549000, 4410, 0x6b9b4ef9
 0, 558000, 230400, 0x590b709d
-1, 567000, 4410, 0xe9a51d77
+1, 558000, 4410, 0x39290f10
 0, 567000, 230400, 0x5d617705
-1, 576000, 4410, 0x69a3c758
+1, 567000, 4410, 0xad718eb4
 0, 576000, 230400, 0xabf981ad
-1, 585000, 4410, 0x725af958
+1, 576000, 4410, 0x82f463ac
 0, 585000, 230400, 0x5a8590cd
-1, 594000, 4410, 0x09db995d
+1, 585000, 4410, 0xfac87cac
 0, 594000, 230400, 0x1bff853d
-1, 603000, 4410, 0x42963941
+1, 594000, 4410, 0x9e8bcca7
 0, 603000, 230400, 0x71d08055
-1, 612000, 4410, 0x33a29bc4
+1, 603000, 4410, 0x52f79c99
 0, 612000, 230400, 0x2ebd817d
-1, 621000, 4410, 0x02ee2bd1
+1, 612000, 4410, 0xf2d14de2
 0, 621000, 230400, 0x6e838255
-1, 630000, 4410, 0xda968535
+1, 621000, 4410, 0x367f95e1
 0, 630000, 230400, 0x043984cd
-1, 639000, 4410, 0x5414a080
+1, 630000, 4410, 0x8bfac293
 0, 639000, 230400, 0x7ff18495
-1, 648000, 4410, 0x021ac433
+1, 639000, 4410, 0x01ea5040
 0, 648000, 230400, 0xa43b8385
-1, 657000, 4410, 0x50195048
+1, 648000, 4410, 0x8ff5e212
 0, 657000, 230400, 0x72b5825d
-1, 666000, 4410, 0xc40921c7
+1, 657000, 4410, 0x93f32824
 0, 666000, 230400, 0x3a178085
-1, 675000, 4410, 0xdbb622e0
+1, 666000, 4410, 0x998f90dc
 0, 675000, 230400, 0x67748245
-1, 684000, 4410, 0xc8d07342
+1, 675000, 4410, 0x65231170
 0, 684000, 230400, 0xeddf81d5
-1, 693000, 4410, 0x6ed9b17a
+1, 684000, 4410, 0xc79039a1
 0, 693000, 230400, 0x8b088665
-1, 702000, 4410, 0x39ac6a03
+1, 693000, 4410, 0x0b0e58bd
 0, 702000, 230400, 0x6c408e15
-1, 711000, 4410, 0x119ed51c
+1, 702000, 4410, 0xc24ab4fa
 0, 711000, 230400, 0x81f196dd
-1, 720000, 4410, 0xc9a20539
+1, 711000, 4410, 0xd3796a8e
 0, 720000, 230400, 0xab9f953d
-1, 729000, 4410, 0x6db5fdbd
+1, 720000, 4410, 0xa37f8295
 0, 729000, 230400, 0xa5f69795
-1, 738000, 4410, 0x64c6b468
+1, 729000, 4410, 0xb760fed7
 0, 738000, 230400, 0xa772950d
-1, 747000, 4410, 0x1286686e
+1, 738000, 4410, 0x05495a34
 0, 747000, 230400, 0x6a5596d5
-1, 756000, 4410, 0x76632813
+1, 747000, 4410, 0x6f203437
 0, 756000, 230400, 0x1355958d
-1, 765000, 4410, 0x9923669b
+1, 756000, 4410, 0x71299402
 0, 765000, 230400, 0x4134981d
-1, 774000, 4410, 0x1cf31b5c
+1, 765000, 4410, 0x72e7b346
 0, 774000, 230400, 0x8b929515
-1, 783000, 4410, 0xa9f14389
+1, 774000, 4410, 0x879b0dae
 0, 783000, 230400, 0x482f95c5
-1, 792000, 4410, 0x9438c5cc
+1, 783000, 4410, 0x041aa1bd
 0, 792000, 230400, 0x7a9795d5
-1, 801000, 4410, 0x48dd0a72
+1, 792000, 4410, 0x18a962e6
 0, 801000, 230400, 0x21c29abd
-1, 810000, 4410, 0xb0fe24dd
+1, 801000, 4410, 0x21d20539
 0, 810000, 230400, 0x9ae6a475
-1, 819000, 4410, 0xdb9d03ac
+1, 810000, 4410, 0x8f449267
 0, 819000, 230400, 0x3734aee5
-1, 828000, 4410, 0x487d7ac3
+1, 819000, 4410, 0xecdc01d6
 0, 828000, 230400, 0xa0a1b365
-1, 837000, 4410, 0x2b61d4d5
+1, 828000, 4410, 0x458abd5a
 0, 837000, 230400, 0x2dcab1c5
-1, 846000, 4410, 0xab934d9c
+1, 837000, 4410, 0xa070ea63
 0, 846000, 230400, 0x9c8b6c44
-1, 855000, 4410, 0xd2ee6f94
+1, 846000, 4410, 0xc25b26ce
 0, 855000, 230400, 0x5da75feb
-1, 864000, 4410, 0x012c3002
+1, 855000, 4410, 0x4d9237ca
 0, 864000, 230400, 0x4d02f8e3
-1, 873000, 4410, 0xfccbd3cc
+1, 864000, 4410, 0x748e1801
 0, 873000, 230400, 0x66824f3a
-1, 882000, 4410, 0xe53230d8
+1, 873000, 4410, 0xc96b69e6
 0, 882000, 230400, 0x0c9257e2
-1, 891000, 4410, 0x2f6a6102
+1, 882000, 4410, 0x6663186c
 0, 891000, 230400, 0xb2927092
-1, 900000, 4410, 0x77bb876a
+1, 891000, 4410, 0x7f6d3081
 0, 900000, 230400, 0xb5dc6e9a
-1, 909000, 4410, 0xbcb76718
+1, 900000, 4410, 0x1a0343b5
 0, 909000, 230400, 0x6e567bc6
-1, 918000, 4410, 0x51c00790
+1, 909000, 4410, 0xc48e338c
 0, 918000, 230400, 0xbf9e0f7a
-1, 927000, 4410, 0x51b8fc5a
+1, 918000, 4410, 0x26fc03c8
 0, 927000, 230400, 0xb16f684a
-1, 936000, 4410, 0x20fe9b42
+1, 927000, 4410, 0x69be7e2d
 0, 936000, 230400, 0xf9e55e81
-1, 945000, 4410, 0x363c5566
+1, 936000, 4410, 0x69a74da1
 0, 945000, 230400, 0xd8d0bcba
-1, 954000, 4410, 0x3424a84c
+1, 945000, 4410, 0x85bd2ab3
 0, 954000, 230400, 0x44720ac0
-1, 963000, 4410, 0x7c3053c0
+1, 954000, 4410, 0xeff05426
 0, 963000, 230400, 0x7d4c2058
-1, 972000, 4410, 0x368f2f30
+1, 963000, 4410, 0x292829e0
 0, 972000, 230400, 0xb0973eb9
-1, 981000, 4410, 0x0f1e6fd2
+1, 972000, 4410, 0x8f741798
 0, 981000, 230400, 0x405a13ce
-1, 990000, 4410, 0x3a1fe07e
+1, 981000, 4410, 0x6b9337e9
 0, 990000, 230400, 0x6422f00a
-1, 999000, 4410, 0x74afd86a
+1, 990000, 4410, 0xe4e1703f
 0, 999000, 230400, 0x924b6c1e
-1, 1008000, 4410, 0xfdf911dd
+1, 999000, 4410, 0x043d6c35
 0, 1008000, 230400, 0xcf7809c0
-1, 1017000, 4410, 0x1206a561
+1, 1008000, 4410, 0x3a8988e7
 0, 1017000, 230400, 0x883a3863
-1, 1026000, 4410, 0x5f0f33d5
+1, 1017000, 4410, 0x1fa7d2a9
 0, 1026000, 230400, 0x6adc9e03
-1, 1035000, 4410, 0xca3d88e0
+1, 1026000, 4410, 0xe28799e3
 0, 1035000, 230400, 0x4f5ab7a8
-1, 1044000, 4410, 0xdf8f19ea
+1, 1035000, 4410, 0xc2df4470
 0, 1044000, 230400, 0xdc0aab94
-1, 1053000, 4410, 0xe3275b9e
-1, 1062000, 4410, 0xee1945c5
-1, 1071000, 4410, 0x0afbd006
-1, 1080000, 4410, 0x90ff8f14
-1, 1089000, 4410, 0xfc0c887a
-1, 1098000, 4410, 0xae9bc232
-1, 1107000, 4410, 0x5f688eb8
-1, 1116000, 4410, 0x9a307469
-1, 1125000, 4410, 0x27f1e324
-1, 1134000, 4410, 0x0c0d4ca2
-1, 1143000, 4410, 0xd7e8ce74
-1, 1152000, 4410, 0x16a4bfd6
-1, 1161000, 4410, 0xbfb02f6d
-1, 1170000, 4410, 0xf4b81a79
-1, 1179000, 4410, 0x05d97288
-1, 1188000, 4410, 0x3a7db4be
-1, 1197000, 4410, 0xc6bea83e
-1, 1206000, 4410, 0x436f62ed
-1, 1215000, 4410, 0x6fabea0c
-1, 1224000, 4410, 0x954878aa
-1, 1233000, 4410, 0x4d10f579
-1, 1242000, 4410, 0xac65932a
-1, 1251000, 4410, 0x6889f957
-1, 1260000, 4410, 0x65cf5830
-1, 1269000, 4410, 0x87a7af71
-1, 1278000, 4410, 0x82378c13
-1, 1287000, 4410, 0x88ab6bd5
-1, 1296000, 4410, 0xf90a3342
-1, 1305000, 4410, 0xd790a1bc
-1, 1314000, 4410, 0x89919d7c
-1, 1323000, 4410, 0x7ffb22bf
-1, 1332000, 4410, 0xfefbcce3
-1, 1341000, 4410, 0x07714e80
-1, 1350000, 4410, 0x73078f53
-1, 1359000, 4410, 0x35c23078
-1, 1368000, 4410, 0x452538bb
-1, 1377000, 4410, 0x61493f33
-1, 1386000, 4410, 0x2137c390
-1, 1395000, 4410, 0x78c9393f
-1, 1404000, 4410, 0x7aeaf8e1
-1, 1413000, 4410, 0x4bb8da1c
-1, 1422000, 4410, 0x5995dfc2
-1, 1431000, 4410, 0xccce8872
-1, 1440000, 4410, 0xca2753a4
-1, 1449000, 4410, 0x4296ff6d
-1, 1458000, 4410, 0xe582d191
-1, 1467000, 4410, 0xc40268da
-1, 1476000, 4410, 0xda1d475e
-1, 1485000, 4410, 0x5e91e4e0
-1, 1494000, 4410, 0xfeb44475
-1, 1503000, 4410, 0x17ff8e38
-1, 1512000, 4410, 0x3bd58bcf
-1, 1521000, 4410, 0x9476e23c
-1, 1530000, 4410, 0x440651ab
-1, 1539000, 4410, 0xb08cdc74
-1, 1548000, 4410, 0x6fc3031f
-1, 1557000, 4410, 0x197ab39a
-1, 1566000, 4410, 0xf92f0e3d
-1, 1575000, 4410, 0xd5f6b678
-1, 1584000, 4410, 0x8af127a6
-1, 1593000, 4410, 0xe22f585e
-1, 1602000, 4410, 0x67515610
-1, 1611000, 4410, 0x21569d7a
-1, 1620000, 4410, 0x114597d8
-1, 1629000, 4410, 0xba213fb6
-1, 1638000, 4410, 0x1aca9fee
-1, 1647000, 4410, 0x48cdd264
-1, 1656000, 4410, 0x533619ec
-1, 1665000, 4410, 0x21466244
-1, 1674000, 4410, 0x26e00e88
-1, 1683000, 4410, 0x8e51d07c
-1, 1692000, 4410, 0xa6c4048a
-1, 1701000, 4410, 0x98ce10e4
-1, 1710000, 4410, 0x379bc8c2
-1, 1719000, 4410, 0x404b09c6
-1, 1728000, 4410, 0xfc89da8a
-1, 1737000, 4410, 0xbdbe6914
-1, 1746000, 4410, 0x2cb09f08
-1, 1755000, 4410, 0x835bf2d9
-1, 1764000, 4410, 0xa4611790
-1, 1773000, 4410, 0x67740896
-1, 1782000, 4410, 0x489f6bd0
-1, 1791000, 4410, 0x072bae9c
-1, 1800000, 4410, 0xadce5a89
-1, 1809000, 4410, 0x209f2c2c
-1, 1818000, 4410, 0xf5706665
-1, 1827000, 4410, 0x631841cb
-1, 1836000, 4410, 0xa1a2c65f
-1, 1845000, 4410, 0x8818b96b
-1, 1854000, 4410, 0x63158025
-1, 1863000, 4410, 0xf6ae79f5
-1, 1872000, 4410, 0xb3dcd214
-1, 1881000, 4410, 0x7a745449
-1, 1890000, 4410, 0x5d2b15f4
-1, 1899000, 4410, 0x48764b7c
-1, 1908000, 4410, 0x1294e119
+1, 1044000, 4410, 0x694d0cf5
+1, 1053000, 4410, 0x5aac2dcf
+1, 1062000, 4410, 0x259fa2db
+1, 1071000, 4410, 0xd16d6803
+1, 1080000, 4410, 0xa4b3478a
+1, 1089000, 4410, 0xdbe0443d
+1, 1098000, 4410, 0x26c16119
+1, 1107000, 4410, 0x0c06475c
+1, 1116000, 4410, 0x6ffaba2d
+1, 1125000, 4410, 0x5b287192
+1, 1134000, 4410, 0xf2cf2651
+1, 1143000, 4410, 0x3857673a
+1, 1152000, 4410, 0x5b555feb
+1, 1161000, 4410, 0x93f997af
+1, 1170000, 4410, 0xb3ba8d35
+1, 1179000, 4410, 0x66433944
+1, 1188000, 4410, 0xf0005a5f
+1, 1197000, 4410, 0xb948541f
+1, 1206000, 4410, 0xc8f1b16f
+1, 1215000, 4410, 0x7d4b7506
+1, 1224000, 4410, 0xac723c55
+1, 1233000, 4410, 0x2926fab5
+1, 1242000, 4410, 0x31684995
+1, 1251000, 4410, 0x35ebfca4
+1, 1260000, 4410, 0x9cd42c18
+1, 1269000, 4410, 0xd7ecd7b1
+1, 1278000, 4410, 0x5e13c602
+1, 1287000, 4410, 0xe955b5e3
+1, 1296000, 4410, 0xefad19a1
+1, 1305000, 4410, 0x435950de
+1, 1314000, 4410, 0x9d624ebe
+1, 1323000, 4410, 0x774a9158
+1, 1332000, 4410, 0x8c41e66a
+1, 1341000, 4410, 0x70112740
+1, 1350000, 4410, 0x55abc7a2
+1, 1359000, 4410, 0x0ec3183c
+1, 1368000, 4410, 0x54609c56
+1, 1377000, 4410, 0x60d49f92
+1, 1386000, 4410, 0x5fb061c8
+1, 1395000, 4410, 0x6e119c98
+1, 1404000, 4410, 0x3f39fc69
+1, 1413000, 4410, 0xef466d0e
+1, 1422000, 4410, 0xf4cb6fe1
+1, 1431000, 4410, 0xc4434439
+1, 1440000, 4410, 0xd02329d2
+1, 1449000, 4410, 0x216cffaf
+1, 1458000, 4410, 0x7e59e8c1
+1, 1467000, 4410, 0xc7c3346d
+1, 1476000, 4410, 0x5b3723af
+1, 1485000, 4410, 0x76097270
+1, 1494000, 4410, 0xae39a233
+1, 1503000, 4410, 0x686a471c
+1, 1512000, 4410, 0x3af3c5e0
+1, 1521000, 4410, 0x11ac711e
+1, 1530000, 4410, 0xcd8da8ce
+1, 1539000, 4410, 0x21296e3a
+1, 1548000, 4410, 0x77168188
+1, 1557000, 4410, 0x5fcf59cd
+1, 1566000, 4410, 0x390c8717
+1, 1575000, 4410, 0x3d5d5b3c
+1, 1584000, 4410, 0x3b8f13d3
+1, 1593000, 4410, 0x5b002c2f
+1, 1602000, 4410, 0x9e1d2b08
+1, 1611000, 4410, 0x69454ebd
+1, 1620000, 4410, 0x62a54bec
+1, 1629000, 4410, 0x4d231fdb
+1, 1638000, 4410, 0x65624ff7
+1, 1647000, 4410, 0x6fc66932
+1, 1656000, 4410, 0x23200cf6
+1, 1665000, 4410, 0xf8033122
+1, 1674000, 4410, 0x0fce0744
+1, 1683000, 4410, 0x9302683e
+1, 1692000, 4410, 0xd2380245
+1, 1701000, 4410, 0x482e0872
+1, 1710000, 4410, 0xe98e6461
+1, 1719000, 4410, 0x1db404e3
+1, 1728000, 4410, 0x47a26d45
+1, 1737000, 4410, 0x449a348a
+1, 1746000, 4410, 0xee874f84
+1, 1755000, 4410, 0xc4ecf965
+1, 1764000, 4410, 0xcc450bc8
+1, 1773000, 4410, 0xb18d044b
+1, 1782000, 4410, 0x895435e8
+1, 1791000, 4410, 0x57e7574e
+1, 1800000, 4410, 0x8041ad3d
+1, 1809000, 4410, 0x853d1616
+1, 1818000, 4410, 0xa11bb32b
+1, 1827000, 4410, 0xe10ea0de
+1, 1836000, 4410, 0xdf2ee328
+1, 1845000, 4410, 0xd5a6dcae
+1, 1854000, 4410, 0xd176c00b
+1, 1863000, 4410, 0x9cd6bcf3
+1, 1872000, 4410, 0x2569690a
+1, 1881000, 4410, 0x6824aa1d
+1, 1890000, 4410, 0xa9110afa
+1, 1899000, 4410, 0x115c25be
+1, 1908000, 4410, 0x1100f085
+1, 1917000, 4410, 0x00000000
+1, 1926000, 4410, 0x00000000
+1, 1935000, 4410, 0x00000000
+1, 1944000, 4410, 0x00000000
+1, 1953000, 4410, 0x00000000
+1, 1962000, 4410, 0x00000000
+1, 1971000, 4410, 0x00000000
+1, 1980000, 4410, 0x00000000
+1, 1989000, 4410, 0x00000000
+1, 1998000, 4410, 0x00000000
+1, 2007000, 4410, 0x00000000
+1, 2016000, 4410, 0x00000000
+1, 2025000, 4410, 0x00000000
+1, 2034000, 4410, 0x00000000
+1, 2043000, 4410, 0x00000000
+1, 2052000, 4410, 0x00000000
+1, 2061000, 4410, 0x00000000
+1, 2070000, 4410, 0x00000000
+1, 2079000, 4410, 0x00000000
+1, 2088000, 4410, 0x00000000
+1, 2097000, 4410, 0x00000000
+1, 2106000, 4410, 0x00000000
+1, 2115000, 4410, 0x00000000
+1, 2124000, 4410, 0x00000000
+1, 2133000, 4410, 0x00000000
+1, 2142000, 4410, 0x00000000
+1, 2151000, 4410, 0x00000000
+1, 2160000, 4410, 0x00000000
+1, 2169000, 4410, 0x00000000
diff --git a/tests/ref/fate/siff b/tests/ref/fate/siff
index 2f67254..05c12c2 100644
--- a/tests/ref/fate/siff
+++ b/tests/ref/fate/siff
@@ -1,5 +1,5 @@
-1, 0, 44100, 0xd0a49e09
 0, 0, 230400, 0x3bd1d731
+1, 0, 44100, 0xd0a49e09
 0, 7500, 230400, 0x9d0774c3
 0, 15000, 230400, 0xa0faafe2
 0, 22500, 230400, 0x38325309
@@ -11,8 +11,8 @@
 0, 67500, 230400, 0x07178dd9
 0, 75000, 230400, 0xf52b8db4
 0, 82500, 230400, 0x2b70c1dc
-1, 90000, 44100, 0xf151af4d
 0, 90000, 230400, 0x8157a6e9
+1, 90000, 44100, 0xf151af4d
 0, 97500, 230400, 0xd4a3c357
 0, 105000, 230400, 0x703861bb
 0, 112500, 230400, 0xa13cf75e
@@ -24,8 +24,8 @@
 0, 157500, 230400, 0x22050962
 0, 165000, 230400, 0x0f5c8a0d
 0, 172500, 230400, 0x3475df44
-1, 180000, 44100, 0xecd3cd08
 0, 180000, 230400, 0x65354e06
+1, 180000, 44100, 0xecd3cd08
 0, 187500, 230400, 0xb9a01978
 0, 195000, 230400, 0x15207ee1
 0, 202500, 230400, 0x3b214f0b
diff --git a/tests/ref/fate/smc b/tests/ref/fate/smc
index 08e3d5e..2901b90 100644
--- a/tests/ref/fate/smc
+++ b/tests/ref/fate/smc
@@ -1,120 +1,120 @@
 0, 0, 230400, 0xf814fc90
-0, 3000, 230400, 0xe1b13137
-0, 6000, 230400, 0xa7f4d408
-0, 9000, 230400, 0x4b86e1d5
-0, 12000, 230400, 0xc663af5a
-0, 15000, 230400, 0x943b5757
-0, 18000, 230400, 0x0d7ee496
-0, 21000, 230400, 0x78792de4
-0, 24000, 230400, 0xd102fb8d
-0, 27000, 230400, 0xf9006139
-0, 30000, 230400, 0x216bd87d
-0, 33000, 230400, 0x1e4c902c
-0, 36000, 230400, 0x5aaa7742
-0, 39000, 230400, 0x48699d93
-0, 42000, 230400, 0xd1e22a5c
-0, 45000, 230400, 0x18929315
-0, 48000, 230400, 0x680dd4d3
-0, 51000, 230400, 0x4cdbcbcb
-0, 54000, 230400, 0x6f810d98
-0, 57000, 230400, 0xb4f68204
-0, 60000, 230400, 0xbd3bb19e
-0, 63000, 230400, 0xab27b424
-0, 66000, 230400, 0xe5dd675d
-0, 69000, 230400, 0x811e45a1
-0, 72000, 230400, 0x951011f7
-0, 75000, 230400, 0x2f1e2b99
-0, 78000, 230400, 0x6657c0d6
-0, 81000, 230400, 0xfd29177d
-0, 84000, 230400, 0x4b4c01d7
-0, 87000, 230400, 0x9af286aa
-0, 90000, 230400, 0xc4e9b193
-0, 93000, 230400, 0x05dc28ec
-0, 96000, 230400, 0x68352119
-0, 99000, 230400, 0x0b87e79c
-0, 102000, 230400, 0x8358b180
-0, 105000, 230400, 0x8debbc9d
-0, 108000, 230400, 0x961c58ce
-0, 111000, 230400, 0xd8a809c8
-0, 114000, 230400, 0x5351789d
-0, 117000, 230400, 0xa7ca598c
-0, 120000, 230400, 0xc5ce1812
-0, 123000, 230400, 0x74496550
-0, 126000, 230400, 0x326e366e
-0, 129000, 230400, 0x27ae9a92
-0, 132000, 230400, 0xadbc8794
-0, 135000, 230400, 0x7f3587d8
-0, 138000, 230400, 0xf0400ca6
-0, 141000, 230400, 0x59a5138e
-0, 144000, 230400, 0x456d62a5
-0, 147000, 230400, 0xf1a5e5f1
-0, 150000, 230400, 0x75c712e4
-0, 153000, 230400, 0xd160780a
-0, 156000, 230400, 0xc6c23cf0
-0, 159000, 230400, 0x0339a2ac
-0, 162000, 230400, 0x0e27a2e2
-0, 165000, 230400, 0x84976300
-0, 168000, 230400, 0xb368f3c4
-0, 171000, 230400, 0xa5231fb8
-0, 174000, 230400, 0x17c036d4
-0, 177000, 230400, 0xfc81a2c0
-0, 180000, 230400, 0x99faa403
-0, 183000, 230400, 0xff59efd3
-0, 186000, 230400, 0xcece1d23
-0, 189000, 230400, 0x56c785d9
-0, 192000, 230400, 0xe5a9f222
-0, 195000, 230400, 0xb80946f8
-0, 198000, 230400, 0xf6b642c6
-0, 201000, 230400, 0x69573aed
-0, 204000, 230400, 0xfb69a1fd
-0, 207000, 230400, 0x100b47f4
-0, 210000, 230400, 0x6edf9543
-0, 213000, 230400, 0x11fdf43c
-0, 216000, 230400, 0xd143bf2a
-0, 219000, 230400, 0x7ca747c4
-0, 222000, 230400, 0xd984bd73
-0, 225000, 230400, 0xc5477e8d
-0, 228000, 230400, 0xf7d58300
-0, 231000, 230400, 0x7a1b9463
-0, 234000, 230400, 0x47a29342
-0, 237000, 230400, 0xdf437f9d
-0, 240000, 230400, 0xf836ef5d
-0, 243000, 230400, 0xc98937af
-0, 246000, 230400, 0x9258695b
-0, 249000, 230400, 0xd4fe179c
-0, 252000, 230400, 0x35d524d3
-0, 255000, 230400, 0xd9ce5484
-0, 258000, 230400, 0xdef776ed
-0, 261000, 230400, 0x154c4057
-0, 264000, 230400, 0xf5c764f1
-0, 267000, 230400, 0x41979b13
-0, 270000, 230400, 0xae4e83db
-0, 273000, 230400, 0x09fc0f83
-0, 276000, 230400, 0x60267fdf
-0, 279000, 230400, 0xeaafc525
-0, 282000, 230400, 0x80cc35e5
-0, 285000, 230400, 0xd82c6164
-0, 288000, 230400, 0xd68b8111
-0, 291000, 230400, 0x96f874a3
-0, 294000, 230400, 0x7fc861c4
-0, 297000, 230400, 0xb911f310
-0, 300000, 230400, 0x35bbf5aa
-0, 303000, 230400, 0xa922b683
-0, 306000, 230400, 0xbf6ae353
-0, 309000, 230400, 0x6bd3984c
-0, 312000, 230400, 0xe51768c0
-0, 315000, 230400, 0xee691624
-0, 318000, 230400, 0xd546fed7
-0, 321000, 230400, 0x98d375e6
-0, 324000, 230400, 0x3b9ca990
-0, 327000, 230400, 0x27128ad1
-0, 330000, 230400, 0x2788e38c
-0, 333000, 230400, 0xb0cf3381
-0, 336000, 230400, 0x4fc86d39
-0, 339000, 230400, 0xf5632fff
-0, 342000, 230400, 0x7fa1e6c2
-0, 345000, 230400, 0xffeef044
-0, 348000, 230400, 0x932af385
-0, 351000, 230400, 0x76738428
-0, 354000, 230400, 0xf6771ba2
-0, 357000, 230400, 0x17e2ff27
+0, 9000, 230400, 0xe1b13137
+0, 18000, 230400, 0xa7f4d408
+0, 27000, 230400, 0x4b86e1d5
+0, 36000, 230400, 0xc663af5a
+0, 45000, 230400, 0x943b5757
+0, 54000, 230400, 0x0d7ee496
+0, 63000, 230400, 0x78792de4
+0, 72000, 230400, 0xd102fb8d
+0, 81000, 230400, 0xf9006139
+0, 90000, 230400, 0x216bd87d
+0, 99000, 230400, 0x1e4c902c
+0, 108000, 230400, 0x5aaa7742
+0, 117000, 230400, 0x48699d93
+0, 126000, 230400, 0xd1e22a5c
+0, 135000, 230400, 0x18929315
+0, 144000, 230400, 0x680dd4d3
+0, 153000, 230400, 0x4cdbcbcb
+0, 162000, 230400, 0x6f810d98
+0, 171000, 230400, 0xb4f68204
+0, 180000, 230400, 0xbd3bb19e
+0, 189000, 230400, 0xab27b424
+0, 198000, 230400, 0xe5dd675d
+0, 207000, 230400, 0x811e45a1
+0, 216000, 230400, 0x951011f7
+0, 225000, 230400, 0x2f1e2b99
+0, 234000, 230400, 0x6657c0d6
+0, 243000, 230400, 0xfd29177d
+0, 252000, 230400, 0x4b4c01d7
+0, 261000, 230400, 0x9af286aa
+0, 270000, 230400, 0xc4e9b193
+0, 279000, 230400, 0x05dc28ec
+0, 288000, 230400, 0x68352119
+0, 297000, 230400, 0x0b87e79c
+0, 306000, 230400, 0x8358b180
+0, 315000, 230400, 0x8debbc9d
+0, 324000, 230400, 0x961c58ce
+0, 333000, 230400, 0xd8a809c8
+0, 342000, 230400, 0x5351789d
+0, 351000, 230400, 0xa7ca598c
+0, 360000, 230400, 0xc5ce1812
+0, 369000, 230400, 0x74496550
+0, 378000, 230400, 0x326e366e
+0, 387000, 230400, 0x27ae9a92
+0, 396000, 230400, 0xadbc8794
+0, 405000, 230400, 0x7f3587d8
+0, 414000, 230400, 0xf0400ca6
+0, 423000, 230400, 0x59a5138e
+0, 432000, 230400, 0x456d62a5
+0, 441000, 230400, 0xf1a5e5f1
+0, 450000, 230400, 0x75c712e4
+0, 459000, 230400, 0xd160780a
+0, 468000, 230400, 0xc6c23cf0
+0, 477000, 230400, 0x0339a2ac
+0, 486000, 230400, 0x0e27a2e2
+0, 495000, 230400, 0x84976300
+0, 504000, 230400, 0xb368f3c4
+0, 513000, 230400, 0xa5231fb8
+0, 522000, 230400, 0x17c036d4
+0, 531000, 230400, 0xfc81a2c0
+0, 540000, 230400, 0x99faa403
+0, 549000, 230400, 0xff59efd3
+0, 558000, 230400, 0xcece1d23
+0, 567000, 230400, 0x56c785d9
+0, 576000, 230400, 0xe5a9f222
+0, 585000, 230400, 0xb80946f8
+0, 594000, 230400, 0xf6b642c6
+0, 603000, 230400, 0x69573aed
+0, 612000, 230400, 0xfb69a1fd
+0, 621000, 230400, 0x100b47f4
+0, 630000, 230400, 0x6edf9543
+0, 639000, 230400, 0x11fdf43c
+0, 648000, 230400, 0xd143bf2a
+0, 657000, 230400, 0x7ca747c4
+0, 666000, 230400, 0xd984bd73
+0, 675000, 230400, 0xc5477e8d
+0, 684000, 230400, 0xf7d58300
+0, 693000, 230400, 0x7a1b9463
+0, 702000, 230400, 0x47a29342
+0, 711000, 230400, 0xdf437f9d
+0, 720000, 230400, 0xf836ef5d
+0, 729000, 230400, 0xc98937af
+0, 738000, 230400, 0x9258695b
+0, 747000, 230400, 0xd4fe179c
+0, 756000, 230400, 0x35d524d3
+0, 765000, 230400, 0xd9ce5484
+0, 774000, 230400, 0xdef776ed
+0, 783000, 230400, 0x154c4057
+0, 792000, 230400, 0xf5c764f1
+0, 801000, 230400, 0x41979b13
+0, 810000, 230400, 0xae4e83db
+0, 819000, 230400, 0x09fc0f83
+0, 828000, 230400, 0x60267fdf
+0, 837000, 230400, 0xeaafc525
+0, 846000, 230400, 0x80cc35e5
+0, 855000, 230400, 0xd82c6164
+0, 864000, 230400, 0xd68b8111
+0, 873000, 230400, 0x96f874a3
+0, 882000, 230400, 0x7fc861c4
+0, 891000, 230400, 0xb911f310
+0, 900000, 230400, 0x35bbf5aa
+0, 909000, 230400, 0xa922b683
+0, 918000, 230400, 0xbf6ae353
+0, 927000, 230400, 0x6bd3984c
+0, 936000, 230400, 0xe51768c0
+0, 945000, 230400, 0xee691624
+0, 954000, 230400, 0xd546fed7
+0, 963000, 230400, 0x98d375e6
+0, 972000, 230400, 0x3b9ca990
+0, 981000, 230400, 0x27128ad1
+0, 990000, 230400, 0x2788e38c
+0, 999000, 230400, 0xb0cf3381
+0, 1008000, 230400, 0x4fc86d39
+0, 1017000, 230400, 0xf5632fff
+0, 1026000, 230400, 0x7fa1e6c2
+0, 1035000, 230400, 0xffeef044
+0, 1044000, 230400, 0x932af385
+0, 1053000, 230400, 0x76738428
+0, 1062000, 230400, 0xf6771ba2
+0, 1071000, 230400, 0x17e2ff27
diff --git a/tests/ref/fate/sub-srt b/tests/ref/fate/sub-srt
new file mode 100644
index 0000000..5a14664
--- /dev/null
+++ b/tests/ref/fate/sub-srt
@@ -0,0 +1 @@
+03b2a3f7e7e83624c8e4d1b5569df758
diff --git a/tests/ref/fate/tiertex-seq b/tests/ref/fate/tiertex-seq
index e4ebf5a..6aa7fc7 100644
--- a/tests/ref/fate/tiertex-seq
+++ b/tests/ref/fate/tiertex-seq
@@ -1,147 +1,147 @@
-1, 0, 1764, 0x00000000
 0, 0, 98304, 0x2e5db4a4
-1, 3600, 1764, 0x80a253d9
+1, 0, 1764, 0x00000000
 0, 3600, 98304, 0xb20c19d0
-1, 7200, 1764, 0x95a16721
+1, 3600, 1764, 0x80a253d9
 0, 7200, 98304, 0xb20c19d0
-1, 10800, 1764, 0x0f0d4cb6
+1, 7200, 1764, 0x95a16721
 0, 10800, 98304, 0xb20c19d0
-1, 14400, 1764, 0x75026779
+1, 10800, 1764, 0x0f0d4cb6
 0, 14400, 98304, 0x6b8538c0
-1, 18000, 1764, 0xb4356e37
+1, 14400, 1764, 0x75026779
 0, 18000, 98304, 0x6b8538c0
-1, 21600, 1764, 0xfafa64cb
+1, 18000, 1764, 0xb4356e37
 0, 21600, 98304, 0x6b8538c0
-1, 25200, 1764, 0xe8fd7970
+1, 21600, 1764, 0xfafa64cb
 0, 25200, 98304, 0x172207e3
-1, 28800, 1764, 0x666879b7
+1, 25200, 1764, 0xe8fd7970
 0, 28800, 98304, 0x172207e3
-1, 32400, 1764, 0xf2cd7770
+1, 28800, 1764, 0x666879b7
 0, 32400, 98304, 0x172207e3
-1, 36000, 1764, 0x54317a1c
+1, 32400, 1764, 0xf2cd7770
 0, 36000, 98304, 0x172207e3
-1, 39600, 1764, 0x9c396930
+1, 36000, 1764, 0x54317a1c
 0, 39600, 98304, 0x63fb7dc1
-1, 43200, 1764, 0x87115ec4
+1, 39600, 1764, 0x9c396930
 0, 43200, 98304, 0x63fb7dc1
-1, 46800, 1764, 0x0c9b69b6
+1, 43200, 1764, 0x87115ec4
 0, 46800, 98304, 0x63fb7dc1
-1, 50400, 1764, 0x8c3a758a
+1, 46800, 1764, 0x0c9b69b6
 0, 50400, 98304, 0x37cf1601
-1, 54000, 1764, 0x605d776a
+1, 50400, 1764, 0x8c3a758a
 0, 54000, 98304, 0x37cf1601
-1, 57600, 1764, 0x0556852d
+1, 54000, 1764, 0x605d776a
 0, 57600, 98304, 0x37cf1601
-1, 61200, 1764, 0x7d4363f8
+1, 57600, 1764, 0x0556852d
 0, 61200, 98304, 0x37cf1601
-1, 64800, 1764, 0xc5cd75d0
+1, 61200, 1764, 0x7d4363f8
 0, 64800, 98304, 0x82941990
-1, 68400, 1764, 0x3ff3646d
+1, 64800, 1764, 0xc5cd75d0
 0, 68400, 98304, 0x82941990
-1, 72000, 1764, 0x10136d25
+1, 68400, 1764, 0x3ff3646d
 0, 72000, 98304, 0x82941990
-1, 75600, 1764, 0xeb1a6cd0
+1, 72000, 1764, 0x10136d25
 0, 75600, 98304, 0x82941990
-1, 79200, 1764, 0xef937ed1
+1, 75600, 1764, 0xeb1a6cd0
 0, 79200, 98304, 0xe0a5309e
-1, 82800, 1764, 0x2d2b6f79
+1, 79200, 1764, 0xef937ed1
 0, 82800, 98304, 0xe0a5309e
-1, 86400, 1764, 0x6f457231
+1, 82800, 1764, 0x2d2b6f79
 0, 86400, 98304, 0xe0a5309e
-1, 90000, 1764, 0x56267c9d
+1, 86400, 1764, 0x6f457231
 0, 90000, 98304, 0x164cb67d
-1, 93600, 1764, 0xd49e79c8
+1, 90000, 1764, 0x56267c9d
 0, 93600, 98304, 0x164cb67d
-1, 97200, 1764, 0xc726703d
+1, 93600, 1764, 0xd49e79c8
 0, 97200, 98304, 0x164cb67d
-1, 100800, 1764, 0x2abf8074
+1, 97200, 1764, 0xc726703d
 0, 100800, 98304, 0x164cb67d
-1, 104400, 1764, 0xb50c556d
+1, 100800, 1764, 0x2abf8074
 0, 104400, 98304, 0xed2189f8
-1, 108000, 1764, 0xc1f2523c
+1, 104400, 1764, 0xb50c556d
 0, 108000, 98304, 0xed2189f8
-1, 111600, 1764, 0x850a6f93
+1, 108000, 1764, 0xc1f2523c
 0, 111600, 98304, 0xed2189f8
-1, 115200, 1764, 0x8da76c31
+1, 111600, 1764, 0x850a6f93
 0, 115200, 98304, 0x7215e529
-1, 118800, 1764, 0xfcccdf13
+1, 115200, 1764, 0x8da76c31
 0, 118800, 98304, 0x7215e529
-1, 122400, 1764, 0x00000000
+1, 118800, 1764, 0xfcccdf13
 0, 122400, 98304, 0x7215e529
-1, 126000, 1764, 0x00000000
+1, 122400, 1764, 0x00000000
 0, 126000, 98304, 0x7215e529
-1, 129600, 1764, 0x00000000
+1, 126000, 1764, 0x00000000
 0, 129600, 98304, 0x170c783b
-1, 133200, 1764, 0x00000000
+1, 129600, 1764, 0x00000000
 0, 133200, 98304, 0x170c783b
-1, 136800, 1764, 0x00000000
+1, 133200, 1764, 0x00000000
 0, 136800, 98304, 0x170c783b
-1, 140400, 1764, 0x00000000
+1, 136800, 1764, 0x00000000
 0, 140400, 98304, 0xf6bd74c7
-1, 144000, 1764, 0x00000000
+1, 140400, 1764, 0x00000000
 0, 144000, 98304, 0xf6bd74c7
-1, 147600, 1764, 0x00000000
+1, 144000, 1764, 0x00000000
 0, 147600, 98304, 0xf6bd74c7
-1, 151200, 1764, 0x00000000
+1, 147600, 1764, 0x00000000
 0, 151200, 98304, 0xf6bd74c7
-1, 154800, 1764, 0x00000000
+1, 151200, 1764, 0x00000000
 0, 154800, 98304, 0x1efd38c4
-1, 158400, 1764, 0x00000000
+1, 154800, 1764, 0x00000000
 0, 158400, 98304, 0x1efd38c4
-1, 162000, 1764, 0x00000000
+1, 158400, 1764, 0x00000000
 0, 162000, 98304, 0x1efd38c4
-1, 165600, 1764, 0x00000000
+1, 162000, 1764, 0x00000000
 0, 165600, 98304, 0x1efd38c4
-1, 169200, 1764, 0x00000000
+1, 165600, 1764, 0x00000000
 0, 169200, 98304, 0x29c26bba
-1, 172800, 1764, 0x00000000
+1, 169200, 1764, 0x00000000
 0, 172800, 98304, 0x29c26bba
-1, 176400, 1764, 0x00000000
+1, 172800, 1764, 0x00000000
 0, 176400, 98304, 0x29c26bba
-1, 180000, 1764, 0x00000000
+1, 176400, 1764, 0x00000000
 0, 180000, 98304, 0x880a6313
-1, 183600, 1764, 0x00000000
+1, 180000, 1764, 0x00000000
 0, 183600, 98304, 0x880a6313
-1, 187200, 1764, 0x00000000
+1, 183600, 1764, 0x00000000
 0, 187200, 98304, 0x880a6313
-1, 190800, 1764, 0x00000000
+1, 187200, 1764, 0x00000000
 0, 190800, 98304, 0x880a6313
-1, 194400, 1764, 0x00000000
+1, 190800, 1764, 0x00000000
 0, 194400, 98304, 0x73f5bb00
-1, 198000, 1764, 0x00000000
+1, 194400, 1764, 0x00000000
 0, 198000, 98304, 0x73f5bb00
-1, 201600, 1764, 0x00000000
+1, 198000, 1764, 0x00000000
 0, 201600, 98304, 0x73f5bb00
-1, 205200, 1764, 0x00000000
+1, 201600, 1764, 0x00000000
 0, 205200, 98304, 0xc85b19ec
-1, 208800, 1764, 0x00000000
+1, 205200, 1764, 0x00000000
 0, 208800, 98304, 0xc85b19ec
-1, 212400, 1764, 0x00000000
+1, 208800, 1764, 0x00000000
 0, 212400, 98304, 0xc85b19ec
-1, 216000, 1764, 0x00000000
+1, 212400, 1764, 0x00000000
 0, 216000, 98304, 0xc85b19ec
-1, 219600, 1764, 0x00000000
+1, 216000, 1764, 0x00000000
 0, 219600, 98304, 0x00000000
-1, 223200, 1764, 0x00000000
+1, 219600, 1764, 0x00000000
 0, 223200, 98304, 0x00000000
-1, 226800, 1764, 0x00000000
+1, 223200, 1764, 0x00000000
 0, 226800, 98304, 0x00000000
-1, 230400, 1764, 0x00000000
+1, 226800, 1764, 0x00000000
 0, 230400, 98304, 0x00000000
-1, 234000, 1764, 0x00000000
+1, 230400, 1764, 0x00000000
 0, 234000, 98304, 0x00000000
-1, 237600, 1764, 0x00000000
+1, 234000, 1764, 0x00000000
 0, 237600, 98304, 0x00000000
-1, 241200, 1764, 0x00000000
+1, 237600, 1764, 0x00000000
 0, 241200, 98304, 0x00000000
-1, 244800, 1764, 0x00000000
+1, 241200, 1764, 0x00000000
 0, 244800, 98304, 0x00000000
-1, 248400, 1764, 0x00000000
+1, 244800, 1764, 0x00000000
 0, 248400, 98304, 0x00000000
-1, 252000, 1764, 0x00000000
+1, 248400, 1764, 0x00000000
 0, 252000, 98304, 0x00000000
-1, 255600, 1764, 0x00000000
+1, 252000, 1764, 0x00000000
 0, 255600, 98304, 0x00000000
+1, 255600, 1764, 0x00000000
 1, 259200, 1764, 0x00000000
 1, 262800, 1764, 0x00000000
 1, 266400, 1764, 0x00000000
diff --git a/tests/ref/fate/truemotion1-15 b/tests/ref/fate/truemotion1-15
new file mode 100644
index 0000000..d103f01
--- /dev/null
+++ b/tests/ref/fate/truemotion1-15
@@ -0,0 +1,218 @@
+0, 0, 161280, 0x7041748d
+1, 0, 10832, 0xe1a811fa
+1, 5527, 10832, 0xb47841f9
+0, 6000, 161280, 0x3cc4dfb5
+1, 11053, 10832, 0x839eedf1
+0, 12000, 161280, 0xca3af22d
+1, 16580, 10832, 0xb48b1f60
+0, 18000, 161280, 0x23ad1d85
+1, 22106, 10832, 0x743936c0
+0, 24000, 161280, 0x9c9cf364
+1, 27633, 10832, 0xe1f039fb
+0, 30000, 161280, 0x1551d6a8
+1, 33159, 10832, 0xef00751a
+0, 36000, 161280, 0xc39f6b95
+1, 38686, 10832, 0x401ed099
+0, 42000, 161280, 0x3b036dcc
+1, 44212, 10832, 0x432a53bd
+0, 48000, 161280, 0xa6fac1db
+1, 49739, 10832, 0xc4276bfd
+0, 54000, 161280, 0x67656b62
+1, 55265, 10832, 0x51f0fa8c
+0, 60000, 161280, 0xb41f47d1
+1, 60792, 10832, 0xcebae622
+0, 66000, 161280, 0xc207249e
+1, 66318, 10832, 0xe9f6dc1f
+1, 71845, 10832, 0xda087fee
+0, 72000, 161280, 0xbee8f843
+1, 77371, 10832, 0x67a621bb
+0, 78000, 161280, 0x092acf46
+1, 82898, 10832, 0xd7be207f
+0, 84000, 161280, 0x8d9e2680
+1, 88424, 10832, 0x19d32507
+0, 90000, 161280, 0x8becc20c
+1, 93951, 10832, 0xe1a3fbfa
+0, 96000, 161280, 0x655e444e
+1, 99478, 10832, 0xd10df779
+0, 102000, 161280, 0x5c112da0
+1, 105004, 10832, 0x4428e1a7
+0, 108000, 161280, 0x232fa9eb
+1, 110531, 10832, 0x7ea9b33d
+0, 114000, 161280, 0x9721745d
+1, 116057, 10832, 0x6852a5a5
+0, 120000, 161280, 0x92f1d880
+1, 121584, 10832, 0xfeb78863
+0, 126000, 161280, 0x16233978
+1, 127110, 10832, 0xf157f928
+0, 132000, 161280, 0x19a27e69
+1, 132637, 10832, 0x86414b3e
+0, 138000, 161280, 0x7b6ad73a
+1, 138163, 10832, 0x2e28cdf6
+1, 143690, 10832, 0x00212e44
+0, 144000, 161280, 0xa7a674aa
+1, 149216, 10832, 0x2d7f9378
+0, 150000, 161280, 0x4e434abb
+1, 154743, 10832, 0x84cb25d7
+0, 156000, 161280, 0xb96eea14
+1, 160269, 10832, 0x3aca41fa
+0, 162000, 161280, 0x1350188c
+1, 165796, 10832, 0x27ad34b9
+0, 168000, 161280, 0x79c6f305
+1, 171322, 10832, 0xe665144a
+0, 174000, 161280, 0xa9c7782d
+1, 176849, 10832, 0xf9546626
+0, 180000, 161280, 0x40a4f456
+1, 182376, 10832, 0xe71c4f22
+0, 186000, 161280, 0xaf291ed6
+1, 187902, 10832, 0x5e61869c
+0, 192000, 161280, 0xab29b4e1
+1, 193429, 10832, 0x571d2c10
+0, 198000, 161280, 0xbfcd2712
+1, 198955, 10832, 0xf0e08cd5
+0, 204000, 161280, 0xff22a0d7
+1, 204482, 10832, 0x66650e49
+0, 210000, 161280, 0xb0ae88a9
+1, 210008, 10832, 0x4024deaf
+1, 215535, 10832, 0xda7bdb14
+0, 216000, 161280, 0x811d1259
+1, 221061, 10832, 0xc27a342f
+0, 222000, 161280, 0x593c39a1
+1, 226588, 10832, 0x574fe679
+0, 228000, 161280, 0x5a5a97f8
+1, 232114, 10832, 0x37db464e
+0, 234000, 161280, 0xa5639ecf
+1, 237641, 10832, 0xb1fa2a83
+0, 240000, 161280, 0x543920c6
+1, 243167, 10832, 0x3d98d9b7
+0, 246000, 161280, 0xb41689ee
+1, 248694, 10832, 0xb7c908e2
+0, 252000, 161280, 0xc0ad83de
+1, 254220, 10832, 0x9f7e44d8
+0, 258000, 161280, 0x9e9e7456
+1, 259747, 10832, 0xae9b8774
+0, 264000, 161280, 0x777ccbfe
+1, 265273, 10832, 0x36916e3f
+0, 270000, 161280, 0x9c2df916
+1, 270800, 10832, 0xd785f5ef
+0, 276000, 161280, 0xe0c13b35
+1, 276327, 10832, 0x2a3a5673
+1, 281853, 10832, 0x7320e379
+0, 282000, 161280, 0x39bfa5a5
+1, 287380, 10832, 0xec787be5
+0, 288000, 161280, 0x35dfb264
+1, 292906, 10832, 0xd0d13aa0
+0, 294000, 161280, 0x43018613
+1, 298433, 10832, 0x34dfcb17
+0, 300000, 161280, 0x43584b8a
+1, 303959, 10832, 0x1a9c29f1
+0, 306000, 161280, 0xa5cd230a
+1, 309486, 10832, 0x3e73dcc1
+0, 312000, 161280, 0x6fe2cfb3
+1, 315012, 10832, 0x7855b053
+0, 318000, 161280, 0x88a7c0db
+1, 320539, 10832, 0x5588df8f
+0, 324000, 161280, 0x476f1cd2
+1, 326065, 10832, 0x6f621299
+0, 330000, 161280, 0x96401d49
+1, 331592, 10832, 0xce7f39c2
+0, 336000, 161280, 0x7d932919
+1, 337118, 10832, 0xd88e6552
+0, 342000, 161280, 0x06465481
+1, 342645, 10832, 0xddc63597
+0, 348000, 161280, 0x39631520
+1, 348171, 10832, 0xe3071865
+1, 353698, 10832, 0x2a44a123
+0, 354000, 161280, 0xc3fff780
+1, 359224, 10832, 0x08d85d45
+0, 360000, 161280, 0xa81faf28
+1, 364751, 10832, 0x4dc5f83a
+0, 366000, 161280, 0x7a311f4f
+1, 370278, 10832, 0x89497812
+0, 372000, 161280, 0x52f9b931
+1, 375804, 10832, 0x9ee1db54
+0, 378000, 161280, 0x938cf016
+1, 381331, 10832, 0x5277d611
+0, 384000, 161280, 0xf8f6e19c
+1, 386857, 10832, 0x570a619c
+0, 390000, 161280, 0xca90561b
+1, 392384, 10832, 0xa217d70f
+0, 396000, 161280, 0x8594d06b
+1, 397910, 10832, 0x6f0ecbf4
+0, 402000, 161280, 0xea32bf3b
+1, 403437, 10832, 0x2704b114
+0, 408000, 161280, 0x4646111a
+1, 408963, 10832, 0xf24e679f
+0, 414000, 161280, 0xee891162
+1, 414490, 10832, 0x05572099
+0, 420000, 161280, 0xcfc32082
+1, 420016, 10832, 0x33942d0c
+1, 425543, 10832, 0xa77ea674
+0, 426000, 161280, 0x863c281a
+1, 431069, 10832, 0xeba663bc
+0, 432000, 161280, 0x01b591aa
+1, 436596, 10832, 0x1338524a
+0, 438000, 161280, 0x211fbc62
+1, 442122, 10832, 0x6182b0b3
+0, 444000, 161280, 0xae2bafe2
+1, 447649, 10832, 0xa410a364
+0, 450000, 161280, 0xcfe46dca
+1, 453176, 10832, 0x2f4374b0
+0, 456000, 161280, 0xcf8fe8a3
+1, 458702, 10832, 0xf41f3a07
+0, 462000, 161280, 0x3f8474eb
+1, 464229, 10832, 0x2b1c50c6
+0, 468000, 161280, 0x06da345a
+1, 469755, 10832, 0x3692ac89
+0, 474000, 161280, 0xbd4d3280
+1, 475282, 10832, 0x5d6bc87e
+0, 480000, 161280, 0xb5e70fea
+1, 480808, 10832, 0x1b1cda0c
+0, 486000, 161280, 0x0c99c804
+1, 486335, 10832, 0x11eaa15f
+1, 491861, 10832, 0x73c7d7ef
+0, 492000, 161280, 0x19841ed4
+1, 497388, 10832, 0x65d7e3be
+0, 498000, 161280, 0xf81dea50
+1, 502914, 10832, 0xb9c00688
+0, 504000, 161280, 0x7777d81c
+1, 508441, 10832, 0x0b98c125
+0, 510000, 161280, 0x0497cfd8
+1, 513967, 10832, 0x331ed413
+0, 516000, 161280, 0x50b6eb64
+1, 519494, 10832, 0x9b68f485
+0, 522000, 161280, 0x5071fc07
+1, 525020, 10832, 0x1b865c55
+0, 528000, 161280, 0xbb7527fb
+1, 530547, 10832, 0x68cef565
+0, 534000, 161280, 0x13054f1f
+1, 536073, 10832, 0x3a605f15
+0, 540000, 161280, 0x4b78fb27
+1, 541600, 10832, 0xd72ff22e
+0, 546000, 161280, 0xf504968f
+1, 547127, 10832, 0x1c672b67
+0, 552000, 161280, 0x555b10b7
+1, 552653, 10832, 0xfd1a7e7e
+0, 558000, 161280, 0xcc0dde40
+1, 558180, 10832, 0x9bf20ead
+1, 563706, 10832, 0x00000000
+0, 564000, 161280, 0xcc0dde40
+1, 569233, 10832, 0x00000000
+0, 570000, 161280, 0x367f60c8
+1, 574759, 10832, 0x00000000
+0, 576000, 161280, 0x367f60c8
+1, 580286, 10832, 0x00000000
+0, 582000, 161280, 0x367f60c8
+1, 585812, 10832, 0x00000000
+0, 588000, 161280, 0x367f60c8
+1, 591339, 10832, 0x00000000
+0, 594000, 161280, 0x367f60c8
+1, 596865, 10832, 0x00000000
+0, 600000, 161280, 0x367f60c8
+1, 602392, 10832, 0x00000000
+0, 606000, 161280, 0x367f60c8
+1, 607918, 10832, 0x00000000
+0, 612000, 161280, 0x367f60c8
+1, 613445, 10832, 0x00000000
+0, 618000, 161280, 0x367f60c8
+1, 618971, 10832, 0x00000000
+0, 624000, 161280, 0x367f60c8
diff --git a/tests/ref/fate/truemotion1-24 b/tests/ref/fate/truemotion1-24
new file mode 100644
index 0000000..b0b1c4e
--- /dev/null
+++ b/tests/ref/fate/truemotion1-24
@@ -0,0 +1,43 @@
+0, 0, 69120, 0x68beb30f
+1, 0, 10832, 0x1597b4c8
+1, 5527, 10832, 0xf9479f8b
+0, 6000, 69120, 0x3976f5cf
+1, 11053, 10832, 0x8db50e74
+0, 12000, 69120, 0xf815bc3c
+1, 16580, 10832, 0x2b33ecbb
+0, 18000, 69120, 0xa7cc0ae6
+1, 22106, 10832, 0x8d0f537b
+0, 24000, 69120, 0xd85ac282
+1, 27633, 10832, 0x922081c7
+0, 30000, 69120, 0xf7fd7edb
+1, 33159, 10832, 0x40291f19
+0, 36000, 69120, 0x433bb6f6
+1, 38686, 10832, 0x88f5271a
+0, 42000, 69120, 0xdbac8bee
+1, 44212, 10832, 0x55c6bbe5
+0, 48000, 69120, 0x88e2a799
+1, 49739, 10832, 0x9b51ae82
+0, 54000, 69120, 0x49617b26
+1, 55265, 10832, 0xcdf2409b
+0, 60000, 69120, 0xeb44ca01
+1, 60792, 10832, 0x0933b1a4
+0, 66000, 69120, 0x6fea37e8
+1, 66318, 10832, 0x24b77006
+1, 71845, 10832, 0xf612fa8a
+0, 72000, 69120, 0xf55d74c7
+1, 77371, 10832, 0x99884b06
+0, 78000, 69120, 0xb5082ca7
+1, 82898, 10832, 0x3c746fbe
+0, 84000, 69120, 0x5876d758
+1, 88424, 10832, 0x05f3b08a
+1, 93951, 10832, 0xa6560483
+1, 99478, 10832, 0xd98a8e19
+1, 105004, 10832, 0xf98a0b2e
+1, 110531, 10832, 0xb1039582
+1, 116057, 10832, 0x85dd5c3f
+1, 121584, 10832, 0x19fc801a
+1, 127110, 10832, 0x95805089
+1, 132637, 10832, 0x576fdec3
+1, 138163, 10832, 0x704a0905
+1, 143690, 10832, 0xf87ce1fa
+1, 149216, 10832, 0xfc0076b9
diff --git a/tests/ref/fate/tscc-15bit b/tests/ref/fate/tscc-15bit
index fb4d558..bc55f0f 100644
--- a/tests/ref/fate/tscc-15bit
+++ b/tests/ref/fate/tscc-15bit
@@ -1,5 +1,5 @@
-1, 0, 22050, 0x1740aaec
 0, 0, 657600, 0xaf456809
+1, 0, 22050, 0x1740aaec
 0, 6000, 657600, 0xaf456809
 0, 12000, 657600, 0xaf456809
 0, 18000, 657600, 0x2dbe6889
@@ -14,8 +14,8 @@
 0, 72000, 657600, 0x2dbe6889
 0, 78000, 657600, 0x2dbe6889
 0, 84000, 657600, 0x2dbe6889
-1, 90000, 22050, 0x75ed6086
 0, 90000, 657600, 0x2dbe6889
+1, 90000, 22050, 0x75ed6086
 0, 96000, 657600, 0x2dbe6889
 0, 102000, 657600, 0x2dbe6889
 0, 108000, 657600, 0x2dbe6889
@@ -30,8 +30,8 @@
 0, 162000, 657600, 0x64cb6889
 0, 168000, 657600, 0x64cb6889
 0, 174000, 657600, 0x64cb6889
-1, 180000, 22050, 0xca52a4e9
 0, 180000, 657600, 0x42036b71
+1, 180000, 22050, 0xca52a4e9
 0, 186000, 657600, 0x42036b71
 0, 192000, 657600, 0x42036b71
 0, 198000, 657600, 0xc40a6889
@@ -46,8 +46,8 @@
 0, 252000, 657600, 0x22d10de0
 0, 258000, 657600, 0xa75f0d60
 0, 264000, 657600, 0x7a440be0
-1, 270000, 22050, 0xb306d419
 0, 270000, 657600, 0x40095d50
+1, 270000, 22050, 0xb306d419
 0, 276000, 657600, 0x40095d50
 0, 282000, 657600, 0x64766320
 0, 288000, 657600, 0x64766320
@@ -62,8 +62,8 @@
 0, 342000, 657600, 0xf51adc49
 0, 348000, 657600, 0xf51adc49
 0, 354000, 657600, 0xf51adc49
-1, 360000, 22050, 0x8cbb9625
 0, 360000, 657600, 0xdd47af59
+1, 360000, 22050, 0x8cbb9625
 0, 366000, 657600, 0xdd47af59
 0, 372000, 657600, 0xffa8acf1
 0, 378000, 657600, 0x5994b059
@@ -78,8 +78,8 @@
 0, 432000, 657600, 0xbe37b549
 0, 438000, 657600, 0xbe37b549
 0, 444000, 657600, 0x1d395bf9
-1, 450000, 22050, 0x34a11f66
 0, 450000, 657600, 0x1d395bf9
+1, 450000, 22050, 0x34a11f66
 0, 456000, 657600, 0x1d395bf9
 0, 462000, 657600, 0x1d395bf9
 0, 468000, 657600, 0x2ec36f37
@@ -94,8 +94,8 @@
 0, 522000, 657600, 0x70064801
 0, 528000, 657600, 0x80d54519
 0, 534000, 657600, 0xe8c942b1
-1, 540000, 22050, 0x1ae81230
 0, 540000, 657600, 0x830d8c24
+1, 540000, 22050, 0x1ae81230
 0, 546000, 657600, 0x830d8c24
 0, 552000, 657600, 0x830d8c24
 0, 558000, 657600, 0xf3c4707c
@@ -110,8 +110,8 @@
 0, 612000, 657600, 0x221ceecf
 0, 618000, 657600, 0x221ceecf
 0, 624000, 657600, 0x221ceecf
-1, 630000, 22050, 0x1217eeba
 0, 630000, 657600, 0x221ceecf
+1, 630000, 22050, 0x1217eeba
 0, 636000, 657600, 0x221ceecf
 0, 642000, 657600, 0x221ceecf
 0, 648000, 657600, 0x3bf6f39f
@@ -126,8 +126,8 @@
 0, 702000, 657600, 0x41f6218d
 0, 708000, 657600, 0x41f6218d
 0, 714000, 657600, 0x41f6218d
-1, 720000, 22050, 0x50e70baa
 0, 720000, 657600, 0xff43ec36
+1, 720000, 22050, 0x50e70baa
 0, 726000, 657600, 0x0b10eb16
 0, 732000, 657600, 0x0b10eb16
 0, 738000, 657600, 0xbdf41aa5
@@ -142,8 +142,8 @@
 0, 792000, 657600, 0x3d4ccf06
 0, 798000, 657600, 0x0897d1de
 0, 804000, 657600, 0x0897d1de
-1, 810000, 22050, 0xb19e89c0
 0, 810000, 657600, 0x3e27e01e
+1, 810000, 22050, 0xb19e89c0
 0, 816000, 657600, 0x3e27e01e
 0, 822000, 657600, 0x3e27e01e
 0, 828000, 657600, 0x3e27e01e
@@ -158,8 +158,8 @@
 0, 882000, 657600, 0xe9967a40
 0, 888000, 657600, 0xe9967a40
 0, 894000, 657600, 0xe9967a40
-1, 900000, 22050, 0x78526696
 0, 900000, 657600, 0x726cb6b8
+1, 900000, 22050, 0x78526696
 0, 906000, 657600, 0x2960b6e8
 0, 912000, 657600, 0x2960b6e8
 0, 918000, 657600, 0x1637d6c8
@@ -174,8 +174,8 @@
 0, 972000, 657600, 0xdfa0d6c8
 0, 978000, 657600, 0xdfa0d6c8
 0, 984000, 657600, 0xdfa0d6c8
-1, 990000, 22050, 0x48e3bb21
 0, 990000, 657600, 0xdfa0d6c8
+1, 990000, 22050, 0x48e3bb21
 0, 996000, 657600, 0xdfa0d6c8
 0, 1002000, 657600, 0xdfa0d6c8
 0, 1008000, 657600, 0xdfa0d6c8
@@ -190,8 +190,8 @@
 0, 1062000, 657600, 0x85e87a68
 0, 1068000, 657600, 0x85e87a68
 0, 1074000, 657600, 0x85e87a68
-1, 1080000, 22050, 0xbc32204a
 0, 1080000, 657600, 0xb0a141a8
+1, 1080000, 22050, 0xbc32204a
 0, 1086000, 657600, 0xb0a141a8
 0, 1092000, 657600, 0xf3333bd8
 0, 1098000, 657600, 0xea090688
@@ -206,8 +206,8 @@
 0, 1152000, 657600, 0xf1d2874a
 0, 1158000, 657600, 0xf1d2874a
 0, 1164000, 657600, 0xf1d2874a
-1, 1170000, 22050, 0xdf6f1e46
 0, 1170000, 657600, 0xa58d6742
+1, 1170000, 22050, 0xdf6f1e46
 0, 1176000, 657600, 0xa58d6742
 0, 1182000, 657600, 0xa58d6742
 0, 1188000, 657600, 0xb0cd11bb
@@ -222,8 +222,8 @@
 0, 1242000, 657600, 0x97ac10bb
 0, 1248000, 657600, 0x97ac10bb
 0, 1254000, 657600, 0xe8b30dd3
-1, 1260000, 22050, 0x4c91da9d
 0, 1260000, 657600, 0x3d0c10bb
+1, 1260000, 22050, 0x4c91da9d
 0, 1266000, 657600, 0x8d2b0dd3
 0, 1272000, 657600, 0x8d2b0dd3
 0, 1278000, 657600, 0xa5760dd3
diff --git a/tests/ref/fate/txd-16bpp b/tests/ref/fate/txd-16bpp
new file mode 100644
index 0000000..aa5979e
--- /dev/null
+++ b/tests/ref/fate/txd-16bpp
@@ -0,0 +1,11 @@
+0, 0, 16384, 0x213f9ea8
+0, 18000, 16384, 0x8185fdb1
+0, 36000, 16384, 0xf03581d1
+0, 54000, 16384, 0x629cd573
+0, 72000, 16384, 0xfe7a5b63
+0, 90000, 16384, 0x4afc05b2
+0, 108000, 16384, 0x074b8515
+0, 126000, 16384, 0x17fde900
+0, 144000, 16384, 0x831bac76
+0, 162000, 16384, 0x2fb579f3
+0, 180000, 16384, 0x68762bed
diff --git a/tests/ref/fate/txd-pal8 b/tests/ref/fate/txd-pal8
new file mode 100644
index 0000000..8d8f2a5
--- /dev/null
+++ b/tests/ref/fate/txd-pal8
@@ -0,0 +1 @@
+0, 0, 786432, 0x56654d61
diff --git a/tests/ref/fate/vc1 b/tests/ref/fate/vc1
index 737dad0..69e9b4a 100644
--- a/tests/ref/fate/vc1
+++ b/tests/ref/fate/vc1
@@ -1,2 +1,15 @@
-0, 0, 38016, 0xf1b25db5
-0, 0, 38016, 0xf1b25db5
+0, 0, 38016, 0xf4715db5
+0, 3600, 38016, 0xf4715db5
+0, 7200, 38016, 0xf4715db5
+0, 10800, 38016, 0xf46af0e1
+0, 14400, 38016, 0x9c1c2cf1
+0, 18000, 38016, 0xff12d87f
+0, 21600, 38016, 0x7408432b
+0, 25200, 38016, 0x7408432b
+0, 28800, 38016, 0x8d11479a
+0, 32400, 38016, 0x8d11479a
+0, 36000, 38016, 0xc4a121ab
+0, 39600, 38016, 0xc4a121ab
+0, 43200, 38016, 0xc4a121ab
+0, 46800, 38016, 0xc4a121ab
+0, 50400, 38016, 0xc4a121ab
diff --git a/tests/ref/fate/vp3 b/tests/ref/fate/vp3
new file mode 100644
index 0000000..7c3d7d1
--- /dev/null
+++ b/tests/ref/fate/vp3
@@ -0,0 +1,114 @@
+0, 0, 261120, 0xc50dec2b
+0, 3600, 261120, 0xaa8d4441
+0, 7200, 261120, 0x932b0d44
+0, 10800, 261120, 0x125e1af7
+0, 14400, 261120, 0x09a763a5
+0, 18000, 261120, 0x56939852
+0, 21600, 261120, 0x0eda6d35
+0, 25200, 261120, 0x2f0d3869
+0, 28800, 261120, 0xe177c34c
+0, 32400, 261120, 0x5d4e833a
+0, 36000, 261120, 0x42e26e7a
+0, 39600, 261120, 0xf5a60b4c
+0, 43200, 261120, 0x29938341
+0, 46800, 261120, 0x0a9ebb80
+0, 50400, 261120, 0xd18c6a11
+0, 54000, 261120, 0x4b8212ac
+0, 57600, 261120, 0x7902aabc
+0, 61200, 261120, 0x4babac44
+0, 64800, 261120, 0xf33efa46
+0, 68400, 261120, 0x110dd40a
+0, 72000, 261120, 0xae327a8a
+0, 75600, 261120, 0xab757d75
+0, 79200, 261120, 0xfbd1402d
+0, 82800, 261120, 0x4f2c5d31
+0, 86400, 261120, 0xc7ea2149
+0, 90000, 261120, 0x86072cf7
+0, 93600, 261120, 0x37c2f2ed
+0, 97200, 261120, 0x1d51ee83
+0, 100800, 261120, 0x72291b8b
+0, 104400, 261120, 0xe9c8ffaf
+0, 108000, 261120, 0x657a1615
+0, 111600, 261120, 0x6f832019
+0, 115200, 261120, 0xf4445a22
+0, 118800, 261120, 0x105306f0
+0, 122400, 261120, 0x34c0c36b
+0, 126000, 261120, 0x7767be18
+0, 129600, 261120, 0x88a7eaeb
+0, 133200, 261120, 0x797e69e4
+0, 136800, 261120, 0x78901f02
+0, 140400, 261120, 0xbc91758e
+0, 144000, 261120, 0x35d47b24
+0, 147600, 261120, 0xaf0ebc82
+0, 151200, 261120, 0x40e63004
+0, 154800, 261120, 0x70d1c5c1
+0, 158400, 261120, 0x8aea2b70
+0, 162000, 261120, 0x51f3cd81
+0, 165600, 261120, 0x8f8584b7
+0, 169200, 261120, 0x921541fb
+0, 172800, 261120, 0xddd3f1ea
+0, 176400, 261120, 0x6be2e960
+0, 180000, 261120, 0x72997a1f
+0, 183600, 261120, 0xe70fc009
+0, 187200, 261120, 0x816a0687
+0, 190800, 261120, 0x2aa79e82
+0, 194400, 261120, 0x85f2fe5c
+0, 198000, 261120, 0x000dd8b6
+0, 201600, 261120, 0x1be19dd4
+0, 205200, 261120, 0xadea80e5
+0, 208800, 261120, 0x0cc2204f
+0, 212400, 261120, 0xd62968a8
+0, 216000, 261120, 0x0afc75c2
+0, 219600, 261120, 0x82341f09
+0, 223200, 261120, 0xbf7e66cd
+0, 226800, 261120, 0x8f3491df
+0, 230400, 261120, 0xc316d383
+0, 234000, 261120, 0x3de7f632
+0, 237600, 261120, 0xda55cfb0
+0, 241200, 261120, 0xbd88bb46
+0, 244800, 261120, 0x75444b17
+0, 248400, 261120, 0x798cc498
+0, 252000, 261120, 0xf9a60fa6
+0, 255600, 261120, 0xbd8debd7
+0, 259200, 261120, 0x7c890029
+0, 262800, 261120, 0x7a75e44a
+0, 266400, 261120, 0x1f04611c
+0, 270000, 261120, 0x96b3ee93
+0, 273600, 261120, 0x7fc11f39
+0, 277200, 261120, 0xe87d6864
+0, 280800, 261120, 0x6797d904
+0, 284400, 261120, 0x9e3e7bde
+0, 288000, 261120, 0xc31a8039
+0, 291600, 261120, 0xe3ef4cf7
+0, 295200, 261120, 0x83c56fc9
+0, 298800, 261120, 0xb304f7aa
+0, 302400, 261120, 0x039a7080
+0, 306000, 261120, 0xffb08224
+0, 309600, 261120, 0xa7be783a
+0, 313200, 261120, 0x572beff3
+0, 316800, 261120, 0x1bc59ae8
+0, 320400, 261120, 0x11c8feb4
+0, 324000, 261120, 0xe2398651
+0, 327600, 261120, 0x37c3efba
+0, 331200, 261120, 0xb32f0dd4
+0, 334800, 261120, 0x66880c50
+0, 338400, 261120, 0x4f7392c8
+0, 342000, 261120, 0x3d5c08f6
+0, 345600, 261120, 0xfd129211
+0, 349200, 261120, 0x9b396ebe
+0, 352800, 261120, 0x75ab9a4a
+0, 356400, 261120, 0xf8c4e7ea
+0, 360000, 261120, 0xdd48c7c3
+0, 363600, 261120, 0xdebf20e6
+0, 367200, 261120, 0x35c32091
+0, 370800, 261120, 0xce5a49c7
+0, 374400, 261120, 0x69fc8e0d
+0, 378000, 261120, 0x43a08b41
+0, 381600, 261120, 0x01a0513c
+0, 385200, 261120, 0x1d3f490a
+0, 388800, 261120, 0xb44df252
+0, 392400, 261120, 0x1259753e
+0, 396000, 261120, 0x4a1538d6
+0, 399600, 261120, 0xd5ed4bd5
+0, 403200, 261120, 0xa21590b5
+0, 406800, 261120, 0xfb2de1f7
diff --git a/tests/ref/fate/vp8-sign-bias b/tests/ref/fate/vp8-sign-bias
new file mode 100644
index 0000000..4e4f6c4
--- /dev/null
+++ b/tests/ref/fate/vp8-sign-bias
@@ -0,0 +1,9 @@
+0, 0, 614880, 12ce23b288485be3ddbc1db28c21517f
+0, 3750, 614880, ce352e1079535ea058c0e9ad50f7cdb8
+0, 7500, 614880, 9f6bf2739a027dfd12c81586cf75d3a3
+0, 11250, 614880, 7593a85ab7790eb39d65fc53f769ed8b
+0, 15000, 614880, 52f47f1e0348f3297d9f233fb5405e8b
+0, 18750, 614880, cd51d2c200bfd66e8e1b0fd6b404570f
+0, 22500, 614880, cf535cf0a53e903cd98a9a944b72da6d
+0, 26250, 614880, 1b270fd2b56daa7892102c2885d23201
+0, 30000, 614880, ff373c0c8a4a319c84e72b1c3d76b399
diff --git a/tests/ref/fate/vp8-test-vector-001 b/tests/ref/fate/vp8-test-vector-001
new file mode 100644
index 0000000..df13892
--- /dev/null
+++ b/tests/ref/fate/vp8-test-vector-001
@@ -0,0 +1,29 @@
+0, 0, 38016, 83c78b5db579710f61f9354d5c51e8c8
+0, 3000, 38016, 8d089d226f52d6cdaffdb3fcc080b75b
+0, 6000, 38016, acaae81ca812145e85e0be83bdf54226
+0, 9000, 38016, e94651d798b6bf5f09a9bba10cacaf7a
+0, 12000, 38016, 60c2607913e528d501962bf407341731
+0, 15000, 38016, e683f2bf28b31e36db88087bd03b6917
+0, 18000, 38016, 0c2923785051bc9b90c2447a85527764
+0, 21000, 38016, 1bc97b6b2e4ca36b149c3768495747ac
+0, 24000, 38016, 0586d948ed3fd479c6dd08055973bcb4
+0, 27000, 38016, c9a1198e1680487c77a2d1631695aeec
+0, 30000, 38016, 547d8ffce9c085231c74717a9b815625
+0, 33000, 38016, d31c02a5591eb7bd8e73703252e1a1ab
+0, 36000, 38016, 23bafc8e22b2ed7e8c5e52369095cd30
+0, 39000, 38016, 9725d52d7810a19b20dcc9bb0fa36abd
+0, 42000, 38016, 7aefaabdcd2595939fd05078d01b484b
+0, 45000, 38016, 828e758d6f0b29b2693b2dc6b09249a6
+0, 48000, 38016, 53f09380dde1420ba270b74d8819537c
+0, 51000, 38016, 09791a7db3bc28258350cfdc95d8f224
+0, 54000, 38016, 2050271dc4ba3f3e427cf8088c96e28d
+0, 57000, 38016, 4e69d3f7cea45844b740368fcd4dd815
+0, 60000, 38016, 4ed07697e239b7f12ee6a97ad09c08fb
+0, 63000, 38016, 1437c129bfbda63ca1d39a94ee91b097
+0, 66000, 38016, 4fc951bf45e164b711591155a59c73fa
+0, 69000, 38016, 97d1007e27b4b9072751e87e8d1f1415
+0, 72000, 38016, 18c809835dcc3d30c93ae1be569dcd24
+0, 75000, 38016, de0fd0035a542791c4dda5735657efc5
+0, 78000, 38016, 27a70ff95d0cfa10f54652c9fb8a9db2
+0, 81000, 38016, 2285b9324ec91099626191f769962e44
+0, 84000, 38016, 56794d911b02190212bca92f88ad60c6
diff --git a/tests/ref/fate/vp8-test-vector-002 b/tests/ref/fate/vp8-test-vector-002
new file mode 100644
index 0000000..0ec5af8
--- /dev/null
+++ b/tests/ref/fate/vp8-test-vector-002
@@ -0,0 +1,49 @@
+0, 0, 38016, 872e9922f37f0e92c767d33e0a15b8e0
+0, 3750, 38016, ea5ad6c6ee4355018fc0ba83b5172836
+0, 7500, 38016, fe744612b2167c9ba6e1dc81c031e16a
+0, 11250, 38016, 744359695caee3f32307a2d7eef09e85
+0, 15000, 38016, 07211ac8d8bae4d931ade402ff6e3c12
+0, 18750, 38016, 2ce02854f228b1378d9dc34cab8d343b
+0, 22500, 38016, af5222ad42c4f22f22fbf19c26c02dcb
+0, 26250, 38016, 88538d39f2647df8fedf15bd1b767bbf
+0, 30000, 38016, d0d936471dd4e9922eb067c0f09eacab
+0, 33750, 38016, 03cb1f5c5026e96f6e686aa1fa9b1028
+0, 37500, 38016, 2ebe35e23d2244c5b0f777fbc01f8f37
+0, 41250, 38016, f9314f5ea91ebbaaed6e37ca0701ed67
+0, 45000, 38016, 37dca7530d09fd1e8bad154b9e312ea2
+0, 48750, 38016, 9841dc8ff6424abe362c4dfe03b5fbd0
+0, 52500, 38016, 72bd0b70c576dfb544f622c488217491
+0, 56250, 38016, 309b21c126153f20f312e38a8dad44e1
+0, 60000, 38016, 0acbb170ede66ebdae4e9d8e56908f75
+0, 63750, 38016, 318c9c3e531d00734b5f78433da176c9
+0, 67500, 38016, 0388dfdb2a792148b44bdb705cc2df99
+0, 71250, 38016, f440adff2b44888becbf3ca16e425441
+0, 75000, 38016, ac41431627d8d1712d40412ab8c3200c
+0, 78750, 38016, 417e1abbfe2a078663dae688ae4a9bb1
+0, 82500, 38016, 73d493bdf4a29d5cfeec610109f582a8
+0, 86250, 38016, 3c026a536ef36467d4a9db6bcc20cec1
+0, 90000, 38016, 57836430f2f10862b84541d99cca062c
+0, 93750, 38016, 04ad6fa97e1ff49931b574bdaaddd5db
+0, 97500, 38016, e94f2ec4cbf2b9067a4a4307eadebb6f
+0, 101250, 38016, e3542cdee672d97c65ab06dbe611247d
+0, 105000, 38016, 6c83c6c76aa8bf73646eb7a714cb42bf
+0, 108750, 38016, b5f64c6fc6d0c777a0a0b9097862f171
+0, 112500, 38016, 293dccaf5027759679bb9e8696b6381a
+0, 116250, 38016, 1a3d015ff9b164cb7922aef0aeac520e
+0, 120000, 38016, 93f9152d9425f0ec43160a0c01c485b2
+0, 123750, 38016, c7c4a8f78f781f70cedc44edc1d06911
+0, 127500, 38016, 21330442d5bef415fd765759d867c98b
+0, 131250, 38016, 6164258040f85206a3833aeb4f27a34f
+0, 135000, 38016, 3213e1405dfe6588a7334a8bc2b1e47f
+0, 138750, 38016, a619fa73f0081a349dfa2b000de19045
+0, 142500, 38016, 1f3cec4bb793dc4a118ddcf500090f37
+0, 146250, 38016, 12308ec77632ca10f1451aec8e62b82f
+0, 150000, 38016, 018c7f50ed4a494a9fcd32fdfed6705f
+0, 153750, 38016, a7282728fbd7e0b49a6967b0ea4e1f61
+0, 157500, 38016, 6aa15ab83e82f246ee9c7b7a040bfaac
+0, 161250, 38016, e4c17d2603e03753d54a142491cf5dc0
+0, 165000, 38016, 0a7331aa707e42e732f04e9175438195
+0, 168750, 38016, b522cfa3f3c706d1901231bb9e6b4b8a
+0, 172500, 38016, 7b2a70e47d9af98cfa6216ed2a7d528c
+0, 176250, 38016, b56e22bc9beacff9c3207b2757fc7f94
+0, 180000, 38016, a3dfc9461c0480cf56ee465ddabf0de1
diff --git a/tests/ref/fate/vp8-test-vector-003 b/tests/ref/fate/vp8-test-vector-003
new file mode 100644
index 0000000..9ff4200
--- /dev/null
+++ b/tests/ref/fate/vp8-test-vector-003
@@ -0,0 +1,49 @@
+0, 0, 38016, 96e6ce168b5ef377053e86ab5484e7f9
+0, 3750, 38016, 10fd750292d8522ab7ee577043604789
+0, 7500, 38016, e040995173dc5c85abbbe38f6823ff9a
+0, 11250, 38016, 5aa18f4fbd8b5b887d74f84cc92075dc
+0, 15000, 38016, f0dc7f520e88b94e5cb924d804b0472a
+0, 18750, 38016, 2375955dce3bb0a824779a800cd1555b
+0, 22500, 38016, 3e96a0e477de39530e1950cff284a854
+0, 26250, 38016, 6cd40fa8a89221f2b990bd8af2a9ee14
+0, 30000, 38016, 0b929243ceeffce836279e2aa84647cd
+0, 33750, 38016, 1e95f0ad25fe033076b57c3852bb3550
+0, 37500, 38016, 81aa93a3f9c56d2aa4b8285d3507e6b4
+0, 41250, 38016, cf9947a302dec306d7f487cf3a2731b0
+0, 45000, 38016, 3b9ca47752db95a049678da07974b476
+0, 48750, 38016, aa6788405dc47dd44867fca6c95ba3d9
+0, 52500, 38016, 276d1c62b908c081c7bbb78f943b0de1
+0, 56250, 38016, eb006b6218e457fd794e9b3a5dfbf638
+0, 60000, 38016, 9dd5312833e770286c5aa5436a00376e
+0, 63750, 38016, 7899278e66aa255ce5bf69a6e1137d0f
+0, 67500, 38016, 0ac7d062ea7550fa0717723b1272abc2
+0, 71250, 38016, d8f1bb881a46ecafcbbe457a004a71f1
+0, 75000, 38016, cc3a04b98159189a74b5241df540d8fb
+0, 78750, 38016, 4e29eb2c8c465ae9ffcfa28ec0b3694b
+0, 82500, 38016, 608fb6ba526e6aa4ad1c0290aedaa69d
+0, 86250, 38016, 4acc6a73547be6310b9a275436c55805
+0, 90000, 38016, 482cf409b86242d30f3a78a6c85364df
+0, 93750, 38016, a22cb76770f112eb1169218cc87c1e4f
+0, 97500, 38016, e74675b051ff05e178a9a24893721d99
+0, 101250, 38016, ee5061bff62c8c8603b7bc2bb2bb29e8
+0, 105000, 38016, a3c0ab11f338bd488c69f2b62e1e5a74
+0, 108750, 38016, 9f6b7e30e0ed4e272393b9a9957752e1
+0, 112500, 38016, 9cce9f2ffff1766d05bda04e46eff997
+0, 116250, 38016, 5105a2ba923bc6f21ea3d32ab1bc7bf8
+0, 120000, 38016, 957d619a1001e2b5e52db166b66b7f50
+0, 123750, 38016, fdb4e71cddeec8a321d9c8d4ffc506ce
+0, 127500, 38016, 9ee646940fb8ac2312d29e9f1c3b6d40
+0, 131250, 38016, a110e81d2105beae81cd36b15bc5ac2f
+0, 135000, 38016, 804b6d8fc99fadb9c6bfdae3becee6b5
+0, 138750, 38016, e217627bbaeebf30456e38aeb1f0746b
+0, 142500, 38016, 56468a2c548dd3085b4bce88c4a1e41d
+0, 146250, 38016, ef170e7f21e2b262525b43d6b25dec4c
+0, 150000, 38016, 3acc3c47def8a0fa0561eaacaf9e41a1
+0, 153750, 38016, 0c3e2187f13e4504fb4b246706bba83c
+0, 157500, 38016, 397326a22e6e49487309c39d64037df8
+0, 161250, 38016, 95236c1319b6f1f692b3998547811ee7
+0, 165000, 38016, 5aff1957504884abf74d6fb74b74b032
+0, 168750, 38016, 6de06343435a8926a746037cab5f633c
+0, 172500, 38016, 3de68e05ddf2c60ee9110048ceefeb6a
+0, 176250, 38016, e637fef689edad6ffd6eeb4a29004bf7
+0, 180000, 38016, bb809114af8df5cb4ed82d3a1d11a673
diff --git a/tests/ref/fate/vp8-test-vector-004 b/tests/ref/fate/vp8-test-vector-004
new file mode 100644
index 0000000..56e05b2
--- /dev/null
+++ b/tests/ref/fate/vp8-test-vector-004
@@ -0,0 +1,29 @@
+0, 0, 38016, 83c78b5db579710f61f9354d5c51e8c8
+0, 3000, 38016, d173eb8a8211a05672b43206609c9034
+0, 6000, 38016, 204e3e91613d647d30244c00fa2b9563
+0, 9000, 38016, 3cc1a395bd10a49b006741778285925b
+0, 12000, 38016, 024548b00dea4f104d6b9a728be05786
+0, 15000, 38016, 01401e9418f2e00ab4ffdb3296d40ffa
+0, 18000, 38016, 35d8b3c1ef9cb864315b7502b93629b2
+0, 21000, 38016, aeb44f0fe4c2eecb26c0bd657d65b00b
+0, 24000, 38016, 42e40bed012bacf59f0c41d4cfd3e52a
+0, 27000, 38016, 9796191fa2bd4572123ea043396e8485
+0, 30000, 38016, 2d6d68b902129f3c3f1730e73b98f9c9
+0, 33000, 38016, ba348b89248b92d0b86d794dc413e6a0
+0, 36000, 38016, 5ce49bf164033d49bef1b23120d202d6
+0, 39000, 38016, 54837a426c63a9c40ef8750232615dad
+0, 42000, 38016, 350bcddf9a34f5003f6f655aaa020a00
+0, 45000, 38016, babb82b1e2ca9315816b6f43b8ef84a0
+0, 48000, 38016, c770825785c51fa374fd5bb08ff9f536
+0, 51000, 38016, e9e0f92e416fcd27ca2e93a0804ac938
+0, 54000, 38016, e0f2b89423da549eaa8b2b89f956f0f8
+0, 57000, 38016, 9926b7e13b51115735eb0af8bb5e4ea1
+0, 60000, 38016, d6b30a058b854c54068ebfc2b05f8fa0
+0, 63000, 38016, a03048df79e41ada8a3ecc15a85e3f94
+0, 66000, 38016, 34bef9af0633a43434841fd5189c161c
+0, 69000, 38016, 219b447552b1ee409c1b9b56176d36bf
+0, 72000, 38016, 95ea99459eaebc2f7233feeaf0549224
+0, 75000, 38016, 34e08ce4067ca67ee9014cf628b6bb1c
+0, 78000, 38016, 066c09a20d11b9dc3fa6972fd7f242c4
+0, 81000, 38016, aed02c1951070ae5febea21ad54add55
+0, 84000, 38016, f5a0fde2d818c4aaabd29b069ced6aea
diff --git a/tests/ref/fate/vp8-test-vector-005 b/tests/ref/fate/vp8-test-vector-005
new file mode 100644
index 0000000..b672ee9
--- /dev/null
+++ b/tests/ref/fate/vp8-test-vector-005
@@ -0,0 +1,49 @@
+0, 0, 38016, e7a4be434df4bb524ba56a03cba901f4
+0, 3750, 38016, d903ade6d49e51485627c044fbb2190c
+0, 7500, 38016, af07ee39629b852870104cb9a9dde9e3
+0, 11250, 38016, 388a5f736db2de15342b62294fda4c82
+0, 15000, 38016, a072600936aa77738fa2fa88ba212849
+0, 18750, 38016, 0f96b1fb05b92498c0e1fcb6552e7e79
+0, 22500, 38016, 68b0db002a0127ee79a7c70062aa8c3a
+0, 26250, 38016, f9bc8edfeb9ceca9227a20cdab6788de
+0, 30000, 38016, bfe2115b000565abc3dce1d38f804ed7
+0, 33750, 38016, 67f17f96177f5464af1b97452560d2af
+0, 37500, 38016, 658278016e5409b69d014fab0d94d0ea
+0, 41250, 38016, 04dfd36afa0ddf22993d21c0a0fc715e
+0, 45000, 38016, 088e5a7cc75a895f01f7a4362f104bc1
+0, 48750, 38016, fb622a1a421b3689950f1adde9296dbb
+0, 52500, 38016, 3711ac7adc816614a2efda9e138f53fc
+0, 56250, 38016, 8e6fe3e68ccf53f23dd430b611fbfa6d
+0, 60000, 38016, 1c77dd651cd38d3308671f0705d29926
+0, 63750, 38016, bb5d7afccebc5d8a29f5980d21530d61
+0, 67500, 38016, e51f2eeb39afa50ea243eaca39974f82
+0, 71250, 38016, 7a73b1546fb5d8d4b05ebd4c839f74f8
+0, 75000, 38016, 62a0db46717d7fb6523c62968fd3bc85
+0, 78750, 38016, 98d6e520a164c42c5d19167c0ad48b22
+0, 82500, 38016, 9749a21ea432221323c1a6b61ea59d51
+0, 86250, 38016, 45fa9a9583db0139611b860bed8f6bc1
+0, 90000, 38016, aac06fe351759ca81a5028f2f4a7b534
+0, 93750, 38016, 7b7c7c16a377d61b6fe474541a18f0cd
+0, 97500, 38016, 2a84883fdfa8450d46b8b9352b7d5a87
+0, 101250, 38016, 3fc42d7dd6fa25ec17d8f2881f81b376
+0, 105000, 38016, bfb243be1eada17adab5580b748248e7
+0, 108750, 38016, 531fd799989db62210efc1999397d280
+0, 112500, 38016, 1c1e68673b295e17fca1b14d1eb1995e
+0, 116250, 38016, 12ee0f8810a1a3574337ef98987cf919
+0, 120000, 38016, 0c6ef1cec243c552e83054d5ac56a8c1
+0, 123750, 38016, cf0af3fb96e57143d335086485fbfa5c
+0, 127500, 38016, f5df68bb123d1f2f59ba471fbd118a9e
+0, 131250, 38016, 0b4a0cf5dd7968fd26959ad2849655b0
+0, 135000, 38016, 0ba766224688a95bfa43ac2453555972
+0, 138750, 38016, ef3f9fd7e5509bb880377fa1997d318c
+0, 142500, 38016, d7486c3176cef98c0046522acbdaa4f0
+0, 146250, 38016, f8dd15973993f4a2acd1d34b3610622e
+0, 150000, 38016, e99b7f294e6bdd9ae18f013f62174fcd
+0, 153750, 38016, 68ccf7e14a1055b24c5faf1b3a1888e7
+0, 157500, 38016, 2f230afb6e5c67e4b7e000317638e919
+0, 161250, 38016, 9cab31ac76ed26a879ac8b88bf7d33a1
+0, 165000, 38016, 1e2affc0f458808b4564bd0453565a81
+0, 168750, 38016, 79669092f6c73053c3de6d0d1408cc8c
+0, 172500, 38016, 7b27977ba84341b9af4d58a7864f763a
+0, 176250, 38016, 2481a387d65e7a16fe831b8da2200985
+0, 180000, 38016, fa5e3bc265877b30ca71de0a2b14663b
diff --git a/tests/ref/fate/vp8-test-vector-006 b/tests/ref/fate/vp8-test-vector-006
new file mode 100644
index 0000000..bbdf814
--- /dev/null
+++ b/tests/ref/fate/vp8-test-vector-006
@@ -0,0 +1,48 @@
+0, 0, 37697, 9ca5df27b0158aca2a38dff946f58c41
+0, 3750, 37697, 627129a99538ec1ac51be910ca92ebc4
+0, 7500, 37697, 6c2df1f21af317aa5bb68b161ca96c70
+0, 11250, 37697, d66db823863838ca5b7f9125609e7de3
+0, 15000, 37697, ecc970f8846290c0b7bf8d0865975cb7
+0, 18750, 37697, 2fe7575c448562e291933e297335e1c8
+0, 22500, 37697, e2a6fb8af11f65ce1153d6021df39e5f
+0, 26250, 37697, 4536008cd0a425c9a9d93cbb3e8ba640
+0, 30000, 37697, 478f042fff1cf0b6fd2eed391879c7ba
+0, 33750, 37697, f079ee39021b1dd730f80bfaff9a6ae4
+0, 37500, 37697, cb9b166c785ceabecf79e12e6068d4e4
+0, 41250, 37697, 6bd6f77dc9c45cec08949a42aa1c2653
+0, 45000, 37697, 1433577eb50b3270c0f1d6d26fb26277
+0, 48750, 37697, 2765b207d230efd9a3e2e93c641b8553
+0, 52500, 37697, a67e2f6bcf3b03e250c0ad8f1384ffb6
+0, 56250, 37697, b5ea80e2dbffefdd8a613c25ee7f5f0c
+0, 60000, 37697, e4b58bf735a8258842ad3c364eb9418c
+0, 63750, 37697, 8e5fc5d4c78eb495f62e4a014a6a2a6c
+0, 67500, 37697, 53bee2faf4cfae16037cda36a6194a57
+0, 71250, 37697, e5c2e1de872a7107f80966ae857557d4
+0, 75000, 37697, 882e46851681e6e3b376b5d1d9e139fb
+0, 78750, 37697, 40b199fe02b5885947af22ce1314a085
+0, 82500, 37697, 942b79dd5360c2a114db760424620a84
+0, 86250, 37697, fe9f69dd6fc113ceec9127d9e12b3958
+0, 90000, 37697, db13edae7e8e8a91d1ec84227c8f818f
+0, 93750, 37697, 1963ea61c3e93150f7604ee6fa09b12c
+0, 97500, 37697, 8cf43556160454d2353cedb9ba5675aa
+0, 101250, 37697, a5e6b5b00fea3d9b1bdbd01fda712f27
+0, 105000, 37697, 35f006cb6e570999b9011282c49c6d22
+0, 108750, 37697, d884d482371cb2727e26475bb390d38b
+0, 112500, 37697, a7233206056d3af69c6cff343b57de84
+0, 116250, 37697, 437492f3e594576e1c17065e0091aa2d
+0, 120000, 37697, 47f0677d9aff054056a194755628fdb8
+0, 123750, 37697, fc93105a16501763a6e6ba3445ee6f32
+0, 127500, 37697, 68612903d08399e0f0d9e28c1f18f6ea
+0, 131250, 37697, a340fbba24c73372e6248f10e878f11b
+0, 135000, 37697, 58c3561b06f9d866587f728877c08860
+0, 138750, 37697, f2dd2a029515ad9c0655ccf86a2c524b
+0, 142500, 37697, 789d43f63cbb302dad9f3e4b33713746
+0, 146250, 37697, d8f979aca1774470269283da048a505b
+0, 150000, 37697, ecc06e2175290319cb36614370c8ad62
+0, 153750, 37697, 5ba26b83766b666007b502a7194170e3
+0, 157500, 37697, 8163a20e9a345b70579c625c50e7ec73
+0, 161250, 37697, 1f1a497d768c4bcd57de11b21baf9138
+0, 165000, 37697, a21e9a52a982675815c9937b49ebb0ff
+0, 168750, 37697, dcc0bd83ce31ac99577cd2f9ced69096
+0, 172500, 37697, df36b27588b8515580d5015e5f66dbf9
+0, 176250, 37697, 156a6351549949953ce3197b990760a9
diff --git a/tests/ref/fate/vp8-test-vector-007 b/tests/ref/fate/vp8-test-vector-007
new file mode 100644
index 0000000..d4aa997
--- /dev/null
+++ b/tests/ref/fate/vp8-test-vector-007
@@ -0,0 +1,29 @@
+0, 0, 38016, 98bd0af6928c144888a9c320270e9f0e
+0, 3000, 38016, 9ff7cff703d58481acd233451388377c
+0, 6000, 38016, e4cd8815527846cc782ea61ef5a46e49
+0, 9000, 38016, db45275b87e194e5b505dd8c47da4f5d
+0, 12000, 38016, c889d0f7bd34faf4df0e0a9eb9fc292a
+0, 15000, 38016, 4dbfb1727baf9b75980e7fdd44ca0924
+0, 18000, 38016, 5f217ac95c891dc81f7193fc5352d582
+0, 21000, 38016, 11166789635e472f629510f551b11e2c
+0, 24000, 38016, 336e6e42e67e1ccb7cda6298cb63f192
+0, 27000, 38016, 02dbcff56882e304d5043d0f9b1ff9ff
+0, 30000, 38016, fe033ea2c6b8b81a9328b470f8b0d6bb
+0, 33000, 38016, 0e3330fe9a7c0439ff53f18f0d15eb48
+0, 36000, 38016, 6c0d7e042a3bb32a128c4a405f59b426
+0, 39000, 38016, 7e51afc33dbf4b77fc5735f5d9ec0248
+0, 42000, 38016, a8381f193f34a5071b8eeba7f5cd1968
+0, 45000, 38016, 501a7914b47ff85c24f0533ee98b9fe9
+0, 48000, 38016, 00bd5fbb7e3b66514e6c77c3a5f118c3
+0, 51000, 38016, 23e296d12a45909cadda252b9f4e67bd
+0, 54000, 38016, fa0b5c69bacf766551bebdde0910eb9f
+0, 57000, 38016, f5cc24d10d58ebc50503ca321db708cc
+0, 60000, 38016, 3997eb9ff6231dee9e23752776113cd6
+0, 63000, 38016, 68d4c9cd494d91dd70e7a94c7a4b9a12
+0, 66000, 38016, 647b34f3aa7318adce68803ba00104fb
+0, 69000, 38016, ffed5301bd6fddd1d24d12e6096cc8a6
+0, 72000, 38016, 9511388180811c10d166886868d6e71c
+0, 75000, 38016, a9b330803b8ccd91596591c0449423ab
+0, 78000, 38016, 69b192888cda09dac658d5820183a2e8
+0, 81000, 38016, 8886e5851e60a7474cc9e214ba6373ad
+0, 84000, 38016, f59e354deedb129a90ab3922838b03d3
diff --git a/tests/ref/fate/vp8-test-vector-008 b/tests/ref/fate/vp8-test-vector-008
new file mode 100644
index 0000000..105b6b4
--- /dev/null
+++ b/tests/ref/fate/vp8-test-vector-008
@@ -0,0 +1,2 @@
+0, 0, 1907424, 7146d3a72b6cb8e43ee5280ef8d661fe
+0, 3913, 1907424, 5a537e9710158efb5ad2683a1d3b4c72
diff --git a/tests/ref/fate/vp8-test-vector-009 b/tests/ref/fate/vp8-test-vector-009
new file mode 100644
index 0000000..c65210e
--- /dev/null
+++ b/tests/ref/fate/vp8-test-vector-009
@@ -0,0 +1,49 @@
+0, 0, 38016, b3a3121c796a60c88988fef5240a07fe
+0, 3750, 38016, f25147764829cf837e00b8fd6383e2c4
+0, 7500, 38016, 1b1552291a89c97d5deea145ab0ac0cd
+0, 11250, 38016, 0b2e75bbbe8f4248eb1519b6542efc96
+0, 15000, 38016, 99e8fc68547e119253ee3b8d79efa774
+0, 18750, 38016, 3aaf9210819238da7f704339bd8f262c
+0, 22500, 38016, de80b11f4c325e6d467d4abe5ad0db51
+0, 26250, 38016, 93d2fba68721768018b35ccac27b6bb1
+0, 30000, 38016, 07d7d4f8ad4151a013b652bec21ea9b8
+0, 33750, 38016, aaa95e4d39aa31cf68fdb8da268827e5
+0, 37500, 38016, 3607fcda0733e0b0fd10a8f7fbe6e39e
+0, 41250, 38016, 6d8cc24ea3b9827ef0147c8b7cc6938d
+0, 45000, 38016, 977a6b65d41b1b70dd4df9f526045675
+0, 48750, 38016, 9258b0e5fc2217c3aebbd96bb06c937a
+0, 52500, 38016, 887378a3aad18346a3827cd0aadc6873
+0, 56250, 38016, c2a3ff302d74eefd0855f2c862766aca
+0, 60000, 38016, 1a7d835f5a977e1fd8cc37bdd8d029ca
+0, 63750, 38016, 232be1f7e334001c3abbed550cc60c34
+0, 67500, 38016, e8cb3470b9a3ffbc7014793514dc89cf
+0, 71250, 38016, 54b20adca41910f003790a975ff7b50d
+0, 75000, 38016, 2c5fce4dcdd538f1d9377fa071f3d615
+0, 78750, 38016, d559840da8cef1f0b1379a592f708f0a
+0, 82500, 38016, ffab5f1060938a62cf8ef9df30ec8a33
+0, 86250, 38016, b7d93c8eda8cce4d387f2ea78c415704
+0, 90000, 38016, 7840aa27333e6350d114b256ab4304f1
+0, 93750, 38016, dc1f3b125177d0ad7f53dd058bba03e7
+0, 97500, 38016, 37134fcaad963a22f4df04c0765af455
+0, 101250, 38016, 4dc062fb76943a75e7b2428e5babbb3c
+0, 105000, 38016, dfda91bc05efc72073a2b6b62f294327
+0, 108750, 38016, 7ffc690c63a1c54e35978336dc5828a3
+0, 112500, 38016, 9ae31bacbc097c2ccf1500ff89882e46
+0, 116250, 38016, 1450c24713dcad41aeba1c44007bf12f
+0, 120000, 38016, f125bb52b8a1b11e076de55cca1069ee
+0, 123750, 38016, 555e1f2a6d293a0bdc9f92e9c3b3118d
+0, 127500, 38016, ec9a8d577a07a4f0d5deae63b3cea6dd
+0, 131250, 38016, a54f74e0ee329db4a78851bb7e54b2ba
+0, 135000, 38016, 99fcfe7ed9028bc443a790f9cf8eb812
+0, 138750, 38016, b9b994ffbe0150945b752a2120b4a475
+0, 142500, 38016, f00d70d8a28cecaaec1eb84592e3f6c3
+0, 146250, 38016, 3bc8ed07fc92c4d339164891e6624306
+0, 150000, 38016, d755777560d745d6bdfa01b9e9cbbcc0
+0, 153750, 38016, bcefb5ef8fae173e413406b4a60e2255
+0, 157500, 38016, fb47098c334b82764e30819066b13096
+0, 161250, 38016, 9e31f68fc96045bba43cf1253eedc419
+0, 165000, 38016, 53522d46d2ba91ab23693db7d41ecda7
+0, 168750, 38016, d66a074ebe6123590622e5cb308d75e5
+0, 172500, 38016, 6574fce175632a22fcc05b47157318e4
+0, 176250, 38016, 31f7fb05d060c1dea46044787772baaf
+0, 180000, 38016, cec733062ae526ae71b39ae0dc402482
diff --git a/tests/ref/fate/vp8-test-vector-010 b/tests/ref/fate/vp8-test-vector-010
new file mode 100644
index 0000000..ea5c8f3
--- /dev/null
+++ b/tests/ref/fate/vp8-test-vector-010
@@ -0,0 +1,57 @@
+0, 0, 115200, 3441ec1a9b9d325c9aeda44e3b68377d
+0, 3000, 115200, bff86a84fd673394f45c09d19a1ee0ac
+0, 6000, 115200, 8cd920f0de408e8cd883f9241680ff80
+0, 9000, 115200, d1b27cbb40859bbbb6da40dce6ddbf1b
+0, 12000, 115200, ca102ed86e45fe452f55a2cf0253de21
+0, 15000, 115200, ac7630be64017becd6e958df360263b5
+0, 18000, 115200, a044041ede746687d33ba6342d8d3edb
+0, 21000, 115200, 75d7c0eec357afd0c2d54e769f551b20
+0, 24000, 115200, eebd916e4fba53a66fc8e6ab98091a0f
+0, 27000, 115200, c0044160a944dcac81efe9f63def4bc2
+0, 30000, 115200, 9ba8b2ccbea045b39bd150ea383abc00
+0, 33000, 115200, 8d7654804fc62f7d52d5bf3d47f536e9
+0, 36000, 115200, 9fd6cd81fbe6cfc43e03cdf166c7ea93
+0, 39000, 115200, a1a494064dba27238005227c0808c5f6
+0, 42000, 115200, b8dca72164ea72b3f257c97c3ad87416
+0, 45000, 115200, 90ae005c0f3ddb4318318805b8fc29cf
+0, 48000, 115200, 8183e7b60f18887a9530a7905db4b417
+0, 51000, 115200, 1650ad1fff9076141f59b660c562f0f2
+0, 54000, 115200, e9ee675cafd270c366ac9d3ced5af879
+0, 57000, 115200, 2257172d6e8628b4dd4d9bf97e9ee2c3
+0, 60000, 115200, 577438f88feca7a876381a6fcf094684
+0, 63000, 115200, 4b37e90eb35cba66d31616169020c039
+0, 66000, 115200, 2c631ab87b8d3b7df13f888e3d6f1690
+0, 69000, 115200, e0d46e04d6a57b20c2b056cd0a0ca1ec
+0, 72000, 115200, 65bd3e207b8ed966b71f40a04f1900b8
+0, 75000, 115200, fd842606a20fb297463b7b3dd6efa2c2
+0, 78000, 115200, 778cd96eabe785320254db7692583f47
+0, 81000, 115200, 094272ad385a64fbc70a62f958e27eff
+0, 84000, 115200, cf5f7b3b94a00938b633ea1d9aa8e8dc
+0, 87000, 115200, 032e2f3649484ca17c739cf89052de77
+0, 90000, 115200, 9afe92189c21675745609e3b21a75941
+0, 93000, 115200, a5e087c496798bfbc64d6c26eee0b3af
+0, 96000, 115200, efb2716347ba2e01f7dc103d2a6cebb4
+0, 99000, 115200, c83541678dcca8937e372102bc4d1f68
+0, 102000, 115200, 3401ed97a9296610c8473dcf03e13f20
+0, 105000, 115200, 35af1327fafe026b6539951a9baee282
+0, 108000, 115200, f320e2d64192849c08c4c5e6d79e4ecf
+0, 111000, 115200, 5a661af83f451d8651cf081399d451b2
+0, 114000, 115200, 625d271b60d91229699f1de35d232b13
+0, 117000, 115200, 8e504154fa8eba5f9807bf40c647eea8
+0, 120000, 115200, 094ecb39a65c71e85d15a587472bb336
+0, 123000, 115200, 4d08bfe5771f00e13646be49e3471c4c
+0, 126000, 115200, 20841206e07721fb631088d492622543
+0, 129000, 115200, edf969142e1b053f951c1a5756f2b5d9
+0, 132000, 115200, 4959a13f20311d9b435e501fd753c94b
+0, 135000, 115200, a7f34e6c985d630af07a9f6dc47ea50e
+0, 138000, 115200, 96f6667d849f3abe4e85e3ce368b76ee
+0, 141000, 115200, a47d443c8aa5f2d2e3b44deab3f4f8e7
+0, 144000, 115200, 4ebda78d96facc4472ecdb4f667be0c6
+0, 147000, 115200, 6ba744c47edab85c6e77584e35e1b735
+0, 150000, 115200, 4d2e6882f15356171e4383111ec70e6e
+0, 153000, 115200, 85077fc81dff947b1251bfbd981aaf52
+0, 156000, 115200, f03e8879a5218387c502eaab31682df9
+0, 159000, 115200, 90f6128298cb52f769d697f9f842df27
+0, 162000, 115200, 700a705680c1a940141bc03ae5de391b
+0, 165000, 115200, 049b3df3ed9673ab8e0f0d0d896f65c2
+0, 168000, 115200, ca8c3e5509211dc92078371f06dc8635
diff --git a/tests/ref/fate/vp8-test-vector-011 b/tests/ref/fate/vp8-test-vector-011
new file mode 100644
index 0000000..99409cd
--- /dev/null
+++ b/tests/ref/fate/vp8-test-vector-011
@@ -0,0 +1,29 @@
+0, 0, 38016, 83c78b5db579710f61f9354d5c51e8c8
+0, 3000, 38016, 9b755a63c7c5352660a265f6e24991e1
+0, 6000, 38016, a591f0b04447d6d6dd9bb990502594aa
+0, 9000, 38016, 6ebbd38d20a4104a842c66df53a8b86e
+0, 12000, 38016, a114c37e74a4252ed66c5c4e7c8df84b
+0, 15000, 38016, 4bad182348dcfb627b3e15bc228a3c8f
+0, 18000, 38016, a843b5c80266f890044a4ba1f59de8ed
+0, 21000, 38016, 34816d9129f252afcbd56d6ad1df94c7
+0, 24000, 38016, 7d7d46cd08e18aea6fc52c0ec58a4803
+0, 27000, 38016, c96c3357d89534fce32251a0d52c68c5
+0, 30000, 38016, 5eb1329f955ab80696d8220605a51552
+0, 33000, 38016, 68b3d5162cd5b004a6dfeac705c75afa
+0, 36000, 38016, b79647c678fbbb9ffbd8c4ff63c05e43
+0, 39000, 38016, 4566eb5f995852d72b6913d2ca2e321c
+0, 42000, 38016, 02e7e951ac9e42eafb1260defaecf685
+0, 45000, 38016, ddbfa0f81a009c41271c9aa587e88baa
+0, 48000, 38016, 27d31dba74cb2170c456830a9f888c0b
+0, 51000, 38016, 0537650a41bb087a5fd33d6347fe9036
+0, 54000, 38016, df2205297d4f00164a3440c8fa1ac4ee
+0, 57000, 38016, 9942b757bd3839c1cd6b1068c68967f2
+0, 60000, 38016, d9284e1e989cd38d0226b1a3c6e89409
+0, 63000, 38016, 12427a3fdc22461fe9d6ff9dd5863bef
+0, 66000, 38016, 63f75f2a63630347671c0e6dd2f88bcb
+0, 69000, 38016, b161169a678e3959b492d83a03d47dee
+0, 72000, 38016, 50a6d4c8722197f0abd1028b968dce58
+0, 75000, 38016, c0f81ef6b25034cff00db1e3c369be97
+0, 78000, 38016, 01b502a4b69d5be7a82f292e735aa087
+0, 81000, 38016, 6bbff03307f93a654e4529e2a5092887
+0, 84000, 38016, 17ef5fd4bd1cc6030e1370a43f1d19bf
diff --git a/tests/ref/fate/vp8-test-vector-012 b/tests/ref/fate/vp8-test-vector-012
new file mode 100644
index 0000000..5af0e4c
--- /dev/null
+++ b/tests/ref/fate/vp8-test-vector-012
@@ -0,0 +1,29 @@
+0, 0, 38016, cc3069a59b6f4319761af2b39923a6e5
+0, 3000, 38016, c0bc935941d994c6af6a864f02a90a62
+0, 6000, 38016, 5b6073ce4a03967aa87e56dfa27e32c2
+0, 9000, 38016, 5310a9d6bf938ed89b10727f11e131c4
+0, 12000, 38016, 290fb1310ea10b862b51d37ff9d79f7c
+0, 15000, 38016, 0ca1accba77dc867df682b8e3768d6e2
+0, 18000, 38016, 2a90659dd4cd5d2f825641be55609d97
+0, 21000, 38016, e003db31fbfeab54385252e8c64197fc
+0, 24000, 38016, 0778609bd9626652e8a8dd07d5ef9f45
+0, 27000, 38016, 36eecf49c4aa2d8c3f232a1dbbb5f4ca
+0, 30000, 38016, f69f30dd8ebb7db4c51e0371f6a23736
+0, 33000, 38016, e9d5293db5122b9683a0853c2ef678cb
+0, 36000, 38016, 75d6a09bca67a82c8aacabb710558330
+0, 39000, 38016, 973d73aa4bb4e3de2cb1ba97685e08ca
+0, 42000, 38016, daf9ce67baaaa02bc56f49b540f22a30
+0, 45000, 38016, d08fd3b942e1219132015819c553f2c2
+0, 48000, 38016, 0aeea73b030e47bbd80bb0fb33fb6ebd
+0, 51000, 38016, 6e9f5f98fffe27abfae52304c693ae44
+0, 54000, 38016, 961c71a47741a1ac47fcaebf958647c8
+0, 57000, 38016, e75e53160b9f33eca0dfba999d8002eb
+0, 60000, 38016, ebb5d79336f75c44a09971dbba6947f3
+0, 63000, 38016, f02317fae5e143103a114ca692b58c25
+0, 66000, 38016, 8282867aa63fa23c48cc0216e21933cc
+0, 69000, 38016, d0d74ebbf56ca62825641028b66cdb20
+0, 72000, 38016, a8df24b0a22fe4fb334ea7063cba8754
+0, 75000, 38016, 8a570e42ad6ab42ead80b5022c2eb2f1
+0, 78000, 38016, dae566f13fa69de11db3ba7673e6211d
+0, 81000, 38016, 914ed8403cdbf4c54d0b9cb1eeee6832
+0, 84000, 38016, 18aa8d4bfe06a04ec4e9ccf9c7a92643
diff --git a/tests/ref/fate/vp8-test-vector-013 b/tests/ref/fate/vp8-test-vector-013
new file mode 100644
index 0000000..fbb1117
--- /dev/null
+++ b/tests/ref/fate/vp8-test-vector-013
@@ -0,0 +1,29 @@
+0, 0, 38016, ad137b9eae93daed28fe31fd5165b4d0
+0, 3000, 38016, 7cd527f647680c0eb305050d27fb8092
+0, 6000, 38016, f306e07a2e86c82a8cc1333be3812326
+0, 9000, 38016, 4ffd6065ef6af716fdb7388479cf300e
+0, 12000, 38016, e776c698ae335107d5794c02cf00d3ee
+0, 15000, 38016, c0043e3283b96a4aa58d2265b007e67e
+0, 18000, 38016, 235dd358e6adb3e144d7d957458e74a0
+0, 21000, 38016, 4d34b966a406e7c2d5cef029ddc76021
+0, 24000, 38016, 65f9eb823a63e17710b111892c415b70
+0, 27000, 38016, 84d4a1d510d1c1aa8f3e7232d574ba9d
+0, 30000, 38016, f3218df364f0e283df56b5d4a9cdfca9
+0, 33000, 38016, 3079d93a140b51fe3e7b4889fd5fdd24
+0, 36000, 38016, 4b76d7f904960792b78378c95453b77a
+0, 39000, 38016, 26cdd39f9cd862b383352bf769d212a0
+0, 42000, 38016, d98dbe7d7b8a5ccc50cb3a2e3dcacec8
+0, 45000, 38016, a931f142064062d7d2d1245278c6edd9
+0, 48000, 38016, 0c6dae06c59c040801be386d7e883f52
+0, 51000, 38016, cec4a68182fb14185360f57de81e73cb
+0, 54000, 38016, 7e819d1d928f974f25d45023a89a6765
+0, 57000, 38016, 6d9a9fd28212940497f881ef4886d756
+0, 60000, 38016, f22969fc06edc0c9190cae8bb22243ae
+0, 63000, 38016, 2fcd676dbf66f842e91649a3d6c80f50
+0, 66000, 38016, ce16e8920e91ec208dfb241addfc612b
+0, 69000, 38016, 3a205f364751ff5e72d7da20e5713f53
+0, 72000, 38016, 2305bcde500197d7697eec4ba89f1533
+0, 75000, 38016, 23712ae207ea2381f886ed038ec3852b
+0, 78000, 38016, 7197e717541573be07f9cda50ba524a9
+0, 81000, 38016, 3f3e3ec6d1d6f49021affbadb75c1fda
+0, 84000, 38016, 424fe8391a419b005a6f142ec65d802b
diff --git a/tests/ref/fate/vp8-test-vector-014 b/tests/ref/fate/vp8-test-vector-014
new file mode 100644
index 0000000..5ce3cef
--- /dev/null
+++ b/tests/ref/fate/vp8-test-vector-014
@@ -0,0 +1,49 @@
+0, 0, 37697, 7a0356dc950e79744d79c98e391ebee9
+0, 3000, 37697, 96e221e75c290dd847b8e55865073366
+0, 6000, 37697, 67638290841837c90f180a01094f9191
+0, 9000, 37697, 93c8e234e123f7a641c5eb44903b75ab
+0, 12000, 37697, b4fa5ce6089221863002019d99ae7f9d
+0, 15000, 37697, 5d3b48fbb681ef2b6a0a5e60c03ee5bd
+0, 18000, 37697, 26635956a9ed343428b36947723b4b94
+0, 21000, 37697, 18e9b11e10350ab20b89482c5d1c5cea
+0, 24000, 37697, 44fe40a7ce85552ccf95a451c5732e57
+0, 27000, 37697, f38758bf6d522023961d08719e92d3ce
+0, 30000, 37697, 28a2a9ebb3633a0822c9a283ab1ddea6
+0, 33000, 37697, 4b4485c9419710ad6d3e6aa11fe3a91b
+0, 36000, 37697, e3f6850a934c6e3e2fed3026e1e53066
+0, 39000, 37697, 4acff1abe788a4944474b82d10af172d
+0, 42000, 37697, 4cbfcc008923e8303df170d4e7b1cf34
+0, 45000, 37697, dde5de0c676f60b4cea26bbf024bbfb7
+0, 48000, 37697, fe1b0890eef18cd4989d251dbc3b7ef2
+0, 51000, 37697, 462303741de9904a13bd46534010f588
+0, 54000, 37697, 7ab2068505dbccdf522a08a65373b6b6
+0, 57000, 37697, cb63092b6880bbdbaa40b40d738aa4dd
+0, 60000, 37697, dca7556869370de600afbda82bb45fae
+0, 63000, 37697, 5f5cae9db9e3aa3f300706ebc3874987
+0, 66000, 37697, eaf7ba4f48eb5722c09420f2be4bc5f3
+0, 69000, 37697, dd5b43b72c8b9c3ad53afef0f8869a68
+0, 72000, 37697, f5d81cadb4b1f69e9700293e38ea36a2
+0, 75000, 37697, 1e56a6becf3099db71fbc7a996c4fbba
+0, 78000, 37697, 7e0676c4af74b59d9560d8b42d400de2
+0, 81000, 37697, 6717c3c344b45e9e202e808d19c9baa8
+0, 84000, 37697, 42b92f6fbd4cc5d4cf4f9b364a8a7741
+0, 87000, 37697, 6caca9fcc03e8b9d326aec18eaaae928
+0, 90000, 37697, cfa2798d156cabe81160c00939102d90
+0, 93000, 37697, 5d018cfac7da660819da2e5d25e8126e
+0, 96000, 37697, 761b7b2b64b22abadb89c58ab294520b
+0, 99000, 37697, 4e066fa627d4dbf3635148eb6b2a0477
+0, 102000, 37697, e0d6dd242cb99c7bc9826a05895344c5
+0, 105000, 37697, 84e7beedcba6da53feb722f30211d2f8
+0, 108000, 37697, af49b3fcc56b02ca746792b1d3bbe1c8
+0, 111000, 37697, cdd9f17b4501bc7f7bedb70f2e33f282
+0, 114000, 37697, 69d853dfd9b09d299faec521acb4e765
+0, 117000, 37697, c3497292359c1a1de81cd5fb062e5175
+0, 120000, 37697, 0e3994e4a62d8c922dbde51186615ea7
+0, 123000, 37697, 86bc5561c72bd17e7473f54f6b6311f1
+0, 126000, 37697, 0c747481e3dc575c6aad4507f8e62d8e
+0, 129000, 37697, 6779dfe5b6a7d4ba5ae5355058f54bc9
+0, 132000, 37697, d7d4e85f48d38c1106a031bd9b57d909
+0, 135000, 37697, a0ab20a38891925fd77ac2b075f0046f
+0, 138000, 37697, 88655045ce8c5cb4c4aa3a5071f1beba
+0, 141000, 37697, 7e849d493185a8f782b53a71151bae26
+0, 144000, 37697, a5b9a0cbfac73d2227118c0718cf9d14
diff --git a/tests/ref/fate/vp8-test-vector-015 b/tests/ref/fate/vp8-test-vector-015
new file mode 100644
index 0000000..7e97342
--- /dev/null
+++ b/tests/ref/fate/vp8-test-vector-015
@@ -0,0 +1,260 @@
+0, 0, 115200, 6b4c7cc0c6a7218362e43cffef6618c9
+0, 3000, 115200, e132a7b1bb4fb15b1019092aedc0e599
+0, 6000, 115200, b36975db60f24088d95385ff7e8b7b8a
+0, 9000, 115200, 4ae6a13ae0435afb2eac66f15a07b143
+0, 12000, 115200, d1de33515e29053171c9fbe969a33fa1
+0, 15000, 115200, cf01450481865c10765995a3b92b440f
+0, 18000, 115200, 274461d33aeab30885b23bf2818ad150
+0, 21000, 115200, cb434c5a829b3d6d15a6e76f05abd51f
+0, 24000, 115200, 512019fa16b1cd6bf308c91d6577cf2a
+0, 27000, 115200, 2d1174741c144b2162806373d0092739
+0, 30000, 115200, 8ec38a17566342a35598bd5ab6d290d5
+0, 33000, 115200, 262b71c9874cc7a5138b12b294575572
+0, 36000, 115200, bfe5e37095dc450dc717fda5ef77b6fe
+0, 39000, 115200, 7fbcdb00872206a597bb69ebe9221b03
+0, 42000, 115200, b599ac8568b6780dec25de4211e071ef
+0, 45000, 115200, 797085b07f4c1e4f4b0116d329403cf8
+0, 48000, 115200, a0d0821365658bee14767698877cc066
+0, 51000, 115200, 286a917e787d474eb78b4797a0909a5e
+0, 54000, 115200, 3548a320f6954c40a00ddf2e4ee212bd
+0, 57000, 115200, 80af737ca733afa28fdae06421b3cf8d
+0, 60000, 115200, f31a2b62cb69bc680b314a033f91881b
+0, 63000, 115200, 02e4a780b3a0d83a8897988ef17b548c
+0, 66000, 115200, 844929e7492b389fc520c5f75d37aa77
+0, 69000, 115200, 558ac4c1c11da425baf832a73e1ac2da
+0, 72000, 115200, 41b21109a7aa5f163ac0967ecd11f792
+0, 75000, 115200, a2a050c04eaa97db43a5a0a96d20a143
+0, 78000, 115200, 18d1881d44ab9dc959c34d92c0cabd36
+0, 81000, 115200, 53618af318cd187b4fcd5a3c22d3ab79
+0, 84000, 115200, 8028e6a6a6dadc8331e39cff1ba2b899
+0, 87000, 115200, 2c32a58d68595ff4100cec4fc1637c55
+0, 90000, 115200, 8ecc02d32f36edd167cabe2a7bc66683
+0, 93000, 115200, 7caa9ce69ac9f71170a69fbcef4c4b34
+0, 96000, 115200, df06a6a8a81979c39f2c3546eb03a3c2
+0, 99000, 115200, 2bfd578fa08335e975d498e11eadc8bc
+0, 102000, 115200, 0d78c5656d56e423ff31cab09855a335
+0, 105000, 115200, 7152d9e35748a7ec2e8da37f0b943325
+0, 108000, 115200, eb9e0e5cba76f0819da6256136ffd4e3
+0, 111000, 115200, c4e5ef875132c06a80f0afb3ee894684
+0, 114000, 115200, d2feb49297dd2f0a532479341d607e64
+0, 117000, 115200, d092d165608f405161fbf73a19df26ca
+0, 120000, 115200, cb228940384c3021af42b0ab81c65d7a
+0, 123000, 115200, 426decfbf29a025a7a5e376951c34b83
+0, 126000, 115200, 42c25e24bfd048bde0f9105d934cb81e
+0, 129000, 115200, 4bf37f8ccb2c4f42fa64a52a4699883f
+0, 132000, 115200, 5a00d85407910d4170d11511f03cc3a7
+0, 135000, 115200, 032072b8713a2cd7434b5be706a8667d
+0, 138000, 115200, e729c561b318aa14d7dbf96299c4675d
+0, 141000, 115200, e7e1d71c1c59bb759c89f15c6e8970f0
+0, 144000, 115200, 9c04011f4d92257a6dc112c5acad0f59
+0, 147000, 115200, ca7c7cbf52dd7af9a62212f3a9bd1f74
+0, 150000, 115200, 3cc9c4d3857d692e0dbfee682d63d32c
+0, 153000, 115200, 1188fc9620cf0d23af21d8823c127b80
+0, 156000, 115200, c614690b8d4d3bea47f1b236ff32d1d8
+0, 159000, 115200, d6ccde3360e6a05b61013e85f96de9e9
+0, 162000, 115200, 7f11cacc42d14121aeab487975ec190b
+0, 165000, 115200, cdd8b538ff107f88c5f0dc7128bc331e
+0, 168000, 115200, f43a387e9bb2f4db387d3f44da16457b
+0, 171000, 115200, b7ba01b86fce2252105f99848e2ac95c
+0, 174000, 115200, 094200f775b6ced838d0c37e0d0b34e6
+0, 177000, 115200, b2d2fa96666b96b7cb624133cf404b09
+0, 180000, 115200, d935644161a2b06f0efc75dc6d0fcf46
+0, 183000, 115200, 2a3be6460f313d7fdd6f6f9c70092a50
+0, 186000, 115200, f8254b6469b807ce0e9a1ea4b98a59db
+0, 189000, 115200, 43639a3293ec640b203e0c8a97e6f45e
+0, 192000, 115200, 055762cccc279c8dd27450ec1d512d5f
+0, 195000, 115200, a90dac910f3cdd216293bebc46b36501
+0, 198000, 115200, 3531ef2a4a59271f89ca0972b65d06aa
+0, 201000, 115200, 1f87adde14795639105be714247d0bd0
+0, 204000, 115200, e991cdd7912266937ca6f0d59199645b
+0, 207000, 115200, 5b98019db0fca644da5ee73e0160c7c5
+0, 210000, 115200, 6276f3907e4bb87885d21e11150d044d
+0, 213000, 115200, 985785d7a788dcc07bd5fb72d3dc758e
+0, 216000, 115200, 3379548a573d068d47d5f54aaf79c8a9
+0, 219000, 115200, a2b36848e7d19383cfabf8bdcabd241a
+0, 222000, 115200, 0aeda76888a5a2426ae3b390e38aba52
+0, 225000, 115200, 2c652e7850ccc10cbc7a3266f1fb6c00
+0, 228000, 115200, 5dfc9e4dce69f1f644fad5b69c0b4008
+0, 231000, 115200, da775fc1469012a0c717ebe5dc940e26
+0, 234000, 115200, 6185a863f7d023ddb2b049e265aab1bb
+0, 237000, 115200, 7a56397397191ab1b7c93a4bdc9b57c1
+0, 240000, 115200, 3e95a3f2c2660dc28ec64efef29615f0
+0, 243000, 115200, b9ba03bd7c09224174368a60af389b9c
+0, 246000, 115200, bfd23a13e077843506a01e44adb27c04
+0, 249000, 115200, 9025dff58a57abcc25da69fd233e312a
+0, 252000, 115200, ba4b91b0fe4d36f77b62ec3fe7b10a96
+0, 255000, 115200, 7955419ff2bc42b703dfc976576a5bd4
+0, 258000, 115200, 36d6a723ebb35c45128bfa8a7bba0d49
+0, 261000, 115200, 77503cc79e3cb0fc74745bac967fee1d
+0, 264000, 115200, a05af40cb4fc009fe94be6dbf148b453
+0, 267000, 115200, 35bc39585679f7c07f1b196879719ce6
+0, 270000, 115200, 48831c2e2212134ab192a123e847c157
+0, 273000, 115200, c09c37f9fd929185452a8beb3c61b839
+0, 276000, 115200, c534a38d586f3cac998240a7013c636c
+0, 279000, 115200, b598c6999442cf0c53ed6a19d1215eb8
+0, 282000, 115200, c639685c8f4af3d006df1833950943aa
+0, 285000, 115200, 351e1c089ba5b9024de6e311c4a4afd3
+0, 288000, 115200, 67d8ea902179548d0b01544249b2411f
+0, 291000, 115200, 3717ddf0edbb2020a5b974678d358d25
+0, 294000, 115200, 85f7c6861241e3f43fc63c397c8c3c37
+0, 297000, 115200, c5b23b4d3d141d8cfbc5354ca1cfd34d
+0, 300000, 115200, c2e42fa6b11cdc3abcf3ee0c3f75a459
+0, 303000, 115200, 34df411aa928d5df3628644d9a38c768
+0, 306000, 115200, a768b448b6c894d9b927bc880249079a
+0, 309000, 115200, a2e9ad0d0ad733b8ccacf0379b05f6f9
+0, 312000, 115200, 4b485e9496ab4d417b8cffaf8754f5cb
+0, 315000, 115200, 47007fabfacd9e9c5a3997fb70d45895
+0, 318000, 115200, 4962433241c7509801b46bea70f38269
+0, 321000, 115200, 7b4593b45606650e78aec67722cfc2bf
+0, 324000, 115200, 882bcbf7d2c12e93df2fbebc6ac19dd8
+0, 327000, 115200, a2998a9c648817236bfffdae454f9fa1
+0, 330000, 115200, 56775760fa99e9a9b7293ddc78a44ece
+0, 333000, 115200, bb245d095424c28dd2ace22a5a511d6a
+0, 336000, 115200, 598c54d2b207190ed549dec7390a4190
+0, 339000, 115200, c73f16b2709527fce3d725ade5aab2fc
+0, 342000, 115200, 32dcad6eb17bee583884029fe18c07a7
+0, 345000, 115200, a1297c404a0d22e0e8e1e4ef67696606
+0, 348000, 115200, 2fef1ac7becf9b8c9f3ac2310f444e3b
+0, 351000, 115200, 0f03614ed3daec6c37c5b564ad24f595
+0, 354000, 115200, 9b175a6353ec377da408b0cf03388081
+0, 357000, 115200, 37b991b4a216a4847d0768a3b878284a
+0, 360000, 115200, faafcd544080a6a4f87a0d0a393ba37b
+0, 363000, 115200, 43ede087f37c1b0392829bbc668242fc
+0, 366000, 115200, b7ed1274016c4d1810d8999d495b7370
+0, 369000, 115200, 22af7bfc83c6e1f2eff2ae26e115b446
+0, 372000, 115200, 969b22455f3be057036ddd5a329b1de3
+0, 375000, 115200, 63c24b8a3d6c3a4c2fd47c48860abff9
+0, 378000, 115200, b407ddc89c538d7b6fb70e48493f872c
+0, 381000, 115200, 5de69fb9e1cd425cd3931116803f5391
+0, 384000, 115200, 07fc7a5cb360edae97db999c2a8d2716
+0, 387000, 115200, 602a17c58cac811e6e71e33448931ce5
+0, 390000, 115200, 44087725484198c8e846d112583e574b
+0, 393000, 115200, 0d81da0d23d196ff972894878bd17b73
+0, 396000, 115200, b3cd65f1bd2274895e54da99bb4c4f07
+0, 399000, 115200, ae8ca35672d8352af49f37f5174c8fbd
+0, 402000, 115200, 9eea1ff900cf680e8208cd5d07a4d284
+0, 405000, 115200, 5a47f272dfda3fe61955875f761a71f2
+0, 408000, 115200, 544558333008db01451c886ac0b62c47
+0, 411000, 115200, 5f8e4f3b11d7f5a28ff5cd9f3a6853bb
+0, 414000, 115200, e9bc3da7060457f2d52a5bf6fe3bb515
+0, 417000, 115200, 6aea6851a092260ae6594c6d9170ea8e
+0, 420000, 115200, 38e7fa5bea809a984a5f810940ca0e49
+0, 423000, 115200, 9e8a23ac9067a1acf8472d7aa3b9811e
+0, 426000, 115200, 6f25f5873afd5c341ca6b3eb284be809
+0, 429000, 115200, 40c3240e6cde94aae793a52cb46487da
+0, 432000, 115200, b7f1f13842fbf0c6e085280eb89b956f
+0, 435000, 115200, 1f059372d8bf4dadf78d8e215bbf9786
+0, 438000, 115200, 50c1d6b76930e765bff5ecbaaae686fe
+0, 441000, 115200, 5bd8cb05ebc034192e08ca8ce18a7964
+0, 444000, 115200, ffc0c20b07e26857dc4f2c079a2ad675
+0, 447000, 115200, 5dafb6ac0953c254182dba124e213c07
+0, 450000, 115200, c774ed25712a38603fe2e224802768cb
+0, 453000, 115200, de549cc803a6138d483be15b28ef2286
+0, 456000, 115200, c963d9bc79c1dd2a47f7f8424c56239e
+0, 459000, 115200, 9df993e0bef1bedbce1a6b596f2c64f4
+0, 462000, 115200, 875792bde0f45358009b506840be68e1
+0, 465000, 115200, 7f8c57083d2df08db6287cb025260788
+0, 468000, 115200, 47eb13bc0942b5cafeea324fc5bf5cd5
+0, 471000, 115200, d89129c7528ff7372f23d1191c75e336
+0, 474000, 115200, bdd14e38b00075d8da485d1517dbbd65
+0, 477000, 115200, 0e8e21a50a5dd1ac6fc881ad38ec38bd
+0, 480000, 115200, a0fce98c23a053b4073715c554b9dc44
+0, 483000, 115200, 18bda80360c72d04c60016682b1f6c8d
+0, 486000, 115200, 306d7556c18dcf58c8183959d1c34c2a
+0, 489000, 115200, 7ada9d23b96ef41322497d1077b00c4d
+0, 492000, 115200, d7df0508be4bd0c3e83f346f0b9a1868
+0, 495000, 115200, 749725f425f6fd4a79269bca900d09ae
+0, 498000, 115200, ed30973158a576e2919e2fcfd00987fc
+0, 501000, 115200, 2486d8b742ccc50cf8683af7f4502aec
+0, 504000, 115200, bdfb21e4236c904aeacd7b094fcffe98
+0, 507000, 115200, df2ef3e452731053ade82506c013164e
+0, 510000, 115200, 4695bfd9aa8e5667572f8f2142c6e538
+0, 513000, 115200, 649f5315cff1d28f0183144bf4d4eea4
+0, 516000, 115200, 450e987b9d6075d32e21d030bc385833
+0, 519000, 115200, 7aec79b25dabfcc2eb2f32e7dbff85f2
+0, 522000, 115200, c9c2a96239ad556a2ee496d7c4c965c1
+0, 525000, 115200, 3a038e48aa1238b62d431823653bc45a
+0, 528000, 115200, 6d5c8de6a281dbce68998b2c38063f33
+0, 531000, 115200, 045032f57d6a50ae148f4372f5083a62
+0, 534000, 115200, 5f39172951e083e712c3b1c528e61a4f
+0, 537000, 115200, 5a49eea76b6a86e305fb207fc1479264
+0, 540000, 115200, 33ca5fb5f3e4ff3a24235da71c5730d5
+0, 543000, 115200, 81f231d20426c5cbd02a85a425f5d0b8
+0, 546000, 115200, 302d94aa9a8d3828cf74c8b2b7e7fdd5
+0, 549000, 115200, c56f4f0c32b0f2c409b64ed10216a40a
+0, 552000, 115200, 9cf7f51e1527f11c38c395bac94849d9
+0, 555000, 115200, 0f17e427d14db658131eb0ccdc2a97ef
+0, 558000, 115200, 2624dd6b8e4e95770f132d90aa6f6119
+0, 561000, 115200, 9ddabfd5f803014443c2a0686869c546
+0, 564000, 115200, 0170cb86a377d791d7cbee2af0836db7
+0, 567000, 115200, f43a7c63bcafb51ead65e2831610612c
+0, 570000, 115200, e7000913b11bdeb74ba4eca110df8470
+0, 573000, 115200, a4208c5fcd101ceb5a976838ae9a811f
+0, 576000, 115200, 8ddcb546ac632c967e879fb5101afa24
+0, 579000, 115200, 547007771194373dd246586744130f7c
+0, 582000, 115200, 3608a46fee2731341ae9f71d3a80918a
+0, 585000, 115200, 758692e173552eb3439a572c953dda0f
+0, 588000, 115200, 481f456d6c6ac2e0325acba5eeabcd26
+0, 591000, 115200, c749a3ef8641d5ec4f25c611ffad1000
+0, 594000, 115200, 93f089f7f1e78b1a4185c0b0d99875fb
+0, 597000, 115200, 1159712bb4dbaed38d2a7558335f4037
+0, 600000, 115200, e8dab85a977f525d4d9b448e4278a34b
+0, 603000, 115200, 780055af1414e7693777a18428b20a07
+0, 606000, 115200, 59252515451fd96ca3f1194d5aadc3a7
+0, 609000, 115200, 0a977d6db761c149316417988657610a
+0, 612000, 115200, ed81d3a10369c12543f9bb6822a249b6
+0, 615000, 115200, 341e844231f6b55ee3c1eb22ca1bac8e
+0, 618000, 115200, d0a180c7d15e30a71e297fda0452c153
+0, 621000, 115200, 58d6f2522ecd8e5fea34cc9f10da2a88
+0, 624000, 115200, dc8f96811577f4fd3e6624abae42f449
+0, 627000, 115200, 3624a2e95f94a0a4413e464f4bf93dcd
+0, 630000, 115200, cb0deeb5f2d570ca23e3be3ab9231fe9
+0, 633000, 115200, 5080848626a52e30eb0f64f234ca3e57
+0, 636000, 115200, a31c9fe4255318d86e7855f01588220f
+0, 639000, 115200, 6c25fd8d1f0e898f6078decc4220d47d
+0, 642000, 115200, 77e52da08ab57ba5784ce42872cc01cb
+0, 645000, 115200, b4a87059745b3b862ef7431a9630f16a
+0, 648000, 115200, 1dadc814514ef00f11010df21d8a9494
+0, 651000, 115200, 5c816a0bbc8ed8fca166aa454093cb59
+0, 654000, 115200, 10320c174423d1712d9ce812701bcaf9
+0, 657000, 115200, 279c9398657af129e072165f41e0fb8c
+0, 660000, 115200, 49d88374bc4d965d3cee3274c7cd9906
+0, 663000, 115200, 48871e22f635f50569dea1bd5ca40d5c
+0, 666000, 115200, 3b8396580f8fbd99daca4df13662f1fc
+0, 669000, 115200, 569245e1bf3cb42aa95f765a8449980f
+0, 672000, 115200, c5cab497d244447df0ab832dcc9c5968
+0, 675000, 115200, 0a98ca4f1d771c4bc0286b825d085955
+0, 678000, 115200, e4a55f175c3933f02ccf74ccf2961da2
+0, 681000, 115200, 462dca7f377d708e753ef0bbde19a090
+0, 684000, 115200, 6f1680f498b0ed6f89a834b5700cc48a
+0, 687000, 115200, 996414e2e3a4bac5868ceeb25b84e6e4
+0, 690000, 115200, 6ecb4d4b857578d32f716c56dc7e6be9
+0, 693000, 115200, e05c8e33157e20c8e8f255e937d6b6cb
+0, 696000, 115200, 6542744da147d16533e41dad287a54fc
+0, 699000, 115200, bb4b6921d2855025fbcaff4c12299d02
+0, 702000, 115200, 6bc3e605759725012f7e44f1285b0899
+0, 705000, 115200, 0be37ecb7cec0cf8a0f9bbc3c590ba98
+0, 708000, 115200, 4f1103e5923ba8dea3e99c8b75eaed3c
+0, 711000, 115200, 220a8fb0409112c4f4ee769880717fea
+0, 714000, 115200, e4c612263cfbc0f41283fd1e88e2ff52
+0, 717000, 115200, ede2bc67ad87cd78191b742dd56419b5
+0, 720000, 115200, ded6a1d0690603aea233e4d624aa60a9
+0, 723000, 115200, 59c8b53e47ebdab696547a887163b272
+0, 726000, 115200, 985f8afbc6df2d64d601d2fdc93571d7
+0, 729000, 115200, e595f0aa7b6b62094f0ad84252105f55
+0, 732000, 115200, c2fe4382a1740bcfc2f4c3573c6c3176
+0, 735000, 115200, 880d8c906a8b39a61b68eb0ada857e5f
+0, 738000, 115200, 9a3ca55d2d75e3c41a86aea2ec87ff76
+0, 741000, 115200, f800751663dbefa61c33c3ebbd5430b4
+0, 744000, 115200, d904333c0c76235c8ffdfc81dffddb46
+0, 747000, 115200, 6a633a9a7686a9a02bd252ec8bcff4fc
+0, 750000, 115200, 930d06ecc252a911a60c2d9d4f2618e6
+0, 753000, 115200, bb146a4410c34bba74883d8ae478f47b
+0, 756000, 115200, be8ab9fc95685ebec64ff1f8129afa35
+0, 759000, 115200, d1f871ea3ceb38bf2b6d00ebfc38187a
+0, 762000, 115200, ba33366e050a5f5abbf8202e0afbb9e8
+0, 765000, 115200, f706356e12cf4082337bb8f7a5a10673
+0, 768000, 115200, 6e8200d3c1cccc0f810985ea2a2030f6
+0, 771000, 115200, caafdc1810556197df6f42336edcc07b
+0, 774000, 115200, 5321ff525f5bb5063443a3dc43fc42af
+0, 777000, 115200, c24bdd3b935f7ca6e9e105b1ae8504db
diff --git a/tests/ref/fate/vp8-test-vector-016 b/tests/ref/fate/vp8-test-vector-016
new file mode 100644
index 0000000..1a82145
--- /dev/null
+++ b/tests/ref/fate/vp8-test-vector-016
@@ -0,0 +1,29 @@
+0, 0, 38016, 905a823da31f71f9c25ebb8dfc9ddd3c
+0, 3000, 38016, 9a1b97859b2f774954dbf96f45a22a0a
+0, 6000, 38016, f0f5651b32577549dc2e6e3050125229
+0, 9000, 38016, 9edf800d31dc653a23ed71d0f3fc32e4
+0, 12000, 38016, 78dd1fa96e63c177f2b90d702c92f48c
+0, 15000, 38016, e1cec336383c4ea63ccaff8bfa5c8e24
+0, 18000, 38016, e8b5a454e178ab7ba9b83dfc10b4171e
+0, 21000, 38016, 572dbaaf319f1681749135c49940c64e
+0, 24000, 38016, b0e8313de033cc75a78532789bb6a3cb
+0, 27000, 38016, ffc5581d83ff67b549d63c7de1a1e8cb
+0, 30000, 38016, 8ae3fcd3d74947d434b7c5f9ee08bbbf
+0, 33000, 38016, 3adff74d92ae0a463dddc6f89965f706
+0, 36000, 38016, f08355430fdf5bb16a91eef05f03186b
+0, 39000, 38016, d477eb8150a1a94dd6af7f067e8c0429
+0, 42000, 38016, f860f225e27871a17060373b79007ec6
+0, 45000, 38016, 22a25c07ac5e7c67df793e0d3169386c
+0, 48000, 38016, a96f9cef4efe74db0cce039c85c03c4d
+0, 51000, 38016, ff9c93cbc364976044144ee631f89bd2
+0, 54000, 38016, 3a6b43090adb6c8b5188d544a08295a8
+0, 57000, 38016, 7f41a10ada80865d24585860065aa5e4
+0, 60000, 38016, 099847f606672fd065e6841000cafcb3
+0, 63000, 38016, fbf543c12ce48633e6d10717862c35a7
+0, 66000, 38016, 1b9956d8a6c45e39d219da33ff7c334a
+0, 69000, 38016, 911eb8f478485c0f4eef1d03f53aa80b
+0, 72000, 38016, b801570a437439ce12c5037df0235742
+0, 75000, 38016, 8d231805d741abe79670a0e9f13712ea
+0, 78000, 38016, 87bfcc2c88c4471067c07fbcf635870d
+0, 81000, 38016, d51b6999afde880bc77597063b58d28f
+0, 84000, 38016, c69c07a34bfad3b5a95b19a84e991c13
diff --git a/tests/ref/fate/vp8-test-vector-017 b/tests/ref/fate/vp8-test-vector-017
new file mode 100644
index 0000000..c461420
--- /dev/null
+++ b/tests/ref/fate/vp8-test-vector-017
@@ -0,0 +1,29 @@
+0, 0, 38016, 905a823da31f71f9c25ebb8dfc9ddd3c
+0, 3000, 38016, f0f411dd067bff05d5d9c64e3f52a4b1
+0, 6000, 38016, c8696f8fa56b4adf18f3db0c384d968f
+0, 9000, 38016, 5772aa26a95092b4a8a117e97d6dde49
+0, 12000, 38016, fc52254ea1cbcc2e7a5b126d8c44a023
+0, 15000, 38016, bf6208554657f568ad69d5c60f692fdb
+0, 18000, 38016, 3a68eef642b250177592455f4aa925d9
+0, 21000, 38016, 98102b7bd56cbe456d86c93e8cdd48eb
+0, 24000, 38016, 59d54b7d97600b2890c8abab2af9a7dc
+0, 27000, 38016, ba4b4bb534ee2a00f418828b9723d996
+0, 30000, 38016, feb1115136fa96d5e9425ac18261de7c
+0, 33000, 38016, ef7eb6dc656c2bd7447c7d8f650108c1
+0, 36000, 38016, 89ec385a0d34c8fd5b1334d8756c96b9
+0, 39000, 38016, 27bc439dd8e6d50c3c7a6e0b390e7418
+0, 42000, 38016, ec36c065d8b668fabb6b16ecc01eea0a
+0, 45000, 38016, 5c94f9b441fc70f62856c835f9e9ad50
+0, 48000, 38016, 4b6c1bd876b00052b39e6ca91cad9c05
+0, 51000, 38016, 1099121afd681cf3218dffb9714a0fd7
+0, 54000, 38016, d0c1de888fab35f33c1148dc80494d20
+0, 57000, 38016, 745941ea768d06ea27c3fbca782e3591
+0, 60000, 38016, 09f85054f188da6f7260debf6b71bbb1
+0, 63000, 38016, 2bdd642a7551681f1ca9680a0d9183a8
+0, 66000, 38016, 054aba9db9790a0f1c79db491a6cac6d
+0, 69000, 38016, fa4b52162f6da0c15100f4382d92d7e4
+0, 72000, 38016, 88c589535811dd394bd1723172329629
+0, 75000, 38016, c11cc1a30199d46db048120969dc4118
+0, 78000, 38016, c61207280f40620f8cd5e962f3aa160f
+0, 81000, 38016, 8a721ecbad0b2f17aabb2d06e27c00aa
+0, 84000, 38016, da32f1d272e065cd31415b23f86837cc
diff --git a/tests/ref/fate/vqa-cc b/tests/ref/fate/vqa-cc
index 5ad2916..d7d7f10 100644
--- a/tests/ref/fate/vqa-cc
+++ b/tests/ref/fate/vqa-cc
@@ -1,5 +1,5 @@
-1, 0, 22048, 0x0665d7f4
 0, 0, 192000, 0x00000000
+1, 0, 22048, 0x0665d7f4
 0, 6000, 192000, 0x00000000
 0, 12000, 192000, 0x00000000
 0, 18000, 192000, 0x00000000
diff --git a/tests/ref/fate/wmv8-drm b/tests/ref/fate/wmv8-drm
new file mode 100644
index 0000000..0150535
--- /dev/null
+++ b/tests/ref/fate/wmv8-drm
@@ -0,0 +1,162 @@
+0, 0, 84480, 0x7760a00b
+0, 3750, 84480, 0xfe39a1db
+0, 7500, 84480, 0xfe39a1db
+0, 11250, 84480, 0xfe39a1db
+0, 15000, 84480, 0xfe39a1db
+0, 18750, 84480, 0xfe39a1db
+0, 22500, 84480, 0xfe39a1db
+0, 26250, 84480, 0xfe39a1db
+0, 30000, 84480, 0xfe39a1db
+0, 33750, 84480, 0xfe39a1db
+0, 37500, 84480, 0xfe39a1db
+0, 41250, 84480, 0xfe39a1db
+0, 45000, 84480, 0xfe39a1db
+0, 48750, 84480, 0xfe39a1db
+0, 52500, 84480, 0xfe39a1db
+0, 56250, 84480, 0xfe39a1db
+0, 60000, 84480, 0xfe39a1db
+0, 63750, 84480, 0xfe39a1db
+0, 67500, 84480, 0xfe39a1db
+0, 71250, 84480, 0xfe39a1db
+0, 75000, 84480, 0xfe39a1db
+0, 78750, 84480, 0xfe39a1db
+0, 82500, 84480, 0xfe39a1db
+0, 86250, 84480, 0xfe39a1db
+0, 90000, 84480, 0xfe39a1db
+0, 93750, 84480, 0xfe39a1db
+0, 97500, 84480, 0xfe39a1db
+0, 101250, 84480, 0xfe39a1db
+0, 105000, 84480, 0xfe39a1db
+0, 108750, 84480, 0xd71961b4
+0, 112500, 84480, 0xc80dedba
+0, 116250, 84480, 0x34d8b538
+0, 120000, 84480, 0x1a86b8e5
+0, 123750, 84480, 0xabf7c25d
+0, 127500, 84480, 0x912600ee
+0, 131250, 84480, 0x7ee7c70b
+0, 135000, 84480, 0x09c5b0d1
+0, 138750, 84480, 0x6dbe6c0c
+0, 142500, 84480, 0x0fe0a120
+0, 146250, 84480, 0x2352d3a2
+0, 150000, 84480, 0xb22ce92e
+0, 153750, 84480, 0x31db0099
+0, 157500, 84480, 0xad2dd73a
+0, 161250, 84480, 0xb9af8e20
+0, 165000, 84480, 0x7b956549
+0, 168750, 84480, 0x3f774b87
+0, 172500, 84480, 0x824a23a3
+0, 176250, 84480, 0x4469a8d8
+0, 180000, 84480, 0xc80c7a0a
+0, 183750, 84480, 0xcf958549
+0, 187500, 84480, 0x449746e3
+0, 191250, 84480, 0xbac66a82
+0, 195000, 84480, 0x99e85855
+0, 198750, 84480, 0xa4a17d17
+0, 202500, 84480, 0xe29c7587
+0, 206250, 84480, 0x551de592
+0, 210000, 84480, 0xe0877bce
+0, 213750, 84480, 0x9660eb35
+0, 217500, 84480, 0x0a34b644
+0, 221250, 84480, 0x352919f0
+0, 225000, 84480, 0xef56ce27
+0, 228750, 84480, 0x030fe862
+0, 232500, 84480, 0x2eba33e2
+0, 236250, 84480, 0x242de401
+0, 240000, 84480, 0xbadd61ca
+0, 243750, 84480, 0x2060465b
+0, 247500, 84480, 0x256e6965
+0, 251250, 84480, 0x243b7084
+0, 255000, 84480, 0x8b3c0b47
+0, 258750, 84480, 0xc174a9af
+0, 262500, 84480, 0xb6d48686
+0, 266250, 84480, 0xa3dd1871
+0, 270000, 84480, 0x04cdcaf7
+0, 273750, 84480, 0x55f89c94
+0, 277500, 84480, 0xda657032
+0, 281250, 84480, 0x38ba7698
+0, 285000, 84480, 0x4d03a7f2
+0, 288750, 84480, 0x115d9035
+0, 292500, 84480, 0x24c6acc6
+0, 296250, 84480, 0xdd2bbcae
+0, 300000, 84480, 0xb4fee0b9
+0, 303750, 84480, 0xc51c14e0
+0, 307500, 84480, 0xfb7737de
+0, 311250, 84480, 0x38675fb0
+0, 315000, 84480, 0x4752c710
+0, 318750, 84480, 0xfeb7491b
+0, 322500, 84480, 0xaa248122
+0, 326250, 84480, 0x9a4af87c
+0, 330000, 84480, 0xedcf09df
+0, 333750, 84480, 0x563a05df
+0, 337500, 84480, 0x0dde1e03
+0, 341250, 84480, 0xd8f0ff65
+0, 345000, 84480, 0xbeb9ae1a
+0, 348750, 84480, 0x416d1468
+0, 352500, 84480, 0x66c87d4c
+0, 356250, 84480, 0xa67c0774
+0, 360000, 84480, 0xd8f8aec1
+0, 363750, 84480, 0xadfa502b
+0, 367500, 84480, 0x50bf20e4
+0, 371250, 84480, 0xbcb3d8cc
+0, 375000, 84480, 0xa54677d7
+0, 378750, 84480, 0x3566042d
+0, 382500, 84480, 0x4c9eed57
+0, 386250, 84480, 0xc3b90e58
+0, 390000, 84480, 0x3c042bfa
+0, 393750, 84480, 0x19f8e890
+0, 397500, 84480, 0xd3dacfb9
+0, 401250, 84480, 0x2365fc6f
+0, 405000, 84480, 0xa2c19d00
+0, 408750, 84480, 0xce94336f
+0, 412500, 84480, 0xfa9bcf14
+0, 416250, 84480, 0x24d6a243
+0, 420000, 84480, 0x24d6a243
+0, 423750, 84480, 0x24d6a243
+0, 427500, 84480, 0x24d6a243
+0, 431250, 84480, 0x24d6a243
+0, 435000, 84480, 0x24d6a243
+0, 438750, 84480, 0x24d6a243
+0, 442500, 84480, 0xae1c8854
+0, 446250, 84480, 0xbb8968bf
+0, 450000, 84480, 0x6f923623
+0, 453750, 84480, 0x22e98029
+0, 457500, 84480, 0x8ac33af3
+0, 461250, 84480, 0x05947b6e
+0, 465000, 84480, 0xfc35661a
+0, 468750, 84480, 0x0e6b6e47
+0, 472500, 84480, 0x82c764bb
+0, 476250, 84480, 0x57a36833
+0, 480000, 84480, 0xc8dd690a
+0, 483750, 84480, 0x02c47232
+0, 487500, 84480, 0x6645715d
+0, 491250, 84480, 0xc64860f7
+0, 495000, 84480, 0x4f5614b3
+0, 498750, 84480, 0xa70842ca
+0, 502500, 84480, 0x379d8458
+0, 506250, 84480, 0xa14701cf
+0, 510000, 84480, 0xad1aa2b2
+0, 513750, 84480, 0xee28f320
+0, 517500, 84480, 0x505801e9
+0, 521250, 84480, 0x7947233b
+0, 525000, 84480, 0x3ce72a9d
+0, 528750, 84480, 0xa6834e64
+0, 532500, 84480, 0xfebf4d70
+0, 536250, 84480, 0x4a0775e2
+0, 540000, 84480, 0x9d7e945b
+0, 543750, 84480, 0xaa9eadd9
+0, 547500, 84480, 0xaa85c9b1
+0, 551250, 84480, 0xa005edaf
+0, 555000, 84480, 0x7fc4e5cc
+0, 558750, 84480, 0xb0f6e8d1
+0, 562500, 84480, 0x9ef9f330
+0, 566250, 84480, 0xbe14ff1f
+0, 570000, 84480, 0xd494048c
+0, 573750, 84480, 0x046166a7
+0, 577500, 84480, 0x052a09b2
+0, 581250, 84480, 0x71fff4ab
+0, 585000, 84480, 0xb9684e41
+0, 588750, 84480, 0x1ddce068
+0, 592500, 84480, 0xb9de300e
+0, 596250, 84480, 0x13962590
+0, 600000, 84480, 0xde79482f
+0, 603750, 84480, 0x7d1ca064
diff --git a/tests/ref/fate/wmv8-drm-nodec b/tests/ref/fate/wmv8-drm-nodec
new file mode 100644
index 0000000..1a70fa5
--- /dev/null
+++ b/tests/ref/fate/wmv8-drm-nodec
@@ -0,0 +1,150 @@
+0, 0, 282, 0x000d949a
+1, 0, 1088, 0x5cd379bb
+1, 39150, 1088, 0x8dfa1368
+1, 66600, 1088, 0xc0d211be
+1, 92070, 1088, 0x8238113a
+0, 108720, 137, 0x903c415e
+0, 112500, 942, 0xd5b7d2aa
+0, 116190, 841, 0xaffd8ce6
+1, 117540, 1088, 0x9f8924b7
+0, 119970, 1164, 0x4ed84836
+0, 123750, 1492, 0x37f3e8aa
+0, 127440, 1663, 0xc091392d
+0, 131220, 1443, 0x6162c718
+0, 135000, 1721, 0x7bdb3dd0
+0, 138690, 1410, 0xde689881
+0, 142470, 1258, 0xb5b86920
+1, 143010, 1088, 0x767f317a
+0, 146250, 2050, 0x99b6d7c7
+0, 149940, 1242, 0x9ba35009
+0, 153720, 1630, 0x17f10192
+0, 157500, 1747, 0xbbee59d7
+0, 161190, 1565, 0xb09b00d9
+0, 164970, 1573, 0xd2e62201
+1, 168480, 1088, 0x57000d38
+0, 168750, 1353, 0x2305a24d
+0, 172440, 1425, 0xf41bbb46
+0, 176220, 1355, 0xfc08a762
+0, 180000, 1363, 0x98cda71d
+0, 183690, 1547, 0x8742f11f
+0, 187470, 1967, 0x43d61723
+0, 191250, 1378, 0xde22c753
+0, 194940, 961, 0x2418a4da
+1, 197820, 1088, 0xad977261
+0, 198720, 968, 0x0d04ba51
+0, 202500, 1140, 0x737f3543
+0, 206190, 1119, 0x3c050388
+0, 209970, 1078, 0xeac8d981
+0, 213750, 1113, 0xebfa0314
+0, 217440, 1229, 0x95dc3cb5
+0, 221220, 1311, 0x8a6f5bda
+0, 225000, 1270, 0x2e66540a
+0, 228690, 1408, 0x5f489779
+0, 232470, 1359, 0x8bd085f5
+0, 236250, 1428, 0xef9ba480
+0, 239940, 1179, 0x5bb221a8
+0, 243720, 1108, 0x9a6019a8
+0, 247500, 1205, 0xccba4d22
+0, 251190, 1306, 0xde708c19
+0, 254970, 1724, 0xa70b521e
+0, 258750, 1336, 0xdf3974b9
+0, 262440, 1259, 0x1f6b4307
+0, 266220, 1194, 0x635f5a43
+0, 270000, 1183, 0x1dd47115
+0, 273690, 1126, 0x5bac3cc8
+0, 277470, 1360, 0x1fe2d981
+0, 281250, 1261, 0x34288acb
+0, 284940, 1250, 0x26bd72b3
+0, 288720, 1147, 0x02e81ba0
+0, 292500, 1368, 0xb8146962
+0, 296190, 1377, 0xf7b6ce65
+0, 299970, 1396, 0x88467dee
+0, 303750, 1408, 0x5585c25c
+0, 307440, 1551, 0x42002c8d
+0, 311220, 1524, 0xbcb609e3
+1, 313380, 1088, 0xdce57471
+0, 315000, 1554, 0x3d740564
+0, 318690, 1467, 0xc349f2d7
+0, 322470, 1066, 0xb7401462
+0, 326250, 1502, 0x3ee602ed
+0, 329940, 1148, 0xba463637
+0, 333720, 1351, 0x5e85ae79
+0, 337500, 1187, 0xed8d6055
+0, 341190, 1200, 0x64185be6
+0, 344970, 1175, 0x12ad3c1e
+0, 348750, 1179, 0x7e034570
+0, 352440, 1136, 0x5c633c51
+1, 352620, 1088, 0xf3887977
+0, 356220, 1064, 0x5eb51d89
+0, 360000, 953, 0xe148bbdd
+0, 363690, 989, 0x901ec306
+0, 367470, 1030, 0x680de26f
+0, 371250, 1078, 0x86e0ee43
+0, 374940, 1232, 0x98546a86
+0, 378720, 1164, 0x93305074
+0, 382500, 1348, 0x27cfa91b
+0, 386190, 1417, 0x2312d70e
+0, 389970, 1285, 0x46ca4cca
+1, 391770, 1088, 0x1d6c8ed2
+0, 393750, 1037, 0xcf09dd3d
+0, 397440, 1005, 0xe780cf1f
+0, 401220, 890, 0x8b1d8c1b
+0, 405000, 1023, 0xd1dbd506
+0, 408690, 803, 0x935e775e
+0, 412470, 1035, 0x6a220483
+0, 416250, 466, 0xd88bb237
+1, 431010, 1088, 0x09115bae
+0, 442440, 945, 0x8f2eb1ec
+0, 446220, 1190, 0x4c451c1b
+0, 450000, 1811, 0x727c52cb
+0, 453690, 1552, 0x73f82bff
+0, 457470, 1544, 0xa7241ece
+0, 461250, 1707, 0x3d1a6464
+0, 464940, 1103, 0x06b22710
+0, 468720, 1122, 0x656725b8
+1, 470160, 1088, 0x0c8b9372
+0, 472500, 1150, 0xf9674678
+0, 476190, 1438, 0x03fac426
+0, 479970, 1623, 0x7adb1321
+0, 483750, 1677, 0x0b9a3e62
+0, 487440, 1124, 0x769c0ea2
+0, 491220, 1221, 0xd942409f
+0, 495000, 1698, 0xd7ca3fe3
+0, 498690, 1262, 0xb994692f
+0, 502470, 2097, 0xf4eb663f
+0, 506250, 1251, 0xfd4f633a
+1, 509310, 1088, 0x75a82540
+0, 509940, 1633, 0xb7e1290e
+0, 513720, 1739, 0xecd18c38
+0, 517500, 1132, 0xc83e1828
+0, 521190, 825, 0xdd02867c
+0, 524970, 903, 0x349ba205
+0, 528750, 1013, 0x1366ec2a
+0, 532440, 1340, 0xeaa2a231
+0, 536220, 1102, 0x82de2889
+0, 540000, 1834, 0x59b99b92
+1, 540720, 1088, 0x690312b0
+0, 543690, 1332, 0x0610813a
+0, 547470, 1275, 0x5b0d7be7
+0, 551250, 1376, 0xd915b0fe
+0, 554940, 1417, 0x8606b34a
+0, 558720, 1360, 0x3bcd93d3
+0, 562500, 1330, 0xd0439c93
+0, 566190, 1562, 0xb2560a09
+1, 568080, 1088, 0x76d50ff3
+0, 569970, 1376, 0x4f9eb447
+0, 573750, 1405, 0x85d3b084
+0, 577440, 1344, 0xcdbda2ae
+0, 581220, 1313, 0xe3067b35
+0, 585000, 1459, 0xf9d2c56f
+0, 588690, 1275, 0xf5536d81
+0, 592470, 1209, 0x3b5b4ea5
+1, 593550, 1088, 0x8766276f
+0, 596250, 1352, 0x7b199d28
+0, 599940, 1349, 0x02adaaf3
+0, 603720, 1464, 0x20d7cfd2
+0, 607500, 1377, 0x78e0b1f4
+0, 611190, 289, 0x1f2e9246
+1, 619020, 1088, 0x678f20fd
+1, 644490, 1088, 0x718afa20
+1, 669960, 1088, 0x758f0939
diff --git a/tests/ref/fate/ws_snd b/tests/ref/fate/ws_snd
new file mode 100644
index 0000000..4004e33
--- /dev/null
+++ b/tests/ref/fate/ws_snd
@@ -0,0 +1 @@
+023317c7876aa5271f086f753d84561b
diff --git a/tests/ref/fate/yop b/tests/ref/fate/yop
new file mode 100644
index 0000000..782fd47
--- /dev/null
+++ b/tests/ref/fate/yop
@@ -0,0 +1,7 @@
+0, 0, 302760, 0x78939253
+0, 7500, 302760, 0x534f5253
+0, 15000, 302760, 0xe991aa82
+0, 22500, 302760, 0xc34b20bd
+0, 30000, 302760, 0x461d29a1
+0, 37500, 302760, 0x45abca02
+0, 45000, 302760, 0xb05448b9
diff --git a/tests/ref/lavf/avi b/tests/ref/lavf/avi
index cf47755..bba0f6f 100644
--- a/tests/ref/lavf/avi
+++ b/tests/ref/lavf/avi
@@ -1,3 +1,3 @@
-7e5e4db8c04f0acd16cff6b30e60d0e5 *./tests/data/lavf/lavf.avi
+f8b3e77a1430c348dc06472571d37191 *./tests/data/lavf/lavf.avi
 331032 ./tests/data/lavf/lavf.avi
 ./tests/data/lavf/lavf.avi CRC=0x2a83e6b0
diff --git a/tests/ref/lavf/gif b/tests/ref/lavf/gif
index 21f639d..fa55d0e 100644
--- a/tests/ref/lavf/gif
+++ b/tests/ref/lavf/gif
@@ -1,2 +1,3 @@
 98968ceb210ab260a6a7af36767b94d3 *./tests/data/lavf/lavf.gif
 2906382 ./tests/data/lavf/lavf.gif
+./tests/data/lavf/lavf.gif CRC=0xe5605ff6
diff --git a/tests/ref/lavf/gxf b/tests/ref/lavf/gxf
index d147bc4..6b39c2f 100644
--- a/tests/ref/lavf/gxf
+++ b/tests/ref/lavf/gxf
@@ -1,3 +1,3 @@
-b52bf18b403ac9a0d12048b2f66cb24c *./tests/data/lavf/lavf.gxf
+346d38d330ab5cb0caa6b5537167bc0d *./tests/data/lavf/lavf.gxf
 796392 ./tests/data/lavf/lavf.gxf
-./tests/data/lavf/lavf.gxf CRC=0xad9e86eb
+./tests/data/lavf/lavf.gxf CRC=0x345f86eb
diff --git a/tests/ref/lavf/mkv b/tests/ref/lavf/mkv
index 213d38b..05eb67d 100644
--- a/tests/ref/lavf/mkv
+++ b/tests/ref/lavf/mkv
@@ -1,3 +1,3 @@
-cf230e089e737ed9449fbfb3cb87da92 *./tests/data/lavf/lavf.mkv
-  320471 ./tests/data/lavf/lavf.mkv
+a36c2d9378b9870880556ced1cb89ecf *./tests/data/lavf/lavf.mkv
+  320478 ./tests/data/lavf/lavf.mkv
 ./tests/data/lavf/lavf.mkv CRC=0x2a83e6b0
diff --git a/tests/ref/lavf/mpg b/tests/ref/lavf/mpg
index 9b1664f..b81cb8a 100644
--- a/tests/ref/lavf/mpg
+++ b/tests/ref/lavf/mpg
@@ -1,3 +1,3 @@
-e36a005ecca9add8bda6e0655d03716f *./tests/data/lavf/lavf.mpg
+dd60652c2193670abffb8c2a123a820e *./tests/data/lavf/lavf.mpg
 372736 ./tests/data/lavf/lavf.mpg
-./tests/data/lavf/lavf.mpg CRC=0x2b39ed74
+./tests/data/lavf/lavf.mpg CRC=0xf361ed74
diff --git a/tests/ref/lavf/mxf b/tests/ref/lavf/mxf
index 84d7a09..d4bbe2f 100644
--- a/tests/ref/lavf/mxf
+++ b/tests/ref/lavf/mxf
@@ -1,6 +1,6 @@
-8e120da0ccd70c4475fdee13fc5f3d0b *./tests/data/lavf/lavf.mxf
+6e9bd63c5cadd7550ad313553ebf665f *./tests/data/lavf/lavf.mxf
 525881 ./tests/data/lavf/lavf.mxf
-./tests/data/lavf/lavf.mxf CRC=0xb6aa0849
-b3174e2db508564c1cce0b5e3c1bc1bd *./tests/data/lavf/lavf.mxf_d10
+./tests/data/lavf/lavf.mxf CRC=0x4ace0849
+e7168856f2b54c6272685967e707fb21 *./tests/data/lavf/lavf.mxf_d10
 5330989 ./tests/data/lavf/lavf.mxf_d10
 ./tests/data/lavf/lavf.mxf_d10 CRC=0xc3f4f92e
diff --git a/tests/ref/lavf/nut b/tests/ref/lavf/nut
index 461b185..6bf659d 100644
--- a/tests/ref/lavf/nut
+++ b/tests/ref/lavf/nut
@@ -1,3 +1,3 @@
-16b9d2cf8effb7dae316c6b9248a49b7 *./tests/data/lavf/lavf.nut
+df1eab0853a22713cf4172acbf1a6b4b *./tests/data/lavf/lavf.nut
 319888 ./tests/data/lavf/lavf.nut
 ./tests/data/lavf/lavf.nut CRC=0x2a83e6b0
diff --git a/tests/ref/lavf/png b/tests/ref/lavf/png
new file mode 100644
index 0000000..4343adb
--- /dev/null
+++ b/tests/ref/lavf/png
@@ -0,0 +1,3 @@
+c162094e51dc1a3203de43e496086dfd *./tests/data/images/png/02.png
+./tests/data/images/png/%02d.png CRC=0x6da01946
+248612 ./tests/data/images/png/02.png
diff --git a/tests/ref/lavf/rm b/tests/ref/lavf/rm
index 0966c0c..a85c763 100644
--- a/tests/ref/lavf/rm
+++ b/tests/ref/lavf/rm
@@ -1,2 +1,2 @@
-e60d3e69beaf94a5c3d2e3344cc620dd *./tests/data/lavf/lavf.rm
+a1c71456f21d5459d2824d75bbdcc80c *./tests/data/lavf/lavf.rm
 346706 ./tests/data/lavf/lavf.rm
diff --git a/tests/ref/lavf/ts b/tests/ref/lavf/ts
index 5b046fb..4028be0 100644
--- a/tests/ref/lavf/ts
+++ b/tests/ref/lavf/ts
@@ -1,3 +1,3 @@
-e0c183639709d6e75bc553a3ed1333dd *./tests/data/lavf/lavf.ts
+1cebaf8b13700a3360e0c32551e36646 *./tests/data/lavf/lavf.ts
 406644 ./tests/data/lavf/lavf.ts
 ./tests/data/lavf/lavf.ts CRC=0x133216c1
diff --git a/tests/ref/lavf/voc_s16 b/tests/ref/lavf/voc_s16
new file mode 100644
index 0000000..425d965
--- /dev/null
+++ b/tests/ref/lavf/voc_s16
@@ -0,0 +1,3 @@
+b20728bf036d2e23508869acbad4e576 *./tests/data/lavf/lavf.s16.voc
+163840 ./tests/data/lavf/lavf.s16.voc
+./tests/data/lavf/lavf.s16.voc CRC=0xfa9b6c39
diff --git a/tests/ref/lavfi/crop b/tests/ref/lavfi/crop
index 75c39f7..32041c2 100644
--- a/tests/ref/lavfi/crop
+++ b/tests/ref/lavfi/crop
@@ -1,2 +1 @@
-3d163f156eaddf41d2be20736f973539 *./tests/data/lavfi/crop.nut
-3554654 ./tests/data/lavfi/crop.nut
+crop                3d163f156eaddf41d2be20736f973539
diff --git a/tests/ref/lavfi/crop_scale b/tests/ref/lavfi/crop_scale
index 48a0734..82e5394 100644
--- a/tests/ref/lavfi/crop_scale
+++ b/tests/ref/lavfi/crop_scale
@@ -1,2 +1 @@
-4ffe30abe99931bc9989f40ae65654b7 *./tests/data/lavfi/crop_scale.nut
-8941454 ./tests/data/lavfi/crop_scale.nut
+crop_scale          0a3d45d58b805b8c47416b9239535f94
diff --git a/tests/ref/lavfi/crop_scale_vflip b/tests/ref/lavfi/crop_scale_vflip
index 314f407..07c729a 100644
--- a/tests/ref/lavfi/crop_scale_vflip
+++ b/tests/ref/lavfi/crop_scale_vflip
@@ -1,2 +1 @@
-3b1c81bb6ce7575f5ee3088ea165dbe7 *./tests/data/lavfi/crop_scale_vflip.nut
-750727 ./tests/data/lavfi/crop_scale_vflip.nut
+crop_scale_vflip    e88a4dfb960d0bb28ee875567bedde5d
diff --git a/tests/ref/lavfi/crop_vflip b/tests/ref/lavfi/crop_vflip
index 96fc9bd..a3f8200 100644
--- a/tests/ref/lavfi/crop_vflip
+++ b/tests/ref/lavfi/crop_vflip
@@ -1,2 +1 @@
-628542e17b6900ee79b1429183ae01b0 *./tests/data/lavfi/crop_vflip.nut
-3554654 ./tests/data/lavfi/crop_vflip.nut
+crop_vflip          628542e17b6900ee79b1429183ae01b0
diff --git a/tests/ref/lavfi/null b/tests/ref/lavfi/null
index b4d006e..3c3b7b7 100644
--- a/tests/ref/lavfi/null
+++ b/tests/ref/lavfi/null
@@ -1,2 +1 @@
-eba2f135a08829387e2f698ff72a2939 *./tests/data/lavfi/null.nut
-7604654 ./tests/data/lavfi/null.nut
+null                eba2f135a08829387e2f698ff72a2939
diff --git a/tests/ref/lavfi/pixdesc_be b/tests/ref/lavfi/pixdesc_be
new file mode 100644
index 0000000..03abcd5
--- /dev/null
+++ b/tests/ref/lavfi/pixdesc_be
@@ -0,0 +1,42 @@
+abgr                037bf9df6a765520ad6d490066bf4b89
+argb                c442a8261c2265a07212ef0f72e35f5a
+bgr24               0d0cb38ab3fa0b2ec0865c14f78b217b
+bgr4_byte           50d23cc82d9dcef2fd12adb81fb9b806
+bgr555be            49f01b1f1f0c84fd9e776dd34cc3c280
+bgr565be            257cf78afa35dc31e9696f139c916715
+bgr8                24bd566170343d06fec6fccfff5abc54
+bgra                76a18a5151242fa137133f604cd624d2
+gray                db08f7f0751900347e6b8649e4164d21
+gray16be            7becf34ae825a3df3969bf4c6bfeb5e2
+gray16le            10bd87059b5c189f3caef2837f4f2b5c
+monob               668ebe8b8103b9046b251b2fa8a1d88f
+monow               9251497f3b0634f1165d12d5a289d943
+nv12                e0af357888584d36eec5aa0f673793ef
+nv21                9a3297f3b34baa038b1f37cb202b512f
+rgb24               b41eba9651e1b5fe386289b506188105
+rgb48be             460b6de89b156290a12d3941db8bd731
+rgb48le             cd93cb34d15996987367dabda3a10128
+rgb4_byte           c93ba89b74c504e7f5ae9d9ab1546c73
+rgb555be            912a62c5e53bfcbac2a0340e10973cf2
+rgb565be            9cadf742e05ddc23a3b5b270f89aad3c
+rgb8                4a9d8e4f2f154e83a7e1735be6300700
+rgba                93a5b3712e6eb8c5b9a09ffc7b9fbc12
+uyvy422             adcf64516a19fce44df77082bdb16291
+yuv410p             2d9225153c83ee1132397d619d94d1b3
+yuv411p             8b298af3e43348ca1b11eb8a3252ac6c
+yuv420p             eba2f135a08829387e2f698ff72a2939
+yuv420p16be         16c009a235cd52b74791a895423152a3
+yuv420p16le         2d59c4f1d0314a5a957a7cfc4b6fabcc
+yuv422p             c9bba4529821d796a6ab09f6a5fd355a
+yuv422p16be         5499502e1c29534a158a1fe60e889f60
+yuv422p16le         e3d61fde6978591596bc36b914386623
+yuv440p             5a064afe2b453bb52cdb3f176b1aa1cf
+yuv444p             0a98447b78fd476aa39686da6a74fa2e
+yuv444p16be         ea602a24b8e6969679265078bd8607b6
+yuv444p16le         1262a0dc57ee147967fc896d04206313
+yuva420p            a29884f3f3dfe1e00b961bc17bef3d47
+yuvj420p            32eec78ba51857b16ce9b813a49b7189
+yuvj422p            0dfa0ed434f73be51428758c69e082cb
+yuvj440p            9c3a093ff64a83ac4cf0b1e65390e236
+yuvj444p            ede1e5882d5c5bba48ea33cf1209d231
+yuyv422             f2569f2b5069a0ee0cecae33de0455e3
diff --git a/tests/ref/lavfi/pixdesc_le b/tests/ref/lavfi/pixdesc_le
new file mode 100644
index 0000000..5832f89
--- /dev/null
+++ b/tests/ref/lavfi/pixdesc_le
@@ -0,0 +1,42 @@
+abgr                037bf9df6a765520ad6d490066bf4b89
+argb                c442a8261c2265a07212ef0f72e35f5a
+bgr24               0d0cb38ab3fa0b2ec0865c14f78b217b
+bgr4_byte           50d23cc82d9dcef2fd12adb81fb9b806
+bgr555le            378d6ac4223651a1adcbf94a3d0d807b
+bgr565le            1dfdd03995c287e3c754b164bf26a355
+bgr8                24bd566170343d06fec6fccfff5abc54
+bgra                76a18a5151242fa137133f604cd624d2
+gray                db08f7f0751900347e6b8649e4164d21
+gray16be            7becf34ae825a3df3969bf4c6bfeb5e2
+gray16le            10bd87059b5c189f3caef2837f4f2b5c
+monob               668ebe8b8103b9046b251b2fa8a1d88f
+monow               9251497f3b0634f1165d12d5a289d943
+nv12                e0af357888584d36eec5aa0f673793ef
+nv21                9a3297f3b34baa038b1f37cb202b512f
+rgb24               b41eba9651e1b5fe386289b506188105
+rgb48be             460b6de89b156290a12d3941db8bd731
+rgb48le             cd93cb34d15996987367dabda3a10128
+rgb4_byte           c93ba89b74c504e7f5ae9d9ab1546c73
+rgb555le            a937a0fc764fb57dc1b3af87cba0273c
+rgb565le            d39aa298bb525e9be8860351c6f62dab
+rgb8                4a9d8e4f2f154e83a7e1735be6300700
+rgba                93a5b3712e6eb8c5b9a09ffc7b9fbc12
+uyvy422             adcf64516a19fce44df77082bdb16291
+yuv410p             2d9225153c83ee1132397d619d94d1b3
+yuv411p             8b298af3e43348ca1b11eb8a3252ac6c
+yuv420p             eba2f135a08829387e2f698ff72a2939
+yuv420p16be         16c009a235cd52b74791a895423152a3
+yuv420p16le         2d59c4f1d0314a5a957a7cfc4b6fabcc
+yuv422p             c9bba4529821d796a6ab09f6a5fd355a
+yuv422p16be         5499502e1c29534a158a1fe60e889f60
+yuv422p16le         e3d61fde6978591596bc36b914386623
+yuv440p             5a064afe2b453bb52cdb3f176b1aa1cf
+yuv444p             0a98447b78fd476aa39686da6a74fa2e
+yuv444p16be         ea602a24b8e6969679265078bd8607b6
+yuv444p16le         1262a0dc57ee147967fc896d04206313
+yuva420p            a29884f3f3dfe1e00b961bc17bef3d47
+yuvj420p            32eec78ba51857b16ce9b813a49b7189
+yuvj422p            0dfa0ed434f73be51428758c69e082cb
+yuvj440p            9c3a093ff64a83ac4cf0b1e65390e236
+yuvj444p            ede1e5882d5c5bba48ea33cf1209d231
+yuyv422             f2569f2b5069a0ee0cecae33de0455e3
diff --git a/tests/ref/lavfi/pixfmts_copy_le b/tests/ref/lavfi/pixfmts_copy_le
new file mode 100644
index 0000000..5832f89
--- /dev/null
+++ b/tests/ref/lavfi/pixfmts_copy_le
@@ -0,0 +1,42 @@
+abgr                037bf9df6a765520ad6d490066bf4b89
+argb                c442a8261c2265a07212ef0f72e35f5a
+bgr24               0d0cb38ab3fa0b2ec0865c14f78b217b
+bgr4_byte           50d23cc82d9dcef2fd12adb81fb9b806
+bgr555le            378d6ac4223651a1adcbf94a3d0d807b
+bgr565le            1dfdd03995c287e3c754b164bf26a355
+bgr8                24bd566170343d06fec6fccfff5abc54
+bgra                76a18a5151242fa137133f604cd624d2
+gray                db08f7f0751900347e6b8649e4164d21
+gray16be            7becf34ae825a3df3969bf4c6bfeb5e2
+gray16le            10bd87059b5c189f3caef2837f4f2b5c
+monob               668ebe8b8103b9046b251b2fa8a1d88f
+monow               9251497f3b0634f1165d12d5a289d943
+nv12                e0af357888584d36eec5aa0f673793ef
+nv21                9a3297f3b34baa038b1f37cb202b512f
+rgb24               b41eba9651e1b5fe386289b506188105
+rgb48be             460b6de89b156290a12d3941db8bd731
+rgb48le             cd93cb34d15996987367dabda3a10128
+rgb4_byte           c93ba89b74c504e7f5ae9d9ab1546c73
+rgb555le            a937a0fc764fb57dc1b3af87cba0273c
+rgb565le            d39aa298bb525e9be8860351c6f62dab
+rgb8                4a9d8e4f2f154e83a7e1735be6300700
+rgba                93a5b3712e6eb8c5b9a09ffc7b9fbc12
+uyvy422             adcf64516a19fce44df77082bdb16291
+yuv410p             2d9225153c83ee1132397d619d94d1b3
+yuv411p             8b298af3e43348ca1b11eb8a3252ac6c
+yuv420p             eba2f135a08829387e2f698ff72a2939
+yuv420p16be         16c009a235cd52b74791a895423152a3
+yuv420p16le         2d59c4f1d0314a5a957a7cfc4b6fabcc
+yuv422p             c9bba4529821d796a6ab09f6a5fd355a
+yuv422p16be         5499502e1c29534a158a1fe60e889f60
+yuv422p16le         e3d61fde6978591596bc36b914386623
+yuv440p             5a064afe2b453bb52cdb3f176b1aa1cf
+yuv444p             0a98447b78fd476aa39686da6a74fa2e
+yuv444p16be         ea602a24b8e6969679265078bd8607b6
+yuv444p16le         1262a0dc57ee147967fc896d04206313
+yuva420p            a29884f3f3dfe1e00b961bc17bef3d47
+yuvj420p            32eec78ba51857b16ce9b813a49b7189
+yuvj422p            0dfa0ed434f73be51428758c69e082cb
+yuvj440p            9c3a093ff64a83ac4cf0b1e65390e236
+yuvj444p            ede1e5882d5c5bba48ea33cf1209d231
+yuyv422             f2569f2b5069a0ee0cecae33de0455e3
diff --git a/tests/ref/lavfi/pixfmts_crop_le b/tests/ref/lavfi/pixfmts_crop_le
new file mode 100644
index 0000000..3016a7f
--- /dev/null
+++ b/tests/ref/lavfi/pixfmts_crop_le
@@ -0,0 +1,36 @@
+abgr                cd761690872843d1b7ab0c695393c751
+argb                2ec6ef18769bcd651c2e8904d5a3ee67
+bgr24               3450fd00cf1493d1ded75544d82ba3ec
+bgr4_byte           2f6ac3cdd4676ab4e2982bdf0664945b
+bgr555le            d22442fc13b464f9ba455b08df4e981f
+bgr565le            891664e5a54ae5968901347da92bc5e9
+bgr8                4b7159e05765bd4703180072d86423c8
+bgra                395c9f706fccda721471acaa5c96c16c
+gray                8c4850e66562a587a292dc728a65ea4a
+gray16be            daa5a6b98fb4a280c57c57bff1a2ab5a
+gray16le            84f5ea7259073edcb893113b42213c8e
+rgb24               3b90ed64b687d3dc186c6ef521dc71a8
+rgb48be             a808128041a1962deaa8620c7448feba
+rgb48le             ce92d02cc322608d5be377cb1940677b
+rgb4_byte           6958029f73c6cdfed4f71020d816f027
+rgb555le            eeb78f8ce6186fba55c941469e60ba67
+rgb565le            6a49700680be9a0d434411825a769556
+rgb8                88b0398c265d1ed7a837dc084fa0917c
+rgba                fd00b24c7597268c32759a84a1de2de4
+yuv410p             a9f2eaa747bf988b7bebe4f442b9c67a
+yuv411p             3334d3aef8dba238658090ac172375d1
+yuv420p             bfea0188ddd4889787c403caae119cc7
+yuv420p16be         8365eff38b8c329aeb95fc605fa229bb
+yuv420p16le         5e8dd38d973d5854abe1ad4efad20cc1
+yuv422p             f2f930a91fe00d4252c4720b5ecd8961
+yuv422p16be         167e4338811a7d272925a4c6417d60da
+yuv422p16le         3359395d5875d581fa1e975013d30114
+yuv440p             2472417d980e395ad6843cbb8b633b29
+yuv444p             1f151980486848c96bc5585ced99003e
+yuv444p16be         d69280c2856865d2ea94bd5292aac1c6
+yuv444p16le         33f43e030bedf9723be4f63c3e9fc80e
+yuva420p            7536753dfbc7932560fb50c921369a0e
+yuvj420p            21f891093006d42d7683b0e1d773a657
+yuvj422p            9a43d474c407590ad8f213880586b45e
+yuvj440p            977351350450ebdbf7a9d20020c6b5a5
+yuvj444p            4a50ba26859dad91dcf7000de0d0efa1
diff --git a/tests/ref/lavfi/pixfmts_hflip_le b/tests/ref/lavfi/pixfmts_hflip_le
new file mode 100644
index 0000000..09976f2
--- /dev/null
+++ b/tests/ref/lavfi/pixfmts_hflip_le
@@ -0,0 +1,36 @@
+abgr                49468c6c9ceee5d52b08b1270a909323
+argb                50ba9f16c6475530602f2983278b82d0
+bgr24               cc53d2011d097972db0d22756c3699e3
+bgr4_byte           aac987e7d1a6a96477cfc0b48a4285de
+bgr555le            ccee08679bac84a1f960c6c9070c5538
+bgr565le            3703466e19e1b52e03a34fd244a8e8e4
+bgr8                50b505a889f0428242305acb642da107
+bgra                01ca21e7e6a8d1281b4553bde8e8a404
+gray                03efcb4ab52a24c0af0e03cfd26c9377
+gray16be            9bcbca979601ddc4869f846f08f3d1dd
+gray16le            c1b8965adcc7f847ee343149ff507073
+rgb24               754f1722fc738590cc407ac65749bfe8
+rgb48be             10743e1577dc3198dbbc7c0b3b8f429e
+rgb48le             dd945a44f39119221407bf7a04f1bc49
+rgb4_byte           c8a3f995fcf3e0919239ea2c413ddc29
+rgb555le            8778ee0cf58ce9ad1d99a1eca9f95e87
+rgb565le            2cb690eb3fcb72da3771ad6a48931158
+rgb8                9e462b811b9b6173397b9cfc1f6b2f17
+rgba                d3d0dc1ecef3ed72f26a2986d0efc204
+yuv410p             acb543ebbbf63eefe533e6faffc006da
+yuv411p             c626cf6d191139b4ca7efc0155f957f1
+yuv420p             2d5c80f9ba2ddd85b2aeda3564cc7d64
+yuv420p16be         758b0c1e2113b15e7afde48da4e4d024
+yuv420p16le         480ccd951dcb806bc875d307e02e50a0
+yuv422p             6e728f4eb9eae287c224f396d84be6ea
+yuv422p16be         a05d43cd62b790087bd37083174557de
+yuv422p16le         6954abebcbc62d81068d58d0c62bdd5b
+yuv440p             a99e2b57ed601f39852715c9d675d0d3
+yuv444p             947e47f7bb5fdccc659d19b7df2b6fc3
+yuv444p16be         e5ef45bc3d2f5b0b2542d5151340c382
+yuv444p16le         70793e3d66d0c23a0cdedabe9c24c2a7
+yuva420p            d83ec0c01498189f179ec574918185f1
+yuvj420p            df3aaaec3bb157c3bde5f0365af30f4f
+yuvj422p            d113871528d510a192797af59df9c05c
+yuvj440p            e8f7ed76e57c892a1e9e27a3f29452db
+yuvj444p            2c3ae369607608c6dcb0d830f00f971a
diff --git a/tests/ref/lavfi/pixfmts_null_le b/tests/ref/lavfi/pixfmts_null_le
new file mode 100644
index 0000000..5832f89
--- /dev/null
+++ b/tests/ref/lavfi/pixfmts_null_le
@@ -0,0 +1,42 @@
+abgr                037bf9df6a765520ad6d490066bf4b89
+argb                c442a8261c2265a07212ef0f72e35f5a
+bgr24               0d0cb38ab3fa0b2ec0865c14f78b217b
+bgr4_byte           50d23cc82d9dcef2fd12adb81fb9b806
+bgr555le            378d6ac4223651a1adcbf94a3d0d807b
+bgr565le            1dfdd03995c287e3c754b164bf26a355
+bgr8                24bd566170343d06fec6fccfff5abc54
+bgra                76a18a5151242fa137133f604cd624d2
+gray                db08f7f0751900347e6b8649e4164d21
+gray16be            7becf34ae825a3df3969bf4c6bfeb5e2
+gray16le            10bd87059b5c189f3caef2837f4f2b5c
+monob               668ebe8b8103b9046b251b2fa8a1d88f
+monow               9251497f3b0634f1165d12d5a289d943
+nv12                e0af357888584d36eec5aa0f673793ef
+nv21                9a3297f3b34baa038b1f37cb202b512f
+rgb24               b41eba9651e1b5fe386289b506188105
+rgb48be             460b6de89b156290a12d3941db8bd731
+rgb48le             cd93cb34d15996987367dabda3a10128
+rgb4_byte           c93ba89b74c504e7f5ae9d9ab1546c73
+rgb555le            a937a0fc764fb57dc1b3af87cba0273c
+rgb565le            d39aa298bb525e9be8860351c6f62dab
+rgb8                4a9d8e4f2f154e83a7e1735be6300700
+rgba                93a5b3712e6eb8c5b9a09ffc7b9fbc12
+uyvy422             adcf64516a19fce44df77082bdb16291
+yuv410p             2d9225153c83ee1132397d619d94d1b3
+yuv411p             8b298af3e43348ca1b11eb8a3252ac6c
+yuv420p             eba2f135a08829387e2f698ff72a2939
+yuv420p16be         16c009a235cd52b74791a895423152a3
+yuv420p16le         2d59c4f1d0314a5a957a7cfc4b6fabcc
+yuv422p             c9bba4529821d796a6ab09f6a5fd355a
+yuv422p16be         5499502e1c29534a158a1fe60e889f60
+yuv422p16le         e3d61fde6978591596bc36b914386623
+yuv440p             5a064afe2b453bb52cdb3f176b1aa1cf
+yuv444p             0a98447b78fd476aa39686da6a74fa2e
+yuv444p16be         ea602a24b8e6969679265078bd8607b6
+yuv444p16le         1262a0dc57ee147967fc896d04206313
+yuva420p            a29884f3f3dfe1e00b961bc17bef3d47
+yuvj420p            32eec78ba51857b16ce9b813a49b7189
+yuvj422p            0dfa0ed434f73be51428758c69e082cb
+yuvj440p            9c3a093ff64a83ac4cf0b1e65390e236
+yuvj444p            ede1e5882d5c5bba48ea33cf1209d231
+yuyv422             f2569f2b5069a0ee0cecae33de0455e3
diff --git a/tests/ref/lavfi/pixfmts_pad_le b/tests/ref/lavfi/pixfmts_pad_le
new file mode 100644
index 0000000..73a44f6
--- /dev/null
+++ b/tests/ref/lavfi/pixfmts_pad_le
@@ -0,0 +1,17 @@
+abgr                e8e5e350c856c051d502cd435a2aa0bd
+argb                a98e0a1213824ee4566d4891468bb614
+bgr24               ac7417cea8d6e799a31a3c9a39b8f202
+bgra                6113a09a023cb2b08e9cad78eb1eb37a
+rgb24               65eed443acc66c4f02bab6df4ebed515
+rgba                74d4158ad0c626e9a7c6923b9ca73294
+yuv410p             a5210eb6a9b10c3269899b935df9a2d6
+yuv411p             a23380c9698e2d80c9fa8a8b6d4f6854
+yuv420p             f8733600369adaea28aa445dbdf2ed4c
+yuv422p             3e0d822c11c716e7636387b1bf27c5ff
+yuv440p             225dd7fbc8cceb24c26b765187d43a9e
+yuv444p             45484f0411d336ce94636da0395f4692
+yuva420p            919722724765dc3a716c38fa53b20580
+yuvj420p            4f20e2799966c21a9d9e0788b0956925
+yuvj422p            e4d84b0683f77a76f1c17d976eff127c
+yuvj440p            9ccc1f03d8d9a00dc4a5888bd77093ad
+yuvj444p            7d202babcedf836e9ae9776163ee9425
diff --git a/tests/ref/lavfi/pixfmts_scale_le b/tests/ref/lavfi/pixfmts_scale_le
new file mode 100644
index 0000000..3ecfed7
--- /dev/null
+++ b/tests/ref/lavfi/pixfmts_scale_le
@@ -0,0 +1,42 @@
+abgr                d894cb97f6c80eb21bdbe8a4eea62d86
+argb                54346f2b2eef10919e0f247241df3b24
+bgr24               570f8d6b51a838aed022ef67535f6bdc
+bgr4_byte           ee1d35a7baf8e9016891929a2f565c0b
+bgr555le            36b745067197f9ca8c1731cac51329c9
+bgr565le            3a514a298c6161a071ddf9963c06509d
+bgr8                7f007fa6c153a16e808a9c51605a4016
+bgra                a5e7040f9a80cccd65e5acf2ca09ace5
+gray                d7786a7d9d99ac74230cc045cab5632c
+gray16be            af39ce3a497f6734b157c8b94544f537
+gray16le            7ac1b788bcc472010df7a97e762485e0
+monob               88c4c050758e64d120f50c7eff694381
+monow               d31772ebaa877fc2a78565937f7f9673
+nv12                4676d59db43d657dc12841f6bc3ab452
+nv21                69c699510ff1fb777b118ebee1002f14
+rgb24               514692e28e8ff6860e415ce4fcf6eb8c
+rgb48be             1894cd30dabcd3180518e4d5f09f25e7
+rgb48le             1354e6e27ce3c1d4d4989ee56030c94b
+rgb4_byte           d81ffd3add95842a618eec81024f0b5c
+rgb555le            a350ef1dc2c9688ed49e7ba018843795
+rgb565le            6f4bb711238baa762d73305213f8d035
+rgb8                091d0170b354ef0e97312b95feb5483f
+rgba                a3d362f222098a00e63867f612018659
+uyvy422             314bd486277111a95d9369b944fa0400
+yuv410p             7df8f6d69b56a8dcb6c7ee908e5018b5
+yuv411p             1143e7c5cc28fe0922b051b17733bc4c
+yuv420p             fdad2d8df8985e3d17e73c71f713cb14
+yuv420p16be         29a0265764530070f5cd3251cc01f66a
+yuv420p16le         6f3a265b084a78baec229238d9f7945f
+yuv422p             918e37701ee7377d16a8a6c119c56a40
+yuv422p16be         ef3e865fc1d0c68977c735323c50af6e
+yuv422p16le         428a9b96214c09cb5a983ce36d6961ff
+yuv440p             461503fdb9b90451020aa3b25ddf041c
+yuv444p             81b2eba962d12e8d64f003ac56f6faf2
+yuv444p16be         99a3738c70c8fbdc5a0e4ad4bf50648d
+yuv444p16le         385d0cc5240d62da0871915be5d86f0a
+yuva420p            8673a9131fb47de69788863f93a50eb7
+yuvj420p            30427bd6caf5bda93a173dbebe759e09
+yuvj422p            fc8288f64fd149573f73cf8da05d8e6d
+yuvj440p            26d0b4713a87ab9637a4062c22e6e70d
+yuvj444p            894e6184d987a5ec4dc6f77bb75ef38c
+yuyv422             169e19ac91b257bd84ace0fdf56559ad
diff --git a/tests/ref/lavfi/pixfmts_vflip_le b/tests/ref/lavfi/pixfmts_vflip_le
new file mode 100644
index 0000000..3b140a2
--- /dev/null
+++ b/tests/ref/lavfi/pixfmts_vflip_le
@@ -0,0 +1,42 @@
+abgr                25e72e9dbd01ab00727c976d577f7be5
+argb                19869bf1a5ac0b6af4d8bbe2c104533c
+bgr24               89108a4ba00201f79b75b9305c42352d
+bgr4_byte           407fcf564ed764c38e1d748f700ab921
+bgr555le            bd7b3ec4d684dfad075d89a606cb8b74
+bgr565le            fdb617533e1e7ff512ea5b6b6233e738
+bgr8                c60f93fd152c6903391d1fe9decd3547
+bgra                7f9b799fb48544e49ce93e91d7f9fca8
+gray                30d9014a9d43b5f37e7aa64be3a3ecfc
+gray16be            6b84b85d3326182fa1217e138249edc5
+gray16le            66bb8faa09dc149734aca3c768a6d4e1
+monob               d0cf8732677a5360b6160133043590d8
+monow               ff9869d067ecb94eb9d90c9750c31fea
+nv12                046f00f598ce14d9854a3534a5c99114
+nv21                01ea369dd2d0d3ed7451dc5c8d61497f
+rgb24               eaefabc168d0b14576bab45bc1e56e1e
+rgb48be             4e0c384163ebab06a08e74637beb02bc
+rgb48le             a77bfeefcd96750cf0e1917a2e2bf1e7
+rgb4_byte           8c6ff02df0b06dd2d574836c3741b2a2
+rgb555le            4f8eaad29a17e0f8e9d8ab743e76b999
+rgb565le            73f247a3315dceaea3022ac7c197c5ef
+rgb8                13a8d89ef78d8127297d899005456ff0
+rgba                1fc6e920a42ec812aaa3b2aa02f37987
+uyvy422             ffbd36720c77398d9a0d03ce2625928f
+yuv410p             7bfb39d7afb49d6a6173e6b23ae321eb
+yuv411p             4a90048cc3a65fac150e53289700efe1
+yuv420p             2e6d6062e8cad37fb3ab2c433b55f382
+yuv420p16be         539076782902664a8acf381bf4f713e8
+yuv420p16le         0f609e588e5a258644ef85170d70e030
+yuv422p             d7f5cb44d9b0210d66d6a8762640ab34
+yuv422p16be         9bd8f8c961822b586fa4cf992be54acc
+yuv422p16le         9c4a1239605c7952b736ac3130163f14
+yuv440p             876385e96165acf51271b20e5d85a416
+yuv444p             9c3c667d1613b72d15bc6d851c5eb8f7
+yuv444p16be         0f4afa4a4aacf4bb6b87641abde71ea9
+yuv444p16le         8f31557bc52adfe00ae8b40a9b8c23f8
+yuva420p            c705d1cf061d8c6580ac690b55f92276
+yuvj420p            41fd02b204da0ab62452cd14b595e2e4
+yuvj422p            7f6ca9bc1812cde02036d7d29a7cce43
+yuvj440p            40591908cca457f51dee30a86c3e8ffd
+yuvj444p            77e5e095881c52a04fd9f5abd1d7b5ac
+yuyv422             e944ff7316cd03c42c091717ce74f602
diff --git a/tests/ref/lavfi/scale200 b/tests/ref/lavfi/scale200
index 115e250..17103a2 100644
--- a/tests/ref/lavfi/scale200
+++ b/tests/ref/lavfi/scale200
@@ -1,2 +1 @@
-f7325609fdb8992bcea0cf3712ea2afc *./tests/data/lavfi/scale200.nut
-3001204 ./tests/data/lavfi/scale200.nut
+scale200            aebdc1c3e08da2a925ba7212b1fadee0
diff --git a/tests/ref/lavfi/scale500 b/tests/ref/lavfi/scale500
index c8ba15b..93ba4f2 100644
--- a/tests/ref/lavfi/scale500
+++ b/tests/ref/lavfi/scale500
@@ -1,2 +1 @@
-7e194861897fb42e20771711fe1aace3 *./tests/data/lavfi/scale500.nut
-18751503 ./tests/data/lavfi/scale500.nut
+scale500            ef865c51156e55ce1ce38c8f90a709e6
diff --git a/tests/ref/lavfi/vflip b/tests/ref/lavfi/vflip
index 977f2d2..66b8732 100644
--- a/tests/ref/lavfi/vflip
+++ b/tests/ref/lavfi/vflip
@@ -1,2 +1 @@
-2e6d6062e8cad37fb3ab2c433b55f382 *./tests/data/lavfi/vflip.nut
-7604654 ./tests/data/lavfi/vflip.nut
+vflip               2e6d6062e8cad37fb3ab2c433b55f382
diff --git a/tests/ref/lavfi/vflip_crop b/tests/ref/lavfi/vflip_crop
index bd19894..6bb832f 100644
--- a/tests/ref/lavfi/vflip_crop
+++ b/tests/ref/lavfi/vflip_crop
@@ -1,2 +1 @@
-72ee0d0dfc8af0cd94a466760313654d *./tests/data/lavfi/vflip_crop.nut
-3554654 ./tests/data/lavfi/vflip_crop.nut
+vflip_crop          72ee0d0dfc8af0cd94a466760313654d
diff --git a/tests/ref/lavfi/vflip_vflip b/tests/ref/lavfi/vflip_vflip
index 55595dd..b719745 100644
--- a/tests/ref/lavfi/vflip_vflip
+++ b/tests/ref/lavfi/vflip_vflip
@@ -1,2 +1 @@
-eba2f135a08829387e2f698ff72a2939 *./tests/data/lavfi/vflip_vflip.nut
-7604654 ./tests/data/lavfi/vflip_vflip.nut
+vflip_vflip         eba2f135a08829387e2f698ff72a2939
diff --git a/tests/ref/seek/ac3.rm.ref b/tests/ref/seek/ac3.rm.ref
deleted file mode 100644
index e8e09e8..0000000
--- a/tests/ref/seek/ac3.rm.ref
+++ /dev/null
@@ -1,39 +0,0 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    271 size:   556
-ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    271 size:   556
-ret:-1         st:-1 flags:1  ts: 1.894167
-ret:-1         st: 0 flags:0  ts: 0.788000
-ret: 0         st: 0 flags:1  ts:-0.317000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    271 size:   556
-ret: 0         st:-1 flags:0  ts: 2.576668
-ret: 0         st: 0 flags:1 dts: 2.960000 pts: 2.960000 pos:  48659 size:   558
-ret:-1         st:-1 flags:1  ts: 1.470835
-ret:-1         st: 0 flags:0  ts: 0.365000
-ret: 0         st: 0 flags:1  ts:-0.741000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    271 size:   556
-ret: 0         st:-1 flags:0  ts: 2.153336
-ret: 0         st: 0 flags:1 dts: 2.960000 pts: 2.960000 pos:  48659 size:   558
-ret:-1         st:-1 flags:1  ts: 1.047503
-ret: 0         st: 0 flags:0  ts:-0.058000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    271 size:   556
-ret: 0         st: 0 flags:1  ts: 2.836000
-ret: 0         st: 0 flags:1 dts: 2.333000 pts: 2.333000 pos:  38413 size:   556
-ret:-1         st:-1 flags:0  ts: 1.730004
-ret:-1         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:0  ts:-0.482000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    271 size:   556
-ret:-1         st: 0 flags:1  ts: 2.413000
-ret:-1         st:-1 flags:0  ts: 1.306672
-ret:-1         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:0  ts:-0.905000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    271 size:   556
-ret: 0         st: 0 flags:1  ts: 1.989000
-ret: 0         st: 0 flags:1 dts: 1.915000 pts: 1.915000 pos:  31581 size:   558
-ret:-1         st:-1 flags:0  ts: 0.883340
-ret: 0         st:-1 flags:1  ts:-0.222493
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    271 size:   556
-ret:-1         st: 0 flags:0  ts: 2.672000
-ret:-1         st: 0 flags:1  ts: 1.566000
-ret:-1         st:-1 flags:0  ts: 0.460008
-ret: 0         st:-1 flags:1  ts:-0.645825
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    271 size:   556
diff --git a/tests/ref/seek/ac3_rm b/tests/ref/seek/ac3_rm
new file mode 100644
index 0000000..4705447
--- /dev/null
+++ b/tests/ref/seek/ac3_rm
@@ -0,0 +1,38 @@
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    271 size:   556
+ret: 0         st:-1 flags:0  ts:-1.000000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    271 size:   556
+ret:-1         st:-1 flags:1  ts: 1.894167
+ret:-1         st: 0 flags:0  ts: 0.788000
+ret: 0         st: 0 flags:1  ts:-0.317000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    271 size:   556
+ret: 0         st:-1 flags:0  ts: 2.576668
+ret: 0         st: 0 flags:1 dts: 2.577000 pts: 2.577000 pos:  42397 size:   558
+ret:-1         st:-1 flags:1  ts: 1.470835
+ret:-1         st: 0 flags:0  ts: 0.365000
+ret: 0         st: 0 flags:1  ts:-0.741000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    271 size:   556
+ret:-1         st:-1 flags:0  ts: 2.153336
+ret:-1         st:-1 flags:1  ts: 1.047503
+ret: 0         st: 0 flags:0  ts:-0.058000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    271 size:   556
+ret:-1         st: 0 flags:1  ts: 2.836000
+ret:-1         st:-1 flags:0  ts: 1.730004
+ret:-1         st:-1 flags:1  ts: 0.624171
+ret: 0         st: 0 flags:0  ts:-0.482000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    271 size:   556
+ret: 0         st: 0 flags:1  ts: 2.413000
+ret: 0         st: 0 flags:1 dts: 2.368000 pts: 2.368000 pos:  38981 size:   558
+ret:-1         st:-1 flags:0  ts: 1.306672
+ret:-1         st:-1 flags:1  ts: 0.200839
+ret: 0         st: 0 flags:0  ts:-0.905000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    271 size:   556
+ret:-1         st: 0 flags:1  ts: 1.989000
+ret:-1         st:-1 flags:0  ts: 0.883340
+ret: 0         st:-1 flags:1  ts:-0.222493
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    271 size:   556
+ret: 0         st: 0 flags:0  ts: 2.672000
+ret: 0         st: 0 flags:1 dts: 2.821000 pts: 2.821000 pos:  46383 size:   556
+ret:-1         st: 0 flags:1  ts: 1.566000
+ret:-1         st:-1 flags:0  ts: 0.460008
+ret: 0         st:-1 flags:1  ts:-0.645825
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    271 size:   556
diff --git a/tests/ref/seek/adpcm_ima.wav.ref b/tests/ref/seek/adpcm_ima_wav
similarity index 100%
rename from tests/ref/seek/adpcm_ima.wav.ref
rename to tests/ref/seek/adpcm_ima_wav
diff --git a/tests/ref/seek/adpcm_ms.wav.ref b/tests/ref/seek/adpcm_ms_wav
similarity index 100%
rename from tests/ref/seek/adpcm_ms.wav.ref
rename to tests/ref/seek/adpcm_ms_wav
diff --git a/tests/ref/seek/adpcm_qt.aiff.ref b/tests/ref/seek/adpcm_qt_aiff
similarity index 100%
rename from tests/ref/seek/adpcm_qt.aiff.ref
rename to tests/ref/seek/adpcm_qt_aiff
diff --git a/tests/ref/seek/adpcm_swf.flv.ref b/tests/ref/seek/adpcm_swf_flv
similarity index 100%
rename from tests/ref/seek/adpcm_swf.flv.ref
rename to tests/ref/seek/adpcm_swf_flv
diff --git a/tests/ref/seek/adpcm_yam.wav.ref b/tests/ref/seek/adpcm_yam_wav
similarity index 100%
rename from tests/ref/seek/adpcm_yam.wav.ref
rename to tests/ref/seek/adpcm_yam_wav
diff --git a/tests/ref/seek/alac.m4a.ref b/tests/ref/seek/alac_m4a
similarity index 100%
rename from tests/ref/seek/alac.m4a.ref
rename to tests/ref/seek/alac_m4a
diff --git a/tests/ref/seek/asv1.avi.ref b/tests/ref/seek/asv1_avi
similarity index 100%
rename from tests/ref/seek/asv1.avi.ref
rename to tests/ref/seek/asv1_avi
diff --git a/tests/ref/seek/asv2.avi.ref b/tests/ref/seek/asv2_avi
similarity index 100%
rename from tests/ref/seek/asv2.avi.ref
rename to tests/ref/seek/asv2_avi
diff --git a/tests/ref/seek/dnxhd-1080i.mov.ref b/tests/ref/seek/dnxhd_1080i_mov
similarity index 100%
rename from tests/ref/seek/dnxhd-1080i.mov.ref
rename to tests/ref/seek/dnxhd_1080i_mov
diff --git a/tests/ref/seek/dnxhd-720p-rd.dnxhd.ref b/tests/ref/seek/dnxhd_720p_dnxhd
similarity index 100%
rename from tests/ref/seek/dnxhd-720p-rd.dnxhd.ref
rename to tests/ref/seek/dnxhd_720p_dnxhd
diff --git a/tests/ref/seek/dnxhd-720p.dnxhd.ref b/tests/ref/seek/dnxhd_720p_rd_dnxhd
similarity index 100%
rename from tests/ref/seek/dnxhd-720p.dnxhd.ref
rename to tests/ref/seek/dnxhd_720p_rd_dnxhd
diff --git a/tests/ref/seek/dv.dv.ref b/tests/ref/seek/dv411_dv
similarity index 100%
rename from tests/ref/seek/dv.dv.ref
rename to tests/ref/seek/dv411_dv
diff --git a/tests/ref/seek/dv50.dv.ref b/tests/ref/seek/dv50_dv
similarity index 100%
rename from tests/ref/seek/dv50.dv.ref
rename to tests/ref/seek/dv50_dv
diff --git a/tests/ref/seek/dv411.dv.ref b/tests/ref/seek/dv_dv
similarity index 100%
rename from tests/ref/seek/dv411.dv.ref
rename to tests/ref/seek/dv_dv
diff --git a/tests/ref/seek/error-mpeg4-adv.avi.ref b/tests/ref/seek/error_mpeg4_adv_avi
similarity index 100%
rename from tests/ref/seek/error-mpeg4-adv.avi.ref
rename to tests/ref/seek/error_mpeg4_adv_avi
diff --git a/tests/ref/seek/ffv1.avi.ref b/tests/ref/seek/ffv1_avi
similarity index 100%
rename from tests/ref/seek/ffv1.avi.ref
rename to tests/ref/seek/ffv1_avi
diff --git a/tests/ref/seek/flac.flac.ref b/tests/ref/seek/flac.flac.ref
deleted file mode 100644
index c9d6a7d..0000000
--- a/tests/ref/seek/flac.flac.ref
+++ /dev/null
@@ -1,27 +0,0 @@
-ret: 0         st: 0 flags:1 dts: NOPTS    pts: NOPTS    pos:   8256 size:  1024
-ret:-1         st:-1 flags:0  ts:-1.000000
-ret:-1         st:-1 flags:1  ts: 1.894167
-ret:-1         st: 0 flags:0  ts: 0.788345
-ret:-1         st: 0 flags:1  ts:-0.317506
-ret:-1         st:-1 flags:0  ts: 2.576668
-ret:-1         st:-1 flags:1  ts: 1.470835
-ret:-1         st: 0 flags:0  ts: 0.365011
-ret:-1         st: 0 flags:1  ts:-0.740839
-ret:-1         st:-1 flags:0  ts: 2.153336
-ret:-1         st:-1 flags:1  ts: 1.047503
-ret:-1         st: 0 flags:0  ts:-0.058322
-ret:-1         st: 0 flags:1  ts: 2.835828
-ret:-1         st:-1 flags:0  ts: 1.730004
-ret:-1         st:-1 flags:1  ts: 0.624171
-ret:-1         st: 0 flags:0  ts:-0.481655
-ret:-1         st: 0 flags:1  ts: 2.412494
-ret:-1         st:-1 flags:0  ts: 1.306672
-ret:-1         st:-1 flags:1  ts: 0.200839
-ret:-1         st: 0 flags:0  ts:-0.904989
-ret:-1         st: 0 flags:1  ts: 1.989184
-ret:-1         st:-1 flags:0  ts: 0.883340
-ret:-1         st:-1 flags:1  ts:-0.222493
-ret:-1         st: 0 flags:0  ts: 2.671678
-ret:-1         st: 0 flags:1  ts: 1.565850
-ret:-1         st:-1 flags:0  ts: 0.460008
-ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/flac_flac b/tests/ref/seek/flac_flac
new file mode 100644
index 0000000..ab31891
--- /dev/null
+++ b/tests/ref/seek/flac_flac
@@ -0,0 +1,49 @@
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   8256 size:   614
+ret: 0         st:-1 flags:0  ts:-1.000000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   8256 size:   614
+ret: 0         st:-1 flags:1  ts: 1.894167
+ret: 0         st: 0 flags:1 dts: 1.880816 pts: 1.880816 pos:  86742 size:  2191
+ret: 0         st: 0 flags:0  ts: 0.788345
+ret: 0         st: 0 flags:1 dts: 0.809796 pts: 0.809796 pos:  27366 size:   615
+ret:-1         st: 0 flags:1  ts:-0.317506
+ret: 0         st:-1 flags:0  ts: 2.576668
+ret: 0         st: 0 flags:1 dts: 2.586122 pts: 2.586122 pos: 145606 size:  2384
+ret: 0         st:-1 flags:1  ts: 1.470835
+ret: 0         st: 0 flags:1 dts: 1.462857 pts: 1.462857 pos:  53388 size:  1851
+ret: 0         st: 0 flags:0  ts: 0.365011
+ret: 0         st: 0 flags:1 dts: 0.365714 pts: 0.365714 pos:  16890 size:   614
+ret:-1         st: 0 flags:1  ts:-0.740839
+ret: 0         st:-1 flags:0  ts: 2.153336
+ret: 0         st: 0 flags:1 dts: 2.168163 pts: 2.168163 pos: 110531 size:  2143
+ret: 0         st:-1 flags:1  ts: 1.047503
+ret: 0         st: 0 flags:1 dts: 1.044898 pts: 1.044898 pos:  32880 size:   579
+ret: 0         st: 0 flags:0  ts:-0.058322
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   8256 size:   614
+ret: 0         st: 0 flags:1  ts: 2.835828
+ret: 0         st: 0 flags:1 dts: 2.821224 pts: 2.821224 pos: 167112 size:  2391
+ret: 0         st:-1 flags:0  ts: 1.730004
+ret: 0         st: 0 flags:1 dts: 1.750204 pts: 1.750204 pos:  75788 size:  2191
+ret: 0         st:-1 flags:1  ts: 0.624171
+ret: 0         st: 0 flags:1 dts: 0.600816 pts: 0.600816 pos:  22446 size:   616
+ret: 0         st: 0 flags:0  ts:-0.481655
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   8256 size:   614
+ret: 0         st: 0 flags:1  ts: 2.412494
+ret: 0         st: 0 flags:1 dts: 2.403265 pts: 2.403265 pos: 129793 size:  2138
+ret: 0         st:-1 flags:0  ts: 1.306672
+ret: 0         st: 0 flags:1 dts: 1.332245 pts: 1.332245 pos:  44812 size:  1609
+ret: 0         st:-1 flags:1  ts: 0.200839
+ret: 0         st: 0 flags:1 dts: 0.182857 pts: 0.182857 pos:  12572 size:   628
+ret: 0         st: 0 flags:0  ts:-0.904989
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   8256 size:   614
+ret: 0         st: 0 flags:1  ts: 1.989184
+ret: 0         st: 0 flags:1 dts: 1.985306 pts: 1.985306 pos:  95508 size:  2169
+ret: 0         st:-1 flags:0  ts: 0.883340
+ret: 0         st: 0 flags:1 dts: 0.888163 pts: 0.888163 pos:  29211 size:   620
+ret:-1         st:-1 flags:1  ts:-0.222493
+ret: 0         st: 0 flags:0  ts: 2.671678
+ret: 0         st: 0 flags:1 dts: 2.690612 pts: 2.690612 pos: 155154 size:  2394
+ret: 0         st: 0 flags:1  ts: 1.565850
+ret: 0         st: 0 flags:1 dts: 1.541224 pts: 1.541224 pos:  59082 size:  1974
+ret: 0         st:-1 flags:0  ts: 0.460008
+ret: 0         st: 0 flags:1 dts: 0.470204 pts: 0.470204 pos:  19353 size:   608
+ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/flashsv.flv.ref b/tests/ref/seek/flashsv_flv
similarity index 100%
rename from tests/ref/seek/flashsv.flv.ref
rename to tests/ref/seek/flashsv_flv
diff --git a/tests/ref/seek/flv.flv.ref b/tests/ref/seek/flv_flv
similarity index 100%
rename from tests/ref/seek/flv.flv.ref
rename to tests/ref/seek/flv_flv
diff --git a/tests/ref/seek/g726.wav.ref b/tests/ref/seek/g726_wav
similarity index 100%
rename from tests/ref/seek/g726.wav.ref
rename to tests/ref/seek/g726_wav
diff --git a/tests/ref/seek/h261.avi.ref b/tests/ref/seek/h261_avi
similarity index 100%
rename from tests/ref/seek/h261.avi.ref
rename to tests/ref/seek/h261_avi
diff --git a/tests/ref/seek/h263.avi.ref b/tests/ref/seek/h263_avi
similarity index 100%
rename from tests/ref/seek/h263.avi.ref
rename to tests/ref/seek/h263_avi
diff --git a/tests/ref/seek/h263p.avi.ref b/tests/ref/seek/h263p_avi
similarity index 100%
rename from tests/ref/seek/h263p.avi.ref
rename to tests/ref/seek/h263p_avi
diff --git a/tests/ref/seek/huffyuv.avi.ref b/tests/ref/seek/huffyuv_avi
similarity index 100%
rename from tests/ref/seek/huffyuv.avi.ref
rename to tests/ref/seek/huffyuv_avi
diff --git a/tests/ref/seek/%02d.bmp.ref b/tests/ref/seek/image_bmp
similarity index 100%
rename from tests/ref/seek/%02d.bmp.ref
rename to tests/ref/seek/image_bmp
diff --git a/tests/ref/seek/%02d.jpg.ref b/tests/ref/seek/image_jpg
similarity index 100%
rename from tests/ref/seek/%02d.jpg.ref
rename to tests/ref/seek/image_jpg
diff --git a/tests/ref/seek/%02d.pcx.ref b/tests/ref/seek/image_pcx
similarity index 100%
rename from tests/ref/seek/%02d.pcx.ref
rename to tests/ref/seek/image_pcx
diff --git a/tests/ref/seek/%02d.pgm.ref b/tests/ref/seek/image_pgm
similarity index 100%
rename from tests/ref/seek/%02d.pgm.ref
rename to tests/ref/seek/image_pgm
diff --git a/tests/ref/seek/%02d.ppm.ref b/tests/ref/seek/image_ppm
similarity index 100%
rename from tests/ref/seek/%02d.ppm.ref
rename to tests/ref/seek/image_ppm
diff --git a/tests/ref/seek/%02d.sgi.ref b/tests/ref/seek/image_sgi
similarity index 100%
rename from tests/ref/seek/%02d.sgi.ref
rename to tests/ref/seek/image_sgi
diff --git a/tests/ref/seek/%02d.tga.ref b/tests/ref/seek/image_tga
similarity index 100%
rename from tests/ref/seek/%02d.tga.ref
rename to tests/ref/seek/image_tga
diff --git a/tests/ref/seek/%02d.tiff.ref b/tests/ref/seek/image_tiff
similarity index 100%
rename from tests/ref/seek/%02d.tiff.ref
rename to tests/ref/seek/image_tiff
diff --git a/tests/ref/seek/jpegls.avi.ref b/tests/ref/seek/jpegls_avi
similarity index 100%
rename from tests/ref/seek/jpegls.avi.ref
rename to tests/ref/seek/jpegls_avi
diff --git a/tests/ref/seek/lavf.asf.ref b/tests/ref/seek/lavf.asf.ref
deleted file mode 100644
index afaed99..0000000
--- a/tests/ref/seek/lavf.asf.ref
+++ /dev/null
@@ -1,53 +0,0 @@
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    575 size: 28487
-ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 1 flags:1 dts: 3.544000 pts: 3.544000 pos: 147775 size:   209
-ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    575 size: 28487
-ret: 0         st: 0 flags:0  ts: 0.788000
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    575 size: 28487
-ret: 0         st: 0 flags:1  ts:-0.317000
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    575 size: 28487
-ret: 0         st: 1 flags:0  ts: 2.577000
-ret: 0         st: 1 flags:1 dts: 3.100000 pts: 3.100000 pos:  29375 size:   208
-ret: 0         st: 1 flags:1  ts: 1.471000
-ret: 0         st: 1 flags:1 dts: 3.100000 pts: 3.100000 pos:  29375 size:   208
-ret: 0         st:-1 flags:0  ts: 0.365002
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    575 size: 28487
-ret: 0         st:-1 flags:1  ts:-0.740831
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    575 size: 28487
-ret: 0         st: 0 flags:0  ts: 2.153000
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    575 size: 28487
-ret: 0         st: 0 flags:1  ts: 1.048000
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    575 size: 28487
-ret: 0         st: 1 flags:0  ts:-0.058000
-ret: 0         st: 1 flags:1 dts: 3.100000 pts: 3.100000 pos:  29375 size:   208
-ret: 0         st: 1 flags:1  ts: 2.836000
-ret: 0         st: 1 flags:1 dts: 3.100000 pts: 3.100000 pos:  29375 size:   208
-ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    575 size: 28487
-ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    575 size: 28487
-ret: 0         st: 0 flags:0  ts:-0.482000
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    575 size: 28487
-ret: 0         st: 0 flags:1  ts: 2.413000
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    575 size: 28487
-ret: 0         st: 1 flags:0  ts: 1.307000
-ret: 0         st: 1 flags:1 dts: 3.100000 pts: 3.100000 pos:  29375 size:   208
-ret: 0         st: 1 flags:1  ts: 0.201000
-ret: 0         st: 1 flags:1 dts: 3.100000 pts: 3.100000 pos:  29375 size:   208
-ret: 0         st:-1 flags:0  ts:-0.904994
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    575 size: 28487
-ret: 0         st:-1 flags:1  ts: 1.989173
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    575 size: 28487
-ret: 0         st: 0 flags:0  ts: 0.883000
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    575 size: 28487
-ret: 0         st: 0 flags:1  ts:-0.222000
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    575 size: 28487
-ret: 0         st: 1 flags:0  ts: 2.672000
-ret: 0         st: 1 flags:1 dts: 3.100000 pts: 3.100000 pos:  29375 size:   208
-ret: 0         st: 1 flags:1  ts: 1.566000
-ret: 0         st: 1 flags:1 dts: 3.100000 pts: 3.100000 pos:  29375 size:   208
-ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    575 size: 28487
-ret: 0         st:-1 flags:1  ts:-0.645825
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    575 size: 28487
diff --git a/tests/ref/seek/lavf.avi.ref b/tests/ref/seek/lavf.avi.ref
deleted file mode 100644
index 964f0b8..0000000
--- a/tests/ref/seek/lavf.avi.ref
+++ /dev/null
@@ -1,44 +0,0 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   9908 size: 27867
-ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   9908 size: 27867
-ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 301466 size: 27864
-ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 301466 size: 27864
-ret:-1         st: 0 flags:1  ts:-0.320000
-ret:-1         st: 1 flags:0  ts: 2.586122
-ret: 0         st: 1 flags:1  ts: 1.462857
-ret: 0         st: 1 flags:1 dts: 1.018776 pts: 1.018776 pos: 329774 size:   209
-ret: 0         st:-1 flags:0  ts: 0.365002
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 156166 size: 27955
-ret:-1         st:-1 flags:1  ts:-0.740831
-ret:-1         st: 0 flags:0  ts: 2.160000
-ret: 0         st: 0 flags:1  ts: 1.040000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 301466 size: 27864
-ret: 0         st: 1 flags:0  ts:-0.052245
-ret: 0         st: 1 flags:1 dts: 0.000000 pts: 0.000000 pos:  37784 size:   208
-ret: 0         st: 1 flags:1  ts: 2.847347
-ret: 0         st: 1 flags:1 dts: 1.018776 pts: 1.018776 pos: 329774 size:   209
-ret:-1         st:-1 flags:0  ts: 1.730004
-ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 156166 size: 27955
-ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   9908 size: 27867
-ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 301466 size: 27864
-ret:-1         st: 1 flags:0  ts: 1.306122
-ret: 0         st: 1 flags:1  ts: 0.208980
-ret: 0         st: 1 flags:1 dts: 0.208980 pts: 0.208980 pos:  92800 size:   209
-ret: 0         st:-1 flags:0  ts:-0.904994
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   9908 size: 27867
-ret: 0         st:-1 flags:1  ts: 1.989173
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 301466 size: 27864
-ret: 0         st: 0 flags:0  ts: 0.880000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 301466 size: 27864
-ret:-1         st: 0 flags:1  ts:-0.240000
-ret:-1         st: 1 flags:0  ts: 2.664490
-ret: 0         st: 1 flags:1  ts: 1.567347
-ret: 0         st: 1 flags:1 dts: 1.018776 pts: 1.018776 pos: 329774 size:   209
-ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 156166 size: 27955
-ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/lavf.mkv.ref b/tests/ref/seek/lavf.mkv.ref
deleted file mode 100644
index 5af4488..0000000
--- a/tests/ref/seek/lavf.mkv.ref
+++ /dev/null
@@ -1,53 +0,0 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    513 size: 27837
-ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    513 size: 27837
-ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 291902 size: 27834
-ret: 0         st: 0 flags:0  ts: 0.788000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 291902 size: 27834
-ret: 0         st: 0 flags:1  ts:-0.317000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    513 size: 27837
-ret: 0         st: 1 flags:0  ts: 2.577000
-ret:-EOF
-ret: 0         st: 1 flags:1  ts: 1.471000
-ret: 0         st: 1 flags:1 dts: 1.019000 pts: 1.019000 pos: 320175 size:   209
-ret: 0         st:-1 flags:0  ts: 0.365002
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146687 size: 27925
-ret: 0         st:-1 flags:1  ts:-0.740831
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    513 size: 27837
-ret: 0         st: 0 flags:0  ts: 2.153000
-ret:-EOF
-ret: 0         st: 0 flags:1  ts: 1.048000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 291902 size: 27834
-ret: 0         st: 1 flags:0  ts:-0.058000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    513 size: 27837
-ret: 0         st: 1 flags:1  ts: 2.836000
-ret: 0         st: 1 flags:1 dts: 1.019000 pts: 1.019000 pos: 320175 size:   209
-ret: 0         st:-1 flags:0  ts: 1.730004
-ret:-EOF
-ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146687 size: 27925
-ret: 0         st: 0 flags:0  ts:-0.482000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    513 size: 27837
-ret: 0         st: 0 flags:1  ts: 2.413000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 291902 size: 27834
-ret: 0         st: 1 flags:0  ts: 1.307000
-ret:-EOF
-ret: 0         st: 1 flags:1  ts: 0.201000
-ret: 0         st: 1 flags:1 dts: 0.183000 pts: 0.183000 pos:  72083 size:   209
-ret: 0         st:-1 flags:0  ts:-0.904994
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    513 size: 27837
-ret: 0         st:-1 flags:1  ts: 1.989173
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 291902 size: 27834
-ret: 0         st: 0 flags:0  ts: 0.883000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 291902 size: 27834
-ret: 0         st: 0 flags:1  ts:-0.222000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    513 size: 27837
-ret: 0         st: 1 flags:0  ts: 2.672000
-ret:-EOF
-ret: 0         st: 1 flags:1  ts: 1.566000
-ret: 0         st: 1 flags:1 dts: 1.019000 pts: 1.019000 pos: 320175 size:   209
-ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146687 size: 27925
-ret: 0         st:-1 flags:1  ts:-0.645825
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    513 size: 27837
diff --git a/tests/ref/seek/lavf.mpg.ref b/tests/ref/seek/lavf.mpg.ref
deleted file mode 100644
index 4f07864..0000000
--- a/tests/ref/seek/lavf.mpg.ref
+++ /dev/null
@@ -1,53 +0,0 @@
-ret: 0         st: 1 flags:1 dts: 0.500000 pts: 0.500000 pos:   2048 size:   208
-ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 1 flags:1 dts: 0.500000 pts: 0.500000 pos:   2048 size:   208
-ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.420000 pts: 1.460000 pos: 339968 size:   681
-ret: 0         st: 0 flags:0  ts: 0.788333
-ret: 0         st: 1 flags:1 dts: 0.761222 pts: 0.761222 pos: 145408 size:   261
-ret: 0         st: 0 flags:1  ts:-0.317500
-ret: 0         st: 1 flags:1 dts: 0.500000 pts: 0.500000 pos:   2048 size:   208
-ret: 0         st: 1 flags:0  ts: 2.576667
-ret: 0         st: 1 flags:1 dts: 1.518778 pts: 1.518778 pos: 370700 size:   235
-ret: 0         st: 1 flags:1  ts: 1.470833
-ret: 0         st: 1 flags:1 dts: 1.283678 pts: 1.283678 pos: 368652 size:   379
-ret: 0         st:-1 flags:0  ts: 0.365002
-ret: 0         st: 1 flags:1 dts: 0.500000 pts: 0.500000 pos:   2048 size:   208
-ret: 0         st:-1 flags:1  ts:-0.740831
-ret: 0         st: 1 flags:1 dts: 0.500000 pts: 0.500000 pos:   2048 size:   208
-ret: 0         st: 0 flags:0  ts: 2.153333
-ret: 0         st: 0 flags:1 dts: 1.420000 pts: 1.460000 pos: 339968 size:   681
-ret: 0         st: 0 flags:1  ts: 1.047500
-ret: 0         st: 0 flags:0 dts: 1.020000 pts: 1.060000 pos: 212992 size: 16484
-ret: 0         st: 1 flags:0  ts:-0.058333
-ret: 0         st: 1 flags:1 dts: 0.500000 pts: 0.500000 pos:   2048 size:   208
-ret: 0         st: 1 flags:1  ts: 2.835833
-ret: 0         st: 1 flags:1 dts: 1.518778 pts: 1.518778 pos: 370700 size:   235
-ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.420000 pts: 1.460000 pos: 339968 size:   681
-ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:0 dts: 0.620000 pts: 0.660000 pos:  67584 size: 15804
-ret: 0         st: 0 flags:0  ts:-0.481667
-ret: 0         st: 1 flags:1 dts: 0.500000 pts: 0.500000 pos:   2048 size:   208
-ret: 0         st: 0 flags:1  ts: 2.412500
-ret: 0         st: 0 flags:1 dts: 1.420000 pts: 1.460000 pos: 339968 size:   681
-ret: 0         st: 1 flags:0  ts: 1.306667
-ret: 0         st: 1 flags:1 dts: 1.518778 pts: 1.518778 pos: 370700 size:   235
-ret: 0         st: 1 flags:1  ts: 0.200844
-ret: 0         st: 1 flags:1 dts: 0.500000 pts: 0.500000 pos:   2048 size:   208
-ret: 0         st:-1 flags:0  ts:-0.904994
-ret: 0         st: 1 flags:1 dts: 0.500000 pts: 0.500000 pos:   2048 size:   208
-ret: 0         st:-1 flags:1  ts: 1.989173
-ret: 0         st: 0 flags:1 dts: 1.420000 pts: 1.460000 pos: 339968 size:   681
-ret: 0         st: 0 flags:0  ts: 0.883344
-ret: 0         st: 0 flags:0 dts: 0.900000 pts: 0.940000 pos: 159744 size: 12809
-ret: 0         st: 0 flags:1  ts:-0.222489
-ret: 0         st: 1 flags:1 dts: 0.500000 pts: 0.500000 pos:   2048 size:   208
-ret: 0         st: 1 flags:0  ts: 2.671678
-ret: 0         st: 1 flags:1 dts: 1.518778 pts: 1.518778 pos: 370700 size:   235
-ret: 0         st: 1 flags:1  ts: 1.565844
-ret: 0         st: 1 flags:1 dts: 1.518778 pts: 1.518778 pos: 370700 size:   235
-ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:0 dts: 0.500000 pts: 0.540000 pos:  26624 size: 16303
-ret: 0         st:-1 flags:1  ts:-0.645825
-ret: 0         st: 1 flags:1 dts: 0.500000 pts: 0.500000 pos:   2048 size:   208
diff --git a/tests/ref/seek/lavf.nut.ref b/tests/ref/seek/lavf.nut.ref
deleted file mode 100644
index fc3ef63..0000000
--- a/tests/ref/seek/lavf.nut.ref
+++ /dev/null
@@ -1,53 +0,0 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    279 size: 27837
-ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    279 size: 27837
-ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146329 size: 27925
-ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146329 size: 27925
-ret: 0         st: 0 flags:1  ts:-0.320000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    279 size: 27837
-ret: 0         st: 1 flags:0  ts: 2.586122
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146329 size: 27925
-ret: 0         st: 1 flags:1  ts: 1.462857
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146329 size: 27925
-ret: 0         st:-1 flags:0  ts: 0.365002
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    279 size: 27837
-ret: 0         st:-1 flags:1  ts:-0.740831
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    279 size: 27837
-ret: 0         st: 0 flags:0  ts: 2.160000
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146329 size: 27925
-ret: 0         st: 0 flags:1  ts: 1.040000
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146329 size: 27925
-ret: 0         st: 1 flags:0  ts:-0.052245
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    279 size: 27837
-ret: 0         st: 1 flags:1  ts: 2.847347
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146329 size: 27925
-ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146329 size: 27925
-ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146329 size: 27925
-ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    279 size: 27837
-ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146329 size: 27925
-ret: 0         st: 1 flags:0  ts: 1.306122
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146329 size: 27925
-ret: 0         st: 1 flags:1  ts: 0.208980
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    279 size: 27837
-ret: 0         st:-1 flags:0  ts:-0.904994
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    279 size: 27837
-ret: 0         st:-1 flags:1  ts: 1.989173
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146329 size: 27925
-ret: 0         st: 0 flags:0  ts: 0.880000
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146329 size: 27925
-ret: 0         st: 0 flags:1  ts:-0.240000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    279 size: 27837
-ret: 0         st: 1 flags:0  ts: 2.664490
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146329 size: 27925
-ret: 0         st: 1 flags:1  ts: 1.567347
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146329 size: 27925
-ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146329 size: 27925
-ret: 0         st:-1 flags:1  ts:-0.645825
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    279 size: 27837
diff --git a/tests/ref/seek/lavf.aif.ref b/tests/ref/seek/lavf_aif
similarity index 100%
rename from tests/ref/seek/lavf.aif.ref
rename to tests/ref/seek/lavf_aif
diff --git a/tests/ref/seek/lavf.al.ref b/tests/ref/seek/lavf_al
similarity index 100%
rename from tests/ref/seek/lavf.al.ref
rename to tests/ref/seek/lavf_al
diff --git a/tests/ref/seek/lavf_asf b/tests/ref/seek/lavf_asf
new file mode 100644
index 0000000..757fd0e
--- /dev/null
+++ b/tests/ref/seek/lavf_asf
@@ -0,0 +1,47 @@
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    575 size: 28487
+ret: 0         st:-1 flags:0  ts:-1.000000
+ret: 0         st: 1 flags:1 dts: 0.444000 pts: 0.444000 pos: 147775 size:   209
+ret: 0         st:-1 flags:1  ts: 1.894167
+ret: 0         st: 1 flags:1 dts: 0.960000 pts: 0.960000 pos:     -1 size:   209
+ret: 0         st: 0 flags:0  ts: 0.788000
+ret: 0         st: 1 flags:1 dts: 0.960000 pts: 0.960000 pos:     -1 size:   209
+ret: 0         st: 0 flags:1  ts:-0.317000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    575 size: 28487
+ret:-1         st: 1 flags:0  ts: 2.577000
+ret:-1         st: 1 flags:1  ts: 1.471000
+ret: 0         st:-1 flags:0  ts: 0.365002
+ret: 0         st: 1 flags:1 dts: 0.444000 pts: 0.444000 pos: 147775 size:   209
+ret: 0         st:-1 flags:1  ts:-0.740831
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    575 size: 28487
+ret: 0         st: 0 flags:0  ts: 2.153000
+ret: 0         st: 1 flags:1 dts: 0.960000 pts: 0.960000 pos:     -1 size:   209
+ret: 0         st: 0 flags:1  ts: 1.048000
+ret: 0         st: 1 flags:1 dts: 0.960000 pts: 0.960000 pos:     -1 size:   209
+ret: 0         st: 1 flags:0  ts:-0.058000
+ret: 0         st: 1 flags:1 dts: 0.000000 pts: 0.000000 pos:  29375 size:   208
+ret:-1         st: 1 flags:1  ts: 2.836000
+ret: 0         st:-1 flags:0  ts: 1.730004
+ret: 0         st: 1 flags:1 dts: 0.960000 pts: 0.960000 pos:     -1 size:   209
+ret: 0         st:-1 flags:1  ts: 0.624171
+ret: 0         st: 1 flags:1 dts: 0.444000 pts: 0.444000 pos: 147775 size:   209
+ret: 0         st: 0 flags:0  ts:-0.482000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    575 size: 28487
+ret: 0         st: 0 flags:1  ts: 2.413000
+ret: 0         st: 1 flags:1 dts: 0.960000 pts: 0.960000 pos:     -1 size:   209
+ret:-1         st: 1 flags:0  ts: 1.307000
+ret: 0         st: 1 flags:1  ts: 0.201000
+ret: 0         st: 1 flags:1 dts: 0.183000 pts: 0.183000 pos:  70975 size:   209
+ret: 0         st:-1 flags:0  ts:-0.904994
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    575 size: 28487
+ret: 0         st:-1 flags:1  ts: 1.989173
+ret: 0         st: 1 flags:1 dts: 0.960000 pts: 0.960000 pos:     -1 size:   209
+ret: 0         st: 0 flags:0  ts: 0.883000
+ret: 0         st: 1 flags:1 dts: 0.960000 pts: 0.960000 pos:     -1 size:   209
+ret: 0         st: 0 flags:1  ts:-0.222000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    575 size: 28487
+ret:-1         st: 1 flags:0  ts: 2.672000
+ret:-1         st: 1 flags:1  ts: 1.566000
+ret: 0         st:-1 flags:0  ts: 0.460008
+ret: 0         st: 1 flags:1 dts: 0.444000 pts: 0.444000 pos: 147775 size:   209
+ret: 0         st:-1 flags:1  ts:-0.645825
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    575 size: 28487
diff --git a/tests/ref/seek/lavf.au.ref b/tests/ref/seek/lavf_au
similarity index 100%
rename from tests/ref/seek/lavf.au.ref
rename to tests/ref/seek/lavf_au
diff --git a/tests/ref/seek/lavf_avi b/tests/ref/seek/lavf_avi
new file mode 100644
index 0000000..03fa47d
--- /dev/null
+++ b/tests/ref/seek/lavf_avi
@@ -0,0 +1,44 @@
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   9908 size: 27867
+ret: 0         st:-1 flags:0  ts:-1.000000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   9908 size: 27867
+ret: 0         st:-1 flags:1  ts: 1.894167
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 301248 size: 27864
+ret: 0         st: 0 flags:0  ts: 0.800000
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 301248 size: 27864
+ret:-1         st: 0 flags:1  ts:-0.320000
+ret:-1         st: 1 flags:0  ts: 2.586122
+ret: 0         st: 1 flags:1  ts: 1.462857
+ret: 0         st: 1 flags:1 dts: 1.018776 pts: 1.018776 pos: 329774 size:   209
+ret: 0         st:-1 flags:0  ts: 0.365002
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 155948 size: 27955
+ret:-1         st:-1 flags:1  ts:-0.740831
+ret:-1         st: 0 flags:0  ts: 2.160000
+ret: 0         st: 0 flags:1  ts: 1.040000
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 301248 size: 27864
+ret: 0         st: 1 flags:0  ts:-0.052245
+ret: 0         st: 1 flags:1 dts: 0.000000 pts: 0.000000 pos:  37784 size:   208
+ret: 0         st: 1 flags:1  ts: 2.847347
+ret: 0         st: 1 flags:1 dts: 1.018776 pts: 1.018776 pos: 329774 size:   209
+ret:-1         st:-1 flags:0  ts: 1.730004
+ret: 0         st:-1 flags:1  ts: 0.624171
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 155948 size: 27955
+ret: 0         st: 0 flags:0  ts:-0.480000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   9908 size: 27867
+ret: 0         st: 0 flags:1  ts: 2.400000
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 301248 size: 27864
+ret:-1         st: 1 flags:0  ts: 1.306122
+ret: 0         st: 1 flags:1  ts: 0.208980
+ret: 0         st: 1 flags:1 dts: 0.208980 pts: 0.208980 pos:  92800 size:   209
+ret: 0         st:-1 flags:0  ts:-0.904994
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   9908 size: 27867
+ret: 0         st:-1 flags:1  ts: 1.989173
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 301248 size: 27864
+ret: 0         st: 0 flags:0  ts: 0.880000
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 301248 size: 27864
+ret:-1         st: 0 flags:1  ts:-0.240000
+ret:-1         st: 1 flags:0  ts: 2.664490
+ret: 0         st: 1 flags:1  ts: 1.567347
+ret: 0         st: 1 flags:1 dts: 1.018776 pts: 1.018776 pos: 329774 size:   209
+ret: 0         st:-1 flags:0  ts: 0.460008
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 155948 size: 27955
+ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/lavf.dv.ref b/tests/ref/seek/lavf_dv
similarity index 100%
rename from tests/ref/seek/lavf.dv.ref
rename to tests/ref/seek/lavf_dv
diff --git a/tests/ref/seek/lavf.ffm.ref b/tests/ref/seek/lavf_ffm
similarity index 100%
rename from tests/ref/seek/lavf.ffm.ref
rename to tests/ref/seek/lavf_ffm
diff --git a/tests/ref/seek/lavf.flv.ref b/tests/ref/seek/lavf_flv
similarity index 100%
rename from tests/ref/seek/lavf.flv.ref
rename to tests/ref/seek/lavf_flv
diff --git a/tests/ref/seek/lavf.gif.ref b/tests/ref/seek/lavf_gif
similarity index 100%
rename from tests/ref/seek/lavf.gif.ref
rename to tests/ref/seek/lavf_gif
diff --git a/tests/ref/seek/lavf.gxf.ref b/tests/ref/seek/lavf_gxf
similarity index 100%
rename from tests/ref/seek/lavf.gxf.ref
rename to tests/ref/seek/lavf_gxf
diff --git a/tests/ref/seek/lavf_mkv b/tests/ref/seek/lavf_mkv
new file mode 100644
index 0000000..9f447b3
--- /dev/null
+++ b/tests/ref/seek/lavf_mkv
@@ -0,0 +1,53 @@
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    513 size: 27837
+ret: 0         st:-1 flags:0  ts:-1.000000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    513 size: 27837
+ret: 0         st:-1 flags:1  ts: 1.894167
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 291934 size: 27834
+ret: 0         st: 0 flags:0  ts: 0.788000
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 291934 size: 27834
+ret: 0         st: 0 flags:1  ts:-0.317000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    513 size: 27837
+ret: 0         st: 1 flags:0  ts: 2.577000
+ret:-EOF
+ret: 0         st: 1 flags:1  ts: 1.471000
+ret: 0         st: 1 flags:1 dts: 1.019000 pts: 1.019000 pos: 320207 size:   209
+ret: 0         st:-1 flags:0  ts: 0.365002
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146703 size: 27925
+ret: 0         st:-1 flags:1  ts:-0.740831
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    513 size: 27837
+ret: 0         st: 0 flags:0  ts: 2.153000
+ret:-EOF
+ret: 0         st: 0 flags:1  ts: 1.048000
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 291934 size: 27834
+ret: 0         st: 1 flags:0  ts:-0.058000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    513 size: 27837
+ret: 0         st: 1 flags:1  ts: 2.836000
+ret: 0         st: 1 flags:1 dts: 1.019000 pts: 1.019000 pos: 320207 size:   209
+ret: 0         st:-1 flags:0  ts: 1.730004
+ret:-EOF
+ret: 0         st:-1 flags:1  ts: 0.624171
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146703 size: 27925
+ret: 0         st: 0 flags:0  ts:-0.482000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    513 size: 27837
+ret: 0         st: 0 flags:1  ts: 2.413000
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 291934 size: 27834
+ret: 0         st: 1 flags:0  ts: 1.307000
+ret:-EOF
+ret: 0         st: 1 flags:1  ts: 0.201000
+ret: 0         st: 1 flags:1 dts: 0.183000 pts: 0.183000 pos:  72083 size:   209
+ret: 0         st:-1 flags:0  ts:-0.904994
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    513 size: 27837
+ret: 0         st:-1 flags:1  ts: 1.989173
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 291934 size: 27834
+ret: 0         st: 0 flags:0  ts: 0.883000
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 291934 size: 27834
+ret: 0         st: 0 flags:1  ts:-0.222000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    513 size: 27837
+ret: 0         st: 1 flags:0  ts: 2.672000
+ret:-EOF
+ret: 0         st: 1 flags:1  ts: 1.566000
+ret: 0         st: 1 flags:1 dts: 1.019000 pts: 1.019000 pos: 320207 size:   209
+ret: 0         st:-1 flags:0  ts: 0.460008
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146703 size: 27925
+ret: 0         st:-1 flags:1  ts:-0.645825
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    513 size: 27837
diff --git a/tests/ref/seek/lavf.mmf.ref b/tests/ref/seek/lavf_mmf
similarity index 100%
rename from tests/ref/seek/lavf.mmf.ref
rename to tests/ref/seek/lavf_mmf
diff --git a/tests/ref/seek/lavf.mov.ref b/tests/ref/seek/lavf_mov
similarity index 100%
rename from tests/ref/seek/lavf.mov.ref
rename to tests/ref/seek/lavf_mov
diff --git a/tests/ref/seek/lavf_mpg b/tests/ref/seek/lavf_mpg
new file mode 100644
index 0000000..dc51195
--- /dev/null
+++ b/tests/ref/seek/lavf_mpg
@@ -0,0 +1,53 @@
+ret: 0         st: 1 flags:1 dts: 1.000000 pts: 1.000000 pos:   2048 size:   208
+ret: 0         st:-1 flags:0  ts:-1.000000
+ret: 0         st: 1 flags:1 dts: 1.000000 pts: 1.000000 pos:   2048 size:   208
+ret: 0         st:-1 flags:1  ts: 1.894167
+ret: 0         st: 0 flags:0 dts: 1.880000 pts: 1.920000 pos: 327680 size: 12894
+ret: 0         st: 0 flags:0  ts: 0.788333
+ret: 0         st: 1 flags:1 dts: 1.000000 pts: 1.000000 pos:   2048 size:   208
+ret: 0         st: 0 flags:1  ts:-0.317500
+ret: 0         st: 1 flags:1 dts: 1.000000 pts: 1.000000 pos:   2048 size:   208
+ret: 0         st: 1 flags:0  ts: 2.576667
+ret: 0         st: 1 flags:1 dts: 2.018778 pts: 2.018778 pos: 370700 size:   235
+ret: 0         st: 1 flags:1  ts: 1.470833
+ret: 0         st: 1 flags:1 dts: 1.261222 pts: 1.261222 pos: 145408 size:   261
+ret: 0         st:-1 flags:0  ts: 0.365002
+ret: 0         st: 1 flags:1 dts: 1.000000 pts: 1.000000 pos:   2048 size:   208
+ret: 0         st:-1 flags:1  ts:-0.740831
+ret: 0         st: 1 flags:1 dts: 1.000000 pts: 1.000000 pos:   2048 size:   208
+ret: 0         st: 0 flags:0  ts: 2.153333
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.960000 pos: 339968 size:   681
+ret: 0         st: 0 flags:1  ts: 1.047500
+ret: 0         st: 0 flags:0 dts: 1.040000 pts: 1.080000 pos:  40960 size: 16073
+ret: 0         st: 1 flags:0  ts:-0.058333
+ret: 0         st: 1 flags:1 dts: 1.000000 pts: 1.000000 pos:   2048 size:   208
+ret: 0         st: 1 flags:1  ts: 2.835833
+ret: 0         st: 1 flags:1 dts: 2.018778 pts: 2.018778 pos: 370700 size:   235
+ret: 0         st:-1 flags:0  ts: 1.730004
+ret: 0         st: 0 flags:0 dts: 1.760000 pts: 1.800000 pos: 292864 size: 13170
+ret: 0         st:-1 flags:1  ts: 0.624171
+ret: 0         st: 1 flags:1 dts: 1.000000 pts: 1.000000 pos:   2048 size:   208
+ret: 0         st: 0 flags:0  ts:-0.481667
+ret: 0         st: 1 flags:1 dts: 1.000000 pts: 1.000000 pos:   2048 size:   208
+ret: 0         st: 0 flags:1  ts: 2.412500
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.960000 pos: 339968 size:   681
+ret: 0         st: 1 flags:0  ts: 1.306667
+ret: 0         st: 1 flags:1 dts: 1.522444 pts: 1.522444 pos: 342028 size:   314
+ret: 0         st: 1 flags:1  ts: 0.200844
+ret: 0         st: 1 flags:1 dts: 1.000000 pts: 1.000000 pos:   2048 size:   208
+ret: 0         st:-1 flags:0  ts:-0.904994
+ret: 0         st: 1 flags:1 dts: 1.000000 pts: 1.000000 pos:   2048 size:   208
+ret: 0         st:-1 flags:1  ts: 1.989173
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.960000 pos: 339968 size:   681
+ret: 0         st: 0 flags:0  ts: 0.883344
+ret: 0         st: 1 flags:1 dts: 1.000000 pts: 1.000000 pos:   2048 size:   208
+ret: 0         st: 0 flags:1  ts:-0.222489
+ret: 0         st: 1 flags:1 dts: 1.000000 pts: 1.000000 pos:   2048 size:   208
+ret: 0         st: 1 flags:0  ts: 2.671678
+ret: 0         st: 1 flags:1 dts: 2.018778 pts: 2.018778 pos: 370700 size:   235
+ret: 0         st: 1 flags:1  ts: 1.565844
+ret: 0         st: 1 flags:1 dts: 1.522444 pts: 1.522444 pos: 342028 size:   314
+ret: 0         st:-1 flags:0  ts: 0.460008
+ret: 0         st: 1 flags:1 dts: 1.000000 pts: 1.000000 pos:   2048 size:   208
+ret: 0         st:-1 flags:1  ts:-0.645825
+ret: 0         st: 1 flags:1 dts: 1.000000 pts: 1.000000 pos:   2048 size:   208
diff --git a/tests/ref/seek/lavf.mxf.ref b/tests/ref/seek/lavf_mxf
similarity index 100%
rename from tests/ref/seek/lavf.mxf.ref
rename to tests/ref/seek/lavf_mxf
diff --git a/tests/ref/seek/lavf.mxf_d10.ref b/tests/ref/seek/lavf_mxf_d10
similarity index 100%
rename from tests/ref/seek/lavf.mxf_d10.ref
rename to tests/ref/seek/lavf_mxf_d10
diff --git a/tests/ref/seek/lavf_nut b/tests/ref/seek/lavf_nut
new file mode 100644
index 0000000..a0714f4
--- /dev/null
+++ b/tests/ref/seek/lavf_nut
@@ -0,0 +1,53 @@
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    279 size: 27837
+ret: 0         st:-1 flags:0  ts:-1.000000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    279 size: 27837
+ret: 0         st:-1 flags:1  ts: 1.894167
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146121 size: 27925
+ret: 0         st: 0 flags:0  ts: 0.800000
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146121 size: 27925
+ret: 0         st: 0 flags:1  ts:-0.320000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    279 size: 27837
+ret: 0         st: 1 flags:0  ts: 2.586122
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146121 size: 27925
+ret: 0         st: 1 flags:1  ts: 1.462857
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146121 size: 27925
+ret: 0         st:-1 flags:0  ts: 0.365002
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    279 size: 27837
+ret: 0         st:-1 flags:1  ts:-0.740831
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    279 size: 27837
+ret: 0         st: 0 flags:0  ts: 2.160000
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146121 size: 27925
+ret: 0         st: 0 flags:1  ts: 1.040000
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146121 size: 27925
+ret: 0         st: 1 flags:0  ts:-0.052245
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    279 size: 27837
+ret: 0         st: 1 flags:1  ts: 2.847347
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146121 size: 27925
+ret: 0         st:-1 flags:0  ts: 1.730004
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146121 size: 27925
+ret: 0         st:-1 flags:1  ts: 0.624171
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146121 size: 27925
+ret: 0         st: 0 flags:0  ts:-0.480000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    279 size: 27837
+ret: 0         st: 0 flags:1  ts: 2.400000
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146121 size: 27925
+ret: 0         st: 1 flags:0  ts: 1.306122
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146121 size: 27925
+ret: 0         st: 1 flags:1  ts: 0.208980
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    279 size: 27837
+ret: 0         st:-1 flags:0  ts:-0.904994
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    279 size: 27837
+ret: 0         st:-1 flags:1  ts: 1.989173
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146121 size: 27925
+ret: 0         st: 0 flags:0  ts: 0.880000
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146121 size: 27925
+ret: 0         st: 0 flags:1  ts:-0.240000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    279 size: 27837
+ret: 0         st: 1 flags:0  ts: 2.664490
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146121 size: 27925
+ret: 0         st: 1 flags:1  ts: 1.567347
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146121 size: 27925
+ret: 0         st:-1 flags:0  ts: 0.460008
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146121 size: 27925
+ret: 0         st:-1 flags:1  ts:-0.645825
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    279 size: 27837
diff --git a/tests/ref/seek/lavf.ogg.ref b/tests/ref/seek/lavf_ogg
similarity index 100%
rename from tests/ref/seek/lavf.ogg.ref
rename to tests/ref/seek/lavf_ogg
diff --git a/tests/ref/seek/lavf.rm.ref b/tests/ref/seek/lavf_rm
similarity index 100%
rename from tests/ref/seek/lavf.rm.ref
rename to tests/ref/seek/lavf_rm
diff --git a/tests/ref/seek/lavf.swf.ref b/tests/ref/seek/lavf_swf
similarity index 100%
rename from tests/ref/seek/lavf.swf.ref
rename to tests/ref/seek/lavf_swf
diff --git a/tests/ref/seek/lavf.ts.ref b/tests/ref/seek/lavf_ts
similarity index 100%
rename from tests/ref/seek/lavf.ts.ref
rename to tests/ref/seek/lavf_ts
diff --git a/tests/ref/seek/lavf.ul.ref b/tests/ref/seek/lavf_ul
similarity index 100%
rename from tests/ref/seek/lavf.ul.ref
rename to tests/ref/seek/lavf_ul
diff --git a/tests/ref/seek/lavf.voc.ref b/tests/ref/seek/lavf_voc
similarity index 100%
rename from tests/ref/seek/lavf.voc.ref
rename to tests/ref/seek/lavf_voc
diff --git a/tests/ref/seek/lavf.wav.ref b/tests/ref/seek/lavf_wav
similarity index 100%
rename from tests/ref/seek/lavf.wav.ref
rename to tests/ref/seek/lavf_wav
diff --git a/tests/ref/seek/lavf.y4m.ref b/tests/ref/seek/lavf_y4m
similarity index 100%
rename from tests/ref/seek/lavf.y4m.ref
rename to tests/ref/seek/lavf_y4m
diff --git a/tests/ref/seek/ljpeg.avi.ref b/tests/ref/seek/ljpeg_avi
similarity index 100%
rename from tests/ref/seek/ljpeg.avi.ref
rename to tests/ref/seek/ljpeg_avi
diff --git a/tests/ref/seek/mjpeg.avi.ref b/tests/ref/seek/mjpeg_avi
similarity index 100%
rename from tests/ref/seek/mjpeg.avi.ref
rename to tests/ref/seek/mjpeg_avi
diff --git a/tests/ref/seek/mp2.mp2.ref b/tests/ref/seek/mp2_mp2
similarity index 100%
rename from tests/ref/seek/mp2.mp2.ref
rename to tests/ref/seek/mp2_mp2
diff --git a/tests/ref/seek/mpeg1.mpg.ref b/tests/ref/seek/mpeg1_mpg
similarity index 100%
rename from tests/ref/seek/mpeg1.mpg.ref
rename to tests/ref/seek/mpeg1_mpg
diff --git a/tests/ref/seek/mpeg1b.mpg.ref b/tests/ref/seek/mpeg1b_mpg
similarity index 100%
rename from tests/ref/seek/mpeg1b.mpg.ref
rename to tests/ref/seek/mpeg1b_mpg
diff --git a/tests/ref/seek/mpeg2_422.mpg.ref b/tests/ref/seek/mpeg2_422_mpg
similarity index 100%
rename from tests/ref/seek/mpeg2_422.mpg.ref
rename to tests/ref/seek/mpeg2_422_mpg
diff --git a/tests/ref/seek/mpeg2.mpg.ref b/tests/ref/seek/mpeg2_mpg
similarity index 100%
rename from tests/ref/seek/mpeg2.mpg.ref
rename to tests/ref/seek/mpeg2_mpg
diff --git a/tests/ref/seek/mpeg2i.mpg.ref b/tests/ref/seek/mpeg2i_mpg
similarity index 100%
rename from tests/ref/seek/mpeg2i.mpg.ref
rename to tests/ref/seek/mpeg2i_mpg
diff --git a/tests/ref/seek/mpeg2ivlc-qprd.mpg.ref b/tests/ref/seek/mpeg2ivlc_qprd_mpg
similarity index 100%
rename from tests/ref/seek/mpeg2ivlc-qprd.mpg.ref
rename to tests/ref/seek/mpeg2ivlc_qprd_mpg
diff --git a/tests/ref/seek/mpeg2reuse.mpg.ref b/tests/ref/seek/mpeg2reuse_mpg
similarity index 100%
rename from tests/ref/seek/mpeg2reuse.mpg.ref
rename to tests/ref/seek/mpeg2reuse_mpg
diff --git a/tests/ref/seek/mpeg2thread.mpg.ref b/tests/ref/seek/mpeg2thread_mpg
similarity index 100%
rename from tests/ref/seek/mpeg2thread.mpg.ref
rename to tests/ref/seek/mpeg2thread_mpg
diff --git a/tests/ref/seek/mpeg2threadivlc.mpg.ref b/tests/ref/seek/mpeg2threadivlc_mpg
similarity index 100%
rename from tests/ref/seek/mpeg2threadivlc.mpg.ref
rename to tests/ref/seek/mpeg2threadivlc_mpg
diff --git a/tests/ref/seek/mpeg4-Q.avi.ref b/tests/ref/seek/mpeg4_Q_avi
similarity index 100%
rename from tests/ref/seek/mpeg4-Q.avi.ref
rename to tests/ref/seek/mpeg4_Q_avi
diff --git a/tests/ref/seek/mpeg4-adap.avi.ref b/tests/ref/seek/mpeg4_adap_avi
similarity index 100%
rename from tests/ref/seek/mpeg4-adap.avi.ref
rename to tests/ref/seek/mpeg4_adap_avi
diff --git a/tests/ref/seek/mpeg4-adv.avi.ref b/tests/ref/seek/mpeg4_adv_avi
similarity index 100%
rename from tests/ref/seek/mpeg4-adv.avi.ref
rename to tests/ref/seek/mpeg4_adv_avi
diff --git a/tests/ref/seek/mpeg4-nr.avi.ref b/tests/ref/seek/mpeg4_nr_avi
similarity index 100%
rename from tests/ref/seek/mpeg4-nr.avi.ref
rename to tests/ref/seek/mpeg4_nr_avi
diff --git a/tests/ref/seek/mpeg4-qprd.avi.ref b/tests/ref/seek/mpeg4_qprd_avi
similarity index 100%
rename from tests/ref/seek/mpeg4-qprd.avi.ref
rename to tests/ref/seek/mpeg4_qprd_avi
diff --git a/tests/ref/seek/mpeg4-rc.avi.ref b/tests/ref/seek/mpeg4_rc_avi
similarity index 100%
rename from tests/ref/seek/mpeg4-rc.avi.ref
rename to tests/ref/seek/mpeg4_rc_avi
diff --git a/tests/ref/seek/mpeg4-thread.avi.ref b/tests/ref/seek/mpeg4_thread_avi
similarity index 100%
rename from tests/ref/seek/mpeg4-thread.avi.ref
rename to tests/ref/seek/mpeg4_thread_avi
diff --git a/tests/ref/seek/msmpeg4.avi.ref b/tests/ref/seek/msmpeg4_avi
similarity index 100%
rename from tests/ref/seek/msmpeg4.avi.ref
rename to tests/ref/seek/msmpeg4_avi
diff --git a/tests/ref/seek/msmpeg4v2.avi.ref b/tests/ref/seek/msmpeg4v2_avi
similarity index 100%
rename from tests/ref/seek/msmpeg4v2.avi.ref
rename to tests/ref/seek/msmpeg4v2_avi
diff --git a/tests/ref/seek/odivx.mp4.ref b/tests/ref/seek/odivx_mp4
similarity index 100%
rename from tests/ref/seek/odivx.mp4.ref
rename to tests/ref/seek/odivx_mp4
diff --git a/tests/ref/seek/pbmpipe.pbm.ref b/tests/ref/seek/pbmpipe_pbm
similarity index 100%
rename from tests/ref/seek/pbmpipe.pbm.ref
rename to tests/ref/seek/pbmpipe_pbm
diff --git a/tests/ref/seek/pcm_alaw.wav.ref b/tests/ref/seek/pcm_alaw_wav
similarity index 100%
rename from tests/ref/seek/pcm_alaw.wav.ref
rename to tests/ref/seek/pcm_alaw_wav
diff --git a/tests/ref/seek/pcm_f32be.au.ref b/tests/ref/seek/pcm_f32be_au
similarity index 100%
rename from tests/ref/seek/pcm_f32be.au.ref
rename to tests/ref/seek/pcm_f32be_au
diff --git a/tests/ref/seek/pcm_f32le.wav.ref b/tests/ref/seek/pcm_f32le_wav
similarity index 100%
rename from tests/ref/seek/pcm_f32le.wav.ref
rename to tests/ref/seek/pcm_f32le_wav
diff --git a/tests/ref/seek/pcm_f64be.au.ref b/tests/ref/seek/pcm_f64be_au
similarity index 100%
rename from tests/ref/seek/pcm_f64be.au.ref
rename to tests/ref/seek/pcm_f64be_au
diff --git a/tests/ref/seek/pcm_f64le.wav.ref b/tests/ref/seek/pcm_f64le_wav
similarity index 100%
rename from tests/ref/seek/pcm_f64le.wav.ref
rename to tests/ref/seek/pcm_f64le_wav
diff --git a/tests/ref/seek/pcm_mulaw.wav.ref b/tests/ref/seek/pcm_mulaw_wav
similarity index 100%
rename from tests/ref/seek/pcm_mulaw.wav.ref
rename to tests/ref/seek/pcm_mulaw_wav
diff --git a/tests/ref/seek/pcm_s16be.mkv.ref b/tests/ref/seek/pcm_s16be_mkv
similarity index 100%
rename from tests/ref/seek/pcm_s16be.mkv.ref
rename to tests/ref/seek/pcm_s16be_mkv
diff --git a/tests/ref/seek/pcm_s16be.mov.ref b/tests/ref/seek/pcm_s16be_mov
similarity index 100%
rename from tests/ref/seek/pcm_s16be.mov.ref
rename to tests/ref/seek/pcm_s16be_mov
diff --git a/tests/ref/seek/pcm_s16le.mkv.ref b/tests/ref/seek/pcm_s16le_mkv
similarity index 100%
rename from tests/ref/seek/pcm_s16le.mkv.ref
rename to tests/ref/seek/pcm_s16le_mkv
diff --git a/tests/ref/seek/pcm_s16le.wav.ref b/tests/ref/seek/pcm_s16le_wav
similarity index 100%
rename from tests/ref/seek/pcm_s16le.wav.ref
rename to tests/ref/seek/pcm_s16le_wav
diff --git a/tests/ref/seek/pcm_s24be.mov.ref b/tests/ref/seek/pcm_s24be_mov
similarity index 100%
rename from tests/ref/seek/pcm_s24be.mov.ref
rename to tests/ref/seek/pcm_s24be_mov
diff --git a/tests/ref/seek/pcm_s24daud.302.ref b/tests/ref/seek/pcm_s24daud_302
similarity index 100%
rename from tests/ref/seek/pcm_s24daud.302.ref
rename to tests/ref/seek/pcm_s24daud_302
diff --git a/tests/ref/seek/pcm_s24le.wav.ref b/tests/ref/seek/pcm_s24le_wav
similarity index 100%
rename from tests/ref/seek/pcm_s24le.wav.ref
rename to tests/ref/seek/pcm_s24le_wav
diff --git a/tests/ref/seek/pcm_s32be.mov.ref b/tests/ref/seek/pcm_s32be_mov
similarity index 100%
rename from tests/ref/seek/pcm_s32be.mov.ref
rename to tests/ref/seek/pcm_s32be_mov
diff --git a/tests/ref/seek/pcm_s32le.wav.ref b/tests/ref/seek/pcm_s32le_wav
similarity index 100%
rename from tests/ref/seek/pcm_s32le.wav.ref
rename to tests/ref/seek/pcm_s32le_wav
diff --git a/tests/ref/seek/pcm_s8.mov.ref b/tests/ref/seek/pcm_s8_mov
similarity index 100%
rename from tests/ref/seek/pcm_s8.mov.ref
rename to tests/ref/seek/pcm_s8_mov
diff --git a/tests/ref/seek/pcm_u8.wav.ref b/tests/ref/seek/pcm_u8_wav
similarity index 100%
rename from tests/ref/seek/pcm_u8.wav.ref
rename to tests/ref/seek/pcm_u8_wav
diff --git a/tests/ref/seek/pcm_zork.wav.ref b/tests/ref/seek/pcm_zork_wav
similarity index 100%
rename from tests/ref/seek/pcm_zork.wav.ref
rename to tests/ref/seek/pcm_zork_wav
diff --git a/tests/ref/seek/pgmpipe.pgm.ref b/tests/ref/seek/pgmpipe_pgm
similarity index 100%
rename from tests/ref/seek/pgmpipe.pgm.ref
rename to tests/ref/seek/pgmpipe_pgm
diff --git a/tests/ref/seek/ppmpipe.ppm.ref b/tests/ref/seek/ppmpipe_ppm
similarity index 100%
rename from tests/ref/seek/ppmpipe.ppm.ref
rename to tests/ref/seek/ppmpipe_ppm
diff --git a/tests/ref/seek/rgb_avi b/tests/ref/seek/rgb_avi
new file mode 100644
index 0000000..888032b
--- /dev/null
+++ b/tests/ref/seek/rgb_avi
@@ -0,0 +1,46 @@
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:304128
+ret: 0         st:-1 flags:0  ts:-1.000000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:304128
+ret: 0         st:-1 flags:1  ts: 1.894167
+ret: 0         st: 0 flags:1 dts: 1.880000 pts: 1.880000 pos:14300052 size:304128
+ret: 0         st: 0 flags:0  ts: 0.800000
+ret: 0         st: 0 flags:1 dts: 0.800000 pts: 0.800000 pos:6088380 size:304128
+ret:-1         st: 0 flags:1  ts:-0.320000
+ret:-1         st:-1 flags:0  ts: 2.576668
+ret: 0         st:-1 flags:1  ts: 1.470835
+ret: 0         st: 0 flags:1 dts: 1.480000 pts: 1.480000 pos:11258692 size:304128
+ret: 0         st: 0 flags:0  ts: 0.360000
+ret: 0         st: 0 flags:1 dts: 0.360000 pts: 0.360000 pos:2742884 size:304128
+ret:-1         st: 0 flags:1  ts:-0.760000
+ret:-1         st:-1 flags:0  ts: 2.153336
+ret: 0         st:-1 flags:1  ts: 1.047503
+ret: 0         st: 0 flags:1 dts: 1.040000 pts: 1.040000 pos:7913196 size:304128
+ret: 0         st: 0 flags:0  ts:-0.040000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:304128
+ret: 0         st: 0 flags:1  ts: 2.840000
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:14908324 size:304128
+ret: 0         st:-1 flags:0  ts: 1.730004
+ret: 0         st: 0 flags:1 dts: 1.720000 pts: 1.720000 pos:13083508 size:304128
+ret: 0         st:-1 flags:1  ts: 0.624171
+ret: 0         st: 0 flags:1 dts: 0.640000 pts: 0.640000 pos:4871836 size:304128
+ret: 0         st: 0 flags:0  ts:-0.480000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:304128
+ret: 0         st: 0 flags:1  ts: 2.400000
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:14908324 size:304128
+ret: 0         st:-1 flags:0  ts: 1.306672
+ret: 0         st: 0 flags:1 dts: 1.320000 pts: 1.320000 pos:10042148 size:304128
+ret: 0         st:-1 flags:1  ts: 0.200839
+ret: 0         st: 0 flags:1 dts: 0.200000 pts: 0.200000 pos:1526340 size:304128
+ret: 0         st: 0 flags:0  ts:-0.920000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:304128
+ret: 0         st: 0 flags:1  ts: 2.000000
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:14908324 size:304128
+ret: 0         st:-1 flags:0  ts: 0.883340
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: 0.880000 pos:6696652 size:304128
+ret:-1         st:-1 flags:1  ts:-0.222493
+ret:-1         st: 0 flags:0  ts: 2.680000
+ret: 0         st: 0 flags:1  ts: 1.560000
+ret: 0         st: 0 flags:1 dts: 1.560000 pts: 1.560000 pos:11866964 size:304128
+ret: 0         st:-1 flags:0  ts: 0.460008
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:3655292 size:304128
+ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/roqav.roq.ref b/tests/ref/seek/roqav_roq
similarity index 100%
rename from tests/ref/seek/roqav.roq.ref
rename to tests/ref/seek/roqav_roq
diff --git a/tests/ref/seek/rv10.rm.ref b/tests/ref/seek/rv10_rm
similarity index 100%
rename from tests/ref/seek/rv10.rm.ref
rename to tests/ref/seek/rv10_rm
diff --git a/tests/ref/seek/rv20.rm.ref b/tests/ref/seek/rv20.rm.ref
deleted file mode 100644
index 5b5cb41..0000000
--- a/tests/ref/seek/rv20.rm.ref
+++ /dev/null
@@ -1,53 +0,0 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    239 size:  9361
-ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    239 size:  9361
-ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  84320 size: 11344
-ret: 0         st: 0 flags:0  ts: 0.788000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  53061 size: 10166
-ret: 0         st: 0 flags:1  ts:-0.317000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    239 size:  9361
-ret: 0         st:-1 flags:0  ts: 2.576668
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 119008 size: 11803
-ret: 0         st:-1 flags:1  ts: 1.470835
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  84320 size: 11344
-ret: 0         st: 0 flags:0  ts: 0.365000
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  25990 size:  9101
-ret: 0         st: 0 flags:1  ts:-0.741000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    239 size:  9361
-ret: 0         st:-1 flags:0  ts: 2.153336
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 119008 size: 11803
-ret: 0         st:-1 flags:1  ts: 1.047503
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  53061 size: 10166
-ret: 0         st: 0 flags:0  ts:-0.058000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    239 size:  9361
-ret: 0         st: 0 flags:1  ts: 2.836000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 119008 size: 11803
-ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 119008 size: 11803
-ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  25990 size:  9101
-ret: 0         st: 0 flags:0  ts:-0.482000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    239 size:  9361
-ret: 0         st: 0 flags:1  ts: 2.413000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 119008 size: 11803
-ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  84320 size: 11344
-ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    239 size:  9361
-ret: 0         st: 0 flags:0  ts:-0.905000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    239 size:  9361
-ret: 0         st: 0 flags:1  ts: 1.989000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 119008 size: 11803
-ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  53061 size: 10166
-ret: 0         st:-1 flags:1  ts:-0.222493
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    239 size:  9361
-ret: 0         st: 0 flags:0  ts: 2.672000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 119008 size: 11803
-ret: 0         st: 0 flags:1  ts: 1.566000
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  84320 size: 11344
-ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  25990 size:  9101
-ret: 0         st:-1 flags:1  ts:-0.645825
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    239 size:  9361
diff --git a/tests/ref/seek/rv20_rm b/tests/ref/seek/rv20_rm
new file mode 100644
index 0000000..f2b24e3
--- /dev/null
+++ b/tests/ref/seek/rv20_rm
@@ -0,0 +1,53 @@
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    239 size:  9361
+ret: 0         st:-1 flags:0  ts:-1.000000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    239 size:  9361
+ret: 0         st:-1 flags:1  ts: 1.894167
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  98158 size: 11344
+ret: 0         st: 0 flags:0  ts: 0.788000
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  61133 size: 10166
+ret: 0         st: 0 flags:1  ts:-0.317000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    239 size:  9361
+ret: 0         st:-1 flags:0  ts: 2.576668
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 139145 size: 11803
+ret: 0         st:-1 flags:1  ts: 1.470835
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  98158 size: 11344
+ret: 0         st: 0 flags:0  ts: 0.365000
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  30753 size:  9101
+ret: 0         st: 0 flags:1  ts:-0.741000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    239 size:  9361
+ret: 0         st:-1 flags:0  ts: 2.153336
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 139145 size: 11803
+ret: 0         st:-1 flags:1  ts: 1.047503
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  61133 size: 10166
+ret: 0         st: 0 flags:0  ts:-0.058000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    239 size:  9361
+ret: 0         st: 0 flags:1  ts: 2.836000
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 139145 size: 11803
+ret: 0         st:-1 flags:0  ts: 1.730004
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 139145 size: 11803
+ret: 0         st:-1 flags:1  ts: 0.624171
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  30753 size:  9101
+ret: 0         st: 0 flags:0  ts:-0.482000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    239 size:  9361
+ret: 0         st: 0 flags:1  ts: 2.413000
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 139145 size: 11803
+ret: 0         st:-1 flags:0  ts: 1.306672
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  98158 size: 11344
+ret: 0         st:-1 flags:1  ts: 0.200839
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    239 size:  9361
+ret: 0         st: 0 flags:0  ts:-0.905000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    239 size:  9361
+ret: 0         st: 0 flags:1  ts: 1.989000
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 139145 size: 11803
+ret: 0         st:-1 flags:0  ts: 0.883340
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  61133 size: 10166
+ret: 0         st:-1 flags:1  ts:-0.222493
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    239 size:  9361
+ret: 0         st: 0 flags:0  ts: 2.672000
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 139145 size: 11803
+ret: 0         st: 0 flags:1  ts: 1.566000
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  98158 size: 11344
+ret: 0         st:-1 flags:0  ts: 0.460008
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  30753 size:  9101
+ret: 0         st:-1 flags:1  ts:-0.645825
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    239 size:  9361
diff --git a/tests/ref/seek/snow53.avi.ref b/tests/ref/seek/snow53_avi
similarity index 100%
rename from tests/ref/seek/snow53.avi.ref
rename to tests/ref/seek/snow53_avi
diff --git a/tests/ref/seek/snow.avi.ref b/tests/ref/seek/snow_avi
similarity index 100%
rename from tests/ref/seek/snow.avi.ref
rename to tests/ref/seek/snow_avi
diff --git a/tests/ref/seek/svq1.mov.ref b/tests/ref/seek/svq1_mov
similarity index 100%
rename from tests/ref/seek/svq1.mov.ref
rename to tests/ref/seek/svq1_mov
diff --git a/tests/ref/seek/wmav1.asf.ref b/tests/ref/seek/wmav1.asf.ref
deleted file mode 100644
index a2892b6..0000000
--- a/tests/ref/seek/wmav1.asf.ref
+++ /dev/null
@@ -1,53 +0,0 @@
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    404 size:   743
-ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 3.286000 pts: 3.286000 pos:   3604 size:   743
-ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    404 size:   743
-ret: 0         st: 0 flags:0  ts: 0.788000
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    404 size:   743
-ret: 0         st: 0 flags:1  ts:-0.317000
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    404 size:   743
-ret: 0         st:-1 flags:0  ts: 2.576668
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    404 size:   743
-ret: 0         st:-1 flags:1  ts: 1.470835
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    404 size:   743
-ret: 0         st: 0 flags:0  ts: 0.365000
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    404 size:   743
-ret: 0         st: 0 flags:1  ts:-0.741000
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    404 size:   743
-ret: 0         st:-1 flags:0  ts: 2.153336
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    404 size:   743
-ret: 0         st:-1 flags:1  ts: 1.047503
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    404 size:   743
-ret: 0         st: 0 flags:0  ts:-0.058000
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    404 size:   743
-ret: 0         st: 0 flags:1  ts: 2.836000
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    404 size:   743
-ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    404 size:   743
-ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    404 size:   743
-ret: 0         st: 0 flags:0  ts:-0.482000
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    404 size:   743
-ret: 0         st: 0 flags:1  ts: 2.413000
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    404 size:   743
-ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    404 size:   743
-ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    404 size:   743
-ret: 0         st: 0 flags:0  ts:-0.905000
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    404 size:   743
-ret: 0         st: 0 flags:1  ts: 1.989000
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    404 size:   743
-ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    404 size:   743
-ret: 0         st:-1 flags:1  ts:-0.222493
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    404 size:   743
-ret: 0         st: 0 flags:0  ts: 2.672000
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    404 size:   743
-ret: 0         st: 0 flags:1  ts: 1.566000
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    404 size:   743
-ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    404 size:   743
-ret: 0         st:-1 flags:1  ts:-0.645825
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    404 size:   743
diff --git a/tests/ref/seek/wmav1_asf b/tests/ref/seek/wmav1_asf
new file mode 100644
index 0000000..47c5b46
--- /dev/null
+++ b/tests/ref/seek/wmav1_asf
@@ -0,0 +1,53 @@
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    404 size:   743
+ret: 0         st:-1 flags:0  ts:-1.000000
+ret: 0         st: 0 flags:1 dts: 0.186000 pts: 0.186000 pos:   3604 size:   743
+ret: 0         st:-1 flags:1  ts: 1.894167
+ret: 0         st: 0 flags:1 dts: 1.858000 pts: 1.858000 pos:  32404 size:   743
+ret: 0         st: 0 flags:0  ts: 0.788000
+ret: 0         st: 0 flags:1 dts: 0.929000 pts: 0.929000 pos:  16404 size:   743
+ret: 0         st: 0 flags:1  ts:-0.317000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    404 size:   743
+ret: 0         st:-1 flags:0  ts: 2.576668
+ret: 0         st: 0 flags:1 dts: 2.601000 pts: 2.601000 pos:  45204 size:   743
+ret: 0         st:-1 flags:1  ts: 1.470835
+ret: 0         st: 0 flags:1 dts: 1.300000 pts: 1.300000 pos:  22804 size:   743
+ret: 0         st: 0 flags:0  ts: 0.365000
+ret: 0         st: 0 flags:1 dts: 0.372000 pts: 0.372000 pos:   6804 size:   743
+ret: 0         st: 0 flags:1  ts:-0.741000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    404 size:   743
+ret: 0         st:-1 flags:0  ts: 2.153336
+ret: 0         st: 0 flags:1 dts: 2.229000 pts: 2.229000 pos:  38804 size:   743
+ret: 0         st:-1 flags:1  ts: 1.047503
+ret: 0         st: 0 flags:1 dts: 0.929000 pts: 0.929000 pos:  16404 size:   743
+ret: 0         st: 0 flags:0  ts:-0.058000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    404 size:   743
+ret: 0         st: 0 flags:1  ts: 2.836000
+ret: 0         st: 0 flags:1 dts: 2.786000 pts: 2.786000 pos:  48404 size:   743
+ret: 0         st:-1 flags:0  ts: 1.730004
+ret: 0         st: 0 flags:1 dts: 1.858000 pts: 1.858000 pos:  32404 size:   743
+ret: 0         st:-1 flags:1  ts: 0.624171
+ret: 0         st: 0 flags:1 dts: 0.557000 pts: 0.557000 pos:  10004 size:   743
+ret: 0         st: 0 flags:0  ts:-0.482000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    404 size:   743
+ret: 0         st: 0 flags:1  ts: 2.413000
+ret: 0         st: 0 flags:1 dts: 2.229000 pts: 2.229000 pos:  38804 size:   743
+ret: 0         st:-1 flags:0  ts: 1.306672
+ret: 0         st: 0 flags:1 dts: 1.486000 pts: 1.486000 pos:  26004 size:   743
+ret: 0         st:-1 flags:1  ts: 0.200839
+ret: 0         st: 0 flags:1 dts: 0.186000 pts: 0.186000 pos:   3604 size:   743
+ret: 0         st: 0 flags:0  ts:-0.905000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    404 size:   743
+ret: 0         st: 0 flags:1  ts: 1.989000
+ret: 0         st: 0 flags:1 dts: 1.858000 pts: 1.858000 pos:  32404 size:   743
+ret: 0         st:-1 flags:0  ts: 0.883340
+ret: 0         st: 0 flags:1 dts: 0.929000 pts: 0.929000 pos:  16404 size:   743
+ret: 0         st:-1 flags:1  ts:-0.222493
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    404 size:   743
+ret: 0         st: 0 flags:0  ts: 2.672000
+ret: 0         st: 0 flags:1 dts: 2.786000 pts: 2.786000 pos:  48404 size:   743
+ret: 0         st: 0 flags:1  ts: 1.566000
+ret: 0         st: 0 flags:1 dts: 1.486000 pts: 1.486000 pos:  26004 size:   743
+ret: 0         st:-1 flags:0  ts: 0.460008
+ret: 0         st: 0 flags:1 dts: 0.557000 pts: 0.557000 pos:  10004 size:   743
+ret: 0         st:-1 flags:1  ts:-0.645825
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    404 size:   743
diff --git a/tests/ref/seek/wmav2.asf.ref b/tests/ref/seek/wmav2.asf.ref
deleted file mode 100644
index bd1b79e..0000000
--- a/tests/ref/seek/wmav2.asf.ref
+++ /dev/null
@@ -1,53 +0,0 @@
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    444 size:   743
-ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 3.286000 pts: 3.286000 pos:   3644 size:   743
-ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    444 size:   743
-ret: 0         st: 0 flags:0  ts: 0.788000
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    444 size:   743
-ret: 0         st: 0 flags:1  ts:-0.317000
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    444 size:   743
-ret: 0         st:-1 flags:0  ts: 2.576668
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    444 size:   743
-ret: 0         st:-1 flags:1  ts: 1.470835
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    444 size:   743
-ret: 0         st: 0 flags:0  ts: 0.365000
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    444 size:   743
-ret: 0         st: 0 flags:1  ts:-0.741000
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    444 size:   743
-ret: 0         st:-1 flags:0  ts: 2.153336
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    444 size:   743
-ret: 0         st:-1 flags:1  ts: 1.047503
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    444 size:   743
-ret: 0         st: 0 flags:0  ts:-0.058000
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    444 size:   743
-ret: 0         st: 0 flags:1  ts: 2.836000
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    444 size:   743
-ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    444 size:   743
-ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    444 size:   743
-ret: 0         st: 0 flags:0  ts:-0.482000
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    444 size:   743
-ret: 0         st: 0 flags:1  ts: 2.413000
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    444 size:   743
-ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    444 size:   743
-ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    444 size:   743
-ret: 0         st: 0 flags:0  ts:-0.905000
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    444 size:   743
-ret: 0         st: 0 flags:1  ts: 1.989000
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    444 size:   743
-ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    444 size:   743
-ret: 0         st:-1 flags:1  ts:-0.222493
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    444 size:   743
-ret: 0         st: 0 flags:0  ts: 2.672000
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    444 size:   743
-ret: 0         st: 0 flags:1  ts: 1.566000
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    444 size:   743
-ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    444 size:   743
-ret: 0         st:-1 flags:1  ts:-0.645825
-ret: 0         st: 0 flags:1 dts: 3.100000 pts: 3.100000 pos:    444 size:   743
diff --git a/tests/ref/seek/wmav2_asf b/tests/ref/seek/wmav2_asf
new file mode 100644
index 0000000..7c58da2
--- /dev/null
+++ b/tests/ref/seek/wmav2_asf
@@ -0,0 +1,53 @@
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    444 size:   743
+ret: 0         st:-1 flags:0  ts:-1.000000
+ret: 0         st: 0 flags:1 dts: 0.186000 pts: 0.186000 pos:   3644 size:   743
+ret: 0         st:-1 flags:1  ts: 1.894167
+ret: 0         st: 0 flags:1 dts: 1.858000 pts: 1.858000 pos:  32444 size:   743
+ret: 0         st: 0 flags:0  ts: 0.788000
+ret: 0         st: 0 flags:1 dts: 0.929000 pts: 0.929000 pos:  16444 size:   743
+ret: 0         st: 0 flags:1  ts:-0.317000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    444 size:   743
+ret: 0         st:-1 flags:0  ts: 2.576668
+ret: 0         st: 0 flags:1 dts: 2.601000 pts: 2.601000 pos:  45244 size:   743
+ret: 0         st:-1 flags:1  ts: 1.470835
+ret: 0         st: 0 flags:1 dts: 1.300000 pts: 1.300000 pos:  22844 size:   743
+ret: 0         st: 0 flags:0  ts: 0.365000
+ret: 0         st: 0 flags:1 dts: 0.372000 pts: 0.372000 pos:   6844 size:   743
+ret: 0         st: 0 flags:1  ts:-0.741000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    444 size:   743
+ret: 0         st:-1 flags:0  ts: 2.153336
+ret: 0         st: 0 flags:1 dts: 2.229000 pts: 2.229000 pos:  38844 size:   743
+ret: 0         st:-1 flags:1  ts: 1.047503
+ret: 0         st: 0 flags:1 dts: 0.929000 pts: 0.929000 pos:  16444 size:   743
+ret: 0         st: 0 flags:0  ts:-0.058000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    444 size:   743
+ret: 0         st: 0 flags:1  ts: 2.836000
+ret: 0         st: 0 flags:1 dts: 2.786000 pts: 2.786000 pos:  48444 size:   743
+ret: 0         st:-1 flags:0  ts: 1.730004
+ret: 0         st: 0 flags:1 dts: 1.858000 pts: 1.858000 pos:  32444 size:   743
+ret: 0         st:-1 flags:1  ts: 0.624171
+ret: 0         st: 0 flags:1 dts: 0.557000 pts: 0.557000 pos:  10044 size:   743
+ret: 0         st: 0 flags:0  ts:-0.482000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    444 size:   743
+ret: 0         st: 0 flags:1  ts: 2.413000
+ret: 0         st: 0 flags:1 dts: 2.229000 pts: 2.229000 pos:  38844 size:   743
+ret: 0         st:-1 flags:0  ts: 1.306672
+ret: 0         st: 0 flags:1 dts: 1.486000 pts: 1.486000 pos:  26044 size:   743
+ret: 0         st:-1 flags:1  ts: 0.200839
+ret: 0         st: 0 flags:1 dts: 0.186000 pts: 0.186000 pos:   3644 size:   743
+ret: 0         st: 0 flags:0  ts:-0.905000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    444 size:   743
+ret: 0         st: 0 flags:1  ts: 1.989000
+ret: 0         st: 0 flags:1 dts: 1.858000 pts: 1.858000 pos:  32444 size:   743
+ret: 0         st:-1 flags:0  ts: 0.883340
+ret: 0         st: 0 flags:1 dts: 0.929000 pts: 0.929000 pos:  16444 size:   743
+ret: 0         st:-1 flags:1  ts:-0.222493
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    444 size:   743
+ret: 0         st: 0 flags:0  ts: 2.672000
+ret: 0         st: 0 flags:1 dts: 2.786000 pts: 2.786000 pos:  48444 size:   743
+ret: 0         st: 0 flags:1  ts: 1.566000
+ret: 0         st: 0 flags:1 dts: 1.486000 pts: 1.486000 pos:  26044 size:   743
+ret: 0         st:-1 flags:0  ts: 0.460008
+ret: 0         st: 0 flags:1 dts: 0.557000 pts: 0.557000 pos:  10044 size:   743
+ret: 0         st:-1 flags:1  ts:-0.645825
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    444 size:   743
diff --git a/tests/ref/seek/wmv1.avi.ref b/tests/ref/seek/wmv1_avi
similarity index 100%
rename from tests/ref/seek/wmv1.avi.ref
rename to tests/ref/seek/wmv1_avi
diff --git a/tests/ref/seek/wmv2.avi.ref b/tests/ref/seek/wmv2_avi
similarity index 100%
rename from tests/ref/seek/wmv2.avi.ref
rename to tests/ref/seek/wmv2_avi
diff --git a/tests/ref/seek/yuv_avi b/tests/ref/seek/yuv_avi
new file mode 100644
index 0000000..49c514e
--- /dev/null
+++ b/tests/ref/seek/yuv_avi
@@ -0,0 +1,46 @@
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:152064
+ret: 0         st:-1 flags:0  ts:-1.000000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:152064
+ret: 0         st:-1 flags:1  ts: 1.894167
+ret: 0         st: 0 flags:1 dts: 1.880000 pts: 1.880000 pos:7153044 size:152064
+ret: 0         st: 0 flags:0  ts: 0.800000
+ret: 0         st: 0 flags:1 dts: 0.800000 pts: 0.800000 pos:3047100 size:152064
+ret:-1         st: 0 flags:1  ts:-0.320000
+ret:-1         st:-1 flags:0  ts: 2.576668
+ret: 0         st:-1 flags:1  ts: 1.470835
+ret: 0         st: 0 flags:1 dts: 1.480000 pts: 1.480000 pos:5632324 size:152064
+ret: 0         st: 0 flags:0  ts: 0.360000
+ret: 0         st: 0 flags:1 dts: 0.360000 pts: 0.360000 pos:1374308 size:152064
+ret:-1         st: 0 flags:1  ts:-0.760000
+ret:-1         st:-1 flags:0  ts: 2.153336
+ret: 0         st:-1 flags:1  ts: 1.047503
+ret: 0         st: 0 flags:1 dts: 1.040000 pts: 1.040000 pos:3959532 size:152064
+ret: 0         st: 0 flags:0  ts:-0.040000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:152064
+ret: 0         st: 0 flags:1  ts: 2.840000
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:7457188 size:152064
+ret: 0         st:-1 flags:0  ts: 1.730004
+ret: 0         st: 0 flags:1 dts: 1.720000 pts: 1.720000 pos:6544756 size:152064
+ret: 0         st:-1 flags:1  ts: 0.624171
+ret: 0         st: 0 flags:1 dts: 0.640000 pts: 0.640000 pos:2438812 size:152064
+ret: 0         st: 0 flags:0  ts:-0.480000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:152064
+ret: 0         st: 0 flags:1  ts: 2.400000
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:7457188 size:152064
+ret: 0         st:-1 flags:0  ts: 1.306672
+ret: 0         st: 0 flags:1 dts: 1.320000 pts: 1.320000 pos:5024036 size:152064
+ret: 0         st:-1 flags:1  ts: 0.200839
+ret: 0         st: 0 flags:1 dts: 0.200000 pts: 0.200000 pos: 766020 size:152064
+ret: 0         st: 0 flags:0  ts:-0.920000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:152064
+ret: 0         st: 0 flags:1  ts: 2.000000
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:7457188 size:152064
+ret: 0         st:-1 flags:0  ts: 0.883340
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: 0.880000 pos:3351244 size:152064
+ret:-1         st:-1 flags:1  ts:-0.222493
+ret:-1         st: 0 flags:0  ts: 2.680000
+ret: 0         st: 0 flags:1  ts: 1.560000
+ret: 0         st: 0 flags:1 dts: 1.560000 pts: 1.560000 pos:5936468 size:152064
+ret: 0         st:-1 flags:0  ts: 0.460008
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:1830524 size:152064
+ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/vsynth1/asv1 b/tests/ref/vsynth1/asv1
index 15ba70b..10c1b03 100644
--- a/tests/ref/vsynth1/asv1
+++ b/tests/ref/vsynth1/asv1
@@ -1,4 +1,4 @@
 b4ce4698764ef2328346badb7227ecbe *./tests/data/vsynth1/asv1.avi
 1489656 ./tests/data/vsynth1/asv1.avi
 2dfc5dfc2c1cbbc2543257cd3d2df6af *./tests/data/asv1.vsynth1.out.yuv
-stddev:   20.00 PSNR: 22.11 bytes:  7603200/  7603200
+stddev:   20.00 PSNR: 22.11 MAXDIFF:  158 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth1/asv2 b/tests/ref/vsynth1/asv2
index 4ac42e1..14b0d1c 100644
--- a/tests/ref/vsynth1/asv2
+++ b/tests/ref/vsynth1/asv2
@@ -1,4 +1,4 @@
 dfba6eaf58e515e324c2b370bfcd9158 *./tests/data/vsynth1/asv2.avi
 1456056 ./tests/data/vsynth1/asv2.avi
 d451be09793cd0f35b6d91fc36e2571a *./tests/data/asv2.vsynth1.out.yuv
-stddev:   18.82 PSNR: 22.63 bytes:  7603200/  7603200
+stddev:   18.82 PSNR: 22.63 MAXDIFF:  131 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth1/dnxhd_1080i b/tests/ref/vsynth1/dnxhd_1080i
index 7429b7d..654242c 100644
--- a/tests/ref/vsynth1/dnxhd_1080i
+++ b/tests/ref/vsynth1/dnxhd_1080i
@@ -1,4 +1,4 @@
-cd1489f18d2186a49ab23c61ed33bce7 *./tests/data/vsynth1/dnxhd-1080i.mov
+8a814d4056ca2810a8ed0bad3b70f358 *./tests/data/vsynth1/dnxhd-1080i.mov
 3031875 ./tests/data/vsynth1/dnxhd-1080i.mov
 0c651e840f860592f0d5b66030d9fa32 *./tests/data/dnxhd_1080i.vsynth1.out.yuv
-stddev:    6.29 PSNR: 32.15 bytes:   760320/  7603200
+stddev:    6.29 PSNR: 32.15 MAXDIFF:   64 bytes:   760320/  7603200
diff --git a/tests/ref/vsynth1/dnxhd_720p b/tests/ref/vsynth1/dnxhd_720p
index 490a9ea..263843d 100644
--- a/tests/ref/vsynth1/dnxhd_720p
+++ b/tests/ref/vsynth1/dnxhd_720p
@@ -1,4 +1,4 @@
 81f5be451dc18cf8a1d333c7885de60b *./tests/data/vsynth1/dnxhd-720p.dnxhd
 2293760 ./tests/data/vsynth1/dnxhd-720p.dnxhd
 94b21e5e68ccf9471eff74afd0ebe319 *./tests/data/dnxhd_720p.vsynth1.out.yuv
-stddev:    6.32 PSNR: 32.11 bytes:   760320/  7603200
+stddev:    6.32 PSNR: 32.11 MAXDIFF:  183 bytes:   760320/  7603200
diff --git a/tests/ref/vsynth1/dnxhd_720p_rd b/tests/ref/vsynth1/dnxhd_720p_rd
index f18ae2d..e77c725 100644
--- a/tests/ref/vsynth1/dnxhd_720p_rd
+++ b/tests/ref/vsynth1/dnxhd_720p_rd
@@ -1,4 +1,4 @@
 1dc6e95925c4f3a230848ec17c02abed *./tests/data/vsynth1/dnxhd-720p-rd.dnxhd
 2293760 ./tests/data/vsynth1/dnxhd-720p-rd.dnxhd
 02972d2aec120ec1577ec9053d68ae0f *./tests/data/dnxhd_720p_rd.vsynth1.out.yuv
-stddev:    6.26 PSNR: 32.19 bytes:   760320/  7603200
+stddev:    6.26 PSNR: 32.19 MAXDIFF:   65 bytes:   760320/  7603200
diff --git a/tests/ref/vsynth1/dv b/tests/ref/vsynth1/dv
index 7b6f1f9..cb0427c 100644
--- a/tests/ref/vsynth1/dv
+++ b/tests/ref/vsynth1/dv
@@ -1,8 +1,8 @@
 27ade3031b17214cf81c19cbf70f37d7 *./tests/data/vsynth1/dv.dv
 7200000 ./tests/data/vsynth1/dv.dv
 02ac7cdeab91d4d5621e7ce96dddc498 *./tests/data/dv.vsynth1.out.yuv
-stddev:    6.90 PSNR: 31.34 bytes:  7603200/  7603200
+stddev:    6.90 PSNR: 31.34 MAXDIFF:   76 bytes:  7603200/  7603200
 bd67f2431db160d4bb6dcd791cea6efd *./tests/data/vsynth1/dv411.dv
 7200000 ./tests/data/vsynth1/dv411.dv
 b6640a3a572353f51284acb746eb00c4 *./tests/data/dv.vsynth1.out.yuv
-stddev:   30.76 PSNR: 18.37 bytes:  7603200/  7603200
+stddev:   30.76 PSNR: 18.37 MAXDIFF:  205 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth1/dv50 b/tests/ref/vsynth1/dv50
index 1e6454d..9ae3385 100644
--- a/tests/ref/vsynth1/dv50
+++ b/tests/ref/vsynth1/dv50
@@ -1,4 +1,4 @@
 26dba84f0ea895b914ef5b333d8394ac *./tests/data/vsynth1/dv50.dv
 14400000 ./tests/data/vsynth1/dv50.dv
 a2ff093e93ffed10f730fa21df02fc50 *./tests/data/dv50.vsynth1.out.yuv
-stddev:    1.72 PSNR: 43.38 bytes:  7603200/  7603200
+stddev:    1.72 PSNR: 43.38 MAXDIFF:   29 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth1/error b/tests/ref/vsynth1/error
index 6b8a49e..c3543f9 100644
--- a/tests/ref/vsynth1/error
+++ b/tests/ref/vsynth1/error
@@ -1,4 +1,4 @@
 7416dfd319f04044d4575dc9d1b406e1 *./tests/data/vsynth1/error-mpeg4-adv.avi
 756836 ./tests/data/vsynth1/error-mpeg4-adv.avi
 ef8bfcd6e0883daba95d0f32486ebe2d *./tests/data/error.vsynth1.out.yuv
-stddev:   18.05 PSNR: 23.00 bytes:  7603200/  7603200
+stddev:   18.05 PSNR: 23.00 MAXDIFF:  245 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth1/ffv1 b/tests/ref/vsynth1/ffv1
index e888d96..bf90915 100644
--- a/tests/ref/vsynth1/ffv1
+++ b/tests/ref/vsynth1/ffv1
@@ -1,4 +1,4 @@
 67ddc7edde5cca49290245d881787890 *./tests/data/vsynth1/ffv1.avi
 2655376 ./tests/data/vsynth1/ffv1.avi
 c5ccac874dbf808e9088bc3107860042 *./tests/data/ffv1.vsynth1.out.yuv
-stddev:    0.00 PSNR:999.99 bytes:  7603200/  7603200
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth1/flashsv b/tests/ref/vsynth1/flashsv
index 6d76e9a..7920193 100644
--- a/tests/ref/vsynth1/flashsv
+++ b/tests/ref/vsynth1/flashsv
@@ -1,4 +1,4 @@
 97894502b4cb57aca1105b6333f72dae *./tests/data/vsynth1/flashsv.flv
 14681925 ./tests/data/vsynth1/flashsv.flv
 947cb24ec45a453348ae6fe3fa278071 *./tests/data/flashsv.vsynth1.out.yuv
-stddev:    2.85 PSNR: 39.03 bytes:  7603200/  7603200
+stddev:    2.85 PSNR: 39.03 MAXDIFF:   49 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth1/flv b/tests/ref/vsynth1/flv
index 04e22eb..17f5656 100644
--- a/tests/ref/vsynth1/flv
+++ b/tests/ref/vsynth1/flv
@@ -1,4 +1,4 @@
 d6a80659cedee7698aefe9c4a8285fa4 *./tests/data/vsynth1/flv.flv
 636269 ./tests/data/vsynth1/flv.flv
 5ab46d8dd01dbb1d63df2a84858a4b05 *./tests/data/flv.vsynth1.out.yuv
-stddev:    8.02 PSNR: 30.04 bytes:  7603200/  7603200
+stddev:    8.02 PSNR: 30.04 MAXDIFF:  105 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth1/h261 b/tests/ref/vsynth1/h261
index 2be9855..36d04f1 100644
--- a/tests/ref/vsynth1/h261
+++ b/tests/ref/vsynth1/h261
@@ -1,4 +1,4 @@
 d155470b713aeebacb85980b0d5f2ce3 *./tests/data/vsynth1/h261.avi
 707588 ./tests/data/vsynth1/h261.avi
 716e83cb51afb1246bfaa80967df48ea *./tests/data/h261.vsynth1.out.yuv
-stddev:    9.11 PSNR: 28.93 bytes:  7603200/  7603200
+stddev:    9.11 PSNR: 28.93 MAXDIFF:  113 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth1/h263 b/tests/ref/vsynth1/h263
index 5703029..6351adc 100644
--- a/tests/ref/vsynth1/h263
+++ b/tests/ref/vsynth1/h263
@@ -1,4 +1,4 @@
 fb4dc9b9eac2628c56cb82cf332e1f58 *./tests/data/vsynth1/h263.avi
 659686 ./tests/data/vsynth1/h263.avi
 1a1ba9a3a63ec1a1a9585fded0a7c954 *./tests/data/h263.vsynth1.out.yuv
-stddev:    8.03 PSNR: 30.03 bytes:  7603200/  7603200
+stddev:    8.03 PSNR: 30.03 MAXDIFF:  103 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth1/h263p b/tests/ref/vsynth1/h263p
index 6ca658f..93df549 100644
--- a/tests/ref/vsynth1/h263p
+++ b/tests/ref/vsynth1/h263p
@@ -1,4 +1,4 @@
 bbcadeceba295e1dad148aea1e57c370 *./tests/data/vsynth1/h263p.avi
 2328348 ./tests/data/vsynth1/h263p.avi
 9554cda00c3487ab3ffda2c3ea22fa2f *./tests/data/h263p.vsynth1.out.yuv
-stddev:    2.06 PSNR: 41.83 bytes:  7603200/  7603200
+stddev:    2.06 PSNR: 41.83 MAXDIFF:   20 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth1/huffyuv b/tests/ref/vsynth1/huffyuv
index f84eee4..fefc84a 100644
--- a/tests/ref/vsynth1/huffyuv
+++ b/tests/ref/vsynth1/huffyuv
@@ -1,4 +1,4 @@
 ace2536fa169d835d0fb332abde28d51 *./tests/data/vsynth1/huffyuv.avi
 7933800 ./tests/data/vsynth1/huffyuv.avi
 c5ccac874dbf808e9088bc3107860042 *./tests/data/huffyuv.vsynth1.out.yuv
-stddev:    0.00 PSNR:999.99 bytes:  7603200/  7603200
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth1/jpegls b/tests/ref/vsynth1/jpegls
index 4e26ec6..636f7fc 100644
--- a/tests/ref/vsynth1/jpegls
+++ b/tests/ref/vsynth1/jpegls
@@ -1,4 +1,4 @@
 519e26bb1ac0f3db8f90b36537f2f760 *./tests/data/vsynth1/jpegls.avi
 9089812 ./tests/data/vsynth1/jpegls.avi
 947cb24ec45a453348ae6fe3fa278071 *./tests/data/jpegls.vsynth1.out.yuv
-stddev:    2.85 PSNR: 39.03 bytes:  7603200/  7603200
+stddev:    2.85 PSNR: 39.03 MAXDIFF:   49 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth1/ljpeg b/tests/ref/vsynth1/ljpeg
index 3202bfc..01d59e7 100644
--- a/tests/ref/vsynth1/ljpeg
+++ b/tests/ref/vsynth1/ljpeg
@@ -1,4 +1,4 @@
 9092f306f165b98ab0bb4f576f198ad5 *./tests/data/vsynth1/ljpeg.avi
 6312936 ./tests/data/vsynth1/ljpeg.avi
 c5ccac874dbf808e9088bc3107860042 *./tests/data/ljpeg.vsynth1.out.yuv
-stddev:    0.00 PSNR:999.99 bytes:  7603200/  7603200
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth1/mjpeg b/tests/ref/vsynth1/mjpeg
index fe54d6f..63a0ff0 100644
--- a/tests/ref/vsynth1/mjpeg
+++ b/tests/ref/vsynth1/mjpeg
@@ -1,4 +1,4 @@
 8bbf9513b1822945539f27a6eff3c7fa *./tests/data/vsynth1/mjpeg.avi
 1516140 ./tests/data/vsynth1/mjpeg.avi
 c6ae81b5b896e4d05ff584311aebdb18 *./tests/data/mjpeg.vsynth1.out.yuv
-stddev:    7.87 PSNR: 30.21 bytes:  7603200/  7603200
+stddev:    7.87 PSNR: 30.21 MAXDIFF:   63 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth1/mpeg b/tests/ref/vsynth1/mpeg
index 882486b..7ae92f1 100644
--- a/tests/ref/vsynth1/mpeg
+++ b/tests/ref/vsynth1/mpeg
@@ -1,4 +1,4 @@
 1428744c6d5835f27506e69be4f837f4 *./tests/data/vsynth1/mpeg1.mpg
 712006 ./tests/data/vsynth1/mpeg1.mpg
 58f0c332bf689117b57fa629a2bc0d2b *./tests/data/mpeg.vsynth1.out.yuv
-stddev:    7.62 PSNR: 30.48 bytes:  7603200/  7603200
+stddev:    7.62 PSNR: 30.48 MAXDIFF:   84 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth1/mpeg1b b/tests/ref/vsynth1/mpeg1b
index 913515e..897a0ce 100644
--- a/tests/ref/vsynth1/mpeg1b
+++ b/tests/ref/vsynth1/mpeg1b
@@ -1,4 +1,4 @@
 777639666b449ab0a7ef260511e40532 *./tests/data/vsynth1/mpeg1b.mpg
 1030337 ./tests/data/vsynth1/mpeg1b.mpg
 91a7fce732b34748e7bf753ebabe2483 *./tests/data/mpeg1b.vsynth1.out.yuv
-stddev:    6.30 PSNR: 32.13 bytes:  7603200/  7603200
+stddev:    6.30 PSNR: 32.13 MAXDIFF:   75 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth1/mpeg2 b/tests/ref/vsynth1/mpeg2
index 7269080..e6d404d 100644
--- a/tests/ref/vsynth1/mpeg2
+++ b/tests/ref/vsynth1/mpeg2
@@ -1,20 +1,20 @@
 fbddea2368cd2028fc8db4dfd4682e94 *./tests/data/vsynth1/mpeg2.mpg
 728044 ./tests/data/vsynth1/mpeg2.mpg
 b41ca49c1a02e66ce64d262e2cdaec15 *./tests/data/mpeg2.vsynth1.out.yuv
-stddev:    7.65 PSNR: 30.45 bytes:  7603200/  7603200
+stddev:    7.65 PSNR: 30.45 MAXDIFF:   84 bytes:  7603200/  7603200
 8f6b20714918e6443e0c03716ed06f0d *./tests/data/vsynth1/mpeg2ivlc-qprd.mpg
 783552 ./tests/data/vsynth1/mpeg2ivlc-qprd.mpg
 98eb9da15f880978e7f2ee1e7ce476ef *./tests/data/mpeg2.vsynth1.out.yuv
-stddev:   10.07 PSNR: 28.06 bytes:  7603200/  7603200
+stddev:   10.07 PSNR: 28.06 MAXDIFF:  165 bytes:  7603200/  7603200
 af0cb75451aaa807beb5102707a98823 *./tests/data/vsynth1/mpeg2_422.mpg
 728200 ./tests/data/vsynth1/mpeg2_422.mpg
 29b518282493203e83b27a939795dc3a *./tests/data/mpeg2.vsynth1.out.yuv
-stddev:   63.33 PSNR: 12.10 bytes: 10137600/  7603200
+stddev:   63.33 PSNR: 12.10 MAXDIFF:  242 bytes: 10137600/  7603200
 4c067397b504d65532d7779cd36f3f88 *./tests/data/vsynth1/mpeg2.mpg
 725668 ./tests/data/vsynth1/mpeg2.mpg
 9f7b065f98d57cdecf90e6f7a2524eb5 *./tests/data/mpeg2.vsynth1.out.yuv
-stddev:    7.65 PSNR: 30.45 bytes:  7603200/  7603200
+stddev:    7.65 PSNR: 30.45 MAXDIFF:   81 bytes:  7603200/  7603200
 ec3f6713c88a2b41f6c369fd64341077 *./tests/data/vsynth1/mpeg2i.mpg
 737473 ./tests/data/vsynth1/mpeg2i.mpg
 97615390fdd69abfcbc7e02df863a7d2 *./tests/data/mpeg2.vsynth1.out.yuv
-stddev:    7.67 PSNR: 30.43 bytes:  7603200/  7603200
+stddev:    7.67 PSNR: 30.43 MAXDIFF:   84 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth1/mpeg2thread b/tests/ref/vsynth1/mpeg2thread
index c2e2c4f..470c2e9 100644
--- a/tests/ref/vsynth1/mpeg2thread
+++ b/tests/ref/vsynth1/mpeg2thread
@@ -1,12 +1,12 @@
 ecd183706688bd977c9994c3d1b23d61 *./tests/data/vsynth1/mpeg2thread.mpg
 801313 ./tests/data/vsynth1/mpeg2thread.mpg
 d1658911ca83f5616c1d32abc40750de *./tests/data/mpeg2thread.vsynth1.out.yuv
-stddev:    7.63 PSNR: 30.48 bytes:  7603200/  7603200
+stddev:    7.63 PSNR: 30.48 MAXDIFF:  110 bytes:  7603200/  7603200
 23d600b026222253c2340e23300a4c02 *./tests/data/vsynth1/mpeg2threadivlc.mpg
 791773 ./tests/data/vsynth1/mpeg2threadivlc.mpg
 d1658911ca83f5616c1d32abc40750de *./tests/data/mpeg2thread.vsynth1.out.yuv
-stddev:    7.63 PSNR: 30.48 bytes:  7603200/  7603200
+stddev:    7.63 PSNR: 30.48 MAXDIFF:  110 bytes:  7603200/  7603200
 d119fe917dd81d1ff758b4ce684a8d9d *./tests/data/vsynth1/mpeg2reuse.mpg
 2074636 ./tests/data/vsynth1/mpeg2reuse.mpg
 92ced6afe8c02304943c400cce51a5f4 *./tests/data/mpeg2thread.vsynth1.out.yuv
-stddev:    7.66 PSNR: 30.44 bytes:  7603200/  7603200
+stddev:    7.66 PSNR: 30.44 MAXDIFF:  111 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth1/mpeg4 b/tests/ref/vsynth1/mpeg4
index 3156fed..76b3904 100644
--- a/tests/ref/vsynth1/mpeg4
+++ b/tests/ref/vsynth1/mpeg4
@@ -1,4 +1,4 @@
 fd83f2ef5887a62b4d755d7cb5f0ac59 *./tests/data/vsynth1/odivx.mp4
 540144 ./tests/data/vsynth1/odivx.mp4
 8828a375448dc5c2215163ba70656f89 *./tests/data/mpeg4.vsynth1.out.yuv
-stddev:    7.97 PSNR: 30.10 bytes:  7603200/  7603200
+stddev:    7.97 PSNR: 30.10 MAXDIFF:  105 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth1/mpeg4adv b/tests/ref/vsynth1/mpeg4adv
index bbd996b..d614310 100644
--- a/tests/ref/vsynth1/mpeg4adv
+++ b/tests/ref/vsynth1/mpeg4adv
@@ -1,16 +1,16 @@
 7d8eb01fd68d83d62a98585757704d47 *./tests/data/vsynth1/mpeg4-adv.avi
 589716 ./tests/data/vsynth1/mpeg4-adv.avi
 f8b226876b1b2c0b98fd6928fd9adbd8 *./tests/data/mpeg4adv.vsynth1.out.yuv
-stddev:    6.98 PSNR: 31.25 bytes:  7603200/  7603200
+stddev:    6.98 PSNR: 31.25 MAXDIFF:   84 bytes:  7603200/  7603200
 d6b7e724a6ad66ab5e4c5a499218b40d *./tests/data/vsynth1/mpeg4-qprd.avi
 710944 ./tests/data/vsynth1/mpeg4-qprd.avi
 e65f4c7f343fe2bad1cac44b7da5f7c4 *./tests/data/mpeg4adv.vsynth1.out.yuv
-stddev:    9.79 PSNR: 28.31 bytes:  7603200/  7603200
+stddev:    9.79 PSNR: 28.31 MAXDIFF:  176 bytes:  7603200/  7603200
 2d870c0da9ab2231ab5fc06981e70399 *./tests/data/vsynth1/mpeg4-adap.avi
 403456 ./tests/data/vsynth1/mpeg4-adap.avi
 fa2049396479b5f170aa764fed5b2a31 *./tests/data/mpeg4adv.vsynth1.out.yuv
-stddev:   14.05 PSNR: 25.17 bytes:  7603200/  7603200
+stddev:   14.05 PSNR: 25.17 MAXDIFF:  184 bytes:  7603200/  7603200
 3bf17c3d04f52988386ce106a2a58976 *./tests/data/vsynth1/mpeg4-Q.avi
 860678 ./tests/data/vsynth1/mpeg4-Q.avi
 756928496245ecc701f79eebeec8e5e6 *./tests/data/mpeg4adv.vsynth1.out.yuv
-stddev:    5.63 PSNR: 33.12 bytes:  7603200/  7603200
+stddev:    5.63 PSNR: 33.12 MAXDIFF:   70 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth1/mpeg4nr b/tests/ref/vsynth1/mpeg4nr
index 24ed8de..c821490 100644
--- a/tests/ref/vsynth1/mpeg4nr
+++ b/tests/ref/vsynth1/mpeg4nr
@@ -1,4 +1,4 @@
 c02f54157ba08ca12ad979c6308212ad *./tests/data/vsynth1/mpeg4-nr.avi
 675638 ./tests/data/vsynth1/mpeg4-nr.avi
 d2b89d5958fb7331f6c9e5b7ecaaa5b6 *./tests/data/mpeg4nr.vsynth1.out.yuv
-stddev:    6.99 PSNR: 31.23 bytes:  7603200/  7603200
+stddev:    6.99 PSNR: 31.23 MAXDIFF:   86 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth1/mpeg4thread b/tests/ref/vsynth1/mpeg4thread
index d8e06fe..d04f436 100644
--- a/tests/ref/vsynth1/mpeg4thread
+++ b/tests/ref/vsynth1/mpeg4thread
@@ -1,4 +1,4 @@
 4f4ea04faad7212374919aa1ec7ff994 *./tests/data/vsynth1/mpeg4-thread.avi
 774760 ./tests/data/vsynth1/mpeg4-thread.avi
 64b96cddf5301990e118978b3a3bcd0d *./tests/data/mpeg4thread.vsynth1.out.yuv
-stddev:   10.13 PSNR: 28.02 bytes:  7603200/  7603200
+stddev:   10.13 PSNR: 28.02 MAXDIFF:  183 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth1/msmpeg4 b/tests/ref/vsynth1/msmpeg4
index 46b72f1..d94d3f0 100644
--- a/tests/ref/vsynth1/msmpeg4
+++ b/tests/ref/vsynth1/msmpeg4
@@ -1,4 +1,4 @@
-d437c6ab3775c50fdec00fa744bb5add *./tests/data/vsynth1/msmpeg4.avi
+4b08952b0afceb17ee3db31b67f6b778 *./tests/data/vsynth1/msmpeg4.avi
 624718 ./tests/data/vsynth1/msmpeg4.avi
 5ca72c39e3fc5df8e62f223c869589f5 *./tests/data/msmpeg4.vsynth1.out.yuv
-stddev:    7.98 PSNR: 30.09 bytes:  7603200/  7603200
+stddev:    7.98 PSNR: 30.09 MAXDIFF:  104 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth1/msmpeg4v2 b/tests/ref/vsynth1/msmpeg4v2
index 69bd62f..dde152d 100644
--- a/tests/ref/vsynth1/msmpeg4v2
+++ b/tests/ref/vsynth1/msmpeg4v2
@@ -1,4 +1,4 @@
 88957e35efcc718bce0307627ad3298d *./tests/data/vsynth1/msmpeg4v2.avi
 623788 ./tests/data/vsynth1/msmpeg4v2.avi
 c6ff1041a0ef62c2a2e5ef519e5e94c4 *./tests/data/msmpeg4v2.vsynth1.out.yuv
-stddev:    7.97 PSNR: 30.10 bytes:  7603200/  7603200
+stddev:    7.97 PSNR: 30.10 MAXDIFF:  105 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth1/qtrle b/tests/ref/vsynth1/qtrle
new file mode 100644
index 0000000..9988897
--- /dev/null
+++ b/tests/ref/vsynth1/qtrle
@@ -0,0 +1,4 @@
+d14041925ce5ec5001dc519276b1a1ab *./tests/data/vsynth1/qtrle.mov
+15263232 ./tests/data/vsynth1/qtrle.mov
+243325fb2cae1a9245efd49aff936327 *./tests/data/qtrle.vsynth1.out.yuv
+stddev:    3.42 PSNR: 37.43 MAXDIFF:   48 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth1/rc b/tests/ref/vsynth1/rc
index cf852a8..be50952 100644
--- a/tests/ref/vsynth1/rc
+++ b/tests/ref/vsynth1/rc
@@ -1,4 +1,4 @@
 1c6dadf75f60f4ba59a0fe0b6eaedf57 *./tests/data/vsynth1/mpeg4-rc.avi
 830160 ./tests/data/vsynth1/mpeg4-rc.avi
 4d95e340db9bc57a559162c039f3784e *./tests/data/rc.vsynth1.out.yuv
-stddev:   10.24 PSNR: 27.92 bytes:  7603200/  7603200
+stddev:   10.24 PSNR: 27.92 MAXDIFF:  196 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth1/rgb b/tests/ref/vsynth1/rgb
new file mode 100644
index 0000000..10a0a13
--- /dev/null
+++ b/tests/ref/vsynth1/rgb
@@ -0,0 +1,4 @@
+05f0719cb52486d9a4beb9cfae3f2571 *./tests/data/vsynth1/rgb.avi
+15213260 ./tests/data/vsynth1/rgb.avi
+243325fb2cae1a9245efd49aff936327 *./tests/data/rgb.vsynth1.out.yuv
+stddev:    3.42 PSNR: 37.43 MAXDIFF:   48 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth1/roq b/tests/ref/vsynth1/roq
index 086ae1c..42456e4 100644
--- a/tests/ref/vsynth1/roq
+++ b/tests/ref/vsynth1/roq
@@ -1,4 +1,4 @@
 cf8b7b0e539bab3169c234ca63d71dd8 *./tests/data/vsynth1/roqav.roq
 101671 ./tests/data/vsynth1/roqav.roq
 0ad983c291b1ed373645c5b12a108c61 *./tests/data/roq.vsynth1.out.yuv
-stddev:    7.74 PSNR: 30.35 bytes:   760320/  7603200
+stddev:    7.74 PSNR: 30.35 MAXDIFF:   89 bytes:   760320/  7603200
diff --git a/tests/ref/vsynth1/rv10 b/tests/ref/vsynth1/rv10
index 7cd50d1..9e0ceec 100644
--- a/tests/ref/vsynth1/rv10
+++ b/tests/ref/vsynth1/rv10
@@ -1,4 +1,4 @@
 4d7e82de72a83905cf84b8abc3e70b8f *./tests/data/vsynth1/rv10.rm
 653905 ./tests/data/vsynth1/rv10.rm
 1a1ba9a3a63ec1a1a9585fded0a7c954 *./tests/data/rv10.vsynth1.out.yuv
-stddev:    8.03 PSNR: 30.03 bytes:  7603200/  7603200
+stddev:    8.03 PSNR: 30.03 MAXDIFF:  103 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth1/rv20 b/tests/ref/vsynth1/rv20
index d8cc2cc..d3b8814 100644
--- a/tests/ref/vsynth1/rv20
+++ b/tests/ref/vsynth1/rv20
@@ -1,4 +1,4 @@
-49f656b3a84bd7173ca219fae310750c *./tests/data/vsynth1/rv20.rm
-627450 ./tests/data/vsynth1/rv20.rm
-a94d2babdc506b95951977cb55642981 *./tests/data/rv20.vsynth1.out.yuv
-stddev:    8.24 PSNR: 29.81 bytes:  7603200/  7603200
+81868601e602eee5b6d80f5ece4aaa98 *./tests/data/vsynth1/rv20.rm
+646016 ./tests/data/vsynth1/rv20.rm
+b45fdb0201b06f7649f44050e262c54c *./tests/data/rv20.vsynth1.out.yuv
+stddev:    8.26 PSNR: 29.79 MAXDIFF:  103 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth1/snow b/tests/ref/vsynth1/snow
index 9178115..ac34760 100644
--- a/tests/ref/vsynth1/snow
+++ b/tests/ref/vsynth1/snow
@@ -1,4 +1,4 @@
 d593b3c1a9729ce6dd1721f58fa93712 *./tests/data/vsynth1/snow.avi
 136088 ./tests/data/vsynth1/snow.avi
 91021b7d6d7908648fe78cc1975af8c4 *./tests/data/snow.vsynth1.out.yuv
-stddev:   22.77 PSNR: 20.98 bytes:  7603200/  7603200
+stddev:   22.77 PSNR: 20.98 MAXDIFF:  172 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth1/snowll b/tests/ref/vsynth1/snowll
index 0246038..427e52d 100644
--- a/tests/ref/vsynth1/snowll
+++ b/tests/ref/vsynth1/snowll
@@ -1,4 +1,4 @@
 6d29e8c06a645cdee45073c4f3d0004e *./tests/data/vsynth1/snow53.avi
 3419980 ./tests/data/vsynth1/snow53.avi
 c5ccac874dbf808e9088bc3107860042 *./tests/data/snowll.vsynth1.out.yuv
-stddev:    0.00 PSNR:999.99 bytes:  7603200/  7603200
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth1/svq1 b/tests/ref/vsynth1/svq1
index b6c95ea..8c647c7 100644
--- a/tests/ref/vsynth1/svq1
+++ b/tests/ref/vsynth1/svq1
@@ -1,4 +1,4 @@
 595fc4e38734521356b60e67b813f0fa *./tests/data/vsynth1/svq1.mov
 1334367 ./tests/data/vsynth1/svq1.mov
 9cc35c54b2c77d36bd7e308b393c1f81 *./tests/data/svq1.vsynth1.out.yuv
-stddev:    9.58 PSNR: 28.50 bytes:  7603200/  7603200
+stddev:    9.58 PSNR: 28.50 MAXDIFF:  210 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth1/wmv1 b/tests/ref/vsynth1/wmv1
index 891c88b..8c32ea8 100644
--- a/tests/ref/vsynth1/wmv1
+++ b/tests/ref/vsynth1/wmv1
@@ -1,4 +1,4 @@
 4f3461315776e5118866fa3819cff9b6 *./tests/data/vsynth1/wmv1.avi
 626908 ./tests/data/vsynth1/wmv1.avi
 5182edba5b5e0354b39ce4f3604b62da *./tests/data/wmv1.vsynth1.out.yuv
-stddev:    7.97 PSNR: 30.09 bytes:  7603200/  7603200
+stddev:    7.97 PSNR: 30.09 MAXDIFF:  110 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth1/wmv2 b/tests/ref/vsynth1/wmv2
index 2e72290..8e1e88d 100644
--- a/tests/ref/vsynth1/wmv2
+++ b/tests/ref/vsynth1/wmv2
@@ -1,4 +1,4 @@
 13efda9d3811345aadc0632fc9a9332b *./tests/data/vsynth1/wmv2.avi
 659852 ./tests/data/vsynth1/wmv2.avi
 5182edba5b5e0354b39ce4f3604b62da *./tests/data/wmv2.vsynth1.out.yuv
-stddev:    7.97 PSNR: 30.09 bytes:  7603200/  7603200
+stddev:    7.97 PSNR: 30.09 MAXDIFF:  110 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth1/yuv b/tests/ref/vsynth1/yuv
new file mode 100644
index 0000000..b98dda5
--- /dev/null
+++ b/tests/ref/vsynth1/yuv
@@ -0,0 +1,4 @@
+aa6b9e862aebcf8902a6d770e7729d59 *./tests/data/vsynth1/yuv.avi
+7610060 ./tests/data/vsynth1/yuv.avi
+c5ccac874dbf808e9088bc3107860042 *./tests/data/yuv.vsynth1.out.yuv
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth2/asv1 b/tests/ref/vsynth2/asv1
index a584645..1d0385c 100644
--- a/tests/ref/vsynth2/asv1
+++ b/tests/ref/vsynth2/asv1
@@ -1,4 +1,4 @@
 4eb34d2de25f67a2706456e999338fe9 *./tests/data/vsynth2/asv1.avi
 832512 ./tests/data/vsynth2/asv1.avi
 c96ff7fd17c52f99ddb7922a4cb9168f *./tests/data/asv1.vsynth2.out.yuv
-stddev:   10.47 PSNR: 27.73 bytes:  7603200/  7603200
+stddev:   10.47 PSNR: 27.73 MAXDIFF:   98 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth2/asv2 b/tests/ref/vsynth2/asv2
index b898420..21ce40a 100644
--- a/tests/ref/vsynth2/asv2
+++ b/tests/ref/vsynth2/asv2
@@ -1,4 +1,4 @@
 9649a4b68fb1107bad13e8a7574cc72d *./tests/data/vsynth2/asv2.avi
 789072 ./tests/data/vsynth2/asv2.avi
 74a78015b64b2cf8cb9da2e44f508a69 *./tests/data/asv2.vsynth2.out.yuv
-stddev:   10.28 PSNR: 27.89 bytes:  7603200/  7603200
+stddev:   10.28 PSNR: 27.89 MAXDIFF:   95 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth2/dnxhd_1080i b/tests/ref/vsynth2/dnxhd_1080i
index 6ab7fbb..3dc0ef5 100644
--- a/tests/ref/vsynth2/dnxhd_1080i
+++ b/tests/ref/vsynth2/dnxhd_1080i
@@ -1,4 +1,4 @@
-1a4594983ae91f41907b89fe3174c527 *./tests/data/vsynth2/dnxhd-1080i.mov
+c81c7cfb375f61b7ab9b60fa340fe52a *./tests/data/vsynth2/dnxhd-1080i.mov
 3031875 ./tests/data/vsynth2/dnxhd-1080i.mov
 3c559af629ae0a8fb1a9a0e4b4da7733 *./tests/data/dnxhd_1080i.vsynth2.out.yuv
-stddev:    1.31 PSNR: 45.77 bytes:   760320/  7603200
+stddev:    1.31 PSNR: 45.77 MAXDIFF:   23 bytes:   760320/  7603200
diff --git a/tests/ref/vsynth2/dnxhd_720p b/tests/ref/vsynth2/dnxhd_720p
index cbf3f37..eab04c6 100644
--- a/tests/ref/vsynth2/dnxhd_720p
+++ b/tests/ref/vsynth2/dnxhd_720p
@@ -1,4 +1,4 @@
 58e07cc6ae0a2d36787044d0e82708a6 *./tests/data/vsynth2/dnxhd-720p.dnxhd
 2293760 ./tests/data/vsynth2/dnxhd-720p.dnxhd
 ab601eaafef74d80d3d20b780dddd836 *./tests/data/dnxhd_720p.vsynth2.out.yuv
-stddev:    1.36 PSNR: 45.45 bytes:   760320/  7603200
+stddev:    1.36 PSNR: 45.45 MAXDIFF:  127 bytes:   760320/  7603200
diff --git a/tests/ref/vsynth2/dnxhd_720p_rd b/tests/ref/vsynth2/dnxhd_720p_rd
index e922495..2d5c4d5 100644
--- a/tests/ref/vsynth2/dnxhd_720p_rd
+++ b/tests/ref/vsynth2/dnxhd_720p_rd
@@ -1,4 +1,4 @@
 092ffb7b8cf3c11556bb05dbb8b476ac *./tests/data/vsynth2/dnxhd-720p-rd.dnxhd
 2293760 ./tests/data/vsynth2/dnxhd-720p-rd.dnxhd
 33547ca318acff9448cba719cb99296d *./tests/data/dnxhd_720p_rd.vsynth2.out.yuv
-stddev:    1.32 PSNR: 45.66 bytes:   760320/  7603200
+stddev:    1.32 PSNR: 45.66 MAXDIFF:   22 bytes:   760320/  7603200
diff --git a/tests/ref/vsynth2/dv b/tests/ref/vsynth2/dv
index 72e4350..676b209 100644
--- a/tests/ref/vsynth2/dv
+++ b/tests/ref/vsynth2/dv
@@ -1,8 +1,8 @@
 bfa766f89bfeabc0ae1044f3954bed52 *./tests/data/vsynth2/dv.dv
 7200000 ./tests/data/vsynth2/dv.dv
 7ec62bd3350a6848364669e6e1e4b9cc *./tests/data/dv.vsynth2.out.yuv
-stddev:    1.71 PSNR: 43.47 bytes:  7603200/  7603200
+stddev:    1.71 PSNR: 43.47 MAXDIFF:   33 bytes:  7603200/  7603200
 00a9d8683ac6826af41bcf7223fb0389 *./tests/data/vsynth2/dv411.dv
 7200000 ./tests/data/vsynth2/dv411.dv
 7f9fa421028aabb11eaf4c6513a5a843 *./tests/data/dv.vsynth2.out.yuv
-stddev:   10.09 PSNR: 28.05 bytes:  7603200/  7603200
+stddev:   10.09 PSNR: 28.05 MAXDIFF:   60 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth2/dv50 b/tests/ref/vsynth2/dv50
index 79c25a8..7e0083b 100644
--- a/tests/ref/vsynth2/dv50
+++ b/tests/ref/vsynth2/dv50
@@ -1,4 +1,4 @@
 61e31c79e8949b25c849753a0785b0d7 *./tests/data/vsynth2/dv50.dv
 14400000 ./tests/data/vsynth2/dv50.dv
 af3f2dd5ab62c1a1d98b07d4aeb6852f *./tests/data/dv50.vsynth2.out.yuv
-stddev:    0.82 PSNR: 49.82 bytes:  7603200/  7603200
+stddev:    0.82 PSNR: 49.82 MAXDIFF:   12 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth2/error b/tests/ref/vsynth2/error
index b273e00..4181b2d 100644
--- a/tests/ref/vsynth2/error
+++ b/tests/ref/vsynth2/error
@@ -1,4 +1,4 @@
 90e65096aa9ebafa3fe3f44a5a47cdc4 *./tests/data/vsynth2/error-mpeg4-adv.avi
 176588 ./tests/data/vsynth2/error-mpeg4-adv.avi
 9fe1082179f80179439953c7397a46ef *./tests/data/error.vsynth2.out.yuv
-stddev:    9.00 PSNR: 29.04 bytes:  7603200/  7603200
+stddev:    9.00 PSNR: 29.04 MAXDIFF:  168 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth2/ffv1 b/tests/ref/vsynth2/ffv1
index f7dd8e9..d251af5 100644
--- a/tests/ref/vsynth2/ffv1
+++ b/tests/ref/vsynth2/ffv1
@@ -1,4 +1,4 @@
 d72b0960e162d4998b9acbabb07e99ab *./tests/data/vsynth2/ffv1.avi
 3525804 ./tests/data/vsynth2/ffv1.avi
 dde5895817ad9d219f79a52d0bdfb001 *./tests/data/ffv1.vsynth2.out.yuv
-stddev:    0.00 PSNR:999.99 bytes:  7603200/  7603200
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth2/flashsv b/tests/ref/vsynth2/flashsv
index b5f0bce..bfbb9e1 100644
--- a/tests/ref/vsynth2/flashsv
+++ b/tests/ref/vsynth2/flashsv
@@ -1,4 +1,4 @@
 0667077971e0cb63b5f49c580006e90e *./tests/data/vsynth2/flashsv.flv
 12368953 ./tests/data/vsynth2/flashsv.flv
 592b3321994e26a990deb3a0a1415de9 *./tests/data/flashsv.vsynth2.out.yuv
-stddev:    0.65 PSNR: 51.84 bytes:  7603200/  7603200
+stddev:    0.65 PSNR: 51.84 MAXDIFF:   14 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth2/flv b/tests/ref/vsynth2/flv
index 7fa57db..716177f 100644
--- a/tests/ref/vsynth2/flv
+++ b/tests/ref/vsynth2/flv
@@ -1,4 +1,4 @@
 2edc92093d36506bcc0a5c0e17e86113 *./tests/data/vsynth2/flv.flv
 131360 ./tests/data/vsynth2/flv.flv
 8999c8264fb0941561f64c4a736e9d88 *./tests/data/flv.vsynth2.out.yuv
-stddev:    5.33 PSNR: 33.59 bytes:  7603200/  7603200
+stddev:    5.33 PSNR: 33.59 MAXDIFF:   80 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth2/h261 b/tests/ref/vsynth2/h261
index ef9454c..07c29ab 100644
--- a/tests/ref/vsynth2/h261
+++ b/tests/ref/vsynth2/h261
@@ -1,4 +1,4 @@
 dfd005d4c9030a0dc889c828a6408b9c *./tests/data/vsynth2/h261.avi
 191086 ./tests/data/vsynth2/h261.avi
 db7ceff174823b98834faa2320ca89ac *./tests/data/h261.vsynth2.out.yuv
-stddev:    6.37 PSNR: 32.03 bytes:  7603200/  7603200
+stddev:    6.37 PSNR: 32.03 MAXDIFF:   77 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth2/h263 b/tests/ref/vsynth2/h263
index 739ba52..7e3fd33 100644
--- a/tests/ref/vsynth2/h263
+++ b/tests/ref/vsynth2/h263
@@ -1,4 +1,4 @@
 9a368687ab34c48079f11a202839a6bc *./tests/data/vsynth2/h263.avi
 160106 ./tests/data/vsynth2/h263.avi
 61213b91b359697ebcefb9e0a53ac54a *./tests/data/h263.vsynth2.out.yuv
-stddev:    5.43 PSNR: 33.42 bytes:  7603200/  7603200
+stddev:    5.43 PSNR: 33.42 MAXDIFF:   77 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth2/h263p b/tests/ref/vsynth2/h263p
index 3c26eb0..314726f 100644
--- a/tests/ref/vsynth2/h263p
+++ b/tests/ref/vsynth2/h263p
@@ -1,4 +1,4 @@
 c7644d40e9f40bbd98e5a978f9f94bb4 *./tests/data/vsynth2/h263p.avi
 868018 ./tests/data/vsynth2/h263p.avi
 4b0ee791f280029dc03c528f76f195d4 *./tests/data/h263p.vsynth2.out.yuv
-stddev:    1.91 PSNR: 42.50 bytes:  7603200/  7603200
+stddev:    1.91 PSNR: 42.50 MAXDIFF:   19 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth2/huffyuv b/tests/ref/vsynth2/huffyuv
index e0e7277..740862a 100644
--- a/tests/ref/vsynth2/huffyuv
+++ b/tests/ref/vsynth2/huffyuv
@@ -1,4 +1,4 @@
 56cd44907a48990e06bd065e189ff461 *./tests/data/vsynth2/huffyuv.avi
 6455232 ./tests/data/vsynth2/huffyuv.avi
 dde5895817ad9d219f79a52d0bdfb001 *./tests/data/huffyuv.vsynth2.out.yuv
-stddev:    0.00 PSNR:999.99 bytes:  7603200/  7603200
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth2/jpegls b/tests/ref/vsynth2/jpegls
index 3f87fd2..e7fa2df 100644
--- a/tests/ref/vsynth2/jpegls
+++ b/tests/ref/vsynth2/jpegls
@@ -1,4 +1,4 @@
 4fc53937f048c900ae6d50fda9dba206 *./tests/data/vsynth2/jpegls.avi
 8334630 ./tests/data/vsynth2/jpegls.avi
 592b3321994e26a990deb3a0a1415de9 *./tests/data/jpegls.vsynth2.out.yuv
-stddev:    0.65 PSNR: 51.84 bytes:  7603200/  7603200
+stddev:    0.65 PSNR: 51.84 MAXDIFF:   14 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth2/ljpeg b/tests/ref/vsynth2/ljpeg
index aec9b56..54c1d86 100644
--- a/tests/ref/vsynth2/ljpeg
+++ b/tests/ref/vsynth2/ljpeg
@@ -1,4 +1,4 @@
 554a4a6a5a9058c588f8bf2de405bc70 *./tests/data/vsynth2/ljpeg.avi
 4766914 ./tests/data/vsynth2/ljpeg.avi
 dde5895817ad9d219f79a52d0bdfb001 *./tests/data/ljpeg.vsynth2.out.yuv
-stddev:    0.00 PSNR:999.99 bytes:  7603200/  7603200
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth2/mjpeg b/tests/ref/vsynth2/mjpeg
index 0b501f9..adee328 100644
--- a/tests/ref/vsynth2/mjpeg
+++ b/tests/ref/vsynth2/mjpeg
@@ -1,4 +1,4 @@
 89df32b46c977fb4cb140ec6c489dd76 *./tests/data/vsynth2/mjpeg.avi
 673224 ./tests/data/vsynth2/mjpeg.avi
 a96a4e15ffcb13e44360df642d049496 *./tests/data/mjpeg.vsynth2.out.yuv
-stddev:    4.32 PSNR: 35.40 bytes:  7603200/  7603200
+stddev:    4.32 PSNR: 35.40 MAXDIFF:   49 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth2/mpeg b/tests/ref/vsynth2/mpeg
index 1f995eb..5a051c8 100644
--- a/tests/ref/vsynth2/mpeg
+++ b/tests/ref/vsynth2/mpeg
@@ -1,4 +1,4 @@
 73ca6f1deab02d1d67a0e8495c026a9e *./tests/data/vsynth2/mpeg1.mpg
 192783 ./tests/data/vsynth2/mpeg1.mpg
 56147e94b12f08df7213e610e177823d *./tests/data/mpeg.vsynth2.out.yuv
-stddev:    4.95 PSNR: 34.22 bytes:  7603200/  7603200
+stddev:    4.95 PSNR: 34.22 MAXDIFF:   57 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth2/mpeg1b b/tests/ref/vsynth2/mpeg1b
index 626fbd0..f51aa3f 100644
--- a/tests/ref/vsynth2/mpeg1b
+++ b/tests/ref/vsynth2/mpeg1b
@@ -1,4 +1,4 @@
 e026a2fef80c9679776d2b5c8be09338 *./tests/data/vsynth2/mpeg1b.mpg
 225198 ./tests/data/vsynth2/mpeg1b.mpg
 1150495f4bd487486ee53326c42d0bb8 *./tests/data/mpeg1b.vsynth2.out.yuv
-stddev:    4.10 PSNR: 35.86 bytes:  7603200/  7603200
+stddev:    4.10 PSNR: 35.86 MAXDIFF:   59 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth2/mpeg2 b/tests/ref/vsynth2/mpeg2
index f4a1c96..a6ab3f6 100644
--- a/tests/ref/vsynth2/mpeg2
+++ b/tests/ref/vsynth2/mpeg2
@@ -1,20 +1,20 @@
 2d55ce623a7be4e8136f80266e487678 *./tests/data/vsynth2/mpeg2.mpg
 198667 ./tests/data/vsynth2/mpeg2.mpg
 b7cae8a1f751b821cddcbe4d5dbc518c *./tests/data/mpeg2.vsynth2.out.yuv
-stddev:    4.96 PSNR: 34.20 bytes:  7603200/  7603200
+stddev:    4.96 PSNR: 34.20 MAXDIFF:   59 bytes:  7603200/  7603200
 1ba5efeb53fab7b4b71edc96d86f6c91 *./tests/data/vsynth2/mpeg2ivlc-qprd.mpg
 244694 ./tests/data/vsynth2/mpeg2ivlc-qprd.mpg
 b26e21599dee48a174bdbc40b2817e55 *./tests/data/mpeg2.vsynth2.out.yuv
-stddev:    4.15 PSNR: 35.76 bytes:  7603200/  7603200
+stddev:    4.15 PSNR: 35.76 MAXDIFF:   74 bytes:  7603200/  7603200
 2c8e33c2d2efab86fc16a195f6877682 *./tests/data/vsynth2/mpeg2_422.mpg
 356124 ./tests/data/vsynth2/mpeg2_422.mpg
 de44597c6c470f3e7019b31245a3ff69 *./tests/data/mpeg2.vsynth2.out.yuv
-stddev:   54.55 PSNR: 13.39 bytes: 10137600/  7603200
+stddev:   54.55 PSNR: 13.39 MAXDIFF:  201 bytes: 10137600/  7603200
 f979bcca866e6e4cad5dc6cb06e56cfb *./tests/data/vsynth2/mpeg2.mpg
 198041 ./tests/data/vsynth2/mpeg2.mpg
 f6d9bf24ff8676a7f6076c05cd2c81a3 *./tests/data/mpeg2.vsynth2.out.yuv
-stddev:    4.97 PSNR: 34.19 bytes:  7603200/  7603200
+stddev:    4.97 PSNR: 34.19 MAXDIFF:   58 bytes:  7603200/  7603200
 f90197a8b6e62ae25f82625337f27240 *./tests/data/vsynth2/mpeg2i.mpg
 204579 ./tests/data/vsynth2/mpeg2i.mpg
 ea5057b60146c06d40449cdfc686bf13 *./tests/data/mpeg2.vsynth2.out.yuv
-stddev:    4.98 PSNR: 34.18 bytes:  7603200/  7603200
+stddev:    4.98 PSNR: 34.18 MAXDIFF:   65 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth2/mpeg2thread b/tests/ref/vsynth2/mpeg2thread
index 9253d7f..3c9c0d0 100644
--- a/tests/ref/vsynth2/mpeg2thread
+++ b/tests/ref/vsynth2/mpeg2thread
@@ -1,12 +1,12 @@
 889c754a42d7689b228853e1ece6d345 *./tests/data/vsynth2/mpeg2thread.mpg
 179650 ./tests/data/vsynth2/mpeg2thread.mpg
 8c6a7ed2eb73bd18fd2bb9829464100d *./tests/data/mpeg2thread.vsynth2.out.yuv
-stddev:    4.72 PSNR: 34.65 bytes:  7603200/  7603200
+stddev:    4.72 PSNR: 34.65 MAXDIFF:   72 bytes:  7603200/  7603200
 10b900e32809758857c596d56746e00e *./tests/data/vsynth2/mpeg2threadivlc.mpg
 178801 ./tests/data/vsynth2/mpeg2threadivlc.mpg
 8c6a7ed2eb73bd18fd2bb9829464100d *./tests/data/mpeg2thread.vsynth2.out.yuv
-stddev:    4.72 PSNR: 34.65 bytes:  7603200/  7603200
+stddev:    4.72 PSNR: 34.65 MAXDIFF:   72 bytes:  7603200/  7603200
 864d6bf2982a61e510003a518be65a2d *./tests/data/vsynth2/mpeg2reuse.mpg
 383419 ./tests/data/vsynth2/mpeg2reuse.mpg
 bb20fa080cfd2b0a687ea7376ff4f902 *./tests/data/mpeg2thread.vsynth2.out.yuv
-stddev:    4.73 PSNR: 34.63 bytes:  7603200/  7603200
+stddev:    4.73 PSNR: 34.63 MAXDIFF:   72 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth2/mpeg4 b/tests/ref/vsynth2/mpeg4
index c24cbd0..9a6158c 100644
--- a/tests/ref/vsynth2/mpeg4
+++ b/tests/ref/vsynth2/mpeg4
@@ -1,4 +1,4 @@
 47de227982e77830a2db278214a08773 *./tests/data/vsynth2/odivx.mp4
 119797 ./tests/data/vsynth2/odivx.mp4
 90a3577850239083a9042bef33c50e85 *./tests/data/mpeg4.vsynth2.out.yuv
-stddev:    5.34 PSNR: 33.57 bytes:  7603200/  7603200
+stddev:    5.34 PSNR: 33.57 MAXDIFF:   83 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth2/mpeg4adv b/tests/ref/vsynth2/mpeg4adv
index 89d21ac..f8568c7 100644
--- a/tests/ref/vsynth2/mpeg4adv
+++ b/tests/ref/vsynth2/mpeg4adv
@@ -1,16 +1,16 @@
 dee7be19486a76d96c88d18eefba8f86 *./tests/data/vsynth2/mpeg4-adv.avi
 141546 ./tests/data/vsynth2/mpeg4-adv.avi
 3f3a21e9db85a9c0f7022f557a5374c1 *./tests/data/mpeg4adv.vsynth2.out.yuv
-stddev:    4.94 PSNR: 34.25 bytes:  7603200/  7603200
+stddev:    4.94 PSNR: 34.25 MAXDIFF:   69 bytes:  7603200/  7603200
 fd5ab0f55dbc959316e32923e86290df *./tests/data/vsynth2/mpeg4-qprd.avi
 231458 ./tests/data/vsynth2/mpeg4-qprd.avi
 de8a883865e2dff7a51f66da6c48df48 *./tests/data/mpeg4adv.vsynth2.out.yuv
-stddev:    3.71 PSNR: 36.72 bytes:  7603200/  7603200
+stddev:    3.71 PSNR: 36.72 MAXDIFF:   61 bytes:  7603200/  7603200
 547e1849dcf910935ff6383ca49e5706 *./tests/data/vsynth2/mpeg4-adap.avi
 198510 ./tests/data/vsynth2/mpeg4-adap.avi
 4affb83f6adc94f31024b4f9e0168945 *./tests/data/mpeg4adv.vsynth2.out.yuv
-stddev:    3.75 PSNR: 36.65 bytes:  7603200/  7603200
+stddev:    3.75 PSNR: 36.65 MAXDIFF:   71 bytes:  7603200/  7603200
 7680d2e7d34399dfdfb8a49cf1e10239 *./tests/data/vsynth2/mpeg4-Q.avi
 163688 ./tests/data/vsynth2/mpeg4-Q.avi
 26dc7c78955fa678fbf150e236eb5627 *./tests/data/mpeg4adv.vsynth2.out.yuv
-stddev:    3.97 PSNR: 36.14 bytes:  7603200/  7603200
+stddev:    3.97 PSNR: 36.14 MAXDIFF:   54 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth2/mpeg4nr b/tests/ref/vsynth2/mpeg4nr
index 1f9499f..ec36d27 100644
--- a/tests/ref/vsynth2/mpeg4nr
+++ b/tests/ref/vsynth2/mpeg4nr
@@ -1,4 +1,4 @@
 c41187c99588fb7229ad330b2f80d28b *./tests/data/vsynth2/mpeg4-nr.avi
 155044 ./tests/data/vsynth2/mpeg4-nr.avi
 f7fc191308679f709405e62271f5c65f *./tests/data/mpeg4nr.vsynth2.out.yuv
-stddev:    4.73 PSNR: 34.63 bytes:  7603200/  7603200
+stddev:    4.73 PSNR: 34.63 MAXDIFF:   64 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth2/mpeg4thread b/tests/ref/vsynth2/mpeg4thread
index c881aa4..63f355b 100644
--- a/tests/ref/vsynth2/mpeg4thread
+++ b/tests/ref/vsynth2/mpeg4thread
@@ -1,4 +1,4 @@
 ba30d10ff70d46e7c5b7fa859ea1faa4 *./tests/data/vsynth2/mpeg4-thread.avi
 250140 ./tests/data/vsynth2/mpeg4-thread.avi
 5355deb8c7609a3f1ff2173aab1dee70 *./tests/data/mpeg4thread.vsynth2.out.yuv
-stddev:    3.69 PSNR: 36.78 bytes:  7603200/  7603200
+stddev:    3.69 PSNR: 36.78 MAXDIFF:   65 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth2/msmpeg4 b/tests/ref/vsynth2/msmpeg4
index d77a454..7620273 100644
--- a/tests/ref/vsynth2/msmpeg4
+++ b/tests/ref/vsynth2/msmpeg4
@@ -1,4 +1,4 @@
-3069f95f2ffca1f20c8ea36e2625fabc *./tests/data/vsynth2/msmpeg4.avi
+26dee25a62a66daba4f38ac6bd8f4677 *./tests/data/vsynth2/msmpeg4.avi
 127680 ./tests/data/vsynth2/msmpeg4.avi
 0e1c6e25c71c6a8fa8e506e3d97ca4c9 *./tests/data/msmpeg4.vsynth2.out.yuv
-stddev:    5.33 PSNR: 33.59 bytes:  7603200/  7603200
+stddev:    5.33 PSNR: 33.59 MAXDIFF:   78 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth2/msmpeg4v2 b/tests/ref/vsynth2/msmpeg4v2
index 3bfd839..9fe913d 100644
--- a/tests/ref/vsynth2/msmpeg4v2
+++ b/tests/ref/vsynth2/msmpeg4v2
@@ -1,4 +1,4 @@
 c09815e40a9d260628e1ebad8b2b3774 *./tests/data/vsynth2/msmpeg4v2.avi
 129918 ./tests/data/vsynth2/msmpeg4v2.avi
 8920194f8bf8f9cdd6c65b3df9e1a292 *./tests/data/msmpeg4v2.vsynth2.out.yuv
-stddev:    5.33 PSNR: 33.59 bytes:  7603200/  7603200
+stddev:    5.33 PSNR: 33.59 MAXDIFF:   80 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth2/qtrle b/tests/ref/vsynth2/qtrle
new file mode 100644
index 0000000..6b2a011
--- /dev/null
+++ b/tests/ref/vsynth2/qtrle
@@ -0,0 +1,4 @@
+d8c1604dc46d9aa4ec0385e6722c6989 *./tests/data/vsynth2/qtrle.mov
+14798419 ./tests/data/vsynth2/qtrle.mov
+b2418e0e3a9a8619b31219cbcf24dc82 *./tests/data/qtrle.vsynth2.out.yuv
+stddev:    1.26 PSNR: 46.06 MAXDIFF:   13 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth2/rc b/tests/ref/vsynth2/rc
index d6eab69..14d9a6c 100644
--- a/tests/ref/vsynth2/rc
+++ b/tests/ref/vsynth2/rc
@@ -1,4 +1,4 @@
 c25ede9e268b834a09a63f5136cd1b95 *./tests/data/vsynth2/mpeg4-rc.avi
 226332 ./tests/data/vsynth2/mpeg4-rc.avi
 2b34e606af895b62a250de98749a19b0 *./tests/data/rc.vsynth2.out.yuv
-stddev:    4.23 PSNR: 35.60 bytes:  7603200/  7603200
+stddev:    4.23 PSNR: 35.60 MAXDIFF:   85 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth2/rgb b/tests/ref/vsynth2/rgb
new file mode 100644
index 0000000..ea83470
--- /dev/null
+++ b/tests/ref/vsynth2/rgb
@@ -0,0 +1,4 @@
+f2e9c419023c743bf99aa5b2e55ad233 *./tests/data/vsynth2/rgb.avi
+15213260 ./tests/data/vsynth2/rgb.avi
+b2418e0e3a9a8619b31219cbcf24dc82 *./tests/data/rgb.vsynth2.out.yuv
+stddev:    1.26 PSNR: 46.06 MAXDIFF:   13 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth2/roq b/tests/ref/vsynth2/roq
index f82f640..a9650de 100644
--- a/tests/ref/vsynth2/roq
+++ b/tests/ref/vsynth2/roq
@@ -1,4 +1,4 @@
 b46f899b2363065c60f3782ba1f8b7bd *./tests/data/vsynth2/roqav.roq
 92786 ./tests/data/vsynth2/roqav.roq
 e69fca960dd0911e9b8d589c13e11dc1 *./tests/data/roq.vsynth2.out.yuv
-stddev:    3.81 PSNR: 36.49 bytes:   760320/  7603200
+stddev:    3.81 PSNR: 36.49 MAXDIFF:   54 bytes:   760320/  7603200
diff --git a/tests/ref/vsynth2/rv10 b/tests/ref/vsynth2/rv10
index c71d0db..75b9265 100644
--- a/tests/ref/vsynth2/rv10
+++ b/tests/ref/vsynth2/rv10
@@ -1,4 +1,4 @@
 b1467b0e8d8cad730e36d1e8ab49d573 *./tests/data/vsynth2/rv10.rm
 154310 ./tests/data/vsynth2/rv10.rm
 61213b91b359697ebcefb9e0a53ac54a *./tests/data/rv10.vsynth2.out.yuv
-stddev:    5.43 PSNR: 33.42 bytes:  7603200/  7603200
+stddev:    5.43 PSNR: 33.42 MAXDIFF:   77 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth2/rv20 b/tests/ref/vsynth2/rv20
index d029e50..903881f 100644
--- a/tests/ref/vsynth2/rv20
+++ b/tests/ref/vsynth2/rv20
@@ -1,4 +1,4 @@
-d864475aa16d84dd99de13e65003672a *./tests/data/vsynth2/rv20.rm
-132734 ./tests/data/vsynth2/rv20.rm
-c66afdcc0daac2f1b4167b9811968877 *./tests/data/rv20.vsynth2.out.yuv
-stddev:    5.42 PSNR: 33.45 bytes:  7603200/  7603200
+96acb098850b9bf309f89e48b08fe96f *./tests/data/vsynth2/rv20.rm
+153302 ./tests/data/vsynth2/rv20.rm
+46f314e70d9bac2e7d82cfc230534977 *./tests/data/rv20.vsynth2.out.yuv
+stddev:    5.48 PSNR: 33.35 MAXDIFF:   81 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth2/snow b/tests/ref/vsynth2/snow
index 521d563..922110b 100644
--- a/tests/ref/vsynth2/snow
+++ b/tests/ref/vsynth2/snow
@@ -1,4 +1,4 @@
 af651d8ef0a66257ac8b2ef8b229f27b *./tests/data/vsynth2/snow.avi
 57700 ./tests/data/vsynth2/snow.avi
 8890189af71a0dd3447c4e8424c9a76b *./tests/data/snow.vsynth2.out.yuv
-stddev:   10.47 PSNR: 27.72 bytes:  7603200/  7603200
+stddev:   10.47 PSNR: 27.72 MAXDIFF:  119 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth2/snowll b/tests/ref/vsynth2/snowll
index 111a2f2..0eb4945 100644
--- a/tests/ref/vsynth2/snowll
+++ b/tests/ref/vsynth2/snowll
@@ -1,4 +1,4 @@
 a8fccf278bbb17d37a756ecf11672b09 *./tests/data/vsynth2/snow53.avi
 2721758 ./tests/data/vsynth2/snow53.avi
 dde5895817ad9d219f79a52d0bdfb001 *./tests/data/snowll.vsynth2.out.yuv
-stddev:    0.00 PSNR:999.99 bytes:  7603200/  7603200
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth2/svq1 b/tests/ref/vsynth2/svq1
index 2a391c3..7c54c74 100644
--- a/tests/ref/vsynth2/svq1
+++ b/tests/ref/vsynth2/svq1
@@ -1,4 +1,4 @@
 7f9fbe4890bc1df67867bf03803dca48 *./tests/data/vsynth2/svq1.mov
 766851 ./tests/data/vsynth2/svq1.mov
 aa03471dac3f49455a33a2b19fda1098 *./tests/data/svq1.vsynth2.out.yuv
-stddev:    3.23 PSNR: 37.93 bytes:  7603200/  7603200
+stddev:    3.23 PSNR: 37.93 MAXDIFF:   61 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth2/wmv1 b/tests/ref/vsynth2/wmv1
index 3339a95..12c3f57 100644
--- a/tests/ref/vsynth2/wmv1
+++ b/tests/ref/vsynth2/wmv1
@@ -1,4 +1,4 @@
 1011e26e7d351c96d7bbfe106d831b69 *./tests/data/vsynth2/wmv1.avi
 129530 ./tests/data/vsynth2/wmv1.avi
 81eee429b665254d19a06607463c0b5e *./tests/data/wmv1.vsynth2.out.yuv
-stddev:    5.33 PSNR: 33.60 bytes:  7603200/  7603200
+stddev:    5.33 PSNR: 33.60 MAXDIFF:   77 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth2/wmv2 b/tests/ref/vsynth2/wmv2
index 61bb5a5..27fcd12 100644
--- a/tests/ref/vsynth2/wmv2
+++ b/tests/ref/vsynth2/wmv2
@@ -1,4 +1,4 @@
 1f6598e9776ed00aebdc44cc8d48cb7c *./tests/data/vsynth2/wmv2.avi
 129860 ./tests/data/vsynth2/wmv2.avi
 81eee429b665254d19a06607463c0b5e *./tests/data/wmv2.vsynth2.out.yuv
-stddev:    5.33 PSNR: 33.60 bytes:  7603200/  7603200
+stddev:    5.33 PSNR: 33.60 MAXDIFF:   77 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth2/yuv b/tests/ref/vsynth2/yuv
new file mode 100644
index 0000000..6593ce9
--- /dev/null
+++ b/tests/ref/vsynth2/yuv
@@ -0,0 +1,4 @@
+30a400773ab26f2c83e469198b156f1d *./tests/data/vsynth2/yuv.avi
+7610060 ./tests/data/vsynth2/yuv.avi
+dde5895817ad9d219f79a52d0bdfb001 *./tests/data/yuv.vsynth2.out.yuv
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/regression-funcs.sh b/tests/regression-funcs.sh
index 8fd17ab..4093656 100755
--- a/tests/regression-funcs.sh
+++ b/tests/regression-funcs.sh
@@ -9,12 +9,14 @@ test_ref=$2
 raw_src_dir=$3
 target_exec=$4
 target_path=$5
+threads=${6:-1}
 
 datadir="./tests/data"
 target_datadir="${target_path}/${datadir}"
 
 this="$test.$test_ref"
-logfile="$datadir/$this.regression"
+logdir="$datadir/regression/$test_ref"
+logfile="$logdir/$test"
 outfile="$datadir/$test_ref/"
 errfile="$datadir/$this.err"
 
@@ -33,23 +35,38 @@ pcm_ref="$datadir/$test_ref.ref.wav"
 crcfile="$datadir/$this.crc"
 target_crcfile="$target_datadir/$this.crc"
 
+cleanfiles="$raw_dst $pcm_dst $crcfile $bench $bench2"
+trap 'rm -f -- $cleanfiles' EXIT
+
 mkdir -p "$datadir"
 mkdir -p "$outfile"
+mkdir -p "$logdir"
+
+(exec >&3) 2>/dev/null || exec 3>&2
 
-[ "${V-0}" -gt 0 ] && echov=echo || echov=:
+[ "${V-0}" -gt 0 ] && echov=echov || echov=:
 [ "${V-0}" -gt 1 ] || exec 2>$errfile
 
+echov(){
+    echo "$@" >&3
+}
+
 . $(dirname $0)/md5.sh
 
-FFMPEG_OPTS="-v 0 -y -flags +bitexact -dct fastint -idct simple -sws_flags +accurate_rnd+bitexact"
+FFMPEG_OPTS="-v 0 -threads $threads -y -flags +bitexact -dct fastint -idct simple -sws_flags +accurate_rnd+bitexact"
+
+run_ffmpeg()
+{
+    $echov $ffmpeg $FFMPEG_OPTS $*
+    $ffmpeg $FFMPEG_OPTS $*
+}
 
 do_ffmpeg()
 {
     f="$1"
     shift
     set -- $* ${target_path}/$f
-    $echov $ffmpeg $FFMPEG_OPTS $*
-    $ffmpeg $FFMPEG_OPTS -benchmark $* > $bench
+    run_ffmpeg -benchmark $* > $bench
     do_md5sum $f >> $logfile
     if [ $f = $raw_dst ] ; then
         $tiny_psnr $f $raw_ref >> $logfile
@@ -67,8 +84,7 @@ do_ffmpeg_nomd5()
     f="$1"
     shift
     set -- $* ${target_path}/$f
-    $echov $ffmpeg $FFMPEG_OPTS $*
-    $ffmpeg $FFMPEG_OPTS -benchmark $* > $bench
+    run_ffmpeg -benchmark $* > $bench
     if [ $f = $raw_dst ] ; then
         $tiny_psnr $f $raw_ref >> $logfile
     elif [ $f = $pcm_dst ] ; then
@@ -84,18 +100,15 @@ do_ffmpeg_crc()
 {
     f="$1"
     shift
-    $echov $ffmpeg $FFMPEG_OPTS $* -f crc "$target_crcfile"
-    $ffmpeg $FFMPEG_OPTS $* -f crc "$target_crcfile"
+    run_ffmpeg $* -f crc "$target_crcfile"
     echo "$f $(cat $crcfile)" >> $logfile
-    rm -f "$crcfile"
 }
 
 do_ffmpeg_nocheck()
 {
     f="$1"
     shift
-    $echov $ffmpeg $FFMPEG_OPTS $*
-    $ffmpeg $FFMPEG_OPTS -benchmark $* > $bench
+    run_ffmpeg -benchmark $* > $bench
     expr "$(cat $bench)" : '.*utime=\(.*s\)' > $bench2
     echo $(cat $bench2) $f >> $benchfile
 }
@@ -103,7 +116,6 @@ do_ffmpeg_nocheck()
 do_video_decoding()
 {
     do_ffmpeg $raw_dst $1 -i $target_path/$file -f rawvideo $2
-    rm -f $raw_dst
 }
 
 do_video_encoding()
diff --git a/tests/rotozoom.c b/tests/rotozoom.c
index 47da1b0..25f0e02 100644
--- a/tests/rotozoom.c
+++ b/tests/rotozoom.c
@@ -3,20 +3,20 @@
  *
  * copyright (c) Sebastien Bechet <s.bechet at av7.net>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/tests/seek-regression.sh b/tests/seek-regression.sh
deleted file mode 100755
index ae0ef67..0000000
--- a/tests/seek-regression.sh
+++ /dev/null
@@ -1,38 +0,0 @@
-#!/bin/sh
-
-LC_ALL=C
-export LC_ALL
-
-src_path=$1
-target_exec=$2
-target_path=$3
-
-[ "${V-0}" -gt 0 ] && echov=echo || echov=:
-[ "${V-0}" -gt 1 ] || exec 2>/dev/null
-
-refdir="$src_path/tests/ref/seek"
-datadir="tests/data"
-
-list=$(ls -1 $datadir/vsynth2/* $datadir/acodec/* $datadir/lavf/*)
-imgs=$(for i in $datadir/images/*; do echo "$i/%02d.${i##*/}"; done)
-err=0
-
-for i in $list $imgs; do
-    base=$(basename $i)
-    logfile="$datadir/$base.seek.regression"
-    reffile="$refdir/$base.ref"
-    echo "TEST SEEK   $base"
-    $echov $target_exec $target_path/tests/seek_test $target_path/$i
-    $target_exec $target_path/tests/seek_test $target_path/$i > $logfile
-    diff -u -w "$reffile" "$logfile" || err=1
-done
-
-if [ $err = 0 ]; then
-    echo
-    echo seek regression test: success
-    exit 0
-else
-    echo
-    echo seek regression test: error
-    exit 1
-fi
diff --git a/tests/seek_test.c b/tests/seek_test.c
index 81a7821..5d4f41c 100644
--- a/tests/seek_test.c
+++ b/tests/seek_test.c
@@ -2,20 +2,20 @@
  * Copyright (c) 2003 Fabrice Bellard
  * Copyright (c) 2007 Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/tests/tiny_psnr.c b/tests/tiny_psnr.c
index f8d1b7b..efa5e01 100644
--- a/tests/tiny_psnr.c
+++ b/tests/tiny_psnr.c
@@ -1,25 +1,26 @@
 /*
  * Copyright (c) 2003 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include <stdio.h>
 #include <stdlib.h>
+#include <string.h>
 #include <inttypes.h>
 #include <assert.h>
 
@@ -113,21 +114,41 @@ int main(int argc,char* argv[]){
     int skip_bytes = argc<6 ? 0 : atoi(argv[5]);
     int size0=0;
     int size1=0;
+    int maxdist = 0;
 
     if(argc<3){
         printf("tiny_psnr <file1> <file2> [<elem size> [<shift> [<skip bytes>]]]\n");
-        printf("For WAV files use the following:\n");
-        printf("./tiny_psnr file1.wav file2.wav 2 0 44 to skip the header.\n");
-        return -1;
+        printf("WAV headers are skipped automatically.\n");
+        return 1;
     }
 
     f[0]= fopen(argv[1], "rb");
     f[1]= fopen(argv[2], "rb");
     if(!f[0] || !f[1]){
         fprintf(stderr, "Could not open input files.\n");
-        return -1;
+        return 1;
     }
-    fseek(f[shift<0], shift < 0 ? -shift : shift, SEEK_SET);
+
+    for (i = 0; i < 2; i++) {
+        uint8_t *p = buf[i];
+        if (fread(p, 1, 12, f[i]) != 12)
+            return 1;
+        if (!memcmp(p,   "RIFF", 4) &&
+            !memcmp(p+8, "WAVE", 4)) {
+            if (fread(p, 1, 8, f[i]) != 8)
+                return 1;
+            while (memcmp(p, "data", 4)) {
+                int s = p[4] | p[5]<<8 | p[6]<<16 | p[7]<<24;
+                fseek(f[i], s, SEEK_CUR);
+                if (fread(p, 1, 8, f[i]) != 8)
+                    return 1;
+            }
+        } else {
+            fseek(f[i], -12, SEEK_CUR);
+        }
+    }
+
+    fseek(f[shift<0], abs(shift), SEEK_CUR);
 
     fseek(f[0],skip_bytes,SEEK_CUR);
     fseek(f[1],skip_bytes,SEEK_CUR);
@@ -139,11 +160,14 @@ int main(int argc,char* argv[]){
         for(j=0; j<FFMIN(s0,s1); j++){
             int64_t a= buf[0][j];
             int64_t b= buf[1][j];
+            int dist;
             if(len==2){
                 a= (int16_t)(a | (buf[0][++j]<<8));
                 b= (int16_t)(b | (buf[1][  j]<<8));
             }
             sse += (a-b) * (a-b);
+            dist = abs(a-b);
+            if (dist > maxdist) maxdist = dist;
         }
         size0 += s0;
         size1 += s1;
@@ -159,9 +183,10 @@ int main(int argc,char* argv[]){
     else
         psnr= 1000*F-1; //floating point free infinity :)
 
-    printf("stddev:%5d.%02d PSNR:%3d.%02d bytes:%9d/%9d\n",
+    printf("stddev:%5d.%02d PSNR:%3d.%02d MAXDIFF:%5d bytes:%9d/%9d\n",
         (int)(dev/F), (int)(dev%F),
         (int)(psnr/F), (int)(psnr%F),
+        maxdist,
         size0, size1);
     return 0;
 }
diff --git a/tests/videogen.c b/tests/videogen.c
index 4238e3f..f114801 100644
--- a/tests/videogen.c
+++ b/tests/videogen.c
@@ -4,20 +4,20 @@
  *
  * Copyright (c) 2002 Fabrice Bellard
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/tools/graph2dot.c b/tools/graph2dot.c
index 57a25a7..5ec6e20 100644
--- a/tools/graph2dot.c
+++ b/tools/graph2dot.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2008-2010 Stefano Sabatini
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -22,7 +22,8 @@
 
 #undef HAVE_AV_CONFIG_H
 #include "libavutil/pixdesc.h"
-#include "libavfilter/graphparser.h"
+#include "libavutil/audioconvert.h"
+#include "libavfilter/avfiltergraph.h"
 
 static void usage(void)
 {
@@ -67,8 +68,18 @@ static void print_digraph(FILE *outfile, AVFilterGraph *graph)
                          dst_filter_ctx->filter->name);
 
                 fprintf(outfile, "\"%s\" -> \"%s\"", filter_ctx_label, dst_filter_ctx_label);
-                fprintf(outfile, " [ label= \"fmt:%s w:%d h:%d\"];\n",
-                        av_pix_fmt_descriptors[link->format].name, link->w, link->h);
+                if (link->type == AVMEDIA_TYPE_VIDEO) {
+                    fprintf(outfile, " [ label= \"fmt:%s w:%d h:%d tb:%d/%d\" ]",
+                            av_pix_fmt_descriptors[link->format].name,
+                            link->w, link->h, link->time_base.num, link->time_base.den);
+                } else if (link->type == AVMEDIA_TYPE_AUDIO) {
+                    char buf[255];
+                    av_get_channel_layout_string(buf, sizeof(buf), -1, link->channel_layout);
+                    fprintf(outfile, " [ label= \"fmt:%s sr:%"PRId64" cl:%s\" ]",
+                            av_get_sample_fmt_name(link->format),
+                            link->sample_rate, buf);
+                }
+                fprintf(outfile, ";\n");
             }
         }
     }
@@ -151,9 +162,7 @@ int main(int argc, char **argv)
         return 1;
     }
 
-    if (avfilter_graph_check_validity(graph, NULL) ||
-        avfilter_graph_config_formats(graph, NULL) ||
-        avfilter_graph_config_links  (graph, NULL))
+    if (avfilter_graph_config(graph, NULL) < 0)
         return 1;
 
     print_digraph(outfile, graph);
diff --git a/tools/jauche_sortierer.sh b/tools/jauche_sortierer.sh
new file mode 100755
index 0000000..1f84f1a
--- /dev/null
+++ b/tools/jauche_sortierer.sh
@@ -0,0 +1,21 @@
+#!/bin/sh
+#GPL
+#TODO
+#add pixelformat/sampleformat into the path of the codecs
+
+FFP=../ffprobe
+TMP=$(mktemp) || exit 1
+TARGET=$1
+shift
+
+for v do
+    BASE=$(basename $v)
+    echo $v | egrep -i '(public|private)' >/dev/null && echo Warning $v may be private
+    $FFP $v 2> $TMP
+    FORM=$((grep 'Input #0, ' -m1 $TMP || echo 'Input #0, unknown') | sed 's/Input #0, \([a-zA-Z0-9_]*\).*/\1/' )
+    mkdir -p $TARGET/container/$FORM
+    ln -s $v $TARGET/container/$FORM/$BASE
+    eval $(grep 'Stream #0\.[^:]*: [a-zA-Z0-9][^:]*: [a-zA-Z0-9]' $TMP | sed 's#[^:]*: \([a-zA-Z0-9]*\)[^:]*: \([a-zA-Z0-9]*\).*#mkdir -p '$TARGET'/\1/\2 ; ln -s '$v' '$TARGET'/\1/\2/'$BASE' ; #')
+done
+
+rm $TMP
diff --git a/tools/lavfi-showfiltfmts.c b/tools/lavfi-showfiltfmts.c
new file mode 100644
index 0000000..30d4725
--- /dev/null
+++ b/tools/lavfi-showfiltfmts.c
@@ -0,0 +1,99 @@
+/*
+ * Copyright (c) 2009 Stefano Sabatini
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "libavformat/avformat.h"
+#include "libavutil/pixdesc.h"
+#include "libavfilter/avfilter.h"
+
+int main(int argc, char **argv)
+{
+    AVFilter *filter;
+    AVFilterContext *filter_ctx;
+    const char *filter_name;
+    const char *filter_args = NULL;
+    int i, j;
+
+    av_log_set_level(AV_LOG_DEBUG);
+
+    if (!argv[1]) {
+        fprintf(stderr, "Missing filter name as argument\n");
+        return 1;
+    }
+
+    filter_name = argv[1];
+    if (argv[2])
+        filter_args = argv[2];
+
+    avfilter_register_all();
+
+    /* get a corresponding filter and open it */
+    if (!(filter = avfilter_get_by_name(filter_name))) {
+        fprintf(stderr, "Unrecognized filter with name '%s'\n", filter_name);
+        return 1;
+    }
+
+    if (avfilter_open(&filter_ctx, filter, NULL) < 0) {
+        fprintf(stderr, "Inpossible to open filter with name '%s'\n", filter_name);
+        return 1;
+    }
+    if (avfilter_init_filter(filter_ctx, filter_args, NULL) < 0) {
+        fprintf(stderr, "Impossible to init filter '%s' with arguments '%s'\n", filter_name, filter_args);
+        return 1;
+    }
+
+    /* create a link for each of the input pads */
+    for (i = 0; i < filter_ctx->input_count; i++) {
+        AVFilterLink *link = av_mallocz(sizeof(AVFilterLink));
+        link->type = filter_ctx->filter->inputs[i].type;
+        filter_ctx->inputs[i] = link;
+    }
+    for (i = 0; i < filter_ctx->output_count; i++) {
+        AVFilterLink *link = av_mallocz(sizeof(AVFilterLink));
+        link->type = filter_ctx->filter->outputs[i].type;
+        filter_ctx->outputs[i] = link;
+    }
+
+    if (filter->query_formats)
+        filter->query_formats(filter_ctx);
+    else
+        avfilter_default_query_formats(filter_ctx);
+
+    /* print the supported formats in input */
+    for (i = 0; i < filter_ctx->input_count; i++) {
+        AVFilterFormats *fmts = filter_ctx->inputs[i]->out_formats;
+        for (j = 0; j < fmts->format_count; j++)
+            printf("INPUT[%d] %s: %s\n",
+                   i, filter_ctx->filter->inputs[i].name,
+                   av_pix_fmt_descriptors[fmts->formats[j]].name);
+    }
+
+    /* print the supported formats in output */
+    for (i = 0; i < filter_ctx->output_count; i++) {
+        AVFilterFormats *fmts = filter_ctx->outputs[i]->in_formats;
+        for (j = 0; j < fmts->format_count; j++)
+            printf("OUTPUT[%d] %s: %s\n",
+                   i, filter_ctx->filter->outputs[i].name,
+                   av_pix_fmt_descriptors[fmts->formats[j]].name);
+    }
+
+    avfilter_free(filter_ctx);
+    fflush(stdout);
+    return 0;
+}
diff --git a/tools/patcheck b/tools/patcheck
index a6923c4..e21a9f6 100755
--- a/tools/patcheck
+++ b/tools/patcheck
@@ -1,5 +1,13 @@
 #!/bin/sh
 
+# if no argument provided, write stdin to a file and re-run the script
+if [ $# = 0 ]; then
+    cat > patcheck.stdout
+    $0 patcheck.stdout
+    rm -f patcheck.stdout
+    exit
+fi
+
 TMP=patcheck.tmp
 OPT="-nH"
 #FILES=`grep '^+++' $* | sed 's/+++ //g'`
@@ -8,7 +16,7 @@ echo patCHeck 1e10.0
 echo This tool is intended to help a human check/review patches it is very far from
 echo being free of false positives and negatives, its output are just hints of what
 echo may or may not be bad. When you use it and it misses something or detects
-echo something wrong, fix it and send a patch to the ffmpeg-dev ML
+echo something wrong, fix it and send a patch to the libav-devel mailing list.
 echo License:GPL Autor: Michael Niedermayer
 
 ERE_PRITYP='(unsigned *|)(char|short|long|int|long *int|short *int|void|float|double|(u|)int(8|16|32|64)_t)'
@@ -42,6 +50,9 @@ hiegrep '/\*[-<\* ]*\*/'  'empty comment' $*
 hiegrep 'for *\( *'"$ERE_PRITYP"' '  'not gcc 2.95 compatible' $*
 hiegrep '(static|inline|const) *\1'  'duplicate word' $*
 hiegrep 'INIT_VLC_USE_STATIC' 'forbidden ancient vlc type' $*
+hiegrep '=[-+\*\&] ' 'looks like compound assignment' $*
+hiegrep2 '/\*\* *[a-zA-Z0-9].*' '\*/' 'Inconsistently formatted doxygen comment' $*
+hiegrep '; */\*\*[^<]' 'Misformatted doxygen comment' $*
 
 hiegrep2 '(int|unsigned|static|void)[a-zA-Z0-9 _]*(init|end)[a-zA-Z0-9 _]*\(.*[^;]$' '(av_cold|:\+[^a-zA-Z_])' 'These functions may need av_cold, please review the whole patch for similar functions needing av_cold' $*
 
@@ -70,6 +81,7 @@ hiegrep '(\( *[0-9] *(&&|\|\|)|(&&|\|\|) *[0-9] *\))' 'overriding condition' $*
 hiegrep '(:\+|,|;)( *|static|\*)*'"$ERE_PRITYP"' *\*( |\*)*(src|source|input|in[^a-z])' 'missing const?' $*
 hiegrep '(:\+|,|;)( *|static|\*)*'"$ERE_PRITYP"' *(src|source|input|in)([0-9A-Z_][0-9A-Za-z_]*){1,} *\[' 'missing const (test2)?' $*
 hiegrep ' *static *'"$ERE_FUNCS"'[^)]*\);' 'static prototype, maybe you should reorder your functions' $*
+hiegrep '@file: *[a-zA-Z0-9_]' 'doxy filetag with filename can in the future cause problems when forgotten during a rename' $*
 
 hiegrep2 '\.long_name *=' 'NULL_IF_CONFIG_SMAL' 'missing NULL_IF_CONFIG_SMAL' $*
 hiegrep2 '\.pix_fmts *= *\(' 'const' 'missing const for pix_fmts array' $*
@@ -83,6 +95,9 @@ hiegrep2 '\.channel_layouts *= *\(' 'const' 'missing const for channel_layouts a
 hiegrep2 "$ERE_TYPES" '(static|av_|ff_|typedef|:\+[^a-zA-Z_])' 'Non static with no ff_/av_ prefix' $*
 
 hiegrep ':\+[^}#]*else' 'missing } prior to else' $*
+hiegrep '(if|while|for)\(' 'missing whitespace between keyword and ( (feel free to ignore)' $*
+hiegrep '(else|do){'       'missing whitespace between keyword and { (feel free to ignore)' $*
+hiegrep '}(else|while)'    'missing whitespace between } and keyword (feel free to ignore)' $*
 
 #FIXME this should print the previous statement maybe
 hiegrep ':\+  *{ *$' '{ should be on the same line as the related previous statement' $*
@@ -112,7 +127,7 @@ for i in \
     ; do
     echo $i | grep '^NULL$' && continue
     egrep $i' *(\+|-|\*|/|\||&|%|)=[^=]' $* >/dev/null || echo "possibly never written:"$i >> $TMP
-    egrep '(=|\(|return).*'$i'[^=]*$'    $* >/dev/null || echo "possibly never read   :"$i >> $TMP
+    egrep '(=|\(|return).*'$i'(==|[^=])*$'    $* >/dev/null || echo "possibly never read   :"$i >> $TMP
     egrep -o $i' *((\+|-|\*|/|\||&|%|)=[^=]|\+\+|--) *(0x|)[0-9]*(;|)'   $* |\
            egrep -v $i' *= *(0x|)[0-9]{1,};'>/dev/null || echo "possibly constant     :"$i >> $TMP
 done
@@ -121,7 +136,7 @@ if test -e $TMP ; then
     cat $TMP
 fi
 
-grep '^Index:.*Changelog' $* >/dev/null || printf "\nMissing changelog entry (ignore if minor change)\n"
+grep '^+++ .*Changelog' $* >/dev/null || printf "\nMissing changelog entry (ignore if minor change)\n"
 
 cat $* | tr '\n' '@' | egrep --color=always -o '(fprintf|av_log|printf)\([^)]*\)[+ ;@]*\1'  >$TMP && printf "\nMergeable calls\n"
 cat $TMP | tr '@' '\n'
diff --git a/tools/pktdumper.c b/tools/pktdumper.c
index ee60414..3ab39ee 100644
--- a/tools/pktdumper.c
+++ b/tools/pktdumper.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2005 Francois Revol
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/tools/probetest.c b/tools/probetest.c
index d1d77b3..7f8d54e 100644
--- a/tools/probetest.c
+++ b/tools/probetest.c
@@ -1,20 +1,20 @@
 /*
  * copyright (c) 2009 Michael Niedermayer <michaelni at gmx.at>
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -30,9 +30,9 @@ static int failures = 0;
 static void probe(AVProbeData *pd, int type, int p, int size)
 {
     int i = 0;
-    AVInputFormat *fmt;
+    AVInputFormat *fmt = NULL;
 
-    for (fmt = first_iformat; fmt != NULL; fmt = fmt->next) {
+    while ((fmt = av_iformat_next(fmt))) {
         if (fmt->flags & AVFMT_NOFILE)
             continue;
         if (fmt->read_probe) {
diff --git a/tools/qt-faststart.c b/tools/qt-faststart.c
index f48ffc0..eefeafd 100644
--- a/tools/qt-faststart.c
+++ b/tools/qt-faststart.c
@@ -8,7 +8,7 @@
  * is in front of the data, thus facilitating network streaming.
  *
  * To compile this program, start from the base directory from which you
- * are building FFmpeg and type:
+ * are building Libav and type:
  *  make tools/qt-faststart
  * The qt-faststart program will be built in the tools/ directory. If you
  * do not build the program in this manner, correct results are not
@@ -27,6 +27,7 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <inttypes.h>
+#include <string.h>
 
 #ifdef __MINGW32__
 #define fseeko(x,y,z)  fseeko64(x,y,z)
@@ -75,15 +76,15 @@
 
 int main(int argc, char *argv[])
 {
-    FILE *infile;
-    FILE *outfile;
+    FILE *infile  = NULL;
+    FILE *outfile = NULL;
     unsigned char atom_bytes[ATOM_PREAMBLE_SIZE];
     uint32_t atom_type = 0;
     uint64_t atom_size = 0;
     uint64_t atom_offset = 0;
     uint64_t last_offset;
-    unsigned char *moov_atom;
-    unsigned char *ftyp_atom = 0;
+    unsigned char *moov_atom = NULL;
+    unsigned char *ftyp_atom = NULL;
     uint64_t moov_atom_size;
     uint64_t ftyp_atom_size = 0;
     uint64_t i, j;
@@ -98,10 +99,15 @@ int main(int argc, char *argv[])
         return 0;
     }
 
+    if (!strcmp(argv[1], argv[2])) {
+        fprintf(stderr, "input and output files need to be different\n");
+        return 1;
+    }
+
     infile = fopen(argv[1], "rb");
     if (!infile) {
         perror(argv[1]);
-        return 1;
+        goto error_out;
     }
 
     /* traverse through the atoms in the file to make sure that 'moov' is
@@ -121,15 +127,12 @@ int main(int argc, char *argv[])
             if (!ftyp_atom) {
                 printf ("could not allocate %"PRIu64" byte for ftyp atom\n",
                         atom_size);
-                fclose(infile);
-                return 1;
+                goto error_out;
             }
             fseeko(infile, -ATOM_PREAMBLE_SIZE, SEEK_CUR);
             if (fread(ftyp_atom, atom_size, 1, infile) != 1) {
                 perror(argv[1]);
-                free(ftyp_atom);
-                fclose(infile);
-                return 1;
+                goto error_out;
             }
             start_offset = ftello(infile);
         } else {
@@ -166,6 +169,12 @@ int main(int argc, char *argv[])
             break;
         }
         atom_offset += atom_size;
+
+        /* The atom header is 8 (or 16 bytes), if the atom size (which
+         * includes these 8 or 16 bytes) is less than that, we won't be
+         * able to continue scanning sensibly after this atom, so break. */
+        if (atom_size < 8)
+            break;
     }
 
     if (atom_type != MOOV_ATOM) {
@@ -184,30 +193,23 @@ int main(int argc, char *argv[])
     if (!moov_atom) {
         printf ("could not allocate %"PRIu64" byte for moov atom\n",
             atom_size);
-        free(ftyp_atom);
-        fclose(infile);
-        return 1;
+        goto error_out;
     }
     if (fread(moov_atom, atom_size, 1, infile) != 1) {
         perror(argv[1]);
-        free(moov_atom);
-        free(ftyp_atom);
-        fclose(infile);
-        return 1;
+        goto error_out;
     }
 
     /* this utility does not support compressed atoms yet, so disqualify
      * files with compressed QT atoms */
     if (BE_32(&moov_atom[12]) == CMOV_ATOM) {
         printf ("this utility does not support compressed moov atoms yet\n");
-        free(moov_atom);
-        free(ftyp_atom);
-        fclose(infile);
-        return 1;
+        goto error_out;
     }
 
     /* close; will be re-opened later */
     fclose(infile);
+    infile = NULL;
 
     /* crawl through the moov chunk in search of stco or co64 atoms */
     for (i = 4; i < moov_atom_size - 4; i++) {
@@ -217,9 +219,7 @@ int main(int argc, char *argv[])
             atom_size = BE_32(&moov_atom[i - 4]);
             if (i + atom_size - 4 > moov_atom_size) {
                 printf (" bad atom size\n");
-                free(moov_atom);
-                free(ftyp_atom);
-                return 1;
+                goto error_out;
             }
             offset_count = BE_32(&moov_atom[i + 8]);
             for (j = 0; j < offset_count; j++) {
@@ -236,9 +236,7 @@ int main(int argc, char *argv[])
             atom_size = BE_32(&moov_atom[i - 4]);
             if (i + atom_size - 4 > moov_atom_size) {
                 printf (" bad atom size\n");
-                free(moov_atom);
-                free(ftyp_atom);
-                return 1;
+                goto error_out;
             }
             offset_count = BE_32(&moov_atom[i + 8]);
             for (j = 0; j < offset_count; j++) {
@@ -261,9 +259,7 @@ int main(int argc, char *argv[])
     infile = fopen(argv[1], "rb");
     if (!infile) {
         perror(argv[1]);
-        free(moov_atom);
-        free(ftyp_atom);
-        return 1;
+        goto error_out;
     }
 
     if (start_offset > 0) { /* seek after ftyp atom */
@@ -274,10 +270,7 @@ int main(int argc, char *argv[])
     outfile = fopen(argv[2], "wb");
     if (!outfile) {
         perror(argv[2]);
-        fclose(outfile);
-        free(moov_atom);
-        free(ftyp_atom);
-        return 1;
+        goto error_out;
     }
 
     /* dump the same ftyp atom */
@@ -324,8 +317,10 @@ int main(int argc, char *argv[])
     return 0;
 
 error_out:
-    fclose(infile);
-    fclose(outfile);
+    if (infile)
+        fclose(infile);
+    if (outfile)
+        fclose(outfile);
     free(moov_atom);
     free(ftyp_atom);
     return 1;
diff --git a/tools/trasher.c b/tools/trasher.c
index 114eb78..e099aa3 100644
--- a/tools/trasher.c
+++ b/tools/trasher.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2007 Michael Niedermayer
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
diff --git a/version.sh b/version.sh
index 774e514..6ec2b25 100755
--- a/version.sh
+++ b/version.sh
@@ -1,37 +1,24 @@
 #!/bin/sh
 
-# check for SVN revision number
-revision=$(cd "$1" && cat snapshot_version 2> /dev/null)
-test $revision || revision=$(cd "$1" && LC_ALL=C svn info 2> /dev/null | grep "Last Changed Rev" | cut -d' ' -f4)
-test $revision || revision=$(cd "$1" && grep committed-rev .svn/entries 2>/dev/null | head -n 1 | cut -d '"' -f2)
-test $revision || revision=$(cd "$1" && sed -n -e '/^dir$/{n
-p
-q
-}' .svn/entries 2>/dev/null)
-test $revision && revision=SVN-r$revision
-
-# check for git svn revision number
-if ! test $revision; then
-    revision=$(cd "$1" && git svn find-rev HEAD 2> /dev/null)
-    test $revision && revision=git-svn-r$revision
-fi
-
 # check for git short hash
-if ! test $revision; then
-    revision=$(cd "$1" && git log -1 --pretty=format:%h 2> /dev/null)
-    test $revision && revision=git-$revision
-fi
+revision=$(cd "$1" && git describe --always 2> /dev/null)
+test "$revision" && revision=git-$revision
 
 # no revision number found
-test $revision || revision=UNKNOWN
+test "$revision" || revision=UNKNOWN
 
 # releases extract the version number from the VERSION file
 version=$(cd "$1" && cat VERSION 2> /dev/null)
-test $version || version=$revision
+test "$version" || version=$revision
 
 test -n "$3" && version=$version-$3
 
-NEW_REVISION="#define FFMPEG_VERSION \"$version\""
+if [ -z "$2" ]; then
+    echo "$version"
+    exit
+fi
+
+NEW_REVISION="#define LIBAV_VERSION \"$version\""
 OLD_REVISION=$(cat version.h 2> /dev/null)
 
 # Update version.h only on revision changes to avoid spurious rebuilds

-- 
Libav/FFmpeg packaging



More information about the pkg-multimedia-commits mailing list